forked from h5py/h5py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.py
679 lines (556 loc) · 24 KB
/
dataset.py
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
# This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
import posixpath as pp
import sys
import numpy
import h5py
from h5py import h5s, h5t, h5r, h5d
from .base import HLObject, py3, phil, with_phil
from . import filters
from . import selections as sel
from . import selections2 as sel2
_LEGACY_GZIP_COMPRESSION_VALS = frozenset(range(10))
def readtime_dtype(basetype, names):
""" Make a NumPy dtype appropriate for reading """
if len(names) == 0: # Not compound, or we want all fields
return basetype
if basetype.names is None: # Names provided, but not compound
raise ValueError("Field names only allowed for compound types")
for name in names: # Check all names are legal
if not name in basetype.names:
raise ValueError("Field %s does not appear in this type." % name)
return numpy.dtype([(name, basetype.fields[name][0]) for name in names])
def make_new_dset(parent, shape=None, dtype=None, data=None,
chunks=None, compression=None, shuffle=None,
fletcher32=None, maxshape=None, compression_opts=None,
fillvalue=None, scaleoffset=None, track_times=None):
""" Return a new low-level dataset identifier
Only creates anonymous datasets.
"""
# Convert data to a C-contiguous ndarray
if data is not None:
import base
data = numpy.asarray(data, order="C", dtype=base.guess_dtype(data))
# Validate shape
if shape is None:
if data is None:
raise TypeError("Either data or shape must be specified")
shape = data.shape
else:
shape = tuple(shape)
if data is not None and (numpy.product(shape) != numpy.product(data.shape)):
raise ValueError("Shape tuple is incompatible with data")
tmp_shape = maxshape if maxshape is not None else shape
# Validate chunk shape
if isinstance(chunks, tuple) and (-numpy.array([ i>=j for i,j in zip(tmp_shape,chunks) if i is not None])).any():
errmsg = "Chunk shape must not be greater than data shape in any dimension. "\
"{} is not compatible with {}".format(chunks, shape)
raise ValueError(errmsg)
if isinstance(dtype, h5py.Datatype):
# Named types are used as-is
tid = dtype.id
dtype = tid.dtype # Following code needs this
else:
# Validate dtype
if dtype is None and data is None:
dtype = numpy.dtype("=f4")
elif dtype is None and data is not None:
dtype = data.dtype
else:
dtype = numpy.dtype(dtype)
tid = h5t.py_create(dtype, logical=1)
# Legacy
if any((compression, shuffle, fletcher32, maxshape,scaleoffset)) and chunks is False:
raise ValueError("Chunked format required for given storage options")
# Legacy
if compression is True:
if compression_opts is None:
compression_opts = 4
compression = 'gzip'
# Legacy
if compression in _LEGACY_GZIP_COMPRESSION_VALS:
if compression_opts is not None:
raise TypeError("Conflict in compression options")
compression_opts = compression
compression = 'gzip'
dcpl = filters.generate_dcpl(shape, dtype, chunks, compression, compression_opts,
shuffle, fletcher32, maxshape, scaleoffset)
if fillvalue is not None:
fillvalue = numpy.array(fillvalue)
dcpl.set_fill_value(fillvalue)
if track_times in (True, False):
dcpl.set_obj_track_times(track_times)
elif track_times is not None:
raise TypeError("track_times must be either True or False")
if maxshape is not None:
maxshape = tuple(m if m is not None else h5s.UNLIMITED for m in maxshape)
sid = h5s.create_simple(shape, maxshape)
dset_id = h5d.create(parent.id, None, tid, sid, dcpl=dcpl)
if data is not None:
dset_id.write(h5s.ALL, h5s.ALL, data)
return dset_id
class AstypeContext(object):
def __init__(self, dset, dtype):
self._dset = dset
self._dtype = numpy.dtype(dtype)
def __enter__(self):
self._dset._local.astype = self._dtype
def __exit__(self, *args):
self._dset._local.astype = None
class Dataset(HLObject):
"""
Represents an HDF5 dataset
"""
def astype(self, dtype):
""" Get a context manager allowing you to perform reads to a
different destination type, e.g.:
>>> with dataset.astype('f8'):
... double_precision = dataset[0:100:2]
"""
return AstypeContext(self, dtype)
@property
@with_phil
def dims(self):
from . dims import DimensionManager
return DimensionManager(self)
@property
@with_phil
def shape(self):
"""Numpy-style shape tuple giving dataset dimensions"""
return self.id.shape
@shape.setter
@with_phil
def shape(self, shape):
self.resize(shape)
@property
@with_phil
def size(self):
"""Numpy-style attribute giving the total dataset size"""
return numpy.prod(self.shape)
@property
@with_phil
def dtype(self):
"""Numpy dtype representing the datatype"""
return self.id.dtype
@property
@with_phil
def value(self):
""" Alias for dataset[()] """
DeprecationWarning("dataset.value has been deprecated. "
"Use dataset[()] instead.")
return self[()]
@property
@with_phil
def chunks(self):
"""Dataset chunks (or None)"""
dcpl = self._dcpl
if dcpl.get_layout() == h5d.CHUNKED:
return dcpl.get_chunk()
return None
@property
@with_phil
def compression(self):
"""Compression strategy (or None)"""
for x in ('gzip','lzf','szip'):
if x in self._filters:
return x
return None
@property
@with_phil
def compression_opts(self):
""" Compression setting. Int(0-9) for gzip, 2-tuple for szip. """
return self._filters.get(self.compression, None)
@property
@with_phil
def shuffle(self):
"""Shuffle filter present (T/F)"""
return 'shuffle' in self._filters
@property
@with_phil
def fletcher32(self):
"""Fletcher32 filter is present (T/F)"""
return 'fletcher32' in self._filters
@property
@with_phil
def scaleoffset(self):
"""Scale/offset filter settings. For integer data types, this is
the number of bits stored, or 0 for auto-detected. For floating
point data types, this is the number of decimal places retained.
If the scale/offset filter is not in use, this is None."""
try:
return self._filters['scaleoffset'][1]
except KeyError:
return None
@property
@with_phil
def maxshape(self):
"""Shape up to which this dataset can be resized. Axes with value
None have no resize limit. """
space = self.id.get_space()
dims = space.get_simple_extent_dims(True)
return tuple(x if x != h5s.UNLIMITED else None for x in dims)
@property
@with_phil
def fillvalue(self):
"""Fill value for this dataset (0 by default)"""
arr = numpy.ndarray((1,), dtype=self.dtype)
dcpl = self._dcpl.get_fill_value(arr)
return arr[0]
@with_phil
def __init__(self, bind):
""" Create a new Dataset object by binding to a low-level DatasetID.
"""
from threading import local
if not isinstance(bind, h5d.DatasetID):
raise ValueError("%s is not a DatasetID" % bind)
HLObject.__init__(self, bind)
self._dcpl = self.id.get_create_plist()
self._filters = filters.get_filters(self._dcpl)
self._local = local()
self._local.astype = None
def resize(self, size, axis=None):
""" Resize the dataset, or the specified axis.
The dataset must be stored in chunked format; it can be resized up to
the "maximum shape" (keyword maxshape) specified at creation time.
The rank of the dataset cannot be changed.
"Size" should be a shape tuple, or if an axis is specified, an integer.
BEWARE: This functions differently than the NumPy resize() method!
The data is not "reshuffled" to fit in the new shape; each axis is
grown or shrunk independently. The coordinates of existing data are
fixed.
"""
with phil:
if self.chunks is None:
raise TypeError("Only chunked datasets can be resized")
if axis is not None:
if not (axis >=0 and axis < self.id.rank):
raise ValueError("Invalid axis (0 to %s allowed)" % (self.id.rank-1))
try:
newlen = int(size)
except TypeError:
raise TypeError("Argument must be a single int if axis is specified")
size = list(self.shape)
size[axis] = newlen
size = tuple(size)
self.id.set_extent(size)
#h5f.flush(self.id) # THG recommends
@with_phil
def __len__(self):
""" The size of the first axis. TypeError if scalar.
Limited to 2**32 on 32-bit systems; Dataset.len() is preferred.
"""
size = self.len()
if size > sys.maxsize:
raise OverflowError("Value too big for Python's __len__; use Dataset.len() instead.")
return size
def len(self):
""" The size of the first axis. TypeError if scalar.
Use of this method is preferred to len(dset), as Python's built-in
len() cannot handle values greater then 2**32 on 32-bit systems.
"""
with phil:
shape = self.shape
if len(shape) == 0:
raise TypeError("Attempt to take len() of scalar dataset")
return shape[0]
@with_phil
def __iter__(self):
""" Iterate over the first axis. TypeError if scalar.
BEWARE: Modifications to the yielded data are *NOT* written to file.
"""
shape = self.shape
if len(shape) == 0:
raise TypeError("Can't iterate over a scalar dataset")
for i in xrange(shape[0]):
yield self[i]
@with_phil
def __getitem__(self, args):
""" Read a slice from the HDF5 dataset.
Takes slices and recarray-style field names (more than one is
allowed!) in any order. Obeys basic NumPy rules, including
broadcasting.
Also supports:
* Boolean "mask" array indexing
"""
args = args if isinstance(args, tuple) else (args,)
# Sort field indices from the rest of the args.
names = tuple(x for x in args if isinstance(x, basestring))
args = tuple(x for x in args if not isinstance(x, basestring))
if not py3:
names = tuple(x.encode('utf-8') if isinstance(x, unicode) else x for x in names)
def strip_fields(basetype):
""" Strip extra dtype information from special types """
if basetype.kind == 'O':
return numpy.dtype('O')
if basetype.fields is not None:
if basetype.kind in ('i','u'):
return basetype.fields['enum'][0]
fields = []
for name in basetype.names:
fff = basetype.fields[name]
if len(fff) == 3:
(subtype, offset, meta) = fff
else:
subtype, meta = fff
offset = 0
subtype = strip_fields(subtype)
fields.append((name, subtype))
return numpy.dtype(fields)
return basetype
def readtime_dtype(basetype, names):
""" Make a NumPy dtype appropriate for reading """
basetype = strip_fields(basetype)
if len(names) == 0: # Not compound, or we want all fields
return basetype
if basetype.names is None: # Names provided, but not compound
raise ValueError("Field names only allowed for compound types")
for name in names: # Check all names are legal
if not name in basetype.names:
raise ValueError("Field %s does not appear in this type." % name)
return numpy.dtype([(name, basetype.fields[name][0]) for name in names])
new_dtype = getattr(self._local, 'astype', None)
if new_dtype is not None:
new_dtype = readtime_dtype(new_dtype, names)
else:
# This is necessary because in the case of array types, NumPy
# discards the array information at the top level.
new_dtype = readtime_dtype(self.id.dtype, names)
mtype = h5t.py_create(new_dtype)
# === Special-case region references ====
if len(args) == 1 and isinstance(args[0], h5r.RegionReference):
obj = h5r.dereference(args[0], self.id)
if obj != self.id:
raise ValueError("Region reference must point to this dataset")
sid = h5r.get_region(args[0], self.id)
mshape = sel.guess_shape(sid)
if mshape is None:
return numpy.array((0,), dtype=new_dtype)
if numpy.product(mshape) == 0:
return numpy.array(mshape, dtype=new_dtype)
out = numpy.empty(mshape, dtype=new_dtype)
sid_out = h5s.create_simple(mshape)
sid_out.select_all()
self.id.read(sid_out, sid, out, mtype)
return out
# === Check for zero-sized datasets =====
if numpy.product(self.shape) == 0:
# These are the only access methods NumPy allows for such objects
if args == (Ellipsis,) or args == tuple():
return numpy.empty(self.shape, dtype=new_dtype)
# === Scalar dataspaces =================
if self.shape == ():
fspace = self.id.get_space()
selection = sel2.select_read(fspace, args)
arr = numpy.ndarray(selection.mshape, dtype=new_dtype)
for mspace, fspace in selection:
self.id.read(mspace, fspace, arr, mtype)
if len(names) == 1:
arr = arr[names[0]]
if selection.mshape is None:
return arr[()]
return arr
# === Everything else ===================
# Perform the dataspace selection.
selection = sel.select(self.shape, args, dsid=self.id)
if selection.nselect == 0:
return numpy.ndarray(selection.mshape, dtype=new_dtype)
# Up-converting to (1,) so that numpy.ndarray correctly creates
# np.void rows in case of multi-field dtype. (issue 135)
single_element = selection.mshape == ()
mshape = (1,) if single_element else selection.mshape
arr = numpy.ndarray(mshape, new_dtype, order='C')
# HDF5 has a bug where if the memory shape has a different rank
# than the dataset, the read is very slow
if len(mshape) < len(self.shape):
# pad with ones
mshape = (1,)*(len(self.shape)-len(mshape)) + mshape
# Perfom the actual read
mspace = h5s.create_simple(mshape)
fspace = selection._id
self.id.read(mspace, fspace, arr, mtype)
# Patch up the output for NumPy
if len(names) == 1:
arr = arr[names[0]] # Single-field recarray convention
if arr.shape == ():
arr = numpy.asscalar(arr)
if single_element:
arr = arr[0]
return arr
@with_phil
def __setitem__(self, args, val):
""" Write to the HDF5 dataset from a Numpy array.
NumPy's broadcasting rules are honored, for "simple" indexing
(slices and integers). For advanced indexing, the shapes must
match.
"""
args = args if isinstance(args, tuple) else (args,)
# Sort field indices from the slicing
names = tuple(x for x in args if isinstance(x, basestring))
args = tuple(x for x in args if not isinstance(x, basestring))
if not py3:
names = tuple(x.encode('utf-8') if isinstance(x, unicode) else x for x in names)
# Generally we try to avoid converting the arrays on the Python
# side. However, for compound literals this is unavoidable.
vlen = h5t.check_dtype(vlen=self.dtype)
if vlen not in (bytes, unicode, None):
try:
val = numpy.asarray(val, dtype=vlen)
except ValueError:
try:
val = numpy.array([numpy.array(x, dtype=vlen)
for x in val], dtype=self.dtype)
except ValueError:
pass
if vlen == val.dtype:
if val.ndim > 1:
tmp = numpy.empty(shape=val.shape[:-1], dtype=object)
tmp.ravel()[:] = [i for i in val.reshape(
(numpy.product(val.shape[:-1]), val.shape[-1]))]
else:
tmp = numpy.array([None], dtype=object)
tmp[0] = val
val = tmp
elif self.dtype.kind == "O" or \
(self.dtype.kind == 'V' and \
(not isinstance(val, numpy.ndarray) or val.dtype.kind != 'V') and \
(self.dtype.subdtype == None)):
if len(names) == 1 and self.dtype.fields is not None:
# Single field selected for write, from a non-array source
if not names[0] in self.dtype.fields:
raise ValueError("No such field for indexing: %s" % names[0])
dtype = self.dtype.fields[names[0]][0]
cast_compound = True
else:
dtype = self.dtype
cast_compound = False
val = numpy.asarray(val, dtype=dtype, order='C')
if cast_compound:
val = val.astype(numpy.dtype([(names[0], dtype)]))
else:
val = numpy.asarray(val, order='C')
# Check for array dtype compatibility and convert
if self.dtype.subdtype is not None:
shp = self.dtype.subdtype[1]
valshp = val.shape[-len(shp):]
if valshp != shp: # Last dimension has to match
raise TypeError("When writing to array types, last N dimensions have to match (got %s, but should be %s)" % (valshp, shp,))
mtype = h5t.py_create(numpy.dtype((val.dtype, shp)))
mshape = val.shape[0:len(val.shape)-len(shp)]
# Make a compound memory type if field-name slicing is required
elif len(names) != 0:
mshape = val.shape
# Catch common errors
if self.dtype.fields is None:
raise TypeError("Illegal slicing argument (not a compound dataset)")
mismatch = [x for x in names if x not in self.dtype.fields]
if len(mismatch) != 0:
mismatch = ", ".join('"%s"'%x for x in mismatch)
raise ValueError("Illegal slicing argument (fields %s not in dataset type)" % mismatch)
# Write non-compound source into a single dataset field
if len(names) == 1 and val.dtype.fields is None:
subtype = h5y.py_create(val.dtype)
mtype = h5t.create(h5t.COMPOUND, subtype.get_size())
mtype.insert(self._e(names[0]), 0, subtype)
# Make a new source type keeping only the requested fields
else:
fieldnames = [x for x in val.dtype.names if x in names] # Keep source order
mtype = h5t.create(h5t.COMPOUND, val.dtype.itemsize)
for fieldname in fieldnames:
subtype = h5t.py_create(val.dtype.fields[fieldname][0])
offset = val.dtype.fields[fieldname][1]
mtype.insert(self._e(fieldname), offset, subtype)
# Use mtype derived from array (let DatasetID.write figure it out)
else:
mshape = val.shape
mtype = None
# Perform the dataspace selection
selection = sel.select(self.shape, args, dsid=self.id)
if selection.nselect == 0:
return
# Broadcast scalars if necessary.
if (mshape == () and selection.mshape != ()):
if self.dtype.subdtype is not None:
raise TypeError("Scalar broadcasting is not supported for array dtypes")
val2 = numpy.empty(selection.mshape[-1], dtype=val.dtype)
val2[...] = val
val = val2
mshape = val.shape
# Perform the write, with broadcasting
# Be careful to pad memory shape with ones to avoid HDF5 chunking
# glitch, which kicks in for mismatched memory/file selections
if(len(mshape) < len(self.shape)):
mshape_pad = (1,)*(len(self.shape)-len(mshape)) + mshape
else:
mshape_pad = mshape
mspace = h5s.create_simple(mshape_pad, (h5s.UNLIMITED,)*len(mshape_pad))
for fspace in selection.broadcast(mshape):
self.id.write(mspace, fspace, val, mtype)
def read_direct(self, dest, source_sel=None, dest_sel=None):
""" Read data directly from HDF5 into an existing NumPy array.
The destination array must be C-contiguous and writable.
Selections must be the output of numpy.s_[<args>].
Broadcasting is supported for simple indexing.
"""
with phil:
if source_sel is None:
source_sel = sel.SimpleSelection(self.shape)
else:
source_sel = sel.select(self.shape, source_sel, self.id) # for numpy.s_
fspace = source_sel._id
if dest_sel is None:
dest_sel = sel.SimpleSelection(dest.shape)
else:
dest_sel = sel.select(dest.shape, dest_sel, self.id)
for mspace in dest_sel.broadcast(source_sel.mshape):
self.id.read(mspace, fspace, dest)
def write_direct(self, source, source_sel=None, dest_sel=None):
""" Write data directly to HDF5 from a NumPy array.
The source array must be C-contiguous. Selections must be
the output of numpy.s_[<args>].
Broadcasting is supported for simple indexing.
"""
with phil:
if source_sel is None:
source_sel = sel.SimpleSelection(source.shape)
else:
source_sel = sel.select(source.shape, source_sel, self.id) # for numpy.s_
mspace = source_sel._id
if dest_sel is None:
dest_sel = sel.SimpleSelection(self.shape)
else:
dest_sel = sel.select(self.shape, dest_sel, self.id)
for fspace in dest_sel.broadcast(source_sel.mshape):
self.id.write(mspace, fspace, source)
@with_phil
def __array__(self, dtype=None):
""" Create a Numpy array containing the whole dataset. DON'T THINK
THIS MEANS DATASETS ARE INTERCHANGABLE WITH ARRAYS. For one thing,
you have to read the whole dataset everytime this method is called.
"""
arr = numpy.empty(self.shape, dtype=self.dtype if dtype is None else dtype)
# Special case for (0,)*-shape datasets
if numpy.product(self.shape) == 0:
return arr
self.read_direct(arr)
return arr
@with_phil
def __repr__(self):
if not self:
r = u'<Closed HDF5 dataset>'
else:
if self.name is None:
namestr = u'("anonymous")'
else:
name = pp.basename(pp.normpath(self.name))
namestr = u'"%s"' % (name if name != u'' else u'/')
r = u'<HDF5 dataset %s: shape %s, type "%s">' % \
(namestr, self.shape, self.dtype.str)
if py3:
return r
return r.encode('utf8')