test_loadtxt.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. """
  2. Tests specific to `np.loadtxt` added during the move of loadtxt to be backed
  3. by C code.
  4. These tests complement those found in `test_io.py`.
  5. """
  6. import sys
  7. import os
  8. import pytest
  9. from tempfile import NamedTemporaryFile, mkstemp
  10. from io import StringIO
  11. import numpy as np
  12. from numpy.ma.testutils import assert_equal
  13. from numpy.testing import assert_array_equal, HAS_REFCOUNT, IS_PYPY
  14. def test_scientific_notation():
  15. """Test that both 'e' and 'E' are parsed correctly."""
  16. data = StringIO(
  17. (
  18. "1.0e-1,2.0E1,3.0\n"
  19. "4.0e-2,5.0E-1,6.0\n"
  20. "7.0e-3,8.0E1,9.0\n"
  21. "0.0e-4,1.0E-1,2.0"
  22. )
  23. )
  24. expected = np.array(
  25. [[0.1, 20., 3.0], [0.04, 0.5, 6], [0.007, 80., 9], [0, 0.1, 2]]
  26. )
  27. assert_array_equal(np.loadtxt(data, delimiter=","), expected)
  28. @pytest.mark.parametrize("comment", ["..", "//", "@-", "this is a comment:"])
  29. def test_comment_multiple_chars(comment):
  30. content = "# IGNORE\n1.5, 2.5# ABC\n3.0,4.0# XXX\n5.5,6.0\n"
  31. txt = StringIO(content.replace("#", comment))
  32. a = np.loadtxt(txt, delimiter=",", comments=comment)
  33. assert_equal(a, [[1.5, 2.5], [3.0, 4.0], [5.5, 6.0]])
  34. @pytest.fixture
  35. def mixed_types_structured():
  36. """
  37. Fixture providing hetergeneous input data with a structured dtype, along
  38. with the associated structured array.
  39. """
  40. data = StringIO(
  41. (
  42. "1000;2.4;alpha;-34\n"
  43. "2000;3.1;beta;29\n"
  44. "3500;9.9;gamma;120\n"
  45. "4090;8.1;delta;0\n"
  46. "5001;4.4;epsilon;-99\n"
  47. "6543;7.8;omega;-1\n"
  48. )
  49. )
  50. dtype = np.dtype(
  51. [('f0', np.uint16), ('f1', np.float64), ('f2', 'S7'), ('f3', np.int8)]
  52. )
  53. expected = np.array(
  54. [
  55. (1000, 2.4, "alpha", -34),
  56. (2000, 3.1, "beta", 29),
  57. (3500, 9.9, "gamma", 120),
  58. (4090, 8.1, "delta", 0),
  59. (5001, 4.4, "epsilon", -99),
  60. (6543, 7.8, "omega", -1)
  61. ],
  62. dtype=dtype
  63. )
  64. return data, dtype, expected
  65. @pytest.mark.parametrize('skiprows', [0, 1, 2, 3])
  66. def test_structured_dtype_and_skiprows_no_empty_lines(
  67. skiprows, mixed_types_structured):
  68. data, dtype, expected = mixed_types_structured
  69. a = np.loadtxt(data, dtype=dtype, delimiter=";", skiprows=skiprows)
  70. assert_array_equal(a, expected[skiprows:])
  71. def test_unpack_structured(mixed_types_structured):
  72. data, dtype, expected = mixed_types_structured
  73. a, b, c, d = np.loadtxt(data, dtype=dtype, delimiter=";", unpack=True)
  74. assert_array_equal(a, expected["f0"])
  75. assert_array_equal(b, expected["f1"])
  76. assert_array_equal(c, expected["f2"])
  77. assert_array_equal(d, expected["f3"])
  78. def test_structured_dtype_with_shape():
  79. dtype = np.dtype([("a", "u1", 2), ("b", "u1", 2)])
  80. data = StringIO("0,1,2,3\n6,7,8,9\n")
  81. expected = np.array([((0, 1), (2, 3)), ((6, 7), (8, 9))], dtype=dtype)
  82. assert_array_equal(np.loadtxt(data, delimiter=",", dtype=dtype), expected)
  83. def test_structured_dtype_with_multi_shape():
  84. dtype = np.dtype([("a", "u1", (2, 2))])
  85. data = StringIO("0 1 2 3\n")
  86. expected = np.array([(((0, 1), (2, 3)),)], dtype=dtype)
  87. assert_array_equal(np.loadtxt(data, dtype=dtype), expected)
  88. def test_nested_structured_subarray():
  89. # Test from gh-16678
  90. point = np.dtype([('x', float), ('y', float)])
  91. dt = np.dtype([('code', int), ('points', point, (2,))])
  92. data = StringIO("100,1,2,3,4\n200,5,6,7,8\n")
  93. expected = np.array(
  94. [
  95. (100, [(1., 2.), (3., 4.)]),
  96. (200, [(5., 6.), (7., 8.)]),
  97. ],
  98. dtype=dt
  99. )
  100. assert_array_equal(np.loadtxt(data, dtype=dt, delimiter=","), expected)
  101. def test_structured_dtype_offsets():
  102. # An aligned structured dtype will have additional padding
  103. dt = np.dtype("i1, i4, i1, i4, i1, i4", align=True)
  104. data = StringIO("1,2,3,4,5,6\n7,8,9,10,11,12\n")
  105. expected = np.array([(1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12)], dtype=dt)
  106. assert_array_equal(np.loadtxt(data, delimiter=",", dtype=dt), expected)
  107. @pytest.mark.parametrize("param", ("skiprows", "max_rows"))
  108. def test_exception_negative_row_limits(param):
  109. """skiprows and max_rows should raise for negative parameters."""
  110. with pytest.raises(ValueError, match="argument must be nonnegative"):
  111. np.loadtxt("foo.bar", **{param: -3})
  112. @pytest.mark.parametrize("param", ("skiprows", "max_rows"))
  113. def test_exception_noninteger_row_limits(param):
  114. with pytest.raises(TypeError, match="argument must be an integer"):
  115. np.loadtxt("foo.bar", **{param: 1.0})
  116. @pytest.mark.parametrize(
  117. "data, shape",
  118. [
  119. ("1 2 3 4 5\n", (1, 5)), # Single row
  120. ("1\n2\n3\n4\n5\n", (5, 1)), # Single column
  121. ]
  122. )
  123. def test_ndmin_single_row_or_col(data, shape):
  124. arr = np.array([1, 2, 3, 4, 5])
  125. arr2d = arr.reshape(shape)
  126. assert_array_equal(np.loadtxt(StringIO(data), dtype=int), arr)
  127. assert_array_equal(np.loadtxt(StringIO(data), dtype=int, ndmin=0), arr)
  128. assert_array_equal(np.loadtxt(StringIO(data), dtype=int, ndmin=1), arr)
  129. assert_array_equal(np.loadtxt(StringIO(data), dtype=int, ndmin=2), arr2d)
  130. @pytest.mark.parametrize("badval", [-1, 3, None, "plate of shrimp"])
  131. def test_bad_ndmin(badval):
  132. with pytest.raises(ValueError, match="Illegal value of ndmin keyword"):
  133. np.loadtxt("foo.bar", ndmin=badval)
  134. @pytest.mark.parametrize(
  135. "ws",
  136. (
  137. " ", # space
  138. "\t", # tab
  139. "\u2003", # em
  140. "\u00A0", # non-break
  141. "\u3000", # ideographic space
  142. )
  143. )
  144. def test_blank_lines_spaces_delimit(ws):
  145. txt = StringIO(
  146. f"1 2{ws}30\n\n{ws}\n"
  147. f"4 5 60{ws}\n {ws} \n"
  148. f"7 8 {ws} 90\n # comment\n"
  149. f"3 2 1"
  150. )
  151. # NOTE: It is unclear that the ` # comment` should succeed. Except
  152. # for delimiter=None, which should use any whitespace (and maybe
  153. # should just be implemented closer to Python
  154. expected = np.array([[1, 2, 30], [4, 5, 60], [7, 8, 90], [3, 2, 1]])
  155. assert_equal(
  156. np.loadtxt(txt, dtype=int, delimiter=None, comments="#"), expected
  157. )
  158. def test_blank_lines_normal_delimiter():
  159. txt = StringIO('1,2,30\n\n4,5,60\n\n7,8,90\n# comment\n3,2,1')
  160. expected = np.array([[1, 2, 30], [4, 5, 60], [7, 8, 90], [3, 2, 1]])
  161. assert_equal(
  162. np.loadtxt(txt, dtype=int, delimiter=',', comments="#"), expected
  163. )
  164. @pytest.mark.parametrize("dtype", (float, object))
  165. def test_maxrows_no_blank_lines(dtype):
  166. txt = StringIO("1.5,2.5\n3.0,4.0\n5.5,6.0")
  167. res = np.loadtxt(txt, dtype=dtype, delimiter=",", max_rows=2)
  168. assert_equal(res.dtype, dtype)
  169. assert_equal(res, np.array([["1.5", "2.5"], ["3.0", "4.0"]], dtype=dtype))
  170. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  171. reason="PyPy bug in error formatting")
  172. @pytest.mark.parametrize("dtype", (np.dtype("f8"), np.dtype("i2")))
  173. def test_exception_message_bad_values(dtype):
  174. txt = StringIO("1,2\n3,XXX\n5,6")
  175. msg = f"could not convert string 'XXX' to {dtype} at row 1, column 2"
  176. with pytest.raises(ValueError, match=msg):
  177. np.loadtxt(txt, dtype=dtype, delimiter=",")
  178. def test_converters_negative_indices():
  179. txt = StringIO('1.5,2.5\n3.0,XXX\n5.5,6.0')
  180. conv = {-1: lambda s: np.nan if s == 'XXX' else float(s)}
  181. expected = np.array([[1.5, 2.5], [3.0, np.nan], [5.5, 6.0]])
  182. res = np.loadtxt(
  183. txt, dtype=np.float64, delimiter=",", converters=conv, encoding=None
  184. )
  185. assert_equal(res, expected)
  186. def test_converters_negative_indices_with_usecols():
  187. txt = StringIO('1.5,2.5,3.5\n3.0,4.0,XXX\n5.5,6.0,7.5\n')
  188. conv = {-1: lambda s: np.nan if s == 'XXX' else float(s)}
  189. expected = np.array([[1.5, 3.5], [3.0, np.nan], [5.5, 7.5]])
  190. res = np.loadtxt(
  191. txt,
  192. dtype=np.float64,
  193. delimiter=",",
  194. converters=conv,
  195. usecols=[0, -1],
  196. encoding=None,
  197. )
  198. assert_equal(res, expected)
  199. # Second test with variable number of rows:
  200. res = np.loadtxt(StringIO('''0,1,2\n0,1,2,3,4'''), delimiter=",",
  201. usecols=[0, -1], converters={-1: (lambda x: -1)})
  202. assert_array_equal(res, [[0, -1], [0, -1]])
  203. def test_ragged_usecols():
  204. # usecols, and negative ones, work even with varying number of columns.
  205. txt = StringIO("0,0,XXX\n0,XXX,0,XXX\n0,XXX,XXX,0,XXX\n")
  206. expected = np.array([[0, 0], [0, 0], [0, 0]])
  207. res = np.loadtxt(txt, dtype=float, delimiter=",", usecols=[0, -2])
  208. assert_equal(res, expected)
  209. txt = StringIO("0,0,XXX\n0\n0,XXX,XXX,0,XXX\n")
  210. with pytest.raises(ValueError,
  211. match="invalid column index -2 at row 2 with 1 columns"):
  212. # There is no -2 column in the second row:
  213. np.loadtxt(txt, dtype=float, delimiter=",", usecols=[0, -2])
  214. def test_empty_usecols():
  215. txt = StringIO("0,0,XXX\n0,XXX,0,XXX\n0,XXX,XXX,0,XXX\n")
  216. res = np.loadtxt(txt, dtype=np.dtype([]), delimiter=",", usecols=[])
  217. assert res.shape == (3,)
  218. assert res.dtype == np.dtype([])
  219. @pytest.mark.parametrize("c1", ["a", "の", "🫕"])
  220. @pytest.mark.parametrize("c2", ["a", "の", "🫕"])
  221. def test_large_unicode_characters(c1, c2):
  222. # c1 and c2 span ascii, 16bit and 32bit range.
  223. txt = StringIO(f"a,{c1},c,1.0\ne,{c2},2.0,g")
  224. res = np.loadtxt(txt, dtype=np.dtype('U12'), delimiter=",")
  225. expected = np.array(
  226. [f"a,{c1},c,1.0".split(","), f"e,{c2},2.0,g".split(",")],
  227. dtype=np.dtype('U12')
  228. )
  229. assert_equal(res, expected)
  230. def test_unicode_with_converter():
  231. txt = StringIO("cat,dog\nαβγ,δεζ\nabc,def\n")
  232. conv = {0: lambda s: s.upper()}
  233. res = np.loadtxt(
  234. txt,
  235. dtype=np.dtype("U12"),
  236. converters=conv,
  237. delimiter=",",
  238. encoding=None
  239. )
  240. expected = np.array([['CAT', 'dog'], ['ΑΒΓ', 'δεζ'], ['ABC', 'def']])
  241. assert_equal(res, expected)
  242. def test_converter_with_structured_dtype():
  243. txt = StringIO('1.5,2.5,Abc\n3.0,4.0,dEf\n5.5,6.0,ghI\n')
  244. dt = np.dtype([('m', np.int32), ('r', np.float32), ('code', 'U8')])
  245. conv = {0: lambda s: int(10*float(s)), -1: lambda s: s.upper()}
  246. res = np.loadtxt(txt, dtype=dt, delimiter=",", converters=conv)
  247. expected = np.array(
  248. [(15, 2.5, 'ABC'), (30, 4.0, 'DEF'), (55, 6.0, 'GHI')], dtype=dt
  249. )
  250. assert_equal(res, expected)
  251. def test_converter_with_unicode_dtype():
  252. """
  253. With the default 'bytes' encoding, tokens are encoded prior to being
  254. passed to the converter. This means that the output of the converter may
  255. be bytes instead of unicode as expected by `read_rows`.
  256. This test checks that outputs from the above scenario are properly decoded
  257. prior to parsing by `read_rows`.
  258. """
  259. txt = StringIO('abc,def\nrst,xyz')
  260. conv = bytes.upper
  261. res = np.loadtxt(
  262. txt, dtype=np.dtype("U3"), converters=conv, delimiter=",")
  263. expected = np.array([['ABC', 'DEF'], ['RST', 'XYZ']])
  264. assert_equal(res, expected)
  265. def test_read_huge_row():
  266. row = "1.5, 2.5," * 50000
  267. row = row[:-1] + "\n"
  268. txt = StringIO(row * 2)
  269. res = np.loadtxt(txt, delimiter=",", dtype=float)
  270. assert_equal(res, np.tile([1.5, 2.5], (2, 50000)))
  271. @pytest.mark.parametrize("dtype", "edfgFDG")
  272. def test_huge_float(dtype):
  273. # Covers a non-optimized path that is rarely taken:
  274. field = "0" * 1000 + ".123456789"
  275. dtype = np.dtype(dtype)
  276. value = np.loadtxt([field], dtype=dtype)[()]
  277. assert value == dtype.type("0.123456789")
  278. @pytest.mark.parametrize(
  279. ("given_dtype", "expected_dtype"),
  280. [
  281. ("S", np.dtype("S5")),
  282. ("U", np.dtype("U5")),
  283. ],
  284. )
  285. def test_string_no_length_given(given_dtype, expected_dtype):
  286. """
  287. The given dtype is just 'S' or 'U' with no length. In these cases, the
  288. length of the resulting dtype is determined by the longest string found
  289. in the file.
  290. """
  291. txt = StringIO("AAA,5-1\nBBBBB,0-3\nC,4-9\n")
  292. res = np.loadtxt(txt, dtype=given_dtype, delimiter=",")
  293. expected = np.array(
  294. [['AAA', '5-1'], ['BBBBB', '0-3'], ['C', '4-9']], dtype=expected_dtype
  295. )
  296. assert_equal(res, expected)
  297. assert_equal(res.dtype, expected_dtype)
  298. def test_float_conversion():
  299. """
  300. Some tests that the conversion to float64 works as accurately as the
  301. Python built-in `float` function. In a naive version of the float parser,
  302. these strings resulted in values that were off by an ULP or two.
  303. """
  304. strings = [
  305. '0.9999999999999999',
  306. '9876543210.123456',
  307. '5.43215432154321e+300',
  308. '0.901',
  309. '0.333',
  310. ]
  311. txt = StringIO('\n'.join(strings))
  312. res = np.loadtxt(txt)
  313. expected = np.array([float(s) for s in strings])
  314. assert_equal(res, expected)
  315. def test_bool():
  316. # Simple test for bool via integer
  317. txt = StringIO("1, 0\n10, -1")
  318. res = np.loadtxt(txt, dtype=bool, delimiter=",")
  319. assert res.dtype == bool
  320. assert_array_equal(res, [[True, False], [True, True]])
  321. # Make sure we use only 1 and 0 on the byte level:
  322. assert_array_equal(res.view(np.uint8), [[1, 0], [1, 1]])
  323. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  324. reason="PyPy bug in error formatting")
  325. @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
  326. @pytest.mark.filterwarnings("error:.*integer via a float.*:DeprecationWarning")
  327. def test_integer_signs(dtype):
  328. dtype = np.dtype(dtype)
  329. assert np.loadtxt(["+2"], dtype=dtype) == 2
  330. if dtype.kind == "u":
  331. with pytest.raises(ValueError):
  332. np.loadtxt(["-1\n"], dtype=dtype)
  333. else:
  334. assert np.loadtxt(["-2\n"], dtype=dtype) == -2
  335. for sign in ["++", "+-", "--", "-+"]:
  336. with pytest.raises(ValueError):
  337. np.loadtxt([f"{sign}2\n"], dtype=dtype)
  338. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  339. reason="PyPy bug in error formatting")
  340. @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
  341. @pytest.mark.filterwarnings("error:.*integer via a float.*:DeprecationWarning")
  342. def test_implicit_cast_float_to_int_fails(dtype):
  343. txt = StringIO("1.0, 2.1, 3.7\n4, 5, 6")
  344. with pytest.raises(ValueError):
  345. np.loadtxt(txt, dtype=dtype, delimiter=",")
  346. @pytest.mark.parametrize("dtype", (np.complex64, np.complex128))
  347. @pytest.mark.parametrize("with_parens", (False, True))
  348. def test_complex_parsing(dtype, with_parens):
  349. s = "(1.0-2.5j),3.75,(7+-5.0j)\n(4),(-19e2j),(0)"
  350. if not with_parens:
  351. s = s.replace("(", "").replace(")", "")
  352. res = np.loadtxt(StringIO(s), dtype=dtype, delimiter=",")
  353. expected = np.array(
  354. [[1.0-2.5j, 3.75, 7-5j], [4.0, -1900j, 0]], dtype=dtype
  355. )
  356. assert_equal(res, expected)
  357. def test_read_from_generator():
  358. def gen():
  359. for i in range(4):
  360. yield f"{i},{2*i},{i**2}"
  361. res = np.loadtxt(gen(), dtype=int, delimiter=",")
  362. expected = np.array([[0, 0, 0], [1, 2, 1], [2, 4, 4], [3, 6, 9]])
  363. assert_equal(res, expected)
  364. def test_read_from_generator_multitype():
  365. def gen():
  366. for i in range(3):
  367. yield f"{i} {i / 4}"
  368. res = np.loadtxt(gen(), dtype="i, d", delimiter=" ")
  369. expected = np.array([(0, 0.0), (1, 0.25), (2, 0.5)], dtype="i, d")
  370. assert_equal(res, expected)
  371. def test_read_from_bad_generator():
  372. def gen():
  373. for entry in ["1,2", b"3, 5", 12738]:
  374. yield entry
  375. with pytest.raises(
  376. TypeError, match=r"non-string returned while reading data"):
  377. np.loadtxt(gen(), dtype="i, i", delimiter=",")
  378. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  379. def test_object_cleanup_on_read_error():
  380. sentinel = object()
  381. already_read = 0
  382. def conv(x):
  383. nonlocal already_read
  384. if already_read > 4999:
  385. raise ValueError("failed half-way through!")
  386. already_read += 1
  387. return sentinel
  388. txt = StringIO("x\n" * 10000)
  389. with pytest.raises(ValueError, match="at row 5000, column 1"):
  390. np.loadtxt(txt, dtype=object, converters={0: conv})
  391. assert sys.getrefcount(sentinel) == 2
  392. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  393. reason="PyPy bug in error formatting")
  394. def test_character_not_bytes_compatible():
  395. """Test exception when a character cannot be encoded as 'S'."""
  396. data = StringIO("–") # == \u2013
  397. with pytest.raises(ValueError):
  398. np.loadtxt(data, dtype="S5")
  399. @pytest.mark.parametrize("conv", (0, [float], ""))
  400. def test_invalid_converter(conv):
  401. msg = (
  402. "converters must be a dictionary mapping columns to converter "
  403. "functions or a single callable."
  404. )
  405. with pytest.raises(TypeError, match=msg):
  406. np.loadtxt(StringIO("1 2\n3 4"), converters=conv)
  407. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  408. reason="PyPy bug in error formatting")
  409. def test_converters_dict_raises_non_integer_key():
  410. with pytest.raises(TypeError, match="keys of the converters dict"):
  411. np.loadtxt(StringIO("1 2\n3 4"), converters={"a": int})
  412. with pytest.raises(TypeError, match="keys of the converters dict"):
  413. np.loadtxt(StringIO("1 2\n3 4"), converters={"a": int}, usecols=0)
  414. @pytest.mark.parametrize("bad_col_ind", (3, -3))
  415. def test_converters_dict_raises_non_col_key(bad_col_ind):
  416. data = StringIO("1 2\n3 4")
  417. with pytest.raises(ValueError, match="converter specified for column"):
  418. np.loadtxt(data, converters={bad_col_ind: int})
  419. def test_converters_dict_raises_val_not_callable():
  420. with pytest.raises(TypeError,
  421. match="values of the converters dictionary must be callable"):
  422. np.loadtxt(StringIO("1 2\n3 4"), converters={0: 1})
  423. @pytest.mark.parametrize("q", ('"', "'", "`"))
  424. def test_quoted_field(q):
  425. txt = StringIO(
  426. f"{q}alpha, x{q}, 2.5\n{q}beta, y{q}, 4.5\n{q}gamma, z{q}, 5.0\n"
  427. )
  428. dtype = np.dtype([('f0', 'U8'), ('f1', np.float64)])
  429. expected = np.array(
  430. [("alpha, x", 2.5), ("beta, y", 4.5), ("gamma, z", 5.0)], dtype=dtype
  431. )
  432. res = np.loadtxt(txt, dtype=dtype, delimiter=",", quotechar=q)
  433. assert_array_equal(res, expected)
  434. @pytest.mark.parametrize("q", ('"', "'", "`"))
  435. def test_quoted_field_with_whitepace_delimiter(q):
  436. txt = StringIO(
  437. f"{q}alpha, x{q} 2.5\n{q}beta, y{q} 4.5\n{q}gamma, z{q} 5.0\n"
  438. )
  439. dtype = np.dtype([('f0', 'U8'), ('f1', np.float64)])
  440. expected = np.array(
  441. [("alpha, x", 2.5), ("beta, y", 4.5), ("gamma, z", 5.0)], dtype=dtype
  442. )
  443. res = np.loadtxt(txt, dtype=dtype, delimiter=None, quotechar=q)
  444. assert_array_equal(res, expected)
  445. def test_quote_support_default():
  446. """Support for quoted fields is disabled by default."""
  447. txt = StringIO('"lat,long", 45, 30\n')
  448. dtype = np.dtype([('f0', 'U24'), ('f1', np.float64), ('f2', np.float64)])
  449. with pytest.raises(ValueError, match="the number of columns changed"):
  450. np.loadtxt(txt, dtype=dtype, delimiter=",")
  451. # Enable quoting support with non-None value for quotechar param
  452. txt.seek(0)
  453. expected = np.array([("lat,long", 45., 30.)], dtype=dtype)
  454. res = np.loadtxt(txt, dtype=dtype, delimiter=",", quotechar='"')
  455. assert_array_equal(res, expected)
  456. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  457. reason="PyPy bug in error formatting")
  458. def test_quotechar_multichar_error():
  459. txt = StringIO("1,2\n3,4")
  460. msg = r".*must be a single unicode character or None"
  461. with pytest.raises(TypeError, match=msg):
  462. np.loadtxt(txt, delimiter=",", quotechar="''")
  463. def test_comment_multichar_error_with_quote():
  464. txt = StringIO("1,2\n3,4")
  465. msg = (
  466. "when multiple comments or a multi-character comment is given, "
  467. "quotes are not supported."
  468. )
  469. with pytest.raises(ValueError, match=msg):
  470. np.loadtxt(txt, delimiter=",", comments="123", quotechar='"')
  471. with pytest.raises(ValueError, match=msg):
  472. np.loadtxt(txt, delimiter=",", comments=["#", "%"], quotechar='"')
  473. # A single character string in a tuple is unpacked though:
  474. res = np.loadtxt(txt, delimiter=",", comments=("#",), quotechar="'")
  475. assert_equal(res, [[1, 2], [3, 4]])
  476. def test_structured_dtype_with_quotes():
  477. data = StringIO(
  478. (
  479. "1000;2.4;'alpha';-34\n"
  480. "2000;3.1;'beta';29\n"
  481. "3500;9.9;'gamma';120\n"
  482. "4090;8.1;'delta';0\n"
  483. "5001;4.4;'epsilon';-99\n"
  484. "6543;7.8;'omega';-1\n"
  485. )
  486. )
  487. dtype = np.dtype(
  488. [('f0', np.uint16), ('f1', np.float64), ('f2', 'S7'), ('f3', np.int8)]
  489. )
  490. expected = np.array(
  491. [
  492. (1000, 2.4, "alpha", -34),
  493. (2000, 3.1, "beta", 29),
  494. (3500, 9.9, "gamma", 120),
  495. (4090, 8.1, "delta", 0),
  496. (5001, 4.4, "epsilon", -99),
  497. (6543, 7.8, "omega", -1)
  498. ],
  499. dtype=dtype
  500. )
  501. res = np.loadtxt(data, dtype=dtype, delimiter=";", quotechar="'")
  502. assert_array_equal(res, expected)
  503. def test_quoted_field_is_not_empty():
  504. txt = StringIO('1\n\n"4"\n""')
  505. expected = np.array(["1", "4", ""], dtype="U1")
  506. res = np.loadtxt(txt, delimiter=",", dtype="U1", quotechar='"')
  507. assert_equal(res, expected)
  508. def test_quoted_field_is_not_empty_nonstrict():
  509. # Same as test_quoted_field_is_not_empty but check that we are not strict
  510. # about missing closing quote (this is the `csv.reader` default also)
  511. txt = StringIO('1\n\n"4"\n"')
  512. expected = np.array(["1", "4", ""], dtype="U1")
  513. res = np.loadtxt(txt, delimiter=",", dtype="U1", quotechar='"')
  514. assert_equal(res, expected)
  515. def test_consecutive_quotechar_escaped():
  516. txt = StringIO('"Hello, my name is ""Monty""!"')
  517. expected = np.array('Hello, my name is "Monty"!', dtype="U40")
  518. res = np.loadtxt(txt, dtype="U40", delimiter=",", quotechar='"')
  519. assert_equal(res, expected)
  520. @pytest.mark.parametrize("data", ("", "\n\n\n", "# 1 2 3\n# 4 5 6\n"))
  521. @pytest.mark.parametrize("ndmin", (0, 1, 2))
  522. @pytest.mark.parametrize("usecols", [None, (1, 2, 3)])
  523. def test_warn_on_no_data(data, ndmin, usecols):
  524. """Check that a UserWarning is emitted when no data is read from input."""
  525. if usecols is not None:
  526. expected_shape = (0, 3)
  527. elif ndmin == 2:
  528. expected_shape = (0, 1) # guess a single column?!
  529. else:
  530. expected_shape = (0,)
  531. txt = StringIO(data)
  532. with pytest.warns(UserWarning, match="input contained no data"):
  533. res = np.loadtxt(txt, ndmin=ndmin, usecols=usecols)
  534. assert res.shape == expected_shape
  535. with NamedTemporaryFile(mode="w") as fh:
  536. fh.write(data)
  537. fh.seek(0)
  538. with pytest.warns(UserWarning, match="input contained no data"):
  539. res = np.loadtxt(txt, ndmin=ndmin, usecols=usecols)
  540. assert res.shape == expected_shape
  541. @pytest.mark.parametrize("skiprows", (2, 3))
  542. def test_warn_on_skipped_data(skiprows):
  543. data = "1 2 3\n4 5 6"
  544. txt = StringIO(data)
  545. with pytest.warns(UserWarning, match="input contained no data"):
  546. np.loadtxt(txt, skiprows=skiprows)
  547. @pytest.mark.parametrize(["dtype", "value"], [
  548. ("i2", 0x0001), ("u2", 0x0001),
  549. ("i4", 0x00010203), ("u4", 0x00010203),
  550. ("i8", 0x0001020304050607), ("u8", 0x0001020304050607),
  551. # The following values are constructed to lead to unique bytes:
  552. ("float16", 3.07e-05),
  553. ("float32", 9.2557e-41), ("complex64", 9.2557e-41+2.8622554e-29j),
  554. ("float64", -1.758571353180402e-24),
  555. # Here and below, the repr side-steps a small loss of precision in
  556. # complex `str` in PyPy (which is probably fine, as repr works):
  557. ("complex128", repr(5.406409232372729e-29-1.758571353180402e-24j)),
  558. # Use integer values that fit into double. Everything else leads to
  559. # problems due to longdoubles going via double and decimal strings
  560. # causing rounding errors.
  561. ("longdouble", 0x01020304050607),
  562. ("clongdouble", repr(0x01020304050607 + (0x00121314151617 * 1j))),
  563. ("U2", "\U00010203\U000a0b0c")])
  564. @pytest.mark.parametrize("swap", [True, False])
  565. def test_byteswapping_and_unaligned(dtype, value, swap):
  566. # Try to create "interesting" values within the valid unicode range:
  567. dtype = np.dtype(dtype)
  568. data = [f"x,{value}\n"] # repr as PyPy `str` truncates some
  569. if swap:
  570. dtype = dtype.newbyteorder()
  571. full_dt = np.dtype([("a", "S1"), ("b", dtype)], align=False)
  572. # The above ensures that the interesting "b" field is unaligned:
  573. assert full_dt.fields["b"][1] == 1
  574. res = np.loadtxt(data, dtype=full_dt, delimiter=",", encoding=None,
  575. max_rows=1) # max-rows prevents over-allocation
  576. assert res["b"] == dtype.type(value)
  577. @pytest.mark.parametrize("dtype",
  578. np.typecodes["AllInteger"] + "efdFD" + "?")
  579. def test_unicode_whitespace_stripping(dtype):
  580. # Test that all numeric types (and bool) strip whitespace correctly
  581. # \u202F is a narrow no-break space, `\n` is just a whitespace if quoted.
  582. # Currently, skip float128 as it did not always support this and has no
  583. # "custom" parsing:
  584. txt = StringIO(' 3 ,"\u202F2\n"')
  585. res = np.loadtxt(txt, dtype=dtype, delimiter=",", quotechar='"')
  586. assert_array_equal(res, np.array([3, 2]).astype(dtype))
  587. @pytest.mark.parametrize("dtype", "FD")
  588. def test_unicode_whitespace_stripping_complex(dtype):
  589. # Complex has a few extra cases since it has two components and
  590. # parentheses
  591. line = " 1 , 2+3j , ( 4+5j ), ( 6+-7j ) , 8j , ( 9j ) \n"
  592. data = [line, line.replace(" ", "\u202F")]
  593. res = np.loadtxt(data, dtype=dtype, delimiter=',')
  594. assert_array_equal(res, np.array([[1, 2+3j, 4+5j, 6-7j, 8j, 9j]] * 2))
  595. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  596. reason="PyPy bug in error formatting")
  597. @pytest.mark.parametrize("dtype", "FD")
  598. @pytest.mark.parametrize("field",
  599. ["1 +2j", "1+ 2j", "1+2 j", "1+-+3", "(1j", "(1", "(1+2j", "1+2j)"])
  600. def test_bad_complex(dtype, field):
  601. with pytest.raises(ValueError):
  602. np.loadtxt([field + "\n"], dtype=dtype, delimiter=",")
  603. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  604. reason="PyPy bug in error formatting")
  605. @pytest.mark.parametrize("dtype",
  606. np.typecodes["AllInteger"] + "efgdFDG" + "?")
  607. def test_nul_character_error(dtype):
  608. # Test that a \0 character is correctly recognized as an error even if
  609. # what comes before is valid (not everything gets parsed internally).
  610. if dtype.lower() == "g":
  611. pytest.xfail("longdouble/clongdouble assignment may misbehave.")
  612. with pytest.raises(ValueError):
  613. np.loadtxt(["1\000"], dtype=dtype, delimiter=",", quotechar='"')
  614. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  615. reason="PyPy bug in error formatting")
  616. @pytest.mark.parametrize("dtype",
  617. np.typecodes["AllInteger"] + "efgdFDG" + "?")
  618. def test_no_thousands_support(dtype):
  619. # Mainly to document behaviour, Python supports thousands like 1_1.
  620. # (e and G may end up using different conversion and support it, this is
  621. # a bug but happens...)
  622. if dtype == "e":
  623. pytest.skip("half assignment currently uses Python float converter")
  624. if dtype in "eG":
  625. pytest.xfail("clongdouble assignment is buggy (uses `complex`?).")
  626. assert int("1_1") == float("1_1") == complex("1_1") == 11
  627. with pytest.raises(ValueError):
  628. np.loadtxt(["1_1\n"], dtype=dtype)
  629. @pytest.mark.parametrize("data", [
  630. ["1,2\n", "2\n,3\n"],
  631. ["1,2\n", "2\r,3\n"]])
  632. def test_bad_newline_in_iterator(data):
  633. # In NumPy <=1.22 this was accepted, because newlines were completely
  634. # ignored when the input was an iterable. This could be changed, but right
  635. # now, we raise an error.
  636. msg = "Found an unquoted embedded newline within a single line"
  637. with pytest.raises(ValueError, match=msg):
  638. np.loadtxt(data, delimiter=",")
  639. @pytest.mark.parametrize("data", [
  640. ["1,2\n", "2,3\r\n"], # a universal newline
  641. ["1,2\n", "'2\n',3\n"], # a quoted newline
  642. ["1,2\n", "'2\r',3\n"],
  643. ["1,2\n", "'2\r\n',3\n"],
  644. ])
  645. def test_good_newline_in_iterator(data):
  646. # The quoted newlines will be untransformed here, but are just whitespace.
  647. res = np.loadtxt(data, delimiter=",", quotechar="'")
  648. assert_array_equal(res, [[1., 2.], [2., 3.]])
  649. @pytest.mark.parametrize("newline", ["\n", "\r", "\r\n"])
  650. def test_universal_newlines_quoted(newline):
  651. # Check that universal newline support within the tokenizer is not applied
  652. # to quoted fields. (note that lines must end in newline or quoted
  653. # fields will not include a newline at all)
  654. data = ['1,"2\n"\n', '3,"4\n', '1"\n']
  655. data = [row.replace("\n", newline) for row in data]
  656. res = np.loadtxt(data, dtype=object, delimiter=",", quotechar='"')
  657. assert_array_equal(res, [['1', f'2{newline}'], ['3', f'4{newline}1']])
  658. def test_null_character():
  659. # Basic tests to check that the NUL character is not special:
  660. res = np.loadtxt(["1\0002\0003\n", "4\0005\0006"], delimiter="\000")
  661. assert_array_equal(res, [[1, 2, 3], [4, 5, 6]])
  662. # Also not as part of a field (avoid unicode/arrays as unicode strips \0)
  663. res = np.loadtxt(["1\000,2\000,3\n", "4\000,5\000,6"],
  664. delimiter=",", dtype=object)
  665. assert res.tolist() == [["1\000", "2\000", "3"], ["4\000", "5\000", "6"]]
  666. def test_iterator_fails_getting_next_line():
  667. class BadSequence:
  668. def __len__(self):
  669. return 100
  670. def __getitem__(self, item):
  671. if item == 50:
  672. raise RuntimeError("Bad things happened!")
  673. return f"{item}, {item+1}"
  674. with pytest.raises(RuntimeError, match="Bad things happened!"):
  675. np.loadtxt(BadSequence(), dtype=int, delimiter=",")
  676. class TestCReaderUnitTests:
  677. # These are internal tests for path that should not be possible to hit
  678. # unless things go very very wrong somewhere.
  679. def test_not_an_filelike(self):
  680. with pytest.raises(AttributeError, match=".*read"):
  681. np.core._multiarray_umath._load_from_filelike(
  682. object(), dtype=np.dtype("i"), filelike=True)
  683. def test_filelike_read_fails(self):
  684. # Can only be reached if loadtxt opens the file, so it is hard to do
  685. # via the public interface (although maybe not impossible considering
  686. # the current "DataClass" backing).
  687. class BadFileLike:
  688. counter = 0
  689. def read(self, size):
  690. self.counter += 1
  691. if self.counter > 20:
  692. raise RuntimeError("Bad bad bad!")
  693. return "1,2,3\n"
  694. with pytest.raises(RuntimeError, match="Bad bad bad!"):
  695. np.core._multiarray_umath._load_from_filelike(
  696. BadFileLike(), dtype=np.dtype("i"), filelike=True)
  697. def test_filelike_bad_read(self):
  698. # Can only be reached if loadtxt opens the file, so it is hard to do
  699. # via the public interface (although maybe not impossible considering
  700. # the current "DataClass" backing).
  701. class BadFileLike:
  702. counter = 0
  703. def read(self, size):
  704. return 1234 # not a string!
  705. with pytest.raises(TypeError,
  706. match="non-string returned while reading data"):
  707. np.core._multiarray_umath._load_from_filelike(
  708. BadFileLike(), dtype=np.dtype("i"), filelike=True)
  709. def test_not_an_iter(self):
  710. with pytest.raises(TypeError,
  711. match="error reading from object, expected an iterable"):
  712. np.core._multiarray_umath._load_from_filelike(
  713. object(), dtype=np.dtype("i"), filelike=False)
  714. def test_bad_type(self):
  715. with pytest.raises(TypeError, match="internal error: dtype must"):
  716. np.core._multiarray_umath._load_from_filelike(
  717. object(), dtype="i", filelike=False)
  718. def test_bad_encoding(self):
  719. with pytest.raises(TypeError, match="encoding must be a unicode"):
  720. np.core._multiarray_umath._load_from_filelike(
  721. object(), dtype=np.dtype("i"), filelike=False, encoding=123)
  722. @pytest.mark.parametrize("newline", ["\r", "\n", "\r\n"])
  723. def test_manual_universal_newlines(self, newline):
  724. # This is currently not available to users, because we should always
  725. # open files with universal newlines enabled `newlines=None`.
  726. # (And reading from an iterator uses slightly different code paths.)
  727. # We have no real support for `newline="\r"` or `newline="\n" as the
  728. # user cannot specify those options.
  729. data = StringIO('0\n1\n"2\n"\n3\n4 #\n'.replace("\n", newline),
  730. newline="")
  731. res = np.core._multiarray_umath._load_from_filelike(
  732. data, dtype=np.dtype("U10"), filelike=True,
  733. quote='"', comment="#", skiplines=1)
  734. assert_array_equal(res[:, 0], ["1", f"2{newline}", "3", "4 "])
  735. def test_delimiter_comment_collision_raises():
  736. with pytest.raises(TypeError, match=".*control characters.*incompatible"):
  737. np.loadtxt(StringIO("1, 2, 3"), delimiter=",", comments=",")
  738. def test_delimiter_quotechar_collision_raises():
  739. with pytest.raises(TypeError, match=".*control characters.*incompatible"):
  740. np.loadtxt(StringIO("1, 2, 3"), delimiter=",", quotechar=",")
  741. def test_comment_quotechar_collision_raises():
  742. with pytest.raises(TypeError, match=".*control characters.*incompatible"):
  743. np.loadtxt(StringIO("1 2 3"), comments="#", quotechar="#")
  744. def test_delimiter_and_multiple_comments_collision_raises():
  745. with pytest.raises(
  746. TypeError, match="Comment characters.*cannot include the delimiter"
  747. ):
  748. np.loadtxt(StringIO("1, 2, 3"), delimiter=",", comments=["#", ","])
  749. @pytest.mark.parametrize(
  750. "ws",
  751. (
  752. " ", # space
  753. "\t", # tab
  754. "\u2003", # em
  755. "\u00A0", # non-break
  756. "\u3000", # ideographic space
  757. )
  758. )
  759. def test_collision_with_default_delimiter_raises(ws):
  760. with pytest.raises(TypeError, match=".*control characters.*incompatible"):
  761. np.loadtxt(StringIO(f"1{ws}2{ws}3\n4{ws}5{ws}6\n"), comments=ws)
  762. with pytest.raises(TypeError, match=".*control characters.*incompatible"):
  763. np.loadtxt(StringIO(f"1{ws}2{ws}3\n4{ws}5{ws}6\n"), quotechar=ws)
  764. @pytest.mark.parametrize("nl", ("\n", "\r"))
  765. def test_control_character_newline_raises(nl):
  766. txt = StringIO(f"1{nl}2{nl}3{nl}{nl}4{nl}5{nl}6{nl}{nl}")
  767. msg = "control character.*cannot be a newline"
  768. with pytest.raises(TypeError, match=msg):
  769. np.loadtxt(txt, delimiter=nl)
  770. with pytest.raises(TypeError, match=msg):
  771. np.loadtxt(txt, comments=nl)
  772. with pytest.raises(TypeError, match=msg):
  773. np.loadtxt(txt, quotechar=nl)
  774. @pytest.mark.parametrize(
  775. ("generic_data", "long_datum", "unitless_dtype", "expected_dtype"),
  776. [
  777. ("2012-03", "2013-01-15", "M8", "M8[D]"), # Datetimes
  778. ("spam-a-lot", "tis_but_a_scratch", "U", "U17"), # str
  779. ],
  780. )
  781. @pytest.mark.parametrize("nrows", (10, 50000, 60000)) # lt, eq, gt chunksize
  782. def test_parametric_unit_discovery(
  783. generic_data, long_datum, unitless_dtype, expected_dtype, nrows
  784. ):
  785. """Check that the correct unit (e.g. month, day, second) is discovered from
  786. the data when a user specifies a unitless datetime."""
  787. # Unit should be "D" (days) due to last entry
  788. data = [generic_data] * 50000 + [long_datum]
  789. expected = np.array(data, dtype=expected_dtype)
  790. # file-like path
  791. txt = StringIO("\n".join(data))
  792. a = np.loadtxt(txt, dtype=unitless_dtype)
  793. assert a.dtype == expected.dtype
  794. assert_equal(a, expected)
  795. # file-obj path
  796. fd, fname = mkstemp()
  797. os.close(fd)
  798. with open(fname, "w") as fh:
  799. fh.write("\n".join(data))
  800. a = np.loadtxt(fname, dtype=unitless_dtype)
  801. os.remove(fname)
  802. assert a.dtype == expected.dtype
  803. assert_equal(a, expected)
  804. def test_str_dtype_unit_discovery_with_converter():
  805. data = ["spam-a-lot"] * 60000 + ["XXXtis_but_a_scratch"]
  806. expected = np.array(
  807. ["spam-a-lot"] * 60000 + ["tis_but_a_scratch"], dtype="U17"
  808. )
  809. conv = lambda s: s.strip("XXX")
  810. # file-like path
  811. txt = StringIO("\n".join(data))
  812. a = np.loadtxt(txt, dtype="U", converters=conv, encoding=None)
  813. assert a.dtype == expected.dtype
  814. assert_equal(a, expected)
  815. # file-obj path
  816. fd, fname = mkstemp()
  817. os.close(fd)
  818. with open(fname, "w") as fh:
  819. fh.write("\n".join(data))
  820. a = np.loadtxt(fname, dtype="U", converters=conv, encoding=None)
  821. os.remove(fname)
  822. assert a.dtype == expected.dtype
  823. assert_equal(a, expected)
  824. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  825. reason="PyPy bug in error formatting")
  826. def test_control_character_empty():
  827. with pytest.raises(TypeError, match="Text reading control character must"):
  828. np.loadtxt(StringIO("1 2 3"), delimiter="")
  829. with pytest.raises(TypeError, match="Text reading control character must"):
  830. np.loadtxt(StringIO("1 2 3"), quotechar="")
  831. with pytest.raises(ValueError, match="comments cannot be an empty string"):
  832. np.loadtxt(StringIO("1 2 3"), comments="")
  833. with pytest.raises(ValueError, match="comments cannot be an empty string"):
  834. np.loadtxt(StringIO("1 2 3"), comments=["#", ""])
  835. def test_control_characters_as_bytes():
  836. """Byte control characters (comments, delimiter) are supported."""
  837. a = np.loadtxt(StringIO("#header\n1,2,3"), comments=b"#", delimiter=b",")
  838. assert_equal(a, [1, 2, 3])
  839. @pytest.mark.filterwarnings('ignore::UserWarning')
  840. def test_field_growing_cases():
  841. # Test empty field appending/growing (each field still takes 1 character)
  842. # to see if the final field appending does not create issues.
  843. res = np.loadtxt([""], delimiter=",", dtype=bytes)
  844. assert len(res) == 0
  845. for i in range(1, 1024):
  846. res = np.loadtxt(["," * i], delimiter=",", dtype=bytes)
  847. assert len(res) == i+1