~jtaylor/ubuntu/precise/python-numpy/multiarch-fix-818867

« back to all changes in this revision

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

  • Committer: Bazaar Package Importer
  • Author(s): Sandro Tosi
  • Date: 2010-10-07 10:19:13 UTC
  • mfrom: (7.1.5 sid)
  • Revision ID: james.westby@ubuntu.com-20101007101913-8b1kmt8ho4upcl9s
Tags: 1:1.4.1-5
* debian/patches/10_use_local_python.org_object.inv_sphinx.diff
  - fixed small typo in description
* debian/patches/changeset_r8364.diff
  - fix memory corruption (double free); thanks to Joseph Barillari for the
    report and to Michael Gilbert for pushing resolution; Closes: #581058

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
from numpy.testing import *
2
 
from numpy.core import *
3
 
import numpy as np
4
 
 
5
 
class TestCtor(TestCase):
6
 
    def test_basic(self):
7
 
        A = array([[1,2],[3,4]])
8
 
        mA = matrix(A)
9
 
        assert all(mA.A == A)
10
 
 
11
 
        B = bmat("A,A;A,A")
12
 
        C = bmat([[A,A], [A,A]])
13
 
        D = array([[1,2,1,2],
14
 
                   [3,4,3,4],
15
 
                   [1,2,1,2],
16
 
                   [3,4,3,4]])
17
 
        assert all(B.A == D)
18
 
        assert all(C.A == D)
19
 
 
20
 
        E = array([[5,6],[7,8]])
21
 
        AEresult = matrix([[1,2,5,6],[3,4,7,8]])
22
 
        assert all(bmat([A,E]) == AEresult)
23
 
 
24
 
        vec = arange(5)
25
 
        mvec = matrix(vec)
26
 
        assert mvec.shape == (1,5)
27
 
 
28
 
    def test_bmat_nondefault_str(self):
29
 
        A = array([[1,2],[3,4]])
30
 
        B = array([[5,6],[7,8]])
31
 
        Aresult = array([[1,2,1,2],
32
 
                         [3,4,3,4],
33
 
                         [1,2,1,2],
34
 
                         [3,4,3,4]])
35
 
        Bresult = array([[5,6,5,6],
36
 
                         [7,8,7,8],
37
 
                         [5,6,5,6],
38
 
                         [7,8,7,8]])
39
 
        mixresult = array([[1,2,5,6],
40
 
                           [3,4,7,8],
41
 
                           [5,6,1,2],
42
 
                           [7,8,3,4]])
43
 
        assert all(bmat("A,A;A,A") == Aresult)
44
 
        assert all(bmat("A,A;A,A",ldict={'A':B}) == Aresult)
45
 
        assert_raises(TypeError, bmat, "A,A;A,A",gdict={'A':B})
46
 
        assert all(bmat("A,A;A,A",ldict={'A':A},gdict={'A':B}) == Aresult)
47
 
        b2 = bmat("A,B;C,D",ldict={'A':A,'B':B},gdict={'C':B,'D':A})
48
 
        assert all(b2 == mixresult)
49
 
 
50
 
 
51
 
class TestProperties(TestCase):
52
 
    def test_sum(self):
53
 
        """Test whether matrix.sum(axis=1) preserves orientation.
54
 
        Fails in NumPy <= 0.9.6.2127.
55
 
        """
56
 
        M = matrix([[1,2,0,0],
57
 
                   [3,4,0,0],
58
 
                   [1,2,1,2],
59
 
                   [3,4,3,4]])
60
 
        sum0 = matrix([8,12,4,6])
61
 
        sum1 = matrix([3,7,6,14]).T
62
 
        sumall = 30
63
 
        assert_array_equal(sum0, M.sum(axis=0))
64
 
        assert_array_equal(sum1, M.sum(axis=1))
65
 
        assert sumall == M.sum()
66
 
 
67
 
 
68
 
    def test_prod(self):
69
 
        x = matrix([[1,2,3],[4,5,6]])
70
 
        assert x.prod() == 720
71
 
        assert all(x.prod(0) == matrix([[4,10,18]]))
72
 
        assert all(x.prod(1) == matrix([[6],[120]]))
73
 
 
74
 
        y = matrix([0,1,3])
75
 
        assert y.prod() == 0
76
 
 
77
 
    def test_max(self):
78
 
        x = matrix([[1,2,3],[4,5,6]])
79
 
        assert x.max() == 6
80
 
        assert all(x.max(0) == matrix([[4,5,6]]))
81
 
        assert all(x.max(1) == matrix([[3],[6]]))
82
 
 
83
 
    def test_min(self):
84
 
        x = matrix([[1,2,3],[4,5,6]])
85
 
        assert x.min() == 1
86
 
        assert all(x.min(0) == matrix([[1,2,3]]))
87
 
        assert all(x.min(1) == matrix([[1],[4]]))
88
 
 
89
 
    def test_ptp(self):
90
 
        x = np.arange(4).reshape((2,2))
91
 
        assert x.ptp() == 3
92
 
        assert all(x.ptp(0) == array([2, 2]))
93
 
        assert all(x.ptp(1) == array([1, 1]))
94
 
 
95
 
    def test_var(self):
96
 
        x = np.arange(9).reshape((3,3))
97
 
        mx = x.view(np.matrix)
98
 
        assert_equal(x.var(ddof=0), mx.var(ddof=0))
99
 
        assert_equal(x.var(ddof=1), mx.var(ddof=1))
100
 
 
101
 
    def test_basic(self):
102
 
        import numpy.linalg as linalg
103
 
 
104
 
        A = array([[1., 2.],
105
 
                   [3., 4.]])
106
 
        mA = matrix(A)
107
 
        assert allclose(linalg.inv(A), mA.I)
108
 
        assert all(array(transpose(A) == mA.T))
109
 
        assert all(array(transpose(A) == mA.H))
110
 
        assert all(A == mA.A)
111
 
 
112
 
        B = A + 2j*A
113
 
        mB = matrix(B)
114
 
        assert allclose(linalg.inv(B), mB.I)
115
 
        assert all(array(transpose(B) == mB.T))
116
 
        assert all(array(conjugate(transpose(B)) == mB.H))
117
 
 
118
 
    def test_pinv(self):
119
 
        x = matrix(arange(6).reshape(2,3))
120
 
        xpinv = matrix([[-0.77777778,  0.27777778],
121
 
                        [-0.11111111,  0.11111111],
122
 
                        [ 0.55555556, -0.05555556]])
123
 
        assert_almost_equal(x.I, xpinv)
124
 
 
125
 
    def test_comparisons(self):
126
 
        A = arange(100).reshape(10,10)
127
 
        mA = matrix(A)
128
 
        mB = matrix(A) + 0.1
129
 
        assert all(mB == A+0.1)
130
 
        assert all(mB == matrix(A+0.1))
131
 
        assert not any(mB == matrix(A-0.1))
132
 
        assert all(mA < mB)
133
 
        assert all(mA <= mB)
134
 
        assert all(mA <= mA)
135
 
        assert not any(mA < mA)
136
 
 
137
 
        assert not any(mB < mA)
138
 
        assert all(mB >= mA)
139
 
        assert all(mB >= mB)
140
 
        assert not any(mB > mB)
141
 
 
142
 
        assert all(mA == mA)
143
 
        assert not any(mA == mB)
144
 
        assert all(mB != mA)
145
 
 
146
 
        assert not all(abs(mA) > 0)
147
 
        assert all(abs(mB > 0))
148
 
 
149
 
    def test_asmatrix(self):
150
 
        A = arange(100).reshape(10,10)
151
 
        mA = asmatrix(A)
152
 
        A[0,0] = -10
153
 
        assert A[0,0] == mA[0,0]
154
 
 
155
 
    def test_noaxis(self):
156
 
        A = matrix([[1,0],[0,1]])
157
 
        assert A.sum() == matrix(2)
158
 
        assert A.mean() == matrix(0.5)
159
 
 
160
 
    def test_repr(self):
161
 
        A = matrix([[1,0],[0,1]])
162
 
        assert repr(A) == "matrix([[1, 0],\n        [0, 1]])"
163
 
 
164
 
class TestCasting(TestCase):
165
 
    def test_basic(self):
166
 
        A = arange(100).reshape(10,10)
167
 
        mA = matrix(A)
168
 
 
169
 
        mB = mA.copy()
170
 
        O = ones((10,10), float64) * 0.1
171
 
        mB = mB + O
172
 
        assert mB.dtype.type == float64
173
 
        assert all(mA != mB)
174
 
        assert all(mB == mA+0.1)
175
 
 
176
 
        mC = mA.copy()
177
 
        O = ones((10,10), complex128)
178
 
        mC = mC * O
179
 
        assert mC.dtype.type == complex128
180
 
        assert all(mA != mB)
181
 
 
182
 
 
183
 
class TestAlgebra(TestCase):
184
 
    def test_basic(self):
185
 
        import numpy.linalg as linalg
186
 
 
187
 
        A = array([[1., 2.],
188
 
                   [3., 4.]])
189
 
        mA = matrix(A)
190
 
 
191
 
        B = identity(2)
192
 
        for i in xrange(6):
193
 
            assert allclose((mA ** i).A, B)
194
 
            B = dot(B, A)
195
 
 
196
 
        Ainv = linalg.inv(A)
197
 
        B = identity(2)
198
 
        for i in xrange(6):
199
 
            assert allclose((mA ** -i).A, B)
200
 
            B = dot(B, Ainv)
201
 
 
202
 
        assert allclose((mA * mA).A, dot(A, A))
203
 
        assert allclose((mA + mA).A, (A + A))
204
 
        assert allclose((3*mA).A, (3*A))
205
 
 
206
 
        mA2 = matrix(A)
207
 
        mA2 *= 3
208
 
        assert allclose(mA2.A, 3*A)
209
 
 
210
 
    def test_pow(self):
211
 
        """Test raising a matrix to an integer power works as expected."""
212
 
        m = matrix("1. 2.; 3. 4.")
213
 
        m2 = m.copy()
214
 
        m2 **= 2
215
 
        mi = m.copy()
216
 
        mi **= -1
217
 
        m4 = m2.copy()
218
 
        m4 **= 2
219
 
        assert_array_almost_equal(m2, m**2)
220
 
        assert_array_almost_equal(m4, np.dot(m2, m2))
221
 
        assert_array_almost_equal(np.dot(mi, m), np.eye(2))
222
 
 
223
 
    def test_notimplemented(self):
224
 
        '''Check that 'not implemented' operations produce a failure.'''
225
 
        A = matrix([[1., 2.],
226
 
                    [3., 4.]])
227
 
 
228
 
        # __rpow__
229
 
        try:
230
 
            1.0**A
231
 
        except TypeError:
232
 
            pass
233
 
        else:
234
 
            self.fail("matrix.__rpow__ doesn't raise a TypeError")
235
 
 
236
 
        # __mul__ with something not a list, ndarray, tuple, or scalar
237
 
        try:
238
 
            A*object()
239
 
        except TypeError:
240
 
            pass
241
 
        else:
242
 
            self.fail("matrix.__mul__ with non-numeric object doesn't raise"
243
 
                      "a TypeError")
244
 
 
245
 
class TestMatrixReturn(TestCase):
246
 
    def test_instance_methods(self):
247
 
        a = matrix([1.0], dtype='f8')
248
 
        methodargs = {
249
 
            'astype' : ('intc',),
250
 
            'clip' : (0.0, 1.0),
251
 
            'compress' : ([1],),
252
 
            'repeat' : (1,),
253
 
            'reshape' : (1,),
254
 
            'swapaxes' : (0,0)
255
 
            }
256
 
        excluded_methods = [
257
 
            'argmin', 'choose', 'dump', 'dumps', 'fill', 'getfield',
258
 
            'getA', 'getA1', 'item', 'nonzero', 'put', 'putmask', 'resize',
259
 
            'searchsorted', 'setflags', 'setfield', 'sort', 'take',
260
 
            'tofile', 'tolist', 'tostring', 'all', 'any', 'sum',
261
 
            'argmax', 'argmin', 'min', 'max', 'mean', 'var', 'ptp',
262
 
            'prod', 'std', 'ctypes', 'itemset'
263
 
            ]
264
 
        for attrib in dir(a):
265
 
            if attrib.startswith('_') or attrib in excluded_methods:
266
 
                continue
267
 
            f = eval('a.%s' % attrib)
268
 
            if callable(f):
269
 
                # reset contents of a
270
 
                a.astype('f8')
271
 
                a.fill(1.0)
272
 
                if attrib in methodargs:
273
 
                    args = methodargs[attrib]
274
 
                else:
275
 
                    args = ()
276
 
                b = f(*args)
277
 
                assert type(b) is matrix, "%s" % attrib
278
 
        assert type(a.real) is matrix
279
 
        assert type(a.imag) is matrix
280
 
        c,d = matrix([0.0]).nonzero()
281
 
        assert type(c) is matrix
282
 
        assert type(d) is matrix
283
 
 
284
 
 
285
 
class TestIndexing(TestCase):
286
 
    def test_basic(self):
287
 
        x = asmatrix(zeros((3,2),float))
288
 
        y = zeros((3,1),float)
289
 
        y[:,0] = [0.8,0.2,0.3]
290
 
        x[:,1] = y>0.5
291
 
        assert_equal(x, [[0,1],[0,0],[0,0]])
292
 
 
293
 
 
294
 
class TestNewScalarIndexing(TestCase):
295
 
    def setUp(self):
296
 
        self.a = matrix([[1, 2],[3,4]])
297
 
 
298
 
    def test_dimesions(self):
299
 
        a = self.a
300
 
        x = a[0]
301
 
        assert_equal(x.ndim, 2)
302
 
 
303
 
    def test_array_from_matrix_list(self):
304
 
        a = self.a
305
 
        x = array([a, a])
306
 
        assert_equal(x.shape, [2,2,2])
307
 
 
308
 
    def test_array_to_list(self):
309
 
        a = self.a
310
 
        assert_equal(a.tolist(),[[1, 2], [3, 4]])
311
 
 
312
 
    def test_fancy_indexing(self):
313
 
        a = self.a
314
 
        x = a[1, [0,1,0]]
315
 
        assert isinstance(x, matrix)
316
 
        assert_equal(x, matrix([[3,  4,  3]]))
317
 
        x = a[[1,0]]
318
 
        assert isinstance(x, matrix)
319
 
        assert_equal(x, matrix([[3,  4], [1, 2]]))
320
 
        x = a[[[1],[0]],[[1,0],[0,1]]]
321
 
        assert isinstance(x, matrix)
322
 
        assert_equal(x, matrix([[4,  3], [1,  2]]))
323
 
 
324
 
    def test_matrix_element(self):
325
 
        x = matrix([[1,2,3],[4,5,6]])
326
 
        assert_equal(x[0][0],matrix([[1,2,3]]))
327
 
        assert_equal(x[0][0].shape,(1,3))
328
 
        assert_equal(x[0].shape,(1,3))
329
 
        assert_equal(x[:,0].shape,(2,1))
330
 
 
331
 
        x = matrix(0)
332
 
        assert_equal(x[0,0],0)
333
 
        assert_equal(x[0],0)
334
 
        assert_equal(x[:,0].shape,x.shape)
335
 
 
336
 
    def test_scalar_indexing(self):
337
 
        x = asmatrix(zeros((3,2),float))
338
 
        assert_equal(x[0,0],x[0][0])
339
 
 
340
 
    def test_row_column_indexing(self):
341
 
        x = asmatrix(np.eye(2))
342
 
        assert_array_equal(x[0,:],[[1,0]])
343
 
        assert_array_equal(x[1,:],[[0,1]])
344
 
        assert_array_equal(x[:,0],[[1],[0]])
345
 
        assert_array_equal(x[:,1],[[0],[1]])
346
 
 
347
 
    def test_boolean_indexing(self):
348
 
        A = arange(6)
349
 
        A.shape = (3,2)
350
 
        x = asmatrix(A)
351
 
        assert_array_equal(x[:,array([True,False])],x[:,0])
352
 
        assert_array_equal(x[array([True,False,False]),:],x[0,:])
353
 
 
354
 
    def test_list_indexing(self):
355
 
        A = arange(6)
356
 
        A.shape = (3,2)
357
 
        x = asmatrix(A)
358
 
        assert_array_equal(x[:,[1,0]],x[:,::-1])
359
 
        assert_array_equal(x[[2,1,0],:],x[::-1,:])
360
 
 
361
 
 
362
 
if __name__ == "__main__":
363
 
    run_module_suite()