Home
A ROOT Guide For Students
Contents
1. 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 in file Get bjectChecked cond data TNtuple 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 gt GetEntry irow row_content my_tuple gt GetArgs pot row_content 0 cur row_content 1 31 20 21 22 23 24 25 M o0 amp RcCtb G 00 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 1 0 temp row content 2 pres row content 3 cout lt lt pot lt lt t lt lt cur lt lt Nt lt lt temp lt lt Nt 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 by using ROOT s TBranch class This is especially important a
2. 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 to us
3. perform 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 gt 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 y end of toy MC loop print result ci cd pull gt Fit gaus pull gt Draw EP ci gt Update void macro9 42 64 65 66 67 68 69 70 71 OMAN an WN HF Be RP Re gt yu NR O 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 7 3 Fitting in General 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 p
4. Kappa Lambda Mu Nu Xi Omicron Pi Rho Sigma Tau Upsilon Phi Chi Psi Omega mnN amp ePoOw gt ZZ gt W E D HEXQ M BORO Variations varepsilon vartheta varsigma varUpsilon varphi varomega Figure B 3 The main Latex symbols that can be interpreted by the TLatex class o Kw 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 f1 Option t option Fit const char formula Option t option Option t goption Axis t xmin 0 Axis t xmax 0 Draw AP and DrawClone AP methods of classes TGraph TGraphPainter ption t goption Axis t xmin 0 Axis t xmax 0 draw draw options 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 v
5. cnt r h Fill rndgen Poisson mean count gROO0T SetStyle Plain TCanvas c new TCanvas cnt r h Draw TCanvas c norm new TCanvas cnt r h 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 n lt lt Skewness lt lt cnt r h GetSkewness lt lt n lt lt Kurtosis lt lt cnt r h GetKurtosis lt lt Mn file macro5 cxx l To optimise the memory usage you might go for one byte TH1C short TH1S integer TH1I or double precision TH1D bin content 23 coo 1ocU 5 c ct r N Oh2 bh2 bh bo ho hlON 202 RRR RPP ee ps NOouPBwWwnNnrFouvomntoauowtrwnNro 5 Histograms Count Rate count_rate Entries 400 o E Mean 3 562 90 RMS 1 792 2 E o E 5 s06 a 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 the s
6. 74 for i in range 0 npar A 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 gt check TMinuit status 81 amin edm errdef Double 0 Double 0 Double 0 82 nvpar nparx icstat Long 0 Long 0 Long 0 83 mnyMinuit mnstat amin edm errdef nvpar nparx icstat 84 4 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 3 accurate 92 2 forced pos def 93 1 approximative 94 O not calculated 95 myMinuit mnprin 3 amin print out by Minuit 96 97 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 111 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
7. To display measurements in ROOT including 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 iac less ExampleData txt to inspect the file E 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 E The data itself consist of lines with four 0 8 real numbers each representing the x and Ae y coordinates and their errors of each data ME l point You should quit 04 gt The argument of the method Draw AP 02E isimportant here It tells the TGraphPainter AA E A E OE eee e A ape QS class to show the axes and to plot mark i 15 2 2 5 3 ers at the x and y positions of the specified data points Note that this simple example ED 3 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
8. 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 7 3 Fitting in General cout lt lt endl cout lt lt Covariance Matrix lt lt endl double dxdi dxdj for int i 1 i lt minfit gt fNu i int ix minfit gt fNexofi i 1 int ndi ix i 1 2 minfit mndxdi minfit fX i 1 i 1 dxdi for Int t j 1 j lt minfit fNu 4j minfit gt mndxdi minfit fX j 1 j 1 dxdj int m TMath Max i j int n TMath Min i j int ndex m m 1 2 n int ndj j j 1 2 eline j 1 dxdixminfit gt fVhmat ndex 1 dxdj minfit gt fUp for Int_t it 1 it lt minfit gt fNu it sprintf line 10 3e eline it 1 cout lt lt line cout lt lt endl void formatGraph TGraph g int col int msize int lwidth g gt SetLineColor col g gt SetMarkerColor col g gt SetMarkerSize msize g gt SetLineWidth lwidth void plotContours TMinuit minfit int pi int p2 Get confidence contours of parameters int ic 0 minfit gt SetPrintLevel 0 not print all countour points minfit gt mncomd Set ERR 4 ic Set the the contour level TGraph cont 2sigma TGraph minfit gt Contour 50 contour w 50 points minfit gt mncomd Set ERR 1 ic Set the the contour level TGraph cont 1sigma TGraph minfit gt Contour 50 contour w 5
9. h from file t THIF h1 THI1F 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 lt 15 fill Fill Float_t x0 Float_t x1 0 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 Draw xi e g 2 dim plot of variables xi and xj Draw xi 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 SetOptFit 11 1 suppress title boxes on graphs and histograms gStyle 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 amp Double t Double t amp f Double t Int t fcn fix a parameter FixParameter Int t ipar release parameter ReleaseParameter Int
10. quite useful for example to represent the errors of 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 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 TCanvas c new TCanvas myCanvas myCanvas 600 600 TGraphPolar grP1 npoints r theta grP1 SetTitle A Fan grPi SetLineWidth 3 grP1 SetLineColor 2 grPi 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 Qoo 1oc 0 40 t o E 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
11. 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 gt 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 Draw c result SaveAs ResistanceDistribution png tNow Set printf End of Job WY 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 O 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 as is described in detail in the ROOT documentatio
12. this is achieved with the method 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 fi 5SetParameter 0 1 root 15 fi 5SetParameter 1 1 root 16 f1 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 simple
13. 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 often 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 THEIETHEIEHIETHEIHEHETHEIEHETHEIEHETHEIEHETHHEHEHHEHEHHEHEHHEHHHHEHHHRHE NE example fit of an angular distribution HHHHHHHHHHHHHHHHHHHHHEA RHR HORROR RHR HRA HAAR HEHE 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 fit a4 x 4 a3 x 3 ta2 x 2 tadl xtaO 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
14. 4 ROOT Global Variables lll 11 3 ROOT Macros ooe sacs Ge Pe deca a e e ae Re EH 13 3 1 General Remarks on ROOT macros lll llle ess ss 13 3 2 A more complete examplel 14 3 39 summary of Visual ellects i o e woe a UE ER teh EO ORE RO UY UR OX ORO NOR RECO A RAN 16 3 3 1 Colours and Graph Markers re 16 3 39 2 Arrows and Lines lt cos c cadea ob ee pe eor ee 16 AE A s bo Shae kg ee ee oe aE E a dede de oe ouis A 17 3 4 Interpretation and Compilation 2 0 a 17 3 4 1 Compile a Macro with ACLIC a 17 3 4 2 Compile a Macro with g3 gt Ire 17 4 1 Read Graph Points from File 222A 19 2 2 Polar Graphs ncm S m Rr e eA ee CAGE ee Bate ek te A AA gene pose ek 20 4 3 21D 7 Graph s x desesosce Roe brake Se Be Ao iXBURCa a ed ee Be 21 C NK a a a a a a a a a aaa a a a d a ia a a ee Saa e daa a G a ae EA SAE aia 23 5l Your Pirst Histogrami s s o siapo o a 2204 bb aee ee dude eb bee POR ve 23 5 2 Add and Divide Histograms ooa a 24 5 3 Two dimensional Histograms o e s e ee 26 29 29 30 30 2 31 cat wea Pe ae deo ke hee awk ee EE Rea we owe aa Ge 32 6 2 4 Processing N tuples Spanning over Several Files 2220200020000 33 6 2 5 For the advanced user Processing trees with a selector script 33 6 2 6 For power users Multi core processing with PROOF lite 36 sube AAA PE 37 OCC e
15. 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 correlated 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 functionsettings 1 grid y title averaging measurements xaxis n 4 24 33 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 O 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
16. Change the slit width or go from 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 I Data Set z E for the classes TGraphErrors and TH1F Predefined fit functions 000 Misi can be selected from a pull down menu including gaus expo pee and pol0 po19 for Gaussian and ee E REN sj aus M polynomials of degree 0 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 Silii tion to the data of a graph or histogram can be performed and the oa _Set Parameters result displayed on the plot The fit panel is shown in Figure 5 The fit panel has a large number of control options to select the General Minimization ae j 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 TVirtualFi
17. Units 6 12 14 20 22 24 35 45 44 0 53 60 Measured Points e A oe Bw Ot a Hs a Ot Ol Ae OrROrRN ON rFPOANOOBRWNEH 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 SetGrid 19 00 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 c oo 1oc0 0 AUNE a es OMAN atk UNEO 4 Graphs TGraphErrors graph_expected macro2_input_expected txt lg lg lg graph expected SetTitle Measurement XYZ and Expectation lenght cm Arb Unies 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 1eg 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 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
18. for the markers is summarised in 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 Qa AUNE ow 0 MN n 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 ACLIiC will create for you a compiled dynami
19. 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 OANA ntKWN KH Q2 Q3 Q2 Q9 C29 h2 nN NNNNNN NH KF A RP RP op FPwWwNYNrF OKO ANDOBWNHRrF OHO AN DAA BPWNFH OC 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 TH1 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 Two dimensional histograms
20. 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 TH1F 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 TH1F my_histogram l My Title root 2 my_histogram Draw Alternatively you can use a simple macro to carry out the job 29 Qoo 1o900 AUNA PRR Ne o Oo oo 1oc cU 5 c0rtr NV NNDNNR PRP RB RP RP Re ee PFPwWwNrRF OKT AWAN ODA 0b rH O 6 File I O void read from file Let s open the TFile TFilex i
21. 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 1 1 const int 2 root 1 2 442 12 const double 1 00000000000000000 e4 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 00 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 e UNBE oc oo I1oco0 0 amp amp 0t PRR Neo 2 ROOT Basics Here we made a step forward W
22. 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 E 33 Qoo I1o0 O0 s C DN ho Ro O0J ODOCdcauN A NN NNNNNNR RRP BR BRR eee ps NOoouPwnhrrowononroauwrwnNr O 6 File I O create template class for Selector to run on a tree PODES open root file containing the Tree TFile f TFile Open conductivity_experiment root create TTree object from it TTree t TTree x f gt Get cond_data this generates the files MySelector h and MySelector C t gt 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 processing via PROOF or PROOF lite is enabled
23. with the following statement for i in 01234 5 do root 1 x b q write ntuple to file cxx VM 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 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 Nt lt lt temp lt lt Nt 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 for the class TSelector is provided by
24. 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 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 Pe MARKERS COLOURS SYMBOLS B 1 Colour Wheel and Graph Markers o y AX 26 27 28 29 30 090 7 8 9 10 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 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 kOpenTriangleUp 7 medium dot kFullDotMedium 27 open diamond kOpenDiamond 8 large scalable dot kFullDotLarge 28 open cross kOpenCross 20 full circle kFullCirc
25. 0 points The minimum of the graph and its 1 sigma error TGraphErrors min g l min g SetMarkerStyle 22 min_g SetPoint 0 minfit gt fU 0 minfit gt fU 1 min_g SetPointError 0 minfit gt fWerr 0 minfit gt fWerr 1 Maquillage of the Graphs formatGraph cont_1sigma kRed p2 p1 formatGraph cont_2sigma kGreen p2 p1 cont_2sigma gt SetTitle Contours tau off set TCanvas cresult new TCanvas cresult 10 410 400 400 cresult gt cd cont_2sigma gt DrawClone APC cont_lsigma gt DrawClone SamePC min g DrawClone PSame if main program for MINUIT fit int example_minuit TMinuit myminuit new TMinuit NFitPar initialize global pointer if initialize fit myminuit 0 return 1 Standard control of a fit with MINUIT int ic 0 integer for condition code myminuit SetFCN the function myminuit gt mncomd MIN Start minimization SIMPLEX first then MIGRAD ic 0 if command executed normally myminuit gt mncomd MINOS ic Call MINOS for asymmetric errors myminuit gt mncomd HESSE ic Call HESSE for correct error matrix end_of_fit myminuit Call user defined fit summary printFit myminuit retrieve output from minuit plotContours myminuit 2 3 contour lines of fit parameters 2 and 3 return 0 file example minuit cxx 45 7 Functions and Parameter Estimation You already know most of the code fragments u
26. NT Karlsruhe Institute of Technology Institut fiir Experimentelle Kernphysik A ROOT Guide For Students A 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 December 5 2013 CHAPTER 1 MEN 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 param
27. TGraph2DErrors 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 x 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 2 1000 0 sin x x 11 sin y y 200 42 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 5Eval x y l 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 zxrnd dte gt SetPointError i ex ey ez Fit function to generated data f2 5SetParameters 0 7 1 5 set initial values for fit f2 5SetTitle Fitted 2D function dte gt Fit f2 21 29 30 31 32 33 34 35 36 37 38 39 40 4 Graphs Plot t
28. 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 ry 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 manual increase m
29. ad update canvas mark as modified to trigger re draw draw canvas Double t Uniform Double t x1 1 Double t Uniform Double t x1 Double t x2 Int t Binomial Int t ntot Double t prob Int_t Poisson Double t mean Double t Exp Double t tau Double t Gaus Double t mean 0 Double t sigma 1 gRandom points to global instance of TRandom3 TCanvas const char name const char title Int t ww Int t wh Divide Int t nx 1 Int t ny 1 Float t xmargin 0 01 Float t ymargin 0 01 Int t color cd Int t subpadnumber 0 Update Modified Bool t flag 1 Draw ption t option and DrawClone 0 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 x1 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 lpf draw Draw and DrawClone LaTEX formatting create Text TLatex Double_t x Double_t y const char text draw Draw and DrawClone file 1 0 create file TFile const char fname Option_t option const chart ftitle Int t compress 1 options NEW CREATE RECREATE READ change direcotry to fle cdO write histogram h to file hi gt Write close file at the end Close read histogram
30. al and background components at the best fit values 0 250 2 S SignalPeak over x ndf 42 03 44 gt E back d Prob 0 5564 u ackgroun Norm 57 83 8 01 200 l Mean 7 01 0 14 LTN Sigma 0 9238 0 1652 a 200 6 5 4 b 16 73 1 03 1507 0 4438 0 0461 100 50 E ke SOX CUT E S CA 05 2 4 6 8 10 12 14 16 18 20 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 compa
31. alue 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 Reset Float_t GetArray SetMaximum Double t ymax SetMinimum Double t ymin Double t GetMean 1 Double t GetRMS 1 Draw Option_t option SAME E p see documentation of class THistPainter clear copy to C array set maximum on y axis set minimum on y axix get mean get RMS draw useful draw options 2 dimensional histogram class with float bin contents 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 book fill Fill Double t x Double t y fill with weight get mean along axis i get RMS along axis i get covariance get correlation draw useful draw options Fill Double t x Double t y Double t w Double t GetMean i Double_t GetRMS i Double_t GetCovariance Double_t GetCorrelationFactor Draw ption t option and DrawClone SAME BOX COL LEGO SURF see documentation of class THistPainter TProfile profile representation for 2 dim histograms book p rofile 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 fi
32. andled 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 DivingRO0OT macros c MySelector C so x 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 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 dH End of Job Date
33. arameters e What happens 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 very general example consisting of a part to be written specifically for each problem and a more general part at the bottom for executing the fit and retrieving the results Data is read from a file stored in an n tuple for repeated access and an extended negative log likelihood function is calculated and minimized with respect to the fit parameters Example of an extended log likelihood fit control part of this macro is general begin of user code global variab
34. 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 Guassian 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 gt 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 gt Divide 2 2 c2 cd 1 bidi h ProjectionX DrawClone c2 cd 2 bidi h ProjectionY DrawClone c2 cd 3 bidi h ProfileX DrawClone c2 cd 4 bidi h ProfileY 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 a projection is performed along th
35. 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 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 TLisd 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 17 Begin called every time a loop on the tree starts a convenient place to create your histograms SlaveBegin ca
36. at t ex n 05 1 07 07 04 05 06 07 08 05 and hand over to TGraphErros object 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 c1 gt Update file TGraphFit C In PvTHON it looks like this usr bin env python Draw a graph with error bars and fit a function 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 Zmake nice Canvas c1 SetGrid define some data points x array f 0 92 0 1 0 25 0 35 0 5 0 61 0 7 0 85 0 89 1 1 3 y array 0 7 2 s 5 6 7 4 9 9 6 8 7 6 3 4 5 1 1 ey array E 8 7 0 5 44 4 4 5 6 7 8 ex array f 05 e 07 04 05 06 07 08 05 nPoints len x tt and hand over to TGraphErros object gr TGraphErrors nPoints x y ex ey gr SetTitle TGraphErrors with Fit gr Draw AP gr Fit gaus c1 Update request user action before ending and deleting graphics window raw_input Press lt ret gt to end gt 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 straig
37. ay 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 00 1oc cU AUNE hop Ro 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 general tasks with user d
38. c library for your macro without 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 macro1l 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 th
39. control of the different steps of the fitting process Line 63 109 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 Line 115 137 Retrieval of the contour lines of two fit parameters one and two o in this example The correlation of the two variables tau and off set is clearly visible Figure 7 2 htemp Contours Entries 170 E T w 0 95 T us ES T af Mean 2 045 9 E J E RMS 1 39 S Ek J dea Underflow 0 0 9 e sE Overflow 0 E 4 E J 0 85 E 4 E FR a 0 8 j aE q E 7 B 3 enr E i Dnm ATL E E H m 0 65 lem 1 o i d 4 i alb ilu ot all i th tt abi 4 o e i Euadbaaasilisasaslaiiisnxdsasalasasalsiiuzsulussslususslsiratsi 0 1 2 3 4 5 0 4 0 5 0 6 0 7 0 8 0 9 1 14 12 x T Figure 7 2 Histogrammed input data with overlayed scaled fit function and one and 2 c contour lines 46 from extended log likelihood fit e Ne oF WN FR CHAPTER 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 lev
40. create a canvas partition it in two sub pads and access them It is very handy to show multiple plots in the same window or image Qoo 1oc0 AUNE w Q9 Q9 b2 b2 h2 b2 h2 b2 Lb2 h2 h2 N KK ppp Nr 0d ANDOTBRWBNrFRFTWOAN OA AHRWNHHrH CO 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 x void macro5 TH1F cnt r h new THiF 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 imeas
41. e 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 If 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 the computer sc
42. e contrary when running the system 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 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 CNT void StandaloneApplication int argc charx argv eventually evaluate the application parameters argc argv gt here the ROOT macro is called ExampleMacro_GUI 17 00 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 argv gROOT gt Reset TApplication app Root Application amp argc argv StandaloneApplication app Argc app Argv app Run return 0 endif Compile
43. e ee ee eee EEEE oe 39 7 1 Fitting Functions to Pseudo Data 2 e 39 7 2 Toy Monte Carlo Experiments 41 feo Fitting in General wx e do ie A A AU qoe AAA we i 43 65 Contents T 47 A NAAA 47 AA A O A PME 49 EIDEM 55 e a a a 55 A O E NE EEN 56 red aps sp ds e etie e eN e rein erue ue yy e ae a ON fe a a 56 5a a BS A ed we Be wi e ey st oe a ely Se E 56 A 2 1 Straight line fit with correlated erros in x and y 57 58 59 A 2 4 Correlated measurements with full covariance matrix 004 60 B Markers Colours Symbols ee 61 B 1 Colour Wheel and Graph Markers lee 61 B2 Lines sande ATrOWS 4i cx tes a ee ER ebd ue de We ddr re er 62 B 3 Latex Symbols 5 ek Ah E oe RE a oe EP De EA OS Oh Ba ee a a 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 AI HENP 96 Workshop Lausanne Sep 1996 Nucl Inst and Meth in Phys Res A 389 1997 81 86 See also b in T T i 67
44. e even declared variables and used a for control structure Note that there are some subtle differences between CINT and the standard C language You do not need the W 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 TF1 f1 new TFi fi sin x x 0 10 root 12 fi gt Draw f1 is a 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 CINT 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 CIN T 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
45. e 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 classes
46. e will 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 bas 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
47. e 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 1ocU m UNE Be RP RP eee Nouv 40 rx 27 7 o 0 JD 0t Co l2 CHAPTER 0 FILE I O 6 1 Storing ROOT Objects ROOT offers the possibility to write the instances of all the classes
48. eated when ROOT is started Data is entered in the histogram in line 5 using the method TH1F Fill in a loop construct As a result the histogram is filled with 1000 random numbers dis tributed according to the defined func tion The histogram is displayed using the method TH1F Draw You may think of Fans Stee Ae RE Ln lA cunts on a all this example as repeated measurements of Gao o o We M M the life time of a quantum mechanical state which are entered into the histogram thus et R giving a visual impression of the probabil Figure 2 3 Visualisation of a histogram filled with exponen ity density distribution The plot is shown tially distributed random numbers in Figure 2 3 40 30 20 o 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 TH1F h new TH1F h example histogram 100 0 5 root ifstream inp double x root inp open expo dat root 4 while inp gt gt x 0 h gt Fill x root 5 h gt Draw root 6 inp close Histograms and random numbers are very impor
49. efined 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 this class allow to set init
50. el 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 packages like providing high level mathematical functions and handling of large multi dimensional matrices or ae EE ordine 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 PvTHON 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 xfi new TFi1 f2 O sin 1 x x 0 10 fi gt SetParameter 0 1
51. er 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 40 file macro8 cxx e Line 3 6 A simple function to ease the make up of lines Remember that the class TF1 inherits from oF WN FH 7 2 Toy Monte Carlo Experiments 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 function and the sign
52. eters Such a model may simply state the current J 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 E 0 6 II gt 0 5 0 4 0 3 i m Model Figure 1 1 Measured data points with error bars and fitted quadratic function
53. fi gt SetParameter 1 1 f1 gt Draw in PyTHON becomes import ROOT f1 ROOT TFi f2 O sin 1 x x 0 10 fi SetParameter 0 1 fi SetParameter 1 1 fi 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 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 Oo o 1octURcctr NNNFP RP RP BP eRe Pe RP NOrovomanronwrk wnrdr O OANA TIKEWN He NNNNRPRFP RP eR BP RP eRe Re Q2 l2rn2 c o AN DA KRWN Fr OO e UNBE 8 ROOT in PYTHON Here is the C version void TGraphFit Draw a graph with error bars and fit a function to it 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 6 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 Flo
54. h from array import array from ROOT import TCanvas TGraphPolar ipt range 0 npoints r array d map lambda x xx 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 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 0 NOQ AUNE OMAN aK ct Be RP RP eee sone uone 0 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 TH1F 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 im
55. he result TCanvas ci 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 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 double amp 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 Surf1 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
56. ht forward PYTHON version relying on the ROOT class TMath usr bin env python the first line allows execution directly from the linux shell 34 macro3 as python script 48 OANA Cc 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 O AN OTK WNH E Nou wndr 8 1 PyROOT Author G Quast Oct 2013 dependencies PYTHON v2 7 pyroot last modified dk dt db HOH FH 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 grPi Draw AOL raw input Press ret to end gt file 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 mat
57. ial 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 complication 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 x 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 doublex pars return pars 0 TMath Gaus vars 0 pars 1 pars 2 pars 3 pars 4 vars 0 pars 5 vars O x vars 0 1 Monte Carlo simulation means that random numbers play a role here which is as crucial as in games of pure chance in the Casino of Monte Carlo 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 7 Functions and Parameter Estimation int macro8 gROOT gt SetStyle Plain gStyle gt SetOptTitle 0 gStyle gt SetOptStat 0 gStyle gt SetOptFit 1111 gStyle gt Se
58. ile 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 oF WN A co 2o 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 32 tay At J 5 8 64 bit long L p 32 bit unsigned int i eE 64 bit unsigned long l floating point 2200 Hoal ui 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 content you can easily create some files
59. is 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 Use Status to set the return value of TTree Process The return value is currently not used Li 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 111 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 ie 6 File I O count number of entries events fNumberOfEvents 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 DE tNow Set tNow Print printf Number of Events i elapsed time Ai sec rate Ag evts sec n fNumberOfEvents tNow Convert tBegin Convert float fNumberOfEvents
60. is 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 read the data back from a ROOT n tuple
61. le 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 ocopyright 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 downleftarrow corner topbar fltbar arcbar L bottombar T uparrow gt rightarrow 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 T P A 7 CO 23 vx m Oo 2 v A a e exe e Upper case Alpha Beta Gamma Delta Epsilon Zeta Eta Theta lota
62. les for this macro TF1 nPDF probability density function for the fit TNtuple inpdata n tuple to hold input data Info for initialisation of MINUIT int NFitPar 3 specify number of fit parameters int initialize fit TMinuit minfit initialisation of FIT Define a probability density function normalized to N exponential in range 0 5 plus off set nPDF new TF1 eplusconstPDF 2 1 1 exp x 0 exp 5 0 lt EOISE21 68 235 3 0 5 5 input data come from a file and are stored in an NTuple inpdata new TNtuple InputData InputData x cout lt lt nNtuple contains lt lt inpdata gt ReadFile expob dat lt lt entries n n minfit gt DefineParameter 0 Param index tau Param name 1 Param initial value 0 1 Param initial error 0 for fix marameter 0 Param lower limit 0 Param upper limit minfit gt DefineParameter 1 of set 0 5 0 1 0 1 minfit gt DefineParameter 2 norm 150 10 0 0 return 0 i The function to be minimized called by MINUIT must have this form 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 91 92 7 Functions and Parameter Estimation void the_function Int_t amp npar Opti
63. lines in the same TLatex object 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 i 30 20 a 10 FU i Maximum F ee Deviation L e L L L L L L L L L L L L L L q 2 4 6 8 10 lenght cm Figure 3 1 Your first plot with data points A version of the same macro in PYTHON is available in the file macro1 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 B 1 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 e among dots triangles crosses or stars An alternative set of names
64. ll with weight Fill Double t x Double t w draw Draw and DrawClone the mathematical function define function in TFormula syntax predefined functions define function via pointer evaluate at x TFi const char name const char formula Double t xmin 0 Double t xmax 1 gaus expo pol0 pol9 landau TFi const char name void fcn Double t xmin Double t xmax Int t npar Eval Double t x Double t Derivative Double t x Double t Integral Double t a Double t b Double t GetRandom SetParameter Int t i Double t parvalue SetParameters const Double t params gr gt Fit TFi or h gt Fit TF1 f Double_t GetParameter Int_t i Double_t GetParError Int_t i calculate derivative calculate integral a to b get random number set parameter i set parameters fit function f to graph gr or histogram h get parameter i get error on parameter i TRandom3 the calss used to generate random sequences of high quality alize random generator with random seed TRandom 0 TRandom UInt t seed UInt t GetSeed initialize random generator with seed get actual seed uniform random number 0 x1 uniform random number x1 x2 random number from binomial distribution random Poisson number random number from exponential random number from Gaussian distribution pre initialised random generator configuring the graphics canvas create canvas of size ww x wh subdivide into pads chage to subp
65. lled 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 JT 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 Process MySelector C4 include MySelector h include lt TH2 h gt lThe 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 71 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 xh pot x h cur h temp h pres h resistance void MySelector Begin TTree treex The Begin function is called at the start of the query When running with PROOF Begin i
66. 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 a 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 extended 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 machind 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 RooF iLab 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 instruction
67. mns 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 correlated 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 4 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 functionsettings 1 3 3 grid y logscale 0 savegraphic roofilab eps saverfl data rfl plot lables title averaging measurements 4 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
68. n 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 Qoo I1o0 Ot s C ND ho Ro Qc oo 1o00 0 4 0t r 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 Ly f eventually start Proof Lite on cores TProof Open workers 4 ch gt SetProof ch gt 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 C 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 The histograms are h
69. n file new TFile my rootfile root Get the Histogram out THiF h in_file GetObjectChecked my_histogram TH1F 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 Get bjectChecked 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 e 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 conditions of pressure and temperature
70. 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 BO Nn OMAN ao cct W Q2 Q0 Q9 Q2 Q9 C2 h2 b2 b2 bh2 bh2 h2 b2 h2 b2 l2 KR HP RP RP RP rR RP O0t 4 Q l2n20du oco 1IoO0c0 4c r t5r Lnr o oo 1oc cguct c 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 l 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 sectior 3 4 some more code fragments will be sho
71. nc x npar apar a apar 0 m apar 1 b apar 2 f Double 0 f a 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 curFuncV curYExcurYE 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 Li 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 un 62 f 0 calcChi2 npar apar 63 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 2x 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 l ierflg 72 73 gt Set starting values and step sizes for parameters
72. npar 0 myMinuit mnemat buf npar retrieve error matrix emat np array buf reshape npar npar provide formatted output of results print An print MINUIT fit completed print fcn minimum 3g amin error code ierflg status icstat print Results t value error corr mat for i in range 0 npar print hs t 10 3e 1le name i finalPar i finalParErr il for j in range 0 i print 3g emat i j 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 o 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 loc 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 R
73. onal Double_t derivatives array optional Double_t amp function_val the function value Double_t par the array of parameters Int_t internal_flag internal flag calculate extended negative log likelihood function_val 0 pass on parameters to PDF nPDF gt SetParameters par 0 par 1 par 2 calculate log L i e loop over ntuple float xntrow for int i 0 i lt inpdata gt GetEntries i inpdata gt GetEntry i ntrow inpdata gt GetArgs function val log nPDF gt Eval ntrow 0 add a Poission term to take into account normalisation function val inpdata GetEntries log par 2 par 2 function val 2 mult by 2 as usual in ROOT i e Dchi2 D logL void end of fit TMinuit minfit compare data with fit at the end TCanvas cfit new TCanvas cfit results 10 10 400 400 cfit cd inpdata gt Draw x TH1F ht htemp access to histogram ht SetLineWidth 2 ht SetLineColor kBlue PDF must be scaled to take into account bin width ht Eval nPDF ht Scale ht GetBinWidth 1 ht SetName Data ht SetTitle Fit to data x N_ Events ht DrawClone C SAME end of user code P F K K K K K K K K K K k K kK K K ok ok OR OK KKK K ok ook oe ok OK K K I OI e oko K K K K aI K a K ok a ale K ale ad ale a K K K ok K ok ak ok ak ak ake ak ake ak ok start of general code F
74. ooStats 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 of your interaction with ROOT 53 APPENDIX ee 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 ASCII 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
75. plementation 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 x 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 usr bin env python 4 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 Set parameters and function to fit a list with convenient names name a m b 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 fitfu
76. put 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 in 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 4 fit m x b 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 4 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 colu
77. r way Make sure you have the file slits 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 xx function code in C x double single double xx double spar double const pi 4 atan 1 return pow sin pixpar 0 x 0 pi par 0 x 0 2 double nslitO double x double xpar double const pi 4 atan 1 return pow sin pixpar 1 x 0 sin pixx 0 2 1All 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 xpar return single x par nslitO x par This is the main program void slits float r ns request user input cout lt lt slit width g scanf f amp r cout lt lt of slits scanf f amp ns cout lt lt interference pattern for lt lt ns lt lt slits width distance lt lt r lt lt endl define function and set options x TF1 Fnslit new TF1 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 SetParame
78. re chi2 and binned log likelihood methods pull int n_toys 10000 int n_tot_entries 100 41 co 12o00 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 63 7 Functions and Parameter Estimation int nbins 40 bool do_chi2 true gROO0T SetStyle Plain TString method prefix Log Likelihood if do chi2 method prefix chi 2 Create histo TH1F h4 new TH1F method_prefix h4 method_prefix Random Gauss nbins lt 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 TH1F method_prefix pull method_prefix pull from gaus fit 50 4 4 Make nice canvases TCanvas cO new TCanvas method_prefix Gauss method_prefix Gauss lt 0 0 320 240 c0 SetGrid Make nice canvases TCanvas ci new TCanvas method_prefix Result method_prefix Sigma lt 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 gt Fill gRandom gt Gaus
79. reen but rather ugly on paper If 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 example in
80. ro1 cxx Let s comment it in detail 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 z 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 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 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 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 A imposes the drawing of the Axes P imposes the drawing of the graphs markers E imposes the drawing of the graphs markers erro
81. rs e Line 38 define a mathematical 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 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
82. s 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 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 in
83. s 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 lt gt 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 gt Uniform 0 10 gRandom gt Gaus 1 0 01 temp gRandom gt 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 2x 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 c str RECREATE cond data Write of
84. s only called on the client The tree argument is deprecated on PROOF 0 is passed TString option GetOption some time measurement tBegin Set printf Begin of Job Wy tBegin Print void MySelector SlaveBegin TTree treex 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 GetOption book some histograms h_pot new THiF 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 TH1F 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 fOutput gt AddAll gDirectory gt 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 and is available via the fObject pointer Th
85. sed above The new part is the user defined minimisation function the function made known to the minimiser via the method SetFCN void f Lines 6 27 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 Note that the main program at the bottom must be called first as it sets up the minimizer Lines 31 47 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 Lines 49 58 procedure called upon 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 Line 61 the general part of the code starts here it contains some helper functions to extract and display information from the class TMinuit and the overall control of the different steps of the fit Lines 140 end Main program
86. 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 gSystem 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 oF WN 0 JO 0t 4 CQ hl n2 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 w
87. 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 TMinuit set DeltaChi2 value for error determination gMinuit gt SetErrorDef float DeltaChi2 get coutour line as TGraph TGraph gMinuit Contour npoints int parl int par2 64 Contents 1 Motivation and Introduction 3 tI Welcome to ROOT i nuek Rom ek ROA ORS biar Ae Soo RC UP ROG wedec chim dos 4 2 ROOT Basics 4 5 2449 xk x ow X X 4 ee a XR Ue RGU A YOX G9 4 OR exo e e a Ces 5 21 ROOT ascalculatof sii partage da aa 24 6 BRE Gb ew Re EEE EE LEE SEE eA EA 5 2 2 ROOT as Function Plotter a a a a a a a a 6 2 3 Controlling ROOT pai sek y sm y E A Up a A O e Er Y 7 2 4 Plotting Measurements ooa m m eos 8 2 5 Histogramsin ROOT se ii eios Ps ek a AES Get AA Xe AOE eor he AR Ro 8 26 Interactive ROO L e 4 goi a ee ume eR Ref Raw GR Rok we OR R GR Dee dvo unen 9 2 ROOT Beginners FAQ zd moo o og ERROR Rex gp ON RP we s 10 ODDO ME 10 2 7 2 Configure ROOT at start up ee ees 10 2 1 3 ROOT command history 2e m 11 2 7
88. tStatX 89 gStyle gt SetStatY 89 gStyle gt SetStatBorderSize 0 TF1 parabola parabola 0 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 THIF 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 x 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 gt 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 gaussian SetParamet
89. tant tools in statistical 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 F 0 22 2 E 3 E gag and select SetLineAttributes then left Sls CM 55 4 E click on Set Parameters This gives ac Immediate preview cess to a panel allowing you to interactively change the parameters of the function as Beet apply ok Cancer shown in Figure 2 4
90. tart 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 TH1Fx bkg_h new THiF exp h Exponential Histo 50 0 10 simulate the measurements TRandom3 rndgen for int imeas 0 imeas lt 4000 imeas exp h Fill rndgen Exp 4 if imeas 4 0 gaus hi 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 TH1Fx histos 4 sig h bkg h gaus hi gaus h2 for int i 0 i lt 4 i histos i J gt S
91. ter 1 ns Fnslit gt 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 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 3 5 e 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 z 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 If you like
92. the code with gt g o ExampleMacro_GUI exe ExampleMacro_GUI root config cflags libs and execute the program with gt ExampleMacro_GUI exe 18 OANA TKWNH Pe RR wn RR O D00ayw0NR 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 Zlg 1g read only 2 first columns into X Y e lg Mlg 1g read only 3 first columns into X Y and EY e WMlg lg VAlg lg 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
93. tter Robust 1 00 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 F 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 s No drawing file name and target directory to store the image T 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 of all methods and classes involved in generating the plot This is a very valuable source of information for your own macros which you will hopefully write after having worked through this tutorial Update Et Reset close Using the interactive capabilities of ROOT is very useful for THIF h LIB Minit MIGRAD itr O Pm 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 further on this just b
94. uble y_errs n_points 5 5 4 7 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 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 0 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 tsplitline Maximum iDeviation text DrawClone mycanvas Print graph with law pdf ifndef CINT int main o1 macr endif file mac
95. umw2 Veryx 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 yn SN o o IIT a a BD oO o o o M e o o o o Gaus Histo 1 Gaus Histo 2 m S AO ITA 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 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 Draw hist bkg h Draw SameHist sig h Draw SameHist Divide THiF dividend new THiF 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 gt GetPad 1 gt SetRightMargin 01 gaus_hi gt DrawNormalized Hist gaus_h2 gt DrawNormalized HistSame c_divide gt cd 2 dividend gt GetYaxis gt SetRangeUser 0 2 49 c_divide gt GetPad 2 gt SetGridy c_divide gt GetPad 2 gt SetRightMargin 01 dividend
96. unction to access info on fit and print it void printFit TMinuit minfit using namespace TMath using namespace std char line 200 Double_t vline 25 Double_t eline 25 cout lt lt n n n cout lt lt Fitted parameters lt lt endl cout lt lt NO NAME VALUE ERROR lt lt endl for int n 0 n lt minfit gt fNu n sprintf line 14d 49s 112 58 8 3g g n 1 const char minfit gt fCpnam n minfit gt fU n minfit gt fWerr n cout lt lt line lt lt endl cout lt lt Correlation Matrix lt lt endl cout lt lt NO GLOBAL for Int_t id 1 id lt minfit fNu id cout lt lt Cid cout lt lt endl for int i 1 i lt minfit fNu i int ix minfit gt fNexofi i 1 int ndi ix i 1 2 for Int_t j 1 j lt minfit fNu 4 j int m Max i j int n Min i j int ndex m x m 1 2 n int ndj j j 1 2 vline j 1 minfit gt fVhmat ndex 1 sqrt fabs minfit gt fVhmat ndi 1 minfit gt fVhmat ndj 1 sprintf line 72d 18 38 ix minfit fGlobcc i 1 cout lt lt line for Int_t it 1 it lt minfit gt fNu it sprintf line 6 3f vline it 1 cout lt lt line 44 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
97. used and so on In a well written complete example 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 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 TH1F h new TH1F h example histogram 100 0 5 root 4 for int i 0 i lt 1000 i h Fill efunc GetRandom root 5 h gt Draw QO AUNE 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 h namely pseudo random numbers generated Entri 1000 B D E Mean 0 3719 with the method TF1 GetRandom which in E E oser turn uses an instance of the ROOT class TRandom cr
98. 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 8 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 coo 1ocU 5 c ctf r Boo Ne oO QO 4 0 N nm CHAPTER 2 n 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 applications But
99. wn allowing you to use the system compiler to compile macros for more efficient execution or turn macros into stand alone applications linked against the ROOT libraries 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 Builds a graph with errors displays it and saves it as image x 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 macroi 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 do
100. x td 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 gt Uniform 250 350 get temperature pres gRandom gt Uniform 0 5 1 5 get pressure cur pot 10 0 05 temp 300 0 2x pres 1 calculate current add some random smearing measurement errors pot gRandom gt Gaus 1 0 01 1 error on voltage temp gRandom gt Gaus 0 0 3 0 3 absolute error on temperature pres gRandom gt Gaus 1 0 02 1 error on pressure cur gRandom Gaus 1 0 01 1 error on current 30 25 26 27 28 29 30 31 32 33 OMAN ano WN HF Rbk O00XJODOGad gt aUJNRAO 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 simple laws and an additional Gaussian smearing Th
101. you can easily extend the example 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 QO 4 0 2 rn 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 1s 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
Download Pdf Manuals
Related Search
Related Contents
Smeg FA561X Instruction Manual HSM2300/2204 v1.0 Installation Instructions Manual de Usuario CR4300/2 OK - Utax Ce livret de compétences PDF Format - Connecting Healthcare Providers Work Planning and Budgeting Tool User`s Manual Haier HRF- 329AA User's Manual 回 インテリアカ丿ヾー F30系 BMW3 Descarga Copyright © All rights reserved.
Failed to retrieve file