Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
test_defmatrix.py456 linesDownload Raw Back to tests
1import collections.abc
2
3import numpy as np
4from numpy import asmatrix, bmat, matrix
5from numpy.linalg import matrix_power
6from numpy.testing import (
7    assert_,
8    assert_almost_equal,
9    assert_array_almost_equal,
10    assert_array_equal,
11    assert_equal,
12    assert_raises,
13)
14
15
16class TestCtor:
17    def test_basic(self):
18        A = np.array([[1, 2], [3, 4]])
19        mA = matrix(A)
20        assert_(np.all(mA.A == A))
21
22        B = bmat("A,A;A,A")
23        C = bmat([[A, A], [A, A]])
24        D = np.array([[1, 2, 1, 2],
25                      [3, 4, 3, 4],
26                      [1, 2, 1, 2],
27                      [3, 4, 3, 4]])
28        assert_(np.all(B.A == D))
29        assert_(np.all(C.A == D))
30
31        E = np.array([[5, 6], [7, 8]])
32        AEresult = matrix([[1, 2, 5, 6], [3, 4, 7, 8]])
33        assert_(np.all(bmat([A, E]) == AEresult))
34
35        vec = np.arange(5)
36        mvec = matrix(vec)
37        assert_(mvec.shape == (1, 5))
38
39    def test_exceptions(self):
40        # Check for ValueError when called with invalid string data.
41        assert_raises(ValueError, matrix, "invalid")
42
43    def test_bmat_nondefault_str(self):
44        A = np.array([[1, 2], [3, 4]])
45        B = np.array([[5, 6], [7, 8]])
46        Aresult = np.array([[1, 2, 1, 2],
47                            [3, 4, 3, 4],
48                            [1, 2, 1, 2],
49                            [3, 4, 3, 4]])
50        mixresult = np.array([[1, 2, 5, 6],
51                              [3, 4, 7, 8],
52                              [5, 6, 1, 2],
53                              [7, 8, 3, 4]])
54        assert_(np.all(bmat("A,A;A,A") == Aresult))
55        assert_(np.all(bmat("A,A;A,A", ldict={'A': B}) == Aresult))
56        assert_raises(TypeError, bmat, "A,A;A,A", gdict={'A': B})
57        assert_(
58            np.all(bmat("A,A;A,A", ldict={'A': A}, gdict={'A': B}) == Aresult))
59        b2 = bmat("A,B;C,D", ldict={'A': A, 'B': B}, gdict={'C': B, 'D': A})
60        assert_(np.all(b2 == mixresult))
61
62
63class TestProperties:
64    def test_sum(self):
65        """Test whether matrix.sum(axis=1) preserves orientation.
66        Fails in NumPy <= 0.9.6.2127.
67        """
68        M = matrix([[1, 2, 0, 0],
69                   [3, 4, 0, 0],
70                   [1, 2, 1, 2],
71                   [3, 4, 3, 4]])
72        sum0 = matrix([8, 12, 4, 6])
73        sum1 = matrix([3, 7, 6, 14]).T
74        sumall = 30
75        assert_array_equal(sum0, M.sum(axis=0))
76        assert_array_equal(sum1, M.sum(axis=1))
77        assert_equal(sumall, M.sum())
78
79        assert_array_equal(sum0, np.sum(M, axis=0))
80        assert_array_equal(sum1, np.sum(M, axis=1))
81        assert_equal(sumall, np.sum(M))
82
83    def test_prod(self):
84        x = matrix([[1, 2, 3], [4, 5, 6]])
85        assert_equal(x.prod(), 720)
86        assert_equal(x.prod(0), matrix([[4, 10, 18]]))
87        assert_equal(x.prod(1), matrix([[6], [120]]))
88
89        assert_equal(np.prod(x), 720)
90        assert_equal(np.prod(x, axis=0), matrix([[4, 10, 18]]))
91        assert_equal(np.prod(x, axis=1), matrix([[6], [120]]))
92
93        y = matrix([0, 1, 3])
94        assert_(y.prod() == 0)
95
96    def test_max(self):
97        x = matrix([[1, 2, 3], [4, 5, 6]])
98        assert_equal(x.max(), 6)
99        assert_equal(x.max(0), matrix([[4, 5, 6]]))
100        assert_equal(x.max(1), matrix([[3], [6]]))
101
102        assert_equal(np.max(x), 6)
103        assert_equal(np.max(x, axis=0), matrix([[4, 5, 6]]))
104        assert_equal(np.max(x, axis=1), matrix([[3], [6]]))
105
106    def test_min(self):
107        x = matrix([[1, 2, 3], [4, 5, 6]])
108        assert_equal(x.min(), 1)
109        assert_equal(x.min(0), matrix([[1, 2, 3]]))
110        assert_equal(x.min(1), matrix([[1], [4]]))
111
112        assert_equal(np.min(x), 1)
113        assert_equal(np.min(x, axis=0), matrix([[1, 2, 3]]))
114        assert_equal(np.min(x, axis=1), matrix([[1], [4]]))
115
116    def test_ptp(self):
117        x = np.arange(4).reshape((2, 2))
118        mx = x.view(np.matrix)
119        assert_(mx.ptp() == 3)
120        assert_(np.all(mx.ptp(0) == np.array([2, 2])))
121        assert_(np.all(mx.ptp(1) == np.array([1, 1])))
122
123    def test_var(self):
124        x = np.arange(9).reshape((3, 3))
125        mx = x.view(np.matrix)
126        assert_equal(x.var(ddof=0), mx.var(ddof=0))
127        assert_equal(x.var(ddof=1), mx.var(ddof=1))
128
129    def test_basic(self):
130        import numpy.linalg as linalg
131
132        A = np.array([[1., 2.],
133                      [3., 4.]])
134        mA = matrix(A)
135        assert_(np.allclose(linalg.inv(A), mA.I))
136        assert_(np.all(np.array(np.transpose(A) == mA.T)))
137        assert_(np.all(np.array(np.transpose(A) == mA.H)))
138        assert_(np.all(A == mA.A))
139
140        B = A + 2j * A
141        mB = matrix(B)
142        assert_(np.allclose(linalg.inv(B), mB.I))
143        assert_(np.all(np.array(np.transpose(B) == mB.T)))
144        assert_(np.all(np.array(np.transpose(B).conj() == mB.H)))
145
146    def test_pinv(self):
147        x = matrix(np.arange(6).reshape(2, 3))
148        xpinv = matrix([[-0.77777778,  0.27777778],
149                        [-0.11111111,  0.11111111],
150                        [ 0.55555556, -0.05555556]])
151        assert_almost_equal(x.I, xpinv)
152
153    def test_comparisons(self):
154        A = np.arange(100).reshape(10, 10)
155        mA = matrix(A)
156        mB = matrix(A) + 0.1
157        assert_(np.all(mB == A + 0.1))
158        assert_(np.all(mB == matrix(A + 0.1)))
159        assert_(not np.any(mB == matrix(A - 0.1)))
160        assert_(np.all(mA < mB))
161        assert_(np.all(mA <= mB))
162        assert_(np.all(mA <= mA))
163        assert_(not np.any(mA < mA))
164
165        assert_(not np.any(mB < mA))
166        assert_(np.all(mB >= mA))
167        assert_(np.all(mB >= mB))
168        assert_(not np.any(mB > mB))
169
170        assert_(np.all(mA == mA))
171        assert_(not np.any(mA == mB))
172        assert_(np.all(mB != mA))
173
174        assert_(not np.all(abs(mA) > 0))
175        assert_(np.all(abs(mB > 0)))
176
177    def test_asmatrix(self):
178        A = np.arange(100).reshape(10, 10)
179        mA = asmatrix(A)
180        A[0, 0] = -10
181        assert_(A[0, 0] == mA[0, 0])
182
183    def test_noaxis(self):
184        A = matrix([[1, 0], [0, 1]])
185        assert_(A.sum() == matrix(2))
186        assert_(A.mean() == matrix(0.5))
187
188    def test_repr(self):
189        A = matrix([[1, 0], [0, 1]])
190        assert_(repr(A) == "matrix([[1, 0],\n        [0, 1]])")
191
192    def test_make_bool_matrix_from_str(self):
193        A = matrix('True; True; False')
194        B = matrix([[True], [True], [False]])
195        assert_array_equal(A, B)
196
197class TestCasting:
198    def test_basic(self):
199        A = np.arange(100).reshape(10, 10)
200        mA = matrix(A)
201
202        mB = mA.copy()
203        O = np.ones((10, 10), np.float64) * 0.1
204        mB = mB + O
205        assert_(mB.dtype.type == np.float64)
206        assert_(np.all(mA != mB))
207        assert_(np.all(mB == mA + 0.1))
208
209        mC = mA.copy()
210        O = np.ones((10, 10), np.complex128)
211        mC = mC * O
212        assert_(mC.dtype.type == np.complex128)
213        assert_(np.all(mA != mB))
214
215
216class TestAlgebra:
217    def test_basic(self):
218        import numpy.linalg as linalg
219
220        A = np.array([[1., 2.], [3., 4.]])
221        mA = matrix(A)
222
223        B = np.identity(2)
224        for i in range(6):
225            assert_(np.allclose((mA ** i).A, B))
226            B = np.dot(B, A)
227
228        Ainv = linalg.inv(A)
229        B = np.identity(2)
230        for i in range(6):
231            assert_(np.allclose((mA ** -i).A, B))
232            B = np.dot(B, Ainv)
233
234        assert_(np.allclose((mA * mA).A, np.dot(A, A)))
235        assert_(np.allclose((mA + mA).A, (A + A)))
236        assert_(np.allclose((3 * mA).A, (3 * A)))
237
238        mA2 = matrix(A)
239        mA2 *= 3
240        assert_(np.allclose(mA2.A, 3 * A))
241
242    def test_pow(self):
243        """Test raising a matrix to an integer power works as expected."""
244        m = matrix("1. 2.; 3. 4.")
245        m2 = m.copy()
246        m2 **= 2
247        mi = m.copy()
248        mi **= -1
249        m4 = m2.copy()
250        m4 **= 2
251        assert_array_almost_equal(m2, m**2)
252        assert_array_almost_equal(m4, np.dot(m2, m2))
253        assert_array_almost_equal(np.dot(mi, m), np.eye(2))
254
255    def test_scalar_type_pow(self):
256        m = matrix([[1, 2], [3, 4]])
257        for scalar_t in [np.int8, np.uint8]:
258            two = scalar_t(2)
259            assert_array_almost_equal(m ** 2, m ** two)
260
261    def test_notimplemented(self):
262        '''Check that 'not implemented' operations produce a failure.'''
263        A = matrix([[1., 2.],
264                    [3., 4.]])
265
266        # __rpow__
267        with assert_raises(TypeError):
268            1.0**A
269
270        # __mul__ with something not a list, ndarray, tuple, or scalar
271        with assert_raises(TypeError):
272            A * object()
273
274
275class TestMatrixReturn:
276    def test_instance_methods(self):
277        a = matrix([1.0], dtype='f8')
278        methodargs = {
279            'astype': ('intc',),
280            'clip': (0.0, 1.0),
281            'compress': ([1],),
282            'repeat': (1,),
283            'reshape': (1,),
284            'swapaxes': (0, 0),
285            'dot': np.array([1.0]),
286            }
287        excluded_methods = [
288            'argmin', 'choose', 'dump', 'dumps', 'fill', 'getfield',
289            'getA', 'getA1', 'item', 'nonzero', 'put', 'putmask', 'resize',
290            'searchsorted', 'setflags', 'setfield', 'sort',
291            'partition', 'argpartition', 'to_device',
292            'take', 'tofile', 'tolist', 'tobytes', 'all', 'any',
293            'sum', 'argmax', 'argmin', 'min', 'max', 'mean', 'var', 'ptp',
294            'prod', 'std', 'ctypes', 'bitwise_count',
295            ]
296        for attrib in dir(a):
297            if attrib.startswith('_') or attrib in excluded_methods:
298                continue
299            f = getattr(a, attrib)
300            if isinstance(f, collections.abc.Callable):
301                # reset contents of a
302                a.astype('f8')
303                a.fill(1.0)
304                args = methodargs.get(attrib, ())
305                b = f(*args)
306                assert_(type(b) is matrix, f"{attrib}")
307        assert_(type(a.real) is matrix)
308        assert_(type(a.imag) is matrix)
309        c, d = matrix([0.0]).nonzero()
310        assert_(type(c) is np.ndarray)
311        assert_(type(d) is np.ndarray)
312
313
314class TestIndexing:
315    def test_basic(self):
316        x = asmatrix(np.zeros((3, 2), float))
317        y = np.zeros((3, 1), float)
318        y[:, 0] = [0.8, 0.2, 0.3]
319        x[:, 1] = y > 0.5
320        assert_equal(x, [[0, 1], [0, 0], [0, 0]])
321
322
323class TestNewScalarIndexing:
324    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 = np.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(np.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 = np.arange(6)
377        A.shape = (3, 2)
378        x = asmatrix(A)
379        assert_array_equal(x[:, np.array([True, False])], x[:, 0])
380        assert_array_equal(x[np.array([True, False, False]), :], x[0, :])
381
382    def test_list_indexing(self):
383        A = np.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
390class TestPower:
391    def test_returntype(self):
392        a = np.array([[0, 1], [0, 0]])
393        assert_(type(matrix_power(a, 2)) is np.ndarray)
394        a = asmatrix(a)
395        assert_(type(matrix_power(a, 2)) is matrix)
396
397    def test_list(self):
398        assert_array_equal(matrix_power([[0, 1], [0, 0]], 2), [[0, 0], [0, 0]])
399
400
401class TestShape:
402
403    a = np.array([[1], [2]])
404    m = matrix([[1], [2]])
405
406    def test_shape(self):
407        assert_equal(self.a.shape, (2, 1))
408        assert_equal(self.m.shape, (2, 1))
409
410    def test_numpy_ravel(self):
411        assert_equal(np.ravel(self.a).shape, (2,))
412        assert_equal(np.ravel(self.m).shape, (2,))
413
414    def test_member_ravel(self):
415        assert_equal(self.a.ravel().shape, (2,))
416        assert_equal(self.m.ravel().shape, (1, 2))
417
418    def test_member_flatten(self):
419        assert_equal(self.a.flatten().shape, (2,))
420        assert_equal(self.m.flatten().shape, (1, 2))
421
422    def test_numpy_ravel_order(self):
423        x = np.array([[1, 2, 3], [4, 5, 6]])
424        assert_equal(np.ravel(x), [1, 2, 3, 4, 5, 6])
425        assert_equal(np.ravel(x, order='F'), [1, 4, 2, 5, 3, 6])
426        assert_equal(np.ravel(x.T), [1, 4, 2, 5, 3, 6])
427        assert_equal(np.ravel(x.T, order='A'), [1, 2, 3, 4, 5, 6])
428        x = matrix([[1, 2, 3], [4, 5, 6]])
429        assert_equal(np.ravel(x), [1, 2, 3, 4, 5, 6])
430        assert_equal(np.ravel(x, order='F'), [1, 4, 2, 5, 3, 6])
431        assert_equal(np.ravel(x.T), [1, 4, 2, 5, 3, 6])
432        assert_equal(np.ravel(x.T, order='A'), [1, 2, 3, 4, 5, 6])
433
434    def test_matrix_ravel_order(self):
435        x = matrix([[1, 2, 3], [4, 5, 6]])
436        assert_equal(x.ravel(), [[1, 2, 3, 4, 5, 6]])
437        assert_equal(x.ravel(order='F'), [[1, 4, 2, 5, 3, 6]])
438        assert_equal(x.T.ravel(), [[1, 4, 2, 5, 3, 6]])
439        assert_equal(x.T.ravel(order='A'), [[1, 2, 3, 4, 5, 6]])
440
441    def test_array_memory_sharing(self):
442        assert_(np.may_share_memory(self.a, self.a.ravel()))
443        assert_(not np.may_share_memory(self.a, self.a.flatten()))
444
445    def test_matrix_memory_sharing(self):
446        assert_(np.may_share_memory(self.m, self.m.ravel()))
447        assert_(not np.may_share_memory(self.m, self.m.flatten()))
448
449    def test_expand_dims_matrix(self):
450        # matrices are always 2d - so expand_dims only makes sense when the
451        # type is changed away from matrix.
452        a = np.arange(10).reshape((2, 5)).view(np.matrix)
453        expanded = np.expand_dims(a, axis=1)
454        assert_equal(expanded.ndim, 3)
455        assert_(not isinstance(expanded, np.matrix))
456 
codekingpro/portable-devtools · Team Ai