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