test_netcdf.py 19 KB

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