files.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 support for HDF5 file objects.
  11. """
  12. import sys
  13. import os
  14. from warnings import warn
  15. from .compat import filename_decode, filename_encode
  16. from .base import phil, with_phil
  17. from .group import Group
  18. from .. import h5, h5f, h5p, h5i, h5fd, _objects
  19. from .. import version
  20. mpi = h5.get_config().mpi
  21. ros3 = h5.get_config().ros3
  22. hdf5_version = version.hdf5_version_tuple[0:3]
  23. swmr_support = False
  24. if hdf5_version >= h5.get_config().swmr_min_hdf5_version:
  25. swmr_support = True
  26. libver_dict = {'earliest': h5f.LIBVER_EARLIEST, 'latest': h5f.LIBVER_LATEST}
  27. libver_dict_r = dict((y, x) for x, y in libver_dict.items())
  28. if hdf5_version >= (1, 10, 2):
  29. libver_dict.update({'v108': h5f.LIBVER_V18, 'v110': h5f.LIBVER_V110})
  30. libver_dict_r.update({h5f.LIBVER_V18: 'v108', h5f.LIBVER_V110: 'v110'})
  31. if hdf5_version >= (1, 11, 4):
  32. libver_dict.update({'v112': h5f.LIBVER_V112})
  33. libver_dict_r.update({h5f.LIBVER_V112: 'v112'})
  34. if hdf5_version >= (1, 13, 0):
  35. libver_dict.update({'v114': h5f.LIBVER_V114})
  36. libver_dict_r.update({h5f.LIBVER_V114: 'v114'})
  37. def _set_fapl_mpio(plist, **kwargs):
  38. """Set file access property list for mpio driver"""
  39. if not mpi:
  40. raise ValueError("h5py was built without MPI support, can't use mpio driver")
  41. import mpi4py.MPI
  42. kwargs.setdefault('info', mpi4py.MPI.Info())
  43. plist.set_fapl_mpio(**kwargs)
  44. def _set_fapl_fileobj(plist, **kwargs):
  45. """Set the Python file object driver in a file access property list"""
  46. plist.set_fileobj_driver(h5fd.fileobj_driver, kwargs.get('fileobj'))
  47. _drivers = {
  48. 'sec2': lambda plist, **kwargs: plist.set_fapl_sec2(**kwargs),
  49. 'stdio': lambda plist, **kwargs: plist.set_fapl_stdio(**kwargs),
  50. 'core': lambda plist, **kwargs: plist.set_fapl_core(**kwargs),
  51. 'family': lambda plist, **kwargs: plist.set_fapl_family(
  52. memb_fapl=plist.copy(),
  53. **kwargs
  54. ),
  55. 'mpio': _set_fapl_mpio,
  56. 'fileobj': _set_fapl_fileobj,
  57. 'split': lambda plist, **kwargs: plist.set_fapl_split(**kwargs),
  58. }
  59. if ros3:
  60. _drivers['ros3'] = lambda plist, **kwargs: plist.set_fapl_ros3(**kwargs)
  61. def register_driver(name, set_fapl):
  62. """Register a custom driver.
  63. Parameters
  64. ----------
  65. name : str
  66. The name of the driver.
  67. set_fapl : callable[PropFAID, **kwargs] -> NoneType
  68. The function to set the fapl to use your custom driver.
  69. """
  70. _drivers[name] = set_fapl
  71. def unregister_driver(name):
  72. """Unregister a custom driver.
  73. Parameters
  74. ----------
  75. name : str
  76. The name of the driver.
  77. """
  78. del _drivers[name]
  79. def registered_drivers():
  80. """Return a frozenset of the names of all of the registered drivers.
  81. """
  82. return frozenset(_drivers)
  83. def make_fapl(driver, libver, rdcc_nslots, rdcc_nbytes, rdcc_w0, **kwds):
  84. """ Set up a file access property list """
  85. plist = h5p.create(h5p.FILE_ACCESS)
  86. if libver is not None:
  87. if libver in libver_dict:
  88. low = libver_dict[libver]
  89. high = h5f.LIBVER_LATEST
  90. else:
  91. low, high = (libver_dict[x] for x in libver)
  92. else:
  93. # we default to earliest
  94. low, high = h5f.LIBVER_EARLIEST, h5f.LIBVER_LATEST
  95. plist.set_libver_bounds(low, high)
  96. cache_settings = list(plist.get_cache())
  97. if rdcc_nslots is not None:
  98. cache_settings[1] = rdcc_nslots
  99. if rdcc_nbytes is not None:
  100. cache_settings[2] = rdcc_nbytes
  101. if rdcc_w0 is not None:
  102. cache_settings[3] = rdcc_w0
  103. plist.set_cache(*cache_settings)
  104. if driver is None or (driver == 'windows' and sys.platform == 'win32'):
  105. # Prevent swallowing unused key arguments
  106. if kwds:
  107. msg = "'{key}' is an invalid keyword argument for this function" \
  108. .format(key=next(iter(kwds)))
  109. raise TypeError(msg)
  110. return plist
  111. try:
  112. set_fapl = _drivers[driver]
  113. except KeyError:
  114. raise ValueError('Unknown driver type "%s"' % driver)
  115. else:
  116. set_fapl(plist, **kwds)
  117. return plist
  118. def make_fcpl(track_order=False, fs_strategy=None, fs_persist=False, fs_threshold=1):
  119. """ Set up a file creation property list """
  120. if track_order or fs_strategy:
  121. plist = h5p.create(h5p.FILE_CREATE)
  122. if track_order:
  123. plist.set_link_creation_order(
  124. h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED)
  125. plist.set_attr_creation_order(
  126. h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED)
  127. if fs_strategy:
  128. strategies = {
  129. 'fsm': h5f.FSPACE_STRATEGY_FSM_AGGR,
  130. 'page': h5f.FSPACE_STRATEGY_PAGE,
  131. 'aggregate': h5f.FSPACE_STRATEGY_AGGR,
  132. 'none': h5f.FSPACE_STRATEGY_NONE
  133. }
  134. fs_strat_num = strategies.get(fs_strategy, -1)
  135. if fs_strat_num == -1:
  136. raise ValueError("Invalid file space strategy type")
  137. plist.set_file_space_strategy(fs_strat_num, fs_persist, fs_threshold)
  138. else:
  139. plist = None
  140. return plist
  141. def make_fid(name, mode, userblock_size, fapl, fcpl=None, swmr=False):
  142. """ Get a new FileID by opening or creating a file.
  143. Also validates mode argument."""
  144. if userblock_size is not None:
  145. if mode in ('r', 'r+'):
  146. raise ValueError("User block may only be specified "
  147. "when creating a file")
  148. try:
  149. userblock_size = int(userblock_size)
  150. except (TypeError, ValueError):
  151. raise ValueError("User block size must be an integer")
  152. if fcpl is None:
  153. fcpl = h5p.create(h5p.FILE_CREATE)
  154. fcpl.set_userblock(userblock_size)
  155. if mode == 'r':
  156. flags = h5f.ACC_RDONLY
  157. if swmr and swmr_support:
  158. flags |= h5f.ACC_SWMR_READ
  159. fid = h5f.open(name, flags, fapl=fapl)
  160. elif mode == 'r+':
  161. fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl)
  162. elif mode in ['w-', 'x']:
  163. fid = h5f.create(name, h5f.ACC_EXCL, fapl=fapl, fcpl=fcpl)
  164. elif mode == 'w':
  165. fid = h5f.create(name, h5f.ACC_TRUNC, fapl=fapl, fcpl=fcpl)
  166. elif mode == 'a':
  167. # Open in append mode (read/write).
  168. # If that fails, create a new file only if it won't clobber an
  169. # existing one (ACC_EXCL)
  170. try:
  171. fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl)
  172. except FileNotFoundError:
  173. fid = h5f.create(name, h5f.ACC_EXCL, fapl=fapl, fcpl=fcpl)
  174. else:
  175. raise ValueError("Invalid mode; must be one of r, r+, w, w-, x, a")
  176. try:
  177. if userblock_size is not None:
  178. existing_fcpl = fid.get_create_plist()
  179. if existing_fcpl.get_userblock() != userblock_size:
  180. raise ValueError("Requested userblock size (%d) does not match that of existing file (%d)" % (userblock_size, existing_fcpl.get_userblock()))
  181. except:
  182. fid.close()
  183. raise
  184. return fid
  185. class File(Group):
  186. """
  187. Represents an HDF5 file.
  188. """
  189. @property
  190. def attrs(self):
  191. """ Attributes attached to this object """
  192. # hdf5 complains that a file identifier is an invalid location for an
  193. # attribute. Instead of self, pass the root group to AttributeManager:
  194. from . import attrs
  195. with phil:
  196. return attrs.AttributeManager(self['/'])
  197. @property
  198. @with_phil
  199. def filename(self):
  200. """File name on disk"""
  201. return filename_decode(h5f.get_name(self.id))
  202. @property
  203. @with_phil
  204. def driver(self):
  205. """Low-level HDF5 file driver used to open file"""
  206. drivers = {h5fd.SEC2: 'sec2',
  207. h5fd.STDIO: 'stdio',
  208. h5fd.CORE: 'core',
  209. h5fd.FAMILY: 'family',
  210. h5fd.WINDOWS: 'windows',
  211. h5fd.MPIO: 'mpio',
  212. h5fd.MPIPOSIX: 'mpiposix',
  213. h5fd.fileobj_driver: 'fileobj'}
  214. if ros3:
  215. drivers[h5fd.ROS3D] = 'ros3'
  216. return drivers.get(self.id.get_access_plist().get_driver(), 'unknown')
  217. @property
  218. @with_phil
  219. def mode(self):
  220. """ Python mode used to open file """
  221. write_intent = h5f.ACC_RDWR
  222. if swmr_support:
  223. write_intent |= h5f.ACC_SWMR_WRITE
  224. return 'r+' if self.id.get_intent() & write_intent else 'r'
  225. @property
  226. @with_phil
  227. def libver(self):
  228. """File format version bounds (2-tuple: low, high)"""
  229. bounds = self.id.get_access_plist().get_libver_bounds()
  230. return tuple(libver_dict_r[x] for x in bounds)
  231. @property
  232. @with_phil
  233. def userblock_size(self):
  234. """ User block size (in bytes) """
  235. fcpl = self.id.get_create_plist()
  236. return fcpl.get_userblock()
  237. if mpi and hdf5_version >= (1, 8, 9):
  238. @property
  239. @with_phil
  240. def atomic(self):
  241. """ Set/get MPI-IO atomic mode
  242. """
  243. return self.id.get_mpi_atomicity()
  244. @atomic.setter
  245. @with_phil
  246. def atomic(self, value):
  247. # pylint: disable=missing-docstring
  248. self.id.set_mpi_atomicity(value)
  249. @property
  250. @with_phil
  251. def swmr_mode(self):
  252. """ Controls single-writer multiple-reader mode """
  253. return swmr_support and bool(self.id.get_intent() & (h5f.ACC_SWMR_READ | h5f.ACC_SWMR_WRITE))
  254. @swmr_mode.setter
  255. @with_phil
  256. def swmr_mode(self, value):
  257. # pylint: disable=missing-docstring
  258. if swmr_support:
  259. if value:
  260. self.id.start_swmr_write()
  261. else:
  262. raise ValueError("It is not possible to forcibly switch SWMR mode off.")
  263. else:
  264. raise RuntimeError('SWMR support is not available in HDF5 version {}.{}.{}.'.format(*hdf5_version))
  265. def __init__(self, name, mode='r', driver=None,
  266. libver=None, userblock_size=None, swmr=False,
  267. rdcc_nslots=None, rdcc_nbytes=None, rdcc_w0=None,
  268. track_order=None, fs_strategy=None, fs_persist=False, fs_threshold=1,
  269. **kwds):
  270. """Create a new file object.
  271. See the h5py user guide for a detailed explanation of the options.
  272. name
  273. Name of the file on disk, or file-like object. Note: for files
  274. created with the 'core' driver, HDF5 still requires this be
  275. non-empty.
  276. mode
  277. r Readonly, file must exist (default)
  278. r+ Read/write, file must exist
  279. w Create file, truncate if exists
  280. w- or x Create file, fail if exists
  281. a Read/write if exists, create otherwise
  282. driver
  283. Name of the driver to use. Legal values are None (default,
  284. recommended), 'core', 'sec2', 'stdio', 'mpio', 'ros3'.
  285. libver
  286. Library version bounds. Supported values: 'earliest', 'v108',
  287. 'v110', 'v112' and 'latest'. The 'v108', 'v110' and 'v112'
  288. options can only be specified with the HDF5 1.10.2 library or later.
  289. userblock_size
  290. Desired size of user block. Only allowed when creating a new
  291. file (mode w, w- or x).
  292. swmr
  293. Open the file in SWMR read mode. Only used when mode = 'r'.
  294. rdcc_nbytes
  295. Total size of the raw data chunk cache in bytes. The default size
  296. is 1024**2 (1 MB) per dataset.
  297. rdcc_w0
  298. The chunk preemption policy for all datasets. This must be
  299. between 0 and 1 inclusive and indicates the weighting according to
  300. which chunks which have been fully read or written are penalized
  301. when determining which chunks to flush from cache. A value of 0
  302. means fully read or written chunks are treated no differently than
  303. other chunks (the preemption is strictly LRU) while a value of 1
  304. means fully read or written chunks are always preempted before
  305. other chunks. If your application only reads or writes data once,
  306. this can be safely set to 1. Otherwise, this should be set lower
  307. depending on how often you re-read or re-write the same data. The
  308. default value is 0.75.
  309. rdcc_nslots
  310. The number of chunk slots in the raw data chunk cache for this
  311. file. Increasing this value reduces the number of cache collisions,
  312. but slightly increases the memory used. Due to the hashing
  313. strategy, this value should ideally be a prime number. As a rule of
  314. thumb, this value should be at least 10 times the number of chunks
  315. that can fit in rdcc_nbytes bytes. For maximum performance, this
  316. value should be set approximately 100 times that number of
  317. chunks. The default value is 521.
  318. track_order
  319. Track dataset/group/attribute creation order under root group
  320. if True. If None use global default h5.get_config().track_order.
  321. fs_strategy
  322. The file space handling strategy to be used. Only allowed when
  323. creating a new file (mode w, w- or x). Defined as:
  324. "fsm" FSM, Aggregators, VFD
  325. "page" Paged FSM, VFD
  326. "aggregate" Aggregators, VFD
  327. "none" VFD
  328. If None use HDF5 defaults.
  329. fs_persist
  330. A boolean value to indicate whether free space should be persistent
  331. or not. Only allowed when creating a new file. The default value
  332. is False.
  333. fs_threshold
  334. The smallest free-space section size that the free space manager
  335. will track. Only allowed when creating a new file. The default
  336. value is 1.
  337. Additional keywords
  338. Passed on to the selected file driver.
  339. """
  340. if fs_strategy and hdf5_version < (1, 10, 1):
  341. raise ValueError("HDF version 1.10.1 or greater required for file space strategy support.")
  342. if swmr and not swmr_support:
  343. raise ValueError("The SWMR feature is not available in this version of the HDF5 library")
  344. if driver == 'ros3' and not ros3:
  345. raise ValueError(
  346. "h5py was built without ROS3 support, can't use ros3 driver")
  347. if isinstance(name, _objects.ObjectID):
  348. if fs_strategy:
  349. raise ValueError("Unable to set file space strategy of an existing file")
  350. with phil:
  351. fid = h5i.get_file_id(name)
  352. else:
  353. if hasattr(name, 'read') and hasattr(name, 'seek'):
  354. if driver not in (None, 'fileobj'):
  355. raise ValueError("Driver must be 'fileobj' for file-like object if specified.")
  356. driver = 'fileobj'
  357. if kwds.get('fileobj', name) != name:
  358. raise ValueError("Invalid value of 'fileobj' argument; "
  359. "must equal to file-like object if specified.")
  360. kwds.update(fileobj=name)
  361. name = repr(name).encode('ASCII', 'replace')
  362. else:
  363. name = filename_encode(name)
  364. if track_order is None:
  365. track_order = h5.get_config().track_order
  366. if fs_strategy and mode not in ('w', 'w-', 'x'):
  367. raise ValueError("Unable to set file space strategy of an existing file")
  368. if swmr and mode != 'r':
  369. warn(
  370. "swmr=True only affects read ('r') mode. For swmr write "
  371. "mode, set f.swmr_mode = True after opening the file.",
  372. stacklevel=2,
  373. )
  374. with phil:
  375. fapl = make_fapl(driver, libver, rdcc_nslots, rdcc_nbytes, rdcc_w0, **kwds)
  376. fid = make_fid(name, mode, userblock_size,
  377. fapl, fcpl=make_fcpl(track_order=track_order, fs_strategy=fs_strategy,
  378. fs_persist=fs_persist, fs_threshold=fs_threshold),
  379. swmr=swmr)
  380. if isinstance(libver, tuple):
  381. self._libver = libver
  382. else:
  383. self._libver = (libver, 'latest')
  384. super(File, self).__init__(fid)
  385. def close(self):
  386. """ Close the file. All open objects become invalid """
  387. with phil:
  388. # Check that the file is still open, otherwise skip
  389. if self.id.valid:
  390. # We have to explicitly murder all open objects related to the file
  391. # Close file-resident objects first, then the files.
  392. # Otherwise we get errors in MPI mode.
  393. self.id._close_open_objects(h5f.OBJ_LOCAL | ~h5f.OBJ_FILE)
  394. self.id._close_open_objects(h5f.OBJ_LOCAL | h5f.OBJ_FILE)
  395. self.id.close()
  396. _objects.nonlocal_close()
  397. def flush(self):
  398. """ Tell the HDF5 library to flush its buffers.
  399. """
  400. with phil:
  401. h5f.flush(self.id)
  402. @with_phil
  403. def __enter__(self):
  404. return self
  405. @with_phil
  406. def __exit__(self, *args):
  407. if self.id:
  408. self.close()
  409. @with_phil
  410. def __repr__(self):
  411. if not self.id:
  412. r = '<Closed HDF5 file>'
  413. else:
  414. # Filename has to be forced to Unicode if it comes back bytes
  415. # Mode is always a "native" string
  416. filename = self.filename
  417. if isinstance(filename, bytes): # Can't decode fname
  418. filename = filename.decode('utf8', 'replace')
  419. r = '<HDF5 file "%s" (mode %s)>' % (os.path.basename(filename),
  420. self.mode)
  421. return r