78
ROOT Intro A (Short) Introduction to ROOT Christian Klein-Bösing IKP Münster 11. Januar 2006

A Short Introduction to ROOT - uni-muenster.de

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

A (Short) Introduction to ROOT

Christian Klein-Bösing

IKP Münster

11. Januar 2006

Page 2: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Page 3: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

What is ROOT?

An object oriented HEP analysis framework „In the mid 1990's, René Brun and Fons Rademakers had

many years of experience developing interactive tools and simulation packages. They had lead successful projects such as PAW, PIAF, and GEANT, and they knew the twenty-year-old FORTRAN libraries had reached their limits. Although still very popular, these tools could not scale up to the challenges offered by the Large Hadron Collider, where the data is a few orders of magnitude larger than anything seen before.“ (ROOT User‘s Guide)

Started in the context of the NA49 Experiment at CERN „Bazaar“ development style:

After 10 years ROOT should have almost all the features you need, because probably someone needed it before

Page 4: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

The ROOT framework

A framework provides you with the tools (utilities and services) to do your work efficiently

Page 5: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

The ROOT framework

A framework provides you with the tools (utilities and services) to do your work efficiently For ROOT this includes the common tasks:

Command Line Interpreter (Macros) Histograms and Fitting Writing a Graphical User Interface 2D Graphics Input/Output …

The ROOT framework is OO Here C++ Encapsulation, Inheritance etc.

Page 6: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

More Information

http://root.cern.ch Latest Version Tutorials User‘s Guide Reference Guide ROOT-Talk

mailing list forum

Page 7: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Sort of an Outline

We want to work with ROOT Not all background information is needed (esp. the OO

philosphy) Start from simple examples (see also http://www-root.fnal.gov/root/)

ROOT structure and installation First ROOT session Command Line Basics Reading files The GUI Coming from PAW Macros

– Fitting– Trees

Best Of ROOT „unexpected“ effects Style Files

Page 8: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Installation

Do it yourself Binaries available for Linux, Unix, Windows, Mac … Or compile your own Or try out the PAIPIX live DVD (bootable Linux DVD for

scientists including ROOT, PAW, CERNLIB etc.) ROOT@IKP

On our LINUX workstations and the GRID-Cluster Default versions, change by setting ROOTSYS,

LD_LIBRARY_PATH and PATH > root

For all NWZNET users: Remote ssh-login to Linux Machine lambda.uni-muenster.de

Windows CIP-Pool (R210) and on the terminal server NWZHOME (Kudos to Jan Auffenberg) Command prompt I:\> root

setenv ROOTSYS /usr/local/root/5.04.00setenv PATH ${ROOTSYS}/bin/:${PATH}setenv LD_LIBRARY_PATH ${ROOTSYS}/lib

Page 9: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Installation

Do it yourself Binaries available for Linux, Unix, Windows, Mac … Or compile your own Or try out the PAIPIX live DVD (bootable Linux DVD for

scientists including ROOT, PAW, CERNLIB etc.) ROOT@IKP

On our LINUX workstations and the GRID-Cluster Default versions, change by setting ROOTSYS,

LD_LIBRARY_PATH and PATH > root

Windows CIP-Pool (R210) and on the terminal server NWZHOME (Kudos to Jan Auffenberg) Command prompt I:\> root

Page 10: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Framework Organization

*.h...

cintmakecintnewproofdproofservrmkdependrootroot.exerootcintroot-configrootd

bin

$ROOTSYS

libCint.solibCore.solibEG.so*libEGPythia.so*libEGPythia6.solibEGVenus.solibGpad.solibGraf.solibGraf3d.solibGui.solibGX11.so*libGX11TTF.solibHist.solibHistPainter.solibHtml.solibMatrix.solibMinuit.solibNew.solibPhysics.solibPostscript.solibProof.so*libRFIO.so*libRGL.solibRint.so*libThread.solibTree.solibTreePlayer.solibTreeViewer.so*libttf.solibX3d.solibXpm.a

Aclock.cxxAclock.hEvent.cxxEvent.hEventLinkDef.hHello.cxxHello.hMainEvent.cxxMakefileMakefile.inMakefile.win32READMETestVectors.cxxTetris.cxxTetris.heventa.cxxeventb.cxxeventload.cxxguitest.cxxhsimple.cxxhworld.cxxminexam.cxxstress.cxxtcollbm.cxxtcollex.cxxtest2html.cxxtstring.cxxvlazy.cxxvmatrix.cxxvvector.cxx

lib testtutorials include

* OptionalInstallation

EditorBar.CIfit.Canalyze.Carchi.Carrow.Cbasic.Cbasic.datbasic3d.Cbenchmarks.Ccanvas.Cclasscat.Ccleanup.Ccompile.Ccopytree.Ccopytree2.Cdemos.Cdemoshelp.Cdialogs.Cdirs.Cellipse.Ceval.Cevent.Cexec1.Cexec2.Cfeynman.Cfildir.Cfile.Cfillrandom.Cfirst.Cfit1.Cfit1_C.C

fitslicesy.Cformula1.Cframework.Cgames.Cgaxis.Cgeometry.Cgerrors.Cgerrors2.Cgraph.Ch1draw.Chadd.Chclient.Chcons.Chprod.Chserv.Chserv2.Chsimple.Chsum.ChsumTimer.Chtmlex.Cio.Clatex.Clatex2.Clatex3.Cmanyaxis.Cmultifit.Cmyfit.Cna49.Cna49geomfile.Cna49view.Cna49visible.C

ntuple1.Coldbenchmarks.Cpdg.datpsexam.Cpstable.Crootalias.Crootenv.Crootlogoff.Crootlogon.Crootmarks.Cruncatalog.sqlrunzdemo.Csecond.Cshapes.Cshared.Csplines.Csqlcreatedb.Csqlfilldb.Csqlselect.Cstaff.Cstaff.datsurfaces.Ctcl.Ctestrandom.Ctornado.Ctree.Ctwo.Cxyslider.CxysliderAction.Czdemo.C

Page 11: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Some ROOT Conventions

Classes begin with T: TH1F, TCanvas Non-class types end with _t:

Char_t Signed Character 1 byte Int_t Signed integer 4 bytes Float_t Float 4 bytes Double_t Float 8 bytes Bool_t Boolean (0=false, 1=true)

Global variables begin with g: gROOT, gDirectory Constansts began with k: kRed, kFullCircle More conventions for actual coding…

Page 12: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Start ROOT

Command Prompt:

-b: run in batch mode without graphics -l: do not show image logo -q: exit after processing command line script file(s)

> root [-b] [-q] [-l] [file1.C] [file2.root]

> root -b -q myMacro.C > myMacro.log

> root -b -q `myMacro.C(\“input.root\“)` > myMacro.log

Page 13: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Start ROOT

Command Prompt:

-b: run in batch mode without graphics -l: do not show image logo -q: exit after processing command line script file(s)

> root [-b] [-q] [-l] [file1.C] [file2.root]

Page 14: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Customizing ROOT

Environment Setup: rootrc ./.rootrc $HOME/.rootrc $ROOTSYS/etc/system.rootrc Defines e.g. load path for macros

Session specific: rootlogon.C, rootlogoff.C, rootalias.C Loaded in the sequence defined in rootrc Typically loads some shared libs or sets style

Unix.*.Root.MacroPath: .:${HOME}/root:${ROOTYS}/macros

{// load path defined in .rootrccout << ">>> ./rootlogon.C " << endl; gROOT->SetStyle("Plain");}

Page 15: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Three User Interfaces

GUI windows, buttons, menus

Root Command line CINT (C++ interpreter)

Macros, applications, libraries C++ compiler and interpreter Script and programming

language are the same! Remember PAW/KUIP

Personal bias towards command line and macros

Page 16: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Example 1 (Command Line): Open a file and draw a histogram

TFile is the ROOT class that handles files C++ syntax

Create a pointer f1 of type TFile

new object is initialized with (“hsimple.root“)

CINT commands are preceded by a “.“ (“.?“ for help on CINT) “.ls“: CINT command “gDirectory->ls()“: C++

equivalent

Page 17: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Example 1 (Command Line): Open a file and draw a histogram

TFile is the ROOT class that handles files C++ syntax

Create a pointer f1 of type TFile

new object is initialized with (“hsimple.root“)

CINT commands are preceded by a “.“ (“.?“ for help on CINT) “.ls“: CINT command “gDirectory->ls()“: C++

equivalent

Page 18: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

ROOT Classes (TFile Example)

Reference Guide: Find the class in the index, for

example TFile. Class Inheritance

TFile (is a) -> TDirectory -> TNamed -> TObject

Class Description Private members Public methods Code

Most ROOT classes are a TObject ROOT files organized like a unix

directory Also Subdirectories Open changes working directory

into the file Global variable

gDirectory ~ $PWD

Page 19: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

TFile Inheritance Tree

unix-like navigation

Page 20: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

TFile Example continued

All Information also available on command prompt CINT auto-completion

TAB

TAB

Page 21: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Drawing Histograms

Page 22: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Drawing Histograms

Page 23: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Drawing Histograms

How is hpx known?CINT/ROOT performs an implicit:gROOT->FindObject(“hpx“)

Why this new window?Need a canvas to draw the histogram, created automatically, implicit:TCanvas *c1 = new TCanvas(“c1“)

Page 24: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Changing the look…

root[] hpx->Draw()

Page 25: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Changing the look…

root[] gROOT->SetStyle(“Plain“)root[] gROOT->ForceStyle();

Page 26: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Changing the look…

root[] gStyle->SetOptStat(0)

Page 27: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Changing the look…

root[] hpx->SetXTitle(“p_{x} (GeV/c)“)root[] hpx->SetYTitle(“Count“)

Page 28: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Changing the look…

root[] hpx->SetMarkerStyle(kFullCircle)root[] hpx->SetMarkerColor(kBlue)root[] hpx->Draw(“PE“)

Page 29: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

The first macro

NB: Macro uses some implicit CINT/ROOT (read: non C++)declarations/initializations

Page 30: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Example 1 (GUI): Open a file and draw a histogram

Page 31: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Example 1 (GUI): Open a file and draw a histogram

Page 32: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Example 1 (GUI): Open a file and draw a histogram

Page 33: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Example 1 (GUI): Open a file and draw a histogram

Page 34: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Example 1 (GUI): Open a file and draw a histogram

Page 35: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Example 1 (GUI): Open a file and draw a histogram

You have to know how to access certain options: Via GUI and as well as via CL.

View->Editor Editor for each

component TCanvas TAxis TH1…

Lowercase difficult…

View->Toolbar Easy placement

of arrows, text Back to Macro

SaveAs: c1.C

Page 36: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

PAW to ROOT

What about old HBOOK/PAW files? Conversion tool coming with ROOT

More information http://root.cern.ch/root/HowtoConvert.html

PAW to ROOT command translations histo/plot 20 chopt (chopt=box/col/cont/...) h20->Draw("opt"); (opt = box/col/cont/...) http://root.cern.ch/root/HowtoConvertFromPAW.html

> h2root file.hbk file.root

Page 37: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Summary

ROOT installation and structure First steps

Opening a file Plotting a histogram Editing the histogram

PAW to ROOT conversion More Examples

Tutorials and examples: http://root.cern.ch/root/Tutorials.html

HowTo‘s: http://root.cern.ch/root/Howto.html Reference Guide: http://root.cern.ch/root/Reference.html

Page 38: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

What‘s next

Macros CINT traps Compiled vs. interpreted

Histogram and file creation Tree creation

Fitting Predefined functions User defined functions

Styles Create your own plot style

Page 39: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Macro execution

Macro as CL argument

Execution in ROOT

> root plot1.C

root[] .x plot1.C

Un-named macro

Page 40: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Macro execution

Macro as CL argument

Execution in ROOT

Load and execute

> root plot1.C

root[] .x plot1.C

root[] .L plot2.Croot[] plot2()

Un-named macro

named macro

Page 41: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Macro execution

Macro as CL argument

Execution in ROOT

Load and execute

Compile and execute

ACLiC (Automatic Compiler of Libraries for CINT)

Compile-time overhead Large macros/many operations

> root plot1.C

root[] .x plot1.C

root[] .L plot2.Croot[] plot2()

root[] .L plot3.C++root[] plot3()

Page 42: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

CINT traps

The Command line and the interpretation of macros is driven by CINT (C/C++-INTerpreter by Masaharu Goto) Covers 95% of ANSI C 85% of ANSI-C++

void func(){ int i; for(i=0;i<10;i++) { int n; /* block scope */ printf("n=%d\\n",n++); } /* n is still alive here in cint, n should be already dead in ANSI C */ }

All variables global

{TFile *f1 = new TFile(“hsimple.root”);f1.ls(); // Not allowed in C++/tolerated in // CINTf1->ls(); // Correct C++

TFile f2(“hsimple.root”);f2->ls(); // Not allowed in C++/tolerated in // CINTf1.ls(); // Correct C++}

Pointers and objects treated similar

The ROOT CL/CINT does not teach you 100% correct C++

TH1F *h1 = new TH1F(“htest“,“Test“,2,0.,2.);htest->Draw();

Implicit Search

Page 43: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Histogram Creation

#include "TSystem.h"#include "TROOT.h"#include "TRandom.h"#include "TH1F.h" // 1-dim histogram of floats#include "TCanvas.h"#include "TStopwatch.h"

#include <iostream>using namespace std;

void histos1(){ TStopwatch timer; timer.Start();

gROOT->SetStyle("Plain"); // create TH1F *h1 = new TH1F("h1","My first histo",100,-4.,4.); // fill for(Int_t i = 0;i<(Int_t)1E+06;i++){ // create a random number following a Gaussian Float_t ran = gRandom->Gaus(0,0.5); h1->Fill(ran); }// loop over i

TCanvas *c1 = new TCanvas(); h1->DrawCopy(); c1->Update(); c1->SaveAs("h1.gif"); timer.Stop(); char cTmp[100]; sprintf(cTmp,"Real Time: %7.3f s, CPU Time: %7.3f s", timer.RealTime(),timer.CpuTime()); cout << cTmp << endl;}

Page 44: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Histogram Creation

TH1F constructor char* name char* title Int_t nbinsx Axis_t xlow Axis_t xup (Axis_t ~ double)

Fill(Axis_t x) Fill(Axis_t x,Stat_t w)

DrawCopy(char* copt) Clone the histogram and

draw the copy Interpreted vs. compiled

#include "TSystem.h"#include "TROOT.h"#include "TRandom.h"#include "TH1F.h" // 1-dim histogram of floats#include "TCanvas.h"#include "TStopwatch.h"

#include <iostream>using namespace std;

void histos1(){ TStopwatch timer; timer.Start();

gROOT->SetStyle("Plain"); // create TH1F *h1 = new TH1F("h1","My first histo",100,-4.,4.); // fill for(Int_t i = 0;i<(Int_t)1E+06;i++){ // create a random number following a Gaussian Float_t ran = gRandom->Gaus(0,0.5); h1->Fill(ran); }// loop over i

TCanvas *c1 = new TCanvas(); h1->DrawCopy(); c1->Update(); c1->SaveAs("h1.gif"); timer.Stop(); char cTmp[100]; sprintf(cTmp,"Real Time: %7.3f s, CPU Time: %7.3f s", timer.RealTime(),timer.CpuTime()); cout << cTmp << endl;}

107.3 s1.723 s0.671 sInterpr.

44.6 s1.111 s0.640 sCompiled

1E+081E+061E+04

Page 45: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Writing to a File

TFile constructur char* filename char *option

READ (default) NEW RECREATE UPDATE

Need to put the histogram into the file!!!

SetDirectory(TDirectory *d) Create the histogram within

the file structure in memory f1->cd();

#include "TSystem.h"#include "TROOT.h"#include "TFile.h"#include "TRandom.h"#include "TH1F.h"

void write(){ // create TH1F *h1 = new TH1F("h1","My first histo",100,-4.,4.); for(Int_t i = 0;i<(Int_t)1E+06;i++){ // create a random number following a Gaussian Float_t ran = gRandom->Gaus(0,0.5); h1->Fill(ran); }// loop over i

// open and write TFile *f1 = new TFile("h1.root","RECREATE"); h1->SetDirectory(f1); f1->Write(); f1->Close();

}

Page 46: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Writing to a File

TFile constructur char* filename char *option

READ (default) NEW RECREATE UPDATE

Need to put the histogram into the file!!!

SetDirectory(TDirectory *d) Create the histogram within

the file structure in memory f1->cd();

#include "TSystem.h"#include "TROOT.h"#include "TFile.h"#include "TRandom.h"#include "TH1F.h"

void write(){ // create TH1F *h1 = new TH1F("h1","My first histo",100,-4.,4.); for(Int_t i = 0;i<(Int_t)1E+06;i++){ // create a random number following a Gaussian Float_t ran = gRandom->Gaus(0,0.5); h1->Fill(ran); }// loop over i

// open and write TFile *f1 = new TFile("h1.root","RECREATE"); h1->SetDirectory(f1); f1->Write(); f1->Close();

}

#include "TSystem.h"#include "TROOT.h"#include "TFile.h"#include "TRandom.h"#include "TH1F.h"

void write(){ // open the file TFile *f1 = new TFile("h1.root","RECREATE"); // create TH1F *h1 = new TH1F("h1","My first histo",100,-4.,4.); for(Int_t i = 0;i<(Int_t)1E+06;i++){ // create a random number following a Gaussian Float_t ran = gRandom->Gaus(0,0.5); h1->Fill(ran); }// loop over i

// write f1->Write(); f1->Close();

}

Page 47: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Read a histogram from a file

Open file Get the object from the file

TObject* Get(char* name) Cast to correct type

We are still in the file If we close the object is lost

(Seg. fault) Set (memory copy) into

gROOT Same for Copy of the histo

TObject* Clone(char *newname)

#include "TSystem.h"#include "TROOT.h"#include "TFile.h"#include "TRandom.h"#include "TH1F.h"#include "TCanvas.h"

void reread(){

gROOT->SetStyle("Plain"); TCanvas *c1 = new TCanvas();

TFile *f1 = new TFile("h1.root"); TH1F *hTmp = (TH1F*)f1->Get("h1"); hTmp->SetDirectory(gROOT); // make a copy TH1F *h1 = (TH1F*)hTmp->Clone("h1_1"); h1->SetDirectory(gROOT); f1->Close(); hTmp->DrawCopy(); h1->SetMarkerStyle(kOpenTriangleUp); h1->DrawCopy("Psame"); c1->Update(); c1->SaveAs("reread.gif");}

Page 48: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Read a histogram from a file

#include "TSystem.h"#include "TROOT.h"#include "TFile.h"#include "TRandom.h"#include "TH1F.h"#include "TCanvas.h"

void reread(){

gROOT->SetStyle("Plain"); TCanvas *c1 = new TCanvas();

TFile *f1 = new TFile("h1.root"); TH1F *hTmp = (TH1F*)f1->Get("h1"); hTmp->SetDirectory(gROOT); // make a copy TH1F *h1 = (TH1F*)hTmp->Clone("h1_1"); h1->SetDirectory(gROOT); f1->Close(); hTmp->DrawCopy(); h1->SetMarkerStyle(kOpenTriangleUp); h1->DrawCopy("Psame"); c1->Update(); c1->SaveAs("reread.gif");}

Page 49: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Functions and Fitting

Function Objects TF1 Three constructors for TF1 User defined functions

Fitting Fit() Subranges and combining functions Fitting background and signal

Page 50: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

TF1 Function Objects

Builtin functions “gaus“, “pol0-9“, “expo“, “landau“

root[] gaus->SetParameters(1,0,3)root[] gaus->Draw()

Page 51: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

TF1 Function Objects

Builtin functions “gaus“, “pol0-9“, “expo“, “landau“

Constructors TF1(const char* name, const char* formula, Double_t xmin = 0, Double_t xmax = 1)

root[] gaus->SetParameters(1,0,3)root[] gaus->Draw()

root[] TF1 *f1 = new TF1(“myfunc“,“[0]*sin(x)/x“,0,10)root[] f1->SetParameter(0,2)root[] f1->Draw()

Page 52: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

TF1 Function Objects

Builtin functions “gaus“, “pol0-9“, “expo“, “landau“

Constructors TF1(const char* name, const char* formula, Double_t xmin = 0, Double_t xmax = 1)

TF1(const char* name, void* fcn, Double_t xmin, Double_t xmax, Int_t npar)

root[] gaus->SetParameters(1,0,3)root[] gaus->Draw()

Double_t fitf(Double_t *x, Double_t *par){ Double_t arg = 0; if (par[2] != 0) arg = (x[0] - par[1])/par[2];

Double_t fitval = par[0]*TMath::Exp(-0.5*arg*arg); return fitval;}

void myfit(){// Creates a Root function based on function fitf above TF1 *func = new TF1("fitf",fitf,-2,2,3);}

Page 53: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

TF1 Function Objects

Builtin functions “gaus“, “pol0-9“, “expo“, “landau“

Constructors TF1(const char* name, const char* formula, Double_t xmin = 0, Double_t xmax = 1) TF1(const char* name, void* fcn, Double_t xmin, Double_t xmax, Int_t npar)

Some usefull member functions SetParameters() SetRange() Integral()

Similar for TF2, TF3

root[] gaus->SetParameters(1,0,3)root[] gaus->Draw()

Page 54: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Fitting

Two ways to address the fitting function Name Pointer

root[] hpx->Fit(“gaus“)

root[] hpx->Fit(func)

Page 55: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Fitting

Two ways to address the fitting function Name Pointer

Better initialize the function parameters

Fitting a (sub-)range Range given in TF1 constructor or via SetRange(x1,x2)

root[] hpx->Fit(“gaus“)

root[] hpx->Fit(func)

root[] func->SetParameters(hpx->GetMaximum(),hpx->GetMean(),hpx->GetRMS())

root[] hpx->Fit(func,“R“)

Page 56: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Fitting

Two ways to address the fitting function Name Pointer

Better initialize the function parameters

Fitting a (sub-)range Range given in TF1 constructor or via SetRange(x1,x2)

Fit paramters printed on console Suppress with option “Q“

Function „added“ to histogram Suppress with option “0“

root[] hpx->Fit(“gaus“)

root[] hpx->Fit(func)

root[] func->SetParameters(hpx->GetMaximum(),hpx->GetMean(),hpx->GetRMS())

root[] hpx->Fit(func,“R“)

Page 57: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Fitting Example

Double_t fitf(Double_t *x, Double_t *par){ Double_t arg = 0; if (par[2] != 0) arg = (x[0] - par[1])/par[2];

Double_t fitval = par[0]*TMath::Exp(-0.5*arg*arg); return fitval;}

void myfit(){// Creates a Root function based on function fitf above TF1 *func = new TF1("fitf",fitf,-2,2,3);

TFile *f = new TFile("hsimple.root");

TCanvas *c1 = new TCanvas("c1","the fit canvas",500,400);

TH1F *hpx = (TH1F*)f->Get("hpx");// Sets initial values and parameter names func->SetParameters(100,0,1); func->SetParNames("Constant","Mean_value","Sigma");

// Fit histogram in range defined by function hpx->Fit(func,"r");

// Gets integral of function between fit limits printf("Integral of function = %g\n",func->Integral(-2,2));}

Page 58: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

A real life Example

Two photon correlation via decay π0 → γγ (m = 135 MeV/c2) η → γγ (m = 548 MeV/c2)

Analysis Calculate invariant mass of all possible photon pair

combination: minv = 2 E1E2 (1- cos θ)

Combinatorial background: Nγγ = Nγ (Nγ - 1)/2 Estimated by mixing different events (uncorrelated

photons) Scaling of mixed event background Subtract background

Page 59: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

A real-life Example

void RealMixFit(){

TCanvas *c1 = new TCanvas(); gStyle->SetOptStat(0); gROOT->ForceStyle();

TFile *f1 = new TFile("pi0_scan9_pid3_C9-17_bins64_rebin2_“ “nSigEx3.0_W0_W1_W2_W3_E2_E3_date000000.root");

// Get the real Events TH1F *hreal = (TH1F*)f1->Get("hRealSave26"); TH1F *hmix = (TH1F*)f1->Get("hMixSave26"); hmix->SetXTitle("m_{inv} (GeV/c^{2})"); hmix->SetMarkerStyle(kFullCircle); hreal->SetXTitle("m_{inv} (GeV/c^{2})"); hreal->SetMarkerStyle(kFullCircle);

hreal->DrawCopy(); c1->Update(); c1->SaveAs("real.gif"); if(getchar()=='q')return;

Nothing new: Read and plot the invariant

mass histogram

Page 60: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

A real-life Example

TH1F* hratio = (TH1F*)hreal->Clone("hratio"); hratio->Divide(hmix); hratio->DrawCopy();

// Reset peak areas... for(int ib = 1;ib<=hratio->GetNbinsX();ib++){ Float_t x = hratio->GetBinCenter(ib); if(x < 0.130+3.*0.01){ // exclude pi0, nominal mass 0.135 hratio->SetBinContent(ib,0); hratio->SetBinError(ib,0); } if((x < 0.51+3.*0.03)&&(x > 0.548-3.*0.03)){ // exclude eta hratio->SetBinContent(ib,0); hratio->SetBinError(ib,0); } } hratio->SetMarkerColor(kBlue); hratio->DrawCopy("same"); TF1 *poli1 = new TF1("poli1","pol1",0.1,0.9); hratio->Fit(poli1,"RQ0"); poli1->SetRange(0,1.);

c1->Update(); c1->SaveAs("realovermix.gif"); if(getchar()=='q')return;

Determine a scaling function by fitting the ratio

Page 61: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

A real-life Example

// scale mix.... for(int ib = 1;ib<=hmix->GetNbinsX();ib++){ Float_t x = hmix->GetBinCenter(ib); Float_t cont = hmix->GetBinContent(ib); Float_t err = hmix->GetBinError(ib); Float_t fScale = poli1->Eval(x); hmix->SetBinContent(ib,cont*fScale); hmix->SetBinError(ib,err*fScale); }

hreal->DrawCopy(); hmix->SetMarkerColor(kBlue); hmix->DrawCopy("same"); c1->Update(); c1->SaveAs("realscaledmix.gif"); if(getchar()=='q')

Scale the backgroundaccordingly

Page 62: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

A real-life Example

TH1F* hdiff = (TH1F*)hreal->Clone("hdiff"); hdiff->Add(hmix,-1.); hdiff->DrawCopy(); TF1 *myg1 = new TF1("myg","gaus",0.05,0.2); myg1->SetLineColor(kRed); hdiff->Fit(myg1,"R"); TF1 *myg2 = new TF1("myg","gaus",0.4,0.6); myg2->SetLineColor(kYellow); hdiff->Fit(myg2,"R+"); c1->Update(); c1->SaveAs("realminusmix.gif"); if(getchar()=='q')return;

Subtract the backgroundand fit the peaks

Control of Energy scale (here ~ 5.5% off)

Page 63: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Trees, a snapshot…

Object TTree TTree has branches and

leaves Branch i.e. a track with px,

py, pz as leaves can be anything (C-struct,

TObject etc) Branch can also be single

float… Usually filled on a per-

cycle/-event basis Store large quantities of same

type structure data Many sophisticated I/O

features Here only simple examples

Page 64: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Tree creation

Create tree and add branches

NB: no constructor for branch element

Only associate variable branch name with pointer and type

Filled for each cycle

px, py, pz and ev change per event

Fill writes to the tree Write Tree at the end to file (to

gDirectory!!)

void tree1w() { // create a tree file tree1.root - create the file, // the Tree and a few branches TFile f("tree1.root","recreate"); TTree t1("t1","a simple Tree with simple variables"); Float_t px, py, pz; Double_t random; Int_t ev; t1.Branch("px",&px,"px/F"); t1.Branch("py",&py,"py/F"); t1.Branch("pz",&pz,"pz/F"); t1.Branch("ev",&ev,"ev/I"); //fill the tree for (Int_t i=0; i<10000; i++) { gRandom->Rannor(px,py); pz = px*px + py*py; ev = i; t1.Fill(); } //save the Tree heade; the file will be automatically closed //when going out of the function scope t1.Write();}

Page 65: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Tree usage

Graphical interface

CL Information on TTree

root[] t1->StartViewer()

root[] t1->Print()

Page 66: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Tree usage

Graphical interface

CL Information on TTree

CL Information on specific entry

root[] t1->StartViewer()

root[] t1->Print()

root[] t1->Show(10)

Page 67: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Tree usage

Graphical interface

CL Information on TTree

CL Information on specific entry

Plot (into htemp) 1D plots 2D plots Cuts Redirect: Draw(“px>>hUser“)

root[] t1->StartViewer()

root[] t1->Print()

root[] t1->Show(10)

Page 68: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Tree usage

Graphical interface

CL Information on TTree

CL Information on specific entry

Plot (into htemp) 1D plots 2D plots Cuts Redirect: Draw(“px>>hUser“)

More sophisticated operations Read Tree via macro

root[] t1->StartViewer()

root[] t1->Print()

root[] t1->Show(10)

root[] t1->MakeCode(“x.C“)

//////////////////////////////////////////////////////////// This file has been automatically generated // (Tue Nov 15 17:06:52 2005 by ROOT version4.04/02)// from TTree t1/a simple Tree with simple variables// found on file: tree1.root//////////////////////////////////////////////////////////

gROOT->Reset(); TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject("tree1.root"); if (!f) { f = new TFile("tree1.root"); } TTree *t1 = (TTree*)gDirectory->Get("t1");//Declaration of leaves types Float_t px; Float_t py; Float_t pz; Int_t ev; // Set branch addresses. t1->SetBranchAddress("px",&px); t1->SetBranchAddress("py",&py); t1->SetBranchAddress("pz",&pz); t1->SetBranchAddress("ev",&ev);// This is the loop skeleton// To read only selected branches, Insert statements like:// t1->SetBranchStatus("*",0); // disable all branches// TTreePlayer->SetBranchStatus("branchname",1); // activate branchname Long64_t nentries = t1->GetEntries();

Int_t nbytes = 0;// for (Long64_t i=0; i<nentries;i++) {// nbytes += t1->GetEntry(i);// }

Page 69: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

ROOT Styles

Common Problem Need different styles for

publication, talk, thesis Colormap Fonts …

Root solution: TStyle Some builtin styles

Plain Pub Bold Video

User defined styles files…

Plain

Video

root[] gROOT->SetStyle(“Plain“)

Page 70: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

User Style Files

Numerous Options See TStyle reference guide

for more details Fonts Axis offsets Linewidth…

void makeplotstyle(){ TStyle *pstyle = new TStyle("PlotStyle1", "Style for single Thesis Plots"); pstyle->SetPalette(1); pstyle->SetCanvasColor(10); pstyle->SetHistFillColor(10); pstyle->SetHistFillStyle(0); pstyle->SetOptTitle(0); pstyle->SetOptStat(0); pstyle->SetPadLeftMargin(0.17); pstyle->SetPadBottomMargin(0.2); pstyle->SetPadTickX(1); pstyle->SetPadTickY(1); pstyle->SetAxisColor(1, "XYZ"); pstyle->SetLabelColor(1, "XYZ"); pstyle->SetTickLength(0.03, "XYZ"); pstyle->SetTitleXSize(0.07); pstyle->SetTitleYSize(0.07); pstyle->SetNdivisions(505, "XYZ"); pstyle->SetLabelOffset(0.02, "XYZ"); pstyle->SetLabelSize(0.05, "XYZ"); pstyle->SetPadLeftMargin(0.2); pstyle->SetPadRightMargin(0.03); pstyle->SetPadBottomMargin(0.2); pstyle->SetTitleXOffset(0.9); // 1.1 pstyle->SetTitleYOffset(0.9); // 1-4 pstyle->SetMarkerSize(1.4); // pstyle->SetLineWidth(2); // pstyle->SetErrorX(0); //removes x-axis error bars // type * 10 + prec 6: helvetica bold 13: times normal 2: times bold const int iFont = 132; pstyle->SetLabelFont(iFont,"xyz"); pstyle->SetStatFont(iFont); pstyle->SetTitleFont(iFont); pstyle->SetTextFont(iFont); TFile f("plotstyle.root", "RECREATE"); f.cd(); pstyle->Write(); f.Close();}

void style(){ TFile *f1 = new TFile("plotstyle.root"); TStyle *s1 = (TStyle*)f1->Get("PlotStyle1"); s1->cd(); gROOT->ForceStyle();

TCanvas *c1 = new TCanvas(); TFile *f1 = new TFile("hsimple.root"); TH1F* h1 = (TH1F*)f1->Get("hpx"); h1->SetXTitle("p_{x} (GeV/c)"); h1->SetYTitle("Count"); h1->Draw(); c1->Update(); c1->SaveAs("mystyle.gif");}

Page 71: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Summary II

Macro execution Compiled vs. interpreted

CINT traps Histogram creation Read/write with root files

Remember the internal directory structure! Functions and fitting Root trees (snapshot) Root styles user defined styles

gROOT->SetStyle(“Plain“)

Page 72: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Create Your Own Class for ROOT I

Example: Generic particle information Inherit from TObject

Basic root-functionality char* GetClassName() FindObject()...

ClassDef macro Streamers Basic methods ${ROOTSYS}/include/Rtypes.h

MyParticle.h#ifndef ROOT_MyParticle#define ROOT_MyParticle

#include "TObject.h"

class MyParticle : public TObject { private: Int_t fNPID; // particle type Double_t fMom[3]; // particle momentum Double_t fVert[3]; // particle Vertex public: MyParticle(){... }

~MyParticle(){}

Double_t GetPx(){return fMom[0];} Double_t GetPy(){return fMom[1];} Double_t GetPz(){return fMom[2];} Double_t* GetMomentum(){return fMom;}

void SetPx(Double_t fPx){fMom[0] = fPx;} void SetPy(Double_t fPy){fMom[1] = fPy;} void SetPz(Double_t fPz){fMom[2] = fPz;} ... ClassDef(MyParticle,1)};

#endif}

Page 73: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Create Your Own Class for ROOT II

ROOT needs some more information to know your class ClassImp Macro

MyMacroLinkDef.h Used to generate dictionary information Defines what is available at the root prompt

MyParticle.C#include "MyParticle.h"

ClassImp(MyParticle)

#ifdef __CINT__

#pragma link off all globals;#pragma link off all classes;#pragma link off all functions;

#pragma link C++ class MyParticle+;

#endif

Page 74: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Create Your Own Class for ROOT III

Makefile Link and compile with

current root settings „root-config“ script

Generate dictionary information via rootcint

PACKAGE = MyParticle

ROOTINC := $(shell root-config --incdir)ROOTLIBS := $(shell root-config --libs)

CXXFLAGS = -I. -I$(ROOTINC) -Wall CINTINCLUDES = -I. -I$(ROOTINC)

LIBS = $(ROOTLIBS)

HDRFILES = $(PACKAGE).hLINKFILES = $(PACKAGE)LinkDef.h

SO = lib$(PACKAGE).so

$(SO) : $(PACKAGE).C $(PACKAGE)_dict.C $(HDRFILES)$(CXX) $(CXXFLAGS) -g -o $@ -shared $< \$(LIBS) $(PACKAGE)_dict.C

$(PACKAGE)_dict.C : $(HDRFILES) $(LINKFILE)rootcint -f $@ -c $(CINTINCLUDES) $^

.PHONY: cleanclean:

rm -f $(SO)rm -f $(PACKAGE)_dict.*

rootcint -f MyParticle_dict.C -c -I. -I/usr/local/root/4.04.02/include MyParticle.h

Page 75: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Use Your Own Class

TAB

Same CL-functionality as any ROOT class (such as TH1F, TFile..)

Page 76: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Final Summary

ROOT installation and structure

First steps on histogram and file handling

Macro execution (compiled and interpreted)

Read/write with root files

Functions and fitting

ROOT styles nnd user defined styles

All examples: http://qgp.uni-muenster.de/~stevero/talks/root_tutorial/macros.tgz

More Examples Tutorials and examples: http://root.cern.ch/root/Tutorials.html HowTo‘s: http://root.cern.ch/root/Howto.html Reference Guide: http://root.cern.ch/root/Reference.html

Page 77: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Final Summary

This was a first attempt of a root crash course Completely biased by personal experience, preferences and

limited knowledge What's missing? What's not needed? Barely touched the surface of ROOT's capabilities

Page 78: A Short Introduction to ROOT - uni-muenster.de

ROOT Intro

Final Summary

This was a first attempt of a root crash course Completely biased by personal experience, preferences and

limited knowledge What's missing? What's not needed? Barely touched the surface of ROOT's capabilities