Home | News | Documentation | Download

Creating a root file with a tree object and TH2D

Dear all,
I would like to generate a root file with a tree and a TH2D from 2 different input root files. Here is the code:

#include <TROOT.h>
#include <Riostream.h>
#include <TChain.h>
#include <TString.h>
#include <TFile.h>
#include <fstream>
#include <TLorentzVector.h>
#include <iostream>
#include <TSystem.h>
#include <TMath.h>
#include <TLeaf.h>
#include <TBranch.h>
#include "TH2D.h"

void addVarToTree()
  // Opening first root file and getting the tree
  TFile *myfile1 = new TFile("file1.root","READ");
  TTree *data_weighted1 = (TTree*)myfile1->Get("data_Weighted");

  // Opening second root file and getting two 2D histograms
  TFile *myfile2 = new TFile("file2.root","READ");
  TH2D *HaccHistoMinus = (TH2D*)myfile2->Get("Hacc_kpipi_Minus_DAsyCorr");
  TH2D *HaccHistoPlus  = (TH2D*)myfile2->Get("Hacc_kpipi_Plus_DAsyCorr");

  // Creating a new root file with the tree and histograms above
  TFile *newfile = new TFile("outputfile.root","recreate");
  TTree *newtree = data_weighted1->CloneTree();


I want to write on “outputfile” the tree “data_Weighted” and the 2D histograms “Hacc_kpipi_Minus_DAsyCorr” and “Hacc_kpipi_Plus_DAsyCorr”. However, after running the script above, I have two trees “data_Weighted”, one correctly cloned, plus a second one which seems being a random sub-sample of the true one. I would like to understand what is happening (why a second “data_Weighted” is showing up in my outputfile).
Many thanks,

Link to the files:

I think the problem is the line newfile->Write();.
This loops on all objects currently stored in memory and writes them to the file. However, since Trees can become very large, they are not stored completely in memory, but written to the current gDirectory (Which is the currently opened file) from time to time.

I suggest you try to replace the line newfile->Write(); with:

data_weighted1->Write(data_weighted1->GetName(), TObject::kOverwrite);

This is the most safe way to achieve what you want I can think of.

Thanks for your reply!
However, now I am having the following message when running the script with your modifications:

Error in TBranch::TBranch::WriteBasketImpl: basket’s WriteBuffer failed.

A root output file is indeed produced with only one tree name, as required. But when I try to access a tree data_weighted1 variable, I have the message:

Error in TBasket::Streamer: The value of fNbytes is incorrect (-654442865) ; trying to recover by setting it to zero

And the leaves are filled in a strange way.

Problem solved! In the line

data_weighted1->Write(data_weighted1->GetName(), TObject::kOverwrite);

I had to replace data_weighted1 with its clone newtree.
Thanks for helping!

Ah yes - That is actually what I meant to write, but I confused the trees.
Sorry for the confusion.

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