예제 #1
0
파일: test_pcg.py 프로젝트: SpuqTeam/spuq
def test_pcg_matrix():
    rand = np.random.mtrand.RandomState(1234).random_sample

    N = 7
    M = rand((N, N))
    A = MatrixOperator(np.dot(M, M.T))
    P = MultiplicationOperator(1, CanonicalBasis(N))
    x = FlatVector(rand((N,)))
    b = A * x
    print

    # solve with identity as preconditioner
    x_ap, zeta, iter = pcg(A, b, P, 0 * x, eps=0.00001)
    assert_array_almost_equal(x.coeffs, x_ap.coeffs)
    assert_true( iter <= N + 3)

    # solve with exact matrix inverse as preconditioner
    # should converge in one step
    P = MatrixSolveOperator(np.dot(M, M.T))
    x_ap, zeta, iter = pcg(A, b, P, 0 * x, eps=0.00001)
    assert_array_almost_equal(x.coeffs, x_ap.coeffs)
    assert_true( iter <= 2)


    P = MatrixOperator(P.as_matrix())
    x_ap, zeta, iter = pcg(A, b, P, 0 * x, eps=0.00001)
    #print iter
    assert_array_almost_equal(x.coeffs, x_ap.coeffs)

    P = DiagonalMatrixOperator(np.diag(A.as_matrix())).inverse()
    x_ap, zeta, iter = pcg(A, b, P, 0 * x, eps=0.00001)
    #print iter
    assert_array_almost_equal(x.coeffs, x_ap.coeffs)
예제 #2
0
def pcg_solve(A, w, coeff_field, pde, stats, pcg_eps, pcg_maxiter):
    b = prepare_rhs(A, w, coeff_field, pde)
    P = PreconditioningOperator(coeff_field.mean_func,
                                pde.assemble_solve_operator)

    w, zeta, numit = pcg(A, b, P, w0=w, eps=pcg_eps, maxiter=pcg_maxiter)
    logger.info("PCG finished with zeta=%f after %i iterations", zeta, numit)

    b2 = A * w
    stats["RESIDUAL-L2"] = error_norm(b, b2, "L2")
    stats["RESIDUAL-H1A"] = error_norm(b, b2, pde.energy_norm)
    stats["DOFS"] = sum([b[mu]._fefunc.function_space().dim() for mu in b.keys()])
    stats["CELLS"] = sum([b[mu]._fefunc.function_space().mesh().num_cells() for mu in b.keys()])
    logger.info("[pcg] Residual = [%s (L2)] [%s (H1A)] with [%s dofs] and [%s cells]", stats["RESIDUAL-L2"], stats["RESIDUAL-H1A"], stats["DOFS"], stats["CELLS"])
    return w, zeta
예제 #3
0
#coeff_field = CoefficientField(a, rvs)
a0 = Constant("1.0")
a = (Expression('A*cos(pi*I*x[0])*cos(pi*I*x[1])', A=1 / i ** 2, I=i, degree=2) for i in count(1))
rvs = (UniformRV() for _ in count())
coeff_field = ParametricCoefficientField(func_func=a, rv_func=rvs, mean_func=a0)

pde = FEMPoisson()
A = MultiOperator(coeff_field, pde.assemble_operator)
mis = [Multiindex([0]),
       Multiindex([1]),
       Multiindex([0, 1]),
       Multiindex([0, 2])]
mesh = UnitSquare(4, 4)
fs = FunctionSpace(mesh, "CG", 1)
F = [interpolate(Expression("*".join(["x[0]"] * i)), fs) for i in range(1, 5)]
vecs = [FEniCSVector(f) for f in F]

w = MultiVectorWithProjection()
for mi, vec in zip(mis, vecs):
    w[mi] = vec
v = A * w
#P = MultiplicationOperator(1, vecs[0].basis)
P = PreconditioningOperator(a0, pde.assemble_solve_operator)
w2, zeta, numit = pcg(A, v, P, 0 * v)

print
print zeta, numit
print inner(w - w2, w - w2) / inner(w, w)
v2 = A * w2
print inner(v - v2, v - v2) / inner(v, v)
예제 #4
0
A = MultiOperator(coeff_field, pde.assemble_operator, pde.assemble_operator_inner_dofs, assembly_type=eval("ASSEMBLY_TYPE." + CONF_assembly_type))

# setup initial solution multivector
w = SampleProblem.setupMultiVector(dict([(mu, m) for mu, m in zip(mis, meshes)]), functools.partial(setup_vector, pde=pde, degree=CONF_FEM_degree))
logger.info("active indices of w after initialisation: %s", w.active_indices())


# ============================================================
# PART C: Assemble and Solve
# ============================================================

try:
    # pcg solver
    b = prepare_rhs(A, w, coeff_field, pde)
    P = PreconditioningOperator(coeff_field.mean_func, pde.assemble_solve_operator)
    w, zeta, numit = pcg(A, b, P, w0=w, eps=CONF_pcg_eps, maxiter=CONF_pcg_maxiter)
    logger.info("PCG finished with zeta=%f after %i iterations", zeta, numit)

#    raise Exception("TESTING")
except Exception as e:
    print e
    def get_exception_frame_data():
        import sys
        import traceback
        tb = sys.exc_info()[2]
        while tb.tb_next:
            tb = tb.tb_next
        frame = tb.tb_frame
        return (frame, frame.f_code.co_name, frame.f_locals)

    def do_debug(**kwargs):
예제 #5
0
# plot mesh
#import dolfin
#dolfin.plot(mesh, interactive=True)

# plot sparsity pattern
#fig = figure()
##spy(M)
#spy(K[0].as_matrix())
#show()

from spuq.application.egsz.pcg import pcg
P = TensorOperator([K0inv], [D[0]])
print 0*w
b = w.copy()
b._X += 1
v = pcg(A, b, P, 0*w )

print "v", v



if False:
    import numpy as np
    import scipy as sp
    import scipy.sparse as spa
    
    
    A=spa.csr_matrix(np.random.rand(7,3))
    B=np.random.rand(3,5)
    print A
    print B