# Presentation: 659135

## ROOT

- An object oriented HEP analysis framework.
- Day 2
- http://www-pat.fnal.gov/root/
- The ROOT system website is at: http://root.cern.ch/

- ROOT Day 2,  Suzanne Panacek

## Day 2

- Last time
- GUI, Command line
- Today
- Command Line (CINT)
- Scripts (CINT & ACLiC)
- Exercises
- Functions and Fitting
- TreeViewer

- ROOT Day 2,  Suzanne Panacek

## Command line

- Environment Settings
- Command types
- CINT Commands
- Global Variables
- TObject

- ROOT Day 2,  Suzanne Panacek

## Environment Settings

- Environment setting file:
- $ROOTSYS/etc/system.rootrc
- looks first in current directory for .rootrc
- second in $HOME/.rootrc
- third in $ROOTSYS/etc/system.rootrc
- Find the current settings
- root[] gEnv->Print()

- ROOT Day 2,  Suzanne Panacek

**Notes:**
The file with the environment setting. 
ROOT looks for the environment setting in the .rootrc file. It first checks if there is one locally ./.rootrc then in the users home directory: $HOME/.rootrc, and finally in the ROOT directory: $ROOTSYS/system.rootrc.

## Environment Settings (cont.)

- The .rootrc file:
- The Macro Path
- Unix.*.Root.MacroPath:.:$(HOME)/myRootMacros
- Options in .rootrc
- Root.ShowPath: false
- History File
- $HOME/.root_hist
- Automatically Executing Macros
- rootlogon.C
- rootlogoff.C
- rootalias.C

- ROOT Day 2,  Suzanne Panacek

**Notes:**
The Dynamic Path is the path used by the loader to find shared libraries. 
The Macro Path is the path used by the loader to look for root scripts when the .X or .L commands are used. 
Root.ShowPath:  trueShows on the command line the path of the object that is used.
Four files can be specified:
Rint.Load: 	rootalias.C  
Rint.Logon:  	rootlogon.C
Rint.Logoff:	rootlogoff.C
Rint.History:	$(HOME)/.root_hist
For example we would like to automatically execute the macro Browser.C. It loads libEvent.so, starts a browser, opens a file, and draws one histogram 
{
gROOT->ProcessLine(".L libEvent.so");
TBrowser * b = new TBrowser();
TFile *  f = new TFile("Event.root");
T->Draw("fTracks.fPx");
}
Make this your logon macro by editing the .rootrc file:
Rint.Logon:             Browser.C

## Command Line Options

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

- ROOT Day 2,  Suzanne Panacek

## Three Types of Commands

- CINT commands start with “.”
- root[0].?
- this command will list all the CINT commands
- root[1].X [filename]
- load [filename] and execute function [filename]
- root[2].L [filename]
- load [filename]
- SHELL commands start with “.!” for example:    root[3] .! ls

- ROOT Day 2,  Suzanne Panacek

## Three Types of Commands

- 3. C++ syntax (almost)
-   	root [0] TBrowser *b = new TBrowser()or
- 	root [0] TBrowser *b = new TBrowser();
- 	The optional Semicolon:
- 	Leave off the 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]**

- ROOT Day 2,  Suzanne Panacek

## Command Line Help

- Use the Tab feature to get help ...
- root [0] b = new TB <TAB>
- root [1] b = new TBrow<TAB>
- root [2] b = new TBrowser(<TAB>
- Find List of Methods
- Find Parameter list

- ROOT Day 2,  Suzanne Panacek

## Coding Conventions

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

- ROOT Day 2,  Suzanne Panacek

## CINT Types

- ROOT Day 2,  Suzanne Panacek

## CINT Extensions to C++

- 1. Declaration can be omitted
-  f = new TFile("Example.root")
- 2. "." notation rather than "->"   f.ls()
- 3. Search  for an object by its name
-  TH1F *smallHisto = new TH1F
- 	           ("**small**","fPx 100",100,-5,5);
- 	**small**->Draw();
**	****	****Warning: These will not work in compiled code!**

- ROOT Day 2,  Suzanne Panacek

**Notes:**
1. The declaration can be omitted when ‘new’ is used:
f = new TFile("Event.root")
2. Can use the simple "." notation rather than "->"
f.ls()
3. In case CINT can not find an object being referenced it will ask ROOT to search for an object with an identical name in the search path defined by TROOT.FindObject(). In addition to a FindObject, CINT will cast it to the class and allocate the variable with the same name:

WARNING: These extensions will not compile with a regular C++ compiler.

## CINT Commands

- [expression] 	evaluates the expression
- root[3] 3*4
- (int)12
- .files  		show loaded source files
- .class [name] 	show class definition
- .g 			prints all objects in the root session
- .ls 			ls on current directory
- .pwd		list the current directory, canvas, 				and style.

- ROOT Day 2,  Suzanne Panacek

**Notes:**
[expression]Almost any  expression can be given. You can inputdeclaration, loops, etc... Exceptions are function definitions,class definition with member function definitions, etc...
.files will show all loaded files including .h files.
.class  .class <ClassName> prints all methods and members of the class.  .class without any arguments will print a list of all classes in order that they were created.
.gwill show a list of objects in the order that they were created.
.ls
shows the contents of the current directory
.pwd
shows the current directory, current style, and current canvas (if there is one)

## Demo on CINT Commands

- .class
- root [0] .L $ROOTSYS/test/libEvent.so
- root [1] .class Event
- .g
- root [2] .g...
- 0x104c7560 Event e , size=56
-   0x0        private: Int_t fNtrack
-   0x0        private: Int_t fNseg
-   0x0        private: Int_t fNvertex
-   ...

- ROOT Day 2,  Suzanne Panacek

## CINT Multi-line Command

- Start with "{" For example:

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

- ROOT Day 2,  Suzanne Panacek

## Global Variables

- gRandom
- gRandom->Gaus(1,2)
- You can replace the random generator with your own:delete gRandom;gRandom = new **TRandom2**(0); //seed=0
- gFile
- gFile->GetName()
- gDirectory
- gDirectory->GetName()
- gSystem
- gSystem->HostName()

- ROOT Day 2,  Suzanne Panacek

**Notes:**
gRandom: is a basic Random number generator (periodicity 10**8). Setting the seed to 0 implies that the seed will be generated from the time. Any other value will be used as a constant.
The following basic Random distributions  are provided:    Gaus(mean,sigma)    Rndm()   Landau(mean,sigma)   Poisson(mean)   Binomial(ntot,prob)
You can customize your root session by replacing the random number generator. You can delete gRandom and recreate it with your own constructor of your own class.
gFile: is a pointer to the current file. 
gDirectory: is a pointer to the current directory. 
gSystem: contains operating system information for the current root session.

## gROOT

- global ROOT session object
- gROOT->GetListOf< list type >();
- gROOT->LoadMacro();
- gROOT->Time();
- gROOT->ProcessLine()

- ROOT Day 2,  Suzanne Panacek

**Notes:**

gROOT is a pointer to the global ROOT session object. Its class is TROOT. Using the gROOT pointer one has access to basically every object created in a ROOT based program. The TROOT object is essentially a container of several lists pointing to the main ROOT objects. 

gROOT->GetListOf< list type >() returns a pointer to a TSeqCollection of the specified list. The available lists to get are: Browsables, Browsers, Canvases, Classes, Colors, Files, Functions, and Geometries. 
gROOT->LoadMacro() loads a macro in the interpreter's memory. Equivalent to the command line command ".L filename".
gROOT->Time(1) Print the real and CPU time it takes for each command. Once turned on, even if in a macro, it needs to be turned off with the command gROOT->Time(0)
gROOT->ProcessLine() processes a single command line, either a C++ statement or an interpreter command starting with a ".". This can be used to execute a CINT statement in a macro. For example:

	gROOT->ProcessLine(".! ls")

Will execute the ls shell command and list the contents of the current directory.

## gROOT->FindObject()

- 	TH1F ***smallHisto **= new TH1F
- 		("**small**","fPx 100",100,-5,5);
- "small" is the _Object Name_
-   gROOT->FindObject("**small**")
- 		(class TObject*)**0x104c7528**
- "smallHisto" is the _Variable Name_
- 	gROOT->FindObject("**smallHisto**")
- 		(class TObject*)**0x0** **// null pointer**
- FindObject needs the _Object Name_.

- ROOT Day 2,  Suzanne Panacek

**Notes:**
gROOT->FindObject(<name>) attempts to find the object with the <name>. This is the name given in the constructor of the object. For example an object created with this constructor:
TH1F *smallH= new TH1F("small","fPx 100",100,-5,5);
will be found by gROOT->FindObject("small"). The object will not be found if the variable name is used. In this example gROOT->FindObject("smallH") will return a null pointer.  The search path for FindObject is
-  List of files-  List of memory mapped files-  List of functions-  List of geometries-  List of canvases -  List of styles -  List of specials - List of materials in current geometry-  List of shapes in current geometry-  List of matrices in current geometry-  List of Nodes in current geometry-  Current Directory in memory-  Current Directory on file 

## gROOT->FindObject() ++

- FindObject returns a pointer to TObject.
- This generates an error:
- gROOT->FindObject("small")->GetBinContent(2)
- This is OK:
- gROOT->FindObject("small")->ClassName()
- TH1F* histo=(TH1F*) gROOT->FindObject("small")
- histo->GetBinContent(2)

- ROOT Day 2,  Suzanne Panacek

**Notes:**
gROOT->FindObject(<name>) returns a pointer to TObject. You will need to cast it first to be useful.
For example: this creates an error.
 gROOT->FindObject("small")->GetBinContent(2)
You must first cast the TObject pointer to a TH1 * to be able to call TH1 methods:
((TH1*) gROOT->FindObject("small"))->GetBinContent(2)
or
TH1F* histo=(TH1F*) gROOT->FindObject("small");histo->GetBinContent(2)
If there are two objects with the same name, you should check the class name of the returned TObject pointer.
root [2] gROOT->FindObject("small")->ClassName()
(Text_t* 0x1052d03c)"TH1F"

## gROOT->FindObject() cont.

- Due to CINT magic this is also OK:
- 	TH1F *smallHisto = new TH1F
- 			("**small**","fPx 100",100,-5,5);
- 	**small**->GetBinContent(2);
- CINT implicitly executes a FindObject("small")
- Casts it to the correct class
- Creates a variable called "small" of the correct class
- 		**Warning: This will not work in compiled code!**

- ROOT Day 2,  Suzanne Panacek

**Notes:**
CINT automatically executes a FindObject is the Object name is used:
small->GetBinContent(2);
This also creates a variable of type TH1F. It is an extension of CINT that will not work in regular C++ code.

## Demonstration: FindObject

- FindObject():
- root [3] f = TFile("Example.root")
- root [4] .ls
- root [5] gROOT->FindObject("myTree")
- root [6] myTree

- ROOT Day 2,  Suzanne Panacek

## TObject: The Mother of all Root objects

- Defines protocol and default behavior for all objects in ROOT.
- I/O
- Drawing/Painting
- TObjects can be stored in collection classes.
- Introspection, Reflection, Runt Time Type Identification

- ROOT Day 2,  Suzanne Panacek

**Notes:**
The TObject class provides the default behavior and protocol for all objects in the ROOT system. It provides a standard protocol for object I/O, error handling, sorting, inspection, printing, and drawing. Every object which inherits from TObject can be stored in the ROOT collection classes. 
I/O examples: 
Write(): Writes this object to the current directory gDirectory.
Inspection: 
Inspect(): draws a canvas with the current state of the object. It displays the value of each member.
Printing
Print():  Prints the name of the class, the name of the variable and the title of the variable. It must be overridden to print the what is relative to the subclass. For example TEnv overrides Print() to print the .rootrc file.
Inheritance Tree:
DrawClass(): draws a canvas with the inheritance tree for the class.
Drawing:
The Draw() method does nothing by default. It has to be overwritten by the subclass to have any action.

## TObject RTTI

- RTTI = the ability of a class to reflect upon itself or to "look inside itself" at run time.
- TClass implement RTTI
- To get the TClass from a TObject descendent:    obj->Class()
- TClass can find the:
- Methods
- Data members
- Base classes

- ROOT Day 2,  Suzanne Panacek

## Summary (Command Line)

- Environment Settings
- Command types
- CINT Commands
- Global Variables
- TObject

- ROOT Day 2,  Suzanne Panacek

## Writing Scripts

- Named and Un-named Scripts
- Debugging
- ACLiC

- ROOT Day 2,  Suzanne Panacek

## Scripts

- _Un-named Script_
- Start with "{" and end with "}"
- All variables are in the global scope
- No class definitions
- No function declarations
- No parameters
- _Named Script_
- C++ functions
- Scope rules follow standard C++
- Function with the same name as the file is executed with a .x
- 	Parameters
- 	Class definitions (derived from a compiled class at your own risk)

- ROOT Day 2,  Suzanne Panacek

## Scripts Examples

- _Un-named Script: hello.C_
- {
-   cout << "Hello" << endl;
- }
- _Named Script:say.C_
- void say(char * what = "Hello")
- {
-   cout << what << endl;
- }
- _Executing the Named Script_
- root [3] .x say.C
- Hello
- root [4] .x say.C("Hi there")
- Hi there

- ROOT Day 2,  Suzanne Panacek

## Resetting the Environment

- gROOT->Reset()
- Calls destructors of all objects created on the stack
- Objects on Heap are not deleted, but pointer variable is disassociated

- ROOT Day 2,  Suzanne Panacek

**Notes:**

gROOT->Reset() 
When running an un-named script over again and this is frequently the case since un-named scripts are used to prototype, one should reset the global environment to clear the variables. This is done by calling gROOT->Reset(). It is good practice, and you will see this in the examples, to begin an un-named script with gROOT->Reset. It clears the global scope to the state just before executing the previous script (not including any logon scripts). 
The gROOT->Reset() calls the destructor of the objects if the object was created on the stack. If the object was created on the heap (via new) it is not deleted, but the variable is no longer associated with it. Creating variables on the heap in un-named scripts and calling gROOT->Reset() without you calling the destructor explicitly will cause a memory leak. 
This may be surprising, but it follows the scope rules. For example, creating an object on the heap in a function (in a named script) without explicitly deleting it will also cause a memory leak. Since when exiting the function only the stack variables are deleted. 

## Debugging: Stepping

- .s           set the step mode to step into              function
- .S           set the step mode to go over              function or loop
- .e           continue to end of the function
- .c           continue to next breakpoint
- .c 45      continue to line 45
- .p <var> print the value of var

- ROOT Day 2,  Suzanne Panacek

**Notes:**
Root> .s
.s turns on the step mode execution.

S
.S sets the step mode to stepping over the function or loop 

e
.e executes the function and steps over it. 

.c 45
.c 45 continues to line 45. This will also change the mode to "continue"

.p prints the value of the variable.

## Debugging: Breakpoints

- .trace MyClass       	prints the executing                               	code to window
- .deltrace MyClass	        removes the trace
- .break MyClass      	breaks at each                               	method of MyClass
- .delbreak MyClass 	removes the break
- .b 34                       	sets a break point at                               	line 34
- .db 34                     	removes the break                               	point at line 34

- ROOT Day 2,  Suzanne Panacek

**Notes:**
.trace MyClass 
Prints the code it is executing without stopping. This is helpful to find the line number to set a break point
.deltrace MyClass
Deactivates the trace command
.break MyClassPuts a breakpoint at the beginning of each method of MyClass.
.delbreak MyClassRemoves the breakpoints at the beginning of each method of MyClass.
.b 34 
Puts a breakpoint at line 34 of the currently executing macro.
.db 34
Removes the breakpoint at line 34. Hitting return will execute to the end of the function.
.D
changes the display mode

## Debugging: Inspecting

- DrawClass()	    Graphic list of methods
-                             including ancestors
- Inspect()             Draw the current                        contents of an object
- Dump()               Lists the current                         contents of an object
- gDebug = 1	    Prints debugging
-                             information

- ROOT Day 2,  Suzanne Panacek

## Tracking Memory Leaks

- Counting Objects and Memory use
- In the .rootrc or system.rootrc file:
- Root.MemStat:   1
- Root.ObjectStat:1
- Print the Object count and Memory use
- gObjectTable->Print();

- ROOT Day 2,  Suzanne Panacek

## Tracking Memory Leaks+

- Example output:
- Before .x FirstContour.C:
-                count     on heap     size    total size      heap size
- Total:        1,079     1,046    3,160      **49,992**      **45,824**
- After:
- Total:        1,783    1,749   17,920    **118,912  114,568**
- Put **gObjectTable->Print()** before and after code segment in your script to find memory leaks.

- ROOT Day 2,  Suzanne Panacek

## ACLiC: Automatic Compiler of Libraries for CINT 

- Use an external compiler to create a shared library from a macro.
- Use
- root [0] .L MyMacro.C**++**** **
- 	Always recompile
- root [0] .L MyMacro.C**+**** **
- 	Recompile as needed

- ROOT Day 2,  Suzanne Panacek

**Notes:**
ACLiC allows the user to use an external compiler to create a shared library from a C++ macro.

The syntax is simply a "++" added to .L command:
root [0] .L MyMacro.C++

Or in a macro you can use the ACLiC to compile and load another macro with the CompileMacro command:
gSystem->CompileMacro("MyMacro.C", "kf");

## ACLiC Use

- Restriction: can not use path name with .L
- .L ../root_base/MyMacro.C+
- Instead do:
- gSystem->cd("../directory");
- gSystem->CompileMacro("MyMacro.C")
- Options are:
- 	k : keep the shared library after the session end.
- 	f : force recompilation.
- To set the Include path:
- 	 .include "-I$HOME/mypackage/include";

- ROOT Day 2,  Suzanne Panacek

**Notes:**

In a script you can load another script by using the CompileMacro command:
gSystem->CompileMacro("MyScript.C");
In general the syntax is:
gSystem->CompileMacro("filename", option);

You can get the include path by typing:
root [0] .include
You can append to the include path by typing:
Root [1] .include "-I$HOME/mypackage/include "

In a macro you can set the include path:
gSystem->SetIncludePath (" -I$HOME/mypackage/include ")
The $ROOTSYS/include directory is automatically appended to the include path, so you don't have to worry about including it, however if you have already added a path, this command will overwrite it.

ACLiC does not creates the dictionaries if you use a directoryname in the filename.  For example:        .L ../root_base/MyMacro.C+will link but will not expose its symbol to cint.To fix the problem you need to first move to the directory:        gSystem->cd("../root_base");        gROOT->ProcessLine(".L MyMacro.C+");

## ACLiC Advantages

- Advantages :
-  syntax checking
-  about five times faster
-  full C++ feature set
- Disadvantage:
- On KCC,  you can load each C++ shared library only once

- ROOT Day 2,  Suzanne Panacek

**Notes:**
ACLiC allows the user to use an external compiler to create a shared library from a C++ macro.
Advantages of the ACLiC are:
 syntax checking is more thorough than CINT and with better error messages
 speed of execution is better because it is compiled rather than interpreted.
 able to use full C++ beyond the limitation of CINT. For example full template support and STL.
Disadvantages:
 with the KCC compiler can only load each C++ shared library once per root session, this also means that you can not use the .U command to unload the shared library. When adding shared libraries one after another, and then removing one that has been added previously to others, the ones added after the one to be removed will also be removed.

## ACLiC Demo

- .L ScriptCompilerDemo.C++
- root [0] gROOT->Time()
- root [1] .L ACLiCDemo.C++
- root [2] .files
- root [3] Demo()
- Compare performance with CINT
- root [0] gROOT->Time()
- root [1] .L ACLiCDemo.C
- root [3] Demo()

- ROOT Day 2,  Suzanne Panacek

**Notes:**
To use ACLiC :
root [0] gROOT->Time() 
root [1] .L ACLiCrDemo.C++
	Real time 0:0:5, CP time 0.030
root [2] .files
  ... 
  4 fp=0x   0 lines=0   file="/home/ghi/spanacek/root102/./ACLiCDemo.so" 
root [3] Demo()
	Real time 0:0:0, CP time 0.280

Compare the speed of ACLiC with the CINT interpreter.
Exit and reenter root.
root [0] gROOT->Time()
root [1].L ACLiCDemo.C
	Real time 0:0:0, CP time 0.000
root [2] Demo()
	Real time 0:0:5, CP time 4.820

## Summary (Scripts)

- Named and Un-named Scripts
- Debugging
- ACLiC

- ROOT Day 2,  Suzanne Panacek

## Getting started with the Exercises

- Go to: http://patwww.fnal.gov/root/class/Setup.htm for setup instructions using Reflection and ssh on fcdfsgi2 and d0mino and minos1.
- Find the exercises on line at:
- http://patwww.fnal.gov/root/class/exercises.htm

- ROOT Day 2,  Suzanne Panacek

## Exercise Overview

- Session A
- Use ROOT command line
- Write a named and un-named script
- Use the GUI to create objects and change their attributes
- Save your canvas to a PostScript file
- Fit a graph
- Session B
- Fit and rotate a histogram
- Use the Object Browser and the Tree Viewer
- Make a profile and contour graphs
- Build an event list from a cut
- Fill a histograms with random numbers
- Use ACLiC

- ROOT Day 2,  Suzanne Panacek

## Exercise Session C

- Session C:
- Study an example analysis from DESY
- Learn about the TTree::MakeSelector method to automatically create a class that loops over each entry in a tree.
- Save and retrieve a canvas to and from a ROOT file
- Compute the integral of a histogram
- Compute the integral of a function within a range

- ROOT Day 2,  Suzanne Panacek

## Solutions to the Exercises

- http://patwww.fnal.gov/root/class/solutions.htm

- ROOT Day 2,  Suzanne Panacek

## ROOT contacts at Fermi

- Philippe Canal , x2545	pcanal@fnal.gov
- Suzanne Panacek, x8334	spanacek@fnal.gov
- Jeff Kallenbach, x2210
-   jeffk@fnal.gov

- ROOT Day 2,  Suzanne Panacek

## Mailing Lists

- the ROOT mailing list:
- roottalk@root.cern.ch
- archives:
- http://root.cern.ch/root/roottalk/AboutRootTalk.html
- Fermilab mailing list:
- about-root@fnal.gov
- archives:
- http://listserv.fnal.gov/archives/about-root.html

- ROOT Day 2,  Suzanne Panacek

## Functions and Fitting

- Function Objects (TF1)
- Three constructors for TF1
- User Defined Functions
- Fitting
- Fit()
- Fitting with a user defined function
- Fitting subranges and combining functions
- Demonstration of background and signal function

- ROOT Day 2,  Suzanne Panacek

## Function Objects (TF1)

- Built in function objects
- see this link for a full list of built in functions
- _[http://root.cern.ch/root/html/TFormula.html#TFormula:TFormula](http://root.cern.ch/root/html/TFormula.html#TFormula:TFormula)_
- use the Fit Panel
- Creating your own function objects
- TF1, TF2, TF3
- Three Signatures for the TF1 constructor

- ROOT Day 2,  Suzanne Panacek

**Notes:**
A TF1 object is a one dimensional function defined between a lower and upper limit.
 In addition to TF1, ROOT provides a TF2 and a TF3.  TF2 is a 2 dimensional function with parameters, and TF3 is a 3 dimensional function with parameters

## TF1 Constructors

- 1. A C++ like expression using x with a fixed set of operators and functions defined in TFormula
- TF1 *f1 = new TF1("f1",**"sin(x)/x"**,0,10);
- f1->Draw();
- TF1 *f2 = new TF1("f2","**f1 * 2**",0,10);

- ROOT Day 2,  Suzanne Panacek

## TF1 Constructors (cont.)

- 2. Same as the previous TF1  with Parameters
- Call the constructor with parameter indices
- TF1 *f1 = new TF1
- ("f1","**[0]**** ***x*sin( **[1]**** ***x)",-3,3);See TFormula for valid expressions
- Set the parameters explicitly
- f1->SetParameter(0,10);f1->SetParameter(1,5);f1->Draw();

- ROOT Day 2,  Suzanne Panacek

## TF1 Constructors (cont.)

- 3. Use a defined function
- Define a function**Double_t MyFunction(Double_t *x, Double_t *par)**{ 	Float_t  xx 	=	x[0];	Double_t val	= 		TMath::Abs(par[0]*sin(par[1]*xx)/xx); 	return val;}
- TF1 constructor TF1 *f1 = new TF1("f1",**MyFunction**,0,10,**2**);
- NOTE: The **2** is the number of parameters in MyFunction.
- Set the parametersf1->SetParameters(2,1);

- ROOT Day 2,  Suzanne Panacek

## Fitting

- To fit a histogram:
- 	TF1 *fn1 = new TF1
- ("**f1**","[0]** ***x*sin([1]*x)",-3,3);
- f1->SetParameters(10,5);aHistogram->Fit("**f1**"); **//name**
- aHistogram->Fit(**fn1**); **// pointer**

- ROOT Day 2,  Suzanne Panacek

## Fitting: Example

- Step 1. Define the function:
**Double_t MyFunction (Double_t *x, Double_t *par)**
- {
- 	Double_t arg= 0;
- 	if (par[2]) arg = (x[0] - par[1])/par[2];
- 	Double_t fitval =
- 		par[0] * TMath::Exp(-0.5*arg*arg);
- 	return fitval;
- }

- ROOT Day 2,  Suzanne Panacek

**Notes:**

To fit a histogram with a user define function:
Step 1:
Create a new macro and define the function to use in the fit. 
{
   Double_t MyFunction (Double_t *x, Double_t *par)
   {
      Double_t arg= 0;	
      if (par[2]) arg = (x[0] - par[1])/par[2];	
      Double_t fitval = 
	par[0]*TMath::Exp(-0.5*arg*arg);
      return fitval;
   }
}

## Fitting (cont.)

- Step 2. TF1 constructorTF1 *aFunction = 		new TF1("**MyGaus**", **MyFunction**, -5,5,**3**);
- Step 3. Set initial value of the parametersaFunction->SetParameters(**5000, ****	****	****h->GetMean(),****	****	****h->GetRMS());**
- Step 4. Fit and draw the histogramh->Fit("**MyGaus**");

- ROOT Day 2,  Suzanne Panacek

**Notes:**
Step 2: Call the constructor for TF1 with the name of the function, the lower and upper limits and the number of parameters.
   TF1 *aFunction = 
      new TF1("MyGaus", MyFunction, -5,5,3);
Step 3**:
Set the parameters: p1 = 5000, p2 = mean of the histogram, p3 = the RMS of the histogram
  aFunction->SetParameters(5000, 		h->GetMean(),		h->GetRMS
Step 4: 
Fit the histogram with the predefined function.
   h->fit("MyGaus");
** we assume you have a histogram h to use.

## Fitting Sub-Ranges Example

- $ROOTSYS/tutorials/multifit.C
- Define the range in the TF1 constructor.
- TF1 *g1 = new TF1("**g1**", "gaus", **85,95**);
- By default, TH1::Fit on the defined histogram range. Use "R" option in the Fit() method.h->Fit**("g1", "R");**

- ROOT Day 2,  Suzanne Panacek

## Fitting Subranges

- ROOT Day 2,  Suzanne Panacek

**Notes:**
Fitting a subrange:
Step 1:
create a function for the fit and give it a subrange in the constructor
   TF1 *g1 = new TF1("g1", "gaus", 85,98);

Step 2:
fit and draw the histogram and use the range specified in the function constructor. 
	h->Fit("g1","R");

Fitting multiple functions 
Step 1:
create one more function, this time we use the gaussian function provided by ROOT. Give it a subrange:   	TF1   *gaus1 = new TF1("g1","gaus",1,3);   
Step 2:Call the Fit method . Use the "R" option to use the range specified by the function constructor. Use the "+" option to add this new function to the list of functions. By default the previous function is deleted.
	aHisto->Fit("g1","R+");

## Fitting Subranges++

- Define gaussian functions
- g1    = new TF1("m1","gaus",85,95);
- g2    = new TF1("m2","gaus",98,108);
- g3    = new TF1("m3","gaus",110,121);
- total = new
- TF1("mstotal","gaus(0)+gaus(3)+gaus(6)",85,125);
- From TFormula:
- gaus(0) is a substitute for : [0]*exp(-0.5*((x-[1])/[2])**2)
- and (0) means start numbering parameters at 0

- ROOT Day 2,  Suzanne Panacek

## Fitting Sub-Ranges++

- Fit each range and get the parameter for "total"
-   h->Fit(g1,"R");
-  h->Fit(g2,"R+");
-  h->Fit(g3,"R+");
-  g1->GetParameters(&par[0]);
-  g2->GetParameters(&par[3]);
-  g3->GetParameters(&par[6]);
-  total->SetParameters(par);
-  h->Fit(total,"R+")

- ROOT Day 2,  Suzanne Panacek

## Signal and Background Demo

- y(E) = a1 + a2E + a3E2    +   AP  ( / 2 )/( (E-)2 + (/2)2) 			background			lorenzianPeak
- 	par[0] = a1			par[0] = AP
- 	par[1] = a2			par[1] = 
- 	par[2] = a3			par[2] = 
- fitFunction = background (x, par ) + lorenzianPeak (x, &par[3])
- 	par[0] = a1
- 	par[1] = a2
- 	par[2] = a3
- 	par[3] = Ap
- 	par[4] = 
- 	par[5] = 

- ROOT Day 2,  Suzanne Panacek

## Fitting Demo

- Look at
- FittingDemo.C
- Unnamed Macro
- fitf.C
- Named Macro
- Run FittingDemo.C
- More info on fitting:
- _[http://root.](http://root.cern.ch/root/html/examples/fit1.C.html)__[cern](http://root.cern.ch/root/html/examples/fit1.C.html)__[.](http://root.cern.ch/root/html/examples/fit1.C.html)__[ch](http://root.cern.ch/root/html/examples/fit1.C.html)__[/root/html/examples/fit1.C.html](http://root.cern.ch/root/html/examples/fit1.C.html)_
- _[http://root.](http://root.cern.ch/root/html/examples/myfit.C.html)__[cern](http://root.cern.ch/root/html/examples/myfit.C.html)__[.](http://root.cern.ch/root/html/examples/myfit.C.html)__[ch](http://root.cern.ch/root/html/examples/myfit.C.html)__[/root/html/examples/](http://root.cern.ch/root/html/examples/myfit.C.html)__[myfit](http://root.cern.ch/root/html/examples/myfit.C.html)__[.C.html](http://root.cern.ch/root/html/examples/myfit.C.html)_
- _[http://root.](http://root.cern.ch/root/html/examples/backsig.C.html)__[cern](http://root.cern.ch/root/html/examples/backsig.C.html)__[.](http://root.cern.ch/root/html/examples/backsig.C.html)__[ch](http://root.cern.ch/root/html/examples/backsig.C.html)__[/root/html/examples/](http://root.cern.ch/root/html/examples/backsig.C.html)__[backsig](http://root.cern.ch/root/html/examples/backsig.C.html)__[.C.html](http://root.cern.ch/root/html/examples/backsig.C.html)_

- ROOT Day 2,  Suzanne Panacek

**Notes:**
See FittingDemo.C and fitf.C

FittingDemo.C is an unamed macro. The concept of named and unamed macros is covered in ROOT 101. A named macro has a function that has the same name as the file and is executed when CINT parses the .X command. All variables in the function are local and not accessible on the command line. An unamed macro is a set of commands enclosed in curly brackets. It can or can not have functions. All commands inside the curly brackets are executed, and the variables are global and available on the command line.

## Summary: Fitting and Functions

- Functions Objects (TF1)
- Three constructors for TF1
- User Defined Functions
- Fitting
- Fit()
- Fitting with a user defined function
- Fitting sub ranges and combining functions
- Demonstration of background and signal function

- ROOT Day 2,  Suzanne Panacek

## The Tree Viewer Overview

- Drawing Histograms
- Using Cuts
- Lego Plots
- Creating new Variables
- Saving the Canvas

- ROOT Day 2,  Suzanne Panacek

## The Tree Viewer

- root[] myTree->StartViewer()
- Contents:
- XYZ
- Cut
- Scan
- Expressions
- Variables (leaves)
- Draw option
- Recording commands
- Histogram
- Range Selector
- IList/OList

- ROOT Day 2,  Suzanne Panacek

**Notes:**
Step by Step 
To create a Tree Viewer
Open the file with the File->Open menu item
In the Browser, right click on the tree. The context menu for the tree appears.
Select StartViewer
Or from the command line
Open the root file 
root[] TFile f("Example.root")
root[] myTree->StartViewer()
Tree Viewer components
Slider To select the events range (min/max). 
Break Interrupt the event loop 
IList	 To select a TEventList as an input selection (List In)
X,Y,Z	 To select the X,Y,Z variable	
Cpad	Specifies the output pad (default = c1) 
Hist	Redefines the default histogram (default = htemp)
OList	Creates a new TEventList using the current selection (List Out)
Gopt	Used to specify graphic options 	
Draw	Display the variable(s) that are placed in the X, Y, Z button	
Scan	Same with TTree::Scan output style		
Weight-Selection	Select the weight/Selection expression
Record	When this is enabled (red), the executed command is printed on the command line, and saved in the history file.	

## Drawing Two Histograms

- Double click on one variable
- Select Superimpose option
- Double click on another variable

- ROOT Day 2,  Suzanne Panacek

**Notes:**
Step by Step 
To draw a variable
In the Tree Viewer select the white box marked xs1 and drag it into the X box.
Select Draw. You should now see a histogram of the variable xs1.
To draw another variable in the same canvas
Select the xs1 box  and drag it out of the X box
In the Tree Viewer, select the white box in the Gopt box
Right click on it, and select the SetLabel item. This will bring up a dialog with a text field.
Type  ‘same’ in the text box.
Select the xmain box and drag it into the X box
Select Draw. You should now see two histograms on the same canvas.
To add color to the histograms
Select the SetFillAttibutes from each histogram’s context menu (right click)
Select a color and fill pattern.

## Adding Weight

- Add a Weight: xmain < 0

- ROOT Day 2,  Suzanne Panacek

**Notes:**
Step by Step 
To add a weight
In the Tree Viewer locate the white box in the Weight-Selection box.
Right click on this box and select SetLabel
Type ‘xmain < 0’ and select OK.
If there is a variable in the X box drag it away
Drag the xs1 variable (the white box marked xs1) into the X box.
Select Draw

## 2D Lego Plots 

- Draw xmain vs. xs1
- Rotating the lego plot

- ROOT Day 2,  Suzanne Panacek

**Notes:**
Step by Step 
To draw  a 2d lego plot
In the Tree Viewer,  drag the xs1 variable into the X box
Drag the xmain variable in to the Y box
Right click on the white box in the Gopt and select SetLabel
Set the label to ‘lego’
Select Draw

## Creating a variable

- 2. Set the name and expression
- 3. Double click to draw it

- 1. Create New Expression

- ROOT Day 2,  Suzanne Panacek

**Notes:**
To create a new variable and draw it
Right click on the Tree Viewer background to bring up the context menu.
Select CreateNewVar
Type xmain*xs1 in the option box when it appears
Select OK. This creates a new variable. It is somewhat hard to find, because it is placed in the upper left corner of the viewer. Locate the new variable now and drag it to the middle of the viewer.
Clear the Weight, Gopt, X, and Y boxes by dragging the variables out.
Double click on the new variable to draw it. 

## More Features

- Record:
- Command is recorded in history file ($HOME/root_hist)
- Is printed on the command line
- Scan:
- 	1) Drag and drop variables to scan box
- 	2) Redirect output to a file
- Saving and recovering a Session:
- 	1) Save the current cuts, expressions into treeviewer.C
- 	2) Read session back

- ROOT Day 2,  Suzanne Panacek

**Notes:**

If the REC. button is enabled (red) the command is saved in the history file and printed on the command line. This is an excellent way to learn the syntax of the draw command and experiment with it.

myTree->Draw("xs1", "", "", 10000, 0);
myTree->Draw("xmain", "", "same", 10000, 0);
myTree->Draw("xs1", "xmain < 0", "same", 10000, 0);
myTree->Draw("xs1:xmain", "", "lego", 10000, 0);

## Saving the Canvas

- The save options:
- Postscript
- gif
- ROOT file
- Macro
- Save as a ROOT file:
- Open the saved ROOT file (c1.root) and draw the canvas
- root[2] > c1.Draw();

- ROOT Day 2,  Suzanne Panacek

**Notes:**
Step by Step
To save the canvas as a root file:
1. In the Canvas window, select the ‘Save As Canvas.root’ option in the File menu
2. This will automatically give the file the name of the canvas and append a .root to it. For example in this case the file will be called c1.root
To reopen the saved canvas:
1. Open the c1.root file with the browser
2. On the command line type:	> c1.Draw();
Opening the file alone does not draw the canvas.

## Summary (TreeViewer)

- Drawing a Two Histogram
- Adding Weight
- Lego Plots
- Creating a variable
- More Commands
- Saving a Canvas

- ROOT Day 2,  Suzanne Panacek