예제 #1
0
def run_simulation():
    L = 3e-8
    W = 1e-8
    H = 1e-8
    mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(L, W, H), 10, 4, 4)

    Ms = 0.86e6  # A/m
    A = 1.3e-11  # J/m

    sim = Sim(mesh, Ms)
    sim.set_m(("2*x[0]/L - 1", "2*x[1]/W - 1", "1"), L=3e-8, H=1e-8, W=1e-8)
    sim.alpha = 0.1
    sim.add(Zeeman((Ms / 2, 0, 0)))
    sim.add(Exchange(A))

    t = 0
    dt = 1e-11
    tmax = 1e-9  # s

    fh = open(os.path.join(MODULE_DIR, "averages.txt"), "w")
    while t <= tmax:
        mx, my, mz = sim.m_average
        fh.write(str(t) + " " + str(mx) + " " + str(my) + " " + str(mz) + "\n")
        t += dt
        sim.run_until(t)
    fh.close()
예제 #2
0
    def test_cosine_solution_robin_boundary_conditions(self):
        dt = 0.05
        t = 0
        final_time = 1
        nx, ny = 31, 31
        degree = 2
        kappa = dla.Constant(3)

        mesh = dla.RectangleMesh(dl.Point(0, 0), dl.Point(1, 1), nx, ny)
        function_space = dl.FunctionSpace(mesh, "Lagrange", degree)
        # bc : kappa * grad u.dot(n)+alpha*u=beta
        alpha = 1
        from functools import partial
        expression = partial(get_gradu_dot_n, kappa, alpha, mesh, degree)
        boundary_conditions = get_robin_boundary_conditions_from_expression(
            expression, dla.Constant(alpha))

        sol = run_model(function_space,
                        kappa,
                        get_forcing(kappa, mesh, degree),
                        get_exact_solution(mesh, degree),
                        dt,
                        final_time,
                        boundary_conditions=boundary_conditions,
                        second_order_timestepping=True,
                        exact_sol=None)

        exact_sol = get_exact_solution(mesh, degree)
        exact_sol.t = final_time
        error = dl.errornorm(exact_sol, sol, mesh=mesh)
        print('Error', error)
        assert error <= 1e-4
예제 #3
0
    def setUp(self):
        np.random.seed(1)
        #self.dim = np.random.randint(1, high=5)
        self.dim = 1

        self.means = np.random.uniform(-10, high=10., size=self.dim)

        self.chol = np.tril(
            np.random.uniform(1, high=10, size=(self.dim, self.dim)))

        self.cov = np.dot(self.chol, self.chol.T)

        self.precision = np.linalg.inv(self.cov)

        mesh = dl.RectangleMesh(dl.mpi_comm_world(), dl.Point(0.0, 0.0),
                                dl.Point(3, 2), 6, 4)

        if self.dim > 1:
            self.Rn = dl.VectorFunctionSpace(mesh, "R", 0, dim=self.dim)
        else:
            self.Rn = dl.FunctionSpace(mesh, "R", 0)

        self.test_prior = GaussianRealPrior(self.Rn, self.cov)

        m = dl.Function(self.Rn)
        m.vector().zero()
        m.vector().set_local(self.means)
        self.test_prior.mean.axpy(1., m.vector())
예제 #4
0
    def test_dirichlet_boundary(self):
        frequency=50
        omega = 2.*np.pi*frequency
        c1,c2 = [343.4,6320]
        gamma=8.4e-4
        
        kappa = omega/c1

        Nx, Ny = [21,21]
        Lx,Ly=[1,1]

        # create function space
        mesh = dl.RectangleMesh(dl.Point(0., 0.), dl.Point(Lx, Ly), Nx, Ny)
        degree=1
        P1=dl.FiniteElement('Lagrange',mesh.ufl_cell(),degree)
        element=dl.MixedElement([P1,P1])
        function_space=dl.FunctionSpace(mesh,element)
        
        boundary_conditions=None
        kappa=dl.Constant(kappa)
        # do not pass element=function_space.ufl_element()
        # as want forcing to be a scalar pass degree instead
        forcing=[
            Forcing(kappa,'real',degree=function_space.ufl_element().degree()),
            Forcing(kappa,'imag',degree=function_space.ufl_element().degree())]

        p=run_model(kappa,forcing,function_space,boundary_conditions)
        error = dl.errornorm(
            ExactSolution(kappa,element=function_space.ufl_element()),p)
        print('Error',error)
        assert error<=3e-2
예제 #5
0
    def test_quadratic_solution(self):
        dt = 0.01
        t = 0
        final_time = 2
        nx, ny = 2, 2
        degree = 2
        alpha, beta = 3, 1.2
        kappa = dla.Constant(1)
        mesh = dla.RectangleMesh(dl.Point(0, 0), dl.Point(1, 1), nx, ny)
        function_space = dl.FunctionSpace(mesh, "Lagrange", degree)

        boundary_conditions = get_dirichlet_boundary_conditions_from_expression(
            get_quadratic_exact_solution(alpha, beta, mesh, degree), 0, 1, 0,
            1)
        sol = run_model(function_space,
                        kappa,
                        get_quadratic_solution_forcing(alpha, beta, mesh,
                                                       degree),
                        get_quadratic_exact_solution(alpha, beta, mesh,
                                                     degree),
                        dt,
                        final_time,
                        boundary_conditions=boundary_conditions)  # ,
        # exact_sol=get_quadratic_exact_solution(alpha,beta,mesh,degree))

        exact_sol = get_quadratic_exact_solution(alpha, beta, mesh, degree)
        exact_sol.t = final_time
        error = dl.errornorm(exact_sol, sol, mesh=mesh)
        print('Error', error)
        assert error <= 3e-14
예제 #6
0
def test_2D_particle_source_region(self):
    """Set up a two-dimensional source region and display it.

           Incomplete

        """

    fncName = '(' + __file__ + ') ' + sys._getframe().f_code.co_name + '():\n'
    print('\ntest: ', fncName, '(' + __file__ + ')')

    #        from UserMesh_y_Fields_FE_XYZ_Module import UserMeshInput_C

    umi2D = UserMeshInput_C()

    # TODO: Change these to TUPLES instead of Points? (to avoid df_m at toplevel)
    umi2D.pmin = df_m.Point(-10.0, -10.0)
    umi2D.pmax = df_m.Point(10.0, 10.0)
    umi2D.cells_on_side = (4, 2)

    ## Boundary conditions for the particles on this mesh

    # Create a 2D particle mesh
    #        pmesh2D = UserMesh_C(umi2D, computeDictionaries=True, computeTree=True, plotFlag=plotFlag)

    return
예제 #7
0
def mesh(Lx=1., Ly=1., Lz=2., grid_spacing=1./16, **namespace):
    m = df.BoxMesh(df.Point(0., 0., 0.), df.Point(Lx, Ly, Lz),
                   int(Lx/(2*grid_spacing)),
                   int(Ly/(2*grid_spacing)),
                   int(Lz/(2*grid_spacing)))
    m = df.refine(m)
    return m
예제 #8
0
def main():
    "Generates the mesh"

    import mshr as m
    import dolfin as d
    import matplotlib.pyplot as plt

    d.set_log_level(13)  # PROGRESS

    r_1 = 0.5  # inner
    r_2 = 2.0  # outer
    res = 10  # resolution

    circle_inner = m.Circle(d.Point(0.0, 0.0), r_1)
    circle_outer = m.Circle(d.Point(0.0, 0.0), r_2)

    domain = circle_outer - circle_inner

    domain.set_subdomain(1, circle_inner)
    domain.set_subdomain(2, circle_outer)

    mesh = m.generate_mesh(domain, res)

    print("max edge length:", mesh.hmax())

    mesh_file_pvd = d.File("mesh.pvd")
    mesh_file_pvd.write(mesh)

    plt.figure()
    d.plot(mesh, title="Mesh")
    plt.show()
    def test_quadratic_diffusion_dirichlet_boundary_conditions(self):
        """
        du/dt = div((1+u**2)*grad(u))+f   in the unit square.
            u = u_D on the boundary.
        """
        nx, ny, degree = 21, 21, 2
        mesh = dla.RectangleMesh(dl.Point(0, 0), dl.Point(1, 1), nx, ny)
        function_space = dl.FunctionSpace(mesh, "Lagrange", degree)

        bndry_obj = get_2d_unit_square_mesh_boundaries()
        boundary_conditions = get_dirichlet_boundary_conditions_from_expression(
            get_quadratic_diffusion_exact_solution(mesh, degree), 0, 1, 0, 1)
        forcing = get_diffusion_forcing(
            quadratic_diffusion, get_quadratic_diffusion_exact_solution_sympy,
            mesh, degree)

        options = {'time_step': 0.05, 'final_time': 1,
                   'forcing': forcing,
                   'boundary_conditions': boundary_conditions,
                   'second_order_timestepping': True,
                   'init_condition': get_quadratic_diffusion_exact_solution(
                       mesh, degree), 'nonlinear_diffusion':
                   quadratic_diffusion}
        sol = run_model(function_space, **options)

        exact_sol = get_quadratic_diffusion_exact_solution(mesh, degree)
        exact_sol.t = options['final_time']
        error = dl.errornorm(exact_sol, sol, mesh=mesh)
        print('Abs. Error', error)
        assert error <= 8e-5
예제 #10
0
def test_dmi_pbc2d_1D(plot=False):
    def m_init_fun(p):
        if p[0] < 10:
            return [0.5, 0, 1]
        else:
            return [-0.5, 0, -1]

    mesh = df.RectangleMesh(df.Point(0, 0), df.Point(20, 2), 10, 1)
    m_init = vector_valued_function(m_init_fun, mesh)

    Ms = 8.6e5
    sim = Simulation(mesh, Ms, pbc='2d', unit_length=1e-9)

    sim.set_m(m_init_fun)

    A = 1.3e-11
    D = 5e-3
    sim.add(Exchange(A))
    sim.add(DMI(D))

    sim.relax(stopping_dmdt=0.0001)

    if plot:
        sim.m_field.plot_with_dolfin()

    mx = [sim.m_field.probe([x + 0.5, 1])[0] for x in range(20)]

    assert np.max(np.abs(mx)) < 1e-6
예제 #11
0
def test_hysteresis(tmpdir):
    os.chdir(str(tmpdir))
    sim = barmini()
    mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1)
    H_ext_list = [(1, 0, 0), (2, 0, 0), (3, 0, 0), (4, 0, 0)]
    N = len(H_ext_list)

    # Run a relaxation and save a vtk snapshot at the end of each stage;
    # this should result in three .vtu files (one for each stage).
    sim1 = sim_with(mesh,
                    Ms=1e6,
                    m_init=(0.8, 0.2, 0),
                    alpha=1.0,
                    unit_length=1e-9,
                    A=None,
                    demag_solver=None)
    sim1.schedule('save_vtk', at_end=True, filename='barmini_hysteresis.pvd')
    res1 = sim1.hysteresis(H_ext_list=H_ext_list)
    assert (len(glob('barmini_hysteresis*.vtu')) == N)
    assert (res1 == None)

    # Run a relaxation with a non-trivial `fun` argument and check
    # that we get a list of return values.
    sim2 = sim_with(mesh,
                    Ms=1e6,
                    m_init=(0.8, 0.2, 0),
                    alpha=1.0,
                    unit_length=1e-9,
                    A=None,
                    demag_solver=None)
    res2 = sim2.hysteresis(H_ext_list=H_ext_list,
                           fun=lambda sim: sim.m_average[0])
    assert (len(res2) == N)
예제 #12
0
def macrospin_box(Ms=0.86e6,
                  m_init=(1, 0, 0),
                  H_ext=(0, 0, 1e6),
                  alpha=0.1,
                  name='macrospin'):
    """
    Cubic mesh of length 1 nm along each edge, with eight vertices
    located in the corners of the cube.

    No anisotropy, exchange coupling or demag is present so that
    magnetic moments at the vertices behave identical under the
    influence of the external field.


    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.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1)
    sim = sim_with(mesh,
                   Ms=0.86e6,
                   alpha=alpha,
                   unit_length=1e-9,
                   A=None,
                   H_ext=H_ext,
                   m_init=(1, 0, 0),
                   name=name)
    return sim
예제 #13
0
def test_crossprod():
    """
    Compute the cross product of two functions f and g numerically
    using `helpers.crossprod` and compare with the analytical
    expression.

    """
    xmin = ymin = zmin = -2
    xmax = ymax = zmax = 3
    nx = ny = nz = 10
    mesh = df.BoxMesh(df.Point(xmin, ymin, zmin), df.Point(xmax, ymax, zmax),
                      nx, ny, nz)
    V = df.VectorFunctionSpace(mesh, 'CG', 1, dim=3)
    u = df.interpolate(df.Expression(['x[0]', 'x[1]', '0'], degree=1), V)
    v = df.interpolate(df.Expression(['-x[1]', 'x[0]', 'x[2]'], degree=1), V)
    w = df.interpolate(
        df.Expression(['x[1]*x[2]', '-x[0]*x[2]', 'x[0]*x[0]+x[1]*x[1]'],
                      degree=1), V)

    a = u.vector().array()
    b = v.vector().array()
    c = w.vector().array()

    axb = crossprod(a, b)
    assert (np.allclose(axb, c))
예제 #14
0
def test_energy_density_function():
    """
    Compute the Zeeman energy density over the entire mesh, integrate it, and
    compare it to the expected result.
    """

    mesh = df.RectangleMesh(df.Point(-50, -50), df.Point(50, 50), 10, 10)
    unit_length = 1e-9
    H = 1e6

    # Create simulation object.
    sim = finmag.Simulation(mesh, 1e5, unit_length=unit_length)

    # Set uniform magnetisation.
    def m_ferromagnetic(pos):
        return np.array([0., 0., 1.])

    sim.set_m(m_ferromagnetic)

    # Assign zeeman object to simulation
    sim.add(Zeeman(H * np.array([0., 0., 1.])))

    # Get energy density function
    edf = sim.get_interaction('Zeeman').energy_density_function()

    # Integrate it over the mesh and compare to expected result.
    total_energy = df.assemble(edf * df.dx) * unit_length
    expected_energy = -mu0 * H
    assert (total_energy + expected_energy) < 1e-6
예제 #15
0
파일: dolfin.py 프로젝트: pkgw/vernon
    def __init__(self, Cg, m0, B0, R_E, c_squared):
        self.Cg = Cg
        self.m0 = m0
        self.B0 = B0
        self.R_E = R_E
        self.c_squared = c_squared

        self.nv = 40
        self.nk = 45 # NB: keep odd to avoid blowups with y = 0!
        self.nl = 8

        self.lmin = 1.1
        self.lmax = 7.0

        self.logvmin = np.log(1e11)
        self.logvmax = np.log(1e17)

        # recall: k{hat}_min => theta_max and vice versa! Y/y = 33 => alpha ~= 4 degr.

        self.khatmax = (33. * R_E * (B0 / self.lmin)**0.5)**0.2
        self.khatmin = -self.khatmax

        self.vk_mesh = d.RectangleMesh(
            d.Point(self.logvmin, self.khatmin),
            d.Point(self.logvmax, self.khatmax),
            self.nv, self.nk
        )
        self.l_mesh = d.IntervalMesh(self.nl, self.lmin, self.lmax)

        self.l_boundary = OneDWallExpression(degree=0).configure(0., self.lmax)
    def test_constant_diffusion_dirichlet_boundary_conditions(self):
        kappa = 3
        nx, ny, degree = 31, 31, 2
        mesh = dla.RectangleMesh(dl.Point(0, 0), dl.Point(1, 1), nx, ny)
        function_space = dl.FunctionSpace(mesh, "Lagrange", degree)

        def constant_diffusion(u):
            return dla.Constant(kappa)

        boundary_conditions = get_dirichlet_boundary_conditions_from_expression(
            get_advec_exact_solution(mesh, degree), 0, 1, 0, 1)

        nlsparam = dict()

        options = {'time_step': 0.05, 'final_time': 1,
                   'forcing': get_advec_forcing(kappa, mesh, degree),
                   'boundary_conditions': boundary_conditions,
                   'second_order_timestepping': True,
                   'init_condition': get_advec_exact_solution(mesh, degree),
                   'nlsparam': nlsparam,
                   'nonlinear_diffusion': constant_diffusion}
        sol = run_model(function_space, **options)

        exact_sol = get_advec_exact_solution(mesh, degree)
        exact_sol.t = options['final_time']
        error = dl.errornorm(exact_sol, sol, mesh=mesh)
        print('Abs. Error', error)
        assert error <= 1e-4
예제 #17
0
def three_dimensional_problem():
    x_max = 100e-9
    y_max = z_max = 1e-9
    x_n = 20
    y_n = z_n = 1

    dolfin_mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(x_max, y_max, z_max),
                             x_n, y_n, z_n)
    print dolfin_mesh.num_vertices()
    oommf_mesh = mesh.Mesh((x_n, y_n, z_n), size=(x_max, y_max, z_max))

    def m_gen(rs):
        xs = rs[0]
        return np.array([
            xs / x_max,
            np.sqrt(1 - (0.9 * xs / x_max)**2 - 0.01), 0.1 * np.ones(len(xs))
        ])

    from finmag.util.oommf.comparison import compare_anisotropy
    return compare_anisotropy(m_gen,
                              Ms,
                              K1, (0, 0, 1),
                              dolfin_mesh,
                              oommf_mesh,
                              dims=3,
                              name="3D")
예제 #18
0
def test_exchange_energy_analytical_2():
    """
    Compare one Exchange energy with the corresponding analytical result.

    """
    REL_TOLERANCE = 5e-5
    lx = 6
    ly = 3
    lz = 2
    nx = 300
    ny = nz = 1
    mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(lx, ly, lz), nx, ny, nz)
    unit_length = 1e-9
    functionspace = df.VectorFunctionSpace(mesh, "CG", 1, 3)
    Ms = Ms = Field(df.FunctionSpace(mesh, 'DG', 0), 8e5)
    A = 13e-12
    m = Field(functionspace)
    m.set(
        df.Expression(['0', 'sin(2*pi*x[0]/l_x)', 'cos(2*pi*x[0]/l_x)'],
                      l_x=lx,
                      degree=1))
    exch = Exchange(A)
    exch.setup(m, Ms, unit_length=unit_length)
    E_expected = A * 4 * pi ** 2 * \
        (ly * unit_length) * (lz * unit_length) / (lx * unit_length)
    E = exch.compute_energy()
    print "expected energy: {}".format(E)
    print "computed energy: {}".format(E_expected)
    assert abs((E - E_expected) / E_expected) < REL_TOLERANCE
예제 #19
0
def demo1():
    # create example simulation
    import finmag
    import dolfin as df
    xmin, ymin, zmin = 0, 0, 0  # one corner of cuboid
    xmax, ymax, zmax = 6, 6, 11  # other corner of cuboid
    nx, ny, nz = 3, 3, 6  # number of subdivisions (use ~2nm edgelength)
    mesh = df.BoxMesh(df.Point(xmin, ymin, zmin), df.Point(xmax, ymax, zmax),
                      nx, ny, nz)
    # standard Py parameters
    sim = finmag.sim_with(mesh,
                          Ms=0.86e6,
                          alpha=0.5,
                          unit_length=1e-9,
                          A=13e-12,
                          m_init=(1, 0, 1))
    filename = 'data.txt'
    ndt = Tablewriter(filename, sim, override=True)
    times = np.linspace(0, 3.0e-11, 6 + 1)
    for i, time in enumerate(times):
        print("In iteration {}, computing up to time {}".format(i, time))
        sim.run_until(time)
        ndt.save()

    # now open file for reading
    f = Tablereader(filename)
    print f.timesteps()
    print f['m_x']
예제 #20
0
def create_simple_mesh(Rint, Rout, resolution):
    # Create circles as Circle(Center, Radius)
    outer_circle = mshr.Circle(df.Point(0, 0), Rout)
    inner_circle = mshr.Circle(df.Point(0, 0), Rint)
    domain = outer_circle - inner_circle
    mesh = mshr.generate_mesh(domain, resolution)
    return mesh
예제 #21
0
def test_current_time():
    size = 20e-9
    simplices = 4
    mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(size, size, size), simplices,
                      simplices, simplices)

    Ms = 860e3
    A = 13.0e-12

    sim = Sim(mesh, Ms)
    sim.set_m((1, 0, 0))
    sim.add(Exchange(A))
    sim.add(Demag())

    t = 0.0
    t_max = 1e-10
    dt = 1e-12

    while t <= t_max:
        t += dt
        sim.run_until(t)
        # cur_t is equal to whatever time the integrator decided to probe last
        assert not sim.integrator.cur_t == 0.0
        # t is equal to our current simulation time
        assert abs(sim.t - t) < epsilon
예제 #22
0
def test_mat_without_dictionnary():
    """FenicsPart instance initialized with only one instance of Material"""
    L_x, L_y = 1, 1
    mesh = fe.RectangleMesh(fe.Point(0.0, 0.0), fe.Point(L_x, L_y), 10, 10)
    dimensions = np.array(((L_x, 0.0), (0.0, L_y)))
    E, nu = 1, 0.3
    material = mat.Material(E, nu, "cp")
    rect_part = part.FenicsPart(
        mesh,
        materials=material,
        subdomains=None,
        global_dimensions=dimensions,
        facet_regions=None,
    )
    elem_type = "CG"
    degree = 2
    strain_fspace = fe.FunctionSpace(
        mesh,
        fe.VectorElement(elem_type, mesh.ufl_cell(), degree, dim=3),
    )
    strain = fe.project(fe.Expression(("1.0+x[0]*x[0]", "0", "1.0"), degree=2),
                        strain_fspace)
    stress = mat.sigma(rect_part.elasticity_tensor, strain)
    energy = fe.assemble(fe.inner(stress, strain) * fe.dx(rect_part.mesh))
    energy_theo = E / (1 + nu) * (1 + 28 / (15 * (1 - nu)))
    assert energy == approx(energy_theo, rel=1e-13)
예제 #23
0
    def test_robin_boundary(self):
        frequency=50
        omega = 2.*np.pi*frequency
        c1,c2 = [343.4,6320]
        gamma=8.4e-4
        
        kappa = omega/c1
        alpha=kappa*gamma

        Nx, Ny = 21,21; Lx, Ly = 1,1

        mesh = dl.RectangleMesh(dl.Point(0., 0.), dl.Point(Lx, Ly), Nx, Ny)
        degree=1
        P1=dl.FiniteElement('Lagrange',mesh.ufl_cell(),degree)
        element=dl.MixedElement([P1,P1])
        function_space=dl.FunctionSpace(mesh,element)
        
        boundary_conditions=get_robin_bndry_conditions(
            kappa,alpha,function_space)
        kappa=dl.Constant(kappa)
        forcing=[
            Forcing(kappa,'real',degree=function_space.ufl_element().degree()),
            Forcing(kappa,'imag',degree=function_space.ufl_element().degree())]
        
        p=run_model(kappa,forcing,function_space,boundary_conditions)
        error = dl.errornorm(
            ExactSolution(kappa,element=function_space.ufl_element()),p,)
        print('Error',error)
        assert error<=3e-2
예제 #24
0
def test_2_materials():
    """FenicsPart instance initialized with only one instance of Material in the materials dictionnary"""
    L_x, L_y = 1, 1
    mesh = fe.RectangleMesh(fe.Point(-L_x, -L_y), fe.Point(L_x, L_y), 20, 20)
    dimensions = np.array(((2 * L_x, 0.0), (0.0, 2 * L_y)))
    subdomains = fe.MeshFunction("size_t", mesh, 2)

    class Right_part(fe.SubDomain):
        def inside(self, x, on_boundary):
            return x[0] >= 0 - fe.DOLFIN_EPS

    subdomain_right = Right_part()
    subdomains.set_all(0)
    subdomain_right.mark(subdomains, 1)
    E_1, E_2, nu = 1, 3, 0.3
    materials = {0: mat.Material(1, 0.3, "cp"), 1: mat.Material(3, 0.3, "cp")}
    rect_part = part.FenicsPart(mesh, materials, subdomains, dimensions)
    elem_type = "CG"
    degree = 2
    strain_fspace = fe.FunctionSpace(
        mesh,
        fe.VectorElement(elem_type, mesh.ufl_cell(), degree, dim=3),
    )
    strain = fe.project(fe.Expression(("1.0+x[0]*x[0]", "0", "1.0"), degree=2),
                        strain_fspace)
    stress = mat.sigma(rect_part.elasticity_tensor, strain)
    energy = fe.assemble(fe.inner(stress, strain) * fe.dx(rect_part.mesh))
    energy_theo = 2 * ((E_1 + E_2) / (1 + nu) * (1 + 28 / (15 * (1 - nu))))
    assert energy == approx(energy_theo, rel=1e-13)
예제 #25
0
    def test_cosine_solution_dirichlet_boundary_conditions(self):
        dt = 0.05
        t = 0
        final_time = 1
        nx, ny = 31, 31
        degree = 2
        kappa = dla.Constant(3)

        mesh = dla.RectangleMesh(dl.Point(0, 0), dl.Point(1, 1), nx, ny)
        function_space = dl.FunctionSpace(mesh, "Lagrange", degree)
        boundary_conditions = get_dirichlet_boundary_conditions_from_expression(
            get_exact_solution(mesh, degree), 0, 1, 0, 1)
        sol = run_model(function_space,
                        kappa,
                        get_forcing(kappa, mesh, degree),
                        get_exact_solution(mesh, degree),
                        dt,
                        final_time,
                        boundary_conditions=boundary_conditions,
                        second_order_timestepping=True,
                        exact_sol=None)

        exact_sol = get_exact_solution(mesh, degree)
        exact_sol.t = final_time
        error = dl.errornorm(exact_sol, sol, mesh=mesh)
        print('Error', error)
        assert error <= 1e-4
예제 #26
0
def test_compute_skyrmion_number_2d_pbc():

    mesh = df.RectangleMesh(df.Point(0, 0), df.Point(100, 100), 40, 40)

    Ms = 8.6e5
    sim = Simulation(mesh, Ms, pbc='2d', unit_length=1e-9)
    sim.set_m(init_skx_down)

    sim.add(Exchange(1.3e-11))
    sim.add(DMI(D=4e-3))
    sim.add(Zeeman((0, 0, 0.45 * Ms)))

    sim.do_precession = False

    sim.relax(stopping_dmdt=1, dt_limit=1e-9)

    #df.plot(sim.m_field.f)
    #df.interactive()
    print np.max(sim.m_field.as_array())

    sky_num = compute_skyrmion_number_2d(sim.m_field.f)

    print 'sky_num = %g' % sky_num

    assert sky_num < -0.95 and sky_num > -1.0
def FunctionFromSamples(g_samples, grid, offset=0.0):
    """
    Given an array of function samples at the points of a grid, construct
    a callable dolfin function by interpolation.
    Inputs:  g_samples (np.array): 2D or 3D array of function samples
             grid (Grid):          grid of Points at which function was sampled
    Returns: Callable dolfin function of 2D or 3D coordinate array p
    """
    n, nd = np.shape(g_samples), len(np.shape(g_samples))
    x, y, z = grid.xtics, grid.ytics, grid.ztics
    vmin, vmax = [x[0], y[0], z[0]], [x[-1], y[-1], z[-1]]
    pmin, pmax = df.Point(vmin[0:nd]), df.Point(vmax[0:nd])
    if nd == 2:
        mesh = df.RectangleMesh(pmin, pmax, n[0], n[1])
    else:
        mesh = df.BoxMesh(pmin, pmax, n[0], n[1], n[2])
    grid_space = df.FunctionSpace(mesh, 'Lagrange', 1)
    g = df.Function(grid_space)
    v = g.vector()
    delta = [t[2] - t[1] if len(t) > 1 else 1.0 for t in [x, y, z]]
    for i, p in enumerate(grid_space.tabulate_dof_coordinates()):
        n = [int(round((p[d] - pmin[d]) / delta[d])) for d in range(nd)]
        v[i] = g_samples[tuple(n)] + offset
    g.set_allow_extrapolation(True)
    return g
예제 #28
0
def bar(name='bar', demag_solver_type=None):
    """Py bar with dimensions 30x30x100nm, initial field
    pointing in (1,0,1) direction.

    Same as example 2 in Nmag manual.

    This function returns a simulation object that is 'ready to go'.

    Useful commands to run this for a minute::

        times = numpy.linspace(0, 3.0e-11, 6 + 1)
        for t in times:
            # Integrate
            sim.run_until(t)
    """

    xmin, ymin, zmin = 0, 0, 0  # one corner of cuboid
    xmax, ymax, zmax = 30, 30, 100  # other corner of cuboid
    # number of subdivisions (use ~2nm edgelength)
    nx, ny, nz = 15, 15, 50
    mesh = df.BoxMesh(df.Point(xmin, ymin, zmin), df.Point(xmax, ymax, zmax),
                      nx, ny, nz)

    sim = finmag.sim_with(mesh,
                          Ms=0.86e6,
                          alpha=0.5,
                          unit_length=1e-9,
                          A=13e-12,
                          m_init=(1, 0, 1),
                          name=name,
                          demag_solver_type=demag_solver_type)

    return sim
예제 #29
0
def extract_mesh_slice(mesh, slice_z):
    coords = mesh.coordinates()
    xmin = min(coords[:, 0])
    xmax = max(coords[:, 0])
    ymin = min(coords[:, 1])
    ymax = max(coords[:, 1])
    nx = int(1 * (xmax - xmin))
    ny = int(1 * (ymax - ymin))
    slice_mesh = embed3d(df.RectangleMesh(df.Point(xmin, ymin),
                                          df.Point(xmax, ymax), nx, ny),
                         z_embed=slice_z)

    V = df.FunctionSpace(mesh, 'CG', 1)
    f = df.Function(V)
    V_slice = df.FunctionSpace(slice_mesh, 'CG', 1)
    f_slice = df.Function(V_slice)

    lg = df.LagrangeInterpolator()

    def restrict_to_slice_mesh(a):
        f.vector().set_local(a)
        lg.interpolate(f_slice, f)
        return f_slice.vector().array()

    return slice_mesh, restrict_to_slice_mesh
예제 #30
0
def test_compare_exchange_for_two_dolfin_meshes():
    """
    Check that a mesh expressed in nanometers gives the same results
    as a mesh expressed in meters for the exchange interaction.

    """
    mesh_nm = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), n, n,
                         n)  # in nm
    m_nm, H_nm, E_nm = exchange(mesh_nm, unit_length=1e-9)

    mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1e-9, 1e-9, 1e-9), n, n, n)
    m, H, E = exchange(mesh, unit_length=1)

    rel_diff_m = np.max(np.abs(m_nm - m))  # norm m = 1
    print "Difference of magnetisation is {:.2f}%.".format(100 * rel_diff_m)
    assert rel_diff_m < REL_TOL

    rel_diff_E = abs((E_nm - E) / E)
    print "Relative difference between E_nm = {:.5g} and E_m = {:.5g} is d = {:.2f}%.".format(
        E_nm, E, 100 * rel_diff_E)
    assert rel_diff_E < REL_TOL

    max_diff_H = np.max(np.abs(H_nm - H) / np.max(H))
    print "Maximum of relative difference between the two fields is d = {:.2f}%.".format(
        100 * max_diff_H)
    assert np.max(np.abs(H)) > 0
    assert max_diff_H < REL_TOL