~ubuntu-branches/ubuntu/precise/python-numpy/precise

« back to all changes in this revision

Viewing changes to numpy/core/tests/test_multiarray.py

  • Committer: Package Import Robot
  • Author(s): Julian Taylor
  • Date: 2012-02-11 12:55:21 UTC
  • mfrom: (7.1.9 experimental) (7.2.3 sid)
  • Revision ID: package-import@ubuntu.com-20120211125521-31q3am7pp3mvt1ho
Tags: 1:1.6.1-5ubuntu1
* debian/patches/search-multiarch-paths.patch: (LP: #818867)
  - add multiarch libdirs to numpy.distutils.system_info
* Merge from Debian unstable, remaining changes:
  - debian/patches/20_disable-plot-extension.patch
     Disable plot_directive extension, and catch ImportErrors when
     matplotlib cannot be imported, which allows us to remove
     python-matplotlib from dependencies.  This is required because
     python-numpy is in main, while python-matplotlib is in universe.
  - Build using dh_python2
    add bin/f2py* to .install files
  - keep Replaces: python-numpy (<< 1:1.3.0-4) in python-numpy-dbg
    for lucid upgrades

Show diffs side-by-side

added added

removed removed

Lines of Context:
112
112
        x.fill(x[0])
113
113
        assert_equal(x['f1'][1], x['f1'][0])
114
114
 
 
115
class TestAssignment(TestCase):
 
116
    def test_assignment_broadcasting(self):
 
117
        a = np.arange(6).reshape(2,3)
 
118
 
 
119
        # Broadcasting the input to the output
 
120
        a[...] = np.arange(3)
 
121
        assert_equal(a, [[0,1,2],[0,1,2]])
 
122
        a[...] = np.arange(2).reshape(2,1)
 
123
        assert_equal(a, [[0,0,0],[1,1,1]])
 
124
 
 
125
        # For compatibility with <= 1.5, a limited version of broadcasting
 
126
        # the output to the input.
 
127
        #
 
128
        # This behavior is inconsistent with NumPy broadcasting
 
129
        # in general, because it only uses one of the two broadcasting
 
130
        # rules (adding a new "1" dimension to the left of the shape),
 
131
        # applied to the output instead of an input. In NumPy 2.0, this kind
 
132
        # of broadcasting assignment will likely be disallowed.
 
133
        a[...] = np.arange(6)[::-1].reshape(1,2,3)
 
134
        assert_equal(a, [[5,4,3],[2,1,0]])
 
135
        # The other type of broadcasting would require a reduction operation.
 
136
        def assign(a,b):
 
137
            a[...] = b
 
138
        assert_raises(ValueError, assign, a, np.arange(12).reshape(2,2,3))
115
139
 
116
140
class TestDtypedescr(TestCase):
117
141
    def test_construction(self):
239
263
        self.assertRaises(IndexError, subscript, a, (newaxis, 0))
240
264
        self.assertRaises(IndexError, subscript, a, (newaxis,)*50)
241
265
 
 
266
    def test_overlapping_assignment(self):
 
267
        # With positive strides
 
268
        a = np.arange(4)
 
269
        a[:-1] = a[1:]
 
270
        assert_equal(a, [1,2,3,3])
 
271
 
 
272
        a = np.arange(4)
 
273
        a[1:] = a[:-1]
 
274
        assert_equal(a, [0,0,1,2])
 
275
 
 
276
        # With positive and negative strides
 
277
        a = np.arange(4)
 
278
        a[:] = a[::-1]
 
279
        assert_equal(a, [3,2,1,0])
 
280
 
 
281
        a = np.arange(6).reshape(2,3)
 
282
        a[::-1,:] = a[:,::-1]
 
283
        assert_equal(a, [[5,4,3],[2,1,0]])
 
284
 
 
285
        a = np.arange(6).reshape(2,3)
 
286
        a[::-1,::-1] = a[:,::-1]
 
287
        assert_equal(a, [[3,4,5],[0,1,2]])
 
288
 
 
289
        # With just one element overlapping
 
290
        a = np.arange(5)
 
291
        a[:3] = a[2:]
 
292
        assert_equal(a, [2,3,4,3,4])
 
293
 
 
294
        a = np.arange(5)
 
295
        a[2:] = a[:3]
 
296
        assert_equal(a, [0,1,0,1,2])
 
297
 
 
298
        a = np.arange(5)
 
299
        a[2::-1] = a[2:]
 
300
        assert_equal(a, [4,3,2,3,4])
 
301
 
 
302
        a = np.arange(5)
 
303
        a[2:] = a[2::-1]
 
304
        assert_equal(a, [0,1,2,1,0])
 
305
 
 
306
        a = np.arange(5)
 
307
        a[2::-1] = a[:1:-1]
 
308
        assert_equal(a, [2,3,4,3,4])
 
309
 
 
310
        a = np.arange(5)
 
311
        a[:1:-1] = a[2::-1]
 
312
        assert_equal(a, [0,1,0,1,2])
242
313
 
243
314
class TestCreation(TestCase):
244
315
    def test_from_attribute(self):
255
326
            msg = 'String conversion for %s' % type
256
327
            assert_equal(array(nstr, dtype=type), result, err_msg=msg)
257
328
 
 
329
    def test_non_sequence_sequence(self):
 
330
        """Should not segfault.
 
331
 
 
332
        Class Fail breaks the sequence protocol for new style classes, i.e.,
 
333
        those derived from object. Class Map is a mapping type indicated by
 
334
        raising a ValueError. At some point we may raise a warning instead
 
335
        of an error in the Fail case.
 
336
 
 
337
        """
 
338
        class Fail(object):
 
339
            def __len__(self):
 
340
                return 1
 
341
 
 
342
            def __getitem__(self, index):
 
343
                raise ValueError()
 
344
 
 
345
        class Map(object):
 
346
            def __len__(self):
 
347
                return 1
 
348
 
 
349
            def __getitem__(self, index):
 
350
                raise KeyError()
 
351
 
 
352
        a = np.array([Map()])
 
353
        assert_(a.shape == (1,))
 
354
        assert_(a.dtype == np.dtype(object))
 
355
        assert_raises(ValueError, np.array, [Fail()])
 
356
 
 
357
 
 
358
class TestStructured(TestCase):
 
359
    def test_subarray_field_access(self):
 
360
        a = np.zeros((3, 5), dtype=[('a', ('i4', (2, 2)))])
 
361
        a['a'] = np.arange(60).reshape(3, 5, 2, 2)
 
362
 
 
363
        # Since the subarray is always in C-order, these aren't equal
 
364
        assert_(np.any(a['a'].T != a.T['a']))
 
365
 
 
366
        # In Fortran order, the subarray gets appended
 
367
        # like in all other cases, not prepended as a special case
 
368
        b = a.copy(order='F')
 
369
        assert_equal(a['a'].shape, b['a'].shape)
 
370
        assert_equal(a.T['a'].shape, a.T.copy()['a'].shape)
 
371
 
 
372
 
 
373
    def test_subarray_comparison(self):
 
374
        # Check that comparisons between record arrays with
 
375
        # multi-dimensional field types work properly
 
376
        a = np.rec.fromrecords(
 
377
            [([1,2,3],'a', [[1,2],[3,4]]),([3,3,3],'b',[[0,0],[0,0]])],
 
378
            dtype=[('a', ('f4',3)), ('b', np.object), ('c', ('i4',(2,2)))])
 
379
        b = a.copy()
 
380
        assert_equal(a==b, [True,True])
 
381
        assert_equal(a!=b, [False,False])
 
382
        b[1].b = 'c'
 
383
        assert_equal(a==b, [True,False])
 
384
        assert_equal(a!=b, [False,True])
 
385
        for i in range(3):
 
386
            b[0].a = a[0].a
 
387
            b[0].a[i] = 5
 
388
            assert_equal(a==b, [False,False])
 
389
            assert_equal(a!=b, [True,True])
 
390
        for i in range(2):
 
391
            for j in range(2):
 
392
                b = a.copy()
 
393
                b[0].c[i,j] = 10
 
394
                assert_equal(a==b, [False,True])
 
395
                assert_equal(a!=b, [True,False])
 
396
 
 
397
        # Check that broadcasting with a subarray works
 
398
        a = np.array([[(0,)],[(1,)]],dtype=[('a','f8')])
 
399
        b = np.array([(0,),(0,),(1,)],dtype=[('a','f8')])
 
400
        assert_equal(a==b, [[True, True, False], [False, False, True]])
 
401
        assert_equal(b==a, [[True, True, False], [False, False, True]])
 
402
        a = np.array([[(0,)],[(1,)]],dtype=[('a','f8',(1,))])
 
403
        b = np.array([(0,),(0,),(1,)],dtype=[('a','f8',(1,))])
 
404
        assert_equal(a==b, [[True, True, False], [False, False, True]])
 
405
        assert_equal(b==a, [[True, True, False], [False, False, True]])
 
406
        a = np.array([[([0,0],)],[([1,1],)]],dtype=[('a','f8',(2,))])
 
407
        b = np.array([([0,0],),([0,1],),([1,1],)],dtype=[('a','f8',(2,))])
 
408
        assert_equal(a==b, [[True, False, False], [False, False, True]])
 
409
        assert_equal(b==a, [[True, False, False], [False, False, True]])
 
410
 
 
411
        # Check that broadcasting Fortran-style arrays with a subarray work
 
412
        a = np.array([[([0,0],)],[([1,1],)]],dtype=[('a','f8',(2,))], order='F')
 
413
        b = np.array([([0,0],),([0,1],),([1,1],)],dtype=[('a','f8',(2,))])
 
414
        assert_equal(a==b, [[True, False, False], [False, False, True]])
 
415
        assert_equal(b==a, [[True, False, False], [False, False, True]])
 
416
 
 
417
        # Check that incompatible sub-array shapes don't result to broadcasting
 
418
        x = np.zeros((1,), dtype=[('a', ('f4', (1,2))), ('b', 'i1')])
 
419
        y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')])
 
420
        assert_equal(x == y, False)
 
421
 
 
422
        x = np.zeros((1,), dtype=[('a', ('f4', (2,1))), ('b', 'i1')])
 
423
        y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')])
 
424
        assert_equal(x == y, False)
 
425
 
258
426
 
259
427
class TestBool(TestCase):
260
428
    def test_test_interning(self):
526
694
        msg = "Test complex searchsorted with nans, side='r'"
527
695
        b = a.searchsorted(a, side='r')
528
696
        assert_equal(b, np.arange(1,10), msg)
 
697
        msg = "Test searchsorted with little endian, side='l'"
 
698
        a = np.array([0,128],dtype='<i4')
 
699
        b = a.searchsorted(np.array(128,dtype='<i4'))
 
700
        assert_equal(b, 1, msg)
 
701
        msg = "Test searchsorted with big endian, side='l'"
 
702
        a = np.array([0,128],dtype='>i4')
 
703
        b = a.searchsorted(np.array(128,dtype='>i4'))
 
704
        assert_equal(b, 1, msg)
529
705
 
530
706
    def test_flatten(self):
531
707
        x0 = np.array([[1,2,3],[4,5,6]], np.int32)
549
725
        assert_equal(np.dot(a, b), a.dot(b))
550
726
        assert_equal(np.dot(np.dot(a, b), c), a.dot(b).dot(c))
551
727
 
 
728
    def test_ravel(self):
 
729
        a = np.array([[0,1],[2,3]])
 
730
        assert_equal(a.ravel(), [0,1,2,3])
 
731
        assert_(not a.ravel().flags.owndata)
 
732
        assert_equal(a.ravel('F'), [0,2,1,3])
 
733
        assert_equal(a.ravel(order='C'), [0,1,2,3])
 
734
        assert_equal(a.ravel(order='F'), [0,2,1,3])
 
735
        assert_equal(a.ravel(order='A'), [0,1,2,3])
 
736
        assert_(not a.ravel(order='A').flags.owndata)
 
737
        assert_equal(a.ravel(order='K'), [0,1,2,3])
 
738
        assert_(not a.ravel(order='K').flags.owndata)
 
739
        assert_equal(a.ravel(), a.reshape(-1))
 
740
 
 
741
        a = np.array([[0,1],[2,3]], order='F')
 
742
        assert_equal(a.ravel(), [0,1,2,3])
 
743
        assert_equal(a.ravel(order='A'), [0,2,1,3])
 
744
        assert_equal(a.ravel(order='K'), [0,2,1,3])
 
745
        assert_(not a.ravel(order='A').flags.owndata)
 
746
        assert_(not a.ravel(order='K').flags.owndata)
 
747
        assert_equal(a.ravel(), a.reshape(-1))
 
748
        assert_equal(a.ravel(order='A'), a.reshape(-1, order='A'))
 
749
 
 
750
        a = np.array([[0,1],[2,3]])[::-1,:]
 
751
        assert_equal(a.ravel(), [2,3,0,1])
 
752
        assert_equal(a.ravel(order='C'), [2,3,0,1])
 
753
        assert_equal(a.ravel(order='F'), [2,0,3,1])
 
754
        assert_equal(a.ravel(order='A'), [2,3,0,1])
 
755
        # 'K' doesn't reverse the axes of negative strides
 
756
        assert_equal(a.ravel(order='K'), [2,3,0,1])
 
757
        assert_(a.ravel(order='K').flags.owndata)
 
758
 
 
759
    def test_setasflat(self):
 
760
        # In this case, setasflat can treat a as a flat array,
 
761
        # and must treat b in chunks of 3
 
762
        a = np.arange(3*3*4).reshape(3,3,4)
 
763
        b = np.arange(3*4*3, dtype='f4').reshape(3,4,3).T
 
764
 
 
765
        assert_(not np.all(a.ravel() == b.ravel()))
 
766
        a.setasflat(b)
 
767
        assert_equal(a.ravel(), b.ravel())
 
768
 
 
769
        # A case where the strides of neither a nor b can be collapsed
 
770
        a = np.arange(3*2*4).reshape(3,2,4)[:,:,:-1]
 
771
        b = np.arange(3*3*3, dtype='f4').reshape(3,3,3).T[:,:,:-1]
 
772
 
 
773
        assert_(not np.all(a.ravel() == b.ravel()))
 
774
        a.setasflat(b)
 
775
        assert_equal(a.ravel(), b.ravel())
 
776
 
552
777
class TestSubscripting(TestCase):
553
778
    def test_test_zero_rank(self):
554
779
        x = array([1,2,3])
617
842
        p = self._loads(asbytes(s))
618
843
        assert_equal(a, p)
619
844
 
 
845
    def test_subarray_int_shape(self):
 
846
        s = "cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'V6'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nN(S'a'\np12\ng3\ntp13\n(dp14\ng12\n(g7\n(S'V4'\np15\nI0\nI1\ntp16\nRp17\n(I3\nS'|'\np18\n(g7\n(S'i1'\np19\nI0\nI1\ntp20\nRp21\n(I3\nS'|'\np22\nNNNI-1\nI-1\nI0\ntp23\nb(I2\nI2\ntp24\ntp25\nNNI4\nI1\nI0\ntp26\nbI0\ntp27\nsg3\n(g7\n(S'V2'\np28\nI0\nI1\ntp29\nRp30\n(I3\nS'|'\np31\n(g21\nI2\ntp32\nNNI2\nI1\nI0\ntp33\nbI4\ntp34\nsI6\nI1\nI0\ntp35\nbI00\nS'\\x01\\x01\\x01\\x01\\x01\\x02'\np36\ntp37\nb."
 
847
        a = np.array([(1,(1,2))], dtype=[('a', 'i1', (2,2)), ('b', 'i1', 2)])
 
848
        p = self._loads(asbytes(s))
 
849
        assert_equal(a, p)
 
850
 
620
851
 
621
852
class TestFancyIndexing(TestCase):
622
853
    def test_list(self):
702
933
            assert all(amax == aargmax.choose(*a.transpose(i,*axes)))
703
934
 
704
935
    def test_combinations(self):
705
 
        err = np.seterr(invalid="ignore")
706
 
        try:
707
 
            for arr, pos in self.nan_arr:
708
 
                assert_equal(np.argmax(arr), pos, err_msg="%r"%arr)
709
 
                assert_equal(arr[np.argmax(arr)], np.max(arr), err_msg="%r"%arr)
710
 
        finally:
711
 
            np.seterr(**err)
 
936
        for arr, pos in self.nan_arr:
 
937
            assert_equal(np.argmax(arr), pos, err_msg="%r"%arr)
 
938
            assert_equal(arr[np.argmax(arr)], np.max(arr), err_msg="%r"%arr)
712
939
 
713
940
 
714
941
class TestMinMax(TestCase):
793
1020
        assert np.all(x <= 4)
794
1021
 
795
1022
 
796
 
class TestPutmask(TestCase):
 
1023
class TestPutmask:
797
1024
    def tst_basic(self,x,T,mask,val):
798
1025
        np.putmask(x,mask,val)
799
1026
        assert np.all(x[mask] == T(val))
812
1039
                        yield self.tst_basic,x.copy().astype(T),T,mask,val
813
1040
 
814
1041
    def test_mask_size(self):
815
 
        self.assertRaises(ValueError, np.putmask,
816
 
                              np.array([1,2,3]), [True], 5)
 
1042
        assert_raises(ValueError, np.putmask, np.array([1,2,3]), [True], 5)
817
1043
 
818
1044
    def tst_byteorder(self,dtype):
819
1045
        x = np.array([1,2,3],dtype)
840
1066
        pass
841
1067
 
842
1068
 
843
 
class TestTake(TestCase):
 
1069
class TestTake:
844
1070
    def tst_basic(self,x):
845
1071
        ind = range(x.shape[0])
846
1072
        assert_array_equal(x.take(ind, axis=0), x)
858
1084
    def test_raise(self):
859
1085
        x = np.random.random(24)*100
860
1086
        x.shape = 2,3,4
861
 
        self.assertRaises(IndexError, x.take, [0,1,2], axis=0)
862
 
        self.assertRaises(IndexError, x.take, [-3], axis=0)
 
1087
        assert_raises(IndexError, x.take, [0,1,2], axis=0)
 
1088
        assert_raises(IndexError, x.take, [-3], axis=0)
863
1089
        assert_array_equal(x.take([-1], axis=0)[0], x[1])
864
1090
 
865
1091
    def test_clip(self):
922
1148
            os.unlink(self.filename)
923
1149
            #tmp_file.close()
924
1150
 
 
1151
    def test_bool_fromstring(self):
 
1152
        v = np.array([True,False,True,False], dtype=np.bool_)
 
1153
        y = np.fromstring('1 0 -2.3 0.0', sep=' ', dtype=np.bool_)
 
1154
        assert_array_equal(v, y)
 
1155
 
925
1156
    def test_empty_files_binary(self):
926
1157
        f = open(self.filename, 'w')
927
1158
        f.close()
1002
1233
                         array([1,2,3,4]),
1003
1234
                         dtype='<f4')
1004
1235
 
 
1236
    @dec.slow # takes > 1 minute on mechanical hard drive
 
1237
    def test_big_binary(self):
 
1238
        """Test workarounds for 32-bit limited fwrite, fseek, and ftell
 
1239
        calls in windows. These normally would hang doing something like this.
 
1240
        See http://projects.scipy.org/numpy/ticket/1660"""
 
1241
        if sys.platform != 'win32':
 
1242
            return
 
1243
        try:
 
1244
            # before workarounds, only up to 2**32-1 worked
 
1245
            fourgbplus = 2**32 + 2**16
 
1246
            testbytes = np.arange(8, dtype=np.int8)
 
1247
            n = len(testbytes)
 
1248
            flike = tempfile.NamedTemporaryFile()
 
1249
            f = flike.file
 
1250
            np.tile(testbytes, fourgbplus // testbytes.nbytes).tofile(f)
 
1251
            flike.seek(0)
 
1252
            a = np.fromfile(f, dtype=np.int8)
 
1253
            flike.close()
 
1254
            assert_(len(a) == fourgbplus)
 
1255
            # check only start and end for speed:
 
1256
            assert_((a[:n] == testbytes).all())
 
1257
            assert_((a[-n:] == testbytes).all())
 
1258
        except (MemoryError, ValueError):
 
1259
            pass
 
1260
 
1005
1261
    def test_string(self):
1006
1262
        self._check_from('1,2,3,4', [1., 2., 3., 4.], sep=',')
1007
1263
 
1031
1287
        v = np.array([1,2,3,4], dtype=np.int_)
1032
1288
        self._check_from('1,2,3,4', v, sep=',', dtype=np.int_)
1033
1289
 
 
1290
    def test_dtype_bool(self):
 
1291
        # can't use _check_from because fromstring can't handle True/False
 
1292
        v = np.array([True, False, True, False], dtype=np.bool_)
 
1293
        s = '1,0,-2.3,0'
 
1294
        f = open(self.filename, 'wb')
 
1295
        f.write(asbytes(s))
 
1296
        f.close()
 
1297
        y = np.fromfile(self.filename, sep=',', dtype=np.bool_)
 
1298
        assert_(y.dtype == '?')
 
1299
        assert_array_equal(y, v)
 
1300
 
1034
1301
    def test_tofile_sep(self):
1035
1302
        x = np.array([1.51, 2, 3.51, 4], dtype=float)
1036
1303
        f = open(self.filename, 'w')
1063
1330
        in_foreign_locale(self.test_tofile_format)()
1064
1331
 
1065
1332
 
1066
 
class TestFromBuffer(TestCase):
 
1333
class TestFromBuffer:
1067
1334
    def tst_basic(self,buffer,expected,kwargs):
1068
1335
        assert_array_equal(np.frombuffer(buffer,**kwargs),expected)
1069
1336
 
1188
1455
        res = dat.var(1)
1189
1456
        assert res.info == dat.info
1190
1457
 
 
1458
class TestDot(TestCase):
 
1459
    def test_dot_2args(self):
 
1460
        from numpy.core.multiarray import dot
 
1461
 
 
1462
        a = np.array([[1, 2], [3, 4]], dtype=float)
 
1463
        b = np.array([[1, 0], [1, 1]], dtype=float)
 
1464
        c = np.array([[3, 2], [7, 4]], dtype=float)
 
1465
 
 
1466
        d = dot(a, b)
 
1467
        assert_allclose(c, d)
 
1468
 
 
1469
    def test_dot_3args(self):
 
1470
        from numpy.core.multiarray import dot
 
1471
 
 
1472
        np.random.seed(22)
 
1473
        f = np.random.random_sample((1024, 16))
 
1474
        v = np.random.random_sample((16, 32))
 
1475
 
 
1476
        r = np.empty((1024, 32))
 
1477
        for i in xrange(12):
 
1478
            dot(f,v,r)
 
1479
        assert_equal(sys.getrefcount(r), 2)
 
1480
        r2 = dot(f,v,out=None)
 
1481
        assert_array_equal(r2, r)
 
1482
        assert_(r is dot(f,v,out=r))
 
1483
 
 
1484
        v = v[:,0].copy() # v.shape == (16,)
 
1485
        r = r[:,0].copy() # r.shape == (1024,)
 
1486
        r2 = dot(f,v)
 
1487
        assert_(r is dot(f,v,r))
 
1488
        assert_array_equal(r2, r)
 
1489
 
 
1490
    def test_dot_3args_errors(self):
 
1491
        from numpy.core.multiarray import dot
 
1492
 
 
1493
        np.random.seed(22)
 
1494
        f = np.random.random_sample((1024, 16))
 
1495
        v = np.random.random_sample((16, 32))
 
1496
 
 
1497
        r = np.empty((1024, 31))
 
1498
        assert_raises(ValueError, dot, f, v, r)
 
1499
 
 
1500
        r = np.empty((1024,))
 
1501
        assert_raises(ValueError, dot, f, v, r)
 
1502
 
 
1503
        r = np.empty((32,))
 
1504
        assert_raises(ValueError, dot, f, v, r)
 
1505
 
 
1506
        r = np.empty((32, 1024))
 
1507
        assert_raises(ValueError, dot, f, v, r)
 
1508
        assert_raises(ValueError, dot, f, v, r.T)
 
1509
 
 
1510
        r = np.empty((1024, 64))
 
1511
        assert_raises(ValueError, dot, f, v, r[:,::2])
 
1512
        assert_raises(ValueError, dot, f, v, r[:,:32])
 
1513
 
 
1514
        r = np.empty((1024, 32), dtype=np.float32)
 
1515
        assert_raises(ValueError, dot, f, v, r)
 
1516
 
 
1517
        r = np.empty((1024, 32), dtype=int)
 
1518
        assert_raises(ValueError, dot, f, v, r)
 
1519
 
1191
1520
 
1192
1521
class TestSummarization(TestCase):
1193
1522
    def test_1d(self):
1243
1572
    def _test_simple2d(self, dt):
1244
1573
        # Test zero and one padding for simple data type
1245
1574
        x = np.array([[0, 1], [2, 3]], dtype=dt)
1246
 
        r = [np.array([[0, 0, 0], [0, 0, 1]], dtype=dt), 
1247
 
             np.array([[0, 0, 0], [0, 1, 0]], dtype=dt), 
1248
 
             np.array([[0, 0, 1], [0, 2, 3]], dtype=dt), 
 
1575
        r = [np.array([[0, 0, 0], [0, 0, 1]], dtype=dt),
 
1576
             np.array([[0, 0, 0], [0, 1, 0]], dtype=dt),
 
1577
             np.array([[0, 0, 1], [0, 2, 3]], dtype=dt),
1249
1578
             np.array([[0, 1, 0], [2, 3, 0]], dtype=dt)]
1250
1579
        l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0], NEIGH_MODE['zero'])
1251
1580
        assert_array_equal(l, r)
1252
1581
 
1253
 
        r = [np.array([[1, 1, 1], [1, 0, 1]], dtype=dt), 
1254
 
             np.array([[1, 1, 1], [0, 1, 1]], dtype=dt), 
1255
 
             np.array([[1, 0, 1], [1, 2, 3]], dtype=dt), 
 
1582
        r = [np.array([[1, 1, 1], [1, 0, 1]], dtype=dt),
 
1583
             np.array([[1, 1, 1], [0, 1, 1]], dtype=dt),
 
1584
             np.array([[1, 0, 1], [1, 2, 3]], dtype=dt),
1256
1585
             np.array([[0, 1, 1], [2, 3, 1]], dtype=dt)]
1257
1586
        l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0], NEIGH_MODE['one'])
1258
1587
        assert_array_equal(l, r)
1259
1588
 
1260
 
        r = [np.array([[4, 4, 4], [4, 0, 1]], dtype=dt), 
1261
 
             np.array([[4, 4, 4], [0, 1, 4]], dtype=dt), 
1262
 
             np.array([[4, 0, 1], [4, 2, 3]], dtype=dt), 
 
1589
        r = [np.array([[4, 4, 4], [4, 0, 1]], dtype=dt),
 
1590
             np.array([[4, 4, 4], [0, 1, 4]], dtype=dt),
 
1591
             np.array([[4, 0, 1], [4, 2, 3]], dtype=dt),
1263
1592
             np.array([[0, 1, 4], [2, 3, 4]], dtype=dt)]
1264
1593
        l = test_neighborhood_iterator(x, [-1, 0, -1, 1], 4, NEIGH_MODE['constant'])
1265
1594
        assert_array_equal(l, r)
1276
1605
 
1277
1606
    def _test_mirror2d(self, dt):
1278
1607
        x = np.array([[0, 1], [2, 3]], dtype=dt)
1279
 
        r = [np.array([[0, 0, 1], [0, 0, 1]], dtype=dt), 
1280
 
             np.array([[0, 1, 1], [0, 1, 1]], dtype=dt), 
1281
 
             np.array([[0, 0, 1], [2, 2, 3]], dtype=dt), 
 
1608
        r = [np.array([[0, 0, 1], [0, 0, 1]], dtype=dt),
 
1609
             np.array([[0, 1, 1], [0, 1, 1]], dtype=dt),
 
1610
             np.array([[0, 0, 1], [2, 2, 3]], dtype=dt),
1282
1611
             np.array([[0, 1, 1], [2, 3, 3]], dtype=dt)]
1283
1612
        l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0], NEIGH_MODE['mirror'])
1284
1613
        assert_array_equal(l, r)
1573
1902
            self._check('^ixxxx', [('f0', 'i'), ('', 'V4')])
1574
1903
            self._check('^i7x', [('f0', 'i'), ('', 'V7')])
1575
1904
 
 
1905
        def test_native_padding_3(self):
 
1906
            dt = np.dtype([('a', 'b'), ('b', 'i'), ('sub', np.dtype('b,i')), ('c', 'i')], align=True)
 
1907
            self._check("T{b:a:xxxi:b:T{b:f0:=i:f1:}:sub:xxxi:c:}", dt)
 
1908
 
 
1909
            dt = np.dtype([('a', 'b'), ('b', 'i'), ('c', 'b'), ('d', 'b'), ('e', 'b'), ('sub', np.dtype('b,i', align=True))])
 
1910
            self._check("T{b:a:=i:b:b:c:b:d:b:e:T{b:f0:xxxi:f1:}:sub:}", dt)
 
1911
 
 
1912
        def test_padding_with_array_inside_struct(self):
 
1913
            dt = np.dtype([('a', 'b'), ('b', 'i'), ('c', 'b', (3,)), ('d', 'i')], align=True)
 
1914
            self._check("T{b:a:xxxi:b:3b:c:xi:d:}", dt)
 
1915
 
1576
1916
        def test_byteorder_inside_struct(self):
1577
1917
            # The byte order after @T{=i} should be '=', not '@'.
1578
1918
            # Check this by noting the absence of native alignment.
1629
1969
                  ('l', 'S4'),
1630
1970
                  ('m', 'U4'),
1631
1971
                  ('n', 'V3'),
1632
 
                  ('o', '?')]
 
1972
                  ('o', '?'),
 
1973
                  ('p', np.half),
 
1974
                 ]
1633
1975
            x = np.array([(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1634
 
                           asbytes('aaaa'), 'bbbb', asbytes('xxx'), True)],
 
1976
                           asbytes('aaaa'), 'bbbb', asbytes('xxx'), True, 1.0)],
1635
1977
                         dtype=dt)
1636
1978
            self._check_roundtrip(x)
1637
1979
 
1663
2005
                x = np.array([1,2,3], dtype='<q')
1664
2006
                assert_raises(ValueError, self._check_roundtrip, x)
1665
2007
 
 
2008
        def test_roundtrip_half(self):
 
2009
            half_list = [
 
2010
                1.0,
 
2011
                -2.0,
 
2012
                6.5504 * 10**4, #  (max half precision)
 
2013
                2**-14, # ~= 6.10352 * 10**-5 (minimum positive normal)
 
2014
                2**-24, # ~= 5.96046 * 10**-8 (minimum strictly positive subnormal)
 
2015
                0.0,
 
2016
                -0.0,
 
2017
                float('+inf'),
 
2018
                float('-inf'),
 
2019
                0.333251953125, # ~= 1/3
 
2020
            ]
 
2021
 
 
2022
            x = np.array(half_list, dtype='>e')
 
2023
            self._check_roundtrip(x)
 
2024
            x = np.array(half_list, dtype='<e')
 
2025
            self._check_roundtrip(x)
 
2026
 
1666
2027
        def test_export_simple_1d(self):
1667
2028
            x = np.array([1,2,3,4,5], dtype='i')
1668
2029
            y = memoryview(x)
1713
2074
                  ('l', 'S4'),
1714
2075
                  ('m', 'U4'),
1715
2076
                  ('n', 'V3'),
1716
 
                  ('o', '?')]
 
2077
                  ('o', '?'),
 
2078
                  ('p', np.half),
 
2079
                 ]
1717
2080
            x = np.array([(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1718
 
                           asbytes('aaaa'), 'bbbb', asbytes('   '), True)],
 
2081
                           asbytes('aaaa'), 'bbbb', asbytes('   '), True, 1.0)],
1719
2082
                         dtype=dt)
1720
2083
            y = memoryview(x)
1721
2084
            assert_equal(y.shape, (1,))
1724
2087
 
1725
2088
            sz = sum([dtype(b).itemsize for a, b in dt])
1726
2089
            if dtype('l').itemsize == 4:
1727
 
                assert_equal(y.format, 'T{b:a:=h:b:i:c:l:d:^q:dx:B:e:@H:f:=I:g:L:h:^Q:hx:=f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:}')
 
2090
                assert_equal(y.format, 'T{b:a:=h:b:i:c:l:d:^q:dx:B:e:@H:f:=I:g:L:h:^Q:hx:=f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}')
1728
2091
            else:
1729
 
                assert_equal(y.format, 'T{b:a:=h:b:i:c:q:d:^q:dx:B:e:@H:f:=I:g:Q:h:^Q:hx:=f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:}')
 
2092
                assert_equal(y.format, 'T{b:a:=h:b:i:c:q:d:^q:dx:B:e:@H:f:=I:g:Q:h:^Q:hx:=f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}')
1730
2093
            assert_equal(y.strides, (sz,))
1731
2094
            assert_equal(y.itemsize, sz)
1732
2095
 
1768
2131
            count_2 = sys.getrefcount(np.core._internal)
1769
2132
            assert_equal(count_1, count_2)
1770
2133
 
 
2134
        def test_padded_struct_array(self):
 
2135
            dt1 = np.dtype([('a', 'b'), ('b', 'i'), ('sub', np.dtype('b,i')), ('c', 'i')], align=True)
 
2136
            x1 = np.arange(dt1.itemsize, dtype=np.int8).view(dt1)
 
2137
            self._check_roundtrip(x1)
 
2138
 
 
2139
            dt2 = np.dtype([('a', 'b'), ('b', 'i'), ('c', 'b', (3,)), ('d', 'i')], align=True)
 
2140
            x2 = np.arange(dt2.itemsize, dtype=np.int8).view(dt2)
 
2141
            self._check_roundtrip(x2)
 
2142
 
 
2143
            dt3 = np.dtype([('a', 'b'), ('b', 'i'), ('c', 'b'), ('d', 'b'), ('e', 'b'), ('sub', np.dtype('b,i', align=True))])
 
2144
            x3 = np.arange(dt3.itemsize, dtype=np.int8).view(dt3)
 
2145
            self._check_roundtrip(x3)
1771
2146
 
1772
2147
if __name__ == "__main__":
1773
2148
    run_module_suite()