Re: [ROOT] Appending To NTuple

From: Rene Brun (Rene.Brun@cern.ch)
Date: Wed Jul 05 2000 - 08:53:04 MEST


Hi Jonathan,

a small example showing how to create an ntuple (ntwrite) and appending
new data to an existing ntuple (ntappend, ntappend2). see comments in code

Rene Brun

void ntwrite()
{

  TFile *file = new TFile("ntuple.root","RECREATE");

  TNtuple *ntuple = new TNtuple("ntuple","Demo ntuple","px:py:pz:random:i");

  Float_t px, py, pz;
  for (Int_t i = 0; i < 25000; i++) {
     gRandom->Rannor(px,py);
     pz = px*px + py*py;
     Float_t random = gRandom->Rndm(1);
     ntuple->Fill(px,py,pz,random,i);
  }

  ntuple->Write();
  file->Close();
  delete file;
}

void ntappend()
{

  TFile *file = new TFile("ntuple.root","UPDATE");

  TNtuple *ntuple = (TNtuple*)file->Get("ntuple");

  Float_t px, py, pz;
  for (Int_t i = 0; i < 25000; i++) {
     gRandom->Rannor(px,py);
     pz = px*px + py*py;
     Float_t random = gRandom->Rndm(1);
     ntuple->Fill(px,py,pz,random,i);
  }

  //each ntuple->Write saves a new ntuple header. You will get the
  // keys ntuple1;1 ntuple;2 ntuple;3 ,etc
  // Assuming 3 cycles (1 call to ntwrite and 2 calls to ntappend),
  // in an interactive session, you can do:
  //   TNtuple *ntuple1 = (TNtuple*) file.Get("ntuple;1");
  //   ntuple1->Draw("px>>hpx1"); // hpx1 will have 25000 entries
  //   TNtuple *ntuple2 = (TNtuple*) file.Get("ntuple;2");
  //   ntuple2->Draw("px>>hpx2"); // hpx2 will have 50000 entries
  //   TNtuple *ntuple3 = (TNtuple*) file.Get("ntuple;3");
  //   ntuple3->Draw("px>>hpx3"); // hpx3 will have 75000 entries
  
  ntuple->Write();
  file->Close();
  delete file;
}

void ntappend2()
{

  TFile *file = new TFile("ntuple.root","UPDATE");

  TNtuple *ntuple = (TNtuple*)file->Get("ntuple");

  Float_t px, py, pz;
  for (Int_t i = 0; i < 25000; i++) {
     gRandom->Rannor(px,py);
     pz = px*px + py*py;
     Float_t random = gRandom->Rndm(1);
     ntuple->Fill(px,py,pz,random,i);
  }

  // keep the latest ntuple header only
  ntuple->Write("",TObject::kOverwrite);
  file->Close();
  delete file;
}


Jon Gans wrote:
> 
> Dear Rooters...
> 
> I want to append to a saved NTuple in a TFile. However doing a
> file->write() merely adds another entry to the current file with the same
> name. How can I get it to append?
>  Thanks
>  jon
> 
> ______________________________________________________________________________
> 
> Jonathan Gans
> Yale University
> Physics Department
> PO BOX 208120
> New Haven, CT 06520-8120                             http://www.jongans.com



This archive was generated by hypermail 2b29 : Tue Jan 02 2001 - 11:50:29 MET