test__iotools.py 13 KB

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