Esempio n. 1
0
def test_save_and_read_mesh_value_collection(tempdir):
    ndiv = 2
    filename = os.path.join(tempdir, "mesh_value_collection.h5")
    mesh = UnitCubeMesh(MPI.comm_world, ndiv, ndiv, ndiv)

    def point2list(p):
        return [p[0], p[1], p[2]]

    # write to file
    with HDF5File(mesh.mpi_comm(), filename, 'w') as f:
        for dim in range(mesh.topology.dim):
            mvc = MeshValueCollection("size_t", mesh, dim)
            mesh.create_entities(dim)
            for e in MeshEntities(mesh, dim):
                # this can be easily computed to the check the value
                val = int(ndiv * sum(point2list(e.midpoint()))) + 1
                mvc.set_value(e.index(), val)
            f.write(mvc, "/mesh_value_collection_{}".format(dim))

    # read from file
    with HDF5File(mesh.mpi_comm(), filename, 'r') as f:
        for dim in range(mesh.topology.dim):
            mvc = f.read_mvc_size_t(mesh,
                                    "/mesh_value_collection_{}".format(dim))
            # check the values
            for (cell, lidx), val in mvc.values().items():
                eidx = Cell(mesh, cell).entities(dim)[lidx]
                mid = point2list(MeshEntity(mesh, dim, eidx).midpoint())
                assert val == int(ndiv * sum(mid)) + 1
Esempio n. 2
0
def convert_vector_nodes_to_cells(root_dir, mesh, V):
    # Extract constants
    total_cell_num = mesh.num_cells()
    dofs_num_per_cell = len(V.dofmap().cell_dofs(0))
    # Pre-define empty arrays
    dof_index_to_cell_table = np.empty((total_cell_num, dofs_num_per_cell), dtype=np.uint32)
    cell_volumes = np.empty(total_cell_num)
    cell_coordinates = np.empty((total_cell_num, 3))
    # Generate cell-to-dof-indices & cell-to-volume matching table & cell coordinates
    file_path1 = root_dir + 'dof_index_to_cell_table.npy'
    file_path2 = root_dir + 'cell_volumes.npy'
    file_path3 = root_dir + 'cell_coordinates.npy'
    if (os.path.isfile(file_path1)) & (os.path.isfile(file_path2)) & (os.path.isfile(file_path3)):
        dof_index_to_cell_table = np.load(file_path1)
        cell_volumes = np.load(file_path2)
        cell_coordinates = np.load(file_path3)
    else:
        print("No cell information file detected")
        print(" ==> Creating new cell information")
        for cell_num in range(total_cell_num):
            dof_index_to_cell_table[cell_num] = V.dofmap().cell_dofs(cell_num)
            cell_volumes[cell_num] = Cell(mesh, cell_num).volume()
            cell_coordinates[cell_num] = MeshEntity(mesh, 3, cell_num).midpoint().array()
        np.save(file_path1, dof_index_to_cell_table)
        np.save(file_path2, cell_volumes)
        np.save(file_path3, cell_coordinates)
    return (cell_volumes, cell_coordinates, dof_index_to_cell_table)
Esempio n. 3
0
def calculate_face_array(mesh):
    total_face_num = mesh.num_faces()
    face_array = np.empty((total_face_num, 3))
    # Get three vertex indices for each face
    for i in range(total_face_num):
        face_array[i] = MeshEntity(mesh, 2, i).entities(0)
    return face_array
Esempio n. 4
0
def test_mesh_topology_against_fiat(mesh_factory, ghost_mode):
    """Test that mesh cells have topology matching to FIAT reference
    cell they were created from.
    """
    func, args = mesh_factory
    xfail_ghosted_quads_hexes(func, ghost_mode)
    mesh = func(*args)

    # Create FIAT cell
    cell_name = CellType.type2string(mesh.type().cell_type())
    fiat_cell = FIAT.ufc_cell(cell_name)

    # Initialize all mesh entities and connectivities
    mesh.init()

    for cell in Cells(mesh):
        # Get mesh-global (MPI-local) indices of cell vertices
        vertex_global_indices = cell.entities(0)

        # Loop over all dimensions of reference cell topology
        for d, d_topology in fiat_cell.get_topology().items():

            # Get entities of dimension d on the cell
            entities = cell.entities(d)
            if len(entities) == 0:  # Fixup for highest dimension
                entities = (cell.index(), )

            # Loop over all entities of fixed dimension d
            for entity_index, entity_topology in d_topology.items():

                # Check that entity vertices map to cell vertices in right order
                entity = MeshEntity(mesh, d, entities[entity_index])
                entity_vertices = entity.entities(0)
                assert all(vertex_global_indices[numpy.array(entity_topology)]
                           == entity_vertices)
Esempio n. 5
0
def test_save_and_read_mesh_value_collection(tempdir):
    ndiv = 2
    filename = os.path.join(tempdir, "mesh_value_collection.h5")
    mesh = UnitCubeMesh(MPI.comm_world, ndiv, ndiv, ndiv)

    # write to file
    with HDF5File(mesh.mpi_comm(), filename, 'w') as f:
        for dim in range(mesh.topology.dim):
            mvc = MeshValueCollection("size_t", mesh, dim)
            mesh.create_entities(dim)
            mp = cpp.mesh.midpoints(mesh, dim, range(mesh.num_entities(dim)))
            for e in range(mesh.num_entities(dim)):
                # this can be easily computed to the check the value
                val = int(ndiv * mp[e].sum()) + 1
                mvc.set_value(e, val)
            f.write(mvc, "/mesh_value_collection_{}".format(dim))

    # read from file
    with HDF5File(mesh.mpi_comm(), filename, 'r') as f:
        for dim in range(mesh.topology.dim):
            mvc = f.read_mvc_size_t(mesh,
                                    "/mesh_value_collection_{}".format(dim))
            mp = cpp.mesh.midpoints(mesh, dim, range(mesh.num_entities(dim)))
            # check the values
            for (cell, lidx), val in mvc.values().items():
                eidx = MeshEntity(mesh, mesh.topology.dim,
                                  cell).entities(dim)[lidx]
                mid = mp[eidx]
                assert val == int(ndiv * mid.sum()) + 1
Esempio n. 6
0
def test_distance_interval():
    mesh = UnitIntervalMesh(MPI.comm_self, 1)
    cell = MeshEntity(mesh, mesh.topology.dim, 0)
    assert cpp.geometry.squared_distance(cell,
                                         numpy.array([-1.0, 0, 0
                                                      ])) == pytest.approx(1.0)
    assert cpp.geometry.squared_distance(cell,
                                         numpy.array([0.5, 0, 0
                                                      ])) == pytest.approx(0.0)
Esempio n. 7
0
 def __call__(self, mesh_entity):
     predicate = self.predicate
     if self.is_identity:
         return predicate(mesh_entity)
     else:
         mesh = mesh_entity.mesh()
         dim = predicate.dim
         return any(
             predicate(MeshEntity(mesh, dim, i))
             for i in mesh_entity.entities(dim))
Esempio n. 8
0
def test_mesh_topology_against_fiat(mesh_factory,
                                    ghost_mode=cpp.mesh.GhostMode.none):
    """Test that mesh cells have topology matching to FIAT reference
    cell they were created from.
    """
    func, args = mesh_factory
    xfail_ghosted_quads_hexes(func, ghost_mode)
    mesh = func(*args)
    if not is_simplex(mesh.cell_type):
        return

    # Order mesh
    cpp.mesh.Ordering.order_simplex(mesh)

    # Create FIAT cell
    cell_name = cpp.mesh.to_string(mesh.cell_type)
    fiat_cell = FIAT.ufc_cell(cell_name)

    # Initialize all mesh entities and connectivities
    mesh.create_connectivity_all()

    for i in range(mesh.num_cells()):
        cell = MeshEntity(mesh, mesh.topology.dim, i)
        # Get mesh-global (MPI-local) indices of cell vertices
        vertex_global_indices = cell.entities(0)

        # Loop over all dimensions of reference cell topology
        for d, d_topology in fiat_cell.get_topology().items():

            # Get entities of dimension d on the cell
            entities = cell.entities(d)
            if len(entities) == 0:  # Fixup for highest dimension
                entities = (i, )

            # Loop over all entities of fixed dimension d
            for entity_index, entity_topology in d_topology.items():

                # Check that entity vertices map to cell vertices in correct order
                entity = MeshEntity(mesh, d, entities[entity_index])
                entity_vertices = entity.entities(0)
                assert all(vertex_global_indices[numpy.array(entity_topology)]
                           == entity_vertices)
Esempio n. 9
0
def test_distance_tetrahedron():
    mesh = UnitCubeMesh(MPI.comm_self, 1, 1, 1)
    cell = MeshEntity(mesh, mesh.topology.dim, 5)
    assert cpp.geometry.squared_distance(cell,
                                         numpy.array([-1.0, -1.0, -1.0
                                                      ])) == pytest.approx(3.0)
    assert cpp.geometry.squared_distance(cell,
                                         numpy.array([-1.0, 0.5, 0.5
                                                      ])) == pytest.approx(1.0)
    assert cpp.geometry.squared_distance(cell,
                                         numpy.array([0.5, 0.5, 0.5
                                                      ])) == pytest.approx(0.0)
Esempio n. 10
0
def test_distance_triangle():
    mesh = UnitSquareMesh(MPI.comm_self, 1, 1)
    cell = MeshEntity(mesh, mesh.topology.dim, 1)
    assert cpp.geometry.squared_distance(cell,
                                         numpy.array([-1.0, -1.0, 0.0
                                                      ])) == pytest.approx(2.0)
    assert cpp.geometry.squared_distance(cell,
                                         numpy.array([-1.0, 0.5, 0.0
                                                      ])) == pytest.approx(1.0)
    assert cpp.geometry.squared_distance(cell,
                                         numpy.array([0.5, 0.5, 0.0
                                                      ])) == pytest.approx(0.0)
def test_compute_collisions_point_2d():

    #    reference = {1: set([226]),
    #                 2: set([136, 137])}

    p = numpy.array([0.3, 0.3, 0.0])
    mesh = UnitSquareMesh(MPI.comm_world, 16, 16)
    for dim in range(1, 3):
        tree = BoundingBoxTree(mesh, mesh.topology.dim)
        entities = tree.compute_collisions_point(p)
        for e in entities:
            ent = MeshEntity(mesh, dim, e)
            mp = ent.midpoint()
            x = (mp[0], mp[1])
            print("test: {}".format(x))
def test_compute_collisions_point_2d():

    reference = {1: set([226]), 2: set([136, 137])}

    p = Point(0.3, 0.3)
    mesh = UnitSquareMesh(16, 16)
    for dim in range(1, 3):
        tree = BoundingBoxTree()
        tree.build(mesh, dim)
        entities = tree.compute_collisions(p)
        for e in entities:
            ent = MeshEntity(mesh, dim, e)
            mp = ent.midpoint()
            x = (mp.x(), mp.y())
            print("test: {}".format(x))
Esempio n. 13
0
def test_tabulate_all_coordinates(mesh_factory):
    func, args = mesh_factory
    mesh = func(*args)
    V = FunctionSpace(mesh, ("Lagrange", 1))
    W0 = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
    W1 = VectorElement("Lagrange", mesh.ufl_cell(), 1)
    W = FunctionSpace(mesh, W0 * W1)

    D = mesh.geometry.dim
    V_dofmap = V.dofmap
    W_dofmap = W.dofmap

    all_coords_V = V.tabulate_dof_coordinates()
    all_coords_W = W.tabulate_dof_coordinates()
    local_size_V = V_dofmap().index_map.size_local * V_dofmap(
    ).index_map.block_size
    local_size_W = W_dofmap().index_map.size_local * W_dofmap(
    ).index_map.block_size

    all_coords_V = all_coords_V.reshape(local_size_V, D)
    all_coords_W = all_coords_W.reshape(local_size_W, D)

    checked_V = [False] * local_size_V
    checked_W = [False] * local_size_W

    # Check that all coordinates are within the cell it should be
    for i in range(mesh.num_cells()):
        cell = MeshEntity(mesh, mesh.topology.dim, i)
        dofs_V = V_dofmap.cell_dofs(i)
        for di in dofs_V:
            if di >= local_size_V:
                continue
            assert cell.contains(all_coords_V[di])
            checked_V[di] = True

        dofs_W = W_dofmap.cell_dofs(cell.index())
        for di in dofs_W:
            if di >= local_size_W:
                continue
            assert cell.contains(all_coords_W[di])
            checked_W[di] = True

    # Assert that all dofs have been checked by the above
    assert all(checked_V)
    assert all(checked_W)
Esempio n. 14
0
def test_tabulate_coord_periodic(mesh_factory):
    def periodic_boundary(x):
        return x[0] < np.finfo(float).eps

    func, args = mesh_factory
    mesh = func(*args)

    V = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
    Q = VectorElement("Lagrange", mesh.ufl_cell(), 1)
    W = V * Q

    V = FunctionSpace(mesh, V, constrained_domain=periodic_boundary)
    W = FunctionSpace(mesh, W, constrained_domain=periodic_boundary)

    L0 = W.sub(0)
    L1 = W.sub(1)
    L01 = L1.sub(0)
    L11 = L1.sub(1)

    sdim = V.element.space_dimension()
    coord0 = np.zeros((sdim, 2), dtype="d")
    coord1 = np.zeros((sdim, 2), dtype="d")
    coord2 = np.zeros((sdim, 2), dtype="d")
    coord3 = np.zeros((sdim, 2), dtype="d")

    for i in range(mesh.num_cells()):
        cell = MeshEntity(mesh, mesh.topology.dim, i)
        coord0 = V.element.tabulate_dof_coordinates(cell)
        coord1 = L0.element.tabulate_dof_coordinates(cell)
        coord2 = L01.element.tabulate_dof_coordinates(cell)
        coord3 = L11.element.tabulate_dof_coordinates(cell)
        coord4 = L1.element.tabulate_dof_coordinates(cell)

        assert (coord0 == coord1).all()
        assert (coord0 == coord2).all()
        assert (coord0 == coord3).all()
        assert (coord4[:sdim] == coord0).all()
        assert (coord4[sdim:] == coord0).all()
Esempio n. 15
0
    def _single_mesh_entity_plot(self, cell_index, tdim):
        'Plot labels of mesh entities of topological dim. that are in cell.'
        # Compute cell->entity connectivity unless cell-cell. Don't need patch
        if self.tdim == tdim:
            entity_indices = [cell_index]
        else:
            entity_indices = Cell(self.mesh, cell_index).entities(tdim)

        color = self.mesh_entity_colors[tdim]
        labels = self.mesh_entity_labels[tdim]
        # Loop through entities of the cell
        for entity_index in entity_indices:
            entity = MeshEntity(self.mesh, tdim, entity_index)
            # Midpoint is label location
            x = entity.midpoint()
            x = [x[i] for i in range(self.gdim)]
            if (self.order == 'global') and self.mpi_size > 1:
                args = x + [str(entity.global_index())]
            else:
                args = x + [str(entity_index)]
            # Create new label if entitiy not labeled already
            if not (entity_index in labels):
                labels[entity_index] = self.axes.text(*args, color=color)
Esempio n. 16
0
def c1(mesh3d):
    # Degenerate cell
    return MeshEntity(mesh3d, mesh3d.topology.dim, 1)
Esempio n. 17
0
def c5(mesh3d):
    # Regular tetrahedron with edge sqrt(2)
    return MeshEntity(mesh3d, mesh3d.topology.dim, 5)
Esempio n. 18
0
def c0(mesh3d):
    """Original tetrahedron from UnitCubeMesh(MPI.comm_world, 1, 1, 1)"""
    return MeshEntity(mesh3d, mesh3d.topology.dim, 0)