test_nditer.py 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987
  1. import sys
  2. import pytest
  3. import numpy as np
  4. import numpy.core._multiarray_tests as _multiarray_tests
  5. from numpy import array, arange, nditer, all
  6. from numpy.testing import (
  7. assert_, assert_equal, assert_array_equal, assert_raises,
  8. HAS_REFCOUNT, suppress_warnings
  9. )
  10. def iter_multi_index(i):
  11. ret = []
  12. while not i.finished:
  13. ret.append(i.multi_index)
  14. i.iternext()
  15. return ret
  16. def iter_indices(i):
  17. ret = []
  18. while not i.finished:
  19. ret.append(i.index)
  20. i.iternext()
  21. return ret
  22. def iter_iterindices(i):
  23. ret = []
  24. while not i.finished:
  25. ret.append(i.iterindex)
  26. i.iternext()
  27. return ret
  28. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  29. def test_iter_refcount():
  30. # Make sure the iterator doesn't leak
  31. # Basic
  32. a = arange(6)
  33. dt = np.dtype('f4').newbyteorder()
  34. rc_a = sys.getrefcount(a)
  35. rc_dt = sys.getrefcount(dt)
  36. with nditer(a, [],
  37. [['readwrite', 'updateifcopy']],
  38. casting='unsafe',
  39. op_dtypes=[dt]) as it:
  40. assert_(not it.iterationneedsapi)
  41. assert_(sys.getrefcount(a) > rc_a)
  42. assert_(sys.getrefcount(dt) > rc_dt)
  43. # del 'it'
  44. it = None
  45. assert_equal(sys.getrefcount(a), rc_a)
  46. assert_equal(sys.getrefcount(dt), rc_dt)
  47. # With a copy
  48. a = arange(6, dtype='f4')
  49. dt = np.dtype('f4')
  50. rc_a = sys.getrefcount(a)
  51. rc_dt = sys.getrefcount(dt)
  52. it = nditer(a, [],
  53. [['readwrite']],
  54. op_dtypes=[dt])
  55. rc2_a = sys.getrefcount(a)
  56. rc2_dt = sys.getrefcount(dt)
  57. it2 = it.copy()
  58. assert_(sys.getrefcount(a) > rc2_a)
  59. assert_(sys.getrefcount(dt) > rc2_dt)
  60. it = None
  61. assert_equal(sys.getrefcount(a), rc2_a)
  62. assert_equal(sys.getrefcount(dt), rc2_dt)
  63. it2 = None
  64. assert_equal(sys.getrefcount(a), rc_a)
  65. assert_equal(sys.getrefcount(dt), rc_dt)
  66. del it2 # avoid pyflakes unused variable warning
  67. def test_iter_best_order():
  68. # The iterator should always find the iteration order
  69. # with increasing memory addresses
  70. # Test the ordering for 1-D to 5-D shapes
  71. for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]:
  72. a = arange(np.prod(shape))
  73. # Test each combination of positive and negative strides
  74. for dirs in range(2**len(shape)):
  75. dirs_index = [slice(None)]*len(shape)
  76. for bit in range(len(shape)):
  77. if ((2**bit) & dirs):
  78. dirs_index[bit] = slice(None, None, -1)
  79. dirs_index = tuple(dirs_index)
  80. aview = a.reshape(shape)[dirs_index]
  81. # C-order
  82. i = nditer(aview, [], [['readonly']])
  83. assert_equal([x for x in i], a)
  84. # Fortran-order
  85. i = nditer(aview.T, [], [['readonly']])
  86. assert_equal([x for x in i], a)
  87. # Other order
  88. if len(shape) > 2:
  89. i = nditer(aview.swapaxes(0, 1), [], [['readonly']])
  90. assert_equal([x for x in i], a)
  91. def test_iter_c_order():
  92. # Test forcing C order
  93. # Test the ordering for 1-D to 5-D shapes
  94. for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]:
  95. a = arange(np.prod(shape))
  96. # Test each combination of positive and negative strides
  97. for dirs in range(2**len(shape)):
  98. dirs_index = [slice(None)]*len(shape)
  99. for bit in range(len(shape)):
  100. if ((2**bit) & dirs):
  101. dirs_index[bit] = slice(None, None, -1)
  102. dirs_index = tuple(dirs_index)
  103. aview = a.reshape(shape)[dirs_index]
  104. # C-order
  105. i = nditer(aview, order='C')
  106. assert_equal([x for x in i], aview.ravel(order='C'))
  107. # Fortran-order
  108. i = nditer(aview.T, order='C')
  109. assert_equal([x for x in i], aview.T.ravel(order='C'))
  110. # Other order
  111. if len(shape) > 2:
  112. i = nditer(aview.swapaxes(0, 1), order='C')
  113. assert_equal([x for x in i],
  114. aview.swapaxes(0, 1).ravel(order='C'))
  115. def test_iter_f_order():
  116. # Test forcing F order
  117. # Test the ordering for 1-D to 5-D shapes
  118. for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]:
  119. a = arange(np.prod(shape))
  120. # Test each combination of positive and negative strides
  121. for dirs in range(2**len(shape)):
  122. dirs_index = [slice(None)]*len(shape)
  123. for bit in range(len(shape)):
  124. if ((2**bit) & dirs):
  125. dirs_index[bit] = slice(None, None, -1)
  126. dirs_index = tuple(dirs_index)
  127. aview = a.reshape(shape)[dirs_index]
  128. # C-order
  129. i = nditer(aview, order='F')
  130. assert_equal([x for x in i], aview.ravel(order='F'))
  131. # Fortran-order
  132. i = nditer(aview.T, order='F')
  133. assert_equal([x for x in i], aview.T.ravel(order='F'))
  134. # Other order
  135. if len(shape) > 2:
  136. i = nditer(aview.swapaxes(0, 1), order='F')
  137. assert_equal([x for x in i],
  138. aview.swapaxes(0, 1).ravel(order='F'))
  139. def test_iter_c_or_f_order():
  140. # Test forcing any contiguous (C or F) order
  141. # Test the ordering for 1-D to 5-D shapes
  142. for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]:
  143. a = arange(np.prod(shape))
  144. # Test each combination of positive and negative strides
  145. for dirs in range(2**len(shape)):
  146. dirs_index = [slice(None)]*len(shape)
  147. for bit in range(len(shape)):
  148. if ((2**bit) & dirs):
  149. dirs_index[bit] = slice(None, None, -1)
  150. dirs_index = tuple(dirs_index)
  151. aview = a.reshape(shape)[dirs_index]
  152. # C-order
  153. i = nditer(aview, order='A')
  154. assert_equal([x for x in i], aview.ravel(order='A'))
  155. # Fortran-order
  156. i = nditer(aview.T, order='A')
  157. assert_equal([x for x in i], aview.T.ravel(order='A'))
  158. # Other order
  159. if len(shape) > 2:
  160. i = nditer(aview.swapaxes(0, 1), order='A')
  161. assert_equal([x for x in i],
  162. aview.swapaxes(0, 1).ravel(order='A'))
  163. def test_iter_best_order_multi_index_1d():
  164. # The multi-indices should be correct with any reordering
  165. a = arange(4)
  166. # 1D order
  167. i = nditer(a, ['multi_index'], [['readonly']])
  168. assert_equal(iter_multi_index(i), [(0,), (1,), (2,), (3,)])
  169. # 1D reversed order
  170. i = nditer(a[::-1], ['multi_index'], [['readonly']])
  171. assert_equal(iter_multi_index(i), [(3,), (2,), (1,), (0,)])
  172. def test_iter_best_order_multi_index_2d():
  173. # The multi-indices should be correct with any reordering
  174. a = arange(6)
  175. # 2D C-order
  176. i = nditer(a.reshape(2, 3), ['multi_index'], [['readonly']])
  177. assert_equal(iter_multi_index(i), [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)])
  178. # 2D Fortran-order
  179. i = nditer(a.reshape(2, 3).copy(order='F'), ['multi_index'], [['readonly']])
  180. assert_equal(iter_multi_index(i), [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)])
  181. # 2D reversed C-order
  182. i = nditer(a.reshape(2, 3)[::-1], ['multi_index'], [['readonly']])
  183. assert_equal(iter_multi_index(i), [(1, 0), (1, 1), (1, 2), (0, 0), (0, 1), (0, 2)])
  184. i = nditer(a.reshape(2, 3)[:, ::-1], ['multi_index'], [['readonly']])
  185. assert_equal(iter_multi_index(i), [(0, 2), (0, 1), (0, 0), (1, 2), (1, 1), (1, 0)])
  186. i = nditer(a.reshape(2, 3)[::-1, ::-1], ['multi_index'], [['readonly']])
  187. assert_equal(iter_multi_index(i), [(1, 2), (1, 1), (1, 0), (0, 2), (0, 1), (0, 0)])
  188. # 2D reversed Fortran-order
  189. i = nditer(a.reshape(2, 3).copy(order='F')[::-1], ['multi_index'], [['readonly']])
  190. assert_equal(iter_multi_index(i), [(1, 0), (0, 0), (1, 1), (0, 1), (1, 2), (0, 2)])
  191. i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1],
  192. ['multi_index'], [['readonly']])
  193. assert_equal(iter_multi_index(i), [(0, 2), (1, 2), (0, 1), (1, 1), (0, 0), (1, 0)])
  194. i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1],
  195. ['multi_index'], [['readonly']])
  196. assert_equal(iter_multi_index(i), [(1, 2), (0, 2), (1, 1), (0, 1), (1, 0), (0, 0)])
  197. def test_iter_best_order_multi_index_3d():
  198. # The multi-indices should be correct with any reordering
  199. a = arange(12)
  200. # 3D C-order
  201. i = nditer(a.reshape(2, 3, 2), ['multi_index'], [['readonly']])
  202. assert_equal(iter_multi_index(i),
  203. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (0, 2, 0), (0, 2, 1),
  204. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1), (1, 2, 0), (1, 2, 1)])
  205. # 3D Fortran-order
  206. i = nditer(a.reshape(2, 3, 2).copy(order='F'), ['multi_index'], [['readonly']])
  207. assert_equal(iter_multi_index(i),
  208. [(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0),
  209. (0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1), (0, 2, 1), (1, 2, 1)])
  210. # 3D reversed C-order
  211. i = nditer(a.reshape(2, 3, 2)[::-1], ['multi_index'], [['readonly']])
  212. assert_equal(iter_multi_index(i),
  213. [(1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1), (1, 2, 0), (1, 2, 1),
  214. (0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (0, 2, 0), (0, 2, 1)])
  215. i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['multi_index'], [['readonly']])
  216. assert_equal(iter_multi_index(i),
  217. [(0, 2, 0), (0, 2, 1), (0, 1, 0), (0, 1, 1), (0, 0, 0), (0, 0, 1),
  218. (1, 2, 0), (1, 2, 1), (1, 1, 0), (1, 1, 1), (1, 0, 0), (1, 0, 1)])
  219. i = nditer(a.reshape(2, 3, 2)[:,:, ::-1], ['multi_index'], [['readonly']])
  220. assert_equal(iter_multi_index(i),
  221. [(0, 0, 1), (0, 0, 0), (0, 1, 1), (0, 1, 0), (0, 2, 1), (0, 2, 0),
  222. (1, 0, 1), (1, 0, 0), (1, 1, 1), (1, 1, 0), (1, 2, 1), (1, 2, 0)])
  223. # 3D reversed Fortran-order
  224. i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1],
  225. ['multi_index'], [['readonly']])
  226. assert_equal(iter_multi_index(i),
  227. [(1, 0, 0), (0, 0, 0), (1, 1, 0), (0, 1, 0), (1, 2, 0), (0, 2, 0),
  228. (1, 0, 1), (0, 0, 1), (1, 1, 1), (0, 1, 1), (1, 2, 1), (0, 2, 1)])
  229. i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1],
  230. ['multi_index'], [['readonly']])
  231. assert_equal(iter_multi_index(i),
  232. [(0, 2, 0), (1, 2, 0), (0, 1, 0), (1, 1, 0), (0, 0, 0), (1, 0, 0),
  233. (0, 2, 1), (1, 2, 1), (0, 1, 1), (1, 1, 1), (0, 0, 1), (1, 0, 1)])
  234. i = nditer(a.reshape(2, 3, 2).copy(order='F')[:,:, ::-1],
  235. ['multi_index'], [['readonly']])
  236. assert_equal(iter_multi_index(i),
  237. [(0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1), (0, 2, 1), (1, 2, 1),
  238. (0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0)])
  239. def test_iter_best_order_c_index_1d():
  240. # The C index should be correct with any reordering
  241. a = arange(4)
  242. # 1D order
  243. i = nditer(a, ['c_index'], [['readonly']])
  244. assert_equal(iter_indices(i), [0, 1, 2, 3])
  245. # 1D reversed order
  246. i = nditer(a[::-1], ['c_index'], [['readonly']])
  247. assert_equal(iter_indices(i), [3, 2, 1, 0])
  248. def test_iter_best_order_c_index_2d():
  249. # The C index should be correct with any reordering
  250. a = arange(6)
  251. # 2D C-order
  252. i = nditer(a.reshape(2, 3), ['c_index'], [['readonly']])
  253. assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5])
  254. # 2D Fortran-order
  255. i = nditer(a.reshape(2, 3).copy(order='F'),
  256. ['c_index'], [['readonly']])
  257. assert_equal(iter_indices(i), [0, 3, 1, 4, 2, 5])
  258. # 2D reversed C-order
  259. i = nditer(a.reshape(2, 3)[::-1], ['c_index'], [['readonly']])
  260. assert_equal(iter_indices(i), [3, 4, 5, 0, 1, 2])
  261. i = nditer(a.reshape(2, 3)[:, ::-1], ['c_index'], [['readonly']])
  262. assert_equal(iter_indices(i), [2, 1, 0, 5, 4, 3])
  263. i = nditer(a.reshape(2, 3)[::-1, ::-1], ['c_index'], [['readonly']])
  264. assert_equal(iter_indices(i), [5, 4, 3, 2, 1, 0])
  265. # 2D reversed Fortran-order
  266. i = nditer(a.reshape(2, 3).copy(order='F')[::-1],
  267. ['c_index'], [['readonly']])
  268. assert_equal(iter_indices(i), [3, 0, 4, 1, 5, 2])
  269. i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1],
  270. ['c_index'], [['readonly']])
  271. assert_equal(iter_indices(i), [2, 5, 1, 4, 0, 3])
  272. i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1],
  273. ['c_index'], [['readonly']])
  274. assert_equal(iter_indices(i), [5, 2, 4, 1, 3, 0])
  275. def test_iter_best_order_c_index_3d():
  276. # The C index should be correct with any reordering
  277. a = arange(12)
  278. # 3D C-order
  279. i = nditer(a.reshape(2, 3, 2), ['c_index'], [['readonly']])
  280. assert_equal(iter_indices(i),
  281. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  282. # 3D Fortran-order
  283. i = nditer(a.reshape(2, 3, 2).copy(order='F'),
  284. ['c_index'], [['readonly']])
  285. assert_equal(iter_indices(i),
  286. [0, 6, 2, 8, 4, 10, 1, 7, 3, 9, 5, 11])
  287. # 3D reversed C-order
  288. i = nditer(a.reshape(2, 3, 2)[::-1], ['c_index'], [['readonly']])
  289. assert_equal(iter_indices(i),
  290. [6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5])
  291. i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['c_index'], [['readonly']])
  292. assert_equal(iter_indices(i),
  293. [4, 5, 2, 3, 0, 1, 10, 11, 8, 9, 6, 7])
  294. i = nditer(a.reshape(2, 3, 2)[:,:, ::-1], ['c_index'], [['readonly']])
  295. assert_equal(iter_indices(i),
  296. [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10])
  297. # 3D reversed Fortran-order
  298. i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1],
  299. ['c_index'], [['readonly']])
  300. assert_equal(iter_indices(i),
  301. [6, 0, 8, 2, 10, 4, 7, 1, 9, 3, 11, 5])
  302. i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1],
  303. ['c_index'], [['readonly']])
  304. assert_equal(iter_indices(i),
  305. [4, 10, 2, 8, 0, 6, 5, 11, 3, 9, 1, 7])
  306. i = nditer(a.reshape(2, 3, 2).copy(order='F')[:,:, ::-1],
  307. ['c_index'], [['readonly']])
  308. assert_equal(iter_indices(i),
  309. [1, 7, 3, 9, 5, 11, 0, 6, 2, 8, 4, 10])
  310. def test_iter_best_order_f_index_1d():
  311. # The Fortran index should be correct with any reordering
  312. a = arange(4)
  313. # 1D order
  314. i = nditer(a, ['f_index'], [['readonly']])
  315. assert_equal(iter_indices(i), [0, 1, 2, 3])
  316. # 1D reversed order
  317. i = nditer(a[::-1], ['f_index'], [['readonly']])
  318. assert_equal(iter_indices(i), [3, 2, 1, 0])
  319. def test_iter_best_order_f_index_2d():
  320. # The Fortran index should be correct with any reordering
  321. a = arange(6)
  322. # 2D C-order
  323. i = nditer(a.reshape(2, 3), ['f_index'], [['readonly']])
  324. assert_equal(iter_indices(i), [0, 2, 4, 1, 3, 5])
  325. # 2D Fortran-order
  326. i = nditer(a.reshape(2, 3).copy(order='F'),
  327. ['f_index'], [['readonly']])
  328. assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5])
  329. # 2D reversed C-order
  330. i = nditer(a.reshape(2, 3)[::-1], ['f_index'], [['readonly']])
  331. assert_equal(iter_indices(i), [1, 3, 5, 0, 2, 4])
  332. i = nditer(a.reshape(2, 3)[:, ::-1], ['f_index'], [['readonly']])
  333. assert_equal(iter_indices(i), [4, 2, 0, 5, 3, 1])
  334. i = nditer(a.reshape(2, 3)[::-1, ::-1], ['f_index'], [['readonly']])
  335. assert_equal(iter_indices(i), [5, 3, 1, 4, 2, 0])
  336. # 2D reversed Fortran-order
  337. i = nditer(a.reshape(2, 3).copy(order='F')[::-1],
  338. ['f_index'], [['readonly']])
  339. assert_equal(iter_indices(i), [1, 0, 3, 2, 5, 4])
  340. i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1],
  341. ['f_index'], [['readonly']])
  342. assert_equal(iter_indices(i), [4, 5, 2, 3, 0, 1])
  343. i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1],
  344. ['f_index'], [['readonly']])
  345. assert_equal(iter_indices(i), [5, 4, 3, 2, 1, 0])
  346. def test_iter_best_order_f_index_3d():
  347. # The Fortran index should be correct with any reordering
  348. a = arange(12)
  349. # 3D C-order
  350. i = nditer(a.reshape(2, 3, 2), ['f_index'], [['readonly']])
  351. assert_equal(iter_indices(i),
  352. [0, 6, 2, 8, 4, 10, 1, 7, 3, 9, 5, 11])
  353. # 3D Fortran-order
  354. i = nditer(a.reshape(2, 3, 2).copy(order='F'),
  355. ['f_index'], [['readonly']])
  356. assert_equal(iter_indices(i),
  357. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  358. # 3D reversed C-order
  359. i = nditer(a.reshape(2, 3, 2)[::-1], ['f_index'], [['readonly']])
  360. assert_equal(iter_indices(i),
  361. [1, 7, 3, 9, 5, 11, 0, 6, 2, 8, 4, 10])
  362. i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['f_index'], [['readonly']])
  363. assert_equal(iter_indices(i),
  364. [4, 10, 2, 8, 0, 6, 5, 11, 3, 9, 1, 7])
  365. i = nditer(a.reshape(2, 3, 2)[:,:, ::-1], ['f_index'], [['readonly']])
  366. assert_equal(iter_indices(i),
  367. [6, 0, 8, 2, 10, 4, 7, 1, 9, 3, 11, 5])
  368. # 3D reversed Fortran-order
  369. i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1],
  370. ['f_index'], [['readonly']])
  371. assert_equal(iter_indices(i),
  372. [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10])
  373. i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1],
  374. ['f_index'], [['readonly']])
  375. assert_equal(iter_indices(i),
  376. [4, 5, 2, 3, 0, 1, 10, 11, 8, 9, 6, 7])
  377. i = nditer(a.reshape(2, 3, 2).copy(order='F')[:,:, ::-1],
  378. ['f_index'], [['readonly']])
  379. assert_equal(iter_indices(i),
  380. [6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5])
  381. def test_iter_no_inner_full_coalesce():
  382. # Check no_inner iterators which coalesce into a single inner loop
  383. for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]:
  384. size = np.prod(shape)
  385. a = arange(size)
  386. # Test each combination of forward and backwards indexing
  387. for dirs in range(2**len(shape)):
  388. dirs_index = [slice(None)]*len(shape)
  389. for bit in range(len(shape)):
  390. if ((2**bit) & dirs):
  391. dirs_index[bit] = slice(None, None, -1)
  392. dirs_index = tuple(dirs_index)
  393. aview = a.reshape(shape)[dirs_index]
  394. # C-order
  395. i = nditer(aview, ['external_loop'], [['readonly']])
  396. assert_equal(i.ndim, 1)
  397. assert_equal(i[0].shape, (size,))
  398. # Fortran-order
  399. i = nditer(aview.T, ['external_loop'], [['readonly']])
  400. assert_equal(i.ndim, 1)
  401. assert_equal(i[0].shape, (size,))
  402. # Other order
  403. if len(shape) > 2:
  404. i = nditer(aview.swapaxes(0, 1),
  405. ['external_loop'], [['readonly']])
  406. assert_equal(i.ndim, 1)
  407. assert_equal(i[0].shape, (size,))
  408. def test_iter_no_inner_dim_coalescing():
  409. # Check no_inner iterators whose dimensions may not coalesce completely
  410. # Skipping the last element in a dimension prevents coalescing
  411. # with the next-bigger dimension
  412. a = arange(24).reshape(2, 3, 4)[:,:, :-1]
  413. i = nditer(a, ['external_loop'], [['readonly']])
  414. assert_equal(i.ndim, 2)
  415. assert_equal(i[0].shape, (3,))
  416. a = arange(24).reshape(2, 3, 4)[:, :-1,:]
  417. i = nditer(a, ['external_loop'], [['readonly']])
  418. assert_equal(i.ndim, 2)
  419. assert_equal(i[0].shape, (8,))
  420. a = arange(24).reshape(2, 3, 4)[:-1,:,:]
  421. i = nditer(a, ['external_loop'], [['readonly']])
  422. assert_equal(i.ndim, 1)
  423. assert_equal(i[0].shape, (12,))
  424. # Even with lots of 1-sized dimensions, should still coalesce
  425. a = arange(24).reshape(1, 1, 2, 1, 1, 3, 1, 1, 4, 1, 1)
  426. i = nditer(a, ['external_loop'], [['readonly']])
  427. assert_equal(i.ndim, 1)
  428. assert_equal(i[0].shape, (24,))
  429. def test_iter_dim_coalescing():
  430. # Check that the correct number of dimensions are coalesced
  431. # Tracking a multi-index disables coalescing
  432. a = arange(24).reshape(2, 3, 4)
  433. i = nditer(a, ['multi_index'], [['readonly']])
  434. assert_equal(i.ndim, 3)
  435. # A tracked index can allow coalescing if it's compatible with the array
  436. a3d = arange(24).reshape(2, 3, 4)
  437. i = nditer(a3d, ['c_index'], [['readonly']])
  438. assert_equal(i.ndim, 1)
  439. i = nditer(a3d.swapaxes(0, 1), ['c_index'], [['readonly']])
  440. assert_equal(i.ndim, 3)
  441. i = nditer(a3d.T, ['c_index'], [['readonly']])
  442. assert_equal(i.ndim, 3)
  443. i = nditer(a3d.T, ['f_index'], [['readonly']])
  444. assert_equal(i.ndim, 1)
  445. i = nditer(a3d.T.swapaxes(0, 1), ['f_index'], [['readonly']])
  446. assert_equal(i.ndim, 3)
  447. # When C or F order is forced, coalescing may still occur
  448. a3d = arange(24).reshape(2, 3, 4)
  449. i = nditer(a3d, order='C')
  450. assert_equal(i.ndim, 1)
  451. i = nditer(a3d.T, order='C')
  452. assert_equal(i.ndim, 3)
  453. i = nditer(a3d, order='F')
  454. assert_equal(i.ndim, 3)
  455. i = nditer(a3d.T, order='F')
  456. assert_equal(i.ndim, 1)
  457. i = nditer(a3d, order='A')
  458. assert_equal(i.ndim, 1)
  459. i = nditer(a3d.T, order='A')
  460. assert_equal(i.ndim, 1)
  461. def test_iter_broadcasting():
  462. # Standard NumPy broadcasting rules
  463. # 1D with scalar
  464. i = nditer([arange(6), np.int32(2)], ['multi_index'], [['readonly']]*2)
  465. assert_equal(i.itersize, 6)
  466. assert_equal(i.shape, (6,))
  467. # 2D with scalar
  468. i = nditer([arange(6).reshape(2, 3), np.int32(2)],
  469. ['multi_index'], [['readonly']]*2)
  470. assert_equal(i.itersize, 6)
  471. assert_equal(i.shape, (2, 3))
  472. # 2D with 1D
  473. i = nditer([arange(6).reshape(2, 3), arange(3)],
  474. ['multi_index'], [['readonly']]*2)
  475. assert_equal(i.itersize, 6)
  476. assert_equal(i.shape, (2, 3))
  477. i = nditer([arange(2).reshape(2, 1), arange(3)],
  478. ['multi_index'], [['readonly']]*2)
  479. assert_equal(i.itersize, 6)
  480. assert_equal(i.shape, (2, 3))
  481. # 2D with 2D
  482. i = nditer([arange(2).reshape(2, 1), arange(3).reshape(1, 3)],
  483. ['multi_index'], [['readonly']]*2)
  484. assert_equal(i.itersize, 6)
  485. assert_equal(i.shape, (2, 3))
  486. # 3D with scalar
  487. i = nditer([np.int32(2), arange(24).reshape(4, 2, 3)],
  488. ['multi_index'], [['readonly']]*2)
  489. assert_equal(i.itersize, 24)
  490. assert_equal(i.shape, (4, 2, 3))
  491. # 3D with 1D
  492. i = nditer([arange(3), arange(24).reshape(4, 2, 3)],
  493. ['multi_index'], [['readonly']]*2)
  494. assert_equal(i.itersize, 24)
  495. assert_equal(i.shape, (4, 2, 3))
  496. i = nditer([arange(3), arange(8).reshape(4, 2, 1)],
  497. ['multi_index'], [['readonly']]*2)
  498. assert_equal(i.itersize, 24)
  499. assert_equal(i.shape, (4, 2, 3))
  500. # 3D with 2D
  501. i = nditer([arange(6).reshape(2, 3), arange(24).reshape(4, 2, 3)],
  502. ['multi_index'], [['readonly']]*2)
  503. assert_equal(i.itersize, 24)
  504. assert_equal(i.shape, (4, 2, 3))
  505. i = nditer([arange(2).reshape(2, 1), arange(24).reshape(4, 2, 3)],
  506. ['multi_index'], [['readonly']]*2)
  507. assert_equal(i.itersize, 24)
  508. assert_equal(i.shape, (4, 2, 3))
  509. i = nditer([arange(3).reshape(1, 3), arange(8).reshape(4, 2, 1)],
  510. ['multi_index'], [['readonly']]*2)
  511. assert_equal(i.itersize, 24)
  512. assert_equal(i.shape, (4, 2, 3))
  513. # 3D with 3D
  514. i = nditer([arange(2).reshape(1, 2, 1), arange(3).reshape(1, 1, 3),
  515. arange(4).reshape(4, 1, 1)],
  516. ['multi_index'], [['readonly']]*3)
  517. assert_equal(i.itersize, 24)
  518. assert_equal(i.shape, (4, 2, 3))
  519. i = nditer([arange(6).reshape(1, 2, 3), arange(4).reshape(4, 1, 1)],
  520. ['multi_index'], [['readonly']]*2)
  521. assert_equal(i.itersize, 24)
  522. assert_equal(i.shape, (4, 2, 3))
  523. i = nditer([arange(24).reshape(4, 2, 3), arange(12).reshape(4, 1, 3)],
  524. ['multi_index'], [['readonly']]*2)
  525. assert_equal(i.itersize, 24)
  526. assert_equal(i.shape, (4, 2, 3))
  527. def test_iter_itershape():
  528. # Check that allocated outputs work with a specified shape
  529. a = np.arange(6, dtype='i2').reshape(2, 3)
  530. i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']],
  531. op_axes=[[0, 1, None], None],
  532. itershape=(-1, -1, 4))
  533. assert_equal(i.operands[1].shape, (2, 3, 4))
  534. assert_equal(i.operands[1].strides, (24, 8, 2))
  535. i = nditer([a.T, None], [], [['readonly'], ['writeonly', 'allocate']],
  536. op_axes=[[0, 1, None], None],
  537. itershape=(-1, -1, 4))
  538. assert_equal(i.operands[1].shape, (3, 2, 4))
  539. assert_equal(i.operands[1].strides, (8, 24, 2))
  540. i = nditer([a.T, None], [], [['readonly'], ['writeonly', 'allocate']],
  541. order='F',
  542. op_axes=[[0, 1, None], None],
  543. itershape=(-1, -1, 4))
  544. assert_equal(i.operands[1].shape, (3, 2, 4))
  545. assert_equal(i.operands[1].strides, (2, 6, 12))
  546. # If we specify 1 in the itershape, it shouldn't allow broadcasting
  547. # of that dimension to a bigger value
  548. assert_raises(ValueError, nditer, [a, None], [],
  549. [['readonly'], ['writeonly', 'allocate']],
  550. op_axes=[[0, 1, None], None],
  551. itershape=(-1, 1, 4))
  552. # Test bug that for no op_axes but itershape, they are NULLed correctly
  553. i = np.nditer([np.ones(2), None, None], itershape=(2,))
  554. def test_iter_broadcasting_errors():
  555. # Check that errors are thrown for bad broadcasting shapes
  556. # 1D with 1D
  557. assert_raises(ValueError, nditer, [arange(2), arange(3)],
  558. [], [['readonly']]*2)
  559. # 2D with 1D
  560. assert_raises(ValueError, nditer,
  561. [arange(6).reshape(2, 3), arange(2)],
  562. [], [['readonly']]*2)
  563. # 2D with 2D
  564. assert_raises(ValueError, nditer,
  565. [arange(6).reshape(2, 3), arange(9).reshape(3, 3)],
  566. [], [['readonly']]*2)
  567. assert_raises(ValueError, nditer,
  568. [arange(6).reshape(2, 3), arange(4).reshape(2, 2)],
  569. [], [['readonly']]*2)
  570. # 3D with 3D
  571. assert_raises(ValueError, nditer,
  572. [arange(36).reshape(3, 3, 4), arange(24).reshape(2, 3, 4)],
  573. [], [['readonly']]*2)
  574. assert_raises(ValueError, nditer,
  575. [arange(8).reshape(2, 4, 1), arange(24).reshape(2, 3, 4)],
  576. [], [['readonly']]*2)
  577. # Verify that the error message mentions the right shapes
  578. try:
  579. nditer([arange(2).reshape(1, 2, 1),
  580. arange(3).reshape(1, 3),
  581. arange(6).reshape(2, 3)],
  582. [],
  583. [['readonly'], ['readonly'], ['writeonly', 'no_broadcast']])
  584. raise AssertionError('Should have raised a broadcast error')
  585. except ValueError as e:
  586. msg = str(e)
  587. # The message should contain the shape of the 3rd operand
  588. assert_(msg.find('(2,3)') >= 0,
  589. 'Message "%s" doesn\'t contain operand shape (2,3)' % msg)
  590. # The message should contain the broadcast shape
  591. assert_(msg.find('(1,2,3)') >= 0,
  592. 'Message "%s" doesn\'t contain broadcast shape (1,2,3)' % msg)
  593. try:
  594. nditer([arange(6).reshape(2, 3), arange(2)],
  595. [],
  596. [['readonly'], ['readonly']],
  597. op_axes=[[0, 1], [0, np.newaxis]],
  598. itershape=(4, 3))
  599. raise AssertionError('Should have raised a broadcast error')
  600. except ValueError as e:
  601. msg = str(e)
  602. # The message should contain "shape->remappedshape" for each operand
  603. assert_(msg.find('(2,3)->(2,3)') >= 0,
  604. 'Message "%s" doesn\'t contain operand shape (2,3)->(2,3)' % msg)
  605. assert_(msg.find('(2,)->(2,newaxis)') >= 0,
  606. ('Message "%s" doesn\'t contain remapped operand shape' +
  607. '(2,)->(2,newaxis)') % msg)
  608. # The message should contain the itershape parameter
  609. assert_(msg.find('(4,3)') >= 0,
  610. 'Message "%s" doesn\'t contain itershape parameter (4,3)' % msg)
  611. try:
  612. nditer([np.zeros((2, 1, 1)), np.zeros((2,))],
  613. [],
  614. [['writeonly', 'no_broadcast'], ['readonly']])
  615. raise AssertionError('Should have raised a broadcast error')
  616. except ValueError as e:
  617. msg = str(e)
  618. # The message should contain the shape of the bad operand
  619. assert_(msg.find('(2,1,1)') >= 0,
  620. 'Message "%s" doesn\'t contain operand shape (2,1,1)' % msg)
  621. # The message should contain the broadcast shape
  622. assert_(msg.find('(2,1,2)') >= 0,
  623. 'Message "%s" doesn\'t contain the broadcast shape (2,1,2)' % msg)
  624. def test_iter_flags_errors():
  625. # Check that bad combinations of flags produce errors
  626. a = arange(6)
  627. # Not enough operands
  628. assert_raises(ValueError, nditer, [], [], [])
  629. # Too many operands
  630. assert_raises(ValueError, nditer, [a]*100, [], [['readonly']]*100)
  631. # Bad global flag
  632. assert_raises(ValueError, nditer, [a], ['bad flag'], [['readonly']])
  633. # Bad op flag
  634. assert_raises(ValueError, nditer, [a], [], [['readonly', 'bad flag']])
  635. # Bad order parameter
  636. assert_raises(ValueError, nditer, [a], [], [['readonly']], order='G')
  637. # Bad casting parameter
  638. assert_raises(ValueError, nditer, [a], [], [['readonly']], casting='noon')
  639. # op_flags must match ops
  640. assert_raises(ValueError, nditer, [a]*3, [], [['readonly']]*2)
  641. # Cannot track both a C and an F index
  642. assert_raises(ValueError, nditer, a,
  643. ['c_index', 'f_index'], [['readonly']])
  644. # Inner iteration and multi-indices/indices are incompatible
  645. assert_raises(ValueError, nditer, a,
  646. ['external_loop', 'multi_index'], [['readonly']])
  647. assert_raises(ValueError, nditer, a,
  648. ['external_loop', 'c_index'], [['readonly']])
  649. assert_raises(ValueError, nditer, a,
  650. ['external_loop', 'f_index'], [['readonly']])
  651. # Must specify exactly one of readwrite/readonly/writeonly per operand
  652. assert_raises(ValueError, nditer, a, [], [[]])
  653. assert_raises(ValueError, nditer, a, [], [['readonly', 'writeonly']])
  654. assert_raises(ValueError, nditer, a, [], [['readonly', 'readwrite']])
  655. assert_raises(ValueError, nditer, a, [], [['writeonly', 'readwrite']])
  656. assert_raises(ValueError, nditer, a,
  657. [], [['readonly', 'writeonly', 'readwrite']])
  658. # Python scalars are always readonly
  659. assert_raises(TypeError, nditer, 1.5, [], [['writeonly']])
  660. assert_raises(TypeError, nditer, 1.5, [], [['readwrite']])
  661. # Array scalars are always readonly
  662. assert_raises(TypeError, nditer, np.int32(1), [], [['writeonly']])
  663. assert_raises(TypeError, nditer, np.int32(1), [], [['readwrite']])
  664. # Check readonly array
  665. a.flags.writeable = False
  666. assert_raises(ValueError, nditer, a, [], [['writeonly']])
  667. assert_raises(ValueError, nditer, a, [], [['readwrite']])
  668. a.flags.writeable = True
  669. # Multi-indices available only with the multi_index flag
  670. i = nditer(arange(6), [], [['readonly']])
  671. assert_raises(ValueError, lambda i:i.multi_index, i)
  672. # Index available only with an index flag
  673. assert_raises(ValueError, lambda i:i.index, i)
  674. # GotoCoords and GotoIndex incompatible with buffering or no_inner
  675. def assign_multi_index(i):
  676. i.multi_index = (0,)
  677. def assign_index(i):
  678. i.index = 0
  679. def assign_iterindex(i):
  680. i.iterindex = 0
  681. def assign_iterrange(i):
  682. i.iterrange = (0, 1)
  683. i = nditer(arange(6), ['external_loop'])
  684. assert_raises(ValueError, assign_multi_index, i)
  685. assert_raises(ValueError, assign_index, i)
  686. assert_raises(ValueError, assign_iterindex, i)
  687. assert_raises(ValueError, assign_iterrange, i)
  688. i = nditer(arange(6), ['buffered'])
  689. assert_raises(ValueError, assign_multi_index, i)
  690. assert_raises(ValueError, assign_index, i)
  691. assert_raises(ValueError, assign_iterrange, i)
  692. # Can't iterate if size is zero
  693. assert_raises(ValueError, nditer, np.array([]))
  694. def test_iter_slice():
  695. a, b, c = np.arange(3), np.arange(3), np.arange(3.)
  696. i = nditer([a, b, c], [], ['readwrite'])
  697. with i:
  698. i[0:2] = (3, 3)
  699. assert_equal(a, [3, 1, 2])
  700. assert_equal(b, [3, 1, 2])
  701. assert_equal(c, [0, 1, 2])
  702. i[1] = 12
  703. assert_equal(i[0:2], [3, 12])
  704. def test_iter_assign_mapping():
  705. a = np.arange(24, dtype='f8').reshape(2, 3, 4).T
  706. it = np.nditer(a, [], [['readwrite', 'updateifcopy']],
  707. casting='same_kind', op_dtypes=[np.dtype('f4')])
  708. with it:
  709. it.operands[0][...] = 3
  710. it.operands[0][...] = 14
  711. assert_equal(a, 14)
  712. it = np.nditer(a, [], [['readwrite', 'updateifcopy']],
  713. casting='same_kind', op_dtypes=[np.dtype('f4')])
  714. with it:
  715. x = it.operands[0][-1:1]
  716. x[...] = 14
  717. it.operands[0][...] = -1234
  718. assert_equal(a, -1234)
  719. # check for no warnings on dealloc
  720. x = None
  721. it = None
  722. def test_iter_nbo_align_contig():
  723. # Check that byte order, alignment, and contig changes work
  724. # Byte order change by requesting a specific dtype
  725. a = np.arange(6, dtype='f4')
  726. au = a.byteswap().newbyteorder()
  727. assert_(a.dtype.byteorder != au.dtype.byteorder)
  728. i = nditer(au, [], [['readwrite', 'updateifcopy']],
  729. casting='equiv',
  730. op_dtypes=[np.dtype('f4')])
  731. with i:
  732. # context manager triggers UPDATEIFCOPY on i at exit
  733. assert_equal(i.dtypes[0].byteorder, a.dtype.byteorder)
  734. assert_equal(i.operands[0].dtype.byteorder, a.dtype.byteorder)
  735. assert_equal(i.operands[0], a)
  736. i.operands[0][:] = 2
  737. assert_equal(au, [2]*6)
  738. del i # should not raise a warning
  739. # Byte order change by requesting NBO
  740. a = np.arange(6, dtype='f4')
  741. au = a.byteswap().newbyteorder()
  742. assert_(a.dtype.byteorder != au.dtype.byteorder)
  743. with nditer(au, [], [['readwrite', 'updateifcopy', 'nbo']],
  744. casting='equiv') as i:
  745. # context manager triggers UPDATEIFCOPY on i at exit
  746. assert_equal(i.dtypes[0].byteorder, a.dtype.byteorder)
  747. assert_equal(i.operands[0].dtype.byteorder, a.dtype.byteorder)
  748. assert_equal(i.operands[0], a)
  749. i.operands[0][:] = 12345
  750. i.operands[0][:] = 2
  751. assert_equal(au, [2]*6)
  752. # Unaligned input
  753. a = np.zeros((6*4+1,), dtype='i1')[1:]
  754. a.dtype = 'f4'
  755. a[:] = np.arange(6, dtype='f4')
  756. assert_(not a.flags.aligned)
  757. # Without 'aligned', shouldn't copy
  758. i = nditer(a, [], [['readonly']])
  759. assert_(not i.operands[0].flags.aligned)
  760. assert_equal(i.operands[0], a)
  761. # With 'aligned', should make a copy
  762. with nditer(a, [], [['readwrite', 'updateifcopy', 'aligned']]) as i:
  763. assert_(i.operands[0].flags.aligned)
  764. # context manager triggers UPDATEIFCOPY on i at exit
  765. assert_equal(i.operands[0], a)
  766. i.operands[0][:] = 3
  767. assert_equal(a, [3]*6)
  768. # Discontiguous input
  769. a = arange(12)
  770. # If it is contiguous, shouldn't copy
  771. i = nditer(a[:6], [], [['readonly']])
  772. assert_(i.operands[0].flags.contiguous)
  773. assert_equal(i.operands[0], a[:6])
  774. # If it isn't contiguous, should buffer
  775. i = nditer(a[::2], ['buffered', 'external_loop'],
  776. [['readonly', 'contig']],
  777. buffersize=10)
  778. assert_(i[0].flags.contiguous)
  779. assert_equal(i[0], a[::2])
  780. def test_iter_array_cast():
  781. # Check that arrays are cast as requested
  782. # No cast 'f4' -> 'f4'
  783. a = np.arange(6, dtype='f4').reshape(2, 3)
  784. i = nditer(a, [], [['readwrite']], op_dtypes=[np.dtype('f4')])
  785. with i:
  786. assert_equal(i.operands[0], a)
  787. assert_equal(i.operands[0].dtype, np.dtype('f4'))
  788. # Byte-order cast '<f4' -> '>f4'
  789. a = np.arange(6, dtype='<f4').reshape(2, 3)
  790. with nditer(a, [], [['readwrite', 'updateifcopy']],
  791. casting='equiv',
  792. op_dtypes=[np.dtype('>f4')]) as i:
  793. assert_equal(i.operands[0], a)
  794. assert_equal(i.operands[0].dtype, np.dtype('>f4'))
  795. # Safe case 'f4' -> 'f8'
  796. a = np.arange(24, dtype='f4').reshape(2, 3, 4).swapaxes(1, 2)
  797. i = nditer(a, [], [['readonly', 'copy']],
  798. casting='safe',
  799. op_dtypes=[np.dtype('f8')])
  800. assert_equal(i.operands[0], a)
  801. assert_equal(i.operands[0].dtype, np.dtype('f8'))
  802. # The memory layout of the temporary should match a (a is (48,4,16))
  803. # except negative strides get flipped to positive strides.
  804. assert_equal(i.operands[0].strides, (96, 8, 32))
  805. a = a[::-1,:, ::-1]
  806. i = nditer(a, [], [['readonly', 'copy']],
  807. casting='safe',
  808. op_dtypes=[np.dtype('f8')])
  809. assert_equal(i.operands[0], a)
  810. assert_equal(i.operands[0].dtype, np.dtype('f8'))
  811. assert_equal(i.operands[0].strides, (96, 8, 32))
  812. # Same-kind cast 'f8' -> 'f4' -> 'f8'
  813. a = np.arange(24, dtype='f8').reshape(2, 3, 4).T
  814. with nditer(a, [],
  815. [['readwrite', 'updateifcopy']],
  816. casting='same_kind',
  817. op_dtypes=[np.dtype('f4')]) as i:
  818. assert_equal(i.operands[0], a)
  819. assert_equal(i.operands[0].dtype, np.dtype('f4'))
  820. assert_equal(i.operands[0].strides, (4, 16, 48))
  821. # Check that WRITEBACKIFCOPY is activated at exit
  822. i.operands[0][2, 1, 1] = -12.5
  823. assert_(a[2, 1, 1] != -12.5)
  824. assert_equal(a[2, 1, 1], -12.5)
  825. a = np.arange(6, dtype='i4')[::-2]
  826. with nditer(a, [],
  827. [['writeonly', 'updateifcopy']],
  828. casting='unsafe',
  829. op_dtypes=[np.dtype('f4')]) as i:
  830. assert_equal(i.operands[0].dtype, np.dtype('f4'))
  831. # Even though the stride was negative in 'a', it
  832. # becomes positive in the temporary
  833. assert_equal(i.operands[0].strides, (4,))
  834. i.operands[0][:] = [1, 2, 3]
  835. assert_equal(a, [1, 2, 3])
  836. def test_iter_array_cast_errors():
  837. # Check that invalid casts are caught
  838. # Need to enable copying for casts to occur
  839. assert_raises(TypeError, nditer, arange(2, dtype='f4'), [],
  840. [['readonly']], op_dtypes=[np.dtype('f8')])
  841. # Also need to allow casting for casts to occur
  842. assert_raises(TypeError, nditer, arange(2, dtype='f4'), [],
  843. [['readonly', 'copy']], casting='no',
  844. op_dtypes=[np.dtype('f8')])
  845. assert_raises(TypeError, nditer, arange(2, dtype='f4'), [],
  846. [['readonly', 'copy']], casting='equiv',
  847. op_dtypes=[np.dtype('f8')])
  848. assert_raises(TypeError, nditer, arange(2, dtype='f8'), [],
  849. [['writeonly', 'updateifcopy']],
  850. casting='no',
  851. op_dtypes=[np.dtype('f4')])
  852. assert_raises(TypeError, nditer, arange(2, dtype='f8'), [],
  853. [['writeonly', 'updateifcopy']],
  854. casting='equiv',
  855. op_dtypes=[np.dtype('f4')])
  856. # '<f4' -> '>f4' should not work with casting='no'
  857. assert_raises(TypeError, nditer, arange(2, dtype='<f4'), [],
  858. [['readonly', 'copy']], casting='no',
  859. op_dtypes=[np.dtype('>f4')])
  860. # 'f4' -> 'f8' is a safe cast, but 'f8' -> 'f4' isn't
  861. assert_raises(TypeError, nditer, arange(2, dtype='f4'), [],
  862. [['readwrite', 'updateifcopy']],
  863. casting='safe',
  864. op_dtypes=[np.dtype('f8')])
  865. assert_raises(TypeError, nditer, arange(2, dtype='f8'), [],
  866. [['readwrite', 'updateifcopy']],
  867. casting='safe',
  868. op_dtypes=[np.dtype('f4')])
  869. # 'f4' -> 'i4' is neither a safe nor a same-kind cast
  870. assert_raises(TypeError, nditer, arange(2, dtype='f4'), [],
  871. [['readonly', 'copy']],
  872. casting='same_kind',
  873. op_dtypes=[np.dtype('i4')])
  874. assert_raises(TypeError, nditer, arange(2, dtype='i4'), [],
  875. [['writeonly', 'updateifcopy']],
  876. casting='same_kind',
  877. op_dtypes=[np.dtype('f4')])
  878. def test_iter_scalar_cast():
  879. # Check that scalars are cast as requested
  880. # No cast 'f4' -> 'f4'
  881. i = nditer(np.float32(2.5), [], [['readonly']],
  882. op_dtypes=[np.dtype('f4')])
  883. assert_equal(i.dtypes[0], np.dtype('f4'))
  884. assert_equal(i.value.dtype, np.dtype('f4'))
  885. assert_equal(i.value, 2.5)
  886. # Safe cast 'f4' -> 'f8'
  887. i = nditer(np.float32(2.5), [],
  888. [['readonly', 'copy']],
  889. casting='safe',
  890. op_dtypes=[np.dtype('f8')])
  891. assert_equal(i.dtypes[0], np.dtype('f8'))
  892. assert_equal(i.value.dtype, np.dtype('f8'))
  893. assert_equal(i.value, 2.5)
  894. # Same-kind cast 'f8' -> 'f4'
  895. i = nditer(np.float64(2.5), [],
  896. [['readonly', 'copy']],
  897. casting='same_kind',
  898. op_dtypes=[np.dtype('f4')])
  899. assert_equal(i.dtypes[0], np.dtype('f4'))
  900. assert_equal(i.value.dtype, np.dtype('f4'))
  901. assert_equal(i.value, 2.5)
  902. # Unsafe cast 'f8' -> 'i4'
  903. i = nditer(np.float64(3.0), [],
  904. [['readonly', 'copy']],
  905. casting='unsafe',
  906. op_dtypes=[np.dtype('i4')])
  907. assert_equal(i.dtypes[0], np.dtype('i4'))
  908. assert_equal(i.value.dtype, np.dtype('i4'))
  909. assert_equal(i.value, 3)
  910. # Readonly scalars may be cast even without setting COPY or BUFFERED
  911. i = nditer(3, [], [['readonly']], op_dtypes=[np.dtype('f8')])
  912. assert_equal(i[0].dtype, np.dtype('f8'))
  913. assert_equal(i[0], 3.)
  914. def test_iter_scalar_cast_errors():
  915. # Check that invalid casts are caught
  916. # Need to allow copying/buffering for write casts of scalars to occur
  917. assert_raises(TypeError, nditer, np.float32(2), [],
  918. [['readwrite']], op_dtypes=[np.dtype('f8')])
  919. assert_raises(TypeError, nditer, 2.5, [],
  920. [['readwrite']], op_dtypes=[np.dtype('f4')])
  921. # 'f8' -> 'f4' isn't a safe cast if the value would overflow
  922. assert_raises(TypeError, nditer, np.float64(1e60), [],
  923. [['readonly']],
  924. casting='safe',
  925. op_dtypes=[np.dtype('f4')])
  926. # 'f4' -> 'i4' is neither a safe nor a same-kind cast
  927. assert_raises(TypeError, nditer, np.float32(2), [],
  928. [['readonly']],
  929. casting='same_kind',
  930. op_dtypes=[np.dtype('i4')])
  931. def test_iter_object_arrays_basic():
  932. # Check that object arrays work
  933. obj = {'a':3,'b':'d'}
  934. a = np.array([[1, 2, 3], None, obj, None], dtype='O')
  935. if HAS_REFCOUNT:
  936. rc = sys.getrefcount(obj)
  937. # Need to allow references for object arrays
  938. assert_raises(TypeError, nditer, a)
  939. if HAS_REFCOUNT:
  940. assert_equal(sys.getrefcount(obj), rc)
  941. i = nditer(a, ['refs_ok'], ['readonly'])
  942. vals = [x_[()] for x_ in i]
  943. assert_equal(np.array(vals, dtype='O'), a)
  944. vals, i, x = [None]*3
  945. if HAS_REFCOUNT:
  946. assert_equal(sys.getrefcount(obj), rc)
  947. i = nditer(a.reshape(2, 2).T, ['refs_ok', 'buffered'],
  948. ['readonly'], order='C')
  949. assert_(i.iterationneedsapi)
  950. vals = [x_[()] for x_ in i]
  951. assert_equal(np.array(vals, dtype='O'), a.reshape(2, 2).ravel(order='F'))
  952. vals, i, x = [None]*3
  953. if HAS_REFCOUNT:
  954. assert_equal(sys.getrefcount(obj), rc)
  955. i = nditer(a.reshape(2, 2).T, ['refs_ok', 'buffered'],
  956. ['readwrite'], order='C')
  957. with i:
  958. for x in i:
  959. x[...] = None
  960. vals, i, x = [None]*3
  961. if HAS_REFCOUNT:
  962. assert_(sys.getrefcount(obj) == rc-1)
  963. assert_equal(a, np.array([None]*4, dtype='O'))
  964. def test_iter_object_arrays_conversions():
  965. # Conversions to/from objects
  966. a = np.arange(6, dtype='O')
  967. i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'],
  968. casting='unsafe', op_dtypes='i4')
  969. with i:
  970. for x in i:
  971. x[...] += 1
  972. assert_equal(a, np.arange(6)+1)
  973. a = np.arange(6, dtype='i4')
  974. i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'],
  975. casting='unsafe', op_dtypes='O')
  976. with i:
  977. for x in i:
  978. x[...] += 1
  979. assert_equal(a, np.arange(6)+1)
  980. # Non-contiguous object array
  981. a = np.zeros((6,), dtype=[('p', 'i1'), ('a', 'O')])
  982. a = a['a']
  983. a[:] = np.arange(6)
  984. i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'],
  985. casting='unsafe', op_dtypes='i4')
  986. with i:
  987. for x in i:
  988. x[...] += 1
  989. assert_equal(a, np.arange(6)+1)
  990. #Non-contiguous value array
  991. a = np.zeros((6,), dtype=[('p', 'i1'), ('a', 'i4')])
  992. a = a['a']
  993. a[:] = np.arange(6) + 98172488
  994. i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'],
  995. casting='unsafe', op_dtypes='O')
  996. with i:
  997. ob = i[0][()]
  998. if HAS_REFCOUNT:
  999. rc = sys.getrefcount(ob)
  1000. for x in i:
  1001. x[...] += 1
  1002. if HAS_REFCOUNT:
  1003. assert_(sys.getrefcount(ob) == rc-1)
  1004. assert_equal(a, np.arange(6)+98172489)
  1005. def test_iter_common_dtype():
  1006. # Check that the iterator finds a common data type correctly
  1007. i = nditer([array([3], dtype='f4'), array([0], dtype='f8')],
  1008. ['common_dtype'],
  1009. [['readonly', 'copy']]*2,
  1010. casting='safe')
  1011. assert_equal(i.dtypes[0], np.dtype('f8'))
  1012. assert_equal(i.dtypes[1], np.dtype('f8'))
  1013. i = nditer([array([3], dtype='i4'), array([0], dtype='f4')],
  1014. ['common_dtype'],
  1015. [['readonly', 'copy']]*2,
  1016. casting='safe')
  1017. assert_equal(i.dtypes[0], np.dtype('f8'))
  1018. assert_equal(i.dtypes[1], np.dtype('f8'))
  1019. i = nditer([array([3], dtype='f4'), array(0, dtype='f8')],
  1020. ['common_dtype'],
  1021. [['readonly', 'copy']]*2,
  1022. casting='same_kind')
  1023. assert_equal(i.dtypes[0], np.dtype('f4'))
  1024. assert_equal(i.dtypes[1], np.dtype('f4'))
  1025. i = nditer([array([3], dtype='u4'), array(0, dtype='i4')],
  1026. ['common_dtype'],
  1027. [['readonly', 'copy']]*2,
  1028. casting='safe')
  1029. assert_equal(i.dtypes[0], np.dtype('u4'))
  1030. assert_equal(i.dtypes[1], np.dtype('u4'))
  1031. i = nditer([array([3], dtype='u4'), array(-12, dtype='i4')],
  1032. ['common_dtype'],
  1033. [['readonly', 'copy']]*2,
  1034. casting='safe')
  1035. assert_equal(i.dtypes[0], np.dtype('i8'))
  1036. assert_equal(i.dtypes[1], np.dtype('i8'))
  1037. i = nditer([array([3], dtype='u4'), array(-12, dtype='i4'),
  1038. array([2j], dtype='c8'), array([9], dtype='f8')],
  1039. ['common_dtype'],
  1040. [['readonly', 'copy']]*4,
  1041. casting='safe')
  1042. assert_equal(i.dtypes[0], np.dtype('c16'))
  1043. assert_equal(i.dtypes[1], np.dtype('c16'))
  1044. assert_equal(i.dtypes[2], np.dtype('c16'))
  1045. assert_equal(i.dtypes[3], np.dtype('c16'))
  1046. assert_equal(i.value, (3, -12, 2j, 9))
  1047. # When allocating outputs, other outputs aren't factored in
  1048. i = nditer([array([3], dtype='i4'), None, array([2j], dtype='c16')], [],
  1049. [['readonly', 'copy'],
  1050. ['writeonly', 'allocate'],
  1051. ['writeonly']],
  1052. casting='safe')
  1053. assert_equal(i.dtypes[0], np.dtype('i4'))
  1054. assert_equal(i.dtypes[1], np.dtype('i4'))
  1055. assert_equal(i.dtypes[2], np.dtype('c16'))
  1056. # But, if common data types are requested, they are
  1057. i = nditer([array([3], dtype='i4'), None, array([2j], dtype='c16')],
  1058. ['common_dtype'],
  1059. [['readonly', 'copy'],
  1060. ['writeonly', 'allocate'],
  1061. ['writeonly']],
  1062. casting='safe')
  1063. assert_equal(i.dtypes[0], np.dtype('c16'))
  1064. assert_equal(i.dtypes[1], np.dtype('c16'))
  1065. assert_equal(i.dtypes[2], np.dtype('c16'))
  1066. def test_iter_copy_if_overlap():
  1067. # Ensure the iterator makes copies on read/write overlap, if requested
  1068. # Copy not needed, 1 op
  1069. for flag in ['readonly', 'writeonly', 'readwrite']:
  1070. a = arange(10)
  1071. i = nditer([a], ['copy_if_overlap'], [[flag]])
  1072. with i:
  1073. assert_(i.operands[0] is a)
  1074. # Copy needed, 2 ops, read-write overlap
  1075. x = arange(10)
  1076. a = x[1:]
  1077. b = x[:-1]
  1078. with nditer([a, b], ['copy_if_overlap'], [['readonly'], ['readwrite']]) as i:
  1079. assert_(not np.shares_memory(*i.operands))
  1080. # Copy not needed with elementwise, 2 ops, exactly same arrays
  1081. x = arange(10)
  1082. a = x
  1083. b = x
  1084. i = nditer([a, b], ['copy_if_overlap'], [['readonly', 'overlap_assume_elementwise'],
  1085. ['readwrite', 'overlap_assume_elementwise']])
  1086. with i:
  1087. assert_(i.operands[0] is a and i.operands[1] is b)
  1088. with nditer([a, b], ['copy_if_overlap'], [['readonly'], ['readwrite']]) as i:
  1089. assert_(i.operands[0] is a and not np.shares_memory(i.operands[1], b))
  1090. # Copy not needed, 2 ops, no overlap
  1091. x = arange(10)
  1092. a = x[::2]
  1093. b = x[1::2]
  1094. i = nditer([a, b], ['copy_if_overlap'], [['readonly'], ['writeonly']])
  1095. assert_(i.operands[0] is a and i.operands[1] is b)
  1096. # Copy needed, 2 ops, read-write overlap
  1097. x = arange(4, dtype=np.int8)
  1098. a = x[3:]
  1099. b = x.view(np.int32)[:1]
  1100. with nditer([a, b], ['copy_if_overlap'], [['readonly'], ['writeonly']]) as i:
  1101. assert_(not np.shares_memory(*i.operands))
  1102. # Copy needed, 3 ops, read-write overlap
  1103. for flag in ['writeonly', 'readwrite']:
  1104. x = np.ones([10, 10])
  1105. a = x
  1106. b = x.T
  1107. c = x
  1108. with nditer([a, b, c], ['copy_if_overlap'],
  1109. [['readonly'], ['readonly'], [flag]]) as i:
  1110. a2, b2, c2 = i.operands
  1111. assert_(not np.shares_memory(a2, c2))
  1112. assert_(not np.shares_memory(b2, c2))
  1113. # Copy not needed, 3 ops, read-only overlap
  1114. x = np.ones([10, 10])
  1115. a = x
  1116. b = x.T
  1117. c = x
  1118. i = nditer([a, b, c], ['copy_if_overlap'],
  1119. [['readonly'], ['readonly'], ['readonly']])
  1120. a2, b2, c2 = i.operands
  1121. assert_(a is a2)
  1122. assert_(b is b2)
  1123. assert_(c is c2)
  1124. # Copy not needed, 3 ops, read-only overlap
  1125. x = np.ones([10, 10])
  1126. a = x
  1127. b = np.ones([10, 10])
  1128. c = x.T
  1129. i = nditer([a, b, c], ['copy_if_overlap'],
  1130. [['readonly'], ['writeonly'], ['readonly']])
  1131. a2, b2, c2 = i.operands
  1132. assert_(a is a2)
  1133. assert_(b is b2)
  1134. assert_(c is c2)
  1135. # Copy not needed, 3 ops, write-only overlap
  1136. x = np.arange(7)
  1137. a = x[:3]
  1138. b = x[3:6]
  1139. c = x[4:7]
  1140. i = nditer([a, b, c], ['copy_if_overlap'],
  1141. [['readonly'], ['writeonly'], ['writeonly']])
  1142. a2, b2, c2 = i.operands
  1143. assert_(a is a2)
  1144. assert_(b is b2)
  1145. assert_(c is c2)
  1146. def test_iter_op_axes():
  1147. # Check that custom axes work
  1148. # Reverse the axes
  1149. a = arange(6).reshape(2, 3)
  1150. i = nditer([a, a.T], [], [['readonly']]*2, op_axes=[[0, 1], [1, 0]])
  1151. assert_(all([x == y for (x, y) in i]))
  1152. a = arange(24).reshape(2, 3, 4)
  1153. i = nditer([a.T, a], [], [['readonly']]*2, op_axes=[[2, 1, 0], None])
  1154. assert_(all([x == y for (x, y) in i]))
  1155. # Broadcast 1D to any dimension
  1156. a = arange(1, 31).reshape(2, 3, 5)
  1157. b = arange(1, 3)
  1158. i = nditer([a, b], [], [['readonly']]*2, op_axes=[None, [0, -1, -1]])
  1159. assert_equal([x*y for (x, y) in i], (a*b.reshape(2, 1, 1)).ravel())
  1160. b = arange(1, 4)
  1161. i = nditer([a, b], [], [['readonly']]*2, op_axes=[None, [-1, 0, -1]])
  1162. assert_equal([x*y for (x, y) in i], (a*b.reshape(1, 3, 1)).ravel())
  1163. b = arange(1, 6)
  1164. i = nditer([a, b], [], [['readonly']]*2,
  1165. op_axes=[None, [np.newaxis, np.newaxis, 0]])
  1166. assert_equal([x*y for (x, y) in i], (a*b.reshape(1, 1, 5)).ravel())
  1167. # Inner product-style broadcasting
  1168. a = arange(24).reshape(2, 3, 4)
  1169. b = arange(40).reshape(5, 2, 4)
  1170. i = nditer([a, b], ['multi_index'], [['readonly']]*2,
  1171. op_axes=[[0, 1, -1, -1], [-1, -1, 0, 1]])
  1172. assert_equal(i.shape, (2, 3, 5, 2))
  1173. # Matrix product-style broadcasting
  1174. a = arange(12).reshape(3, 4)
  1175. b = arange(20).reshape(4, 5)
  1176. i = nditer([a, b], ['multi_index'], [['readonly']]*2,
  1177. op_axes=[[0, -1], [-1, 1]])
  1178. assert_equal(i.shape, (3, 5))
  1179. def test_iter_op_axes_errors():
  1180. # Check that custom axes throws errors for bad inputs
  1181. # Wrong number of items in op_axes
  1182. a = arange(6).reshape(2, 3)
  1183. assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2,
  1184. op_axes=[[0], [1], [0]])
  1185. # Out of bounds items in op_axes
  1186. assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2,
  1187. op_axes=[[2, 1], [0, 1]])
  1188. assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2,
  1189. op_axes=[[0, 1], [2, -1]])
  1190. # Duplicate items in op_axes
  1191. assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2,
  1192. op_axes=[[0, 0], [0, 1]])
  1193. assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2,
  1194. op_axes=[[0, 1], [1, 1]])
  1195. # Different sized arrays in op_axes
  1196. assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2,
  1197. op_axes=[[0, 1], [0, 1, 0]])
  1198. # Non-broadcastable dimensions in the result
  1199. assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2,
  1200. op_axes=[[0, 1], [1, 0]])
  1201. def test_iter_copy():
  1202. # Check that copying the iterator works correctly
  1203. a = arange(24).reshape(2, 3, 4)
  1204. # Simple iterator
  1205. i = nditer(a)
  1206. j = i.copy()
  1207. assert_equal([x[()] for x in i], [x[()] for x in j])
  1208. i.iterindex = 3
  1209. j = i.copy()
  1210. assert_equal([x[()] for x in i], [x[()] for x in j])
  1211. # Buffered iterator
  1212. i = nditer(a, ['buffered', 'ranged'], order='F', buffersize=3)
  1213. j = i.copy()
  1214. assert_equal([x[()] for x in i], [x[()] for x in j])
  1215. i.iterindex = 3
  1216. j = i.copy()
  1217. assert_equal([x[()] for x in i], [x[()] for x in j])
  1218. i.iterrange = (3, 9)
  1219. j = i.copy()
  1220. assert_equal([x[()] for x in i], [x[()] for x in j])
  1221. i.iterrange = (2, 18)
  1222. next(i)
  1223. next(i)
  1224. j = i.copy()
  1225. assert_equal([x[()] for x in i], [x[()] for x in j])
  1226. # Casting iterator
  1227. with nditer(a, ['buffered'], order='F', casting='unsafe',
  1228. op_dtypes='f8', buffersize=5) as i:
  1229. j = i.copy()
  1230. assert_equal([x[()] for x in j], a.ravel(order='F'))
  1231. a = arange(24, dtype='<i4').reshape(2, 3, 4)
  1232. with nditer(a, ['buffered'], order='F', casting='unsafe',
  1233. op_dtypes='>f8', buffersize=5) as i:
  1234. j = i.copy()
  1235. assert_equal([x[()] for x in j], a.ravel(order='F'))
  1236. def test_iter_allocate_output_simple():
  1237. # Check that the iterator will properly allocate outputs
  1238. # Simple case
  1239. a = arange(6)
  1240. i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']],
  1241. op_dtypes=[None, np.dtype('f4')])
  1242. assert_equal(i.operands[1].shape, a.shape)
  1243. assert_equal(i.operands[1].dtype, np.dtype('f4'))
  1244. def test_iter_allocate_output_buffered_readwrite():
  1245. # Allocated output with buffering + delay_bufalloc
  1246. a = arange(6)
  1247. i = nditer([a, None], ['buffered', 'delay_bufalloc'],
  1248. [['readonly'], ['allocate', 'readwrite']])
  1249. with i:
  1250. i.operands[1][:] = 1
  1251. i.reset()
  1252. for x in i:
  1253. x[1][...] += x[0][...]
  1254. assert_equal(i.operands[1], a+1)
  1255. def test_iter_allocate_output_itorder():
  1256. # The allocated output should match the iteration order
  1257. # C-order input, best iteration order
  1258. a = arange(6, dtype='i4').reshape(2, 3)
  1259. i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']],
  1260. op_dtypes=[None, np.dtype('f4')])
  1261. assert_equal(i.operands[1].shape, a.shape)
  1262. assert_equal(i.operands[1].strides, a.strides)
  1263. assert_equal(i.operands[1].dtype, np.dtype('f4'))
  1264. # F-order input, best iteration order
  1265. a = arange(24, dtype='i4').reshape(2, 3, 4).T
  1266. i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']],
  1267. op_dtypes=[None, np.dtype('f4')])
  1268. assert_equal(i.operands[1].shape, a.shape)
  1269. assert_equal(i.operands[1].strides, a.strides)
  1270. assert_equal(i.operands[1].dtype, np.dtype('f4'))
  1271. # Non-contiguous input, C iteration order
  1272. a = arange(24, dtype='i4').reshape(2, 3, 4).swapaxes(0, 1)
  1273. i = nditer([a, None], [],
  1274. [['readonly'], ['writeonly', 'allocate']],
  1275. order='C',
  1276. op_dtypes=[None, np.dtype('f4')])
  1277. assert_equal(i.operands[1].shape, a.shape)
  1278. assert_equal(i.operands[1].strides, (32, 16, 4))
  1279. assert_equal(i.operands[1].dtype, np.dtype('f4'))
  1280. def test_iter_allocate_output_opaxes():
  1281. # Specifying op_axes should work
  1282. a = arange(24, dtype='i4').reshape(2, 3, 4)
  1283. i = nditer([None, a], [], [['writeonly', 'allocate'], ['readonly']],
  1284. op_dtypes=[np.dtype('u4'), None],
  1285. op_axes=[[1, 2, 0], None])
  1286. assert_equal(i.operands[0].shape, (4, 2, 3))
  1287. assert_equal(i.operands[0].strides, (4, 48, 16))
  1288. assert_equal(i.operands[0].dtype, np.dtype('u4'))
  1289. def test_iter_allocate_output_types_promotion():
  1290. # Check type promotion of automatic outputs
  1291. i = nditer([array([3], dtype='f4'), array([0], dtype='f8'), None], [],
  1292. [['readonly']]*2+[['writeonly', 'allocate']])
  1293. assert_equal(i.dtypes[2], np.dtype('f8'))
  1294. i = nditer([array([3], dtype='i4'), array([0], dtype='f4'), None], [],
  1295. [['readonly']]*2+[['writeonly', 'allocate']])
  1296. assert_equal(i.dtypes[2], np.dtype('f8'))
  1297. i = nditer([array([3], dtype='f4'), array(0, dtype='f8'), None], [],
  1298. [['readonly']]*2+[['writeonly', 'allocate']])
  1299. assert_equal(i.dtypes[2], np.dtype('f4'))
  1300. i = nditer([array([3], dtype='u4'), array(0, dtype='i4'), None], [],
  1301. [['readonly']]*2+[['writeonly', 'allocate']])
  1302. assert_equal(i.dtypes[2], np.dtype('u4'))
  1303. i = nditer([array([3], dtype='u4'), array(-12, dtype='i4'), None], [],
  1304. [['readonly']]*2+[['writeonly', 'allocate']])
  1305. assert_equal(i.dtypes[2], np.dtype('i8'))
  1306. def test_iter_allocate_output_types_byte_order():
  1307. # Verify the rules for byte order changes
  1308. # When there's just one input, the output type exactly matches
  1309. a = array([3], dtype='u4').newbyteorder()
  1310. i = nditer([a, None], [],
  1311. [['readonly'], ['writeonly', 'allocate']])
  1312. assert_equal(i.dtypes[0], i.dtypes[1])
  1313. # With two or more inputs, the output type is in native byte order
  1314. i = nditer([a, a, None], [],
  1315. [['readonly'], ['readonly'], ['writeonly', 'allocate']])
  1316. assert_(i.dtypes[0] != i.dtypes[2])
  1317. assert_equal(i.dtypes[0].newbyteorder('='), i.dtypes[2])
  1318. def test_iter_allocate_output_types_scalar():
  1319. # If the inputs are all scalars, the output should be a scalar
  1320. i = nditer([None, 1, 2.3, np.float32(12), np.complex128(3)], [],
  1321. [['writeonly', 'allocate']] + [['readonly']]*4)
  1322. assert_equal(i.operands[0].dtype, np.dtype('complex128'))
  1323. assert_equal(i.operands[0].ndim, 0)
  1324. def test_iter_allocate_output_subtype():
  1325. # Make sure that the subtype with priority wins
  1326. class MyNDArray(np.ndarray):
  1327. __array_priority__ = 15
  1328. # subclass vs ndarray
  1329. a = np.array([[1, 2], [3, 4]]).view(MyNDArray)
  1330. b = np.arange(4).reshape(2, 2).T
  1331. i = nditer([a, b, None], [],
  1332. [['readonly'], ['readonly'], ['writeonly', 'allocate']])
  1333. assert_equal(type(a), type(i.operands[2]))
  1334. assert_(type(b) is not type(i.operands[2]))
  1335. assert_equal(i.operands[2].shape, (2, 2))
  1336. # If subtypes are disabled, we should get back an ndarray.
  1337. i = nditer([a, b, None], [],
  1338. [['readonly'], ['readonly'],
  1339. ['writeonly', 'allocate', 'no_subtype']])
  1340. assert_equal(type(b), type(i.operands[2]))
  1341. assert_(type(a) is not type(i.operands[2]))
  1342. assert_equal(i.operands[2].shape, (2, 2))
  1343. def test_iter_allocate_output_errors():
  1344. # Check that the iterator will throw errors for bad output allocations
  1345. # Need an input if no output data type is specified
  1346. a = arange(6)
  1347. assert_raises(TypeError, nditer, [a, None], [],
  1348. [['writeonly'], ['writeonly', 'allocate']])
  1349. # Allocated output should be flagged for writing
  1350. assert_raises(ValueError, nditer, [a, None], [],
  1351. [['readonly'], ['allocate', 'readonly']])
  1352. # Allocated output can't have buffering without delayed bufalloc
  1353. assert_raises(ValueError, nditer, [a, None], ['buffered'],
  1354. ['allocate', 'readwrite'])
  1355. # Must specify at least one input
  1356. assert_raises(ValueError, nditer, [None, None], [],
  1357. [['writeonly', 'allocate'],
  1358. ['writeonly', 'allocate']],
  1359. op_dtypes=[np.dtype('f4'), np.dtype('f4')])
  1360. # If using op_axes, must specify all the axes
  1361. a = arange(24, dtype='i4').reshape(2, 3, 4)
  1362. assert_raises(ValueError, nditer, [a, None], [],
  1363. [['readonly'], ['writeonly', 'allocate']],
  1364. op_dtypes=[None, np.dtype('f4')],
  1365. op_axes=[None, [0, np.newaxis, 1]])
  1366. # If using op_axes, the axes must be within bounds
  1367. assert_raises(ValueError, nditer, [a, None], [],
  1368. [['readonly'], ['writeonly', 'allocate']],
  1369. op_dtypes=[None, np.dtype('f4')],
  1370. op_axes=[None, [0, 3, 1]])
  1371. # If using op_axes, there can't be duplicates
  1372. assert_raises(ValueError, nditer, [a, None], [],
  1373. [['readonly'], ['writeonly', 'allocate']],
  1374. op_dtypes=[None, np.dtype('f4')],
  1375. op_axes=[None, [0, 2, 1, 0]])
  1376. # Not all axes may be specified if a reduction. If there is a hole
  1377. # in op_axes, this is an error.
  1378. a = arange(24, dtype='i4').reshape(2, 3, 4)
  1379. assert_raises(ValueError, nditer, [a, None], ["reduce_ok"],
  1380. [['readonly'], ['readwrite', 'allocate']],
  1381. op_dtypes=[None, np.dtype('f4')],
  1382. op_axes=[None, [0, np.newaxis, 2]])
  1383. def test_iter_remove_axis():
  1384. a = arange(24).reshape(2, 3, 4)
  1385. i = nditer(a, ['multi_index'])
  1386. i.remove_axis(1)
  1387. assert_equal([x for x in i], a[:, 0,:].ravel())
  1388. a = a[::-1,:,:]
  1389. i = nditer(a, ['multi_index'])
  1390. i.remove_axis(0)
  1391. assert_equal([x for x in i], a[0,:,:].ravel())
  1392. def test_iter_remove_multi_index_inner_loop():
  1393. # Check that removing multi-index support works
  1394. a = arange(24).reshape(2, 3, 4)
  1395. i = nditer(a, ['multi_index'])
  1396. assert_equal(i.ndim, 3)
  1397. assert_equal(i.shape, (2, 3, 4))
  1398. assert_equal(i.itviews[0].shape, (2, 3, 4))
  1399. # Removing the multi-index tracking causes all dimensions to coalesce
  1400. before = [x for x in i]
  1401. i.remove_multi_index()
  1402. after = [x for x in i]
  1403. assert_equal(before, after)
  1404. assert_equal(i.ndim, 1)
  1405. assert_raises(ValueError, lambda i:i.shape, i)
  1406. assert_equal(i.itviews[0].shape, (24,))
  1407. # Removing the inner loop means there's just one iteration
  1408. i.reset()
  1409. assert_equal(i.itersize, 24)
  1410. assert_equal(i[0].shape, tuple())
  1411. i.enable_external_loop()
  1412. assert_equal(i.itersize, 24)
  1413. assert_equal(i[0].shape, (24,))
  1414. assert_equal(i.value, arange(24))
  1415. def test_iter_iterindex():
  1416. # Make sure iterindex works
  1417. buffersize = 5
  1418. a = arange(24).reshape(4, 3, 2)
  1419. for flags in ([], ['buffered']):
  1420. i = nditer(a, flags, buffersize=buffersize)
  1421. assert_equal(iter_iterindices(i), list(range(24)))
  1422. i.iterindex = 2
  1423. assert_equal(iter_iterindices(i), list(range(2, 24)))
  1424. i = nditer(a, flags, order='F', buffersize=buffersize)
  1425. assert_equal(iter_iterindices(i), list(range(24)))
  1426. i.iterindex = 5
  1427. assert_equal(iter_iterindices(i), list(range(5, 24)))
  1428. i = nditer(a[::-1], flags, order='F', buffersize=buffersize)
  1429. assert_equal(iter_iterindices(i), list(range(24)))
  1430. i.iterindex = 9
  1431. assert_equal(iter_iterindices(i), list(range(9, 24)))
  1432. i = nditer(a[::-1, ::-1], flags, order='C', buffersize=buffersize)
  1433. assert_equal(iter_iterindices(i), list(range(24)))
  1434. i.iterindex = 13
  1435. assert_equal(iter_iterindices(i), list(range(13, 24)))
  1436. i = nditer(a[::1, ::-1], flags, buffersize=buffersize)
  1437. assert_equal(iter_iterindices(i), list(range(24)))
  1438. i.iterindex = 23
  1439. assert_equal(iter_iterindices(i), list(range(23, 24)))
  1440. i.reset()
  1441. i.iterindex = 2
  1442. assert_equal(iter_iterindices(i), list(range(2, 24)))
  1443. def test_iter_iterrange():
  1444. # Make sure getting and resetting the iterrange works
  1445. buffersize = 5
  1446. a = arange(24, dtype='i4').reshape(4, 3, 2)
  1447. a_fort = a.ravel(order='F')
  1448. i = nditer(a, ['ranged'], ['readonly'], order='F',
  1449. buffersize=buffersize)
  1450. assert_equal(i.iterrange, (0, 24))
  1451. assert_equal([x[()] for x in i], a_fort)
  1452. for r in [(0, 24), (1, 2), (3, 24), (5, 5), (0, 20), (23, 24)]:
  1453. i.iterrange = r
  1454. assert_equal(i.iterrange, r)
  1455. assert_equal([x[()] for x in i], a_fort[r[0]:r[1]])
  1456. i = nditer(a, ['ranged', 'buffered'], ['readonly'], order='F',
  1457. op_dtypes='f8', buffersize=buffersize)
  1458. assert_equal(i.iterrange, (0, 24))
  1459. assert_equal([x[()] for x in i], a_fort)
  1460. for r in [(0, 24), (1, 2), (3, 24), (5, 5), (0, 20), (23, 24)]:
  1461. i.iterrange = r
  1462. assert_equal(i.iterrange, r)
  1463. assert_equal([x[()] for x in i], a_fort[r[0]:r[1]])
  1464. def get_array(i):
  1465. val = np.array([], dtype='f8')
  1466. for x in i:
  1467. val = np.concatenate((val, x))
  1468. return val
  1469. i = nditer(a, ['ranged', 'buffered', 'external_loop'],
  1470. ['readonly'], order='F',
  1471. op_dtypes='f8', buffersize=buffersize)
  1472. assert_equal(i.iterrange, (0, 24))
  1473. assert_equal(get_array(i), a_fort)
  1474. for r in [(0, 24), (1, 2), (3, 24), (5, 5), (0, 20), (23, 24)]:
  1475. i.iterrange = r
  1476. assert_equal(i.iterrange, r)
  1477. assert_equal(get_array(i), a_fort[r[0]:r[1]])
  1478. def test_iter_buffering():
  1479. # Test buffering with several buffer sizes and types
  1480. arrays = []
  1481. # F-order swapped array
  1482. arrays.append(np.arange(24,
  1483. dtype='c16').reshape(2, 3, 4).T.newbyteorder().byteswap())
  1484. # Contiguous 1-dimensional array
  1485. arrays.append(np.arange(10, dtype='f4'))
  1486. # Unaligned array
  1487. a = np.zeros((4*16+1,), dtype='i1')[1:]
  1488. a.dtype = 'i4'
  1489. a[:] = np.arange(16, dtype='i4')
  1490. arrays.append(a)
  1491. # 4-D F-order array
  1492. arrays.append(np.arange(120, dtype='i4').reshape(5, 3, 2, 4).T)
  1493. for a in arrays:
  1494. for buffersize in (1, 2, 3, 5, 8, 11, 16, 1024):
  1495. vals = []
  1496. i = nditer(a, ['buffered', 'external_loop'],
  1497. [['readonly', 'nbo', 'aligned']],
  1498. order='C',
  1499. casting='equiv',
  1500. buffersize=buffersize)
  1501. while not i.finished:
  1502. assert_(i[0].size <= buffersize)
  1503. vals.append(i[0].copy())
  1504. i.iternext()
  1505. assert_equal(np.concatenate(vals), a.ravel(order='C'))
  1506. def test_iter_write_buffering():
  1507. # Test that buffering of writes is working
  1508. # F-order swapped array
  1509. a = np.arange(24).reshape(2, 3, 4).T.newbyteorder().byteswap()
  1510. i = nditer(a, ['buffered'],
  1511. [['readwrite', 'nbo', 'aligned']],
  1512. casting='equiv',
  1513. order='C',
  1514. buffersize=16)
  1515. x = 0
  1516. with i:
  1517. while not i.finished:
  1518. i[0] = x
  1519. x += 1
  1520. i.iternext()
  1521. assert_equal(a.ravel(order='C'), np.arange(24))
  1522. def test_iter_buffering_delayed_alloc():
  1523. # Test that delaying buffer allocation works
  1524. a = np.arange(6)
  1525. b = np.arange(1, dtype='f4')
  1526. i = nditer([a, b], ['buffered', 'delay_bufalloc', 'multi_index', 'reduce_ok'],
  1527. ['readwrite'],
  1528. casting='unsafe',
  1529. op_dtypes='f4')
  1530. assert_(i.has_delayed_bufalloc)
  1531. assert_raises(ValueError, lambda i:i.multi_index, i)
  1532. assert_raises(ValueError, lambda i:i[0], i)
  1533. assert_raises(ValueError, lambda i:i[0:2], i)
  1534. def assign_iter(i):
  1535. i[0] = 0
  1536. assert_raises(ValueError, assign_iter, i)
  1537. i.reset()
  1538. assert_(not i.has_delayed_bufalloc)
  1539. assert_equal(i.multi_index, (0,))
  1540. with i:
  1541. assert_equal(i[0], 0)
  1542. i[1] = 1
  1543. assert_equal(i[0:2], [0, 1])
  1544. assert_equal([[x[0][()], x[1][()]] for x in i], list(zip(range(6), [1]*6)))
  1545. def test_iter_buffered_cast_simple():
  1546. # Test that buffering can handle a simple cast
  1547. a = np.arange(10, dtype='f4')
  1548. i = nditer(a, ['buffered', 'external_loop'],
  1549. [['readwrite', 'nbo', 'aligned']],
  1550. casting='same_kind',
  1551. op_dtypes=[np.dtype('f8')],
  1552. buffersize=3)
  1553. with i:
  1554. for v in i:
  1555. v[...] *= 2
  1556. assert_equal(a, 2*np.arange(10, dtype='f4'))
  1557. def test_iter_buffered_cast_byteswapped():
  1558. # Test that buffering can handle a cast which requires swap->cast->swap
  1559. a = np.arange(10, dtype='f4').newbyteorder().byteswap()
  1560. i = nditer(a, ['buffered', 'external_loop'],
  1561. [['readwrite', 'nbo', 'aligned']],
  1562. casting='same_kind',
  1563. op_dtypes=[np.dtype('f8').newbyteorder()],
  1564. buffersize=3)
  1565. with i:
  1566. for v in i:
  1567. v[...] *= 2
  1568. assert_equal(a, 2*np.arange(10, dtype='f4'))
  1569. with suppress_warnings() as sup:
  1570. sup.filter(np.ComplexWarning)
  1571. a = np.arange(10, dtype='f8').newbyteorder().byteswap()
  1572. i = nditer(a, ['buffered', 'external_loop'],
  1573. [['readwrite', 'nbo', 'aligned']],
  1574. casting='unsafe',
  1575. op_dtypes=[np.dtype('c8').newbyteorder()],
  1576. buffersize=3)
  1577. with i:
  1578. for v in i:
  1579. v[...] *= 2
  1580. assert_equal(a, 2*np.arange(10, dtype='f8'))
  1581. def test_iter_buffered_cast_byteswapped_complex():
  1582. # Test that buffering can handle a cast which requires swap->cast->copy
  1583. a = np.arange(10, dtype='c8').newbyteorder().byteswap()
  1584. a += 2j
  1585. i = nditer(a, ['buffered', 'external_loop'],
  1586. [['readwrite', 'nbo', 'aligned']],
  1587. casting='same_kind',
  1588. op_dtypes=[np.dtype('c16')],
  1589. buffersize=3)
  1590. with i:
  1591. for v in i:
  1592. v[...] *= 2
  1593. assert_equal(a, 2*np.arange(10, dtype='c8') + 4j)
  1594. a = np.arange(10, dtype='c8')
  1595. a += 2j
  1596. i = nditer(a, ['buffered', 'external_loop'],
  1597. [['readwrite', 'nbo', 'aligned']],
  1598. casting='same_kind',
  1599. op_dtypes=[np.dtype('c16').newbyteorder()],
  1600. buffersize=3)
  1601. with i:
  1602. for v in i:
  1603. v[...] *= 2
  1604. assert_equal(a, 2*np.arange(10, dtype='c8') + 4j)
  1605. a = np.arange(10, dtype=np.clongdouble).newbyteorder().byteswap()
  1606. a += 2j
  1607. i = nditer(a, ['buffered', 'external_loop'],
  1608. [['readwrite', 'nbo', 'aligned']],
  1609. casting='same_kind',
  1610. op_dtypes=[np.dtype('c16')],
  1611. buffersize=3)
  1612. with i:
  1613. for v in i:
  1614. v[...] *= 2
  1615. assert_equal(a, 2*np.arange(10, dtype=np.clongdouble) + 4j)
  1616. a = np.arange(10, dtype=np.longdouble).newbyteorder().byteswap()
  1617. i = nditer(a, ['buffered', 'external_loop'],
  1618. [['readwrite', 'nbo', 'aligned']],
  1619. casting='same_kind',
  1620. op_dtypes=[np.dtype('f4')],
  1621. buffersize=7)
  1622. with i:
  1623. for v in i:
  1624. v[...] *= 2
  1625. assert_equal(a, 2*np.arange(10, dtype=np.longdouble))
  1626. def test_iter_buffered_cast_structured_type():
  1627. # Tests buffering of structured types
  1628. # simple -> struct type (duplicates the value)
  1629. sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')]
  1630. a = np.arange(3, dtype='f4') + 0.5
  1631. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1632. casting='unsafe',
  1633. op_dtypes=sdt)
  1634. vals = [np.array(x) for x in i]
  1635. assert_equal(vals[0]['a'], 0.5)
  1636. assert_equal(vals[0]['b'], 0)
  1637. assert_equal(vals[0]['c'], [[(0.5)]*3]*2)
  1638. assert_equal(vals[0]['d'], 0.5)
  1639. assert_equal(vals[1]['a'], 1.5)
  1640. assert_equal(vals[1]['b'], 1)
  1641. assert_equal(vals[1]['c'], [[(1.5)]*3]*2)
  1642. assert_equal(vals[1]['d'], 1.5)
  1643. assert_equal(vals[0].dtype, np.dtype(sdt))
  1644. # object -> struct type
  1645. sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')]
  1646. a = np.zeros((3,), dtype='O')
  1647. a[0] = (0.5, 0.5, [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5]], 0.5)
  1648. a[1] = (1.5, 1.5, [[1.5, 1.5, 1.5], [1.5, 1.5, 1.5]], 1.5)
  1649. a[2] = (2.5, 2.5, [[2.5, 2.5, 2.5], [2.5, 2.5, 2.5]], 2.5)
  1650. if HAS_REFCOUNT:
  1651. rc = sys.getrefcount(a[0])
  1652. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1653. casting='unsafe',
  1654. op_dtypes=sdt)
  1655. vals = [x.copy() for x in i]
  1656. assert_equal(vals[0]['a'], 0.5)
  1657. assert_equal(vals[0]['b'], 0)
  1658. assert_equal(vals[0]['c'], [[(0.5)]*3]*2)
  1659. assert_equal(vals[0]['d'], 0.5)
  1660. assert_equal(vals[1]['a'], 1.5)
  1661. assert_equal(vals[1]['b'], 1)
  1662. assert_equal(vals[1]['c'], [[(1.5)]*3]*2)
  1663. assert_equal(vals[1]['d'], 1.5)
  1664. assert_equal(vals[0].dtype, np.dtype(sdt))
  1665. vals, i, x = [None]*3
  1666. if HAS_REFCOUNT:
  1667. assert_equal(sys.getrefcount(a[0]), rc)
  1668. # single-field struct type -> simple
  1669. sdt = [('a', 'f4')]
  1670. a = np.array([(5.5,), (8,)], dtype=sdt)
  1671. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1672. casting='unsafe',
  1673. op_dtypes='i4')
  1674. assert_equal([x_[()] for x_ in i], [5, 8])
  1675. # make sure multi-field struct type -> simple doesn't work
  1676. sdt = [('a', 'f4'), ('b', 'i8'), ('d', 'O')]
  1677. a = np.array([(5.5, 7, 'test'), (8, 10, 11)], dtype=sdt)
  1678. assert_raises(TypeError, lambda: (
  1679. nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1680. casting='unsafe',
  1681. op_dtypes='i4')))
  1682. # struct type -> struct type (field-wise copy)
  1683. sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', 'O')]
  1684. sdt2 = [('d', 'u2'), ('a', 'O'), ('b', 'f8')]
  1685. a = np.array([(1, 2, 3), (4, 5, 6)], dtype=sdt1)
  1686. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1687. casting='unsafe',
  1688. op_dtypes=sdt2)
  1689. assert_equal(i[0].dtype, np.dtype(sdt2))
  1690. assert_equal([np.array(x_) for x_ in i],
  1691. [np.array((1, 2, 3), dtype=sdt2),
  1692. np.array((4, 5, 6), dtype=sdt2)])
  1693. # make sure struct type -> struct type with different
  1694. # number of fields fails
  1695. sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', 'O')]
  1696. sdt2 = [('b', 'O'), ('a', 'f8')]
  1697. a = np.array([(1, 2, 3), (4, 5, 6)], dtype=sdt1)
  1698. assert_raises(ValueError, lambda : (
  1699. nditer(a, ['buffered', 'refs_ok'], ['readwrite'],
  1700. casting='unsafe',
  1701. op_dtypes=sdt2)))
  1702. def test_iter_buffered_cast_subarray():
  1703. # Tests buffering of subarrays
  1704. # one element -> many (copies it to all)
  1705. sdt1 = [('a', 'f4')]
  1706. sdt2 = [('a', 'f8', (3, 2, 2))]
  1707. a = np.zeros((6,), dtype=sdt1)
  1708. a['a'] = np.arange(6)
  1709. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1710. casting='unsafe',
  1711. op_dtypes=sdt2)
  1712. assert_equal(i[0].dtype, np.dtype(sdt2))
  1713. for x, count in zip(i, list(range(6))):
  1714. assert_(np.all(x['a'] == count))
  1715. # one element -> many -> back (copies it to all)
  1716. sdt1 = [('a', 'O', (1, 1))]
  1717. sdt2 = [('a', 'O', (3, 2, 2))]
  1718. a = np.zeros((6,), dtype=sdt1)
  1719. a['a'][:, 0, 0] = np.arange(6)
  1720. i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'],
  1721. casting='unsafe',
  1722. op_dtypes=sdt2)
  1723. with i:
  1724. assert_equal(i[0].dtype, np.dtype(sdt2))
  1725. count = 0
  1726. for x in i:
  1727. assert_(np.all(x['a'] == count))
  1728. x['a'][0] += 2
  1729. count += 1
  1730. assert_equal(a['a'], np.arange(6).reshape(6, 1, 1)+2)
  1731. # many -> one element -> back (copies just element 0)
  1732. sdt1 = [('a', 'O', (3, 2, 2))]
  1733. sdt2 = [('a', 'O', (1,))]
  1734. a = np.zeros((6,), dtype=sdt1)
  1735. a['a'][:, 0, 0, 0] = np.arange(6)
  1736. i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'],
  1737. casting='unsafe',
  1738. op_dtypes=sdt2)
  1739. with i:
  1740. assert_equal(i[0].dtype, np.dtype(sdt2))
  1741. count = 0
  1742. for x in i:
  1743. assert_equal(x['a'], count)
  1744. x['a'] += 2
  1745. count += 1
  1746. assert_equal(a['a'], np.arange(6).reshape(6, 1, 1, 1)*np.ones((1, 3, 2, 2))+2)
  1747. # many -> one element -> back (copies just element 0)
  1748. sdt1 = [('a', 'f8', (3, 2, 2))]
  1749. sdt2 = [('a', 'O', (1,))]
  1750. a = np.zeros((6,), dtype=sdt1)
  1751. a['a'][:, 0, 0, 0] = np.arange(6)
  1752. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1753. casting='unsafe',
  1754. op_dtypes=sdt2)
  1755. assert_equal(i[0].dtype, np.dtype(sdt2))
  1756. count = 0
  1757. for x in i:
  1758. assert_equal(x['a'], count)
  1759. count += 1
  1760. # many -> one element (copies just element 0)
  1761. sdt1 = [('a', 'O', (3, 2, 2))]
  1762. sdt2 = [('a', 'f4', (1,))]
  1763. a = np.zeros((6,), dtype=sdt1)
  1764. a['a'][:, 0, 0, 0] = np.arange(6)
  1765. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1766. casting='unsafe',
  1767. op_dtypes=sdt2)
  1768. assert_equal(i[0].dtype, np.dtype(sdt2))
  1769. count = 0
  1770. for x in i:
  1771. assert_equal(x['a'], count)
  1772. count += 1
  1773. # many -> matching shape (straightforward copy)
  1774. sdt1 = [('a', 'O', (3, 2, 2))]
  1775. sdt2 = [('a', 'f4', (3, 2, 2))]
  1776. a = np.zeros((6,), dtype=sdt1)
  1777. a['a'] = np.arange(6*3*2*2).reshape(6, 3, 2, 2)
  1778. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1779. casting='unsafe',
  1780. op_dtypes=sdt2)
  1781. assert_equal(i[0].dtype, np.dtype(sdt2))
  1782. count = 0
  1783. for x in i:
  1784. assert_equal(x['a'], a[count]['a'])
  1785. count += 1
  1786. # vector -> smaller vector (truncates)
  1787. sdt1 = [('a', 'f8', (6,))]
  1788. sdt2 = [('a', 'f4', (2,))]
  1789. a = np.zeros((6,), dtype=sdt1)
  1790. a['a'] = np.arange(6*6).reshape(6, 6)
  1791. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1792. casting='unsafe',
  1793. op_dtypes=sdt2)
  1794. assert_equal(i[0].dtype, np.dtype(sdt2))
  1795. count = 0
  1796. for x in i:
  1797. assert_equal(x['a'], a[count]['a'][:2])
  1798. count += 1
  1799. # vector -> bigger vector (pads with zeros)
  1800. sdt1 = [('a', 'f8', (2,))]
  1801. sdt2 = [('a', 'f4', (6,))]
  1802. a = np.zeros((6,), dtype=sdt1)
  1803. a['a'] = np.arange(6*2).reshape(6, 2)
  1804. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1805. casting='unsafe',
  1806. op_dtypes=sdt2)
  1807. assert_equal(i[0].dtype, np.dtype(sdt2))
  1808. count = 0
  1809. for x in i:
  1810. assert_equal(x['a'][:2], a[count]['a'])
  1811. assert_equal(x['a'][2:], [0, 0, 0, 0])
  1812. count += 1
  1813. # vector -> matrix (broadcasts)
  1814. sdt1 = [('a', 'f8', (2,))]
  1815. sdt2 = [('a', 'f4', (2, 2))]
  1816. a = np.zeros((6,), dtype=sdt1)
  1817. a['a'] = np.arange(6*2).reshape(6, 2)
  1818. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1819. casting='unsafe',
  1820. op_dtypes=sdt2)
  1821. assert_equal(i[0].dtype, np.dtype(sdt2))
  1822. count = 0
  1823. for x in i:
  1824. assert_equal(x['a'][0], a[count]['a'])
  1825. assert_equal(x['a'][1], a[count]['a'])
  1826. count += 1
  1827. # vector -> matrix (broadcasts and zero-pads)
  1828. sdt1 = [('a', 'f8', (2, 1))]
  1829. sdt2 = [('a', 'f4', (3, 2))]
  1830. a = np.zeros((6,), dtype=sdt1)
  1831. a['a'] = np.arange(6*2).reshape(6, 2, 1)
  1832. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1833. casting='unsafe',
  1834. op_dtypes=sdt2)
  1835. assert_equal(i[0].dtype, np.dtype(sdt2))
  1836. count = 0
  1837. for x in i:
  1838. assert_equal(x['a'][:2, 0], a[count]['a'][:, 0])
  1839. assert_equal(x['a'][:2, 1], a[count]['a'][:, 0])
  1840. assert_equal(x['a'][2,:], [0, 0])
  1841. count += 1
  1842. # matrix -> matrix (truncates and zero-pads)
  1843. sdt1 = [('a', 'f8', (2, 3))]
  1844. sdt2 = [('a', 'f4', (3, 2))]
  1845. a = np.zeros((6,), dtype=sdt1)
  1846. a['a'] = np.arange(6*2*3).reshape(6, 2, 3)
  1847. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  1848. casting='unsafe',
  1849. op_dtypes=sdt2)
  1850. assert_equal(i[0].dtype, np.dtype(sdt2))
  1851. count = 0
  1852. for x in i:
  1853. assert_equal(x['a'][:2, 0], a[count]['a'][:, 0])
  1854. assert_equal(x['a'][:2, 1], a[count]['a'][:, 1])
  1855. assert_equal(x['a'][2,:], [0, 0])
  1856. count += 1
  1857. def test_iter_buffering_badwriteback():
  1858. # Writing back from a buffer cannot combine elements
  1859. # a needs write buffering, but had a broadcast dimension
  1860. a = np.arange(6).reshape(2, 3, 1)
  1861. b = np.arange(12).reshape(2, 3, 2)
  1862. assert_raises(ValueError, nditer, [a, b],
  1863. ['buffered', 'external_loop'],
  1864. [['readwrite'], ['writeonly']],
  1865. order='C')
  1866. # But if a is readonly, it's fine
  1867. nditer([a, b], ['buffered', 'external_loop'],
  1868. [['readonly'], ['writeonly']],
  1869. order='C')
  1870. # If a has just one element, it's fine too (constant 0 stride, a reduction)
  1871. a = np.arange(1).reshape(1, 1, 1)
  1872. nditer([a, b], ['buffered', 'external_loop', 'reduce_ok'],
  1873. [['readwrite'], ['writeonly']],
  1874. order='C')
  1875. # check that it fails on other dimensions too
  1876. a = np.arange(6).reshape(1, 3, 2)
  1877. assert_raises(ValueError, nditer, [a, b],
  1878. ['buffered', 'external_loop'],
  1879. [['readwrite'], ['writeonly']],
  1880. order='C')
  1881. a = np.arange(4).reshape(2, 1, 2)
  1882. assert_raises(ValueError, nditer, [a, b],
  1883. ['buffered', 'external_loop'],
  1884. [['readwrite'], ['writeonly']],
  1885. order='C')
  1886. def test_iter_buffering_string():
  1887. # Safe casting disallows shrinking strings
  1888. a = np.array(['abc', 'a', 'abcd'], dtype=np.bytes_)
  1889. assert_equal(a.dtype, np.dtype('S4'))
  1890. assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'],
  1891. op_dtypes='S2')
  1892. i = nditer(a, ['buffered'], ['readonly'], op_dtypes='S6')
  1893. assert_equal(i[0], b'abc')
  1894. assert_equal(i[0].dtype, np.dtype('S6'))
  1895. a = np.array(['abc', 'a', 'abcd'], dtype=np.unicode_)
  1896. assert_equal(a.dtype, np.dtype('U4'))
  1897. assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'],
  1898. op_dtypes='U2')
  1899. i = nditer(a, ['buffered'], ['readonly'], op_dtypes='U6')
  1900. assert_equal(i[0], u'abc')
  1901. assert_equal(i[0].dtype, np.dtype('U6'))
  1902. def test_iter_buffering_growinner():
  1903. # Test that the inner loop grows when no buffering is needed
  1904. a = np.arange(30)
  1905. i = nditer(a, ['buffered', 'growinner', 'external_loop'],
  1906. buffersize=5)
  1907. # Should end up with just one inner loop here
  1908. assert_equal(i[0].size, a.size)
  1909. @pytest.mark.slow
  1910. def test_iter_buffered_reduce_reuse():
  1911. # large enough array for all views, including negative strides.
  1912. a = np.arange(2*3**5)[3**5:3**5+1]
  1913. flags = ['buffered', 'delay_bufalloc', 'multi_index', 'reduce_ok', 'refs_ok']
  1914. op_flags = [('readonly',), ('readwrite', 'allocate')]
  1915. op_axes_list = [[(0, 1, 2), (0, 1, -1)], [(0, 1, 2), (0, -1, -1)]]
  1916. # wrong dtype to force buffering
  1917. op_dtypes = [float, a.dtype]
  1918. def get_params():
  1919. for xs in range(-3**2, 3**2 + 1):
  1920. for ys in range(xs, 3**2 + 1):
  1921. for op_axes in op_axes_list:
  1922. # last stride is reduced and because of that not
  1923. # important for this test, as it is the inner stride.
  1924. strides = (xs * a.itemsize, ys * a.itemsize, a.itemsize)
  1925. arr = np.lib.stride_tricks.as_strided(a, (3, 3, 3), strides)
  1926. for skip in [0, 1]:
  1927. yield arr, op_axes, skip
  1928. for arr, op_axes, skip in get_params():
  1929. nditer2 = np.nditer([arr.copy(), None],
  1930. op_axes=op_axes, flags=flags, op_flags=op_flags,
  1931. op_dtypes=op_dtypes)
  1932. with nditer2:
  1933. nditer2.operands[-1][...] = 0
  1934. nditer2.reset()
  1935. nditer2.iterindex = skip
  1936. for (a2_in, b2_in) in nditer2:
  1937. b2_in += a2_in.astype(np.int_)
  1938. comp_res = nditer2.operands[-1]
  1939. for bufsize in range(0, 3**3):
  1940. nditer1 = np.nditer([arr, None],
  1941. op_axes=op_axes, flags=flags, op_flags=op_flags,
  1942. buffersize=bufsize, op_dtypes=op_dtypes)
  1943. with nditer1:
  1944. nditer1.operands[-1][...] = 0
  1945. nditer1.reset()
  1946. nditer1.iterindex = skip
  1947. for (a1_in, b1_in) in nditer1:
  1948. b1_in += a1_in.astype(np.int_)
  1949. res = nditer1.operands[-1]
  1950. assert_array_equal(res, comp_res)
  1951. def test_iter_no_broadcast():
  1952. # Test that the no_broadcast flag works
  1953. a = np.arange(24).reshape(2, 3, 4)
  1954. b = np.arange(6).reshape(2, 3, 1)
  1955. c = np.arange(12).reshape(3, 4)
  1956. nditer([a, b, c], [],
  1957. [['readonly', 'no_broadcast'],
  1958. ['readonly'], ['readonly']])
  1959. assert_raises(ValueError, nditer, [a, b, c], [],
  1960. [['readonly'], ['readonly', 'no_broadcast'], ['readonly']])
  1961. assert_raises(ValueError, nditer, [a, b, c], [],
  1962. [['readonly'], ['readonly'], ['readonly', 'no_broadcast']])
  1963. class TestIterNested:
  1964. def test_basic(self):
  1965. # Test nested iteration basic usage
  1966. a = arange(12).reshape(2, 3, 2)
  1967. i, j = np.nested_iters(a, [[0], [1, 2]])
  1968. vals = [list(j) for _ in i]
  1969. assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
  1970. i, j = np.nested_iters(a, [[0, 1], [2]])
  1971. vals = [list(j) for _ in i]
  1972. assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]])
  1973. i, j = np.nested_iters(a, [[0, 2], [1]])
  1974. vals = [list(j) for _ in i]
  1975. assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
  1976. def test_reorder(self):
  1977. # Test nested iteration basic usage
  1978. a = arange(12).reshape(2, 3, 2)
  1979. # In 'K' order (default), it gets reordered
  1980. i, j = np.nested_iters(a, [[0], [2, 1]])
  1981. vals = [list(j) for _ in i]
  1982. assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
  1983. i, j = np.nested_iters(a, [[1, 0], [2]])
  1984. vals = [list(j) for _ in i]
  1985. assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]])
  1986. i, j = np.nested_iters(a, [[2, 0], [1]])
  1987. vals = [list(j) for _ in i]
  1988. assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
  1989. # In 'C' order, it doesn't
  1990. i, j = np.nested_iters(a, [[0], [2, 1]], order='C')
  1991. vals = [list(j) for _ in i]
  1992. assert_equal(vals, [[0, 2, 4, 1, 3, 5], [6, 8, 10, 7, 9, 11]])
  1993. i, j = np.nested_iters(a, [[1, 0], [2]], order='C')
  1994. vals = [list(j) for _ in i]
  1995. assert_equal(vals, [[0, 1], [6, 7], [2, 3], [8, 9], [4, 5], [10, 11]])
  1996. i, j = np.nested_iters(a, [[2, 0], [1]], order='C')
  1997. vals = [list(j) for _ in i]
  1998. assert_equal(vals, [[0, 2, 4], [6, 8, 10], [1, 3, 5], [7, 9, 11]])
  1999. def test_flip_axes(self):
  2000. # Test nested iteration with negative axes
  2001. a = arange(12).reshape(2, 3, 2)[::-1, ::-1, ::-1]
  2002. # In 'K' order (default), the axes all get flipped
  2003. i, j = np.nested_iters(a, [[0], [1, 2]])
  2004. vals = [list(j) for _ in i]
  2005. assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
  2006. i, j = np.nested_iters(a, [[0, 1], [2]])
  2007. vals = [list(j) for _ in i]
  2008. assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]])
  2009. i, j = np.nested_iters(a, [[0, 2], [1]])
  2010. vals = [list(j) for _ in i]
  2011. assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
  2012. # In 'C' order, flipping axes is disabled
  2013. i, j = np.nested_iters(a, [[0], [1, 2]], order='C')
  2014. vals = [list(j) for _ in i]
  2015. assert_equal(vals, [[11, 10, 9, 8, 7, 6], [5, 4, 3, 2, 1, 0]])
  2016. i, j = np.nested_iters(a, [[0, 1], [2]], order='C')
  2017. vals = [list(j) for _ in i]
  2018. assert_equal(vals, [[11, 10], [9, 8], [7, 6], [5, 4], [3, 2], [1, 0]])
  2019. i, j = np.nested_iters(a, [[0, 2], [1]], order='C')
  2020. vals = [list(j) for _ in i]
  2021. assert_equal(vals, [[11, 9, 7], [10, 8, 6], [5, 3, 1], [4, 2, 0]])
  2022. def test_broadcast(self):
  2023. # Test nested iteration with broadcasting
  2024. a = arange(2).reshape(2, 1)
  2025. b = arange(3).reshape(1, 3)
  2026. i, j = np.nested_iters([a, b], [[0], [1]])
  2027. vals = [list(j) for _ in i]
  2028. assert_equal(vals, [[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]]])
  2029. i, j = np.nested_iters([a, b], [[1], [0]])
  2030. vals = [list(j) for _ in i]
  2031. assert_equal(vals, [[[0, 0], [1, 0]], [[0, 1], [1, 1]], [[0, 2], [1, 2]]])
  2032. def test_dtype_copy(self):
  2033. # Test nested iteration with a copy to change dtype
  2034. # copy
  2035. a = arange(6, dtype='i4').reshape(2, 3)
  2036. i, j = np.nested_iters(a, [[0], [1]],
  2037. op_flags=['readonly', 'copy'],
  2038. op_dtypes='f8')
  2039. assert_equal(j[0].dtype, np.dtype('f8'))
  2040. vals = [list(j) for _ in i]
  2041. assert_equal(vals, [[0, 1, 2], [3, 4, 5]])
  2042. vals = None
  2043. # writebackifcopy - using context manager
  2044. a = arange(6, dtype='f4').reshape(2, 3)
  2045. i, j = np.nested_iters(a, [[0], [1]],
  2046. op_flags=['readwrite', 'updateifcopy'],
  2047. casting='same_kind',
  2048. op_dtypes='f8')
  2049. with i, j:
  2050. assert_equal(j[0].dtype, np.dtype('f8'))
  2051. for x in i:
  2052. for y in j:
  2053. y[...] += 1
  2054. assert_equal(a, [[0, 1, 2], [3, 4, 5]])
  2055. assert_equal(a, [[1, 2, 3], [4, 5, 6]])
  2056. # writebackifcopy - using close()
  2057. a = arange(6, dtype='f4').reshape(2, 3)
  2058. i, j = np.nested_iters(a, [[0], [1]],
  2059. op_flags=['readwrite', 'updateifcopy'],
  2060. casting='same_kind',
  2061. op_dtypes='f8')
  2062. assert_equal(j[0].dtype, np.dtype('f8'))
  2063. for x in i:
  2064. for y in j:
  2065. y[...] += 1
  2066. assert_equal(a, [[0, 1, 2], [3, 4, 5]])
  2067. i.close()
  2068. j.close()
  2069. assert_equal(a, [[1, 2, 3], [4, 5, 6]])
  2070. def test_dtype_buffered(self):
  2071. # Test nested iteration with buffering to change dtype
  2072. a = arange(6, dtype='f4').reshape(2, 3)
  2073. i, j = np.nested_iters(a, [[0], [1]],
  2074. flags=['buffered'],
  2075. op_flags=['readwrite'],
  2076. casting='same_kind',
  2077. op_dtypes='f8')
  2078. assert_equal(j[0].dtype, np.dtype('f8'))
  2079. for x in i:
  2080. for y in j:
  2081. y[...] += 1
  2082. assert_equal(a, [[1, 2, 3], [4, 5, 6]])
  2083. def test_0d(self):
  2084. a = np.arange(12).reshape(2, 3, 2)
  2085. i, j = np.nested_iters(a, [[], [1, 0, 2]])
  2086. vals = [list(j) for _ in i]
  2087. assert_equal(vals, [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])
  2088. i, j = np.nested_iters(a, [[1, 0, 2], []])
  2089. vals = [list(j) for _ in i]
  2090. assert_equal(vals, [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]])
  2091. i, j, k = np.nested_iters(a, [[2, 0], [], [1]])
  2092. vals = []
  2093. for x in i:
  2094. for y in j:
  2095. vals.append([z for z in k])
  2096. assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
  2097. def test_iter_nested_iters_dtype_buffered(self):
  2098. # Test nested iteration with buffering to change dtype
  2099. a = arange(6, dtype='f4').reshape(2, 3)
  2100. i, j = np.nested_iters(a, [[0], [1]],
  2101. flags=['buffered'],
  2102. op_flags=['readwrite'],
  2103. casting='same_kind',
  2104. op_dtypes='f8')
  2105. with i, j:
  2106. assert_equal(j[0].dtype, np.dtype('f8'))
  2107. for x in i:
  2108. for y in j:
  2109. y[...] += 1
  2110. assert_equal(a, [[1, 2, 3], [4, 5, 6]])
  2111. def test_iter_reduction_error():
  2112. a = np.arange(6)
  2113. assert_raises(ValueError, nditer, [a, None], [],
  2114. [['readonly'], ['readwrite', 'allocate']],
  2115. op_axes=[[0], [-1]])
  2116. a = np.arange(6).reshape(2, 3)
  2117. assert_raises(ValueError, nditer, [a, None], ['external_loop'],
  2118. [['readonly'], ['readwrite', 'allocate']],
  2119. op_axes=[[0, 1], [-1, -1]])
  2120. def test_iter_reduction():
  2121. # Test doing reductions with the iterator
  2122. a = np.arange(6)
  2123. i = nditer([a, None], ['reduce_ok'],
  2124. [['readonly'], ['readwrite', 'allocate']],
  2125. op_axes=[[0], [-1]])
  2126. # Need to initialize the output operand to the addition unit
  2127. with i:
  2128. i.operands[1][...] = 0
  2129. # Do the reduction
  2130. for x, y in i:
  2131. y[...] += x
  2132. # Since no axes were specified, should have allocated a scalar
  2133. assert_equal(i.operands[1].ndim, 0)
  2134. assert_equal(i.operands[1], np.sum(a))
  2135. a = np.arange(6).reshape(2, 3)
  2136. i = nditer([a, None], ['reduce_ok', 'external_loop'],
  2137. [['readonly'], ['readwrite', 'allocate']],
  2138. op_axes=[[0, 1], [-1, -1]])
  2139. # Need to initialize the output operand to the addition unit
  2140. with i:
  2141. i.operands[1][...] = 0
  2142. # Reduction shape/strides for the output
  2143. assert_equal(i[1].shape, (6,))
  2144. assert_equal(i[1].strides, (0,))
  2145. # Do the reduction
  2146. for x, y in i:
  2147. # Use a for loop instead of ``y[...] += x``
  2148. # (equivalent to ``y[...] = y[...].copy() + x``),
  2149. # because y has zero strides we use for the reduction
  2150. for j in range(len(y)):
  2151. y[j] += x[j]
  2152. # Since no axes were specified, should have allocated a scalar
  2153. assert_equal(i.operands[1].ndim, 0)
  2154. assert_equal(i.operands[1], np.sum(a))
  2155. # This is a tricky reduction case for the buffering double loop
  2156. # to handle
  2157. a = np.ones((2, 3, 5))
  2158. it1 = nditer([a, None], ['reduce_ok', 'external_loop'],
  2159. [['readonly'], ['readwrite', 'allocate']],
  2160. op_axes=[None, [0, -1, 1]])
  2161. it2 = nditer([a, None], ['reduce_ok', 'external_loop',
  2162. 'buffered', 'delay_bufalloc'],
  2163. [['readonly'], ['readwrite', 'allocate']],
  2164. op_axes=[None, [0, -1, 1]], buffersize=10)
  2165. with it1, it2:
  2166. it1.operands[1].fill(0)
  2167. it2.operands[1].fill(0)
  2168. it2.reset()
  2169. for x in it1:
  2170. x[1][...] += x[0]
  2171. for x in it2:
  2172. x[1][...] += x[0]
  2173. assert_equal(it1.operands[1], it2.operands[1])
  2174. assert_equal(it2.operands[1].sum(), a.size)
  2175. def test_iter_buffering_reduction():
  2176. # Test doing buffered reductions with the iterator
  2177. a = np.arange(6)
  2178. b = np.array(0., dtype='f8').byteswap().newbyteorder()
  2179. i = nditer([a, b], ['reduce_ok', 'buffered'],
  2180. [['readonly'], ['readwrite', 'nbo']],
  2181. op_axes=[[0], [-1]])
  2182. with i:
  2183. assert_equal(i[1].dtype, np.dtype('f8'))
  2184. assert_(i[1].dtype != b.dtype)
  2185. # Do the reduction
  2186. for x, y in i:
  2187. y[...] += x
  2188. # Since no axes were specified, should have allocated a scalar
  2189. assert_equal(b, np.sum(a))
  2190. a = np.arange(6).reshape(2, 3)
  2191. b = np.array([0, 0], dtype='f8').byteswap().newbyteorder()
  2192. i = nditer([a, b], ['reduce_ok', 'external_loop', 'buffered'],
  2193. [['readonly'], ['readwrite', 'nbo']],
  2194. op_axes=[[0, 1], [0, -1]])
  2195. # Reduction shape/strides for the output
  2196. with i:
  2197. assert_equal(i[1].shape, (3,))
  2198. assert_equal(i[1].strides, (0,))
  2199. # Do the reduction
  2200. for x, y in i:
  2201. # Use a for loop instead of ``y[...] += x``
  2202. # (equivalent to ``y[...] = y[...].copy() + x``),
  2203. # because y has zero strides we use for the reduction
  2204. for j in range(len(y)):
  2205. y[j] += x[j]
  2206. assert_equal(b, np.sum(a, axis=1))
  2207. # Iterator inner double loop was wrong on this one
  2208. p = np.arange(2) + 1
  2209. it = np.nditer([p, None],
  2210. ['delay_bufalloc', 'reduce_ok', 'buffered', 'external_loop'],
  2211. [['readonly'], ['readwrite', 'allocate']],
  2212. op_axes=[[-1, 0], [-1, -1]],
  2213. itershape=(2, 2))
  2214. with it:
  2215. it.operands[1].fill(0)
  2216. it.reset()
  2217. assert_equal(it[0], [1, 2, 1, 2])
  2218. # Iterator inner loop should take argument contiguity into account
  2219. x = np.ones((7, 13, 8), np.int8)[4:6,1:11:6,1:5].transpose(1, 2, 0)
  2220. x[...] = np.arange(x.size).reshape(x.shape)
  2221. y_base = np.arange(4*4, dtype=np.int8).reshape(4, 4)
  2222. y_base_copy = y_base.copy()
  2223. y = y_base[::2,:,None]
  2224. it = np.nditer([y, x],
  2225. ['buffered', 'external_loop', 'reduce_ok'],
  2226. [['readwrite'], ['readonly']])
  2227. with it:
  2228. for a, b in it:
  2229. a.fill(2)
  2230. assert_equal(y_base[1::2], y_base_copy[1::2])
  2231. assert_equal(y_base[::2], 2)
  2232. def test_iter_buffering_reduction_reuse_reduce_loops():
  2233. # There was a bug triggering reuse of the reduce loop inappropriately,
  2234. # which caused processing to happen in unnecessarily small chunks
  2235. # and overran the buffer.
  2236. a = np.zeros((2, 7))
  2237. b = np.zeros((1, 7))
  2238. it = np.nditer([a, b], flags=['reduce_ok', 'external_loop', 'buffered'],
  2239. op_flags=[['readonly'], ['readwrite']],
  2240. buffersize=5)
  2241. with it:
  2242. bufsizes = [x.shape[0] for x, y in it]
  2243. assert_equal(bufsizes, [5, 2, 5, 2])
  2244. assert_equal(sum(bufsizes), a.size)
  2245. def test_iter_writemasked_badinput():
  2246. a = np.zeros((2, 3))
  2247. b = np.zeros((3,))
  2248. m = np.array([[True, True, False], [False, True, False]])
  2249. m2 = np.array([True, True, False])
  2250. m3 = np.array([0, 1, 1], dtype='u1')
  2251. mbad1 = np.array([0, 1, 1], dtype='i1')
  2252. mbad2 = np.array([0, 1, 1], dtype='f4')
  2253. # Need an 'arraymask' if any operand is 'writemasked'
  2254. assert_raises(ValueError, nditer, [a, m], [],
  2255. [['readwrite', 'writemasked'], ['readonly']])
  2256. # A 'writemasked' operand must not be readonly
  2257. assert_raises(ValueError, nditer, [a, m], [],
  2258. [['readonly', 'writemasked'], ['readonly', 'arraymask']])
  2259. # 'writemasked' and 'arraymask' may not be used together
  2260. assert_raises(ValueError, nditer, [a, m], [],
  2261. [['readonly'], ['readwrite', 'arraymask', 'writemasked']])
  2262. # 'arraymask' may only be specified once
  2263. assert_raises(ValueError, nditer, [a, m, m2], [],
  2264. [['readwrite', 'writemasked'],
  2265. ['readonly', 'arraymask'],
  2266. ['readonly', 'arraymask']])
  2267. # An 'arraymask' with nothing 'writemasked' also doesn't make sense
  2268. assert_raises(ValueError, nditer, [a, m], [],
  2269. [['readwrite'], ['readonly', 'arraymask']])
  2270. # A writemasked reduction requires a similarly smaller mask
  2271. assert_raises(ValueError, nditer, [a, b, m], ['reduce_ok'],
  2272. [['readonly'],
  2273. ['readwrite', 'writemasked'],
  2274. ['readonly', 'arraymask']])
  2275. # But this should work with a smaller/equal mask to the reduction operand
  2276. np.nditer([a, b, m2], ['reduce_ok'],
  2277. [['readonly'],
  2278. ['readwrite', 'writemasked'],
  2279. ['readonly', 'arraymask']])
  2280. # The arraymask itself cannot be a reduction
  2281. assert_raises(ValueError, nditer, [a, b, m2], ['reduce_ok'],
  2282. [['readonly'],
  2283. ['readwrite', 'writemasked'],
  2284. ['readwrite', 'arraymask']])
  2285. # A uint8 mask is ok too
  2286. np.nditer([a, m3], ['buffered'],
  2287. [['readwrite', 'writemasked'],
  2288. ['readonly', 'arraymask']],
  2289. op_dtypes=['f4', None],
  2290. casting='same_kind')
  2291. # An int8 mask isn't ok
  2292. assert_raises(TypeError, np.nditer, [a, mbad1], ['buffered'],
  2293. [['readwrite', 'writemasked'],
  2294. ['readonly', 'arraymask']],
  2295. op_dtypes=['f4', None],
  2296. casting='same_kind')
  2297. # A float32 mask isn't ok
  2298. assert_raises(TypeError, np.nditer, [a, mbad2], ['buffered'],
  2299. [['readwrite', 'writemasked'],
  2300. ['readonly', 'arraymask']],
  2301. op_dtypes=['f4', None],
  2302. casting='same_kind')
  2303. def test_iter_writemasked():
  2304. a = np.zeros((3,), dtype='f8')
  2305. msk = np.array([True, True, False])
  2306. # When buffering is unused, 'writemasked' effectively does nothing.
  2307. # It's up to the user of the iterator to obey the requested semantics.
  2308. it = np.nditer([a, msk], [],
  2309. [['readwrite', 'writemasked'],
  2310. ['readonly', 'arraymask']])
  2311. with it:
  2312. for x, m in it:
  2313. x[...] = 1
  2314. # Because we violated the semantics, all the values became 1
  2315. assert_equal(a, [1, 1, 1])
  2316. # Even if buffering is enabled, we still may be accessing the array
  2317. # directly.
  2318. it = np.nditer([a, msk], ['buffered'],
  2319. [['readwrite', 'writemasked'],
  2320. ['readonly', 'arraymask']])
  2321. with it:
  2322. for x, m in it:
  2323. x[...] = 2.5
  2324. # Because we violated the semantics, all the values became 2.5
  2325. assert_equal(a, [2.5, 2.5, 2.5])
  2326. # If buffering will definitely happening, for instance because of
  2327. # a cast, only the items selected by the mask will be copied back from
  2328. # the buffer.
  2329. it = np.nditer([a, msk], ['buffered'],
  2330. [['readwrite', 'writemasked'],
  2331. ['readonly', 'arraymask']],
  2332. op_dtypes=['i8', None],
  2333. casting='unsafe')
  2334. with it:
  2335. for x, m in it:
  2336. x[...] = 3
  2337. # Even though we violated the semantics, only the selected values
  2338. # were copied back
  2339. assert_equal(a, [3, 3, 2.5])
  2340. def test_iter_non_writable_attribute_deletion():
  2341. it = np.nditer(np.ones(2))
  2342. attr = ["value", "shape", "operands", "itviews", "has_delayed_bufalloc",
  2343. "iterationneedsapi", "has_multi_index", "has_index", "dtypes",
  2344. "ndim", "nop", "itersize", "finished"]
  2345. for s in attr:
  2346. assert_raises(AttributeError, delattr, it, s)
  2347. def test_iter_writable_attribute_deletion():
  2348. it = np.nditer(np.ones(2))
  2349. attr = [ "multi_index", "index", "iterrange", "iterindex"]
  2350. for s in attr:
  2351. assert_raises(AttributeError, delattr, it, s)
  2352. def test_iter_element_deletion():
  2353. it = np.nditer(np.ones(3))
  2354. try:
  2355. del it[1]
  2356. del it[1:2]
  2357. except TypeError:
  2358. pass
  2359. except Exception:
  2360. raise AssertionError
  2361. def test_iter_allocated_array_dtypes():
  2362. # If the dtype of an allocated output has a shape, the shape gets
  2363. # tacked onto the end of the result.
  2364. it = np.nditer(([1, 3, 20], None), op_dtypes=[None, ('i4', (2,))])
  2365. for a, b in it:
  2366. b[0] = a - 1
  2367. b[1] = a + 1
  2368. assert_equal(it.operands[1], [[0, 2], [2, 4], [19, 21]])
  2369. # Check the same (less sensitive) thing when `op_axes` with -1 is given.
  2370. it = np.nditer(([[1, 3, 20]], None), op_dtypes=[None, ('i4', (2,))],
  2371. flags=["reduce_ok"], op_axes=[None, (-1, 0)])
  2372. for a, b in it:
  2373. b[0] = a - 1
  2374. b[1] = a + 1
  2375. assert_equal(it.operands[1], [[0, 2], [2, 4], [19, 21]])
  2376. # Make sure this works for scalars too
  2377. it = np.nditer((10, 2, None), op_dtypes=[None, None, ('i4', (2, 2))])
  2378. for a, b, c in it:
  2379. c[0, 0] = a - b
  2380. c[0, 1] = a + b
  2381. c[1, 0] = a * b
  2382. c[1, 1] = a / b
  2383. assert_equal(it.operands[2], [[8, 12], [20, 5]])
  2384. def test_0d_iter():
  2385. # Basic test for iteration of 0-d arrays:
  2386. i = nditer([2, 3], ['multi_index'], [['readonly']]*2)
  2387. assert_equal(i.ndim, 0)
  2388. assert_equal(next(i), (2, 3))
  2389. assert_equal(i.multi_index, ())
  2390. assert_equal(i.iterindex, 0)
  2391. assert_raises(StopIteration, next, i)
  2392. # test reset:
  2393. i.reset()
  2394. assert_equal(next(i), (2, 3))
  2395. assert_raises(StopIteration, next, i)
  2396. # test forcing to 0-d
  2397. i = nditer(np.arange(5), ['multi_index'], [['readonly']], op_axes=[()])
  2398. assert_equal(i.ndim, 0)
  2399. assert_equal(len(i), 1)
  2400. i = nditer(np.arange(5), ['multi_index'], [['readonly']],
  2401. op_axes=[()], itershape=())
  2402. assert_equal(i.ndim, 0)
  2403. assert_equal(len(i), 1)
  2404. # passing an itershape alone is not enough, the op_axes are also needed
  2405. with assert_raises(ValueError):
  2406. nditer(np.arange(5), ['multi_index'], [['readonly']], itershape=())
  2407. # Test a more complex buffered casting case (same as another test above)
  2408. sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')]
  2409. a = np.array(0.5, dtype='f4')
  2410. i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
  2411. casting='unsafe', op_dtypes=sdt)
  2412. vals = next(i)
  2413. assert_equal(vals['a'], 0.5)
  2414. assert_equal(vals['b'], 0)
  2415. assert_equal(vals['c'], [[(0.5)]*3]*2)
  2416. assert_equal(vals['d'], 0.5)
  2417. def test_object_iter_cleanup():
  2418. # see gh-18450
  2419. # object arrays can raise a python exception in ufunc inner loops using
  2420. # nditer, which should cause iteration to stop & cleanup. There were bugs
  2421. # in the nditer cleanup when decref'ing object arrays.
  2422. # This test would trigger valgrind "uninitialized read" before the bugfix.
  2423. assert_raises(TypeError, lambda: np.zeros((17000, 2), dtype='f4') * None)
  2424. # this more explicit code also triggers the invalid access
  2425. arr = np.arange(np.BUFSIZE * 10).reshape(10, -1).astype(str)
  2426. oarr = arr.astype(object)
  2427. oarr[:, -1] = None
  2428. assert_raises(TypeError, lambda: np.add(oarr[:, ::-1], arr[:, ::-1]))
  2429. # followup: this tests for a bug introduced in the first pass of gh-18450,
  2430. # caused by an incorrect fallthrough of the TypeError
  2431. class T:
  2432. def __bool__(self):
  2433. raise TypeError("Ambiguous")
  2434. assert_raises(TypeError, np.logical_or.reduce,
  2435. np.array([T(), T()], dtype='O'))
  2436. def test_object_iter_cleanup_reduce():
  2437. # Similar as above, but a complex reduction case that was previously
  2438. # missed (see gh-18810).
  2439. # The following array is special in that it cannot be flattened:
  2440. arr = np.array([[None, 1], [-1, -1], [None, 2], [-1, -1]])[::2]
  2441. with pytest.raises(TypeError):
  2442. np.sum(arr)
  2443. @pytest.mark.parametrize("arr", [
  2444. np.ones((8000, 4, 2), dtype=object)[:, ::2, :],
  2445. np.ones((8000, 4, 2), dtype=object, order="F")[:, ::2, :],
  2446. np.ones((8000, 4, 2), dtype=object)[:, ::2, :].copy("F")])
  2447. def test_object_iter_cleanup_large_reduce(arr):
  2448. # More complicated calls are possible for large arrays:
  2449. out = np.ones(8000, dtype=np.intp)
  2450. # force casting with `dtype=object`
  2451. res = np.sum(arr, axis=(1, 2), dtype=object, out=out)
  2452. assert_array_equal(res, np.full(8000, 4, dtype=object))
  2453. def test_iter_too_large():
  2454. # The total size of the iterator must not exceed the maximum intp due
  2455. # to broadcasting. Dividing by 1024 will keep it small enough to
  2456. # give a legal array.
  2457. size = np.iinfo(np.intp).max // 1024
  2458. arr = np.lib.stride_tricks.as_strided(np.zeros(1), (size,), (0,))
  2459. assert_raises(ValueError, nditer, (arr, arr[:, None]))
  2460. # test the same for multiindex. That may get more interesting when
  2461. # removing 0 dimensional axis is allowed (since an iterator can grow then)
  2462. assert_raises(ValueError, nditer,
  2463. (arr, arr[:, None]), flags=['multi_index'])
  2464. def test_iter_too_large_with_multiindex():
  2465. # When a multi index is being tracked, the error is delayed this
  2466. # checks the delayed error messages and getting below that by
  2467. # removing an axis.
  2468. base_size = 2**10
  2469. num = 1
  2470. while base_size**num < np.iinfo(np.intp).max:
  2471. num += 1
  2472. shape_template = [1, 1] * num
  2473. arrays = []
  2474. for i in range(num):
  2475. shape = shape_template[:]
  2476. shape[i * 2] = 2**10
  2477. arrays.append(np.empty(shape))
  2478. arrays = tuple(arrays)
  2479. # arrays are now too large to be broadcast. The different modes test
  2480. # different nditer functionality with or without GIL.
  2481. for mode in range(6):
  2482. with assert_raises(ValueError):
  2483. _multiarray_tests.test_nditer_too_large(arrays, -1, mode)
  2484. # but if we do nothing with the nditer, it can be constructed:
  2485. _multiarray_tests.test_nditer_too_large(arrays, -1, 7)
  2486. # When an axis is removed, things should work again (half the time):
  2487. for i in range(num):
  2488. for mode in range(6):
  2489. # an axis with size 1024 is removed:
  2490. _multiarray_tests.test_nditer_too_large(arrays, i*2, mode)
  2491. # an axis with size 1 is removed:
  2492. with assert_raises(ValueError):
  2493. _multiarray_tests.test_nditer_too_large(arrays, i*2 + 1, mode)
  2494. def test_writebacks():
  2495. a = np.arange(6, dtype='f4')
  2496. au = a.byteswap().newbyteorder()
  2497. assert_(a.dtype.byteorder != au.dtype.byteorder)
  2498. it = nditer(au, [], [['readwrite', 'updateifcopy']],
  2499. casting='equiv', op_dtypes=[np.dtype('f4')])
  2500. with it:
  2501. it.operands[0][:] = 100
  2502. assert_equal(au, 100)
  2503. # do it again, this time raise an error,
  2504. it = nditer(au, [], [['readwrite', 'updateifcopy']],
  2505. casting='equiv', op_dtypes=[np.dtype('f4')])
  2506. try:
  2507. with it:
  2508. assert_equal(au.flags.writeable, False)
  2509. it.operands[0][:] = 0
  2510. raise ValueError('exit context manager on exception')
  2511. except:
  2512. pass
  2513. assert_equal(au, 0)
  2514. assert_equal(au.flags.writeable, True)
  2515. # cannot reuse i outside context manager
  2516. assert_raises(ValueError, getattr, it, 'operands')
  2517. it = nditer(au, [], [['readwrite', 'updateifcopy']],
  2518. casting='equiv', op_dtypes=[np.dtype('f4')])
  2519. with it:
  2520. x = it.operands[0]
  2521. x[:] = 6
  2522. assert_(x.flags.writebackifcopy)
  2523. assert_equal(au, 6)
  2524. assert_(not x.flags.writebackifcopy)
  2525. x[:] = 123 # x.data still valid
  2526. assert_equal(au, 6) # but not connected to au
  2527. it = nditer(au, [],
  2528. [['readwrite', 'updateifcopy']],
  2529. casting='equiv', op_dtypes=[np.dtype('f4')])
  2530. # reentering works
  2531. with it:
  2532. with it:
  2533. for x in it:
  2534. x[...] = 123
  2535. it = nditer(au, [],
  2536. [['readwrite', 'updateifcopy']],
  2537. casting='equiv', op_dtypes=[np.dtype('f4')])
  2538. # make sure exiting the inner context manager closes the iterator
  2539. with it:
  2540. with it:
  2541. for x in it:
  2542. x[...] = 123
  2543. assert_raises(ValueError, getattr, it, 'operands')
  2544. # do not crash if original data array is decrefed
  2545. it = nditer(au, [],
  2546. [['readwrite', 'updateifcopy']],
  2547. casting='equiv', op_dtypes=[np.dtype('f4')])
  2548. del au
  2549. with it:
  2550. for x in it:
  2551. x[...] = 123
  2552. # make sure we cannot reenter the closed iterator
  2553. enter = it.__enter__
  2554. assert_raises(RuntimeError, enter)
  2555. def test_close_equivalent():
  2556. ''' using a context amanger and using nditer.close are equivalent
  2557. '''
  2558. def add_close(x, y, out=None):
  2559. addop = np.add
  2560. it = np.nditer([x, y, out], [],
  2561. [['readonly'], ['readonly'], ['writeonly','allocate']])
  2562. for (a, b, c) in it:
  2563. addop(a, b, out=c)
  2564. ret = it.operands[2]
  2565. it.close()
  2566. return ret
  2567. def add_context(x, y, out=None):
  2568. addop = np.add
  2569. it = np.nditer([x, y, out], [],
  2570. [['readonly'], ['readonly'], ['writeonly','allocate']])
  2571. with it:
  2572. for (a, b, c) in it:
  2573. addop(a, b, out=c)
  2574. return it.operands[2]
  2575. z = add_close(range(5), range(5))
  2576. assert_equal(z, range(0, 10, 2))
  2577. z = add_context(range(5), range(5))
  2578. assert_equal(z, range(0, 10, 2))
  2579. def test_close_raises():
  2580. it = np.nditer(np.arange(3))
  2581. assert_equal (next(it), 0)
  2582. it.close()
  2583. assert_raises(StopIteration, next, it)
  2584. assert_raises(ValueError, getattr, it, 'operands')
  2585. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  2586. def test_warn_noclose():
  2587. a = np.arange(6, dtype='f4')
  2588. au = a.byteswap().newbyteorder()
  2589. with suppress_warnings() as sup:
  2590. sup.record(RuntimeWarning)
  2591. it = np.nditer(au, [], [['readwrite', 'updateifcopy']],
  2592. casting='equiv', op_dtypes=[np.dtype('f4')])
  2593. del it
  2594. assert len(sup.log) == 1
  2595. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  2596. @pytest.mark.parametrize(["in_dtype", "buf_dtype"],
  2597. [("i", "O"), ("O", "i"), # most simple cases
  2598. ("i,O", "O,O"), # structured partially only copying O
  2599. ("O,i", "i,O"), # structured casting to and from O
  2600. ])
  2601. @pytest.mark.parametrize("steps", [1, 2, 3])
  2602. def test_partial_iteration_cleanup(in_dtype, buf_dtype, steps):
  2603. value = 123 # relies on python cache (leak-check will still find it)
  2604. arr = np.full(int(np.BUFSIZE * 2.5), value).astype(in_dtype)
  2605. count = sys.getrefcount(value)
  2606. it = np.nditer(arr, op_dtypes=[np.dtype(buf_dtype)],
  2607. flags=["buffered", "external_loop", "refs_ok"], casting="unsafe")
  2608. for step in range(steps):
  2609. # The iteration finishes in 3 steps, the first two are partial
  2610. next(it)
  2611. # Note that resetting does not free references
  2612. del it
  2613. assert count == sys.getrefcount(value)
  2614. # Repeat the test with `iternext`
  2615. it = np.nditer(arr, op_dtypes=[np.dtype(buf_dtype)],
  2616. flags=["buffered", "external_loop", "refs_ok"], casting="unsafe")
  2617. for step in range(steps):
  2618. it.iternext()
  2619. del it # should ensure cleanup
  2620. assert count == sys.getrefcount(value)
  2621. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  2622. @pytest.mark.parametrize(["in_dtype", "buf_dtype"],
  2623. [("O", "i"), # most simple cases
  2624. ("O,i", "i,O"), # structured casting to and from O
  2625. ])
  2626. def test_partial_iteration_error(in_dtype, buf_dtype):
  2627. value = 123 # relies on python cache (leak-check will still find it)
  2628. arr = np.full(int(np.BUFSIZE * 2.5), value).astype(in_dtype)
  2629. if in_dtype == "O":
  2630. arr[int(np.BUFSIZE * 1.5)] = None
  2631. else:
  2632. arr[int(np.BUFSIZE * 1.5)]["f0"] = None
  2633. count = sys.getrefcount(value)
  2634. it = np.nditer(arr, op_dtypes=[np.dtype(buf_dtype)],
  2635. flags=["buffered", "external_loop", "refs_ok"], casting="unsafe")
  2636. with pytest.raises(TypeError):
  2637. # pytest.raises seems to have issues with the error originating
  2638. # in the for loop, so manually unravel:
  2639. next(it)
  2640. next(it) # raises TypeError
  2641. # Repeat the test with `iternext` after resetting, the buffers should
  2642. # already be cleared from any references, so resetting is sufficient.
  2643. it.reset()
  2644. with pytest.raises(TypeError):
  2645. it.iternext()
  2646. it.iternext()
  2647. assert count == sys.getrefcount(value)