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`)
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 = false;
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)
761, fClusterRangeEnd(nullptr)
762, fClusterSize(nullptr)
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(nullptr)
775, fDirectory(nullptr)
776, fBranches()
777, fLeaves()
778, fAliases(nullptr)
779, fEventList(nullptr)
780, fEntryList(nullptr)
781, fIndexValues()
782, fIndex()
783, fTreeIndex(nullptr)
784, fFriends(nullptr)
785, fExternalFriends(nullptr)
786, fPerfStats(nullptr)
787, fUserInfo(nullptr)
788, fPlayer(nullptr)
789, fClones(nullptr)
790, fBranchRef(nullptr)
792, fTransientBuffer(nullptr)
793, fCacheDoAutoInit(true)
795, fCacheUserSet(false)
796, fIMTEnabled(ROOT::IsImplicitMTEnabled())
798{
799 fMaxEntries = 1000000000;
800 fMaxEntries *= 1000;
801
802 fMaxEntryLoop = 1000000000;
803 fMaxEntryLoop *= 1000;
804
805 fBranches.SetOwner(true);
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(nullptr)
843, fClusterSize(nullptr)
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(nullptr)
856, fDirectory(dir)
857, fBranches()
858, fLeaves()
859, fAliases(nullptr)
860, fEventList(nullptr)
861, fEntryList(nullptr)
862, fIndexValues()
863, fIndex()
864, fTreeIndex(nullptr)
865, fFriends(nullptr)
866, fExternalFriends(nullptr)
867, fPerfStats(nullptr)
868, fUserInfo(nullptr)
869, fPlayer(nullptr)
870, fClones(nullptr)
871, fBranchRef(nullptr)
872, fFriendLockStatus(0)
873, fTransientBuffer(nullptr)
874, fCacheDoAutoInit(true)
875, fCacheDoClusterPrefetch(false)
876, fCacheUserSet(false)
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
906 fBranches.SetOwner(true);
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
940 TFile *file = fDirectory->GetFile();
941 MoveReadCache(file,nullptr);
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.
965 CopyAddresses(clone,true);
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 = nullptr;
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 = nullptr;
990 }
991 if (fAliases) {
992 fAliases->Delete();
993 delete fAliases;
994 fAliases = nullptr;
995 }
996 if (fUserInfo) {
997 fUserInfo->Delete();
998 delete fUserInfo;
999 fUserInfo = nullptr;
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 = nullptr;
1010 }
1011 if (fEntryList) {
1012 if (fEntryList->TestBit(kCanDelete) && fEntryList->GetDirectory()==nullptr) {
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=nullptr;
1018 }
1019 }
1020 delete fTreeIndex;
1021 fTreeIndex = nullptr;
1022 delete fBranchRef;
1023 fBranchRef = nullptr;
1024 delete [] fClusterRangeEnd;
1025 fClusterRangeEnd = nullptr;
1026 delete [] fClusterSize;
1027 fClusterSize = nullptr;
1028
1029 if (fTransientBuffer) {
1030 delete fTransientBuffer;
1031 fTransientBuffer = nullptr;
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 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 }
1082 TTreeCache *tc = GetReadCache(f,true);
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
1099Int_t TTree::AddBranchToCache(TBranch *b, bool subbranches)
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 }
1125 TTreeCache *tc = GetReadCache(f,true);
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 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 }
1165 TTreeCache *tc = GetReadCache(f,true);
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
1182Int_t TTree::DropBranchFromCache(TBranch *b, bool subbranches)
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 }
1208 TTreeCache *tc = GetReadCache(f,true);
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.
1220void TTree::AddClone(TTree* clone)
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) : false;
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 warn)
1399{
1400 if (!tree) {
1401 return nullptr;
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
1529 TFile *file = fDirectory->GetFile();
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 nullptr;
1563 }
1564 return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
1565 }
1566 TClass* actualClass = nullptr;
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 nullptr;
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 nullptr;
1608 }
1609 TClass* actualClass = nullptr;
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 nullptr;
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 nullptr;
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 nullptr;
1644 } else if (claim == nullptr) {
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 nullptr;
1647 }
1648 ptrClass = claim;
1649 }
1650 TClass* actualClass = nullptr;
1651 if (!addobj) {
1652 Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
1653 return nullptr;
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 nullptr;
1683 }
1684 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1685 Error("Branch", writeStlWithoutProxyMsg,
1686 actualClass->GetName(), branchname, actualClass->GetName());
1687 return nullptr;
1688 }
1689 return BronchExec(branchname, actualClass->GetName(), (void*) addobj, false, 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 nullptr;
1706 }
1707 TClass* actualClass = nullptr;
1708 if (!addobj) {
1709 Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
1710 return nullptr;
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 nullptr;
1720 }
1721 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1722 Error("Branch", writeStlWithoutProxyMsg,
1723 actualClass->GetName(), branchname, actualClass->GetName());
1724 return nullptr;
1725 }
1726 return BronchExec(branchname, actualClass->GetName(), (void*) addobj, false, 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 = nullptr;
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 = nullptr;
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`)
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 = nullptr;
1993 return nullptr;
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 nullptr;
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 nullptr;
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 = nullptr;
2101 const char* dname = nullptr;
2102 TString branchname;
2103 char** apointer = (char**) addobj;
2104 TObject* obj = (TObject*) *apointer;
2105 bool delobj = false;
2106 if (!obj) {
2107 obj = (TObject*) cl->New();
2108 delobj = true;
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 = nullptr;
2119 TRealData* rd = nullptr;
2120 TRealData* rdi = nullptr;
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 = nullptr;
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 = nullptr;
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, true, 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 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 nullptr;
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 = nullptr;
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 nullptr;
2438 }
2439 if (!clones->GetClass()) {
2440 Error("Bronch", "TClonesArray with no class defined in branch: %s", name);
2441 return nullptr;
2442 }
2443 if (!clones->GetClass()->HasDataMemberInfo()) {
2444 Error("Bronch", "TClonesArray with no dictionary defined in branch: %s", name);
2445 return nullptr;
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(false);
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 nullptr;
2468 }
2469 if ((splitlevel > 0) && inklass && (inklass->GetCollectionProxy() == nullptr)) {
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 nullptr;
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 hasCustomStreamer = false;
2501 if (!cl->HasDataMemberInfo() && !cl->GetCollectionProxy()) {
2502 Error("Bronch", "Cannot find dictionary for class: %s", classname);
2503 return nullptr;
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 = true;
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 delobj = false;
2540
2541 if (!objptr) {
2542 objptr = (char*) cl->New();
2543 delobj = true;
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 nullptr;
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 = nullptr;
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 = nullptr;
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 canOptimize /* = true */ )
2654{
2655 if (!cl) {
2656 return nullptr;
2657 }
2658 cl->BuildRealData(pointer);
2660
2661 // Create StreamerInfo for all base classes.
2662 TBaseClass* base = nullptr;
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)
2686bool TTree::EnableCache()
2687{
2688 TFile* file = GetCurrentFile();
2689 if (!file)
2690 return false;
2691 // Check for an existing cache
2692 TTreeCache* pf = GetReadCache(file);
2693 if (pf)
2694 return true;
2695 if (fCacheUserSet && fCacheSize == 0)
2696 return false;
2697 return (0 == SetCacheSizeAux(true, -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 == nullptr) {
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 = nullptr;
2809 TObject* obj = nullptr;
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 = nullptr;
2841 delete[] fname;
2842 fname = nullptr;
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 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 = nullptr;
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 == nullptr) {
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. See TTree::SetBranchStatus for more
3081/// information and usage regarding the (de)activation of branches. More
3082/// examples are provided in the tutorials listed below.
3083///
3084/// NOTE: If the TTree is a TChain, the structure of the first TTree
3085/// is used for the copy.
3086///
3087/// IMPORTANT: The cloned tree stays connected with this tree until
3088/// this tree is deleted. In particular, any changes in
3089/// branch addresses in this tree are forwarded to the
3090/// clone trees, unless a branch in a clone tree has had
3091/// its address changed, in which case that change stays in
3092/// effect. When this tree is deleted, all the addresses of
3093/// the cloned tree are reset to their default values.
3094///
3095/// If 'option' contains the word 'fast' and nentries is -1, the
3096/// cloning will be done without unzipping or unstreaming the baskets
3097/// (i.e., a direct copy of the raw bytes on disk).
3098///
3099/// When 'fast' is specified, 'option' can also contain a sorting
3100/// order for the baskets in the output file.
3101///
3102/// There are currently 3 supported sorting order:
3103///
3104/// - SortBasketsByOffset (the default)
3105/// - SortBasketsByBranch
3106/// - SortBasketsByEntry
3107///
3108/// When using SortBasketsByOffset the baskets are written in the
3109/// output file in the same order as in the original file (i.e. the
3110/// baskets are sorted by their offset in the original file; Usually
3111/// this also means that the baskets are sorted by the index/number of
3112/// the _last_ entry they contain)
3113///
3114/// When using SortBasketsByBranch all the baskets of each individual
3115/// branches are stored contiguously. This tends to optimize reading
3116/// speed when reading a small number (1->5) of branches, since all
3117/// their baskets will be clustered together instead of being spread
3118/// across the file. However it might decrease the performance when
3119/// reading more branches (or the full entry).
3120///
3121/// When using SortBasketsByEntry the baskets with the lowest starting
3122/// entry are written first. (i.e. the baskets are sorted by the
3123/// index/number of the first entry they contain). This means that on
3124/// the file the baskets will be in the order in which they will be
3125/// needed when reading the whole tree sequentially.
3126///
3127/// For examples of CloneTree, see tutorials:
3128///
3129/// - copytree.C:
3130/// A macro to copy a subset of a TTree to a new TTree.
3131/// The input file has been generated by the program in
3132/// $ROOTSYS/test/Event with: Event 1000 1 1 1
3133///
3134/// - copytree2.C:
3135/// A macro to copy a subset of a TTree to a new TTree.
3136/// One branch of the new Tree is written to a separate file.
3137/// The input file has been generated by the program in
3138/// $ROOTSYS/test/Event with: Event 1000 1 1 1
3140TTree* TTree::CloneTree(Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
3141{
3142 // Options
3143 bool fastClone = false;
3144
3145 TString opt = option;
3146 opt.ToLower();
3147 if (opt.Contains("fast")) {
3148 fastClone = true;
3149 }
3150
3151 // If we are a chain, switch to the first tree.
3152 if ((fEntries > 0) && (LoadTree(0) < 0)) {
3153 // FIXME: We need an error message here.
3154 return nullptr;
3155 }
3156
3157 // Note: For a tree we get the this pointer, for
3158 // a chain we get the chain's current tree.
3159 TTree* thistree = GetTree();
3160
3161 // We will use this to override the IO features on the cloned branches.
3162 ROOT::TIOFeatures features = this->GetIOFeatures();
3163 ;
3164
3165 // Note: For a chain, the returned clone will be
3166 // a clone of the chain's first tree.
3167 TTree* newtree = (TTree*) thistree->Clone();
3168 if (!newtree) {
3169 return nullptr;
3170 }
3171
3172 // The clone should not delete any objects allocated by SetAddress().
3173 TObjArray* branches = newtree->GetListOfBranches();
3174 Int_t nb = branches->GetEntriesFast();
3175 for (Int_t i = 0; i < nb; ++i) {
3176 TBranch* br = (TBranch*) branches->UncheckedAt(i);
3178 ((TBranchElement*) br)->ResetDeleteObject();
3179 }
3180 }
3181
3182 // Add the new tree to the list of clones so that
3183 // we can later inform it of changes to branch addresses.
3184 thistree->AddClone(newtree);
3185 if (thistree != this) {
3186 // In case this object is a TChain, add the clone
3187 // also to the TChain's list of clones.
3188 AddClone(newtree);
3189 }
3190
3191 newtree->Reset();
3192
3193 TDirectory* ndir = newtree->GetDirectory();
3194 TFile* nfile = nullptr;
3195 if (ndir) {
3196 nfile = ndir->GetFile();
3197 }
3198 Int_t newcomp = -1;
3199 if (nfile) {
3200 newcomp = nfile->GetCompressionSettings();
3201 }
3202
3203 //
3204 // Delete non-active branches from the clone.
3205 //
3206 // Note: If we are a chain, this does nothing
3207 // since chains have no leaves.
3208 TObjArray* leaves = newtree->GetListOfLeaves();
3209 Int_t nleaves = leaves->GetEntriesFast();
3210 for (Int_t lndx = 0; lndx < nleaves; ++lndx) {
3211 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(lndx);
3212 if (!leaf) {
3213 continue;
3214 }
3215 TBranch* branch = leaf->GetBranch();
3216 if (branch && (newcomp > -1)) {
3217 branch->SetCompressionSettings(newcomp);
3218 }
3219 if (branch) branch->SetIOFeatures(features);
3220 if (!branch || !branch->TestBit(kDoNotProcess)) {
3221 continue;
3222 }
3223 // size might change at each iteration of the loop over the leaves.
3224 nb = branches->GetEntriesFast();
3225 for (Long64_t i = 0; i < nb; ++i) {
3226 TBranch* br = (TBranch*) branches->UncheckedAt(i);
3227 if (br == branch) {
3228 branches->RemoveAt(i);
3229 delete br;
3230 br = nullptr;
3231 branches->Compress();
3232 break;
3233 }
3234 TObjArray* lb = br->GetListOfBranches();
3235 Int_t nb1 = lb->GetEntriesFast();
3236 for (Int_t j = 0; j < nb1; ++j) {
3237 TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
3238 if (!b1) {
3239 continue;
3240 }
3241 if (b1 == branch) {
3242 lb->RemoveAt(j);
3243 delete b1;
3244 b1 = nullptr;
3245 lb->Compress();
3246 break;
3247 }
3248 TObjArray* lb1 = b1->GetListOfBranches();
3249 Int_t nb2 = lb1->GetEntriesFast();
3250 for (Int_t k = 0; k < nb2; ++k) {
3251 TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
3252 if (!b2) {
3253 continue;
3254 }
3255 if (b2 == branch) {
3256 lb1->RemoveAt(k);
3257 delete b2;
3258 b2 = nullptr;
3259 lb1->Compress();
3260 break;
3261 }
3262 }
3263 }
3264 }
3265 }
3266 leaves->Compress();
3267
3268 // Copy MakeClass status.
3269 newtree->SetMakeClass(fMakeClass);
3270
3271 // Copy branch addresses.
3272 CopyAddresses(newtree);
3273
3274 //
3275 // Copy entries if requested.
3276 //
3277
3278 if (nentries != 0) {
3279 if (fastClone && (nentries < 0)) {
3280 if ( newtree->CopyEntries( this, -1, option, false ) < 0 ) {
3281 // There was a problem!
3282 Error("CloneTTree", "TTree has not been cloned\n");
3283 delete newtree;
3284 newtree = nullptr;
3285 return nullptr;
3286 }
3287 } else {
3288 newtree->CopyEntries( this, nentries, option, false );
3289 }
3290 }
3291
3292 return newtree;
3293}
3294
3295////////////////////////////////////////////////////////////////////////////////
3296/// Set branch addresses of passed tree equal to ours.
3297/// If undo is true, reset the branch addresses instead of copying them.
3298/// This ensures 'separation' of a cloned tree from its original.
3300void TTree::CopyAddresses(TTree* tree, bool undo)
3301{
3302 // Copy branch addresses starting from branches.
3303 TObjArray* branches = GetListOfBranches();
3304 Int_t nbranches = branches->GetEntriesFast();
3305 for (Int_t i = 0; i < nbranches; ++i) {
3306 TBranch* branch = (TBranch*) branches->UncheckedAt(i);
3307 if (branch->TestBit(kDoNotProcess)) {
3308 continue;
3309 }
3310 if (undo) {
3311 TBranch* br = tree->GetBranch(branch->GetName());
3312 tree->ResetBranchAddress(br);
3313 } else {
3314 char* addr = branch->GetAddress();
3315 if (!addr) {
3316 if (branch->IsA() == TBranch::Class()) {
3317 // If the branch was created using a leaflist, the branch itself may not have
3318 // an address but the leaf might already.
3319 TLeaf *firstleaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
3320 if (!firstleaf || firstleaf->GetValuePointer()) {
3321 // Either there is no leaf (and thus no point in copying the address)
3322 // or the leaf has an address but we can not copy it via the branche
3323 // this will be copied via the next loop (over the leaf).
3324 continue;
3325 }
3326 }
3327 // Note: This may cause an object to be allocated.
3328 branch->SetAddress(nullptr);
3329 addr = branch->GetAddress();
3330 }
3331 TBranch* br = tree->GetBranch(branch->GetFullName());
3332 if (br) {
3333 if (br->GetMakeClass() != branch->GetMakeClass())
3334 br->SetMakeClass(branch->GetMakeClass());
3335 br->SetAddress(addr);
3336 // The copy does not own any object allocated by SetAddress().
3338 ((TBranchElement*) br)->ResetDeleteObject();
3339 }
3340 } else {
3341 Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
3342 }
3343 }
3344 }
3345
3346 // Copy branch addresses starting from leaves.
3347 TObjArray* tleaves = tree->GetListOfLeaves();
3348 Int_t ntleaves = tleaves->GetEntriesFast();
3349 std::set<TLeaf*> updatedLeafCount;
3350 for (Int_t i = 0; i < ntleaves; ++i) {
3351 TLeaf* tleaf = (TLeaf*) tleaves->UncheckedAt(i);
3352 TBranch* tbranch = tleaf->GetBranch();
3353 TBranch* branch = GetBranch(tbranch->GetName());
3354 if (!branch) {
3355 continue;
3356 }
3357 TLeaf* leaf = branch->GetLeaf(tleaf->GetName());
3358 if (!leaf) {
3359 continue;
3360 }
3361 if (branch->TestBit(kDoNotProcess)) {
3362 continue;
3363 }
3364 if (undo) {
3365 // Now we know whether the address has been transfered
3366 tree->ResetBranchAddress(tbranch);
3367 } else {
3368 TBranchElement *mother = dynamic_cast<TBranchElement*>(leaf->GetBranch()->GetMother());
3369 bool needAddressReset = false;
3370 if (leaf->GetLeafCount() && (leaf->TestBit(TLeaf::kNewValue) || !leaf->GetValuePointer() || (mother && mother->IsObjectOwner())) && tleaf->GetLeafCount())
3371 {
3372 // If it is an array and it was allocated by the leaf itself,
3373 // let's make sure it is large enough for the incoming data.
3374 if (leaf->GetLeafCount()->GetMaximum() < tleaf->GetLeafCount()->GetMaximum()) {
3375 leaf->GetLeafCount()->IncludeRange( tleaf->GetLeafCount() );
3376 updatedLeafCount.insert(leaf->GetLeafCount());
3377 needAddressReset = true;
3378 } else {
3379 needAddressReset = (updatedLeafCount.find(leaf->GetLeafCount()) != updatedLeafCount.end());
3380 }
3381 }
3382 if (needAddressReset && leaf->GetValuePointer()) {
3383 if (leaf->IsA() == TLeafElement::Class() && mother)
3384 mother->ResetAddress();
3385 else
3386 leaf->SetAddress(nullptr);
3387 }
3388 if (!branch->GetAddress() && !leaf->GetValuePointer()) {
3389 // We should attempts to set the address of the branch.
3390 // something like:
3391 //(TBranchElement*)branch->GetMother()->SetAddress(0)
3392 //plus a few more subtleties (see TBranchElement::GetEntry).
3393 //but for now we go the simplest route:
3394 //
3395 // Note: This may result in the allocation of an object.
3396 branch->SetupAddresses();
3397 }
3398 if (branch->GetAddress()) {
3399 tree->SetBranchAddress(branch->GetName(), (void*) branch->GetAddress());
3400 TBranch* br = tree->GetBranch(branch->GetName());
3401 if (br) {
3402 if (br->IsA() != branch->IsA()) {
3403 Error(
3404 "CopyAddresses",
3405 "Branch kind mismatch between input tree '%s' and output tree '%s' for branch '%s': '%s' vs '%s'",
3406 tree->GetName(), br->GetTree()->GetName(), br->GetName(), branch->IsA()->GetName(),
3407 br->IsA()->GetName());
3408 }
3409 // The copy does not own any object allocated by SetAddress().
3410 // FIXME: We do too much here, br may not be a top-level branch.
3412 ((TBranchElement*) br)->ResetDeleteObject();
3413 }
3414 } else {
3415 Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
3416 }
3417 } else {
3418 tleaf->SetAddress(leaf->GetValuePointer());
3419 }
3420 }
3421 }
3422
3423 if (undo &&
3424 ( tree->IsA()->InheritsFrom("TNtuple") || tree->IsA()->InheritsFrom("TNtupleD") )
3425 ) {
3426 tree->ResetBranchAddresses();
3427 }
3428}
3429
3430namespace {
3431
3432 enum EOnIndexError { kDrop, kKeep, kBuild };
3433
3434 bool R__HandleIndex(EOnIndexError onIndexError, TTree *newtree, TTree *oldtree)
3435 {
3436 // Return true if we should continue to handle indices, false otherwise.
3437
3438 bool withIndex = true;
3439
3440 if ( newtree->GetTreeIndex() ) {
3441 if ( oldtree->GetTree()->GetTreeIndex() == nullptr ) {
3442 switch (onIndexError) {
3443 case kDrop:
3444 delete newtree->GetTreeIndex();
3445 newtree->SetTreeIndex(nullptr);
3446 withIndex = false;
3447 break;
3448 case kKeep:
3449 // Nothing to do really.
3450 break;
3451 case kBuild:
3452 // Build the index then copy it
3453 if (oldtree->GetTree()->BuildIndex(newtree->GetTreeIndex()->GetMajorName(), newtree->GetTreeIndex()->GetMinorName())) {
3454 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), true);
3455 // Clean up
3456 delete oldtree->GetTree()->GetTreeIndex();
3457 oldtree->GetTree()->SetTreeIndex(nullptr);
3458 }
3459 break;
3460 }
3461 } else {
3462 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), true);
3463 }
3464 } else if ( oldtree->GetTree()->GetTreeIndex() != nullptr ) {
3465 // We discover the first index in the middle of the chain.
3466 switch (onIndexError) {
3467 case kDrop:
3468 // Nothing to do really.
3469 break;
3470 case kKeep: {
3472 index->SetTree(newtree);
3473 newtree->SetTreeIndex(index);
3474 break;
3475 }
3476 case kBuild:
3477 if (newtree->GetEntries() == 0) {
3478 // Start an index.
3480 index->SetTree(newtree);
3481 newtree->SetTreeIndex(index);
3482 } else {
3483 // Build the index so far.
3484 if (newtree->BuildIndex(oldtree->GetTree()->GetTreeIndex()->GetMajorName(), oldtree->GetTree()->GetTreeIndex()->GetMinorName())) {
3485 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), true);
3486 }
3487 }
3488 break;
3489 }
3490 } else if ( onIndexError == kDrop ) {
3491 // There is no index on this or on tree->GetTree(), we know we have to ignore any further
3492 // index
3493 withIndex = false;
3494 }
3495 return withIndex;
3496 }
3497}
3498
3499////////////////////////////////////////////////////////////////////////////////
3500/// Copy nentries from given tree to this tree.
3501/// This routines assumes that the branches that intended to be copied are
3502/// already connected. The typical case is that this tree was created using
3503/// tree->CloneTree(0).
3504///
3505/// By default copy all entries.
3506///
3507/// Returns number of bytes copied to this tree.
3508///
3509/// If 'option' contains the word 'fast' and nentries is -1, the cloning will be
3510/// done without unzipping or unstreaming the baskets (i.e., a direct copy of the
3511/// raw bytes on disk).
3512///
3513/// When 'fast' is specified, 'option' can also contains a sorting order for the
3514/// baskets in the output file.
3515///
3516/// There are currently 3 supported sorting order:
3517///
3518/// - SortBasketsByOffset (the default)
3519/// - SortBasketsByBranch
3520/// - SortBasketsByEntry
3521///
3522/// See TTree::CloneTree for a detailed explanation of the semantics of these 3 options.
3523///
3524/// If the tree or any of the underlying tree of the chain has an index, that index and any
3525/// index in the subsequent underlying TTree objects will be merged.
3526///
3527/// There are currently three 'options' to control this merging:
3528/// - NoIndex : all the TTreeIndex object are dropped.
3529/// - DropIndexOnError : if any of the underlying TTree object do no have a TTreeIndex,
3530/// they are all dropped.
3531/// - AsIsIndexOnError [default]: In case of missing TTreeIndex, the resulting TTree index has gaps.
3532/// - BuildIndexOnError : If any of the underlying TTree objects do not have a TTreeIndex,
3533/// all TTreeIndex are 'ignored' and the missing piece are rebuilt.
3535Long64_t TTree::CopyEntries(TTree* tree, Long64_t nentries /* = -1 */, Option_t* option /* = "" */, bool needCopyAddresses /* = false */)
3536{
3537 if (!tree) {
3538 return 0;
3539 }
3540 // Options
3541 TString opt = option;
3542 opt.ToLower();
3543 bool fastClone = opt.Contains("fast");
3544 bool withIndex = !opt.Contains("noindex");
3545 EOnIndexError onIndexError;
3546 if (opt.Contains("asisindex")) {
3547 onIndexError = kKeep;
3548 } else if (opt.Contains("buildindex")) {
3549 onIndexError = kBuild;
3550 } else if (opt.Contains("dropindex")) {
3551 onIndexError = kDrop;
3552 } else {
3553 onIndexError = kBuild;
3554 }
3555 Ssiz_t cacheSizeLoc = opt.Index("cachesize=");
3556 Long64_t cacheSize = -1;
3557 if (cacheSizeLoc != TString::kNPOS) {
3558 // If the parse faile, cacheSize stays at -1.
3559 Ssiz_t cacheSizeEnd = opt.Index(" ",cacheSizeLoc+10) - (cacheSizeLoc+10);
3560 TSubString cacheSizeStr( opt(cacheSizeLoc+10,cacheSizeEnd) );
3561 auto parseResult = ROOT::FromHumanReadableSize(cacheSizeStr,cacheSize);
3562 if (parseResult == ROOT::EFromHumanReadableSize::kParseFail) {
3563 Warning("CopyEntries","The cachesize option can not be parsed: %s. The default size will be used.",cacheSizeStr.String().Data());
3564 } else if (parseResult == ROOT::EFromHumanReadableSize::kOverflow) {
3565 double m;
3566 const char *munit = nullptr;
3567 ROOT::ToHumanReadableSize(std::numeric_limits<decltype(cacheSize)>::max(),false,&m,&munit);
3568
3569 Warning("CopyEntries","The cachesize option is too large: %s (%g%s max). The default size will be used.",cacheSizeStr.String().Data(),m,munit);
3570 }
3571 }
3572 if (gDebug > 0 && cacheSize != -1) Info("CopyEntries","Using Cache size: %lld\n",cacheSize);
3573
3574 Long64_t nbytes = 0;
3575 Long64_t treeEntries = tree->GetEntriesFast();
3576 if (nentries < 0) {
3577 nentries = treeEntries;
3578 } else if (nentries > treeEntries) {
3579 nentries = treeEntries;
3580 }
3581
3582 if (fastClone && (nentries < 0 || nentries == tree->GetEntriesFast())) {
3583 // Quickly copy the basket without decompression and streaming.
3584 Long64_t totbytes = GetTotBytes();
3585 for (Long64_t i = 0; i < nentries; i += tree->GetTree()->GetEntries()) {
3586 if (tree->LoadTree(i) < 0) {
3587 break;
3588 }
3589 if ( withIndex ) {
3590 withIndex = R__HandleIndex( onIndexError, this, tree );
3591 }
3592 if (this->GetDirectory()) {
3593 TFile* file2 = this->GetDirectory()->GetFile();
3594 if (file2 && (file2->GetEND() > TTree::GetMaxTreeSize())) {
3595 if (this->GetDirectory() == (TDirectory*) file2) {
3596 this->ChangeFile(file2);
3597 }
3598 }
3599 }
3600 TTreeCloner cloner(tree->GetTree(), this, option, TTreeCloner::kNoWarnings);
3601 if (cloner.IsValid()) {
3602 this->SetEntries(this->GetEntries() + tree->GetTree()->GetEntries());
3603 if (cacheSize != -1) cloner.SetCacheSize(cacheSize);
3604 cloner.Exec();
3605 } else {
3606 if (i == 0) {
3607 Warning("CopyEntries","%s",cloner.GetWarning());
3608 // If the first cloning does not work, something is really wrong
3609 // (since apriori the source and target are exactly the same structure!)
3610 return -1;
3611 } else {
3612 if (cloner.NeedConversion()) {
3613 TTree *localtree = tree->GetTree();
3614 Long64_t tentries = localtree->GetEntries();
3615 if (needCopyAddresses) {
3616 // Copy MakeClass status.
3617 tree->SetMakeClass(fMakeClass);
3618 // Copy branch addresses.
3619 CopyAddresses(tree);
3620 }
3621 for (Long64_t ii = 0; ii < tentries; ii++) {
3622 if (localtree->GetEntry(ii) <= 0) {
3623 break;
3624 }
3625 this->Fill();
3626 }
3627 if (needCopyAddresses)
3628 tree->ResetBranchAddresses();
3629 if (this->GetTreeIndex()) {
3630 this->GetTreeIndex()->Append(tree->GetTree()->GetTreeIndex(), true);
3631 }
3632 } else {
3633 Warning("CopyEntries","%s",cloner.GetWarning());
3634 if (tree->GetDirectory() && tree->GetDirectory()->GetFile()) {
3635 Warning("CopyEntries", "Skipped file %s\n", tree->GetDirectory()->GetFile()->GetName());
3636 } else {
3637 Warning("CopyEntries", "Skipped file number %d\n", tree->GetTreeNumber());
3638 }
3639 }
3640 }
3641 }
3642
3643 }
3644 if (this->GetTreeIndex()) {
3645 this->GetTreeIndex()->Append(nullptr,false); // Force the sorting
3646 }
3647 nbytes = GetTotBytes() - totbytes;
3648 } else {
3649 if (nentries < 0) {
3650 nentries = treeEntries;
3651 } else if (nentries > treeEntries) {
3652 nentries = treeEntries;
3653 }
3654 if (needCopyAddresses) {
3655 // Copy MakeClass status.
3656 tree->SetMakeClass(fMakeClass);
3657 // Copy branch addresses.
3658 CopyAddresses(tree);
3659 }
3660 Int_t treenumber = -1;
3661 for (Long64_t i = 0; i < nentries; i++) {
3662 if (tree->LoadTree(i) < 0) {
3663 break;
3664 }
3665 if (treenumber != tree->GetTreeNumber()) {
3666 if ( withIndex ) {
3667 withIndex = R__HandleIndex( onIndexError, this, tree );
3668 }
3669 treenumber = tree->GetTreeNumber();
3670 }
3671 if (tree->GetEntry(i) <= 0) {
3672 break;
3673 }
3674 nbytes += this->Fill();
3675 }
3676 if (needCopyAddresses)
3677 tree->ResetBranchAddresses();
3678 if (this->GetTreeIndex()) {
3679 this->GetTreeIndex()->Append(nullptr,false); // Force the sorting
3680 }
3681 }
3682 return nbytes;
3683}
3684
3685////////////////////////////////////////////////////////////////////////////////
3686/// Copy a tree with selection.
3687///
3688/// ### Important:
3689///
3690/// The returned copied tree stays connected with the original tree
3691/// until the original tree is deleted. In particular, any changes
3692/// to the branch addresses in the original tree are also made to
3693/// the copied tree. Any changes made to the branch addresses of the
3694/// copied tree are overridden anytime the original tree changes its
3695/// branch addresses. When the original tree is deleted, all the
3696/// branch addresses of the copied tree are set to zero.
3697///
3698/// For examples of CopyTree, see the tutorials:
3699///
3700/// - copytree.C:
3701/// Example macro to copy a subset of a tree to a new tree.
3702/// The input file was generated by running the program in
3703/// $ROOTSYS/test/Event in this way:
3704/// ~~~ {.cpp}
3705/// ./Event 1000 1 1 1
3706/// ~~~
3707/// - copytree2.C
3708/// Example macro to copy a subset of a tree to a new tree.
3709/// One branch of the new tree is written to a separate file.
3710/// The input file was generated by running the program in
3711/// $ROOTSYS/test/Event in this way:
3712/// ~~~ {.cpp}
3713/// ./Event 1000 1 1 1
3714/// ~~~
3715/// - copytree3.C
3716/// Example macro to copy a subset of a tree to a new tree.
3717/// Only selected entries are copied to the new tree.
3718/// NOTE that only the active branches are copied.
3720TTree* TTree::CopyTree(const char* selection, Option_t* option /* = 0 */, Long64_t nentries /* = TTree::kMaxEntries */, Long64_t firstentry /* = 0 */)
3721{
3722 GetPlayer();
3723 if (fPlayer) {
3724 return fPlayer->CopyTree(selection, option, nentries, firstentry);
3725 }
3726 return nullptr;
3727}
3728
3729////////////////////////////////////////////////////////////////////////////////
3730/// Create a basket for this tree and given branch.
3733{
3734 if (!branch) {
3735 return nullptr;
3736 }
3737 return new TBasket(branch->GetName(), GetName(), branch);
3738}
3739
3740////////////////////////////////////////////////////////////////////////////////
3741/// Delete this tree from memory or/and disk.
3742///
3743/// - if option == "all" delete Tree object from memory AND from disk
3744/// all baskets on disk are deleted. All keys with same name
3745/// are deleted.
3746/// - if option =="" only Tree object in memory is deleted.
3748void TTree::Delete(Option_t* option /* = "" */)
3749{
3750 TFile *file = GetCurrentFile();
3751
3752 // delete all baskets and header from file
3753 if (file && option && !strcmp(option,"all")) {
3754 if (!file->IsWritable()) {
3755 Error("Delete","File : %s is not writable, cannot delete Tree:%s", file->GetName(),GetName());
3756 return;
3757 }
3758
3759 //find key and import Tree header in memory
3760 TKey *key = fDirectory->GetKey(GetName());
3761 if (!key) return;
3762
3763 TDirectory *dirsav = gDirectory;
3764 file->cd();
3765
3766 //get list of leaves and loop on all the branches baskets
3767 TIter next(GetListOfLeaves());
3768 TLeaf *leaf;
3769 char header[16];
3770 Int_t ntot = 0;
3771 Int_t nbask = 0;
3772 Int_t nbytes,objlen,keylen;
3773 while ((leaf = (TLeaf*)next())) {
3774 TBranch *branch = leaf->GetBranch();
3775 Int_t nbaskets = branch->GetMaxBaskets();
3776 for (Int_t i=0;i<nbaskets;i++) {
3777 Long64_t pos = branch->GetBasketSeek(i);
3778 if (!pos) continue;
3779 TFile *branchFile = branch->GetFile();
3780 if (!branchFile) continue;
3781 branchFile->GetRecordHeader(header,pos,16,nbytes,objlen,keylen);
3782 if (nbytes <= 0) continue;
3783 branchFile->MakeFree(pos,pos+nbytes-1);
3784 ntot += nbytes;
3785 nbask++;
3786 }
3787 }
3788
3789 // delete Tree header key and all keys with the same name
3790 // A Tree may have been saved many times. Previous cycles are invalid.
3791 while (key) {
3792 ntot += key->GetNbytes();
3793 key->Delete();
3794 delete key;
3795 key = fDirectory->GetKey(GetName());
3796 }
3797 if (dirsav) dirsav->cd();
3798 if (gDebug) Info("TTree::Delete", "Deleting Tree: %s: %d baskets deleted. Total space freed = %d bytes\n",GetName(),nbask,ntot);
3799 }
3800
3801 if (fDirectory) {
3802 fDirectory->Remove(this);
3803 //delete the file cache if it points to this Tree
3804 MoveReadCache(file,nullptr);
3805 fDirectory = nullptr;
3807 }
3808
3809 // Delete object from CINT symbol table so it can not be used anymore.
3810 gCling->DeleteGlobal(this);
3811
3812 // Warning: We have intentional invalidated this object while inside a member function!
3813 delete this;
3814}
3815
3816 ///////////////////////////////////////////////////////////////////////////////
3817 /// Called by TKey and TObject::Clone to automatically add us to a directory
3818 /// when we are read from a file.
3821{
3822 if (fDirectory == dir) return;
3823 if (fDirectory) {
3824 fDirectory->Remove(this);
3825 // Delete or move the file cache if it points to this Tree
3826 TFile *file = fDirectory->GetFile();
3827 MoveReadCache(file,dir);
3828 }
3829 fDirectory = dir;
3830 TBranch* b = nullptr;
3831 TIter next(GetListOfBranches());
3832 while((b = (TBranch*) next())) {
3833 b->UpdateFile();
3834 }
3835 if (fBranchRef) {
3837 }
3838 if (fDirectory) fDirectory->Append(this);
3839}
3840
3841////////////////////////////////////////////////////////////////////////////////
3842/// Draw expression varexp for specified entries.
3843///
3844/// \return -1 in case of error or number of selected events in case of success.
3845///
3846/// This function accepts TCut objects as arguments.
3847/// Useful to use the string operator +
3848///
3849/// Example:
3850///
3851/// ~~~ {.cpp}
3852/// ntuple.Draw("x",cut1+cut2+cut3);
3853/// ~~~
3854
3856Long64_t TTree::Draw(const char* varexp, const TCut& selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
3857{
3858 return TTree::Draw(varexp, selection.GetTitle(), option, nentries, firstentry);
3859}
3860
3861/////////////////////////////////////////////////////////////////////////////////////////
3862/// \brief Draw expression varexp for entries and objects that pass a (optional) selection.
3863///
3864/// \return -1 in case of error or number of selected events in case of success.
3865///
3866/// \param [in] varexp
3867/// \parblock
3868/// A string that takes one of these general forms:
3869/// - "e1" produces a 1-d histogram (TH1F) of expression "e1"
3870/// - "e1:e2" produces an unbinned 2-d scatter-plot (TGraph) of "e1"
3871/// on the y-axis versus "e2" on the x-axis
3872/// - "e1:e2:e3" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
3873/// vs "e2" vs "e3" on the z-, y-, x-axis, respectively
3874/// - "e1:e2:e3:e4" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
3875/// vs "e2" vs "e3" and "e4" mapped on the current color palette.
3876/// (to create histograms in the 2, 3, and 4 dimensional case,
3877/// see section "Saving the result of Draw to an histogram")
3878/// - "e1:e2:e3:e4:e5" with option "GL5D" produces a 5D plot using OpenGL. `gStyle->SetCanvasPreferGL(true)` is needed.
3879/// - Any number of variables no fewer than two can be used with the options "CANDLE" and "PARA"
3880/// - An arbitrary number of variables can be used with the option "GOFF"
3881///
3882/// Examples:
3883/// - "x": the simplest case, it draws a 1-Dim histogram of column x
3884/// - "sqrt(x)", "x*y/z": draw histogram with the values of the specified numerical expression across TTree events
3885/// - "y:sqrt(x)": 2-Dim histogram of y versus sqrt(x)
3886/// - "px:py:pz:2.5*E": produces a 3-d scatter-plot of px vs py ps pz
3887/// and the color number of each marker will be 2.5*E.
3888/// If the color number is negative it is set to 0.
3889/// If the color number is greater than the current number of colors
3890/// it is set to the highest color number. The default number of
3891/// colors is 50. See TStyle::SetPalette for setting a new color palette.
3892///
3893/// The expressions can use all the operations and built-in functions
3894/// supported by TFormula (see TFormula::Analyze()), including free
3895/// functions taking numerical arguments (e.g. TMath::Bessel()).
3896/// In addition, you can call member functions taking numerical
3897/// arguments. For example, these are two valid expressions:
3898/// ~~~ {.cpp}
3899/// TMath::BreitWigner(fPx,3,2)
3900/// event.GetHistogram()->GetXaxis()->GetXmax()
3901/// ~~~
3902/// \endparblock
3903/// \param [in] selection
3904/// \parblock
3905/// A string containing a selection expression.
3906/// In a selection all usual C++ mathematical and logical operators are allowed.
3907/// The value corresponding to the selection expression is used as a weight
3908/// to fill the histogram (a weight of 0 is equivalent to not filling the histogram).\n
3909/// \n
3910/// Examples:
3911/// - "x<y && sqrt(z)>3.2": returns a weight = 0 or 1
3912/// - "(x+y)*(sqrt(z)>3.2)": returns a weight = x+y if sqrt(z)>3.2, 0 otherwise\n
3913/// \n
3914/// If the selection expression returns an array, it is iterated over in sync with the
3915/// array returned by the varexp argument (as described below in "Drawing expressions using arrays and array
3916/// elements"). For example, if, for a given event, varexp evaluates to
3917/// `{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:
3918/// ~~~{.cpp}
3919/// // Muon_pt is an array: fill a histogram with the array elements > 100 in each event
3920/// tree->Draw('Muon_pt', 'Muon_pt > 100')
3921/// ~~~
3922/// \endparblock
3923/// \param [in] option
3924/// \parblock
3925/// The drawing option.
3926/// - When an histogram is produced it can be any histogram drawing option
3927/// listed in THistPainter.
3928/// - when no option is specified:
3929/// - the default histogram drawing option is used
3930/// if the expression is of the form "e1".
3931/// - if the expression is of the form "e1:e2"or "e1:e2:e3" a cloud of
3932/// unbinned 2D or 3D points is drawn respectively.
3933/// - if the expression has four fields "e1:e2:e3:e4" a cloud of unbinned 3D
3934/// points is produced with e1 vs e2 vs e3, and e4 is mapped on the current color
3935/// palette.
3936/// - If option COL is specified when varexp has three fields:
3937/// ~~~ {.cpp}
3938/// tree.Draw("e1:e2:e3","","col");
3939/// ~~~
3940/// a 2D scatter is produced with e1 vs e2, and e3 is mapped on the current
3941/// color palette. The colors for e3 are evaluated once in linear scale before
3942/// painting. Therefore changing the pad to log scale along Z as no effect
3943/// on the colors.
3944/// - if expression has more than four fields the option "PARA"or "CANDLE"
3945/// can be used.
3946/// - If option contains the string "goff", no graphics is generated.
3947/// \endparblock
3948/// \param [in] nentries The number of entries to process (default is all)
3949/// \param [in] firstentry The first entry to process (default is 0)
3950///
3951/// ### Drawing expressions using arrays and array elements
3952///
3953/// Let assumes, a leaf fMatrix, on the branch fEvent, which is a 3 by 3 array,
3954/// or a TClonesArray.
3955/// In a TTree::Draw expression you can now access fMatrix using the following
3956/// syntaxes:
3957///
3958/// | String passed | What is used for each entry of the tree
3959/// |-----------------|--------------------------------------------------------|
3960/// | `fMatrix` | the 9 elements of fMatrix |
3961/// | `fMatrix[][]` | the 9 elements of fMatrix |
3962/// | `fMatrix[2][2]` | only the elements fMatrix[2][2] |
3963/// | `fMatrix[1]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
3964/// | `fMatrix[1][]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
3965/// | `fMatrix[][0]` | the 3 elements fMatrix[0][0], fMatrix[1][0] and fMatrix[2][0] |
3966///
3967/// "fEvent.fMatrix...." same as "fMatrix..." (unless there is more than one leaf named fMatrix!).
3968///
3969/// In summary, if a specific index is not specified for a dimension, TTree::Draw
3970/// will loop through all the indices along this dimension. Leaving off the
3971/// last (right most) dimension of specifying then with the two characters '[]'
3972/// is equivalent. For variable size arrays (and TClonesArray) the range
3973/// of the first dimension is recalculated for each entry of the tree.
3974/// You can also specify the index as an expression of any other variables from the
3975/// tree.
3976///
3977/// TTree::Draw also now properly handling operations involving 2 or more arrays.
3978///
3979/// Let assume a second matrix fResults[5][2], here are a sample of some
3980/// of the possible combinations, the number of elements they produce and
3981/// the loop used:
3982///
3983/// | expression | element(s) | Loop |
3984/// |----------------------------------|------------|--------------------------|
3985/// | `fMatrix[2][1] - fResults[5][2]` | one | no loop |
3986/// | `fMatrix[2][] - fResults[5][2]` | three | on 2nd dim fMatrix |
3987/// | `fMatrix[2][] - fResults[5][]` | two | on both 2nd dimensions |
3988/// | `fMatrix[][2] - fResults[][1]` | three | on both 1st dimensions |
3989/// | `fMatrix[][2] - fResults[][]` | six | on both 1st and 2nd dimensions of fResults |
3990/// | `fMatrix[][2] - fResults[3][]` | two | on 1st dim of fMatrix and 2nd of fResults (at the same time) |
3991/// | `fMatrix[][] - fResults[][]` | six | on 1st dim then on 2nd dim |
3992/// | `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.|
3993///
3994///
3995/// In summary, TTree::Draw loops through all unspecified dimensions. To
3996/// figure out the range of each loop, we match each unspecified dimension
3997/// from left to right (ignoring ALL dimensions for which an index has been
3998/// specified), in the equivalent loop matched dimensions use the same index
3999/// and are restricted to the smallest range (of only the matched dimensions).
4000/// When involving variable arrays, the range can of course be different
4001/// for each entry of the tree.
4002///
4003/// So the loop equivalent to "fMatrix[][2] - fResults[3][]" is:
4004/// ~~~ {.cpp}
4005/// for (Int_t i0; i < min(3,2); i++) {
4006/// use the value of (fMatrix[i0][2] - fMatrix[3][i0])
4007/// }
4008/// ~~~
4009/// So the loop equivalent to "fMatrix[][2] - fResults[][]" is:
4010/// ~~~ {.cpp}
4011/// for (Int_t i0; i < min(3,5); i++) {
4012/// for (Int_t i1; i1 < 2; i1++) {
4013/// use the value of (fMatrix[i0][2] - fMatrix[i0][i1])
4014/// }
4015/// }
4016/// ~~~
4017/// So the loop equivalent to "fMatrix[][] - fResults[][]" is:
4018/// ~~~ {.cpp}
4019/// for (Int_t i0; i < min(3,5); i++) {
4020/// for (Int_t i1; i1 < min(3,2); i1++) {
4021/// use the value of (fMatrix[i0][i1] - fMatrix[i0][i1])
4022/// }
4023/// }
4024/// ~~~
4025/// So the loop equivalent to "fMatrix[][fResults[][]]" is:
4026/// ~~~ {.cpp}
4027/// for (Int_t i0; i0 < 3; i0++) {
4028/// for (Int_t j2; j2 < 5; j2++) {
4029/// for (Int_t j3; j3 < 2; j3++) {
4030/// i1 = fResults[j2][j3];
4031/// use the value of fMatrix[i0][i1]
4032/// }
4033/// }
4034/// ~~~
4035/// ### Retrieving the result of Draw
4036///
4037/// By default a temporary histogram called `htemp` is created. It will be:
4038///
4039/// - A TH1F* in case of a mono-dimensional distribution: `Draw("e1")`,
4040/// - A TH2F* in case of a bi-dimensional distribution: `Draw("e1:e2")`,
4041/// - A TH3F* in case of a three-dimensional distribution: `Draw("e1:e2:e3")`.
4042///
4043/// In the one dimensional case the `htemp` is filled and drawn whatever the drawing
4044/// option is.
4045///
4046/// In the two and three dimensional cases, with the default drawing option (`""`),
4047/// a cloud of points is drawn and the histogram `htemp` is not filled. For all the other
4048/// drawing options `htemp` will be filled.
4049///
4050/// In all cases `htemp` can be retrieved by calling:
4051///
4052/// ~~~ {.cpp}
4053/// auto htemp = (TH1F*)gPad->GetPrimitive("htemp"); // 1D
4054/// auto htemp = (TH2F*)gPad->GetPrimitive("htemp"); // 2D
4055/// auto htemp = (TH3F*)gPad->GetPrimitive("htemp"); // 3D
4056/// ~~~
4057///
4058/// In the two dimensional case (`Draw("e1;e2")`), with the default drawing option, the
4059/// data is filled into a TGraph named `Graph`. This TGraph can be retrieved by
4060/// calling
4061///
4062/// ~~~ {.cpp}
4063/// auto graph = (TGraph*)gPad->GetPrimitive("Graph");
4064/// ~~~
4065///
4066/// For the three and four dimensional cases, with the default drawing option, an unnamed
4067/// TPolyMarker3D is produced, and therefore cannot be retrieved.
4068///
4069/// In all cases `htemp` can be used to access the axes. For instance in the 2D case:
4070///
4071/// ~~~ {.cpp}
4072/// auto htemp = (TH2F*)gPad->GetPrimitive("htemp");
4073/// auto xaxis = htemp->GetXaxis();
4074/// ~~~
4075///
4076/// When the option `"A"` is used (with TGraph painting option) to draw a 2D
4077/// distribution:
4078/// ~~~ {.cpp}
4079/// tree.Draw("e1:e2","","A*");
4080/// ~~~
4081/// a scatter plot is produced (with stars in that case) but the axis creation is
4082/// delegated to TGraph and `htemp` is not created.
4083///
4084/// ### Saving the result of Draw to a histogram
4085///
4086/// If `varexp` contains `>>hnew` (following the variable(s) name(s)),
4087/// the new histogram called `hnew` is created and it is kept in the current
4088/// directory (and also the current pad). This works for all dimensions.
4089///
4090/// Example:
4091/// ~~~ {.cpp}
4092/// tree.Draw("sqrt(x)>>hsqrt","y>0")
4093/// ~~~
4094/// will draw `sqrt(x)` and save the histogram as "hsqrt" in the current
4095/// directory. To retrieve it do:
4096/// ~~~ {.cpp}
4097/// TH1F *hsqrt = (TH1F*)gDirectory->Get("hsqrt");
4098/// ~~~
4099/// The binning information is taken from the environment variables
4100/// ~~~ {.cpp}
4101/// Hist.Binning.?D.?
4102/// ~~~
4103/// In addition, the name of the histogram can be followed by up to 9
4104/// numbers between '(' and ')', where the numbers describe the
4105/// following:
4106///
4107/// - 1 - bins in x-direction
4108/// - 2 - lower limit in x-direction
4109/// - 3 - upper limit in x-direction
4110/// - 4-6 same for y-direction
4111/// - 7-9 same for z-direction
4112///
4113/// When a new binning is used the new value will become the default.
4114/// Values can be skipped.
4115///
4116/// Example:
4117/// ~~~ {.cpp}
4118/// tree.Draw("sqrt(x)>>hsqrt(500,10,20)")
4119/// // plot sqrt(x) between 10 and 20 using 500 bins
4120/// tree.Draw("sqrt(x):sin(y)>>hsqrt(100,10,60,50,.1,.5)")
4121/// // plot sqrt(x) against sin(y)
4122/// // 100 bins in x-direction; lower limit on x-axis is 10; upper limit is 60
4123/// // 50 bins in y-direction; lower limit on y-axis is .1; upper limit is .5
4124/// ~~~
4125/// By default, the specified histogram is reset.
4126/// To continue to append data to an existing histogram, use "+" in front
4127/// of the histogram name.
4128///
4129/// A '+' in front of the histogram name is ignored, when the name is followed by
4130/// binning information as described in the previous paragraph.
4131/// ~~~ {.cpp}
4132/// tree.Draw("sqrt(x)>>+hsqrt","y>0")
4133/// ~~~
4134/// will not reset `hsqrt`, but will continue filling. This works for 1-D, 2-D
4135/// and 3-D histograms.
4136///
4137/// ### Accessing collection objects
4138///
4139/// TTree::Draw default's handling of collections is to assume that any
4140/// request on a collection pertain to it content. For example, if fTracks
4141/// is a collection of Track objects, the following:
4142/// ~~~ {.cpp}
4143/// tree->Draw("event.fTracks.fPx");
4144/// ~~~
4145/// will plot the value of fPx for each Track objects inside the collection.
4146/// Also
4147/// ~~~ {.cpp}
4148/// tree->Draw("event.fTracks.size()");
4149/// ~~~
4150/// would plot the result of the member function Track::size() for each
4151/// Track object inside the collection.
4152/// To access information about the collection itself, TTree::Draw support
4153/// the '@' notation. If a variable which points to a collection is prefixed
4154/// or postfixed with '@', the next part of the expression will pertain to
4155/// the collection object. For example:
4156/// ~~~ {.cpp}
4157/// tree->Draw("event.@fTracks.size()");
4158/// ~~~
4159/// will plot the size of the collection referred to by `fTracks` (i.e the number
4160/// of Track objects).
4161///
4162/// ### Drawing 'objects'
4163///
4164/// When a class has a member function named AsDouble or AsString, requesting
4165/// to directly draw the object will imply a call to one of the 2 functions.
4166/// If both AsDouble and AsString are present, AsDouble will be used.
4167/// AsString can return either a char*, a std::string or a TString.s
4168/// For example, the following
4169/// ~~~ {.cpp}
4170/// tree->Draw("event.myTTimeStamp");
4171/// ~~~
4172/// will draw the same histogram as
4173/// ~~~ {.cpp}
4174/// tree->Draw("event.myTTimeStamp.AsDouble()");
4175/// ~~~
4176/// In addition, when the object is a type TString or std::string, TTree::Draw
4177/// will call respectively `TString::Data` and `std::string::c_str()`
4178///
4179/// If the object is a TBits, the histogram will contain the index of the bit
4180/// that are turned on.
4181///
4182/// ### Retrieving information about the tree itself.
4183///
4184/// You can refer to the tree (or chain) containing the data by using the
4185/// string 'This'.
4186/// You can then could any TTree methods. For example:
4187/// ~~~ {.cpp}
4188/// tree->Draw("This->GetReadEntry()");
4189/// ~~~
4190/// will display the local entry numbers be read.
4191/// ~~~ {.cpp}
4192/// tree->Draw("This->GetUserInfo()->At(0)->GetName()");
4193/// ~~~
4194/// will display the name of the first 'user info' object.
4195///
4196/// ### Special functions and variables
4197///
4198/// `Entry$`: A TTree::Draw formula can use the special variable `Entry$`
4199/// to access the entry number being read. For example to draw every
4200/// other entry use:
4201/// ~~~ {.cpp}
4202/// tree.Draw("myvar","Entry$%2==0");
4203/// ~~~
4204/// - `Entry$` : return the current entry number (`== TTree::GetReadEntry()`)
4205/// - `LocalEntry$` : return the current entry number in the current tree of a
4206/// chain (`== GetTree()->GetReadEntry()`)
4207/// - `Entries$` : return the total number of entries (== TTree::GetEntries())
4208/// - `LocalEntries$` : return the total number of entries in the current tree
4209/// of a chain (== GetTree()->TTree::GetEntries())
4210/// - `Length$` : return the total number of element of this formula for this
4211/// entry (`==TTreeFormula::GetNdata()`)
4212/// - `Iteration$` : return the current iteration over this formula for this
4213/// entry (i.e. varies from 0 to `Length$`).
4214/// - `Length$(formula )` : return the total number of element of the formula
4215/// given as a parameter.
4216/// - `Sum$(formula )` : return the sum of the value of the elements of the
4217/// formula given as a parameter. For example the mean for all the elements in
4218/// one entry can be calculated with: `Sum$(formula )/Length$(formula )`
4219/// - `Min$(formula )` : return the minimum (within one TTree entry) of the value of the
4220/// elements of the formula given as a parameter.
4221/// - `Max$(formula )` : return the maximum (within one TTree entry) of the value of the
4222/// elements of the formula given as a parameter.
4223/// - `MinIf$(formula,condition)`
4224/// - `MaxIf$(formula,condition)` : return the minimum (maximum) (within one TTree entry)
4225/// of the value of the elements of the formula given as a parameter
4226/// if they match the condition. If no element matches the condition,
4227/// the result is zero. To avoid the resulting peak at zero, use the
4228/// pattern:
4229/// ~~~ {.cpp}
4230/// tree->Draw("MinIf$(formula,condition)","condition");
4231/// ~~~
4232/// which will avoid calculation `MinIf$` for the entries that have no match
4233/// for the condition.
4234/// - `Alt$(primary,alternate)` : return the value of "primary" if it is available
4235/// for the current iteration otherwise return the value of "alternate".
4236/// For example, with arr1[3] and arr2[2]
4237/// ~~~ {.cpp}
4238/// tree->Draw("arr1+Alt$(arr2,0)");
4239/// ~~~
4240/// will draw arr1[0]+arr2[0] ; arr1[1]+arr2[1] and arr1[2]+0
4241/// Or with a variable size array arr3
4242/// ~~~ {.cpp}
4243/// tree->Draw("Alt$(arr3[0],0)+Alt$(arr3[1],0)+Alt$(arr3[2],0)");
4244/// ~~~
4245/// will draw the sum arr3 for the index 0 to min(2,actual_size_of_arr3-1)
4246/// As a comparison
4247/// ~~~ {.cpp}
4248/// tree->Draw("arr3[0]+arr3[1]+arr3[2]");
4249/// ~~~
4250/// will draw the sum arr3 for the index 0 to 2 only if the
4251/// actual_size_of_arr3 is greater or equal to 3.
4252/// Note that the array in 'primary' is flattened/linearized thus using
4253/// `Alt$` with multi-dimensional arrays of different dimensions in unlikely
4254/// to yield the expected results. To visualize a bit more what elements
4255/// would be matched by TTree::Draw, TTree::Scan can be used:
4256/// ~~~ {.cpp}
4257/// tree->Scan("arr1:Alt$(arr2,0)");
4258/// ~~~
4259/// will print on one line the value of arr1 and (arr2,0) that will be
4260/// matched by
4261/// ~~~ {.cpp}
4262/// tree->Draw("arr1-Alt$(arr2,0)");
4263/// ~~~
4264/// The ternary operator is not directly supported in TTree::Draw however, to plot the
4265/// equivalent of `var2<20 ? -99 : var1`, you can use:
4266/// ~~~ {.cpp}
4267/// tree->Draw("(var2<20)*99+(var2>=20)*var1","");
4268/// ~~~
4269///
4270/// ### Drawing a user function accessing the TTree data directly
4271///
4272/// If the formula contains a file name, TTree::MakeProxy will be used
4273/// to load and execute this file. In particular it will draw the
4274/// result of a function with the same name as the file. The function
4275/// will be executed in a context where the name of the branches can
4276/// be used as a C++ variable.
4277///
4278/// For example draw px using the file hsimple.root (generated by the
4279/// hsimple.C tutorial), we need a file named hsimple.cxx:
4280/// ~~~ {.cpp}
4281/// double hsimple() {
4282/// return px;
4283/// }
4284/// ~~~
4285/// MakeProxy can then be used indirectly via the TTree::Draw interface
4286/// as follow:
4287/// ~~~ {.cpp}
4288/// new TFile("hsimple.root")
4289/// ntuple->Draw("hsimple.cxx");
4290/// ~~~
4291/// A more complete example is available in the tutorials directory:
4292/// `h1analysisProxy.cxx`, `h1analysProxy.h` and `h1analysisProxyCut.C`
4293/// which reimplement the selector found in `h1analysis.C`
4294///
4295/// The main features of this facility are:
4296///
4297/// * on-demand loading of branches
4298/// * ability to use the 'branchname' as if it was a data member
4299/// * protection against array out-of-bound
4300/// * ability to use the branch data as object (when the user code is available)
4301///
4302/// See TTree::MakeProxy for more details.
4303///
4304/// ### Making a Profile histogram
4305///
4306/// In case of a 2-Dim expression, one can generate a TProfile histogram
4307/// instead of a TH2F histogram by specifying option=prof or option=profs
4308/// or option=profi or option=profg ; the trailing letter select the way
4309/// the bin error are computed, See TProfile2D::SetErrorOption for
4310/// details on the differences.
4311/// The option=prof is automatically selected in case of y:x>>pf
4312/// where pf is an existing TProfile histogram.
4313///
4314/// ### Making a 2D Profile histogram
4315///
4316/// In case of a 3-Dim expression, one can generate a TProfile2D histogram
4317/// instead of a TH3F histogram by specifying option=prof or option=profs.
4318/// or option=profi or option=profg ; the trailing letter select the way
4319/// the bin error are computed, See TProfile2D::SetErrorOption for
4320/// details on the differences.
4321/// The option=prof is automatically selected in case of z:y:x>>pf
4322/// where pf is an existing TProfile2D histogram.
4323///
4324/// ### Making a 5D plot using GL
4325///
4326/// If option GL5D is specified together with 5 variables, a 5D plot is drawn
4327/// using OpenGL. See $ROOTSYS/tutorials/tree/staff.C as example.
4328///
4329/// ### Making a parallel coordinates plot
4330///
4331/// In case of a 2-Dim or more expression with the option=para, one can generate
4332/// a parallel coordinates plot. With that option, the number of dimensions is
4333/// arbitrary. Giving more than 4 variables without the option=para or
4334/// option=candle or option=goff will produce an error.
4335///
4336/// ### Making a candle sticks chart
4337///
4338/// In case of a 2-Dim or more expression with the option=candle, one can generate
4339/// a candle sticks chart. With that option, the number of dimensions is
4340/// arbitrary. Giving more than 4 variables without the option=para or
4341/// option=candle or option=goff will produce an error.
4342///
4343/// ### Normalizing the output histogram to 1
4344///
4345/// When option contains "norm" the output histogram is normalized to 1.
4346///
4347/// ### Saving the result of Draw to a TEventList, a TEntryList or a TEntryListArray
4348///
4349/// TTree::Draw can be used to fill a TEventList object (list of entry numbers)
4350/// instead of histogramming one variable.
4351/// If varexp0 has the form >>elist , a TEventList object named "elist"
4352/// is created in the current directory. elist will contain the list
4353/// of entry numbers satisfying the current selection.
4354/// If option "entrylist" is used, a TEntryList object is created
4355/// If the selection contains arrays, vectors or any container class and option
4356/// "entrylistarray" is used, a TEntryListArray object is created
4357/// containing also the subentries satisfying the selection, i.e. the indices of
4358/// the branches which hold containers classes.
4359/// Example:
4360/// ~~~ {.cpp}
4361/// tree.Draw(">>yplus","y>0")
4362/// ~~~
4363/// will create a TEventList object named "yplus" in the current directory.
4364/// In an interactive session, one can type (after TTree::Draw)
4365/// ~~~ {.cpp}
4366/// yplus.Print("all")
4367/// ~~~
4368/// to print the list of entry numbers in the list.
4369/// ~~~ {.cpp}
4370/// tree.Draw(">>yplus", "y>0", "entrylist")
4371/// ~~~
4372/// will create a TEntryList object names "yplus" in the current directory
4373/// ~~~ {.cpp}
4374/// tree.Draw(">>yplus", "y>0", "entrylistarray")
4375/// ~~~
4376/// will create a TEntryListArray object names "yplus" in the current directory
4377///
4378/// By default, the specified entry list is reset.
4379/// To continue to append data to an existing list, use "+" in front
4380/// of the list name;
4381/// ~~~ {.cpp}
4382/// tree.Draw(">>+yplus","y>0")
4383/// ~~~
4384/// will not reset yplus, but will enter the selected entries at the end
4385/// of the existing list.
4386///
4387/// ### Using a TEventList, TEntryList or TEntryListArray as Input
4388///
4389/// Once a TEventList or a TEntryList object has been generated, it can be used as input
4390/// for TTree::Draw. Use TTree::SetEventList or TTree::SetEntryList to set the
4391/// current event list
4392///
4393/// Example 1:
4394/// ~~~ {.cpp}
4395/// TEventList *elist = (TEventList*)gDirectory->Get("yplus");
4396/// tree->SetEventList(elist);
4397/// tree->Draw("py");
4398/// ~~~
4399/// Example 2:
4400/// ~~~ {.cpp}
4401/// TEntryList *elist = (TEntryList*)gDirectory->Get("yplus");
4402/// tree->SetEntryList(elist);
4403/// tree->Draw("py");
4404/// ~~~
4405/// If a TEventList object is used as input, a new TEntryList object is created
4406/// inside the SetEventList function. In case of a TChain, all tree headers are loaded
4407/// for this transformation. This new object is owned by the chain and is deleted
4408/// with it, unless the user extracts it by calling GetEntryList() function.
4409/// See also comments to SetEventList() function of TTree and TChain.
4410///
4411/// If arrays are used in the selection criteria and TEntryListArray is not used,
4412/// all the entries that have at least one element of the array that satisfy the selection
4413/// are entered in the list.
4414///
4415/// Example:
4416/// ~~~ {.cpp}
4417/// tree.Draw(">>pyplus","fTracks.fPy>0");
4418/// tree->SetEventList(pyplus);
4419/// tree->Draw("fTracks.fPy");
4420/// ~~~
4421/// will draw the fPy of ALL tracks in event with at least one track with
4422/// a positive fPy.
4423///
4424/// To select only the elements that did match the original selection
4425/// use TEventList::SetReapplyCut or TEntryList::SetReapplyCut.
4426///
4427/// Example:
4428/// ~~~ {.cpp}
4429/// tree.Draw(">>pyplus","fTracks.fPy>0");
4430/// pyplus->SetReapplyCut(true);
4431/// tree->SetEventList(pyplus);
4432/// tree->Draw("fTracks.fPy");
4433/// ~~~
4434/// will draw the fPy of only the tracks that have a positive fPy.
4435///
4436/// To draw only the elements that match a selection in case of arrays,
4437/// you can also use TEntryListArray (faster in case of a more general selection).
4438///
4439/// Example:
4440/// ~~~ {.cpp}
4441/// tree.Draw(">>pyplus","fTracks.fPy>0", "entrylistarray");
4442/// tree->SetEntryList(pyplus);
4443/// tree->Draw("fTracks.fPy");
4444/// ~~~
4445/// will draw the fPy of only the tracks that have a positive fPy,
4446/// but without redoing the selection.
4447///
4448/// Note: Use tree->SetEventList(0) if you do not want use the list as input.
4449///
4450/// ### How to obtain more info from TTree::Draw
4451///
4452/// Once TTree::Draw has been called, it is possible to access useful
4453/// information still stored in the TTree object via the following functions:
4454///
4455/// - GetSelectedRows() // return the number of values accepted by the selection expression. In case where no selection was specified, returns the number of values processed.
4456/// - GetV1() // returns a pointer to the double array of V1
4457/// - GetV2() // returns a pointer to the double array of V2
4458/// - GetV3() // returns a pointer to the double array of V3
4459/// - GetV4() // returns a pointer to the double array of V4
4460/// - GetW() // returns a pointer to the double array of Weights where weight equal the result of the selection expression.
4461///
4462/// where V1,V2,V3 correspond to the expressions in
4463/// ~~~ {.cpp}
4464/// TTree::Draw("V1:V2:V3:V4",selection);
4465/// ~~~
4466/// If the expression has more than 4 component use GetVal(index)
4467///
4468/// Example:
4469/// ~~~ {.cpp}
4470/// Root > ntuple->Draw("py:px","pz>4");
4471/// Root > TGraph *gr = new TGraph(ntuple->GetSelectedRows(),
4472/// ntuple->GetV2(), ntuple->GetV1());
4473/// Root > gr->Draw("ap"); //draw graph in current pad
4474/// ~~~
4475///
4476/// A more complete complete tutorial (treegetval.C) shows how to use the
4477/// GetVal() method.
4478///
4479/// creates a TGraph object with a number of points corresponding to the
4480/// number of entries selected by the expression "pz>4", the x points of the graph
4481/// being the px values of the Tree and the y points the py values.
4482///
4483/// Important note: By default TTree::Draw creates the arrays obtained
4484/// with GetW, GetV1, GetV2, GetV3, GetV4, GetVal with a length corresponding
4485/// to the parameter fEstimate. The content will be the last `GetSelectedRows() % GetEstimate()`
4486/// values calculated.
4487/// By default fEstimate=1000000 and can be modified
4488/// via TTree::SetEstimate. To keep in memory all the results (in case
4489/// where there is only one result per entry), use
4490/// ~~~ {.cpp}
4491/// tree->SetEstimate(tree->GetEntries()+1); // same as tree->SetEstimate(-1);
4492/// ~~~
4493/// You must call SetEstimate if the expected number of selected rows
4494/// you need to look at is greater than 1000000.
4495///
4496/// You can use the option "goff" to turn off the graphics output
4497/// of TTree::Draw in the above example.
4498///
4499/// ### Automatic interface to TTree::Draw via the TTreeViewer
4500///
4501/// A complete graphical interface to this function is implemented
4502/// in the class TTreeViewer.
4503/// To start the TTreeViewer, three possibilities:
4504/// - select TTree context menu item "StartViewer"
4505/// - type the command "TTreeViewer TV(treeName)"
4506/// - execute statement "tree->StartViewer();"
4508Long64_t TTree::Draw(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
4509{
4510 GetPlayer();
4511 if (fPlayer)
4512 return fPlayer->DrawSelect(varexp,selection,option,nentries,firstentry);
4513 return -1;
4514}
4515
4516////////////////////////////////////////////////////////////////////////////////
4517/// Remove some baskets from memory.
4519void TTree::DropBaskets()
4520{
4521 TBranch* branch = nullptr;
4523 for (Int_t i = 0; i < nb; ++i) {
4524 branch = (TBranch*) fBranches.UncheckedAt(i);
4525 branch->DropBaskets("all");
4526 }
4527}
4528
4529////////////////////////////////////////////////////////////////////////////////
4530/// Drop branch buffers to accommodate nbytes below MaxVirtualsize.
4533{
4534 // Be careful not to remove current read/write buffers.
4535 Int_t nleaves = fLeaves.GetEntriesFast();
4536 for (Int_t i = 0; i < nleaves; ++i) {
4537 TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
4538 TBranch* branch = (TBranch*) leaf->GetBranch();
4539 Int_t nbaskets = branch->GetListOfBaskets()->GetEntries();
4540 for (Int_t j = 0; j < nbaskets - 1; ++j) {
4541 if ((j == branch->GetReadBasket()) || (j == branch->GetWriteBasket())) {
4542 continue;
4543 }
4544 TBasket* basket = (TBasket*)branch->GetListOfBaskets()->UncheckedAt(j);
4545 if (basket) {
4546 basket->DropBuffers();
4548 return;
4549 }
4550 }
4551 }
4552 }
4553}
4554
4555////////////////////////////////////////////////////////////////////////////////
4556/// Fill all branches.
4557///
4558/// This function loops on all the branches of this tree. For
4559/// each branch, it copies to the branch buffer (basket) the current
4560/// values of the leaves data types. If a leaf is a simple data type,
4561/// a simple conversion to a machine independent format has to be done.
4562///
4563/// This machine independent version of the data is copied into a
4564/// basket (each branch has its own basket). When a basket is full
4565/// (32k worth of data by default), it is then optionally compressed
4566/// and written to disk (this operation is also called committing or
4567/// 'flushing' the basket). The committed baskets are then
4568/// immediately removed from memory.
4569///
4570/// The function returns the number of bytes committed to the
4571/// individual branches.
4572///
4573/// If a write error occurs, the number of bytes returned is -1.
4574///
4575/// If no data are written, because, e.g., the branch is disabled,
4576/// the number of bytes returned is 0.
4577///
4578/// __The baskets are flushed and the Tree header saved at regular intervals__
4579///
4580/// At regular intervals, when the amount of data written so far is
4581/// greater than fAutoFlush (see SetAutoFlush) all the baskets are flushed to disk.
4582/// This makes future reading faster as it guarantees that baskets belonging to nearby
4583/// entries will be on the same disk region.
4584/// When the first call to flush the baskets happen, we also take this opportunity
4585/// to optimize the baskets buffers.
4586/// We also check if the amount of data written is greater than fAutoSave (see SetAutoSave).
4587/// In this case we also write the Tree header. This makes the Tree recoverable up to this point
4588/// in case the program writing the Tree crashes.
4589/// The decisions to FlushBaskets and Auto Save can be made based either on the number
4590/// of bytes written (fAutoFlush and fAutoSave negative) or on the number of entries
4591/// written (fAutoFlush and fAutoSave positive).
4592/// Note that the user can decide to call FlushBaskets and AutoSave in her event loop
4593/// base on the number of events written instead of the number of bytes written.
4594///
4595/// \note Calling `TTree::FlushBaskets` too often increases the IO time.
4596///
4597/// \note Calling `TTree::AutoSave` too often increases the IO time and also the
4598/// file size.
4599///
4600/// \note This method calls `TTree::ChangeFile` when the tree reaches a size
4601/// greater than `TTree::fgMaxTreeSize`. This doesn't happen if the tree is
4602/// attached to a `TMemFile` or derivate.
4605{
4606 Int_t nbytes = 0;
4607 Int_t nwrite = 0;
4608 Int_t nerror = 0;
4609 Int_t nbranches = fBranches.GetEntriesFast();
4610
4611 // Case of one single super branch. Automatically update
4612 // all the branch addresses if a new object was created.
4613 if (nbranches == 1)
4614 ((TBranch *)fBranches.UncheckedAt(0))->UpdateAddress();
4615
4616 if (fBranchRef)
4617 fBranchRef->Clear();
4618
4619#ifdef R__USE_IMT
4620 const auto useIMT = ROOT::IsImplicitMTEnabled() && fIMTEnabled;
4622 if (useIMT) {
4623 fIMTFlush = true;
4624 fIMTZipBytes.store(0);
4625 fIMTTotBytes.store(0);
4626 }
4627#endif
4628
4629 for (Int_t i = 0; i < nbranches; ++i) {
4630 // Loop over all branches, filling and accumulating bytes written and error counts.
4631 TBranch *branch = (TBranch *)fBranches.UncheckedAt(i);
4632
4633 if (branch->TestBit(kDoNotProcess))
4634 continue;
4635
4636#ifndef R__USE_IMT
4637 nwrite = branch->FillImpl(nullptr);
4638#else
4639 nwrite = branch->FillImpl(useIMT ? &imtHelper : nullptr);
4640#endif
4641 if (nwrite < 0) {
4642 if (nerror < 2) {
4643 Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld\n"
4644 " This error is symptomatic of a Tree created as a memory-resident Tree\n"
4645 " Instead of doing:\n"
4646 " TTree *T = new TTree(...)\n"
4647 " TFile *f = new TFile(...)\n"
4648 " you should do:\n"
4649 " TFile *f = new TFile(...)\n"
4650 " TTree *T = new TTree(...)\n\n",
4651 GetName(), branch->GetName(), nwrite, fEntries + 1);
4652 } else {
4653 Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld", GetName(), branch->GetName(), nwrite,
4654 fEntries + 1);
4655 }
4656 ++nerror;
4657 } else {
4658 nbytes += nwrite;
4659 }
4660 }
4661
4662#ifdef R__USE_IMT
4663 if (fIMTFlush) {
4664 imtHelper.Wait();
4665 fIMTFlush = false;
4666 const_cast<TTree *>(this)->AddTotBytes(fIMTTotBytes);
4667 const_cast<TTree *>(this)->AddZipBytes(fIMTZipBytes);
4668 nbytes += imtHelper.GetNbytes();
4669 nerror += imtHelper.GetNerrors();
4670 }
4671#endif
4672
4673 if (fBranchRef)
4674 fBranchRef->Fill();
4675
4676 ++fEntries;
4677
4678 if (fEntries > fMaxEntries)
4679 KeepCircular();
4680
4681 if (gDebug > 0)
4682 Info("TTree::Fill", " - A: %d %lld %lld %lld %lld %lld %lld \n", nbytes, fEntries, fAutoFlush, fAutoSave,
4684
4685 bool autoFlush = false;
4686 bool autoSave = false;
4687
4688 if (fAutoFlush != 0 || fAutoSave != 0) {
4689 // Is it time to flush or autosave baskets?
4690 if (fFlushedBytes == 0) {
4691 // If fFlushedBytes == 0, it means we never flushed or saved, so
4692 // we need to check if it's time to do it and recompute the values
4693 // of fAutoFlush and fAutoSave in terms of the number of entries.
4694 // Decision can be based initially either on the number of bytes
4695 // or the number of entries written.
4696 Long64_t zipBytes = GetZipBytes();
4697
4698 if (fAutoFlush)
4699 autoFlush = fAutoFlush < 0 ? (zipBytes > -fAutoFlush) : fEntries % fAutoFlush == 0;
4700
4701 if (fAutoSave)
4702 autoSave = fAutoSave < 0 ? (zipBytes > -fAutoSave) : fEntries % fAutoSave == 0;
4703
4704 if (autoFlush || autoSave) {
4705 // First call FlushBasket to make sure that fTotBytes is up to date.
4707 autoFlush = false; // avoid auto flushing again later
4708
4709 // When we are in one-basket-per-cluster mode, there is no need to optimize basket:
4710 // they will automatically grow to the size needed for an event cluster (with the basket
4711 // shrinking preventing them from growing too much larger than the actually-used space).
4713 OptimizeBaskets(GetTotBytes(), 1, "");
4714 if (gDebug > 0)
4715 Info("TTree::Fill", "OptimizeBaskets called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n",
4717 }
4719 fAutoFlush = fEntries; // Use test on entries rather than bytes
4720
4721 // subsequently in run
4722 if (fAutoSave < 0) {
4723 // Set fAutoSave to the largest integer multiple of
4724 // fAutoFlush events such that fAutoSave*fFlushedBytes
4725 // < (minus the input value of fAutoSave)
4726 Long64_t totBytes = GetTotBytes();
4727 if (zipBytes != 0) {
4728 fAutoSave = TMath::Max(fAutoFlush, fEntries * ((-fAutoSave / zipBytes) / fEntries));
4729 } else if (totBytes != 0) {
4730 fAutoSave = TMath::Max(fAutoFlush, fEntries * ((-fAutoSave / totBytes) / fEntries));
4731 } else {
4733 TTree::Class()->WriteBuffer(b, (TTree *)this);
4734 Long64_t total = b.Length();
4736 }
4737 } else if (fAutoSave > 0) {
4739 }
4740
4741 if (fAutoSave != 0 && fEntries >= fAutoSave)
4742 autoSave = true;
4743
4744 if (gDebug > 0)
4745 Info("TTree::Fill", "First AutoFlush. fAutoFlush = %lld, fAutoSave = %lld\n", fAutoFlush, fAutoSave);
4746 }
4747 } else {
4748 // Check if we need to auto flush
4749 if (fAutoFlush) {
4750 if (fNClusterRange == 0)
4751 autoFlush = fEntries > 1 && fEntries % fAutoFlush == 0;
4752 else
4753 autoFlush = (fEntries - (fClusterRangeEnd[fNClusterRange - 1] + 1)) % fAutoFlush == 0;
4754 }
4755 // Check if we need to auto save
4756 if (fAutoSave)
4757 autoSave = fEntries % fAutoSave == 0;
4758 }
4759 }
4760
4761 if (autoFlush) {
4763 if (gDebug > 0)
4764 Info("TTree::Fill", "FlushBaskets() called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n", fEntries,
4767 }
4768
4769 if (autoSave) {
4770 AutoSave(); // does not call FlushBasketsImpl() again
4771 if (gDebug > 0)
4772 Info("TTree::Fill", "AutoSave called at entry %lld, fZipBytes=%lld, fSavedBytes=%lld\n", fEntries,
4774 }
4775
4776 // Check that output file is still below the maximum size.
4777 // If above, close the current file and continue on a new file.
4778 // Currently, the automatic change of file is restricted
4779 // to the case where the tree is in the top level directory.
4780 if (fDirectory)
4781 if (TFile *file = fDirectory->GetFile())
4782 if (static_cast<TDirectory *>(file) == fDirectory && (file->GetEND() > fgMaxTreeSize))
4783 // Changing file clashes with the design of TMemFile and derivates, see #6523.
4784 if (!(dynamic_cast<TMemFile *>(file)))
4785 ChangeFile(file);
4786
4787 return nerror == 0 ? nbytes : -1;
4788}
4789
4790////////////////////////////////////////////////////////////////////////////////
4791/// Search in the array for a branch matching the branch name,
4792/// with the branch possibly expressed as a 'full' path name (with dots).
4794static TBranch *R__FindBranchHelper(TObjArray *list, const char *branchname) {
4795 if (list==nullptr || branchname == nullptr || branchname[0] == '\0') return nullptr;
4796
4797 Int_t nbranches = list->GetEntries();
4798
4799 UInt_t brlen = strlen(branchname);
4800
4801 for(Int_t index = 0; index < nbranches; ++index) {
4802 TBranch *where = (TBranch*)list->UncheckedAt(index);
4803
4804 const char *name = where->GetName();
4805 UInt_t len = strlen(name);
4806 if (len && name[len-1]==']') {
4807 const char *dim = strchr(name,'[');
4808 if (dim) {
4809 len = dim - name;
4810 }
4811 }
4812 if (brlen == len && strncmp(branchname,name,len)==0) {
4813 return where;
4814 }
4815 TBranch *next = nullptr;
4816 if ((brlen >= len) && (branchname[len] == '.')
4817 && strncmp(name, branchname, len) == 0) {
4818 // The prefix subbranch name match the branch name.
4819
4820 next = where->FindBranch(branchname);
4821 if (!next) {
4822 next = where->FindBranch(branchname+len+1);
4823 }
4824 if (next) return next;
4825 }
4826 const char *dot = strchr((char*)branchname,'.');
4827 if (dot) {
4828 if (len==(size_t)(dot-branchname) &&
4829 strncmp(branchname,name,dot-branchname)==0 ) {
4830 return R__FindBranchHelper(where->GetListOfBranches(),dot+1);
4831 }
4832 }
4833 }
4834 return nullptr;
4835}
4836
4837////////////////////////////////////////////////////////////////////////////////
4838/// Return the branch that correspond to the path 'branchname', which can
4839/// include the name of the tree or the omitted name of the parent branches.
4840/// In case of ambiguity, returns the first match.
4842TBranch* TTree::FindBranch(const char* branchname)
4843{
4844 // We already have been visited while recursively looking
4845 // through the friends tree, let return
4847 return nullptr;
4848 }
4849
4850 if (!branchname)
4851 return nullptr;
4852
4853 TBranch* branch = nullptr;
4854 // If the first part of the name match the TTree name, look for the right part in the
4855 // list of branches.
4856 // This will allow the branchname to be preceded by
4857 // the name of this tree.
4858 if (strncmp(fName.Data(),branchname,fName.Length())==0 && branchname[fName.Length()]=='.') {
4859 branch = R__FindBranchHelper( GetListOfBranches(), branchname + fName.Length() + 1);
4860 if (branch) return branch;
4861 }
4862 // If we did not find it, let's try to find the full name in the list of branches.
4863 branch = R__FindBranchHelper(GetListOfBranches(), branchname);
4864 if (branch) return branch;
4865
4866 // If we still did not find, let's try to find it within each branch assuming it does not the branch name.
4867 TIter next(GetListOfBranches());
4868 while ((branch = (TBranch*) next())) {
4869 TBranch* nestedbranch = branch->FindBranch(branchname);
4870 if (nestedbranch) {
4871 return nestedbranch;
4872 }
4873 }
4874
4875 // Search in list of friends.
4876 if (!fFriends) {
4877 return nullptr;
4878 }
4879 TFriendLock lock(this, kFindBranch);
4880 TIter nextf(fFriends);
4881 TFriendElement* fe = nullptr;
4882 while ((fe = (TFriendElement*) nextf())) {
4883 TTree* t = fe->GetTree();
4884 if (!t) {
4885 continue;
4886 }
4887 // If the alias is present replace it with the real name.
4888 const char *subbranch = strstr(branchname, fe->GetName());
4889 if (subbranch != branchname) {
4890 subbranch = nullptr;
4891 }
4892 if (subbranch) {
4893 subbranch += strlen(fe->GetName());
4894 if (*subbranch != '.') {
4895 subbranch = nullptr;
4896 } else {
4897 ++subbranch;
4898 }
4899 }
4900 std::ostringstream name;
4901 if (subbranch) {
4902 name << t->GetName() << "." << subbranch;
4903 } else {
4904 name << branchname;
4905 }
4906 branch = t->FindBranch(name.str().c_str());
4907 if (branch) {
4908 return branch;
4909 }
4910 }
4911 return nullptr;
4912}
4913
4914////////////////////////////////////////////////////////////////////////////////
4915/// Find leaf..
4917TLeaf* TTree::FindLeaf(const char* searchname)
4918{
4919 if (!searchname)
4920 return nullptr;
4921
4922 // We already have been visited while recursively looking
4923 // through the friends tree, let's return.
4925 return nullptr;
4926 }
4927
4928 // This will allow the branchname to be preceded by
4929 // the name of this tree.
4930 const char* subsearchname = strstr(searchname, GetName());
4931 if (subsearchname != searchname) {
4932 subsearchname = nullptr;
4933 }
4934 if (subsearchname) {
4935 subsearchname += strlen(GetName());
4936 if (*subsearchname != '.') {
4937 subsearchname = nullptr;
4938 } else {
4939 ++subsearchname;
4940 if (subsearchname[0] == 0) {
4941 subsearchname = nullptr;
4942 }
4943 }
4944 }
4945
4946 TString leafname;
4947 TString leaftitle;
4948 TString longname;
4949 TString longtitle;
4950
4951 const bool searchnameHasDot = strchr(searchname, '.') != nullptr;
4952
4953 // For leaves we allow for one level up to be prefixed to the name.
4954 TIter next(GetListOfLeaves());
4955 TLeaf* leaf = nullptr;
4956 while ((leaf = (TLeaf*) next())) {
4957 leafname = leaf->GetName();
4958 Ssiz_t dim = leafname.First('[');
4959 if (dim >= 0) leafname.Remove(dim);
4960
4961 if (leafname == searchname) {
4962 return leaf;
4963 }
4964 if (subsearchname && leafname == subsearchname) {
4965 return leaf;
4966 }
4967 // The TLeafElement contains the branch name
4968 // in its name, let's use the title.
4969 leaftitle = leaf->GetTitle();
4970 dim = leaftitle.First('[');
4971 if (dim >= 0) leaftitle.Remove(dim);
4972
4973 if (leaftitle == searchname) {
4974 return leaf;
4975 }
4976 if (subsearchname && leaftitle == subsearchname) {
4977 return leaf;
4978 }
4979 if (!searchnameHasDot)
4980 continue;
4981 TBranch* branch = leaf->GetBranch();
4982 if (branch) {
4983 longname.Form("%s.%s",branch->GetName(),leafname.Data());
4984 dim = longname.First('[');
4985 if (dim>=0) longname.Remove(dim);
4986 if (longname == searchname) {
4987 return leaf;
4988 }
4989 if (subsearchname && longname == subsearchname) {
4990 return leaf;
4991 }
4992 longtitle.Form("%s.%s",branch->GetName(),leaftitle.Data());
4993 dim = longtitle.First('[');
4994 if (dim>=0) longtitle.Remove(dim);
4995 if (longtitle == searchname) {
4996 return leaf;
4997 }
4998 if (subsearchname && longtitle == subsearchname) {
4999 return leaf;
5000 }
5001 // The following is for the case where the branch is only
5002 // a sub-branch. Since we do not see it through
5003 // TTree::GetListOfBranches, we need to see it indirectly.
5004 // This is the less sturdy part of this search ... it may
5005 // need refining ...
5006 if (strstr(searchname, ".") && !strcmp(searchname, branch->GetName())) {
5007 return leaf;
5008 }
5009 if (subsearchname && strstr(subsearchname, ".") && !strcmp(subsearchname, branch->GetName())) {
5010 return leaf;
5011 }
5012 }
5013 }
5014 // Search in list of friends.
5015 if (!fFriends) {
5016 return nullptr;
5017 }
5018 TFriendLock lock(this, kFindLeaf);
5019 TIter nextf(fFriends);
5020 TFriendElement* fe = nullptr;
5021 while ((fe = (TFriendElement*) nextf())) {
5022 TTree* t = fe->GetTree();
5023 if (!t) {
5024 continue;
5025 }
5026 // If the alias is present replace it with the real name.
5027 subsearchname = strstr(searchname, fe->GetName());
5028 if (subsearchname != searchname) {
5029 subsearchname = nullptr;
5030 }
5031 if (subsearchname) {
5032 subsearchname += strlen(fe->GetName());
5033 if (*subsearchname != '.') {
5034 subsearchname = nullptr;
5035 } else {
5036 ++subsearchname;
5037 }
5038 }
5039 if (subsearchname) {
5040 leafname.Form("%s.%s",t->GetName(),subsearchname);
5041 } else {
5042 leafname = searchname;
5043 }
5044 leaf = t->FindLeaf(leafname);
5045 if (leaf) {
5046 return leaf;
5047 }
5048 }
5049 return nullptr;
5050}
5051
5052////////////////////////////////////////////////////////////////////////////////
5053/// Fit a projected item(s) from a tree.
5054///
5055/// funcname is a TF1 function.
5056///
5057/// See TTree::Draw() for explanations of the other parameters.
5058///
5059/// By default the temporary histogram created is called htemp.
5060/// If varexp contains >>hnew , the new histogram created is called hnew
5061/// and it is kept in the current directory.
5062///
5063/// The function returns the number of selected entries.
5064///
5065/// Example:
5066/// ~~~ {.cpp}
5067/// tree.Fit(pol4,"sqrt(x)>>hsqrt","y>0")
5068/// ~~~
5069/// will fit sqrt(x) and save the histogram as "hsqrt" in the current
5070/// directory.
5071///
5072/// See also TTree::UnbinnedFit
5073///
5074/// ## Return status
5075///
5076/// The function returns the status of the histogram fit (see TH1::Fit)
5077/// If no entries were selected, the function returns -1;
5078/// (i.e. fitResult is null if the fit is OK)
5080Int_t TTree::Fit(const char* funcname, const char* varexp, const char* selection, Option_t* option, Option_t* goption, Long64_t nentries, Long64_t firstentry)
5081{
5082 GetPlayer();
5083 if (fPlayer) {
5084 return fPlayer->Fit(funcname, varexp, selection, option, goption, nentries, firstentry);
5085 }
5086 return -1;
5087}
5088
5089namespace {
5090struct BoolRAIIToggle {
5091 bool &m_val;
5092
5093 BoolRAIIToggle(bool &val) : m_val(val) { m_val = true; }
5094 ~BoolRAIIToggle() { m_val = false; }
5095};
5096}
5097
5098////////////////////////////////////////////////////////////////////////////////
5099/// Write to disk all the basket that have not yet been individually written and
5100/// create an event cluster boundary (by default).
5101///
5102/// If the caller wishes to flush the baskets but not create an event cluster,
5103/// then set create_cluster to false.
5104///
5105/// If ROOT has IMT-mode enabled, this will launch multiple TBB tasks in parallel
5106/// via TThreadExecutor to do this operation; one per basket compression. If the
5107/// caller utilizes TBB also, care must be taken to prevent deadlocks.
5108///
5109/// For example, let's say the caller holds mutex A and calls FlushBaskets; while
5110/// TBB is waiting for the ROOT compression tasks to complete, it may decide to
5111/// run another one of the user's tasks in this thread. If the second user task
5112/// tries to acquire A, then a deadlock will occur. The example call sequence
5113/// looks like this:
5114///
5115/// - User acquires mutex A
5116/// - User calls FlushBaskets.
5117/// - ROOT launches N tasks and calls wait.
5118/// - TBB schedules another user task, T2.
5119/// - T2 tries to acquire mutex A.
5120///
5121/// At this point, the thread will deadlock: the code may function with IMT-mode
5122/// disabled if the user assumed the legacy code never would run their own TBB
5123/// tasks.
5124///
5125/// SO: users of TBB who want to enable IMT-mode should carefully review their
5126/// locking patterns and make sure they hold no coarse-grained application
5127/// locks when they invoke ROOT.
5128///
5129/// Return the number of bytes written or -1 in case of write error.
5130Int_t TTree::FlushBaskets(bool create_cluster) const
5131{
5132 Int_t retval = FlushBasketsImpl();
5133 if (retval == -1) return retval;
5134
5135 if (create_cluster) const_cast<TTree *>(this)->MarkEventCluster();
5136 return retval;
5137}
5138
5139////////////////////////////////////////////////////////////////////////////////
5140/// Internal implementation of the FlushBaskets algorithm.
5141/// Unlike the public interface, this does NOT create an explicit event cluster
5142/// boundary; it is up to the (internal) caller to determine whether that should
5143/// done.
5144///
5145/// Otherwise, the comments for FlushBaskets applies.
5148{
5149 if (!fDirectory) return 0;
5150 Int_t nbytes = 0;
5151 Int_t nerror = 0;
5152 TObjArray *lb = const_cast<TTree*>(this)->GetListOfBranches();
5153 Int_t nb = lb->GetEntriesFast();
5154
5155#ifdef R__USE_IMT
5156 const auto useIMT = ROOT::IsImplicitMTEnabled() && fIMTEnabled;
5157 if (useIMT) {
5158 // ROOT-9668: here we need to check if the size of fSortedBranches is different from the
5159 // size of the list of branches before triggering the initialisation of the fSortedBranches
5160 // container to cover two cases:
5161 // 1. This is the first time we flush. fSortedBranches is empty and we need to fill it.
5162 // 2. We flushed at least once already but a branch has been be added to the tree since then
5163 if (fSortedBranches.size() != unsigned(nb)) { const_cast<TTree*>(this)->InitializeBranchLists(false); }
5164
5165 BoolRAIIToggle sentry(fIMTFlush);
5166 fIMTZipBytes.store(0);
5167 fIMTTotBytes.store(0);
5168 std::atomic<Int_t> nerrpar(0);
5169 std::atomic<Int_t> nbpar(0);
5170 std::atomic<Int_t> pos(0);
5171
5172 auto mapFunction = [&]() {
5173 // The branch to process is obtained when the task starts to run.
5174 // This way, since branches are sorted, we make sure that branches
5175 // leading to big tasks are processed first. If we assigned the
5176 // branch at task creation time, the scheduler would not necessarily
5177 // respect our sorting.
5178 Int_t j = pos.fetch_add(1);
5179
5180 auto branch = fSortedBranches[j].second;
5181 if (R__unlikely(!branch)) { return; }
5182
5183 if (R__unlikely(gDebug > 0)) {
5184 std::stringstream ss;
5185 ss << std::this_thread::get_id();
5186 Info("FlushBaskets", "[IMT] Thread %s", ss.str().c_str());
5187 Info("FlushBaskets", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
5188 }
5189
5190 Int_t nbtask = branch->FlushBaskets();
5191
5192 if (nbtask < 0) { nerrpar++; }
5193 else { nbpar += nbtask; }
5194 };
5195
5197 pool.Foreach(mapFunction, nb);
5198
5199 fIMTFlush = false;
5200 const_cast<TTree*>(this)->AddTotBytes(fIMTTotBytes);
5201 const_cast<TTree*>(this)->AddZipBytes(fIMTZipBytes);
5202
5203 return nerrpar ? -1 : nbpar.load();
5204 }
5205#endif
5206 for (Int_t j = 0; j < nb; j++) {
5207 TBranch* branch = (TBranch*) lb->UncheckedAt(j);
5208 if (branch) {
5209 Int_t nwrite = branch->FlushBaskets();
5210 if (nwrite<0) {
5211 ++nerror;
5212 } else {
5213 nbytes += nwrite;
5214 }
5215 }
5216 }
5217 if (nerror) {
5218 return -1;
5219 } else {
5220 return nbytes;
5221 }
5222}
5223
5224////////////////////////////////////////////////////////////////////////////////
5225/// Returns the expanded value of the alias. Search in the friends if any.
5227const char* TTree::GetAlias(const char* aliasName) const
5228{
5229 // We already have been visited while recursively looking
5230 // through the friends tree, let's return.
5232 return nullptr;
5233 }
5234 if (fAliases) {
5235 TObject* alias = fAliases->FindObject(aliasName);
5236 if (alias) {
5237 return alias->GetTitle();
5238 }
5239 }
5240 if (!fFriends) {
5241 return nullptr;
5242 }
5243 TFriendLock lock(const_cast<TTree*>(this), kGetAlias);
5244 TIter nextf(fFriends);
5245 TFriendElement* fe = nullptr;
5246 while ((fe = (TFriendElement*) nextf())) {
5247 TTree* t = fe->GetTree();
5248 if (t) {
5249 const char* alias = t->GetAlias(aliasName);
5250 if (alias) {
5251 return alias;
5252 }
5253 const char* subAliasName = strstr(aliasName, fe->GetName());
5254 if (subAliasName && (subAliasName[strlen(fe->GetName())] == '.')) {
5255 alias = t->GetAlias(aliasName + strlen(fe->GetName()) + 1);
5256 if (alias) {
5257 return alias;
5258 }
5259 }
5260 }
5261 }
5262 return nullptr;
5263}
5264
5265namespace {
5266/// Do a breadth first search through the implied hierarchy
5267/// of branches.
5268/// To avoid scanning through the list multiple time
5269/// we also remember the 'depth-first' match.
5270TBranch *R__GetBranch(const TObjArray &branches, const char *name)
5271{
5272 TBranch *result = nullptr;
5273 Int_t nb = branches.GetEntriesFast();
5274 for (Int_t i = 0; i < nb; i++) {
5275 TBranch* b = (TBranch*)branches.UncheckedAt(i);
5276 if (!b)
5277 continue;
5278 if (!strcmp(b->GetName(), name)) {
5279 return b;
5280 }
5281 if (!strcmp(b->GetFullName(), name)) {
5282 return b;
5283 }
5284 if (!result)
5285 result = R__GetBranch(*(b->GetListOfBranches()), name);
5286 }
5287 return result;
5288}
5289}
5290
5291////////////////////////////////////////////////////////////////////////////////
5292/// Return pointer to the branch with the given name in this tree or its friends.
5293/// The search is done breadth first.
5295TBranch* TTree::GetBranch(const char* name)
5296{
5297 // We already have been visited while recursively
5298 // looking through the friends tree, let's return.
5300 return nullptr;
5301 }
5302
5303 if (!name)
5304 return nullptr;
5305
5306 // Look for an exact match in the list of top level
5307 // branches.
5309 if (result)
5310 return result;
5311
5312 // Search using branches, breadth first.
5313 result = R__GetBranch(fBranches, name);
5314 if (result)
5315 return result;
5316
5317 // Search using leaves.
5318 TObjArray* leaves = GetListOfLeaves();
5319 Int_t nleaves = leaves->GetEntriesFast();
5320 for (Int_t i = 0; i < nleaves; i++) {
5321 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
5322 TBranch* branch = leaf->GetBranch();
5323 if (!strcmp(branch->GetName(), name)) {
5324 return branch;
5325 }
5326 if (!strcmp(branch->GetFullName(), name)) {
5327 return branch;
5328 }
5329 }
5330
5331 if (!fFriends) {
5332 return nullptr;
5333 }
5334
5335 // Search in list of friends.
5336 TFriendLock lock(this, kGetBranch);
5337 TIter next(fFriends);
5338 TFriendElement* fe = nullptr;
5339 while ((fe = (TFriendElement*) next())) {
5340 TTree* t = fe->GetTree();
5341 if (t) {
5342 TBranch* branch = t->GetBranch(name);
5343 if (branch) {
5344