| 1 |
# Copyright (c) 2013-2023, 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 for the classes to marshall Python types to/from file. |
| 28 |
|
| 29 |
""" |
| 30 |
|
| 31 |
import sys |
| 32 |
import posixpath |
| 33 |
import collections |
| 34 |
|
| 35 |
try: |
| 36 |
from pkg_resources import parse_version |
| 37 |
except: |
| 38 |
from distutils.version import StrictVersion as parse_version |
| 39 |
|
| 40 |
import numpy as np |
| 41 |
import h5py |
| 42 |
|
| 43 |
from hdf5storage.utilities import * |
| 44 |
from hdf5storage import lowlevel |
| 45 |
from hdf5storage.lowlevel import write_data, read_data |
| 46 |
|
| 47 |
|
| 48 |
# Ubuntu 12.04's h5py doesn't have __version__ set so we need to try to |
| 49 |
# grab the version and if it isn't available, just assume it is 2.0. |
| 50 |
try: |
| 51 |
_H5PY_VERSION = h5py.__version__ |
| 52 |
except: |
| 53 |
_H5PY_VERSION = '2.0' |
| 54 |
|
| 55 |
|
| 56 |
def write_object_array(f, data, options): |
| 57 |
""" Writes an array of objects recursively. |
| 58 |
|
| 59 |
Writes the elements of the given object array recursively in the |
| 60 |
HDF5 Group ``options.group_for_references`` and returns an |
| 61 |
``h5py.Reference`` array to all the elements. |
| 62 |
|
| 63 |
Parameters |
| 64 |
---------- |
| 65 |
f : h5py.File |
| 66 |
The HDF5 file handle that is open. |
| 67 |
data : numpy.ndarray of objects |
| 68 |
Numpy object array to write the elements of. |
| 69 |
options : hdf5storage.core.Options |
| 70 |
hdf5storage options object. |
| 71 |
|
| 72 |
Returns |
| 73 |
------- |
| 74 |
numpy.ndarray of h5py.Reference |
| 75 |
A reference array pointing to all the elements written to the |
| 76 |
HDF5 file. For those that couldn't be written, the respective |
| 77 |
element points to the canonical empty. |
| 78 |
|
| 79 |
Raises |
| 80 |
------ |
| 81 |
TypeNotMatlabCompatibleError |
| 82 |
If writing a type not compatible with MATLAB and |
| 83 |
`options.action_for_matlab_incompatible` is set to ``'error'``. |
| 84 |
|
| 85 |
See Also |
| 86 |
-------- |
| 87 |
read_object_array |
| 88 |
hdf5storage.Options.group_for_references |
| 89 |
h5py.Reference |
| 90 |
|
| 91 |
""" |
| 92 |
# We need to grab the special reference dtype and make an empty |
| 93 |
# array to store all the references in. |
| 94 |
ref_dtype = h5py.special_dtype(ref=h5py.Reference) |
| 95 |
data_refs = np.zeros(shape=data.shape, dtype='object') |
| 96 |
|
| 97 |
# We need to make sure that the group to hold references is present, |
| 98 |
# and create it if it isn't. |
| 99 |
|
| 100 |
if options.group_for_references not in f: |
| 101 |
f.create_group(options.group_for_references) |
| 102 |
|
| 103 |
grp2 = f[options.group_for_references] |
| 104 |
|
| 105 |
if not isinstance(grp2, h5py.Group): |
| 106 |
del f[options.group_for_references] |
| 107 |
f.create_group(options.group_for_references) |
| 108 |
grp2 = f[options.group_for_references] |
| 109 |
|
| 110 |
# The Dataset 'a' needs to be present as the canonical empty. It is |
| 111 |
# just and np.uint32/64([0, 0]) with its a MATLAB_class of |
| 112 |
# 'canonical empty' and the 'MATLAB_empty' attribute set. If it |
| 113 |
# isn't present or is incorrectly formatted, it is created |
| 114 |
# truncating anything previously there. |
| 115 |
if 'a' not in grp2 or grp2['a'].shape != (2,) \ |
| 116 |
or not grp2['a'].dtype.name.startswith('uint') \ |
| 117 |
or np.any(grp2['a'][...] != np.uint64([0, 0])) \ |
| 118 |
or get_attribute_string(grp2['a'], 'MATLAB_class') != \ |
| 119 |
'canonical empty' \ |
| 120 |
or get_attribute(grp2['a'], 'MATLAB_empty') != 1: |
| 121 |
if 'a' in grp2: |
| 122 |
del grp2['a'] |
| 123 |
grp2.create_dataset('a', data=np.uint64([0, 0])) |
| 124 |
set_attribute_string(grp2['a'], 'MATLAB_class', |
| 125 |
'canonical empty') |
| 126 |
set_attribute(grp2['a'], 'MATLAB_empty', |
| 127 |
np.uint8(1)) |
| 128 |
|
| 129 |
# Go through all the elements of data and write them, gabbing their |
| 130 |
# references and putting them in data_refs. They will be put in |
| 131 |
# group_for_references, which is also what the H5PATH needs to be |
| 132 |
# set to if we are doing MATLAB compatibility (otherwise, the |
| 133 |
# attribute needs to be deleted). If an element can't be written |
| 134 |
# (doing matlab compatibility, but it isn't compatible with matlab |
| 135 |
# and action_for_matlab_incompatible option is True), the reference |
| 136 |
# to the canonical empty will be used for the reference array to |
| 137 |
# point to. |
| 138 |
for index, x in np.ndenumerate(data): |
| 139 |
data_refs[index] = None |
| 140 |
name_for_ref = next_unused_name_in_group(grp2, 16) |
| 141 |
write_data(f, grp2, name_for_ref, x, None, options) |
| 142 |
if name_for_ref in grp2: |
| 143 |
data_refs[index] = grp2[name_for_ref].ref |
| 144 |
if options.matlab_compatible: |
| 145 |
set_attribute_string(grp2[name_for_ref], |
| 146 |
'H5PATH', grp2.name) |
| 147 |
else: |
| 148 |
del_attribute(grp2[name_for_ref], 'H5PATH') |
| 149 |
else: |
| 150 |
data_refs[index] = grp2['a'].ref |
| 151 |
|
| 152 |
# Now, the dtype needs to be changed to the reference type and the |
| 153 |
# whole thing copied over to data_to_store. |
| 154 |
return data_refs.astype(ref_dtype).copy() |
| 155 |
|
| 156 |
|
| 157 |
def read_object_array(f, data, options): |
| 158 |
""" Reads an array of objects recursively. |
| 159 |
|
| 160 |
Read the elements of the given HDF5 Reference array recursively |
| 161 |
in the and constructs a ``numpy.object_`` array from its elements, |
| 162 |
which is returned. |
| 163 |
|
| 164 |
Parameters |
| 165 |
---------- |
| 166 |
f : h5py.File |
| 167 |
The HDF5 file handle that is open. |
| 168 |
data : numpy.ndarray of h5py.Reference |
| 169 |
The array of HDF5 References to read and make an object array |
| 170 |
from. |
| 171 |
options : hdf5storage.core.Options |
| 172 |
hdf5storage options object. |
| 173 |
|
| 174 |
Raises |
| 175 |
------ |
| 176 |
NotImplementedError |
| 177 |
If reading the object from file is currently not supported. |
| 178 |
|
| 179 |
Returns |
| 180 |
------- |
| 181 |
numpy.ndarray of numpy.object\\_ |
| 182 |
The Python object array containing the items pointed to by |
| 183 |
`data`. |
| 184 |
|
| 185 |
See Also |
| 186 |
-------- |
| 187 |
write_object_array |
| 188 |
hdf5storage.Options.group_for_references |
| 189 |
h5py.Reference |
| 190 |
|
| 191 |
""" |
| 192 |
# Go through all the elements of data and read them using their |
| 193 |
# references, and the putting the output in new object array. |
| 194 |
data_derefed = np.zeros(shape=data.shape, dtype='object') |
| 195 |
for index, x in np.ndenumerate(data): |
| 196 |
try: |
| 197 |
data_derefed[index] = read_data(f, f[x].parent, \ |
| 198 |
posixpath.basename(f[x].name), options) |
| 199 |
except: |
| 200 |
raise |
| 201 |
return data_derefed |
| 202 |
|
| 203 |
|
| 204 |
class TypeMarshaller(object): |
| 205 |
""" Base class for marshallers of Python types. |
| 206 |
|
| 207 |
Base class providing the class interface for marshallers of Python |
| 208 |
types to/from disk. All marshallers should inherit from this class |
| 209 |
or at least replicate its functionality. This includes several |
| 210 |
attributes that are needed in order for reading/writing methods to |
| 211 |
know if it is the appropriate marshaller to use and methods to |
| 212 |
actually do the reading and writing. |
| 213 |
|
| 214 |
Subclasses should run this class's ``__init__()`` first |
| 215 |
thing. Inheritance information is in the **Notes** section of each |
| 216 |
method. Generally, ``read``, ``write``, and ``write_metadata`` need |
| 217 |
to be overridden and the different attributes set to the proper |
| 218 |
values. |
| 219 |
|
| 220 |
For marshalling types that are containers of other data, one will |
| 221 |
need to appropriate read/write them with the lowlevel functions |
| 222 |
``lowlevel.read_data`` and ``lowlevel.write_data``. |
| 223 |
|
| 224 |
Attributes |
| 225 |
---------- |
| 226 |
python_attributes : set of str |
| 227 |
Attributes used to store type information. |
| 228 |
matlab_attributes : set of str |
| 229 |
Attributes used for MATLAB compatibility. |
| 230 |
types : list of types |
| 231 |
Types the marshaller can work on. |
| 232 |
python_type_strings : list of str |
| 233 |
Type strings of readable types. |
| 234 |
matlab_classes : list of str |
| 235 |
Readable MATLAB classes. |
| 236 |
|
| 237 |
See Also |
| 238 |
-------- |
| 239 |
hdf5storage.core.Options |
| 240 |
h5py.Dataset |
| 241 |
h5py.Group |
| 242 |
h5py.AttributeManager |
| 243 |
hdf5storage.lowlevel.read_data |
| 244 |
hdf5storage.lowlevel.write_data |
| 245 |
|
| 246 |
""" |
| 247 |
def __init__(self): |
| 248 |
#: Attributes used to store type information. |
| 249 |
#: |
| 250 |
#: set of str |
| 251 |
#: |
| 252 |
#: ``set`` of attribute names the marshaller uses when |
| 253 |
#: an ``Option.store_python_metadata`` is ``True``. |
| 254 |
self.python_attributes = set(['Python.Type']) |
| 255 |
|
| 256 |
#: Attributes used for MATLAB compatibility. |
| 257 |
#: |
| 258 |
#: ``set`` of ``str`` |
| 259 |
#: |
| 260 |
#: ``set`` of attribute names the marshaller uses when maintaing |
| 261 |
#: Matlab HDF5 based mat file compatibility |
| 262 |
#: (``Option.matlab_compatible`` is ``True``). |
| 263 |
self.matlab_attributes = set(['H5PATH']) |
| 264 |
|
| 265 |
#: List of Python types that can be marshalled. |
| 266 |
#: |
| 267 |
#: list of types |
| 268 |
#: |
| 269 |
#: ``list`` of the types (gotten by doing ``type(data)``) that the |
| 270 |
#: marshaller can marshall. Default value is ``[]``. |
| 271 |
self.types = [] |
| 272 |
|
| 273 |
#: Type strings of readable types. |
| 274 |
#: |
| 275 |
#: list of str |
| 276 |
#: |
| 277 |
#: ``list`` of the ``str`` that the marshaller would put in the |
| 278 |
#: HDF5 attribute 'Python.Type' to identify the Python type to be |
| 279 |
#: able to read it back correctly. Default value is ``[]``. |
| 280 |
self.python_type_strings = [] |
| 281 |
|
| 282 |
#: MATLAB class strings of readable types. |
| 283 |
#: |
| 284 |
#: list of str |
| 285 |
#: |
| 286 |
#: ``list`` of the MATLAB class ``str`` that the marshaller can |
| 287 |
#: read into Python objects. Default value is ``[]``. |
| 288 |
self.matlab_classes = [] |
| 289 |
|
| 290 |
def get_type_string(self, data, type_string): |
| 291 |
""" Gets type string. |
| 292 |
|
| 293 |
Finds the type string for 'data' contained in |
| 294 |
``python_type_strings`` using its ``type``. Non-``None`` |
| 295 |
'type_string` overrides whatever type string is looked up. |
| 296 |
The override makes it easier for subclasses to convert something |
| 297 |
that the parent marshaller can write to disk but still put the |
| 298 |
right type string in place). |
| 299 |
|
| 300 |
Parameters |
| 301 |
---------- |
| 302 |
data : type to be marshalled |
| 303 |
The Python object that is being written to disk. |
| 304 |
type_string : str or None |
| 305 |
If it is a ``str``, it overrides any looked up type |
| 306 |
string. ``None`` means don't override. |
| 307 |
|
| 308 |
Returns |
| 309 |
------- |
| 310 |
str |
| 311 |
The type string associated with 'data'. Will be |
| 312 |
'type_string' if it is not ``None``. |
| 313 |
|
| 314 |
Notes |
| 315 |
----- |
| 316 |
Subclasses probably do not need to override this method. |
| 317 |
|
| 318 |
""" |
| 319 |
if type_string is not None: |
| 320 |
return type_string |
| 321 |
else: |
| 322 |
i = self.types.index(type(data)) |
| 323 |
return self.python_type_strings[i] |
| 324 |
|
| 325 |
def write(self, f, grp, name, data, type_string, options): |
| 326 |
""" Writes an object's metadata to file. |
| 327 |
|
| 328 |
Writes the Python object 'data' to 'name' in h5py.Group 'grp'. |
| 329 |
|
| 330 |
Parameters |
| 331 |
---------- |
| 332 |
f : h5py.File |
| 333 |
The HDF5 file handle that is open. |
| 334 |
grp : h5py.Group or h5py.File |
| 335 |
The parent HDF5 Group (or File if at '/') that contains the |
| 336 |
object with the specified name. |
| 337 |
name : str |
| 338 |
Name of the object. |
| 339 |
data |
| 340 |
The object to write to file. |
| 341 |
type_string : str or None |
| 342 |
The type string for `data`. If it is ``None``, one will have |
| 343 |
to be gotten by ``get_type_string``. |
| 344 |
options : hdf5storage.core.Options |
| 345 |
hdf5storage options object. |
| 346 |
|
| 347 |
Raises |
| 348 |
------ |
| 349 |
NotImplementedError |
| 350 |
If writing 'data' to file is currently not supported. |
| 351 |
TypeNotMatlabCompatibleError |
| 352 |
If writing a type not compatible with MATLAB and |
| 353 |
`options.action_for_matlab_incompatible` is set to |
| 354 |
``'error'``. |
| 355 |
|
| 356 |
Notes |
| 357 |
----- |
| 358 |
Must be overridden in a subclass because a |
| 359 |
``NotImplementedError`` is thrown immediately. |
| 360 |
|
| 361 |
See Also |
| 362 |
-------- |
| 363 |
hdf5storage.lowlevel.write_data |
| 364 |
|
| 365 |
""" |
| 366 |
raise NotImplementedError('Can''t write data type: ' |
| 367 |
+ str(type(data))) |
| 368 |
|
| 369 |
def write_metadata(self, f, grp, name, data, type_string, options): |
| 370 |
""" Writes an object to file. |
| 371 |
|
| 372 |
Writes the metadata for a Python object `data` to file at `name` |
| 373 |
in h5py.Group `grp`. Metadata is written to HDF5 |
| 374 |
Attributes. Existing Attributes that are not being used are |
| 375 |
deleted. |
| 376 |
|
| 377 |
Parameters |
| 378 |
---------- |
| 379 |
f : h5py.File |
| 380 |
The HDF5 file handle that is open. |
| 381 |
grp : h5py.Group or h5py.File |
| 382 |
The parent HDF5 Group (or File if at '/') that contains the |
| 383 |
object with the specified name. |
| 384 |
name : str |
| 385 |
Name of the object. |
| 386 |
data |
| 387 |
The object to write to file. |
| 388 |
type_string : str or None |
| 389 |
The type string for `data`. If it is ``None``, one will have |
| 390 |
to be gotten by ``get_type_string``. |
| 391 |
options : hdf5storage.core.Options |
| 392 |
hdf5storage options object. |
| 393 |
|
| 394 |
Notes |
| 395 |
----- |
| 396 |
The attribute 'Python.Type' is set to the type string. All H5PY |
| 397 |
Attributes not in ``python_attributes`` and/or |
| 398 |
``matlab_attributes`` (depending on the attributes of 'options') |
| 399 |
are deleted. These are needed functions for writting essentially |
| 400 |
any Python object, so subclasses should probably call the |
| 401 |
baseclass's version of this function if they override it and |
| 402 |
just provide the additional functionality needed. This requires |
| 403 |
that the names of any additional HDF5 Attributes are put in the |
| 404 |
appropriate set. |
| 405 |
|
| 406 |
""" |
| 407 |
# Make sure we have a complete type_string. |
| 408 |
type_string = self.get_type_string(data, type_string) |
| 409 |
|
| 410 |
# The metadata that is written depends on the format. |
| 411 |
|
| 412 |
dsetgrp = grp[name] |
| 413 |
if options.store_python_metadata: |
| 414 |
set_attribute_string(dsetgrp, 'Python.Type', type_string) |
| 415 |
|
| 416 |
# If we are not storing python information or doing MATLAB |
| 417 |
# compatibility, then attributes not in the python and/or |
| 418 |
# MATLAB lists need to be removed. |
| 419 |
|
| 420 |
attributes_used = set() |
| 421 |
|
| 422 |
if options.store_python_metadata: |
| 423 |
attributes_used |= self.python_attributes |
| 424 |
|
| 425 |
if options.matlab_compatible: |
| 426 |
attributes_used |= self.matlab_attributes |
| 427 |
|
| 428 |
for attribute in (set(dsetgrp.attrs.keys()) - attributes_used): |
| 429 |
del_attribute(dsetgrp, attribute) |
| 430 |
|
| 431 |
def read(self, f, grp, name, options): |
| 432 |
""" Read a Python object from file. |
| 433 |
|
| 434 |
Reads the Python object 'name' from the HDF5 Group 'grp', if |
| 435 |
possible, and returns it. |
| 436 |
|
| 437 |
Parameters |
| 438 |
---------- |
| 439 |
f : h5py.File |
| 440 |
The HDF5 file handle that is open. |
| 441 |
grp : h5py.Group or h5py.File |
| 442 |
The parent HDF5 Group (or File if at '/') that contains the |
| 443 |
object with the specified name. |
| 444 |
name : str |
| 445 |
Name of the object. |
| 446 |
options : hdf5storage.core.Options |
| 447 |
hdf5storage options object. |
| 448 |
|
| 449 |
Raises |
| 450 |
------ |
| 451 |
NotImplementedError |
| 452 |
If reading the object from file is currently not supported. |
| 453 |
|
| 454 |
Returns |
| 455 |
------- |
| 456 |
data |
| 457 |
The Python object 'name' in the HDF5 Group 'grp'. |
| 458 |
|
| 459 |
Notes |
| 460 |
----- |
| 461 |
Must be overridden in a subclass because a |
| 462 |
``NotImplementedError`` is thrown immediately. |
| 463 |
|
| 464 |
See Also |
| 465 |
-------- |
| 466 |
hdf5storage.lowlevel.read_data |
| 467 |
|
| 468 |
""" |
| 469 |
raise NotImplementedError('Can''t read data: ' + name) |
| 470 |
|
| 471 |
|
| 472 |
class NumpyScalarArrayMarshaller(TypeMarshaller): |
| 473 |
def __init__(self): |
| 474 |
TypeMarshaller.__init__(self) |
| 475 |
self.python_attributes |= set(['Python.Shape', 'Python.Empty', |
| 476 |
'Python.numpy.UnderlyingType', |
| 477 |
'Python.numpy.Container', |
| 478 |
'Python.Fields']) |
| 479 |
self.matlab_attributes |= set(['MATLAB_class', 'MATLAB_empty', |
| 480 |
'MATLAB_int_decode', |
| 481 |
'MATLAB_fields']) |
| 482 |
# As np.str_ is the unicode type string in Python 3 and the bare |
| 483 |
# bytes string in Python 2, we have to use np.unicode_ which is |
| 484 |
# or points to the unicode one in both versions. |
| 485 |
self.types = [np.ndarray, np.matrix, |
| 486 |
np.chararray, np.core.records.recarray, |
| 487 |
np.bool_, np.void, |
| 488 |
np.uint8, np.uint16, np.uint32, np.uint64, |
| 489 |
np.int8, np.int16, np.int32, np.int64, |
| 490 |
np.float32, np.float64, |
| 491 |
np.complex64, np.complex128, |
| •492 |
np.bytes_, np.str_, np.object_] |
| 493 |
self._numpy_types = list(self.types) |
| 494 |
# Using Python 3 type strings. |
| 495 |
self.python_type_strings = ['numpy.ndarray', 'numpy.matrix', |
| 496 |
'numpy.chararray', |
| 497 |
'numpy.recarray', |
| 498 |
'numpy.bool_', 'numpy.void', |
| 499 |
'numpy.uint8', 'numpy.uint16', |
| 500 |
'numpy.uint32', 'numpy.uint64', |
| 501 |
'numpy.int8', 'numpy.int16', |
| 502 |
'numpy.int32', 'numpy.int64', |
| 503 |
'numpy.float32', 'numpy.float64', |
| 504 |
'numpy.complex64', |
| 505 |
'numpy.complex128', |
| 506 |
'numpy.bytes_', 'numpy.str_', |
| 507 |
'numpy.object_'] |
| 508 |
|
| 509 |
# If we are storing in MATLAB format, we will need to be able to |
| 510 |
# set the MATLAB_class attribute. The different numpy types just |
| 511 |
# need to be properly mapped to the right strings. Some types do |
| 512 |
# not have a string since MATLAB does not support them. |
| 513 |
|
| 514 |
self.__MATLAB_classes = {np.bool_: 'logical', |
| 515 |
np.uint8: 'uint8', |
| 516 |
np.uint16: 'uint16', |
| 517 |
np.uint32: 'uint32', |
| 518 |
np.uint64: 'uint64', |
| 519 |
np.int8: 'int8', |
| 520 |
np.int16: 'int16', |
| 521 |
np.int32: 'int32', |
| 522 |
np.int64: 'int64', |
| 523 |
np.float32: 'single', |
| 524 |
np.float64: 'double', |
| 525 |
np.complex64: 'single', |
| 526 |
np.complex128: 'double', |
| 527 |
np.bytes_: 'char', |
| •528 |
np.str_: 'char', |
| 529 |
np.object_: 'cell'} |
| 530 |
|
| 531 |
# Make a dict to look up the opposite direction (given a matlab |
| 532 |
# class, what numpy type to use. |
| 533 |
|
| 534 |
self.__MATLAB_classes_reverse = {'logical': np.bool_, |
| 535 |
'uint8': np.uint8, |
| 536 |
'uint16': np.uint16, |
| 537 |
'uint32': np.uint32, |
| 538 |
'uint64': np.uint64, |
| 539 |
'int8': np.int8, |
| 540 |
'int16': np.int16, |
| 541 |
'int32': np.int32, |
| 542 |
'int64': np.int64, |
| 543 |
'single': np.float32, |
| 544 |
'double': np.float64, |
| •545 |
'char': np.str_, |
| 546 |
'cell': np.object_, |
| 547 |
'canonical empty': np.float64, |
| 548 |
'struct': np.object_} |
| 549 |
|
| 550 |
|
| 551 |
# Set matlab_classes to the supported classes (the values). |
| 552 |
self.matlab_classes = list(self.__MATLAB_classes.values()) |
| 553 |
|
| 554 |
# For h5py >= 2.2, half precisions (np.float16) are supported. |
| 555 |
if parse_version(_H5PY_VERSION) \ |
| 556 |
>= parse_version('2.2'): |
| 557 |
self.types.append(np.float16) |
| 558 |
self.python_type_strings.append('numpy.float16') |
| 559 |
|
| 560 |
def write(self, f, grp, name, data, type_string, options): |
| 561 |
# If we are doing matlab compatibility and the data type is not |
| 562 |
# one of those that is supported for matlab, skip writing the |
| 563 |
# data or throw an error if appropriate. structured ndarrays and |
| 564 |
# recarrays are compatible if the |
| 565 |
# structured_numpy_ndarray_as_struct option is set. |
| 566 |
if options.matlab_compatible \ |
| 567 |
and not (data.dtype.type in self.__MATLAB_classes \ |
| 568 |
or (data.dtype.fields is not None \ |
| 569 |
and options.structured_numpy_ndarray_as_struct)): |
| 570 |
if options.action_for_matlab_incompatible == 'error': |
| 571 |
raise lowlevel.TypeNotMatlabCompatibleError( \ |
| 572 |
'Data type ' + data.dtype.name |
| 573 |
+ ' not supported by MATLAB.') |
| 574 |
elif options.action_for_matlab_incompatible == 'discard': |
| 575 |
return |
| 576 |
|
| 577 |
# Need to make a set of data that will be stored. It will start |
| 578 |
# out as a copy of data and then be steadily manipulated. |
| 579 |
|
| 580 |
data_to_store = data.copy() |
| 581 |
|
| 582 |
# recarrays must be converted to structured ndarrays in order |
| 583 |
# for h5py to be able to write them. |
| 584 |
if isinstance(data_to_store, np.core.records.recarray): |
| 585 |
data_to_store = data_to_store.view(np.ndarray) |
| 586 |
|
| 587 |
# Optionally convert bytes_ strings to UTF-16, if possible (all |
| 588 |
# are in the ASCII character set). This is done by simply |
| 589 |
# converting to uint16's and checking that each one's value is |
| 590 |
# less than 128 (in the ASCII character set). This will require |
| 591 |
# making them at least 1 dimensional. If it fails, throw an |
| 592 |
# exception. |
| 593 |
if data.dtype.type == np.bytes_ \ |
| 594 |
and options.convert_numpy_bytes_to_utf16: |
| 595 |
if data_to_store.nbytes == 0: |
| 596 |
data_to_store = np.uint16([]) |
| 597 |
else: |
| 598 |
data_to_store = np.uint16(np.atleast_1d( \ |
| 599 |
data_to_store).view(np.ndarray).view(np.uint8)) |
| 600 |
if np.any(data_to_store >= 128): |
| 601 |
raise NotImplementedError( \ |
| 602 |
'Can''t write non-ASCII numpy.bytes_.') |
| 603 |
|
| 604 |
# As of 2013-12-13, h5py cannot write numpy.str_ (UTF-32 |
| 605 |
# encoding) types (its numpy.unicode_ in Python 2, which is an |
| 606 |
# alias for it in Python 3). If the option is set to try to |
| 607 |
# convert them to UTF-16, then an attempt at the conversion is |
| 608 |
# made. If no conversion is to be done, the conversion throws an |
| 609 |
# exception (a UTF-32 character had no UTF-16 equivalent), or a |
| 610 |
# UTF-32 character gets turned into a UTF-16 doublet (the |
| 611 |
# increase in the number of columns will be by a factor more |
| 612 |
# than the length of the strings); then it will be simply |
| 613 |
# converted to uint32's byte for byte instead. |
| 614 |
|
| •615 |
if data.dtype.type == np.str_: |
| 616 |
new_data = None |
| 617 |
if options.convert_numpy_str_to_utf16: |
| 618 |
try: |
| 619 |
new_data = convert_numpy_str_to_uint16( \ |
| 620 |
data_to_store) |
| 621 |
except: |
| 622 |
pass |
| •623 |
if new_data is None or (type(data_to_store) == np.str_ \ |
| 624 |
and len(data_to_store) != len(new_data)) \ |
| 625 |
or (isinstance(data_to_store, np.ndarray) \ |
| 626 |
and new_data.shape[-1] != data_to_store.shape[-1] \ |
| 627 |
* (data_to_store.dtype.itemsize//4)): |
| 628 |
data_to_store = convert_numpy_str_to_uint32( \ |
| 629 |
data_to_store) |
| 630 |
else: |
| 631 |
data_to_store = new_data |
| 632 |
|
| 633 |
# Convert scalars to arrays if that option is set. For 1d |
| 634 |
# arrays, an option determines whether they become row or column |
| 635 |
# vectors. |
| 636 |
|
| 637 |
if options.make_atleast_2d: |
| 638 |
new_data = np.atleast_2d(data_to_store) |
| 639 |
if len(data_to_store.shape) == 1 \ |
| 640 |
and options.oned_as == 'column': |
| 641 |
new_data = new_data.T |
| 642 |
data_to_store = new_data |
| 643 |
|
| 644 |
# Reverse the dimension order if that option is set. |
| 645 |
|
| 646 |
if options.reverse_dimension_order: |
| 647 |
data_to_store = data_to_store.T |
| 648 |
|
| 649 |
# Bools need to be converted to uint8 if the option is given. |
| 650 |
if data_to_store.dtype.name == 'bool' \ |
| 651 |
and options.convert_bools_to_uint8: |
| 652 |
data_to_store = np.uint8(data_to_store) |
| 653 |
|
| 654 |
# If data is empty, we instead need to store the shape of the |
| 655 |
# array if the appropriate option is set. |
| 656 |
|
| 657 |
if options.store_shape_for_empty and (data.size == 0 \ |
| 658 |
or ((data.dtype.type == np.bytes_ \ |
| 659 |
or data.dtype.type == np.str_) \ |
| 660 |
and data.nbytes == 0)): |
| 661 |
data_to_store = np.uint64(data_to_store.shape) |
| 662 |
|
| 663 |
# If it is a complex type, then it needs to be encoded to have |
| 664 |
# the proper complex field names. |
| 665 |
if np.iscomplexobj(data_to_store): |
| 666 |
data_to_store = encode_complex(data_to_store, |
| 667 |
options.complex_names) |
| 668 |
|
| 669 |
# If we are storing an object type and it isn't empty |
| 670 |
# (data_to_store is still an object), then we must recursively |
| 671 |
# write what each element points to and make an array of the |
| 672 |
# references to them. |
| 673 |
if data_to_store.dtype.name == 'object': |
| 674 |
data_to_store = write_object_array(f, data_to_store, |
| 675 |
options) |
| 676 |
|
| 677 |
# If it an ndarray with fields and we are writing such things as |
| 678 |
# a Group/struct or if its shape is zero (h5py can't write it |
| 679 |
# Dataset then), that needs to be handled. Otherwise, it is |
| 680 |
# simply written as is to a Dataset. As HDF5 Reference types do |
| 681 |
# look like a structured object array, those have to be excluded |
| 682 |
# explicitly. Complex types may have been converted so that they |
| 683 |
# can have different field names as an HDF5 COMPOUND type, so |
| 684 |
# those have to be excluded too. Also, if any of its fields are |
| 685 |
# an object time (no matter how nested), then rather than |
| 686 |
# converting that field to a HDF5 Reference types, it will just |
| 687 |
# be written as a Group instead (just have to see if ", 'O'" is |
| 688 |
# in str(data_to_store.dtype). |
| 689 |
# |
| 690 |
# A flag, wrote_as_struct, is set depending on which path is |
| 691 |
# taken, which is then passed onto write_metadata. |
| 692 |
|
| 693 |
if data_to_store.dtype.fields is not None \ |
| 694 |
and h5py.check_dtype(ref=data_to_store.dtype) \ |
| 695 |
is not h5py.Reference \ |
| 696 |
and not np.iscomplexobj(data) \ |
| 697 |
and (options.structured_numpy_ndarray_as_struct \ |
| 698 |
or (data_to_store.dtype.hasobject \ |
| 699 |
or '\\x00' in str(data_to_store.dtype)) \ |
| 700 |
or does_dtype_have_a_zero_shape(data_to_store.dtype)): |
| 701 |
wrote_as_struct = True |
| 702 |
# Grab the list of fields that don't have a null character |
| 703 |
# or a / in them since those can't be written. |
| 704 |
field_names = [n for n in data_to_store.dtype.names |
| 705 |
if '/' not in n and '\x00' not in n] |
| 706 |
|
| 707 |
# Throw and exception if we had to exclude any field names. |
| 708 |
if len(field_names) != len(data_to_store.dtype.names): |
| 709 |
raise NotImplementedError("Null characters ('\x00') " \ |
| 710 |
+ "and '/' in the field names of this type of " \ |
| 711 |
+ 'numpy.ndarray are not supported.') |
| 712 |
|
| 713 |
# If the group doesn't exist, it needs to be created. If it |
| 714 |
# already exists but is not a group, it needs to be deleted |
| 715 |
# before being created. |
| 716 |
|
| 717 |
if name not in grp: |
| 718 |
grp.create_group(name) |
| 719 |
elif not isinstance(grp[name], h5py.Group): |
| 720 |
del grp[name] |
| 721 |
grp.create_group(name) |
| 722 |
|
| 723 |
grp2 = grp[name] |
| 724 |
|
| 725 |
# Write the metadata, and set the MATLAB_class to 'struct' |
| 726 |
# explicitly. |
| 727 |
if options.matlab_compatible: |
| 728 |
set_attribute_string(grp2, 'MATLAB_class', |
| 729 |
'struct') |
| 730 |
|
| 731 |
# Delete any Datasets/Groups not corresponding to a field |
| 732 |
# name in data if that option is set. |
| 733 |
|
| 734 |
if options.delete_unused_variables: |
| 735 |
for field in set([i for i in grp2]).difference( \ |
| 736 |
set(field_names)): |
| 737 |
del grp2[field] |
| 738 |
|
| 739 |
# Go field by field making an object array (make an empty |
| 740 |
# object array and assign element wise) and write it inside |
| 741 |
# the Group. If it only has a single element, write that |
| 742 |
# single element extracted from it (will be a standard |
| 743 |
# Dataset as opposed to a HDF5 Reference array). The H5PATH |
| 744 |
# attribute needs to be set appropriately, while all other |
| 745 |
# attributes need to be deleted. |
| 746 |
grp2_name = grp2.name |
| 747 |
for field in field_names: |
| 748 |
new_data = np.zeros(shape=data_to_store.shape, |
| 749 |
dtype='object') |
| 750 |
for index, x in np.ndenumerate(data_to_store): |
| 751 |
new_data[index] = x[field] |
| 752 |
|
| 753 |
# If we are supposed to reverse dimension order, it has |
| 754 |
# already been done, but write_data expects that it |
| 755 |
# hasn't, so it needs to be reversed again before |
| 756 |
# passing it on. |
| 757 |
if options.reverse_dimension_order: |
| 758 |
new_data = new_data.T |
| 759 |
|
| 760 |
# If there is only a single element, write it extracted |
| 761 |
# (don't need to use a Reference array in this |
| 762 |
# case). Otherwise, write the whole thing. |
| 763 |
if np.prod(new_data.shape) == 1: |
| 764 |
write_data(f, grp2, field, new_data.flatten()[0], |
| 765 |
None, options) |
| 766 |
else: |
| 767 |
write_data(f, grp2, field, new_data, None, options) |
| 768 |
|
| 769 |
if field in grp2: |
| 770 |
grp2_field = grp2[field] |
| 771 |
if options.matlab_compatible: |
| 772 |
set_attribute_string(grp2_field, 'H5PATH', |
| 773 |
grp2_name) |
| 774 |
else: |
| 775 |
del_attribute(grp2_field, 'H5PATH') |
| 776 |
|
| 777 |
# In the case that we wrote a Reference array (not a |
| 778 |
# single element), then all other attributes need to |
| 779 |
# be removed. |
| 780 |
if np.prod(new_data.shape) != 1: |
| 781 |
for attribute in (set( \ |
| 782 |
grp2_field.attrs.keys()) \ |
| 783 |
- set(['H5PATH'])): |
| 784 |
del_attribute(grp2_field, attribute) |
| 785 |
else: |
| 786 |
wrote_as_struct = False |
| 787 |
# If it has fields and it isn't a Reference type, none of |
| 788 |
# them can contain a / character. |
| 789 |
if data_to_store.dtype.fields is not None \ |
| 790 |
and h5py.check_dtype(ref=data_to_store.dtype) \ |
| 791 |
is not h5py.Reference: |
| 792 |
for n in data_to_store.dtype.fields: |
| 793 |
if '\x00' in n: |
| 794 |
raise NotImplementedError( \ |
| 795 |
"Null characters ('\x00') " \ |
| 796 |
+ 'in the field names of this type of ' \ |
| 797 |
+ 'numpy.ndarray are not supported.') |
| 798 |
|
| 799 |
# Set the storage options such as compression, chunking, |
| 800 |
# filters, etc. If the data is being compressed (compression |
| 801 |
# is enabled and the data is bigger than the threshold), |
| 802 |
# turn on compression, set the algorithm, set the |
| 803 |
# compression level, and enable the shuffle and fletcher32 |
| 804 |
# filters appropriately. If the data is not being |
| 805 |
# compressed, turn on the fletcher32 filter if |
| 806 |
# indicated. Compression should not be done for scalars. |
| 807 |
filters = dict() |
| 808 |
is_scalar = (data_to_store.shape != tuple()) |
| 809 |
if is_scalar and options.compress \ |
| 810 |
and data_to_store.nbytes \ |
| 811 |
>= options.compress_size_threshold: |
| 812 |
filters['compression'] = \ |
| 813 |
options.compression_algorithm |
| 814 |
if filters['compression'] == 'gzip': |
| 815 |
filters['compression_opts'] = \ |
| 816 |
options.gzip_compression_level |
| 817 |
filters['shuffle'] = options.shuffle_filter |
| 818 |
filters['fletcher32'] = \ |
| 819 |
options.compressed_fletcher32_filter |
| 820 |
else: |
| 821 |
filters['compression'] = None |
| 822 |
filters['shuffle'] = False |
| 823 |
filters['compression_opts'] = None |
| 824 |
if is_scalar: |
| 825 |
filters['fletcher32'] = \ |
| 826 |
options.uncompressed_fletcher32_filter |
| 827 |
else: |
| 828 |
filters['fletcher32'] = False |
| 829 |
|
| 830 |
# Set the chunking to auto if it is being chuncked |
| 831 |
# (compressed or using the fletcher32 filter). |
| 832 |
if filters['compression'] is not None \ |
| 833 |
or filters['fletcher32']: |
| 834 |
filters['chunks'] = True |
| 835 |
else: |
| 836 |
filters['chunks'] = None |
| 837 |
|
| 838 |
# The data must first be written. If name is not present |
| 839 |
# yet, then it must be created. If it is present, but not a |
| 840 |
# Dataset, has the wrong dtype, is the wrong shape, doesn't |
| 841 |
# use the same compression, or doesn't use the same filters; |
| 842 |
# then it must be deleted and then written. Otherwise, it is |
| 843 |
# just overwritten in place. |
| 844 |
if name not in grp: |
| 845 |
grp.create_dataset(name, data=data_to_store, |
| 846 |
**filters) |
| 847 |
else: |
| 848 |
# avoid multiple calls to __getitem__ by storing the |
| 849 |
# reference in a local variable |
| 850 |
dset = grp[name] |
| 851 |
if not isinstance(dset, h5py.Dataset) \ |
| 852 |
or dset.dtype != data_to_store.dtype \ |
| 853 |
or dset.shape != data_to_store.shape \ |
| 854 |
or dset.compression != filters['compression'] \ |
| 855 |
or dset.shuffle != filters['shuffle'] \ |
| 856 |
or dset.fletcher32 != filters['fletcher32'] \ |
| 857 |
or dset.compression_opts != \ |
| 858 |
filters['compression_opts']: |
| 859 |
del grp[name] |
| 860 |
grp.create_dataset(name, data=data_to_store, |
| 861 |
**filters) |
| 862 |
else: |
| 863 |
dset[...] = data_to_store |
| 864 |
|
| 865 |
# Write the metadata using the inherited function (good enough). |
| 866 |
self.write_metadata(f, grp, name, data, type_string, |
| 867 |
options, wrote_as_struct=wrote_as_struct) |
| 868 |
|
| 869 |
def write_metadata(self, f, grp, name, data, type_string, options, |
| 870 |
wrote_as_struct=False): |
| 871 |
# wote_as_struct is used to pass whether data was written like a |
| 872 |
# matlab struct or not. If yes, then the field names must be put |
| 873 |
# in the metadata. |
| 874 |
|
| 875 |
# First, call the inherited version to do most of the work. |
| 876 |
|
| 877 |
TypeMarshaller.write_metadata(self, f, grp, name, data, |
| 878 |
type_string, options) |
| 879 |
|
| 880 |
# Write the underlying numpy type if we are storing python |
| 881 |
# information. |
| 882 |
|
| 883 |
# If we are storing python information; the shape, underlying |
| 884 |
# numpy type, and its type of container ('scalar', 'ndarray', |
| 885 |
# 'matrix', or 'chararray') need to be stored. |
| 886 |
|
| 887 |
# avoid multiple calls to __getitem__ by storing the |
| 888 |
# reference in a local variable |
| 889 |
dsetgrp = grp[name] |
| 890 |
|
| 891 |
if options.store_python_metadata: |
| 892 |
set_attribute(dsetgrp, 'Python.Shape', |
| 893 |
np.uint64(data.shape)) |
| 894 |
|
| 895 |
# Now, in Python 3, the dtype names for bare bytes and |
| 896 |
# unicode strings start with 'bytes' and 'str' respectively, |
| 897 |
# but in Python 2, they start with 'string' and 'unicode' |
| 898 |
# respectively. The Python 2 ones must be converted to the |
| 899 |
# Python 3 ones for writing. |
| 900 |
set_attribute_string(dsetgrp, \ |
| 901 |
'Python.numpy.UnderlyingType', \ |
| 902 |
data.dtype.name.replace('string', 'bytes').replace( \ |
| 903 |
'unicode', 'str')) |
| 904 |
if isinstance(data, np.matrix): |
| 905 |
container = 'matrix' |
| 906 |
elif isinstance(data, np.chararray): |
| 907 |
container = 'chararray' |
| 908 |
elif isinstance(data, np.core.records.recarray): |
| 909 |
container = 'recarray' |
| 910 |
elif isinstance(data, np.ndarray): |
| 911 |
container = 'ndarray' |
| 912 |
else: |
| 913 |
container = 'scalar' |
| 914 |
set_attribute_string(dsetgrp, 'Python.numpy.Container', |
| 915 |
container) |
| 916 |
|
| 917 |
# If it was written like a matlab struct, then we set the |
| 918 |
# 'Python.Fields' and 'MATLAB_fields' Attributes to the field |
| 919 |
# names if we are storing python metadata or doing matlab |
| 920 |
# compatibility and we are storing a structured ndarray as a |
| 921 |
# structure. |
| 922 |
if wrote_as_struct: |
| 923 |
# Grab the list of fields. They need to be converted to |
| 924 |
# unicode in Python 2.x. |
| 925 |
if sys.hexversion >= 0x03000000: |
| 926 |
field_names = list(data.dtype.names) |
| 927 |
else: |
| 928 |
field_names = [c.decode('UTF-8') |
| 929 |
for c in list(data.dtype.names)] |
| 930 |
|
| 931 |
# Write or delete 'Python.Fields' as appropriate. |
| 932 |
if options.store_python_metadata: |
| 933 |
set_attribute_string_array(dsetgrp, |
| 934 |
'Python.Fields', |
| 935 |
field_names) |
| 936 |
else: |
| 937 |
del_attribute(dsetgrp, 'Python.Fields') |
| 938 |
|
| 939 |
# If we are making it MATLAB compatible and have h5py |
| 940 |
# version >= 2.3, then we can set the MATLAB_fields |
| 941 |
# Attribute as long as all keys are mappable to |
| 942 |
# ASCII. Otherwise, the attribute should be deleted. It is |
| 943 |
# written as a vlen='S1' array of bytes_ arrays of the |
| 944 |
# individual characters. |
| 945 |
if options.matlab_compatible \ |
| 946 |
and parse_version( \ |
| 947 |
_H5PY_VERSION) \ |
| 948 |
>= parse_version('2.3'): |
| 949 |
try: |
| 950 |
dt = h5py.special_dtype(vlen=np.dtype('S1')) |
| 951 |
fs = np.empty(shape=(len(field_names),), dtype=dt) |
| 952 |
for i, s in enumerate(field_names): |
| 953 |
fs[i] = np.array([c.encode('ascii') for c in s], |
| 954 |
dtype='S1') |
| 955 |
except UnicodeEncodeError: |
| 956 |
del_attribute(dsetgrp, 'MATLAB_fields') |
| 957 |
else: |
| 958 |
set_attribute(dsetgrp, 'MATLAB_fields', fs) |
| 959 |
else: |
| 960 |
del_attribute(dsetgrp, 'MATLAB_fields') |
| 961 |
else: |
| 962 |
del_attribute(dsetgrp, 'Python.Fields') |
| 963 |
del_attribute(dsetgrp, 'MATLAB_fields') |
| 964 |
|
| 965 |
# If data is empty, we need to set the Python.Empty and |
| 966 |
# MATLAB_empty attributes to 1 if we are storing type info or |
| 967 |
# making it MATLAB compatible. Otherwise, no empty attribute is |
| 968 |
# set and existing ones must be deleted. |
| 969 |
|
| 970 |
if data.size == 0 or ((data.dtype.type == np.bytes_ \ |
| 971 |
or data.dtype.type == np.str_) |
| 972 |
and data.nbytes == 0): |
| 973 |
if options.store_python_metadata: |
| 974 |
set_attribute(dsetgrp, 'Python.Empty', |
| 975 |
np.uint8(1)) |
| 976 |
else: |
| 977 |
del_attribute(dsetgrp, 'Python.Empty') |
| 978 |
if options.matlab_compatible: |
| 979 |
set_attribute(dsetgrp, 'MATLAB_empty', |
| 980 |
np.uint8(1)) |
| 981 |
else: |
| 982 |
del_attribute(dsetgrp, 'MATLAB_empty') |
| 983 |
else: |
| 984 |
del_attribute(dsetgrp, 'Python.Empty') |
| 985 |
del_attribute(dsetgrp, 'MATLAB_empty') |
| 986 |
|
| 987 |
# If we are making it MATLAB compatible, the MATLAB_class |
| 988 |
# attribute needs to be set looking up the data type (gotten |
| 989 |
# using np.dtype.type). If it is a string or bool type, then |
| 990 |
# the MATLAB_int_decode attribute must be set to the number of |
| 991 |
# bytes each element takes up (dtype.itemsize). If the dtype has |
| 992 |
# fields and we are writing it as a structure, the class needs |
| 993 |
# to be overriddent to 'struct'. Otherwise, the attributes must |
| 994 |
# be deleted. |
| 995 |
|
| 996 |
tp = data.dtype.type |
| 997 |
if options.matlab_compatible: |
| 998 |
if data.dtype.fields is not None \ |
| 999 |
and options.structured_numpy_ndarray_as_struct: |
| 1000 |
set_attribute_string(dsetgrp, 'MATLAB_class', |
| 1001 |
'struct') |
| 1002 |
elif tp in self.__MATLAB_classes: |
| 1003 |
set_attribute_string(dsetgrp, 'MATLAB_class', |
| 1004 |
self.__MATLAB_classes[tp]) |
| 1005 |
if tp in (np.bytes_, np.str_, np.bool_): |
| 1006 |
set_attribute(dsetgrp, 'MATLAB_int_decode', |
| 1007 |
np.int64(grp[name].dtype.itemsize)) |
| 1008 |
else: |
| 1009 |
del_attribute(dsetgrp, 'MATLAB_int_decode') |
| 1010 |
else: |
| 1011 |
del_attribute(dsetgrp, 'MATLAB_class') |
| 1012 |
del_attribute(dsetgrp, 'MATLAB_empty') |
| 1013 |
del_attribute(dsetgrp, 'MATLAB_int_decode') |
| 1014 |
else: |
| 1015 |
del_attribute(dsetgrp, 'MATLAB_class') |
| 1016 |
del_attribute(dsetgrp, 'MATLAB_empty') |
| 1017 |
del_attribute(dsetgrp, 'MATLAB_int_decode') |
| 1018 |
|
| 1019 |
def read(self, f, grp, name, options): |
| 1020 |
# If name is not present, then we can't read it and have to |
| 1021 |
# throw an error. |
| 1022 |
if name not in grp: |
| 1023 |
raise NotImplementedError(name + ' is not present.') |
| 1024 |
|
| 1025 |
# Get the object. |
| 1026 |
dsetgrp = grp[name] |
| 1027 |
|
| 1028 |
# Get the different attributes this marshaller uses. |
| 1029 |
|
| 1030 |
if sys.hexversion >= 0x03000000: |
| 1031 |
defaultfactory = type(None) |
| 1032 |
else: |
| 1033 |
defaultfactory = lambda : None |
| 1034 |
attributes = collections.defaultdict(defaultfactory) |
| 1035 |
read_all_attributes_into(dsetgrp.attrs, attributes) |
| 1036 |
|
| 1037 |
str_attrs = dict() |
| 1038 |
for attr_name in ('Python.Type', |
| 1039 |
'Python.numpy.UnderlyingType', |
| 1040 |
'Python.numpy.Container', |
| 1041 |
'MATLAB_class'): |
| 1042 |
value = attributes[attr_name] |
| 1043 |
if value is None: |
| 1044 |
str_attrs[attr_name] = value |
| 1045 |
elif (sys.hexversion >= 0x03000000 \ |
| 1046 |
and isinstance(value, str)) \ |
| 1047 |
or (sys.hexversion < 0x03000000 \ |
| 1048 |
and isinstance(value, unicode)): |
| 1049 |
str_attrs[attr_name] = value |
| 1050 |
elif isinstance(value, bytes): |
| 1051 |
str_attrs[attr_name] = value.decode() |
| •1052 |
elif isinstance(value, np.str_): |
| 1053 |
str_attrs[attr_name] = str(value) |
| 1054 |
elif isinstance(value, np.bytes_): |
| 1055 |
str_attrs[attr_name] = value.decode() |
| 1056 |
else: |
| 1057 |
str_attrs[attr_name] = None |
| 1058 |
|
| 1059 |
type_string = str_attrs['Python.Type'] |
| 1060 |
underlying_type = str_attrs['Python.numpy.UnderlyingType'] |
| 1061 |
container = str_attrs['Python.numpy.Container'] |
| 1062 |
matlab_class = str_attrs['MATLAB_class'] |
| 1063 |
|
| 1064 |
shape = attributes['Python.Shape'] |
| 1065 |
python_empty = attributes['Python.Empty'] |
| 1066 |
matlab_empty = attributes['MATLAB_empty'] |
| 1067 |
|
| 1068 |
python_fields = attributes['Python.Fields'] |
| 1069 |
if python_fields is not None: |
| 1070 |
python_fields = [convert_to_str(x) |
| 1071 |
for x in python_fields] |
| 1072 |
|
| 1073 |
# Read the MATLAB_fields Attribute if it was present. |
| 1074 |
matlab_fields = attributes['MATLAB_fields'] |
| 1075 |
|
| 1076 |
# If it is a Dataset, it can simply be read and then acted upon |
| 1077 |
# (if it is an HDF5 Reference array, it will need to be read |
| 1078 |
# recursively). If it is a Group, then it is a structured |
| 1079 |
# ndarray like object that needs to be read field wise and |
| 1080 |
# constructed. |
| 1081 |
if isinstance(dsetgrp, h5py.Dataset): |
| 1082 |
# Read the data. |
| 1083 |
data = dsetgrp[...] |
| 1084 |
|
| 1085 |
# If it is a reference type, then we need to make an object |
| 1086 |
# array that is its replicate, but with the objects they are |
| 1087 |
# pointing to in their elements instead of just the |
| 1088 |
# references. |
| 1089 |
if h5py.check_dtype(ref=dsetgrp.dtype) is not None: |
| 1090 |
data = read_object_array(f, data, options) |
| 1091 |
else: |
| 1092 |
# Starting with an empty dict, all that has to be done is |
| 1093 |
# iterate through all the Datasets and Groups in dsetgrp |
| 1094 |
# and add them to a dict with their name as the key. Since |
| 1095 |
# we don't want an exception thrown by reading an element to |
| 1096 |
# stop the whole reading process, the reading is wrapped in |
| 1097 |
# a try block that just catches exceptions and then does |
| 1098 |
# nothing about them (nothing needs to be done). We also |
| 1099 |
# need to keep track of whether any of the fields are |
| 1100 |
# Groups, aren't Reference arrays, or have attributes other |
| 1101 |
# than H5PATH since that means that the fields are the |
| 1102 |
# values (single element structured ndarray), as opposed to |
| 1103 |
# Reference arrays to all the values (multi-element structed |
| 1104 |
# ndarray). In Python 2, the field names need to be |
| 1105 |
# converted to str from unicode when storing the fields in |
| 1106 |
# struct_data. |
| 1107 |
struct_data = dict() |
| 1108 |
is_multi_element = True |
| 1109 |
for k, fld in dsetgrp.items(): |
| 1110 |
# We must exclude group_for_references |
| 1111 |
if fld.name == options.group_for_references: |
| 1112 |
continue |
| 1113 |
if isinstance(fld, h5py.Group) \ |
| 1114 |
or h5py.check_dtype(ref=fld.dtype) is None \ |
| 1115 |
or len(set(fld.attrs.keys()) \ |
| 1116 |
& ((set(self.python_attributes) \ |
| 1117 |
| set(self.matlab_attributes)) |
| 1118 |
- set(['H5PATH', 'MATLAB_empty', |
| 1119 |
'Python.Empty']))) != 0: |
| 1120 |
is_multi_element = False |
| 1121 |
try: |
| 1122 |
struct_data[k] = read_data(f, dsetgrp, k, |
| 1123 |
options) |
| 1124 |
except: |
| 1125 |
pass |
| 1126 |
|
| 1127 |
# If it isn't multi element, we need to pack all the values |
| 1128 |
# in struct_array inside of numpy.object_'s so that the code |
| 1129 |
# after this that depends on this will work. |
| 1130 |
if not is_multi_element: |
| 1131 |
for k, v in struct_data.items(): |
| 1132 |
obj = np.zeros((1,), dtype='object') |
| 1133 |
obj[0] = v |
| 1134 |
struct_data[k] = obj |
| 1135 |
|
| 1136 |
# The dtype for the structured ndarray needs to be |
| 1137 |
# composed. This is done by going through each field (in the |
| 1138 |
# proper order, if the fields were given, or any order if |
| 1139 |
# not) and determine the dtype and shape of that field to |
| 1140 |
# put in the list. |
| 1141 |
|
| 1142 |
if python_fields is not None or matlab_fields is not None: |
| 1143 |
if python_fields is not None: |
| 1144 |
fields = python_fields |
| 1145 |
else: |
| 1146 |
fields = [numpy_to_bytes(k).decode() |
| 1147 |
for k in matlab_fields] |
| 1148 |
# Now, there may be fields available that were not |
| 1149 |
# given, but still should be read. Keys that are not in |
| 1150 |
# python_fields need to be added to the list. |
| 1151 |
extra_fields = list(set(struct_data.keys()) |
| 1152 |
- set(fields)) |
| 1153 |
fields.extend(sorted(extra_fields)) |
| 1154 |
else: |
| 1155 |
fields = sorted(list(struct_data.keys())) |
| 1156 |
|
| 1157 |
dt_whole = [] |
| 1158 |
for k in fields: |
| 1159 |
# In Python 2, the field names for a structured ndarray |
| 1160 |
# must be str as opposed to unicode, so k needs to be |
| 1161 |
# converted in the Python 2 case. |
| 1162 |
if sys.hexversion >= 0x03000000: |
| 1163 |
k_name = k |
| 1164 |
else: |
| 1165 |
k_name = k.encode('UTF-8') |
| 1166 |
|
| 1167 |
# Read the value. |
| 1168 |
v = struct_data[k] |
| 1169 |
|
| 1170 |
# If any of the elements are not Numpy types or if they |
| 1171 |
# don't all have the exact same dtype and shape, then |
| 1172 |
# this field will just be an object field. |
| 1173 |
if v.size == 0 or type(v.flat[0]) \ |
| 1174 |
not in self._numpy_types: |
| 1175 |
dt_whole.append((k_name, 'object')) |
| 1176 |
continue |
| 1177 |
|
| 1178 |
first = v.flatten()[0] |
| 1179 |
dt = first.dtype |
| 1180 |
sp = first.shape |
| 1181 |
all_same = True |
| 1182 |
for index, x in np.ndenumerate(v): |
| 1183 |
if not isinstance(x, tuple(self.types)) \ |
| 1184 |
or dt != x.dtype or sp != x.shape: |
| 1185 |
all_same = False |
| 1186 |
break |
| 1187 |
|
| 1188 |
# If they are all the same, then dt and shape should be |
| 1189 |
# used. Otherwise, it has to be object. |
| 1190 |
if all_same: |
| 1191 |
dt_whole.append((k_name, dt, sp)) |
| 1192 |
else: |
| 1193 |
dt_whole.append((k_name, 'object')) |
| 1194 |
|
| 1195 |
# Make the structured ndarray with the constructed |
| 1196 |
# dtype. The shape is simply the shape of the object arrays |
| 1197 |
# of its fields, so we might as well use the shape of |
| 1198 |
# v. Then, all the elements of every field need to be |
| 1199 |
# assigned. Now, if dtype's itemsize is 0, a TypeError will |
| 1200 |
# be thrown by numpy due to a bug in numpy. np.zeros (as |
| 1201 |
# well as ones and empty) does not like to make arrays with |
| 1202 |
# no bytes. A workaround is to make an empty array of some |
| 1203 |
# other type and convert its dtype. The smallest one we can |
| 1204 |
# make is an np.int8([]). Yes, one byte will be wasted, but |
| 1205 |
# at least no errors will happen. |
| 1206 |
dtwhole = np.dtype(dt_whole) |
| 1207 |
if dtwhole.itemsize == 0: |
| 1208 |
data = np.zeros(shape=v.shape, |
| 1209 |
dtype='int8').astype(dtwhole) |
| 1210 |
else: |
| 1211 |
data = np.zeros(shape=v.shape, dtype=dtwhole) |
| 1212 |
for k, v in struct_data.items(): |
| 1213 |
# There is no sense iterating through the elements if |
| 1214 |
# the shape is an empty shape. |
| 1215 |
if all(data.shape) and all(v.shape): |
| 1216 |
for index, x in np.ndenumerate(v): |
| 1217 |
if sys.hexversion >= 0x03000000: |
| 1218 |
data[k][index] = x |
| 1219 |
else: |
| 1220 |
data[k.encode('UTF-8')][index] = x |
| 1221 |
|
| 1222 |
# If metadata is present, that can be used to do convert to the |
| 1223 |
# desired/closest Python data types. If none is present, or not |
| 1224 |
# enough of it, then no conversions can be done. |
| 1225 |
if type_string is not None and underlying_type is not None and \ |
| 1226 |
shape is not None: |
| 1227 |
# If the Attributes 'Python.Fields' and/or 'MATLAB_fields' |
| 1228 |
# are present, the underlying type needs to be changed to |
| 1229 |
# the proper dtype for the structure. |
| 1230 |
if python_fields is not None or matlab_fields is not None: |
| 1231 |
if python_fields is not None: |
| 1232 |
fields = python_fields |
| 1233 |
else: |
| 1234 |
fields = [numpy_to_bytes(k).decode() |
| 1235 |
for k in matlab_fields] |
| 1236 |
struct_dtype = list() |
| 1237 |
for k in fields: |
| 1238 |
if sys.hexversion >= 0x03000000: |
| 1239 |
struct_dtype.append((k, 'object')) |
| 1240 |
else: |
| 1241 |
struct_dtype.append((k.encode('UTF-8'), |
| 1242 |
'object')) |
| 1243 |
else: |
| 1244 |
struct_dtype = None |
| 1245 |
|
| 1246 |
# If it is empty ('Python.Empty' set to 1), then the shape |
| 1247 |
# information is stored in data and we need to set data to |
| 1248 |
# the empty array of the proper type (in underlying_type) |
| 1249 |
# and the given shape. If we are going to transpose it |
| 1250 |
# later, we need to transpose it now so that it still keeps |
| 1251 |
# the right shape. Also, if it is a structure that we just |
| 1252 |
# figured out the dtype for, that needs to be used. |
| 1253 |
if python_empty == 1: |
| 1254 |
if underlying_type.startswith('bytes'): |
| 1255 |
if underlying_type == 'bytes': |
| 1256 |
nchars = 1 |
| 1257 |
else: |
| 1258 |
nchars = int(int( |
| 1259 |
underlying_type[len('bytes'):]) |
| 1260 |
/ 8) |
| 1261 |
data = np.zeros(tuple(shape), |
| 1262 |
dtype='S' + str(nchars)) |
| 1263 |
elif underlying_type.startswith('str'): |
| 1264 |
if underlying_type == 'str': |
| 1265 |
nchars = 1 |
| 1266 |
else: |
| 1267 |
nchars = int(int( |
| 1268 |
underlying_type[len('str'):]) |
| 1269 |
/ 32) |
| 1270 |
data = np.zeros(tuple(shape), |
| 1271 |
dtype='U' + str(nchars)) |
| 1272 |
elif struct_dtype is not None: |
| 1273 |
data = np.zeros(tuple(shape), |
| 1274 |
dtype=struct_dtype) |
| 1275 |
else: |
| 1276 |
data = np.zeros(tuple(shape), |
| 1277 |
dtype=underlying_type) |
| 1278 |
if matlab_class is not None or \ |
| 1279 |
options.reverse_dimension_order: |
| 1280 |
data = data.T |
| 1281 |
|
| 1282 |
# If it is a complex type, then it needs to be decoded |
| 1283 |
# properly. |
| 1284 |
if underlying_type.startswith('complex'): |
| 1285 |
data = decode_complex(data) |
| 1286 |
|
| 1287 |
# If its underlying type is 'bool' but it is something else, |
| 1288 |
# then it needs to be converted (means it was written with |
| 1289 |
# the convert_bools_to_uint8 option). |
| 1290 |
if underlying_type == 'bool' and data.dtype.name != 'bool': |
| 1291 |
data = np.bool_(data) |
| 1292 |
|
| 1293 |
# If MATLAB attributes are present or the reverse dimension |
| 1294 |
# order option was given, the dimension order needs to be |
| 1295 |
# reversed. This needs to be done before any reshaping as |
| 1296 |
# the shape was stored before any dimensional reordering. |
| 1297 |
if matlab_class is not None or \ |
| 1298 |
options.reverse_dimension_order: |
| 1299 |
data = data.T |
| 1300 |
|
| 1301 |
# String types might have to be decoded depending on the |
| 1302 |
# underlying type, and MATLAB class if given. They also need |
| 1303 |
# to be properly decoded into strings of the right length if |
| 1304 |
# it originally represented an array of strings (turned into |
| 1305 |
# uints of some sort). The length in bits is contained in |
| 1306 |
# the dtype name, which is the underlying_type. |
| 1307 |
if underlying_type.startswith('bytes'): |
| 1308 |
if underlying_type == 'bytes': |
| 1309 |
data = np.bytes_(b'') |
| 1310 |
else: |
| 1311 |
data = convert_to_numpy_bytes(data, \ |
| 1312 |
length=int(underlying_type[5:])//8) |
| 1313 |
elif underlying_type.startswith('str') \ |
| 1314 |
or matlab_class == 'char': |
| 1315 |
if underlying_type == 'str': |
| •1316 |
data = np.str_('') |
| 1317 |
elif underlying_type.startswith('str'): |
| 1318 |
data = convert_to_numpy_str(data, \ |
| 1319 |
length=int(underlying_type[3:])//32) |
| 1320 |
else: |
| 1321 |
data = convert_to_numpy_str(data) |
| 1322 |
|
| 1323 |
# If the shape of data and the shape attribute are |
| 1324 |
# different but give the same number of elements, then data |
| 1325 |
# needs to be reshaped. |
| 1326 |
if tuple(shape) != data.shape \ |
| 1327 |
and np.prod(shape) == np.prod(data.shape): |
| 1328 |
data = data.reshape(tuple(shape)) |
| 1329 |
|
| 1330 |
# If data is a structured ndarray and the type string says |
| 1331 |
# it is a recarray, then turn it into one. |
| 1332 |
if type_string == 'numpy.recarray': |
| 1333 |
data = data.view(np.core.records.recarray) |
| 1334 |
|
| 1335 |
# Convert to scalar, matrix, chararray, or ndarray depending |
| 1336 |
# on the container type. For an empty scalar string, it |
| 1337 |
# needs to be manually set to '' and b'' or there will be |
| 1338 |
# problems. |
| 1339 |
if container == 'scalar': |
| 1340 |
if underlying_type.startswith('bytes'): |
| 1341 |
if python_empty == 1: |
| 1342 |
data = np.bytes_(b'') |
| 1343 |
elif isinstance(data, np.ndarray): |
| 1344 |
data = data.flatten()[0] |
| 1345 |
elif underlying_type.startswith('str'): |
| 1346 |
if python_empty == 1: |
| •1347 |
data = np.str_('') |
| 1348 |
elif isinstance(data, np.ndarray): |
| 1349 |
data = data.flatten()[0] |
| 1350 |
else: |
| 1351 |
data = data.flatten()[0] |
| 1352 |
elif container == 'matrix': |
| 1353 |
data = np.asmatrix(data) |
| 1354 |
elif container == 'chararray': |
| 1355 |
data = data.view(np.chararray) |
| 1356 |
elif container == 'ndarray': |
| 1357 |
data = np.asarray(data) |
| 1358 |
|
| 1359 |
elif matlab_class in self.__MATLAB_classes_reverse: |
| 1360 |
# MATLAB formatting information was given. The extraction |
| 1361 |
# did most of the work except handling empties, array |
| 1362 |
# dimension order, and string conversion. |
| 1363 |
|
| 1364 |
# If it is empty ('MATLAB_empty' set to 1), then the shape |
| 1365 |
# information is stored in data and we need to set data to |
| 1366 |
# the empty array of the proper type. If it is a MATLAB |
| 1367 |
# struct, then the proper dtype has to be constructed from |
| 1368 |
# the field names if present (the dtype of each individual |
| 1369 |
# field is set to object). |
| 1370 |
if matlab_empty == 1: |
| 1371 |
if matlab_fields is None: |
| 1372 |
data = np.zeros(tuple(np.uint64(data)), \ |
| 1373 |
dtype=self.__MATLAB_classes_reverse[ \ |
| 1374 |
matlab_class]) |
| 1375 |
else: |
| 1376 |
dt_whole = list() |
| 1377 |
for k in matlab_fields: |
| 1378 |
if sys.hexversion >= 0x03000000: |
| 1379 |
dt_whole.append((numpy_to_bytes(k).decode(), |
| 1380 |
'object')) |
| 1381 |
else: |
| 1382 |
dt_whole.append((numpy_to_bytes(k), |
| 1383 |
'object')) |
| 1384 |
data = np.zeros(shape=tuple(np.uint64(data)), |
| 1385 |
dtype=dt_whole) |
| 1386 |
|
| 1387 |
# The order of the dimensions must be switched from Fortran |
| 1388 |
# order which MATLAB uses to C order which Python uses. |
| 1389 |
data = data.T |
| 1390 |
|
| 1391 |
# Now, if the matlab class is 'single' or 'double', data |
| 1392 |
# could possibly be a complex type which needs to be |
| 1393 |
# properly decoded. |
| 1394 |
if matlab_class in ['single', 'double']: |
| 1395 |
data = decode_complex(data) |
| 1396 |
|
| 1397 |
# If it is a logical, then it must be converted to |
| 1398 |
# numpy.bool8. |
| 1399 |
if matlab_class == 'logical': |
| 1400 |
data = np.bool_(data) |
| 1401 |
|
| 1402 |
# If it is a 'char' type, the proper conversion to |
| 1403 |
# numpy.unicode needs to be done. |
| 1404 |
if matlab_class == 'char': |
| 1405 |
data = convert_to_numpy_str(data) |
| 1406 |
|
| 1407 |
# Done adjusting data, so it can be returned. |
| 1408 |
return data |
| 1409 |
|
| 1410 |
|
| 1411 |
class PythonScalarMarshaller(NumpyScalarArrayMarshaller): |
| 1412 |
def __init__(self): |
| 1413 |
NumpyScalarArrayMarshaller.__init__(self) |
| 1414 |
|
| 1415 |
# In Python 3, there is only a single integer type int, which is |
| 1416 |
# variable width. In Python 2, there is the fixed width int and |
| 1417 |
# the variable width long. Python 2 needs to be able to save |
| 1418 |
# with either, but Python 3 needs to map both to int, which can |
| 1419 |
# be done by just putting the type int for its entry in types. |
| 1420 |
if sys.hexversion >= 0x03000000: |
| 1421 |
self.types = [bool, int, int, float, complex] |
| 1422 |
else: |
| 1423 |
self.types = [bool, int, long, float, complex] |
| 1424 |
self.python_type_strings = ['bool', 'int', 'long', 'float', |
| 1425 |
'complex'] |
| 1426 |
# As the parent class already has MATLAB strings handled, there |
| 1427 |
# are no MATLAB classes that this marshaller should be used for. |
| 1428 |
self.matlab_classes = [] |
| 1429 |
|
| 1430 |
def write(self, f, grp, name, data, type_string, options): |
| 1431 |
# data just needs to be converted to the appropriate numpy |
| 1432 |
# type. If it is a Python 3.x int or Python 2.x long that is too |
| 1433 |
# big to fit in a numpy.int64, we need to throw an not |
| 1434 |
# implemented exception so it doesn't get packaged as an |
| 1435 |
# object. It is converted explicitly to a numpy.int64. If it is |
| 1436 |
# too big, there will be an OverflowError. Otherwise, data is |
| 1437 |
# passed through np.array and then access [()] to get the scalar |
| 1438 |
# back as a scalar numpy type. The proper type_string needs to |
| 1439 |
# be grabbed now as the parent function will have a modified |
| 1440 |
# form of data to guess from if not given the right one |
| 1441 |
# explicitly. |
| 1442 |
if sys.hexversion >= 0x03000000: |
| 1443 |
tp = int |
| 1444 |
else: |
| 1445 |
tp = long |
| 1446 |
if type(data) == tp: |
| 1447 |
try: |
| 1448 |
out = np.int64(data) |
| 1449 |
except OverflowError: |
| 1450 |
raise NotImplementedError('Int/long too big to fit ' |
| 1451 |
+ 'into numpy.int64.') |
| 1452 |
else: |
| 1453 |
out = data |
| 1454 |
NumpyScalarArrayMarshaller.write(self, f, grp, name, |
| 1455 |
np.array(out)[()], |
| 1456 |
self.get_type_string(data, |
| 1457 |
type_string), options) |
| 1458 |
|
| 1459 |
def read(self, f, grp, name, options): |
| 1460 |
# Use the parent class version to read it and do most of the |
| 1461 |
# work. |
| 1462 |
data = NumpyScalarArrayMarshaller.read(self, f, grp, name, |
| 1463 |
options) |
| 1464 |
|
| 1465 |
# The type string determines how to convert it back to a Python |
| 1466 |
# type (just look up the entry in types). As it might be |
| 1467 |
# returned as an ndarray, we just need to use the item |
| 1468 |
# method. Now, since int and long are unified in Python 3.x and |
| 1469 |
# the size of int in Python 2.x is not always the same, if the |
| 1470 |
# type_string is 'int', then we need to check to see if it can |
| 1471 |
# fit into an int if we are in Python 2.x. If it will fit, it is |
| 1472 |
# returned as an int. If it would not fit, it is returned as a |
| 1473 |
# long. |
| 1474 |
type_string = get_attribute_string(grp[name], 'Python.Type') |
| 1475 |
if type_string in self.python_type_strings: |
| 1476 |
tp = self.types[self.python_type_strings.index( |
| 1477 |
type_string)] |
| 1478 |
sdata = data.item() |
| 1479 |
if sys.hexversion >= 0x03000000 or tp != int: |
| 1480 |
return tp(sdata) |
| 1481 |
else: |
| 1482 |
num = long(sdata) |
| 1483 |
if num > sys.maxint or num < -(sys.maxint - 1): |
| 1484 |
return num |
| 1485 |
else: |
| 1486 |
return int(num) |
| 1487 |
else: |
| 1488 |
# Must be some other type, so return it as is. |
| 1489 |
return data |
| 1490 |
|
| 1491 |
|
| 1492 |
class PythonStringMarshaller(NumpyScalarArrayMarshaller): |
| 1493 |
def __init__(self): |
| 1494 |
NumpyScalarArrayMarshaller.__init__(self) |
| 1495 |
# In Python 3, the unicode and bare bytes type strings are str |
| 1496 |
# and bytes, but before Python 3, they were unicode and str |
| 1497 |
# respectively. The Python 3 python_type_strings will be used, |
| 1498 |
# though. |
| 1499 |
if sys.hexversion >= 0x03000000: |
| 1500 |
self.types = [str, bytes, bytearray] |
| 1501 |
else: |
| 1502 |
self.types = [unicode, str, bytearray] |
| 1503 |
self.python_type_strings = ['str', 'bytes', 'bytearray'] |
| 1504 |
# As the parent class already has MATLAB strings handled, there |
| 1505 |
# are no MATLAB classes that this marshaller should be used for. |
| 1506 |
self.matlab_classes = [] |
| 1507 |
|
| 1508 |
def write(self, f, grp, name, data, type_string, options): |
| 1509 |
# data just needs to be converted to a numpy string of the |
| 1510 |
# appropriate type (str to np.str_ and the others to np.bytes_). |
| 1511 |
if (sys.hexversion >= 0x03000000 and isinstance(data, str)) \ |
| 1512 |
or (sys.hexversion < 0x03000000 \ |
| 1513 |
and isinstance(data, unicode)): |
| •1514 |
cdata = np.str_(data) |
| 1515 |
else: |
| 1516 |
cdata = np.bytes_(data) |
| 1517 |
|
| 1518 |
# Now pass it to the parent version of this function to write |
| 1519 |
# it. The proper type_string needs to be grabbed now as the |
| 1520 |
# parent function will have a modified form of data to guess |
| 1521 |
# from if not given the right one explicitly. |
| 1522 |
NumpyScalarArrayMarshaller.write(self, f, grp, name, cdata, |
| 1523 |
self.get_type_string(data, |
| 1524 |
type_string), options) |
| 1525 |
|
| 1526 |
def read(self, f, grp, name, options): |
| 1527 |
# Use the parent class version to read it and do most of the |
| 1528 |
# work. |
| 1529 |
data = NumpyScalarArrayMarshaller.read(self, f, grp, name, |
| 1530 |
options) |
| 1531 |
|
| 1532 |
# The type string determines how to convert it back to a Python |
| 1533 |
# type (just look up the entry in types). Otherwise, return it |
| 1534 |
# as is. |
| 1535 |
type_string = get_attribute_string(grp[name], 'Python.Type') |
| 1536 |
if type_string == 'str': |
| 1537 |
return convert_to_str(data) |
| 1538 |
elif type_string == 'bytes': |
| 1539 |
if sys.hexversion >= 0x03000000: |
| 1540 |
return bytes(data) |
| 1541 |
else: |
| 1542 |
return str(data) |
| 1543 |
elif type_string == 'bytearray': |
| 1544 |
return bytearray(data) |
| 1545 |
else: |
| 1546 |
return data |
| 1547 |
|
| 1548 |
|
| 1549 |
class PythonNoneMarshaller(NumpyScalarArrayMarshaller): |
| 1550 |
def __init__(self): |
| 1551 |
NumpyScalarArrayMarshaller.__init__(self) |
| 1552 |
self.types = [type(None)] |
| 1553 |
self.python_type_strings = ['builtins.NoneType'] |
| 1554 |
# None corresponds to no MATLAB class. |
| 1555 |
self.matlab_classes = [] |
| 1556 |
|
| 1557 |
def write(self, f, grp, name, data, type_string, options): |
| 1558 |
# Just going to use the parent function with an empty double |
| 1559 |
# (two dimensional so that MATLAB will import it as a []) as the |
| 1560 |
# data and the right type_string set (parent can't guess right |
| 1561 |
# from the modified form). |
| 1562 |
NumpyScalarArrayMarshaller.write(self, f, grp, name, |
| 1563 |
np.float64([]), |
| 1564 |
self.get_type_string(data, |
| 1565 |
type_string), options) |
| 1566 |
|
| 1567 |
def read(self, f, grp, name, options): |
| 1568 |
# There is only one value, so return it. |
| 1569 |
return None |
| 1570 |
|
| 1571 |
|
| 1572 |
class PythonDictMarshaller(TypeMarshaller): |
| 1573 |
def __init__(self): |
| 1574 |
TypeMarshaller.__init__(self) |
| 1575 |
self.python_attributes |= set(['Python.Fields']) |
| 1576 |
self.matlab_attributes |= set(['MATLAB_class', 'MATLAB_fields']) |
| 1577 |
self.types = [dict] |
| 1578 |
self.python_type_strings = ['dict'] |
| 1579 |
self.__MATLAB_classes = {dict: 'struct'} |
| 1580 |
# Set matlab_classes to empty since NumpyScalarArrayMarshaller |
| 1581 |
# handles Groups by default now. |
| 1582 |
self.matlab_classes = list() |
| 1583 |
|
| 1584 |
def write(self, f, grp, name, data, type_string, options): |
| 1585 |
# Check for any field names that are not unicode since they |
| 1586 |
# cannot be handled. Also check for null characters and / |
| 1587 |
# characters since they can't be handled either. How it is |
| 1588 |
# checked (what type it is) and the error message are different |
| 1589 |
# for each Python version. |
| 1590 |
|
| 1591 |
if sys.hexversion >= 0x03000000: |
| 1592 |
for fieldname in data: |
| 1593 |
if not isinstance(fieldname, str): |
| 1594 |
raise NotImplementedError('Dictionaries with non-' |
| 1595 |
+ 'str keys are not ' |
| 1596 |
+ 'supported: ' |
| 1597 |
+ repr(fieldname)) |
| 1598 |
if '\x00' in fieldname or '/' in fieldname: |
| 1599 |
raise NotImplementedError('Dictionary keys with ' \ |
| 1600 |
+ "null characters ('\x00') and '/' are not " \ |
| 1601 |
+ 'supported.') |
| 1602 |
else: |
| 1603 |
for fieldname in data: |
| 1604 |
if not isinstance(fieldname, unicode): |
| 1605 |
raise NotImplementedError('Dictionaries with non-' |
| 1606 |
+ 'unicode keys are not ' |
| 1607 |
+ 'supported: ' |
| 1608 |
+ repr(fieldname)) |
| 1609 |
if unicode('\x00') in fieldname \ |
| 1610 |
or unicode('/') in fieldname: |
| 1611 |
raise NotImplementedError('Dictionary keys with ' \ |
| 1612 |
+ "null characters ('\x00') and '/' are not " \ |
| 1613 |
+ 'supported.') |
| 1614 |
|
| 1615 |
# If the group doesn't exist, it needs to be created. If it |
| 1616 |
# already exists but is not a group, it needs to be deleted |
| 1617 |
# before being created. |
| 1618 |
|
| 1619 |
if name not in grp: |
| 1620 |
grp2 = grp.create_group(name) |
| 1621 |
elif not isinstance(grp[name], h5py.Group): |
| 1622 |
del grp[name] |
| 1623 |
grp2 = grp.create_group(name) |
| 1624 |
else: |
| 1625 |
grp2 = grp[name] |
| 1626 |
|
| 1627 |
# Write the metadata. |
| 1628 |
self.write_metadata(f, grp, name, data, type_string, options) |
| 1629 |
|
| 1630 |
# Delete any Datasets/Groups not corresponding to a field name |
| 1631 |
# in data if that option is set. |
| 1632 |
|
| 1633 |
if options.delete_unused_variables: |
| 1634 |
for field in set([i for i in grp2]).difference( \ |
| 1635 |
set([i for i in data])): |
| 1636 |
del grp2[field] |
| 1637 |
|
| 1638 |
# Go through all the elements of data and write them. The H5PATH |
| 1639 |
# needs to be set as the path of grp2 on all of them if we are |
| 1640 |
# doing MATLAB compatibility (otherwise, the attribute needs to |
| 1641 |
# be deleted). |
| 1642 |
grp2_name = grp2.name |
| 1643 |
for k, v in data.items(): |
| 1644 |
write_data(f, grp2, k, v, None, options) |
| 1645 |
if k in grp2: |
| 1646 |
if options.matlab_compatible: |
| 1647 |
set_attribute_string(grp2[k], 'H5PATH', grp2_name) |
| 1648 |
else: |
| 1649 |
del_attribute(grp2[k], 'H5PATH') |
| 1650 |
|
| 1651 |
def write_metadata(self, f, grp, name, data, type_string, options): |
| 1652 |
# First, call the inherited version to do most of the work and |
| 1653 |
# get the group. |
| 1654 |
|
| 1655 |
TypeMarshaller.write_metadata(self, f, grp, name, data, |
| 1656 |
type_string, options) |
| 1657 |
grp2 = grp[name] |
| 1658 |
|
| 1659 |
# Grab all the keys and sort the list. |
| 1660 |
fields = sorted(list(data.keys())) |
| 1661 |
|
| 1662 |
# If we are storing python metadata, we need to set the |
| 1663 |
# 'Python.Fields' Attribute to be all the keys. |
| 1664 |
if options.store_python_metadata: |
| 1665 |
set_attribute_string_array(grp2, 'Python.Fields', |
| 1666 |
fields) |
| 1667 |
|
| 1668 |
# If we are making it MATLAB compatible and have h5py version |
| 1669 |
# >= 2.3, then we can set the MATLAB_fields Attribute as long as |
| 1670 |
# all keys are mappable to ASCII. Otherwise, the attribute |
| 1671 |
# should be deleted. It is written as a vlen='S1' array of |
| 1672 |
# bytes_ arrays of the individual characters. |
| 1673 |
if options.matlab_compatible \ |
| 1674 |
and parse_version(_H5PY_VERSION) \ |
| 1675 |
>= parse_version('2.3'): |
| 1676 |
try: |
| 1677 |
dt = h5py.special_dtype(vlen=np.dtype('S1')) |
| 1678 |
fs = np.empty(shape=(len(fields),), dtype=dt) |
| 1679 |
for i, s in enumerate(fields): |
| 1680 |
fs[i] = np.array([c.encode('ascii') for c in s], |
| 1681 |
dtype='S1') |
| 1682 |
except UnicodeDecodeError: |
| 1683 |
del_attribute(grp2, 'MATLAB_fields') |
| 1684 |
else: |
| 1685 |
set_attribute(grp2, 'MATLAB_fields', fs) |
| 1686 |
else: |
| 1687 |
del_attribute(grp2, 'MATLAB_fields') |
| 1688 |
|
| 1689 |
# If we are making it MATLAB compatible, the MATLAB_class |
| 1690 |
# attribute needs to be set for the data type. If the type |
| 1691 |
# cannot be found or if we are not doing MATLAB compatibility, |
| 1692 |
# the attributes need to be deleted. |
| 1693 |
|
| 1694 |
tp = type(data) |
| 1695 |
if options.matlab_compatible and tp in self.__MATLAB_classes: |
| 1696 |
set_attribute_string(grp2, 'MATLAB_class', |
| 1697 |
self.__MATLAB_classes[tp]) |
| 1698 |
else: |
| 1699 |
del_attribute(grp2, 'MATLAB_class') |
| 1700 |
|
| 1701 |
def read(self, f, grp, name, options): |
| 1702 |
# If name is not present or is not a Group, then we can't read |
| 1703 |
# it and have to throw an error. |
| 1704 |
grp2 = grp.get(name) |
| 1705 |
if grp2 is None: |
| 1706 |
raise NotImplementedError('No object with name ' + name |
| 1707 |
+ 'is present.') |
| 1708 |
if not isinstance(grp2, h5py.Group): |
| 1709 |
raise NotImplementedError(name + ' is not a Group.') |
| 1710 |
|
| 1711 |
# Starting with an empty dict, all that has to be done is |
| 1712 |
# iterate through all the Datasets and Groups in grp[name] and |
| 1713 |
# add them to the dict with their name as the key. Since we |
| 1714 |
# don't want an exception thrown by reading an element to stop |
| 1715 |
# the whole reading process, the reading is wrapped in a try |
| 1716 |
# block that just catches exceptions and then does nothing about |
| 1717 |
# them (nothing needs to be done). |
| 1718 |
data = dict() |
| 1719 |
for k, dsetgrp in grp2.items(): |
| 1720 |
# We must exclude group_for_references |
| 1721 |
if dsetgrp.name == options.group_for_references: |
| 1722 |
continue |
| 1723 |
try: |
| 1724 |
data[k] = read_data(f, grp2, k, options) |
| 1725 |
except: |
| 1726 |
pass |
| 1727 |
return data |
| 1728 |
|
| 1729 |
|
| 1730 |
class PythonListMarshaller(NumpyScalarArrayMarshaller): |
| 1731 |
def __init__(self): |
| 1732 |
NumpyScalarArrayMarshaller.__init__(self) |
| 1733 |
self.types = [list] |
| 1734 |
self.python_type_strings = ['list'] |
| 1735 |
# As the parent class already has MATLAB strings handled, there |
| 1736 |
# are no MATLAB classes that this marshaller should be used for. |
| 1737 |
self.matlab_classes = [] |
| 1738 |
|
| 1739 |
def write(self, f, grp, name, data, type_string, options): |
| 1740 |
# data just needs to be converted to the appropriate numpy type |
| 1741 |
# (pass it through np.object_ to get the and then pass it to the |
| 1742 |
# parent version of this function. The proper type_string needs |
| 1743 |
# to be grabbed now as the parent function will have a modified |
| 1744 |
# form of data to guess from if not given the right one |
| 1745 |
# explicitly. |
| 1746 |
out = np.zeros(dtype='object', shape=(len(data), )) |
| 1747 |
out[:] = data |
| 1748 |
NumpyScalarArrayMarshaller.write(self, f, grp, name, |
| 1749 |
out, |
| 1750 |
self.get_type_string(data, |
| 1751 |
type_string), options) |
| 1752 |
|
| 1753 |
def read(self, f, grp, name, options): |
| 1754 |
# Use the parent class version to read it and do most of the |
| 1755 |
# work. |
| 1756 |
data = NumpyScalarArrayMarshaller.read(self, f, grp, name, |
| 1757 |
options) |
| 1758 |
|
| 1759 |
# Passing it through list does all the work of making it a list |
| 1760 |
# again. |
| 1761 |
return list(data) |
| 1762 |
|
| 1763 |
|
| 1764 |
class PythonTupleSetDequeMarshaller(PythonListMarshaller): |
| 1765 |
def __init__(self): |
| 1766 |
PythonListMarshaller.__init__(self) |
| 1767 |
self.types = [tuple, set, frozenset, collections.deque] |
| 1768 |
self.python_type_strings = ['tuple', 'set', 'frozenset', |
| 1769 |
'collections.deque'] |
| 1770 |
# As the parent class already has MATLAB strings handled, there |
| 1771 |
# are no MATLAB classes that this marshaller should be used for. |
| 1772 |
self.matlab_classes = [] |
| 1773 |
|
| 1774 |
def write(self, f, grp, name, data, type_string, options): |
| 1775 |
# data just needs to be converted to a list and then pass it to |
| 1776 |
# the parent version of this function. The proper type_string |
| 1777 |
# needs to be grabbed now as the parent function will have a |
| 1778 |
# modified form of data to guess from if not given the right one |
| 1779 |
# explicitly. |
| 1780 |
PythonListMarshaller.write(self, f, grp, name, list(data), |
| 1781 |
self.get_type_string(data, |
| 1782 |
type_string), options) |
| 1783 |
|
| 1784 |
def read(self, f, grp, name, options): |
| 1785 |
# Use the parent class version to read it and do most of the |
| 1786 |
# work. |
| 1787 |
data = PythonListMarshaller.read(self, f, grp, name, |
| 1788 |
options) |
| 1789 |
|
| 1790 |
# The type string determines how to convert it back to a Python |
| 1791 |
# type (just look up the entry in types). |
| 1792 |
type_string = get_attribute_string(grp[name], 'Python.Type') |
| 1793 |
if type_string in self.python_type_strings: |
| 1794 |
tp = self.types[self.python_type_strings.index( |
| 1795 |
type_string)] |
| 1796 |
return tp(data) |
| 1797 |
else: |
| 1798 |
# Must be some other type, so return it as is. |
| 1799 |
return data |