attrs.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. # This file is part of h5py, a Python interface to the HDF5 library.
  2. #
  3. # http://www.h5py.org
  4. #
  5. # Copyright 2008-2013 Andrew Collette and contributors
  6. #
  7. # License: Standard 3-clause BSD; see "license.txt" for full license terms
  8. # and contributor agreement.
  9. """
  10. Implements high-level operations for attributes.
  11. Provides the AttributeManager class, available on high-level objects
  12. as <obj>.attrs.
  13. """
  14. import numpy
  15. import uuid
  16. from .. import h5, h5s, h5t, h5a, h5p
  17. from . import base
  18. from .base import phil, with_phil, Empty, is_empty_dataspace, product
  19. from .datatype import Datatype
  20. class AttributeManager(base.MutableMappingHDF5, base.CommonStateObject):
  21. """
  22. Allows dictionary-style access to an HDF5 object's attributes.
  23. These are created exclusively by the library and are available as
  24. a Python attribute at <object>.attrs
  25. Like Group objects, attributes provide a minimal dictionary-
  26. style interface. Anything which can be reasonably converted to a
  27. Numpy array or Numpy scalar can be stored.
  28. Attributes are automatically created on assignment with the
  29. syntax <obj>.attrs[name] = value, with the HDF5 type automatically
  30. deduced from the value. Existing attributes are overwritten.
  31. To modify an existing attribute while preserving its type, use the
  32. method modify(). To specify an attribute of a particular type and
  33. shape, use create().
  34. """
  35. def __init__(self, parent):
  36. """ Private constructor.
  37. """
  38. self._id = parent.id
  39. @with_phil
  40. def __getitem__(self, name):
  41. """ Read the value of an attribute.
  42. """
  43. attr = h5a.open(self._id, self._e(name))
  44. if is_empty_dataspace(attr):
  45. return Empty(attr.dtype)
  46. dtype = attr.dtype
  47. shape = attr.shape
  48. # Do this first, as we'll be fiddling with the dtype for top-level
  49. # array types
  50. htype = h5t.py_create(dtype)
  51. # NumPy doesn't support top-level array types, so we have to "fake"
  52. # the correct type and shape for the array. For example, consider
  53. # attr.shape == (5,) and attr.dtype == '(3,)f'. Then:
  54. if dtype.subdtype is not None:
  55. subdtype, subshape = dtype.subdtype
  56. shape = attr.shape + subshape # (5, 3)
  57. dtype = subdtype # 'f'
  58. arr = numpy.ndarray(shape, dtype=dtype, order='C')
  59. attr.read(arr, mtype=htype)
  60. string_info = h5t.check_string_dtype(dtype)
  61. if string_info and (string_info.length is None):
  62. # Vlen strings: convert bytes to Python str
  63. arr = numpy.array([
  64. b.decode('utf-8', 'surrogateescape') for b in arr.flat
  65. ], dtype=dtype).reshape(arr.shape)
  66. if len(arr.shape) == 0:
  67. return arr[()]
  68. return arr
  69. def get_id(self, name):
  70. """Get a low-level AttrID object for the named attribute.
  71. """
  72. return h5a.open(self._id, self._e(name))
  73. @with_phil
  74. def __setitem__(self, name, value):
  75. """ Set a new attribute, overwriting any existing attribute.
  76. The type and shape of the attribute are determined from the data. To
  77. use a specific type or shape, or to preserve the type of an attribute,
  78. use the methods create() and modify().
  79. """
  80. self.create(name, data=value)
  81. @with_phil
  82. def __delitem__(self, name):
  83. """ Delete an attribute (which must already exist). """
  84. h5a.delete(self._id, self._e(name))
  85. def create(self, name, data, shape=None, dtype=None):
  86. """ Create a new attribute, overwriting any existing attribute.
  87. name
  88. Name of the new attribute (required)
  89. data
  90. An array to initialize the attribute (required)
  91. shape
  92. Shape of the attribute. Overrides data.shape if both are
  93. given, in which case the total number of points must be unchanged.
  94. dtype
  95. Data type of the attribute. Overrides data.dtype if both
  96. are given.
  97. """
  98. with phil:
  99. # First, make sure we have a NumPy array. We leave the data type
  100. # conversion for HDF5 to perform.
  101. if not isinstance(data, Empty):
  102. data = base.array_for_new_object(data, specified_dtype=dtype)
  103. if shape is None:
  104. shape = data.shape
  105. elif isinstance(shape, int):
  106. shape = (shape,)
  107. use_htype = None # If a committed type is given, we must use it
  108. # in the call to h5a.create.
  109. if isinstance(dtype, Datatype):
  110. use_htype = dtype.id
  111. dtype = dtype.dtype
  112. elif dtype is None:
  113. dtype = data.dtype
  114. else:
  115. dtype = numpy.dtype(dtype) # In case a string, e.g. 'i8' is passed
  116. original_dtype = dtype # We'll need this for top-level array types
  117. # Where a top-level array type is requested, we have to do some
  118. # fiddling around to present the data as a smaller array of
  119. # subarrays.
  120. if dtype.subdtype is not None:
  121. subdtype, subshape = dtype.subdtype
  122. # Make sure the subshape matches the last N axes' sizes.
  123. if shape[-len(subshape):] != subshape:
  124. raise ValueError("Array dtype shape %s is incompatible with data shape %s" % (subshape, shape))
  125. # New "advertised" shape and dtype
  126. shape = shape[0:len(shape)-len(subshape)]
  127. dtype = subdtype
  128. # Not an array type; make sure to check the number of elements
  129. # is compatible, and reshape if needed.
  130. else:
  131. if shape is not None and numpy.product(shape, dtype=numpy.ulonglong) != numpy.product(data.shape, dtype=numpy.ulonglong):
  132. raise ValueError("Shape of new attribute conflicts with shape of data")
  133. if shape != data.shape:
  134. data = data.reshape(shape)
  135. # We need this to handle special string types.
  136. if not isinstance(data, Empty):
  137. data = numpy.asarray(data, dtype=dtype)
  138. # Make HDF5 datatype and dataspace for the H5A calls
  139. if use_htype is None:
  140. htype = h5t.py_create(original_dtype, logical=True)
  141. htype2 = h5t.py_create(original_dtype) # Must be bit-for-bit representation rather than logical
  142. else:
  143. htype = use_htype
  144. htype2 = None
  145. if isinstance(data, Empty):
  146. space = h5s.create(h5s.NULL)
  147. else:
  148. space = h5s.create_simple(shape)
  149. # This mess exists because you can't overwrite attributes in HDF5.
  150. # So we write to a temporary attribute first, and then rename.
  151. tempname = uuid.uuid4().hex
  152. attr = h5a.create(self._id, self._e(tempname), htype, space)
  153. try:
  154. if not isinstance(data, Empty):
  155. attr.write(data, mtype=htype2)
  156. except:
  157. attr.close()
  158. h5a.delete(self._id, self._e(tempname))
  159. raise
  160. else:
  161. try:
  162. # No atomic rename in HDF5 :(
  163. if h5a.exists(self._id, self._e(name)):
  164. h5a.delete(self._id, self._e(name))
  165. h5a.rename(self._id, self._e(tempname), self._e(name))
  166. except:
  167. attr.close()
  168. h5a.delete(self._id, self._e(tempname))
  169. raise
  170. finally:
  171. attr.close()
  172. def modify(self, name, value):
  173. """ Change the value of an attribute while preserving its type.
  174. Differs from __setitem__ in that if the attribute already exists, its
  175. type is preserved. This can be very useful for interacting with
  176. externally generated files.
  177. If the attribute doesn't exist, it will be automatically created.
  178. """
  179. with phil:
  180. if not name in self:
  181. self[name] = value
  182. else:
  183. attr = h5a.open(self._id, self._e(name))
  184. if is_empty_dataspace(attr):
  185. raise OSError("Empty attributes can't be modified")
  186. # If the input data is already an array, let HDF5 do the conversion.
  187. # If it's a list or similar, don't make numpy guess a dtype for it.
  188. dt = None if isinstance(value, numpy.ndarray) else attr.dtype
  189. value = numpy.asarray(value, order='C', dtype=dt)
  190. # Allow the case of () <-> (1,)
  191. if (value.shape != attr.shape) and not \
  192. (value.size == 1 and product(attr.shape) == 1):
  193. raise TypeError("Shape of data is incompatible with existing attribute")
  194. attr.write(value)
  195. @with_phil
  196. def __len__(self):
  197. """ Number of attributes attached to the object. """
  198. # I expect we will not have more than 2**32 attributes
  199. return h5a.get_num_attrs(self._id)
  200. def __iter__(self):
  201. """ Iterate over the names of attributes. """
  202. with phil:
  203. attrlist = []
  204. def iter_cb(name, *args):
  205. """ Callback to gather attribute names """
  206. attrlist.append(self._d(name))
  207. cpl = self._id.get_create_plist()
  208. crt_order = cpl.get_attr_creation_order()
  209. cpl.close()
  210. if crt_order & h5p.CRT_ORDER_TRACKED:
  211. idx_type = h5.INDEX_CRT_ORDER
  212. else:
  213. idx_type = h5.INDEX_NAME
  214. h5a.iterate(self._id, iter_cb, index_type=idx_type)
  215. for name in attrlist:
  216. yield name
  217. @with_phil
  218. def __contains__(self, name):
  219. """ Determine if an attribute exists, by name. """
  220. return h5a.exists(self._id, self._e(name))
  221. @with_phil
  222. def __repr__(self):
  223. if not self._id:
  224. return "<Attributes of closed HDF5 object>"
  225. return "<Attributes of HDF5 object at %s>" % id(self._id)