Re: [ROOT] read ASCII data file

From: Christian Holm Christensen (cholm@hehi03.nbi.dk)
Date: Thu Feb 06 2003 - 17:14:33 MET


sherry pan <chpan@glue.umd.edu> wrote concerning
  [ROOT] read ASCII data file  [Thu, 6 Feb 2003 09:03:11 -0500 (EST)] 
----------------------------------------------------------------------
> Hi,
> 
> How to read in an ASCII data file (2D or 3D array) to root?

Pretty simple:

  int write(const TString& filename, Int_t ncol, int nrow) 
  {
    ofstream out(filename.Data());
    if (!out || out.bad()) return 1;
    
  
    for (Int_t i = 0; i < nrow; i++) {
      for (Int_t j = 0; j < ncol; j++) 
        out << i * nrow + j << "\t";
      out << endl;
    }
    
    out.close();
  
    return 0;
  }
  
  TTree* read (const TString& filename, Int_t ncol) 
  {
    TString vars;
    for (Int_t i = 0; i < ncol; i++) {
      vars += Form("x%d", i); 
      if (i==0) vars += "/D"; 
      if (i + 1 != ncol) vars += ":";
    }
    TArrayD x(ncol);
    TTree* tree = new TTree("tree", "Tree"); 
    tree->Branch("data", &x.fArray, vars.Data());
    
    ifstream in(filename.Data());
    if (!in || in->bad()) return 1;
    
    while (!in.eof()) {
      x.Reset();
      for (Int_t i = 0; i < ncol; i++) in >> x[i];
      tree->Fill();
    }
    in.close();
  
    return tree;
  }
   

Try this out by doing 

  prompt> root 
  root [0] .L foo.C 
  root [1] write("foo.dat", 3, 10) 
  root [2] TTree* t = read("foo.dat", 3); 
  root [3] t->Draw("x1:x2", "col"); 

Yours, 

 ___  |  Christian Holm Christensen 
  |_| |	 -------------------------------------------------------------
    | |	 Address: Sankt Hansgade 23, 1. th.  Phone:  (+45) 35 35 96 91
     _|	          DK-2200 Copenhagen N       Cell:   (+45) 24 61 85 91
    _|	          Denmark                    Office: (+45) 353  25 305
 ____|	 Email:   cholm@nbi.dk               Web:    www.nbi.dk/~cholm
 | |



This archive was generated by hypermail 2b29 : Thu Jan 01 2004 - 17:50:09 MET