Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
test_interaction.py361 linesDownload Raw Back to tests
1"""Tests of interaction of matrix with other parts of numpy.
2
3Note that tests with MaskedArray and linalg are done in separate files.
4"""
5import textwrap
6import warnings
7
8import pytest
9
10import numpy as np
11from numpy.testing import (
12    assert_,
13    assert_almost_equal,
14    assert_array_almost_equal,
15    assert_array_equal,
16    assert_equal,
17    assert_raises,
18    assert_raises_regex,
19)
20
21
22def test_fancy_indexing():
23    # The matrix class messes with the shape. While this is always
24    # weird (getitem is not used, it does not have setitem nor knows
25    # about fancy indexing), this tests gh-3110
26    # 2018-04-29: moved here from core.tests.test_index.
27    m = np.matrix([[1, 2], [3, 4]])
28
29    assert_(isinstance(m[[0, 1, 0], :], np.matrix))
30
31    # gh-3110. Note the transpose currently because matrices do *not*
32    # support dimension fixing for fancy indexing correctly.
33    x = np.asmatrix(np.arange(50).reshape(5, 10))
34    assert_equal(x[:2, np.array(-1)], x[:2, -1].T)
35
36
37def test_polynomial_mapdomain():
38    # test that polynomial preserved matrix subtype.
39    # 2018-04-29: moved here from polynomial.tests.polyutils.
40    dom1 = [0, 4]
41    dom2 = [1, 3]
42    x = np.matrix([dom1, dom1])
43    res = np.polynomial.polyutils.mapdomain(x, dom1, dom2)
44    assert_(isinstance(res, np.matrix))
45
46
47def test_sort_matrix_none():
48    # 2018-04-29: moved here from core.tests.test_multiarray
49    a = np.matrix([[2, 1, 0]])
50    actual = np.sort(a, axis=None)
51    expected = np.matrix([[0, 1, 2]])
52    assert_equal(actual, expected)
53    assert_(type(expected) is np.matrix)
54
55
56def test_partition_matrix_none():
57    # gh-4301
58    # 2018-04-29: moved here from core.tests.test_multiarray
59    a = np.matrix([[2, 1, 0]])
60    actual = np.partition(a, 1, axis=None)
61    expected = np.matrix([[0, 1, 2]])
62    assert_equal(actual, expected)
63    assert_(type(expected) is np.matrix)
64
65
66def test_dot_scalar_and_matrix_of_objects():
67    # Ticket #2469
68    # 2018-04-29: moved here from core.tests.test_multiarray
69    arr = np.matrix([1, 2], dtype=object)
70    desired = np.matrix([[3, 6]], dtype=object)
71    assert_equal(np.dot(arr, 3), desired)
72    assert_equal(np.dot(3, arr), desired)
73
74
75def test_inner_scalar_and_matrix():
76    # 2018-04-29: moved here from core.tests.test_multiarray
77    for dt in np.typecodes['AllInteger'] + np.typecodes['AllFloat'] + '?':
78        sca = np.array(3, dtype=dt)[()]
79        arr = np.matrix([[1, 2], [3, 4]], dtype=dt)
80        desired = np.matrix([[3, 6], [9, 12]], dtype=dt)
81        assert_equal(np.inner(arr, sca), desired)
82        assert_equal(np.inner(sca, arr), desired)
83
84
85def test_inner_scalar_and_matrix_of_objects():
86    # Ticket #4482
87    # 2018-04-29: moved here from core.tests.test_multiarray
88    arr = np.matrix([1, 2], dtype=object)
89    desired = np.matrix([[3, 6]], dtype=object)
90    assert_equal(np.inner(arr, 3), desired)
91    assert_equal(np.inner(3, arr), desired)
92
93
94def test_iter_allocate_output_subtype():
95    # Make sure that the subtype with priority wins
96    # 2018-04-29: moved here from core.tests.test_nditer, given the
97    # matrix specific shape test.
98
99    # matrix vs ndarray
100    a = np.matrix([[1, 2], [3, 4]])
101    b = np.arange(4).reshape(2, 2).T
102    i = np.nditer([a, b, None], [],
103                  [['readonly'], ['readonly'], ['writeonly', 'allocate']])
104    assert_(type(i.operands[2]) is np.matrix)
105    assert_(type(i.operands[2]) is not np.ndarray)
106    assert_equal(i.operands[2].shape, (2, 2))
107
108    # matrix always wants things to be 2D
109    b = np.arange(4).reshape(1, 2, 2)
110    assert_raises(RuntimeError, np.nditer, [a, b, None], [],
111                  [['readonly'], ['readonly'], ['writeonly', 'allocate']])
112    # but if subtypes are disabled, the result can still work
113    i = np.nditer([a, b, None], [],
114                  [['readonly'], ['readonly'],
115                   ['writeonly', 'allocate', 'no_subtype']])
116    assert_(type(i.operands[2]) is np.ndarray)
117    assert_(type(i.operands[2]) is not np.matrix)
118    assert_equal(i.operands[2].shape, (1, 2, 2))
119
120
121def like_function():
122    # 2018-04-29: moved here from core.tests.test_numeric
123    a = np.matrix([[1, 2], [3, 4]])
124    for like_function in np.zeros_like, np.ones_like, np.empty_like:
125        b = like_function(a)
126        assert_(type(b) is np.matrix)
127
128        c = like_function(a, subok=False)
129        assert_(type(c) is not np.matrix)
130
131
132def test_array_astype():
133    # 2018-04-29: copied here from core.tests.test_api
134    # subok=True passes through a matrix
135    a = np.matrix([[0, 1, 2], [3, 4, 5]], dtype='f4')
136    b = a.astype('f4', subok=True, copy=False)
137    assert_(a is b)
138
139    # subok=True is default, and creates a subtype on a cast
140    b = a.astype('i4', copy=False)
141    assert_equal(a, b)
142    assert_equal(type(b), np.matrix)
143
144    # subok=False never returns a matrix
145    b = a.astype('f4', subok=False, copy=False)
146    assert_equal(a, b)
147    assert_(not (a is b))
148    assert_(type(b) is not np.matrix)
149
150
151def test_stack():
152    # 2018-04-29: copied here from core.tests.test_shape_base
153    # check np.matrix cannot be stacked
154    m = np.matrix([[1, 2], [3, 4]])
155    assert_raises_regex(ValueError, 'shape too large to be a matrix',
156                        np.stack, [m, m])
157
158
159def test_object_scalar_multiply():
160    # Tickets #2469 and #4482
161    # 2018-04-29: moved here from core.tests.test_ufunc
162    arr = np.matrix([1, 2], dtype=object)
163    desired = np.matrix([[3, 6]], dtype=object)
164    assert_equal(np.multiply(arr, 3), desired)
165    assert_equal(np.multiply(3, arr), desired)
166
167
168def test_nanfunctions_matrices():
169    # Check that it works and that type and
170    # shape are preserved
171    # 2018-04-29: moved here from core.tests.test_nanfunctions
172    mat = np.matrix(np.eye(3))
173    for f in [np.nanmin, np.nanmax]:
174        res = f(mat, axis=0)
175        assert_(isinstance(res, np.matrix))
176        assert_(res.shape == (1, 3))
177        res = f(mat, axis=1)
178        assert_(isinstance(res, np.matrix))
179        assert_(res.shape == (3, 1))
180        res = f(mat)
181        assert_(np.isscalar(res))
182    # check that rows of nan are dealt with for subclasses (#4628)
183    mat[1] = np.nan
184    for f in [np.nanmin, np.nanmax]:
185        with warnings.catch_warnings(record=True) as w:
186            warnings.simplefilter('always')
187            res = f(mat, axis=0)
188            assert_(isinstance(res, np.matrix))
189            assert_(not np.any(np.isnan(res)))
190            assert_(len(w) == 0)
191
192        with warnings.catch_warnings(record=True) as w:
193            warnings.simplefilter('always')
194            res = f(mat, axis=1)
195            assert_(isinstance(res, np.matrix))
196            assert_(np.isnan(res[1, 0]) and not np.isnan(res[0, 0])
197                    and not np.isnan(res[2, 0]))
198            assert_(len(w) == 1, 'no warning raised')
199            assert_(issubclass(w[0].category, RuntimeWarning))
200
201        with warnings.catch_warnings(record=True) as w:
202            warnings.simplefilter('always')
203            res = f(mat)
204            assert_(np.isscalar(res))
205            assert_(res != np.nan)
206            assert_(len(w) == 0)
207
208
209def test_nanfunctions_matrices_general():
210    # Check that it works and that type and
211    # shape are preserved
212    # 2018-04-29: moved here from core.tests.test_nanfunctions
213    mat = np.matrix(np.eye(3))
214    for f in (np.nanargmin, np.nanargmax, np.nansum, np.nanprod,
215              np.nanmean, np.nanvar, np.nanstd):
216        res = f(mat, axis=0)
217        assert_(isinstance(res, np.matrix))
218        assert_(res.shape == (1, 3))
219        res = f(mat, axis=1)
220        assert_(isinstance(res, np.matrix))
221        assert_(res.shape == (3, 1))
222        res = f(mat)
223        assert_(np.isscalar(res))
224
225    for f in np.nancumsum, np.nancumprod:
226        res = f(mat, axis=0)
227        assert_(isinstance(res, np.matrix))
228        assert_(res.shape == (3, 3))
229        res = f(mat, axis=1)
230        assert_(isinstance(res, np.matrix))
231        assert_(res.shape == (3, 3))
232        res = f(mat)
233        assert_(isinstance(res, np.matrix))
234        assert_(res.shape == (1, 3 * 3))
235
236
237def test_average_matrix():
238    # 2018-04-29: moved here from core.tests.test_function_base.
239    y = np.matrix(np.random.rand(5, 5))
240    assert_array_equal(y.mean(0), np.average(y, 0))
241
242    a = np.matrix([[1, 2], [3, 4]])
243    w = np.matrix([[1, 2], [3, 4]])
244
245    r = np.average(a, axis=0, weights=w)
246    assert_equal(type(r), np.matrix)
247    assert_equal(r, [[2.5, 10.0 / 3]])
248
249
250def test_dot_matrix():
251    # Test to make sure matrices give the same answer as ndarrays
252    # 2018-04-29: moved here from core.tests.test_function_base.
253    x = np.linspace(0, 5)
254    y = np.linspace(-5, 0)
255    mx = np.matrix(x)
256    my = np.matrix(y)
257    r = np.dot(x, y)
258    mr = np.dot(mx, my.T)
259    assert_almost_equal(mr, r)
260
261
262def test_ediff1d_matrix():
263    # 2018-04-29: moved here from core.tests.test_arraysetops.
264    assert isinstance(np.ediff1d(np.matrix(1)), np.matrix)
265    assert isinstance(np.ediff1d(np.matrix(1), to_begin=1), np.matrix)
266
267
268def test_apply_along_axis_matrix():
269    # this test is particularly malicious because matrix
270    # refuses to become 1d
271    # 2018-04-29: moved here from core.tests.test_shape_base.
272    def double(row):
273        return row * 2
274
275    m = np.matrix([[0, 1], [2, 3]])
276    expected = np.matrix([[0, 2], [4, 6]])
277
278    result = np.apply_along_axis(double, 0, m)
279    assert_(isinstance(result, np.matrix))
280    assert_array_equal(result, expected)
281
282    result = np.apply_along_axis(double, 1, m)
283    assert_(isinstance(result, np.matrix))
284    assert_array_equal(result, expected)
285
286
287def test_kron_matrix():
288    # 2018-04-29: moved here from core.tests.test_shape_base.
289    a = np.ones([2, 2])
290    m = np.asmatrix(a)
291    assert_equal(type(np.kron(a, a)), np.ndarray)
292    assert_equal(type(np.kron(m, m)), np.matrix)
293    assert_equal(type(np.kron(a, m)), np.matrix)
294    assert_equal(type(np.kron(m, a)), np.matrix)
295
296
297class TestConcatenatorMatrix:
298    # 2018-04-29: moved here from core.tests.test_index_tricks.
299    def test_matrix(self):
300        a = [1, 2]
301        b = [3, 4]
302
303        ab_r = np.r_['r', a, b]
304        ab_c = np.r_['c', a, b]
305
306        assert_equal(type(ab_r), np.matrix)
307        assert_equal(type(ab_c), np.matrix)
308
309        assert_equal(np.array(ab_r), [[1, 2, 3, 4]])
310        assert_equal(np.array(ab_c), [[1], [2], [3], [4]])
311
312        assert_raises(ValueError, lambda: np.r_['rc', a, b])
313
314    def test_matrix_scalar(self):
315        r = np.r_['r', [1, 2], 3]
316        assert_equal(type(r), np.matrix)
317        assert_equal(np.array(r), [[1, 2, 3]])
318
319    def test_matrix_builder(self):
320        a = np.array([1])
321        b = np.array([2])
322        c = np.array([3])
323        d = np.array([4])
324        actual = np.r_['a, b; c, d']
325        expected = np.bmat([[a, b], [c, d]])
326
327        assert_equal(actual, expected)
328        assert_equal(type(actual), type(expected))
329
330
331def test_array_equal_error_message_matrix():
332    # 2018-04-29: moved here from testing.tests.test_utils.
333    with pytest.raises(AssertionError) as exc_info:
334        assert_equal(np.array([1, 2]), np.matrix([1, 2]))
335    msg = str(exc_info.value)
336    msg_reference = textwrap.dedent("""\
337
338    Arrays are not equal
339
340    (shapes (2,), (1, 2) mismatch)
341     ACTUAL: array([1, 2])
342     DESIRED: matrix([[1, 2]])""")
343    assert_equal(msg, msg_reference)
344
345
346def test_array_almost_equal_matrix():
347    # Matrix slicing keeps things 2-D, while array does not necessarily.
348    # See gh-8452.
349    # 2018-04-29: moved here from testing.tests.test_utils.
350    m1 = np.matrix([[1., 2.]])
351    m2 = np.matrix([[1., np.nan]])
352    m3 = np.matrix([[1., -np.inf]])
353    m4 = np.matrix([[np.nan, np.inf]])
354    m5 = np.matrix([[1., 2.], [np.nan, np.inf]])
355    for assert_func in assert_array_almost_equal, assert_almost_equal:
356        for m in m1, m2, m3, m4, m5:
357            assert_func(m, m)
358            a = np.array(m)
359            assert_func(a, m)
360            assert_func(m, a)
361 
codekingpro/portable-devtools · Team Ai