Debian Codegraph @

hdf5storage/utilities.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # Copyright (c) 2013-2016, Freja Nordsiek
2 # All rights reserved.
3 #
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
6 # met:
7 #
8 # 1. Redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer.
10 #
11 # 2. Redistributions in binary form must reproduce the above copyright
12 # notice, this list of conditions and the following disclaimer in the
13 # documentation and/or other materials provided with the distribution.
14 #
15 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19 # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27 """ Module of functions to set and delete HDF5 attributes.
28
29 """
30
31 import sys
32 import collections
33 import copy
34 import random
35
36 # In old versions of Python, everyting in collections.abc was in
37 # collections.
38 try:
39 import collections.abc
40 except ImportError:
41 collections.abc = collections
42
43 try:
44 from pkg_resources import parse_version
45 except:
46 from distutils.version import StrictVersion as parse_version\
47
48 import numpy as np
49 import h5py
50
51
52 # We need to determine if h5py is one of the versions that cannot read
53 # the MATLAB_fields Attribute in the normal fashion so that we can
54 # handle it specially.
55 _cant_read_matlab_fields = (
56 parse_version(h5py.__version__)
57 < parse_version('2.3'))
58 _handle_matlab_fields_specially = (
59 parse_version(h5py.__version__)
60 in (parse_version('3.0'),
61 parse_version('3.1')))
62
63 if _handle_matlab_fields_specially:
64 import ctypes
65 import h5py._objects
66
67
68 # Determine if numpy.ndarrays and scalars have a tobytes method or
69 # not. If they don't, then the tostring method must be used instead.
70 _numpy_has_tobytes = hasattr(np.array([1]), 'tobytes')
71
72
73 def numpy_to_bytes(obj):
74 """ Get the raw bytes of a numpy object's data.
75
76 Calls the ``tobytes`` method on `obj` for new versions of ``numpy``
77 where the method exists, and ``tostring`` for old versions of
78 ``numpy`` where it does not.
79
80 Parameters
81 ----------
82 obj : numpy.generic or numpy.ndarray
83 Numpy scalar or array.
84
85 Returns
86 -------
87 data : bytes
88 The raw data.
89
90 """
91 if _numpy_has_tobytes:
92 return obj.tobytes()
93 else:
94 return obj.tostring()
95
96
97 def read_matlab_fields_attribute(attrs):
98 """ Reads the ``MATLAB_fields`` Attribute.
99
100 On some versions of ``h5py``, the ``MATLAB_fields`` Attribute cannot
101 be read in the standard way and must instead be read in a more
102 manual fashion. This function reads the Attribute by the proper
103 method.
104
105 Parameters
106 ----------
107 attrs : h5py.AttributeManager
108 The Attribute manager to read from.
109
110 Returns
111 -------
112 value : numpy.ndarray or None
113 The value of the ``MATLAB_fields`` Attribute, or ``None`` if it
114 isn't available or its format is invalid.
115
116 Raises
117 ------
118 TypeError
119 If an argument has the wrong type.
120
121 """
122 if not isinstance(attrs, h5py.AttributeManager):
123 raise TypeError('attrs must be a h5py.AttributeManager.')
124 if not _handle_matlab_fields_specially:
125 return attrs.get('MATLAB_fields')
126 if _cant_read_matlab_fields or 'MATLAB_fields' not in attrs:
127 return None
128 # The following method is loosely based on the method provided by
129 # takluyver at
130 # https://github.com/h5py/h5py/issues/1817#issuecomment-781385699
131 #
132 # but has been improved by reading it directly as (size_t, void*)
133 # pairs uint64s instead of using struct.unpack, and avoiding making
134 # intermediate copies of the data by copying directly to the output
135 # array.
136 with h5py._objects.phil:
137 attr_id = attrs.get_id('MATLAB_fields')
138 dt = np.dtype([('length', np.uintp), ('pointer', np.intp)])
139 raw_buf = np.empty(attr_id.shape, dtype=dt)
140 attr_id.read(raw_buf, mtype=attr_id.get_type())
141 attr = np.empty(raw_buf.shape, dtype='object')
142 for i, (length, ptr) in enumerate(raw_buf.flat):
143 at = np.empty(length, dtype='S1')
144 ctypes.memmove(at.ctypes.data, int(ptr), int(length))
145 attr.flat[i] = at
146 return attr
147
148
149 def read_all_attributes_into(attrs, out):
150 """ Reads all Attributes into a MutableMapping (dict-like)
151
152 Reads all Attributes into the MutableMapping (dict-like) out,
153 including the special handling of the ``MATLAB_fields`` Attribute on
154 versions of ``h5py`` where it cannot be read in the standard
155 fashion.
156
157 Parameters
158 ----------
159 attrs : h5py.AttributeManager
160 The Attribute manager to read from.
161 out : MutableMapping
162 The MutableMapping (dict-like) to write the Attributes into.
163
164 Raises
165 ------
166 TypeError
167 If an argument has the wrong type.
168
169 See Also
170 --------
171 read_matlab_fields_attribute
172
173 """
174 if not isinstance(attrs, h5py.AttributeManager):
175 raise TypeError('attrs must be a h5py.AttributeManager.')
176 if not isinstance(out, (dict, collections.defaultdict,
177 collections.abc.MutableMapping)):
178 raise TypeError('out must be a MutableMapping.')
179 if not _handle_matlab_fields_specially \
180 or 'MATLAB_fields' not in attrs:
181 out.update(attrs.items())
182 else:
183 for k in attrs:
184 if k != 'MATLAB_fields':
185 out[k] = attrs[k]
186 else:
187 out[k] = read_matlab_fields_attribute(attrs)
188
189
190 def does_dtype_have_a_zero_shape(dt):
191 """ Determine whether a dtype (or its fields) have zero shape.
192
193 Determines whether the given ``numpy.dtype`` has a shape with a zero
194 element or if one of its fields does, or if one of its fields'
195 fields does, and so on recursively. The following dtypes do not have
196 zero shape.
197
198 * ``'uint8'``
199 * ``[('a', 'int32'), ('blah', 'float16', (3, 3))]``
200 * ``[('a', [('b', 'complex64')], (2, 1, 3))]``
201
202 But the following do
203
204 * ``('uint8', (1, 0))``
205 * ``[('a', 'int32'), ('blah', 'float16', (3, 0))]``
206 * ``[('a', [('b', 'complex64')], (2, 0, 3))]``
207
208 Parameters
209 ----------
210 dt : numpy.dtype
211 The dtype to check.
212
213 Returns
214 -------
215 yesno : bool
216 Whether `dt` or one of its fields has a shape with at least one
217 element that is zero.
218
219 Raises
220 ------
221 TypeError
222 If `dt` is not a ``numpy.dtype``.
223
224 """
225 components = [dt]
226 while 0 != len(components):
227 c = components.pop()
228 if 0 in c.shape:
229 return True
230 if c.names is not None:
231 components.extend([v[0] for v in c.fields.values()])
232 if c.base != c:
233 components.append(c.base)
234 return False
235
236
237 def next_unused_name_in_group(grp, length):
238 """ Gives a name that isn't used in a Group.
239
240 Generates a name of the desired length that is not a Dataset or
241 Group in the given group. Note, if length is not large enough and
242 `grp` is full enough, there may be no available names meaning that
243 this function will hang.
244
245 Parameters
246 ----------
247 grp : h5py.Group or h5py.File
248 The HDF5 Group (or File if at '/') to generate an unused name
249 in.
250 length : int
251 Number of characters the name should be.
252
253 Returns
254 -------
255 str
256 A name that isn't already an existing Dataset or Group in
257 `grp`.
258
259 """
260 # While
261 #
262 # ltrs = string.ascii_letters + string.digits
263 # name = ''.join([random.choice(ltrs) for i in range(length)])
264 #
265 # seems intuitive, its performance is abysmal compared to
266 #
267 # '%0{0}x'.format(length) % random.getrandbits(length * 4)
268 #
269 # The difference is a factor of 20. Idea from
270 #
271 # https://stackoverflow.com/questions/2782229/most-lightweight-way-
272 # to-create-a-random-string-and-a-random-hexadecimal-number/
273 # 35161595#35161595
274 fmt = '%0{0}x'.format(length)
275 name = fmt % random.getrandbits(length * 4)
276 while name in grp:
277 name = fmt % random.getrandbits(length * 4)
278 return name
279
280
281 def convert_numpy_str_to_uint16(data):
282 """ Converts a numpy.unicode\\_ to UTF-16 in numpy.uint16 form.
283
284 Convert a ``numpy.unicode_`` or an array of them (they are UTF-32
285 strings) to UTF-16 in the equivalent array of ``numpy.uint16``. The
286 conversion will throw an exception if any characters cannot be
287 converted to UTF-16. Strings are expanded along rows (across columns)
288 so a 2x3x4 array of 10 element strings will get turned into a 2x30x4
289 array of uint16's if every UTF-32 character converts easily to a
290 UTF-16 singlet, as opposed to a UTF-16 doublet.
291
292 Parameters
293 ----------
294 data : numpy.unicode\\_ or numpy.ndarray of numpy.unicode\\_
295 The string or array of them to convert.
296
297 Returns
298 -------
299 array : numpy.ndarray of numpy.uint16
300 The result of the conversion.
301
302 Raises
303 ------
304 UnicodeEncodeError
305 If a UTF-32 character has no UTF-16 representation.
306
307 See Also
308 --------
309 convert_numpy_str_to_uint32
310 convert_to_numpy_str
311
312 """
313 # An empty string should be an empty uint16
314 if data.nbytes == 0:
315 return np.uint16([])
316
317 # We need to use the UTF-16 codec for our endianness. Using the
318 # right one means we don't have to worry about removing the BOM.
319 if sys.byteorder == 'little':
320 codec = 'UTF-16LE'
321 else:
322 codec = 'UTF-16BE'
323
324 # numpy.char.encode can do the conversion element wise. Then, we
325 # just have convert to uin16 with the appropriate dimensions. The
326 # dimensions are gotten from the shape of the converted data with
327 # the number of column increased by the number of words (pair of
328 # bytes) in the strings.
329 cdata = np.char.encode(np.atleast_1d(data), codec)
330 shape = list(cdata.shape)
331 shape[-1] *= (cdata.dtype.itemsize // 2)
332 return np.ndarray(shape=shape, dtype='uint16',
333 buffer=numpy_to_bytes(cdata))
334
335
336 def convert_numpy_str_to_uint32(data):
337 """ Converts a numpy.str\\_ to its numpy.uint32 representation.
338
339 Convert a ``numpy.str`` or an array of them (they are UTF-32
340 strings) into the equivalent array of ``numpy.uint32`` that is byte
341 for byte identical. Strings are expanded along rows (across columns)
342 so a 2x3x4 array of 10 element strings will get turned into a 2x30x4
343 array of uint32's.
344
345 Parameters
346 ----------
347 data : numpy.str\\_ or numpy.ndarray of numpy.str\\_
348 The string or array of them to convert.
349
350 Returns
351 -------
352 numpy.ndarray of numpy.uint32
353 The result of the conversion.
354
355 See Also
356 --------
357 convert_numpy_str_to_uint16
358 decode_to_numpy_str
359
360 """
361 if data.nbytes == 0:
362 # An empty string should be an empty uint32.
363 return np.uint32([])
364 else:
365 # We need to calculate the new shape from the current shape,
366 # which will have to be expanded along the rows to fit all the
367 # characters (the dtype.itemsize gets the number of bytes in
368 # each string, which is just 4 times the number of
369 # characters. Then it is a mstter of getting a view of the
370 # string (in flattened form so that it is contiguous) as uint32
371 # and then reshaping it.
372 shape = list(np.atleast_1d(data).shape)
373 shape[-1] *= data.dtype.itemsize//4
374 return data.flatten().view(np.uint32).reshape(tuple(shape))
375
376 def convert_to_str(data):
377 """ Decodes data to the Python 3.x str (Python 2.x unicode) type.
378
379 Decodes `data` to a Python 3.x ``str`` (Python 2.x ``unicode``). If
380 it can't be decoded, it is returned as is. Unsigned integers, Python
381 ``bytes``, and Numpy strings (``numpy.str_`` and
382 ``numpy.bytes_``). Python 3.x ``bytes``, Python 2.x ``str``, and
383 ``numpy.bytes_`` are assumed to be encoded in UTF-8.
384
385 Parameters
386 ----------
387 data : some type
388 Data decode into an ``str`` string.
389
390 Returns
391 -------
392 str or data
393 If `data` can be decoded into a ``str``, the decoded version is
394 returned. Otherwise, `data` is returned unchanged.
395
396 See Also
397 --------
398 convert_to_numpy_str
399 convert_to_numpy_bytes
400
401 """
402 # How the conversion is done depends on the exact underlying
403 # type. Numpy types are handled separately. For uint types, it is
404 # assumed to be stored as UTF-8, UTF-16, or UTF-32 depending on the
405 # size when converting to an str. numpy.string_ is just like
406 # converting a bytes. numpy.unicode has to be encoded into bytes
407 # before it can be decoded back into an str. bytes is decoded
408 # assuming it is in UTF-8. Otherwise, data has to be returned as is.
409
410 if isinstance(data, (np.ndarray, np.uint8, np.uint16, np.uint32,
411 np.bytes_, np.unicode_)):
412 if data.dtype.name == 'uint8':
413 return numpy_to_bytes(data.flatten()).decode('UTF-8')
414 elif data.dtype.name == 'uint16':
415 return numpy_to_bytes(data.flatten()).decode('UTF-16')
416 elif data.dtype.name == 'uint32':
417 return numpy_to_bytes(data.flatten()).decode('UTF-32')
418 elif data.dtype.char == 'S':
419 return data.decode('UTF-8')
420 else:
421 if isinstance(data, np.ndarray):
422 return numpy_to_bytes(data.flatten()).decode('UTF-32')
423 else:
424 return data.encode('UTF-32').decode('UTF-32')
425
426 if isinstance(data, bytes):
427 return data.decode('UTF-8')
428 else:
429 return data
430
431
432 def convert_to_numpy_str(data, length=None):
433 """ Decodes data to Numpy unicode string (str\\_).
434
435 Decodes `data` to Numpy unicode string (UTF-32), which is
436 ``numpy.str_``, or an array of them. If it can't be decoded, it is
437 returned as is. Unsigned integers, Python string types (``str``,
438 ``bytes``), and ``numpy.bytes_`` are supported. If it is an array of
439 ``numpy.bytes_``, an array of those all converted to ``numpy.str_``
440 is returned. Python 3.x ``bytes``, Python 2.x ``str``, and
441 ``numpy.bytes_`` are assumed to be encoded in UTF-8.
442
443 For an array of unsigned integers, it may be desirable to make an
444 array with strings of some specified length as opposed to an array
445 of the same size with each element being a one element string. This
446 naturally arises when converting strings to unsigned integer types
447 in the first place, so it needs to be reversible. The `length`
448 parameter specifies how many to group together into a string
449 (desired string length). For 1d arrays, this is along its only
450 dimension. For higher dimensional arrays, it is done along each row
451 (across columns). So, for a 3x10x5 input array of uints and a
452 `length` of 5, the output array would be a 3x2x5 of 5 element
453 strings.
454
455 Parameters
456 ----------
457 data : some type
458 Data decode into a Numpy unicode string.
459 length : int or None, optional
460 The number of consecutive elements (in the case of unsigned
461 integer `data`) to compose each string in the output array from.
462 ``None`` indicates the full amount for a 1d array or the number
463 of columns (full length of row) for a higher dimension array.
464
465 Returns
466 -------
467 numpy.str\\_ or numpy.ndarray of numpy.str\\_ or data
468 If `data` can be decoded into a ``numpy.str_`` or a
469 ``numpy.ndarray`` of them, the decoded version is returned.
470 Otherwise, `data` is returned unchanged.
471
472 See Also
473 --------
474 convert_to_str
475 convert_to_numpy_bytes
476 numpy.str_
477
478 """
479 # The method of conversion depends on its type.
480 if isinstance(data, np.unicode_) or (isinstance(data, np.ndarray) \
481 and data.dtype.char == 'U'):
482 # It is already an np.str_ or array of them, so nothing needs to
483 # be done.
484 return data
485 elif (sys.hexversion >= 0x03000000 and isinstance(data, str)) \
486 or (sys.hexversion < 0x03000000 \
487 and isinstance(data, unicode)):
488 # Easily converted through constructor.
489 return np.unicode_(data)
490 elif isinstance(data, (bytes, bytearray, np.bytes_)):
491 # All of them can be decoded and then passed through the
492 # constructor.
493 return np.unicode_(data.decode('UTF-8'))
494 elif isinstance(data, (np.uint8, np.uint16)):
495 # They are single UTF-8 or UTF-16 scalars, and are easily
496 # converted to a UTF-8 string and then passed through the
497 # constructor.
498 return np.unicode_(convert_to_str(data))
499 elif isinstance(data, np.uint32):
500 # It is just the uint32 version of the character, so it just
501 # needs to be have the dtype essentially changed by having its
502 # bytes read into ndarray.
503 return np.ndarray(shape=tuple(), dtype='U1',
504 buffer=numpy_to_bytes(data.flatten()))[()]
505 elif isinstance(data, np.ndarray) and data.dtype.char == 'S':
506 # We just need to convert it elementwise.
507 new_data = np.zeros(shape=data.shape,
508 dtype='U' + str(data.dtype.itemsize))
509 for index, x in np.ndenumerate(data):
510 new_data[index] = np.unicode_(x.decode('UTF-8'))
511 return new_data
512 elif isinstance(data, np.ndarray) \
513 and data.dtype.name in ('uint8', 'uint16', 'uint32'):
514 # It is an ndarray of some uint type. How it is converted
515 # depends on its shape. If its shape is just (), then it is just
516 # a scalar wrapped in an array, which can be converted by
517 # recursing the scalar value back into this function.
518 shape = list(data.shape)
519 if len(shape) == 0:
520 return convert_to_numpy_str(data[()])
521
522 # As there are more than one element, it gets a bit more
523 # complicated. We need to take the subarrays of the specified
524 # length along columns (1D arrays will be treated as row arrays
525 # here), each of those converted to an str_ scalar (normal
526 # string) and stuffed into a new array.
527 #
528 # If the length was not given, it needs to be set to full. Then
529 # the shape of the new array needs to be calculated (divide the
530 # appropriate dimension, which depends on the number of
531 # dimentions).
532 if len(shape) == 1:
533 if length is None:
534 length = shape[0]
535 new_shape = (shape[0]//length,)
536 else:
537 if length is None:
538 length = shape[-1]
539 new_shape = copy.deepcopy(shape)
540 new_shape[-1] //= length
541
542 # The new array can be made as all zeros (nulls) with enough
543 # padding to hold everything (dtype='UL' where 'L' is the
544 # length). It will start out as a 1d array and be reshaped into
545 # the proper shape later (makes indexing easier).
546 new_data = np.zeros(shape=(np.prod(new_shape),),
547 dtype='U'+str(length))
548
549 # With data flattened into a 1d array, we just need to take
550 # length sized chunks, convert them (if they are uint8 or 16,
551 # then decode to str first, if they are uint32, put them as an
552 # input buffer for an ndarray of type 'U').
553 data = data.flatten()
554 for i in range(0, new_data.shape[0]):
555 chunk = data[(i*length):((i+1)*length)]
556 if data.dtype.name == 'uint32':
557 new_data[i] = np.ndarray(
558 shape=tuple(),
559 dtype=new_data.dtype,
560 buffer=numpy_to_bytes(chunk))[()]
561 else:
562 new_data[i] = np.unicode_(convert_to_str(chunk))
563
564 # Only thing is left is to reshape it.
565 return new_data.reshape(tuple(new_shape))
566 else:
567 # Couldn't figure out what it is, so nothing can be done but
568 # return it as is.
569 return data
570
571
572 def convert_to_numpy_bytes(data, length=None):
573 """ Decodes data to Numpy UTF-8 econded string (bytes\\_).
574
575 Decodes `data` to a Numpy UTF-8 encoded string, which is
576 ``numpy.bytes_``, or an array of them in which case it will be ASCII
577 encoded instead. If it can't be decoded, it is returned as
578 is. Unsigned integers, Python string types (``str``, ``bytes``), and
579 ``numpy.str_`` (UTF-32) are supported.
580
581 For an array of unsigned integers, it may be desirable to make an
582 array with strings of some specified length as opposed to an array
583 of the same size with each element being a one element string. This
584 naturally arises when converting strings to unsigned integer types
585 in the first place, so it needs to be reversible. The `length`
586 parameter specifies how many to group together into a string
587 (desired string length). For 1d arrays, this is along its only
588 dimension. For higher dimensional arrays, it is done along each row
589 (across columns). So, for a 3x10x5 input array of uints and a
590 `length` of 5, the output array would be a 3x2x5 of 5 element
591 strings.
592
593 Parameters
594 ----------
595 data : some type
596 Data decode into a Numpy UTF-8 encoded string/s.
597 length : int or None, optional
598 The number of consecutive elements (in the case of unsigned
599 integer `data`) to compose each string in the output array from.
600 ``None`` indicates the full amount for a 1d array or the number
601 of columns (full length of row) for a higher dimension array.
602
603 Returns
604 -------
605 numpy.bytes\\_ or numpy.ndarray of numpy.bytes\\_ or data
606 If `data` can be decoded into a ``numpy.bytes_`` or a
607 ``numpy.ndarray`` of them, the decoded version is returned.
608 Otherwise, `data` is returned unchanged.
609
610 See Also
611 --------
612 convert_to_str
613 convert_to_numpy_str
614 numpy.bytes_
615
616 """
617 # The method of conversion depends on its type.
618 if isinstance(data, np.bytes_) or (isinstance(data, np.ndarray) \
619 and data.dtype.char == 'S'):
620 # It is already an np.bytes_ or array of them, so nothing needs
621 # to be done.
622 return data
623 elif isinstance(data, (bytes, bytearray)):
624 # Easily converted through constructor.
625 return np.bytes_(data)
626 elif (sys.hexversion >= 0x03000000 and isinstance(data, str)) \
627 or (sys.hexversion < 0x03000000 \
628 and isinstance(data, unicode)):
629 return np.bytes_(data.encode('UTF-8'))
630 elif isinstance(data, (np.uint16, np.uint32)):
631 # They are single UTF-16 or UTF-32 scalars, and are easily
632 # converted to a UTF-8 string and then passed through the
633 # constructor.
634 return np.bytes_(convert_to_str(data).encode('UTF-8'))
635 elif isinstance(data, np.uint8):
636 # It is just the uint8 version of the character, so it just
637 # needs to be have the dtype essentially changed by having its
638 # bytes read into ndarray.
639 return np.ndarray(shape=tuple(), dtype='S1',
640 buffer=numpy_to_bytes(data.flatten()))[()]
641 elif isinstance(data, np.ndarray) and data.dtype.char == 'U':
642 # We just need to convert it elementwise.
643 new_data = np.zeros(shape=data.shape,
644 dtype='S' + str(data.dtype.itemsize))
645 for index, x in np.ndenumerate(data):
646 new_data[index] = np.bytes_(x.encode('UTF-8'))
647 return new_data
648 elif isinstance(data, np.ndarray) \
649 and data.dtype.name in ('uint8', 'uint16', 'uint32'):
650 # It is an ndarray of some uint type. How it is converted
651 # depends on its shape. If its shape is just (), then it is just
652 # a scalar wrapped in an array, which can be converted by
653 # recursing the scalar value back into this function.
654 shape = list(data.shape)
655 if len(shape) == 0:
656 return convert_to_numpy_bytes(data[()])
657
658 # As there are more than one element, it gets a bit more
659 # complicated. We need to take the subarrays of the specified
660 # length along columns (1D arrays will be treated as row arrays
661 # here), each of those converted to an str_ scalar (normal
662 # string) and stuffed into a new array.
663 #
664 # If the length was not given, it needs to be set to full. Then
665 # the shape of the new array needs to be calculated (divide the
666 # appropriate dimension, which depends on the number of
667 # dimentions).
668 if len(shape) == 1:
669 if length is None:
670 length2 = shape[0]
671 new_shape = (shape[0],)
672 else:
673 length2 = length
674 new_shape = (shape[0]//length2,)
675 else:
676 if length is None:
677 length2 = shape[-1]
678 else:
679 length2 = length
680 new_shape = copy.deepcopy(shape)
681 new_shape[-1] //= length2
682
683 # The new array can be made as all zeros (nulls) with enough
684 # padding to hold everything (dtype='UL' where 'L' is the
685 # length). It will start out as a 1d array and be reshaped into
686 # the proper shape later (makes indexing easier).
687 new_data = np.zeros(shape=(np.prod(new_shape),),
688 dtype='S'+str(length2))
689
690 # With data flattened into a 1d array, we just need to take
691 # length sized chunks, convert them (if they are uint8 or 16,
692 # then decode to str first, if they are uint32, put them as an
693 # input buffer for an ndarray of type 'U').
694 data = data.flatten()
695 for i in range(0, new_data.shape[0]):
696 chunk = data[(i*length2):((i+1)*length2)]
697 if data.dtype.name == 'uint8':
698 new_data[i] = np.ndarray(
699 shape=tuple(),
700 dtype=new_data.dtype,
701 buffer=numpy_to_bytes(chunk))[()]
702 else:
703 new_data[i] = np.bytes_( \
704 convert_to_str(chunk).encode('UTF-8'))
705
706 # Only thing is left is to reshape it.
707 return new_data.reshape(tuple(new_shape))
708 else:
709 # Couldn't figure out what it is, so nothing can be done but
710 # return it as is.
711 return data
712
713
714 def decode_complex(data, complex_names=(None, None)):
715 """ Decodes possibly complex data read from an HDF5 file.
716
717 Decodes possibly complex datasets read from an HDF5 file. HDF5
718 doesn't have a native complex type, so they are stored as
719 H5T_COMPOUND types with fields such as 'r' and 'i' for the real and
720 imaginary parts. As there is no standardization for field names, the
721 field names have to be given explicitly, or the fieldnames in `data`
722 analyzed for proper decoding to figure out the names. A variety of
723 reasonably expected combinations of field names are checked and used
724 if available to decode. If decoding is not possible, it is returned
725 as is.
726
727 Parameters
728 ----------
729 data : arraylike
730 The data read from an HDF5 file, that might be complex, to
731 decode into the proper Numpy complex type.
732 complex_names : tuple of 2 str and/or Nones, optional
733 ``tuple`` of the names to use (in order) for the real and
734 imaginary fields. A ``None`` indicates that various common
735 field names should be tried.
736
737 Returns
738 -------
739 decoded data or data
740 If `data` can be decoded into a complex type, the decoded
741 complex version is returned. Otherwise, `data` is returned
742 unchanged.
743
744 See Also
745 --------
746 encode_complex
747
748 Notes
749 -----
750 Currently looks for real field names of ``('r', 're', 'real')`` and
751 imaginary field names of ``('i', 'im', 'imag', 'imaginary')``
752 ignoring case.
753
754 """
755 # Now, complex types are stored in HDF5 files as an H5T_COMPOUND type
756 # with fields along the lines of ('r', 're', 'real') and ('i', 'im',
757 # 'imag', 'imaginary') for the real and imaginary parts, which most
758 # likely won't be properly extracted back into making a Python
759 # complex type unless the proper h5py configuration is set. Since we
760 # can't depend on it being set and adjusting it is hazardous (the
761 # setting is global), it is best to just decode it manually. These
762 # fields are obtained from the fields of its dtype. Obviously, if
763 # there are no fields, then there is nothing to do.
764 if data.dtype.fields is None:
765 return data
766
767 fields = list(data.dtype.fields)
768
769 # If there aren't exactly two fields, then it can't be complex.
770 if len(fields) != 2:
771 return data
772
773 # We need to grab the field names for the real and imaginary
774 # parts. This will be done by seeing which list, if any, each field
775 # is and setting variables to the proper name if it is in it (they
776 # are initialized to None so that we know if one isn't found).
777
778 real_fields = ['r', 're', 'real']
779 imag_fields = ['i', 'im', 'imag', 'imaginary']
780
781 cnames = list(complex_names)
782 for s in fields:
783 if s.lower() in real_fields:
784 cnames[0] = s
785 elif s.lower() in imag_fields:
786 cnames[1] = s
787
788 # If the real and imaginary fields were found, construct the complex
789 # form from the fields. This is done by finding the complex type
790 # that they cast to, making an array, and then setting the
791 # parts. Otherwise, return what we were given because it isn't in
792 # the right form.
793 if cnames[0] is not None and cnames[1] is not None:
794 cdata = np.result_type(data[cnames[0]].dtype, \
795 data[cnames[1]].dtype, 'complex64').type(data[cnames[0]])
796 cdata.imag = data[cnames[1]]
797 return cdata
798 else:
799 return data
800
801
802 def encode_complex(data, complex_names):
803 """ Encodes complex data to having arbitrary complex field names.
804
805 Encodes complex `data` to have the real and imaginary field names
806 given in `complex_numbers`. This is needed because the field names
807 have to be set so that it can be written to an HDF5 file with the
808 right field names (HDF5 doesn't have a native complex type, so
809 H5T_COMPOUND have to be used).
810
811 Parameters
812 ----------
813 data : arraylike
814 The data to encode as a complex type with the desired real and
815 imaginary part field names.
816 complex_names : tuple of 2 str
817 ``tuple`` of the names to use (in order) for the real and
818 imaginary fields.
819
820 Returns
821 -------
822 encoded data
823 `data` encoded into having the specified field names for the
824 real and imaginary parts.
825
826 See Also
827 --------
828 decode_complex
829
830 """
831 # Grab the dtype name, and convert it to the right non-complex type
832 # if it isn't already one.
833 dtype_name = data.dtype.name
834 if dtype_name[0:7] == 'complex':
835 dtype_name = 'float' + str(int(float(dtype_name[7:])/2))
836
837 # Create the new version of the data with the right field names for
838 # the real and complex parts. This is easy to do with putting the
839 # right detype in the view function.
840 dt = np.dtype([(complex_names[0], dtype_name),
841 (complex_names[1], dtype_name)])
842 return data.view(dt).copy()
843
844
845 def get_attribute(target, name):
846 """ Gets an attribute from a Dataset or Group.
847
848 Gets the value of an Attribute if it is present (get ``None`` if
849 not).
850
851 Parameters
852 ----------
853 target : Dataset or Group
854 Dataset or Group to get the attribute of.
855 name : str
856 Name of the attribute to get.
857
858 Returns
859 -------
860 The value of the attribute if it is present, or ``None`` if it
861 isn't.
862
863 """
864 try:
865 return target.attrs[name]
866 except:
867 return None
868
869
870 def get_attribute_string(target, name):
871 """ Gets a string attribute from a Dataset or Group.
872
873 Gets the value of an Attribute that is a string if it is present
874 (get ``None`` if it is not present or isn't a string type).
875
876 Parameters
877 ----------
878 target : Dataset or Group
879 Dataset or Group to get the string attribute of.
880 name : str
881 Name of the attribute to get.
882
883 Returns
884 -------
885 str or None
886 The ``str`` value of the attribute if it is present, or ``None``
887 if it isn't or isn't a type that can be converted to ``str``
888
889 """
890 value = get_attribute(target, name)
891 if value is None:
892 return value
893 elif (sys.hexversion >= 0x03000000 and isinstance(value, str)) \
894 or (sys.hexversion < 0x03000000 \
895 and isinstance(value, unicode)):
896 return value
897 elif isinstance(value, bytes):
898 return value.decode()
899 elif isinstance(value, np.unicode_):
900 return str(value)
901 elif isinstance(value, np.bytes_):
902 return value.decode()
903 else:
904 return None
905
906
907 def get_attribute_string_array(target, name):
908 """ Gets a string array Attribute from a Dataset or Group.
909
910 Gets the value of an Attribute that is a string array if it is
911 present (get ``None`` if not).
912
913 Parameters
914 ----------
915 target : Dataset or Group
916 Dataset or Group to get the attribute of.
917 name : str
918 Name of the string array Attribute to get.
919
920 Returns
921 -------
922 list of str or None
923 The string array value of the Attribute if it is present, or
924 ``None`` if it isn't.
925
926 """
927 value = get_attribute(target, name)
928 if value is None:
929 return value
930 return [convert_to_str(x) for x in value]
931
932
933 def set_attribute(target, name, value):
934 """ Sets an attribute on a Dataset or Group.
935
936 If the attribute `name` doesn't exist yet, it is created. If it
937 already exists, it is overwritten if it differs from `value`.
938
939 Parameters
940 ----------
941 target : Dataset or Group
942 Dataset or Group to set the attribute of.
943 name : str
944 Name of the attribute to set.
945 value : numpy type other than ``numpy.str_``
946 Value to set the attribute to.
947
948 """
949
950 # use alias to speed up the code
951 target_attributes = target.attrs
952 if name not in target_attributes:
953 target_attributes.create(name, value)
954 elif name == 'MATLAB_fields':
955 if not np.array_equal(value, read_matlab_fields_attribute(
956 target_attributes)):
957 target_attributes.create(name, value)
958 else:
959 attr = target_attributes[name]
960 if attr.dtype != value.dtype \
961 or attr.shape != value.shape:
962 target_attributes.create(name, value)
963 elif np.any(attr != value):
964 target_attributes.modify(name, value)
965
966
967 def set_attribute_string(target, name, value):
968 """ Sets an attribute to a string on a Dataset or Group.
969
970 If the attribute `name` doesn't exist yet, it is created. If it
971 already exists, it is overwritten if it differs from `value`.
972
973 Parameters
974 ----------
975 target : Dataset or Group
976 Dataset or Group to set the string attribute of.
977 name : str
978 Name of the attribute to set.
979 value : string
980 Value to set the attribute to. Can be any sort of string type
981 that will convert to a ``numpy.bytes_``
982
983 """
984 set_attribute(target, name, np.bytes_(value))
985
986
987 def set_attribute_string_array(target, name, string_list):
988 """ Sets an attribute to an array of string on a Dataset or Group.
989
990 If the attribute `name` doesn't exist yet, it is created. If it
991 already exists, it is overwritten with the list of string
992 `string_list` (they will be vlen strings).
993
994 Parameters
995 ----------
996 target : Dataset or Group
997 Dataset or Group to set the string array attribute of.
998 name : str
999 Name of the attribute to set.
1000 string_list : list of str
1001 List of strings to set the attribute to. Strings must be ``str``
1002
1003 """
1004 s_list = [convert_to_str(s) for s in string_list]
1005 if sys.hexversion >= 0x03000000:
1006 target.attrs.create(name, s_list,
1007 dtype=h5py.special_dtype(vlen=str))
1008 else:
1009 target.attrs.create(name, s_list,
1010 dtype=h5py.special_dtype(vlen=unicode))
1011
1012
1013 def del_attribute(target, name):
1014 """ Deletes an attribute on a Dataset or Group.
1015
1016 If the attribute `name` exists, it is deleted.
1017
1018 Parameters
1019 ----------
1020 target : Dataset or Group
1021 Dataset or Group to delete attribute of.
1022 name : str
1023 Name of the attribute to delete.
1024
1025 """
1026 attr_manager = target.attrs
1027 if name in attr_manager:
1028 del attr_manager[name]