test_io.py 101 KB

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