Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Root
Description: Its all about the explanation of root.

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


A ROOT Guide For Beginners

“Diving Into ROOT”

2

Contents
1 Motivation and Introduction

5

2 ROOT Basics

7

2
...


7

2
...


8

2
...


9

2
...
11

2
...
11

2
...
13

2
...
15

2
...
15
2
...
1

ROOT type declarations for basic data types
...
8
...
17

2
...
3

ROOT command history

2
...
4

ROOT Global Pointers


...
17

3 ROOT Macros

19

3
...
19

3
...
20

3
...
22
3
...
1
3
...
2

Arrows and Lines
...
3
...
4

Colours and Graph Markers
...
24

Interpretation and Compilation
...
4
...
24

3
...
2

Compile a Macro with the Compiler
...
1

Read Graph Points from File
...
2

Polar Graphs
...
3

2D Graphs

4
...
33


...
1

Your First Histogram


...
2

Add and Divide Histograms
...
3

Two-dimensional Histograms
...
4

Multiple histograms
...
1

Fitting Functions to Pseudo Data
...
2

Toy Monte Carlo Experiments
...
1

Storing ROOT Objects
...
2

N-tuples in ROOT
...
2
...
52

7
...
2

Reading N-tuples
...
2
...
54

7
...
4

Processing N-tuples Spanning over Several Files

7
...
5

For the advanced user: Processing trees with a selector script
...
2
...
59

7
...
7

Optimisation Regarding N-tuples
...
1

61

PyROOT
...
1
...
2


...
63

Custom code: from C++ to Python
...
Among its prominent features are an advanced graphical user interface, ideal
for interactive analysis, an interpreter for the C++ programming language, for rapid and efficient prototyping and a
persistency mechanism for C++ objects, used also to write every year petabytes of data recorded by the Large Hadron
Collider experiments
...


Chapter 1

Motivation and Introduction
Welcome to data analysis!
Comparison of measurements to theoretical models is one of the standard tasks in experimental physics
...
Very often, the model depends on parameters
...

As a first step, a visualisation of the data is needed
...
g
...
Quite often, these manipulations are complex ones, and a powerful library of mathematical
functions and procedures should be provided - think for example of an integral or peak-search or a Fourier transformation
applied to an input spectrum to obtain the actual measurement described by the model
...
In subsequent analysis, the statistical nature of the errors must be handled properly
...

See Figure 1
...
Several standard methods are available, and a data
analysis tool should provide easy access to more than one of them
...

Quite often, the data volume to be analyzed is large - think of fine-granular measurements accumulated with the aid of
computers
...

In Quantum mechanics, models typically only predict the probability density function (“pdf”) of measurements depending
on a number of parameters, and the aim of the experimental analysis is to extract the parameters from the observed
distribution of frequencies at which certain values of the measurement are observed
...

Simulation of expected data is another important aspect in data analysis
...
In many
cases, the distribution of the measurement errors is not precisely known, and simulation offers the possibility to test the
effects of different assumptions
...

ROOT is very flexible and provides both a programming interface to use in own applications and a graphical user interface
for interactive data analysis
...
This guide will hopefully lay the
ground for more complex applications in your future scientific work building on a modern, state-of the art tool for data
analysis
...
This goal will be accomplished
using concrete examples, according to the “learning by doing” principle
...
Nevertheless, once you feel confident with the concepts presented in the
following chapters, you will be able to appreciate the ROOT Users Guide (The ROOT Users Guide 2015) and navigate
5

6

CHAPTER 1
...
You can
even look at the code itself, since ROOT is a free, open-source product
...
Jus take advantage from the immense available literature about C++ if you do not have
any idea of what this language is about
...
), but in this guide we will implicitly assume that
you are using Linux
...
Just seek the “Pro” version on this webpage http://root
...
ch/downloading-root
...
Just pick up the
flavour you need and follow the installation instructions
...
It has an interpreter for macros (Cling (“What Is Cling” 2015)) that you can run from the command line or run like
applications
...
This is extremely
useful for debugging, quick hacking and testing
...


2
...
The prompt should appear shortly:
root [0]
and let’s dive in with the steps shown here:
root [0] 1+1
(int)2
root [1] 2*(4+2)/12
...
000000e+00
root [2] sqrt(3
...
732051e+00
root [3] 1 > 2
(bool) false
root [4] TMath::Pi()
(Double_t) 3
...
2)
(Double_t) 2
...
You can see that ROOT offers you the possibility not only to type in C++ statements, but also advanced
mathematical functions, which live in the TMath namespace
...
A numerical example with the well known geometrical series:
root [6]
(double)
root [7]
(int) 30
root [8]

double x=
...
000000e-01
int N=30
double geom_series=0
7

8

CHAPTER 2
...
000000e+00
root [9] for (int i=0;iroot [10] TMath::Abs(geom_series - (1-TMath::Power(x,N-1))/(1-x))
(Double_t) 1
...
We even declared variables and used a for control structure
...
You do not need the “;” at the end of line in interactive
mode – try the difference e
...
using the command at line root [6]
...
2

Learn C++ at the ROOT prompt

Behind the ROOT prompt there is an interpreter based on a real compiler toolkit: LLVM
...
For example in the following snippet we define a lambda function,
a vector and we sort it in different ways:
root
root
root
root
0
3
5
4
1
2
root
root
0
1
2
3
4
5
root
root
5
4
3
2
1
0

[0]
[1]
[2]
[3]

using doubles = std::vector;
auto pVec = [](const doubles& v){for (auto&& x:v) cout << x << endl;};
doubles v{0,3,5,4,1,2};
pVec(v);

[4] std::sort(v
...
end());
[5] pVec(v);

[6] std::sort(v
...
end(),[](double a, double b){return a>b;});
[7] pVec(v);

Or, if you prefer random number generation:
root [0] std::default_random_engine generator;
root [1] std::normal_distribution distribution(0
...
);
root [2] distribution(generator)
(std::normal_distribution::result_type) -1
...
086818e+00
root [4] distribution(generator)
(std::normal_distribution::result_type) 6
...
3
...
3

9

ROOT as function plotter

Using one of ROOT’s powerful classes, here TF1,1 will allow us to display a function of one variable, x
...
,10
...
Draw();
f1 is an instance of a TF1 class, the arguments are used in the constructor; the first one of type string is a name to be
entered in the internal ROOT memory management system, the second string type parameter defines the function, here
sin(x)/x, and the two parameters of type double define the range of the variable x
...

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
...
Here is an example:
root
root
root
root

[13]
[14]
[15]
[16]

TF1 f2("f2","[0]*sin([1]*x)/x",0
...
);
f2
...
SetParameter(1,1);
f2
...
Try playing with the parameters and plot the function again
...
To make full use of this
and other ROOT classes, visit the documentation on the Internet under http://root
...
ch/drupal/content/reference-guide
...

You should definitely download this guide to your own system to have it at you disposal whenever you need it
...
You can also do
this using standard C or C++ code
...
Please do not type in the example below at the ROOT command line, there is a much simpler way: Make sure you
have the file slits
...
C in the shell
...
C, i
...
all the lines in the file will be executed one after the other
...


4
5

auto pi = TMath::Pi();

6
7
8
9
10

// function code in C
double single(double *x, double *par) {
return pow(sin(pi*par[0]*x[0])/(pi*par[0]*x[0]),2);
}

11
12
13
14

double nslit0(double *x,double *par){
return pow(sin(pi*par[1]*x[0])/sin(pi*x[0]),2);
}

15
16
17
18

double nslit(double *x, double *par){
return single(x,par) * nslit0(x,par);
}

19
20
21

// This is the main program
void slits() {
1 All

ROOT classes’ names start with the letter T
...
In this context all classes’ names are of the form Roo*
...
ROOT BASICS
float r,ns;

22
23

// request user input
cout << "slit width / g ? ";
scanf("%f",&r);
cout << "# of slits? ";
scanf("%f",&ns);
cout <<"interference pattern for "<< ns
<<" slits, width/distance: "<
24
25
26
27
28
29
30
31

// define function and set options
TF1 *Fnslit = new TF1("Fnslit",nslit,-5
...
,2);
Fnslit->SetNpx(500);

32
33
34
35

// set parameters, as read in above
Fnslit->SetParameter(0,r);
Fnslit->SetParameter(1,ns);

36
37
38
39
40
41
42

}

// draw the interference pattern for a grid with n slits
Fnslit->Draw();

Figure 2
...
C with parameters 0
...

The example first asks for user input, namely the ratio of slit width over slit distance, and the number of slits
...
1
...
4
...
Let us go through it in detail:
Lines 7-18 define the necessary functions in C++ code, split into three separate functions, as suggested by the problem
considered
...
More important for us here is the definition of the
interface of these functions to make them usable for the ROOT class TF1: the first argument is the pointer to x, the second
one points to the array of parameters
...
After asking for user input, a
ROOT function is defined using the C-type function given in the beginning
...

Here, we used a macro, some sort of lightweight program, that the interpreter distributed with ROOT, Cling, is able to
execute
...


2
...
This character is the dot at the beginning of a line:
root [1]
...

• quit root, simply type
...
?
• access the shell of the operating system, type
...
g
...
!pwd
• execute a macro, enter
...
x slits
...
L ; in the above example, you might instead have used the command
...
C
followed by the function call slits();
...

• compile a macro, type
...
One could decide to compile a macro in order to obtain
better performance or to get nearer to the production environment
...
help at the prompt to inspect the full list
...
5

Plotting Measurements

To display measurements in ROOT, including errors, there exists a powerful class TGraphErrors with different types of
constructors
...
txt in text format:
root [0] TGraphErrors gr("ExampleData
...
Draw("AP");

12

CHAPTER 2
...
2: Visualisation of data points with errors using the class TGraphErrors
...
6
...
2
...
txt is available in the directory from which you started ROOT
...
txt to inspect the file, you will see that the format is very
simple and easy to understand
...
It is very convenient to add some comments about the
type of data
...

The argument of the method Draw("AP") is important here
...
Note that this simple example relies on
the default settings of ROOT, concerning the size of the canvas holding the plot, the marker type and the line colours
and thickness used and so on
...
A full chapter on graphs will explain many more of the features of the class
TGraphErrors and its relation to other ROOT classes in much more detail
...
6

Histograms in ROOT

Frequency distributions in ROOT are handled by a set of classes derived from the histogram class TH1, in our case TH1F
...

root
root
root
root
root
root

[0]
[1]
[2]
[3]
[4]
[5]

TF1 efunc("efunc","exp([0]+[1]*x)",0
...
);
efunc
...
SetParameter(1,-1);
TH1F h("h","example histogram",100,0
...
);
for (int i=0;i<1000;i++) {h
...
GetRandom());}
h
...
In line 3 a
histogram is instantiated, with a name, a title, a certain number of bins (100 of them, equidistant, equally sized) in the
range from 0 to 5
...

Data is entered in the histogram at line 4 using the method TH1F::Fill in a loop construct
...
The histogram is displayed using the
method TH1F::Draw()
...
The
plot is shown in Figure 2
...

Note that you will not obtain an identical plot when executing the lines above, depending on how the random number
generator is initialised
...
The following lines of C++ code do the job
...
dat” is read in via an input stream and filled in the histogram until end
of file is reached
...
,5
...
open("expo
...
Fill(x); }
h
...
close();

Histograms and random numbers are very important tools in statistical data analysis, a whole chapter will be dedicated to
this topic
...
ROOT BASICS

Figure 2
...


2
...
INTERACTIVE ROOT

2
...
You will notice that this is much more than a static picture,
as the mouse pointer changes its shape when touching objects on the plot
...
g
...
Depending on
which plot you are investigating, menus for the ROOT classes TF1, TGraphErrors or TH1F will show up when a right-click
is performed on the respective graphical representations
...
g
...
Try it!

Figure 2
...

You will probably like the following: in the output produced by the example slits
...
This gives access to a panel allowing you to interactively
change the parameters of the function, as shown in Figure 2
...
Change the slit width, or go from one to two and then
three or more slits, just as you like
...

Another very useful interactive tool is the FitPanel, available for the classes TGraphErrors and TH1F
...
In addition, user-defined functions using the same
syntax as for functions with parameters are possible
...
The fit panel is shown in Figure 2
...
The fit panel has a number of control options to
select the fit method, fix or release individual parameters in the fit, to steer the level of output printed on the console, or
to extract and display additional information like contour lines showing parameter correlations
...

If you are satisfied with your plot, you probably want to save it
...
from the menu line of the window
...
There is one very noticeable feature here: you can
store a plot as a root macro! In this macro, you find the C++ representation of all methods and classes involved in
generating the plot
...

Using ROOT’s interactive capabilities is useful for a first exploration of possibilities
...
We will not comment further on this, just be aware of the existence of
ROOT’s interactive features and use them if you find them convenient
...


2
...
We will try to clarify some of them
with further explanations in the following
...
ROOT BASICS

Figure 2
...


2
...
ROOT BEGINNERS’ FAQ

2
...
1

17

ROOT type declarations for basic data types

In the official ROOT documentation, you find special data types replacing the normal ones, e
...
Double_t, Float_t or
Int_t replacing the standard double, float or int types
...
If you want adaptive code of this type, use the ROOT type declarations
...
If you intend to become a ROOT developer, however, you better stick to the official coding rules!

2
...
2

Configure ROOT at start-up

The behaviour of a ROOT session can be tailored with the options in the
...
Examples of the tunable parameters
are the ones related to the operating and window system, to the fonts to be used, to the location of start-up files
...
rootrc file in the following order:

...
rootrc //user directory
• $ROOTSYS/etc/system
...
rootrc files are found in the search paths above, the options are merged, with precedence local, user,
global
...
Have a look to its documentation if
you need such rather advanced features
...
rootrc defines the location of two rather important files inspected at
start-up: rootalias
...
C
...

rootalias
...
rootlogon
...

This is done most easily by creating a new TStyle object with your preferred settings, as described in the class reference
guide, and then use the command gROOT->SetStyle("MyStyleName"); to make this new style definition the default one
...
C coming with this tutorial
...
C that
it called when the session is finished
...
8
...
root_hist in your home directory
...
It is also convenient to extract
successful ROOT commands with the help of a text editor for use in your own macros
...
8
...
Some of them were already implicitly introduced (for example in the
section Configure ROOT at start-up)
...
Technically it is an instance of the TROOT class
...
The TROOT
object is essentially a container of several lists pointing to the main ROOT objects
...
This class includes
functions to set some of the following object attributes
...
ROOT BASICS





Markers
Functions
Histogram Statistics and Titles
etc
...

• gInterpreter: The entry point for the ROOT interpreter
...

At this point you have already learnt quite a bit about some basic features of ROOT
...
In this guide, we will describe macros executed by the ROOT C++ interpreter
Cling
...


3
...
The general structure for a macro
stored in file MacroName
...

your lines of C++ code

...
C
at the system prompt, or executed using
...
x MacroName
...
or it can be loaded into a ROOT session and then be executed by typing
root [0]
...
C
root [1] MacroName();
at the ROOT prompt
...
A small set of options can help making your plot nicer
...
ROOT MACROS

gStyle->SetOptFit(1111);
gStyle->SetPalette(57);
gStyle->SetOptTitle(0);

...
Divide(2,2); //set subdivisions, called pads
c1
...

Below, in section Interpretation and Compilation, some more code fragments will be shown, allowing you to use the system
compiler to compile macros for more efficient execution, or turn macros into stand-alone applications linked against the
ROOT libraries
...
2

A more complete example

Let us now look at a rather complete example of a typical task in data analysis, a macro that constructs a graph with
errors, fits a (linear) model to it and saves it as an image
...
C
The code is built around the ROOT class TGraphErrors, which was already introduced previously
...
The macro shown below uses additional classes, TF1 to
define a function, TCanvas to define size and properties of the window used for our plot, and TLegend to add a nice legend
...

1
2
3

// Builds a graph with errors, displays it and saves it as
// image
...
h"
"TROOT
...
h"
"TF1
...
h"
"TArrow
...
h"

12
13
14
15
16
17
18
19
20
21

void macro1(){
// The values and the errors on the Y axis
const int n_points=10;
double x_vals[n_points]=
{1,2,3,4,5,6,7,8,9,10};
double y_vals[n_points]=
{6,12,14,20,22,24,35,45,44,53};
double y_errs[n_points]=
{5,5,4
...
5,4
...
1,2
...
1,4
...
43};

22
23

// Instance of the graph

3
...
A MORE COMPLETE EXAMPLE

21

TGraphErrors graph(n_points,x_vals,y_vals,nullptr,y_errs);
graph
...
Units");

24
25
26

// Make the plot estetically better
graph
...
SetMarkerColor(kBlue);
graph
...
DrawClone("APE");

35
36
37

// Define a linear function
TF1 f("Linear law","[0]+x*[1]",
...
5);
// Let's make the funcion line nicer
f
...
SetLineStyle(2);
// Fit it to the graph and draw it
graph
...
DrawClone("Same");

38
39
40
41
42
43
44
45

// Build and Draw a legend
TLegend leg(
...
7,
...
9,"Lab
...
SetFillColor(0);
graph
...
AddEntry(&graph,"Exp
...
AddEntry(&f,"Th
...
DrawClone("Same");

46
47
48
49
50
51
52
53

// Draw an arrow on the canvas
TArrow arrow(8,8,6
...
02,"|>");
arrow
...
DrawClone();

54
55
56
57
58

// Add some text to the plot
TLatex text(8
...
5,"#splitline{Maximum}{Deviation}");
text
...
pdf");

65
66
67
68

int main(){
macro1();
}
Let’s comment it in detail:
• Line 13 : the name of the principal function (it plays the role of the “main” function in compiled programs) in the
macro file
...

• Line 24-25 : instance of the TGraphErrors class
...
The second
line defines in one shot the title of the graph and the titles of the two axes, separated by a “;”
...

• Line 33 : the canvas object that will host the drawn objects
...


22

CHAPTER 3
...
It has to be a clone, to survive after the
scope of macro1, and be displayed on screen after the end of the macro execution
...

– P imposes the drawing of the graph’s markers
...

• Line 39 : define a mathematical function
...

• Line 41 : maquillage
...

• Line 43 : fits the f function to the graph, observe that the pointer is passed
...

• Line 44 : again draws the clone of the object on the canvas
...
The function f will be drawn using the same axis system defined by the
previously drawn graph
...
The constructor takes as parameters
the lower left and upper right corners coordinates with respect to the total size of the canvas, assumed to be 1,
and the legend header string
...
Observe how the legend is drawn at the end: looks familiar now, right ?
• Line 55-57 : defines an arrow with a triangle on the right hand side, a thickness of 2 and draws it
...
The
#splitline{}{} construct allows to store multiple lines in the same TLatex object
...
The format is automatically inferred from the file extension (it could have been
eps, gif,
...
1
...
3
3
...
1

Summary of Visual effects
Colours and Graph Markers

We have seen that to specify a colour, some identifiers like kWhite, kRed or kBlue can be specified for markers, lines,
arrows etc
...
To know more about the full
story, refer to the online documentation of TColor
...
Select the most suited symbols for your plot among dots, triangles, crosses
or stars
...


3
...
2

Arrows and Lines

The macro line 55 shows how to define an arrow and draw it
...
The constructors of lines and arrows always contain the coordinates of the endpoints
...
Do not underestimate the role of lines and arrows in your plots
...


3
...
SUMMARY OF VISUAL EFFECTS

23

Figure 3
...
A well formatted plot, clear for the reader is crucial to communicate the relevance of
your results to the reader
...
3
...
ROOT MACROS

Text

Also text plays a fundamental role in making the plots self-explanatory
...
The objects of this class are constructed with the coordinates of the bottom-left corner of the text
and a string which contains the text itself
...

If “\” is used as control character , then the TMathText interface is invoked
...


3
...
This is sufficient for a wide range of applications, but you might have already asked yourself “how can
this code be compiled ?”
...


3
...
1

Compile a Macro with ACLiC

ACLiC will create for you a compiled dynamic library for your macro, without any effort from your side, except the
insertion of the appropriate header files in lines 5–11
...
To generate an object
library from the macro code, from inside the interpreter type (please note the “+”):
root [1]
...
C+
Once this operation is accomplished, the macro symbols will be available in memory and you will be able to execute it
simply by calling from inside the interpreter:
root [2] macro1()

3
...
2

Compile a Macro with the Compiler

A plethora of excellent compilers are available, both free and commercial
...

In this case, you have to include the appropriate headers in the code and then exploit the root-config tool for the automatic
settings of all the compiler flags
...
In order to make the code executable stand-alone, an entry point
for the operating system is needed, in C++ this is the procedure int main();
...
This defines the
procedure main, the only purpose of which is to call your macro:
int main() {
ExampleMacro();
return 0;
}
To create a stand-alone program from a macro called ExampleMacro
...
C `root-config --cflags --libs`
and execute it by typing
>
...
4
...
If you want your stand-alone application have display graphics
output and respond to mouse and keyboard, a slightly more complex piece of code can be used
...
As a additional feature, this code example offers
access to parameters eventually passed to the program when started from the command line
...
Argc(), app
...
Run();
return 0;
}
Compile the code with
> g++ -o ExampleMacro_GUI ExampleMacro_GUI `root-config --cflags --libs`
and execute the program with
>
...
ROOT MACROS

Chapter 4

Graphs
In this Chapter we will learn how to exploit some of the functionalities ROOT provides to display data exploiting the class
TGraphErrors, which you already got to know previously
...
1

Read Graph Points from File

The fastest way in which you can fill a graph with experimental data is to use the constructor which reads data points and
their errors from an ASCII file (i
...
standard text) format:
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
This approach has the nice feature of allowing the user to reuse the macro for many different data sets
...
The nice graphic result shown is produced by the macro below, which reads two such input files and uses
different options to display the data points
...
7
4
...
2
5
...
9
4
...
8
5
...
GRAPHS

// Reads the points from a file and produces a simple graph
...
/macro2_input_expected
...
SetTitle(
"Measurement XYZ and Expectation;"
"lenght [cm];"
"Arb
...
SetFillColor(kYellow);
graph_expected
...
/macro2_input
...
SetMarkerStyle(kCircle);
graph
...
DrawClone("PESame");
// Draw the Legend
TLegend leg(
...
7,
...
9,"Lab
...
SetFillColor(0);
leg
...
AddEntry(&graph,"Measured Points");
leg
...
Print();
return 0;

4
...
POLAR GRAPHS

29

In addition to the inspection of the plot, you can check the actual contents of the graph with the TGraph::Print() method
at any time, obtaining a printout of the coordinates of data points on screen
...


4
...
You can see the example macro in the following and the resulting Figure is 4
...


2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

void macro3(){
auto c = new TCanvas("myCanvas","myCanvas",600,600);
Double_t rmin=0
...
;
const Int_t npoints=1000;
Double_t r[npoints];
Double_t theta[npoints];
for (Int_t ipt = 0; ipt < npoints; ipt++) {
r[ipt] = ipt*(rmax-rmin)/npoints+rmin;
theta[ipt] = TMath::Sin(r[ipt]);
}
TGraphPolar grP1 (npoints,r,theta);
grP1
...
SetLineWidth(3);
grP1
...
DrawClone("L");
}
A new element was added on line 4, the size of the canvas: it is sometimes optically better to show plots in specific canvas
sizes
...
3

2D Graphs

Under specific circumstances, it might be useful to plot some quantities versus two variables, therefore creating a bidimensional graph
...
The following macro
produces a bi-dimensional graph representing a hypothetical measurement, fits a bi-dimensional function to it and draws it
together with its x and y projections
...
This time, the graph is populated
with data points using random numbers, introducing a new and very important ingredient, the ROOT TRandom3 random
number generator using the Mersenne Twister algorithm (Matsumoto 1997)
...
3;
const int nd = 500;

6
7
8
9
10
11
12
13

TRandom3 my_random_generator;
TF2 f2("f2",
"1000*(([0]*sin(x)/x)*([1]*sin(y)/y))+200",
-6,6,-6,6);
f2
...
GRAPHS

Figure 4
...


4
...
2D GRAPHS
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

}

31

double rnd, x, y, z, ex, ey, ez;
for (Int_t i=0; if2
...
Uniform(-e,e);
z = f2
...
SetPoint(i,x,y,z);
ex = 0
...
Uniform();
ey = 0
...
Uniform();
ez = fabs(z*rnd);
dte
...
SetParameters(0
...
5); // set initial values for fit
f2
...
Fit(&f2);
// Plot the result
auto c1 = new TCanvas();
f2
...
SetLineColor(kBlue-5);
TF2
*f2c = (TF2*)f2
...
5);
Yaxis->SetTitle("Y Title"); Yaxis->SetTitleOffset(1
...
5);
dte
...
Project("x")->Draw();
c_p->cd(2);
dte
...
Comment this line to give it a try
...

• Line 7 : The instance of the random generator
...
See the on-line documentation
to appreciate the full power of this ROOT feature
...
This is its two-dimensional version
...

• Line 27-29 : Fitting a 2-dimensional function just works like in the one-dimensional case, i
...
initialisation of parameters
and calling of the Fit() method
...
See Figure 4
...

• Line 35-40 : Retrieve the axis pointer and define the axis titles
...


32

CHAPTER 4
...
It is very handy to
show multiple plots in the same window or image
...
2: A dataset fitted with a bidimensional function visualised as a colored surface
...
4
...
4

33

Multiple graphs

The class TMultigraph allows to manipulate a set of graphs as a single entity
...
When drawn, the X and Y axis ranges are automatically computed such as all the graphs will be visible
...

void multigraph(){
TCanvas *c1 = new TCanvas("c1","multigraph",700,500);
c1->SetGrid();

5

TMultiGraph *mg = new TMultiGraph();

6
7

// create first graph
const Int_t n1 = 10;
Double_t px1[] = {-0
...
05, 0
...
35, 0
...
61,0
...
85,0
...
95};
Double_t py1[] = {-1,2
...
6,7
...
6,8
...
3,4
...
05,
...
07,
...
04,
...
06,
...
08,
...
8,
...
6,
...
4,
...
5,
...
7,
...
28, 0
...
19, 0
...
45, 0
...
65,0
...
90,1
...
1,3
...
55,9
...
26,5
...
04,
...
08,
...
05,
...
07,
...
08,
...
6,
...
7,
...
3,
...
4,
...
6,
...

• Line 9-28 : create two graphs with errors and add them in the multigraph
...
The axis limits are computed automatically to make sure all the graphs’ points
will be in range
...
cern
...
GRAPHS

Figure 4
...


Chapter 5

Histograms
Histograms play a fundamental role in any type of physics analysis, not only to visualise measurements but being a powerful
form of data reduction
...
We will
focus in this chapter on uni- and bi- dimensional histograms the bin contents of which are represented by floating point
numbers,1 the TH1F and TH2F classes respectively
...
1

Your First Histogram

Let’s suppose you want to measure the counts of a Geiger detector located in proximity of a radioactive source in a given
time interval
...
The count distribution in this case is a Poisson
distribution
...

1
2

// Create, Fill and draw an Histogram which reproduces the
// counts of a scaler linked to a Geiger counter
...
5, // Lower X Boundary
15
...
6f;
TRandom3 rndgen;
// simulate the measurements
for (int imeas=0;imeas<400;imeas++)
cnt_r_h->Fill(rndgen
...


35

36

CHAPTER 5
...
1):

Figure 5
...
Only bins corresponding to integer values are filled given the
discrete nature of the poissonian distribution
...
The main differences with respect to graphs that emerge from the example are:
• line 5 : The histograms have a name and a title right from the start, no predefined number of entries but a number of
bins and a lower-upper range
...

• line 18 and 21 : The histogram can be drawn also normalised, ROOT automatically takes cares of the necessary
rescaling
...


5
...
The most useful are addition and division
...

1

// Divide and add 1D Histograms

2
3
4
5

void format_h(TH1F* h, int linecolor){
h->SetLineWidth(3);
h->SetLineColor(linecolor);

5
...
ADD AND DIVIDE HISTOGRAMS
}

6
7
8

void macro6(){

9

auto
auto
auto
auto

10
11
12
13

sig_h=new TH1F("sig_h","Signal Histo",50,0,10);
gaus_h1=new TH1F("gaus_h1","Gauss Histo 1",30,0,10);
gaus_h2=new TH1F("gaus_h2","Gauss Histo 2",30,0,10);
bkg_h=new TH1F("exp_h","Exponential Histo",50,0,10);

14

// simulate the measurements
TRandom3 rndgen;
for (int imeas=0;imeas<4000;imeas++){
bkg_h->Fill(rndgen
...
Gaus(5,2));
if (imeas%4==0) gaus_h2->Fill(rndgen
...
Gaus(5,
...
);
sum_h->SetTitle("Exponential + Gaussian;X variable;Y variable");
format_h(sum_h,kBlue);

28
29
30
31
32
33

auto c_sum= new TCanvas();
sum_h->Draw("hist");
bkg_h->Draw("SameHist");
sig_h->Draw("SameHist");

34
35
36
37
38

// Divide
auto dividend=new TH1F(*gaus_h1);
dividend->Divide(gaus_h2);

39
40
41
42

// Graphical Maquillage
dividend->SetTitle(";X axis;Gaus Histo 1 / Gaus Histo 2");
format_h(dividend,kOrange);
gaus_h1->SetTitle(";;Gaus Histo 1 and Gaus Histo 2");
gStyle->SetOptStat(0);

43
44
45
46
47
48

TCanvas* c_divide= new TCanvas();
c_divide->Divide(1,2,0,0);
c_divide->cd(1);
c_divide->GetPad(1)->SetRightMargin(
...
49);
c_divide->GetPad(2)->SetGridy();
c_divide->GetPad(2)->SetRightMargin(
...
2 and 5
...

Some lines now need a bit of clarification:

37

38

CHAPTER 5
...
2: The sum of two histograms
...
3: The ratio of two histograms
...
3
...
In this case the function simply
sets up some parameters to conveniently set the line of histograms
...

• line 30 : The sum of two histograms
...

• line 41 : The division of two histograms is rather straightforward
...
These lines provide a skeleton to perform this operation
...
3

Two-dimensional Histograms

Two-dimensional histograms are a very useful tool, for example to inspect correlations between variables
...
Let’s see how in this macro:
// Draw a Bidimensional Histogram in many ways
// together with its profiles and projections
void macro7(){
gStyle->SetPalette(kBird);
gStyle->SetOptStat(0);
gStyle->SetOptTitle(0);
TH2F bidi_h("bidi_h","2D Histo;Gaussian Vals;Exp
...
Fill(rgen
...
Exp(4),
...
DrawClone("Cont1");
c->cd(2);bidi_h
...
DrawClone("lego2");
c->cd(4);bidi_h
...
ProjectionX()->DrawClone();
c2->cd(2);bidi_h
...
ProfileX()->DrawClone();
c2->cd(4);bidi_h
...
4)
and the second one projections and profiles (Figure 5
...

When a projection is performed along the x (y) direction, for every bin along the x (y) axis, all bin contents along the y (x)
axis are summed up (upper the plots of Figure 5
...
When a profile is performed along the x (y) direction, for every bin
along the x (y) axis, the average of all the bin contents along the y (x) is calculated together with their RMS and displayed
as a symbol with error bar (lower two plots of Figure 5
...

Correlations between the variables are quantified by the methods Double_t GetCovariance() and Double_t
GetCorrelationFactor()
...
HISTOGRAMS

Figure 5
...


5
...
TWO-DIMENSIONAL HISTOGRAMS

Figure 5
...


41

42

CHAPTER 5
...
4

Multiple histograms

The class THStack allows to manipulate a set of histograms as a single entity
...

When drawn, the X and Y axis ranges are automatically computed such as all the histograms will be visible
...
The next macros shows how it looks for 2D histograms:
1

// Example of stacked histograms using the class THStack

2
3
4

void hstack(){
THStack *a = new THStack("a","Stacked 2D histograms");

5

TF2 *f1 = new TF2("f1","xygaus + xygaus(5) + xylandau(10)",-4,4,-4,4);
Double_t params1[] = {130,-1
...
8,1
...
5,-2,0
...
7,-3,0
...
4,1
...
1,2, 80,2,0
...
5};
f2->SetParameters(params2);
TH2F *h2stb = new TH2F("h2stb","h2stb",20,-4,4,20,-4,4);
h2stb->SetFillColor(46);
h2stb->FillRandom("f2",3000);

13
14
15
16
17
18
19

a->Add(h2sta);
a->Add(h2stb);

20
21
22
23
24

}

a->Draw();

• Line 4 : creates the stack
...

• Lines 20-21 : add the histograms in the stack
...
The colour distinguish the two histograms 5
...


5
...
MULTIPLE HISTOGRAMS

Figure 5
...


43

44

CHAPTER 5
...
In this chapter we will add
more detail to the previous approximate explanations to face the fundamental topic of parameter estimation by fitting
functions to data
...
The class TFitResult allows access to the detailed results
...
This is most easily achieved by applying
the analysis to many sets of simulated data (or “pseudo data”), each representing one possible version of the true experiment
...
1 Since the true
values of all parameters are known in the pseudo-data, the differences between the parameter estimates from the analysis
procedure w
...
t
...


6
...

ROOT offers various minimisation algorithms to minimise a chi2 or a negative log-likelihood function
...
A C++ version is also available,
MINUIT2, as well as Fumili (Silin 1983) an algorithm optimised for fitting
...
Steering options for the minimiser, such as the
convergence tolerance or the maximum number of function calls, can also be set using the methods of this class
...


1 “Monte Carlo” simulation means that random numbers play a role here which is as crucial as in games of pure chance in the Casino of
Monte Carlo
...
FUNCTIONS AND PARAMETER ESTIMATION

The complication level of the code below is intentionally a little higher than in the previous examples
...
1:
1
2
3

void format_line(TAttLine* line,int col,int sty){
line->SetLineWidth(5); line->SetLineColor(col);
line->SetLineStyle(sty);}

4
5
6
7

double the_gausppar(double* vars, double* pars){
return pars[0]*TMath::Gaus(vars[0],pars[1],pars[2])+
pars[3]+pars[4]*vars[0]+pars[5]*vars[0]*vars[0];}

8
9
10
11
12

int macro8(){
gStyle->SetOptTitle(0); gStyle->SetOptStat(0);
gStyle->SetOptFit(1111); gStyle->SetStatBorderSize(0);
gStyle->SetStatX(
...
89);

13
14
15

TF1 parabola("parabola","[0]+[1]*x+[2]*x**2",0,20);
format_line(¶bola,kBlue,2);

16
17
18

TF1 gaussian("gaussian","[0]*TMath::Gaus(x,[1],[2])",0,20);
format_line(&gaussian,kRed,2);

19
20
21
22
23
24
25

TF1 gausppar("gausppar",the_gausppar,-0,20,6);
double a=15; double b=-1
...
03;
double norm=4; double mean=7; double sigma=1;
gausppar
...
SetParNames("Norm","Mean","Sigma","a","b","c");
format_line(&gausppar,kBlue,1);

26
27
28

TH1F histo("histo","Signal plus background;X vals;Y Vals",50,0,20);
histo
...
Fill(gausppar
...
SetParameter(0,50);
gausppar
...
GetNpar();
for (int ipar=2;ipar ...

auto fitResPtr = histo
...
and retrieve fit results
fitResPtr->Print(); // print fit results
// get covariance Matrix an print it
TMatrixDSym covMatrix (fitResPtr->GetCovarianceMatrix());
covMatrix
...
SetParameter(ipar,gausppar
...
SetParameter(ipar,gausppar
...
GetYaxis()->SetRangeUser(0,250);
histo
...
DrawClone("Same"); gaussian
...
2
...
DrawClone("Same");
return 0;

57
58
59
60

47

}

Some step by step explanation is at this point necessary:
• Lines 1-3 : A simple function to ease the make-up of lines
...

• Lines 5-7 : Definition of a customised function, namely a Gaussian (the “signal”) plus a parabolic function, the
“background”
...
In particular we want that the parameters of the fit appear very clearly
and nicely on the plot
...

• Lines 27-31 : Define and fill a histogram
...
This part of the code is very important for each fit procedure, as it sets the
initial values of the fit
...

• Lines 42-46 : Retrieve the output from the fit
...

• Lines 54-end: Plot the pseudo-data, the fitted function and the signal and background components at the best-fit
values
...
2

Toy Monte Carlo Experiments

Let us look at a simple example of a toy experiment comparing two methods to fit a function to a histogram, the χ2
method and a method called “binned log-likelihood fit”, both available in ROOT
...
If everything is OK, the distribution of the pull values is a standard normal distribution, i
...
a
σp
Gaussian distribution centred around zero with a standard deviation of one
...
Each time, a fit is performed according to the selected method,
and the pull is calculated and filled into a histogram
...

// Check pull distribution to compare chi2 and binned
// log-likelihood methods
...
FUNCTIONS AND PARAMETER ESTIMATION

Figure 6
...
This plot is another example of how making a plot
“self-explanatory” can help you better displaying your results
...
2
...
SetMarkerStyle(21);
h4
...
8);
h4
...
5,1
...
,4
...
Reset();
// Fill histo
for ( int j = 0; jh4
...
Fit("gaus","q"); // Chi2 fit
else h4
...
Draw("ep");
c0->Update();}

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

}

// Get sigma from fit
TF1 *fit = h4
...
Fill(sig);
pull
...
DrawClone();

67
68
69
70
71
72
73

void macro9(){
int n_toys=10000;
int n_tot_entries=100;
int n_bins=40;
cout << "Performing Pull Experiment with chi2 \n";
pull(n_toys,n_tot_entries,n_bins,true);

49

50
74
75
76

}

CHAPTER 6
...
Note that the
variable pull in line 61 is different from the definition above: instead of the parameter error on mean, the fitted standard
deviation of the distribution divided by the square root of the number of entries, sig/sqrt(n_tot_entries), is used
...
Basically all books about statistical methods
provide a complete treatment of the aforementioned topics
...
1

Storing ROOT Objects

ROOT offers the possibility to write instances of classes on disk, into a ROOT-file (see the TFile class for more details)
...
When reading the file back, the object is reconstructed
in memory
...
This topic is beyond the scope of this document: it is worth to mention that
I/O can be performed out of the box for the almost complete set of ROOT classes
...

void write_to_file(){
// Instance of our histogram
TH1F h("my_histogram","My Title;X;# of entries",100,-5,5);
// Let's fill it randomly
h
...
root","RECREATE");
// Write the histogram in the file
h
...
Close();

Not bad, eh ? Especially for a language that does not foresees persistency natively like C++
...

Now, you may use the Cling command line to access information in the file and draw the previously written histogram:
> root my_rootfile
...
root as _file0
...
root
TFile*
my_rootfile
...
FILE I/O AND PARALLEL ANALYSIS

Alternatively, you can use a simple macro to carry out the job:
void read_from_file(){
// Let's open the TFile
TFile in_file("my_rootfile
...
GetObject("my_histogram",h);
// Draw it
h->Draw();

}

7
...
2
...
ROOT offers the possibility to do much better
than that, with its own n-tuple classes
...

• Possibility to store many n-tuple rows
...

• Interactive inspection with TBrowser
...

In this section we will discuss briefly the TNtuple class, which is a simplified version of the TTree class
...
Let’s tackle the problem according to the usual strategy commenting a minimal
example
// Fill an n-tuple and write it to a file simulating measurement of
// conductivity of a material in different conditions of pressure
// and temperature
...
root","RECREATE");
// Initialise the TNtuple
TNtuple cond_data("cond_data",
"Example N-Tuple",
"Potential:Current:Temperature:Pressure");
// Fill it randomly to fake the acquired data
TRandom3 rndm;
float pot,cur,temp,pres;
for (int i=0;i<10000;++i){
pot=rndm
...
,10
...
Uniform(250
...
); // get temperature
pres=rndm
...
5,1
...
+0
...
)-0
...
)); // current
// add some random smearing (measurement errors)

53

7
...
N-TUPLES IN ROOT
pot*=rndm
...
,0
...
Gaus(0
...
3); // 0
...

pres*=rndm
...
,0
...
Gaus(1
...
01); // 1% error
// write to ntuple
cond_data
...

on pressure
on current

// Save the ntuple and close the file
cond_data
...
Close();

This data written to this example n-tuple represents, in the statistical sense, three independent variables (Potential or
Voltage, Pressure and Temperature), and one variable (Current) which depends on the others according to very simple
laws, and an additional Gaussian smearing
...

Imagine your task now consists in finding the relations among the variables – of course without knowing the code used to
generate them
...
Open the
ROOT file (cond_data
...
Simply clicking on them you can obtain histograms of the variables!
Next, try the following commands at the shell prompt and in the interactive ROOT shell, respectively:
> root conductivity_experiment
...
root as _file0
...


7
...
2

Reading N-tuples

For completeness, you find here a small macro to read the data back from a ROOT n-tuple
// Read the previously produced N-Tuple and print on screen
// its content
void read_ntuple_from_file(){
// Open a file, save the ntuple and close the file

54

CHAPTER 7
...
root");
TNtuple* my_tuple;in_file
...
By doing so, the logic for
reading the n-tuple and the code to process it can be split and the source code remains clear
...
2
...
This is especially important as
TNtuple::Fill() accepts only floats
...
The Fill() function then fills the current values of the connected variables to the tree
...

void write_ntuple_to_file_advanced(
const std::string& outputFileName="conductivity_experiment
...
c_str(),"RECREATE");
// Initialise the TNtuple
TTree cond_data("cond_data", "Example N-Tuple");
// define the variables and book them for the ntuple
float pot,cur,temp,pres;
cond_data
...
Branch("Current", &cur, "Current/F");
cond_data
...
Branch("Pressure", &pres, "Pressure/F");
for (int i=0;i// Fill it randomly to fake the acquired data
pot=gRandom->Uniform(0
...
)*gRandom->Gaus(1
...
01);
temp=gRandom->Uniform(250
...
)+gRandom->Gaus(0
...
3);
pres=gRandom->Uniform(0
...
5)*gRandom->Gaus(1
...
02);
cur=pot/(10
...
05*(temp-300
...
2*(pres-1
...
,0
...
Fill();}

55

7
...
N-TUPLES IN ROOT

}

// Save the ntuple and close the file
cond_data
...
Close();

The Branch() function requires a pointer to a variable and a definition of the variable type
...
Please note that ROOT is not checking the input and mistakes are likely to result in serious
problems
...
g
...

List of variable types that can be used to define the type of a branch in ROOT:
type

size

C++

identifier

signed integer

32 bit

int

I

64 bit

long

L

32 bit

unsigned int

i

64 bit

unsigned long

l

32 bit

float

F

64 bit

double

D

-

bool

O

unsigned integer
floating point
boolean

7
...
4

Processing N-tuples Spanning over Several Files

Usually n-tuples or trees span over many files and it would be difficult to add them manually
...
Its usage is shown in the following macro which is very similar to the previous
example
...
The files are added with
the function Add(fileName), where one can also use wild-cards as shown in the example
...

you can easily create some files with the following statement:
for i in 0 1 2 3 4 5; \\
do root -l -x -b -q \\
"write_ntuple_to_file
...
root\", 100)"; \\
done

void read_ntuple_with_chain(){
// initiate a TChain with the name of the TTree to be processed
TChain in_chain("cond_data");
in_chain
...
root"); // add files,
// wildcards work
// define variables and assign them to the corresponding branches
float pot, cur, temp, pres;
in_chain
...
SetBranchAddress("Current", &cur);
in_chain
...
SetBranchAddress("Pressure", &pres);
cout << "Potential\tCurrent\tTemperature\tPressure\n";
for (size_t irow=0; irow ...
FILE I/O AND PARALLEL ANALYSIS

}

7
...
5

in_chain
...
This
method takes as arguments an instance of a – user-implemented– class of type TSelector, and – optionally – the
number of entries and the first entry to be processed
...
C below
...
root from the example above and creates from it the header file
MySelector
...
C
...
2
...
root");
// create TTree object from it
TTree *t; f
...
h and MySelector
...

Typically, initialization like booking of histograms is performed in SlaveBegin(), the analysis, i
...
the selection of entries,
calculations and filling of histograms, is done in Process(), and final operations like plotting and storing of results happen
in SlaveTerminate() or Terminate()
...

A simple example of a selector class is shown in the macro MySelector
...
The example is executed with the following
sequence of commands:
> TChain *ch=new TChain("cond_data", "Chain for Example N-Tuple");
> ch->Add("conductivity_experiment*
...
C+");
As usual, the “+” appended to the name of the macro to be executed initiates the compilation of the MySelector
...

The code in MySelector
...
1 The final processing in Terminate() allows to access histograms and store,
display or save them as pictures
...
See the commented listing below
for more details; most of the text is actually comments generated automatically by TTree::MakeSelector
...
h has been generated automatically
// by the ROOT utility TTree::MakeSelector()
...
For more information on the TSelector
// framework see $ROOTSYS/README/README
...

// The following methods are defined in this file:
//
Begin():
called every time a loop on the tree starts,
//
a convenient place to create your histograms
...

//
Process():
called for each event, in this function you decide what
//
to read and fill your histograms
...

//
Terminate():
called at the end of the loop on the tree,
//
a convenient place to draw/fit your histograms
...
C")
1 The usage of fOutput is not really needed for this simple example, but it allows re-usage of the exact code in parallel processing with PROOF
(see next section)
...
FILE I/O AND PARALLEL ANALYSIS

// root> T->Process("MySelector
...
C+")
//
#include "MySelector
...
h>
#include ...

// When running with PROOF Begin() is only called on the client
...

TString option = GetOption();
}
void MySelector::SlaveBegin(TTree * /*tree*/ )
{
// The SlaveBegin() function is called after the Begin() function
...

// The tree argument is deprecated (on PROOF 0 is passed)
...
The entry argument
// specifies which entry in the currently loaded tree is to be processed
...
When processing
// keyed objects with PROOF, the object is already loaded and is available
// via the fObject pointer
...
It can contain
// simple or elaborate selection criteria, run algorithms on the data
// of the event and typically fill histograms
...

//
// Use fStatus to set the return value of TTree::Process()
...

}

return kTRUE;

void MySelector::SlaveTerminate()
{
// The SlaveTerminate() function is called after all entries or objects
// have been processed
...

}

7
...
N-TUPLES IN ROOT

59

void MySelector::Terminate()
{
// The Terminate() function is the last function to be called during
// a query
...

}

7
...
6

For power-users: Multi-core processing with PROOF lite

The processing of n-tuples via a selector function of type TSelector through TChain::Process(), as described at the end
of the previous section, offers an additional advantage in particular for very large data sets: on distributed systems or
multi-core architectures, portions of data can be processed in parallel, thus significantly reducing the execution time
...

On distributed systems, a PROOF server and worker nodes have to be set up, as described in detail in the ROOT
documentation
...
Try the following little macro,
RunMySelector
...
root");
// eventually, start Proof Lite on cores
TProof::Open("workers=4");
ch->SetProof();
ch->Process("MySelector
...
Now, when issuing the
command ch->Process("MySelector
...
C is compiled and executed on each slave node
...
The list of n-tuple files is analysed, and portions
of the data are assigned to the available slave processes
...
Upon termination, the PROOF master collects the histograms from the slaves
and merges them
...
The
histograms are handled via the instances fOutput of class TList in each slave process, and can be retrieved from this list
after merging in Terminate
...
You could also
generate a large number of files and use wildcards to add the to the TChain
...
C
and watch what happens:
Processing RunMySelector
...

+++ Starting PROOF-Lite with 4 workers +++
Opening connections to workers: OK (4 workers)
Setting up worker servers: OK (4 workers)
PROOF set to parallel mode (4 workers)
Info in : starting query: 1
Info in : nwrks: 4
Info in : creating shared library
~/DivingROOT/macros/MySelector_C
...
FILE I/O AND PARALLEL ANALYSIS

Info in :
Setting max number of workers per node to 4
Validating files: OK (4 files)
Info in :
fraction of remote files 1
...
png has been created
*==* ----- End of Job ----- Date/Time = Wed Feb 15 23:00:08 2012
Lite-0: all output objects have been merged
Log files of the whole processing chain are kept in the directory ~
...
This is very helpful for
debugging or if something goes wrong
...

It is worth to remind the reader that the speed of typical data analysis programs limited by the I/O speed (for example
the latencies implied by reading data from a hard drive)
...


7
...
7

Optimisation Regarding N-tuples

ROOT automatically applies compression algorithms on n-tuples to reduce the memory consumption
...
Nevertheless,
you should think about the design of your n-tuples and your analyses as soon as the processing time exceeds some minutes
...
If your measurement has only a limited precision,
it is needless to store it with double precision
...

Although the compression can handle redundant values, the processing time increase with every variable that has to
be filled
...
The default
value is 30MB
...
Please note that the caching mechanism can cover
only one TTree object per TFile object
...
This mechanism can result in a significant speed-up for simple operations on trees
with many branches
...
The ROOT documentation on this class also includes
an introductory example
...
e
...


Chapter 8

ROOT in Python
ROOT offers the possibility to interface to Python via a set of bindings called PyROOT
...
With the help of PyROOT it becomes possible to
combine the power of a scripting language with ROOT tools
...
g
...
python
...


8
...
Coming back to our
first example, simply plotting a function in ROOT, the following C++ code:
TF1 *f1 = new TF1("f2","[0]*sin([1]*x)/x",0
...
);
f1->SetParameter(0,1);
f1->SetParameter(1,1);
f1->Draw();
in Python becomes:
import ROOT
f1 = ROOT
...
,10
...
SetParameter(0,1);
f1
...
Draw();
A slightly more advanced example hands over data defined in the macro to the ROOT class TGraphErrors
...
The first line in the Python script allows it to be
executed directly from the operating system, without the need to start the script from python or the highly recommended
powerful interactive shell ipython
...

Here is the C++ version:
void TGraphFit(){
//
// Draw a graph with error bars and fit a function to it
//
gStyle->SetOptFit(111) ; //superimpose fit results
// make nice Canvas
TCanvas *c1 = new TCanvas("c1" ,"Daten" ,200 ,10 ,700 ,500) ;
c1->SetGrid( ) ;
61

62

}

CHAPTER 8
...

const Int_t n = 10;
Float_t x[n] = {-0
...
1, 0
...
35, 0
...
61, 0
...
85, 0
...
1};
Float_t y[n] = {0
...
9, 5
...
4, 9
...
6, 8
...
3, 4
...
1};
Float_t ey[n] = {
...
7 ,
...
5 ,
...
4 ,
...
6 ,
...
8};
Float_t ex[n] = {
...
1 ,
...
07 ,
...
05 ,
...
07 ,
...
05};
// and hand over to TGraphErros object
TGraphErrors *gr = new TGraphErrors(n,x,y,ex,ey);
gr->SetTitle("TGraphErrors with Fit") ;
gr->Draw("AP");
// now perform a fit (with errors in x and y!)
gr->Fit("gaus");
c1->Update();

In Python it looks like this:
#
# Draw a graph with error bars and fit a function to it
#
from ROOT import gStyle, TCanvas, TGraphErrors
from array import array
gStyle
...
SetGrid ()
#define some data points
...
22, 0
...
25, 0
...
5, 0
...
7, 0
...
89, 1
...
7, 2
...
6, 7
...
, 9
...
7, 6
...
5, 1
...
8 ,
...
6 ,
...
4 ,
...
5 ,
...
7 ,
...
05 ,
...
07 ,
...
04 ,
...
06 ,
...
08 ,
...
and hand over to TGraphErros object
gr=TGraphErrors ( nPoints , x , y , ex , ey )
gr
...
Draw ( "AP" ) ;
gr
...
Update ()
# request user action before ending (and deleting graphics window)
raw_input('Press to end -> ')
Comparing the C++ and Python versions in these two examples, it now should be clear how easy it is to convert any
ROOT Macro in C++ to a Python version
...
A straight-forward Python version relying on the ROOT class
TMath:
# Builds a polar graph in a square Canvas
...

rmax = TMath
...

npoints = 300
r = array('d',[0]*npoints)
theta = array('d',[0]*npoints)
for ipt in xrange(0,npoints):
r[ipt] = ipt*(rmax-rmin)/npoints+rmin

8
...
CUSTOM CODE: FROM C++ TO PYTHON

63

theta[ipt] = TMath
...
SetTitle("A Fan")
grP1
...
SetLineColor(2)
grP1
...
")

8
...
1

More Python- less C++

You may have noticed already that there are some Python modules providing functionality similar to ROOT classes, which
fit more seamlessly into your Python code
...
With the math package, the part of the code becomes
import math
from array import array
from ROOT import TCanvas , TGraphPolar

...
)+rmin,ipt))
theta=array('d',map(math
...
])

...
1
...
1

Customised Binning

This example combines comfortable handling of arrays in Python to define variable bin sizes of a ROOT histogram
...
TH1F("hist", "hist", len(arrBins)-1, arrBins)
# fill it with equally spaced numbers
for i in range (1 ,16) :
histo
...
Draw ()

8
...
Take for
example this header file, containing a class and a function
...
h
#include "stdio
...
ROOT IN PYTHON

A(int i):m_i(i){}
int getI() const {return m_i;}
private:
int m_i=0;
};
void printA(const A& a ){
printf ("The value of A instance is %i
...
getI());
}
>>>
>>>
>>>
>>>
The

import ROOT
ROOT
...
ProcessLine('#include "cpp2pythonExample
...
A(123)
ROOT
...


This example might seem trivial, but it shows a powerful ROOT feature
...
There is still a lot coming to mind to be said, but by now
you are experienced enough to use the ROOT documentation, most importantly the ROOT home page and the ROOT
reference guide with the documentation of all ROOT classes, or the ROOT users guide
...

There are some powerful features of ROOT which were not treated in this document, e
...
packages named RooFit and
RooStats providing an advanced framework for model building, fitting and statistical analysis
...
The remarkable ability of ROOT to handle large data volumes was already mentioned in this guide, implemented
through the class TTree
...
but hopefully not of your interaction with ROOT !

65

66

CHAPTER 9
...
1997
...
” http://www
...
sci
...
ac
...

html
...
N
...
“FUMILI
...

The ROOT Reference Guide
...
http://root
...
ch/drupal/content/reference-guide
...
2015
...
cern
...

“What Is Cling
...
https://root
...
ch/drupal/content/cling
Title: Root
Description: Its all about the explanation of root.