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