test_netcdf.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. ''' Tests for netcdf '''
  2. import os
  3. from os.path import join as pjoin, dirname
  4. import shutil
  5. import tempfile
  6. import warnings
  7. from io import BytesIO
  8. from glob import glob
  9. from contextlib import contextmanager
  10. import numpy as np
  11. from numpy.testing import (assert_, assert_allclose, assert_equal,
  12. break_cycles, suppress_warnings, IS_PYPY)
  13. from pytest import raises as assert_raises
  14. from scipy.io import netcdf_file
  15. from scipy._lib._tmpdirs import in_tempdir
  16. TEST_DATA_PATH = pjoin(dirname(__file__), 'data')
  17. N_EG_ELS = 11 # number of elements for example variable
  18. VARTYPE_EG = 'b' # var type for example variable
  19. @contextmanager
  20. def make_simple(*args, **kwargs):
  21. f = netcdf_file(*args, **kwargs)
  22. f.history = 'Created for a test'
  23. f.createDimension('time', N_EG_ELS)
  24. time = f.createVariable('time', VARTYPE_EG, ('time',))
  25. time[:] = np.arange(N_EG_ELS)
  26. time.units = 'days since 2008-01-01'
  27. f.flush()
  28. yield f
  29. f.close()
  30. def check_simple(ncfileobj):
  31. '''Example fileobj tests '''
  32. assert_equal(ncfileobj.history, b'Created for a test')
  33. time = ncfileobj.variables['time']
  34. assert_equal(time.units, b'days since 2008-01-01')
  35. assert_equal(time.shape, (N_EG_ELS,))
  36. assert_equal(time[-1], N_EG_ELS-1)
  37. def assert_mask_matches(arr, expected_mask):
  38. '''
  39. Asserts that the mask of arr is effectively the same as expected_mask.
  40. In contrast to numpy.ma.testutils.assert_mask_equal, this function allows
  41. testing the 'mask' of a standard numpy array (the mask in this case is treated
  42. as all False).
  43. Parameters
  44. ----------
  45. arr : ndarray or MaskedArray
  46. Array to test.
  47. expected_mask : array_like of booleans
  48. A list giving the expected mask.
  49. '''
  50. mask = np.ma.getmaskarray(arr)
  51. assert_equal(mask, expected_mask)
  52. def test_read_write_files():
  53. # test round trip for example file
  54. cwd = os.getcwd()
  55. try:
  56. tmpdir = tempfile.mkdtemp()
  57. os.chdir(tmpdir)
  58. with make_simple('simple.nc', 'w') as f:
  59. pass
  60. # read the file we just created in 'a' mode
  61. with netcdf_file('simple.nc', 'a') as f:
  62. check_simple(f)
  63. # add something
  64. f._attributes['appendRan'] = 1
  65. # To read the NetCDF file we just created::
  66. with netcdf_file('simple.nc') as f:
  67. # Using mmap is the default (but not on pypy)
  68. assert_equal(f.use_mmap, not IS_PYPY)
  69. check_simple(f)
  70. assert_equal(f._attributes['appendRan'], 1)
  71. # Read it in append (and check mmap is off)
  72. with netcdf_file('simple.nc', 'a') as f:
  73. assert_(not f.use_mmap)
  74. check_simple(f)
  75. assert_equal(f._attributes['appendRan'], 1)
  76. # Now without mmap
  77. with netcdf_file('simple.nc', mmap=False) as f:
  78. # Using mmap is the default
  79. assert_(not f.use_mmap)
  80. check_simple(f)
  81. # To read the NetCDF file we just created, as file object, no
  82. # mmap. When n * n_bytes(var_type) is not divisible by 4, this
  83. # raised an error in pupynere 1.0.12 and scipy rev 5893, because
  84. # calculated vsize was rounding up in units of 4 - see
  85. # https://www.unidata.ucar.edu/software/netcdf/guide_toc.html
  86. with open('simple.nc', 'rb') as fobj:
  87. with netcdf_file(fobj) as f:
  88. # by default, don't use mmap for file-like
  89. assert_(not f.use_mmap)
  90. check_simple(f)
  91. # Read file from fileobj, with mmap
  92. with suppress_warnings() as sup:
  93. if IS_PYPY:
  94. sup.filter(RuntimeWarning,
  95. "Cannot close a netcdf_file opened with mmap=True.*")
  96. with open('simple.nc', 'rb') as fobj:
  97. with netcdf_file(fobj, mmap=True) as f:
  98. assert_(f.use_mmap)
  99. check_simple(f)
  100. # Again read it in append mode (adding another att)
  101. with open('simple.nc', 'r+b') as fobj:
  102. with netcdf_file(fobj, 'a') as f:
  103. assert_(not f.use_mmap)
  104. check_simple(f)
  105. f.createDimension('app_dim', 1)
  106. var = f.createVariable('app_var', 'i', ('app_dim',))
  107. var[:] = 42
  108. # And... check that app_var made it in...
  109. with netcdf_file('simple.nc') as f:
  110. check_simple(f)
  111. assert_equal(f.variables['app_var'][:], 42)
  112. finally:
  113. if IS_PYPY:
  114. # windows cannot remove a dead file held by a mmap
  115. # that has not been collected in PyPy
  116. break_cycles()
  117. break_cycles()
  118. os.chdir(cwd)
  119. shutil.rmtree(tmpdir)
  120. def test_read_write_sio():
  121. eg_sio1 = BytesIO()
  122. with make_simple(eg_sio1, 'w'):
  123. str_val = eg_sio1.getvalue()
  124. eg_sio2 = BytesIO(str_val)
  125. with netcdf_file(eg_sio2) as f2:
  126. check_simple(f2)
  127. # Test that error is raised if attempting mmap for sio
  128. eg_sio3 = BytesIO(str_val)
  129. assert_raises(ValueError, netcdf_file, eg_sio3, 'r', True)
  130. # Test 64-bit offset write / read
  131. eg_sio_64 = BytesIO()
  132. with make_simple(eg_sio_64, 'w', version=2) as f_64:
  133. str_val = eg_sio_64.getvalue()
  134. eg_sio_64 = BytesIO(str_val)
  135. with netcdf_file(eg_sio_64) as f_64:
  136. check_simple(f_64)
  137. assert_equal(f_64.version_byte, 2)
  138. # also when version 2 explicitly specified
  139. eg_sio_64 = BytesIO(str_val)
  140. with netcdf_file(eg_sio_64, version=2) as f_64:
  141. check_simple(f_64)
  142. assert_equal(f_64.version_byte, 2)
  143. def test_bytes():
  144. raw_file = BytesIO()
  145. f = netcdf_file(raw_file, mode='w')
  146. # Dataset only has a single variable, dimension and attribute to avoid
  147. # any ambiguity related to order.
  148. f.a = 'b'
  149. f.createDimension('dim', 1)
  150. var = f.createVariable('var', np.int16, ('dim',))
  151. var[0] = -9999
  152. var.c = 'd'
  153. f.sync()
  154. actual = raw_file.getvalue()
  155. expected = (b'CDF\x01'
  156. b'\x00\x00\x00\x00'
  157. b'\x00\x00\x00\x0a'
  158. b'\x00\x00\x00\x01'
  159. b'\x00\x00\x00\x03'
  160. b'dim\x00'
  161. b'\x00\x00\x00\x01'
  162. b'\x00\x00\x00\x0c'
  163. b'\x00\x00\x00\x01'
  164. b'\x00\x00\x00\x01'
  165. b'a\x00\x00\x00'
  166. b'\x00\x00\x00\x02'
  167. b'\x00\x00\x00\x01'
  168. b'b\x00\x00\x00'
  169. b'\x00\x00\x00\x0b'
  170. b'\x00\x00\x00\x01'
  171. b'\x00\x00\x00\x03'
  172. b'var\x00'
  173. b'\x00\x00\x00\x01'
  174. b'\x00\x00\x00\x00'
  175. b'\x00\x00\x00\x0c'
  176. b'\x00\x00\x00\x01'
  177. b'\x00\x00\x00\x01'
  178. b'c\x00\x00\x00'
  179. b'\x00\x00\x00\x02'
  180. b'\x00\x00\x00\x01'
  181. b'd\x00\x00\x00'
  182. b'\x00\x00\x00\x03'
  183. b'\x00\x00\x00\x04'
  184. b'\x00\x00\x00\x78'
  185. b'\xd8\xf1\x80\x01')
  186. assert_equal(actual, expected)
  187. def test_encoded_fill_value():
  188. with netcdf_file(BytesIO(), mode='w') as f:
  189. f.createDimension('x', 1)
  190. var = f.createVariable('var', 'S1', ('x',))
  191. assert_equal(var._get_encoded_fill_value(), b'\x00')
  192. var._FillValue = b'\x01'
  193. assert_equal(var._get_encoded_fill_value(), b'\x01')
  194. var._FillValue = b'\x00\x00' # invalid, wrong size
  195. assert_equal(var._get_encoded_fill_value(), b'\x00')
  196. def test_read_example_data():
  197. # read any example data files
  198. for fname in glob(pjoin(TEST_DATA_PATH, '*.nc')):
  199. with netcdf_file(fname, 'r'):
  200. pass
  201. with netcdf_file(fname, 'r', mmap=False):
  202. pass
  203. def test_itemset_no_segfault_on_readonly():
  204. # Regression test for ticket #1202.
  205. # Open the test file in read-only mode.
  206. filename = pjoin(TEST_DATA_PATH, 'example_1.nc')
  207. with suppress_warnings() as sup:
  208. sup.filter(RuntimeWarning,
  209. "Cannot close a netcdf_file opened with mmap=True, when netcdf_variables or arrays referring to its data still exist")
  210. with netcdf_file(filename, 'r', mmap=True) as f:
  211. time_var = f.variables['time']
  212. # time_var.assignValue(42) should raise a RuntimeError--not seg. fault!
  213. assert_raises(RuntimeError, time_var.assignValue, 42)
  214. def test_appending_issue_gh_8625():
  215. stream = BytesIO()
  216. with make_simple(stream, mode='w') as f:
  217. f.createDimension('x', 2)
  218. f.createVariable('x', float, ('x',))
  219. f.variables['x'][...] = 1
  220. f.flush()
  221. contents = stream.getvalue()
  222. stream = BytesIO(contents)
  223. with netcdf_file(stream, mode='a') as f:
  224. f.variables['x'][...] = 2
  225. def test_write_invalid_dtype():
  226. dtypes = ['int64', 'uint64']
  227. if np.dtype('int').itemsize == 8: # 64-bit machines
  228. dtypes.append('int')
  229. if np.dtype('uint').itemsize == 8: # 64-bit machines
  230. dtypes.append('uint')
  231. with netcdf_file(BytesIO(), 'w') as f:
  232. f.createDimension('time', N_EG_ELS)
  233. for dt in dtypes:
  234. assert_raises(ValueError, f.createVariable, 'time', dt, ('time',))
  235. def test_flush_rewind():
  236. stream = BytesIO()
  237. with make_simple(stream, mode='w') as f:
  238. x = f.createDimension('x',4) # x is used in createVariable
  239. v = f.createVariable('v', 'i2', ['x'])
  240. v[:] = 1
  241. f.flush()
  242. len_single = len(stream.getvalue())
  243. f.flush()
  244. len_double = len(stream.getvalue())
  245. assert_(len_single == len_double)
  246. def test_dtype_specifiers():
  247. # Numpy 1.7.0-dev had a bug where 'i2' wouldn't work.
  248. # Specifying np.int16 or similar only works from the same commit as this
  249. # comment was made.
  250. with make_simple(BytesIO(), mode='w') as f:
  251. f.createDimension('x',4)
  252. f.createVariable('v1', 'i2', ['x'])
  253. f.createVariable('v2', np.int16, ['x'])
  254. f.createVariable('v3', np.dtype(np.int16), ['x'])
  255. def test_ticket_1720():
  256. io = BytesIO()
  257. items = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
  258. with netcdf_file(io, 'w') as f:
  259. f.history = 'Created for a test'
  260. f.createDimension('float_var', 10)
  261. float_var = f.createVariable('float_var', 'f', ('float_var',))
  262. float_var[:] = items
  263. float_var.units = 'metres'
  264. f.flush()
  265. contents = io.getvalue()
  266. io = BytesIO(contents)
  267. with netcdf_file(io, 'r') as f:
  268. assert_equal(f.history, b'Created for a test')
  269. float_var = f.variables['float_var']
  270. assert_equal(float_var.units, b'metres')
  271. assert_equal(float_var.shape, (10,))
  272. assert_allclose(float_var[:], items)
  273. def test_mmaps_segfault():
  274. filename = pjoin(TEST_DATA_PATH, 'example_1.nc')
  275. if not IS_PYPY:
  276. with warnings.catch_warnings():
  277. warnings.simplefilter("error")
  278. with netcdf_file(filename, mmap=True) as f:
  279. x = f.variables['lat'][:]
  280. # should not raise warnings
  281. del x
  282. def doit():
  283. with netcdf_file(filename, mmap=True) as f:
  284. return f.variables['lat'][:]
  285. # should not crash
  286. with suppress_warnings() as sup:
  287. sup.filter(RuntimeWarning,
  288. "Cannot close a netcdf_file opened with mmap=True, when netcdf_variables or arrays referring to its data still exist")
  289. x = doit()
  290. x.sum()
  291. def test_zero_dimensional_var():
  292. io = BytesIO()
  293. with make_simple(io, 'w') as f:
  294. v = f.createVariable('zerodim', 'i2', [])
  295. # This is checking that .isrec returns a boolean - don't simplify it
  296. # to 'assert not ...'
  297. assert v.isrec is False, v.isrec
  298. f.flush()
  299. def test_byte_gatts():
  300. # Check that global "string" atts work like they did before py3k
  301. # unicode and general bytes confusion
  302. with in_tempdir():
  303. filename = 'g_byte_atts.nc'
  304. f = netcdf_file(filename, 'w')
  305. f._attributes['holy'] = b'grail'
  306. f._attributes['witch'] = 'floats'
  307. f.close()
  308. f = netcdf_file(filename, 'r')
  309. assert_equal(f._attributes['holy'], b'grail')
  310. assert_equal(f._attributes['witch'], b'floats')
  311. f.close()
  312. def test_open_append():
  313. # open 'w' put one attr
  314. with in_tempdir():
  315. filename = 'append_dat.nc'
  316. f = netcdf_file(filename, 'w')
  317. f._attributes['Kilroy'] = 'was here'
  318. f.close()
  319. # open again in 'a', read the att and a new one
  320. f = netcdf_file(filename, 'a')
  321. assert_equal(f._attributes['Kilroy'], b'was here')
  322. f._attributes['naughty'] = b'Zoot'
  323. f.close()
  324. # open yet again in 'r' and check both atts
  325. f = netcdf_file(filename, 'r')
  326. assert_equal(f._attributes['Kilroy'], b'was here')
  327. assert_equal(f._attributes['naughty'], b'Zoot')
  328. f.close()
  329. def test_append_recordDimension():
  330. dataSize = 100
  331. with in_tempdir():
  332. # Create file with record time dimension
  333. with netcdf_file('withRecordDimension.nc', 'w') as f:
  334. f.createDimension('time', None)
  335. f.createVariable('time', 'd', ('time',))
  336. f.createDimension('x', dataSize)
  337. x = f.createVariable('x', 'd', ('x',))
  338. x[:] = np.array(range(dataSize))
  339. f.createDimension('y', dataSize)
  340. y = f.createVariable('y', 'd', ('y',))
  341. y[:] = np.array(range(dataSize))
  342. f.createVariable('testData', 'i', ('time', 'x', 'y'))
  343. f.flush()
  344. f.close()
  345. for i in range(2):
  346. # Open the file in append mode and add data
  347. with netcdf_file('withRecordDimension.nc', 'a') as f:
  348. f.variables['time'].data = np.append(f.variables["time"].data, i)
  349. f.variables['testData'][i, :, :] = np.full((dataSize, dataSize), i)
  350. f.flush()
  351. # Read the file and check that append worked
  352. with netcdf_file('withRecordDimension.nc') as f:
  353. assert_equal(f.variables['time'][-1], i)
  354. assert_equal(f.variables['testData'][-1, :, :].copy(), np.full((dataSize, dataSize), i))
  355. assert_equal(f.variables['time'].data.shape[0], i+1)
  356. assert_equal(f.variables['testData'].data.shape[0], i+1)
  357. # Read the file and check that 'data' was not saved as user defined
  358. # attribute of testData variable during append operation
  359. with netcdf_file('withRecordDimension.nc') as f:
  360. with assert_raises(KeyError) as ar:
  361. f.variables['testData']._attributes['data']
  362. ex = ar.value
  363. assert_equal(ex.args[0], 'data')
  364. def test_maskandscale():
  365. t = np.linspace(20, 30, 15)
  366. t[3] = 100
  367. tm = np.ma.masked_greater(t, 99)
  368. fname = pjoin(TEST_DATA_PATH, 'example_2.nc')
  369. with netcdf_file(fname, maskandscale=True) as f:
  370. Temp = f.variables['Temperature']
  371. assert_equal(Temp.missing_value, 9999)
  372. assert_equal(Temp.add_offset, 20)
  373. assert_equal(Temp.scale_factor, np.float32(0.01))
  374. found = Temp[:].compressed()
  375. del Temp # Remove ref to mmap, so file can be closed.
  376. expected = np.round(tm.compressed(), 2)
  377. assert_allclose(found, expected)
  378. with in_tempdir():
  379. newfname = 'ms.nc'
  380. f = netcdf_file(newfname, 'w', maskandscale=True)
  381. f.createDimension('Temperature', len(tm))
  382. temp = f.createVariable('Temperature', 'i', ('Temperature',))
  383. temp.missing_value = 9999
  384. temp.scale_factor = 0.01
  385. temp.add_offset = 20
  386. temp[:] = tm
  387. f.close()
  388. with netcdf_file(newfname, maskandscale=True) as f:
  389. Temp = f.variables['Temperature']
  390. assert_equal(Temp.missing_value, 9999)
  391. assert_equal(Temp.add_offset, 20)
  392. assert_equal(Temp.scale_factor, np.float32(0.01))
  393. expected = np.round(tm.compressed(), 2)
  394. found = Temp[:].compressed()
  395. del Temp
  396. assert_allclose(found, expected)
  397. # ------------------------------------------------------------------------
  398. # Test reading with masked values (_FillValue / missing_value)
  399. # ------------------------------------------------------------------------
  400. def test_read_withValuesNearFillValue():
  401. # Regression test for ticket #5626
  402. fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
  403. with netcdf_file(fname, maskandscale=True) as f:
  404. vardata = f.variables['var1_fillval0'][:]
  405. assert_mask_matches(vardata, [False, True, False])
  406. def test_read_withNoFillValue():
  407. # For a variable with no fill value, reading data with maskandscale=True
  408. # should return unmasked data
  409. fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
  410. with netcdf_file(fname, maskandscale=True) as f:
  411. vardata = f.variables['var2_noFillval'][:]
  412. assert_mask_matches(vardata, [False, False, False])
  413. assert_equal(vardata, [1,2,3])
  414. def test_read_withFillValueAndMissingValue():
  415. # For a variable with both _FillValue and missing_value, the _FillValue
  416. # should be used
  417. IRRELEVANT_VALUE = 9999
  418. fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
  419. with netcdf_file(fname, maskandscale=True) as f:
  420. vardata = f.variables['var3_fillvalAndMissingValue'][:]
  421. assert_mask_matches(vardata, [True, False, False])
  422. assert_equal(vardata, [IRRELEVANT_VALUE, 2, 3])
  423. def test_read_withMissingValue():
  424. # For a variable with missing_value but not _FillValue, the missing_value
  425. # should be used
  426. fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
  427. with netcdf_file(fname, maskandscale=True) as f:
  428. vardata = f.variables['var4_missingValue'][:]
  429. assert_mask_matches(vardata, [False, True, False])
  430. def test_read_withFillValNaN():
  431. fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
  432. with netcdf_file(fname, maskandscale=True) as f:
  433. vardata = f.variables['var5_fillvalNaN'][:]
  434. assert_mask_matches(vardata, [False, True, False])
  435. def test_read_withChar():
  436. fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
  437. with netcdf_file(fname, maskandscale=True) as f:
  438. vardata = f.variables['var6_char'][:]
  439. assert_mask_matches(vardata, [False, True, False])
  440. def test_read_with2dVar():
  441. fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
  442. with netcdf_file(fname, maskandscale=True) as f:
  443. vardata = f.variables['var7_2d'][:]
  444. assert_mask_matches(vardata, [[True, False], [False, False], [False, True]])
  445. def test_read_withMaskAndScaleFalse():
  446. # If a variable has a _FillValue (or missing_value) attribute, but is read
  447. # with maskandscale set to False, the result should be unmasked
  448. fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
  449. # Open file with mmap=False to avoid problems with closing a mmap'ed file
  450. # when arrays referring to its data still exist:
  451. with netcdf_file(fname, maskandscale=False, mmap=False) as f:
  452. vardata = f.variables['var3_fillvalAndMissingValue'][:]
  453. assert_mask_matches(vardata, [False, False, False])
  454. assert_equal(vardata, [1, 2, 3])