xref: /aosp_15_r20/external/pytorch/test/torch_np/numpy_tests/lib/test_index_tricks.py (revision da0073e96a02ea20f0ac840b70461e3646d07c45)
1# Owner(s): ["module: dynamo"]
2
3import functools
4from unittest import expectedFailure as xfail, skipIf
5
6from pytest import raises as assert_raises  # , assert_raises_regex,
7
8from torch.testing._internal.common_utils import (
9    instantiate_parametrized_tests,
10    parametrize,
11    run_tests,
12    TEST_WITH_TORCHDYNAMO,
13    TestCase,
14    xpassIfTorchDynamo,
15)
16
17
18skip = functools.partial(skipIf, True)
19
20
21# If we are going to trace through these, we should use NumPy
22# If testing on eager mode, we use torch._numpy
23if TEST_WITH_TORCHDYNAMO:
24    import numpy as np
25    from numpy import diag_indices, diag_indices_from, fill_diagonal, index_exp, s_
26    from numpy.testing import (
27        assert_,
28        assert_almost_equal,
29        assert_array_almost_equal,
30        assert_array_equal,
31        assert_equal,
32        assert_raises_regex,
33    )
34else:
35    import torch._numpy as np
36    from torch._numpy import (
37        diag_indices,
38        diag_indices_from,
39        fill_diagonal,
40        index_exp,
41        s_,
42    )
43    from torch._numpy.testing import (
44        assert_,
45        assert_almost_equal,
46        assert_array_almost_equal,
47        assert_array_equal,
48        assert_equal,
49    )
50
51
52@xpassIfTorchDynamo  # (reason="unravel_index not implemented")
53@instantiate_parametrized_tests
54class TestRavelUnravelIndex(TestCase):
55    def test_basic(self):
56        assert_equal(np.unravel_index(2, (2, 2)), (1, 0))
57
58        # test that new shape argument works properly
59        assert_equal(np.unravel_index(indices=2, shape=(2, 2)), (1, 0))
60
61        # test that an invalid second keyword argument
62        # is properly handled, including the old name `dims`.
63        with assert_raises(TypeError):
64            np.unravel_index(indices=2, hape=(2, 2))
65
66        with assert_raises(TypeError):
67            np.unravel_index(2, hape=(2, 2))
68
69        with assert_raises(TypeError):
70            np.unravel_index(254, ims=(17, 94))
71
72        with assert_raises(TypeError):
73            np.unravel_index(254, dims=(17, 94))
74
75        assert_equal(np.ravel_multi_index((1, 0), (2, 2)), 2)
76        assert_equal(np.unravel_index(254, (17, 94)), (2, 66))
77        assert_equal(np.ravel_multi_index((2, 66), (17, 94)), 254)
78        assert_raises(ValueError, np.unravel_index, -1, (2, 2))
79        assert_raises(TypeError, np.unravel_index, 0.5, (2, 2))
80        assert_raises(ValueError, np.unravel_index, 4, (2, 2))
81        assert_raises(ValueError, np.ravel_multi_index, (-3, 1), (2, 2))
82        assert_raises(ValueError, np.ravel_multi_index, (2, 1), (2, 2))
83        assert_raises(ValueError, np.ravel_multi_index, (0, -3), (2, 2))
84        assert_raises(ValueError, np.ravel_multi_index, (0, 2), (2, 2))
85        assert_raises(TypeError, np.ravel_multi_index, (0.1, 0.0), (2, 2))
86
87        assert_equal(np.unravel_index((2 * 3 + 1) * 6 + 4, (4, 3, 6)), [2, 1, 4])
88        assert_equal(np.ravel_multi_index([2, 1, 4], (4, 3, 6)), (2 * 3 + 1) * 6 + 4)
89
90        arr = np.array([[3, 6, 6], [4, 5, 1]])
91        assert_equal(np.ravel_multi_index(arr, (7, 6)), [22, 41, 37])
92        assert_equal(np.ravel_multi_index(arr, (7, 6), order="F"), [31, 41, 13])
93        assert_equal(np.ravel_multi_index(arr, (4, 6), mode="clip"), [22, 23, 19])
94        assert_equal(
95            np.ravel_multi_index(arr, (4, 4), mode=("clip", "wrap")), [12, 13, 13]
96        )
97        assert_equal(np.ravel_multi_index((3, 1, 4, 1), (6, 7, 8, 9)), 1621)
98
99        assert_equal(
100            np.unravel_index(np.array([22, 41, 37]), (7, 6)), [[3, 6, 6], [4, 5, 1]]
101        )
102        assert_equal(
103            np.unravel_index(np.array([31, 41, 13]), (7, 6), order="F"),
104            [[3, 6, 6], [4, 5, 1]],
105        )
106        assert_equal(np.unravel_index(1621, (6, 7, 8, 9)), [3, 1, 4, 1])
107
108    def test_empty_indices(self):
109        msg1 = "indices must be integral: the provided empty sequence was"
110        msg2 = "only int indices permitted"
111        assert_raises_regex(TypeError, msg1, np.unravel_index, [], (10, 3, 5))
112        assert_raises_regex(TypeError, msg1, np.unravel_index, (), (10, 3, 5))
113        assert_raises_regex(TypeError, msg2, np.unravel_index, np.array([]), (10, 3, 5))
114        assert_equal(
115            np.unravel_index(np.array([], dtype=int), (10, 3, 5)), [[], [], []]
116        )
117        assert_raises_regex(TypeError, msg1, np.ravel_multi_index, ([], []), (10, 3))
118        assert_raises_regex(
119            TypeError, msg1, np.ravel_multi_index, ([], ["abc"]), (10, 3)
120        )
121        assert_raises_regex(
122            TypeError, msg2, np.ravel_multi_index, (np.array([]), np.array([])), (5, 3)
123        )
124        assert_equal(
125            np.ravel_multi_index(
126                (np.array([], dtype=int), np.array([], dtype=int)), (5, 3)
127            ),
128            [],
129        )
130        assert_equal(np.ravel_multi_index(np.array([[], []], dtype=int), (5, 3)), [])
131
132    def test_big_indices(self):
133        # ravel_multi_index for big indices (issue #7546)
134        if np.intp == np.int64:
135            arr = ([1, 29], [3, 5], [3, 117], [19, 2], [2379, 1284], [2, 2], [0, 1])
136            assert_equal(
137                np.ravel_multi_index(arr, (41, 7, 120, 36, 2706, 8, 6)),
138                [5627771580, 117259570957],
139            )
140
141        # test unravel_index for big indices (issue #9538)
142        assert_raises(ValueError, np.unravel_index, 1, (2**32 - 1, 2**31 + 1))
143
144        # test overflow checking for too big array (issue #7546)
145        dummy_arr = ([0], [0])
146        half_max = np.iinfo(np.intp).max // 2
147        assert_equal(np.ravel_multi_index(dummy_arr, (half_max, 2)), [0])
148        assert_raises(ValueError, np.ravel_multi_index, dummy_arr, (half_max + 1, 2))
149        assert_equal(np.ravel_multi_index(dummy_arr, (half_max, 2), order="F"), [0])
150        assert_raises(
151            ValueError, np.ravel_multi_index, dummy_arr, (half_max + 1, 2), order="F"
152        )
153
154    def test_dtypes(self):
155        # Test with different data types
156        for dtype in [np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64]:
157            coords = np.array([[1, 0, 1, 2, 3, 4], [1, 6, 1, 3, 2, 0]], dtype=dtype)
158            shape = (5, 8)
159            uncoords = 8 * coords[0] + coords[1]
160            assert_equal(np.ravel_multi_index(coords, shape), uncoords)
161            assert_equal(coords, np.unravel_index(uncoords, shape))
162            uncoords = coords[0] + 5 * coords[1]
163            assert_equal(np.ravel_multi_index(coords, shape, order="F"), uncoords)
164            assert_equal(coords, np.unravel_index(uncoords, shape, order="F"))
165
166            coords = np.array(
167                [[1, 0, 1, 2, 3, 4], [1, 6, 1, 3, 2, 0], [1, 3, 1, 0, 9, 5]],
168                dtype=dtype,
169            )
170            shape = (5, 8, 10)
171            uncoords = 10 * (8 * coords[0] + coords[1]) + coords[2]
172            assert_equal(np.ravel_multi_index(coords, shape), uncoords)
173            assert_equal(coords, np.unravel_index(uncoords, shape))
174            uncoords = coords[0] + 5 * (coords[1] + 8 * coords[2])
175            assert_equal(np.ravel_multi_index(coords, shape, order="F"), uncoords)
176            assert_equal(coords, np.unravel_index(uncoords, shape, order="F"))
177
178    def test_clipmodes(self):
179        # Test clipmodes
180        assert_equal(
181            np.ravel_multi_index([5, 1, -1, 2], (4, 3, 7, 12), mode="wrap"),
182            np.ravel_multi_index([1, 1, 6, 2], (4, 3, 7, 12)),
183        )
184        assert_equal(
185            np.ravel_multi_index(
186                [5, 1, -1, 2], (4, 3, 7, 12), mode=("wrap", "raise", "clip", "raise")
187            ),
188            np.ravel_multi_index([1, 1, 0, 2], (4, 3, 7, 12)),
189        )
190        assert_raises(ValueError, np.ravel_multi_index, [5, 1, -1, 2], (4, 3, 7, 12))
191
192    def test_writeability(self):
193        # See gh-7269
194        x, y = np.unravel_index([1, 2, 3], (4, 5))
195        assert_(x.flags.writeable)
196        assert_(y.flags.writeable)
197
198    def test_0d(self):
199        # gh-580
200        x = np.unravel_index(0, ())
201        assert_equal(x, ())
202
203        assert_raises_regex(ValueError, "0d array", np.unravel_index, [0], ())
204        assert_raises_regex(ValueError, "out of bounds", np.unravel_index, [1], ())
205
206    @parametrize("mode", ["clip", "wrap", "raise"])
207    def test_empty_array_ravel(self, mode):
208        res = np.ravel_multi_index(
209            np.zeros((3, 0), dtype=np.intp), (2, 1, 0), mode=mode
210        )
211        assert res.shape == (0,)
212
213        with assert_raises(ValueError):
214            np.ravel_multi_index(np.zeros((3, 1), dtype=np.intp), (2, 1, 0), mode=mode)
215
216    def test_empty_array_unravel(self):
217        res = np.unravel_index(np.zeros(0, dtype=np.intp), (2, 1, 0))
218        # res is a tuple of three empty arrays
219        assert len(res) == 3
220        assert all(a.shape == (0,) for a in res)
221
222        with assert_raises(ValueError):
223            np.unravel_index([1], (2, 1, 0))
224
225
226@xfail  # (reason="mgrid not implemented")
227@instantiate_parametrized_tests
228class TestGrid(TestCase):
229    def test_basic(self):
230        a = mgrid[-1:1:10j]
231        b = mgrid[-1:1:0.1]
232        assert_(a.shape == (10,))
233        assert_(b.shape == (20,))
234        assert_(a[0] == -1)
235        assert_almost_equal(a[-1], 1)
236        assert_(b[0] == -1)
237        assert_almost_equal(b[1] - b[0], 0.1, 11)
238        assert_almost_equal(b[-1], b[0] + 19 * 0.1, 11)
239        assert_almost_equal(a[1] - a[0], 2.0 / 9.0, 11)
240
241    @xfail  # (reason="retstep not implemented")
242    def test_linspace_equivalence(self):
243        y, st = np.linspace(2, 10, retstep=True)
244        assert_almost_equal(st, 8 / 49.0)
245        assert_array_almost_equal(y, mgrid[2:10:50j], 13)
246
247    def test_nd(self):
248        c = mgrid[-1:1:10j, -2:2:10j]
249        d = mgrid[-1:1:0.1, -2:2:0.2]
250        assert_(c.shape == (2, 10, 10))
251        assert_(d.shape == (2, 20, 20))
252        assert_array_equal(c[0][0, :], -np.ones(10, "d"))
253        assert_array_equal(c[1][:, 0], -2 * np.ones(10, "d"))
254        assert_array_almost_equal(c[0][-1, :], np.ones(10, "d"), 11)
255        assert_array_almost_equal(c[1][:, -1], 2 * np.ones(10, "d"), 11)
256        assert_array_almost_equal(d[0, 1, :] - d[0, 0, :], 0.1 * np.ones(20, "d"), 11)
257        assert_array_almost_equal(d[1, :, 1] - d[1, :, 0], 0.2 * np.ones(20, "d"), 11)
258
259    def test_sparse(self):
260        grid_full = mgrid[-1:1:10j, -2:2:10j]
261        grid_sparse = ogrid[-1:1:10j, -2:2:10j]
262
263        # sparse grids can be made dense by broadcasting
264        grid_broadcast = np.broadcast_arrays(*grid_sparse)
265        for f, b in zip(grid_full, grid_broadcast):
266            assert_equal(f, b)
267
268    @parametrize(
269        "start, stop, step, expected",
270        [
271            (None, 10, 10j, (200, 10)),
272            (-10, 20, None, (1800, 30)),
273        ],
274    )
275    def test_mgrid_size_none_handling(self, start, stop, step, expected):
276        # regression test None value handling for
277        # start and step values used by mgrid;
278        # internally, this aims to cover previously
279        # unexplored code paths in nd_grid()
280        grid = mgrid[start:stop:step, start:stop:step]
281        # need a smaller grid to explore one of the
282        # untested code paths
283        grid_small = mgrid[start:stop:step]
284        assert_equal(grid.size, expected[0])
285        assert_equal(grid_small.size, expected[1])
286
287    @xfail  # (reason="mgrid not implementd")
288    def test_accepts_npfloating(self):
289        # regression test for #16466
290        grid64 = mgrid[0.1:0.33:0.1,]
291        grid32 = mgrid[np.float32(0.1) : np.float32(0.33) : np.float32(0.1),]
292        assert_(grid32.dtype == np.float64)
293        assert_array_almost_equal(grid64, grid32)
294
295        # different code path for single slice
296        grid64 = mgrid[0.1:0.33:0.1]
297        grid32 = mgrid[np.float32(0.1) : np.float32(0.33) : np.float32(0.1)]
298        assert_(grid32.dtype == np.float64)
299        assert_array_almost_equal(grid64, grid32)
300
301    @skip(reason="longdouble")
302    def test_accepts_longdouble(self):
303        # regression tests for #16945
304        grid64 = mgrid[0.1:0.33:0.1,]
305        grid128 = mgrid[np.longdouble(0.1) : np.longdouble(0.33) : np.longdouble(0.1),]
306        assert_(grid128.dtype == np.longdouble)
307        assert_array_almost_equal(grid64, grid128)
308
309        grid128c_a = mgrid[0 : np.longdouble(1) : 3.4j]
310        grid128c_b = mgrid[0 : np.longdouble(1) : 3.4j,]
311        assert_(grid128c_a.dtype == grid128c_b.dtype == np.longdouble)
312        assert_array_equal(grid128c_a, grid128c_b[0])
313
314        # different code path for single slice
315        grid64 = mgrid[0.1:0.33:0.1]
316        grid128 = mgrid[np.longdouble(0.1) : np.longdouble(0.33) : np.longdouble(0.1)]
317        assert_(grid128.dtype == np.longdouble)
318        assert_array_almost_equal(grid64, grid128)
319
320    @skip(reason="longdouble")
321    def test_accepts_npcomplexfloating(self):
322        # Related to #16466
323        assert_array_almost_equal(
324            mgrid[0.1:0.3:3j,], mgrid[0.1 : 0.3 : np.complex64(3j),]
325        )
326
327        # different code path for single slice
328        assert_array_almost_equal(
329            mgrid[0.1:0.3:3j], mgrid[0.1 : 0.3 : np.complex64(3j)]
330        )
331
332        # Related to #16945
333        grid64_a = mgrid[0.1:0.3:3.3j]
334        grid64_b = mgrid[0.1:0.3:3.3j,][0]
335        assert_(grid64_a.dtype == grid64_b.dtype == np.float64)
336        assert_array_equal(grid64_a, grid64_b)
337
338        grid128_a = mgrid[0.1 : 0.3 : np.clongdouble(3.3j)]
339        grid128_b = mgrid[0.1 : 0.3 : np.clongdouble(3.3j),][0]
340        assert_(grid128_a.dtype == grid128_b.dtype == np.longdouble)
341        assert_array_equal(grid64_a, grid64_b)
342
343
344@xfail  # (reason="r_ not implemented")
345class TestConcatenator(TestCase):
346    def test_1d(self):
347        assert_array_equal(r_[1, 2, 3, 4, 5, 6], np.array([1, 2, 3, 4, 5, 6]))
348        b = np.ones(5)
349        c = r_[b, 0, 0, b]
350        assert_array_equal(c, [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1])
351
352    def test_mixed_type(self):
353        g = r_[10.1, 1:10]
354        assert_(g.dtype == "f8")
355
356    def test_more_mixed_type(self):
357        g = r_[-10.1, np.array([1]), np.array([2, 3, 4]), 10.0]
358        assert_(g.dtype == "f8")
359
360    def test_complex_step(self):
361        # Regression test for #12262
362        g = r_[0:36:100j]
363        assert_(g.shape == (100,))
364
365        # Related to #16466
366        g = r_[0 : 36 : np.complex64(100j)]
367        assert_(g.shape == (100,))
368
369    def test_2d(self):
370        b = np.random.rand(5, 5)
371        c = np.random.rand(5, 5)
372        d = r_["1", b, c]  # append columns
373        assert_(d.shape == (5, 10))
374        assert_array_equal(d[:, :5], b)
375        assert_array_equal(d[:, 5:], c)
376        d = r_[b, c]
377        assert_(d.shape == (10, 5))
378        assert_array_equal(d[:5, :], b)
379        assert_array_equal(d[5:, :], c)
380
381    def test_0d(self):
382        assert_equal(r_[0, np.array(1), 2], [0, 1, 2])
383        assert_equal(r_[[0, 1, 2], np.array(3)], [0, 1, 2, 3])
384        assert_equal(r_[np.array(0), [1, 2, 3]], [0, 1, 2, 3])
385
386
387@xfail  # (reason="ndenumerate not implemented")
388class TestNdenumerate(TestCase):
389    def test_basic(self):
390        a = np.array([[1, 2], [3, 4]])
391        assert_equal(
392            list(ndenumerate(a)), [((0, 0), 1), ((0, 1), 2), ((1, 0), 3), ((1, 1), 4)]
393        )
394
395
396class TestIndexExpression(TestCase):
397    def test_regression_1(self):
398        # ticket #1196
399        a = np.arange(2)
400        assert_equal(a[:-1], a[s_[:-1]])
401        assert_equal(a[:-1], a[index_exp[:-1]])
402
403    def test_simple_1(self):
404        a = np.random.rand(4, 5, 6)
405
406        assert_equal(a[:, :3, [1, 2]], a[index_exp[:, :3, [1, 2]]])
407        assert_equal(a[:, :3, [1, 2]], a[s_[:, :3, [1, 2]]])
408
409
410@xfail  # (reason="ix_ not implemented")
411class TestIx_(TestCase):
412    def test_regression_1(self):
413        # Test empty untyped inputs create outputs of indexing type, gh-5804
414        (a,) = ix_(range(0))
415        assert_equal(a.dtype, np.intp)
416
417        (a,) = ix_([])
418        assert_equal(a.dtype, np.intp)
419
420        # but if the type is specified, don't change it
421        (a,) = ix_(np.array([], dtype=np.float32))
422        assert_equal(a.dtype, np.float32)
423
424    def test_shape_and_dtype(self):
425        sizes = (4, 5, 3, 2)
426        # Test both lists and arrays
427        for func in (range, np.arange):
428            arrays = ix_(*[func(sz) for sz in sizes])
429            for k, (a, sz) in enumerate(zip(arrays, sizes)):
430                assert_equal(a.shape[k], sz)
431                assert_(all(sh == 1 for j, sh in enumerate(a.shape) if j != k))
432                assert_(np.issubdtype(a.dtype, np.integer))
433
434    def test_bool(self):
435        bool_a = [True, False, True, True]
436        (int_a,) = np.nonzero(bool_a)
437        assert_equal(ix_(bool_a)[0], int_a)
438
439    def test_1d_only(self):
440        idx2d = [[1, 2, 3], [4, 5, 6]]
441        assert_raises(ValueError, ix_, idx2d)
442
443    def test_repeated_input(self):
444        length_of_vector = 5
445        x = np.arange(length_of_vector)
446        out = ix_(x, x)
447        assert_equal(out[0].shape, (length_of_vector, 1))
448        assert_equal(out[1].shape, (1, length_of_vector))
449        # check that input shape is not modified
450        assert_equal(x.shape, (length_of_vector,))
451
452
453class TestC(TestCase):
454    @xpassIfTorchDynamo  # (reason="c_ not implemented")
455    def test_c_(self):
456        a = np.c_[np.array([[1, 2, 3]]), 0, 0, np.array([[4, 5, 6]])]
457        assert_equal(a, [[1, 2, 3, 0, 0, 4, 5, 6]])
458
459
460class TestFillDiagonal(TestCase):
461    def test_basic(self):
462        a = np.zeros((3, 3), dtype=int)
463        fill_diagonal(a, 5)
464        assert_array_equal(a, np.array([[5, 0, 0], [0, 5, 0], [0, 0, 5]]))
465
466    def test_tall_matrix(self):
467        a = np.zeros((10, 3), dtype=int)
468        fill_diagonal(a, 5)
469        assert_array_equal(
470            a,
471            np.array(
472                [
473                    [5, 0, 0],
474                    [0, 5, 0],
475                    [0, 0, 5],
476                    [0, 0, 0],
477                    [0, 0, 0],
478                    [0, 0, 0],
479                    [0, 0, 0],
480                    [0, 0, 0],
481                    [0, 0, 0],
482                    [0, 0, 0],
483                ]
484            ),
485        )
486
487    def test_tall_matrix_wrap(self):
488        a = np.zeros((10, 3), dtype=int)
489        fill_diagonal(a, 5, True)
490        assert_array_equal(
491            a,
492            np.array(
493                [
494                    [5, 0, 0],
495                    [0, 5, 0],
496                    [0, 0, 5],
497                    [0, 0, 0],
498                    [5, 0, 0],
499                    [0, 5, 0],
500                    [0, 0, 5],
501                    [0, 0, 0],
502                    [5, 0, 0],
503                    [0, 5, 0],
504                ]
505            ),
506        )
507
508    def test_wide_matrix(self):
509        a = np.zeros((3, 10), dtype=int)
510        fill_diagonal(a, 5)
511        assert_array_equal(
512            a,
513            np.array(
514                [
515                    [5, 0, 0, 0, 0, 0, 0, 0, 0, 0],
516                    [0, 5, 0, 0, 0, 0, 0, 0, 0, 0],
517                    [0, 0, 5, 0, 0, 0, 0, 0, 0, 0],
518                ]
519            ),
520        )
521
522    def test_operate_4d_array(self):
523        a = np.zeros((3, 3, 3, 3), dtype=int)
524        fill_diagonal(a, 4)
525        i = np.array([0, 1, 2])
526        assert_equal(np.where(a != 0), (i, i, i, i))
527
528    def test_low_dim_handling(self):
529        # raise error with low dimensionality
530        a = np.zeros(3, dtype=int)
531        with assert_raises(ValueError):
532            fill_diagonal(a, 5)
533
534    def test_hetero_shape_handling(self):
535        # raise error with high dimensionality and
536        # shape mismatch
537        a = np.zeros((3, 3, 7, 3), dtype=int)
538        with assert_raises(ValueError):
539            fill_diagonal(a, 2)
540
541
542class TestDiagIndices(TestCase):
543    def test_diag_indices(self):
544        di = diag_indices(4)
545        a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
546        a[di] = 100
547        assert_array_equal(
548            a,
549            np.array(
550                [[100, 2, 3, 4], [5, 100, 7, 8], [9, 10, 100, 12], [13, 14, 15, 100]]
551            ),
552        )
553
554        # Now, we create indices to manipulate a 3-d array:
555        d3 = diag_indices(2, 3)
556
557        # And use it to set the diagonal of a zeros array to 1:
558        a = np.zeros((2, 2, 2), dtype=int)
559        a[d3] = 1
560        assert_array_equal(a, np.array([[[1, 0], [0, 0]], [[0, 0], [0, 1]]]))
561
562
563class TestDiagIndicesFrom(TestCase):
564    def test_diag_indices_from(self):
565        x = np.random.random((4, 4))
566        r, c = diag_indices_from(x)
567        assert_array_equal(r, np.arange(4))
568        assert_array_equal(c, np.arange(4))
569
570    def test_error_small_input(self):
571        x = np.ones(7)
572        with assert_raises(ValueError):
573            diag_indices_from(x)
574
575    def test_error_shape_mismatch(self):
576        x = np.zeros((3, 3, 2, 3), dtype=int)
577        with assert_raises(ValueError):
578            diag_indices_from(x)
579
580
581class TestNdIndex(TestCase):
582    @xfail  # (reason="ndindex not implemented")
583    def test_ndindex(self):
584        x = list(ndindex(1, 2, 3))
585        expected = [ix for ix, e in ndenumerate(np.zeros((1, 2, 3)))]
586        assert_array_equal(x, expected)
587
588        x = list(ndindex((1, 2, 3)))
589        assert_array_equal(x, expected)
590
591        # Test use of scalars and tuples
592        x = list(ndindex((3,)))
593        assert_array_equal(x, list(ndindex(3)))
594
595        # Make sure size argument is optional
596        x = list(ndindex())
597        assert_equal(x, [()])
598
599        x = list(ndindex(()))
600        assert_equal(x, [()])
601
602        # Make sure 0-sized ndindex works correctly
603        x = list(ndindex(*[0]))
604        assert_equal(x, [])
605
606
607if __name__ == "__main__":
608    run_tests()
609