test__iotools.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. from __future__ import division, absolute_import, print_function
  2. import time
  3. from datetime import date
  4. import numpy as np
  5. from numpy.testing import (
  6. assert_, assert_equal, assert_allclose, assert_raises,
  7. )
  8. from numpy.lib._iotools import (
  9. LineSplitter, NameValidator, StringConverter,
  10. has_nested_fields, easy_dtype, flatten_dtype
  11. )
  12. from numpy.compat import unicode
  13. class TestLineSplitter(object):
  14. "Tests the LineSplitter class."
  15. def test_no_delimiter(self):
  16. "Test LineSplitter w/o delimiter"
  17. strg = " 1 2 3 4 5 # test"
  18. test = LineSplitter()(strg)
  19. assert_equal(test, ['1', '2', '3', '4', '5'])
  20. test = LineSplitter('')(strg)
  21. assert_equal(test, ['1', '2', '3', '4', '5'])
  22. def test_space_delimiter(self):
  23. "Test space delimiter"
  24. strg = " 1 2 3 4 5 # test"
  25. test = LineSplitter(' ')(strg)
  26. assert_equal(test, ['1', '2', '3', '4', '', '5'])
  27. test = LineSplitter(' ')(strg)
  28. assert_equal(test, ['1 2 3 4', '5'])
  29. def test_tab_delimiter(self):
  30. "Test tab delimiter"
  31. strg = " 1\t 2\t 3\t 4\t 5 6"
  32. test = LineSplitter('\t')(strg)
  33. assert_equal(test, ['1', '2', '3', '4', '5 6'])
  34. strg = " 1 2\t 3 4\t 5 6"
  35. test = LineSplitter('\t')(strg)
  36. assert_equal(test, ['1 2', '3 4', '5 6'])
  37. def test_other_delimiter(self):
  38. "Test LineSplitter on delimiter"
  39. strg = "1,2,3,4,,5"
  40. test = LineSplitter(',')(strg)
  41. assert_equal(test, ['1', '2', '3', '4', '', '5'])
  42. #
  43. strg = " 1,2,3,4,,5 # test"
  44. test = LineSplitter(',')(strg)
  45. assert_equal(test, ['1', '2', '3', '4', '', '5'])
  46. # gh-11028 bytes comment/delimiters should get encoded
  47. strg = b" 1,2,3,4,,5 % test"
  48. test = LineSplitter(delimiter=b',', comments=b'%')(strg)
  49. assert_equal(test, ['1', '2', '3', '4', '', '5'])
  50. def test_constant_fixed_width(self):
  51. "Test LineSplitter w/ fixed-width fields"
  52. strg = " 1 2 3 4 5 # test"
  53. test = LineSplitter(3)(strg)
  54. assert_equal(test, ['1', '2', '3', '4', '', '5', ''])
  55. #
  56. strg = " 1 3 4 5 6# test"
  57. test = LineSplitter(20)(strg)
  58. assert_equal(test, ['1 3 4 5 6'])
  59. #
  60. strg = " 1 3 4 5 6# test"
  61. test = LineSplitter(30)(strg)
  62. assert_equal(test, ['1 3 4 5 6'])
  63. def test_variable_fixed_width(self):
  64. strg = " 1 3 4 5 6# test"
  65. test = LineSplitter((3, 6, 6, 3))(strg)
  66. assert_equal(test, ['1', '3', '4 5', '6'])
  67. #
  68. strg = " 1 3 4 5 6# test"
  69. test = LineSplitter((6, 6, 9))(strg)
  70. assert_equal(test, ['1', '3 4', '5 6'])
  71. # -----------------------------------------------------------------------------
  72. class TestNameValidator(object):
  73. def test_case_sensitivity(self):
  74. "Test case sensitivity"
  75. names = ['A', 'a', 'b', 'c']
  76. test = NameValidator().validate(names)
  77. assert_equal(test, ['A', 'a', 'b', 'c'])
  78. test = NameValidator(case_sensitive=False).validate(names)
  79. assert_equal(test, ['A', 'A_1', 'B', 'C'])
  80. test = NameValidator(case_sensitive='upper').validate(names)
  81. assert_equal(test, ['A', 'A_1', 'B', 'C'])
  82. test = NameValidator(case_sensitive='lower').validate(names)
  83. assert_equal(test, ['a', 'a_1', 'b', 'c'])
  84. # check exceptions
  85. assert_raises(ValueError, NameValidator, case_sensitive='foobar')
  86. def test_excludelist(self):
  87. "Test excludelist"
  88. names = ['dates', 'data', 'Other Data', 'mask']
  89. validator = NameValidator(excludelist=['dates', 'data', 'mask'])
  90. test = validator.validate(names)
  91. assert_equal(test, ['dates_', 'data_', 'Other_Data', 'mask_'])
  92. def test_missing_names(self):
  93. "Test validate missing names"
  94. namelist = ('a', 'b', 'c')
  95. validator = NameValidator()
  96. assert_equal(validator(namelist), ['a', 'b', 'c'])
  97. namelist = ('', 'b', 'c')
  98. assert_equal(validator(namelist), ['f0', 'b', 'c'])
  99. namelist = ('a', 'b', '')
  100. assert_equal(validator(namelist), ['a', 'b', 'f0'])
  101. namelist = ('', 'f0', '')
  102. assert_equal(validator(namelist), ['f1', 'f0', 'f2'])
  103. def test_validate_nb_names(self):
  104. "Test validate nb names"
  105. namelist = ('a', 'b', 'c')
  106. validator = NameValidator()
  107. assert_equal(validator(namelist, nbfields=1), ('a',))
  108. assert_equal(validator(namelist, nbfields=5, defaultfmt="g%i"),
  109. ['a', 'b', 'c', 'g0', 'g1'])
  110. def test_validate_wo_names(self):
  111. "Test validate no names"
  112. namelist = None
  113. validator = NameValidator()
  114. assert_(validator(namelist) is None)
  115. assert_equal(validator(namelist, nbfields=3), ['f0', 'f1', 'f2'])
  116. # -----------------------------------------------------------------------------
  117. def _bytes_to_date(s):
  118. return date(*time.strptime(s, "%Y-%m-%d")[:3])
  119. class TestStringConverter(object):
  120. "Test StringConverter"
  121. def test_creation(self):
  122. "Test creation of a StringConverter"
  123. converter = StringConverter(int, -99999)
  124. assert_equal(converter._status, 1)
  125. assert_equal(converter.default, -99999)
  126. def test_upgrade(self):
  127. "Tests the upgrade method."
  128. converter = StringConverter()
  129. assert_equal(converter._status, 0)
  130. # test int
  131. assert_equal(converter.upgrade('0'), 0)
  132. assert_equal(converter._status, 1)
  133. # On systems where long defaults to 32-bit, the statuses will be
  134. # offset by one, so we check for this here.
  135. import numpy.core.numeric as nx
  136. status_offset = int(nx.dtype(nx.int_).itemsize < nx.dtype(nx.int64).itemsize)
  137. # test int > 2**32
  138. assert_equal(converter.upgrade('17179869184'), 17179869184)
  139. assert_equal(converter._status, 1 + status_offset)
  140. # test float
  141. assert_allclose(converter.upgrade('0.'), 0.0)
  142. assert_equal(converter._status, 2 + status_offset)
  143. # test complex
  144. assert_equal(converter.upgrade('0j'), complex('0j'))
  145. assert_equal(converter._status, 3 + status_offset)
  146. # test str
  147. # note that the longdouble type has been skipped, so the
  148. # _status increases by 2. Everything should succeed with
  149. # unicode conversion (5).
  150. for s in ['a', u'a', b'a']:
  151. res = converter.upgrade(s)
  152. assert_(type(res) is unicode)
  153. assert_equal(res, u'a')
  154. assert_equal(converter._status, 5 + status_offset)
  155. def test_missing(self):
  156. "Tests the use of missing values."
  157. converter = StringConverter(missing_values=('missing',
  158. 'missed'))
  159. converter.upgrade('0')
  160. assert_equal(converter('0'), 0)
  161. assert_equal(converter(''), converter.default)
  162. assert_equal(converter('missing'), converter.default)
  163. assert_equal(converter('missed'), converter.default)
  164. try:
  165. converter('miss')
  166. except ValueError:
  167. pass
  168. def test_upgrademapper(self):
  169. "Tests updatemapper"
  170. dateparser = _bytes_to_date
  171. StringConverter.upgrade_mapper(dateparser, date(2000, 1, 1))
  172. convert = StringConverter(dateparser, date(2000, 1, 1))
  173. test = convert('2001-01-01')
  174. assert_equal(test, date(2001, 1, 1))
  175. test = convert('2009-01-01')
  176. assert_equal(test, date(2009, 1, 1))
  177. test = convert('')
  178. assert_equal(test, date(2000, 1, 1))
  179. def test_string_to_object(self):
  180. "Make sure that string-to-object functions are properly recognized"
  181. old_mapper = StringConverter._mapper[:] # copy of list
  182. conv = StringConverter(_bytes_to_date)
  183. assert_equal(conv._mapper, old_mapper)
  184. assert_(hasattr(conv, 'default'))
  185. def test_keep_default(self):
  186. "Make sure we don't lose an explicit default"
  187. converter = StringConverter(None, missing_values='',
  188. default=-999)
  189. converter.upgrade('3.14159265')
  190. assert_equal(converter.default, -999)
  191. assert_equal(converter.type, np.dtype(float))
  192. #
  193. converter = StringConverter(
  194. None, missing_values='', default=0)
  195. converter.upgrade('3.14159265')
  196. assert_equal(converter.default, 0)
  197. assert_equal(converter.type, np.dtype(float))
  198. def test_keep_default_zero(self):
  199. "Check that we don't lose a default of 0"
  200. converter = StringConverter(int, default=0,
  201. missing_values="N/A")
  202. assert_equal(converter.default, 0)
  203. def test_keep_missing_values(self):
  204. "Check that we're not losing missing values"
  205. converter = StringConverter(int, default=0,
  206. missing_values="N/A")
  207. assert_equal(
  208. converter.missing_values, {'', 'N/A'})
  209. def test_int64_dtype(self):
  210. "Check that int64 integer types can be specified"
  211. converter = StringConverter(np.int64, default=0)
  212. val = "-9223372036854775807"
  213. assert_(converter(val) == -9223372036854775807)
  214. val = "9223372036854775807"
  215. assert_(converter(val) == 9223372036854775807)
  216. def test_uint64_dtype(self):
  217. "Check that uint64 integer types can be specified"
  218. converter = StringConverter(np.uint64, default=0)
  219. val = "9223372043271415339"
  220. assert_(converter(val) == 9223372043271415339)
  221. class TestMiscFunctions(object):
  222. def test_has_nested_dtype(self):
  223. "Test has_nested_dtype"
  224. ndtype = np.dtype(float)
  225. assert_equal(has_nested_fields(ndtype), False)
  226. ndtype = np.dtype([('A', '|S3'), ('B', float)])
  227. assert_equal(has_nested_fields(ndtype), False)
  228. ndtype = np.dtype([('A', int), ('B', [('BA', float), ('BB', '|S1')])])
  229. assert_equal(has_nested_fields(ndtype), True)
  230. def test_easy_dtype(self):
  231. "Test ndtype on dtypes"
  232. # Simple case
  233. ndtype = float
  234. assert_equal(easy_dtype(ndtype), np.dtype(float))
  235. # As string w/o names
  236. ndtype = "i4, f8"
  237. assert_equal(easy_dtype(ndtype),
  238. np.dtype([('f0', "i4"), ('f1', "f8")]))
  239. # As string w/o names but different default format
  240. assert_equal(easy_dtype(ndtype, defaultfmt="field_%03i"),
  241. np.dtype([('field_000', "i4"), ('field_001', "f8")]))
  242. # As string w/ names
  243. ndtype = "i4, f8"
  244. assert_equal(easy_dtype(ndtype, names="a, b"),
  245. np.dtype([('a', "i4"), ('b', "f8")]))
  246. # As string w/ names (too many)
  247. ndtype = "i4, f8"
  248. assert_equal(easy_dtype(ndtype, names="a, b, c"),
  249. np.dtype([('a', "i4"), ('b', "f8")]))
  250. # As string w/ names (not enough)
  251. ndtype = "i4, f8"
  252. assert_equal(easy_dtype(ndtype, names=", b"),
  253. np.dtype([('f0', "i4"), ('b', "f8")]))
  254. # ... (with different default format)
  255. assert_equal(easy_dtype(ndtype, names="a", defaultfmt="f%02i"),
  256. np.dtype([('a', "i4"), ('f00', "f8")]))
  257. # As list of tuples w/o names
  258. ndtype = [('A', int), ('B', float)]
  259. assert_equal(easy_dtype(ndtype), np.dtype([('A', int), ('B', float)]))
  260. # As list of tuples w/ names
  261. assert_equal(easy_dtype(ndtype, names="a,b"),
  262. np.dtype([('a', int), ('b', float)]))
  263. # As list of tuples w/ not enough names
  264. assert_equal(easy_dtype(ndtype, names="a"),
  265. np.dtype([('a', int), ('f0', float)]))
  266. # As list of tuples w/ too many names
  267. assert_equal(easy_dtype(ndtype, names="a,b,c"),
  268. np.dtype([('a', int), ('b', float)]))
  269. # As list of types w/o names
  270. ndtype = (int, float, float)
  271. assert_equal(easy_dtype(ndtype),
  272. np.dtype([('f0', int), ('f1', float), ('f2', float)]))
  273. # As list of types w names
  274. ndtype = (int, float, float)
  275. assert_equal(easy_dtype(ndtype, names="a, b, c"),
  276. np.dtype([('a', int), ('b', float), ('c', float)]))
  277. # As simple dtype w/ names
  278. ndtype = np.dtype(float)
  279. assert_equal(easy_dtype(ndtype, names="a, b, c"),
  280. np.dtype([(_, float) for _ in ('a', 'b', 'c')]))
  281. # As simple dtype w/o names (but multiple fields)
  282. ndtype = np.dtype(float)
  283. assert_equal(
  284. easy_dtype(ndtype, names=['', '', ''], defaultfmt="f%02i"),
  285. np.dtype([(_, float) for _ in ('f00', 'f01', 'f02')]))
  286. def test_flatten_dtype(self):
  287. "Testing flatten_dtype"
  288. # Standard dtype
  289. dt = np.dtype([("a", "f8"), ("b", "f8")])
  290. dt_flat = flatten_dtype(dt)
  291. assert_equal(dt_flat, [float, float])
  292. # Recursive dtype
  293. dt = np.dtype([("a", [("aa", '|S1'), ("ab", '|S2')]), ("b", int)])
  294. dt_flat = flatten_dtype(dt)
  295. assert_equal(dt_flat, [np.dtype('|S1'), np.dtype('|S2'), int])
  296. # dtype with shaped fields
  297. dt = np.dtype([("a", (float, 2)), ("b", (int, 3))])
  298. dt_flat = flatten_dtype(dt)
  299. assert_equal(dt_flat, [float, int])
  300. dt_flat = flatten_dtype(dt, True)
  301. assert_equal(dt_flat, [float] * 2 + [int] * 3)
  302. # dtype w/ titles
  303. dt = np.dtype([(("a", "A"), "f8"), (("b", "B"), "f8")])
  304. dt_flat = flatten_dtype(dt)
  305. assert_equal(dt_flat, [float, float])