ROOT Tutorials Exercises for Desy C++ School

Topics

This tutorial aims to provide a complement to the lecture shown at the Desy C++ School, November 2013. This tutorial is focus on data analysis in ROOT using Tree's and Proof. It does not cover other features of ROOT such as histogramming or fitting techniques. The main features of ROOT are presented: histogramming, data analysis using trees and advanced fitting techniques.

Material for the course

The slides of the lectures are available in electronic form from the school Agenda page. As complementary material, one can look at
  • ROOT Primer Guide, available in pdf, html or epub format. This introductory guide illustrates the main features of ROOT, relevant for the typical problems of data analysis: input and plotting of data from measurements and fitting of analytical functions.
  • ROOT user guide. It can be downloaded in various format (or only individual chatters) from here.
  • RooFit User Guide, available in pdf format. A coincide RooFit quick start guide is also available here.
  • A tar file with all the exercise solutions (all the ROOT macro required) is available here

Introduction

We will focus first on simpler exercises. The solution of the exercise is often to write a running ROOT macro. Two levels of help will be provided: a hint and a full solution. Try not to jump straight to the solution even if you experience some frustration. The help is organised as follow:

Here the hint is shown.

Here the solution is shown.

Some points linked to the exercises are optional and marked with a Pointing hand icon: they are useful to scrutinise in more detail some aspects. Try to solve them if you have the time.

Setting up ROOT

ROOT is installed in the virtual machines prepared for the course. It should be automatically available from the Terminal. If not, one should run the fallowing lines (or put in the default login shell script):

export ROOTSYS=/usr/local/ROOT
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
. $ROOTSYS/bin/thisroot.sh

The version of ROOT available in the school virtual machines which should be 5.34.11.

Setting up ROOT pre-release version 6

Some exercises require some new functionality of ROOT, which will be available only in the new version 6, expected for the end of the year. In order to solve for this exercise and try the new version, you need to set-up a different environment variable for $ROOTSYS.

ROOT I/O and Trees

Set of Exercises working with the Trees in ROOT. First will start with an exercise on the I/O of ROOT by storing and reading an histogram from a file

Exercise 1: Writing and Reading Histogram from a file

Open a file then create a simple histogram, for example an histogram generated with exponential distribution. Fit it and write it in a file. Why the ROOT Canvas does not show the histogram ? Do you know what to do to have the histogram displayed ?

Use TFile::Open to open the file or just create a TFile object. Call TH1::Write to write the histogram in the file after having filled it.

#include "TFile.h"
#include "TH1.h"
#include "TRandom.h"

void histogramWrite() { 

   TFile f("histogram.root","RECREATE");

   TH1D * h1 = new TH1D("h1","h1",100,0,10); 
   for (int i = 0; i < 10000; ++i) 
      h1->Fill(gRandom->Exp(5) ); 

   h1->Fit("expo");
   h1->Draw();

   f.Write("h1"); 
   f.Close();
}
The histogram is not shown, becausem when the file is close, it is automatically deleted.

Now read the histogram from the file and plot it.

Create a file object (or call TFile::Open) and then TFile::Get

void histogramRead() { 

   TFile * file = new TFile("histogram.root");

   TH1 * h1 = 0;
   file->GetObject("h1",h1);
   // you can also use nut you need to cast if you compile the code
   //TH1 * h1 = (TH1*) file->Get("h1");

   h1->Draw();
}

Pointing hand You can also use the TBrowser to open the file and display the histogram.

Pointing hand What is going to happen if you delete the file after having retrieved the histogram from the file ?

Exercise 2: Creating a ROOT Tree

Create a simple ROOT tree containing 4 variables (for example x,y,z,t). Fill the tree with data (for example 10000 events) where x is generated according to a uniform distribution, y a gaussian and z an exponential and t a Landau distribution. Write also the tree in the file.

Create the Tree class and then declare each branch for each simple variables as described in the lecture slides. See the documentation of TTree::Branch on how to declare branches for simple variables (fundamental types). You can also look at the tutorial tutorials/tree/tree1.C as example, on how TTree:Branch is used to define the tree branches containing the variables. Alternatively you can use also the TNtuple class. An example for the tuple class is the tutorial tutorials/hsimple.C.

#include "TRandom.h"
#include "TFile.h"
#include "TTree.h"

void SimpleTree(int  n = 10000) { 

// open a file
   TFile f("SimpleTree.root","RECREATE");

   TTree * data = new TTree("tree","Example TTree");
   double x, y, z, t; 
   data->Branch("x",&x,"x/D");
   data->Branch("y",&y,"y/D");
   data->Branch("z",&z,"z/D");
   data->Branch("t",&t,"t/D");

// fill it with random data
   for (int i = 0; i<n; ++i) {       x = gRandom->Uniform(-10,10); 
      y = gRandom->Gaus(0,5);
      z = gRandom->Exp(10);
      t = gRandom->Landau(0,2);
      
      data->Fill();
   } 
   data->Write();
   f.Close();

}

Afterwards having saved the file, re-open the file and get the tree. Plot each single variable and also one variable versus another one (for example x versus y) using TTree::Draw. You can also use the TBrowser

Exercise 3: Creating a ROOT Tree containing a collection of LorentzVector's

Create a TTree containing a collection of 4D LorentzVectors. For example one could generated a list of pions (let's suppose 20/event in average) with an exponential distribution in pt and a uniform distribution in phi and Eta.

Measure the time to write a TTree with 100000 events.

Try to generate the tree in split mode (default) and no-split mode. Use TTree->Print() to see the content of the generated trees. Did you see a difference in performances in writing when using or not using splitting ?

Create the Tree class and then define a branch containing a std::vector<ROOT::Math::XYZTVector> > ( or if you prefer a std::vector ). In this second case you need to generate the dictionary for the type written in the tree. You can do this by adding at the beginning of the macro these following lines
#ifdef __MAKECINT__ 
#pragma link C++ class std::vector<TLorentzVector>+;
#endif
For creating a branch not split, use a plot level of zero, while for splitting use 99 (the default value). The split level is passed as last parameter in TTree::Branch (see the reference documentation). For measuring the writing time you can use for example the TStopwatch class. Before the loop you create the TStopwatch class and you call TStopwatch::Start(). At the end of the macro you call TStopwatch::Stop() and then TStopwatch::Print() to get the elapsed time. You can also use the TTreePerfStats class (see its reference documentation), which will make also a summary performance graph.

//
// Example showing how to write and read a std vector of ROOT::Math LorentzVector in a ROOT tree. 
// a variable number of track Vectors is generated 
// according to a Poisson distribution with random momentum exponentially distributed in pt and uniformly distributed 
// in phi and eta. 
// distributions are displayed  in a canvas. 
//
// To execute the macro type in: 
//
//   root[0]: .x  WriteVectorCollection.C




#include "TRandom2.h"
#include "TSystem.h"
#include "TStopwatch.h"
#include "TFile.h"
#include "TTree.h"
#include "TLorentzVector.h"
#include "TTreePerfStats.h"
#include <iostream>

#include "Math/Vector4D.h"
#include "Math/VectorUtil.h"


// if using TLorentzVector we need to generate the dictionary
// ROOT has already dictionary for vector<XYZTVector>
// #ifdef __MAKECINT__ 
// #pragma link C++ class std::vector<TLorentzVector>+;
// #endif


using namespace ROOT::Math;



void WriteVectorCollection(int n, int splitlevel = 0) { 


  // to load dictionary library for std::vector<XYZTVector>
  gSystem->Load("libGenVector");

  TRandom2 R; 
  TStopwatch timer;


  TFile f1("vectorCollection.root","RECREATE");

  // create tree
  TTree t1("t1","Tree with new LorentzVector");

  std::vector<ROOT::Math::XYZTVector>  tracks; 
  std::vector<ROOT::Math::XYZTVector> * pTracks = &tracks; 

  // std::vector<TLorentzVector>  tlv; 
  // std::vector<TLorentzVector> * pTLV = &tlv;

  t1.Branch("tracks",&pTracks,32000,splitlevel);

  double M = 0.13957;  // set pi+ mass


  timer.Start();
  for (int i = 0; i < n; ++i) {      int nPart = R.Poisson(20);     pTracks->clear();
    pTracks->reserve(nPart); 
    for (int j = 0; j < nPart; ++j) {       double pt = R.Exp(10);       double eta = R.Uniform(-3,3);       double phi = R.Uniform(0.0 , 2*TMath::Pi() );       PtEtaPhiMVector v(pt,eta,phi,M);        XYZTVector q(v.X(), v.Y(), v.Z(), v.E());   // use conversion operator between vectors       //TLorentzVector q(v.X(), v.Y(), v.Z(), v.E() );       // fill track vector       pTracks->push_back(q);
      
    }
         

    t1.Fill(); 
  }

  f1.Write();
  timer.Stop();
  std::cout << " Time for writing Tree with collection of LorentzVector " << timer.RealTime() << "  " << timer.CpuTime() << std::endl; 

  t1.Print();

}

Try now to use a TClonesArray and/or a TObjArray and measure the time to create the tree. Did you see an increase/decrease in performances ?

Now you must add in the Branch the TClonesArray (or TObjArray object). Remember that for the TClonesArray you must construct them by passing the class name of the contained object. You must also use only classes deriving from TObject. Thus you can only use TLorentzVector and not the template ROOT::Math::LorentzVector class. Remember you need to use a special syntax to create the new object and to fill the TClonesArray. See the TClonesArray documentation

//
// Example showing how to write and read a std vector of ROOT::Math LorentzVector in a ROOT tree. 
// a variable number of track Vectors is generated 
// according to a Poisson distribution with random momentum exponentially distributed in pt and uniformly distributed 
// in phi and eta. 
// distributions are displayed  in a canvas. 
//
// To execute the macro type in: 
//
//   root[0]: .x  WriteVectorCollection.C




#include "TRandom2.h"
#include "TStopwatch.h"
#include "TFile.h"
#include "TTree.h"
#include "TLorentzVector.h"
#include "TTreePerfStats.h"
#include <iostream>
#include "TClonesArray.h"


#include "Math/Vector4D.h"




using namespace ROOT::Math;



void WriteArrayCollection(int n, int splitlevel = 0) { 



  TRandom2 R; 
  TStopwatch timer;


  TFile f1("arrayCollection.root","RECREATE");

  // create tree
  TTree t1("t1","Tree with new LorentzVector");

  //N.B. one must specify the name of the contained class in the TClonesArray constructor
  TClonesArray * pTracks = new TClonesArray("TLorentzVector");

  //TObjArray * pTracks = new TObjArray();


  t1.Branch("tracks",&pTracks,32000,splitlevel);

  double M = 0.13957;  // set pi+ mass


  timer.Start();
  for (int i = 0; i < n; ++i) {      int nPart = R.Poisson(20);     pTracks->Clear();
    for (int j = 0; j < nPart; ++j) {       double pt = R.Exp(10);       double eta = R.Uniform(-3,3);       double phi = R.Uniform(0.0 , 2*TMath::Pi() );       PtEtaPhiMVector v(pt,eta,phi,M);        new ( (*pTracks)[j] ) TLorentzVector(v.X(), v.Y(), v.Z(), v.E() );       //pTracks->Add( new TLorentzVector(v.X(), v.Y(), v.Z(), v.E() ) );
      
    }
         

    t1.Fill(); 
  }

  f1.Write();
  timer.Stop();
  std::cout << " Time for writing Tree with array of LorentzVector " << timer.RealTime() << "  " << timer.CpuTime() << std::endl; 

  t1.Print();

}

Exercise 4: Read a ROOT Tree containing a collection of LorentzVector's

Using TTree::Draw plot:

- the number of tracks per event in an histogram with 50 bins between 0 and 50. - a profile plot showing the pt of the number of tracks vs the event number - a candle plot with the pt of the first 5 tracks when the number of tracks is larger or equal 5.

- To plot the size of the collection use the special keyword "@". - To get the tree entry number use the special keyword "Entry$". - To make a profile plot use the graphics option "prof" (3rd parameter in TTree::Draw). - To make a candle plot use the graphics option "candle". See also TTree::Draw documentation

Using some C/C++ code to plot the Px distribution of the tracks. Measure the time to read the tree and compare in case the tree was generated with splitting or not splitting. Plot also the invariant mass of all 2-tracks combinations. This you cannot do with TTree;:Draw.

Read the tree, by getting the pointer from the file and then loop on its entry. before looping declare the object you want to read and pass its pointer address (i.e. Object **) to TTree::SetBranchAddress. Loop on all the vector combination and add them together and get the invariant mass of the sum of the two-vector combinations.

//
// Example showing how to write and read a std vector of ROOT::Math LorentzVector in a ROOT tree. 
// In the write() function a variable number of track Vectors is generated 
// according to a Poisson distribution with random momentum uniformly distributed 
// in phi and eta. 
// In the read() the vectors are read back and the content analyzed and 
// some information such as number of tracks per event or the track pt 
// distributions are displayed  in a canvas. 
//
// To execute the macro type in: 
//
//   root[0]: .x  vectorCollection.C




#include "TStopwatch.h"
#include "TFile.h"
#include "TTree.h"
#include "TH1.h"
#include "TCanvas.h"
#include "TMath.h"
#include "TLorentzVector.h"
#include "TTreePerfStats.h"
#include <iostream>

// CINT does not understand some files included by LorentzVector
#include "Math/Vector4D.h"


// #ifdef __MAKECINT__ 
// #pragma link C++ class std::vector<TLorentzVector>+;
// #endif


using namespace ROOT::Math;




void ReadVectorCollection(const char * fileName = "vectorCollection.root") { 



  TH1D * h1 = new TH1D("h1","Number of track per event",51,-0.5,50.5);
  TH1D * h2 = new TH1D("h2","Track Px",100,0,100);
  TH1D * hinv = new TH1D("hinv","Track invariant mass",100,0,100);


  TFile f1(fileName);

  // create tree
  TTree *t1 = (TTree*)f1.Get("t1");

  std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * pTracks = 0;
  t1->SetBranchAddress("tracks",&pTracks);

  TStopwatch timer; 
  timer.Start();
  int n = (int) t1->GetEntries();
  std::cout << " Tree Entries " << n << std::endl;    for (int i = 0; i < n; ++i) {      t1->GetEntry(i);
    int ntrk = pTracks->size(); 
    h1->Fill(ntrk);
    for (int j = 0; j < ntrk; ++j) {        XYZTVector v = (*pTracks)[j];        h2->Fill(v.X());
      // compute invariant mass
      for (int k = j+1; k < ntrk; ++k) {           XYZTVector q = (*pTracks)[k];           double minv = (v+q).M();           hinv->Fill(minv);
      }
    }
  }


  timer.Stop();
  std::cout << " Time to read Tree " << timer.RealTime() << "  " << timer.CpuTime() << std::endl;       TCanvas *c1 = new TCanvas("c1","demo of Trees",10,10,600,800);   c1->Divide(1,3); 
  
  c1->cd(1);
  h1->Draw();
  c1->cd(2);
  h2->Draw();
  c1->cd(3);
  hinv->Draw();
}

Try now to plot the invariant mass of the 2-track combinations for all tracks with a pt > 3 GeV using a proxy function (see TTree::MakeProxy) and/or or TTree::MakeClass or TTree::MakeSelector.

Using the proxy function. Create a file proxy.C as following:
TH1D *h1;

void proxy_Begin(TTree*) {
  // create here histogram
   h1 = ..
}

double proxy() {
   // put here user code

   // for example 
   int ntracks = tracks->size(); 
   for (int i = 0; i < ntracks; ++i) { 
     double pt = tracks[i].Pt()
     if (pt > something) { 
     
       }
      }
   }
   return 0;
}

void proxy_Terminate() {
   // draw the histogram
  h1->Draw();
}
Note that when using a proxy function the tree must be generated in split mode to have access to all information. This is a limitation. Also you cannot use weight/cut expression in TTree::Draw.

Using MakeClass/MakeSelector

Generate the skeleton code using TTree::MakeClass or TTree::MakeSelector. Note that now to have the full access to the vector the tree must be generated in non-split mode. Currently MakeClass/MakeSelector do not work if this particular tree is generated in split mode.

Solution for proxy case:
TH1D *h1;

void proxy_Begin(TTree*) {
   h1 = new TH1D("h1","inv mass",100,0,100);
}

double proxy() {
   int ntracks = tracks->size(); 
   for (int i = 0; i < ntracks; ++i) {        for (int j = i+1; j < ntracks; ++j) {           if (tracks[i].Pt() > 3 && tracks[j].Pt() > 3)  
            h1->Fill( (tracks[i] + tracks[j]).M() );
      }
   }
   return 0;
}

void proxy_Terminate() {
  h1->Draw();
}
Solution for MakeClass:
<span class='twikiAlert'>
     Error: File attachment at https://twiki.cern.ch/twiki/pub/Main/ROOTDesyTutorial2013/VectorCollectionClass.C,%PARAM2% does not exist 
</span>
Solution for Selector:
<span class='twikiAlert'>
     Error: File attachment at https://twiki.cern.ch/twiki/pub/Main/ROOTDesyTutorial2013/VectorCollectionSelector.C,%PARAM2% does not exist 
</span>

Exercise 2: Creating a ROOT Tree containing an EventData object

Create a ROOT tree which contains an EventData object. The EventData object is defined in the file below

#ifndef EventData_h
#define EventData_h


#include <vector>
#include "Math/Vector4D.h"
#include "Math/Vector3D.h"


class Particle {
public:
   Particle() { //memset(fTags, 0, sizeof(fTags));
 }
  
   
   
   ROOT::Math::XYZVector  fPosition;   // vertex position
   ROOT::Math::PtEtaPhiMVector fVector;     // particle vector 
   int  fCharge;        // particle charge
   int fType;           // particle type (0=pho, 1 ele, 2...)
};

class TF1; 

class EventData {
public:

   std::vector<Particle> fParticles; // particles of the event
   int fEventSize; // size (in bytes) of the event


   void SetSize() {
      fEventSize = sizeof(EventData) + fParticles.size() * sizeof(Particle);
   }
   void Clear() {
      fParticles.clear();
   }

   void AddParticle(const Particle& p) { fParticles.push_back(p); }

   void Generate();

   //ClassDef(EventData,1); // Data for an event
};


#ifdef __MAKECINT__ 
#pragma link C++ class Particle+;
#pragma link C++ class EventData+;
#pragma link C++ class std::vector<Particle>+;
#endif

#endif
   

The EventData object provides a method (Generate() ) to generate one event and it is implemented in the file below

#include "EventData.h"
#include "TRandom.h"
#include "TGenPhaseSpace.h"
#include "Math/Vector4D.h"
#include "TLorentzVector.h"

// generate the events

// parameters

int NTRACKS = 40; 
// parameter for pt distribution
double PtAvg = 20;   
int NTYPES = 8;
double masses[] = { 0, 0.0005, 0.105, 0.135, 0.139, 0.4937, 0.4976, 3.096 }; 
int charge [] = { 0, 1, 1, 0, 1, 1, 0, 0 }; 
double fractions[] = { 0.1, 0.12, 0.08, 0.05, 0.5, 0.1, 0.049 , 0.01 };  
double sigmax = 10.E-6; 
double sigmay = 10.E-6; 
double sigmaz = 5.; 

using namespace ROOT::Math;

ROOT::Math::PtEtaPhiMVector SmearVector(const ROOT::Math::XYZTVector & v) { 
   double x = v.X()*(1. + gRandom->Gaus(0, 0.1) );
   double y = v.Y()*(1. + gRandom->Gaus(0, 0.1) );
   double z = v.Z()*(1. + gRandom->Gaus(0, 0.1) );
   ROOT::Math::PxPyPzMVector tmp(x,y,z,v.M() );
   return PtEtaPhiMVector(tmp);
}


void EventData::Generate()  { 


   // get expected value for each type
   for (int i = 0; i < NTYPES; ++i) {        double nexp = fractions[i] * NTRACKS;        int np = gRandom->Poisson(nexp); 
      for (int j = 0; j < np; ++j) {           Particle p;           p.fPosition = XYZVector( gRandom->Gaus(0,sigmax), gRandom->Gaus(0, sigmay), gRandom->Gaus(0, sigmaz) ); 
         double pt = gRandom->Exp(PtAvg); 
         double eta = gRandom->Uniform(-3,3);
         double phi = gRandom->Uniform(-TMath::Pi(), TMath::Pi() ); 
         double mass = masses[i];
         p.fVector = PtEtaPhiMVector(pt, eta, phi, mass); 
         p.fType = i; 
         p.fCharge = charge[i];
         if (p.fCharge) { 
            int tmp = gRandom->Integer(2); 
            if (tmp == 0) p.fCharge = -1; 
         }
         // special case for decays
         if (i == 3 ) { 
            // pi0
            TGenPhaseSpace evt; 
            double m[2] = {0,0};
            TLorentzVector W( p.fVector.X(), p.fVector.Y(), p.fVector.Z(), p.fVector.E() );
            evt.SetDecay(W, 2, m);
            evt.Generate();
            TLorentzVector * v1 = evt.GetDecay(0); 
            TLorentzVector * v2 = evt.GetDecay(1); 
            Particle p1; 
            Particle p2; 
            p1.fPosition = p.fPosition; 
            p2.fPosition = p.fPosition; 
            p1.fCharge = 0;
            p2.fCharge = 0;
            p1.fType = 0; 
            p2.fType = 0;

            p1.fVector = SmearVector(XYZTVector(v1->X(), v1->Y(), v1->Z(), v1->E() )); 
            p2.fVector = SmearVector(XYZTVector(v2->X(), v2->Y(), v2->Z(), v2->E() )); 
            AddParticle(p1);
            AddParticle(p2);
         }
         if (i == 6) { 
            // Ks
            TGenPhaseSpace evt; 
            double m[2] = {0.139,0.139};
            TLorentzVector W( p.fVector.X(), p.fVector.Y(), p.fVector.Z(), p.fVector.E() );
            evt.SetDecay(W, 2, m);
            evt.Generate();
            TLorentzVector * v1 = evt.GetDecay(0); 
            TLorentzVector * v2 = evt.GetDecay(1); 
            double ctau = 2.6844 * p.fVector.Gamma(); 
            double disp = gRandom->Exp(ctau); 
            double dispX = disp * p.fVector.X()/p.fVector.P(); 
            double dispY = disp * p.fVector.Y()/p.fVector.P(); 
            double dispZ = disp * p.fVector.Z()/p.fVector.P(); 
            Particle p1; 
            Particle p2; 
            p1.fPosition = XYZVector( p.fPosition.X() + dispX,  p.fPosition.Y() + dispY,  p.fPosition.Z() + dispZ);
            p2.fPosition = p1.fPosition; 
            p1.fCharge = 1;
            p2.fCharge = -1;
            p1.fType = 4; 
            p2.fType = 4;

            p1.fVector = SmearVector(XYZTVector(v1->X(), v1->Y(), v1->Z(), v1->E() )); 
            p2.fVector = SmearVector(XYZTVector(v2->X(), v2->Y(), v2->Z(), v2->E() )); 
            AddParticle(p1);
            AddParticle(p2);
         }
         if (i == 7 ) { 
            // J/psi
            TGenPhaseSpace evt; 
            double m1[2] = {0.0005,0.0005};
            double m2[2] = {0.105,0.105};
            int tmp = gRandom->Integer(2);
            TLorentzVector W( p.fVector.X(), p.fVector.Y(), p.fVector.Z(), p.fVector.E() );
            if (tmp == 0)
               evt.SetDecay(W, 2, m1);
            else 
               evt.SetDecay(W, 2, m2);

            evt.Generate();

            TLorentzVector * v1 = evt.GetDecay(0); 
            TLorentzVector * v2 = evt.GetDecay(1); 
            Particle p1; 
            Particle p2; 
            p1.fPosition = p.fPosition; 
            p2.fPosition = p.fPosition; 
            p1.fCharge = 1;
            p2.fCharge = -1;
            p1.fType = 1; 
            p2.fType = 1;
            if (tmp == 1) {
               p1.fType = 2; 
               p2.fType = 2;
            }

            p1.fVector = SmearVector(XYZTVector(v1->X(), v1->Y(), v1->Z(), v1->E() )); 
            p2.fVector = SmearVector(XYZTVector(v2->X(), v2->Y(), v2->Z(), v2->E() )); 
            AddParticle(p1);
            AddParticle(p2);
         }
         else
            AddParticle(p);

      }
   }
}

Look at the macro defining the EventData class and the implementation generating the events. Write the macro creating the tree and filling with them with the events containing the EventData object.

// Prefer compiled:
#include "TTree.h"
#include "TFile.h"
#include "TRandom.h"
#include "TMath.h"
#include <vector>

#include "EventData.h"

void CreateEventTree(Long64_t numEvents = 200, int splitlevel = 99) {
   TFile* f = new TFile("eventdata_s99.root", "RECREATE");
   TTree* tree = new TTree("tree", "Tutorial tree");

   EventData* event = new EventData();
   tree->Branch("event", &event,32000,splitlevel);

   Particle p;

   for (Long64_t i = 0; i < numEvents; ++i) {       event->Clear();
      event->Generate();
      event->SetSize();

      tree->Fill();

   }

   tree->Print();
   tree->Write();
   delete f;
}

Look at the macro and try to understand. Run the macro to create and write the tree in the file.

Exercise 6: Analyzing a ROOT Tree

Read the tree containing the EventData class. The aim is to get the invariant mass distribution of the photons, of the opposite charged particles and of the opposite charged leptons (electrons and muons). You can write code to read the Tree yourself directly or use the proxy function or TTree::MakeClass or TTree::MakeSelector.

Now read the Tree with a macro and calculate the sum of all event sizes.

For example this is a suggestion to write the code to read the tree
  • Open the file using its file name in TFile::Open() and get the Tree. Remember to check if the file pointer is not null. If it is null means the file is not existing.
  • Get then a pointer to the tree.
  • Connect a Tree Branch with the Data Member.We have to somehow connect the branch we want to read with the variables used to actually store the data by calling TTree::SetBranchAddress().
  • Load the TTree data. For the analysis example we need to access the events' size, which is stored in the variable eventSize. But the TTree first needs to load the data for each event it contains. For that call TBranch::GetEntry(entry) in a loop, passing the TTree entry number from the loop index to GetEntry(). Again TBranch is the class name, but you obviously need to call it on an object. To know how many entries the tree contains, simply call TTree::GetEntries(). The branch is stored in eventSizeBranch.
  • In the same loop, compute the total size of all events (simply add the current event size to the total size)
  • Without the call to GetEntry(), the variables will not contain data. GetEntry() loads the data into the variables connected with the tree by the call to SetBranchAddress().
  • Access the Analysis Result. At the end of the loop, print the sum of all event sizes. This sum shows you the real power of a TTree: even though you can analyze large amounts of data (our example tree with 22MB is tiny!) ROOT needs just a few MB of your RAM, no matter how many events you analyze. Imagine what it would be like if you had to load all data into memory, e.g. using a simple vector<EventData>



Exercise 7: Chaining ROOT Trees.

Using the macro to create the EventData tree, we run few times (e.g. 2 or 3 times) using a different file name each time. Afterwards use then the TChain class to merge the trees.

See the example in the lecture slide on how to use TTree::Chain or its reference documentation.

Here is for example the macro to create several trees
#include "TRandom.h"
#include "TFile.h"
#include "TTree.h"

void SimpleTree(const char * filename= "tree.root") {

   TTree data("tree","Example TTree");
   double x, y, z, t;
   data.Branch("x",&x,"x/D");
   data.Branch("y",&y,"y/D");
   data.Branch("z",&z,"z/D");
   data.Branch("t",&t,"t/D");

// fill it with random data                                                                                                   
   for (int i = 0; i<10000; ++i) {
      x = gRandom->Uniform(-10,10);
      y = gRandom->Gaus(0,5);
      z = gRandom->Exp(10);
      t = gRandom->Landau(0,2);

      data.Fill();
   }
// write in a file                                                                                                            
   TFile f(filename,"RECREATE");
   data.Write();
   f.Close();

}
%

This are the few lines to create the TChain, that you can run directly from the prompt. You can also use wildcard's to chain many files

TChain chain("tree");
chain.Add("tree*.root")
chain.Draw("t")

Exercise 8: Using Tree Friends

Suppose we have the Tree with the vector of LorentzVector. We want now to add a new branch to this tree containing an std::vector< std::vector< double> > which contains the mass invariant of each track with respect all the other tracks. Make a new Tree. Read from the file the Tree used before and add as a friend to this tree. Plot then the invariant mass where at least one of the track has a pT larger than 3 GeV.

Here is the macro to create a second tree, containing the invariant mass


Here are the lines of codes to Draw the x of the first tree versus the x of the second tree with a selection depending on u and t. You can run these lines from the ROOT prompt.

TFile f("tree.root");   // to get  the first tree
 tree->AddFriend("tree_2","tree_2.root");         
tree->Draw("x:tree_2.x","t<100 && tree_2.u<6","COLZ");

Exercise 9: Using the TSelector class for analysing a TTree

Create the Selector for the EventData TTree made before. Use TTree::MakeSelector to create your own Selector class. The aim as in a previous exercise is to plot the invariant masses for: - the photons, - the opposite charged particles - for the muon and electrons

Inside the code of your Selector do the following:

  • book the histograms in the initialisation routine
  • fill the histogram in the Process function
  • draw the histogram in the Terminate function

Here is what you need to do, after having opened the file with the tree
tree->MakeSelector("MySelector.C");

The file MySelector.h and MySelector.C will be created. Add in MySelector.h, inside the class MySelector, a new data member, the histogram you want to create,

TH1D * h_t;

Edit then the file MySelector.C and add in MySelector::SlaveBegin the booking of the histogram.

h_t = new TH1D("h_t","t",100,0,100);

In MySelector::Process the filling of the histogram after calling TSelector::GetEntry()

GetEntry(entry);
h_t->Fill(t);

In MySelector::Terminate the drawing of the histogram.

After having saved the file run the selection by doing (for example from the ROOT prompt):

TFile f("tree.root");
tree->Process("MySelector.C+");

See the attached file MySelector.h and MySelector.C.
Topic attachments
I Attachment History Action Size Date Who Comment
C source code filec CreateEventTree.C r1 manage 0.6 K 2013-11-14 - 11:01 LorenzoMoneta  
Unknown file formatcxx EventData.cxx r1 manage 4.9 K 2013-11-14 - 11:01 LorenzoMoneta  
Header fileh EventData.h r1 manage 1.0 K 2013-11-14 - 11:01 LorenzoMoneta  
C source code filec ReadVectorCollection.C r1 manage 2.2 K 2013-11-14 - 10:04 LorenzoMoneta  
C source code filec SimpleTree.C r1 manage 0.6 K 2013-11-14 - 10:04 LorenzoMoneta  
C source code filec WriteArrayCollection.C r1 manage 1.8 K 2013-11-14 - 10:04 LorenzoMoneta  
C source code filec WriteVectorCollection.C r1 manage 2.0 K 2013-11-14 - 10:04 LorenzoMoneta  
C source code filec proxy.C r1 manage 0.4 K 2013-11-14 - 11:01 LorenzoMoneta  
Edit | Attach | Watch | Print version | History: r10 | r5 < r4 < r3 < r2 | Backlinks | Raw View | Raw edit | More topic actions...
Topic revision: r3 - 2013-11-14 - LorenzoMoneta
 
    • Cern Search Icon Cern Search
    • TWiki Search Icon TWiki Search
    • Google Search Icon Google Search

    Main All webs login

This site is powered by the TWiki collaboration platform Powered by PerlCopyright & 2008-2020 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback