Debian Codegraph @

petl/io/pytables.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import absolute_import, print_function, division
3
4
5 from contextlib import contextmanager
6 from petl.compat import string_types
7
8
9 from petl.errors import ArgumentError
10 from petl.util.base import Table, iterpeek, data
11 from petl.io.numpy import infer_dtype
12
13
14 def fromhdf5(source, where=None, name=None, condition=None,
15 condvars=None, start=None, stop=None, step=None):
16 """
17 Provides access to an HDF5 table. E.g.::
18
19 >>> import petl as etl
20 >>>
21 >>> # set up a new hdf5 table to demonstrate with
22 >>> class FooBar(tables.IsDescription): # doctest: +SKIP
23 ... foo = tables.Int32Col(pos=0) # doctest: +SKIP
24 ... bar = tables.StringCol(6, pos=2) # doctest: +SKIP
25 >>> #
26 >>> def setup_hdf5_table():
27 ... import tables
28 ... h5file = tables.open_file('example.h5', mode='w',
29 ... title='Example file')
30 ... h5file.create_group('/', 'testgroup', 'Test Group')
31 ... h5table = h5file.create_table('/testgroup', 'testtable', FooBar,
32 ... 'Test Table')
33 ... # load some data into the table
34 ... table1 = (('foo', 'bar'),
35 ... (1, b'asdfgh'),
36 ... (2, b'qwerty'),
37 ... (3, b'zxcvbn'))
38 ... for row in table1[1:]:
39 ... for i, f in enumerate(table1[0]):
40 ... h5table.row[f] = row[i]
41 ... h5table.row.append()
42 ... h5file.flush()
43 ... h5file.close()
44 >>>
45 >>> setup_hdf5_table() # doctest: +SKIP
46 >>>
47 >>> # now demonstrate use of fromhdf5
48 >>> table1 = etl.fromhdf5('example.h5', '/testgroup', 'testtable') # doctest: +SKIP
49 >>> table1 # doctest: +SKIP
50 +-----+-----------+
51 | foo | bar |
52 +=====+===========+
53 | 1 | b'asdfgh' |
54 +-----+-----------+
55 | 2 | b'qwerty' |
56 +-----+-----------+
57 | 3 | b'zxcvbn' |
58 +-----+-----------+
59
60 >>> # alternatively just specify path to table node
61 ... table1 = etl.fromhdf5('example.h5', '/testgroup/testtable') # doctest: +SKIP
62 >>> # ...or use an existing tables.File object
63 ... h5file = tables.open_file('example.h5') # doctest: +SKIP
64 >>> table1 = etl.fromhdf5(h5file, '/testgroup/testtable') # doctest: +SKIP
65 >>> # ...or use an existing tables.Table object
66 ... h5tbl = h5file.get_node('/testgroup/testtable') # doctest: +SKIP
67 >>> table1 = etl.fromhdf5(h5tbl) # doctest: +SKIP
68 >>> # use a condition to filter data
69 ... table2 = etl.fromhdf5(h5tbl, condition='foo < 3') # doctest: +SKIP
70 >>> table2 # doctest: +SKIP
71 +-----+-----------+
72 | foo | bar |
73 +=====+===========+
74 | 1 | b'asdfgh' |
75 +-----+-----------+
76 | 2 | b'qwerty' |
77 +-----+-----------+
78
79 >>> h5file.close() # doctest: +SKIP
80
81 """
82
83 return HDF5View(source, where=where, name=name,
84 condition=condition, condvars=condvars,
85 start=start, stop=stop, step=step)
86
87
88 class HDF5View(Table):
89
90 def __init__(self, source, where=None, name=None, condition=None,
91 condvars=None, start=None, stop=None, step=None):
92 self.source = source
93 self.where = where
94 self.name = name
95 self.condition = condition
96 self.condvars = condvars
97 self.start = start
98 self.stop = stop
99 self.step = step
100
101 def __iter__(self):
102 return iterhdf5(self.source, self.where, self.name, self.condition,
103 self.condvars, self.start, self.stop, self.step)
104
105
106 @contextmanager
107 def _get_hdf5_table(source, where, name, mode='r'):
108 import tables
109
110 needs_closing = False
111 h5file = None
112
113 # allow for polymorphic args
114 if isinstance(source, tables.Table):
115
116 # source is a table
117 h5tbl = source
118
119 elif isinstance(source, string_types):
120
121 # assume source is the name of an HDF5 file, try to open it
122 h5file = tables.open_file(source, mode=mode)
123 needs_closing = True
124 h5tbl = h5file.get_node(where, name=name)
125
126 elif isinstance(source, tables.File):
127
128 # source is an HDF5 file object
129 h5file = source
130 h5tbl = h5file.get_node(where, name=name)
131
132 else:
133
134 # invalid source
135 raise ArgumentError('invalid source argument, expected file name or '
136 'tables.File or tables.Table object, found: %r'
137 % source)
138
139 try:
140 yield h5tbl
141 finally:
142 # tidy up
143 if needs_closing:
144 h5file.close()
145
146
147 @contextmanager
148 def _get_hdf5_file(source, mode='r'):
149 import tables
150
151 needs_closing = False
152
153 # allow for polymorphic args
154 if isinstance(source, string_types):
155
156 # assume source is the name of an HDF5 file, try to open it
157 h5file = tables.open_file(source, mode=mode)
158 needs_closing = True
159
160 elif isinstance(source, tables.File):
161
162 # source is an HDF5 file object
163 h5file = source
164
165 else:
166
167 # invalid source
168 raise ArgumentError('invalid source argument, expected file name or '
169 'tables.File object, found: %r' % source)
170
171 try:
172 yield h5file
173 finally:
174 if needs_closing:
175 h5file.close()
176
177
178 def iterhdf5(source, where, name, condition, condvars, start, stop, step):
179
180 with _get_hdf5_table(source, where, name) as h5tbl:
181
182 # header row
183 hdr = tuple(h5tbl.colnames)
184 yield hdr
185
186 # determine how to iterate over the table
187 if condition is not None:
188 it = h5tbl.where(condition, condvars=condvars,
189 start=start, stop=stop, step=step)
190
191 else:
192 it = h5tbl.iterrows(start=start, stop=stop, step=step)
193
194 # data rows
195 for row in it:
196 yield row[:] # access row as a tuple
197
198
199 def fromhdf5sorted(source, where=None, name=None, sortby=None, checkCSI=False,
200 start=None, stop=None, step=None):
201 """
202 Provides access to an HDF5 table, sorted by an indexed column, e.g.::
203
204 >>> import petl as etl
205 >>>
206 >>> # set up a new hdf5 table to demonstrate with
207 >>> class FooBar(tables.IsDescription): # doctest: +SKIP
208 ... foo = tables.Int32Col(pos=0) # doctest: +SKIP
209 ... bar = tables.StringCol(6, pos=2) # doctest: +SKIP
210 >>>
211 >>> def setup_hdf5_index():
212 ... import tables
213 ... h5file = tables.open_file('example.h5', mode='w',
214 ... title='Example file')
215 ... h5file.create_group('/', 'testgroup', 'Test Group')
216 ... h5table = h5file.create_table('/testgroup', 'testtable', FooBar,
217 ... 'Test Table')
218 ... # load some data into the table
219 ... table1 = (('foo', 'bar'),
220 ... (1, b'asdfgh'),
221 ... (2, b'qwerty'),
222 ... (3, b'zxcvbn'))
223 ... for row in table1[1:]:
224 ... for i, f in enumerate(table1[0]):
225 ... h5table.row[f] = row[i]
226 ... h5table.row.append()
227 ... h5table.cols.foo.create_csindex() # CS index is required
228 ... h5file.flush()
229 ... h5file.close()
230 >>>
231 >>> setup_hdf5_index() # doctest: +SKIP
232 >>>
233 ... # access the data, sorted by the indexed column
234 ... table2 = etl.fromhdf5sorted('example.h5', '/testgroup', 'testtable', sortby='foo') # doctest: +SKIP
235 >>> table2 # doctest: +SKIP
236 +-----+-----------+
237 | foo | bar |
238 +=====+===========+
239 | 1 | b'zxcvbn' |
240 +-----+-----------+
241 | 2 | b'qwerty' |
242 +-----+-----------+
243 | 3 | b'asdfgh' |
244 +-----+-----------+
245
246 """
247
248 assert sortby is not None, 'no column specified to sort by'
249 return HDF5SortedView(source, where=where, name=name,
250 sortby=sortby, checkCSI=checkCSI,
251 start=start, stop=stop, step=step)
252
253
254 class HDF5SortedView(Table):
255
256 def __init__(self, source, where=None, name=None, sortby=None,
257 checkCSI=False, start=None, stop=None, step=None):
258 self.source = source
259 self.where = where
260 self.name = name
261 self.sortby = sortby
262 self.checkCSI = checkCSI
263 self.start = start
264 self.stop = stop
265 self.step = step
266
267 def __iter__(self):
268 return iterhdf5sorted(self.source, self.where, self.name, self.sortby,
269 self.checkCSI, self.start, self.stop, self.step)
270
271
272 def iterhdf5sorted(source, where, name, sortby, checkCSI, start, stop, step):
273
274 with _get_hdf5_table(source, where, name) as h5tbl:
275
276 # header row
277 hdr = tuple(h5tbl.colnames)
278 yield hdr
279
280 it = h5tbl.itersorted(sortby,
281 checkCSI=checkCSI,
282 start=start,
283 stop=stop,
284 step=step)
285 for row in it:
286 yield row[:] # access row as a tuple
287
288
289 def tohdf5(table, source, where=None, name=None, create=False, drop=False,
290 description=None, title='', filters=None, expectedrows=10000,
291 chunkshape=None, byteorder=None, createparents=False,
292 sample=1000):
293 """
294 Write to an HDF5 table. If `create` is `False`, assumes the table
295 already exists, and attempts to truncate it before loading. If `create`
296 is `True`, a new table will be created, and if `drop` is True,
297 any existing table will be dropped first. If `description` is `None`,
298 the description will be guessed. E.g.::
299
300 >>> import petl as etl
301 >>> table1 = (('foo', 'bar'),
302 ... (1, b'asdfgh'),
303 ... (2, b'qwerty'),
304 ... (3, b'zxcvbn'))
305 >>> etl.tohdf5(table1, 'example.h5', '/testgroup', 'testtable',
306 ... drop=True, create=True, createparents=True) # doctest: +SKIP
307 >>> etl.fromhdf5('example.h5', '/testgroup', 'testtable') # doctest: +SKIP
308 +-----+-----------+
309 | foo | bar |
310 +=====+===========+
311 | 1 | b'asdfgh' |
312 +-----+-----------+
313 | 2 | b'qwerty' |
314 +-----+-----------+
315 | 3 | b'zxcvbn' |
316 +-----+-----------+
317
318 """
319
320 import tables
321 it = iter(table)
322
323 if create:
324 with _get_hdf5_file(source, mode='a') as h5file:
325
326 if drop:
327 try:
328 h5file.get_node(where, name)
329 except tables.NoSuchNodeError:
330 pass
331 else:
332 h5file.remove_node(where, name)
333
334 # determine datatype
335 if description is None:
336 peek, it = iterpeek(it, sample)
337 # use a numpy dtype
338 description = infer_dtype(peek)
339
340 # create the table
341 h5file.create_table(where, name, description,
342 title=title,
343 filters=filters,
344 expectedrows=expectedrows,
345 chunkshape=chunkshape,
346 byteorder=byteorder,
347 createparents=createparents)
348
349 with _get_hdf5_table(source, where, name, mode='a') as h5table:
350
351 # truncate the existing table
352 h5table.truncate(0)
353
354 # load the data
355 _insert(it, h5table)
356
357
358 Table.tohdf5 = tohdf5
359
360
361 def appendhdf5(table, source, where=None, name=None):
362 """
363 As :func:`petl.io.hdf5.tohdf5` but don't truncate the target table before
364 loading.
365
366 """
367
368 with _get_hdf5_table(source, where, name, mode='a') as h5table:
369
370 # load the data
371 _insert(table, h5table)
372
373
374 Table.appendhdf5 = appendhdf5
375
376
377 def _insert(table, h5table):
378 it = data(table) # don't need header
379 for row in it:
380 for i, f in enumerate(h5table.colnames):
381 # depends on order of fields being the same in input table
382 # and hd5 table, but field names don't need to match
383 h5table.row[f] = row[i]
384 h5table.row.append()
385 h5table.flush()