Пример #1
0
def compute(grid, space, schemeName, schemeArgs):
    # solve the pde
    df = space.interpolate([0], name="solution")
    scheme = create.scheme(schemeName, [a == b, *dbc],
                           space,
                           solver="cg",
                           **schemeArgs,
                           parameters=parameters)
    info = scheme.solve(target=df)

    # compute the error
    edf = exact - df
    err = [inner(edf, edf), inner(grad(edf), grad(edf))]
    errors = [math.sqrt(e) for e in integrate(grid, err, order=8)]

    return df, errors, info
Пример #2
0
def test(operator):
    model = [
        equation,
        DirichletBC(uflSpace, [None, x[0]**2], 2),  # bottom
        DirichletBC(uflSpace, [exact[0], None], 3),  # top
        DirichletBC(uflSpace, [None, None], 4),  # left
        DirichletBC(uflSpace, exact, 1)
    ]  # right
    parameters = {"newton." + k: v for k, v in newtonParameter.items()}

    scheme = create.scheme(operator, model, spc, parameters=parameters)
    solution = spc.interpolate([0, 0], name="solution")
    scheme.solve(target=solution)
    l2errA = sqrt(integrate(grid, (solution - exact)**2, 5))
    grid.hierarchicalGrid.globalRefine(2)
    # note: without the `clear` the code can fail since the new dofs in 'solution' can be nan
    solution.clear()
    scheme.solve(target=solution)
    l2errB = sqrt(integrate(grid, (solution - exact)**2, 5))
    return solution, l2errA, l2errB
Пример #3
0
def test(space):
    if test_numpy:
        numpySpace = create.space(space,
                                  grid,
                                  dimRange=1,
                                  order=1,
                                  storage='numpy')
        numpyScheme = create.scheme("galerkin", model, numpySpace)
        numpy_h = create.function("discrete", numpySpace, name="numpy")
        numpy_dofs = numpy_h.as_numpy
        # numpyScheme.solve(target = numpy_h)
        start = time.time()
        for i in range(testLoop):
            linOp = linearOperator(numpyScheme)
            numpyScheme.jacobian(numpy_h, linOp)
            numpy_mat = linOp.as_numpy
        end = time.time()
        # print( "numpy:", (end-start)/testLoop, flush=True )
        # sys.stdout.flush()
        numpy_coo = numpy_mat.tocoo()
        # for i,j,v in zip(numpy_coo.row,numpy_coo.col,numpy_coo.data):
        #     print(i,j,v)
        # print("****************************",flush=True)

    if test_istl:
        istlSpace = create.space(space,
                                 grid,
                                 dimRange=1,
                                 order=1,
                                 storage='istl')
        istlScheme = create.scheme("galerkin", model, istlSpace)
        istl_h = create.function("discrete", istlSpace, name="istl")
        istl_dofs = istl_h.as_istl
        # istlScheme.solve(target = istl_h)
        start = time.time()
        for i in range(testLoop):
            linOp = linearOperator(istlScheme)
            istlScheme.jacobian(istl_h, linOp)
            istl_mat = linOp.as_istl
        end = time.time()
        # print( "istl:", (end-start)/testLoop, flush=True )
        # sys.stdout.flush()
        # there is no way yet to go from istl to scipy - would be nice to have
        # istl_coo = istl_mat.tocoo()
        # for i,j,v in zip(eigen_coo.row,eigen_coo.col,eigen_coo.data):
        #     print(i,j,v)
        # print("****************************",flush=True)

    if test_petsc:
        import petsc4py
        from petsc4py import PETSc
        petsc4py.init(sys.argv)
        petscSpace = create.space(space,
                                  grid,
                                  dimRange=1,
                                  order=1,
                                  storage='petsc')
        petscScheme = create.scheme("galerkin", model, petscSpace)
        petsc_h = create.function("discrete", petscSpace, name="petsc")
        petsc_dofs = petsc_h.as_petsc
        # petscScheme.solve(target = petsc_h)
        linOp = linearOperator(petscScheme)
        petscScheme.jacobian(petsc_h, linOp)
        petsc_mat = linOp.as_petsc
        rptr, cind, vals = petsc_mat.getValuesCSR()
        petsc_coo = scipy.sparse.csr_matrix((vals, cind, rptr)).tocoo()
        start = time.time()
        for i in range(testLoop):
            linOp = linearOperator(petscScheme)
            petscScheme.jacobian(petsc_h, linOp)
            petsc_mat = linOp.as_petsc
        end = time.time()
        # print( "petsc:", (end-start)/testLoop, flush=True )
        # sys.stdout.flush()

        ksp = PETSc.KSP()
        ksp.create(PETSc.COMM_WORLD)
        ksp.setType("cg")
        # ksp.getPC().setType("icc")
        petsc_h.clear()
        res = petsc_h.copy()
        petscScheme(petsc_h, res)
        petscScheme.jacobian(petsc_h, linOp)
        petsc_mat = linOp.as_petsc
        ksp.setOperators(petsc_mat, petsc_mat)
        ksp.setFromOptions()
        ksp.solve(res.as_petsc, petsc_h.as_petsc)

        # print("****************************",flush=True)
        # print(petsc_mat.size, petsc_mat.getSize(), petsc_mat.getSizes())
        # print(petsc_mat.getType())
        # print(type(petsc_mat))
        # print(petscSpace.size)
        # print(petsc_mat.assembled)
        # rptr, cind, vals = petsc_mat.getValuesCSR()
        # petsc_coo = scipy.sparse.csr_matrix((vals,cind,rptr),shape=(100,100)).tocoo()
        # for i,j,v in zip(petsc_coo.row,petsc_coo.col,petsc_coo.data):
        #     print(i,j,v)

    if test_istl:
        try:  # istl_coo does not exist
            assert (istl_coo.row == numpy_coo.row).all()
            assert (istl_coo.col == numpy_coo.col).all()
            assert np.allclose(istl_coo.data, numpy_coo.data)
        except:
            # print("issue between istl and numpy matrices")
            pass
    if test_petsc:
        try:
            assert (petsc_coo.row == numpy_coo.row).all()
            assert (petsc_coo.col == numpy_coo.col).all()
            assert np.allclose(petsc_coo.data, numpy_coo.data)
        except:
            # print("issue between petsc and numpy matrices")
            pass
Пример #4
0
    limiter(tmp, target)


# <markdowncell>
# Time stepping
# Converting UFL forms to scheme

# <codecell>
if coupled:
    form = form_s + form_p
    tpModel = create.model("integrands", grid, form == 0)
    # tpModel.penalty  = penalty
    # tpModel.timeStep = dt
    scheme = create.scheme(
        "galerkin",
        tpModel,
        spc, ("suitesparse", "umfpack"),
        parameters={"newton." + k: v
                    for k, v in newtonParameters.items()})
else:
    uflSpace1 = Space((P.dimWorld, P.dimWorld), 1)
    u1 = TrialFunction(uflSpace1)
    v1 = TestFunction(uflSpace1)
    form_p = replace(form_p, {
        u: as_vector([u1[0], intermediate.s[0]]),
        v: as_vector([v1[0], 0.])
    })
    form_s = replace(
        form_s, {
            u: as_vector([solution[0], u1[0]]),
            intermediate: as_vector([solution[0], intermediate[1]]),
            v: as_vector([0., v1[0]])
Пример #5
0
# now generate the model code and compile
model = create.model("elliptic",
                     surface,
                     equation,
                     coefficients={
                         u_n: solution_n,
                         u_0: solution_0
                     })

# Create volume
Volume = (1 / 3) * inner(Nu(solution, solution_0), A1(solution))
intVolume = integrate(surface, Volume, order=1)[0]

# create the solver using a standard fem scheme
scheme = create.scheme("h1", SolutionSpace, model, solver="bicgstab")
scheme.model.tau = deltaT
scheme.model.x_0 = X_0
scheme.model.omega = Omega
scheme.model.k_psi = K_PSI
scheme.model.k_b = K_B
scheme.model.p_0 = P_0
scheme.model.IntVolume = intVolume
scheme.model.k_0 = K_0
scheme.model.l_0 = L_0
scheme.model.u_B = U_B

# now loop through time and output the solution after each time step
steps = int(finalT / deltaT)
print("Begin time step")
for n in range(1, steps + 1):
Пример #6
0
q = TestFunction(spcP)
exact_u = as_vector([x[1] * (1. - x[1]), 0])
exact_p = as_vector([(-2 * x[0] + 2) * mu])
f = as_vector([
    0,
] * grid.dimension)
f += nu * exact_u
mainModel = (nu * dot(u, v) + mu * inner(grad(u) + grad(u).T, grad(v)) -
             dot(f, v)) * dx
gradModel = -inner(p[0] * Identity(grid.dimension), grad(v)) * dx
divModel = -div(u) * q[0] * dx
massModel = inner(p, q) * dx
preconModel = inner(grad(p), grad(q)) * dx

# can also use 'operator' everywhere
mainOp = create.scheme("galerkin",
                       (mainModel == 0, DirichletBC(spcU, exact_u, 1)), spcU)
gradOp = create.operator("galerkin", gradModel, spcP, spcU)
divOp = create.operator("galerkin", divModel, spcU, spcP)
massOp = create.scheme("galerkin", massModel == 0, spcP)
preconOp = create.scheme("galerkin", preconModel == 0, spcP)

mainOp.model.mu = 0.1
mainOp.model.nu = 0.01

velocity = spcU.interpolate([
    0,
] * spcU.dimRange, name="velocity")
pressure = spcP.interpolate([0], name="pressure")
rhsVelo = velocity.copy()
rhsPress = pressure.copy()
Пример #7
0
       inner( diffusiveFlux(u,grad(u)), outer(v, n) ) ) * ds
a += mu / hS * inner(jump(u), jump(v)) * dS
a += mu / hs * inner(u, v) * ds

newtonParameter = {
    "tolerance": 1e-10,
    "verbose": "true",
    "linear.tolerance": 1e-11,
    "linear.preconditioning.method": "ilu",
    "linear.preconditioning.iterations": 1,
    "linear.preconditioning.relaxation": 1.2,
    "linear.verbose": "false"
}
scheme = create.scheme(
    "galerkin",
    a == 0,
    parameters={"newton." + k: v
                for k, v in newtonParameter.items()})

solution = space.interpolate([0], name="solution")
scheme.solve(target=solution)
solutionp = solution.copy(name="solutionp")


def markp(element):
    return 1 if element.geometry.center[0] < 0.5 else 2


spaceAdapt(space, markp, [solution, solutionp])
grid.writeVTK("pre-hplaplace", pointdata=[solution, solutionp], subsampling=3)
scheme.solve(target=solutionp)
Пример #8
0
dt = Constant(0, "dt")  # time step
t = Constant(0, "t")  # current time

abs_du = sqrt(inner(grad(u), grad(u)))
K = 2 / (1 + sqrt(1 + 4 * abs_du))
# a = (inner((u - u_h_n)/dt, v) + inner(K*grad(u), grad(v)))*dx
a = (inner((u) / dt, v) + inner(u, v)) * dx
exact = as_vector([
    exp(-2 * t) * (initial - 1) + 1,
] * dimR)
b = replace(a, {u: exact})

solverParam = {"newton.verbose": 0, "newton.linear.verbose": 0}
scheme = create.scheme("galerkin",
                       a == b,
                       space,
                       solver='cg',
                       parameters=solverParam)
scheme.setQuadratureOrders(quadOrder, quadOrder)

scheme.model.dt = 0.05

grid.writeVTK('initial', pointdata={'initial': initial})

start = time.time()
t = 0
A = linearOperator(scheme)
while t < 1.0:
    scheme.model.t = t
    u_h_n.assign(u_h)
    scheme.solve(target=u_h)
Пример #9
0
                     polyGrid,
                     order=1,
                     dimRange=1,
                     storage="istl",
                     conforming=True)
u = TrialFunction(space)
v = TestFunction(space)
x = SpatialCoordinate(space)
exact = as_vector([(x[0] - x[0] * x[0]) * (x[1] - x[1] * x[1])])
Dcoeff = lambda u: 1.0 + u[0]**2
a = (Dcoeff(u) * inner(grad(u), grad(v))) * dx
b = -div(Dcoeff(exact) * grad(exact[0])) * v[0] * dx
dbcs = [dune.ufl.DirichletBC(space, exact, i + 1) for i in range(4)]
scheme = create.scheme("vem", [a == b, *dbcs],
                       space,
                       gradStabilization=Dcoeff(u),
                       solver="cg",
                       parameters=parameters)
solution = space.interpolate([0], name="solution")
info = scheme.solve(target=solution)
edf = exact - solution
errors = [
    math.sqrt(e) for e in integrate(
        polyGrid,
        [inner(edf, edf), inner(grad(edf), grad(edf))], order=5)
]
print(errors)
solution.plot(gridLines=None, colorbar="horizontal")
# <markdowncell>
# # Linear Elasticity
# As final example we solve a linear elasticity equation usign a
Пример #10
0
hF = FacetArea(uflSpace.cell())
# he = FacetArea(uflSpace.cell()) / Min( avg('+'), avg('-') )
heInv = hF / avg(hT)
exact = as_vector([cos(pi * x[0]) * cos(pi * x[1])])

#########

a = inner(grad(u - exact), grad(v)) * dx
a += mu * hT * div(grad(u[0] - exact[0])) * div(grad(v[0])) * dx
s = mu / heInv * inner(jump(grad(u[0])), jump(grad(v[0]))) * dS
s += mu / hF * inner(u - exact, v) * ds
model = create.model("integrands", grid, a + s == 0)
scheme = create.scheme(
    "galerkin",
    model,
    spc,
    solver="cg",
    parameters={"newton." + k: v
                for k, v in newtonParameter.items()})
solA = spc.interpolate([0], name="solA")
scheme.solve(solA)

########

a = div(grad(u[0] - exact[0])) * div(grad(v[0])) * dx
s = mu * heInv * inner(jump(grad(u[0])), jump(grad(v[0]))) * dS
s += mu / hF**3 * inner(u - exact, v) * ds
model = create.model("integrands", grid, a + s == 0)
scheme = create.scheme(
    "galerkin",
    model,