Home | News | Documentation | Download

Read a Root file with branches

Dear Experts,

I have a root file which has a tree, a branch and then leaves. The structure is shown in the picture here: file. It seems like I cannot read it simply by using tree->SetBranchAddress.

Moreover, the leaves are have dots (.) in their name which is causing problems, eg: "ReconstructedParticles.p.x or mcparticles2.ID. This is the macro that I prepared: macro.C (1.9 KB)

Would you please help me sort this out?

Sincerely,
Sanjeeda


Please read tips for efficient and successful posting and posting code

ROOT Version: 5.34
Platform: Ubuntu
Compiler: Not Provided


Hi Sanjeeda,

Would it be possible to also attach a (sample of the) ROOT file? That would help us to work on the code.

Cheers,
Jakob

Dear @jblomer,

Thank you for your response.

The file is too large, and I am not able to attach it here. I am sending a google drive link. Please let me know if you are able to download the file: pythia8NCDIS_5x100_minQ2=1000_beamEffects_xAngle=-0.025_hiDiv_1.0029.root - Google Drive

I see a few issues in this code:

  • There is an extra trailing space in the string specifying the ROOT file name
  • The C++ identifies, unlike branch names, must not contain dots (e.g., Float_t ReconstructedParticles.p.x is invalid but Float_t px would be ok)
  • You’d only need to change the style of the histograms once outside the event loop.

The actual problem, however, is that the file contains a vector of particles in every event and not just one particle. One possibility to fill the histograms would be using a TTreeReader like this

TFile *f = new TFile("FileName.root");
TTreeReader reader("events", f);
TTreeReaderArray<Float_t> pxArray(reader, "ReconstructedParticles.p.x");
TH1F *h1 = new TH1F("px","",100, -20, 20);
h1->GetXaxis()->SetTitle("px");
h1->GetXaxis()->SetTitleSize(0.05);
h1->GetXaxis()->CenterTitle();
h1->SetLineWidth(2);

while (reader.Next()) {
   for (auto px: pxArray)
      h1->Fill(px);
}

TFile * f1 = new TFile("output.root","RECREATE");
h1->Write();
f1->Close();

@jblomer Thank you very much.