def test_hierarchical_matrix(): n = 30 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)]) HS = BlockMatrix([ [ S[:n // 2, :n // 2], LowRankMatrix.from_full_matrix_with_ACA(S[n // 2:, :n // 2], tol=1e-5) ], [ LowRankMatrix.from_full_matrix_with_ACA(S[:n // 2, n // 2:], tol=1e-5), S[n // 2:, n // 2:] ], ]) assert np.allclose(HS.full_matrix(), S, rtol=2e-1) doubled = HS + HS assert np.allclose(2 * S, doubled.full_matrix(), rtol=2e-1)
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