File: tutorial1.py

package info (click to toggle)
pytables 3.3.0-5
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 14,972 kB
  • ctags: 16,919
  • sloc: python: 59,339; ansic: 46,596; cpp: 1,463; sh: 476; makefile: 428
file content (312 lines) | stat: -rw-r--r-- 8,012 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
"""Small but quite comprehensive example showing the use of PyTables.

The program creates an output file, 'tutorial1.h5'.  You can view it
with any HDF5 generic utility.

"""


from __future__ import print_function
import os
import traceback

SECTION = "I HAVE NO TITLE"


def tutsep():
    print('----8<----', SECTION, '----8<----')


def tutprint(obj):
    tutsep()
    print(obj)


def tutrepr(obj):
    tutsep()
    print(repr(obj))


def tutexc():
    tutsep()
    traceback.print_exc(file=sys.stdout)


SECTION = "Importing tables objects"
from numpy import *
from tables import *


SECTION = "Declaring a Column Descriptor"
# Define a user record to characterize some kind of particles
class Particle(IsDescription):
    name      = StringCol(16)   # 16-character String
    idnumber  = Int64Col()      # Signed 64-bit integer
    ADCcount  = UInt16Col()     # Unsigned short integer
    TDCcount  = UInt8Col()      # unsigned byte
    grid_i    = Int32Col()      # integer
    grid_j    = IntCol()        # integer (equivalent to Int32Col)
    pressure  = Float32Col()    # float  (single-precision)
    energy    = FloatCol()      # double (double-precision)


SECTION = "Creating a PyTables file from scratch"
# Open a file in "w"rite mode
h5file = open_file('tutorial1.h5', mode="w", title="Test file")


SECTION = "Creating a new group"
# Create a new group under "/" (root)
group = h5file.create_group("/", 'detector', 'Detector information')


SECTION = "Creating a new table"
# Create one table on it
table = h5file.create_table(group, 'readout', Particle, "Readout example")

tutprint(h5file)
tutrepr(h5file)

# Get a shortcut to the record object in table
particle = table.row

# Fill the table with 10 particles
for i in range(10):
    particle['name'] = 'Particle: %6d' % (i)
    particle['TDCcount'] = i % 256
    particle['ADCcount'] = (i * 256) % (1 << 16)
    particle['grid_i'] = i
    particle['grid_j'] = 10 - i
    particle['pressure'] = float(i*i)
    particle['energy'] = float(particle['pressure'] ** 4)
    particle['idnumber'] = i * (2 ** 34)
    # Insert a new particle record
    particle.append()

# Flush the buffers for table
table.flush()


SECTION = "Reading (and selecting) data in a table"
# Read actual data from table. We are interested in collecting pressure values
# on entries where TDCcount field is greater than 3 and pressure less than 50
table = h5file.root.detector.readout
pressure = [
    x['pressure'] for x in table
    if x['TDCcount'] > 3 and 20 <= x['pressure'] < 50
]

tutrepr(pressure)

# Read also the names with the same cuts
names = [
    x['name'] for x in table
    if x['TDCcount'] > 3 and 20 <= x['pressure'] < 50
]

tutrepr(names)


SECTION = "Creating new array objects"
gcolumns = h5file.create_group(h5file.root, "columns", "Pressure and Name")

tutrepr(
    h5file.create_array(gcolumns, 'pressure', array(pressure),
                       "Pressure column selection")
)

tutrepr(
    h5file.create_array('/columns', 'name', names, "Name column selection")
)

tutprint(h5file)


SECTION = "Closing the file and looking at its content"
# Close the file
h5file.close()

tutsep()
os.system('h5ls -rd tutorial1.h5')
tutsep()
os.system('ptdump tutorial1.h5')


"""This example shows how to browse the object tree and enlarge tables.

Before to run this program you need to execute first tutorial1-1.py
that create the tutorial1.h5 file needed here.

"""


SECTION = "Traversing the object tree"
# Reopen the file in append mode
h5file = open_file("tutorial1.h5", "a")

# Print the object tree created from this filename
# List all the nodes (Group and Leaf objects) on tree
tutprint(h5file)

# List all the nodes (using File iterator) on tree
tutsep()
for node in h5file:
    print(node)

# Now, only list all the groups on tree
tutsep()
for group in h5file.walk_groups("/"):
    print(group)

# List only the arrays hanging from /
tutsep()
for group in h5file.walk_groups("/"):
    for array in h5file.list_nodes(group, classname='Array'):
        print(array)

# This gives the same result
tutsep()
for array in h5file.walk_nodes("/", "Array"):
    print(array)

# And finally, list only leafs on /detector group (there should be one!)
# Other way using iterators and natural naming
tutsep()
for leaf in h5file.root.detector('Leaf'):
    print(leaf)


SECTION = "Setting and getting user attributes"
# Get a pointer to '/detector/readout'
table = h5file.root.detector.readout

# Attach it a string (date) attribute
table.attrs.gath_date = "Wed, 06/12/2003 18:33"

# Attach a floating point attribute
table.attrs.temperature = 18.4
table.attrs.temp_scale = "Celsius"

# Get a pointer to '/detector'
detector = h5file.root.detector
# Attach a general object to the parent (/detector) group
detector._v_attrs.stuff = [5, (2.3, 4.5), "Integer and tuple"]

# Now, get the attributes
tutrepr(table.attrs.gath_date)
tutrepr(table.attrs.temperature)
tutrepr(table.attrs.temp_scale)
tutrepr(detector._v_attrs.stuff)

# Delete permanently the attribute gath_date of /detector/readout
del table.attrs.gath_date

# Print a representation of all attributes in  /detector/table
tutrepr(table.attrs)

# Get the (user) attributes of /detector/table
tutprint(table.attrs._f_list("user"))

# Get the (sys) attributes of /detector/table
tutprint(table.attrs._f_list("sys"))

# Rename an attribute
table.attrs._f_rename("temp_scale", "tempScale")
tutprint(table.attrs._f_list())

# Try to rename a system attribute:
try:
    table.attrs._f_rename("VERSION", "version")
except:
    tutexc()

h5file.flush()
tutsep()
os.system('h5ls -vr tutorial1.h5/detector/readout')


SECTION = "Getting object metadata"
# Get metadata from table
tutsep()
print("Object:", table)
tutsep()
print("Table name:", table.name)
tutsep()
print("Table title:", table.title)
tutsep()
print("Number of rows in table:", table.nrows)
tutsep()
print("Table variable names with their type and shape:")
tutsep()
for name in table.colnames:
    print(name, ':= %s, %s' % (table.coltypes[name], table.colshapes[name]))

tutprint(table.__doc__)

# Get the object in "/columns pressure"
pressureObject = h5file.get_node("/columns", "pressure")

# Get some metadata on this object
tutsep()
print("Info on the object:", repr(pressureObject))
tutsep()
print(" shape: ==>", pressureObject.shape)
tutsep()
print(" title: ==>", pressureObject.title)
tutsep()
print(" type: ==>", pressureObject.type)


SECTION = "Reading data from Array objects"
# Read the 'pressure' actual data
pressureArray = pressureObject.read()
tutrepr(pressureArray)
tutsep()
print("pressureArray is an object of type:", type(pressureArray))

# Read the 'name' Array actual data
nameArray = h5file.root.columns.name.read()
tutrepr(nameArray)
print("nameArray is an object of type:", type(nameArray))

# Print the data for both arrays
tutprint("Data on arrays nameArray and pressureArray:")
tutsep()
for i in range(pressureObject.shape[0]):
    print(nameArray[i], "-->", pressureArray[i])
tutrepr(pressureObject.name)


SECTION = "Appending data to an existing table"
# Create a shortcut to table object
table = h5file.root.detector.readout
# Get the object row from table
particle = table.row

# Append 5 new particles to table
for i in range(10, 15):
    particle['name'] = 'Particle: %6d' % (i)
    particle['TDCcount'] = i % 256
    particle['ADCcount'] = (i * 256) % (1 << 16)
    particle['grid_i'] = i
    particle['grid_j'] = 10 - i
    particle['pressure'] = float(i*i)
    particle['energy'] = float(particle['pressure'] ** 4)
    particle['idnumber'] = i * (2 ** 34)  # This exceeds long integer range
    particle.append()

# Flush this table
table.flush()

# Print the data using the table iterator:
tutsep()
for r in table:
    print("%-16s | %11.1f | %11.4g | %6d | %6d | %8d |" % \
          (r['name'], r['pressure'], r['energy'], r['grid_i'], r['grid_j'],
           r['TDCcount']))

# Delete some rows on the Table (yes, rows can be removed!)
tutrepr(table.remove_rows(5, 10))

# Close the file
h5file.close()