Exemple #1
0
def _test_reduced_mesh_elliptic_matrix(V, reduced_mesh):
    reduced_V = reduced_mesh.get_reduced_function_spaces()
    dofs = reduced_mesh.get_dofs_list()
    reduced_dofs = reduced_mesh.get_reduced_dofs_list()

    u = TrialFunction(V)
    v = TestFunction(V)

    trial = 1
    test = 0
    u_N = TrialFunction(reduced_V[trial])
    v_N = TestFunction(reduced_V[test])

    A = assemble((u.dx(0) * v + u * v) * dx)
    A_N = assemble((u_N.dx(0) * v_N + u_N * v_N) * dx)

    A_dofs = evaluate_and_vectorize_sparse_matrix_at_dofs(A, dofs)
    A_N_reduced_dofs = evaluate_and_vectorize_sparse_matrix_at_dofs(A_N, reduced_dofs)

    test_logger.log(DEBUG, "A at dofs:")
    test_logger.log(DEBUG, str(A_dofs))
    test_logger.log(DEBUG, "A_N at reduced dofs:")
    test_logger.log(DEBUG, str(A_N_reduced_dofs))
    test_logger.log(DEBUG, "Error:")
    test_logger.log(DEBUG, str(A_dofs - A_N_reduced_dofs))

    assert isclose(A_dofs, A_N_reduced_dofs).all()
Exemple #2
0
    def __init__(self, U_m, mesh):
        """Function spaces and BCs"""
        V = VectorFunctionSpace(mesh, 'P', 2)
        Q = FunctionSpace(mesh, 'P', 1)
        self.mesh = mesh
        self.vu, self.vp = TestFunction(V), TestFunction(Q)  # for integration
        self.u_, self.p_ = Function(V), Function(Q)  # for the solution
        self.u_1, self.p_1 = Function(V), Function(Q)  # for the prev. solution
        self.u_k, self.p_k = Function(V), Function(Q)  # for the prev. solution
        self.u, self.p = TrialFunction(V), TrialFunction(Q)  # unknown!

        U0_str = "4.*U_m*x[1]*(.41-x[1])/(.41*.41)"
        x = [0,
             .41 / 2]  # evaluate the Expression at the center of the channel
        self.U_mean = np.mean(2 / 3 * eval(U0_str))

        U0 = Expression((U0_str, "0"), U_m=U_m, degree=2)
        bc0 = DirichletBC(V, Constant((0, 0)), cylinderwall)
        bc1 = DirichletBC(V, Constant((0, 0)), topandbottom)
        bc2 = DirichletBC(V, U0, inlet)
        bc3 = DirichletBC(Q, Constant(0), outlet)
        self.bcu = [bc0, bc1, bc2]
        self.bcp = [bc3]
        # ds is needed to compute drag and lift.
        ASD1 = AutoSubDomain(topandbottom)
        ASD2 = AutoSubDomain(cylinderwall)
        mf = MeshFunction("size_t", mesh, 1)
        mf.set_all(0)
        ASD1.mark(mf, 1)
        ASD2.mark(mf, 2)
        self.ds_ = ds(subdomain_data=mf, domain=mesh)
        return
Exemple #3
0
def _test_reduced_mesh_collapsed_matrix(V, U, reduced_mesh):
    reduced_V = reduced_mesh.get_reduced_function_spaces()
    dofs = reduced_mesh.get_dofs_list()
    reduced_dofs = reduced_mesh.get_reduced_dofs_list()

    u = TrialFunction(U)
    (u_0, u_1) = split(u)
    v = TestFunction(V)

    trial = 1
    test = 0
    u_N = TrialFunction(reduced_V[trial])
    v_N = TestFunction(reduced_V[test])
    (u_N_0, u_N_1) = split(u_N)

    A = assemble(inner(u_0, v) * dx + u_1 * v[0] * dx)
    A_N = assemble(inner(u_N_0, v_N) * dx + u_N_1 * v_N[0] * dx)

    A_dofs = evaluate_and_vectorize_sparse_matrix_at_dofs(A, dofs)
    A_N_reduced_dofs = evaluate_and_vectorize_sparse_matrix_at_dofs(A_N, reduced_dofs)

    test_logger.log(DEBUG, "A at dofs:")
    test_logger.log(DEBUG, str(A_dofs))
    test_logger.log(DEBUG, "A_N at reduced dofs:")
    test_logger.log(DEBUG, str(A_N_reduced_dofs))
    test_logger.log(DEBUG, "Error:")
    test_logger.log(DEBUG, str(A_dofs - A_N_reduced_dofs))

    assert isclose(A_dofs, A_N_reduced_dofs).all()
Exemple #4
0
def test_nest_matrix(pushpop_parameters):

    # Create Matrices and insert into nest
    A00 = PETScMatrix()
    A01 = PETScMatrix()
    A10 = PETScMatrix()
    mesh = UnitSquareMesh(12, 12)
    V = FunctionSpace(mesh, "Lagrange", 2)
    Q = FunctionSpace(mesh, "Lagrange", 1)
    u, v = TrialFunction(V), TestFunction(V)
    p, q = TrialFunction(Q), TestFunction(Q)
    assemble(u * v * dx, tensor=A00)
    assemble(p * v * dx, tensor=A01)
    assemble(u * q * dx, tensor=A10)

    AA = PETScNestMatrix([A00, A01, A10, None])

    # Create compatible RHS Vectors and insert into nest
    u = PETScVector()
    p = PETScVector()
    x = PETScVector()

    A00.init_vector(u, 1)
    A01.init_vector(p, 1)
    AA.init_vectors(x, [u, p])
Exemple #5
0
def _test_reduced_mesh_mixed_matrix(V, reduced_mesh):
    reduced_V = reduced_mesh.get_reduced_function_spaces()
    dofs = reduced_mesh.get_dofs_list()
    reduced_dofs = reduced_mesh.get_reduced_dofs_list()

    u = TrialFunction(V)
    v = TestFunction(V)
    (u_0, u_1) = split(u)
    (v_0, v_1) = split(v)

    trial = 1
    test = 0
    u_N = TrialFunction(reduced_V[trial])
    v_N = TestFunction(reduced_V[test])
    (u_N_0, u_N_1) = split(u_N)
    (v_N_0, v_N_1) = split(v_N)

    A = assemble(u_0[0]*v_0[0]*dx + u_0[0]*v_0[1]*dx + u_0[1]*v_0[0]*dx + u_0[1]*v_0[1]*dx + u_1*v_1*dx + u_0[0]*v_1*dx + u_1*v_0[1]*dx)
    A_N = assemble(u_N_0[0]*v_N_0[0]*dx + u_N_0[0]*v_N_0[1]*dx + u_N_0[1]*v_N_0[0]*dx + u_N_0[1]*v_N_0[1]*dx + u_N_1*v_N_1*dx + u_N_0[0]*v_N_1*dx + u_N_1*v_N_0[1]*dx)

    A_dofs = evaluate_and_vectorize_sparse_matrix_at_dofs(A, dofs)
    A_N_reduced_dofs = evaluate_and_vectorize_sparse_matrix_at_dofs(A_N, reduced_dofs)

    log(PROGRESS, "A at dofs:\n" + str(A_dofs))
    log(PROGRESS, "A_N at reduced dofs:\n" + str(A_N_reduced_dofs))
    log(PROGRESS, "Error:\n" + str(A_dofs - A_N_reduced_dofs))
    
    assert isclose(A_dofs, A_N_reduced_dofs).all()
def weighted_gradient_matrix(mesh, i, family='CG', degree=1, constrained_domain=None):
    """Compute weighted gradient matrix

    The matrix allows you to compute the gradient of a P1 Function
    through a simple matrix vector product

    CG family:
        p_ is the pressure solution on CG1
        dPdX = weighted_gradient_matrix(mesh, 0, 'CG', degree)
        V = FunctionSpace(mesh, 'CG', degree)
        dpdx = Function(V)
        dpdx.vector()[:] = dPdX * p_.vector()

        The space for dpdx must be continuous Lagrange of some order

    CR family:
        p_ is the pressure solution on CR
        dPdX = weighted_gradient_matrix(mesh, 0, 'CR', 1)
        V = FunctionSpace(mesh, 'CR', 1)
        dpdx = Function(V)
        dpdx.vector()[:] = dPdX * p_.vector()

    """

    DG = FunctionSpace(mesh, 'DG', 0)

    if family == 'CG':
        # Source and Target spaces are CG_1 and CG_degree
        S = FunctionSpace(mesh, 'CG', 1, constrained_domain=constrained_domain)
        T = FunctionSpace(mesh, 'CG', degree, constrained_domain=constrained_domain)
    elif family == 'CR':
        if degree != 1:
            print('\033[1;37;34m%s\033[0m' % 'Ignoring degree')

        # Source and Target spaces are CR
        S = FunctionSpace(mesh, 'CR', 1, constrained_domain=constrained_domain)
        T = S
    else:
        raise ValueError('Only CG and CR families are allowed.')

    G = assemble(TrialFunction(DG)*TestFunction(T)*dx)
    dg = Function(DG)
    if isinstance(i, (tuple, list)):
        CC = []
        for ii in i:
            dP = assemble(TrialFunction(S).dx(ii)*TestFunction(DG)*dx)
            A = Matrix(G)
            Cp = compiled_gradient_module.compute_weighted_gradient_matrix(A, dP, dg)
            CC.append(Cp)
        return CC
    else:
        dP = assemble(TrialFunction(S).dx(i)*TestFunction(DG)*dx)        
        Cp = compiled_gradient_module.compute_weighted_gradient_matrix(G, dP, dg)
        #info(G, True)        
        #info(dP, True)        
        return Cp
Exemple #7
0
 def assemble_operator_for_restriction_decorator_impl(self, term):
     original_term = restricted_term_to_original_term.get(term)
     if original_term is None:  # term was not a original term
         return assemble_operator(self, term)
     else:
         assert (term.endswith("_restricted") or term.startswith("inner_product_")
                 or term.startswith("dirichlet_bc_"))
         if term.endswith("_restricted") or term.startswith("inner_product_"):
             test_int = _to_int(self.V, test)
             trial_int = _to_int(self.V, trial)
             assert test_int is not None or trial_int is not None
             replacements = dict()
             if test_int is not None:
                 original_test = split(TestFunction(self.V))
                 original_test = original_test[test_int]
                 restricted_test = TestFunction(self.V.sub(test_int).collapse())
                 replacements[original_test] = restricted_test
             if trial_int is not None:
                 original_trial = split(TrialFunction(self.V))
                 original_trial = original_trial[trial_int]
                 restricted_trial = TrialFunction(self.V.sub(trial_int).collapse())
                 replacements[original_trial] = restricted_trial
             return tuple(replace(op, replacements) for op in assemble_operator(self, original_term))
         elif term.startswith("dirichlet_bc_"):
             assert test is None
             trial_int = _to_int(self.V, trial)
             assert trial_int is not None
             original_dirichlet_bcs = assemble_operator(self, original_term)
             restricted_dirichlet_bcs = list()
             for original_dirichlet_bc in original_dirichlet_bcs:
                 restricted_dirichlet_bc = list()
                 for original_dirichlet_bc_i in original_dirichlet_bc:
                     V = original_dirichlet_bc_i.function_space()
                     parent_V = V
                     assert hasattr(parent_V, "_root_space_after_sub")
                     while parent_V._root_space_after_sub is not None:
                         parent_V = parent_V._root_space_after_sub
                         assert hasattr(parent_V, "_root_space_after_sub")
                     V_component = [int(c) for c in V.component()]
                     assert len(V_component) >= 1
                     assert V_component[0] == trial_int
                     restricted_V = parent_V.sub(V_component[0]).collapse()
                     for c in V_component[1:]:
                         restricted_V = restricted_V.sub(c)
                     restricted_value = Constant(zeros(original_dirichlet_bc_i.value().ufl_shape))
                     args = list()
                     args.append(restricted_V)
                     args.append(restricted_value)
                     args.extend(original_dirichlet_bc_i._domain)
                     kwargs = original_dirichlet_bc_i._kwargs
                     restricted_dirichlet_bc.append(DirichletBC(*args, **kwargs))
                 assert len(restricted_dirichlet_bc) == len(original_dirichlet_bc)
                 restricted_dirichlet_bcs.append(restricted_dirichlet_bc)
             assert len(restricted_dirichlet_bcs) == len(original_dirichlet_bcs)
             return tuple(restricted_dirichlet_bcs)
Exemple #8
0
def navier_stokes_IPCS(mesh, dt, parameter):
    """
    fenics code: weak form of the problem.
    """
    mu, rho, nu = parameter
    V = VectorFunctionSpace(mesh, 'P', 2)
    Q = FunctionSpace(mesh, 'P', 1)

    bc0 = DirichletBC(V, Constant((0, 0)), cylinderwall)
    bc1 = DirichletBC(V, Constant((0, 0)), topandbottom)
    bc2 = DirichletBC(V, U0, inlet)
    bc3 = DirichletBC(Q, Constant(1), outlet)
    bcs = [bc0, bc1, bc2, bc3]

    # ds is needed to compute drag and lift. Not used here.
    ASD1 = AutoSubDomain(topandbottom)
    ASD2 = AutoSubDomain(cylinderwall)
    mf = MeshFunction("size_t", mesh, 1)
    mf.set_all(0)
    ASD1.mark(mf, 1)
    ASD2.mark(mf, 2)
    ds_ = ds(subdomain_data=mf, domain=mesh)

    vu, vp = TestFunction(V), TestFunction(Q)  # for integration
    u_, p_ = Function(V), Function(Q)  # for the solution
    u_1, p_1 = Function(V), Function(Q)  # for the prev. solution
    u, p = TrialFunction(V), TrialFunction(Q)  # unknown!
    bcu = [bcs[0], bcs[1], bcs[2]]
    bcp = [bcs[3]]

    n = FacetNormal(mesh)
    u_mid = (u + u_1) / 2.0
    F1 = rho*dot((u - u_1) / dt, vu)*dx \
        + rho*dot(dot(u_1, nabla_grad(u_1)), vu)*dx \
        + inner(sigma(u_mid, p_1, mu), epsilon(vu))*dx \
        + dot(p_1*n, vu)*ds - dot(mu*nabla_grad(u_mid)*n, vu)*ds
    a1 = lhs(F1)
    L1 = rhs(F1)
    # Define variational problem for step 2
    a2 = dot(nabla_grad(p), nabla_grad(vp)) * dx
    L2 = dot(nabla_grad(p_1), nabla_grad(vp)) * dx - (
        rho / dt) * div(u_) * vp * dx  # rho missing in FEniCS tutorial
    # Define variational problem for step 3
    a3 = dot(u, vu) * dx
    L3 = dot(u_, vu) * dx - dt * dot(nabla_grad(p_ - p_1), vu) * dx
    # Assemble matrices
    A1 = assemble(a1)
    A2 = assemble(a2)
    A3 = assemble(a3)
    # Apply boundary conditions to matrices
    [bc.apply(A1) for bc in bcu]
    [bc.apply(A2) for bc in bcp]
    return u_, p_, u_1, p_1, L1, A1, L2, A2, L3, A3, bcu, bcp
Exemple #9
0
 def __init__(self, V, Vm, bc, bcadj, \
 RHSinput=[], ObsOp=[], UD=[], Regul=[], Data=[], plot=False, \
 mycomm=None):
     # Define test, trial and all other functions
     self.trial = TrialFunction(V)
     self.test = TestFunction(V)
     self.mtrial = TrialFunction(Vm)
     self.mtest = TestFunction(Vm)
     self.rhs = Function(V)
     self.m = Function(Vm)
     self.mcopy = Function(Vm)
     self.srchdir = Function(Vm)
     self.delta_m = Function(Vm)
     self.MG = Function(Vm)
     self.MGv = self.MG.vector()
     self.Grad = Function(Vm)
     self.Gradnorm = 0.0
     self.lenm = len(self.m.vector().array())
     self.u = Function(V)
     self.ud = Function(V)
     self.diff = Function(V)
     self.p = Function(V)
     # Store other info:
     self.ObsOp = ObsOp
     self.UD = UD
     self.reset()  # Initialize U, C and E to []
     self.Data = Data
     self.GN = 1.0  # GN = 0.0 => GN Hessian; = 1.0 => full Hessian
     # Define weak forms to assemble A, C and E
     self._wkforma()
     self._wkformc()
     self._wkforme()
     # Operators and bc
     LinearOperator.__init__(self, self.delta_m.vector(), \
     self.delta_m.vector())
     self.bc = bc
     self.bcadj = bcadj
     self._assemble_solverM(Vm)
     self.assemble_A()
     self.assemble_RHS(RHSinput)
     self.Regul = Regul
     self.regparam = 1.0
     if Regul != []:
         self.PD = self.Regul.isPD()
     # Counters, tolerances and others
     self.nbPDEsolves = 0  # Updated when solve_A called
     self.nbfwdsolves = 0  # Counter for plots
     self.nbadjsolves = 0  # Counter for plots
     # MPI:
     self.mycomm = mycomm
Exemple #10
0
    def __init__(self,
                 form,
                 Space,
                 bcs=[],
                 name="x",
                 matvec=[None, None],
                 method="default",
                 solver_type="cg",
                 preconditioner_type="default"):

        Function.__init__(self, Space, name=name)
        self.form = form
        self.method = method
        self.bcs = bcs
        self.matvec = matvec
        self.trial = trial = TrialFunction(Space)
        self.test = test = TestFunction(Space)
        Mass = inner(trial, test) * dx()
        self.bf = inner(form, test) * dx()
        self.rhs = Vector(self.vector())

        if method.lower() == "default":
            self.A = A_cache[(Mass, tuple(bcs))]
            self.sol = Solver_cache[(Mass, tuple(bcs), solver_type,
                                     preconditioner_type)]

        elif method.lower() == "lumping":
            assert Space.ufl_element().degree() < 2
            self.A = A_cache[(Mass, tuple(bcs))]
            ones = Function(Space)
            ones.vector()[:] = 1.
            self.ML = self.A * ones.vector()
            self.ML.set_local(1. / self.ML.array())
 def __init__(self, Th, N):
     self.N = N
     mesh = UnitSquareMesh(Th, Th)
     self.V = FunctionSpace(mesh, "Lagrange", 1)
     u = TrialFunction(self.V)
     v = TestFunction(self.V)
     self.a = lambda k: k * inner(grad(u), grad(v)) * dx
Exemple #12
0
def mpi1d_weak_solution(V: FunctionSpace, f: Function, ft: Function,
                        fx: Function) -> (Function, Function):

    # Define trial and test functions.
    v = TrialFunction(V)
    w = TestFunction(V)

    # Define weak formulation.
    A = (v.dx(1) * w.dx(1) + v * w + (fx * v + f * v.dx(1)) *
         (fx * w + f * w.dx(1))) * dx
    b = -ft * (fx * w + f * w.dx(1)) * dx

    #    F = (v.dx(1) * w.dx(1) + v * w
    #         + (fx * v + f * v.dx(1) + ft) * (fx * w + f * w.dx(1))) * dx

    #   A = lhs(F)
    #   b = rhs(F)

    # Compute solution.
    v = Function(V)
    solve(A == b, v)

    # Compute k.
    k = project(fx * v + f * v.dx(1) + ft, V)

    return v, k
Exemple #13
0
    def __init__(self,
                 form,
                 mesh,
                 bcs=[],
                 name="CG1",
                 method={},
                 bounded=False):

        solver_type = method.get('solver_type', 'cg')
        preconditioner_type = method.get('preconditioner_type', 'default')
        solver_method = method.get('method', 'default')
        self.bounded = bounded

        Space = FunctionSpace(mesh, "CG", 1)
        OasisFunction.__init__(self,
                               form,
                               Space,
                               bcs=bcs,
                               name=name,
                               method=solver_method,
                               solver_type=solver_type,
                               preconditioner_type=preconditioner_type)

        if solver_method.lower() == "weightedaverage":
            from fenicstools import compiled_gradient_module
            DG = FunctionSpace(mesh, 'DG', 0)
            # Cannot use cache. Matrix will be modified
            self.A = assemble(TrialFunction(DG) * self.test * dx())
            self.dg = dg = Function(DG)
            compiled_gradient_module.compute_DG0_to_CG_weight_matrix(
                self.A, dg)
            self.bf_dg = inner(form, TestFunction(DG)) * dx()
Exemple #14
0
 def __init__(self, V, expression_type, basis_generation):
     self.V = V
     # Parametrized function to be interpolated
     mock_problem = MockProblem(V)
     f = ParametrizedExpression(mock_problem,
                                "0",
                                mu=(1., ),
                                element=V.ufl_element())
     #
     folder_prefix = os.path.join("test_eim_approximation_00_tempdir",
                                  expression_type, basis_generation)
     assert expression_type in ("Function", "Vector", "Matrix")
     if expression_type == "Function":
         # Call Parent constructor
         EIMApproximation.__init__(self, mock_problem,
                                   ParametrizedExpressionFactory(f),
                                   folder_prefix, basis_generation)
     elif expression_type == "Vector":
         v = TestFunction(V)
         form = f * v * dx
         # Call Parent constructor
         EIMApproximation.__init__(self, mock_problem,
                                   ParametrizedTensorFactory(form),
                                   folder_prefix, basis_generation)
     elif expression_type == "Matrix":
         u = TrialFunction(V)
         v = TestFunction(V)
         form = f * u * v * dx
         # Call Parent constructor
         EIMApproximation.__init__(self, mock_problem,
                                   ParametrizedTensorFactory(form),
                                   folder_prefix, basis_generation)
     else:  # impossible to arrive here anyway thanks to the assert
         raise AssertionError("Invalid expression_type")
Exemple #15
0
def les_update(nut_, nut_form, A_mass, At, u_, dt, bc_ksgs, bt, ksgs_sol,
               KineticEnergySGS, CG1, ksgs, delta, **NS_namespace):

    p, q = TrialFunction(CG1), TestFunction(CG1)

    Ck = KineticEnergySGS["Ck"]
    Ce = KineticEnergySGS["Ce"]

    Sij = sym(grad(u_))
    assemble(dt * inner(dot(u_, 0.5 * grad(p)), q) * dx + inner(
        (dt * Ce * sqrt(ksgs) / delta) * 0.5 * p, q) * dx +
             inner(dt * Ck * sqrt(ksgs) * delta * grad(0.5 * p), grad(q)) * dx,
             tensor=At)

    assemble(dt * 2 * Ck * delta * sqrt(ksgs) * inner(Sij, grad(u_)) * q * dx,
             tensor=bt)
    bt.axpy(1.0, A_mass * ksgs.vector())
    bt.axpy(-1.0, At * ksgs.vector())
    At.axpy(1.0, A_mass, True)

    # Solve for ksgs
    bc_ksgs.apply(At, bt)
    ksgs_sol.solve(At, ksgs.vector(), bt)
    ksgs.vector().set_local(ksgs.vector().array().clip(min=1e-7))
    ksgs.vector().apply("insert")

    # Update nut_
    nut_()
Exemple #16
0
 def __init__(self, truth_problem, expression_type, basis_generation):
     self.V = truth_problem.V
     #
     folder_prefix = os.path.join("test_eim_approximation_17_tempdir",
                                  expression_type, basis_generation)
     assert expression_type in ("Function", "Vector", "Matrix")
     if expression_type == "Function":
         # Call Parent constructor
         EIMApproximation.__init__(
             self, truth_problem,
             ParametrizedExpressionFactory(truth_problem._solution),
             folder_prefix, basis_generation)
     elif expression_type == "Vector":
         v = TestFunction(self.V)
         form = inner(truth_problem._solution, v) * dx
         # Call Parent constructor
         EIMApproximation.__init__(self, truth_problem,
                                   ParametrizedTensorFactory(form),
                                   folder_prefix, basis_generation)
     elif expression_type == "Matrix":
         u = TrialFunction(self.V)
         v = TestFunction(self.V)
         form = inner(truth_problem._solution, u) * v[0] * dx
         # Call Parent constructor
         EIMApproximation.__init__(self, truth_problem,
                                   ParametrizedTensorFactory(form),
                                   folder_prefix, basis_generation)
     else:  # impossible to arrive here anyway thanks to the assert
         raise AssertionError("Invalid expression_type")
Exemple #17
0
def test_krylov_solver_lu():

    mesh = UnitSquareMesh(MPI.comm_world, 12, 12)
    V = FunctionSpace(mesh, ("Lagrange", 1))
    u, v = TrialFunction(V), TestFunction(V)

    a = inner(u, v) * dx
    L = inner(1.0, v) * dx
    A = assemble_matrix(a)
    A.assemble()
    b = assemble_vector(L)
    b.ghostUpdate(addv=PETSc.InsertMode.ADD, mode=PETSc.ScatterMode.REVERSE)

    norm = 13.0

    solver = PETScKrylovSolver(mesh.mpi_comm())
    solver.set_options_prefix("test_lu_")
    PETScOptions.set("test_lu_ksp_type", "preonly")
    PETScOptions.set("test_lu_pc_type", "lu")
    solver.set_from_options()
    x = A.createVecRight()
    solver.set_operator(A)
    solver.solve(x, b)

    # *Tight* tolerance for LU solves
    assert round(x.norm(PETSc.NormType.N2) - norm, 12) == 0
Exemple #18
0
    def solve(self, dt):
        self.u = Function(self.V0)
        self.w = TestFunction(self.V0)
        self.du = TrialFunction(self.V0)

        x = SpatialCoordinate(self.mesh0)

        L = inner( self.S(), self.eps(self.w) )*dx(degree=4)\
        - inner( self.b, self.w )*dx(degree=4)\
        - inner( self.h, self.w )*ds(degree=4)\
        + inner( 1e-6*self.u, self.w )*ds(degree=4)\
        - inner( min_value(x[2]+self.ut[2]+self.u[2], 0) * Constant((0,0,-1.0)), self.w )*ds(degree=4)

        a = derivative(L, self.u, self.du)

        problem = NonlinearVariationalProblem(L, self.u, bcs=[], J=a)
        solver = NonlinearVariationalSolver(problem)

        solver.solve()

        self.ut.vector()[:] = self.ut.vector()[:] + self.u.vector()[:]

        ALE.move(self.mesh, Function(self.V, self.u.vector()))

        self.v.vector()[:] = self.u.vector()[:] / dt
        self.n = FacetNormal(self.mesh)
Exemple #19
0
    def __init__(self, simulation, every_timestep):
        """
        Calculate the hydrostatic pressure
        """
        self.simulation = simulation
        self.active = True
        self.every_timestep = every_timestep
        rho = simulation.data['rho']
        g = simulation.data['g']
        ph = simulation.data['p_hydrostatic']

        # Define the weak form
        Vp = ph.function_space()
        p = TrialFunction(Vp)
        q = TestFunction(Vp)
        a = dot(grad(p), grad(q)) * dx
        L = rho * dot(g, grad(q)) * dx

        self.func = ph
        self.tensor_lhs = assemble(a)
        self.form_rhs = Form(L)
        self.null_space = None
        self.solver = linear_solver_from_input(
            simulation,
            'solver/p_hydrostatic',
            default_parameters=DEFAULT_SOLVER_CONFIGURATION,
        )
Exemple #20
0
        def _change_degree(self, degree, *args, **kwargs):
            gc.collect()

            with self.global_preprocessing_time:
                logger.debug('Creating function space...')
                self._V = FunctionSpace(self._mesh, "CG", degree)
                logger.debug('Done.  Creating integration subdomains...')
                self.create_integration_subdomains()
                logger.debug('Done.  Creating test function...')
                self._v = TestFunction(self._V)
                logger.debug('Done.  Creating potential function...')
                self._potential_function = Function(self._V)
                logger.debug('Done.  Creating trial function...')
                self._potential_trial = TrialFunction(self._V)
                logger.debug('Done.  Creating LHS part of equation...')
                self._a = self._lhs()
                logger.debug('Done.  Assembling linear equation matrix...')
                self._terms_with_unknown = assemble(self._a)
                logger.debug('Done.  Defining boundary condition...')
                self._dirichlet_bc = self._boundary_condition(*args, **kwargs)
                logger.debug('Done.  Applying boundary condition to the matrix...')
                self._dirichlet_bc.apply(self._terms_with_unknown)

                logger.debug('Done.  Creating solver...')
                self._solver = KrylovSolver("cg", "ilu")
                self._solver.parameters["maximum_iterations"] = self.MAX_ITER
                self._solver.parameters["absolute_tolerance"] = 1E-8
                logger.debug('Done.  Solver created.')

            self._degree = degree
def divergence_matrix(mesh):
    CR = VectorFunctionSpace(mesh, 'CR', 1)
    DG = FunctionSpace(mesh, 'DG', 0)
    A = cg1_cr_interpolation_matrix(mesh)
    M = assemble(dot(div(TrialFunction(CR)), TestFunction(DG)) * dx())
    C = compiled_cr_module.cr_divergence_matrix(M, A, DG, CR)
    return C
 def __init__(self, mock_problem, expression_type, basis_generation):
     self.V = mock_problem.V
     # Parametrized function to be interpolated
     mu = SymbolicParameters(mock_problem, self.V, (1., ))
     x = SpatialCoordinate(self.V.mesh())
     f = (1 - x[0]) * cos(3 * pi * mu[0] * (1 + x[0])) * exp(-mu[0] *
                                                             (1 + x[0]))
     #
     folder_prefix = os.path.join("test_eim_approximation_09_tempdir",
                                  expression_type, basis_generation)
     assert expression_type in ("Function", "Vector", "Matrix")
     if expression_type == "Function":
         # Call Parent constructor
         EIMApproximation.__init__(self, mock_problem,
                                   ParametrizedExpressionFactory(f),
                                   folder_prefix, basis_generation)
     elif expression_type == "Vector":
         v = TestFunction(self.V)
         form = f * v * dx
         # Call Parent constructor
         EIMApproximation.__init__(self, mock_problem,
                                   ParametrizedTensorFactory(form),
                                   folder_prefix, basis_generation)
     elif expression_type == "Matrix":
         u = TrialFunction(self.V)
         v = TestFunction(self.V)
         form = f * u * v * dx
         # Call Parent constructor
         EIMApproximation.__init__(self, mock_problem,
                                   ParametrizedTensorFactory(form),
                                   folder_prefix, basis_generation)
     else:  # impossible to arrive here anyway thanks to the assert
         raise AssertionError("Invalid expression_type")
    def __init__(self, Th, callback_type):
        # Create mesh and define function space
        mesh = UnitSquareMesh(Th, Th)
        self.V = FunctionSpace(mesh, "Lagrange", 1)
        # Define variational problem
        du = TrialFunction(self.V)
        v = TestFunction(self.V)
        self.u = Function(self.V)
        self.r = lambda u, g: inner(grad(u), grad(v)) * dx + inner(
            u + u**3, v) * dx - g * v * dx
        self.j = lambda u, r: derivative(r, u, du)
        # Define initial guess
        self.initial_guess_expression = Expression(
            "0.1 + 0.9*x[0]*x[1]", element=self.V.ufl_element())
        # Define callback function depending on callback type
        assert callback_type in ("form callbacks", "tensor callbacks")
        if callback_type == "form callbacks":

            def callback(arg):
                return arg
        elif callback_type == "tensor callbacks":

            def callback(arg):
                return assemble(arg)

        self.callback_type = callback_type
        self.callback = callback
Exemple #24
0
def test_nullspace_check(mesh, degree):
    V = VectorFunctionSpace(mesh, ('Lagrange', degree))
    u, v = TrialFunction(V), TestFunction(V)

    mesh.geometry.coord_mapping = fem.create_coordinate_map(mesh)

    E, nu = 2.0e2, 0.3
    mu = E / (2.0 * (1.0 + nu))
    lmbda = E * nu / ((1.0 + nu) * (1.0 - 2.0 * nu))

    def sigma(w, gdim):
        return 2.0 * mu * ufl.sym(grad(w)) + lmbda * ufl.tr(
            grad(w)) * ufl.Identity(gdim)

    a = inner(sigma(u, mesh.geometry.dim), grad(v)) * dx
    zero = Function(V)
    L = inner(zero, v) * dx

    # Assemble matrix and create compatible vector
    A, L = assembling.assemble_system(a, L, [])

    # Create null space basis and test
    null_space = build_elastic_nullspace(V)
    assert null_space.in_nullspace(A, tol=1.0e-8)
    null_space.orthonormalize()
    assert null_space.in_nullspace(A, tol=1.0e-8)

    # Create incorrect null space basis and test
    null_space = build_broken_elastic_nullspace(V)
    assert not null_space.in_nullspace(A, tol=1.0e-8)
    null_space.orthonormalize()
    assert not null_space.in_nullspace(A, tol=1.0e-8)
Exemple #25
0
    def _assemble(self):
        # Get input:
        self.gamma = self.Parameters['gamma']
        if self.Parameters.has_key('beta'): self.beta = self.Parameters['beta']
        else: self.beta = 0.0
        self.Vm = self.Parameters['Vm']
        self.m0 = Function(self.Vm)
        if self.Parameters.has_key('m0'):
            setfct(self.m0, self.Parameters['m0'])
        self.mtrial = TrialFunction(self.Vm)
        self.mtest = TestFunction(self.Vm)
        self.mysample = Function(self.Vm)
        self.draw = Function(self.Vm)
        # Assemble:
        self.R = assemble(inner(nabla_grad(self.mtrial), \
        nabla_grad(self.mtest))*dx)
        self.M = assemble(inner(self.mtrial, self.mtest) * dx)

        self.Msolver = PETScKrylovSolver('cg', 'jacobi')
        self.Msolver.parameters["maximum_iterations"] = 2000
        self.Msolver.parameters["relative_tolerance"] = 1e-24
        self.Msolver.parameters["absolute_tolerance"] = 1e-24
        self.Msolver.parameters["error_on_nonconvergence"] = True
        self.Msolver.parameters["nonzero_initial_guess"] = False
        self.Msolver.set_operator(self.M)

        # preconditioner is Gamma^{-1}:
        if self.beta > 1e-10:
            self.precond = self.gamma * self.R + self.beta * self.M
        else:
            self.precond = self.gamma * self.R + (1e-10) * self.M
        # Minvprior is M.A^2 (if you use M inner-product):
        self.Minvprior = self.gamma * self.R + self.beta * self.M
Exemple #26
0
 def __init__(self, V, subdomains, expression_type, basis_generation):
     self.V = V
     # Parametrized function to be interpolated
     mock_problem = MockProblem(V)
     f = ParametrizedExpression(
         mock_problem,
         "exp( - 2*pow(x[0]-mu[0], 2) - 2*pow(x[1]-mu[1], 2) )",
         mu=(0., 0.),
         element=V.ufl_element())
     # Subdomain measure
     dx = Measure("dx")(subdomain_data=subdomains)(1)
     #
     folder_prefix = os.path.join("test_eim_approximation_04_tempdir",
                                  expression_type, basis_generation)
     assert expression_type in ("Vector", "Matrix")
     if expression_type == "Vector":
         v = TestFunction(V)
         form = f * v * dx
         # Call Parent constructor
         EIMApproximation.__init__(self, mock_problem,
                                   ParametrizedTensorFactory(form),
                                   folder_prefix, basis_generation)
     elif expression_type == "Matrix":
         u = TrialFunction(V)
         v = TestFunction(V)
         form = f * u * v * dx
         # Call Parent constructor
         EIMApproximation.__init__(self, mock_problem,
                                   ParametrizedTensorFactory(form),
                                   folder_prefix, basis_generation)
     else:  # impossible to arrive here anyway thanks to the assert
         raise AssertionError("Invalid expression_type")
Exemple #27
0
 def __init__(self, V, **kwargs):
     # Call parent
     ParametrizedProblem.__init__(
         self,
         os.path.join("test_eim_approximation_17_tempdir",
                      expression_type, basis_generation,
                      "mock_problem"))
     # Minimal subset of a ParametrizedDifferentialProblem
     self.V = V
     self._solution = Function(V)
     self.components = ["u", "s", "p"]
     # Parametrized function to be interpolated
     x = SpatialCoordinate(V.mesh())
     mu = SymbolicParameters(self, V, (-1., -1.))
     self.f00 = 1. / sqrt(
         pow(x[0] - mu[0], 2) + pow(x[1] - mu[1], 2) + 0.01)
     self.f01 = 1. / sqrt(
         pow(x[0] - mu[0], 4) + pow(x[1] - mu[1], 4) + 0.01)
     # Inner product
     f = TrialFunction(self.V)
     g = TestFunction(self.V)
     self.inner_product = assemble(inner(f, g) * dx)
     # Collapsed vector and space
     self.V0 = V.sub(0).collapse()
     self.V00 = V.sub(0).sub(0).collapse()
     self.V1 = V.sub(1).collapse()
Exemple #28
0
 def __init__(self, V, expression_type, basis_generation):
     self.V = V
     # Parametrized function to be interpolated
     mock_problem = MockProblem(V)
     f_expression = (
         ("1/sqrt(pow(x[0]-mu[0], 2) + pow(x[1]-mu[1], 2) + 0.01)",
          "exp( - 2*pow(x[0]-mu[0], 2) - 2*pow(x[1]-mu[1], 2) )"),
         ("10.*(1-x[0])*cos(3*pi*(pi+mu[1])*(1+x[1]))*exp(-(pi+mu[0])*(1+x[0]))",
          "sqrt(pow(x[0]-mu[0], 2) + pow(x[1]-mu[1], 2) + 0.01)")
     )
     tensor_element = TensorElement(V.sub(0).ufl_element())
     f = ParametrizedExpression(mock_problem, f_expression, mu=(-1., -1.), element=tensor_element)
     #
     folder_prefix = os.path.join("test_eim_approximation_07_tempdir", expression_type, basis_generation)
     assert expression_type in ("Function", "Vector", "Matrix")
     if expression_type == "Function":
         # Call Parent constructor
         EIMApproximation.__init__(
             self, mock_problem, ParametrizedExpressionFactory(f), folder_prefix, basis_generation)
     elif expression_type == "Vector":
         v = TestFunction(V)
         form = inner(f, grad(v)) * dx
         # Call Parent constructor
         EIMApproximation.__init__(
             self, mock_problem, ParametrizedTensorFactory(form), folder_prefix, basis_generation)
     elif expression_type == "Matrix":
         u = TrialFunction(V)
         v = TestFunction(V)
         form = inner(grad(u) * f, grad(v)) * dx
         # Call Parent constructor
         EIMApproximation.__init__(
             self, mock_problem, ParametrizedTensorFactory(form), folder_prefix, basis_generation)
     else:  # impossible to arrive here anyway thanks to the assert
         raise AssertionError("Invalid expression_type")
def test_lhs_rhs_simple():
    """Test taking lhs/rhs of DOLFIN specific forms (constants
    without cell). """

    mesh = RectangleMesh(MPI.comm_world, [numpy.array([0.0, 0.0, 0.0]),
                                          numpy.array([2.0, 1.0, 0.0])],
                         [3, 5], CellType.triangle)
    V = FunctionSpace(mesh, "CG", 1)
    f = 2.0
    g = 3.0
    v = TestFunction(V)
    u = TrialFunction(V)

    F = inner(g * grad(f * v), grad(u)) * dx + f * v * dx
    a, L = system(F)

    Fl = lhs(F)
    Fr = rhs(F)
    assert(Fr)

    a0 = inner(grad(v), grad(u)) * dx

    n = assemble(a).norm("frobenius")  # noqa
    nl = assemble(Fl).norm("frobenius")  # noqa
    n0 = 6.0 * assemble(a0).norm("frobenius")  # noqa

    assert round(n - n0, 7) == 0
    assert round(n - nl, 7) == 0
Exemple #30
0
def test_local_assembler_1D():
    mesh = UnitIntervalMesh(MPI.comm_world, 20)
    V = FunctionSpace(mesh, 'CG', 1)
    u = TrialFunction(V)
    v = TestFunction(V)
    c = Cell(mesh, 0)

    a_scalar = 1.0 * dx(domain=mesh)
    a_vector = v * dx
    a_matrix = u * v * dx

    A_scalar = assemble_local(a_scalar, c)
    A_vector = assemble_local(a_vector, c)
    A_matrix = assemble_local(a_matrix, c)

    assert isinstance(A_scalar, float)
    assert numpy.isclose(A_scalar, 0.05)

    assert isinstance(A_vector, numpy.ndarray)
    assert A_vector.shape == (2,)
    assert numpy.isclose(A_vector[0], 0.025)
    assert numpy.isclose(A_vector[1], 0.025)

    assert isinstance(A_matrix, numpy.ndarray)
    assert A_matrix.shape == (2, 2)
    assert numpy.isclose(A_matrix[0, 0], 1 / 60)
    assert numpy.isclose(A_matrix[0, 1], 1 / 120)
    assert numpy.isclose(A_matrix[1, 0], 1 / 120)
    assert numpy.isclose(A_matrix[1, 1], 1 / 60)