PageRenderTime 27ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/dnaCompleteExome_optimized/pymodules/python2.7/lib/python/scipy/io/tests/test_netcdf.py

https://gitlab.com/pooja043/Globus_Docker_3
Python | 339 lines | 237 code | 64 blank | 38 comment | 42 complexity | b44e37846a81f264d1800baf04983a48 MD5 | raw file
  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_raises,
  13. assert_equal, run_module_suite)
  14. from scipy.io.netcdf 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 test_read_write_files():
  38. # test round trip for example file
  39. cwd = os.getcwd()
  40. try:
  41. tmpdir = tempfile.mkdtemp()
  42. os.chdir(tmpdir)
  43. with make_simple('simple.nc', 'w') as f:
  44. pass
  45. # read the file we just created in 'a' mode
  46. with netcdf_file('simple.nc', 'a') as f:
  47. check_simple(f)
  48. # add something
  49. f._attributes['appendRan'] = 1
  50. # To read the NetCDF file we just created::
  51. with netcdf_file('simple.nc') as f:
  52. # Using mmap is the default
  53. assert_(f.use_mmap)
  54. check_simple(f)
  55. assert_equal(f._attributes['appendRan'], 1)
  56. # Read it in append (and check mmap is off)
  57. with netcdf_file('simple.nc', 'a') as f:
  58. assert_(not f.use_mmap)
  59. check_simple(f)
  60. assert_equal(f._attributes['appendRan'], 1)
  61. # Now without mmap
  62. with netcdf_file('simple.nc', mmap=False) as f:
  63. # Using mmap is the default
  64. assert_(not f.use_mmap)
  65. check_simple(f)
  66. # To read the NetCDF file we just created, as file object, no
  67. # mmap. When n * n_bytes(var_type) is not divisible by 4, this
  68. # raised an error in pupynere 1.0.12 and scipy rev 5893, because
  69. # calculated vsize was rounding up in units of 4 - see
  70. # http://www.unidata.ucar.edu/software/netcdf/docs/netcdf.html
  71. with open('simple.nc', 'rb') as fobj:
  72. with netcdf_file(fobj) as f:
  73. # by default, don't use mmap for file-like
  74. assert_(not f.use_mmap)
  75. check_simple(f)
  76. # Read file from fileobj, with mmap
  77. with open('simple.nc', 'rb') as fobj:
  78. with netcdf_file(fobj, mmap=True) as f:
  79. assert_(f.use_mmap)
  80. check_simple(f)
  81. # Again read it in append mode (adding another att)
  82. with open('simple.nc', 'r+b') as fobj:
  83. with netcdf_file(fobj, 'a') as f:
  84. assert_(not f.use_mmap)
  85. check_simple(f)
  86. f.createDimension('app_dim', 1)
  87. var = f.createVariable('app_var', 'i', ('app_dim',))
  88. var[:] = 42
  89. # And... check that app_var made it in...
  90. with netcdf_file('simple.nc') as f:
  91. check_simple(f)
  92. assert_equal(f.variables['app_var'][:], 42)
  93. except:
  94. os.chdir(cwd)
  95. shutil.rmtree(tmpdir)
  96. raise
  97. os.chdir(cwd)
  98. shutil.rmtree(tmpdir)
  99. def test_read_write_sio():
  100. eg_sio1 = BytesIO()
  101. with make_simple(eg_sio1, 'w') as f1:
  102. str_val = eg_sio1.getvalue()
  103. eg_sio2 = BytesIO(str_val)
  104. with netcdf_file(eg_sio2) as f2:
  105. check_simple(f2)
  106. # Test that error is raised if attempting mmap for sio
  107. eg_sio3 = BytesIO(str_val)
  108. assert_raises(ValueError, netcdf_file, eg_sio3, 'r', True)
  109. # Test 64-bit offset write / read
  110. eg_sio_64 = BytesIO()
  111. with make_simple(eg_sio_64, 'w', version=2) as f_64:
  112. str_val = eg_sio_64.getvalue()
  113. eg_sio_64 = BytesIO(str_val)
  114. with netcdf_file(eg_sio_64) as f_64:
  115. check_simple(f_64)
  116. assert_equal(f_64.version_byte, 2)
  117. # also when version 2 explicitly specified
  118. eg_sio_64 = BytesIO(str_val)
  119. with netcdf_file(eg_sio_64, version=2) as f_64:
  120. check_simple(f_64)
  121. assert_equal(f_64.version_byte, 2)
  122. def test_read_example_data():
  123. # read any example data files
  124. for fname in glob(pjoin(TEST_DATA_PATH, '*.nc')):
  125. with netcdf_file(fname, 'r') as f:
  126. pass
  127. with netcdf_file(fname, 'r', mmap=False) as f:
  128. pass
  129. def test_itemset_no_segfault_on_readonly():
  130. # Regression test for ticket #1202.
  131. # Open the test file in read-only mode.
  132. with warnings.catch_warnings():
  133. warnings.simplefilter("ignore")
  134. filename = pjoin(TEST_DATA_PATH, 'example_1.nc')
  135. with netcdf_file(filename, 'r') as f:
  136. time_var = f.variables['time']
  137. # time_var.assignValue(42) should raise a RuntimeError--not seg. fault!
  138. assert_raises(RuntimeError, time_var.assignValue, 42)
  139. def test_write_invalid_dtype():
  140. dtypes = ['int64', 'uint64']
  141. if np.dtype('int').itemsize == 8: # 64-bit machines
  142. dtypes.append('int')
  143. if np.dtype('uint').itemsize == 8: # 64-bit machines
  144. dtypes.append('uint')
  145. with netcdf_file(BytesIO(), 'w') as f:
  146. f.createDimension('time', N_EG_ELS)
  147. for dt in dtypes:
  148. assert_raises(ValueError, f.createVariable, 'time', dt, ('time',))
  149. def test_flush_rewind():
  150. stream = BytesIO()
  151. with make_simple(stream, mode='w') as f:
  152. x = f.createDimension('x',4)
  153. v = f.createVariable('v', 'i2', ['x'])
  154. v[:] = 1
  155. f.flush()
  156. len_single = len(stream.getvalue())
  157. f.flush()
  158. len_double = len(stream.getvalue())
  159. assert_(len_single == len_double)
  160. def test_dtype_specifiers():
  161. # Numpy 1.7.0-dev had a bug where 'i2' wouldn't work.
  162. # Specifying np.int16 or similar only works from the same commit as this
  163. # comment was made.
  164. with make_simple(BytesIO(), mode='w') as f:
  165. f.createDimension('x',4)
  166. f.createVariable('v1', 'i2', ['x'])
  167. f.createVariable('v2', np.int16, ['x'])
  168. f.createVariable('v3', np.dtype(np.int16), ['x'])
  169. def test_ticket_1720():
  170. io = BytesIO()
  171. items = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
  172. with netcdf_file(io, 'w') as f:
  173. f.history = 'Created for a test'
  174. f.createDimension('float_var', 10)
  175. float_var = f.createVariable('float_var', 'f', ('float_var',))
  176. float_var[:] = items
  177. float_var.units = 'metres'
  178. f.flush()
  179. contents = io.getvalue()
  180. io = BytesIO(contents)
  181. with netcdf_file(io, 'r') as f:
  182. assert_equal(f.history, b'Created for a test')
  183. float_var = f.variables['float_var']
  184. assert_equal(float_var.units, b'metres')
  185. assert_equal(float_var.shape, (10,))
  186. assert_allclose(float_var[:], items)
  187. def test_mmaps_segfault():
  188. filename = pjoin(TEST_DATA_PATH, 'example_1.nc')
  189. with warnings.catch_warnings():
  190. warnings.simplefilter("error")
  191. with netcdf_file(filename, mmap=True) as f:
  192. x = f.variables['lat'][:]
  193. # should not raise warnings
  194. del x
  195. def doit():
  196. with netcdf_file(filename, mmap=True) as f:
  197. return f.variables['lat'][:]
  198. # should not crash
  199. with warnings.catch_warnings():
  200. warnings.simplefilter("ignore")
  201. x = doit()
  202. x.sum()
  203. def test_zero_dimensional_var():
  204. io = BytesIO()
  205. with make_simple(io, 'w') as f:
  206. v = f.createVariable('zerodim', 'i2', [])
  207. # This is checking that .isrec returns a boolean - don't simplify it
  208. # to 'assert not ...'
  209. assert v.isrec is False, v.isrec
  210. f.flush()
  211. def test_byte_gatts():
  212. # Check that global "string" atts work like they did before py3k
  213. # unicode and general bytes confusion
  214. with in_tempdir():
  215. filename = 'g_byte_atts.nc'
  216. f = netcdf_file(filename, 'w')
  217. f._attributes['holy'] = b'grail'
  218. f._attributes['witch'] = 'floats'
  219. f.close()
  220. f = netcdf_file(filename, 'r')
  221. assert_equal(f._attributes['holy'], b'grail')
  222. assert_equal(f._attributes['witch'], b'floats')
  223. f.close()
  224. def test_open_append():
  225. # open 'w' put one attr
  226. with in_tempdir():
  227. filename = 'append_dat.nc'
  228. f = netcdf_file(filename, 'w')
  229. f._attributes['Kilroy'] = 'was here'
  230. f.close()
  231. # open again in 'a', read the att and and a new one
  232. f = netcdf_file(filename, 'a')
  233. assert_equal(f._attributes['Kilroy'], b'was here')
  234. f._attributes['naughty'] = b'Zoot'
  235. f.close()
  236. # open yet again in 'r' and check both atts
  237. f = netcdf_file(filename, 'r')
  238. assert_equal(f._attributes['Kilroy'], b'was here')
  239. assert_equal(f._attributes['naughty'], b'Zoot')
  240. f.close()
  241. def test_maskandscale():
  242. t = np.linspace(20, 30, 15)
  243. t[3] = 100
  244. tm = np.ma.masked_greater(t, 99)
  245. fname = pjoin(TEST_DATA_PATH, 'example_2.nc')
  246. with netcdf_file(fname, maskandscale=True) as f:
  247. Temp = f.variables['Temperature']
  248. assert_equal(Temp.missing_value, 9999)
  249. assert_equal(Temp.add_offset, 20)
  250. assert_equal(Temp.scale_factor, np.float32(0.01))
  251. found = Temp[:].compressed()
  252. del Temp # Remove ref to mmap, so file can be closed.
  253. expected = np.round(tm.compressed(), 2)
  254. assert_allclose(found, expected)
  255. with in_tempdir():
  256. newfname = 'ms.nc'
  257. f = netcdf_file(newfname, 'w', maskandscale=True)
  258. f.createDimension('Temperature', len(tm))
  259. temp = f.createVariable('Temperature', 'i', ('Temperature',))
  260. temp.missing_value = 9999
  261. temp.scale_factor = 0.01
  262. temp.add_offset = 20
  263. temp[:] = tm
  264. f.close()
  265. with netcdf_file(newfname, maskandscale=True) as f:
  266. Temp = f.variables['Temperature']
  267. assert_equal(Temp.missing_value, 9999)
  268. assert_equal(Temp.add_offset, 20)
  269. assert_equal(Temp.scale_factor, np.float32(0.01))
  270. expected = np.round(tm.compressed(), 2)
  271. found = Temp[:].compressed()
  272. del Temp
  273. assert_allclose(found, expected)
  274. if __name__ == "__main__":
  275. run_module_suite()