test_regression.py 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558
  1. import copy
  2. import sys
  3. import gc
  4. import tempfile
  5. import pytest
  6. from os import path
  7. from io import BytesIO
  8. from itertools import chain
  9. import numpy as np
  10. from numpy.testing import (
  11. assert_, assert_equal, IS_PYPY, assert_almost_equal,
  12. assert_array_equal, assert_array_almost_equal, assert_raises,
  13. assert_raises_regex, assert_warns, suppress_warnings,
  14. _assert_valid_refcount, HAS_REFCOUNT, IS_PYSTON, IS_WASM
  15. )
  16. from numpy.testing._private.utils import _no_tracing, requires_memory
  17. from numpy.compat import asbytes, asunicode, pickle
  18. class TestRegression:
  19. def test_invalid_round(self):
  20. # Ticket #3
  21. v = 4.7599999999999998
  22. assert_array_equal(np.array([v]), np.array(v))
  23. def test_mem_empty(self):
  24. # Ticket #7
  25. np.empty((1,), dtype=[('x', np.int64)])
  26. def test_pickle_transposed(self):
  27. # Ticket #16
  28. a = np.transpose(np.array([[2, 9], [7, 0], [3, 8]]))
  29. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  30. with BytesIO() as f:
  31. pickle.dump(a, f, protocol=proto)
  32. f.seek(0)
  33. b = pickle.load(f)
  34. assert_array_equal(a, b)
  35. def test_dtype_names(self):
  36. # Ticket #35
  37. # Should succeed
  38. np.dtype([(('name', 'label'), np.int32, 3)])
  39. def test_reduce(self):
  40. # Ticket #40
  41. assert_almost_equal(np.add.reduce([1., .5], dtype=None), 1.5)
  42. def test_zeros_order(self):
  43. # Ticket #43
  44. np.zeros([3], int, 'C')
  45. np.zeros([3], order='C')
  46. np.zeros([3], int, order='C')
  47. def test_asarray_with_order(self):
  48. # Check that nothing is done when order='F' and array C/F-contiguous
  49. a = np.ones(2)
  50. assert_(a is np.asarray(a, order='F'))
  51. def test_ravel_with_order(self):
  52. # Check that ravel works when order='F' and array C/F-contiguous
  53. a = np.ones(2)
  54. assert_(not a.ravel('F').flags.owndata)
  55. def test_sort_bigendian(self):
  56. # Ticket #47
  57. a = np.linspace(0, 10, 11)
  58. c = a.astype(np.dtype('<f8'))
  59. c.sort()
  60. assert_array_almost_equal(c, a)
  61. def test_negative_nd_indexing(self):
  62. # Ticket #49
  63. c = np.arange(125).reshape((5, 5, 5))
  64. origidx = np.array([-1, 0, 1])
  65. idx = np.array(origidx)
  66. c[idx]
  67. assert_array_equal(idx, origidx)
  68. def test_char_dump(self):
  69. # Ticket #50
  70. ca = np.char.array(np.arange(1000, 1010), itemsize=4)
  71. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  72. with BytesIO() as f:
  73. pickle.dump(ca, f, protocol=proto)
  74. f.seek(0)
  75. ca = np.load(f, allow_pickle=True)
  76. def test_noncontiguous_fill(self):
  77. # Ticket #58.
  78. a = np.zeros((5, 3))
  79. b = a[:, :2,]
  80. def rs():
  81. b.shape = (10,)
  82. assert_raises(AttributeError, rs)
  83. def test_bool(self):
  84. # Ticket #60
  85. np.bool_(1) # Should succeed
  86. def test_indexing1(self):
  87. # Ticket #64
  88. descr = [('x', [('y', [('z', 'c16', (2,)),]),]),]
  89. buffer = ((([6j, 4j],),),)
  90. h = np.array(buffer, dtype=descr)
  91. h['x']['y']['z']
  92. def test_indexing2(self):
  93. # Ticket #65
  94. descr = [('x', 'i4', (2,))]
  95. buffer = ([3, 2],)
  96. h = np.array(buffer, dtype=descr)
  97. h['x']
  98. def test_round(self):
  99. # Ticket #67
  100. x = np.array([1+2j])
  101. assert_almost_equal(x**(-1), [1/(1+2j)])
  102. def test_scalar_compare(self):
  103. # Trac Ticket #72
  104. # https://github.com/numpy/numpy/issues/565
  105. a = np.array(['test', 'auto'])
  106. assert_array_equal(a == 'auto', np.array([False, True]))
  107. assert_(a[1] == 'auto')
  108. assert_(a[0] != 'auto')
  109. b = np.linspace(0, 10, 11)
  110. # This should return true for now, but will eventually raise an error:
  111. with suppress_warnings() as sup:
  112. sup.filter(FutureWarning)
  113. assert_(b != 'auto')
  114. assert_(b[0] != 'auto')
  115. def test_unicode_swapping(self):
  116. # Ticket #79
  117. ulen = 1
  118. ucs_value = '\U0010FFFF'
  119. ua = np.array([[[ucs_value*ulen]*2]*3]*4, dtype='U%s' % ulen)
  120. ua.newbyteorder() # Should succeed.
  121. def test_object_array_fill(self):
  122. # Ticket #86
  123. x = np.zeros(1, 'O')
  124. x.fill([])
  125. def test_mem_dtype_align(self):
  126. # Ticket #93
  127. assert_raises(TypeError, np.dtype,
  128. {'names':['a'], 'formats':['foo']}, align=1)
  129. def test_endian_bool_indexing(self):
  130. # Ticket #105
  131. a = np.arange(10., dtype='>f8')
  132. b = np.arange(10., dtype='<f8')
  133. xa = np.where((a > 2) & (a < 6))
  134. xb = np.where((b > 2) & (b < 6))
  135. ya = ((a > 2) & (a < 6))
  136. yb = ((b > 2) & (b < 6))
  137. assert_array_almost_equal(xa, ya.nonzero())
  138. assert_array_almost_equal(xb, yb.nonzero())
  139. assert_(np.all(a[ya] > 0.5))
  140. assert_(np.all(b[yb] > 0.5))
  141. def test_endian_where(self):
  142. # GitHub issue #369
  143. net = np.zeros(3, dtype='>f4')
  144. net[1] = 0.00458849
  145. net[2] = 0.605202
  146. max_net = net.max()
  147. test = np.where(net <= 0., max_net, net)
  148. correct = np.array([ 0.60520202, 0.00458849, 0.60520202])
  149. assert_array_almost_equal(test, correct)
  150. def test_endian_recarray(self):
  151. # Ticket #2185
  152. dt = np.dtype([
  153. ('head', '>u4'),
  154. ('data', '>u4', 2),
  155. ])
  156. buf = np.recarray(1, dtype=dt)
  157. buf[0]['head'] = 1
  158. buf[0]['data'][:] = [1, 1]
  159. h = buf[0]['head']
  160. d = buf[0]['data'][0]
  161. buf[0]['head'] = h
  162. buf[0]['data'][0] = d
  163. assert_(buf[0]['head'] == 1)
  164. def test_mem_dot(self):
  165. # Ticket #106
  166. x = np.random.randn(0, 1)
  167. y = np.random.randn(10, 1)
  168. # Dummy array to detect bad memory access:
  169. _z = np.ones(10)
  170. _dummy = np.empty((0, 10))
  171. z = np.lib.stride_tricks.as_strided(_z, _dummy.shape, _dummy.strides)
  172. np.dot(x, np.transpose(y), out=z)
  173. assert_equal(_z, np.ones(10))
  174. # Do the same for the built-in dot:
  175. np.core.multiarray.dot(x, np.transpose(y), out=z)
  176. assert_equal(_z, np.ones(10))
  177. def test_arange_endian(self):
  178. # Ticket #111
  179. ref = np.arange(10)
  180. x = np.arange(10, dtype='<f8')
  181. assert_array_equal(ref, x)
  182. x = np.arange(10, dtype='>f8')
  183. assert_array_equal(ref, x)
  184. def test_arange_inf_step(self):
  185. ref = np.arange(0, 1, 10)
  186. x = np.arange(0, 1, np.inf)
  187. assert_array_equal(ref, x)
  188. ref = np.arange(0, 1, -10)
  189. x = np.arange(0, 1, -np.inf)
  190. assert_array_equal(ref, x)
  191. ref = np.arange(0, -1, -10)
  192. x = np.arange(0, -1, -np.inf)
  193. assert_array_equal(ref, x)
  194. ref = np.arange(0, -1, 10)
  195. x = np.arange(0, -1, np.inf)
  196. assert_array_equal(ref, x)
  197. def test_arange_underflow_stop_and_step(self):
  198. finfo = np.finfo(np.float64)
  199. ref = np.arange(0, finfo.eps, 2 * finfo.eps)
  200. x = np.arange(0, finfo.eps, finfo.max)
  201. assert_array_equal(ref, x)
  202. ref = np.arange(0, finfo.eps, -2 * finfo.eps)
  203. x = np.arange(0, finfo.eps, -finfo.max)
  204. assert_array_equal(ref, x)
  205. ref = np.arange(0, -finfo.eps, -2 * finfo.eps)
  206. x = np.arange(0, -finfo.eps, -finfo.max)
  207. assert_array_equal(ref, x)
  208. ref = np.arange(0, -finfo.eps, 2 * finfo.eps)
  209. x = np.arange(0, -finfo.eps, finfo.max)
  210. assert_array_equal(ref, x)
  211. def test_argmax(self):
  212. # Ticket #119
  213. a = np.random.normal(0, 1, (4, 5, 6, 7, 8))
  214. for i in range(a.ndim):
  215. a.argmax(i) # Should succeed
  216. def test_mem_divmod(self):
  217. # Ticket #126
  218. for i in range(10):
  219. divmod(np.array([i])[0], 10)
  220. def test_hstack_invalid_dims(self):
  221. # Ticket #128
  222. x = np.arange(9).reshape((3, 3))
  223. y = np.array([0, 0, 0])
  224. assert_raises(ValueError, np.hstack, (x, y))
  225. def test_squeeze_type(self):
  226. # Ticket #133
  227. a = np.array([3])
  228. b = np.array(3)
  229. assert_(type(a.squeeze()) is np.ndarray)
  230. assert_(type(b.squeeze()) is np.ndarray)
  231. def test_add_identity(self):
  232. # Ticket #143
  233. assert_equal(0, np.add.identity)
  234. def test_numpy_float_python_long_addition(self):
  235. # Check that numpy float and python longs can be added correctly.
  236. a = np.float_(23.) + 2**135
  237. assert_equal(a, 23. + 2**135)
  238. def test_binary_repr_0(self):
  239. # Ticket #151
  240. assert_equal('0', np.binary_repr(0))
  241. def test_rec_iterate(self):
  242. # Ticket #160
  243. descr = np.dtype([('i', int), ('f', float), ('s', '|S3')])
  244. x = np.rec.array([(1, 1.1, '1.0'),
  245. (2, 2.2, '2.0')], dtype=descr)
  246. x[0].tolist()
  247. [i for i in x[0]]
  248. def test_unicode_string_comparison(self):
  249. # Ticket #190
  250. a = np.array('hello', np.unicode_)
  251. b = np.array('world')
  252. a == b
  253. def test_tobytes_FORTRANORDER_discontiguous(self):
  254. # Fix in r2836
  255. # Create non-contiguous Fortran ordered array
  256. x = np.array(np.random.rand(3, 3), order='F')[:, :2]
  257. assert_array_almost_equal(x.ravel(), np.frombuffer(x.tobytes()))
  258. def test_flat_assignment(self):
  259. # Correct behaviour of ticket #194
  260. x = np.empty((3, 1))
  261. x.flat = np.arange(3)
  262. assert_array_almost_equal(x, [[0], [1], [2]])
  263. x.flat = np.arange(3, dtype=float)
  264. assert_array_almost_equal(x, [[0], [1], [2]])
  265. def test_broadcast_flat_assignment(self):
  266. # Ticket #194
  267. x = np.empty((3, 1))
  268. def bfa():
  269. x[:] = np.arange(3)
  270. def bfb():
  271. x[:] = np.arange(3, dtype=float)
  272. assert_raises(ValueError, bfa)
  273. assert_raises(ValueError, bfb)
  274. @pytest.mark.xfail(IS_WASM, reason="not sure why")
  275. @pytest.mark.parametrize("index",
  276. [np.ones(10, dtype=bool), np.arange(10)],
  277. ids=["boolean-arr-index", "integer-arr-index"])
  278. def test_nonarray_assignment(self, index):
  279. # See also Issue gh-2870, test for non-array assignment
  280. # and equivalent unsafe casted array assignment
  281. a = np.arange(10)
  282. with pytest.raises(ValueError):
  283. a[index] = np.nan
  284. with np.errstate(invalid="warn"):
  285. with pytest.warns(RuntimeWarning, match="invalid value"):
  286. a[index] = np.array(np.nan) # Only warns
  287. def test_unpickle_dtype_with_object(self):
  288. # Implemented in r2840
  289. dt = np.dtype([('x', int), ('y', np.object_), ('z', 'O')])
  290. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  291. with BytesIO() as f:
  292. pickle.dump(dt, f, protocol=proto)
  293. f.seek(0)
  294. dt_ = pickle.load(f)
  295. assert_equal(dt, dt_)
  296. def test_mem_array_creation_invalid_specification(self):
  297. # Ticket #196
  298. dt = np.dtype([('x', int), ('y', np.object_)])
  299. # Wrong way
  300. assert_raises(ValueError, np.array, [1, 'object'], dt)
  301. # Correct way
  302. np.array([(1, 'object')], dt)
  303. def test_recarray_single_element(self):
  304. # Ticket #202
  305. a = np.array([1, 2, 3], dtype=np.int32)
  306. b = a.copy()
  307. r = np.rec.array(a, shape=1, formats=['3i4'], names=['d'])
  308. assert_array_equal(a, b)
  309. assert_equal(a, r[0][0])
  310. def test_zero_sized_array_indexing(self):
  311. # Ticket #205
  312. tmp = np.array([])
  313. def index_tmp():
  314. tmp[np.array(10)]
  315. assert_raises(IndexError, index_tmp)
  316. def test_chararray_rstrip(self):
  317. # Ticket #222
  318. x = np.chararray((1,), 5)
  319. x[0] = b'a '
  320. x = x.rstrip()
  321. assert_equal(x[0], b'a')
  322. def test_object_array_shape(self):
  323. # Ticket #239
  324. assert_equal(np.array([[1, 2], 3, 4], dtype=object).shape, (3,))
  325. assert_equal(np.array([[1, 2], [3, 4]], dtype=object).shape, (2, 2))
  326. assert_equal(np.array([(1, 2), (3, 4)], dtype=object).shape, (2, 2))
  327. assert_equal(np.array([], dtype=object).shape, (0,))
  328. assert_equal(np.array([[], [], []], dtype=object).shape, (3, 0))
  329. assert_equal(np.array([[3, 4], [5, 6], None], dtype=object).shape, (3,))
  330. def test_mem_around(self):
  331. # Ticket #243
  332. x = np.zeros((1,))
  333. y = [0]
  334. decimal = 6
  335. np.around(abs(x-y), decimal) <= 10.0**(-decimal)
  336. def test_character_array_strip(self):
  337. # Ticket #246
  338. x = np.char.array(("x", "x ", "x "))
  339. for c in x:
  340. assert_equal(c, "x")
  341. def test_lexsort(self):
  342. # Lexsort memory error
  343. v = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
  344. assert_equal(np.lexsort(v), 0)
  345. def test_lexsort_invalid_sequence(self):
  346. # Issue gh-4123
  347. class BuggySequence:
  348. def __len__(self):
  349. return 4
  350. def __getitem__(self, key):
  351. raise KeyError
  352. assert_raises(KeyError, np.lexsort, BuggySequence())
  353. def test_lexsort_zerolen_custom_strides(self):
  354. # Ticket #14228
  355. xs = np.array([], dtype='i8')
  356. assert np.lexsort((xs,)).shape[0] == 0 # Works
  357. xs.strides = (16,)
  358. assert np.lexsort((xs,)).shape[0] == 0 # Was: MemoryError
  359. def test_lexsort_zerolen_custom_strides_2d(self):
  360. xs = np.array([], dtype='i8')
  361. xs.shape = (0, 2)
  362. xs.strides = (16, 16)
  363. assert np.lexsort((xs,), axis=0).shape[0] == 0
  364. xs.shape = (2, 0)
  365. xs.strides = (16, 16)
  366. assert np.lexsort((xs,), axis=0).shape[0] == 2
  367. def test_lexsort_invalid_axis(self):
  368. assert_raises(np.AxisError, np.lexsort, (np.arange(1),), axis=2)
  369. assert_raises(np.AxisError, np.lexsort, (np.array([]),), axis=1)
  370. assert_raises(np.AxisError, np.lexsort, (np.array(1),), axis=10)
  371. def test_lexsort_zerolen_element(self):
  372. dt = np.dtype([]) # a void dtype with no fields
  373. xs = np.empty(4, dt)
  374. assert np.lexsort((xs,)).shape[0] == xs.shape[0]
  375. def test_pickle_py2_bytes_encoding(self):
  376. # Check that arrays and scalars pickled on Py2 are
  377. # unpickleable on Py3 using encoding='bytes'
  378. test_data = [
  379. # (original, py2_pickle)
  380. (np.unicode_('\u6f2c'),
  381. b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n"
  382. b"(S'U1'\np2\nI0\nI1\ntp3\nRp4\n(I3\nS'<'\np5\nNNNI4\nI4\n"
  383. b"I0\ntp6\nbS',o\\x00\\x00'\np7\ntp8\nRp9\n."),
  384. (np.array([9e123], dtype=np.float64),
  385. b"cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\n"
  386. b"p1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\n"
  387. b"p7\n(S'f8'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'<'\np11\nNNNI-1\nI-1\n"
  388. b"I0\ntp12\nbI00\nS'O\\x81\\xb7Z\\xaa:\\xabY'\np13\ntp14\nb."),
  389. (np.array([(9e123,)], dtype=[('name', float)]),
  390. b"cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n"
  391. b"(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n"
  392. b"(S'V8'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nN(S'name'\np12\ntp13\n"
  393. b"(dp14\ng12\n(g7\n(S'f8'\np15\nI0\nI1\ntp16\nRp17\n(I3\nS'<'\np18\nNNNI-1\n"
  394. b"I-1\nI0\ntp19\nbI0\ntp20\nsI8\nI1\nI0\ntp21\n"
  395. b"bI00\nS'O\\x81\\xb7Z\\xaa:\\xabY'\np22\ntp23\nb."),
  396. ]
  397. for original, data in test_data:
  398. result = pickle.loads(data, encoding='bytes')
  399. assert_equal(result, original)
  400. if isinstance(result, np.ndarray) and result.dtype.names is not None:
  401. for name in result.dtype.names:
  402. assert_(isinstance(name, str))
  403. def test_pickle_dtype(self):
  404. # Ticket #251
  405. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  406. pickle.dumps(float, protocol=proto)
  407. def test_swap_real(self):
  408. # Ticket #265
  409. assert_equal(np.arange(4, dtype='>c8').imag.max(), 0.0)
  410. assert_equal(np.arange(4, dtype='<c8').imag.max(), 0.0)
  411. assert_equal(np.arange(4, dtype='>c8').real.max(), 3.0)
  412. assert_equal(np.arange(4, dtype='<c8').real.max(), 3.0)
  413. def test_object_array_from_list(self):
  414. # Ticket #270 (gh-868)
  415. assert_(np.array([1, None, 'A']).shape == (3,))
  416. def test_multiple_assign(self):
  417. # Ticket #273
  418. a = np.zeros((3, 1), int)
  419. a[[1, 2]] = 1
  420. def test_empty_array_type(self):
  421. assert_equal(np.array([]).dtype, np.zeros(0).dtype)
  422. def test_void_copyswap(self):
  423. dt = np.dtype([('one', '<i4'), ('two', '<i4')])
  424. x = np.array((1, 2), dtype=dt)
  425. x = x.byteswap()
  426. assert_(x['one'] > 1 and x['two'] > 2)
  427. def test_method_args(self):
  428. # Make sure methods and functions have same default axis
  429. # keyword and arguments
  430. funcs1 = ['argmax', 'argmin', 'sum', ('product', 'prod'),
  431. ('sometrue', 'any'),
  432. ('alltrue', 'all'), 'cumsum', ('cumproduct', 'cumprod'),
  433. 'ptp', 'cumprod', 'prod', 'std', 'var', 'mean',
  434. 'round', 'min', 'max', 'argsort', 'sort']
  435. funcs2 = ['compress', 'take', 'repeat']
  436. for func in funcs1:
  437. arr = np.random.rand(8, 7)
  438. arr2 = arr.copy()
  439. if isinstance(func, tuple):
  440. func_meth = func[1]
  441. func = func[0]
  442. else:
  443. func_meth = func
  444. res1 = getattr(arr, func_meth)()
  445. res2 = getattr(np, func)(arr2)
  446. if res1 is None:
  447. res1 = arr
  448. if res1.dtype.kind in 'uib':
  449. assert_((res1 == res2).all(), func)
  450. else:
  451. assert_(abs(res1-res2).max() < 1e-8, func)
  452. for func in funcs2:
  453. arr1 = np.random.rand(8, 7)
  454. arr2 = np.random.rand(8, 7)
  455. res1 = None
  456. if func == 'compress':
  457. arr1 = arr1.ravel()
  458. res1 = getattr(arr2, func)(arr1)
  459. else:
  460. arr2 = (15*arr2).astype(int).ravel()
  461. if res1 is None:
  462. res1 = getattr(arr1, func)(arr2)
  463. res2 = getattr(np, func)(arr1, arr2)
  464. assert_(abs(res1-res2).max() < 1e-8, func)
  465. def test_mem_lexsort_strings(self):
  466. # Ticket #298
  467. lst = ['abc', 'cde', 'fgh']
  468. np.lexsort((lst,))
  469. def test_fancy_index(self):
  470. # Ticket #302
  471. x = np.array([1, 2])[np.array([0])]
  472. assert_equal(x.shape, (1,))
  473. def test_recarray_copy(self):
  474. # Ticket #312
  475. dt = [('x', np.int16), ('y', np.float64)]
  476. ra = np.array([(1, 2.3)], dtype=dt)
  477. rb = np.rec.array(ra, dtype=dt)
  478. rb['x'] = 2.
  479. assert_(ra['x'] != rb['x'])
  480. def test_rec_fromarray(self):
  481. # Ticket #322
  482. x1 = np.array([[1, 2], [3, 4], [5, 6]])
  483. x2 = np.array(['a', 'dd', 'xyz'])
  484. x3 = np.array([1.1, 2, 3])
  485. np.rec.fromarrays([x1, x2, x3], formats="(2,)i4,a3,f8")
  486. def test_object_array_assign(self):
  487. x = np.empty((2, 2), object)
  488. x.flat[2] = (1, 2, 3)
  489. assert_equal(x.flat[2], (1, 2, 3))
  490. def test_ndmin_float64(self):
  491. # Ticket #324
  492. x = np.array([1, 2, 3], dtype=np.float64)
  493. assert_equal(np.array(x, dtype=np.float32, ndmin=2).ndim, 2)
  494. assert_equal(np.array(x, dtype=np.float64, ndmin=2).ndim, 2)
  495. def test_ndmin_order(self):
  496. # Issue #465 and related checks
  497. assert_(np.array([1, 2], order='C', ndmin=3).flags.c_contiguous)
  498. assert_(np.array([1, 2], order='F', ndmin=3).flags.f_contiguous)
  499. assert_(np.array(np.ones((2, 2), order='F'), ndmin=3).flags.f_contiguous)
  500. assert_(np.array(np.ones((2, 2), order='C'), ndmin=3).flags.c_contiguous)
  501. def test_mem_axis_minimization(self):
  502. # Ticket #327
  503. data = np.arange(5)
  504. data = np.add.outer(data, data)
  505. def test_mem_float_imag(self):
  506. # Ticket #330
  507. np.float64(1.0).imag
  508. def test_dtype_tuple(self):
  509. # Ticket #334
  510. assert_(np.dtype('i4') == np.dtype(('i4', ())))
  511. def test_dtype_posttuple(self):
  512. # Ticket #335
  513. np.dtype([('col1', '()i4')])
  514. def test_numeric_carray_compare(self):
  515. # Ticket #341
  516. assert_equal(np.array(['X'], 'c'), b'X')
  517. def test_string_array_size(self):
  518. # Ticket #342
  519. assert_raises(ValueError,
  520. np.array, [['X'], ['X', 'X', 'X']], '|S1')
  521. def test_dtype_repr(self):
  522. # Ticket #344
  523. dt1 = np.dtype(('uint32', 2))
  524. dt2 = np.dtype(('uint32', (2,)))
  525. assert_equal(dt1.__repr__(), dt2.__repr__())
  526. def test_reshape_order(self):
  527. # Make sure reshape order works.
  528. a = np.arange(6).reshape(2, 3, order='F')
  529. assert_equal(a, [[0, 2, 4], [1, 3, 5]])
  530. a = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
  531. b = a[:, 1]
  532. assert_equal(b.reshape(2, 2, order='F'), [[2, 6], [4, 8]])
  533. def test_reshape_zero_strides(self):
  534. # Issue #380, test reshaping of zero strided arrays
  535. a = np.ones(1)
  536. a = np.lib.stride_tricks.as_strided(a, shape=(5,), strides=(0,))
  537. assert_(a.reshape(5, 1).strides[0] == 0)
  538. def test_reshape_zero_size(self):
  539. # GitHub Issue #2700, setting shape failed for 0-sized arrays
  540. a = np.ones((0, 2))
  541. a.shape = (-1, 2)
  542. # Cannot test if NPY_RELAXED_STRIDES_DEBUG changes the strides.
  543. # With NPY_RELAXED_STRIDES_DEBUG the test becomes superfluous.
  544. @pytest.mark.skipif(np.ones(1).strides[0] == np.iinfo(np.intp).max,
  545. reason="Using relaxed stride debug")
  546. def test_reshape_trailing_ones_strides(self):
  547. # GitHub issue gh-2949, bad strides for trailing ones of new shape
  548. a = np.zeros(12, dtype=np.int32)[::2] # not contiguous
  549. strides_c = (16, 8, 8, 8)
  550. strides_f = (8, 24, 48, 48)
  551. assert_equal(a.reshape(3, 2, 1, 1).strides, strides_c)
  552. assert_equal(a.reshape(3, 2, 1, 1, order='F').strides, strides_f)
  553. assert_equal(np.array(0, dtype=np.int32).reshape(1, 1).strides, (4, 4))
  554. def test_repeat_discont(self):
  555. # Ticket #352
  556. a = np.arange(12).reshape(4, 3)[:, 2]
  557. assert_equal(a.repeat(3), [2, 2, 2, 5, 5, 5, 8, 8, 8, 11, 11, 11])
  558. def test_array_index(self):
  559. # Make sure optimization is not called in this case.
  560. a = np.array([1, 2, 3])
  561. a2 = np.array([[1, 2, 3]])
  562. assert_equal(a[np.where(a == 3)], a2[np.where(a2 == 3)])
  563. def test_object_argmax(self):
  564. a = np.array([1, 2, 3], dtype=object)
  565. assert_(a.argmax() == 2)
  566. def test_recarray_fields(self):
  567. # Ticket #372
  568. dt0 = np.dtype([('f0', 'i4'), ('f1', 'i4')])
  569. dt1 = np.dtype([('f0', 'i8'), ('f1', 'i8')])
  570. for a in [np.array([(1, 2), (3, 4)], "i4,i4"),
  571. np.rec.array([(1, 2), (3, 4)], "i4,i4"),
  572. np.rec.array([(1, 2), (3, 4)]),
  573. np.rec.fromarrays([(1, 2), (3, 4)], "i4,i4"),
  574. np.rec.fromarrays([(1, 2), (3, 4)])]:
  575. assert_(a.dtype in [dt0, dt1])
  576. def test_random_shuffle(self):
  577. # Ticket #374
  578. a = np.arange(5).reshape((5, 1))
  579. b = a.copy()
  580. np.random.shuffle(b)
  581. assert_equal(np.sort(b, axis=0), a)
  582. def test_refcount_vdot(self):
  583. # Changeset #3443
  584. _assert_valid_refcount(np.vdot)
  585. def test_startswith(self):
  586. ca = np.char.array(['Hi', 'There'])
  587. assert_equal(ca.startswith('H'), [True, False])
  588. def test_noncommutative_reduce_accumulate(self):
  589. # Ticket #413
  590. tosubtract = np.arange(5)
  591. todivide = np.array([2.0, 0.5, 0.25])
  592. assert_equal(np.subtract.reduce(tosubtract), -10)
  593. assert_equal(np.divide.reduce(todivide), 16.0)
  594. assert_array_equal(np.subtract.accumulate(tosubtract),
  595. np.array([0, -1, -3, -6, -10]))
  596. assert_array_equal(np.divide.accumulate(todivide),
  597. np.array([2., 4., 16.]))
  598. def test_convolve_empty(self):
  599. # Convolve should raise an error for empty input array.
  600. assert_raises(ValueError, np.convolve, [], [1])
  601. assert_raises(ValueError, np.convolve, [1], [])
  602. def test_multidim_byteswap(self):
  603. # Ticket #449
  604. r = np.array([(1, (0, 1, 2))], dtype="i2,3i2")
  605. assert_array_equal(r.byteswap(),
  606. np.array([(256, (0, 256, 512))], r.dtype))
  607. def test_string_NULL(self):
  608. # Changeset 3557
  609. assert_equal(np.array("a\x00\x0b\x0c\x00").item(),
  610. 'a\x00\x0b\x0c')
  611. def test_junk_in_string_fields_of_recarray(self):
  612. # Ticket #483
  613. r = np.array([[b'abc']], dtype=[('var1', '|S20')])
  614. assert_(asbytes(r['var1'][0][0]) == b'abc')
  615. def test_take_output(self):
  616. # Ensure that 'take' honours output parameter.
  617. x = np.arange(12).reshape((3, 4))
  618. a = np.take(x, [0, 2], axis=1)
  619. b = np.zeros_like(a)
  620. np.take(x, [0, 2], axis=1, out=b)
  621. assert_array_equal(a, b)
  622. def test_take_object_fail(self):
  623. # Issue gh-3001
  624. d = 123.
  625. a = np.array([d, 1], dtype=object)
  626. if HAS_REFCOUNT:
  627. ref_d = sys.getrefcount(d)
  628. try:
  629. a.take([0, 100])
  630. except IndexError:
  631. pass
  632. if HAS_REFCOUNT:
  633. assert_(ref_d == sys.getrefcount(d))
  634. def test_array_str_64bit(self):
  635. # Ticket #501
  636. s = np.array([1, np.nan], dtype=np.float64)
  637. with np.errstate(all='raise'):
  638. np.array_str(s) # Should succeed
  639. def test_frompyfunc_endian(self):
  640. # Ticket #503
  641. from math import radians
  642. uradians = np.frompyfunc(radians, 1, 1)
  643. big_endian = np.array([83.4, 83.5], dtype='>f8')
  644. little_endian = np.array([83.4, 83.5], dtype='<f8')
  645. assert_almost_equal(uradians(big_endian).astype(float),
  646. uradians(little_endian).astype(float))
  647. def test_mem_string_arr(self):
  648. # Ticket #514
  649. s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
  650. t = []
  651. np.hstack((t, s))
  652. def test_arr_transpose(self):
  653. # Ticket #516
  654. x = np.random.rand(*(2,)*16)
  655. x.transpose(list(range(16))) # Should succeed
  656. def test_string_mergesort(self):
  657. # Ticket #540
  658. x = np.array(['a']*32)
  659. assert_array_equal(x.argsort(kind='m'), np.arange(32))
  660. def test_argmax_byteorder(self):
  661. # Ticket #546
  662. a = np.arange(3, dtype='>f')
  663. assert_(a[a.argmax()] == a.max())
  664. def test_rand_seed(self):
  665. # Ticket #555
  666. for l in np.arange(4):
  667. np.random.seed(l)
  668. def test_mem_deallocation_leak(self):
  669. # Ticket #562
  670. a = np.zeros(5, dtype=float)
  671. b = np.array(a, dtype=float)
  672. del a, b
  673. def test_mem_on_invalid_dtype(self):
  674. "Ticket #583"
  675. assert_raises(ValueError, np.fromiter, [['12', ''], ['13', '']], str)
  676. def test_dot_negative_stride(self):
  677. # Ticket #588
  678. x = np.array([[1, 5, 25, 125., 625]])
  679. y = np.array([[20.], [160.], [640.], [1280.], [1024.]])
  680. z = y[::-1].copy()
  681. y2 = y[::-1]
  682. assert_equal(np.dot(x, z), np.dot(x, y2))
  683. def test_object_casting(self):
  684. # This used to trigger the object-type version of
  685. # the bitwise_or operation, because float64 -> object
  686. # casting succeeds
  687. def rs():
  688. x = np.ones([484, 286])
  689. y = np.zeros([484, 286])
  690. x |= y
  691. assert_raises(TypeError, rs)
  692. def test_unicode_scalar(self):
  693. # Ticket #600
  694. x = np.array(["DROND", "DROND1"], dtype="U6")
  695. el = x[1]
  696. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  697. new = pickle.loads(pickle.dumps(el, protocol=proto))
  698. assert_equal(new, el)
  699. def test_arange_non_native_dtype(self):
  700. # Ticket #616
  701. for T in ('>f4', '<f4'):
  702. dt = np.dtype(T)
  703. assert_equal(np.arange(0, dtype=dt).dtype, dt)
  704. assert_equal(np.arange(0.5, dtype=dt).dtype, dt)
  705. assert_equal(np.arange(5, dtype=dt).dtype, dt)
  706. def test_bool_flat_indexing_invalid_nr_elements(self):
  707. s = np.ones(10, dtype=float)
  708. x = np.array((15,), dtype=float)
  709. def ia(x, s, v):
  710. x[(s > 0)] = v
  711. assert_raises(IndexError, ia, x, s, np.zeros(9, dtype=float))
  712. assert_raises(IndexError, ia, x, s, np.zeros(11, dtype=float))
  713. # Old special case (different code path):
  714. assert_raises(ValueError, ia, x.flat, s, np.zeros(9, dtype=float))
  715. assert_raises(ValueError, ia, x.flat, s, np.zeros(11, dtype=float))
  716. def test_mem_scalar_indexing(self):
  717. # Ticket #603
  718. x = np.array([0], dtype=float)
  719. index = np.array(0, dtype=np.int32)
  720. x[index]
  721. def test_binary_repr_0_width(self):
  722. assert_equal(np.binary_repr(0, width=3), '000')
  723. def test_fromstring(self):
  724. assert_equal(np.fromstring("12:09:09", dtype=int, sep=":"),
  725. [12, 9, 9])
  726. def test_searchsorted_variable_length(self):
  727. x = np.array(['a', 'aa', 'b'])
  728. y = np.array(['d', 'e'])
  729. assert_equal(x.searchsorted(y), [3, 3])
  730. def test_string_argsort_with_zeros(self):
  731. # Check argsort for strings containing zeros.
  732. x = np.frombuffer(b"\x00\x02\x00\x01", dtype="|S2")
  733. assert_array_equal(x.argsort(kind='m'), np.array([1, 0]))
  734. assert_array_equal(x.argsort(kind='q'), np.array([1, 0]))
  735. def test_string_sort_with_zeros(self):
  736. # Check sort for strings containing zeros.
  737. x = np.frombuffer(b"\x00\x02\x00\x01", dtype="|S2")
  738. y = np.frombuffer(b"\x00\x01\x00\x02", dtype="|S2")
  739. assert_array_equal(np.sort(x, kind="q"), y)
  740. def test_copy_detection_zero_dim(self):
  741. # Ticket #658
  742. np.indices((0, 3, 4)).T.reshape(-1, 3)
  743. def test_flat_byteorder(self):
  744. # Ticket #657
  745. x = np.arange(10)
  746. assert_array_equal(x.astype('>i4'), x.astype('<i4').flat[:])
  747. assert_array_equal(x.astype('>i4').flat[:], x.astype('<i4'))
  748. def test_sign_bit(self):
  749. x = np.array([0, -0.0, 0])
  750. assert_equal(str(np.abs(x)), '[0. 0. 0.]')
  751. def test_flat_index_byteswap(self):
  752. for dt in (np.dtype('<i4'), np.dtype('>i4')):
  753. x = np.array([-1, 0, 1], dtype=dt)
  754. assert_equal(x.flat[0].dtype, x[0].dtype)
  755. def test_copy_detection_corner_case(self):
  756. # Ticket #658
  757. np.indices((0, 3, 4)).T.reshape(-1, 3)
  758. # Cannot test if NPY_RELAXED_STRIDES_DEBUG changes the strides.
  759. # With NPY_RELAXED_STRIDES_DEBUG the test becomes superfluous,
  760. # 0-sized reshape itself is tested elsewhere.
  761. @pytest.mark.skipif(np.ones(1).strides[0] == np.iinfo(np.intp).max,
  762. reason="Using relaxed stride debug")
  763. def test_copy_detection_corner_case2(self):
  764. # Ticket #771: strides are not set correctly when reshaping 0-sized
  765. # arrays
  766. b = np.indices((0, 3, 4)).T.reshape(-1, 3)
  767. assert_equal(b.strides, (3 * b.itemsize, b.itemsize))
  768. def test_object_array_refcounting(self):
  769. # Ticket #633
  770. if not hasattr(sys, 'getrefcount'):
  771. return
  772. # NB. this is probably CPython-specific
  773. cnt = sys.getrefcount
  774. a = object()
  775. b = object()
  776. c = object()
  777. cnt0_a = cnt(a)
  778. cnt0_b = cnt(b)
  779. cnt0_c = cnt(c)
  780. # -- 0d -> 1-d broadcast slice assignment
  781. arr = np.zeros(5, dtype=np.object_)
  782. arr[:] = a
  783. assert_equal(cnt(a), cnt0_a + 5)
  784. arr[:] = b
  785. assert_equal(cnt(a), cnt0_a)
  786. assert_equal(cnt(b), cnt0_b + 5)
  787. arr[:2] = c
  788. assert_equal(cnt(b), cnt0_b + 3)
  789. assert_equal(cnt(c), cnt0_c + 2)
  790. del arr
  791. # -- 1-d -> 2-d broadcast slice assignment
  792. arr = np.zeros((5, 2), dtype=np.object_)
  793. arr0 = np.zeros(2, dtype=np.object_)
  794. arr0[0] = a
  795. assert_(cnt(a) == cnt0_a + 1)
  796. arr0[1] = b
  797. assert_(cnt(b) == cnt0_b + 1)
  798. arr[:, :] = arr0
  799. assert_(cnt(a) == cnt0_a + 6)
  800. assert_(cnt(b) == cnt0_b + 6)
  801. arr[:, 0] = None
  802. assert_(cnt(a) == cnt0_a + 1)
  803. del arr, arr0
  804. # -- 2-d copying + flattening
  805. arr = np.zeros((5, 2), dtype=np.object_)
  806. arr[:, 0] = a
  807. arr[:, 1] = b
  808. assert_(cnt(a) == cnt0_a + 5)
  809. assert_(cnt(b) == cnt0_b + 5)
  810. arr2 = arr.copy()
  811. assert_(cnt(a) == cnt0_a + 10)
  812. assert_(cnt(b) == cnt0_b + 10)
  813. arr2 = arr[:, 0].copy()
  814. assert_(cnt(a) == cnt0_a + 10)
  815. assert_(cnt(b) == cnt0_b + 5)
  816. arr2 = arr.flatten()
  817. assert_(cnt(a) == cnt0_a + 10)
  818. assert_(cnt(b) == cnt0_b + 10)
  819. del arr, arr2
  820. # -- concatenate, repeat, take, choose
  821. arr1 = np.zeros((5, 1), dtype=np.object_)
  822. arr2 = np.zeros((5, 1), dtype=np.object_)
  823. arr1[...] = a
  824. arr2[...] = b
  825. assert_(cnt(a) == cnt0_a + 5)
  826. assert_(cnt(b) == cnt0_b + 5)
  827. tmp = np.concatenate((arr1, arr2))
  828. assert_(cnt(a) == cnt0_a + 5 + 5)
  829. assert_(cnt(b) == cnt0_b + 5 + 5)
  830. tmp = arr1.repeat(3, axis=0)
  831. assert_(cnt(a) == cnt0_a + 5 + 3*5)
  832. tmp = arr1.take([1, 2, 3], axis=0)
  833. assert_(cnt(a) == cnt0_a + 5 + 3)
  834. x = np.array([[0], [1], [0], [1], [1]], int)
  835. tmp = x.choose(arr1, arr2)
  836. assert_(cnt(a) == cnt0_a + 5 + 2)
  837. assert_(cnt(b) == cnt0_b + 5 + 3)
  838. del tmp # Avoid pyflakes unused variable warning
  839. def test_mem_custom_float_to_array(self):
  840. # Ticket 702
  841. class MyFloat:
  842. def __float__(self):
  843. return 1.0
  844. tmp = np.atleast_1d([MyFloat()])
  845. tmp.astype(float) # Should succeed
  846. def test_object_array_refcount_self_assign(self):
  847. # Ticket #711
  848. class VictimObject:
  849. deleted = False
  850. def __del__(self):
  851. self.deleted = True
  852. d = VictimObject()
  853. arr = np.zeros(5, dtype=np.object_)
  854. arr[:] = d
  855. del d
  856. arr[:] = arr # refcount of 'd' might hit zero here
  857. assert_(not arr[0].deleted)
  858. arr[:] = arr # trying to induce a segfault by doing it again...
  859. assert_(not arr[0].deleted)
  860. def test_mem_fromiter_invalid_dtype_string(self):
  861. x = [1, 2, 3]
  862. assert_raises(ValueError,
  863. np.fromiter, [xi for xi in x], dtype='S')
  864. def test_reduce_big_object_array(self):
  865. # Ticket #713
  866. oldsize = np.setbufsize(10*16)
  867. a = np.array([None]*161, object)
  868. assert_(not np.any(a))
  869. np.setbufsize(oldsize)
  870. def test_mem_0d_array_index(self):
  871. # Ticket #714
  872. np.zeros(10)[np.array(0)]
  873. def test_nonnative_endian_fill(self):
  874. # Non-native endian arrays were incorrectly filled with scalars
  875. # before r5034.
  876. if sys.byteorder == 'little':
  877. dtype = np.dtype('>i4')
  878. else:
  879. dtype = np.dtype('<i4')
  880. x = np.empty([1], dtype=dtype)
  881. x.fill(1)
  882. assert_equal(x, np.array([1], dtype=dtype))
  883. def test_dot_alignment_sse2(self):
  884. # Test for ticket #551, changeset r5140
  885. x = np.zeros((30, 40))
  886. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  887. y = pickle.loads(pickle.dumps(x, protocol=proto))
  888. # y is now typically not aligned on a 8-byte boundary
  889. z = np.ones((1, y.shape[0]))
  890. # This shouldn't cause a segmentation fault:
  891. np.dot(z, y)
  892. def test_astype_copy(self):
  893. # Ticket #788, changeset r5155
  894. # The test data file was generated by scipy.io.savemat.
  895. # The dtype is float64, but the isbuiltin attribute is 0.
  896. data_dir = path.join(path.dirname(__file__), 'data')
  897. filename = path.join(data_dir, "astype_copy.pkl")
  898. with open(filename, 'rb') as f:
  899. xp = pickle.load(f, encoding='latin1')
  900. xpd = xp.astype(np.float64)
  901. assert_((xp.__array_interface__['data'][0] !=
  902. xpd.__array_interface__['data'][0]))
  903. def test_compress_small_type(self):
  904. # Ticket #789, changeset 5217.
  905. # compress with out argument segfaulted if cannot cast safely
  906. import numpy as np
  907. a = np.array([[1, 2], [3, 4]])
  908. b = np.zeros((2, 1), dtype=np.single)
  909. try:
  910. a.compress([True, False], axis=1, out=b)
  911. raise AssertionError("compress with an out which cannot be "
  912. "safely casted should not return "
  913. "successfully")
  914. except TypeError:
  915. pass
  916. def test_attributes(self):
  917. # Ticket #791
  918. class TestArray(np.ndarray):
  919. def __new__(cls, data, info):
  920. result = np.array(data)
  921. result = result.view(cls)
  922. result.info = info
  923. return result
  924. def __array_finalize__(self, obj):
  925. self.info = getattr(obj, 'info', '')
  926. dat = TestArray([[1, 2, 3, 4], [5, 6, 7, 8]], 'jubba')
  927. assert_(dat.info == 'jubba')
  928. dat.resize((4, 2))
  929. assert_(dat.info == 'jubba')
  930. dat.sort()
  931. assert_(dat.info == 'jubba')
  932. dat.fill(2)
  933. assert_(dat.info == 'jubba')
  934. dat.put([2, 3, 4], [6, 3, 4])
  935. assert_(dat.info == 'jubba')
  936. dat.setfield(4, np.int32, 0)
  937. assert_(dat.info == 'jubba')
  938. dat.setflags()
  939. assert_(dat.info == 'jubba')
  940. assert_(dat.all(1).info == 'jubba')
  941. assert_(dat.any(1).info == 'jubba')
  942. assert_(dat.argmax(1).info == 'jubba')
  943. assert_(dat.argmin(1).info == 'jubba')
  944. assert_(dat.argsort(1).info == 'jubba')
  945. assert_(dat.astype(TestArray).info == 'jubba')
  946. assert_(dat.byteswap().info == 'jubba')
  947. assert_(dat.clip(2, 7).info == 'jubba')
  948. assert_(dat.compress([0, 1, 1]).info == 'jubba')
  949. assert_(dat.conj().info == 'jubba')
  950. assert_(dat.conjugate().info == 'jubba')
  951. assert_(dat.copy().info == 'jubba')
  952. dat2 = TestArray([2, 3, 1, 0], 'jubba')
  953. choices = [[0, 1, 2, 3], [10, 11, 12, 13],
  954. [20, 21, 22, 23], [30, 31, 32, 33]]
  955. assert_(dat2.choose(choices).info == 'jubba')
  956. assert_(dat.cumprod(1).info == 'jubba')
  957. assert_(dat.cumsum(1).info == 'jubba')
  958. assert_(dat.diagonal().info == 'jubba')
  959. assert_(dat.flatten().info == 'jubba')
  960. assert_(dat.getfield(np.int32, 0).info == 'jubba')
  961. assert_(dat.imag.info == 'jubba')
  962. assert_(dat.max(1).info == 'jubba')
  963. assert_(dat.mean(1).info == 'jubba')
  964. assert_(dat.min(1).info == 'jubba')
  965. assert_(dat.newbyteorder().info == 'jubba')
  966. assert_(dat.prod(1).info == 'jubba')
  967. assert_(dat.ptp(1).info == 'jubba')
  968. assert_(dat.ravel().info == 'jubba')
  969. assert_(dat.real.info == 'jubba')
  970. assert_(dat.repeat(2).info == 'jubba')
  971. assert_(dat.reshape((2, 4)).info == 'jubba')
  972. assert_(dat.round().info == 'jubba')
  973. assert_(dat.squeeze().info == 'jubba')
  974. assert_(dat.std(1).info == 'jubba')
  975. assert_(dat.sum(1).info == 'jubba')
  976. assert_(dat.swapaxes(0, 1).info == 'jubba')
  977. assert_(dat.take([2, 3, 5]).info == 'jubba')
  978. assert_(dat.transpose().info == 'jubba')
  979. assert_(dat.T.info == 'jubba')
  980. assert_(dat.var(1).info == 'jubba')
  981. assert_(dat.view(TestArray).info == 'jubba')
  982. # These methods do not preserve subclasses
  983. assert_(type(dat.nonzero()[0]) is np.ndarray)
  984. assert_(type(dat.nonzero()[1]) is np.ndarray)
  985. def test_recarray_tolist(self):
  986. # Ticket #793, changeset r5215
  987. # Comparisons fail for NaN, so we can't use random memory
  988. # for the test.
  989. buf = np.zeros(40, dtype=np.int8)
  990. a = np.recarray(2, formats="i4,f8,f8", names="id,x,y", buf=buf)
  991. b = a.tolist()
  992. assert_( a[0].tolist() == b[0])
  993. assert_( a[1].tolist() == b[1])
  994. def test_nonscalar_item_method(self):
  995. # Make sure that .item() fails graciously when it should
  996. a = np.arange(5)
  997. assert_raises(ValueError, a.item)
  998. def test_char_array_creation(self):
  999. a = np.array('123', dtype='c')
  1000. b = np.array([b'1', b'2', b'3'])
  1001. assert_equal(a, b)
  1002. def test_unaligned_unicode_access(self):
  1003. # Ticket #825
  1004. for i in range(1, 9):
  1005. msg = 'unicode offset: %d chars' % i
  1006. t = np.dtype([('a', 'S%d' % i), ('b', 'U2')])
  1007. x = np.array([(b'a', 'b')], dtype=t)
  1008. assert_equal(str(x), "[(b'a', 'b')]", err_msg=msg)
  1009. def test_sign_for_complex_nan(self):
  1010. # Ticket 794.
  1011. with np.errstate(invalid='ignore'):
  1012. C = np.array([-np.inf, -2+1j, 0, 2-1j, np.inf, np.nan])
  1013. have = np.sign(C)
  1014. want = np.array([-1+0j, -1+0j, 0+0j, 1+0j, 1+0j, np.nan])
  1015. assert_equal(have, want)
  1016. def test_for_equal_names(self):
  1017. # Ticket #674
  1018. dt = np.dtype([('foo', float), ('bar', float)])
  1019. a = np.zeros(10, dt)
  1020. b = list(a.dtype.names)
  1021. b[0] = "notfoo"
  1022. a.dtype.names = b
  1023. assert_(a.dtype.names[0] == "notfoo")
  1024. assert_(a.dtype.names[1] == "bar")
  1025. def test_for_object_scalar_creation(self):
  1026. # Ticket #816
  1027. a = np.object_()
  1028. b = np.object_(3)
  1029. b2 = np.object_(3.0)
  1030. c = np.object_([4, 5])
  1031. d = np.object_([None, {}, []])
  1032. assert_(a is None)
  1033. assert_(type(b) is int)
  1034. assert_(type(b2) is float)
  1035. assert_(type(c) is np.ndarray)
  1036. assert_(c.dtype == object)
  1037. assert_(d.dtype == object)
  1038. def test_array_resize_method_system_error(self):
  1039. # Ticket #840 - order should be an invalid keyword.
  1040. x = np.array([[0, 1], [2, 3]])
  1041. assert_raises(TypeError, x.resize, (2, 2), order='C')
  1042. def test_for_zero_length_in_choose(self):
  1043. "Ticket #882"
  1044. a = np.array(1)
  1045. assert_raises(ValueError, lambda x: x.choose([]), a)
  1046. def test_array_ndmin_overflow(self):
  1047. "Ticket #947."
  1048. assert_raises(ValueError, lambda: np.array([1], ndmin=33))
  1049. def test_void_scalar_with_titles(self):
  1050. # No ticket
  1051. data = [('john', 4), ('mary', 5)]
  1052. dtype1 = [(('source:yy', 'name'), 'O'), (('source:xx', 'id'), int)]
  1053. arr = np.array(data, dtype=dtype1)
  1054. assert_(arr[0][0] == 'john')
  1055. assert_(arr[0][1] == 4)
  1056. def test_void_scalar_constructor(self):
  1057. #Issue #1550
  1058. #Create test string data, construct void scalar from data and assert
  1059. #that void scalar contains original data.
  1060. test_string = np.array("test")
  1061. test_string_void_scalar = np.core.multiarray.scalar(
  1062. np.dtype(("V", test_string.dtype.itemsize)), test_string.tobytes())
  1063. assert_(test_string_void_scalar.view(test_string.dtype) == test_string)
  1064. #Create record scalar, construct from data and assert that
  1065. #reconstructed scalar is correct.
  1066. test_record = np.ones((), "i,i")
  1067. test_record_void_scalar = np.core.multiarray.scalar(
  1068. test_record.dtype, test_record.tobytes())
  1069. assert_(test_record_void_scalar == test_record)
  1070. # Test pickle and unpickle of void and record scalars
  1071. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  1072. assert_(pickle.loads(
  1073. pickle.dumps(test_string, protocol=proto)) == test_string)
  1074. assert_(pickle.loads(
  1075. pickle.dumps(test_record, protocol=proto)) == test_record)
  1076. @_no_tracing
  1077. def test_blasdot_uninitialized_memory(self):
  1078. # Ticket #950
  1079. for m in [0, 1, 2]:
  1080. for n in [0, 1, 2]:
  1081. for k in range(3):
  1082. # Try to ensure that x->data contains non-zero floats
  1083. x = np.array([123456789e199], dtype=np.float64)
  1084. if IS_PYPY:
  1085. x.resize((m, 0), refcheck=False)
  1086. else:
  1087. x.resize((m, 0))
  1088. y = np.array([123456789e199], dtype=np.float64)
  1089. if IS_PYPY:
  1090. y.resize((0, n), refcheck=False)
  1091. else:
  1092. y.resize((0, n))
  1093. # `dot` should just return zero (m, n) matrix
  1094. z = np.dot(x, y)
  1095. assert_(np.all(z == 0))
  1096. assert_(z.shape == (m, n))
  1097. def test_zeros(self):
  1098. # Regression test for #1061.
  1099. # Set a size which cannot fit into a 64 bits signed integer
  1100. sz = 2 ** 64
  1101. with assert_raises_regex(ValueError,
  1102. 'Maximum allowed dimension exceeded'):
  1103. np.empty(sz)
  1104. def test_huge_arange(self):
  1105. # Regression test for #1062.
  1106. # Set a size which cannot fit into a 64 bits signed integer
  1107. sz = 2 ** 64
  1108. with assert_raises_regex(ValueError,
  1109. 'Maximum allowed size exceeded'):
  1110. np.arange(sz)
  1111. assert_(np.size == sz)
  1112. def test_fromiter_bytes(self):
  1113. # Ticket #1058
  1114. a = np.fromiter(list(range(10)), dtype='b')
  1115. b = np.fromiter(list(range(10)), dtype='B')
  1116. assert_(np.alltrue(a == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])))
  1117. assert_(np.alltrue(b == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])))
  1118. def test_array_from_sequence_scalar_array(self):
  1119. # Ticket #1078: segfaults when creating an array with a sequence of
  1120. # 0d arrays.
  1121. a = np.array((np.ones(2), np.array(2)), dtype=object)
  1122. assert_equal(a.shape, (2,))
  1123. assert_equal(a.dtype, np.dtype(object))
  1124. assert_equal(a[0], np.ones(2))
  1125. assert_equal(a[1], np.array(2))
  1126. a = np.array(((1,), np.array(1)), dtype=object)
  1127. assert_equal(a.shape, (2,))
  1128. assert_equal(a.dtype, np.dtype(object))
  1129. assert_equal(a[0], (1,))
  1130. assert_equal(a[1], np.array(1))
  1131. def test_array_from_sequence_scalar_array2(self):
  1132. # Ticket #1081: weird array with strange input...
  1133. t = np.array([np.array([]), np.array(0, object)], dtype=object)
  1134. assert_equal(t.shape, (2,))
  1135. assert_equal(t.dtype, np.dtype(object))
  1136. def test_array_too_big(self):
  1137. # Ticket #1080.
  1138. assert_raises(ValueError, np.zeros, [975]*7, np.int8)
  1139. assert_raises(ValueError, np.zeros, [26244]*5, np.int8)
  1140. def test_dtype_keyerrors_(self):
  1141. # Ticket #1106.
  1142. dt = np.dtype([('f1', np.uint)])
  1143. assert_raises(KeyError, dt.__getitem__, "f2")
  1144. assert_raises(IndexError, dt.__getitem__, 1)
  1145. assert_raises(TypeError, dt.__getitem__, 0.0)
  1146. def test_lexsort_buffer_length(self):
  1147. # Ticket #1217, don't segfault.
  1148. a = np.ones(100, dtype=np.int8)
  1149. b = np.ones(100, dtype=np.int32)
  1150. i = np.lexsort((a[::-1], b))
  1151. assert_equal(i, np.arange(100, dtype=int))
  1152. def test_object_array_to_fixed_string(self):
  1153. # Ticket #1235.
  1154. a = np.array(['abcdefgh', 'ijklmnop'], dtype=np.object_)
  1155. b = np.array(a, dtype=(np.str_, 8))
  1156. assert_equal(a, b)
  1157. c = np.array(a, dtype=(np.str_, 5))
  1158. assert_equal(c, np.array(['abcde', 'ijklm']))
  1159. d = np.array(a, dtype=(np.str_, 12))
  1160. assert_equal(a, d)
  1161. e = np.empty((2, ), dtype=(np.str_, 8))
  1162. e[:] = a[:]
  1163. assert_equal(a, e)
  1164. def test_unicode_to_string_cast(self):
  1165. # Ticket #1240.
  1166. a = np.array([['abc', '\u03a3'],
  1167. ['asdf', 'erw']],
  1168. dtype='U')
  1169. assert_raises(UnicodeEncodeError, np.array, a, 'S4')
  1170. def test_unicode_to_string_cast_error(self):
  1171. # gh-15790
  1172. a = np.array(['\x80'] * 129, dtype='U3')
  1173. assert_raises(UnicodeEncodeError, np.array, a, 'S')
  1174. b = a.reshape(3, 43)[:-1, :-1]
  1175. assert_raises(UnicodeEncodeError, np.array, b, 'S')
  1176. def test_mixed_string_byte_array_creation(self):
  1177. a = np.array(['1234', b'123'])
  1178. assert_(a.itemsize == 16)
  1179. a = np.array([b'123', '1234'])
  1180. assert_(a.itemsize == 16)
  1181. a = np.array(['1234', b'123', '12345'])
  1182. assert_(a.itemsize == 20)
  1183. a = np.array([b'123', '1234', b'12345'])
  1184. assert_(a.itemsize == 20)
  1185. a = np.array([b'123', '1234', b'1234'])
  1186. assert_(a.itemsize == 16)
  1187. def test_misaligned_objects_segfault(self):
  1188. # Ticket #1198 and #1267
  1189. a1 = np.zeros((10,), dtype='O,c')
  1190. a2 = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 'S10')
  1191. a1['f0'] = a2
  1192. repr(a1)
  1193. np.argmax(a1['f0'])
  1194. a1['f0'][1] = "FOO"
  1195. a1['f0'] = "FOO"
  1196. np.array(a1['f0'], dtype='S')
  1197. np.nonzero(a1['f0'])
  1198. a1.sort()
  1199. copy.deepcopy(a1)
  1200. def test_misaligned_scalars_segfault(self):
  1201. # Ticket #1267
  1202. s1 = np.array(('a', 'Foo'), dtype='c,O')
  1203. s2 = np.array(('b', 'Bar'), dtype='c,O')
  1204. s1['f1'] = s2['f1']
  1205. s1['f1'] = 'Baz'
  1206. def test_misaligned_dot_product_objects(self):
  1207. # Ticket #1267
  1208. # This didn't require a fix, but it's worth testing anyway, because
  1209. # it may fail if .dot stops enforcing the arrays to be BEHAVED
  1210. a = np.array([[(1, 'a'), (0, 'a')], [(0, 'a'), (1, 'a')]], dtype='O,c')
  1211. b = np.array([[(4, 'a'), (1, 'a')], [(2, 'a'), (2, 'a')]], dtype='O,c')
  1212. np.dot(a['f0'], b['f0'])
  1213. def test_byteswap_complex_scalar(self):
  1214. # Ticket #1259 and gh-441
  1215. for dtype in [np.dtype('<'+t) for t in np.typecodes['Complex']]:
  1216. z = np.array([2.2-1.1j], dtype)
  1217. x = z[0] # always native-endian
  1218. y = x.byteswap()
  1219. if x.dtype.byteorder == z.dtype.byteorder:
  1220. # little-endian machine
  1221. assert_equal(x, np.frombuffer(y.tobytes(), dtype=dtype.newbyteorder()))
  1222. else:
  1223. # big-endian machine
  1224. assert_equal(x, np.frombuffer(y.tobytes(), dtype=dtype))
  1225. # double check real and imaginary parts:
  1226. assert_equal(x.real, y.real.byteswap())
  1227. assert_equal(x.imag, y.imag.byteswap())
  1228. def test_structured_arrays_with_objects1(self):
  1229. # Ticket #1299
  1230. stra = 'aaaa'
  1231. strb = 'bbbb'
  1232. x = np.array([[(0, stra), (1, strb)]], 'i8,O')
  1233. x[x.nonzero()] = x.ravel()[:1]
  1234. assert_(x[0, 1] == x[0, 0])
  1235. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  1236. def test_structured_arrays_with_objects2(self):
  1237. # Ticket #1299 second test
  1238. stra = 'aaaa'
  1239. strb = 'bbbb'
  1240. numb = sys.getrefcount(strb)
  1241. numa = sys.getrefcount(stra)
  1242. x = np.array([[(0, stra), (1, strb)]], 'i8,O')
  1243. x[x.nonzero()] = x.ravel()[:1]
  1244. assert_(sys.getrefcount(strb) == numb)
  1245. assert_(sys.getrefcount(stra) == numa + 2)
  1246. def test_duplicate_title_and_name(self):
  1247. # Ticket #1254
  1248. dtspec = [(('a', 'a'), 'i'), ('b', 'i')]
  1249. assert_raises(ValueError, np.dtype, dtspec)
  1250. def test_signed_integer_division_overflow(self):
  1251. # Ticket #1317.
  1252. def test_type(t):
  1253. min = np.array([np.iinfo(t).min])
  1254. min //= -1
  1255. with np.errstate(over="ignore"):
  1256. for t in (np.int8, np.int16, np.int32, np.int64, int):
  1257. test_type(t)
  1258. def test_buffer_hashlib(self):
  1259. from hashlib import sha256
  1260. x = np.array([1, 2, 3], dtype=np.dtype('<i4'))
  1261. assert_equal(sha256(x).hexdigest(), '4636993d3e1da4e9d6b8f87b79e8f7c6d018580d52661950eabc3845c5897a4d')
  1262. def test_0d_string_scalar(self):
  1263. # Bug #1436; the following should succeed
  1264. np.asarray('x', '>c')
  1265. def test_log1p_compiler_shenanigans(self):
  1266. # Check if log1p is behaving on 32 bit intel systems.
  1267. assert_(np.isfinite(np.log1p(np.exp2(-53))))
  1268. def test_fromiter_comparison(self):
  1269. a = np.fromiter(list(range(10)), dtype='b')
  1270. b = np.fromiter(list(range(10)), dtype='B')
  1271. assert_(np.alltrue(a == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])))
  1272. assert_(np.alltrue(b == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])))
  1273. def test_fromstring_crash(self):
  1274. # Ticket #1345: the following should not cause a crash
  1275. with assert_warns(DeprecationWarning):
  1276. np.fromstring(b'aa, aa, 1.0', sep=',')
  1277. def test_ticket_1539(self):
  1278. dtypes = [x for x in np.sctypeDict.values()
  1279. if (issubclass(x, np.number)
  1280. and not issubclass(x, np.timedelta64))]
  1281. a = np.array([], np.bool_) # not x[0] because it is unordered
  1282. failures = []
  1283. for x in dtypes:
  1284. b = a.astype(x)
  1285. for y in dtypes:
  1286. c = a.astype(y)
  1287. try:
  1288. np.dot(b, c)
  1289. except TypeError:
  1290. failures.append((x, y))
  1291. if failures:
  1292. raise AssertionError("Failures: %r" % failures)
  1293. def test_ticket_1538(self):
  1294. x = np.finfo(np.float32)
  1295. for name in 'eps epsneg max min resolution tiny'.split():
  1296. assert_equal(type(getattr(x, name)), np.float32,
  1297. err_msg=name)
  1298. def test_ticket_1434(self):
  1299. # Check that the out= argument in var and std has an effect
  1300. data = np.array(((1, 2, 3), (4, 5, 6), (7, 8, 9)))
  1301. out = np.zeros((3,))
  1302. ret = data.var(axis=1, out=out)
  1303. assert_(ret is out)
  1304. assert_array_equal(ret, data.var(axis=1))
  1305. ret = data.std(axis=1, out=out)
  1306. assert_(ret is out)
  1307. assert_array_equal(ret, data.std(axis=1))
  1308. def test_complex_nan_maximum(self):
  1309. cnan = complex(0, np.nan)
  1310. assert_equal(np.maximum(1, cnan), cnan)
  1311. def test_subclass_int_tuple_assignment(self):
  1312. # ticket #1563
  1313. class Subclass(np.ndarray):
  1314. def __new__(cls, i):
  1315. return np.ones((i,)).view(cls)
  1316. x = Subclass(5)
  1317. x[(0,)] = 2 # shouldn't raise an exception
  1318. assert_equal(x[0], 2)
  1319. def test_ufunc_no_unnecessary_views(self):
  1320. # ticket #1548
  1321. class Subclass(np.ndarray):
  1322. pass
  1323. x = np.array([1, 2, 3]).view(Subclass)
  1324. y = np.add(x, x, x)
  1325. assert_equal(id(x), id(y))
  1326. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  1327. def test_take_refcount(self):
  1328. # ticket #939
  1329. a = np.arange(16, dtype=float)
  1330. a.shape = (4, 4)
  1331. lut = np.ones((5 + 3, 4), float)
  1332. rgba = np.empty(shape=a.shape + (4,), dtype=lut.dtype)
  1333. c1 = sys.getrefcount(rgba)
  1334. try:
  1335. lut.take(a, axis=0, mode='clip', out=rgba)
  1336. except TypeError:
  1337. pass
  1338. c2 = sys.getrefcount(rgba)
  1339. assert_equal(c1, c2)
  1340. def test_fromfile_tofile_seeks(self):
  1341. # On Python 3, tofile/fromfile used to get (#1610) the Python
  1342. # file handle out of sync
  1343. f0 = tempfile.NamedTemporaryFile()
  1344. f = f0.file
  1345. f.write(np.arange(255, dtype='u1').tobytes())
  1346. f.seek(20)
  1347. ret = np.fromfile(f, count=4, dtype='u1')
  1348. assert_equal(ret, np.array([20, 21, 22, 23], dtype='u1'))
  1349. assert_equal(f.tell(), 24)
  1350. f.seek(40)
  1351. np.array([1, 2, 3], dtype='u1').tofile(f)
  1352. assert_equal(f.tell(), 43)
  1353. f.seek(40)
  1354. data = f.read(3)
  1355. assert_equal(data, b"\x01\x02\x03")
  1356. f.seek(80)
  1357. f.read(4)
  1358. data = np.fromfile(f, dtype='u1', count=4)
  1359. assert_equal(data, np.array([84, 85, 86, 87], dtype='u1'))
  1360. f.close()
  1361. def test_complex_scalar_warning(self):
  1362. for tp in [np.csingle, np.cdouble, np.clongdouble]:
  1363. x = tp(1+2j)
  1364. assert_warns(np.ComplexWarning, float, x)
  1365. with suppress_warnings() as sup:
  1366. sup.filter(np.ComplexWarning)
  1367. assert_equal(float(x), float(x.real))
  1368. def test_complex_scalar_complex_cast(self):
  1369. for tp in [np.csingle, np.cdouble, np.clongdouble]:
  1370. x = tp(1+2j)
  1371. assert_equal(complex(x), 1+2j)
  1372. def test_complex_boolean_cast(self):
  1373. # Ticket #2218
  1374. for tp in [np.csingle, np.cdouble, np.clongdouble]:
  1375. x = np.array([0, 0+0.5j, 0.5+0j], dtype=tp)
  1376. assert_equal(x.astype(bool), np.array([0, 1, 1], dtype=bool))
  1377. assert_(np.any(x))
  1378. assert_(np.all(x[1:]))
  1379. def test_uint_int_conversion(self):
  1380. x = 2**64 - 1
  1381. assert_equal(int(np.uint64(x)), x)
  1382. def test_duplicate_field_names_assign(self):
  1383. ra = np.fromiter(((i*3, i*2) for i in range(10)), dtype='i8,f8')
  1384. ra.dtype.names = ('f1', 'f2')
  1385. repr(ra) # should not cause a segmentation fault
  1386. assert_raises(ValueError, setattr, ra.dtype, 'names', ('f1', 'f1'))
  1387. def test_eq_string_and_object_array(self):
  1388. # From e-mail thread "__eq__ with str and object" (Keith Goodman)
  1389. a1 = np.array(['a', 'b'], dtype=object)
  1390. a2 = np.array(['a', 'c'])
  1391. assert_array_equal(a1 == a2, [True, False])
  1392. assert_array_equal(a2 == a1, [True, False])
  1393. def test_nonzero_byteswap(self):
  1394. a = np.array([0x80000000, 0x00000080, 0], dtype=np.uint32)
  1395. a.dtype = np.float32
  1396. assert_equal(a.nonzero()[0], [1])
  1397. a = a.byteswap().newbyteorder()
  1398. assert_equal(a.nonzero()[0], [1]) # [0] if nonzero() ignores swap
  1399. def test_find_common_type_boolean(self):
  1400. # Ticket #1695
  1401. assert_(np.find_common_type([], ['?', '?']) == '?')
  1402. def test_empty_mul(self):
  1403. a = np.array([1.])
  1404. a[1:1] *= 2
  1405. assert_equal(a, [1.])
  1406. def test_array_side_effect(self):
  1407. # The second use of itemsize was throwing an exception because in
  1408. # ctors.c, discover_itemsize was calling PyObject_Length without
  1409. # checking the return code. This failed to get the length of the
  1410. # number 2, and the exception hung around until something checked
  1411. # PyErr_Occurred() and returned an error.
  1412. assert_equal(np.dtype('S10').itemsize, 10)
  1413. np.array([['abc', 2], ['long ', '0123456789']], dtype=np.string_)
  1414. assert_equal(np.dtype('S10').itemsize, 10)
  1415. def test_any_float(self):
  1416. # all and any for floats
  1417. a = np.array([0.1, 0.9])
  1418. assert_(np.any(a))
  1419. assert_(np.all(a))
  1420. def test_large_float_sum(self):
  1421. a = np.arange(10000, dtype='f')
  1422. assert_equal(a.sum(dtype='d'), a.astype('d').sum())
  1423. def test_ufunc_casting_out(self):
  1424. a = np.array(1.0, dtype=np.float32)
  1425. b = np.array(1.0, dtype=np.float64)
  1426. c = np.array(1.0, dtype=np.float32)
  1427. np.add(a, b, out=c)
  1428. assert_equal(c, 2.0)
  1429. def test_array_scalar_contiguous(self):
  1430. # Array scalars are both C and Fortran contiguous
  1431. assert_(np.array(1.0).flags.c_contiguous)
  1432. assert_(np.array(1.0).flags.f_contiguous)
  1433. assert_(np.array(np.float32(1.0)).flags.c_contiguous)
  1434. assert_(np.array(np.float32(1.0)).flags.f_contiguous)
  1435. def test_squeeze_contiguous(self):
  1436. # Similar to GitHub issue #387
  1437. a = np.zeros((1, 2)).squeeze()
  1438. b = np.zeros((2, 2, 2), order='F')[:, :, ::2].squeeze()
  1439. assert_(a.flags.c_contiguous)
  1440. assert_(a.flags.f_contiguous)
  1441. assert_(b.flags.f_contiguous)
  1442. def test_squeeze_axis_handling(self):
  1443. # Issue #10779
  1444. # Ensure proper handling of objects
  1445. # that don't support axis specification
  1446. # when squeezing
  1447. class OldSqueeze(np.ndarray):
  1448. def __new__(cls,
  1449. input_array):
  1450. obj = np.asarray(input_array).view(cls)
  1451. return obj
  1452. # it is perfectly reasonable that prior
  1453. # to numpy version 1.7.0 a subclass of ndarray
  1454. # might have been created that did not expect
  1455. # squeeze to have an axis argument
  1456. # NOTE: this example is somewhat artificial;
  1457. # it is designed to simulate an old API
  1458. # expectation to guard against regression
  1459. def squeeze(self):
  1460. return super().squeeze()
  1461. oldsqueeze = OldSqueeze(np.array([[1],[2],[3]]))
  1462. # if no axis argument is specified the old API
  1463. # expectation should give the correct result
  1464. assert_equal(np.squeeze(oldsqueeze),
  1465. np.array([1,2,3]))
  1466. # likewise, axis=None should work perfectly well
  1467. # with the old API expectation
  1468. assert_equal(np.squeeze(oldsqueeze, axis=None),
  1469. np.array([1,2,3]))
  1470. # however, specification of any particular axis
  1471. # should raise a TypeError in the context of the
  1472. # old API specification, even when using a valid
  1473. # axis specification like 1 for this array
  1474. with assert_raises(TypeError):
  1475. # this would silently succeed for array
  1476. # subclasses / objects that did not support
  1477. # squeeze axis argument handling before fixing
  1478. # Issue #10779
  1479. np.squeeze(oldsqueeze, axis=1)
  1480. # check for the same behavior when using an invalid
  1481. # axis specification -- in this case axis=0 does not
  1482. # have size 1, but the priority should be to raise
  1483. # a TypeError for the axis argument and NOT a
  1484. # ValueError for squeezing a non-empty dimension
  1485. with assert_raises(TypeError):
  1486. np.squeeze(oldsqueeze, axis=0)
  1487. # the new API knows how to handle the axis
  1488. # argument and will return a ValueError if
  1489. # attempting to squeeze an axis that is not
  1490. # of length 1
  1491. with assert_raises(ValueError):
  1492. np.squeeze(np.array([[1],[2],[3]]), axis=0)
  1493. def test_reduce_contiguous(self):
  1494. # GitHub issue #387
  1495. a = np.add.reduce(np.zeros((2, 1, 2)), (0, 1))
  1496. b = np.add.reduce(np.zeros((2, 1, 2)), 1)
  1497. assert_(a.flags.c_contiguous)
  1498. assert_(a.flags.f_contiguous)
  1499. assert_(b.flags.c_contiguous)
  1500. @pytest.mark.skipif(IS_PYSTON, reason="Pyston disables recursion checking")
  1501. def test_object_array_self_reference(self):
  1502. # Object arrays with references to themselves can cause problems
  1503. a = np.array(0, dtype=object)
  1504. a[()] = a
  1505. assert_raises(RecursionError, int, a)
  1506. assert_raises(RecursionError, float, a)
  1507. a[()] = None
  1508. @pytest.mark.skipif(IS_PYSTON, reason="Pyston disables recursion checking")
  1509. def test_object_array_circular_reference(self):
  1510. # Test the same for a circular reference.
  1511. a = np.array(0, dtype=object)
  1512. b = np.array(0, dtype=object)
  1513. a[()] = b
  1514. b[()] = a
  1515. assert_raises(RecursionError, int, a)
  1516. # NumPy has no tp_traverse currently, so circular references
  1517. # cannot be detected. So resolve it:
  1518. a[()] = None
  1519. # This was causing a to become like the above
  1520. a = np.array(0, dtype=object)
  1521. a[...] += 1
  1522. assert_equal(a, 1)
  1523. def test_object_array_nested(self):
  1524. # but is fine with a reference to a different array
  1525. a = np.array(0, dtype=object)
  1526. b = np.array(0, dtype=object)
  1527. a[()] = b
  1528. assert_equal(int(a), int(0))
  1529. assert_equal(float(a), float(0))
  1530. def test_object_array_self_copy(self):
  1531. # An object array being copied into itself DECREF'ed before INCREF'ing
  1532. # causing segmentation faults (gh-3787)
  1533. a = np.array(object(), dtype=object)
  1534. np.copyto(a, a)
  1535. if HAS_REFCOUNT:
  1536. assert_(sys.getrefcount(a[()]) == 2)
  1537. a[()].__class__ # will segfault if object was deleted
  1538. def test_zerosize_accumulate(self):
  1539. "Ticket #1733"
  1540. x = np.array([[42, 0]], dtype=np.uint32)
  1541. assert_equal(np.add.accumulate(x[:-1, 0]), [])
  1542. def test_objectarray_setfield(self):
  1543. # Setfield should not overwrite Object fields with non-Object data
  1544. x = np.array([1, 2, 3], dtype=object)
  1545. assert_raises(TypeError, x.setfield, 4, np.int32, 0)
  1546. def test_setting_rank0_string(self):
  1547. "Ticket #1736"
  1548. s1 = b"hello1"
  1549. s2 = b"hello2"
  1550. a = np.zeros((), dtype="S10")
  1551. a[()] = s1
  1552. assert_equal(a, np.array(s1))
  1553. a[()] = np.array(s2)
  1554. assert_equal(a, np.array(s2))
  1555. a = np.zeros((), dtype='f4')
  1556. a[()] = 3
  1557. assert_equal(a, np.array(3))
  1558. a[()] = np.array(4)
  1559. assert_equal(a, np.array(4))
  1560. def test_string_astype(self):
  1561. "Ticket #1748"
  1562. s1 = b'black'
  1563. s2 = b'white'
  1564. s3 = b'other'
  1565. a = np.array([[s1], [s2], [s3]])
  1566. assert_equal(a.dtype, np.dtype('S5'))
  1567. b = a.astype(np.dtype('S0'))
  1568. assert_equal(b.dtype, np.dtype('S5'))
  1569. def test_ticket_1756(self):
  1570. # Ticket #1756
  1571. s = b'0123456789abcdef'
  1572. a = np.array([s]*5)
  1573. for i in range(1, 17):
  1574. a1 = np.array(a, "|S%d" % i)
  1575. a2 = np.array([s[:i]]*5)
  1576. assert_equal(a1, a2)
  1577. def test_fields_strides(self):
  1578. "gh-2355"
  1579. r = np.frombuffer(b'abcdefghijklmnop'*4*3, dtype='i4,(2,3)u2')
  1580. assert_equal(r[0:3:2]['f1'], r['f1'][0:3:2])
  1581. assert_equal(r[0:3:2]['f1'][0], r[0:3:2][0]['f1'])
  1582. assert_equal(r[0:3:2]['f1'][0][()], r[0:3:2][0]['f1'][()])
  1583. assert_equal(r[0:3:2]['f1'][0].strides, r[0:3:2][0]['f1'].strides)
  1584. def test_alignment_update(self):
  1585. # Check that alignment flag is updated on stride setting
  1586. a = np.arange(10)
  1587. assert_(a.flags.aligned)
  1588. a.strides = 3
  1589. assert_(not a.flags.aligned)
  1590. def test_ticket_1770(self):
  1591. "Should not segfault on python 3k"
  1592. import numpy as np
  1593. try:
  1594. a = np.zeros((1,), dtype=[('f1', 'f')])
  1595. a['f1'] = 1
  1596. a['f2'] = 1
  1597. except ValueError:
  1598. pass
  1599. except Exception:
  1600. raise AssertionError
  1601. def test_ticket_1608(self):
  1602. "x.flat shouldn't modify data"
  1603. x = np.array([[1, 2], [3, 4]]).T
  1604. np.array(x.flat)
  1605. assert_equal(x, [[1, 3], [2, 4]])
  1606. def test_pickle_string_overwrite(self):
  1607. import re
  1608. data = np.array([1], dtype='b')
  1609. blob = pickle.dumps(data, protocol=1)
  1610. data = pickle.loads(blob)
  1611. # Check that loads does not clobber interned strings
  1612. s = re.sub("a(.)", "\x01\\1", "a_")
  1613. assert_equal(s[0], "\x01")
  1614. data[0] = 0x6a
  1615. s = re.sub("a(.)", "\x01\\1", "a_")
  1616. assert_equal(s[0], "\x01")
  1617. def test_pickle_bytes_overwrite(self):
  1618. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  1619. data = np.array([1], dtype='b')
  1620. data = pickle.loads(pickle.dumps(data, protocol=proto))
  1621. data[0] = 0x7d
  1622. bytestring = "\x01 ".encode('ascii')
  1623. assert_equal(bytestring[0:1], '\x01'.encode('ascii'))
  1624. def test_pickle_py2_array_latin1_hack(self):
  1625. # Check that unpickling hacks in Py3 that support
  1626. # encoding='latin1' work correctly.
  1627. # Python2 output for pickle.dumps(numpy.array([129], dtype='b'))
  1628. data = (b"cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\n"
  1629. b"tp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'i1'\np8\n"
  1630. b"I0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS'\\x81'\n"
  1631. b"p13\ntp14\nb.")
  1632. # This should work:
  1633. result = pickle.loads(data, encoding='latin1')
  1634. assert_array_equal(result, np.array([129]).astype('b'))
  1635. # Should not segfault:
  1636. assert_raises(Exception, pickle.loads, data, encoding='koi8-r')
  1637. def test_pickle_py2_scalar_latin1_hack(self):
  1638. # Check that scalar unpickling hack in Py3 that supports
  1639. # encoding='latin1' work correctly.
  1640. # Python2 output for pickle.dumps(...)
  1641. datas = [
  1642. # (original, python2_pickle, koi8r_validity)
  1643. (np.unicode_('\u6bd2'),
  1644. (b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n"
  1645. b"(S'U1'\np2\nI0\nI1\ntp3\nRp4\n(I3\nS'<'\np5\nNNNI4\nI4\nI0\n"
  1646. b"tp6\nbS'\\xd2k\\x00\\x00'\np7\ntp8\nRp9\n."),
  1647. 'invalid'),
  1648. (np.float64(9e123),
  1649. (b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n(S'f8'\n"
  1650. b"p2\nI0\nI1\ntp3\nRp4\n(I3\nS'<'\np5\nNNNI-1\nI-1\nI0\ntp6\n"
  1651. b"bS'O\\x81\\xb7Z\\xaa:\\xabY'\np7\ntp8\nRp9\n."),
  1652. 'invalid'),
  1653. (np.bytes_(b'\x9c'), # different 8-bit code point in KOI8-R vs latin1
  1654. (b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n(S'S1'\np2\n"
  1655. b"I0\nI1\ntp3\nRp4\n(I3\nS'|'\np5\nNNNI1\nI1\nI0\ntp6\nbS'\\x9c'\np7\n"
  1656. b"tp8\nRp9\n."),
  1657. 'different'),
  1658. ]
  1659. for original, data, koi8r_validity in datas:
  1660. result = pickle.loads(data, encoding='latin1')
  1661. assert_equal(result, original)
  1662. # Decoding under non-latin1 encoding (e.g.) KOI8-R can
  1663. # produce bad results, but should not segfault.
  1664. if koi8r_validity == 'different':
  1665. # Unicode code points happen to lie within latin1,
  1666. # but are different in koi8-r, resulting to silent
  1667. # bogus results
  1668. result = pickle.loads(data, encoding='koi8-r')
  1669. assert_(result != original)
  1670. elif koi8r_validity == 'invalid':
  1671. # Unicode code points outside latin1, so results
  1672. # to an encoding exception
  1673. assert_raises(ValueError, pickle.loads, data, encoding='koi8-r')
  1674. else:
  1675. raise ValueError(koi8r_validity)
  1676. def test_structured_type_to_object(self):
  1677. a_rec = np.array([(0, 1), (3, 2)], dtype='i4,i8')
  1678. a_obj = np.empty((2,), dtype=object)
  1679. a_obj[0] = (0, 1)
  1680. a_obj[1] = (3, 2)
  1681. # astype records -> object
  1682. assert_equal(a_rec.astype(object), a_obj)
  1683. # '=' records -> object
  1684. b = np.empty_like(a_obj)
  1685. b[...] = a_rec
  1686. assert_equal(b, a_obj)
  1687. # '=' object -> records
  1688. b = np.empty_like(a_rec)
  1689. b[...] = a_obj
  1690. assert_equal(b, a_rec)
  1691. def test_assign_obj_listoflists(self):
  1692. # Ticket # 1870
  1693. # The inner list should get assigned to the object elements
  1694. a = np.zeros(4, dtype=object)
  1695. b = a.copy()
  1696. a[0] = [1]
  1697. a[1] = [2]
  1698. a[2] = [3]
  1699. a[3] = [4]
  1700. b[...] = [[1], [2], [3], [4]]
  1701. assert_equal(a, b)
  1702. # The first dimension should get broadcast
  1703. a = np.zeros((2, 2), dtype=object)
  1704. a[...] = [[1, 2]]
  1705. assert_equal(a, [[1, 2], [1, 2]])
  1706. @pytest.mark.slow_pypy
  1707. def test_memoryleak(self):
  1708. # Ticket #1917 - ensure that array data doesn't leak
  1709. for i in range(1000):
  1710. # 100MB times 1000 would give 100GB of memory usage if it leaks
  1711. a = np.empty((100000000,), dtype='i1')
  1712. del a
  1713. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  1714. def test_ufunc_reduce_memoryleak(self):
  1715. a = np.arange(6)
  1716. acnt = sys.getrefcount(a)
  1717. np.add.reduce(a)
  1718. assert_equal(sys.getrefcount(a), acnt)
  1719. def test_search_sorted_invalid_arguments(self):
  1720. # Ticket #2021, should not segfault.
  1721. x = np.arange(0, 4, dtype='datetime64[D]')
  1722. assert_raises(TypeError, x.searchsorted, 1)
  1723. def test_string_truncation(self):
  1724. # Ticket #1990 - Data can be truncated in creation of an array from a
  1725. # mixed sequence of numeric values and strings (gh-2583)
  1726. for val in [True, 1234, 123.4, complex(1, 234)]:
  1727. for tostr, dtype in [(asunicode, "U"), (asbytes, "S")]:
  1728. b = np.array([val, tostr('xx')], dtype=dtype)
  1729. assert_equal(tostr(b[0]), tostr(val))
  1730. b = np.array([tostr('xx'), val], dtype=dtype)
  1731. assert_equal(tostr(b[1]), tostr(val))
  1732. # test also with longer strings
  1733. b = np.array([val, tostr('xxxxxxxxxx')], dtype=dtype)
  1734. assert_equal(tostr(b[0]), tostr(val))
  1735. b = np.array([tostr('xxxxxxxxxx'), val], dtype=dtype)
  1736. assert_equal(tostr(b[1]), tostr(val))
  1737. def test_string_truncation_ucs2(self):
  1738. # Ticket #2081. Python compiled with two byte unicode
  1739. # can lead to truncation if itemsize is not properly
  1740. # adjusted for NumPy's four byte unicode.
  1741. a = np.array(['abcd'])
  1742. assert_equal(a.dtype.itemsize, 16)
  1743. def test_unique_stable(self):
  1744. # Ticket #2063 must always choose stable sort for argsort to
  1745. # get consistent results
  1746. v = np.array(([0]*5 + [1]*6 + [2]*6)*4)
  1747. res = np.unique(v, return_index=True)
  1748. tgt = (np.array([0, 1, 2]), np.array([ 0, 5, 11]))
  1749. assert_equal(res, tgt)
  1750. def test_unicode_alloc_dealloc_match(self):
  1751. # Ticket #1578, the mismatch only showed up when running
  1752. # python-debug for python versions >= 2.7, and then as
  1753. # a core dump and error message.
  1754. a = np.array(['abc'], dtype=np.unicode_)[0]
  1755. del a
  1756. def test_refcount_error_in_clip(self):
  1757. # Ticket #1588
  1758. a = np.zeros((2,), dtype='>i2').clip(min=0)
  1759. x = a + a
  1760. # This used to segfault:
  1761. y = str(x)
  1762. # Check the final string:
  1763. assert_(y == "[0 0]")
  1764. def test_searchsorted_wrong_dtype(self):
  1765. # Ticket #2189, it used to segfault, so we check that it raises the
  1766. # proper exception.
  1767. a = np.array([('a', 1)], dtype='S1, int')
  1768. assert_raises(TypeError, np.searchsorted, a, 1.2)
  1769. # Ticket #2066, similar problem:
  1770. dtype = np.format_parser(['i4', 'i4'], [], [])
  1771. a = np.recarray((2,), dtype)
  1772. a[...] = [(1, 2), (3, 4)]
  1773. assert_raises(TypeError, np.searchsorted, a, 1)
  1774. def test_complex64_alignment(self):
  1775. # Issue gh-2668 (trac 2076), segfault on sparc due to misalignment
  1776. dtt = np.complex64
  1777. arr = np.arange(10, dtype=dtt)
  1778. # 2D array
  1779. arr2 = np.reshape(arr, (2, 5))
  1780. # Fortran write followed by (C or F) read caused bus error
  1781. data_str = arr2.tobytes('F')
  1782. data_back = np.ndarray(arr2.shape,
  1783. arr2.dtype,
  1784. buffer=data_str,
  1785. order='F')
  1786. assert_array_equal(arr2, data_back)
  1787. def test_structured_count_nonzero(self):
  1788. arr = np.array([0, 1]).astype('i4, (2)i4')[:1]
  1789. count = np.count_nonzero(arr)
  1790. assert_equal(count, 0)
  1791. def test_copymodule_preserves_f_contiguity(self):
  1792. a = np.empty((2, 2), order='F')
  1793. b = copy.copy(a)
  1794. c = copy.deepcopy(a)
  1795. assert_(b.flags.fortran)
  1796. assert_(b.flags.f_contiguous)
  1797. assert_(c.flags.fortran)
  1798. assert_(c.flags.f_contiguous)
  1799. def test_fortran_order_buffer(self):
  1800. import numpy as np
  1801. a = np.array([['Hello', 'Foob']], dtype='U5', order='F')
  1802. arr = np.ndarray(shape=[1, 2, 5], dtype='U1', buffer=a)
  1803. arr2 = np.array([[['H', 'e', 'l', 'l', 'o'],
  1804. ['F', 'o', 'o', 'b', '']]])
  1805. assert_array_equal(arr, arr2)
  1806. def test_assign_from_sequence_error(self):
  1807. # Ticket #4024.
  1808. arr = np.array([1, 2, 3])
  1809. assert_raises(ValueError, arr.__setitem__, slice(None), [9, 9])
  1810. arr.__setitem__(slice(None), [9])
  1811. assert_equal(arr, [9, 9, 9])
  1812. def test_format_on_flex_array_element(self):
  1813. # Ticket #4369.
  1814. dt = np.dtype([('date', '<M8[D]'), ('val', '<f8')])
  1815. arr = np.array([('2000-01-01', 1)], dt)
  1816. formatted = '{0}'.format(arr[0])
  1817. assert_equal(formatted, str(arr[0]))
  1818. def test_deepcopy_on_0d_array(self):
  1819. # Ticket #3311.
  1820. arr = np.array(3)
  1821. arr_cp = copy.deepcopy(arr)
  1822. assert_equal(arr, arr_cp)
  1823. assert_equal(arr.shape, arr_cp.shape)
  1824. assert_equal(int(arr), int(arr_cp))
  1825. assert_(arr is not arr_cp)
  1826. assert_(isinstance(arr_cp, type(arr)))
  1827. def test_deepcopy_F_order_object_array(self):
  1828. # Ticket #6456.
  1829. a = {'a': 1}
  1830. b = {'b': 2}
  1831. arr = np.array([[a, b], [a, b]], order='F')
  1832. arr_cp = copy.deepcopy(arr)
  1833. assert_equal(arr, arr_cp)
  1834. assert_(arr is not arr_cp)
  1835. # Ensure that we have actually copied the item.
  1836. assert_(arr[0, 1] is not arr_cp[1, 1])
  1837. # Ensure we are allowed to have references to the same object.
  1838. assert_(arr[0, 1] is arr[1, 1])
  1839. # Check the references hold for the copied objects.
  1840. assert_(arr_cp[0, 1] is arr_cp[1, 1])
  1841. def test_deepcopy_empty_object_array(self):
  1842. # Ticket #8536.
  1843. # Deepcopy should succeed
  1844. a = np.array([], dtype=object)
  1845. b = copy.deepcopy(a)
  1846. assert_(a.shape == b.shape)
  1847. def test_bool_subscript_crash(self):
  1848. # gh-4494
  1849. c = np.rec.array([(1, 2, 3), (4, 5, 6)])
  1850. masked = c[np.array([True, False])]
  1851. base = masked.base
  1852. del masked, c
  1853. base.dtype
  1854. def test_richcompare_crash(self):
  1855. # gh-4613
  1856. import operator as op
  1857. # dummy class where __array__ throws exception
  1858. class Foo:
  1859. __array_priority__ = 1002
  1860. def __array__(self, *args, **kwargs):
  1861. raise Exception()
  1862. rhs = Foo()
  1863. lhs = np.array(1)
  1864. for f in [op.lt, op.le, op.gt, op.ge]:
  1865. assert_raises(TypeError, f, lhs, rhs)
  1866. assert_(not op.eq(lhs, rhs))
  1867. assert_(op.ne(lhs, rhs))
  1868. def test_richcompare_scalar_and_subclass(self):
  1869. # gh-4709
  1870. class Foo(np.ndarray):
  1871. def __eq__(self, other):
  1872. return "OK"
  1873. x = np.array([1, 2, 3]).view(Foo)
  1874. assert_equal(10 == x, "OK")
  1875. assert_equal(np.int32(10) == x, "OK")
  1876. assert_equal(np.array([10]) == x, "OK")
  1877. def test_pickle_empty_string(self):
  1878. # gh-3926
  1879. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  1880. test_string = np.string_('')
  1881. assert_equal(pickle.loads(
  1882. pickle.dumps(test_string, protocol=proto)), test_string)
  1883. def test_frompyfunc_many_args(self):
  1884. # gh-5672
  1885. def passer(*args):
  1886. pass
  1887. assert_raises(ValueError, np.frompyfunc, passer, 32, 1)
  1888. def test_repeat_broadcasting(self):
  1889. # gh-5743
  1890. a = np.arange(60).reshape(3, 4, 5)
  1891. for axis in chain(range(-a.ndim, a.ndim), [None]):
  1892. assert_equal(a.repeat(2, axis=axis), a.repeat([2], axis=axis))
  1893. def test_frompyfunc_nout_0(self):
  1894. # gh-2014
  1895. def f(x):
  1896. x[0], x[-1] = x[-1], x[0]
  1897. uf = np.frompyfunc(f, 1, 0)
  1898. a = np.array([[1, 2, 3], [4, 5], [6, 7, 8, 9]], dtype=object)
  1899. assert_equal(uf(a), ())
  1900. expected = np.array([[3, 2, 1], [5, 4], [9, 7, 8, 6]], dtype=object)
  1901. assert_array_equal(a, expected)
  1902. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  1903. def test_leak_in_structured_dtype_comparison(self):
  1904. # gh-6250
  1905. recordtype = np.dtype([('a', np.float64),
  1906. ('b', np.int32),
  1907. ('d', (str, 5))])
  1908. # Simple case
  1909. a = np.zeros(2, dtype=recordtype)
  1910. for i in range(100):
  1911. a == a
  1912. assert_(sys.getrefcount(a) < 10)
  1913. # The case in the bug report.
  1914. before = sys.getrefcount(a)
  1915. u, v = a[0], a[1]
  1916. u == v
  1917. del u, v
  1918. gc.collect()
  1919. after = sys.getrefcount(a)
  1920. assert_equal(before, after)
  1921. def test_empty_percentile(self):
  1922. # gh-6530 / gh-6553
  1923. assert_array_equal(np.percentile(np.arange(10), []), np.array([]))
  1924. def test_void_compare_segfault(self):
  1925. # gh-6922. The following should not segfault
  1926. a = np.ones(3, dtype=[('object', 'O'), ('int', '<i2')])
  1927. a.sort()
  1928. def test_reshape_size_overflow(self):
  1929. # gh-7455
  1930. a = np.ones(20)[::2]
  1931. if np.dtype(np.intp).itemsize == 8:
  1932. # 64 bit. The following are the prime factors of 2**63 + 5,
  1933. # plus a leading 2, so when multiplied together as int64,
  1934. # the result overflows to a total size of 10.
  1935. new_shape = (2, 13, 419, 691, 823, 2977518503)
  1936. else:
  1937. # 32 bit. The following are the prime factors of 2**31 + 5,
  1938. # plus a leading 2, so when multiplied together as int32,
  1939. # the result overflows to a total size of 10.
  1940. new_shape = (2, 7, 7, 43826197)
  1941. assert_raises(ValueError, a.reshape, new_shape)
  1942. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  1943. reason="PyPy bug in error formatting")
  1944. def test_invalid_structured_dtypes(self):
  1945. # gh-2865
  1946. # mapping python objects to other dtypes
  1947. assert_raises(ValueError, np.dtype, ('O', [('name', 'i8')]))
  1948. assert_raises(ValueError, np.dtype, ('i8', [('name', 'O')]))
  1949. assert_raises(ValueError, np.dtype,
  1950. ('i8', [('name', [('name', 'O')])]))
  1951. assert_raises(ValueError, np.dtype, ([('a', 'i4'), ('b', 'i4')], 'O'))
  1952. assert_raises(ValueError, np.dtype, ('i8', 'O'))
  1953. # wrong number/type of tuple elements in dict
  1954. assert_raises(ValueError, np.dtype,
  1955. ('i', {'name': ('i', 0, 'title', 'oops')}))
  1956. assert_raises(ValueError, np.dtype,
  1957. ('i', {'name': ('i', 'wrongtype', 'title')}))
  1958. # disallowed as of 1.13
  1959. assert_raises(ValueError, np.dtype,
  1960. ([('a', 'O'), ('b', 'O')], [('c', 'O'), ('d', 'O')]))
  1961. # allowed as a special case due to existing use, see gh-2798
  1962. a = np.ones(1, dtype=('O', [('name', 'O')]))
  1963. assert_equal(a[0], 1)
  1964. # In particular, the above union dtype (and union dtypes in general)
  1965. # should mainly behave like the main (object) dtype:
  1966. assert a[0] is a.item()
  1967. assert type(a[0]) is int
  1968. def test_correct_hash_dict(self):
  1969. # gh-8887 - __hash__ would be None despite tp_hash being set
  1970. all_types = set(np.sctypeDict.values()) - {np.void}
  1971. for t in all_types:
  1972. val = t()
  1973. try:
  1974. hash(val)
  1975. except TypeError as e:
  1976. assert_equal(t.__hash__, None)
  1977. else:
  1978. assert_(t.__hash__ != None)
  1979. def test_scalar_copy(self):
  1980. scalar_types = set(np.sctypeDict.values())
  1981. values = {
  1982. np.void: b"a",
  1983. np.bytes_: b"a",
  1984. np.unicode_: "a",
  1985. np.datetime64: "2017-08-25",
  1986. }
  1987. for sctype in scalar_types:
  1988. item = sctype(values.get(sctype, 1))
  1989. item2 = copy.copy(item)
  1990. assert_equal(item, item2)
  1991. def test_void_item_memview(self):
  1992. va = np.zeros(10, 'V4')
  1993. x = va[:1].item()
  1994. va[0] = b'\xff\xff\xff\xff'
  1995. del va
  1996. assert_equal(x, b'\x00\x00\x00\x00')
  1997. def test_void_getitem(self):
  1998. # Test fix for gh-11668.
  1999. assert_(np.array([b'a'], 'V1').astype('O') == b'a')
  2000. assert_(np.array([b'ab'], 'V2').astype('O') == b'ab')
  2001. assert_(np.array([b'abc'], 'V3').astype('O') == b'abc')
  2002. assert_(np.array([b'abcd'], 'V4').astype('O') == b'abcd')
  2003. def test_structarray_title(self):
  2004. # The following used to segfault on pypy, due to NPY_TITLE_KEY
  2005. # not working properly and resulting to double-decref of the
  2006. # structured array field items:
  2007. # See: https://bitbucket.org/pypy/pypy/issues/2789
  2008. for j in range(5):
  2009. structure = np.array([1], dtype=[(('x', 'X'), np.object_)])
  2010. structure[0]['x'] = np.array([2])
  2011. gc.collect()
  2012. def test_dtype_scalar_squeeze(self):
  2013. # gh-11384
  2014. values = {
  2015. 'S': b"a",
  2016. 'M': "2018-06-20",
  2017. }
  2018. for ch in np.typecodes['All']:
  2019. if ch in 'O':
  2020. continue
  2021. sctype = np.dtype(ch).type
  2022. scvalue = sctype(values.get(ch, 3))
  2023. for axis in [None, ()]:
  2024. squeezed = scvalue.squeeze(axis=axis)
  2025. assert_equal(squeezed, scvalue)
  2026. assert_equal(type(squeezed), type(scvalue))
  2027. def test_field_access_by_title(self):
  2028. # gh-11507
  2029. s = 'Some long field name'
  2030. if HAS_REFCOUNT:
  2031. base = sys.getrefcount(s)
  2032. t = np.dtype([((s, 'f1'), np.float64)])
  2033. data = np.zeros(10, t)
  2034. for i in range(10):
  2035. str(data[['f1']])
  2036. if HAS_REFCOUNT:
  2037. assert_(base <= sys.getrefcount(s))
  2038. @pytest.mark.parametrize('val', [
  2039. # arrays and scalars
  2040. np.ones((10, 10), dtype='int32'),
  2041. np.uint64(10),
  2042. ])
  2043. @pytest.mark.parametrize('protocol',
  2044. range(2, pickle.HIGHEST_PROTOCOL + 1)
  2045. )
  2046. def test_pickle_module(self, protocol, val):
  2047. # gh-12837
  2048. s = pickle.dumps(val, protocol)
  2049. assert b'_multiarray_umath' not in s
  2050. if protocol == 5 and len(val.shape) > 0:
  2051. # unpickling ndarray goes through _frombuffer for protocol 5
  2052. assert b'numpy.core.numeric' in s
  2053. else:
  2054. assert b'numpy.core.multiarray' in s
  2055. def test_object_casting_errors(self):
  2056. # gh-11993 update to ValueError (see gh-16909), since strings can in
  2057. # principle be converted to complex, but this string cannot.
  2058. arr = np.array(['AAAAA', 18465886.0, 18465886.0], dtype=object)
  2059. assert_raises(ValueError, arr.astype, 'c8')
  2060. def test_eff1d_casting(self):
  2061. # gh-12711
  2062. x = np.array([1, 2, 4, 7, 0], dtype=np.int16)
  2063. res = np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99]))
  2064. assert_equal(res, [-99, 1, 2, 3, -7, 88, 99])
  2065. # The use of safe casting means, that 1<<20 is cast unsafely, an
  2066. # error may be better, but currently there is no mechanism for it.
  2067. res = np.ediff1d(x, to_begin=(1<<20), to_end=(1<<20))
  2068. assert_equal(res, [0, 1, 2, 3, -7, 0])
  2069. def test_pickle_datetime64_array(self):
  2070. # gh-12745 (would fail with pickle5 installed)
  2071. d = np.datetime64('2015-07-04 12:59:59.50', 'ns')
  2072. arr = np.array([d])
  2073. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  2074. dumped = pickle.dumps(arr, protocol=proto)
  2075. assert_equal(pickle.loads(dumped), arr)
  2076. def test_bad_array_interface(self):
  2077. class T:
  2078. __array_interface__ = {}
  2079. with assert_raises(ValueError):
  2080. np.array([T()])
  2081. def test_2d__array__shape(self):
  2082. class T:
  2083. def __array__(self):
  2084. return np.ndarray(shape=(0,0))
  2085. # Make sure __array__ is used instead of Sequence methods.
  2086. def __iter__(self):
  2087. return iter([])
  2088. def __getitem__(self, idx):
  2089. raise AssertionError("__getitem__ was called")
  2090. def __len__(self):
  2091. return 0
  2092. t = T()
  2093. # gh-13659, would raise in broadcasting [x=t for x in result]
  2094. arr = np.array([t])
  2095. assert arr.shape == (1, 0, 0)
  2096. @pytest.mark.skipif(sys.maxsize < 2 ** 31 + 1, reason='overflows 32-bit python')
  2097. def test_to_ctypes(self):
  2098. #gh-14214
  2099. arr = np.zeros((2 ** 31 + 1,), 'b')
  2100. assert arr.size * arr.itemsize > 2 ** 31
  2101. c_arr = np.ctypeslib.as_ctypes(arr)
  2102. assert_equal(c_arr._length_, arr.size)
  2103. def test_complex_conversion_error(self):
  2104. # gh-17068
  2105. with pytest.raises(TypeError, match=r"Unable to convert dtype.*"):
  2106. complex(np.array("now", np.datetime64))
  2107. def test__array_interface__descr(self):
  2108. # gh-17068
  2109. dt = np.dtype(dict(names=['a', 'b'],
  2110. offsets=[0, 0],
  2111. formats=[np.int64, np.int64]))
  2112. descr = np.array((1, 1), dtype=dt).__array_interface__['descr']
  2113. assert descr == [('', '|V8')] # instead of [(b'', '|V8')]
  2114. @pytest.mark.skipif(sys.maxsize < 2 ** 31 + 1, reason='overflows 32-bit python')
  2115. @requires_memory(free_bytes=9e9)
  2116. def test_dot_big_stride(self):
  2117. # gh-17111
  2118. # blas stride = stride//itemsize > int32 max
  2119. int32_max = np.iinfo(np.int32).max
  2120. n = int32_max + 3
  2121. a = np.empty([n], dtype=np.float32)
  2122. b = a[::n-1]
  2123. b[...] = 1
  2124. assert b.strides[0] > int32_max * b.dtype.itemsize
  2125. assert np.dot(b, b) == 2.0
  2126. def test_frompyfunc_name(self):
  2127. # name conversion was failing for python 3 strings
  2128. # resulting in the default '?' name. Also test utf-8
  2129. # encoding using non-ascii name.
  2130. def cassé(x):
  2131. return x
  2132. f = np.frompyfunc(cassé, 1, 1)
  2133. assert str(f) == "<ufunc 'cassé (vectorized)'>"
  2134. @pytest.mark.parametrize("operation", [
  2135. 'add', 'subtract', 'multiply', 'floor_divide',
  2136. 'conjugate', 'fmod', 'square', 'reciprocal',
  2137. 'power', 'absolute', 'negative', 'positive',
  2138. 'greater', 'greater_equal', 'less',
  2139. 'less_equal', 'equal', 'not_equal', 'logical_and',
  2140. 'logical_not', 'logical_or', 'bitwise_and', 'bitwise_or',
  2141. 'bitwise_xor', 'invert', 'left_shift', 'right_shift',
  2142. 'gcd', 'lcm'
  2143. ]
  2144. )
  2145. @pytest.mark.parametrize("order", [
  2146. ('b->', 'B->'),
  2147. ('h->', 'H->'),
  2148. ('i->', 'I->'),
  2149. ('l->', 'L->'),
  2150. ('q->', 'Q->'),
  2151. ]
  2152. )
  2153. def test_ufunc_order(self, operation, order):
  2154. # gh-18075
  2155. # Ensure signed types before unsigned
  2156. def get_idx(string, str_lst):
  2157. for i, s in enumerate(str_lst):
  2158. if string in s:
  2159. return i
  2160. raise ValueError(f"{string} not in list")
  2161. types = getattr(np, operation).types
  2162. assert get_idx(order[0], types) < get_idx(order[1], types), (
  2163. f"Unexpected types order of ufunc in {operation}"
  2164. f"for {order}. Possible fix: Use signed before unsigned"
  2165. "in generate_umath.py")