def test_vec_to_sym_matrix(): # Check error if unsuitable size vec = np.ones(31) assert_raises_regex(ValueError, 'Vector of unsuitable shape', vec_to_sym_matrix, vec) # Check error if given diagonal shape incompatible with vec vec = np.ones(3) diagonal = np.zeros(4) assert_raises_regex(ValueError, 'incompatible with vector', vec_to_sym_matrix, vec, diagonal) # Check output value is correct vec = np.ones(6, ) sym = np.array([[sqrt(2), 1., 1.], [1., sqrt(2), 1.], [1., 1., sqrt(2)]]) assert_array_almost_equal(vec_to_sym_matrix(vec), sym) # Check output value is correct with seperate diagonal vec = np.ones(3, ) diagonal = np.ones(3) assert_array_almost_equal(vec_to_sym_matrix(vec, diagonal=diagonal), sym) # Check vec_to_sym_matrix is the inverse function of sym_matrix_to_vec # when diagonal is included assert_array_almost_equal(vec_to_sym_matrix(sym_matrix_to_vec(sym)), sym) # when diagonal is discarded vec = sym_matrix_to_vec(sym, discard_diagonal=True) diagonal = np.diagonal(sym) / sqrt(2) assert_array_almost_equal(vec_to_sym_matrix(vec, diagonal=diagonal), sym)
def test_sym_matrix_to_vec(): sym = np.ones((3, 3)) sqrt2 = 1. / sqrt(2.) vec = np.array([sqrt2, 1., sqrt2, 1., 1., sqrt2]) assert_array_almost_equal(sym_matrix_to_vec(sym), vec) vec = np.array([1., 1., 1.]) assert_array_almost_equal(sym_matrix_to_vec(sym, discard_diagonal=True), vec) # Check sym_matrix_to_vec is the inverse function of vec_to_sym_matrix n = 5 p = n * (n + 1) // 2 rand_gen = np.random.RandomState(0) # when diagonal is included vec = rand_gen.rand(p) sym = vec_to_sym_matrix(vec) assert_array_almost_equal(sym_matrix_to_vec(sym), vec) # when diagonal given separately diagonal = rand_gen.rand(n + 1) sym = vec_to_sym_matrix(vec, diagonal=diagonal) assert_array_almost_equal(sym_matrix_to_vec(sym, discard_diagonal=True), vec) # multiple matrices case when diagonal is included vecs = np.asarray([vec, 2. * vec, 0.5 * vec]) syms = vec_to_sym_matrix(vecs) assert_array_almost_equal(sym_matrix_to_vec(syms), vecs) # multiple matrices case when diagonal is given seperately diagonals = np.asarray([diagonal, 3. * diagonal, -diagonal]) syms = vec_to_sym_matrix(vecs, diagonal=diagonals) assert_array_almost_equal(sym_matrix_to_vec(syms, discard_diagonal=True), vecs)