test_netcdf.py 19 KB

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