test_dataset.py 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365
  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 os
  17. import sys
  18. import numpy as np
  19. import platform
  20. import pytest
  21. import threading
  22. from concurrent.futures import ThreadPoolExecutor
  23. from h5py import File, Dataset
  24. from h5py._hl.base import is_empty_dataspace, product
  25. from h5py import h5f, h5t
  26. import h5py
  27. from .common import ut, TestCase, NUMPY_RELEASE_VERSION, is_main_thread, make_name
  28. from .data_files import get_data_file_path
  29. from ..h5py_warnings import H5pyDeprecationWarning
  30. class BaseDataset(TestCase):
  31. def setUp(self):
  32. self.f = File(self.mktemp(), 'w')
  33. def tearDown(self):
  34. if self.f:
  35. self.f.close()
  36. class TestRepr(BaseDataset):
  37. """
  38. Feature: repr(Dataset) behaves sensibly
  39. """
  40. endian_mark = '>' if sys.byteorder=='big' else '<'
  41. def test_repr_basic(self):
  42. name = make_name()
  43. ds = self.f.create_dataset(name, (4,), dtype='int32')
  44. assert repr(ds) == f'<HDF5 dataset "{name}": shape (4,), type "{self.endian_mark}i4">'
  45. @pytest.mark.thread_unsafe
  46. def test_repr_closed(self):
  47. """ repr() works on live and dead datasets """
  48. ds = self.f.create_dataset(make_name(), (4,), dtype="f4")
  49. self.f.close()
  50. assert repr(ds) == '<Closed HDF5 dataset>'
  51. def test_repr_anonymous(self):
  52. ds = self.f.create_dataset(None, (4,), dtype='int32')
  53. assert repr(ds) == f'<HDF5 dataset (anonymous): shape (4,), type "{self.endian_mark}i4">'
  54. class TestCreateShape(BaseDataset):
  55. """
  56. Feature: Datasets can be created from a shape only
  57. """
  58. def test_create_scalar(self):
  59. """ Create a scalar dataset """
  60. dset = self.f.create_dataset(make_name(), (), dtype='f4')
  61. self.assertEqual(dset.shape, ())
  62. def test_create_simple(self):
  63. """ Create a size-1 dataset """
  64. dset = self.f.create_dataset(make_name(), (1,), dtype='f4')
  65. self.assertEqual(dset.shape, (1,))
  66. def test_create_integer(self):
  67. """ Create a size-1 dataset with integer shape"""
  68. dset = self.f.create_dataset(make_name(), 1, dtype='f4')
  69. self.assertEqual(dset.shape, (1,))
  70. def test_create_extended_1d(self):
  71. """ Create an extended dataset with tuple shape """
  72. dset = self.f.create_dataset(make_name(), (63,), dtype='f4')
  73. self.assertEqual(dset.shape, (63,))
  74. self.assertEqual(dset.size, 63)
  75. def test_create_extended_2d(self):
  76. """ Create an extended dataset with 2 dimensions """
  77. dset = self.f.create_dataset(make_name(), (6, 10), dtype='f4')
  78. self.assertEqual(dset.shape, (6, 10))
  79. self.assertEqual(dset.size, (60))
  80. def test_create_integer_extended(self):
  81. """ Create an extended dataset with integer shape """
  82. dset = self.f.create_dataset(make_name(), 63, dtype='f4')
  83. self.assertEqual(dset.shape, (63,))
  84. self.assertEqual(dset.size, 63)
  85. def test_default_dtype(self):
  86. """ Confirm that the default dtype is float """
  87. dset = self.f.create_dataset(make_name(), (63,), dtype='f4')
  88. self.assertEqual(dset.dtype, np.dtype('=f4'))
  89. def test_missing_shape(self):
  90. """ Missing shape raises TypeError """
  91. with self.assertRaises(TypeError):
  92. self.f.create_dataset(make_name())
  93. def test_long_double(self):
  94. """ Confirm that the default dtype is float """
  95. dset = self.f.create_dataset(make_name(), (63,), dtype=np.longdouble)
  96. if platform.machine() in ['ppc64le']:
  97. pytest.xfail("Storage of long double deactivated on %s" % platform.machine())
  98. self.assertEqual(dset.dtype, np.longdouble)
  99. @ut.skipIf(not hasattr(np, "complex256"), "No support for complex256")
  100. def test_complex256(self):
  101. """ Confirm that the default dtype is float """
  102. dset = self.f.create_dataset(make_name(), (63,),
  103. dtype=np.dtype('complex256'))
  104. self.assertEqual(dset.dtype, np.dtype('complex256'))
  105. def test_name_bytes(self):
  106. dset = self.f.create_dataset(make_name("foo").encode('utf-8'), (1,), dtype='f4')
  107. self.assertEqual(dset.shape, (1,))
  108. dset2 = self.f.create_dataset((make_name("bar{}/baz")).encode('utf-8'), (2,), dtype='f4')
  109. self.assertEqual(dset2.shape, (2,))
  110. def test_no_dtype(self):
  111. # From h5py 4.0, either dtype or data will be required
  112. with pytest.warns(H5pyDeprecationWarning):
  113. dset = self.f.create_dataset(make_name(), (5,))
  114. assert dset.dtype == np.dtype('f4')
  115. class TestCreateData(BaseDataset):
  116. """
  117. Feature: Datasets can be created from existing data
  118. """
  119. def test_create_scalar(self):
  120. """ Create a scalar dataset from existing array """
  121. data = np.ones((), 'f')
  122. dset = self.f.create_dataset(make_name(), data=data)
  123. self.assertEqual(dset.shape, data.shape)
  124. def test_create_extended(self):
  125. """ Create an extended dataset from existing data """
  126. data = np.ones((63,), 'f')
  127. dset = self.f.create_dataset(make_name(), data=data)
  128. self.assertEqual(dset.shape, data.shape)
  129. def test_dataset_intermediate_group(self):
  130. """ Create dataset with missing intermediate groups """
  131. name = make_name("/foo{}/bar/baz")
  132. ds = self.f.create_dataset(name, shape=(10, 10), dtype='<i4')
  133. self.assertIsInstance(ds, h5py.Dataset)
  134. self.assertTrue(name in self.f)
  135. def test_reshape(self):
  136. """ Create from existing data, and make it fit a new shape """
  137. data = np.arange(30, dtype='f')
  138. dset = self.f.create_dataset(make_name(), shape=(10, 3), data=data)
  139. self.assertEqual(dset.shape, (10, 3))
  140. self.assertArrayEqual(dset[...], data.reshape((10, 3)))
  141. def test_appropriate_low_level_id(self):
  142. " Binding Dataset to a non-DatasetID identifier fails with ValueError "
  143. with self.assertRaises(ValueError):
  144. Dataset(self.f['/'].id)
  145. def check_h5_string(self, dset, cset, length):
  146. tid = dset.id.get_type()
  147. assert isinstance(tid, h5t.TypeStringID)
  148. assert tid.get_cset() == cset
  149. if length is None:
  150. assert tid.is_variable_str()
  151. else:
  152. assert not tid.is_variable_str()
  153. assert tid.get_size() == length
  154. def test_create_bytestring(self):
  155. """ Creating dataset with byte string yields vlen ASCII dataset """
  156. def check_vlen_ascii(dset):
  157. self.check_h5_string(dset, h5t.CSET_ASCII, length=None)
  158. check_vlen_ascii(self.f.create_dataset(make_name("a"), data=b'abc'))
  159. check_vlen_ascii(self.f.create_dataset(make_name("b"), data=[b'abc', b'def']))
  160. check_vlen_ascii(self.f.create_dataset(make_name("c"), data=[[b'abc'], [b'def']]))
  161. check_vlen_ascii(self.f.create_dataset(
  162. make_name("d"), data=np.array([b'abc', b'def'], dtype=object)
  163. ))
  164. def test_create_np_s(self):
  165. dset = self.f.create_dataset(make_name(), data=np.array([b'abc', b'def'], dtype='S3'))
  166. self.check_h5_string(dset, h5t.CSET_ASCII, length=3)
  167. def test_create_strings(self):
  168. def check_vlen_utf8(dset):
  169. self.check_h5_string(dset, h5t.CSET_UTF8, length=None)
  170. check_vlen_utf8(self.f.create_dataset(make_name("a"), data='abc'))
  171. check_vlen_utf8(self.f.create_dataset(make_name("b"), data=['abc', 'def']))
  172. check_vlen_utf8(self.f.create_dataset(make_name("c"), data=[['abc'], ['def']]))
  173. check_vlen_utf8(self.f.create_dataset(
  174. make_name("d"), data=np.array(['abc', 'def'], dtype=object)
  175. ))
  176. def test_create_np_u(self):
  177. with self.assertRaises(TypeError):
  178. self.f.create_dataset(make_name(), data=np.array([b'abc', b'def'], dtype='U3'))
  179. def test_empty_create_via_None_shape(self):
  180. name = make_name()
  181. self.f.create_dataset(name, dtype='f')
  182. self.assertTrue(is_empty_dataspace(self.f[name].id))
  183. def test_empty_create_via_Empty_class(self):
  184. name = make_name()
  185. self.f.create_dataset(name, data=h5py.Empty(dtype='f'))
  186. self.assertTrue(is_empty_dataspace(self.f[name].id))
  187. def test_create_incompatible_data(self):
  188. # Shape tuple is incompatible with data
  189. with self.assertRaises(ValueError):
  190. self.f.create_dataset(make_name(), shape=4, data= np.arange(3))
  191. class TestReadDirectly:
  192. """
  193. Feature: Read data directly from Dataset into a Numpy array
  194. """
  195. @pytest.mark.parametrize(
  196. 'source_shape,dest_shape,source_sel,dest_sel',
  197. [
  198. ((100,), (100,), np.s_[0:10], np.s_[50:60]),
  199. ((70,), (100,), np.s_[50:60], np.s_[90:]),
  200. ((30, 10), (20, 20), np.s_[:20, :], np.s_[:, :10]),
  201. ((5, 7, 9), (6,), np.s_[2, :6, 3], np.s_[:]),
  202. ])
  203. def test_read_direct(self, writable_file, source_shape, dest_shape, source_sel, dest_sel):
  204. source_values = np.arange(product(source_shape), dtype="int64").reshape(source_shape)
  205. dset = writable_file.create_dataset(make_name(), source_shape, data=source_values)
  206. arr = np.full(dest_shape, -1, dtype="int64")
  207. expected = arr.copy()
  208. expected[dest_sel] = source_values[source_sel]
  209. dset.read_direct(arr, source_sel, dest_sel)
  210. np.testing.assert_array_equal(arr, expected)
  211. def test_no_sel(self, writable_file):
  212. dset = writable_file.create_dataset(make_name(), (10,), data=np.arange(10, dtype="int64"))
  213. arr = np.ones((10,), dtype="int64")
  214. dset.read_direct(arr)
  215. np.testing.assert_array_equal(arr, np.arange(10, dtype="int64"))
  216. def test_empty(self, writable_file):
  217. empty_dset = writable_file.create_dataset(make_name(), dtype='int64')
  218. arr = np.ones((100,), 'int64')
  219. with pytest.raises(TypeError):
  220. empty_dset.read_direct(arr, np.s_[0:10], np.s_[50:60])
  221. def test_wrong_shape(self, writable_file):
  222. dset = writable_file.create_dataset(make_name(), (100,), dtype='int64')
  223. arr = np.ones((200,))
  224. with pytest.raises(TypeError):
  225. dset.read_direct(arr)
  226. def test_not_c_contiguous(self, writable_file):
  227. dset = writable_file.create_dataset(make_name(), (10, 10), dtype='int64')
  228. arr = np.ones((10, 10), order='F')
  229. with pytest.raises(TypeError):
  230. dset.read_direct(arr)
  231. def test_zero_length(self, writable_file):
  232. shape = (0, 20)
  233. dset = writable_file.create_dataset(make_name(), shape, dtype=np.int64)
  234. arr = np.zeros(shape, dtype=np.int64)
  235. dset.read_direct(arr)
  236. # We should still get an error if the shape is wrong
  237. arr2 = np.zeros((0, 25), dtype=np.int64)
  238. with pytest.raises(TypeError):
  239. dset.read_direct(arr2)
  240. class TestWriteDirectly:
  241. """
  242. Feature: Write Numpy array directly into Dataset
  243. """
  244. @pytest.mark.parametrize(
  245. 'source_shape,dest_shape,source_sel,dest_sel',
  246. [
  247. ((100,), (100,), np.s_[0:10], np.s_[50:60]),
  248. ((70,), (100,), np.s_[50:60], np.s_[90:]),
  249. ((30, 10), (20, 20), np.s_[:20, :], np.s_[:, :10]),
  250. ((5, 7, 9), (6,), np.s_[2, :6, 3], np.s_[:]),
  251. ])
  252. def test_write_direct(self, writable_file, source_shape, dest_shape, source_sel, dest_sel):
  253. dset = writable_file.create_dataset(make_name(), dest_shape, dtype='int32', fillvalue=-1)
  254. arr = np.arange(product(source_shape)).reshape(source_shape)
  255. expected = np.full(dest_shape, -1, dtype='int32')
  256. expected[dest_sel] = arr[source_sel]
  257. dset.write_direct(arr, source_sel, dest_sel)
  258. np.testing.assert_array_equal(dset[:], expected)
  259. def test_empty(self, writable_file):
  260. empty_dset = writable_file.create_dataset(make_name(), dtype='int64')
  261. with pytest.raises(TypeError):
  262. empty_dset.write_direct(np.ones((100,)), np.s_[0:10], np.s_[50:60])
  263. def test_wrong_shape(self, writable_file):
  264. dset = writable_file.create_dataset(make_name(), (100,), dtype='int64')
  265. arr = np.ones((200,))
  266. with pytest.raises(TypeError):
  267. dset.write_direct(arr)
  268. def test_not_c_contiguous(self, writable_file):
  269. dset = writable_file.create_dataset(make_name(), (10, 10), dtype='int64')
  270. arr = np.ones((10, 10), order='F')
  271. with pytest.raises(TypeError):
  272. dset.write_direct(arr)
  273. class TestCreateRequire(BaseDataset):
  274. """
  275. Feature: Datasets can be created only if they don't exist in the file
  276. """
  277. def test_create(self):
  278. """ Create new dataset with no conflicts """
  279. dset = self.f.require_dataset(make_name(), (10, 3), 'f')
  280. self.assertIsInstance(dset, Dataset)
  281. self.assertEqual(dset.shape, (10, 3))
  282. def test_create_existing(self):
  283. """ require_dataset yields existing dataset """
  284. name = make_name()
  285. dset = self.f.require_dataset(name, (10, 3), 'f')
  286. dset[0, 0] = 123
  287. dset2 = self.f.require_dataset(name, (10, 3), 'f')
  288. self.assertEqual(dset, dset2)
  289. def test_create_1D_integer(self):
  290. """ require_dataset with integer shape yields existing dataset"""
  291. name = make_name()
  292. dset = self.f.require_dataset(name, 10, 'f')
  293. dset[0] = 123
  294. dset2 = self.f.require_dataset(name, 10, 'f')
  295. self.assertEqual(dset, dset2)
  296. def test_create_1D_tuple(self):
  297. name = make_name()
  298. dset = self.f.require_dataset(name, (10,), 'f')
  299. dset[0] = 123
  300. dset2 = self.f.require_dataset(name, 10, 'f')
  301. self.assertEqual(dset, dset2)
  302. def test_create_1D_binary(self):
  303. name = make_name()
  304. dset = self.f.require_dataset(name, 10, 'f')
  305. dset[0] = 123
  306. dset2 = self.f.require_dataset(name.encode('utf-8'), (10,), 'f')
  307. self.assertEqual(dset, dset2)
  308. def test_shape_conflict(self):
  309. """ require_dataset with shape conflict yields TypeError """
  310. name = make_name()
  311. self.f.create_dataset(name, (10, 3), 'f')
  312. with self.assertRaises(TypeError):
  313. self.f.require_dataset(name, (10, 4), 'f')
  314. def test_type_conflict(self):
  315. """ require_dataset with object type conflict yields TypeError """
  316. name = make_name()
  317. self.f.create_group(name)
  318. with self.assertRaises(TypeError):
  319. self.f.require_dataset(name, (10, 3), 'f')
  320. def test_dtype_conflict(self):
  321. """ require_dataset with dtype conflict (strict mode) yields TypeError
  322. """
  323. name = make_name()
  324. dset = self.f.create_dataset(name, (10, 3), 'f')
  325. with self.assertRaises(TypeError):
  326. self.f.require_dataset(name, (10, 3), 'S10')
  327. def test_dtype_exact(self):
  328. """ require_dataset with exactly dtype match """
  329. name = make_name()
  330. dset = self.f.create_dataset(name, (10, 3), 'f')
  331. dset[0, 0] = 123
  332. dset2 = self.f.require_dataset(name, (10, 3), 'f', exact=True)
  333. self.assertEqual(dset, dset2)
  334. def test_dtype_close(self):
  335. """ require_dataset with convertible type succeeds (non-strict mode)
  336. """
  337. name = make_name()
  338. dset = self.f.create_dataset(name, (10, 3), 'i4')
  339. # Set a value too large for i2 to test for spurious intermediate conversions
  340. dset[0, 0] = 98765
  341. dset2 = self.f.require_dataset(name, (10, 3), 'i2', exact=False)
  342. self.assertEqual(dset, dset2)
  343. self.assertEqual(dset2.dtype, np.dtype('i4'))
  344. class TestCreateChunked(BaseDataset):
  345. """
  346. Feature: Datasets can be created by manually specifying chunks
  347. """
  348. def test_create_chunks(self):
  349. """ Create via chunks tuple """
  350. dset = self.f.create_dataset(make_name(), shape=(100,), chunks=(10,), dtype='f4')
  351. self.assertEqual(dset.chunks, (10,))
  352. def test_create_chunks_integer(self):
  353. """ Create via chunks integer """
  354. dset = self.f.create_dataset(make_name(), shape=(100,), chunks=10, dtype='f4')
  355. self.assertEqual(dset.chunks, (10,))
  356. def test_chunks_mismatch(self):
  357. """ Illegal chunk size raises ValueError """
  358. with self.assertRaises(ValueError):
  359. self.f.create_dataset(make_name(), shape=(100,), chunks=(200,), dtype='f4')
  360. def test_chunks_false(self):
  361. """ Chunked format required for given storage options """
  362. with self.assertRaises(ValueError):
  363. self.f.create_dataset(make_name(), shape=(10,), maxshape=100, chunks=False, dtype='f4')
  364. def test_chunks_scalar(self):
  365. """ Attempting to create chunked scalar dataset raises TypeError """
  366. with self.assertRaises(TypeError):
  367. self.f.create_dataset(make_name(), shape=(), chunks=(50,), dtype='f4')
  368. def test_auto_chunks(self):
  369. """ Auto-chunking of datasets """
  370. dset = self.f.create_dataset(make_name(), shape=(20, 100), chunks=True, dtype='f4')
  371. self.assertIsInstance(dset.chunks, tuple)
  372. self.assertEqual(len(dset.chunks), 2)
  373. def test_auto_chunks_abuse(self):
  374. """ Auto-chunking with pathologically large element sizes """
  375. dset = self.f.create_dataset(make_name(), shape=(3,), dtype='S100000000', chunks=True)
  376. self.assertEqual(dset.chunks, (1,))
  377. def test_scalar_assignment(self):
  378. """ Test scalar assignment of chunked dataset """
  379. dset = self.f.create_dataset(make_name(), shape=(3, 50, 50),
  380. dtype=np.int32, chunks=(1, 50, 50))
  381. # test assignment of selection smaller than chunk size
  382. dset[1, :, 40] = 10
  383. self.assertTrue(np.all(dset[1, :, 40] == 10))
  384. # test assignment of selection equal to chunk size
  385. dset[1] = 11
  386. self.assertTrue(np.all(dset[1] == 11))
  387. # test assignment of selection bigger than chunk size
  388. dset[0:2] = 12
  389. self.assertTrue(np.all(dset[0:2] == 12))
  390. def test_auto_chunks_no_shape(self):
  391. """ Auto-chunking of empty datasets not allowed"""
  392. name = make_name()
  393. with pytest.raises(TypeError, match='Empty') as err:
  394. self.f.create_dataset(name, dtype='S100', chunks=True)
  395. with pytest.raises(TypeError, match='Empty') as err:
  396. self.f.create_dataset(name, dtype='S100', maxshape=20)
  397. class TestCreateFillvalue(BaseDataset):
  398. """
  399. Feature: Datasets can be created with fill value
  400. """
  401. def test_create_fillval(self):
  402. """ Fill value is reflected in dataset contents """
  403. dset = self.f.create_dataset(make_name(), (10,), fillvalue=4.0, dtype='f4')
  404. self.assertEqual(dset[0], 4.0)
  405. self.assertEqual(dset[7], 4.0)
  406. def test_property(self):
  407. """ Fill value is recoverable via property """
  408. dset = self.f.create_dataset(make_name(), (10,), fillvalue=3.0, dtype='f4')
  409. self.assertEqual(dset.fillvalue, 3.0)
  410. self.assertNotIsInstance(dset.fillvalue, np.ndarray)
  411. def test_property_none(self):
  412. """ .fillvalue property works correctly if not set """
  413. dset = self.f.create_dataset(make_name(), (10,), dtype='f4')
  414. self.assertEqual(dset.fillvalue, 0)
  415. def test_compound(self):
  416. """ Fill value works with compound types """
  417. dt = np.dtype([('a', 'f4'), ('b', 'i8')])
  418. v = np.ones((1,), dtype=dt)[0]
  419. dset = self.f.create_dataset(make_name(), (10,), dtype=dt, fillvalue=v)
  420. self.assertEqual(dset.fillvalue, v)
  421. self.assertAlmostEqual(dset[4], v)
  422. def test_exc(self):
  423. """ Bogus fill value raises ValueError """
  424. with self.assertRaises(ValueError):
  425. dset = self.f.create_dataset(make_name(), (10,),
  426. dtype=[('a', 'i'), ('b', 'f')], fillvalue=42)
  427. class TestFillTime(BaseDataset):
  428. """
  429. Feature: Datasets created with specified fill time property
  430. """
  431. def test_fill_time_default(self):
  432. """ Fill time default to IFSET """
  433. dset = self.f.create_dataset(make_name(), (10,), 'f4', fillvalue=4.0)
  434. plist = dset.id.get_create_plist()
  435. self.assertEqual(plist.get_fill_time(), h5py.h5d.FILL_TIME_IFSET)
  436. self.assertEqual(dset[0], 4.0)
  437. self.assertEqual(dset[7], 4.0)
  438. @ut.skipIf('gzip' not in h5py.filters.encode, "DEFLATE is not installed")
  439. def test_compressed_default(self):
  440. """ Fill time is IFSET for compressed dataset (chunked) """
  441. dset = self.f.create_dataset(make_name(), (10,), "f4", compression='gzip',
  442. fillvalue=4.0)
  443. plist = dset.id.get_create_plist()
  444. self.assertEqual(plist.get_fill_time(), h5py.h5d.FILL_TIME_IFSET)
  445. self.assertEqual(dset[0], 4.0)
  446. self.assertEqual(dset[7], 4.0)
  447. def test_fill_time_never(self):
  448. """ Fill time set to NEVER """
  449. dset = self.f.create_dataset(make_name(), (10,), "f4", fillvalue=4.0,
  450. fill_time='never')
  451. plist = dset.id.get_create_plist()
  452. self.assertEqual(plist.get_fill_time(), h5py.h5d.FILL_TIME_NEVER)
  453. # should not be equal to the explicitly set fillvalue
  454. self.assertNotEqual(dset[0], 4.0)
  455. self.assertNotEqual(dset[7], 4.0)
  456. def test_fill_time_alloc(self):
  457. """ Fill time explicitly set to ALLOC """
  458. dset = self.f.create_dataset(make_name(), (10,), "f4", fillvalue=4.0,
  459. fill_time='alloc')
  460. plist = dset.id.get_create_plist()
  461. self.assertEqual(plist.get_fill_time(), h5py.h5d.FILL_TIME_ALLOC)
  462. def test_fill_time_ifset(self):
  463. """ Fill time explicitly set to IFSET """
  464. dset = self.f.create_dataset(make_name(), (10,), 'f4', chunks=(2,), fillvalue=4.0,
  465. fill_time='ifset')
  466. plist = dset.id.get_create_plist()
  467. self.assertEqual(plist.get_fill_time(), h5py.h5d.FILL_TIME_IFSET)
  468. def test_invalid_fill_time(self):
  469. """ Choice of fill_time is 'alloc', 'never', 'ifset' """
  470. with self.assertRaises(ValueError):
  471. dset = self.f.create_dataset(make_name(), (10,), 'f4', fill_time='fill_bad')
  472. def test_non_str_fill_time(self):
  473. """ fill_time must be a string """
  474. with self.assertRaises(ValueError):
  475. dset = self.f.create_dataset(make_name(), (10,), 'f4', fill_time=2)
  476. def test_resize_chunk_fill_time_default(self):
  477. """ The resize dataset will be filled (by default fill value 0) """
  478. dset = self.f.create_dataset(make_name(), (50, ), 'f4', maxshape=(100, ),
  479. chunks=(5, ))
  480. plist = dset.id.get_create_plist()
  481. self.assertEqual(plist.get_fill_time(), h5py.h5d.FILL_TIME_IFSET)
  482. assert np.isclose(dset[:], 0.0).all()
  483. dset.resize((100, ))
  484. assert np.isclose(dset[:], 0.0).all()
  485. def test_resize_chunk_fill_time_never(self):
  486. """ The resize dataset won't be filled """
  487. dset = self.f.create_dataset(make_name(), (50, ), 'f4', maxshape=(100, ),
  488. fillvalue=4.0, fill_time='never',
  489. chunks=(5, ))
  490. plist = dset.id.get_create_plist()
  491. self.assertEqual(plist.get_fill_time(), h5py.h5d.FILL_TIME_NEVER)
  492. assert not np.isclose(dset[:], 4.0).any()
  493. dset.resize((100, ))
  494. assert not np.isclose(dset[:], 4.0).any()
  495. @pytest.mark.parametrize('dt,expected', [
  496. (int, 0),
  497. (np.int32, 0),
  498. (np.int64, 0),
  499. (float, 0.0),
  500. (np.float32, 0.0),
  501. (np.float64, 0.0),
  502. (h5py.string_dtype(encoding='utf-8', length=5), b''),
  503. (h5py.string_dtype(encoding='ascii', length=5), b''),
  504. (h5py.string_dtype(encoding='utf-8'), b''),
  505. (h5py.string_dtype(encoding='ascii'), b''),
  506. (h5py.string_dtype(), b''),
  507. ])
  508. def test_get_unset_fill_value(dt, expected, writable_file):
  509. dset = writable_file.create_dataset(make_name(), (10,), dtype=dt)
  510. assert dset.fillvalue == expected
  511. class TestCreateNamedType(BaseDataset):
  512. """
  513. Feature: Datasets created from an existing named type
  514. """
  515. def test_named(self):
  516. """ Named type object works and links the dataset to type """
  517. name = make_name("type")
  518. self.f[name] = np.dtype('f8')
  519. dt = self.f[name]
  520. dset = self.f.create_dataset(make_name("x"), (100,), dtype=dt)
  521. self.assertEqual(dset.dtype, np.dtype('f8'))
  522. self.assertEqual(dset.id.get_type(), dt.id)
  523. self.assertTrue(dset.id.get_type().committed())
  524. @ut.skipIf('gzip' not in h5py.filters.encode, "DEFLATE is not installed")
  525. class TestCreateGzip(BaseDataset):
  526. """
  527. Feature: Datasets created with gzip compression
  528. """
  529. def test_gzip(self):
  530. """ Create with explicit gzip options """
  531. dset = self.f.create_dataset(make_name(), (20, 30), 'f4', compression='gzip',
  532. compression_opts=9)
  533. self.assertEqual(dset.compression, 'gzip')
  534. self.assertEqual(dset.compression_opts, 9)
  535. def test_gzip_implicit(self):
  536. """ Create with implicit gzip level (level 4) """
  537. dset = self.f.create_dataset(make_name(), (20, 30), 'f4', compression='gzip')
  538. self.assertEqual(dset.compression, 'gzip')
  539. self.assertEqual(dset.compression_opts, 4)
  540. @pytest.mark.thread_unsafe(reason="monkey-patch")
  541. def test_gzip_number(self):
  542. """ Create with gzip level by specifying integer """
  543. name = make_name()
  544. dset = self.f.create_dataset(name, (20, 30), 'f4', compression=7)
  545. self.assertEqual(dset.compression, 'gzip')
  546. self.assertEqual(dset.compression_opts, 7)
  547. original_compression_vals = h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS
  548. try:
  549. h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS = tuple()
  550. with self.assertRaises(ValueError):
  551. dset = self.f.create_dataset(name, (20, 30), 'f4', compression=7)
  552. finally:
  553. h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS = original_compression_vals
  554. def test_gzip_exc(self):
  555. """ Illegal gzip level (explicit or implicit) raises ValueError """
  556. name = make_name()
  557. with self.assertRaises((ValueError, RuntimeError)):
  558. self.f.create_dataset(name, (20, 30), 'f4', compression=14)
  559. with self.assertRaises(ValueError):
  560. self.f.create_dataset(name, (20, 30), 'f4', compression=-4)
  561. with self.assertRaises(ValueError):
  562. self.f.create_dataset(name, (20, 30), 'f4', compression='gzip',
  563. compression_opts=14)
  564. @ut.skipIf('gzip' not in h5py.filters.encode, "DEFLATE is not installed")
  565. class TestCreateCompressionNumber(BaseDataset):
  566. """
  567. Feature: Datasets created with a compression code
  568. """
  569. @pytest.mark.thread_unsafe(reason="monkey-patch")
  570. def test_compression_number(self):
  571. """ Create with compression number of gzip (h5py.h5z.FILTER_DEFLATE) and a compression level of 7"""
  572. original_compression_vals = h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS
  573. try:
  574. h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS = tuple()
  575. dset = self.f.create_dataset('foo', (20, 30), compression=h5py.h5z.FILTER_DEFLATE, compression_opts=(7,), dtype='f4')
  576. finally:
  577. h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS = original_compression_vals
  578. self.assertEqual(dset.compression, 'gzip')
  579. self.assertEqual(dset.compression_opts, 7)
  580. @pytest.mark.thread_unsafe(reason="monkey-patch")
  581. def test_compression_number_invalid(self):
  582. """ Create with invalid compression numbers """
  583. with self.assertRaises(ValueError) as e:
  584. self.f.create_dataset('foo', (20, 30), compression=-999, dtype='f4')
  585. self.assertIn("Invalid filter", str(e.exception))
  586. with self.assertRaises(ValueError) as e:
  587. self.f.create_dataset('foo', (20, 30), compression=100, dtype='f4')
  588. self.assertIn("Unknown compression", str(e.exception))
  589. original_compression_vals = h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS
  590. try:
  591. h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS = tuple()
  592. # Using gzip compression requires a compression level specified in compression_opts
  593. with self.assertRaises(IndexError):
  594. self.f.create_dataset('foo', (20, 30), compression=h5py.h5z.FILTER_DEFLATE, dtype='f4')
  595. finally:
  596. h5py._hl.dataset._LEGACY_GZIP_COMPRESSION_VALS = original_compression_vals
  597. @ut.skipIf('lzf' not in h5py.filters.encode, "LZF is not installed")
  598. class TestCreateLZF(BaseDataset):
  599. """
  600. Feature: Datasets created with LZF compression
  601. """
  602. def test_lzf_sparse(self):
  603. """ Create with explicit lzf (empty chunks)"""
  604. dset = self.f.create_dataset(make_name(), (20, 30), compression='lzf', dtype='f4')
  605. self.assertEqual(dset.compression, 'lzf')
  606. self.assertEqual(dset.compression_opts, None)
  607. def test_lzf_dense(self):
  608. """ Create with explicit lzf (populated)"""
  609. name = make_name()
  610. testdata = np.arange(100)
  611. dset = self.f.create_dataset(name, data=testdata, compression='lzf')
  612. self.assertEqual(dset.compression, 'lzf')
  613. self.assertEqual(dset.compression_opts, None)
  614. self.f.flush() # Actually write to file
  615. readdata = self.f[name][()]
  616. self.assertArrayEqual(readdata, testdata)
  617. def test_lzf_exc(self):
  618. """ Giving lzf options raises ValueError """
  619. with self.assertRaises(ValueError):
  620. self.f.create_dataset(make_name(), (20, 30), 'f4', compression='lzf',
  621. compression_opts=4)
  622. @ut.skipIf('szip' not in h5py.filters.encode, "SZIP is not installed")
  623. class TestCreateSZIP(BaseDataset):
  624. """
  625. Feature: Datasets created with LZF compression
  626. """
  627. def test_szip(self):
  628. """ Create with explicit szip """
  629. dset = self.f.create_dataset(make_name(), (20, 30), 'f4', compression='szip',
  630. compression_opts=('ec', 16))
  631. @ut.skipIf('shuffle' not in h5py.filters.encode, "SHUFFLE is not installed")
  632. class TestCreateShuffle(BaseDataset):
  633. """
  634. Feature: Datasets can use shuffling filter
  635. """
  636. def test_shuffle(self):
  637. """ Enable shuffle filter """
  638. dset = self.f.create_dataset(make_name(), (20, 30), shuffle=True, dtype='f4')
  639. self.assertTrue(dset.shuffle)
  640. @ut.skipIf('fletcher32' not in h5py.filters.encode, "FLETCHER32 is not installed")
  641. class TestCreateFletcher32(BaseDataset):
  642. """
  643. Feature: Datasets can use the fletcher32 filter
  644. """
  645. def test_fletcher32(self):
  646. """ Enable fletcher32 filter """
  647. dset = self.f.create_dataset(make_name(), (20, 30), fletcher32=True, dtype='f4')
  648. self.assertTrue(dset.fletcher32)
  649. @ut.skipIf('scaleoffset' not in h5py.filters.encode, "SCALEOFFSET is not installed")
  650. class TestCreateScaleOffset(BaseDataset):
  651. """
  652. Feature: Datasets can use the scale/offset filter
  653. Note: loss of precision caused by scaleoffset only becomes visible
  654. when closing and reopening the File.
  655. Can't close/reopen the shared self.f in pytest-run-parallel.
  656. """
  657. def test_float_fails_without_options(self):
  658. """ Ensure that a scale factor is required for scaleoffset compression of floating point data """
  659. with self.assertRaises(ValueError):
  660. dset = self.f.create_dataset(make_name(), (20, 30), dtype=float, scaleoffset=True)
  661. def test_non_integer(self):
  662. """ Check when scaleoffset is negetive"""
  663. with self.assertRaises(ValueError):
  664. dset = self.f.create_dataset(make_name(), (20, 30), dtype=float, scaleoffset=-0.1)
  665. def test_unsupport_dtype(self):
  666. """ Check when dtype is unsupported type"""
  667. with self.assertRaises(TypeError):
  668. dset = self.f.create_dataset(make_name(), (20, 30), dtype=bool, scaleoffset=True)
  669. def test_float(self):
  670. """ Scaleoffset filter works for floating point data """
  671. scalefac = 4
  672. shape = (100, 300)
  673. range = 20 * 10 ** scalefac
  674. testdata = (np.random.rand(*shape) - 0.5) * range
  675. fname = self.mktemp()
  676. with h5py.File(fname, 'w') as f:
  677. dset = f.create_dataset(
  678. 'foo', shape, dtype=np.float64, scaleoffset=scalefac
  679. )
  680. # Dataset reports that scaleoffset is in use
  681. assert dset.scaleoffset is not None
  682. # Dataset round-trips
  683. dset[...] = testdata
  684. with h5py.File(fname, 'r') as f:
  685. readdata = f['foo'][...]
  686. # Test that data round-trips to requested precision
  687. self.assertArrayEqual(readdata, testdata, precision=10 ** (-scalefac))
  688. # Test that the filter is actually active (i.e. compression is lossy)
  689. assert not (readdata == testdata).all()
  690. def test_int(self):
  691. """ Scaleoffset filter works for integer data with default precision """
  692. nbits = 12
  693. shape = (100, 300)
  694. testdata = np.random.randint(0, 2 ** nbits - 1, size=shape, dtype=np.int64)
  695. fname = self.mktemp()
  696. with h5py.File(fname, 'w') as f:
  697. # Create dataset; note omission of nbits (for library-determined precision)
  698. dset = f.create_dataset('foo', shape, dtype=np.int64, scaleoffset=True)
  699. # Dataset reports scaleoffset enabled
  700. assert dset.scaleoffset is not None
  701. # Data round-trips correctly and identically
  702. dset[...] = testdata
  703. with h5py.File(fname, 'r') as f:
  704. readdata = f['foo'][...]
  705. self.assertArrayEqual(readdata, testdata)
  706. def test_int_with_minbits(self):
  707. """ Scaleoffset filter works for integer data with specified precision """
  708. nbits = 12
  709. shape = (100, 300)
  710. testdata = np.random.randint(0, 2 ** nbits, size=shape, dtype=np.int64)
  711. fname = self.mktemp()
  712. with h5py.File(fname, 'w') as f:
  713. dset = f.create_dataset('foo', shape, dtype=np.int64, scaleoffset=nbits)
  714. # Dataset reports scaleoffset enabled with correct precision
  715. self.assertTrue(dset.scaleoffset == 12)
  716. # Data round-trips correctly
  717. dset[...] = testdata
  718. with h5py.File(fname, 'r') as f:
  719. readdata = f['foo'][...]
  720. self.assertArrayEqual(readdata, testdata)
  721. def test_int_with_minbits_lossy(self):
  722. """ Scaleoffset filter works for integer data with specified precision """
  723. nbits = 12
  724. shape = (100, 300)
  725. testdata = np.random.randint(0, 2 ** (nbits + 1) - 1, size=shape, dtype=np.int64)
  726. fname = self.mktemp()
  727. with h5py.File(fname, 'w') as f:
  728. dset = f.create_dataset('foo', shape, dtype=np.int64, scaleoffset=nbits)
  729. # Dataset reports scaleoffset enabled with correct precision
  730. self.assertTrue(dset.scaleoffset == 12)
  731. # Data can be written and read
  732. dset[...] = testdata
  733. with h5py.File(fname, 'r') as f:
  734. readdata = f['foo'][...]
  735. # Compression is lossy
  736. assert not (readdata == testdata).all()
  737. class TestExternal(BaseDataset):
  738. """
  739. Feature: Datasets with the external storage property
  740. """
  741. def test_contents(self):
  742. """ Create and access an external dataset """
  743. shape = (6, 100)
  744. testdata = np.random.random(shape)
  745. # create a dataset in an external file and set it
  746. ext_file = self.mktemp()
  747. external = [(ext_file, 0, h5f.UNLIMITED)]
  748. # ${ORIGIN} should be replaced by the parent dir of the HDF5 file
  749. dset = self.f.create_dataset(make_name(), shape, dtype=testdata.dtype, external=external, efile_prefix="${ORIGIN}")
  750. dset[...] = testdata
  751. assert dset.external is not None
  752. # verify file's existence, size, and contents
  753. with open(ext_file, 'rb') as fid:
  754. contents = fid.read()
  755. assert contents == testdata.tobytes()
  756. efile_prefix = pathlib.Path(dset.id.get_access_plist().get_efile_prefix().decode()).as_posix()
  757. parent = pathlib.Path(self.f.filename).parent.as_posix()
  758. assert efile_prefix == parent
  759. def test_contents_efile_prefix(self):
  760. """ Create and access an external dataset using an efile_prefix"""
  761. name = make_name()
  762. shape = (6, 100)
  763. testdata = np.random.random(shape)
  764. # create a dataset in an external file and set it
  765. ext_file = self.mktemp()
  766. # set only the basename, let the efile_prefix do the rest
  767. external = [(os.path.basename(ext_file), 0, h5f.UNLIMITED)]
  768. dset = self.f.create_dataset(name, shape, dtype=testdata.dtype, external=external, efile_prefix=os.path.dirname(ext_file))
  769. dset[...] = testdata
  770. assert dset.external is not None
  771. # verify file's existence, size, and contents
  772. with open(ext_file, 'rb') as fid:
  773. contents = fid.read()
  774. assert contents == testdata.tobytes()
  775. # check efile_prefix
  776. efile_prefix = pathlib.Path(dset.id.get_access_plist().get_efile_prefix().decode()).as_posix()
  777. parent = pathlib.Path(ext_file).parent.as_posix()
  778. assert efile_prefix == parent
  779. dset2 = self.f.require_dataset(name, shape, testdata.dtype, efile_prefix=os.path.dirname(ext_file))
  780. assert dset2.external is not None
  781. dset2[()] == testdata
  782. def test_name_str(self):
  783. """ External argument may be a file name str only """
  784. self.f.create_dataset(make_name(), (6, 100), external=self.mktemp(), dtype='f4')
  785. def test_name_path(self):
  786. """ External argument may be a file name path only """
  787. self.f.create_dataset(make_name(), (6, 100), 'f4',
  788. external=pathlib.Path(self.mktemp()))
  789. def test_iter_multi(self):
  790. """ External argument may be an iterable of multiple tuples """
  791. ext_file = self.mktemp()
  792. N = 100
  793. external = iter((ext_file, x * 1000, 1000) for x in range(N))
  794. dset = self.f.create_dataset(make_name(), (6, 100), external=external, dtype='f4')
  795. assert len(dset.external) == N
  796. def test_invalid(self):
  797. """ Test with invalid external lists """
  798. shape = (6, 100)
  799. ext_file = self.mktemp()
  800. for exc_type, external in [
  801. (TypeError, [ext_file]),
  802. (TypeError, [ext_file, 0]),
  803. (TypeError, [ext_file, 0, h5f.UNLIMITED]),
  804. (ValueError, [(ext_file,)]),
  805. (ValueError, [(ext_file, 0)]),
  806. (ValueError, [(ext_file, 0, h5f.UNLIMITED, 0)]),
  807. (TypeError, [(ext_file, 0, "h5f.UNLIMITED")]),
  808. ]:
  809. with self.assertRaises(exc_type):
  810. self.f.create_dataset(make_name(), shape, external=external, dtype='f4')
  811. def test_create_expandable(self):
  812. """ Create expandable external dataset """
  813. ext_file = self.mktemp()
  814. shape = (128, 64)
  815. maxshape = (None, 64)
  816. exp_dset = self.f.create_dataset(
  817. make_name(), shape, 'f4', maxshape=maxshape, external=ext_file
  818. )
  819. assert exp_dset.chunks is None
  820. assert exp_dset.shape == shape
  821. assert exp_dset.maxshape == maxshape
  822. class TestAutoCreate(BaseDataset):
  823. """
  824. Feature: Datasets auto-created from data produce the correct types
  825. """
  826. def assert_string_type(self, ds, cset, variable=True):
  827. tid = ds.id.get_type()
  828. self.assertEqual(type(tid), h5py.h5t.TypeStringID)
  829. self.assertEqual(tid.get_cset(), cset)
  830. if variable:
  831. assert tid.is_variable_str()
  832. def test_vlen_bytes(self):
  833. """Assigning byte strings produces a vlen string ASCII dataset """
  834. x = make_name("x")
  835. y = make_name("y")
  836. z = make_name("z")
  837. self.f[x] = b"Hello there"
  838. self.assert_string_type(self.f[x], h5py.h5t.CSET_ASCII)
  839. self.f[y] = [b"a", b"bc"]
  840. self.assert_string_type(self.f[y], h5py.h5t.CSET_ASCII)
  841. self.f[z] = np.array([b"a", b"bc"], dtype=np.object_)
  842. self.assert_string_type(self.f[z], h5py.h5t.CSET_ASCII)
  843. def test_vlen_unicode(self):
  844. """Assigning unicode strings produces a vlen string UTF-8 dataset """
  845. x = make_name("x")
  846. y = make_name("y")
  847. z = make_name("z")
  848. self.f[x] = "Hello there" + chr(0x2034)
  849. self.assert_string_type(self.f[x], h5py.h5t.CSET_UTF8)
  850. self.f[y] = ["a", "bc"]
  851. self.assert_string_type(self.f[y], h5py.h5t.CSET_UTF8)
  852. # 2D array; this only works with an array, not nested lists
  853. self.f[z] = np.array([["a", "bc"]], dtype=np.object_)
  854. self.assert_string_type(self.f[z], h5py.h5t.CSET_UTF8)
  855. def test_string_fixed(self):
  856. """ Assignment of fixed-length byte string produces a fixed-length
  857. ascii dataset """
  858. name = make_name()
  859. self.f[name] = np.bytes_("Hello there")
  860. ds = self.f[name]
  861. self.assert_string_type(ds, h5py.h5t.CSET_ASCII, variable=False)
  862. self.assertEqual(ds.id.get_type().get_size(), 11)
  863. class TestCreateLike(BaseDataset):
  864. def test_no_chunks(self):
  865. x = make_name("x")
  866. y = make_name("y")
  867. self.f[x] = np.arange(25).reshape(5, 5)
  868. self.f.create_dataset_like(y, self.f[x])
  869. dslike = self.f[y]
  870. self.assertEqual(dslike.shape, (5, 5))
  871. self.assertIs(dslike.chunks, None)
  872. def test_track_times(self):
  873. x = make_name("x")
  874. y = make_name("y")
  875. z = make_name("z")
  876. w = make_name("w")
  877. orig = self.f.create_dataset(x, data=np.arange(12),
  878. track_times=True)
  879. self.assertNotEqual(0, h5py.h5g.get_objinfo(orig._id).mtime)
  880. similar = self.f.create_dataset_like(y, orig)
  881. self.assertNotEqual(0, h5py.h5g.get_objinfo(similar._id).mtime)
  882. orig = self.f.create_dataset(z, data=np.arange(12),
  883. track_times=False)
  884. self.assertEqual(0, h5py.h5g.get_objinfo(orig._id).mtime)
  885. similar = self.f.create_dataset_like(w, orig)
  886. self.assertEqual(0, h5py.h5g.get_objinfo(similar._id).mtime)
  887. def test_maxshape(self):
  888. """ Test when other.maxshape != other.shape """
  889. other = self.f.create_dataset(make_name("x"), (10,), maxshape=20, dtype='f4')
  890. similar = self.f.create_dataset_like(make_name("y"), other)
  891. self.assertEqual(similar.shape, (10,))
  892. self.assertEqual(similar.maxshape, (20,))
  893. class TestChunkIterator(BaseDataset):
  894. def test_no_chunks(self):
  895. dset = self.f.create_dataset(make_name(), (), dtype='f4')
  896. with self.assertRaises(TypeError):
  897. dset.iter_chunks()
  898. def test_rank_mismatch(self):
  899. dset = self.f.create_dataset(make_name(), shape=(100,), chunks=(32,), dtype='f4')
  900. with self.assertRaises(ValueError):
  901. dset.iter_chunks((slice(19,67), 9))
  902. def test_1d(self):
  903. dset = self.f.create_dataset(make_name(), (100,), chunks=(32,), dtype='f4')
  904. expected = ((slice(0,32,1),), (slice(32,64,1),), (slice(64,96,1),),
  905. (slice(96,100,1),))
  906. self.assertEqual(list(dset.iter_chunks()), list(expected))
  907. expected = ((slice(50,64,1),), (slice(64,96,1),), (slice(96,97,1),))
  908. self.assertEqual(list(dset.iter_chunks(np.s_[50:97])), list(expected))
  909. expected = ((slice(0,32,1),), (slice(32,50,1),))
  910. self.assertEqual(list(dset.iter_chunks(np.s_[:50])), list(expected))
  911. expected = ((slice(96,97,1),),)
  912. self.assertEqual(list(dset.iter_chunks(np.s_[96])), list(expected))
  913. def test_2d(self):
  914. dset = self.f.create_dataset(make_name(), (100,100), chunks=(32,64), dtype='f4')
  915. expected = (
  916. (slice(0, 32, 1), slice(0, 64, 1)),
  917. (slice(0, 32, 1), slice(64, 100, 1)),
  918. (slice(32, 64, 1), slice(0, 64, 1)),
  919. (slice(32, 64, 1), slice(64, 100, 1)),
  920. (slice(64, 96, 1), slice(0, 64, 1)),
  921. (slice(64, 96, 1), slice(64, 100, 1)),
  922. (slice(96, 100, 1), slice(0, 64, 1)),
  923. (slice(96, 100, 1), slice(64, 100, 1)),
  924. )
  925. self.assertEqual(list(dset.iter_chunks()), list(expected))
  926. expected = ((slice(48, 52, 1), slice(40, 50, 1)),)
  927. self.assertEqual(list(dset.iter_chunks(np.s_[48:52,40:50])), list(expected))
  928. expected = (
  929. (slice(0, 32, 1), slice(40, 64, 1)),
  930. (slice(0, 32, 1), slice(64, 100, 1)),
  931. (slice(32, 52, 1), slice(40, 64, 1)),
  932. (slice(32, 52, 1), slice(64, 100, 1)),
  933. )
  934. self.assertEqual(list(dset.iter_chunks(np.s_[:52,40:])), list(expected))
  935. expected = (
  936. (slice(96, 97, 1), slice(19, 64, 1)),
  937. (slice(96, 97, 1), slice(64, 67, 1)),
  938. )
  939. self.assertEqual(list(dset.iter_chunks(np.s_[96,19:67])), list(expected))
  940. def test_2d_partial_slice(self):
  941. dset = self.f.create_dataset(make_name(), (5,5), chunks=(2,2), dtype='f4')
  942. expected = ((slice(3, 4, 1), slice(3, 4, 1)),
  943. (slice(3, 4, 1), slice(4, 5, 1)),
  944. (slice(4, 5, 1), slice(3, 4, 1)),
  945. (slice(4, 5, 1), slice(4, 5, 1)))
  946. sel = slice(3,5)
  947. self.assertEqual(list(dset.iter_chunks((sel, sel))), list(expected))
  948. class TestResize(BaseDataset):
  949. """
  950. Feature: Datasets created with "maxshape" may be resized
  951. """
  952. def test_create(self):
  953. """ Create dataset with "maxshape" """
  954. dset = self.f.create_dataset(make_name(), (20, 30), maxshape=(20, 60), dtype='f4')
  955. self.assertIsNot(dset.chunks, None)
  956. self.assertEqual(dset.maxshape, (20, 60))
  957. def test_create_1D_integer_maxshape_tuple(self):
  958. """ Create dataset with "maxshape" using tuple shape and integer maxshape"""
  959. dset = self.f.create_dataset(make_name(), (20,), maxshape=20, dtype='f4')
  960. self.assertIsNot(dset.chunks, None)
  961. self.assertEqual(dset.maxshape, (20,))
  962. def test_create_1D_integer_maxshape_integer(self):
  963. """ Create dataset with "maxshape" using integer shape and integer maxshape"""
  964. dset = self.f.create_dataset(make_name(), 20, maxshape=20, dtype='f4')
  965. self.assertEqual(dset.maxshape, (20,))
  966. def test_resize(self):
  967. """ Datasets may be resized up to maxshape """
  968. dset = self.f.create_dataset(make_name(), (20, 30), maxshape=(20, 60), dtype='f4')
  969. self.assertEqual(dset.shape, (20, 30))
  970. dset.resize((20, 50))
  971. self.assertEqual(dset.shape, (20, 50))
  972. dset.resize((20, 60))
  973. self.assertEqual(dset.shape, (20, 60))
  974. def test_resize_1D(self):
  975. """ Datasets may be resized up to maxshape using integer maxshape"""
  976. dset = self.f.create_dataset(make_name(), 20, maxshape=40, dtype='f4')
  977. self.assertEqual(dset.shape, (20,))
  978. dset.resize((30,))
  979. self.assertEqual(dset.shape, (30,))
  980. def test_resize_over(self):
  981. """ Resizing past maxshape triggers an exception """
  982. dset = self.f.create_dataset(make_name(), (20, 30), maxshape=(20, 60), dtype='f4')
  983. with self.assertRaises(Exception):
  984. dset.resize((20, 70))
  985. def test_resize_nonchunked(self):
  986. """ Resizing non-chunked dataset raises TypeError """
  987. dset = self.f.create_dataset(make_name(), (20, 30), dtype='f4')
  988. with self.assertRaises(TypeError):
  989. dset.resize((20, 60))
  990. def test_resize_axis(self):
  991. """ Resize specified axis """
  992. dset = self.f.create_dataset(make_name(), (20, 30), maxshape=(20, 60), dtype='f4')
  993. dset.resize(50, axis=1)
  994. self.assertEqual(dset.shape, (20, 50))
  995. def test_axis_exc(self):
  996. """ Illegal axis raises ValueError """
  997. dset = self.f.create_dataset(make_name(), (20, 30), maxshape=(20, 60), dtype='f4')
  998. with self.assertRaises(ValueError):
  999. dset.resize(50, axis=2)
  1000. def test_zero_dim(self):
  1001. """ Allow zero-length initial dims for unlimited axes (issue 111) """
  1002. dset = self.f.create_dataset(make_name(), (15, 0), maxshape=(15, None), dtype='f4')
  1003. self.assertEqual(dset.shape, (15, 0))
  1004. self.assertEqual(dset.maxshape, (15, None))
  1005. class TestDtype(BaseDataset):
  1006. """
  1007. Feature: Dataset dtype is available as .dtype property
  1008. """
  1009. def test_dtype(self):
  1010. """ Retrieve dtype from dataset """
  1011. dset = self.f.create_dataset(make_name(), (5,), '|S10')
  1012. self.assertEqual(dset.dtype, np.dtype('|S10'))
  1013. def test_dtype_complex32(self):
  1014. """ Retrieve dtype from complex float16 dataset (gh-2156) """
  1015. # No native support in numpy as of v1.23.3, so expect compound type.
  1016. complex32 = np.dtype([('r', np.float16), ('i', np.float16)])
  1017. dset = self.f.create_dataset(make_name(), (5,), complex32)
  1018. self.assertEqual(dset.dtype, complex32)
  1019. class TestLen(BaseDataset):
  1020. """
  1021. Feature: Size of first axis is available via Python's len
  1022. """
  1023. def test_len(self):
  1024. """ Python len() (under 32 bits) """
  1025. dset = self.f.create_dataset(make_name(), (312, 15), dtype='f4')
  1026. self.assertEqual(len(dset), 312)
  1027. def test_len_big(self):
  1028. """ Python len() vs Dataset.len() """
  1029. dset = self.f.create_dataset(make_name(), (2 ** 33, 15), dtype='f4')
  1030. self.assertEqual(dset.shape, (2 ** 33, 15))
  1031. if sys.maxsize == 2 ** 31 - 1:
  1032. with self.assertRaises(OverflowError):
  1033. len(dset)
  1034. else:
  1035. self.assertEqual(len(dset), 2 ** 33)
  1036. self.assertEqual(dset.len(), 2 ** 33)
  1037. class TestIter(BaseDataset):
  1038. """
  1039. Feature: Iterating over a dataset yields rows
  1040. """
  1041. def test_iter(self):
  1042. """ Iterating over a dataset yields rows """
  1043. data = np.arange(30, dtype='f').reshape((10, 3))
  1044. dset = self.f.create_dataset(make_name(), data=data)
  1045. for x, y in zip(dset, data, strict=True):
  1046. self.assertEqual(len(x), 3)
  1047. self.assertArrayEqual(x, y)
  1048. def test_iter_scalar(self):
  1049. """ Iterating over scalar dataset raises TypeError """
  1050. dset = self.f.create_dataset(make_name(), shape=(), dtype='f4')
  1051. with self.assertRaises(TypeError):
  1052. [x for x in dset]
  1053. class TestStrings(BaseDataset):
  1054. """
  1055. Feature: Datasets created with vlen and fixed datatypes correctly
  1056. translate to and from HDF5
  1057. """
  1058. def test_vlen_bytes(self):
  1059. """ Vlen bytes dataset maps to vlen ascii in the file """
  1060. dt = h5py.string_dtype(encoding='ascii')
  1061. ds = self.f.create_dataset(make_name(), (100,), dtype=dt)
  1062. tid = ds.id.get_type()
  1063. self.assertEqual(type(tid), h5py.h5t.TypeStringID)
  1064. self.assertEqual(tid.get_cset(), h5py.h5t.CSET_ASCII)
  1065. string_info = h5py.check_string_dtype(ds.dtype)
  1066. self.assertEqual(string_info.encoding, 'ascii')
  1067. def test_vlen_bytes_fillvalue(self):
  1068. """ Vlen bytes dataset handles fillvalue """
  1069. dt = h5py.string_dtype(encoding='ascii')
  1070. fill_value = b'bar'
  1071. ds = self.f.create_dataset(make_name(), (100,), dtype=dt, fillvalue=fill_value)
  1072. self.assertEqual(ds[0], fill_value)
  1073. self.assertEqual(ds.asstr()[0], fill_value.decode())
  1074. self.assertEqual(ds.fillvalue, fill_value)
  1075. def test_vlen_unicode(self):
  1076. """ Vlen unicode dataset maps to vlen utf-8 in the file """
  1077. dt = h5py.string_dtype()
  1078. ds = self.f.create_dataset(make_name(), (100,), dtype=dt)
  1079. tid = ds.id.get_type()
  1080. self.assertEqual(type(tid), h5py.h5t.TypeStringID)
  1081. self.assertEqual(tid.get_cset(), h5py.h5t.CSET_UTF8)
  1082. string_info = h5py.check_string_dtype(ds.dtype)
  1083. self.assertEqual(string_info.encoding, 'utf-8')
  1084. def test_vlen_unicode_fillvalue(self):
  1085. """ Vlen unicode dataset handles fillvalue """
  1086. dt = h5py.string_dtype()
  1087. fill_value = 'bár'
  1088. ds = self.f.create_dataset(make_name(), (100,), dtype=dt, fillvalue=fill_value)
  1089. self.assertEqual(ds[0], fill_value.encode("utf-8"))
  1090. self.assertEqual(ds.asstr()[0], fill_value)
  1091. self.assertEqual(ds.fillvalue, fill_value.encode("utf-8"))
  1092. def test_fixed_ascii(self):
  1093. """ Fixed-length bytes dataset maps to fixed-length ascii in the file
  1094. """
  1095. dt = np.dtype("|S10")
  1096. ds = self.f.create_dataset(make_name(), (100,), dtype=dt)
  1097. tid = ds.id.get_type()
  1098. self.assertEqual(type(tid), h5py.h5t.TypeStringID)
  1099. self.assertFalse(tid.is_variable_str())
  1100. self.assertEqual(tid.get_size(), 10)
  1101. self.assertEqual(tid.get_cset(), h5py.h5t.CSET_ASCII)
  1102. string_info = h5py.check_string_dtype(ds.dtype)
  1103. self.assertEqual(string_info.encoding, 'ascii')
  1104. self.assertEqual(string_info.length, 10)
  1105. def test_fixed_bytes_fillvalue(self):
  1106. """ Vlen bytes dataset handles fillvalue """
  1107. dt = h5py.string_dtype(encoding='ascii', length=10)
  1108. fill_value = b'bar'
  1109. ds = self.f.create_dataset(make_name(), (100,), dtype=dt, fillvalue=fill_value)
  1110. self.assertEqual(ds[0], fill_value)
  1111. self.assertEqual(ds.asstr()[0], fill_value.decode())
  1112. self.assertEqual(ds.fillvalue, fill_value)
  1113. def test_fixed_utf8(self):
  1114. dt = h5py.string_dtype(encoding='utf-8', length=5)
  1115. ds = self.f.create_dataset(make_name(), (100,), dtype=dt)
  1116. tid = ds.id.get_type()
  1117. self.assertEqual(tid.get_cset(), h5py.h5t.CSET_UTF8)
  1118. s = 'cù'
  1119. ds[0] = s.encode('utf-8')
  1120. ds[1] = s
  1121. ds[2:4] = [s, s]
  1122. ds[4:6] = np.array([s, s], dtype=object)
  1123. ds[6:8] = np.array([s.encode('utf-8')] * 2, dtype=dt)
  1124. with self.assertRaises(TypeError):
  1125. ds[8:10] = np.array([s, s], dtype='U')
  1126. np.testing.assert_array_equal(ds[:8], np.array([s.encode('utf-8')] * 8, dtype='S'))
  1127. def test_fixed_utf_8_fillvalue(self):
  1128. """ Vlen unicode dataset handles fillvalue """
  1129. dt = h5py.string_dtype(encoding='utf-8', length=10)
  1130. fill_value = 'bár'.encode("utf-8")
  1131. ds = self.f.create_dataset(make_name(), (100,), dtype=dt, fillvalue=fill_value)
  1132. self.assertEqual(ds[0], fill_value)
  1133. self.assertEqual(ds.asstr()[0], fill_value.decode("utf-8"))
  1134. self.assertEqual(ds.fillvalue, fill_value)
  1135. def test_fixed_unicode(self):
  1136. """ Fixed-length unicode datasets are unsupported (raise TypeError) """
  1137. dt = np.dtype("|U10")
  1138. with self.assertRaises(TypeError):
  1139. ds = self.f.create_dataset(make_name(), (100,), dtype=dt)
  1140. def test_roundtrip_vlen_bytes(self):
  1141. """ writing and reading to vlen bytes dataset preserves type and content
  1142. """
  1143. dt = h5py.string_dtype(encoding='ascii')
  1144. ds = self.f.create_dataset(make_name(), (100,), dtype=dt)
  1145. data = b"Hello\xef"
  1146. ds[0] = data
  1147. out = ds[0]
  1148. self.assertEqual(type(out), bytes)
  1149. self.assertEqual(out, data)
  1150. def test_roundtrip_fixed_bytes(self):
  1151. """ Writing to and reading from fixed-length bytes dataset preserves
  1152. type and content """
  1153. dt = np.dtype("|S10")
  1154. ds = self.f.create_dataset(make_name(), (100,), dtype=dt)
  1155. data = b"Hello\xef"
  1156. ds[0] = data
  1157. out = ds[0]
  1158. self.assertEqual(type(out), np.bytes_)
  1159. self.assertEqual(out, data)
  1160. def test_retrieve_vlen_unicode(self):
  1161. dt = h5py.string_dtype()
  1162. ds = self.f.create_dataset(make_name(), (10,), dtype=dt)
  1163. data = "fàilte"
  1164. ds[0] = data
  1165. self.assertIsInstance(ds[0], bytes)
  1166. out = ds.asstr()[0]
  1167. self.assertIsInstance(out, str)
  1168. self.assertEqual(out, data)
  1169. def test_asstr(self):
  1170. ds = self.f.create_dataset(make_name(), (10,), dtype=h5py.string_dtype())
  1171. data = "fàilte"
  1172. ds[0] = data
  1173. strwrap1 = ds.asstr('ascii')
  1174. with self.assertRaises(UnicodeDecodeError):
  1175. strwrap1[0]
  1176. # Different errors parameter
  1177. self.assertEqual(ds.asstr('ascii', 'ignore')[0], 'filte')
  1178. # latin-1 will decode it but give the wrong text
  1179. self.assertNotEqual(ds.asstr('latin-1')[0], data)
  1180. # len of ds
  1181. self.assertEqual(10, len(ds.asstr()))
  1182. # Array output
  1183. np.testing.assert_array_equal(
  1184. ds.asstr()[:1], np.array([data], dtype=object)
  1185. )
  1186. np.testing.assert_array_equal(
  1187. np.asarray(ds.asstr())[:1], np.array([data], dtype=object)
  1188. )
  1189. def test_asstr_fixed(self):
  1190. dt = h5py.string_dtype(length=5)
  1191. ds = self.f.create_dataset(make_name(), (10,), dtype=dt)
  1192. data = 'cù'
  1193. ds[0] = np.array(data.encode('utf-8'), dtype=dt)
  1194. self.assertIsInstance(ds[0], np.bytes_)
  1195. out = ds.asstr()[0]
  1196. self.assertIsInstance(out, str)
  1197. self.assertEqual(out, data)
  1198. # Different errors parameter
  1199. self.assertEqual(ds.asstr('ascii', 'ignore')[0], 'c')
  1200. # latin-1 will decode it but give the wrong text
  1201. self.assertNotEqual(ds.asstr('latin-1')[0], data)
  1202. # Array output
  1203. np.testing.assert_array_equal(
  1204. ds.asstr()[:1], np.array([data], dtype=object)
  1205. )
  1206. def test_unicode_write_error(self):
  1207. """Encoding error when writing a non-ASCII string to an ASCII vlen dataset"""
  1208. dt = h5py.string_dtype('ascii')
  1209. ds = self.f.create_dataset(make_name(), (100,), dtype=dt)
  1210. data = "fàilte"
  1211. with self.assertRaises(UnicodeEncodeError):
  1212. ds[0] = data
  1213. def test_unicode_write_bytes(self):
  1214. """ Writing valid utf-8 byte strings to a unicode vlen dataset is OK
  1215. """
  1216. dt = h5py.string_dtype()
  1217. ds = self.f.create_dataset(make_name(), (100,), dtype=dt)
  1218. data = (u"Hello there" + chr(0x2034)).encode('utf8')
  1219. ds[0] = data
  1220. out = ds[0]
  1221. self.assertEqual(type(out), bytes)
  1222. self.assertEqual(out, data)
  1223. def test_vlen_bytes_write_ascii_str(self):
  1224. """ Writing an ascii str to ascii vlen dataset is OK
  1225. """
  1226. dt = h5py.string_dtype('ascii')
  1227. ds = self.f.create_dataset(make_name(), (100,), dtype=dt)
  1228. data = "ASCII string"
  1229. ds[0] = data
  1230. out = ds[0]
  1231. self.assertEqual(type(out), bytes)
  1232. self.assertEqual(out, data.encode('ascii'))
  1233. class TestCompound(BaseDataset):
  1234. """
  1235. Feature: Compound types correctly round-trip
  1236. """
  1237. def test_rt(self):
  1238. """ Compound types are read back in correct order (issue 236)"""
  1239. dt = np.dtype([ ('weight', np.float64),
  1240. ('cputime', np.float64),
  1241. ('walltime', np.float64),
  1242. ('parents_offset', np.uint32),
  1243. ('n_parents', np.uint32),
  1244. ('status', np.uint8),
  1245. ('endpoint_type', np.uint8), ])
  1246. testdata = np.ndarray((16,), dtype=dt)
  1247. for key in dt.fields:
  1248. testdata[key] = np.random.random((16,)) * 100
  1249. name = make_name()
  1250. self.f[name] = testdata
  1251. outdata = self.f[name][...]
  1252. self.assertTrue(np.all(outdata == testdata))
  1253. self.assertEqual(outdata.dtype, testdata.dtype)
  1254. def test_assign(self):
  1255. dt = np.dtype([ ('weight', (np.float64, 3)),
  1256. ('endpoint_type', np.uint8), ])
  1257. testdata = np.ndarray((16,), dtype=dt)
  1258. for key in dt.fields:
  1259. testdata[key] = np.random.random(size=testdata[key].shape) * 100
  1260. name = make_name()
  1261. ds = self.f.create_dataset(name, (16,), dtype=dt)
  1262. for key in dt.fields:
  1263. ds[key] = testdata[key]
  1264. outdata = self.f[name][...]
  1265. self.assertTrue(np.all(outdata == testdata))
  1266. self.assertEqual(outdata.dtype, testdata.dtype)
  1267. def test_fields(self):
  1268. dt = np.dtype([
  1269. ('x', np.float64),
  1270. ('y', np.float64),
  1271. ('z', np.float64),
  1272. ])
  1273. testdata = np.ndarray((16,), dtype=dt)
  1274. for key in dt.fields:
  1275. testdata[key] = np.random.random((16,)) * 100
  1276. name = make_name()
  1277. self.f[name] = testdata
  1278. ds = self.f[name]
  1279. # Extract multiple fields
  1280. np.testing.assert_array_equal(
  1281. ds.fields(['x', 'y'])[:], testdata[['x', 'y']]
  1282. )
  1283. # Extract single field
  1284. np.testing.assert_array_equal(
  1285. ds.fields('x')[:], testdata['x']
  1286. )
  1287. # Check __array__() method of fields wrapper
  1288. np.testing.assert_array_equal(
  1289. np.asarray(ds.fields(['x', 'y'])), testdata[['x', 'y']]
  1290. )
  1291. # Check type conversion of __array__() method
  1292. dt_int = np.dtype([('x', np.int32)])
  1293. np.testing.assert_array_equal(
  1294. np.asarray(ds.fields(['x']), dtype=dt_int),
  1295. testdata[['x']].astype(dt_int)
  1296. )
  1297. # Check len() on fields wrapper
  1298. assert len(ds.fields('x')) == 16
  1299. def test_nested_compound_vlen(self):
  1300. dt_inner = np.dtype([('a', h5py.vlen_dtype(np.int32)),
  1301. ('b', h5py.vlen_dtype(np.int32))])
  1302. dt = np.dtype([('f1', h5py.vlen_dtype(dt_inner)),
  1303. ('f2', np.int64)])
  1304. inner1 = (np.array(range(1, 3), dtype=np.int32),
  1305. np.array(range(6, 9), dtype=np.int32))
  1306. inner2 = (np.array(range(10, 14), dtype=np.int32),
  1307. np.array(range(16, 21), dtype=np.int32))
  1308. data = np.array([(np.array([inner1, inner2], dtype=dt_inner), 2),
  1309. (np.array([inner1], dtype=dt_inner), 3)],
  1310. dtype=dt)
  1311. name = make_name()
  1312. self.f[name] = data
  1313. out = self.f[name]
  1314. # Specifying check_alignment=False because vlen fields have 8 bytes of padding
  1315. # because the vlen datatype in hdf5 occupies 16 bytes
  1316. self.assertArrayEqual(out, data, check_alignment=False)
  1317. class TestSubarray(BaseDataset):
  1318. def test_write_list(self):
  1319. ds = self.f.create_dataset(make_name(), (1,), dtype="3int8")
  1320. ds[0] = [1, 2, 3]
  1321. np.testing.assert_array_equal(ds[:], [[1, 2, 3]])
  1322. ds[:] = [[4, 5, 6]]
  1323. np.testing.assert_array_equal(ds[:], [[4, 5, 6]])
  1324. def test_write_array(self):
  1325. ds = self.f.create_dataset(make_name(), (1,), dtype="3int8")
  1326. ds[0] = np.array([1, 2, 3])
  1327. np.testing.assert_array_equal(ds[:], [[1, 2, 3]])
  1328. ds[:] = np.array([[4, 5, 6]])
  1329. np.testing.assert_array_equal(ds[:], [[4, 5, 6]])
  1330. class TestEnum(BaseDataset):
  1331. """
  1332. Feature: Enum datatype info is preserved, read/write as integer
  1333. """
  1334. EDICT = {'RED': 0, 'GREEN': 1, 'BLUE': 42}
  1335. def test_create(self):
  1336. """ Enum datasets can be created and type correctly round-trips """
  1337. dt = h5py.enum_dtype(self.EDICT, basetype='i')
  1338. ds = self.f.create_dataset(make_name(), (100, 100), dtype=dt)
  1339. dt2 = ds.dtype
  1340. dict2 = h5py.check_enum_dtype(dt2)
  1341. self.assertEqual(dict2, self.EDICT)
  1342. def test_readwrite(self):
  1343. """ Enum datasets can be read/written as integers """
  1344. dt = h5py.enum_dtype(self.EDICT, basetype='i4')
  1345. ds = self.f.create_dataset(make_name(), (100, 100), dtype=dt)
  1346. ds[35, 37] = 42
  1347. ds[1, :] = 1
  1348. self.assertEqual(ds[35, 37], 42)
  1349. self.assertArrayEqual(ds[1, :], np.array((1,) * 100, dtype='i4'))
  1350. class TestFloats(BaseDataset):
  1351. """
  1352. Test support for mini and extended-precision floats
  1353. """
  1354. def _exectest(self, dt):
  1355. dset = self.f.create_dataset(make_name(), (100,), dtype=dt)
  1356. self.assertEqual(dset.dtype, dt)
  1357. data = np.ones((100,), dtype=dt)
  1358. dset[...] = data
  1359. self.assertArrayEqual(dset[...], data)
  1360. @ut.skipUnless(hasattr(np, 'float16'), "NumPy float16 support required")
  1361. def test_mini(self):
  1362. """ Mini-floats round trip """
  1363. self._exectest(np.dtype('float16'))
  1364. # TODO: move these tests to test_h5t
  1365. def test_mini_mapping(self):
  1366. """ Test mapping for float16 """
  1367. if hasattr(np, 'float16'):
  1368. self.assertEqual(h5t.IEEE_F16LE.dtype, np.dtype('<f2'))
  1369. else:
  1370. self.assertEqual(h5t.IEEE_F16LE.dtype, np.dtype('<f4'))
  1371. class TestTrackTimes(BaseDataset):
  1372. """
  1373. Feature: track_times
  1374. """
  1375. def test_disable_track_times(self):
  1376. """ check that when track_times=False, the time stamp=0 (Jan 1, 1970) """
  1377. ds = self.f.create_dataset(make_name(), (4,), track_times=False, dtype='f4')
  1378. ds_mtime = h5py.h5g.get_objinfo(ds._id).mtime
  1379. self.assertEqual(0, ds_mtime)
  1380. def test_invalid_track_times(self):
  1381. """ check that when give track_times an invalid value """
  1382. with self.assertRaises(TypeError):
  1383. self.f.create_dataset(make_name(), (4,), track_times='null', dtype='f4')
  1384. class TestZeroShape(BaseDataset):
  1385. """
  1386. Features of datasets with (0,)-shape axes
  1387. """
  1388. def test_array_conversion(self):
  1389. """ Empty datasets can be converted to NumPy arrays """
  1390. ds = self.f.create_dataset(make_name("x"), 0, maxshape=None, dtype='f4')
  1391. self.assertEqual(ds.shape, np.array(ds).shape)
  1392. ds = self.f.create_dataset(make_name("y"), (0,), maxshape=(None,), dtype='f4')
  1393. self.assertEqual(ds.shape, np.array(ds).shape)
  1394. ds = self.f.create_dataset(make_name("z"), (0, 0), maxshape=(None, None), dtype='f4')
  1395. self.assertEqual(ds.shape, np.array(ds).shape)
  1396. def test_reading(self):
  1397. """ Slicing into empty datasets works correctly """
  1398. dt = [('a', 'f'), ('b', 'i')]
  1399. ds = self.f.create_dataset(make_name(), (0,), dtype=dt, maxshape=(None,))
  1400. arr = np.empty((0,), dtype=dt)
  1401. self.assertEqual(ds[...].shape, arr.shape)
  1402. self.assertEqual(ds[...].dtype, arr.dtype)
  1403. self.assertEqual(ds[()].shape, arr.shape)
  1404. self.assertEqual(ds[()].dtype, arr.dtype)
  1405. class TestRegionRefs(BaseDataset):
  1406. """
  1407. Various features of region references
  1408. """
  1409. def setUp(self):
  1410. BaseDataset.setUp(self)
  1411. self.data = np.arange(100 * 100).reshape((100, 100))
  1412. self.dset = self.f.create_dataset('x', data=self.data)
  1413. self.dset[...] = self.data
  1414. def test_create_ref(self):
  1415. """ Region references can be used as slicing arguments """
  1416. slic = np.s_[25:35, 10:100:5]
  1417. ref = self.dset.regionref[slic]
  1418. self.assertArrayEqual(self.dset[ref], self.data[slic])
  1419. def test_empty_region(self):
  1420. ref = self.dset.regionref[:0]
  1421. out = self.dset[ref]
  1422. assert out.size == 0
  1423. # Ideally we should preserve shape (0, 100), but it seems this is lost.
  1424. def test_scalar_dataset(self):
  1425. ds = self.f.create_dataset(make_name(), data=1.0, dtype='f4')
  1426. sid = h5py.h5s.create(h5py.h5s.SCALAR)
  1427. # Deselected
  1428. sid.select_none()
  1429. ref = h5py.h5r.create(ds.id, b'.', h5py.h5r.DATASET_REGION, sid)
  1430. assert ds[ref] == h5py.Empty(np.dtype('f4'))
  1431. # Selected
  1432. sid.select_all()
  1433. ref = h5py.h5r.create(ds.id, b'.', h5py.h5r.DATASET_REGION, sid)
  1434. assert ds[ref] == ds[()]
  1435. def test_ref_shape(self):
  1436. """ Region reference shape and selection shape """
  1437. slic = np.s_[25:35, 10:100:5]
  1438. ref = self.dset.regionref[slic]
  1439. self.assertEqual(self.dset.regionref.shape(ref), self.dset.shape)
  1440. self.assertEqual(self.dset.regionref.selection(ref), (10, 18))
  1441. class TestAstype(BaseDataset):
  1442. """.astype() wrapper & context manager
  1443. """
  1444. def test_astype_wrapper(self):
  1445. dset = self.f.create_dataset(make_name(), (100,), dtype='i2')
  1446. dset[...] = np.arange(100)
  1447. arr = dset.astype('f4')[:]
  1448. self.assertArrayEqual(arr, np.arange(100, dtype='f4'))
  1449. def test_astype_wrapper_len(self):
  1450. dset = self.f.create_dataset(make_name(), (100,), dtype='i2')
  1451. dset[...] = np.arange(100)
  1452. self.assertEqual(100, len(dset.astype('f4')))
  1453. def test_astype_wrapper_asarray(self):
  1454. dset = self.f.create_dataset(make_name(), (100,), dtype='i2')
  1455. dset[...] = np.arange(100)
  1456. arr = np.asarray(dset.astype('f4'), dtype='i2')
  1457. self.assertArrayEqual(arr, np.arange(100, dtype='i2'))
  1458. class TestScalarCompound(BaseDataset):
  1459. """
  1460. Retrieval of a single field from a scalar compound dataset should
  1461. strip the field info
  1462. """
  1463. def test_scalar_compound(self):
  1464. dt = np.dtype([('a', 'i')])
  1465. dset = self.f.create_dataset(make_name(), (), dtype=dt)
  1466. self.assertEqual(dset['a'].dtype, np.dtype('i'))
  1467. class TestVlen(BaseDataset):
  1468. def test_int(self):
  1469. dt = h5py.vlen_dtype(int)
  1470. ds = self.f.create_dataset(make_name(), (4,), dtype=dt)
  1471. ds[0] = np.arange(3)
  1472. ds[1] = np.arange(0)
  1473. ds[2] = [1, 2, 3]
  1474. ds[3] = np.arange(1)
  1475. self.assertArrayEqual(ds[0], np.arange(3))
  1476. self.assertArrayEqual(ds[1], np.arange(0))
  1477. self.assertArrayEqual(ds[2], np.array([1, 2, 3]))
  1478. self.assertArrayEqual(ds[1], np.arange(0))
  1479. ds[0:2] = np.array([np.arange(5), np.arange(4)], dtype=object)
  1480. self.assertArrayEqual(ds[0], np.arange(5))
  1481. self.assertArrayEqual(ds[1], np.arange(4))
  1482. ds[0:2] = np.array([np.arange(3), np.arange(3)])
  1483. self.assertArrayEqual(ds[0], np.arange(3))
  1484. self.assertArrayEqual(ds[1], np.arange(3))
  1485. def test_reuse_from_other(self):
  1486. dt = h5py.vlen_dtype(int)
  1487. ds = self.f.create_dataset(make_name("x"), (1,), dtype=dt)
  1488. self.f.create_dataset(make_name("y"), (1,), ds[()].dtype)
  1489. def test_reuse_struct_from_other(self):
  1490. dt = [('a', int), ('b', h5py.vlen_dtype(int))]
  1491. fname = self.mktemp()
  1492. with h5py.File(fname, 'w') as f:
  1493. f.create_dataset("x", (1,), dtype=dt)
  1494. with h5py.File(fname, 'a') as f:
  1495. f.create_dataset("y", (1,), f["x"]['b'][()].dtype)
  1496. def test_convert(self):
  1497. dt = h5py.vlen_dtype(int)
  1498. ds = self.f.create_dataset(make_name(), (3,), dtype=dt)
  1499. ds[0] = np.array([1.4, 1.2])
  1500. ds[1] = np.array([1.2])
  1501. ds[2] = [1.2, 2, 3]
  1502. self.assertArrayEqual(ds[0], np.array([1, 1]))
  1503. self.assertArrayEqual(ds[1], np.array([1]))
  1504. self.assertArrayEqual(ds[2], np.array([1, 2, 3]))
  1505. ds[0:2] = np.array([[0.1, 1.1, 2.1, 3.1, 4], np.arange(4)], dtype=object)
  1506. self.assertArrayEqual(ds[0], np.arange(5))
  1507. self.assertArrayEqual(ds[1], np.arange(4))
  1508. ds[0:2] = np.array([np.array([0.1, 1.2, 2.2]),
  1509. np.array([0.2, 1.2, 2.2])])
  1510. self.assertArrayEqual(ds[0], np.arange(3))
  1511. self.assertArrayEqual(ds[1], np.arange(3))
  1512. def test_multidim(self):
  1513. dt = h5py.vlen_dtype(int)
  1514. ds = self.f.create_dataset(make_name(), (2, 2), dtype=dt)
  1515. ds[0, 0] = np.arange(1)
  1516. ds[:, :] = np.array([[np.arange(3), np.arange(2)],
  1517. [np.arange(1), np.arange(2)]], dtype=object)
  1518. ds[:, :] = np.array([[np.arange(2), np.arange(2)],
  1519. [np.arange(2), np.arange(2)]])
  1520. def _help_float_testing(self, np_dt):
  1521. """
  1522. Helper for testing various vlen numpy data types.
  1523. :param np_dt: Numpy datatype to test
  1524. """
  1525. dt = h5py.vlen_dtype(np_dt)
  1526. ds = self.f.create_dataset(make_name(), (5,), dtype=dt)
  1527. # Create some arrays, and assign them to the dataset
  1528. array_0 = np.array([1., 2., 30.], dtype=np_dt)
  1529. array_1 = np.array([100.3, 200.4, 98.1, -10.5, -300.0], dtype=np_dt)
  1530. # Test that a numpy array of different type gets cast correctly
  1531. array_2 = np.array([1, 2, 8], dtype=np.dtype('int32'))
  1532. casted_array_2 = array_2.astype(np_dt)
  1533. # Test that we can set a list of floats.
  1534. list_3 = [1., 2., 900., 0., -0.5]
  1535. list_array_3 = np.array(list_3, dtype=np_dt)
  1536. # Test that a list of integers gets casted correctly
  1537. list_4 = [-1, -100, 0, 1, 9999, 70]
  1538. list_array_4 = np.array(list_4, dtype=np_dt)
  1539. ds[0] = array_0
  1540. ds[1] = array_1
  1541. ds[2] = array_2
  1542. ds[3] = list_3
  1543. ds[4] = list_4
  1544. self.assertArrayEqual(array_0, ds[0])
  1545. self.assertArrayEqual(array_1, ds[1])
  1546. self.assertArrayEqual(casted_array_2, ds[2])
  1547. self.assertArrayEqual(list_array_3, ds[3])
  1548. self.assertArrayEqual(list_array_4, ds[4])
  1549. # Test that we can reassign arrays in the dataset
  1550. list_array_3 = np.array([0.3, 2.2], dtype=np_dt)
  1551. ds[0] = list_array_3[:]
  1552. self.assertArrayEqual(list_array_3, ds[0])
  1553. # Make sure we can close the file.
  1554. self.f.flush()
  1555. if is_main_thread():
  1556. self.f.close()
  1557. def test_numpy_float16(self):
  1558. np_dt = np.dtype('float16')
  1559. self._help_float_testing(np_dt)
  1560. def test_numpy_float32(self):
  1561. np_dt = np.dtype('float32')
  1562. self._help_float_testing(np_dt)
  1563. def test_numpy_float64_from_dtype(self):
  1564. np_dt = np.dtype('float64')
  1565. self._help_float_testing(np_dt)
  1566. def test_numpy_float64_2(self):
  1567. np_dt = np.float64
  1568. self._help_float_testing(np_dt)
  1569. def test_non_contiguous_arrays_bool(self):
  1570. """Test that non-contiguous arrays are stored correctly"""
  1571. name = make_name()
  1572. self.f.create_dataset(name, (10,), dtype=h5py.vlen_dtype('bool'))
  1573. ds = self.f[name]
  1574. x = np.array([True, False, True, True, False, False, False])
  1575. ds[0] = x[::2]
  1576. assert all(ds[0] == x[::2]), f"{ds[0]} != {x[::2]}"
  1577. def test_non_contiguous_arrays_int(self):
  1578. name = make_name()
  1579. self.f.create_dataset(name, (10,), dtype=h5py.vlen_dtype('int8'))
  1580. ds = self.f[name]
  1581. y = np.array([2, 4, 1, 5, -1, 3, 7])
  1582. ds[0] = y[::2]
  1583. assert all(ds[0] == y[::2]), f"{ds[0]} != {y[::2]}"
  1584. def test_asstr_array_dtype(self):
  1585. dt = h5py.string_dtype(encoding='ascii')
  1586. fill_value = b'bar'
  1587. ds = self.f.create_dataset(make_name(), (100,), dtype=dt, fillvalue=fill_value)
  1588. with pytest.raises(ValueError):
  1589. np.array(ds.asstr(), dtype=int)
  1590. class TestLowOpen(BaseDataset):
  1591. def test_get_access_list(self):
  1592. """ Test H5Dget_access_plist """
  1593. ds = self.f.create_dataset(make_name(), (4,), dtype='f4')
  1594. p_list = ds.id.get_access_plist()
  1595. def test_dapl(self):
  1596. """ Test the dapl keyword to h5d.open """
  1597. name = make_name()
  1598. dapl = h5py.h5p.create(h5py.h5p.DATASET_ACCESS)
  1599. dset = self.f.create_dataset(name, (100,), dtype='f4')
  1600. del dset
  1601. dsid = h5py.h5d.open(self.f.id, name.encode('utf-8'), dapl)
  1602. self.assertIsInstance(dsid, h5py.h5d.DatasetID)
  1603. def test_get_chunk_details():
  1604. from io import BytesIO
  1605. buf = BytesIO()
  1606. name = make_name()
  1607. with h5py.File(buf, 'w') as fout:
  1608. fout.create_dataset(name, shape=(100, 100), chunks=(10, 10), dtype='i4')
  1609. fout[name][:] = 1
  1610. buf.seek(0)
  1611. with h5py.File(buf, 'r') as fin:
  1612. ds = fin[name].id
  1613. assert ds.get_num_chunks() == 100
  1614. for j in range(100):
  1615. offset = tuple(np.array(np.unravel_index(j, (10, 10))) * 10)
  1616. si = ds.get_chunk_info(j)
  1617. assert si.chunk_offset == offset
  1618. assert si.filter_mask == 0
  1619. assert si.byte_offset is not None
  1620. assert si.size > 0
  1621. si = ds.get_chunk_info_by_coord((0, 0))
  1622. assert si.chunk_offset == (0, 0)
  1623. assert si.filter_mask == 0
  1624. assert si.byte_offset is not None
  1625. assert si.size > 0
  1626. @ut.skipUnless(h5py.version.hdf5_version_tuple >= (1, 12, 3) or
  1627. (h5py.version.hdf5_version_tuple >= (1, 10, 10) and h5py.version.hdf5_version_tuple < (1, 10, 99)),
  1628. "chunk iteration requires HDF5 1.10.10 and later 1.10, or 1.12.3 and later")
  1629. def test_chunk_iter():
  1630. """H5Dchunk_iter() for chunk information"""
  1631. from io import BytesIO
  1632. buf = BytesIO()
  1633. name = make_name()
  1634. with h5py.File(buf, 'w') as f:
  1635. f.create_dataset(name, shape=(100, 100), chunks=(10, 10), dtype='i4')
  1636. f[name][:] = 1
  1637. buf.seek(0)
  1638. with h5py.File(buf, 'r') as f:
  1639. dsid = f[name].id
  1640. num_chunks = dsid.get_num_chunks()
  1641. assert num_chunks == 100
  1642. ci = {}
  1643. for j in range(num_chunks):
  1644. si = dsid.get_chunk_info(j)
  1645. ci[si.chunk_offset] = si
  1646. def callback(chunk_info):
  1647. known = ci[chunk_info.chunk_offset]
  1648. assert chunk_info.chunk_offset == known.chunk_offset
  1649. assert chunk_info.filter_mask == known.filter_mask
  1650. assert chunk_info.byte_offset == known.byte_offset
  1651. assert chunk_info.size == known.size
  1652. dsid.chunk_iter(callback)
  1653. def test_empty_shape(writable_file):
  1654. ds = writable_file.create_dataset(make_name(), dtype='int32')
  1655. assert ds.shape is None
  1656. assert ds.maxshape is None
  1657. def test_zero_storage_size():
  1658. # https://github.com/h5py/h5py/issues/1475
  1659. from io import BytesIO
  1660. buf = BytesIO()
  1661. with h5py.File(buf, 'w') as fout:
  1662. fout.create_dataset('empty', dtype='uint8')
  1663. buf.seek(0)
  1664. with h5py.File(buf, 'r') as fin:
  1665. assert fin['empty'].chunks is None
  1666. assert fin['empty'].id.get_offset() is None
  1667. assert fin['empty'].id.get_storage_size() == 0
  1668. def test_python_int_uint64(writable_file):
  1669. # https://github.com/h5py/h5py/issues/1547
  1670. data = [np.iinfo(np.int64).max, np.iinfo(np.int64).max + 1]
  1671. # Check creating a new dataset
  1672. ds = writable_file.create_dataset(make_name(), data=data, dtype=np.uint64)
  1673. assert ds.dtype == np.dtype(np.uint64)
  1674. np.testing.assert_array_equal(ds[:], np.array(data, dtype=np.uint64))
  1675. # Check writing to an existing dataset
  1676. ds[:] = data
  1677. np.testing.assert_array_equal(ds[:], np.array(data, dtype=np.uint64))
  1678. def test_setitem_fancy_indexing(writable_file):
  1679. # https://github.com/h5py/h5py/issues/1593
  1680. arr = writable_file.create_dataset(make_name(), (5, 1000, 2), dtype=np.uint8)
  1681. block = np.random.randint(255, size=(5, 3, 2))
  1682. arr[:, [0, 2, 4], ...] = block
  1683. def test_vlen_spacepad():
  1684. with File(get_data_file_path("vlen_string_dset.h5")) as f:
  1685. assert f["DS1"][0] == b"Parting"
  1686. def test_vlen_nullterm():
  1687. with File(get_data_file_path("vlen_string_dset_utc.h5")) as f:
  1688. assert f["ds1"][0] == b"2009-12-20T10:16:18.662409Z"
  1689. def test_allow_unknown_filter(writable_file):
  1690. # apparently 256-511 are reserved for testing purposes
  1691. fake_filter_id = 256
  1692. ds = writable_file.create_dataset(
  1693. make_name(), shape=(10, 10), dtype=np.uint8, compression=fake_filter_id,
  1694. allow_unknown_filter=True
  1695. )
  1696. assert str(fake_filter_id) in ds._filters
  1697. assert ds.compression == 'unknown'
  1698. def test_dset_chunk_cache():
  1699. """Chunk cache configuration for individual datasets."""
  1700. from io import BytesIO
  1701. buf = BytesIO()
  1702. name = make_name()
  1703. with h5py.File(buf, 'w') as fout:
  1704. ds = fout.create_dataset(
  1705. name, shape=(10, 20), chunks=(5, 4), dtype='i4',
  1706. rdcc_nbytes=2 * 1024 * 1024, rdcc_w0=0.2, rdcc_nslots=997)
  1707. ds_chunk_cache = ds.id.get_access_plist().get_chunk_cache()
  1708. assert fout.id.get_access_plist().get_cache()[1:] != ds_chunk_cache
  1709. assert ds_chunk_cache == (997, 2 * 1024 * 1024, 0.2)
  1710. buf.seek(0)
  1711. with h5py.File(buf, 'r') as fin:
  1712. ds = fin.require_dataset(
  1713. name, shape=(10, 20), dtype='i4',
  1714. rdcc_nbytes=3 * 1024 * 1024, rdcc_w0=0.67, rdcc_nslots=709)
  1715. ds_chunk_cache = ds.id.get_access_plist().get_chunk_cache()
  1716. assert fin.id.get_access_plist().get_cache()[1:] != ds_chunk_cache
  1717. assert ds_chunk_cache == (709, 3 * 1024 * 1024, 0.67)
  1718. class TestCommutative(BaseDataset):
  1719. """
  1720. Test the symmetry of operators, at least with the numpy types.
  1721. Issue: https://github.com/h5py/h5py/issues/1947
  1722. """
  1723. def test_numpy_commutative(self,):
  1724. """
  1725. Create a h5py dataset, extract one element convert to numpy
  1726. Check that it returns symmetric response to == and !=
  1727. """
  1728. shape = (100,1)
  1729. dset = self.f.create_dataset(make_name(), shape, dtype=float,
  1730. data=np.random.rand(*shape))
  1731. # grab a value from the elements, ie dset[0, 0]
  1732. # check that mask arrays are commutative wrt ==, !=
  1733. val = np.float64(dset[0, 0])
  1734. assert np.all((val == dset) == (dset == val))
  1735. assert np.all((val != dset) == (dset != val))
  1736. # generate sample not in the dset, ie max(dset)+delta
  1737. # check that mask arrays are commutative wrt ==, !=
  1738. delta = 0.001
  1739. nval = np.nanmax(dset)+delta
  1740. assert np.all((nval == dset) == (dset == nval))
  1741. assert np.all((nval != dset) == (dset != nval))
  1742. def test_basetype_commutative(self,):
  1743. """
  1744. Create a h5py dataset and check basetype compatibility.
  1745. Check that operation is symmetric, even if it is potentially
  1746. not meaningful.
  1747. """
  1748. shape = (100,1)
  1749. dset = self.f.create_dataset(make_name(), shape, dtype=float,
  1750. data=np.random.rand(*shape))
  1751. # generate float type, sample float(0.)
  1752. # check that operation is symmetric (but potentially meaningless)
  1753. val = float(0.)
  1754. assert (val == dset) == (dset == val)
  1755. assert (val != dset) == (dset != val)
  1756. class TestVirtualPrefix(BaseDataset):
  1757. """
  1758. Test setting virtual prefix
  1759. """
  1760. def test_virtual_prefix_create(self):
  1761. shape = (100,1)
  1762. virtual_prefix = "/path/to/virtual"
  1763. dset = self.f.create_dataset(make_name(), shape, dtype=float,
  1764. data=np.random.rand(*shape),
  1765. virtual_prefix = virtual_prefix)
  1766. virtual_prefix_readback = pathlib.Path(dset.id.get_access_plist().get_virtual_prefix().decode()).as_posix()
  1767. assert virtual_prefix_readback == virtual_prefix
  1768. def test_virtual_prefix_require(self):
  1769. virtual_prefix = "/path/to/virtual"
  1770. dset = self.f.require_dataset(make_name(), (10, 3), 'f', virtual_prefix = virtual_prefix)
  1771. virtual_prefix_readback = pathlib.Path(dset.id.get_access_plist().get_virtual_prefix().decode()).as_posix()
  1772. self.assertEqual(virtual_prefix, virtual_prefix_readback)
  1773. self.assertIsInstance(dset, Dataset)
  1774. self.assertEqual(dset.shape, (10, 3))
  1775. def ds_str(file, shape=(10, )):
  1776. dt = h5py.string_dtype(encoding='ascii')
  1777. fill_value = b'fill'
  1778. return file.create_dataset(make_name(), shape, dtype=dt, fillvalue=fill_value)
  1779. def ds_fields(file, shape=(10, )):
  1780. dt = np.dtype([
  1781. ('foo', h5py.string_dtype(encoding='ascii')),
  1782. ('bar', np.float64),
  1783. ])
  1784. fill_value = np.asarray(('fill', 0.0), dtype=dt)
  1785. name = make_name()
  1786. file[name] = np.broadcast_to(fill_value, shape)
  1787. return file[name]
  1788. view_getters = pytest.mark.parametrize(
  1789. "view_getter,make_ds",
  1790. [
  1791. (lambda ds: ds, ds_str),
  1792. (lambda ds: ds.astype(dtype=object), ds_str),
  1793. (lambda ds: ds.asstr(), ds_str),
  1794. (lambda ds: ds.fields("foo"), ds_fields),
  1795. ],
  1796. ids=["ds", "astype", "asstr", "fields"],
  1797. )
  1798. COPY_IF_NEEDED = False if NUMPY_RELEASE_VERSION < (2, 0) else None
  1799. @pytest.mark.parametrize("copy", [True, COPY_IF_NEEDED])
  1800. @view_getters
  1801. def test_array_copy(view_getter, make_ds, copy, writable_file):
  1802. ds = make_ds(writable_file)
  1803. view = view_getter(ds)
  1804. np.array(view, copy=copy)
  1805. @pytest.mark.skipif(
  1806. NUMPY_RELEASE_VERSION < (2, 0),
  1807. reason="forbidding copies requires numpy 2",
  1808. )
  1809. @view_getters
  1810. def test_array_copy_false(view_getter, make_ds, writable_file):
  1811. ds = make_ds(writable_file)
  1812. view = view_getter(ds)
  1813. with pytest.raises(ValueError, match="memory allocation cannot be avoided"):
  1814. np.array(view, copy=False)
  1815. @view_getters
  1816. def test_array_dtype(view_getter, make_ds, writable_file):
  1817. ds = make_ds(writable_file)
  1818. view = view_getter(ds)
  1819. assert np.array(view, dtype='|S10').dtype == np.dtype('|S10')
  1820. @view_getters
  1821. def test_array_scalar(view_getter, make_ds, writable_file):
  1822. ds = make_ds(writable_file, shape=())
  1823. view = view_getter(ds)
  1824. assert isinstance(view[()], (bytes, str))
  1825. assert np.array(view).shape == ()
  1826. @view_getters
  1827. def test_array_nd(view_getter, make_ds, writable_file):
  1828. ds = make_ds(writable_file, shape=(5, 6))
  1829. view = view_getter(ds)
  1830. assert np.array(view).shape == (5, 6)
  1831. @view_getters
  1832. def test_view_properties(view_getter, make_ds, writable_file):
  1833. ds = make_ds(writable_file, shape=(5, 6))
  1834. view = view_getter(ds)
  1835. assert view.dtype == np.dtype(object)
  1836. assert view.ndim == 2
  1837. assert view.shape == (5, 6)
  1838. assert view.size == 30
  1839. assert len(view) == 5
  1840. @pytest.mark.thread_unsafe(reason="spawns thread pool itself")
  1841. def test_concurrent_dataset_creation(writable_file):
  1842. N_THREADS = 25
  1843. N_DATASETS_PER_THREAD = 5
  1844. # Defines a thread barrier that will be spawned before parallel execution
  1845. # this increases the probability of concurrent access clashes.
  1846. barrier = threading.Barrier(N_THREADS)
  1847. def closure(ithread):
  1848. # Ensure that all threads reach this point before concurrent execution.
  1849. barrier.wait()
  1850. for j in range(N_DATASETS_PER_THREAD):
  1851. writable_file.create_dataset(f'concurrent_{ithread:02d}_{j:02d}', (1000,), dtype='i4')
  1852. with ThreadPoolExecutor(max_workers=N_THREADS) as executor:
  1853. futures = [executor.submit(closure, ithread) for ithread in range(N_THREADS)]
  1854. [f.result() for f in futures]
  1855. expected = set(f'concurrent_{i:02d}_{j:02d}' for i in range(N_THREADS) for j in range(N_DATASETS_PER_THREAD))
  1856. assert set(writable_file) == expected
  1857. def test_filter_properties(writable_file):
  1858. name = make_name()
  1859. ds = writable_file.create_dataset(
  1860. name, shape=1000, dtype=np.float32,
  1861. fletcher32=True, shuffle=True, compression='lzf'
  1862. )
  1863. assert ds.filter_ids == (
  1864. h5py.h5z.FILTER_SHUFFLE, h5py.h5z.FILTER_LZF, h5py.h5z.FILTER_FLETCHER32
  1865. )
  1866. assert ds.filter_names == ('shuffle', 'lzf', 'fletcher32')
  1867. def test_store_refs(writable_file):
  1868. ds1 = writable_file.create_dataset(make_name("foo"), data=np.arange(12))
  1869. refs_ds = writable_file.create_dataset(make_name("refs"), data=[writable_file.ref, ds1.ref])
  1870. assert isinstance(refs_ds[0], h5py.Reference)
  1871. assert writable_file[refs_ds[0]] == writable_file
  1872. assert isinstance(refs_ds[1], h5py.Reference)
  1873. assert writable_file[refs_ds[1]] == ds1
  1874. # Single reference
  1875. ref_scalar_ds = writable_file.create_dataset(make_name("ref_scalar"), data=ds1.ref)
  1876. assert isinstance(ref_scalar_ds[()], h5py.h5r.Reference)
  1877. assert writable_file[ref_scalar_ds[()]] == ds1
  1878. def test_store_regionrefs(writable_file):
  1879. ds1 = writable_file.create_dataset(make_name("foo"), data=np.arange(12))
  1880. regionrefs_ds = writable_file.create_dataset(make_name("regrefs"), data=[
  1881. ds1.regionref[:-1], ds1.regionref[1:]
  1882. ])
  1883. assert isinstance(regionrefs_ds[0], h5py.RegionReference)
  1884. np.testing.assert_array_equal(ds1[regionrefs_ds[0]], np.arange(11))
  1885. np.testing.assert_array_equal(ds1[regionrefs_ds[1]], np.arange(1, 12))
  1886. refs_ds = writable_file.create_dataset(make_name("refs"), shape=(1,), dtype=h5py.ref_dtype)
  1887. with pytest.raises(TypeError, match="convert"):
  1888. refs_ds[0] = ds1.regionref[:6]