Using TTreeReader to read different instances in a single branch

Hi,

So I’m just trying to read some data from different instances in a single branch. Right now my code looks like:

TFile *f = TFile::Open("test.root");
TTreeReader myReader("tree", f);
TTreeReaderValue<float> p(myReader, "momentum");
while (myReader.Next()){
    printf("%f \n", *p);
}

To my understanding, the myReader.Next() loops over the leaves in the tree; and will then print out the momentum for each. However, in each leaf I have multiple events, for instance when I run tree->Scan() I get something like:

Row Instance EventNumb Momentum
0......0.......0..........0.325
0......1.......0..........0.123
0......2.......0..........0.532
1......0.......1..........0.125
...

So right now, my code will just print out the first momentum value for each leaf; i.e. here it will print 0.325 then 0.125. How can I loop over the instances in each branch to get all the data? So far; all examples I’ve seen using TTreeReaderValue only deal with the case where there is a single instance in each branch.

Thanks

Hi,
you are reading branch “momentum” as a float but it is actually an array of floats. Switch TTreeReaderValue to TTreeReaderArray (I haven’t tested the code, but it should give you an idea of what I mean):

std::unique_ptr<TFile> f(TFile::Open("test.root"));
TTreeReader myReader("tree", f);
TTreeReaderArray<float> momentum(myReader, "momentum");
while (myReader.Next()){
  for (auto &m : momentum)
    std::cout << m << " ";
  std::endl;
}
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.