Exemple #1
0
        def __init__(self, mesh_path=None):
            self.global_preprocessing_time = Stopwatch()
            self.local_preprocessing_time = Stopwatch()
            self.solving_time = Stopwatch()

            if mesh_path is not None:
                self.PATH = mesh_path

            logger.debug('Loading mesh...')

            # with XDMFFile(self.PATH + '.xdmf') as fh:
            #     self._mesh = Mesh()
            #     fh.read(self._mesh)
            #
            # with XDMFFile(self.PATH + '_boundaries.xdmf') as fh:
            #     mvc = MeshValueCollection("size_t", self._mesh, 2)
            #     fh.read(mvc, "boundaries")
            #     self._boundaries = cpp.mesh.MeshFunctionSizet(self._mesh, mvc)
            #
            # with XDMFFile(self.PATH + '_subdomains.xdmf') as fh:
            #     mvc = MeshValueCollection("size_t", self._mesh, 3)
            #     fh.read(mvc, "subdomains")
            #     self._subdomains = cpp.mesh.MeshFunctionSizet(self._mesh, mvc)

            self._mesh = Mesh(self.PATH + '.xml')
            self._subdomains = MeshFunction("size_t", self._mesh,
                                            self.PATH + '_physical_region.xml')
            self._boundaries = MeshFunction("size_t", self._mesh,
                                            self.PATH + '_facet_region.xml')

            logger.debug('Done.')
            self._degree = None
Exemple #2
0
	def __init__(self, x0, y0, z0, R, n):
		class SphereSurface(SubDomain):
			def inside(self, x, on_boundary):
				return on_boundary
		class X_Symmetric(SubDomain):
			def inside(self, x, on_boundary):
				return near(x[0], x0)
		class Y_Symmetric(SubDomain):
			def inside(self, x, on_boundary):
				return near(x[1], y0)
		class Z_Symmetric(SubDomain):
			def inside(self, x, on_boundary):
				return near(x[2], z0)
		self.geometry = Sphere(Point(x0, y0, z0), R, segments=n) - Box(Point(x0 + R, y0, z0 - R), Point(x0 - R, y0 - R, z0 + R)) - Box(Point(x0 - R, y0 + R, z0), Point(x0 + R, y0, z0 - R)) - Box(Point(x0, y0, z0), Point(x0 - R, y0 + R, z0 + R))
		self.mesh = generate_mesh(self.geometry, n)
		self.domains = MeshFunction("size_t", self.mesh, self.mesh.topology().dim())
		self.domains.set_all(0)
		self.dx = Measure('dx', domain=self.mesh, subdomain_data=self.domains)
		self.boundaries = MeshFunction("size_t", self.mesh, self.mesh.topology().dim()-1)
		self.boundaries.set_all(0)
		self.sphereSurface = SphereSurface()
		self.sphereSurface.mark(self.boundaries, 1)
		self.x_symmetric = X_Symmetric()
		self.x_symmetric.mark(self.boundaries, 2)
		self.y_symmetric = Y_Symmetric()
		self.y_symmetric.mark(self.boundaries, 3)
		self.z_symmetric = Z_Symmetric()
		self.z_symmetric.mark(self.boundaries, 4)
		self.ds = Measure('ds', domain=self.mesh, subdomain_data=self.boundaries)
		self.dS = Measure('dS', domain=self.mesh, subdomain_data=self.boundaries)
Exemple #3
0
def test_meshfunction_where_equal():
    mesh = UnitSquareMesh(MPI.comm_self, 2, 2)

    cf = MeshFunction("size_t", mesh, mesh.topology.dim, 0)
    cf.set_all(1)
    cf[0] = 3
    cf[3] = 3
    assert list(cf.where_equal(3)) == [0, 3]
    assert list(cf.where_equal(1)) == [1, 2, 4, 5, 6, 7]

    ff = MeshFunction("size_t", mesh, mesh.topology.dim - 1, 100)
    ff.set_all(0)
    ff[0] = 1
    ff[2] = 3
    ff[3] = 3
    assert list(ff.where_equal(1)) == [0]
    assert list(ff.where_equal(3)) == [2, 3]
    assert list(ff.where_equal(0)) == [1] + list(range(4, ff.size()))

    vf = MeshFunction("size_t", mesh, 0, 0)
    vf.set_all(3)
    vf[1] = 1
    vf[2] = 1
    assert list(vf.where_equal(1)) == [1, 2]
    assert list(vf.where_equal(3)) == [0] + list(range(3, vf.size()))
Exemple #4
0
def test_mesh_function_assign_2D_cells():
    mesh = UnitSquareMesh(MPI.comm_world, 3, 3)
    ncells = mesh.num_cells()
    f = MeshFunction("int", mesh, mesh.topology.dim, 0)
    for cell in Cells(mesh):
        f[cell] = ncells - cell.index()

    g = MeshValueCollection("int", mesh, 2)
    g.assign(f)
    assert ncells == f.size()
    assert ncells == g.size()

    f2 = MeshFunction("int", mesh, g, 0)

    for cell in Cells(mesh):
        value = ncells - cell.index()
        assert value == g.get_value(cell.index(), 0)
        assert f2[cell] == g.get_value(cell.index(), 0)

    h = MeshValueCollection("int", mesh, 2)
    global_indices = mesh.topology.global_indices(2)
    ncells_global = mesh.num_entities_global(2)
    for cell in Cells(mesh):
        if global_indices[cell.index()] in [5, 8, 10]:
            continue
        value = ncells_global - global_indices[cell.index()]
        h.set_value(cell.index(), int(value))

    f3 = MeshFunction("int", mesh, h, 0)

    values = f3.array()
    values[values > ncells_global] = 0.

    assert MPI.sum(mesh.mpi_comm(), values.sum() * 1.0) == 140.
Exemple #5
0
def test_mesh_function_assign_2D_facets():
    mesh = UnitSquareMesh(MPI.comm_world, 3, 3)
    mesh.create_entities(1)
    tdim = mesh.topology.dim
    num_cell_facets = cpp.mesh.cell_num_entities(mesh.cell_type, tdim - 1)

    f = MeshFunction("int", mesh, tdim - 1, 25)
    connectivity = mesh.topology.connectivity(tdim, tdim - 1)
    for c in range(mesh.num_cells()):
        facets = connectivity.connections(c)
        for i in range(num_cell_facets):
            assert 25 == f.values[facets[i]]

    g = MeshValueCollection("int", mesh, 1)
    g.assign(f)
    assert mesh.num_entities(tdim - 1) == len(f.values)
    assert mesh.num_cells() * 3 == g.size()
    for c in range(mesh.num_cells()):
        for i in range(num_cell_facets):
            assert 25 == g.get_value(c, i)

    f2 = MeshFunction("int", mesh, g, 0)

    connectivity = mesh.topology.connectivity(tdim, tdim - 1)
    for c in range(mesh.num_cells()):
        facets = connectivity.connections(c)
        for i in range(num_cell_facets):
            assert f2.values[facets[i]] == g.get_value(c, i)
Exemple #6
0
def test_mesh_function_assign_2D_cells():
    mesh = UnitSquareMesh(MPI.comm_world, 3, 3)
    ncells = mesh.num_cells()
    f = MeshFunction("int", mesh, mesh.topology.dim, 0)
    for c in range(ncells):
        f.values[c] = ncells - c

    g = MeshValueCollection("int", mesh, 2)
    g.assign(f)
    assert ncells == len(f.values)
    assert ncells == g.size()

    f2 = MeshFunction("int", mesh, g, 0)

    for c in range(mesh.num_cells()):
        value = ncells - c
        assert value == g.get_value(c, 0)
        assert f2.values[c] == g.get_value(c, 0)

    h = MeshValueCollection("int", mesh, 2)
    global_indices = mesh.topology.global_indices(2)
    ncells_global = mesh.num_entities_global(2)
    for c in range(mesh.num_cells()):
        if global_indices[c] in [5, 8, 10]:
            continue
        value = ncells_global - global_indices[c]
        h.set_value(c, int(value))

    f3 = MeshFunction("int", mesh, h, 0)

    values = f3.values
    values[values > ncells_global] = 0.

    assert MPI.sum(mesh.mpi_comm(), values.sum() * 1.0) == 140.
Exemple #7
0
def test_append_and_load_mesh_functions(tempdir, encoding, data_type):
    if invalid_config(encoding):
        pytest.skip("XDMF unsupported in current configuration")

    dtype_str, dtype = data_type

    meshes = [
        UnitSquareMesh(MPI.comm_world, 12, 12),
        UnitCubeMesh(MPI.comm_world, 2, 2, 2)
    ]

    for mesh in meshes:
        dim = mesh.topology.dim

        vf = MeshFunction(dtype_str, mesh, 0, 0)
        vf.rename("vertices")
        ff = MeshFunction(dtype_str, mesh, mesh.topology.dim - 1, 0)
        ff.rename("facets")
        cf = MeshFunction(dtype_str, mesh, mesh.topology.dim, 0)
        cf.rename("cells")

        if (MPI.size(mesh.mpi_comm()) == 1):
            for vertex in Vertices(mesh):
                vf[vertex] = dtype(vertex.index())
            for facet in Facets(mesh):
                ff[facet] = dtype(facet.index())
            for cell in Cells(mesh):
                cf[cell] = dtype(cell.index())
        else:
            for vertex in Vertices(mesh):
                vf[vertex] = dtype(vertex.global_index())
            for facet in Facets(mesh):
                ff[facet] = dtype(facet.global_index())
            for cell in Cells(mesh):
                cf[cell] = dtype(cell.global_index())

        filename = os.path.join(tempdir, "appended_mf_%dD.xdmf" % dim)

        with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as xdmf:
            xdmf.write(mesh)
            xdmf.write(vf)
            xdmf.write(ff)
            xdmf.write(cf)

        with XDMFFile(mesh.mpi_comm(), filename) as xdmf:
            read_function = getattr(xdmf, "read_mf_" + dtype_str)
            vf_in = read_function(mesh, "vertices")
            ff_in = read_function(mesh, "facets")
            cf_in = read_function(mesh, "cells")

        diff = 0
        for vertex in Vertices(mesh):
            diff += (vf_in[vertex] - vf[vertex])
        for facet in Facets(mesh):
            diff += (ff_in[facet] - ff[facet])
        for cell in Cells(mesh):
            diff += (cf_in[cell] - cf[cell])
        assert diff == 0
Exemple #8
0
 def refine_meshes(self, subdomain):
     sub1_marker = MeshFunction("bool", self.mesh1,
                                self.mesh1.topology().dim())
     sub2_marker = MeshFunction("bool", self.mesh2,
                                self.mesh2.topology().dim())
     subdomain.mark(sub1_marker, True)
     subdomain.mark(sub2_marker, True)
     self.mesh1 = refine(self.mesh1, sub1_marker)
     self.mesh2 = refine(self.mesh2, sub2_marker)
Exemple #9
0
def read_mesh():
    # mesh = Mesh("data/backward_facing_step.xml")
    # subdomains = MeshFunction("size_t", mesh, "data/backward_facing_step_physical_region.xml")
    # boundaries = MeshFunction("size_t", mesh, "data/backward_facing_step_facet_region.xml")
    mesh = Mesh("data/hyperelastic_cube.xml")
    subdomains = MeshFunction("size_t", mesh, "data/hyperelastic_cube_physical_region.xml")
    boundaries = MeshFunction("size_t", mesh, "data/hyperelastic_cube_facet_region.xml")
    restrictions = MeshRestriction(mesh, "data/hyperelastic_cube_interface_restriction.rtc.xml")
    return (mesh, subdomains, boundaries, restrictions)
Exemple #10
0
 def mesh_generator(n):
     mesh = UnitSquareMesh(n, n, "left/right")
     dim = mesh.topology().dim()
     domains = MeshFunction("size_t", mesh, dim)
     domains.set_all(0)
     dx = Measure("dx", subdomain_data=domains)
     boundaries = MeshFunction("size_t", mesh, dim - 1)
     boundaries.set_all(0)
     ds = Measure("ds", subdomain_data=boundaries)
     return mesh, dx, ds
Exemple #11
0
def read_h5(h5Path):
    mesh = Mesh()
    hdf = HDF5File(mesh.mpi_comm(), h5Path, 'r')
    hdf.read(mesh, '/mesh', False)
    subdomains = MeshFunction('size_t', mesh, 3)
    boundaries = MeshFunction('size_t', mesh, 2)

    hdf.read(subdomains, '/subdomains')
    hdf.read(boundaries, '/boundaries')

    return mesh, subdomains, boundaries
def show_fenics_mesh(fname):
    # boundary layer, quad element is not supported
    from dolfin import Mesh, MeshFunction, plot, interactive  # TODO: fenicsX may have change API
    mesh = Mesh(fname+".xml")
    if os.path.exists(fname+"_physical_region.xml"):
        subdomains = MeshFunction("size_t", mesh, fname+"_physical_region.xml")
        plot(subdomains)
    if os.path.exists(fname+"_facet_region.xml"):
        boundaries = MeshFunction("size_t", mesh, fname+"_facet_region.xml")
        plot(boundaries)

    plot(mesh)
    interactive()  # FIXME: this event loop may conflict with FreeCAD GUI's
Exemple #13
0
def test_append_and_load_mesh_value_collections(tempdir, encoding, data_type):
    if invalid_config(encoding):
        pytest.skip("XDMF unsupported in current configuration")

    dtype_str, dtype = data_type

    mesh = UnitCubeMesh(MPI.comm_world, 2, 2, 2)
    mesh.init()
    for d in range(mesh.geometry.dim + 1):
        mesh.init_global(d)

    mvc_v = MeshValueCollection(dtype_str, mesh, 0)
    mvc_v.rename("vertices")
    mvc_e = MeshValueCollection(dtype_str, mesh, 1)
    mvc_e.rename("edges")
    mvc_f = MeshValueCollection(dtype_str, mesh, 2)
    mvc_f.rename("facets")
    mvc_c = MeshValueCollection(dtype_str, mesh, 3)
    mvc_c.rename("cells")

    mvcs = [mvc_v, mvc_e, mvc_f, mvc_c]

    filename = os.path.join(tempdir, "appended_mvcs.xdmf")
    with XDMFFile(mesh.mpi_comm(), filename) as xdmf:
        for mvc in mvcs:
            for ent in MeshEntities(mesh, mvc.dim):
                assert (mvc.set_value(ent.index(), dtype(ent.global_index())))
            xdmf.write(mvc)

    mvc_v_in = MeshValueCollection(dtype_str, mesh, 0)
    mvc_e_in = MeshValueCollection(dtype_str, mesh, 1)
    mvc_f_in = MeshValueCollection(dtype_str, mesh, 2)
    mvc_c_in = MeshValueCollection(dtype_str, mesh, 3)

    with XDMFFile(mesh.mpi_comm(), filename) as xdmf:
        read_function = getattr(xdmf, "read_mvc_" + dtype_str)
        mvc_v_in = read_function(mesh, "vertices")
        mvc_e_in = read_function(mesh, "edges")
        mvc_f_in = read_function(mesh, "facets")
        mvc_c_in = read_function(mesh, "cells")

    mvcs_in = [mvc_v_in, mvc_e_in, mvc_f_in, mvc_c_in]

    for (mvc, mvc_in) in zip(mvcs, mvcs_in):
        mf = MeshFunction(dtype_str, mesh, mvc, 0)
        mf_in = MeshFunction(dtype_str, mesh, mvc_in, 0)

        diff = 0
        for ent in MeshEntities(mesh, mf.dim):
            diff += (mf_in[ent] - mf[ent])
        assert (diff == 0)
Exemple #14
0
def test_Create(cube):
    """Create MeshFunctions."""

    v = MeshFunction("size_t", cube, 0, 0)
    assert v.size() == cube.num_vertices()

    v = MeshFunction("size_t", cube, 1, 0)
    assert v.size() == cube.num_entities(1)

    v = MeshFunction("size_t", cube, 2, 0)
    assert v.size() == cube.num_facets()

    v = MeshFunction("size_t", cube, 3, 0)
    assert v.size() == cube.num_cells()
 def _read(self, mesh, filename, encoding=None):
     assert filename.endswith(".rtc.xml") or filename.endswith(".rtc.xdmf")
     # Read in MeshFunctions
     D = mesh.topology().dim()
     for d in range(D + 1):
         if filename.endswith(".rtc.xml"):
             mesh_function_d = MeshFunction("bool", mesh, filename + "/mesh_function_" + str(d) + ".xml")
         else:
             mesh_function_d = MeshFunction("bool", mesh, d)
             xdmf_file = XDMFFile(filename + "/mesh_function_" + str(d) + ".xdmf")
             if encoding is not None:
                 xdmf_file.read(mesh_function_d, encoding)
             else:
                 xdmf_file.read(mesh_function_d)
         self.append(mesh_function_d)
Exemple #16
0
def test_mesh_function_assign_2D_vertices():
    mesh = UnitSquareMesh(MPI.comm_world, 3, 3)
    mesh.create_entities(0)
    f = MeshFunction("int", mesh, 0, 25)
    g = MeshValueCollection("int", mesh, 0)
    g.assign(f)
    assert mesh.num_entities(0) == f.size()
    assert mesh.num_cells() * 3 == g.size()

    f2 = MeshFunction("int", mesh, g, 0)

    for cell in Cells(mesh):
        for i, vert in enumerate(VertexRange(cell)):
            assert 25 == g.get_value(cell.index(), i)
            assert f2[vert] == g.get_value(cell.index(), i)
Exemple #17
0
def test_save_mesh_value_collection(tempdir, encoding, data_type):
    dtype_str, dtype = data_type
    mesh = UnitCubeMesh(MPI.comm_world, 4, 4, 4)
    tdim = mesh.topology.dim
    meshfn = MeshFunction(dtype_str, mesh, mesh.topology.dim, False)
    meshfn.name = "volume_marker"
    mp = cpp.mesh.midpoints(mesh, tdim, range(mesh.num_entities(tdim)))
    for i in range(mesh.num_cells()):
        if mp[i, 1] > 0.1:
            meshfn.values[i] = 1
        if mp[i, 1] > 0.9:
            meshfn.values[i] = 2

    for mvc_dim in range(0, tdim + 1):
        mvc = MeshValueCollection(dtype_str, mesh, mvc_dim)
        tag = "dim_{}_marker".format(mvc_dim)
        mvc.name = tag
        mesh.create_connectivity(mvc_dim, tdim)
        mp = cpp.mesh.midpoints(mesh, mvc_dim,
                                range(mesh.num_entities(mvc_dim)))
        for e in range(mesh.num_entities(mvc_dim)):
            if (mp[e, 0] > 0.5):
                mvc.set_value(e, dtype(1))

        filename = os.path.join(tempdir, "mvc_{}.xdmf".format(mvc_dim))

        with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as xdmf:
            xdmf.write(meshfn)
            xdmf.write(mvc)

        with XDMFFile(mesh.mpi_comm(), filename) as xdmf:
            read_function = getattr(xdmf, "read_mvc_" + dtype_str)
            mvc = read_function(mesh, tag)
Exemple #18
0
def test_save_1d_mesh(tempdir, encoding):
    filename = os.path.join(tempdir, "mf_1D.xdmf")
    mesh = UnitIntervalMesh(MPI.comm_world, 32)
    mf = MeshFunction("size_t", mesh, mesh.topology.dim, 0)
    mf.values[:] = numpy.arange(mesh.num_entities(1))
    with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as file:
        file.write(mf)
Exemple #19
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)
Exemple #20
0
class OCylinderFlowConstant(object):
    'Flow past a cylinder in the bend of O shaped turn. Constant force.'
    name = 'o-cylinder-constant'
    # Forcing
    f = Constant((0., 0.))

    # Mesh and function marking facets
    mesh = Mesh(mesh_path('o-cylinder.xml'))
    f_f = MeshFunction('size_t', mesh,
                       mesh_path('o-cylinder_facet_region.xml'))

    # Inflow and Noslip domains to be used for BC construction
    inflow = [f_f, 18]
    noslip = [f_f, 17]

    # Duration
    T = 10

    # Inflow profile
    U_max = 3.5
    unit = 0.1  # Basic scaling unit for mesh definition
    s = 3  # Arm length of the channel, ALWAYS SYNC THIS VALUE WITH .geo

    u_in = InflowProfileConstant(U_max=U_max,
                                 t=0,
                                 unit=unit,
                                 s=s,
                                 K=T,
                                 compute_width=compute_width_O_cylinder)

    # Reynolds number
    Re = Constant(100)
Exemple #21
0
def convert_meshfunctions_to_submesh(mesh, submesh, meshfunctions_on_mesh):
    assert meshfunctions_on_mesh is None or (isinstance(
        meshfunctions_on_mesh, list) and len(meshfunctions_on_mesh) > 0)
    if meshfunctions_on_mesh is None:
        return None
    meshfunctions_on_submesh = list()
    # Create submesh subdomains
    for mesh_subdomain in meshfunctions_on_mesh:
        submesh_subdomain = MeshFunction("size_t", submesh,
                                         mesh_subdomain.dim())
        submesh_subdomain.set_all(0)
        assert submesh_subdomain.dim() in (submesh.topology().dim(),
                                           submesh.topology().dim() - 1)
        if submesh_subdomain.dim() == submesh.topology().dim():
            for submesh_cell in cells(submesh):
                submesh_subdomain.array()[
                    submesh_cell.index()] = mesh_subdomain.array()[
                        submesh.submesh_to_mesh_cell_local_indices[
                            submesh_cell.index()]]
        elif submesh_subdomain.dim() == submesh.topology().dim() - 1:
            for submesh_facet in facets(submesh):
                submesh_subdomain.array()[
                    submesh_facet.index()] = mesh_subdomain.array()[
                        submesh.submesh_to_mesh_facet_local_indices[
                            submesh_facet.index()]]
        else:  # impossible to arrive here anyway, thanks to the assert
            raise TypeError(
                "Invalid arguments in convert_meshfunctions_to_submesh.")
        meshfunctions_on_submesh.append(submesh_subdomain)
    return meshfunctions_on_submesh
Exemple #22
0
    def test_convert_diffpack(self):
        from dolfin import Mesh, MPI, MeshFunction, mpi_comm_world
        if MPI.size(mpi_comm_world()) != 1:
            return
        fname = os.path.join("data", "diffpack_tet")
        dfname = fname + ".xml"

        # Read triangle file and convert to a dolfin xml mesh file
        meshconvert.diffpack2xml(fname + ".grid", dfname)

        # Read in dolfin mesh and check number of cells and vertices
        mesh = Mesh(dfname)
        self.assertEqual(mesh.num_vertices(), 27)
        self.assertEqual(mesh.num_cells(), 48)
        self.assertEqual(len(mesh.domains().markers(3)), 48)
        self.assertEqual(len(mesh.domains().markers(2)), 16)

        mf_basename = dfname.replace(".xml", "_marker_%d.xml")
        for marker, num in [(3, 9), (6, 9), (7, 3), (8, 1)]:

            mf_name = mf_basename % marker
            mf = MeshFunction("size_t", mesh, mf_name)
            self.assertEqual(sum(mf.array() == marker), num)
            os.unlink(mf_name)

        # Clean up
        os.unlink(dfname)
def boundaries(mesh):
    boundaries = MeshFunction("size_t", mesh, mesh.topology().dim() - 1, 0)
    for f in facets(mesh):
        boundaries.array()[f.index()] = 0
        for v in vertices(f):
            boundaries.array()[f.index()] += v.global_index()
    return boundaries
Exemple #24
0
def test_save_mesh_value_collection(tempdir, encoding, data_type):
    dtype_str, dtype = data_type
    mesh = UnitCubeMesh(MPI.comm_world, 4, 4, 4)
    tdim = mesh.topology.dim
    meshfn = MeshFunction(dtype_str, mesh, mesh.topology.dim, False)
    meshfn.rename("volume_marker")
    for c in Cells(mesh):
        if c.midpoint()[1] > 0.1:
            meshfn[c] = dtype(1)
        if c.midpoint()[1] > 0.9:
            meshfn[c] = dtype(2)

    for mvc_dim in range(0, tdim + 1):
        mvc = MeshValueCollection(dtype_str, mesh, mvc_dim)
        tag = "dim_%d_marker" % mvc_dim
        mvc.rename(tag)
        mesh.init(mvc_dim, tdim)
        for e in MeshEntities(mesh, mvc_dim):
            if (e.midpoint()[0] > 0.5):
                mvc.set_value(e.index(), dtype(1))

        filename = os.path.join(tempdir, "mvc_%d.xdmf" % mvc_dim)

        with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as xdmf:
            xdmf.write(meshfn)
            xdmf.write(mvc)

        with XDMFFile(mesh.mpi_comm(), filename) as xdmf:
            read_function = getattr(xdmf, "read_mvc_" + dtype_str)
            mvc = read_function(mesh, tag)
Exemple #25
0
def test_save_3D_facet_function(tempdir, encoding, data_type):
    dtype_str, dtype = data_type
    mesh = UnitCubeMesh(MPI.comm_world, 4, 4, 4)
    mf = MeshFunction(dtype_str, mesh, mesh.topology.dim - 1, 0)
    mf.rename("facets")

    if (MPI.size(mesh.mpi_comm()) == 1):
        for facet in Facets(mesh):
            mf[facet] = dtype(facet.index())
    else:
        for facet in Facets(mesh):
            mf[facet] = dtype(facet.global_index())
    filename = os.path.join(tempdir, "mf_facet_3D_%s.xdmf" % dtype_str)

    with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as xdmf:
        xdmf.write(mf)

    with XDMFFile(mesh.mpi_comm(), filename) as xdmf:
        read_function = getattr(xdmf, "read_mf_" + dtype_str)
        mf_in = read_function(mesh, "facets")

    diff = 0
    for facet in Facets(mesh):
        diff += (mf_in[facet] - mf[facet])
    assert diff == 0
def test_numpy_access(dtype, mesh):
    dtype_str, dtype = dtype
    mf = MeshFunction(dtype_str, mesh, 0, 0)

    values = mf.values
    values[:] = numpy.random.rand(len(values))
    assert numpy.all(values == mf.values)
Exemple #27
0
def test_multiple_datasets(tempdir, encoding):
    mesh = UnitSquareMesh(MPI.comm_world, 2, 2)
    cf0 = MeshFunction('size_t', mesh, 2, 11)
    cf0.name = 'cf0'
    cf1 = MeshFunction('size_t', mesh, 2, 22)
    cf1.name = 'cf1'
    filename = os.path.join(tempdir, "multiple_mf.xdmf")
    with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as xdmf:
        xdmf.write(mesh)
        xdmf.write(cf0)
        xdmf.write(cf1)
    with XDMFFile(mesh.mpi_comm(), filename) as xdmf:
        mesh = xdmf.read_mesh(cpp.mesh.GhostMode.none)
        cf0 = xdmf.read_mf_size_t(mesh, "cf0")
        cf1 = xdmf.read_mf_size_t(mesh, "cf1")
    assert (cf0.values[0] == 11 and cf1.values[0] == 22)
Exemple #28
0
    def test_convert_diffpack_2d(self):

        from dolfin import Mesh, MPI, MeshFunction

        fname = os.path.join(os.path.dirname(__file__), "data", "diffpack_tri")
        dfname = fname + ".xml"

        # Read triangle file and convert to a dolfin xml mesh file
        meshconvert.diffpack2xml(fname + ".grid", dfname)

        # Read in dolfin mesh and check number of cells and vertices
        mesh = Mesh(dfname)

        self.assertEqual(mesh.num_vertices(), 41)
        self.assertEqual(mesh.num_cells(), 64)
        self.assertEqual(len(mesh.domains().markers(2)), 64)

        mf_basename = dfname.replace(".xml", "_marker_%d.xml")
        for marker, num in [(1, 10), (2, 5), (3, 5)]:

            mf_name = mf_basename % marker
            mf = MeshFunction("size_t", mesh, mf_name)
            self.assertEqual(sum(mf.array() == marker), num)
            os.unlink(mf_name)

        # Clean up
        os.unlink(dfname)
def test_save_and_read_meshfunction_3D(tempdir):
    filename = os.path.join(tempdir, "meshfn-3d.h5")

    # Write to file
    mesh = UnitCubeMesh(MPI.comm_world, 2, 2, 2)
    mf_file = HDF5File(mesh.mpi_comm(), filename, "w")

    # save meshfuns to compare when reading back
    meshfunctions = []
    for i in range(0, 4):
        mf = MeshFunction('double', mesh, i, 0.0)
        # NB choose a value to set which will be the same
        # on every process for each entity
        for cell in MeshEntities(mesh, i):
            mf[cell] = cell.midpoint()[0]
        meshfunctions.append(mf)
        mf_file.write(mf, "/meshfunction/group/%d/meshfun" % i)
    mf_file.close()

    # Read back from file
    mf_file = HDF5File(mesh.mpi_comm(), filename, "r")
    for i in range(0, 4):
        mf2 = mf_file.read_mf_double(mesh,
                                     "/meshfunction/group/%d/meshfun" % i)
        for cell in MeshEntities(mesh, i):
            assert meshfunctions[i][cell] == mf2[cell]
    mf_file.close()
def convert(msh_file, h5_file):
    '''Convert msh file to h5_file'''
    root, _ = os.path.splitext(msh_file)
    assert os.path.splitext(msh_file)[1] == '.msh'
    assert os.path.splitext(h5_file)[1] == '.h5'

    # Get the xml mesh
    xml_file = '.'.join([root, 'xml'])
    subprocess.call(['dolfin-convert %s %s' % (msh_file, xml_file)],
                    shell=True)
    # Success?
    assert os.path.exists(xml_file)

    mesh = Mesh(xml_file)
    out = HDF5File(mesh.mpi_comm(), h5_file, 'w')
    out.write(mesh, 'mesh')

    for region in ('facet_region.xml', ):
        name, _ = region.split('_')
        r_xml_file = '_'.join([root, region])

        f = MeshFunction('size_t', mesh, r_xml_file)
        out.write(f, name)

    # Sucess?
    assert os.path.exists(h5_file)

    return mesh