Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TTreePlayer.cxx
Go to the documentation of this file.
1// @(#)root/treeplayer:$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/**
13 * \defgroup treeplayer TTreePlayer
14 * \ingroup tree
15 * \brief It contains utilities to plot data stored in a TTree.
16 * \note See also Tree package documentation
17 * \note See also Chapter about Trees and Selectors in the Users Guide
18 * \note See also ROOT examples in tutorials and test directories: Event application, benchmarks
19 */
20
21/** \class TTreePlayer
22
23Implement some of the functionality of the class TTree requiring access to
24extra libraries (Histogram, display, etc).
25*/
26
27#include "TTreePlayer.h"
28
29#include <cstring>
30#include <cstdio>
31#include <cstdlib>
32#include <iostream>
33#include <fstream>
34#include <vector>
35
36#include "TROOT.h"
37#include "TApplication.h"
38#include "TSystem.h"
39#include "TFile.h"
40#include "TEnv.h"
41#include "TEventList.h"
42#include "TEntryList.h"
43#include "TBranchObject.h"
44#include "TBranchElement.h"
45#include "TStreamerInfo.h"
46#include "TStreamerElement.h"
47#include "TLeafObject.h"
48#include "TLeafF.h"
49#include "TLeafD.h"
50#include "TLeafC.h"
51#include "TLeafB.h"
52#include "TLeafI.h"
53#include "TLeafS.h"
54#include "TMath.h"
55#include "TH1.h"
56#include "TPolyMarker.h"
57#include "TPolyMarker3D.h"
58#include "TText.h"
59#include "TDirectory.h"
60#include "TClonesArray.h"
61#include "TClass.h"
62#include "TVirtualPad.h"
63#include "TProfile.h"
64#include "TProfile2D.h"
65#include "TTreeFormula.h"
66#include "TTreeFormulaManager.h"
67#include "TStyle.h"
68#include "Foption.h"
69#include "TTreeResult.h"
70#include "TTreeRow.h"
71#include "TPrincipal.h"
72#include "TChain.h"
73#include "TChainElement.h"
74#include "TF1.h"
75#include "TVirtualFitter.h"
76#include "THLimitsFinder.h"
77#include "TSelectorDraw.h"
78#include "TSelectorEntries.h"
79#include "TPluginManager.h"
80#include "TObjString.h"
81#include "TTreeProxyGenerator.h"
83#include "TTreeIndex.h"
84#include "TChainIndex.h"
85#include "TRefProxy.h"
86#include "TRefArrayProxy.h"
87#include "TVirtualMonitoring.h"
88#include "TTreeCache.h"
89#include "TVirtualMutex.h"
90#include "ThreadLocalStorage.h"
91#include "strlcpy.h"
92#include "snprintf.h"
93
94#include "HFitInterface.h"
95#include "Fit/BinData.h"
96#include "Fit/UnBinData.h"
98
99
101
103
104
105////////////////////////////////////////////////////////////////////////////////
106/// Default Tree constructor.
107
109{
110 fTree = nullptr;
111 fScanFileName = nullptr;
112 fScanRedirect = false;
113 fSelectedRows = 0;
114 fDimension = 0;
115 fHistogram = nullptr;
116 fFormulaList = new TList();
117 fFormulaList->SetOwner(true);
118 fSelector = new TSelectorDraw();
119 fSelectorFromFile = nullptr;
120 fSelectorClass = nullptr;
121 fSelectorUpdate = nullptr;
122 fInput = new TList();
123 fInput->Add(new TNamed("varexp",""));
124 fInput->Add(new TNamed("selection",""));
126 {
128 gROOT->GetListOfCleanups()->Add(this);
129 }
130 TClass::GetClass("TRef")->AdoptReferenceProxy(new TRefProxy());
131 TClass::GetClass("TRefArray")->AdoptReferenceProxy(new TRefArrayProxy());
132}
133
134////////////////////////////////////////////////////////////////////////////////
135/// Tree destructor.
136
138{
139 delete fFormulaList;
140 delete fSelector;
142 fInput->Delete();
143 delete fInput;
145 gROOT->GetListOfCleanups()->Remove(this);
146}
147
148////////////////////////////////////////////////////////////////////////////////
149/// Build the index for the tree (see TTree::BuildIndex)
150/// In some cases, a warning is printed about switching from
151/// TChainIndex to TTreeIndex when indices in files are not sorted. Note
152/// that unsorted indices lead to a significant performance degradation, not only when building the index itself,
153/// but also later on when performing the joining with other datasets. Thus, in general, it is not recommended to
154/// ignore the warning except for special cases with prior knowledge that sorting the files and/or entries is actually
155/// more expensive, or just not possible.
156
158{
160 if (dynamic_cast<const TChain*>(T)) {
162 if (index->IsZombie()) {
163 delete index;
164 Warning("BuildIndex", "Creating a TChainIndex unsuccessful - switching to TTreeIndex (much slower)");
165 }
166 else
167 return index;
168 }
170}
171
172////////////////////////////////////////////////////////////////////////////////
173/// Copy a Tree with selection, make a clone of this Tree header, then copy the
174/// selected entries.
175///
176/// - selection is a standard selection expression (see TTreePlayer::Draw)
177/// - option is reserved for possible future use
178/// - nentries is the number of entries to process (default is all)
179/// - first is the first entry to process (default is 0)
180///
181/// IMPORTANT: The copied tree stays connected with this tree until this tree
182/// is deleted. In particular, any changes in branch addresses
183/// in this tree are forwarded to the clone trees. Any changes
184/// made to the branch addresses of the copied trees are over-ridden
185/// anytime this tree changes its branch addresses.
186/// Once this tree is deleted, all the addresses of the copied tree
187/// are reset to their default values.
188///
189/// The following example illustrates how to copy some events from the Tree
190/// generated in $ROOTSYS/test/Event
191/// ~~~{.cpp}
192/// gSystem->Load("libEvent");
193/// TFile f("Event.root");
194/// TTree *T = (TTree*)f.Get("T");
195/// Event *event = new Event();
196/// T->SetBranchAddress("event",&event);
197/// TFile f2("Event2.root","recreate");
198/// TTree *T2 = T->CopyTree("fNtrack<595");
199/// T2->Write();
200/// ~~~
201
204{
205
206 // we make a copy of the tree header
207 TTree *tree = fTree->CloneTree(0);
208 if (tree == nullptr) return nullptr;
209
210 // The clone should not delete any shared i/o buffers.
212 Int_t nb = branches->GetEntriesFast();
213 for (Int_t i = 0; i < nb; ++i) {
214 TBranch* br = (TBranch*) branches->UncheckedAt(i);
215 if (br->InheritsFrom(TBranchElement::Class())) {
216 ((TBranchElement*) br)->ResetDeleteObject();
217 }
218 }
219
222
223 // Compile selection expression if there is one
224 TTreeFormula *select = nullptr; // no need to interfere with fSelect since we
225 // handle the loop explicitly below and can call
226 // UpdateFormulaLeaves ourselves.
227 if (strlen(selection)) {
228 select = new TTreeFormula("Selection",selection,fTree);
229 if (!select || !select->GetNdim()) {
230 delete select;
231 delete tree;
232 return nullptr;
233 }
234 fFormulaList->Add(select);
235 }
236
237 //loop on the specified entries
238 Int_t tnumber = -1;
241 if (entryNumber < 0) break;
243 if (localEntry < 0) break;
244 if (tnumber != fTree->GetTreeNumber()) {
246 if (select) select->UpdateFormulaLeaves();
247 }
248 if (select) {
249 Int_t ndata = select->GetNdata();
250 bool keep = false;
251 for(Int_t current = 0; current<ndata && !keep; current++) {
252 keep |= (select->EvalInstance(current) != 0);
253 }
254 if (!keep) continue;
255 }
257 tree->Fill();
258 }
260 return tree;
261}
262
263////////////////////////////////////////////////////////////////////////////////
264/// Delete any selector created by this object.
265/// The selector has been created using TSelector::GetSelector(file)
266
268{
270 if (fSelectorClass->IsLoaded()) {
271 delete fSelectorFromFile;
272 }
273 }
274 fSelectorFromFile = nullptr;
275 fSelectorClass = nullptr;
276}
277
278namespace {
279
280// TTree::Draw can take the name of a C++ script file (optionally with an
281// ACLiC mode suffix and arguments, e.g. "myscript.C+(2)") instead of a
282// TTreeFormula expression for both the variable expression and the
283// selection; see "Drawing a user function accessing the TTree data directly"
284// in the TTree::Draw documentation. Determine whether 'expression' names
285// such a script file.
286//
287// Besides checking that the file exists, we require that the candidate has an
288// extension: TTreeProxyGenerator::WriteProxy() needs one to derive the name of
289// the function to call. This avoids misinterpreting an expression like "abs(x)"
290// as the script "abs" called with argument "(x)" whenever an unrelated file
291// with that name happens to exist in the current directory (JIRA ROOT-8000).
292
293bool IsScriptFile(const char *expression)
294{
295 if (!expression || !expression[0])
296 return false;
297
298 const TString candidate = expression;
299
300 // These tokens only appear in TTreeFormula expressions, never in the name of
301 // a script file, so their presence rules out a script file.
302 static const std::vector<TString> formulaTokens = {
303 "Alt$", "Entries$", "LocalEntries$", "Length$", "Entry$", "LocalEntry$", "Min$",
304 "Max$", "MinIf$", "MaxIf$", "Iteration$", "Sum$", ">", "<"};
305 for (const TString &token : formulaTokens)
306 if (candidate.Index(token) >= 0)
308
309 TString aclicMode, arguments, io;
311 const Ssiz_t dot_pos = realname.Last('.');
312 if (dot_pos == kNPOS || dot_pos < realname.Last('/'))
313 return false;
314
316}
317
318} // anonymous namespace
319
320////////////////////////////////////////////////////////////////////////////////
321/// Draw the result of a C++ script.
322///
323/// The macrofilename and optionally cutfilename are assumed to contain
324/// at least a method with the same name as the file. The method
325/// should return a value that can be automatically cast to
326/// respectively a double and a boolean.
327///
328/// Both methods will be executed in a context such that the
329/// branch names can be used as C++ variables. This is
330/// accomplished by generating a TTreeProxy (see MakeProxy)
331/// and including the files in the proper location.
332///
333/// If the branch name can not be used a proper C++ symbol name,
334/// it will be modified as follow:
335/// - white spaces are removed
336/// - if the leading character is not a letter, an underscore is inserted
337/// - < and > are replace by underscores
338/// - * is replaced by st
339/// - & is replaced by rf
340///
341/// If a cutfilename is specified, for each entry, we execute
342/// ~~~{.cpp}
343/// if (cutfilename()) htemp->Fill(macrofilename());
344/// ~~~
345/// If no cutfilename is specified, for each entry we execute
346/// ~~~{.cpp}
347/// htemp(macrofilename());
348/// ~~~
349/// The default for the histogram are the same as for
350/// TTreePlayer::DrawSelect
351
353 const char *macrofilename, const char *cutfilename,
355{
356 if (!macrofilename || strlen(macrofilename)==0) return 0;
357
359 TString arguments;
360 TString io;
364
365 // we ignore the aclicMode for the cutfilename!
367
369
371
372 selname = gp.GetFileName();
373 if (aclicMode.Length()==0) {
374 Warning("DrawScript","TTreeProxy does not work in interpreted mode yet. The script will be compiled.");
375 aclicMode = "+";
376 }
377 selname.Append(aclicMode);
378
379 Info("DrawScript","%s",Form("Will process tree/chain using %s",selname.Data()));
381 fTree->SetNotify(nullptr);
382
383 // could delete the file selname+".h"
384 // However this would remove the optimization of avoiding a useless
385 // recompilation if the user ask for the same thing twice!
386
387 return result;
388}
389
390////////////////////////////////////////////////////////////////////////////////
391/// Draw expression varexp for specified entries that matches the selection.
392/// Returns -1 in case of error or number of selected events in case of success.
393///
394/// See the documentation of TTree::Draw for the complete details.
395
397{
398 if (fTree->GetEntriesFriend() == 0) return 0;
399
400 // Let's see if we have a filename as arguments instead of
401 // a TTreeFormula expression.
402
403 if (IsScriptFile(varexp0)) {
404
406 Error("DrawSelect",
407 "Drawing using a C++ macro currently requires that both the expression and the selection are "
408 "files\n\t\"%s\" is not a file",
409 selection);
410 return 0;
411 }
412 return DrawScript("generatedSel",varexp0,selection,option,nentries,firstentry);
413
414 } else if (IsScriptFile(selection)) {
415
416 Error("DrawSelect",
417 "Drawing using a C++ macro currently requires that both the expression and the selection are "
418 "files\n\t\"%s\" is not a file",
419 varexp0);
420 return 0;
421 }
422
425 TEntryList *elist = fTree->GetEntryList();
426 if (evlist && elist){
427 elist->SetBit(kCanDelete, true);
428 }
429 TNamed *cvarexp = (TNamed*)fInput->FindObject("varexp");
430 TNamed *cselection = (TNamed*)fInput->FindObject("selection");
431 if (cvarexp) cvarexp->SetTitle(varexp0);
432 if (cselection) cselection->SetTitle(selection);
433
434 TString opt = option;
435 opt.ToLower();
436 bool optpara = false;
437 bool optcandle = false;
438 bool optgl5d = false;
439 bool optnorm = false;
440 if (opt.Contains("norm")) {optnorm = true; opt.ReplaceAll("norm",""); opt.ReplaceAll(" ","");}
441 if (opt.Contains("para")) optpara = true;
442 if (opt.Contains("candle")) optcandle = true;
443 if (opt.Contains("gl5d")) optgl5d = true;
444 bool pgl = gStyle->GetCanvasPreferGL();
445 if (optgl5d) {
447 if (!gPad) {
448 if (pgl == false) gStyle->SetCanvasPreferGL(true);
449 gROOT->ProcessLineFast("new TCanvas();");
450 }
451 }
452
453 // Do not process more than fMaxEntryLoop entries
455
456 // invoke the selector
460
461 //*-* an Event List
462 if (fDimension <= 0) {
464 if (fSelector->GetCleanElist()) {
465 // We are in the case where the input list was reset!
466 fTree->SetEntryList(elist);
467 delete fSelector->GetObject();
468 }
469 return nrows;
470 }
471
472 // Draw generated histogram
475 bool draw = false;
476 if (!drawflag && !opt.Contains("goff")) draw = true;
478 if (optnorm) {
480 if (sumh != 0) fHistogram->Scale(1./sumh);
481 }
482
483 if (drawflag) {
484 if (gPad) {
485 if (!opt.Contains("same") && !opt.Contains("goff")) {
486 gPad->DrawFrame(-1.,-1.,1.,1.);
487 TText *text_empty = new TText(0.,0.,"Empty");
488 text_empty->SetTextAlign(22);
489 text_empty->SetTextFont(42);
490 text_empty->SetTextSize(0.1);
491 text_empty->SetTextColor(1);
492 text_empty->Draw();
493 }
494 } else {
495 Warning("DrawSelect", "The selected TTree subset is empty.");
496 }
497 }
498
499 //*-*- 1-D distribution
500 if (fDimension == 1 && !(optpara||optcandle)) {
502 if (draw) fHistogram->Draw(opt.Data());
503
504 //*-*- 2-D distribution
505 } else if (fDimension == 2 && !(optpara||optcandle)) {
508 if (action == 4) {
509 if (draw) fHistogram->Draw(opt.Data());
510 } else {
511 bool graph = false;
512 Int_t l = opt.Length();
513 if (l == 0 || opt == "same") graph = true;
514 if (opt.Contains("p") || opt.Contains("*") || opt.Contains("l")) graph = true;
515 if (opt.Contains("surf") || opt.Contains("lego") || opt.Contains("cont")) graph = false;
516 if (opt.Contains("col") || opt.Contains("hist") || opt.Contains("scat")) graph = false;
517 if (!graph) {
518 if (draw) fHistogram->Draw(opt.Data());
519 } else {
521 }
522 }
523 //*-*- 3-D distribution
524 } else if (fDimension == 3 && !(optpara||optcandle)) {
528 if (action == 23) {
529 if (draw) fHistogram->Draw(opt.Data());
530 } else if (action == 33) {
531 if (draw) {
532 if (opt.Contains("z")) fHistogram->Draw("func z");
533 else fHistogram->Draw("func");
534 }
535 } else {
536 Int_t noscat = opt.Length();
537 if (opt.Contains("same")) noscat -= 4;
538 if (noscat) {
539 if (draw) fHistogram->Draw(opt.Data());
540 } else {
542 }
543 }
544 //*-*- 4-D distribution
545 } else if (fDimension == 4 && !(optpara||optcandle)) {
549 if (draw) fHistogram->Draw(opt.Data());
552 for (Int_t col=0;col<ncolors;col++) {
553 if (!pms) continue;
554 TPolyMarker3D *pm3d = (TPolyMarker3D*)pms->UncheckedAt(col);
555 if (draw) pm3d->Draw();
556 }
557 //*-*- Parallel Coordinates or Candle chart.
558 } else if (fDimension > 1 && (optpara || optcandle)) {
559 if (draw) {
561 fTree->Draw(">>enlist",selection,"entrylist",nentries,firstentry);
562 TObject *enlist = gDirectory->FindObject("enlist");
563 gROOT->ProcessLine(Form("TParallelCoord::SetEntryList((TParallelCoord*)0x%zx,(TEntryList*)0x%zx)",
564 (size_t)para, (size_t)enlist));
565 }
566 //*-*- 5d with gl
567 } else if (fDimension == 5 && optgl5d) {
568 gROOT->ProcessLineFast(Form("(new TGL5DDataSet((TTree *)0x%zx))->Draw(\"%s\");", (size_t)fTree, opt.Data()));
570 }
571
573 return fSelectedRows;
574}
575
576////////////////////////////////////////////////////////////////////////////////
577/// Fit a projected item(s) from a Tree.
578/// Returns -1 in case of error or number of selected events in case of success.
579///
580/// The formula is a TF1 expression.
581///
582/// See TTree::Draw for explanations of the other parameters.
583///
584/// By default the temporary histogram created is called htemp.
585/// If varexp contains >>hnew , the new histogram created is called hnew
586/// and it is kept in the current directory.
587/// Example:
588/// ~~~{.cpp}
589/// tree.Fit("pol4","sqrt(x)>>hsqrt","y>0")
590/// will fit sqrt(x) and save the histogram as "hsqrt" in the current
591/// directory.
592/// ~~~
593///
594/// The function returns the status of the histogram fit (see TH1::Fit)
595/// If no entries were selected, the function returns -1;
596/// (i.e. fitResult is null if the fit is OK)
597
599{
600 Int_t nch = option ? strlen(option) + 10 : 10;
601 char *opt = new char[nch];
602 if (option) strlcpy(opt,option,nch-1);
603 else strlcpy(opt,"goff",5);
604
606
607 delete [] opt;
608 Int_t fitResult = -1;
609
610 if (fHistogram && nsel > 0) {
611 fitResult = fHistogram->Fit(formula,option,goption);
612 }
613 return fitResult;
614}
615
616////////////////////////////////////////////////////////////////////////////////
617/// Return the number of entries matching the selection.
618/// Return -1 in case of errors.
619///
620/// If the selection uses any arrays or containers, we return the number
621/// of entries where at least one element match the selection.
622/// GetEntries is implemented using the selector class TSelectorEntries,
623/// which can be used directly (see code in TTreePlayer::GetEntries) for
624/// additional option.
625/// If SetEventList was used on the TTree or TChain, only that subset
626/// of entries will be considered.
627
629{
631 fTree->Process(&s);
632 fTree->SetNotify(nullptr);
633 return s.GetSelectedRows();
634}
635
636////////////////////////////////////////////////////////////////////////////////
637/// return the number of entries to be processed
638/// this function checks that nentries is not bigger than the number
639/// of entries in the Tree or in the associated TEventlist
640
642{
644 if (lastentry > fTree->GetEntriesFriend()-1) {
647 }
648 TEntryList *elist = fTree->GetEntryList();
649 if (elist && elist->GetN() < nentries) nentries = elist->GetN();
650 return nentries;
651}
652
653////////////////////////////////////////////////////////////////////////////////
654/// Return name corresponding to colindex in varexp.
655///
656/// - varexp is a string of names separated by :
657/// - index is an array with pointers to the start of name[i] in varexp
658
660{
661 TTHREAD_TLS_DECL(std::string,column);
662 if (colindex<0 ) return "";
663 Int_t i1,n;
664 i1 = index[colindex] + 1;
665 n = index[colindex+1] - i1;
666 column = varexp(i1,n).Data();
667 // return (const char*)Form((const char*)column);
668 return column.c_str();
669}
670
671////////////////////////////////////////////////////////////////////////////////
672/// Return the name of the branch pointer needed by MakeClass/MakeSelector
673
674static TString R__GetBranchPointerName(TLeaf *leaf, bool replace = true)
675{
676 TLeaf *leafcount = leaf->GetLeafCount();
677 TBranch *branch = leaf->GetBranch();
678
679 TString branchname( branch->GetName() );
680
681 if ( branch->GetNleaves() <= 1 ) {
682 if (branch->IsA() != TBranchObject::Class()) {
683 if (!leafcount) {
684 TBranch *mother = branch->GetMother();
685 const char* ltitle = leaf->GetTitle();
686 if (mother && mother!=branch) {
687 branchname = mother->GetName();
688 if (branchname[branchname.Length()-1]!='.') {
689 branchname += ".";
690 }
691 if (strncmp(branchname.Data(),ltitle,branchname.Length())==0) {
692 branchname = "";
693 }
694 } else {
695 branchname = "";
696 }
698 }
699 }
700 }
701 if (replace) {
702 char *bname = (char*)branchname.Data();
703 char *twodim = (char*)strstr(bname,"[");
704 if (twodim) *twodim = 0;
705 while (*bname) {
706 if (*bname == '.') *bname='_';
707 if (*bname == ',') *bname='_';
708 if (*bname == ':') *bname='_';
709 if (*bname == '<') *bname='_';
710 if (*bname == '>') *bname='_';
711 if (*bname == '#') *bname='_';
712 if (*bname == '@') *bname='_';
713 bname++;
714 }
715 }
716 return branchname;
717}
718
719////////////////////////////////////////////////////////////////////////////////
720/// Generate skeleton analysis class for this Tree.
721///
722/// The following files are produced: classname.h and classname.C
723/// If classname is 0, classname will be called "nameoftree.
724///
725/// The generated code in classname.h includes the following:
726/// - Identification of the original Tree and Input file name
727/// - Definition of analysis class (data and functions)
728/// - the following class functions:
729/// - constructor (connecting by default the Tree file)
730/// - GetEntry(Long64_t entry)
731/// - Init(TTree *tree) to initialize a new TTree
732/// - Show(Long64_t entry) to read and Dump entry
733///
734/// The generated code in classname.C includes only the main
735/// analysis function Loop.
736///
737/// To use this function:
738/// - connect your Tree file (eg: TFile f("myfile.root");)
739/// - T->MakeClass("MyClass");
740///
741/// where T is the name of the Tree in file myfile.root
742/// and MyClass.h, MyClass.C the name of the files created by this function.
743/// In a ROOT session, you can do:
744/// ~~~{.cpp}
745/// root> .L MyClass.C
746/// root> MyClass t
747/// root> t.GetEntry(12); // Fill t data members with entry number 12
748/// root> t.Show(); // Show values of entry 12
749/// root> t.Show(16); // Read and show values of entry 16
750/// root> t.Loop(); // Loop on all entries
751/// ~~~
752/// NOTE: Do not use the code generated for one Tree in case of a TChain.
753/// Maximum dimensions calculated on the basis of one TTree only
754/// might be too small when processing all the TTrees in one TChain.
755/// Instead of myTree.MakeClass(.., use myChain.MakeClass(..
756
757Int_t TTreePlayer::MakeClass(const char *classname, const char *option)
758{
759 TString opt = option;
760 opt.ToLower();
761
762 // Connect output files
763 const TString fileNameStem = classname ? classname : fTree->GetName();
766 Warning("TTreePlayer::MakeClass", "The %s name provided ('%s') is not a valid C++ identifier and will be converted to '%s'.",(classname ? "class" : "tree"), fileNameStem.Data(), cppClassName.Data());
767
769 thead.Form("%s.h", fileNameStem.Data());
770 FILE *fp = fopen(thead, "w");
771 if (!fp) {
772 Error("MakeClass","cannot open output file %s", thead.Data());
773 return 3;
774 }
776 tcimp.Form("%s.C", fileNameStem.Data());
777 FILE *fpc = fopen(tcimp, "w");
778 if (!fpc) {
779 Error("MakeClass","cannot open output file %s", tcimp.Data());
780 fclose(fp);
781 return 3;
782 }
784 if (fTree->GetDirectory() && fTree->GetDirectory()->GetFile()) {
785 treefile = fTree->GetDirectory()->GetFile()->GetName();
786 } else {
787 treefile = "Memory Directory";
788 }
789 // In the case of a chain, the GetDirectory information usually does
790 // pertain to the Chain itself but to the currently loaded tree.
791 // So we can not rely on it.
793 bool isHbook = fTree->InheritsFrom("THbookTree");
794 if (isHbook)
796
797//======================Generate classname.h=====================
798 // Print header
800 Int_t nleaves = leaves ? leaves->GetEntriesFast() : 0;
801 TDatime td;
802 fprintf(fp,"//////////////////////////////////////////////////////////\n");
803 fprintf(fp,"// This class has been automatically generated on\n");
804 fprintf(fp,"// %s by ROOT version %s\n",td.AsString(),gROOT->GetVersion());
805 if (!ischain) {
806 fprintf(fp,"// from TTree %s/%s\n",fTree->GetName(),fTree->GetTitle());
807 fprintf(fp,"// found on file: %s\n",treefile.Data());
808 } else {
809 fprintf(fp,"// from TChain %s/%s\n",fTree->GetName(),fTree->GetTitle());
810 }
811 fprintf(fp,"//////////////////////////////////////////////////////////\n");
812 fprintf(fp,"\n");
813 fprintf(fp,"#ifndef %s_h\n",cppClassName.Data());
814 fprintf(fp,"#define %s_h\n",cppClassName.Data());
815 fprintf(fp,"\n");
816 fprintf(fp,"#include <TROOT.h>\n");
817 fprintf(fp,"#include <TChain.h>\n");
818 fprintf(fp,"#include <TFile.h>\n");
819 if (isHbook) fprintf(fp,"#include <THbookFile.h>\n");
820 if (opt.Contains("selector")) fprintf(fp,"#include <TSelector.h>\n");
821
822 // See if we can add any #include about the user data.
823 Int_t l;
824 fprintf(fp,"\n// Header file for the classes stored in the TTree if any.\n");
826 listOfHeaders.SetOwner();
827 constexpr auto length = std::char_traits<char>::length;
828 for (l=0;l<nleaves;l++) {
829 TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
830 TBranch *branch = leaf->GetBranch();
831 TClass *cl = TClass::GetClass(branch->GetClassName());
832 if (cl && cl->IsLoaded() && !listOfHeaders.FindObject(cl->GetName())) {
833 const char *declfile = cl->GetDeclFileName();
834 if (declfile && declfile[0]) {
835 static const char *precstl = "prec_stl/";
836 static const unsigned int precstl_len = strlen(precstl);
837 static const char *rootinclude = "include/";
838 static const unsigned int rootinclude_len = strlen(rootinclude);
840 fprintf(fp,"#include <%s>\n",declfile+precstl_len);
842 } else if (strncmp(declfile,"/usr/include/",13) == 0) {
843 fprintf(fp,"#include <%s>\n",declfile+length("/include/c++/"));
844 listOfHeaders.Add(new TNamed(cl->GetName(),declfile+length("/include/c++/")));
845 } else if (strstr(declfile,"/include/c++/") != nullptr) {
846 fprintf(fp,"#include <%s>\n",declfile+length("/include/c++/"));
847 listOfHeaders.Add(new TNamed(cl->GetName(),declfile+length("/include/c++/")));
848 } else if (strncmp(declfile,rootinclude,rootinclude_len) == 0) {
849 fprintf(fp,"#include <%s>\n",declfile+rootinclude_len);
851 } else {
852 fprintf(fp,"#include \"%s\"\n",declfile);
853 listOfHeaders.Add(new TNamed(cl->GetName(),declfile));
854 }
855 }
856 }
857 }
858
859 // First loop on all leaves to generate dimension declarations
860 Int_t len, lenb;
861 char blen[1024];
862 char *bname;
863 Int_t *leaflen = new Int_t[nleaves];
865 for (l=0;l<nleaves;l++) {
866 TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
867 leafs->AddAt(new TObjString(leaf->GetName()),l);
868 leaflen[l] = leaf->GetMaximum();
869 }
870 if (ischain) {
871 // In case of a chain, one must find the maximum dimension of each leaf
872 // One must be careful and not assume that all Trees in the chain
873 // have the same leaves and in the same order!
874 TChain *chain = (TChain*)fTree;
875 Int_t ntrees = chain->GetNtrees();
876 for (Int_t file=0;file<ntrees;file++) {
877 Long64_t first = chain->GetTreeOffset()[file];
878 chain->LoadTree(first);
879 for (l=0;l<nleaves;l++) {
880 TObjString *obj = (TObjString*)leafs->At(l);
881 TLeaf *leaf = chain->GetLeaf(obj->GetName());
882 if (leaf) {
883 leaflen[l] = TMath::Max(leaflen[l],leaf->GetMaximum());
884 }
885 }
886 }
887 chain->LoadTree(0);
888 }
889
890 fprintf(fp,"\n");
891 if (opt.Contains("selector")) {
892 fprintf(fp,"class %s : public TSelector {\n",cppClassName.Data());
893 fprintf(fp,"public :\n");
894 fprintf(fp," TTree *fChain; ///<!pointer to the analyzed TTree or TChain\n");
895 } else {
896 fprintf(fp,"class %s {\n",cppClassName.Data());
897 fprintf(fp,"public :\n");
898 fprintf(fp," TTree *fChain; ///<!pointer to the analyzed TTree or TChain\n");
899 fprintf(fp," Int_t fCurrent; ///<!current Tree number in a TChain\n");
900 }
901
902 fprintf(fp,"\n// Fixed size dimensions of array or collections stored in the TTree if any.\n");
904 for (l=0;l<nleaves;l++) {
905 TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
906 strlcpy(blen,leaf->GetName(),sizeof(blen));
907 bname = &blen[0];
908 while (*bname) {
909 if (*bname == '.') *bname='_';
910 if (*bname == ',') *bname='_';
911 if (*bname == ':') *bname='_';
912 if (*bname == '<') *bname='_';
913 if (*bname == '>') *bname='_';
914 bname++;
915 }
916 lenb = strlen(blen);
917 if (blen[lenb-1] == '_') {
918 blen[lenb-1] = 0;
919 len = leaflen[l];
920 if (len <= 0) len = 1;
921 fprintf(fp," static constexpr Int_t kMax%s = %d;\n",blen,len);
922 }
923 }
924 delete [] leaflen;
925 leafs->Delete();
926 delete leafs;
927
928// second loop on all leaves to generate type declarations
929 fprintf(fp,"\n // Declaration of leaf types\n");
932 TBranchElement *bre=nullptr;
933 const char *headOK = " ";
934 const char *headcom = " //";
935 const char *head;
936 char branchname[1024];
937 char aprefix[1024];
938 TObjArray branches(100);
939 TObjArray mustInit(100);
941 mustInitArr.SetOwner(false);
943 for (l=0;l<nleaves;l++) {
944 Int_t kmax = 0;
945 head = headOK;
946 leafStatus[l] = 0;
947 TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
948 len = leaf->GetLen(); if (len<=0) len = 1;
949 leafcount =leaf->GetLeafCount();
950 TBranch *branch = leaf->GetBranch();
951 branchname[0] = 0;
952 strlcpy(branchname,branch->GetName(),sizeof(branchname));
953 strlcpy(aprefix,branch->GetName(),sizeof(aprefix));
954 if (!branches.FindObject(branch)) branches.Add(branch);
955 else leafStatus[l] = 1;
956 if ( branch->GetNleaves() > 1) {
957 // More than one leaf for the branch we need to distinguish them
958 strlcat(branchname,".",sizeof(branchname));
959 strlcat(branchname,leaf->GetTitle(),sizeof(branchname));
960 if (leafcount) {
961 // remove any dimension in title
962 char *dim = (char*)strstr(branchname,"["); if (dim) dim[0] = 0;
963 }
964 } else {
965 strlcpy(branchname,branch->GetName(),sizeof(branchname));
966 }
967 char *twodim = (char*)strstr(leaf->GetTitle(),"][");
968 bname = branchname;
969 while (*bname) {
970 if (*bname == '.') *bname='_';
971 if (*bname == ',') *bname='_';
972 if (*bname == ':') *bname='_';
973 if (*bname == '<') *bname='_';
974 if (*bname == '>') *bname='_';
975 bname++;
976 }
977 if (branch->IsA() == TBranchObject::Class()) {
978 if (branch->GetListOfBranches()->GetEntriesFast()) {leafStatus[l] = 1; continue;}
980 if (!leafobj->GetClass()) {leafStatus[l] = 1; head = headcom;}
981 fprintf(fp,"%s%-15s *%s;\n",head,leafobj->GetTypeName(), leafobj->GetName());
982 if (leafStatus[l] == 0) mustInit.Add(leafobj);
983 continue;
984 }
985 if (leafcount) {
986 len = leafcount->GetMaximum();
987 if (len<=0) len = 1;
988 strlcpy(blen,leafcount->GetName(),sizeof(blen));
989 bname = &blen[0];
990 while (*bname) {
991 if (*bname == '.') *bname='_';
992 if (*bname == ',') *bname='_';
993 if (*bname == ':') *bname='_';
994 if (*bname == '<') *bname='_';
995 if (*bname == '>') *bname='_';
996 bname++;
997 }
998 lenb = strlen(blen);
999 if (blen[lenb-1] == '_') {blen[lenb-1] = 0; kmax = 1;}
1000 else snprintf(blen,sizeof(blen),"%d",len);
1001 }
1002 if (branch->IsA() == TBranchElement::Class()) {
1004 if (bre->GetType() != 3 && bre->GetType() != 4
1005 && bre->GetStreamerType() <= 0 && bre->GetListOfBranches()->GetEntriesFast()) {
1006 leafStatus[l] = 0;
1007 }
1008 if (bre->GetType() == 3 || bre->GetType() == 4) {
1009 fprintf(fp," %-15s %s_;\n","Int_t", ROOT::Internal::GetCppName(branchname).Data());
1010 continue;
1011 }
1012 if (bre->IsBranchFolder()) {
1013 fprintf(fp," %-15s *%s;\n",bre->GetClassName(), ROOT::Internal::GetCppName(branchname).Data());
1014 mustInit.Add(bre);
1015 continue;
1016 } else {
1017 if (branch->GetListOfBranches()->GetEntriesFast()) {leafStatus[l] = 1;}
1018 }
1019 if (bre->GetStreamerType() < 0) {
1020 if (branch->GetListOfBranches()->GetEntriesFast()) {
1021 fprintf(fp,"%s%-15s *%s;\n",headcom,bre->GetClassName(), ROOT::Internal::GetCppName(branchname).Data());
1022 } else {
1023 fprintf(fp,"%s%-15s *%s;\n",head,bre->GetClassName(), ROOT::Internal::GetCppName(branchname).Data());
1024 mustInit.Add(bre);
1025 }
1026 continue;
1027 }
1028 if (bre->GetStreamerType() == 0) {
1029 if (!TClass::GetClass(bre->GetClassName())->HasInterpreterInfo()) {leafStatus[l] = 1; head = headcom;}
1030 fprintf(fp,"%s%-15s *%s;\n",head,bre->GetClassName(), ROOT::Internal::GetCppName(branchname).Data());
1031 if (leafStatus[l] == 0) mustInit.Add(bre);
1032 continue;
1033 }
1034 if (bre->GetStreamerType() > 60) {
1035 TClass *cle = TClass::GetClass(bre->GetClassName());
1036 if (!cle) {leafStatus[l] = 1; continue;}
1037 if (bre->GetStreamerType() == 66) leafStatus[l] = 0;
1038 char brename[256];
1039 strlcpy(brename,bre->GetName(),255);
1040 char *bren = brename;
1041 char *adot = strrchr(bren,'.');
1042 if (adot) bren = adot+1;
1043 char *brack = strchr(bren,'[');
1044 if (brack) *brack = 0;
1045 TStreamerElement *elem = (TStreamerElement*)cle->GetStreamerInfo()->GetElements()->FindObject(bren);
1046 if (elem) {
1047 if (elem->IsA() == TStreamerBase::Class()) {leafStatus[l] = 1; continue;}
1048 if (!TClass::GetClass(elem->GetTypeName())) {leafStatus[l] = 1; continue;}
1049 if (!TClass::GetClass(elem->GetTypeName())->HasInterpreterInfo()) {leafStatus[l] = 1; head = headcom;}
1050 if (leafcount) fprintf(fp,"%s%-15s %s[kMax%s];\n",head,elem->GetTypeName(), ROOT::Internal::GetCppName(branchname).Data(),blen);
1051 else fprintf(fp,"%s%-15s %s;\n",head,elem->GetTypeName(), ROOT::Internal::GetCppName(branchname).Data());
1052 } else {
1053 if (!TClass::GetClass(bre->GetClassName())->HasInterpreterInfo()) {leafStatus[l] = 1; head = headcom;}
1054 fprintf(fp,"%s%-15s %s;\n",head,bre->GetClassName(), ROOT::Internal::GetCppName(branchname).Data());
1055 }
1056 continue;
1057 }
1058 }
1059 if (strlen(leaf->GetTypeName()) == 0) {leafStatus[l] = 1; continue;}
1060 if (leafcount) {
1061 //len = leafcount->GetMaximum();
1062 //strlcpy(blen,leafcount->GetName(),sizeof(blen));
1063 //bname = &blen[0];
1064 //while (*bname) {if (*bname == '.') *bname='_'; bname++;}
1065 //lenb = strlen(blen);
1066 //Int_t kmax = 0;
1067 //if (blen[lenb-1] == '_') {blen[lenb-1] = 0; kmax = 1;}
1068 //else sprintf(blen,"%d",len);
1069
1070 const char *stars = " ";
1071 if (bre && bre->GetBranchCount2()) {
1072 stars = "*";
1073 }
1074 // Dimensions can be in the branchname for a split Object with a fix length C array.
1075 // Theses dimensions HAVE TO be placed after the dimension explicited by leafcount
1077 char *dimInName = (char*) strstr(branchname,"[");
1078 if ( twodim || dimInName ) {
1079 if (dimInName) {
1081 dimInName[0] = 0; // terminate branchname before the array dimensions.
1082 }
1083 if (twodim) dimensions += (char*)(twodim+1);
1084 }
1085 const char* leafcountName = leafcount->GetName();
1086 char b2len[1024];
1087 if (bre && bre->GetBranchCount2()) {
1088 TLeaf * l2 = (TLeaf*)bre->GetBranchCount2()->GetListOfLeaves()->At(0);
1089 strlcpy(b2len,l2->GetName(),sizeof(b2len));
1090 bname = &b2len[0];
1091 while (*bname) {
1092 if (*bname == '.') *bname='_';
1093 if (*bname == ',') *bname='_';
1094 if (*bname == ':') *bname='_';
1095 if (*bname == '<') *bname='_';
1096 if (*bname == '>') *bname='_';
1097 bname++;
1098 }
1100 }
1101 if (dimensions.Length()) {
1102 if (kmax) fprintf(fp," %-14s %s%s[kMax%s]%s; //[%s]\n",leaf->GetTypeName(), stars,
1104 else fprintf(fp," %-14s %s%s[%d]%s; //[%s]\n",leaf->GetTypeName(), stars,
1106 } else {
1107 if (kmax) fprintf(fp," %-14s %s%s[kMax%s]; //[%s]\n",leaf->GetTypeName(), stars, ROOT::Internal::GetCppName(branchname).Data(),blen,leafcountName);
1108 else fprintf(fp," %-14s %s%s[%d]; //[%s]\n",leaf->GetTypeName(), stars, ROOT::Internal::GetCppName(branchname).Data(),len,leafcountName);
1109 }
1110 if (stars[0]=='*') {
1111 TNamed *n;
1112 if (kmax) n = new TNamed(branchname, Form("kMax%s",blen));
1113 else n = new TNamed(branchname, Form("%d",len));
1114 mustInitArr.Add(n);
1115 }
1116 } else {
1117 if (strstr(branchname,"[")) len = 1;
1118 if (len < 2) fprintf(fp," %-15s %s;\n",leaf->GetTypeName(), ROOT::Internal::GetCppName(branchname).Data());
1119 else {
1120 if (twodim) fprintf(fp," %-15s %s%s;\n",leaf->GetTypeName(), ROOT::Internal::GetCppName(branchname).Data(),(char*)strstr(leaf->GetTitle(),"["));
1121 else fprintf(fp," %-15s %s[%d];\n",leaf->GetTypeName(), ROOT::Internal::GetCppName(branchname).Data(),len);
1122 }
1123 }
1124 }
1125
1126// generate list of branches
1127 fprintf(fp,"\n");
1128 fprintf(fp," // List of branches\n");
1129 for (l=0;l<nleaves;l++) {
1130 if (leafStatus[l]) continue;
1131 TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
1132 fprintf(fp," TBranch *b_%s; ///<!\n",R__GetBranchPointerName(leaf).Data());
1133 }
1134
1135// generate class member functions prototypes
1136 if (opt.Contains("selector")) {
1137 fprintf(fp,"\n");
1138 fprintf(fp," %s(TTree * /*tree*/ =0) : fChain(0) { }\n",cppClassName.Data()) ;
1139 fprintf(fp," ~%s() override { }\n",cppClassName.Data());
1140 fprintf(fp," Int_t Version() const override { return 2; }\n");
1141 fprintf(fp," void Begin(TTree *tree) override;\n");
1142 fprintf(fp," void SlaveBegin(TTree *tree) override;\n");
1143 fprintf(fp," void Init(TTree *tree) override;\n");
1144 fprintf(fp," bool Notify() override;\n");
1145 fprintf(fp," bool Process(Long64_t entry) override;\n");
1146 fprintf(fp," Int_t GetEntry(Long64_t entry, Int_t getall = 0) override { return fChain ? fChain->GetTree()->GetEntry(entry, getall) : 0; }\n");
1147 fprintf(fp," void SetOption(const char *option) override { fOption = option; }\n");
1148 fprintf(fp," void SetObject(TObject *obj) override { fObject = obj; }\n");
1149 fprintf(fp," void SetInputList(TList *input) override { fInput = input; }\n");
1150 fprintf(fp," TList* GetOutputList() const override { return fOutput; }\n");
1151 fprintf(fp," void SlaveTerminate() override;\n");
1152 fprintf(fp," void Terminate() override;\n\n");
1153 fprintf(fp," ClassDefOverride(%s,0);\n",cppClassName.Data());
1154 fprintf(fp,"};\n");
1155 fprintf(fp,"\n");
1156 fprintf(fp,"#endif\n");
1157 fprintf(fp,"\n");
1158 } else {
1159 fprintf(fp,"\n");
1160 fprintf(fp," %s(TTree *tree=0);\n",cppClassName.Data());
1161 fprintf(fp," virtual ~%s();\n",cppClassName.Data());
1162 fprintf(fp," virtual Int_t Cut(Long64_t entry);\n");
1163 fprintf(fp," virtual Int_t GetEntry(Long64_t entry);\n");
1164 fprintf(fp," virtual Long64_t LoadTree(Long64_t entry);\n");
1165 fprintf(fp," virtual void Init(TTree *tree);\n");
1166 fprintf(fp," virtual void Loop();\n");
1167 fprintf(fp," virtual bool Notify();\n");
1168 fprintf(fp," virtual void Show(Long64_t entry = -1);\n");
1169 fprintf(fp,"};\n");
1170 fprintf(fp,"\n");
1171 fprintf(fp,"#endif\n");
1172 fprintf(fp,"\n");
1173 }
1174// generate code for class constructor
1175 fprintf(fp,"#ifdef %s_cxx\n",cppClassName.Data());
1176 if (!opt.Contains("selector")) {
1177 fprintf(fp,"%s::%s(TTree *tree) : fChain(0) \n",cppClassName.Data(),cppClassName.Data());
1178 fprintf(fp,"{\n");
1179 fprintf(fp,"// if parameter tree is not specified (or zero), connect the file\n");
1180 fprintf(fp,"// used to generate this class and read the Tree.\n");
1181 fprintf(fp," if (tree == 0) {\n");
1182 if (ischain) {
1183 fprintf(fp,"\n#ifdef SINGLE_TREE\n");
1184 fprintf(fp," // The following code should be used if you want this class to access\n");
1185 fprintf(fp," // a single tree instead of a chain\n");
1186 }
1187 if (isHbook) {
1188 fprintf(fp," THbookFile *f = (THbookFile*)gROOT->GetListOfBrowsables()->FindObject(\"%s\");\n",
1189 treefile.Data());
1190 fprintf(fp," if (!f) {\n");
1191 fprintf(fp," f = new THbookFile(\"%s\");\n",treefile.Data());
1192 fprintf(fp," }\n");
1193 Int_t hid;
1194 sscanf(fTree->GetName(),"h%d",&hid);
1195 fprintf(fp," tree = (TTree*)f->Get(%d);\n\n",hid);
1196 } else {
1197 fprintf(fp," TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject(\"%s\");\n",treefile.Data());
1198 fprintf(fp," if (!f || !f->IsOpen()) {\n");
1199 fprintf(fp," f = new TFile(\"%s\");\n",treefile.Data());
1200 fprintf(fp," }\n");
1201 if (fTree->GetDirectory() != fTree->GetCurrentFile()) {
1202 fprintf(fp," TDirectory * dir = (TDirectory*)f->Get(\"%s\");\n",fTree->GetDirectory()->GetPath());
1203 fprintf(fp," dir->GetObject(\"%s\",tree);\n\n",fTree->GetName());
1204 } else {
1205 fprintf(fp," f->GetObject(\"%s\",tree);\n\n",fTree->GetName());
1206 }
1207 }
1208 if (ischain) {
1209 fprintf(fp,"#else // SINGLE_TREE\n\n");
1210 fprintf(fp," // The following code should be used if you want this class to access a chain\n");
1211 fprintf(fp," // of trees.\n");
1212 fprintf(fp," TChain * chain = new TChain(\"%s\",\"%s\");\n",
1213 fTree->GetName(),fTree->GetTitle());
1214 {
1216 TIter next(((TChain*)fTree)->GetListOfFiles());
1218 while ((element = (TChainElement*)next())) {
1219 fprintf(fp," chain->Add(\"%s/%s\");\n",element->GetTitle(),element->GetName());
1220 }
1221 }
1222 fprintf(fp," tree = chain;\n");
1223 fprintf(fp,"#endif // SINGLE_TREE\n\n");
1224 }
1225 fprintf(fp," }\n");
1226 fprintf(fp," Init(tree);\n");
1227 fprintf(fp,"}\n");
1228 fprintf(fp,"\n");
1229 }
1230
1231// generate code for class destructor()
1232 if (!opt.Contains("selector")) {
1233 fprintf(fp,"%s::~%s()\n",cppClassName.Data(),cppClassName.Data());
1234 fprintf(fp,"{\n");
1235 fprintf(fp," if (!fChain) return;\n");
1236 if (isHbook) {
1237 //fprintf(fp," delete fChain->GetCurrentFile();\n");
1238 } else {
1239 fprintf(fp," delete fChain->GetCurrentFile();\n");
1240 }
1241 fprintf(fp,"}\n");
1242 fprintf(fp,"\n");
1243 }
1244// generate code for class member function GetEntry()
1245 if (!opt.Contains("selector")) {
1246 fprintf(fp,"Int_t %s::GetEntry(Long64_t entry)\n",cppClassName.Data());
1247 fprintf(fp,"{\n");
1248 fprintf(fp,"// Read contents of entry.\n");
1249
1250 fprintf(fp," if (!fChain) return 0;\n");
1251 fprintf(fp," return fChain->GetEntry(entry);\n");
1252 fprintf(fp,"}\n");
1253 }
1254// generate code for class member function LoadTree()
1255 if (!opt.Contains("selector")) {
1256 fprintf(fp,"Long64_t %s::LoadTree(Long64_t entry)\n",cppClassName.Data());
1257 fprintf(fp,"{\n");
1258 fprintf(fp,"// Set the environment to read one entry\n");
1259 fprintf(fp," if (!fChain) return -5;\n");
1260 fprintf(fp," Long64_t centry = fChain->LoadTree(entry);\n");
1261 fprintf(fp," if (centry < 0) return centry;\n");
1262 fprintf(fp," if (fChain->GetTreeNumber() != fCurrent) {\n");
1263 fprintf(fp," fCurrent = fChain->GetTreeNumber();\n");
1264 fprintf(fp," Notify();\n");
1265 fprintf(fp," }\n");
1266 fprintf(fp," return centry;\n");
1267 fprintf(fp,"}\n");
1268 fprintf(fp,"\n");
1269 }
1270
1271// generate code for class member function Init(), first pass = get branch pointer
1272 fprintf(fp,"void %s::Init(TTree *tree)\n",cppClassName.Data());
1273 fprintf(fp,"{\n");
1274 fprintf(fp," // The Init() function is called when the selector needs to initialize\n"
1275 " // a new tree or chain. Typically here the branch addresses and branch\n"
1276 " // pointers of the tree will be set.\n"
1277 " // It is normally not necessary to make changes to the generated\n"
1278 " // code, but the routine can be extended by the user if needed.\n\n");
1279 if (mustInit.Last()) {
1280 TIter next(&mustInit);
1281 TObject *obj;
1282 fprintf(fp," // Set object pointer\n");
1283 while( (obj = next()) ) {
1284 if (obj->InheritsFrom(TBranch::Class())) {
1285 strlcpy(branchname,((TBranch*)obj)->GetName(),sizeof(branchname));
1286 } else if (obj->InheritsFrom(TLeaf::Class())) {
1287 strlcpy(branchname,((TLeaf*)obj)->GetName(),sizeof(branchname));
1288 }
1289 branchname[1023]=0;
1290 bname = branchname;
1291 while (*bname) {
1292 if (*bname == '.') *bname='_';
1293 if (*bname == ',') *bname='_';
1294 if (*bname == ':') *bname='_';
1295 if (*bname == '<') *bname='_';
1296 if (*bname == '>') *bname='_';
1297 bname++;
1298 }
1299 fprintf(fp," %s = 0;\n",ROOT::Internal::GetCppName(branchname).Data() );
1300 }
1301 }
1302 if (mustInitArr.Last()) {
1303 TIter next(&mustInitArr);
1304 TNamed *info;
1305 fprintf(fp," // Set array pointer\n");
1306 while( (info = (TNamed*)next()) ) {
1307 fprintf(fp," for(int i=0; i<%s; ++i) %s[i] = 0;\n",info->GetTitle(),info->GetName());
1308 }
1309 fprintf(fp,"\n");
1310 }
1311 fprintf(fp," // Set branch addresses and branch pointers\n");
1312 fprintf(fp," if (!tree) return;\n");
1313 fprintf(fp," fChain = tree;\n");
1314 if (!opt.Contains("selector")) fprintf(fp," fCurrent = -1;\n");
1315 fprintf(fp," fChain->SetMakeClass(1);\n");
1316 fprintf(fp,"\n");
1317 for (l=0;l<nleaves;l++) {
1318 if (leafStatus[l]) continue;
1319 TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
1320 len = leaf->GetLen();
1321 leafcount =leaf->GetLeafCount();
1322 TBranch *branch = leaf->GetBranch();
1323 strlcpy(aprefix,branch->GetName(),sizeof(aprefix));
1324
1325 if ( branch->GetNleaves() > 1) {
1326 // More than one leaf for the branch we need to distinguish them
1327 strlcpy(branchname,branch->GetName(),sizeof(branchname));
1328 strlcat(branchname,".",sizeof(branchname));
1329 strlcat(branchname,leaf->GetTitle(),sizeof(branchname));
1330 if (leafcount) {
1331 // remove any dimension in title
1332 char *dim = (char*)strstr(branchname,"["); if (dim) dim[0] = 0;
1333 }
1334 } else {
1335 strlcpy(branchname,branch->GetName(),sizeof(branchname));
1336 if (branch->IsA() == TBranchElement::Class()) {
1338 if (bre->GetType() == 3 || bre->GetType()==4) strlcat(branchname,"_",sizeof(branchname));
1339 }
1340 }
1341 bname = branchname;
1342 char *brak = strstr(branchname,"["); if (brak) *brak = 0;
1343 char *twodim = (char*)strstr(bname,"["); if (twodim) *twodim = 0;
1344 while (*bname) {
1345 if (*bname == '.') *bname='_';
1346 if (*bname == ',') *bname='_';
1347 if (*bname == ':') *bname='_';
1348 if (*bname == '<') *bname='_';
1349 if (*bname == '>') *bname='_';
1350 bname++;
1351 }
1352 const char *maybedisable = "";
1353 if (branch != fTree->GetBranch(branch->GetName())) {
1354 Error("MakeClass","The branch named %s (full path name: %s) is hidden by another branch of the same name and its data will not be loaded.",branch->GetName(),R__GetBranchPointerName(leaf,false).Data());
1355 maybedisable = "// ";
1356 }
1357 if (branch->IsA() == TBranchObject::Class()) {
1358 if (branch->GetListOfBranches()->GetEntriesFast()) {
1359 fprintf(fp,"%s fChain->SetBranchAddress(\"%s\",(void*)-1,&b_%s);\n",maybedisable,branch->GetName(),R__GetBranchPointerName(leaf).Data());
1360 continue;
1361 }
1362 strlcpy(branchname,branch->GetName(),sizeof(branchname));
1363 }
1364 if (branch->IsA() == TBranchElement::Class()) {
1365 if (((TBranchElement*)branch)->GetType() == 3) len =1;
1366 if (((TBranchElement*)branch)->GetType() == 4) len =1;
1367 }
1368 if (leafcount) len = leafcount->GetMaximum()+1;
1369 if (len > 1) fprintf(fp,"%s fChain->SetBranchAddress(\"%s\", %s, &b_%s);\n",
1371 else fprintf(fp,"%s fChain->SetBranchAddress(\"%s\", &%s, &b_%s);\n",
1373 }
1374 //must call Notify in case of MakeClass
1375 if (!opt.Contains("selector")) {
1376 fprintf(fp," Notify();\n");
1377 }
1378
1379 fprintf(fp,"}\n");
1380 fprintf(fp,"\n");
1381
1382// generate code for class member function Notify()
1383 fprintf(fp,"bool %s::Notify()\n",cppClassName.Data());
1384 fprintf(fp,"{\n");
1385 fprintf(fp," // The Notify() function is called when a new file is opened. This\n"
1386 " // can be for a new TTree in a TChain. It is normally not necessary to make changes\n"
1387 " // to the generated code, but the routine can be extended by the\n"
1388 " // user if needed. The return value is currently not used.\n\n");
1389 fprintf(fp," return true;\n");
1390 fprintf(fp,"}\n");
1391 fprintf(fp,"\n");
1392
1393// generate code for class member function Show()
1394 if (!opt.Contains("selector")) {
1395 fprintf(fp,"void %s::Show(Long64_t entry)\n",cppClassName.Data());
1396 fprintf(fp,"{\n");
1397 fprintf(fp,"// Print contents of entry.\n");
1398 fprintf(fp,"// If entry is not specified, print current entry\n");
1399
1400 fprintf(fp," if (!fChain) return;\n");
1401 fprintf(fp," fChain->Show(entry);\n");
1402 fprintf(fp,"}\n");
1403 }
1404// generate code for class member function Cut()
1405 if (!opt.Contains("selector")) {
1406 fprintf(fp,"Int_t %s::Cut(Long64_t entry)\n",cppClassName.Data());
1407 fprintf(fp,"{\n");
1408 fprintf(fp,"// This function may be called from Loop.\n");
1409 fprintf(fp,"// returns 1 if entry is accepted.\n");
1410 fprintf(fp,"// returns -1 otherwise.\n");
1411
1412 fprintf(fp," return 1;\n");
1413 fprintf(fp,"}\n");
1414 }
1415 fprintf(fp,"#endif // #ifdef %s_cxx\n",cppClassName.Data());
1416
1417//======================Generate classname.C=====================
1418 if (!opt.Contains("selector")) {
1419 // generate code for class member function Loop()
1420 fprintf(fpc,"#define %s_cxx\n",cppClassName.Data());
1421 fprintf(fpc,"#include \"%s\"\n",thead.Data());
1422 fprintf(fpc,"#include <TH2.h>\n");
1423 fprintf(fpc,"#include <TStyle.h>\n");
1424 fprintf(fpc,"#include <TCanvas.h>\n");
1425 fprintf(fpc,"\n");
1426 fprintf(fpc,"void %s::Loop()\n",cppClassName.Data());
1427 fprintf(fpc,"{\n");
1428 fprintf(fpc,"// In a ROOT session, you can do:\n");
1429 fprintf(fpc,"// root> .L %s.C\n",fileNameStem.Data());
1430 fprintf(fpc,"// root> %s t\n",cppClassName.Data());
1431 fprintf(fpc,"// root> t.GetEntry(12); // Fill t data members with entry number 12\n");
1432 fprintf(fpc,"// root> t.Show(); // Show values of entry 12\n");
1433 fprintf(fpc,"// root> t.Show(16); // Read and show values of entry 16\n");
1434 fprintf(fpc,"// root> t.Loop(); // Loop on all entries\n");
1435 fprintf(fpc,"//\n");
1436 fprintf(fpc,"\n// This is the loop skeleton where:\n");
1437 fprintf(fpc,"// jentry is the global entry number in the chain\n");
1438 fprintf(fpc,"// ientry is the entry number in the current Tree\n");
1439 fprintf(fpc,"// Note that the argument to GetEntry must be:\n");
1440 fprintf(fpc,"// jentry for TChain::GetEntry\n");
1441 fprintf(fpc,"// ientry for TTree::GetEntry and TBranch::GetEntry\n");
1442 fprintf(fpc,"//\n");
1443 fprintf(fpc,"// To read only selected branches, Insert statements like:\n");
1444 fprintf(fpc,"// METHOD1:\n");
1445 fprintf(fpc,"// fChain->SetBranchStatus(\"*\",0); // disable all branches\n");
1446 fprintf(fpc,"// fChain->SetBranchStatus(\"branchname\",1); // activate branchname\n");
1447 fprintf(fpc,"// METHOD2: replace line\n");
1448 fprintf(fpc,"// fChain->GetEntry(jentry); //read all branches\n");
1449 fprintf(fpc,"//by b_branchname->GetEntry(ientry); //read only this branch\n");
1450 fprintf(fpc," if (fChain == 0) return;\n");
1451 fprintf(fpc,"\n Long64_t nentries = fChain->GetEntriesFast();\n");
1452 fprintf(fpc,"\n Long64_t nbytes = 0, nb = 0;\n");
1453 fprintf(fpc," for (Long64_t jentry=0; jentry<nentries;jentry++) {\n");
1454 fprintf(fpc," Long64_t ientry = LoadTree(jentry);\n");
1455 fprintf(fpc," if (ientry < 0) break;\n");
1456 fprintf(fpc," nb = fChain->GetEntry(jentry); nbytes += nb;\n");
1457 fprintf(fpc," // if (Cut(ientry) < 0) continue;\n");
1458 fprintf(fpc," }\n");
1459 fprintf(fpc,"}\n");
1460 }
1461 if (opt.Contains("selector")) {
1462 // generate usage comments and list of includes
1463 fprintf(fpc,"#define %s_cxx\n",cppClassName.Data());
1464 fprintf(fpc,"// The class definition in %s.h has been generated automatically\n",fileNameStem.Data());
1465 fprintf(fpc,"// by the ROOT utility TTree::MakeSelector(). This class is derived\n");
1466 fprintf(fpc,"// from the ROOT class TSelector. For more information on the TSelector\n"
1467 "// framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual.\n\n");
1468 fprintf(fpc,"// The following methods are defined in this file:\n");
1469 fprintf(fpc,"// Begin(): called every time a loop on the tree starts,\n");
1470 fprintf(fpc,"// a convenient place to create your histograms.\n");
1471 fprintf(fpc,"// SlaveBegin(): called after Begin()\n");
1472 fprintf(fpc,"// Process(): called for each event, in this function you decide what\n");
1473 fprintf(fpc,"// to read and fill your histograms.\n");
1474 fprintf(fpc,"// SlaveTerminate: called at the end of the loop on the tree.\n");
1475 fprintf(fpc,"// Terminate(): called at the end of the loop on the tree,\n");
1476 fprintf(fpc,"// a convenient place to draw/fit your histograms.\n");
1477 fprintf(fpc,"//\n");
1478 fprintf(fpc,"// To use this file, try the following session on your Tree T:\n");
1479 fprintf(fpc,"//\n");
1480 fprintf(fpc,"// root> T->Process(\"%s.C\")\n",fileNameStem.Data());
1481 fprintf(fpc,"// root> T->Process(\"%s.C\",\"some options\")\n",fileNameStem.Data());
1482 fprintf(fpc,"// root> T->Process(\"%s.C+\")\n",fileNameStem.Data());
1483 fprintf(fpc,"//\n\n");
1484 fprintf(fpc,"#include \"%s\"\n",thead.Data());
1485 fprintf(fpc,"#include <TH2.h>\n");
1486 fprintf(fpc,"#include <TStyle.h>\n");
1487 fprintf(fpc,"\n");
1488 // generate code for class member function Begin
1489 fprintf(fpc,"\n");
1490 fprintf(fpc,"void %s::Begin(TTree * /*tree*/)\n",cppClassName.Data());
1491 fprintf(fpc,"{\n");
1492 fprintf(fpc," // The Begin() function is called at the start of the query.\n");
1493 fprintf(fpc," // The tree argument is deprecated.\n");
1494 fprintf(fpc,"\n");
1495 fprintf(fpc," TString option = GetOption();\n");
1496 fprintf(fpc,"\n");
1497 fprintf(fpc,"}\n");
1498 // generate code for class member function SlaveBegin
1499 fprintf(fpc,"\n");
1500 fprintf(fpc,"void %s::SlaveBegin(TTree * /*tree*/)\n",cppClassName.Data());
1501 fprintf(fpc,"{\n");
1502 fprintf(fpc," // The SlaveBegin() function is called after the Begin() function.\n");
1503 fprintf(fpc," // The tree argument is deprecated.\n");
1504 fprintf(fpc,"\n");
1505 fprintf(fpc," TString option = GetOption();\n");
1506 fprintf(fpc,"\n");
1507 fprintf(fpc,"}\n");
1508 // generate code for class member function Process
1509 fprintf(fpc,"\n");
1510 fprintf(fpc,"bool %s::Process(Long64_t entry)\n",cppClassName.Data());
1511 fprintf(fpc,"{\n");
1512 fprintf(fpc," // The Process() function is called for each entry in the tree to be processed. The entry argument\n"
1513 " // specifies which entry in the currently loaded tree is to be processed.\n"
1514 " // It can be passed to either %s::GetEntry() or TBranch::GetEntry()\n"
1515 " // to read either all or the required parts of the data.\n"
1516 " //\n"
1517 " // This function should contain the \"body\" of the analysis. It can contain\n"
1518 " // simple or elaborate selection criteria, run algorithms on the data\n"
1519 " // of the event and typically fill histograms.\n"
1520 " //\n"
1521 " // The processing can be stopped by calling Abort().\n"
1522 " //\n"
1523 " // Use fStatus to set the return value of TTree::Process().\n"
1524 " //\n"
1525 " // The return value is currently not used.\n\n", cppClassName.Data());
1526 fprintf(fpc,"\n");
1527 fprintf(fpc," return true;\n");
1528 fprintf(fpc,"}\n");
1529 // generate code for class member function SlaveTerminate
1530 fprintf(fpc,"\n");
1531 fprintf(fpc,"void %s::SlaveTerminate()\n",cppClassName.Data());
1532 fprintf(fpc,"{\n");
1533 fprintf(fpc," // The SlaveTerminate() function is called after all entries or objects\n"
1534 " // have been processed.");
1535 fprintf(fpc,"\n");
1536 fprintf(fpc,"\n");
1537 fprintf(fpc,"}\n");
1538 // generate code for class member function Terminate
1539 fprintf(fpc,"\n");
1540 fprintf(fpc,"void %s::Terminate()\n",cppClassName.Data());
1541 fprintf(fpc,"{\n");
1542 fprintf(fpc," // The Terminate() function is the last function to be called during\n"
1543 " // a query. It always runs on the client, it can be used to present\n"
1544 " // the results graphically or save the results to file.");
1545 fprintf(fpc,"\n");
1546 fprintf(fpc,"\n");
1547 fprintf(fpc,"}\n");
1548 }
1549 Info("MakeClass","Files: %s and %s generated from TTree: %s",thead.Data(),tcimp.Data(),fTree->GetName());
1550 delete [] leafStatus;
1551 fclose(fp);
1552 fclose(fpc);
1553
1554 return 0;
1555}
1556
1557
1558////////////////////////////////////////////////////////////////////////////////
1559/// Generate skeleton function for this Tree
1560///
1561/// The function code is written on filename.
1562/// If filename is 0, filename will be called nameoftree.C
1563///
1564/// The generated code includes the following:
1565/// - Identification of the original Tree and Input file name
1566/// - Connection of the Tree file
1567/// - Declaration of Tree variables
1568/// - Setting of branches addresses
1569/// - A skeleton for the entry loop
1570///
1571/// To use this function:
1572/// - connect your Tree file (eg: TFile f("myfile.root");)
1573/// - T->MakeCode("anal.C");
1574/// where T is the name of the Tree in file myfile.root
1575/// and anal.C the name of the file created by this function.
1576///
1577/// NOTE: Since the implementation of this function, a new and better
1578/// function TTree::MakeClass() has been developed.
1579
1581{
1582// Connect output file
1583 TString tfile;
1584 if (filename)
1585 tfile = filename;
1586 else
1587 tfile.Form("%s.C", fTree->GetName());
1588 FILE *fp = fopen(tfile, "w");
1589 if (!fp) {
1590 Error("MakeCode","cannot open output file %s", tfile.Data());
1591 return 3;
1592 }
1594 if (fTree->GetDirectory() && fTree->GetDirectory()->GetFile()) {
1595 treefile = fTree->GetDirectory()->GetFile()->GetName();
1596 } else {
1597 treefile = "Memory Directory";
1598 }
1599 // In the case of a chain, the GetDirectory information usually does
1600 // pertain to the Chain itself but to the currently loaded tree.
1601 // So we can not rely on it.
1603
1604// Print header
1606 Int_t nleaves = leaves ? leaves->GetEntriesFast() : 0;
1607 TDatime td;
1608 fprintf(fp,"{\n");
1609 fprintf(fp,"//////////////////////////////////////////////////////////\n");
1610 fprintf(fp,"// This file has been automatically generated \n");
1611 fprintf(fp,"// (%s by ROOT version%s)\n",td.AsString(),gROOT->GetVersion());
1612 if (!ischain) {
1613 fprintf(fp,"// from TTree %s/%s\n",fTree->GetName(),fTree->GetTitle());
1614 fprintf(fp,"// found on file: %s\n",treefile.Data());
1615 } else {
1616 fprintf(fp,"// from TChain %s/%s\n",fTree->GetName(),fTree->GetTitle());
1617 }
1618 fprintf(fp,"//////////////////////////////////////////////////////////\n");
1619 fprintf(fp,"\n");
1620 fprintf(fp,"\n");
1621
1622
1623// Reset and file connect
1624 fprintf(fp,"//Reset ROOT and connect tree file\n");
1625 fprintf(fp," gROOT->Reset();\n");
1626 if (ischain) {
1627 fprintf(fp,"\n#ifdef SINGLE_TREE\n");
1628 fprintf(fp," // The following code should be used if you want this code to access\n");
1629 fprintf(fp," // a single tree instead of a chain\n");
1630 }
1631 fprintf(fp," TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject(\"%s\");\n",treefile.Data());
1632 fprintf(fp," if (!f) {\n");
1633 fprintf(fp," f = new TFile(\"%s\");\n",treefile.Data());
1634 fprintf(fp," }\n");
1635 if (fTree->GetDirectory() != fTree->GetCurrentFile()) {
1636 fprintf(fp," TDirectory * dir = (TDirectory*)f->Get(\"%s\");\n",fTree->GetDirectory()->GetPath());
1637 fprintf(fp," dir->GetObject(\"%s\",tree);\n\n",fTree->GetName());
1638 } else {
1639 fprintf(fp," f->GetObject(\"%s\",tree);\n\n",fTree->GetName());
1640 }
1641 if (ischain) {
1642 fprintf(fp,"#else // SINGLE_TREE\n\n");
1643 fprintf(fp," // The following code should be used if you want this code to access a chain\n");
1644 fprintf(fp," // of trees.\n");
1645 fprintf(fp," TChain *%s = new TChain(\"%s\",\"%s\");\n",
1647 {
1649 TIter next(((TChain*)fTree)->GetListOfFiles());
1651 while ((element = (TChainElement*)next())) {
1652 fprintf(fp," %s->Add(\"%s/%s\");\n",fTree->GetName(),element->GetTitle(),element->GetName());
1653 }
1654 }
1655 fprintf(fp,"#endif // SINGLE_TREE\n\n");
1656 }
1657
1658// First loop on all leaves to generate type declarations
1659 fprintf(fp,"//Declaration of leaves types\n");
1660 Int_t len, l;
1663 char *bname;
1664 const char *headOK = " ";
1665 const char *headcom = " //";
1666 const char *head;
1667 char branchname[1024];
1668 for (l=0;l<nleaves;l++) {
1669 TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
1670 len = leaf->GetLen();
1671 leafcount =leaf->GetLeafCount();
1672 TBranch *branch = leaf->GetBranch();
1673 if (branch->GetListOfBranches()->GetEntriesFast() > 0) continue;
1674
1675 if ( branch->GetNleaves() > 1) {
1676 // More than one leaf for the branch we need to distinguish them
1677 strlcpy(branchname,branch->GetName(),sizeof(branchname));
1678 strlcat(branchname,".",sizeof(branchname));
1679 strlcat(branchname,leaf->GetTitle(),sizeof(branchname));
1680 if (leafcount) {
1681 // remove any dimension in title
1682 char *dim = (char*)strstr(branchname,"[");
1683 if (dim) dim[0] = 0;
1684 }
1685 } else {
1686 if (leafcount) strlcpy(branchname,branch->GetName(),sizeof(branchname));
1687 else strlcpy(branchname,leaf->GetTitle(),sizeof(branchname));
1688 }
1689 char *twodim = (char*)strstr(leaf->GetTitle(),"][");
1690 bname = branchname;
1691 while (*bname) {
1692 if (*bname == '.') *bname='_';
1693 if (*bname == ',') *bname='_';
1694 if (*bname == ':') *bname='_';
1695 if (*bname == '<') *bname='_';
1696 if (*bname == '>') *bname='_';
1697 bname++;
1698 }
1699 if (branch->IsA() == TBranchObject::Class()) {
1701 if (leafobj->GetClass()) head = headOK;
1702 else head = headcom;
1703 fprintf(fp,"%s%-15s *%s = 0;\n",head,leafobj->GetTypeName(), leafobj->GetName());
1704 continue;
1705 }
1706 if (leafcount) {
1707 len = leafcount->GetMaximum();
1708 // Dimensions can be in the branchname for a split Object with a fix length C array.
1709 // Theses dimensions HAVE TO be placed after the dimension explicited by leafcount
1710 char *dimInName = (char*) strstr(branchname,"[");
1712 if ( twodim || dimInName ) {
1713 if (dimInName) {
1715 dimInName[0] = 0; // terminate branchname before the array dimensions.
1716 }
1717 if (twodim) dimensions += (char*)(twodim+1);
1718 }
1719 if (dimensions.Length()) {
1720 fprintf(fp," %-15s %s[%d]%s;\n",leaf->GetTypeName(), branchname,len,dimensions.Data());
1721 } else {
1722 fprintf(fp," %-15s %s[%d];\n",leaf->GetTypeName(), branchname,len);
1723 }
1724 } else {
1725 if (strstr(branchname,"[")) len = 1;
1726 if (len < 2) fprintf(fp," %-15s %s;\n",leaf->GetTypeName(), branchname);
1727 else fprintf(fp," %-15s %s[%d];\n",leaf->GetTypeName(), branchname,len);
1728 }
1729 }
1730
1731// Second loop on all leaves to set the corresponding branch address
1732 fprintf(fp,"\n // Set branch addresses.\n");
1733 for (l=0;l<nleaves;l++) {
1734 TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
1735 len = leaf->GetLen();
1736 leafcount =leaf->GetLeafCount();
1737 TBranch *branch = leaf->GetBranch();
1738
1739 if ( branch->GetNleaves() > 1) {
1740 // More than one leaf for the branch we need to distinguish them
1741 strlcpy(branchname,branch->GetName(),sizeof(branchname));
1742 strlcat(branchname,".",sizeof(branchname));
1743 strlcat(branchname,leaf->GetTitle(),sizeof(branchname));
1744 if (leafcount) {
1745 // remove any dimension in title
1746 char *dim = (char*)strstr(branchname,"[");
1747 if (dim) dim[0] = 0;
1748 }
1749 } else {
1750 if (leafcount) strlcpy(branchname,branch->GetName(),sizeof(branchname));
1751 else strlcpy(branchname,leaf->GetTitle(),sizeof(branchname));
1752 }
1753 bname = branchname;
1754 while (*bname) {
1755 if (*bname == '.') *bname='_';
1756 if (*bname == ',') *bname='_';
1757 if (*bname == ':') *bname='_';
1758 if (*bname == '<') *bname='_';
1759 if (*bname == '>') *bname='_';
1760 bname++;
1761 }
1762 char *brak = strstr(branchname,"[");
1763 if (brak) *brak = 0;
1764 head = headOK;
1765 if (branch->IsA() == TBranchObject::Class()) {
1766 strlcpy(branchname,branch->GetName(),sizeof(branchname));
1768 if (!leafobj->GetClass()) head = headcom;
1769 }
1770 if (leafcount) len = leafcount->GetMaximum()+1;
1771 if (len > 1 || brak) fprintf(fp,"%s%s->SetBranchAddress(\"%s\",%s);\n",head,fTree->GetName(),branch->GetName(),branchname);
1772 else fprintf(fp,"%s%s->SetBranchAddress(\"%s\",&%s);\n",head,fTree->GetName(),branch->GetName(),branchname);
1773 }
1774
1775//Generate instructions to make the loop on entries
1776 fprintf(fp,"\n// This is the loop skeleton\n");
1777 fprintf(fp,"// To read only selected branches, Insert statements like:\n");
1778 fprintf(fp,"// %s->SetBranchStatus(\"*\",0); // disable all branches\n",fTree->GetName());
1779 fprintf(fp,"// %s->SetBranchStatus(\"branchname\",1); // activate branchname\n",GetName());
1780 fprintf(fp,"\n Long64_t nentries = %s->GetEntries();\n",fTree->GetName());
1781 fprintf(fp,"\n Long64_t nbytes = 0;\n");
1782 fprintf(fp,"// for (Long64_t i=0; i<nentries;i++) {\n");
1783 fprintf(fp,"// nbytes += %s->GetEntry(i);\n",fTree->GetName());
1784 fprintf(fp,"// }\n");
1785 fprintf(fp,"}\n");
1786
1787 printf("Macro: %s generated from Tree: %s\n",tfile.Data(), fTree->GetName());
1788 fclose(fp);
1789
1790 return 0;
1791}
1792
1793////////////////////////////////////////////////////////////////////////////////
1794/// Generate a skeleton analysis class for this Tree using TBranchProxy.
1795/// TBranchProxy is the base of a class hierarchy implementing an
1796/// indirect access to the content of the branches of a TTree.
1797///
1798/// "proxyClassname" is expected to be of the form:
1799/// ~~~{.cpp}
1800/// [path/]fileprefix
1801/// ~~~
1802/// The skeleton will then be generated in the file:
1803/// ~~~{.cpp}
1804/// fileprefix.h
1805/// ~~~
1806/// located in the current directory or in 'path/' if it is specified.
1807/// The class generated will be named 'fileprefix'.
1808/// If the fileprefix contains a period, the right side of the period
1809/// will be used as the extension (instead of 'h') and the left side
1810/// will be used as the classname.
1811///
1812/// "macrofilename" and optionally "cutfilename" are expected to point
1813/// to source file which will be included in by the generated skeletong.
1814/// Method of the same name as the file(minus the extension and path)
1815/// will be called by the generated skeleton's Process method as follow:
1816/// ~~~{.cpp}
1817/// [if (cutfilename())] htemp->Fill(macrofilename());
1818/// ~~~
1819/// "option" can be used select some of the optional features during
1820/// the code generation. The possible options are:
1821/// - nohist : indicates that the generated ProcessFill should not
1822/// fill the histogram.
1823///
1824/// 'maxUnrolling' controls how deep in the class hierarchy does the
1825/// system 'unroll' class that are not split. 'unrolling' a class
1826/// will allow direct access to its data members a class (this
1827/// emulates the behavior of TTreeFormula).
1828///
1829/// The main features of this skeleton are:
1830///
1831/// * on-demand loading of branches
1832/// * ability to use the 'branchname' as if it was a data member
1833/// * protection against array out-of-bound
1834/// * ability to use the branch data as object (when the user code is available)
1835///
1836/// For example with Event.root, if
1837/// ~~~{.cpp}
1838/// Double_t somepx = fTracks.fPx[2];
1839/// ~~~
1840/// is executed by one of the method of the skeleton,
1841/// somepx will be updated with the current value of fPx of the 3rd track.
1842///
1843/// Both macrofilename and the optional cutfilename are expected to be
1844/// the name of source files which contain at least a free standing
1845/// function with the signature:
1846/// ~~~{.cpp}
1847/// x_t macrofilename(); // i.e function with the same name as the file
1848/// ~~~
1849/// and
1850/// ~~~{.cpp}
1851/// y_t cutfilename(); // i.e function with the same name as the file
1852/// ~~~
1853/// x_t and y_t needs to be types that can convert respectively to a double
1854/// and a bool (because the skeleton uses:
1855/// ~~~{.cpp}
1856/// if (cutfilename()) htemp->Fill(macrofilename());
1857/// ~~~
1858/// This 2 functions are run in a context such that the branch names are
1859/// available as local variables of the correct (read-only) type.
1860///
1861/// Note that if you use the same 'variable' twice, it is more efficient
1862/// to 'cache' the value. For example
1863/// ~~~{.cpp}
1864/// Int_t n = fEventNumber; // Read fEventNumber
1865/// if (n<10 || n>10) { ... }
1866/// ~~~
1867/// is more efficient than
1868/// ~~~{.cpp}
1869/// if (fEventNumber<10 || fEventNumber>10)
1870/// ~~~
1871/// Access to TClonesArray.
1872///
1873/// If a branch (or member) is a TClonesArray (let's say fTracks), you
1874/// can access the TClonesArray itself by using ->:
1875/// ~~~{.cpp}
1876/// fTracks->GetLast();
1877/// ~~~
1878/// However this will load the full TClonesArray object and its content.
1879/// To quickly read the size of the TClonesArray use (note the dot):
1880/// ~~~{.cpp}
1881/// fTracks.GetEntries();
1882/// ~~~
1883/// This will read only the size from disk if the TClonesArray has been
1884/// split.
1885/// To access the content of the TClonesArray, use the [] operator:
1886/// ~~~
1887/// float px = fTracks[i].fPx; // fPx of the i-th track
1888/// ~~~
1889/// Warning:
1890///
1891/// The variable actually use for access are 'wrapper' around the
1892/// real data type (to add autoload for example) and hence getting to
1893/// the data involves the implicit call to a C++ conversion operator.
1894/// This conversion is automatic in most case. However it is not invoked
1895/// in a few cases, in particular in variadic function (like printf).
1896/// So when using printf you should either explicitly cast the value or
1897/// use any intermediary variable:
1898/// ~~~{.cpp}
1899/// fprintf(stdout,"trs[%d].a = %d\n",i,(int)trs.a[i]);
1900/// ~~~
1901/// Also, optionally, the generated selector will also call methods named
1902/// macrofilename_methodname in each of 6 main selector methods if the method
1903/// macrofilename_methodname exist (Where macrofilename is stripped of its
1904/// extension).
1905///
1906/// Concretely, with the script named h1analysisProxy.C,
1907///
1908/// - The method calls the method (if it exist)
1909/// - Begin -> void h1analysisProxy_Begin(TTree*);
1910/// - SlaveBegin -> void h1analysisProxy_SlaveBegin(TTree*);
1911/// - Notify -> bool h1analysisProxy_Notify();
1912/// - Process -> bool h1analysisProxy_Process(Long64_t);
1913/// - SlaveTerminate -> void h1analysisProxy_SlaveTerminate();
1914/// - Terminate -> void h1analysisProxy_Terminate();
1915///
1916/// If a file name macrofilename.h (or .hh, .hpp, .hxx, .hPP, .hXX) exist
1917/// it is included before the declaration of the proxy class. This can
1918/// be used in particular to insure that the include files needed by
1919/// the macro file are properly loaded.
1920///
1921/// The default histogram is accessible via the variable named 'htemp'.
1922///
1923/// If the library of the classes describing the data in the branch is
1924/// loaded, the skeleton will add the needed `include` statements and
1925/// give the ability to access the object stored in the branches.
1926///
1927/// To draw px using the file `hsimple.root (generated by the
1928/// hsimple.C tutorial), we need a file named hsimple.cxx:
1929///
1930/// ~~~{.cpp}
1931/// double hsimple() {
1932/// return px;
1933/// }
1934/// ~~~
1935/// MakeProxy can then be used indirectly via the TTree::Draw interface
1936/// as follow:
1937/// ~~~{.cpp}
1938/// new TFile("hsimple.root")
1939/// ntuple->Draw("hsimple.cxx");
1940/// ~~~
1941/// A more complete example is available in the tutorials directory:
1942/// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
1943/// which reimplement the selector found in h1analysis.C
1944
1946 const char *macrofilename, const char *cutfilename,
1947 const char *option, Int_t maxUnrolling)
1948{
1949 if (macrofilename==nullptr || strlen(macrofilename)==0 ) {
1950 // We currently require a file name for the script
1951 Error("MakeProxy","A file name for the user script is required");
1952 return 0;
1953 }
1954
1956
1957 return 0;
1958}
1959
1960
1961////////////////////////////////////////////////////////////////////////////////
1962/// Generate skeleton selector class for this tree.
1963///
1964/// The following files are produced: classname.h and classname.C.
1965/// If classname is 0, the selector will be called "nameoftree".
1966/// The option can be used to specify the branches that will have a data member.
1967/// - If option is empty, readers will be generated for each leaf.
1968/// - If option is "@", readers will be generated for the topmost branches.
1969/// - Individual branches can also be picked by their name:
1970/// - "X" generates readers for leaves of X.
1971/// - "@X" generates a reader for X as a whole.
1972/// - "@X;Y" generates a reader for X as a whole and also readers for the
1973/// leaves of Y.
1974/// - For further examples see the figure below.
1975///
1976/// \image html ttree_makeselector_option_examples.png
1977///
1978/// The generated code in classname.h includes the following:
1979/// - Identification of the original Tree and Input file name
1980/// - Definition of selector class (data and functions)
1981/// - The following class functions:
1982/// - constructor and destructor
1983/// - void Begin(TTree *tree)
1984/// - void SlaveBegin(TTree *tree)
1985/// - void Init(TTree *tree)
1986/// - bool Notify()
1987/// - bool Process(Long64_t entry)
1988/// - void Terminate()
1989/// - void SlaveTerminate()
1990///
1991/// The selector derives from TSelector.
1992/// The generated code in classname.C includes empty functions defined above.
1993///
1994/// To use this function:
1995/// - connect your Tree file (eg: `TFile f("myfile.root");`)
1996/// - `T->MakeSelector("myselect");`
1997/// where `T` is the name of the Tree in file `myfile.root`
1998/// and `myselect.h`, `myselect.C` the name of the files created by this
1999/// function.
2000///
2001/// In a ROOT session, you can do:
2002/// ~~~ {.cpp}
2003/// root > T->Process("myselect.C")
2004/// ~~~
2006{
2007 if (!classname) classname = fTree->GetName();
2008
2010
2011 return 0;
2012}
2013
2014
2015////////////////////////////////////////////////////////////////////////////////
2016/// Interface to the Principal Components Analysis class.
2017///
2018/// Create an instance of TPrincipal
2019/// Fill it with the selected variables
2020///
2021/// - if option "n" is specified, the TPrincipal object is filled with
2022/// normalized variables.
2023/// - If option "p" is specified, compute the principal components
2024/// - If option "p" and "d" print results of analysis
2025/// - If option "p" and "h" generate standard histograms
2026/// - If option "p" and "c" generate code of conversion functions
2027///
2028/// return a pointer to the TPrincipal object. It is the user responsibility
2029/// to delete this object.
2030///
2031/// The option default value is "np"
2032///
2033/// See TTreePlayer::DrawSelect for explanation of the other parameters.
2034
2036{
2037 TTreeFormula **var;
2038 std::vector<TString> cnames;
2039 TString opt = option;
2040 opt.ToLower();
2041 TPrincipal *principal = nullptr;
2043 Int_t i,nch;
2044 Int_t ncols = 8; // by default first 8 columns are printed only
2046 Int_t nleaves = leaves->GetEntriesFast();
2047 if (nleaves < ncols) ncols = nleaves;
2048 nch = varexp ? strlen(varexp) : 0;
2049
2051
2052//*-*- Compile selection expression if there is one
2053 TTreeFormula *select = nullptr;
2054 if (strlen(selection)) {
2055 select = new TTreeFormula("Selection",selection,fTree);
2056 if (!select) return principal;
2057 if (!select->GetNdim()) { delete select; return principal; }
2058 fFormulaList->Add(select);
2059 }
2060//*-*- if varexp is empty, take first 8 columns by default
2061 int allvar = 0;
2062 if (varexp && !strcmp(varexp, "*")) { ncols = nleaves; allvar = 1; }
2063 if (nch == 0 || allvar) {
2064 for (i=0;i<ncols;i++) {
2065 cnames.push_back( ((TLeaf*)leaves->At(i))->GetName() );
2066 }
2067//*-*- otherwise select only the specified columns
2068 } else {
2070 }
2071 var = new TTreeFormula* [ncols];
2072 Double_t *xvars = new Double_t[ncols];
2073
2074//*-*- Create the TreeFormula objects corresponding to each column
2075 for (i=0;i<ncols;i++) {
2076 var[i] = new TTreeFormula("Var1",cnames[i].Data(),fTree);
2077 fFormulaList->Add(var[i]);
2078 }
2079
2080//*-*- Create a TreeFormulaManager to coordinate the formulas
2082 if (fFormulaList->LastIndex()>=0) {
2084 for(i=0;i<=fFormulaList->LastIndex();i++) {
2085 manager->Add((TTreeFormula*)fFormulaList->At(i));
2086 }
2087 manager->Sync();
2088 }
2089
2090//*-* Build the TPrincipal object
2091 if (opt.Contains("n")) principal = new TPrincipal(ncols, "n");
2092 else principal = new TPrincipal(ncols);
2093
2094//*-*- loop on all selected entries
2095 fSelectedRows = 0;
2096 Int_t tnumber = -1;
2099 if (entryNumber < 0) break;
2101 if (localEntry < 0) break;
2102 if (tnumber != fTree->GetTreeNumber()) {
2104 if (manager) manager->UpdateFormulaLeaves();
2105 }
2106 int ndata = 1;
2107 if (manager && manager->GetMultiplicity()) {
2108 ndata = manager->GetNdata();
2109 }
2110
2111 for(int inst=0;inst<ndata;inst++) {
2112 bool loaded = false;
2113 if (select) {
2114 if (select->EvalInstance(inst) == 0) {
2115 continue;
2116 }
2117 }
2118
2119 if (inst==0) loaded = true;
2120 else if (!loaded) {
2121 // EvalInstance(0) always needs to be called so that
2122 // the proper branches are loaded.
2123 for (i=0;i<ncols;i++) {
2124 var[i]->EvalInstance(0);
2125 }
2126 loaded = true;
2127 }
2128
2129 for (i=0;i<ncols;i++) {
2130 xvars[i] = var[i]->EvalInstance(inst);
2131 }
2132 principal->AddRow(xvars);
2133 }
2134 }
2135
2136 //*-* some actions with principal ?
2137 if (opt.Contains("p")) {
2138 principal->MakePrincipals(); // Do the actual analysis
2139 if (opt.Contains("d")) principal->Print();
2140 if (opt.Contains("h")) principal->MakeHistograms();
2141 if (opt.Contains("c")) principal->MakeCode();
2142 }
2143
2144//*-*- delete temporary objects
2146 delete [] var;
2147 delete [] xvars;
2148
2149 return principal;
2150}
2151
2152////////////////////////////////////////////////////////////////////////////////
2153/// Process this tree executing the TSelector code in the specified filename.
2154/// The return value is -1 in case of error and TSelector::GetStatus() in
2155/// in case of success.
2156///
2157/// The code in filename is loaded (interpreted or compiled, see below),
2158/// filename must contain a valid class implementation derived from TSelector,
2159/// where TSelector has the following member functions:
2160///
2161/// - Begin(): called every time a loop on the tree starts,
2162/// a convenient place to create your histograms.
2163/// - SlaveBegin(): called after Begin().
2164/// - Process(): called for each event, in this function you decide what
2165/// to read and fill your histograms.
2166/// - SlaveTerminate(): called at the end of the loop on the tree
2167/// - Terminate(): called at the end of the loop on the tree,
2168/// a convenient place to draw/fit your histograms.
2169///
2170/// If filename is of the form file.C, the file will be interpreted.
2171/// If filename is of the form file.C++, the file file.C will be compiled
2172/// and dynamically loaded.
2173///
2174/// If filename is of the form file.C+, the file file.C will be compiled
2175/// and dynamically loaded. At next call, if file.C is older than file.o
2176/// and file.so, the file.C is not compiled, only file.so is loaded.
2177///
2178/// ### NOTE 1
2179/// It may be more interesting to invoke directly the other Process function
2180/// accepting a TSelector* as argument.eg
2181/// ~~~{.cpp}
2182/// MySelector *selector = (MySelector*)TSelector::GetSelector(filename);
2183/// selector->CallSomeFunction(..);
2184/// mytree.Process(selector,..);
2185/// ~~~
2186/// ### NOTE 2
2187/// One should not call this function twice with the same selector file
2188/// in the same script. If this is required, proceed as indicated in NOTE1,
2189/// by getting a pointer to the corresponding TSelector,eg
2190///#### workaround 1
2191/// ~~~{.cpp}
2192///void stubs1() {
2193/// TSelector *selector = TSelector::GetSelector("h1test.C");
2194/// TFile *f1 = new TFile("stubs_nood_le1.root");
2195/// TTree *h1 = (TTree*)f1->Get("h1");
2196/// h1->Process(selector);
2197/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
2198/// TTree *h2 = (TTree*)f2->Get("h1");
2199/// h2->Process(selector);
2200///}
2201/// ~~~
2202/// or use ACLIC to compile the selector
2203///#### workaround 2
2204/// ~~~{.cpp}
2205///void stubs2() {
2206/// TFile *f1 = new TFile("stubs_nood_le1.root");
2207/// TTree *h1 = (TTree*)f1->Get("h1");
2208/// h1->Process("h1test.C+");
2209/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
2210/// TTree *h2 = (TTree*)f2->Get("h1");
2211/// h2->Process("h1test.C+");
2212///}
2213/// ~~~
2214
2216{
2217 DeleteSelectorFromFile(); //delete previous selector if any
2218
2219 // This might reloads the script and delete your option
2220 // string! so let copy it first:
2221 TString opt(option);
2222 TString file(filename);
2223 TSelector *selector = TSelector::GetSelector(file);
2224 if (!selector) return -1;
2225
2226 fSelectorFromFile = selector;
2227 fSelectorClass = selector->IsA();
2228
2229 Long64_t nsel = Process(selector,opt,nentries,firstentry);
2230 return nsel;
2231}
2232
2233////////////////////////////////////////////////////////////////////////////////
2234/// Process this tree executing the code in the specified selector.
2235/// The return value is -1 in case of error and TSelector::GetStatus() in
2236/// in case of success.
2237///
2238/// The TSelector class has the following member functions:
2239///
2240/// - Begin(): called every time a loop on the tree starts,
2241/// a convenient place to create your histograms.
2242/// - SlaveBegin(): called after Begin()
2243/// - Process(): called for each event, in this function you decide what
2244/// to read and fill your histograms.
2245/// - SlaveTerminate(): called at the end of the loop on the tree
2246/// - Terminate(): called at the end of the loop on the tree,
2247/// a convenient place to draw/fit your histograms.
2248///
2249/// If the Tree (Chain) has an associated EventList, the loop is on the nentries
2250/// of the EventList, starting at firstentry, otherwise the loop is on the
2251/// specified Tree entries.
2252
2254{
2256
2258
2259 fTree->SetNotify(selector);
2260
2261 selector->SetOption(option);
2262
2263 selector->Begin(fTree); //<===call user initialization function
2264 selector->SlaveBegin(fTree); //<===call user initialization function
2265 if (selector->Version() >= 2)
2266 selector->Init(fTree);
2267 selector->Notify();
2268
2270 gMonitoringWriter->SendProcessingStatus("STARTED",true);
2271
2272 bool process = (selector->GetAbort() != TSelector::kAbortProcess &&
2273 (selector->Version() != 0 || selector->GetStatus() != -1)) ? true : false;
2274 if (process) {
2275
2278
2279 //set the file cache
2280 TTreeCache *tpf = nullptr;
2282 if (curfile) {
2283 tpf = (TTreeCache*)curfile->GetCacheRead(fTree);
2284 if (tpf)
2285 tpf->SetEntryRange(firstentry,firstentry+nentries);
2286 else {
2287 // Create the TTreeCache with the default size unless the
2288 // user explicitly disabled it.
2289 fTree->EnableCache();
2290 tpf = (TTreeCache*)curfile->GetCacheRead(fTree);
2291 if (tpf) tpf->SetEntryRange(firstentry,firstentry+nentries);
2292 }
2293 }
2294
2295 //Create a timer to get control in the entry loop(s)
2296 TProcessEventTimer *timer = nullptr;
2298 if (!gROOT->IsBatch() && interval)
2300
2301 //loop on entries (elist or all entries)
2303
2304 bool useCutFill = selector->Version() == 0;
2305
2306 // force the first monitoring info
2309
2310 //trying to set the first tree, because in the Draw function
2311 //the tree corresponding to firstentry has already been loaded,
2312 //so it is not set in the entry list
2313 fSelectorUpdate = selector;
2315
2316 for (entry = firstentry; entry - firstentry < nentries; entry++) {
2318 if (entryNumber < 0) break;
2319 if (timer && timer->ProcessEvents()) break;
2320 if (gROOT->IsInterrupted()) break;
2322 if (localEntry < 0) break;
2323 if(useCutFill) {
2324 if (selector->ProcessCut(localEntry))
2325 selector->ProcessFill(localEntry); //<==call user analysis function
2326 } else {
2327 selector->Process(localEntry); //<==call user analysis function
2328 }
2331 if (selector->GetAbort() == TSelector::kAbortProcess) break;
2332 if (selector->GetAbort() == TSelector::kAbortFile) {
2333 // Skip to the next file.
2334 entry += fTree->GetTree()->GetEntries() - localEntry;
2335 // Reset the abort status.
2336 selector->ResetAbort();
2337 }
2338 }
2339 delete timer;
2340 //we must reset the cache
2341 {
2343 if (curfile2 && fTree->GetCacheSize() > 0) {
2344 tpf = (TTreeCache*)curfile2->GetCacheRead(fTree);
2345 if (tpf) tpf->SetEntryRange(0,0);
2346 }
2347 }
2348 }
2349
2350 process = (selector->GetAbort() != TSelector::kAbortProcess &&
2351 (selector->Version() != 0 || selector->GetStatus() != -1)) ? true : false;
2352 Long64_t res = (process) ? 0 : -1;
2353 if (process) {
2354 selector->SlaveTerminate(); //<==call user termination function
2355 selector->Terminate(); //<==call user termination function
2356 res = selector->GetStatus();
2357 }
2358 fTree->SetNotify(nullptr); // Detach the selector from the tree.
2359 fSelectorUpdate = nullptr;
2362
2363 return res;
2364}
2365
2366////////////////////////////////////////////////////////////////////////////////
2367/// cleanup pointers in the player pointing to obj
2368
2370{
2371 if (fHistogram == obj) fHistogram = nullptr;
2372}
2373
2374////////////////////////////////////////////////////////////////////////////////
2375/// \brief Loop on Tree and print entries passing selection. Interactive
2376/// pagination break is on by default.
2377/// \param varexp If varexp is 0 (or "") then print only first 8 columns.
2378/// If varexp = "*" print all columns. Otherwise a columns selection can
2379/// be made using "var1:var2:var3".
2380/// \param selection a text formula selecting which entries to scan
2381/// \param firstentry first entry to scan
2382/// \param nentries total number of entries to scan (starting from firstentry). Defaults to all entries.
2383/// \return The function returns the number of entries passing the selection.
2384///
2385/// By default 50 lines are shown and you are asked for `<CR>` or `q`
2386/// to see the next 50 lines. Depending on the Tree structure, one entry might
2387/// be printed across several lines, distinguished by the `Instance` column.
2388/// You can change the default number of lines to be shown before `<CR>` or `q`
2389/// via mytree->SetScanField(maxlines) where maxlines is 50 by default.
2390/// If maxlines is set to 0 all entries of the Tree are shown, and you are
2391/// not prompted to press `<CR>` or `q` to end the loop.
2392///
2393/// This option is interesting when dumping the contents of a Tree to
2394/// an ascii file, eg from the command line.
2395/// ### with ROOT 5
2396/// ~~~{.cpp}
2397/// root [0] tree->SetScanField(0);
2398/// root [1] tree->Scan("*"); >tree.log
2399/// ~~~
2400/// ### with ROOT 6
2401/// ~~~{.cpp}
2402/// root [0] tree->SetScanField(0);
2403/// root [1] .> tree.log
2404/// tree->Scan("*");
2405/// .>
2406/// ~~~
2407/// will create a file `tree.log`
2408/// ### From a script
2409/// One could use TSystem::RedirectOutput, but it's cleaner to call:
2410/// ~~~{.cpp}
2411/// /// tree->SetScanField(0);
2412/// auto logname = TString(tree->GetName())+".log";
2413/// auto player = static_cast<TTreePlayer *>(tree->GetPlayer());
2414/// player->SetScanFileName(logname);
2415/// player->SetScanRedirect(true);
2416/// tree->Scan();
2417/// ~~~
2418///
2419/// Arrays (within an entry) are printed in their linear forms.
2420/// If several arrays with multiple dimensions are printed together,
2421/// they will NOT be synchronized. For example print
2422/// arr1[4][2] and arr2[2][3] will results in a printing similar to:
2423/// ~~~{.cpp}
2424/// ***********************************************
2425/// * Row * Instance * arr1 * arr2 *
2426/// ***********************************************
2427/// * x * 0 * arr1[0][0]* arr2[0][0]*
2428/// * x * 1 * arr1[0][1]* arr2[0][1]*
2429/// * x * 2 * arr1[1][0]* arr2[0][2]*
2430/// * x * 3 * arr1[1][1]* arr2[1][0]*
2431/// * x * 4 * arr1[2][0]* arr2[1][1]*
2432/// * x * 5 * arr1[2][1]* arr2[1][2]*
2433/// * x * 6 * arr1[3][0]* *
2434/// * x * 7 * arr1[3][1]* *
2435/// ~~~
2436/// However, if there is a selection criterion which is an array, then
2437/// all the formulas will be synchronized with the selection criterion
2438/// (see TTreePlayer::DrawSelect for more information).
2439///
2440/// \param option The options string can contains the following parameters:
2441///
2442/// - lenmax=dd
2443/// Where 'dd' is the maximum number of elements per array that should
2444/// be printed. If 'dd' is 0, all elements are printed (this is the
2445/// default)
2446/// - colsize=ss
2447/// Where 'ss' will be used as the default size for all the column
2448/// If this options is not specified, the default column size is 9
2449/// - precision=pp
2450/// Where 'pp' will be used as the default 'precision' for the
2451/// printing format.
2452/// - col=xxx
2453/// Where 'xxx' is colon (:) delimited list of printing format for
2454/// each column. The format string should follow the printf format
2455/// specification. The value given will be prefixed by % and, if no
2456/// conversion specifier is given, will be suffixed by the letter g.
2457/// before being passed to fprintf. If no format is specified for a
2458/// column, the default is used (aka ${colsize}.${precision}g )
2459/// As with printf, a leading minus sign left-justifies the column,
2460/// e.g. `col=-20s` prints a 20-character-wide, left-justified column.
2461///
2462/// For example:
2463/// ~~~{.cpp}
2464/// tree->Scan("a:b:c","","colsize=30 precision=3 col=::20.10:#x:5ld");
2465/// ~~~
2466/// Will print 3 columns, the first 2 columns will be 30 characters long,
2467/// the third columns will be 20 characters long. The printing format used
2468/// for the columns (assuming they are numbers) will be respectively:
2469/// ~~~ {.cpp}
2470/// %30.3g %30.3g %20.10g %#x %5ld
2471/// ~~~
2472
2474 Option_t * option,
2476{
2477 constexpr auto length = std::char_traits<char>::length;
2478 TString opt = option;
2479 opt.ToLower();
2480 UInt_t ui;
2481 UInt_t lenmax = 0;
2483 UInt_t colPrecision = 9;
2484 std::vector<TString> colFormats;
2485 std::vector<Int_t> colSizes;
2486
2487 if (opt.Contains("lenmax=")) {
2488 int start = opt.Index("lenmax=");
2489 int numpos = start + length("lenmax=");
2490 int numlen = 0;
2491 int len = opt.Length();
2492 while( (numpos+numlen<len) && isdigit(opt[numpos+numlen]) ) numlen++;
2493 TString num = opt(numpos,numlen);
2494 opt.Remove(start,length("lenmax")+numlen);
2495
2496 lenmax = atoi(num.Data());
2497 }
2498 if (opt.Contains("colsize=")) {
2499 int start = opt.Index("colsize=");
2500 int numpos = start + length("colsize=");
2501 int numlen = 0;
2502 int len = opt.Length();
2503 while( (numpos+numlen<len) && isdigit(opt[numpos+numlen]) ) numlen++;
2504 TString num = opt(numpos,numlen);
2505 opt.Remove(start,length("size")+numlen);
2506
2507 colDefaultSize = atoi(num.Data());
2509 if (colPrecision>18) colPrecision = 18;
2510 }
2511 if (opt.Contains("precision=")) {
2512 int start = opt.Index("precision=");
2513 int numpos = start + length("precision=");
2514 int numlen = 0;
2515 int len = opt.Length();
2516 while( (numpos+numlen<len) && isdigit(opt[numpos+numlen]) ) numlen++;
2517 TString num = opt(numpos,numlen);
2518 opt.Remove(start,length("precision")+numlen);
2519
2520 colPrecision = atoi(num.Data());
2521 }
2523 if (opt.Contains("col=")) {
2524 int start = opt.Index("col=");
2525 int numpos = start + length("col=");
2526 int numlen = 0;
2527 int len = opt.Length();
2528 while( (numpos+numlen<len) &&
2529 (isdigit(opt[numpos+numlen])
2530 || opt[numpos+numlen] == 'c'
2531 || opt[numpos+numlen] == 'd'
2532 || opt[numpos+numlen] == 'i'
2533 || opt[numpos+numlen] == 'o'
2534 || opt[numpos+numlen] == 'x'
2535 || opt[numpos+numlen] == 'X'
2536 || opt[numpos+numlen] == 'u'
2537 || opt[numpos+numlen] == 'f'
2538 || opt[numpos+numlen] == 'e'
2539 || opt[numpos+numlen] == 'E'
2540 || opt[numpos+numlen] == 'g'
2541 || opt[numpos+numlen] == 'G'
2542 || opt[numpos+numlen] == 'l'
2543 || opt[numpos+numlen] == 'L'
2544 || opt[numpos+numlen] == 'h'
2545 || opt[numpos+numlen] == 's'
2546 || opt[numpos+numlen] == '#'
2547 || opt[numpos+numlen] == '-'
2548 || opt[numpos+numlen]=='.'
2549 || opt[numpos+numlen]==':')) numlen++;
2550 TString flist = opt(numpos,numlen);
2551 opt.Remove(start,length("col")+numlen);
2552
2553 int i = 0;
2554 while(i<flist.Length() && flist[i]==':') {
2555 colFormats.push_back(defFormat);
2556 colSizes.push_back(colDefaultSize);
2557 ++i;
2558 }
2559 for(; i<flist.Length(); ++i) {
2560 int next = flist.Index(":",i);
2561 if (next==i) {
2562 colFormats.push_back(defFormat);
2563 } else if (next==kNPOS) {
2564 colFormats.push_back(flist(i,flist.Length()-i));
2565 i = flist.Length();
2566 } else {
2567 colFormats.push_back(flist(i,next-i));
2568 i = next;
2569 }
2570 // A leading '-' requests left-justification (printf convention) and
2571 // yields a negative size; a size of 0 means "use the default".
2572 Int_t siz = atoi(colFormats[colFormats.size()-1].Data());
2573 colSizes.push_back( siz ? siz : colDefaultSize );
2574 }
2575 }
2576
2577 TTreeFormula **var;
2578 std::vector<TString> cnames;
2581 Int_t i,nch;
2582 UInt_t ncols = 8; // by default first 8 columns are printed only
2583 std::ofstream out;
2584 const char *fname = nullptr;
2586 if (fScanRedirect) {
2587 fTree->SetScanField(0); // no page break if Scan is redirected
2589 if (!fname) fname = "";
2591 if (!lenfile) {
2592 fownname = fTree->GetName();
2593 fownname.Append("-scan.dat");
2594 fname = fownname.Data();
2595 }
2596 out.open(fname, std::ios::out);
2597 if (!out.good ()) {
2598 Error("Scan","Can not open file for redirection");
2599 return 0;
2600 }
2601 }
2603 if (leaves==nullptr) return 0;
2604 UInt_t nleaves = leaves->GetEntriesFast();
2605 if (nleaves < ncols) ncols = nleaves;
2606 nch = varexp ? strlen(varexp) : 0;
2607
2609
2610//*-*- Compile selection expression if there is one
2611 TTreeFormula *select = nullptr;
2612 if (selection && strlen(selection)) {
2613 select = new TTreeFormula("Selection",selection,fTree);
2614 if (!select) return -1;
2615 if (!select->GetNdim()) { delete select; return -1; }
2616 fFormulaList->Add(select);
2617 }
2618//*-*- if varexp is empty, take first 8 columns by default
2619 int allvar = 0;
2620 if (varexp && !strcmp(varexp, "*")) { ncols = nleaves; allvar = 1; }
2621 if (nch == 0 || allvar) {
2622 UInt_t ncs = ncols;
2623 ncols = 0;
2624 for (ui=0;ui<ncs;++ui) {
2625 TLeaf *lf = (TLeaf*)leaves->At(ui);
2626 if (lf->GetBranch()->GetListOfBranches()->GetEntries() > 0) continue;
2627 cnames.push_back( lf->GetBranch()->GetMother()->GetName() );
2628 if (cnames[ncols] == lf->GetName() ) {
2629 // Already complete, let move on.
2630 } else if (cnames[ncols][cnames[ncols].Length()-1]=='.') {
2631 cnames[ncols] = lf->GetBranch()->GetName(); // name of branch already include mother's name
2632 } else {
2633 if (lf->GetBranch()->GetMother()->IsA()->InheritsFrom(TBranchElement::Class())) {
2634 TBranchElement *mother = (TBranchElement*)lf->GetBranch()->GetMother();
2635 if (mother->GetType() == 3 || mother->GetType() == 4) {
2636 // The name of the mother branch is embedded in the sub-branch names.
2637 cnames[ncols] = lf->GetBranch()->GetName();
2638 ++ncols;
2639 continue;
2640 }
2641 }
2642 if (!strchr(lf->GetBranch()->GetName() ,'[') ) {
2643 cnames[ncols].Append('.');
2644 cnames[ncols].Append( lf->GetBranch()->GetName() );
2645 }
2646 }
2647 if (lf->GetBranch()->IsA() == TBranch::Class() ||
2648 strcmp( lf->GetBranch()->GetName(), lf->GetName() ) != 0 ) {
2649 cnames[ncols].Append('.');
2650 cnames[ncols].Append( lf->GetName() );
2651 }
2652 ++ncols;
2653 }
2654//*-*- otherwise select only the specified columns
2655 } else {
2656
2658
2659 }
2660 var = new TTreeFormula* [ncols];
2661
2662 for(ui=colFormats.size();ui<ncols;++ui) {
2663 colFormats.push_back(defFormat);
2664 colSizes.push_back(colDefaultSize);
2665 }
2666
2667//*-*- Create the TreeFormula objects corresponding to each column
2668 for (ui=0;ui<ncols;ui++) {
2669 var[ui] = new TTreeFormula("Var1",cnames[ui].Data(),fTree);
2670 fFormulaList->Add(var[ui]);
2671 }
2672
2673//*-*- Create a TreeFormulaManager to coordinate the formulas
2675 bool hasArray = false;
2676 bool forceDim = false;
2677 if (fFormulaList->LastIndex()>=0) {
2678 if (select) {
2679 if (select->GetManager()->GetMultiplicity() > 0 ) {
2681 for(i=0;i<=fFormulaList->LastIndex();i++) {
2682 manager->Add((TTreeFormula*)fFormulaList->At(i));
2683 }
2684 manager->Sync();
2685 }
2686 }
2687 for(i=0;i<=fFormulaList->LastIndex();i++) {
2689 switch( form->GetManager()->GetMultiplicity() ) {
2690 case 1:
2691 case 2:
2692 hasArray = true;
2693 forceDim = true;
2694 break;
2695 case -1:
2696 forceDim = true;
2697 break;
2698 case 0:
2699 break;
2700 }
2701
2702 }
2703 }
2704
2705//*-*- Print header
2706 onerow = "***********";
2707 if (hasArray) onerow += "***********";
2708
2709 for (ui=0;ui<ncols;ui++) {
2710 TString starFormat = Form("*%%%d.%ds",std::abs(colSizes[ui])+2,std::abs(colSizes[ui])+2);
2711 onerow += Form(starFormat.Data(),var[ui]->PrintValue(-2));
2712 }
2713 if (fScanRedirect)
2714 out<<onerow.Data()<<"*"<<std::endl;
2715 else
2716 printf("%s*\n",onerow.Data());
2717 onerow = "* Row ";
2718 if (hasArray) onerow += "* Instance ";
2719 for (ui=0;ui<ncols;ui++) {
2720 TString numbFormat = Form("* %%%d.%ds ",colSizes[ui],std::abs(colSizes[ui]));
2721 onerow += Form(numbFormat.Data(),var[ui]->PrintValue(-1));
2722 }
2723 if (fScanRedirect)
2724 out<<onerow.Data()<<"*"<<std::endl;
2725 else
2726 printf("%s*\n",onerow.Data());
2727 onerow = "***********";
2728 if (hasArray) onerow += "***********";
2729 for (ui=0;ui<ncols;ui++) {
2730 TString starFormat = Form("*%%%d.%ds",std::abs(colSizes[ui])+2,std::abs(colSizes[ui])+2);
2731 onerow += Form(starFormat.Data(),var[ui]->PrintValue(-2));
2732 }
2733 if (fScanRedirect)
2734 out<<onerow.Data()<<"*"<<std::endl;
2735 else
2736 printf("%s*\n",onerow.Data());
2737//*-*- loop on all selected entries
2738 fSelectedRows = 0;
2739 Int_t tnumber = -1;
2740 bool exitloop = false;
2741 for (entry = firstentry; entry - firstentry < nentries && !exitloop; entry++) {
2743 if (entryNumber < 0) break;
2745 if (localEntry < 0) break;
2746 if (tnumber != fTree->GetTreeNumber()) {
2748 if (manager) manager->UpdateFormulaLeaves();
2749 else {
2750 for(i=0;i<=fFormulaList->LastIndex();i++) {
2752 }
2753 }
2754 }
2755
2756 int ndata = 1;
2757 if (forceDim) {
2758
2759 if (manager) {
2760
2761 ndata = manager->GetNdata(true);
2762
2763 } else {
2764
2765 // let's print the max number of column
2766 for (ui=0;ui<ncols;ui++) {
2767 if (ndata < var[ui]->GetNdata() ) {
2768 ndata = var[ui]->GetNdata();
2769 }
2770 }
2771 if (select && select->GetNdata()==0) ndata = 0;
2772 }
2773
2774 }
2775
2776 if (lenmax && ndata>(int)lenmax) ndata = lenmax;
2777 bool loaded = false;
2778 for(int inst=0;inst<ndata;inst++) {
2779 if (select) {
2780 if (select->EvalInstance(inst) == 0) {
2781 continue;
2782 }
2783 }
2784 if (inst==0) loaded = true;
2785 else if (!loaded) {
2786 // EvalInstance(0) always needs to be called so that
2787 // the proper branches are loaded.
2788 for (ui=0;ui<ncols;ui++) {
2789 var[ui]->EvalInstance(0);
2790 }
2791 loaded = true;
2792 }
2793 onerow = Form("* %8lld ",entryNumber);
2794 if (hasArray) {
2795 onerow += Form("* %8d ",inst);
2796 }
2797 for (ui=0;ui<ncols;++ui) {
2798 TString numbFormat = Form("* %%%d.%ds ",colSizes[ui],std::abs(colSizes[ui]));
2799 if (var[ui]->GetNdim()) onerow += Form(numbFormat.Data(),var[ui]->PrintValue(0,inst,colFormats[ui].Data()));
2800 else {
2801 TString emptyForm = Form("* %%%dc ",colSizes[ui]);
2802 onerow += Form(emptyForm.Data(),' ');
2803 }
2804 }
2805 fSelectedRows++;
2806 if (fScanRedirect)
2807 out<<onerow.Data()<<"*"<<std::endl;
2808 else
2809 printf("%s*\n",onerow.Data());
2810 if (fTree->GetScanField() > 0 && fSelectedRows > 0) {
2811 if (fSelectedRows%fTree->GetScanField() == 0) {
2812 fprintf(stderr,"Type <CR> to continue or q to quit ==> ");
2813 int answer, readch;
2814 readch = getchar();
2815 answer = readch;
2816 while (readch != '\n' && readch != EOF) readch = getchar();
2817 if (answer == 'q' || answer == 'Q') {
2818 exitloop = true;
2819 break;
2820 }
2821 }
2822 }
2823 }
2824 }
2825 onerow = "***********";
2826 if (hasArray) onerow += "***********";
2827 for (ui=0;ui<ncols;ui++) {
2828 TString starFormat = Form("*%%%d.%ds",std::abs(colSizes[ui])+2,std::abs(colSizes[ui])+2);
2829 onerow += Form(starFormat.Data(),var[ui]->PrintValue(-2));
2830 }
2831 if (fScanRedirect)
2832 out<<onerow.Data()<<"*"<<std::endl;
2833 else
2834 printf("%s*\n",onerow.Data());
2835 if (select) Printf("==> %lld selected %s", fSelectedRows,
2836 fSelectedRows == 1 ? "entry" : "entries");
2837 if (fScanRedirect) printf("File <%s> created\n", fname);
2838
2839//*-*- delete temporary objects
2841 // The TTreeFormulaManager is deleted by the last TTreeFormula.
2842 delete [] var;
2843 return fSelectedRows;
2844}
2845
2846////////////////////////////////////////////////////////////////////////////////
2847/// Loop on Tree and return TSQLResult object containing entries passing
2848/// selection. If varexp is 0 (or "") then print only first 8 columns.
2849/// If varexp = "*" print all columns. Otherwise a columns selection can
2850/// be made using "var1:var2:var3". In case of error 0 is returned otherwise
2851/// a TSQLResult object which must be deleted by the user.
2852
2855{
2856 TTreeFormula **var;
2857 std::vector<TString> cnames;
2860 Int_t i,nch;
2861 Int_t ncols = 8; // by default first 8 columns are printed only
2863 Int_t nleaves = leaves->GetEntriesFast();
2864 if (nleaves < ncols) ncols = nleaves;
2865 nch = varexp ? strlen(varexp) : 0;
2866
2868
2869 // compile selection expression if there is one
2870 TTreeFormula *select = nullptr;
2871 if (strlen(selection)) {
2872 select = new TTreeFormula("Selection",selection,fTree);
2873 if (!select) return nullptr;
2874 if (!select->GetNdim()) { delete select; return nullptr; }
2875 fFormulaList->Add(select);
2876 }
2877
2878 // if varexp is empty, take first 8 columns by default
2879 int allvar = 0;
2880 if (varexp && !strcmp(varexp, "*")) { ncols = nleaves; allvar = 1; }
2881 if (nch == 0 || allvar) {
2882 for (i=0;i<ncols;i++) {
2883 cnames.push_back( ((TLeaf*)leaves->At(i))->GetName() );
2884 }
2885 } else {
2886 // otherwise select only the specified columns
2888 }
2889 var = new TTreeFormula* [ncols];
2890
2891 // create the TreeFormula objects corresponding to each column
2892 for (i=0;i<ncols;i++) {
2893 var[i] = new TTreeFormula("Var1",cnames[i].Data(),fTree);
2894 fFormulaList->Add(var[i]);
2895 }
2896
2897 // fill header info into result object
2898 TTreeResult *res = new TTreeResult(ncols);
2899 for (i = 0; i < ncols; i++) {
2900 res->AddField(i, var[i]->PrintValue(-1));
2901 }
2902
2903 //*-*- Create a TreeFormulaManager to coordinate the formulas
2905 if (fFormulaList->LastIndex()>=0) {
2907 for(i=0;i<=fFormulaList->LastIndex();i++) {
2908 manager->Add((TTreeFormula*)fFormulaList->At(i));
2909 }
2910 manager->Sync();
2911 }
2912
2913 // loop on all selected entries
2914 const char *aresult;
2915 Int_t len;
2916 char *arow = new char[ncols*50];
2917 fSelectedRows = 0;
2918 Int_t tnumber = -1;
2919 Int_t *fields = new Int_t[ncols];
2922 if (entryNumber < 0) break;
2924 if (localEntry < 0) break;
2925 if (tnumber != fTree->GetTreeNumber()) {
2927 for (i=0;i<ncols;i++) var[i]->UpdateFormulaLeaves();
2928 }
2929
2930 Int_t ndata = 1;
2931 if (manager && manager->GetMultiplicity()) {
2932 ndata = manager->GetNdata();
2933 }
2934
2935 if (select) {
2936 select->GetNdata();
2937 if (select->EvalInstance(0) == 0) continue;
2938 }
2939
2940 bool loaded = false;
2941 for(int inst=0;inst<ndata;inst++) {
2942 if (select) {
2943 if (select->EvalInstance(inst) == 0) {
2944 continue;
2945 }
2946 }
2947
2948 if (inst==0) loaded = true;
2949 else if (!loaded) {
2950 // EvalInstance(0) always needs to be called so that
2951 // the proper branches are loaded.
2952 for (i=0;i<ncols;i++) {
2953 var[i]->EvalInstance(0);
2954 }
2955 loaded = true;
2956 }
2957 for (i=0;i<ncols;i++) {
2958 aresult = var[i]->PrintValue(0,inst);
2959 len = strlen(aresult)+1;
2960 if (i == 0) {
2962 fields[i] = len;
2963 } else {
2965 fields[i] = fields[i-1] + len;
2966 }
2967 }
2968 res->AddRow(new TTreeRow(ncols,fields,arow));
2969 fSelectedRows++;
2970 }
2971 }
2972
2973 // delete temporary objects
2975 // The TTreeFormulaManager is deleted by the last TTreeFormula.
2976 delete [] fields;
2977 delete [] arow;
2978 delete [] var;
2979
2980 return res;
2981}
2982
2983////////////////////////////////////////////////////////////////////////////////
2984/// Set number of entries to estimate variable limits.
2985
2990
2991////////////////////////////////////////////////////////////////////////////////
2992/// Start the TTreeViewer on this TTree.
2993///
2994/// - ww is the width of the canvas in pixels
2995/// - wh is the height of the canvas in pixels
2996
2998{
2999 // unused variables
3000 (void) ww;
3001 (void) wh;
3002
3003 if (!gApplication)
3005 // make sure that the Gpad and GUI libs are loaded
3006
3007 TString hname = gEnv->GetValue("TreeViewer.Name", "TTreeViewer");
3008
3010 if (gApplication)
3011 gApplication->InitializeGraphics(hname == "RTreeViewer");
3012
3013 if (gROOT->IsBatch()) {
3014 if ((hname != "RTreeViewer") || gROOT->IsWebDisplayBatch()) {
3015 Warning("StartViewer", "The tree viewer cannot run in batch mode");
3016 return;
3017 }
3018 }
3019
3020 if (auto h = gROOT->GetPluginManager()->FindHandler("TVirtualTreeViewer", hname.Data())) {
3021 if (h->LoadPlugin() != -1)
3022 h->ExecPlugin(1, fTree);
3023 }
3024}
3025
3026////////////////////////////////////////////////////////////////////////////////
3027/// Unbinned fit of one or more variable(s) from a Tree.
3028///
3029/// funcname is a TF1 function.
3030///
3031/// See TTree::Draw for explanations of the other parameters.
3032///
3033/// Fit the variable varexp using the function funcname using the
3034/// selection cuts given by selection.
3035///
3036/// The list of fit options is given in parameter option.
3037///
3038/// - option = "Q" Quiet mode (minimum printing)
3039/// - option = "V" Verbose mode (default is between Q and V)
3040/// - option = "E" Perform better Errors estimation using Minos technique
3041/// - option = "M" More. Improve fit results
3042/// - option = "D" Draw the projected histogram with the fitted function
3043/// normalized to the number of selected rows
3044/// and multiplied by the bin width
3045///
3046/// You can specify boundary limits for some or all parameters via
3047/// ~~~{.cpp}
3048/// func->SetParLimits(p_number, parmin, parmax);
3049/// ~~~
3050/// if parmin>=parmax, the parameter is fixed
3051///
3052/// Note that you are not forced to fix the limits for all parameters.
3053/// For example, if you fit a function with 6 parameters, you can do:
3054/// ~~~{.cpp}
3055/// func->SetParameters(0,3.1,1.e-6,0.1,-8,100);
3056/// func->SetParLimits(4,-10,-4);
3057/// func->SetParLimits(5, 1,1);
3058/// ~~~
3059/// With this setup, parameters 0->3 can vary freely
3060/// - Parameter 4 has boundaries [-10,-4] with initial value -8
3061/// - Parameter 5 is fixed to 100.
3062///
3063/// For the fit to be meaningful, the function must be self-normalized.
3064///
3065/// i.e. It must have the same integral regardless of the parameter
3066/// settings. Otherwise the fit will effectively just maximize the
3067/// area.
3068///
3069/// It is mandatory to have a normalization variable
3070/// which is fixed for the fit. e.g.
3071/// ~~~{.cpp}
3072/// TF1* f1 = new TF1("f1", "gaus(0)/sqrt(2*3.14159)/[2]", 0, 5);
3073/// f1->SetParameters(1, 3.1, 0.01);
3074/// f1->SetParLimits(0, 1, 1); // fix the normalization parameter to 1
3075/// data->UnbinnedFit("f1", "jpsimass", "jpsipt>3.0");
3076/// ~~~
3077///
3078/// 1, 2 and 3 Dimensional fits are supported.
3079/// See also TTree::Fit
3080///
3081/// ### Return status
3082///
3083/// The function return the status of the fit in the following form
3084/// ~~~{.cpp}
3085/// fitResult = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult
3086/// ~~~
3087/// - The fitResult is 0 is the fit is OK.
3088/// - The fitResult is negative in case of an error not connected with the fit.
3089/// - The number of entries used in the fit can be obtained via
3090/// ~~~{.cpp}
3091/// mytree.GetSelectedRows();
3092/// ~~~
3093/// - If the number of selected entries is null the function returns -1
3094///
3095/// new implementation using new Fitter classes
3096
3098{
3099 // function is given by name, find it in gROOT
3100 TF1* fitfunc = (TF1*)gROOT->GetFunction(funcname);
3101 if (!fitfunc) { Error("UnbinnedFit", "Unknown function: %s",funcname); return 0; }
3102
3103 Int_t npar = fitfunc->GetNpar();
3104 if (npar <=0) { Error("UnbinnedFit", "Illegal number of parameters = %d",npar); return 0; }
3105
3106 // Spin through the data to select out the events of interest
3107 // Make sure that the arrays V1,etc are created large enough to accommodate
3108 // all entries
3112
3113 // build FitOptions
3114 TString opt = option;
3115 opt.ToUpper();
3117 if (opt.Contains("Q")) fitOption.Quiet = 1;
3118 if (opt.Contains("V")){fitOption.Verbose = 1; fitOption.Quiet = 0;}
3119 if (opt.Contains("E")) fitOption.Errors = 1;
3120 if (opt.Contains("M")) fitOption.More = 1;
3121 if (!opt.Contains("D")) fitOption.Nograph = 1; // what about 0
3122 // could add range and automatic normalization of functions and gradient
3123
3124 TString drawOpt = "goff";
3125 if (!fitOption.Nograph) drawOpt = "";
3127
3128 if (!fitOption.Nograph && GetSelectedRows() <= 0 && GetDimension() > 4) {
3129 Info("UnbinnedFit","Ignore option D with more than 4 variables");
3131 }
3132
3133 //if no selected entries return
3135
3136 if (nrows <= 0) {
3137 Error("UnbinnedFit", "Cannot fit: no entries selected");
3138 return -1;
3139 }
3140
3141 // Check that function has same dimension as number of variables
3142 Int_t ndim = GetDimension();
3143 // do not check with TF1::GetNdim() since it returns 1 for TF1 classes created with
3144 // a C function with larger dimension
3145
3146
3147 // use pointer stored in the tree (not copy the data in)
3148 std::vector<double *> vlist(ndim);
3149 for (int i = 0; i < ndim; ++i)
3150 vlist[i] = fSelector->GetVal(i);
3151
3152 // fill the fit data object
3153 // the object will be then managed by the fitted classes - however it will be invalid when the
3154 // data pointers (given by fSelector->GetVal() ) wil be invalidated
3156
3157
3158
3161
3162 //reset estimate
3164
3165 //if option "D" is specified, draw the projected histogram
3166 //with the fitted function normalized to the number of selected rows
3167 //and multiplied by the bin width
3168 if (!fitOption.Nograph && fHistogram) {
3169 if (fHistogram->GetDimension() < 2) {
3170 TH1 *hf = (TH1*)fHistogram->Clone("unbinnedFit");
3171 hf->SetLineWidth(3);
3172 hf->Reset();
3175 for (Int_t bin=1;bin<=nbins;bin++) {
3176 Double_t func = norm*fitfunc->Eval(hf->GetBinCenter(bin));
3177 hf->SetBinContent(bin,func);
3178 }
3179 fHistogram->GetListOfFunctions()->Add(hf,"lsame");
3180 }
3181 fHistogram->Draw();
3182 }
3183
3184
3185 return int(ret);
3186
3187}
3188
3189////////////////////////////////////////////////////////////////////////////////
3190/// this function is called by TChain::LoadTree when a new Tree is loaded.
3191/// Because Trees in a TChain may have a different list of leaves, one
3192/// must update the leaves numbers in the TTreeFormula used by the TreePlayer.
3193
3195{
3196 if (fSelector) fSelector->Notify();
3197 if (fSelectorUpdate){
3198 //If the selector is writing into a TEntryList, the entry list's
3199 //sublists need to be changed according to the loaded tree
3201 //FIXME: should be more consistent with selector from file
3202 TObject *obj = fSelector->GetObject();
3203 if (obj){
3206 }
3207 }
3208 }
3211 TEntryList *elist=nullptr;
3212 while ((elist=(TEntryList*)next())){
3213 if (elist->InheritsFrom(TEntryList::Class())){
3214 elist->SetTree(fTree->GetTree());
3215 }
3216 }
3217 }
3218 }
3219
3220 if (fFormulaList->GetSize()) {
3222 while (lnk) {
3223 lnk->GetObject()->Notify();
3224 lnk = lnk->Next();
3225 }
3226 }
3227}
#define R__EXTERN
Definition DllImport.h:26
#define h(i)
Definition RSha256.hxx:106
int Ssiz_t
String size (currently int)
Definition RtypesCore.h:82
double Double_t
Double 8 bytes.
Definition RtypesCore.h:74
constexpr Ssiz_t kNPOS
The equivalent of std::string::npos for the ROOT class TString.
Definition RtypesCore.h:132
long long Long64_t
Portable signed long integer 8 bytes.
Definition RtypesCore.h:84
const char Option_t
Option string (const char)
Definition RtypesCore.h:81
R__EXTERN TApplication * gApplication
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
#define gDirectory
Definition TDirectory.h:385
R__EXTERN TEnv * gEnv
Definition TEnv.h:126
Option_t Option_t option
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h length
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
int nentries
R__EXTERN TVirtualMutex * gROOTMutex
Definition TROOT.h:63
#define gROOT
Definition TROOT.h:417
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2570
void Printf(const char *fmt,...)
Formats a string in a circular formatting buffer and prints the string.
Definition TString.cxx:2584
R__EXTERN TStyle * gStyle
Definition TStyle.h:442
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
TVirtualFitter * tFitter
R__EXTERN Foption_t Foption
static TString R__GetBranchPointerName(TLeaf *leaf, bool replace=true)
Return the name of the branch pointer needed by MakeClass/MakeSelector.
R__EXTERN TVirtualMonitoringWriter * gMonitoringWriter
#define R__LOCKGUARD(mutex)
#define gPad
Class describing the un-binned data sets (just x coordinates values) of any dimensions.
Definition UnBinData.h:46
const_iterator begin() const
void InitializeGraphics(Bool_t only_web=kFALSE)
Initialize the graphics environment.
static void CreateApplication()
Static function used to create a default application environment.
static void NeedGraphicsLibs()
Static method.
Int_t GetNbins() const
Definition TAxis.h:127
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
Definition TAxis.cxx:546
A Branch for the case of an object.
static TClass * Class()
static TClass * Class()
A TTree is a list of TBranches.
Definition TBranch.h:93
static TClass * Class()
A TChainElement describes a component of a TChain.
A Chain Index.
Definition TChainIndex.h:40
A chain is a collection of files containing TTree objects.
Definition TChain.h:33
static TClass * Class()
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
Bool_t IsLoaded() const
Return true if the shared library of this class is currently in the a process's memory.
Definition TClass.cxx:6017
const char * GetDeclFileName() const
Return name of the file containing the declaration of this class.
Definition TClass.cxx:3525
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition TClass.cxx:2994
virtual void SetOwner(Bool_t enable=kTRUE)
Set whether this collection is the owner (enable==true) of its content.
virtual Int_t GetSize() const
Return the capacity of the collection, i.e.
This class stores the date and time with a precision of one second in an unsigned 32 bit word (950130...
Definition TDatime.h:37
TDirectory::TContext keeps track and restore the current directory.
Definition TDirectory.h:89
virtual const char * GetPath() const
Returns the full path of the directory.
virtual TFile * GetFile() const
Definition TDirectory.h:221
A List of entry numbers in a TTree or TChain.
Definition TEntryList.h:26
static TClass * Class()
virtual void SetTree(const TTree *tree)
If a list for a tree with such name and filename exists, sets it as the current sublist If not,...
virtual Long64_t GetN() const
Definition TEntryList.h:78
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition TEnv.cxx:511
<div class="legacybox"><h2>Legacy Code</h2> TEventList is a legacy interface: there will be no bug fi...
Definition TEventList.h:31
1-Dim function class
Definition TF1.h:182
A file, usually with extension .root, that stores data and code in the form of serialized objects in ...
Definition TFile.h:130
static Long64_t GetFileBytesRead()
Static function returning the total number of bytes read from all files.
Definition TFile.cxx:4286
Provides an indirection to the TFitResult class and with a semantics identical to a TFitResult pointe...
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:109
virtual Int_t GetDimension() const
Definition TH1.h:527
TAxis * GetXaxis()
Definition TH1.h:571
virtual Double_t GetSumOfWeights() const
Return the sum of weights across all bins excluding under/overflows.
Definition TH1.h:559
virtual TFitResultPtr Fit(const char *formula, Option_t *option="", Option_t *goption="", Double_t xmin=0, Double_t xmax=0)
Fit histogram with function fname.
Definition TH1.cxx:4050
void Draw(Option_t *option="") override
Draw this histogram with options.
Definition TH1.cxx:3193
@ kNoAxis
NOTE: Must always be 0 !!!
Definition TH1.h:122
virtual UInt_t SetCanExtend(UInt_t extendBitMask)
Make the histogram axes extendable / not extendable according to the bit mask returns the previous bi...
Definition TH1.cxx:6860
TList * GetListOfFunctions() const
Definition TH1.h:488
virtual void Scale(Double_t c1=1, Option_t *option="")
Multiply this histogram by a constant c1.
Definition TH1.cxx:6815
TObject * Clone(const char *newname="") const override
Make a complete copy of the underlying object.
Definition TH1.cxx:2882
virtual void LabelsDeflate(Option_t *axis="X")
Reduce the number of bins for the axis passed in the option to the number of bins having a label.
Definition TH1.cxx:5423
A TLeaf for a general object derived from TObject.
Definition TLeafObject.h:31
A TLeaf describes individual elements of a TBranch See TBranch structure in TTree.
Definition TLeaf.h:57
static TClass * Class()
A doubly linked list.
Definition TList.h:38
void Clear(Option_t *option="") override
Remove all objects from the list.
Definition TList.cxx:532
TObject * FindObject(const char *name) const override
Find an object in this list using its name.
Definition TList.cxx:708
void Add(TObject *obj) override
Definition TList.h:81
virtual TObjLink * FirstLink() const
Definition TList.h:107
void Delete(Option_t *option="") override
Remove all objects from the list AND delete all heap based objects.
Definition TList.cxx:600
TObject * At(Int_t idx) const override
Returns the object at position idx. Returns 0 if idx is out of range.
Definition TList.cxx:487
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:50
An array of TObjects.
Definition TObjArray.h:31
Collectable string class.
Definition TObjString.h:28
const char * GetName() const override
Returns name of object.
Definition TObjString.h:38
Mother of all ROOT objects.
Definition TObject.h:42
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:461
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1082
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition TObject.cxx:886
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition TObject.cxx:548
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1096
@ kCanDelete
if object in a list can be deleted
Definition TObject.h:71
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:1070
A 3D polymarker.
Principal Components Analysis (PCA)
Definition TPrincipal.h:21
A container proxy, which allows to access references stored in a TRefArray from TTree::Draw.
A specialized TSelector for TTree::Draw.
virtual void SetEstimate(Long64_t n)
Set number of entries to estimate variable limits.
TTreeFormula * GetVar3() const
See TSelectorDraw::GetVar.
virtual Long64_t GetDrawFlag() const
TH1 * GetOldHistogram() const
virtual UInt_t SplitNames(const TString &varexp, std::vector< TString > &names)
Build Index array for names in varexp.
TObject * GetObject() const
TTreeFormula * GetVar2() const
See TSelectorDraw::GetVar.
virtual Int_t GetAction() const
TTreeFormula * GetVar1() const
See TSelectorDraw::GetVar.
virtual Int_t GetDimension() const
virtual Double_t * GetVal(Int_t i) const
Return the last values corresponding to the i-th component of the formula being processed (where the ...
bool Notify() override
This function is called at the first entry of a new tree in a chain.
virtual bool GetCleanElist() const
The class is derived from the ROOT class TSelector.
virtual Long64_t GetSelectedRows() const
A TSelector object is used by the TTree::Draw, TTree::Scan, TTree::Process to navigate in a TTree and...
Definition TSelector.h:31
virtual EAbort GetAbort() const
Definition TSelector.h:73
virtual void ProcessFill(Long64_t)
This method is called for all selected entries.
@ kAbortProcess
Definition TSelector.h:34
virtual void Init(TTree *)
Definition TSelector.h:53
virtual int Version() const
Definition TSelector.h:52
virtual bool ProcessCut(Long64_t)
This method is called before processing entry.
virtual bool Process(Long64_t)
The Process() function is called for each entry in the tree to be processed.
TClass * IsA() const override
Definition TSelector.h:79
virtual void SlaveBegin(TTree *)
Definition TSelector.h:55
bool Notify() override
This method must be overridden to handle object notification (the base implementation is no-op).
Definition TSelector.h:56
virtual void SetOption(const char *option)
Definition TSelector.h:64
virtual Long64_t GetStatus() const
Definition TSelector.h:58
virtual void SetInputList(TList *input)
Definition TSelector.h:66
virtual TList * GetOutputList() const
Definition TSelector.h:69
virtual void SlaveTerminate()
Definition TSelector.h:70
virtual void ResetAbort()
Definition TSelector.h:74
virtual void Begin(TTree *)
Definition TSelector.h:54
virtual void Terminate()
Definition TSelector.h:71
static TSelector * GetSelector(const char *filename)
The code in filename is loaded (interpreted or compiled, see below), filename must contain a valid cl...
Int_t LastIndex() const
static TClass * Class()
Describe one element (data member) to be Streamed.
Basic string class.
Definition TString.h:138
Ssiz_t Length() const
Definition TString.h:427
void ToLower()
Change string to lower-case.
Definition TString.cxx:1189
const char * Data() const
Definition TString.h:386
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:715
void ToUpper()
Change string to upper case.
Definition TString.cxx:1202
TString & Remove(Ssiz_t pos)
Definition TString.h:696
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition TString.cxx:2437
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:643
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition TString.h:662
Bool_t GetCanvasPreferGL() const
Definition TStyle.h:189
void SetCanvasPreferGL(Bool_t prefer=kTRUE)
Definition TStyle.h:345
Int_t GetNumberOfColors() const
Return number of colors in the color palette.
Definition TStyle.cxx:1176
virtual Bool_t IsFileInIncludePath(const char *name, char **fullpath=nullptr)
Return true if 'name' is a file that can be found in the ROOT include path or the current directory.
Definition TSystem.cxx:980
virtual TString SplitAclicMode(const char *filename, TString &mode, TString &args, TString &io) const
This method split a filename of the form:
Definition TSystem.cxx:4326
Base class for several text objects.
Definition TText.h:22
A cache to speed-up the reading of ROOT datasets.
Definition TTreeCache.h:32
Used to coordinate one or more TTreeFormula objects.
Used to pass a selection expression to the Tree drawing routine.
virtual bool IsInteger(bool fast=true) const
Return TRUE if the formula corresponds to one single Tree leaf and this leaf is short,...
virtual char * PrintValue(Int_t mode=0) const
Return value of variable as a string.
T EvalInstance(Int_t i=0, const char *stringStack[]=nullptr)
Evaluate this treeformula.
virtual Int_t GetNdata()
Return number of available instances in the formula.
A Tree Index with majorname and minorname.
Definition TTreeIndex.h:29
Int_t MakeCode(const char *filename) override
Generate skeleton function for this Tree.
TTree * CopyTree(const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry) override
Copy a Tree with selection, make a clone of this Tree header, then copy the selected entries.
Long64_t DrawSelect(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry) override
Draw expression varexp for specified entries that matches the selection.
TList * fInput
! input list to the selector
Definition TTreePlayer.h:53
void DeleteSelectorFromFile()
Delete any selector created by this object.
void SetEstimate(Long64_t n) override
Set number of entries to estimate variable limits.
Int_t UnbinnedFit(const char *formula, const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry) override
Unbinned fit of one or more variable(s) from a Tree.
void RecursiveRemove(TObject *obj) override
cleanup pointers in the player pointing to obj
Long64_t DrawScript(const char *wrapperPrefix, const char *macrofilename, const char *cutfilename, Option_t *option, Long64_t nentries, Long64_t firstentry) override
Draw the result of a C++ script.
TSelectorDraw * fSelector
! Pointer to current selector
Definition TTreePlayer.h:50
void SetTree(TTree *t) override
Long64_t GetSelectedRows() const override
Definition TTreePlayer.h:81
Int_t MakeReader(const char *classname, Option_t *option) override
Generate skeleton selector class for this tree.
const char * GetNameByIndex(TString &varexp, Int_t *index, Int_t colindex)
Return name corresponding to colindex in varexp.
Long64_t fSelectedRows
Number of selected entries.
Definition TTreePlayer.h:48
Long64_t Scan(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry) override
Loop on Tree and print entries passing selection.
TSelector * fSelectorFromFile
! Pointer to a user defined selector created by this TTreePlayer object
Definition TTreePlayer.h:51
const char * fScanFileName
Name of the file where Scan is redirected.
Definition TTreePlayer.h:46
TList * fFormulaList
! Pointer to a list of coordinated list TTreeFormula (used by Scan and Query)
Definition TTreePlayer.h:54
bool fScanRedirect
Switch to redirect TTree::Scan output to a file.
Definition TTreePlayer.h:45
TTree * fTree
! Pointer to current Tree
Definition TTreePlayer.h:44
void StartViewer(Int_t ww, Int_t wh) override
Start the TTreeViewer on this TTree.
Int_t MakeProxy(const char *classname, const char *macrofilename=nullptr, const char *cutfilename=nullptr, const char *option=nullptr, Int_t maxUnrolling=3) override
Generate a skeleton analysis class for this Tree using TBranchProxy.
Int_t MakeClass(const char *classname, Option_t *option) override
Generate skeleton analysis class for this Tree.
TPrincipal * Principal(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry) override
Interface to the Principal Components Analysis class.
TSelector * fSelectorUpdate
! Set to the selector address when it's entry list needs to be updated by the UpdateFormulaLeaves fun...
Definition TTreePlayer.h:55
TH1 * fHistogram
! Pointer to histogram used for the projection
Definition TTreePlayer.h:49
void UpdateFormulaLeaves() override
this function is called by TChain::LoadTree when a new Tree is loaded.
Long64_t Process(const char *filename, Option_t *option, Long64_t nentries, Long64_t firstentry) override
Process this tree executing the TSelector code in the specified filename.
TSQLResult * Query(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry) override
Loop on Tree and return TSQLResult object containing entries passing selection.
TClass * fSelectorClass
! Pointer to the actual class of the TSelectorFromFile
Definition TTreePlayer.h:52
Long64_t GetEntries(const char *selection) override
Return the number of entries matching the selection.
Int_t GetDimension() const override
Definition TTreePlayer.h:74
Int_t fDimension
Dimension of the current expression.
Definition TTreePlayer.h:47
TTreePlayer()
Default Tree constructor.
TVirtualIndex * BuildIndex(const TTree *T, const char *majorname, const char *minorname, bool long64major=false, bool long64minor=false) override
Build the index for the tree (see TTree::BuildIndex) In some cases, a warning is printed about switch...
~TTreePlayer() override
Tree destructor.
Int_t Fit(const char *formula, const char *varexp, const char *selection, Option_t *option, Option_t *goption, Long64_t nentries, Long64_t firstentry) override
Fit a projected item(s) from a Tree.
virtual Long64_t GetEntriesToProcess(Long64_t firstentry, Long64_t nentries) const
return the number of entries to be processed this function checks that nentries is not bigger than th...
Class defining interface to a TTree query result with the same interface as for SQL databases.
Definition TTreeResult.h:34
void AddRow(TSQLRow *row)
Adopt a row to result set.
void AddField(Int_t field, const char *fieldname)
Add field name to result set.
Class defining interface to a row of a TTree query result.
Definition TTreeRow.h:29
A TTree represents a columnar dataset.
Definition TTree.h:89
virtual Int_t Fill()
Fill all branches.
Definition TTree.cxx:4675
bool EnableCache()
Enable the TTreeCache unless explicitly disabled for this TTree by a prior call to SetCacheSize(0).
Definition TTree.cxx:2715
virtual TBranch * GetBranch(const char *name)
Return pointer to the branch with the given name in this tree or its friends.
Definition TTree.cxx:5452
virtual Int_t GetScanField() const
Definition TTree.h:598
virtual Int_t GetEntry(Long64_t entry, Int_t getall=0)
Read all branches of entry and return total number of bytes read.
Definition TTree.cxx:5740
virtual Long64_t GetEstimate() const
Definition TTree.h:554
virtual TObjArray * GetListOfLeaves()
Definition TTree.h:576
TFile * GetCurrentFile() const
Return pointer to the current file.
Definition TTree.cxx:5577
void Draw(Option_t *opt) override
Default Draw method for all objects.
Definition TTree.h:478
virtual void SetNotify(TObject *obj)
Sets the address of the object to be notified when the tree is loaded.
Definition TTree.cxx:9518
TDirectory * GetDirectory() const
Definition TTree.h:509
virtual TEntryList * GetEntryList()
Returns the entry list assigned to this tree.
Definition TTree.cxx:5956
virtual Long64_t Process(const char *filename, Option_t *option="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)
Process this tree executing the TSelector code in the specified filename.
Definition TTree.cxx:7666
virtual Long64_t GetEntries() const
Definition TTree.h:510
virtual void SetEstimate(Long64_t nentries=1000000)
Set number of entries to estimate variable limits.
Definition TTree.cxx:9386
virtual Long64_t GetEntryNumber(Long64_t entry) const
Return entry number corresponding to entry.
Definition TTree.cxx:5967
virtual TTree * CloneTree(Long64_t nentries=-1, Option_t *option="")
Create a clone of this tree and copy nentries.
Definition TTree.cxx:3173
virtual TObjArray * GetListOfBranches()
Definition TTree.h:575
virtual TTree * GetTree() const
Definition TTree.h:604
virtual void SetEntryList(TEntryList *list, Option_t *opt="")
Set an EntryList.
Definition TTree.cxx:9322
virtual Long64_t LoadTree(Long64_t entry)
Set current entry.
Definition TTree.cxx:6606
TEventList * GetEventList() const
Definition TTree.h:560
virtual Long64_t GetEntriesFriend() const
Returns a number corresponding to:
Definition TTree.cxx:5612
virtual Int_t GetTreeNumber() const
Definition TTree.h:606
virtual Int_t GetTimerInterval() const
Definition TTree.h:601
virtual void SetScanField(Int_t n=50)
Sets the default maximum number of lines to be shown before <CR> when calling Scan().
Definition TTree.h:743
virtual Long64_t GetCacheSize() const
Definition TTree.h:500
virtual Long64_t GetMaxEntryLoop() const
Definition TTree.h:584
Abstract Base Class for Fitting.
Abstract interface for Tree Index.
virtual Bool_t SendProcessingProgress(Double_t, Double_t, Bool_t=kFALSE)
virtual Bool_t SendProcessingStatus(const char *, Bool_t=kFALSE)
const Int_t n
Definition legend1.C:16
TFitResultPtr UnBinFit(ROOT::Fit::UnBinData *data, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption)
fit an unbin data set (from tree or from histogram buffer) using a TF1 pointer and fit options.
Definition HFitImpl.cxx:832
TString GetCppName(TString name)
Convert a valid TTree branch name or filename into a valid C++ variable name.
Short_t Max(Short_t a, Short_t b)
Returns the largest of a and b.
Definition TMathBase.h:249
Short_t Min(Short_t a, Short_t b)
Returns the smallest of a and b.
Definition TMathBase.h:197
TLine l
Definition textangle.C:4