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`)
93 - `b` : an 8 bit unsigned integer (`UChar_t`)
94 - `S` : a 16 bit signed integer (`Short_t`)
95 - `s` : a 16 bit unsigned integer (`UShort_t`)
96 - `I` : a 32 bit signed integer (`Int_t`)
97 - `i` : a 32 bit unsigned integer (`UInt_t`)
98 - `F` : a 32 bit floating point (`Float_t`)
99 - `f` : a 24 bit floating point with truncated mantissa (`Float16_t`)
100 - `D` : a 64 bit floating point (`Double_t`)
101 - `d` : a 24 bit truncated floating point (`Double32_t`)
102 - `L` : a 64 bit signed integer (`Long64_t`)
103 - `l` : a 64 bit unsigned integer (`ULong64_t`)
104 - `G` : a long signed integer, stored as 64 bit (`Long_t`)
105 - `g` : a long unsigned integer, stored as 64 bit (`ULong_t`)
106 - `O` : [the letter `o`, not a zero] a boolean (`Bool_t`)
107
108 Examples:
109 - A int: "myVar/I"
110 - A float array with fixed size: "myArrfloat[42]/F"
111 - An double array with variable size, held by the `myvar` column: "myArrdouble[myvar]/D"
112 - An Double32_t array with variable size, held by the `myvar` column , with values between 0 and 16: "myArr[myvar]/d[0,10]"
113
114- If the address points to a single numerical variable, the leaflist is optional:
115~~~ {.cpp}
116 int value;
117 tree->Branch(branchname, &value);
118~~~
119- If the address points to more than one numerical variable, we strongly recommend
120 that the variable be sorted in decreasing order of size. Any other order will
121 result in a non-portable TTree (i.e. you will not be able to read it back on a
122 platform with a different padding strategy).
123 We recommend to persistify objects rather than composite leaflists.
124- In case of the truncated floating point types (Float16_t and Double32_t) you can
125 furthermore specify the range in the style [xmin,xmax] or [xmin,xmax,nbits] after
126 the type character. For example, for storing a variable size array `myArr` of
127 `Double32_t` with values within a range of `[0, 2*pi]` and the size of which is
128 stored in a branch called `myArrSize`, the syntax for the `leaflist` string would
129 be: `myArr[myArrSize]/d[0,twopi]`. Of course the number of bits could be specified,
130 the standard rules of opaque typedefs annotation are valid. For example, if only
131 18 bits were sufficient, the syntax would become: `myArr[myArrSize]/d[0,twopi,18]`
132
133\anchor addingacolumnofstl
134## Adding a column holding STL collection instances (e.g. std::vector, std::list, std::unordered_map)
135
136~~~ {.cpp}
137 auto branch = tree.Branch( branchname, STLcollection, buffsize, splitlevel);
138~~~
139STLcollection is the address of a pointer to std::vector, std::list,
140std::deque, std::set or std::multiset containing pointers to objects.
141If the splitlevel is a value bigger than 100 (TTree::kSplitCollectionOfPointers)
142then the collection will be written in split mode, e.g. if it contains objects of
143any types deriving from TTrack this function will sort the objects
144based on their type and store them in separate branches in split
145mode.
146
147~~~ {.cpp}
148 branch->SetAddress(void *address)
149~~~
150In case of dynamic structures changing with each entry for example, one must
151redefine the branch address before filling the branch again.
152This is done via the TBranch::SetAddress member function.
153
154\anchor addingacolumnofobjs
155## Add a column holding objects
156
157~~~ {.cpp}
158 MyClass object;
159 auto branch = tree.Branch(branchname, &object, bufsize, splitlevel)
160~~~
161Note: The 2nd parameter must be the address of a valid object.
162 The object must not be destroyed (i.e. be deleted) until the TTree
163 is deleted or TTree::ResetBranchAddress is called.
164
165- if splitlevel=0, the object is serialized in the branch buffer.
166- if splitlevel=1 (default), this branch will automatically be split
167 into subbranches, with one subbranch for each data member or object
168 of the object itself. In case the object member is a TClonesArray,
169 the mechanism described in case C is applied to this array.
170- if splitlevel=2 ,this branch will automatically be split
171 into subbranches, with one subbranch for each data member or object
172 of the object itself. In case the object member is a TClonesArray,
173 it is processed as a TObject*, only one branch.
174
175Another available syntax is the following:
176
177~~~ {.cpp}
178 auto branch = tree.Branch(branchname, &p_object, bufsize, splitlevel)
179 auto branch = tree.Branch(branchname, className, &p_object, bufsize, splitlevel)
180~~~
181- p_object is a pointer to an object.
182- If className is not specified, Branch uses the type of p_object to determine the
183 type of the object.
184- If className is used to specify explicitly the object type, the className must
185 be of a type related to the one pointed to by the pointer. It should be either
186 a parent or derived class.
187
188Note: The pointer whose address is passed to TTree::Branch must not
189 be destroyed (i.e. go out of scope) until the TTree is deleted or
190 TTree::ResetBranchAddress is called.
191
192Note: The pointer p_object must be initialized before calling TTree::Branch
193- Do either:
194~~~ {.cpp}
195 MyDataClass* p_object = nullptr;
196 tree.Branch(branchname, &p_object);
197~~~
198- Or:
199~~~ {.cpp}
200 auto p_object = new MyDataClass;
201 tree.Branch(branchname, &p_object);
202~~~
203Whether the pointer is set to zero or not, the ownership of the object
204is not taken over by the TTree. I.e. even though an object will be allocated
205by TTree::Branch if the pointer p_object is zero, the object will <b>not</b>
206be deleted when the TTree is deleted.
207
208\anchor addingacolumnoftclonesarray
209## Add a column holding TClonesArray instances
210
211*It is recommended to use STL containers instead of TClonesArrays*.
212
213~~~ {.cpp}
214 // clonesarray is the address of a pointer to a TClonesArray.
215 auto branch = tree.Branch(branchname,clonesarray, bufsize, splitlevel)
216~~~
217The TClonesArray is a direct access list of objects of the same class.
218For example, if the TClonesArray is an array of TTrack objects,
219this function will create one subbranch for each data member of
220the object TTrack.
221
222\anchor fillthetree
223## Fill the Tree
224
225A TTree instance is filled with the invocation of the TTree::Fill method:
226~~~ {.cpp}
227 tree.Fill()
228~~~
229Upon its invocation, a loop on all defined branches takes place that for each branch invokes
230the TBranch::Fill method.
231
232\anchor addcoltoexistingtree
233## Add a column to an already existing Tree
234
235You may want to add a branch to an existing tree. For example,
236if one variable in the tree was computed with a certain algorithm,
237you may want to try another algorithm and compare the results.
238One solution is to add a new branch, fill it, and save the tree.
239The code below adds a simple branch to an existing tree.
240Note the kOverwrite option in the Write method, it overwrites the
241existing tree. If it is not specified, two copies of the tree headers
242are saved.
243~~~ {.cpp}
244 void tree3AddBranch() {
245 TFile f("tree3.root", "update");
246
247 Float_t new_v;
248 auto t3 = f->Get<TTree>("t3");
249 auto newBranch = t3->Branch("new_v", &new_v, "new_v/F");
250
251 Long64_t nentries = t3->GetEntries(); // read the number of entries in the t3
252
253 for (Long64_t i = 0; i < nentries; i++) {
254 new_v = gRandom->Gaus(0, 1);
255 newBranch->Fill();
256 }
257
258 t3->Write("", TObject::kOverwrite); // save only the new version of the tree
259 }
260~~~
261It is not always possible to add branches to existing datasets stored in TFiles: for example,
262these files might not be writeable, just readable. In addition, modifying in place a TTree
263causes a new TTree instance to be written and the previous one to be deleted.
264For this reasons, ROOT offers the concept of friends for TTree and TChain:
265if is good practice to rely on friend trees rather than adding a branch manually.
266
267\anchor fullexample
268## An Example
269
270Begin_Macro
271../../../tutorials/tree/tree.C
272End_Macro
273
274~~~ {.cpp}
275 // A simple example with histograms and a tree
276 //
277 // This program creates :
278 // - a one dimensional histogram
279 // - a two dimensional histogram
280 // - a profile histogram
281 // - a tree
282 //
283 // These objects are filled with some random numbers and saved on a file.
284
285 #include "TFile.h"
286 #include "TH1.h"
287 #include "TH2.h"
288 #include "TProfile.h"
289 #include "TRandom.h"
290 #include "TTree.h"
291
292 //__________________________________________________________________________
293 main(int argc, char **argv)
294 {
295 // Create a new ROOT binary machine independent file.
296 // Note that this file may contain any kind of ROOT objects, histograms,trees
297 // pictures, graphics objects, detector geometries, tracks, events, etc..
298 // This file is now becoming the current directory.
299 TFile hfile("htree.root","RECREATE","Demo ROOT file with histograms & trees");
300
301 // Create some histograms and a profile histogram
302 TH1F hpx("hpx","This is the px distribution",100,-4,4);
303 TH2F hpxpy("hpxpy","py ps px",40,-4,4,40,-4,4);
304 TProfile hprof("hprof","Profile of pz versus px",100,-4,4,0,20);
305
306 // Define some simple structures
307 typedef struct {Float_t x,y,z;} POINT;
308 typedef struct {
309 Int_t ntrack,nseg,nvertex;
310 UInt_t flag;
311 Float_t temperature;
312 } EVENTN;
313 POINT point;
314 EVENTN eventn;
315
316 // Create a ROOT Tree
317 TTree tree("T","An example of ROOT tree with a few branches");
318 tree.Branch("point",&point,"x:y:z");
319 tree.Branch("eventn",&eventn,"ntrack/I:nseg:nvertex:flag/i:temperature/F");
320 tree.Branch("hpx","TH1F",&hpx,128000,0);
321
322 Float_t px,py,pz;
323
324 // Here we start a loop on 1000 events
325 for ( Int_t i=0; i<1000; i++) {
326 gRandom->Rannor(px,py);
327 pz = px*px + py*py;
328 const auto random = gRandom->::Rndm(1);
329
330 // Fill histograms
331 hpx.Fill(px);
332 hpxpy.Fill(px,py,1);
333 hprof.Fill(px,pz,1);
334
335 // Fill structures
336 point.x = 10*(random-1);
337 point.y = 5*random;
338 point.z = 20*random;
339 eventn.ntrack = Int_t(100*random);
340 eventn.nseg = Int_t(2*eventn.ntrack);
341 eventn.nvertex = 1;
342 eventn.flag = Int_t(random+0.5);
343 eventn.temperature = 20+random;
344
345 // Fill the tree. For each event, save the 2 structures and 3 objects
346 // In this simple example, the objects hpx, hprof and hpxpy are slightly
347 // different from event to event. We expect a big compression factor!
348 tree->Fill();
349 }
350 // End of the loop
351
352 tree.Print();
353
354 // Save all objects in this file
355 hfile.Write();
356
357 // Close the file. Note that this is automatically done when you leave
358 // the application upon file destruction.
359 hfile.Close();
360
361 return 0;
362}
363~~~
364*/
365
366#include <ROOT/RConfig.hxx>
367#include "TTree.h"
368
369#include "ROOT/TIOFeatures.hxx"
370#include "TArrayC.h"
371#include "TBufferFile.h"
372#include "TBaseClass.h"
373#include "TBasket.h"
374#include "TBranchClones.h"
375#include "TBranchElement.h"
376#include "TBranchObject.h"
377#include "TBranchRef.h"
378#include "TBrowser.h"
379#include "TClass.h"
380#include "TClassEdit.h"
381#include "TClonesArray.h"
382#include "TCut.h"
383#include "TDataMember.h"
384#include "TDataType.h"
385#include "TDirectory.h"
386#include "TError.h"
387#include "TEntryList.h"
388#include "TEnv.h"
389#include "TEventList.h"
390#include "TFile.h"
391#include "TFolder.h"
392#include "TFriendElement.h"
393#include "TInterpreter.h"
394#include "TLeaf.h"
395#include "TLeafB.h"
396#include "TLeafC.h"
397#include "TLeafD.h"
398#include "TLeafElement.h"
399#include "TLeafF.h"
400#include "TLeafI.h"
401#include "TLeafL.h"
402#include "TLeafObject.h"
403#include "TLeafS.h"
404#include "TList.h"
405#include "TMath.h"
406#include "TMemFile.h"
407#include "TROOT.h"
408#include "TRealData.h"
409#include "TRegexp.h"
410#include "TRefTable.h"
411#include "TStreamerElement.h"
412#include "TStreamerInfo.h"
413#include "TStyle.h"
414#include "TSystem.h"
415#include "TTreeCloner.h"
416#include "TTreeCache.h"
417#include "TTreeCacheUnzip.h"
420#include "TVirtualIndex.h"
421#include "TVirtualPerfStats.h"
422#include "TVirtualPad.h"
423#include "TBranchSTL.h"
424#include "TSchemaRuleSet.h"
425#include "TFileMergeInfo.h"
426#include "ROOT/StringConv.hxx"
427#include "TVirtualMutex.h"
428#include "strlcpy.h"
429#include "snprintf.h"
430
431#include "TBranchIMTHelper.h"
432#include "TNotifyLink.h"
433
434#include <chrono>
435#include <cstddef>
436#include <iostream>
437#include <fstream>
438#include <sstream>
439#include <string>
440#include <cstdio>
441#include <climits>
442#include <algorithm>
443#include <set>
444
445#ifdef R__USE_IMT
447#include <thread>
448#endif
450constexpr Int_t kNEntriesResort = 100;
452
453Int_t TTree::fgBranchStyle = 1; // Use new TBranch style with TBranchElement.
454Long64_t TTree::fgMaxTreeSize = 100000000000LL;
455
457
458////////////////////////////////////////////////////////////////////////////////
459////////////////////////////////////////////////////////////////////////////////
460////////////////////////////////////////////////////////////////////////////////
462static char DataTypeToChar(EDataType datatype)
463{
464 // Return the leaflist 'char' for a given datatype.
465
466 switch(datatype) {
467 case kChar_t: return 'B';
468 case kUChar_t: return 'b';
469 case kBool_t: return 'O';
470 case kShort_t: return 'S';
471 case kUShort_t: return 's';
472 case kCounter:
473 case kInt_t: return 'I';
474 case kUInt_t: return 'i';
475 case kDouble_t: return 'D';
476 case kDouble32_t: return 'd';
477 case kFloat_t: return 'F';
478 case kFloat16_t: return 'f';
479 case kLong_t: return 'G';
480 case kULong_t: return 'g';
481 case kchar: return 0; // unsupported
482 case kLong64_t: return 'L';
483 case kULong64_t: return 'l';
484
485 case kCharStar: return 'C';
486 case kBits: return 0; //unsupported
487
488 case kOther_t:
489 case kNoType_t:
490 default:
491 return 0;
492 }
493 return 0;
494}
495
496////////////////////////////////////////////////////////////////////////////////
497/// \class TTree::TFriendLock
498/// Helper class to prevent infinite recursion in the usage of TTree Friends.
499
500////////////////////////////////////////////////////////////////////////////////
501/// Record in tree that it has been used while recursively looks through the friends.
504: fTree(tree)
505{
506 // We could also add some code to acquire an actual
507 // lock to prevent multi-thread issues
508 fMethodBit = methodbit;
509 if (fTree) {
512 } else {
513 fPrevious = 0;
514 }
515}
516
517////////////////////////////////////////////////////////////////////////////////
518/// Copy constructor.
521 fTree(tfl.fTree),
522 fMethodBit(tfl.fMethodBit),
523 fPrevious(tfl.fPrevious)
524{
525}
526
527////////////////////////////////////////////////////////////////////////////////
528/// Assignment operator.
531{
532 if(this!=&tfl) {
533 fTree=tfl.fTree;
534 fMethodBit=tfl.fMethodBit;
535 fPrevious=tfl.fPrevious;
536 }
537 return *this;
538}
539
540////////////////////////////////////////////////////////////////////////////////
541/// Restore the state of tree the same as before we set the lock.
544{
545 if (fTree) {
546 if (!fPrevious) {
547 fTree->fFriendLockStatus &= ~(fMethodBit & kBitMask);
548 }
549 }
550}
551
552////////////////////////////////////////////////////////////////////////////////
553/// \class TTree::TClusterIterator
554/// Helper class to iterate over cluster of baskets.
555
556////////////////////////////////////////////////////////////////////////////////
557/// Regular constructor.
558/// TTree is not set as const, since we might modify if it is a TChain.
560TTree::TClusterIterator::TClusterIterator(TTree *tree, Long64_t firstEntry) : fTree(tree), fClusterRange(0), fStartEntry(0), fNextEntry(0), fEstimatedSize(-1)
561{
562 if (fTree->fNClusterRange) {
563 // Find the correct cluster range.
564 //
565 // Since fClusterRangeEnd contains the inclusive upper end of the range, we need to search for the
566 // range that was containing the previous entry and add 1 (because BinarySearch consider the values
567 // to be the inclusive start of the bucket).
569
570 Long64_t entryInRange;
571 Long64_t pedestal;
572 if (fClusterRange == 0) {
573 pedestal = 0;
574 entryInRange = firstEntry;
575 } else {
576 pedestal = fTree->fClusterRangeEnd[fClusterRange-1] + 1;
577 entryInRange = firstEntry - pedestal;
578 }
579 Long64_t autoflush;
581 autoflush = fTree->fAutoFlush;
582 } else {
583 autoflush = fTree->fClusterSize[fClusterRange];
584 }
585 if (autoflush <= 0) {
586 autoflush = GetEstimatedClusterSize();
587 }
588 fStartEntry = pedestal + entryInRange - entryInRange%autoflush;
589 } else if ( fTree->GetAutoFlush() <= 0 ) {
590 // Case of old files before November 9 2009 *or* small tree where AutoFlush was never set.
591 fStartEntry = firstEntry;
592 } else {
593 fStartEntry = firstEntry - firstEntry%fTree->GetAutoFlush();
594 }
595 fNextEntry = fStartEntry; // Position correctly for the first call to Next()
596}
597
598////////////////////////////////////////////////////////////////////////////////
599/// Estimate the cluster size.
600///
601/// In almost all cases, this quickly returns the size of the auto-flush
602/// in the TTree.
603///
604/// However, in the case where the cluster size was not fixed (old files and
605/// case where autoflush was explicitly set to zero), we need estimate
606/// a cluster size in relation to the size of the cache.
607///
608/// After this value is calculated once for the TClusterIterator, it is
609/// cached and reused in future calls.
612{
613 auto autoFlush = fTree->GetAutoFlush();
614 if (autoFlush > 0) return autoFlush;
615 if (fEstimatedSize > 0) return fEstimatedSize;
616
617 Long64_t zipBytes = fTree->GetZipBytes();
618 if (zipBytes == 0) {
619 fEstimatedSize = fTree->GetEntries() - 1;
620 if (fEstimatedSize <= 0)
621 fEstimatedSize = 1;
622 } else {
623 Long64_t clusterEstimate = 1;
624 Long64_t cacheSize = fTree->GetCacheSize();
625 if (cacheSize == 0) {
626 // Humm ... let's double check on the file.
627 TFile *file = fTree->GetCurrentFile();
628 if (file) {
629 TFileCacheRead *cache = fTree->GetReadCache(file);
630 if (cache) {
631 cacheSize = cache->GetBufferSize();
632 }
633 }
634 }
635 // If neither file nor tree has a cache, use the current default.
636 if (cacheSize <= 0) {
637 cacheSize = 30000000;
638 }
639 clusterEstimate = fTree->GetEntries() * cacheSize / zipBytes;
640 // If there are no entries, then just default to 1.
641 fEstimatedSize = clusterEstimate ? clusterEstimate : 1;
642 }
643 return fEstimatedSize;
644}
645
646////////////////////////////////////////////////////////////////////////////////
647/// Move on to the next cluster and return the starting entry
648/// of this next cluster
651{
652 fStartEntry = fNextEntry;
653 if (fTree->fNClusterRange || fTree->GetAutoFlush() > 0) {
654 if (fClusterRange == fTree->fNClusterRange) {
655 // We are looking at a range which size
656 // is defined by AutoFlush itself and goes to the GetEntries.
657 fNextEntry += GetEstimatedClusterSize();
658 } else {
659 if (fStartEntry > fTree->fClusterRangeEnd[fClusterRange]) {
660 ++fClusterRange;
661 }
662 if (fClusterRange == fTree->fNClusterRange) {
663 // We are looking at the last range which size
664 // is defined by AutoFlush itself and goes to the GetEntries.
665 fNextEntry += GetEstimatedClusterSize();
666 } else {
667 Long64_t clusterSize = fTree->fClusterSize[fClusterRange];
668 if (clusterSize == 0) {
669 clusterSize = GetEstimatedClusterSize();
670 }
671 fNextEntry += clusterSize;
672 if (fNextEntry > fTree->fClusterRangeEnd[fClusterRange]) {
673 // The last cluster of the range was a partial cluster,
674 // so the next cluster starts at the beginning of the
675 // next range.
676 fNextEntry = fTree->fClusterRangeEnd[fClusterRange] + 1;
677 }
678 }
679 }
680 } else {
681 // Case of old files before November 9 2009
682 fNextEntry = fStartEntry + GetEstimatedClusterSize();
683 }
684 if (fNextEntry > fTree->GetEntries()) {
685 fNextEntry = fTree->GetEntries();
686 }
687 return fStartEntry;
688}
689
690////////////////////////////////////////////////////////////////////////////////
691/// Move on to the previous cluster and return the starting entry
692/// of this previous cluster
695{
696 fNextEntry = fStartEntry;
697 if (fTree->fNClusterRange || fTree->GetAutoFlush() > 0) {
698 if (fClusterRange == 0 || fTree->fNClusterRange == 0) {
699 // We are looking at a range which size
700 // is defined by AutoFlush itself.
701 fStartEntry -= GetEstimatedClusterSize();
702 } else {
703 if (fNextEntry <= fTree->fClusterRangeEnd[fClusterRange]) {
704 --fClusterRange;
705 }
706 if (fClusterRange == 0) {
707 // We are looking at the first range.
708 fStartEntry = 0;
709 } else {
710 Long64_t clusterSize = fTree->fClusterSize[fClusterRange];
711 if (clusterSize == 0) {
712 clusterSize = GetEstimatedClusterSize();
713 }
714 fStartEntry -= clusterSize;
715 }
716 }
717 } else {
718 // Case of old files before November 9 2009 or trees that never auto-flushed.
719 fStartEntry = fNextEntry - GetEstimatedClusterSize();
720 }
721 if (fStartEntry < 0) {
722 fStartEntry = 0;
723 }
724 return fStartEntry;
725}
726
727////////////////////////////////////////////////////////////////////////////////
728////////////////////////////////////////////////////////////////////////////////
729////////////////////////////////////////////////////////////////////////////////
730
731////////////////////////////////////////////////////////////////////////////////
732/// Default constructor and I/O constructor.
733///
734/// Note: We do *not* insert ourself into the current directory.
735///
738: TNamed()
739, TAttLine()
740, TAttFill()
741, TAttMarker()
742, fEntries(0)
743, fTotBytes(0)
744, fZipBytes(0)
745, fSavedBytes(0)
746, fFlushedBytes(0)
747, fWeight(1)
749, fScanField(25)
750, fUpdate(0)
754, fMaxEntries(0)
755, fMaxEntryLoop(0)
757, fAutoSave( -300000000)
758, fAutoFlush(-30000000)
759, fEstimate(1000000)
761, fClusterSize(0)
762, fCacheSize(0)
763, fChainOffset(0)
764, fReadEntry(-1)
765, fTotalBuffers(0)
766, fPacketSize(100)
767, fNfill(0)
768, fDebug(0)
769, fDebugMin(0)
770, fDebugMax(9999999)
771, fMakeClass(0)
772, fFileNumber(0)
773, fNotify(0)
774, fDirectory(0)
775, fBranches()
776, fLeaves()
777, fAliases(0)
778, fEventList(0)
779, fEntryList(0)
780, fIndexValues()
781, fIndex()
782, fTreeIndex(0)
783, fFriends(0)
785, fPerfStats(0)
786, fUserInfo(0)
787, fPlayer(0)
788, fClones(0)
789, fBranchRef(0)
795, fIMTEnabled(ROOT::IsImplicitMTEnabled())
797{
798 fMaxEntries = 1000000000;
799 fMaxEntries *= 1000;
800
801 fMaxEntryLoop = 1000000000;
802 fMaxEntryLoop *= 1000;
803
805}
806
807////////////////////////////////////////////////////////////////////////////////
808/// Normal tree constructor.
809///
810/// The tree is created in the current directory.
811/// Use the various functions Branch below to add branches to this tree.
812///
813/// If the first character of title is a "/", the function assumes a folder name.
814/// In this case, it creates automatically branches following the folder hierarchy.
815/// splitlevel may be used in this case to control the split level.
817TTree::TTree(const char* name, const char* title, Int_t splitlevel /* = 99 */,
818 TDirectory* dir /* = gDirectory*/)
819: TNamed(name, title)
820, TAttLine()
821, TAttFill()
822, TAttMarker()
823, fEntries(0)
824, fTotBytes(0)
825, fZipBytes(0)
826, fSavedBytes(0)
827, fFlushedBytes(0)
828, fWeight(1)
829, fTimerInterval(0)
830, fScanField(25)
831, fUpdate(0)
832, fDefaultEntryOffsetLen(1000)
833, fNClusterRange(0)
834, fMaxClusterRange(0)
835, fMaxEntries(0)
836, fMaxEntryLoop(0)
837, fMaxVirtualSize(0)
838, fAutoSave( -300000000)
839, fAutoFlush(-30000000)
840, fEstimate(1000000)
841, fClusterRangeEnd(0)
842, fClusterSize(0)
843, fCacheSize(0)
844, fChainOffset(0)
845, fReadEntry(-1)
846, fTotalBuffers(0)
847, fPacketSize(100)
848, fNfill(0)
849, fDebug(0)
850, fDebugMin(0)
851, fDebugMax(9999999)
852, fMakeClass(0)
853, fFileNumber(0)
854, fNotify(0)
855, fDirectory(dir)
856, fBranches()
857, fLeaves()
858, fAliases(0)
859, fEventList(0)
860, fEntryList(0)
861, fIndexValues()
862, fIndex()
863, fTreeIndex(0)
864, fFriends(0)
865, fExternalFriends(0)
866, fPerfStats(0)
867, fUserInfo(0)
868, fPlayer(0)
869, fClones(0)
870, fBranchRef(0)
871, fFriendLockStatus(0)
872, fTransientBuffer(0)
873, fCacheDoAutoInit(kTRUE)
874, fCacheDoClusterPrefetch(kFALSE)
875, fCacheUserSet(kFALSE)
876, fIMTEnabled(ROOT::IsImplicitMTEnabled())
877, fNEntriesSinceSorting(0)
878{
879 // TAttLine state.
883
884 // TAttFill state.
887
888 // TAttMarkerState.
892
893 fMaxEntries = 1000000000;
894 fMaxEntries *= 1000;
895
896 fMaxEntryLoop = 1000000000;
897 fMaxEntryLoop *= 1000;
898
899 // Insert ourself into the current directory.
900 // FIXME: This is very annoying behaviour, we should
901 // be able to choose to not do this like we
902 // can with a histogram.
903 if (fDirectory) fDirectory->Append(this);
904
906
907 // If title starts with "/" and is a valid folder name, a superbranch
908 // is created.
909 // FIXME: Why?
910 if (strlen(title) > 2) {
911 if (title[0] == '/') {
912 Branch(title+1,32000,splitlevel);
913 }
914 }
915}
916
917////////////////////////////////////////////////////////////////////////////////
918/// Destructor.
921{
922 if (auto link = dynamic_cast<TNotifyLinkBase*>(fNotify)) {
923 link->Clear();
924 }
925 if (fAllocationCount && (gDebug > 0)) {
926 Info("TTree::~TTree", "For tree %s, allocation count is %u.", GetName(), fAllocationCount.load());
927#ifdef R__TRACK_BASKET_ALLOC_TIME
928 Info("TTree::~TTree", "For tree %s, allocation time is %lluus.", GetName(), fAllocationTime.load());
929#endif
930 }
931
932 if (fDirectory) {
933 // We are in a directory, which may possibly be a file.
934 if (fDirectory->GetList()) {
935 // Remove us from the directory listing.
936 fDirectory->Remove(this);
937 }
938 //delete the file cache if it points to this Tree
941 }
942
943 // Remove the TTree from any list (linked to to the list of Cleanups) to avoid the unnecessary call to
944 // this RecursiveRemove while we delete our content.
946 ResetBit(kMustCleanup); // Don't redo it.
947
948 // We don't own the leaves in fLeaves, the branches do.
949 fLeaves.Clear();
950 // I'm ready to destroy any objects allocated by
951 // SetAddress() by my branches. If I have clones,
952 // tell them to zero their pointers to this shared
953 // memory.
954 if (fClones && fClones->GetEntries()) {
955 // I have clones.
956 // I am about to delete the objects created by
957 // SetAddress() which we are sharing, so tell
958 // the clones to release their pointers to them.
959 for (TObjLink* lnk = fClones->FirstLink(); lnk; lnk = lnk->Next()) {
960 TTree* clone = (TTree*) lnk->GetObject();
961 // clone->ResetBranchAddresses();
962
963 // Reset only the branch we have set the address of.
964 CopyAddresses(clone,kTRUE);
965 }
966 }
967 // Get rid of our branches, note that this will also release
968 // any memory allocated by TBranchElement::SetAddress().
970
971 // The TBranch destructor is using fDirectory to detect whether it
972 // owns the TFile that contains its data (See TBranch::~TBranch)
973 fDirectory = nullptr;
974
975 // FIXME: We must consider what to do with the reset of these if we are a clone.
976 delete fPlayer;
977 fPlayer = 0;
978 if (fExternalFriends) {
979 using namespace ROOT::Detail;
981 fetree->Reset();
982 fExternalFriends->Clear("nodelete");
984 }
985 if (fFriends) {
986 fFriends->Delete();
987 delete fFriends;
988 fFriends = 0;
989 }
990 if (fAliases) {
991 fAliases->Delete();
992 delete fAliases;
993 fAliases = 0;
994 }
995 if (fUserInfo) {
996 fUserInfo->Delete();
997 delete fUserInfo;
998 fUserInfo = 0;
999 }
1000 if (fClones) {
1001 // Clone trees should no longer be removed from fClones when they are deleted.
1002 {
1004 gROOT->GetListOfCleanups()->Remove(fClones);
1005 }
1006 // Note: fClones does not own its content.
1007 delete fClones;
1008 fClones = 0;
1009 }
1010 if (fEntryList) {
1012 // Delete the entry list if it is marked to be deleted and it is not also
1013 // owned by a directory. (Otherwise we would need to make sure that a
1014 // TDirectoryFile that has a TTree in it does a 'slow' TList::Delete.
1015 delete fEntryList;
1016 fEntryList=0;
1017 }
1018 }
1019 delete fTreeIndex;
1020 fTreeIndex = 0;
1021 delete fBranchRef;
1022 fBranchRef = 0;
1023 delete [] fClusterRangeEnd;
1024 fClusterRangeEnd = 0;
1025 delete [] fClusterSize;
1026 fClusterSize = 0;
1027
1028 if (fTransientBuffer) {
1029 delete fTransientBuffer;
1030 fTransientBuffer = 0;
1031 }
1032}
1033
1034////////////////////////////////////////////////////////////////////////////////
1035/// Returns the transient buffer currently used by this TTree for reading/writing baskets.
1038{
1039 if (fTransientBuffer) {
1040 if (fTransientBuffer->BufferSize() < size) {
1042 }
1043 return fTransientBuffer;
1044 }
1046 return fTransientBuffer;
1047}
1048
1049////////////////////////////////////////////////////////////////////////////////
1050/// Add branch with name bname to the Tree cache.
1051/// If bname="*" all branches are added to the cache.
1052/// if subbranches is true all the branches of the subbranches are
1053/// also put to the cache.
1054///
1055/// Returns:
1056/// - 0 branch added or already included
1057/// - -1 on error
1059Int_t TTree::AddBranchToCache(const char*bname, Bool_t subbranches)
1060{
1061 if (!GetTree()) {
1062 if (LoadTree(0)<0) {
1063 Error("AddBranchToCache","Could not load a tree");
1064 return -1;
1065 }
1066 }
1067 if (GetTree()) {
1068 if (GetTree() != this) {
1069 return GetTree()->AddBranchToCache(bname, subbranches);
1070 }
1071 } else {
1072 Error("AddBranchToCache", "No tree is available. Branch was not added to the cache");
1073 return -1;
1074 }
1075
1076 TFile *f = GetCurrentFile();
1077 if (!f) {
1078 Error("AddBranchToCache", "No file is available. Branch was not added to the cache");
1079 return -1;
1080 }
1082 if (!tc) {
1083 Error("AddBranchToCache", "No cache is available, branch not added");
1084 return -1;
1085 }
1086 return tc->AddBranch(bname,subbranches);
1087}
1088
1089////////////////////////////////////////////////////////////////////////////////
1090/// Add branch b to the Tree cache.
1091/// if subbranches is true all the branches of the subbranches are
1092/// also put to the cache.
1093///
1094/// Returns:
1095/// - 0 branch added or already included
1096/// - -1 on error
1099{
1100 if (!GetTree()) {
1101 if (LoadTree(0)<0) {
1102 Error("AddBranchToCache","Could not load a tree");
1103 return -1;
1104 }
1105 }
1106 if (GetTree()) {
1107 if (GetTree() != this) {
1108 Int_t res = GetTree()->AddBranchToCache(b, subbranches);
1109 if (res<0) {
1110 Error("AddBranchToCache", "Error adding branch");
1111 }
1112 return res;
1113 }
1114 } else {
1115 Error("AddBranchToCache", "No tree is available. Branch was not added to the cache");
1116 return -1;
1117 }
1118
1119 TFile *f = GetCurrentFile();
1120 if (!f) {
1121 Error("AddBranchToCache", "No file is available. Branch was not added to the cache");
1122 return -1;
1123 }
1125 if (!tc) {
1126 Error("AddBranchToCache", "No cache is available, branch not added");
1127 return -1;
1128 }
1129 return tc->AddBranch(b,subbranches);
1130}
1131
1132////////////////////////////////////////////////////////////////////////////////
1133/// Remove the branch with name 'bname' from the Tree cache.
1134/// If bname="*" all branches are removed from the cache.
1135/// if subbranches is true all the branches of the subbranches are
1136/// also removed from the cache.
1137///
1138/// Returns:
1139/// - 0 branch dropped or not in cache
1140/// - -1 on error
1142Int_t TTree::DropBranchFromCache(const char*bname, Bool_t subbranches)
1143{
1144 if (!GetTree()) {
1145 if (LoadTree(0)<0) {
1146 Error("DropBranchFromCache","Could not load a tree");
1147 return -1;
1148 }
1149 }
1150 if (GetTree()) {
1151 if (GetTree() != this) {
1152 return GetTree()->DropBranchFromCache(bname, subbranches);
1153 }
1154 } else {
1155 Error("DropBranchFromCache", "No tree is available. Branch was not dropped from the cache");
1156 return -1;
1157 }
1158
1159 TFile *f = GetCurrentFile();
1160 if (!f) {
1161 Error("DropBranchFromCache", "No file is available. Branch was not dropped from the cache");
1162 return -1;
1163 }
1165 if (!tc) {
1166 Error("DropBranchFromCache", "No cache is available, branch not dropped");
1167 return -1;
1168 }
1169 return tc->DropBranch(bname,subbranches);
1170}
1171
1172////////////////////////////////////////////////////////////////////////////////
1173/// Remove the branch b from the Tree cache.
1174/// if subbranches is true all the branches of the subbranches are
1175/// also removed from the cache.
1176///
1177/// Returns:
1178/// - 0 branch dropped or not in cache
1179/// - -1 on error
1182{
1183 if (!GetTree()) {
1184 if (LoadTree(0)<0) {
1185 Error("DropBranchFromCache","Could not load a tree");
1186 return -1;
1187 }
1188 }
1189 if (GetTree()) {
1190 if (GetTree() != this) {
1191 Int_t res = GetTree()->DropBranchFromCache(b, subbranches);
1192 if (res<0) {
1193 Error("DropBranchFromCache", "Error dropping branch");
1194 }
1195 return res;
1196 }
1197 } else {
1198 Error("DropBranchFromCache", "No tree is available. Branch was not dropped from the cache");
1199 return -1;
1200 }
1201
1202 TFile *f = GetCurrentFile();
1203 if (!f) {
1204 Error("DropBranchFromCache", "No file is available. Branch was not dropped from the cache");
1205 return -1;
1206 }
1208 if (!tc) {
1209 Error("DropBranchFromCache", "No cache is available, branch not dropped");
1210 return -1;
1211 }
1212 return tc->DropBranch(b,subbranches);
1213}
1214
1215////////////////////////////////////////////////////////////////////////////////
1216/// Add a cloned tree to our list of trees to be notified whenever we change
1217/// our branch addresses or when we are deleted.
1219void TTree::AddClone(TTree* clone)
1220{
1221 if (!fClones) {
1222 fClones = new TList();
1223 fClones->SetOwner(false);
1224 // So that the clones are automatically removed from the list when
1225 // they are deleted.
1226 {
1228 gROOT->GetListOfCleanups()->Add(fClones);
1229 }
1230 }
1231 if (!fClones->FindObject(clone)) {
1232 fClones->Add(clone);
1233 }
1234}
1235
1236// Check whether mainTree and friendTree can be friends w.r.t. the kEntriesReshuffled bit.
1237// In particular, if any has the bit set, then friendTree must have a TTreeIndex and the
1238// branches used for indexing must be present in mainTree.
1239// Return true if the trees can be friends, false otherwise.
1240bool CheckReshuffling(TTree &mainTree, TTree &friendTree)
1241{
1242 const auto isMainReshuffled = mainTree.TestBit(TTree::kEntriesReshuffled);
1243 const auto isFriendReshuffled = friendTree.TestBit(TTree::kEntriesReshuffled);
1244 const auto friendHasValidIndex = [&] {
1245 auto idx = friendTree.GetTreeIndex();
1246 return idx ? idx->IsValidFor(&mainTree) : kFALSE;
1247 }();
1248
1249 if ((isMainReshuffled || isFriendReshuffled) && !friendHasValidIndex) {
1250 const auto reshuffledTreeName = isMainReshuffled ? mainTree.GetName() : friendTree.GetName();
1251 const auto msg = "Tree '%s' has the kEntriesReshuffled bit set, and cannot be used as friend nor can be added as "
1252 "a friend unless the main tree has a TTreeIndex on the friend tree '%s'. You can also unset the "
1253 "bit manually if you know what you are doing.";
1254 Error("AddFriend", msg, reshuffledTreeName, friendTree.GetName());
1255 return false;
1256 }
1257 return true;
1258}
1259
1260////////////////////////////////////////////////////////////////////////////////
1261/// Add a TFriendElement to the list of friends.
1262///
1263/// This function:
1264/// - opens a file if filename is specified
1265/// - reads a Tree with name treename from the file (current directory)
1266/// - adds the Tree to the list of friends
1267/// see other AddFriend functions
1268///
1269/// A TFriendElement TF describes a TTree object TF in a file.
1270/// When a TFriendElement TF is added to the list of friends of an
1271/// existing TTree T, any variable from TF can be referenced in a query
1272/// to T.
1273///
1274/// A tree keeps a list of friends. In the context of a tree (or a chain),
1275/// friendship means unrestricted access to the friends data. In this way
1276/// it is much like adding another branch to the tree without taking the risk
1277/// of damaging it. To add a friend to the list, you can use the TTree::AddFriend
1278/// method. The tree in the diagram below has two friends (friend_tree1 and
1279/// friend_tree2) and now has access to the variables a,b,c,i,j,k,l and m.
1280///
1281/// \image html ttree_friend1.png
1282///
1283/// The AddFriend method has two parameters, the first is the tree name and the
1284/// second is the name of the ROOT file where the friend tree is saved.
1285/// AddFriend automatically opens the friend file. If no file name is given,
1286/// the tree called ft1 is assumed to be in the same file as the original tree.
1287///
1288/// tree.AddFriend("ft1","friendfile1.root");
1289/// If the friend tree has the same name as the original tree, you can give it
1290/// an alias in the context of the friendship:
1291///
1292/// tree.AddFriend("tree1 = tree","friendfile1.root");
1293/// Once the tree has friends, we can use TTree::Draw as if the friend's
1294/// variables were in the original tree. To specify which tree to use in
1295/// the Draw method, use the syntax:
1296/// ~~~ {.cpp}
1297/// <treeName>.<branchname>.<varname>
1298/// ~~~
1299/// If the variablename is enough to uniquely identify the variable, you can
1300/// leave out the tree and/or branch name.
1301/// For example, these commands generate a 3-d scatter plot of variable "var"
1302/// in the TTree tree versus variable v1 in TTree ft1 versus variable v2 in
1303/// TTree ft2.
1304/// ~~~ {.cpp}
1305/// tree.AddFriend("ft1","friendfile1.root");
1306/// tree.AddFriend("ft2","friendfile2.root");
1307/// tree.Draw("var:ft1.v1:ft2.v2");
1308/// ~~~
1309/// \image html ttree_friend2.png
1310///
1311/// The picture illustrates the access of the tree and its friends with a
1312/// Draw command.
1313/// When AddFriend is called, the ROOT file is automatically opened and the
1314/// friend tree (ft1) is read into memory. The new friend (ft1) is added to
1315/// the list of friends of tree.
1316/// The number of entries in the friend must be equal or greater to the number
1317/// of entries of the original tree. If the friend tree has fewer entries a
1318/// warning is given and the missing entries are not included in the histogram.
1319/// To retrieve the list of friends from a tree use TTree::GetListOfFriends.
1320/// When the tree is written to file (TTree::Write), the friends list is saved
1321/// with it. And when the tree is retrieved, the trees on the friends list are
1322/// also retrieved and the friendship restored.
1323/// When a tree is deleted, the elements of the friend list are also deleted.
1324/// It is possible to declare a friend tree that has the same internal
1325/// structure (same branches and leaves) as the original tree, and compare the
1326/// same values by specifying the tree.
1327/// ~~~ {.cpp}
1328/// tree.Draw("var:ft1.var:ft2.var")
1329/// ~~~
1331TFriendElement *TTree::AddFriend(const char *treename, const char *filename)
1332{
1333 if (!fFriends) {
1334 fFriends = new TList();
1335 }
1336 TFriendElement *fe = new TFriendElement(this, treename, filename);
1337
1338 TTree *t = fe->GetTree();
1339 bool canAddFriend = true;
1340 if (t) {
1341 canAddFriend = CheckReshuffling(*this, *t);
1342 if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
1343 Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent Tree: %lld", treename,
1345 }
1346 } else {
1347 Error("AddFriend", "Cannot find tree '%s' in file '%s', friend not added", treename, filename);
1348 canAddFriend = false;
1349 }
1350
1351 if (canAddFriend)
1352 fFriends->Add(fe);
1353 return fe;
1354}
1355
1356////////////////////////////////////////////////////////////////////////////////
1357/// Add a TFriendElement to the list of friends.
1358///
1359/// The TFile is managed by the user (e.g. the user must delete the file).
1360/// For complete description see AddFriend(const char *, const char *).
1361/// This function:
1362/// - reads a Tree with name treename from the file
1363/// - adds the Tree to the list of friends
1365TFriendElement *TTree::AddFriend(const char *treename, TFile *file)
1366{
1367 if (!fFriends) {
1368 fFriends = new TList();
1369 }
1370 TFriendElement *fe = new TFriendElement(this, treename, file);
1371 R__ASSERT(fe);
1372 TTree *t = fe->GetTree();
1373 bool canAddFriend = true;
1374 if (t) {
1375 canAddFriend = CheckReshuffling(*this, *t);
1376 if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
1377 Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent tree: %lld", treename,
1378 file->GetName(), t->GetEntries(), fEntries);
1379 }
1380 } else {
1381 Error("AddFriend", "Cannot find tree '%s' in file '%s', friend not added", treename, file->GetName());
1382 canAddFriend = false;
1383 }
1384
1385 if (canAddFriend)
1386 fFriends->Add(fe);
1387 return fe;
1388}
1389
1390////////////////////////////////////////////////////////////////////////////////
1391/// Add a TFriendElement to the list of friends.
1392///
1393/// The TTree is managed by the user (e.g., the user must delete the file).
1394/// For a complete description see AddFriend(const char *, const char *).
1396TFriendElement *TTree::AddFriend(TTree *tree, const char *alias, Bool_t warn)
1397{
1398 if (!tree) {
1399 return 0;
1400 }
1401 if (!fFriends) {
1402 fFriends = new TList();
1403 }
1404 TFriendElement *fe = new TFriendElement(this, tree, alias);
1405 R__ASSERT(fe); // this assert is for historical reasons. Don't remove it unless you understand all the consequences.
1406 TTree *t = fe->GetTree();
1407 if (warn && (t->GetEntries() < fEntries)) {
1408 Warning("AddFriend", "FriendElement '%s' in file '%s' has less entries %lld than its parent tree: %lld",
1409 tree->GetName(), fe->GetFile() ? fe->GetFile()->GetName() : "(memory resident)", t->GetEntries(),
1410 fEntries);
1411 }
1412 if (CheckReshuffling(*this, *t))
1413 fFriends->Add(fe);
1414 else
1415 tree->RemoveExternalFriend(fe);
1416 return fe;
1417}
1418
1419////////////////////////////////////////////////////////////////////////////////
1420/// AutoSave tree header every fAutoSave bytes.
1421///
1422/// When large Trees are produced, it is safe to activate the AutoSave
1423/// procedure. Some branches may have buffers holding many entries.
1424/// If fAutoSave is negative, AutoSave is automatically called by
1425/// TTree::Fill when the number of bytes generated since the previous
1426/// AutoSave is greater than -fAutoSave bytes.
1427/// If fAutoSave is positive, AutoSave is automatically called by
1428/// TTree::Fill every N entries.
1429/// This function may also be invoked by the user.
1430/// Each AutoSave generates a new key on the file.
1431/// Once the key with the tree header has been written, the previous cycle
1432/// (if any) is deleted.
1433///
1434/// Note that calling TTree::AutoSave too frequently (or similarly calling
1435/// TTree::SetAutoSave with a small value) is an expensive operation.
1436/// You should make tests for your own application to find a compromise
1437/// between speed and the quantity of information you may loose in case of
1438/// a job crash.
1439///
1440/// In case your program crashes before closing the file holding this tree,
1441/// the file will be automatically recovered when you will connect the file
1442/// in UPDATE mode.
1443/// The Tree will be recovered at the status corresponding to the last AutoSave.
1444///
1445/// if option contains "SaveSelf", gDirectory->SaveSelf() is called.
1446/// This allows another process to analyze the Tree while the Tree is being filled.
1447///
1448/// if option contains "FlushBaskets", TTree::FlushBaskets is called and all
1449/// the current basket are closed-out and written to disk individually.
1450///
1451/// By default the previous header is deleted after having written the new header.
1452/// if option contains "Overwrite", the previous Tree header is deleted
1453/// before written the new header. This option is slightly faster, but
1454/// the default option is safer in case of a problem (disk quota exceeded)
1455/// when writing the new header.
1456///
1457/// The function returns the number of bytes written to the file.
1458/// if the number of bytes is null, an error has occurred while writing
1459/// the header to the file.
1460///
1461/// ## How to write a Tree in one process and view it from another process
1462///
1463/// The following two scripts illustrate how to do this.
1464/// The script treew.C is executed by process1, treer.C by process2
1465///
1466/// script treew.C:
1467/// ~~~ {.cpp}
1468/// void treew() {
1469/// TFile f("test.root","recreate");
1470/// TNtuple *ntuple = new TNtuple("ntuple","Demo","px:py:pz:random:i");
1471/// Float_t px, py, pz;
1472/// for ( Int_t i=0; i<10000000; i++) {
1473/// gRandom->Rannor(px,py);
1474/// pz = px*px + py*py;
1475/// Float_t random = gRandom->Rndm(1);
1476/// ntuple->Fill(px,py,pz,random,i);
1477/// if (i%1000 == 1) ntuple->AutoSave("SaveSelf");
1478/// }
1479/// }
1480/// ~~~
1481/// script treer.C:
1482/// ~~~ {.cpp}
1483/// void treer() {
1484/// TFile f("test.root");
1485/// TTree *ntuple = (TTree*)f.Get("ntuple");
1486/// TCanvas c1;
1487/// Int_t first = 0;
1488/// while(1) {
1489/// if (first == 0) ntuple->Draw("px>>hpx", "","",10000000,first);
1490/// else ntuple->Draw("px>>+hpx","","",10000000,first);
1491/// first = (Int_t)ntuple->GetEntries();
1492/// c1.Update();
1493/// gSystem->Sleep(1000); //sleep 1 second
1494/// ntuple->Refresh();
1495/// }
1496/// }
1497/// ~~~
1500{
1501 if (!fDirectory || fDirectory == gROOT || !fDirectory->IsWritable()) return 0;
1502 if (gDebug > 0) {
1503 Info("AutoSave", "Tree:%s after %lld bytes written\n",GetName(),GetTotBytes());
1504 }
1505 TString opt = option;
1506 opt.ToLower();
1507
1508 if (opt.Contains("flushbaskets")) {
1509 if (gDebug > 0) Info("AutoSave", "calling FlushBaskets \n");
1511 }
1512
1514
1516 Long64_t nbytes;
1517 if (opt.Contains("overwrite")) {
1518 nbytes = fDirectory->WriteTObject(this,"","overwrite");
1519 } else {
1520 nbytes = fDirectory->WriteTObject(this); //nbytes will be 0 if Write failed (disk space exceeded)
1521 if (nbytes && key && strcmp(ClassName(), key->GetClassName()) == 0) {
1522 key->Delete();
1523 delete key;
1524 }
1525 }
1526 // save StreamerInfo
1528 if (file) file->WriteStreamerInfo();
1529
1530 if (opt.Contains("saveself")) {
1532 //the following line is required in case GetUserInfo contains a user class
1533 //for which the StreamerInfo must be written. One could probably be a bit faster (Rene)
1534 if (file) file->WriteHeader();
1535 }
1536
1537 return nbytes;
1538}
1539
1540namespace {
1541 // This error message is repeated several times in the code. We write it once.
1542 const char* writeStlWithoutProxyMsg = "The class requested (%s) for the branch \"%s\""
1543 " is an instance of an stl collection and does not have a compiled CollectionProxy."
1544 " Please generate the dictionary for this collection (%s) to avoid to write corrupted data.";
1545}
1546
1547////////////////////////////////////////////////////////////////////////////////
1548/// Same as TTree::Branch() with added check that addobj matches className.
1549///
1550/// \see TTree::Branch() for other details.
1551///
1553TBranch* TTree::BranchImp(const char* branchname, const char* classname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
1554{
1555 TClass* claim = TClass::GetClass(classname);
1556 if (!ptrClass) {
1557 if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
1558 Error("Branch", writeStlWithoutProxyMsg,
1559 claim->GetName(), branchname, claim->GetName());
1560 return 0;
1561 }
1562 return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
1563 }
1564 TClass* actualClass = 0;
1565 void** addr = (void**) addobj;
1566 if (addr) {
1567 actualClass = ptrClass->GetActualClass(*addr);
1568 }
1569 if (ptrClass && claim) {
1570 if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
1571 // Note we currently do not warn in case of splicing or over-expectation).
1572 if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
1573 // The type is the same according to the C++ type_info, we must be in the case of
1574 // a template of Double32_t. This is actually a correct case.
1575 } else {
1576 Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the pointer passed (%s)",
1577 claim->GetName(), branchname, ptrClass->GetName());
1578 }
1579 } else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
1580 if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
1581 // The type is the same according to the C++ type_info, we must be in the case of
1582 // a template of Double32_t. This is actually a correct case.
1583 } else {
1584 Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
1585 actualClass->GetName(), branchname, claim->GetName());
1586 }
1587 }
1588 }
1589 if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
1590 Error("Branch", writeStlWithoutProxyMsg,
1591 claim->GetName(), branchname, claim->GetName());
1592 return 0;
1593 }
1594 return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
1595}
1596
1597////////////////////////////////////////////////////////////////////////////////
1598/// Same as TTree::Branch but automatic detection of the class name.
1599/// \see TTree::Branch for other details.
1601TBranch* TTree::BranchImp(const char* branchname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
1602{
1603 if (!ptrClass) {
1604 Error("Branch", "The pointer specified for %s is not of a class known to ROOT", branchname);
1605 return 0;
1606 }
1607 TClass* actualClass = 0;
1608 void** addr = (void**) addobj;
1609 if (addr && *addr) {
1610 actualClass = ptrClass->GetActualClass(*addr);
1611 if (!actualClass) {
1612 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",
1613 branchname, ptrClass->GetName());
1614 actualClass = ptrClass;
1615 } else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
1616 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());
1617 return 0;
1618 }
1619 } else {
1620 actualClass = ptrClass;
1621 }
1622 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1623 Error("Branch", writeStlWithoutProxyMsg,
1624 actualClass->GetName(), branchname, actualClass->GetName());
1625 return 0;
1626 }
1627 return Branch(branchname, actualClass->GetName(), (void*) addobj, bufsize, splitlevel);
1628}
1629
1630////////////////////////////////////////////////////////////////////////////////
1631/// Same as TTree::Branch but automatic detection of the class name.
1632/// \see TTree::Branch for other details.
1634TBranch* TTree::BranchImpRef(const char* branchname, const char *classname, TClass* ptrClass, void *addobj, Int_t bufsize, Int_t splitlevel)
1635{
1636 TClass* claim = TClass::GetClass(classname);
1637 if (!ptrClass) {
1638 if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
1639 Error("Branch", writeStlWithoutProxyMsg,
1640 claim->GetName(), branchname, claim->GetName());
1641 return 0;
1642 } else if (claim == 0) {
1643 Error("Branch", "The pointer specified for %s is not of a class known to ROOT and %s is not a known class", branchname, classname);
1644 return 0;
1645 }
1646 ptrClass = claim;
1647 }
1648 TClass* actualClass = 0;
1649 if (!addobj) {
1650 Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
1651 return 0;
1652 }
1653 actualClass = ptrClass->GetActualClass(addobj);
1654 if (ptrClass && claim) {
1655 if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
1656 // Note we currently do not warn in case of splicing or over-expectation).
1657 if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
1658 // The type is the same according to the C++ type_info, we must be in the case of
1659 // a template of Double32_t. This is actually a correct case.
1660 } else {
1661 Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the object passed (%s)",
1662 claim->GetName(), branchname, ptrClass->GetName());
1663 }
1664 } else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
1665 if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
1666 // The type is the same according to the C++ type_info, we must be in the case of
1667 // a template of Double32_t. This is actually a correct case.
1668 } else {
1669 Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
1670 actualClass->GetName(), branchname, claim->GetName());
1671 }
1672 }
1673 }
1674 if (!actualClass) {
1675 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",
1676 branchname, ptrClass->GetName());
1677 actualClass = ptrClass;
1678 } else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
1679 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());
1680 return 0;
1681 }
1682 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1683 Error("Branch", writeStlWithoutProxyMsg,
1684 actualClass->GetName(), branchname, actualClass->GetName());
1685 return 0;
1686 }
1687 return BronchExec(branchname, actualClass->GetName(), (void*) addobj, kFALSE, bufsize, splitlevel);
1688}
1689
1690////////////////////////////////////////////////////////////////////////////////
1691/// Same as TTree::Branch but automatic detection of the class name.
1692/// \see TTree::Branch for other details.
1694TBranch* TTree::BranchImpRef(const char* branchname, TClass* ptrClass, EDataType datatype, void* addobj, Int_t bufsize, Int_t splitlevel)
1695{
1696 if (!ptrClass) {
1697 if (datatype == kOther_t || datatype == kNoType_t) {
1698 Error("Branch", "The pointer specified for %s is not of a class or type known to ROOT", branchname);
1699 } else {
1700 TString varname; varname.Form("%s/%c",branchname,DataTypeToChar(datatype));
1701 return Branch(branchname,addobj,varname.Data(),bufsize);
1702 }
1703 return 0;
1704 }
1705 TClass* actualClass = 0;
1706 if (!addobj) {
1707 Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
1708 return 0;
1709 }
1710 actualClass = ptrClass->GetActualClass(addobj);
1711 if (!actualClass) {
1712 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",
1713 branchname, ptrClass->GetName());
1714 actualClass = ptrClass;
1715 } else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
1716 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());
1717 return 0;
1718 }
1719 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1720 Error("Branch", writeStlWithoutProxyMsg,
1721 actualClass->GetName(), branchname, actualClass->GetName());
1722 return 0;
1723 }
1724 return BronchExec(branchname, actualClass->GetName(), (void*) addobj, kFALSE, bufsize, splitlevel);
1725}
1726
1727////////////////////////////////////////////////////////////////////////////////
1728// Wrapper to turn Branch call with an std::array into the relevant leaf list
1729// call
1730TBranch *TTree::BranchImpArr(const char *branchname, EDataType datatype, std::size_t N, void *addobj, Int_t bufsize,
1731 Int_t /* splitlevel */)
1732{
1733 if (datatype == kOther_t || datatype == kNoType_t) {
1734 Error("Branch",
1735 "The inner type of the std::array passed specified for %s is not of a class or type known to ROOT",
1736 branchname);
1737 } else {
1738 TString varname;
1739 varname.Form("%s[%d]/%c", branchname, (int)N, DataTypeToChar(datatype));
1740 return Branch(branchname, addobj, varname.Data(), bufsize);
1741 }
1742 return nullptr;
1743}
1744
1745////////////////////////////////////////////////////////////////////////////////
1746/// Deprecated function. Use next function instead.
1748Int_t TTree::Branch(TList* li, Int_t bufsize /* = 32000 */ , Int_t splitlevel /* = 99 */)
1749{
1750 return Branch((TCollection*) li, bufsize, splitlevel);
1751}
1752
1753////////////////////////////////////////////////////////////////////////////////
1754/// Create one branch for each element in the collection.
1755///
1756/// Each entry in the collection becomes a top level branch if the
1757/// corresponding class is not a collection. If it is a collection, the entry
1758/// in the collection becomes in turn top level branches, etc.
1759/// The splitlevel is decreased by 1 every time a new collection is found.
1760/// For example if list is a TObjArray*
1761/// - if splitlevel = 1, one top level branch is created for each element
1762/// of the TObjArray.
1763/// - if splitlevel = 2, one top level branch is created for each array element.
1764/// if, in turn, one of the array elements is a TCollection, one top level
1765/// branch will be created for each element of this collection.
1766///
1767/// In case a collection element is a TClonesArray, the special Tree constructor
1768/// for TClonesArray is called.
1769/// The collection itself cannot be a TClonesArray.
1770///
1771/// The function returns the total number of branches created.
1772///
1773/// If name is given, all branch names will be prefixed with name_.
1774///
1775/// IMPORTANT NOTE1: This function should not be called with splitlevel < 1.
1776///
1777/// IMPORTANT NOTE2: The branches created by this function will have names
1778/// corresponding to the collection or object names. It is important
1779/// to give names to collections to avoid misleading branch names or
1780/// identical branch names. By default collections have a name equal to
1781/// the corresponding class name, e.g. the default name for a TList is "TList".
1782///
1783/// And in general, in case two or more master branches contain subbranches
1784/// with identical names, one must add a "." (dot) character at the end
1785/// of the master branch name. This will force the name of the subbranches
1786/// to be of the form `master.subbranch` instead of simply `subbranch`.
1787/// This situation happens when the top level object
1788/// has two or more members referencing the same class.
1789/// For example, if a Tree has two branches B1 and B2 corresponding
1790/// to objects of the same class MyClass, one can do:
1791/// ~~~ {.cpp}
1792/// tree.Branch("B1.","MyClass",&b1,8000,1);
1793/// tree.Branch("B2.","MyClass",&b2,8000,1);
1794/// ~~~
1795/// if MyClass has 3 members a,b,c, the two instructions above will generate
1796/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
1797///
1798/// Example:
1799/// ~~~ {.cpp}
1800/// {
1801/// TTree T("T","test list");
1802/// TList *list = new TList();
1803///
1804/// TObjArray *a1 = new TObjArray();
1805/// a1->SetName("a1");
1806/// list->Add(a1);
1807/// TH1F *ha1a = new TH1F("ha1a","ha1",100,0,1);
1808/// TH1F *ha1b = new TH1F("ha1b","ha1",100,0,1);
1809/// a1->Add(ha1a);
1810/// a1->Add(ha1b);
1811/// TObjArray *b1 = new TObjArray();
1812/// b1->SetName("b1");
1813/// list->Add(b1);
1814/// TH1F *hb1a = new TH1F("hb1a","hb1",100,0,1);
1815/// TH1F *hb1b = new TH1F("hb1b","hb1",100,0,1);
1816/// b1->Add(hb1a);
1817/// b1->Add(hb1b);
1818///
1819/// TObjArray *a2 = new TObjArray();
1820/// a2->SetName("a2");
1821/// list->Add(a2);
1822/// TH1S *ha2a = new TH1S("ha2a","ha2",100,0,1);
1823/// TH1S *ha2b = new TH1S("ha2b","ha2",100,0,1);
1824/// a2->Add(ha2a);
1825/// a2->Add(ha2b);
1826///
1827/// T.Branch(list,16000,2);
1828/// T.Print();
1829/// }
1830/// ~~~
1832Int_t TTree::Branch(TCollection* li, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */, const char* name /* = "" */)
1833{
1834
1835 if (!li) {
1836 return 0;
1837 }
1838 TObject* obj = 0;
1839 Int_t nbranches = GetListOfBranches()->GetEntries();
1840 if (li->InheritsFrom(TClonesArray::Class())) {
1841 Error("Branch", "Cannot call this constructor for a TClonesArray");
1842 return 0;
1843 }
1844 Int_t nch = strlen(name);
1845 TString branchname;
1846 TIter next(li);
1847 while ((obj = next())) {
1848 if ((splitlevel > 1) && obj->InheritsFrom(TCollection::Class()) && !obj->InheritsFrom(TClonesArray::Class())) {
1849 TCollection* col = (TCollection*) obj;
1850 if (nch) {
1851 branchname.Form("%s_%s_", name, col->GetName());
1852 } else {
1853 branchname.Form("%s_", col->GetName());
1854 }
1855 Branch(col, bufsize, splitlevel - 1, branchname);
1856 } else {
1857 if (nch && (name[nch-1] == '_')) {
1858 branchname.Form("%s%s", name, obj->GetName());
1859 } else {
1860 if (nch) {
1861 branchname.Form("%s_%s", name, obj->GetName());
1862 } else {
1863 branchname.Form("%s", obj->GetName());
1864 }
1865 }
1866 if (splitlevel > 99) {
1867 branchname += ".";
1868 }
1869 Bronch(branchname, obj->ClassName(), li->GetObjectRef(obj), bufsize, splitlevel - 1);
1870 }
1871 }
1872 return GetListOfBranches()->GetEntries() - nbranches;
1873}
1874
1875////////////////////////////////////////////////////////////////////////////////
1876/// Create one branch for each element in the folder.
1877/// Returns the total number of branches created.
1879Int_t TTree::Branch(const char* foldername, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
1880{
1881 TObject* ob = gROOT->FindObjectAny(foldername);
1882 if (!ob) {
1883 return 0;
1884 }
1885 if (ob->IsA() != TFolder::Class()) {
1886 return 0;
1887 }
1888 Int_t nbranches = GetListOfBranches()->GetEntries();
1889 TFolder* folder = (TFolder*) ob;
1890 TIter next(folder->GetListOfFolders());
1891 TObject* obj = 0;
1892 char* curname = new char[1000];
1893 char occur[20];
1894 while ((obj = next())) {
1895 snprintf(curname,1000, "%s/%s", foldername, obj->GetName());
1896 if (obj->IsA() == TFolder::Class()) {
1897 Branch(curname, bufsize, splitlevel - 1);
1898 } else {
1899 void* add = (void*) folder->GetListOfFolders()->GetObjectRef(obj);
1900 for (Int_t i = 0; i < 1000; ++i) {
1901 if (curname[i] == 0) {
1902 break;
1903 }
1904 if (curname[i] == '/') {
1905 curname[i] = '.';
1906 }
1907 }
1908 Int_t noccur = folder->Occurence(obj);
1909 if (noccur > 0) {
1910 snprintf(occur,20, "_%d", noccur);
1911 strlcat(curname, occur,1000);
1912 }
1913 TBranchElement* br = (TBranchElement*) Bronch(curname, obj->ClassName(), add, bufsize, splitlevel - 1);
1914 if (br) br->SetBranchFolder();
1915 }
1916 }
1917 delete[] curname;
1918 return GetListOfBranches()->GetEntries() - nbranches;
1919}
1920
1921////////////////////////////////////////////////////////////////////////////////
1922/// Create a new TTree Branch.
1923///
1924/// This Branch constructor is provided to support non-objects in
1925/// a Tree. The variables described in leaflist may be simple
1926/// variables or structures. // See the two following
1927/// constructors for writing objects in a Tree.
1928///
1929/// By default the branch buffers are stored in the same file as the Tree.
1930/// use TBranch::SetFile to specify a different file
1931///
1932/// * address is the address of the first item of a structure.
1933/// * leaflist is the concatenation of all the variable names and types
1934/// separated by a colon character :
1935/// The variable name and the variable type are separated by a slash (/).
1936/// The variable type may be 0,1 or 2 characters. If no type is given,
1937/// the type of the variable is assumed to be the same as the previous
1938/// variable. If the first variable does not have a type, it is assumed
1939/// of type F by default. The list of currently supported types is given below:
1940/// - `C` : a character string terminated by the 0 character
1941/// - `B` : an 8 bit signed integer (`Char_t`)
1942/// - `b` : an 8 bit unsigned integer (`UChar_t`)
1943/// - `S` : a 16 bit signed integer (`Short_t`)
1944/// - `s` : a 16 bit unsigned integer (`UShort_t`)
1945/// - `I` : a 32 bit signed integer (`Int_t`)
1946/// - `i` : a 32 bit unsigned integer (`UInt_t`)
1947/// - `F` : a 32 bit floating point (`Float_t`)
1948/// - `f` : a 24 bit floating point with truncated mantissa (`Float16_t`)
1949/// - `D` : a 64 bit floating point (`Double_t`)
1950/// - `d` : a 24 bit truncated floating point (`Double32_t`)
1951/// - `L` : a 64 bit signed integer (`Long64_t`)
1952/// - `l` : a 64 bit unsigned integer (`ULong64_t`)
1953/// - `G` : a long signed integer, stored as 64 bit (`Long_t`)
1954/// - `g` : a long unsigned integer, stored as 64 bit (`ULong_t`)
1955/// - `O` : [the letter `o`, not a zero] a boolean (`Bool_t`)
1956///
1957/// Arrays of values are supported with the following syntax:
1958/// - If leaf name has the form var[nelem], where nelem is alphanumeric, then
1959/// if nelem is a leaf name, it is used as the variable size of the array,
1960/// otherwise return 0.
1961/// - If leaf name has the form var[nelem], where nelem is a non-negative integer, then
1962/// it is used as the fixed size of the array.
1963/// - If leaf name has the form of a multi-dimensional array (e.g. var[nelem][nelem2])
1964/// where nelem and nelem2 are non-negative integer) then
1965/// it is used as a 2 dimensional array of fixed size.
1966/// - In case of the truncated floating point types (Float16_t and Double32_t) you can
1967/// furthermore specify the range in the style [xmin,xmax] or [xmin,xmax,nbits] after
1968/// the type character. See `TStreamerElement::GetRange()` for further information.
1969///
1970/// Any of other form is not supported.
1971///
1972/// Note that the TTree will assume that all the item are contiguous in memory.
1973/// On some platform, this is not always true of the member of a struct or a class,
1974/// due to padding and alignment. Sorting your data member in order of decreasing
1975/// sizeof usually leads to their being contiguous in memory.
1976///
1977/// * bufsize is the buffer size in bytes for this branch
1978/// The default value is 32000 bytes and should be ok for most cases.
1979/// You can specify a larger value (e.g. 256000) if your Tree is not split
1980/// and each entry is large (Megabytes)
1981/// A small value for bufsize is optimum if you intend to access
1982/// the entries in the Tree randomly and your Tree is in split mode.
1984TBranch* TTree::Branch(const char* name, void* address, const char* leaflist, Int_t bufsize /* = 32000 */)
1985{
1986 TBranch* branch = new TBranch(this, name, address, leaflist, bufsize);
1987 if (branch->IsZombie()) {
1988 delete branch;
1989 branch = 0;
1990 return 0;
1991 }
1992 fBranches.Add(branch);
1993 return branch;
1994}
1995
1996////////////////////////////////////////////////////////////////////////////////
1997/// Create a new branch with the object of class classname at address addobj.
1998///
1999/// WARNING:
2000///
2001/// Starting with Root version 3.01, the Branch function uses the new style
2002/// branches (TBranchElement). To get the old behaviour, you can:
2003/// - call BranchOld or
2004/// - call TTree::SetBranchStyle(0)
2005///
2006/// Note that with the new style, classname does not need to derive from TObject.
2007/// It must derived from TObject if the branch style has been set to 0 (old)
2008///
2009/// Note: See the comments in TBranchElement::SetAddress() for a more
2010/// detailed discussion of the meaning of the addobj parameter in
2011/// the case of new-style branches.
2012///
2013/// Use splitlevel < 0 instead of splitlevel=0 when the class
2014/// has a custom Streamer
2015///
2016/// Note: if the split level is set to the default (99), TTree::Branch will
2017/// not issue a warning if the class can not be split.
2019TBranch* TTree::Branch(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
2020{
2021 if (fgBranchStyle == 1) {
2022 return Bronch(name, classname, addobj, bufsize, splitlevel);
2023 } else {
2024 if (splitlevel < 0) {
2025 splitlevel = 0;
2026 }
2027 return BranchOld(name, classname, addobj, bufsize, splitlevel);
2028 }
2029}
2030
2031////////////////////////////////////////////////////////////////////////////////
2032/// Create a new TTree BranchObject.
2033///
2034/// Build a TBranchObject for an object of class classname.
2035/// addobj is the address of a pointer to an object of class classname.
2036/// IMPORTANT: classname must derive from TObject.
2037/// The class dictionary must be available (ClassDef in class header).
2038///
2039/// This option requires access to the library where the corresponding class
2040/// is defined. Accessing one single data member in the object implies
2041/// reading the full object.
2042/// See the next Branch constructor for a more efficient storage
2043/// in case the entry consists of arrays of identical objects.
2044///
2045/// By default the branch buffers are stored in the same file as the Tree.
2046/// use TBranch::SetFile to specify a different file
2047///
2048/// IMPORTANT NOTE about branch names:
2049///
2050/// And in general, in case two or more master branches contain subbranches
2051/// with identical names, one must add a "." (dot) character at the end
2052/// of the master branch name. This will force the name of the subbranches
2053/// to be of the form `master.subbranch` instead of simply `subbranch`.
2054/// This situation happens when the top level object
2055/// has two or more members referencing the same class.
2056/// For example, if a Tree has two branches B1 and B2 corresponding
2057/// to objects of the same class MyClass, one can do:
2058/// ~~~ {.cpp}
2059/// tree.Branch("B1.","MyClass",&b1,8000,1);
2060/// tree.Branch("B2.","MyClass",&b2,8000,1);
2061/// ~~~
2062/// if MyClass has 3 members a,b,c, the two instructions above will generate
2063/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
2064///
2065/// bufsize is the buffer size in bytes for this branch
2066/// The default value is 32000 bytes and should be ok for most cases.
2067/// You can specify a larger value (e.g. 256000) if your Tree is not split
2068/// and each entry is large (Megabytes)
2069/// A small value for bufsize is optimum if you intend to access
2070/// the entries in the Tree randomly and your Tree is in split mode.
2072TBranch* TTree::BranchOld(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 1 */)
2073{
2074 TClass* cl = TClass::GetClass(classname);
2075 if (!cl) {
2076 Error("BranchOld", "Cannot find class: '%s'", classname);
2077 return 0;
2078 }
2079 if (!cl->IsTObject()) {
2080 if (fgBranchStyle == 0) {
2081 Fatal("BranchOld", "The requested class ('%s') does not inherit from TObject.\n"
2082 "\tfgBranchStyle is set to zero requesting by default to use BranchOld.\n"
2083 "\tIf this is intentional use Bronch instead of Branch or BranchOld.", classname);
2084 } else {
2085 Fatal("BranchOld", "The requested class ('%s') does not inherit from TObject.\n"
2086 "\tYou can not use BranchOld to store objects of this type.",classname);
2087 }
2088 return 0;
2089 }
2090 TBranch* branch = new TBranchObject(this, name, classname, addobj, bufsize, splitlevel);
2091 fBranches.Add(branch);
2092 if (!splitlevel) {
2093 return branch;
2094 }
2095 // We are going to fully split the class now.
2096 TObjArray* blist = branch->GetListOfBranches();
2097 const char* rdname = 0;
2098 const char* dname = 0;
2099 TString branchname;
2100 char** apointer = (char**) addobj;
2101 TObject* obj = (TObject*) *apointer;
2102 Bool_t delobj = kFALSE;
2103 if (!obj) {
2104 obj = (TObject*) cl->New();
2105 delobj = kTRUE;
2106 }
2107 // Build the StreamerInfo if first time for the class.
2108 BuildStreamerInfo(cl, obj);
2109 // Loop on all public data members of the class and its base classes.
2110 Int_t lenName = strlen(name);
2111 Int_t isDot = 0;
2112 if (name[lenName-1] == '.') {
2113 isDot = 1;
2114 }
2115 TBranch* branch1 = 0;
2116 TRealData* rd = 0;
2117 TRealData* rdi = 0;
2118 TIter nexti(cl->GetListOfRealData());
2119 TIter next(cl->GetListOfRealData());
2120 // Note: This loop results in a full split because the
2121 // real data list includes all data members of
2122 // data members.
2123 while ((rd = (TRealData*) next())) {
2124 if (rd->TestBit(TRealData::kTransient)) continue;
2125
2126 // Loop over all data members creating branches for each one.
2127 TDataMember* dm = rd->GetDataMember();
2128 if (!dm->IsPersistent()) {
2129 // Do not process members with an "!" as the first character in the comment field.
2130 continue;
2131 }
2132 if (rd->IsObject()) {
2133 // We skip data members of class type.
2134 // But we do build their real data, their
2135 // streamer info, and write their streamer
2136 // info to the current directory's file.
2137 // Oh yes, and we also do this for all of
2138 // their base classes.
2140 if (clm) {
2141 BuildStreamerInfo(clm, (char*) obj + rd->GetThisOffset());
2142 }
2143 continue;
2144 }
2145 rdname = rd->GetName();
2146 dname = dm->GetName();
2147 if (cl->CanIgnoreTObjectStreamer()) {
2148 // Skip the TObject base class data members.
2149 // FIXME: This prevents a user from ever
2150 // using these names themself!
2151 if (!strcmp(dname, "fBits")) {
2152 continue;
2153 }
2154 if (!strcmp(dname, "fUniqueID")) {
2155 continue;
2156 }
2157 }
2158 TDataType* dtype = dm->GetDataType();
2159 Int_t code = 0;
2160 if (dtype) {
2161 code = dm->GetDataType()->GetType();
2162 }
2163 // Encode branch name. Use real data member name
2164 branchname = rdname;
2165 if (isDot) {
2166 if (dm->IsaPointer()) {
2167 // FIXME: This is wrong! The asterisk is not usually in the front!
2168 branchname.Form("%s%s", name, &rdname[1]);
2169 } else {
2170 branchname.Form("%s%s", name, &rdname[0]);
2171 }
2172 }
2173 // FIXME: Change this to a string stream.
2174 TString leaflist;
2175 Int_t offset = rd->GetThisOffset();
2176 char* pointer = ((char*) obj) + offset;
2177 if (dm->IsaPointer()) {
2178 // We have a pointer to an object or a pointer to an array of basic types.
2179 TClass* clobj = 0;
2180 if (!dm->IsBasic()) {
2181 clobj = TClass::GetClass(dm->GetTypeName());
2182 }
2183 if (clobj && clobj->InheritsFrom(TClonesArray::Class())) {
2184 // We have a pointer to a clones array.
2185 char* cpointer = (char*) pointer;
2186 char** ppointer = (char**) cpointer;
2187 TClonesArray* li = (TClonesArray*) *ppointer;
2188 if (splitlevel != 2) {
2189 if (isDot) {
2190 branch1 = new TBranchClones(branch,branchname, pointer, bufsize);
2191 } else {
2192 // FIXME: This is wrong! The asterisk is not usually in the front!
2193 branch1 = new TBranchClones(branch,&branchname.Data()[1], pointer, bufsize);
2194 }
2195 blist->Add(branch1);
2196 } else {
2197 if (isDot) {
2198 branch1 = new TBranchObject(branch, branchname, li->ClassName(), pointer, bufsize);
2199 } else {
2200 // FIXME: This is wrong! The asterisk is not usually in the front!
2201 branch1 = new TBranchObject(branch, &branchname.Data()[1], li->ClassName(), pointer, bufsize);
2202 }
2203 blist->Add(branch1);
2204 }
2205 } else if (clobj) {
2206 // We have a pointer to an object.
2207 //
2208 // It must be a TObject object.
2209 if (!clobj->IsTObject()) {
2210 continue;
2211 }
2212 branch1 = new TBranchObject(branch, dname, clobj->GetName(), pointer, bufsize, 0);
2213 if (isDot) {
2214 branch1->SetName(branchname);
2215 } else {
2216 // FIXME: This is wrong! The asterisk is not usually in the front!
2217 // Do not use the first character (*).
2218 branch1->SetName(&branchname.Data()[1]);
2219 }
2220 blist->Add(branch1);
2221 } else {
2222 // We have a pointer to an array of basic types.
2223 //
2224 // Check the comments in the text of the code for an index specification.
2225 const char* index = dm->GetArrayIndex();
2226 if (index[0]) {
2227 // We are a pointer to a varying length array of basic types.
2228 //check that index is a valid data member name
2229 //if member is part of an object (e.g. fA and index=fN)
2230 //index must be changed from fN to fA.fN
2231 TString aindex (rd->GetName());
2232 Ssiz_t rdot = aindex.Last('.');
2233 if (rdot>=0) {
2234 aindex.Remove(rdot+1);
2235 aindex.Append(index);
2236 }
2237 nexti.Reset();
2238 while ((rdi = (TRealData*) nexti())) {
2239 if (rdi->TestBit(TRealData::kTransient)) continue;
2240
2241 if (!strcmp(rdi->GetName(), index)) {
2242 break;
2243 }
2244 if (!strcmp(rdi->GetName(), aindex)) {
2245 index = rdi->GetName();
2246 break;
2247 }
2248 }
2249
2250 char vcode = DataTypeToChar((EDataType)code);
2251 // Note that we differentiate between strings and
2252 // char array by the fact that there is NO specified
2253 // size for a string (see next if (code == 1)
2254
2255 if (vcode) {
2256 leaflist.Form("%s[%s]/%c", &rdname[0], index, vcode);
2257 } else {
2258 Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
2259 leaflist = "";
2260 }
2261 } else {
2262 // We are possibly a character string.
2263 if (code == 1) {
2264 // We are a character string.
2265 leaflist.Form("%s/%s", dname, "C");
2266 } else {
2267 // Invalid array specification.
2268 // FIXME: We need an error message here.
2269 continue;
2270 }
2271 }
2272 // There are '*' in both the branchname and leaflist, remove them.
2273 TString bname( branchname );
2274 bname.ReplaceAll("*","");
2275 leaflist.ReplaceAll("*","");
2276 // Add the branch to the tree and indicate that the address
2277 // is that of a pointer to be dereferenced before using.
2278 branch1 = new TBranch(branch, bname, *((void**) pointer), leaflist, bufsize);
2279 TLeaf* leaf = (TLeaf*) branch1->GetListOfLeaves()->At(0);
2281 leaf->SetAddress((void**) pointer);
2282 blist->Add(branch1);
2283 }
2284 } else if (dm->IsBasic()) {
2285 // We have a basic type.
2286
2287 char vcode = DataTypeToChar((EDataType)code);
2288 if (vcode) {
2289 leaflist.Form("%s/%c", rdname, vcode);
2290 } else {
2291 Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
2292 leaflist = "";
2293 }
2294 branch1 = new TBranch(branch, branchname, pointer, leaflist, bufsize);
2295 branch1->SetTitle(rdname);
2296 blist->Add(branch1);
2297 } else {
2298 // We have a class type.
2299 // Note: This cannot happen due to the rd->IsObject() test above.
2300 // FIXME: Put an error message here just in case.
2301 }
2302 if (branch1) {
2303 branch1->SetOffset(offset);
2304 } else {
2305 Warning("BranchOld", "Cannot process member: '%s'", rdname);
2306 }
2307 }
2308 if (delobj) {
2309 delete obj;
2310 obj = 0;
2311 }
2312 return branch;
2313}
2314
2315////////////////////////////////////////////////////////////////////////////////
2316/// Build the optional branch supporting the TRefTable.
2317/// This branch will keep all the information to find the branches
2318/// containing referenced objects.
2319///
2320/// At each Tree::Fill, the branch numbers containing the
2321/// referenced objects are saved to the TBranchRef basket.
2322/// When the Tree header is saved (via TTree::Write), the branch
2323/// is saved keeping the information with the pointers to the branches
2324/// having referenced objects.
2327{
2328 if (!fBranchRef) {
2329 fBranchRef = new TBranchRef(this);
2330 }
2331 return fBranchRef;
2332}
2333
2334////////////////////////////////////////////////////////////////////////////////
2335/// Create a new TTree BranchElement.
2336///
2337/// ## WARNING about this new function
2338///
2339/// This function is designed to replace the internal
2340/// implementation of the old TTree::Branch (whose implementation
2341/// has been moved to BranchOld).
2342///
2343/// NOTE: The 'Bronch' method supports only one possible calls
2344/// signature (where the object type has to be specified
2345/// explicitly and the address must be the address of a pointer).
2346/// For more flexibility use 'Branch'. Use Bronch only in (rare)
2347/// cases (likely to be legacy cases) where both the new and old
2348/// implementation of Branch needs to be used at the same time.
2349///
2350/// This function is far more powerful than the old Branch
2351/// function. It supports the full C++, including STL and has
2352/// the same behaviour in split or non-split mode. classname does
2353/// not have to derive from TObject. The function is based on
2354/// the new TStreamerInfo.
2355///
2356/// Build a TBranchElement for an object of class classname.
2357///
2358/// addr is the address of a pointer to an object of class
2359/// classname. The class dictionary must be available (ClassDef
2360/// in class header).
2361///
2362/// Note: See the comments in TBranchElement::SetAddress() for a more
2363/// detailed discussion of the meaning of the addr parameter.
2364///
2365/// This option requires access to the library where the
2366/// corresponding class is defined. Accessing one single data
2367/// member in the object implies reading the full object.
2368///
2369/// By default the branch buffers are stored in the same file as the Tree.
2370/// use TBranch::SetFile to specify a different file
2371///
2372/// IMPORTANT NOTE about branch names:
2373///
2374/// And in general, in case two or more master branches contain subbranches
2375/// with identical names, one must add a "." (dot) character at the end
2376/// of the master branch name. This will force the name of the subbranches
2377/// to be of the form `master.subbranch` instead of simply `subbranch`.
2378/// This situation happens when the top level object
2379/// has two or more members referencing the same class.
2380/// For example, if a Tree has two branches B1 and B2 corresponding
2381/// to objects of the same class MyClass, one can do:
2382/// ~~~ {.cpp}
2383/// tree.Branch("B1.","MyClass",&b1,8000,1);
2384/// tree.Branch("B2.","MyClass",&b2,8000,1);
2385/// ~~~
2386/// if MyClass has 3 members a,b,c, the two instructions above will generate
2387/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
2388///
2389/// bufsize is the buffer size in bytes for this branch
2390/// The default value is 32000 bytes and should be ok for most cases.
2391/// You can specify a larger value (e.g. 256000) if your Tree is not split
2392/// and each entry is large (Megabytes)
2393/// A small value for bufsize is optimum if you intend to access
2394/// the entries in the Tree randomly and your Tree is in split mode.
2395///
2396/// Use splitlevel < 0 instead of splitlevel=0 when the class
2397/// has a custom Streamer
2398///
2399/// Note: if the split level is set to the default (99), TTree::Branch will
2400/// not issue a warning if the class can not be split.
2402TBranch* TTree::Bronch(const char* name, const char* classname, void* addr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
2403{
2404 return BronchExec(name, classname, addr, kTRUE, bufsize, splitlevel);
2405}
2406
2407////////////////////////////////////////////////////////////////////////////////
2408/// Helper function implementing TTree::Bronch and TTree::Branch(const char *name, T &obj);
2410TBranch* TTree::BronchExec(const char* name, const char* classname, void* addr, Bool_t isptrptr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
2411{
2412 TClass* cl = TClass::GetClass(classname);
2413 if (!cl) {
2414 Error("Bronch", "Cannot find class:%s", classname);
2415 return 0;
2416 }
2417
2418 //if splitlevel <= 0 and class has a custom Streamer, we must create
2419 //a TBranchObject. We cannot assume that TClass::ReadBuffer is consistent
2420 //with the custom Streamer. The penalty is that one cannot process
2421 //this Tree without the class library containing the class.
2422
2423 char* objptr = 0;
2424 if (!isptrptr) {
2425 objptr = (char*)addr;
2426 } else if (addr) {
2427 objptr = *((char**) addr);
2428 }
2429
2430 if (cl == TClonesArray::Class()) {
2431 TClonesArray* clones = (TClonesArray*) objptr;
2432 if (!clones) {
2433 Error("Bronch", "Pointer to TClonesArray is null");
2434 return 0;
2435 }
2436 if (!clones->GetClass()) {
2437 Error("Bronch", "TClonesArray with no class defined in branch: %s", name);
2438 return 0;
2439 }
2440 if (!clones->GetClass()->HasDataMemberInfo()) {
2441 Error("Bronch", "TClonesArray with no dictionary defined in branch: %s", name);
2442 return 0;
2443 }
2444 bool hasCustomStreamer = clones->GetClass()->TestBit(TClass::kHasCustomStreamerMember);
2445 if (splitlevel > 0) {
2446 if (hasCustomStreamer)
2447 Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", clones->GetClass()->GetName());
2448 } else {
2449 if (hasCustomStreamer) clones->BypassStreamer(kFALSE);
2450 TBranchObject *branch = new TBranchObject(this,name,classname,addr,bufsize,0,/*compress=*/ -1,isptrptr);
2451 fBranches.Add(branch);
2452 return branch;
2453 }
2454 }
2455
2456 if (cl->GetCollectionProxy()) {
2458 //if (!collProxy) {
2459 // Error("Bronch", "%s is missing its CollectionProxy (for branch %s)", classname, name);
2460 //}
2461 TClass* inklass = collProxy->GetValueClass();
2462 if (!inklass && (collProxy->GetType() == 0)) {
2463 Error("Bronch", "%s with no class defined in branch: %s", classname, name);
2464 return 0;
2465 }
2466 if ((splitlevel > 0) && inklass && (inklass->GetCollectionProxy() == 0)) {
2468 if ((stl != ROOT::kSTLmap) && (stl != ROOT::kSTLmultimap)) {
2469 if (!inklass->HasDataMemberInfo()) {
2470 Error("Bronch", "Container with no dictionary defined in branch: %s", name);
2471 return 0;
2472 }
2474 Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", inklass->GetName());
2475 }
2476 }
2477 }
2478 //-------------------------------------------------------------------------
2479 // If the splitting switch is enabled, the split level is big enough and
2480 // the collection contains pointers we can split it
2481 //////////////////////////////////////////////////////////////////////////
2482
2483 TBranch *branch;
2484 if( splitlevel > kSplitCollectionOfPointers && collProxy->HasPointers() )
2485 branch = new TBranchSTL( this, name, collProxy, bufsize, splitlevel );
2486 else
2487 branch = new TBranchElement(this, name, collProxy, bufsize, splitlevel);
2488 fBranches.Add(branch);
2489 if (isptrptr) {
2490 branch->SetAddress(addr);
2491 } else {
2492 branch->SetObject(addr);
2493 }
2494 return branch;
2495 }
2496
2497 Bool_t hasCustomStreamer = kFALSE;
2498 if (!cl->HasDataMemberInfo() && !cl->GetCollectionProxy()) {
2499 Error("Bronch", "Cannot find dictionary for class: %s", classname);
2500 return 0;
2501 }
2502
2504 // Not an STL container and the linkdef file had a "-" after the class name.
2505 hasCustomStreamer = kTRUE;
2506 }
2507
2508 if (splitlevel < 0 || ((splitlevel == 0) && hasCustomStreamer && cl->IsTObject())) {
2509 TBranchObject* branch = new TBranchObject(this, name, classname, addr, bufsize, 0, /*compress=*/ ROOT::RCompressionSetting::EAlgorithm::kInherit, isptrptr);
2510 fBranches.Add(branch);
2511 return branch;
2512 }
2513
2514 if (cl == TClonesArray::Class()) {
2515 // Special case of TClonesArray.
2516 // No dummy object is created.
2517 // The streamer info is not rebuilt unoptimized.
2518 // No dummy top-level branch is created.
2519 // No splitting is attempted.
2520 TBranchElement* branch = new TBranchElement(this, name, (TClonesArray*) objptr, bufsize, splitlevel%kSplitCollectionOfPointers);
2521 fBranches.Add(branch);
2522 if (isptrptr) {
2523 branch->SetAddress(addr);
2524 } else {
2525 branch->SetObject(addr);
2526 }
2527 return branch;
2528 }
2529
2530 //
2531 // If we are not given an object to use as an i/o buffer
2532 // then create a temporary one which we will delete just
2533 // before returning.
2534 //
2535
2536 Bool_t delobj = kFALSE;
2537
2538 if (!objptr) {
2539 objptr = (char*) cl->New();
2540 delobj = kTRUE;
2541 }
2542
2543 //
2544 // Avoid splitting unsplittable classes.
2545 //
2546
2547 if ((splitlevel > 0) && !cl->CanSplit()) {
2548 if (splitlevel != 99) {
2549 Warning("Bronch", "%s cannot be split, resetting splitlevel to 0", cl->GetName());
2550 }
2551 splitlevel = 0;
2552 }
2553
2554 //
2555 // Make sure the streamer info is built and fetch it.
2556 //
2557 // If we are splitting, then make sure the streamer info
2558 // is built unoptimized (data members are not combined).
2559 //
2560
2561 TStreamerInfo* sinfo = BuildStreamerInfo(cl, objptr, splitlevel==0);
2562 if (!sinfo) {
2563 Error("Bronch", "Cannot build the StreamerInfo for class: %s", cl->GetName());
2564 return 0;
2565 }
2566
2567 //
2568 // Create a dummy top level branch object.
2569 //
2570
2571 Int_t id = -1;
2572 if (splitlevel > 0) {
2573 id = -2;
2574 }
2575 TBranchElement* branch = new TBranchElement(this, name, sinfo, id, objptr, bufsize, splitlevel);
2576 fBranches.Add(branch);
2577
2578 //
2579 // Do splitting, if requested.
2580 //
2581
2582 if (splitlevel%kSplitCollectionOfPointers > 0) {
2583 branch->Unroll(name, cl, sinfo, objptr, bufsize, splitlevel);
2584 }
2585
2586 //
2587 // Setup our offsets into the user's i/o buffer.
2588 //
2589
2590 if (isptrptr) {
2591 branch->SetAddress(addr);
2592 } else {
2593 branch->SetObject(addr);
2594 }
2595
2596 if (delobj) {
2597 cl->Destructor(objptr);
2598 objptr = 0;
2599 }
2600
2601 return branch;
2602}
2603
2604////////////////////////////////////////////////////////////////////////////////
2605/// Browse content of the TTree.
2608{
2610 if (fUserInfo) {
2611 if (strcmp("TList",fUserInfo->GetName())==0) {
2612 fUserInfo->SetName("UserInfo");
2613 b->Add(fUserInfo);
2614 fUserInfo->SetName("TList");
2615 } else {
2616 b->Add(fUserInfo);
2617 }
2618 }
2619}
2620
2621////////////////////////////////////////////////////////////////////////////////
2622/// Build a Tree Index (default is TTreeIndex).
2623/// See a description of the parameters and functionality in
2624/// TTreeIndex::TTreeIndex().
2625///
2626/// The return value is the number of entries in the Index (< 0 indicates failure).
2627///
2628/// A TTreeIndex object pointed by fTreeIndex is created.
2629/// This object will be automatically deleted by the TTree destructor.
2630/// If an index is already existing, this is replaced by the new one without being
2631/// deleted. This behaviour prevents the deletion of a previously external index
2632/// assigned to the TTree via the TTree::SetTreeIndex() method.
2633/// \see also comments in TTree::SetTreeIndex().
2635Int_t TTree::BuildIndex(const char* majorname, const char* minorname /* = "0" */)
2636{
2637 fTreeIndex = GetPlayer()->BuildIndex(this, majorname, minorname);
2638 if (fTreeIndex->IsZombie()) {
2639 delete fTreeIndex;
2640 fTreeIndex = 0;
2641 return 0;
2642 }
2643 return fTreeIndex->GetN();
2644}
2645
2646////////////////////////////////////////////////////////////////////////////////
2647/// Build StreamerInfo for class cl.
2648/// pointer is an optional argument that may contain a pointer to an object of cl.
2650TStreamerInfo* TTree::BuildStreamerInfo(TClass* cl, void* pointer /* = 0 */, Bool_t canOptimize /* = kTRUE */ )
2651{
2652 if (!cl) {
2653 return 0;
2654 }
2655 cl->BuildRealData(pointer);
2657
2658 // Create StreamerInfo for all base classes.
2659 TBaseClass* base = 0;
2660 TIter nextb(cl->GetListOfBases());
2661 while((base = (TBaseClass*) nextb())) {
2662 if (base->IsSTLContainer()) {
2663 continue;
2664 }
2665 TClass* clm = TClass::GetClass(base->GetName());
2666 BuildStreamerInfo(clm, pointer, canOptimize);
2667 }
2668 if (sinfo && fDirectory) {
2670 }
2671 return sinfo;
2672}
2673
2674////////////////////////////////////////////////////////////////////////////////
2675/// Enable the TTreeCache unless explicitly disabled for this TTree by
2676/// a prior call to `SetCacheSize(0)`.
2677/// If the environment variable `ROOT_TTREECACHE_SIZE` or the rootrc config
2678/// `TTreeCache.Size` has been set to zero, this call will over-ride them with
2679/// a value of 1.0 (i.e. use a cache size to hold 1 cluster)
2680///
2681/// Return true if there is a cache attached to the `TTree` (either pre-exisiting
2682/// or created as part of this call)
2684{
2686 if (!file)
2687 return kFALSE;
2688 // Check for an existing cache
2690 if (pf)
2691 return kTRUE;
2692 if (fCacheUserSet && fCacheSize == 0)
2693 return kFALSE;
2694 return (0 == SetCacheSizeAux(kTRUE, -1));
2695}
2696
2697////////////////////////////////////////////////////////////////////////////////
2698/// Called by TTree::Fill() when file has reached its maximum fgMaxTreeSize.
2699/// Create a new file. If the original file is named "myfile.root",
2700/// subsequent files are named "myfile_1.root", "myfile_2.root", etc.
2701///
2702/// Returns a pointer to the new file.
2703///
2704/// Currently, the automatic change of file is restricted
2705/// to the case where the tree is in the top level directory.
2706/// The file should not contain sub-directories.
2707///
2708/// Before switching to a new file, the tree header is written
2709/// to the current file, then the current file is closed.
2710///
2711/// To process the multiple files created by ChangeFile, one must use
2712/// a TChain.
2713///
2714/// The new file name has a suffix "_N" where N is equal to fFileNumber+1.
2715/// By default a Root session starts with fFileNumber=0. One can set
2716/// fFileNumber to a different value via TTree::SetFileNumber.
2717/// In case a file named "_N" already exists, the function will try
2718/// a file named "__N", then "___N", etc.
2719///
2720/// fgMaxTreeSize can be set via the static function TTree::SetMaxTreeSize.
2721/// The default value of fgMaxTreeSize is 100 Gigabytes.
2722///
2723/// If the current file contains other objects like TH1 and TTree,
2724/// these objects are automatically moved to the new file.
2725///
2726/// \warning Be careful when writing the final Tree header to the file!
2727/// Don't do:
2728/// ~~~ {.cpp}
2729/// TFile *file = new TFile("myfile.root","recreate");
2730/// TTree *T = new TTree("T","title");
2731/// T->Fill(); // Loop
2732/// file->Write();
2733/// file->Close();
2734/// ~~~
2735/// \warning but do the following:
2736/// ~~~ {.cpp}
2737/// TFile *file = new TFile("myfile.root","recreate");
2738/// TTree *T = new TTree("T","title");
2739/// T->Fill(); // Loop
2740/// file = T->GetCurrentFile(); // To get the pointer to the current file
2741/// file->Write();
2742/// file->Close();
2743/// ~~~
2744///
2745/// \note This method is never called if the input file is a `TMemFile` or derivate.
2748{
2749 file->cd();
2750 Write();
2751 Reset();
2752 constexpr auto kBufSize = 2000;
2753 char* fname = new char[kBufSize];
2754 ++fFileNumber;
2755 char uscore[10];
2756 for (Int_t i = 0; i < 10; ++i) {
2757 uscore[i] = 0;
2758 }
2759 Int_t nus = 0;
2760 // Try to find a suitable file name that does not already exist.
2761 while (nus < 10) {
2762 uscore[nus] = '_';
2763 fname[0] = 0;
2764 strlcpy(fname, file->GetName(), kBufSize);
2765
2766 if (fFileNumber > 1) {
2767 char* cunder = strrchr(fname, '_');
2768 if (cunder) {
2769 snprintf(cunder, kBufSize - Int_t(cunder - fname), "%s%d", uscore, fFileNumber);
2770 const char* cdot = strrchr(file->GetName(), '.');
2771 if (cdot) {
2772 strlcat(fname, cdot, kBufSize);
2773 }
2774 } else {
2775 char fcount[21];
2776 snprintf(fcount,21, "%s%d", uscore, fFileNumber);
2777 strlcat(fname, fcount, kBufSize);
2778 }
2779 } else {
2780 char* cdot = strrchr(fname, '.');
2781 if (cdot) {
2782 snprintf(cdot, kBufSize - Int_t(fname-cdot), "%s%d", uscore, fFileNumber);
2783 strlcat(fname, strrchr(file->GetName(), '.'), kBufSize);
2784 } else {
2785 char fcount[21];
2786 snprintf(fcount,21, "%s%d", uscore, fFileNumber);
2787 strlcat(fname, fcount, kBufSize);
2788 }
2789 }
2790 if (gSystem->AccessPathName(fname)) {
2791 break;
2792 }
2793 ++nus;
2794 Warning("ChangeFile", "file %s already exist, trying with %d underscores", fname, nus+1);
2795 }
2796 Int_t compress = file->GetCompressionSettings();
2797 TFile* newfile = TFile::Open(fname, "recreate", "chain files", compress);
2798 if (newfile == 0) {
2799 Error("Fill","Failed to open new file %s, continuing as a memory tree.",fname);
2800 } else {
2801 Printf("Fill: Switching to new file: %s", fname);
2802 }
2803 // The current directory may contain histograms and trees.
2804 // These objects must be moved to the new file.
2805 TBranch* branch = 0;
2806 TObject* obj = 0;
2807 while ((obj = file->GetList()->First())) {
2808 file->Remove(obj);
2809 // Histogram: just change the directory.
2810 if (obj->InheritsFrom("TH1")) {
2811 gROOT->ProcessLine(TString::Format("((%s*)0x%zx)->SetDirectory((TDirectory*)0x%zx);", obj->ClassName(), (size_t) obj, (size_t) newfile));
2812 continue;
2813 }
2814 // Tree: must save all trees in the old file, reset them.
2815 if (obj->InheritsFrom(TTree::Class())) {
2816 TTree* t = (TTree*) obj;
2817 if (t != this) {
2818 t->AutoSave();
2819 t->Reset();
2821 }
2822 t->SetDirectory(newfile);
2823 TIter nextb(t->GetListOfBranches());
2824 while ((branch = (TBranch*)nextb())) {
2825 branch->SetFile(newfile);
2826 }
2827 if (t->GetBranchRef()) {
2828 t->GetBranchRef()->SetFile(newfile);
2829 }
2830 continue;
2831 }
2832 // Not a TH1 or a TTree, move object to new file.
2833 if (newfile) newfile->Append(obj);
2834 file->Remove(obj);
2835 }
2836 file->TObject::Delete();
2837 file = 0;
2838 delete[] fname;
2839 fname = 0;
2840 return newfile;
2841}
2842
2843////////////////////////////////////////////////////////////////////////////////
2844/// Check whether or not the address described by the last 3 parameters
2845/// matches the content of the branch. If a Data Model Evolution conversion
2846/// is involved, reset the fInfo of the branch.
2847/// The return values are:
2848//
2849/// - kMissingBranch (-5) : Missing branch
2850/// - kInternalError (-4) : Internal error (could not find the type corresponding to a data type number)
2851/// - kMissingCompiledCollectionProxy (-3) : Missing compiled collection proxy for a compiled collection
2852/// - kMismatch (-2) : Non-Class Pointer type given does not match the type expected by the branch
2853/// - kClassMismatch (-1) : Class Pointer type given does not match the type expected by the branch
2854/// - kMatch (0) : perfect match
2855/// - kMatchConversion (1) : match with (I/O) conversion
2856/// - kMatchConversionCollection (2) : match with (I/O) conversion of the content of a collection
2857/// - kMakeClass (3) : MakeClass mode so we can not check.
2858/// - kVoidPtr (4) : void* passed so no check was made.
2859/// - kNoCheck (5) : Underlying TBranch not yet available so no check was made.
2860/// In addition this can be multiplexed with the two bits:
2861/// - kNeedEnableDecomposedObj : in order for the address (type) to be 'usable' the branch needs to be in Decomposed Object (aka MakeClass) mode.
2862/// - kNeedDisableDecomposedObj : in order for the address (type) to be 'usable' the branch needs to not be in Decomposed Object (aka MakeClass) mode.
2863/// This bits can be masked out by using kDecomposedObjMask
2865Int_t TTree::CheckBranchAddressType(TBranch* branch, TClass* ptrClass, EDataType datatype, Bool_t isptr)
2866{
2867 if (GetMakeClass()) {
2868 // If we are in MakeClass mode so we do not really use classes.
2869 return kMakeClass;
2870 }
2871
2872 // Let's determine what we need!
2873 TClass* expectedClass = 0;
2874 EDataType expectedType = kOther_t;
2875 if (0 != branch->GetExpectedType(expectedClass,expectedType) ) {
2876 // Something went wrong, the warning message has already been issued.
2877 return kInternalError;
2878 }
2879 bool isBranchElement = branch->InheritsFrom( TBranchElement::Class() );
2880 if (expectedClass && datatype == kOther_t && ptrClass == 0) {
2881 if (isBranchElement) {
2882 TBranchElement* bEl = (TBranchElement*)branch;
2883 bEl->SetTargetClass( expectedClass->GetName() );
2884 }
2885 if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
2886 Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
2887 "The class expected (%s) refers to an stl collection and do not have a compiled CollectionProxy. "
2888 "Please generate the dictionary for this class (%s)",
2889 branch->GetName(), expectedClass->GetName(), expectedClass->GetName());
2891 }
2892 if (!expectedClass->IsLoaded()) {
2893 // The originally expected class does not have a dictionary, it is then plausible that the pointer being passed is the right type
2894 // (we really don't know). So let's express that.
2895 Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
2896 "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."
2897 "Please generate the dictionary for this class (%s)",
2898 branch->GetName(), expectedClass->GetName(), expectedClass->GetName());
2899 } else {
2900 Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
2901 "This is probably due to a missing dictionary, the original data class for this branch is %s.", branch->GetName(), expectedClass->GetName());
2902 }
2903 return kClassMismatch;
2904 }
2905 if (expectedClass && ptrClass && (branch->GetMother() == branch)) {
2906 // Top Level branch
2907 if (!isptr) {
2908 Error("SetBranchAddress", "The address for \"%s\" should be the address of a pointer!", branch->GetName());
2909 }
2910 }
2911 if (expectedType == kFloat16_t) {
2912 expectedType = kFloat_t;
2913 }
2914 if (expectedType == kDouble32_t) {
2915 expectedType = kDouble_t;
2916 }
2917 if (datatype == kFloat16_t) {
2918 datatype = kFloat_t;
2919 }
2920 if (datatype == kDouble32_t) {
2921 datatype = kDouble_t;
2922 }
2923
2924 /////////////////////////////////////////////////////////////////////////////
2925 // Deal with the class renaming
2926 /////////////////////////////////////////////////////////////////////////////
2927
2928 if( expectedClass && ptrClass &&
2929 expectedClass != ptrClass &&
2930 isBranchElement &&
2931 ptrClass->GetSchemaRules() &&
2932 ptrClass->GetSchemaRules()->HasRuleWithSourceClass( expectedClass->GetName() ) ) {
2933 TBranchElement* bEl = (TBranchElement*)branch;
2934
2935 if ( ptrClass->GetCollectionProxy() && expectedClass->GetCollectionProxy() ) {
2936 if (gDebug > 7)
2937 Info("SetBranchAddress", "Matching STL collection (at least according to the SchemaRuleSet when "
2938 "reading a %s into a %s",expectedClass->GetName(),ptrClass->GetName());
2939
2940 bEl->SetTargetClass( ptrClass->GetName() );
2941 return kMatchConversion;
2942
2943 } else if ( !ptrClass->GetConversionStreamerInfo( expectedClass, bEl->GetClassVersion() ) &&
2944 !ptrClass->FindConversionStreamerInfo( expectedClass, bEl->GetCheckSum() ) ) {
2945 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());
2946
2947 bEl->SetTargetClass( expectedClass->GetName() );
2948 return kClassMismatch;
2949 }
2950 else {
2951
2952 bEl->SetTargetClass( ptrClass->GetName() );
2953 return kMatchConversion;
2954 }
2955
2956 } else if (expectedClass && ptrClass && !expectedClass->InheritsFrom(ptrClass)) {
2957
2958 if (expectedClass->GetCollectionProxy() && ptrClass->GetCollectionProxy() &&
2959 isBranchElement &&
2960 expectedClass->GetCollectionProxy()->GetValueClass() &&
2961 ptrClass->GetCollectionProxy()->GetValueClass() )
2962 {
2963 // In case of collection, we know how to convert them, if we know how to convert their content.
2964 // NOTE: we need to extend this to std::pair ...
2965
2966 TClass *onfileValueClass = expectedClass->GetCollectionProxy()->GetValueClass();
2967 TClass *inmemValueClass = ptrClass->GetCollectionProxy()->GetValueClass();
2968
2969 if (inmemValueClass->GetSchemaRules() &&
2970 inmemValueClass->GetSchemaRules()->HasRuleWithSourceClass(onfileValueClass->GetName() ) )
2971 {
2972 TBranchElement* bEl = (TBranchElement*)branch;
2973 bEl->SetTargetClass( ptrClass->GetName() );
2975 }
2976 }
2977
2978 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());
2979 if (isBranchElement) {
2980 TBranchElement* bEl = (TBranchElement*)branch;
2981 bEl->SetTargetClass( expectedClass->GetName() );
2982 }
2983 return kClassMismatch;
2984
2985 } else if ((expectedType != kOther_t) && (datatype != kOther_t) && (expectedType != kNoType_t) && (datatype != kNoType_t) && (expectedType != datatype)) {
2986 if (datatype != kChar_t) {
2987 // For backward compatibility we assume that (char*) was just a cast and/or a generic address
2988 Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" (%d) by the branch: %s",
2989 TDataType::GetTypeName(datatype), datatype, TDataType::GetTypeName(expectedType), expectedType, branch->GetName());
2990 return kMismatch;
2991 }
2992 } else if ((expectedClass && (datatype != kOther_t && datatype != kNoType_t && datatype != kInt_t)) ||
2993 (ptrClass && (expectedType != kOther_t && expectedType != kNoType_t && datatype != kInt_t)) ) {
2994 // Sometime a null pointer can look an int, avoid complaining in that case.
2995 if (expectedClass) {
2996 Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" by the branch: %s",
2997 TDataType::GetTypeName(datatype), datatype, expectedClass->GetName(), branch->GetName());
2998 if (isBranchElement) {
2999 TBranchElement* bEl = (TBranchElement*)branch;
3000 bEl->SetTargetClass( expectedClass->GetName() );
3001 }
3002 } else {
3003 // 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
3004 // a struct).
3005 bool found = false;
3006 if (ptrClass->IsLoaded()) {
3007 TIter next(ptrClass->GetListOfRealData());
3008 TRealData *rdm;
3009 while ((rdm = (TRealData*)next())) {
3010 if (rdm->GetThisOffset() == 0) {
3011 TDataType *dmtype = rdm->GetDataMember()->GetDataType();
3012 if (dmtype) {
3013 EDataType etype = (EDataType)dmtype->GetType();
3014 if (etype == expectedType) {
3015 found = true;
3016 }
3017 }
3018 break;
3019 }
3020 }
3021 } else {
3022 TIter next(ptrClass->GetListOfDataMembers());
3023 TDataMember *dm;
3024 while ((dm = (TDataMember*)next())) {
3025 if (dm->GetOffset() == 0) {
3026 TDataType *dmtype = dm->GetDataType();
3027 if (dmtype) {
3028 EDataType etype = (EDataType)dmtype->GetType();
3029 if (etype == expectedType) {
3030 found = true;
3031 }
3032 }
3033 break;
3034 }
3035 }
3036 }
3037 if (found) {
3038 // let's check the size.
3039 TLeaf *last = (TLeaf*)branch->GetListOfLeaves()->Last();
3040 long len = last->GetOffset() + last->GetLenType() * last->GetLen();
3041 if (len <= ptrClass->Size()) {
3042 return kMatch;
3043 }
3044 }
3045 Error("SetBranchAddress", "The pointer type given \"%s\" does not correspond to the type needed \"%s\" (%d) by the branch: %s",
3046 ptrClass->GetName(), TDataType::GetTypeName(expectedType), expectedType, branch->GetName());
3047 }
3048 return kMismatch;
3049 }
3050 if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
3051 Error("SetBranchAddress", writeStlWithoutProxyMsg,
3052 expectedClass->GetName(), branch->GetName(), expectedClass->GetName());
3053 if (isBranchElement) {
3054 TBranchElement* bEl = (TBranchElement*)branch;
3055 bEl->SetTargetClass( expectedClass->GetName() );
3056 }
3058 }
3059 if (isBranchElement) {
3060 if (expectedClass) {
3061 TBranchElement* bEl = (TBranchElement*)branch;
3062 bEl->SetTargetClass( expectedClass->GetName() );
3063 } else if (expectedType != kNoType_t && expectedType != kOther_t) {
3065 }
3066 }
3067 return kMatch;
3068}
3069
3070////////////////////////////////////////////////////////////////////////////////
3071/// Create a clone of this tree and copy nentries.
3072///
3073/// By default copy all entries.
3074/// The compression level of the cloned tree is set to the destination
3075/// file's compression level.
3076///
3077/// NOTE: Only active branches are copied.
3078/// NOTE: If the TTree is a TChain, the structure of the first TTree
3079/// is used for the copy.
3080///
3081/// IMPORTANT: The cloned tree stays connected with this tree until
3082/// this tree is deleted. In particular, any changes in
3083/// branch addresses in this tree are forwarded to the
3084/// clone trees, unless a branch in a clone tree has had
3085/// its address changed, in which case that change stays in
3086/// effect. When this tree is deleted, all the addresses of
3087/// the cloned tree are reset to their default values.
3088///
3089/// If 'option' contains the word 'fast' and nentries is -1, the
3090/// cloning will be done without unzipping or unstreaming the baskets
3091/// (i.e., a direct copy of the raw bytes on disk).
3092///
3093/// When 'fast' is specified, 'option' can also contain a sorting
3094/// order for the baskets in the output file.
3095///
3096/// There are currently 3 supported sorting order:
3097///
3098/// - SortBasketsByOffset (the default)
3099/// - SortBasketsByBranch
3100/// - SortBasketsByEntry
3101///
3102/// When using SortBasketsByOffset the baskets are written in the
3103/// output file in the same order as in the original file (i.e. the
3104/// baskets are sorted by their offset in the original file; Usually
3105/// this also means that the baskets are sorted by the index/number of
3106/// the _last_ entry they contain)
3107///
3108/// When using SortBasketsByBranch all the baskets of each individual
3109/// branches are stored contiguously. This tends to optimize reading
3110/// speed when reading a small number (1->5) of branches, since all
3111/// their baskets will be clustered together instead of being spread
3112/// across the file. However it might decrease the performance when
3113/// reading more branches (or the full entry).
3114///
3115/// When using SortBasketsByEntry the baskets with the lowest starting
3116/// entry are written first. (i.e. the baskets are sorted by the
3117/// index/number of the first entry they contain). This means that on
3118/// the file the baskets will be in the order in which they will be
3119/// needed when reading the whole tree sequentially.
3120///
3121/// For examples of CloneTree, see tutorials:
3122///
3123/// - copytree.C:
3124/// A macro to copy a subset of a TTree to a new TTree.
3125/// The input file has been generated by the program in
3126/// $ROOTSYS/test/Event with: Event 1000 1 1 1
3127///
3128/// - copytree2.C:
3129/// A macro to copy a subset of a TTree to a new TTree.
3130/// One branch of the new Tree is written to a separate file.
3131/// The input file has been generated by the program in
3132/// $ROOTSYS/test/Event with: Event 1000 1 1 1
3134TTree* TTree::CloneTree(Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
3135{
3136 // Options
3137 Bool_t fastClone = kFALSE;
3138
3139 TString opt = option;
3140 opt.ToLower();
3141 if (opt.Contains("fast")) {
3142 fastClone = kTRUE;
3143 }
3144
3145 // If we are a chain, switch to the first tree.
3146 if ((fEntries > 0) && (LoadTree(0) < 0)) {
3147 // FIXME: We need an error message here.
3148 return 0;
3149 }
3150
3151 // Note: For a tree we get the this pointer, for
3152 // a chain we get the chain's current tree.
3153 TTree* thistree = GetTree();
3154
3155 // We will use this to override the IO features on the cloned branches.
3156 ROOT::TIOFeatures features = this->GetIOFeatures();
3157 ;
3158
3159 // Note: For a chain, the returned clone will be
3160 // a clone of the chain's first tree.
3161 TTree* newtree = (TTree*) thistree->Clone();
3162 if (!newtree) {
3163 return 0;
3164 }
3165
3166 // The clone should not delete any objects allocated by SetAddress().
3167 TObjArray* branches = newtree->GetListOfBranches();
3168 Int_t nb = branches->GetEntriesFast();
3169 for (Int_t i = 0; i < nb; ++i) {
3170 TBranch* br = (TBranch*) branches->UncheckedAt(i);
3172 ((TBranchElement*) br)->ResetDeleteObject();
3173 }
3174 }
3175
3176 // Add the new tree to the list of clones so that
3177 // we can later inform it of changes to branch addresses.
3178 thistree->AddClone(newtree);
3179 if (thistree != this) {
3180 // In case this object is a TChain, add the clone
3181 // also to the TChain's list of clones.
3182 AddClone(newtree);
3183 }
3184
3185 newtree->Reset();
3186
3187 TDirectory* ndir = newtree->GetDirectory();
3188 TFile* nfile = 0;
3189 if (ndir) {
3190 nfile = ndir->GetFile();
3191 }
3192 Int_t newcomp = -1;
3193 if (nfile) {
3194 newcomp = nfile->GetCompressionSettings();
3195 }
3196
3197 //
3198 // Delete non-active branches from the clone.
3199 //
3200 // Note: If we are a chain, this does nothing
3201 // since chains have no leaves.
3202 TObjArray* leaves = newtree->GetListOfLeaves();
3203 Int_t nleaves = leaves->GetEntriesFast();
3204 for (Int_t lndx = 0; lndx < nleaves; ++lndx) {
3205 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(lndx);
3206 if (!leaf) {
3207 continue;
3208 }
3209 TBranch* branch = leaf->GetBranch();
3210 if (branch && (newcomp > -1)) {
3211 branch->SetCompressionSettings(newcomp);
3212 }
3213 if (branch) branch->SetIOFeatures(features);
3214 if (!branch || !branch->TestBit(kDoNotProcess)) {
3215 continue;
3216 }
3217 // size might change at each iteration of the loop over the leaves.
3218 nb = branches->GetEntriesFast();
3219 for (Long64_t i = 0; i < nb; ++i) {
3220 TBranch* br = (TBranch*) branches->UncheckedAt(i);
3221 if (br == branch) {
3222 branches->RemoveAt(i);
3223 delete br;
3224 br = 0;
3225 branches->Compress();
3226 break;
3227 }
3228 TObjArray* lb = br->GetListOfBranches();
3229 Int_t nb1 = lb->GetEntriesFast();
3230 for (Int_t j = 0; j < nb1; ++j) {
3231 TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
3232 if (!b1) {
3233 continue;
3234 }
3235 if (b1 == branch) {
3236 lb->RemoveAt(j);
3237 delete b1;
3238 b1 = 0;
3239 lb->Compress();
3240 break;
3241 }
3242 TObjArray* lb1 = b1->GetListOfBranches();
3243 Int_t nb2 = lb1->GetEntriesFast();
3244 for (Int_t k = 0; k < nb2; ++k) {
3245 TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
3246 if (!b2) {
3247 continue;
3248 }
3249 if (b2 == branch) {
3250 lb1->RemoveAt(k);
3251 delete b2;
3252 b2 = 0;
3253 lb1->Compress();
3254 break;
3255 }
3256 }
3257 }
3258 }
3259 }
3260 leaves->Compress();
3261
3262 // Copy MakeClass status.
3263 newtree->SetMakeClass(fMakeClass);
3264
3265 // Copy branch addresses.
3266 CopyAddresses(newtree);
3267
3268 //
3269 // Copy entries if requested.
3270 //
3271
3272 if (nentries != 0) {
3273 if (fastClone && (nentries < 0)) {
3274 if ( newtree->CopyEntries( this, -1, option, kFALSE ) < 0 ) {
3275 // There was a problem!
3276 Error("CloneTTree", "TTree has not been cloned\n");
3277 delete newtree;
3278 newtree = 0;
3279 return 0;
3280 }
3281 } else {
3282 newtree->CopyEntries( this, nentries, option, kFALSE );
3283 }
3284 }
3285
3286 return newtree;
3287}
3288
3289////////////////////////////////////////////////////////////////////////////////
3290/// Set branch addresses of passed tree equal to ours.
3291/// If undo is true, reset the branch addresses instead of copying them.
3292/// This ensures 'separation' of a cloned tree from its original.
3295{
3296 // Copy branch addresses starting from branches.
3297 TObjArray* branches = GetListOfBranches();
3298 Int_t nbranches = branches->GetEntriesFast();
3299 for (Int_t i = 0; i < nbranches; ++i) {
3300 TBranch* branch = (TBranch*) branches->UncheckedAt(i);
3301 if (branch->TestBit(kDoNotProcess)) {
3302 continue;
3303 }
3304 if (undo) {
3305 TBranch* br = tree->GetBranch(branch->GetName());
3306 tree->ResetBranchAddress(br);
3307 } else {
3308 char* addr = branch->GetAddress();
3309 if (!addr) {
3310 if (branch->IsA() == TBranch::Class()) {
3311 // If the branch was created using a leaflist, the branch itself may not have
3312 // an address but the leaf might already.
3313 TLeaf *firstleaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
3314 if (!firstleaf || firstleaf->GetValuePointer()) {
3315 // Either there is no leaf (and thus no point in copying the address)
3316 // or the leaf has an address but we can not copy it via the branche
3317 // this will be copied via the next loop (over the leaf).
3318 continue;
3319 }
3320 }
3321 // Note: This may cause an object to be allocated.
3322 branch->SetAddress(0);
3323 addr = branch->GetAddress();
3324 }
3325 TBranch* br = tree->GetBranch(branch->GetFullName());
3326 if (br) {
3327 if (br->GetMakeClass() != branch->GetMakeClass())
3328 br->SetMakeClass(branch->GetMakeClass());
3329 br->SetAddress(addr);
3330 // The copy does not own any object allocated by SetAddress().
3332 ((TBranchElement*) br)->ResetDeleteObject();
3333 }
3334 } else {
3335 Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
3336 }
3337 }
3338 }
3339
3340 // Copy branch addresses starting from leaves.
3341 TObjArray* tleaves = tree->GetListOfLeaves();
3342 Int_t ntleaves = tleaves->GetEntriesFast();
3343 std::set<TLeaf*> updatedLeafCount;
3344 for (Int_t i = 0; i < ntleaves; ++i) {
3345 TLeaf* tleaf = (TLeaf*) tleaves->UncheckedAt(i);
3346 TBranch* tbranch = tleaf->GetBranch();
3347 TBranch* branch = GetBranch(tbranch->GetName());
3348 if (!branch) {
3349 continue;
3350 }
3351 TLeaf* leaf = branch->GetLeaf(tleaf->GetName());
3352 if (!leaf) {
3353 continue;
3354 }
3355 if (branch->TestBit(kDoNotProcess)) {
3356 continue;
3357 }
3358 if (undo) {
3359 // Now we know whether the address has been transfered
3360 tree->ResetBranchAddress(tbranch);
3361 } else {
3362 TBranchElement *mother = dynamic_cast<TBranchElement*>(leaf->GetBranch()->GetMother());
3363 bool needAddressReset = false;
3364 if (leaf->GetLeafCount() && (leaf->TestBit(TLeaf::kNewValue) || !leaf->GetValuePointer() || (mother && mother->IsObjectOwner())) && tleaf->GetLeafCount())
3365 {
3366 // If it is an array and it was allocated by the leaf itself,
3367 // let's make sure it is large enough for the incoming data.
3368 if (leaf->GetLeafCount()->GetMaximum() < tleaf->GetLeafCount()->GetMaximum()) {
3369 leaf->GetLeafCount()->IncludeRange( tleaf->GetLeafCount() );
3370 updatedLeafCount.insert(leaf->GetLeafCount());
3371 needAddressReset = true;
3372 } else {
3373 needAddressReset = (updatedLeafCount.find(leaf->GetLeafCount()) != updatedLeafCount.end());
3374 }
3375 }
3376 if (needAddressReset && leaf->GetValuePointer()) {
3377 if (leaf->IsA() == TLeafElement::Class() && mother)
3378 mother->ResetAddress();
3379 else
3380 leaf->SetAddress(nullptr);
3381 }
3382 if (!branch->GetAddress() && !leaf->GetValuePointer()) {
3383 // We should attempts to set the address of the branch.
3384 // something like:
3385 //(TBranchElement*)branch->GetMother()->SetAddress(0)
3386 //plus a few more subtleties (see TBranchElement::GetEntry).
3387 //but for now we go the simplest route:
3388 //
3389 // Note: This may result in the allocation of an object.
3390 branch->SetupAddresses();
3391 }
3392 if (branch->GetAddress()) {
3393 tree->SetBranchAddress(branch->GetName(), (void*) branch->GetAddress());
3394 TBranch* br = tree->GetBranch(branch->GetName());
3395 if (br) {
3396 if (br->IsA() != branch->IsA()) {
3397 Error(
3398 "CopyAddresses",
3399 "Branch kind mismatch between input tree '%s' and output tree '%s' for branch '%s': '%s' vs '%s'",
3400 tree->GetName(), br->GetTree()->GetName(), br->GetName(), branch->IsA()->GetName(),
3401 br->IsA()->GetName());
3402 }
3403 // The copy does not own any object allocated by SetAddress().
3404 // FIXME: We do too much here, br may not be a top-level branch.
3406 ((TBranchElement*) br)->ResetDeleteObject();
3407 }
3408 } else {
3409 Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
3410 }
3411 } else {
3412 tleaf->SetAddress(leaf->GetValuePointer());
3413 }
3414 }
3415 }
3416
3417 if (undo &&
3418 ( tree->IsA()->InheritsFrom("TNtuple") || tree->IsA()->InheritsFrom("TNtupleD") )
3419 ) {
3420 tree->ResetBranchAddresses();
3421 }
3422}
3423
3424namespace {
3425
3426 enum EOnIndexError { kDrop, kKeep, kBuild };
3427
3428 static Bool_t R__HandleIndex(EOnIndexError onIndexError, TTree *newtree, TTree *oldtree)
3429 {
3430 // Return true if we should continue to handle indices, false otherwise.
3431
3432 Bool_t withIndex = kTRUE;
3433
3434 if ( newtree->GetTreeIndex() ) {
3435 if ( oldtree->GetTree()->GetTreeIndex() == 0 ) {
3436 switch (onIndexError) {
3437 case kDrop:
3438 delete newtree->GetTreeIndex();
3439 newtree->SetTreeIndex(0);
3440 withIndex = kFALSE;
3441 break;
3442 case kKeep:
3443 // Nothing to do really.
3444 break;
3445 case kBuild:
3446 // Build the index then copy it
3447 if (oldtree->GetTree()->BuildIndex(newtree->GetTreeIndex()->GetMajorName(), newtree->GetTreeIndex()->GetMinorName())) {
3448 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
3449 // Clean up
3450 delete oldtree->GetTree()->GetTreeIndex();
3451 oldtree->GetTree()->SetTreeIndex(0);
3452 }
3453 break;
3454 }
3455 } else {
3456 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
3457 }
3458 } else if ( oldtree->GetTree()->GetTreeIndex() != 0 ) {
3459 // We discover the first index in the middle of the chain.
3460 switch (onIndexError) {
3461 case kDrop:
3462 // Nothing to do really.
3463 break;
3464 case kKeep: {
3466 index->SetTree(newtree);
3467 newtree->SetTreeIndex(index);
3468 break;
3469 }
3470 case kBuild:
3471 if (newtree->GetEntries() == 0) {
3472 // Start an index.
3474 index->SetTree(newtree);
3475 newtree->SetTreeIndex(index);
3476 } else {
3477 // Build the index so far.
3478 if (newtree->BuildIndex(oldtree->GetTree()->GetTreeIndex()->GetMajorName(), oldtree->GetTree()->GetTreeIndex()->GetMinorName())) {
3479 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), kTRUE);
3480 }
3481 }
3482 break;
3483 }
3484 } else if ( onIndexError == kDrop ) {
3485 // There is no index on this or on tree->GetTree(), we know we have to ignore any further
3486 // index
3487 withIndex = kFALSE;
3488 }
3489 return withIndex;
3490 }
3491}
3492
3493////////////////////////////////////////////////////////////////////////////////
3494/// Copy nentries from given tree to this tree.
3495/// This routines assumes that the branches that intended to be copied are
3496/// already connected. The typical case is that this tree was created using
3497/// tree->CloneTree(0).
3498///
3499/// By default copy all entries.
3500///
3501/// Returns number of bytes copied to this tree.
3502///
3503/// If 'option' contains the word 'fast' and nentries is -1, the cloning will be
3504/// done without unzipping or unstreaming the baskets (i.e., a direct copy of the
3505/// raw bytes on disk).
3506///
3507/// When 'fast' is specified, 'option' can also contains a sorting order for the
3508/// baskets in the output file.
3509///
3510/// There are currently 3 supported sorting order:
3511///
3512/// - SortBasketsByOffset (the default)
3513/// - SortBasketsByBranch
3514/// - SortBasketsByEntry
3515///
3516/// See TTree::CloneTree for a detailed explanation of the semantics of these 3 options.
3517///
3518/// If the tree or any of the underlying tree of the chain has an index, that index and any
3519/// index in the subsequent underlying TTree objects will be merged.
3520///
3521/// There are currently three 'options' to control this merging:
3522/// - NoIndex : all the TTreeIndex object are dropped.
3523/// - DropIndexOnError : if any of the underlying TTree object do no have a TTreeIndex,
3524/// they are all dropped.
3525/// - AsIsIndexOnError [default]: In case of missing TTreeIndex, the resulting TTree index has gaps.
3526/// - BuildIndexOnError : If any of the underlying TTree objects do not have a TTreeIndex,
3527/// all TTreeIndex are 'ignored' and the missing piece are rebuilt.
3529Long64_t TTree::CopyEntries(TTree* tree, Long64_t nentries /* = -1 */, Option_t* option /* = "" */, Bool_t needCopyAddresses /* = false */)
3530{
3531 if (!tree) {
3532 return 0;
3533 }
3534 // Options
3535 TString opt = option;
3536 opt.ToLower();
3537 Bool_t fastClone = opt.Contains("fast");
3538 Bool_t withIndex = !opt.Contains("noindex");
3539 EOnIndexError onIndexError;
3540 if (opt.Contains("asisindex")) {
3541 onIndexError = kKeep;
3542 } else if (opt.Contains("buildindex")) {
3543 onIndexError = kBuild;
3544 } else if (opt.Contains("dropindex")) {
3545 onIndexError = kDrop;
3546 } else {
3547 onIndexError = kBuild;
3548 }
3549 Ssiz_t cacheSizeLoc = opt.Index("cachesize=");
3550 Int_t cacheSize = -1;
3551 if (cacheSizeLoc != TString::kNPOS) {
3552 // If the parse faile, cacheSize stays at -1.
3553 Ssiz_t cacheSizeEnd = opt.Index(" ",cacheSizeLoc+10) - (cacheSizeLoc+10);
3554 TSubString cacheSizeStr( opt(cacheSizeLoc+10,cacheSizeEnd) );
3555 auto parseResult = ROOT::FromHumanReadableSize(cacheSizeStr,cacheSize);
3556 if (parseResult == ROOT::EFromHumanReadableSize::kParseFail) {
3557 Warning("CopyEntries","The cachesize option can not be parsed: %s. The default size will be used.",cacheSizeStr.String().Data());
3558 } else if (parseResult == ROOT::EFromHumanReadableSize::kOverflow) {
3559 double m;
3560 const char *munit = nullptr;
3561 ROOT::ToHumanReadableSize(std::numeric_limits<decltype(cacheSize)>::max(),false,&m,&munit);
3562
3563 Warning("CopyEntries","The cachesize option is too large: %s (%g%s max). The default size will be used.",cacheSizeStr.String().Data(),m,munit);
3564 }
3565 }
3566 if (gDebug > 0 && cacheSize != -1) Info("CopyEntries","Using Cache size: %d\n",cacheSize);
3567
3568 Long64_t nbytes = 0;
3569 Long64_t treeEntries = tree->GetEntriesFast();
3570 if (nentries < 0) {
3571 nentries = treeEntries;
3572 } else if (nentries > treeEntries) {
3573 nentries = treeEntries;
3574 }
3575
3576 if (fastClone && (nentries < 0 || nentries == tree->GetEntriesFast())) {
3577 // Quickly copy the basket without decompression and streaming.
3578 Long64_t totbytes = GetTotBytes();
3579 for (Long64_t i = 0; i < nentries; i += tree->GetTree()->GetEntries()) {
3580 if (tree->LoadTree(i) < 0) {
3581 break;
3582 }
3583 if ( withIndex ) {
3584 withIndex = R__HandleIndex( onIndexError, this, tree );
3585 }
3586 if (this->GetDirectory()) {
3587 TFile* file2 = this->GetDirectory()->GetFile();
3588 if (file2 && (file2->GetEND() > TTree::GetMaxTreeSize())) {
3589 if (this->GetDirectory() == (TDirectory*) file2) {
3590 this->ChangeFile(file2);
3591 }
3592 }
3593 }
3594 TTreeCloner cloner(tree->GetTree(), this, option, TTreeCloner::kNoWarnings);
3595 if (cloner.IsValid()) {
3596 this->SetEntries(this->GetEntries() + tree->GetTree()->GetEntries());
3597 if (cacheSize != -1) cloner.SetCacheSize(cacheSize);
3598 cloner.Exec();
3599 } else {
3600 if (i == 0) {
3601 Warning("CopyEntries","%s",cloner.GetWarning());
3602 // If the first cloning does not work, something is really wrong
3603 // (since apriori the source and target are exactly the same structure!)
3604 return -1;
3605 } else {
3606 if (cloner.NeedConversion()) {
3607 TTree *localtree = tree->GetTree();
3608 Long64_t tentries = localtree->GetEntries();
3609 if (needCopyAddresses) {
3610 // Copy MakeClass status.
3611 tree->SetMakeClass(fMakeClass);
3612 // Copy branch addresses.
3614 }
3615 for (Long64_t ii = 0; ii < tentries; ii++) {
3616 if (localtree->GetEntry(ii) <= 0) {
3617 break;
3618 }
3619 this->Fill();
3620 }
3621 if (needCopyAddresses)
3622 tree->ResetBranchAddresses();
3623 if (this->GetTreeIndex()) {
3624 this->GetTreeIndex()->Append(tree->GetTree()->GetTreeIndex(), kTRUE);
3625 }
3626 } else {
3627 Warning("CopyEntries","%s",cloner.GetWarning());
3628 if (tree->GetDirectory() && tree->GetDirectory()->GetFile()) {
3629 Warning("CopyEntries", "Skipped file %s\n", tree->GetDirectory()->GetFile()->GetName());
3630 } else {
3631 Warning("CopyEntries", "Skipped file number %d\n", tree->GetTreeNumber());
3632 }
3633 }
3634 }
3635 }
3636
3637 }
3638 if (this->GetTreeIndex()) {
3639 this->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
3640 }
3641 nbytes = GetTotBytes() - totbytes;
3642 } else {
3643 if (nentries < 0) {
3644 nentries = treeEntries;
3645 } else if (nentries > treeEntries) {
3646 nentries = treeEntries;
3647 }
3648 if (needCopyAddresses) {
3649 // Copy MakeClass status.
3650 tree->SetMakeClass(fMakeClass);
3651 // Copy branch addresses.
3653 }
3654 Int_t treenumber = -1;
3655 for (Long64_t i = 0; i < nentries; i++) {
3656 if (tree->LoadTree(i) < 0) {
3657 break;
3658 }
3659 if (treenumber != tree->GetTreeNumber()) {
3660 if ( withIndex ) {
3661 withIndex = R__HandleIndex( onIndexError, this, tree );
3662 }
3663 treenumber = tree->GetTreeNumber();
3664 }
3665 if (tree->GetEntry(i) <= 0) {
3666 break;
3667 }
3668 nbytes += this->Fill();
3669 }
3670 if (needCopyAddresses)
3671 tree->ResetBranchAddresses();
3672 if (this->GetTreeIndex()) {
3673 this->GetTreeIndex()->Append(0,kFALSE); // Force the sorting
3674 }
3675 }
3676 return nbytes;
3677}
3678
3679////////////////////////////////////////////////////////////////////////////////
3680/// Copy a tree with selection.
3681///
3682/// ### Important:
3683///
3684/// The returned copied tree stays connected with the original tree
3685/// until the original tree is deleted. In particular, any changes
3686/// to the branch addresses in the original tree are also made to
3687/// the copied tree. Any changes made to the branch addresses of the
3688/// copied tree are overridden anytime the original tree changes its
3689/// branch addresses. When the original tree is deleted, all the
3690/// branch addresses of the copied tree are set to zero.
3691///
3692/// For examples of CopyTree, see the tutorials:
3693///
3694/// - copytree.C:
3695/// Example macro to copy a subset of a tree to a new tree.
3696/// The input file was generated by running the program in
3697/// $ROOTSYS/test/Event in this way:
3698/// ~~~ {.cpp}
3699/// ./Event 1000 1 1 1
3700/// ~~~
3701/// - copytree2.C
3702/// Example macro to copy a subset of a tree to a new tree.
3703/// One branch of the new tree is written to a separate file.
3704/// The input file was generated by running the program in
3705/// $ROOTSYS/test/Event in this way:
3706/// ~~~ {.cpp}
3707/// ./Event 1000 1 1 1
3708/// ~~~
3709/// - copytree3.C
3710/// Example macro to copy a subset of a tree to a new tree.
3711/// Only selected entries are copied to the new tree.
3712/// NOTE that only the active branches are copied.
3714TTree* TTree::CopyTree(const char* selection, Option_t* option /* = 0 */, Long64_t nentries /* = TTree::kMaxEntries */, Long64_t firstentry /* = 0 */)
3715{
3716 GetPlayer();
3717 if (fPlayer) {
3718 return fPlayer->CopyTree(selection, option, nentries, firstentry);
3719 }
3720 return 0;
3721}
3722
3723////////////////////////////////////////////////////////////////////////////////
3724/// Create a basket for this tree and given branch.
3727{
3728 if (!branch) {
3729 return 0;
3730 }
3731 return new TBasket(branch->GetName(), GetName(), branch);
3732}
3733
3734////////////////////////////////////////////////////////////////////////////////
3735/// Delete this tree from memory or/and disk.
3736///
3737/// - if option == "all" delete Tree object from memory AND from disk
3738/// all baskets on disk are deleted. All keys with same name
3739/// are deleted.
3740/// - if option =="" only Tree object in memory is deleted.
3742void TTree::Delete(Option_t* option /* = "" */)
3743{
3745
3746 // delete all baskets and header from file
3747 if (file && option && !strcmp(option,"all")) {
3748 if (!file->IsWritable()) {
3749 Error("Delete","File : %s is not writable, cannot delete Tree:%s", file->GetName(),GetName());
3750 return;
3751 }
3752
3753 //find key and import Tree header in memory
3754 TKey *key = fDirectory->GetKey(GetName());
3755 if (!key) return;
3756
3757 TDirectory *dirsav = gDirectory;
3758 file->cd();
3759
3760 //get list of leaves and loop on all the branches baskets
3761 TIter next(GetListOfLeaves());
3762 TLeaf *leaf;
3763 char header[16];
3764 Int_t ntot = 0;
3765 Int_t nbask = 0;
3766 Int_t nbytes,objlen,keylen;
3767 while ((leaf = (TLeaf*)next())) {
3768 TBranch *branch = leaf->GetBranch();
3769 Int_t nbaskets = branch->GetMaxBaskets();
3770 for (Int_t i=0;i<nbaskets;i++) {
3771 Long64_t pos = branch->GetBasketSeek(i);
3772 if (!pos) continue;
3773 TFile *branchFile = branch->GetFile();
3774 if (!branchFile) continue;
3775 branchFile->GetRecordHeader(header,pos,16,nbytes,objlen,keylen);
3776 if (nbytes <= 0) continue;
3777 branchFile->MakeFree(pos,pos+nbytes-1);
3778 ntot += nbytes;
3779 nbask++;
3780 }
3781 }
3782
3783 // delete Tree header key and all keys with the same name
3784 // A Tree may have been saved many times. Previous cycles are invalid.
3785 while (key) {
3786 ntot += key->GetNbytes();
3787 key->Delete();
3788 delete key;
3789 key = fDirectory->GetKey(GetName());
3790 }
3791 if (dirsav) dirsav->cd();
3792 if (gDebug) Info("TTree::Delete", "Deleting Tree: %s: %d baskets deleted. Total space freed = %d bytes\n",GetName(),nbask,ntot);
3793 }
3794
3795 if (fDirectory) {
3796 fDirectory->Remove(this);
3797 //delete the file cache if it points to this Tree
3799 fDirectory = nullptr;
3801 }
3802
3803 // Delete object from CINT symbol table so it can not be used anymore.
3804 gCling->DeleteGlobal(this);
3805
3806 // Warning: We have intentional invalidated this object while inside a member function!
3807 delete this;
3808}
3809
3810 ///////////////////////////////////////////////////////////////////////////////
3811 /// Called by TKey and TObject::Clone to automatically add us to a directory
3812 /// when we are read from a file.
3815{
3816 if (fDirectory == dir) return;
3817 if (fDirectory) {
3818 fDirectory->Remove(this);
3819 // Delete or move the file cache if it points to this Tree
3821 MoveReadCache(file,dir);
3822 }
3823 fDirectory = dir;
3824 TBranch* b = 0;
3825 TIter next(GetListOfBranches());
3826 while((b = (TBranch*) next())) {
3827 b->UpdateFile();
3828 }
3829 if (fBranchRef) {
3831 }
3832 if (fDirectory) fDirectory->Append(this);
3833}
3834
3835////////////////////////////////////////////////////////////////////////////////
3836/// Draw expression varexp for specified entries.
3837///
3838/// \return -1 in case of error or number of selected events in case of success.
3839///
3840/// This function accepts TCut objects as arguments.
3841/// Useful to use the string operator +
3842///
3843/// Example:
3844///
3845/// ~~~ {.cpp}
3846/// ntuple.Draw("x",cut1+cut2+cut3);
3847/// ~~~
3848
3850Long64_t TTree::Draw(const char* varexp, const TCut& selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
3851{
3852 return TTree::Draw(varexp, selection.GetTitle(), option, nentries, firstentry);
3853}
3854
3855/////////////////////////////////////////////////////////////////////////////////////////
3856/// \brief Draw expression varexp for entries and objects that pass a (optional) selection.
3857///
3858/// \return -1 in case of error or number of selected events in case of success.
3859///
3860/// \param [in] varexp
3861/// \parblock
3862/// A string that takes one of these general forms:
3863/// - "e1" produces a 1-d histogram (TH1F) of expression "e1"
3864/// - "e1:e2" produces an unbinned 2-d scatter-plot (TGraph) of "e1"
3865/// on the y-axis versus "e2" on the x-axis
3866/// - "e1:e2:e3" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
3867/// vs "e2" vs "e3" on the z-, y-, x-axis, respectively
3868/// - "e1:e2:e3:e4" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
3869/// vs "e2" vs "e3" and "e4" mapped on the current color palette.
3870/// (to create histograms in the 2, 3, and 4 dimensional case,
3871/// see section "Saving the result of Draw to an histogram")
3872///
3873/// Examples:
3874/// - "x": the simplest case, it draws a 1-Dim histogram of column x
3875/// - "sqrt(x)", "x*y/z": draw histogram with the values of the specified numerical expression across TTree events
3876/// - "y:sqrt(x)": 2-Dim histogram of y versus sqrt(x)
3877/// - "px:py:pz:2.5*E": produces a 3-d scatter-plot of px vs py ps pz
3878/// and the color number of each marker will be 2.5*E.
3879/// If the color number is negative it is set to 0.
3880/// If the color number is greater than the current number of colors
3881/// it is set to the highest color number. The default number of
3882/// colors is 50. See TStyle::SetPalette for setting a new color palette.
3883///
3884/// The expressions can use all the operations and built-in functions
3885/// supported by TFormula (see TFormula::Analyze()), including free
3886/// functions taking numerical arguments (e.g. TMath::Bessel()).
3887/// In addition, you can call member functions taking numerical
3888/// arguments. For example, these are two valid expressions:
3889/// ~~~ {.cpp}
3890/// TMath::BreitWigner(fPx,3,2)
3891/// event.GetHistogram()->GetXaxis()->GetXmax()
3892/// ~~~
3893/// \endparblock
3894/// \param [in] selection
3895/// \parblock
3896/// A string containing a selection expression.
3897/// In a selection all usual C++ mathematical and logical operators are allowed.
3898/// The value corresponding to the selection expression is used as a weight
3899/// to fill the histogram (a weight of 0 is equivalent to not filling the histogram).\n
3900/// \n
3901/// Examples:
3902/// - "x<y && sqrt(z)>3.2": returns a weight = 0 or 1
3903/// - "(x+y)*(sqrt(z)>3.2)": returns a weight = x+y if sqrt(z)>3.2, 0 otherwise\n
3904/// \n
3905/// If the selection expression returns an array, it is iterated over in sync with the
3906/// array returned by the varexp argument (as described below in "Drawing expressions using arrays and array
3907/// elements"). For example, if, for a given event, varexp evaluates to
3908/// `{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:
3909/// ~~~{.cpp}
3910/// // Muon_pt is an array: fill a histogram with the array elements > 100 in each event
3911/// tree->Draw('Muon_pt', 'Muon_pt > 100')
3912/// ~~~
3913/// \endparblock
3914/// \param [in] option
3915/// \parblock
3916/// The drawing option.
3917/// - When an histogram is produced it can be any histogram drawing option
3918/// listed in THistPainter.
3919/// - when no option is specified:
3920/// - the default histogram drawing option is used
3921/// if the expression is of the form "e1".
3922/// - if the expression is of the form "e1:e2"or "e1:e2:e3" a cloud of
3923/// unbinned 2D or 3D points is drawn respectively.
3924/// - if the expression has four fields "e1:e2:e3:e4" a cloud of unbinned 3D
3925/// points is produced with e1 vs e2 vs e3, and e4 is mapped on the current color
3926/// palette.
3927/// - If option COL is specified when varexp has three fields:
3928/// ~~~ {.cpp}
3929/// tree.Draw("e1:e2:e3","","col");
3930/// ~~~
3931/// a 2D scatter is produced with e1 vs e2, and e3 is mapped on the current
3932/// color palette. The colors for e3 are evaluated once in linear scale before
3933/// painting. Therefore changing the pad to log scale along Z as no effect
3934/// on the colors.
3935/// - if expression has more than four fields the option "PARA"or "CANDLE"
3936/// can be used.
3937/// - If option contains the string "goff", no graphics is generated.
3938/// \endparblock
3939/// \param [in] nentries The number of entries to process (default is all)
3940/// \param [in] firstentry The first entry to process (default is 0)
3941///
3942/// ### Drawing expressions using arrays and array elements
3943///
3944/// Let assumes, a leaf fMatrix, on the branch fEvent, which is a 3 by 3 array,
3945/// or a TClonesArray.
3946/// In a TTree::Draw expression you can now access fMatrix using the following
3947/// syntaxes:
3948///
3949/// | String passed | What is used for each entry of the tree
3950/// |-----------------|--------------------------------------------------------|
3951/// | `fMatrix` | the 9 elements of fMatrix |
3952/// | `fMatrix[][]` | the 9 elements of fMatrix |
3953/// | `fMatrix[2][2]` | only the elements fMatrix[2][2] |
3954/// | `fMatrix[1]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
3955/// | `fMatrix[1][]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
3956/// | `fMatrix[][0]` | the 3 elements fMatrix[0][0], fMatrix[1][0] and fMatrix[2][0] |
3957///
3958/// "fEvent.fMatrix...." same as "fMatrix..." (unless there is more than one leaf named fMatrix!).
3959///
3960/// In summary, if a specific index is not specified for a dimension, TTree::Draw
3961/// will loop through all the indices along this dimension. Leaving off the
3962/// last (right most) dimension of specifying then with the two characters '[]'
3963/// is equivalent. For variable size arrays (and TClonesArray) the range
3964/// of the first dimension is recalculated for each entry of the tree.
3965/// You can also specify the index as an expression of any other variables from the
3966/// tree.
3967///
3968/// TTree::Draw also now properly handling operations involving 2 or more arrays.
3969///
3970/// Let assume a second matrix fResults[5][2], here are a sample of some
3971/// of the possible combinations, the number of elements they produce and
3972/// the loop used:
3973///
3974/// | expression | element(s) | Loop |
3975/// |----------------------------------|------------|--------------------------|
3976/// | `fMatrix[2][1] - fResults[5][2]` | one | no loop |
3977/// | `fMatrix[2][] - fResults[5][2]` | three | on 2nd dim fMatrix |
3978/// | `fMatrix[2][] - fResults[5][]` | two | on both 2nd dimensions |
3979/// | `fMatrix[][2] - fResults[][1]` | three | on both 1st dimensions |
3980/// | `fMatrix[][2] - fResults[][]` | six | on both 1st and 2nd dimensions of fResults |
3981/// | `fMatrix[][2] - fResults[3][]` | two | on 1st dim of fMatrix and 2nd of fResults (at the same time) |
3982/// | `fMatrix[][] - fResults[][]` | six | on 1st dim then on 2nd dim |
3983/// | `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.|
3984///
3985///
3986/// In summary, TTree::Draw loops through all unspecified dimensions. To
3987/// figure out the range of each loop, we match each unspecified dimension
3988/// from left to right (ignoring ALL dimensions for which an index has been
3989/// specified), in the equivalent loop matched dimensions use the same index
3990/// and are restricted to the smallest range (of only the matched dimensions).
3991/// When involving variable arrays, the range can of course be different
3992/// for each entry of the tree.
3993///
3994/// So the loop equivalent to "fMatrix[][2] - fResults[3][]" is:
3995/// ~~~ {.cpp}
3996/// for (Int_t i0; i < min(3,2); i++) {
3997/// use the value of (fMatrix[i0][2] - fMatrix[3][i0])
3998/// }
3999/// ~~~
4000/// So the loop equivalent to "fMatrix[][2] - fResults[][]" is:
4001/// ~~~ {.cpp}
4002/// for (Int_t i0; i < min(3,5); i++) {
4003/// for (Int_t i1; i1 < 2; i1++) {
4004/// use the value of (fMatrix[i0][2] - fMatrix[i0][i1])
4005/// }
4006/// }
4007/// ~~~
4008/// So the loop equivalent to "fMatrix[][] - fResults[][]" is:
4009/// ~~~ {.cpp}
4010/// for (Int_t i0; i < min(3,5); i++) {
4011/// for (Int_t i1; i1 < min(3,2); i1++) {
4012/// use the value of (fMatrix[i0][i1] - fMatrix[i0][i1])
4013/// }
4014/// }
4015/// ~~~
4016/// So the loop equivalent to "fMatrix[][fResults[][]]" is:
4017/// ~~~ {.cpp}
4018/// for (Int_t i0; i0 < 3; i0++) {
4019/// for (Int_t j2; j2 < 5; j2++) {
4020/// for (Int_t j3; j3 < 2; j3++) {
4021/// i1 = fResults[j2][j3];
4022/// use the value of fMatrix[i0][i1]
4023/// }
4024/// }
4025/// ~~~
4026/// ### Retrieving the result of Draw
4027///
4028/// By default a temporary histogram called `htemp` is created. It will be:
4029///
4030/// - A TH1F* in case of a mono-dimensional distribution: `Draw("e1")`,
4031/// - A TH2F* in case of a bi-dimensional distribution: `Draw("e1:e2")`,
4032/// - A TH3F* in case of a three-dimensional distribution: `Draw("e1:e2:e3")`.
4033///
4034/// In the one dimensional case the `htemp` is filled and drawn whatever the drawing
4035/// option is.
4036///
4037/// In the two and three dimensional cases, with the default drawing option (`""`),
4038/// a cloud of points is drawn and the histogram `htemp` is not filled. For all the other
4039/// drawing options `htemp` will be filled.
4040///
4041/// In all cases `htemp` can be retrieved by calling:
4042///
4043/// ~~~ {.cpp}
4044/// auto htemp = (TH1F*)gPad->GetPrimitive("htemp"); // 1D
4045/// auto htemp = (TH2F*)gPad->GetPrimitive("htemp"); // 2D
4046/// auto htemp = (TH3F*)gPad->GetPrimitive("htemp"); // 3D
4047/// ~~~
4048///
4049/// In the two dimensional case (`Draw("e1;e2")`), with the default drawing option, the
4050/// data is filled into a TGraph named `Graph`. This TGraph can be retrieved by
4051/// calling
4052///
4053/// ~~~ {.cpp}
4054/// auto graph = (TGraph*)gPad->GetPrimitive("Graph");
4055/// ~~~
4056///
4057/// For the three and four dimensional cases, with the default drawing option, an unnamed
4058/// TPolyMarker3D is produced, and therefore cannot be retrieved.
4059///
4060/// In all cases `htemp` can be used to access the axes. For instance in the 2D case:
4061///
4062/// ~~~ {.cpp}
4063/// auto htemp = (TH2F*)gPad->GetPrimitive("htemp");
4064/// auto xaxis = htemp->GetXaxis();
4065/// ~~~
4066///
4067/// When the option `"A"` is used (with TGraph painting option) to draw a 2D
4068/// distribution:
4069/// ~~~ {.cpp}
4070/// tree.Draw("e1:e2","","A*");
4071/// ~~~
4072/// a scatter plot is produced (with stars in that case) but the axis creation is
4073/// delegated to TGraph and `htemp` is not created.
4074///
4075/// ### Saving the result of Draw to a histogram
4076///
4077/// If `varexp` contains `>>hnew` (following the variable(s) name(s)),
4078/// the new histogram called `hnew` is created and it is kept in the current
4079/// directory (and also the current pad). This works for all dimensions.
4080///
4081/// Example:
4082/// ~~~ {.cpp}
4083/// tree.Draw("sqrt(x)>>hsqrt","y>0")
4084/// ~~~
4085/// will draw `sqrt(x)` and save the histogram as "hsqrt" in the current
4086/// directory. To retrieve it do:
4087/// ~~~ {.cpp}
4088/// TH1F *hsqrt = (TH1F*)gDirectory->Get("hsqrt");
4089/// ~~~
4090/// The binning information is taken from the environment variables
4091/// ~~~ {.cpp}
4092/// Hist.Binning.?D.?
4093/// ~~~
4094/// In addition, the name of the histogram can be followed by up to 9
4095/// numbers between '(' and ')', where the numbers describe the
4096/// following:
4097///
4098/// - 1 - bins in x-direction
4099/// - 2 - lower limit in x-direction
4100/// - 3 - upper limit in x-direction
4101/// - 4-6 same for y-direction
4102/// - 7-9 same for z-direction
4103///
4104/// When a new binning is used the new value will become the default.
4105/// Values can be skipped.
4106///
4107/// Example:
4108/// ~~~ {.cpp}
4109/// tree.Draw("sqrt(x)>>hsqrt(500,10,20)")
4110/// // plot sqrt(x) between 10 and 20 using 500 bins
4111/// tree.Draw("sqrt(x):sin(y)>>hsqrt(100,10,60,50,.1,.5)")
4112/// // plot sqrt(x) against sin(y)
4113/// // 100 bins in x-direction; lower limit on x-axis is 10; upper limit is 60
4114/// // 50 bins in y-direction; lower limit on y-axis is .1; upper limit is .5
4115/// ~~~
4116/// By default, the specified histogram is reset.
4117/// To continue to append data to an existing histogram, use "+" in front
4118/// of the histogram name.
4119///
4120/// A '+' in front of the histogram name is ignored, when the name is followed by
4121/// binning information as described in the previous paragraph.
4122/// ~~~ {.cpp}
4123/// tree.Draw("sqrt(x)>>+hsqrt","y>0")
4124/// ~~~
4125/// will not reset `hsqrt`, but will continue filling. This works for 1-D, 2-D
4126/// and 3-D histograms.
4127///
4128/// ### Accessing collection objects
4129///
4130/// TTree::Draw default's handling of collections is to assume that any
4131/// request on a collection pertain to it content. For example, if fTracks
4132/// is a collection of Track objects, the following:
4133/// ~~~ {.cpp}
4134/// tree->Draw("event.fTracks.fPx");
4135/// ~~~
4136/// will plot the value of fPx for each Track objects inside the collection.
4137/// Also
4138/// ~~~ {.cpp}
4139/// tree->Draw("event.fTracks.size()");
4140/// ~~~
4141/// would plot the result of the member function Track::size() for each
4142/// Track object inside the collection.
4143/// To access information about the collection itself, TTree::Draw support
4144/// the '@' notation. If a variable which points to a collection is prefixed
4145/// or postfixed with '@', the next part of the expression will pertain to
4146/// the collection object. For example:
4147/// ~~~ {.cpp}
4148/// tree->Draw("event.@fTracks.size()");
4149/// ~~~
4150/// will plot the size of the collection referred to by `fTracks` (i.e the number
4151/// of Track objects).
4152///
4153/// ### Drawing 'objects'
4154///
4155/// When a class has a member function named AsDouble or AsString, requesting
4156/// to directly draw the object will imply a call to one of the 2 functions.
4157/// If both AsDouble and AsString are present, AsDouble will be used.
4158/// AsString can return either a char*, a std::string or a TString.s
4159/// For example, the following
4160/// ~~~ {.cpp}
4161/// tree->Draw("event.myTTimeStamp");
4162/// ~~~
4163/// will draw the same histogram as
4164/// ~~~ {.cpp}
4165/// tree->Draw("event.myTTimeStamp.AsDouble()");
4166/// ~~~
4167/// In addition, when the object is a type TString or std::string, TTree::Draw
4168/// will call respectively `TString::Data` and `std::string::c_str()`
4169///
4170/// If the object is a TBits, the histogram will contain the index of the bit
4171/// that are turned on.
4172///
4173/// ### Retrieving information about the tree itself.
4174///
4175/// You can refer to the tree (or chain) containing the data by using the
4176/// string 'This'.
4177/// You can then could any TTree methods. For example:
4178/// ~~~ {.cpp}
4179/// tree->Draw("This->GetReadEntry()");
4180/// ~~~
4181/// will display the local entry numbers be read.
4182/// ~~~ {.cpp}
4183/// tree->Draw("This->GetUserInfo()->At(0)->GetName()");
4184/// ~~~
4185/// will display the name of the first 'user info' object.
4186///
4187/// ### Special functions and variables
4188///
4189/// `Entry$`: A TTree::Draw formula can use the special variable `Entry$`
4190/// to access the entry number being read. For example to draw every
4191/// other entry use:
4192/// ~~~ {.cpp}
4193/// tree.Draw("myvar","Entry$%2==0");
4194/// ~~~
4195/// - `Entry$` : return the current entry number (`== TTree::GetReadEntry()`)
4196/// - `LocalEntry$` : return the current entry number in the current tree of a
4197/// chain (`== GetTree()->GetReadEntry()`)
4198/// - `Entries$` : return the total number of entries (== TTree::GetEntries())
4199/// - `LocalEntries$` : return the total number of entries in the current tree
4200/// of a chain (== GetTree()->TTree::GetEntries())
4201/// - `Length$` : return the total number of element of this formula for this
4202/// entry (`==TTreeFormula::GetNdata()`)
4203/// - `Iteration$` : return the current iteration over this formula for this
4204/// entry (i.e. varies from 0 to `Length$`).
4205/// - `Length$(formula )` : return the total number of element of the formula
4206/// given as a parameter.
4207/// - `Sum$(formula )` : return the sum of the value of the elements of the
4208/// formula given as a parameter. For example the mean for all the elements in
4209/// one entry can be calculated with: `Sum$(formula )/Length$(formula )`
4210/// - `Min$(formula )` : return the minimum (within one TTree entry) of the value of the
4211/// elements of the formula given as a parameter.
4212/// - `Max$(formula )` : return the maximum (within one TTree entry) of the value of the
4213/// elements of the formula given as a parameter.
4214/// - `MinIf$(formula,condition)`
4215/// - `MaxIf$(formula,condition)` : return the minimum (maximum) (within one TTree entry)
4216/// of the value of the elements of the formula given as a parameter
4217/// if they match the condition. If no element matches the condition,
4218/// the result is zero. To avoid the resulting peak at zero, use the
4219/// pattern:
4220/// ~~~ {.cpp}
4221/// tree->Draw("MinIf$(formula,condition)","condition");
4222/// ~~~
4223/// which will avoid calculation `MinIf$` for the entries that have no match
4224/// for the condition.
4225/// - `Alt$(primary,alternate)` : return the value of "primary" if it is available
4226/// for the current iteration otherwise return the value of "alternate".
4227/// For example, with arr1[3] and arr2[2]
4228/// ~~~ {.cpp}
4229/// tree->Draw("arr1+Alt$(arr2,0)");
4230/// ~~~
4231/// will draw arr1[0]+arr2[0] ; arr1[1]+arr2[1] and arr1[2]+0
4232/// Or with a variable size array arr3
4233/// ~~~ {.cpp}
4234/// tree->Draw("Alt$(arr3[0],0)+Alt$(arr3[1],0)+Alt$(arr3[2],0)");
4235/// ~~~
4236/// will draw the sum arr3 for the index 0 to min(2,actual_size_of_arr3-1)
4237/// As a comparison
4238/// ~~~ {.cpp}
4239/// tree->Draw("arr3[0]+arr3[1]+arr3[2]");
4240/// ~~~
4241/// will draw the sum arr3 for the index 0 to 2 only if the
4242/// actual_size_of_arr3 is greater or equal to 3.
4243/// Note that the array in 'primary' is flattened/linearized thus using
4244/// `Alt$` with multi-dimensional arrays of different dimensions in unlikely
4245/// to yield the expected results. To visualize a bit more what elements
4246/// would be matched by TTree::Draw, TTree::Scan can be used:
4247/// ~~~ {.cpp}
4248/// tree->Scan("arr1:Alt$(arr2,0)");
4249/// ~~~
4250/// will print on one line the value of arr1 and (arr2,0) that will be
4251/// matched by
4252/// ~~~ {.cpp}
4253/// tree->Draw("arr1-Alt$(arr2,0)");
4254/// ~~~
4255/// The ternary operator is not directly supported in TTree::Draw however, to plot the
4256/// equivalent of `var2<20 ? -99 : var1`, you can use:
4257/// ~~~ {.cpp}
4258/// tree->Draw("(var2<20)*99+(var2>=20)*var1","");
4259/// ~~~
4260///
4261/// ### Drawing a user function accessing the TTree data directly
4262///
4263/// If the formula contains a file name, TTree::MakeProxy will be used
4264/// to load and execute this file. In particular it will draw the
4265/// result of a function with the same name as the file. The function
4266/// will be executed in a context where the name of the branches can
4267/// be used as a C++ variable.
4268///
4269/// For example draw px using the file hsimple.root (generated by the
4270/// hsimple.C tutorial), we need a file named hsimple.cxx:
4271/// ~~~ {.cpp}
4272/// double hsimple() {
4273/// return px;
4274/// }
4275/// ~~~
4276/// MakeProxy can then be used indirectly via the TTree::Draw interface
4277/// as follow:
4278/// ~~~ {.cpp}
4279/// new TFile("hsimple.root")
4280/// ntuple->Draw("hsimple.cxx");
4281/// ~~~
4282/// A more complete example is available in the tutorials directory:
4283/// `h1analysisProxy.cxx`, `h1analysProxy.h` and `h1analysisProxyCut.C`
4284/// which reimplement the selector found in `h1analysis.C`
4285///
4286/// The main features of this facility are:
4287///
4288/// * on-demand loading of branches
4289/// * ability to use the 'branchname' as if it was a data member
4290/// * protection against array out-of-bound
4291/// * ability to use the branch data as object (when the user code is available)
4292///
4293/// See TTree::MakeProxy for more details.
4294///
4295/// ### Making a Profile histogram
4296///
4297/// In case of a 2-Dim expression, one can generate a TProfile histogram
4298/// instead of a TH2F histogram by specifying option=prof or option=profs
4299/// or option=profi or option=profg ; the trailing letter select the way
4300/// the bin error are computed, See TProfile2D::SetErrorOption for
4301/// details on the differences.
4302/// The option=prof is automatically selected in case of y:x>>pf
4303/// where pf is an existing TProfile histogram.
4304///
4305/// ### Making a 2D Profile histogram
4306///
4307/// In case of a 3-Dim expression, one can generate a TProfile2D histogram
4308/// instead of a TH3F histogram by specifying option=prof or option=profs.
4309/// or option=profi or option=profg ; the trailing letter select the way
4310/// the bin error are computed, See TProfile2D::SetErrorOption for
4311/// details on the differences.
4312/// The option=prof is automatically selected in case of z:y:x>>pf
4313/// where pf is an existing TProfile2D histogram.
4314///
4315/// ### Making a 5D plot using GL
4316///
4317/// If option GL5D is specified together with 5 variables, a 5D plot is drawn
4318/// using OpenGL. See $ROOTSYS/tutorials/tree/staff.C as example.
4319///
4320/// ### Making a parallel coordinates plot
4321///
4322/// In case of a 2-Dim or more expression with the option=para, one can generate
4323/// a parallel coordinates plot. With that option, the number of dimensions is
4324/// arbitrary. Giving more than 4 variables without the option=para or
4325/// option=candle or option=goff will produce an error.
4326///
4327/// ### Making a candle sticks chart
4328///
4329/// In case of a 2-Dim or more expression with the option=candle, one can generate
4330/// a candle sticks chart. With that option, the number of dimensions is
4331/// arbitrary. Giving more than 4 variables without the option=para or
4332/// option=candle or option=goff will produce an error.
4333///
4334/// ### Normalizing the output histogram to 1
4335///
4336/// When option contains "norm" the output histogram is normalized to 1.
4337///
4338/// ### Saving the result of Draw to a TEventList, a TEntryList or a TEntryListArray
4339///
4340/// TTree::Draw can be used to fill a TEventList object (list of entry numbers)
4341/// instead of histogramming one variable.
4342/// If varexp0 has the form >>elist , a TEventList object named "elist"
4343/// is created in the current directory. elist will contain the list
4344/// of entry numbers satisfying the current selection.
4345/// If option "entrylist" is used, a TEntryList object is created
4346/// If the selection contains arrays, vectors or any container class and option
4347/// "entrylistarray" is used, a TEntryListArray object is created
4348/// containing also the subentries satisfying the selection, i.e. the indices of
4349/// the branches which hold containers classes.
4350/// Example:
4351/// ~~~ {.cpp}
4352/// tree.Draw(">>yplus","y>0")
4353/// ~~~
4354/// will create a TEventList object named "yplus" in the current directory.
4355/// In an interactive session, one can type (after TTree::Draw)
4356/// ~~~ {.cpp}
4357/// yplus.Print("all")
4358/// ~~~
4359/// to print the list of entry numbers in the list.
4360/// ~~~ {.cpp}
4361/// tree.Draw(">>yplus", "y>0", "entrylist")
4362/// ~~~
4363/// will create a TEntryList object names "yplus" in the current directory
4364/// ~~~ {.cpp}
4365/// tree.Draw(">>yplus", "y>0", "entrylistarray")
4366/// ~~~
4367/// will create a TEntryListArray object names "yplus" in the current directory
4368///
4369/// By default, the specified entry list is reset.
4370/// To continue to append data to an existing list, use "+" in front
4371/// of the list name;
4372/// ~~~ {.cpp}
4373/// tree.Draw(">>+yplus","y>0")
4374/// ~~~
4375/// will not reset yplus, but will enter the selected entries at the end
4376/// of the existing list.
4377///
4378/// ### Using a TEventList, TEntryList or TEntryListArray as Input
4379///
4380/// Once a TEventList or a TEntryList object has been generated, it can be used as input
4381/// for TTree::Draw. Use TTree::SetEventList or TTree::SetEntryList to set the
4382/// current event list
4383///
4384/// Example 1:
4385/// ~~~ {.cpp}
4386/// TEventList *elist = (TEventList*)gDirectory->Get("yplus");
4387/// tree->SetEventList(elist);
4388/// tree->Draw("py");
4389/// ~~~
4390/// Example 2:
4391/// ~~~ {.cpp}
4392/// TEntryList *elist = (TEntryList*)gDirectory->Get("yplus");
4393/// tree->SetEntryList(elist);
4394/// tree->Draw("py");
4395/// ~~~
4396/// If a TEventList object is used as input, a new TEntryList object is created
4397/// inside the SetEventList function. In case of a TChain, all tree headers are loaded
4398/// for this transformation. This new object is owned by the chain and is deleted
4399/// with it, unless the user extracts it by calling GetEntryList() function.
4400/// See also comments to SetEventList() function of TTree and TChain.
4401///
4402/// If arrays are used in the selection criteria and TEntryListArray is not used,
4403/// all the entries that have at least one element of the array that satisfy the selection
4404/// are entered in the list.
4405///
4406/// Example:
4407/// ~~~ {.cpp}
4408/// tree.Draw(">>pyplus","fTracks.fPy>0");
4409/// tree->SetEventList(pyplus);
4410/// tree->Draw("fTracks.fPy");
4411/// ~~~
4412/// will draw the fPy of ALL tracks in event with at least one track with
4413/// a positive fPy.
4414///
4415/// To select only the elements that did match the original selection
4416/// use TEventList::SetReapplyCut or TEntryList::SetReapplyCut.
4417///
4418/// Example:
4419/// ~~~ {.cpp}
4420/// tree.Draw(">>pyplus","fTracks.fPy>0");
4421/// pyplus->SetReapplyCut(kTRUE);
4422/// tree->SetEventList(pyplus);
4423/// tree->Draw("fTracks.fPy");
4424/// ~~~
4425/// will draw the fPy of only the tracks that have a positive fPy.
4426///
4427/// To draw only the elements that match a selection in case of arrays,
4428/// you can also use TEntryListArray (faster in case of a more general selection).
4429///
4430/// Example:
4431/// ~~~ {.cpp}
4432/// tree.Draw(">>pyplus","fTracks.fPy>0", "entrylistarray");
4433/// tree->SetEntryList(pyplus);
4434/// tree->Draw("fTracks.fPy");
4435/// ~~~
4436/// will draw the fPy of only the tracks that have a positive fPy,
4437/// but without redoing the selection.
4438///
4439/// Note: Use tree->SetEventList(0) if you do not want use the list as input.
4440///
4441/// ### How to obtain more info from TTree::Draw
4442///
4443/// Once TTree::Draw has been called, it is possible to access useful
4444/// information still stored in the TTree object via the following functions:
4445///
4446/// - GetSelectedRows() // return the number of values accepted by the selection expression. In case where no selection was specified, returns the number of values processed.
4447/// - GetV1() // returns a pointer to the double array of V1
4448/// - GetV2() // returns a pointer to the double array of V2
4449/// - GetV3() // returns a pointer to the double array of V3
4450/// - GetV4() // returns a pointer to the double array of V4
4451/// - GetW() // returns a pointer to the double array of Weights where weight equal the result of the selection expression.
4452///
4453/// where V1,V2,V3 correspond to the expressions in
4454/// ~~~ {.cpp}
4455/// TTree::Draw("V1:V2:V3:V4",selection);
4456/// ~~~
4457/// If the expression has more than 4 component use GetVal(index)
4458///
4459/// Example:
4460/// ~~~ {.cpp}
4461/// Root > ntuple->Draw("py:px","pz>4");
4462/// Root > TGraph *gr = new TGraph(ntuple->GetSelectedRows(),
4463/// ntuple->GetV2(), ntuple->GetV1());
4464/// Root > gr->Draw("ap"); //draw graph in current pad
4465/// ~~~
4466///
4467/// A more complete complete tutorial (treegetval.C) shows how to use the
4468/// GetVal() method.
4469///
4470/// creates a TGraph object with a number of points corresponding to the
4471/// number of entries selected by the expression "pz>4", the x points of the graph
4472/// being the px values of the Tree and the y points the py values.
4473///
4474/// Important note: By default TTree::Draw creates the arrays obtained
4475/// with GetW, GetV1, GetV2, GetV3, GetV4, GetVal with a length corresponding
4476/// to the parameter fEstimate. The content will be the last `GetSelectedRows() % GetEstimate()`
4477/// values calculated.
4478/// By default fEstimate=1000000 and can be modified
4479/// via TTree::SetEstimate. To keep in memory all the results (in case
4480/// where there is only one result per entry), use
4481/// ~~~ {.cpp}
4482/// tree->SetEstimate(tree->GetEntries()+1); // same as tree->SetEstimate(-1);
4483/// ~~~
4484/// You must call SetEstimate if the expected number of selected rows
4485/// you need to look at is greater than 1000000.
4486///
4487/// You can use the option "goff" to turn off the graphics output
4488/// of TTree::Draw in the above example.
4489///
4490/// ### Automatic interface to TTree::Draw via the TTreeViewer
4491///
4492/// A complete graphical interface to this function is implemented
4493/// in the class TTreeViewer.
4494/// To start the TTreeViewer, three possibilities:
4495/// - select TTree context menu item "StartViewer"
4496/// - type the command "TTreeViewer TV(treeName)"
4497/// - execute statement "tree->StartViewer();"
4499Long64_t TTree::Draw(const char* varexp, const char* selection, Option_t* option, Long64_t nentries, Long64_t firstentry)
4500{
4501 GetPlayer();
4502 if (fPlayer)
4503 return fPlayer->DrawSelect(varexp,selection,option,nentries,firstentry);
4504 return -1;
4505}
4506
4507////////////////////////////////////////////////////////////////////////////////
4508/// Remove some baskets from memory.
4510void TTree::DropBaskets()
4511{
4512 TBranch* branch = 0;
4514 for (Int_t i = 0; i < nb; ++i) {
4515 branch = (TBranch*) fBranches.UncheckedAt(i);
4516 branch->DropBaskets("all");
4517 }
4518}
4519
4520////////////////////////////////////////////////////////////////////////////////
4521/// Drop branch buffers to accommodate nbytes below MaxVirtualsize.
4524{
4525 // Be careful not to remove current read/write buffers.
4526 Int_t nleaves = fLeaves.GetEntriesFast();
4527 for (Int_t i = 0; i < nleaves; ++i) {
4528 TLeaf* leaf = (TLeaf*) fLeaves.UncheckedAt(i);
4529 TBranch* branch = (TBranch*) leaf->GetBranch();
4530 Int_t nbaskets = branch->GetListOfBaskets()->GetEntries();
4531 for (Int_t j = 0; j < nbaskets - 1; ++j) {
4532 if ((j == branch->GetReadBasket()) || (j == branch->GetWriteBasket())) {
4533 continue;
4534 }
4535 TBasket* basket = (TBasket*)branch->GetListOfBaskets()->UncheckedAt(j);
4536 if (basket) {
4537 basket->DropBuffers();
4539 return;
4540 }
4541 }
4542 }
4543 }
4544}
4545
4546////////////////////////////////////////////////////////////////////////////////
4547/// Fill all branches.
4548///
4549/// This function loops on all the branches of this tree. For
4550/// each branch, it copies to the branch buffer (basket) the current
4551/// values of the leaves data types. If a leaf is a simple data type,
4552/// a simple conversion to a machine independent format has to be done.
4553///
4554/// This machine independent version of the data is copied into a
4555/// basket (each branch has its own basket). When a basket is full
4556/// (32k worth of data by default), it is then optionally compressed
4557/// and written to disk (this operation is also called committing or
4558/// 'flushing' the basket). The committed baskets are then
4559/// immediately removed from memory.
4560///
4561/// The function returns the number of bytes committed to the
4562/// individual branches.
4563///
4564/// If a write error occurs, the number of bytes returned is -1.
4565///
4566/// If no data are written, because, e.g., the branch is disabled,
4567/// the number of bytes returned is 0.
4568///
4569/// __The baskets are flushed and the Tree header saved at regular intervals__
4570///
4571/// At regular intervals, when the amount of data written so far is
4572/// greater than fAutoFlush (see SetAutoFlush) all the baskets are flushed to disk.
4573/// This makes future reading faster as it guarantees that baskets belonging to nearby
4574/// entries will be on the same disk region.
4575/// When the first call to flush the baskets happen, we also take this opportunity
4576/// to optimize the baskets buffers.
4577/// We also check if the amount of data written is greater than fAutoSave (see SetAutoSave).
4578/// In this case we also write the Tree header. This makes the Tree recoverable up to this point
4579/// in case the program writing the Tree crashes.
4580/// The decisions to FlushBaskets and Auto Save can be made based either on the number
4581/// of bytes written (fAutoFlush and fAutoSave negative) or on the number of entries
4582/// written (fAutoFlush and fAutoSave positive).
4583/// Note that the user can decide to call FlushBaskets and AutoSave in her event loop
4584/// base on the number of events written instead of the number of bytes written.
4585///
4586/// \note Calling `TTree::FlushBaskets` too often increases the IO time.
4587///
4588/// \note Calling `TTree::AutoSave` too often increases the IO time and also the
4589/// file size.
4590///
4591/// \note This method calls `TTree::ChangeFile` when the tree reaches a size
4592/// greater than `TTree::fgMaxTreeSize`. This doesn't happen if the tree is
4593/// attached to a `TMemFile` or derivate.
4596{
4597 Int_t nbytes = 0;
4598 Int_t nwrite = 0;
4599 Int_t nerror = 0;
4600 Int_t nbranches = fBranches.GetEntriesFast();
4601
4602 // Case of one single super branch. Automatically update
4603 // all the branch addresses if a new object was created.
4604 if (nbranches == 1)
4605 ((TBranch *)fBranches.UncheckedAt(0))->UpdateAddress();
4606
4607 if (fBranchRef)
4608 fBranchRef->Clear();
4609
4610#ifdef R__USE_IMT
4611 const auto useIMT = ROOT::IsImplicitMTEnabled() && fIMTEnabled;
4613 if (useIMT) {
4614 fIMTFlush = true;
4615 fIMTZipBytes.store(0);
4616 fIMTTotBytes.store(0);
4617 }
4618#endif
4619
4620 for (Int_t i = 0; i < nbranches; ++i) {
4621 // Loop over all branches, filling and accumulating bytes written and error counts.
4622 TBranch *branch = (TBranch *)fBranches.UncheckedAt(i);
4623
4624 if (branch->TestBit(kDoNotProcess))
4625 continue;
4626
4627#ifndef R__USE_IMT
4628 nwrite = branch->FillImpl(nullptr);
4629#else
4630 nwrite = branch->FillImpl(useIMT ? &imtHelper : nullptr);
4631#endif
4632 if (nwrite < 0) {
4633 if (nerror < 2) {
4634 Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld\n"
4635 " This error is symptomatic of a Tree created as a memory-resident Tree\n"
4636 " Instead of doing:\n"
4637 " TTree *T = new TTree(...)\n"
4638 " TFile *f = new TFile(...)\n"
4639 " you should do:\n"
4640 " TFile *f = new TFile(...)\n"
4641 " TTree *T = new TTree(...)\n\n",
4642 GetName(), branch->GetName(), nwrite, fEntries + 1);
4643 } else {
4644 Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld", GetName(), branch->GetName(), nwrite,
4645 fEntries + 1);
4646 }
4647 ++nerror;
4648 } else {
4649 nbytes += nwrite;
4650 }
4651 }
4652
4653#ifdef R__USE_IMT
4654 if (fIMTFlush) {
4655 imtHelper.Wait();
4656 fIMTFlush = false;
4657 const_cast<TTree *>(this)->AddTotBytes(fIMTTotBytes);
4658 const_cast<TTree *>(this)->AddZipBytes(fIMTZipBytes);
4659 nbytes += imtHelper.GetNbytes();
4660 nerror += imtHelper.GetNerrors();
4661 }
4662#endif
4663
4664 if (fBranchRef)
4665 fBranchRef->Fill();
4666
4667 ++fEntries;
4668
4669 if (fEntries > fMaxEntries)
4670 KeepCircular();
4671
4672 if (gDebug > 0)
4673 Info("TTree::Fill", " - A: %d %lld %lld %lld %lld %lld %lld \n", nbytes, fEntries, fAutoFlush, fAutoSave,
4675
4676 bool autoFlush = false;
4677 bool autoSave = false;
4678
4679 if (fAutoFlush != 0 || fAutoSave != 0) {
4680 // Is it time to flush or autosave baskets?
4681 if (fFlushedBytes == 0) {
4682 // If fFlushedBytes == 0, it means we never flushed or saved, so
4683 // we need to check if it's time to do it and recompute the values
4684 // of fAutoFlush and fAutoSave in terms of the number of entries.
4685 // Decision can be based initially either on the number of bytes
4686 // or the number of entries written.
4687 Long64_t zipBytes = GetZipBytes();
4688
4689 if (fAutoFlush)
4690 autoFlush = fAutoFlush < 0 ? (zipBytes > -fAutoFlush) : fEntries % fAutoFlush == 0;
4691
4692 if (fAutoSave)
4693 autoSave = fAutoSave < 0 ? (zipBytes > -fAutoSave) : fEntries % fAutoSave == 0;
4694
4695 if (autoFlush || autoSave) {
4696 // First call FlushBasket to make sure that fTotBytes is up to date.
4698 autoFlush = false; // avoid auto flushing again later
4699
4700 // When we are in one-basket-per-cluster mode, there is no need to optimize basket:
4701 // they will automatically grow to the size needed for an event cluster (with the basket
4702 // shrinking preventing them from growing too much larger than the actually-used space).
4704 OptimizeBaskets(GetTotBytes(), 1, "");
4705 if (gDebug > 0)
4706 Info("TTree::Fill", "OptimizeBaskets called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n",
4708 }
4710 fAutoFlush = fEntries; // Use test on entries rather than bytes
4711
4712 // subsequently in run
4713 if (fAutoSave < 0) {
4714 // Set fAutoSave to the largest integer multiple of
4715 // fAutoFlush events such that fAutoSave*fFlushedBytes
4716 // < (minus the input value of fAutoSave)
4717 Long64_t totBytes = GetTotBytes();
4718 if (zipBytes != 0) {
4719 fAutoSave = TMath::Max(fAutoFlush, fEntries * ((-fAutoSave / zipBytes) / fEntries));
4720 } else if (totBytes != 0) {
4721 fAutoSave = TMath::Max(fAutoFlush, fEntries * ((-fAutoSave / totBytes) / fEntries));
4722 } else {
4724 TTree::Class()->WriteBuffer(b, (TTree *)this);
4725 Long64_t total = b.Length();
4727 }
4728 } else if (fAutoSave > 0) {
4730 }
4731
4732 if (fAutoSave != 0 && fEntries >= fAutoSave)
4733 autoSave = true;
4734
4735 if (gDebug > 0)
4736 Info("TTree::Fill", "First AutoFlush. fAutoFlush = %lld, fAutoSave = %lld\n", fAutoFlush, fAutoSave);
4737 }
4738 } else {
4739 // Check if we need to auto flush
4740 if (fAutoFlush) {
4741 if (fNClusterRange == 0)
4742 autoFlush = fEntries > 1 && fEntries % fAutoFlush == 0;
4743 else
4744 autoFlush = (fEntries - (fClusterRangeEnd[fNClusterRange - 1] + 1)) % fAutoFlush == 0;
4745 }
4746 // Check if we need to auto save
4747 if (fAutoSave)
4748 autoSave = fEntries % fAutoSave == 0;
4749 }
4750 }
4751
4752 if (autoFlush) {
4754 if (gDebug > 0)
4755 Info("TTree::Fill", "FlushBaskets() called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n", fEntries,
4758 }
4759
4760 if (autoSave) {
4761 AutoSave(); // does not call FlushBasketsImpl() again
4762 if (gDebug > 0)
4763 Info("TTree::Fill", "AutoSave called at entry %lld, fZipBytes=%lld, fSavedBytes=%lld\n", fEntries,
4765 }
4766
4767 // Check that output file is still below the maximum size.
4768 // If above, close the current file and continue on a new file.
4769 // Currently, the automatic change of file is restricted
4770 // to the case where the tree is in the top level directory.
4771 if (fDirectory)
4772 if (TFile *file = fDirectory->GetFile())
4773 if (static_cast<TDirectory *>(file) == fDirectory && (file->GetEND() > fgMaxTreeSize))
4774 // Changing file clashes with the design of TMemFile and derivates, see #6523.
4775 if (!(dynamic_cast<TMemFile *>(file)))
4777
4778 return nerror == 0 ? nbytes : -1;
4779}
4780
4781////////////////////////////////////////////////////////////////////////////////
4782/// Search in the array for a branch matching the branch name,
4783/// with the branch possibly expressed as a 'full' path name (with dots).
4785static TBranch *R__FindBranchHelper(TObjArray *list, const char *branchname) {
4786 if (list==0 || branchname == 0 || branchname[0] == '\0') return 0;
4787
4788 Int_t nbranches = list->GetEntries();
4789
4790 UInt_t brlen = strlen(branchname);
4791
4792 for(Int_t index = 0; index < nbranches; ++index) {
4793 TBranch *where = (TBranch*)list->UncheckedAt(index);
4794
4795 const char *name = where->GetName();
4796 UInt_t len = strlen(name);
4797 if (len && name[len-1]==']') {
4798 const char *dim = strchr(name,'[');
4799 if (dim) {
4800 len = dim - name;
4801 }
4802 }
4803 if (brlen == len && strncmp(branchname,name,len)==0) {
4804 return where;
4805 }
4806 TBranch *next = 0;
4807 if ((brlen >= len) && (branchname[len] == '.')
4808 && strncmp(name, branchname, len) == 0) {
4809 // The prefix subbranch name match the branch name.
4810
4811 next = where->FindBranch(branchname);
4812 if (!next) {
4813 next = where->FindBranch(branchname+len+1);
4814 }
4815 if (next) return next;
4816 }
4817 const char *dot = strchr((char*)branchname,'.');
4818 if (dot) {
4819 if (len==(size_t)(dot-branchname) &&
4820 strncmp(branchname,name,dot-branchname)==0 ) {
4821 return R__FindBranchHelper(where->GetListOfBranches(),dot+1);
4822 }
4823 }
4824 }
4825 return 0;
4826}
4827
4828////////////////////////////////////////////////////////////////////////////////
4829/// Return the branch that correspond to the path 'branchname', which can
4830/// include the name of the tree or the omitted name of the parent branches.
4831/// In case of ambiguity, returns the first match.
4833TBranch* TTree::FindBranch(const char* branchname)
4834{
4835 // We already have been visited while recursively looking
4836 // through the friends tree, let return
4838 return nullptr;
4839 }
4840
4841 if (!branchname)
4842 return nullptr;
4843
4844 TBranch* branch = nullptr;
4845 // If the first part of the name match the TTree name, look for the right part in the
4846 // list of branches.
4847 // This will allow the branchname to be preceded by
4848 // the name of this tree.
4849 if (strncmp(fName.Data(),branchname,fName.Length())==0 && branchname[fName.Length()]=='.') {
4850 branch = R__FindBranchHelper( GetListOfBranches(), branchname + fName.Length() + 1);
4851 if (branch) return branch;
4852 }
4853 // If we did not find it, let's try to find the full name in the list of branches.
4854 branch = R__FindBranchHelper(GetListOfBranches(), branchname);
4855 if (branch) return branch;
4856
4857 // If we still did not find, let's try to find it within each branch assuming it does not the branch name.
4858 TIter next(GetListOfBranches());
4859 while ((branch = (TBranch*) next())) {
4860 TBranch* nestedbranch = branch->FindBranch(branchname);
4861 if (nestedbranch) {
4862 return nestedbranch;
4863 }
4864 }
4865
4866 // Search in list of friends.
4867 if (!fFriends) {
4868 return nullptr;
4869 }
4870 TFriendLock lock(this, kFindBranch);
4871 TIter nextf(fFriends);
4872 TFriendElement* fe = nullptr;
4873 while ((fe = (TFriendElement*) nextf())) {
4874 TTree* t = fe->GetTree();
4875 if (!t) {
4876 continue;
4877 }
4878 // If the alias is present replace it with the real name.
4879 const char *subbranch = strstr(branchname, fe->GetName());
4880 if (subbranch != branchname) {
4881 subbranch = nullptr;
4882 }
4883 if (subbranch) {
4884 subbranch += strlen(fe->GetName());
4885 if (*subbranch != '.') {
4886 subbranch = nullptr;
4887 } else {
4888 ++subbranch;
4889 }
4890 }
4891 std::ostringstream name;
4892 if (subbranch) {
4893 name << t->GetName() << "." << subbranch;
4894 } else {
4895 name << branchname;
4896 }
4897 branch = t->FindBranch(name.str().c_str());
4898 if (branch) {
4899 return branch;
4900 }
4901 }
4902 return nullptr;
4903}
4904
4905////////////////////////////////////////////////////////////////////////////////
4906/// Find leaf..
4908TLeaf* TTree::FindLeaf(const char* searchname)
4909{
4910 if (!searchname)
4911 return nullptr;
4912
4913 // We already have been visited while recursively looking
4914 // through the friends tree, let's return.
4916 return nullptr;
4917 }
4918
4919 // This will allow the branchname to be preceded by
4920 // the name of this tree.
4921 const char* subsearchname = strstr(searchname, GetName());
4922 if (subsearchname != searchname) {
4923 subsearchname = nullptr;
4924 }
4925 if (subsearchname) {
4926 subsearchname += strlen(GetName());
4927 if (*subsearchname != '.') {
4928 subsearchname = nullptr;
4929 } else {
4930 ++subsearchname;
4931 if (subsearchname[0] == 0) {
4932 subsearchname = nullptr;
4933 }
4934 }
4935 }
4936
4937 TString leafname;
4938 TString leaftitle;
4939 TString longname;
4940 TString longtitle;
4941
4942 const bool searchnameHasDot = strchr(searchname, '.') != nullptr;
4943
4944 // For leaves we allow for one level up to be prefixed to the name.
4945 TIter next(GetListOfLeaves());
4946 TLeaf* leaf = nullptr;
4947 while ((leaf = (TLeaf*) next())) {
4948 leafname = leaf->GetName();
4949 Ssiz_t dim = leafname.First('[');
4950 if (dim >= 0) leafname.Remove(dim);
4951
4952 if (leafname == searchname) {
4953 return leaf;
4954 }
4955 if (subsearchname && leafname == subsearchname) {
4956 return leaf;
4957 }
4958 // The TLeafElement contains the branch name
4959 // in its name, let's use the title.
4960 leaftitle = leaf->GetTitle();
4961 dim = leaftitle.First('[');
4962 if (dim >= 0) leaftitle.Remove(dim);
4963
4964 if (leaftitle == searchname) {
4965 return leaf;
4966 }
4967 if (subsearchname && leaftitle == subsearchname) {
4968 return leaf;
4969 }
4970 if (!searchnameHasDot)
4971 continue;
4972 TBranch* branch = leaf->GetBranch();
4973 if (branch) {
4974 longname.Form("%s.%s",branch->GetName(),leafname.Data());
4975 dim = longname.First('[');
4976 if (dim>=0) longname.Remove(dim);
4977 if (longname == searchname) {
4978 return leaf;
4979 }
4980 if (subsearchname && longname == subsearchname) {
4981 return leaf;
4982 }
4983 longtitle.Form("%s.%s",branch->GetName(),leaftitle.Data());
4984 dim = longtitle.First('[');
4985 if (dim>=0) longtitle.Remove(dim);
4986 if (longtitle == searchname) {
4987 return leaf;
4988 }
4989 if (subsearchname && longtitle == subsearchname) {
4990 return leaf;
4991 }
4992 // The following is for the case where the branch is only
4993 // a sub-branch. Since we do not see it through
4994 // TTree::GetListOfBranches, we need to see it indirectly.
4995 // This is the less sturdy part of this search ... it may
4996 // need refining ...
4997 if (strstr(searchname, ".") && !strcmp(searchname, branch->GetName())) {
4998 return leaf;
4999 }
5000 if (subsearchname && strstr(subsearchname, ".") && !strcmp(subsearchname, branch->GetName())) {
5001 return leaf;
5002 }
5003 }
5004 }
5005 // Search in list of friends.
5006 if (!fFriends) {
5007 return nullptr;
5008 }
5009 TFriendLock lock(this, kFindLeaf);
5010 TIter nextf(fFriends);
5011 TFriendElement* fe = nullptr;
5012 while ((fe = (TFriendElement*) nextf())) {
5013 TTree* t = fe->GetTree();
5014 if (!t) {
5015 continue;
5016 }
5017 // If the alias is present replace it with the real name.
5018 subsearchname = strstr(searchname, fe->GetName());
5019 if (subsearchname != searchname) {
5020 subsearchname = nullptr;
5021 }
5022 if (subsearchname) {
5023 subsearchname += strlen(fe->GetName());
5024 if (*subsearchname != '.') {
5025 subsearchname = nullptr;
5026 } else {
5027 ++subsearchname;
5028 }
5029 }
5030 if (subsearchname) {
5031 leafname.Form("%s.%s",t->GetName(),subsearchname);
5032 } else {
5033 leafname = searchname;
5034 }
5035 leaf = t->FindLeaf(leafname);
5036 if (leaf) {
5037 return leaf;
5038 }
5039 }
5040 return nullptr;
5041}
5042
5043////////////////////////////////////////////////////////////////////////////////
5044/// Fit a projected item(s) from a tree.
5045///
5046/// funcname is a TF1 function.
5047///
5048/// See TTree::Draw() for explanations of the other parameters.
5049///
5050/// By default the temporary histogram created is called htemp.
5051/// If varexp contains >>hnew , the new histogram created is called hnew
5052/// and it is kept in the current directory.
5053///
5054/// The function returns the number of selected entries.
5055///
5056/// Example:
5057/// ~~~ {.cpp}
5058/// tree.Fit(pol4,"sqrt(x)>>hsqrt","y>0")
5059/// ~~~
5060/// will fit sqrt(x) and save the histogram as "hsqrt" in the current
5061/// directory.
5062///
5063/// See also TTree::UnbinnedFit
5064///
5065/// ## Return status
5066///
5067/// The function returns the status of the histogram fit (see TH1::Fit)
5068/// If no entries were selected, the function returns -1;
5069/// (i.e. fitResult is null if the fit is OK)
5071Int_t TTree::Fit(const char* funcname, const char* varexp, const char* selection, Option_t* option, Option_t* goption, Long64_t nentries, Long64_t firstentry)
5072{
5073 GetPlayer();
5074 if (fPlayer) {
5075 return fPlayer->Fit(funcname, varexp, selection, option, goption, nentries, firstentry);
5076 }
5077 return -1;
5078}
5079
5080namespace {
5081struct BoolRAIIToggle {
5082 Bool_t &m_val;
5083
5084 BoolRAIIToggle(Bool_t &val) : m_val(val) { m_val = true; }
5085 ~BoolRAIIToggle() { m_val = false; }
5086};
5087}
5088
5089////////////////////////////////////////////////////////////////////////////////
5090/// Write to disk all the basket that have not yet been individually written and
5091/// create an event cluster boundary (by default).
5092///
5093/// If the caller wishes to flush the baskets but not create an event cluster,
5094/// then set create_cluster to false.
5095///
5096/// If ROOT has IMT-mode enabled, this will launch multiple TBB tasks in parallel
5097/// via TThreadExecutor to do this operation; one per basket compression. If the
5098/// caller utilizes TBB also, care must be taken to prevent deadlocks.
5099///
5100/// For example, let's say the caller holds mutex A and calls FlushBaskets; while
5101/// TBB is waiting for the ROOT compression tasks to complete, it may decide to
5102/// run another one of the user's tasks in this thread. If the second user task
5103/// tries to acquire A, then a deadlock will occur. The example call sequence
5104/// looks like this:
5105///
5106/// - User acquires mutex A
5107/// - User calls FlushBaskets.
5108/// - ROOT launches N tasks and calls wait.
5109/// - TBB schedules another user task, T2.
5110/// - T2 tries to acquire mutex A.
5111///
5112/// At this point, the thread will deadlock: the code may function with IMT-mode
5113/// disabled if the user assumed the legacy code never would run their own TBB
5114/// tasks.
5115///
5116/// SO: users of TBB who want to enable IMT-mode should carefully review their
5117/// locking patterns and make sure they hold no coarse-grained application
5118/// locks when they invoke ROOT.
5119///
5120/// Return the number of bytes written or -1 in case of write error.
5121Int_t TTree::FlushBaskets(Bool_t create_cluster) const
5122{
5123 Int_t retval = FlushBasketsImpl();
5124 if (retval == -1) return retval;
5125
5126 if (create_cluster) const_cast<TTree *>(this)->MarkEventCluster();
5127 return retval;
5128}
5129
5130////////////////////////////////////////////////////////////////////////////////
5131/// Internal implementation of the FlushBaskets algorithm.
5132/// Unlike the public interface, this does NOT create an explicit event cluster
5133/// boundary; it is up to the (internal) caller to determine whether that should
5134/// done.
5135///
5136/// Otherwise, the comments for FlushBaskets applies.
5139{
5140 if (!fDirectory) return 0;
5141 Int_t nbytes = 0;
5142 Int_t nerror = 0;
5143 TObjArray *lb = const_cast<TTree*>(this)->GetListOfBranches();
5144 Int_t nb = lb->GetEntriesFast();
5145
5146#ifdef R__USE_IMT
5147 const auto useIMT = ROOT::IsImplicitMTEnabled() && fIMTEnabled;
5148 if (useIMT) {
5149 // ROOT-9668: here we need to check if the size of fSortedBranches is different from the
5150 // size of the list of branches before triggering the initialisation of the fSortedBranches
5151 // container to cover two cases:
5152 // 1. This is the first time we flush. fSortedBranches is empty and we need to fill it.
5153 // 2. We flushed at least once already but a branch has been be added to the tree since then
5154 if (fSortedBranches.size() != unsigned(nb)) { const_cast<TTree*>(this)->InitializeBranchLists(false); }
5155
5156 BoolRAIIToggle sentry(fIMTFlush);
5157 fIMTZipBytes.store(0);
5158 fIMTTotBytes.store(0);
5159 std::atomic<Int_t> nerrpar(0);
5160 std::atomic<Int_t> nbpar(0);
5161 std::atomic<Int_t> pos(0);
5162
5163 auto mapFunction = [&]() {
5164 // The branch to process is obtained when the task starts to run.
5165 // This way, since branches are sorted, we make sure that branches
5166 // leading to big tasks are processed first. If we assigned the
5167 // branch at task creation time, the scheduler would not necessarily
5168 // respect our sorting.
5169 Int_t j = pos.fetch_add(1);
5170
5171 auto branch = fSortedBranches[j].second;
5172 if (R__unlikely(!branch)) { return; }
5173
5174 if (R__unlikely(gDebug > 0)) {
5175 std::stringstream ss;
5176 ss << std::this_thread::get_id();
5177 Info("FlushBaskets", "[IMT] Thread %s", ss.str().c_str());
5178 Info("FlushBaskets", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
5179 }
5180
5181 Int_t nbtask = branch->FlushBaskets();
5182
5183 if (nbtask < 0) { nerrpar++; }
5184 else { nbpar += nbtask; }
5185 };
5186
5188 pool.Foreach(mapFunction, nb);
5189
5190 fIMTFlush = false;
5191 const_cast<TTree*>(this)->AddTotBytes(fIMTTotBytes);
5192 const_cast<TTree*>(this)->AddZipBytes(fIMTZipBytes);
5193
5194 return nerrpar ? -1 : nbpar.load();
5195 }
5196#endif
5197 for (Int_t j = 0; j < nb; j++) {
5198 TBranch* branch = (TBranch*) lb->UncheckedAt(j);
5199 if (branch) {
5200 Int_t nwrite = branch->FlushBaskets();
5201 if (nwrite<0) {
5202 ++nerror;
5203 } else {
5204 nbytes += nwrite;
5205 }
5206 }
5207 }
5208 if (nerror) {
5209 return -1;
5210 } else {
5211 return nbytes;
5212 }
5213}
5214
5215////////////////////////////////////////////////////////////////////////////////
5216/// Returns the expanded value of the alias. Search in the friends if any.
5218const char* TTree::GetAlias(const char* aliasName) const
5219{
5220 // We already have been visited while recursively looking
5221 // through the friends tree, let's return.
5223 return nullptr;
5224 }
5225 if (fAliases) {
5226 TObject* alias = fAliases->FindObject(aliasName);
5227 if (alias) {
5228 return alias->GetTitle();
5229 }
5230 }
5231 if (!fFriends) {
5232 return nullptr;
5233 }
5234 TFriendLock lock(const_cast<TTree*>(this), kGetAlias);
5235 TIter nextf(fFriends);
5236 TFriendElement* fe = nullptr;
5237 while ((fe = (TFriendElement*) nextf())) {
5238 TTree* t = fe->GetTree();
5239 if (t) {
5240 const char* alias = t->GetAlias(aliasName);
5241 if (alias) {
5242 return alias;
5243 }
5244 const char* subAliasName = strstr(aliasName, fe->GetName());
5245 if (subAliasName && (subAliasName[strlen(fe->GetName())] == '.')) {
5246 alias = t->GetAlias(aliasName + strlen(fe->GetName()) + 1);
5247 if (alias) {
5248 return alias;
5249 }
5250 }
5251 }
5252 }
5253 return nullptr;
5254}
5255
5256namespace {
5257/// Do a breadth first search through the implied hierarchy
5258/// of branches.
5259/// To avoid scanning through the list multiple time
5260/// we also remember the 'depth-first' match.
5261TBranch *R__GetBranch(const TObjArray &branches, const char *name)
5262{
5263 TBranch *result = nullptr;
5264 Int_t nb = branches.GetEntriesFast();
5265 for (Int_t i = 0; i < nb; i++) {
5266 TBranch* b = (TBranch*)branches.UncheckedAt(i);
5267 if (!b)
5268 continue;
5269 if (!strcmp(b->GetName(), name)) {
5270 return b;
5271 }
5272 if (!strcmp(b->GetFullName(), name)) {
5273 return b;
5274 }
5275 if (!result)
5276 result = R__GetBranch(*(b->GetListOfBranches()), name);
5277 }
5278 return result;
5279}
5280}
5281
5282////////////////////////////////////////////////////////////////////////////////
5283/// Return pointer to the branch with the given name in this tree or its friends.
5284/// The search is done breadth first.
5286TBranch* TTree::GetBranch(const char* name)
5287{
5288 // We already have been visited while recursively
5289 // looking through the friends tree, let's return.
5291 return nullptr;
5292 }
5293
5294 if (!name)
5295 return nullptr;
5296
5297 // Look for an exact match in the list of top level
5298 // branches.
5300 if (result)
5301 return result;
5302
5303 // Search using branches, breadth first.
5304 result = R__GetBranch(fBranches, name);
5305 if (result)
5306 return result;
5307
5308 // Search using leaves.
5309 TObjArray* leaves = GetListOfLeaves();
5310 Int_t nleaves = leaves->GetEntriesFast();
5311 for (Int_t i = 0; i < nleaves; i++) {
5312 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
5313 TBranch* branch = leaf->GetBranch();
5314 if (!strcmp(branch->GetName(), name)) {
5315 return branch;
5316 }
5317 if (!strcmp(branch->GetFullName(), name)) {
5318 return branch;
5319 }
5320 }
5321
5322 if (!fFriends) {
5323 return nullptr;
5324 }
5325
5326 // Search in list of friends.
<