Пример #1
0
 def RectangleMesh(*args, **kwargs):
     if len(args) >= 2 and isinstance(args[0], dolfin.Point) and isinstance(
             args[1], dolfin.Point):
         return dolfin.RectangleMesh(args[0].x(), args[0].y(), args[1].x(),
                                     args[1].y(), *args[2:], **kwargs)
     elif len(args) >= 3 and isinstance(
             args[1], dolfin.Point) and isinstance(args[2], dolfin.Point):
         return dolfin.RectangleMesh(args[0], args[1].x(), args[1].y(),
                                     args[2].x(), args[2].y(), *args[3:],
                                     **kwargs)
     else:
         return dolfin.RectangleMesh(*args, **kwargs)
Пример #2
0
def test_build_mesh():
    """
    Create a few meshes, extract the vertices and cells from them and pass them
    to build_mesh() to rebuild the mesh. Then check that the result is the same
    as the original.
    """
    def assert_mesh_builds_correctly(mesh):
        coords = mesh.coordinates()
        cells = mesh.cells()
        mesh_new = build_mesh(coords, cells)
        assert np.allclose(coords, mesh_new.coordinates())
        assert np.allclose(cells, mesh_new.cells())

    mesh1 = df.RectangleMesh(df.Point(0, 0), df.Point(20, 10), 12, 8)
    assert_mesh_builds_correctly(mesh1)

    mesh2_temp = mshr.Circle(df.Point(2.0, -3.0), 10)
    mesh2 = mshr.generate_mesh(mesh2_temp, 10)
    assert_mesh_builds_correctly(mesh2)

    mesh3 = df.BoxMesh(df.Point(0, 0, 0), df.Point(20, 10, 5), 12, 8, 3)
    assert_mesh_builds_correctly(mesh3)

    mesh4_temp = mshr.Sphere(df.Point(2.0, 3.0, -4.0), 10)
    mesh4 = mshr.generate_mesh(mesh4_temp, 10)
    assert_mesh_builds_correctly(mesh4)
Пример #3
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
Пример #4
0
def mesh(Lx=1, Ly=5, grid_spacing=1./16, rad_init=0.75, **namespace):
    m = df.RectangleMesh(df.Point(0., 0.), df.Point(Lx, Ly),
                         int(Lx/(1*grid_spacing)),
                         int(Ly/(1*grid_spacing)))

    for k in range(3):
        cell_markers = df.MeshFunction("bool", m, 2)
        origin = df.Point(0.0, 0.0)
        for cell in df.cells(m):
            p = cell.midpoint()
            x = p.x()
            y = p.y()

            k_p = 1.6-0.2*k
            k_m = 0.4+0.2*k
            rad_x = 0.75*rad_init
            rad_y = 1.25*rad_init
            
            if (bool(p.distance(origin) < k_p*rad_init and
                     p.distance(origin) > k_m*rad_init)
                or bool((x/rad_x)**2 + (y/rad_y)**2 < k_p**2 and
                        (x/rad_x)**2 + (y/rad_y)**2 > k_m**2)
                or bool((x/rad_y)**2 + (y/rad_x)**2 < k_p**2 and
                        (x/rad_y)**2 + (y/rad_x)**2 > k_m**2)
                or p.y() < 0.5 - k*0.2):
                cell_markers[cell] = True
            else:
                cell_markers[cell] = False
        m = df.refine(m, cell_markers)
    return m
Пример #5
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
Пример #6
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())
Пример #7
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
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
Пример #9
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)
Пример #10
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)
Пример #11
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
def test_basic_interior_facet_assembly():

    ghost_mode = dolfin.cpp.mesh.GhostMode.none
    if (dolfin.MPI.size(dolfin.MPI.comm_world) > 1):
        ghost_mode = dolfin.cpp.mesh.GhostMode.shared_facet

    mesh = dolfin.RectangleMesh(
        dolfin.MPI.comm_world,
        [numpy.array([0.0, 0.0, 0.0]),
         numpy.array([1.0, 1.0, 0.0])], [5, 5],
        cell_type=dolfin.cpp.mesh.CellType.Type.triangle,
        ghost_mode=ghost_mode)

    V = dolfin.function.FunctionSpace(mesh, ("DG", 1))
    u, v = dolfin.TrialFunction(V), dolfin.TestFunction(V)

    a = ufl.inner(ufl.avg(u), ufl.avg(v)) * ufl.dS

    A = dolfin.fem.assemble_matrix(a)
    A.assemble()
    assert isinstance(A, PETSc.Mat)

    L = ufl.conj(ufl.avg(v)) * ufl.dS

    b = dolfin.fem.assemble_vector(L)
    b.assemble()
    assert isinstance(b, PETSc.Vec)
Пример #13
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
Пример #14
0
    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)
Пример #15
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
Пример #16
0
def test_mesh_is_periodic(tmpdir):
    """

    """
    os.chdir(str(tmpdir))

    # Create a bunch of 2D meshes with different periodicity
    # and check that we detect this periodicity correctly.
    mesh1 = create_periodic_mesh(periodicity='none', dim=2)
    assert not mesh_is_periodic(mesh1, 'x')
    #assert not mesh_is_periodic(mesh1, 'y')
    assert not mesh_is_periodic(mesh1, 'xy')

    mesh2 = create_periodic_mesh(periodicity='x', dim=2)
    assert mesh_is_periodic(mesh2, 'x')
    #assert not mesh_is_periodic(mesh2, 'y')
    assert not mesh_is_periodic(mesh2, 'xy')

    mesh3 = create_periodic_mesh(periodicity='y', dim=2)
    assert not mesh_is_periodic(mesh3, 'x')
    #assert mesh_is_periodic(mesh3, 'y')
    assert not mesh_is_periodic(mesh3, 'xy')

    mesh4 = create_periodic_mesh(periodicity='xy', dim=2)
    assert mesh_is_periodic(mesh4, 'x')
    #assert mesh_is_periodic(mesh4, 'y')
    assert mesh_is_periodic(mesh4, 'xy')

    mesh_rectangle = df.RectangleMesh(df.Point(0, 0), df.Point(20, 10), 12, 8)
    assert mesh_is_periodic(mesh_rectangle, 'x')
    #assert mesh_is_periodic(mesh_rectangle, 'y')
    assert mesh_is_periodic(mesh_rectangle, 'xy')

    # Repeat this process for a bunch of 3D meshes with
    # different periodicity.
    mesh5 = create_periodic_mesh(periodicity='none', dim=3)
    assert not mesh_is_periodic(mesh5, 'x')
    #assert not mesh_is_periodic(mesh5, 'y')
    assert not mesh_is_periodic(mesh5, 'xy')

    mesh6 = create_periodic_mesh(periodicity='x', dim=3)
    assert mesh_is_periodic(mesh6, 'x')
    #assert not mesh_is_periodic(mesh6, 'y')
    assert not mesh_is_periodic(mesh6, 'xy')

    mesh7 = create_periodic_mesh(periodicity='y', dim=3)
    assert not mesh_is_periodic(mesh7, 'x')
    #assert mesh_is_periodic(mesh7, 'y')
    assert not mesh_is_periodic(mesh7, 'xy')

    mesh8 = create_periodic_mesh(periodicity='xy', dim=3)
    assert mesh_is_periodic(mesh8, 'x')
    #assert mesh_is_periodic(mesh8, 'y')
    assert mesh_is_periodic(mesh8, 'xy')

    mesh_box = df.BoxMesh(df.Point(0, 0, 0), df.Point(20, 10, 5), 12, 8, 3)
    assert mesh_is_periodic(mesh_box, 'x')
    #assert mesh_is_periodic(mesh_box, 'y')
    assert mesh_is_periodic(mesh_box, 'xy')
def hyper_rectangle(first_point, second_point, n_points=10):
    assert isinstance(first_point, (tuple, list))
    assert isinstance(second_point, (tuple, list))
    dim = len(first_point)
    assert dim == 2 or dim == 3
    assert len(second_point) == dim
    assert all(
        all(isinstance(x, float) for x in p)
        for p in (first_point, second_point))
    assert all(y - x > 0.0 for x, y in zip(first_point, second_point))
    corner_points = (dlfn.Point(*first_point), dlfn.Point(*second_point))

    assert isinstance(n_points, (int, tuple, list))
    if isinstance(n_points, (tuple, list)):
        assert all(isinstance(n, int) and n > 0 for n in n_points)
        assert len(n_points) == dim
    else:
        n_points > 0
        n_points = (n_points, ) * dim

    # mesh generation
    if dim == 2:

        mesh = dlfn.RectangleMesh(*corner_points, *n_points)
    else:
        mesh = dlfn.BoxMesh(*corner_points, *n_points)
    assert dim == mesh.topology().dim()

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

    # mark boundaries
    BoundaryMarkers = HyperCubeBoundaryMarkers

    gamma01 = dlfn.CompiledSubDomain("near(x[0], val) && on_boundary",
                                     val=first_point[0])
    gamma02 = dlfn.CompiledSubDomain("near(x[0], val) && on_boundary",
                                     val=second_point[0])
    gamma03 = dlfn.CompiledSubDomain("near(x[1], val) && on_boundary",
                                     val=first_point[1])
    gamma04 = dlfn.CompiledSubDomain("near(x[1], val) && on_boundary",
                                     val=second_point[1])

    gamma01.mark(facet_marker, BoundaryMarkers.left.value)
    gamma02.mark(facet_marker, BoundaryMarkers.right.value)
    gamma03.mark(facet_marker, BoundaryMarkers.bottom.value)
    gamma04.mark(facet_marker, BoundaryMarkers.top.value)

    if dim == 3:
        gamma05 = dlfn.CompiledSubDomain("near(x[2], val) && on_boundary",
                                         val=first_point[2])
        gamma06 = dlfn.CompiledSubDomain("near(x[2], val) && on_boundary",
                                         val=second_point[2])

        gamma05.mark(facet_marker, BoundaryMarkers.back.value)
        gamma06.mark(facet_marker, BoundaryMarkers.front.value)

    return mesh, facet_marker
Пример #18
0
    def get_domain(self):
        """
        Define the Finite Element domain for the problem
        """

        # Finite Element Mesh in solid
        self.ice_mesh = dolfin.RectangleMesh(dolfin.Point(self.w0,self.zmin),dolfin.Point(self.wf,self.zmax),self.n,self.n)
        self.ice_V = dolfin.FunctionSpace(self.ice_mesh,'CG',1)

        self.flags.append('get_domain')
Пример #19
0
def mesh(Lx=1., Ly=2., grid_spacing=1./16., **namespace):
    m = df.RectangleMesh(df.Point(0., 0.), df.Point(Lx, Ly),
                            int(Lx/grid_spacing), int(Ly/grid_spacing))
    x = m.coordinates()

    beta = 1.

    x[:, 1] = beta*x[:, 1] + (1.-beta)*0.5*Ly*(1 + np.arctan(
        np.pi*((x[:, 1]-0.5*Ly) / (0.5*Ly)))/np.arctan(np.pi))
    return m
Пример #20
0
def test_dmi_uses_unit_length_2dmesh():
    """
    Set up a helical state in two meshes (one expressed in SI units
    the other expressed in nanometers) and compute energies and fields.

    """
    A = 8.78e-12  # J/m
    D = 1.58e-3  # J/m^2
    Ms = 3.84e5  # A/m

    energies = []

    # unit_lengths 1e-9 and 1 are common, let's throw in an intermediate length
    # just to challenge the system a little:
    for unit_length in (1, 1e-4, 1e-9):
        radius = 200e-9 / unit_length
        maxh = 5e-9 / unit_length
        helical_period = (4 * pi * A / D) / unit_length
        k = 2 * pi / helical_period
        # HF 27 April 2014: The next command fails in dolfin 1.3
        # mesh = df.CircleMesh(df.Point(0, 0), radius, maxh)
        # The actual shape of the domain shouldn't matter for the test,
        # so let's use a Rectangular mesh which should work the same:

        nx = ny = int(round(radius / maxh))
        mesh = df.RectangleMesh(df.Point(0, 0), df.Point(radius, radius), nx,
                                ny)

        S3 = df.VectorFunctionSpace(mesh, "CG", 1, dim=3)
        m_expr = df.Expression(("0", "cos(k * x[0])", "sin(k * x[0])"),
                               k=k,
                               degree=1)
        m = Field(S3, m_expr, name='m')
        dmi = DMI(D)
        Ms_dg = Field(df.FunctionSpace(mesh, 'DG', 0), Ms)
        dmi.setup(m, Ms_dg, unit_length=unit_length)
        energies.append(dmi.compute_energy())

        H = df.Function(S3)
        H.vector()[:] = dmi.compute_field()
        print H(0.0, 0.0)

        print "Using unit_length = {}.".format(unit_length)
        print "Helical period {}.".format(helical_period)
        print "Energy {}.".format(dmi.compute_energy())

    rel_diff_energies = abs(energies[0] - energies[1]) / abs(energies[1])
    print "Relative difference of energy {}.".format(rel_diff_energies)
    assert rel_diff_energies < 1e-13

    rel_diff_energies2 = abs(energies[0] - energies[2]) / abs(energies[2])
    print "Relative difference2 of energy {}.".format(rel_diff_energies2)
    assert rel_diff_energies2 < 1e-13
Пример #21
0
def rectangle_mesh(p0, p1, nx, ny, diagonal="left/right"):
    '''
    Parameters
    ----------
    nx: int
        Number of cells along x-axis.
    ny (optional): int
        Number of cells along y-axis.
    diagonal: str
        Possible options: "left/right", "crossed", "left", or "right".

    '''

    return dolfin.RectangleMesh(dolfin.Point(p0), dolfin.Point(p1), nx, ny, diagonal)
Пример #22
0
def test_global_area_2D():
    """FenicsPart method global_aera, for a 2D part"""
    L_x, L_y = 10.0, 4.0
    mesh = fe.RectangleMesh(fe.Point(0.0, 0.0), fe.Point(L_x, L_y), 10, 10)
    material = {"0": mat.Material(1.0, 0.3, "cp")}
    dimensions = np.array(((L_x, 0.0), (0.0, L_y)))
    rect_part = part.FenicsPart(
        mesh,
        materials=material,
        subdomains=None,
        global_dimensions=dimensions,
        facet_regions=None,
    )
    assert rect_part.global_area == approx(40.0, rel=1e-10)
Пример #23
0
def test_bndModel():

    Lx, Ly, Nx, Ny, NxyMicro = 2.0, 0.5, 12, 4, 50
    singleScaleFile = resultFolder + "bar_single_scale.xdmf"
    multiScaleFile = resultFolder + "bar_multiscale_standalone_%s.xdmf"
    start = timer()
    print("simulating single scale")
    os.system("python bar_single_scale.py %d %d" % (Nx, Ny))
    end = timer()
    print('finished in ', end - start)

    for bndModel in ['per', 'lin', 'MR', 'lag']:
        suffix = "{0} {1} {2} {3} > log_{3}.txt".format(
            Nx, Ny, NxyMicro, bndModel)

        start = timer()
        print("simulating using " + bndModel)
        os.system("python bar_multiscale_standalone.py " + suffix)
        end = timer()
        print('finished in ', end - start)

    mesh = df.RectangleMesh(df.Point(0.0, 0.0), df.Point(Lx, Ly), Nx, Ny,
                            "right/left")

    Uh = df.VectorFunctionSpace(mesh, "Lagrange", 1)

    uh0 = df.Function(Uh)

    with df.XDMFFile(resultFolder + "bar_single_scale.xdmf") as f:
        f.read_checkpoint(uh0, 'u')

    error = {}
    ehtemp = df.Function(Uh)

    for bndModel in ['per', 'lin', 'MR', 'lag']:

        with df.XDMFFile(multiScaleFile % bndModel) as f:
            f.read_checkpoint(ehtemp, 'u')

        ehtemp.vector().set_local(ehtemp.vector().get_local()[:] -
                                  uh0.vector().get_local()[:])

        error[bndModel] = df.norm(ehtemp)
        print(error[bndModel])

    assert np.abs(error['lin'] - error['lag']) < 1e-12
    assert np.abs(error['per'] - 0.006319071443377064) < 1e-12
    assert np.abs(error['lin'] - 0.007901978018038507) < 1e-12
    assert np.abs(error['MR'] - 0.0011744201374588351) < 1e-12
Пример #24
0
def spinwaves_to_vtk(points, mesh, data_fun, component, directory=""):
    rs, ts, delta_mj_t = spinwaves(points, mesh, data_fun, component)
    mesh = df.RectangleMesh(df.Point(ts[0] * 1e12, rs[0] * 1e9),
                            df.Point(ts[-1] * 1e12, rs[-1] * 1e9),
                            len(ts) - 1,
                            len(rs) - 1)

    excitation_data = np.swapaxes(delta_mj_t, 0, 1).reshape(-1)
    S1 = df.FunctionSpace(mesh, "CG", 1)
    excitation = df.Function(S1)
    excitation.rename("delta_m{}_t".format(component), "excitation")
    excitation.vector()[:] = excitation_data

    f = df.File(os.path.join(directory, "excitation.pvd"), "compressed")
    f << excitation
Пример #25
0
def test_value_set_update():
    """
    Test to check that the value member variable updates when set_value is
    called.
    """
    init_value = [1., 2., 3.]
    second_value = [100., 200., 400.]

    zeeman = Zeeman(init_value)
    mesh = df.RectangleMesh(df.Point(0, 0), df.Point(1, 1), 10, 10)
    sim = finmag.Simulation(mesh, 1e5)
    sim.add(zeeman)
    zeeman.set_value(second_value)

    assert zeeman.value == second_value
Пример #26
0
def cubic_anisotropy(K1=520e3, K2=0, K3=0):
    mesh = df.RectangleMesh(df.Point(0, 0), df.Point(50, 2), 20, 1)

    sim = Simulation(mesh, Ms, unit_length=1e-9)
    sim.set_m(m_init)

    sim.add(
        CubicAnisotropy(K1=K1,
                        K2=K2,
                        K3=K3,
                        u1=(1, 0, 0),
                        u2=(0, 1, 0),
                        assemble=False))

    field1 = sim.effective_field()
Пример #27
0
def mesh2d(inner, outer, *meshres, stefan=True):
    origin = dolfin.Point(0., 0.)
    if stefan:
        geometry = mshr.Circle(origin, outer, 2 * meshres[0]) - mshr.Circle(
            origin, inner, int(0.5 * meshres[0]))
        mesh = mshr.generate_mesh(geometry, meshres[0])
        mesh.init()
        # Construct of the facet markers:
        boundary = (dolfin.MeshFunction("size_t", mesh,
                                        mesh.topology().dim() - 1, 0), {})
        for f in dolfin.facets(mesh):
            if f.midpoint().distance(origin) <= inner and f.exterior():
                boundary[0][f] = 1  # inner radius
                boundary[1]['inner'] = 1
            elif f.midpoint().distance(origin) >= (inner +
                                                   outer) / 2 and f.exterior():
                boundary[0][f] = 2  # outer radius
                boundary[1]['outer'] = 2
        # Definition of measures and normal vector:
        n = dolfin.FacetNormal(mesh)
        dx = dolfin.Measure("dx", mesh)
        ds = dolfin.Measure("ds", domain=mesh, subdomain_data=boundary[0])
    else:
        width = inner
        height = outer
        mesh = dolfin.RectangleMesh(origin, Point(width, height), meshres[0],
                                    meshres[1])
        mesh.init()
        boundary = (dolfin.MeshFunction("size_t", mesh,
                                        mesh.topology().dim() - 1, 0), {})
        for f in dolfin.facets(mesh):
            if dolfin.near(f.midpoint()[1], 0.):
                boundary[0][f] = 1  # bottom
                boundary[1]['bottom'] = 1
            elif dolfin.near(f.midpoint()[1], height):
                boundary[0][f] = 2  # top
                boundary[1]['top'] = 2
            elif dolfin.near(f.midpoint()[0], 0.):
                boundary[0][f] = 3  # left
                boundary[1]['left'] = 3
            elif dolfin.near(f.midpoint()[0], width):
                boundary[0][f] = 4  # right
                boundary[1]['right'] = 4
        # Definition of measures and normal vector:
        n = dolfin.FacetNormal(mesh)
        dx = dolfin.Measure("dx", mesh)
        ds = dolfin.Measure("ds", subdomain_data=boundary[0])
    return (mesh, boundary, n, dx, ds)
Пример #28
0
    def test_periodic_solver():
        # mesh = Mesh("demos/mesh/rectangle_periodic.xml")
        Lx = 2 * df.DOLFIN_PI
        Ly = 2 * df.DOLFIN_PI
        Nx = 256
        Ny = 256
        mesh = df.RectangleMesh(df.Point(0, 0), df.Point(Lx, Ly), Nx, Ny)

        d = mesh.geometry().dim()
        L = np.empty(2 * d)
        for i in range(d):
            l_min = mesh.coordinates()[:, i].min()
            l_max = mesh.coordinates()[:, i].max()
            L[i] = l_min
            L[d + i] = l_max

        PBC = PeriodicBoundary([Lx, Ly])
        V = df.FunctionSpace(mesh, "CG", 1, constrained_domain=PBC)

        class Source(df.Expression):
            def eval(self, values, x):
                values[0] = np.sin(x[0])

        class Exact(df.Expression):
            def eval(self, values, x):
                values[0] = np.sin(x[0])

        f = Source(degree=2)
        phi_e = Exact(degree=2)

        poisson = PoissonSolver(V, remove_null_space=True)
        phi = poisson.solve(f)

        # error_l2 = errornorm(phi_e, phi, "L2")
        # print("l2 norm: ", error_l2)

        vertex_values_phi_e = phi_e.compute_vertex_values(mesh)
        vertex_values_phi = phi.compute_vertex_values(mesh)

        error_max = np.max(vertex_values_phi_e - \
                            vertex_values_phi)
        tol = 1E-9
        msg = 'error_max = %g' % error_max
        print(msg)
        assert error_max < tol, msg

        df.plot(phi, interactive=True)
        df.plot(phi_e, mesh=mesh, interactive=True)
Пример #29
0
def test_parallel():

    Lx, Ly, Ny, Nx, NxyMicro = 0.5, 2.0, 12, 5, 50
    bndModel = 'per'
    suffix = "%d %d %d %s > log_%s.txt" % (Nx, Ny, NxyMicro, bndModel,
                                           bndModel)

    start = timer()
    print("simulating single core")
    os.system("python bar_multiscale_standalone.py " + suffix)
    end = timer()
    print('finished in ', end - start)

    for nProc in [1, 2, 3, 4]:
        start = timer()
        print("simulating using nProc", nProc)
        os.system("mpirun -n %d python bar_multiscale_parallel.py " % nProc +
                  suffix)
        end = timer()
        print('finished in ', end - start)

    mesh = df.RectangleMesh(df.Point(0.0, 0.0), df.Point(Lx, Ly), Nx, Ny,
                            "right/left")

    Uh = df.VectorFunctionSpace(mesh, "Lagrange", 1)

    uh0 = df.Function(Uh)

    with df.XDMFFile("bar_multiscale_standalone_%s.xdmf" % bndModel) as f:
        f.read_checkpoint(uh0, 'u')

    error = {}
    ehtemp = df.Function(Uh)

    for nProc in [1, 2, 3, 4]:

        with df.XDMFFile("bar_multiscale_parallel_%s_np%d.xdmf" %
                         (bndModel, nProc)) as f:
            f.read_checkpoint(ehtemp, 'u')

        ehtemp.vector().set_local(ehtemp.vector().get_local()[:] -
                                  uh0.vector().get_local()[:])

        error[nProc] = df.norm(ehtemp)

    assert np.max(np.array(list(error.values()))) < 1e-13
Пример #30
0
    def test_save_fenics_function(self):
        nx, ny, degree = 31, 31, 2
        mesh = dl.RectangleMesh(dl.Point(0, 0), dl.Point(1, 1), nx, ny)
        function_space = dl.FunctionSpace(mesh, "Lagrange", degree)

        import os
        import tempfile
        fd, filename = tempfile.mkstemp()

        try:
            function1 = dl.Function(function_space)
            save_fenics_function(function1, filename)
            function2 = load_fenics_function(function_space, filename)
        finally:
            os.remove(filename)
        assert (dl.errornorm(function1, function2)) < 1e-15

        msg = 'Warning save_fenics_function does not work if calling load function again'