Debian Codegraph @

pypy/module/micronumpy/test/test_nditer.py

raw symbols SCIP
1 import py
2 from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
3
4
5 class AppTestNDIter(BaseNumpyAppTest):
6 def test_type(self):
7 import numpy as np
8 assert type(np.nditer) is type
9 assert np.nditer.__name__ == 'nditer'
10 assert np.nditer.__module__ == 'numpy'
11 try:
12 class Sub(np.nditer):
13 pass
14 except TypeError as e:
15 assert "not an acceptable base" in str(e)
16 else:
17 assert False
18
19 def test_basic(self):
20 from numpy import arange, nditer, ndarray
21 a = arange(6).reshape(2,3)
22 i = nditer(a)
23 r = []
24 for x in i:
25 assert type(x) is ndarray
26 assert x.base is i
27 assert x.shape == ()
28 assert x.strides == ()
29 exc = raises(ValueError, "x[()] = 42")
30 assert str(exc.value) == 'assignment destination is read-only'
31 r.append(x)
32 assert r == [0, 1, 2, 3, 4, 5]
33 r = []
34 for x in nditer(a.T):
35 r.append(x)
36 assert r == [0, 1, 2, 3, 4, 5]
37
38 def test_order(self):
39 from numpy import arange, nditer
40 a = arange(6).reshape(2,3)
41 r = []
42 for x in nditer(a, order='C'):
43 r.append(x)
44 assert r == [0, 1, 2, 3, 4, 5]
45 r = []
46 for x in nditer(a, order='F'):
47 r.append(x)
48 assert r == [0, 3, 1, 4, 2, 5]
49
50 def test_readwrite(self):
51 from numpy import arange, nditer, ndarray
52 a = arange(6).reshape(2,3)
53 i = nditer(a, op_flags=['readwrite'])
54 for x in i:
55 assert type(x) is ndarray
56 assert x.base is i
57 assert x.shape == ()
58 assert x.strides == ()
59 x[...] = 2 * x
60 assert (a == [[0, 2, 4], [6, 8, 10]]).all()
61
62 def test_external_loop(self):
63 from numpy import arange, nditer, array
64 a = arange(24).reshape(2, 3, 4)
65 import sys
66 r = []
67 for x in nditer(a, flags=['external_loop']):
68 r.append(x)
69 assert len(r) == 1
70 assert r[0].shape == (24,)
71 assert (array(r) == range(24)).all()
72 r = []
73 for x in nditer(a, flags=['external_loop'], order='F'):
74 r.append(x)
75 assert len(r) == 12
76 assert (array(r) == [[ 0, 12], [ 4, 16], [ 8, 20], [ 1, 13], [ 5, 17], [ 9, 21],
77 [ 2, 14], [ 6, 18], [10, 22], [ 3, 15], [ 7, 19], [11, 23],
78 ]).all()
79 e = raises(ValueError, 'r[0][0] = 0')
80 assert str(e.value) == 'assignment destination is read-only'
81 r = []
82 for x in nditer(a.T, flags=['external_loop'], order='F'):
83 r.append(x)
84 array_r = array(r)
85 assert len(array_r.shape) == 2
86 assert array_r.shape == (1,24)
87 assert (array(r) == arange(24)).all()
88
89 def test_index(self):
90 from numpy import arange, nditer
91 a = arange(6).reshape(2,3)
92
93 r = []
94 it = nditer(a, flags=['c_index'])
95 assert it.has_index
96 for value in it:
97 r.append((value, it.index))
98 assert r == [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
99 exc = None
100 try:
101 it.index
102 except ValueError as e:
103 exc = e
104 assert exc
105
106 r = []
107 it = nditer(a, flags=['f_index'])
108 assert it.has_index
109 for value in it:
110 r.append((value, it.index))
111 assert r == [(0, 0), (1, 2), (2, 4), (3, 1), (4, 3), (5, 5)]
112
113 def test_iters_with_different_order(self):
114 from numpy import nditer, array
115
116 a = array([[1, 2], [3, 4]], order="C")
117 b = array([[1, 2], [3, 4]], order="F")
118
119 it = nditer([a, b])
120 r = list(it)
121 assert r == zip(range(1, 5), range(1, 5))
122
123 def test_interface(self):
124 from numpy import arange, nditer, zeros
125 import sys
126 a = arange(6).reshape(2,3)
127 r = []
128 it = nditer(a, flags=['f_index'])
129 while not it.finished:
130 r.append((it[0], it.index))
131 it.iternext()
132 assert r == [(0, 0), (1, 2), (2, 4), (3, 1), (4, 3), (5, 5)]
133 it = nditer(a, flags=['multi_index'], op_flags=['writeonly'])
134 if '__pypy__' in sys.builtin_module_names:
135 raises(NotImplementedError, 'it[0] = 3')
136 skip('nditer.__setitem__ not implmented')
137 while not it.finished:
138 it[0] = it.multi_index[1] - it.multi_index[0]
139 it.iternext()
140 assert (a == [[0, 1, 2], [-1, 0, 1]]).all()
141 # b = zeros((2, 3))
142 # exc = raises(ValueError, nditer, b, flags=['c_index', 'external_loop'])
143 # assert str(exc.value).startswith("Iterator flag EXTERNAL_LOOP cannot")
144
145 def test_buffered(self):
146 from numpy import arange, nditer, array, isscalar
147 a = arange(24).reshape(2, 3, 4)
148 r = []
149 for x in nditer(a, flags=['external_loop'], order='F'):
150 r.append(x)
151 array_r = array(r)
152 assert len(array_r.shape) == 2
153 assert array_r.shape == (12, 2)
154 assert (array_r == [[0, 12], [4, 16], [8, 20], [1, 13], [5, 17], [9, 21],
155 [2, 14], [6, 18], [10, 22], [3, 15], [7, 19], [11, 23]]).all
156 assert (a == arange(24).reshape(2, 3, 4)).all()
157 a[0,0,0] = 100
158 assert r[0][0] == 100
159
160 r = []
161 it = nditer(a, flags=['buffered'], order='F')
162 for x in it:
163 r.append(x)
164 array_r = array(r)
165 assert len(array_r.shape) == 1
166 assert array_r.shape == (24,)
167 assert r[0].shape == ()
168 assert not isscalar(r[0])
169 assert (array_r == [0, 12, 4, 16, 8, 20, 1, 13, 5, 17, 9, 21,
170 2, 14, 6, 18, 10, 22, 3, 15, 7, 19, 11, 23]).all
171 assert a.shape == (2, 3, 4)
172 a[0,0,0] = 0
173 # buffered copies the data into a tmp array
174 assert r[0] == 100
175 assert (a == arange(24).reshape(2, 3, 4)).all()
176
177 r = []
178 for x in nditer(a, flags=['external_loop', 'buffered'], order='F'):
179 r.append(x)
180 assert r[0].shape == (24,)
181 assert (array_r == [0, 12, 4, 16, 8, 20, 1, 13, 5, 17, 9, 21,
182 2, 14, 6, 18, 10, 22, 3, 15, 7, 19, 11, 23]).all
183 assert a.shape == (2, 3, 4)
184 assert (a == arange(24).reshape(2, 3, 4)).all()
185
186 def test_zerosize(self):
187 from numpy import nditer, array
188 for a in [ array([]), array([1]), array([1, 2]) ]:
189 buffersize = max(16 * 1024 ** 2 // a.itemsize, 1)
190 r = []
191 for chunk in nditer(a,
192 flags=['external_loop', 'buffered', 'zerosize_ok'],
193 buffersize=buffersize, order='C'):
194 r.append(chunk)
195 assert (r == a).all()
196
197 def test_op_dtype(self):
198 from numpy import arange, nditer, sqrt, array
199 a = arange(6).reshape(2,3) - 3
200 exc = raises(TypeError, nditer, a, op_dtypes=['complex'])
201 assert str(exc.value).startswith("Iterator operand required copying or buffering")
202 exc = raises(ValueError, nditer, a, op_flags=['copy'], op_dtypes=['complex128'])
203 assert str(exc.value) == "None of the iterator flags READWRITE," \
204 " READONLY, or WRITEONLY were specified for an operand"
205 r = []
206 for x in nditer(a, op_flags=['readonly','copy'],
207 op_dtypes=['complex128']):
208 r.append(sqrt(x))
209 assert abs((array(r) - [1.73205080757j, 1.41421356237j, 1j, 0j,
210 1+0j, 1.41421356237+0j]).sum()) < 1e-5
211 multi = nditer([None, array([2, 3], dtype='int64'), array(2., dtype='double')],
212 op_dtypes=['int64', 'int64', 'float64'],
213 op_flags=[['writeonly', 'allocate'], ['readonly'], ['readonly']])
214 for a, b, c in multi:
215 a[...] = b * c
216 assert (multi.operands[0] == [4, 6]).all()
217
218 def test_casting(self):
219 from numpy import arange, nditer
220 import sys
221 a = arange(6.)
222 exc = raises(TypeError, nditer, a, flags=['buffered'], op_dtypes=['float32'])
223 assert str(exc.value) == "Iterator operand 0 dtype could not be " + \
224 "cast from dtype('float64') to dtype('float32') according to the" +\
225 " rule 'safe'"
226 r = []
227 for x in nditer(a, flags=['buffered'], op_dtypes=['float32'],
228 casting='same_kind'):
229 r.append(x)
230 assert r == [0., 1., 2., 3., 4., 5.]
231 exc = raises(TypeError, nditer, a, flags=['buffered'],
232 op_dtypes=['int32'], casting='same_kind')
233 assert str(exc.value).startswith("Iterator operand 0 dtype could not be cast")
234 r = []
235 b = arange(6)
236 exc = raises(TypeError, nditer, b, flags=['buffered'], op_dtypes=['float64'],
237 op_flags=['readwrite'], casting='same_kind')
238 assert str(exc.value).startswith("Iterator requested dtype could not be cast")
239
240 def test_broadcast(self):
241 from numpy import arange, nditer
242 a = arange(3)
243 b = arange(6).reshape(2,3)
244 r = []
245 it = nditer([a, b])
246 assert it.itersize == 6
247 for x,y in it:
248 r.append((x, y))
249 assert r == [(0, 0), (1, 1), (2, 2), (0, 3), (1, 4), (2, 5)]
250 a = arange(2)
251 exc = raises(ValueError, nditer, [a, b])
252 assert str(exc.value).find('shapes (2,) (2,3)') > 0
253
254 def test_outarg(self):
255 from numpy import nditer, zeros, arange
256 import sys
257
258 def square1(a):
259 it = nditer([a, None])
260 for x,y in it:
261 y[...] = x*x
262 return it.operands[1]
263 assert (square1([1, 2, 3]) == [1, 4, 9]).all()
264
265 def square2(a, out=None):
266 it = nditer([a, out], flags=['external_loop', 'buffered'],
267 op_flags=[['readonly'],
268 ['writeonly', 'allocate', 'no_broadcast']])
269 for x,y in it:
270 y[...] = x*x
271 return it.operands[1]
272 assert (square2([1, 2, 3]) == [1, 4, 9]).all()
273 b = zeros((3, ))
274 c = square2([1, 2, 3], out=b)
275 assert (c == [1., 4., 9.]).all()
276 assert (b == c).all()
277 exc = raises(ValueError, square2, arange(6).reshape(2, 3), out=b)
278 assert str(exc.value).find("doesn't match the broadcast shape") > 0
279
280 def test_outer_product(self):
281 from numpy import nditer, arange
282 a = arange(3)
283 import sys
284 b = arange(8).reshape(2,4)
285 if '__pypy__' in sys.builtin_module_names:
286 raises(NotImplementedError, nditer, [a, b, None], flags=['external_loop'],
287 op_axes=[[0, -1, -1], [-1, 0, 1], None])
288 skip('nditer op_axes not implemented yet')
289 it = nditer([a, b, None], flags=['external_loop'],
290 op_axes=[[0, -1, -1], [-1, 0, 1], None])
291 for x, y, z in it:
292 z[...] = x*y
293 assert it.operands[2].shape == (3, 2, 4)
294 for i in range(a.size):
295 assert (it.operands[2][i] == a[i]*b).all()
296
297 def test_reduction(self):
298 from numpy import nditer, arange, array
299 import sys
300 a = arange(24).reshape(2, 3, 4)
301 b = array(0)
302 if '__pypy__' in sys.builtin_module_names:
303 raises(NotImplementedError, nditer, [a, b], flags=['reduce_ok'])
304 skip('nditer reduce_ok not implemented yet')
305 #reduction operands must be readwrite
306 for x, y in nditer([a, b], flags=['reduce_ok', 'external_loop'],
307 op_flags=[['readonly'], ['readwrite']]):
308 y[...] += x
309 assert b == 276
310 assert b == a.sum()
311
312 # reduction and allocation requires op_axes and initialization
313 it = nditer([a, None], flags=['reduce_ok', 'external_loop'],
314 op_flags=[['readonly'], ['readwrite', 'allocate']],
315 op_axes=[None, [0,1,-1]])
316 it.operands[1][...] = 0
317 for x, y in it:
318 y[...] += x
319
320 assert (it.operands[1] == [[6, 22, 38], [54, 70, 86]]).all()
321 assert (it.operands[1] == a.sum(axis=2)).all()
322
323 # previous example with buffering, requires more flags and reset
324 it = nditer([a, None], flags=['reduce_ok', 'external_loop',
325 'buffered', 'delay_bufalloc'],
326 op_flags=[['readonly'], ['readwrite', 'allocate']],
327 op_axes=[None, [0,1,-1]])
328 it.operands[1][...] = 0
329 it.reset()
330 for x, y in it:
331 y[...] += x
332
333 assert (it.operands[1] == [[6, 22, 38], [54, 70, 86]]).all()
334 assert (it.operands[1] == a.sum(axis=2)).all()
335
336 def test_get_dtypes(self):
337 from numpy import array, nditer
338 x = array([1, 2])
339 y = array([1.0, 2.0])
340 assert nditer([x, y]).dtypes == (x.dtype, y.dtype)
341
342 def test_multi_index(self):
343 import numpy as np
344 a = np.arange(6).reshape(2, 3)
345 it = np.nditer(a, flags=['multi_index'])
346 res = []
347 while not it.finished:
348 res.append((it[0], it.multi_index))
349 it.iternext()
350 assert res == [(0, (0, 0)), (1, (0, 1)),
351 (2, (0, 2)), (3, (1, 0)),
352 (4, (1, 1)), (5, (1, 2))]
353
354 def test_itershape(self):
355 # Check that allocated outputs work with a specified shape
356 from numpy import nditer, arange
357 import sys
358 if '__pypy__' in sys.builtin_module_names:
359 skip("op_axes not totally supported yet")
360 a = arange(6, dtype='i2').reshape(2,3)
361 i = nditer([a, None], [], [['readonly'], ['writeonly','allocate']],
362 op_axes=[[0,1,None], None],
363 itershape=(-1,-1,4))
364 assert i.operands[1].shape == (2,3,4)
365 assert i.operands[1].strides, (24,8,2)
366
367 i = nditer([a.T, None], [], [['readonly'], ['writeonly','allocate']],
368 op_axes=[[0,1,None], None],
369 itershape=(-1,-1,4))
370 assert i.operands[1].shape, (3,2,4)
371 assert i.operands[1].strides, (8,24,2)
372
373 i = nditer([a.T, None], [], [['readonly'], ['writeonly','allocate']],
374 order='F',
375 op_axes=[[0,1,None], None],
376 itershape=(-1,-1,4))
377 assert i.operands[1].shape, (3,2,4)
378 assert i.operands[1].strides, (2,6,12)
379
380 # If we specify 1 in the itershape, it shouldn't allow broadcasting
381 # of that dimension to a bigger value
382 raises(ValueError, nditer, [a, None], [],
383 [['readonly'], ['writeonly','allocate']],
384 op_axes=[[0,1,None], None],
385 itershape=(-1,1,4))
386