How to use TTreeReaderValue?

Hello,

I am trying to compile a very simple code just to understand how to use TTreeReader and TTreeReaderValue.

`#include “TFile.h”
#include “TH1F.h”
#include “TCanvas.h”
#include “TMath.h”
#include “TTreeReader.h”
#include “TTreeReaderValue.h”

void Tuto(){

TFile *f = TFile::Open(“http://root.cern/files/introtutorials/eventdata.root”);
TTreeReader myReader(“EventTree”,f);
TTreeReaderValue<Float_t> posY(myReader, “fPosY”);

TH1F *posY_p = new TH1F(“posY_p”,“PosY vs Momentum”,100,0,100);

while(myReader.Next()){
posY_p->Fill(posY);
}

posY_p->Draw();
}`

I have no problem with TTreeReader alone, but TTreeReaderValue gives me the following error message :

“error: no matching constructor for initialization of ‘TTreeReaderValue<Float_t>’ (aka
‘TTreeReaderValue’)
TTreeReaderValue<Float_t> posY(myReader, “fPosY”);”

Do you have any idea ?

ROOT Version: 6.18/0.4
Platform: Ubuntu 16.04
Compiler: g++

Thank you very much.

Hi Mario,

I could not reproduce the exact error message, but I see the following issues. The fPosY branch is in fact not a simple value but a member an fParticle object, where every given event can consist of multiple particles. You can check the schema of the tree with EventTree->Print(). The brackets in the line

*Br    2 :fParticles.fPosY : Double_t fPosY[fParticles_]                     *

indicate that fPosY is an array of Double_t values. So instead of using a TTreeReaderValue you’d need to #include <TTreeReaderArray.h> and use

TTreeReaderArray<Double_t> posY(myReader, "fParticles.fPosY");

In the loop, you can then fill the histogram with an inner loop over all the y values like

for (auto v : posY)
   posY_p->Fill(v);

Alternatively, you can use an RDataFrame (#include <ROOT/RDataFrame.hxx>) and write

ROOT::RDataFrame df("EventTree", "http://root.cern/files/introtutorials/eventdata.root");
auto h = df.Histo1D({"posY_p", "PosY vs Momentum", 100, 0, 100}, "fParticles");
h->DrawCopy();

Cheers,
Jakob

Hello Jakob,

It works perfectly now thank you.

Cheers,
Mario.