Beispiel #1
0
def test_low_rank_blocks():
    n = 10

    # Test initialization
    a, b = np.random.rand(n, 1), np.random.rand(1, n)
    LR = LowRankMatrix(a, b)
    assert LR.shape == LR.full_matrix().shape
    assert matrix_rank(LR.full_matrix()) == LR.rank == 1
    assert LR.density == 2 * n / n**2

    a, b = np.random.rand(n, 2), np.random.rand(2, n)
    LR = LowRankMatrix(a, b)
    assert LR.shape == LR.full_matrix().shape
    assert matrix_rank(LR.full_matrix()) == LR.rank == 2

    # Test creation from SVD
    A = np.arange(n**2).reshape((n, n)) + 1.0
    dumb_low_rank = LowRankMatrix.from_full_matrix_with_SVD(A, n)
    assert np.allclose(dumb_low_rank.full_matrix() - A, 0.0)

    A_rank_1 = LowRankMatrix.from_full_matrix_with_SVD(A, 1)
    assert matrix_rank(A_rank_1.full_matrix()) == A_rank_1.rank == 1

    # Test recompression
    recompressed = dumb_low_rank.recompress(new_rank=2)
    assert recompressed.rank == matrix_rank(recompressed.full_matrix()) == 2

    recompressed = dumb_low_rank.recompress(tol=1e-1)
    assert recompressed.rank <= dumb_low_rank.rank

    # Test multiplication with vector
    b = np.random.rand(n)
    assert np.allclose(A_rank_1 @ b, A_rank_1.full_matrix() @ b)

    # Test creation with ACA
    full_A_rank_1 = A_rank_1.full_matrix()
    A_rank_1_again = LowRankMatrix.from_full_matrix_with_ACA(full_A_rank_1,
                                                             max_rank=5)
    assert matrix_rank(A_rank_1_again.full_matrix()) == 1
    assert np.allclose(A_rank_1_again.full_matrix(), full_A_rank_1)

    # Test creation from function with ACA
    X = np.linspace(0, 1, n)
    Y = np.linspace(10, 11, n)

    def f(i, j):
        return 1 / abs(X[i] - Y[j])

    S = np.array([[f(i, j) for j in range(n)] for i in range(n)])
    SLR = LowRankMatrix.from_function_with_ACA(f, n, n, max_rank=2, tol=1e-2)
    assert SLR.shape == (n, n)
    assert np.allclose(SLR.full_matrix(), S, atol=1e-2)

    with pytest.raises(NoConvergenceOfACA):
        LowRankMatrix.from_function_with_ACA(f, n, n, max_rank=1, tol=1e-3)

    summed = SLR + A_rank_1
    assert summed.rank == 1
Beispiel #2
0
def full_like(A, value, dtype=np.float64):
    """A matrix of the same kind and shape as A but filled with a single value."""
    if isinstance(A, BlockMatrix):
        new_matrix = []
        for i in range(A._stored_nb_blocks[0]):
            line = []
            for j in range(A._stored_nb_blocks[1]):
                line.append(
                    full_like(A._stored_blocks[i, j], value, dtype=dtype))
            new_matrix.append(line)
        return A.__class__(new_matrix)
    elif isinstance(A, LowRankMatrix):
        return LowRankMatrix(np.ones((A.shape[0], 1)),
                             np.full((1, A.shape[1]), value))
    elif isinstance(A, np.ndarray):
        return np.full_like(A, value, dtype=dtype)