Using TTreeReaderValue when a branch doesn't always exist

Dear ROOTers,

I have data and MC .root files, the files contain almost identical trees except MC trees have an extra branch called weight.

I would like to use the same macro to go through both of these files. The following example is more or less what I have but gives a “branch doesn’t exist” error if running on data. The output should ideally print event weight 1.0 for all data, and the contents of the weight branch for MC.

void main(TString sample = "data" ) {
  TFile *f;
  if ( sample == "data" ) {
    f = new TFile("data.root");
  } else if ( sample == "mc" ) {
    f = new TFile("mc.root");
  TTreeReader reader("myTree",f); // tree called "myTree" in file f
  // example branch common to mc and data
  TTreeReaderValue<Float_t> energy(reader,"E");
  // the following branch exists only in mc, gives an error when running on data
  TTreeReaderValue<Float_t> weight(reader,"weight");
  Float_t event_weight = 1.0; // data weight = 1 by default
  while ( reader.Next() ) {
    if ( sample == "mc" )  {
      event_weight = *weight;
    std::cout  << "event energy " << *energy << std::endl;
    std::cout  << "event weight " << event_weight << std::endl;
  } // finished looping over events

I would like something akin to what I’ve done for the TFile, first declaring a generic *f, then pointing it to the right file depending on if it is data or MC, but I can’t seem to find in the documentation a way to declare an empty TTreeReaderValue and then set it to the correct address.

If you could give me some ideas on how to implement something like this I would be thankful.

_ROOT Version: 6.12.06
_Platform: Linux
Compiler: Not Provided


TTreeReaderValue<Float_t> weight(reader, sample=="mc"?"weight":"E");

And yes, I realize this is dirty.

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