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