Exemple #1
0
def test_save_and_checkpoint_timeseries(tempdir, encoding):
    mesh = UnitSquareMesh(MPI.comm_world, 16, 16)
    filename = os.path.join(tempdir, "u2_checkpoint.xdmf")
    FE = FiniteElement("CG", mesh.ufl_cell(), 2)
    V = FunctionSpace(mesh, FE)

    times = [0.5, 0.2, 0.1]
    u_out = [None] * len(times)
    u_in = [None] * len(times)

    with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as file:
        for i, p in enumerate(times):
            u_out[i] = interpolate(Expression("x[0]*p", p=p, degree=1), V)
            file.write_checkpoint(u_out[i], "u_out", p)

    with XDMFFile(mesh.mpi_comm(), filename) as file:
        for i, p in enumerate(times):
            u_in[i] = file.read_checkpoint(V, "u_out", i)

    for i, p in enumerate(times):
        u_in[i].vector().axpy(-1.0, u_out[i].vector())
        assert u_in[i].vector().norm(cpp.la.Norm.l2) < 1.0e-12

    # test reading last
    with XDMFFile(mesh.mpi_comm(), filename) as file:
        u_in_last = file.read_checkpoint(V, "u_out", -1)

    u_out[-1].vector().axpy(-1.0, u_in_last.vector())
    assert u_out[-1].vector().norm(cpp.la.Norm.l2) < 1.0e-12
Exemple #2
0
def test_save_and_checkpoint_timeseries(tempdir, encoding):
    mesh = UnitSquareMesh(MPI.comm_world, 16, 16)
    filename = os.path.join(tempdir, "u2_checkpoint.xdmf")
    FE = FiniteElement("CG", mesh.ufl_cell(), 2)
    V = FunctionSpace(mesh, FE)

    times = [0.5, 0.2, 0.1]
    u_out = [None] * len(times)
    u_in = [None] * len(times)

    p = 0.0

    def expr_eval(values, x):
        values[:, 0] = x[:, 0] * p

    with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as file:
        for i, p in enumerate(times):
            u_out[i] = interpolate(expr_eval, V)
            file.write_checkpoint(u_out[i], "u_out", p)

    with XDMFFile(mesh.mpi_comm(), filename) as file:
        for i, p in enumerate(times):
            u_in[i] = file.read_checkpoint(V, "u_out", i)

    for i, p in enumerate(times):
        u_in[i].vector.axpy(-1.0, u_out[i].vector)
        assert u_in[i].vector.norm() < 1.0e-12

    # test reading last
    with XDMFFile(mesh.mpi_comm(), filename) as file:
        u_in_last = file.read_checkpoint(V, "u_out", -1)

    u_out[-1].vector.axpy(-1.0, u_in_last.vector)
    assert u_out[-1].vector.norm() < 1.0e-12
Exemple #3
0
def _test_eigen_solver_sparse(callback_type):
    from rbnics.backends.dolfin import EigenSolver

    # Define mesh
    mesh = UnitSquareMesh(10, 10)

    # Define function space
    V_element = VectorElement("Lagrange", mesh.ufl_cell(), 2)
    Q_element = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
    W_element = MixedElement(V_element, Q_element)
    W = FunctionSpace(mesh, W_element)

    # Create boundaries
    class Wall(SubDomain):
        def inside(self, x, on_boundary):
            return on_boundary and (x[1] < 0 + DOLFIN_EPS
                                    or x[1] > 1 - DOLFIN_EPS)

    boundaries = MeshFunction("size_t", mesh, mesh.topology().dim() - 1)
    boundaries.set_all(0)
    wall = Wall()
    wall.mark(boundaries, 1)

    # Define variational problem
    vq = TestFunction(W)
    (v, q) = split(vq)
    up = TrialFunction(W)
    (u, p) = split(up)
    lhs = inner(grad(u), grad(v)) * dx - div(v) * p * dx - div(u) * q * dx
    rhs = -inner(p, q) * dx

    # Define boundary condition
    bc = [DirichletBC(W.sub(0), Constant((0., 0.)), boundaries, 1)]

    # Define eigensolver depending on callback type
    assert callback_type in ("form callbacks", "tensor callbacks")
    if callback_type == "form callbacks":
        solver = EigenSolver(W, lhs, rhs, bc)
    elif callback_type == "tensor callbacks":
        LHS = assemble(lhs)
        RHS = assemble(rhs)
        solver = EigenSolver(W, LHS, RHS, bc)

    # Solve the eigenproblem
    solver.set_parameters({
        "linear_solver": "mumps",
        "problem_type": "gen_non_hermitian",
        "spectrum": "target real",
        "spectral_transform": "shift-and-invert",
        "spectral_shift": 1.e-5
    })
    solver.solve(1)
    r, c = solver.get_eigenvalue(0)
    assert abs(c) < 1.e-10
    assert r > 0., "r = " + str(r) + " is not positive"
    print("Sparse inf-sup constant: ", sqrt(r))
    return (sqrt(r), solver.condensed_A, solver.condensed_B)
Exemple #4
0
def test_clear_sub_map_data_vector(mesh):
    mesh = UnitSquareMesh(8, 8)
    P1 = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
    W = FunctionSpace(mesh, P1 * P1)

    # Check block size
    assert W.dofmap().index_map.block_size == 2

    W.dofmap().clear_sub_map_data()
    with pytest.raises(RuntimeError):
        W0 = W.sub(0)
        assert (W0)
    with pytest.raises(RuntimeError):
        W1 = W.sub(1)
        assert (W1)
Exemple #5
0
#
# Next, various model parameters are defined::

# Model parameters
lmbda = 1.0e-02  # surface parameter
dt = 5.0e-06  # time step
theta = 0.5  # time stepping family, e.g. theta=1 -> backward Euler, theta=0.5 -> Crank-Nicolson

# A unit square mesh with 97 (= 96 + 1) vertices in each direction is
# created, and on this mesh a
# :py:class:`FunctionSpace<dolfin.functions.functionspace.FunctionSpace>`
# ``ME`` is built using a pair of linear Lagrangian elements. ::

# Create mesh and build function space
mesh = UnitSquareMesh(MPI.comm_world, 96, 96, CellType.triangle)
P1 = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
ME = FunctionSpace(mesh, P1 * P1)

# Trial and test functions of the space ``ME`` are now defined::

# Define trial and test functions
du = TrialFunction(ME)
q, v = TestFunctions(ME)

# .. index:: split functions
#
# For the test functions,
# :py:func:`TestFunctions<dolfin.functions.function.TestFunctions>` (note
# the 's' at the end) is used to define the scalar test functions ``q``
# and ``v``. The
# :py:class:`TrialFunction<dolfin.functions.function.TrialFunction>`
def test_unsteady_stokes():
    nx, ny = 15, 15
    k = 1
    nu = Constant(1.0e-0)
    dt = Constant(2.5e-2)
    num_steps = 20
    theta0 = 1.0  # Initial theta value
    theta1 = 0.5  # Theta after 1 step
    theta = Constant(theta0)

    mesh = UnitSquareMesh(nx, ny)

    # The 'unsteady version' of the benchmark in the 2012 paper by Labeur&Wells
    u_exact = Expression(
        (
            "sin(t) * x[0]*x[0]*(1.0 - x[0])*(1.0 - x[0])*(2.0*x[1] \
                           -6.0*x[1]*x[1] + 4.0*x[1]*x[1]*x[1])",
            "-sin(t)* x[1]*x[1]*(1.0 - x[1])*(1.0 - x[1])*(2.0*x[0] \
                           - 6.0*x[0]*x[0] + 4.0*x[0]*x[0]*x[0])",
        ),
        t=0,
        degree=7,
        domain=mesh,
    )
    p_exact = Expression("sin(t) * x[0]*(1.0 - x[0])",
                         t=0,
                         degree=7,
                         domain=mesh)
    du_exact = Expression(
        (
            "cos(t) * x[0]*x[0]*(1.0 - x[0])*(1.0 - x[0])*(2.0*x[1] \
                            - 6.0*x[1]*x[1] + 4.0*x[1]*x[1]*x[1])",
            "-cos(t)* x[1]*x[1]*(1.0 - x[1])*(1.0 - x[1])*(2.0*x[0] \
                            -6.0*x[0]*x[0] + 4.0*x[0]*x[0]*x[0])",
        ),
        t=0,
        degree=7,
        domain=mesh,
    )

    ux_exact = Expression(
        (
            "x[0]*x[0]*(1.0 - x[0])*(1.0 - x[0])*(2.0*x[1] \
                            - 6.0*x[1]*x[1] + 4.0*x[1]*x[1]*x[1])",
            "-x[1]*x[1]*(1.0 - x[1])*(1.0 - x[1])*(2.0*x[0] \
                            - 6.0*x[0]*x[0] + 4.0*x[0]*x[0]*x[0])",
        ),
        degree=7,
        domain=mesh,
    )

    px_exact = Expression("x[0]*(1.0 - x[0])", degree=7, domain=mesh)

    sin_ext = Expression("sin(t)", t=0, degree=7, domain=mesh)

    f = du_exact + sin_ext * div(px_exact * Identity(2) -
                                 2 * sym(grad(ux_exact)))

    Vhigh = VectorFunctionSpace(mesh, "DG", 7)
    Phigh = FunctionSpace(mesh, "DG", 7)

    # New syntax:
    V = VectorElement("DG", mesh.ufl_cell(), k)
    Q = FiniteElement("DG", mesh.ufl_cell(), k - 1)
    Vbar = VectorElement("DGT", mesh.ufl_cell(), k)
    Qbar = FiniteElement("DGT", mesh.ufl_cell(), k)

    mixedL = FunctionSpace(mesh, MixedElement([V, Q]))
    mixedG = FunctionSpace(mesh, MixedElement([Vbar, Qbar]))
    V2 = FunctionSpace(mesh, V)

    Uh = Function(mixedL)
    Uhbar = Function(mixedG)
    U0 = Function(mixedL)
    Uhbar0 = Function(mixedG)
    u0, p0 = split(U0)
    ubar0, pbar0 = split(Uhbar0)
    ustar = Function(V2)

    # Then the boundary conditions
    bc0 = DirichletBC(mixedG.sub(0), Constant((0, 0)), Gamma)
    bc1 = DirichletBC(mixedG.sub(1), Constant(0), Corner, "pointwise")
    bcs = [bc0, bc1]

    alpha = Constant(6 * k * k)
    forms_stokes = FormsStokes(mesh, mixedL, mixedG,
                               alpha).forms_unsteady(ustar, dt, nu, f)
    ssc = StokesStaticCondensation(
        mesh,
        forms_stokes["A_S"],
        forms_stokes["G_S"],
        forms_stokes["G_ST"],
        forms_stokes["B_S"],
        forms_stokes["Q_S"],
        forms_stokes["S_S"],
    )

    t = 0.0
    step = 0
    for step in range(num_steps):
        step += 1
        t += float(dt)
        if comm.Get_rank() == 0:
            print("Step " + str(step) + " Time " + str(t))

        # Set time level in exact solution
        u_exact.t = t
        p_exact.t = t

        du_exact.t = t - (1 - float(theta)) * float(dt)
        sin_ext.t = t - (1 - float(theta)) * float(dt)

        ssc.assemble_global_lhs()
        ssc.assemble_global_rhs()
        for bc in bcs:
            ssc.apply_boundary(bc)

        ssc.solve_problem(Uhbar, Uh, "none", "default")
        assign(U0, Uh)
        assign(ustar, U0.sub(0))
        assign(Uhbar0, Uhbar)
        if step == 1:
            theta.assign(theta1)

        udiv_e = sqrt(assemble(div(Uh.sub(0)) * div(Uh.sub(0)) * dx))

    u_ex_h = interpolate(u_exact, Vhigh)
    p_ex_h = interpolate(p_exact, Phigh)

    u_error = sqrt(assemble(dot(Uh.sub(0) - u_ex_h, Uh.sub(0) - u_ex_h) * dx))
    p_error = sqrt(assemble(dot(Uh.sub(1) - p_ex_h, Uh.sub(1) - p_ex_h) * dx))

    assert udiv_e < 1e-12
    assert u_error < 1.5e-4
    assert p_error < 1e-2
def test_steady_stokes(k):
    # Polynomial order and mesh resolution
    nx_list = [4, 8, 16]

    nu = Constant(1)

    if comm.Get_rank() == 0:
        print('{:=^72}'.format('Computing for polynomial order ' + str(k)))

    # Error listst
    error_u, error_p, error_div = [], [], []

    for nx in nx_list:
        if comm.Get_rank() == 0:
            print('# Resolution ' + str(nx))

        mesh = UnitSquareMesh(nx, nx)

        # Get forcing from exact solutions
        u_exact, p_exact = exact_solution(mesh)
        f = div(p_exact * Identity(2) - 2 * nu * sym(grad(u_exact)))

        # Define FunctionSpaces and functions
        V = VectorElement("DG", mesh.ufl_cell(), k)
        Q = FiniteElement("DG", mesh.ufl_cell(), k - 1)
        Vbar = VectorElement("DGT", mesh.ufl_cell(), k)
        Qbar = FiniteElement("DGT", mesh.ufl_cell(), k)

        mixedL = FunctionSpace(mesh, MixedElement([V, Q]))
        mixedG = FunctionSpace(mesh, MixedElement([Vbar, Qbar]))

        Uh = Function(mixedL)
        Uhbar = Function(mixedG)

        # Set forms
        alpha = Constant(6 * k * k)
        forms_stokes = FormsStokes(mesh, mixedL, mixedG,
                                   alpha).forms_steady(nu, f)

        # No-slip boundary conditions, set pressure in one of the corners
        bc0 = DirichletBC(mixedG.sub(0), Constant((0, 0)), Gamma)
        bc1 = DirichletBC(mixedG.sub(1), Constant(0), Corner, "pointwise")
        bcs = [bc0, bc1]

        # Initialize static condensation class
        ssc = StokesStaticCondensation(mesh, forms_stokes['A_S'],
                                       forms_stokes['G_S'],
                                       forms_stokes['B_S'],
                                       forms_stokes['Q_S'],
                                       forms_stokes['S_S'], bcs)

        # Assemble global system and incorporates bcs
        ssc.assemble_global_system(True)
        # Solve using mumps
        ssc.solve_problem(Uhbar, Uh, "mumps", "default")

        # Compute velocity/pressure/local div error
        uh, ph = Uh.split()
        e_u = np.sqrt(np.abs(assemble(dot(uh - u_exact, uh - u_exact) * dx)))
        e_p = np.sqrt(np.abs(assemble((ph - p_exact) * (ph - p_exact) * dx)))
        e_d = np.sqrt(np.abs(assemble(div(uh) * div(uh) * dx)))

        if comm.rank == 0:
            error_u.append(e_u)
            error_p.append(e_p)
            error_div.append(e_d)
            print('Error in velocity ' + str(error_u[-1]))
            print('Error in pressure ' + str(error_p[-1]))
            print('Local mass error ' + str(error_div[-1]))

    if comm.rank == 0:
        iterator_list = [1. / float(nx) for nx in nx_list]
        conv_u = compute_convergence(iterator_list, error_u)
        conv_p = compute_convergence(iterator_list, error_p)

        assert any(conv > k + 0.75 for conv in conv_u)
        assert any(conv > (k - 1) + 0.75 for conv in conv_p)
class Lid_driven_cavity(object):
    def __init__(self):
        n = 40
        self.mesh = UnitSquareMesh(n, n, "crossed")

        # Define mesh and boundaries.
        class LeftBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and x[0] < DOLFIN_EPS

        class RightBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and x[0] > 1.0 - DOLFIN_EPS

        class LowerBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and x[1] < DOLFIN_EPS

        class UpperBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and x[1] > 1.0 - DOLFIN_EPS

        class RestrictedUpperBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return (
                    on_boundary
                    and x[1] > 1.0 - DOLFIN_EPS
                    and DOLFIN_EPS < x[0]
                    and x[0] < 0.5 - DOLFIN_EPS
                )

        left = LeftBoundary()
        right = RightBoundary()
        lower = LowerBoundary()
        upper = UpperBoundary()
        # restricted_upper = RestrictedUpperBoundary()

        # Be particularly careful with the boundary conditions.
        # The main problem here is that the PPE system is consistent if and
        # only if
        #
        #     \int_\Omega div(u) = \int_\Gamma n.u = 0.
        #
        # This is exactly and even pointwise fulfilled for the continuous
        # problem.  In the discrete case, we can have to make sure that n.u is
        # 0 all along the boundary.
        # In the lid-driven cavity problem, of particular interest are the
        # corner points at the lid. One has to assert that the z-component of u
        # is 0 all across the lid, and the x-component of u is 0 everywhere but
        # the lid.  Since u is L2-"continuous", the lid condition on u_x must
        # not be enforced in the corner points. The u_y component must be
        # enforced all over the lid, including the end points.
        V_element = FiniteElement("CG", self.mesh.ufl_cell(), 2)
        self.W = FunctionSpace(self.mesh, V_element * V_element)

        self.u_bcs = [
            DirichletBC(self.W, (0.0, 0.0), left),
            DirichletBC(self.W, (0.0, 0.0), right),
            # DirichletBC(self.W.sub(0), Expression('x[0]'), restricted_upper),
            DirichletBC(self.W, (0.0, 0.0), lower),
            DirichletBC(self.W.sub(0), Constant("1.0"), upper),
            DirichletBC(self.W.sub(1), 0.0, upper),
            # DirichletBC(self.W.sub(0), Constant('-1.0'), lower),
            # DirichletBC(self.W.sub(1), 0.0, lower),
            # DirichletBC(self.W.sub(1), Constant('1.0'), left),
            # DirichletBC(self.W.sub(0), 0.0, left),
            # DirichletBC(self.W.sub(1), Constant('-1.0'), right),
            # DirichletBC(self.W.sub(0), 0.0, right),
        ]
        self.P = FunctionSpace(self.mesh, "CG", 1)
        self.p_bcs = []
        return
class Lid_driven_cavity(object):
    def __init__(self):
        n = 40
        self.mesh = UnitSquareMesh(n, n, "crossed")

        # Define mesh and boundaries.
        class LeftBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and x[0] < DOLFIN_EPS

        class RightBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and x[0] > 1.0 - DOLFIN_EPS

        class LowerBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and x[1] < DOLFIN_EPS

        class UpperBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and x[1] > 1.0 - DOLFIN_EPS

        class RestrictedUpperBoundary(SubDomain):
            def inside(self, x, on_boundary):
                return (on_boundary and x[1] > 1.0 - DOLFIN_EPS
                        and DOLFIN_EPS < x[0] and x[0] < 0.5 - DOLFIN_EPS)

        left = LeftBoundary()
        right = RightBoundary()
        lower = LowerBoundary()
        upper = UpperBoundary()
        # restricted_upper = RestrictedUpperBoundary()

        # Be particularly careful with the boundary conditions.
        # The main problem here is that the PPE system is consistent if and
        # only if
        #
        #     \int_\Omega div(u) = \int_\Gamma n.u = 0.
        #
        # This is exactly and even pointwise fulfilled for the continuous
        # problem.  In the discrete case, we can have to make sure that n.u is
        # 0 all along the boundary.
        # In the lid-driven cavity problem, of particular interest are the
        # corner points at the lid. One has to assert that the z-component of u
        # is 0 all across the lid, and the x-component of u is 0 everywhere but
        # the lid.  Since u is L2-"continuous", the lid condition on u_x must
        # not be enforced in the corner points. The u_y component must be
        # enforced all over the lid, including the end points.
        V_element = FiniteElement("CG", self.mesh.ufl_cell(), 2)
        self.W = FunctionSpace(self.mesh, V_element * V_element)

        self.u_bcs = [
            DirichletBC(self.W, (0.0, 0.0), left),
            DirichletBC(self.W, (0.0, 0.0), right),
            # DirichletBC(self.W.sub(0), Expression('x[0]'), restricted_upper),
            DirichletBC(self.W, (0.0, 0.0), lower),
            DirichletBC(self.W.sub(0), Constant("1.0"), upper),
            DirichletBC(self.W.sub(1), 0.0, upper),
            # DirichletBC(self.W.sub(0), Constant('-1.0'), lower),
            # DirichletBC(self.W.sub(1), 0.0, lower),
            # DirichletBC(self.W.sub(1), Constant('1.0'), left),
            # DirichletBC(self.W.sub(0), 0.0, left),
            # DirichletBC(self.W.sub(1), Constant('-1.0'), right),
            # DirichletBC(self.W.sub(0), 0.0, right),
        ]
        self.P = FunctionSpace(self.mesh, "CG", 1)
        self.p_bcs = []
        return
Exemple #10
0
from dolfin import CellDiameter, Constant, det, dx, Expression, Function, FunctionSpace, grad, has_pybind11, inner, TensorFunctionSpace, TestFunction, TrialFunction, UnitSquareMesh, VectorFunctionSpace
if has_pybind11():
    from dolfin.cpp.log import log, LogLevel, set_log_level
    PROGRESS = LogLevel.PROGRESS
else:
    from dolfin import log, PROGRESS, set_log_level
set_log_level(PROGRESS)
from rbnics.backends.dolfin import SeparatedParametrizedForm
from rbnics.eim.utils.decorators.store_map_from_solution_to_problem import _solution_to_problem_map

# Common variables
mesh = UnitSquareMesh(10, 10)

V = VectorFunctionSpace(mesh, "Lagrange", 2)

expr1 = Expression("x[0]", mu_0=0., degree=1, cell=mesh.ufl_cell()) # f_5
expr2 = Expression(("x[0]", "x[1]"), mu_0=0., degree=1, cell=mesh.ufl_cell()) # f_6
expr3 = Expression((("1*x[0]", "2*x[1]"), ("3*x[0]", "4*x[1]")), mu_0=0., degree=1, cell=mesh.ufl_cell()) # f_7
expr4 = Expression((("4*x[0]", "3*x[1]"), ("2*x[0]", "1*x[1]")), mu_0=0., degree=1, cell=mesh.ufl_cell()) # f_8
expr5 = Expression("x[0]", degree=1, cell=mesh.ufl_cell()) # f_9
expr6 = Expression(("x[0]", "x[1]"), degree=1, cell=mesh.ufl_cell()) # f_10
expr7 = Expression((("1*x[0]", "2*x[1]"), ("3*x[0]", "4*x[1]")), degree=1, cell=mesh.ufl_cell()) # f_11
expr8 = Expression((("4*x[0]", "3*x[1]"), ("2*x[0]", "1*x[1]")), degree=1, cell=mesh.ufl_cell()) # f_12
expr9 = Constant(((1, 2), (3, 4))) # f_13

scalar_V = FunctionSpace(mesh, "Lagrange", 3)
tensor_V = TensorFunctionSpace(mesh, "Lagrange", 1)
expr10 = Function(scalar_V) # f_18
expr11 = Function(V) # f_21
expr12 = Function(tensor_V) # f_24
expr13 = Function(scalar_V) # f_27
def test_poisson(k):
    # Polynomial order and mesh resolution
    nx_list = [4, 8, 16]

    # Error list
    error_u_l2, error_u_h1 = [], []

    for nx in nx_list:
        mesh = UnitSquareMesh(nx, nx)

        # Define FunctionSpaces and functions
        V = FunctionSpace(mesh, "DG", k)
        Vbar = FunctionSpace(mesh,
                             FiniteElement("CG", mesh.ufl_cell(), k)["facet"])

        u_soln = Expression("sin(pi*x[0])*sin(pi*x[1])",
                            degree=k + 1,
                            domain=mesh)
        f = Expression("2*pi*pi*sin(pi*x[0])*sin(pi*x[1])", degree=k + 1)
        u, v = Function(V), TestFunction(V)
        ubar, vbar = Function(Vbar), TestFunction(Vbar)

        n = FacetNormal(mesh)
        h = CellDiameter(mesh)
        alpha = Constant(6 * k * k)
        penalty = alpha / h

        def facet_integral(integrand):
            return integrand('-') * dS + integrand('+') * dS + integrand * ds

        u_flux = ubar
        F_v_flux = grad(u) + penalty * outer(u_flux - u, n)

        residual_local = inner(grad(u), grad(v)) * dx
        residual_local += facet_integral(inner(outer(u_flux - u, n), grad(v)))
        residual_local -= facet_integral(inner(F_v_flux, outer(v, n)))
        residual_local -= f * v * dx

        residual_global = facet_integral(inner(F_v_flux, outer(vbar, n)))

        a_ll = derivative(residual_local, u)
        a_lg = derivative(residual_local, ubar)
        a_gl = derivative(residual_global, u)
        a_gg = derivative(residual_global, ubar)

        l_l = -residual_local
        l_g = -residual_global

        bcs = [DirichletBC(Vbar, u_soln, "on_boundary")]

        # Initialize static condensation assembler
        assembler = AssemblerStaticCondensation(a_ll, a_lg, a_gl, a_gg, l_l,
                                                l_g, bcs)

        A_g, b_g = PETScMatrix(), PETScVector()
        assembler.assemble_global_lhs(A_g)
        assembler.assemble_global_rhs(b_g)

        for bc in bcs:
            bc.apply(A_g, b_g)

        solver = PETScKrylovSolver()
        solver.set_operator(A_g)
        PETScOptions.set("ksp_type", "preonly")
        PETScOptions.set("pc_type", "lu")
        PETScOptions.set("pc_factor_mat_solver_type", "mumps")
        solver.set_from_options()

        solver.solve(ubar.vector(), b_g)
        assembler.backsubstitute(ubar._cpp_object, u._cpp_object)

        # Compute L2 and H1 norms
        e_u_l2 = assemble((u - u_soln)**2 * dx)**0.5
        e_u_h1 = assemble(grad(u - u_soln)**2 * dx)**0.5

        if mesh.mpi_comm().rank == 0:
            error_u_l2.append(e_u_l2)
            error_u_h1.append(e_u_h1)

    if mesh.mpi_comm().rank == 0:
        iterator_list = [1.0 / float(nx) for nx in nx_list]
        conv_u_l2 = compute_convergence(iterator_list, error_u_l2)
        conv_u_h1 = compute_convergence(iterator_list, error_u_h1)

        # Optimal rate of k + 1 - tolerance
        assert np.all(conv_u_l2 >= (k + 1.0 - 0.15))
        # Optimal rate of k - tolerance
        assert np.all(conv_u_h1 >= (k - 0.1))
Exemple #12
0
from dolfin import CellDiameter, Constant, det, dx, Expression, Function, FunctionSpace, grad, has_pybind11, inner, TensorFunctionSpace, TestFunction, TrialFunction, UnitSquareMesh, VectorFunctionSpace
if has_pybind11():
    from dolfin.cpp.log import log, LogLevel, set_log_level
    PROGRESS = LogLevel.PROGRESS
else:
    from dolfin import log, PROGRESS, set_log_level
set_log_level(PROGRESS)
from rbnics.backends.dolfin import SeparatedParametrizedForm
from rbnics.utils.decorators.store_map_from_solution_to_problem import _solution_to_problem_map

# Common variables
mesh = UnitSquareMesh(10, 10)

V = VectorFunctionSpace(mesh, "Lagrange", 2)

expr1 = Expression("x[0]", mu_0=0., degree=1, cell=mesh.ufl_cell())  # f_5
expr2 = Expression(("x[0]", "x[1]"), mu_0=0., degree=1,
                   cell=mesh.ufl_cell())  # f_6
expr3 = Expression((("1*x[0]", "2*x[1]"), ("3*x[0]", "4*x[1]")),
                   mu_0=0.,
                   degree=1,
                   cell=mesh.ufl_cell())  # f_7
expr4 = Expression((("4*x[0]", "3*x[1]"), ("2*x[0]", "1*x[1]")),
                   mu_0=0.,
                   degree=1,
                   cell=mesh.ufl_cell())  # f_8
expr5 = Expression("x[0]", degree=1, cell=mesh.ufl_cell())  # f_9
expr6 = Expression(("x[0]", "x[1]"), degree=1, cell=mesh.ufl_cell())  # f_10
expr7 = Expression((("1*x[0]", "2*x[1]"), ("3*x[0]", "4*x[1]")),
                   degree=1,
                   cell=mesh.ufl_cell())  # f_11