comparison DEPENDENCIES/mingw32/Python27/Lib/site-packages/numpy/matrixlib/tests/test_defmatrix.py @ 87:2a2c65a20a8b

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