Home

A ROOT Guide For Students - Institut für Experimentelle Kernphysik

image

Contents

1. 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 proof for each worker node This is very helpful for debugging or if something goes wrong As the the method described here also works without using PROOF the development work on an analysis script can be done in the standard way on a small subset of the data and only for the full processing one would use parallelism via PROOF 6 2 7 Optimisation Regarding N tuples ROOT automatically applies compression algorithms on n tuples to reduce the memory consumption A value that is in most cases only zero will consume only small space on your disk but it has to be deflated on reading Nevertheless you should think about the design of your n tuples and your analyses as soon as the processing time exceeds some minutes e Try to keep your n tuples simple and use appropriate variable types If your measurement has only a limited precision it is needless to store it with double precision e Experimental conditions that do not change with every single measurement should be stored in a separate tree Although the compression can handle redundant values the processing time increase with every variable that has to be filled 37 6 File I O e The function SetCacheSize long specifies the size of the cache for reading a TTree object from a file The default value is 30MB A m
2. The function to be minimized called by MINUIT must have this form void fFCN Int_t amp npar number of parameters optional double gin array of derivatives w r t parameters optional double amp n21L the function value double par array of parameters int iflag inernal flag calculate negative log likelihood n21L 0 set parameters of PDF PDF gt SetParameters par 0 par 1 calculate log L i e loop over ntuple float xntrow for int i 0 i lt inpdata gt GetEntries 1 inpdata gt GetEntry i ntrow inpdata gt GetArgs n21L log PDF gt Eval ntrow 0 n21L 2 multiply by two as common elsewhere in ROOT 43 30 31 32 33 34 35 36 37 38 39 40 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 7 Functions and Parameter Estimation main program fit control void negLogLfit define a probability density function normalized to one PDF new TFi eplusconstPDF 1 1 exp x 0 exp 5 01 01 11 5 0 5 exponential in range 0 5 plus off set input data come from a file and are stored in an NTuple inpdata new TNtuple InputData InputData x read data from file and store in ntuple ifstream inp
3. 100 F No Chi square are easily available through the latest version of the graphical in Fit Options terface As function fitting is of prime importance in any kind of Integral Use range data analysis this topic will again show up in later chapters Best errors F Improve fit results If you are satisfied with your plot you probably want to save p All weights 1 Add to list it Just close all selector boxes you opened previously and select D Empty bins weights 1 Use Gradient the menu item Save as from the menu line of the window which Drawioptions will pop up a file selector box to allow you to choose the format SAME A No drawing file name and target directory to store the image z B TF Do not store draw Advanced There is one very noticeable feature here you can store a plot as a root macro In this macro you find the C representation x 0 00 ga as PCT y of all methods and classes involved in generating the plot This is OS a very valuable source of information for your own macros which you will hopefully write after having worked through this tutorial Update Et Beset close Using the interactive capabilities of ROOT is very useful for THIF h LIB Minuit MIGRAD Itr 0 Prn DEF y a first exploration of possibilities Other ROOT classes you will be encountering in this tutorial have such graphical interfaces as Figure 2 5 Fit functions to graphs and well We will not comment furthe
4. 83 myMinuit mnstat amin edm errdef nvpar nparx icstat 84 meaning of parameters 85 amin value of fcn at minimum chi 2 86 edm estimated distance to mimimum 87 errdef delta fcn used to define 1 sigma errors 88 nvpar number of variable parameters 89 nparx total number of parameters 90 icstat status of error matrix 91 4 3 accurate 92 2 forced pos def 93 l approximative 94 i 0 not calculated 95 myMinuit mnprin 3 amin print out by Minuit 96 97 4 gt get results from MINUIT 98 finalPar 99 finalParErr 100 p pe Double 0 Double 0 101 for i in range 0 npar 51 102 103 104 105 106 107 108 109 110 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 8 ROOT in PYTHON myMinuit GetParameter i p pe retrieve parameters and errors finalPar append float p finalParErr append float pe get covariance matrix buf arr d npar npar 0 myMinuit mnemat buf npar retrieve error matrix emat np array buf reshape npar npar gt provide formatted output of results print An print MINUIT fit completed print fcn minimum 3g amin error code ierflg status icstat print Results Nt value error corr mat for i in range 0 npar print 4s t 10 3e 1e name i finalPar i finalParErr i for j in range 0 i print 4 3g l emat i j
5. APPENDIX C MOST RELEVANT CLASSES AND THEIR METHODS This list of classes and methods shows the most relevant ones which have been considered in this guide It is an excerpt from the ROOT class reference guide TGraphErrors the graph class with error bars create Graph frm file TGraphErrors const char filename const char format lg lg lg lg Option t option create graph fom C arrays TGraphErrors Int_t n const Float t x const Float t y const Float t ex 0 const Float t ey 0 create graph from histogram TGraphErrors const THi h fit a function Fit TFi fi Option t option Option t goption Axis t xmin 0 Axis t xmax 0 Fit const char formula Option t option Option t goption Axis t xmin 0 Axis t xmax 0 draw Draw AP and DrawClone AP draw options methods of classes TGraph TGraphPainter the histogram class with float bin contents create book histogram THiF const char name const char title Int t nbinsx Double_t xlow Double t xup store also squared weights Sumu2 fill a value Fill Double t x fill with weight Fill Double t x Double t w set bin content SetBinContent Int t bin Double t content get bin content Double_t GetBinContent Int t bin const fill with random numbers FillRandom const char fname Int t ntimes clear Reset O copy to C array Float t GetArrayO set maximum on y axis SetMaximum Double t ymax set minimum on y axix
6. curFuncV curYEscurYE 50 return chisq 51 52 the function fcn called by MINUIT repeatedly with varying parameters 53 NOTE the function name is set via TMinuit SetFCN 54 def fcn npar deriv f apar iflag 55 meaning of parametrs 56 npar number of parameters 57 deriv aray of derivatives df dp_i x optional 58 f value of function to be minimised typically chi2 or negLogL 59 apar the array of parameters 60 iflag internal flag 1 at first call 3 at the last 4 during minimisation 61 Hann 62 f 0 calcChi2 npar apar 63 i 64 65 gt set up MINUIT 66 myMinuit TMinuit npar initialize TMinuit with maximum of npar parameters 67 myMinuit SetFCN fcn set function to minimize 68 arglist arr d 2 0 01 set error definition 69 ierflg Long 0 70 arglist 0 1 i 1 sigma is Delta chi 2 1 71 myMinuit mnexcm SET ERR arglist 1 ierflg 72 73 t gt Set starting values and step sizes for parameters 74 for i in range 0 npar Define the parameters for the fit 75 myMinuit mnparm i name i vstart i step i 0 0 ierflg 76 arglist 0 6000 Number of calls to FCN before giving up 77 arglist 1 0 3 Tolerance 78 myMinuit mnexcm MIGRAD arglist 2 ierflg execute the minimisation 79 80 f gt check TMinuit status 81 amin edm errdef Double 0 Double 0 Double 0 82 nvpar nparx icstat Long 0 Long 0 Long 0
7. gt Sumw2 Very Important 24 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 5 2 Add and Divide Histograms MN N o o IIT a al cA Oo o o o M e o o o o Gaus Histo 1 Gaus Histo 2 BR 3 e PAPA PAPA TTT Y Om Figure 5 2 The sum of two histograms and the ratio format_h histos i i 1 Sum THiF sum_h new TH1F x bkg_h sum_h gt Add sig_h 1 sum_h gt SetTitle Exponential Gaussian format h sum h kBlue TCanvas c sum new TCanvas sum_h gt Draw hist bkg_h gt Draw SameHist sig_h gt Draw SameHist Divide THiF dividend new TH1F gaus_h1 dividend gt Divide gaus_h2 Graphical Maquillage dividend gt SetTitle X axis Gaus Histo 1 Gaus Histo 2 format_h dividend k range gaus_hi gt SetTitle Gaus Histo 1 and Gaus Histo 2 gStyle gt SetOptStat 0 gStyle gt SetOptTitle 0 TCanvas c_divide new TCanvas c_divide gt Divide 1 2 0 0 c_divide cd 1 c_divide GetPad 1 gt SetRightMargin 01 gaus_h1 gt DrawNormalized Hist gaus_h2 gt DrawNormalized HistSame c divide cd 2 dividend gt GetYaxis gt SetRangeUser 0 2 49 c_divide gt GetPad 2 gt SetGridy c_divide gt GetPad 2 gt SetRightMarg
8. o ExampleMacro_GUI exe ExampleMacro_GUI root config cflags libs and execute the program with gt ExampleMacro GUI exe 18 OMAN DA KWN HE meee wn KF o ow krwnere CHAPTER 4 GRAPHS In this Chapter we will learn how to exploit some of the functionalities that ROOT provides to display data based on the class TGraphErrors which you already got to know previously 4 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 a file in ASCII i e standard text format TGraphErrors const char filename const char format lg lg lg lg Option t option The format string can be e lg Mg read only 2 first columns into X Y e lg Mg lg read only 3 first columns into X Y and EY e Wilg Mg Mlg MVAlg read only 4 first columns into X Y EX EY This approach has a the nice feature of allowing the user to reuse the macro for many different data sets Here is an example of an input file 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 Measurement XYZ and Expectation Measurement of Friday 26 March Experiment 2 Physics Lab Lab Lesson 2 70 ps M Expected Points Arb Units 6 12 14 20 22 2
9. SetMinimum Double t ymin get mean Double t GetMean 1 get RMS Double t GetRMS 1 draw Draw U ption t option useful draw options SAME E pr see documentation of class THistPainter 2 dimensional histogram class with float bin contents ook TH2F const char name const char title Int t nbinsx Double t xlow Double t xup Int_t nbinsy Double t ylow Double t yup fill Fill Double t x Double t y fill with weight Fill Double t x Double t y Double t w get mean along axis i Double_t GetMean i get RMS along axis i Double_t GetRMS i get covariance Double_t GetCovariance get correlation Double_t GetCorrelationFactor draw Draw Option_t option and DrawClone useful draw options SAME BOX COL LEGO SURF see documentation of class THistPainter TProfile profile representation for 2 dim histograms book profile histogram TProfile const char name const char title Int t nbinsx Double t xlow Double t xup Double t ylow Double t yup Option_t option fill a value Fill Double t x fill with weight Fill Double t x Double t w draw DrawO and DrawClone the mathematical function define function in TFormula syntax TFi const char name const char formula Double t xmin 0 Double t xmax 1 predefined functions gaus expo pol0 pol9 landau define function via pointer TFi const char name void fcn Double t xmin Double t xmax Int t npar evaluate at x Eval Double_
10. Two dimensional histograms are a very useful tool for example to inspect correlations between variables You can exploit the bi dimensional histogram classes provided by ROOT in a very simple way Let s see how in the following macro Draw a Bidimensional Histogram in many ways together with its profiles and projectionsx void macro gROOT gt SetStyle Plain gStyle gt SetPalette 1 gStyle gt SetOptStat 0 gStyle gt SetOptTitle 0 TH2F bidi_h bidi_h 2D Histo Guiassian Vals Exp Vals 30 5 5 X axis 30 0 10 Y axis TRandom3 rndgen for int i 0 i lt 500000 i bidi_h Fill rndgen Gaus 0 2 10 rndgen Exp 4 TCanvas c new TCanvas Canvas Canvas 800 800 c Divide 2 2 c gt cd 1 bidi_h DrawClone Contz c gt cd 2 bidi_h DrawClone Colz c gt cd 3 bidi_h DrawClone lego2 c gt cd 4 bidi_h DrawClone surf3 Profiles and Projections TCanvas c2 new TCanvas Canvas2 Canvas2 800 800 c2 Divide 2 2 c2 gt cd 1 bidi_h ProjectionX gt DrawClone c2 gt cd 2 bidi_h ProjectionY gt DrawClone c2 gt cd 3 bidi h ProfileX DrawClone c2 gt cd 4 bidi_h ProfileY gt DrawClone file macro macro7 cxx Two kinds of plots are provided by the code the first one containing three dimensional representations Fig ure 5 3 and the second one projections and profiles of the bi dimensional histogram When
11. double x inp open expob dat while inp gt gt x 0 inpdata gt Fill x inp close create fitter instance and initialize using Minuit TVirtualFitter SetDefaultFitter Minuit TFitter fit TFitter TVirtualFitter Fitter NULL NFitPar the above type cast is a bit ugly needed to gain access to TMinuit object which is possible only via class TFitter x fit gt SetFCN fFCN assign function to be minimized set initial values of parameters fit SetParameter 0 parameter index tau parameter name 1 initial value 0 1 initial uncertainty 0 fixes parameter 0 upper limit 0 not set 0 lower limit 0 not set name val err low up fit SetParameter l off 0 5 0 1 0 0 run the fit double arglist 2 5000 0 01 max number of function calls tolerance fit ExecuteCommand MINIMIZE arglist 2 performs SIMPLEX MIGRAD gt algorithms fit ExecuteCommand MINOS arglist 0 MINOS error evaluation retrieve output int nvpar nparx double amin edm errdef if fit gt GetStats amin edm errdef nvpar nparx 3 cout lt lt endl lt lt x x Fit converged lt lt nlL lt lt amin lt lt edm lt lt edm lt lt nvpar lt lt nvpar lt lt nparx lt lt nparx lt lt lt endl lt lt end1 fit gt PrintResults 4 amin get covariance Matrix an print it TMatrixD covMatrix new TMatrixD nparx nparx
12. fit gt GetCovarianceMatrix covMatrix gt Print plot data fit result and parameter contours TCanvas c new TCanvas c contours 10 10 400 600 c gt Divide 1 2 c gt cd 1 inpdata gt Draw x THiF htemp TH1F gPad gt GetPrimitive htemp THiF ht TH1F htemp gt Clone ht gt SetLineWidth 2 ht gt SetLineColor kBlue PDF must be scaled to take account of of Entries and bin width ht gt Eval PDF ht gt Scale inpdata gt GetEntries ht GetBinWidth 1 44 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 7 3 Fitting in General ht gt Draw C SAME plot contours c cd 2 Get contour for parameter 0 versus parameter 1 for ERRDEF 4 fit SetErrorDef 4 note 4 and not 2 TMinuit minuit fit GetMinuit TGraph gr2 TGraph minuit gt Contour 40 0 1 gr2 gt SetTitle 1 sigma and 2 sigma contours tau off set gr2 gt SetFillColor 42 gr2 gt Draw alf Get contour for parameter 0 versus parameter 1 for ERRDEF 1 fit SetErrorDef 1 TGraph gri TGraph minuit gt Contour 40 0 1 gri gt SetFillColor 38 gri Draw 1f clean up delete inpdata delete PDF file negLogLfit cxx You already know most of the code fragments used above The new part is the user defined minimisation function fFCN made known to the minimiser via the method SetFCN vo
13. 001741 0 001741 0 001741 0 000383 0 000383 0 000383 0 000383 0 001741 0 010404 0 001741 0 001741 0 000383 0 000383 0 000383 0 000383 0 001741 0 001741 0 008281 0 001741 0 000383 0 000383 0 000383 0 000383 0 001741 0 001741 0 001741 0 006561 60 APPENDIX B IN MARKERS COLOURS SYMBOLS B 1 Colour Wheel and Graph Markers A O qn X X 25 26 27 28 29 30 6 7 8 9 0 11 ROOT Color Wheel Figure B 1 The wheel shows all available colours in ROOT and the codes to specify them and The markers provided by ROOT Table B 1 Alternative symbols to select the ROOT markers for graphs Integer Description Literal Integer Description Literal 1 dot kDot 21 full square kFullSquare 2 kPlus 22 full triangle up kFullTriangleUp 3 m kStar 23 full triangle down kFullTriangleDown 4 O kCircle 24 open circle kOpenCircle 5 x kMultiply 25 open square kOpenSquare 6 small dot kFullDotSmall 26 open triangle up kOpen TriangleUp 7 medium dot kFullDotMedium 27 open diamond kOpenDiamond 8 large scalable dot kFullDotLarge 28 Open cross kOpenCross 20 full circle kFullCircle 29 open star kOpenStar 61 B Markers Colours Symbols B 2 Lines and Arrows e e T eI 4 po Figure B 2 The arrows styles available in ROOT B 3 Latex Symbols w o a gt 62 club diamond voidn X aleph leq 2 geq approx neq in notin supset S subseteq cap V eup oc
14. 17 3 4 Interpretation and Compilation a a eA 17 3 4 14 Compile a Macro with ACTIC re 17 3 4 2 Compile a Macro with g oaoa Rn 17 4 1 Read Graph Points from File 4 2 Polar Graphs oicc oes 4 99 x xem Eos a 9 ES uE Sor Pee eor deum wav wea X de 20 TA Pc 21 A GOLA HAN AD AY Oana ase ee eas 23 b l Your First Histogram s eces me ae See GE a A Ge ee ee es 23 5 2 Add and Divide Histograms s sacs ate goe eo a 24 5 3 Two dimensional Histograms 000 02 ee 26 TT ee Ake EEE 39 7 1 Fitting Functions to Pseudo Data le 39 7 2 Toy Monte Carlo Experiments oaoa eee 41 3 Fitting in General sc ob eR IR or VR A e SERE VR EUR ee a 43 65 Contents A A A ARS 47 NA ee ete 47 8 1 1 More PYTHON less ROOT e 49 A ROGEILAb isa e e Sa ia a ed ae a 55 ER suu he oe Bee 55 AAA Tee re oe ee ee ee ee ee 56 A 1 2 Usage of RooFiLab rs 56 ETUR ETAT E 56 A 2 Straight line fit with correlated erros in x and y 57 A 2 2 Averaging correlated measurements 58 A 2 3 Fit of a polynomyal to data with Poisson errors 59 A 2 4 Correlated measurements with full covariance matrix 004 60 B Markers Colours Symbols oA 61 B 1 Colour Wheel and Graph Markers 2A 61 IB 2 Linesand ATTOWS 2369602 x03 6 mb an ay eru Gy D tede ut Dar e up wo D ce ar d teen le Wed Wear ub X ore 62 B 3 Late
15. 4 5 4 2 5 1 2 9 4 1 4 8 5 43 Instance of the graph TGraphErrors graph n_points x_vals y_vals NULL y_errs graph SetTitle Measurement XYZ lenght cm l Arb Units Make the plot estetically better gROOT gt SetStyle Plain graph SetMarkerStyle kOpenCircle graph SetMarkerColor kBlue graph SetLineColor kBlue The canvas on which we ll draw the graph TCanvas mycanvas new TCanvas Draw the graph graph DrawClone APE 14 37 38 39 40 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 67 68 69 3 2 A more complete example Define a linear function TF1 f Linear law O x 1 5 10 5 Let s make the funcion line nicer f SetLineColor kRed f SetLineStyle 2 Fit it to the graph and draw it graph Fit amp f f DrawClone Same Build and Draw a legend TLegend leg 1 7 3 9 Lab Lesson 1 leg SetFillColor 0 graph SetFillColor 0 leg AddEntry amp graph Exp Points leg AddEntry amp f Th Law leg DrawClone Same Draw an arrow on the canvas TArrow arrow 8 8 6 2 23 0 02 arrow SetLineWidth 2 arrow DrawClone Add some text to the plot TLatex text 8 2 7 5 splitline Maximum Deviation text DrawClone mycanvas Print graph with law pdf ifndef __CINT int main macroi j endif file macro1 cxx Let s comment it in det
16. Table 3 3 2 Arrows and Lines The macro line 56 shows how to define an arrow and draw it The class representing arrows is TArrow which inherits from TLine The constructors of lines and arrows always contain the coordinates of the endpoints Arrows also foresee parameters to specify their shapes see Figure B 2 Do not underestimate the role of lines and arrows in your plots Since each plot should contain a message it is convenient to stress it with additional graphics primitives 16 QO MASON O J 4 Q hl rn 3 4 Interpretation and Compilation 3 3 3 Text Also text plays a fundamental role in making the plots self explanatory A possibility to add text in your plot is provided by the TLatex class 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 The real twist is that ordinary Latex mathematical symbols are automatically interpreted you just need to replace the by a see Figure B 3 3 4 Interpretation and Compilation As you observed up to now we heavily exploited the capabilities of ROOT for interpreting our code more than compiling and then executing This is sufficient for a wide range of applications but you might have already asked yourself how can this code be compiled There are two answers 3 4 1 Compile a Macro with ACLiC ACLiC will create for you a compiled dynamic library for your macro withou
17. 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 To explore the power of this mechanism generate some very large n tuples using the script from Section 6 2 3 you could try 10000000 events this results in a large n tuple of about 160 MByte in size You could also generate a large number of files and use wildcards to add the to the TCHain Now execute gt root 1 RunMySelector C and watch what happens Processing RunMySelector C 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 lt TProofLite SetQueryRunning gt starting query 1 Info in lt TProofQueryResult SetRunning gt nwrks 4 Info in lt TUnixSystem ACLiC gt creating shared library DivingROOT macros lt MySelector_C so Begin of Job Date Time Wed Feb 15 23 00 04 2012 Looking up for exact location of files OK 4 files Looking up for exact location of files OK 4 files Info in lt TPacketizerAdaptive TPacketizerAdaptive gt Setting max number of gt workers per node to 4 Validating files OK 4 files Info in lt TPacketizerAdaptive InitStats gt fraction of remote files 1 000000 Info in lt TCanvas Print gt file ResistanceDistribution png has been created End of Job
18. Tk H Gb Gb Gk Gk xxx Builds a polar graph in a square Canvas from ROOT import TCanvas TGraphPolar TMath from array import array rmin 0 rmax 6 TMath Pi npoints 300 r array d npoints 0 theta array d npoints 0 e array d npoints 0 for ipt in range 0 npoints r ipt ipt rmax rmin npoints 1 rmin theta ipt TMath Sin r ipt c TCanvas myCanvas myCanvas 600 600 grPi TGraphPolar npoints r theta e e grP1 SetTitle A Fan grP1 SetLineWidth 3 grP1 SetLineColor 2 grP1 Draw A0L raw input Press lt ret gt to end gt fi E e macro3 py 8 1 1 More PYTHON less ROOT 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 A more pythonic version of the above macro3 would use a replacement of the ROOT class TMath for the provisoining of data to TGraphPolar With the math package the part of the code becomes import math from array import array from ROOT import TCanvas TGraphPolar ipt range 0 npoints r array d map lambda x x rmax rmin npoints 1 rmin ipt theta array d map math sin r e array d npoints 0 Using the very powerful package numpy and the built in functions to handle numerical arrays makes the PyTHON code more compact and readable import numpy as np from ROOT import TCanvas TGraphPolar
19. as is described in detail in the ROOT documentation On a single computer with multiple cores PROOF lite can be used instead Try the following little macro RunMySelector C which contains two extra lines compared to the example above adjust the number of workers according to the number of CPU cores 36 OMAN DAK Wh Ro OMAN DAK WN HE 10 11 12 13 14 15 16 17 18 6 2 N tuples in ROOT set up a TChain TChain ch new TChain cond_data My Chain for Example N Tuple ch gt Add conductivity_experiment root eventually start Proof Lite on cores TProof Open workers 4 ch SetProof HH ch Process MySelector C file RunMySelector C The first command TProof Open starts a local PROOF server and the command ch gt SetProof enables processing of the chain using PROOF Now when issuing the command ch gt Process MySelector Ct the code in MySelector C is compiled and executed on each slave node The methods Begin and Terminate are executed on the master only The list of n tuple files is analysed and portions of the data are assigned to the available slave processes Histograms booked in SlaveBegin exist in the processes on the slave nodes and are filled accordingly Upon termination the PROOF master collects the histograms from the slaves and merges them In Terminate all merged histograms are available and can be inspected analysed or stored
20. be executed directly from the operating system without the need to start the script from python or the highly recommended powerful interactive shell ipython The last line in the python script is there to allow you to have a look at the graphical output in the ROOT canvas before it disappears upon termination of the script 47 coo 1co oc H8 WN A NNNFP RP RP BP RPP Pe op NOorovomanoonooark wnro OMAN DAK WN HE NON ON ON LB RRP RE BRP RP RP op WN ODO Noa 4rkwNnNr O RNA 8 ROOT in PYTHON Here is the C version void TGraphFit Draw a graph with error bars and fit a function to it H gStyle gt SetOptFit 111 superimpose fit results make nice Canvas TCanvas ci new TCanvas ci Daten 200 10 700 500 ci SetGrid define some data points const Int t n 10 Float t x n 0 22 0 1 0 25 0 35 0 5 0 61 0 7 0 85 0 89 1 1 Float t y n 0 7 2 9 5 E 7 4 9 9 6 8 7 6 3 4 5 1 1 Float_t ey n 8 7 6 5 4 4 5 6 7 8 Float_t ex n 05 1 07 ea 04 05 06 07 08 05 and hand over to TGraphiterad cient TGraphErrors gr new TGraphErrors n x y ex ey gr gt SetTitle TGraphErrors with Fit gr gt Draw AP now perform a fit with errors in x and y gr gt Fit gaus ci Update file TGraphFit C In PYTHON it looks like this usr bin env python Draw a graph with error bars and fit a funct
21. describe macros executed by the ROOT C interpreter CINT An alternative way to access ROOT classes interactively or in a script will be shown in Chapter 8 where we describe how to use the scritping language PYTHON This is most suitable for smaller analysis projects as some overhead of the C language can be avoided It is very easy to convert ROOT macros into python scripts using the pyroot interface Since ROOT itself is written in C let us start with Root macros in C As an additional advantage it is relatively easy to turn a ROOT C macro into compiled and hence much faster code either as a pre compiled library to load into ROOT or as a stand alone application by adding some include statements for header files or some dressing code to any macro 3 1 General Remarks on ROOT macros If you have a number of lines which you were able to execute at the ROOT prompt they can be turned into a ROOT macro by giving them a name which corresponds to the file name without extension The general structure for a macro stored in file MacroName cxx is void MacroName lt TE your lines of CINT code The macro is executed by typing gt root MacroName cxx at the system prompt or it can be loaded into a ROOT session and then be executed by typing root 0 L MacroName cxx root 1 MacroName at the ROOT prompt Note that more than one macro can be loaded this way as each macro has a unique
22. e Code starting at line 93 illustrates how contour lines of two fit parameters of one and two c are produced The correlation of the two variables tau and off set is clearly visible Figure 7 2 x htemp Contours T Entries 170 W os y I 8 Mean 2 045 Y RMS 1 39 5 d Underflow 0 09 Overflow 0 o a a PEEFFEEEFEHTTTT T Tr TITTTTTTTTTTTTTTTTTIT e N tulirrrilirrrilirnilirilirrilini B AT AL LU Dn o a al x e a e a e a ar E e ES e io a Figure 7 2 Histogrammed input data with overlayed scaled fit function and one and 2 c contour lines from the likelihood fit 45 RN a oR WN n CHAPTER 9 ROOT IN PYTHON ROOT also offers an interface named PyRoot see http root cern ch drupal content pyroot to the PYTHON programming language PYTHON is used in a wide variety of application areas and one of the most used scripting languages today With its very high level data types with dynamic typing its intuitive object orientation and the clear and efficient syntax PYTHON is very suited to control even complicated analysis work flows With the help of PyROOT it becomes possible to combine the power of a scripting language with ROOT methods Introductory material to PYTHON is available from many sources in the Internet see e g There are additional very powerful PYTHON package
23. errors there exists a powerful class TGrapErrors with different types of constructors In the example here we use data from the file ExampleData txt in text format root 0 TGraphErrors gr new TGraphErrors ExampleData txt root 1 gr gt Draw AP You should see the output shown in Figure 2 2 Make sure the file ExampleData txt is available in the directory from which you started ROOT Inspect this file now with your favourate editor or use the command g iac less ExampleData txt to inspect the file you will see that the format is very sim UE o ple and easy to understand Lines begin 12 ning with are ignored very convenient to E add some comments on the type of data The data itself consist of lines with four 0 8 real numbers each representing the x and T y coordinates and their errors of each data ME l point You should quit 04 The argument of the method Draw AP 02E is important here It tells the TGraphPainter A A aee SE su ere AREA AN class to show the axes and to plot mark 15 2 2 5 ers at the x and y positions of the specified data points Note that this simple example TE D relies on the default settings of ROOT con Figure 2 2 Visualisation of data points with errors using the cerning the size of the canvas holding the class TGraphErrors plot the marker type and the line colours and thickness used and so on In a well written complete exampl
24. name in the ROOT name space Because many other macros may have been executed in the same shell before it is a good idea to reset all ROOT parameters at the beginning of a macro and define your preferred graphics options e g with the code fragment re initialise ROOT gROOT gt Reset re initialize ROOT gROOT gt SetStyle Plain set empty TStyle nicer on paper gStyle gt SetOptStat 111111 print statistics on plots 0 for no output gStyle gt SetOptFit 1111 print fit results on plot 0 for no ouput gStyle gt SetPalette 1 set nicer colors than default gStyle gt SetOptTitle 0 suppress title box 13 RNA coo IococU H5 wn A w Q2 Qo Q2 C29 Qo Y h2 b2 h2 h2 h2 h2 bh2 h2 hl2r2 A ppp O0 4 Qtr DUAN DOTBRWNRrFTMOAN DUP 0t oc 3 ROOT Macros Next you should create a canvas for graphical output with size subdivisions and format suitable to your needs see documentation of class TCanvas create a canvas specify position and size in pixels TCanvas ci ci Title 0 0 400 300 ci Divide 2 2 set subdivisions called pads ci cd 1 change to pad 1 of canvas cl These parts of a well written macro are pretty standard and you should remember to include pieces of code like in the examples above to make sure your output always comes out as you had intended Below in sectio some more code fragments will be shown allowing you to use the system comp
25. np sqrt emat i i np sqrt emat j j print gt plot result using matplotlib plt figure plt errorbar ax ay yerr ey fmt 0 label data the data x np arange ax 0 ax nPoints 1 abs ax nPoints 1 ax 0 100 y fitfunc x npar finalPar function at best fit point plt title Fit Result plt grid plt plot x y label fit function plt legend 1oc 0 plt show file fitting example py 52 CONCLUDING REMARKS This is the end of our guided tour through ROOT for beginners 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 A very useful way for you to continue exploring ROOT is to study the examples in the sub directory tutorials of any ROOT installation There are some powerful additions to ROOT e g packages named RooFit and RooStats providing a frame work for model building fitting and statistical analysis The ROOT class TMVA offers multi variate analysis tools including an artificial neural network and many other advanced methods for classification problems The remarkable ability of ROOT to handle large data volumes was already mentioned in this guide implemented through the class TTree But there is still much more for you to explore End of this guide but hopefully not
26. of your interaction with ROOT 53 APPENDIX OA ROOFILAB A 1 Root based tool for fitting RooFiLab Although simple in principle the fomulation of a problem in C and the complex environment of the ROOT framework pose a relativly high hurdle to overcome for the beginner A simplification and extension of avialable standard methods for function fitting to one dimesional distributions is the package RooFiLab Root Fits for Laboratory courses Based on ROOT this program developed at KIT Karlsruhe Institute of Technology URL http www ekp physik uni Karlsruhe de quast RooFiLab offers an easy to use structured graphical user interface and an ASCIT input format for typical use cases in student laboratory courses Correlated erros on both the x and y coordinate are also supported In the most general case covariance matrices of the x and y coordinates can be specified There is also a simplified possibility for special cases of fully correlated absolute or relative errors on the measurements An example fit is shown in Figure A 1 Title of Graphic 0 12 0 1 0 08 0 06 Y Axis 0 04 0 02 ce m NI e gt al o x o a o Figure A 1 Example of a straight line fit with independent and correlated systematic errors on both the x and y directions High flexibility in the definition of the model is achieved by direct usage of the ROOT interpreter which has been exten
27. open the TFile TFile in file new TFile my_rootfile root Get the Histogram out THiF h THiF in file Get 0bjectChecked my histogram THiF Draw it h gt DrawClone file read_from_file cxx Please note that the order of opening files for write access and creating objects determines whether the ob jects are stored or not You can avoid this behaviour by using the Write function as shown in the previous example Although you could access an object within a file also with the Get function and a dynamic type cast it is advisable to use GetObjectChecked 6 2 N tuples in ROOT 6 2 1 Storing simple N tuples Up to now we have seen how to manipulate input read from ASCII files ROOT offers the possibility to do much better than that with its own n tuple classes Among the many advantages provided by these classes one could cite Optimised disk I O Possibility to store many n tuple rows Millions e Write the n tuples in ROOT files e Interactive inspection with TBrowser e Store not only numbers but also objects in the columns In this section we will discuss briefly the TNtuple class which is a simplified version of the TTree class A ROOT TNtuple object can store rows of float entries 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 con
28. parameters e fixing of start values and Fit by Eye e execution of the fit eventually iteratively by fixing some of the free parameters e options for graphical output IMPORT DATA SPECIFY INITIAL VALUES Selection Graph graph1 Graph 1 y Function tem x b Specify initial Values m 0 0102124 E b 0 001 00647 m Information on the Fit Function Chi 2 10 7874 Degrees of freedom 11 RUN ROOT FIT FINISH ANALYSIS Figure A 2 The grafical user interface of RooFiLab During execution ROOT functionality is also available Of particular importance are procedures for interactive manilulations of the output graphcis and their export As usual the context menu is opened by right klicking of the components of the graph or via the Toolbar at the top of the graphics window In addition to interactive usage of the controls of the graphical interface fits can also be executed automatically by specification of control options in the input file definig the data inputs After an interactive fit options can thus be archived in the input file and then be used for repeated automated fits A 2 Examples with RooFiLab The following subsections show simple examples illustrating the usage of RooFiLab and may serve as the basis for own applications http www ekp physik uni karlsruhe de quast VMroot 56 A 2 Examples with RooFiLab A 2 1 Straight line fit with correlated erros i
29. useful for example to represent the errors of a theoretical prediction 4 2 Polar Graphs With ROOT you can profit from rather advanced plotting routines like the ones implemented in the TPolarGraph a class to draw graphs in polar coordinates It is very easy to use as you see in the example macro and the resulting plot Builds a polar graph in a square Canvas void macro3 double rmin 0 double rmax TMath Pi 6 const int npoints 300 Double_t r npoints Double_t theta npoints for Int t ipt 0 ipt lt npoints ipt r ipt ipt rmax rmin npoints 1 rmin theta ipt TMath Sin r ipt j TCanvas c new TCanvas myCanvas myCanvas 600 600 TGraphPolar grP1 npoints r theta grP1 SetTitle A Fan grPi SetLineWidth 3 grP1 SetLineColor 2 grP1 DrawClone AOL file macro3 cxx 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 Some PYTHON variants of this macro are shown and discussed in Chapter 8 20 OMAN DAK WN HE o 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 4 3 2D Graphs Figure 4 1 The graph of a fan obtained with ROOT 4 3 2D Graphs On some occasions it might be useful to plot some quantities versus two variables therefore creating a bi dimensional graph Of course ROOT can help you in this task with the TGraph2DError
30. 1 new TCanvas f2 Draw Surfi dte gt Draw PO Same Make the x and y projections TCanvas c p new TCanvas ProjCan The Projections 1000 400 c p Divide 2 1 c_p gt cd 1 dte gt Project x gt Draw c_p gt cd 2 dte gt Project y gt Draw 22 file macro4 cxx Line 3 This sets the palette colour code to a much nicer one than the default Comment this line to give it a try Line 4 sets a style type without fill color and shadows for pads Looks much nicer on paper than the default setting Line 9 The instance of the random generator You can then draw out of this instance random numbers distributed according to different probability density functions like the Uniform one at lines 25 26 See the on line documentation to appreciate the full power of this ROOT feature Line 10 You are already familiar with the TF1 class This is its two dimensional correspondent At line 21 two random numbers distributed according to the TF2 formula are drawn with the method TF2 GetRandom2 doubleg a double amp b Line 26 28 Fitting a 2 dimensional function just works like in the one dimensional case i e initialisation of parameters and calling of the Fit method Line 31 The Surf option draws the TF2 objects but also bi dimensional histograms as coloured surfaces with a wire frame on three dimensional canvases Line 34 39 Here you learn how to create a canvas partition
31. 1111 gStyle gt SetStatX 89 gStyle gt SetStatY 89 gStyle SetStatBorderSize 0 TF1 parabola parabola O 1 x 2 x 2 0 20 format line amp parabola kBlue 2 TF1 gaussian gaussian O TMath Gaus x 11 21 0 20 format line amp gaussian kRed 2 TF1 gausppar gausppar the gausppar 0 20 6 double a 15 double b 1 2 double c 03 double norm 4 double mean 7 double sigma 1 gausppar SetParameters norm mean sigma a b c gausppar SetParNames Norm Mean Sigma a b c format line amp gausppar kBlue 1 TH1F histo histo Signal plus background X vals Y Vals 50 0 20 histo SetMarkerStyle 8 Fake the data for int i 1 i lt 5000 i histo Fill gausppar GetRandom Reset the parameters before the fit and set by eye a peak at 6 with an area of more or less 50 gausppar SetParameter 0 50 gausppar SetParameter 1 6 int npar gausppar GetNpar for int ipar 2 ipar lt npar ipar gausppar SetParameter ipar l perform fit histo Fit amp gausppar and retrieve fit results TVirtualFitter fit TVirtualFitter GetFitter get fit method fit PrintResults 2 0 print fit results get covariance Matrix an print it TMatrixD covMatrix new TMatrixD npar npar fit gt GetCovarianceMatrix covMatrix gt Print Set the values of the gaussian and parabola for int ipar 0 ipar lt 3 ipar gaussia
32. 4 35 45 44 0 53 60 Measured Points e A CU ROG RN ok qa a Ot Ol A oOrROrFRNMW ON FPOANOOKR WME w poe Pa j 6 8 10 lenght cm file macro2 input txt Reads the points from a file and produces a simple graph int macro2 gROOT gt SetStyle Plain TCanvas c new TCanvas c gt SetGrid 19 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 OMAN DAK WN EH el a es WOON OTK WN FO 4 Graphs TGraphErrors graph_expected macro2_input_expected txt lg lg 4 lg graph_expected SetTitle Measurement XYZ and Expectation lenght cm Arb c Units graph_expected SetFillColor kYellow graph expected DrawClone E3AL E3 draws the band TGraphErrors graph macro2_input txt lg lg lg graph SetMarkerStyle kCircle graph SetFillColor 0 graph DrawClone PESame Draw the Legend TLegend leg 1 7 3 9 Lab Lesson 2 leg SetFillColor 0 leg AddEntry amp graph expected Expected Points leg AddEntry amp graph Measured Points leg DrawClone Same c Print graph with band pdf return 0 file macro2 cxx Beyond looking at 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 The macro also shows us how to print a coloured band around a graph instead of error bars quite
33. CIT Karlsruhe Institute of Technology Institut f r Experimentelle Kernphysik A ROOT Guide For Students Fi http root cern ch Diving Into ROOT Abstract ROOT is an object oriented framework for data anal ysis Among its prominent features are an advanced graphical user interface for visualization and inter active data analysis and an interpreter for the C programming language which allows rapid prototyp ing of analysis code based on the C classes pro vided by ROOT Access to ROOT classes is also pos sible from the very versatile and popular scripting language PYTHON This introductory guide shows the main features ap plicable to typical problems of data analysis in stu dent labs input and plotting of data from measure ments and comparison with and fitting of analytical functions Although appearing to be quite a heavy gun for some of the simpler problems getting used to a tool like ROOT at this stage is an optimal prepa ration for the demanding tasks in state of the art scientific data analysis Authors Danilo PIPARO G nter QUAST Manuel ZEISE Version of July 27 2015 CHAPTER 1 MOTIVATION AND INTRODUCTION Welcome to data analysis Comparison of measurements to theoretical models is one of the standard tasks in experimental physics In the most simple case a model is just a function providing predictions of measured data Very often the model depends on parame
34. Draw draw the interference pattern for a grid with n slits file slits cxx The example first asks for user input namely the ratio of slit width over slit dis nslit tance and the number of slits After en tering this information you should see the graphical output as is shown in Figure 2 1 below 3 5 e This is a more complicated example than the ones we have seen before so spend some time analysing it carefully you should have understood it before continuing Let us go through in de tail 2 5 1 5 A 0 5 Lines 6 19 define the necessary functions d 2 9 2 a in C code split into three separate func tions as suggested by the problem consid ered The full interference pattern is given by the product of a function depending on the ratio of the width and distance of the slits and a second one depending on the number of slits 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 The main program starts in line 17 with the definition of a function slits of type void After asking for user input a ROOT function is defined using the C type function given in the beginning We can now use all methods of the TF1 class to control the behaviour of our function nice isn t it Tf you like you can easily extend the e
35. 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 4 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 4 Correlations between the variables are quantified by the methods Double_T GetCovariance and Double_t GetCorrelationFactor 26 2500 2000 1500 1000 500 1 1 2 3 4 5 Guassian Vals Exp Vals 5 3 Two dimensional Histograms y 0 5 4 3 2 14 0 12 3 4 5 Guassian Vals 2500 2000 1500 1000 500 Figure 5 3 Different ways of representing bi dimensional histograms 35000 30000 25000 20000 15000 10000 5000 Spore Guassian Vals 6 96 6 94 6 92 6 88 6 86 6 84 6 82 6 8 Guassian Vals Figure 5 4 The projections and profiles of bi dimensional histograms 40000 35000 30000 25000 20000 15000 10000 5000 0 06 0 04 0 02 0 04 8 9 10 Exp Vals 27 coo IococU wn A Bee RP ee ee Nook wnrr o 10 Ct KR WN He CHAPTER FILE I O 6 1 Storing ROOT Objects ROOT offers the possibility to write t
36. ad 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 TFile in_file conductivity_experiment root TNtuplex my_tuple TNtuple in_file Get0bjectChecked cond_data TNtuple lt 4 gt H float pot cur temp pres float row content cout lt lt Potential tCurrent tTemperature tPressure n for int irow 0 irow lt my_tuple gt GetEntries irow my_tuple GetEntry irow row_content my_tuple gt GetArgs pot row_content 0 31 19 20 21 22 23 24 25 ZX O 0 WN FH oo 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 6 File I O cur row content 1 temp row_content 2 pres row_content 3 cout lt lt pot lt lt Xt lt lt cur lt lt Xt lt lt temp lt lt Xt lt lt pres lt lt endl file read_ntuple_from_file cxx The macro shows the easiest way of accessing the content of a n tuple after loading the n tuple its branches are assigned to variables and GetEntry long automatically fills them with the content for a specific row 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 6 2 3 Storing Arbitrary N tuples It is also possible to write n tuples of arbitrary type
37. ail e Line 11 the name of the principal function it plays the role of the main function in compiled programs in the macro file It has to be the same as the file name without extension e Line 22 23 instance of the TGraphErrors class The constructor takes the number of points and the pointers to the arrays of x values y values x errors in this case none represented by the NULL pointer and y errors The second line defines in one shot the title of the graph and the titles of the two axes separated by a e Line 26 29 the first line refers to the style of the plot set as Plain This is done through a manipulation of the global variable gSystem ROOT global variables begin always with g The following three lines are rather intuitive right To understand better the enumerators for colours and styles see the reference for the TColor and TMarker classes e Line 32 the canvas object that will host the drawn objects The memory leak is intentional to make the object existing also out of the macrol scope e Line 35 the method DrawClone draws a clone of the object on the canvas It has to be a clone to survive after the scope of macroi and be displayed on screen after the end of the macro execution The string option APE stands for Aimposes the drawing of the Axes P imposes the drawing of the graphs markers E imposes the drawing of the graphs markers errors e Line 38 define a mathem
38. anual increase may help in certain situations Please note that the caching mechanism can cover only one TTree object per TFile object e You can select the branches to be covered by the caching algorithm with AddBranchToCache and deactivate unneeded branches with SetBranchStatus This mechanism can result in a significant speed up for simple operations on trees with many branches e You can measure the performance easily with TTreePerfStats The ROOT documentation on this class also includes an introductory example For example TTreePerfStats can show you that it is beneficial to store meta data and payload data separately i e write the meta data tree in a bulk to a file at the end of your job instead of writing both trees interleaved 38 coo IococU H5 WN HF hop o CHAPTER FUNCTIONS AND PARAMETER ESTIMATION After going through the previous chapters you already know how to use mathematical functions class TF1 and you got some insight into the graph TGraphErrors and histogram classes TH1F for data visualisation 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 For graphs and histograms ROOT offers an easy to use interface to perform fits either the fit panel of the graphical interface or the Fit method The class TVirtualFitter allows access to the detailed results and can also be used for more gen
39. appens if you increase the number of entries per histogram by a factor of ten Why 7 3 Fitting in General In the examples above we used the simplified fitting interface of ROOT and the default minimisation functions In general however fitting tasks often require special user defined minimisation functions This is the case when data cannot be represented as one or two dimensional histograms or graphs when errors are correlated and covariance matrices must be taken into account or when external constrains on some of the fit parameters exist The default minimiser in ROOT is MINUIT a package that has been in use since decades It offers several minimisation methods and a large number of features accessible through the class TMinuit A more modern generalised interface allowing to use other minimises also exists see class TVirtualFitter but still lacks some of the original features offered by TMinuit The macro below provides a rather general example Data is read from a file stored in an n tuple for repeated access and an extended negative log likelihood function is calculated and minimised with respect to the fit parameters Example of a negative log likelihood fit unbinned based on the ROOT classes TVirtualFitter and TMinuit global variables for this macro TF1 PDF probability density function for the fit TNtuple x inpdata n tuple to hold input data int NFitPar 2 specify number of fit parameters
40. atical function There are several ways to accomplish this but in this case the constructor accepts the name of the function the formula and the function range e Line 40 maquillage Try to give a look to the line styles at your disposal visiting the documentation of the TLine class e Line 42 fits the f function to the graph observe that the pointer is passed It is more interesting to look at the output on the screen to see the parameters values and other crucial information that we will learn to read at the end of this guide 15 3 ROOT Macros e Line 43 again draws the clone of the object on the canvas The Same option avoids the cancellation of the already drawn objects in our case the graph e Line 46 51 completes the plot with a legend represented by a TLegend instance 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 You can add to the legend the objects previously drawn or not drawn through the addEntry method Observe how the legend is drawn at the end looks familiar now right e Line 54 56 defines an arrow with a triangle on the right hand side a thickness of 2 and draws it e Line 59 61 interpret a Latex string which hast its lower left corner located in the specified coordinate The splitline construct allows to store multiple lines in the same TLatex obje
41. atistical data analysis and the whole Chapter 5 will be dedicated to this 2 6 Interactive ROOT Look at one of your plots again and move the mouse across 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 When the mouse is over an object a right click opens a pull down menu displaying in the top line the name of the ROOT class you are dealing with e g TCanvas for the display window itself TFrame for the frame of the plot TAxis for the axes TPaveText for the plot name 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 The menu items allow direct access to the members of the various classes and you can even modify them e g change colour and size of the axis ticks or labels the function lines marker types and so on Try it You will probably like the following in the output produced by the example Name Fix Value Min Set Range Max perat slits cxx right click on the function line 0 B 022 018 amp E 0 22 E p 3 MEG gag and select SetLineAttributes then left Sls CM 55 4 3 click on Set Parameters This gives ac MULUS cess to a panel allowing you to interactively E change the parameters of the function as _Beset emp ok Cancel shown in Figure 2 4 Change the slit width or go f
42. by using ROOT s TBranch class This is especially important as TNtuple Fill accepts only floats The following macro creates the ame n tuple as before but the branches are booked directly The Fill function then fills the current values of the connected variables to the tree Fill an n tuple and write it to a file simulating measurement of conductivity of a material in different conditions of pressure and temperature using branches void write ntuple to file advanced std string outputFileName 4 conductivity experiment root unsigned int numDataPoints 10000 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 Potential amp pot Potential F cond data Branch Current amp cur Current F cond data Branch Temperature amp temp Temperature F cond data Branch Pressure amp pres Pressure F for int i 0 i lt numDataPoints i Fill it randomly to fake the acquired data pot gRandom Uniform 0 10 gRandom Gaus 1 0 01 temp gRandom Uniform 250 350 gRandom gt Gaus 0 0 3 pres gRandom gt Uniform 0 5 1 5 gRandom gt Gaus 1 0 02 cur pot 10 0 05 temp 300 0 2 pres 1 gRandom gt Gaus 1 0 01 write to ntuple cond data Fill Open a file save the ntuple and close the file TFile ofile outputFileName
43. c_str RECREATE cond_data Write ofile Close file write_ntuple_to_file_advanced cxx The Branch function requires a pointer to a variable and a definition of the variable type Table lists some of the possible values Please note that ROOT is not checking the input and mistakes are likely to result in serious problems This holds especially if values are read as another type than they have been written e g when storing a variable as float and reading it as double 32 or IN A eo Io0 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 6 2 N tuples in ROOT Table 6 1 List of variable types that can be used to define the type of a branch in ROOT type size C identifier signed integer 22 n m 64 bit long L toneles 32 bit unsigned int i 64 bit unsigned long l floating point PA sl pus 2 64 bit double D boolean bool O 6 2 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 ROOT thus kindly provides a helper class in the form of TChain Its usage is shown in the following macro which is very similar to the previous example The constructor of a TChain takes the name of the TTree or TNuple as an argument The files are added with the function Add fileName where one can also use wild cards as shown in the example Read several previously produced N Tuples and print on screen its
44. content you can easily create some files with the following statement for i in 0123 4 5 do root 1 x b q write ntuple to file cxx V conductivity experiment i 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 Add conductivity experiment root add files wildcards work define variables and assign them to the corresponding branches float pot cur temp pres my_tuple gt SetBranchAddress Potential amp pot my_tuple gt SetBranchAddress Current amp cur my_tuple gt SetBranchAddress Temperature amp temp my_tuple gt SetBranchAddress Pressure amp pres cout lt lt Potential tCurrent tTemperature tPressure n for size_t irow 0 irow lt in_chain GetEntries irow in_chain GetEntry irow loads all variables that have been connected to branches cout lt lt pot lt lt Xt lt lt cur lt lt Xt lt lt temp lt lt Xt lt lt pres lt lt endl file read_ntuple_with_chain cxx 6 2 5 For the advanced user Processing trees with a selector script Another very general and powerful way of processing a TChain is provided via the method TChain Process 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 A template f
45. ct e Line 62 save the canvas as image The format is automatically inferred from the file extension it could have been eps gif Let s give a look to the obtained plot in figure 3 1 Beautiful outcome for such a small bunch of lines isn t it Measurement XYZ o E 60 Lab Lesson 1 e Exp Points lt 50 gt Th Law a st 40 P d 30 20 a 10 Po i Maximum F ee Deviation E e L L L L L L L L L L L L L L 0 2 4 6 8 10 lenght cm Figure 3 1 Your first plot with data points A version of the same macro in PvTHON is available in the file macroi py you may want to open it in the editor and have a look at the differences right now please consult the introductory sections of Chapter 8 first This example shows how easy it is to change a ROOT macro from C to PYTHON 3 3 Summary of Visual effects 3 3 1 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 The complete summary of colours is represented by the ROOT colour wheel shown in appendix in figure To know more about the full story refer to the online documentation of TColor ROOT provides an analogue of the colour wheel for the graphics markers Select the most suited symbols for your plot see pum among dots triangles crosses or stars An alternative set of names for the markers is summarised in
46. ction and the signal and background components at the best fit values v C 2 S SignalPeak over d E d background Norm 57 83 8 01 200 l Mean 7 01 0 14 LTN Sigma 0 9238 0 1652 E a 200 6 5 4 E b 16 73 1 03 1 LL 50r 0 4438 0 0461 100 50 E 1 FM MS S to Ua eg 8 16 72 74 716 718 720 X vals Figure 7 1 Function fit to pseudo data 7 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 x method and a method called binned log likelihood fit both available in ROOT As a very simple yet powerful quantity to check the quality of the fit results we construct for each pseudo data set the so called pull the difference of the estimated and the true value of a parameter normalised to the estimated error on the parameter pestim Ptrue 0p If everything is OK the distribution of the pull values is a standard normal distribution i e a Gaussian distribution centred around zero with a standard deviation of one The macro performs a rather big number of toy experiments where a histogram is repeatedly filled with Gaussian distributed numbers representing the pseudo data in this example Each time a fit is performed according to the selected method and the pull is calculated and filled into a histogram Here is the code Toy Monte Carlo example check pull distribution to co
47. d measurements Averaging correlated measurements formally corresponds to a fit of a constant The measurements in this example are the individual measurements of the mass of the Z Boson at the electron positron collider LEP at CERN The common error of 1 7 MeV results from uncertainties in the centre of mass energy of the accelerator The line systerrors 0 0 0017 abs abs specifies this common aboslute error on each measurement Mesurements of Z Mass by AELPH DELPHI L3 and OPAL graphics options markersettings 1 5 4 24 13 functionsettings 3 grid y logscale 0 savegraphic roofilab eps saverfl data rfl plot lables title averaging measurements xaxis n yaxis Mass of Z boson graphlegend Z mass measurements bottom right functionlegend average Z mass bottom right fit control 4 fit m m average fit initialvalues 91 2 dofit true staterrors y control command systerrors 0 0 0017 abs abs the data LEP electroweak working group CERN 2000 1 91 1893 0 0031 2 91 1863 0 0028 3 91 1894 0 0030 4 91 1853 0 0029 58 A 2 Examples with RooFiLab A 2 3 Fit of a polynomyal to data with Poisson errors This example show the fit of a fourth order polynomial to data with uncorrelated Poissonian errors i e erros given by the square root of the data points Although the errors are non Gaussion in this case a x fit of
48. d used a for control structure Note that there are some subtle differences between CINT and the standard C language You do not need the at the end of line in interactive mode try the difference e g using the command at line root 6 2 2 ROOT as Function Plotter Using one of ROOT s powerful classes here TF1 will allow us to display a function of one variable x Try the following root 11 TFi fi new TFi fi sin x x 0 10 root 12 f1 gt Draw f1 isa pointer to 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 real define the range of the variable x The Draw method here without any parameters displays the function in a window which should pop up after you typed the above two lines Note again differences between CIN T and C you could have omitted the at the end of lines of CINT woud have accepted the to access the method Draw However it is best to stick to standard C syntax and avoid CINT specific code as will become clear in a moment A slightly extended version of this example is the definition of a function with parameters called 0 1 and so on in ROOT formula syntax We now need a way to assign values to these parameters this is achieved with the meth
49. ded to use named parameters instead of parameter numbers In addition more complex models can be implemented as C or C functions wich are compiled and linked at run time The elements of the grafical user interface see Figure A 2 and control via the input file are described in the manual file RooFiLab pdf in the subdirectory RooFiLab doc in German language A brief overview is given here 55 A RooFiLab A 1 1 Installation RooFiLab is availalbe fully installed along with ROOT in a virtual machinq based on the Ubuntu distribution The compressed disk image is most easily imported into the freely available virtualisation tool VirtualBox for the most common Linux distributions for Windows versions XP and later and for Macintosh operating systems The program code of RooFiLab is distributed from the URL given above as a compressed archive RooFiLab tar gz After unpacking the installation under Linux proceeds by executing make the file Makefile contains all necces sary instructions A ROOT installation must be present and initialized i e the environment variable PATH must contain the path to the ROOT executable and LD LIBRARY PATH must point to the ROOT libraries A 1 2 Usage of RooFiLab RooFiLab offers two windows one is used for control the other is for graphics output The control window as depicted in FigurdA 2 is separated into four Shutters offering the following actions e data input and definition of functions and
50. ditions of pressure and temperature void write ntuple to file Initialise the TNtuple TNtuple cond data cond data Example N Tuple Potential Current Temperature Pressure Fill it randomly to fake the acquired data float pot cur temp pres for int i 0 i lt 10000 i pot gRandom gt Uniform 0 10 get voltage temp gRandom Uniform 250 350 get temperature pres gRandom gt Uniform 0 5 1 5 get pressure cur pot 10 0 05 temp 300 0 2 pres 1 calculate current add some random smearing measurement errors pot gRandom gt Gaus 1 0 01 1 error on voltage temp gRandom Gaus 0 0 3 0 3 absolute error on temperature pres gRandom gt Gaus 1 0 02 1 error on pressure curs gRandom gt Gaus 1 0 01 1 error on current 30 25 26 27 28 29 30 31 32 33 coo I1ococ cUH85ct 10 11 12 13 14 15 16 17 18 6 2 N tuples in ROOT write to ntuple cond data Fill pot cur temp pres Open a file save the ntuple and close the file TFile ofile conductivity experiment root RECREATE cond_data Write ofile Close file write_ntuple_to_file cxx This data written to this example n tuple represents in the statistical sense three independent variables Poten tial or Voltage Pressure and Temperature and one variable Current which depends on the the others according to very simp
51. e all this would need to be specified explicitly in order to obtain nice and reproducible results 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 2 5 Histograms in ROOT Frequency distributions in ROOT are handled by a set of classes derived from the histogram class TH1 in our case TH1F The letter F stands for float meaning that the data type float is used to store the entries in one histogram bin O0 4 Q2 N nb root 0 TF1 efunc efunc exp O 1 x 0 5 root 1 efunc SetParameter 0 1 root 2 efunc SetParameter 1 1 root 3 THiF h new THiF h example histogram 100 0 5 root 4 for int i 0 i lt 1000 i h gt Fill efunc GetRandom root 5 h gt Draw O0 4 Q2 N n 2 6 Interactive ROOT The first three lines of this example define a function an exponential in this case and set its parameters In Line 4 a histogram is instantiated with a name a title a certain number of 100 bins i e equidistant equally sized intervals in the range from 0 to 5 We use yet another new feature of ROOT to fill this histogram with data example histogram MEE namely pseudo random numbers generated E Mean 0 9719 with the method TF1 GetRandom which in S AMS aser turn uses an instance of the ROOT class E TRandom created when ROOT i
52. e computer screen but rather ugly on paper Tf you want to use ROOT graphs in documents you should change some of the default options 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 gt SetStyle MyStyle to make this new style definition the default one As an example have a look in the file rootlogon C coming with this tutorial There is also a possibility to set many ROOT features in particular those closely related to the operating and window system like e g the fonts to be used where to find start up files or where to store a file containing the command history and many others The file searched for at ROOT start up is called rootrc and must 10 2 7 ROOT Beginners FAQ reside in the user s home directory reading and interpeting this file is handled by the ROOT class TEnv see its documentation if you need such rather advanced features 2 7 3 ROOT command history Every command typed at the ROOT prompt is stored in a file root_hist in your home directory ROOT uses this file to allow for navigation in the command history with the up arrow and down arrow keys It is also convenient to extract successful ROOT commands with the help of a text editor for use in your own macros 2 7 4 ROOT Global Variables All global variables in ROOT begin with a small g Some of them were already implicitly introduced for exa
53. eral tasks with user defined minimisation functions Very often it is necessary to study the statistical properties of analysis procedures 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 If the simulation only deals with the final distributions observed in data and does not perform a full simulation of the underlying physics and the experimental apparatus the name Toy Monte Carlo is frequently used Since the true values of all parameters are known in the pseudo data the differences between the parameter estimates from the analysis procedure w r t the true values can be determined and it is also possible to check that the analysis procedure provides correct error estimates 7 1 Fitting Functions to Pseudo Data In the example below a pseudo data set is produced and a model fitted to it ROOT offers various fit methods all inheriting from a virtual class TVirtualFitter The default fitter in ROOT is MINUIT a classical fitting package originally implemented in the FORTRAN programming language Recently a C version MINUIT2 has been added and the new package FUMILI All of these methods determine the best fit parameters their errors and correlations by minimising a x or a negative log likelihood function A pointer to the active fitting method is accessible via an instance of class TVirtualFitter Methods of th
54. ert tBegin Convert float fNumber fEvents tNow Convert tBegin Convert void MySelector Terminate The Terminate function is the last function to be called during a query It always runs on the client it can be used to present the results graphically or save the results to file finally store all output TFile hfile MySelector_Result root RECREATE MuonResults fOutput Write Example to retrieve output from output list h_resistance dynamic_cast lt TH1F gt fOutput gt FindObject resistance TCanvas c_result cresult Resistance 100 100 300 300 h_resistance gt Draw c_result SaveAs ResistanceDistribution png tNow Set printf End of dob sm ys tNow Print file MySelector C 6 2 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 modern computers with multi core CPUs or hyper threading enabled this allows a much faster turnaround of analyses since all the available CPU power is used On distributed systems a PROOF server and worker nodes have to be set up
55. g 2 dim plot of variables xi and xj Draw xi xj fill existing histogram from ntuple Project const char hname const char varexp const char selection global pointers gStyle and gSystem as instances of classes TStyle and TSystem show statistics box gStyle gt SetOptStat 11 1 show fit parameters in statistics box gStyle gt SetO0ptFit 11 1 suppress title boxes on graphs and histograms gStyle gt SetOptTitle 0 for animations add pause in milliseconds gSystem gt Sleep UInt_t t Fitting set default fitter e g name Minuit TVirtualFitter SetDefaultFitter const char name create Fitter instance TVirtualFitter Fitter 0 Int_t maxpar 25 define a parameter Int_t SetParameter Int t ipar const char parname Double t value Double_t verr Double t vlow Double t vhigh set function to be minimized SetFCN void Int t Double t Double t f Double t Int t fcn fix a parameter FixParameter Int t ipar release parameter ReleaseParameter Int t ipar get pointer to active fitter instance static TVirtualFitter GetFitter interaction with fitter Int_t ExecuteCommand const char command Double t args Int t nargs example start fit with MINUIT double arglist 2 5000 0 01 ExecuteCommand MINIMIZE arglist 2 example error evaluation MINUIT MINOS ExecuteCommand MINOS arglist 0 get pointer to covariance matrix Double_t GetCovarianceMatrix const interaction with MINUIT via global pointer gMinuit of class set De
56. g via PROOF or PROOF lite is enabled as will be explained below A simple example of a selector class is shown in the macro MySelector C The example is executed with the following sequence of commands gt TChain ch new TChain cond data My Chain for Example N Tuple gt ch gt Add conductivity_experiment root gt ch gt Process MySelector Ct As usual the appended to the name of the macro to be executed initiates the compilation of the MySelector C with the system compiler in order to improve performance The code in MySelector C shown in the listing below books some histograms in SlaveBegin and adds them to the instance fOutput which is of the class TList The final processing in Terminate allows to access histograms and store display or save them as pictures This is shown in the example via the TList fOutput See the commented listing below for more details most of the text is actually comments generated automatically by TTree MakeSelector define MySelector cxx The class definition in MySelector h has been generated automatically by the ROOT utility TTree MakeSelector This class is derived from the ROOT class TSelector For more information on the TSelector framework see ROOTSYS README README SELECTOR or the ROOT User Manual The following methods are defined in this file if Begin called every time a loop on the tree starts a convenient place to crea
57. he instances of all the classes inheriting from the class TObject basically all classes in ROOT on disk into what is referred to as ROOT file a file created by the TFile class One says that the object is made persistent by storing it on disk When reading the file back the object can be restored to memory We can explore this functionality with histograms and two simple macros void write_to_file Istance of our histogram THIF h my_histogram My Title X of entries 100 5 5 Let s fill it randomly h FillRandom gaus Let s open a TFile TFile out_file my_rootfile root RECREATE Write the histogram in the file h Write Close the file out_file Close file write_to_file cxx The RECREATE option forces ROOT to create a new file even if a file with the same name exists on disk Now you may use the CINT command line to access information in the file and draw the previously written histogram gt gt gt root my rootfile root root 0 Attaching file my rootfile root as _fileO root 1 _file0 1s TFilexx my rootfile root TFilex my_rootfile root KEY THIF my_histogram l My Title root 2 my_histogram Draw Alternatively you can use a simple macro to carry out the job 29 coo o 1Iococ ctt hop Nr o OCOAN Dork wn eH NNNNNRP PRP BRP RP Re RP RP ps H Q0 N00 qt AN DTK WN FH O 6 File I O void read from file Let s
58. he query When running with PROOF Begin is only called on the client The tree argument is deprecated on PROOF 0 is passed TString option Get ption some time measurement tBegin Set printf Begin of Job Wy tBegin Print void MySelector SlaveBegin TTree xtreex The SlaveBegin function is called after the Begin function When running with PROOF SlaveBegin is called on each slave server The tree argument is deprecated on PROOF 0 is passed TString option Get ption book some histograms h_pot new TH1F pot potential 100 0 5 10 5 h_cur new THiF cur current 100 0 1 1 5 h_temp new THiF temp temperature 100 200 400 h_pres new THiF pres pressure 100 0 2 h resistance new THiF resistance resistance 100 5 15 add all booked histograms to output list only really needed for PROOF f utput AddAll gDirectory GetList Bool_t MySelector Process Long64_t entry The Process function is called for each entry in the tree or possibly keyed object in the case of PROOF to be processed The entry argument specifies which entry in the currently loaded tree is to be processed It can be passed to either MySelector GetEntry or TBranch GetEntry to read either all or the required parts of the data When processing keyed objects with PROOF the object is already loaded a
59. id f e Lines 11 29 definition of function to be minimised the parameter list number of parameters eventually analytically calculated derivatives w r t the parameters the return value of the function the array of parameters and a control flag is fixed as it is expected by the minimisation package This function is repeatedly called by the minimisation package with different values of the function parameters e Lines 35 63 initialisation of the fit definition of a probability density function as a TF1 creation and filling of an n tuple containing the data read from a file and the definition of the fit parameters and their initial values and ranges The minimiser is instantiated in lines 48 and 49 e Lines 66 68 execute the fit first a general minimisation and then an error analysis using the MINOS method e Lines 70 106 retrieval of fit results after completion of the fit this part needs access to the data and serves for a comparison of the fit result with the data here we show the fitted function on top of a histogram of the input data Note that the PDF of a likelihood fit needs to be scaled to take into account the bin width of the histogram e Line 63 91 The function printFit illustrates how to access the best fit values of the parameters and their errors and correlations from an object of TMinuit Here they are written to standard output it is easy to redirect this into a file or some other data structure if required
60. iler to compile macros for more efficient execution or turn macros into stand alone applications linked against the ROOT libraries 3 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 To run this macro simply type in the shell gt root macrol cxx The code is build around the ROOT class TGraphErrors which was already introduced previously Have a look at it in the class reference guide where you will also find further examples 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 For the moment ignore the commented include statements for header files they will only become important at the end section 3 4 xxx Builds a graph with errors displays it and saves it as image x first include some header files within CINT these will be ignored include TCanvas h include TROOT h include TGraphErrors h include TF1 h include TLegend h include TArrow h include TLatex h 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 7
61. in 01 dividend gt Draw file macro6 cxx The plots that you will obtain are shown in 5 2 Some lines now need a bit of clarification e line 3 CINT as we know is also able to interpret more than one function per file In this case the function simply sets up some parameters to conveniently set the line of histograms e line 20 to 22 Some contracted C syntax for conditional statements is used to fill the histograms with different numbers of entries inside the loop e line 27 This is a crucial step for the sum and ratio of histograms to handle errors properly The method TH1 Sumw2 causes the squares of weights to be stored inside the histogram equivalent to the number of 25 OMAN DAK WN HEH Qo Q2 Q2 Qo Qo h2 b2 h2 NNN NNNNHP pp Ho C0 ND 0 t Oo QO 0tC CcobF2 c oo 1O00 0 0 tbt oc0o 5 Histograms entries per bin if weights of 1 are used This information is needed to correctly calculate the errors of each bin entry when the methods T H1 Add and TH1 Divide are applied e line 33 The sum of two histograms A weight can be assigned to the added histogram for example to comfortably switch to subtraction e line 44 The division of two histograms is rather straightforward e line 53 to 63 When you draw two quantities and their ratios it is much better if all the information is condensed in one single plot These lines provide a skeleton to perform this operation 5 3 Two dimensional Histograms
62. ion 1 Motivation and Introduction Quite often the data volume to be analyzed is large think of fine granular measurements accumulated with the aid of computers A usable tool therefore must contain easy to use and efficient methods for data handling In Quantum mechanics models typically only predict the probability density function pdf of mea surements 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 Measurements of this kind require means to generate and visualize frequency distributions so called histograms and stringent statistical treatment to extract the model parameters from purely statistical distributions Simulation of expected data is another important aspect in data analysis By repeated generation of pseudo data which are analysed in the same manner as intended for the real data analysis procedures can be validated or compared 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 1 1 Welcome to ROOT A powerful software framework addressing all of the above requirements is ROOT I an open source project coordinated by the European Centre for Particle Physics CERN in Geneva ROOT is very flexible and provides both a programming interface t
63. ion to it from ROOT import gStyle TCanvas TGraphErrors from array import array gStyle SetOptFit 111 superimpose fit results ci TCanvas ci Data 200 10 700 500 make nice Canvas ci SetGrid define some data points x array f 0 22 0 1 0 25 0 35 0 5 0 61 0 7 0 85 0 89 1 1 y array f 0 7 2 9 5 6 7 5 9 9 6 8 7 6 3 4 5 1 1 ey array f 8 7 6 5 4 5 6 7 8 ex array f 05 07 07 pra 05 06 07 08 05 nPoints len x and hand over to TGraphErros object gr TGraphErrors nPoints x y ex ey gr SetTitle TGraphErrors with Fit gr Draw AP gr Fit gaus ci Update request user action before ending and deleting graphics window raw input Press lt ret gt to end gt 1 file TGraphFit py 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 As another example let us revisit macro3 from Chapter 4 A straight forward PYTHON version relying on the ROOT class TMath usr bin env python the first line allows execution directly from the linux shell _ macro3 as python script 48 O OND C 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 O 0 JONA Nook 05 hl 8 1 PyROOT Author G Quast Oct 2013 dependencies PYTHON v2 7 pyroot last modified
64. is class allow to set initial values or allowed ranges for the fit parameters provide means for fixing and releasing of parameters and offer steering options for the numerical precision and most importantly allow to retrieve the status of the fit upon completion and the fit results The documentation of the class TVirtualFitter gives a list of all currently implemented methods The complexity level of the code below is intentionally a little higher than in the previous examples The graphical output of the macro is shown in Figure 7 1 Define and play with TFls void format line TAttLine line int col int sty line gt SetLineWidth 5 line gt SetLineColor col line gt SetLineStyle sty double the_gausppar double vars doubles pars return pars 0 TMath Gaus vars 0 pars 1 pars 2 pars 3 pars 4 vars 0 pars 5 vars 0 vars 0 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 39 12 13 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 7 Functions and Parameter Estimation int macro8 gROOT gt SetStyle Plain gStyle gt SetOptTitle 0 gStyle gt SetOptStat 0 gStyle gt SetOptFit
65. it in two sub pads and access them It is very handy to show multiple plots in the same window or image OMAN DA KWN HE Q2 Qo Qo h2 b2 h2 bh2 h2 b2 h2 h2 h2 NYP RP KR PRP RP RP RP RP MKH lc 0 qQ o 10O00t 4 Q2tl2r Oo Soda yaNRA O CHAPTER 5 HISTOGRAMS Histograms play a fundamental role in any type of Physics analysis not only displaying measurements but being a powerful form of data reduction ROOT presents many classes that represent histograms all inheriting from the TH1 class We will focus in this chapter on uni and bi dimensional histograms whose bin contents are represented by floating point numbers the TH1F and TH2F classes respectively 5 1 Your First Histogram Let s suppose that you want to measure the counts of a Geiger detector put in proximity of a radioactive source in a given time interval This would give you an idea of the activity of your source The count distribution in this case is a Poisson distribution Let s see how operatively you can fill and draw a histogram in the following example macro Create Fill and draw an Histogram which reproduces the counts of a scaler linked to a Geiger counter void macro5 THiF cnt_r_h new TH1F count_rate Count Rate N_ Counts occurencies 100 Number of Bins 0 5 Lower X Boundary 15 5 Upper X Boundary const float mean count 3 6 TRandom3 rndgen simulate the measurements for int imeas 0 imeas lt 400 imea
66. its cxx on disk and type root slits cxx in the shell This will start root and make it read the macro slit cxx i e all the lines in the file will be executed one after the other example to draw the interference pattern of light falling on a grid with n slits and ratio r of slit widht over distance between slits lt function code in C x double single double x double spar double const pi 4 atan 1 return pow sin pixpar 0 x 0 pispar 0 x 0 2 double nslitO double x double par double const pi 4 atan 1 return pow sin pispar 1 x 0 sin pi x 0 2 1 All ROOT classes start with the letter T 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 2 3 Controlling ROOT double nslit double x double par return single x par nslitO x par This is the main program x void slits float r ns request user input cout lt lt slit width g scanf 4f amp r cout lt lt of slits scanf 4f amp ns cout lt lt interference pattern for lt lt ns lt lt slits width distance lt lt r lt lt endl xdefine function and set options TF1 Fnslit new TFi Fnslit nslit 5 001 5 2 Fnslit gt SetNpx 500 set number of points to 500 Fnslit gt SetParameter 0 r set parameters as read in above Fnslit gt SetParameter 1 ns Fnslit gt
67. le laws and an additional Gaussian smearing This set of variables mimics a measurement of an electrical resistance while varying pressure and temperature Imagine your task now consists in finding the relations among the variables of course without knowing the code used to generate them You will see that the possibilities of the NTuple class enable you to perform this analysis task Open the ROOT file cond_data root written by the macro above in an interactive section and use a TBrowser to interactively inspect it root 0 new TBrowser You find the columns of your n tuple written as leafs 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 gt root conductivity experiment root Attaching file conductivity experiment root as _fileO root 0 cond data Draw Current Potential You just produced a correlation plot with one single line of code Try to extend the syntax typing for example root 1 cond data Draw Current Potential Temperature 270 What do you obtain Now try root 2 cond data Draw Current Potential Temperature It should have become clear from these examples how to navigate in such a multi dimensional space of variables and uncover relations between variables using n tuples 6 2 2 Reading N tuples For completeness you find here a small macro to re
68. ltaChi2 value for error determination gMinuit SetErrorDef float DeltaChi2 get coutour line as TGraph TGraph gMinuit gt Contour npoints int pari int par2 64 Contents 1 Motivation and Introduction 2 2 2 a 3 1 1 Welcome to ROQT i 233 xk Rok a RRA a 2 9 X Ee ea aa wR ER e O G 4 2 ROOT B stts 3 airis odiada DUE SSSR Non Roboter A E UR Y ue hbo e ELE UE 5 21 ROOT ascalenlatof 3 64 6 4 2 6 909 Yom yo MO eed ba Pam a a Wow oS 5 2 2 ROOT as Function Plotter lll e a a a a a a e e ea ns 6 2a Controlin ROO Bhe an ined a di AOS q aim TOS de ca 7 2 4 Plotting Measurements 2 lS o o 8 2 5 Histograms in ROOT 6595 ena Ec oe Ey RR a S e Ec Roe E E Born 8 2 6 Interactive ROOT recada ba Koa RR eU Eo GRRE ERREUR dedo dE E G 9 2 1 ROOT Beginners FAQ iiu eso cr b a AUR RURSUS WO XU e EUR E WR EUR m PR 10 2 7 1 ROOT type declarations for basic data types 2 2 0 002 220 0020 10 2 7 2 Configure ROOT at start up ees 10 2 1 3 ROOT command history 2 oo or oe tom e a Re 11 T O E E 11 B ROOF Macros 224 cb ebb ee co Se Eo aho e ba d ber eda dede E ok oboe ba d catus 13 3 1 General Remarks on ROOT macros e 13 3 2 A more complete example es 14 3 39 Summary ot Visual effects ea s nae A rw ROS ew ERY a E M Pho feeds 16 3 3 1 Colours and Graph Markers e 16 3 9 2 Arrows and Limest ssh 16 A pv TTC
69. mpare chi2 and binned log likelihood methods void pull int n_toys 10000 41 O OND C 10 11 12 13 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 51 52 53 54 55 56 57 58 59 60 61 62 7 Functions and Parameter Estimation 42 int n tot entries 100 int nbins 40 bool do_chi2 true gROOT gt SetStyle Plain TString method_prefix Log Likelihood if do_chi2 method_prefix chi 2 Create histo THiF h4 new TH1F method_prefix h4 method_prefix Random Gauss nbins 4 4 h4 gt SetMarkerStyle 21 h4 gt SetMarkerSize 0 8 h4 gt SetMarkerColor kRed Histogram for sigma and pull THiF sigma new TH1F method_prefix sigma method_prefix sigma from gaus gt fit 50 0 5 1 5 THiF pull new TH1iF method_prefix pull method_prefix pull from gaus fit 50 4 4 Make nice canvases TCanvas c0 new TCanvas method_prefix Gauss method_prefix Gauss 0 0 320 240 cO gt SetGrid Make nice canvases TCanvas c1 new TCanvas method_prefix Result method_prefix Sigma gt Distribution 0 300 600 400 c0 cd float sig mean for int i 0 icn toys i Reset histo contents h4 gt Reset Fill histo for int j 0 j lt n_tot_entries j h4 Fill gRandom Gaus perf
70. mple in session 2 7 2 The most important among them are presented in the following e gROOT the gROOT variable is the entry point to the ROOT system Technically it is an instance of the TROOT class 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 the gRandom variable is a variable that points to a random number generator instance of the type TRandom3 Such a variable is useful to access in every point of a program the same random number generator in order to achieve a good quality of the random sequence e By default ROOT creates a default style that can be accessed via the gStyle pointer This class includes functions to set some of the following object attributes Canvas Pad Histogram axis Lines Fill areas Text Markers Functions Histogram Statistics and Titles e An instance of a base class defining a generic interface to the underlying Operating System in our case TUnixSystem At this point you have already learnt quite a bit about some basic features of ROOT Please move on to become an expert 11 oR WN oN O CO 0 NM n CHAPTER 3 ROOT MACROS You know how other books go on and on about programming fundamentals and finally work up to building a complete working program Let s skip all that In this part of the guide we will
71. n SetParameter ipar gausppar GetParameter ipar parabola SetParameter ipar gausppar GetParameter ipar 3 histo GetYaxis gt SetRangeUser 0 250 histo DrawClone PE parabola DrawClone Same gaussian DrawClone Same TLatex latex 2 220 splitline Signal Peak over background latex DrawClone Same return 0 40 file macro8 cxx Sc N Aa 7 2 Toy Monte Carlo Experiments e Line 3 6 A simple function to ease the make up of lines Remember that the class TF1 inherits from TAttLine e Line 8 10 Definition of a customised function namely a Gaussian the signal plus a parabolic function the background e Line 13 18 Some maquillage for the Canvas In particular we want that the parameters of the fit appear very clearly and nicely on the plot e Line 26 31 define and initialise an instance of TF1 e Line 33 40 define and fill a histogram e Line 42 48 for convenience the same function as for the generation of the pseudo data is used in the fit hence we need to reset the function parameters This part of the code is very important for each fit procedure as it sets the initial values of the fit e Line 51 A very simple command well known by now fit the function to the histogram e Line 53 58 retrieve the output from the fit Here we simply print the fit result and access and print the covariance matrix of the parameters e Line 60 end plot the pseudo data the fitted fun
72. n x and y This RooFiLab input file contains several control lines and documents the available options Control lines are comment lines starting with followed by a keyword The control command dofit automated fit defined by the input data and the control options in the file straight line fit to data with errors in x and y incl simple correlations staterrors xy systerrors 0 02 0 04 rel rel fit m xtb m b roofilab fit initialvalues 0 015 0 command to execute fit dofit true show systematic erros as second error bar secondgraph syst title Fit to data with correlated errors graphlegend Data bottom right functionlegend Model bottom right xaxis X values yaxis Y values or f x markersettings 1 5 4 24 functionsettings 1 3 2 grid y logscale 0 savegraphic roofilab eps Eingabe der Daten values in up to four columns separated by whitespaces except for linebreaks or linefeeds x y ex ey 4 05 0 035 0 12 0 006 4 36 0 056 0 13 0 007 4 68 0 052 0 09 0 005 4 80 0 044 0 09 0 005 5 09 0 048 0 14 0 007 5 46 0 055 0 14 0 007 5 71 0 066 0 17 0 009 5 83 0 048 0 21 0 011 6 44 0 075 0 22 0 011 8 09 0 070 0 28 0 014 8 72 0 097 0 32 0 016 9 36 0 080 0 37 0 018 9 60 0 120 0 39 0 020 true triggers an 57 A RooFiLab A 2 2 Averaging correlate
73. nd is available via the fObject pointer This function should contain the body of the analysis It can contain simple or elaborate selection criteria run algorithms on the data of the event and typically fill histograms The processing can be stopped by calling Abort 7 Use fStatus to set the return value of TTree Process The return value is currently not used begin processing GetEntry entry 35 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 WE 6 File I O count number of entries events H HNumberOfEvents analsiys code comes here fill histograms h_pot gt Fill Potential h_cur gt Fill Current h_temp gt Fill Temperature h_pres gt Fill Pressure h_resistance gt Fill Potential Current return kTRUE kFALSE would abort processing void MySelector SlaveTerminate The SlaveTerminate function is called after all entries or objects have been processed When running with PROOF SlaveTerminate is called on each slave server some statistics at end of job printf n End of Slave Job 10 tNow Set tNow Print printf Number of Events i elapsed time Ai sec rate Ag evts sec n fNumberOfEvents tNow Conv
74. o use in own applications and a graphical user interface for interactive data analysis The purpose of this document is to serve as a beginners guide and provides extendable examples for your own use cases based on typical problems addressed in student labs 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 guide in form of a tutorial is intended to introduce you to the ROOT package in about 50 pages This goal will be accomplished using concrete examples according to the learning by doing principle Also because of this reason this guide cannot cover the complexity of the ROOT package Nevertheless once you feel confident with the concepts presented in the following chapters you will be able to appreciate the ROOT Users Guide 2 and navigate through the Class Reference 3 to find all the details you might be interested in You can even look at the code itself since ROOT is a free open source product Use these documents in parallel to this tutorial The ROOT Data Analysis Framework itself is written in and heavily relys on the programming language C and therefore some knowledge about C andC is required Eventually just profit from the immense available literature about C if you do not have any idea of what object oriented programming could be Recently an alternative and very powerful way to use and control ROOT cla
75. od SetParameter parameter number parameter value of class TF1 Here is an example root 13 TF1 f1 new TFi1 f2 O sin 1 x x 0 10 root 14 fi1 5SetParameter 0 1 root 15 fi gt SetParameter 1 1 root 16 fi gt Draw Of course this version shows the same results as the initial one Try playing with the parameters and plot the function again The class TF1 has a large number of very useful methods including integration and differentiation To make full use of this and other ROOT classes visit the documentation on the Internet under Formulae in ROOT are evaluated using the class TFormula so also look up the relevant class documentation for examples implemented functions and syntax On many systems this class reference guide is available locally and you should definitely download it to your own system to have it at you disposal whenever you need it To extend a little bit on the above example consider a more complex function you would like to define You can also do this using standard C or C code In many cases this is the only practical way as the ROOT formula interpreter has clear limitations concerning complexity and speed of evaluation Consider the example below which calculates and displays the interference pattern produced by light falling on a multiple slit 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 sl
76. ons But it is also an interactive shell that can evaluate arbitrary statements and expressions This is extremely useful for debugging quick hacking and testing Let us first have a look at some very simple examples 2 1 ROOT as calculator You can even use the ROOT interactive shell in lieu of a calculator Launch the ROOT interactive shell with the command gt root on your Linux box The prompt should appear shortly root 1 and let s dive in with the steps shown here root 0 141 const int 2 root 1 2x 4 2 12 const double 1 00000000000000000e 00 root 2 sqrt 3 const double 1 73205080756887719e 00 root 3 1 2 const int 0 root 4 TMath Pi Double t 3 14159265358979312 e 00 root 5 TMath Erf 2 Double t 2 22702589210478447e 01 Not bad 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 Now let s do something more elaborated A numerical example with the well known geometrical series root 6 double x 5 root 7 int N 30 root 8 double geom_series 0 root 9 for int i 0 i lt N i geom_series TMath Power x i root 10 TMath Abs geom series 1 TMath Power x N 1 1 x Double t 1 86264514923095703e 09 RNA OMAN DAK WN HF meee N RO 2 ROOT Basics Here we made a step forward We even declared variables an
77. opyright copyright trademark void3 times divide bullet circ voidb infty doublequote lt angle lbar cbar arcbottom arctop downarrow lt leftarrow leftrightarrow O otimes Downarrow lt Leftarrow stLeftrightarrowII prod void8 o Box hbar parallel v heart 4 spade S Jgothic R Rgothic LT GT equiv propto C subset notsubset supseteq oslash wedge v vee oright void1 A AA aa pm 3dots upoint V nabla 9 partial J downleftarrow corner topbar fltbar starcbar L bottombar T uparrow gt rightarrow O oplus J surd ft Uparrow Rightarrow Y sum int perp odot Lower case alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega a a ow lt T P A 7 CO 23 xm Oo 2 v Q a e exe e Upper case Alpha Beta Gamma Delta Epsilon Zeta Eta Theta lota Kappa Lambda Mu Nu Xi Omicron Pi Rho Sigma Tau Upsilon Phi Chi Psi Omega mnN amp ePoOw gt ZZ gt W E DHEXQ AMD ARO Variations varepsilon vartheta varsigma varUpsilon varphi varomega Figure B 3 The main Latex symbols that can be interpreted by the TLatex class o Kw
78. or the class TSelector is provided by the method TTree MakeSelector as is shown in the little macro makeSelector C below It opens the n tuple conductivity_experiment root from the example above and creates from it the header file MySelector h and a template to insert your own analysis code MySelector C id 33 O 0 IDO om c hr Ro OAN Dork WN eH NNNNNNNNP RPP BR BPR eee ps NO TR WNrF OM WON DTK WN FH O 6 File I O create template class for Selector to run on a tree EEE EEL OEE ETAL open root file containing the Tree TFile f TFile pen conductivity experiment root create TTree object from it TTree t TTree f Get cond data this generates the files MySelector h and MySelector C t MakeSelector MySelector file makeMySelector C The template contains the entry points Begin and SlaveBegin called before processing of the TChain starts Process called for every entry of the chain and SlaveTerminate and Terminate called after the last entry has been processed Typically initialization like booking of histograms is performed in SlaveBegin the analysis i e 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 The entry points SlaveBegin and SlaveTerminate are called on so called slave nodes only if parallel processin
79. orm fit if do_chi2 h4 gt Fit gaus q Chi2 fit else h4 Fit gaus 1q Likelihood fit some control output on the way if 1 1 100 4 h4 gt Draw EP cO Update j Get sigma from fit TF1 fitfunc h4 gt GetFunction gaus sig fitfunc gt GetParameter 2 mean fitfunc gt GetParameter 1 sigma gt Fill sig pull gt Fill mean sig sqrt n_tot_entries end of toy MC loop print result ci gt cd pull gt Fit gaus pull gt Draw EP ci gt Update 63 64 65 66 67 68 69 70 71 OAN DAK WN EH WPNNNYNYNYNNNNHPH PEPE pl pl pl pl ps Q 0 di O0 OX Q m f O 00 10 0 40 20 7 3 Fitting in General void macro9 int n_toys 10000 int n_tot_entries 100 int n_bins 40 cout lt lt Performing Pull Experiment with chi2 An pull n toys n tot entries n bins true cout lt lt Performing Pull Experiment with Log Likelihood n pull n toys n tot entries n bins false file macro9 cxx Your present knowledge of ROOT should be enough to understand all the technicalities behind the macro Note that the variable pull in line 54 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 e What method exhibits the better performance with the default parameters e What h
80. r bin env python python script EXAMPLE showing how to set up a fit with MINUIT using pyroot Author G Quast May 2013 dependencies PYTHON v2 7 pyroot numpy matplotlib array last modified Oct 6 2013 from ROOT import TMinuit Double Long import numpy as np from array import array as arr import matplotlib pyplot as plt gt define some data ax arr f e 0 05 0 36 0 68 0 80 1 09 1 46 1 71 1 83 2 44 2 09 3 72 4 36 4 60 ay arr f e 0 35 0 26 0 52 0 44 0 48 0 55 0 66 0 48 0 75 0 70 0 75 0 80 0 90 ey arr f 0 06 0 07 0 05 0 05 0 07 0 07 0 09 0 10 0 11 0 10 0 11 0 12 0 10 nPoints len ax gt Set parameters and function to fit a list with convenient names name an nm p Li H the initial values vstart arr d 1 0 1 0 1 0 and the initial step size step arr d 0 001 0 001 0 001 npar len name this defines the function we want to fit def fitfunc x npar apar a apar 0 m apar 1 b apar 2 f Double 0 ax xx x m x b return f 50 8 1 PyROOT 40 41 gt this is the definition of the function to minimize here a chi 2 function 42 def calcChi2 npar apar 43 chisq 0 0 44 for i in range 0 nPoints 45 x ax i 46 curFuncV fitfunc x npar apar AT curYV ay i 48 curYE ey i 49 chisq curYV curFuncV curYV
81. r np linspace rmin rmax npoints theta np sin r e np zeros npoints file macro3_numpy py Customised Binning This example combines comfortable handling of arrays in PYTHON to define variable bin sizes of a ROOT his togram All we need to know is the interface of the relevant ROOT class and its methods from the ROOT documentation 49 o 10 Ct d 0 EH OANDoK WN FH Bee RP Pe eee NOoPkwnr 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 8 ROOT in PYTHON THiF const char name const char title Int_t nbinsx const Double t xbins Here is the PYTHON code import ROOT from array import array arrBins array d 1 4 9 16 array of bin edges histo ROOT THiF hist hist len arrBins 1 arrBins fill it with equally spaced numbers for i in range 1 16 histo Fill i histo Draw file histrogram py A fit example in PYTHON using TMinuit from ROOT One may even wish to go one step further and do most of the implementation directly in PYTHON while using only some ROOT classes In the example below the ROOT class TMinuit is used as the minimizer in a x fit Data are provided as PYTHON arrays the function to be fitted and the y function are defined in PYTHON and iteratively called by Minuit The results are extracted to PYTHON objects and plotting is done via the very powerful and versatile python package matplotlib us
82. r on this just be aware of the histograms existence of interactive features in ROOT and use them if you find convenient Some trial and error is certainly necessary to find your way through the enormous number of menus and possible parameter settings 2 7 ROOT Beginners FAQ At this point of the guide some basic question could have already come to your mind We will try to clarify some of them with further explanations in the following 2 7 1 ROOT type declarations for basic data types In the official ROOT documentation you find special data types replacing the normal ones e g Double_t Float_t or Int_t replacing the standard double float or int types Using the ROOT types makes it easier to port code between platforms 64 32 bit or operating systems windows Linux as these types are mapped to suitable ones in the ROOT header files If you want adaptive code of this type use the ROOT type declarations However usually you do not need such adaptive code and you can safely use the standard C type declarations for your private code as we did and will do throughout this guide If you intend to become a ROOT developer however you better stick to the official coding rules 2 7 2 Configure ROOT at start up Tf the file rootlogon C exists in your home directory it is executed by ROOT at start up Such a file can be used to set preferred options for each new ROOT session The ROOT default for displaying graphics looks OK on th
83. related among groups of measurements These are specified in the full 8x8 covariance matrix which is composed of 4x4 block matrices The control line covmatrices 0 wmass cov specifies that not covariance matrix in x and the matrix wmass cov are to be used in the fit Mesurements of W Mass by AELPH DELPHI L3 and OPAL example of fit with covariance matrix graphics options markersettings 1 5 4 24 functionsettings 1 3 3 grid y title averaging measurements xaxis n yaxis Mass of W boson graphlegend W mass measurements top right functionlegend average W mass top right fit control fit m m Wmittelung fit initialvalues 80 5 dofit true the data LEP electroweak working group CERN 2006 staterrors 0 systerrors 0 0 abs abs covmatrices 0 wmass cov 1 80 429 0 059 qqlv ALEPH 2 80 340 0 076 qqlv DELPHI 3 80 213 0 071 qqlv L3 4 80 449 0 062 qqlv OPAL 5 80 475 0 082 qqqq ALEPH 6 80 310 0 102 qqqq DELPHI 7 80 323 0 091 qqqq L3 8 80 353 0 081 qqqq OPAL file wmass cov 0 003481 0 000316 0 000316 0 000316 0 000383 0 000383 0 000383 0 000383 0 000316 0 005776 0 000316 0 000316 0 000383 0 000383 0 000383 0 000383 0 000316 0 000316 0 005041 0 000316 0 000383 0 000383 0 000383 0 000383 0 000316 0 000316 0 000316 0 003844 0 000383 0 000383 0 000383 0 000383 0 000383 0 000383 0 000383 0 000383 0 006724 0
84. rom one to two and then three or Figure 2 4 Interactive ROOT panel for setting function more slits just as you like When clicking parameters on Apply the function plot is updated to reflect the actual value of the parame ters you have set 2 ROOT Basics Another very useful interactive tool is the FitPanel available Data Set z E for the classes TGraphErrors and TH1F Predefined fit functions Me D can be selected from a pull down menu including gaus expo pare and pol0 4pol9 for Gaussian and exponential functions or REN sj aus M polynomials of degree O to 9 respectively In addition user Poet PENNE defined functions using the same syntax as for functions with pa rameters are possible gaus After setting the initial parameters a fit of the selected func Silent tion to the data of a graph or histogram can be performed and the gous _Set Parameters result displayed on the plot The fit panel is shown in Figure 2 5 The fit panel has a large number of control options to select the General Minimization ME Fit Setti fit method fix or release individual paramters in the fit to steer aros the level of output printed on the console or to extract and dis Chi square User Denned play additional information like contour lines showing parameter Linear ft correlations Most of the methods of the class TVirtualFitter Robust
85. s cnt_r_h gt Fill rndgen Poisson mean_count gROOT gt SetStyle Plain TCanvas c new TCanvas cnt_r_h gt Draw TCanvas c_norm new TCanvas cnt_r_h gt DrawNormalized Print summary cout lt lt Moments of Distribution n lt lt Mean lt lt cnt_r_h gt GetMean lt lt lt lt cnt_r_h gt GetMeanError lt lt An lt lt RMS lt lt cnt r h GetRMS lt lt lt lt cnt_r_h gt GetRMSError lt lt An lt lt Skewness lt lt cnt_r_h gt GetSkewness lt lt An lt lt Kurtosis lt lt cnt_r_h gt GetKurtosis lt lt An file macro5 cxx 1To optimise the memory usage you might go for one byte TH1C short THIS integer TH1T or double precision TH1D bin content 23 coo 1co cU H5 cC rt NNNNNNNNKP RP RRB RP PRP RPP NOTR WN Fr COHUO AN DTK WN HF O 5 Histograms Count Rate count_rate Entries 400 o E Mean 3 562 3 90 RMS 1 792 2 E o E 5 s06 2E o Lr o 7O CE 605 50E 4oE 30E 205 10E gel Aou Ha dou suada Pe ak oaa lus 0 2 4 6 8 10 12 14 Figure 5 1 The result of a counting pseudo experiment Which gives you the following plot Using histograms is rather simple The main differences with respect to graphs that emerge from the example are e line 5 The histograms have a name and a title right from
86. s like providing high level mathematical functions and handling of large multi dimensional matrices or ns plotting tools for publication quality graphics PyROOT additionally adds to this access to the vast capabilities of the ROOT universe To use ROOT from PYTHON the environment variable PYTHONPATH must include the path to the library path ROOTSYS lib of a ROOT version with PYTHON support Then PyROOT provides direct interactions with ROOT classes from PYTHON by importing ROOT py into PYTHON scrips via the command import ROOT it is also possible to import only selected classes from ROOT e g from ROOT import TF1 8 1 PyROOT The access to ROOT classes and their methods in PyROOT is almost identical to C macros except for the special language features of PYTHON most importantly dynamic type declaration at the time of assignment Coming back to our first example simply plotting a function in ROOT the following C code TF1 f1 new TFi f2 O sin 1 x x 0 10 fi gt SetParameter 0 1 fi gt SetParameter 1 1 fi Draw in PYTHON becomes import ROOT f1 ROOT TF1 2 0 sin 1 x x 0 10 f1 SetParameter 0 1 f1 SetParameter 1 1 f1 Draw A slightly more advanced example hands over data defined in the macro to the ROOT class TGraphErrors Note that a PyTHON array can be used to pass data between PyTHON and ROOT The first line in the PyTHON script allows it to
87. s class 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 Some points of the code will be explained in detail 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 6 Create Draw and fit a TGraph2DErrors void macro4 gStyle gt SetPalette 1 gROOT gt SetStyle Plain const double e 0 3 const int nd 500 TRandom3 my random generator TF2 f2 new TF2 f2 1000 C O sin x x i sin y y 200 6 6 6 6 f2 SetParameters 1 1 TGraph2DErrors dte new TGraph2DErrors nd Fill the 2D graph double rnd x y Z ex ey ez for Int t i 0 i lt nd i f2 GetRandom2 x y rnd my_random_generator Uniform e e A random number in e e z f2 gt Eval x y 1 rnd dte gt SetPoint i x y z ex 0 05 my_random_generator Uniform ey 0 05 my_random_generator Uniform ez TMath Abs z rnd dte gt SetPointError i ex ey ez j Fit function to generated data f2 SetParameters 0 7 1 5 set initial values for fit f2 SetTitle Fitted 2D function dte Fit f2 21 29 30 31 32 33 34 35 36 37 38 39 40 4 Graphs Plot the result TCanvas c
88. s started E Data is entered in the histogram in line E 5 using the method TH1F Fill in a loop A construct As a result the histogram E is filled with 1000 random numbers dis E tributed according to the defined func ES tion The histogram is displayed using the E method TH1F Draw You may think of A Stee EEG ERE Ln lA nas fiel this example as repeated measurements of 05 1 15 2 o BS gg S5 amp 539 S the life time of a quantum mechanical state which are entered into the histogram thus i i giving a visual impression of the probabil Figure 2 3 Visualisation of a histogram filled with exponen ity denuitvdistzihution Th plot is show tially distributed random numbers in Figure 2 3 Note that you will not obtain an iden tical plot when executing the above lines depending on how the random number generator is initialised The class TH1F does not contain a convenient input format from plain text files The following lines of C code do the job One number per line stored in the text file expo dat is read in via an input stream and filled in the histogram until end of file is reached root 1 THiF h new THiF h example histogram 100 0 5 root 2 ifstream inp double x root 3 inp open expo dat root 4 while inp gt gt x 0 h Fill x root 5 h Draw root 6 inp close Histograms and random numbers are very important tools in st
89. sses via the interpreted high level programming language PYTHON became available PYTHON itself offers powerful modules and packages for data handling numerical applications and scienfific computing A vast number of bindings or wrappers to packages and tools written in other languages is also available Access to the ROOT functionality is provided by the ROOT package PyRoot 5 allowing interactive work as well as scritps based on PYTHON This is presented at the end of this guide in Chapter S ROOT is available for many platforms Linux Mac OS X Windows but in this guide we will implicitly assume that you are using Linux The first thing you need to do with ROOT is install it Or do you Obtaining the latest ROOT version is straightforward Just seek the Pro version on this webpage You will find precompiled versions for the different architectures or the ROOT source code to compile yourself Just pick up the flavour you need and follow the installation instructions Or even simpler use a virtual machine with ROOT installed ready for use as availalbe under e g http www ekp physik uni karlsruhe de quast Let s dive into ROOT OVCaAN Doe c0 t A hop wor o O0 4 CQ hl rn CHAPTER 2 A BASICS Now that you have installed ROOT what s this interactive shell thing you re running It s like this ROOT leads a double life It has an interpreter for macros CINT 4 that you can run from the command line or run like applicati
90. t any effort from your side except the insertion of the appropriate header files in lines 3 9 In this example they are already included This does not harm as they are not loaded by CINT To generate an object libary from the macro code from inside the interpreter type please note the root 1 L macro1 cxx 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 4 2 Compile a Macro with g 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 root config is a script that comes with ROOT it prints all flags and libraries needed to compile code and link it with the ROOT libraries 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 The easiest way to turn a ROOT macro code into a stand alone application is to add the following dressing code at the end of the macro file This defines the procedure main the only purpose of which is to call your macro ifndef CINT int main ExampleMacro return 0 endif Within ROOT the symbol __CINT__ is defined and the code enclosed by ifndef __CINT__ and endif is not executed on the contrary when running the sys
91. t x calculate derivative Double_t Derivative Double t x calculate integral a to b Double t Integral Double t a Double t b get random number Double t GetRandom set parameter i SetParameter Int t i Double t parvalue set parameters SetParameters const Double t params fit function f to graph gr or histogram h gr gt Fit TF1 f or h gt Fit TF1 f get parameter i Double_t GetParameter Int t i get error on parameter i Double_t GetParError Int t i the calss used to generate random sequences of high quality initialize random generator with random seed TRandom 0 initialize random generator with seed TRandom UInt t seed get actual seed Ulnt_t GetSeedO uniform random number 10 x1 Double t Uniform Double t x1 1 uniform random number x1 x2 Double t Uniform Double t xi Double_t x2 random number from binomial distribution Int t Binomial Int_t ntot Double t prob random Poisson number Int_t Poisson Double t mean random number from exponential Double t Exp Double_t tau random number from Gaussian distribution Double_t Gaus Double_t mean 0 Double t sigma 1 pre initialised random generator gRandom points to global instance of TRandom3 configuring the graphics canvas create canvas of size ww x wh TCanvas const char name const char title Int t ww Int t wh subdivide into pads Divide Int t nx 1 Int t ny 1 Float t xmargin 0 01 Float t ymargin 0 01 Int t color 0 chage to subpad cd Int_t subpadnumber 0 upda
92. te canvas Update O mark as modified to trigger re draw Modified Bool_t flag 1 draw canvas Draw Option_t option and DrawClone 63 C Most Relevant Classes and their Methods TLegend the legend in a plot Fundamental for the understanding of the contents create Legend TLegend Double_t xi Double t yi Double t x2 Double t y2 const char header Option_t option brNDC add an entry AddEntry TObject obj const char label Option t option lpf add text entry AddEntry const char name const char label Option t option 1pf draw DrawO and DrawCloneO LaTEX formatting create Text TLatex Double t x Double t y const char text draw DrawO and DrawCloneO file I O create file TFile const char fname Option t option const char ftitle Int t compress 1 options NEW CREATE RECREATE READ change direcotry to fle c O write histogram h to file hi gt write close file at the end CloseO read histogram h from file f THIF h1 TH1F f Get const char histname TNtuple variables in ntuples create TNtuple const char name const char title const char varlist format varlist x0 x2 xn n 15 fill Fill Float t xO Float t x Float t x2 0 Float t x14 0 initialize from file ReadFile const char filename plot variables Draw const char varexp const char selection e g plot variable xi Draw xi e g plot variable with cut on others Drag xi xj 3 e
93. te your histograms SlaveBegin called after Begin when on PROOF called only on the slave servers Process called for each event in this function you decide what to read and fill your histograms SlaveTerminate called at the end of the loop on the tree when on PROOF di called only on the slave servers Terminate called at the end of the loop on the tree a convenient place to draw fit your histograms To use this file try the following session on your Tree T Root gt T Process MySelector C Root gt T Process MySelector C some options Root gt T gt Process MySelector C Y include MySelector h include lt TH2 h gt l 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 34 28 29 30 31 32 33 34 35 36 37 38 39 40 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 67 68 69 70 cel 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 6 2 N tuples in ROOT include lt TStyle h gt include lt TCanvas h gt user defined variables may come here UInt t fNumberOfEvents TDatime tBegin tNow THIF h_pot h_cur h_temp h_pres h_resistance void MySelector Begin TTree treex The Begin function is called at the start of t
94. tem compiler g this symbol is not defined and the code is compiled To create a stand alone program from a macro called ExampleMacro C simply type gt g o ExampleMacro exe ExampleMacro C root config cflags libs and execute it by typing gt ExampleMacro exe This procedure will however not give access to the ROOT graphics as neither control of mouse or keyboard events nor access to the graphics windows of ROOT is available 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 In the example below a macro ExampleMacro_GUI is executed by the ROOT class TApplication As a further feature this code example offers access to parameters eventually passed to the program when started from the command line Here is the code fragment ifndef CINT void StandaloneApplication int argc char x argv eventually evaluate the application parameters argc argv gt here the ROOT macro is called ExampleMacro GUI 17 Oo on 10 11 12 13 14 15 3 ROOT Macros This is the standard main of C starting a ROOT application int main int argc char x argv gROOT gt Reset TApplication app Root Application amp argc argv StandaloneApplication app Argc app Argv app Run return 0 endif Compile the code with gt g
95. ten results in acceptable results With the option fitmethod likelihood a likelihood method can be selected In this case the statistical errors are ignored and may be ommitted For technical reasons the x values must be equi distant in this case due to usage of ROOT class TH1 TERERERERETERERERERERETRERETERETETETETETETETETEHETEERETE IET IE SERE SERE RERETRERETERETEHETETEHETEETEEHEEH EERE AR example fit of an angular distribution HERRIA HORROR HORROR HORROR HEARSE RODAR RODAR RAPE REA EERE RARA BINE E G plot commands title angular distribution xaxis cos theta yaxis number of events graphlegend observed rate top left functionlegend fitted cos theta distribution top left markersettings 1 5 2 5 functionsettings 1 3 3 fit control 4 fit a4 x 4ta3 x 3ta2 x 2tadl xta0O a0 al a2 a3 a4 v vs cost fit dofit true fitmethod likelihood uncomment to perform a Log Likelihood fit definition of data staterrors y cost N sqrt N 0 9 81 9 0 0 7 50 7 1 0 5 35 5 9 0 3 27 5 2 0 1 26 5 1 0 1 60 7 7 0 3 106 10 3 0 5 189 13 7 0 7 318 17 8 0 9 520 22 8 59 A RooFiLab A 2 4 Correlated measurements with full covariance matrix As a more complex example the averaging procedure for measurements of the W Boson mass is shown here Measurements of the four LEP experiments in two final states have different systematic errors which are cor
96. ters Such a model may simply state the current I is proportional to the voltage U and the task of the experimentalist consists of determining the resistance R from a set of measurements As a first step a visualisation of the data is needed Next some manipulations typically have to be applied e g corrections or parameter transformations 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 One specialty of experimental physics are the inevitable errors affecting each measurement and visu alization tools have to include these In subsequent analysis the statistical nature of the errors must be handled properly As the last step measurements are compared to models and free model parameters need to be de termined in this process see FigurdI 1 for an example of a function model fit to data points Several standard methods are available and a data analysis tool should provide easy access to more than one of them Means to quantify the level of agreement between measurements and model must also be available 0 9 0 8 0 7 f x 0 6 Yz 0 5 0 4 0 3 i m Model Figure 1 1 Measured data points with error bars and fitted quadratic funct
97. the start no predefined number of entries but a number of bins and a lower upper range e line 15 An entry is stored in the histogram through the TH1F Fill method e line 19 and 22 The histogram can be drawn also normalised ROOT automatically takes cares of the necessary rescaling e line 25 to 31 This small snippet shows how easy it is to access the moments and associated errors of a histogram 5 2 Add and Divide Histograms Quite a large number of operations can be carried out with histograms The most useful are addition and division In the following macro we will learn how to manage these procedures within ROOT Divide and add 1D Histograms void format h TH1F h int linecolor h gt SetLineWidth 3 h gt SetLineColor linecolor void macro6 gROOT gt SetStyle Plain THiF sig_h new THiF sig_h Signal Histo 50 0 10 THiF gaus_hi new THiF gaus hi Gauss Histo 1 30 0 10 THiF gaus h2 new THiF gaus h2 Gauss Histo 2 30 0 10 THiF bkg_h new THiF exp h Exponential Histo 50 0 10 simulate the measurements TRandom3 rndgen for int imeas 0 imeas lt 4000 imeas bkg_h gt Fill rndgen Exp 4 if imeas 4 0 gaus_hi gt Fill rndgen Gaus 5 2 if imeas 4 0 gaus_h2 gt Fill rndgen Gaus 5 2 if imeas 10 0 sig_h gt Fill rndgen Gaus 5 5 Format Histograms THiF histos 4 sig_h bkg_h gaus_h1 gaus_h2 for int i 0 i lt 4 4 i histos i
98. x 5ymbols xu bee GGG EKER o Een dee ce AA So Roe Eos be be A m ens 62 C Most Relevant Classes and their Methods e 63 66 BIBLIOGRAPHY 1 ReneBrun and Fons Rademakers ROOT An Object Oriented Data Analysis Framework Proceedings Al HENP 96 Workshop Lausanne Sep 1996 Nucl Inst and Meth in Phys Res A 389 1997 81 86 See also bi in T s i 67
99. xample to also plot the interference pattern of a single slit using function double single or of a grid with narrow slits function double nslitO in TF1 instances Here we used a macro some sort of lightweight program that the interpreter distributed with ROOT CINT is able to execute This is a rather extraordinary situation since C is not natively an interpreted language There is much more to say therefore there is a dedicated chapter on macros Figure 2 1 Output of macro slits cxx with parameters 0 2 and 2 2 3 Controlling ROOT One more remark at this point as every command you type into ROOT is usually interpreted by CINT an escape character is needed to pass commands to ROOT directly This character is the dot at the beginning of 2 ROOT Basics a line root 1 lt command gt To e quit root simply type q e obtain a list of commands use e access the shell of the operating system type lt 0S_command gt try e g ls or pwd e execute a macro enter x lt file_name gt in the above example you might have used x slits cxx at the ROOT prompt e load a macro type L lt file_name gt in the above example you might instead have used the command L slits cxx followed by the function call slits Note that after loading a macro all functions and procedures defined therein are available at the ROOT prompt 2 4 Plotting Measurements To display measurements in ROOT including

Download Pdf Manuals

image

Related Search

Related Contents

  Le voyaGe de kGonta bo Le chaman  Portable User Interface  Thermaltake SopranoFx  p500 ver 2.0 user manual  manual tecnico del electricista  PEPEROSSO Manuale v1-0  OBM-21αS(カウン太くん21αS)  dossier - Ville d`Antony  UMDLOTI/OHLANGA WASTEWATER REVIEW  

Copyright © All rights reserved.
Failed to retrieve file