Esempio n. 1
0
 def test_block_diag_1(self):
     """ block_diag with one matrix """
     assert_equal(
         construct.block_diag([[1, 0]]).todense(), matrix([[1, 0]]))
     assert_equal(
         construct.block_diag([[[1, 0]]]).todense(), matrix([[1, 0]]))
     assert_equal(
         construct.block_diag([[[1], [0]]]).todense(), matrix([[1], [0]]))
     # just on scalar
     assert_equal(construct.block_diag([1]).todense(), matrix([[1]]))
Esempio n. 2
0
 def test_block_diag_1(self):
     """ block_diag with one matrix """
     assert_equal(construct.block_diag([[1, 0]]).todense(),
                  matrix([[1, 0]]))
     assert_equal(construct.block_diag([[[1, 0]]]).todense(),
                  matrix([[1, 0]]))
     assert_equal(construct.block_diag([[[1], [0]]]).todense(),
                  matrix([[1], [0]]))
     # just on scalar
     assert_equal(construct.block_diag([1]).todense(),
                  matrix([[1]]))
Esempio n. 3
0
 def test_misc_types(self):
     A = expm(np.array([[1]]))
     assert_allclose(expm(((1, ), )), A)
     assert_allclose(expm([[1]]), A)
     assert_allclose(expm(matrix([[1]])), A)
     assert_allclose(expm(np.array([[1]])), A)
     assert_allclose(expm(csc_matrix([[1]])).A, A)
     B = expm(np.array([[1j]]))
     assert_allclose(expm(((1j, ), )), B)
     assert_allclose(expm([[1j]]), B)
     assert_allclose(expm(matrix([[1j]])), B)
     assert_allclose(expm(csc_matrix([[1j]])).A, B)
Esempio n. 4
0
 def test_misc_types(self):
     A = expm(np.array([[1]]))
     assert_allclose(expm(((1,),)), A)
     assert_allclose(expm([[1]]), A)
     assert_allclose(expm(matrix([[1]])), A)
     assert_allclose(expm(np.array([[1]])), A)
     assert_allclose(expm(csc_matrix([[1]])).A, A)
     B = expm(np.array([[1j]]))
     assert_allclose(expm(((1j,),)), B)
     assert_allclose(expm([[1j]]), B)
     assert_allclose(expm(matrix([[1j]])), B)
     assert_allclose(expm(csc_matrix([[1j]])).A, B)
def test_orthogonal_procrustes_array_conversion():
    np.random.seed(1234)
    for m, n in ((6, 4), (4, 4), (4, 6)):
        A_arr = np.random.randn(m, n)
        B_arr = np.random.randn(m, n)
        As = (A_arr, A_arr.tolist(), matrix(A_arr))
        Bs = (B_arr, B_arr.tolist(), matrix(B_arr))
        R_arr, s = orthogonal_procrustes(A_arr, B_arr)
        AR_arr = A_arr.dot(R_arr)
        for A, B in product(As, Bs):
            R, s = orthogonal_procrustes(A, B)
            AR = A_arr.dot(R)
            assert_allclose(AR, AR_arr)
Esempio n. 6
0
def test_orthogonal_procrustes_array_conversion():
    np.random.seed(1234)
    for m, n in ((6, 4), (4, 4), (4, 6)):
        A_arr = np.random.randn(m, n)
        B_arr = np.random.randn(m, n)
        As = (A_arr, A_arr.tolist(), matrix(A_arr))
        Bs = (B_arr, B_arr.tolist(), matrix(B_arr))
        R_arr, s = orthogonal_procrustes(A_arr, B_arr)
        AR_arr = A_arr.dot(R_arr)
        for A, B in product(As, Bs):
            R, s = orthogonal_procrustes(A, B)
            AR = A_arr.dot(R)
            assert_allclose(AR, AR_arr)
Esempio n. 7
0
 def test_double_integrator(self):
     # double integrator: y'' = 2u
     A = matrix("0. 1.; 0. 0.")
     B = matrix("0.; 1.")
     C = matrix("2. 0.")
     system = self.lti_nowarn(A, B, C, 0.)
     t = np.linspace(0, 5)
     u = np.ones_like(t)
     tout, y, x = lsim(system, u, t)
     expected_x = np.transpose(np.array([0.5 * tout**2, tout]))
     expected_y = tout**2
     assert_almost_equal(x, expected_x)
     assert_almost_equal(y, expected_y)
Esempio n. 8
0
 def test_double_integrator(self):
     # double integrator: y'' = 2u
     A = matrix("0. 1.; 0. 0.")
     B = matrix("0.; 1.")
     C = matrix("2. 0.")
     system = self.lti_nowarn(A, B, C, 0.)
     t = np.linspace(0,5)
     u = np.ones_like(t)
     tout, y, x = lsim(system, u, t)
     expected_x = np.transpose(np.array([0.5 * tout**2, tout]))
     expected_y = tout**2
     assert_almost_equal(x, expected_x)
     assert_almost_equal(y, expected_y)
Esempio n. 9
0
    def test_matrix(self):
        a = [[1, 2, 3]]
        b = np.array(a)

        assert isinstance(sputils.matrix(a), np.matrix)
        assert isinstance(sputils.matrix(b), np.matrix)

        c = sputils.matrix(b)
        c[:, :] = 123
        assert_equal(b, a)

        c = sputils.matrix(b, copy=False)
        c[:, :] = 123
        assert_equal(b, [[123, 123, 123]])
Esempio n. 10
0
    def test_block_diag_sparse_matrices(self):
        """ block_diag with sparse matrices """

        sparse_col_matrices = [coo_matrix(([[1, 2, 3]]), shape=(1, 3)),
                               coo_matrix(([[4, 5]]), shape=(1, 2))]
        block_sparse_cols_matrices = construct.block_diag(sparse_col_matrices)
        assert_equal(block_sparse_cols_matrices.todense(),
                     matrix([[1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]))

        sparse_row_matrices = [coo_matrix(([[1], [2], [3]]), shape=(3, 1)),
                               coo_matrix(([[4], [5]]), shape=(2, 1))]
        block_sparse_row_matrices = construct.block_diag(sparse_row_matrices)
        assert_equal(block_sparse_row_matrices.todense(),
                     matrix([[1, 0], [2, 0], [3, 0], [0, 4], [0, 5]]))
Esempio n. 11
0
 def test_jordan_block(self):
     # Non-diagonalizable A matrix
     #   x1' + x1 = x2
     #   x2' + x2 = u
     #   y = x1
     # Exact solution with u = 0 is y(t) = t exp(-t)
     A = matrix("-1. 1.; 0. -1.")
     B = matrix("0.; 1.")
     C = matrix("1. 0.")
     system = self.lti_nowarn(A, B, C, 0.)
     t = np.linspace(0, 5)
     u = np.zeros_like(t)
     tout, y, x = lsim(system, u, t, X0=[0.0, 1.0])
     expected_y = tout * np.exp(-tout)
     assert_almost_equal(y, expected_y)
Esempio n. 12
0
 def test_jordan_block(self):
     # Non-diagonalizable A matrix
     #   x1' + x1 = x2
     #   x2' + x2 = u
     #   y = x1
     # Exact solution with u = 0 is y(t) = t exp(-t)
     A = matrix("-1. 1.; 0. -1.")
     B = matrix("0.; 1.")
     C = matrix("1. 0.")
     system = self.lti_nowarn(A, B, C, 0.)
     t = np.linspace(0,5)
     u = np.zeros_like(t)
     tout, y, x = lsim(system, u, t, X0=[0.0, 1.0])
     expected_y = tout * np.exp(-tout)
     assert_almost_equal(y, expected_y)
Esempio n. 13
0
def test_linear_sum_assignment_input_validation():
    # Since the input should be a 2D array.
    assert_raises(ValueError, lap.solve, [1, 2, 3])

    cost_matrix = [[1, 2, 3], [4, 5, 6]]
    assert_array_equal(lap.solve(cost_matrix),
                       lap.solve(np.asarray(cost_matrix)))
    assert_array_equal(lap.solve(cost_matrix),
                       lap.solve(matrix(cost_matrix)))

    eye = np.identity(3)
    assert_array_equal(lap.solve(eye.astype(np.bool)),
                       lap.solve(eye))
    assert_raises(ValueError, lap.solve, eye.astype(str))

    eye[0][0] = np.nan
    assert_raises(ValueError, lap.solve, eye)

    eye = np.identity(3)
    eye[1][1] = -np.inf
    assert_raises(ValueError, lap.solve, eye)

    eye = np.identity(3)
    eye[:, 0] = np.inf
    assert_raises(ValueError, lap.solve, eye)

    # Note that solve requires that num_rows cannot exceed num_cols
    cost_matrix = np.array([[0     , np.inf, np.inf],
                            [np.inf,      0, np.inf],
                            [np.inf, np.inf,      0],
                            [0     ,      0,      0]])
    assert_raises(ValueError, laptools._solve, cost_matrix)
Esempio n. 14
0
def test_linear_sum_assignment_input_validation():

    assert_raises(ValueError, linear_sum_assignment, [1, 2, 3])

    C = [[1, 2, 3], [4, 5, 6]]
    assert_array_equal(linear_sum_assignment(C),
                       linear_sum_assignment(np.asarray(C)))
    assert_array_equal(linear_sum_assignment(C),
                       linear_sum_assignment(matrix(C)))

    I = np.identity(3)
    assert_array_equal(linear_sum_assignment(I.astype(np.bool_)),
                       linear_sum_assignment(I))
    assert_raises(ValueError, linear_sum_assignment, I.astype(str))

    I[0][0] = np.nan
    with pytest.raises(ValueError, match="contains invalid numeric entries"):
        linear_sum_assignment(I)

    I = np.identity(3)
    I[1][1] = -np.inf
    with pytest.raises(ValueError, match="contains invalid numeric entries"):
        linear_sum_assignment(I)

    I = np.identity(3)
    I[:, 0] = np.inf
    with pytest.raises(ValueError, match="cost matrix is infeasible"):
        linear_sum_assignment(I)
Esempio n. 15
0
    def _divide_sparse(self, other):
        """
        Divide this matrix by a second sparse matrix.
        """
        if other.shape != self.shape:
            raise ValueError('inconsistent shapes')

        r = self._binopt(other, '_eldiv_')

        if np.issubdtype(r.dtype, np.inexact):
            # Eldiv leaves entries outside the combined sparsity
            # pattern empty, so they must be filled manually.
            # Everything outside of other's sparsity is NaN, and everything
            # inside it is either zero or defined by eldiv.
            out = np.empty(self.shape, dtype=self.dtype)
            out.fill(np.nan)
            row, col = other.nonzero()
            out[row, col] = 0
            r = r.tocoo()
            out[r.row, r.col] = r.data
            out = matrix(out)
        else:
            # integers types go with nan <-> 0
            out = r

        return out
def test_linear_sum_assignment_input_validation():

    assert_raises(ValueError, linear_sum_assignment, [1, 2, 3])

    C = [[1, 2, 3], [4, 5, 6]]
    assert_array_equal(linear_sum_assignment(C),
                       linear_sum_assignment(np.asarray(C)))
    assert_array_equal(linear_sum_assignment(C),
                       linear_sum_assignment(matrix(C)))

    I = np.identity(3)
    assert_array_equal(linear_sum_assignment(I.astype(np.bool)),
                       linear_sum_assignment(I))
    assert_raises(ValueError, linear_sum_assignment, I.astype(str))

    I[0][0] = np.nan
    assert_raises(ValueError, linear_sum_assignment, I)

    I = np.identity(3)
    I[1][1] = -np.inf
    assert_raises(ValueError, linear_sum_assignment, I)

    I = np.identity(3)
    I[:, 0] = np.inf
    assert_raises(ValueError, linear_sum_assignment, I)
Esempio n. 17
0
 def test_minimize_tnc1b(self):
     x0, bnds = matrix([-2, 1]), ([-np.inf, None], [-1.5, None])
     xopt = [1, 1]
     x = optimize.minimize(self.f1,
                           x0,
                           method='TNC',
                           bounds=bnds,
                           options=self.opts).x
     assert_allclose(self.f1(x), self.f1(xopt), atol=1e-4)
Esempio n. 18
0
def test_regression_std_vector_dtypes():
    # Regression test for gh-3780, checking the std::vector typemaps
    # in sparsetools.cxx are complete.
    for dtype in supported_dtypes:
        ad = matrix([[1, 2], [3, 4]]).astype(dtype)
        a = csr_matrix(ad, dtype=dtype)

        # getcol is one function using std::vector typemaps, and should not fail
        assert_equal(a.getcol(0).todense(), ad[:, 0])
Esempio n. 19
0
        def make_cases(original, dtype):
            cases = []

            cases.append((matrix(original, dtype=dtype), original))
            cases.append((np.array(original, dtype=dtype), original))
            cases.append((sparse.csr_matrix(original, dtype=dtype), original))

            # Test default implementations of _adjoint and _rmatvec, which
            # refer to each other.
            def mv(x, dtype):
                y = original.dot(x)
                if len(x.shape) == 2:
                    y = y.reshape(-1, 1)
                return y

            def rmv(x, dtype):
                return original.T.conj().dot(x)

            class BaseMatlike(interface.LinearOperator):
                args = ()

                def __init__(self, dtype):
                    self.dtype = np.dtype(dtype)
                    self.shape = original.shape

                def _matvec(self, x):
                    return mv(x, self.dtype)

            class HasRmatvec(BaseMatlike):
                args = ()

                def _rmatvec(self, x):
                    return rmv(x, self.dtype)

            class HasAdjoint(BaseMatlike):
                args = ()

                def _adjoint(self):
                    shape = self.shape[1], self.shape[0]
                    matvec = partial(rmv, dtype=self.dtype)
                    rmatvec = partial(mv, dtype=self.dtype)
                    return interface.LinearOperator(matvec=matvec,
                                                    rmatvec=rmatvec,
                                                    dtype=self.dtype,
                                                    shape=shape)

            class HasRmatmat(HasRmatvec):
                def _matmat(self, x):
                    return original.dot(x)

                def _rmatmat(self, x):
                    return original.T.conj().dot(x)

            cases.append((HasRmatvec(dtype), original))
            cases.append((HasAdjoint(dtype), original))
            cases.append((HasRmatmat(dtype), original))
            return cases
Esempio n. 20
0
 def _add_dense(self, other):
     if other.shape != self.shape:
         raise ValueError('Incompatible shapes.')
     dtype = upcast_char(self.dtype.char, other.dtype.char)
     order = self._swap('CF')[0]
     result = np.array(other, dtype=dtype, order=order, copy=True)
     M, N = self._swap(self.shape)
     y = result if result.flags.c_contiguous else result.T
     csr_todense(M, N, self.indptr, self.indices, self.data, y)
     return matrix(result, copy=False)
Esempio n. 21
0
    def test_block_diag_basic(self):
        """ basic test for block_diag """
        A = coo_matrix([[1, 2], [3, 4]])
        B = coo_matrix([[5], [6]])
        C = coo_matrix([[7]])

        expected = matrix([[1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 5, 0],
                           [0, 0, 6, 0], [0, 0, 0, 7]])

        assert_equal(construct.block_diag((A, B, C)).todense(), expected)
Esempio n. 22
0
    def test_block_diag_basic(self):
        """ basic test for block_diag """
        A = coo_matrix([[1,2],[3,4]])
        B = coo_matrix([[5],[6]])
        C = coo_matrix([[7]])

        expected = matrix([[1, 2, 0, 0],
                           [3, 4, 0, 0],
                           [0, 0, 5, 0],
                           [0, 0, 6, 0],
                           [0, 0, 0, 7]])

        assert_equal(construct.block_diag((A, B, C)).todense(), expected)
Esempio n. 23
0
    def test_hstack(self):

        A = coo_matrix([[1,2],[3,4]])
        B = coo_matrix([[5],[6]])

        expected = matrix([[1, 2, 5],
                           [3, 4, 6]])
        assert_equal(construct.hstack([A,B]).todense(), expected)
        assert_equal(construct.hstack([A,B], dtype=np.float32).dtype, np.float32)
        assert_equal(construct.hstack([A.tocsc(),B.tocsc()]).todense(),
                     expected)
        assert_equal(construct.hstack([A.tocsc(),B.tocsc()], dtype=np.float32).dtype,
                     np.float32)
Esempio n. 24
0
    def test_bmat(self):

        A = coo_matrix([[1,2],[3,4]])
        B = coo_matrix([[5],[6]])
        C = coo_matrix([[7]])
        D = coo_matrix((0,0))

        expected = matrix([[1, 2, 5],
                           [3, 4, 6],
                           [0, 0, 7]])
        assert_equal(construct.bmat([[A,B],[None,C]]).todense(), expected)

        expected = matrix([[1, 2, 0],
                           [3, 4, 0],
                           [0, 0, 7]])
        assert_equal(construct.bmat([[A,None],[None,C]]).todense(), expected)

        expected = matrix([[0, 5],
                           [0, 6],
                           [7, 0]])
        assert_equal(construct.bmat([[None,B],[C,None]]).todense(), expected)

        expected = matrix(np.empty((0,0)))
        assert_equal(construct.bmat([[None,None]]).todense(), expected)
        assert_equal(construct.bmat([[None,D],[D,None]]).todense(), expected)

        # test bug reported in gh-5976
        expected = matrix([[7]])
        assert_equal(construct.bmat([[None,D],[C,None]]).todense(), expected)

        # test failure cases
        with assert_raises(ValueError) as excinfo:
            construct.bmat([[A], [B]])
        excinfo.match(r'Got blocks\[1,0\]\.shape\[1\] == 1, expected 2')

        with assert_raises(ValueError) as excinfo:
            construct.bmat([[A, C]])
        excinfo.match(r'Got blocks\[0,1\]\.shape\[0\] == 1, expected 2')
Esempio n. 25
0
    def test_vstack(self):

        A = coo_matrix([[1,2],[3,4]])
        B = coo_matrix([[5,6]])

        expected = matrix([[1, 2],
                           [3, 4],
                           [5, 6]])
        assert_equal(construct.vstack([A,B]).todense(), expected)
        assert_equal(construct.vstack([A,B], dtype=np.float32).dtype, np.float32)
        assert_equal(construct.vstack([A.tocsr(),B.tocsr()]).todense(),
                     expected)
        assert_equal(construct.vstack([A.tocsr(),B.tocsr()], dtype=np.float32).dtype,
                     np.float32)
        assert_equal(construct.vstack([A.tocsr(),B.tocsr()],
                                      dtype=np.float32).indices.dtype, np.int32)
        assert_equal(construct.vstack([A.tocsr(),B.tocsr()],
                                      dtype=np.float32).indptr.dtype, np.int32)
Esempio n. 26
0
        def make_cases(dtype):
            self.cases.append(matrix([[1,2,3],[4,5,6]], dtype=dtype))
            self.cases.append(np.array([[1,2,3],[4,5,6]], dtype=dtype))
            self.cases.append(sparse.csr_matrix([[1,2,3],[4,5,6]], dtype=dtype))

            # Test default implementations of _adjoint and _rmatvec, which
            # refer to each other.
            def mv(x, dtype):
                y = np.array([1 * x[0] + 2 * x[1] + 3 * x[2],
                              4 * x[0] + 5 * x[1] + 6 * x[2]], dtype=dtype)
                if len(x.shape) == 2:
                    y = y.reshape(-1, 1)
                return y

            def rmv(x, dtype):
                return np.array([1 * x[0] + 4 * x[1],
                                 2 * x[0] + 5 * x[1],
                                 3 * x[0] + 6 * x[1]], dtype=dtype)

            class BaseMatlike(interface.LinearOperator):
                def __init__(self, dtype):
                    self.dtype = np.dtype(dtype)
                    self.shape = (2,3)

                def _matvec(self, x):
                    return mv(x, self.dtype)

            class HasRmatvec(BaseMatlike):
                def _rmatvec(self,x):
                    return rmv(x, self.dtype)

            class HasAdjoint(BaseMatlike):
                def _adjoint(self):
                    shape = self.shape[1], self.shape[0]
                    matvec = partial(rmv, dtype=self.dtype)
                    rmatvec = partial(mv, dtype=self.dtype)
                    return interface.LinearOperator(matvec=matvec,
                                                    rmatvec=rmatvec,
                                                    dtype=self.dtype,
                                                    shape=shape)

            self.cases.append(HasRmatvec(dtype))
            self.cases.append(HasAdjoint(dtype))
Esempio n. 27
0
def test_linear_sum_assignment_input_validation():
    assert_raises(ValueError, linear_sum_assignment, [1, 2, 3])

    C = [[1, 2, 3], [4, 5, 6]]
    assert_array_equal(linear_sum_assignment(C),
                       linear_sum_assignment(np.asarray(C)))
    assert_array_equal(linear_sum_assignment(C),
                       linear_sum_assignment(matrix(C)))

    I = np.identity(3)
    assert_array_equal(linear_sum_assignment(I.astype(np.bool)),
                       linear_sum_assignment(I))
    assert_raises(ValueError, linear_sum_assignment, I.astype(str))

    I[0][0] = np.nan
    assert_raises(ValueError, linear_sum_assignment, I)

    I = np.identity(3)
    I[1][1] = np.inf
    assert_raises(ValueError, linear_sum_assignment, I)
Esempio n. 28
0
    def test_scale_rows_and_cols(self):
        D = matrix([[1,0,0,2,3],
                    [0,4,0,5,0],
                    [0,0,6,7,0]])

        #TODO expose through function
        S = csr_matrix(D)
        v = array([1,2,3])
        csr_scale_rows(3,5,S.indptr,S.indices,S.data,v)
        assert_equal(S.todense(), diag(v)*D)

        S = csr_matrix(D)
        v = array([1,2,3,4,5])
        csr_scale_columns(3,5,S.indptr,S.indices,S.data,v)
        assert_equal(S.todense(), D@diag(v))

        # blocks
        E = kron(D,[[1,2],[3,4]])
        S = bsr_matrix(E,blocksize=(2,2))
        v = array([1,2,3,4,5,6])
        bsr_scale_rows(3,5,2,2,S.indptr,S.indices,S.data,v)
        assert_equal(S.todense(), diag(v)@E)

        S = bsr_matrix(E,blocksize=(2,2))
        v = array([1,2,3,4,5,6,7,8,9,10])
        bsr_scale_columns(3,5,2,2,S.indptr,S.indices,S.data,v)
        assert_equal(S.todense(), E@diag(v))

        E = kron(D,[[1,2,3],[4,5,6]])
        S = bsr_matrix(E,blocksize=(2,3))
        v = array([1,2,3,4,5,6])
        bsr_scale_rows(3,5,2,3,S.indptr,S.indices,S.data,v)
        assert_equal(S.todense(), diag(v)@E)

        S = bsr_matrix(E,blocksize=(2,3))
        v = array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
        bsr_scale_columns(3,5,2,3,S.indptr,S.indices,S.data,v)
        assert_equal(S.todense(), E@diag(v))
Esempio n. 29
0
    def test_scale_rows_and_cols(self):
        D = matrix([[1, 0, 0, 2, 3], [0, 4, 0, 5, 0], [0, 0, 6, 7, 0]])

        #TODO expose through function
        S = csr_matrix(D)
        v = array([1, 2, 3])
        csr_scale_rows(3, 5, S.indptr, S.indices, S.data, v)
        assert_equal(S.todense(), diag(v) * D)

        S = csr_matrix(D)
        v = array([1, 2, 3, 4, 5])
        csr_scale_columns(3, 5, S.indptr, S.indices, S.data, v)
        assert_equal(S.todense(), D @ diag(v))

        # blocks
        E = kron(D, [[1, 2], [3, 4]])
        S = bsr_matrix(E, blocksize=(2, 2))
        v = array([1, 2, 3, 4, 5, 6])
        bsr_scale_rows(3, 5, 2, 2, S.indptr, S.indices, S.data, v)
        assert_equal(S.todense(), diag(v) @ E)

        S = bsr_matrix(E, blocksize=(2, 2))
        v = array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
        bsr_scale_columns(3, 5, 2, 2, S.indptr, S.indices, S.data, v)
        assert_equal(S.todense(), E @ diag(v))

        E = kron(D, [[1, 2, 3], [4, 5, 6]])
        S = bsr_matrix(E, blocksize=(2, 3))
        v = array([1, 2, 3, 4, 5, 6])
        bsr_scale_rows(3, 5, 2, 3, S.indptr, S.indices, S.data, v)
        assert_equal(S.todense(), diag(v) @ E)

        S = bsr_matrix(E, blocksize=(2, 3))
        v = array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
        bsr_scale_columns(3, 5, 2, 3, S.indptr, S.indices, S.data, v)
        assert_equal(S.todense(), E @ diag(v))
Esempio n. 30
0
    def test_bmat(self):

        A = coo_matrix([[1, 2], [3, 4]])
        B = coo_matrix([[5], [6]])
        C = coo_matrix([[7]])
        D = coo_matrix((0, 0))

        expected = array([[1, 2, 5], [3, 4, 6], [0, 0, 7]])
        assert_equal(construct.bmat([[A, B], [None, C]]).toarray(), expected)
        E = csr_matrix((1, 2), dtype=np.int32)
        assert_equal(
            construct.bmat([[A.tocsr(), B.tocsr()], [E, C.tocsr()]]).toarray(),
            expected)
        assert_equal(
            construct.bmat([[A.tocsc(), B.tocsc()], [E.tocsc(),
                                                     C.tocsc()]]).toarray(),
            expected)

        expected = array([[1, 2, 0], [3, 4, 0], [0, 0, 7]])
        assert_equal(
            construct.bmat([[A, None], [None, C]]).toarray(), expected)
        assert_equal(
            construct.bmat([[A.tocsr(), E.T.tocsr()],
                            [E, C.tocsr()]]).toarray(), expected)
        assert_equal(
            construct.bmat([[A.tocsc(), E.T.tocsc()], [E.tocsc(),
                                                       C.tocsc()]]).toarray(),
            expected)

        Z = csr_matrix((1, 1), dtype=np.int32)
        expected = array([[0, 5], [0, 6], [7, 0]])
        assert_equal(
            construct.bmat([[None, B], [C, None]]).toarray(), expected)
        assert_equal(
            construct.bmat([[E.T.tocsr(), B.tocsr()],
                            [C.tocsr(), Z]]).toarray(), expected)
        assert_equal(
            construct.bmat([[E.T.tocsc(), B.tocsc()], [C.tocsc(),
                                                       Z.tocsc()]]).toarray(),
            expected)

        expected = matrix(np.empty((0, 0)))
        assert_equal(construct.bmat([[None, None]]).toarray(), expected)
        assert_equal(
            construct.bmat([[None, D], [D, None]]).toarray(), expected)

        # test bug reported in gh-5976
        expected = array([[7]])
        assert_equal(
            construct.bmat([[None, D], [C, None]]).toarray(), expected)

        # test failure cases
        with assert_raises(ValueError) as excinfo:
            construct.bmat([[A], [B]])
        excinfo.match(r'Got blocks\[1,0\]\.shape\[1\] == 1, expected 2')

        with assert_raises(ValueError) as excinfo:
            construct.bmat([[A.tocsr()], [B.tocsr()]])
        excinfo.match(r'incompatible dimensions for axis 1')

        with assert_raises(ValueError) as excinfo:
            construct.bmat([[A.tocsc()], [B.tocsc()]])
        excinfo.match(r'Mismatching dimensions along axis 1: {1, 2}')

        with assert_raises(ValueError) as excinfo:
            construct.bmat([[A, C]])
        excinfo.match(r'Got blocks\[0,1\]\.shape\[0\] == 1, expected 2')

        with assert_raises(ValueError) as excinfo:
            construct.bmat([[A.tocsr(), C.tocsr()]])
        excinfo.match(r'Mismatching dimensions along axis 0: {1, 2}')

        with assert_raises(ValueError) as excinfo:
            construct.bmat([[A.tocsc(), C.tocsc()]])
        excinfo.match(r'incompatible dimensions for axis 0')
Esempio n. 31
0
def test_linear_sum_assignment_input_object():
    C = [[1, 2, 3], [4, 5, 6]]
    assert_array_equal(linear_sum_assignment(C),
                       linear_sum_assignment(np.asarray(C)))
    assert_array_equal(linear_sum_assignment(C),
                       linear_sum_assignment(matrix(C)))
Esempio n. 32
0
 def test_isdense(self):
     assert_equal(sputils.isdense(np.array([1])), True)
     assert_equal(sputils.isdense(matrix([1])), True)
Esempio n. 33
0
    def test_matvec(self):
        def get_matvecs(A):
            return [{
                        'shape': A.shape,
                        'matvec': lambda x: np.dot(A, x).reshape(A.shape[0]),
                        'rmatvec': lambda x: np.dot(A.T.conj(),
                                                    x).reshape(A.shape[1])
                    },
                    {
                        'shape': A.shape,
                        'matvec': lambda x: np.dot(A, x),
                        'rmatvec': lambda x: np.dot(A.T.conj(), x),
                        'matmat': lambda x: np.dot(A, x)
                    }]

        for matvecs in get_matvecs(self.A):
            A = interface.LinearOperator(**matvecs)

            assert_(A.args == ())

            assert_equal(A.matvec(np.array([1,2,3])), [14,32])
            assert_equal(A.matvec(np.array([[1],[2],[3]])), [[14],[32]])
            assert_equal(A * np.array([1,2,3]), [14,32])
            assert_equal(A * np.array([[1],[2],[3]]), [[14],[32]])
            assert_equal(A.dot(np.array([1,2,3])), [14,32])
            assert_equal(A.dot(np.array([[1],[2],[3]])), [[14],[32]])

            assert_equal(A.matvec(matrix([[1],[2],[3]])), [[14],[32]])
            assert_equal(A * matrix([[1],[2],[3]]), [[14],[32]])
            assert_equal(A.dot(matrix([[1],[2],[3]])), [[14],[32]])

            assert_equal((2*A)*[1,1,1], [12,30])
            assert_equal((2*A).rmatvec([1,1]), [10, 14, 18])
            assert_equal((2*A).H.matvec([1,1]), [10, 14, 18])
            assert_equal((2*A)*[[1],[1],[1]], [[12],[30]])
            assert_equal((2*A).matmat([[1],[1],[1]]), [[12],[30]])
            assert_equal((A*2)*[1,1,1], [12,30])
            assert_equal((A*2)*[[1],[1],[1]], [[12],[30]])
            assert_equal((2j*A)*[1,1,1], [12j,30j])
            assert_equal((A+A)*[1,1,1], [12, 30])
            assert_equal((A+A).rmatvec([1,1]), [10, 14, 18])
            assert_equal((A+A).H.matvec([1,1]), [10, 14, 18])
            assert_equal((A+A)*[[1],[1],[1]], [[12], [30]])
            assert_equal((A+A).matmat([[1],[1],[1]]), [[12], [30]])
            assert_equal((-A)*[1,1,1], [-6,-15])
            assert_equal((-A)*[[1],[1],[1]], [[-6],[-15]])
            assert_equal((A-A)*[1,1,1], [0,0])
            assert_equal((A-A)*[[1],[1],[1]], [[0],[0]])

            z = A+A
            assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] is A)
            z = 2*A
            assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] == 2)

            assert_(isinstance(A.matvec([1, 2, 3]), np.ndarray))
            assert_(isinstance(A.matvec(np.array([[1],[2],[3]])), np.ndarray))
            assert_(isinstance(A * np.array([1,2,3]), np.ndarray))
            assert_(isinstance(A * np.array([[1],[2],[3]]), np.ndarray))
            assert_(isinstance(A.dot(np.array([1,2,3])), np.ndarray))
            assert_(isinstance(A.dot(np.array([[1],[2],[3]])), np.ndarray))

            assert_(isinstance(A.matvec(matrix([[1],[2],[3]])), np.ndarray))
            assert_(isinstance(A * matrix([[1],[2],[3]]), np.ndarray))
            assert_(isinstance(A.dot(matrix([[1],[2],[3]])), np.ndarray))

            assert_(isinstance(2*A, interface._ScaledLinearOperator))
            assert_(isinstance(2j*A, interface._ScaledLinearOperator))
            assert_(isinstance(A+A, interface._SumLinearOperator))
            assert_(isinstance(-A, interface._ScaledLinearOperator))
            assert_(isinstance(A-A, interface._SumLinearOperator))

            assert_((2j*A).dtype == np.complex_)

            assert_raises(ValueError, A.matvec, np.array([1,2]))
            assert_raises(ValueError, A.matvec, np.array([1,2,3,4]))
            assert_raises(ValueError, A.matvec, np.array([[1],[2]]))
            assert_raises(ValueError, A.matvec, np.array([[1],[2],[3],[4]]))

            assert_raises(ValueError, lambda: A*A)
            assert_raises(ValueError, lambda: A**2)

        for matvecsA, matvecsB in product(get_matvecs(self.A),
                                          get_matvecs(self.B)):
            A = interface.LinearOperator(**matvecsA)
            B = interface.LinearOperator(**matvecsB)

            assert_equal((A*B)*[1,1], [50,113])
            assert_equal((A*B)*[[1],[1]], [[50],[113]])
            assert_equal((A*B).matmat([[1],[1]]), [[50],[113]])

            assert_equal((A*B).rmatvec([1,1]), [71,92])
            assert_equal((A*B).H.matvec([1,1]), [71,92])

            assert_(isinstance(A*B, interface._ProductLinearOperator))

            assert_raises(ValueError, lambda: A+B)
            assert_raises(ValueError, lambda: A**2)

            z = A*B
            assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] is B)

        for matvecsC in get_matvecs(self.C):
            C = interface.LinearOperator(**matvecsC)

            assert_equal((C**2)*[1,1], [17,37])
            assert_equal((C**2).rmatvec([1,1]), [22,32])
            assert_equal((C**2).H.matvec([1,1]), [22,32])
            assert_equal((C**2).matmat([[1],[1]]), [[17],[37]])

            assert_(isinstance(C**2, interface._PowerLinearOperator))
Esempio n. 34
0
 def test_zero_matrix(self):
     a = matrix([[0., 0], [0, 0]])
     assert_array_almost_equal(expm(a), [[1, 0], [0, 1]])
Esempio n. 35
0
    def test_matvec(self):
        def get_matvecs(A):
            return [{
                'shape':
                A.shape,
                'matvec':
                lambda x: np.dot(A, x).reshape(A.shape[0]),
                'rmatvec':
                lambda x: np.dot(A.T.conj(), x).reshape(A.shape[1])
            }, {
                'shape': A.shape,
                'matvec': lambda x: np.dot(A, x),
                'rmatvec': lambda x: np.dot(A.T.conj(), x),
                'rmatmat': lambda x: np.dot(A.T.conj(), x),
                'matmat': lambda x: np.dot(A, x)
            }]

        for matvecs in get_matvecs(self.A):
            A = interface.LinearOperator(**matvecs)

            assert_(A.args == ())

            assert_equal(A.matvec(np.array([1, 2, 3])), [14, 32])
            assert_equal(A.matvec(np.array([[1], [2], [3]])), [[14], [32]])
            assert_equal(A * np.array([1, 2, 3]), [14, 32])
            assert_equal(A * np.array([[1], [2], [3]]), [[14], [32]])
            assert_equal(A.dot(np.array([1, 2, 3])), [14, 32])
            assert_equal(A.dot(np.array([[1], [2], [3]])), [[14], [32]])

            assert_equal(A.matvec(matrix([[1], [2], [3]])), [[14], [32]])
            assert_equal(A * matrix([[1], [2], [3]]), [[14], [32]])
            assert_equal(A.dot(matrix([[1], [2], [3]])), [[14], [32]])

            assert_equal((2 * A) * [1, 1, 1], [12, 30])
            assert_equal((2 * A).rmatvec([1, 1]), [10, 14, 18])
            assert_equal((2 * A).H.matvec([1, 1]), [10, 14, 18])
            assert_equal((2 * A) * [[1], [1], [1]], [[12], [30]])
            assert_equal((2 * A).matmat([[1], [1], [1]]), [[12], [30]])
            assert_equal((A * 2) * [1, 1, 1], [12, 30])
            assert_equal((A * 2) * [[1], [1], [1]], [[12], [30]])
            assert_equal((2j * A) * [1, 1, 1], [12j, 30j])
            assert_equal((A + A) * [1, 1, 1], [12, 30])
            assert_equal((A + A).rmatvec([1, 1]), [10, 14, 18])
            assert_equal((A + A).H.matvec([1, 1]), [10, 14, 18])
            assert_equal((A + A) * [[1], [1], [1]], [[12], [30]])
            assert_equal((A + A).matmat([[1], [1], [1]]), [[12], [30]])
            assert_equal((-A) * [1, 1, 1], [-6, -15])
            assert_equal((-A) * [[1], [1], [1]], [[-6], [-15]])
            assert_equal((A - A) * [1, 1, 1], [0, 0])
            assert_equal((A - A) * [[1], [1], [1]], [[0], [0]])

            X = np.array([[1, 2], [3, 4]])
            # A_asarray = np.array([[1, 2, 3], [4, 5, 6]])
            assert_equal((2 * A).rmatmat(X), np.dot((2 * self.A).T, X))
            assert_equal((A * 2).rmatmat(X), np.dot((self.A * 2).T, X))
            assert_equal((2j * A).rmatmat(X), np.dot((2j * self.A).T.conj(),
                                                     X))
            assert_equal((A * 2j).rmatmat(X), np.dot((self.A * 2j).T.conj(),
                                                     X))
            assert_equal((A + A).rmatmat(X), np.dot((self.A + self.A).T, X))
            assert_equal((A + 2j * A).rmatmat(X),
                         np.dot((self.A + 2j * self.A).T.conj(), X))
            assert_equal((-A).rmatmat(X), np.dot((-self.A).T, X))
            assert_equal((A - A).rmatmat(X), np.dot((self.A - self.A).T, X))
            assert_equal((2j * A).rmatmat(2j * X),
                         np.dot((2j * self.A).T.conj(), 2j * X))

            z = A + A
            assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] is A)
            z = 2 * A
            assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] == 2)

            assert_(isinstance(A.matvec([1, 2, 3]), np.ndarray))
            assert_(isinstance(A.matvec(np.array([[1], [2], [3]])),
                               np.ndarray))
            assert_(isinstance(A * np.array([1, 2, 3]), np.ndarray))
            assert_(isinstance(A * np.array([[1], [2], [3]]), np.ndarray))
            assert_(isinstance(A.dot(np.array([1, 2, 3])), np.ndarray))
            assert_(isinstance(A.dot(np.array([[1], [2], [3]])), np.ndarray))

            assert_(isinstance(A.matvec(matrix([[1], [2], [3]])), np.ndarray))
            assert_(isinstance(A * matrix([[1], [2], [3]]), np.ndarray))
            assert_(isinstance(A.dot(matrix([[1], [2], [3]])), np.ndarray))

            assert_(isinstance(2 * A, interface._ScaledLinearOperator))
            assert_(isinstance(2j * A, interface._ScaledLinearOperator))
            assert_(isinstance(A + A, interface._SumLinearOperator))
            assert_(isinstance(-A, interface._ScaledLinearOperator))
            assert_(isinstance(A - A, interface._SumLinearOperator))

            assert_((2j * A).dtype == np.complex_)

            assert_raises(ValueError, A.matvec, np.array([1, 2]))
            assert_raises(ValueError, A.matvec, np.array([1, 2, 3, 4]))
            assert_raises(ValueError, A.matvec, np.array([[1], [2]]))
            assert_raises(ValueError, A.matvec, np.array([[1], [2], [3], [4]]))

            assert_raises(ValueError, lambda: A * A)
            assert_raises(ValueError, lambda: A**2)

        for matvecsA, matvecsB in product(get_matvecs(self.A),
                                          get_matvecs(self.B)):
            A = interface.LinearOperator(**matvecsA)
            B = interface.LinearOperator(**matvecsB)
            # AtimesB = np.array([[22, 28], [49, 64]])
            AtimesB = self.A.dot(self.B)
            X = np.array([[1, 2], [3, 4]])

            assert_equal((A * B).rmatmat(X), np.dot((AtimesB).T, X))
            assert_equal((2j * A * B).rmatmat(X),
                         np.dot((2j * AtimesB).T.conj(), X))

            assert_equal((A * B) * [1, 1], [50, 113])
            assert_equal((A * B) * [[1], [1]], [[50], [113]])
            assert_equal((A * B).matmat([[1], [1]]), [[50], [113]])

            assert_equal((A * B).rmatvec([1, 1]), [71, 92])
            assert_equal((A * B).H.matvec([1, 1]), [71, 92])

            assert_(isinstance(A * B, interface._ProductLinearOperator))

            assert_raises(ValueError, lambda: A + B)
            assert_raises(ValueError, lambda: A**2)

            z = A * B
            assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] is B)

        for matvecsC in get_matvecs(self.C):
            C = interface.LinearOperator(**matvecsC)
            X = np.array([[1, 2], [3, 4]])

            assert_equal(C.rmatmat(X), np.dot((self.C).T, X))
            assert_equal((C**2).rmatmat(X),
                         np.dot((np.dot(self.C, self.C)).T, X))

            assert_equal((C**2) * [1, 1], [17, 37])
            assert_equal((C**2).rmatvec([1, 1]), [22, 32])
            assert_equal((C**2).H.matvec([1, 1]), [22, 32])
            assert_equal((C**2).matmat([[1], [1]]), [[17], [37]])

            assert_(isinstance(C**2, interface._PowerLinearOperator))
Esempio n. 36
0
 def test_isdense(self):
     assert_equal(sputils.isdense(np.array([1])), True)
     assert_equal(sputils.isdense(matrix([1])), True)
Esempio n. 37
0
class TestSolveLyapunov(object):

    cases = [
        (np.array([[1, 2], [3, 4]]), np.array([[9, 10], [11, 12]])),
        # a, q all complex.
        (np.array([[1.0 + 1j, 2.0], [3.0 - 4.0j, 5.0]]),
         np.array([[2.0 - 2j, 2.0 + 2j], [-1.0 - 1j, 2.0]])),
        # a real; q complex.
        (np.array([[1.0, 2.0], [3.0, 5.0]]),
         np.array([[2.0 - 2j, 2.0 + 2j], [-1.0 - 1j, 2.0]])),
        # a complex; q real.
        (np.array([[1.0 + 1j, 2.0],
                   [3.0 - 4.0j, 5.0]]), np.array([[2.0, 2.0], [-1.0, 2.0]])),
        # An example from Kitagawa, 1977
        (np.array([[3, 9, 5, 1, 4], [1, 2, 3, 8, 4], [4, 6, 6, 6, 3],
                   [1, 5, 2, 0, 7], [5, 3, 3, 1, 5]]),
         np.array([[2, 4, 1, 0, 1], [4, 1, 0, 2, 0], [1, 0, 3, 0, 3],
                   [0, 2, 0, 1, 0], [1, 0, 3, 0, 4]])),
        # Companion matrix example. a complex; q real; a.shape[0] = 11
        (np.array([[
            0.100 + 0.j, 0.091 + 0.j, 0.082 + 0.j, 0.073 + 0.j, 0.064 + 0.j,
            0.055 + 0.j, 0.046 + 0.j, 0.037 + 0.j, 0.028 + 0.j, 0.019 + 0.j,
            0.010 + 0.j
        ],
                   [
                       1.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j
                   ],
                   [
                       0.000 + 0.j, 1.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j
                   ],
                   [
                       0.000 + 0.j, 0.000 + 0.j, 1.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j
                   ],
                   [
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 1.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j
                   ],
                   [
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       1.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j
                   ],
                   [
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 1.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j
                   ],
                   [
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 1.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j
                   ],
                   [
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 1.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j
                   ],
                   [
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       1.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j
                   ],
                   [
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j, 0.000 + 0.j,
                       0.000 + 0.j, 1.000 + 0.j, 0.000 + 0.j
                   ]]), np.eye(11)),
        # https://github.com/scipy/scipy/issues/4176
        (matrix([[0, 1], [-1 / 2,
                          -1]]), (matrix([0, 3]).T * matrix([0, 3]).T.T)),
        # https://github.com/scipy/scipy/issues/4176
        (matrix([[0, 1],
                 [-1 / 2,
                  -1]]), (np.array(matrix([0, 3]).T * matrix([0, 3]).T.T))),
    ]

    def test_continuous_squareness_and_shape(self):
        nsq = np.ones((3, 2))
        sq = np.eye(3)
        assert_raises(ValueError, solve_continuous_lyapunov, nsq, sq)
        assert_raises(ValueError, solve_continuous_lyapunov, sq, nsq)
        assert_raises(ValueError, solve_continuous_lyapunov, sq, np.eye(2))

    def check_continuous_case(self, a, q):
        x = solve_continuous_lyapunov(a, q)
        assert_array_almost_equal(
            np.dot(a, x) + np.dot(x,
                                  a.conj().transpose()), q)

    def check_discrete_case(self, a, q, method=None):
        x = solve_discrete_lyapunov(a, q, method=method)
        assert_array_almost_equal(
            np.dot(np.dot(a, x),
                   a.conj().transpose()) - x, -1.0 * q)

    def test_cases(self):
        for case in self.cases:
            self.check_continuous_case(case[0], case[1])
            self.check_discrete_case(case[0], case[1])
            self.check_discrete_case(case[0], case[1], method='direct')
            self.check_discrete_case(case[0], case[1], method='bilinear')
Esempio n. 38
0
 def test_zero_matrix(self):
     a = matrix([[0.,0],[0,0]])
     assert_array_almost_equal(expm(a),[[1,0],[0,1]])