예제 #1
0
def errornorm(a, b, normid='L2', **kwargs):
    from math import sqrt
    from dune.fem.function import integrate
    grid = kwargs.get("grid", None)
    order = kwargs.get("order", 0)
    if grid is None:
        try:
            grid = a.grid
        except AttributeError:
            pass
    if grid is None:
        try:
            grid = b.grid
        except AttributeError:
            pass
    if grid is None:
        raise ValueError("can not extract grid from arguments")
    try:
        order += a.order
    except AttributeError:
        pass
    try:
        order += b.order
    except AttributeError:
        pass
    if normid == 'L2':
        error = inner(a - b, a - b)
        return sqrt(integrate(grid, error, 2 * order + 1))
    else:
        raise ValueError('errornorm with identifier', normid, ' not known\n')
예제 #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 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
예제 #4
0
def compute(scheme, uh, A, exact):
    start = time.time()
    scheme(uh, uh.copy())
    runTime = [time.time() - start]
    start = time.time()
    scheme.jacobian(uh, A)
    runTime += [time.time() - start]
    start = time.time()
    for i in range(20):
        scheme(uh, uh.copy())
        scheme.jacobian(uh, A)
    runTime += [time.time() - start]
    start = time.time()
    error = math.sqrt(
        integrate(uh.space.gridView, dot(uh - exact, uh - exact), order=5))
    runTime += [time.time() - start]
    return runTime, error
예제 #5
0
def errorMeasure(w, dw):
    rel = integrate(grid, [w[1]**2, dw[1]**2], 5)
    return math.sqrt(rel[1]) < tolerance * math.sqrt(rel[0])
예제 #6
0
def compute(space, epsilon, weakBnd, skeleton, mol=None):
    u = TrialFunction(space)
    v = TestFunction(space)
    n = FacetNormal(space)
    he = avg(CellVolume(space)) / FacetArea(space)
    hbnd = CellVolume(space) / FacetArea(space)
    x = SpatialCoordinate(space)

    exact = uflFunction(space.gridView,
                        name="exact",
                        order=3,
                        ufl=sin(x[0] * x[1]))
    uh = space.interpolate(exact, name="solution")

    # diffusion factor
    eps = Constant(epsilon, "eps")
    # transport direction and upwind flux
    b = as_vector([1, 0])
    hatb = (dot(b, n) + abs(dot(b, n))) / 2.0
    # characteristic function for left/right boundary
    dD = conditional((1 + x[0]) * (1 - x[0]) < 1e-10, 1, 0)
    # penalty parameter
    beta = Constant(20 * space.order**2, "beta")

    rhs = -(div(eps * grad(exact) - b * exact)) * v * dx
    aInternal = dot(eps * grad(u) - b * u, grad(v)) * dx
    aInternal -= eps * dot(grad(exact), n) * v * (1 - dD) * ds

    diffSkeleton  = eps*beta/he*jump(u)*jump(v)*dS -\
                    eps*dot(avg(grad(u)),n('+'))*jump(v)*dS -\
                    eps*jump(u)*dot(avg(grad(v)),n('+'))*dS
    if weakBnd:
        diffSkeleton += eps*beta/hbnd*(u-exact)*v*dD*ds -\
                        eps*dot(grad(exact),n)*v*dD*ds
    advSkeleton = jump(hatb * u) * jump(v) * dS
    if weakBnd:
        advSkeleton += (hatb * u + (dot(b, n) - hatb) * exact) * v * dD * ds

    if skeleton:
        form = aInternal + diffSkeleton + advSkeleton
    else:
        form = aInternal

    if weakBnd and skeleton:
        strongBC = None
    else:
        strongBC = DirichletBC(space, exact, dD)

    if space.storage[0] == "numpy":
        solver = {
            "solver": ("suitesparse", "umfpack"),
            "parameters": {
                "newton.verbose": True,
                "newton.linear.verbose": False,
                "newton.linear.tolerance": 1e-5,
            }
        }
    else:
        solver = {
            "solver": "bicgstab",
            "parameters": {
                "newton.linear.preconditioning.method": "ilu",
                "newton.linear.tolerance": 1e-13,
                "newton.verbose": True,
                "newton.linear.verbose": False
            }
        }
    if mol == 'mol':
        scheme = molSolutionScheme([form == rhs, strongBC], **solver)
    else:
        scheme = solutionScheme([form == rhs, strongBC], **solver)

    eoc = []
    info = scheme.solve(target=uh)

    error = dot(uh - exact, uh - exact)
    error0 = math.sqrt(integrate(gridView, error, order=5))
    print(error0, " # output", flush=True)
    for i in range(3):
        gridView.hierarchicalGrid.globalRefine(1)
        uh.interpolate(exact)
        scheme.solve(target=uh)
        error = dot(uh - exact, uh - exact)
        error1 = math.sqrt(integrate(gridView, error, order=5))
        eoc += [math.log(error1 / error0) / math.log(0.5)]
        print(i, error0, error1, eoc, " # output", flush=True)
        error0 = error1

    # print(space.order,epsilon,eoc)
    if (eoc[-1] - (space.order + 1)) < -0.1:
        print("ERROR:", space.order, epsilon, eoc)
    return eoc
예제 #7
0
        (Tension_im + Bending + Linkers_im) + g - f) * dx

equation = a_im == a_ex

# 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
예제 #8
0
from dune.grid import structuredGrid as leafGridView
gridView = leafGridView([0, 0], [1, 1], [4, 4])

# <markdowncell>
# ## Grid Functions
# We can integrate grid function
# <codecell>

from ufl import SpatialCoordinate, triangle
x = SpatialCoordinate(triangle)

exact = 1/2*(x[0]**2+x[1]**2) - 1/3*(x[0]**3 - x[1]**3) + 1

from dune.fem.function import integrate
mass = integrate(gridView, exact, order=5)
print(mass)

# <markdowncell>
# and plot them using matplotlib or write a vtk file for postprocessing
# <codecell>

from dune.fem.plotting import plotPointData as plot
plot(exact, grid=gridView)
gridView.writeVTK('exact', pointdata={'exact': exact})

from dune.fem.function import uflFunction
exact_gf = uflFunction(gridView, name="ufl", order=1, ufl=exact)
mass = 0
for element in gridView.elements:
  mass += exact_gf(element,[0.5,0.5]) * element.geometry.volume
예제 #9
0
estimator_ufl = ( (forcing-strong)*dualWeight[0] ) * v[0] * dx +\
                ( inner(jump(residual[0]*grad(u[0])), n('+'))*\
                  avg(dualWeight[0]) ) * avg(v[0]) * dS
estimator = create.operator("galerkin", estimator_ufl, spc, fvspace)
estimator.setQuadratureOrders(4*order+2,4*order+2)

uh = spc.interpolate([0], name="dg")
scheme = create.scheme("galerkin", [a==b,bnd],
            spc, solver="cg",
            parameters={"fem.solver.newton." + k: v for k, v in newtonParameter.items()})
scheme.solve(target=uh)

op = create.operator("galerkin", inner(jump(u),jump(v))*dS, spc)
w = spc.interpolate([0],name="tmp")
op(uh, w)
dgError = [ math.sqrt( integrate(grid,(uh[0]-exact[0])**2,order=7) ),
            math.sqrt( integrate(grid,inner(grad(uh[0]-exact[0]),grad(uh[0]-exact[0])),order=7)\
            + w.scalarProductDofs(uh)) ]
l2Errors = [dgError[0]]
h1Errors = [dgError[1]]

zh = spc.interpolate([0],name="dual_h")
dualOp = create.scheme("galerkin", [adjoint(a)==0],
                 spc, solver="cg",
                 parameters={"newton." + k: v for k, v in newtonParameter.items()})
pointFunctional = spc.interpolate([0],name="pointFunctional")
point = FieldVector([0.6,0.4])
errors = [ expression2GF(grid, exact-s, reconOrder) for s in solutions ]
dualErrors = algorithm.run('pointFunctional', 'pointfunctional.hh', point, pointFunctional, *errors)
dualOp.solve(target=zh, rhs=pointFunctional)
dualWeight.project(zh-zh)
예제 #10
0
from ufl import *

import math
import dune.fem
from dune.fem.function import integrate
import dune.create as create
from dune.ufl import DirichletBC, Space

dimRange = 12  # needs to be >= 4, test with 4,8,11
grid = create.grid("ALUConform", "../data/mixed.dgf", dimgrid=2)

from ufl import SpatialCoordinate
uflSpace = dune.ufl.Space(2, dimRange)
x = SpatialCoordinate(uflSpace.cell())
from math import pi, log, sqrt
from ufl import cos, sin, as_vector
exact = as_vector(
    [sin(3 * pi * x[0]), x[1] * x[1], x[0] *
     x[0], cos(3. * pi * x[1])] + [0] * (dimRange - 4))
v1 = integrate(grid, exact, 5).two_norm

space = create.space("Lagrange", grid, dimRange=dimRange, order=1)
u = space.interpolate(exact, name="u")
v2 = integrate(grid, u, 5).two_norm

print(v1, v2, v1 - v2)
v3 = integrate(grid, inner(grad(u[11]), grad(u[11])), 5)
예제 #11
0
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
# conforming VEM space:

# First we setup the domain
# <codecell>
L, W = 1, 0.2

constructor = cartesianDomain([0, 0], [L, W], [1, 1])
polyGrid = create.grid("polygrid",
예제 #12
0
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,
    spc,
    solver="cg",
    parameters={"newton." + k: v
                for k, v in newtonParameter.items()})
solB = spc.interpolate([0], name="solB")
scheme.solve(solB)

errA_sol = math.sqrt(integrate(grid, (solA - exact)**2, 5))
errB_sol = math.sqrt(integrate(grid, (solB - exact)**2, 5))
errA_B = math.sqrt(integrate(grid, (solA - solB)**2, 5))

print(
    errA_sol, errB_sol,
    errA_B)  # 0.0004520603651576     0.013241522498765897 0.012944687615068362

assert abs(errA_sol - 0.00045) / 0.00045 < 0.1
assert abs(errB_sol - 0.013) / 0.013 < 0.1
assert abs(errA_B - 0.013) / 0.013 < 0.1
예제 #13
0
v = TestFunction(space)
x = SpatialCoordinate(space.cell())

ubar = space.interpolate(as_vector([
    dot(x, x),
] * dimR), name="ubar")
a = (inner(0.5 * dot(u, u), v[0]) + inner(u[0] * grad(u), grad(v))) * dx
op = create.operator("galerkin", a, space)
A = linearOperator(op)
op.jacobian(ubar, A)
A(arg, destA)

da = apply_derivatives(derivative(action(a, ubar), ubar, u))
dop = create.operator("galerkin", da, space)
dop(arg, destB)
err = integrate(grid, (destA - destB)**2, 5)
# print("error=",err)
assert (err < 1e-15)

A = linearOperator(dop)
dop.jacobian(arg, A)
A(arg, destC)
err = integrate(grid, (destA - destC)**2, 5)
# print("error=",err)
assert (err < 1e-15)

###############################################################

op(ubar, destA)

lina = (inner(0.5 * dot(ubar, u), v[0]) +