Corso di Analisi dei Dati e delle Informazioni *

Similar documents
Brent A. Perdue. July 15, 2009

Introduction to ROOT

11 Input/Output. The Physical Layout of ROOT Files

Introduction to ROOT and data analysis

GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4GO4G

An Incomplete C++ Primer. University of Wyoming MA 5310

ROOT Basics. Deb Mohapatra. This lecture is based on Fermilab ROOT tutorial and ROOT lecture in CERN summer school

Use of ROOT in Geant4

12 Trees. Why Should You Use a Tree? A Simple TTree

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

The C Programming Language course syllabus associate level

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

16 Collection Classes

Makefiles and ROOT. Sean Brisbane 12/12/11

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

C++ Programming Language

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

C++ INTERVIEW QUESTIONS

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

25 Writing a Graphical User Interface

Web-based based Access to ROOT

Glossary of Object Oriented Terms

Getting Started with the Internet Communications Engine

A QUICK OVERVIEW OF THE OMNeT++ IDE

ROOT: A Data Analysis and Data Mining Tool from CERN

CISC 181 Project 3 Designing Classes for Bank Accounts

Appendix K Introduction to Microsoft Visual C++ 6.0

C++FA 5.1 PRACTICE MID-TERM EXAM

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

WESTMORELAND COUNTY PUBLIC SCHOOLS Integrated Instructional Pacing Guide and Checklist Computer Math

C Programming Review & Productivity Tools

Fundamentals of Java Programming

CS 103 Lab Linux and Virtual Machines

El Dorado Union High School District Educational Services

DiskPulse DISK CHANGE MONITOR

Xcode Project Management Guide. (Legacy)

Leak Check Version 2.1 for Linux TM

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

CORBA Programming with TAOX11. The C++11 CORBA Implementation

This chapter is an example of a typical physics analysis. Large data files are chained together and analyzed using the TSelector class.

Compiler Construction

Object Oriented Software Design II

Monitoring, Tracing, Debugging (Under Construction)

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

Getting off the ground when creating an RVM test-bench

Visual Basic Programming. An Introduction

Introduction to Matlab

TEL2821/IS2150: INTRODUCTION TO SECURITY Lab: Operating Systems and Access Control

2. Advance Certificate Course in Information Technology

Understand for FORTRAN

The System Monitor Handbook. Chris Schlaeger John Tapsell Chris Schlaeger Tobias Koenig

Introduction. What is an Operating System?

AP Computer Science Java Subset

CS506 Web Design and Development Solved Online Quiz No. 01

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Curriculum Map. Discipline: Computer Science Course: C++

Facebook Twitter YouTube Google Plus Website

ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology)

Web interface for online ROOT and DAQ applications

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

Beginner s Matlab Tutorial

Appendix M: Introduction to Microsoft Visual C Express Edition

Basics of I/O Streams and File I/O

Object Oriented Software Design II

Netscape Internet Service Broker for C++ Programmer's Guide. Contents

C++ Overloading, Constructors, Assignment operator

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Developing an ODBC C++ Client with MySQL Database

N3458: Simple Database Integration in C++11

Working with Excel in Origin

Illustration 1: Diagram of program function and data flow

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1


Running your first Linux Program

Visual Studio 2008 Express Editions

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Elixir Schedule Designer User Manual

IVI Configuration Store

Java (12 Weeks) Introduction to Java Programming Language

#pragma omp critical x = x + 1; !$OMP CRITICAL X = X + 1!$OMP END CRITICAL. (Very inefficiant) example using critical instead of reduction:

CatDV Pro Workgroup Serve r

Computing Concepts with Java Essentials

Compute Cluster Server Lab 3: Debugging the parallel MPI programs in Microsoft Visual Studio 2005

Unit Storage Structures 1. Storage Structures. Unit 4.3

Parallel and Distributed Computing Programming Assignment 1

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

C++ Crash Kurs. C++ Object-Oriented Programming

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

MOVES Batch Mode: Setting up and running groups of related MOVES run specifications. EPA Office of Transportation and Air Quality 11/3/2010

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

Parallelization: Binary Tree Traversal

Xeon Phi Application Development on Windows OS

Good FORTRAN Programs

AN INTRODUCTION TO UNIX

Comp151. Definitions & Declarations

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

Course MS10975A Introduction to Programming. Length: 5 Days

MAS 500 Intelligence Tips and Tricks Booklet Vol. 1

Transcription:

Corso di Analisi dei Dati e delle Informazioni * University of Pavia Doctorate School in Physics 2015 edition ROOT: an object-oriented Data Analysis framework * CADI: caṡo s. m. [dal lat. casus -us, propr. «caduta», der. di cadĕre «cadere», dal gioco dei dadi] Andrea Fontana Istituto Nazionale di Fisica Nucleare Sezione di Pavia

Course program C++ review A Vector3 class ROOT classes Interactive sessions, named and unnamed macros Graphs Histograms Ntuples Trees Tfiles Random numbers Mininimization with Tminuit ROOT exercises MC theory: Buffon s needle MC basics: central limit, hit or miss, tests n random generators Best fit with Minuit: Gradient, simplex, seek Chi2 and likelihood Binned and unbinned data Parameters estimation Statistical tests Addendum: Excel advances Solver Statistical tests External (free) libraries

ROOT classes The backbone of the ROOT architecture is a layered class hierarchy with, currently, around 1200 classes grouped in about 60 frameworks (libraries) divided in 19 main categories (modules). This hierarchy is organized in a mostly single-rooted class library, that is, most of the classes inherit from a common base class TObject.

Mother of all ROOT objects. Tobject and ROOT classes hierarchy The TObject class provides default behaviour and protocol for all objects in the ROOT system. It provides protocol for object I/O, error handling, sorting, inspection, printing, drawing, etc. Every object which inherits from TObject can be stored in the ROOT collection classes.

ROOT classes used in Physics ROOT has been developed by physicists and it was originally thought as a tool for physicists in the HEP community for analysing and displaying data. Now ROOT is much more widely known and used and its role became more general: it is now used in other fields, like in mathematical finance and in banking/trading. Its main role is still for the physicist, though, and the classes that it provides that are useful for us can be grouped as follows: - classes for data analysis; - classes for Physics computations and simulations; - classes for programming graphical interfaces;

ROOT analysis classes The first classes to be studied to start playing with ROOT are the ones to create histograms, graphs and trees/ntuples and to save them in ROOT files. Since these classes play a central role in many ROOT applications in HEP, We will see how to use them: - TF1 - TGraph - TH1F, TH2F - TNtuple - TFile - TTree We ll see also how to fit an experimental histogram with a parametrical function (e.g. a Gauss distribution).

Functions ROOT can be used to display a function of one variable, x TF1 *f1 = new TF1("f1","sin(x)/x",0.,10.); f1->draw(); A slightly extended version of this example is the definition of a function with parameters, called [0], [1] and so on in the ROOT formula syntax TF1 *f1 = new TF1("f2","[0]*sin([1]*x)/x",0.,10.); f1->setparameter(0,1); f1->setparameter(1,1); f1->draw();

User defined functions ROOT can be used to display also user functions of n variables and m parameters, by passing a pointer to the array of variables and to the array of parameters: double func(double *x, double *p) { return p[0]+p[1]*pow(x[0],1); } The function can be defined, together with the parameters, as: TF1 *f=new TF1("f",func,0,10,2); f->setparameter(0,1); f->setparameter(1,1); f->draw();

Graphs A graph is a graphical object made of two arrays X and Y and it holds the x,y coordinates of N points. First the data vectors with N elements are defined and the the constructor is invoked: Int_t N=10; Double_t x[n], y[n]; TGraph *g1 = new TGraph(N, x, y); The graph is drawn with: g1->draw(); and many graphical options are available: g1->draw( AL ); axis with polyline between points g1->draw( A* ); star at each point g1->draw( AB ); bar chart Graphs can be superimposed by leaving out the A option for the second graph or using a MultiGraph.

A sample Graph grandom->uniform(0.,1.)

Multigraphs Using a MultiGraph is a cool way to plot various graphs on the same canvas. A TMultiGraph object is simply a collection of TGraph objects (think of it like of an array of TGraphs ) Assuming to have two independent graphs: TGraph *g1 = new Tgraph(N, x1, y1); TGraph *g2 = new Tgraph(N, x2, y2); we can plot them on the same sheet: TMultiGraph *mg = new TMultiGraph(); mg->add(g1); mg->add(g2); mg->draw( ALP );

Graphs: input from ASCII files A graph is a graphical object made of two arrays X and Y and it holds the x,y coordinates of N points. TGraphErrors(const char *filename, const char *format="%lg %lg %lg %lg", Option_t *option=""); The format string can be: "%lg %lg" read only 2 first columns into X,Y "%lg %lg %lg" read only 3 first columns into X,Y and EY "%lg %lg %lg %lg" read only 4 first columns into X,Y,EX,EY

Histograms ROOT supports histograms in 1D, 2D and 3D and also profile histograms. Histograms are created with the constructor: TH1F *h1 = new TH1F( h1, h1 title, 100, 0, 5); TH2F *h2 = new TH2F( h2, h2 title, 100, 0, 5, 100, -1, 1); With the following parameters (for the TH1 object): - histogram s name (TH1F inherits from TNamed) - histogram s title - number of bins - x minimum - x maximum The bin size is fixed by default, but variable bin sizes are supported with the constructor TH1F *h1 = new TH1F( h1, h1 title, 100, xbins); where xbins is an array of low edges for each bin.

Filling Histograms Histograms are filled using the Fill() method that is overloaded to handle different cases: h1->fill(x); h1->fill(x,w); h2->fill(x,y); h2->fill(x,y,w); The Fill() method computes the bin number corresponding to the given x and y argument and increments this bin by the given weight (the default weight is 1). During filling some statistical parameters are incremented to compute the mean value and the root mean square. A random number filling method is available to fill histograms according to a distribution: h1->fillrandom( gaus,10000);

Drawing Histograms Histograms can be drawn in various formats and with many options. The basic command is: h1->draw(); The histogram is drawn inside a TPad and within a TCanvas. These are graphical objects used to store multiple histograms in the same view: Tcanvas *c1 = new Tcanvas( c1, Canvas with histos ); c1->divide(1,2); c1->cd(1); h1->draw(); c1->cd(2); h2->draw(); It is possible to superimpose histograms with: h1->draw(); h2->draw( same );

A sample 1D histogram

Fitting Histogram ROOT provides a graphical interface to fit 1D histograms according to well known and very common functions: Gaussian, Landau, Polynomia and user functions. To fit an histogram with a user function, it is necessary to write a separate function that holds the function and the parameters in an array. Better method: class TMinuit.

Comparing TF1, TGraph and TH1F Some warnings on common operations, like: Direct comparison Rescaling Normalization Integration See example

TNtuple Ntuples are very common data structures in the HEP community to store experimental data and their use stems from the days of PAW and fortran programming. An ntuple can be thought as a spreadsheet table in two dimensions and it is a structure optimized to collect and store numerical data into a ROOT file. It is built with the constructor: Tntuple *nt = new Tntuple( ntuple, A simple table, x:y ); and filled (within a loop where x and y are evaluated) with: ntuple->fill(x,y); It can be viewed and browsed with: ntuple->print(); ntuple->scan();

Working with data in ntuples The Scan() method allows to browse through all the ntuple entries. It is also possible to make cuts on variables with commands like: ntuple->scan( x, y>0.5 ); It is possible to directly draw histograms of data entries in ntuples by invoking the Draw() method for the ntuple. A default histogram called htemp is draw n on a default canvas: ntuple->draw( x );

The C++ interpreter Written by Masaharu Goto in C (up to ROOT 5) CLING in ROOT6 (very new!) Standalone (non root) version available Incorporated in ROOT Applied for: Interactive command line Macro execution (language: C++ with extras); may compile macro at runtime (ACLiC feature) for debugging purposes Generates object introspection metadata ( dictionary ) when compiling ROOT

CINT command line 1. CINT native commands start with..? list all the CINT commands.x [filename] load [filename] and execute function [filename] e.g.: root[1].x plot.c( data.root ).L [filename] load [filename] e.g. root[2].l plot.c.! [shellcmd] execute shell command e.g. root[3].! ls al

CINT command line 2.Expression evaluation (advanced calculator): root[3] 3*4 (int)12 3. C++ Syntax (almost; see below...): root [0] TBrowser *b = new TBrowser() or root [0] TBrowser *b = new TBrowser(); 4. Leave off final semicolon to see the return value of the command. root [0] 23+5 // show return value (int)28 root [1] 23+5; // no return value root [2]

CINT: differences with compiled C++ Declaration can be omitted f = new TFile( data.root"); Member access: "." and "-> both possible (depends on ROOT version) f.ls() or f->ls() Local object is not deleted when leaving scope { TString s( test ); cout << s.data()<<endl; // OK } cout << s.data()<< endl; // only in CINT!

CINT: differences with compiled C++ 1. Unknown variables are automatically initialized by searching the object of that name in groot: TH1F *h = new TH1F ( histo","fpx,100,-5,5); histo->draw(); Implicitely the following is done (as correct for compiled code): TH1F* histo=dynamic_cast<th1f*> (groot->findobject( histo")); histo->draw(); C++ variable name ROOT object name

Using ROOT classes interactively >root root [] TF1 f1( function1","sin(x)/x",0,10); root [] f1.draw(); // pure C++ or root [] function1.draw(); //cint reference by root name root [] f1.eval(1.2456789)... See ROOT class documentation root [] f1.derivative(2.3) for existing methods!.. http://root.cern.ch/root/html/tf1.html root [] f1.integral(0,3)... root [].q

Root GUI: TCanvas

Root GUI: TBrowser

Global ROOT objects (examples) groot (session object singleton, class TROOT) TObject* ob=groot->findobject( hpx ); // get known object by root name TSeqCollection* list= groot->getlistoffiles(); // access to collections of registered objects groot->setbatch(ktrue); // switch to non graphic mode gsystem (operating system interface, class TSystem) gsystem->load( libstt.so ); // load external library (for CINT) gsystem->exec( rm rf *.root ); // call shell command (from compiled code) gdirectory (current root directory, class TDirectory) cout <<gdirectory->getname()<< endl; gpad (currently selected draw pad, class TPad) gpad->clear();

Unnamed scripts Example hsimple.c (from ROOT tutorials): http://root.cern.ch/root/html/examples/hsimple.c.html used ROOT classes: TFile: root file handle object TCanvas: window to draw graphics TH1F, TH2F, TProfile: histogram classes TNtuple: ntuple of values (simple TTree) TRandom (global grandom): random generator TBenchmark (global gbenchmark)

Named scripts Examples (from tutorial directory in ROOT): root >.L fithist.c root > fithist() root > root >.x fithist.c() script must contain one function with same name as scriptfile (for.x) script function may have arguments script may contain also other functions / subroutines script may contain class definitions objects in scope of named scripts are deleted after leaving script, objects in scope of unnamed scripts remain available! root >.L htest.c root > htw() root > htr1() root > htr2() root > htr3() A good example

ROOT files ROOT objects can be saved to files for future analysis or simply for storage. A ROOT file is very similar to a UNIX file directory, with directories and objects organized in a user-decided structure and in a machine independent format (very important!). By opening a ROOT file (in overwrite mode) with the constructor: TFile f( Test.root, recreate ); this file becomes the current directory and all the objects created from now on are saved into the file by invoking the respective Write method (which is a method defined for TObject). For instance for an histogram called h, we will write it to the above Tfile by: h->write(); This method is not very efficient for writing MANY objects.

TFile and TDirectory TDirectory: logical organisation of Tobjects (ownership, subdirectory structure,...) TFile is a TDirectory related to a storage medium (disk, tape, remote server,...) Last created TFile is current file: TH1 and TTrees created afterwards are owned by file and deleted on file close! (default, can be changed by user) TObject::Write() saves to current file A Root object belongs to one TDirectory only, but may be in several collections and TFolder

A sample ROOT file We have an histogram filled with random numbers generated according to a Gaussian distribution and save it into a ROOT file: TFile f( Histos.root, recreate ); char name[10], title[20]; for(int_t k=0; k<15; k++){ sprintf(name, h%d,k); sprintf(title, Histo %d,k); TH1F *h = new TH1F(name, title, 100, -4, 4); h->fillrandom( gaus,1000);} h->write(); f.close(); The file can then be reopened and its contents loaded in memory for display or further use: TFile f( Histos.root ); TH1F *g = (TH1F*)f.Get( h3 ); g->draw();

Useful facts about ROOT files It is possible to graphically browse through a ROOT file using a Tbrowser object: TFile f( Test.root ); TBrowser browser; A ROOT file is always compressed by default using a gzip-like compression algorithm. The default level of compression is 1, a compromise value for speed a compression efficiency. It can be changed by: f.setcompressionlevel(n) n=0: no compression, n=9: best By closing a ROOT file, all the objects in the present directory are saved to the file and removed from the memory. Any reference to them results in an error! f.close(); h->draw(); ERROR!

Saving objects to files A TFile provides persistency, but it is not very efficient in terms of optimizing disk space and access speed. This is particularly true when saving many objects of the same class. Writing millions of objects to a TFile involves writing an object header to the file which is always the same, with a great waste of time and space. ROOT provides a solution to this problem (very common in HEP) with the TTree class (and its simplified version TNtuple class). A TTree provides a structure to organize data, clever enough not to duplicate the object header and optimized for data access. These structures are filled with data and written to a TFile, instead of writing data directly to the TFile. A TTree is a true OO database for storing data and is widely used in the HEP community for saving data.

Trees A Tree is a key concept in ROOT and it also give the name to ROOT, along with Tbranch, Tleaf A Ttree object is a generalization of the ntuple concept and is a structure to hold objects, both ROOT objects and user-defined objects. A Ttree is divided in branches, one branch for each object and when it is filled the branch buffers are filled first and written to the file when the buffer is full. TTrees are also optimized for access to data by using a hierarchy of branches that can be accessed individually. Important: a Ttree is not editable! Once written, no data cannot be updated and it can only be read.

TTrees features Designed to store large number of events (buffering, compression, IO with TFile) Data organized hierarchically into branches Branches may be read back partially (performance!) TTree::Draw(... ) implicit analysis loop by string expression TTree::MakeClass() automatic code generation for explicit analysis loop TChain : public TTree process sequentially trees of same structure in several files TTree::AddFriend access parallel events of a friend tree with different branch structure (for TTree::Draw() expression)

TBranches The TTree basic entry is a Tbranch object, that creates a column (very loosely speaking) in our table. A Tbranch can hold an entire object, a list of variables or even an array of objects. TBranches can be built in three ways: 1) with a list of variables from a C-like structure (see ntuples) tree->branch( Data Branch,&data, x/d:y/d ); 2) with an object (like a TVector3 for example): TVector3 *v = new TVector3(); tree->branch( Data Branch, TVector3, &v,64000,0); 3) with an array of objects (like a TClonesArray of TVector3s): TClonesArray ca; tree->branch( Data Branch, TVector3, &ca,64000,0);

TTrees of objects The TBranch method stores objects constructed according to a given class in a branch: TVector3 *v = new TVector3(); tree->branch( Data Branch, TVector3, &v,64000,1); Parameters to the Branch() method are: - branch name - the class name - the address of a pointer to an object - the buffer size (in bytes) - a flag that indicates the split mode (in split mode=1 the data members (leaves) are saved in separate subbranches, while in split mode=0 the object is saved as an entity and not broken down to elementary types). The tree is then filled (within a loop where v contains data): tree->fill();

The 5 steps to build a TTree There is traditionally a 5 steps recipe to build a tree, fill it with data and store it into a ROOT file: 1) Create the file 2) Create the TTree 3) Add Tbranches to the TTree 4) Fill the TTree 5) Write the TTree to the TFile

Creating a TTree TFile* hfile = new File("AFile.root","RECREATE","Example"); TTree* mytree = new TTree( Mytree, Mytree ); TEvent *event = new TEvent(); // structure to save mytree->branch("eventbranch", TEvent",&event, 32000,1); Branch name Event class name Address of pointer to event object Buffer size Split level Split=0 Split=1 (default)

Filling a TTree for(int_t i=0; i<500000; ++i){ Float_t random = grandom->rndm(1); event->fvalue=random*3; // put values into event structure event->fsum+=random;... mytree->fill(); // will write event into tree basket buffer } mytree->write(); // will write tree buffers and header to file delete myfile; // destructor of TFile will close it TTree::Fill will write data from all active branches (deactivate branch with TTree::SetBranchStatus) Different TTree::Branch() methods for data from simple variables, collections, folders, class objects (see ROOT docs and tutorials)

Reading a TTree explicitely TFile hfile("afile.root"); TTree* tr= dynamic_cast<ttree*>(hfile.get( Mytree )); if(tr==0){ cerr << error: did not find tree! ; return 1; // or may throw exception here... } TObject* h1= new TH1F( hpx, title,2048,0,2047); TEvent* eve= new TEvent; tr->setbranchaddress( EventBranch,&eve); // by branchname! Int_t all=tr->getentries(); // number of events for(int_t i=0; i<all; ++i){ tr->getentry(i); // read event #i into memory h1->fill(eve->fvalue); // do analysis on members of event class here! //... }

Reading a TTree explicitely Event object at SetBranchAddress must match the structure used on writing the tree TTree::GetEntry will read data from active branches only (deactivate branch with SetBranchStatus( branchname, 0)) Use TChain instead of TTree to sum trees of same structure in different files (see ROOT doc). TTree::MakeClass() generates sourcecode for event reading from given TTree (eventclass need not be known!) See example below... Explicit reading of events is not necessary for simple analysis, use TTree::Draw() feature (GUI: treeviewer)!

TTree Draw() examples TTree* tr=.. // got from file tr->draw( fvalue, fvalue>100 && fvalue<500 ); // fill default histogram htemp with fvalue if // condition is true; draw htemp tr->draw( fx:fy >> hpxpy,, lego ); // fill existing 2d histogram of name hpxpy // and display as lego plot tr->draw( fmatrix[][]/fvalue >>+hmatrix, ); // continue filling histogram hmatrix // with sum of all elements of matrix by fvalue tr->draw( >>myeventlist, sqrt(fvalue)>fmatrix[0][2] ); // mark all events in tree that fulfill // the condition into TEventList myeventlist

TTree Draw() TTree::Draw(expression,selection,option) May fill histogram/graph from expression, or will mark matching events in a TEventList Expression may contain any combination of known branch names Expression may specify output histogram name and dimensions, or output eventlist Selection gives condition between branch values of one event; this must be true to execute expression Option may contain draw option for result histogram See ROOT Docs for complete list of features!

TEventList A ROOT TEventList is a list of event numbers. The TEventList is used to constrain the events used in processing such as for histogram creation. This is useful when dealing with large files. root [0] TFile f( data.root") root [1] TTree *t = (TTree*)f->Get( tree") root [2] t->getentries() (const Stat_t)3.44180000000000000e+004 root [3] t->draw(">>elist", x>0 && y<0") (Int_t)13485 root [4] elist->getn() (const Int_t)13485 root [5] t->seteventlist(elist) root [6] t->draw( z") root [7] t->seteventlist(0) root [8] t->draw( z")

TEventList What about more complex TTrees like the hits, digi and reconstruction ROOT TTrees? In this case, we use an event loop to find the events that satisfy our criteria. TFile *f = new TFile( data.root ); TTree *t = (TTree*)f->Get( tree ); Event *evt = new Event(); t->setbranchaddress( Event, &evt); TEventList *elist = new TEventList(); UInt_t numevents = t->getentries(); UInt_t i; for (i = 0; i < numevents; i++) { t->getevent(i); if (evt->value() > 0) { elist->enter(i); } evt->clean();

TTree MakeClass() TFile hfile("afile.root"); TTree* tr= dynamic_cast<ttree*>(hfile.get( Mytree )); if(tr!=0) tr->makeclass( MyAnalysis ); Generates code skeleton for analysis of any Ttree (files MyAnalysis.h, MyAnalysis.C) Tree is analyzed by generated class MyAnalysis: members contain each branch/leaf found in tree constructor initializes tree/chain from file(s) Init(TTree*) sets branch addresses to members Show(int num) dumps entry #num Loop() here user can put own analysis code

TTree MakeClass() root>.l MyAnalysis.C root> MyAnalysis an; // should initialize tree root> an.loop(); // run implicit analysis loop Class MyAnalysis may be used from CINT or can be compiled Quick code generation even for unknown data structures! Substructure of original event class may be lost, all tree branches are mapped flat to MyAnalysis data members See Root users guide for further description...

Automatic Compiler of Libraries for CINT (ACLiC) >root root [].x fithisto.c() execute script in interpreter root [].x fithisto.c+() compile script into library fithist.c.so in background, then execute function (note: only recompile if fithist.c have changed since last compile) root [].x fithisto.c++() compile library in any case before execution root [].L fithisto.c+ compile script and load library, but do not execute root [] fithisto() will execute loaded function root [].L fithisto.c++g // compile and execute function with debug (-g) root [].x fithisto.c++o // compile and execute function with optimization (-O) ACLiC needs external tools to compile the shared library.

Executables and ROOT scripts Very simple way to transform a ROOT script into a real compiled executable program by using the TROOT class. #include <iostream> #include "TApplication.h" #include "TFile.h" #include "TH1.h" { using namespace std; int main(int argc, char **argv) { } TApplication myapp("app", &argc, argv); TFile *f=new TFile("pdebug.root","recreate"); TH1F *h=new TH1F("h","h",100,-5,5); h->fillrandom("gaus",10000); h->draw(); h->write(); The original script: groot->reset(); TH1F *h=new TH1F("h","h",100,-5,5); h->fillrandom("gaus",10000); h->draw(); Working with a real programs makes // f->close(); easier to debug it and allows to create myapp.run(); CINT independent programs, that } return 0; only use ROOT as an external library.

Debugging ROOT A debug session of a ROOT program with TVector3 objects: a is on the stack, *b on the heap! Having a ROOT executable program, it is much more easy to debug it by using standard debuggers, like gdb or ddd. CINT has its own debug, but it is very basic and lacks a graphical interface.

C++ differences CINT interpreted ACLiC Compiled code ROOT class declarations ROOT classes require to ROOT classes require to are known implicitely include declarations, too include declarations, too NOTE: include all non- e.g. #include TH1.h e.g. #include TH1.h ROOT classes! ROOT class definitions Automatic linking against ROOT classes require to are known implicitely ROOT libs and the link against respective generated library libraries when building executable Makefile No function declaration needed Declare function before use Declare function before use CINT C++ Compiler C++ Compiler C++

Extending ROOT Creation of a ROOT dictionary allow to access the ROOT advanced I/O functions by adding extra member functions to user classes (streamers) and to add RTTI data to users programs. RTTI means Run Time Type Information and it is a system to find out which class an object belongs, its baseclasses, its datamembers and methods, the methods signatures and other informations needed to make advanced object browsers and to use the automatic documentation generation. To add user classes to ROOT it is necessary to add two calls to functions that links the classes to the dictionary: - ClassDef(ClassName, ClassVersionID); - ClassImp(ClassName); and to prepare a LinkDef.h file and a Makefile.

Adding own classes to ROOT Motivation: User subclasses of TObject may benefit from ROOT I/O, collections, runtime introspection,... Interpreter: just load class definition (see MakeClass example), but no I/O for new class possible! Compiled into user library: add ClassImp / ClassDef statements in class sources prepare LinkDef.h file provide dictionary generation in Makefile

Adding own classes to ROOT MyEvent.h class MyEvent : public TObject{ public: MyEvent(); fvalue; fmatrix[100][100]; // lots of data members here... ClassDef(MyEvent,1) }; Macros, create code for Streamer, type information, etc. ClassImp(MyEvent) MyEvent::MyEvent(){} // may contain other method definitions... MyEvent.cxx

Adding own classes to ROOT LinkDef.h #ifdef CINT #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link C++ class MyEvent; #endif Class name may have Options: #pragma link C++ class MyEvent-; do not generate automatic streamer (for objects with customized streamers) #pragma link C++ class MyEvent!; do not generate the operator >> (for classes not inheriting from TObject) #pragma link C++ class MyEvent+; enable new ROOT I/O (from Root >v.3)

Adding own classes to ROOT In the Makefile (for generation and linking of ROOT dictionary): libmyevent.so: MyEvent.o MyEventDict.o g++ -shared Wl soname libmyevent.so O MyEvent.o MyEventDict.o o libmyevent.so #... #... MyEventDict.cxx MyEvent.h LinkDef.h $(ROOTSYS)/bin/rootcint -f MyEventDict.cxx -c MyEvent.h LinkDef.h

Exercise 1 Write simple class, call it MyClass and store it in MyClass.h and MyClass.cxx Generate dictionary: rootcint f MyDict.cxx c MyClass.h Compile MyClass.cxx and mydict.cxx into a shared library: g++ -shared fpic `root-config - cflags` -o libmyclass.so MyClass.cxx MyDict.cxx

Exercise 1 (cont.) Start ROOT, load libmyclass.so: $ root root [0] gsystem->load( libmyclass ) Create and play with MyClass object: root [1] MyClass a root [2] a.print() root [3]

Linking Class to ROOT RTTI To link a class to the ROOT RTTI system two macros need to be added to MyClass: ClassDef(class name, version id) // MyClass.h class MyClass { public:... ClassDef(MyClass,1) // analyse my data }; ClassImp(class name) // MyClass.cxx #include MyClass.h ClassImp(MyClass)

ClassDef and ClassImp These macros provide: Several static methods to obtain reflection/meta class information static TClass *Class(); static const char *Class_Name(); virtual TClass *IsA() const; Inspection and Streamer (I/O) methods virtual void ShowMembers(TMemberInspector &insp, char *parent); static Version_t Class_Version() { return id; } virtual void Streamer(TBuffer &b); friend TBuffer &operator>>(tbuffer &buf, name *&obj); Methods returning header and source file name Small class and static object to register class to ROOT when library is loaded

Exercise 2 Add ClassDef() and ClassImp() macros to MyClass And also add: #include <Rtypes.h> to MyClass.h Repeat same steps as in exercise 1: rootcint f MyDict.cxx c MyClass.h g++ -shared fpic `root-config - cflags` -o libmyclass.so MyClass.cxx MyDict.cxx $ root root [0] gsystem->load( libmyclass ) root [1] MyClass a root [2] a.print() root [3] a.p<tab> works now

Full Integration into ROOT To make your class a fully ROOT supported class, with full I/O capabilities, just add derivation from TObject to MyClass // MyClass.h class MyClass : public TObject { public:... ClassDef(MyClass,1) // analyse my data };

Exercise 3 Add public derivation from TObject to your class Replace the Rtypes.h include by TObject.h Repeat same two build steps as in the previous exercises Create object of MyClass and Dump() its run time contents: root [1] MyClass a root [2] a.dump() Root [3]

Exercise 3 (cont.) Open a file and write the object: root [1] MyClass a root [2] TFile f( test.root, recreate ) root [3] a.write( a1 ) root [4] f.close() Open a file and read the object: root [1] TFile f( test.root ) root [2] MyClass *a = (MyClass*) f.get( a1 ) root [3] f.close() root [4] a->dump()

Summary ROOT is a powerful tool for the modern HEP physicist both for analysis and for simulations. ROOT offers collections, folders, directories and files for organization of TObjects TTree is powerful class for keeping and analyzing event data (Draw(), TEventList(), MakeClass(),..) User can ROOTify own classes with a simple recipe (ClassImp, ClassDef, LinkDef.h, Makefile) Two things to remember when doing Physics with ROOT or any other OO system: - Quantum Mechanics is more difficult and you know it already! - Hamming s Rule: The purpose of computing is insight, not numbers.

Where to go from here?

Documentation and Forum