Exemple #1
0
def macrospin(Ms=0.86e6,
              m_init=(1, 0, 0),
              H_ext=(0, 0, 1e6),
              alpha=0.1,
              name='macrospin'):
    """
    Minimal mesh with two vertices (1 nm apart). No anisotropy,
    exchange coupling or demag is present so that magnetic moments at
    the two vertices behave identical under the influence of the
    external field. (Ideally, we would only have a single vertex but
    Dolfin doesn't support this.)

    Default values for the arguments:

        Ms = 0.86e6  (saturation magnetisation in A/m)

        m_init = (1, 0, 0)  (initial magnetisation pointing along the x-axis)

        H_ext = (0, 0, 1e6)  (external field in A/m)

        alpha = 0.1  (Gilbert damping coefficient)

    """
    mesh = df.UnitIntervalMesh(1)

    sim = Simulation(mesh, Ms=Ms, unit_length=1e-9, name=name)
    sim.alpha = alpha
    sim.set_m(m_init)
    sim.add(Zeeman(H_ext))

    return sim
Exemple #2
0
 def setUp(self):
     self.mesh = mesh = dolfin.UnitIntervalMesh(30)
     self.element = element = dolfin.FiniteElement("CG", mesh.ufl_cell(), 3)
     self.W = W = dolfin.FunctionSpace(mesh, element)
     self.u = dolfin.Function(W, name='u')
     self.v = dolfin.TestFunction(W)
     self.x = dolfin.SpatialCoordinate(mesh)[0]
Exemple #3
0
    def __init__(self,
                 *,
                 time: df.Constant,
                 cell_model: CellModel,
                 parameters: df.Parameters = None) -> None:
        """Create solver from given cell model and optional parameters."""
        # Define carefully chosen dummy mesh
        mesh = df.UnitIntervalMesh(1)

        _function_space = df.FunctionSpace(mesh, "CG", 1)
        indicator_function = df.Function(_function_space)
        indicator_function.vector()[:] = 1

        extension_modules = import_extension_modules()
        from extension_modules import load_module

        ode_module = load_module(
            "LatticeODESolver",
            recompile=parameters["reload_extension_modules"],
            verbose=parameters["reload_extension_modules"])

        odemap = ode_module.ODEMap()
        odemap.add_ode(1, ode_module.SimpleODE())

        super().__init__(time=time,
                         mesh=mesh,
                         cell_model=cell_model,
                         parameter_map=odemap,
                         indicator_function=indicator_function,
                         parameters=parameters)
    def __init__(self, t_end=None, func=None):
        Problem_verification.__init__(self, t_end, func)

        self.u0_expr = dol.Constant(1)
        self.V = dol.FunctionSpace(dol.UnitIntervalMesh(1), 'DG', 0)

        # rhs
        self.f1 = dol.Expression('pow(t, 2)', t=0, degree=2)
        self.f2 = dol.Expression('pow(t, 2)', t=0, degree=2)

        Problem_FE.__init__(self)
        # CN, higher order
        F = (dol.inner(
            self.v, self.utrial - self.uold + self.dt * 0.5 *
            (self.uold + self.utrial)) * dol.dx -
             0.5 * self.dt * dol.inner(self.f1 + self.f2, self.v) * dol.dx)
        prob = dol.LinearVariationalProblem(dol.lhs(F), dol.rhs(F), self.unew)
        self.solver = dol.LinearVariationalSolver(prob)
        # IE, lower order
        Flow = (dol.inner(
            self.v, self.utrial - self.uold + self.dt * self.utrial) * dol.dx -
                self.dt * dol.inner(self.f2, self.v) * dol.dx)
        problow = dol.LinearVariationalProblem(dol.lhs(Flow), dol.rhs(Flow),
                                               self.ulow)
        self.solver_low = dol.LinearVariationalSolver(problow)
def test_plot_dolfin_function(tmpdir):
    os.chdir(str(tmpdir))
    interval_mesh = df.UnitIntervalMesh(2)
    square_mesh = df.UnitSquareMesh(2, 2)
    cube_mesh = df.UnitCubeMesh(2, 2, 2)

    S = df.FunctionSpace(cube_mesh, 'CG', 1)
    V2 = df.VectorFunctionSpace(square_mesh, 'CG', 1, dim=3)
    V3 = df.VectorFunctionSpace(cube_mesh, 'CG', 1, dim=3)

    s = df.Function(S)
    v2 = df.Function(V2)
    v3 = df.Function(V3)
    v3.vector()[:] = 1.0

    # Wrong function space dimension
    with pytest.raises(TypeError):
        plot_dolfin_function(s, outfile='buggy.png')

    # Plotting a 3D function on a 3D mesh should work
    plot_dolfin_function(v3, outfile='plot.png')
    assert (os.path.exists('plot.png'))

    # Try 2-dimensional mesh as well
    plot_dolfin_function(v2, outfile='plot_2d_mesh.png')
    assert (os.path.exists('plot_2d_mesh.png'))
Exemple #6
0
 def _fenics_vector_spaces(draw, np_data_list, compatible, count, dims):
     ret = []
     for d, ar in zip(dims, np_data_list):
         assume(d > 1)
         if d not in _FENICS_spaces:
             _FENICS_spaces[d] = FenicsVectorSpace(df.FunctionSpace(df.UnitIntervalMesh(d - 1), 'Lagrange', 1))
         ret.append((_FENICS_spaces[d], ar))
     return ret
Exemple #7
0
def _test_scipy_advance_time():
    mesh = df.UnitIntervalMesh(10)
    sim = Simulation(mesh, Ms=1, unit_length=1e-9, integrator_backend="scipy")
    sim.set_m((1, 0, 0))
    sim.advance_time(1e-12)
    sim.advance_time(2e-12)
    sim.advance_time(2e-12)
    sim.advance_time(2e-12)
Exemple #8
0
    def __init__(self, problem_params, dtype_u=fenics_mesh, dtype_f=rhs_fenics_mesh):
        """
        Initialization routine

        Args:
            problem_params (dict): custom parameters for the example
            dtype_u: FEniCS mesh data type (will be passed to parent class)
            dtype_f: FEniCS mesh data data type with implicit and explicit parts (will be passed to parent class)
        """

        # define the Dirichlet boundary
        # def Boundary(x, on_boundary):
        #     return on_boundary

        # these parameters will be used later, so assert their existence
        essential_keys = ['c_nvars', 't0', 'family', 'order', 'refinements', 'nu']
        for key in essential_keys:
            if key not in problem_params:
                msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys()))
                raise ParameterError(msg)

        # set logger level for FFC and dolfin
        logging.getLogger('FFC').setLevel(logging.WARNING)
        logging.getLogger('UFL').setLevel(logging.WARNING)

        # set solver and form parameters
        df.parameters["form_compiler"]["optimize"] = True
        df.parameters["form_compiler"]["cpp_optimize"] = True
        df.parameters['allow_extrapolation'] = True

        # set mesh and refinement (for multilevel)
        mesh = df.UnitIntervalMesh(problem_params['c_nvars'])
        for i in range(problem_params['refinements']):
            mesh = df.refine(mesh)

        # define function space for future reference
        self.V = df.FunctionSpace(mesh, problem_params['family'], problem_params['order'])
        tmp = df.Function(self.V)
        print('DoFs on this level:', len(tmp.vector()[:]))

        # invoke super init, passing number of dofs, dtype_u and dtype_f
        super(fenics_heat, self).__init__(self.V, dtype_u, dtype_f, problem_params)

        # Stiffness term (Laplace)
        u = df.TrialFunction(self.V)
        v = df.TestFunction(self.V)
        a_K = -1.0 * df.inner(df.nabla_grad(u), self.params.nu * df.nabla_grad(v)) * df.dx

        # Mass term
        a_M = u * v * df.dx

        self.M = df.assemble(a_M)
        self.K = df.assemble(a_K)

        # set forcing term as expression
        self.g = df.Expression('-cos(a*x[0]) * (sin(t) - b*a*a*cos(t))', a=np.pi, b=self.params.nu, t=self.params.t0,
                               degree=self.params.order)
def get_mesh(dimension: int, N: int) -> df.Mesh:
    """Create the mesh [0, 1]^d cm."""
    if dimension == 1:
        mesh = df.UnitIntervalMesh(N)
    elif dimension == 2:
        mesh = df.UnitSquareMesh(N, N)  # 1cm time 1cm
    elif dimension == 3:
        mesh = df.UnitCubeMesh(N, N, N)  # 1cm time 1cm
    return mesh
Exemple #10
0
    def setUp(self):
        d.set_log_level(d.LogLevel.WARNING)
        N = 50
        order = 2
        tF = 0.10
        # Dirichlet boundary characteristic time
        tau = tF / 10.0
        # time step
        h = 0.001

        self.num_steps = round(tF / h)

        # Mesh and Function space
        mesh = d.UnitIntervalMesh(N)
        V = d.FunctionSpace(mesh, "P", order)
        w = d.TestFunction(V)
        v = d.TrialFunction(V)

        # Initial conditions chosen such that the wave travels to the right
        uInit = d.Expression(
            "((1./3 < x[0]) && (x[0] < 2./3)) ? 0.5*(1-cos(2*pi*3*(x[0]-1./3))) : 0.",
            degree=2,
        )

        u = d.interpolate(uInit, V)  # values

        # Dirichlet boundary on the right with its derivatives
        g = d.Expression(
            "(t < total) ? 0.4*(1.-cos(2*pi*t/total))/2. : 0.",
            degree=2,
            t=0.0,
            total=tau,
        )
        dg = d.Expression(
            "(t < total) ? 0.4*(pi/total) * sin(2*pi*t/total) : 0.",
            degree=2,
            t=0.0,
            total=tau,
        )

        def updateBC(t):
            g.t = t
            dg.t = t

        def right(x, on_boundary):
            return on_boundary and d.near(x[0], 1.0)

        bc0 = d.DirichletBC(V, g, right)
        bc1 = d.DirichletBC(V, dg, right)
        self.bc = [bc0, bc1]

        L1 = -d.inner(d.grad(w), d.grad(u)) * d.dx
        L2 = w * v * d.dx
        self.parameters = (L1, L2, u, h, updateBC)
Exemple #11
0
def test_cyclic_refs_in_simulation_object_barmini():

    import finmag
    import dolfin as df
    mesh = df.UnitIntervalMesh(1)
    s = finmag.example.barmini()
    s.run_until(1e-12)
    refcount = s.shutdown()
    # The number 4 is emperical. If it increases, we
    # have introduced an extra cyclic reference.
    assert refcount <= 4
Exemple #12
0
def condM(n, precond=lambda M: np.eye(M.shape[0])):
    mesh = df.UnitIntervalMesh(n)
    V = df.FunctionSpace(mesh, 'CG', 1)

    u, v = df.TrialFunction(V), df.TestFunction(V)
    M = df.assemble(df.inner(u, v)*df.dx).array()
    B = precond(M)

    eigw = eigvalsh(M, B)
    lmin, lmax = np.sort(np.abs(eigw))[[0, -1]]

    return lmin, lmax, lmax/lmin
Exemple #13
0
def test_cyclic_refs_in_simulation_object_basic():

    import finmag
    import dolfin as df
    mesh = df.UnitIntervalMesh(1)
    s = finmag.Simulation(mesh, Ms=1, unit_length=1e-9, name='simple')
    refcount = s.shutdown()
    # The number 4 is emperical. If it increases, we
    # have introduced an extra cyclic reference.
    # Update: the cythonised code seems to have only 3 references at his point. Updated
    # to smaller than 4 to allow binary build tests to pass.
    assert refcount <= 4
Exemple #14
0
def setup():
    mesh = df.UnitIntervalMesh(3)
    V = df.FunctionSpace(mesh, "CG", 1)
    alpha = df.Function(V)
    alpha.assign(df.Constant(1))
    W = df.VectorFunctionSpace(mesh, "CG", 1, dim=3)
    m = df.Function(W)
    m.assign(df.Constant((0.6, 0.8, 0)))
    H = df.Function(W)
    H.assign(df.Constant((1, 2, 3)))
    dmdt = df.Function(W)
    return mesh, V, alpha, W, m, H, dmdt
Exemple #15
0
def get_arguments(dim=2, th=False, nx=2):
    if dim == 1:
        mesh = dolfin.UnitIntervalMesh(nx)
    elif dim == 2:
        mesh = dolfin.UnitSquareMesh(nx, nx)
    elif dim == 3:
        mesh = dolfin.UnitCubeMesh(nx, nx, nx)
    P1 = dolfin.FiniteElement("Lagrange", mesh.ufl_cell(), 1)
    P2 = dolfin.FiniteElement("Lagrange", mesh.ufl_cell(), 2)
    args = [mesh, P1, P1, P2, P1]
    if th:
        args.append(P1)
    return tuple(args)
    def __init__(self, t_end = None, func = None, para_stiff = None, adjoint = False):
        Problem_Basic.__init__(self, t_end = t_end, func = func, para_stiff = para_stiff)
        
        self.k = dol.Constant(self.k)
        self.u0_expr = dol.Constant(self.u0) # initial value
        
        mesh = dol.UnitIntervalMesh(1)
        R_elem = dol.FiniteElement("R", mesh.ufl_cell(), 0)
        V_elem = dol.MixedElement([R_elem, R_elem])
        self.V = dol.FunctionSpace(mesh, V_elem)
        
        if adjoint:
            self.z0_expr = dol.Constant(np.array([0., 0.])) # initial value adj
            
        Problem_FE.__init__(self, adjoint)
        
        (self.v1     , self.v2)      = dol.split(self.v)
        (self.u1trial, self.u2trial) = dol.split(self.utrial)
        (self.u1old  , self.u2old)   = dol.split(self.uold)
        (self.u1low  , self.u2low)   = dol.split(self.ulow)
        
        ## Crank nicolson weak formulation
        F = (dol.inner(self.v1, self.u1trial - self.u1old + self.dt * (0.5 * (self.u1old + self.u1trial) - 0.5 * (self.u2old + self.u2trial)))*dol.dx
           + dol.inner(self.v2, self.u2trial - self.u2old - self.k * self.dt * 0.5 * (self.u2old + self.u2trial))*dol.dx)
        prob = dol.LinearVariationalProblem(dol.lhs(F), dol.rhs(F), self.unew)
        self.solver = dol.LinearVariationalSolver(prob)
        ## Implicit Euler weak formulation for error estimation
        Flow = (dol.inner(self.v1, self.u1trial - self.u1old + self.dt * (self.u1trial - self.u2trial))*dol.dx
              + dol.inner(self.v2, self.u2trial - self.u2old - self.k * self.dt * self.u2trial)*dol.dx)
        problow = dol.LinearVariationalProblem(dol.lhs(Flow), dol.rhs(Flow), self.ulow)
        self.solver_low = dol.LinearVariationalSolver(problow)

        if adjoint:
            (self.z1old  , self.z2old)   = dol.split(self.zold)
            (self.z1trial, self.z2trial) = dol.split(self.ztrial)
            
            if self.func not in [1, 2]:
                raise ValueError('DWR not (yet) implemented for this functional')
                
            adj_src = dol.Function(self.V)
            if   self.func == 1:    adj_src.interpolate(dol.Constant((1, 0)))
            elif self.func == 2:    adj_src.interpolate(dol.Constant((0, 1)))
            
            src1, src2 = dol.split(adj_src)
 
            Fadj = (dol.inner(self.z1trial - self.z1old + 0.5 * self.dt * (-self.z1trial - self.z1old + 2*src1), self.v1)*dol.dx +
                    dol.inner(self.z2trial - self.z2old + 0.5 * self.dt * ( self.z1trial + self.z1old + self.k*(self.z2trial + self.z2old) + 2*src2), self.v2)*dol.dx)
            prob_adj = dol.LinearVariationalProblem(dol.lhs(Fadj), dol.rhs(Fadj), self.znew)
            self.solver_adj = dol.LinearVariationalSolver(prob_adj)
Exemple #17
0
def system0(n):
    import dolfin as df
    mesh = df.UnitIntervalMesh(n)
    V = df.FunctionSpace(mesh, 'CG', 1)
    u = df.TrialFunction(V)
    v = df.TestFunction(V)
    bc = df.DirichletBC(V, df.Constant(0), 'on_boundary')

    a = df.inner(df.grad(u), df.grad(v)) * df.dx
    m = df.inner(u, v) * df.dx
    L = df.inner(df.Constant(0), v) * df.dx

    A, _ = df.assemble_system(a, L, bc)
    M, _ = df.assemble_system(m, L, bc)

    return A, M
Exemple #18
0
def generate_Mesh(shape):
    ndim = len(shape)
    Nd = tuple(shape)
    if ndim == 1:
        mesh = dl.UnitIntervalMesh(shape[0])
    elif ndim == 2:
        mesh = dl.UnitSquareMesh.create(shape[0], shape[1],
                                        dl.CellType.Type.quadrilateral)
        # mesh = dl.UnitSquareMesh(shape[0], shape[1])
    elif ndim == 3:
        mesh = dl.UnitCubeMesh.create(shape[0], shape[1], shape[2],
                                      dl.CellType.Type.hexahedron)
    else:
        raise Exception(
            "The case of Dimension={0:d} is not inplemented!".format(ndim))
    return mesh
Exemple #19
0
    def __init__(self,
                 cell_model: CellModel,
                 time: df.Constant,
                 reload_ext_modules: bool = False,
                 parameters: df.Parameters = None) -> None:
        """Create solver from given cell model and optional parameters."""
        # Store model
        self.cell_model = cell_model

        # Define carefully chosen dummy mesh
        mesh = df.UnitIntervalMesh(1)

        super().__init__(mesh,
                         time,
                         cell_model,
                         reload_ext_modules=reload_ext_modules,
                         parameters=parameters)
Exemple #20
0
    def buildMesh(self):
        #-----------------------------------------------------------------------------------
        """ Discretize the domain """

        if self.tDim == 1:
            self.mesh = df.UnitIntervalMesh(self.meshOpt['nXElem'])
        if self.tDim == 2:
            self.mesh = df.UnitSquareMesh(self.meshOpt['nXElem'],\
                                          self.meshOpt['nYElem'])
        if self.tDim == 3:
            self.mesh = df.UnitCubeMesh(self.meshOpt['nXElem'],\
                                               self.meshOpt['nYElem'],\
                                               self.meshOpt['nXElem'])

        self._buildMeshCompleted = True

        return
Exemple #21
0
    def test1D(self):
        n = 10
        mesh = dl.UnitIntervalMesh(n)

        true_sub = dl.CompiledSubDomain("x[0] <= .5")
        true_marker = dl.MeshFunction('size_t', mesh, 1, value=0)
        true_sub.mark(true_marker, 1)

        np_sub = np.ones(n, dtype=np.uint)
        np_sub[n // 2:] = 0
        h = 1. / n
        marker = dl.MeshFunction('size_t', mesh, 1)
        numpy2MeshFunction(mesh, [h], np_sub, marker)

        assert_allclose(marker.array(),
                        true_marker.array(),
                        rtol=1e-7,
                        atol=1e-9)
    def test_1d(self):
        prm = c.Parameters(c.Constraint.UNIAXIAL_STRAIN)
        mesh = df.UnitIntervalMesh(10)

        u_bc = 42.0
        problem = c.MechanicsProblem(mesh, prm, law(prm))
        bcs = []
        bcs.append(df.DirichletBC(problem.Vd, [0], boundary.plane_at(0)))
        bcs.append(df.DirichletBC(problem.Vd, [u_bc], boundary.plane_at(1)))
        problem.set_bcs(bcs)

        u = problem.solve()

        xs = np.linspace(0, 1, 5)
        for x in xs:
            u_fem = u((x))
            u_correct = x * u_bc
            self.assertAlmostEqual(u_fem, u_correct)
    def __init__(self, t_end=None, func=None):
        Problem_verification.__init__(self, t_end, func)

        self.u0_expr = dol.Constant(1)
        self.V = dol.FunctionSpace(dol.UnitIntervalMesh(1), 'DG', 0)

        Problem_FE.__init__(self)
        # CN, higher order
        F = dol.inner(
            self.v, self.utrial - self.uold + self.dt * 0.5 *
            (self.uold + self.utrial)) * dol.dx
        prob = dol.LinearVariationalProblem(dol.lhs(F), dol.rhs(F), self.unew)
        self.solver = dol.LinearVariationalSolver(prob)
        # IE, lower order
        Flow = dol.inner(
            self.v, self.utrial - self.uold + self.dt * self.utrial) * dol.dx
        problow = dol.LinearVariationalProblem(dol.lhs(Flow), dol.rhs(Flow),
                                               self.ulow)
        self.solver_low = dol.LinearVariationalSolver(problow)
    def test1D(self):
        n = 10
        mesh = dl.UnitIntervalMesh(n)
        Vh = dl.FunctionSpace(mesh, "CG", 2)

        n_np = 2 * n
        h = 1. / float(n_np)
        f_np = np.linspace(0., 1., n_np + 1)
        f_exp = NumpyScalarExpression1D()
        f_exp.setData(f_np, h)

        f_exp2 = dl.Expression("x[0]", degree=2)

        fh_1 = dl.interpolate(f_exp, Vh).vector()
        fh_2 = dl.interpolate(f_exp2, Vh).vector()

        fh_1.axpy(-1., fh_2)

        error = fh_1.norm("l2")

        assert_allclose([error], [0.], rtol=1e-7, atol=1e-9)
Exemple #25
0
    def __init__(self,
                 *,
                 cell_model: CellModel,
                 time: df.Constant,
                 parameters: df.Parameters = None) -> None:
        """Create solver from given cell model and optional parameters."""
        assert isinstance(cell_model, CellModel), \
            "Expecting model to be a CellModel, not %r" % cell_model
        assert (isinstance(time, df.Constant)), \
            "Expecting time to be a Constant instance, not %r" % time
        assert isinstance(parameters, df.Parameters) or parameters is None, \
            "Expecting parameters to be a Parameters (or None), not %r" % parameters

        # Define carefully chosen dummy mesh
        mesh = df.UnitIntervalMesh(1)

        super().__init__(mesh=mesh,
                         time=time,
                         model=cell_model,
                         I_s=cell_model.stimulus,
                         parameters=parameters)
def hyper_simplex(dim, n_refinements=0):
    assert isinstance(dim, int)
    assert dim <= 2, "This method is only implemented in 1D and 2D."
    assert isinstance(n_refinements, int) and n_refinements >= 0

    # mesh generation
    if dim == 1:
        mesh = dlfn.UnitIntervalMesh(n_refinements)
    elif dim == 2:
        mesh = dlfn.UnitTriangleMesh.create()

    # mesh refinement
    if dim != 1:
        for i in range(n_refinements):
            mesh = dlfn.refine(mesh)

    # MeshFunction for boundaries ids
    facet_marker = dlfn.MeshFunction("size_t", mesh, dim - 1)
    facet_marker.set_all(0)

    # mark boundaries
    BoundaryMarkers = HyperSimplexBoundaryMarkers
    if dim == 1:
        gamma01 = dlfn.CompiledSubDomain("near(x[0], 0.0) && on_boundary")
        gamma02 = dlfn.CompiledSubDomain("near(x[0], 1.0) && on_boundary")

        gamma01.mark(facet_marker, BoundaryMarkers.left.value)
        gamma02.mark(facet_marker, BoundaryMarkers.right.value)

    elif dim == 2:
        gamma00 = dlfn.CompiledSubDomain("on_boundary")
        gamma01 = dlfn.CompiledSubDomain("near(x[0], 0.0) && on_boundary")
        gamma02 = dlfn.CompiledSubDomain("near(x[1], 0.0) && on_boundary")
        # first mark the entire boundary with the diagonal id
        gamma00.mark(facet_marker, BoundaryMarkers.diagonal.value)
        # then mark the other edges with the correct ids
        gamma01.mark(facet_marker, BoundaryMarkers.left.value)
        gamma02.mark(facet_marker, BoundaryMarkers.bottom.value)

    return mesh, facet_marker
Exemple #27
0
    def test_uniaxial(self):
        prm = c.Parameters(c.Constraint.UNIAXIAL_STRESS)
        prm.deg_d = 1
        prm.alpha = 0.999
        prm.gf = 0.01
        k0 = 2.0e-4
        prm.ft = k0 * prm.E
        law = law_from_prm(prm)

        mesh = df.UnitIntervalMesh(1)
        problem = c.MechanicsProblem(mesh, prm, law)

        bc0 = df.DirichletBC(problem.Vd, [0], boundary.plane_at(0))
        bc_expr = df.Expression(["u"], u=0, degree=0)
        bc1 = df.DirichletBC(problem.Vd, bc_expr, boundary.plane_at(1))

        problem.set_bcs([bc0, bc1])

        ld = c.helper.LoadDisplacementCurve(bc1)

        # ld.show()

        solver = df.NewtonSolver()
        solver.parameters["linear_solver"] = "mumps"
        solver.parameters["maximum_iterations"] = 10
        solver.parameters["error_on_nonconvergence"] = False

        u_max = 100 * k0
        for u in np.linspace(0, u_max, 101):
            bc_expr.u = u
            converged = solver.solve(problem, problem.u.vector())
            assert converged
            problem.update()
            ld(u, df.assemble(problem.R))

        GF = np.trapz(ld.load, ld.disp)
        self.assertAlmostEqual(GF,
                               0.5 * k0**2 * prm.E + prm.gf,
                               delta=prm.gf / 100)
Exemple #28
0
def test_embed3d():
    # Create a 2D mesh which we want to embed in 3D space
    mesh_2d = df.RectangleMesh(df.Point(0, 0), df.Point(20, 10), 10, 5)
    coords_2d = mesh_2d.coordinates()
    z_embed = 4.2

    # Create array containing the expected 3D coordinates
    coords_3d_expected = z_embed * np.ones((len(coords_2d), 3))
    coords_3d_expected[:, :2] = coords_2d

    # Create the embedded 3D mesh
    mesh_3d = embed3d(mesh_2d, z_embed)
    coords_3d = mesh_3d.coordinates()

    # Check that the coordinates coincide
    assert (np.allclose(coords_3d, coords_3d_expected))

    # Check that we can't embed a 1D or 3D mesh (TODO: we could make these
    # work, but currently they are not implemented)
    with pytest.raises(NotImplementedError):
        embed3d(df.UnitIntervalMesh(4))
    with pytest.raises(NotImplementedError):
        embed3d(df.UnitCubeMesh(4, 4, 4))
Exemple #29
0
def test_verify_function_space_type():
    N = 10
    mesh1d = df.UnitIntervalMesh(N)
    mesh2d = df.UnitSquareMesh(N, N)
    mesh3d = df.UnitCubeMesh(N, N, N)

    V1 = df.FunctionSpace(mesh3d, 'DG', 0)
    V2 = df.VectorFunctionSpace(mesh1d, 'DG', 0, dim=1)
    V3 = df.VectorFunctionSpace(mesh2d, 'CG', 1, dim=3)

    # Check that verifying the known function space types works as expected
    assert (verify_function_space_type(V1, 'DG', 0, dim=None))
    assert (verify_function_space_type(V2, 'DG', 0, dim=1))
    assert (verify_function_space_type(V3, 'CG', 1, dim=3))

    # Check that the verification function returns 'False' if we pass in a
    # non-matching function space type.
    # wrong 'dim' (should be None)
    assert (not verify_function_space_type(V1, 'DG', 0, dim=1))
    # wrong degree
    assert (not verify_function_space_type(V1, 'DG', 1, dim=None))
    # wrong family
    assert (not verify_function_space_type(V1, 'CG', 0, dim=None))

    # wrong 'dim' (should be 1)
    assert (not verify_function_space_type(V2, 'DG', 0, dim=None))
    # wrong 'dim' (should be 1)
    assert (not verify_function_space_type(V2, 'DG', 0, dim=42))
    assert (not verify_function_space_type(V2, 'DG', 42, dim=1)
            )  # wrong degree
    assert (not verify_function_space_type(V2, 'CG', 0, dim=1))  # wrong family

    # wrong dimension
    assert (not verify_function_space_type(V3, 'CG', 1, dim=42))
    assert (not verify_function_space_type(V3, 'CG', 42, dim=1)
            )  # wrong degree
    assert (not verify_function_space_type(V3, 'DG', 1, dim=3))  # wrong family
Exemple #30
0
def macrospin_interval(Ms=0.86e6,
                       m_init=(1, 0, 0),
                       H_ext=(0, 0, 1e6),
                       alpha=0.1,
                       name='macrospin'):
    """
    1d mesh (= interval) with two vertices which are 1 nm apart.

    No anisotropy, exchange coupling or demag is present so that
    magnetic moments at the vertices behave identical under the
    influence of the external field. The damping constant has the
    value alpha=0.1.


    Default values for the arguments:

        Ms = 0.86e6  (saturation magnetisation in A/m)

        m_init = (1, 0, 0)  (initial magnetisation pointing along the x-axis)

        H_ext = (0, 0, 1e6)  (external field in A/m)

        alpha = 0.1  (Gilbert damping coefficient)

    """
    mesh = df.UnitIntervalMesh()
    sim = sim_with(mesh,
                   Ms=1e6,
                   m_init=(1, 0, 0),
                   alpha=alpha,
                   unit_length=1e-9,
                   H_ext=H_ext,
                   A=None,
                   demag_solver=None,
                   name=name)
    return sim