test_dataset.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  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. Dataset testing operations.
  11. Tests all dataset operations, including creation, with the exception of:
  12. 1. Slicing operations for read and write, handled by module test_slicing
  13. 2. Type conversion for read and write (currently untested)
  14. """
  15. import pathlib
  16. import sys
  17. import numpy as np
  18. import platform
  19. import pytest
  20. from .common import ut, TestCase
  21. from .data_files import get_data_file_path
  22. from h5py import File, Group, Dataset
  23. from h5py._hl.base import is_empty_dataspace
  24. from h5py import h5f, h5t
  25. import h5py
  26. import h5py._hl.selections as sel
  27. class BaseDataset(TestCase):
  28. def setUp(self):
  29. self.f = File(self.mktemp(), 'w')
  30. def tearDown(self):
  31. if self.f:
  32. self.f.close()
  33. class TestRepr(BaseDataset):
  34. """
  35. Feature: repr(Dataset) behaves sensibly
  36. """
  37. def test_repr_open(self):
  38. """ repr() works on live and dead datasets """
  39. ds = self.f.create_dataset('foo', (4,))
  40. self.assertIsInstance(repr(ds), str)
  41. self.f.close()
  42. self.assertIsInstance(repr(ds), str)
  43. class TestCreateShape(BaseDataset):
  44. """
  45. Feature: Datasets can be created from a shape only
  46. """
  47. def test_create_scalar(self):
  48. """ Create a scalar dataset """
  49. dset = self.f.create_dataset('foo', ())
  50. self.assertEqual(dset.shape, ())
  51. def test_create_simple(self):
  52. """ Create a size-1 dataset """
  53. dset = self.f.create_dataset('foo', (1,))
  54. self.assertEqual(dset.shape, (1,))
  55. def test_create_integer(self):
  56. """ Create a size-1 dataset with integer shape"""
  57. dset = self.f.create_dataset('foo', 1)
  58. self.assertEqual(dset.shape, (1,))
  59. def test_create_extended(self):
  60. """ Create an extended dataset """
  61. dset = self.f.create_dataset('foo', (63,))
  62. self.assertEqual(dset.shape, (63,))
  63. self.assertEqual(dset.size, 63)
  64. dset = self.f.create_dataset('bar', (6, 10))
  65. self.assertEqual(dset.shape, (6, 10))
  66. self.assertEqual(dset.size, (60))
  67. def test_create_integer_extended(self):
  68. """ Create an extended dataset """
  69. dset = self.f.create_dataset('foo', 63)
  70. self.assertEqual(dset.shape, (63,))
  71. self.assertEqual(dset.size, 63)
  72. dset = self.f.create_dataset('bar', (6, 10))
  73. self.assertEqual(dset.shape, (6, 10))
  74. self.assertEqual(dset.size, (60))
  75. def test_default_dtype(self):
  76. """ Confirm that the default dtype is float """
  77. dset = self.f.create_dataset('foo', (63,))
  78. self.assertEqual(dset.dtype, np.dtype('=f4'))
  79. def test_missing_shape(self):
  80. """ Missing shape raises TypeError """
  81. with self.assertRaises(TypeError):
  82. self.f.create_dataset('foo')
  83. def test_long_double(self):
  84. """ Confirm that the default dtype is float """
  85. dset = self.f.create_dataset('foo', (63,), dtype=np.longdouble)
  86. if platform.machine() in ['ppc64le']:
  87. pytest.xfail("Storage of long double deactivated on %s" % platform.machine())
  88. self.assertEqual(dset.dtype, np.longdouble)
  89. @ut.skipIf(not hasattr(np, "complex256"), "No support for complex256")
  90. def test_complex256(self):
  91. """ Confirm that the default dtype is float """
  92. dset = self.f.create_dataset('foo', (63,),
  93. dtype=np.dtype('complex256'))
  94. self.assertEqual(dset.dtype, np.dtype('complex256'))
  95. def test_name_bytes(self):
  96. dset = self.f.create_dataset(b'foo', (1,))
  97. self.assertEqual(dset.shape, (1,))
  98. dset2 = self.f.create_dataset(b'bar/baz', (2,))
  99. self.assertEqual(dset2.shape, (2,))
  100. class TestCreateData(BaseDataset):
  101. """
  102. Feature: Datasets can be created from existing data
  103. """
  104. def test_create_scalar(self):
  105. """ Create a scalar dataset from existing array """
  106. data = np.ones((), 'f')
  107. dset = self.f.create_dataset('foo', data=data)
  108. self.assertEqual(dset.shape, data.shape)
  109. def test_create_extended(self):
  110. """ Create an extended dataset from existing data """
  111. data = np.ones((63,), 'f')
  112. dset = self.f.create_dataset('foo', data=data)
  113. self.assertEqual(dset.shape, data.shape)
  114. def test_dataset_intermediate_group(self):
  115. """ Create dataset with missing intermediate groups """
  116. ds = self.f.create_dataset("/foo/bar/baz", shape=(10, 10), dtype='<i4')
  117. self.assertIsInstance(ds, h5py.Dataset)
  118. self.assertTrue("/foo/bar/baz" in self.f)
  119. def test_reshape(self):
  120. """ Create from existing data, and make it fit a new shape """
  121. data = np.arange(30, dtype='f')
  122. dset = self.f.create_dataset('foo', shape=(10, 3), data=data)
  123. self.assertEqual(dset.shape, (10, 3))
  124. self.assertArrayEqual(dset[...], data.reshape((10, 3)))
  125. def test_appropriate_low_level_id(self):
  126. " Binding Dataset to a non-DatasetID identifier fails with ValueError "
  127. with self.assertRaises(ValueError):
  128. Dataset(self.f['/'].id)
  129. def check_h5_string(self, dset, cset, length):
  130. tid = dset.id.get_type()
  131. assert isinstance(tid, h5t.TypeStringID)
  132. assert tid.get_cset() == cset
  133. if length is None:
  134. assert tid.is_variable_str()
  135. else:
  136. assert not tid.is_variable_str()
  137. assert tid.get_size() == length
  138. def test_create_bytestring(self):
  139. """ Creating dataset with byte string yields vlen ASCII dataset """
  140. def check_vlen_ascii(dset):
  141. self.check_h5_string(dset, h5t.CSET_ASCII, length=None)
  142. check_vlen_ascii(self.f.create_dataset('a', data=b'abc'))
  143. check_vlen_ascii(self.f.create_dataset('b', data=[b'abc', b'def']))
  144. check_vlen_ascii(self.f.create_dataset('c', data=[[b'abc'], [b'def']]))
  145. check_vlen_ascii(self.f.create_dataset(
  146. 'd', data=np.array([b'abc', b'def'], dtype=object)
  147. ))
  148. def test_create_np_s(self):
  149. dset = self.f.create_dataset('a', data=np.array([b'abc', b'def'], dtype='S3'))
  150. self.check_h5_string(dset, h5t.CSET_ASCII, length=3)
  151. def test_create_strings(self):
  152. def check_vlen_utf8(dset):
  153. self.check_h5_string(dset, h5t.CSET_UTF8, length=None)
  154. check_vlen_utf8(self.f.create_dataset('a', data='abc'))
  155. check_vlen_utf8(self.f.create_dataset('b', data=['abc', 'def']))
  156. check_vlen_utf8(self.f.create_dataset('c', data=[['abc'], ['def']]))
  157. check_vlen_utf8(self.f.create_dataset(
  158. 'd', data=np.array(['abc', 'def'], dtype=object)
  159. ))
  160. def test_create_np_u(self):
  161. with self.assertRaises(TypeError):
  162. self.f.create_dataset('a', data=np.array([b'abc', b'def'], dtype='U3'))
  163. def test_empty_create_via_None_shape(self):
  164. self.f.create_dataset('foo', dtype='f')
  165. self.assertTrue(is_empty_dataspace(self.f['foo'].id))
  166. def test_empty_create_via_Empty_class(self):
  167. self.f.create_dataset('foo', data=h5py.Empty(dtype='f'))
  168. self.assertTrue(is_empty_dataspace(self.f['foo'].id))
  169. def test_create_incompatible_data(self):
  170. # Shape tuple is incompatible with data
  171. with self.assertRaises(ValueError):
  172. self.f.create_dataset('bar', shape=4, data= np.arange(3))
  173. class TestReadDirectly:
  174. """
  175. Feature: Read data directly from Dataset into a Numpy array
  176. """
  177. @pytest.mark.parametrize(
  178. 'source_shape,dest_shape,source_sel,dest_sel',
  179. [
  180. ((100,), (100,), np.s_[0:10], np.s_[50:60]),
  181. ((70,), (100,), np.s_[50:60], np.s_[90:]),
  182. ((30, 10), (20, 20), np.s_[:20, :], np.s_[:, :10]),
  183. ((5, 7, 9), (6,), np.s_[2, :6, 3], np.s_[:]),
  184. ])
  185. def test_read_direct(self, writable_file, source_shape, dest_shape, source_sel, dest_sel):
  186. source_values = np.arange(np.product(source_shape), dtype="int64").reshape(source_shape)
  187. dset = writable_file.create_dataset("dset", source_shape, data=source_values)
  188. arr = np.full(dest_shape, -1, dtype="int64")
  189. expected = arr.copy()
  190. expected[dest_sel] = source_values[source_sel]
  191. dset.read_direct(arr, source_sel, dest_sel)
  192. np.testing.assert_array_equal(arr, expected)
  193. def test_no_sel(self, writable_file):
  194. dset = writable_file.create_dataset("dset", (10,), data=np.arange(10, dtype="int64"))
  195. arr = np.ones((10,), dtype="int64")
  196. dset.read_direct(arr)
  197. np.testing.assert_array_equal(arr, np.arange(10, dtype="int64"))
  198. def test_empty(self, writable_file):
  199. empty_dset = writable_file.create_dataset("edset", dtype='int64')
  200. arr = np.ones((100,), 'int64')
  201. with pytest.raises(TypeError):
  202. empty_dset.read_direct(arr, np.s_[0:10], np.s_[50:60])
  203. def test_wrong_shape(self, writable_file):
  204. dset = writable_file.create_dataset("dset", (100,), dtype='int64')
  205. arr = np.ones((200,))
  206. with pytest.raises(TypeError):
  207. dset.read_direct(arr)
  208. def test_not_c_contiguous(self, writable_file):
  209. dset = writable_file.create_dataset("dset", (10, 10), dtype='int64')
  210. arr = np.ones((10, 10), order='F')
  211. with pytest.raises(TypeError):
  212. dset.read_direct(arr)
  213. class TestWriteDirectly:
  214. """
  215. Feature: Write Numpy array directly into Dataset
  216. """
  217. @pytest.mark.parametrize(
  218. 'source_shape,dest_shape,source_sel,dest_sel',
  219. [
  220. ((100,), (100,), np.s_[0:10], np.s_[50:60]),
  221. ((70,), (100,), np.s_[50:60], np.s_[90:]),
  222. ((30, 10), (20, 20), np.s_[:20, :], np.s_[:, :10]),
  223. ((5, 7, 9), (6,), np.s_[2, :6, 3], np.s_[:]),
  224. ])
  225. def test_write_direct(self, writable_file, source_shape, dest_shape, source_sel, dest_sel):
  226. dset = writable_file.create_dataset('dset', dest_shape, dtype='int32', fillvalue=-1)
  227. arr = np.arange(np.product(source_shape)).reshape(source_shape)
  228. expected = np.full(dest_shape, -1, dtype='int32')
  229. expected[dest_sel] = arr[source_sel]
  230. dset.write_direct(arr, source_sel, dest_sel)
  231. np.testing.assert_array_equal(dset[:], expected)
  232. def test_empty(self, writable_file):
  233. empty_dset = writable_file.create_dataset("edset", dtype='int64')
  234. with pytest.raises(TypeError):
  235. empty_dset.write_direct(np.ones((100,)), np.s_[0:10], np.s_[50:60])
  236. def test_wrong_shape(self, writable_file):
  237. dset = writable_file.create_dataset("dset", (100,), dtype='int64')
  238. arr = np.ones((200,))
  239. with pytest.raises(TypeError):
  240. dset.write_direct(arr)
  241. def test_not_c_contiguous(self, writable_file):
  242. dset = writable_file.create_dataset("dset", (10, 10), dtype='int64')
  243. arr = np.ones((10, 10), order='F')
  244. with pytest.raises(TypeError):
  245. dset.write_direct(arr)
  246. class TestCreateRequire(BaseDataset):
  247. """
  248. Feature: Datasets can be created only if they don't exist in the file
  249. """
  250. def test_create(self):
  251. """ Create new dataset with no conflicts """
  252. dset = self.f.require_dataset('foo', (10, 3), 'f')
  253. self.assertIsInstance(dset, Dataset)
  254. self.assertEqual(dset.shape, (10, 3))
  255. def test_create_existing(self):
  256. """ require_dataset yields existing dataset """
  257. dset = self.f.require_dataset('foo', (10, 3), 'f')
  258. dset2 = self.f.require_dataset('foo', (10, 3), 'f')
  259. self.assertEqual(dset, dset2)
  260. def test_create_1D(self):
  261. """ require_dataset with integer shape yields existing dataset"""
  262. dset = self.f.require_dataset('foo', 10, 'f')
  263. dset2 = self.f.require_dataset('foo', 10, 'f')
  264. self.assertEqual(dset, dset2)
  265. dset = self.f.require_dataset('bar', (10,), 'f')
  266. dset2 = self.f.require_dataset('bar', 10, 'f')
  267. self.assertEqual(dset, dset2)
  268. dset = self.f.require_dataset('baz', 10, 'f')
  269. dset2 = self.f.require_dataset(b'baz', (10,), 'f')
  270. self.assertEqual(dset, dset2)
  271. def test_shape_conflict(self):
  272. """ require_dataset with shape conflict yields TypeError """
  273. self.f.create_dataset('foo', (10, 3), 'f')
  274. with self.assertRaises(TypeError):
  275. self.f.require_dataset('foo', (10, 4), 'f')
  276. def test_type_conflict(self):
  277. """ require_dataset with object type conflict yields TypeError """
  278. self.f.create_group('foo')
  279. with self.assertRaises(TypeError):
  280. self.f.require_dataset('foo', (10, 3), 'f')
  281. def test_dtype_conflict(self):
  282. """ require_dataset with dtype conflict (strict mode) yields TypeError
  283. """
  284. dset = self.f.create_dataset('foo', (10, 3), 'f')
  285. with self.assertRaises(TypeError):
  286. self.f.require_dataset('foo', (10, 3), 'S10')
  287. def test_dtype_exact(self):
  288. """ require_dataset with exactly dtype match """
  289. dset = self.f.create_dataset('foo', (10, 3), 'f')
  290. dset2 = self.f.require_dataset('foo', (10, 3), 'f', exact=True)
  291. self.assertEqual(dset, dset2)
  292. def test_dtype_close(self):
  293. """ require_dataset with convertible type succeeds (non-strict mode)
  294. """
  295. dset = self.f.create_dataset('foo', (10, 3), 'i4')
  296. dset2 = self.f.require_dataset('foo', (10, 3), 'i2', exact=False)
  297. self.assertEqual(dset, dset2)
  298. self.assertEqual(dset2.dtype, np.dtype('i4'))
  299. class TestCreateChunked(BaseDataset):
  300. """
  301. Feature: Datasets can be created by manually specifying chunks
  302. """
  303. def test_create_chunks(self):
  304. """ Create via chunks tuple """
  305. dset = self.f.create_dataset('foo', shape=(100,), chunks=(10,))
  306. self.assertEqual(dset.chunks, (10,))
  307. def test_create_chunks_integer(self):
  308. """ Create via chunks integer """
  309. dset = self.f.create_dataset('foo', shape=(100,), chunks=10)
  310. self.assertEqual(dset.chunks, (10,))
  311. def test_chunks_mismatch(self):
  312. """ Illegal chunk size raises ValueError """
  313. with self.assertRaises(ValueError):
  314. self.f.create_dataset('foo', shape=(100,), chunks=(200,))
  315. def test_chunks_false(self):
  316. """ Chunked format required for given storage options """
  317. with self.assertRaises(ValueError):
  318. self.f.create_dataset('foo', shape=(10,), maxshape=100, chunks=False)
  319. def test_chunks_scalar(self):
  320. """ Attempting to create chunked scalar dataset raises TypeError """
  321. with self.assertRaises(TypeError):
  322. self.f.create_dataset('foo', shape=(), chunks=(50,))
  323. def test_auto_chunks(self):
  324. """ Auto-chunking of datasets """
  325. dset = self.f.create_dataset('foo', shape=(20, 100), chunks=True)
  326. self.assertIsInstance(dset.chunks, tuple)
  327. self.assertEqual(len(dset.chunks), 2)
  328. def test_auto_chunks_abuse(self):
  329. """ Auto-chunking with pathologically large element sizes """
  330. dset = self.f.create_dataset('foo', shape=(3,), dtype='S100000000', chunks=True)
  331. self.assertEqual(dset.chunks, (1,))
  332. def test_scalar_assignment(self):
  333. """ Test scalar assignment of chunked dataset """
  334. dset = self.f.create_dataset('foo', shape=(3, 50, 50),
  335. dtype=np.int32, chunks=(1, 50, 50))
  336. # test assignment of selection smaller than chunk size
  337. dset[1, :, 40] = 10
  338. self.assertTrue(np.all(dset[1, :, 40] == 10))
  339. # test assignment of selection equal to chunk size
  340. dset[1] = 11
  341. self.assertTrue(np.all(dset[1] == 11))
  342. # test assignment of selection bigger than chunk size
  343. dset[0:2] = 12
  344. self.assertTrue(np.all(dset[0:2] == 12))
  345. def test_auto_chunks_no_shape(self):
  346. """ Auto-chunking of empty datasets not allowed"""
  347. with pytest.raises(TypeError, match='Empty') as err:
  348. self.f.create_dataset('foo', dtype='S100', chunks=True)
  349. with pytest.raises(TypeError, match='Empty') as err:
  350. self.f.create_dataset('foo', dtype='S100', maxshape=20)
  351. class TestCreateFillvalue(BaseDataset):
  352. """
  353. Feature: Datasets can be created with fill value
  354. """
  355. def test_create_fillval(self):
  356. """ Fill value is reflected in dataset contents """
  357. dset = self.f.create_dataset('foo', (10,), fillvalue=4.0)
  358. self.assertEqual(dset[0], 4.0)
  359. self.assertEqual(dset[7], 4.0)
  360. def test_property(self):
  361. """ Fill value is recoverable via property """
  362. dset = self.f.create_dataset('foo', (10,), fillvalue=3.0)
  363. self.assertEqual(dset.fillvalue, 3.0)
  364. self.assertNotIsInstance(dset.fillvalue, np.ndarray)
  365. def test_property_none(self):
  366. """ .fillvalue property works correctly if not set """
  367. dset = self.f.create_dataset('foo', (10,))
  368. self.assertEqual(dset.fillvalue, 0)
  369. def test_compound(self):
  370. """ Fill value works with compound types """
  371. dt = np.dtype([('a', 'f4'), ('b', 'i8')])
  372. v = np.ones((1,), dtype=dt)[0]
  373. dset = self.f.create_dataset('foo', (10,), dtype=dt, fillvalue=v)
  374. self.assertEqual(dset.fillvalue, v)
  375. self.assertAlmostEqual(dset[4], v)
  376. def test_exc(self):
  377. """ Bogus fill value raises ValueError """
  378. with self.assertRaises(ValueError):
  379. dset = self.f.create_dataset('foo', (10,),
  380. dtype=[('a', 'i'), ('b', 'f')], fillvalue=42)
  381. class TestCreateNamedType(BaseDataset):
  382. """
  383. Feature: Datasets created from an existing named type
  384. """
  385. def test_named(self):
  386. """ Named type object works and links the dataset to type """
  387. self.f['type'] = np.dtype('f8')
  388. dset = self.f.create_dataset('x', (100,), dtype=self.f['type'])
  389. self.assertEqual(dset.dtype, np.dtype('f8'))
  390. self.assertEqual(dset.id.get_type(), self.f['type'].id)
  391. self.assertTrue(dset.id.get_type().committed())
  392. @ut.skipIf('gzip' not in h5py.filters.encode, "DEFLATE is not installed")
  393. class TestCreateGzip(BaseDataset):
  394. """
  395. Feature: Datasets created with gzip compression
  396. """
  397. def test_gzip(self):
  398. """ Create with explicit gzip options """
  399. dset = self.f.create_dataset('foo', (20, 30), compression='gzip',
  400. compression_opts=9)
  401. self.assertEqual(dset.compression, 'gzip')
  402. self.assertEqual(dset.compression_opts, 9)
  403. def test_gzip_implicit(self):
  404. """ Create with implicit gzip level (level 4) """
  405. dset = self.f.create_dataset('foo', (20, 30), compression='gzip')
  406. self.assertEqual(dset.compression, 'gzip')
  407. self.assertEqual(dset.compression_opts, 4)
  408. def test_gzip_number(self):
  409. """ Create with gzip level by specifying integer """
  410. dset = self.f.create_dataset('foo', (20, 30), compression=7)
  411. self.assertEqual(dset.compression, 'gzip')
  412. self.assertEqual(dset.compression_opts, 7)
  413. original_compression_vals = h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS
  414. try:
  415. h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS = tuple()
  416. with self.assertRaises(ValueError):
  417. dset = self.f.create_dataset('foo', (20, 30), compression=7)
  418. finally:
  419. h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS = original_compression_vals
  420. def test_gzip_exc(self):
  421. """ Illegal gzip level (explicit or implicit) raises ValueError """
  422. with self.assertRaises((ValueError, RuntimeError)):
  423. self.f.create_dataset('foo', (20, 30), compression=14)
  424. with self.assertRaises(ValueError):
  425. self.f.create_dataset('foo', (20, 30), compression=-4)
  426. with self.assertRaises(ValueError):
  427. self.f.create_dataset('foo', (20, 30), compression='gzip',
  428. compression_opts=14)
  429. @ut.skipIf('gzip' not in h5py.filters.encode, "DEFLATE is not installed")
  430. class TestCreateCompressionNumber(BaseDataset):
  431. """
  432. Feature: Datasets created with a compression code
  433. """
  434. def test_compression_number(self):
  435. """ Create with compression number of gzip (h5py.h5z.FILTER_DEFLATE) and a compression level of 7"""
  436. original_compression_vals = h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS
  437. try:
  438. h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS = tuple()
  439. dset = self.f.create_dataset('foo', (20, 30), compression=h5py.h5z.FILTER_DEFLATE, compression_opts=(7,))
  440. finally:
  441. h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS = original_compression_vals
  442. self.assertEqual(dset.compression, 'gzip')
  443. self.assertEqual(dset.compression_opts, 7)
  444. def test_compression_number_invalid(self):
  445. """ Create with invalid compression numbers """
  446. with self.assertRaises(ValueError) as e:
  447. self.f.create_dataset('foo', (20, 30), compression=-999)
  448. self.assertIn("Invalid filter", str(e.exception))
  449. with self.assertRaises(ValueError) as e:
  450. self.f.create_dataset('foo', (20, 30), compression=100)
  451. self.assertIn("Unknown compression", str(e.exception))
  452. original_compression_vals = h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS
  453. try:
  454. h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS = tuple()
  455. # Using gzip compression requires a compression level specified in compression_opts
  456. with self.assertRaises(IndexError):
  457. self.f.create_dataset('foo', (20, 30), compression=h5py.h5z.FILTER_DEFLATE)
  458. finally:
  459. h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS = original_compression_vals
  460. @ut.skipIf('lzf' not in h5py.filters.encode, "LZF is not installed")
  461. class TestCreateLZF(BaseDataset):
  462. """
  463. Feature: Datasets created with LZF compression
  464. """
  465. def test_lzf(self):
  466. """ Create with explicit lzf """
  467. dset = self.f.create_dataset('foo', (20, 30), compression='lzf')
  468. self.assertEqual(dset.compression, 'lzf')
  469. self.assertEqual(dset.compression_opts, None)
  470. testdata = np.arange(100)
  471. dset = self.f.create_dataset('bar', data=testdata, compression='lzf')
  472. self.assertEqual(dset.compression, 'lzf')
  473. self.assertEqual(dset.compression_opts, None)
  474. self.f.flush() # Actually write to file
  475. readdata = self.f['bar'][()]
  476. self.assertArrayEqual(readdata, testdata)
  477. def test_lzf_exc(self):
  478. """ Giving lzf options raises ValueError """
  479. with self.assertRaises(ValueError):
  480. self.f.create_dataset('foo', (20, 30), compression='lzf',
  481. compression_opts=4)
  482. @ut.skipIf('szip' not in h5py.filters.encode, "SZIP is not installed")
  483. class TestCreateSZIP(BaseDataset):
  484. """
  485. Feature: Datasets created with LZF compression
  486. """
  487. def test_szip(self):
  488. """ Create with explicit szip """
  489. dset = self.f.create_dataset('foo', (20, 30), compression='szip',
  490. compression_opts=('ec', 16))
  491. @ut.skipIf('shuffle' not in h5py.filters.encode, "SHUFFLE is not installed")
  492. class TestCreateShuffle(BaseDataset):
  493. """
  494. Feature: Datasets can use shuffling filter
  495. """
  496. def test_shuffle(self):
  497. """ Enable shuffle filter """
  498. dset = self.f.create_dataset('foo', (20, 30), shuffle=True)
  499. self.assertTrue(dset.shuffle)
  500. @ut.skipIf('fletcher32' not in h5py.filters.encode, "FLETCHER32 is not installed")
  501. class TestCreateFletcher32(BaseDataset):
  502. """
  503. Feature: Datasets can use the fletcher32 filter
  504. """
  505. def test_fletcher32(self):
  506. """ Enable fletcher32 filter """
  507. dset = self.f.create_dataset('foo', (20, 30), fletcher32=True)
  508. self.assertTrue(dset.fletcher32)
  509. @ut.skipIf('scaleoffset' not in h5py.filters.encode, "SCALEOFFSET is not installed")
  510. class TestCreateScaleOffset(BaseDataset):
  511. """
  512. Feature: Datasets can use the scale/offset filter
  513. """
  514. def test_float_fails_without_options(self):
  515. """ Ensure that a scale factor is required for scaleoffset compression of floating point data """
  516. with self.assertRaises(ValueError):
  517. dset = self.f.create_dataset('foo', (20, 30), dtype=float, scaleoffset=True)
  518. def test_non_integer(self):
  519. """ Check when scaleoffset is negetive"""
  520. with self.assertRaises(ValueError):
  521. dset = self.f.create_dataset('foo', (20, 30), dtype=float, scaleoffset=-0.1)
  522. def test_unsupport_dtype(self):
  523. """ Check when dtype is unsupported type"""
  524. with self.assertRaises(TypeError):
  525. dset = self.f.create_dataset('foo', (20, 30), dtype=bool, scaleoffset=True)
  526. def test_float(self):
  527. """ Scaleoffset filter works for floating point data """
  528. scalefac = 4
  529. shape = (100, 300)
  530. range = 20 * 10 ** scalefac
  531. testdata = (np.random.rand(*shape) - 0.5) * range
  532. dset = self.f.create_dataset('foo', shape, dtype=float, scaleoffset=scalefac)
  533. # Dataset reports that scaleoffset is in use
  534. assert dset.scaleoffset is not None
  535. # Dataset round-trips
  536. dset[...] = testdata
  537. filename = self.f.filename
  538. self.f.close()
  539. self.f = h5py.File(filename, 'r')
  540. readdata = self.f['foo'][...]
  541. # Test that data round-trips to requested precision
  542. self.assertArrayEqual(readdata, testdata, precision=10 ** (-scalefac))
  543. # Test that the filter is actually active (i.e. compression is lossy)
  544. assert not (readdata == testdata).all()
  545. def test_int(self):
  546. """ Scaleoffset filter works for integer data with default precision """
  547. nbits = 12
  548. shape = (100, 300)
  549. testdata = np.random.randint(0, 2 ** nbits - 1, size=shape)
  550. # Create dataset; note omission of nbits (for library-determined precision)
  551. dset = self.f.create_dataset('foo', shape, dtype=int, scaleoffset=True)
  552. # Dataset reports scaleoffset enabled
  553. assert dset.scaleoffset is not None
  554. # Data round-trips correctly and identically
  555. dset[...] = testdata
  556. filename = self.f.filename
  557. self.f.close()
  558. self.f = h5py.File(filename, 'r')
  559. readdata = self.f['foo'][...]
  560. self.assertArrayEqual(readdata, testdata)
  561. def test_int_with_minbits(self):
  562. """ Scaleoffset filter works for integer data with specified precision """
  563. nbits = 12
  564. shape = (100, 300)
  565. testdata = np.random.randint(0, 2 ** nbits, size=shape)
  566. dset = self.f.create_dataset('foo', shape, dtype=int, scaleoffset=nbits)
  567. # Dataset reports scaleoffset enabled with correct precision
  568. self.assertTrue(dset.scaleoffset == 12)
  569. # Data round-trips correctly
  570. dset[...] = testdata
  571. filename = self.f.filename
  572. self.f.close()
  573. self.f = h5py.File(filename, 'r')
  574. readdata = self.f['foo'][...]
  575. self.assertArrayEqual(readdata, testdata)
  576. def test_int_with_minbits_lossy(self):
  577. """ Scaleoffset filter works for integer data with specified precision """
  578. nbits = 12
  579. shape = (100, 300)
  580. testdata = np.random.randint(0, 2 ** (nbits + 1) - 1, size=shape)
  581. dset = self.f.create_dataset('foo', shape, dtype=int, scaleoffset=nbits)
  582. # Dataset reports scaleoffset enabled with correct precision
  583. self.assertTrue(dset.scaleoffset == 12)
  584. # Data can be written and read
  585. dset[...] = testdata
  586. filename = self.f.filename
  587. self.f.close()
  588. self.f = h5py.File(filename, 'r')
  589. readdata = self.f['foo'][...]
  590. # Compression is lossy
  591. assert not (readdata == testdata).all()
  592. class TestExternal(BaseDataset):
  593. """
  594. Feature: Datasets with the external storage property
  595. """
  596. def test_contents(self):
  597. """ Create and access an external dataset """
  598. shape = (6, 100)
  599. testdata = np.random.random(shape)
  600. # create a dataset in an external file and set it
  601. ext_file = self.mktemp()
  602. external = [(ext_file, 0, h5f.UNLIMITED)]
  603. dset = self.f.create_dataset('foo', shape, dtype=testdata.dtype, external=external)
  604. dset[...] = testdata
  605. assert dset.external is not None
  606. # verify file's existence, size, and contents
  607. with open(ext_file, 'rb') as fid:
  608. contents = fid.read()
  609. assert contents == testdata.tobytes()
  610. def test_name_str(self):
  611. """ External argument may be a file name str only """
  612. self.f.create_dataset('foo', (6, 100), external=self.mktemp())
  613. def test_name_path(self):
  614. """ External argument may be a file name path only """
  615. self.f.create_dataset('foo', (6, 100),
  616. external=pathlib.Path(self.mktemp()))
  617. def test_iter_multi(self):
  618. """ External argument may be an iterable of multiple tuples """
  619. ext_file = self.mktemp()
  620. N = 100
  621. external = iter((ext_file, x * 1000, 1000) for x in range(N))
  622. dset = self.f.create_dataset('poo', (6, 100), external=external)
  623. assert len(dset.external) == N
  624. def test_invalid(self):
  625. """ Test with invalid external lists """
  626. shape = (6, 100)
  627. ext_file = self.mktemp()
  628. for exc_type, external in [
  629. (TypeError, [ext_file]),
  630. (TypeError, [ext_file, 0]),
  631. (TypeError, [ext_file, 0, h5f.UNLIMITED]),
  632. (ValueError, [(ext_file,)]),
  633. (ValueError, [(ext_file, 0)]),
  634. (ValueError, [(ext_file, 0, h5f.UNLIMITED, 0)]),
  635. (TypeError, [(ext_file, 0, "h5f.UNLIMITED")]),
  636. ]:
  637. with self.assertRaises(exc_type):
  638. self.f.create_dataset('foo', shape, external=external)
  639. class TestAutoCreate(BaseDataset):
  640. """
  641. Feature: Datasets auto-created from data produce the correct types
  642. """
  643. def assert_string_type(self, ds, cset, variable=True):
  644. tid = ds.id.get_type()
  645. self.assertEqual(type(tid), h5py.h5t.TypeStringID)
  646. self.assertEqual(tid.get_cset(), cset)
  647. if variable:
  648. assert tid.is_variable_str()
  649. def test_vlen_bytes(self):
  650. """Assigning byte strings produces a vlen string ASCII dataset """
  651. self.f['x'] = b"Hello there"
  652. self.assert_string_type(self.f['x'], h5py.h5t.CSET_ASCII)
  653. self.f['y'] = [b"a", b"bc"]
  654. self.assert_string_type(self.f['y'], h5py.h5t.CSET_ASCII)
  655. self.f['z'] = np.array([b"a", b"bc"], dtype=np.object_)
  656. self.assert_string_type(self.f['z'], h5py.h5t.CSET_ASCII)
  657. def test_vlen_unicode(self):
  658. """Assigning unicode strings produces a vlen string UTF-8 dataset """
  659. self.f['x'] = "Hello there" + chr(0x2034)
  660. self.assert_string_type(self.f['x'], h5py.h5t.CSET_UTF8)
  661. self.f['y'] = ["a", "bc"]
  662. self.assert_string_type(self.f['y'], h5py.h5t.CSET_UTF8)
  663. # 2D array; this only works with an array, not nested lists
  664. self.f['z'] = np.array([["a", "bc"]], dtype=np.object_)
  665. self.assert_string_type(self.f['z'], h5py.h5t.CSET_UTF8)
  666. def test_string_fixed(self):
  667. """ Assignment of fixed-length byte string produces a fixed-length
  668. ascii dataset """
  669. self.f['x'] = np.string_("Hello there")
  670. ds = self.f['x']
  671. self.assert_string_type(ds, h5py.h5t.CSET_ASCII, variable=False)
  672. self.assertEqual(ds.id.get_type().get_size(), 11)
  673. class TestCreateLike(BaseDataset):
  674. def test_no_chunks(self):
  675. self.f['lol'] = np.arange(25).reshape(5, 5)
  676. self.f.create_dataset_like('like_lol', self.f['lol'])
  677. dslike = self.f['like_lol']
  678. self.assertEqual(dslike.shape, (5, 5))
  679. self.assertIs(dslike.chunks, None)
  680. def test_track_times(self):
  681. orig = self.f.create_dataset('honda', data=np.arange(12),
  682. track_times=True)
  683. self.assertNotEqual(0, h5py.h5g.get_objinfo(orig._id).mtime)
  684. similar = self.f.create_dataset_like('hyundai', orig)
  685. self.assertNotEqual(0, h5py.h5g.get_objinfo(similar._id).mtime)
  686. orig = self.f.create_dataset('ibm', data=np.arange(12),
  687. track_times=False)
  688. self.assertEqual(0, h5py.h5g.get_objinfo(orig._id).mtime)
  689. similar = self.f.create_dataset_like('lenovo', orig)
  690. self.assertEqual(0, h5py.h5g.get_objinfo(similar._id).mtime)
  691. def test_maxshape(self):
  692. """ Test when other.maxshape != other.shape """
  693. other = self.f.create_dataset('other', (10,), maxshape=20)
  694. similar = self.f.create_dataset_like('sim', other)
  695. self.assertEqual(similar.shape, (10,))
  696. self.assertEqual(similar.maxshape, (20,))
  697. class TestChunkIterator(BaseDataset):
  698. def test_no_chunks(self):
  699. dset = self.f.create_dataset("foo", ())
  700. with self.assertRaises(TypeError):
  701. dset.iter_chunks()
  702. def test_1d(self):
  703. dset = self.f.create_dataset("foo", (100,), chunks=(32,))
  704. expected = ((slice(0,32,1),), (slice(32,64,1),), (slice(64,96,1),),
  705. (slice(96,100,1),))
  706. self.assertEqual(list(dset.iter_chunks()), list(expected))
  707. expected = ((slice(50,64,1),), (slice(64,96,1),), (slice(96,97,1),))
  708. self.assertEqual(list(dset.iter_chunks(np.s_[50:97])), list(expected))
  709. def test_2d(self):
  710. dset = self.f.create_dataset("foo", (100,100), chunks=(32,64))
  711. expected = ((slice(0, 32, 1), slice(0, 64, 1)), (slice(0, 32, 1),
  712. slice(64, 100, 1)), (slice(32, 64, 1), slice(0, 64, 1)),
  713. (slice(32, 64, 1), slice(64, 100, 1)), (slice(64, 96, 1),
  714. slice(0, 64, 1)), (slice(64, 96, 1), slice(64, 100, 1)),
  715. (slice(96, 100, 1), slice(0, 64, 1)), (slice(96, 100, 1),
  716. slice(64, 100, 1)))
  717. self.assertEqual(list(dset.iter_chunks()), list(expected))
  718. expected = ((slice(48, 52, 1), slice(40, 50, 1)),)
  719. self.assertEqual(list(dset.iter_chunks(np.s_[48:52,40:50])), list(expected))
  720. class TestResize(BaseDataset):
  721. """
  722. Feature: Datasets created with "maxshape" may be resized
  723. """
  724. def test_create(self):
  725. """ Create dataset with "maxshape" """
  726. dset = self.f.create_dataset('foo', (20, 30), maxshape=(20, 60))
  727. self.assertIsNot(dset.chunks, None)
  728. self.assertEqual(dset.maxshape, (20, 60))
  729. def test_create_1D(self):
  730. """ Create dataset with "maxshape" using integer maxshape"""
  731. dset = self.f.create_dataset('foo', (20,), maxshape=20)
  732. self.assertIsNot(dset.chunks, None)
  733. self.assertEqual(dset.maxshape, (20,))
  734. dset = self.f.create_dataset('bar', 20, maxshape=20)
  735. self.assertEqual(dset.maxshape, (20,))
  736. def test_resize(self):
  737. """ Datasets may be resized up to maxshape """
  738. dset = self.f.create_dataset('foo', (20, 30), maxshape=(20, 60))
  739. self.assertEqual(dset.shape, (20, 30))
  740. dset.resize((20, 50))
  741. self.assertEqual(dset.shape, (20, 50))
  742. dset.resize((20, 60))
  743. self.assertEqual(dset.shape, (20, 60))
  744. def test_resize_1D(self):
  745. """ Datasets may be resized up to maxshape using integer maxshape"""
  746. dset = self.f.create_dataset('foo', 20, maxshape=40)
  747. self.assertEqual(dset.shape, (20,))
  748. dset.resize((30,))
  749. self.assertEqual(dset.shape, (30,))
  750. def test_resize_over(self):
  751. """ Resizing past maxshape triggers an exception """
  752. dset = self.f.create_dataset('foo', (20, 30), maxshape=(20, 60))
  753. with self.assertRaises(Exception):
  754. dset.resize((20, 70))
  755. def test_resize_nonchunked(self):
  756. """ Resizing non-chunked dataset raises TypeError """
  757. dset = self.f.create_dataset("foo", (20, 30))
  758. with self.assertRaises(TypeError):
  759. dset.resize((20, 60))
  760. def test_resize_axis(self):
  761. """ Resize specified axis """
  762. dset = self.f.create_dataset('foo', (20, 30), maxshape=(20, 60))
  763. dset.resize(50, axis=1)
  764. self.assertEqual(dset.shape, (20, 50))
  765. def test_axis_exc(self):
  766. """ Illegal axis raises ValueError """
  767. dset = self.f.create_dataset('foo', (20, 30), maxshape=(20, 60))
  768. with self.assertRaises(ValueError):
  769. dset.resize(50, axis=2)
  770. def test_zero_dim(self):
  771. """ Allow zero-length initial dims for unlimited axes (issue 111) """
  772. dset = self.f.create_dataset('foo', (15, 0), maxshape=(15, None))
  773. self.assertEqual(dset.shape, (15, 0))
  774. self.assertEqual(dset.maxshape, (15, None))
  775. class TestDtype(BaseDataset):
  776. """
  777. Feature: Dataset dtype is available as .dtype property
  778. """
  779. def test_dtype(self):
  780. """ Retrieve dtype from dataset """
  781. dset = self.f.create_dataset('foo', (5,), '|S10')
  782. self.assertEqual(dset.dtype, np.dtype('|S10'))
  783. class TestLen(BaseDataset):
  784. """
  785. Feature: Size of first axis is available via Python's len
  786. """
  787. def test_len(self):
  788. """ Python len() (under 32 bits) """
  789. dset = self.f.create_dataset('foo', (312, 15))
  790. self.assertEqual(len(dset), 312)
  791. def test_len_big(self):
  792. """ Python len() vs Dataset.len() """
  793. dset = self.f.create_dataset('foo', (2 ** 33, 15))
  794. self.assertEqual(dset.shape, (2 ** 33, 15))
  795. if sys.maxsize == 2 ** 31 - 1:
  796. with self.assertRaises(OverflowError):
  797. len(dset)
  798. else:
  799. self.assertEqual(len(dset), 2 ** 33)
  800. self.assertEqual(dset.len(), 2 ** 33)
  801. class TestIter(BaseDataset):
  802. """
  803. Feature: Iterating over a dataset yields rows
  804. """
  805. def test_iter(self):
  806. """ Iterating over a dataset yields rows """
  807. data = np.arange(30, dtype='f').reshape((10, 3))
  808. dset = self.f.create_dataset('foo', data=data)
  809. for x, y in zip(dset, data):
  810. self.assertEqual(len(x), 3)
  811. self.assertArrayEqual(x, y)
  812. def test_iter_scalar(self):
  813. """ Iterating over scalar dataset raises TypeError """
  814. dset = self.f.create_dataset('foo', shape=())
  815. with self.assertRaises(TypeError):
  816. [x for x in dset]
  817. class TestStrings(BaseDataset):
  818. """
  819. Feature: Datasets created with vlen and fixed datatypes correctly
  820. translate to and from HDF5
  821. """
  822. def test_vlen_bytes(self):
  823. """ Vlen bytes dataset maps to vlen ascii in the file """
  824. dt = h5py.string_dtype(encoding='ascii')
  825. ds = self.f.create_dataset('x', (100,), dtype=dt)
  826. tid = ds.id.get_type()
  827. self.assertEqual(type(tid), h5py.h5t.TypeStringID)
  828. self.assertEqual(tid.get_cset(), h5py.h5t.CSET_ASCII)
  829. string_info = h5py.check_string_dtype(ds.dtype)
  830. self.assertEqual(string_info.encoding, 'ascii')
  831. def test_vlen_unicode(self):
  832. """ Vlen unicode dataset maps to vlen utf-8 in the file """
  833. dt = h5py.string_dtype()
  834. ds = self.f.create_dataset('x', (100,), dtype=dt)
  835. tid = ds.id.get_type()
  836. self.assertEqual(type(tid), h5py.h5t.TypeStringID)
  837. self.assertEqual(tid.get_cset(), h5py.h5t.CSET_UTF8)
  838. string_info = h5py.check_string_dtype(ds.dtype)
  839. self.assertEqual(string_info.encoding, 'utf-8')
  840. def test_fixed_ascii(self):
  841. """ Fixed-length bytes dataset maps to fixed-length ascii in the file
  842. """
  843. dt = np.dtype("|S10")
  844. ds = self.f.create_dataset('x', (100,), dtype=dt)
  845. tid = ds.id.get_type()
  846. self.assertEqual(type(tid), h5py.h5t.TypeStringID)
  847. self.assertFalse(tid.is_variable_str())
  848. self.assertEqual(tid.get_size(), 10)
  849. self.assertEqual(tid.get_cset(), h5py.h5t.CSET_ASCII)
  850. string_info = h5py.check_string_dtype(ds.dtype)
  851. self.assertEqual(string_info.encoding, 'ascii')
  852. self.assertEqual(string_info.length, 10)
  853. def test_fixed_utf8(self):
  854. dt = h5py.string_dtype(encoding='utf-8', length=5)
  855. ds = self.f.create_dataset('x', (100,), dtype=dt)
  856. tid = ds.id.get_type()
  857. self.assertEqual(tid.get_cset(), h5py.h5t.CSET_UTF8)
  858. s = 'cù'
  859. ds[0] = s.encode('utf-8')
  860. ds[1] = s
  861. ds[2:4] = [s, s]
  862. ds[4:6] = np.array([s, s], dtype=object)
  863. ds[6:8] = np.array([s.encode('utf-8')] * 2, dtype=dt)
  864. with self.assertRaises(TypeError):
  865. ds[8:10] = np.array([s, s], dtype='U')
  866. np.testing.assert_array_equal(ds[:8], np.array([s.encode('utf-8')] * 8, dtype='S'))
  867. def test_fixed_unicode(self):
  868. """ Fixed-length unicode datasets are unsupported (raise TypeError) """
  869. dt = np.dtype("|U10")
  870. with self.assertRaises(TypeError):
  871. ds = self.f.create_dataset('x', (100,), dtype=dt)
  872. def test_roundtrip_vlen_bytes(self):
  873. """ writing and reading to vlen bytes dataset preserves type and content
  874. """
  875. dt = h5py.string_dtype(encoding='ascii')
  876. ds = self.f.create_dataset('x', (100,), dtype=dt)
  877. data = b"Hello\xef"
  878. ds[0] = data
  879. out = ds[0]
  880. self.assertEqual(type(out), bytes)
  881. self.assertEqual(out, data)
  882. def test_roundtrip_fixed_bytes(self):
  883. """ Writing to and reading from fixed-length bytes dataset preserves
  884. type and content """
  885. dt = np.dtype("|S10")
  886. ds = self.f.create_dataset('x', (100,), dtype=dt)
  887. data = b"Hello\xef"
  888. ds[0] = data
  889. out = ds[0]
  890. self.assertEqual(type(out), np.string_)
  891. self.assertEqual(out, data)
  892. def test_retrieve_vlen_unicode(self):
  893. dt = h5py.string_dtype()
  894. ds = self.f.create_dataset('x', (10,), dtype=dt)
  895. data = "fàilte"
  896. ds[0] = data
  897. self.assertIsInstance(ds[0], bytes)
  898. out = ds.asstr()[0]
  899. self.assertIsInstance(out, str)
  900. self.assertEqual(out, data)
  901. def test_asstr(self):
  902. ds = self.f.create_dataset('x', (10,), dtype=h5py.string_dtype())
  903. data = "fàilte"
  904. ds[0] = data
  905. strwrap1 = ds.asstr('ascii')
  906. with self.assertRaises(UnicodeDecodeError):
  907. out = strwrap1[0]
  908. # Different errors parameter
  909. self.assertEqual(ds.asstr('ascii', 'ignore')[0], 'filte')
  910. # latin-1 will decode it but give the wrong text
  911. self.assertNotEqual(ds.asstr('latin-1')[0], data)
  912. # Array output
  913. np.testing.assert_array_equal(
  914. ds.asstr()[:1], np.array([data], dtype=object)
  915. )
  916. def test_asstr_fixed(self):
  917. dt = h5py.string_dtype(length=5)
  918. ds = self.f.create_dataset('x', (10,), dtype=dt)
  919. data = 'cù'
  920. ds[0] = np.array(data.encode('utf-8'), dtype=dt)
  921. self.assertIsInstance(ds[0], np.bytes_)
  922. out = ds.asstr()[0]
  923. self.assertIsInstance(out, str)
  924. self.assertEqual(out, data)
  925. # Different errors parameter
  926. self.assertEqual(ds.asstr('ascii', 'ignore')[0], 'c')
  927. # latin-1 will decode it but give the wrong text
  928. self.assertNotEqual(ds.asstr('latin-1')[0], data)
  929. # Array output
  930. np.testing.assert_array_equal(
  931. ds.asstr()[:1], np.array([data], dtype=object)
  932. )
  933. def test_unicode_write_error(self):
  934. """Encoding error when writing a non-ASCII string to an ASCII vlen dataset"""
  935. dt = h5py.string_dtype('ascii')
  936. ds = self.f.create_dataset('x', (100,), dtype=dt)
  937. data = "fàilte"
  938. with self.assertRaises(UnicodeEncodeError):
  939. ds[0] = data
  940. def test_unicode_write_bytes(self):
  941. """ Writing valid utf-8 byte strings to a unicode vlen dataset is OK
  942. """
  943. dt = h5py.string_dtype()
  944. ds = self.f.create_dataset('x', (100,), dtype=dt)
  945. data = (u"Hello there" + chr(0x2034)).encode('utf8')
  946. ds[0] = data
  947. out = ds[0]
  948. self.assertEqual(type(out), bytes)
  949. self.assertEqual(out, data)
  950. def test_vlen_bytes_write_ascii_str(self):
  951. """ Writing an ascii str to ascii vlen dataset is OK
  952. """
  953. dt = h5py.string_dtype('ascii')
  954. ds = self.f.create_dataset('x', (100,), dtype=dt)
  955. data = "ASCII string"
  956. ds[0] = data
  957. out = ds[0]
  958. self.assertEqual(type(out), bytes)
  959. self.assertEqual(out, data.encode('ascii'))
  960. class TestCompound(BaseDataset):
  961. """
  962. Feature: Compound types correctly round-trip
  963. """
  964. def test_rt(self):
  965. """ Compound types are read back in correct order (issue 236)"""
  966. dt = np.dtype([ ('weight', np.float64),
  967. ('cputime', np.float64),
  968. ('walltime', np.float64),
  969. ('parents_offset', np.uint32),
  970. ('n_parents', np.uint32),
  971. ('status', np.uint8),
  972. ('endpoint_type', np.uint8), ])
  973. testdata = np.ndarray((16,), dtype=dt)
  974. for key in dt.fields:
  975. testdata[key] = np.random.random((16,)) * 100
  976. self.f['test'] = testdata
  977. outdata = self.f['test'][...]
  978. self.assertTrue(np.all(outdata == testdata))
  979. self.assertEqual(outdata.dtype, testdata.dtype)
  980. def test_assign(self):
  981. dt = np.dtype([ ('weight', (np.float64, 3)),
  982. ('endpoint_type', np.uint8), ])
  983. testdata = np.ndarray((16,), dtype=dt)
  984. for key in dt.fields:
  985. testdata[key] = np.random.random(size=testdata[key].shape) * 100
  986. ds = self.f.create_dataset('test', (16,), dtype=dt)
  987. for key in dt.fields:
  988. ds[key] = testdata[key]
  989. outdata = self.f['test'][...]
  990. self.assertTrue(np.all(outdata == testdata))
  991. self.assertEqual(outdata.dtype, testdata.dtype)
  992. def test_fields(self):
  993. dt = np.dtype([
  994. ('x', np.float64),
  995. ('y', np.float64),
  996. ('z', np.float64),
  997. ])
  998. testdata = np.ndarray((16,), dtype=dt)
  999. for key in dt.fields:
  1000. testdata[key] = np.random.random((16,)) * 100
  1001. self.f['test'] = testdata
  1002. # Extract multiple fields
  1003. np.testing.assert_array_equal(
  1004. self.f['test'].fields(['x', 'y'])[:], testdata[['x', 'y']]
  1005. )
  1006. # Extract single field
  1007. np.testing.assert_array_equal(
  1008. self.f['test'].fields('x')[:], testdata['x']
  1009. )
  1010. class TestSubarray(BaseDataset):
  1011. def test_write_list(self):
  1012. ds = self.f.create_dataset("a", (1,), dtype="3int8")
  1013. ds[0] = [1, 2, 3]
  1014. np.testing.assert_array_equal(ds[:], [[1, 2, 3]])
  1015. ds[:] = [[4, 5, 6]]
  1016. np.testing.assert_array_equal(ds[:], [[4, 5, 6]])
  1017. def test_write_array(self):
  1018. ds = self.f.create_dataset("a", (1,), dtype="3int8")
  1019. ds[0] = np.array([1, 2, 3])
  1020. np.testing.assert_array_equal(ds[:], [[1, 2, 3]])
  1021. ds[:] = np.array([[4, 5, 6]])
  1022. np.testing.assert_array_equal(ds[:], [[4, 5, 6]])
  1023. class TestEnum(BaseDataset):
  1024. """
  1025. Feature: Enum datatype info is preserved, read/write as integer
  1026. """
  1027. EDICT = {'RED': 0, 'GREEN': 1, 'BLUE': 42}
  1028. def test_create(self):
  1029. """ Enum datasets can be created and type correctly round-trips """
  1030. dt = h5py.enum_dtype(self.EDICT, basetype='i')
  1031. ds = self.f.create_dataset('x', (100, 100), dtype=dt)
  1032. dt2 = ds.dtype
  1033. dict2 = h5py.check_enum_dtype(dt2)
  1034. self.assertEqual(dict2, self.EDICT)
  1035. def test_readwrite(self):
  1036. """ Enum datasets can be read/written as integers """
  1037. dt = h5py.enum_dtype(self.EDICT, basetype='i4')
  1038. ds = self.f.create_dataset('x', (100, 100), dtype=dt)
  1039. ds[35, 37] = 42
  1040. ds[1, :] = 1
  1041. self.assertEqual(ds[35, 37], 42)
  1042. self.assertArrayEqual(ds[1, :], np.array((1,) * 100, dtype='i4'))
  1043. class TestFloats(BaseDataset):
  1044. """
  1045. Test support for mini and extended-precision floats
  1046. """
  1047. def _exectest(self, dt):
  1048. dset = self.f.create_dataset('x', (100,), dtype=dt)
  1049. self.assertEqual(dset.dtype, dt)
  1050. data = np.ones((100,), dtype=dt)
  1051. dset[...] = data
  1052. self.assertArrayEqual(dset[...], data)
  1053. @ut.skipUnless(hasattr(np, 'float16'), "NumPy float16 support required")
  1054. def test_mini(self):
  1055. """ Mini-floats round trip """
  1056. self._exectest(np.dtype('float16'))
  1057. # TODO: move these tests to test_h5t
  1058. def test_mini_mapping(self):
  1059. """ Test mapping for float16 """
  1060. if hasattr(np, 'float16'):
  1061. self.assertEqual(h5t.IEEE_F16LE.dtype, np.dtype('<f2'))
  1062. else:
  1063. self.assertEqual(h5t.IEEE_F16LE.dtype, np.dtype('<f4'))
  1064. class TestTrackTimes(BaseDataset):
  1065. """
  1066. Feature: track_times
  1067. """
  1068. def test_disable_track_times(self):
  1069. """ check that when track_times=False, the time stamp=0 (Jan 1, 1970) """
  1070. ds = self.f.create_dataset('foo', (4,), track_times=False)
  1071. ds_mtime = h5py.h5g.get_objinfo(ds._id).mtime
  1072. self.assertEqual(0, ds_mtime)
  1073. def test_invalid_track_times(self):
  1074. """ check that when give track_times an invalid value """
  1075. with self.assertRaises(TypeError):
  1076. self.f.create_dataset('foo', (4,), track_times='null')
  1077. class TestZeroShape(BaseDataset):
  1078. """
  1079. Features of datasets with (0,)-shape axes
  1080. """
  1081. def test_array_conversion(self):
  1082. """ Empty datasets can be converted to NumPy arrays """
  1083. ds = self.f.create_dataset('x', 0, maxshape=None)
  1084. self.assertEqual(ds.shape, np.array(ds).shape)
  1085. ds = self.f.create_dataset('y', (0,), maxshape=(None,))
  1086. self.assertEqual(ds.shape, np.array(ds).shape)
  1087. ds = self.f.create_dataset('z', (0, 0), maxshape=(None, None))
  1088. self.assertEqual(ds.shape, np.array(ds).shape)
  1089. def test_reading(self):
  1090. """ Slicing into empty datasets works correctly """
  1091. dt = [('a', 'f'), ('b', 'i')]
  1092. ds = self.f.create_dataset('x', (0,), dtype=dt, maxshape=(None,))
  1093. arr = np.empty((0,), dtype=dt)
  1094. self.assertEqual(ds[...].shape, arr.shape)
  1095. self.assertEqual(ds[...].dtype, arr.dtype)
  1096. self.assertEqual(ds[()].shape, arr.shape)
  1097. self.assertEqual(ds[()].dtype, arr.dtype)
  1098. # https://github.com/h5py/h5py/issues/1492
  1099. empty_regionref_xfail = pytest.mark.xfail(
  1100. h5py.version.hdf5_version_tuple == (1, 10, 6),
  1101. reason="Issue with empty region refs in HDF5 1.10.6",
  1102. )
  1103. class TestRegionRefs(BaseDataset):
  1104. """
  1105. Various features of region references
  1106. """
  1107. def setUp(self):
  1108. BaseDataset.setUp(self)
  1109. self.data = np.arange(100 * 100).reshape((100, 100))
  1110. self.dset = self.f.create_dataset('x', data=self.data)
  1111. self.dset[...] = self.data
  1112. def test_create_ref(self):
  1113. """ Region references can be used as slicing arguments """
  1114. slic = np.s_[25:35, 10:100:5]
  1115. ref = self.dset.regionref[slic]
  1116. self.assertArrayEqual(self.dset[ref], self.data[slic])
  1117. @empty_regionref_xfail
  1118. def test_empty_region(self):
  1119. ref = self.dset.regionref[:0]
  1120. out = self.dset[ref]
  1121. assert out.size == 0
  1122. # Ideally we should preserve shape (0, 100), but it seems this is lost.
  1123. @empty_regionref_xfail
  1124. def test_scalar_dataset(self):
  1125. ds = self.f.create_dataset("scalar", data=1.0, dtype='f4')
  1126. sid = h5py.h5s.create(h5py.h5s.SCALAR)
  1127. # Deselected
  1128. sid.select_none()
  1129. ref = h5py.h5r.create(ds.id, b'.', h5py.h5r.DATASET_REGION, sid)
  1130. assert ds[ref] == h5py.Empty(np.dtype('f4'))
  1131. # Selected
  1132. sid.select_all()
  1133. ref = h5py.h5r.create(ds.id, b'.', h5py.h5r.DATASET_REGION, sid)
  1134. assert ds[ref] == ds[()]
  1135. def test_ref_shape(self):
  1136. """ Region reference shape and selection shape """
  1137. slic = np.s_[25:35, 10:100:5]
  1138. ref = self.dset.regionref[slic]
  1139. self.assertEqual(self.dset.regionref.shape(ref), self.dset.shape)
  1140. self.assertEqual(self.dset.regionref.selection(ref), (10, 18))
  1141. class TestAstype(BaseDataset):
  1142. """.astype() wrapper & context manager
  1143. """
  1144. def test_astype_ctx(self):
  1145. dset = self.f.create_dataset('x', (100,), dtype='i2')
  1146. dset[...] = np.arange(100)
  1147. with dset.astype('f8'):
  1148. self.assertArrayEqual(dset[...], np.arange(100, dtype='f8'))
  1149. with dset.astype('f4') as f4ds:
  1150. self.assertArrayEqual(f4ds[...], np.arange(100, dtype='f4'))
  1151. def test_astype_wrapper(self):
  1152. dset = self.f.create_dataset('x', (100,), dtype='i2')
  1153. dset[...] = np.arange(100)
  1154. arr = dset.astype('f4')[:]
  1155. self.assertArrayEqual(arr, np.arange(100, dtype='f4'))
  1156. class TestScalarCompound(BaseDataset):
  1157. """
  1158. Retrieval of a single field from a scalar compound dataset should
  1159. strip the field info
  1160. """
  1161. def test_scalar_compound(self):
  1162. dt = np.dtype([('a', 'i')])
  1163. dset = self.f.create_dataset('x', (), dtype=dt)
  1164. self.assertEqual(dset['a'].dtype, np.dtype('i'))
  1165. class TestVlen(BaseDataset):
  1166. def test_int(self):
  1167. dt = h5py.vlen_dtype(int)
  1168. ds = self.f.create_dataset('vlen', (4,), dtype=dt)
  1169. ds[0] = np.arange(3)
  1170. ds[1] = np.arange(0)
  1171. ds[2] = [1, 2, 3]
  1172. ds[3] = np.arange(1)
  1173. self.assertArrayEqual(ds[0], np.arange(3))
  1174. self.assertArrayEqual(ds[1], np.arange(0))
  1175. self.assertArrayEqual(ds[2], np.array([1, 2, 3]))
  1176. self.assertArrayEqual(ds[1], np.arange(0))
  1177. ds[0:2] = np.array([np.arange(5), np.arange(4)], dtype=object)
  1178. self.assertArrayEqual(ds[0], np.arange(5))
  1179. self.assertArrayEqual(ds[1], np.arange(4))
  1180. ds[0:2] = np.array([np.arange(3), np.arange(3)])
  1181. self.assertArrayEqual(ds[0], np.arange(3))
  1182. self.assertArrayEqual(ds[1], np.arange(3))
  1183. def test_reuse_from_other(self):
  1184. dt = h5py.vlen_dtype(int)
  1185. ds = self.f.create_dataset('vlen', (1,), dtype=dt)
  1186. self.f.create_dataset('vlen2', (1,), ds[()].dtype)
  1187. def test_reuse_struct_from_other(self):
  1188. dt = [('a', int), ('b', h5py.vlen_dtype(int))]
  1189. ds = self.f.create_dataset('vlen', (1,), dtype=dt)
  1190. fname = self.f.filename
  1191. self.f.close()
  1192. self.f = h5py.File(fname, 'a')
  1193. self.f.create_dataset('vlen2', (1,), self.f['vlen']['b'][()].dtype)
  1194. def test_convert(self):
  1195. dt = h5py.vlen_dtype(int)
  1196. ds = self.f.create_dataset('vlen', (3,), dtype=dt)
  1197. ds[0] = np.array([1.4, 1.2])
  1198. ds[1] = np.array([1.2])
  1199. ds[2] = [1.2, 2, 3]
  1200. self.assertArrayEqual(ds[0], np.array([1, 1]))
  1201. self.assertArrayEqual(ds[1], np.array([1]))
  1202. self.assertArrayEqual(ds[2], np.array([1, 2, 3]))
  1203. ds[0:2] = np.array([[0.1, 1.1, 2.1, 3.1, 4], np.arange(4)], dtype=object)
  1204. self.assertArrayEqual(ds[0], np.arange(5))
  1205. self.assertArrayEqual(ds[1], np.arange(4))
  1206. ds[0:2] = np.array([np.array([0.1, 1.2, 2.2]),
  1207. np.array([0.2, 1.2, 2.2])])
  1208. self.assertArrayEqual(ds[0], np.arange(3))
  1209. self.assertArrayEqual(ds[1], np.arange(3))
  1210. def test_multidim(self):
  1211. dt = h5py.vlen_dtype(int)
  1212. ds = self.f.create_dataset('vlen', (2, 2), dtype=dt)
  1213. ds[0, 0] = np.arange(1)
  1214. ds[:, :] = np.array([[np.arange(3), np.arange(2)],
  1215. [np.arange(1), np.arange(2)]], dtype=object)
  1216. ds[:, :] = np.array([[np.arange(2), np.arange(2)],
  1217. [np.arange(2), np.arange(2)]])
  1218. def _help_float_testing(self, np_dt, dataset_name='vlen'):
  1219. """
  1220. Helper for testing various vlen numpy data types.
  1221. :param np_dt: Numpy datatype to test
  1222. :param dataset_name: String name of the dataset to create for testing.
  1223. """
  1224. dt = h5py.vlen_dtype(np_dt)
  1225. ds = self.f.create_dataset(dataset_name, (5,), dtype=dt)
  1226. # Create some arrays, and assign them to the dataset
  1227. array_0 = np.array([1., 2., 30.], dtype=np_dt)
  1228. array_1 = np.array([100.3, 200.4, 98.1, -10.5, -300.0], dtype=np_dt)
  1229. # Test that a numpy array of different type gets cast correctly
  1230. array_2 = np.array([1, 2, 8], dtype=np.dtype('int32'))
  1231. casted_array_2 = array_2.astype(np_dt)
  1232. # Test that we can set a list of floats.
  1233. list_3 = [1., 2., 900., 0., -0.5]
  1234. list_array_3 = np.array(list_3, dtype=np_dt)
  1235. # Test that a list of integers gets casted correctly
  1236. list_4 = [-1, -100, 0, 1, 9999, 70]
  1237. list_array_4 = np.array(list_4, dtype=np_dt)
  1238. ds[0] = array_0
  1239. ds[1] = array_1
  1240. ds[2] = array_2
  1241. ds[3] = list_3
  1242. ds[4] = list_4
  1243. self.assertArrayEqual(array_0, ds[0])
  1244. self.assertArrayEqual(array_1, ds[1])
  1245. self.assertArrayEqual(casted_array_2, ds[2])
  1246. self.assertArrayEqual(list_array_3, ds[3])
  1247. self.assertArrayEqual(list_array_4, ds[4])
  1248. # Test that we can reassign arrays in the dataset
  1249. list_array_3 = np.array([0.3, 2.2], dtype=np_dt)
  1250. ds[0] = list_array_3[:]
  1251. self.assertArrayEqual(list_array_3, ds[0])
  1252. # Make sure we can close the file.
  1253. self.f.flush()
  1254. self.f.close()
  1255. def test_numpy_float16(self):
  1256. np_dt = np.dtype('float16')
  1257. self._help_float_testing(np_dt)
  1258. def test_numpy_float32(self):
  1259. np_dt = np.dtype('float32')
  1260. self._help_float_testing(np_dt)
  1261. def test_numpy_float64_from_dtype(self):
  1262. np_dt = np.dtype('float64')
  1263. self._help_float_testing(np_dt)
  1264. def test_numpy_float64_2(self):
  1265. np_dt = np.float64
  1266. self._help_float_testing(np_dt)
  1267. def test_non_contiguous_arrays(self):
  1268. """Test that non-contiguous arrays are stored correctly"""
  1269. self.f.create_dataset('nc', (10,), dtype=h5py.vlen_dtype('bool'))
  1270. x = np.array([True, False, True, True, False, False, False])
  1271. self.f['nc'][0] = x[::2]
  1272. assert all(self.f['nc'][0] == x[::2]), f"{self.f['nc'][0]} != {x[::2]}"
  1273. self.f.create_dataset('nc2', (10,), dtype=h5py.vlen_dtype('int8'))
  1274. y = np.array([2, 4, 1, 5, -1, 3, 7])
  1275. self.f['nc2'][0] = y[::2]
  1276. assert all(self.f['nc2'][0] == y[::2]), f"{self.f['nc2'][0]} != {y[::2]}"
  1277. class TestLowOpen(BaseDataset):
  1278. def test_get_access_list(self):
  1279. """ Test H5Dget_access_plist """
  1280. ds = self.f.create_dataset('foo', (4,))
  1281. p_list = ds.id.get_access_plist()
  1282. def test_dapl(self):
  1283. """ Test the dapl keyword to h5d.open """
  1284. dapl = h5py.h5p.create(h5py.h5p.DATASET_ACCESS)
  1285. dset = self.f.create_dataset('x', (100,))
  1286. del dset
  1287. dsid = h5py.h5d.open(self.f.id, b'x', dapl)
  1288. self.assertIsInstance(dsid, h5py.h5d.DatasetID)
  1289. @ut.skipUnless(h5py.version.hdf5_version_tuple >= (1, 10, 5),
  1290. "chunk info requires HDF5 >= 1.10.5")
  1291. def test_get_chunk_details():
  1292. from io import BytesIO
  1293. buf = BytesIO()
  1294. with h5py.File(buf, 'w') as fout:
  1295. fout.create_dataset('test', shape=(100, 100), chunks=(10, 10), dtype='i4')
  1296. fout['test'][:] = 1
  1297. buf.seek(0)
  1298. with h5py.File(buf, 'r') as fin:
  1299. ds = fin['test'].id
  1300. assert ds.get_num_chunks() == 100
  1301. for j in range(100):
  1302. offset = tuple(np.array(np.unravel_index(j, (10, 10))) * 10)
  1303. si = ds.get_chunk_info(j)
  1304. assert si.chunk_offset == offset
  1305. assert si.filter_mask == 0
  1306. assert si.byte_offset is not None
  1307. assert si.size > 0
  1308. si = ds.get_chunk_info_by_coord((0, 0))
  1309. assert si.chunk_offset == (0, 0)
  1310. assert si.filter_mask == 0
  1311. assert si.byte_offset is not None
  1312. assert si.size > 0
  1313. def test_empty_shape(writable_file):
  1314. ds = writable_file.create_dataset('empty', dtype='int32')
  1315. assert ds.shape is None
  1316. assert ds.maxshape is None
  1317. def test_zero_storage_size():
  1318. # https://github.com/h5py/h5py/issues/1475
  1319. from io import BytesIO
  1320. buf = BytesIO()
  1321. with h5py.File(buf, 'w') as fout:
  1322. fout.create_dataset('empty', dtype='uint8')
  1323. buf.seek(0)
  1324. with h5py.File(buf, 'r') as fin:
  1325. assert fin['empty'].chunks is None
  1326. assert fin['empty'].id.get_offset() is None
  1327. assert fin['empty'].id.get_storage_size() == 0
  1328. def test_python_int_uint64(writable_file):
  1329. # https://github.com/h5py/h5py/issues/1547
  1330. data = [np.iinfo(np.int64).max, np.iinfo(np.int64).max + 1]
  1331. # Check creating a new dataset
  1332. ds = writable_file.create_dataset('x', data=data, dtype=np.uint64)
  1333. assert ds.dtype == np.dtype(np.uint64)
  1334. np.testing.assert_array_equal(ds[:], np.array(data, dtype=np.uint64))
  1335. # Check writing to an existing dataset
  1336. ds[:] = data
  1337. np.testing.assert_array_equal(ds[:], np.array(data, dtype=np.uint64))
  1338. def test_setitem_fancy_indexing(writable_file):
  1339. # https://github.com/h5py/h5py/issues/1593
  1340. arr = writable_file.create_dataset('data', (5, 1000, 2), dtype=np.uint8)
  1341. block = np.random.randint(255, size=(5, 3, 2))
  1342. arr[:, [0, 2, 4], ...] = block
  1343. def test_vlen_spacepad():
  1344. with File(get_data_file_path("vlen_string_dset.h5")) as f:
  1345. assert f["DS1"][0] == b"Parting"
  1346. def test_vlen_nullterm():
  1347. with File(get_data_file_path("vlen_string_dset_utc.h5")) as f:
  1348. assert f["ds1"][0] == b"2009-12-20T10:16:18.662409Z"
  1349. @pytest.mark.skipif(
  1350. h5py.version.hdf5_version_tuple < (1, 10, 3),
  1351. reason="Appears you cannot pass an unknown filter id for HDF5 < 1.10.3"
  1352. )
  1353. def test_allow_unknown_filter(writable_file):
  1354. # apparently 256-511 are reserved for testing purposes
  1355. fake_filter_id = 256
  1356. ds = writable_file.create_dataset(
  1357. 'data', shape=(10, 10), dtype=np.uint8, compression=fake_filter_id,
  1358. allow_unknown_filter=True
  1359. )
  1360. assert str(fake_filter_id) in ds._filters