First Steps: N-tuples


Creating, filling and displaying n-tuples. Reading ASCII data files.

The Lesson

ROOT's TNtuple class provides equivalent facilities to the n-tuple operations in PAW. TNtuple inherits from TTree which extends many of the PAW concepts to an object structure.

To get a first taste, create a file called:-

ntuple.cxx that contains:-

   FILE *fp = fopen("ntuple.dat","r"); 

   Float_t x,y,z;
   Int_t ncols;
   Int_t nlines = 0;

   TNtuple *ntuple = new TNtuple("ntuple","data from ascii file","x:y:z");

   while(1) {
      ncols = fscanf(fp,"%f %f %f",&x, &y, &z);
      if (ncols < 0) break;    

   cout << " found " << nlines << " points" << endl ;


   ntuple->Draw("z : sqrt(x*x + y*y)");

It is a slightly simplified version of the ROOT Tutorial Reading an ascii file and making an ntuple It starts with a bit of pure C and shows how the function fopen is used to establish a file pointer to read ( hence "r") the file ntuple.dat:- FILE *fp = fopen("ntuple.dat","r"); Next, having defined a set of Float_t and Int_t variables a TNtuple object is created:- TNtuple *ntuple = new TNtuple("ntuple","data from ascii file","x:y:z"); Its constructor is supplied with a name, a title, and variables list which contains colon separated names. Now there is a while loop that run for ever. while(1) { ... } The function fscanf is passed the file pointer and is told to decode 3 floats:- ncols = fscanf(fp,"%f %f %f",&x, &y, &z); You can think of "%f %f %f" like the FORTRAN FORMAT : F,F,F. fscanf stores its results in the variables x,y,z. Note that fscanf has to be passed the addresses of its output variables. This is all to do with the fact that C only passes arguments by value so fscanf needs a pointer to a float in order to update it. If fscanf returns less than zero then it means that the EOF has been reached and so the break statement is used to escape from the while loop:- if (ncols < 0) break; If not the TNuple object is asked to Fill itself with the data read from the file:- ntuple->Fill(x,y,z); Once the file read in full the n-tuple is asked to print itself- ntuple->Print(); Finally comes a very powerful command to draw itself:- ntuple->Draw("z : sqrt(x*x + y*y)"); This produces a 2D plot of z against the square root of x squared + y squared. The Draw message is similar to PAW's NTUPLE/PLOT command. For more details of the Draw message see the Automated Event Processing section of the TTree class.

To run this example you also need to create:-

ntuple.dat You can either create your own file containing 3 floating point numbers in free format on each of as many lines as you like, or you can take a copy of ntuple.dat Start ROOT and execute the file ntuple.cxx. Afterwards you can produces more plots, e.g.:- ntuple->Draw("x", "y<z");


Go Back to the The First Steps Top Page

If you have any comments about this page please send them to Nick West