v0.05 root 102 root is an object oriented hep analysis framework

90
V0.05 ROOT 102 ROOT is an object oriented HEP analysis framework

Upload: roberta-dennis

Post on 29-Dec-2015

239 views

Category:

Documents


3 download

TRANSCRIPT

V0.05

ROOT 102

ROOT is an object oriented HEP analysis framework

2V0.05

ROOT contacts at Fermi

– Philippe Canal , [email protected]

– Peter Malzacher, [email protected]

– Suzanne Panacek, [email protected]

3V0.05

What We Will Cover Today

• Macros – Fitting – I/O– Analysis

• CINT– Command line– Debugging– Environment

MacrosGUI

CINT

4V0.05

Class ScheduleSession 1: Functions and Fitting

– Function Objects (TF1)– Fitting

Session 2: Building ROOT Trees – Files, Trees, and Branches– 5 Steps to build a TTree– Exercise #1

Break

5V0.05

Class ScheduleSession 3: Putting Trees to Work

– Using Trees in Analysis – Exercise #2

Session 4: More about CINT – Environment settings– CINT debugging– Exercise #3

Session 5: For real Experts– How to add your own root classes– Script compiler

6V0.05

Session1: Functions and Fitting• Function Objects (TF1)

– Three constructors for TF1– User Defined Functions

• Fitting– Fit()– Fitting with a user defined function– Fitting subranges and combining functions– Demonstration of background and signal

function

7V0.05

Function Objects (TF1)

• Built in function objects– see this link for a full list of built in functions

http://root.cern.ch/root/html/TFormula.html#TFormula:TFormula

– use the Fit Panel

• Creating your own function objects– TF1, TF2, TF3– Three Signatures for the TF1 constructor

8V0.05

TF1 Constructors1. A C++ like expression using x with a fixed set

of operators and functions defined in TFormula

TF1 *f1 = new TF1("f1","sin(x)/x",0,10);

f1->Draw();

TF1 *f2 = new TF1("f2","f1 * 2",0,10);

9V0.05

TF1 Constructors (cont.)

2. Same as the previous TF1 with Parameters Call the constructor with parameter indices

TF1 *f1 = new TF1 ("f1","[0] *x*sin( [1] *x)",-3,3);

Set the parameters explicitly

f1->SetParameter(0,10);f1->SetParameter(1,5);f1->Draw();

10V0.05

TF1 Constructors (cont.)

3. Use a defined function Define a functionDouble_t MyFunction(Double_t *x, Double_t *par){

Float_t xx = x[0];Double_t val=

TMath::Abs(par[0]*sin(par[1]*xx)/xx); return val;

}

TF1 constructor TF1 *f1 = new TF1("f1",MyFunction,0,10,2);

NOTE: The 2 is the number of parameters in MyFunction.

Set the parametersf1->SetParameters(2,1);

11V0.05

FittingTo fit a histogram:

<Histogram>->Fit("<FunctionName>");

TF1 *f1 = new TF1 ("f1","[0] *x*sin([1]*x)",-3,3);

f1->SetParameters(10,5);aHistogram->Fit("f1");

12V0.05

FittingExample: fitting a histogram with user defined function.

Step 1. Define the function:Double_t MyFunction (Double_t *x, Double_t *par)

{

Double_t arg= 0;

if (par[2]) arg = (x[0] - par[1])/par[2];

Double_t fitval =

par[0] * TMath::Exp(-0.5*arg*arg);

return fitval;

}

13V0.05

Fitting (cont.)

Step 2. TF1 constructorTF1 *aFunction =

new TF1("MyGaus", MyFunction, -5,5,3);

Step 3. Set initial value of the parametersaFunction->SetParameters(5000,

h->GetMean(),h->GetRMS());

Step 4. Fit and draw the histogramh->Fit("MyGaus");

14V0.05

Fitting Subranges

• Define the range in the TF1 constructor.TF1 *g1 = new TF1("g1", "gaus", 85,95);

• Use "R" option in the Fit() method.h->Fit("g1", "R");

15V0.05

Combining Functions

• Add two functions with "+" operator.

• Assign the parameters for each contributing function.

16V0.05

Combining Functionsy(E) = a1 + a2E + a3E2 + AP

( / 2 )/( (E-)2 + (/2)2)

background lorenzianPeakpar[0] = a1 par[0] = AP

par[1] = a2 par[1] = par[2] = a3 par[2] =

fitFunction = background (x, par ) + lorenzianPeak (x, &par[3])par[0] = a1 par[1] = a2 par[2] = a3

par[3] = Ap

par[4] = par[5] =

17V0.05

Fitting DemoLook at

• FittingDemo.C

• fitf.C

Run FittingDemo.C

More info on fitting:http://root.cern.ch/root/html/examples/fit1.C.html

http://root.cern.ch/root/html/examples/myfit.C.html

http://root.cern.ch/root/html/examples/backsig.C.html

18V0.05

Session1: Functions and Fitting Summary

• Functions Objects (TF1)– Three constructors for TF1– User Defined Functions

• Fitting– Fit()– Fitting with a user defined function– Fitting subranges and combining functions– Demonstration of background and signal

function

19V0.05

Session 2: Building ROOT Trees• Overview of

– ROOT Files– Trees– Branches

• 5 Steps to build a TTree• Demonstration

Building a tree with an object.

• Exercise #1

20V0.05

ROOT Files (TFile)

• When a ROOT file is opened it becomes the current directory.

• Histograms and trees are automatically saved in the file.

• When the file is closed the histogram and tree objects associated with the file are deleted.

• Any object derived from TObject can be written to a ROOT file. It has to be added explicitly.

21V0.05

ROOT Trees (TTree)

• Storing large number of entries.

• Hierarchy of branches and

leaves.

• Reading selective branches

• Use TTree::AutoSave() to save

the tree.

22V0.05

ROOT Branches (TBranch)

• Independent of each other

• Can be written to different files

• Three kinds of branches:

– simple structure or list of variables

– any object (TObject)

– a TClonesArray

23V0.05

Five Steps to Build a Tree

Steps:

1. Create a TFile

2. Create a TTree

3. Add TBranch to the TTree

4. Fill the tree

5. Write the file

24V0.05

Step 1: Create a TFile Object

The TFile constructor– file name (i.e. " AFile.root ") – option: NEW, CREATE, RECREATE,

UPDATE, or READ– file title, shown in the root browser– compression level 0-9, defaults to 1.

TFile *hfile = new TFile("AFile.root","RECREATE","Example");

25V0.05

Step 2: Create a TTree Object

A tree is a list of branches.

The TTree Constructor:– Tree Name (e.g. "T") – Tree Title– Maximum total size of buffers

kept in memory (defaults to 64 MB)

TTree *tree = new TTree("T","A ROOT tree");

26V0.05

Step 3: Adding Branches with an Object• Branch name

• Class name

• Object (descendant of TObject)

• Buffer size (default = 32,000)

• Split level (default = 1)

Event *event = new Event();tree->Branch ("EventBranch","Event",&event,64000,1);

27V0.05

Splitting a BranchSetting the split level (default = 1)

Split level = 0 Split level = 1

Example:

tree->Branch("EvBr","Event",&ev,64000,0);

28V0.05

Adding Branches with a List of Variables• Branch name• Address: the address of the first

item of a structure.• Leaflist: all variable names and

types

ExampleTBranch *b = tree->Branch ("Ev_Branch",&event,

"ntrack/I:nseg:nvtex:flag/i:temp/F");

29V0.05

Adding Branches with a TClonesArray

• Branch name

• Clones array

• Buffer size

• Split level (default = 1)

Example:tree->Branch( "Track_B",&Track,64000,1);

30V0.05

Step 4: Fill the Tree • Create a for loop

• Create Event objects.

• Call the Fill method for the tree.

tree->Fill()

31V0.05

Step 5: Write the File

The TFile::Write()– Writes Histograms and Trees– Write is needed to write file header

hfile->Write();

32V0.05

Demonstration: 5 steps to build a Tree• BuildTreeDemo.C

– create "AFile.root"– 2nd Type of Branch,

crated with a class name and split.

• .X BuildTreeDemo.C– One tree called "T"– One branch for each

data member of Event. – recursive split (see Track)

33V0.05

Session 2: Building ROOT Trees Summary

• Overview of – ROOT Files– Trees– Branches

• 5 Steps to build a TTree• Demonstration

building a tree with an object

34V0.05

Exercises #1Write a macro (ABCWrite.C) that creates a tree

from the floating numbers in the ASCII file ABC.txt. The tree should contain 2 branches. The first branch has three variables (a,b,c). The second branch has one variable p=sqrt(a*a + b*b + c*c). Write the tree to a file called ABC.root.

ABC.txt can be found at:www-pat.fnal.gov/root/102/ABC.txt

35V0.05

Session 3: Putting Trees to WorkUsing Trees in Analysis

– From the command line– Using MakeClass– Using Chains

Exercise #2

36V0.05

Using Trees in Analysis

The TTree::Draw()

Parameters:

1. expressions for x,y,z

myTree->Draw("ntrack");myTree->Draw("sqrt(ntrack): ntrack");

37V0.05

Using Trees in Analysis (cont.)The TTree::Draw()

Parameters:

2. selection

3. draw option

4. number of entries

myTree->Draw("sqrt(ntrack): ntrack","temp > 20.8");

myTree ->Draw("sqrt(ntrack): ntrack","temp >20.8","surf2");

38V0.05

Using Trees in Analysis (cont.)

If the Branch was created with an object and was not split we can still use the Draw() method.

myTree->Draw("event.GetNtrack()");

event = branch name

GetNtrack() = a method of the object on the

branch.

39V0.05

Histograms and Lists • The TTree::Draw() parameters continued:

- saving the histogram

myTree ->Draw(" ntrack >> myHisto");myHisto->Draw();

- saving an event list myTree ->Draw(">> myList","ntrack>0");

myList->Print("all")

- using an event listmyTree ->SetEventList(myList);myTree ->Draw("ntrack");

40V0.05

Information about the TTree Contents

After executing the Draw command, we can get information about the TTree:

– GetSelectedRows()• Returns the number of entries accepted by the selection expression.

– GetV1(), GetV2(), GetV3()• returns a pointer to the float array of the first, second, or third variable (x,y,z)

– GetW()

41V0.05

Introducing MakeClass

• Draw() is powerful and quick.

• What if you would like to plot the masses of all oppositely charged pairs of tracks? You need a loop over all events, find all pairs of tracks, and calculate the required quantities.

• ROOT provides MakeClass to do this.

42V0.05

Using MakeClassScenario: We would like to do selective

plotting. For simplicity we choose to plot only the first 100 tracks of each entry.

We have a ROOT file with a tree with one branch which has leaves of type "Event". The designer has made the class definition available in the shared library libEvent.so and given you the header file Event.h.

43V0.05

Event.h

• Event has – a TClonesArray of Tracks– GetNtrack() method– much more …

• Track has– a GetPx() method– much more ...

TObject

EventGetNtrack()GetNseg()

GetNvertex()...

fTracks

TrackGetPx()GetPy()

...

TObject

fNtrack fNtrack

fPx fPyfPz

44V0.05

Using MakeClass()

1. Load the shared library

root [0].L libEvent.so

2. Load the root file

root [1] TFile *f = new TFile("EventOB.root");

3. Call MakeClassroot [2] T->MakeClass("MyClass");

- creates MyClass.C and MyClass.h- where does T come from?

45V0.05

Using MakeClass()

MyClass.h and MyClass.C

– MyClass.h– contains the class definition of "MyClass"

– MyTree.C– contains the class implementation of

"MyClass"

46V0.05

Loading and Using MyClass.CLoad the macro and create a MyClass object:

root [0].L libEvent.soroot [1].L MyClass.Croot [2] MyClass *m = new MyClass ();

47V0.05

GetEntry()

MyClass::GetEntry()root [3] m->GetEntry(1);

root [4] m->event->GetNtrack()

(Int_t)597

root [5] m->GetEntry(2);

root [6] m->event->GetNtrack()

(Int_t)606

48V0.05

Loop()

MyClass::Loop()root [6] m->Loop();

Bytes read: 48492

Bytes read: 48413

Bytes read: 48255

Bytes read: 48413

Bytes read: 48255

Bytes read: 48176

...

49V0.05

Expanding Loop()Modifying MyClass::Loop()

1. Create a Track objectTrack *track = 0;

2. Create two histogramsTH1F *myHisto = new TH1F(

"myHisto","fPx",100,-5,5);

TH1F *smallHisto = new TH1F(

"small","fPx 100",100,-5,5);

50V0.05

Expanding Loop() (cont.)

3. In Event loop, get the event branchb_event->GetEntry(i);

4. And get the number of tracksn_Tracks = event->GetNtrack();

6. Add track loopfor (Int_t j = 0; j < n_Tracks; j++){

track = (Track*) event->GetTracks()->At(j);

51V0.05

Expanding Loop() (cont.)

7. Fill the first histogram with PxmyHisto->Fill(track->GetPx());

8. Add an if statement for the first 100 tracksif (j < 100){

smallHisto->Fill(track->GetPx());}

9. Outside of the Event loop, draw the histograms

myHisto->Draw();smallHisto->Draw("Same");

52V0.05

Expanding Loop() (cont.)

.L libEvent.so

.L MyClass.C

MyClass *m = new MyClass();

m->Loop()

53V0.05

ChainsScenario:

Perform an analysis using multiple ROOT files. All files are of the same structure and have the same tree.

54V0.05

Chains (cont.)TChain::Add()

root [3] TChain chain("T");

root [4] chain.Add("Event.root")

root [5] chain.Draw("fTracks.fPx")

root [6] myCanvas->cd(2);

root [7] chain.Add("Event50.root")

root [8] chain.Draw("fTracks.fPx")

55V0.05

Chains (cont.)• TChain::GetListOf…

To see the files that are chained

chain.GetListOfFiles()->Print()

List the branches and leaves of the chain.

chain.GetListOfBranches()->Print()

chain.GetListOfLeaves()->Print()

• TChain::Merge()

To merge the files in a chain and write them to a new file :

chain.Merge("all.root")

56V0.05

Demo: Changing "MyClass" to use a Chain

1. Changing MyClassChain.h– Change TTree to TChain– Use Add() to add the files to the chain

2. Changing MyClassChain.C– TTree to TChain

57V0.05

Demo: Changing "MyClass"

3. Load and executeMyClassChain.C

58V0.05

Session 3 SummaryPutting Trees to Work

Using Trees in Analysis– From the command line using

TTree::Draw() – Using MakeClass and Loop()– Using Chains

59V0.05

Exercise #2

Use MakeClass on the ABC.root file and call the class "ABC". Modify the loop to draw a histogram of the last 100 entries of p.

60V0.05

Session 4: More about CINT• Coding Conventions• Global Variables• Environment Settings• CINT• Debugging

– Stepping– Setting breakpoints– Inspecting

61V0.05

Coding Conventions

Based on Taligent• Classes begin with T TTree, TBrowser• Non-class types end with _t Int_t • Data members begin with f fTree • Member functions begin with a capital Loop() • Constants begin with k kInitialSize, kRed • Static variables begin with g gEnv • Static data members

begin with fg fgTokenClient

62V0.05

Coding Conventions (cont.)

• Enumeration types

begin with E EColorLevel • Locals and parameters

begin with a lower case nbytes • Getters and setters

begin with Get, Set, or Is (boolean)SetLast(), GetFirst(), IsDone()

63V0.05

TObject: The Mother of all Root objects

• Defines protocol and default behavior for all objects in ROOT.

– I/O – Inspection– Printing – Drawing– TObjects can be stored in collection classes.

64V0.05

gROOT

• gROOT->Reset();

• gROOT->GetListOf< list type >();

• gROOT->LoadMacro();

• gROOT->Time();

• gROOT->ProcessLine()

65V0.05

gROOT->FindObject(<Name>)• smallHisto is the Variable Name• small is the Object Name.TH1F *smallHisto = new TH1F

("small","fPx 100",100,-5,5);

gROOT->FindObject("smallHisto")

(class TObject*)0x0 // null pointer

gROOT->FindObject("small")

(class TObject*)0x104c7528

• FindObject needs the Object Name.

66V0.05

gROOT->FindObject() cont.FindObject returns a pointer to TObject.

Need to cast it to call class methods.

This generates an error:gROOT->FindObject("small")->GetBinContent(2)

This is OK:gROOT->FindObject("small")->ClassName()

TH1F* histo=(TH1F*) gROOT->FindObject("small")

histo->GetBinContent(2)

67V0.05

gROOT->FindObject() cont.

Due to CINT magic this is also OK:TH1F *smallHisto = new TH1F

("small","fPx 100",100,-5,5);

small->GetBinContent(2);

• CINT implicitly executes a FindObject("small") • Casts it to the correct class• Creates a variable called "small" of the correct

class

Warning: This will not work in compiled code!

68V0.05

Global Variables (cont.)• gRandom

gRandom->Gaus(1,2) You can replace the random generator with your own:

delete gRandom;gRandom = new TRandom2(0); //seed=0

• gFile gFile->GetName()

• gDirectory gDirectory->GetName()

• gSystem gSystem->HostName()

69V0.05

Environment Settings

• Find the current settings– gEnv->Print()

• .rootrc– looks first in current directory– second in ~ ($HOME)– third in $ROOTSYS

70V0.05

Environment Settings (cont.) The .rootrc file:

The Macro Path Unix.*.Root.MacroPath:.:$(HOME)/myRootMacros

Options in rootrc Root.ShowPath: false

History File $HOME/.root_hist

Automatically Executing Macros rootlogon.C rootlogoff.C rootalias.C

71V0.05

Command Line Options

> root -/? Usage: root [-l] [-b] [-n] [-q] [file1.C ... fileN.C] Options: -b : run in batch mode without graphics -n : do not execute logon and logoff macros as specified in .rootrc -q : exit after processing command line macro files -l : do not show splash screen

72V0.05

CINT Commands

• [expression] evaluates the expression root[3] 3*4 (int)12

• .files show loaded source files• .class [name] show class definition• .g prints all objects in the root session• .ls ls on current directory• .pwd list the current directory, canvas,

and style.

73V0.05

Demo on CINT Commands

.class root [0] .L libEvent.so

root [1] .class Event

.g root [2] .g...

0x104c7560 Event e , size=56

0x0 private: Int_t fNtrack

0x0 private: Int_t fNseg

0x0 private: Int_t fNvertex

...

74V0.05

CINT Extensions to C++

1. Declaration can be omitted

f = new TFile("Event.root")

2. "." notation rather than "->" f.ls()

3. Search for an object

TH1F *smallHisto = new TH1F

("small","fPx 100",100,-5,5);

small->Draw();Warning: These will not work in compiled code!

75V0.05

CINT TypesC++ type Size (bytes) ROOT types

Size(bytes)

FORTRAN analog

(unsigned)char 1 (U)Char_t 1 CHARACTER*1

(unsigned)short(int)

2 (U)Short_t 2 INTEGER*2

(unsigned)int 2 or 4 (U)Int_t 4 INTEGER*4

(unsigned)long(int)

4 or 8 (U)Long_t 8 INTEGER*8

float 4 Float_t 4 REAL*4

double 8 (=4) Double_t 8 REAL*8

long double16 (=

double)REAL*16

76V0.05

CINT Multi-line Command

Start with "{"

For example:

root [9] { end with '}'> Int_t j = 0; end with '}'> for (Int_t i = 0; i < 3; i++) end with '}'> { end with '}'> j= j + i; end with '}'> cout <<"i = " <<i<<", j = " <<j<<endl;end with '}'> } end with '}'> }i = 0, j = 0i = 1, j = 1i = 2, j = 3

77V0.05

Debugging: Stepping.s set the step mode to step into

function

.S set the step mode to go over function or loop

.e continue to end of the function

.c continue to next breakpoint

.c 45 continue to line 45

.p <var> print the value of var

78V0.05

Debugging: Breakpoints.trace MyClass prints the executing

code to window

.deltrace MyClass removes the trace

.break MyClass breaks at each method of MyClass

.delbreak MyClass removes the break

.b 34 sets a break point at line 34

.db 34 removes the break point at line 34

79V0.05

Debugging: Inspecting

DrawClass() Draws the inheritance tree

Inspect() Draw the current contents of an object

Dump() Lists the current contents of an object

gDebug = 1 Prints debugging

information

80V0.05

Demonstration: CINT commandsDrawClass() and Dump():

root [0] .L libEvent.so

root [1] Event e

root [2] e->DrawClass()

root [2] e->Dump()

FindObject():root [3] f = TFile("AFile.root")

root [4] .ls

root [5] gROOT->FindObject("T")

root [6] T

81V0.05

Summary of Session 4: More about CINT

• Coding Conventions• Global Variables• Environment Settings• CINT• Debugging

– Stepping– Setting breakpoints– Inspecting

82V0.05

Exercise #3

Download Ex3.C Ex3.h and Ex3.root from the website:

http://pat-www/root/102/Files.htm

Use the CINT debugger to step through the Loop() method of the Ex3.C macro. Find the values of nentries, and the value of "p" when "i = 122".

83V0.05

Session 5: For the real Expert

• Adding your own class

• Script compiler

84V0.05

Adding your own class to ROOT

Step 1:define your classes.

Step 2:ClassDef(ClassName,ClassVersionID) ClassImp(ClassName)

85V0.05

ClassDef and ClassImp

ClassDef and ClassImp are needed for1. RTTI (run time type identification) :

root[0] .class <Class Name>

prints the members and functions of the class

root[0] <object>->ClassName()

returns the name of object's class

2. I/O

Streamer method needed for writing to ROOT files and Trees.

86V0.05

rootcintStep 3:

create a LinkDef.h file.

Step 4:call rootcint in the Makefile to create a CINT dictionary.

EventDict.cxx Event.h EventLinkDef.h

$(ROOTSYS)/bin/rootcint -f EventDict.cxx -c Event.h EventLinkDef.h

For more information: http://root.cern.ch/root/RootCintMan.html

$ROOTSYS/test/Makefile, Event.cxx, and Event.h

87V0.05

The Script Compiler

A ROOT enhancement developed at Fermi (by Philippe Canal)

• Advantages :– syntax checking– speed of execution– full C++ feature set

• Disadvantages:– load each C++ shared library once the– shared library (.so) is temporary

88V0.05

Demonstration of the Script Compiler

• .L ScriptCompilerDemo.C++or gSystem->CompileMacro("ScriptCompilerDemo.C");

root [0] gROOT->Time()

root [1] .L ScriptCompilerDemo.C++

root [2] .files

root [3] Demo()

• Compare performance with CINTroot [0] gROOT->Time()

root [1] .L ScriptCompilerDemo.C

root [3] Demo()

89V0.05

Adding Your Class With the Script Compiler

Step 1: Write the class definition in a separate file.

Step 2: Add the ClassDef and ClassImp macro calls to the class definition.

Step 3: Load the class with the script compiler. In another script:

gSystem->CompileMacro("ABCClass.C");

or from the command line:root[0] .L ABCClass.C++

For an example see ABCWriteClass.C and ABCClass.C

90V0.05

Wrap up

• Questions ?• Feedback Forms

• More information:www-pat.fnal.gov/root/102

http://root.cern.ch

[email protected]

[email protected]

http://ods.fnal.gov/ods/root-eval