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