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-2000, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11/**
12 \defgroup tree Tree Library
13
14 In order to store columnar datasets, ROOT provides the TTree, TChain,
15 TNtuple and TNtupleD classes.
16 The TTree class represents a columnar dataset. Any C++ type can be stored in the
17 columns. The TTree has allowed to store about **1 EB** of data coming from the LHC alone:
18 it is demonstrated to scale and it's battle tested. It has been optimized during the years
19 to reduce dataset sizes on disk and to deliver excellent runtime performance.
20 It allows to access only part of the columns of the datasets, too.
21 The TNtuple and TNtupleD classes are specialisations of the TTree class which can
22 only hold single precision and double precision floating-point numbers respectively;
23 The TChain is a collection of TTrees, which can be located also in different files.
24
25*/
26
27/** \class TTree
28\ingroup tree
29
30A TTree represents a columnar dataset. Any C++ type can be stored in its columns.
31
32A TTree, often called in jargon *tree*, consists of a list of independent columns or *branches*,
33represented by the TBranch class.
34Behind each branch, buffers are allocated automatically by ROOT.
35Such buffers are automatically written to disk or kept in memory until the size stored in the
36attribute fMaxVirtualSize is reached.
37Variables of one branch are written to the same buffer. A branch buffer is
38automatically compressed if the file compression attribute is set (default).
39Branches may be written to different files (see TBranch::SetFile).
40
41The ROOT user can decide to make one single branch and serialize one object into
42one single I/O buffer or to make several branches.
43Making several branches is particularly interesting in the data analysis phase,
44when it is desirable to have a high reading rate and not all columns are equally interesting
45
46\anchor creatingattreetoc
47## Create a TTree to store columnar data
48- [Construct a TTree](\ref creatingattree)
49- [Add a column of Fundamental Types and Arrays thereof](\ref addcolumnoffundamentaltypes)
50- [Add a column of a STL Collection instances](\ref addingacolumnofstl)
51- [Add a column holding an object](\ref addingacolumnofobjs)
52- [Add a column holding a TObjectArray](\ref addingacolumnofobjs)
53- [Fill the tree](\ref fillthetree)
54- [Add a column to an already existing Tree](\ref addcoltoexistingtree)
55- [An Example](\ref fullexample)
56
57\anchor creatingattree
58## Construct a TTree
59
60~~~ {.cpp}
61 TTree tree(name, title)
62~~~
63Creates a Tree with name and title.
64
65Various kinds of branches can be added to a tree:
66- Variables representing fundamental types, simple classes/structures or list of variables: for example for C or Fortran
67structures.
68- Any C++ object or collection, provided by the STL or ROOT.
69
70In the following, the details about the creation of different types of branches are given.
71
72\anchor addcolumnoffundamentaltypes
73## Add a column ("branch") holding fundamental types and arrays thereof
74This strategy works also for lists of variables, e.g. to describe simple structures.
75It is strongly recommended to persistify those as objects rather than lists of leaves.
76
77~~~ {.cpp}
78 auto branch = tree.Branch(branchname, address, leaflist, bufsize)
79~~~
80- address is the address of the first item of a structure
81- leaflist is the concatenation of all the variable names and types
82 separated by a colon character :
83 The variable name and the variable type are separated by a
84 slash (/). The variable type must be 1 character. (Characters
85 after the first are legal and will be appended to the visible
86 name of the leaf, but have no effect.) If no type is given, the
87 type of the variable is assumed to be the same as the previous
88 variable. If the first variable does not have a type, it is
89 assumed of type F by default. The list of currently supported
90 types is given below:
91 - `C` : a character string terminated by the 0 character
92 - `B` : an 8 bit signed integer (`Char_t`); Treated as a character when in an array.
93 - `b` : an 8 bit unsigned integer (`UChar_t`)
94 - `S` : a 16 bit signed integer (`Short_t`)
95 - `s` : a 16 bit unsigned integer (`UShort_t`)
96 - `I` : a 32 bit signed integer (`Int_t`)
97 - `i` : a 32 bit unsigned integer (`UInt_t`)
98 - `F` : a 32 bit floating point (`Float_t`)
99 - `f` : a 24 bit floating point with truncated mantissa (`Float16_t`)
100 - `D` : a 64 bit floating point (`Double_t`)
101 - `d` : a 24 bit truncated floating point (`Double32_t`)
102 - `L` : a 64 bit signed integer (`Long64_t`)
103 - `l` : a 64 bit unsigned integer (`ULong64_t`)
104 - `G` : a long signed integer, stored as 64 bit (`Long_t`)
105 - `g` : a long unsigned integer, stored as 64 bit (`ULong_t`)
106 - `O` : [the letter `o`, not a zero] a boolean (`Bool_t`)
107
108 Examples:
109 - A int: "myVar/I"
110 - A float array with fixed size: "myArrfloat[42]/F"
111 - An double array with variable size, held by the `myvar` column: "myArrdouble[myvar]/D"
112 - An Double32_t array with variable size, held by the `myvar` column , with values between 0 and 16: "myArr[myvar]/d[0,10]"
113 - The `myvar` column, which holds the variable size, **MUST** be an `Int_t` (/I).
114
115- If the address points to a single numerical variable, the leaflist is optional:
116~~~ {.cpp}
117 int value;
118 tree->Branch(branchname, &value);
119~~~
120- If the address points to more than one numerical variable, we strongly recommend
121 that the variable be sorted in decreasing order of size. Any other order will
122 result in a non-portable TTree (i.e. you will not be able to read it back on a
123 platform with a different padding strategy).
124 We recommend to persistify objects rather than composite leaflists.
125- In case of the truncated floating point types (Float16_t and Double32_t) you can
126 furthermore specify the range in the style [xmin,xmax] or [xmin,xmax,nbits] after
127 the type character. For example, for storing a variable size array `myArr` of
128 `Double32_t` with values within a range of `[0, 2*pi]` and the size of which is stored
129 in an `Int_t` (/I) branch called `myArrSize`, the syntax for the `leaflist` string would
130 be: `myArr[myArrSize]/d[0,twopi]`. Of course the number of bits could be specified,
131 the standard rules of opaque typedefs annotation are valid. For example, if only
132 18 bits were sufficient, the syntax would become: `myArr[myArrSize]/d[0,twopi,18]`
133
134\anchor addingacolumnofstl
135## Adding a column holding STL collection instances (e.g. std::vector, std::list, std::unordered_map)
136
137~~~ {.cpp}
138 auto branch = tree.Branch( branchname, STLcollection, buffsize, splitlevel);
139~~~
140STLcollection is the address of a pointer to std::vector, std::list,
141std::deque, std::set or std::multiset containing pointers to objects.
142If the splitlevel is a value bigger than 100 (TTree::kSplitCollectionOfPointers)
143then the collection will be written in split mode, e.g. if it contains objects of
144any types deriving from TTrack this function will sort the objects
145based on their type and store them in separate branches in split
146mode.
147
148~~~ {.cpp}
149 branch->SetAddress(void *address)
150~~~
151In case of dynamic structures changing with each entry for example, one must
152redefine the branch address before filling the branch again.
153This is done via the TBranch::SetAddress member function.
154
155\anchor addingacolumnofobjs
156## Add a column holding objects
157
158~~~ {.cpp}
159 MyClass object;
160 auto branch = tree.Branch(branchname, &object, bufsize, splitlevel)
161~~~
162Note: The 2nd parameter must be the address of a valid object.
163 The object must not be destroyed (i.e. be deleted) until the TTree
164 is deleted or TTree::ResetBranchAddress is called.
165
166- if splitlevel=0, the object is serialized in the branch buffer.
167- if splitlevel=1 (default), this branch will automatically be split
168 into subbranches, with one subbranch for each data member or object
169 of the object itself. In case the object member is a TClonesArray,
170 the mechanism described in case C is applied to this array.
171- if splitlevel=2 ,this branch will automatically be split
172 into subbranches, with one subbranch for each data member or object
173 of the object itself. In case the object member is a TClonesArray,
174 it is processed as a TObject*, only one branch.
175
176Another available syntax is the following:
177
178~~~ {.cpp}
179 auto branch = tree.Branch(branchname, &p_object, bufsize, splitlevel)
180 auto branch = tree.Branch(branchname, className, &p_object, bufsize, splitlevel)
181~~~
182- p_object is a pointer to an object.
183- If className is not specified, Branch uses the type of p_object to determine the
184 type of the object.
185- If className is used to specify explicitly the object type, the className must
186 be of a type related to the one pointed to by the pointer. It should be either
187 a parent or derived class.
188
189Note: The pointer whose address is passed to TTree::Branch must not
190 be destroyed (i.e. go out of scope) until the TTree is deleted or
191 TTree::ResetBranchAddress is called.
192
193Note: The pointer p_object must be initialized before calling TTree::Branch
194- Do either:
195~~~ {.cpp}
196 MyDataClass* p_object = nullptr;
197 tree.Branch(branchname, &p_object);
198~~~
199- Or:
200~~~ {.cpp}
201 auto p_object = new MyDataClass;
202 tree.Branch(branchname, &p_object);
203~~~
204Whether the pointer is set to zero or not, the ownership of the object
205is not taken over by the TTree. I.e. even though an object will be allocated
206by TTree::Branch if the pointer p_object is zero, the object will <b>not</b>
207be deleted when the TTree is deleted.
208
209\anchor addingacolumnoftclonesarray
210## Add a column holding TClonesArray instances
211
212*It is recommended to use STL containers instead of TClonesArrays*.
213
214~~~ {.cpp}
215 // clonesarray is the address of a pointer to a TClonesArray.
216 auto branch = tree.Branch(branchname,clonesarray, bufsize, splitlevel)
217~~~
218The TClonesArray is a direct access list of objects of the same class.
219For example, if the TClonesArray is an array of TTrack objects,
220this function will create one subbranch for each data member of
221the object TTrack.
222
223\anchor fillthetree
224## Fill the Tree
225
226A TTree instance is filled with the invocation of the TTree::Fill method:
227~~~ {.cpp}
228 tree.Fill()
229~~~
230Upon its invocation, a loop on all defined branches takes place that for each branch invokes
231the TBranch::Fill method.
232
233\anchor addcoltoexistingtree
234## Add a column to an already existing Tree
235
236You may want to add a branch to an existing tree. For example,
237if one variable in the tree was computed with a certain algorithm,
238you may want to try another algorithm and compare the results.
239One solution is to add a new branch, fill it, and save the tree.
240The code below adds a simple branch to an existing tree.
241Note the kOverwrite option in the Write method, it overwrites the
242existing tree. If it is not specified, two copies of the tree headers
243are saved.
244~~~ {.cpp}
245 void tree3AddBranch() {
246 TFile f("tree3.root", "update");
247
248 Float_t new_v;
249 auto t3 = f->Get<TTree>("t3");
250 auto newBranch = t3->Branch("new_v", &new_v, "new_v/F");
251
252 Long64_t nentries = t3->GetEntries(); // read the number of entries in the t3
253
254 for (Long64_t i = 0; i < nentries; i++) {
255 new_v = gRandom->Gaus(0, 1);
256 newBranch->Fill();
257 }
258
259 t3->Write("", TObject::kOverwrite); // save only the new version of the tree
260 }
261~~~
262It is not always possible to add branches to existing datasets stored in TFiles: for example,
263these files might not be writeable, just readable. In addition, modifying in place a TTree
264causes a new TTree instance to be written and the previous one to be deleted.
265For this reasons, ROOT offers the concept of friends for TTree and TChain:
266if is good practice to rely on friend trees rather than adding a branch manually.
267
268\anchor fullexample
269## An Example
270
271Begin_Macro
272../../../tutorials/tree/tree.C
273End_Macro
274
275~~~ {.cpp}
276 // A simple example with histograms and a tree
277 //
278 // This program creates :
279 // - a one dimensional histogram
280 // - a two dimensional histogram
281 // - a profile histogram
282 // - a tree
283 //
284 // These objects are filled with some random numbers and saved on a file.
285
286 #include "TFile.h"
287 #include "TH1.h"
288 #include "TH2.h"
289 #include "TProfile.h"
290 #include "TRandom.h"
291 #include "TTree.h"
292
293 //__________________________________________________________________________
294 main(int argc, char **argv)
295 {
296 // Create a new ROOT binary machine independent file.
297 // Note that this file may contain any kind of ROOT objects, histograms,trees
298 // pictures, graphics objects, detector geometries, tracks, events, etc..
299 // This file is now becoming the current directory.
300 TFile hfile("htree.root","RECREATE","Demo ROOT file with histograms & trees");
301
302 // Create some histograms and a profile histogram
303 TH1F hpx("hpx","This is the px distribution",100,-4,4);
304 TH2F hpxpy("hpxpy","py ps px",40,-4,4,40,-4,4);
305 TProfile hprof("hprof","Profile of pz versus px",100,-4,4,0,20);
306
307 // Define some simple structures
308 typedef struct {Float_t x,y,z;} POINT;
309 typedef struct {
310 Int_t ntrack,nseg,nvertex;
311 UInt_t flag;
312 Float_t temperature;
313 } EVENTN;
314 POINT point;
315 EVENTN eventn;
316
317 // Create a ROOT Tree
318 TTree tree("T","An example of ROOT tree with a few branches");
319 tree.Branch("point",&point,"x:y:z");
320 tree.Branch("eventn",&eventn,"ntrack/I:nseg:nvertex:flag/i:temperature/F");
321 tree.Branch("hpx","TH1F",&hpx,128000,0);
322
323 Float_t px,py,pz;
324
325 // Here we start a loop on 1000 events
326 for ( Int_t i=0; i<1000; i++) {
327 gRandom->Rannor(px,py);
328 pz = px*px + py*py;
329 const auto random = gRandom->::Rndm(1);
330
331 // Fill histograms
332 hpx.Fill(px);
333 hpxpy.Fill(px,py,1);
334 hprof.Fill(px,pz,1);
335
336 // Fill structures
337 point.x = 10*(random-1);
338 point.y = 5*random;
339 point.z = 20*random;
340 eventn.ntrack = Int_t(100*random);
341 eventn.nseg = Int_t(2*eventn.ntrack);
342 eventn.nvertex = 1;
343 eventn.flag = Int_t(random+0.5);
344 eventn.temperature = 20+random;
345
346 // Fill the tree. For each event, save the 2 structures and 3 objects
347 // In this simple example, the objects hpx, hprof and hpxpy are slightly
348 // different from event to event. We expect a big compression factor!
349 tree->Fill();
350 }
351 // End of the loop
352
353 tree.Print();
354
355 // Save all objects in this file
356 hfile.Write();
357
358 // Close the file. Note that this is automatically done when you leave
359 // the application upon file destruction.
360 hfile.Close();
361
362 return 0;
363}
364~~~
365*/
366
367#include <ROOT/RConfig.hxx>
368#include "TTree.h"
369
370#include "ROOT/TIOFeatures.hxx"
371#include "TArrayC.h"
372#include "TBufferFile.h"
373#include "TBaseClass.h"
374#include "TBasket.h"
375#include "TBranchClones.h"
376#include "TBranchElement.h"
377#include "TBranchObject.h"
378#include "TBranchRef.h"
379#include "TBrowser.h"
380#include "TClass.h"
381#include "TClassEdit.h"
382#include "TClonesArray.h"
383#include "TCut.h"
384#include "TDataMember.h"
385#include "TDataType.h"
386#include "TDirectory.h"
387#include "TError.h"
388#include "TEntryList.h"
389#include "TEnv.h"
390#include "TEventList.h"
391#include "TFile.h"
392#include "TFolder.h"
393#include "TFriendElement.h"
394#include "TInterpreter.h"
395#include "TLeaf.h"
396#include "TLeafB.h"
397#include "TLeafC.h"
398#include "TLeafD.h"
399#include "TLeafElement.h"
400#include "TLeafF.h"
401#include "TLeafI.h"
402#include "TLeafL.h"
403#include "TLeafObject.h"
404#include "TLeafS.h"
405#include "TList.h"
406#include "TMath.h"
407#include "TMemFile.h"
408#include "TROOT.h"
409#include "TRealData.h"
410#include "TRegexp.h"
411#include "TRefTable.h"
412#include "TStreamerElement.h"
413#include "TStreamerInfo.h"
414#include "TStyle.h"
415#include "TSystem.h"
416#include "TTreeCloner.h"
417#include "TTreeCache.h"
418#include "TTreeCacheUnzip.h"
421#include "TVirtualIndex.h"
422#include "TVirtualPerfStats.h"
423#include "TVirtualPad.h"
424#include "TBranchSTL.h"
425#include "TSchemaRuleSet.h"
426#include "TFileMergeInfo.h"
427#include "ROOT/StringConv.hxx"
428#include "TVirtualMutex.h"
429#include "strlcpy.h"
430#include "snprintf.h"
431
432#include "TBranchIMTHelper.h"
433#include "TNotifyLink.h"
434
435#include <chrono>
436#include <cstddef>
437#include <iostream>
438#include <fstream>
439#include <sstream>
440#include <string>
441#include <cstdio>
442#include <climits>
443#include <algorithm>
444#include <set>
445
446#ifdef R__USE_IMT
448#include <thread>
449#endif
451constexpr Int_t kNEntriesResort = 100;
453
454Int_t TTree::fgBranchStyle = 1; // Use new TBranch style with TBranchElement.
455Long64_t TTree::fgMaxTreeSize = 100000000000LL;
456
458
459////////////////////////////////////////////////////////////////////////////////
460////////////////////////////////////////////////////////////////////////////////
461////////////////////////////////////////////////////////////////////////////////
463static char DataTypeToChar(EDataType datatype)
464{
465 // Return the leaflist 'char' for a given datatype.
466
467 switch(datatype) {
468 case kChar_t: return 'B';
469 case kUChar_t: return 'b';
470 case kBool_t: return 'O';
471 case kShort_t: return 'S';
472 case kUShort_t: return 's';
473 case kCounter:
474 case kInt_t: return 'I';
475 case kUInt_t: return 'i';
476 case kDouble_t: return 'D';
477 case kDouble32_t: return 'd';
478 case kFloat_t: return 'F';
479 case kFloat16_t: return 'f';
480 case kLong_t: return 'G';
481 case kULong_t: return 'g';
482 case kchar: return 0; // unsupported
483 case kLong64_t: return 'L';
484 case kULong64_t: return 'l';
485
486 case kCharStar: return 'C';
487 case kBits: return 0; //unsupported
488
489 case kOther_t:
490 case kNoType_t:
491 default:
492 return 0;
493 }
494 return 0;
495}
496
497////////////////////////////////////////////////////////////////////////////////
498/// \class TTree::TFriendLock
499/// Helper class to prevent infinite recursion in the usage of TTree Friends.
500
501////////////////////////////////////////////////////////////////////////////////
502/// Record in tree that it has been used while recursively looks through the friends.
505: fTree(tree)
506{
507 // We could also add some code to acquire an actual
508 // lock to prevent multi-thread issues
509 fMethodBit = methodbit;
510 if (fTree) {
513 } else {
514 fPrevious = 0;
515 }
516}
517
518////////////////////////////////////////////////////////////////////////////////
519/// Copy constructor.
522 fTree(tfl.fTree),
523 fMethodBit(tfl.fMethodBit),
524 fPrevious(tfl.fPrevious)
525{
526}
527
528////////////////////////////////////////////////////////////////////////////////
529/// Assignment operator.
532{
533 if(this!=&tfl) {
534 fTree=tfl.fTree;
535 fMethodBit=tfl.fMethodBit;
536 fPrevious=tfl.fPrevious;
537 }
538 return *this;
539}
540
541////////////////////////////////////////////////////////////////////////////////
542/// Restore the state of tree the same as before we set the lock.
545{
546 if (fTree) {
547 if (!fPrevious) {
548 fTree->fFriendLockStatus &= ~(fMethodBit & kBitMask);
549 }
550 }
551}
552
553////////////////////////////////////////////////////////////////////////////////
554/// \class TTree::TClusterIterator
555/// Helper class to iterate over cluster of baskets.
556
557////////////////////////////////////////////////////////////////////////////////
558/// Regular constructor.
559/// TTree is not set as const, since we might modify if it is a TChain.
561TTree::TClusterIterator::TClusterIterator(TTree *tree, Long64_t firstEntry) : fTree(tree), fClusterRange(0), fStartEntry(0), fNextEntry(0), fEstimatedSize(-1)
562{
563 if (fTree->fNClusterRange) {
564 // Find the correct cluster range.
565 //
566 // Since fClusterRangeEnd contains the inclusive upper end of the range, we need to search for the
567 // range that was containing the previous entry and add 1 (because BinarySearch consider the values
568 // to be the inclusive start of the bucket).
570
571 Long64_t entryInRange;
572 Long64_t pedestal;
573 if (fClusterRange == 0) {
574 pedestal = 0;
575 entryInRange = firstEntry;
576 } else {
577 pedestal = fTree->fClusterRangeEnd[fClusterRange-1] + 1;
578 entryInRange = firstEntry - pedestal;
579 }
580 Long64_t autoflush;
582 autoflush = fTree->fAutoFlush;
583 } else {
584 autoflush = fTree->fClusterSize[fClusterRange];
585 }
586 if (autoflush <= 0) {
587 autoflush = GetEstimatedClusterSize();
588 }
589 fStartEntry = pedestal + entryInRange - entryInRange%autoflush;
590 } else if ( fTree->GetAutoFlush() <= 0 ) {
591 // Case of old files before November 9 2009 *or* small tree where AutoFlush was never set.
592 fStartEntry = firstEntry;
593 } else {
594 fStartEntry = firstEntry - firstEntry%fTree->GetAutoFlush();
595 }
596 fNextEntry = fStartEntry; // Position correctly for the first call to Next()
597}
598
599////////////////////////////////////////////////////////////////////////////////
600/// Estimate the cluster size.
601///
602/// In almost all cases, this quickly returns the size of the auto-flush
603/// in the TTree.
604///
605/// However, in the case where the cluster size was not fixed (old files and
606/// case where autoflush was explicitly set to zero), we need estimate
607/// a cluster size in relation to the size of the cache.
608///
609/// After this value is calculated once for the TClusterIterator, it is
610/// cached and reused in future calls.
613{
614 auto autoFlush = fTree->GetAutoFlush();
615 if (autoFlush > 0) return autoFlush;
616 if (fEstimatedSize > 0) return fEstimatedSize;
617
618 Long64_t zipBytes = fTree->GetZipBytes();
619 if (zipBytes == 0) {
620 fEstimatedSize = fTree->GetEntries() - 1;
621 if (fEstimatedSize <= 0)
622 fEstimatedSize = 1;
623 } else {
624 Long64_t clusterEstimate = 1;
625 Long64_t cacheSize = fTree->GetCacheSize();
626 if (cacheSize == 0) {
627 // Humm ... let's double check on the file.
628 TFile *file = fTree->GetCurrentFile();
629 if (file) {
630 TFileCacheRead *cache = fTree->GetReadCache(file);
631 if (cache) {
632 cacheSize = cache->GetBufferSize();
633 }
634 }
635 }
636 // If neither file nor tree has a cache, use the current default.
637 if (cacheSize <= 0) {
638 cacheSize = 30000000;
639 }
640 clusterEstimate = fTree->GetEntries() * cacheSize / zipBytes;
641 // If there are no entries, then just default to 1.
642 fEstimatedSize = clusterEstimate ? clusterEstimate : 1;
643 }
644 return fEstimatedSize;
645}
646
647////////////////////////////////////////////////////////////////////////////////
648/// Move on to the next cluster and return the starting entry
649/// of this next cluster
652{
653 fStartEntry = fNextEntry;
654 if (fTree->fNClusterRange || fTree->GetAutoFlush() > 0) {
655 if (fClusterRange == fTree->fNClusterRange) {
656 // We are looking at a range which size
657 // is defined by AutoFlush itself and goes to the GetEntries.
658 fNextEntry += GetEstimatedClusterSize();
659 } else {
660 if (fStartEntry > fTree->fClusterRangeEnd[fClusterRange]) {
661 ++fClusterRange;
662 }
663 if (fClusterRange == fTree->fNClusterRange) {
664 // We are looking at the last range which size
665 // is defined by AutoFlush itself and goes to the GetEntries.
666 fNextEntry += GetEstimatedClusterSize();
667 } else {
668 Long64_t clusterSize = fTree->fClusterSize[fClusterRange];
669 if (clusterSize == 0) {
670 clusterSize = GetEstimatedClusterSize();
671 }
672 fNextEntry += clusterSize;
673 if (fNextEntry > fTree->fClusterRangeEnd[fClusterRange]) {
674 // The last cluster of the range was a partial cluster,
675 // so the next cluster starts at the beginning of the
676 // next range.
677 fNextEntry = fTree->fClusterRangeEnd[fClusterRange] + 1;
678 }
679 }
680 }
681 } else {
682 // Case of old files before November 9 2009
683 fNextEntry = fStartEntry + GetEstimatedClusterSize();
684 }
685 if (fNextEntry > fTree->GetEntries()) {
686 fNextEntry = fTree->GetEntries();
687 }
688 return fStartEntry;
689}
690
691////////////////////////////////////////////////////////////////////////////////
692/// Move on to the previous cluster and return the starting entry
693/// of this previous cluster
696{
697 fNextEntry = fStartEntry;
698 if (fTree->fNClusterRange || fTree->GetAutoFlush() > 0) {
699 if (fClusterRange == 0 || fTree->fNClusterRange == 0) {
700 // We are looking at a range which size
701 // is defined by AutoFlush itself.
702 fStartEntry -= GetEstimatedClusterSize();
703 } else {
704 if (fNextEntry <= fTree->fClusterRangeEnd[fClusterRange]) {
705 --fClusterRange;
706 }
707 if (fClusterRange == 0) {
708 // We are looking at the first range.
709 fStartEntry = 0;
710 } else {
711 Long64_t clusterSize = fTree->fClusterSize[fClusterRange];
712 if (clusterSize == 0) {
713 clusterSize = GetEstimatedClusterSize();
714 }
715 fStartEntry -= clusterSize;
716 }
717 }
718 } else {
719 // Case of old files before November 9 2009 or trees that never auto-flushed.
720 fStartEntry = fNextEntry - GetEstimatedClusterSize();
721 }
722 if (fStartEntry < 0) {
723 fStartEntry = 0;
724 }
725 return fStartEntry;
726}
727
728////////////////////////////////////////////////////////////////////////////////
729////////////////////////////////////////////////////////////////////////////////
730////////////////////////////////////////////////////////////////////////////////
731
732////////////////////////////////////////////////////////////////////////////////
733/// Default constructor and I/O constructor.
734///
735/// Note: We do *not* insert ourself into the current directory.
736///
739: TNamed()
740, TAttLine()
741, TAttFill()
742, TAttMarker()
743, fEntries(0)
744, fTotBytes(0)
745, fZipBytes(0)
746, fSavedBytes(0)
747, fFlushedBytes(0)
748, fWeight(1)
750, fScanField(25)
751, fUpdate(0)
755, fMaxEntries(0)
756, fMaxEntryLoop(0)
758, fAutoSave( -300000000)
759, fAutoFlush(-30000000)
760, fEstimate(1000000)
762, fClusterSize(0)
763, fCacheSize(0)
764, fChainOffset(0)
765, fReadEntry(-1)
766, fTotalBuffers(0)
767, fPacketSize(100)
768, fNfill(0)
769, fDebug(0)
770, fDebugMin(0)
771, fDebugMax(9999999)
772, fMakeClass(0)
773, fFileNumber(0)
774, fNotify(0)
775, fDirectory(0)
776, fBranches()
777, fLeaves()
778, fAliases(0)
779, fEventList(0)
780, fEntryList(0)
781, fIndexValues()
782, fIndex()
783, fTreeIndex(0)
784, fFriends(0)
786, fPerfStats(0)
787, fUserInfo(0)
788, fPlayer(0)
789, fClones(0)
790, fBranchRef(0)
796, fIMTEnabled(ROOT::IsImplicitMTEnabled())
798{
799 fMaxEntries = 1000000000;
800 fMaxEntries *= 1000;
801
802 fMaxEntryLoop = 1000000000;
803 fMaxEntryLoop *= 1000;
804
806}
807
808////////////////////////////////////////////////////////////////////////////////
809/// Normal tree constructor.
810///
811/// The tree is created in the current directory.
812/// Use the various functions Branch below to add branches to this tree.
813///
814/// If the first character of title is a "/", the function assumes a folder name.
815/// In this case, it creates automatically branches following the folder hierarchy.
816/// splitlevel may be used in this case to control the split level.
818TTree::TTree(const char* name, const char* title, Int_t splitlevel /* = 99 */,
819 TDirectory* dir /* = gDirectory*/)
820: TNamed(name, title)
821, TAttLine()
822, TAttFill()
823, TAttMarker()
824, fEntries(0)
825, fTotBytes(0)
826, fZipBytes(0)
827, fSavedBytes(0)
828, fFlushedBytes(0)
829, fWeight(1)
830, fTimerInterval(0)
831, fScanField(25)
832, fUpdate(0)
833, fDefaultEntryOffsetLen(1000)
834, fNClusterRange(0)
835, fMaxClusterRange(0)
836, fMaxEntries(0)
837, fMaxEntryLoop(0)
838, fMaxVirtualSize(0)
839, fAutoSave( -300000000)
840, fAutoFlush(-30000000)
841, fEstimate(1000000)
842, fClusterRangeEnd(0)
843, fClusterSize(0)
844, fCacheSize(0)
845, fChainOffset(0)
846, fReadEntry(-1)
847, fTotalBuffers(0)
848, fPacketSize(100)
849, fNfill(0)
850, fDebug(0)
851, fDebugMin(0)
852, fDebugMax(9999999)
853, fMakeClass(0)
854, fFileNumber(0)
855, fNotify(0)
856, fDirectory(dir)
857, fBranches()
858, fLeaves()
859, fAliases(0)
860, fEventList(0)
861, fEntryList(0)
862, fIndexValues()
863, fIndex()
864, fTreeIndex(0)
865, fFriends(0)
866, fExternalFriends(0)
867, fPerfStats(0)
868, fUserInfo(0)
869, fPlayer(0)
870, fClones(0)
871, fBranchRef(0)
872, fFriendLockStatus(0)
873, fTransientBuffer(0)
874, fCacheDoAutoInit(kTRUE)
875, fCacheDoClusterPrefetch(kFALSE)
876, fCacheUserSet(kFALSE)
877, fIMTEnabled(ROOT::IsImplicitMTEnabled())
878, fNEntriesSinceSorting(0)
879{
880 // TAttLine state.
884
885 // TAttFill state.
888
889 // TAttMarkerState.
893
894 fMaxEntries = 1000000000;
895 fMaxEntries *= 1000;
896
897 fMaxEntryLoop = 1000000000;
898 fMaxEntryLoop *= 1000;
899
900 // Insert ourself into the current directory.
901 // FIXME: This is very annoying behaviour, we should
902 // be able to choose to not do this like we
903 // can with a histogram.
904 if (fDirectory) fDirectory->Append(this);
905
907
908 // If title starts with "/" and is a valid folder name, a superbranch
909 // is created.
910 // FIXME: Why?
911 if (strlen(title) > 2) {
912 if (title[0] == '/') {
913 Branch(title+1,32000,splitlevel);
914 }
915 }
916}
917
918////////////////////////////////////////////////////////////////////////////////
919/// Destructor.
922{
923 if (auto link = dynamic_cast<TNotifyLinkBase*>(fNotify)) {
924 link->Clear();
925 }
926 if (fAllocationCount && (gDebug > 0)) {
927 Info("TTree::~TTree", "For tree %s, allocation count is %u.", GetName(), fAllocationCount.load());
928#ifdef R__TRACK_BASKET_ALLOC_TIME
929 Info("TTree::~TTree", "For tree %s, allocation time is %lluus.", GetName(), fAllocationTime.load());
930#endif
931 }
932
933 if (fDirectory) {
934 // We are in a directory, which may possibly be a file.
935 if (fDirectory->GetList()) {
936 // Remove us from the directory listing.
937 fDirectory->Remove(this);
938 }
939 //delete the file cache if it points to this Tree
942 }
943
944 // Remove the TTree from any list (linked to to the list of Cleanups) to avoid the unnecessary call to
945 // this RecursiveRemove while we delete our content.
947 ResetBit(kMustCleanup); // Don't redo it.
948
949 // We don't own the leaves in fLeaves, the branches do.
950 fLeaves.Clear();
951 // I'm ready to destroy any objects allocated by
952 // SetAddress() by my branches. If I have clones,
953 // tell them to zero their pointers to this shared
954 // memory.
955 if (fClones && fClones->GetEntries()) {
956 // I have clones.
957 // I am about to delete the objects created by
958 // SetAddress() which we are sharing, so tell
959 // the clones to release their pointers to them.
960 for (TObjLink* lnk = fClones->FirstLink(); lnk; lnk = lnk->Next()) {
961 TTree* clone = (TTree*) lnk->GetObject();
962 // clone->ResetBranchAddresses();
963
964 // Reset only the branch we have set the address of.
966 }
967 }
968 // Get rid of our branches, note that this will also release
969 // any memory allocated by TBranchElement::SetAddress().
971
972 // The TBranch destructor is using fDirectory to detect whether it
973 // owns the TFile that contains its data (See TBranch::~TBranch)
974 fDirectory = nullptr;
975
976 // FIXME: We must consider what to do with the reset of these if we are a clone.
977 delete fPlayer;
978 fPlayer = 0;
979 if (fExternalFriends) {
980 using namespace ROOT::Detail;
982 fetree->Reset();
983 fExternalFriends->Clear("nodelete");
985 }
986 if (fFriends) {
987 fFriends->Delete();
988 delete fFriends;
989 fFriends = 0;
990 }
991 if (fAliases) {
992 fAliases->Delete();
993 delete fAliases;
994 fAliases = 0;
995 }
996 if (fUserInfo) {
997 fUserInfo->Delete();
998 delete fUserInfo;
999 fUserInfo = 0;
1000 }
1001 if (fClones) {
1002 // Clone trees should no longer be removed from fClones when they are deleted.
1003 {
1005 gROOT->GetListOfCleanups()->Remove(fClones);
1006 }
1007 // Note: fClones does not own its content.
1008 delete fClones;
1009 fClones = 0;
1010 }
1011 if (fEntryList) {
1013 // Delete the entry list if it is marked to be deleted and it is not also
1014 // owned by a directory. (Otherwise we would need to make sure that a
1015 // TDirectoryFile that has a TTree in it does a 'slow' TList::Delete.
1016 delete fEntryList;
1017 fEntryList=0;
1018 }
1019 }
1020 delete fTreeIndex;
1021 fTreeIndex = 0;
1022 delete fBranchRef;
1023 fBranchRef = 0;
1024 delete [] fClusterRangeEnd;
1025 fClusterRangeEnd = 0;
1026 delete [] fClusterSize;
1027 fClusterSize = 0;
1028
1029 if (fTransientBuffer) {
1030 delete fTransientBuffer;
1031 fTransientBuffer = 0;
1032 }
1033}
1034
1035////////////////////////////////////////////////////////////////////////////////
1036/// Returns the transient buffer currently used by this TTree for reading/writing baskets.
1039{
1040 if (fTransientBuffer) {
1041 if (fTransientBuffer->BufferSize() < size) {
1043 }
1044 return fTransientBuffer;
1045 }
1047 return fTransientBuffer;
1048}
1049
1050////////////////////////////////////////////////////////////////////////////////
1051/// Add branch with name bname to the Tree cache.
1052/// If bname="*" all branches are added to the cache.
1053/// if subbranches is true all the branches of the subbranches are
1054/// also put to the cache.
1055///
1056/// Returns:
1057/// - 0 branch added or already included
1058/// - -1 on error
1060Int_t TTree::AddBranchToCache(const char*bname, Bool_t subbranches)
1061{
1062 if (!GetTree()) {
1063 if (LoadTree(0)<0) {
1064 Error("AddBranchToCache","Could not load a tree");
1065 return -1;
1066 }
1067 }
1068 if (GetTree()) {
1069 if (GetTree() != this) {
1070 return GetTree()->AddBranchToCache(bname, subbranches);
1071 }
1072 } else {
1073 Error("AddBranchToCache", "No tree is available. Branch was not added to the cache");
1074 return -1;
1075 }
1076
1077 TFile *f = GetCurrentFile();
1078 if (!f) {
1079 Error("AddBranchToCache", "No file is available. Branch was not added to the cache");
1080 return -1;
1081 }
1083 if (!tc) {
1084 Error("AddBranchToCache", "No cache is available, branch not added");
1085 return -1;
1086 }
1087 return tc->AddBranch(bname,subbranches);
1088}
1089
1090////////////////////////////////////////////////////////////////////////////////
1091/// Add branch b to the Tree cache.
1092/// if subbranches is true all the branches of the subbranches are
1093/// also put to the cache.
1094///
1095/// Returns:
1096/// - 0 branch added or already included
1097/// - -1 on error
1100{
1101 if (!GetTree()) {
1102 if (LoadTree(0)<0) {
1103 Error("AddBranchToCache","Could not load a tree");
1104 return -1;
1105 }
1106 }
1107 if (GetTree()) {
1108 if (GetTree() != this) {
1109 Int_t res = GetTree()->AddBranchToCache(b, subbranches);
1110 if (res<0) {
1111 Error("AddBranchToCache", "Error adding branch");
1112 }
1113 return res;
1114 }
1115 } else {
1116 Error("AddBranchToCache", "No tree is available. Branch was not added to the cache");
1117 return -1;
1118 }
1119
1120 TFile *f = GetCurrentFile();
1121 if (!f) {
1122 Error("AddBranchToCache", "No file is available. Branch was not added to the cache");
1123 return -1;
1124 }
1126 if (!tc) {
1127 Error("AddBranchToCache", "No cache is available, branch not added");
1128 return -1;
1129 }
1130 return tc->AddBranch(b,subbranches);
1131}
1132
1133////////////////////////////////////////////////////////////////////////////////
1134/// Remove the branch with name 'bname' from the Tree cache.
1135/// If bname="*" all branches are removed from the cache.
1136/// if subbranches is true all the branches of the subbranches are
1137/// also removed from the cache.
1138///
1139/// Returns:
1140/// - 0 branch dropped or not in cache
1141/// - -1 on error
1143Int_t TTree::DropBranchFromCache(const char*bname, Bool_t subbranches)
1144{
1145 if (!GetTree()) {
1146 if (LoadTree(0)<0) {
1147 Error("DropBranchFromCache","Could not load a tree");
1148 return -1;
1149 }
1150 }
1151 if (GetTree()) {
1152 if (GetTree() != this) {
1153 return GetTree()->DropBranchFromCache(bname, subbranches);
1154 }
1155 } else {
1156 Error("DropBranchFromCache", "No tree is available. Branch was not dropped from the cache");
1157 return -1;
1158 }
1159
1160 TFile *f = GetCurrentFile();
1161 if (!f) {
1162 Error("DropBranchFromCache", "No file is available. Branch was not dropped from the cache");
1163 return -1;
1164 }
1166 if (!tc) {
1167 Error("DropBranchFromCache", "No cache is available, branch not dropped");
1168 return -1;
1169 }
1170 return tc->DropBranch(bname,subbranches);
1171}
1172
1173////////////////////////////////////////////////////////////////////////////////
1174/// Remove the branch b from the Tree cache.
1175/// if subbranches is true all the branches of the subbranches are
1176/// also removed from the cache.
1177///
1178/// Returns:
1179/// - 0 branch dropped or not in cache
1180/// - -1 on error
1183{
1184 if (!GetTree()) {
1185 if (LoadTree(0)<0) {
1186 Error("DropBranchFromCache","Could not load a tree");
1187 return -1;
1188 }
1189 }
1190 if (GetTree()) {
1191 if (GetTree() != this) {
1192 Int_t res = GetTree()->DropBranchFromCache(b, subbranches);
1193 if (res<0) {
1194 Error("DropBranchFromCache", "Error dropping branch");
1195 }
1196 return res;
1197 }
1198 } else {
1199 Error("DropBranchFromCache", "No tree is available. Branch was not dropped from the cache");
1200 return -1;
1201 }
1202
1203 TFile *f = GetCurrentFile();
1204 if (!f) {
1205 Error("DropBranchFromCache", "No file is available. Branch was not dropped from the cache");
1206 return -1;
1207 }
1209 if (!tc) {
1210 Error("DropBranchFromCache", "No cache is available, branch not dropped");
1211 return -1;
1212 }
1213 return tc->DropBranch(b,subbranches);
1214}
1215
1216////////////////////////////////////////////////////////////////////////////////
1217/// Add a cloned tree to our list of trees to be notified whenever we change
1218/// our branch addresses or when we are deleted.
1221{
1222 if (!fClones) {
1223 fClones = new TList();
1224 fClones->SetOwner(false);
1225 // So that the clones are automatically removed from the list when
1226 // they are deleted.
1227 {
1229 gROOT->GetListOfCleanups()->Add(fClones);
1230 }
1231 }
1232 if (!fClones->FindObject(clone)) {
1233 fClones->Add(clone);
1234 }
1235}
1236
1237// Check whether mainTree and friendTree can be friends w.r.t. the kEntriesReshuffled bit.
1238// In particular, if any has the bit set, then friendTree must have a TTreeIndex and the
1239// branches used for indexing must be present in mainTree.
1240// Return true if the trees can be friends, false otherwise.
1241bool CheckReshuffling(TTree &mainTree, TTree &friendTree)
1242{
1243 const auto isMainReshuffled = mainTree.TestBit(TTree::kEntriesReshuffled);
1244 const auto isFriendReshuffled = friendTree.TestBit(TTree::kEntriesReshuffled);
1245 const auto friendHasValidIndex = [&] {
1246 auto idx = friendTree.GetTreeIndex();
1247 return idx ? idx->IsValidFor(&mainTree) : kFALSE;
1248 }();
1249
1250 if ((isMainReshuffled || isFriendReshuffled) && !friendHasValidIndex) {
1251 const auto reshuffledTreeName = isMainReshuffled ? mainTree.GetName() : friendTree.GetName();
1252 const auto msg =
1253 "Tree '%s' has the kEntriesReshuffled bit set and cannot have friends nor can be added as a friend unless the "
1254 "main tree has a TTreeIndex on the friend tree '%s'. You can also unset the bit manually if you know what you "
1255 "are doing; note that you risk associating wrong TTree entries of the friend with those of the main TTree!";
1256 Error("AddFriend", msg, reshuffledTreeName, friendTree.GetName());
1257 return false;
1258 }
1259 return true;
1260}
1261
1262////////////////////////////////////////////////////////////////////////////////
1263/// Add a TFriendElement to the list of friends.
1264///
1265/// This function:
1266/// - opens a file if filename is specified
1267/// - reads a Tree with name treename from the file (current directory)
1268/// - adds the Tree to the list of friends
1269/// see other AddFriend functions
1270///
1271/// A TFriendElement TF describes a TTree object TF in a file.
1272/// When a TFriendElement TF is added to the list of friends of an
1273/// existing TTree T, any variable from TF can be referenced in a query
1274/// to T.
1275///
1276/// A tree keeps a list of friends. In the context of a tree (or a chain),
1277/// friendship means unrestricted access to the friends data. In this way
1278/// it is much like adding another branch to the tree without taking the risk
1279/// of damaging it. To add a friend to the list, you can use the TTree::AddFriend
1280/// method. The tree in the diagram below has two friends (friend_tree1 and
1281/// friend_tree2) and now has access to the variables a,b,c,i,j,k,l and m.
1282///
1283/// \image html ttree_friend1.png
1284///
1285/// The AddFriend method has two parameters, the first is the tree name and the
1286/// second is the name of the ROOT file where the friend tree is saved.
1287/// AddFriend automatically opens the friend file. If no file name is given,
1288/// the tree called ft1 is assumed to be in the same file as the original tree.
1289///
1290/// tree.AddFriend("ft1","friendfile1.root");
1291/// If the friend tree has the same name as the original tree, you can give it
1292/// an alias in the context of the friendship:
1293///
1294/// tree.AddFriend("tree1 = tree","friendfile1.root");
1295/// Once the tree has friends, we can use TTree::Draw as if the friend's
1296/// variables were in the original tree. To specify which tree to use in
1297/// the Draw method, use the syntax:
1298/// ~~~ {.cpp}
1299/// <treeName>.<branchname>.<varname>
1300/// ~~~
1301/// If the variablename is enough to uniquely identify the variable, you can
1302/// leave out the tree and/or branch name.
1303/// For example, these commands generate a 3-d scatter plot of variable "var"
1304/// in the TTree tree versus variable v1 in TTree ft1 versus variable v2 in
1305/// TTree ft2.
1306/// ~~~ {.cpp}
1307/// tree.AddFriend("ft1","friendfile1.root");
1308/// tree.AddFriend("ft2","friendfile2.root");
1309/// tree.Draw("var:ft1.v1:ft2.v2");
1310/// ~~~
1311/// \image html ttree_friend2.png
1312///
1313/// The picture illustrates the access of the tree and its friends with a
1314/// Draw command.
1315/// When AddFriend is called, the ROOT file is automatically opened and the
1316/// friend tree (ft1) is read into memory. The new friend (ft1) is added to
1317/// the list of friends of tree.
1318/// The number of entries in the friend must be equal or greater to the number
1319/// of entries of the original tree. If the friend tree has fewer entries a
1320/// warning is given and the missing entries are not included in the histogram.
1321/// To retrieve the list of friends from a tree use TTree::GetListOfFriends.
1322/// When the tree is written to file (TTree::Write), the friends list is saved
1323/// with it. And when the tree is retrieved, the trees on the friends list are
1324/// also retrieved and the friendship restored.
1325/// When a tree is deleted, the elements of the friend list are also deleted.
1326/// It is possible to declare a friend tree that has the same internal
1327/// structure (same branches and leaves) as the original tree, and compare the
1328/// same values by specifying the tree.
1329/// ~~~ {.cpp}
1330/// tree.Draw("var:ft1.var:ft2.var")
1331/// ~~~
1333TFriendElement *TTree::AddFriend(const char *treename, const char *filename)
1334{
1335 if (!fFriends) {
1336 fFriends = new TList();
1337 }
1338 TFriendElement *fe = new TFriendElement(this, treename, filename);
1339
1340 TTree *t = fe->GetTree();
1341 bool canAddFriend = true;
1342 if (t) {
1343 canAddFriend = CheckReshuffling(*this, *t);
1344 if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
1345 Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent Tree: %lld", treename,
1347 }
1348 } else {
1349 Error("AddFriend", "Cannot find tree '%s' in file '%s', friend not added", treename, filename);
1350 canAddFriend = false;
1351 }
1352
1353 if (canAddFriend)
1354 fFriends->Add(fe);
1355 return fe;
1356}
1357
1358////////////////////////////////////////////////////////////////////////////////
1359/// Add a TFriendElement to the list of friends.
1360///
1361/// The TFile is managed by the user (e.g. the user must delete the file).
1362/// For complete description see AddFriend(const char *, const char *).
1363/// This function:
1364/// - reads a Tree with name treename from the file
1365/// - adds the Tree to the list of friends
1367TFriendElement *TTree::AddFriend(const char *treename, TFile *file)
1368{
1369 if (!fFriends) {
1370 fFriends = new TList();
1371 }
1372 TFriendElement *fe = new TFriendElement(this, treename, file);
1373 R__ASSERT(fe);
1374 TTree *t = fe->GetTree();
1375 bool canAddFriend = true;
1376 if (t) {
1377 canAddFriend = CheckReshuffling(*this, *t);
1378 if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
1379 Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent tree: %lld", treename,
1380 file->GetName(), t->GetEntries(), fEntries);
1381 }
1382 } else {
1383 Error("AddFriend", "Cannot find tree '%s' in file '%s', friend not added", treename, file->GetName());
1384 canAddFriend = false;
1385 }
1386
1387 if (canAddFriend)
1388 fFriends->Add(fe);
1389 return fe;
1390}
1391
1392////////////////////////////////////////////////////////////////////////////////
1393/// Add a TFriendElement to the list of friends.
1394///
1395/// The TTree is managed by the user (e.g., the user must delete the file).
1396/// For a complete description see AddFriend(const char *, const char *).
1398TFriendElement *TTree::AddFriend(TTree *tree, const char *alias, Bool_t warn)
1399{
1400 if (!tree) {
1401 return 0;
1402 }
1403 if (!fFriends) {
1404 fFriends = new TList();
1405 }
1406 TFriendElement *fe = new TFriendElement(this, tree, alias);
1407 R__ASSERT(fe); // this assert is for historical reasons. Don't remove it unless you understand all the consequences.
1408 TTree *t = fe->GetTree();
1409 if (warn && (t->GetEntries() < fEntries)) {
1410 Warning("AddFriend", "FriendElement '%s' in file '%s' has less entries %lld than its parent tree: %lld",
1411 tree->GetName(), fe->GetFile() ? fe->GetFile()->GetName() : "(memory resident)", t->GetEntries(),
1412 fEntries);
1413 }
1414 if (CheckReshuffling(*this, *t))
1415 fFriends->Add(fe);
1416 else
1417 tree->RemoveExternalFriend(fe);
1418 return fe;
1419}
1420
1421////////////////////////////////////////////////////////////////////////////////
1422/// AutoSave tree header every fAutoSave bytes.
1423///
1424/// When large Trees are produced, it is safe to activate the AutoSave
1425/// procedure. Some branches may have buffers holding many entries.
1426/// If fAutoSave is negative, AutoSave is automatically called by
1427/// TTree::Fill when the number of bytes generated since the previous
1428/// AutoSave is greater than -fAutoSave bytes.
1429/// If fAutoSave is positive, AutoSave is automatically called by
1430/// TTree::Fill every N entries.
1431/// This function may also be invoked by the user.
1432/// Each AutoSave generates a new key on the file.
1433/// Once the key with the tree header has been written, the previous cycle
1434/// (if any) is deleted.
1435///
1436/// Note that calling TTree::AutoSave too frequently (or similarly calling
1437/// TTree::SetAutoSave with a small value) is an expensive operation.
1438/// You should make tests for your own application to find a compromise
1439/// between speed and the quantity of information you may loose in case of
1440/// a job crash.
1441///
1442/// In case your program crashes before closing the file holding this tree,
1443/// the file will be automatically recovered when you will connect the file
1444/// in UPDATE mode.
1445/// The Tree will be recovered at the status corresponding to the last AutoSave.
1446///
1447/// if option contains "SaveSelf", gDirectory->SaveSelf() is called.
1448/// This allows another process to analyze the Tree while the Tree is being filled.
1449///
1450/// if option contains "FlushBaskets", TTree::FlushBaskets is called and all
1451/// the current basket are closed-out and written to disk individually.
1452///
1453/// By default the previous header is deleted after having written the new header.
1454/// if option contains "Overwrite", the previous Tree header is deleted
1455/// before written the new header. This option is slightly faster, but
1456/// the default option is safer in case of a problem (disk quota exceeded)
1457/// when writing the new header.
1458///
1459/// The function returns the number of bytes written to the file.
1460/// if the number of bytes is null, an error has occurred while writing
1461/// the header to the file.
1462///
1463/// ## How to write a Tree in one process and view it from another process
1464///
1465/// The following two scripts illustrate how to do this.
1466/// The script treew.C is executed by process1, treer.C by process2
1467///
1468/// script treew.C:
1469/// ~~~ {.cpp}
1470/// void treew() {
1471/// TFile f("test.root","recreate");
1472/// TNtuple *ntuple = new TNtuple("ntuple","Demo","px:py:pz:random:i");
1473/// Float_t px, py, pz;
1474/// for ( Int_t i=0; i<10000000; i++) {
1475/// gRandom->Rannor(px,py);
1476/// pz = px*px + py*py;
1477/// Float_t random = gRandom->Rndm(1);
1478/// ntuple->Fill(px,py,pz,random,i);
1479/// if (i%1000 == 1) ntuple->AutoSave("SaveSelf");
1480/// }
1481/// }
1482/// ~~~
1483/// script treer.C:
1484/// ~~~ {.cpp}
1485/// void treer() {
1486/// TFile f("test.root");
1487/// TTree *ntuple = (TTree*)f.Get("ntuple");
1488/// TCanvas c1;
1489/// Int_t first = 0;
1490/// while(1) {
1491/// if (first == 0) ntuple->Draw("px>>hpx", "","",10000000,first);
1492/// else ntuple->Draw("px>>+hpx","","",10000000,first);
1493/// first = (Int_t)ntuple->GetEntries();
1494/// c1.Update();
1495/// gSystem->Sleep(1000); //sleep 1 second
1496/// ntuple->Refresh();
1497/// }
1498/// }
1499/// ~~~
1502{
1503 if (!fDirectory || fDirectory == gROOT || !fDirectory->IsWritable()) return 0;
1504 if (gDebug > 0) {
1505 Info("AutoSave", "Tree:%s after %lld bytes written\n",GetName(),GetTotBytes());
1506 }
1507 TString opt = option;
1508 opt.ToLower();
1509
1510 if (opt.Contains("flushbaskets")) {
1511 if (gDebug > 0) Info("AutoSave", "calling FlushBaskets \n");
1513 }
1514
1516
1518 Long64_t nbytes;
1519 if (opt.Contains("overwrite")) {
1520 nbytes = fDirectory->WriteTObject(this,"","overwrite");
1521 } else {
1522 nbytes = fDirectory->WriteTObject(this); //nbytes will be 0 if Write failed (disk space exceeded)
1523 if (nbytes && key && strcmp(ClassName(), key->GetClassName()) == 0) {
1524 key->Delete();
1525 delete key;
1526 }
1527 }
1528 // save StreamerInfo
1530 if (file) file->WriteStreamerInfo();
1531
1532 if (opt.Contains("saveself")) {
1534 //the following line is required in case GetUserInfo contains a user class
1535 //for which the StreamerInfo must be written. One could probably be a bit faster (Rene)
1536 if (file) file->WriteHeader();
1537 }
1538
1539 return nbytes;
1540}
1541
1542namespace {
1543 // This error message is repeated several times in the code. We write it once.
1544 const char* writeStlWithoutProxyMsg = "The class requested (%s) for the branch \"%s\""
1545 " is an instance of an stl collection and does not have a compiled CollectionProxy."
1546 " Please generate the dictionary for this collection (%s) to avoid to write corrupted data.";
1547}
1548
1549////////////////////////////////////////////////////////////////////////////////
1550/// Same as TTree::Branch() with added check that addobj matches className.
1551///
1552/// \see TTree::Branch() for other details.
1553///
1555TBranch* TTree::BranchImp(const char* branchname, const char* classname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
1556{
1557 TClass* claim = TClass::GetClass(classname);
1558 if (!ptrClass) {
1559 if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
1560 Error("Branch", writeStlWithoutProxyMsg,
1561 claim->GetName(), branchname, claim->GetName());
1562 return 0;
1563 }
1564 return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
1565 }
1566 TClass* actualClass = 0;
1567 void** addr = (void**) addobj;
1568 if (addr) {
1569 actualClass = ptrClass->GetActualClass(*addr);
1570 }
1571 if (ptrClass && claim) {
1572 if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
1573 // Note we currently do not warn in case of splicing or over-expectation).
1574 if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
1575 // The type is the same according to the C++ type_info, we must be in the case of
1576 // a template of Double32_t. This is actually a correct case.
1577 } else {
1578 Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the pointer passed (%s)",
1579 claim->GetName(), branchname, ptrClass->GetName());
1580 }
1581 } else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
1582 if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
1583 // The type is the same according to the C++ type_info, we must be in the case of
1584 // a template of Double32_t. This is actually a correct case.
1585 } else {
1586 Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
1587 actualClass->GetName(), branchname, claim->GetName());
1588 }
1589 }
1590 }
1591 if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
1592 Error("Branch", writeStlWithoutProxyMsg,
1593 claim->GetName(), branchname, claim->GetName());
1594 return 0;
1595 }
1596 return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
1597}
1598
1599////////////////////////////////////////////////////////////////////////////////
1600/// Same as TTree::Branch but automatic detection of the class name.
1601/// \see TTree::Branch for other details.
1603TBranch* TTree::BranchImp(const char* branchname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
1604{
1605 if (!ptrClass) {
1606 Error("Branch", "The pointer specified for %s is not of a class known to ROOT", branchname);
1607 return 0;
1608 }
1609 TClass* actualClass = 0;
1610 void** addr = (void**) addobj;
1611 if (addr && *addr) {
1612 actualClass = ptrClass->GetActualClass(*addr);
1613 if (!actualClass) {
1614 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",
1615 branchname, ptrClass->GetName());
1616 actualClass = ptrClass;
1617 } else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
1618 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());
1619 return 0;
1620 }
1621 } else {
1622 actualClass = ptrClass;
1623 }
1624 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1625 Error("Branch", writeStlWithoutProxyMsg,
1626 actualClass->GetName(), branchname, actualClass->GetName());
1627 return 0;
1628 }
1629 return Branch(branchname, actualClass->GetName(), (void*) addobj, bufsize, splitlevel);
1630}
1631
1632////////////////////////////////////////////////////////////////////////////////
1633/// Same as TTree::Branch but automatic detection of the class name.
1634/// \see TTree::Branch for other details.
1636TBranch* TTree::BranchImpRef(const char* branchname, const char *classname, TClass* ptrClass, void *addobj, Int_t bufsize, Int_t splitlevel)
1637{
1638 TClass* claim = TClass::GetClass(classname);
1639 if (!ptrClass) {
1640 if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
1641 Error("Branch", writeStlWithoutProxyMsg,
1642 claim->GetName(), branchname, claim->GetName());
1643 return 0;
1644 } else if (claim == 0) {
1645 Error("Branch", "The pointer specified for %s is not of a class known to ROOT and %s is not a known class", branchname, classname);
1646 return 0;
1647 }
1648 ptrClass = claim;
1649 }
1650 TClass* actualClass = 0;
1651 if (!addobj) {
1652 Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
1653 return 0;
1654 }
1655 actualClass = ptrClass->GetActualClass(addobj);
1656 if (ptrClass && claim) {
1657 if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
1658 // Note we currently do not warn in case of splicing or over-expectation).
1659 if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
1660 // The type is the same according to the C++ type_info, we must be in the case of
1661 // a template of Double32_t. This is actually a correct case.
1662 } else {
1663 Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the object passed (%s)",
1664 claim->GetName(), branchname, ptrClass->GetName());
1665 }
1666 } else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
1667 if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
1668 // The type is the same according to the C++ type_info, we must be in the case of
1669 // a template of Double32_t. This is actually a correct case.
1670 } else {
1671 Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
1672 actualClass->GetName(), branchname, claim->GetName());
1673 }
1674 }
1675 }
1676 if (!actualClass) {
1677 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",
1678 branchname, ptrClass->GetName());
1679 actualClass = ptrClass;
1680 } else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
1681 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());
1682 return 0;
1683 }
1684 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1685 Error("Branch", writeStlWithoutProxyMsg,
1686 actualClass->GetName(), branchname, actualClass->GetName());
1687 return 0;
1688 }
1689 return BronchExec(branchname, actualClass->GetName(), (void*) addobj, kFALSE, bufsize, splitlevel);
1690}
1691
1692////////////////////////////////////////////////////////////////////////////////
1693/// Same as TTree::Branch but automatic detection of the class name.
1694/// \see TTree::Branch for other details.
1696TBranch* TTree::BranchImpRef(const char* branchname, TClass* ptrClass, EDataType datatype, void* addobj, Int_t bufsize, Int_t splitlevel)
1697{
1698 if (!ptrClass) {
1699 if (datatype == kOther_t || datatype == kNoType_t) {
1700 Error("Branch", "The pointer specified for %s is not of a class or type known to ROOT", branchname);
1701 } else {
1702 TString varname; varname.Form("%s/%c",branchname,DataTypeToChar(datatype));
1703 return Branch(branchname,addobj,varname.Data(),bufsize);
1704 }
1705 return 0;
1706 }
1707 TClass* actualClass = 0;
1708 if (!addobj) {
1709 Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
1710 return 0;
1711 }
1712 actualClass = ptrClass->GetActualClass(addobj);
1713 if (!actualClass) {
1714 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",
1715 branchname, ptrClass->GetName());
1716 actualClass = ptrClass;
1717 } else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
1718 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());
1719 return 0;
1720 }
1721 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1722 Error("Branch", writeStlWithoutProxyMsg,
1723 actualClass->GetName(), branchname, actualClass->GetName());
1724 return 0;
1725 }
1726 return BronchExec(branchname, actualClass->GetName(), (void*) addobj, kFALSE, bufsize, splitlevel);
1727}
1728
1729////////////////////////////////////////////////////////////////////////////////
1730// Wrapper to turn Branch call with an std::array into the relevant leaf list
1731// call
1732TBranch *TTree::BranchImpArr(const char *branchname, EDataType datatype, std::size_t N, void *addobj, Int_t bufsize,
1733 Int_t /* splitlevel */)
1734{
1735 if (datatype == kOther_t || datatype == kNoType_t) {
1736 Error("Branch",
1737 "The inner type of the std::array passed specified for %s is not of a class or type known to ROOT",
1738 branchname);
1739 } else {
1740 TString varname;
1741 varname.Form("%s[%d]/%c", branchname, (int)N, DataTypeToChar(datatype));
1742 return Branch(branchname, addobj, varname.Data(), bufsize);
1743 }
1744 return nullptr;
1745}
1746
1747////////////////////////////////////////////////////////////////////////////////
1748/// Deprecated function. Use next function instead.
1750Int_t TTree::Branch(TList* li, Int_t bufsize /* = 32000 */ , Int_t splitlevel /* = 99 */)
1751{
1752 return Branch((TCollection*) li, bufsize, splitlevel);
1753}
1754
1755////////////////////////////////////////////////////////////////////////////////
1756/// Create one branch for each element in the collection.
1757///
1758/// Each entry in the collection becomes a top level branch if the
1759/// corresponding class is not a collection. If it is a collection, the entry
1760/// in the collection becomes in turn top level branches, etc.
1761/// The splitlevel is decreased by 1 every time a new collection is found.
1762/// For example if list is a TObjArray*
1763/// - if splitlevel = 1, one top level branch is created for each element
1764/// of the TObjArray.
1765/// - if splitlevel = 2, one top level branch is created for each array element.
1766/// if, in turn, one of the array elements is a TCollection, one top level
1767/// branch will be created for each element of this collection.
1768///
1769/// In case a collection element is a TClonesArray, the special Tree constructor
1770/// for TClonesArray is called.
1771/// The collection itself cannot be a TClonesArray.
1772///
1773/// The function returns the total number of branches created.
1774///
1775/// If name is given, all branch names will be prefixed with name_.
1776///
1777/// IMPORTANT NOTE1: This function should not be called with splitlevel < 1.
1778///
1779/// IMPORTANT NOTE2: The branches created by this function will have names
1780/// corresponding to the collection or object names. It is important
1781/// to give names to collections to avoid misleading branch names or
1782/// identical branch names. By default collections have a name equal to
1783/// the corresponding class name, e.g. the default name for a TList is "TList".
1784///
1785/// And in general, in case two or more master branches contain subbranches
1786/// with identical names, one must add a "." (dot) character at the end
1787/// of the master branch name. This will force the name of the subbranches
1788/// to be of the form `master.subbranch` instead of simply `subbranch`.
1789/// This situation happens when the top level object
1790/// has two or more members referencing the same class.
1791/// For example, if a Tree has two branches B1 and B2 corresponding
1792/// to objects of the same class MyClass, one can do:
1793/// ~~~ {.cpp}
1794/// tree.Branch("B1.","MyClass",&b1,8000,1);
1795/// tree.Branch("B2.","MyClass",&b2,8000,1);
1796/// ~~~
1797/// if MyClass has 3 members a,b,c, the two instructions above will generate
1798/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
1799///
1800/// Example:
1801/// ~~~ {.cpp}
1802/// {
1803/// TTree T("T","test list");
1804/// TList *list = new TList();
1805///
1806/// TObjArray *a1 = new TObjArray();
1807/// a1->SetName("a1");
1808/// list->Add(a1);
1809/// TH1F *ha1a = new TH1F("ha1a","ha1",100,0,1);
1810/// TH1F *ha1b = new TH1F("ha1b","ha1",100,0,1);
1811/// a1->Add(ha1a);
1812/// a1->Add(ha1b);
1813/// TObjArray *b1 = new TObjArray();
1814/// b1->SetName("b1");
1815/// list->Add(b1);
1816/// TH1F *hb1a = new TH1F("hb1a","hb1",100,0,1);
1817/// TH1F *hb1b = new TH1F("hb1b","hb1",100,0,1);
1818/// b1->Add(hb1a);
1819/// b1->Add(hb1b);
1820///
1821/// TObjArray *a2 = new TObjArray();
1822/// a2->SetName("a2");
1823/// list->Add(a2);
1824/// TH1S *ha2a = new TH1S("ha2a","ha2",100,0,1);
1825/// TH1S *ha2b = new TH1S("ha2b","ha2",100,0,1);
1826/// a2->Add(ha2a);
1827/// a2->Add(ha2b);
1828///
1829/// T.Branch(list,16000,2);
1830/// T.Print();
1831/// }
1832/// ~~~
1834Int_t TTree::Branch(TCollection* li, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */, const char* name /* = "" */)
1835{
1836
1837 if (!li) {
1838 return 0;
1839 }
1840 TObject* obj = 0;
1841 Int_t nbranches = GetListOfBranches()->GetEntries();
1842 if (li->InheritsFrom(TClonesArray::Class())) {
1843 Error("Branch", "Cannot call this constructor for a TClonesArray");
1844 return 0;
1845 }
1846 Int_t nch = strlen(name);
1847 TString branchname;
1848 TIter next(li);
1849 while ((obj = next())) {
1850 if ((splitlevel > 1) && obj->InheritsFrom(TCollection::Class()) && !obj->InheritsFrom(TClonesArray::Class())) {
1851 TCollection* col = (TCollection*) obj;
1852 if (nch) {
1853 branchname.Form("%s_%s_", name, col->GetName());
1854 } else {
1855 branchname.Form("%s_", col->GetName());
1856 }
1857 Branch(col, bufsize, splitlevel - 1, branchname);
1858 } else {
1859 if (nch && (name[nch-1] == '_')) {
1860 branchname.Form("%s%s", name, obj->GetName());
1861 } else {
1862 if (nch) {
1863 branchname.Form("%s_%s", name, obj->GetName());
1864 } else {
1865 branchname.Form("%s", obj->GetName());
1866 }
1867 }
1868 if (splitlevel > 99) {
1869 branchname += ".";
1870 }
1871 Bronch(branchname, obj->ClassName(), li->GetObjectRef(obj), bufsize, splitlevel - 1);
1872 }
1873 }
1874 return GetListOfBranches()->GetEntries() - nbranches;
1875}
1876
1877////////////////////////////////////////////////////////////////////////////////
1878/// Create one branch for each element in the folder.
1879/// Returns the total number of branches created.
1881Int_t TTree::Branch(const char* foldername, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
1882{
1883 TObject* ob = gROOT->FindObjectAny(foldername);
1884 if (!ob) {
1885 return 0;
1886 }
1887 if (ob->IsA() != TFolder::Class()) {
1888 return 0;
1889 }
1890 Int_t nbranches = GetListOfBranches()->GetEntries();
1891 TFolder* folder = (TFolder*) ob;
1892 TIter next(folder->GetListOfFolders());
1893 TObject* obj = 0;
1894 char* curname = new char[1000];
1895 char occur[20];
1896 while ((obj = next())) {
1897 snprintf(curname,1000, "%s/%s", foldername, obj->GetName());
1898 if (obj->IsA() == TFolder::Class()) {
1899 Branch(curname, bufsize, splitlevel - 1);
1900 } else {
1901 void* add = (void*) folder->GetListOfFolders()->GetObjectRef(obj);
1902 for (Int_t i = 0; i < 1000; ++i) {
1903 if (curname[i] == 0) {
1904 break;
1905 }
1906 if (curname[i] == '/') {
1907 curname[i] = '.';
1908 }
1909 }
1910 Int_t noccur = folder->Occurence(obj);
1911 if (noccur > 0) {
1912 snprintf(occur,20, "_%d", noccur);
1913 strlcat(curname, occur,1000);
1914 }
1915 TBranchElement* br = (TBranchElement*) Bronch(curname, obj->ClassName(), add, bufsize, splitlevel - 1);
1916 if (br) br->SetBranchFolder();
1917 }
1918 }
1919 delete[] curname;
1920 return GetListOfBranches()->GetEntries() - nbranches;
1921}
1922
1923////////////////////////////////////////////////////////////////////////////////
1924/// Create a new TTree Branch.
1925///
1926/// This Branch constructor is provided to support non-objects in
1927/// a Tree. The variables described in leaflist may be simple
1928/// variables or structures. // See the two following
1929/// constructors for writing objects in a Tree.
1930///
1931/// By default the branch buffers are stored in the same file as the Tree.
1932/// use TBranch::SetFile to specify a different file
1933///
1934/// * address is the address of the first item of a structure.
1935/// * leaflist is the concatenation of all the variable names and types
1936/// separated by a colon character :
1937/// The variable name and the variable type are separated by a slash (/).
1938/// The variable type may be 0,1 or 2 characters. If no type is given,
1939/// the type of the variable is assumed to be the same as the previous
1940/// variable. If the first variable does not have a type, it is assumed
1941/// of type F by default. The list of currently supported types is given below:
1942/// - `C` : a character string terminated by the 0 character
1943/// - `B` : an 8 bit signed integer (`Char_t`); Treated as a character when in an array.
1944/// - `b` : an 8 bit unsigned integer (`UChar_t`)
1945/// - `S` : a 16 bit signed integer (`Short_t`)
1946/// - `s` : a 16 bit unsigned integer (`UShort_t`)
1947/// - `I` : a 32 bit signed integer (`Int_t`)
1948/// - `i` : a 32 bit unsigned integer (`UInt_t`)
1949/// - `F` : a 32 bit floating point (`Float_t`)
1950/// - `f` : a 24 bit floating point with truncated mantissa (`Float16_t`)
1951/// - `D` : a 64 bit floating point (`Double_t`)
1952/// - `d` : a 24 bit truncated floating point (`Double32_t`)
1953/// - `L` : a 64 bit signed integer (`Long64_t`)
1954/// - `l` : a 64 bit unsigned integer (`ULong64_t`)
1955/// - `G` : a long signed integer, stored as 64 bit (`Long_t`)
1956/// - `g` : a long unsigned integer, stored as 64 bit (`ULong_t`)
1957/// - `O` : [the letter `o`, not a zero] a boolean (`Bool_t`)
1958///
1959/// Arrays of values are supported with the following syntax:
1960/// - If leaf name has the form var[nelem], where nelem is alphanumeric, then
1961/// if nelem is a leaf name, it is used as the variable size of the array,
1962/// otherwise return 0.
1963/// The leaf referred to by nelem **MUST** be an int (/I),
1964/// - If leaf name has the form var[nelem], where nelem is a non-negative integer, then
1965/// it is used as the fixed size of the array.
1966/// - If leaf name has the form of a multi-dimensional array (e.g. var[nelem][nelem2])
1967/// where nelem and nelem2 are non-negative integer) then
1968/// it is used as a 2 dimensional array of fixed size.
1969/// - In case of the truncated floating point types (Float16_t and Double32_t) you can
1970/// furthermore specify the range in the style [xmin,xmax] or [xmin,xmax,nbits] after
1971/// the type character. See `TStreamerElement::GetRange()` for further information.
1972///
1973/// Any of other form is not supported.
1974///
1975/// Note that the TTree will assume that all the item are contiguous in memory.
1976/// On some platform, this is not always true of the member of a struct or a class,
1977/// due to padding and alignment. Sorting your data member in order of decreasing
1978/// sizeof usually leads to their being contiguous in memory.
1979///
1980/// * bufsize is the buffer size in bytes for this branch
1981/// The default value is 32000 bytes and should be ok for most cases.
1982/// You can specify a larger value (e.g. 256000) if your Tree is not split
1983/// and each entry is large (Megabytes)
1984/// A small value for bufsize is optimum if you intend to access
1985/// the entries in the Tree randomly and your Tree is in split mode.
1987TBranch* TTree::Branch(const char* name, void* address, const char* leaflist, Int_t bufsize /* = 32000 */)
1988{
1989 TBranch* branch = new TBranch(this, name, address, leaflist, bufsize);
1990 if (branch->IsZombie()) {
1991 delete branch;
1992 branch = 0;
1993 return 0;
1994 }
1995 fBranches.Add(branch);
1996 return branch;
1997}
1998
1999////////////////////////////////////////////////////////////////////////////////
2000/// Create a new branch with the object of class classname at address addobj.
2001///
2002/// WARNING:
2003///
2004/// Starting with Root version 3.01, the Branch function uses the new style
2005/// branches (TBranchElement). To get the old behaviour, you can:
2006/// - call BranchOld or
2007/// - call TTree::SetBranchStyle(0)
2008///
2009/// Note that with the new style, classname does not need to derive from TObject.
2010/// It must derived from TObject if the branch style has been set to 0 (old)
2011///
2012/// Note: See the comments in TBranchElement::SetAddress() for a more
2013/// detailed discussion of the meaning of the addobj parameter in
2014/// the case of new-style branches.
2015///
2016/// Use splitlevel < 0 instead of splitlevel=0 when the class
2017/// has a custom Streamer
2018///
2019/// Note: if the split level is set to the default (99), TTree::Branch will
2020/// not issue a warning if the class can not be split.
2022TBranch* TTree::Branch(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
2023{
2024 if (fgBranchStyle == 1) {
2025 return Bronch(name, classname, addobj, bufsize, splitlevel);
2026 } else {
2027 if (splitlevel < 0) {
2028 splitlevel = 0;
2029 }
2030 return BranchOld(name, classname, addobj, bufsize, splitlevel);
2031 }
2032}
2033
2034////////////////////////////////////////////////////////////////////////////////
2035/// Create a new TTree BranchObject.
2036///
2037/// Build a TBranchObject for an object of class classname.
2038/// addobj is the address of a pointer to an object of class classname.
2039/// IMPORTANT: classname must derive from TObject.
2040/// The class dictionary must be available (ClassDef in class header).
2041///
2042/// This option requires access to the library where the corresponding class
2043/// is defined. Accessing one single data member in the object implies
2044/// reading the full object.
2045/// See the next Branch constructor for a more efficient storage
2046/// in case the entry consists of arrays of identical objects.
2047///
2048/// By default the branch buffers are stored in the same file as the Tree.
2049/// use TBranch::SetFile to specify a different file
2050///
2051/// IMPORTANT NOTE about branch names:
2052///
2053/// And in general, in case two or more master branches contain subbranches
2054/// with identical names, one must add a "." (dot) character at the end
2055/// of the master branch name. This will force the name of the subbranches
2056/// to be of the form `master.subbranch` instead of simply `subbranch`.
2057/// This situation happens when the top level object
2058/// has two or more members referencing the same class.
2059/// For example, if a Tree has two branches B1 and B2 corresponding
2060/// to objects of the same class MyClass, one can do:
2061/// ~~~ {.cpp}
2062/// tree.Branch("B1.","MyClass",&b1,8000,1);
2063/// tree.Branch("B2.","MyClass",&b2,8000,1);
2064/// ~~~
2065/// if MyClass has 3 members a,b,c, the two instructions above will generate
2066/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
2067///
2068/// bufsize is the buffer size in bytes for this branch
2069/// The default value is 32000 bytes and should be ok for most cases.
2070/// You can specify a larger value (e.g. 256000) if your Tree is not split
2071/// and each entry is large (Megabytes)
2072/// A small value for bufsize is optimum if you intend to access
2073/// the entries in the Tree randomly and your Tree is in split mode.
2075TBranch* TTree::BranchOld(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 1 */)
2076{
2077 TClass* cl = TClass::GetClass(classname);
2078 if (!cl) {
2079 Error("BranchOld", "Cannot find class: '%s'", classname);
2080 return 0;
2081 }
2082 if (!cl->IsTObject()) {
2083 if (fgBranchStyle == 0) {
2084 Fatal("BranchOld", "The requested class ('%s') does not inherit from TObject.\n"
2085 "\tfgBranchStyle is set to zero requesting by default to use BranchOld.\n"
2086 "\tIf this is intentional use Bronch instead of Branch or BranchOld.", classname);
2087 } else {
2088 Fatal("BranchOld", "The requested class ('%s') does not inherit from TObject.\n"
2089 "\tYou can not use BranchOld to store objects of this type.",classname);
2090 }
2091 return 0;
2092 }
2093 TBranch* branch = new TBranchObject(this, name, classname, addobj, bufsize, splitlevel);
2094 fBranches.Add(branch);
2095 if (!splitlevel) {
2096 return branch;
2097 }
2098 // We are going to fully split the class now.
2099 TObjArray* blist = branch->GetListOfBranches();
2100 const char* rdname = 0;
2101 const char* dname = 0;
2102 TString branchname;
2103 char** apointer = (char**) addobj;
2104 TObject* obj = (TObject*) *apointer;
2105 Bool_t delobj = kFALSE;
2106 if (!obj) {
2107 obj = (TObject*) cl->New();
2108 delobj = kTRUE;
2109 }
2110 // Build the StreamerInfo if first time for the class.
2111 BuildStreamerInfo(cl, obj);
2112 // Loop on all public data members of the class and its base classes.
2113 Int_t lenName = strlen(name);
2114 Int_t isDot = 0;
2115 if (name[lenName-1] == '.') {
2116 isDot = 1;
2117 }
2118 TBranch* branch1 = 0;
2119 TRealData* rd = 0;
2120 TRealData* rdi = 0;
2121 TIter nexti(cl->GetListOfRealData());
2122 TIter next(cl->GetListOfRealData());
2123 // Note: This loop results in a full split because the
2124 // real data list includes all data members of
2125 // data members.
2126 while ((rd = (TRealData*) next())) {
2127 if (rd->TestBit(TRealData::kTransient)) continue;
2128
2129 // Loop over all data members creating branches for each one.
2130 TDataMember* dm = rd->GetDataMember();
2131 if (!dm->IsPersistent()) {
2132 // Do not process members with an "!" as the first character in the comment field.
2133 continue;
2134 }
2135 if (rd->IsObject()) {
2136 // We skip data members of class type.
2137 // But we do build their real data, their
2138 // streamer info, and write their streamer
2139 // info to the current directory's file.
2140 // Oh yes, and we also do this for all of
2141 // their base classes.
2143 if (clm) {
2144 BuildStreamerInfo(clm, (char*) obj + rd->GetThisOffset());
2145 }
2146 continue;
2147 }
2148 rdname = rd->GetName();
2149 dname = dm->GetName();
2150 if (cl->CanIgnoreTObjectStreamer()) {
2151 // Skip the TObject base class data members.
2152 // FIXME: This prevents a user from ever
2153 // using these names themself!
2154 if (!strcmp(dname, "fBits")) {
2155 continue;
2156 }
2157 if (!strcmp(dname, "fUniqueID")) {
2158 continue;
2159 }
2160 }
2161 TDataType* dtype = dm->GetDataType();
2162 Int_t code = 0;
2163 if (dtype) {
2164 code = dm->GetDataType()->GetType();
2165 }
2166 // Encode branch name. Use real data member name
2167 branchname = rdname;
2168 if (isDot) {
2169 if (dm->IsaPointer()) {
2170 // FIXME: This is wrong! The asterisk is not usually in the front!
2171 branchname.Form("%s%s", name, &rdname[1]);
2172 } else {
2173 branchname.Form("%s%s", name, &rdname[0]);
2174 }
2175 }
2176 // FIXME: Change this to a string stream.
2177 TString leaflist;
2178 Int_t offset = rd->GetThisOffset();
2179 char* pointer = ((char*) obj) + offset;
2180 if (dm->IsaPointer()) {
2181 // We have a pointer to an object or a pointer to an array of basic types.
2182 TClass* clobj = 0;
2183 if (!dm->IsBasic()) {
2184 clobj = TClass::GetClass(dm->GetTypeName());
2185 }
2186 if (clobj && clobj->InheritsFrom(TClonesArray::Class())) {
2187 // We have a pointer to a clones array.
2188 char* cpointer = (char*) pointer;
2189 char** ppointer = (char**) cpointer;
2190 TClonesArray* li = (TClonesArray*) *ppointer;
2191 if (splitlevel != 2) {
2192 if (isDot) {
2193 branch1 = new TBranchClones(branch,branchname, pointer, bufsize);
2194 } else {
2195 // FIXME: This is wrong! The asterisk is not usually in the front!
2196 branch1 = new TBranchClones(branch,&branchname.Data()[1], pointer, bufsize);
2197 }
2198 blist->Add(branch1);
2199 } else {
2200 if (isDot) {
2201 branch1 = new TBranchObject(branch, branchname, li->ClassName(), pointer, bufsize);
2202 } else {
2203 // FIXME: This is wrong! The asterisk is not usually in the front!
2204 branch1 = new TBranchObject(branch, &branchname.Data()[1], li->ClassName(), pointer, bufsize);
2205 }
2206 blist->Add(branch1);
2207 }
2208 } else if (clobj) {
2209 // We have a pointer to an object.
2210 //
2211 // It must be a TObject object.
2212 if (!clobj->IsTObject()) {
2213 continue;
2214 }
2215 branch1 = new TBranchObject(branch, dname, clobj->GetName(), pointer, bufsize, 0);
2216 if (isDot) {
2217 branch1->SetName(branchname);
2218 } else {
2219 // FIXME: This is wrong! The asterisk is not usually in the front!
2220 // Do not use the first character (*).
2221 branch1->SetName(&branchname.Data()[1]);
2222 }
2223 blist->Add(branch1);
2224 } else {
2225 // We have a pointer to an array of basic types.
2226 //
2227 // Check the comments in the text of the code for an index specification.
2228 const char* index = dm->GetArrayIndex();
2229 if (index[0]) {
2230 // We are a pointer to a varying length array of basic types.
2231 //check that index is a valid data member name
2232 //if member is part of an object (e.g. fA and index=fN)
2233 //index must be changed from fN to fA.fN
2234 TString aindex (rd->GetName());
2235 Ssiz_t rdot = aindex.Last('.');
2236 if (rdot>=0) {
2237 aindex.Remove(rdot+1);
2238 aindex.Append(index);
2239 }
2240 nexti.Reset();
2241 while ((rdi = (TRealData*) nexti())) {
2242 if (rdi->TestBit(TRealData::kTransient)) continue;
2243
2244 if (!strcmp(rdi->GetName(), index)) {
2245 break;
2246 }
2247 if (!strcmp(rdi->GetName(), aindex)) {
2248 index = rdi->GetName();
2249 break;
2250 }
2251 }
2252
2253 char vcode = DataTypeToChar((EDataType)code);
2254 // Note that we differentiate between strings and
2255 // char array by the fact that there is NO specified
2256 // size for a string (see next if (code == 1)
2257
2258 if (vcode) {
2259 leaflist.Form("%s[%s]/%c", &rdname[0], index, vcode);
2260 } else {
2261 Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
2262 leaflist = "";
2263 }
2264 } else {
2265 // We are possibly a character string.
2266 if (code == 1) {
2267 // We are a character string.
2268 leaflist.Form("%s/%s", dname, "C");
2269 } else {
2270 // Invalid array specification.
2271 // FIXME: We need an error message here.
2272 continue;
2273 }
2274 }
2275 // There are '*' in both the branchname and leaflist, remove them.
2276 TString bname( branchname );
2277 bname.ReplaceAll("*","");
2278 leaflist.ReplaceAll("*","");
2279 // Add the branch to the tree and indicate that the address
2280 // is that of a pointer to be dereferenced before using.
2281 branch1 = new TBranch(branch, bname, *((void**) pointer), leaflist, bufsize);
2282 TLeaf* leaf = (TLeaf*) branch1->GetListOfLeaves()->At(0);
2284 leaf->SetAddress((void**) pointer);
2285 blist->Add(branch1);
2286 }
2287 } else if (dm->IsBasic()) {
2288 // We have a basic type.
2289
2290 char vcode = DataTypeToChar((EDataType)code);
2291 if (vcode) {
2292 leaflist.Form("%s/%c", rdname, vcode);
2293 } else {
2294 Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
2295 leaflist = "";
2296 }
2297 branch1 = new TBranch(branch, branchname, pointer, leaflist, bufsize);
2298 branch1->SetTitle(rdname);
2299 blist->Add(branch1);
2300 } else {
2301 // We have a class type.
2302 // Note: This cannot happen due to the rd->IsObject() test above.
2303 // FIXME: Put an error message here just in case.
2304 }
2305 if (branch1) {
2306 branch1->SetOffset(offset);
2307 } else {
2308 Warning("BranchOld", "Cannot process member: '%s'", rdname);
2309 }
2310 }
2311 if (delobj) {
2312 delete obj;
2313 obj = 0;
2314 }
2315 return branch;
2316}
2317
2318////////////////////////////////////////////////////////////////////////////////
2319/// Build the optional branch supporting the TRefTable.
2320/// This branch will keep all the information to find the branches
2321/// containing referenced objects.
2322///
2323/// At each Tree::Fill, the branch numbers containing the
2324/// referenced objects are saved to the TBranchRef basket.
2325/// When the Tree header is saved (via TTree::Write), the branch
2326/// is saved keeping the information with the pointers to the branches
2327/// having referenced objects.
2330{
2331 if (!fBranchRef) {
2332 fBranchRef = new TBranchRef(this);
2333 }
2334 return fBranchRef;
2335}
2336
2337////////////////////////////////////////////////////////////////////////////////
2338/// Create a new TTree BranchElement.
2339///
2340/// ## WARNING about this new function
2341///
2342/// This function is designed to replace the internal
2343/// implementation of the old TTree::Branch (whose implementation
2344/// has been moved to BranchOld).
2345///
2346/// NOTE: The 'Bronch' method supports only one possible calls
2347/// signature (where the object type has to be specified
2348/// explicitly and the address must be the address of a pointer).
2349/// For more flexibility use 'Branch'. Use Bronch only in (rare)
2350/// cases (likely to be legacy cases) where both the new and old
2351/// implementation of Branch needs to be used at the same time.
2352///
2353/// This function is far more powerful than the old Branch
2354/// function. It supports the full C++, including STL and has
2355/// the same behaviour in split or non-split mode. classname does
2356/// not have to derive from TObject. The function is based on
2357/// the new TStreamerInfo.
2358///
2359/// Build a TBranchElement for an object of class classname.
2360///
2361/// addr is the address of a pointer to an object of class
2362/// classname. The class dictionary must be available (ClassDef
2363/// in class header).
2364///
2365/// Note: See the comments in TBranchElement::SetAddress() for a more
2366/// detailed discussion of the meaning of the addr parameter.
2367///
2368/// This option requires access to the library where the
2369/// corresponding class is defined. Accessing one single data
2370/// member in the object implies reading the full object.
2371///
2372/// By default the branch buffers are stored in the same file as the Tree.
2373/// use TBranch::SetFile to specify a different file
2374///
2375/// IMPORTANT NOTE about branch names:
2376///
2377/// And in general, in case two or more master branches contain subbranches
2378/// with identical names, one must add a "." (dot) character at the end
2379/// of the master branch name. This will force the name of the subbranches
2380/// to be of the form `master.subbranch` instead of simply `subbranch`.
2381/// This situation happens when the top level object
2382/// has two or more members referencing the same class.
2383/// For example, if a Tree has two branches B1 and B2 corresponding
2384/// to objects of the same class MyClass, one can do:
2385/// ~~~ {.cpp}
2386/// tree.Branch("B1.","MyClass",&b1,8000,1);
2387/// tree.Branch("B2.","MyClass",&b2,8000,1);
2388/// ~~~
2389/// if MyClass has 3 members a,b,c, the two instructions above will generate
2390/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
2391///
2392/// bufsize is the buffer size in bytes for this branch
2393/// The default value is 32000 bytes and should be ok for most cases.
2394/// You can specify a larger value (e.g. 256000) if your Tree is not split
2395/// and each entry is large (Megabytes)
2396/// A small value for bufsize is optimum if you intend to access
2397/// the entries in the Tree randomly and your Tree is in split mode.
2398///
2399/// Use splitlevel < 0 instead of splitlevel=0 when the class
2400/// has a custom Streamer
2401///
2402/// Note: if the split level is set to the default (99), TTree::Branch will
2403/// not issue a warning if the class can not be split.
2405TBranch* TTree::Bronch(const char* name, const char* classname, void* addr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
2406{
2407 return BronchExec(name, classname, addr, kTRUE, bufsize, splitlevel);
2408}
2409
2410////////////////////////////////////////////////////////////////////////////////
2411/// Helper function implementing TTree::Bronch and TTree::Branch(const char *name, T &obj);
2413TBranch* TTree::BronchExec(const char* name, const char* classname, void* addr, Bool_t isptrptr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
2414{
2415 TClass* cl = TClass::GetClass(classname);
2416 if (!cl) {
2417 Error("Bronch", "Cannot find class:%s", classname);
2418 return 0;
2419 }
2420
2421 //if splitlevel <= 0 and class has a custom Streamer, we must create
2422 //a TBranchObject. We cannot assume that TClass::ReadBuffer is consistent
2423 //with the custom Streamer. The penalty is that one cannot process
2424 //this Tree without the class library containing the class.
2425
2426 char* objptr = 0;
2427 if (!isptrptr) {
2428 objptr = (char*)addr;
2429 } else if (addr) {
2430 objptr = *((char**) addr);
2431 }
2432
2433 if (cl == TClonesArray::Class()) {
2434 TClonesArray* clones = (TClonesArray*) objptr;
2435 if (!clones) {
2436 Error("Bronch", "Pointer to TClonesArray is null");
2437 return 0;
2438 }
2439 if (!clones->GetClass()) {
2440 Error("Bronch", "TClonesArray with no class defined in branch: %s", name);
2441 return 0;
2442 }
2443 if (!clones->GetClass()->HasDataMemberInfo()) {
2444 Error("Bronch", "TClonesArray with no dictionary defined in branch: %s", name);
2445 return 0;
2446 }
2447 bool hasCustomStreamer = clones->GetClass()->HasCustomStreamerMember();
2448 if (splitlevel > 0) {
2449 if (hasCustomStreamer)
2450 Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", clones->GetClass()->GetName());
2451 } else {
2452 if (hasCustomStreamer) clones->BypassStreamer(kFALSE);
2453 TBranchObject *branch = new TBranchObject(this,name,classname,addr,bufsize,0,/*compress=*/ -1,isptrptr);
2454 fBranches.Add(branch);
2455 return branch;
2456 }
2457 }
2458
2459 if (cl->GetCollectionProxy()) {
2461 //if (!collProxy) {
2462 // Error("Bronch", "%s is missing its CollectionProxy (for branch %s)", classname, name);
2463 //}
2464 TClass* inklass = collProxy->GetValueClass();
2465 if (!inklass && (collProxy->GetType() == 0)) {
2466 Error("Bronch", "%s with no class defined in branch: %s", classname, name);
2467 return 0;
2468 }
2469 if ((splitlevel > 0) && inklass && (inklass->GetCollectionProxy() == 0)) {
2471 if ((stl != ROOT::kSTLmap) && (stl != ROOT::kSTLmultimap)) {
2472 if (!inklass->HasDataMemberInfo()) {
2473 Error("Bronch", "Container with no dictionary defined in branch: %s", name);
2474 return 0;
2475 }
2476 if (inklass->HasCustomStreamerMember()) {
2477 Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", inklass->GetName());
2478 }
2479 }
2480 }
2481 //-------------------------------------------------------------------------
2482 // If the splitting switch is enabled, the split level is big enough and
2483 // the collection contains pointers we can split it
2484 //////////////////////////////////////////////////////////////////////////
2485
2486 TBranch *branch;
2487 if( splitlevel > kSplitCollectionOfPointers && collProxy->HasPointers() )
2488 branch = new TBranchSTL( this, name, collProxy, bufsize, splitlevel );
2489 else
2490 branch = new TBranchElement(this, name, collProxy, bufsize, splitlevel);
2491 fBranches.Add(branch);
2492 if (isptrptr) {
2493 branch->SetAddress(addr);
2494 } else {
2495 branch->SetObject(addr);
2496 }
2497 return branch;
2498 }
2499
2500 Bool_t hasCustomStreamer = kFALSE;
2501 if (!cl->HasDataMemberInfo() && !cl->GetCollectionProxy()) {
2502 Error("Bronch", "Cannot find dictionary for class: %s", classname);
2503 return 0;
2504 }
2505
2506 if (!cl->GetCollectionProxy() && cl->HasCustomStreamerMember()) {
2507 // Not an STL container and the linkdef file had a "-" after the class name.
2508 hasCustomStreamer = kTRUE;
2509 }
2510
2511 if (splitlevel < 0 || ((splitlevel == 0) && hasCustomStreamer && cl->IsTObject())) {
2512 TBranchObject* branch = new TBranchObject(this, name, classname, addr, bufsize, 0, /*compress=*/ ROOT::RCompressionSetting::EAlgorithm::kInherit, isptrptr);
2513 fBranches.Add(branch);
2514 return branch;
2515 }
2516
2517 if (cl == TClonesArray::Class()) {
2518 // Special case of TClonesArray.
2519 // No dummy object is created.
2520 // The streamer info is not rebuilt unoptimized.
2521 // No dummy top-level branch is created.
2522 // No splitting is attempted.
2523 TBranchElement* branch = new TBranchElement(this, name, (TClonesArray*) objptr, bufsize, splitlevel%kSplitCollectionOfPointers);
2524 fBranches.Add(branch);
2525 if (isptrptr) {
2526 branch->SetAddress(addr);
2527 } else {
2528 branch->SetObject(addr);
2529 }
2530 return branch;
2531 }
2532
2533 //
2534 // If we are not given an object to use as an i/o buffer
2535 // then create a temporary one which we will delete just
2536 // before returning.
2537 //
2538
2539 Bool_t delobj = kFALSE;
2540
2541 if (!objptr) {
2542 objptr = (char*) cl->New();
2543 delobj = kTRUE;
2544 }
2545
2546 //
2547 // Avoid splitting unsplittable classes.
2548 //
2549
2550 if ((splitlevel > 0) && !cl->CanSplit()) {
2551 if (splitlevel != 99) {
2552 Warning("Bronch", "%s cannot be split, resetting splitlevel to 0", cl->GetName());
2553 }
2554 splitlevel = 0;
2555 }
2556
2557 //
2558 // Make sure the streamer info is built and fetch it.
2559 //
2560 // If we are splitting, then make sure the streamer info
2561 // is built unoptimized (data members are not combined).
2562 //
2563
2564 TStreamerInfo* sinfo = BuildStreamerInfo(cl, objptr, splitlevel==0);
2565 if (!sinfo) {
2566 Error("Bronch", "Cannot build the StreamerInfo for class: %s", cl->GetName());
2567 return 0;
2568 }
2569
2570 //
2571 // Create a dummy top level branch object.
2572 //
2573
2574 Int_t id = -1;
2575 if (splitlevel > 0) {
2576 id = -2;
2577 }
2578 TBranchElement* branch = new TBranchElement(this, name, sinfo, id, objptr, bufsize, splitlevel);
2579 fBranches.Add(branch);
2580
2581 //
2582 // Do splitting, if requested.
2583 //
2584
2585 if (splitlevel%kSplitCollectionOfPointers > 0) {
2586 branch->Unroll(name, cl, sinfo, objptr, bufsize, splitlevel);
2587 }
2588
2589 //
2590 // Setup our offsets into the user's i/o buffer.
2591 //
2592
2593 if (isptrptr) {
2594 branch->SetAddress(addr);
2595 } else {
2596 branch->SetObject(addr);
2597 }
2598
2599 if (delobj) {
2600 cl->Destructor(objptr);
2601 objptr = 0;
2602 }
2603
2604 return branch;
2605}
2606
2607////////////////////////////////////////////////////////////////////////////////
2608/// Browse content of the TTree.
2611{
2613 if (fUserInfo) {
2614 if (strcmp("TList",fUserInfo->GetName())==0) {
2615 fUserInfo->SetName("UserInfo");
2616 b->Add(fUserInfo);
2617 fUserInfo->SetName("TList");
2618 } else {
2619 b->Add(fUserInfo);
2620 }
2621 }
2622}
2623
2624////////////////////////////////////////////////////////////////////////////////
2625/// Build a Tree Index (default is TTreeIndex).
2626/// See a description of the parameters and functionality in
2627/// TTreeIndex::TTreeIndex().
2628///
2629/// The return value is the number of entries in the Index (< 0 indicates failure).
2630///
2631/// A TTreeIndex object pointed by fTreeIndex is created.
2632/// This object will be automatically deleted by the TTree destructor.
2633/// If an index is already existing, this is replaced by the new one without being
2634/// deleted. This behaviour prevents the deletion of a previously external index
2635/// assigned to the TTree via the TTree::SetTreeIndex() method.
2636/// \see also comments in TTree::SetTreeIndex().
2638Int_t TTree::BuildIndex(const char* majorname, const char* minorname /* = "0" */)
2639{
2640 fTreeIndex = GetPlayer()->BuildIndex(this, majorname, minorname);
2641 if (fTreeIndex->IsZombie()) {
2642 delete fTreeIndex;
2643 fTreeIndex = 0;
2644 return 0;
2645 }
2646 return fTreeIndex->GetN();
2647}
2648
2649////////////////////////////////////////////////////////////////////////////////
2650/// Build StreamerInfo for class cl.
2651/// pointer is an optional argument that may contain a pointer to an object of cl.
2653TStreamerInfo* TTree::BuildStreamerInfo(TClass* cl, void* pointer /* = 0 */, Bool_t canOptimize /* = kTRUE */ )
2654{
2655 if (!cl) {
2656 return 0;
2657 }
2658 cl->BuildRealData(pointer);
2660
2661 // Create StreamerInfo for all base classes.
2662 TBaseClass* base = 0;
2663 TIter nextb(cl->GetListOfBases());
2664 while((base = (TBaseClass*) nextb())) {
2665 if (base->IsSTLContainer()) {
2666 continue;
2667 }
2668 TClass* clm = TClass::GetClass(base->GetName());
2669 BuildStreamerInfo(clm, pointer, canOptimize);
2670 }
2671 if (sinfo && fDirectory) {
2673 }
2674 return sinfo;
2675}
2676
2677////////////////////////////////////////////////////////////////////////////////
2678/// Enable the TTreeCache unless explicitly disabled for this TTree by
2679/// a prior call to `SetCacheSize(0)`.
2680/// If the environment variable `ROOT_TTREECACHE_SIZE` or the rootrc config
2681/// `TTreeCache.Size` has been set to zero, this call will over-ride them with
2682/// a value of 1.0 (i.e. use a cache size to hold 1 cluster)
2683///
2684/// Return true if there is a cache attached to the `TTree` (either pre-exisiting
2685/// or created as part of this call)
2687{
2689 if (!file)
2690 return kFALSE;
2691 // Check for an existing cache
2693 if (pf)
2694 return kTRUE;
2695 if (fCacheUserSet && fCacheSize == 0)
2696 return kFALSE;
2697 return (0 == SetCacheSizeAux(kTRUE, -1));
2698}
2699
2700////////////////////////////////////////////////////////////////////////////////
2701/// Called by TTree::Fill() when file has reached its maximum fgMaxTreeSize.
2702/// Create a new file. If the original file is named "myfile.root",
2703/// subsequent files are named "myfile_1.root", "myfile_2.root", etc.
2704///
2705/// Returns a pointer to the new file.
2706///
2707/// Currently, the automatic change of file is restricted
2708/// to the case where the tree is in the top level directory.
2709/// The file should not contain sub-directories.
2710///
2711/// Before switching to a new file, the tree header is written
2712/// to the current file, then the current file is closed.
2713///
2714/// To process the multiple files created by ChangeFile, one must use
2715/// a TChain.
2716///
2717/// The new file name has a suffix "_N" where N is equal to fFileNumber+1.
2718/// By default a Root session starts with fFileNumber=0. One can set
2719/// fFileNumber to a different value via TTree::SetFileNumber.
2720/// In case a file named "_N" already exists, the function will try
2721/// a file named "__N", then "___N", etc.
2722///
2723/// fgMaxTreeSize can be set via the static function TTree::SetMaxTreeSize.
2724/// The default value of fgMaxTreeSize is 100 Gigabytes.
2725///
2726/// If the current file contains other objects like TH1 and TTree,
2727/// these objects are automatically moved to the new file.
2728///
2729/// \warning Be careful when writing the final Tree header to the file!
2730/// Don't do:
2731/// ~~~ {.cpp}
2732/// TFile *file = new TFile("myfile.root","recreate");
2733/// TTree *T = new TTree("T","title");
2734/// T->Fill(); // Loop
2735/// file->Write();
2736/// file->Close();
2737/// ~~~
2738/// \warning but do the following:
2739/// ~~~ {.cpp}
2740/// TFile *file = new TFile("myfile.root","recreate");
2741/// TTree *T = new TTree("T","title");
2742/// T->Fill(); // Loop
2743/// file = T->GetCurrentFile(); // To get the pointer to the current file
2744/// file->Write();
2745/// file->Close();
2746/// ~~~
2747///
2748/// \note This method is never called if the input file is a `TMemFile` or derivate.
2751{
2752 file->cd();
2753 Write();
2754 Reset();
2755 constexpr auto kBufSize = 2000;
2756 char* fname = new char[kBufSize];
2757 ++fFileNumber;
2758 char uscore[10];
2759 for (Int_t i = 0; i < 10; ++i) {
2760 uscore[i] = 0;
2761 }
2762 Int_t nus = 0;
2763 // Try to find a suitable file name that does not already exist.
2764 while (nus < 10) {
2765 uscore[nus] = '_';
2766 fname[0] = 0;
2767 strlcpy(fname, file->GetName(), kBufSize);
2768
2769 if (fFileNumber > 1) {
2770 char* cunder = strrchr(fname, '_');
2771 if (cunder) {
2772 snprintf(cunder, kBufSize - Int_t(cunder - fname), "%s%d", uscore, fFileNumber);
2773 const char* cdot = strrchr(file->GetName(), '.');
2774 if (cdot) {
2775 strlcat(fname, cdot, kBufSize);
2776 }
2777 } else {
2778 char fcount[21];
2779 snprintf(fcount,21, "%s%d", uscore, fFileNumber);
2780 strlcat(fname, fcount, kBufSize);
2781 }
2782 } else {
2783 char* cdot = strrchr(fname, '.');
2784 if (cdot) {
2785 snprintf(cdot, kBufSize - Int_t(fname-cdot), "%s%d", uscore, fFileNumber);
2786 strlcat(fname, strrchr(file->GetName(), '.'), kBufSize);
2787 } else {
2788 char fcount[21];
2789 snprintf(fcount,21, "%s%d", uscore, fFileNumber);
2790 strlcat(fname, fcount, kBufSize);
2791 }
2792 }
2793 if (gSystem->AccessPathName(fname)) {
2794 break;
2795 }
2796 ++nus;
2797 Warning("ChangeFile", "file %s already exist, trying with %d underscores", fname, nus+1);
2798 }
2799 Int_t compress = file->GetCompressionSettings();
2800 TFile* newfile = TFile::Open(fname, "recreate", "chain files", compress);
2801 if (newfile == 0) {
2802 Error("Fill","Failed to open new file %s, continuing as a memory tree.",fname);
2803 } else {
2804 Printf("Fill: Switching to new file: %s", fname);
2805 }
2806 // The current directory may contain histograms and trees.
2807 // These objects must be moved to the new file.
2808 TBranch* branch = 0;
2809 TObject* obj = 0;
2810 while ((obj = file->GetList()->First())) {
2811 file->Remove(obj);
2812 // Histogram: just change the directory.
2813 if (obj->InheritsFrom("TH1")) {
2814 gROOT->ProcessLine(TString::Format("((%s*)0x%zx)->SetDirectory((TDirectory*)0x%zx);", obj->ClassName(), (size_t) obj, (size_t) newfile));
2815 continue;
2816 }
2817 // Tree: must save all trees in the old file, reset them.
2818 if (obj->InheritsFrom(TTree::Class())) {
2819 TTree* t = (TTree*) obj;
2820 if (t != this) {
2821 t->AutoSave();
2822 t->Reset();
2824 }
2825 t->SetDirectory(newfile);
2826 TIter nextb(t->GetListOfBranches());
2827 while ((branch = (TBranch*)nextb())) {
2828 branch->SetFile(newfile);
2829 }
2830 if (t->GetBranchRef()) {
2831 t->GetBranchRef()->SetFile(newfile);
2832 }
2833 continue;
2834 }
2835 // Not a TH1 or a TTree, move object to new file.
2836 if (newfile) newfile->Append(obj);
2837 file->Remove(obj);
2838 }
2839 file->TObject::Delete();
2840 file = 0;
2841 delete[] fname;
2842 fname = 0;
2843 return newfile;
2844}
2845
2846////////////////////////////////////////////////////////////////////////////////
2847/// Check whether or not the address described by the last 3 parameters
2848/// matches the content of the branch. If a Data Model Evolution conversion
2849/// is involved, reset the fInfo of the branch.
2850/// The return values are:
2851//
2852/// - kMissingBranch (-5) : Missing branch
2853/// - kInternalError (-4) : Internal error (could not find the type corresponding to a data type number)
2854/// - kMissingCompiledCollectionProxy (-3) : Missing compiled collection proxy for a compiled collection
2855/// - kMismatch (-2) : Non-Class Pointer type given does not match the type expected by the branch
2856/// - kClassMismatch (-1) : Class Pointer type given does not match the type expected by the branch
2857/// - kMatch (0) : perfect match
2858/// - kMatchConversion (1) : match with (I/O) conversion
2859/// - kMatchConversionCollection (2) : match with (I/O) conversion of the content of a collection
2860/// - kMakeClass (3) : MakeClass mode so we can not check.
2861/// - kVoidPtr (4) : void* passed so no check was made.
2862/// - kNoCheck (5) : Underlying TBranch not yet available so no check was made.
2863/// In addition this can be multiplexed with the two bits:
2864/// - kNeedEnableDecomposedObj : in order for the address (type) to be 'usable' the branch needs to be in Decomposed Object (aka MakeClass) mode.
2865/// - kNeedDisableDecomposedObj : in order for the address (type) to be 'usable' the branch needs to not be in Decomposed Object (aka MakeClass) mode.
2866/// This bits can be masked out by using kDecomposedObjMask
2868Int_t TTree::CheckBranchAddressType(TBranch* branch, TClass* ptrClass, EDataType datatype, Bool_t isptr)
2869{
2870 if (GetMakeClass()) {
2871 // If we are in MakeClass mode so we do not really use classes.
2872 return kMakeClass;
2873 }
2874
2875 // Let's determine what we need!
2876 TClass* expectedClass = 0;
2877 EDataType expectedType = kOther_t;
2878 if (0 != branch->GetExpectedType(expectedClass,expectedType) ) {
2879 // Something went wrong, the warning message has already been issued.
2880 return kInternalError;
2881 }
2882 bool isBranchElement = branch->InheritsFrom( TBranchElement::Class() );
2883 if (expectedClass && datatype == kOther_t && ptrClass == 0) {
2884 if (isBranchElement) {
2885 TBranchElement* bEl = (TBranchElement*)branch;
2886 bEl->SetTargetClass( expectedClass->GetName() );
2887 }
2888 if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
2889 Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
2890 "The class expected (%s) refers to an stl collection and do not have a compiled CollectionProxy. "
2891 "Please generate the dictionary for this class (%s)",
2892 branch->GetName(), expectedClass->GetName(), expectedClass->GetName());
2894 }
2895 if (!expectedClass->IsLoaded()) {
2896 // The originally expected class does not have a dictionary, it is then plausible that the pointer being passed is the right type
2897 // (we really don't know). So let's express that.
2898 Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
2899 "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."
2900 "Please generate the dictionary for this class (%s)",
2901 branch->GetName(), expectedClass->GetName(), expectedClass->GetName());
2902 } else {
2903 Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
2904 "This is probably due to a missing dictionary, the original data class for this branch is %s.", branch->GetName(), expectedClass->GetName());
2905 }
2906 return kClassMismatch;
2907 }
2908 if (expectedClass && ptrClass && (branch->GetMother() == branch)) {
2909 // Top Level branch
2910 if (!isptr) {
2911 Error("SetBranchAddress", "The address for \"%s\" should be the address of a pointer!", branch->GetName());
2912 }
2913 }
2914 if (expectedType == kFloat16_t) {
2915 expectedType = kFloat_t;
2916 }
2917 if (expectedType == kDouble32_t) {
2918 expectedType = kDouble_t;
2919 }
2920 if (datatype == kFloat16_t) {
2921 datatype = kFloat_t;
2922 }
2923 if (datatype == kDouble32_t) {
2924 datatype = kDouble_t;
2925 }
2926
2927 /////////////////////////////////////////////////////////////////////////////
2928 // Deal with the class renaming
2929 /////////////////////////////////////////////////////////////////////////////
2930
2931 if( expectedClass && ptrClass &&
2932 expectedClass != ptrClass &&
2933 isBranchElement &&
2934 ptrClass->GetSchemaRules() &&
2935 ptrClass->GetSchemaRules()->HasRuleWithSourceClass( expectedClass->GetName() ) ) {
2936 TBranchElement* bEl = (TBranchElement*)branch;
2937
2938 if ( ptrClass->GetCollectionProxy() && expectedClass->GetCollectionProxy() ) {
2939 if (gDebug > 7)
2940 Info("SetBranchAddress", "Matching STL collection (at least according to the SchemaRuleSet when "
2941 "reading a %s into a %s",expectedClass->GetName(),ptrClass->GetName());
2942
2943 bEl->SetTargetClass( ptrClass->GetName() );
2944 return kMatchConversion;
2945
2946 } else if ( !ptrClass->GetConversionStreamerInfo( expectedClass, bEl->GetClassVersion() ) &&
2947 !ptrClass->FindConversionStreamerInfo( expectedClass, bEl->GetCheckSum() ) ) {
2948 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());
2949
2950 bEl->SetTargetClass( expectedClass->GetName() );
2951 return kClassMismatch;
2952 }
2953 else {
2954
2955 bEl->SetTargetClass( ptrClass->GetName() );
2956 return kMatchConversion;
2957 }
2958
2959 } else if (expectedClass && ptrClass && !expectedClass->InheritsFrom(ptrClass)) {
2960
2961 if (expectedClass->GetCollectionProxy() && ptrClass->GetCollectionProxy() &&
2962 isBranchElement &&
2963 expectedClass->GetCollectionProxy()->GetValueClass() &&
2964 ptrClass->GetCollectionProxy()->GetValueClass() )
2965 {
2966 // In case of collection, we know how to convert them, if we know how to convert their content.
2967 // NOTE: we need to extend this to std::pair ...
2968
2969 TClass *onfileValueClass = expectedClass->GetCollectionProxy()->GetValueClass();
2970 TClass *inmemValueClass = ptrClass->GetCollectionProxy()->GetValueClass();
2971
2972 if (inmemValueClass->GetSchemaRules() &&
2973 inmemValueClass->GetSchemaRules()->HasRuleWithSourceClass(onfileValueClass->GetName() ) )
2974 {
2975 TBranchElement* bEl = (TBranchElement*)branch;
2976 bEl->SetTargetClass( ptrClass->GetName() );
2978 }
2979 }
2980
2981 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());
2982 if (isBranchElement) {
2983 TBranchElement* bEl = (TBranchElement*)branch;
2984 bEl->SetTargetClass( expectedClass->GetName() );
2985 }
2986 return kClassMismatch;
2987
2988 } else if ((expectedType != kOther_t) && (datatype != kOther_t) && (expectedType != kNoType_t) && (datatype != kNoType_t) && (expectedType != datatype)) {
2989 if (datatype != kChar_t) {
2990 // For backward compatibility we assume that (char*) was just a cast and/or a generic address
2991 Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" (%d) by the branch: %s",
2992 TDataType::GetTypeName(datatype), datatype, TDataType::GetTypeName(expectedType), expectedType, branch->GetName());
2993 return kMismatch;
2994 }
2995 } else if ((expectedClass && (datatype != kOther_t && datatype != kNoType_t && datatype != kInt_t)) ||
2996 (ptrClass && (expectedType != kOther_t && expectedType != kNoType_t && datatype != kInt_t)) ) {
2997 // Sometime a null pointer can look an int, avoid complaining in that case.
2998 if (expectedClass) {
2999 Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" by the branch: %s",
3000 TDataType::GetTypeName(datatype), datatype, expectedClass->GetName(), branch->GetName());
3001 if (isBranchElement) {
3002 TBranchElement* bEl = (TBranchElement*)branch;
3003 bEl->SetTargetClass( expectedClass->GetName() );
3004 }
3005 } else {
3006 // 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
3007 // a struct).
3008 bool found = false;
3009 if (ptrClass->IsLoaded()) {
3010 TIter next(ptrClass->GetListOfRealData());
3011 TRealData *rdm;
3012 while ((rdm = (TRealData*)next())) {
3013 if (rdm->GetThisOffset() == 0) {
3014 TDataType *dmtype = rdm->GetDataMember()->GetDataType();
3015 if (dmtype) {
3016 EDataType etype = (EDataType)dmtype->GetType();
3017 if (etype == expectedType) {
3018 found = true;
3019 }
3020 }
3021 break;
3022 }
3023 }
3024 } else {
3025 TIter next(ptrClass->GetListOfDataMembers());
3026 TDataMember *dm;
3027 while ((dm = (TDataMember*)next())) {
3028 if (dm->GetOffset() == 0) {
3029 TDataType *dmtype = dm->GetDataType();
3030 if (dmtype) {
3031 EDataType etype = (EDataType)dmtype->GetType();
3032 if (etype == expectedType) {
3033 found = true;
3034 }
3035 }
3036 break;
3037 }
3038 }
3039 }
3040 if (found) {
3041 // let's check the size.
3042 TLeaf *last = (TLeaf*)branch->GetListOfLeaves()->Last();
3043 long len = last->GetOffset() + last->GetLenType() * last->GetLen();
3044 if (len <= ptrClass->Size()) {
3045 return kMatch;
3046 }
3047 }
3048 Error("SetBranchAddress", "The pointer type given \"%s\" does not correspond to the type needed \"%s\" (%d) by the branch: %s",
3049 ptrClass->GetName(), TDataType::GetTypeName(expectedType), expectedType, branch->GetName());
3050 }
3051 return kMismatch;
3052 }
3053 if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
3054 Error("SetBranchAddress", writeStlWithoutProxyMsg,
3055 expectedClass->GetName(), branch->GetName(), expectedClass->GetName());
3056 if (isBranchElement) {
3057 TBranchElement* bEl = (TBranchElement*)branch;
3058 bEl->SetTargetClass( expectedClass->GetName() );
3059 }
3061 }
3062 if (isBranchElement) {
3063 if (expectedClass) {
3064 TBranchElement* bEl = (TBranchElement*)branch;
3065 bEl->SetTargetClass( expectedClass->GetName() );
3066 } else if (expectedType != kNoType_t && expectedType != kOther_t) {
3068 }
3069 }
3070 return kMatch;
3071}
3072
3073////////////////////////////////////////////////////////////////////////////////
3074/// Create a clone of this tree and copy nentries.
3075///
3076/// By default copy all entries.
3077/// The compression level of the cloned tree is set to the destination
3078/// file's compression level.
3079///
3080/// NOTE: Only active branches are copied.
3081/// NOTE: If the TTree is a TChain, the structure of the first TTree
3082/// is used for the copy.
3083///
3084/// IMPORTANT: The cloned tree stays connected with this tree until
3085/// this tree is deleted. In particular, any changes in
3086/// branch addresses in this tree are forwarded to the
3087/// clone trees, unless a branch in a clone tree has had
3088/// its address changed, in which case that change stays in
3089/// effect. When this tree is deleted, all the addresses of
3090/// the cloned tree are reset to their default values.
3091///
3092/// If 'option' contains the word 'fast' and nentries is -1, the
3093/// cloning will be done without unzipping or unstreaming the baskets
3094/// (i.e., a direct copy of the raw bytes on disk).
3095///
3096/// When 'fast' is specified, 'option' can also contain a sorting
3097/// order for the baskets in the output file.
3098///
3099/// There are currently 3 supported sorting order:
3100///
3101/// - SortBasketsByOffset (the default)
3102/// - SortBasketsByBranch
3103/// - SortBasketsByEntry
3104///
3105/// When using SortBasketsByOffset the baskets are written in the
3106/// output file in the same order as in the original file (i.e. the
3107/// baskets are sorted by their offset in the original file; Usually
3108/// this also means that the baskets are sorted by the index/number of
3109/// the _last_ entry they contain)
3110///
3111/// When using SortBasketsByBranch all the baskets of each individual
3112/// branches are stored contiguously. This tends to optimize reading
3113/// speed when reading a small number (1->5) of branches, since all
3114/// their baskets will be clustered together instead of being spread
3115/// across the file. However it might decrease the performance when
3116/// reading more branches (or the full entry).
3117///
3118/// When using SortBasketsByEntry the baskets with the lowest starting
3119/// entry are written first. (i.e. the baskets are sorted by the
3120/// index/number of the first entry they contain). This means that on
3121/// the file the baskets will be in the order in which they will be
3122/// needed when reading the whole tree sequentially.
3123///
3124/// For examples of CloneTree, see tutorials:
3125///
3126/// - copytree.C:
3127/// A macro to copy a subset of a TTree to a new TTree.
3128/// The input file has been generated by the program in
3129/// $ROOTSYS/test/Event with: Event 1000 1 1 1
3130///
3131/// - copytree2.C:
3132/// A macro to copy a subset of a TTree to a new TTree.
3133/// One branch of the new Tree is written to a separate file.
3134/// The input file has been generated by the program in
3135/// $ROOTSYS/test/Event with: Event 1000 1 1 1
3137TTree* TTree::CloneTree(Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
3138{
3139 // Options
3140 Bool_t fastClone = kFALSE;
3141
3142 TString opt = option;
3143 opt.ToLower();
3144 if (opt.Contains("fast")) {
3145 fastClone = kTRUE;
3146 }
3147
3148 // If we are a chain, switch to the first tree.
3149 if ((fEntries > 0) && (LoadTree(0) < 0)) {
3150 // FIXME: We need an error message here.
3151 return 0;
3152 }
3153
3154 // Note: For a tree we get the this pointer, for
3155 // a chain we get the chain's current tree.
3156 TTree* thistree = GetTree();
3157
3158 // We will use this to override the IO features on the cloned branches.
3159 ROOT::TIOFeatures features = this->GetIOFeatures();
3160 ;
3161
3162 // Note: For a chain, the returned clone will be
3163 // a clone of the chain's first tree.
3164 TTree* newtree = (TTree*) thistree->Clone();
3165 if (!newtree) {
3166 return 0;
3167 }
3168
3169 // The clone should not delete any objects allocated by SetAddress().
3170 TObjArray* branches = newtree->GetListOfBranches();
3171 Int_t nb = branches->GetEntriesFast();
3172 for (Int_t i = 0; i < nb; ++i) {
3173 TBranch* br = (TBranch*) branches->UncheckedAt(i);
3175 ((TBranchElement*) br)->ResetDeleteObject();
3176 }
3177 }
3178
3179 // Add the new tree to the list of clones so that
3180 // we can later inform it of changes to branch addresses.
3181 thistree->AddClone(newtree);
3182 if (thistree != this) {
3183 // In case this object is a TChain, add the clone
3184 // also to the TChain's list of clones.
3185 AddClone(newtree);
3186 }
3187
3188 newtree->Reset();
3189
3190 TDirectory* ndir = newtree->GetDirectory();
3191 TFile* nfile = 0;
3192 if (ndir) {
3193 nfile = ndir->GetFile();
3194 }
3195 Int_t newcomp = -1;
3196 if (nfile) {
3197 newcomp = nfile->GetCompressionSettings();
3198 }
3199
3200 //
3201 // Delete non-active branches from the clone.
3202 //
3203 // Note: If we are a chain, this does nothing
3204 // since chains have no leaves.
3205 TObjArray* leaves = newtree->GetListOfLeaves();
3206 Int_t nleaves = leaves->GetEntriesFast();
3207 for (Int_t lndx = 0; lndx < nleaves; ++lndx) {
3208 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(lndx);
3209 if (!leaf) {
3210 continue;
3211 }
3212 TBranch* branch = leaf->GetBranch();
3213 if (branch && (newcomp > -1)) {
3214 branch->SetCompressionSettings(newcomp);
3215 }
3216 if (branch) branch->SetIOFeatures(features);
3217 if (!branch || !branch->TestBit(kDoNotProcess)) {
3218 continue;
3219 }
3220 // size might change at each iteration of the loop over the leaves.
3221 nb = branches->GetEntriesFast();
3222 for (Long64_t i = 0; i < nb; ++i) {
3223 TBranch* br = (TBranch*) branches->UncheckedAt(i);
3224 if (br == branch) {
3225 branches->RemoveAt(i);
3226 delete br;
3227 br = 0;
3228 branches->Compress();
3229 break;
3230 }
3231 TObjArray* lb = br->GetListOfBranches();
3232 Int_t nb1 = lb->GetEntriesFast();
3233 for (Int_t j = 0; j < nb1; ++j) {
3234 TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
3235 if (!b1) {
3236 continue;
3237 }
3238 if (b1 == branch) {
3239 lb->RemoveAt(j);
3240 delete b1;
3241 b1 = 0;
3242 lb->Compress();
3243 break;
3244 }
3245 TObjArray* lb1 = b1->GetListOfBranches();
3246 Int_t nb2 = lb1->GetEntriesFast();
3247 for (Int_t k = 0; k < nb2; ++k) {
3248 TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
3249 if (!b2) {
3250 continue;
3251 }
3252 if (b2 == branch) {
3253 lb1->RemoveAt(k);
3254 delete b2;
3255 b2 = 0;
3256 lb1->Compress();
3257 break;
3258 }
3259 }
3260 }
3261 }
3262 }
3263 leaves->Compress();
3264
3265 // Copy MakeClass status.
3266 newtree->SetMakeClass(fMakeClass);
3267
3268 // Copy branch addresses.
3269 CopyAddresses(newtree);
3270
3271 //
3272 // Copy entries if requested.
3273 //
3274
3275 if (nentries != 0) {
3276 if (fastClone && (nentries < 0)) {
3277 if ( newtree->CopyEntries( this, -1, option, kFALSE ) < 0 ) {
3278 // There was a problem!
3279 Error("CloneTTree", "TTree has not been cloned\n");
3280 delete newtree;
3281 newtree = 0;
3282 return 0;
3283 }
3284 } else {
3285 newtree->CopyEntries( this, nentries, option, kFALSE );
3286 }
3287 }
3288
3289 return newtree;
3290}
3291
3292////////////////////////////////////////////////////////////////////////////////
3293/// Set branch addresses of passed tree equal to ours.
3294/// If undo is true, reset the branch addresses instead of copying them.
3295/// This ensures 'separation' of a cloned tree from its original.
3298{
3299 // Copy branch addresses starting from branches.
3300 TObjArray* branches = GetListOfBranches();
3301 Int_t nbranches = branches->GetEntriesFast();
3302 for (Int_t i = 0; i < nbranches; ++i) {
3303 TBranch* branch = (TBranch*) branches->UncheckedAt(i);
3304 if (branch->TestBit(kDoNotProcess)) {
3305 continue;
3306 }
3307 if (undo) {
3308 TBranch* br = tree->GetBranch(branch->GetName());
3309 tree->ResetBranchAddress(br);
3310 } else {
3311 char* addr = branch->GetAddress();
3312 if (!addr) {
3313 if (branch->IsA() == TBranch::Class()) {
3314 // If the branch was created using a leaflist, the branch itself may not have
3315 // an address but the leaf might already.
3316 TLeaf *firstleaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
3317 if (!firstleaf || firstleaf->GetValuePointer()) {
3318 // Either there is no leaf (and thus no point in copying the address)
3319 // or the leaf has an address but we can not copy it via the branche
3320 // this will be copied via the next loop (over the leaf).
3321 continue;
3322 }
3323 }
3324 // Note: This may cause an object to be allocated.
3325 branch->SetAddress(0);
3326 addr = branch->GetAddress();
3327 }
3328 TBranch* br = tree->GetBranch(branch->GetFullName());
3329 if (br) {
3330 if (br->GetMakeClass() != branch->GetMakeClass())
3331 br->SetMakeClass(branch->GetMakeClass());
3332 br->SetAddress(addr);
3333 // The copy does not own any object allocated by SetAddress().
3335 ((TBranchElement*) br)->ResetDeleteObject();
3336 }
3337 } else {
3338 Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
3339 }
3340 }
3341 }
3342
3343 // Copy branch addresses starting from leaves.
3344 TObjArray* tleaves = tree->GetListOfLeaves();
3345 Int_t ntleaves = tleaves->GetEntriesFast();
3346 std::set<TLeaf*> updatedLeafCount;
3347 for (Int_t i = 0; i < ntleaves; ++i) {
3348 TLeaf* tleaf = (TLeaf*) tleaves->UncheckedAt(i);
3349 TBranch* tbranch = tleaf->GetBranch();
3350 TBranch* branch = GetBranch(tbranch->GetName());
3351 if (!branch) {
3352 continue;
3353 }
3354 TLeaf* leaf = branch->GetLeaf(tleaf->GetName());
3355 if (!leaf) {
3356 continue;
3357 }
3358 if (branch->TestBit(kDoNotProcess)) {
3359 continue;
3360 }
3361 if (undo) {
3362 // Now we know whether the address has been transfered
3363 tree->ResetBranchAddress(tbranch);
3364 } else {
3365 TBranchElement *mother = dynamic_cast<TBranchElement*>(leaf->GetBranch()->GetMother());
3366 bool needAddressReset = false;
3367 if (leaf->GetLeafCount() && (leaf->TestBit(TLeaf::kNewValue) || !leaf->GetValuePointer() || (mother && mother->IsObjectOwner())) && tleaf->GetLeafCount())
3368 {
3369 // If it is an array and it was allocated by the leaf itself,
3370 // let's make sure it is large enough for the incoming data.
3371 if (leaf->GetLeafCount()->GetMaximum() < tleaf->GetLeafCount()->GetMaximum()) {
3372 leaf->GetLeafCount()->IncludeRange( tleaf->GetLeafCount() );
3373 updatedLeafCount.insert(leaf->GetLeafCount());
3374 needAddressReset = true;
3375 } else {
3376 needAddressReset = (updatedLeafCount.find(leaf->GetLeafCount()) != updatedLeafCount.end());
3377 }
3378 }
3379 if (needAddressReset && leaf->GetValuePointer()) {
3380 if (leaf->IsA() == TLeafElement::Class() && mother)
3381 mother->ResetAddress();
3382 else
3383 leaf->SetAddress(nullptr);
3384 }
3385 if (!branch->GetAddress() && !leaf->GetValuePointer()) {
3386 // We should attempts to set the address of the branch.
3387 // something like:
3388 //(TBranchElement*)branch->GetMother()->SetAddress(0)
3389 //plus a few more subtleties (see TBranchElement::GetEntry).
3390 //but for now we go the simplest route:
3391 //
3392 // Note: This may result in the allocation of an object.
3393 branch->SetupAddresses();
3394 }
3395 if (branch->GetAddress()) {
3396 tree->SetBranchAddress(branch->GetName(), (void*) branch->GetAddress());
3397 TBranch* br = tree->GetBranch(branch->GetName());
3398 if (br) {
3399 if (br->IsA() != branch->IsA()) {
3400 Error(
3401 "CopyAddresses",
3402 "Branch kind mismatch between input tree '%s' and output tree '%s' for branch '%s': '%s' vs '%s'",
3403 tree->GetName(), br->GetTree()->GetName(), br->GetName(), branch->IsA()->GetName(),
3404 br->IsA()->GetName());
3405 }
3406 // The copy does not own any object allocated by SetAddress().
3407 // FIXME: We do too much here, br may not be a top-level branch.
3409 ((TBranchElement*) br)->ResetDeleteObject();
3410 }
3411 } else {
3412 Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
3413 }
3414 } else {
3415 tleaf->SetAddress(leaf->GetValuePointer());
3416 }
3417 }
3418 }
3419
3420 if (undo &&
3421 ( tree->IsA()->InheritsFrom("TNtuple") || tree->IsA()->InheritsFrom("TNtupleD") )
3422 ) {
3423 tree->ResetBranchAddresses();
3424 }
3425}
3426
3427namespace {
3428
3429 enum EOnIndexError { kDrop, kKeep, kBuild };
3430
3431 static Bool_t R__HandleIndex(EOnIndexError onIndexError, TTree *newtree, TTree *oldtree)
3432 {
3433 // Return true if we should continue to handle indices, false otherwise.
3434
3435 Bool_t withIndex = kTRUE;
3436
3437 if ( newtree->GetTreeIndex() ) {
3438 if ( oldtree->GetTree()->GetTreeIndex() == 0 ) {
3439 switch (onIndexError) {
3440 case kDrop:
3441 delete newtree->GetTreeIndex();
3442 newtree->SetTreeIndex(0);
3443 withIndex = kFALSE;
3444 break;
3445 case kKeep:
3446 // Nothing to do really.
3447 break;
3448 case kBuild:
3449 // Build the index then copy it
3450 if (oldtree->GetTree()->BuildIndex(newtree->GetTreeIndex()->GetMajorName(), newtree->GetTreeIndex()->GetMinorName())) {
3451 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
3452 // Clean up
3453 delete oldtree->GetTree()->GetTreeIndex();
3454 oldtree->GetTree()->SetTreeIndex(0);
3455 }
3456 break;
3457 }
3458 } else {
3459 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
3460 }
3461 } else if ( oldtree->GetTree()->GetTreeIndex() != 0 ) {
3462 // We discover the first index in the middle of the chain.
3463 switch (onIndexError) {
3464 case kDrop:
3465 // Nothing to do really.
3466 break;
3467 case kKeep: {
3469 index->SetTree(newtree);
3470 newtree->SetTreeIndex(index);
3471 break;
3472 }
3473 case kBuild:
3474 if (newtree->GetEntries() == 0) {
3475 // Start an index.
3477 index->SetTree(newtree);
3478 newtree->SetTreeIndex(index);
3479 } else {
3480 // Build the index so far.
3481 if (newtree->BuildIndex(oldtree->GetTree()->GetTreeIndex()->GetMajorName(), oldtree->GetTree()->GetTreeIndex()->GetMinorName())) {
3482 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
3483 }
3484 }
3485 break;
3486 }
3487 } else if ( onIndexError == kDrop ) {
3488 // There is no index on this or on tree->GetTree(), we know we have to ignore any further
3489 // index
3490 withIndex = kFALSE;
3491 }
3492 return withIndex;
3493 }
3494}
3495
3496////////////////////////////////////////////////////////////////////////////////
3497/// Copy nentries from given tree to this tree.
3498/// This routines assumes that the branches that intended to be copied are
3499/// already connected. The typical case is that this tree was created using
3500/// tree->CloneTree(0).
3501///
3502/// By default copy all entries.
3503///
3504/// Returns number of bytes copied to this tree.
3505///
3506/// If 'option' contains the word 'fast' and nentries is -1, the cloning will be
3507/// done without unzipping or unstreaming the baskets (i.e., a direct copy of the
3508/// raw bytes on disk).
3509///
3510/// When 'fast' is specified, 'option' can also contains a sorting order for the
3511/// baskets in the output file.
3512///
3513/// There are currently 3 supported sorting order:
3514///
3515/// - SortBasketsByOffset (the default)
3516/// - SortBasketsByBranch
3517/// - SortBasketsByEntry
3518///
3519/// See TTree::CloneTree for a detailed explanation of the semantics of these 3 options.
3520///
3521/// If the tree or any of the underlying tree of the chain has an index, that index and any
3522/// index in the subsequent underlying TTree objects will be merged.
3523///
3524/// There are currently three 'options' to control this merging:
3525/// - NoIndex : all the TTreeIndex object are dropped.
3526/// - DropIndexOnError : if any of the underlying TTree object do no have a TTreeIndex,
3527/// they are all dropped.
3528/// - AsIsIndexOnError [default]: In case of missing TTreeIndex, the resulting TTree index has gaps.
3529/// - BuildIndexOnError : If any of the underlying TTree objects do not have a TTreeIndex,
3530/// all TTreeIndex are 'ignored' and the missing piece are rebuilt.
3532Long64_t TTree::CopyEntries(TTree* tree, Long64_t nentries /* = -1 */, Option_t* option /* = "" */, Bool_t needCopyAddresses /* = false */)
3533{
3534 if (!tree) {
3535 return 0;
3536 }
3537 // Options
3538 TString opt = option;
3539 opt.ToLower();
3540 Bool_t fastClone = opt.Contains("fast");
3541 Bool_t withIndex = !opt.Contains("noindex");
3542 EOnIndexError onIndexError;
3543 if (opt.Contains("asisindex")) {
3544 onIndexError = kKeep;
3545 } else if (opt.Contains("buildindex")) {
3546 onIndexError = kBuild;
3547 } else if (opt.Contains("dropindex")) {
3548 onIndexError = kDrop;
3549 } else {
3550 onIndexError = kBuild;
3551 }
3552 Ssiz_t cacheSizeLoc = opt.Index("cachesize=");
3553 Int_t cacheSize = -1;
3554 if (cacheSizeLoc != TString::kNPOS) {
3555 // If the parse faile, cacheSize stays at -1.
3556 Ssiz_t cacheSizeEnd = opt.Index(" ",cacheSizeLoc+10) - (cacheSizeLoc+10);
3557 TSubString cacheSizeStr( opt(cacheSizeLoc+10,cacheSizeEnd) );
3558 auto parseResult = ROOT::FromHumanReadableSize(cacheSizeStr,cacheSize);
3559 if (parseResult == ROOT::EFromHumanReadableSize::kParseFail) {
3560 Warning("CopyEntries","The cachesize option can not be parsed: %s. The default size will be used.",cacheSizeStr.String().Data());
3561 } else if (parseResult == ROOT::EFromHumanReadableSize::kOverflow) {
3562 double m;
3563 const char *munit = nullptr;
3564 ROOT::ToHumanReadableSize(std::numeric_limits<decltype(cacheSize)>::max(),false,&m,&munit);
3565
3566 Warning("CopyEntries","The cachesize option is too large: %s (%g%s max). The default size will be used.",cacheSizeStr.String().Data(),m,munit);
3567 }
3568 }
3569 if (gDebug > 0 && cacheSize != -1) Info("CopyEntries","Using Cache size: %d\n",cacheSize);
3570
3571 Long64_t nbytes = 0;
3572 Long64_t treeEntries = tree->GetEntriesFast();
3573 if (nentries < 0) {
3574 nentries = treeEntries;
3575 } else if (nentries > treeEntries) {
3576 nentries = treeEntries;
3577 }
3578
3579 if (fastClone && (nentries < 0 || nentries == tree->GetEntriesFast())) {
3580 // Quickly copy the basket without decompression and streaming.
3581 Long64_t totbytes = GetTotBytes();
3582 for (Long64_t i = 0; i < nentries; i += tree->GetTree()->GetEntries()) {
3583 if (tree->LoadTree(i) < 0) {
3584 break;
3585 }
3586 if ( withIndex ) {
3587 withIndex = R__HandleIndex( onIndexError, this, tree );
3588 }
3589 if (this->GetDirectory()) {
3590 TFile* file2 = this->GetDirectory()->GetFile();
3591 if (file2 && (file2->GetEND() > TTree::GetMaxTreeSize())) {
3592 if (this->GetDirectory() == (TDirectory*) file2) {
3593 this->ChangeFile(file2);
3594 }
3595 }
3596 }
3597 TTreeCloner cloner(tree->GetTree(), this, option, TTreeCloner::kNoWarnings);
3598 if (cloner.IsValid()) {
3599 this->SetEntries(this->GetEntries() + tree->GetTree()->GetEntries());
3600 if (cacheSize != -1) cloner.SetCacheSize(cacheSize);
3601 cloner.Exec();
3602 } else {
3603 if (i == 0) {
3604 Warning("CopyEntries","%s",cloner.GetWarning());
3605 // If the first cloning does not work, something is really wrong
3606 // (since apriori the source and target are exactly the same structure!)
3607 return -1;
3608 } else {
3609 if (cloner.NeedConversion()) {
3610 TTree *localtree = tree->GetTree();
3611 Long64_t tentries = localtree->GetEntries();
3612 if (needCopyAddresses) {
3613 // Copy MakeClass status.
3614 tree->SetMakeClass(fMakeClass);
3615 // Copy branch addresses.
3617 }
3618 for (Long64_t ii = 0; ii < tentries; ii++) {
3619 if (localtree->GetEntry(ii) <= 0) {
3620 break;
3621 }
3622 this->Fill();
3623 }
3624 if (needCopyAddresses)
3625 tree->ResetBranchAddresses();
3626 if (this->GetTreeIndex()) {
3627 this->GetTreeIndex()->Append(tree->GetTree()->GetTreeIndex(), kTRUE);
3628 }
3629 } else {
3630 Warning("CopyEntries","%s",cloner.GetWarning());
3631 if (tree->GetDirectory() && tree->GetDirectory()->GetFile()) {
3632 Warning("CopyEntries", "Skipped file %s\n", tree->GetDirectory()->GetFile()->GetName());
3633 } else {
3634 Warning("CopyEntries", "Skipped file number %d\n", tree->GetTreeNumber());
3635 }
3636 }
3637 }
3638 }
3639
3640 }
3641 if (this->GetTreeIndex()) {
3642 this->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
3643 }
3644 nbytes = GetTotBytes() - totbytes;
3645 } else {
3646 if (nentries < 0) {
3647 nentries = treeEntries;
3648 } else if (nentries > treeEntries) {
3649 nentries = treeEntries;
3650 }
3651 if (needCopyAddresses) {
3652 // Copy MakeClass status.
3653 tree->SetMakeClass(fMakeClass);
3654 // Copy branch addresses.
3656 }
3657 Int_t treenumber = -1;
3658 for (Long64_t i = 0; i < nentries; i++) {
3659 if (tree->LoadTree(i) < 0) {
3660 break;
3661 }
3662 if (treenumber != tree->GetTreeNumber()) {
3663 if ( withIndex ) {
3664 withIndex = R__HandleIndex( onIndexError, this, tree );
3665 }
3666 treenumber = tree->GetTreeNumber();
3667 }
3668 if (tree->GetEntry(i) <= 0) {
3669 break;
3670 }
3671 nbytes += this->Fill();
3672 }
3673 if (needCopyAddresses)
3674 tree->ResetBranchAddresses();
3675 if (this->GetTreeIndex()) {
3676 this->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
3677 }
3678 }
3679 return nbytes;
3680}
3681
3682////////////////////////////////////////////////////////////////////////////////
3683/// Copy a tree with selection.
3684///
3685/// ### Important:
3686///
3687/// The returned copied tree stays connected with the original tree
3688/// until the original tree is deleted. In particular, any changes
3689/// to the branch addresses in the original tree are also made to
3690/// the copied tree. Any changes made to the branch addresses of the
3691/// copied tree are overridden anytime the original tree changes its
3692/// branch addresses. When the original tree is deleted, all the
3693/// branch addresses of the copied tree are set to zero.
3694///
3695/// For examples of CopyTree, see the tutorials:
3696///
3697/// - copytree.C:
3698/// Example macro to copy a subset of a tree to a new tree.
3699/// The input file was generated by running the program in
3700/// $ROOTSYS/test/Event in this way:
3701/// ~~~ {.cpp}
3702/// ./Event 1000 1 1 1
3703/// ~~~
3704/// - copytree2.C
3705/// Example macro to copy a subset of a tree to a new tree.
3706/// One branch of the new tree is written to a separate file.
3707/// The input file was generated by running the program in
3708/// $ROOTSYS/test/Event in this way:
3709/// ~~~ {.cpp}
3710/// ./Event 1000 1 1 1
3711/// ~~~
3712/// - copytree3.C
3713/// Example macro to copy a subset of a tree to a new tree.
3714/// Only selected entries are copied to the new tree.
3715/// NOTE that only the active branches are copied.
3717TTree* TTree::CopyTree(const char* selection, Option_t* option /* = 0 */, Long64_t nentries /* = TTree::kMaxEntries */, Long64_t firstentry /* = 0 */)
3718{
3719 GetPlayer();
3720 if (fPlayer) {
3721 return fPlayer->CopyTree(selection, option, nentries, firstentry);
3722 }
3723 return 0;
3724}
3725
3726////////////////////////////////////////////////////////////////////////////////
3727/// Create a basket for this tree and given branch.
3730{
3731 if (!branch) {
3732 return 0;
3733 }
3734 return new TBasket(branch->GetName(), GetName(), branch);
3735}
3736
3737////////////////////////////////////////////////////////////////////////////////
3738/// Delete this tree from memory or/and disk.
3739///
3740/// - if option == "all" delete Tree object from memory AND from disk
3741/// all baskets on disk are deleted. All keys with same name
3742/// are deleted.
3743/// - if option =="" only Tree object in memory is deleted.
3745void TTree::Delete(Option_t* option /* = "" */)
3746{
3748
3749 // delete all baskets and header from file
3750 if (file && option && !strcmp(option,"all")) {
3751 if (!file->IsWritable()) {
3752 Error("Delete","File : %s is not writable, cannot delete Tree:%s", file->GetName(),GetName());
3753 return;
3754 }
3755
3756 //find key and import Tree header in memory
3757 TKey *key = fDirectory->GetKey(GetName());
3758 if (!key) return;
3759
3760 TDirectory *dirsav = gDirectory;
3761 file->cd();
3762
3763 //get list of leaves and loop on all the branches baskets
3764 TIter next(GetListOfLeaves());
3765 TLeaf *leaf;
3766 char header[16];
3767 Int_t ntot = 0;
3768 Int_t nbask = 0;
3769 Int_t nbytes,objlen,keylen;
3770 while ((leaf = (TLeaf*)next())) {
3771 TBranch *branch = leaf->GetBranch();
3772 Int_t nbaskets = branch->GetMaxBaskets();
3773 for (Int_t i=0;i<nbaskets;i++) {
3774 Long64_t pos = branch->GetBasketSeek(i);
3775 if (!pos) continue;
3776 TFile *branchFile = branch->GetFile();
3777 if (!branchFile) continue;
3778 branchFile->GetRecordHeader(header,pos,16,nbytes,objlen,keylen);
3779 if (nbytes <= 0) continue;
3780 branchFile->MakeFree(pos,pos+nbytes-1);
3781 ntot += nbytes;
3782 nbask++;
3783 }
3784 }
3785
3786 // delete Tree header key and all keys with the same name
3787 // A Tree may have been saved many times. Previous cycles are invalid.
3788 while (key) {
3789 ntot += key->GetNbytes();
3790 key->Delete();
3791 delete key;
3792 key = fDirectory->GetKey(GetName());
3793 }
3794 if (dirsav) dirsav->cd();
3795 if (gDebug) Info("TTree::Delete", "Deleting Tree: %s: %d baskets deleted. Total space freed = %d bytes\n",GetName(),nbask,ntot);
3796 }
3797
3798 if (fDirectory) {
3799 fDirectory->Remove(this);
3800 //delete the file cache if it points to this Tree
3802 fDirectory = nullptr;
3804 }
3805
3806 // Delete object from CINT symbol table so it can not be used anymore.
3807 gCling->DeleteGlobal(this);
3808
3809 // Warning: We have intentional invalidated this object while inside a member function!
3810 delete this;
3811}
3812
3813 ///////////////////////////////////////////////////////////////////////////////
3814 /// Called by TKey and TObject::Clone to automatically add us to a directory
3815 /// when we are read from a file.
3818{
3819 if (fDirectory == dir) return;
3820 if (fDirectory) {
3821 fDirectory->Remove(this);
3822 // Delete or move the file cache if it points to this Tree
3824 MoveReadCache(file,dir);
3825 }
3826 fDirectory = dir;
3827 TBranch* b = 0;
3828 TIter next(GetListOfBranches());
3829 while((b = (TBranch*) next())) {
3830 b->UpdateFile();
3831 }
3832 if (fBranchRef) {
3834 }
3835 if (fDirectory) fDirectory->Append(this);
3836}
3837
3838////////////////////////////////////////////////////////////////////////////////
3839/// Draw expression varexp for specified entries.
3840///
3841/// \return -1 in case of error or number of selected events in case of success.
3842///
3843/// This function accepts TCut objects as arguments.
3844/// Useful to use the string operator +
3845///
3846/// Example:
3847///
3848/// ~~~ {.cpp}
3849/// ntuple.Draw("x",cut1+cut2+cut3);
3850/// ~~~
3851
3853Long64_t TTree::Draw(const char* varexp, const TCut& selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
3854{
3855 return TTree::Draw(varexp, selection.GetTitle(), option, nentries, firstentry);
3856}
3857
3858/////////////////////////////////////////////////////////////////////////////////////////
3859/// \brief Draw expression varexp for entries and objects that pass a (optional) selection.
3860///
3861/// \return -1 in case of error or number of selected events in case of success.
3862///
3863/// \param [in] varexp
3864/// \parblock
3865/// A string that takes one of these general forms:
3866/// - "e1" produces a 1-d histogram (TH1F) of expression "e1"
3867/// - "e1:e2" produces an unbinned 2-d scatter-plot (TGraph) of "e1"
3868/// on the y-axis versus "e2" on the x-axis
3869/// - "e1:e2:e3" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
3870/// vs "e2" vs "e3" on the z-, y-, x-axis, respectively
3871/// - "e1:e2:e3:e4" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
3872/// vs "e2" vs "e3" and "e4" mapped on the current color palette.
3873/// (to create histograms in the 2, 3, and 4 dimensional case,
3874/// see section "Saving the result of Draw to an histogram")
3875/// - "e1:e2:e3:e4:e5" with option "GL5D" produces a 5D plot using OpenGL. `gStyle->SetCanvasPreferGL(true)` is needed.
3876/// - Any number of variables no fewer than two can be used with the options "CANDLE" and "PARA"
3877/// - An arbitrary number of variables can be used with the option "GOFF"
3878///
3879/// Examples:
3880/// - "x": the simplest case, it draws a 1-Dim histogram of column x
3881/// - "sqrt(x)", "x*y/z": draw histogram with the values of the specified numerical expression across TTree events
3882/// - "y:sqrt(x)": 2-Dim histogram of y versus sqrt(x)
3883/// - "px:py:pz:2.5*E": produces a 3-d scatter-plot of px vs py ps pz
3884/// and the color number of each marker will be 2.5*E.
3885/// If the color number is negative it is set to 0.
3886/// If the color number is greater than the current number of colors
3887/// it is set to the highest color number. The default number of
3888/// colors is 50. See TStyle::SetPalette for setting a new color palette.
3889///
3890/// The expressions can use all the operations and built-in functions
3891/// supported by TFormula (see TFormula::Analyze()), including free
3892/// functions taking numerical arguments (e.g. TMath::Bessel()).
3893/// In addition, you can call member functions taking numerical
3894/// arguments. For example, these are two valid expressions:
3895/// ~~~ {.cpp}
3896/// TMath::BreitWigner(fPx,3,2)
3897/// event.GetHistogram()->GetXaxis()->GetXmax()
3898/// ~~~
3899/// \endparblock
3900/// \param [in] selection
3901/// \parblock
3902/// A string containing a selection expression.
3903/// In a selection all usual C++ mathematical and logical operators are allowed.
3904/// The value corresponding to the selection expression is used as a weight
3905/// to fill the histogram (a weight of 0 is equivalent to not filling the histogram).\n
3906/// \n
3907/// Examples:
3908/// - "x<y && sqrt(z)>3.2": returns a weight = 0 or 1
3909/// - "(x+y)*(sqrt(z)>3.2)": returns a weight = x+y if sqrt(z)>3.2, 0 otherwise\n
3910/// \n
3911/// If the selection expression returns an array, it is iterated over in sync with the
3912/// array returned by the varexp argument (as described below in "Drawing expressions using arrays and array
3913/// elements"). For example, if, for a given event, varexp evaluates to
3914/// `{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:
3915/// ~~~{.cpp}
3916/// // Muon_pt is an array: fill a histogram with the array elements > 100 in each event
3917/// tree->Draw('Muon_pt', 'Muon_pt > 100')
3918/// ~~~
3919/// \endparblock
3920/// \param [in] option
3921/// \parblock
3922/// The drawing option.
3923/// - When an histogram is produced it can be any histogram drawing option
3924/// listed in THistPainter.
3925/// - when no option is specified:
3926/// - the default histogram drawing option is used
3927/// if the expression is of the form "e1".
3928/// - if the expression is of the form "e1:e2"or "e1:e2:e3" a cloud of
3929/// unbinned 2D or 3D points is drawn respectively.
3930/// - if the expression has four fields "e1:e2:e3:e4" a cloud of unbinned 3D
3931/// points is produced with e1 vs e2 vs e3, and e4 is mapped on the current color
3932/// palette.
3933/// - If option COL is specified when varexp has three fields:
3934/// ~~~ {.cpp}
3935/// tree.Draw("e1:e2:e3","","col");
3936/// ~~~
3937/// a 2D scatter is produced with e1 vs e2, and e3 is mapped on the current
3938/// color palette. The colors for e3 are evaluated once in linear scale before
3939/// painting. Therefore changing the pad to log scale along Z as no effect
3940/// on the colors.
3941/// - if expression has more than four fields the option "PARA"or "CANDLE"
3942/// can be used.
3943/// - If option contains the string "goff", no graphics is generated.
3944/// \endparblock
3945/// \param [in] nentries The number of entries to process (default is all)
3946/// \param [in] firstentry The first entry to process (default is 0)
3947///
3948/// ### Drawing expressions using arrays and array elements
3949///
3950/// Let assumes, a leaf fMatrix, on the branch fEvent, which is a 3 by 3 array,
3951/// or a TClonesArray.
3952/// In a TTree::Draw expression you can now access fMatrix using the following
3953/// syntaxes:
3954///
3955/// | String passed | What is used for each entry of the tree
3956/// |-----------------|--------------------------------------------------------|
3957/// | `fMatrix` | the 9 elements of fMatrix |
3958/// | `fMatrix[][]` | the 9 elements of fMatrix |
3959/// | `fMatrix[2][2]` | only the elements fMatrix[2][2] |
3960/// | `fMatrix[1]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
3961/// | `fMatrix[1][]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
3962/// | `fMatrix[][0]` | the 3 elements fMatrix[0][0], fMatrix[1][0] and fMatrix[2][0] |
3963///
3964/// "fEvent.fMatrix...." same as "fMatrix..." (unless there is more than one leaf named fMatrix!).
3965///
3966/// In summary, if a specific index is not specified for a dimension, TTree::Draw
3967/// will loop through all the indices along this dimension. Leaving off the
3968/// last (right most) dimension of specifying then with the two characters '[]'
3969/// is equivalent. For variable size arrays (and TClonesArray) the range
3970/// of the first dimension is recalculated for each entry of the tree.
3971/// You can also specify the index as an expression of any other variables from the
3972/// tree.
3973///
3974/// TTree::Draw also now properly handling operations involving 2 or more arrays.
3975///
3976/// Let assume a second matrix fResults[5][2], here are a sample of some
3977/// of the possible combinations, the number of elements they produce and
3978/// the loop used:
3979///
3980/// | expression | element(s) | Loop |
3981/// |----------------------------------|------------|--------------------------|
3982/// | `fMatrix[2][1] - fResults[5][2]` | one | no loop |
3983/// | `fMatrix[2][] - fResults[5][2]` | three | on 2nd dim fMatrix |
3984/// | `fMatrix[2][] - fResults[5][]` | two | on both 2nd dimensions |
3985/// | `fMatrix[][2] - fResults[][1]` | three | on both 1st dimensions |
3986/// | `fMatrix[][2] - fResults[][]` | six | on both 1st and 2nd dimensions of fResults |
3987/// | `fMatrix[][2] - fResults[3][]` | two | on 1st dim of fMatrix and 2nd of fResults (at the same time) |
3988/// | `fMatrix[][] - fResults[][]` | six | on 1st dim then on 2nd dim |
3989/// | `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.|
3990///
3991///
3992/// In summary, TTree::Draw loops through all unspecified dimensions. To
3993/// figure out the range of each loop, we match each unspecified dimension
3994/// from left to right (ignoring ALL dimensions for which an index has been
3995/// specified), in the equivalent loop matched dimensions use the same index
3996/// and are restricted to the smallest range (of only the matched dimensions).
3997/// When involving variable arrays, the range can of course be different
3998/// for each entry of the tree.
3999///
4000/// So the loop equivalent to "fMatrix[][2] - fResults[3][]" is:
4001/// ~~~ {.cpp}
4002/// for (Int_t i0; i < min(3,2); i++) {
4003/// use the value of (fMatrix[i0][2] - fMatrix[3][i0])
4004/// }
4005/// ~~~
4006/// So the loop equivalent to "fMatrix[][2] - fResults[][]" is:
4007/// ~~~ {.cpp}
4008/// for (Int_t i0; i < min(3,5); i++) {
4009/// for (Int_t i1; i1 < 2; i1++) {
4010/// use the value of (fMatrix[i0][2] - fMatrix[i0][i1])
4011/// }
4012/// }
4013/// ~~~
4014/// So the loop equivalent to "fMatrix[][] - fResults[][]" is:
4015/// ~~~ {.cpp}
4016/// for (Int_t i0; i < min(3,5); i++) {
4017/// for (Int_t i1; i1 < min(3,2); i1++) {
4018/// use the value of (fMatrix[i0][i1] - fMatrix[i0][i1])
4019/// }
4020/// }
4021/// ~~~
4022/// So the loop equivalent to "fMatrix[][fResults[][]]" is:
4023/// ~~~ {.cpp}
4024/// for (Int_t i0; i0 < 3; i0++) {
4025/// for (Int_t j2; j2 < 5; j2++) {
4026/// for (Int_t j3; j3 < 2; j3++) {
4027/// i1 = fResults[j2][j3];
4028/// use the value of fMatrix[i0][i1]
4029/// }
4030/// }
4031/// ~~~
4032/// ### Retrieving the result of Draw
4033///
4034/// By default a temporary histogram called `htemp` is created. It will be:
4035///
4036/// - A TH1F* in case of a mono-dimensional distribution: `Draw("e1")`,
4037/// - A TH2F* in case of a bi-dimensional distribution: `Draw("e1:e2")`,
4038/// - A TH3F* in case of a three-dimensional distribution: `Draw("e1:e2:e3")`.
4039///
4040/// In the one dimensional case the `htemp` is filled and drawn whatever the drawing
4041/// option is.
4042///
4043/// In the two and three dimensional cases, with the default drawing option (`""`),
4044/// a cloud of points is drawn and the histogram `htemp` is not filled. For all the other
4045/// drawing options `htemp` will be filled.
4046///
4047/// In all cases `htemp` can be retrieved by calling:
4048///
4049/// ~~~ {.cpp}
4050/// auto htemp = (TH1F*)gPad->GetPrimitive("htemp"); // 1D
4051/// auto htemp = (TH2F*)gPad->GetPrimitive("htemp"); // 2D
4052/// auto htemp = (TH3F*)gPad->GetPrimitive("htemp"); // 3D
4053/// ~~~
4054///
4055/// In the two dimensional case (`Draw("e1;e2")`), with the default drawing option, the
4056/// data is filled into a TGraph named `Graph`. This TGraph can be retrieved by
4057/// calling
4058///
4059/// ~~~ {.cpp}
4060/// auto graph = (TGraph*)gPad->GetPrimitive("Graph");
4061/// ~~~
4062///
4063/// For the three and four dimensional cases, with the default drawing option, an unnamed
4064/// TPolyMarker3D is produced, and therefore cannot be retrieved.
4065///
4066/// In all cases `htemp` can be used to access the axes. For instance in the 2D case:
4067///
4068/// ~~~ {.cpp}
4069/// auto htemp = (TH2F*)gPad->GetPrimitive("htemp");
4070/// auto xaxis = htemp->GetXaxis();
4071/// ~~~
4072///
4073/// When the option `"A"` is used (with TGraph painting option) to draw a 2D
4074/// distribution:
4075/// ~~~ {.cpp}
4076/// tree.Draw("e1:e2","","A*");
4077/// ~~~
4078/// a scatter plot is produced (with stars in that case) but the axis creation is
4079/// delegated to TGraph and `htemp` is not created.
4080///
4081/// ### Saving the result of Draw to a histogram
4082///
4083/// If `varexp` contains `>>hnew` (following the variable(s) name(s)),
4084/// the new histogram called `hnew` is created and it is kept in the current
4085/// directory (and also the current pad). This works for all dimensions.
4086///
4087/// Example:
4088/// ~~~ {.cpp}
4089/// tree.Draw("sqrt(x)>>hsqrt","y>0")
4090/// ~~~
4091/// will draw `sqrt(x)` and save the histogram as "hsqrt" in the current
4092/// directory. To retrieve it do:
4093/// ~~~ {.cpp}
4094/// TH1F *hsqrt = (TH1F*)gDirectory->Get("hsqrt");
4095/// ~~~
4096/// The binning information is taken from the environment variables
4097/// ~~~ {.cpp}
4098/// Hist.Binning.?D.?
4099/// ~~~
4100/// In addition, the name of the histogram can be followed by up to 9
4101/// numbers between '(' and ')', where the numbers describe the
4102/// following:
4103///
4104/// - 1 - bins in x-direction
4105/// - 2 - lower limit in x-direction
4106/// - 3 - upper limit in x-direction
4107/// - 4-6 same for y-direction
4108/// - 7-9 same for z-direction
4109///
4110/// When a new binning is used the new value will become the default.
4111/// Values can be skipped.
4112///
4113/// Example:
4114/// ~~~ {.cpp}
4115/// tree.Draw("sqrt(x)>>hsqrt(500,10,20)")
4116/// // plot sqrt(x) between 10 and 20 using 500 bins
4117/// tree.Draw("sqrt(x):sin(y)>>hsqrt(100,10,60,50,.1,.5)")
4118/// // plot sqrt(x) against sin(y)
4119/// // 100 bins in x-direction; lower limit on x-axis is 10; upper limit is 60
4120/// // 50 bins in y-direction; lower limit on y-axis is .1; upper limit is .5
4121/// ~~~
4122/// By default, the specified histogram is reset.
4123/// To continue to append data to an existing histogram, use "+" in front
4124/// of the histogram name.
4125///
4126/// A '+' in front of the histogram name is ignored, when the name is followed by
4127/// binning information as described in the previous paragraph.
4128/// ~~~ {.cpp}
4129/// tree.Draw("sqrt(x)>>+hsqrt","y>0")
4130/// ~~~
4131/// will not reset `hsqrt`, but will continue filling. This works for 1-D, 2-D
4132/// and 3-D histograms.
4133///
4134/// ### Accessing collection objects
4135///
4136/// TTree::Draw default's handling of collections is to assume that any
4137/// request on a collection pertain to it content. For example, if fTracks
4138/// is a collection of Track objects, the following:
4139/// ~~~ {.cpp}
4140/// tree->Draw("event.fTracks.fPx");
4141/// ~~~
4142/// will plot the value of fPx for each Track objects inside the collection.
4143/// Also
4144/// ~~~ {.cpp}
4145/// tree->Draw("event.fTracks.size()");
4146/// ~~~
4147/// would plot the result of the member function Track::size() for each
4148/// Track object inside the collection.
4149/// To access information about the collection itself, TTree::Draw support
4150/// the '@' notation. If a variable which points to a collection is prefixed
4151/// or postfixed with '@', the next part of the expression will pertain to
4152/// the collection object. For example:
4153/// ~~~ {.cpp}
4154/// tree->Draw("event.@fTracks.size()");
4155/// ~~~
4156/// will plot the size of the collection referred to by `fTracks` (i.e the number
4157/// of Track objects).
4158///
4159/// ### Drawing 'objects'
4160///
4161/// When a class has a member function named AsDouble or AsString, requesting
4162/// to directly draw the object will imply a call to one of the 2 functions.
4163/// If both AsDouble and AsString are present, AsDouble will be used.
4164/// AsString can return either a char*, a std::string or a TString.s
4165/// For example, the following
4166/// ~~~ {.cpp}
4167/// tree->Draw("event.myTTimeStamp");
4168/// ~~~
4169/// will draw the same histogram as
4170/// ~~~ {.cpp}
4171/// tree->Draw("event.myTTimeStamp.AsDouble()");
4172/// ~~~
4173/// In addition, when the object is a type TString or std::string, TTree::Draw
4174/// will call respectively `TString::Data` and `std::string::c_str()`
4175///
4176/// If the object is a TBits, the histogram will contain the index of the bit
4177/// that are turned on.
4178///
4179/// ### Retrieving information about the tree itself.
4180///
4181/// You can refer to the tree (or chain) containing the data by using the
4182/// string 'This'.
4183/// You can then could any TTree methods. For example:
4184/// ~~~ {.cpp}
4185/// tree->Draw("This->GetReadEntry()");
4186/// ~~~
4187/// will display the local entry numbers be read.
4188/// ~~~ {.cpp}
4189/// tree->Draw("This->GetUserInfo()->At(0)->GetName()");
4190/// ~~~
4191/// will display the name of the first 'user info' object.
4192///
4193/// ### Special functions and variables
4194///
4195/// `Entry$`: A TTree::Draw formula can use the special variable `Entry$`
4196/// to access the entry number being read. For example to draw every
4197/// other entry use:
4198/// ~~~ {.cpp}
4199/// tree.Draw("myvar","Entry$%2==0");
4200/// ~~~
4201/// - `Entry$` : return the current entry number (`== TTree::GetReadEntry()`)
4202/// - `LocalEntry$` : return the current entry number in the current tree of a
4203/// chain (`== GetTree()->GetReadEntry()`)
4204/// - `Entries$` : return the total number of entries (== TTree::GetEntries())
4205/// - `LocalEntries$` : return the total number of entries in the current tree
4206/// of a chain (== GetTree()->TTree::GetEntries())
4207/// - `Length$` : return the total number of element of this formula for this
4208/// entry (`==TTreeFormula::GetNdata()`)
4209/// - `Iteration$` : return the current iteration over this formula for this
4210/// entry (i.e. varies from 0 to `Length$`).
4211/// - `Length$(formula )` : return the total number of element of the formula
4212/// given as a parameter.
4213/// - `Sum$(formula )` : return the sum of the value of the elements of the
4214/// formula given as a parameter. For example the mean for all the elements in
4215/// one entry can be calculated with: `Sum$(formula )/Length$(formula )`
4216/// - `Min$(formula )` : return the minimum (within one TTree entry) of the value of the
4217/// elements of the formula given as a parameter.
4218/// - `Max$(formula )` : return the maximum (within one TTree entry) of the value of the
4219/// elements of the formula given as a parameter.
4220/// - `MinIf$(formula,condition)`
4221/// - `MaxIf$(formula,condition)` : return the minimum (maximum) (within one TTree entry)
4222/// of the value of the elements of the formula given as a parameter
4223/// if they match the condition. If no element matches the condition,
4224/// the result is zero. To avoid the resulting peak at zero, use the
4225/// pattern:
4226/// ~~~ {.cpp}
4227/// tree->Draw("MinIf$(formula,condition)","condition");
4228/// ~~~
4229/// which will avoid calculation `MinIf$` for the entries that have no match
4230/// for the condition.
4231/// - `Alt$(primary,alternate)` : return the value of "primary" if it is available
4232/// for the current iteration otherwise return the value of "alternate".
4233/// For example, with arr1[3] and arr2[2]
4234/// ~~~ {.cpp}
4235/// tree->Draw("arr1+Alt$(arr2,0)");
4236/// ~~~
4237/// will draw arr1[0]+arr2[0] ; arr1[1]+arr2[1] and arr1[2]+0
4238/// Or with a variable size array arr3
4239/// ~~~ {.cpp}
4240/// tree->Draw("Alt$(arr3[0],0)+Alt$(arr3[1],0)+Alt$(arr3[2],0)");
4241/// ~~~
4242/// will draw the sum arr3 for the index 0 to min(2,actual_size_of_arr3-1)
4243/// As a comparison
4244/// ~~~ {.cpp}
4245/// tree->Draw("arr3[0]+arr3[1]+arr3[2]");
4246/// ~~~
4247/// will draw the sum arr3 for the index 0 to 2 only if the
4248/// actual_size_of_arr3 is greater or equal to 3.
4249/// Note that the array in 'primary' is flattened/linearized thus using
4250/// `Alt$` with multi-dimensional arrays of different dimensions in unlikely
4251/// to yield the expected results. To visualize a bit more what elements
4252/// would be matched by TTree::Draw, TTree::Scan can be used:
4253/// ~~~ {.cpp}
4254/// tree->Scan("arr1:Alt$(arr2,0)");
4255/// ~~~
4256/// will print on one line the value of arr1 and (arr2,0) that will be
4257/// matched by
4258/// ~~~ {.cpp}
4259/// tree->Draw("arr1-Alt$(arr2,0)");
4260/// ~~~
4261/// The ternary operator is not directly supported in TTree::Draw however, to plot the
4262/// equivalent of `var2<20 ? -99 : var1`, you can use:
4263/// ~~~ {.cpp}
4264/// tree->Draw("(var2<20)*99+(var2>=20)*var1","");
4265/// ~~~
4266///
4267/// ### Drawing a user function accessing the TTree data directly
4268///
4269/// If the formula contains a file name, TTree::MakeProxy will be used
4270/// to load and execute this file. In particular it will draw the
4271/// result of a function with the same name as the file. The function
4272/// will be executed in a context where the name of the branches can
4273/// be used as a C++ variable.
4274///
4275/// For example draw px using the file hsimple.root (generated by the
4276/// hsimple.C tutorial), we need a file named hsimple.cxx:
4277/// ~~~ {.cpp}
4278/// double hsimple() {
4279/// return px;
4280/// }
4281/// ~~~
4282/// MakeProxy can then be used indirectly via the TTree::Draw interface
4283/// as follow:
4284/// ~~~ {.cpp}
4285/// new TFile("hsimple.root")
4286/// ntuple->Draw("hsimple.cxx");
4287/// ~~~
4288/// A more complete example is available in the tutorials directory:
4289/// `h1analysisProxy.cxx`, `h1analysProxy.h` and `h1analysisProxyCut.C`
4290/// which reimplement the selector found in `h1analysis.C`
4291///
4292/// The main features of this facility are:
4293///
4294/// * on-demand loading of branches
4295/// * ability to use the 'branchname' as if it was a data member
4296/// * protection against array out-of-bound
4297/// * ability to use the branch data as object (when the user code is available)
4298///
4299/// See TTree::MakeProxy for more details.
4300///
4301/// ### Making a Profile histogram
4302///
4303/// In case of a 2-Dim expression, one can generate a TProfile histogram
4304/// instead of a TH2F histogram by specifying option=prof or option=profs
4305/// or option=profi or option=profg ; the trailing letter select the way
4306/// the bin error are computed, See TProfile2D::SetErrorOption for
4307/// details on the differences.
4308/// The option=prof is automatically selected in case of y:x>>pf
4309/// where pf is an existing TProfile histogram.
4310///
4311/// ### Making a 2D Profile histogram
4312///
4313/// In case of a 3-Dim expression, one can generate a TProfile2D histogram
4314/// instead of a TH3F histogram by specifying option=prof or option=profs.
4315/// or option=profi or option=profg ; the trailing letter select the way
4316/// the bin error are computed, See TProfile2D::SetErrorOption for
4317/// details on the differences.
4318/// The option=prof is automatically selected in case of z:y:x>>pf
4319/// where pf is an existing TProfile2D histogram.
4320///
4321/// ### Making a 5D plot using GL
4322///
4323/// If option GL5D is specified together with 5 variables, a 5D plot is drawn
4324/// using OpenGL. See $ROOTSYS/tutorials/tree/staff.C as example.
4325///
4326/// ### Making a parallel coordinates plot
4327///
4328/// In case of a 2-Dim or more expression with the option=para, one can generate
4329/// a parallel coordinates plot. With that option, the number of dimensions is
4330/// arbitrary. Giving more than 4 variables without the option=para or
4331/// option=candle or option=goff will produce an error.
4332///
4333/// ### Making a candle sticks chart
4334///
4335/// In case of a 2-Dim or more expression with the option=candle, one can generate
4336/// a candle sticks chart. With that option, the number of dimensions is
4337/// arbitrary. Giving more than 4 variables without the option=para or
4338/// option=candle or option=goff will produce an error.
4339///
4340/// ### Normalizing the output histogram to 1
4341///
4342/// When option contains "norm" the output histogram is normalized to 1.
4343///
4344/// ### Saving the result of Draw to a TEventList, a TEntryList or a TEntryListArray
4345///
4346/// TTree::Draw can be used to fill a TEventList object (list of entry numbers)
4347/// instead of histogramming one variable.
4348/// If varexp0 has the form >>elist , a TEventList object named "elist"
4349/// is created in the current directory. elist will contain the list
4350/// of entry numbers satisfying the current selection.
4351/// If option "entrylist" is used, a TEntryList object is created
4352/// If the selection contains arrays, vectors or any container class and option
4353/// "entrylistarray" is used, a TEntryListArray object is created
4354/// containing also the subentries satisfying the selection, i.e. the indices of
4355/// the branches which hold containers classes.
4356/// Example:
4357/// ~~~ {.cpp}
4358/// tree.Draw(">>yplus","y>0")
4359/// ~~~
4360/// will create a TEventList object named "yplus" in the current directory.
4361/// In an interactive session, one can type (after TTree::Draw)
4362/// ~~~ {.cpp}
4363/// yplus.Print("all")
4364/// ~~~
4365/// to print the list of entry numbers in the list.
4366/// ~~~ {.cpp}
4367/// tree.Draw(">>yplus", "y>0", "entrylist")
4368/// ~~~
4369/// will create a TEntryList object names "yplus" in the current directory
4370/// ~~~ {.cpp}
4371/// tree.Draw(">>yplus", "y>0", "entrylistarray")
4372/// ~~~
4373/// will create a TEntryListArray object names "yplus" in the current directory
4374///
4375/// By default, the specified entry list is reset.
4376/// To continue to append data to an existing list, use "+" in front
4377/// of the list name;
4378/// ~~~ {.cpp}
4379/// tree.Draw(">>+yplus","y>0")
4380/// ~~~
4381/// will not reset yplus, but will enter the selected entries at the end
4382/// of the existing list.
4383///
4384/// ### Using a TEventList, TEntryList or TEntryListArray as Input
4385///
4386/// Once a TEventList or a TEntryList object has been generated, it can be used as input
4387/// for TTree::Draw. Use TTree::SetEventList or TTree::SetEntryList to set the
4388/// current event list
4389///
4390/// Example 1:
4391/// ~~~ {.cpp}
4392/// TEventList *elist = (TEventList*)gDirectory->Get("yplus");
4393/// tree->SetEventList(elist);
4394/// tree->Draw("py");
4395/// ~~~
4396/// Example 2:
4397/// ~~~ {.cpp}
4398/// TEntryList *elist = (TEntryList*)gDirectory->Get("yplus");
4399/// tree->SetEntryList(elist);
4400/// tree->Draw("py");
4401/// ~~~
4402/// If a TEventList object is used as input, a new TEntryList object is created
4403/// inside the SetEventList function. In case of a TChain, all tree headers are loaded
4404/// for this transformation. This new object is owned by the chain and is deleted
4405/// with it, unless the user extracts it by calling GetEntryList() function.
4406/// See also comments to SetEventList() function of TTree and TChain.
4407///
4408/// If arrays are used in the selection criteria and TEntryListArray is not used,
4409/// all the entries that have at least one element of the array that satisfy the selection
4410/// are entered in the list.
4411///
4412/// Example:
4413/// ~~~ {.cpp}
4414/// tree.Draw(">>pyplus","fTracks.fPy>0");
4415/// tree->SetEventList(pyplus);
4416/// tree->Draw("fTracks.fPy");
4417/// ~~~
4418/// will draw the fPy of ALL tracks in event with at least one track with
4419/// a positive fPy.
4420///
4421/// To select only the elements that did match the original selection
4422/// use TEventList::SetReapplyCut or TEntryList::SetReapplyCut.
4423///
4424/// Example:
4425/// ~~~ {.cpp}
4426/// tree.Draw(">>pyplus","fTracks.fPy>0");
4427/// pyplus->SetReapplyCut(kTRUE);
4428/// tree->SetEventList(pyplus);
4429/// tree->Draw("fTracks.fPy");
4430/// ~~~
4431/// will draw the fPy of only the tracks that have a positive fPy.
4432///
4433/// To draw only the elements that match a selection in case of arrays,
4434/// you can also use TEntryListArray (faster in case of a more general selection).
4435///
4436/// Example:
4437/// ~~~ {.cpp}
4438/// tree.Draw(">>pyplus","fTracks.fPy>0", "entrylistarray");
4439/// tree->SetEntryList(pyplus);
4440/// tree->Draw("fTracks.fPy");
4441/// ~~~
4442/// will draw the fPy of only the tracks that have a positive fPy,
4443/// but without redoing the selection.
4444///
4445/// Note: Use tree->SetEventList(0) if you do not want use the list as input.
4446///
4447/// ### How to obtain more info from TTree::Draw
4448///
4449/// Once TTree::Draw has been called, it is possible to access useful
4450/// information still stored in the TTree object via the following functions:
4451///
4452/// - GetSelectedRows() // return the number of values accepted by the selection expression. In case where no selection was specified, returns the number of values processed.
4453/// - GetV1() // returns a pointer to the double array of V1
4454/// - GetV2() // returns a pointer to the double array of V2
4455/// - GetV3() // returns a pointer to the double array of V3
4456/// - GetV4() // returns a pointer to the double array of V4
4457/// - GetW() // returns a pointer to the double array of Weights where weight equal the result of the selection expression.
4458///
4459/// where V1,V2,V3 correspond to the expressions in
4460/// ~~~ {.cpp}
4461/// TTree::Draw("V1:V2:V3:V4",selection);
4462/// ~~~
4463/// If the expression has more than 4 component use GetVal(index)
4464///
4465/// Example:
4466/// ~~~ {.cpp}
4467/// Root > ntuple->Draw("py:px","pz>4");
4468/// Root > TGraph *gr = new TGraph(ntuple->GetSelectedRows(),
4469/// ntuple->GetV2(), ntuple->GetV1());
4470/// Root > gr->Draw("ap"); //draw graph in current pad
4471/// ~~~
4472///
4473/// A more complete complete tutorial (treegetval.C) shows how to use the
4474/// GetVal() method.
4475///
4476/// creates a TGraph object with a number of points corresponding to the
4477/// number of entries selected by the expression "pz>4", the x points of the graph
4478/// being the px values of the Tree and the y points the py values.
4479///
4480/// Important note: By default TTree::Draw creates the arrays obtained
4481/// with GetW, GetV1, GetV2, GetV3, GetV4, GetVal with a length corresponding
4482/// to the parameter fEstimate. The content will be the last `GetSelectedRows() % GetEstimate()`
4483/// values calculated.
4484/// By default fEstimate=1000000 and can be modified
4485/// via TTree::SetEstimate. To keep in memory all the results (in case
4486/// where there is only one result per entry), use
4487/// ~~~ {.cpp}
4488/// tree->SetEstimate(tree->GetEntries()+1); // same as tree->SetEstimate(-1);
4489/// ~~~
4490/// You must call SetEstimate if the expected number of selected rows
4491/// you need to look at is greater than 1000000.
4492///
4493/// You can use the option "goff" to turn off the graphics output
4494/// of TTree::Draw in the above example.
4495///
4496/// ### Automatic interface to TTree::Draw via the TTreeViewer
4497///
4498/// A complete graphical interface to this function is implemented
4499/// in the class TTreeViewer.
4500/// To start the TTreeViewer, three possibilities:
4501/// - select TTree context menu item "StartViewer"
4502/// - type the command "TTreeViewer TV(treeName)"
4503/// - execute statement "tree->StartViewer();"
4505Long64_t TTree::Draw(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
4506{
4507 GetPlayer();
4508 if (fPlayer)
4509 return fPlayer->DrawSelect(varexp,selection,option,nentries,firstentry);
4510 return -1;
4511}
4512
4513////////////////////////////////////////////////////////////////////////////////
4514/// Remove some baskets from memory.
4516void TTree::DropBaskets()
4517{
4518 TBranch* branch = 0;
4520 for (Int_t i = 0; i < nb; ++i) {
4521 branch = (TBranch*) fBranches.UncheckedAt(i);
4522 branch->DropBaskets("all");
4523 }
4524}
4525
4526////////////////////////////////////////////////////////////////////////////////
4527/// Drop branch buffers to accommodate nbytes below MaxVirtualsize.
4530{
4531 // Be careful not to remove current read/write buffers.
4532 Int_t nleaves = fLeaves.GetEntriesFast();
4533 for (Int_t i = 0; i < nleaves; ++i) {
4534 TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
4535 TBranch* branch = (TBranch*) leaf->GetBranch();
4536 Int_t nbaskets = branch->GetListOfBaskets()->GetEntries();
4537 for (Int_t j = 0; j < nbaskets - 1; ++j) {
4538 if ((j == branch->GetReadBasket()) || (j == branch->GetWriteBasket())) {
4539 continue;
4540 }
4541 TBasket* basket = (TBasket*)branch->GetListOfBaskets()->UncheckedAt(j);
4542 if (basket) {
4543 basket->DropBuffers();
4545 return;
4546 }
4547 }
4548 }
4549 }
4550}
4551
4552////////////////////////////////////////////////////////////////////////////////
4553/// Fill all branches.
4554///
4555/// This function loops on all the branches of this tree. For
4556/// each branch, it copies to the branch buffer (basket) the current
4557/// values of the leaves data types. If a leaf is a simple data type,
4558/// a simple conversion to a machine independent format has to be done.
4559///
4560/// This machine independent version of the data is copied into a
4561/// basket (each branch has its own basket). When a basket is full
4562/// (32k worth of data by default), it is then optionally compressed
4563/// and written to disk (this operation is also called committing or
4564/// 'flushing' the basket). The committed baskets are then
4565/// immediately removed from memory.
4566///
4567/// The function returns the number of bytes committed to the
4568/// individual branches.
4569///
4570/// If a write error occurs, the number of bytes returned is -1.
4571///
4572/// If no data are written, because, e.g., the branch is disabled,
4573/// the number of bytes returned is 0.
4574///
4575/// __The baskets are flushed and the Tree header saved at regular intervals__
4576///
4577/// At regular intervals, when the amount of data written so far is
4578/// greater than fAutoFlush (see SetAutoFlush) all the baskets are flushed to disk.
4579/// This makes future reading faster as it guarantees that baskets belonging to nearby
4580/// entries will be on the same disk region.
4581/// When the first call to flush the baskets happen, we also take this opportunity
4582/// to optimize the baskets buffers.
4583/// We also check if the amount of data written is greater than fAutoSave (see SetAutoSave).
4584/// In this case we also write the Tree header. This makes the Tree recoverable up to this point
4585/// in case the program writing the Tree crashes.
4586/// The decisions to FlushBaskets and Auto Save can be made based either on the number
4587/// of bytes written (fAutoFlush and fAutoSave negative) or on the number of entries
4588/// written (fAutoFlush and fAutoSave positive).
4589/// Note that the user can decide to call FlushBaskets and AutoSave in her event loop
4590/// base on the number of events written instead of the number of bytes written.
4591///
4592/// \note Calling `TTree::FlushBaskets` too often increases the IO time.
4593///
4594/// \note Calling `TTree::AutoSave` too often increases the IO time and also the
4595/// file size.
4596///
4597/// \note This method calls `TTree::ChangeFile` when the tree reaches a size
4598/// greater than `TTree::fgMaxTreeSize`. This doesn't happen if the tree is
4599/// attached to a `TMemFile` or derivate.
4602{
4603 Int_t nbytes = 0;
4604 Int_t nwrite = 0;
4605 Int_t nerror = 0;
4606 Int_t nbranches = fBranches.GetEntriesFast();
4607
4608 // Case of one single super branch. Automatically update
4609 // all the branch addresses if a new object was created.
4610 if (nbranches == 1)
4611 ((TBranch *)fBranches.UncheckedAt(0))->UpdateAddress();
4612
4613 if (fBranchRef)
4614 fBranchRef->Clear();
4615
4616#ifdef R__USE_IMT
4617 const auto useIMT = ROOT::IsImplicitMTEnabled() && fIMTEnabled;
4619 if (useIMT) {
4620 fIMTFlush = true;
4621 fIMTZipBytes.store(0);
4622 fIMTTotBytes.store(0);
4623 }
4624#endif
4625
4626 for (Int_t i = 0; i < nbranches; ++i) {
4627 // Loop over all branches, filling and accumulating bytes written and error counts.
4628 TBranch *branch = (TBranch *)fBranches.UncheckedAt(i);
4629
4630 if (branch->TestBit(kDoNotProcess))
4631 continue;
4632
4633#ifndef R__USE_IMT
4634 nwrite = branch->FillImpl(nullptr);
4635#else
4636 nwrite = branch->FillImpl(useIMT ? &imtHelper : nullptr);
4637#endif
4638 if (nwrite < 0) {
4639 if (nerror < 2) {
4640 Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld\n"
4641 " This error is symptomatic of a Tree created as a memory-resident Tree\n"
4642 " Instead of doing:\n"
4643 " TTree *T = new TTree(...)\n"
4644 " TFile *f = new TFile(...)\n"
4645 " you should do:\n"
4646 " TFile *f = new TFile(...)\n"
4647 " TTree *T = new TTree(...)\n\n",
4648 GetName(), branch->GetName(), nwrite, fEntries + 1);
4649 } else {
4650 Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld", GetName(), branch->GetName(), nwrite,
4651 fEntries + 1);
4652 }
4653 ++nerror;
4654 } else {
4655 nbytes += nwrite;
4656 }
4657 }
4658
4659#ifdef R__USE_IMT
4660 if (fIMTFlush) {
4661 imtHelper.Wait();
4662 fIMTFlush = false;
4663 const_cast<TTree *>(this)->AddTotBytes(fIMTTotBytes);
4664 const_cast<TTree *>(this)->AddZipBytes(fIMTZipBytes);
4665 nbytes += imtHelper.GetNbytes();
4666 nerror += imtHelper.GetNerrors();
4667 }
4668#endif
4669
4670 if (fBranchRef)
4671 fBranchRef->Fill();
4672
4673 ++fEntries;
4674
4675 if (fEntries > fMaxEntries)
4676 KeepCircular();
4677
4678 if (gDebug > 0)
4679 Info("TTree::Fill", " - A: %d %lld %lld %lld %lld %lld %lld \n", nbytes, fEntries, fAutoFlush, fAutoSave,
4681
4682 bool autoFlush = false;
4683 bool autoSave = false;
4684
4685 if (fAutoFlush != 0 || fAutoSave != 0) {
4686 // Is it time to flush or autosave baskets?
4687 if (fFlushedBytes == 0) {
4688 // If fFlushedBytes == 0, it means we never flushed or saved, so
4689 // we need to check if it's time to do it and recompute the values
4690 // of fAutoFlush and fAutoSave in terms of the number of entries.
4691 // Decision can be based initially either on the number of bytes
4692 // or the number of entries written.
4693 Long64_t zipBytes = GetZipBytes();
4694
4695 if (fAutoFlush)
4696 autoFlush = fAutoFlush < 0 ? (zipBytes > -fAutoFlush) : fEntries % fAutoFlush == 0;
4697
4698 if (fAutoSave)
4699 autoSave = fAutoSave < 0 ? (zipBytes > -fAutoSave) : fEntries % fAutoSave == 0;
4700
4701 if (autoFlush || autoSave) {
4702 // First call FlushBasket to make sure that fTotBytes is up to date.
4704 autoFlush = false; // avoid auto flushing again later
4705
4706 // When we are in one-basket-per-cluster mode, there is no need to optimize basket:
4707 // they will automatically grow to the size needed for an event cluster (with the basket
4708 // shrinking preventing them from growing too much larger than the actually-used space).
4710 OptimizeBaskets(GetTotBytes(), 1, "");
4711 if (gDebug > 0)
4712 Info("TTree::Fill", "OptimizeBaskets called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n",
4714 }
4716 fAutoFlush = fEntries; // Use test on entries rather than bytes
4717
4718 // subsequently in run
4719 if (fAutoSave < 0) {
4720 // Set fAutoSave to the largest integer multiple of
4721 // fAutoFlush events such that fAutoSave*fFlushedBytes
4722 // < (minus the input value of fAutoSave)
4723 Long64_t totBytes = GetTotBytes();
4724 if (zipBytes != 0) {
4725 fAutoSave = TMath::Max(fAutoFlush, fEntries * ((-fAutoSave / zipBytes) / fEntries));
4726 } else if (totBytes != 0) {
4727 fAutoSave = TMath::Max(fAutoFlush, fEntries * ((-fAutoSave / totBytes) / fEntries));
4728 } else {
4730 TTree::Class()->WriteBuffer(b, (TTree *)this);
4731 Long64_t total = b.Length();
4733 }
4734 } else if (fAutoSave > 0) {
4736 }
4737
4738 if (fAutoSave != 0 && fEntries >= fAutoSave)
4739 autoSave = true;
4740
4741 if (gDebug > 0)
4742 Info("TTree::Fill", "First AutoFlush. fAutoFlush = %lld, fAutoSave = %lld\n", fAutoFlush, fAutoSave);
4743 }
4744 } else {
4745 // Check if we need to auto flush
4746 if (fAutoFlush) {
4747 if (fNClusterRange == 0)
4748 autoFlush = fEntries > 1 && fEntries % fAutoFlush == 0;
4749 else
4750 autoFlush = (fEntries - (fClusterRangeEnd[fNClusterRange - 1] + 1)) % fAutoFlush == 0;
4751 }
4752 // Check if we need to auto save
4753 if (fAutoSave)
4754 autoSave = fEntries % fAutoSave == 0;
4755 }
4756 }
4757
4758 if (autoFlush) {
4760 if (gDebug > 0)
4761 Info("TTree::Fill", "FlushBaskets() called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n", fEntries,
4764 }
4765
4766 if (autoSave) {
4767 AutoSave(); // does not call FlushBasketsImpl() again
4768 if (gDebug > 0)
4769 Info("TTree::Fill", "AutoSave called at entry %lld, fZipBytes=%lld, fSavedBytes=%lld\n", fEntries,
4771 }
4772
4773 // Check that output file is still below the maximum size.
4774 // If above, close the current file and continue on a new file.
4775 // Currently, the automatic change of file is restricted
4776 // to the case where the tree is in the top level directory.
4777 if (fDirectory)
4778 if (TFile *file = fDirectory->GetFile())
4779 if (static_cast<TDirectory *>(file) == fDirectory && (file->GetEND() > fgMaxTreeSize))
4780 // Changing file clashes with the design of TMemFile and derivates, see #6523.
4781 if (!(dynamic_cast<TMemFile *>(file)))
4783
4784 return nerror == 0 ? nbytes : -1;
4785}
4786
4787////////////////////////////////////////////////////////////////////////////////
4788/// Search in the array for a branch matching the branch name,
4789/// with the branch possibly expressed as a 'full' path name (with dots).
4791static TBranch *R__FindBranchHelper(TObjArray *list, const char *branchname) {
4792 if (list==0 || branchname == 0 || branchname[0] == '\0') return 0;
4793
4794 Int_t nbranches = list->GetEntries();
4795
4796 UInt_t brlen = strlen(branchname);
4797
4798 for(Int_t index = 0; index < nbranches; ++index) {
4799 TBranch *where = (TBranch*)list->UncheckedAt(index);
4800
4801 const char *name = where->GetName();
4802 UInt_t len = strlen(name);
4803 if (len && name[len-1]==']') {
4804 const char *dim = strchr(name,'[');
4805 if (dim) {
4806 len = dim - name;
4807 }
4808 }
4809 if (brlen == len && strncmp(branchname,name,len)==0) {
4810 return where;
4811 }
4812 TBranch *next = 0;
4813 if ((brlen >= len) && (branchname[len] == '.')
4814 && strncmp(name, branchname, len) == 0) {
4815 // The prefix subbranch name match the branch name.
4816
4817 next = where->FindBranch(branchname);
4818 if (!next) {
4819 next = where->FindBranch(branchname+len+1);
4820 }
4821 if (next) return next;
4822 }
4823 const char *dot = strchr((char*)branchname,'.');
4824 if (dot) {
4825 if (len==(size_t)(dot-branchname) &&
4826 strncmp(branchname,name,dot-branchname)==0 ) {
4827 return R__FindBranchHelper(where->GetListOfBranches(),dot+1);
4828 }
4829 }
4830 }
4831 return 0;
4832}
4833
4834////////////////////////////////////////////////////////////////////////////////
4835/// Return the branch that correspond to the path 'branchname', which can
4836/// include the name of the tree or the omitted name of the parent branches.
4837/// In case of ambiguity, returns the first match.
4839TBranch* TTree::FindBranch(const char* branchname)
4840{
4841 // We already have been visited while recursively looking
4842 // through the friends tree, let return
4844 return nullptr;
4845 }
4846
4847 if (!branchname)
4848 return nullptr;
4849
4850 TBranch* branch = nullptr;
4851 // If the first part of the name match the TTree name, look for the right part in the
4852 // list of branches.
4853 // This will allow the branchname to be preceded by
4854 // the name of this tree.
4855 if (strncmp(fName.Data(),branchname,fName.Length())==0 && branchname[fName.Length()]=='.') {
4856 branch = R__FindBranchHelper( GetListOfBranches(), branchname + fName.Length() + 1);
4857 if (branch) return branch;
4858 }
4859 // If we did not find it, let's try to find the full name in the list of branches.
4860 branch = R__FindBranchHelper(GetListOfBranches(), branchname);
4861 if (branch) return branch;
4862
4863 // If we still did not find, let's try to find it within each branch assuming it does not the branch name.
4864 TIter next(GetListOfBranches());
4865 while ((branch = (TBranch*) next())) {
4866 TBranch* nestedbranch = branch->FindBranch(branchname);
4867 if (nestedbranch) {
4868 return nestedbranch;
4869 }
4870 }
4871
4872 // Search in list of friends.
4873 if (!fFriends) {
4874 return nullptr;
4875 }
4876 TFriendLock lock(this, kFindBranch);
4877 TIter nextf(fFriends);
4878 TFriendElement* fe = nullptr;
4879 while ((fe = (TFriendElement*) nextf())) {
4880 TTree* t = fe->GetTree();
4881 if (!t) {
4882 continue;
4883 }
4884 // If the alias is present replace it with the real name.
4885 const char *subbranch = strstr(branchname, fe->GetName());
4886 if (subbranch != branchname) {
4887 subbranch = nullptr;
4888 }
4889 if (subbranch) {
4890 subbranch += strlen(fe->GetName());
4891 if (*subbranch != '.') {
4892 subbranch = nullptr;
4893 } else {
4894 ++subbranch;
4895 }
4896 }
4897 std::ostringstream name;
4898 if (subbranch) {
4899 name << t->GetName() << "." << subbranch;
4900 } else {
4901 name << branchname;
4902 }
4903 branch = t->FindBranch(name.str().c_str());
4904 if (branch) {
4905 return branch;
4906 }
4907 }
4908 return nullptr;
4909}
4910
4911////////////////////////////////////////////////////////////////////////////////
4912/// Find leaf..
4914TLeaf* TTree::FindLeaf(const char* searchname)
4915{
4916 if (!searchname)
4917 return nullptr;
4918
4919 // We already have been visited while recursively looking
4920 // through the friends tree, let's return.
4922 return nullptr;
4923 }
4924
4925 // This will allow the branchname to be preceded by
4926 // the name of this tree.
4927 const char* subsearchname = strstr(searchname, GetName());
4928 if (subsearchname != searchname) {
4929 subsearchname = nullptr;
4930 }
4931 if (subsearchname) {
4932 subsearchname += strlen(GetName());
4933 if (*subsearchname != '.') {
4934 subsearchname = nullptr;
4935 } else {
4936 ++subsearchname;
4937 if (subsearchname[0] == 0) {
4938 subsearchname = nullptr;
4939 }
4940 }
4941 }
4942
4943 TString leafname;
4944 TString leaftitle;
4945 TString longname;
4946 TString longtitle;
4947
4948 const bool searchnameHasDot = strchr(searchname, '.') != nullptr;
4949
4950 // For leaves we allow for one level up to be prefixed to the name.
4951 TIter next(GetListOfLeaves());
4952 TLeaf* leaf = nullptr;
4953 while ((leaf = (TLeaf*) next())) {
4954 leafname = leaf->GetName();
4955 Ssiz_t dim = leafname.First('[');
4956 if (dim >= 0) leafname.Remove(dim);
4957
4958 if (leafname == searchname) {
4959 return leaf;
4960 }
4961 if (subsearchname && leafname == subsearchname) {
4962 return leaf;
4963 }
4964 // The TLeafElement contains the branch name
4965 // in its name, let's use the title.
4966 leaftitle = leaf->GetTitle();
4967 dim = leaftitle.First('[');
4968 if (dim >= 0) leaftitle.Remove(dim);
4969
4970 if (leaftitle == searchname) {
4971 return leaf;
4972 }
4973 if (subsearchname && leaftitle == subsearchname) {
4974 return leaf;
4975 }
4976 if (!searchnameHasDot)
4977 continue;
4978 TBranch* branch = leaf->GetBranch();
4979 if (branch) {
4980 longname.Form("%s.%s",branch->GetName(),leafname.Data());
4981 dim = longname.First('[');
4982 if (dim>=0) longname.Remove(dim);
4983 if (longname == searchname) {
4984 return leaf;
4985 }
4986 if (subsearchname && longname == subsearchname) {
4987 return leaf;
4988 }
4989 longtitle.Form("%s.%s",branch->GetName(),leaftitle.Data());
4990 dim = longtitle.First('[');
4991 if (dim>=0) longtitle.Remove(dim);
4992 if (longtitle == searchname) {
4993 return leaf;
4994 }
4995 if (subsearchname && longtitle == subsearchname) {
4996 return leaf;
4997 }
4998 // The following is for the case where the branch is only
4999 // a sub-branch. Since we do not see it through
5000 // TTree::GetListOfBranches, we need to see it indirectly.
5001 // This is the less sturdy part of this search ... it may
5002 // need refining ...
5003 if (strstr(searchname, ".") && !strcmp(searchname, branch->GetName())) {
5004 return leaf;
5005 }
5006 if (subsearchname && strstr(subsearchname, ".") && !strcmp(subsearchname, branch->GetName())) {
5007 return leaf;
5008 }
5009 }
5010 }
5011 // Search in list of friends.
5012 if (!fFriends) {
5013 return nullptr;
5014 }
5015 TFriendLock lock(this, kFindLeaf);
5016 TIter nextf(fFriends);
5017 TFriendElement* fe = nullptr;
5018 while ((fe = (TFriendElement*) nextf())) {
5019 TTree* t = fe->GetTree();
5020 if (!t) {
5021 continue;
5022 }
5023 // If the alias is present replace it with the real name.
5024 subsearchname = strstr(searchname, fe->GetName());
5025 if (subsearchname != searchname) {
5026 subsearchname = nullptr;
5027 }
5028 if (subsearchname) {
5029 subsearchname += strlen(fe->GetName());
5030 if (*subsearchname != '.') {
5031 subsearchname = nullptr;
5032 } else {
5033 ++subsearchname;
5034 }
5035 }
5036 if (subsearchname) {
5037 leafname.Form("%s.%s",t->GetName(),subsearchname);
5038 } else {
5039 leafname = searchname;
5040 }
5041 leaf = t->FindLeaf(leafname);
5042 if (leaf) {
5043 return leaf;
5044 }
5045 }
5046 return nullptr;
5047}
5048
5049////////////////////////////////////////////////////////////////////////////////
5050/// Fit a projected item(s) from a tree.
5051///
5052/// funcname is a TF1 function.
5053///
5054/// See TTree::Draw() for explanations of the other parameters.
5055///
5056/// By default the temporary histogram created is called htemp.
5057/// If varexp contains >>hnew , the new histogram created is called hnew
5058/// and it is kept in the current directory.
5059///
5060/// The function returns the number of selected entries.
5061///
5062/// Example:
5063/// ~~~ {.cpp}
5064/// tree.Fit(pol4,"sqrt(x)>>hsqrt","y>0")
5065/// ~~~
5066/// will fit sqrt(x) and save the histogram as "hsqrt" in the current
5067/// directory.
5068///
5069/// See also TTree::UnbinnedFit
5070///
5071/// ## Return status
5072///
5073/// The function returns the status of the histogram fit (see TH1::Fit)
5074/// If no entries were selected, the function returns -1;
5075/// (i.e. fitResult is null if the fit is OK)
5077Int_t TTree::Fit(const char* funcname, const char* varexp, const char* selection, Option_t* option, Option_t* goption, Long64_t nentries, Long64_t firstentry)
5078{
5079 GetPlayer();
5080 if (fPlayer) {
5081 return fPlayer->Fit(funcname, varexp, selection, option, goption, nentries, firstentry);
5082 }
5083 return -1;
5084}
5085
5086namespace {
5087struct BoolRAIIToggle {
5088 Bool_t &m_val;
5089
5090 BoolRAIIToggle(Bool_t &val) : m_val(val) { m_val = true; }
5091 ~BoolRAIIToggle() { m_val = false; }
5092};
5093}
5094
5095////////////////////////////////////////////////////////////////////////////////
5096/// Write to disk all the basket that have not yet been individually written and
5097/// create an event cluster boundary (by default).
5098///
5099/// If the caller wishes to flush the baskets but not create an event cluster,
5100/// then set create_cluster to false.
5101///
5102/// If ROOT has IMT-mode enabled, this will launch multiple TBB tasks in parallel
5103/// via TThreadExecutor to do this operation; one per basket compression. If the
5104/// caller utilizes TBB also, care must be taken to prevent deadlocks.
5105///
5106/// For example, let's say the caller holds mutex A and calls FlushBaskets; while
5107/// TBB is waiting for the ROOT compression tasks to complete, it may decide to
5108/// run another one of the user's tasks in this thread. If the second user task
5109/// tries to acquire A, then a deadlock will occur. The example call sequence
5110/// looks like this:
5111///
5112/// - User acquires mutex A
5113/// - User calls FlushBaskets.
5114/// - ROOT launches N tasks and calls wait.
5115/// - TBB schedules another user task, T2.
5116/// - T2 tries to acquire mutex A.
5117///
5118/// At this point, the thread will deadlock: the code may function with IMT-mode
5119/// disabled if the user assumed the legacy code never would run their own TBB
5120/// tasks.
5121///
5122/// SO: users of TBB who want to enable IMT-mode should carefully review their
5123/// locking patterns and make sure they hold no coarse-grained application
5124/// locks when they invoke ROOT.
5125///
5126/// Return the number of bytes written or -1 in case of write error.
5127Int_t TTree::FlushBaskets(Bool_t create_cluster) const
5128{
5129 Int_t retval = FlushBasketsImpl();
5130 if (retval == -1) return retval;
5131
5132 if (create_cluster) const_cast<TTree *>(this)->MarkEventCluster();
5133 return retval;
5134}
5135
5136////////////////////////////////////////////////////////////////////////////////
5137/// Internal implementation of the FlushBaskets algorithm.
5138/// Unlike the public interface, this does NOT create an explicit event cluster
5139/// boundary; it is up to the (internal) caller to determine whether that should
5140/// done.
5141///
5142/// Otherwise, the comments for FlushBaskets applies.
5145{
5146 if (!fDirectory) return 0;
5147 Int_t nbytes = 0;
5148 Int_t nerror = 0;
5149 TObjArray *lb = const_cast<TTree*>(this)->GetListOfBranches();
5150 Int_t nb = lb->GetEntriesFast();
5151
5152#ifdef R__USE_IMT
5153 const auto useIMT = ROOT::IsImplicitMTEnabled() && fIMTEnabled;
5154 if (useIMT) {
5155 // ROOT-9668: here we need to check if the size of fSortedBranches is different from the
5156 // size of the list of branches before triggering the initialisation of the fSortedBranches
5157 // container to cover two cases:
5158 // 1. This is the first time we flush. fSortedBranches is empty and we need to fill it.
5159 // 2. We flushed at least once already but a branch has been be added to the tree since then
5160 if (fSortedBranches.size() != unsigned(nb)) { const_cast<TTree*>(this)->InitializeBranchLists(false); }
5161
5162 BoolRAIIToggle sentry(fIMTFlush);
5163 fIMTZipBytes.store(0);
5164 fIMTTotBytes.store(0);
5165 std::atomic<Int_t> nerrpar(0);
5166 std::atomic<Int_t> nbpar(0);
5167 std::atomic<Int_t> pos(0);
5168
5169 auto mapFunction = [&]() {
5170 // The branch to process is obtained when the task starts to run.
5171 // This way, since branches are sorted, we make sure that branches
5172 // leading to big tasks are processed first. If we assigned the
5173 // branch at task creation time, the scheduler would not necessarily
5174 // respect our sorting.
5175 Int_t j = pos.fetch_add(1);
5176
5177 auto branch = fSortedBranches[j].second;
5178 if (R__unlikely(!branch)) { return; }
5179
5180 if (R__unlikely(gDebug > 0)) {
5181 std::stringstream ss;
5182 ss << std::this_thread::get_id();
5183 Info("FlushBaskets", "[IMT] Thread %s", ss.str().c_str());
5184 Info("FlushBaskets", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
5185 }
5186
5187 Int_t nbtask = branch->FlushBaskets();
5188
5189 if (nbtask < 0) { nerrpar++; }
5190 else { nbpar += nbtask; }
5191 };
5192
5194 pool.Foreach(mapFunction, nb);
5195
5196 fIMTFlush = false;
5197 const_cast<TTree*>(this)->AddTotBytes(fIMTTotBytes);
5198 const_cast<TTree*>(this)->AddZipBytes(fIMTZipBytes);
5199
5200 return nerrpar ? -1 : nbpar.load();
5201 }
5202#endif
5203 for (Int_t j = 0; j < nb; j++) {
5204 TBranch* branch = (TBranch*) lb->UncheckedAt(j);
5205 if (branch) {
5206 Int_t nwrite = branch->FlushBaskets();
5207 if (nwrite<0) {
5208 ++nerror;
5209 } else {
5210 nbytes += nwrite;
5211 }
5212 }
5213 }
5214 if (nerror) {
5215 return -1;
5216 } else {
5217 return nbytes;
5218 }
5219}
5220
5221////////////////////////////////////////////////////////////////////////////////
5222/// Returns the expanded value of the alias. Search in the friends if any.
5224const char* TTree::GetAlias(const char* aliasName) const
5225{
5226 // We already have been visited while recursively looking
5227 // through the friends tree, let's return.
5229 return nullptr;
5230 }
5231 if (fAliases) {
5232 TObject* alias = fAliases->FindObject(aliasName);
5233 if (alias) {
5234 return alias->GetTitle();
5235 }
5236 }
5237 if (!fFriends) {
5238 return nullptr;
5239 }
5240 TFriendLock lock(const_cast<TTree*>(this), kGetAlias);
5241 TIter nextf(fFriends);
5242 TFriendElement* fe = nullptr;
5243 while ((fe = (TFriendElement*) nextf())) {
5244 TTree* t = fe->GetTree();
5245 if (t) {
5246 const char* alias = t->GetAlias(aliasName);
5247 if (alias) {
5248 return alias;
5249 }
5250 const char* subAliasName = strstr(aliasName, fe->GetName());
5251 if (subAliasName && (subAliasName[strlen(fe->GetName())] == '.')) {
5252 alias = t->GetAlias(aliasName + strlen(fe->GetName()) + 1);
5253 if (alias) {
5254 return alias;
5255 }
5256 }
5257 }
5258 }
5259 return nullptr;
5260}
5261
5262namespace {
5263/// Do a breadth first search through the implied hierarchy
5264/// of branches.
5265/// To avoid scanning through the list multiple time
5266/// we also remember the 'depth-first' match.
5267TBranch *R__GetBranch(const TObjArray &branches, const char *name)
5268{
5269 TBranch *result = nullptr;
5270 Int_t nb = branches.GetEntriesFast();
5271 for (Int_t i = 0; i < nb; i++) {
5272 TBranch* b = (TBranch*)branches.UncheckedAt(i);
5273 if (!b)
5274 continue;
5275 if (!strcmp(b->GetName(), name)) {
5276 return b;
5277 }
5278 if (!strcmp(b->GetFullName(), name)) {
5279 return b;
5280 }
5281 if (!result)
5282 result = R__GetBranch(*(b->GetListOfBranches()), name);
5283 }
5284 return result;
5285}
5286}
5287
5288////////////////////////////////////////////////////////////////////////////////
5289/// Return pointer to the branch with the given name in this tree or its friends.
5290/// The search is done breadth first.
5292TBranch* TTree::GetBranch(const char* name)
5293{
5294 // We already have been visited while recursively
5295 // looking through the friends tree, let's return.
5297 return nullptr;
5298 }
5299
5300 if (!name)
5301 return nullptr;
5302
5303 // Look for an exact match in the list of top level
5304 // branches.
5306 if (result)
5307 return result;
5308
5309 // Search using branches, breadth first.
5310 result = R__GetBranch(fBranches, name);
5311 if (result)
5312 return result;
5313
5314 // Search using leaves.
5315 TObjArray* leaves = GetListOfLeaves();
5316 Int_t nleaves = leaves->GetEntriesFast();
5317 for (Int_t i = 0; i < nleaves; i++) {
5318 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
5319 TBranch* branch = leaf->GetBranch();
5320 if (!strcmp(branch->GetName(), name)) {
5321 return branch;
5322 }
5323 if (!strcmp(branch->GetFullName(), name)) {
5324 return branch;
5325 }
5326 }
5327
5328 if (!fFriends) {
5329 return nullptr;
5330 }
5331
5332 // Search in list of friends.
5333 TFriendLock lock(this, kGetBranch);
5334 TIter next(fFriends);
5335 TFriendElement* fe = nullptr;
5336 while ((fe = (TFriendElement*) next())) {
5337 TTree* t = fe->GetTree();
5338 if (t) {
5339 TBranch* branch = t->GetBranch(name);
5340 if (branch) {
5341 return branch;
5342 }
5343 }
5344 }
5345
5346 // Second pass in the list of friends when
5347 // the branch name is prefixed by the tree name.
5348 next.Reset();
5349 while ((fe = (TFriendElement*) next())) {
5350 TTree* t = fe->GetTree();
5351 if (!t) {
5352 continue;
5353 }
5354 const char* subname = strstr(name, fe->GetName());
5355 if (subname != name) {
5356 continue;
5357 }
5358 Int_t l = strlen(fe->GetName());
5359 subname += l;
5360 if (*subname != '.') {
5361 continue;
5362 }
5363 subname++;
5364 TBranch* branch = t->GetBranch(subname);
5365 if (branch) {
5366 return branch;
5367 }
5368 }
5369 return nullptr;
5370}
5371
5372////////////////////////////////////////////////////////////////////////////////
5373/// Return status of branch with name branchname.
5374///
5375/// - 0 if branch is not activated
5376/// - 1 if branch is activated
5378Bool_t TTree::GetBranchStatus(const char* branchname) const
5379{
5380 TBranch* br = const_cast<TTree*>(this)->GetBranch(branchname);
5381 if (br) {
5382 return br->TestBit(kDoNotProcess) == 0;
5383 }
5384 return 0;
5385}
5386
5387////////////////////////////////////////////////////////////////////////////////
5388/// Static function returning the current branch style.
5389///
5390/// - style = 0 old Branch
5391/// - style = 1 new Bronch
5394{
5395 return fgBranchStyle;
5396}
5397
5398////////////////////////////////////////////////////////////////////////////////
5399/// Used for automatic sizing of the cache.
5400///
5401/// Estimates a suitable size for the tree cache based on AutoFlush.
5402/// A cache sizing factor is taken from the configuration. If this yields zero
5403/// and withDefault is true the historical algorithm for default size is used.
5405Long64_t TTree::GetCacheAutoSize(Bool_t withDefault /* = kFALSE */ )
5406{
5407 auto calculateCacheSize = [this](Double_t cacheFactor)
5408 {
5409 Long64_t cacheSize = 0;
5410 if (fAutoFlush < 0) {
5411 cacheSize = Long64_t(-cacheFactor * fAutoFlush);
5412 } else if (fAutoFlush == 0) {
5413 const auto medianClusterSize = GetMedianClusterSize();
5414 if (medianClusterSize > 0)
5415 cacheSize = Long64_t(cacheFactor * 1.5 * medianClusterSize * GetZipBytes() / (fEntries + 1));
5416 else
5417 cacheSize = Long64_t(cacheFactor * 1.5 * 30000000); // use the default value of fAutoFlush
5418 } else {
5419 cacheSize = Long64_t(cacheFactor * 1.5 * fAutoFlush * GetZipBytes() / (fEntries + 1));
5420 }
5421 if (cacheSize >= (INT_MAX / 4)) {
5422 cacheSize = INT_MAX / 4;
5423 }
5424 return cacheSize;
5425 };
5426
5427 const char *stcs;
5428 Double_t cacheFactor = 0.0;
5429 if (!(stcs = gSystem->Getenv("ROOT_TTREECACHE_SIZE")) || !*stcs) {
5430 cacheFactor = gEnv->GetValue("TTreeCache.Size", 1.0);
5431 } else {
5432 cacheFactor = TString(stcs).Atof();
5433 }
5434
5435 if (cacheFactor < 0.0) {
5436 // ignore negative factors
5437 cacheFactor = 0.0;
5438 }
5439
5440 Long64_t cacheSize = calculateCacheSize(cacheFactor);
5441
5442 if (cacheSize < 0) {
5443 cacheSize = 0;
5444 }
5445
5446 if (cacheSize == 0 && withDefault) {
5447 cacheSize = calculateCacheSize(1.0);
5448 }
5449
5450 return cacheSize;
5451}
5452
5453////////////////////////////////////////////////////////////////////////////////
5454/// Return an iterator over the cluster of baskets starting at firstentry.
5455///
5456/// This iterator is not yet supported for TChain object.
5457/// ~~~ {.cpp}
5458/// TTree::TClusterIterator clusterIter = tree->GetClusterIterator(entry);
5459/// Long64_t clusterStart;
5460/// while( (clusterStart = clusterIter()) < tree->GetEntries() ) {
5461/// printf("The cluster starts at %lld and ends at %lld (inclusive)\n",clusterStart,clusterIter.GetNextEntry()-1);
5462/// }
5463/// ~~~
5466{
5467 // create cache if wanted
5468 if (fCacheDoAutoInit)
5470
5471 return TClusterIterator(this,firstentry);
5472}
5473
5474////////////////////////////////////////////////////////////////////////////////
5475/// Return pointer to the current file.
5478{
5479 if (!fDirectory || fDirectory==gROOT) {
5480 return 0;
5481 }
5482 return fDirectory->GetFile();
5483}
5484
5485////////////////////////////////////////////////////////////////////////////////
5486/// Return the number of entries matching the selection.
5487/// Return -1 in case of errors.
5488///
5489/// If the selection uses any arrays or containers, we return the number
5490/// of entries where at least one element match the selection.
5491/// GetEntries is implemented using the selector class TSelectorEntries,
5492/// which can be used directly (see code in TTreePlayer::GetEntries) for
5493/// additional option.
5494/// If SetEventList was used on the TTree or TChain, only that subset
5495/// of entries will be considered.
5497Long64_t TTree::GetEntries(const char *selection)
5498{
5499 GetPlayer();
5500 if (fPlayer) {
5501 return fPlayer->GetEntries(selection);
5502 }
5503 return -1;
5504}
5505
5506////////////////////////////////////////////////////////////////////////////////
5507/// Return pointer to the 1st Leaf named name in any Branch of this Tree or
5508/// any branch in the list of friend trees.
5511{
5512 if (fEntries) return fEntries;
5513 if (!fFriends) return 0;
5515 if (!fr) return 0;
5516 TTree *t = fr->GetTree();
5517 if (t==0) return 0;
5518 return t->GetEntriesFriend();
5519}
5520
5521////////////////////////////////////////////////////////////////////////////////
5522/// Read all branches of entry and return total number of bytes read.
5523///
5524/// - `getall = 0` : get only active branches
5525/// - `getall = 1` : get all branches
5526///
5527/// The function returns the number of bytes read from the input buffer.
5528/// If entry does not exist the function returns 0.
5529/// If an I/O error occurs, the function returns -1.
5530///
5531/// If the Tree has friends, also read the friends entry.
5532///
5533/// To activate/deactivate one or more branches, use TBranch::SetBranchStatus
5534/// For example, if you have a Tree with several hundred branches, and you
5535/// are interested only by branches named "a" and "b", do
5536/// ~~~ {.cpp}
5537/// mytree.SetBranchStatus("*",0); //disable all branches
5538/// mytree.SetBranchStatus("a",1);
5539/// mytree.SetBranchStatus("b",1);
5540/// ~~~
5541/// when calling mytree.GetEntry(i); only branches "a" and "b" will be read.
5542///
5543/// __WARNING!!__
5544/// If your Tree has been created in split mode with a parent branch "parent.",
5545/// ~~~ {.cpp}
5546/// mytree.SetBranchStatus("parent",1);
5547/// ~~~
5548/// will not activate the sub-branches of "parent". You should do:
5549/// ~~~ {.cpp}
5550/// mytree.SetBranchStatus("parent*",1);
5551/// ~~~
5552/// Without the trailing dot in the branch creation you have no choice but to
5553/// call SetBranchStatus explicitly for each of the sub branches.
5554///
5555/// An alternative is to call directly
5556/// ~~~ {.cpp}
5557/// brancha.GetEntry(i)
5558/// branchb.GetEntry(i);
5559/// ~~~
5560/// ## IMPORTANT NOTE
5561///
5562/// By default, GetEntry reuses the space allocated by the previous object
5563/// for each branch. You can force the previous object to be automatically
5564/// deleted if you call mybranch.SetAutoDelete(kTRUE) (default is kFALSE).
5565///
5566/// Example:
5567///
5568/// Consider the example in $ROOTSYS/test/Event.h
5569/// The top level branch in the tree T is declared with:
5570/// ~~~ {.cpp}
5571/// Event *event = 0; //event must be null or point to a valid object
5572/// //it must be initialized
5573/// T.SetBranchAddress("event",&event);
5574/// ~~~
5575/// When reading the Tree, one can choose one of these 3 options:
5576///
5577/// ## OPTION 1
5578///
5579/// ~~~ {.cpp}
5580/// for (Long64_t i=0;i<nentries;i++) {
5581/// T.GetEntry(i);
5582/// // the object event has been filled at this point
5583/// }
5584/// ~~~
5585/// The default (recommended). At the first entry an object of the class
5586/// Event will be created and pointed by event. At the following entries,
5587/// event will be overwritten by the new data. All internal members that are
5588/// TObject* are automatically deleted. It is important that these members
5589/// be in a valid state when GetEntry is called. Pointers must be correctly
5590/// initialized. However these internal members will not be deleted if the
5591/// characters "->" are specified as the first characters in the comment
5592/// field of the data member declaration.
5593///
5594/// If "->" is specified, the pointer member is read via pointer->Streamer(buf).
5595/// In this case, it is assumed that the pointer is never null (case of
5596/// pointer TClonesArray *fTracks in the Event example). If "->" is not
5597/// specified, the pointer member is read via buf >> pointer. In this case
5598/// the pointer may be null. Note that the option with "->" is faster to
5599/// read or write and it also consumes less space in the file.
5600///
5601/// ## OPTION 2
5602///
5603/// The option AutoDelete is set
5604/// ~~~ {.cpp}
5605/// TBranch *branch = T.GetBranch("event");
5606/// branch->SetAddress(&event);
5607/// branch->SetAutoDelete(kTRUE);
5608/// for (Long64_t i=0;i<nentries;i++) {
5609/// T.GetEntry(i);
5610/// // the object event has been filled at this point
5611/// }
5612/// ~~~
5613/// In this case, at each iteration, the object event is deleted by GetEntry
5614/// and a new instance of Event is created and filled.
5615///
5616/// ## OPTION 3
5617///
5618/// ~~~ {.cpp}
5619/// Same as option 1, but you delete yourself the event.
5620///
5621/// for (Long64_t i=0;i<nentries;i++) {
5622/// delete event;
5623/// event = 0; // EXTREMELY IMPORTANT
5624/// T.GetEntry(i);
5625/// // the object event has been filled at this point
5626/// }
5627/// ~~~
5628/// It is strongly recommended to use the default option 1. It has the
5629/// additional advantage that functions like TTree::Draw (internally calling
5630/// TTree::GetEntry) will be functional even when the classes in the file are
5631/// not available.
5632///
5633/// Note: See the comments in TBranchElement::SetAddress() for the
5634/// object ownership policy of the underlying (user) data.
5636Int_t TTree::GetEntry(Long64_t entry, Int_t getall)
5637{
5638 // We already have been visited while recursively looking
5639 // through the friends tree, let return
5640 if (kGetEntry & fFriendLockStatus) return 0;
5641
5642 if (entry < 0 || entry >= fEntries) return 0;
5643 Int_t i;
5644 Int_t nbytes = 0;
5645 fReadEntry = entry;
5646
5647 // create cache if wanted
5648 if (fCacheDoAutoInit)
5650
5651 Int_t nbranches = fBranches.GetEntriesUnsafe();
5652 Int_t nb=0;
5653
5654 auto seqprocessing = [&]() {
5655 TBranch *branch;
5656 for (i=0;i<nbranches;i++) {
5657 branch = (TBranch*)fBranches.UncheckedAt(i);
5658 nb = branch->GetEntry(entry, getall);
5659 if (nb < 0) break;
5660 nbytes += nb;
5661 }
5662 };
5663
5664#ifdef R__USE_IMT
5666 if (fSortedBranches.empty())
5668
5669 // Count branches are processed first and sequentially
5670 for (auto branch : fSeqBranches) {
5671 nb = branch->GetEntry(entry, getall);
5672 if (nb < 0) break;
5673 nbytes += nb;
5674 }
5675 if (nb < 0) return nb;
5676
5677 // Enable this IMT use case (activate its locks)
5679
5680 Int_t errnb = 0;
5681 std::atomic<Int_t> pos(0);
5682 std::atomic<Int_t> nbpar(0);
5683
5684 auto mapFunction = [&]() {
5685 // The branch to process is obtained when the task starts to run.
5686 // This way, since branches are sorted, we make sure that branches
5687 // leading to big tasks are processed first. If we assigned the
5688 // branch at task creation time, the scheduler would not necessarily
5689 // respect our sorting.
5690 Int_t j = pos.fetch_add(1);
5691
5692 Int_t nbtask = 0;
5693 auto branch = fSortedBranches[j].second;
5694
5695 if (gDebug > 0) {
5696 std::stringstream ss;
5697 ss << std::this_thread::get_id();
5698 Info("GetEntry", "[IMT] Thread %s", ss.str().c_str());
5699 Info("GetEntry", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
5700 }
5701
5702 std::chrono::time_point<std::chrono::system_clock> start, end;
5703
5704 start = std::chrono::system_clock::now();
5705 nbtask = branch->GetEntry(entry, getall);
5706 end = std::chrono::system_clock::now();
5707
5708 Long64_t tasktime = (Long64_t)std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
5709 fSortedBranches[j].first += tasktime;
5710
5711 if (nbtask < 0) errnb = nbtask;
5712 else nbpar += nbtask;
5713 };
5714
5716 pool.Foreach(mapFunction, fSortedBranches.size());
5717
5718 if (errnb < 0) {
5719 nb = errnb;
5720 }
5721 else {
5722 // Save the number of bytes read by the tasks
5723 nbytes += nbpar;
5724
5725 // Re-sort branches if necessary
5729 }
5730 }
5731 }
5732 else {
5733 seqprocessing();
5734 }
5735#else
5736 seqprocessing();
5737#endif
5738 if (nb < 0) return nb;
5739
5740 // GetEntry in list of friends
5741 if (!fFriends) return nbytes;
5742 TFriendLock lock(this,kGetEntry);
5743 TIter nextf(fFriends);
5744 TFriendElement *fe;
5745 while ((fe = (TFriendElement*)nextf())) {
5746 TTree *t = fe->GetTree();
5747 if (t) {
5749 nb = t->GetEntry(t->GetReadEntry(),getall);
5750 } else {
5751 if ( t->LoadTreeFriend(entry,this) >= 0 ) {
5752 nb = t->GetEntry(t->GetReadEntry(),getall);
5753 } else nb = 0;
5754 }
5755 if (nb < 0) return nb;
5756 nbytes += nb;
5757 }
5758 }
5759 return nbytes;
5760}
5761
5762
5763////////////////////////////////////////////////////////////////////////////////
5764/// Divides the top-level branches into two vectors: (i) branches to be
5765/// processed sequentially and (ii) branches to be processed in parallel.
5766/// Even if IMT is on, some branches might need to be processed first and in a
5767/// sequential fashion: in the parallelization of GetEntry, those are the
5768/// branches that store the size of another branch for every entry
5769/// (e.g. the size of an array branch). If such branches were processed
5770/// in parallel with the rest, there could be two threads invoking
5771/// TBranch::GetEntry on one of them at the same time, since a branch that
5772/// depends on a size (or count) branch will also invoke GetEntry on the latter.
5773/// This method can be invoked several times during the event loop if the TTree
5774/// is being written, for example when adding new branches. In these cases, the
5775/// `checkLeafCount` parameter is false.
5776/// \param[in] checkLeafCount True if we need to check whether some branches are
5777/// count leaves.
5779void TTree::InitializeBranchLists(bool checkLeafCount)
5780{
5781 Int_t nbranches = fBranches.GetEntriesFast();
5782
5783 // The special branch fBranchRef needs to be processed sequentially:
5784 // we add it once only.
5785 if (fBranchRef && fBranchRef != fSeqBranches[0]) {
5786 fSeqBranches.push_back(fBranchRef);
5787 }
5788
5789 // The branches to be processed sequentially are those that are the leaf count of another branch
5790 if (checkLeafCount) {
5791 for (Int_t i = 0; i < nbranches; i++) {
5792 TBranch* branch = (TBranch*)fBranches.UncheckedAt(i);
5793 auto leafCount = ((TLeaf*)branch->GetListOfLeaves()->At(0))->GetLeafCount();
5794 if (leafCount) {
5795 auto countBranch = leafCount->GetBranch();
5796 if (std::find(fSeqBranches.begin(), fSeqBranches.end(), countBranch) == fSeqBranches.end()) {
5797 fSeqBranches.push_back(countBranch);
5798 }
5799 }
5800 }
5801 }
5802
5803 // Any branch that is not a leaf count can be safely processed in parallel when reading
5804 // We need to reset the vector to make sure we do not re-add several times the same branch.
5805 if (!checkLeafCount) {
5806 fSortedBranches.clear();
5807 }
5808 for (Int_t i = 0; i < nbranches; i++) {
5809 Long64_t bbytes = 0;
5810 TBranch* branch = (TBranch*)fBranches.UncheckedAt(i);
5811 if (std::find(fSeqBranches.begin(), fSeqBranches.end(), branch) == fSeqBranches.end()) {
5812 bbytes = branch->GetTotBytes("*");
5813 fSortedBranches.emplace_back(bbytes, branch);
5814 }
5815 }
5816
5817 // Initially sort parallel branches by size
5818 std::sort(fSortedBranches.begin(),
5819 fSortedBranches.end(),
5820 [](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
5821 return a.first > b.first;
5822 });
5823
5824 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5825 fSortedBranches[i].first = 0LL;
5826 }
5827}
5828
5829////////////////////////////////////////////////////////////////////////////////
5830/// Sorts top-level branches by the last average task time recorded per branch.
5833{
5834 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5836 }
5837
5838 std::sort(fSortedBranches.begin(),
5839 fSortedBranches.end(),
5840 [](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
5841 return a.first > b.first;
5842 });
5843
5844 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5845 fSortedBranches[i].first = 0LL;
5846 }
5847}
5848
5849////////////////////////////////////////////////////////////////////////////////
5850///Returns the entry list assigned to this tree
5853{
5854 return fEntryList;
5855}
5856
5857////////////////////////////////////////////////////////////////////////////////
5858/// Return entry number corresponding to entry.
5859///
5860/// if no TEntryList set returns entry
5861/// else returns the entry number corresponding to the list index=entry
5864{
5865 if (!fEntryList) {
5866 return entry;
5867 }
5868
5869 return fEntryList->GetEntry(entry);
5870}
5871
5872////////////////////////////////////////////////////////////////////////////////
5873/// Return entry number corresponding to major and minor number.
5874/// Note that this function returns only the entry number, not the data
5875/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
5876/// the BuildIndex function has created a table of Long64_t* of sorted values
5877/// corresponding to val = major<<31 + minor;
5878/// The function performs binary search in this sorted table.
5879/// If it finds a pair that matches val, it returns directly the
5880/// index in the table.
5881/// If an entry corresponding to major and minor is not found, the function
5882/// returns the index of the major,minor pair immediately lower than the
5883/// requested value, ie it will return -1 if the pair is lower than
5884/// the first entry in the index.
5885///
5886/// See also GetEntryNumberWithIndex
5889{
5890 if (!fTreeIndex) {
5891 return -1;
5892 }
5893 return fTreeIndex->GetEntryNumberWithBestIndex(major, minor);
5894}
5895
5896////////////////////////////////////////////////////////////////////////////////
5897/// Return entry number corresponding to major and minor number.
5898/// Note that this function returns only the entry number, not the data
5899/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
5900/// the BuildIndex function has created a table of Long64_t* of sorted values
5901/// corresponding to val = major<<31 + minor;
5902/// The function performs binary search in this sorted table.
5903/// If it finds a pair that matches val, it returns directly the
5904/// index in the table, otherwise it returns -1.
5905///
5906/// See also GetEntryNumberWithBestIndex
5909{
5910 if (!fTreeIndex) {
5911 return -1;
5912 }
5913 return fTreeIndex->GetEntryNumberWithIndex(major, minor);
5914}
5915
5916////////////////////////////////////////////////////////////////////////////////
5917/// Read entry corresponding to major and minor number.
5918///
5919/// The function returns the total number of bytes read.
5920/// If the Tree has friend trees, the corresponding entry with
5921/// the index values (major,minor) is read. Note that the master Tree
5922/// and its friend may have different entry serial numbers corresponding
5923/// to (major,minor).
5926{
5927 // We already have been visited while recursively looking
5928 // through the friends tree, let's return.
5930 return 0;
5931 }
5932 Long64_t serial = GetEntryNumberWithIndex(major, minor);
5933 if (serial < 0) {
5934 return -1;
5935 }
5936 // create cache if wanted
5937 if (fCacheDoAutoInit)
5939
5940 Int_t i;
5941 Int_t nbytes = 0;
5942 fReadEntry = serial;
5943 TBranch *branch;
5944 Int_t nbranches = fBranches.GetEntriesFast();
5945 Int_t nb;
5946 for (i = 0; i < nbranches; ++i) {
5947 branch = (TBranch*)fBranches.UncheckedAt(i);
5948 nb = branch->GetEntry(serial);
5949 if (nb < 0) return nb;
5950 nbytes += nb;
5951 }
5952 // GetEntry in list of friends
5953 if (!fFriends) return nbytes;
5955 TIter nextf(fFriends);
5956 TFriendElement* fe = 0;
5957 while ((fe = (TFriendElement*) nextf())) {
5958 TTree *t = fe->GetTree();
5959 if (t) {
5960 serial = t->GetEntryNumberWithIndex(major,minor);
5961 if (serial <0) return -nbytes;
5962 nb = t->GetEntry(serial);
5963 if (nb < 0) return nb;
5964 nbytes += nb;
5965 }
5966 }
5967 return nbytes;
5968}
5969
5970////////////////////////////////////////////////////////////////////////////////
5971/// Return a pointer to the TTree friend whose name or alias is `friendname`.
5973TTree* TTree::GetFriend(const char *friendname) const
5974{
5975
5976 // We already have been visited while recursively
5977 // looking through the friends tree, let's return.
5979 return 0;
5980 }
5981 if (!fFriends) {
5982 return 0;
5983 }
5984 TFriendLock lock(const_cast<TTree*>(this), kGetFriend);
5985 TIter nextf(fFriends);
5986 TFriendElement* fe = 0;
5987 while ((fe = (TFriendElement*) nextf())) {
5988 if (strcmp(friendname,fe->GetName())==0
5989 || strcmp(friendname,fe->GetTreeName())==0) {
5990 return fe->GetTree();
5991 }
5992 }
5993 // After looking at the first level,
5994 // let's see if it is a friend of friends.
5995 nextf.Reset();
5996 fe = 0;
5997 while ((fe = (TFriendElement*) nextf())) {
5998 TTree *res = fe->GetTree()->GetFriend(friendname);
5999 if (res) {
6000 return res;
6001 }
6002 }
6003 return 0;
6004}
6005
6006////////////////////////////////////////////////////////////////////////////////
6007/// If the 'tree' is a friend, this method returns its alias name.
6008///
6009/// This alias is an alternate name for the tree.
6010///
6011/// It can be used in conjunction with a branch or leaf name in a TTreeFormula,
6012/// to specify in which particular tree the branch or leaf can be found if
6013/// the friend trees have branches or leaves with the same name as the master
6014/// tree.
6015///
6016/// It can also be used in conjunction with an alias created using
6017/// TTree::SetAlias in a TTreeFormula, e.g.:
6018/// ~~~ {.cpp}
6019/// maintree->Draw("treealias.fPx - treealias.myAlias");
6020/// ~~~
6021/// where fPx is a branch of the friend tree aliased as 'treealias' and 'myAlias'
6022/// was created using TTree::SetAlias on the friend tree.
6023///
6024/// However, note that 'treealias.myAlias' will be expanded literally,
6025/// without remembering that it comes from the aliased friend and thus
6026/// the branch name might not be disambiguated properly, which means
6027/// that you may not be able to take advantage of this feature.
6028///
6030const char* TTree::GetFriendAlias(TTree* tree) const
6031{
6032 if ((tree == this) || (tree == GetTree())) {
6033 return 0;
6034 }
6035
6036 // We already have been visited while recursively
6037 // looking through the friends tree, let's return.
6039 return 0;
6040 }
6041 if (!fFriends) {
6042 return 0;
6043 }
6044 TFriendLock lock(const_cast<TTree*>(this), kGetFriendAlias);
6045 TIter nextf(fFriends);
6046 TFriendElement* fe = 0;
6047 while ((fe = (TFriendElement*) nextf())) {
6048 TTree* t = fe->GetTree();
6049 if (t == tree) {
6050 return fe->GetName();
6051 }
6052 // Case of a chain:
6053 if (t && t->GetTree() == tree) {
6054 return fe->GetName();
6055 }
6056 }
6057 // After looking at the first level,
6058 // let's see if it is a friend of friends.
6059 nextf.Reset();
6060 fe = 0;
6061 while ((fe = (TFriendElement*) nextf())) {
6062 const char* res = fe->GetTree()->GetFriendAlias(tree);
6063 if (res) {
6064 return res;
6065 }
6066 }
6067 return 0;
6068}
6069
6070////////////////////////////////////////////////////////////////////////////////
6071/// Returns the current set of IO settings
6073{
6074 return fIOFeatures;
6075}
6076
6077////////////////////////////////////////////////////////////////////////////////
6078/// Creates a new iterator that will go through all the leaves on the tree itself and its friend.
6081{
6082 return new TTreeFriendLeafIter(this, dir);
6083}
6084
6085////////////////////////////////////////////////////////////////////////////////
6086/// Return pointer to the 1st Leaf named name in any Branch of this
6087/// Tree or any branch in the list of friend trees.
6088///
6089/// The leaf name can contain the name of a friend tree with the
6090/// syntax: friend_dir_and_tree.full_leaf_name
6091/// the friend_dir_and_tree can be of the form:
6092/// ~~~ {.cpp}
6093/// TDirectoryName/TreeName
6094/// ~~~
6096TLeaf* TTree::GetLeafImpl(const char* branchname, const char *leafname)
6097{
6098 TLeaf *leaf = nullptr;
6099 if (branchname) {
6100 TBranch *branch = FindBranch(branchname);
6101 if (branch) {
6102 leaf = branch->GetLeaf(leafname);
6103 if (leaf) {
6104 return leaf;
6105 }
6106 }
6107 }
6108 TIter nextl(GetListOfLeaves());
6109 while ((leaf = (TLeaf*)nextl())) {
6110 if (strcmp(leaf->GetFullName(), leafname) != 0 && strcmp(leaf->GetName(), leafname) != 0)
6111 continue; // leafname does not match GetName() nor GetFullName(), this is not the right leaf
6112 if (branchname) {
6113 // check the branchname is also a match
6114 TBranch *br = leaf->GetBranch();
6115 // if a quick comparison with the branch full name is a match, we are done
6116 if (!strcmp(br->GetFullName(), branchname))
6117 return leaf;
6118 UInt_t nbch = strlen(branchname);
6119 const char* brname = br->GetName();
6120 TBranch *mother = br->GetMother();
6121 if (strncmp(brname,branchname,nbch)) {
6122 if (mother != br) {
6123 const char *mothername = mother->GetName();
6124 UInt_t motherlen = strlen(mothername);
6125 if (!strcmp(mothername, branchname)) {
6126 return leaf;
6127 } else if (nbch > motherlen && strncmp(mothername,branchname,motherlen)==0 && (mothername[motherlen-1]=='.' || branchname[motherlen]=='.')) {
6128 // 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.
6129 if (strncmp(brname,branchname+motherlen+1,nbch-motherlen-1)) {
6130 // No it does not
6131 continue;
6132 } // else we have match so we can proceed.
6133 } else {
6134 // no match
6135 continue;
6136 }
6137 } else {
6138 continue;
6139 }
6140 }
6141 // The start of the branch name is identical to the content
6142 // of 'aname' before the first '/'.
6143 // Let's make sure that it is not longer (we are trying
6144 // to avoid having jet2/value match the branch jet23
6145 if ((strlen(brname) > nbch) && (brname[nbch] != '.') && (brname[nbch] != '[')) {
6146 continue;
6147 }
6148 }
6149 return leaf;
6150 }
6151 if (!fFriends) return nullptr;
6152 TFriendLock lock(this,kGetLeaf);
6153 TIter next(fFriends);
6154 TFriendElement *fe;
6155 while ((fe = (TFriendElement*)next())) {
6156 TTree *t = fe->GetTree();
6157 if (t) {
6158 leaf = t->GetLeaf(branchname, leafname);
6159 if (leaf) return leaf;
6160 }
6161 }
6162
6163 //second pass in the list of friends when the leaf name
6164 //is prefixed by the tree name
6165 TString strippedArg;
6166 next.Reset();
6167 while ((fe = (TFriendElement*)next())) {
6168 TTree *t = fe->GetTree();
6169 if (!t) continue;
6170 const char *subname = strstr(leafname,fe->GetName());
6171 if (subname != leafname) continue;
6172 Int_t l = strlen(fe->GetName());
6173 subname += l;
6174 if (*subname != '.') continue;
6175 subname++;
6176 strippedArg += subname;
6177 leaf = t->GetLeaf(branchname,subname);
6178 if (leaf) return leaf;
6179 }
6180 return nullptr;
6181}
6182
6183////////////////////////////////////////////////////////////////////////////////
6184/// Return pointer to the 1st Leaf named name in any Branch of this
6185/// Tree or any branch in the list of friend trees.
6186///
6187/// The leaf name can contain the name of a friend tree with the
6188/// syntax: friend_dir_and_tree.full_leaf_name
6189/// the friend_dir_and_tree can be of the form:
6190///
6191/// TDirectoryName/TreeName
6193TLeaf* TTree::GetLeaf(const char* branchname, const char *leafname)
6194{
6195 if (leafname == 0) return 0;
6196
6197 // We already have been visited while recursively looking
6198 // through the friends tree, let return
6200 return 0;
6201 }
6202
6203 return GetLeafImpl(branchname,leafname);
6204}
6205
6206////////////////////////////////////////////////////////////////////////////////
6207/// Return pointer to first leaf named "name" in any branch of this
6208/// tree or its friend trees.
6209///
6210/// \param[in] name may be in the form 'branch/leaf'
6211///
6213TLeaf* TTree::GetLeaf(const char *name)
6214{
6215 // Return nullptr if name is invalid or if we have
6216 // already been visited while searching friend trees
6217 if (!name || (kGetLeaf & fFriendLockStatus))
6218 return nullptr;
6219
6220 std::string path(name);
6221 const auto sep = path.find_last_of("/");
6222 if (sep != std::string::npos)
6223 return GetLeafImpl(path.substr(0, sep).c_str(), name+sep+1);
6224
6225 return GetLeafImpl(nullptr, name);
6226}
6227
6228////////////////////////////////////////////////////////////////////////////////
6229/// Return maximum of column with name columname.
6230/// if the Tree has an associated TEventList or TEntryList, the maximum
6231/// is computed for the entries in this list.
6233Double_t TTree::GetMaximum(const char* columname)
6234{
6235 TLeaf* leaf = this->GetLeaf(columname);
6236 if (!leaf) {
6237 return 0;
6238 }
6239
6240 // create cache if wanted
6241 if (fCacheDoAutoInit)
6243
6244 TBranch* branch = leaf->GetBranch();
6245 Double_t cmax = -DBL_MAX;
6246 for (Long64_t i = 0; i < fEntries; ++i) {
6247 Long64_t entryNumber = this->GetEntryNumber(i);
6248 if (entryNumber < 0) break;
6249 branch->GetEntry(entryNumber);
6250 for (Int_t j = 0; j < leaf->GetLen(); ++j) {
6251 Double_t val = leaf->GetValue(j);
6252 if (val > cmax) {
6253 cmax = val;
6254 }
6255 }
6256 }
6257 return cmax;
6258}
6259
6260////////////////////////////////////////////////////////////////////////////////
6261/// Static function which returns the tree file size limit in bytes.
6264{
6265 return fgMaxTreeSize;
6266}
6267
6268////////////////////////////////////////////////////////////////////////////////
6269/// Return minimum of column with name columname.
6270/// if the Tree has an associated TEventList or TEntryList, the minimum
6271/// is computed for the entries in this list.
6273Double_t TTree::GetMinimum(const char* columname)
6274{
6275 TLeaf* leaf = this->GetLeaf(columname);
6276 if (!leaf) {
6277 return 0;
6278 }
6279
6280 // create cache if wanted
6281 if (fCacheDoAutoInit)
6283
6284 TBranch* branch = leaf->GetBranch();
6285 Double_t cmin = DBL_MAX;
6286 for (Long64_t i = 0; i < fEntries; ++i) {
6287 Long64_t entryNumber = this->GetEntryNumber(i);
6288 if (entryNumber < 0) break;
6289 branch->GetEntry(entryNumber);
6290 for (Int_t j = 0;j < leaf->GetLen(); ++j) {
6291 Double_t val = leaf->GetValue(j);
6292 if (val < cmin) {
6293 cmin = val;
6294 }
6295 }
6296 }
6297 return cmin;
6298}
6299
6300////////////////////////////////////////////////////////////////////////////////
6301/// Load the TTreePlayer (if not already done).
6304{
6305 if (fPlayer) {
6306 return fPlayer;
6307 }
6309 return fPlayer;
6310}
6311
6312////////////////////////////////////////////////////////////////////////////////
6313/// Find and return the TTreeCache registered with the file and which may
6314/// contain branches for us.
6317{
6318 TTreeCache *pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(GetTree()));
6319 if (pe && pe->GetTree() != GetTree())
6320 pe = nullptr;
6321 return pe;
6322}
6323
6324////////////////////////////////////////////////////////////////////////////////
6325/// Find and return the TTreeCache registered with the file and which may
6326/// contain branches for us. If create is true and there is no cache
6327/// a new cache is created with default size.
6330{
6332 if (create && !pe) {
6333 if (fCacheDoAutoInit)
6335 pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(GetTree()));
6336 if (pe && pe->GetTree() != GetTree()) pe = 0;
6337 }
6338 return pe;
6339}
6340
6341////////////////////////////////////////////////////////////////////////////////
6342/// Return a pointer to the list containing user objects associated to this tree.
6343///
6344/// The list is automatically created if it does not exist.
6345///
6346/// WARNING: By default the TTree destructor will delete all objects added
6347/// to this list. If you do not want these objects to be deleted,
6348/// call:
6349///
6350/// mytree->GetUserInfo()->Clear();
6351///
6352/// before deleting the tree.
6355{
6356 if (!fUserInfo) {
6357 fUserInfo = new TList();
6358 fUserInfo->SetName("UserInfo");
6359 }
6360 return fUserInfo;
6361}
6362
6363////////////////////////////////////////////////////////////////////////////////
6364/// Appends the cluster range information stored in 'fromtree' to this tree,
6365/// including the value of fAutoFlush.
6366///
6367/// This is used when doing a fast cloning (by TTreeCloner).
6368/// See also fAutoFlush and fAutoSave if needed.
6370void TTree::ImportClusterRanges(TTree *fromtree)
6371{
6372 Long64_t autoflush = fromtree->GetAutoFlush();
6373 if (fromtree->fNClusterRange == 0 && fromtree->fAutoFlush == fAutoFlush) {
6374 // nothing to do
6375 } else if (fNClusterRange || fromtree->fNClusterRange) {
6376 Int_t newsize = fNClusterRange + 1 + fromtree->fNClusterRange;
6377 if (newsize > fMaxClusterRange) {
6378 if (fMaxClusterRange) {
6380 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
6382 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
6383 fMaxClusterRange = newsize;
6384 } else {
6385 fMaxClusterRange = newsize;
6388 }
6389 }
6390 if (fEntries) {
6394 }
6395 for (Int_t i = 0 ; i < fromtree->fNClusterRange; ++i) {
6399 }
6400 fAutoFlush = autoflush;
6401 } else {
6402 SetAutoFlush( autoflush );
6403 }
6404 Long64_t autosave = GetAutoSave();
6405 if (autoflush > 0 && autosave > 0) {
6406 SetAutoSave( autoflush*(autosave/autoflush) );
6407 }
6408}
6409
6410////////////////////////////////////////////////////////////////////////////////
6411/// Keep a maximum of fMaxEntries in memory.
6414{
6416 Long64_t maxEntries = fMaxEntries - (fMaxEntries / 10);
6417 for (Int_t i = 0; i < nb; ++i) {
6418 TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
6419 branch->KeepCircular(maxEntries);
6420 }
6421 if (fNClusterRange) {
6422 Long64_t entriesOffset = fEntries - maxEntries;
6423 Int_t oldsize = fNClusterRange;
6424 for(Int_t i = 0, j = 0; j < oldsize; ++j) {
6425 if (fClusterRangeEnd[j] > entriesOffset) {
6426 fClusterRangeEnd[i] = fClusterRangeEnd[j] - entriesOffset;
6427 ++i;
6428 } else {
6430 }
6431 }
6432 }
6433 fEntries = maxEntries;
6434 fReadEntry = -1;
6435}
6436
6437////////////////////////////////////////////////////////////////////////////////
6438/// Read in memory all baskets from all branches up to the limit of maxmemory bytes.
6439///
6440/// If maxmemory is non null and positive SetMaxVirtualSize is called
6441/// with this value. Default for maxmemory is 2000000000 (2 Gigabytes).
6442/// The function returns the total number of baskets read into memory
6443/// if negative an error occurred while loading the branches.
6444/// This method may be called to force branch baskets in memory
6445/// when random access to branch entries is required.
6446/// If random access to only a few branches is required, you should
6447/// call directly TBranch::LoadBaskets.
6450{
6451 if (maxmemory > 0) SetMaxVirtualSize(maxmemory);
6452
6453 TIter next(GetListOfLeaves());
6454 TLeaf *leaf;
6455 Int_t nimported = 0;
6456 while ((leaf=(TLeaf*)next())) {
6457 nimported += leaf->GetBranch()->LoadBaskets();//break;
6458 }
6459 return nimported;
6460}
6461
6462////////////////////////////////////////////////////////////////////////////////
6463/// Set current entry.
6464///
6465/// Returns -2 if entry does not exist (just as TChain::LoadTree()).
6466/// Returns -6 if an error occurs in the notification callback (just as TChain::LoadTree()).
6467///
6468/// Calls fNotify->Notify() (if fNotify is not null) when starting the processing of a new tree.
6469///
6470/// \note This function is overloaded in TChain.
6472{
6473 // We have already been visited while recursively looking
6474 // through the friend trees, let's return
6476 // We need to return a negative value to avoid a circular list of friends
6477 // to think that there is always an entry somewhere in the list.
6478 return -1;
6479 }
6480
6481 // create cache if wanted
6482 if (fCacheDoAutoInit && entry >=0)
6484
6485 if (fNotify) {
6486 if (fReadEntry < 0) {
6487 fNotify->Notify();
6488 }
6489 }
6490 fReadEntry = entry;
6491
6492 Bool_t friendHasEntry = kFALSE;
6493 if (fFriends) {
6494 // Set current entry in friends as well.
6495 //
6496 // An alternative would move this code to each of the
6497 // functions calling LoadTree (and to overload a few more).
6498 Bool_t needUpdate = kFALSE;
6499 {
6500 // This scope is need to insure the lock is released at the right time
6501 TIter nextf(fFriends);
6502 TFriendLock lock(this, kLoadTree);
6503 TFriendElement* fe = 0;
6504 while ((fe = (TFriendElement*) nextf())) {
6506 // This friend element was added by the chain that owns this
6507 // tree, the chain will deal with loading the correct entry.
6508 continue;
6509 }
6510 TTree* friendTree = fe->GetTree();
6511 if (friendTree) {
6512 if (friendTree->LoadTreeFriend(entry, this) >= 0) {
6513 friendHasEntry = kTRUE;
6514 }
6515 }
6516 if (fe->IsUpdated()) {
6517 needUpdate = kTRUE;
6518 fe->ResetUpdated();
6519 }
6520 } // for each friend
6521 }
6522 if (needUpdate) {
6523 //update list of leaves in all TTreeFormula of the TTreePlayer (if any)
6524 if (fPlayer) {
6526 }
6527 //Notify user if requested
6528 if (fNotify) {
6529 if(!fNotify->Notify()) return -6;
6530 }
6531 }
6532 }
6533
6534 if ((fReadEntry >= fEntries) && !friendHasEntry) {
6535 fReadEntry = -1;
6536 return -2;
6537 }
6538 return fReadEntry;
6539}
6540
6541////////////////////////////////////////////////////////////////////////////////
6542/// Load entry on behalf of our master tree, we may use an index.
6543///
6544/// Called by LoadTree() when the masterTree looks for the entry
6545/// number in a friend tree (us) corresponding to the passed entry
6546/// number in the masterTree.
6547///
6548/// If we have no index, our entry number and the masterTree entry
6549/// number are the same.
6550///
6551/// If we *do* have an index, we must find the (major, minor) value pair
6552/// in masterTree to locate our corresponding entry.
6553///
6555Long64_t TTree::LoadTreeFriend(Long64_t entry, TTree* masterTree)
6556{
6557 if (!fTreeIndex) {
6558 return LoadTree(entry);
6559 }
6560 return LoadTree(fTreeIndex->GetEntryNumberFriend(masterTree));
6561}
6562
6563////////////////////////////////////////////////////////////////////////////////
6564/// Generate a skeleton analysis class for this tree.
6565///
6566/// The following files are produced: classname.h and classname.C.
6567/// If classname is 0, classname will be called "nameoftree".
6568///
6569/// The generated code in classname.h includes the following:
6570///
6571/// - Identification of the original tree and the input file name.
6572/// - Definition of an analysis class (data members and member functions).
6573/// - The following member functions:
6574/// - constructor (by default opening the tree file),
6575/// - GetEntry(Long64_t entry),
6576/// - Init(TTree* tree) to initialize a new TTree,
6577/// - Show(Long64_t entry) to read and dump entry.
6578///
6579/// The generated code in classname.C includes only the main
6580/// analysis function Loop.
6581///
6582/// To use this function:
6583///
6584/// - Open your tree file (eg: TFile f("myfile.root");)
6585/// - T->MakeClass("MyClass");
6586///
6587/// where T is the name of the TTree in file myfile.root,
6588/// and MyClass.h, MyClass.C the name of the files created by this function.
6589/// In a ROOT session, you can do:
6590/// ~~~ {.cpp}
6591/// root > .L MyClass.C
6592/// root > MyClass* t = new MyClass;
6593/// root > t->GetEntry(12); // Fill data members of t with entry number 12.
6594/// root > t->Show(); // Show values of entry 12.
6595/// root > t->Show(16); // Read and show values of entry 16.
6596/// root > t->Loop(); // Loop on all entries.
6597/// ~~~
6598/// NOTE: Do not use the code generated for a single TTree which is part
6599/// of a TChain to process that entire TChain. The maximum dimensions
6600/// calculated for arrays on the basis of a single TTree from the TChain
6601/// might be (will be!) too small when processing all of the TTrees in
6602/// the TChain. You must use myChain.MakeClass() to generate the code,
6603/// not myTree.MakeClass(...).
6605Int_t TTree::MakeClass(const char* classname, Option_t* option)
6606{
6607 GetPlayer();
6608 if (!fPlayer) {
6609 return 0;
6610 }
6611 return fPlayer->MakeClass(classname, option);
6612}
6613
6614////////////////////////////////////////////////////////////////////////////////
6615/// Generate a skeleton function for this tree.
6616///
6617/// The function code is written on filename.
6618/// If filename is 0, filename will be called nameoftree.C
6619///
6620/// The generated code includes the following:
6621/// - Identification of the original Tree and Input file name,
6622/// - Opening the Tree file,
6623/// - Declaration of Tree variables,
6624/// - Setting of branches addresses,
6625/// - A skeleton for the entry loop.
6626///
6627/// To use this function:
6628///
6629/// - Open your Tree file (eg: TFile f("myfile.root");)
6630/// - T->MakeCode("MyAnalysis.C");
6631///
6632/// where T is the name of the TTree in file myfile.root
6633/// and MyAnalysis.C the name of the file created by this function.
6634///
6635/// NOTE: Since the implementation of this function, a new and better
6636/// function TTree::MakeClass() has been developed.
6638Int_t TTree::MakeCode(const char* filename)
6639{
6640 Warning("MakeCode", "MakeCode is obsolete. Use MakeClass or MakeSelector instead");
6641
6642 GetPlayer();
6643 if (!fPlayer) return 0;
6644 return fPlayer->MakeCode(filename);
6645}
6646
6647////////////////////////////////////////////////////////////////////////////////
6648/// Generate a skeleton analysis class for this Tree using TBranchProxy.
6649///
6650/// TBranchProxy is the base of a class hierarchy implementing an
6651/// indirect access to the content of the branches of a TTree.
6652///
6653/// "proxyClassname" is expected to be of the form:
6654/// ~~~ {.cpp}
6655/// [path/]fileprefix
6656/// ~~~
6657/// The skeleton will then be generated in the file:
6658/// ~~~ {.cpp}
6659/// fileprefix.h
6660/// ~~~
6661/// located in the current directory or in 'path/' if it is specified.
6662/// The class generated will be named 'fileprefix'
6663///
6664/// "macrofilename" and optionally "cutfilename" are expected to point
6665/// to source files which will be included by the generated skeleton.
6666/// Method of the same name as the file(minus the extension and path)
6667/// will be called by the generated skeleton's Process method as follow:
6668/// ~~~ {.cpp}
6669/// [if (cutfilename())] htemp->Fill(macrofilename());
6670/// ~~~
6671/// "option" can be used select some of the optional features during
6672/// the code generation. The possible options are:
6673///
6674/// - nohist : indicates that the generated ProcessFill should not fill the histogram.
6675///
6676/// 'maxUnrolling' controls how deep in the class hierarchy does the
6677/// system 'unroll' classes that are not split. Unrolling a class
6678/// allows direct access to its data members (this emulates the behavior
6679/// of TTreeFormula).
6680///
6681/// The main features of this skeleton are:
6682///
6683/// * on-demand loading of branches
6684/// * ability to use the 'branchname' as if it was a data member
6685/// * protection against array out-of-bounds errors
6686/// * ability to use the branch data as an object (when the user code is available)
6687///
6688/// For example with Event.root, if
6689/// ~~~ {.cpp}
6690/// Double_t somePx = fTracks.fPx[2];
6691/// ~~~
6692/// is executed by one of the method of the skeleton,
6693/// somePx will updated with the current value of fPx of the 3rd track.
6694///
6695/// Both macrofilename and the optional cutfilename are expected to be
6696/// the name of source files which contain at least a free standing
6697/// function with the signature:
6698/// ~~~ {.cpp}
6699/// x_t macrofilename(); // i.e function with the same name as the file
6700/// ~~~
6701/// and
6702/// ~~~ {.cpp}
6703/// y_t cutfilename(); // i.e function with the same name as the file
6704/// ~~~
6705/// x_t and y_t needs to be types that can convert respectively to a double
6706/// and a bool (because the skeleton uses:
6707///
6708/// if (cutfilename()) htemp->Fill(macrofilename());
6709///
6710/// These two functions are run in a context such that the branch names are
6711/// available as local variables of the correct (read-only) type.
6712///
6713/// Note that if you use the same 'variable' twice, it is more efficient
6714/// to 'cache' the value. For example:
6715/// ~~~ {.cpp}
6716/// Int_t n = fEventNumber; // Read fEventNumber
6717/// if (n<10 || n>10) { ... }
6718/// ~~~
6719/// is more efficient than
6720/// ~~~ {.cpp}
6721/// if (fEventNumber<10 || fEventNumber>10)
6722/// ~~~
6723/// Also, optionally, the generated selector will also call methods named
6724/// macrofilename_methodname in each of 6 main selector methods if the method
6725/// macrofilename_methodname exist (Where macrofilename is stripped of its
6726/// extension).
6727///
6728/// Concretely, with the script named h1analysisProxy.C,
6729///
6730/// - The method calls the method (if it exist)
6731/// - Begin -> void h1analysisProxy_Begin(TTree*);
6732/// - SlaveBegin -> void h1analysisProxy_SlaveBegin(TTree*);
6733/// - Notify -> Bool_t h1analysisProxy_Notify();
6734/// - Process -> Bool_t h1analysisProxy_Process(Long64_t);
6735/// - SlaveTerminate -> void h1analysisProxy_SlaveTerminate();
6736/// - Terminate -> void h1analysisProxy_Terminate();
6737///
6738/// If a file name macrofilename.h (or .hh, .hpp, .hxx, .hPP, .hXX) exist
6739/// it is included before the declaration of the proxy class. This can
6740/// be used in particular to insure that the include files needed by
6741/// the macro file are properly loaded.
6742///
6743/// The default histogram is accessible via the variable named 'htemp'.
6744///
6745/// If the library of the classes describing the data in the branch is
6746/// loaded, the skeleton will add the needed `include` statements and
6747/// give the ability to access the object stored in the branches.
6748///
6749/// To draw px using the file hsimple.root (generated by the
6750/// hsimple.C tutorial), we need a file named hsimple.cxx:
6751/// ~~~ {.cpp}
6752/// double hsimple() {
6753/// return px;
6754/// }
6755/// ~~~
6756/// MakeProxy can then be used indirectly via the TTree::Draw interface
6757/// as follow:
6758/// ~~~ {.cpp}
6759/// new TFile("hsimple.root")
6760/// ntuple->Draw("hsimple.cxx");
6761/// ~~~
6762/// A more complete example is available in the tutorials directory:
6763/// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
6764/// which reimplement the selector found in h1analysis.C
6766Int_t TTree::MakeProxy(const char* proxyClassname, const char* macrofilename, const char* cutfilename, const char* option, Int_t maxUnrolling)
6767{
6768 GetPlayer();
6769 if (!fPlayer) return 0;
6770 return fPlayer->MakeProxy(proxyClassname,macrofilename,cutfilename,option,maxUnrolling);
6771}
6772
6773////////////////////////////////////////////////////////////////////////////////
6774/// Generate skeleton selector class for this tree.
6775///
6776/// The following files are produced: selector.h and selector.C.
6777/// If selector is 0, the selector will be called "nameoftree".
6778/// The option can be used to specify the branches that will have a data member.
6779/// - If option is "=legacy", a pre-ROOT6 selector will be generated (data
6780/// members and branch pointers instead of TTreeReaders).
6781/// - If option is empty, readers will be generated for each leaf.
6782/// - If option is "@", readers will be generated for the topmost branches.
6783/// - Individual branches can also be picked by their name:
6784/// - "X" generates readers for leaves of X.
6785/// - "@X" generates a reader for X as a whole.
6786/// - "@X;Y" generates a reader for X as a whole and also readers for the
6787/// leaves of Y.
6788/// - For further examples see the figure below.
6789///
6790/// \image html ttree_makeselector_option_examples.png
6791///
6792/// The generated code in selector.h includes the following:
6793/// - Identification of the original Tree and Input file name
6794/// - Definition of selector class (data and functions)
6795/// - The following class functions:
6796/// - constructor and destructor
6797/// - void Begin(TTree *tree)
6798/// - void SlaveBegin(TTree *tree)
6799/// - void Init(TTree *tree)
6800/// - Bool_t Notify()
6801/// - Bool_t Process(Long64_t entry)
6802/// - void Terminate()
6803/// - void SlaveTerminate()
6804///
6805/// The class selector derives from TSelector.
6806/// The generated code in selector.C includes empty functions defined above.
6807///
6808/// To use this function:
6809///
6810/// - connect your Tree file (eg: `TFile f("myfile.root");`)
6811/// - `T->MakeSelector("myselect");`
6812///
6813/// where T is the name of the Tree in file myfile.root
6814/// and myselect.h, myselect.C the name of the files created by this function.
6815/// In a ROOT session, you can do:
6816/// ~~~ {.cpp}
6817/// root > T->Process("myselect.C")
6818/// ~~~
6820Int_t TTree::MakeSelector(const char* selector, Option_t* option)
6821{
6822 TString opt(option);
6823 if(opt.EqualTo("=legacy", TString::ECaseCompare::kIgnoreCase)) {
6824 return MakeClass(selector, "selector");
6825 } else {
6826 GetPlayer();
6827 if (!fPlayer) return 0;
6828 return fPlayer->MakeReader(selector, option);
6829 }
6830}
6831
6832////////////////////////////////////////////////////////////////////////////////
6833/// Check if adding nbytes to memory we are still below MaxVirtualsize.
6836{
6837 if ((fTotalBuffers + nbytes) < fMaxVirtualSize) {
6838 return kFALSE;
6839 }
6840 return kTRUE;
6841}
6842
6843////////////////////////////////////////////////////////////////////////////////
6844/// Static function merging the trees in the TList into a new tree.
6845///
6846/// Trees in the list can be memory or disk-resident trees.
6847/// The new tree is created in the current directory (memory if gROOT).
6849TTree* TTree::MergeTrees(TList* li, Option_t* options)
6850{
6851 if (!li) return 0;
6852 TIter next(li);
6853 TTree *newtree = 0;
6854 TObject *obj;
6855
6856 while ((obj=next())) {
6857 if (!obj->InheritsFrom(TTree::Class())) continue;
6858 TTree *tree = (TTree*)obj;
6859 Long64_t nentries = tree->GetEntries();
6860 if (nentries == 0) continue;
6861 if (!newtree) {
6862 newtree = (TTree*)tree->CloneTree(-1, options);
6863 if (!newtree) continue;
6864
6865 // Once the cloning is done, separate the trees,
6866 // to avoid as many side-effects as possible
6867 // The list of clones is guaranteed to exist since we
6868 // just cloned the tree.
6869 tree->GetListOfClones()->Remove(newtree);
6870 tree->ResetBranchAddresses();
6871 newtree->ResetBranchAddresses();
6872 continue;
6873 }
6874
6875 newtree->CopyEntries(tree, -1, options, kTRUE);
6876 }
6877 if (newtree && newtree->GetTreeIndex()) {
6878 newtree->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
6879 }
6880 return newtree;
6881}
6882
6883////////////////////////////////////////////////////////////////////////////////
6884/// Merge the trees in the TList into this tree.
6885///
6886/// Returns the total number of entries in the merged tree.
6889{
6890 if (!li) return 0;
6891 Long64_t storeAutoSave = fAutoSave;
6892 // Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
6893 // key would invalidate its iteration (or require costly measure to not use the deleted keys).
6894 // Also since this is part of a merging operation, the output file is not as precious as in
6895 // the general case since the input file should still be around.
6896 fAutoSave = 0;
6897 TIter next(li);
6898 TTree *tree;
6899 while ((tree = (TTree*)next())) {
6900 if (tree==this) continue;
6901 if (!tree->InheritsFrom(TTree::Class())) {
6902 Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
6903 fAutoSave = storeAutoSave;
6904 return -1;
6905 }
6906
6907 Long64_t nentries = tree->GetEntries();
6908 if (nentries == 0) continue;
6909
6910 CopyEntries(tree, -1, options, kTRUE);
6911 }
6912 fAutoSave = storeAutoSave;
6913 return GetEntries();
6914}
6915
6916////////////////////////////////////////////////////////////////////////////////
6917/// Merge the trees in the TList into this tree.
6918/// If info->fIsFirst is true, first we clone this TTree info the directory
6919/// info->fOutputDirectory and then overlay the new TTree information onto
6920/// this TTree object (so that this TTree object is now the appropriate to
6921/// use for further merging).
6922///
6923/// Returns the total number of entries in the merged tree.
6926{
6927 const char *options = info ? info->fOptions.Data() : "";
6928 if (info && info->fIsFirst && info->fOutputDirectory && info->fOutputDirectory->GetFile() != GetCurrentFile()) {
6929 if (GetCurrentFile() == nullptr) {
6930 // In memory TTree, all we need to do is ... write it.
6933 fDirectory->WriteTObject(this);
6934 } else if (info->fOptions.Contains("fast")) {
6936 } else {
6938 TIOFeatures saved_features = fIOFeatures;
6939 TTree *newtree = CloneTree(-1, options);
6940 if (info->fIOFeatures)
6941 fIOFeatures = *(info->fIOFeatures);
6942 else
6943 fIOFeatures = saved_features;
6944 if (newtree) {
6945 newtree->Write();
6946 delete newtree;
6947 }
6948 // Make sure things are really written out to disk before attempting any reading.
6949 info->fOutputDirectory->GetFile()->Flush();
6950 info->fOutputDirectory->ReadTObject(this,this->GetName());
6951 }
6952 }
6953 if (!li) return 0;
6954 Long64_t storeAutoSave = fAutoSave;
6955 // Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
6956 // key would invalidate its iteration (or require costly measure to not use the deleted keys).
6957 // Also since this is part of a merging operation, the output file is not as precious as in
6958 // the general case since the input file should still be around.
6959 fAutoSave = 0;
6960 TIter next(li);
6961 TTree *tree;
6962 while ((tree = (TTree*)next())) {
6963 if (tree==this) continue;
6964 if (!tree->InheritsFrom(TTree::Class())) {
6965 Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
6966 fAutoSave = storeAutoSave;
6967 return -1;
6968 }
6969
6970 CopyEntries(tree, -1, options, kTRUE);
6971 }
6972 fAutoSave = storeAutoSave;
6973 return GetEntries();
6974}
6975
6976////////////////////////////////////////////////////////////////////////////////
6977/// Move a cache from a file to the current file in dir.
6978/// if src is null no operation is done, if dir is null or there is no
6979/// current file the cache is deleted.
6982{
6983 if (!src) return;
6984 TFile *dst = (dir && dir != gROOT) ? dir->GetFile() : 0;
6985 if (src == dst) return;
6986
6988 if (dst) {
6989 src->SetCacheRead(0,this);
6990 dst->SetCacheRead(pf, this);
6991 } else {
6992 if (pf) {
6993 pf->WaitFinishPrefetch();
6994 }
6995 src->SetCacheRead(0,this);
6996 delete pf;
6997 }
6998}
6999
7000////////////////////////////////////////////////////////////////////////////////
7001/// Copy the content to a new new file, update this TTree with the new
7002/// location information and attach this TTree to the new directory.
7003///
7004/// options: Indicates a basket sorting method, see TTreeCloner::TTreeCloner for
7005/// details
7006///
7007/// If new and old directory are in the same file, the data is untouched,
7008/// this "just" does a call to SetDirectory.
7009/// Equivalent to an "in place" cloning of the TTree.
7010Bool_t TTree::InPlaceClone(TDirectory *newdirectory, const char *options)
7011{
7012 if (!newdirectory) {
7014 SetDirectory(nullptr);
7015 return true;
7016 }
7017 if (newdirectory->GetFile() == GetCurrentFile()) {
7018 SetDirectory(newdirectory);
7019 return true;
7020 }
7021 TTreeCloner cloner(this, newdirectory, options);
7022 if (cloner.IsValid())
7023 return cloner.Exec();
7024 else
7025 return false;
7026}
7027
7028////////////////////////////////////////////////////////////////////////////////
7029/// Function called when loading a new class library.
7032{
7033 TIter next(GetListOfLeaves());
7034 TLeaf* leaf = 0;
7035 while ((leaf = (TLeaf*) next())) {
7036 leaf->Notify();
7037 leaf->GetBranch()->Notify();
7038 }
7039 return kTRUE;
7040}
7041
7042////////////////////////////////////////////////////////////////////////////////
7043/// This function may be called after having filled some entries in a Tree.
7044/// Using the information in the existing branch buffers, it will reassign
7045/// new branch buffer sizes to optimize time and memory.
7046///
7047/// The function computes the best values for branch buffer sizes such that
7048/// the total buffer sizes is less than maxMemory and nearby entries written
7049/// at the same time.
7050/// In case the branch compression factor for the data written so far is less
7051/// than compMin, the compression is disabled.
7052///
7053/// if option ="d" an analysis report is printed.
7055void TTree::OptimizeBaskets(ULong64_t maxMemory, Float_t minComp, Option_t *option)
7056{
7057 //Flush existing baskets if the file is writable
7058 if (this->GetDirectory()->IsWritable()) this->FlushBasketsImpl();
7059
7060 TString opt( option );
7061 opt.ToLower();
7062 Bool_t pDebug = opt.Contains("d");
7063 TObjArray *leaves = this->GetListOfLeaves();
7064 Int_t nleaves = leaves->GetEntries();
7065 Double_t treeSize = (Double_t)this->GetTotBytes();
7066
7067 if (nleaves == 0 || treeSize == 0) {
7068 // We're being called too early, we really have nothing to do ...
7069 return;
7070 }
7071 Double_t aveSize = treeSize/nleaves;
7072 UInt_t bmin = 512;
7073 UInt_t bmax = 256000;
7074 Double_t memFactor = 1;
7075 Int_t i, oldMemsize,newMemsize,oldBaskets,newBaskets;
7076 i = oldMemsize = newMemsize = oldBaskets = newBaskets = 0;
7077
7078 //we make two passes
7079 //one pass to compute the relative branch buffer sizes
7080 //a second pass to compute the absolute values
7081 for (Int_t pass =0;pass<2;pass++) {
7082 oldMemsize = 0; //to count size of baskets in memory with old buffer size
7083 newMemsize = 0; //to count size of baskets in memory with new buffer size
7084 oldBaskets = 0; //to count number of baskets with old buffer size
7085 newBaskets = 0; //to count number of baskets with new buffer size
7086 for (i=0;i<nleaves;i++) {
7087 TLeaf *leaf = (TLeaf*)leaves->At(i);
7088 TBranch *branch = leaf->GetBranch();
7089 Double_t totBytes = (Double_t)branch->GetTotBytes();
7090 Double_t idealFactor = totBytes/aveSize;
7091 UInt_t sizeOfOneEntry;
7092 if (branch->GetEntries() == 0) {
7093 // There is no data, so let's make a guess ...
7094 sizeOfOneEntry = aveSize;
7095 } else {
7096 sizeOfOneEntry = 1+(UInt_t)(totBytes / (Double_t)branch->GetEntries());
7097 }
7098 Int_t oldBsize = branch->GetBasketSize();
7099 oldMemsize += oldBsize;
7100 oldBaskets += 1+Int_t(totBytes/oldBsize);
7101 Int_t nb = branch->GetListOfBranches()->GetEntries();
7102 if (nb > 0) {
7103 newBaskets += 1+Int_t(totBytes/oldBsize);
7104 continue;
7105 }
7106 Double_t bsize = oldBsize*idealFactor*memFactor; //bsize can be very large !
7107 if (bsize < 0) bsize = bmax;
7108 if (bsize > bmax) bsize = bmax;
7109 UInt_t newBsize = UInt_t(bsize);
7110 if (pass) { // only on the second pass so that it doesn't interfere with scaling
7111 // If there is an entry offset, it will be stored in the same buffer as the object data; hence,
7112 // we must bump up the size of the branch to account for this extra footprint.
7113 // If fAutoFlush is not set yet, let's assume that it is 'in the process of being set' to
7114 // the value of GetEntries().
7115 Long64_t clusterSize = (fAutoFlush > 0) ? fAutoFlush : branch->GetEntries();
7116 if (branch->GetEntryOffsetLen()) {
7117 newBsize = newBsize + (clusterSize * sizeof(Int_t) * 2);
7118 }
7119 // We used ATLAS fully-split xAOD for testing, which is a rather unbalanced TTree, 10K branches,
7120 // with 8K having baskets smaller than 512 bytes. To achieve good I/O performance ATLAS uses auto-flush 100,
7121 // resulting in the smallest baskets being ~300-400 bytes, so this change increases their memory by about 8k*150B =~ 1MB,
7122 // at the same time it significantly reduces the number of total baskets because it ensures that all 100 entries can be
7123 // stored in a single basket (the old optimization tended to make baskets too small). In a toy example with fixed sized
7124 // structures we found a factor of 2 fewer baskets needed in the new scheme.
7125 // rounds up, increases basket size to ensure all entries fit into single basket as intended
7126 newBsize = newBsize - newBsize%512 + 512;
7127 }
7128 if (newBsize < sizeOfOneEntry) newBsize = sizeOfOneEntry;
7129 if (newBsize < bmin) newBsize = bmin;
7130 if (newBsize > 10000000) newBsize = bmax;
7131 if (pass) {
7132 if (pDebug) Info("OptimizeBaskets", "Changing buffer size from %6d to %6d bytes for %s\n",oldBsize,newBsize,branch->GetName());
7133 branch->SetBasketSize(newBsize);
7134 }
7135 newMemsize += newBsize;
7136 // For this number to be somewhat accurate when newBsize is 'low'
7137 // we do not include any space for meta data in the requested size (newBsize) even-though SetBasketSize will
7138 // not let it be lower than 100+TBranch::fEntryOffsetLen.
7139 newBaskets += 1+Int_t(totBytes/newBsize);
7140 if (pass == 0) continue;
7141 //Reset the compression level in case the compression factor is small
7142 Double_t comp = 1;
7143 if (branch->GetZipBytes() > 0) comp = totBytes/Double_t(branch->GetZipBytes());
7144 if (comp > 1 && comp < minComp) {
7145 if (pDebug) Info("OptimizeBaskets", "Disabling compression for branch : %s\n",branch->GetName());
7147 }
7148 }
7149 // coverity[divide_by_zero] newMemsize can not be zero as there is at least one leaf
7150 memFactor = Double_t(maxMemory)/Double_t(newMemsize);
7151 if (memFactor > 100) memFactor = 100;
7152 Double_t bmin_new = bmin*memFactor;
7153 Double_t bmax_new = bmax*memFactor;
7154 static const UInt_t hardmax = 1*1024*1024*1024; // Really, really never give more than 1Gb to a single buffer.
7155
7156 // Really, really never go lower than 8 bytes (we use this number
7157 // so that the calculation of the number of basket is consistent
7158 // but in fact SetBasketSize will not let the size go below
7159 // TBranch::fEntryOffsetLen + (100 + strlen(branch->GetName())
7160 // (The 2nd part being a slight over estimate of the key length.
7161 static const UInt_t hardmin = 8;
7162 bmin = (bmin_new > hardmax) ? hardmax : ( bmin_new < hardmin ? hardmin : (UInt_t)bmin_new );
7163 bmax = (bmax_new > hardmax) ? bmin : (UInt_t)bmax_new;
7164 }
7165 if (pDebug) {
7166 Info("OptimizeBaskets", "oldMemsize = %d, newMemsize = %d\n",oldMemsize, newMemsize);
7167 Info("OptimizeBaskets", "oldBaskets = %d, newBaskets = %d\n",oldBaskets, newBaskets);
7168 }
7169}
7170
7171////////////////////////////////////////////////////////////////////////////////
7172/// Interface to the Principal Components Analysis class.
7173///
7174/// Create an instance of TPrincipal
7175///
7176/// Fill it with the selected variables
7177///
7178/// - if option "n" is specified, the TPrincipal object is filled with
7179/// normalized variables.
7180/// - If option "p" is specified, compute the principal components
7181/// - If option "p" and "d" print results of analysis
7182/// - If option "p" and "h" generate standard histograms
7183/// - If option "p" and "c" generate code of conversion functions
7184/// - return a pointer to the TPrincipal object. It is the user responsibility
7185/// - to delete this object.
7186/// - The option default value is "np"
7187///
7188/// see TTree::Draw for explanation of the other parameters.
7189///
7190/// The created object is named "principal" and a reference to it
7191/// is added to the list of specials Root objects.
7192/// you can retrieve a pointer to the created object via:
7193/// ~~~ {.cpp}
7194/// TPrincipal *principal =
7195/// (TPrincipal*)gROOT->GetListOfSpecials()->FindObject("principal");
7196/// ~~~
7198TPrincipal* TTree::Principal(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
7199{
7200 GetPlayer();
7201 if (fPlayer) {
7202 return fPlayer->Principal(varexp, selection, option, nentries, firstentry);
7203 }
7204 return 0;
7205}
7206
7207////////////////////////////////////////////////////////////////////////////////
7208/// Print a summary of the tree contents.
7209///
7210/// - If option contains "all" friend trees are also printed.
7211/// - If option contains "toponly" only the top level branches are printed.
7212/// - If option contains "clusters" information about the cluster of baskets is printed.
7213///
7214/// Wildcarding can be used to print only a subset of the branches, e.g.,
7215/// `T.Print("Elec*")` will print all branches with name starting with "Elec".
7217void TTree::Print(Option_t* option) const
7218{
7219 // We already have been visited while recursively looking
7220 // through the friends tree, let's return.
7221 if (kPrint & fFriendLockStatus) {
7222 return;
7223 }
7224 Int_t s = 0;
7225 Int_t skey = 0;
7226 if (fDirectory) {
7227 TKey* key = fDirectory->GetKey(GetName());
7228 if (key) {
7229 skey = key->GetKeylen();
7230 s = key->GetNbytes();
7231 }
7232 }
7233 Long64_t total = skey;
7234 Long64_t zipBytes = GetZipBytes();
7235 if (zipBytes > 0) {
7236 total += GetTotBytes();
7237 }
7239 TTree::Class()->WriteBuffer(b, (TTree*) this);
7240 total += b.Length();
7241 Long64_t file = zipBytes + s;
7242 Float_t cx = 1;
7243 if (zipBytes) {
7244 cx = (GetTotBytes() + 0.00001) / zipBytes;
7245 }
7246 Printf("******************************************************************************");
7247 Printf("*Tree :%-10s: %-54s *", GetName(), GetTitle());
7248 Printf("*Entries : %8lld : Total = %15lld bytes File Size = %10lld *", fEntries, total, file);
7249 Printf("* : : Tree compression factor = %6.2f *", cx);
7250 Printf("******************************************************************************");
7251
7252 // Avoid many check of option validity
7253 if (!option)
7254 option = "";
7255
7256 if (strncmp(option,"clusters",strlen("clusters"))==0) {
7257 Printf("%-16s %-16s %-16s %8s %20s",
7258 "Cluster Range #", "Entry Start", "Last Entry", "Size", "Number of clusters");
7259 Int_t index= 0;
7260 Long64_t clusterRangeStart = 0;
7261 Long64_t totalClusters = 0;
7262 bool estimated = false;
7263 bool unknown = false;
7264 auto printer = [this, &totalClusters, &estimated, &unknown](Int_t ind, Long64_t start, Long64_t end, Long64_t recordedSize) {
7265 Long64_t nclusters = 0;
7266 if (recordedSize > 0) {
7267 nclusters = (1 + end - start) / recordedSize;
7268 Printf("%-16d %-16lld %-16lld %8lld %10lld",
7269 ind, start, end, recordedSize, nclusters);
7270 } else {
7271 // NOTE: const_cast ... DO NOT Merge for now
7272 TClusterIterator iter((TTree*)this, start);
7273 iter.Next();
7274 auto estimated_size = iter.GetNextEntry() - start;
7275 if (estimated_size > 0) {
7276 nclusters = (1 + end - start) / estimated_size;
7277 Printf("%-16d %-16lld %-16lld %8lld %10lld (estimated)",
7278 ind, start, end, recordedSize, nclusters);
7279 estimated = true;
7280 } else {
7281 Printf("%-16d %-16lld %-16lld %8lld (unknown)",
7282 ind, start, end, recordedSize);
7283 unknown = true;
7284 }
7285 }
7286 start = end + 1;
7287 totalClusters += nclusters;
7288 };
7289 if (fNClusterRange) {
7290 for( ; index < fNClusterRange; ++index) {
7291 printer(index, clusterRangeStart, fClusterRangeEnd[index], fClusterSize[index]);
7292 clusterRangeStart = fClusterRangeEnd[index] + 1;
7293 }
7294 }
7295 printer(index, clusterRangeStart, fEntries - 1, fAutoFlush);
7296 if (unknown) {
7297 Printf("Total number of clusters: (unknown)");
7298 } else {
7299 Printf("Total number of clusters: %lld %s", totalClusters, estimated ? "(estimated)" : "");
7300 }
7301 return;
7302 }
7303
7304 Int_t nl = const_cast<TTree*>(this)->GetListOfLeaves()->GetEntries();
7305 Int_t l;
7306 TBranch* br = nullptr;
7307 TLeaf* leaf = nullptr;
7308 if (strstr(option, "toponly")) {
7309 Long64_t *count = new Long64_t[nl];
7310 Int_t keep =0;
7311 for (l=0;l<nl;l++) {
7312 leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
7313 br = leaf->GetBranch();
7314 if (strchr(br->GetName(),'.')) {
7315 count[l] = -1;
7316 count[keep] += br->GetZipBytes();
7317 } else {
7318 keep = l;
7319 count[keep] = br->GetZipBytes();
7320 }
7321 }
7322 for (l=0;l<nl;l++) {
7323 if (count[l] < 0) continue;
7324 leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
7325 br = leaf->GetBranch();
7326 Printf("branch: %-20s %9lld\n",br->GetName(),count[l]);
7327 }
7328 delete [] count;
7329 } else {
7330 TString reg = "*";
7331 if (strlen(option) && strchr(option,'*')) reg = option;
7332 TRegexp re(reg,kTRUE);
7333 TIter next(const_cast<TTree*>(this)->GetListOfBranches());
7335 while ((br= (TBranch*)next())) {
7336 TString st = br->GetName();
7337 st.ReplaceAll("/","_");
7338 if (st.Index(re) == kNPOS) continue;
7339 br->Print(option);
7340 }
7341 }
7342
7343 //print TRefTable (if one)
7345
7346 //print friends if option "all"
7347 if (!fFriends || !strstr(option,"all")) return;
7348 TIter nextf(fFriends);
7349 TFriendLock lock(const_cast<TTree*>(this),kPrint);
7350 TFriendElement *fr;
7351 while ((fr = (TFriendElement*)nextf())) {
7352 TTree * t = fr->GetTree();
7353 if (t) t->Print(option);
7354 }
7355}
7356
7357////////////////////////////////////////////////////////////////////////////////
7358/// Print statistics about the TreeCache for this tree.
7359/// Like:
7360/// ~~~ {.cpp}
7361/// ******TreeCache statistics for file: cms2.root ******
7362/// Reading 73921562 bytes in 716 transactions
7363/// Average transaction = 103.242405 Kbytes
7364/// Number of blocks in current cache: 202, total size : 6001193
7365/// ~~~
7366/// if option = "a" the list of blocks in the cache is printed
7369{
7370 TFile *f = GetCurrentFile();
7371 if (!f) return;
7372 TTreeCache *tc = GetReadCache(f);
7373 if (tc) tc->Print(option);
7374}
7375
7376////////////////////////////////////////////////////////////////////////////////
7377/// Process this tree executing the TSelector code in the specified filename.
7378/// The return value is -1 in case of error and TSelector::GetStatus() in
7379/// in case of success.
7380///
7381/// The code in filename is loaded (interpreted or compiled, see below),
7382/// filename must contain a valid class implementation derived from TSelector,
7383/// where TSelector has the following member functions:
7384///
7385/// - `Begin()`: called every time a loop on the tree starts,
7386/// a convenient place to create your histograms.
7387/// - `SlaveBegin()`: called after Begin(), when on PROOF called only on the
7388/// slave servers.
7389/// - `Process()`: called for each event, in this function you decide what
7390/// to read and fill your histograms.
7391/// - `SlaveTerminate`: called at the end of the loop on the tree, when on PROOF
7392/// called only on the slave servers.
7393/// - `Terminate()`: called at the end of the loop on the tree,
7394/// a convenient place to draw/fit your histograms.
7395///
7396/// If filename is of the form file.C, the file will be interpreted.
7397///
7398/// If filename is of the form file.C++, the file file.C will be compiled
7399/// and dynamically loaded.
7400///
7401/// If filename is of the form file.C+, the file file.C will be compiled
7402/// and dynamically loaded. At next call, if file.C is older than file.o
7403/// and file.so, the file.C is not compiled, only file.so is loaded.
7404///
7405/// ## NOTE1
7406///
7407/// It may be more interesting to invoke directly the other Process function
7408/// accepting a TSelector* as argument.eg
7409/// ~~~ {.cpp}
7410/// MySelector *selector = (MySelector*)TSelector::GetSelector(filename);
7411/// selector->CallSomeFunction(..);
7412/// mytree.Process(selector,..);
7413/// ~~~
7414/// ## NOTE2
7415//
7416/// One should not call this function twice with the same selector file
7417/// in the same script. If this is required, proceed as indicated in NOTE1,
7418/// by getting a pointer to the corresponding TSelector,eg
7419///
7420/// ### Workaround 1
7421///
7422/// ~~~ {.cpp}
7423/// void stubs1() {
7424/// TSelector *selector = TSelector::GetSelector("h1test.C");
7425/// TFile *f1 = new TFile("stubs_nood_le1.root");
7426/// TTree *h1 = (TTree*)f1->Get("h1");
7427/// h1->Process(selector);
7428/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
7429/// TTree *h2 = (TTree*)f2->Get("h1");
7430/// h2->Process(selector);
7431/// }
7432/// ~~~
7433/// or use ACLIC to compile the selector
7434///
7435/// ### Workaround 2
7436///
7437/// ~~~ {.cpp}
7438/// void stubs2() {
7439/// TFile *f1 = new TFile("stubs_nood_le1.root");
7440/// TTree *h1 = (TTree*)f1->Get("h1");
7441/// h1->Process("h1test.C+");
7442/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
7443/// TTree *h2 = (TTree*)f2->Get("h1");
7444/// h2->Process("h1test.C+");
7445/// }
7446/// ~~~
7449{
7450 GetPlayer();
7451 if (fPlayer) {
7452 return fPlayer->Process(filename, option, nentries, firstentry);
7453 }
7454 return -1;
7455}
7456
7457////////////////////////////////////////////////////////////////////////////////
7458/// Process this tree executing the code in the specified selector.
7459/// The return value is -1 in case of error and TSelector::GetStatus() in
7460/// in case of success.
7461///
7462/// The TSelector class has the following member functions:
7463///
7464/// - `Begin()`: called every time a loop on the tree starts,
7465/// a convenient place to create your histograms.
7466/// - `SlaveBegin()`: called after Begin(), when on PROOF called only on the
7467/// slave servers.
7468/// - `Process()`: called for each event, in this function you decide what
7469/// to read and fill your histograms.
7470/// - `SlaveTerminate`: called at the end of the loop on the tree, when on PROOF
7471/// called only on the slave servers.
7472/// - `Terminate()`: called at the end of the loop on the tree,
7473/// a convenient place to draw/fit your histograms.
7474///
7475/// If the Tree (Chain) has an associated EventList, the loop is on the nentries
7476/// of the EventList, starting at firstentry, otherwise the loop is on the
7477/// specified Tree entries.
7480{
7481 GetPlayer();
7482 if (fPlayer) {
7483 return fPlayer->Process(selector, option, nentries, firstentry);
7484 }
7485 return -1;
7486}
7487
7488////////////////////////////////////////////////////////////////////////////////
7489/// Make a projection of a tree using selections.
7490///
7491/// Depending on the value of varexp (described in Draw) a 1-D, 2-D, etc.,
7492/// projection of the tree will be filled in histogram hname.
7493/// Note that the dimension of hname must match with the dimension of varexp.
7494///
7496Long64_t TTree::Project(const char* hname, const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
7497{
7498 TString var;
7499 var.Form("%s>>%s", varexp, hname);
7500 TString opt("goff");
7501 if (option) {
7502 opt.Form("%sgoff", option);
7503 }
7504 Long64_t nsel = Draw(var, selection, opt, nentries, firstentry);
7505 return nsel;
7506}
7507
7508////////////////////////////////////////////////////////////////////////////////
7509/// Loop over entries and return a TSQLResult object containing entries following selection.
7511TSQLResult* TTree::Query(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
7512{
7513 GetPlayer();
7514 if (fPlayer) {
7515 return fPlayer->Query(varexp, selection, option, nentries, firstentry);
7516 }
7517 return 0;
7518}
7519
7520////////////////////////////////////////////////////////////////////////////////
7521/// Create or simply read branches from filename.
7522///
7523/// if branchDescriptor = "" (default), it is assumed that the Tree descriptor
7524/// is given in the first line of the file with a syntax like
7525/// ~~~ {.cpp}
7526/// A/D:Table[2]/F:Ntracks/I:astring/C
7527/// ~~~
7528/// otherwise branchDescriptor must be specified with the above syntax.
7529///
7530/// - If the type of the first variable is not specified, it is assumed to be "/F"
7531/// - If the type of any other variable is not specified, the type of the previous
7532/// variable is assumed. eg
7533/// - `x:y:z` (all variables are assumed of type "F")
7534/// - `x/D:y:z` (all variables are of type "D")
7535/// - `x:y/D:z` (x is type "F", y and z of type "D")
7536///
7537/// delimiter allows for the use of another delimiter besides whitespace.
7538/// This provides support for direct import of common data file formats
7539/// like csv. If delimiter != ' ' and branchDescriptor == "", then the
7540/// branch description is taken from the first line in the file, but
7541/// delimiter is used for the branch names tokenization rather than ':'.
7542/// Note however that if the values in the first line do not use the
7543/// /[type] syntax, all variables are assumed to be of type "F".
7544/// If the filename ends with extensions .csv or .CSV and a delimiter is
7545/// not specified (besides ' '), the delimiter is automatically set to ','.
7546///
7547/// Lines in the input file starting with "#" are ignored. Leading whitespace
7548/// for each column data is skipped. Empty lines are skipped.
7549///
7550/// A TBranch object is created for each variable in the expression.
7551/// The total number of rows read from the file is returned.
7552///
7553/// ## FILLING a TTree WITH MULTIPLE INPUT TEXT FILES
7554///
7555/// To fill a TTree with multiple input text files, proceed as indicated above
7556/// for the first input file and omit the second argument for subsequent calls
7557/// ~~~ {.cpp}
7558/// T.ReadFile("file1.dat","branch descriptor");
7559/// T.ReadFile("file2.dat");
7560/// ~~~
7562Long64_t TTree::ReadFile(const char* filename, const char* branchDescriptor, char delimiter)
7563{
7564 if (!filename || !*filename) {
7565 Error("ReadFile","File name not specified");
7566 return 0;
7567 }
7568
7569 std::ifstream in;
7570 in.open(filename);
7571 if (!in.good()) {
7572 Error("ReadFile","Cannot open file: %s",filename);
7573 return 0;
7574 }
7575 const char* ext = strrchr(filename, '.');
7576 if(ext && ((strcmp(ext, ".csv") == 0) || (strcmp(ext, ".CSV") == 0)) && delimiter == ' ') {
7577 delimiter = ',';
7578 }
7579 return ReadStream(in, branchDescriptor, delimiter);
7580}
7581
7582////////////////////////////////////////////////////////////////////////////////
7583/// Determine which newline this file is using.
7584/// Return '\\r' for Windows '\\r\\n' as that already terminates.
7586char TTree::GetNewlineValue(std::istream &inputStream)
7587{
7588 Long_t inPos = inputStream.tellg();
7589 char newline = '\n';
7590 while(1) {
7591 char c = 0;
7592 inputStream.get(c);
7593 if(!inputStream.good()) {
7594 Error("ReadStream","Error reading stream: no newline found.");
7595 return 0;
7596 }
7597 if(c == newline) break;
7598 if(c == '\r') {
7599 newline = '\r';
7600 break;
7601 }
7602 }
7603 inputStream.clear();
7604 inputStream.seekg(inPos);
7605 return newline;
7606}
7607
7608////////////////////////////////////////////////////////////////////////////////
7609/// Create or simply read branches from an input stream.
7610///
7611/// \see reference information for TTree::ReadFile
7613Long64_t TTree::ReadStream(std::istream& inputStream, const char *branchDescriptor, char delimiter)
7614{
7615 char newline = 0;
7616 std::stringstream ss;
7617 std::istream *inTemp;
7618 Long_t inPos = inputStream.tellg();
7619 if (!inputStream.good()) {
7620 Error("ReadStream","Error reading stream");
7621 return 0;
7622 }
7623 if (inPos == -1) {
7624 ss << std::cin.rdbuf();
7625 newline = GetNewlineValue(ss);
7626 inTemp = &ss;
7627 } else {
7628 newline = GetNewlineValue(inputStream);
7629 inTemp = &inputStream;
7630 }
7631 std::istream& in = *inTemp;
7632 Long64_t nlines = 0;
7633
7634 TBranch *branch = 0;
7635 Int_t nbranches = fBranches.GetEntries();
7636 if (nbranches == 0) {
7637 char *bdname = new char[4000];
7638 char *bd = new char[100000];
7639 Int_t nch = 0;
7640 if (branchDescriptor) nch = strlen(branchDescriptor);
7641 // branch Descriptor is null, read its definition from the first line in the file
7642 if (!nch) {
7643 do {
7644 in.getline(bd, 100000, newline);
7645 if (!in.good()) {
7646 delete [] bdname;
7647 delete [] bd;
7648 Error("ReadStream","Error reading stream");
7649 return 0;
7650 }
7651 char *cursor = bd;
7652 while( isspace(*cursor) && *cursor != '\n' && *cursor != '\0') {
7653 ++cursor;
7654 }
7655 if (*cursor != '#' && *cursor != '\n' && *cursor != '\0') {
7656 break;
7657 }
7658 } while (true);
7659 ++nlines;
7660 nch = strlen(bd);
7661 } else {
7662 strlcpy(bd,branchDescriptor,100000);
7663 }
7664
7665 //parse the branch descriptor and create a branch for each element
7666 //separated by ":"
7667 void *address = &bd[90000];
7668 char *bdcur = bd;
7669 TString desc="", olddesc="F";
7670 char bdelim = ':';
7671 if(delimiter != ' ') {
7672 bdelim = delimiter;
7673 if (strchr(bdcur,bdelim)==0 && strchr(bdcur,':') != 0) {
7674 // revert to the default
7675 bdelim = ':';
7676 }
7677 }
7678 while (bdcur) {
7679 char *colon = strchr(bdcur,bdelim);
7680 if (colon) *colon = 0;
7681 strlcpy(bdname,bdcur,4000);
7682 char *slash = strchr(bdname,'/');
7683 if (slash) {
7684 *slash = 0;
7685 desc = bdcur;
7686 olddesc = slash+1;
7687 } else {
7688 desc.Form("%s/%s",bdname,olddesc.Data());
7689 }
7690 char *bracket = strchr(bdname,'[');
7691 if (bracket) {
7692 *bracket = 0;
7693 }
7694 branch = new TBranch(this,bdname,address,desc.Data(),32000);
7695 if (branch->IsZombie()) {
7696 delete branch;
7697 Warning("ReadStream","Illegal branch definition: %s",bdcur);
7698 } else {
7699 fBranches.Add(branch);
7700 branch->SetAddress(0);
7701 }
7702 if (!colon)break;
7703 bdcur = colon+1;
7704 }
7705 delete [] bdname;
7706 delete [] bd;
7707 }
7708
7709 nbranches = fBranches.GetEntries();
7710
7711 if (gDebug > 1) {
7712 Info("ReadStream", "Will use branches:");
7713 for (int i = 0 ; i < nbranches; ++i) {
7714 TBranch* br = (TBranch*) fBranches.At(i);
7715 Info("ReadStream", " %s: %s [%s]", br->GetName(),
7716 br->GetTitle(), br->GetListOfLeaves()->At(0)->IsA()->GetName());
7717 }
7718 if (gDebug > 3) {
7719 Info("ReadStream", "Dumping read tokens, format:");
7720 Info("ReadStream", "LLLLL:BBB:gfbe:GFBE:T");
7721 Info("ReadStream", " L: line number");
7722 Info("ReadStream", " B: branch number");
7723 Info("ReadStream", " gfbe: good / fail / bad / eof of token");
7724 Info("ReadStream", " GFBE: good / fail / bad / eof of file");
7725 Info("ReadStream", " T: Token being read");
7726 }
7727 }
7728
7729 //loop on all lines in the file
7730 Long64_t nGoodLines = 0;
7731 std::string line;
7732 const char sDelimBuf[2] = { delimiter, 0 };
7733 const char* sDelim = sDelimBuf;
7734 if (delimiter == ' ') {
7735 // ' ' really means whitespace
7736 sDelim = "[ \t]";
7737 }
7738 while(in.good()) {
7739 if (newline == '\r' && in.peek() == '\n') {
7740 // Windows, skip '\n':
7741 in.get();
7742 }
7743 std::getline(in, line, newline);
7744 ++nlines;
7745
7746 TString sLine(line);
7747 sLine = sLine.Strip(TString::kLeading); // skip leading whitespace
7748 if (sLine.IsNull()) {
7749 if (gDebug > 2) {
7750 Info("ReadStream", "Skipping empty line number %lld", nlines);
7751 }
7752 continue; // silently skip empty lines
7753 }
7754 if (sLine[0] == '#') {
7755 if (gDebug > 2) {
7756 Info("ReadStream", "Skipping comment line number %lld: '%s'",
7757 nlines, line.c_str());
7758 }
7759 continue;
7760 }
7761 if (gDebug > 2) {
7762 Info("ReadStream", "Parsing line number %lld: '%s'",
7763 nlines, line.c_str());
7764 }
7765
7766 // Loop on branches and read the branch values into their buffer
7767 branch = 0;
7768 TString tok; // one column's data
7769 TString leafData; // leaf data, possibly multiple tokens for e.g. /I[2]
7770 std::stringstream sToken; // string stream feeding leafData into leaves
7771 Ssiz_t pos = 0;
7772 Int_t iBranch = 0;
7773 Bool_t goodLine = kTRUE; // whether the row can be filled into the tree
7774 Int_t remainingLeafLen = 0; // remaining columns for the current leaf
7775 while (goodLine && iBranch < nbranches
7776 && sLine.Tokenize(tok, pos, sDelim)) {
7777 tok = tok.Strip(TString::kLeading); // skip leading whitespace
7778 if (tok.IsNull() && delimiter == ' ') {
7779 // 1 2 should not be interpreted as 1,,,2 but 1, 2.
7780 // Thus continue until we have a non-empty token.
7781 continue;
7782 }
7783
7784 if (!remainingLeafLen) {
7785 // next branch!
7786 branch = (TBranch*)fBranches.At(iBranch);
7787 }
7788 TLeaf *leaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
7789 if (!remainingLeafLen) {
7790 remainingLeafLen = leaf->GetLen();
7791 if (leaf->GetMaximum() > 0) {
7792 // This is a dynamic leaf length, i.e. most likely a TLeafC's
7793 // string size. This still translates into one token:
7794 remainingLeafLen = 1;
7795 }
7796
7797 leafData = tok;
7798 } else {
7799 // append token to laf data:
7800 leafData += " ";
7801 leafData += tok;
7802 }
7803 --remainingLeafLen;
7804 if (remainingLeafLen) {
7805 // need more columns for this branch:
7806 continue;
7807 }
7808 ++iBranch;
7809
7810 // initialize stringstream with token
7811 sToken.clear();
7812 sToken.seekp(0, std::ios_base::beg);
7813 sToken.str(leafData.Data());
7814 sToken.seekg(0, std::ios_base::beg);
7815 leaf->ReadValue(sToken, 0 /* 0 = "all" */);
7816 if (gDebug > 3) {
7817 Info("ReadStream", "%5lld:%3d:%d%d%d%d:%d%d%d%d:%s",
7818 nlines, iBranch,
7819 (int)sToken.good(), (int)sToken.fail(),
7820 (int)sToken.bad(), (int)sToken.eof(),
7821 (int)in.good(), (int)in.fail(),
7822 (int)in.bad(), (int)in.eof(),
7823 sToken.str().c_str());
7824 }
7825
7826 // Error handling
7827 if (sToken.bad()) {
7828 // How could that happen for a stringstream?
7829 Warning("ReadStream",
7830 "Buffer error while reading data for branch %s on line %lld",
7831 branch->GetName(), nlines);
7832 } else if (!sToken.eof()) {
7833 if (sToken.fail()) {
7834 Warning("ReadStream",
7835 "Couldn't read formatted data in \"%s\" for branch %s on line %lld; ignoring line",
7836 tok.Data(), branch->GetName(), nlines);
7837 goodLine = kFALSE;
7838 } else {
7839 std::string remainder;
7840 std::getline(sToken, remainder, newline);
7841 if (!remainder.empty()) {
7842 Warning("ReadStream",
7843 "Ignoring trailing \"%s\" while reading data for branch %s on line %lld",
7844 remainder.c_str(), branch->GetName(), nlines);
7845 }
7846 }
7847 }
7848 } // tokenizer loop
7849
7850 if (iBranch < nbranches) {
7851 Warning("ReadStream",
7852 "Read too few columns (%d < %d) in line %lld; ignoring line",
7853 iBranch, nbranches, nlines);
7854 goodLine = kFALSE;
7855 } else if (pos != kNPOS) {
7856 sLine = sLine.Strip(TString::kTrailing);
7857 if (pos < sLine.Length()) {
7858 Warning("ReadStream",
7859 "Ignoring trailing \"%s\" while reading line %lld",
7860 sLine.Data() + pos - 1 /* also print delimiter */,
7861 nlines);
7862 }
7863 }
7864
7865 //we are now ready to fill the tree
7866 if (goodLine) {
7867 Fill();
7868 ++nGoodLines;
7869 }
7870 }
7871
7872 return nGoodLines;
7873}
7874
7875////////////////////////////////////////////////////////////////////////////////
7876/// Make sure that obj (which is being deleted or will soon be) is no
7877/// longer referenced by this TTree.
7880{
7881 if (obj == fEventList) {
7882 fEventList = nullptr;
7883 }
7884 if (obj == fEntryList) {
7885 fEntryList = nullptr;
7886 }
7887 if (fUserInfo) {
7889 }
7890 if (fPlayer == obj) {
7891 fPlayer = nullptr;
7892 }
7893 if (fTreeIndex == obj) {
7894 fTreeIndex = nullptr;
7895 }
7896 if (fAliases == obj) {
7897 fAliases = nullptr;
7898 } else if (fAliases) {
7900 }
7901 if (fFriends == obj) {
7902 fFriends = nullptr;
7903 } else if (fFriends) {
7905 }
7906}
7907
7908////////////////////////////////////////////////////////////////////////////////
7909/// Refresh contents of this tree and its branches from the current status on disk.
7910///
7911/// One can call this function in case the tree file is being
7912/// updated by another process.
7914void TTree::Refresh()
7915{
7916 if (!fDirectory->GetFile()) {
7917 return;
7918 }
7920 fDirectory->Remove(this);
7922 if (!tree) {
7923 return;
7924 }
7925 //copy info from tree header into this Tree
7926 fEntries = 0;
7927 fNClusterRange = 0;
7929
7930 fAutoSave = tree->fAutoSave;
7931 fEntries = tree->fEntries;
7932 fTotBytes = tree->GetTotBytes();
7933 fZipBytes = tree->GetZipBytes();
7934 fSavedBytes = tree->fSavedBytes;
7935 fTotalBuffers = tree->fTotalBuffers.load();
7936
7937 //loop on all branches and update them
7938 Int_t nleaves = fLeaves.GetEntriesFast();
7939 for (Int_t i = 0; i < nleaves; i++) {
7940 TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
7941 TBranch* branch = (TBranch*) leaf->GetBranch();
7942 branch->Refresh(tree->GetBranch(branch->GetName()));
7943 }
7945 fDirectory->Append(this);
7946 delete tree;
7947 tree = 0;
7948}
7949
7950////////////////////////////////////////////////////////////////////////////////
7951/// Record a TFriendElement that we need to warn when the chain switches to
7952/// a new file (typically this is because this chain is a friend of another
7953/// TChain)
7956{
7957 if (!fExternalFriends)
7958 fExternalFriends = new TList();
7959 fExternalFriends->Add(fe);
7960}
7961
7962
7963////////////////////////////////////////////////////////////////////////////////
7964/// Removes external friend
7967{
7969}
7970
7971
7972////////////////////////////////////////////////////////////////////////////////
7973/// Remove a friend from the list of friends.
7975void TTree::RemoveFriend(TTree* oldFriend)
7976{
7977 // We already have been visited while recursively looking
7978 // through the friends tree, let return
7980 return;
7981 }
7982 if (!fFriends) {
7983 return;
7984 }
7985 TFriendLock lock(this, kRemoveFriend);
7986 TIter nextf(fFriends);
7987 TFriendElement* fe = 0;
7988 while ((fe = (TFriendElement*) nextf())) {
7989 TTree* friend_t = fe->GetTree();
7990 if (friend_t == oldFriend) {
7991 fFriends->Remove(fe);
7992 delete fe;
7993 fe = 0;
7994 }
7995 }
7996}
7997
7998////////////////////////////////////////////////////////////////////////////////
7999/// Reset baskets, buffers and entries count in all branches and leaves.
8002{
8003 fNotify = 0;
8004 fEntries = 0;
8005 fNClusterRange = 0;
8006 fTotBytes = 0;
8007 fZipBytes = 0;
8008 fFlushedBytes = 0;
8009 fSavedBytes = 0;
8010 fTotalBuffers = 0;
8011 fChainOffset = 0;
8012 fReadEntry = -1;
8013
8014 delete fTreeIndex;
8015 fTreeIndex = 0;
8016
8018 for (Int_t i = 0; i < nb; ++i) {
8019 TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
8020 branch->Reset(option);
8021 }
8022
8023 if (fBranchRef) {
8024 fBranchRef->Reset();
8025 }
8026}
8027
8028////////////////////////////////////////////////////////////////////////////////
8029/// Resets the state of this TTree after a merge (keep the customization but
8030/// forget the data).
8033{
8034 fEntries = 0;
8035 fNClusterRange = 0;
8036 fTotBytes = 0;
8037 fZipBytes = 0;
8038 fSavedBytes = 0;
8039 fFlushedBytes = 0;
8040 fTotalBuffers = 0;
8041 fChainOffset = 0;
8042 fReadEntry = -1;
8043
8044 delete fTreeIndex;
8045 fTreeIndex = 0;
8046
8048 for (Int_t i = 0; i < nb; ++i) {
8049 TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
8050 branch->ResetAfterMerge(info);
8051 }
8052
8053 if (fBranchRef) {
8055 }
8056}
8057
8058////////////////////////////////////////////////////////////////////////////////
8059/// Tell all of our branches to set their addresses to zero.
8060///
8061/// Note: If any of our branches own any objects, they are deleted.
8064{
8065 if (br && br->GetTree()) {
8066 br->ResetAddress();
8067 }
8068}
8069
8070////////////////////////////////////////////////////////////////////////////////
8071/// Tell all of our branches to drop their current objects and allocate new ones.
8074{
8075 TObjArray* branches = GetListOfBranches();
8076 Int_t nbranches = branches->GetEntriesFast();
8077 for (Int_t i = 0; i < nbranches; ++i) {
8078 TBranch* branch = (TBranch*) branches->UncheckedAt(i);
8079 branch->ResetAddress();
8080 }
8081}
8082
8083////////////////////////////////////////////////////////////////////////////////
8084/// Loop over tree entries and print entries passing selection.
8085///
8086/// - If varexp is 0 (or "") then print only first 8 columns.
8087/// - If varexp = "*" print all columns.
8088///
8089/// Otherwise a columns selection can be made using "var1:var2:var3".
8090/// \see TTreePlayer::Scan for more information
8092Long64_t TTree::Scan(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
8093{
8094 GetPlayer();
8095 if (fPlayer) {
8096 return fPlayer->Scan(varexp, selection, option, nentries, firstentry);
8097 }
8098 return -1;
8099}
8100
8101////////////////////////////////////////////////////////////////////////////////
8102/// Set a tree variable alias.
8103///
8104/// Set an alias for an expression/formula based on the tree 'variables'.
8105///
8106/// The content of 'aliasName' can be used in TTreeFormula (i.e. TTree::Draw,
8107/// TTree::Scan, TTreeViewer) and will be evaluated as the content of
8108/// 'aliasFormula'.
8109///
8110/// If the content of 'aliasFormula' only contains symbol names, periods and
8111/// array index specification (for example event.fTracks[3]), then
8112/// the content of 'aliasName' can be used as the start of symbol.
8113///
8114/// If the alias 'aliasName' already existed, it is replaced by the new
8115/// value.
8116///
8117/// When being used, the alias can be preceded by an eventual 'Friend Alias'
8118/// (see TTree::GetFriendAlias)
8119///
8120/// Return true if it was added properly.
8121///
8122/// For example:
8123/// ~~~ {.cpp}
8124/// tree->SetAlias("x1","(tdc1[1]-tdc1[0])/49");
8125/// tree->SetAlias("y1","(tdc1[3]-tdc1[2])/47");
8126/// tree->SetAlias("x2","(tdc2[1]-tdc2[0])/49");
8127/// tree->SetAlias("y2","(tdc2[3]-tdc2[2])/47");
8128/// tree->Draw("y2-y1:x2-x1");
8129///
8130/// tree->SetAlias("theGoodTrack","event.fTracks[3]");
8131/// tree->Draw("theGoodTrack.fPx"); // same as "event.fTracks[3].fPx"
8132/// ~~~
8134Bool_t TTree::SetAlias(const char* aliasName, const char* aliasFormula)
8135{
8136 if (!aliasName || !aliasFormula) {
8137 return kFALSE;
8138 }
8139 if (!aliasName[0] || !aliasFormula[0]) {
8140 return kFALSE;
8141 }
8142 if (!fAliases) {
8143 fAliases = new TList;
8144 } else {
8145 TNamed* oldHolder = (TNamed*) fAliases->FindObject(aliasName);
8146 if (oldHolder) {
8147 oldHolder->SetTitle(aliasFormula);
8148 return kTRUE;
8149 }
8150 }
8151 TNamed* holder = new TNamed(aliasName, aliasFormula);
8152 fAliases->Add(holder);
8153 return kTRUE;
8154}
8155
8156////////////////////////////////////////////////////////////////////////////////
8157/// This function may be called at the start of a program to change
8158/// the default value for fAutoFlush.
8159///
8160/// ### CASE 1 : autof > 0
8161///
8162/// autof is the number of consecutive entries after which TTree::Fill will
8163/// flush all branch buffers to disk.
8164///
8165/// ### CASE 2 : autof < 0
8166///
8167/// When filling the Tree the branch buffers will be flushed to disk when
8168/// more than autof bytes have been written to the file. At the first FlushBaskets
8169/// TTree::Fill will replace fAutoFlush by the current value of fEntries.
8170///
8171/// Calling this function with autof<0 is interesting when it is hard to estimate
8172/// the size of one entry. This value is also independent of the Tree.
8173///
8174/// The Tree is initialized with fAutoFlush=-30000000, ie that, by default,
8175/// the first AutoFlush will be done when 30 MBytes of data are written to the file.
8176///
8177/// ### CASE 3 : autof = 0
8178///
8179/// The AutoFlush mechanism is disabled.
8180///
8181/// Flushing the buffers at regular intervals optimize the location of
8182/// consecutive entries on the disk by creating clusters of baskets.
8183///
8184/// A cluster of baskets is a set of baskets that contains all
8185/// the data for a (consecutive) set of entries and that is stored
8186/// consecutively on the disk. When reading all the branches, this
8187/// is the minimum set of baskets that the TTreeCache will read.
8189void TTree::SetAutoFlush(Long64_t autof /* = -30000000 */ )
8190{
8191 // Implementation note:
8192 //
8193 // A positive value of autoflush determines the size (in number of entries) of
8194 // a cluster of baskets.
8195 //
8196 // If the value of autoflush is changed over time (this happens in
8197 // particular when the TTree results from fast merging many trees),
8198 // we record the values of fAutoFlush in the data members:
8199 // fClusterRangeEnd and fClusterSize.
8200 // In the code we refer to a range of entries where the size of the
8201 // cluster of baskets is the same (i.e the value of AutoFlush was
8202 // constant) is called a ClusterRange.
8203 //
8204 // The 2 arrays (fClusterRangeEnd and fClusterSize) have fNClusterRange
8205 // active (used) values and have fMaxClusterRange allocated entries.
8206 //
8207 // fClusterRangeEnd contains the last entries number of a cluster range.
8208 // In particular this means that the 'next' cluster starts at fClusterRangeEnd[]+1
8209 // fClusterSize contains the size in number of entries of all the cluster
8210 // within the given range.
8211 // The last range (and the only one if fNClusterRange is zero) start at
8212 // fNClusterRange[fNClusterRange-1]+1 and ends at the end of the TTree. The
8213 // size of the cluster in this range is given by the value of fAutoFlush.
8214 //
8215 // For example printing the beginning and end of each the ranges can be done by:
8216 //
8217 // Printf("%-16s %-16s %-16s %5s",
8218 // "Cluster Range #", "Entry Start", "Last Entry", "Size");
8219 // Int_t index= 0;
8220 // Long64_t clusterRangeStart = 0;
8221 // if (fNClusterRange) {
8222 // for( ; index < fNClusterRange; ++index) {
8223 // Printf("%-16d %-16lld %-16lld %5lld",
8224 // index, clusterRangeStart, fClusterRangeEnd[index], fClusterSize[index]);
8225 // clusterRangeStart = fClusterRangeEnd[index] + 1;
8226 // }
8227 // }
8228 // Printf("%-16d %-16lld %-16lld %5lld",
8229 // index, prevEntry, fEntries - 1, fAutoFlush);
8230 //
8231
8232 // Note: We store the entry number corresponding to the end of the cluster
8233 // rather than its start in order to avoid using the array if the cluster
8234 // size never varies (If there is only one value of AutoFlush for the whole TTree).
8235
8236 if( fAutoFlush != autof) {
8237 if ((fAutoFlush > 0 || autof > 0) && fFlushedBytes) {
8238 // The mechanism was already enabled, let's record the previous
8239 // cluster if needed.
8241 }
8242 fAutoFlush = autof;
8243 }
8244}
8245
8246////////////////////////////////////////////////////////////////////////////////
8247/// Mark the previous event as being at the end of the event cluster.
8248///
8249/// So, if fEntries is set to 10 (and this is the first cluster) when MarkEventCluster
8250/// is called, then the first cluster has 9 events.
8252{
8253 if (!fEntries) return;
8254
8255 if ( (fNClusterRange+1) > fMaxClusterRange ) {
8256 if (fMaxClusterRange) {
8257 // Resize arrays to hold a larger event cluster.
8258 Int_t newsize = TMath::Max(10,Int_t(2*fMaxClusterRange));
8260 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
8262 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
8263 fMaxClusterRange = newsize;
8264 } else {
8265 // Cluster ranges have never been initialized; create them now.
8266 fMaxClusterRange = 2;
8269 }
8270 }
8272 // If we are auto-flushing, then the cluster size is the same as the current auto-flush setting.
8273 if (fAutoFlush > 0) {
8274 // Even if the user triggers MarkEventRange prior to fAutoFlush being present, the TClusterIterator
8275 // will appropriately go to the next event range.
8277 // Otherwise, assume there is one cluster per event range (e.g., user is manually controlling the flush).
8278 } else if (fNClusterRange == 0) {
8280 } else {
8282 }
8284}
8285
8286/// Estimate the median cluster size for the TTree.
8287/// This value provides e.g. a reasonable cache size default if other heuristics fail.
8288/// Clusters with size 0 and the very last cluster range, that might not have been committed to fClusterSize yet,
8289/// are ignored for the purposes of the calculation.
8291{
8292 std::vector<Long64_t> clusterSizesPerRange;
8293 clusterSizesPerRange.reserve(fNClusterRange);
8294
8295 // We ignore cluster sizes of 0 for the purposes of this function.
8296 // We also ignore the very last cluster range which might not have been committed to fClusterSize.
8297 std::copy_if(fClusterSize, fClusterSize + fNClusterRange, std::back_inserter(clusterSizesPerRange),
8298 [](Long64_t size) { return size != 0; });
8299
8300 std::vector<double> nClustersInRange; // we need to store doubles because of the signature of TMath::Median
8301 nClustersInRange.reserve(clusterSizesPerRange.size());
8302
8303 auto clusterRangeStart = 0ll;
8304 for (int i = 0; i < fNClusterRange; ++i) {
8305 const auto size = fClusterSize[i];
8306 R__ASSERT(size >= 0);
8307 if (fClusterSize[i] == 0)
8308 continue;
8309 const auto nClusters = (1 + fClusterRangeEnd[i] - clusterRangeStart) / fClusterSize[i];
8310 nClustersInRange.emplace_back(nClusters);
8311 clusterRangeStart = fClusterRangeEnd[i] + 1;
8312 }
8313
8314 R__ASSERT(nClustersInRange.size() == clusterSizesPerRange.size());
8315 const auto medianClusterSize =
8316 TMath::Median(nClustersInRange.size(), clusterSizesPerRange.data(), nClustersInRange.data());
8317 return medianClusterSize;
8318}
8319
8320////////////////////////////////////////////////////////////////////////////////
8321/// In case of a program crash, it will be possible to recover the data in the
8322/// tree up to the last AutoSave point.
8323/// This function may be called before filling a TTree to specify when the
8324/// branch buffers and TTree header are flushed to disk as part of
8325/// TTree::Fill().
8326/// The default is -300000000, ie the TTree will write data to disk once it
8327/// exceeds 300 MBytes.
8328/// CASE 1: If fAutoSave is positive the watermark is reached when a multiple of
8329/// fAutoSave entries have been filled.
8330/// CASE 2: If fAutoSave is negative the watermark is reached when -fAutoSave
8331/// bytes can be written to the file.
8332/// CASE 3: If fAutoSave is 0, AutoSave() will never be called automatically
8333/// as part of TTree::Fill().
8335void TTree::SetAutoSave(Long64_t autos)
8336{
8337 fAutoSave = autos;
8338}
8339
8340////////////////////////////////////////////////////////////////////////////////
8341/// Set a branch's basket size.
8342///
8343/// bname is the name of a branch.
8344///
8345/// - if bname="*", apply to all branches.
8346/// - if bname="xxx*", apply to all branches with name starting with xxx
8347///
8348/// see TRegexp for wildcarding options
8349/// buffsize = branc basket size
8351void TTree::SetBasketSize(const char* bname, Int_t buffsize)
8352{
8353 Int_t nleaves = fLeaves.GetEntriesFast();
8354 TRegexp re(bname, kTRUE);
8355 Int_t nb = 0;
8356 for (Int_t i = 0; i < nleaves; i++) {
8357 TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
8358 TBranch* branch = (TBranch*) leaf->GetBranch();
8359 TString s = branch->GetName();
8360 if (strcmp(bname, branch->GetName()) && (s.Index(re) == kNPOS)) {
8361 continue;
8362 }
8363 nb++;
8364 branch->SetBasketSize(buffsize);
8365 }
8366 if (!nb) {
8367 Error("SetBasketSize", "unknown branch -> '%s'", bname);
8368 }
8369}
8370
8371////////////////////////////////////////////////////////////////////////////////
8372/// Change branch address, dealing with clone trees properly.
8373/// See TTree::CheckBranchAddressType for the semantic of the return value.
8374///
8375/// Note: See the comments in TBranchElement::SetAddress() for the
8376/// meaning of the addr parameter and the object ownership policy.
8378Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr)
8379{
8380 TBranch* branch = GetBranch(bname);
8381 if (!branch) {
8382 if (ptr) *ptr = 0;
8383 Error("SetBranchAddress", "unknown branch -> %s", bname);
8384 return kMissingBranch;
8385 }
8386 return SetBranchAddressImp(branch,addr,ptr);
8387}
8388
8389////////////////////////////////////////////////////////////////////////////////
8390/// Verify the validity of the type of addr before calling SetBranchAddress.
8391/// See TTree::CheckBranchAddressType for the semantic of the return value.
8392///
8393/// Note: See the comments in TBranchElement::SetAddress() for the
8394/// meaning of the addr parameter and the object ownership policy.
8396Int_t TTree::SetBranchAddress(const char* bname, void* addr, TClass* ptrClass, EDataType datatype, Bool_t isptr)
8397{
8398 return SetBranchAddress(bname, addr, 0, ptrClass, datatype, isptr);
8399}
8400
8401////////////////////////////////////////////////////////////////////////////////
8402/// Verify the validity of the type of addr before calling SetBranchAddress.
8403/// See TTree::CheckBranchAddressType for the semantic of the return value.
8404///
8405/// Note: See the comments in TBranchElement::SetAddress() for the
8406/// meaning of the addr parameter and the object ownership policy.
8408Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr, TClass* ptrClass, EDataType datatype, Bool_t isptr)
8409{
8410 TBranch* branch = GetBranch(bname);
8411 if (!branch) {
8412 if (ptr) *ptr = 0;
8413 Error("SetBranchAddress", "unknown branch -> %s", bname);
8414 return kMissingBranch;
8415 }
8416
8417 Int_t res = CheckBranchAddressType(branch, ptrClass, datatype, isptr);
8418
8419 // This will set the value of *ptr to branch.
8420 if (res >= 0) {
8421 // The check succeeded.
8422 if ((res & kNeedEnableDecomposedObj) && !branch->GetMakeClass())
8423 branch->SetMakeClass(kTRUE);
8424 SetBranchAddressImp(branch,addr,ptr);
8425 } else {
8426 if (ptr) *ptr = 0;
8427 }
8428 return res;
8429}
8430
8431////////////////////////////////////////////////////////////////////////////////
8432/// Change branch address, dealing with clone trees properly.
8433/// See TTree::CheckBranchAddressType for the semantic of the return value.
8434///
8435/// Note: See the comments in TBranchElement::SetAddress() for the
8436/// meaning of the addr parameter and the object ownership policy.
8438Int_t TTree::SetBranchAddressImp(TBranch *branch, void* addr, TBranch** ptr)
8439{
8440 if (ptr) {
8441 *ptr = branch;
8442 }
8443 if (fClones) {
8444 void* oldAddr = branch->GetAddress();
8445 TIter next(fClones);
8446 TTree* clone = 0;
8447 const char *bname = branch->GetName();
8448 while ((clone = (TTree*) next())) {
8449 TBranch* cloneBr = clone->GetBranch(bname);
8450 if (cloneBr && (cloneBr->GetAddress() == oldAddr)) {
8451 cloneBr->SetAddress(addr);
8452 }
8453 }
8454 }
8455 branch->SetAddress(addr);
8456 return kVoidPtr;
8457}
8458
8459////////////////////////////////////////////////////////////////////////////////
8460/// Set branch status to Process or DoNotProcess.
8461///
8462/// When reading a Tree, by default, all branches are read.
8463/// One can speed up considerably the analysis phase by activating
8464/// only the branches that hold variables involved in a query.
8465///
8466/// bname is the name of a branch.
8467///
8468/// - if bname="*", apply to all branches.
8469/// - if bname="xxx*", apply to all branches with name starting with xxx
8470///
8471/// see TRegexp for wildcarding options
8472///
8473/// - status = 1 branch will be processed
8474/// - = 0 branch will not be processed
8475///
8476/// Example:
8477///
8478/// Assume a tree T with sub-branches a,b,c,d,e,f,g,etc..
8479/// when doing T.GetEntry(i) all branches are read for entry i.
8480/// to read only the branches c and e, one can do
8481/// ~~~ {.cpp}
8482/// T.SetBranchStatus("*",0); //disable all branches
8483/// T.SetBranchStatus("c",1);
8484/// T.setBranchStatus("e",1);
8485/// T.GetEntry(i);
8486/// ~~~
8487/// bname is interpreted as a wild-carded TRegexp (see TRegexp::MakeWildcard).
8488/// Thus, "a*b" or "a.*b" matches branches starting with "a" and ending with
8489/// "b", but not any other branch with an "a" followed at some point by a
8490/// "b". For this second behavior, use "*a*b*". Note that TRegExp does not
8491/// support '|', and so you cannot select, e.g. track and shower branches
8492/// with "track|shower".
8493///
8494/// __WARNING! WARNING! WARNING!__
8495///
8496/// SetBranchStatus is matching the branch based on match of the branch
8497/// 'name' and not on the branch hierarchy! In order to be able to
8498/// selectively enable a top level object that is 'split' you need to make
8499/// sure the name of the top level branch is prefixed to the sub-branches'
8500/// name (by adding a dot ('.') at the end of the Branch creation and use the
8501/// corresponding bname.
8502///
8503/// I.e If your Tree has been created in split mode with a parent branch "parent."
8504/// (note the trailing dot).
8505/// ~~~ {.cpp}
8506/// T.SetBranchStatus("parent",1);
8507/// ~~~
8508/// will not activate the sub-branches of "parent". You should do:
8509/// ~~~ {.cpp}
8510/// T.SetBranchStatus("parent*",1);
8511/// ~~~
8512/// Without the trailing dot in the branch creation you have no choice but to
8513/// call SetBranchStatus explicitly for each of the sub branches.
8514///
8515/// An alternative to this function is to read directly and only
8516/// the interesting branches. Example:
8517/// ~~~ {.cpp}
8518/// TBranch *brc = T.GetBranch("c");
8519/// TBranch *bre = T.GetBranch("e");
8520/// brc->GetEntry(i);
8521/// bre->GetEntry(i);
8522/// ~~~
8523/// If found is not 0, the number of branch(es) found matching the regular
8524/// expression is returned in *found AND the error message 'unknown branch'
8525/// is suppressed.
8527void TTree::SetBranchStatus(const char* bname, Bool_t status, UInt_t* found)
8528{
8529 // We already have been visited while recursively looking
8530 // through the friends tree, let return
8532 return;
8533 }
8534
8535 if (!bname || !*bname) {
8536 Error("SetBranchStatus", "Input regexp is an empty string: no match against branch names will be attempted.");
8537 return;
8538 }
8539
8540 TBranch *branch, *bcount, *bson;
8541 TLeaf *leaf, *leafcount;
8542
8543 Int_t i,j;
8544 Int_t nleaves = fLeaves.GetEntriesFast();
8545 TRegexp re(bname,kTRUE);
8546 Int_t nb = 0;
8547
8548 // first pass, loop on all branches
8549 // for leafcount branches activate/deactivate in function of status
8550 for (i=0;i<nleaves;i++) {
8551 leaf = (TLeaf*)fLeaves.UncheckedAt(i);
8552 branch = (TBranch*)leaf->GetBranch();
8553 TString s = branch->GetName();
8554 if (strcmp(bname,"*")) { //Regexp gives wrong result for [] in name
8555 TString longname;
8556 longname.Form("%s.%s",GetName(),branch->GetName());
8557 if (strcmp(bname,branch->GetName())
8558 && longname != bname
8559 && s.Index(re) == kNPOS) continue;
8560 }
8561 nb++;
8562 if (status) branch->ResetBit(kDoNotProcess);
8563 else branch->SetBit(kDoNotProcess);
8564 leafcount = leaf->GetLeafCount();
8565 if (leafcount) {
8566 bcount = leafcount->GetBranch();
8567 if (status) bcount->ResetBit(kDoNotProcess);
8568 else bcount->SetBit(kDoNotProcess);
8569 }
8570 }
8571 if (nb==0 && !strchr(bname,'*')) {
8572 branch = GetBranch(bname);
8573 if (branch) {
8574 if (status) branch->ResetBit(kDoNotProcess);
8575 else branch->SetBit(kDoNotProcess);
8576 ++nb;
8577 }
8578 }
8579
8580 //search in list of friends
8581 UInt_t foundInFriend = 0;
8582 if (fFriends) {
8583 TFriendLock lock(this,kSetBranchStatus);
8584 TIter nextf(fFriends);
8585 TFriendElement *fe;
8586 TString name;
8587 while ((fe = (TFriendElement*)nextf())) {
8588 TTree *t = fe->GetTree();
8589 if (!t) continue;
8590
8591 // If the alias is present replace it with the real name.
8592 const char *subbranch = strstr(bname,fe->GetName());
8593 if (subbranch!=bname) subbranch = nullptr;
8594 if (subbranch) {
8595 subbranch += strlen(fe->GetName());
8596 if ( *subbranch != '.' ) subbranch = nullptr;
8597 else subbranch ++;
8598 }
8599 if (subbranch) {
8600 name.Form("%s.%s",t->GetName(),subbranch);
8601 } else {
8602 name = bname;
8603 }
8604 t->SetBranchStatus(name,status, &foundInFriend);
8605 }
8606 }
8607 if (!nb && !foundInFriend) {
8608 if (!found) {
8609 if (status) {
8610 if (strchr(bname,'*') != 0)
8611 Error("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
8612 else
8613 Error("SetBranchStatus", "unknown branch -> %s", bname);
8614 } else {
8615 if (strchr(bname,'*') != 0)
8616 Warning("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
8617 else
8618 Warning("SetBranchStatus", "unknown branch -> %s", bname);
8619 }
8620 }
8621 return;
8622 }
8623 if (found) *found = nb + foundInFriend;
8624
8625 // second pass, loop again on all branches
8626 // activate leafcount branches for active branches only
8627 for (i = 0; i < nleaves; i++) {
8628 leaf = (TLeaf*)fLeaves.UncheckedAt(i);
8629 branch = (TBranch*)leaf->GetBranch();
8630 if (!branch->TestBit(kDoNotProcess)) {
8631 leafcount = leaf->GetLeafCount();
8632 if (leafcount) {
8633 bcount = leafcount->GetBranch();
8634 bcount->ResetBit(kDoNotProcess);
8635 }
8636 } else {
8637 //Int_t nbranches = branch->GetListOfBranches()->GetEntriesFast();
8638 Int_t nbranches = branch->GetListOfBranches()->GetEntries();
8639 for (j=0;j<nbranches;j++) {
8640 bson = (TBranch*)branch->GetListOfBranches()->UncheckedAt(j);
8641 if (!bson) continue;
8642 if (!bson->TestBit(kDoNotProcess)) {
8643 if (bson->GetNleaves() <= 0) continue;
8644 branch->ResetBit(kDoNotProcess);
8645 break;
8646 }
8647 }
8648 }
8649 }
8650}
8651
8652////////////////////////////////////////////////////////////////////////////////
8653/// Set the current branch style. (static function)
8654///
8655/// - style = 0 old Branch
8656/// - style = 1 new Bronch
8659{
8661}
8662
8663////////////////////////////////////////////////////////////////////////////////
8664/// Set maximum size of the file cache .
8665//
8666/// - if cachesize = 0 the existing cache (if any) is deleted.
8667/// - if cachesize = -1 (default) it is set to the AutoFlush value when writing
8668/// the Tree (default is 30 MBytes).
8669///
8670/// Returns:
8671/// - 0 size set, cache was created if possible
8672/// - -1 on error
8675{
8676 // remember that the user has requested an explicit cache setup
8678
8679 return SetCacheSizeAux(kFALSE, cacheSize);
8680}
8681
8682////////////////////////////////////////////////////////////////////////////////
8683/// Set the size of the file cache and create it if possible.
8684///
8685/// If autocache is true:
8686/// this may be an autocreated cache, possibly enlarging an existing
8687/// autocreated cache. The size is calculated. The value passed in cacheSize:
8688/// - cacheSize = 0 make cache if default cache creation is enabled
8689/// - cacheSize = -1 make a default sized cache in any case
8690///
8691/// If autocache is false:
8692/// this is a user requested cache. cacheSize is used to size the cache.
8693/// This cache should never be automatically adjusted.
8694///
8695/// Returns:
8696/// - 0 size set, or existing autosized cache almost large enough.
8697/// (cache was created if possible)
8698/// - -1 on error
8700Int_t TTree::SetCacheSizeAux(Bool_t autocache /* = kTRUE */, Long64_t cacheSize /* = 0 */ )
8701{
8702 if (autocache) {
8703 // used as a once only control for automatic cache setup
8705 }
8706
8707 if (!autocache) {
8708 // negative size means the user requests the default
8709 if (cacheSize < 0) {
8710 cacheSize = GetCacheAutoSize(kTRUE);
8711 }
8712 } else {
8713 if (cacheSize == 0) {
8714 cacheSize = GetCacheAutoSize();
8715 } else if (cacheSize < 0) {
8716 cacheSize = GetCacheAutoSize(kTRUE);
8717 }
8718 }
8719
8721 if (!file || GetTree() != this) {
8722 // if there's no file or we are not a plain tree (e.g. if we're a TChain)
8723 // do not create a cache, only record the size if one was given
8724 if (!autocache) {
8725 fCacheSize = cacheSize;
8726 }
8727 if (GetTree() != this) {
8728 return 0;
8729 }
8730 if (!autocache && cacheSize>0) {
8731 Warning("SetCacheSizeAux", "A TTreeCache could not be created because the TTree has no file");
8732 }
8733 return 0;
8734 }
8735
8736 // Check for an existing cache
8738 if (pf) {
8739 if (autocache) {
8740 // reset our cache status tracking in case existing cache was added
8741 // by the user without using one of the TTree methods
8742 fCacheSize = pf->GetBufferSize();
8744
8745 if (fCacheUserSet) {
8746 // existing cache was created by the user, don't change it
8747 return 0;
8748 }
8749 } else {
8750 // update the cache to ensure it records the user has explicitly
8751 // requested it
8753 }
8754
8755 // if we're using an automatically calculated size and the existing
8756 // cache is already almost large enough don't resize
8757 if (autocache && Long64_t(0.80*cacheSize) < fCacheSize) {
8758 // already large enough
8759 return 0;
8760 }
8761
8762 if (cacheSize == fCacheSize) {
8763 return 0;
8764 }
8765
8766 if (cacheSize == 0) {
8767 // delete existing cache
8768 pf->WaitFinishPrefetch();
8769 file->SetCacheRead(0,this);
8770 delete pf;
8771 pf = 0;
8772 } else {
8773 // resize
8774 Int_t res = pf->SetBufferSize(cacheSize);
8775 if (res < 0) {
8776 return -1;
8777 }
8778 }
8779 } else {
8780 // no existing cache
8781 if (autocache) {
8782 if (fCacheUserSet) {
8783 // value was already set manually.
8784 if (fCacheSize == 0) return 0;
8785 // Expected a cache should exist; perhaps the user moved it
8786 // Do nothing more here.
8787 if (cacheSize) {
8788 Error("SetCacheSizeAux", "Not setting up an automatically sized TTreeCache because of missing cache previously set");
8789 }
8790 return -1;
8791 }
8792 }
8793 }
8794
8795 fCacheSize = cacheSize;
8796 if (cacheSize == 0 || pf) {
8797 return 0;
8798 }
8799
8800#ifdef R__USE_IMT
8801 if(TTreeCacheUnzip::IsParallelUnzip() && file->GetCompressionLevel() > 0)
8802 pf = new TTreeCacheUnzip(this, cacheSize);
8803 else
8804#endif
8805 pf = new TTreeCache(this, cacheSize);
8806
8807 pf->SetAutoCreated(autocache);
8808
8809 return 0;
8810}
8811
8812////////////////////////////////////////////////////////////////////////////////
8813///interface to TTreeCache to set the cache entry range
8814///
8815/// Returns:
8816/// - 0 entry range set
8817/// - -1 on error
8820{
8821 if (!GetTree()) {
8822 if (LoadTree(0)<0) {
8823 Error("SetCacheEntryRange","Could not load a tree");
8824 return -1;
8825 }
8826 }
8827 if (GetTree()) {
8828 if (GetTree() != this) {
8829 return GetTree()->SetCacheEntryRange(first, last);
8830 }
8831 } else {
8832 Error("SetCacheEntryRange", "No tree is available. Could not set cache entry range");
8833 return -1;
8834 }
8835
8836 TFile *f = GetCurrentFile();
8837 if (!f) {
8838 Error("SetCacheEntryRange", "No file is available. Could not set cache entry range");
8839 return -1;
8840 }
8842 if (!tc) {
8843 Error("SetCacheEntryRange", "No cache is available. Could not set entry range");
8844 return -1;
8845 }
8846 tc->SetEntryRange(first,last);
8847 return 0;
8848}
8849
8850////////////////////////////////////////////////////////////////////////////////
8851/// Interface to TTreeCache to set the number of entries for the learning phase
8854{
8856}
8857
8858////////////////////////////////////////////////////////////////////////////////
8859/// Enable/Disable circularity for this tree.
8860///
8861/// if maxEntries > 0 a maximum of maxEntries is kept in one buffer/basket
8862/// per branch in memory.
8863/// Note that when this function is called (maxEntries>0) the Tree
8864/// must be empty or having only one basket per branch.
8865/// if maxEntries <= 0 the tree circularity is disabled.
8866///
8867/// #### NOTE 1:
8868/// Circular Trees are interesting in online real time environments
8869/// to store the results of the last maxEntries events.
8870/// #### NOTE 2:
8871/// Calling SetCircular with maxEntries <= 0 is necessary before
8872/// merging circular Trees that have been saved on files.
8873/// #### NOTE 3:
8874/// SetCircular with maxEntries <= 0 is automatically called
8875/// by TChain::Merge
8876/// #### NOTE 4:
8877/// A circular Tree can still be saved in a file. When read back,
8878/// it is still a circular Tree and can be filled again.
8880void TTree::SetCircular(Long64_t maxEntries)
8881{
8882 if (maxEntries <= 0) {
8883 // Disable circularity.
8884 fMaxEntries = 1000000000;
8885 fMaxEntries *= 1000;
8887 //in case the Tree was originally created in gROOT, the branch
8888 //compression level was set to -1. If the Tree is now associated to
8889 //a file, reset the compression level to the file compression level
8890 if (fDirectory) {
8891 TFile* bfile = fDirectory->GetFile();
8893 if (bfile) {
8894 compress = bfile->GetCompressionSettings();
8895 }
8897 for (Int_t i = 0; i < nb; i++) {
8898 TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
8899 branch->SetCompressionSettings(compress);
8900 }
8901 }
8902 } else {
8903 // Enable circularity.
8904 fMaxEntries = maxEntries;
8906 }
8907}
8908
8909////////////////////////////////////////////////////////////////////////////////
8910/// Set the debug level and the debug range.
8911///
8912/// For entries in the debug range, the functions TBranchElement::Fill
8913/// and TBranchElement::GetEntry will print the number of bytes filled
8914/// or read for each branch.
8916void TTree::SetDebug(Int_t level, Long64_t min, Long64_t max)
8917{
8918 fDebug = level;
8919 fDebugMin = min;
8920 fDebugMax = max;
8921}
8922
8923////////////////////////////////////////////////////////////////////////////////
8924/// Update the default value for the branch's fEntryOffsetLen.
8925/// If updateExisting is true, also update all the existing branches.
8926/// If newdefault is less than 10, the new default value will be 10.
8928void TTree::SetDefaultEntryOffsetLen(Int_t newdefault, Bool_t updateExisting)
8929{
8930 if (newdefault < 10) {
8931 newdefault = 10;
8932 }
8933 fDefaultEntryOffsetLen = newdefault;
8934 if (updateExisting) {
8935 TIter next( GetListOfBranches() );
8936 TBranch *b;
8937 while ( ( b = (TBranch*)next() ) ) {
8938 b->SetEntryOffsetLen( newdefault, kTRUE );
8939 }
8940 if (fBranchRef) {
8941 fBranchRef->SetEntryOffsetLen( newdefault, kTRUE );
8942 }
8943 }
8944}
8945
8946////////////////////////////////////////////////////////////////////////////////
8947/// Change the tree's directory.
8948///
8949/// Remove reference to this tree from current directory and
8950/// add reference to new directory dir. The dir parameter can
8951/// be 0 in which case the tree does not belong to any directory.
8952///
8955{
8956 if (fDirectory == dir) {
8957 return;
8958 }
8959 if (fDirectory) {
8960 fDirectory->Remove(this);
8961
8962 // Delete or move the file cache if it points to this Tree
8964 MoveReadCache(file,dir);
8965 }
8966 fDirectory = dir;
8967 if (fDirectory) {
8968 fDirectory->Append(this);
8969 }
8970 TFile* file = 0;
8971 if (fDirectory) {
8972 file = fDirectory->GetFile();
8973 }
8974 if (fBranchRef) {
8976 }
8977 TBranch* b = 0;
8978 TIter next(GetListOfBranches());
8979 while((b = (TBranch*) next())) {
8980 b->SetFile(file);
8981 }
8982}
8983
8984////////////////////////////////////////////////////////////////////////////////
8985/// Change number of entries in the tree.
8986///
8987/// If n >= 0, set number of entries in the tree = n.
8988///
8989/// If n < 0, set number of entries in the tree to match the
8990/// number of entries in each branch. (default for n is -1)
8991///
8992/// This function should be called only when one fills each branch
8993/// independently via TBranch::Fill without calling TTree::Fill.
8994/// Calling TTree::SetEntries() make sense only if the number of entries
8995/// in each branch is identical, a warning is issued otherwise.
8996/// The function returns the number of entries.
8997///
9000{
9001 // case 1 : force number of entries to n
9002 if (n >= 0) {
9003 fEntries = n;
9004 return n;
9005 }
9006
9007 // case 2; compute the number of entries from the number of entries in the branches
9008 TBranch* b(nullptr), *bMin(nullptr), *bMax(nullptr);
9009 Long64_t nMin = kMaxEntries;
9010 Long64_t nMax = 0;
9011 TIter next(GetListOfBranches());
9012 while((b = (TBranch*) next())){
9013 Long64_t n2 = b->GetEntries();
9014 if (!bMin || n2 < nMin) {
9015 nMin = n2;
9016 bMin = b;
9017 }
9018 if (!bMax || n2 > nMax) {
9019 nMax = n2;
9020 bMax = b;
9021 }
9022 }
9023 if (bMin && nMin != nMax) {
9024 Warning("SetEntries", "Tree branches have different numbers of entries, eg %s has %lld entries while %s has %lld entries.",
9025 bMin->GetName(), nMin, bMax->GetName(), nMax);
9026 }
9027 fEntries = nMax;
9028 return fEntries;
9029}
9030
9031////////////////////////////////////////////////////////////////////////////////
9032/// Set an EntryList
9034void TTree::SetEntryList(TEntryList *enlist, Option_t * /*opt*/)
9035{
9036 if (fEntryList) {
9037 //check if the previous entry list is owned by the tree
9039 delete fEntryList;
9040 }
9041 }
9042 fEventList = 0;
9043 if (!enlist) {
9044 fEntryList = 0;
9045 return;
9046 }
9047 fEntryList = enlist;
9048 fEntryList->SetTree(this);
9049
9050}
9051
9052////////////////////////////////////////////////////////////////////////////////
9053/// This function transfroms the given TEventList into a TEntryList
9054/// The new TEntryList is owned by the TTree and gets deleted when the tree
9055/// is deleted. This TEntryList can be returned by GetEntryList() function.
9057void TTree::SetEventList(TEventList *evlist)
9058{
9059 fEventList = evlist;
9060 if (fEntryList){
9062 TEntryList *tmp = fEntryList;
9063 fEntryList = 0; // Avoid problem with RecursiveRemove.
9064 delete tmp;
9065 } else {
9066 fEntryList = 0;
9067 }
9068 }
9069
9070 if (!evlist) {
9071 fEntryList = 0;
9072 fEventList = 0;
9073 return;
9074 }
9075
9076 fEventList = evlist;
9077 char enlistname[100];
9078 snprintf(enlistname,100, "%s_%s", evlist->GetName(), "entrylist");
9079 fEntryList = new TEntryList(enlistname, evlist->GetTitle());
9080 fEntryList->SetDirectory(0); // We own this.
9081 Int_t nsel = evlist->GetN();
9082 fEntryList->SetTree(this);
9083 Long64_t entry;
9084 for (Int_t i=0; i<nsel; i++){
9085 entry = evlist->GetEntry(i);
9086 fEntryList->Enter(entry);
9087 }
9090}
9091
9092////////////////////////////////////////////////////////////////////////////////
9093/// Set number of entries to estimate variable limits.
9094/// If n is -1, the estimate is set to be the current maximum
9095/// for the tree (i.e. GetEntries() + 1)
9096/// If n is less than -1, the behavior is undefined.
9098void TTree::SetEstimate(Long64_t n /* = 1000000 */)
9099{
9100 if (n == 0) {
9101 n = 10000;
9102 } else if (n < 0) {
9103 n = fEntries - n;
9104 }
9105 fEstimate = n;
9106 GetPlayer();
9107 if (fPlayer) {
9109 }
9110}
9111
9112////////////////////////////////////////////////////////////////////////////////
9113/// Provide the end-user with the ability to enable/disable various experimental
9114/// IO features for this TTree.
9115///
9116/// Returns all the newly-set IO settings.
9119{
9120 // Purposely ignore all unsupported bits; TIOFeatures implementation already warned the user about the
9121 // error of their ways; this is just a safety check.
9122 UChar_t featuresRequested = features.GetFeatures() & static_cast<UChar_t>(TBasket::EIOBits::kSupported);
9123
9124 UChar_t curFeatures = fIOFeatures.GetFeatures();
9125 UChar_t newFeatures = ~curFeatures & featuresRequested;
9126 curFeatures |= newFeatures;
9127 fIOFeatures.Set(curFeatures);
9128
9129 ROOT::TIOFeatures newSettings(newFeatures);
9130 return newSettings;
9131}
9132
9133////////////////////////////////////////////////////////////////////////////////
9134/// Set fFileNumber to number.
9135/// fFileNumber is used by TTree::Fill to set the file name
9136/// for a new file to be created when the current file exceeds fgTreeMaxSize.
9137/// (see TTree::ChangeFile)
9138/// if fFileNumber=10, the new file name will have a suffix "_11",
9139/// ie, fFileNumber is incremented before setting the file name
9141void TTree::SetFileNumber(Int_t number)
9142{
9143 if (fFileNumber < 0) {
9144 Warning("SetFileNumber", "file number must be positive. Set to 0");
9145 fFileNumber = 0;
9146 return;
9147 }
9148 fFileNumber = number;
9149}
9150
9151////////////////////////////////////////////////////////////////////////////////
9152/// Set all the branches in this TTree to be in decomposed object mode
9153/// (also known as MakeClass mode).
9154///
9155/// For MakeClass mode 0, the TTree expects the address where the data is stored
9156/// to be set by either the user or the TTree to the address of a full object
9157/// through the top level branch.
9158/// For MakeClass mode 1, this address is expected to point to a numerical type
9159/// or C-style array (variable or not) of numerical type, representing the
9160/// primitive data members.
9161/// The function's primary purpose is to allow the user to access the data
9162/// directly with numerical type variable rather than having to have the original
9163/// set of classes (or a reproduction thereof).
9165void TTree::SetMakeClass(Int_t make)
9166{
9167 fMakeClass = make;
9168
9170 for (Int_t i = 0; i < nb; ++i) {
9171 TBranch* branch = (TBranch*) fBranches.UncheckedAt(i);
9172 branch->SetMakeClass(make);
9173 }
9174}
9175
9176////////////////////////////////////////////////////////////////////////////////
9177/// Set the maximum size in bytes of a Tree file (static function).
9178/// The default size is 100000000000LL, ie 100 Gigabytes.
9179///
9180/// In TTree::Fill, when the file has a size > fgMaxTreeSize,
9181/// the function closes the current file and starts writing into
9182/// a new file with a name of the style "file_1.root" if the original
9183/// requested file name was "file.root".
9185void TTree::SetMaxTreeSize(Long64_t maxsize)
9186{
9187 fgMaxTreeSize = maxsize;
9188}
9189
9190////////////////////////////////////////////////////////////////////////////////
9191/// Change the name of this tree.
9193void TTree::SetName(const char* name)
9194{
9195 if (gPad) {
9196 gPad->Modified();
9197 }
9198 // Trees are named objects in a THashList.
9199 // We must update hashlists if we change the name.
9200 TFile *file = 0;
9201 TTreeCache *pf = 0;
9202 if (fDirectory) {
9203 fDirectory->Remove(this);
9204 if ((file = GetCurrentFile())) {
9205 pf = GetReadCache(file);
9206 file->SetCacheRead(0,this,TFile::kDoNotDisconnect);
9207 }
9208 }
9209 // This changes our hash value.
9210 fName = name;
9211 if (fDirectory) {
9212 fDirectory->Append(this);
9213 if (pf) {
9214 file->SetCacheRead(pf,this,TFile::kDoNotDisconnect);
9215 }
9216 }
9217}
9219void TTree::SetNotify(TObject *obj)
9220{
9221 if (obj && fNotify && dynamic_cast<TNotifyLinkBase *>(fNotify)) {
9222 auto *oldLink = static_cast<TNotifyLinkBase *>(fNotify);
9223 auto *newLink = dynamic_cast<TNotifyLinkBase *>(obj);
9224 if (!newLink) {
9225 Warning("TTree::SetNotify",
9226 "The tree or chain already has a fNotify registered and it is a TNotifyLink, while the new object is "
9227 "not a TNotifyLink. Setting fNotify to the new value will lead to an orphan linked list of "
9228 "TNotifyLinks and it is most likely not intended. If this is the intended goal, please call "
9229 "SetNotify(nullptr) first to silence this warning.");
9230 } else if (newLink->GetNext() != oldLink && oldLink->GetNext() != newLink) {
9231 // If newLink->GetNext() == oldLink then we are prepending the new head, as in TNotifyLink::PrependLink
9232 // If oldLink->GetNext() == newLink then we are removing the head of the list, as in TNotifyLink::RemoveLink
9233 // Otherwise newLink and oldLink are unrelated:
9234 Warning("TTree::SetNotify",
9235 "The tree or chain already has a TNotifyLink registered, and the new TNotifyLink `obj` does not link "
9236 "to it. Setting fNotify to the new value will lead to an orphan linked list of TNotifyLinks and it is "
9237 "most likely not intended. If this is the intended goal, please call SetNotify(nullptr) first to "
9238 "silence this warning.");
9239 }
9240 }
9241
9242 fNotify = obj;
9243}
9244
9245////////////////////////////////////////////////////////////////////////////////
9246/// Change the name and title of this tree.
9248void TTree::SetObject(const char* name, const char* title)
9249{
9250 if (gPad) {
9251 gPad->Modified();
9252 }
9253
9254 // Trees are named objects in a THashList.
9255 // We must update hashlists if we change the name
9256 TFile *file = 0;
9257 TTreeCache *pf = 0;
9258 if (fDirectory) {
9259 fDirectory->Remove(this);
9260 if ((file = GetCurrentFile())) {
9261 pf = GetReadCache(file);
9262 file->SetCacheRead(0,this,TFile::kDoNotDisconnect);
9263 }
9264 }
9265 // This changes our hash value.
9266 fName = name;
9267 fTitle = title;
9268 if (fDirectory) {
9269 fDirectory->Append(this);
9270 if (pf) {
9271 file->SetCacheRead(pf,this,TFile::kDoNotDisconnect);
9272 }
9273 }
9274}
9275
9276////////////////////////////////////////////////////////////////////////////////
9277/// Enable or disable parallel unzipping of Tree buffers.
9279void TTree::SetParallelUnzip(Bool_t opt, Float_t RelSize)
9280{
9281#ifdef R__USE_IMT
9282 if (GetTree() == 0) {
9284 if (!GetTree())
9285 return;
9286 }
9287 if (GetTree() != this) {
9288 GetTree()->SetParallelUnzip(opt, RelSize);
9289 return;
9290 }
9292 if (!file)
9293 return;
9294
9296 if (pf && !( opt ^ (nullptr != dynamic_cast<TTreeCacheUnzip*>(pf)))) {
9297 // done with opt and type are in agreement.
9298 return;
9299 }
9300 delete pf;
9301 auto cacheSize = GetCacheAutoSize(kTRUE);
9302 if (opt) {
9303 auto unzip = new TTreeCacheUnzip(this, cacheSize);
9304 unzip->SetUnzipBufferSize( Long64_t(cacheSize * RelSize) );
9305 } else {
9306 pf = new TTreeCache(this, cacheSize);
9307 }
9308#else
9309 (void)opt;
9310 (void)RelSize;
9311#endif
9312}
9313
9314////////////////////////////////////////////////////////////////////////////////
9315/// Set perf stats
9318{
9319 fPerfStats = perf;
9320}
9321
9322////////////////////////////////////////////////////////////////////////////////
9323/// The current TreeIndex is replaced by the new index.
9324/// Note that this function does not delete the previous index.
9325/// This gives the possibility to play with more than one index, e.g.,
9326/// ~~~ {.cpp}
9327/// TVirtualIndex* oldIndex = tree.GetTreeIndex();
9328/// tree.SetTreeIndex(newIndex);
9329/// tree.Draw();
9330/// tree.SetTreeIndex(oldIndex);
9331/// tree.Draw(); etc
9332/// ~~~
9335{
9336 if (fTreeIndex) {
9337 fTreeIndex->SetTree(0);
9338 }
9339 fTreeIndex = index;
9340}
9341
9342////////////////////////////////////////////////////////////////////////////////
9343/// Set tree weight.
9344///
9345/// The weight is used by TTree::Draw to automatically weight each
9346/// selected entry in the resulting histogram.
9347///
9348/// For example the equivalent of:
9349/// ~~~ {.cpp}
9350/// T.Draw("x", "w")
9351/// ~~~
9352/// is:
9353/// ~~~ {.cpp}
9354/// T.SetWeight(w);
9355/// T.Draw("x");
9356/// ~~~
9357/// This function is redefined by TChain::SetWeight. In case of a
9358/// TChain, an option "global" may be specified to set the same weight
9359/// for all trees in the TChain instead of the default behaviour
9360/// using the weights of each tree in the chain (see TChain::SetWeight).
9363{
9364 fWeight = w;
9365}
9366
9367////////////////////////////////////////////////////////////////////////////////
9368/// Print values of all active leaves for entry.
9369///
9370/// - if entry==-1, print current entry (default)
9371/// - if a leaf is an array, a maximum of lenmax elements is printed.
9373void TTree::Show(Long64_t entry, Int_t lenmax)
9374{
9375 if (entry != -1) {
9376 Int_t ret = LoadTree(entry);
9377 if (ret == -2) {
9378 Error("Show()", "Cannot read entry %lld (entry does not exist)", entry);
9379 return;
9380 } else if (ret == -1) {
9381 Error("Show()", "Cannot read entry %lld (I/O error)", entry);
9382 return;
9383 }
9384 ret = GetEntry(entry);
9385 if (ret == -1) {
9386 Error("Show()", "Cannot read entry %lld (I/O error)", entry);
9387 return;
9388 } else if (ret == 0) {
9389 Error("Show()", "Cannot read entry %lld (no data read)", entry);
9390 return;
9391 }
9392 }
9393 printf("======> EVENT:%lld\n", fReadEntry);
9394 TObjArray* leaves = GetListOfLeaves();
9395 Int_t nleaves = leaves->GetEntriesFast();
9396 Int_t ltype;
9397 for (Int_t i = 0; i < nleaves; i++) {
9398 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
9399 TBranch* branch = leaf->GetBranch();
9400 if (branch->TestBit(kDoNotProcess)) {
9401 continue;
9402 }
9403 Int_t len = leaf->GetLen();
9404 if (len <= 0) {
9405 continue;
9406 }
9407 len = TMath::Min(len, lenmax);
9408 if (leaf->IsA() == TLeafElement::Class()) {
9409 leaf->PrintValue(lenmax);
9410 continue;
9411 }
9412 if (branch->GetListOfBranches()->GetEntriesFast() > 0) {
9413 continue;
9414 }
9415 ltype = 10;
9416 if (leaf->IsA() == TLeafF::Class()) {
9417 ltype = 5;
9418 }
9419 if (leaf->IsA() == TLeafD::Class()) {
9420 ltype = 5;
9421 }
9422 if (leaf->IsA() == TLeafC::Class()) {
9423 len = 1;
9424 ltype = 5;
9425 };
9426 printf(" %-15s = ", leaf->GetName());
9427 for (Int_t l = 0; l < len; l++) {
9428 leaf->PrintValue(l);
9429 if (l == (len - 1)) {
9430 printf("\n");
9431 continue;
9432 }
9433 printf(", ");
9434 if ((l % ltype) == 0) {
9435 printf("\n ");
9436 }
9437 }
9438 }
9439}
9440
9441////////////////////////////////////////////////////////////////////////////////
9442/// Start the TTreeViewer on this tree.
9443///
9444/// - ww is the width of the canvas in pixels
9445/// - wh is the height of the canvas in pixels
9447void TTree::StartViewer()
9448{
9449 GetPlayer();
9450 if (fPlayer) {
9451 fPlayer->StartViewer(600, 400);
9452 }
9453}
9454
9455////////////////////////////////////////////////////////////////////////////////
9456/// Stop the cache learning phase
9457///
9458/// Returns:
9459/// - 0 learning phase stopped or not active
9460/// - -1 on error
9463{
9464 if (!GetTree()) {
9465 if (LoadTree(0)<0) {
9466 Error("StopCacheLearningPhase","Could not load a tree");
9467 return -1;
9468 }
9469 }
9470 if (GetTree()) {
9471 if (GetTree() != this) {
9472 return GetTree()->StopCacheLearningPhase();
9473 }
9474 } else {
9475 Error("StopCacheLearningPhase", "No tree is available. Could not stop cache learning phase");
9476 return -1;
9477 }
9478
9479 TFile *f = GetCurrentFile();
9480 if (!f) {
9481 Error("StopCacheLearningPhase", "No file is available. Could not stop cache learning phase");
9482 return -1;
9483 }
9485 if (!tc) {
9486 Error("StopCacheLearningPhase", "No cache is available. Could not stop learning phase");
9487 return -1;
9488 }
9489 tc->StopLearningPhase();
9490 return 0;
9491}
9492
9493////////////////////////////////////////////////////////////////////////////////
9494/// Set the fTree member for all branches and sub branches.
9496static void TBranch__SetTree(TTree *tree, TObjArray &branches)
9497{
9498 Int_t nb = branches.GetEntriesFast();
9499 for (Int_t i = 0; i < nb; ++i) {
9500 TBranch* br = (TBranch*) branches.UncheckedAt(i);
9501 br->SetTree(tree);
9502
9503 Int_t writeBasket = br->GetWriteBasket();
9504 for (Int_t j = writeBasket; j >= 0; --j) {
9505 TBasket *bk = (TBasket*)br->GetListOfBaskets()->UncheckedAt(j);
9506 if (bk) {
9507 tree->IncrementTotalBuffers(bk->GetBufferSize());
9508 }
9509 }
9510
9512 }
9513}
9514
9515////////////////////////////////////////////////////////////////////////////////
9516/// Set the fTree member for all friend elements.
9519{
9520 if (frlist) {
9521 TObjLink *lnk = frlist->FirstLink();
9522 while (lnk) {
9523 TFriendElement *elem = (TFriendElement*)lnk->GetObject();
9524 elem->fParentTree = tree;
9525 lnk = lnk->Next();
9526 }
9527 }
9528}
9529
9530////////////////////////////////////////////////////////////////////////////////
9531/// Stream a class object.
9534{
9535 if (b.IsReading()) {
9536 UInt_t R__s, R__c;
9537 if (fDirectory) {
9538 fDirectory->Remove(this);
9539 //delete the file cache if it points to this Tree
9542 }
9543 fDirectory = 0;
9546 Version_t R__v = b.ReadVersion(&R__s, &R__c);
9547 if (R__v > 4) {
9548 b.ReadClassBuffer(TTree::Class(), this, R__v, R__s, R__c);
9549
9550 fBranches.SetOwner(kTRUE); // True needed only for R__v < 19 and most R__v == 19
9551
9552 if (fBranchRef) fBranchRef->SetTree(this);
9555
9556 if (fTreeIndex) {
9557 fTreeIndex->SetTree(this);
9558 }
9559 if (fIndex.fN) {
9560 Warning("Streamer", "Old style index in this tree is deleted. Rebuild the index via TTree::BuildIndex");
9561 fIndex.Set(0);
9562 fIndexValues.Set(0);
9563 }
9564 if (fEstimate <= 10000) {
9565 fEstimate = 1000000;
9566 }
9567
9568 if (fNClusterRange) {
9569 // The I/O allocated just enough memory to hold the
9570 // current set of ranges.
9572 }
9573
9574 // Throughs calls to `GetCacheAutoSize` or `EnableCache` (for example
9575 // by TTreePlayer::Process, the cache size will be automatically
9576 // determined unless the user explicitly call `SetCacheSize`
9577 fCacheSize = 0;
9579
9581 return;
9582 }
9583 //====process old versions before automatic schema evolution
9584 Stat_t djunk;
9585 Int_t ijunk;
9590 b >> fScanField;
9591 b >> ijunk; fMaxEntryLoop = (Long64_t)ijunk;
9592 b >> ijunk; fMaxVirtualSize = (Long64_t)ijunk;
9593 b >> djunk; fEntries = (Long64_t)djunk;
9594 b >> djunk; fTotBytes = (Long64_t)djunk;
9595 b >> djunk; fZipBytes = (Long64_t)djunk;
9596 b >> ijunk; fAutoSave = (Long64_t)ijunk;
9597 b >> ijunk; fEstimate = (Long64_t)ijunk;
9598 if (fEstimate <= 10000) fEstimate = 1000000;
9600 if (fBranchRef) fBranchRef->SetTree(this);
9604 if (R__v > 1) fIndexValues.Streamer(b);
9605 if (R__v > 2) fIndex.Streamer(b);
9606 if (R__v > 3) {
9607 TList OldInfoList;
9608 OldInfoList.Streamer(b);
9609 OldInfoList.Delete();
9610 }
9611 fNClusterRange = 0;
9614 b.CheckByteCount(R__s, R__c, TTree::IsA());
9615 //====end of old versions
9616 } else {
9617 if (fBranchRef) {
9618 fBranchRef->Clear();
9619 }
9621 if (table) TRefTable::SetRefTable(0);
9622
9623 b.WriteClassBuffer(TTree::Class(), this);
9624
9625 if (table) TRefTable::SetRefTable(table);
9626 }
9627}
9628
9629////////////////////////////////////////////////////////////////////////////////
9630/// Unbinned fit of one or more variable(s) from a tree.
9631///
9632/// funcname is a TF1 function.
9633///
9634/// \see TTree::Draw for explanations of the other parameters.
9635///
9636/// Fit the variable varexp using the function funcname using the
9637/// selection cuts given by selection.
9638///
9639/// The list of fit options is given in parameter option.
9640///
9641/// - option = "Q" Quiet mode (minimum printing)
9642/// - option = "V" Verbose mode (default is between Q and V)
9643/// - option = "E" Perform better Errors estimation using Minos technique
9644/// - option = "M" More. Improve fit results
9645///
9646/// You can specify boundary limits for some or all parameters via
9647/// ~~~ {.cpp}
9648/// func->SetParLimits(p_number, parmin, parmax);
9649/// ~~~
9650/// if parmin>=parmax, the parameter is fixed
9651///
9652/// Note that you are not forced to fix the limits for all parameters.
9653/// For example, if you fit a function with 6 parameters, you can do:
9654/// ~~~ {.cpp}
9655/// func->SetParameters(0,3.1,1.e-6,0.1,-8,100);
9656/// func->SetParLimits(4,-10,-4);
9657/// func->SetParLimits(5, 1,1);
9658/// ~~~
9659/// With this setup:
9660///
9661/// - Parameters 0->3 can vary freely
9662/// - Parameter 4 has boundaries [-10,-4] with initial value -8
9663/// - Parameter 5 is fixed to 100.
9664///
9665/// For the fit to be meaningful, the function must be self-normalized.
9666///
9667/// i.e. It must have the same integral regardless of the parameter
9668/// settings. Otherwise the fit will effectively just maximize the
9669/// area.
9670///
9671/// It is mandatory to have a normalization variable
9672/// which is fixed for the fit. e.g.
9673/// ~~~ {.cpp}
9674/// TF1* f1 = new TF1("f1", "gaus(0)/sqrt(2*3.14159)/[2]", 0, 5);
9675/// f1->SetParameters(1, 3.1, 0.01);
9676/// f1->SetParLimits(0, 1, 1); // fix the normalization parameter to 1
9677/// data->UnbinnedFit("f1", "jpsimass", "jpsipt>3.0");
9678/// ~~~
9679/// 1, 2 and 3 Dimensional fits are supported. See also TTree::Fit
9680///
9681/// Return status:
9682///
9683/// - The function return the status of the fit in the following form
9684/// fitResult = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult
9685/// - The fitResult is 0 is the fit is OK.
9686/// - The fitResult is negative in case of an error not connected with the fit.
9687/// - The number of entries used in the fit can be obtained via mytree.GetSelectedRows();
9688/// - If the number of selected entries is null the function returns -1
9690Int_t TTree::UnbinnedFit(const char* funcname, const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
9691{
9692 GetPlayer();
9693 if (fPlayer) {
9694 return fPlayer->UnbinnedFit(funcname, varexp, selection, option, nentries, firstentry);
9695 }
9696 return -1;
9697}
9698
9699////////////////////////////////////////////////////////////////////////////////
9700/// Replace current attributes by current style.
9703{
9704 if (gStyle->IsReading()) {
9713 } else {
9722 }
9723}
9724
9725////////////////////////////////////////////////////////////////////////////////
9726/// Write this object to the current directory. For more see TObject::Write
9727/// If option & kFlushBasket, call FlushBasket before writing the tree.
9729Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize) const
9730{
9733 return 0;
9734 return TObject::Write(name, option, bufsize);
9735}
9736
9737////////////////////////////////////////////////////////////////////////////////
9738/// Write this object to the current directory. For more see TObject::Write
9739/// If option & kFlushBasket, call FlushBasket before writing the tree.
9741Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize)
9742{
9743 return ((const TTree*)this)->Write(name, option, bufsize);
9744}
9745
9746////////////////////////////////////////////////////////////////////////////////
9747/// \class TTreeFriendLeafIter
9748///
9749/// Iterator on all the leaves in a TTree and its friend
9750
9752
9753////////////////////////////////////////////////////////////////////////////////
9754/// Create a new iterator. By default the iteration direction
9755/// is kIterForward. To go backward use kIterBackward.
9758: fTree(const_cast<TTree*>(tree))
9759, fLeafIter(0)
9760, fTreeIter(0)
9761, fDirection(dir)
9762{
9763}
9764
9765////////////////////////////////////////////////////////////////////////////////
9766/// Copy constructor. Does NOT copy the 'cursor' location!
9769: TIterator(iter)
9770, fTree(iter.fTree)
9771, fLeafIter(0)
9772, fTreeIter(0)
9773, fDirection(iter.fDirection)
9774{
9775}
9776
9777////////////////////////////////////////////////////////////////////////////////
9778/// Overridden assignment operator. Does NOT copy the 'cursor' location!
9781{
9782 if (this != &rhs && rhs.IsA() == TTreeFriendLeafIter::Class()) {
9783 const TTreeFriendLeafIter &rhs1 = (const TTreeFriendLeafIter &)rhs;
9784 fDirection = rhs1.fDirection;
9785 }
9786 return *this;
9787}
9788
9789////////////////////////////////////////////////////////////////////////////////
9790/// Overridden assignment operator. Does NOT copy the 'cursor' location!
9793{
9794 if (this != &rhs) {
9795 fDirection = rhs.fDirection;
9796 }
9797 return *this;
9798}
9799
9800////////////////////////////////////////////////////////////////////////////////
9801/// Go the next friend element
9804{
9805 if (!fTree) return 0;
9806
9807 TObject * next;
9808 TTree * nextTree;
9809
9810 if (!fLeafIter) {
9811 TObjArray *list = fTree->GetListOfLeaves();
9812 if (!list) return 0; // Can happen with an empty chain.
9814 if (!fLeafIter) return 0;
9815 }
9816
9817 next = fLeafIter->Next();
9818 if (!next) {
9819 if (!fTreeIter) {
9821 if (!list) return next;
9823 if (!fTreeIter) return 0;
9824 }
9825 TFriendElement * nextFriend = (TFriendElement*) fTreeIter->Next();
9826 ///nextTree = (TTree*)fTreeIter->Next();
9827 if (nextFriend) {
9828 nextTree = const_cast<TTree*>(nextFriend->GetTree());
9829 if (!nextTree) return Next();
9832 if (!fLeafIter) return 0;
9833 next = fLeafIter->Next();
9834 }
9835 }
9836 return next;
9837}
9838
9839////////////////////////////////////////////////////////////////////////////////
9840/// Returns the object option stored in the list.
9843{
9844 if (fLeafIter) return fLeafIter->GetOption();
9845 return "";
9846}
#define R__unlikely(expr)
Definition RConfig.hxx:586
#define SafeDelete(p)
Definition RConfig.hxx:525
#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
TObject * clone(const char *newname) const override
RooAbsTestStatistic * create(const char *name, const char *title, RooAbsReal &real, RooAbsData &adata, const RooArgSet &projDeps, RooAbsTestStatistic::Configuration const &cfg) override
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
bool Bool_t
Definition RtypesCore.h:63
int Int_t
Definition RtypesCore.h:45
short Version_t
Definition RtypesCore.h:65
unsigned char UChar_t
Definition RtypesCore.h:38
long Long_t
Definition RtypesCore.h:54
unsigned int UInt_t
Definition RtypesCore.h:46
float Float_t
Definition RtypesCore.h:57
constexpr Bool_t kFALSE
Definition RtypesCore.h:101
double Double_t
Definition RtypesCore.h:59
constexpr Ssiz_t kNPOS
Definition RtypesCore.h:124
long long Long64_t
Definition RtypesCore.h:80
unsigned long long ULong64_t
Definition RtypesCore.h:81
constexpr Bool_t kTRUE
Definition RtypesCore.h:100
const char Option_t
Definition RtypesCore.h:66
#define ClassImp(name)
Definition Rtypes.h:377
const Int_t kDoNotProcess
Definition TBranch.h:56
EDataType
Definition TDataType.h:28
@ kNoType_t
Definition TDataType.h:33
@ kFloat_t
Definition TDataType.h:31
@ kULong64_t
Definition TDataType.h:32
@ kInt_t
Definition TDataType.h:30
@ kchar
Definition TDataType.h:31
@ kLong_t
Definition TDataType.h:30
@ kDouble32_t
Definition TDataType.h:31
@ kShort_t
Definition TDataType.h:29
@ kBool_t
Definition TDataType.h:32
@ kBits
Definition TDataType.h:34
@ kULong_t
Definition TDataType.h:30
@ kLong64_t
Definition TDataType.h:32
@ kUShort_t
Definition TDataType.h:29
@ kDouble_t
Definition TDataType.h:31
@ kCharStar
Definition TDataType.h:34
@ kChar_t
Definition TDataType.h:29
@ kUChar_t
Definition TDataType.h:29
@ kCounter
Definition TDataType.h:34
@ kUInt_t
Definition TDataType.h:30
@ kFloat16_t
Definition TDataType.h:33
@ kOther_t
Definition TDataType.h:32
#define gDirectory
Definition TDirectory.h:384
R__EXTERN TEnv * gEnv
Definition TEnv.h:170
#define R__ASSERT(e)
Definition TError.h:118
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:185
#define N
static unsigned int total
Option_t Option_t option
Option_t Option_t SetLineWidth
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t cursor
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t SetFillStyle
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t SetLineColor
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Option_t Option_t SetFillColor
Option_t Option_t SetMarkerStyle
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t src
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void reg
Option_t Option_t style
char name[80]
Definition TGX11.cxx:110
int nentries
R__EXTERN TInterpreter * gCling
Int_t gDebug
Definition TROOT.cxx:597
R__EXTERN TVirtualMutex * gROOTMutex
Definition TROOT.h:63
#define gROOT
Definition TROOT.h:407
void Printf(const char *fmt,...)
Formats a string in a circular formatting buffer and prints the string.
Definition TString.cxx:2481
R__EXTERN TStyle * gStyle
Definition TStyle.h:433
R__EXTERN TSystem * gSystem
Definition TSystem.h:560
constexpr Int_t kNEntriesResort
Definition TTree.cxx:450
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:4790
static char DataTypeToChar(EDataType datatype)
Definition TTree.cxx:462
void TFriendElement__SetTree(TTree *tree, TList *frlist)
Set the fTree member for all friend elements.
Definition TTree.cxx:9517
bool CheckReshuffling(TTree &mainTree, TTree &friendTree)
Definition TTree.cxx:1240
static void TBranch__SetTree(TTree *tree, TObjArray &branches)
Set the fTree member for all branches and sub branches.
Definition TTree.cxx:9495
constexpr Float_t kNEntriesResortInv
Definition TTree.cxx:451
#define R__LOCKGUARD(mutex)
#define gPad
#define snprintf
Definition civetweb.c:1540
Bool_t HasRuleWithSourceClass(const TString &source) const
Return True if we have any rule whose source class is 'source'.
A helper class for managing IMT work during TTree:Fill operations.
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 Foreach(F func, unsigned nTimes, unsigned nChunks=0)
Execute a function without arguments several times in parallel, dividing the execution in nChunks.
void Streamer(TBuffer &) override
Stream a TArrayD object.
Definition TArrayD.cxx:149
void Set(Int_t n) override
Set size of this array to n doubles.
Definition TArrayD.cxx:106
void Set(Int_t n) override
Set size of this array to n ints.
Definition TArrayI.cxx:105
void Streamer(TBuffer &) override
Stream a TArrayI object.
Definition TArrayI.cxx:148
Int_t fN
Definition TArray.h:38
Fill Area Attributes class.
Definition TAttFill.h:19
virtual void Streamer(TBuffer &)
virtual Color_t GetFillColor() const
Return the fill area color.
Definition TAttFill.h:30
virtual Style_t GetFillStyle() const
Return the fill area style.
Definition TAttFill.h:31
Line Attributes class.
Definition TAttLine.h:18
virtual void Streamer(TBuffer &)
virtual Color_t GetLineColor() const
Return the line color.
Definition TAttLine.h:33
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition TAttLine.h:42
virtual Width_t GetLineWidth() const
Return the line width.
Definition TAttLine.h:35
virtual Style_t GetLineStyle() const
Return the line style.
Definition TAttLine.h:34
Marker Attributes class.
Definition TAttMarker.h:19
virtual Style_t GetMarkerStyle() const
Return the marker style.
Definition TAttMarker.h:32
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
Definition TAttMarker.h:38
virtual Color_t GetMarkerColor() const
Return the marker color.
Definition TAttMarker.h:31
virtual Size_t GetMarkerSize() const
Return the marker size.
Definition TAttMarker.h:33
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
Definition TAttMarker.h:40
virtual void Streamer(TBuffer &)
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
Definition TAttMarker.h:45
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
virtual Int_t DropBuffers()
Drop buffers of this basket if it is not the current basket.
Definition TBasket.cxx:173
Int_t GetBufferSize() const
Definition TBasket.h:122
A Branch for the case of an array of clone objects.
A Branch for the case of an object.
virtual void SetBranchFolder()
static TClass * Class()
Int_t GetClassVersion()
const char * GetClassName() const override
Return the name of the user class whose content is stored in this branch, if any.
void ResetAddress() override
Set branch address to zero and free all allocated memory.
virtual Bool_t IsObjectOwner() const
Int_t Unroll(const char *name, TClass *cltop, TClass *cl, char *ptr, Int_t basketsize, Int_t splitlevel, Int_t btype)
Split class cl into sub-branches of this branch.
void SetAddress(void *addobj) override
Point this branch at an object.
virtual void SetTargetClass(const char *name)
Set the name of the class of the in-memory object into which the data will loaded.
void SetObject(void *objadd) override
Set object this branch is pointing to.
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
virtual TLeaf * GetLeaf(const char *name) const
Return pointer to the 1st Leaf named name in thisBranch.
Definition TBranch.cxx:2055
virtual void SetupAddresses()
If the branch address is not set, we set all addresses starting with the top level parent branch.
Definition TBranch.cxx:3294
virtual void ResetAddress()
Reset the address of the branch.
Definition TBranch.cxx:2651
virtual Long64_t GetBasketSeek(Int_t basket) const
Return address of basket in the file.
Definition TBranch.cxx:1302
virtual char * GetAddress() const
Definition TBranch.h:212
void SetCompressionSettings(Int_t settings=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault)
Set compression settings.
Definition TBranch.cxx:2805
TTree * GetTree() const
Definition TBranch.h:252
static TClass * Class()
virtual TString GetFullName() const
Return the 'full' name of the branch.
Definition TBranch.cxx:2031
Int_t GetWriteBasket() const
Definition TBranch.h:238
virtual void DropBaskets(Option_t *option="")
Loop on all branch baskets.
Definition TBranch.cxx:757
TObjArray * GetListOfBranches()
Definition TBranch.h:246
virtual void SetTree(TTree *tree)
Definition TBranch.h:287
virtual void SetEntryOffsetLen(Int_t len, Bool_t updateSubBranches=kFALSE)
Update the default value for the branch's fEntryOffsetLen if and only if it was already non zero (and...
Definition TBranch.cxx:2821
virtual Int_t GetEntry(Long64_t entry=0, Int_t getall=0)
Read all leaves of entry and return total number of bytes read.
Definition TBranch.cxx:1706
TClass * IsA() const override
Definition TBranch.h:295
void Print(Option_t *option="") const override
Print TBranch parameters.
Definition TBranch.cxx:2341
static void ResetCount()
Static function resetting fgCount.
Definition TBranch.cxx:2674
virtual void SetObject(void *objadd)
Set object this branch is pointing to.
Definition TBranch.cxx:2936
Int_t FlushBaskets()
Flush to disk all the baskets of this branch and any of subbranches.
Definition TBranch.cxx:1136
virtual void SetAddress(void *add)
Set address of this branch.
Definition TBranch.cxx:2682
Int_t GetNleaves() const
Definition TBranch.h:249
virtual void SetFile(TFile *file=nullptr)
Set file where this branch writes/reads its buffers.
Definition TBranch.cxx:2863
TObjArray * GetListOfBaskets()
Definition TBranch.h:245
Long64_t GetEntries() const
Definition TBranch.h:251
virtual void UpdateFile()
Refresh the value of fDirectory (i.e.
Definition TBranch.cxx:3304
Int_t GetReadBasket() const
Definition TBranch.h:236
Int_t GetMaxBaskets() const
Definition TBranch.h:248
virtual TFile * GetFile(Int_t mode=0)
Return pointer to the file where branch buffers reside, returns 0 in case branch buffers reside in th...
Definition TBranch.cxx:1853
virtual void KeepCircular(Long64_t maxEntries)
keep a maximum of fMaxEntries in memory
Definition TBranch.cxx:2283
virtual void ResetAfterMerge(TFileMergeInfo *)
Reset a Branch.
Definition TBranch.cxx:2598
virtual Bool_t GetMakeClass() const
Return whether this branch is in a mode where the object are decomposed or not (Also known as MakeCla...
Definition TBranch.cxx:2117
virtual TBranch * FindBranch(const char *name)
Find the immediate sub-branch with passed name.
Definition TBranch.cxx:1035
virtual Int_t LoadBaskets()
Baskets associated to this branch are forced to be in memory.
Definition TBranch.cxx:2309
void SetIOFeatures(TIOFeatures &features)
Definition TBranch.h:283
Long64_t GetTotBytes(Option_t *option="") const
Return total number of bytes in the branch (excluding current buffer) if option ="*" includes all sub...
Definition TBranch.cxx:2220
virtual Bool_t SetMakeClass(Bool_t decomposeObj=kTRUE)
Set the branch in a mode where the object are decomposed (Also known as MakeClass mode).
Definition TBranch.cxx:2927
virtual void SetOffset(Int_t offset=0)
Definition TBranch.h:285
virtual Int_t GetExpectedType(TClass *&clptr, EDataType &type)
Fill expectedClass and expectedType with information on the data type of the object/values contained ...
Definition TBranch.cxx:1834
virtual Int_t GetBasketSize() const
Definition TBranch.h:217
Long64_t GetZipBytes(Option_t *option="") const
Return total number of zip bytes in the branch if option ="*" includes all sub-branches of this branc...
Definition TBranch.cxx:2238
virtual void SetBasketSize(Int_t buffsize)
Set the basket size The function makes sure that the basket size is greater than fEntryOffsetlen.
Definition TBranch.cxx:2729
virtual void Refresh(TBranch *b)
Refresh this branch using new information in b This function is called by TTree::Refresh.
Definition TBranch.cxx:2508
TObjArray * GetListOfLeaves()
Definition TBranch.h:247
Int_t Fill()
Definition TBranch.h:205
virtual void Reset(Option_t *option="")
Reset a Branch.
Definition TBranch.cxx:2557
TBranch * GetMother() const
Get our top-level parent branch in the tree.
Definition TBranch.cxx:2127
virtual Int_t FillImpl(ROOT::Internal::TBranchIMTHelper *)
Loop on all leaves of this branch to fill Basket buffer.
Definition TBranch.cxx:856
Int_t GetEntryOffsetLen() const
Definition TBranch.h:227
Using a TBrowser one can browse all ROOT objects.
Definition TBrowser.h:37
The concrete implementation of TBuffer for writing/reading to/from a ROOT file or socket.
Definition TBufferFile.h:47
Buffer base class used for serializing objects.
Definition TBuffer.h:43
void Expand(Int_t newsize, Bool_t copy=kTRUE)
Expand (or shrink) the I/O buffer to newsize bytes.
Definition TBuffer.cxx:223
Int_t BufferSize() const
Definition TBuffer.h:98
@ kWrite
Definition TBuffer.h:73
@ kRead
Definition TBuffer.h:73
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:81
Bool_t CanSplit() const
Return true if the data member of this TClass can be saved separately.
Definition TClass.cxx:2319
ROOT::ESTLType GetCollectionType() const
Return the 'type' of the STL the TClass is representing.
Definition TClass.cxx:2886
void * New(ENewType defConstructor=kClassNew, Bool_t quiet=kFALSE) const
Return a pointer to a newly allocated object of this class.
Definition TClass.cxx:4978
Bool_t HasDataMemberInfo() const
Definition TClass.h:407
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:508
void Destructor(void *obj, Bool_t dtorOnly=kFALSE)
Explicitly call destructor for object.
Definition TClass.cxx:5400
void BuildRealData(void *pointer=nullptr, Bool_t isTransient=kFALSE)
Build a full list of persistent data members.
Definition TClass.cxx:2031
const std::type_info * GetTypeInfo() const
Definition TClass.h:496
TList * GetListOfDataMembers(Bool_t load=kTRUE)
Return list containing the TDataMembers of a class.
Definition TClass.cxx:3770
TList * GetListOfRealData() const
Definition TClass.h:453
Bool_t CanIgnoreTObjectStreamer()
Definition TClass.h:393
const ROOT::Detail::TSchemaRuleSet * GetSchemaRules() const
Return the set of the schema rules if any.
Definition TClass.cxx:1932
TList * GetListOfBases()
Return list containing the TBaseClass(es) of a class.
Definition TClass.cxx:3636
Bool_t IsLoaded() const
Return true if the shared library of this class is currently in the a process's memory.
Definition TClass.cxx:5912
Bool_t IsTObject() const
Return kTRUE is the class inherits from TObject.
Definition TClass.cxx:5938
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:4599
Bool_t InheritsFrom(const char *cl) const override
Return kTRUE if this class inherits from a class with name "classname".
Definition TClass.cxx:4874
TVirtualCollectionProxy * GetCollectionProxy() const
Return the proxy describing the collection (if any).
Definition TClass.cxx:2897
TVirtualStreamerInfo * GetConversionStreamerInfo(const char *onfile_classname, Int_t version) const
Return a Conversion StreamerInfo from the class 'classname' for version number 'version' to this clas...
Definition TClass.cxx:7086
TVirtualStreamerInfo * FindConversionStreamerInfo(const char *onfile_classname, UInt_t checksum) const
Return a Conversion StreamerInfo from the class 'classname' for the layout represented by 'checksum' ...
Definition TClass.cxx:7193
Version_t GetClassVersion() const
Definition TClass.h:420
TClass * GetActualClass(const void *object) const
Return a pointer to the real class of the object.
Definition TClass.cxx:2607
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:2968
Int_t WriteBuffer(TBuffer &b, void *pointer, const char *info="")
Function called by the Streamer functions to serialize object at p to buffer b.
Definition TClass.cxx:6779
An array of clone (identical) objects.
void BypassStreamer(Bool_t bypass=kTRUE)
When the kBypassStreamer bit is set, the automatically generated Streamer can call directly TClass::W...
TClass * GetClass() const
static TClass * Class()
Collection abstract base class.
Definition TCollection.h:65
virtual TObject ** GetObjectRef(const TObject *obj) const =0
virtual TIterator * MakeIterator(Bool_t dir=kIterForward) const =0
static TClass * Class()
void SetName(const char *name)
const char * GetName() const override
Return name of this collection.
virtual Int_t GetEntries() const
virtual void SetOwner(Bool_t enable=kTRUE)
Set whether this collection is the owner (enable==true) of its content.
void Browse(TBrowser *b) override
Browse this collection (called by TBrowser).
A specialized string object used for TTree selections.
Definition TCut.h:25
All ROOT classes may have RTTI (run time type identification) support added.
Definition TDataMember.h:31
Bool_t IsPersistent() const
Definition TDataMember.h:91
Bool_t IsBasic() const
Return true if data member is a basic type, e.g. char, int, long...
Bool_t IsaPointer() const
Return true if data member is a pointer.
TDataType * GetDataType() const
Definition TDataMember.h:76
Longptr_t GetOffset() const
Get offset from "this".
const char * GetTypeName() const
Get the decayed type name of this data member, removing const and volatile qualifiers,...
const char * GetArrayIndex() const
If the data member is pointer and has a valid array size in its comments GetArrayIndex returns a stri...
const char * GetFullTypeName() const
Get the concrete type name of this data member, including const and volatile qualifiers.
Basic data type descriptor (datatype information is obtained from CINT).
Definition TDataType.h:44
Int_t GetType() const
Definition TDataType.h:68
TString GetTypeName()
Get basic type of typedef, e,g.: "class TDirectory*" -> "TDirectory".
void Append(TObject *obj, Bool_t replace=kFALSE) override
Append object to this directory.
TDirectory::TContext keeps track and restore the current directory.
Definition TDirectory.h:89
Describe directory structure in memory.
Definition TDirectory.h:45
virtual TList * GetList() const
Definition TDirectory.h:222
virtual void Append(TObject *obj, Bool_t replace=kFALSE)
Append object to this directory.
virtual Int_t WriteTObject(const TObject *obj, const char *name=nullptr, Option_t *="", Int_t=0)
Write an object with proper type checking.
virtual TFile * GetFile() const
Definition TDirectory.h:220
virtual Bool_t cd()
Change current directory to "this" directory.
virtual Int_t ReadKeys(Bool_t=kTRUE)
Definition TDirectory.h:248
virtual Bool_t IsWritable() const
Definition TDirectory.h:237
virtual TKey * GetKey(const char *, Short_t=9999) const
Definition TDirectory.h:221
virtual Int_t ReadTObject(TObject *, const char *)
Definition TDirectory.h:249
virtual void SaveSelf(Bool_t=kFALSE)
Definition TDirectory.h:255
virtual TList * GetListOfKeys() const
Definition TDirectory.h:223
void GetObject(const char *namecycle, T *&ptr)
Get an object with proper type checking.
Definition TDirectory.h:212
virtual TObject * Remove(TObject *)
Remove an object from the in-memory list.
Streamer around an arbitrary STL like container, which implements basic container functionality.
A List of entry numbers in a TTree or TChain.
Definition TEntryList.h:26
virtual void SetReapplyCut(Bool_t apply=kFALSE)
Definition TEntryList.h:108
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 Bool_t Enter(Long64_t entry, TTree *tree=nullptr)
Add entry #entry to the list.
virtual void SetDirectory(TDirectory *dir)
Add reference to directory dir. dir can be 0.
virtual Long64_t GetEntry(Long64_t index)
Return the number of the entry #index of this TEntryList in the TTree or TChain See also Next().
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition TEnv.cxx:491
A TEventList object is a list of selected events (entries) in a TTree.
Definition TEventList.h:31
virtual Long64_t GetEntry(Int_t index) const
Return value of entry at index in the list.
virtual Int_t GetN() const
Definition TEventList.h:56
virtual Bool_t GetReapplyCut() const
Definition TEventList.h:57
A cache when reading files over the network.
virtual void WaitFinishPrefetch()
virtual Int_t GetBufferSize() const
TIOFeatures * fIOFeatures
TDirectory * fOutputDirectory
A ROOT file is composed of a header, followed by consecutive data records (TKey instances) with a wel...
Definition TFile.h:53
virtual void SetCacheRead(TFileCacheRead *cache, TObject *tree=nullptr, ECacheAction action=kDisconnect)
Set a pointer to the read cache.
Definition TFile.cxx:2351
Int_t GetCompressionSettings() const
Definition TFile.h:406
virtual Long64_t GetEND() const
Definition TFile.h:231
@ kDoNotDisconnect
Definition TFile.h:70
virtual void Flush()
Synchronize a file's in-memory and on-disk states.
Definition TFile.cxx:1127
virtual void MakeFree(Long64_t first, Long64_t last)
Mark unused bytes on the file.
Definition TFile.cxx:1470
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:4075
Int_t GetRecordHeader(char *buf, Long64_t first, Int_t maxbytes, Int_t &nbytes, Int_t &objlen, Int_t &keylen)
Read the logical record header starting at a certain postion.
Definition TFile.cxx:1287
<div class="legacybox"><h2>Legacy Code</h2> TFolder is a legacy interface: there will be no bug fixes...
Definition TFolder.h:30
TCollection * GetListOfFolders() const
Definition TFolder.h:55
virtual Int_t Occurence(const TObject *obj) const
Return occurence number of object in the list of objects of this folder.
Definition TFolder.cxx:427
static TClass * Class()
A TFriendElement TF describes a TTree object TF in a file.
virtual const char * GetTreeName() const
Get the actual TTree name of the friend.
virtual TTree * GetTree()
Return pointer to friend TTree.
virtual TFile * GetFile()
Return pointer to TFile containing this friend TTree.
Bool_t IsUpdated() const
TTree * fParentTree
! pointer to the parent TTree
virtual Int_t DeleteGlobal(void *obj)=0
void Reset()
Iterator abstract base class.
Definition TIterator.h:30
virtual TObject * Next()=0
virtual TClass * IsA() const
Definition TIterator.h:48
virtual Option_t * GetOption() const
Definition TIterator.h:40
Book space in a file, create I/O buffers, to fill them, (un)compress them.
Definition TKey.h:28
void Delete(Option_t *option="") override
Delete an object from the file.
Definition TKey.cxx:538
Int_t GetKeylen() const
Definition TKey.h:84
Int_t GetNbytes() const
Definition TKey.h:86
virtual const char * GetClassName() const
Definition TKey.h:75
static TClass * Class()
static TClass * Class()
static TClass * Class()
static TClass * Class()
A TLeaf describes individual elements of a TBranch See TBranch structure in TTree.
Definition TLeaf.h:57
virtual Double_t GetValue(Int_t i=0) const
Definition TLeaf.h:183
virtual void * GetValuePointer() const
Definition TLeaf.h:138
virtual Int_t GetLenType() const
Definition TLeaf.h:133
virtual void ReadValue(std::istream &, Char_t=' ')
Definition TLeaf.h:156
virtual Int_t GetMaximum() const
Definition TLeaf.h:134
virtual Int_t GetLen() const
Return the number of effective elements of this leaf, for the current entry.
Definition TLeaf.cxx:404
virtual TLeaf * GetLeafCount() const
If this leaf stores a variable-sized array or a multi-dimensional array whose last dimension has vari...
Definition TLeaf.h:121
virtual Bool_t IncludeRange(TLeaf *)
Definition TLeaf.h:146
TClass * IsA() const override
Definition TLeaf.h:168
virtual void SetAddress(void *add=nullptr)
Definition TLeaf.h:185
TBranch * GetBranch() const
Definition TLeaf.h:116
@ kNewValue
Set if we own the value buffer and so must delete it ourselves.
Definition TLeaf.h:96
@ kIndirectAddress
Data member is a pointer to an array of basic types.
Definition TLeaf.h:95
virtual TString GetFullName() const
Return the full name (including the parent's branch names) of the leaf.
Definition TLeaf.cxx:224
virtual Int_t GetOffset() const
Definition TLeaf.h:137
virtual void PrintValue(Int_t i=0) const
Definition TLeaf.h:184
A doubly linked list.
Definition TList.h:38
void Streamer(TBuffer &) override
Stream all objects in the collection to or from the I/O buffer.
Definition TList.cxx:1191
void Clear(Option_t *option="") override
Remove all objects from the list.
Definition TList.cxx:402
TObject * FindObject(const char *name) const override
Find an object in this list using its name.
Definition TList.cxx:578
void RecursiveRemove(TObject *obj) override
Remove object from this collection and recursively remove the object from all other objects (and coll...
Definition TList.cxx:764
void Add(TObject *obj) override
Definition TList.h:81
TObject * Remove(TObject *obj) override
Remove object from the list.
Definition TList.cxx:822
virtual TObjLink * FirstLink() const
Definition TList.h:102
void Delete(Option_t *option="") override
Remove all objects from the list AND delete all heap based objects.
Definition TList.cxx:470
TObject * At(Int_t idx) const override
Returns the object at position idx. Returns 0 if idx is out of range.
Definition TList.cxx:357
A TMemFile is like a normal TFile except that it reads and writes only from memory.
Definition TMemFile.h:19
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
TObject * Clone(const char *newname="") const override
Make a clone of an object using the Streamer facility.
Definition TNamed.cxx:74
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition TNamed.cxx:164
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
void Streamer(TBuffer &) override
Stream an object of class TObject.
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:48
TString fTitle
Definition TNamed.h:33
TNamed()
Definition TNamed.h:36
TString fName
Definition TNamed.h:32
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition TNamed.cxx:140
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.
TObject * Last() const override
Return the object in the last filled slot. Returns 0 if no entries.
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.
TIterator * MakeIterator(Bool_t dir=kIterForward) const override
Returns an array iterator.
virtual void Compress()
Remove empty slots from array.
Int_t GetEntries() const override
Return the number of objects in array (i.e.
void Delete(Option_t *option="") override
Remove all objects from the array AND delete all heap based objects.
TObject * At(Int_t idx) const override
Definition TObjArray.h:164
TObject * UncheckedAt(Int_t i) const
Definition TObjArray.h:84
TObject * RemoveAt(Int_t idx) override
Remove object at index idx.
TObject * FindObject(const char *name) const override
Find an object in this collection using its name.
void Add(TObject *obj) override
Definition TObjArray.h:68
Mother of all ROOT objects.
Definition TObject.h:41
virtual Bool_t Notify()
This method must be overridden to handle object notification (the base implementation is no-op).
Definition TObject.cxx:594
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:439
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:199
@ kBitMask
Definition TObject.h:86
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:207
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:973
R__ALWAYS_INLINE Bool_t IsZombie() const
Definition TObject.h:153
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:880
@ kOnlyPrepStep
Used to request that the class specific implementation of TObject::Write just prepare the objects to ...
Definition TObject.h:106
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition TObject.cxx:780
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition TObject.cxx:525
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:987
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition TObject.cxx:1015
virtual const char * GetTitle() const
Returns title of object.
Definition TObject.cxx:483
virtual TClass * IsA() const
Definition TObject.h:243
void ResetBit(UInt_t f)
Definition TObject.h:198
@ kCanDelete
if object in a list can be deleted
Definition TObject.h:62
@ kMustCleanup
if object destructor must call RecursiveRemove()
Definition TObject.h:64
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:961
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
const char * GetName() const override
Returns name of object.
Definition TRealData.h:52
TDataMember * GetDataMember() const
Definition TRealData.h:53
Bool_t IsObject() const
Definition TRealData.h:56
Long_t GetThisOffset() const
Definition TRealData.h:55
A TRefTable maintains the association between a referenced object and the parent object supporting th...
Definition TRefTable.h:35
static void SetRefTable(TRefTable *table)
Static function setting the current TRefTable.
static TRefTable * GetRefTable()
Static function returning the current TRefTable.
Regular expression class.
Definition TRegexp.h:31
A TSelector object is used by the TTree::Draw, TTree::Scan, TTree::Process to navigate in a TTree and...
Definition TSelector.h:31
static void * ReAlloc(void *vp, size_t size, size_t oldsize)
Reallocate (i.e.
Definition TStorage.cxx:183
Describes a persistent version of a class.
void ForceWriteInfo(TFile *file, Bool_t force=kFALSE) override
Recursively mark streamer infos for writing to a file.
Basic string class.
Definition TString.h:139
Ssiz_t Length() const
Definition TString.h:421
void ToLower()
Change string to lower-case.
Definition TString.cxx:1170
static constexpr Ssiz_t kNPOS
Definition TString.h:280
TSubString Strip(EStripType s=kTrailing, char c=' ') const
Return a substring of self stripped at beginning and/or end.
Definition TString.cxx:1151
Double_t Atof() const
Return floating-point value contained in string.
Definition TString.cxx:2032
Ssiz_t First(char c) const
Find first occurrence of a character c.
Definition TString.cxx:531
const char * Data() const
Definition TString.h:380
Bool_t EqualTo(const char *cs, ECaseCompare cmp=kExact) const
Definition TString.h:645
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:704
@ kLeading
Definition TString.h:278
@ kTrailing
Definition TString.h:278
@ kIgnoreCase
Definition TString.h:279
Ssiz_t Last(char c) const
Find last occurrence of a character c.
Definition TString.cxx:924
TObjArray * Tokenize(const TString &delim) const
This function is used to isolate sequential tokens in a TString.
Definition TString.cxx:2242
Bool_t IsNull() const
Definition TString.h:418
TString & Remove(Ssiz_t pos)
Definition TString.h:685
TString & Append(const char *cs)
Definition TString.h:576
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:2356
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition TString.cxx:2334
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:636
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition TString.h:651
void SetHistFillColor(Color_t color=1)
Definition TStyle.h:376
Color_t GetHistLineColor() const
Definition TStyle.h:231
Bool_t IsReading() const
Definition TStyle.h:294
void SetHistLineStyle(Style_t styl=0)
Definition TStyle.h:379
Style_t GetHistFillStyle() const
Definition TStyle.h:232
Color_t GetHistFillColor() const
Definition TStyle.h:230
void SetHistLineColor(Color_t color=1)
Definition TStyle.h:377
Style_t GetHistLineStyle() const
Definition TStyle.h:233
void SetHistFillStyle(Style_t styl=0)
Definition TStyle.h:378
Width_t GetHistLineWidth() const
Definition TStyle.h:234
void SetHistLineWidth(Width_t width=1)
Definition TStyle.h:380
A zero length substring is legal.
Definition TString.h:85
TString & String()
Definition TString.h:124
virtual const char * Getenv(const char *env)
Get environment variable.
Definition TSystem.cxx:1650
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:1283
A TTreeCache which exploits parallelized decompression of its own content.
static Bool_t 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...
TTree * GetTree() const
Definition TTreeCache.h:149
virtual void SetEntryRange(Long64_t emin, Long64_t emax)
Set the minimum and maximum entry number to be processed this information helps to optimize the numbe...
Bool_t IsAutoCreated() const
Definition TTreeCache.h:150
void SetAutoCreated(Bool_t val)
Definition TTreeCache.h:164
virtual Int_t DropBranch(TBranch *b, Bool_t subbranches=kFALSE)
Remove a branch to the list of branches to be stored in the cache this function is called by TBranch:...
Int_t SetBufferSize(Int_t buffersize) override
Change the underlying buffer size of the cache.
virtual void StopLearningPhase()
This is the counterpart of StartLearningPhase() and can be used to stop the learning phase.
void Print(Option_t *option="") const override
Print cache statistics.
Int_t AddBranch(TBranch *b, Bool_t subgbranches=kFALSE) override
Add a branch to the list of branches to be stored in the cache this function is called by the user vi...
Class implementing or helping the various TTree cloning method.
Definition TTreeCloner.h:31
Bool_t Exec()
Execute the cloning.
Bool_t IsValid()
const char * GetWarning() const
void SetCacheSize(Int_t size)
Set the TFile cache size to be used.
Bool_t NeedConversion()
Iterator on all the leaves in a TTree and its friend.
Definition TTree.h:670
TTree * fTree
tree being iterated
Definition TTree.h:673
TIterator & operator=(const TIterator &rhs) override
Overridden assignment operator. Does NOT copy the 'cursor' location!
Definition TTree.cxx:9779
TObject * Next() override
Go the next friend element.
Definition TTree.cxx:9802
TIterator * fLeafIter
current leaf sub-iterator.
Definition TTree.h:674
Option_t * GetOption() const override
Returns the object option stored in the list.
Definition TTree.cxx:9841
TIterator * fTreeIter
current tree sub-iterator.
Definition TTree.h:675
Bool_t fDirection
iteration direction
Definition TTree.h:676
static TClass * Class()
Helper class to iterate over cluster of baskets.
Definition TTree.h:270
Long64_t GetEstimatedClusterSize()
Estimate the cluster size.
Definition TTree.cxx:611
Long64_t Previous()
Move on to the previous cluster and return the starting entry of this previous cluster.
Definition TTree.cxx:694
Long64_t Next()
Move on to the next cluster and return the starting entry of this next cluster.
Definition TTree.cxx:650
Long64_t GetNextEntry()
Definition TTree.h:307
TClusterIterator(TTree *tree, Long64_t firstEntry)
Regular constructor.
Definition TTree.cxx:560
Helper class to prevent infinite recursion in the usage of TTree Friends.
Definition TTree.h:188
TFriendLock & operator=(const TFriendLock &)
Assignment operator.
Definition TTree.cxx:530
TFriendLock(const TFriendLock &)
Copy constructor.
Definition TTree.cxx:520
UInt_t fMethodBit
Definition TTree.h:192
TTree * fTree
Definition TTree.h:191
~TFriendLock()
Restore the state of tree the same as before we set the lock.
Definition TTree.cxx:543
Bool_t fPrevious
Definition TTree.h:193
A TTree represents a columnar dataset.
Definition TTree.h:79
virtual Int_t Fill()
Fill all branches.
Definition TTree.cxx:4600
virtual TFriendElement * AddFriend(const char *treename, const char *filename="")
Add a TFriendElement to the list of friends.
Definition TTree.cxx:1332
TBranchRef * fBranchRef
Branch supporting the TRefTable (if any)
Definition TTree.h:136
virtual Int_t AddBranchToCache(const char *bname, Bool_t subbranches=kFALSE)
Add branch with name bname to the Tree cache.
Definition TTree.cxx:1059
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:4838
virtual TBranch * GetBranch(const char *name)
Return pointer to the branch with the given name in this tree or its friends.
Definition TTree.cxx:5291
static Int_t GetBranchStyle()
Static function returning the current branch style.
Definition TTree.cxx:5392
TList * fFriends
pointer to list of friend elements
Definition TTree.h:130
UInt_t fFriendLockStatus
! Record which method is locking the friend recursion
Definition TTree.h:137
virtual TLeaf * GetLeafImpl(const char *branchname, const char *leafname)
Return pointer to the 1st Leaf named name in any Branch of this Tree or any branch in the list of fri...
Definition TTree.cxx:6095
Long64_t fTotBytes
Total number of bytes in all branches before compression.
Definition TTree.h:86
Int_t fMaxClusterRange
! Memory allocated for the cluster range.
Definition TTree.h:96
virtual void Show(Long64_t entry=-1, Int_t lenmax=20)
Print values of all active leaves for entry.
Definition TTree.cxx:9372
TEventList * fEventList
! Pointer to event selection list (if one)
Definition TTree.h:125
virtual Long64_t GetAutoSave() const
Definition TTree.h:448
Long64_t GetCacheAutoSize(Bool_t withDefault=kFALSE)
Used for automatic sizing of the cache.
Definition TTree.cxx:5404
virtual Int_t StopCacheLearningPhase()
Stop the cache learning phase.
Definition TTree.cxx:9461
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:5635
std::vector< std::pair< Long64_t, TBranch * > > fSortedBranches
! Branches to be processed in parallel when IMT is on, sorted by average task time
Definition TTree.h:144
virtual void SetCircular(Long64_t maxEntries)
Enable/Disable circularity for this tree.
Definition TTree.cxx:8879
Long64_t fSavedBytes
Number of autosaved bytes.
Definition TTree.h:88
Long64_t GetMedianClusterSize()
Estimate the median cluster size for the TTree.
Definition TTree.cxx:8289
virtual TClusterIterator GetClusterIterator(Long64_t firstentry)
Return an iterator over the cluster of baskets starting at firstentry.
Definition TTree.cxx:5464
virtual void ResetBranchAddress(TBranch *)
Tell all of our branches to set their addresses to zero.
Definition TTree.cxx:8062
char GetNewlineValue(std::istream &inputStream)
Determine which newline this file is using.
Definition TTree.cxx:7585
virtual Int_t CheckBranchAddressType(TBranch *branch, TClass *ptrClass, EDataType datatype, Bool_t ptr)
Check whether or not the address described by the last 3 parameters matches the content of the branch...
Definition TTree.cxx:2867
TIOFeatures fIOFeatures
IO features to define for newly-written baskets and branches.
Definition TTree.h:114
Bool_t Notify() override
Function called when loading a new class library.
Definition TTree.cxx:7030
virtual Long64_t GetEntryNumberWithIndex(Long64_t major, Long64_t minor=0) const
Return entry number corresponding to major and minor number.
Definition TTree.cxx:5907
Long64_t fDebugMin
! First entry number to debug
Definition TTree.h:112
virtual Long64_t SetEntries(Long64_t n=-1)
Change number of entries in the tree.
Definition TTree.cxx:8998
virtual TObjArray * GetListOfLeaves()
Definition TTree.h:489
Bool_t fCacheDoClusterPrefetch
! true if cache is prefetching whole clusters
Definition TTree.h:140
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:2074
virtual TBranch * BranchRef()
Build the optional branch supporting the TRefTable.
Definition TTree.cxx:2328
virtual Bool_t 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:7009
TFile * GetCurrentFile() const
Return pointer to the current file.
Definition TTree.cxx:5476
TList * fAliases
List of aliases for expressions based on the tree branches.
Definition TTree.h:124
virtual TTree * CopyTree(const char *selection, Option_t *option="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)
Copy a tree with selection.
Definition TTree.cxx:3716
virtual Int_t FlushBaskets(Bool_t 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:5126
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:5076
Int_t SetCacheSizeAux(Bool_t autocache=kTRUE, Long64_t cacheSize=0)
Set the size of the file cache and create it if possible.
Definition TTree.cxx:8699
Long64_t * fClusterRangeEnd
[fNClusterRange] Last entry of a cluster range.
Definition TTree.h:103
void Streamer(TBuffer &) override
Stream a class object.
Definition TTree.cxx:9532
std::atomic< Long64_t > fIMTZipBytes
! Zip bytes for the IMT flush baskets.
Definition TTree.h:161
void RecursiveRemove(TObject *obj) override
Make sure that obj (which is being deleted or will soon be) is no longer referenced by this TTree.
Definition TTree.cxx:7878
TVirtualTreePlayer * GetPlayer()
Load the TTreePlayer (if not already done).
Definition TTree.cxx:6302
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:6765
virtual Long64_t ReadStream(std::istream &inputStream, const char *branchDescriptor="", char delimiter=' ')
Create or simply read branches from an input stream.
Definition TTree.cxx:7612
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:8915
Int_t fScanField
Number of runs before prompting in Scan.
Definition TTree.h:92
void Draw(Option_t *opt) override
Default Draw method for all objects.
Definition TTree.h:431
virtual TTree * GetFriend(const char *) const
Return a pointer to the TTree friend whose name or alias is friendname.
Definition TTree.cxx:5972
virtual Long64_t CopyEntries(TTree *tree, Long64_t nentries=-1, Option_t *option="", Bool_t needCopyAddresses=false)
Copy nentries from given tree to this tree.
Definition TTree.cxx:3531
virtual void SetNotify(TObject *obj)
Sets the address of the object to be notified when the tree is loaded.
Definition TTree.cxx:9218
virtual Double_t GetMaximum(const char *columname)
Return maximum of column with name columname.
Definition TTree.cxx:6232
virtual Long64_t GetEntryNumberWithBestIndex(Long64_t major, Long64_t minor=0) const
Return entry number corresponding to major and minor number.
Definition TTree.cxx:5887
static void SetMaxTreeSize(Long64_t maxsize=100000000000LL)
Set the maximum size in bytes of a Tree file (static function).
Definition TTree.cxx:9184
void Print(Option_t *option="") const override
Print a summary of the tree contents.
Definition TTree.cxx:7216
virtual TBranch * BronchExec(const char *name, const char *classname, void *addobj, Bool_t isptrptr, Int_t bufsize, Int_t splitlevel)
Helper function implementing TTree::Bronch and TTree::Branch(const char *name, T &obj);.
Definition TTree.cxx:2412
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:9689
Int_t fNClusterRange
Number of Cluster range in addition to the one defined by 'AutoFlush'.
Definition TTree.h:95
virtual void PrintCacheStats(Option_t *option="") const
Print statistics about the TreeCache for this tree.
Definition TTree.cxx:7367
virtual Int_t BuildIndex(const char *majorname, const char *minorname="0")
Build a Tree Index (default is TTreeIndex).
Definition TTree.cxx:2637
TVirtualTreePlayer * fPlayer
! Pointer to current Tree player
Definition TTree.h:134
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:9164
TObjArray fBranches
List of Branches.
Definition TTree.h:122
TDirectory * GetDirectory() const
Definition TTree.h:462
TTreeCache * GetReadCache(TFile *file) const
Find and return the TTreeCache registered with the file and which may contain branches for us.
Definition TTree.cxx:6315
Bool_t fCacheUserSet
! true if the cache setting was explicitly given by user
Definition TTree.h:141
Long64_t fEntries
Number of entries.
Definition TTree.h:84
virtual TFile * ChangeFile(TFile *file)
Called by TTree::Fill() when file has reached its maximum fgMaxTreeSize.
Definition TTree.cxx:2749
virtual Bool_t GetBranchStatus(const char *branchname) const
Return status of branch with name branchname.
Definition TTree.cxx:5377
virtual TEntryList * GetEntryList()
Returns the entry list assigned to this tree.
Definition TTree.cxx:5851
TStreamerInfo * BuildStreamerInfo(TClass *cl, void *pointer=nullptr, Bool_t canOptimize=kTRUE)
Build StreamerInfo for class cl.
Definition TTree.cxx:2652
virtual void SetWeight(Double_t w=1, Option_t *option="")
Set tree weight.
Definition TTree.cxx:9361
void InitializeBranchLists(bool checkLeafCount)
Divides the top-level branches into two vectors: (i) branches to be processed sequentially and (ii) b...
Definition TTree.cxx:5778
virtual Int_t SetBranchAddress(const char *bname, void *add, TBranch **ptr=nullptr)
Change branch address, dealing with clone trees properly.
Definition TTree.cxx:8377
Long64_t * fClusterSize
[fNClusterRange] Number of entries in each cluster for a given range.
Definition TTree.h:104
Long64_t fFlushedBytes
Number of auto-flushed bytes.
Definition TTree.h:89
virtual void SetPerfStats(TVirtualPerfStats *perf)
Set perf stats.
Definition TTree.cxx:9316
std::atomic< Long64_t > fIMTTotBytes
! Total bytes for the IMT flush baskets
Definition TTree.h:160
virtual void SetCacheLearnEntries(Int_t n=10)
Interface to TTreeCache to set the number of entries for the learning phase.
Definition TTree.cxx:8852
TEntryList * fEntryList
! Pointer to event selection list (if one)
Definition TTree.h:126
virtual TVirtualIndex * GetTreeIndex() const
Definition TTree.h:518
TList * fExternalFriends
! List of TFriendsElement pointing to us and need to be notified of LoadTree. Content not owned.
Definition TTree.h:131
virtual Long64_t Merge(TCollection *list, Option_t *option="")
Merge the trees in the TList into this tree.
Definition TTree.cxx:6887
virtual void SetMaxVirtualSize(Long64_t size=0)
Definition TTree.h:625
virtual void DropBaskets()
Remove some baskets from memory.
Definition TTree.cxx:4515
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:8334
Long64_t fMaxEntryLoop
Maximum number of entries to process.
Definition TTree.h:98
virtual void SetDirectory(TDirectory *dir)
Change the tree's directory.
Definition TTree.cxx:8953
void SortBranchesByTime()
Sorts top-level branches by the last average task time recorded per branch.
Definition TTree.cxx:5831
void Delete(Option_t *option="") override
Delete this tree from memory or/and disk.
Definition TTree.cxx:3744
virtual TBranchRef * GetBranchRef() const
Definition TTree.h:450
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:7447
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:1635
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:9056
void MoveReadCache(TFile *src, TDirectory *dir)
Move a cache from a file to the current file in dir.
Definition TTree.cxx:6980
Long64_t fAutoFlush
Auto-flush tree when fAutoFlush entries written or -fAutoFlush (compressed) bytes produced.
Definition TTree.h:101
Int_t fUpdate
Update frequency for EntryLoop.
Definition TTree.h:93
virtual void ResetAfterMerge(TFileMergeInfo *)
Resets the state of this TTree after a merge (keep the customization but forget the data).
Definition TTree.cxx:8031
virtual void CopyAddresses(TTree *, Bool_t undo=kFALSE)
Set branch addresses of passed tree equal to ours.
Definition TTree.cxx:3296
virtual Long64_t GetEntries() const
Definition TTree.h:463
virtual void SetEstimate(Long64_t nentries=1000000)
Set number of entries to estimate variable limits.
Definition TTree.cxx:9097
virtual TIterator * GetIteratorOnAllLeaves(Bool_t dir=kIterForward)
Creates a new iterator that will go through all the leaves on the tree itself and its friend.
Definition TTree.cxx:6079
Int_t fTimerInterval
Timer interval in milliseconds.
Definition TTree.h:91
Int_t fDebug
! Debug level
Definition TTree.h:111
virtual Long64_t AutoSave(Option_t *option="")
AutoSave tree header every fAutoSave bytes.
Definition TTree.cxx:1500
virtual Long64_t GetEntryNumber(Long64_t entry) const
Return entry number corresponding to entry.
Definition TTree.cxx:5862
virtual TTree * CloneTree(Long64_t nentries=-1, Option_t *option="")
Create a clone of this tree and copy nentries.
Definition TTree.cxx:3136
Int_t fFileNumber
! current file number (if file extensions)
Definition TTree.h:116
virtual TLeaf * GetLeaf(const char *branchname, const char *leafname)
Return pointer to the 1st Leaf named name in any Branch of this Tree or any branch in the list of fri...
Definition TTree.cxx:6192
virtual Long64_t GetZipBytes() const
Definition TTree.h:545
TObjArray fLeaves
Direct pointers to individual branch leaves.
Definition TTree.h:123
virtual void Reset(Option_t *option="")
Reset baskets, buffers and entries count in all branches and leaves.
Definition TTree.cxx:8000
virtual void KeepCircular()
Keep a maximum of fMaxEntries in memory.
Definition TTree.cxx:6412
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:3816
virtual Bool_t SetAlias(const char *aliasName, const char *aliasFormula)
Set a tree variable alias.
Definition TTree.cxx:8133
Long64_t fMaxVirtualSize
Maximum total size of buffers kept in memory.
Definition TTree.h:99
virtual Long64_t GetTotBytes() const
Definition TTree.h:516
virtual Int_t MakeSelector(const char *selector=nullptr, Option_t *option="")
Generate skeleton selector class for this tree.
Definition TTree.cxx:6819
virtual void SetObject(const char *name, const char *title)
Change the name and title of this tree.
Definition TTree.cxx:9247
TVirtualPerfStats * fPerfStats
! pointer to the current perf stats object
Definition TTree.h:132
Double_t fWeight
Tree weight (see TTree::SetWeight)
Definition TTree.h:90
std::vector< TBranch * > fSeqBranches
! Branches to be processed sequentially when IMT is on
Definition TTree.h:145
Bool_t EnableCache()
Enable the TTreeCache unless explicitly disabled for this TTree by a prior call to SetCacheSize(0).
Definition TTree.cxx:2685
Long64_t fDebugMax
! Last entry number to debug
Definition TTree.h:113
Int_t fDefaultEntryOffsetLen
Initial Length of fEntryOffset table in the basket buffers.
Definition TTree.h:94
TTree()
Default constructor and I/O constructor.
Definition TTree.cxx:737
Long64_t fAutoSave
Autosave tree when fAutoSave entries written or -fAutoSave (compressed) bytes produced.
Definition TTree.h:100
TBranch * Branch(const char *name, T *obj, Int_t bufsize=32000, Int_t splitlevel=99)
Add a new branch, and infer the data type from the type of obj being passed.
Definition TTree.h:353
virtual void SetDefaultEntryOffsetLen(Int_t newdefault, Bool_t updateExisting=kFALSE)
Update the default value for the branch's fEntryOffsetLen.
Definition TTree.cxx:8927
std::atomic< UInt_t > fAllocationCount
indicates basket should be resized to exact memory usage, but causes significant
Definition TTree.h:152
virtual Int_t GetEntryWithIndex(Int_t major, Int_t minor=0)
Read entry corresponding to major and minor number.
Definition TTree.cxx:5924
static TTree * MergeTrees(TList *list, Option_t *option="")
Static function merging the trees in the TList into a new tree.
Definition TTree.cxx:6848
virtual void SetBranchStatus(const char *bname, Bool_t status=1, UInt_t *found=nullptr)
Set branch status to Process or DoNotProcess.
Definition TTree.cxx:8526
virtual Long64_t GetReadEntry() const
Definition TTree.h:509
virtual TObjArray * GetListOfBranches()
Definition TTree.h:488
virtual void SetParallelUnzip(Bool_t opt=kTRUE, Float_t RelSize=-1)
Enable or disable parallel unzipping of Tree buffers.
Definition TTree.cxx:9278
Long64_t fZipBytes
Total number of bytes in all branches after compression.
Definition TTree.h:87
virtual TTree * GetTree() const
Definition TTree.h:517
TBuffer * fTransientBuffer
! Pointer to the current transient buffer.
Definition TTree.h:138
Bool_t fIMTEnabled
! true if implicit multi-threading is enabled for this tree
Definition TTree.h:142
virtual void SetEntryList(TEntryList *list, Option_t *opt="")
Set an EntryList.
Definition TTree.cxx:9033
virtual Int_t DropBranchFromCache(const char *bname, Bool_t subbranches=kFALSE)
Remove the branch with name 'bname' from the Tree cache.
Definition TTree.cxx:1142
virtual void AddZipBytes(Int_t zip)
Definition TTree.h:332
virtual Long64_t LoadTree(Long64_t entry)
Set current entry.
Definition TTree.cxx:6470
virtual Long64_t ReadFile(const char *filename, const char *branchDescriptor="", char delimiter=' ')
Create or simply read branches from filename.
Definition TTree.cxx:7561
virtual const char * GetAlias(const char *aliasName) const
Returns the expanded value of the alias. Search in the friends if any.
Definition TTree.cxx:5223
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:9117
virtual TBasket * CreateBasket(TBranch *)
Create a basket for this tree and given branch.
Definition TTree.cxx:3728
TList * fUserInfo
pointer to a list of user objects associated to this Tree
Definition TTree.h:133
virtual Double_t GetMinimum(const char *columname)
Return minimum of column with name columname.
Definition TTree.cxx:6272
virtual void RemoveFriend(TTree *)
Remove a friend from the list of friends.
Definition TTree.cxx:7974
virtual Long64_t GetEntriesFast() const
Definition TTree.h:465
void Browse(TBrowser *) override
Browse content of the TTree.
Definition TTree.cxx:2609
virtual TList * GetUserInfo()
Return a pointer to the list containing user objects associated to this tree.
Definition TTree.cxx:6353
Long64_t fChainOffset
! Offset of 1st entry of this Tree in a TChain
Definition TTree.h:106
@ kOnlyFlushAtCluster
If set, the branch's buffers will grow until an event cluster boundary is hit, guaranteeing a basket ...
Definition TTree.h:256
@ kEntriesReshuffled
If set, signals that this TTree is the output of the processing of another TTree, and the entries are...
Definition TTree.h:261
@ kCircular
Definition TTree.h:252
virtual Long64_t GetEntriesFriend() const
Return pointer to the 1st Leaf named name in any Branch of this Tree or any branch in the list of fri...
Definition TTree.cxx:5509
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:7510
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:2404
virtual void SetBasketSize(const char *bname, Int_t buffsize=16000)
Set a branch's basket size.
Definition TTree.cxx:8350
static void SetBranchStyle(Int_t style=1)
Set the current branch style.
Definition TTree.cxx:8657
~TTree() override
Destructor.
Definition TTree.cxx:920
void ImportClusterRanges(TTree *fromtree)
Appends the cluster range information stored in 'fromtree' to this tree, including the value of fAuto...
Definition TTree.cxx:6369
TClass * IsA() const override
Definition TTree.h:659
Long64_t fEstimate
Number of entries to estimate histogram limits.
Definition TTree.h:102
Int_t FlushBasketsImpl() const
Internal implementation of the FlushBaskets algorithm.
Definition TTree.cxx:5143
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:6554
@ kSplitCollectionOfPointers
Definition TTree.h:266
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:9740
TVirtualIndex * fTreeIndex
Pointer to the tree Index (if any)
Definition TTree.h:129
void UseCurrentStyle() override
Replace current attributes by current style.
Definition TTree.cxx:9701
TObject * fNotify
Object to be notified when loading a Tree.
Definition TTree.h:120
virtual TBranch * BranchImp(const char *branchname, const char *classname, TClass *ptrClass, void *addobj, Int_t bufsize, Int_t splitlevel)
Same as TTree::Branch() with added check that addobj matches className.
Definition TTree.cxx:1554
Long64_t fCacheSize
! Maximum size of file buffers
Definition TTree.h:105
TList * fClones
! List of cloned trees which share our addresses
Definition TTree.h:135
std::atomic< Long64_t > fTotalBuffers
! Total number of bytes in branch buffers
Definition TTree.h:108
Bool_t fCacheDoAutoInit
! true if cache auto creation or resize check is needed
Definition TTree.h:139
static TClass * Class()
@ kFindBranch
Definition TTree.h:212
@ kFindLeaf
Definition TTree.h:213
@ kGetEntryWithIndex
Definition TTree.h:217
@ kPrint
Definition TTree.h:222
@ kGetFriend
Definition TTree.h:218
@ kGetBranch
Definition TTree.h:215
@ kSetBranchStatus
Definition TTree.h:224
@ kLoadTree
Definition TTree.h:221
@ kGetEntry
Definition TTree.h:216
@ kGetLeaf
Definition TTree.h:220
@ kRemoveFriend
Definition TTree.h:223
@ kGetFriendAlias
Definition TTree.h:219
@ kGetAlias
Definition TTree.h:214
virtual void SetTreeIndex(TVirtualIndex *index)
The current TreeIndex is replaced by the new index.
Definition TTree.cxx:9333
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:7054
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:7495
virtual Int_t SetCacheEntryRange(Long64_t first, Long64_t last)
interface to TTreeCache to set the cache entry range
Definition TTree.cxx:8818
static Long64_t GetMaxTreeSize()
Static function which returns the tree file size limit in bytes.
Definition TTree.cxx:6262
Int_t SetBranchAddressImp(TBranch *branch, void *addr, TBranch **ptr)
Change branch address, dealing with clone trees properly.
Definition TTree.cxx:8437
Long64_t fMaxEntries
Maximum number of entries in case of circular buffers.
Definition TTree.h:97
virtual void DropBuffers(Int_t nbytes)
Drop branch buffers to accommodate nbytes below MaxVirtualsize.
Definition TTree.cxx:4528
virtual TList * GetListOfFriends() const
Definition TTree.h:490
virtual void Refresh()
Refresh contents of this tree and its branches from the current status on disk.
Definition TTree.cxx:7913
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:8188
static Long64_t fgMaxTreeSize
Maximum size of a file containing a Tree.
Definition TTree.h:155
Long64_t fReadEntry
! Number of the entry being processed
Definition TTree.h:107
TArrayD fIndexValues
Sorted index values.
Definition TTree.h:127
void MarkEventCluster()
Mark the previous event as being at the end of the event cluster.
Definition TTree.cxx:8250
UInt_t fNEntriesSinceSorting
! Number of entries processed since the last re-sorting of branches
Definition TTree.h:143
virtual void SetFileNumber(Int_t number=0)
Set fFileNumber to number.
Definition TTree.cxx:9140
virtual TLeaf * FindLeaf(const char *name)
Find leaf..
Definition TTree.cxx:4913
virtual void StartViewer()
Start the TTreeViewer on this tree.
Definition TTree.cxx:9446
Int_t GetMakeClass() const
Definition TTree.h:495
virtual Int_t MakeCode(const char *filename=nullptr)
Generate a skeleton function for this tree.
Definition TTree.cxx:6637
TDirectory * fDirectory
! Pointer to directory holding this tree
Definition TTree.h:121
@ kNeedEnableDecomposedObj
Definition TTree.h:244
@ kClassMismatch
Definition TTree.h:237
@ kVoidPtr
Definition TTree.h:242
@ kMatchConversionCollection
Definition TTree.h:240
@ kMissingCompiledCollectionProxy
Definition TTree.h:235
@ kMismatch
Definition TTree.h:236
@ kMatchConversion
Definition TTree.h:239
@ kInternalError
Definition TTree.h:234
@ kMatch
Definition TTree.h:238
@ kMissingBranch
Definition TTree.h:233
@ kMakeClass
Definition TTree.h:241
static Int_t fgBranchStyle
Old/New branch style.
Definition TTree.h:154
virtual void ResetBranchAddresses()
Tell all of our branches to drop their current objects and allocate new ones.
Definition TTree.cxx:8072
Int_t fNfill
! Local for EntryLoop
Definition TTree.h:110
void SetName(const char *name) override
Change the name of this tree.
Definition TTree.cxx:9192
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:7954
TArrayI fIndex
Index of sorted values.
Definition TTree.h:128
virtual Int_t SetCacheSize(Long64_t cachesize=-1)
Set maximum size of the file cache .
Definition TTree.cxx:8673
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:1219
TBuffer * GetTransientBuffer(Int_t size)
Returns the transient buffer currently used by this TTree for reading/writing baskets.
Definition TTree.cxx:1037
ROOT::TIOFeatures GetIOFeatures() const
Returns the current set of IO settings.
Definition TTree.cxx:6071
virtual Int_t MakeClass(const char *classname=nullptr, Option_t *option="")
Generate a skeleton analysis class for this tree.
Definition TTree.cxx:6604
virtual const char * GetFriendAlias(TTree *) const
If the 'tree' is a friend, this method returns its alias name.
Definition TTree.cxx:6029
virtual void RemoveExternalFriend(TFriendElement *)
Removes external friend.
Definition TTree.cxx:7965
Bool_t MemoryFull(Int_t nbytes)
Check if adding nbytes to memory we are still below MaxVirtualsize.
Definition TTree.cxx:6834
Int_t fPacketSize
! Number of entries in one packet for parallel root
Definition TTree.h:109
virtual TBranch * BranchImpArr(const char *branchname, EDataType datatype, std::size_t N, void *addobj, Int_t bufsize, Int_t splitlevel)
Definition TTree.cxx:1731
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:8091
Bool_t fIMTFlush
! True if we are doing a multithreaded flush.
Definition TTree.h:159
virtual void AddTotBytes(Int_t tot)
Definition TTree.h:331
Int_t fMakeClass
! not zero when processing code generated by MakeClass
Definition TTree.h:115
virtual Int_t LoadBaskets(Long64_t maxmemory=2000000000)
Read in memory all baskets from all branches up to the limit of maxmemory bytes.
Definition TTree.cxx:6448
static constexpr Long64_t kMaxEntries
Definition TTree.h:229
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:7197
virtual Long64_t GetAutoFlush() const
Definition TTree.h:447
Defines a common interface to inspect/change the contents of an object that represents a collection.
virtual EDataType GetType() const =0
If the value type is a fundamental data type, return its type (see enumeration EDataType).
virtual TClass * GetValueClass() const =0
If the value type is a user-defined class, return a pointer to the TClass representing the value type...
virtual Bool_t HasPointers() const =0
Return true if the content is of type 'pointer to'.
Abstract interface for Tree Index.
virtual void Append(const TVirtualIndex *, Bool_t delaySort=kFALSE)=0
virtual const char * GetMajorName() const =0
virtual Long64_t GetEntryNumberWithIndex(Long64_t major, Long64_t minor) const =0
virtual Long64_t GetEntryNumberFriend(const TTree *)=0
virtual const char * GetMinorName() const =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
virtual Bool_t IsValidFor(const TTree *parent)=0
Provides the interface for the PROOF internal performance measurement and event tracing.
Abstract base class defining the interface for the plugins that implement Draw, Scan,...
virtual Long64_t Scan(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)=0
virtual void UpdateFormulaLeaves()=0
virtual Long64_t DrawSelect(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)=0
virtual Int_t MakeCode(const char *filename)=0
virtual Int_t UnbinnedFit(const char *formula, const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)=0
virtual Long64_t GetEntries(const char *)=0
virtual Int_t MakeProxy(const char *classname, const char *macrofilename=nullptr, const char *cutfilename=nullptr, const char *option=nullptr, Int_t maxUnrolling=3)=0
virtual TSQLResult * Query(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)=0
virtual TPrincipal * Principal(const char *varexp="", const char *selection="", Option_t *option="np", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)=0
virtual void StartViewer(Int_t ww, Int_t wh)=0
virtual Int_t MakeReader(const char *classname, Option_t *option)=0
virtual TVirtualIndex * BuildIndex(const TTree *T, const char *majorname, const char *minorname)=0
virtual TTree * CopyTree(const char *selection, Option_t *option="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)=0
virtual Long64_t Process(const char *filename, Option_t *option="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)=0
virtual void SetEstimate(Long64_t n)=0
static TVirtualTreePlayer * TreePlayer(TTree *obj)
Static function returning a pointer to a Tree player.
virtual Int_t MakeClass(const char *classname, const char *option)=0
virtual Int_t Fit(const char *formula, const char *varexp, const char *selection, Option_t *option, Option_t *goption, Long64_t nentries, Long64_t firstentry)=0
TLine * line
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:387
This file contains a specialised ROOT message handler to test for diagnostic in unit tests.
Bool_t IsImplicitMTEnabled()
Returns true if the implicit multi-threading in ROOT is enabled.
Definition TROOT.cxx:570
ESTLType
Definition ESTLType.h:28
@ kSTLmap
Definition ESTLType.h:33
@ kSTLmultimap
Definition ESTLType.h:34
void CallRecursiveRemoveIfNeeded(TObject &obj)
call RecursiveRemove for obj if gROOT is valid and obj.TestBit(kMustCleanup) is true.
Definition TROOT.h:396
void ToHumanReadableSize(value_type bytes, Bool_t si, Double_t *coeff, const char **units)
Return the size expressed in 'human readable' format.
EFromHumanReadableSize FromHumanReadableSize(std::string_view str, T &value)
Convert strings like the following into byte counts 5MB, 5 MB, 5M, 3.7GB, 123b, 456kB,...
Short_t Max(Short_t a, Short_t b)
Returns the largest of a and b.
Definition TMathBase.h:250
Double_t Median(Long64_t n, const T *a, const Double_t *w=nullptr, Long64_t *work=nullptr)
Same as RMS.
Definition TMath.h:1272
Short_t Min(Short_t a, Short_t b)
Returns the smallest of a and b.
Definition TMathBase.h:198
Long64_t BinarySearch(Long64_t n, const T *array, T value)
Binary search in an array of n values to locate value.
Definition TMathBase.h:347
Definition file.py:1
Definition first.py:1
Definition tree.py:1
TCanvas * slash()
Definition slash.C:1
@ kUseGlobal
Use the global compression algorithm.
Definition Compression.h:90
@ kInherit
Some objects use this value to denote that the compression algorithm should be inherited from the par...
Definition Compression.h:88
@ kUseCompiledDefault
Use the compile-time default setting.
Definition Compression.h:52
th1 Draw()
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4