Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
test_twodim_base.py560 linesDownload Raw Back to tests
1"""Test functions for matrix module
2
3"""
4import pytest
5
6import numpy as np
7from numpy import (
8    add,
9    arange,
10    array,
11    diag,
12    eye,
13    fliplr,
14    flipud,
15    histogram2d,
16    mask_indices,
17    ones,
18    tri,
19    tril_indices,
20    tril_indices_from,
21    triu_indices,
22    triu_indices_from,
23    vander,
24    zeros,
25)
26from numpy.testing import (
27    assert_,
28    assert_array_almost_equal,
29    assert_array_equal,
30    assert_array_max_ulp,
31    assert_equal,
32    assert_raises,
33)
34
35
36def get_mat(n):
37    data = arange(n)
38    data = add.outer(data, data)
39    return data
40
41
42class TestEye:
43    def test_basic(self):
44        assert_equal(eye(4),
45                     array([[1, 0, 0, 0],
46                            [0, 1, 0, 0],
47                            [0, 0, 1, 0],
48                            [0, 0, 0, 1]]))
49
50        assert_equal(eye(4, dtype='f'),
51                     array([[1, 0, 0, 0],
52                            [0, 1, 0, 0],
53                            [0, 0, 1, 0],
54                            [0, 0, 0, 1]], 'f'))
55
56        assert_equal(eye(3) == 1,
57                     eye(3, dtype=bool))
58
59    def test_uint64(self):
60        # Regression test for gh-9982
61        assert_equal(eye(np.uint64(2), dtype=int), array([[1, 0], [0, 1]]))
62        assert_equal(eye(np.uint64(2), M=np.uint64(4), k=np.uint64(1)),
63                     array([[0, 1, 0, 0], [0, 0, 1, 0]]))
64
65    def test_diag(self):
66        assert_equal(eye(4, k=1),
67                     array([[0, 1, 0, 0],
68                            [0, 0, 1, 0],
69                            [0, 0, 0, 1],
70                            [0, 0, 0, 0]]))
71
72        assert_equal(eye(4, k=-1),
73                     array([[0, 0, 0, 0],
74                            [1, 0, 0, 0],
75                            [0, 1, 0, 0],
76                            [0, 0, 1, 0]]))
77
78    def test_2d(self):
79        assert_equal(eye(4, 3),
80                     array([[1, 0, 0],
81                            [0, 1, 0],
82                            [0, 0, 1],
83                            [0, 0, 0]]))
84
85        assert_equal(eye(3, 4),
86                     array([[1, 0, 0, 0],
87                            [0, 1, 0, 0],
88                            [0, 0, 1, 0]]))
89
90    def test_diag2d(self):
91        assert_equal(eye(3, 4, k=2),
92                     array([[0, 0, 1, 0],
93                            [0, 0, 0, 1],
94                            [0, 0, 0, 0]]))
95
96        assert_equal(eye(4, 3, k=-2),
97                     array([[0, 0, 0],
98                            [0, 0, 0],
99                            [1, 0, 0],
100                            [0, 1, 0]]))
101
102    def test_eye_bounds(self):
103        assert_equal(eye(2, 2, 1), [[0, 1], [0, 0]])
104        assert_equal(eye(2, 2, -1), [[0, 0], [1, 0]])
105        assert_equal(eye(2, 2, 2), [[0, 0], [0, 0]])
106        assert_equal(eye(2, 2, -2), [[0, 0], [0, 0]])
107        assert_equal(eye(3, 2, 2), [[0, 0], [0, 0], [0, 0]])
108        assert_equal(eye(3, 2, 1), [[0, 1], [0, 0], [0, 0]])
109        assert_equal(eye(3, 2, -1), [[0, 0], [1, 0], [0, 1]])
110        assert_equal(eye(3, 2, -2), [[0, 0], [0, 0], [1, 0]])
111        assert_equal(eye(3, 2, -3), [[0, 0], [0, 0], [0, 0]])
112
113    def test_strings(self):
114        assert_equal(eye(2, 2, dtype='S3'),
115                     [[b'1', b''], [b'', b'1']])
116
117    def test_bool(self):
118        assert_equal(eye(2, 2, dtype=bool), [[True, False], [False, True]])
119
120    def test_order(self):
121        mat_c = eye(4, 3, k=-1)
122        mat_f = eye(4, 3, k=-1, order='F')
123        assert_equal(mat_c, mat_f)
124        assert mat_c.flags.c_contiguous
125        assert not mat_c.flags.f_contiguous
126        assert not mat_f.flags.c_contiguous
127        assert mat_f.flags.f_contiguous
128
129
130class TestDiag:
131    def test_vector(self):
132        vals = (100 * arange(5)).astype('l')
133        b = zeros((5, 5))
134        for k in range(5):
135            b[k, k] = vals[k]
136        assert_equal(diag(vals), b)
137        b = zeros((7, 7))
138        c = b.copy()
139        for k in range(5):
140            b[k, k + 2] = vals[k]
141            c[k + 2, k] = vals[k]
142        assert_equal(diag(vals, k=2), b)
143        assert_equal(diag(vals, k=-2), c)
144
145    def test_matrix(self, vals=None):
146        if vals is None:
147            vals = (100 * get_mat(5) + 1).astype('l')
148        b = zeros((5,))
149        for k in range(5):
150            b[k] = vals[k, k]
151        assert_equal(diag(vals), b)
152        b = b * 0
153        for k in range(3):
154            b[k] = vals[k, k + 2]
155        assert_equal(diag(vals, 2), b[:3])
156        for k in range(3):
157            b[k] = vals[k + 2, k]
158        assert_equal(diag(vals, -2), b[:3])
159
160    def test_fortran_order(self):
161        vals = array((100 * get_mat(5) + 1), order='F', dtype='l')
162        self.test_matrix(vals)
163
164    def test_diag_bounds(self):
165        A = [[1, 2], [3, 4], [5, 6]]
166        assert_equal(diag(A, k=2), [])
167        assert_equal(diag(A, k=1), [2])
168        assert_equal(diag(A, k=0), [1, 4])
169        assert_equal(diag(A, k=-1), [3, 6])
170        assert_equal(diag(A, k=-2), [5])
171        assert_equal(diag(A, k=-3), [])
172
173    def test_failure(self):
174        assert_raises(ValueError, diag, [[[1]]])
175
176
177class TestFliplr:
178    def test_basic(self):
179        assert_raises(ValueError, fliplr, ones(4))
180        a = get_mat(4)
181        b = a[:, ::-1]
182        assert_equal(fliplr(a), b)
183        a = [[0, 1, 2],
184             [3, 4, 5]]
185        b = [[2, 1, 0],
186             [5, 4, 3]]
187        assert_equal(fliplr(a), b)
188
189
190class TestFlipud:
191    def test_basic(self):
192        a = get_mat(4)
193        b = a[::-1, :]
194        assert_equal(flipud(a), b)
195        a = [[0, 1, 2],
196             [3, 4, 5]]
197        b = [[3, 4, 5],
198             [0, 1, 2]]
199        assert_equal(flipud(a), b)
200
201
202class TestHistogram2d:
203    def test_simple(self):
204        x = array(
205            [0.41702200, 0.72032449, 1.1437481e-4, 0.302332573, 0.146755891])
206        y = array(
207            [0.09233859, 0.18626021, 0.34556073, 0.39676747, 0.53881673])
208        xedges = np.linspace(0, 1, 10)
209        yedges = np.linspace(0, 1, 10)
210        H = histogram2d(x, y, (xedges, yedges))[0]
211        answer = array(
212            [[0, 0, 0, 1, 0, 0, 0, 0, 0],
213             [0, 0, 0, 0, 0, 0, 1, 0, 0],
214             [0, 0, 0, 0, 0, 0, 0, 0, 0],
215             [1, 0, 1, 0, 0, 0, 0, 0, 0],
216             [0, 1, 0, 0, 0, 0, 0, 0, 0],
217             [0, 0, 0, 0, 0, 0, 0, 0, 0],
218             [0, 0, 0, 0, 0, 0, 0, 0, 0],
219             [0, 0, 0, 0, 0, 0, 0, 0, 0],
220             [0, 0, 0, 0, 0, 0, 0, 0, 0]])
221        assert_array_equal(H.T, answer)
222        H = histogram2d(x, y, xedges)[0]
223        assert_array_equal(H.T, answer)
224        H, xedges, yedges = histogram2d(list(range(10)), list(range(10)))
225        assert_array_equal(H, eye(10, 10))
226        assert_array_equal(xedges, np.linspace(0, 9, 11))
227        assert_array_equal(yedges, np.linspace(0, 9, 11))
228
229    def test_asym(self):
230        x = array([1, 1, 2, 3, 4, 4, 4, 5])
231        y = array([1, 3, 2, 0, 1, 2, 3, 4])
232        H, xed, yed = histogram2d(
233            x, y, (6, 5), range=[[0, 6], [0, 5]], density=True)
234        answer = array(
235            [[0., 0, 0, 0, 0],
236             [0, 1, 0, 1, 0],
237             [0, 0, 1, 0, 0],
238             [1, 0, 0, 0, 0],
239             [0, 1, 1, 1, 0],
240             [0, 0, 0, 0, 1]])
241        assert_array_almost_equal(H, answer / 8., 3)
242        assert_array_equal(xed, np.linspace(0, 6, 7))
243        assert_array_equal(yed, np.linspace(0, 5, 6))
244
245    def test_density(self):
246        x = array([1, 2, 3, 1, 2, 3, 1, 2, 3])
247        y = array([1, 1, 1, 2, 2, 2, 3, 3, 3])
248        H, xed, yed = histogram2d(
249            x, y, [[1, 2, 3, 5], [1, 2, 3, 5]], density=True)
250        answer = array([[1, 1, .5],
251                        [1, 1, .5],
252                        [.5, .5, .25]]) / 9.
253        assert_array_almost_equal(H, answer, 3)
254
255    def test_all_outliers(self):
256        r = np.random.rand(100) + 1. + 1e6  # histogramdd rounds by decimal=6
257        H, xed, yed = histogram2d(r, r, (4, 5), range=([0, 1], [0, 1]))
258        assert_array_equal(H, 0)
259
260    def test_empty(self):
261        a, edge1, edge2 = histogram2d([], [], bins=([0, 1], [0, 1]))
262        assert_array_max_ulp(a, array([[0.]]))
263
264        a, edge1, edge2 = histogram2d([], [], bins=4)
265        assert_array_max_ulp(a, np.zeros((4, 4)))
266
267    def test_binparameter_combination(self):
268        x = array(
269            [0, 0.09207008, 0.64575234, 0.12875982, 0.47390599,
270             0.59944483, 1])
271        y = array(
272            [0, 0.14344267, 0.48988575, 0.30558665, 0.44700682,
273             0.15886423, 1])
274        edges = (0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1)
275        H, xe, ye = histogram2d(x, y, (edges, 4))
276        answer = array(
277            [[2., 0., 0., 0.],
278             [0., 1., 0., 0.],
279             [0., 0., 0., 0.],
280             [0., 0., 0., 0.],
281             [0., 1., 0., 0.],
282             [1., 0., 0., 0.],
283             [0., 1., 0., 0.],
284             [0., 0., 0., 0.],
285             [0., 0., 0., 0.],
286             [0., 0., 0., 1.]])
287        assert_array_equal(H, answer)
288        assert_array_equal(ye, array([0., 0.25, 0.5, 0.75, 1]))
289        H, xe, ye = histogram2d(x, y, (4, edges))
290        answer = array(
291            [[1., 1., 0., 1., 0., 0., 0., 0., 0., 0.],
292             [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
293             [0., 1., 0., 0., 1., 0., 0., 0., 0., 0.],
294             [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]])
295        assert_array_equal(H, answer)
296        assert_array_equal(xe, array([0., 0.25, 0.5, 0.75, 1]))
297
298    def test_dispatch(self):
299        class ShouldDispatch:
300            def __array_function__(self, function, types, args, kwargs):
301                return types, args, kwargs
302
303        xy = [1, 2]
304        s_d = ShouldDispatch()
305        r = histogram2d(s_d, xy)
306        # Cannot use assert_equal since that dispatches...
307        assert_(r == ((ShouldDispatch,), (s_d, xy), {}))
308        r = histogram2d(xy, s_d)
309        assert_(r == ((ShouldDispatch,), (xy, s_d), {}))
310        r = histogram2d(xy, xy, bins=s_d)
311        assert_(r, ((ShouldDispatch,), (xy, xy), {'bins': s_d}))
312        r = histogram2d(xy, xy, bins=[s_d, 5])
313        assert_(r, ((ShouldDispatch,), (xy, xy), {'bins': [s_d, 5]}))
314        assert_raises(Exception, histogram2d, xy, xy, bins=[s_d])
315        r = histogram2d(xy, xy, weights=s_d)
316        assert_(r, ((ShouldDispatch,), (xy, xy), {'weights': s_d}))
317
318    @pytest.mark.parametrize(("x_len", "y_len"), [(10, 11), (20, 19)])
319    def test_bad_length(self, x_len, y_len):
320        x, y = np.ones(x_len), np.ones(y_len)
321        with pytest.raises(ValueError,
322                           match='x and y must have the same length.'):
323            histogram2d(x, y)
324
325
326class TestTri:
327    def test_dtype(self):
328        out = array([[1, 0, 0],
329                     [1, 1, 0],
330                     [1, 1, 1]])
331        assert_array_equal(tri(3), out)
332        assert_array_equal(tri(3, dtype=bool), out.astype(bool))
333
334
335def test_tril_triu_ndim2():
336    for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']:
337        a = np.ones((2, 2), dtype=dtype)
338        b = np.tril(a)
339        c = np.triu(a)
340        assert_array_equal(b, [[1, 0], [1, 1]])
341        assert_array_equal(c, b.T)
342        # should return the same dtype as the original array
343        assert_equal(b.dtype, a.dtype)
344        assert_equal(c.dtype, a.dtype)
345
346
347def test_tril_triu_ndim3():
348    for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']:
349        a = np.array([
350            [[1, 1], [1, 1]],
351            [[1, 1], [1, 0]],
352            [[1, 1], [0, 0]],
353            ], dtype=dtype)
354        a_tril_desired = np.array([
355            [[1, 0], [1, 1]],
356            [[1, 0], [1, 0]],
357            [[1, 0], [0, 0]],
358            ], dtype=dtype)
359        a_triu_desired = np.array([
360            [[1, 1], [0, 1]],
361            [[1, 1], [0, 0]],
362            [[1, 1], [0, 0]],
363            ], dtype=dtype)
364        a_triu_observed = np.triu(a)
365        a_tril_observed = np.tril(a)
366        assert_array_equal(a_triu_observed, a_triu_desired)
367        assert_array_equal(a_tril_observed, a_tril_desired)
368        assert_equal(a_triu_observed.dtype, a.dtype)
369        assert_equal(a_tril_observed.dtype, a.dtype)
370
371
372def test_tril_triu_with_inf():
373    # Issue 4859
374    arr = np.array([[1, 1, np.inf],
375                    [1, 1, 1],
376                    [np.inf, 1, 1]])
377    out_tril = np.array([[1, 0, 0],
378                         [1, 1, 0],
379                         [np.inf, 1, 1]])
380    out_triu = out_tril.T
381    assert_array_equal(np.triu(arr), out_triu)
382    assert_array_equal(np.tril(arr), out_tril)
383
384
385def test_tril_triu_dtype():
386    # Issue 4916
387    # tril and triu should return the same dtype as input
388    for c in np.typecodes['All']:
389        if c == 'V':
390            continue
391        arr = np.zeros((3, 3), dtype=c)
392        assert_equal(np.triu(arr).dtype, arr.dtype)
393        assert_equal(np.tril(arr).dtype, arr.dtype)
394
395    # check special cases
396    arr = np.array([['2001-01-01T12:00', '2002-02-03T13:56'],
397                    ['2004-01-01T12:00', '2003-01-03T13:45']],
398                   dtype='datetime64')
399    assert_equal(np.triu(arr).dtype, arr.dtype)
400    assert_equal(np.tril(arr).dtype, arr.dtype)
401
402    arr = np.zeros((3, 3), dtype='f4,f4')
403    assert_equal(np.triu(arr).dtype, arr.dtype)
404    assert_equal(np.tril(arr).dtype, arr.dtype)
405
406
407def test_mask_indices():
408    # simple test without offset
409    iu = mask_indices(3, np.triu)
410    a = np.arange(9).reshape(3, 3)
411    assert_array_equal(a[iu], array([0, 1, 2, 4, 5, 8]))
412    # Now with an offset
413    iu1 = mask_indices(3, np.triu, 1)
414    assert_array_equal(a[iu1], array([1, 2, 5]))
415
416
417def test_tril_indices():
418    # indices without and with offset
419    il1 = tril_indices(4)
420    il2 = tril_indices(4, k=2)
421    il3 = tril_indices(4, m=5)
422    il4 = tril_indices(4, k=2, m=5)
423
424    a = np.array([[1, 2, 3, 4],
425                  [5, 6, 7, 8],
426                  [9, 10, 11, 12],
427                  [13, 14, 15, 16]])
428    b = np.arange(1, 21).reshape(4, 5)
429
430    # indexing:
431    assert_array_equal(a[il1],
432                       array([1, 5, 6, 9, 10, 11, 13, 14, 15, 16]))
433    assert_array_equal(b[il3],
434                       array([1, 6, 7, 11, 12, 13, 16, 17, 18, 19]))
435
436    # And for assigning values:
437    a[il1] = -1
438    assert_array_equal(a,
439                       array([[-1, 2, 3, 4],
440                              [-1, -1, 7, 8],
441                              [-1, -1, -1, 12],
442                              [-1, -1, -1, -1]]))
443    b[il3] = -1
444    assert_array_equal(b,
445                       array([[-1, 2, 3, 4, 5],
446                              [-1, -1, 8, 9, 10],
447                              [-1, -1, -1, 14, 15],
448                              [-1, -1, -1, -1, 20]]))
449    # These cover almost the whole array (two diagonals right of the main one):
450    a[il2] = -10
451    assert_array_equal(a,
452                       array([[-10, -10, -10, 4],
453                              [-10, -10, -10, -10],
454                              [-10, -10, -10, -10],
455                              [-10, -10, -10, -10]]))
456    b[il4] = -10
457    assert_array_equal(b,
458                       array([[-10, -10, -10, 4, 5],
459                              [-10, -10, -10, -10, 10],
460                              [-10, -10, -10, -10, -10],
461                              [-10, -10, -10, -10, -10]]))
462
463
464class TestTriuIndices:
465    def test_triu_indices(self):
466        iu1 = triu_indices(4)
467        iu2 = triu_indices(4, k=2)
468        iu3 = triu_indices(4, m=5)
469        iu4 = triu_indices(4, k=2, m=5)
470
471        a = np.array([[1, 2, 3, 4],
472                      [5, 6, 7, 8],
473                      [9, 10, 11, 12],
474                      [13, 14, 15, 16]])
475        b = np.arange(1, 21).reshape(4, 5)
476
477        # Both for indexing:
478        assert_array_equal(a[iu1],
479                           array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16]))
480        assert_array_equal(b[iu3],
481                           array([1, 2, 3, 4, 5, 7, 8, 9,
482                                  10, 13, 14, 15, 19, 20]))
483
484        # And for assigning values:
485        a[iu1] = -1
486        assert_array_equal(a,
487                           array([[-1, -1, -1, -1],
488                                  [5, -1, -1, -1],
489                                  [9, 10, -1, -1],
490                                  [13, 14, 15, -1]]))
491        b[iu3] = -1
492        assert_array_equal(b,
493                           array([[-1, -1, -1, -1, -1],
494                                  [6, -1, -1, -1, -1],
495                                  [11, 12, -1, -1, -1],
496                                  [16, 17, 18, -1, -1]]))
497
498        # These cover almost the whole array (two diagonals right of the
499        # main one):
500        a[iu2] = -10
501        assert_array_equal(a,
502                           array([[-1, -1, -10, -10],
503                                  [5, -1, -1, -10],
504                                  [9, 10, -1, -1],
505                                  [13, 14, 15, -1]]))
506        b[iu4] = -10
507        assert_array_equal(b,
508                           array([[-1, -1, -10, -10, -10],
509                                  [6, -1, -1, -10, -10],
510                                  [11, 12, -1, -1, -10],
511                                  [16, 17, 18, -1, -1]]))
512
513
514class TestTrilIndicesFrom:
515    def test_exceptions(self):
516        assert_raises(ValueError, tril_indices_from, np.ones((2,)))
517        assert_raises(ValueError, tril_indices_from, np.ones((2, 2, 2)))
518        # assert_raises(ValueError, tril_indices_from, np.ones((2, 3)))
519
520
521class TestTriuIndicesFrom:
522    def test_exceptions(self):
523        assert_raises(ValueError, triu_indices_from, np.ones((2,)))
524        assert_raises(ValueError, triu_indices_from, np.ones((2, 2, 2)))
525        # assert_raises(ValueError, triu_indices_from, np.ones((2, 3)))
526
527
528class TestVander:
529    def test_basic(self):
530        c = np.array([0, 1, -2, 3])
531        v = vander(c)
532        powers = np.array([[0, 0, 0, 0, 1],
533                           [1, 1, 1, 1, 1],
534                           [16, -8, 4, -2, 1],
535                           [81, 27, 9, 3, 1]])
536        # Check default value of N:
537        assert_array_equal(v, powers[:, 1:])
538        # Check a range of N values, including 0 and 5 (greater than default)
539        m = powers.shape[1]
540        for n in range(6):
541            v = vander(c, N=n)
542            assert_array_equal(v, powers[:, m - n:m])
543
544    def test_dtypes(self):
545        c = array([11, -12, 13], dtype=np.int8)
546        v = vander(c)
547        expected = np.array([[121, 11, 1],
548                             [144, -12, 1],
549                             [169, 13, 1]])
550        assert_array_equal(v, expected)
551
552        c = array([1.0 + 1j, 1.0 - 1j])
553        v = vander(c, N=3)
554        expected = np.array([[2j, 1 + 1j, 1],
555                             [-2j, 1 - 1j, 1]])
556        # The data is floating point, but the values are small integers,
557        # so assert_array_equal *should* be safe here (rather than, say,
558        # assert_array_almost_equal).
559        assert_array_equal(v, expected)
560 
codekingpro/portable-devtools · Team Ai