| 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 |
This is the hdf5storage package, a Python package to read and write |
| 28 |
python data types to HDF5 (Heirarchal Data Format) files beyond just |
| 29 |
Numpy types. |
| 30 |
|
| 31 |
Version 0.1.19 |
| 32 |
|
| 33 |
""" |
| 34 |
|
| 35 |
__version__ = "0.1.19" |
| 36 |
|
| 37 |
import sys |
| 38 |
import os |
| 39 |
import posixpath |
| 40 |
import copy |
| 41 |
import inspect |
| 42 |
import datetime |
| 43 |
import h5py |
| 44 |
|
| 45 |
from . import lowlevel |
| 46 |
from hdf5storage.lowlevel import Hdf5storageError, CantReadError, \ |
| 47 |
TypeNotMatlabCompatibleError |
| 48 |
|
| 49 |
from . import Marshallers |
| 50 |
|
| 51 |
|
| 52 |
class Options(object): |
| 53 |
""" Set of options governing how data is read/written to/from disk. |
| 54 |
|
| 55 |
There are many ways that data can be transformed as it is read or |
| 56 |
written from a file, and many attributes can be used to describe the |
| 57 |
data depending on its format. The option with the most effect is the |
| 58 |
`matlab_compatible` option. It makes sure that the file is |
| 59 |
compatible with MATLAB's HDF5 based version 7.3 mat file format. It |
| 60 |
overrides several options to the values in the following table. |
| 61 |
|
| 62 |
================================== ==================== |
| 63 |
attribute value |
| 64 |
================================== ==================== |
| 65 |
delete_unused_variables ``True`` |
| 66 |
structured_numpy_ndarray_as_struct ``True`` |
| 67 |
make_atleast_2d ``True`` |
| 68 |
convert_numpy_bytes_to_utf16 ``True`` |
| 69 |
convert_numpy_str_to_utf16 ``True`` |
| 70 |
convert_bools_to_uint8 ``True`` |
| 71 |
reverse_dimension_order ``True`` |
| 72 |
store_shape_for_empty ``True`` |
| 73 |
complex_names ``('real', 'imag')`` |
| 74 |
group_for_references ``'/#refs#'`` |
| 75 |
compression_algorithm ``'gzip'`` |
| 76 |
================================== ==================== |
| 77 |
|
| 78 |
In addition to setting these options, a specially formatted block of |
| 79 |
bytes is put at the front of the file so that MATLAB can recognize |
| 80 |
its format. |
| 81 |
|
| 82 |
Parameters |
| 83 |
---------- |
| 84 |
store_python_metadata : bool, optional |
| 85 |
See Attributes. |
| 86 |
matlab_compatible : bool, optional |
| 87 |
See Attributes. |
| 88 |
action_for_matlab_incompatible : str, optional |
| 89 |
See Attributes. Only valid values are 'ignore', 'discard', and |
| 90 |
'error'. |
| 91 |
delete_unused_variables : bool, optional |
| 92 |
See Attributes. |
| 93 |
structured_numpy_ndarray_as_struct : bool, optional |
| 94 |
See Attributes. |
| 95 |
make_atleast_2d : bool, optional |
| 96 |
See Attributes. |
| 97 |
convert_numpy_bytes_to_utf16 : bool, optional |
| 98 |
See Attributes. |
| 99 |
convert_numpy_str_to_utf16 : bool, optional |
| 100 |
See Attributes. |
| 101 |
convert_bools_to_uint8 : bool, optional |
| 102 |
See Attributes. |
| 103 |
reverse_dimension_order : bool, optional |
| 104 |
See Attributes. |
| 105 |
store_shape_for_empty : bool, optional |
| 106 |
See Attributes. |
| 107 |
complex_names : tuple of two str, optional |
| 108 |
See Attributes. |
| 109 |
group_for_references : str, optional |
| 110 |
See Attributes. |
| 111 |
oned_as : str, optional |
| 112 |
See Attributes. |
| 113 |
compress : bool, optional |
| 114 |
See Attributes. |
| 115 |
compress_size_threshold : int, optional |
| 116 |
See Attributes. |
| 117 |
compression_algorithm : str, optional |
| 118 |
See Attributes. |
| 119 |
gzip_compression_level : int, optional |
| 120 |
See Attributes. |
| 121 |
shuffle_filter : bool, optional |
| 122 |
See Attributes. |
| 123 |
compressed_fletcher32_filter : bool, optional |
| 124 |
See Attributes. |
| 125 |
uncompressed_fletcher32_filter : bool, optional |
| 126 |
See Attributes. |
| 127 |
marshaller_collection : MarshallerCollection, optional |
| 128 |
See Attributes. |
| 129 |
**keywords : |
| 130 |
Additional keyword arguments. They are ignored. They are allowed |
| 131 |
to be given to be more compatible with future versions of this |
| 132 |
package where more options will be added. |
| 133 |
|
| 134 |
Attributes |
| 135 |
---------- |
| 136 |
store_python_metadata : bool |
| 137 |
matlab_compatible : bool |
| 138 |
action_for_matlab_incompatible : str |
| 139 |
delete_unused_variables : bool |
| 140 |
structured_numpy_ndarray_as_struct : bool |
| 141 |
make_atleast_2d : bool |
| 142 |
convert_numpy_bytes_to_utf16 : bool |
| 143 |
convert_numpy_str_to_utf16 : bool |
| 144 |
convert_bools_to_uint8 : bool |
| 145 |
reverse_dimension_order : bool |
| 146 |
store_shape_for_empty : bool |
| 147 |
complex_names : tuple of two str |
| 148 |
group_for_references : str |
| 149 |
oned_as : {'row', 'column'} |
| 150 |
compress : bool |
| 151 |
compress_size_threshold : int |
| 152 |
compression_algorithm : {'gzip', 'lzf', 'szip'} |
| 153 |
gzip_compression_level : int |
| 154 |
shuffle_filter : bool |
| 155 |
compressed_fletcher32_filter : bool |
| 156 |
uncompressed_fletcher32_filter : bool |
| 157 |
scalar_options : dict |
| 158 |
``h5py.Group.create_dataset`` options for writing scalars. |
| 159 |
array_options : dict |
| 160 |
``h5py.Group.create_dataset`` options for writing scalars. |
| 161 |
marshaller_collection : MarshallerCollection |
| 162 |
Collection of marshallers to disk. |
| 163 |
|
| 164 |
""" |
| 165 |
def __init__(self, store_python_metadata=True, |
| 166 |
matlab_compatible=True, |
| 167 |
action_for_matlab_incompatible='error', |
| 168 |
delete_unused_variables=False, |
| 169 |
structured_numpy_ndarray_as_struct=False, |
| 170 |
make_atleast_2d=False, |
| 171 |
convert_numpy_bytes_to_utf16=False, |
| 172 |
convert_numpy_str_to_utf16=False, |
| 173 |
convert_bools_to_uint8=False, |
| 174 |
reverse_dimension_order=False, |
| 175 |
store_shape_for_empty=False, |
| 176 |
complex_names=('r', 'i'), |
| 177 |
group_for_references="/#refs#", |
| 178 |
oned_as='row', |
| 179 |
compress=True, |
| 180 |
compress_size_threshold=16*1024, |
| 181 |
compression_algorithm='gzip', |
| 182 |
gzip_compression_level=7, |
| 183 |
shuffle_filter=True, |
| 184 |
compressed_fletcher32_filter=True, |
| 185 |
uncompressed_fletcher32_filter=False, |
| 186 |
marshaller_collection=None, |
| 187 |
**keywords): |
| 188 |
|
| 189 |
# Set the defaults. |
| 190 |
|
| 191 |
self._store_python_metadata = True |
| 192 |
self._action_for_matlab_incompatible = 'error' |
| 193 |
self._delete_unused_variables = False |
| 194 |
self._structured_numpy_ndarray_as_struct = False |
| 195 |
self._make_atleast_2d = False |
| 196 |
self._convert_numpy_bytes_to_utf16 = False |
| 197 |
self._convert_numpy_str_to_utf16 = False |
| 198 |
self._convert_bools_to_uint8 = False |
| 199 |
self._reverse_dimension_order = False |
| 200 |
self._store_shape_for_empty = False |
| 201 |
self._complex_names = ('r', 'i') |
| 202 |
self._group_for_references = "/#refs#" |
| 203 |
self._oned_as = 'row' |
| 204 |
self._compress = True |
| 205 |
self._compress_size_threshold = 16*1024 |
| 206 |
self._compression_algorithm = 'gzip' |
| 207 |
self._gzip_compression_level = 7 |
| 208 |
self._shuffle_filter = True |
| 209 |
self._compressed_fletcher32_filter = True |
| 210 |
self._uncompressed_fletcher32_filter = False |
| 211 |
self._matlab_compatible = True |
| 212 |
|
| 213 |
# Apply all the given options using the setters, making sure to |
| 214 |
# do matlab_compatible last since it will override most of the |
| 215 |
# other ones. |
| 216 |
|
| 217 |
self.store_python_metadata = store_python_metadata |
| 218 |
self.action_for_matlab_incompatible = \ |
| 219 |
action_for_matlab_incompatible |
| 220 |
self.delete_unused_variables = delete_unused_variables |
| 221 |
self.structured_numpy_ndarray_as_struct = \ |
| 222 |
structured_numpy_ndarray_as_struct |
| 223 |
self.make_atleast_2d = make_atleast_2d |
| 224 |
self.convert_numpy_bytes_to_utf16 = convert_numpy_bytes_to_utf16 |
| 225 |
self.convert_numpy_str_to_utf16 = convert_numpy_str_to_utf16 |
| 226 |
self.convert_bools_to_uint8 = convert_bools_to_uint8 |
| 227 |
self.reverse_dimension_order = reverse_dimension_order |
| 228 |
self.store_shape_for_empty = store_shape_for_empty |
| 229 |
self.complex_names = complex_names |
| 230 |
self.group_for_references = group_for_references |
| 231 |
self.oned_as = oned_as |
| 232 |
self.compress = compress |
| 233 |
self.compress_size_threshold = compress_size_threshold |
| 234 |
self.compression_algorithm = compression_algorithm |
| 235 |
self.gzip_compression_level = gzip_compression_level |
| 236 |
self.shuffle_filter = shuffle_filter |
| 237 |
self.compressed_fletcher32_filter = compressed_fletcher32_filter |
| 238 |
self.uncompressed_fletcher32_filter = \ |
| 239 |
uncompressed_fletcher32_filter |
| 240 |
self.matlab_compatible = matlab_compatible |
| 241 |
|
| 242 |
# Set the h5py options to use for writing scalars and arrays to |
| 243 |
# blank for now. |
| 244 |
|
| 245 |
self.scalar_options = dict() |
| 246 |
self.array_options = dict() |
| 247 |
|
| 248 |
# Use the given marshaller collection if it was |
| 249 |
# given. Otherwise, use the default. |
| 250 |
|
| 251 |
#: Collection of marshallers to disk. |
| 252 |
#: |
| 253 |
#: MarshallerCollection |
| 254 |
#: |
| 255 |
#: See Also |
| 256 |
#: -------- |
| 257 |
#: MarshallerCollection |
| 258 |
self.marshaller_collection = marshaller_collection |
| 259 |
if not isinstance(marshaller_collection, MarshallerCollection): |
| 260 |
self.marshaller_collection = MarshallerCollection() |
| 261 |
|
| 262 |
@property |
| 263 |
def store_python_metadata(self): |
| 264 |
""" Whether or not to store Python metadata. |
| 265 |
|
| 266 |
bool |
| 267 |
|
| 268 |
If ``True`` (default), information on the Python type for each |
| 269 |
object written to disk is put in its attributes so that it can |
| 270 |
be read back into Python as the same type. |
| 271 |
|
| 272 |
""" |
| 273 |
return self._store_python_metadata |
| 274 |
|
| 275 |
@store_python_metadata.setter |
| 276 |
def store_python_metadata(self, value): |
| 277 |
# Check that it is a bool, and then set it. This option does not |
| 278 |
# effect MATLAB compatibility |
| 279 |
if isinstance(value, bool): |
| 280 |
self._store_python_metadata = value |
| 281 |
|
| 282 |
@property |
| 283 |
def matlab_compatible(self): |
| 284 |
""" Whether or not to make the file compatible with MATLAB. |
| 285 |
|
| 286 |
bool |
| 287 |
|
| 288 |
If ``True`` (default), data is written to file in such a way |
| 289 |
that it compatible with MATLAB's version 7.3 mat file format |
| 290 |
which is HDF5 based. Setting it to ``True`` forces other options |
| 291 |
to hold the specific values in the table below. |
| 292 |
|
| 293 |
================================== ==================== |
| 294 |
attribute value |
| 295 |
================================== ==================== |
| 296 |
delete_unused_variables ``True`` |
| 297 |
structured_numpy_ndarray_as_struct ``True`` |
| 298 |
make_atleast_2d ``True`` |
| 299 |
convert_numpy_bytes_to_utf16 ``True`` |
| 300 |
convert_numpy_str_to_utf16 ``True`` |
| 301 |
convert_bools_to_uint8 ``True`` |
| 302 |
reverse_dimension_order ``True`` |
| 303 |
store_shape_for_empty ``True`` |
| 304 |
complex_names ``('real', 'imag')`` |
| 305 |
group_for_references ``'/#refs#'`` |
| 306 |
compression_algorithm ``'gzip'`` |
| 307 |
================================== ==================== |
| 308 |
|
| 309 |
In addition to setting these options, a specially formatted |
| 310 |
block of bytes is put at the front of the file so that MATLAB |
| 311 |
can recognize its format. |
| 312 |
|
| 313 |
""" |
| 314 |
return self._matlab_compatible |
| 315 |
|
| 316 |
@matlab_compatible.setter |
| 317 |
def matlab_compatible(self, value): |
| 318 |
# If it is a bool, it can be set. If it is set to true, then |
| 319 |
# several other options need to be set appropriately. |
| 320 |
if isinstance(value, bool): |
| 321 |
self._matlab_compatible = value |
| 322 |
if value: |
| 323 |
self._delete_unused_variables = True |
| 324 |
self._structured_numpy_ndarray_as_struct = True |
| 325 |
self._make_atleast_2d = True |
| 326 |
self._convert_numpy_bytes_to_utf16 = True |
| 327 |
self._convert_numpy_str_to_utf16 = True |
| 328 |
self._convert_bools_to_uint8 = True |
| 329 |
self._reverse_dimension_order = True |
| 330 |
self._store_shape_for_empty = True |
| 331 |
self._complex_names = ('real', 'imag') |
| 332 |
self._group_for_references = "/#refs#" |
| 333 |
self._compression_algorithm = 'gzip' |
| 334 |
|
| 335 |
@property |
| 336 |
def action_for_matlab_incompatible(self): |
| 337 |
""" The action to do when writing non-MATLAB compatible data. |
| 338 |
|
| 339 |
{'ignore', 'discard', 'error'} |
| 340 |
|
| 341 |
The action to perform when doing MATLAB compatibility but a type |
| 342 |
being written is not MATLAB compatible. The actions are to write |
| 343 |
the data anyways ('ignore'), don't write the incompatible data |
| 344 |
('discard'), or throw a ``TypeNotMatlabCompatibleError`` |
| 345 |
exception. The default is 'error'. |
| 346 |
|
| 347 |
See Also |
| 348 |
-------- |
| 349 |
matlab_compatible |
| 350 |
hdf5storage.lowlevel.TypeNotMatlabCompatibleError |
| 351 |
|
| 352 |
""" |
| 353 |
return self._action_for_matlab_incompatible |
| 354 |
|
| 355 |
@action_for_matlab_incompatible.setter |
| 356 |
def action_for_matlab_incompatible(self, value): |
| 357 |
# Check that it is one of the allowed values, and then set |
| 358 |
# it. This option does not effect MATLAB compatibility. |
| 359 |
if value in ('ignore', 'discard', 'error'): |
| 360 |
self._action_for_matlab_incompatible = value |
| 361 |
|
| 362 |
@property |
| 363 |
def delete_unused_variables(self): |
| 364 |
""" Whether or not to delete file variables not written to. |
| 365 |
|
| 366 |
bool |
| 367 |
|
| 368 |
If ``True`` (defaults to ``False`` unless MATLAB compatibility |
| 369 |
is being done), variables in the file below where writing starts |
| 370 |
that are not written to are deleted. |
| 371 |
|
| 372 |
Must be ``True`` if doing MATLAB compatibility. |
| 373 |
|
| 374 |
""" |
| 375 |
return self._delete_unused_variables |
| 376 |
|
| 377 |
@delete_unused_variables.setter |
| 378 |
def delete_unused_variables(self, value): |
| 379 |
# Check that it is a bool, and then set it. If it is false, we |
| 380 |
# are not doing MATLAB compatible formatting. |
| 381 |
if isinstance(value, bool): |
| 382 |
self._delete_unused_variables = value |
| 383 |
if not self._delete_unused_variables: |
| 384 |
self._matlab_compatible = False |
| 385 |
|
| 386 |
@property |
| 387 |
def structured_numpy_ndarray_as_struct(self): |
| 388 |
""" Whether or not to convert structured ndarrays to structs. |
| 389 |
|
| 390 |
bool |
| 391 |
|
| 392 |
If ``True`` (defaults to ``False`` unless MATLAB compatibility |
| 393 |
is being done), all ``numpy.ndarray``s with fields (compound |
| 394 |
dtypes) are written as HDF5 Groups with the fields as Datasets |
| 395 |
(correspond to struct arrays in MATLAB). |
| 396 |
|
| 397 |
Must be ``True`` if doing MATLAB compatibility. MATLAB cannot |
| 398 |
handle the compound types made by writing these types. |
| 399 |
|
| 400 |
""" |
| 401 |
return self._structured_numpy_ndarray_as_struct |
| 402 |
|
| 403 |
@structured_numpy_ndarray_as_struct.setter |
| 404 |
def structured_numpy_ndarray_as_struct(self, value): |
| 405 |
# Check that it is a bool, and then set it. If it is false, we |
| 406 |
# are not doing MATLAB compatible formatting. |
| 407 |
if isinstance(value, bool): |
| 408 |
self._structured_numpy_ndarray_as_struct = value |
| 409 |
if not self._structured_numpy_ndarray_as_struct: |
| 410 |
self._matlab_compatible = False |
| 411 |
|
| 412 |
@property |
| 413 |
def make_atleast_2d(self): |
| 414 |
""" Whether or not to convert scalar types to 2D arrays. |
| 415 |
|
| 416 |
bool |
| 417 |
|
| 418 |
If ``True`` (defaults to ``False`` unless MATLAB compatibility |
| 419 |
is being done), all scalar types are converted to 2D arrays when |
| 420 |
written to file. ``oned_as`` determines whether 1D arrays are |
| 421 |
turned into row or column vectors. |
| 422 |
|
| 423 |
Must be ``True`` if doing MATLAB compatibility. MATLAB can only |
| 424 |
import 2D and higher dimensional arrays. |
| 425 |
|
| 426 |
See Also |
| 427 |
-------- |
| 428 |
oned_as |
| 429 |
|
| 430 |
""" |
| 431 |
return self._make_atleast_2d |
| 432 |
|
| 433 |
@make_atleast_2d.setter |
| 434 |
def make_atleast_2d(self, value): |
| 435 |
# Check that it is a bool, and then set it. If it is false, we |
| 436 |
# are not doing MATLAB compatible formatting. |
| 437 |
if isinstance(value, bool): |
| 438 |
self._make_atleast_2d = value |
| 439 |
if not self._make_atleast_2d: |
| 440 |
self._matlab_compatible = False |
| 441 |
|
| 442 |
@property |
| 443 |
def convert_numpy_bytes_to_utf16(self): |
| 444 |
""" Whether or not to convert numpy.bytes\\_ to UTF-16. |
| 445 |
|
| 446 |
bool |
| 447 |
|
| 448 |
If ``True`` (defaults to ``False`` unless MATLAB compatibility |
| 449 |
is being done), ``numpy.bytes_`` and anything that is converted |
| 450 |
to them (``bytes``, and ``bytearray``) are converted to UTF-16 |
| 451 |
before being written to file as ``numpy.uint16``. |
| 452 |
|
| 453 |
Must be ``True`` if doing MATLAB compatibility. MATLAB uses |
| 454 |
UTF-16 for its strings. |
| 455 |
|
| 456 |
See Also |
| 457 |
-------- |
| 458 |
numpy.bytes_ |
| 459 |
convert_numpy_str_to_utf16 |
| 460 |
|
| 461 |
""" |
| 462 |
return self._convert_numpy_bytes_to_utf16 |
| 463 |
|
| 464 |
@convert_numpy_bytes_to_utf16.setter |
| 465 |
def convert_numpy_bytes_to_utf16(self, value): |
| 466 |
# Check that it is a bool, and then set it. If it is false, we |
| 467 |
# are not doing MATLAB compatible formatting. |
| 468 |
if isinstance(value, bool): |
| 469 |
self._convert_numpy_bytes_to_utf16 = value |
| 470 |
if not self._convert_numpy_bytes_to_utf16: |
| 471 |
self._matlab_compatible = False |
| 472 |
|
| 473 |
@property |
| 474 |
def convert_numpy_str_to_utf16(self): |
| 475 |
""" Whether or not to convert numpy.str\\_ to UTF-16. |
| 476 |
|
| 477 |
bool |
| 478 |
|
| 479 |
If ``True`` (defaults to ``False`` unless MATLAB compatibility |
| 480 |
is being done), ``numpy.str_`` and anything that is converted |
| 481 |
to them (``str``) will be converted to UTF-16 if possible before |
| 482 |
being written to file as ``numpy.uint16``. If doing so would |
| 483 |
lead to a loss of data (character can't be translated to |
| 484 |
UTF-16) or would change the shape of an array of ``numpy.str_`` |
| 485 |
due to a character being converted into a pair 2-bytes, the |
| 486 |
conversion will not be made and the string will be stored in |
| 487 |
UTF-32 form as a ``numpy.uint32``. |
| 488 |
|
| 489 |
Must be ``True`` if doing MATLAB compatibility. MATLAB uses |
| 490 |
UTF-16 for its strings. |
| 491 |
|
| 492 |
See Also |
| 493 |
-------- |
| 494 |
numpy.bytes_ |
| 495 |
convert_numpy_str_to_utf16 |
| 496 |
|
| 497 |
""" |
| 498 |
return self._convert_numpy_str_to_utf16 |
| 499 |
|
| 500 |
@convert_numpy_str_to_utf16.setter |
| 501 |
def convert_numpy_str_to_utf16(self, value): |
| 502 |
# Check that it is a bool, and then set it. If it is false, we |
| 503 |
# are not doing MATLAB compatible formatting. |
| 504 |
if isinstance(value, bool): |
| 505 |
self._convert_numpy_str_to_utf16 = value |
| 506 |
if not self._convert_numpy_str_to_utf16: |
| 507 |
self._matlab_compatible = False |
| 508 |
|
| 509 |
@property |
| 510 |
def convert_bools_to_uint8(self): |
| 511 |
""" Whether or not to convert bools to ``numpy.uint8``. |
| 512 |
|
| 513 |
bool |
| 514 |
|
| 515 |
If ``True`` (defaults to ``False`` unless MATLAB compatibility |
| 516 |
is being done), bool types are converted to ``numpy.uint8`` |
| 517 |
before being written to file. |
| 518 |
|
| 519 |
Must be ``True`` if doing MATLAB compatibility. MATLAB doesn't |
| 520 |
use the enums that ``h5py`` wants to use by default and also |
| 521 |
uses uint8 intead of int8. |
| 522 |
|
| 523 |
""" |
| 524 |
return self._convert_bools_to_uint8 |
| 525 |
|
| 526 |
@convert_bools_to_uint8.setter |
| 527 |
def convert_bools_to_uint8(self, value): |
| 528 |
# Check that it is a bool, and then set it. If it is false, we |
| 529 |
# are not doing MATLAB compatible formatting. |
| 530 |
if isinstance(value, bool): |
| 531 |
self._convert_bools_to_uint8 = value |
| 532 |
if not self._convert_bools_to_uint8: |
| 533 |
self._matlab_compatible = False |
| 534 |
|
| 535 |
@property |
| 536 |
def reverse_dimension_order(self): |
| 537 |
""" Whether or not to reverse the order of array dimensions. |
| 538 |
|
| 539 |
bool |
| 540 |
|
| 541 |
If ``True`` (defaults to ``False`` unless MATLAB compatibility |
| 542 |
is being done), the dimension order of ``numpy.ndarray`` and |
| 543 |
``numpy.matrix`` are reversed. This switches them from C |
| 544 |
ordering to Fortran ordering. The switch of ordering is |
| 545 |
essentially a transpose. |
| 546 |
|
| 547 |
Must be ``True`` if doing MATLAB compatibility. MATLAB uses |
| 548 |
Fortran ordering. |
| 549 |
|
| 550 |
""" |
| 551 |
return self._reverse_dimension_order |
| 552 |
|
| 553 |
@reverse_dimension_order.setter |
| 554 |
def reverse_dimension_order(self, value): |
| 555 |
# Check that it is a bool, and then set it. If it is false, we |
| 556 |
# are not doing MATLAB compatible formatting. |
| 557 |
if isinstance(value, bool): |
| 558 |
self._reverse_dimension_order = value |
| 559 |
if not self._reverse_dimension_order: |
| 560 |
self._matlab_compatible = False |
| 561 |
|
| 562 |
@property |
| 563 |
def store_shape_for_empty(self): |
| 564 |
""" Whether to write the shape if an object has no elements. |
| 565 |
|
| 566 |
bool |
| 567 |
|
| 568 |
If ``True`` (defaults to ``False`` unless MATLAB compatibility |
| 569 |
is being done), objects that have no elements (e.g. a |
| 570 |
0x0x2 array) will have their shape (an array of the number of |
| 571 |
elements along each axis) written to disk in place of nothing, |
| 572 |
which would otherwise be written. |
| 573 |
|
| 574 |
Must be ``True`` if doing MATLAB compatibility. For empty |
| 575 |
arrays, MATLAB requires that the shape array be written in its |
| 576 |
place along with the attribute 'MATLAB_empty' set to 1 to flag |
| 577 |
it. |
| 578 |
|
| 579 |
""" |
| 580 |
return self._store_shape_for_empty |
| 581 |
|
| 582 |
@store_shape_for_empty.setter |
| 583 |
def store_shape_for_empty(self, value): |
| 584 |
# Check that it is a bool, and then set it. If it is false, we |
| 585 |
# are not doing MATLAB compatible formatting. |
| 586 |
if isinstance(value, bool): |
| 587 |
self._store_shape_for_empty = value |
| 588 |
if not self._store_shape_for_empty: |
| 589 |
self._matlab_compatible = False |
| 590 |
|
| 591 |
@property |
| 592 |
def complex_names(self): |
| 593 |
""" Names to use for the real and imaginary fields. |
| 594 |
|
| 595 |
tuple of two str |
| 596 |
|
| 597 |
``(r, i)`` where `r` and `i` are two ``str``. When reading and |
| 598 |
writing complex numbers, the real part gets the name in `r` and |
| 599 |
the imaginary part gets the name in `i`. ``h5py`` uses |
| 600 |
``('r', 'i')`` by default, unless MATLAB compatibility is being |
| 601 |
done in which case its default is ``('real', 'imag')``. |
| 602 |
|
| 603 |
Must be ``('real', 'imag')`` if doing MATLAB compatibility. |
| 604 |
|
| 605 |
""" |
| 606 |
return self._complex_names |
| 607 |
|
| 608 |
@complex_names.setter |
| 609 |
def complex_names(self, value): |
| 610 |
# Check that it is a tuple of two strings, and then set it. If |
| 611 |
# it is something other than ('real', 'imag'), then we are not |
| 612 |
# doing MATLAB compatible formatting. |
| 613 |
if isinstance(value, tuple) and len(value) == 2 \ |
| 614 |
and isinstance(value[0], str) \ |
| 615 |
and isinstance(value[1], str): |
| 616 |
self._complex_names = value |
| 617 |
if self._complex_names != ('real', 'imag'): |
| 618 |
self._matlab_compatible = False |
| 619 |
|
| 620 |
@property |
| 621 |
def group_for_references(self): |
| 622 |
""" Path for where to put objects pointed at by references. |
| 623 |
|
| 624 |
str |
| 625 |
|
| 626 |
The absolute POSIX path for the Group to place all data that is |
| 627 |
pointed to by another piece of data (needed for |
| 628 |
``numpy.object_`` and similar types). This path is automatically |
| 629 |
excluded from its parent group when reading back a ``dict``. |
| 630 |
|
| 631 |
Must be ``'/#refs#`` if doing MATLAB compatibility. |
| 632 |
|
| 633 |
""" |
| 634 |
return self._group_for_references |
| 635 |
|
| 636 |
@group_for_references.setter |
| 637 |
def group_for_references(self, value): |
| 638 |
# Check that it an str and a valid absolute POSIX path, and then |
| 639 |
# set it. If it is something other than "/#refs#", then we are |
| 640 |
# not doing MATLAB compatible formatting. |
| 641 |
if isinstance(value, str): |
| 642 |
pth = posixpath.normpath(value) |
| 643 |
if len(pth) > 1 and posixpath.isabs(pth): |
| 644 |
self._group_for_references = value |
| 645 |
if self._group_for_references != "/#refs#": |
| 646 |
self._matlab_compatible = False |
| 647 |
|
| 648 |
@property |
| 649 |
def oned_as(self): |
| 650 |
""" Vector that 1D arrays become when making everything >= 2D. |
| 651 |
|
| 652 |
{'row', 'column'} |
| 653 |
|
| 654 |
When the ``make_atleast_2d`` option is set (set implicitly by |
| 655 |
doing MATLAB compatibility), this option controls whether 1D |
| 656 |
arrays become row vectors or column vectors. |
| 657 |
|
| 658 |
See Also |
| 659 |
-------- |
| 660 |
make_atleast_2d |
| 661 |
|
| 662 |
""" |
| 663 |
return self._oned_as |
| 664 |
|
| 665 |
@oned_as.setter |
| 666 |
def oned_as(self, value): |
| 667 |
# Check that it is one of the valid values before setting it. |
| 668 |
if value in ('row', 'column'): |
| 669 |
self._oned_as = value |
| 670 |
|
| 671 |
@property |
| 672 |
def compress(self): |
| 673 |
""" Whether to compress large python objects (datasets). |
| 674 |
|
| 675 |
bool |
| 676 |
|
| 677 |
If ``True``, python objects (datasets) larger than |
| 678 |
``compress_size_threshold`` will be compressed. |
| 679 |
|
| 680 |
See Also |
| 681 |
-------- |
| 682 |
compress_size_threshold |
| 683 |
compression_algorithm |
| 684 |
shuffle_filter |
| 685 |
compressed_fletcher32_filter |
| 686 |
|
| 687 |
""" |
| 688 |
return self._compress |
| 689 |
|
| 690 |
@compress.setter |
| 691 |
def compress(self, value): |
| 692 |
# Check that it is a bool, and then set it. |
| 693 |
if isinstance(value, bool): |
| 694 |
self._compress = value |
| 695 |
|
| 696 |
@property |
| 697 |
def compress_size_threshold(self): |
| 698 |
""" Minimum size of a python object before it is compressed. |
| 699 |
|
| 700 |
int |
| 701 |
|
| 702 |
Minimum size in bytes a python object must be for it to be |
| 703 |
compressed if ``compress`` is set. Must be non-negative. |
| 704 |
|
| 705 |
See Also |
| 706 |
-------- |
| 707 |
compress |
| 708 |
|
| 709 |
""" |
| 710 |
return self._compress_size_threshold |
| 711 |
|
| 712 |
@compress_size_threshold.setter |
| 713 |
def compress_size_threshold(self, value): |
| 714 |
# Check that it is a non-negative integer, and then set it. |
| 715 |
if isinstance(value, int) and value >= 0: |
| 716 |
self._compress_size_threshold = value |
| 717 |
|
| 718 |
@property |
| 719 |
def compression_algorithm(self): |
| 720 |
""" Algorithm to use for compression. |
| 721 |
|
| 722 |
{'gzip', 'lzf', 'szip'} |
| 723 |
|
| 724 |
Compression algorithm to use When the ``compress`` option is set |
| 725 |
and a python object is larger than ``compress_size_threshold``. |
| 726 |
``'gzip'`` is the only MATLAB compatible option. |
| 727 |
|
| 728 |
``'gzip'`` is also known as the Deflate algorithm, which is the |
| 729 |
default compression algorithm of ZIP files and is a common |
| 730 |
compression algorithm used on tarballs. It is the most |
| 731 |
compatible option. It has good compression and is reasonably |
| 732 |
fast. Its compression level is set with the |
| 733 |
``gzip_compression_level`` option, which is an integer between 0 |
| 734 |
and 9 inclusive. |
| 735 |
|
| 736 |
``'lzf'`` is a very fast but low to moderate compression |
| 737 |
algorithm. It is less commonly used than gzip/Deflate, but |
| 738 |
doesn't have any patent or license issues. |
| 739 |
|
| 740 |
``'szip'`` is a compression algorithm that has some patents and |
| 741 |
license restrictions. It is not always available. |
| 742 |
|
| 743 |
See Also |
| 744 |
-------- |
| 745 |
compress |
| 746 |
compress_size_threshold |
| 747 |
h5py.Group.create_dataset |
| 748 |
|
| 749 |
""" |
| 750 |
return self._compression_algorithm |
| 751 |
|
| 752 |
@compression_algorithm.setter |
| 753 |
def compression_algorithm(self, value): |
| 754 |
# Check that it is one of the valid values before setting it. If |
| 755 |
# it is something other than 'gzip', then we are not doing |
| 756 |
# MATLAB compatible formatting. |
| 757 |
if value in ('gzip', 'lzf', 'szip'): |
| 758 |
self._compression_algorithm = value |
| 759 |
if self._compression_algorithm != 'gzip': |
| 760 |
self._matlab_compatible = False |
| 761 |
|
| 762 |
@property |
| 763 |
def gzip_compression_level(self): |
| 764 |
""" The compression level to use when doing the gzip algorithm. |
| 765 |
|
| 766 |
int |
| 767 |
|
| 768 |
Compression level to use when data is being compressed with the |
| 769 |
``'gzip'`` algorithm. Must be an integer between 0 and 9 |
| 770 |
inclusive. Lower values are faster while higher values give |
| 771 |
better compression. |
| 772 |
|
| 773 |
See Also |
| 774 |
-------- |
| 775 |
compress |
| 776 |
compression_algorithm |
| 777 |
|
| 778 |
""" |
| 779 |
return self._gzip_compression_level |
| 780 |
|
| 781 |
@gzip_compression_level.setter |
| 782 |
def gzip_compression_level(self, value): |
| 783 |
# Check that it is an integer between 0 and 9. |
| 784 |
if isinstance(value, int) and value >= 0 and value <= 9: |
| 785 |
self._gzip_compression_level = value |
| 786 |
|
| 787 |
@property |
| 788 |
def shuffle_filter(self): |
| 789 |
""" Whether to use the shuffle filter on compressed python objects. |
| 790 |
|
| 791 |
bool |
| 792 |
|
| 793 |
If ``True``, python objects (datasets) that are compressed are |
| 794 |
run through the shuffle filter, which reversibly rearranges the |
| 795 |
data to improve compression. |
| 796 |
|
| 797 |
See Also |
| 798 |
-------- |
| 799 |
compress |
| 800 |
h5py.Group.create_dataset |
| 801 |
|
| 802 |
""" |
| 803 |
return self._shuffle_filter |
| 804 |
|
| 805 |
@shuffle_filter.setter |
| 806 |
def shuffle_filter(self, value): |
| 807 |
# Check that it is a bool, and then set it. |
| 808 |
if isinstance(value, bool): |
| 809 |
self._shuffle_filter = value |
| 810 |
|
| 811 |
@property |
| 812 |
def compressed_fletcher32_filter(self): |
| 813 |
""" Whether to use the fletcher32 filter on compressed python objects. |
| 814 |
|
| 815 |
bool |
| 816 |
|
| 817 |
If ``True``, python objects (datasets) that are compressed are |
| 818 |
run through the fletcher32 filter, which stores a checksum with |
| 819 |
each chunk so that data corruption can be more easily detected. |
| 820 |
|
| 821 |
See Also |
| 822 |
-------- |
| 823 |
compress |
| 824 |
shuffle_filter |
| 825 |
uncompressed_flether32_filter |
| 826 |
h5py.Group.create_dataset |
| 827 |
|
| 828 |
""" |
| 829 |
return self._compressed_fletcher32_filter |
| 830 |
|
| 831 |
@compressed_fletcher32_filter.setter |
| 832 |
def compressed_fletcher32_filter(self, value): |
| 833 |
# Check that it is a bool, and then set it. |
| 834 |
if isinstance(value, bool): |
| 835 |
self._compressed_fletcher32_filter = value |
| 836 |
|
| 837 |
@property |
| 838 |
def uncompressed_fletcher32_filter(self): |
| 839 |
""" Whether to use the fletcher32 filter on uncompressed non-scalar python objects. |
| 840 |
|
| 841 |
bool |
| 842 |
|
| 843 |
If ``True``, python objects (datasets) that are **NOT** |
| 844 |
compressed and are not scalars (when converted to a Numpy type, |
| 845 |
their shape is not an empty ``tuple``) are run through the |
| 846 |
fletcher32 filter, which stores a checksum with each chunk so |
| 847 |
that data corruption can be more easily detected. This forces |
| 848 |
all uncompressed data to be chuncked regardless of how small and |
| 849 |
can increase file sizes. |
| 850 |
|
| 851 |
See Also |
| 852 |
-------- |
| 853 |
compress |
| 854 |
shuffle_filter |
| 855 |
compressed_flether32_filter |
| 856 |
h5py.Group.create_dataset |
| 857 |
|
| 858 |
""" |
| 859 |
return self._uncompressed_fletcher32_filter |
| 860 |
|
| 861 |
@uncompressed_fletcher32_filter.setter |
| 862 |
def uncompressed_fletcher32_filter(self, value): |
| 863 |
# Check that it is a bool, and then set it. |
| 864 |
if isinstance(value, bool): |
| 865 |
self._uncompressed_fletcher32_filter = value |
| 866 |
|
| 867 |
|
| 868 |
class MarshallerCollection(object): |
| 869 |
""" Represents, maintains, and retreives a set of marshallers. |
| 870 |
|
| 871 |
Maintains a list of marshallers used to marshal data types to and |
| 872 |
from HDF5 files. It includes the builtin marshallers from the |
| 873 |
``hdf5storage.Marshallers`` module as well as any user supplied or |
| 874 |
added marshallers. While the builtin list cannot be changed; user |
| 875 |
ones can be added or removed. Also has functions to get the |
| 876 |
marshaller appropriate for ``type`` or type_string for a python data |
| 877 |
type. |
| 878 |
|
| 879 |
User marshallers must provide the same interface as |
| 880 |
``hdf5storage.Marshallers.TypeMarshaller``, which is probably most |
| 881 |
easily done by inheriting from it. |
| 882 |
|
| 883 |
Parameters |
| 884 |
---------- |
| 885 |
marshallers : marshaller or list of marshallers, optional |
| 886 |
The user marshaller/s to add to the collection. Could also be a |
| 887 |
``tuple``, ``set``, or ``frozenset`` of marshallers. |
| 888 |
|
| 889 |
See Also |
| 890 |
-------- |
| 891 |
hdf5storage.Marshallers |
| 892 |
hdf5storage.Marshallers.TypeMarshaller |
| 893 |
|
| 894 |
""" |
| 895 |
def __init__(self, marshallers=[]): |
| 896 |
# Two lists of marshallers need to be maintained: one for the |
| 897 |
# builtin ones in the Marshallers module, and another for user |
| 898 |
# supplied ones. |
| 899 |
|
| 900 |
# Grab all the marshallers in the Marshallers module (they are |
| 901 |
# the classes) by inspection. |
| 902 |
self._builtin_marshallers = [m() for key, m in dict( |
| 903 |
inspect.getmembers(Marshallers, |
| 904 |
inspect.isclass)).items() |
| 905 |
if m != Marshallers.parse_version] |
| 906 |
self._user_marshallers = [] |
| 907 |
|
| 908 |
# A list of all the marshallers will be needed along with |
| 909 |
# dictionaries to lookup up the marshaller to use for given |
| 910 |
# types, type string, or MATLAB class string (they are the |
| 911 |
# keys). |
| 912 |
self._marshallers = [] |
| 913 |
self._types = dict() |
| 914 |
self._type_strings = dict() |
| 915 |
self._matlab_classes = dict() |
| 916 |
|
| 917 |
# Add any user given marshallers. |
| 918 |
self.add_marshaller(copy.deepcopy(marshallers)) |
| 919 |
|
| 920 |
def _update_marshallers(self): |
| 921 |
""" Update the full marshaller list and other data structures. |
| 922 |
|
| 923 |
Makes a full list of both builtin and user marshallers and |
| 924 |
rebuilds internal data structures used for looking up which |
| 925 |
marshaller to use for reading/writing Python objects to/from |
| 926 |
file. |
| 927 |
|
| 928 |
""" |
| 929 |
# Combine both sets of marshallers. |
| 930 |
self._marshallers = copy.deepcopy(self._builtin_marshallers) |
| 931 |
self._marshallers.extend(copy.deepcopy(self._user_marshallers)) |
| 932 |
|
| 933 |
# Construct the dictionary to look up the appropriate marshaller |
| 934 |
# by type. It would normally be a dict comprehension such as |
| 935 |
# |
| 936 |
# self._types = {tp: m for m in self._marshallers |
| 937 |
# for tp in m.types} |
| 938 |
# |
| 939 |
# but that is not supported in Python 2.6 so it has to be done |
| 940 |
# with a for loop. |
| 941 |
|
| 942 |
self._types = dict() |
| 943 |
for m in self._marshallers: |
| 944 |
for tp in m.types: |
| 945 |
self._types[tp] = m |
| 946 |
|
| 947 |
# The equivalent one to read data types given type strings needs |
| 948 |
# to be created from it. Basically, we have to make the key be |
| 949 |
# the python_type_string from it. Same issue as before with |
| 950 |
# Python 2.6 |
| 951 |
# |
| 952 |
# self._type_strings = {type_string: m for key, m in |
| 953 |
# self._types.items() for type_string in |
| 954 |
# m.python_type_strings} |
| 955 |
|
| 956 |
self._type_strings = dict() |
| 957 |
for key, m in self._types.items(): |
| 958 |
for type_string in m.python_type_strings: |
| 959 |
self._type_strings[type_string] = m |
| 960 |
|
| 961 |
# The equivalent one to read data types given MATLAB class |
| 962 |
# strings needs to be created from it. Basically, we have to |
| 963 |
# make the key be the matlab_class from it. Same issue as before |
| 964 |
# with Python 2.6 |
| 965 |
# |
| 966 |
# self._matlab_classes = {matlab_class: m for key, m in |
| 967 |
# self._types.items() for matlab_class in |
| 968 |
# m.matlab_classes} |
| 969 |
|
| 970 |
self._matlab_classes = dict() |
| 971 |
for key, m in self._types.items(): |
| 972 |
for matlab_class in m.matlab_classes: |
| 973 |
self._matlab_classes[matlab_class] = m |
| 974 |
|
| 975 |
def add_marshaller(self, marshallers): |
| 976 |
""" Add a marshaller/s to the user provided list. |
| 977 |
|
| 978 |
Adds a marshaller or a list of them to the user provided set of |
| 979 |
marshallers. |
| 980 |
|
| 981 |
Parameters |
| 982 |
---------- |
| 983 |
marshallers : marshaller or list of marshallers |
| 984 |
The user marshaller/s to add to the user provided |
| 985 |
collection. Could also be a ``tuple``, ``set``, or |
| 986 |
``frozenset`` of marshallers. |
| 987 |
|
| 988 |
""" |
| 989 |
if not isinstance(marshallers, (list, tuple, set, frozenset)): |
| 990 |
marshallers = [marshallers] |
| 991 |
for m in marshallers: |
| 992 |
if m not in self._user_marshallers: |
| 993 |
self._user_marshallers.append(copy.deepcopy(m)) |
| 994 |
self._update_marshallers() |
| 995 |
|
| 996 |
def remove_marshaller(self, marshallers): |
| 997 |
""" Removes a marshaller/s from the user provided list. |
| 998 |
|
| 999 |
Removes a marshaller or a list of them from the user provided set |
| 1000 |
of marshallers. |
| 1001 |
|
| 1002 |
Parameters |
| 1003 |
---------- |
| 1004 |
marshallers : marshaller or list of marshallers |
| 1005 |
The user marshaller/s to from the user provided collection. |
| 1006 |
Could also be a ``tuple``, ``set``, or ``frozenset`` of |
| 1007 |
marshallers. |
| 1008 |
|
| 1009 |
""" |
| 1010 |
if not isinstance(marshallers, (list, tuple, set, frozenset)): |
| 1011 |
marshallers = [marshallers] |
| 1012 |
for m in marshallers: |
| 1013 |
if m in self._user_marshallers: |
| 1014 |
self._user_marshallers.remove(m) |
| 1015 |
self._update_marshallers() |
| 1016 |
|
| 1017 |
def clear_marshallers(self): |
| 1018 |
""" Clears the list of user provided marshallers. |
| 1019 |
|
| 1020 |
Removes all user provided marshallers, but not the builtin ones |
| 1021 |
from the ``hdf5storage.Marshallers`` module, from the list of |
| 1022 |
marshallers used. |
| 1023 |
|
| 1024 |
""" |
| 1025 |
self._user_marshallers.clear() |
| 1026 |
self._update_marshallers() |
| 1027 |
|
| 1028 |
def get_marshaller_for_type(self, tp): |
| 1029 |
""" Gets the appropriate marshaller for a type. |
| 1030 |
|
| 1031 |
Retrieves the marshaller, if any, that can be used to read/write |
| 1032 |
a Python object with type 'tp'. |
| 1033 |
|
| 1034 |
Parameters |
| 1035 |
---------- |
| 1036 |
tp : type |
| 1037 |
Python object ``type``. |
| 1038 |
|
| 1039 |
Returns |
| 1040 |
------- |
| 1041 |
marshaller |
| 1042 |
The marshaller that can read/write the type to |
| 1043 |
file. ``None`` if no appropriate marshaller is found. |
| 1044 |
|
| 1045 |
See Also |
| 1046 |
-------- |
| 1047 |
hdf5storage.Marshallers.TypeMarshaller.types |
| 1048 |
|
| 1049 |
""" |
| 1050 |
if tp in self._types: |
| 1051 |
return copy.deepcopy(self._types[tp]) |
| 1052 |
else: |
| 1053 |
return None |
| 1054 |
|
| 1055 |
def get_marshaller_for_type_string(self, type_string): |
| 1056 |
""" Gets the appropriate marshaller for a type string. |
| 1057 |
|
| 1058 |
Retrieves the marshaller, if any, that can be used to read/write |
| 1059 |
a Python object with the given type string. |
| 1060 |
|
| 1061 |
Parameters |
| 1062 |
---------- |
| 1063 |
type_string : str |
| 1064 |
Type string for a Python object. |
| 1065 |
|
| 1066 |
Returns |
| 1067 |
------- |
| 1068 |
marshaller |
| 1069 |
The marshaller that can read/write the type to |
| 1070 |
file. ``None`` if no appropriate marshaller is found. |
| 1071 |
|
| 1072 |
See Also |
| 1073 |
-------- |
| 1074 |
hdf5storage.Marshallers.TypeMarshaller.python_type_strings |
| 1075 |
|
| 1076 |
""" |
| 1077 |
if type_string in self._type_strings: |
| 1078 |
return copy.deepcopy(self._type_strings[type_string]) |
| 1079 |
else: |
| 1080 |
return None |
| 1081 |
|
| 1082 |
def get_marshaller_for_matlab_class(self, matlab_class): |
| 1083 |
""" Gets the appropriate marshaller for a MATLAB class string. |
| 1084 |
|
| 1085 |
Retrieves the marshaller, if any, that can be used to read/write |
| 1086 |
a Python object associated with the given MATLAB class string. |
| 1087 |
|
| 1088 |
Parameters |
| 1089 |
---------- |
| 1090 |
matlab_class : str |
| 1091 |
MATLAB class string for a Python object. |
| 1092 |
|
| 1093 |
Returns |
| 1094 |
------- |
| 1095 |
marshaller |
| 1096 |
The marshaller that can read/write the type to |
| 1097 |
file. ``None`` if no appropriate marshaller is found. |
| 1098 |
|
| 1099 |
See Also |
| 1100 |
-------- |
| 1101 |
hdf5storage.Marshallers.TypeMarshaller.python_type_strings |
| 1102 |
|
| 1103 |
""" |
| 1104 |
if matlab_class in self._matlab_classes: |
| 1105 |
return copy.deepcopy(self._matlab_classes[matlab_class]) |
| 1106 |
else: |
| 1107 |
return None |
| 1108 |
|
| 1109 |
|
| 1110 |
def writes(mdict, filename='data.h5', truncate_existing=False, |
| 1111 |
truncate_invalid_matlab=False, options=None, **keywords): |
| 1112 |
""" Writes data into an HDF5 file (high level). |
| 1113 |
|
| 1114 |
High level function to store one or more Python types (data) to |
| 1115 |
specified pathes in an HDF5 file. The paths are specified as POSIX |
| 1116 |
style paths where the directory name is the Group to put it in and |
| 1117 |
the basename is the name to write it to. |
| 1118 |
|
| 1119 |
There are various options that can be used to influence how the data |
| 1120 |
is written. They can be passed as an already constructed ``Options`` |
| 1121 |
into `options` or as additional keywords that will be used to make |
| 1122 |
one by ``options = Options(**keywords)``. |
| 1123 |
|
| 1124 |
Two very important options are ``store_python_metadata`` and |
| 1125 |
``matlab_compatible``, which are ``bool``. The first makes it so |
| 1126 |
that enough metadata (HDF5 Attributes) are written that `data` can |
| 1127 |
be read back accurately without it (or its contents if it is a |
| 1128 |
container type) ending up different types, transposed in the case of |
| 1129 |
numpy arrays, etc. The latter makes it so that the appropriate |
| 1130 |
metadata is written, string and bool and complex types are converted |
| 1131 |
properly, and numpy arrays are transposed; which is needed to make |
| 1132 |
sure that MATLAB can import `data` correctly (the HDF5 header is |
| 1133 |
also set so MATLAB will recognize it). |
| 1134 |
|
| 1135 |
Parameters |
| 1136 |
---------- |
| 1137 |
mdict : dict, dict like |
| 1138 |
The ``dict`` or other dictionary type object of paths |
| 1139 |
and data to write to the file. The paths, the keys, must be |
| 1140 |
POSIX style paths where the directory name is the Group to put |
| 1141 |
it in and the basename is the name to write it to. The values |
| 1142 |
are the data to write. |
| 1143 |
filename : str, optional |
| 1144 |
The name of the HDF5 file to write `data` to. |
| 1145 |
truncate_existing : bool, optional |
| 1146 |
Whether to truncate the file if it already exists before writing |
| 1147 |
to it. |
| 1148 |
truncate_invalid_matlab : bool, optional |
| 1149 |
Whether to truncate a file if matlab_compatibility is being |
| 1150 |
done and the file doesn't have the proper header (userblock in |
| 1151 |
HDF5 terms) setup for MATLAB metadata to be placed. |
| 1152 |
options : Options, optional |
| 1153 |
The options to use when writing. Is mutually exclusive with any |
| 1154 |
additional keyword arguments given (set to ``None`` or don't |
| 1155 |
provide to use them). |
| 1156 |
**keywords : |
| 1157 |
If `options` was not provided or was ``None``, these are used as |
| 1158 |
arguments to make a ``Options``. |
| 1159 |
|
| 1160 |
Raises |
| 1161 |
------ |
| 1162 |
NotImplementedError |
| 1163 |
If writing `data` is not supported. |
| 1164 |
TypeNotMatlabCompatibleError |
| 1165 |
If writing a type not compatible with MATLAB and |
| 1166 |
`options.action_for_matlab_incompatible` is set to ``'error'``. |
| 1167 |
|
| 1168 |
See Also |
| 1169 |
-------- |
| 1170 |
write : Writes just a single piece of data |
| 1171 |
reads |
| 1172 |
read |
| 1173 |
Options |
| 1174 |
lowlevel.write_data : Low level version |
| 1175 |
|
| 1176 |
""" |
| 1177 |
# Pack the different options into an Options class if an Options was |
| 1178 |
# not given. |
| 1179 |
if not isinstance(options, Options): |
| 1180 |
options = Options(**keywords) |
| 1181 |
|
| 1182 |
# Go through mdict, extract the paths and data, and process the |
| 1183 |
# paths. A list of tulpes for each piece of data to write will be |
| 1184 |
# constructed where he first element is the group name, the second |
| 1185 |
# the target name (name of the Dataset/Group holding the data), and |
| 1186 |
# the third element the data to write. |
| 1187 |
towrite = [] |
| 1188 |
for p, v in mdict.items(): |
| 1189 |
# Remove double slashes and a non-root trailing slash. |
| 1190 |
path = posixpath.normpath(p) |
| 1191 |
|
| 1192 |
# Extract the group name and the target name (will be a dataset if |
| 1193 |
# data can be mapped to it, but will end up being made into a group |
| 1194 |
# otherwise. As HDF5 files use posix path, conventions, posixpath |
| 1195 |
# will do everything. |
| 1196 |
groupname = posixpath.dirname(path) |
| 1197 |
targetname = posixpath.basename(path) |
| 1198 |
|
| 1199 |
# If groupname got turned into blank, then it is just root. |
| 1200 |
if groupname == '': |
| 1201 |
groupname = '/' |
| 1202 |
|
| 1203 |
# If targetname got turned blank, then it is the current directory. |
| 1204 |
if targetname == '': |
| 1205 |
targetname = '.' |
| 1206 |
|
| 1207 |
# Pack into towrite. |
| 1208 |
towrite.append((groupname, targetname, v)) |
| 1209 |
|
| 1210 |
# Open/create the hdf5 file but don't write the data yet since the |
| 1211 |
# userblock still needs to be set. This is all wrapped in a try |
| 1212 |
# block, so that the file can be closed if any errors happen (the |
| 1213 |
# error is re-raised). |
| 1214 |
f = None |
| 1215 |
try: |
| 1216 |
|
| 1217 |
# If the file doesn't already exist or the option is set to |
| 1218 |
# truncate it if it does, just open it truncating whatever is |
| 1219 |
# there. Otherwise, open it for read/write access without |
| 1220 |
# truncating. Now, if we are doing matlab compatibility and it |
| 1221 |
# doesn't have a big enough userblock (for metadata for MATLAB |
| 1222 |
# to be able to tell it is a valid .mat file) and the |
| 1223 |
# truncate_invalid_matlab is set, then it needs to be closed and |
| 1224 |
# re-opened with truncation. Whenever we create the file from |
| 1225 |
# scratch, even if matlab compatibility isn't being done, a |
| 1226 |
# sufficiently sized userblock is going to be allocated |
| 1227 |
# (smallest size is 512) for future use (after all, someone |
| 1228 |
# might want to turn it to a .mat file later and need it and it |
| 1229 |
# is only 512 bytes). |
| 1230 |
|
| 1231 |
if truncate_existing or not os.path.isfile(filename): |
| 1232 |
f = h5py.File(filename, mode='w', userblock_size=512) |
| 1233 |
else: |
| 1234 |
f = h5py.File(filename, mode='a') |
| 1235 |
if options.matlab_compatible and truncate_invalid_matlab \ |
| 1236 |
and f.userblock_size < 128: |
| 1237 |
f.close() |
| 1238 |
f = h5py.File(filename, mode='w', userblock_size=512) |
| 1239 |
except: |
| 1240 |
raise |
| 1241 |
finally: |
| 1242 |
# If the hdf5 file was opened at all, get the userblock size and |
| 1243 |
# close it since we need to set the userblock. |
| 1244 |
if isinstance(f, h5py.File): |
| 1245 |
userblock_size = f.userblock_size |
| 1246 |
f.close() |
| 1247 |
else: |
| 1248 |
raise IOError('Unable to create or open file.') |
| 1249 |
|
| 1250 |
# If we are doing MATLAB formatting and there is a sufficiently |
| 1251 |
# large userblock, write the new userblock. The same sort of error |
| 1252 |
# handling is used. |
| 1253 |
if options.matlab_compatible and userblock_size >= 128: |
| 1254 |
# Get the time. |
| 1255 |
now = datetime.datetime.now() |
| 1256 |
|
| 1257 |
# Construct the leading string. The MATLAB one looks like |
| 1258 |
# |
| 1259 |
# s = 'MATLAB 7.3 MAT-file, Platform: GLNXA64, Created on: ' \ |
| 1260 |
# + now.strftime('%a %b %d %H:%M:%S %Y') \ |
| 1261 |
# + ' HDF5 schema 1.00 .' |
| 1262 |
# |
| 1263 |
# Platform is going to be changed to CPython version. The |
| 1264 |
# version is just gotten from sys.version_info, which is a class |
| 1265 |
# for Python >= 2.7, but a tuple before that. |
| 1266 |
|
| 1267 |
v = sys.version_info |
| 1268 |
if sys.hexversion >= 0x02070000: |
| 1269 |
v = {'major': v.major, 'minor': v.minor, 'micro': v.micro} |
| 1270 |
else: |
| 1271 |
v = {'major': v[0], 'minor': v[1], 'micro': v[1]} |
| 1272 |
|
| 1273 |
s = 'MATLAB 7.3 MAT-file, Platform: CPython ' \ |
| 1274 |
+ '{0}.{1}.{2}'.format(v['major'], v['minor'], v['micro']) \ |
| 1275 |
+ ', Created on: {0} {1}'.format( |
| 1276 |
('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[ \ |
| 1277 |
now.weekday()], \ |
| 1278 |
('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', \ |
| 1279 |
'Sep', 'Oct', 'Nov', 'Dec')[now.month - 1]) \ |
| 1280 |
+ now.strftime(' %d %H:%M:%S %Y') \ |
| 1281 |
+ ' HDF5 schema 1.00 .' |
| 1282 |
|
| 1283 |
# Make the bytearray while padding with spaces up to 128-12 |
| 1284 |
# (the minus 12 is there since the last 12 bytes are special. |
| 1285 |
|
| 1286 |
b = bytearray(s + (128-12-len(s))*' ', encoding='utf-8') |
| 1287 |
|
| 1288 |
# Add 8 nulls (0) and the magic number (or something) that |
| 1289 |
# MATLAB uses. Lengths must be gone to to make sure the argument |
| 1290 |
# to fromhex is unicode because Python 2.6 requires it. |
| 1291 |
|
| 1292 |
b.extend(bytearray.fromhex( |
| 1293 |
b'00000000 00000000 0002494D'.decode())) |
| 1294 |
|
| 1295 |
# Now, write it to the beginning of the file. |
| 1296 |
|
| 1297 |
try: |
| 1298 |
fd = open(filename, 'r+b') |
| 1299 |
fd.write(b) |
| 1300 |
except: |
| 1301 |
raise |
| 1302 |
finally: |
| 1303 |
fd.close() |
| 1304 |
|
| 1305 |
# Open the hdf5 file again and write the data, making the Group if |
| 1306 |
# necessary. This is all wrapped in a try block, so that the file |
| 1307 |
# can be closed if any errors happen (the error is re-raised). |
| 1308 |
f = None |
| 1309 |
try: |
| 1310 |
f = h5py.File(filename, mode='a') |
| 1311 |
|
| 1312 |
# Go through each element of towrite and write them. |
| 1313 |
for groupname, targetname, data in towrite: |
| 1314 |
# Need to make sure groupname is a valid group in f and grab its |
| 1315 |
# handle to pass on to the low level function. |
| 1316 |
grp = f.get(groupname) |
| 1317 |
if grp is None: |
| 1318 |
grp = f.require_group(groupname) |
| 1319 |
|
| 1320 |
# Hand off to the low level function. |
| 1321 |
lowlevel.write_data(f, grp, targetname, data, |
| 1322 |
None, options) |
| 1323 |
except: |
| 1324 |
raise |
| 1325 |
finally: |
| 1326 |
if isinstance(f, h5py.File): |
| 1327 |
f.close() |
| 1328 |
|
| 1329 |
|
| 1330 |
def write(data, path='/', filename='data.h5', truncate_existing=False, |
| 1331 |
truncate_invalid_matlab=False, options=None, **keywords): |
| 1332 |
""" Writes one piece of data into an HDF5 file (high level). |
| 1333 |
|
| 1334 |
A wrapper around ``writes`` to write a single piece of data, |
| 1335 |
`data`, to a single location, `path`. |
| 1336 |
|
| 1337 |
High level function to store a Python type (`data`) to a specified |
| 1338 |
path (`path`) in an HDF5 file. The path is specified as a POSIX |
| 1339 |
style path where the directory name is the Group to put it in and |
| 1340 |
the basename is the name to write it to. |
| 1341 |
|
| 1342 |
There are various options that can be used to influence how the data |
| 1343 |
is written. They can be passed as an already constructed ``Options`` |
| 1344 |
into `options` or as additional keywords that will be used to make |
| 1345 |
one by ``options = Options(**keywords)``. |
| 1346 |
|
| 1347 |
Two very important options are ``store_python_metadata`` and |
| 1348 |
``matlab_compatible``, which are ``bool``. The first makes it so |
| 1349 |
that enough metadata (HDF5 Attributes) are written that `data` can |
| 1350 |
be read back accurately without it (or its contents if it is a |
| 1351 |
container type) ending up different types, transposed in the case of |
| 1352 |
numpy arrays, etc. The latter makes it so that the appropriate |
| 1353 |
metadata is written, string and bool and complex types are converted |
| 1354 |
properly, and numpy arrays are transposed; which is needed to make |
| 1355 |
sure that MATLAB can import `data` correctly (the HDF5 header is |
| 1356 |
also set so MATLAB will recognize it). |
| 1357 |
|
| 1358 |
Parameters |
| 1359 |
---------- |
| 1360 |
data : any |
| 1361 |
The data to write. |
| 1362 |
path : str, optional |
| 1363 |
The path to write `data` to. Must be a POSIX style path where |
| 1364 |
the directory name is the Group to put it in and the basename |
| 1365 |
is the name to write it to. |
| 1366 |
filename : str, optional |
| 1367 |
The name of the HDF5 file to write `data` to. |
| 1368 |
truncate_existing : bool, optional |
| 1369 |
Whether to truncate the file if it already exists before writing |
| 1370 |
to it. |
| 1371 |
truncate_invalid_matlab : bool, optional |
| 1372 |
Whether to truncate a file if matlab_compatibility is being |
| 1373 |
done and the file doesn't have the proper header (userblock in |
| 1374 |
HDF5 terms) setup for MATLAB metadata to be placed. |
| 1375 |
options : Options, optional |
| 1376 |
The options to use when writing. Is mutually exclusive with any |
| 1377 |
additional keyword arguments given (set to ``None`` or don't |
| 1378 |
provide to use them). |
| 1379 |
**keywords : |
| 1380 |
If `options` was not provided or was ``None``, these are used as |
| 1381 |
arguments to make a ``Options``. |
| 1382 |
|
| 1383 |
Raises |
| 1384 |
------ |
| 1385 |
NotImplementedError |
| 1386 |
If writing `data` is not supported. |
| 1387 |
TypeNotMatlabCompatibleError |
| 1388 |
If writing a type not compatible with MATLAB and |
| 1389 |
`options.action_for_matlab_incompatible` is set to ``'error'``. |
| 1390 |
|
| 1391 |
See Also |
| 1392 |
-------- |
| 1393 |
writes : Writes more than one piece of data at once |
| 1394 |
reads |
| 1395 |
read |
| 1396 |
Options |
| 1397 |
lowlevel.write_data : Low level version |
| 1398 |
|
| 1399 |
""" |
| 1400 |
writes(mdict={path: data}, filename=filename, |
| 1401 |
truncate_existing=truncate_existing, |
| 1402 |
truncate_invalid_matlab=truncate_invalid_matlab, |
| 1403 |
options=options, **keywords) |
| 1404 |
|
| 1405 |
|
| 1406 |
def reads(paths, filename='data.h5', options=None, **keywords): |
| 1407 |
""" Reads data from an HDF5 file (high level). |
| 1408 |
|
| 1409 |
High level function to read one or more pieces of data from an HDF5 |
| 1410 |
file located at the paths specified in `paths` into Python |
| 1411 |
types. Each path is specified as a POSIX style path where the data |
| 1412 |
to read is located. |
| 1413 |
|
| 1414 |
There are various options that can be used to influence how the data |
| 1415 |
is read. They can be passed as an already constructed ``Options`` |
| 1416 |
into `options` or as additional keywords that will be used to make |
| 1417 |
one by ``options = Options(**keywords)``. |
| 1418 |
|
| 1419 |
Parameters |
| 1420 |
---------- |
| 1421 |
paths : iterable of str |
| 1422 |
An iterable of paths to read data from. Each must be a POSIX |
| 1423 |
style path where the directory name is the Group to put it in |
| 1424 |
and the basename is the name to write it to. |
| 1425 |
filename : str, optional |
| 1426 |
The name of the HDF5 file to read data from. |
| 1427 |
options : Options, optional |
| 1428 |
The options to use when reading. Is mutually exclusive with any |
| 1429 |
additional keyword arguments given (set to ``None`` or don't |
| 1430 |
provide to use them). |
| 1431 |
**keywords : |
| 1432 |
If `options` was not provided or was ``None``, these are used as |
| 1433 |
arguments to make a ``Options``. |
| 1434 |
|
| 1435 |
Returns |
| 1436 |
------- |
| 1437 |
datas : iterable |
| 1438 |
An iterable holding the piece of data for each path in `paths` |
| 1439 |
in the same order. |
| 1440 |
|
| 1441 |
Raises |
| 1442 |
------ |
| 1443 |
CantReadError |
| 1444 |
If reading the data can't be done. |
| 1445 |
|
| 1446 |
See Also |
| 1447 |
-------- |
| 1448 |
read : Reads just a single piece of data |
| 1449 |
writes |
| 1450 |
write |
| 1451 |
Options |
| 1452 |
lowlevel.read_data : Low level version. |
| 1453 |
|
| 1454 |
""" |
| 1455 |
# Pack the different options into an Options class if an Options was |
| 1456 |
# not given. By default, the matlab_compatible option is set to |
| 1457 |
# False. So, if it wasn't passed in the keywords, this needs to be |
| 1458 |
# added to override the default value (True) for a new Options. |
| 1459 |
if not isinstance(options, Options): |
| 1460 |
kw = copy.deepcopy(keywords) |
| 1461 |
if 'matlab_compatible' not in kw: |
| 1462 |
kw['matlab_compatible'] = False |
| 1463 |
options = Options(**kw) |
| 1464 |
|
| 1465 |
# Process the paths and stuff the group names and target names as |
| 1466 |
# tuples into toread. |
| 1467 |
toread = [] |
| 1468 |
for p in paths: |
| 1469 |
# Remove double slashes and a non-root trailing slash. |
| 1470 |
|
| 1471 |
path = posixpath.normpath(p) |
| 1472 |
|
| 1473 |
# Extract the group name and the target name (will be a dataset if |
| 1474 |
# data can be mapped to it, but will end up being made into a group |
| 1475 |
# otherwise. As HDF5 files use posix path, conventions, posixpath |
| 1476 |
# will do everything. |
| 1477 |
groupname = posixpath.dirname(path) |
| 1478 |
targetname = posixpath.basename(path) |
| 1479 |
|
| 1480 |
# If groupname got turned into blank, then it is just root. |
| 1481 |
if groupname == '': |
| 1482 |
groupname = '/' |
| 1483 |
|
| 1484 |
# If targetname got turned blank, then it is the current directory. |
| 1485 |
if targetname == '': |
| 1486 |
targetname = '.' |
| 1487 |
|
| 1488 |
# Pack them into toread |
| 1489 |
toread.append((groupname, targetname)) |
| 1490 |
|
| 1491 |
# Open the hdf5 file and start reading the data. This is all wrapped |
| 1492 |
# in a try block, so that the file can be closed if any errors |
| 1493 |
# happen (the error is re-raised). |
| 1494 |
try: |
| 1495 |
f = None |
| 1496 |
f = h5py.File(filename, mode='r') |
| 1497 |
|
| 1498 |
# Read the data item by item |
| 1499 |
datas = [] |
| 1500 |
for groupname, targetname in toread: |
| 1501 |
# Check that the containing group is in f and is indeed a |
| 1502 |
# group. If it isn't an error needs to be thrown. |
| 1503 |
grp = f.get(groupname) |
| 1504 |
if grp is None or not isinstance(grp, h5py.Group): |
| 1505 |
raise CantReadError('Could not find containing Group ' |
| 1506 |
+ groupname + '.') |
| 1507 |
|
| 1508 |
# Hand off everything to the low level reader. |
| 1509 |
datas.append(lowlevel.read_data(f, grp, |
| 1510 |
targetname, options)) |
| 1511 |
except: |
| 1512 |
raise |
| 1513 |
finally: |
| 1514 |
if f is not None: |
| 1515 |
f.close() |
| 1516 |
|
| 1517 |
return datas |
| 1518 |
|
| 1519 |
|
| 1520 |
def read(path='/', filename='data.h5', |
| 1521 |
options=None, **keywords): |
| 1522 |
""" Reads one piece of data from an HDF5 file (high level). |
| 1523 |
|
| 1524 |
A wrapper around ``reads`` to read a single piece of data at the |
| 1525 |
single location `path`. |
| 1526 |
|
| 1527 |
High level function to read data from an HDF5 file located at `path` |
| 1528 |
into Python types. The path is specified as a POSIX style path where |
| 1529 |
the data to read is located. |
| 1530 |
|
| 1531 |
There are various options that can be used to influence how the data |
| 1532 |
is read. They can be passed as an already constructed ``Options`` |
| 1533 |
into `options` or as additional keywords that will be used to make |
| 1534 |
one by ``options = Options(**keywords)``. |
| 1535 |
|
| 1536 |
Parameters |
| 1537 |
---------- |
| 1538 |
path : str, optional |
| 1539 |
The path to read data from. Must be a POSIX style path where |
| 1540 |
the directory name is the Group to put it in and the basename |
| 1541 |
is the name to write it to. |
| 1542 |
filename : str, optional |
| 1543 |
The name of the HDF5 file to read data from. |
| 1544 |
options : Options, optional |
| 1545 |
The options to use when reading. Is mutually exclusive with any |
| 1546 |
additional keyword arguments given (set to ``None`` or don't |
| 1547 |
provide to use them). |
| 1548 |
**keywords : |
| 1549 |
If `options` was not provided or was ``None``, these are used as |
| 1550 |
arguments to make a ``Options``. |
| 1551 |
|
| 1552 |
Returns |
| 1553 |
------- |
| 1554 |
data : |
| 1555 |
The piece of data at `path`. |
| 1556 |
|
| 1557 |
Raises |
| 1558 |
------ |
| 1559 |
CantReadError |
| 1560 |
If reading the data can't be done. |
| 1561 |
|
| 1562 |
See Also |
| 1563 |
-------- |
| 1564 |
reads : Reads more than one piece of data at once |
| 1565 |
writes |
| 1566 |
write |
| 1567 |
Options |
| 1568 |
lowlevel.read_data : Low level version. |
| 1569 |
|
| 1570 |
""" |
| 1571 |
return reads(paths=(path,), filename=filename, options=options, |
| 1572 |
**keywords)[0] |
| 1573 |
|
| 1574 |
|
| 1575 |
def savemat(file_name, mdict, appendmat=True, format='7.3', |
| 1576 |
oned_as='row', store_python_metadata=True, |
| 1577 |
action_for_matlab_incompatible='error', |
| 1578 |
marshaller_collection=None, truncate_existing=False, |
| 1579 |
truncate_invalid_matlab=False, **keywords): |
| 1580 |
""" Save a dictionary of python types to a MATLAB MAT file. |
| 1581 |
|
| 1582 |
Saves the data provided in the dictionary `mdict` to a MATLAB MAT |
| 1583 |
file. `format` determines which kind/vesion of file to use. The |
| 1584 |
'7.3' version, which is HDF5 based, is handled by this package and |
| 1585 |
all types that this package can write are supported. Versions 4 and |
| 1586 |
5 are not HDF5 based, so everything is dispatched to the SciPy |
| 1587 |
package's ``scipy.io.savemat`` function, which this function is |
| 1588 |
modelled after (arguments not specific to this package have the same |
| 1589 |
names, etc.). |
| 1590 |
|
| 1591 |
Parameters |
| 1592 |
---------- |
| 1593 |
file_name : str or file-like object |
| 1594 |
Name of the MAT file to store in. The '.mat' extension is |
| 1595 |
added on automatically if not present if `appendmat` is set to |
| 1596 |
``True``. An open file-like object can be passed if the writing |
| 1597 |
is being dispatched to SciPy (`format` < 7.3). |
| 1598 |
mdict : dict |
| 1599 |
The dictionary of variables and their contents to store in the |
| 1600 |
file. |
| 1601 |
appendmat : bool, optional |
| 1602 |
Whether to append the '.mat' extension to `file_name` if it |
| 1603 |
doesn't already end in it or not. |
| 1604 |
format : {'4', '5', '7.3'}, optional |
| 1605 |
The MATLAB mat file format to use. The '7.3' format is handled |
| 1606 |
by this package while the '4' and '5' formats are dispatched to |
| 1607 |
SciPy. |
| 1608 |
oned_as : {'row', 'column'}, optional |
| 1609 |
Whether 1D arrays should be turned into row or column vectors. |
| 1610 |
store_python_metadata : bool, optional |
| 1611 |
Whether or not to store Python type information. Doing so allows |
| 1612 |
most types to be read back perfectly. Only applicable if not |
| 1613 |
dispatching to SciPy (`format` >= 7.3). |
| 1614 |
action_for_matlab_incompatible: str, optional |
| 1615 |
The action to perform writing data that is not MATLAB |
| 1616 |
compatible. The actions are to write the data anyways |
| 1617 |
('ignore'), don't write the incompatible data ('discard'), or |
| 1618 |
throw a ``TypeNotMatlabCompatibleError`` exception. |
| 1619 |
marshaller_collection : MarshallerCollection, optional |
| 1620 |
Collection of marshallers to disk to use. Only applicable if |
| 1621 |
not dispatching to SciPy (`format` >= 7.3). |
| 1622 |
truncate_existing : bool, optional |
| 1623 |
Whether to truncate the file if it already exists before writing |
| 1624 |
to it. |
| 1625 |
truncate_invalid_matlab : bool, optional |
| 1626 |
Whether to truncate a file if the file doesn't have the proper |
| 1627 |
header (userblock in HDF5 terms) setup for MATLAB metadata to be |
| 1628 |
placed. |
| 1629 |
**keywords : |
| 1630 |
Additional keywords arguments to be passed onto |
| 1631 |
``scipy.io.savemat`` if dispatching to SciPy (`format` < 7.3). |
| 1632 |
|
| 1633 |
Raises |
| 1634 |
------ |
| 1635 |
ImportError |
| 1636 |
If `format` < 7.3 and the ``scipy`` module can't be found. |
| 1637 |
NotImplementedError |
| 1638 |
If writing a variable in `mdict` is not supported. |
| 1639 |
TypeNotMatlabCompatibleError |
| 1640 |
If writing a type not compatible with MATLAB and |
| 1641 |
`action_for_matlab_incompatible` is set to ``'error'``. |
| 1642 |
|
| 1643 |
Notes |
| 1644 |
----- |
| 1645 |
Writing the same data and then reading it back from disk using the |
| 1646 |
HDF5 based version 7.3 format (the functions in this package) or the |
| 1647 |
older format (SciPy functions) can lead to very different |
| 1648 |
results. Each package supports a different set of data types and |
| 1649 |
converts them to and from the same MATLAB types differently. |
| 1650 |
|
| 1651 |
See Also |
| 1652 |
-------- |
| 1653 |
loadmat : Equivelent function to do reading. |
| 1654 |
scipy.io.savemat : SciPy function this one models after and |
| 1655 |
dispatches to. |
| 1656 |
Options |
| 1657 |
writes : Function used to do the actual writing. |
| 1658 |
|
| 1659 |
""" |
| 1660 |
# If format is a number less than 7.3, the call needs to be |
| 1661 |
# dispatched to the scipy version, if it is available, with all the |
| 1662 |
# relevant and extra keywords options provided. |
| 1663 |
if float(format) < 7.3: |
| 1664 |
import scipy.io |
| 1665 |
scipy.io.savemat(file_name, mdict, appendmat=appendmat, |
| 1666 |
format=format, oned_as=oned_as, **keywords) |
| 1667 |
return |
| 1668 |
|
| 1669 |
# Append .mat if it isn't on the end of the file name and we are |
| 1670 |
# supposed to. |
| 1671 |
if appendmat and not file_name.endswith('.mat'): |
| 1672 |
file_name = file_name + '.mat' |
| 1673 |
|
| 1674 |
# Make the options with matlab compatibility forced. |
| 1675 |
options = Options(store_python_metadata=store_python_metadata, \ |
| 1676 |
matlab_compatible=True, oned_as=oned_as, \ |
| 1677 |
action_for_matlab_incompatible=action_for_matlab_incompatible, \ |
| 1678 |
marshaller_collection=marshaller_collection) |
| 1679 |
|
| 1680 |
# Write the variables in the dictionary to file. |
| 1681 |
writes(mdict=mdict, filename=file_name, |
| 1682 |
truncate_existing=truncate_existing, |
| 1683 |
truncate_invalid_matlab=truncate_invalid_matlab, |
| 1684 |
options=options) |
| 1685 |
|
| 1686 |
|
| 1687 |
def loadmat(file_name, mdict=None, appendmat=True, |
| 1688 |
variable_names=None, |
| 1689 |
marshaller_collection=None, **keywords): |
| 1690 |
""" Loads data to a MATLAB MAT file. |
| 1691 |
|
| 1692 |
Reads data from the specified variables (or all) in a MATLAB MAT |
| 1693 |
file. There are many different formats of MAT files. This package |
| 1694 |
can only handle the HDF5 based ones (the version 7.3 and later). |
| 1695 |
As SciPy's ``scipy.io.loadmat`` function can handle the earlier |
| 1696 |
formats, if this function cannot read the file, it will dispatch it |
| 1697 |
onto the scipy function with all the calling arguments it uses |
| 1698 |
passed on. This function is modelled after the SciPy one (arguments |
| 1699 |
not specific to this package have the same names, etc.). |
| 1700 |
|
| 1701 |
Warning |
| 1702 |
------- |
| 1703 |
Variables in `variable_names` that are missing from the file do not |
| 1704 |
cause an exception and will just be missing from the output. |
| 1705 |
|
| 1706 |
Parameters |
| 1707 |
---------- |
| 1708 |
file_name : str |
| 1709 |
Name of the MAT file to read from. The '.mat' extension is |
| 1710 |
added on automatically if not present if `appendmat` is set to |
| 1711 |
``True``. |
| 1712 |
mdict : dict, optional |
| 1713 |
The dictionary to insert read variables into |
| 1714 |
appendmat : bool, optional |
| 1715 |
Whether to append the '.mat' extension to `file_name` if it |
| 1716 |
doesn't already end in it or not. |
| 1717 |
variable_names: None or sequence, optional |
| 1718 |
The variable names to read from the file. ``None`` selects all. |
| 1719 |
marshaller_collection : MarshallerCollection, optional |
| 1720 |
Collection of marshallers from disk to use. Only applicable if |
| 1721 |
not dispatching to SciPy (version 7.3 and newer files). |
| 1722 |
**keywords : |
| 1723 |
Additional keywords arguments to be passed onto |
| 1724 |
``scipy.io.loadmat`` if dispatching to SciPy if the file is not |
| 1725 |
a version 7.3 or later format. |
| 1726 |
|
| 1727 |
Returns |
| 1728 |
------- |
| 1729 |
dict |
| 1730 |
Dictionary of all the variables read from the MAT file (name |
| 1731 |
as the key, and content as the value). If a variable was missing |
| 1732 |
from the file, it will not be present here. |
| 1733 |
|
| 1734 |
Raises |
| 1735 |
------ |
| 1736 |
ImportError |
| 1737 |
If it is not a version 7.3 .mat file and the ``scipy`` module |
| 1738 |
can't be found when dispatching to SciPy. |
| 1739 |
CantReadError |
| 1740 |
If reading the data can't be done. |
| 1741 |
|
| 1742 |
Notes |
| 1743 |
----- |
| 1744 |
Writing the same data and then reading it back from disk using the |
| 1745 |
HDF5 based version 7.3 format (the functions in this package) or the |
| 1746 |
older format (SciPy functions) can lead to very different |
| 1747 |
results. Each package supports a different set of data types and |
| 1748 |
converts them to and from the same MATLAB types differently. |
| 1749 |
|
| 1750 |
See Also |
| 1751 |
-------- |
| 1752 |
savemat : Equivalent function to do writing. |
| 1753 |
scipy.io.loadmat : SciPy function this one models after and |
| 1754 |
dispatches to. |
| 1755 |
Options |
| 1756 |
reads : Function used to do the actual reading. |
| 1757 |
|
| 1758 |
""" |
| 1759 |
# Will first assume that it is the HDF5 based 7.3 format. If an |
| 1760 |
# OSError occurs, then it wasn't an HDF5 file and the scipy function |
| 1761 |
# can be tried instead. |
| 1762 |
try: |
| 1763 |
# Make the options with the given marshallers. |
| 1764 |
options = Options(marshaller_collection=marshaller_collection) |
| 1765 |
|
| 1766 |
# Append .mat if it isn't on the end of the file name and we are |
| 1767 |
# supposed to. |
| 1768 |
if appendmat and not file_name.endswith('.mat'): |
| 1769 |
filename = file_name + '.mat' |
| 1770 |
else: |
| 1771 |
filename = file_name |
| 1772 |
|
| 1773 |
# Read everything if we were instructed. |
| 1774 |
|
| 1775 |
if variable_names is None: |
| 1776 |
data = dict() |
| 1777 |
with h5py.File(filename, mode='r') as f: |
| 1778 |
for k in f: |
| 1779 |
# Read if not group_for_references. Data that |
| 1780 |
# produces errors when read is dicarded (the OSError |
| 1781 |
# that would happen if this is not an HDF5 file |
| 1782 |
# would already have happened when opening the |
| 1783 |
# file). |
| 1784 |
if f[k].name != options.group_for_references: |
| 1785 |
try: |
| 1786 |
data[k] = lowlevel.read_data(f, f, k, |
| 1787 |
options) |
| 1788 |
except: |
| 1789 |
pass |
| 1790 |
|
| 1791 |
else: |
| 1792 |
# Extract the desired fields one by one, catching any errors |
| 1793 |
# for missing variables (so we don't fall back to |
| 1794 |
# scipy.io.loadmat). |
| 1795 |
data = dict() |
| 1796 |
with h5py.File(filename, mode='r') as f: |
| 1797 |
for k in variable_names: |
| 1798 |
try: |
| 1799 |
data[k] = lowlevel.read_data(f, f, k, options) |
| 1800 |
except: |
| 1801 |
pass |
| 1802 |
|
| 1803 |
# Read all the variables, stuff them into mdict, and return it. |
| 1804 |
if mdict is None: |
| 1805 |
mdict = dict() |
| 1806 |
for k, v in data.items(): |
| 1807 |
mdict[k] = v |
| 1808 |
return mdict |
| 1809 |
except OSError: |
| 1810 |
import scipy.io |
| 1811 |
return scipy.io.loadmat(file_name, mdict, appendmat=appendmat, |
| 1812 |
variable_names=variable_names, |
| 1813 |
**keywords) |