Logo ROOT   6.07/09
Reference Guide
Namespaces
staff.py File Reference

Namespaces

 staff
 

Detailed Description

View in nbviewer Open in SWAN example of macro to read data from an ascii file and create a root file with a Tree.

NOTE: comparing the results of this macro with those of staff.C, you'll notice that the resultant file is a couple of bytes smaller, because the code below strips all white-spaces, whereas the .C version does not.

1 
2 import re, array, os
3 import ROOT
4 from ROOT import TFile, TTree, gROOT, AddressOf
5 
6 ## A C/C++ structure is required, to allow memory based access
7 gROOT.ProcessLine(
8 "struct staff_t {\
9  Int_t Category;\
10  UInt_t Flag;\
11  Int_t Age;\
12  Int_t Service;\
13  Int_t Children;\
14  Int_t Grade;\
15  Int_t Step;\
16  Int_t Hrweek;\
17  Int_t Cost;\
18  Char_t Division[4];\
19  Char_t Nation[3];\
20 };" );
21 
22 ## Function to read in data from ASCII file and fill the ROOT tree
23 def staff():
24 
25  staff = ROOT.staff_t()
26 
27  # The input file cern.dat is a copy of the CERN staff data base
28  # from 1988
29 
30  f = TFile( 'staff.root', 'RECREATE' )
31  tree = TTree( 'T', 'staff data from ascii file' )
32  tree.Branch( 'staff', staff, 'Category/I:Flag:Age:Service:Children:Grade:Step:Hrweek:Cost' )
33  tree.Branch( 'Divisions', AddressOf( staff, 'Division' ), 'Division/C' )
34  tree.Branch( 'Nation', AddressOf( staff, 'Nation' ), 'Nation/C' )
35 
36  # note that the branches Division and Nation cannot be on the first branch
37  fname = os.path.join(ROOT.gROOT.GetTutorialsDir(), 'tree', 'cernstaff.dat')
38  for line in open(fname).readlines():
39  t = list(filter( lambda x: x, re.split( '\s+', line ) ) )
40  staff.Category = int(t[0]) # assign as integers
41  staff.Flag = int(t[1])
42  staff.Age = int(t[2])
43  staff.Service = int(t[3])
44  staff.Children = int(t[4])
45  staff.Grade = int(t[5])
46  staff.Step = int(t[6])
47  staff.Hrweek = int(t[7])
48  staff.Cost = int(t[8])
49  staff.Division = t[9] # assign as strings
50  staff.Nation = t[10]
51 
52  tree.Fill()
53 
54  tree.Print()
55  tree.Write()
56 
57 #### run fill function if invoked on CLI
58 if __name__ == '__main__':
59  staff()
Author
Wim Lavrijsen

Definition in file staff.py.