files.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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 inspect
  13. import os
  14. import sys
  15. from warnings import warn
  16. from .compat import filename_decode, filename_encode
  17. from .base import phil, with_phil
  18. from .group import Group, set_fapl_file_locking
  19. from .. import h5, h5f, h5p, h5i, h5fd, _objects
  20. from .. import version
  21. mpi = h5.get_config().mpi
  22. ros3 = h5.get_config().ros3
  23. direct_vfd = h5.get_config().direct_vfd
  24. hdf5_version = version.hdf5_version_tuple[0:3]
  25. libver_dict = {'earliest': h5f.LIBVER_EARLIEST, 'latest': h5f.LIBVER_LATEST,
  26. 'v108': h5f.LIBVER_V18, 'v110': h5f.LIBVER_V110}
  27. libver_dict_r = dict((y, x) for x, y in libver_dict.items())
  28. if hdf5_version >= (1, 11, 4):
  29. libver_dict.update({'v112': h5f.LIBVER_V112})
  30. libver_dict_r.update({h5f.LIBVER_V112: 'v112'})
  31. if hdf5_version >= (1, 13, 0):
  32. libver_dict.update({'v114': h5f.LIBVER_V114})
  33. libver_dict_r.update({h5f.LIBVER_V114: 'v114'})
  34. if hdf5_version >= (2, 0, 0):
  35. libver_dict.update({'v200': h5f.LIBVER_V200})
  36. libver_dict_r.update({h5f.LIBVER_V200: 'v200'})
  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. if direct_vfd:
  62. _drivers['direct'] = lambda plist, **kwargs: plist.set_fapl_direct(**kwargs) # noqa
  63. def register_driver(name, set_fapl):
  64. """Register a custom driver.
  65. Parameters
  66. ----------
  67. name : str
  68. The name of the driver.
  69. set_fapl : callable[PropFAID, **kwargs] -> NoneType
  70. The function to set the fapl to use your custom driver.
  71. """
  72. _drivers[name] = set_fapl
  73. def unregister_driver(name):
  74. """Unregister a custom driver.
  75. Parameters
  76. ----------
  77. name : str
  78. The name of the driver.
  79. """
  80. del _drivers[name]
  81. def registered_drivers():
  82. """Return a frozenset of the names of all of the registered drivers.
  83. """
  84. return frozenset(_drivers)
  85. def make_fapl(
  86. driver, libver=None, rdcc_nslots=None, rdcc_nbytes=None, rdcc_w0=None,
  87. locking=None, page_buf_size=None, min_meta_keep=0, min_raw_keep=0,
  88. alignment_threshold=1, alignment_interval=1, meta_block_size=None,
  89. **kwds
  90. ):
  91. """ Set up a file access property list """
  92. plist = h5p.create(h5p.FILE_ACCESS)
  93. if libver is not None:
  94. if libver in libver_dict:
  95. low = libver_dict[libver]
  96. high = h5f.LIBVER_LATEST
  97. else:
  98. low, high = (libver_dict[x] for x in libver)
  99. else:
  100. # we default to earliest
  101. low, high = h5f.LIBVER_EARLIEST, h5f.LIBVER_LATEST
  102. plist.set_libver_bounds(low, high)
  103. plist.set_alignment(alignment_threshold, alignment_interval)
  104. cache_settings = list(plist.get_cache())
  105. if rdcc_nslots is not None:
  106. cache_settings[1] = rdcc_nslots
  107. if rdcc_nbytes is not None:
  108. cache_settings[2] = rdcc_nbytes
  109. if rdcc_w0 is not None:
  110. cache_settings[3] = rdcc_w0
  111. plist.set_cache(*cache_settings)
  112. if page_buf_size:
  113. plist.set_page_buffer_size(int(page_buf_size), int(min_meta_keep),
  114. int(min_raw_keep))
  115. if meta_block_size is not None:
  116. plist.set_meta_block_size(int(meta_block_size))
  117. if locking is not None:
  118. set_fapl_file_locking(plist, locking)
  119. if driver is None or (driver == 'windows' and sys.platform == 'win32'):
  120. # Prevent swallowing unused key arguments
  121. if kwds:
  122. msg = "'{key}' is an invalid keyword argument for this function" \
  123. .format(key=next(iter(kwds)))
  124. raise TypeError(msg)
  125. return plist
  126. try:
  127. set_fapl = _drivers[driver]
  128. except KeyError as exc:
  129. raise ValueError(f'Unknown driver type {driver!r}') from exc
  130. else:
  131. if driver == 'ros3':
  132. token = kwds.pop('session_token', None)
  133. set_fapl(plist, **kwds)
  134. if token:
  135. if hdf5_version < (1, 14, 2):
  136. raise ValueError('HDF5 >= 1.14.2 required for AWS session token')
  137. plist.set_fapl_ros3_token(token)
  138. else:
  139. set_fapl(plist, **kwds)
  140. return plist
  141. def make_fcpl(track_order=False, track_times=False, fs_strategy=None, fs_persist=False,
  142. fs_threshold=1, fs_page_size=None):
  143. """ Set up a file creation property list """
  144. plist = h5p.create(h5p.FILE_CREATE)
  145. if track_order:
  146. plist.set_link_creation_order(
  147. h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED)
  148. plist.set_attr_creation_order(
  149. h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED)
  150. if track_times is None:
  151. track_times = False # Allow explicit None to mean h5py's default
  152. if track_times in (True, False):
  153. plist.set_obj_track_times(track_times)
  154. else:
  155. raise TypeError("track_times must be either True or False")
  156. if fs_strategy:
  157. strategies = {
  158. 'fsm': h5f.FSPACE_STRATEGY_FSM_AGGR,
  159. 'page': h5f.FSPACE_STRATEGY_PAGE,
  160. 'aggregate': h5f.FSPACE_STRATEGY_AGGR,
  161. 'none': h5f.FSPACE_STRATEGY_NONE
  162. }
  163. fs_strat_num = strategies.get(fs_strategy, -1)
  164. if fs_strat_num == -1:
  165. raise ValueError("Invalid file space strategy type")
  166. plist.set_file_space_strategy(fs_strat_num, fs_persist, fs_threshold)
  167. if fs_page_size and fs_strategy == 'page':
  168. plist.set_file_space_page_size(int(fs_page_size))
  169. return plist
  170. def make_fid(name, mode, userblock_size, fapl, fcpl=None, swmr=False):
  171. """ Get a new FileID by opening or creating a file.
  172. Also validates mode argument."""
  173. if userblock_size is not None:
  174. if mode in ('r', 'r+'):
  175. raise ValueError("User block may only be specified "
  176. "when creating a file")
  177. try:
  178. userblock_size = int(userblock_size)
  179. except (TypeError, ValueError):
  180. raise ValueError("User block size must be an integer") from None
  181. if fcpl is None:
  182. fcpl = h5p.create(h5p.FILE_CREATE)
  183. fcpl.set_userblock(userblock_size)
  184. if mode == 'r':
  185. flags = h5f.ACC_RDONLY
  186. if swmr:
  187. flags |= h5f.ACC_SWMR_READ
  188. fid = h5f.open(name, flags, fapl=fapl)
  189. elif mode == 'r+':
  190. fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl)
  191. elif mode in ['w-', 'x']:
  192. fid = h5f.create(name, h5f.ACC_EXCL, fapl=fapl, fcpl=fcpl)
  193. elif mode == 'w':
  194. fid = h5f.create(name, h5f.ACC_TRUNC, fapl=fapl, fcpl=fcpl)
  195. elif mode == 'a':
  196. # Open in append mode (read/write).
  197. # If that fails, create a new file only if it won't clobber an
  198. # existing one (ACC_EXCL)
  199. try:
  200. fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl)
  201. # Not all drivers raise FileNotFoundError (commented those that do not)
  202. except FileNotFoundError if fapl.get_driver() in (
  203. h5fd.SEC2,
  204. h5fd.DIRECT if direct_vfd else -1,
  205. # h5fd.STDIO,
  206. # h5fd.CORE,
  207. h5fd.FAMILY,
  208. h5fd.WINDOWS,
  209. # h5fd.MPIO,
  210. # h5fd.MPIPOSIX,
  211. h5fd.fileobj_driver,
  212. h5fd.ROS3D if ros3 else -1,
  213. ) else OSError:
  214. fid = h5f.create(name, h5f.ACC_EXCL, fapl=fapl, fcpl=fcpl)
  215. else:
  216. raise ValueError("Invalid mode; must be one of r, r+, w, w-, x, a")
  217. try:
  218. if userblock_size is not None:
  219. existing_fcpl = fid.get_create_plist()
  220. if existing_fcpl.get_userblock() != userblock_size:
  221. raise ValueError("Requested userblock size (%d) does not match that of existing file (%d)" % (userblock_size, existing_fcpl.get_userblock()))
  222. except Exception as e:
  223. fid.close()
  224. raise e
  225. return fid
  226. class File(Group):
  227. """
  228. Represents an HDF5 file.
  229. """
  230. @property
  231. def attrs(self):
  232. """ Attributes attached to this object """
  233. # hdf5 complains that a file identifier is an invalid location for an
  234. # attribute. Instead of self, pass the root group to AttributeManager:
  235. from . import attrs
  236. with phil:
  237. return attrs.AttributeManager(self['/'])
  238. @property
  239. @with_phil
  240. def filename(self):
  241. """File name on disk"""
  242. return filename_decode(h5f.get_name(self.id))
  243. @property
  244. @with_phil
  245. def driver(self):
  246. """Low-level HDF5 file driver used to open file"""
  247. drivers = {h5fd.SEC2: 'sec2',
  248. h5fd.STDIO: 'stdio',
  249. h5fd.CORE: 'core',
  250. h5fd.FAMILY: 'family',
  251. h5fd.WINDOWS: 'windows',
  252. h5fd.MPIO: 'mpio',
  253. h5fd.MPIPOSIX: 'mpiposix',
  254. h5fd.fileobj_driver: 'fileobj'}
  255. if ros3:
  256. drivers[h5fd.ROS3D] = 'ros3'
  257. if direct_vfd:
  258. drivers[h5fd.DIRECT] = 'direct'
  259. return drivers.get(self.id.get_access_plist().get_driver(), 'unknown')
  260. @property
  261. @with_phil
  262. def mode(self):
  263. """ Python mode used to open file """
  264. write_intent = h5f.ACC_RDWR | h5f.ACC_SWMR_WRITE
  265. return 'r+' if self.id.get_intent() & write_intent else 'r'
  266. @property
  267. @with_phil
  268. def libver(self):
  269. """File format version bounds (2-tuple: low, high)"""
  270. bounds = self.id.get_access_plist().get_libver_bounds()
  271. return tuple(libver_dict_r[x] for x in bounds)
  272. @property
  273. @with_phil
  274. def userblock_size(self):
  275. """ User block size (in bytes) """
  276. fcpl = self.id.get_create_plist()
  277. return fcpl.get_userblock()
  278. @property
  279. @with_phil
  280. def meta_block_size(self):
  281. """ Meta block size (in bytes) """
  282. fapl = self.id.get_access_plist()
  283. return fapl.get_meta_block_size()
  284. if mpi:
  285. @property
  286. @with_phil
  287. def atomic(self):
  288. """ Set/get MPI-IO atomic mode
  289. """
  290. return self.id.get_mpi_atomicity()
  291. @atomic.setter
  292. @with_phil
  293. def atomic(self, value):
  294. # pylint: disable=missing-docstring
  295. self.id.set_mpi_atomicity(value)
  296. @property
  297. @with_phil
  298. def swmr_mode(self):
  299. """ Controls single-writer multiple-reader mode """
  300. return bool(self.id.get_intent() & (h5f.ACC_SWMR_READ | h5f.ACC_SWMR_WRITE))
  301. @swmr_mode.setter
  302. @with_phil
  303. def swmr_mode(self, value):
  304. # pylint: disable=missing-docstring
  305. if value:
  306. self.id.start_swmr_write()
  307. else:
  308. raise ValueError("It is not possible to forcibly switch SWMR mode off.")
  309. def __init__(self, name, mode='r', driver=None, libver=None, userblock_size=None, swmr=False,
  310. rdcc_nslots=None, rdcc_nbytes=None, rdcc_w0=None, track_order=None,
  311. fs_strategy=None, fs_persist=False, fs_threshold=1, fs_page_size=None,
  312. page_buf_size=None, min_meta_keep=0, min_raw_keep=0, locking=None,
  313. alignment_threshold=1, alignment_interval=1, meta_block_size=None,
  314. *, track_times=False, **kwds):
  315. """Create a new file object.
  316. See the h5py user guide for a detailed explanation of the options.
  317. name
  318. Name of the file on disk, or file-like object. Note: for files
  319. created with the 'core' driver, HDF5 still requires this be
  320. non-empty.
  321. mode
  322. r Readonly, file must exist (default)
  323. r+ Read/write, file must exist
  324. w Create file, truncate if exists
  325. w- or x Create file, fail if exists
  326. a Read/write if exists, create otherwise
  327. driver
  328. Name of the driver to use. Legal values are None (default,
  329. recommended), 'core', 'sec2', 'direct', 'stdio', 'mpio', 'ros3'.
  330. libver
  331. Library version bounds. Supported values: 'earliest', 'v108',
  332. 'v110', 'v112', 'v114', 'v200' and 'latest' depending on the
  333. version of libhdf5 h5py is built against.
  334. userblock_size
  335. Desired size of user block. Only allowed when creating a new
  336. file (mode w, w- or x).
  337. swmr
  338. Open the file in SWMR read mode. Only used when mode = 'r'.
  339. rdcc_nslots
  340. The number of chunk slots in the raw data chunk cache for this
  341. file. Increasing this value reduces the number of cache collisions,
  342. but slightly increases the memory used. Due to the hashing
  343. strategy, this value should ideally be a prime number. As a rule of
  344. thumb, this value should be at least 10 times the number of chunks
  345. that can fit in rdcc_nbytes bytes. For maximum performance, this
  346. value should be set approximately 100 times that number of
  347. chunks. The default value is 521. Applies to all datasets unless individually changed.
  348. rdcc_nbytes
  349. Total size of the dataset chunk cache in bytes. The default size per
  350. dataset is 1024**2 (1 MiB) for HDF5 before 2.0 and 8 MiB for HDF5
  351. 2.0 and later. Applies to all datasets unless individually changed.
  352. rdcc_w0
  353. The chunk preemption policy for all datasets. This must be
  354. between 0 and 1 inclusive and indicates the weighting according to
  355. which chunks which have been fully read or written are penalized
  356. when determining which chunks to flush from cache. A value of 0
  357. means fully read or written chunks are treated no differently than
  358. other chunks (the preemption is strictly LRU) while a value of 1
  359. means fully read or written chunks are always preempted before
  360. other chunks. If your application only reads or writes data once,
  361. this can be safely set to 1. Otherwise, this should be set lower
  362. depending on how often you re-read or re-write the same data. The
  363. default value is 0.75. Applies to all datasets unless individually changed.
  364. track_order
  365. Track dataset/group/attribute creation order under root group
  366. if True. If None use global default h5.get_config().track_order.
  367. track_times: bool or None, default: False
  368. If True, store timestamps for this group in the file.
  369. If None, fall back to the default value.
  370. fs_strategy
  371. The file space handling strategy to be used. Only allowed when
  372. creating a new file (mode w, w- or x). Defined as:
  373. "fsm" FSM, Aggregators, VFD
  374. "page" Paged FSM, VFD
  375. "aggregate" Aggregators, VFD
  376. "none" VFD
  377. If None use HDF5 defaults.
  378. fs_page_size
  379. File space page size in bytes. Only used when fs_strategy="page". If
  380. None use the HDF5 default (4096 bytes).
  381. fs_persist
  382. A boolean value to indicate whether free space should be persistent
  383. or not. Only allowed when creating a new file. The default value
  384. is False.
  385. fs_threshold
  386. The smallest free-space section size that the free space manager
  387. will track. Only allowed when creating a new file. The default
  388. value is 1.
  389. page_buf_size
  390. Page buffer size in bytes. Only allowed for HDF5 files created with
  391. fs_strategy="page". Must be a power of two value and greater or
  392. equal than the file space page size when creating the file. It is
  393. not used by default.
  394. min_meta_keep
  395. Minimum percentage of metadata to keep in the page buffer before
  396. allowing pages containing metadata to be evicted. Applicable only if
  397. page_buf_size is set. Default value is zero.
  398. min_raw_keep
  399. Minimum percentage of raw data to keep in the page buffer before
  400. allowing pages containing raw data to be evicted. Applicable only if
  401. page_buf_size is set. Default value is zero.
  402. locking
  403. The file locking behavior. Defined as:
  404. - False (or "false") -- Disable file locking
  405. - True (or "true") -- Enable file locking
  406. - "best-effort" -- Enable file locking but ignore some errors
  407. - None -- Use HDF5 defaults
  408. .. warning::
  409. The HDF5_USE_FILE_LOCKING environment variable can override
  410. this parameter.
  411. alignment_threshold
  412. Together with ``alignment_interval``, this property ensures that
  413. any file object greater than or equal in size to the alignment
  414. threshold (in bytes) will be aligned on an address which is a
  415. multiple of alignment interval.
  416. alignment_interval
  417. This property should be used in conjunction with
  418. ``alignment_threshold``. See the description above. For more
  419. details, see
  420. https://support.hdfgroup.org/documentation/hdf5/latest/group___f_a_p_l.html#gab99d5af749aeb3896fd9e3ceb273677a
  421. meta_block_size
  422. Set the current minimum size, in bytes, of new metadata block allocations.
  423. See https://support.hdfgroup.org/documentation/hdf5/latest/group___f_a_p_l.html#ga8822e3dedc8e1414f20871a87d533cb1
  424. Additional keywords
  425. Passed on to the selected file driver.
  426. """
  427. if driver == 'ros3':
  428. if not ros3:
  429. raise ValueError("h5py was built without ROS3 support, can't use ros3 driver")
  430. if hdf5_version < (2, 0, 0):
  431. from urllib.parse import urlparse
  432. url = urlparse(name)
  433. if url.scheme == 's3':
  434. aws_region = kwds.get('aws_region', b'').decode('ascii')
  435. if len(aws_region) == 0:
  436. raise ValueError('AWS region required for s3:// location')
  437. name = f'https://s3.{aws_region}.amazonaws.com/{url.netloc}{url.path}'
  438. elif url.scheme not in ('https', 'http'):
  439. raise ValueError(f'{name}: S3 location must begin with '
  440. 'either "https://", "http://", or "s3://"')
  441. if isinstance(name, _objects.ObjectID):
  442. if fs_strategy:
  443. raise ValueError("Unable to set file space strategy of an existing file")
  444. with phil:
  445. fid = h5i.get_file_id(name)
  446. else:
  447. if hasattr(name, 'read') and hasattr(name, 'seek'):
  448. if driver not in (None, 'fileobj'):
  449. raise ValueError("Driver must be 'fileobj' for file-like object if specified.")
  450. driver = 'fileobj'
  451. if kwds.get('fileobj', name) != name:
  452. raise ValueError("Invalid value of 'fileobj' argument; "
  453. "must equal to file-like object if specified.")
  454. kwds.update(fileobj=name)
  455. name = repr(name).encode('ASCII', 'replace')
  456. else:
  457. name = filename_encode(name)
  458. if track_order is None:
  459. track_order = h5.get_config().track_order
  460. if fs_strategy and mode not in ('w', 'w-', 'x'):
  461. raise ValueError("Unable to set file space strategy of an existing file")
  462. if swmr and mode != 'r':
  463. warn(
  464. "swmr=True only affects read ('r') mode. For swmr write "
  465. "mode, set f.swmr_mode = True after opening the file.",
  466. stacklevel=2,
  467. )
  468. with phil:
  469. fapl = make_fapl(driver, libver, rdcc_nslots, rdcc_nbytes, rdcc_w0,
  470. locking, page_buf_size, min_meta_keep, min_raw_keep,
  471. alignment_threshold=alignment_threshold,
  472. alignment_interval=alignment_interval,
  473. meta_block_size=meta_block_size,
  474. **kwds)
  475. fcpl = make_fcpl(track_order=track_order, track_times=track_times,
  476. fs_strategy=fs_strategy, fs_persist=fs_persist,
  477. fs_threshold=fs_threshold, fs_page_size=fs_page_size)
  478. fid = make_fid(name, mode, userblock_size, fapl, fcpl, swmr=swmr)
  479. if isinstance(libver, tuple):
  480. self._libver = libver
  481. else:
  482. self._libver = (libver, 'latest')
  483. super().__init__(fid)
  484. _in_memory_file_counter = 0
  485. @classmethod
  486. @with_phil
  487. def in_memory(cls, file_image=None, **kwargs):
  488. """Create an HDF5 file in memory, without an underlying file
  489. file_image
  490. The initial file contents as bytes (or anything that supports the
  491. Python buffer interface). HDF5 takes a copy of this data.
  492. block_size
  493. Chunk size for new memory alloactions (default 64 KiB).
  494. Other keyword arguments are like File(), although name, mode,
  495. driver and locking can't be passed.
  496. """
  497. for k in ('driver', 'locking', 'backing_store'):
  498. if k in kwargs:
  499. raise TypeError(
  500. f"File.in_memory() got an unexpected keyword argument {k!r}"
  501. )
  502. fcpl_kwargs = {}
  503. for k in inspect.signature(make_fcpl).parameters:
  504. if k in kwargs:
  505. fcpl_kwargs[k] = kwargs.pop(k)
  506. fcpl = make_fcpl(**fcpl_kwargs)
  507. fapl = make_fapl(driver="core", backing_store=False, **kwargs)
  508. if file_image:
  509. if fcpl_kwargs:
  510. kw = ', '.join(fcpl_kwargs)
  511. raise TypeError(f"{kw} parameters cannot be used with file_image")
  512. fapl.set_file_image(file_image)
  513. # We have to give HDF5 a filename, but it should never use it.
  514. # This is a hint both in memory, and in case a bug ever creates a file.
  515. # The name also needs to be different from any other open file;
  516. # we use a simple counter (protected by the 'phil' lock) for this.
  517. name = b"h5py_in_memory_nonfile_%d" % cls._in_memory_file_counter
  518. cls._in_memory_file_counter += 1
  519. if file_image:
  520. fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl)
  521. else:
  522. fid = h5f.create(name, h5f.ACC_EXCL, fapl=fapl, fcpl=fcpl)
  523. return cls(fid)
  524. def close(self):
  525. """ Close the file. All open objects become invalid """
  526. with phil:
  527. # Check that the file is still open, otherwise skip
  528. if self.id.valid:
  529. # We have to explicitly murder all open objects related to the file
  530. # Close file-resident objects first, then the files.
  531. # Otherwise we get errors in MPI mode.
  532. self.id._close_open_objects(h5f.OBJ_LOCAL | ~h5f.OBJ_FILE)
  533. self.id._close_open_objects(h5f.OBJ_LOCAL | h5f.OBJ_FILE)
  534. self.id.close()
  535. def flush(self):
  536. """ Tell the HDF5 library to flush its buffers.
  537. """
  538. with phil:
  539. h5f.flush(self.id)
  540. @with_phil
  541. def __enter__(self):
  542. return self
  543. @with_phil
  544. def __exit__(self, *args):
  545. if self.id:
  546. self.close()
  547. @with_phil
  548. def __repr__(self):
  549. if not self.id:
  550. r = '<Closed HDF5 file>'
  551. else:
  552. # Filename has to be forced to Unicode if it comes back bytes
  553. # Mode is always a "native" string
  554. filename = self.filename
  555. if isinstance(filename, bytes): # Can't decode fname
  556. filename = filename.decode('utf8', 'replace')
  557. r = f'<HDF5 file "{os.path.basename(filename)}" (mode {self.mode})>'
  558. return r