test_io.py 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749
  1. import sys
  2. import gc
  3. import gzip
  4. import os
  5. import threading
  6. import time
  7. import warnings
  8. import io
  9. import re
  10. import pytest
  11. from pathlib import Path
  12. from tempfile import NamedTemporaryFile
  13. from io import BytesIO, StringIO
  14. from datetime import datetime
  15. import locale
  16. from multiprocessing import Value, get_context
  17. from ctypes import c_bool
  18. import numpy as np
  19. import numpy.ma as ma
  20. from numpy.lib._iotools import ConverterError, ConversionWarning
  21. from numpy.compat import asbytes
  22. from numpy.ma.testutils import assert_equal
  23. from numpy.testing import (
  24. assert_warns, assert_, assert_raises_regex, assert_raises,
  25. assert_allclose, assert_array_equal, temppath, tempdir, IS_PYPY,
  26. HAS_REFCOUNT, suppress_warnings, assert_no_gc_cycles, assert_no_warnings,
  27. break_cycles, IS_WASM
  28. )
  29. from numpy.testing._private.utils import requires_memory
  30. class TextIO(BytesIO):
  31. """Helper IO class.
  32. Writes encode strings to bytes if needed, reads return bytes.
  33. This makes it easier to emulate files opened in binary mode
  34. without needing to explicitly convert strings to bytes in
  35. setting up the test data.
  36. """
  37. def __init__(self, s=""):
  38. BytesIO.__init__(self, asbytes(s))
  39. def write(self, s):
  40. BytesIO.write(self, asbytes(s))
  41. def writelines(self, lines):
  42. BytesIO.writelines(self, [asbytes(s) for s in lines])
  43. IS_64BIT = sys.maxsize > 2**32
  44. try:
  45. import bz2
  46. HAS_BZ2 = True
  47. except ImportError:
  48. HAS_BZ2 = False
  49. try:
  50. import lzma
  51. HAS_LZMA = True
  52. except ImportError:
  53. HAS_LZMA = False
  54. def strptime(s, fmt=None):
  55. """
  56. This function is available in the datetime module only from Python >=
  57. 2.5.
  58. """
  59. if type(s) == bytes:
  60. s = s.decode("latin1")
  61. return datetime(*time.strptime(s, fmt)[:3])
  62. class RoundtripTest:
  63. def roundtrip(self, save_func, *args, **kwargs):
  64. """
  65. save_func : callable
  66. Function used to save arrays to file.
  67. file_on_disk : bool
  68. If true, store the file on disk, instead of in a
  69. string buffer.
  70. save_kwds : dict
  71. Parameters passed to `save_func`.
  72. load_kwds : dict
  73. Parameters passed to `numpy.load`.
  74. args : tuple of arrays
  75. Arrays stored to file.
  76. """
  77. save_kwds = kwargs.get('save_kwds', {})
  78. load_kwds = kwargs.get('load_kwds', {"allow_pickle": True})
  79. file_on_disk = kwargs.get('file_on_disk', False)
  80. if file_on_disk:
  81. target_file = NamedTemporaryFile(delete=False)
  82. load_file = target_file.name
  83. else:
  84. target_file = BytesIO()
  85. load_file = target_file
  86. try:
  87. arr = args
  88. save_func(target_file, *arr, **save_kwds)
  89. target_file.flush()
  90. target_file.seek(0)
  91. if sys.platform == 'win32' and not isinstance(target_file, BytesIO):
  92. target_file.close()
  93. arr_reloaded = np.load(load_file, **load_kwds)
  94. self.arr = arr
  95. self.arr_reloaded = arr_reloaded
  96. finally:
  97. if not isinstance(target_file, BytesIO):
  98. target_file.close()
  99. # holds an open file descriptor so it can't be deleted on win
  100. if 'arr_reloaded' in locals():
  101. if not isinstance(arr_reloaded, np.lib.npyio.NpzFile):
  102. os.remove(target_file.name)
  103. def check_roundtrips(self, a):
  104. self.roundtrip(a)
  105. self.roundtrip(a, file_on_disk=True)
  106. self.roundtrip(np.asfortranarray(a))
  107. self.roundtrip(np.asfortranarray(a), file_on_disk=True)
  108. if a.shape[0] > 1:
  109. # neither C nor Fortran contiguous for 2D arrays or more
  110. self.roundtrip(np.asfortranarray(a)[1:])
  111. self.roundtrip(np.asfortranarray(a)[1:], file_on_disk=True)
  112. def test_array(self):
  113. a = np.array([], float)
  114. self.check_roundtrips(a)
  115. a = np.array([[1, 2], [3, 4]], float)
  116. self.check_roundtrips(a)
  117. a = np.array([[1, 2], [3, 4]], int)
  118. self.check_roundtrips(a)
  119. a = np.array([[1 + 5j, 2 + 6j], [3 + 7j, 4 + 8j]], dtype=np.csingle)
  120. self.check_roundtrips(a)
  121. a = np.array([[1 + 5j, 2 + 6j], [3 + 7j, 4 + 8j]], dtype=np.cdouble)
  122. self.check_roundtrips(a)
  123. def test_array_object(self):
  124. a = np.array([], object)
  125. self.check_roundtrips(a)
  126. a = np.array([[1, 2], [3, 4]], object)
  127. self.check_roundtrips(a)
  128. def test_1D(self):
  129. a = np.array([1, 2, 3, 4], int)
  130. self.roundtrip(a)
  131. @pytest.mark.skipif(sys.platform == 'win32', reason="Fails on Win32")
  132. def test_mmap(self):
  133. a = np.array([[1, 2.5], [4, 7.3]])
  134. self.roundtrip(a, file_on_disk=True, load_kwds={'mmap_mode': 'r'})
  135. a = np.asfortranarray([[1, 2.5], [4, 7.3]])
  136. self.roundtrip(a, file_on_disk=True, load_kwds={'mmap_mode': 'r'})
  137. def test_record(self):
  138. a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
  139. self.check_roundtrips(a)
  140. @pytest.mark.slow
  141. def test_format_2_0(self):
  142. dt = [(("%d" % i) * 100, float) for i in range(500)]
  143. a = np.ones(1000, dtype=dt)
  144. with warnings.catch_warnings(record=True):
  145. warnings.filterwarnings('always', '', UserWarning)
  146. self.check_roundtrips(a)
  147. class TestSaveLoad(RoundtripTest):
  148. def roundtrip(self, *args, **kwargs):
  149. RoundtripTest.roundtrip(self, np.save, *args, **kwargs)
  150. assert_equal(self.arr[0], self.arr_reloaded)
  151. assert_equal(self.arr[0].dtype, self.arr_reloaded.dtype)
  152. assert_equal(self.arr[0].flags.fnc, self.arr_reloaded.flags.fnc)
  153. class TestSavezLoad(RoundtripTest):
  154. def roundtrip(self, *args, **kwargs):
  155. RoundtripTest.roundtrip(self, np.savez, *args, **kwargs)
  156. try:
  157. for n, arr in enumerate(self.arr):
  158. reloaded = self.arr_reloaded['arr_%d' % n]
  159. assert_equal(arr, reloaded)
  160. assert_equal(arr.dtype, reloaded.dtype)
  161. assert_equal(arr.flags.fnc, reloaded.flags.fnc)
  162. finally:
  163. # delete tempfile, must be done here on windows
  164. if self.arr_reloaded.fid:
  165. self.arr_reloaded.fid.close()
  166. os.remove(self.arr_reloaded.fid.name)
  167. @pytest.mark.skipif(IS_PYPY, reason="Hangs on PyPy")
  168. @pytest.mark.skipif(not IS_64BIT, reason="Needs 64bit platform")
  169. @pytest.mark.slow
  170. def test_big_arrays(self):
  171. L = (1 << 31) + 100000
  172. a = np.empty(L, dtype=np.uint8)
  173. with temppath(prefix="numpy_test_big_arrays_", suffix=".npz") as tmp:
  174. np.savez(tmp, a=a)
  175. del a
  176. npfile = np.load(tmp)
  177. a = npfile['a'] # Should succeed
  178. npfile.close()
  179. del a # Avoid pyflakes unused variable warning.
  180. def test_multiple_arrays(self):
  181. a = np.array([[1, 2], [3, 4]], float)
  182. b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex)
  183. self.roundtrip(a, b)
  184. def test_named_arrays(self):
  185. a = np.array([[1, 2], [3, 4]], float)
  186. b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex)
  187. c = BytesIO()
  188. np.savez(c, file_a=a, file_b=b)
  189. c.seek(0)
  190. l = np.load(c)
  191. assert_equal(a, l['file_a'])
  192. assert_equal(b, l['file_b'])
  193. def test_named_arrays_with_like(self):
  194. a = np.array([[1, 2], [3, 4]], float)
  195. b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex)
  196. c = BytesIO()
  197. np.savez(c, file_a=a, like=b)
  198. c.seek(0)
  199. l = np.load(c)
  200. assert_equal(a, l['file_a'])
  201. assert_equal(b, l['like'])
  202. def test_BagObj(self):
  203. a = np.array([[1, 2], [3, 4]], float)
  204. b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex)
  205. c = BytesIO()
  206. np.savez(c, file_a=a, file_b=b)
  207. c.seek(0)
  208. l = np.load(c)
  209. assert_equal(sorted(dir(l.f)), ['file_a','file_b'])
  210. assert_equal(a, l.f.file_a)
  211. assert_equal(b, l.f.file_b)
  212. @pytest.mark.skipif(IS_WASM, reason="Cannot start thread")
  213. def test_savez_filename_clashes(self):
  214. # Test that issue #852 is fixed
  215. # and savez functions in multithreaded environment
  216. def writer(error_list):
  217. with temppath(suffix='.npz') as tmp:
  218. arr = np.random.randn(500, 500)
  219. try:
  220. np.savez(tmp, arr=arr)
  221. except OSError as err:
  222. error_list.append(err)
  223. errors = []
  224. threads = [threading.Thread(target=writer, args=(errors,))
  225. for j in range(3)]
  226. for t in threads:
  227. t.start()
  228. for t in threads:
  229. t.join()
  230. if errors:
  231. raise AssertionError(errors)
  232. def test_not_closing_opened_fid(self):
  233. # Test that issue #2178 is fixed:
  234. # verify could seek on 'loaded' file
  235. with temppath(suffix='.npz') as tmp:
  236. with open(tmp, 'wb') as fp:
  237. np.savez(fp, data='LOVELY LOAD')
  238. with open(tmp, 'rb', 10000) as fp:
  239. fp.seek(0)
  240. assert_(not fp.closed)
  241. np.load(fp)['data']
  242. # fp must not get closed by .load
  243. assert_(not fp.closed)
  244. fp.seek(0)
  245. assert_(not fp.closed)
  246. @pytest.mark.slow_pypy
  247. def test_closing_fid(self):
  248. # Test that issue #1517 (too many opened files) remains closed
  249. # It might be a "weak" test since failed to get triggered on
  250. # e.g. Debian sid of 2012 Jul 05 but was reported to
  251. # trigger the failure on Ubuntu 10.04:
  252. # http://projects.scipy.org/numpy/ticket/1517#comment:2
  253. with temppath(suffix='.npz') as tmp:
  254. np.savez(tmp, data='LOVELY LOAD')
  255. # We need to check if the garbage collector can properly close
  256. # numpy npz file returned by np.load when their reference count
  257. # goes to zero. Python 3 running in debug mode raises a
  258. # ResourceWarning when file closing is left to the garbage
  259. # collector, so we catch the warnings.
  260. with suppress_warnings() as sup:
  261. sup.filter(ResourceWarning) # TODO: specify exact message
  262. for i in range(1, 1025):
  263. try:
  264. np.load(tmp)["data"]
  265. except Exception as e:
  266. msg = "Failed to load data from a file: %s" % e
  267. raise AssertionError(msg)
  268. finally:
  269. if IS_PYPY:
  270. gc.collect()
  271. def test_closing_zipfile_after_load(self):
  272. # Check that zipfile owns file and can close it. This needs to
  273. # pass a file name to load for the test. On windows failure will
  274. # cause a second error will be raised when the attempt to remove
  275. # the open file is made.
  276. prefix = 'numpy_test_closing_zipfile_after_load_'
  277. with temppath(suffix='.npz', prefix=prefix) as tmp:
  278. np.savez(tmp, lab='place holder')
  279. data = np.load(tmp)
  280. fp = data.zip.fp
  281. data.close()
  282. assert_(fp.closed)
  283. class TestSaveTxt:
  284. def test_array(self):
  285. a = np.array([[1, 2], [3, 4]], float)
  286. fmt = "%.18e"
  287. c = BytesIO()
  288. np.savetxt(c, a, fmt=fmt)
  289. c.seek(0)
  290. assert_equal(c.readlines(),
  291. [asbytes((fmt + ' ' + fmt + '\n') % (1, 2)),
  292. asbytes((fmt + ' ' + fmt + '\n') % (3, 4))])
  293. a = np.array([[1, 2], [3, 4]], int)
  294. c = BytesIO()
  295. np.savetxt(c, a, fmt='%d')
  296. c.seek(0)
  297. assert_equal(c.readlines(), [b'1 2\n', b'3 4\n'])
  298. def test_1D(self):
  299. a = np.array([1, 2, 3, 4], int)
  300. c = BytesIO()
  301. np.savetxt(c, a, fmt='%d')
  302. c.seek(0)
  303. lines = c.readlines()
  304. assert_equal(lines, [b'1\n', b'2\n', b'3\n', b'4\n'])
  305. def test_0D_3D(self):
  306. c = BytesIO()
  307. assert_raises(ValueError, np.savetxt, c, np.array(1))
  308. assert_raises(ValueError, np.savetxt, c, np.array([[[1], [2]]]))
  309. def test_structured(self):
  310. a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
  311. c = BytesIO()
  312. np.savetxt(c, a, fmt='%d')
  313. c.seek(0)
  314. assert_equal(c.readlines(), [b'1 2\n', b'3 4\n'])
  315. def test_structured_padded(self):
  316. # gh-13297
  317. a = np.array([(1, 2, 3),(4, 5, 6)], dtype=[
  318. ('foo', 'i4'), ('bar', 'i4'), ('baz', 'i4')
  319. ])
  320. c = BytesIO()
  321. np.savetxt(c, a[['foo', 'baz']], fmt='%d')
  322. c.seek(0)
  323. assert_equal(c.readlines(), [b'1 3\n', b'4 6\n'])
  324. def test_multifield_view(self):
  325. a = np.ones(1, dtype=[('x', 'i4'), ('y', 'i4'), ('z', 'f4')])
  326. v = a[['x', 'z']]
  327. with temppath(suffix='.npy') as path:
  328. path = Path(path)
  329. np.save(path, v)
  330. data = np.load(path)
  331. assert_array_equal(data, v)
  332. def test_delimiter(self):
  333. a = np.array([[1., 2.], [3., 4.]])
  334. c = BytesIO()
  335. np.savetxt(c, a, delimiter=',', fmt='%d')
  336. c.seek(0)
  337. assert_equal(c.readlines(), [b'1,2\n', b'3,4\n'])
  338. def test_format(self):
  339. a = np.array([(1, 2), (3, 4)])
  340. c = BytesIO()
  341. # Sequence of formats
  342. np.savetxt(c, a, fmt=['%02d', '%3.1f'])
  343. c.seek(0)
  344. assert_equal(c.readlines(), [b'01 2.0\n', b'03 4.0\n'])
  345. # A single multiformat string
  346. c = BytesIO()
  347. np.savetxt(c, a, fmt='%02d : %3.1f')
  348. c.seek(0)
  349. lines = c.readlines()
  350. assert_equal(lines, [b'01 : 2.0\n', b'03 : 4.0\n'])
  351. # Specify delimiter, should be overridden
  352. c = BytesIO()
  353. np.savetxt(c, a, fmt='%02d : %3.1f', delimiter=',')
  354. c.seek(0)
  355. lines = c.readlines()
  356. assert_equal(lines, [b'01 : 2.0\n', b'03 : 4.0\n'])
  357. # Bad fmt, should raise a ValueError
  358. c = BytesIO()
  359. assert_raises(ValueError, np.savetxt, c, a, fmt=99)
  360. def test_header_footer(self):
  361. # Test the functionality of the header and footer keyword argument.
  362. c = BytesIO()
  363. a = np.array([(1, 2), (3, 4)], dtype=int)
  364. test_header_footer = 'Test header / footer'
  365. # Test the header keyword argument
  366. np.savetxt(c, a, fmt='%1d', header=test_header_footer)
  367. c.seek(0)
  368. assert_equal(c.read(),
  369. asbytes('# ' + test_header_footer + '\n1 2\n3 4\n'))
  370. # Test the footer keyword argument
  371. c = BytesIO()
  372. np.savetxt(c, a, fmt='%1d', footer=test_header_footer)
  373. c.seek(0)
  374. assert_equal(c.read(),
  375. asbytes('1 2\n3 4\n# ' + test_header_footer + '\n'))
  376. # Test the commentstr keyword argument used on the header
  377. c = BytesIO()
  378. commentstr = '% '
  379. np.savetxt(c, a, fmt='%1d',
  380. header=test_header_footer, comments=commentstr)
  381. c.seek(0)
  382. assert_equal(c.read(),
  383. asbytes(commentstr + test_header_footer + '\n' + '1 2\n3 4\n'))
  384. # Test the commentstr keyword argument used on the footer
  385. c = BytesIO()
  386. commentstr = '% '
  387. np.savetxt(c, a, fmt='%1d',
  388. footer=test_header_footer, comments=commentstr)
  389. c.seek(0)
  390. assert_equal(c.read(),
  391. asbytes('1 2\n3 4\n' + commentstr + test_header_footer + '\n'))
  392. def test_file_roundtrip(self):
  393. with temppath() as name:
  394. a = np.array([(1, 2), (3, 4)])
  395. np.savetxt(name, a)
  396. b = np.loadtxt(name)
  397. assert_array_equal(a, b)
  398. def test_complex_arrays(self):
  399. ncols = 2
  400. nrows = 2
  401. a = np.zeros((ncols, nrows), dtype=np.complex128)
  402. re = np.pi
  403. im = np.e
  404. a[:] = re + 1.0j * im
  405. # One format only
  406. c = BytesIO()
  407. np.savetxt(c, a, fmt=' %+.3e')
  408. c.seek(0)
  409. lines = c.readlines()
  410. assert_equal(
  411. lines,
  412. [b' ( +3.142e+00+ +2.718e+00j) ( +3.142e+00+ +2.718e+00j)\n',
  413. b' ( +3.142e+00+ +2.718e+00j) ( +3.142e+00+ +2.718e+00j)\n'])
  414. # One format for each real and imaginary part
  415. c = BytesIO()
  416. np.savetxt(c, a, fmt=' %+.3e' * 2 * ncols)
  417. c.seek(0)
  418. lines = c.readlines()
  419. assert_equal(
  420. lines,
  421. [b' +3.142e+00 +2.718e+00 +3.142e+00 +2.718e+00\n',
  422. b' +3.142e+00 +2.718e+00 +3.142e+00 +2.718e+00\n'])
  423. # One format for each complex number
  424. c = BytesIO()
  425. np.savetxt(c, a, fmt=['(%.3e%+.3ej)'] * ncols)
  426. c.seek(0)
  427. lines = c.readlines()
  428. assert_equal(
  429. lines,
  430. [b'(3.142e+00+2.718e+00j) (3.142e+00+2.718e+00j)\n',
  431. b'(3.142e+00+2.718e+00j) (3.142e+00+2.718e+00j)\n'])
  432. def test_complex_negative_exponent(self):
  433. # Previous to 1.15, some formats generated x+-yj, gh 7895
  434. ncols = 2
  435. nrows = 2
  436. a = np.zeros((ncols, nrows), dtype=np.complex128)
  437. re = np.pi
  438. im = np.e
  439. a[:] = re - 1.0j * im
  440. c = BytesIO()
  441. np.savetxt(c, a, fmt='%.3e')
  442. c.seek(0)
  443. lines = c.readlines()
  444. assert_equal(
  445. lines,
  446. [b' (3.142e+00-2.718e+00j) (3.142e+00-2.718e+00j)\n',
  447. b' (3.142e+00-2.718e+00j) (3.142e+00-2.718e+00j)\n'])
  448. def test_custom_writer(self):
  449. class CustomWriter(list):
  450. def write(self, text):
  451. self.extend(text.split(b'\n'))
  452. w = CustomWriter()
  453. a = np.array([(1, 2), (3, 4)])
  454. np.savetxt(w, a)
  455. b = np.loadtxt(w)
  456. assert_array_equal(a, b)
  457. def test_unicode(self):
  458. utf8 = b'\xcf\x96'.decode('UTF-8')
  459. a = np.array([utf8], dtype=np.unicode_)
  460. with tempdir() as tmpdir:
  461. # set encoding as on windows it may not be unicode even on py3
  462. np.savetxt(os.path.join(tmpdir, 'test.csv'), a, fmt=['%s'],
  463. encoding='UTF-8')
  464. def test_unicode_roundtrip(self):
  465. utf8 = b'\xcf\x96'.decode('UTF-8')
  466. a = np.array([utf8], dtype=np.unicode_)
  467. # our gz wrapper support encoding
  468. suffixes = ['', '.gz']
  469. if HAS_BZ2:
  470. suffixes.append('.bz2')
  471. if HAS_LZMA:
  472. suffixes.extend(['.xz', '.lzma'])
  473. with tempdir() as tmpdir:
  474. for suffix in suffixes:
  475. np.savetxt(os.path.join(tmpdir, 'test.csv' + suffix), a,
  476. fmt=['%s'], encoding='UTF-16-LE')
  477. b = np.loadtxt(os.path.join(tmpdir, 'test.csv' + suffix),
  478. encoding='UTF-16-LE', dtype=np.unicode_)
  479. assert_array_equal(a, b)
  480. def test_unicode_bytestream(self):
  481. utf8 = b'\xcf\x96'.decode('UTF-8')
  482. a = np.array([utf8], dtype=np.unicode_)
  483. s = BytesIO()
  484. np.savetxt(s, a, fmt=['%s'], encoding='UTF-8')
  485. s.seek(0)
  486. assert_equal(s.read().decode('UTF-8'), utf8 + '\n')
  487. def test_unicode_stringstream(self):
  488. utf8 = b'\xcf\x96'.decode('UTF-8')
  489. a = np.array([utf8], dtype=np.unicode_)
  490. s = StringIO()
  491. np.savetxt(s, a, fmt=['%s'], encoding='UTF-8')
  492. s.seek(0)
  493. assert_equal(s.read(), utf8 + '\n')
  494. @pytest.mark.parametrize("fmt", ["%f", b"%f"])
  495. @pytest.mark.parametrize("iotype", [StringIO, BytesIO])
  496. def test_unicode_and_bytes_fmt(self, fmt, iotype):
  497. # string type of fmt should not matter, see also gh-4053
  498. a = np.array([1.])
  499. s = iotype()
  500. np.savetxt(s, a, fmt=fmt)
  501. s.seek(0)
  502. if iotype is StringIO:
  503. assert_equal(s.read(), "%f\n" % 1.)
  504. else:
  505. assert_equal(s.read(), b"%f\n" % 1.)
  506. @pytest.mark.skipif(sys.platform=='win32', reason="files>4GB may not work")
  507. @pytest.mark.slow
  508. @requires_memory(free_bytes=7e9)
  509. def test_large_zip(self):
  510. def check_large_zip(memoryerror_raised):
  511. memoryerror_raised.value = False
  512. try:
  513. # The test takes at least 6GB of memory, writes a file larger
  514. # than 4GB. This tests the ``allowZip64`` kwarg to ``zipfile``
  515. test_data = np.asarray([np.random.rand(
  516. np.random.randint(50,100),4)
  517. for i in range(800000)], dtype=object)
  518. with tempdir() as tmpdir:
  519. np.savez(os.path.join(tmpdir, 'test.npz'),
  520. test_data=test_data)
  521. except MemoryError:
  522. memoryerror_raised.value = True
  523. raise
  524. # run in a subprocess to ensure memory is released on PyPy, see gh-15775
  525. # Use an object in shared memory to re-raise the MemoryError exception
  526. # in our process if needed, see gh-16889
  527. memoryerror_raised = Value(c_bool)
  528. # Since Python 3.8, the default start method for multiprocessing has
  529. # been changed from 'fork' to 'spawn' on macOS, causing inconsistency
  530. # on memory sharing model, lead to failed test for check_large_zip
  531. ctx = get_context('fork')
  532. p = ctx.Process(target=check_large_zip, args=(memoryerror_raised,))
  533. p.start()
  534. p.join()
  535. if memoryerror_raised.value:
  536. raise MemoryError("Child process raised a MemoryError exception")
  537. # -9 indicates a SIGKILL, probably an OOM.
  538. if p.exitcode == -9:
  539. pytest.xfail("subprocess got a SIGKILL, apparently free memory was not sufficient")
  540. assert p.exitcode == 0
  541. class LoadTxtBase:
  542. def check_compressed(self, fopen, suffixes):
  543. # Test that we can load data from a compressed file
  544. wanted = np.arange(6).reshape((2, 3))
  545. linesep = ('\n', '\r\n', '\r')
  546. for sep in linesep:
  547. data = '0 1 2' + sep + '3 4 5'
  548. for suffix in suffixes:
  549. with temppath(suffix=suffix) as name:
  550. with fopen(name, mode='wt', encoding='UTF-32-LE') as f:
  551. f.write(data)
  552. res = self.loadfunc(name, encoding='UTF-32-LE')
  553. assert_array_equal(res, wanted)
  554. with fopen(name, "rt", encoding='UTF-32-LE') as f:
  555. res = self.loadfunc(f)
  556. assert_array_equal(res, wanted)
  557. def test_compressed_gzip(self):
  558. self.check_compressed(gzip.open, ('.gz',))
  559. @pytest.mark.skipif(not HAS_BZ2, reason="Needs bz2")
  560. def test_compressed_bz2(self):
  561. self.check_compressed(bz2.open, ('.bz2',))
  562. @pytest.mark.skipif(not HAS_LZMA, reason="Needs lzma")
  563. def test_compressed_lzma(self):
  564. self.check_compressed(lzma.open, ('.xz', '.lzma'))
  565. def test_encoding(self):
  566. with temppath() as path:
  567. with open(path, "wb") as f:
  568. f.write('0.\n1.\n2.'.encode("UTF-16"))
  569. x = self.loadfunc(path, encoding="UTF-16")
  570. assert_array_equal(x, [0., 1., 2.])
  571. def test_stringload(self):
  572. # umlaute
  573. nonascii = b'\xc3\xb6\xc3\xbc\xc3\xb6'.decode("UTF-8")
  574. with temppath() as path:
  575. with open(path, "wb") as f:
  576. f.write(nonascii.encode("UTF-16"))
  577. x = self.loadfunc(path, encoding="UTF-16", dtype=np.unicode_)
  578. assert_array_equal(x, nonascii)
  579. def test_binary_decode(self):
  580. utf16 = b'\xff\xfeh\x04 \x00i\x04 \x00j\x04'
  581. v = self.loadfunc(BytesIO(utf16), dtype=np.unicode_, encoding='UTF-16')
  582. assert_array_equal(v, np.array(utf16.decode('UTF-16').split()))
  583. def test_converters_decode(self):
  584. # test converters that decode strings
  585. c = TextIO()
  586. c.write(b'\xcf\x96')
  587. c.seek(0)
  588. x = self.loadfunc(c, dtype=np.unicode_,
  589. converters={0: lambda x: x.decode('UTF-8')})
  590. a = np.array([b'\xcf\x96'.decode('UTF-8')])
  591. assert_array_equal(x, a)
  592. def test_converters_nodecode(self):
  593. # test native string converters enabled by setting an encoding
  594. utf8 = b'\xcf\x96'.decode('UTF-8')
  595. with temppath() as path:
  596. with io.open(path, 'wt', encoding='UTF-8') as f:
  597. f.write(utf8)
  598. x = self.loadfunc(path, dtype=np.unicode_,
  599. converters={0: lambda x: x + 't'},
  600. encoding='UTF-8')
  601. a = np.array([utf8 + 't'])
  602. assert_array_equal(x, a)
  603. class TestLoadTxt(LoadTxtBase):
  604. loadfunc = staticmethod(np.loadtxt)
  605. def setup_method(self):
  606. # lower chunksize for testing
  607. self.orig_chunk = np.lib.npyio._loadtxt_chunksize
  608. np.lib.npyio._loadtxt_chunksize = 1
  609. def teardown_method(self):
  610. np.lib.npyio._loadtxt_chunksize = self.orig_chunk
  611. def test_record(self):
  612. c = TextIO()
  613. c.write('1 2\n3 4')
  614. c.seek(0)
  615. x = np.loadtxt(c, dtype=[('x', np.int32), ('y', np.int32)])
  616. a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
  617. assert_array_equal(x, a)
  618. d = TextIO()
  619. d.write('M 64 75.0\nF 25 60.0')
  620. d.seek(0)
  621. mydescriptor = {'names': ('gender', 'age', 'weight'),
  622. 'formats': ('S1', 'i4', 'f4')}
  623. b = np.array([('M', 64.0, 75.0),
  624. ('F', 25.0, 60.0)], dtype=mydescriptor)
  625. y = np.loadtxt(d, dtype=mydescriptor)
  626. assert_array_equal(y, b)
  627. def test_array(self):
  628. c = TextIO()
  629. c.write('1 2\n3 4')
  630. c.seek(0)
  631. x = np.loadtxt(c, dtype=int)
  632. a = np.array([[1, 2], [3, 4]], int)
  633. assert_array_equal(x, a)
  634. c.seek(0)
  635. x = np.loadtxt(c, dtype=float)
  636. a = np.array([[1, 2], [3, 4]], float)
  637. assert_array_equal(x, a)
  638. def test_1D(self):
  639. c = TextIO()
  640. c.write('1\n2\n3\n4\n')
  641. c.seek(0)
  642. x = np.loadtxt(c, dtype=int)
  643. a = np.array([1, 2, 3, 4], int)
  644. assert_array_equal(x, a)
  645. c = TextIO()
  646. c.write('1,2,3,4\n')
  647. c.seek(0)
  648. x = np.loadtxt(c, dtype=int, delimiter=',')
  649. a = np.array([1, 2, 3, 4], int)
  650. assert_array_equal(x, a)
  651. def test_missing(self):
  652. c = TextIO()
  653. c.write('1,2,3,,5\n')
  654. c.seek(0)
  655. x = np.loadtxt(c, dtype=int, delimiter=',',
  656. converters={3: lambda s: int(s or - 999)})
  657. a = np.array([1, 2, 3, -999, 5], int)
  658. assert_array_equal(x, a)
  659. def test_converters_with_usecols(self):
  660. c = TextIO()
  661. c.write('1,2,3,,5\n6,7,8,9,10\n')
  662. c.seek(0)
  663. x = np.loadtxt(c, dtype=int, delimiter=',',
  664. converters={3: lambda s: int(s or - 999)},
  665. usecols=(1, 3,))
  666. a = np.array([[2, -999], [7, 9]], int)
  667. assert_array_equal(x, a)
  668. def test_comments_unicode(self):
  669. c = TextIO()
  670. c.write('# comment\n1,2,3,5\n')
  671. c.seek(0)
  672. x = np.loadtxt(c, dtype=int, delimiter=',',
  673. comments='#')
  674. a = np.array([1, 2, 3, 5], int)
  675. assert_array_equal(x, a)
  676. def test_comments_byte(self):
  677. c = TextIO()
  678. c.write('# comment\n1,2,3,5\n')
  679. c.seek(0)
  680. x = np.loadtxt(c, dtype=int, delimiter=',',
  681. comments=b'#')
  682. a = np.array([1, 2, 3, 5], int)
  683. assert_array_equal(x, a)
  684. def test_comments_multiple(self):
  685. c = TextIO()
  686. c.write('# comment\n1,2,3\n@ comment2\n4,5,6 // comment3')
  687. c.seek(0)
  688. x = np.loadtxt(c, dtype=int, delimiter=',',
  689. comments=['#', '@', '//'])
  690. a = np.array([[1, 2, 3], [4, 5, 6]], int)
  691. assert_array_equal(x, a)
  692. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  693. reason="PyPy bug in error formatting")
  694. def test_comments_multi_chars(self):
  695. c = TextIO()
  696. c.write('/* comment\n1,2,3,5\n')
  697. c.seek(0)
  698. x = np.loadtxt(c, dtype=int, delimiter=',',
  699. comments='/*')
  700. a = np.array([1, 2, 3, 5], int)
  701. assert_array_equal(x, a)
  702. # Check that '/*' is not transformed to ['/', '*']
  703. c = TextIO()
  704. c.write('*/ comment\n1,2,3,5\n')
  705. c.seek(0)
  706. assert_raises(ValueError, np.loadtxt, c, dtype=int, delimiter=',',
  707. comments='/*')
  708. def test_skiprows(self):
  709. c = TextIO()
  710. c.write('comment\n1,2,3,5\n')
  711. c.seek(0)
  712. x = np.loadtxt(c, dtype=int, delimiter=',',
  713. skiprows=1)
  714. a = np.array([1, 2, 3, 5], int)
  715. assert_array_equal(x, a)
  716. c = TextIO()
  717. c.write('# comment\n1,2,3,5\n')
  718. c.seek(0)
  719. x = np.loadtxt(c, dtype=int, delimiter=',',
  720. skiprows=1)
  721. a = np.array([1, 2, 3, 5], int)
  722. assert_array_equal(x, a)
  723. def test_usecols(self):
  724. a = np.array([[1, 2], [3, 4]], float)
  725. c = BytesIO()
  726. np.savetxt(c, a)
  727. c.seek(0)
  728. x = np.loadtxt(c, dtype=float, usecols=(1,))
  729. assert_array_equal(x, a[:, 1])
  730. a = np.array([[1, 2, 3], [3, 4, 5]], float)
  731. c = BytesIO()
  732. np.savetxt(c, a)
  733. c.seek(0)
  734. x = np.loadtxt(c, dtype=float, usecols=(1, 2))
  735. assert_array_equal(x, a[:, 1:])
  736. # Testing with arrays instead of tuples.
  737. c.seek(0)
  738. x = np.loadtxt(c, dtype=float, usecols=np.array([1, 2]))
  739. assert_array_equal(x, a[:, 1:])
  740. # Testing with an integer instead of a sequence
  741. for int_type in [int, np.int8, np.int16,
  742. np.int32, np.int64, np.uint8, np.uint16,
  743. np.uint32, np.uint64]:
  744. to_read = int_type(1)
  745. c.seek(0)
  746. x = np.loadtxt(c, dtype=float, usecols=to_read)
  747. assert_array_equal(x, a[:, 1])
  748. # Testing with some crazy custom integer type
  749. class CrazyInt:
  750. def __index__(self):
  751. return 1
  752. crazy_int = CrazyInt()
  753. c.seek(0)
  754. x = np.loadtxt(c, dtype=float, usecols=crazy_int)
  755. assert_array_equal(x, a[:, 1])
  756. c.seek(0)
  757. x = np.loadtxt(c, dtype=float, usecols=(crazy_int,))
  758. assert_array_equal(x, a[:, 1])
  759. # Checking with dtypes defined converters.
  760. data = '''JOE 70.1 25.3
  761. BOB 60.5 27.9
  762. '''
  763. c = TextIO(data)
  764. names = ['stid', 'temp']
  765. dtypes = ['S4', 'f8']
  766. arr = np.loadtxt(c, usecols=(0, 2), dtype=list(zip(names, dtypes)))
  767. assert_equal(arr['stid'], [b"JOE", b"BOB"])
  768. assert_equal(arr['temp'], [25.3, 27.9])
  769. # Testing non-ints in usecols
  770. c.seek(0)
  771. bogus_idx = 1.5
  772. assert_raises_regex(
  773. TypeError,
  774. '^usecols must be.*%s' % type(bogus_idx).__name__,
  775. np.loadtxt, c, usecols=bogus_idx
  776. )
  777. assert_raises_regex(
  778. TypeError,
  779. '^usecols must be.*%s' % type(bogus_idx).__name__,
  780. np.loadtxt, c, usecols=[0, bogus_idx, 0]
  781. )
  782. def test_bad_usecols(self):
  783. with pytest.raises(OverflowError):
  784. np.loadtxt(["1\n"], usecols=[2**64], delimiter=",")
  785. with pytest.raises((ValueError, OverflowError)):
  786. # Overflow error on 32bit platforms
  787. np.loadtxt(["1\n"], usecols=[2**62], delimiter=",")
  788. with pytest.raises(TypeError,
  789. match="If a structured dtype .*. But 1 usecols were given and "
  790. "the number of fields is 3."):
  791. np.loadtxt(["1,1\n"], dtype="i,(2)i", usecols=[0], delimiter=",")
  792. def test_fancy_dtype(self):
  793. c = TextIO()
  794. c.write('1,2,3.0\n4,5,6.0\n')
  795. c.seek(0)
  796. dt = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
  797. x = np.loadtxt(c, dtype=dt, delimiter=',')
  798. a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dt)
  799. assert_array_equal(x, a)
  800. def test_shaped_dtype(self):
  801. c = TextIO("aaaa 1.0 8.0 1 2 3 4 5 6")
  802. dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
  803. ('block', int, (2, 3))])
  804. x = np.loadtxt(c, dtype=dt)
  805. a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])],
  806. dtype=dt)
  807. assert_array_equal(x, a)
  808. def test_3d_shaped_dtype(self):
  809. c = TextIO("aaaa 1.0 8.0 1 2 3 4 5 6 7 8 9 10 11 12")
  810. dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
  811. ('block', int, (2, 2, 3))])
  812. x = np.loadtxt(c, dtype=dt)
  813. a = np.array([('aaaa', 1.0, 8.0,
  814. [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])],
  815. dtype=dt)
  816. assert_array_equal(x, a)
  817. def test_str_dtype(self):
  818. # see gh-8033
  819. c = ["str1", "str2"]
  820. for dt in (str, np.bytes_):
  821. a = np.array(["str1", "str2"], dtype=dt)
  822. x = np.loadtxt(c, dtype=dt)
  823. assert_array_equal(x, a)
  824. def test_empty_file(self):
  825. with pytest.warns(UserWarning, match="input contained no data"):
  826. c = TextIO()
  827. x = np.loadtxt(c)
  828. assert_equal(x.shape, (0,))
  829. x = np.loadtxt(c, dtype=np.int64)
  830. assert_equal(x.shape, (0,))
  831. assert_(x.dtype == np.int64)
  832. def test_unused_converter(self):
  833. c = TextIO()
  834. c.writelines(['1 21\n', '3 42\n'])
  835. c.seek(0)
  836. data = np.loadtxt(c, usecols=(1,),
  837. converters={0: lambda s: int(s, 16)})
  838. assert_array_equal(data, [21, 42])
  839. c.seek(0)
  840. data = np.loadtxt(c, usecols=(1,),
  841. converters={1: lambda s: int(s, 16)})
  842. assert_array_equal(data, [33, 66])
  843. def test_dtype_with_object(self):
  844. # Test using an explicit dtype with an object
  845. data = """ 1; 2001-01-01
  846. 2; 2002-01-31 """
  847. ndtype = [('idx', int), ('code', object)]
  848. func = lambda s: strptime(s.strip(), "%Y-%m-%d")
  849. converters = {1: func}
  850. test = np.loadtxt(TextIO(data), delimiter=";", dtype=ndtype,
  851. converters=converters)
  852. control = np.array(
  853. [(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))],
  854. dtype=ndtype)
  855. assert_equal(test, control)
  856. def test_uint64_type(self):
  857. tgt = (9223372043271415339, 9223372043271415853)
  858. c = TextIO()
  859. c.write("%s %s" % tgt)
  860. c.seek(0)
  861. res = np.loadtxt(c, dtype=np.uint64)
  862. assert_equal(res, tgt)
  863. def test_int64_type(self):
  864. tgt = (-9223372036854775807, 9223372036854775807)
  865. c = TextIO()
  866. c.write("%s %s" % tgt)
  867. c.seek(0)
  868. res = np.loadtxt(c, dtype=np.int64)
  869. assert_equal(res, tgt)
  870. def test_from_float_hex(self):
  871. # IEEE doubles and floats only, otherwise the float32
  872. # conversion may fail.
  873. tgt = np.logspace(-10, 10, 5).astype(np.float32)
  874. tgt = np.hstack((tgt, -tgt)).astype(float)
  875. inp = '\n'.join(map(float.hex, tgt))
  876. c = TextIO()
  877. c.write(inp)
  878. for dt in [float, np.float32]:
  879. c.seek(0)
  880. res = np.loadtxt(
  881. c, dtype=dt, converters=float.fromhex, encoding="latin1")
  882. assert_equal(res, tgt, err_msg="%s" % dt)
  883. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  884. reason="PyPy bug in error formatting")
  885. def test_default_float_converter_no_default_hex_conversion(self):
  886. """
  887. Ensure that fromhex is only used for values with the correct prefix and
  888. is not called by default. Regression test related to gh-19598.
  889. """
  890. c = TextIO("a b c")
  891. with pytest.raises(ValueError,
  892. match=".*convert string 'a' to float64 at row 0, column 1"):
  893. np.loadtxt(c)
  894. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  895. reason="PyPy bug in error formatting")
  896. def test_default_float_converter_exception(self):
  897. """
  898. Ensure that the exception message raised during failed floating point
  899. conversion is correct. Regression test related to gh-19598.
  900. """
  901. c = TextIO("qrs tuv") # Invalid values for default float converter
  902. with pytest.raises(ValueError,
  903. match="could not convert string 'qrs' to float64"):
  904. np.loadtxt(c)
  905. def test_from_complex(self):
  906. tgt = (complex(1, 1), complex(1, -1))
  907. c = TextIO()
  908. c.write("%s %s" % tgt)
  909. c.seek(0)
  910. res = np.loadtxt(c, dtype=complex)
  911. assert_equal(res, tgt)
  912. def test_complex_misformatted(self):
  913. # test for backward compatibility
  914. # some complex formats used to generate x+-yj
  915. a = np.zeros((2, 2), dtype=np.complex128)
  916. re = np.pi
  917. im = np.e
  918. a[:] = re - 1.0j * im
  919. c = BytesIO()
  920. np.savetxt(c, a, fmt='%.16e')
  921. c.seek(0)
  922. txt = c.read()
  923. c.seek(0)
  924. # misformat the sign on the imaginary part, gh 7895
  925. txt_bad = txt.replace(b'e+00-', b'e00+-')
  926. assert_(txt_bad != txt)
  927. c.write(txt_bad)
  928. c.seek(0)
  929. res = np.loadtxt(c, dtype=complex)
  930. assert_equal(res, a)
  931. def test_universal_newline(self):
  932. with temppath() as name:
  933. with open(name, 'w') as f:
  934. f.write('1 21\r3 42\r')
  935. data = np.loadtxt(name)
  936. assert_array_equal(data, [[1, 21], [3, 42]])
  937. def test_empty_field_after_tab(self):
  938. c = TextIO()
  939. c.write('1 \t2 \t3\tstart \n4\t5\t6\t \n7\t8\t9.5\t')
  940. c.seek(0)
  941. dt = {'names': ('x', 'y', 'z', 'comment'),
  942. 'formats': ('<i4', '<i4', '<f4', '|S8')}
  943. x = np.loadtxt(c, dtype=dt, delimiter='\t')
  944. a = np.array([b'start ', b' ', b''])
  945. assert_array_equal(x['comment'], a)
  946. def test_unpack_structured(self):
  947. txt = TextIO("M 21 72\nF 35 58")
  948. dt = {'names': ('a', 'b', 'c'), 'formats': ('|S1', '<i4', '<f4')}
  949. a, b, c = np.loadtxt(txt, dtype=dt, unpack=True)
  950. assert_(a.dtype.str == '|S1')
  951. assert_(b.dtype.str == '<i4')
  952. assert_(c.dtype.str == '<f4')
  953. assert_array_equal(a, np.array([b'M', b'F']))
  954. assert_array_equal(b, np.array([21, 35]))
  955. assert_array_equal(c, np.array([72., 58.]))
  956. def test_ndmin_keyword(self):
  957. c = TextIO()
  958. c.write('1,2,3\n4,5,6')
  959. c.seek(0)
  960. assert_raises(ValueError, np.loadtxt, c, ndmin=3)
  961. c.seek(0)
  962. assert_raises(ValueError, np.loadtxt, c, ndmin=1.5)
  963. c.seek(0)
  964. x = np.loadtxt(c, dtype=int, delimiter=',', ndmin=1)
  965. a = np.array([[1, 2, 3], [4, 5, 6]])
  966. assert_array_equal(x, a)
  967. d = TextIO()
  968. d.write('0,1,2')
  969. d.seek(0)
  970. x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=2)
  971. assert_(x.shape == (1, 3))
  972. d.seek(0)
  973. x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=1)
  974. assert_(x.shape == (3,))
  975. d.seek(0)
  976. x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=0)
  977. assert_(x.shape == (3,))
  978. e = TextIO()
  979. e.write('0\n1\n2')
  980. e.seek(0)
  981. x = np.loadtxt(e, dtype=int, delimiter=',', ndmin=2)
  982. assert_(x.shape == (3, 1))
  983. e.seek(0)
  984. x = np.loadtxt(e, dtype=int, delimiter=',', ndmin=1)
  985. assert_(x.shape == (3,))
  986. e.seek(0)
  987. x = np.loadtxt(e, dtype=int, delimiter=',', ndmin=0)
  988. assert_(x.shape == (3,))
  989. # Test ndmin kw with empty file.
  990. with pytest.warns(UserWarning, match="input contained no data"):
  991. f = TextIO()
  992. assert_(np.loadtxt(f, ndmin=2).shape == (0, 1,))
  993. assert_(np.loadtxt(f, ndmin=1).shape == (0,))
  994. def test_generator_source(self):
  995. def count():
  996. for i in range(10):
  997. yield "%d" % i
  998. res = np.loadtxt(count())
  999. assert_array_equal(res, np.arange(10))
  1000. def test_bad_line(self):
  1001. c = TextIO()
  1002. c.write('1 2 3\n4 5 6\n2 3')
  1003. c.seek(0)
  1004. # Check for exception and that exception contains line number
  1005. assert_raises_regex(ValueError, "3", np.loadtxt, c)
  1006. def test_none_as_string(self):
  1007. # gh-5155, None should work as string when format demands it
  1008. c = TextIO()
  1009. c.write('100,foo,200\n300,None,400')
  1010. c.seek(0)
  1011. dt = np.dtype([('x', int), ('a', 'S10'), ('y', int)])
  1012. np.loadtxt(c, delimiter=',', dtype=dt, comments=None) # Should succeed
  1013. @pytest.mark.skipif(locale.getpreferredencoding() == 'ANSI_X3.4-1968',
  1014. reason="Wrong preferred encoding")
  1015. def test_binary_load(self):
  1016. butf8 = b"5,6,7,\xc3\x95scarscar\r\n15,2,3,hello\r\n"\
  1017. b"20,2,3,\xc3\x95scar\r\n"
  1018. sutf8 = butf8.decode("UTF-8").replace("\r", "").splitlines()
  1019. with temppath() as path:
  1020. with open(path, "wb") as f:
  1021. f.write(butf8)
  1022. with open(path, "rb") as f:
  1023. x = np.loadtxt(f, encoding="UTF-8", dtype=np.unicode_)
  1024. assert_array_equal(x, sutf8)
  1025. # test broken latin1 conversion people now rely on
  1026. with open(path, "rb") as f:
  1027. x = np.loadtxt(f, encoding="UTF-8", dtype="S")
  1028. x = [b'5,6,7,\xc3\x95scarscar', b'15,2,3,hello', b'20,2,3,\xc3\x95scar']
  1029. assert_array_equal(x, np.array(x, dtype="S"))
  1030. def test_max_rows(self):
  1031. c = TextIO()
  1032. c.write('1,2,3,5\n4,5,7,8\n2,1,4,5')
  1033. c.seek(0)
  1034. x = np.loadtxt(c, dtype=int, delimiter=',',
  1035. max_rows=1)
  1036. a = np.array([1, 2, 3, 5], int)
  1037. assert_array_equal(x, a)
  1038. def test_max_rows_with_skiprows(self):
  1039. c = TextIO()
  1040. c.write('comments\n1,2,3,5\n4,5,7,8\n2,1,4,5')
  1041. c.seek(0)
  1042. x = np.loadtxt(c, dtype=int, delimiter=',',
  1043. skiprows=1, max_rows=1)
  1044. a = np.array([1, 2, 3, 5], int)
  1045. assert_array_equal(x, a)
  1046. c = TextIO()
  1047. c.write('comment\n1,2,3,5\n4,5,7,8\n2,1,4,5')
  1048. c.seek(0)
  1049. x = np.loadtxt(c, dtype=int, delimiter=',',
  1050. skiprows=1, max_rows=2)
  1051. a = np.array([[1, 2, 3, 5], [4, 5, 7, 8]], int)
  1052. assert_array_equal(x, a)
  1053. def test_max_rows_with_read_continuation(self):
  1054. c = TextIO()
  1055. c.write('1,2,3,5\n4,5,7,8\n2,1,4,5')
  1056. c.seek(0)
  1057. x = np.loadtxt(c, dtype=int, delimiter=',',
  1058. max_rows=2)
  1059. a = np.array([[1, 2, 3, 5], [4, 5, 7, 8]], int)
  1060. assert_array_equal(x, a)
  1061. # test continuation
  1062. x = np.loadtxt(c, dtype=int, delimiter=',')
  1063. a = np.array([2,1,4,5], int)
  1064. assert_array_equal(x, a)
  1065. def test_max_rows_larger(self):
  1066. #test max_rows > num rows
  1067. c = TextIO()
  1068. c.write('comment\n1,2,3,5\n4,5,7,8\n2,1,4,5')
  1069. c.seek(0)
  1070. x = np.loadtxt(c, dtype=int, delimiter=',',
  1071. skiprows=1, max_rows=6)
  1072. a = np.array([[1, 2, 3, 5], [4, 5, 7, 8], [2, 1, 4, 5]], int)
  1073. assert_array_equal(x, a)
  1074. @pytest.mark.parametrize(["skip", "data"], [
  1075. (1, ["ignored\n", "1,2\n", "\n", "3,4\n"]),
  1076. # "Bad" lines that do not end in newlines:
  1077. (1, ["ignored", "1,2", "", "3,4"]),
  1078. (1, StringIO("ignored\n1,2\n\n3,4")),
  1079. # Same as above, but do not skip any lines:
  1080. (0, ["-1,0\n", "1,2\n", "\n", "3,4\n"]),
  1081. (0, ["-1,0", "1,2", "", "3,4"]),
  1082. (0, StringIO("-1,0\n1,2\n\n3,4"))])
  1083. def test_max_rows_empty_lines(self, skip, data):
  1084. with pytest.warns(UserWarning,
  1085. match=f"Input line 3.*max_rows={3-skip}"):
  1086. res = np.loadtxt(data, dtype=int, skiprows=skip, delimiter=",",
  1087. max_rows=3-skip)
  1088. assert_array_equal(res, [[-1, 0], [1, 2], [3, 4]][skip:])
  1089. if isinstance(data, StringIO):
  1090. data.seek(0)
  1091. with warnings.catch_warnings():
  1092. warnings.simplefilter("error", UserWarning)
  1093. with pytest.raises(UserWarning):
  1094. np.loadtxt(data, dtype=int, skiprows=skip, delimiter=",",
  1095. max_rows=3-skip)
  1096. class Testfromregex:
  1097. def test_record(self):
  1098. c = TextIO()
  1099. c.write('1.312 foo\n1.534 bar\n4.444 qux')
  1100. c.seek(0)
  1101. dt = [('num', np.float64), ('val', 'S3')]
  1102. x = np.fromregex(c, r"([0-9.]+)\s+(...)", dt)
  1103. a = np.array([(1.312, 'foo'), (1.534, 'bar'), (4.444, 'qux')],
  1104. dtype=dt)
  1105. assert_array_equal(x, a)
  1106. def test_record_2(self):
  1107. c = TextIO()
  1108. c.write('1312 foo\n1534 bar\n4444 qux')
  1109. c.seek(0)
  1110. dt = [('num', np.int32), ('val', 'S3')]
  1111. x = np.fromregex(c, r"(\d+)\s+(...)", dt)
  1112. a = np.array([(1312, 'foo'), (1534, 'bar'), (4444, 'qux')],
  1113. dtype=dt)
  1114. assert_array_equal(x, a)
  1115. def test_record_3(self):
  1116. c = TextIO()
  1117. c.write('1312 foo\n1534 bar\n4444 qux')
  1118. c.seek(0)
  1119. dt = [('num', np.float64)]
  1120. x = np.fromregex(c, r"(\d+)\s+...", dt)
  1121. a = np.array([(1312,), (1534,), (4444,)], dtype=dt)
  1122. assert_array_equal(x, a)
  1123. @pytest.mark.parametrize("path_type", [str, Path])
  1124. def test_record_unicode(self, path_type):
  1125. utf8 = b'\xcf\x96'
  1126. with temppath() as str_path:
  1127. path = path_type(str_path)
  1128. with open(path, 'wb') as f:
  1129. f.write(b'1.312 foo' + utf8 + b' \n1.534 bar\n4.444 qux')
  1130. dt = [('num', np.float64), ('val', 'U4')]
  1131. x = np.fromregex(path, r"(?u)([0-9.]+)\s+(\w+)", dt, encoding='UTF-8')
  1132. a = np.array([(1.312, 'foo' + utf8.decode('UTF-8')), (1.534, 'bar'),
  1133. (4.444, 'qux')], dtype=dt)
  1134. assert_array_equal(x, a)
  1135. regexp = re.compile(r"([0-9.]+)\s+(\w+)", re.UNICODE)
  1136. x = np.fromregex(path, regexp, dt, encoding='UTF-8')
  1137. assert_array_equal(x, a)
  1138. def test_compiled_bytes(self):
  1139. regexp = re.compile(b'(\\d)')
  1140. c = BytesIO(b'123')
  1141. dt = [('num', np.float64)]
  1142. a = np.array([1, 2, 3], dtype=dt)
  1143. x = np.fromregex(c, regexp, dt)
  1144. assert_array_equal(x, a)
  1145. def test_bad_dtype_not_structured(self):
  1146. regexp = re.compile(b'(\\d)')
  1147. c = BytesIO(b'123')
  1148. with pytest.raises(TypeError, match='structured datatype'):
  1149. np.fromregex(c, regexp, dtype=np.float64)
  1150. #####--------------------------------------------------------------------------
  1151. class TestFromTxt(LoadTxtBase):
  1152. loadfunc = staticmethod(np.genfromtxt)
  1153. def test_record(self):
  1154. # Test w/ explicit dtype
  1155. data = TextIO('1 2\n3 4')
  1156. test = np.genfromtxt(data, dtype=[('x', np.int32), ('y', np.int32)])
  1157. control = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
  1158. assert_equal(test, control)
  1159. #
  1160. data = TextIO('M 64.0 75.0\nF 25.0 60.0')
  1161. descriptor = {'names': ('gender', 'age', 'weight'),
  1162. 'formats': ('S1', 'i4', 'f4')}
  1163. control = np.array([('M', 64.0, 75.0), ('F', 25.0, 60.0)],
  1164. dtype=descriptor)
  1165. test = np.genfromtxt(data, dtype=descriptor)
  1166. assert_equal(test, control)
  1167. def test_array(self):
  1168. # Test outputting a standard ndarray
  1169. data = TextIO('1 2\n3 4')
  1170. control = np.array([[1, 2], [3, 4]], dtype=int)
  1171. test = np.genfromtxt(data, dtype=int)
  1172. assert_array_equal(test, control)
  1173. #
  1174. data.seek(0)
  1175. control = np.array([[1, 2], [3, 4]], dtype=float)
  1176. test = np.loadtxt(data, dtype=float)
  1177. assert_array_equal(test, control)
  1178. def test_1D(self):
  1179. # Test squeezing to 1D
  1180. control = np.array([1, 2, 3, 4], int)
  1181. #
  1182. data = TextIO('1\n2\n3\n4\n')
  1183. test = np.genfromtxt(data, dtype=int)
  1184. assert_array_equal(test, control)
  1185. #
  1186. data = TextIO('1,2,3,4\n')
  1187. test = np.genfromtxt(data, dtype=int, delimiter=',')
  1188. assert_array_equal(test, control)
  1189. def test_comments(self):
  1190. # Test the stripping of comments
  1191. control = np.array([1, 2, 3, 5], int)
  1192. # Comment on its own line
  1193. data = TextIO('# comment\n1,2,3,5\n')
  1194. test = np.genfromtxt(data, dtype=int, delimiter=',', comments='#')
  1195. assert_equal(test, control)
  1196. # Comment at the end of a line
  1197. data = TextIO('1,2,3,5# comment\n')
  1198. test = np.genfromtxt(data, dtype=int, delimiter=',', comments='#')
  1199. assert_equal(test, control)
  1200. def test_skiprows(self):
  1201. # Test row skipping
  1202. control = np.array([1, 2, 3, 5], int)
  1203. kwargs = dict(dtype=int, delimiter=',')
  1204. #
  1205. data = TextIO('comment\n1,2,3,5\n')
  1206. test = np.genfromtxt(data, skip_header=1, **kwargs)
  1207. assert_equal(test, control)
  1208. #
  1209. data = TextIO('# comment\n1,2,3,5\n')
  1210. test = np.loadtxt(data, skiprows=1, **kwargs)
  1211. assert_equal(test, control)
  1212. def test_skip_footer(self):
  1213. data = ["# %i" % i for i in range(1, 6)]
  1214. data.append("A, B, C")
  1215. data.extend(["%i,%3.1f,%03s" % (i, i, i) for i in range(51)])
  1216. data[-1] = "99,99"
  1217. kwargs = dict(delimiter=",", names=True, skip_header=5, skip_footer=10)
  1218. test = np.genfromtxt(TextIO("\n".join(data)), **kwargs)
  1219. ctrl = np.array([("%f" % i, "%f" % i, "%f" % i) for i in range(41)],
  1220. dtype=[(_, float) for _ in "ABC"])
  1221. assert_equal(test, ctrl)
  1222. def test_skip_footer_with_invalid(self):
  1223. with suppress_warnings() as sup:
  1224. sup.filter(ConversionWarning)
  1225. basestr = '1 1\n2 2\n3 3\n4 4\n5 \n6 \n7 \n'
  1226. # Footer too small to get rid of all invalid values
  1227. assert_raises(ValueError, np.genfromtxt,
  1228. TextIO(basestr), skip_footer=1)
  1229. # except ValueError:
  1230. # pass
  1231. a = np.genfromtxt(
  1232. TextIO(basestr), skip_footer=1, invalid_raise=False)
  1233. assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]]))
  1234. #
  1235. a = np.genfromtxt(TextIO(basestr), skip_footer=3)
  1236. assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]]))
  1237. #
  1238. basestr = '1 1\n2 \n3 3\n4 4\n5 \n6 6\n7 7\n'
  1239. a = np.genfromtxt(
  1240. TextIO(basestr), skip_footer=1, invalid_raise=False)
  1241. assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.], [6., 6.]]))
  1242. a = np.genfromtxt(
  1243. TextIO(basestr), skip_footer=3, invalid_raise=False)
  1244. assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.]]))
  1245. def test_header(self):
  1246. # Test retrieving a header
  1247. data = TextIO('gender age weight\nM 64.0 75.0\nF 25.0 60.0')
  1248. with warnings.catch_warnings(record=True) as w:
  1249. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1250. test = np.genfromtxt(data, dtype=None, names=True)
  1251. assert_(w[0].category is np.VisibleDeprecationWarning)
  1252. control = {'gender': np.array([b'M', b'F']),
  1253. 'age': np.array([64.0, 25.0]),
  1254. 'weight': np.array([75.0, 60.0])}
  1255. assert_equal(test['gender'], control['gender'])
  1256. assert_equal(test['age'], control['age'])
  1257. assert_equal(test['weight'], control['weight'])
  1258. def test_auto_dtype(self):
  1259. # Test the automatic definition of the output dtype
  1260. data = TextIO('A 64 75.0 3+4j True\nBCD 25 60.0 5+6j False')
  1261. with warnings.catch_warnings(record=True) as w:
  1262. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1263. test = np.genfromtxt(data, dtype=None)
  1264. assert_(w[0].category is np.VisibleDeprecationWarning)
  1265. control = [np.array([b'A', b'BCD']),
  1266. np.array([64, 25]),
  1267. np.array([75.0, 60.0]),
  1268. np.array([3 + 4j, 5 + 6j]),
  1269. np.array([True, False]), ]
  1270. assert_equal(test.dtype.names, ['f0', 'f1', 'f2', 'f3', 'f4'])
  1271. for (i, ctrl) in enumerate(control):
  1272. assert_equal(test['f%i' % i], ctrl)
  1273. def test_auto_dtype_uniform(self):
  1274. # Tests whether the output dtype can be uniformized
  1275. data = TextIO('1 2 3 4\n5 6 7 8\n')
  1276. test = np.genfromtxt(data, dtype=None)
  1277. control = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
  1278. assert_equal(test, control)
  1279. def test_fancy_dtype(self):
  1280. # Check that a nested dtype isn't MIA
  1281. data = TextIO('1,2,3.0\n4,5,6.0\n')
  1282. fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
  1283. test = np.genfromtxt(data, dtype=fancydtype, delimiter=',')
  1284. control = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=fancydtype)
  1285. assert_equal(test, control)
  1286. def test_names_overwrite(self):
  1287. # Test overwriting the names of the dtype
  1288. descriptor = {'names': ('g', 'a', 'w'),
  1289. 'formats': ('S1', 'i4', 'f4')}
  1290. data = TextIO(b'M 64.0 75.0\nF 25.0 60.0')
  1291. names = ('gender', 'age', 'weight')
  1292. test = np.genfromtxt(data, dtype=descriptor, names=names)
  1293. descriptor['names'] = names
  1294. control = np.array([('M', 64.0, 75.0),
  1295. ('F', 25.0, 60.0)], dtype=descriptor)
  1296. assert_equal(test, control)
  1297. def test_bad_fname(self):
  1298. with pytest.raises(TypeError, match='fname must be a string,'):
  1299. np.genfromtxt(123)
  1300. def test_commented_header(self):
  1301. # Check that names can be retrieved even if the line is commented out.
  1302. data = TextIO("""
  1303. #gender age weight
  1304. M 21 72.100000
  1305. F 35 58.330000
  1306. M 33 21.99
  1307. """)
  1308. # The # is part of the first name and should be deleted automatically.
  1309. with warnings.catch_warnings(record=True) as w:
  1310. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1311. test = np.genfromtxt(data, names=True, dtype=None)
  1312. assert_(w[0].category is np.VisibleDeprecationWarning)
  1313. ctrl = np.array([('M', 21, 72.1), ('F', 35, 58.33), ('M', 33, 21.99)],
  1314. dtype=[('gender', '|S1'), ('age', int), ('weight', float)])
  1315. assert_equal(test, ctrl)
  1316. # Ditto, but we should get rid of the first element
  1317. data = TextIO(b"""
  1318. # gender age weight
  1319. M 21 72.100000
  1320. F 35 58.330000
  1321. M 33 21.99
  1322. """)
  1323. with warnings.catch_warnings(record=True) as w:
  1324. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1325. test = np.genfromtxt(data, names=True, dtype=None)
  1326. assert_(w[0].category is np.VisibleDeprecationWarning)
  1327. assert_equal(test, ctrl)
  1328. def test_names_and_comments_none(self):
  1329. # Tests case when names is true but comments is None (gh-10780)
  1330. data = TextIO('col1 col2\n 1 2\n 3 4')
  1331. test = np.genfromtxt(data, dtype=(int, int), comments=None, names=True)
  1332. control = np.array([(1, 2), (3, 4)], dtype=[('col1', int), ('col2', int)])
  1333. assert_equal(test, control)
  1334. def test_file_is_closed_on_error(self):
  1335. # gh-13200
  1336. with tempdir() as tmpdir:
  1337. fpath = os.path.join(tmpdir, "test.csv")
  1338. with open(fpath, "wb") as f:
  1339. f.write('\N{GREEK PI SYMBOL}'.encode())
  1340. # ResourceWarnings are emitted from a destructor, so won't be
  1341. # detected by regular propagation to errors.
  1342. with assert_no_warnings():
  1343. with pytest.raises(UnicodeDecodeError):
  1344. np.genfromtxt(fpath, encoding="ascii")
  1345. def test_autonames_and_usecols(self):
  1346. # Tests names and usecols
  1347. data = TextIO('A B C D\n aaaa 121 45 9.1')
  1348. with warnings.catch_warnings(record=True) as w:
  1349. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1350. test = np.genfromtxt(data, usecols=('A', 'C', 'D'),
  1351. names=True, dtype=None)
  1352. assert_(w[0].category is np.VisibleDeprecationWarning)
  1353. control = np.array(('aaaa', 45, 9.1),
  1354. dtype=[('A', '|S4'), ('C', int), ('D', float)])
  1355. assert_equal(test, control)
  1356. def test_converters_with_usecols(self):
  1357. # Test the combination user-defined converters and usecol
  1358. data = TextIO('1,2,3,,5\n6,7,8,9,10\n')
  1359. test = np.genfromtxt(data, dtype=int, delimiter=',',
  1360. converters={3: lambda s: int(s or - 999)},
  1361. usecols=(1, 3,))
  1362. control = np.array([[2, -999], [7, 9]], int)
  1363. assert_equal(test, control)
  1364. def test_converters_with_usecols_and_names(self):
  1365. # Tests names and usecols
  1366. data = TextIO('A B C D\n aaaa 121 45 9.1')
  1367. with warnings.catch_warnings(record=True) as w:
  1368. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1369. test = np.genfromtxt(data, usecols=('A', 'C', 'D'), names=True,
  1370. dtype=None,
  1371. converters={'C': lambda s: 2 * int(s)})
  1372. assert_(w[0].category is np.VisibleDeprecationWarning)
  1373. control = np.array(('aaaa', 90, 9.1),
  1374. dtype=[('A', '|S4'), ('C', int), ('D', float)])
  1375. assert_equal(test, control)
  1376. def test_converters_cornercases(self):
  1377. # Test the conversion to datetime.
  1378. converter = {
  1379. 'date': lambda s: strptime(s, '%Y-%m-%d %H:%M:%SZ')}
  1380. data = TextIO('2009-02-03 12:00:00Z, 72214.0')
  1381. test = np.genfromtxt(data, delimiter=',', dtype=None,
  1382. names=['date', 'stid'], converters=converter)
  1383. control = np.array((datetime(2009, 2, 3), 72214.),
  1384. dtype=[('date', np.object_), ('stid', float)])
  1385. assert_equal(test, control)
  1386. def test_converters_cornercases2(self):
  1387. # Test the conversion to datetime64.
  1388. converter = {
  1389. 'date': lambda s: np.datetime64(strptime(s, '%Y-%m-%d %H:%M:%SZ'))}
  1390. data = TextIO('2009-02-03 12:00:00Z, 72214.0')
  1391. test = np.genfromtxt(data, delimiter=',', dtype=None,
  1392. names=['date', 'stid'], converters=converter)
  1393. control = np.array((datetime(2009, 2, 3), 72214.),
  1394. dtype=[('date', 'datetime64[us]'), ('stid', float)])
  1395. assert_equal(test, control)
  1396. def test_unused_converter(self):
  1397. # Test whether unused converters are forgotten
  1398. data = TextIO("1 21\n 3 42\n")
  1399. test = np.genfromtxt(data, usecols=(1,),
  1400. converters={0: lambda s: int(s, 16)})
  1401. assert_equal(test, [21, 42])
  1402. #
  1403. data.seek(0)
  1404. test = np.genfromtxt(data, usecols=(1,),
  1405. converters={1: lambda s: int(s, 16)})
  1406. assert_equal(test, [33, 66])
  1407. def test_invalid_converter(self):
  1408. strip_rand = lambda x: float((b'r' in x.lower() and x.split()[-1]) or
  1409. (b'r' not in x.lower() and x.strip() or 0.0))
  1410. strip_per = lambda x: float((b'%' in x.lower() and x.split()[0]) or
  1411. (b'%' not in x.lower() and x.strip() or 0.0))
  1412. s = TextIO("D01N01,10/1/2003 ,1 %,R 75,400,600\r\n"
  1413. "L24U05,12/5/2003, 2 %,1,300, 150.5\r\n"
  1414. "D02N03,10/10/2004,R 1,,7,145.55")
  1415. kwargs = dict(
  1416. converters={2: strip_per, 3: strip_rand}, delimiter=",",
  1417. dtype=None)
  1418. assert_raises(ConverterError, np.genfromtxt, s, **kwargs)
  1419. def test_tricky_converter_bug1666(self):
  1420. # Test some corner cases
  1421. s = TextIO('q1,2\nq3,4')
  1422. cnv = lambda s: float(s[1:])
  1423. test = np.genfromtxt(s, delimiter=',', converters={0: cnv})
  1424. control = np.array([[1., 2.], [3., 4.]])
  1425. assert_equal(test, control)
  1426. def test_dtype_with_converters(self):
  1427. dstr = "2009; 23; 46"
  1428. test = np.genfromtxt(TextIO(dstr,),
  1429. delimiter=";", dtype=float, converters={0: bytes})
  1430. control = np.array([('2009', 23., 46)],
  1431. dtype=[('f0', '|S4'), ('f1', float), ('f2', float)])
  1432. assert_equal(test, control)
  1433. test = np.genfromtxt(TextIO(dstr,),
  1434. delimiter=";", dtype=float, converters={0: float})
  1435. control = np.array([2009., 23., 46],)
  1436. assert_equal(test, control)
  1437. def test_dtype_with_converters_and_usecols(self):
  1438. dstr = "1,5,-1,1:1\n2,8,-1,1:n\n3,3,-2,m:n\n"
  1439. dmap = {'1:1':0, '1:n':1, 'm:1':2, 'm:n':3}
  1440. dtyp = [('e1','i4'),('e2','i4'),('e3','i2'),('n', 'i1')]
  1441. conv = {0: int, 1: int, 2: int, 3: lambda r: dmap[r.decode()]}
  1442. test = np.recfromcsv(TextIO(dstr,), dtype=dtyp, delimiter=',',
  1443. names=None, converters=conv)
  1444. control = np.rec.array([(1,5,-1,0), (2,8,-1,1), (3,3,-2,3)], dtype=dtyp)
  1445. assert_equal(test, control)
  1446. dtyp = [('e1','i4'),('e2','i4'),('n', 'i1')]
  1447. test = np.recfromcsv(TextIO(dstr,), dtype=dtyp, delimiter=',',
  1448. usecols=(0,1,3), names=None, converters=conv)
  1449. control = np.rec.array([(1,5,0), (2,8,1), (3,3,3)], dtype=dtyp)
  1450. assert_equal(test, control)
  1451. def test_dtype_with_object(self):
  1452. # Test using an explicit dtype with an object
  1453. data = """ 1; 2001-01-01
  1454. 2; 2002-01-31 """
  1455. ndtype = [('idx', int), ('code', object)]
  1456. func = lambda s: strptime(s.strip(), "%Y-%m-%d")
  1457. converters = {1: func}
  1458. test = np.genfromtxt(TextIO(data), delimiter=";", dtype=ndtype,
  1459. converters=converters)
  1460. control = np.array(
  1461. [(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))],
  1462. dtype=ndtype)
  1463. assert_equal(test, control)
  1464. ndtype = [('nest', [('idx', int), ('code', object)])]
  1465. with assert_raises_regex(NotImplementedError,
  1466. 'Nested fields.* not supported.*'):
  1467. test = np.genfromtxt(TextIO(data), delimiter=";",
  1468. dtype=ndtype, converters=converters)
  1469. # nested but empty fields also aren't supported
  1470. ndtype = [('idx', int), ('code', object), ('nest', [])]
  1471. with assert_raises_regex(NotImplementedError,
  1472. 'Nested fields.* not supported.*'):
  1473. test = np.genfromtxt(TextIO(data), delimiter=";",
  1474. dtype=ndtype, converters=converters)
  1475. def test_dtype_with_object_no_converter(self):
  1476. # Object without a converter uses bytes:
  1477. parsed = np.genfromtxt(TextIO("1"), dtype=object)
  1478. assert parsed[()] == b"1"
  1479. parsed = np.genfromtxt(TextIO("string"), dtype=object)
  1480. assert parsed[()] == b"string"
  1481. def test_userconverters_with_explicit_dtype(self):
  1482. # Test user_converters w/ explicit (standard) dtype
  1483. data = TextIO('skip,skip,2001-01-01,1.0,skip')
  1484. test = np.genfromtxt(data, delimiter=",", names=None, dtype=float,
  1485. usecols=(2, 3), converters={2: bytes})
  1486. control = np.array([('2001-01-01', 1.)],
  1487. dtype=[('', '|S10'), ('', float)])
  1488. assert_equal(test, control)
  1489. def test_utf8_userconverters_with_explicit_dtype(self):
  1490. utf8 = b'\xcf\x96'
  1491. with temppath() as path:
  1492. with open(path, 'wb') as f:
  1493. f.write(b'skip,skip,2001-01-01' + utf8 + b',1.0,skip')
  1494. test = np.genfromtxt(path, delimiter=",", names=None, dtype=float,
  1495. usecols=(2, 3), converters={2: np.compat.unicode},
  1496. encoding='UTF-8')
  1497. control = np.array([('2001-01-01' + utf8.decode('UTF-8'), 1.)],
  1498. dtype=[('', '|U11'), ('', float)])
  1499. assert_equal(test, control)
  1500. def test_spacedelimiter(self):
  1501. # Test space delimiter
  1502. data = TextIO("1 2 3 4 5\n6 7 8 9 10")
  1503. test = np.genfromtxt(data)
  1504. control = np.array([[1., 2., 3., 4., 5.],
  1505. [6., 7., 8., 9., 10.]])
  1506. assert_equal(test, control)
  1507. def test_integer_delimiter(self):
  1508. # Test using an integer for delimiter
  1509. data = " 1 2 3\n 4 5 67\n890123 4"
  1510. test = np.genfromtxt(TextIO(data), delimiter=3)
  1511. control = np.array([[1, 2, 3], [4, 5, 67], [890, 123, 4]])
  1512. assert_equal(test, control)
  1513. def test_missing(self):
  1514. data = TextIO('1,2,3,,5\n')
  1515. test = np.genfromtxt(data, dtype=int, delimiter=',',
  1516. converters={3: lambda s: int(s or - 999)})
  1517. control = np.array([1, 2, 3, -999, 5], int)
  1518. assert_equal(test, control)
  1519. def test_missing_with_tabs(self):
  1520. # Test w/ a delimiter tab
  1521. txt = "1\t2\t3\n\t2\t\n1\t\t3"
  1522. test = np.genfromtxt(TextIO(txt), delimiter="\t",
  1523. usemask=True,)
  1524. ctrl_d = np.array([(1, 2, 3), (np.nan, 2, np.nan), (1, np.nan, 3)],)
  1525. ctrl_m = np.array([(0, 0, 0), (1, 0, 1), (0, 1, 0)], dtype=bool)
  1526. assert_equal(test.data, ctrl_d)
  1527. assert_equal(test.mask, ctrl_m)
  1528. def test_usecols(self):
  1529. # Test the selection of columns
  1530. # Select 1 column
  1531. control = np.array([[1, 2], [3, 4]], float)
  1532. data = TextIO()
  1533. np.savetxt(data, control)
  1534. data.seek(0)
  1535. test = np.genfromtxt(data, dtype=float, usecols=(1,))
  1536. assert_equal(test, control[:, 1])
  1537. #
  1538. control = np.array([[1, 2, 3], [3, 4, 5]], float)
  1539. data = TextIO()
  1540. np.savetxt(data, control)
  1541. data.seek(0)
  1542. test = np.genfromtxt(data, dtype=float, usecols=(1, 2))
  1543. assert_equal(test, control[:, 1:])
  1544. # Testing with arrays instead of tuples.
  1545. data.seek(0)
  1546. test = np.genfromtxt(data, dtype=float, usecols=np.array([1, 2]))
  1547. assert_equal(test, control[:, 1:])
  1548. def test_usecols_as_css(self):
  1549. # Test giving usecols with a comma-separated string
  1550. data = "1 2 3\n4 5 6"
  1551. test = np.genfromtxt(TextIO(data),
  1552. names="a, b, c", usecols="a, c")
  1553. ctrl = np.array([(1, 3), (4, 6)], dtype=[(_, float) for _ in "ac"])
  1554. assert_equal(test, ctrl)
  1555. def test_usecols_with_structured_dtype(self):
  1556. # Test usecols with an explicit structured dtype
  1557. data = TextIO("JOE 70.1 25.3\nBOB 60.5 27.9")
  1558. names = ['stid', 'temp']
  1559. dtypes = ['S4', 'f8']
  1560. test = np.genfromtxt(
  1561. data, usecols=(0, 2), dtype=list(zip(names, dtypes)))
  1562. assert_equal(test['stid'], [b"JOE", b"BOB"])
  1563. assert_equal(test['temp'], [25.3, 27.9])
  1564. def test_usecols_with_integer(self):
  1565. # Test usecols with an integer
  1566. test = np.genfromtxt(TextIO(b"1 2 3\n4 5 6"), usecols=0)
  1567. assert_equal(test, np.array([1., 4.]))
  1568. def test_usecols_with_named_columns(self):
  1569. # Test usecols with named columns
  1570. ctrl = np.array([(1, 3), (4, 6)], dtype=[('a', float), ('c', float)])
  1571. data = "1 2 3\n4 5 6"
  1572. kwargs = dict(names="a, b, c")
  1573. test = np.genfromtxt(TextIO(data), usecols=(0, -1), **kwargs)
  1574. assert_equal(test, ctrl)
  1575. test = np.genfromtxt(TextIO(data),
  1576. usecols=('a', 'c'), **kwargs)
  1577. assert_equal(test, ctrl)
  1578. def test_empty_file(self):
  1579. # Test that an empty file raises the proper warning.
  1580. with suppress_warnings() as sup:
  1581. sup.filter(message="genfromtxt: Empty input file:")
  1582. data = TextIO()
  1583. test = np.genfromtxt(data)
  1584. assert_equal(test, np.array([]))
  1585. # when skip_header > 0
  1586. test = np.genfromtxt(data, skip_header=1)
  1587. assert_equal(test, np.array([]))
  1588. def test_fancy_dtype_alt(self):
  1589. # Check that a nested dtype isn't MIA
  1590. data = TextIO('1,2,3.0\n4,5,6.0\n')
  1591. fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
  1592. test = np.genfromtxt(data, dtype=fancydtype, delimiter=',', usemask=True)
  1593. control = ma.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=fancydtype)
  1594. assert_equal(test, control)
  1595. def test_shaped_dtype(self):
  1596. c = TextIO("aaaa 1.0 8.0 1 2 3 4 5 6")
  1597. dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
  1598. ('block', int, (2, 3))])
  1599. x = np.genfromtxt(c, dtype=dt)
  1600. a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])],
  1601. dtype=dt)
  1602. assert_array_equal(x, a)
  1603. def test_withmissing(self):
  1604. data = TextIO('A,B\n0,1\n2,N/A')
  1605. kwargs = dict(delimiter=",", missing_values="N/A", names=True)
  1606. test = np.genfromtxt(data, dtype=None, usemask=True, **kwargs)
  1607. control = ma.array([(0, 1), (2, -1)],
  1608. mask=[(False, False), (False, True)],
  1609. dtype=[('A', int), ('B', int)])
  1610. assert_equal(test, control)
  1611. assert_equal(test.mask, control.mask)
  1612. #
  1613. data.seek(0)
  1614. test = np.genfromtxt(data, usemask=True, **kwargs)
  1615. control = ma.array([(0, 1), (2, -1)],
  1616. mask=[(False, False), (False, True)],
  1617. dtype=[('A', float), ('B', float)])
  1618. assert_equal(test, control)
  1619. assert_equal(test.mask, control.mask)
  1620. def test_user_missing_values(self):
  1621. data = "A, B, C\n0, 0., 0j\n1, N/A, 1j\n-9, 2.2, N/A\n3, -99, 3j"
  1622. basekwargs = dict(dtype=None, delimiter=",", names=True,)
  1623. mdtype = [('A', int), ('B', float), ('C', complex)]
  1624. #
  1625. test = np.genfromtxt(TextIO(data), missing_values="N/A",
  1626. **basekwargs)
  1627. control = ma.array([(0, 0.0, 0j), (1, -999, 1j),
  1628. (-9, 2.2, -999j), (3, -99, 3j)],
  1629. mask=[(0, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)],
  1630. dtype=mdtype)
  1631. assert_equal(test, control)
  1632. #
  1633. basekwargs['dtype'] = mdtype
  1634. test = np.genfromtxt(TextIO(data),
  1635. missing_values={0: -9, 1: -99, 2: -999j}, usemask=True, **basekwargs)
  1636. control = ma.array([(0, 0.0, 0j), (1, -999, 1j),
  1637. (-9, 2.2, -999j), (3, -99, 3j)],
  1638. mask=[(0, 0, 0), (0, 1, 0), (1, 0, 1), (0, 1, 0)],
  1639. dtype=mdtype)
  1640. assert_equal(test, control)
  1641. #
  1642. test = np.genfromtxt(TextIO(data),
  1643. missing_values={0: -9, 'B': -99, 'C': -999j},
  1644. usemask=True,
  1645. **basekwargs)
  1646. control = ma.array([(0, 0.0, 0j), (1, -999, 1j),
  1647. (-9, 2.2, -999j), (3, -99, 3j)],
  1648. mask=[(0, 0, 0), (0, 1, 0), (1, 0, 1), (0, 1, 0)],
  1649. dtype=mdtype)
  1650. assert_equal(test, control)
  1651. def test_user_filling_values(self):
  1652. # Test with missing and filling values
  1653. ctrl = np.array([(0, 3), (4, -999)], dtype=[('a', int), ('b', int)])
  1654. data = "N/A, 2, 3\n4, ,???"
  1655. kwargs = dict(delimiter=",",
  1656. dtype=int,
  1657. names="a,b,c",
  1658. missing_values={0: "N/A", 'b': " ", 2: "???"},
  1659. filling_values={0: 0, 'b': 0, 2: -999})
  1660. test = np.genfromtxt(TextIO(data), **kwargs)
  1661. ctrl = np.array([(0, 2, 3), (4, 0, -999)],
  1662. dtype=[(_, int) for _ in "abc"])
  1663. assert_equal(test, ctrl)
  1664. #
  1665. test = np.genfromtxt(TextIO(data), usecols=(0, -1), **kwargs)
  1666. ctrl = np.array([(0, 3), (4, -999)], dtype=[(_, int) for _ in "ac"])
  1667. assert_equal(test, ctrl)
  1668. data2 = "1,2,*,4\n5,*,7,8\n"
  1669. test = np.genfromtxt(TextIO(data2), delimiter=',', dtype=int,
  1670. missing_values="*", filling_values=0)
  1671. ctrl = np.array([[1, 2, 0, 4], [5, 0, 7, 8]])
  1672. assert_equal(test, ctrl)
  1673. test = np.genfromtxt(TextIO(data2), delimiter=',', dtype=int,
  1674. missing_values="*", filling_values=-1)
  1675. ctrl = np.array([[1, 2, -1, 4], [5, -1, 7, 8]])
  1676. assert_equal(test, ctrl)
  1677. def test_withmissing_float(self):
  1678. data = TextIO('A,B\n0,1.5\n2,-999.00')
  1679. test = np.genfromtxt(data, dtype=None, delimiter=',',
  1680. missing_values='-999.0', names=True, usemask=True)
  1681. control = ma.array([(0, 1.5), (2, -1.)],
  1682. mask=[(False, False), (False, True)],
  1683. dtype=[('A', int), ('B', float)])
  1684. assert_equal(test, control)
  1685. assert_equal(test.mask, control.mask)
  1686. def test_with_masked_column_uniform(self):
  1687. # Test masked column
  1688. data = TextIO('1 2 3\n4 5 6\n')
  1689. test = np.genfromtxt(data, dtype=None,
  1690. missing_values='2,5', usemask=True)
  1691. control = ma.array([[1, 2, 3], [4, 5, 6]], mask=[[0, 1, 0], [0, 1, 0]])
  1692. assert_equal(test, control)
  1693. def test_with_masked_column_various(self):
  1694. # Test masked column
  1695. data = TextIO('True 2 3\nFalse 5 6\n')
  1696. test = np.genfromtxt(data, dtype=None,
  1697. missing_values='2,5', usemask=True)
  1698. control = ma.array([(1, 2, 3), (0, 5, 6)],
  1699. mask=[(0, 1, 0), (0, 1, 0)],
  1700. dtype=[('f0', bool), ('f1', bool), ('f2', int)])
  1701. assert_equal(test, control)
  1702. def test_invalid_raise(self):
  1703. # Test invalid raise
  1704. data = ["1, 1, 1, 1, 1"] * 50
  1705. for i in range(5):
  1706. data[10 * i] = "2, 2, 2, 2 2"
  1707. data.insert(0, "a, b, c, d, e")
  1708. mdata = TextIO("\n".join(data))
  1709. kwargs = dict(delimiter=",", dtype=None, names=True)
  1710. def f():
  1711. return np.genfromtxt(mdata, invalid_raise=False, **kwargs)
  1712. mtest = assert_warns(ConversionWarning, f)
  1713. assert_equal(len(mtest), 45)
  1714. assert_equal(mtest, np.ones(45, dtype=[(_, int) for _ in 'abcde']))
  1715. #
  1716. mdata.seek(0)
  1717. assert_raises(ValueError, np.genfromtxt, mdata,
  1718. delimiter=",", names=True)
  1719. def test_invalid_raise_with_usecols(self):
  1720. # Test invalid_raise with usecols
  1721. data = ["1, 1, 1, 1, 1"] * 50
  1722. for i in range(5):
  1723. data[10 * i] = "2, 2, 2, 2 2"
  1724. data.insert(0, "a, b, c, d, e")
  1725. mdata = TextIO("\n".join(data))
  1726. kwargs = dict(delimiter=",", dtype=None, names=True,
  1727. invalid_raise=False)
  1728. def f():
  1729. return np.genfromtxt(mdata, usecols=(0, 4), **kwargs)
  1730. mtest = assert_warns(ConversionWarning, f)
  1731. assert_equal(len(mtest), 45)
  1732. assert_equal(mtest, np.ones(45, dtype=[(_, int) for _ in 'ae']))
  1733. #
  1734. mdata.seek(0)
  1735. mtest = np.genfromtxt(mdata, usecols=(0, 1), **kwargs)
  1736. assert_equal(len(mtest), 50)
  1737. control = np.ones(50, dtype=[(_, int) for _ in 'ab'])
  1738. control[[10 * _ for _ in range(5)]] = (2, 2)
  1739. assert_equal(mtest, control)
  1740. def test_inconsistent_dtype(self):
  1741. # Test inconsistent dtype
  1742. data = ["1, 1, 1, 1, -1.1"] * 50
  1743. mdata = TextIO("\n".join(data))
  1744. converters = {4: lambda x: "(%s)" % x.decode()}
  1745. kwargs = dict(delimiter=",", converters=converters,
  1746. dtype=[(_, int) for _ in 'abcde'],)
  1747. assert_raises(ValueError, np.genfromtxt, mdata, **kwargs)
  1748. def test_default_field_format(self):
  1749. # Test default format
  1750. data = "0, 1, 2.3\n4, 5, 6.7"
  1751. mtest = np.genfromtxt(TextIO(data),
  1752. delimiter=",", dtype=None, defaultfmt="f%02i")
  1753. ctrl = np.array([(0, 1, 2.3), (4, 5, 6.7)],
  1754. dtype=[("f00", int), ("f01", int), ("f02", float)])
  1755. assert_equal(mtest, ctrl)
  1756. def test_single_dtype_wo_names(self):
  1757. # Test single dtype w/o names
  1758. data = "0, 1, 2.3\n4, 5, 6.7"
  1759. mtest = np.genfromtxt(TextIO(data),
  1760. delimiter=",", dtype=float, defaultfmt="f%02i")
  1761. ctrl = np.array([[0., 1., 2.3], [4., 5., 6.7]], dtype=float)
  1762. assert_equal(mtest, ctrl)
  1763. def test_single_dtype_w_explicit_names(self):
  1764. # Test single dtype w explicit names
  1765. data = "0, 1, 2.3\n4, 5, 6.7"
  1766. mtest = np.genfromtxt(TextIO(data),
  1767. delimiter=",", dtype=float, names="a, b, c")
  1768. ctrl = np.array([(0., 1., 2.3), (4., 5., 6.7)],
  1769. dtype=[(_, float) for _ in "abc"])
  1770. assert_equal(mtest, ctrl)
  1771. def test_single_dtype_w_implicit_names(self):
  1772. # Test single dtype w implicit names
  1773. data = "a, b, c\n0, 1, 2.3\n4, 5, 6.7"
  1774. mtest = np.genfromtxt(TextIO(data),
  1775. delimiter=",", dtype=float, names=True)
  1776. ctrl = np.array([(0., 1., 2.3), (4., 5., 6.7)],
  1777. dtype=[(_, float) for _ in "abc"])
  1778. assert_equal(mtest, ctrl)
  1779. def test_easy_structured_dtype(self):
  1780. # Test easy structured dtype
  1781. data = "0, 1, 2.3\n4, 5, 6.7"
  1782. mtest = np.genfromtxt(TextIO(data), delimiter=",",
  1783. dtype=(int, float, float), defaultfmt="f_%02i")
  1784. ctrl = np.array([(0, 1., 2.3), (4, 5., 6.7)],
  1785. dtype=[("f_00", int), ("f_01", float), ("f_02", float)])
  1786. assert_equal(mtest, ctrl)
  1787. def test_autostrip(self):
  1788. # Test autostrip
  1789. data = "01/01/2003 , 1.3, abcde"
  1790. kwargs = dict(delimiter=",", dtype=None)
  1791. with warnings.catch_warnings(record=True) as w:
  1792. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1793. mtest = np.genfromtxt(TextIO(data), **kwargs)
  1794. assert_(w[0].category is np.VisibleDeprecationWarning)
  1795. ctrl = np.array([('01/01/2003 ', 1.3, ' abcde')],
  1796. dtype=[('f0', '|S12'), ('f1', float), ('f2', '|S8')])
  1797. assert_equal(mtest, ctrl)
  1798. with warnings.catch_warnings(record=True) as w:
  1799. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1800. mtest = np.genfromtxt(TextIO(data), autostrip=True, **kwargs)
  1801. assert_(w[0].category is np.VisibleDeprecationWarning)
  1802. ctrl = np.array([('01/01/2003', 1.3, 'abcde')],
  1803. dtype=[('f0', '|S10'), ('f1', float), ('f2', '|S5')])
  1804. assert_equal(mtest, ctrl)
  1805. def test_replace_space(self):
  1806. # Test the 'replace_space' option
  1807. txt = "A.A, B (B), C:C\n1, 2, 3.14"
  1808. # Test default: replace ' ' by '_' and delete non-alphanum chars
  1809. test = np.genfromtxt(TextIO(txt),
  1810. delimiter=",", names=True, dtype=None)
  1811. ctrl_dtype = [("AA", int), ("B_B", int), ("CC", float)]
  1812. ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype)
  1813. assert_equal(test, ctrl)
  1814. # Test: no replace, no delete
  1815. test = np.genfromtxt(TextIO(txt),
  1816. delimiter=",", names=True, dtype=None,
  1817. replace_space='', deletechars='')
  1818. ctrl_dtype = [("A.A", int), ("B (B)", int), ("C:C", float)]
  1819. ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype)
  1820. assert_equal(test, ctrl)
  1821. # Test: no delete (spaces are replaced by _)
  1822. test = np.genfromtxt(TextIO(txt),
  1823. delimiter=",", names=True, dtype=None,
  1824. deletechars='')
  1825. ctrl_dtype = [("A.A", int), ("B_(B)", int), ("C:C", float)]
  1826. ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype)
  1827. assert_equal(test, ctrl)
  1828. def test_replace_space_known_dtype(self):
  1829. # Test the 'replace_space' (and related) options when dtype != None
  1830. txt = "A.A, B (B), C:C\n1, 2, 3"
  1831. # Test default: replace ' ' by '_' and delete non-alphanum chars
  1832. test = np.genfromtxt(TextIO(txt),
  1833. delimiter=",", names=True, dtype=int)
  1834. ctrl_dtype = [("AA", int), ("B_B", int), ("CC", int)]
  1835. ctrl = np.array((1, 2, 3), dtype=ctrl_dtype)
  1836. assert_equal(test, ctrl)
  1837. # Test: no replace, no delete
  1838. test = np.genfromtxt(TextIO(txt),
  1839. delimiter=",", names=True, dtype=int,
  1840. replace_space='', deletechars='')
  1841. ctrl_dtype = [("A.A", int), ("B (B)", int), ("C:C", int)]
  1842. ctrl = np.array((1, 2, 3), dtype=ctrl_dtype)
  1843. assert_equal(test, ctrl)
  1844. # Test: no delete (spaces are replaced by _)
  1845. test = np.genfromtxt(TextIO(txt),
  1846. delimiter=",", names=True, dtype=int,
  1847. deletechars='')
  1848. ctrl_dtype = [("A.A", int), ("B_(B)", int), ("C:C", int)]
  1849. ctrl = np.array((1, 2, 3), dtype=ctrl_dtype)
  1850. assert_equal(test, ctrl)
  1851. def test_incomplete_names(self):
  1852. # Test w/ incomplete names
  1853. data = "A,,C\n0,1,2\n3,4,5"
  1854. kwargs = dict(delimiter=",", names=True)
  1855. # w/ dtype=None
  1856. ctrl = np.array([(0, 1, 2), (3, 4, 5)],
  1857. dtype=[(_, int) for _ in ('A', 'f0', 'C')])
  1858. test = np.genfromtxt(TextIO(data), dtype=None, **kwargs)
  1859. assert_equal(test, ctrl)
  1860. # w/ default dtype
  1861. ctrl = np.array([(0, 1, 2), (3, 4, 5)],
  1862. dtype=[(_, float) for _ in ('A', 'f0', 'C')])
  1863. test = np.genfromtxt(TextIO(data), **kwargs)
  1864. def test_names_auto_completion(self):
  1865. # Make sure that names are properly completed
  1866. data = "1 2 3\n 4 5 6"
  1867. test = np.genfromtxt(TextIO(data),
  1868. dtype=(int, float, int), names="a")
  1869. ctrl = np.array([(1, 2, 3), (4, 5, 6)],
  1870. dtype=[('a', int), ('f0', float), ('f1', int)])
  1871. assert_equal(test, ctrl)
  1872. def test_names_with_usecols_bug1636(self):
  1873. # Make sure we pick up the right names w/ usecols
  1874. data = "A,B,C,D,E\n0,1,2,3,4\n0,1,2,3,4\n0,1,2,3,4"
  1875. ctrl_names = ("A", "C", "E")
  1876. test = np.genfromtxt(TextIO(data),
  1877. dtype=(int, int, int), delimiter=",",
  1878. usecols=(0, 2, 4), names=True)
  1879. assert_equal(test.dtype.names, ctrl_names)
  1880. #
  1881. test = np.genfromtxt(TextIO(data),
  1882. dtype=(int, int, int), delimiter=",",
  1883. usecols=("A", "C", "E"), names=True)
  1884. assert_equal(test.dtype.names, ctrl_names)
  1885. #
  1886. test = np.genfromtxt(TextIO(data),
  1887. dtype=int, delimiter=",",
  1888. usecols=("A", "C", "E"), names=True)
  1889. assert_equal(test.dtype.names, ctrl_names)
  1890. def test_fixed_width_names(self):
  1891. # Test fix-width w/ names
  1892. data = " A B C\n 0 1 2.3\n 45 67 9."
  1893. kwargs = dict(delimiter=(5, 5, 4), names=True, dtype=None)
  1894. ctrl = np.array([(0, 1, 2.3), (45, 67, 9.)],
  1895. dtype=[('A', int), ('B', int), ('C', float)])
  1896. test = np.genfromtxt(TextIO(data), **kwargs)
  1897. assert_equal(test, ctrl)
  1898. #
  1899. kwargs = dict(delimiter=5, names=True, dtype=None)
  1900. ctrl = np.array([(0, 1, 2.3), (45, 67, 9.)],
  1901. dtype=[('A', int), ('B', int), ('C', float)])
  1902. test = np.genfromtxt(TextIO(data), **kwargs)
  1903. assert_equal(test, ctrl)
  1904. def test_filling_values(self):
  1905. # Test missing values
  1906. data = b"1, 2, 3\n1, , 5\n0, 6, \n"
  1907. kwargs = dict(delimiter=",", dtype=None, filling_values=-999)
  1908. ctrl = np.array([[1, 2, 3], [1, -999, 5], [0, 6, -999]], dtype=int)
  1909. test = np.genfromtxt(TextIO(data), **kwargs)
  1910. assert_equal(test, ctrl)
  1911. def test_comments_is_none(self):
  1912. # Github issue 329 (None was previously being converted to 'None').
  1913. with warnings.catch_warnings(record=True) as w:
  1914. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1915. test = np.genfromtxt(TextIO("test1,testNonetherestofthedata"),
  1916. dtype=None, comments=None, delimiter=',')
  1917. assert_(w[0].category is np.VisibleDeprecationWarning)
  1918. assert_equal(test[1], b'testNonetherestofthedata')
  1919. with warnings.catch_warnings(record=True) as w:
  1920. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1921. test = np.genfromtxt(TextIO("test1, testNonetherestofthedata"),
  1922. dtype=None, comments=None, delimiter=',')
  1923. assert_(w[0].category is np.VisibleDeprecationWarning)
  1924. assert_equal(test[1], b' testNonetherestofthedata')
  1925. def test_latin1(self):
  1926. latin1 = b'\xf6\xfc\xf6'
  1927. norm = b"norm1,norm2,norm3\n"
  1928. enc = b"test1,testNonethe" + latin1 + b",test3\n"
  1929. s = norm + enc + norm
  1930. with warnings.catch_warnings(record=True) as w:
  1931. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1932. test = np.genfromtxt(TextIO(s),
  1933. dtype=None, comments=None, delimiter=',')
  1934. assert_(w[0].category is np.VisibleDeprecationWarning)
  1935. assert_equal(test[1, 0], b"test1")
  1936. assert_equal(test[1, 1], b"testNonethe" + latin1)
  1937. assert_equal(test[1, 2], b"test3")
  1938. test = np.genfromtxt(TextIO(s),
  1939. dtype=None, comments=None, delimiter=',',
  1940. encoding='latin1')
  1941. assert_equal(test[1, 0], "test1")
  1942. assert_equal(test[1, 1], "testNonethe" + latin1.decode('latin1'))
  1943. assert_equal(test[1, 2], "test3")
  1944. with warnings.catch_warnings(record=True) as w:
  1945. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1946. test = np.genfromtxt(TextIO(b"0,testNonethe" + latin1),
  1947. dtype=None, comments=None, delimiter=',')
  1948. assert_(w[0].category is np.VisibleDeprecationWarning)
  1949. assert_equal(test['f0'], 0)
  1950. assert_equal(test['f1'], b"testNonethe" + latin1)
  1951. def test_binary_decode_autodtype(self):
  1952. utf16 = b'\xff\xfeh\x04 \x00i\x04 \x00j\x04'
  1953. v = self.loadfunc(BytesIO(utf16), dtype=None, encoding='UTF-16')
  1954. assert_array_equal(v, np.array(utf16.decode('UTF-16').split()))
  1955. def test_utf8_byte_encoding(self):
  1956. utf8 = b"\xcf\x96"
  1957. norm = b"norm1,norm2,norm3\n"
  1958. enc = b"test1,testNonethe" + utf8 + b",test3\n"
  1959. s = norm + enc + norm
  1960. with warnings.catch_warnings(record=True) as w:
  1961. warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
  1962. test = np.genfromtxt(TextIO(s),
  1963. dtype=None, comments=None, delimiter=',')
  1964. assert_(w[0].category is np.VisibleDeprecationWarning)
  1965. ctl = np.array([
  1966. [b'norm1', b'norm2', b'norm3'],
  1967. [b'test1', b'testNonethe' + utf8, b'test3'],
  1968. [b'norm1', b'norm2', b'norm3']])
  1969. assert_array_equal(test, ctl)
  1970. def test_utf8_file(self):
  1971. utf8 = b"\xcf\x96"
  1972. with temppath() as path:
  1973. with open(path, "wb") as f:
  1974. f.write((b"test1,testNonethe" + utf8 + b",test3\n") * 2)
  1975. test = np.genfromtxt(path, dtype=None, comments=None,
  1976. delimiter=',', encoding="UTF-8")
  1977. ctl = np.array([
  1978. ["test1", "testNonethe" + utf8.decode("UTF-8"), "test3"],
  1979. ["test1", "testNonethe" + utf8.decode("UTF-8"), "test3"]],
  1980. dtype=np.unicode_)
  1981. assert_array_equal(test, ctl)
  1982. # test a mixed dtype
  1983. with open(path, "wb") as f:
  1984. f.write(b"0,testNonethe" + utf8)
  1985. test = np.genfromtxt(path, dtype=None, comments=None,
  1986. delimiter=',', encoding="UTF-8")
  1987. assert_equal(test['f0'], 0)
  1988. assert_equal(test['f1'], "testNonethe" + utf8.decode("UTF-8"))
  1989. def test_utf8_file_nodtype_unicode(self):
  1990. # bytes encoding with non-latin1 -> unicode upcast
  1991. utf8 = '\u03d6'
  1992. latin1 = '\xf6\xfc\xf6'
  1993. # skip test if cannot encode utf8 test string with preferred
  1994. # encoding. The preferred encoding is assumed to be the default
  1995. # encoding of io.open. Will need to change this for PyTest, maybe
  1996. # using pytest.mark.xfail(raises=***).
  1997. try:
  1998. encoding = locale.getpreferredencoding()
  1999. utf8.encode(encoding)
  2000. except (UnicodeError, ImportError):
  2001. pytest.skip('Skipping test_utf8_file_nodtype_unicode, '
  2002. 'unable to encode utf8 in preferred encoding')
  2003. with temppath() as path:
  2004. with io.open(path, "wt") as f:
  2005. f.write("norm1,norm2,norm3\n")
  2006. f.write("norm1," + latin1 + ",norm3\n")
  2007. f.write("test1,testNonethe" + utf8 + ",test3\n")
  2008. with warnings.catch_warnings(record=True) as w:
  2009. warnings.filterwarnings('always', '',
  2010. np.VisibleDeprecationWarning)
  2011. test = np.genfromtxt(path, dtype=None, comments=None,
  2012. delimiter=',')
  2013. # Check for warning when encoding not specified.
  2014. assert_(w[0].category is np.VisibleDeprecationWarning)
  2015. ctl = np.array([
  2016. ["norm1", "norm2", "norm3"],
  2017. ["norm1", latin1, "norm3"],
  2018. ["test1", "testNonethe" + utf8, "test3"]],
  2019. dtype=np.unicode_)
  2020. assert_array_equal(test, ctl)
  2021. def test_recfromtxt(self):
  2022. #
  2023. data = TextIO('A,B\n0,1\n2,3')
  2024. kwargs = dict(delimiter=",", missing_values="N/A", names=True)
  2025. test = np.recfromtxt(data, **kwargs)
  2026. control = np.array([(0, 1), (2, 3)],
  2027. dtype=[('A', int), ('B', int)])
  2028. assert_(isinstance(test, np.recarray))
  2029. assert_equal(test, control)
  2030. #
  2031. data = TextIO('A,B\n0,1\n2,N/A')
  2032. test = np.recfromtxt(data, dtype=None, usemask=True, **kwargs)
  2033. control = ma.array([(0, 1), (2, -1)],
  2034. mask=[(False, False), (False, True)],
  2035. dtype=[('A', int), ('B', int)])
  2036. assert_equal(test, control)
  2037. assert_equal(test.mask, control.mask)
  2038. assert_equal(test.A, [0, 2])
  2039. def test_recfromcsv(self):
  2040. #
  2041. data = TextIO('A,B\n0,1\n2,3')
  2042. kwargs = dict(missing_values="N/A", names=True, case_sensitive=True)
  2043. test = np.recfromcsv(data, dtype=None, **kwargs)
  2044. control = np.array([(0, 1), (2, 3)],
  2045. dtype=[('A', int), ('B', int)])
  2046. assert_(isinstance(test, np.recarray))
  2047. assert_equal(test, control)
  2048. #
  2049. data = TextIO('A,B\n0,1\n2,N/A')
  2050. test = np.recfromcsv(data, dtype=None, usemask=True, **kwargs)
  2051. control = ma.array([(0, 1), (2, -1)],
  2052. mask=[(False, False), (False, True)],
  2053. dtype=[('A', int), ('B', int)])
  2054. assert_equal(test, control)
  2055. assert_equal(test.mask, control.mask)
  2056. assert_equal(test.A, [0, 2])
  2057. #
  2058. data = TextIO('A,B\n0,1\n2,3')
  2059. test = np.recfromcsv(data, missing_values='N/A',)
  2060. control = np.array([(0, 1), (2, 3)],
  2061. dtype=[('a', int), ('b', int)])
  2062. assert_(isinstance(test, np.recarray))
  2063. assert_equal(test, control)
  2064. #
  2065. data = TextIO('A,B\n0,1\n2,3')
  2066. dtype = [('a', int), ('b', float)]
  2067. test = np.recfromcsv(data, missing_values='N/A', dtype=dtype)
  2068. control = np.array([(0, 1), (2, 3)],
  2069. dtype=dtype)
  2070. assert_(isinstance(test, np.recarray))
  2071. assert_equal(test, control)
  2072. #gh-10394
  2073. data = TextIO('color\n"red"\n"blue"')
  2074. test = np.recfromcsv(data, converters={0: lambda x: x.strip(b'\"')})
  2075. control = np.array([('red',), ('blue',)], dtype=[('color', (bytes, 4))])
  2076. assert_equal(test.dtype, control.dtype)
  2077. assert_equal(test, control)
  2078. def test_max_rows(self):
  2079. # Test the `max_rows` keyword argument.
  2080. data = '1 2\n3 4\n5 6\n7 8\n9 10\n'
  2081. txt = TextIO(data)
  2082. a1 = np.genfromtxt(txt, max_rows=3)
  2083. a2 = np.genfromtxt(txt)
  2084. assert_equal(a1, [[1, 2], [3, 4], [5, 6]])
  2085. assert_equal(a2, [[7, 8], [9, 10]])
  2086. # max_rows must be at least 1.
  2087. assert_raises(ValueError, np.genfromtxt, TextIO(data), max_rows=0)
  2088. # An input with several invalid rows.
  2089. data = '1 1\n2 2\n0 \n3 3\n4 4\n5 \n6 \n7 \n'
  2090. test = np.genfromtxt(TextIO(data), max_rows=2)
  2091. control = np.array([[1., 1.], [2., 2.]])
  2092. assert_equal(test, control)
  2093. # Test keywords conflict
  2094. assert_raises(ValueError, np.genfromtxt, TextIO(data), skip_footer=1,
  2095. max_rows=4)
  2096. # Test with invalid value
  2097. assert_raises(ValueError, np.genfromtxt, TextIO(data), max_rows=4)
  2098. # Test with invalid not raise
  2099. with suppress_warnings() as sup:
  2100. sup.filter(ConversionWarning)
  2101. test = np.genfromtxt(TextIO(data), max_rows=4, invalid_raise=False)
  2102. control = np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])
  2103. assert_equal(test, control)
  2104. test = np.genfromtxt(TextIO(data), max_rows=5, invalid_raise=False)
  2105. control = np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])
  2106. assert_equal(test, control)
  2107. # Structured array with field names.
  2108. data = 'a b\n#c d\n1 1\n2 2\n#0 \n3 3\n4 4\n5 5\n'
  2109. # Test with header, names and comments
  2110. txt = TextIO(data)
  2111. test = np.genfromtxt(txt, skip_header=1, max_rows=3, names=True)
  2112. control = np.array([(1.0, 1.0), (2.0, 2.0), (3.0, 3.0)],
  2113. dtype=[('c', '<f8'), ('d', '<f8')])
  2114. assert_equal(test, control)
  2115. # To continue reading the same "file", don't use skip_header or
  2116. # names, and use the previously determined dtype.
  2117. test = np.genfromtxt(txt, max_rows=None, dtype=test.dtype)
  2118. control = np.array([(4.0, 4.0), (5.0, 5.0)],
  2119. dtype=[('c', '<f8'), ('d', '<f8')])
  2120. assert_equal(test, control)
  2121. def test_gft_using_filename(self):
  2122. # Test that we can load data from a filename as well as a file
  2123. # object
  2124. tgt = np.arange(6).reshape((2, 3))
  2125. linesep = ('\n', '\r\n', '\r')
  2126. for sep in linesep:
  2127. data = '0 1 2' + sep + '3 4 5'
  2128. with temppath() as name:
  2129. with open(name, 'w') as f:
  2130. f.write(data)
  2131. res = np.genfromtxt(name)
  2132. assert_array_equal(res, tgt)
  2133. def test_gft_from_gzip(self):
  2134. # Test that we can load data from a gzipped file
  2135. wanted = np.arange(6).reshape((2, 3))
  2136. linesep = ('\n', '\r\n', '\r')
  2137. for sep in linesep:
  2138. data = '0 1 2' + sep + '3 4 5'
  2139. s = BytesIO()
  2140. with gzip.GzipFile(fileobj=s, mode='w') as g:
  2141. g.write(asbytes(data))
  2142. with temppath(suffix='.gz2') as name:
  2143. with open(name, 'w') as f:
  2144. f.write(data)
  2145. assert_array_equal(np.genfromtxt(name), wanted)
  2146. def test_gft_using_generator(self):
  2147. # gft doesn't work with unicode.
  2148. def count():
  2149. for i in range(10):
  2150. yield asbytes("%d" % i)
  2151. res = np.genfromtxt(count())
  2152. assert_array_equal(res, np.arange(10))
  2153. def test_auto_dtype_largeint(self):
  2154. # Regression test for numpy/numpy#5635 whereby large integers could
  2155. # cause OverflowErrors.
  2156. # Test the automatic definition of the output dtype
  2157. #
  2158. # 2**66 = 73786976294838206464 => should convert to float
  2159. # 2**34 = 17179869184 => should convert to int64
  2160. # 2**10 = 1024 => should convert to int (int32 on 32-bit systems,
  2161. # int64 on 64-bit systems)
  2162. data = TextIO('73786976294838206464 17179869184 1024')
  2163. test = np.genfromtxt(data, dtype=None)
  2164. assert_equal(test.dtype.names, ['f0', 'f1', 'f2'])
  2165. assert_(test.dtype['f0'] == float)
  2166. assert_(test.dtype['f1'] == np.int64)
  2167. assert_(test.dtype['f2'] == np.int_)
  2168. assert_allclose(test['f0'], 73786976294838206464.)
  2169. assert_equal(test['f1'], 17179869184)
  2170. assert_equal(test['f2'], 1024)
  2171. def test_unpack_float_data(self):
  2172. txt = TextIO("1,2,3\n4,5,6\n7,8,9\n0.0,1.0,2.0")
  2173. a, b, c = np.loadtxt(txt, delimiter=",", unpack=True)
  2174. assert_array_equal(a, np.array([1.0, 4.0, 7.0, 0.0]))
  2175. assert_array_equal(b, np.array([2.0, 5.0, 8.0, 1.0]))
  2176. assert_array_equal(c, np.array([3.0, 6.0, 9.0, 2.0]))
  2177. def test_unpack_structured(self):
  2178. # Regression test for gh-4341
  2179. # Unpacking should work on structured arrays
  2180. txt = TextIO("M 21 72\nF 35 58")
  2181. dt = {'names': ('a', 'b', 'c'), 'formats': ('S1', 'i4', 'f4')}
  2182. a, b, c = np.genfromtxt(txt, dtype=dt, unpack=True)
  2183. assert_equal(a.dtype, np.dtype('S1'))
  2184. assert_equal(b.dtype, np.dtype('i4'))
  2185. assert_equal(c.dtype, np.dtype('f4'))
  2186. assert_array_equal(a, np.array([b'M', b'F']))
  2187. assert_array_equal(b, np.array([21, 35]))
  2188. assert_array_equal(c, np.array([72., 58.]))
  2189. def test_unpack_auto_dtype(self):
  2190. # Regression test for gh-4341
  2191. # Unpacking should work when dtype=None
  2192. txt = TextIO("M 21 72.\nF 35 58.")
  2193. expected = (np.array(["M", "F"]), np.array([21, 35]), np.array([72., 58.]))
  2194. test = np.genfromtxt(txt, dtype=None, unpack=True, encoding="utf-8")
  2195. for arr, result in zip(expected, test):
  2196. assert_array_equal(arr, result)
  2197. assert_equal(arr.dtype, result.dtype)
  2198. def test_unpack_single_name(self):
  2199. # Regression test for gh-4341
  2200. # Unpacking should work when structured dtype has only one field
  2201. txt = TextIO("21\n35")
  2202. dt = {'names': ('a',), 'formats': ('i4',)}
  2203. expected = np.array([21, 35], dtype=np.int32)
  2204. test = np.genfromtxt(txt, dtype=dt, unpack=True)
  2205. assert_array_equal(expected, test)
  2206. assert_equal(expected.dtype, test.dtype)
  2207. def test_squeeze_scalar(self):
  2208. # Regression test for gh-4341
  2209. # Unpacking a scalar should give zero-dim output,
  2210. # even if dtype is structured
  2211. txt = TextIO("1")
  2212. dt = {'names': ('a',), 'formats': ('i4',)}
  2213. expected = np.array((1,), dtype=np.int32)
  2214. test = np.genfromtxt(txt, dtype=dt, unpack=True)
  2215. assert_array_equal(expected, test)
  2216. assert_equal((), test.shape)
  2217. assert_equal(expected.dtype, test.dtype)
  2218. @pytest.mark.parametrize("ndim", [0, 1, 2])
  2219. def test_ndmin_keyword(self, ndim: int):
  2220. # lets have the same behaviour of ndmin as loadtxt
  2221. # as they should be the same for non-missing values
  2222. txt = "42"
  2223. a = np.loadtxt(StringIO(txt), ndmin=ndim)
  2224. b = np.genfromtxt(StringIO(txt), ndmin=ndim)
  2225. assert_array_equal(a, b)
  2226. class TestPathUsage:
  2227. # Test that pathlib.Path can be used
  2228. def test_loadtxt(self):
  2229. with temppath(suffix='.txt') as path:
  2230. path = Path(path)
  2231. a = np.array([[1.1, 2], [3, 4]])
  2232. np.savetxt(path, a)
  2233. x = np.loadtxt(path)
  2234. assert_array_equal(x, a)
  2235. def test_save_load(self):
  2236. # Test that pathlib.Path instances can be used with save.
  2237. with temppath(suffix='.npy') as path:
  2238. path = Path(path)
  2239. a = np.array([[1, 2], [3, 4]], int)
  2240. np.save(path, a)
  2241. data = np.load(path)
  2242. assert_array_equal(data, a)
  2243. def test_save_load_memmap(self):
  2244. # Test that pathlib.Path instances can be loaded mem-mapped.
  2245. with temppath(suffix='.npy') as path:
  2246. path = Path(path)
  2247. a = np.array([[1, 2], [3, 4]], int)
  2248. np.save(path, a)
  2249. data = np.load(path, mmap_mode='r')
  2250. assert_array_equal(data, a)
  2251. # close the mem-mapped file
  2252. del data
  2253. if IS_PYPY:
  2254. break_cycles()
  2255. break_cycles()
  2256. @pytest.mark.xfail(IS_WASM, reason="memmap doesn't work correctly")
  2257. def test_save_load_memmap_readwrite(self):
  2258. # Test that pathlib.Path instances can be written mem-mapped.
  2259. with temppath(suffix='.npy') as path:
  2260. path = Path(path)
  2261. a = np.array([[1, 2], [3, 4]], int)
  2262. np.save(path, a)
  2263. b = np.load(path, mmap_mode='r+')
  2264. a[0][0] = 5
  2265. b[0][0] = 5
  2266. del b # closes the file
  2267. if IS_PYPY:
  2268. break_cycles()
  2269. break_cycles()
  2270. data = np.load(path)
  2271. assert_array_equal(data, a)
  2272. def test_savez_load(self):
  2273. # Test that pathlib.Path instances can be used with savez.
  2274. with temppath(suffix='.npz') as path:
  2275. path = Path(path)
  2276. np.savez(path, lab='place holder')
  2277. with np.load(path) as data:
  2278. assert_array_equal(data['lab'], 'place holder')
  2279. def test_savez_compressed_load(self):
  2280. # Test that pathlib.Path instances can be used with savez.
  2281. with temppath(suffix='.npz') as path:
  2282. path = Path(path)
  2283. np.savez_compressed(path, lab='place holder')
  2284. data = np.load(path)
  2285. assert_array_equal(data['lab'], 'place holder')
  2286. data.close()
  2287. def test_genfromtxt(self):
  2288. with temppath(suffix='.txt') as path:
  2289. path = Path(path)
  2290. a = np.array([(1, 2), (3, 4)])
  2291. np.savetxt(path, a)
  2292. data = np.genfromtxt(path)
  2293. assert_array_equal(a, data)
  2294. def test_recfromtxt(self):
  2295. with temppath(suffix='.txt') as path:
  2296. path = Path(path)
  2297. with path.open('w') as f:
  2298. f.write('A,B\n0,1\n2,3')
  2299. kwargs = dict(delimiter=",", missing_values="N/A", names=True)
  2300. test = np.recfromtxt(path, **kwargs)
  2301. control = np.array([(0, 1), (2, 3)],
  2302. dtype=[('A', int), ('B', int)])
  2303. assert_(isinstance(test, np.recarray))
  2304. assert_equal(test, control)
  2305. def test_recfromcsv(self):
  2306. with temppath(suffix='.txt') as path:
  2307. path = Path(path)
  2308. with path.open('w') as f:
  2309. f.write('A,B\n0,1\n2,3')
  2310. kwargs = dict(missing_values="N/A", names=True, case_sensitive=True)
  2311. test = np.recfromcsv(path, dtype=None, **kwargs)
  2312. control = np.array([(0, 1), (2, 3)],
  2313. dtype=[('A', int), ('B', int)])
  2314. assert_(isinstance(test, np.recarray))
  2315. assert_equal(test, control)
  2316. def test_gzip_load():
  2317. a = np.random.random((5, 5))
  2318. s = BytesIO()
  2319. f = gzip.GzipFile(fileobj=s, mode="w")
  2320. np.save(f, a)
  2321. f.close()
  2322. s.seek(0)
  2323. f = gzip.GzipFile(fileobj=s, mode="r")
  2324. assert_array_equal(np.load(f), a)
  2325. # These next two classes encode the minimal API needed to save()/load() arrays.
  2326. # The `test_ducktyping` ensures they work correctly
  2327. class JustWriter:
  2328. def __init__(self, base):
  2329. self.base = base
  2330. def write(self, s):
  2331. return self.base.write(s)
  2332. def flush(self):
  2333. return self.base.flush()
  2334. class JustReader:
  2335. def __init__(self, base):
  2336. self.base = base
  2337. def read(self, n):
  2338. return self.base.read(n)
  2339. def seek(self, off, whence=0):
  2340. return self.base.seek(off, whence)
  2341. def test_ducktyping():
  2342. a = np.random.random((5, 5))
  2343. s = BytesIO()
  2344. f = JustWriter(s)
  2345. np.save(f, a)
  2346. f.flush()
  2347. s.seek(0)
  2348. f = JustReader(s)
  2349. assert_array_equal(np.load(f), a)
  2350. def test_gzip_loadtxt():
  2351. # Thanks to another windows brokenness, we can't use
  2352. # NamedTemporaryFile: a file created from this function cannot be
  2353. # reopened by another open call. So we first put the gzipped string
  2354. # of the test reference array, write it to a securely opened file,
  2355. # which is then read from by the loadtxt function
  2356. s = BytesIO()
  2357. g = gzip.GzipFile(fileobj=s, mode='w')
  2358. g.write(b'1 2 3\n')
  2359. g.close()
  2360. s.seek(0)
  2361. with temppath(suffix='.gz') as name:
  2362. with open(name, 'wb') as f:
  2363. f.write(s.read())
  2364. res = np.loadtxt(name)
  2365. s.close()
  2366. assert_array_equal(res, [1, 2, 3])
  2367. def test_gzip_loadtxt_from_string():
  2368. s = BytesIO()
  2369. f = gzip.GzipFile(fileobj=s, mode="w")
  2370. f.write(b'1 2 3\n')
  2371. f.close()
  2372. s.seek(0)
  2373. f = gzip.GzipFile(fileobj=s, mode="r")
  2374. assert_array_equal(np.loadtxt(f), [1, 2, 3])
  2375. def test_npzfile_dict():
  2376. s = BytesIO()
  2377. x = np.zeros((3, 3))
  2378. y = np.zeros((3, 3))
  2379. np.savez(s, x=x, y=y)
  2380. s.seek(0)
  2381. z = np.load(s)
  2382. assert_('x' in z)
  2383. assert_('y' in z)
  2384. assert_('x' in z.keys())
  2385. assert_('y' in z.keys())
  2386. for f, a in z.items():
  2387. assert_(f in ['x', 'y'])
  2388. assert_equal(a.shape, (3, 3))
  2389. assert_(len(z.items()) == 2)
  2390. for f in z:
  2391. assert_(f in ['x', 'y'])
  2392. assert_('x' in z.keys())
  2393. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  2394. def test_load_refcount():
  2395. # Check that objects returned by np.load are directly freed based on
  2396. # their refcount, rather than needing the gc to collect them.
  2397. f = BytesIO()
  2398. np.savez(f, [1, 2, 3])
  2399. f.seek(0)
  2400. with assert_no_gc_cycles():
  2401. np.load(f)
  2402. f.seek(0)
  2403. dt = [("a", 'u1', 2), ("b", 'u1', 2)]
  2404. with assert_no_gc_cycles():
  2405. x = np.loadtxt(TextIO("0 1 2 3"), dtype=dt)
  2406. assert_equal(x, np.array([((0, 1), (2, 3))], dtype=dt))