Exemplo n.º 1
0
    def test_cms1dl2_exp_pb(self):
        # Define temporal and spatial sample points.
        m, n = 10, 20

        # Create constant image sequence.
        f = Constant(1.0)
        fd = Constant(0.0)

        # Compute velocity.
        v, k, res, fun = cms1dl2_exp_pb(m, n, f, fd, fd, 1.0, 1.0, 1.0)

        np.testing.assert_allclose(v.shape, (m, n))
        np.testing.assert_allclose(v, np.zeros_like(v))
        np.testing.assert_allclose(k.shape, (m, n))
        np.testing.assert_allclose(k, np.zeros_like(k))
Exemplo n.º 2
0
    def __init__(self, problem, parameters={}, lb=None):
        super(DamageSolverSNES, self).__init__()
        self.problem = problem
        self.energy = problem.energy
        self.state = problem.state
        self.alpha = problem.state['alpha']
        self.alpha_dvec = as_backend_type(self.alpha.vector())
        self.alpha_pvec = self.alpha_dvec.vec()

        self.bcs = problem.bcs
        self.parameters = parameters
        comm = self.alpha.function_space().mesh().mpi_comm()
        self.comm = comm
        V = self.alpha.function_space()
        self.V = V
        self.Ealpha = derivative(
            self.energy, self.alpha,
            dolfin.TestFunction(self.alpha.ufl_function_space()))
        self.dm = self.alpha.function_space().dofmap()
        solver = PETScSNESSolver()
        snes = solver.snes()

        if lb == None:
            lb = interpolate(Constant(0.), V)
        ub = interpolate(Constant(1.), V)

        prefix = "damage_"
        snes.setOptionsPrefix(prefix)
        for option, value in self.parameters["snes"].items():
            PETScOptions.set(prefix + option, value)
            log(LogLevel.DEBUG,
                "DEBUG: Set: {} = {}".format(prefix + option, value))

        snes.setFromOptions()

        (J, F, bcs_alpha) = (problem.J, problem.F, problem.bcs)
        self.ass = SystemAssembler(J, F, bcs_alpha)
        self.b = self.init_residual()
        snes.setFunction(self.residual, self.b.vec())
        self.A = self.init_jacobian()
        snes.setJacobian(self.jacobian, self.A.mat())
        snes.ksp.setOperators(self.A.mat())

        snes.setVariableBounds(self.problem.lb.vec(), self.problem.ub.vec())  #

        # snes.solve(None, Function(V).vector().vec())

        self.solver = snes
Exemplo n.º 3
0
    def amg_solve(N, method):
        # Elasticity parameters
        E = 1.0e9
        nu = 0.3
        mu = E / (2.0 * (1.0 + nu))
        lmbda = E * nu / ((1.0 + nu) * (1.0 - 2.0 * nu))

        # Stress computation
        def sigma(v):
            return 2.0 * mu * sym(grad(v)) + lmbda * tr(sym(
                grad(v))) * Identity(2)

        # Define problem
        mesh = UnitSquareMesh(MPI.comm_world, N, N)
        V = VectorFunctionSpace(mesh, 'Lagrange', 1)
        bc = DirichletBC(V, Constant((0.0, 0.0)),
                         lambda x, on_boundary: on_boundary)
        u = TrialFunction(V)
        v = TestFunction(V)

        # Forms
        a, L = inner(sigma(u), grad(v)) * dx, dot(Constant((1.0, 1.0)), v) * dx

        # Assemble linear algebra objects
        A, b = assemble_system(a, L, bc)

        # Create solution function
        u = Function(V)

        # Create near null space basis and orthonormalize
        null_space = build_nullspace(V, u.vector())

        # Attached near-null space to matrix
        A.set_near_nullspace(null_space)

        # Test that basis is orthonormal
        assert null_space.is_orthonormal()

        # Create PETSC smoothed aggregation AMG preconditioner, and
        # create CG solver
        #        pc = PETScPreconditioner(method)
        solver = PETScKrylovSolver("cg", method)

        # Set matrix operator
        solver.set_operator(A)

        # Compute solution and return number of iterations
        return solver.solve(u.vector(), b)
Exemplo n.º 4
0
    def calculate_penalties(self):
        """
        Calculate SIPG penalty
        """
        mesh = self.simulation.data['mesh']
        P = self.simulation.data['Vp'].ufl_element().degree()
        rho_min, rho_max = self.simulation.multi_phase_model.get_density_range()
        k_min = 1.0 / rho_max
        k_max = 1.0 / rho_min
        penalty_dS = define_penalty(mesh, P, k_min, k_max, boost_factor=3, exponent=1.0)
        penalty_ds = penalty_dS * 2
        self.simulation.log.info(
            '    DG SIP penalty pressure:  dS %.1f  ds %.1f' % (penalty_dS, penalty_ds)
        )

        return Constant(penalty_dS), Constant(penalty_ds)
Exemplo n.º 5
0
def test_multi_ps_vector(mesh):
    """Tests point source PointSource(V, source) for mulitple point
    sources applied to a vector for 1D, 2D and 3D. Global points given
    to constructor from rank 0 processor.

    """

    c_ids = [0, 1, 2]
    rank = MPI.rank(mesh.mpi_comm())
    V = FunctionSpace(mesh, "CG", 1)
    v = TestFunction(V)
    b = assemble(Constant(0.0) * v * dx)

    source = []
    if rank == 0:
        for c_id in c_ids:
            cell = Cell(mesh, c_id)
            point = cell.midpoint()
            source.append((point, 10.0))
    ps = PointSource(V, source)
    ps.apply(b)

    # Checks b sums to correct value
    b_sum = b.sum()
    assert round(b_sum - len(c_ids) * 10.0) == 0
Exemplo n.º 6
0
    def __init__(self, mesh, FuncSpace_dict, beta_map=Constant(1e-6), ds=ds):
        """
        Instantiate FormsPDEMap

        Parameters
        ----------
        mesh: dolfin.Mesh
            Dolfin Mesh
        FuncSpace_dict: dict
            Dictionary containing the function space definitions. Following keys are required:
                - FuncSpace_local: function space for local variable
                - FuncSpace_lambda: function space for Lagrange multiplier
                - FuncSpace_bar: function space for control variable
        beta_map: dolfin.Constant, optional
            Penalty/Regularizatio term to establish coupling between local unknown and control.
            Defaults to Constant(1e-6)
        ds: dolfin.Measure, optional
            ds Measure of mesh
        """

        self.W = FuncSpace_dict["FuncSpace_local"]
        self.T = FuncSpace_dict["FuncSpace_lambda"]
        self.Wbar = FuncSpace_dict["FuncSpace_bar"]

        self.n = FacetNormal(mesh)
        self.beta_map = beta_map
        self.ds = ds
        self.gdim = mesh.geometry().dim()
Exemplo n.º 7
0
    def set_form(self, form):
        """
        This function is called by simulator.set_form to set up the equations
        for the electric field. This function will add an equation that
        sets the field to zero everywhere.

        Args:
            form: A FEniCS variational form.
        """
        # first set rho (not used in calculations for this potential)
        F = Constant(self.simulator.F)
        rho = Function(self.simulator.geometry.V)
        for ion in self.simulator.ion_list:
            rho += F * ion.z * ion.c_new
        self.rho = rho

        # update variational form
        v, d = self.simulator.v_phi, self.simulator.d_phi
        form += (inner(nabla_grad(self.phi_new), nabla_grad(v)) +
                 self.dummy_new * v + self.phi_new * d) * dx

        v, d = self.simulator.v_phi_ps, self.simulator.d_phi_ps
        form += (inner(nabla_grad(self.phi_ps_new), nabla_grad(v)) +
                 self.phi_ps_new * d + v * self.dummy_ps_new) * dx

        return form
Exemplo n.º 8
0
 def assemble_solution(self, t):  # returns
     """
     :param t: time
     :return: Womersley flow (analytic solution) at time t
     analytic solution at any time is a steady parabolic flow + linear combination of 8 modes
     modes were precomputed as 8 functions on given mesh and stored in hdf5 file
     """
     if self.tc is not None:
         self.tc.start('assembleSol')
     sol = Function(self.solutionSpace)
     # analytic solution has zero x and y components
     dofs2 = self.solutionSpace.sub(2).dofmap().dofs(
     )  # gives field of indices corresponding to z axis
     sol.assign(Constant(("0.0", "0.0", "0.0")))  # QQ not needed
     sol.vector()[dofs2] += self.factor * self.bessel_parabolic.vector(
     ).array()  # parabolic part of sol
     for idx in range(8):  # add modes of Womersley sol
         sol.vector()[dofs2] += self.factor * cos(
             self.coefs_exp[idx] * pi *
             t) * self.bessel_real[idx].vector().array()
         sol.vector()[dofs2] += self.factor * -sin(
             self.coefs_exp[idx] * pi *
             t) * self.bessel_complex[idx].vector().array()
     if self.tc is not None:
         self.tc.end('assembleSol')
     return sol
Exemplo n.º 9
0
    def test_cmscr1d_weak_solution_zero_Dirichlet(self):
        print("Running test 'test_cmscr1d_weak_solution_zero_Dirichlet'")
        # Define temporal and spatial sample points.
        m, n = 10, 20

        # Define mesh and function space.
        mesh = UnitSquareMesh(m - 1, n - 1)
        V = dh.create_function_space(mesh, 'default')
        W = dh.create_vector_function_space(mesh, 'default')

        # Define boundary conditions for velocity.
        bc = DirichletBC(W.sub(0), Constant(0), dh.DirichletBoundary())

        # Create zero function.
        f = Function(V)

        # Compute velocity.
        v, k, res, fun, converged = cmscr1d_weak_solution(W, f,
                                                          f.dx(0), f.dx(1),
                                                          1.0, 1.0,
                                                          1.0, 1.0, 1.0,
                                                          bcs=bc)
        v = v.vector().get_local()
        k = k.vector().get_local()

        np.testing.assert_allclose(v.shape, m * n)
        np.testing.assert_allclose(v, np.zeros_like(v))
        np.testing.assert_allclose(k.shape, m * n)
        np.testing.assert_allclose(k, np.zeros_like(k))
Exemplo n.º 10
0
def structure_setup(d_, v_, phi, psi, n, rho_s, \
            dx, mu_s, lamda_s, k, mesh_file, theta, **semimp_namespace):

    delta = 1E10

    F_solid_linear = rho_s/k*inner(v_["n"] - v_["n-1"], psi)*dx \
                   + delta*(1.0/k)*inner(d_["n"] - d_["n-1"], phi)*dx \
           - delta*inner(Constant(theta)*v_["n"] + Constant(1 - theta)*v_["n-1"], phi)*dx

    gravity = Constant((0, -2 * rho_s))
    F_solid_linear -= inner(gravity, psi) * dx

    F_solid_nonlinear = Constant(theta)*inner(Piola1(d_["n"], lamda_s, mu_s), grad(psi))*dx +\
    Constant(1 - theta)*inner(Piola1(d_["n-1"], lamda_s, mu_s), grad(psi))*dx
    return dict(F_solid_linear=F_solid_linear,
                F_solid_nonlinear=F_solid_nonlinear)
Exemplo n.º 11
0
    def __init__(self, eps=0.01):

        # Time horizon
        self.T = [0., 1.0]
        self.t = Constant(self.T[1])
        self.eps = eps
        self.timeDependentCoefs = True
Exemplo n.º 12
0
def structure_setup(d_, v_, p_, phi, psi, gamma, dS, mu_f, n,\
            dx_s, dx_f, mu_s, rho_s, lamda_s, k, mesh_file, theta, g, **semimp_namespace):

    delta = 1E10


    F_solid_linear = rho_s/k*inner(v_["n"] - v_["n-1"], psi)*dx_s \
           + delta*(1/k)*inner(d_["n"] - d_["n-1"], phi)*dx_s \
    		   - delta*inner(Constant(theta)*v_["n"] + Constant(1 - theta)*v_["n-1"], phi)*dx_s \

    gravity = Constant((0, -g*rho_s))
    F_solid_linear -= inner(gravity, psi)*dx_s

    F_solid_nonlinear = inner(Piola1(Constant(theta)*d_["n"] + Constant(1 - theta)*d_["n-1"], lamda_s, mu_s), grad(psi))*dx_s

    return dict(F_solid_linear = F_solid_linear, F_solid_nonlinear = F_solid_nonlinear)
Exemplo n.º 13
0
def test_krylov_solver_options_prefix(pushpop_parameters):
    "Test set/get PETScKrylov solver prefix option"

    # Set backend
    parameters["linear_algebra_backend"] = "PETSc"

    # Prefix
    prefix = "test_foo_"

    # Create solver and set prefix
    solver = PETScKrylovSolver()
    solver.set_options_prefix(prefix)

    # Check prefix (pre solve)
    assert solver.get_options_prefix() == prefix

    # Solve a system of equations
    mesh = UnitSquareMesh(4, 4)
    V = FunctionSpace(mesh, "Lagrange", 1)
    u, v = TrialFunction(V), TestFunction(V)
    a, L = u*v*dx, Constant(1.0)*v*dx
    A, b = assemble(a), assemble(L)
    solver.set_operator(A)
    solver.solve(b.copy(), b)

    # Check prefix (post solve)
    assert solver.get_options_prefix() == prefix
Exemplo n.º 14
0
def test_krylov_solver_norm_type():
    """Check setting of norm type used in testing for convergence by
    PETScKrylovSolver

    """

    norm_type = (PETScKrylovSolver.norm_type_default_norm,
                 PETScKrylovSolver.norm_type_natural,
                 PETScKrylovSolver.norm_type_preconditioned,
                 PETScKrylovSolver.norm_type_none,
                 PETScKrylovSolver.norm_type_unpreconditioned)

    for norm in norm_type:
        # Solve a system of equations
        mesh = UnitSquareMesh(4, 4)
        V = FunctionSpace(mesh, "Lagrange", 1)
        u, v = TrialFunction(V), TestFunction(V)
        a = u*v*dx
        L = Constant(1.0)*v*dx
        A, b = assemble(a), assemble(L)

        solver = PETScKrylovSolver("cg")
        solver.parameters["maximum_iterations"] = 2
        solver.parameters["error_on_nonconvergence"] = False
        solver.set_norm_type(norm)
        solver.set_operator(A)
        solver.solve(b.copy(), b)
        solver.get_norm_type()

        if norm is not PETScKrylovSolver.norm_type_default_norm:
            assert solver.get_norm_type() == norm
Exemplo n.º 15
0
def bulk_electrostriction(E, e_r, p, direction, q_b):
    """ calculate the bulk electrostriction force """
    pp = as_matrix(p)  # photoelestic tensor is stored as as numpy array
    if direction == 'backward':
        EE_6vec_r = as_vector([
            E[0] * E[0], E[1] * E[1], -E[2] * E[2], 0.0, 0.0, 2.0 * E[0] * E[1]
        ])
        EE_6vec_i = as_vector(
            [0.0, 0.0, 0.0, 2.0 * E[1] * E[2], 2.0 * E[0] * E[2], 0.0])
        sigma_r = -0.5 * epsilon_0 * e_r**2 * pp * EE_6vec_r
        sigma_i = -0.5 * epsilon_0 * e_r**2 * pp * EE_6vec_i
        f_r = f_elst_r(sigma_r, sigma_i, q_b)
        f_i = f_elst_i(sigma_r, sigma_i, q_b)

    elif direction == 'forward':
        EE_6vec_r = as_vector([
            E[0] * E[0], E[1] * E[1], E[2] * E[2], 0.0, 0.0, 2.0 * E[0] * E[1]
        ])
        # EE_6vec_i, sigma_i, q_b is zero
        sigma_r = -0.5 * epsilon_0 * e_r**2 * pp * EE_6vec_r
        # no need to multiply zeros ...
        f_r = as_vector([
            -Dx(sigma_r[0], 0) - Dx(sigma_r[5], 1),
            -Dx(sigma_r[5], 0) - Dx(sigma_r[1], 1),
            -Dx(sigma_r[4], 0) - Dx(sigma_r[3], 1)
        ])
        f_i = Constant((0.0, 0.0, 0.0), cell=triangle)
        #f_i = as_vector([ - q_b*sigma_r[4],- q_b*sigma_r[3],- q_b*sigma_r[2]])

    else:
        raise ValueError('Specify scattering direction as forward or backward')

    return (f_r, f_i)
Exemplo n.º 16
0
def test_pointsource_vector_fs(mesh, point):
    """Tests point source when given constructor PointSource(V, point,
    mag) with a vector for a vector function space that isn't placed
    at a node for 1D, 2D and 3D. Global points given to constructor
    from rank 0 processor.

    """

    rank = MPI.rank(mesh.mpi_comm())
    V = VectorFunctionSpace(mesh, "CG", 1)
    v = TestFunction(V)
    b = assemble(dot(Constant([0.0] * mesh.geometry().dim()), v) * dx)
    if rank == 0:
        ps = PointSource(V, point, 10.0)
    else:
        ps = PointSource(V, [])
    ps.apply(b)

    # Checks array sums to correct value
    b_sum = b.sum()
    assert round(b_sum - 10.0 * V.num_sub_spaces()) == 0

    # Checks point source is added to correct part of the array
    v2d = vertex_to_dof_map(V)
    for v in vertices(mesh):
        if near(v.midpoint().distance(point), 0.0):
            for spc_idx in range(V.num_sub_spaces()):
                ind = v2d[v.index() * V.num_sub_spaces() + spc_idx]
                if ind < len(b.get_local()):
                    assert np.round(b.get_local()[ind] - 10.0) == 0
Exemplo n.º 17
0
def test_multi_ps_matrix(mesh):
    """Tests point source PointSource(V, source) for mulitple point
    sources applied to a matrix for 1D, 2D and 3D. Global points given
    to constructor from rank 0 processor.

    """

    c_ids = [0, 1, 2]
    rank = MPI.rank(mesh.mpi_comm())
    V = VectorFunctionSpace(mesh, "CG", 1, dim=2)
    u, v = TrialFunction(V), TestFunction(V)
    A = assemble(Constant(0.0) * dot(u, v) * dx)

    source = []
    if rank == 0:
        for c_id in c_ids:
            cell = Cell(mesh, c_id)
            point = cell.midpoint()
            source.append((point, 10.0))
    ps = PointSource(V, source)
    ps.apply(A)

    # Checks b sums to correct value
    a_sum = MPI.sum(mesh.mpi_comm(), np.sum(A.array()))
    assert round(a_sum - 2 * len(c_ids) * 10) == 0
Exemplo n.º 18
0
 def initialize(self, warp, istart):
     self.istart = istart
     for i in xrange(istart, istart + self.N):
         rad = 0.0
         ist = 0
         for n, d in zip(self.Ns, self.Dias):
             for j in xrange(n):
                 print j
                 fib = warp.fibrils[i * np.sum(self.Ns) + ist]
                 qhh = Geometry_Curves.qhh_stockinette2
                 temp_field = Function(fib.problem.spaces['V'])
                 p1 = rad * np.cos(2.0 * np.pi * float(j) / float(n))
                 p2 = rad * np.sin(2.0 * np.pi * float(j) / float(n))
                 for fix in xrange(3):
                     temp_field.interpolate(
                         Expression(qhh[fix],
                                    sq=-(self.restL - self.setL) /
                                    self.restL,
                                    p=np.pi / self.restL * (4.0),
                                    o=self.setL / 3.5,
                                    A1=1.3 * self.width / self.N,
                                    A2=self.width / self.N,
                                    y1=p1,
                                    y2=p2))
                     assign(fib.problem.fields['wx'].sub(fix), temp_field)
                     temp_field.interpolate(Constant((0.0, 0.0, 0.0)))
                     assign(fib.problem.fields['wv'].sub(fix), temp_field)
                 ist += 1
             rad += d
Exemplo n.º 19
0
 def _boundary_flux(self):
     f = self._fm.function()
     f.interpolate(self._base_potential_gradient_normal_expression)
     return assemble(
         sum(
             Constant(c) * f * self._ds(s)
             for s, c in self.BOUNDARY_CONDUCTIVITY))
Exemplo n.º 20
0
    def __init__(self, simulation):
        """
        A Navier-Stokes coupled solver based on the LDG scheme

        :type simulation: ocellaris.Simulation
        """
        self.simulation = sim = simulation
        self.read_input()
        self.create_functions()

        # First time step timestepping coefficients
        self.set_timestepping_coefficients([1, -1, 0])

        # Solver control parameters
        sim.data['dt'] = Constant(simulation.dt)

        # Create equation
        self.eqs = CoupledEquationsLDG(simulation)

        # Velocity post_processing
        self.velocity_postprocessor = None
        if self.velocity_postprocessing_method == BDM:
            self.velocity_postprocessor = VelocityBDMProjection(
                sim, sim.data['u'])

        if self.fix_pressure_dof:
            pdof = get_global_row_number(self.subspaces[sim.ndim])
            self.pressure_row_to_fix = numpy.array([pdof], dtype=numpy.intc)

        # Store number of iterations
        self.niters = None
Exemplo n.º 21
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 = mesh.geometry.dim * (0.0, )
    L = inner(Constant(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)
Exemplo n.º 22
0
def les_setup(u_, mesh, KineticEnergySGS, assemble_matrix, CG1Function,
              nut_krylov_solver, bcs, **NS_namespace):
    """
    Set up for solving the Kinetic Energy SGS-model.
    """
    DG = FunctionSpace(mesh, "DG", 0)
    CG1 = FunctionSpace(mesh, "CG", 1)
    dim = mesh.geometry().dim()
    delta = Function(DG)
    delta.vector().zero()
    delta.vector().axpy(1.0, assemble(TestFunction(DG) * dx))
    delta.vector().set_local(delta.vector().array()**(1. / dim))
    delta.vector().apply('insert')

    Ck = KineticEnergySGS["Ck"]
    ksgs = interpolate(Constant(1E-7), CG1)
    bc_ksgs = DirichletBC(CG1, 0, "on_boundary")
    A_mass = assemble_matrix(TrialFunction(CG1) * TestFunction(CG1) * dx)
    nut_form = Ck * delta * sqrt(ksgs)
    bcs_nut = derived_bcs(CG1, bcs['u0'], u_)
    nut_ = CG1Function(nut_form,
                       mesh,
                       method=nut_krylov_solver,
                       bcs=bcs_nut,
                       bounded=True,
                       name="nut")
    At = Matrix()
    bt = Vector(nut_.vector())
    ksgs_sol = KrylovSolver("bicgstab", "additive_schwarz")
    #ksgs_sol.parameters["preconditioner"]["structure"] = "same_nonzero_pattern"
    ksgs_sol.parameters["error_on_nonconvergence"] = False
    ksgs_sol.parameters["monitor_convergence"] = False
    ksgs_sol.parameters["report"] = False
    del NS_namespace
    return locals()
Exemplo n.º 23
0
 def _boundary_condition(self, *args, **kwargs):
     return DirichletBC(
         self._V,
         Constant(
             self.potential_behind_dome(self.RADIUS, *args,
                                        **kwargs)),
         self._boundaries, self.EXTERNAL_SURFACE)
Exemplo n.º 24
0
    def __new__(cls, mesh, tolerance=1e-12):
        dim = mesh.geometry().dim()
        X = MeshPool._X[dim - 1]

        test = assemble(dot(X, X) * CellVolume(mesh)**(0.25) *
                        dx()) * assemble(Constant(1) * dx(domain=mesh))
        assert test > 0.0
        assert test < np.inf

        # Do a garbage collect to collect any garbage references
        # Needed for full parallel compatibility
        gc.collect()
        keys = np.array(MeshPool._existing.keys())
        self = None
        if len(keys) > 0:
            diff = np.abs(keys - test) / np.abs(test)
            idx = np.argmin(np.abs(keys - test))

            if diff[idx] <= tolerance and isinstance(
                    mesh, type(MeshPool._existing[keys[idx]])):
                self = MeshPool._existing[keys[idx]]

        if self is None:
            self = mesh
            MeshPool._existing[test] = self
        return self
Exemplo n.º 25
0
def get_distance_function(config, domains):
    V = dolfin.FunctionSpace(config.domain.mesh, "CG", 1)
    v = dolfin.TestFunction(V)
    d = dolfin.TrialFunction(V)
    sol = dolfin.Function(V)
    s = dolfin.interpolate(Constant(1.0), V)
    domains_func = dolfin.Function(dolfin.FunctionSpace(config.domain.mesh, "DG", 0))
    domains_func.vector().set_local(domains.array().astype(numpy.float))

    def boundary(x):
        eps_x = config.params["turbine_x"]
        eps_y = config.params["turbine_y"]

        min_val = 1
        for e_x, e_y in [(-eps_x, 0), (eps_x, 0), (0, -eps_y), (0, eps_y)]:
            try:
                min_val = min(min_val, domains_func((x[0] + e_x, x[1] + e_y)))
            except RuntimeError:
                pass

        return min_val == 1.0

    bc = dolfin.DirichletBC(V, 0.0, boundary)

    # Solve the diffusion problem with a constant source term
    log(INFO, "Solving diffusion problem to identify feasible area ...")
    a = dolfin.inner(dolfin.grad(d), dolfin.grad(v)) * dolfin.dx
    L = dolfin.inner(s, v) * dolfin.dx
    dolfin.solve(a == L, sol, bc)

    return sol
Exemplo n.º 26
0
    def __init__(self, V, kappa):
        '''
        Parameters
        ----------
        V : dolfin.FunctionSpace
            Function space.
        kappa : float
            Filter diffusivity constant.

        '''

        if not isinstance(V, dolfin.FunctionSpace):
            raise TypeError(
                'Parameter `V` must be of type `dolfin.FunctionSpace`.')

        v = dolfin.TestFunction(V)
        f = dolfin.TrialFunction(V)

        x = V.mesh().coordinates()
        l = (x.max(0) - x.min(0)).min()
        k = Constant(float(kappa) * l**2)

        a_M = f * v * dx
        a_D = k * dot(grad(f), grad(v)) * dx

        A = assemble(a_M + a_D)
        self._M = assemble(a_M)

        self.solver = dolfin.LUSolver(A, "mumps")
        self.solver.parameters["symmetric"] = True
Exemplo n.º 27
0
 def _assemble_operator_for_stability_factor_impl(self_, term):
     if term == "stability_factor_left_hand_matrix":
         return tuple(f + adjoint(f) for f in assemble_operator(self_, "a"))
     elif term == "stability_factor_right_hand_matrix":
         return assemble_operator(self_, "inner_product")
     elif term == "stability_factor_dirichlet_bc":
         original_dirichlet_bcs = assemble_operator(self_, "dirichlet_bc")
         zeroed_dirichlet_bcs = list()
         for original_dirichlet_bc in original_dirichlet_bcs:
             zeroed_dirichlet_bc = list()
             for original_dirichlet_bc_i in original_dirichlet_bc:
                 args = list()
                 args.append(original_dirichlet_bc_i.function_space())
                 zero_value = Constant(
                     zeros(original_dirichlet_bc_i.value().ufl_shape))
                 args.append(zero_value)
                 args.extend(original_dirichlet_bc_i._domain)
                 kwargs = original_dirichlet_bc_i._kwargs
                 zeroed_dirichlet_bc.append(DirichletBC(*args, **kwargs))
             assert len(zeroed_dirichlet_bc) == len(original_dirichlet_bc)
             zeroed_dirichlet_bcs.append(zeroed_dirichlet_bc)
         assert len(zeroed_dirichlet_bcs) == len(original_dirichlet_bcs)
         return tuple(zeroed_dirichlet_bcs)
     else:
         return assemble_operator(self_, term)
Exemplo n.º 28
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)
Exemplo n.º 29
0
def test_closed_boundary(advection_scheme):
    # FIXME: rk3 scheme does not bounces off the wall properly
    xmin, xmax = 0., 1.
    ymin, ymax = 0., 1.

    mesh = RectangleMesh(Point(xmin, ymin), Point(xmax, ymax), 10, 10)

    # Particle
    x = np.array([[0.975, 0.475]])

    # Given velocity field:
    vexpr = Constant((1., 0.))
    # Given time do_step:
    dt = 0.05
    # Then bounced position is
    x_bounced = np.array([[0.975, 0.475]])

    p = particles(x, [x, x], mesh)

    V = VectorFunctionSpace(mesh, "CG", 1)
    v = Function(V)
    v.assign(vexpr)

    # Different boundary parts
    bound_left = UnitSquareLeft()
    bound_right = UnitSquareRight()
    bound_top = UnitSquareTop()
    bound_bottom = UnitSquareBottom()

    # Mark all facets
    facet_marker = MeshFunction('size_t', mesh, mesh.topology().dim() - 1)
    facet_marker.set_all(0)

    # Mark as closed
    bound_right.mark(facet_marker, 1)

    # Mark other boundaries as open
    bound_left.mark(facet_marker, 2)
    bound_top.mark(facet_marker, 2)
    bound_bottom.mark(facet_marker, 2)

    if advection_scheme == 'euler':
        ap = advect_particles(p, V, v, facet_marker)
    elif advection_scheme == 'rk2':
        ap = advect_rk2(p, V, v, facet_marker)
    elif advection_scheme == 'rk3':
        ap = advect_rk3(p, V, v, facet_marker)
    else:
        assert False

    # Do one timestep, particle must bounce from wall of
    ap.do_step(dt)
    xpE = p.positions()

    # Check if particle correctly bounced off from closed wall
    xpE_root = comm.gather(xpE, root=0)
    if comm.rank == 0:
        xpE_root = np.float64(np.vstack(xpE_root))
        error = np.linalg.norm(x_bounced - xpE_root)
        assert(error < 1e-10)
Exemplo n.º 30
0
def test_pointsource_matrix_second_constructor(mesh, point):
    """Tests point source when given different constructor PointSource(V1,
    V2, point, mag) with a matrix and when placed at a node for 1D, 2D
    and 3D. Global points given to constructor from rank 0
    processor. Currently only implemented if V1=V2.

    """

    V1 = FunctionSpace(mesh, "CG", 1)
    V2 = FunctionSpace(mesh, "CG", 1)

    rank = MPI.rank(mesh.mpi_comm())
    u, v = TrialFunction(V1), TestFunction(V2)
    w = Function(V1)
    A = assemble(Constant(0.0) * u * v * dx)
    if rank == 0:
        ps = PointSource(V1, V2, point, 10.0)
    else:
        ps = PointSource(V1, V2, [])
    ps.apply(A)

    # Checks array sums to correct value
    a_sum = MPI.sum(mesh.mpi_comm(), np.sum(A.array()))
    assert round(a_sum - 10.0) == 0

    # Checks point source is added to correct part of the array
    A.get_diagonal(w.vector())
    v2d = vertex_to_dof_map(V1)
    for v in vertices(mesh):
        if near(v.midpoint().distance(point), 0.0):
            ind = v2d[v.index()]
            if ind < len(A.array()):
                assert np.round(w.vector()[ind] - 10.0) == 0