Exemplo n.º 1
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)
Exemplo n.º 2
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"
    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_{}_marker".format(mvc_dim)
        mvc.name = tag
        mesh.create_connectivity(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_{}.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)
Exemplo n.º 3
0
def import_mesh(
        prefix="mesh",
        subdomains=False,
        dim=2,
        directory=".",
):
    """Function importing a dolfin mesh.

    Arguments:
        prefix (str, optional): mesh files prefix (eg. my_mesh.msh,
            my_mesh_domain.xdmf, my_mesh_bondaries.xdmf). Defaults to "mesh".
        subdomains (bool, optional): True if there are subdomains. Defaults to
            False.
        dim (int, optional): dimension of the domain. Defaults to 2.
        directory (str, optional): directory of the mesh files. Defaults to ".".

    Output:
        - dolfin Mesh object containing the domain;
        - dolfin MeshFunction object containing the physical lines (dim=2) or
            surfaces (dim=3) defined in the msh file and the sub-domains;
        - association table
    """
    # Set the file name
    domain = "{}_domain.xdmf".format(prefix)
    boundaries = "{}_boundaries.xdmf".format(prefix)

    # create 2 xdmf files if not converted before
    if not os.path.exists("{}/{}".format(directory, domain)) or \
       not os.path.exists("{}/{}".format(directory, boundaries)):
        msh2xdmf("{}.msh".format(prefix), dim=dim, directory=directory)

    # Import the converted domain
    mesh = Mesh()
    with XDMFFile("{}/{}".format(directory, domain)) as infile:
        infile.read(mesh)
    # Import the boundaries
    boundaries_mvc = MeshValueCollection("size_t", mesh, dim=dim)
    with XDMFFile("{}/{}".format(directory, boundaries)) as infile:
        infile.read(boundaries_mvc, 'boundaries')
    boundaries_mf = MeshFunctionSizet(mesh, boundaries_mvc)
    # Import the subdomains
    if subdomains:
        subdomains_mvc = MeshValueCollection("size_t", mesh, dim=dim)
        with XDMFFile("{}/{}".format(directory, domain)) as infile:
            infile.read(subdomains_mvc, 'subdomains')
        subdomains_mf = MeshFunctionSizet(mesh, subdomains_mvc)
    # Import the association table
    association_table_name = "{}/{}_{}".format(
        directory, prefix, "association_table.ini")
    file_content = ConfigParser()
    file_content.read(association_table_name)
    association_table = dict(file_content["ASSOCIATION TABLE"])
    # Convert the value from string to int
    for key, value in association_table.items():
        association_table[key] = int(value)
    # Return the Mesh and the MeshFunction objects
    if not subdomains:
        return mesh, boundaries_mf, association_table
    else:
        return mesh, boundaries_mf, subdomains_mf, association_table
Exemplo n.º 4
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
Exemplo 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
Exemplo n.º 6
0
def import_mesh_from_xdmf(
    prefix="mesh",
    subdomains=False,
    dim=2,
    directory=".",
):
    """
    Function importing a dolfin mesh.

    Arguments:
        - domain (str): name of the domain XDMF file;
        - boundaries (str): name of the boundaries XDMF file;
        - dim (int): dimension of the domain;
        - subdomains (bool): true if there are subdomains, else false
        - directory (str): (optional) directory of the mesh;

    Output:
        - dolfin Mesh object containing the domain;
        - dolfin MeshFunction object containing the physical lines (dim=2) or
            surfaces (dim=3) defined in the msh file and the sub-domains;
        - association table
    """
    # Set the file name
    domain = "{}_domain.xdmf".format(prefix)
    boundaries = "{}_boundaries.xdmf".format(prefix)
    # Import the converted domain
    mesh = Mesh()
    with XDMFFile("{}/{}".format(directory, domain)) as infile:
        infile.read(mesh)
    # Import the boundaries
    boundaries_mvc = MeshValueCollection("size_t", mesh, dim=dim)
    with XDMFFile("{}/{}".format(directory, boundaries)) as infile:
        infile.read(boundaries_mvc, 'boundaries')
    boundaries_mf = MeshFunctionSizet(mesh, boundaries_mvc)
    # Import the subdomains
    if subdomains:
        subdomains_mvc = MeshValueCollection("size_t", mesh, dim=dim)
        with XDMFFile("{}/{}".format(directory, domain)) as infile:
            infile.read(subdomains_mvc, 'subdomains')
        subdomains_mf = MeshFunctionSizet(mesh, subdomains_mvc)
    # Import the association table
    association_table_name = "{}/{}_{}".format(directory, prefix,
                                               "association_table.ini")
    file_content = ConfigParser()
    file_content.read(association_table_name)
    association_table = dict(file_content["ASSOCIATION TABLE"])
    # Convert the value from string to int
    for key, value in association_table.items():
        association_table[key] = int(value)
    # Return the Mesh and the MeshFunction objects
    if not subdomains:
        return mesh, boundaries_mf, association_table
    else:
        return mesh, boundaries_mf, subdomains_mf, association_table
Exemplo n.º 7
0
def DolfinReader(directory, file):
    msh = Mesh()
    with XDMFFile("{}/{}.xdmf".format(directory, file)) as infile:
        infile.read(msh)
        dim = msh.topology().dim()
    mvc = MeshValueCollection("size_t", msh, dim=dim - 1)
    with XDMFFile("{}/{}_facets.xdmf".format(directory, file)) as infile:
        infile.read(mvc, "boundaries")
    boundaries = MeshFunctionSizet(msh, mvc)
    mvc = MeshValueCollection("size_t", msh, dim=dim)
    with XDMFFile("{}/{}_physical_region.xdmf".format(directory,
                                                      file)) as infile:
        infile.read(mvc, "subdomains")
    subdomains = MeshFunctionSizet(msh, mvc)
    return msh, boundaries, subdomains
Exemplo n.º 8
0
def import_mesh_from_xdmf(domain="domain.xdmf",
                          boundaries="boundaries.xdmf",
                          labels="labels.yaml",
                          subdomains=False,
                          dim=2,
                          directory="."):
    """
    Function importing a msh mesh and converting it into a dolfin mesh.

    Arguments:
        - domain (str): name of the domain XDMF file;
        - boundaries (str): name of the boundaries XDMF file;
        - dim (int): dimension of the domain;
        - subdomains (bool): true if there are subdomains, else false
        - directory (str): (optional) directory of the mesh;

    Output:
        - dolfin Mesh object containing the domain;
        - dolfin MeshFunction object containing the physical lines (dim=2) or
        surfaces (dim=3) defined in the msh file and the sub-domains;
        - a dictionary with labels for boundaries and subdomains
    """
    # Import the converted domain
    mesh = Mesh()
    with XDMFFile("{}/{}".format(directory, domain)) as infile:
        infile.read(mesh)
    # Import the boundaries
    boundaries_mvc = MeshValueCollection("size_t", mesh, dim=dim)
    with XDMFFile("{}/{}".format(directory, boundaries)) as infile:
        infile.read(boundaries_mvc, 'boundaries')
    boundaries_mf = MeshFunctionSizet(mesh, boundaries_mvc)
    # Import the subdomains
    if subdomains:
        subdomains_mvc = MeshValueCollection("size_t", mesh, dim=dim)
        with XDMFFile("{}/{}".format(directory, domain)) as infile:
            infile.read(subdomains_mvc, 'subdomains')
        subdomains_mf = MeshFunctionSizet(mesh, subdomains_mvc)
    # Import labels
    with open("{}/{}".format(directory, labels), 'r') as infile:
        labels = yaml.load(infile, Loader=yaml.FullLoader)
    # Return the Mesh and the MeshFunction objects
    if not subdomains:
        return mesh, boundaries_mf, labels
    else:
        return mesh, boundaries_mf, subdomains_mf, labels
    print(labels)
Exemplo n.º 9
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)
def test_assign_2D_facets():
    mesh = UnitSquareMesh(MPI.comm_world, 3, 3)
    mesh.init(2, 1)
    ncells = mesh.num_cells()
    f = MeshValueCollection("int", mesh, 1)
    all_new = True
    for cell in Cells(mesh):
        value = ncells - cell.index()
        for i, facet in enumerate(FacetRange(cell)):
            all_new = all_new and f.set_value(cell.index(), i, value + i)

    g = MeshValueCollection("int", mesh, 1)
    g.assign(f)
    assert ncells * 3 == f.size()
    assert ncells * 3 == g.size()
    assert all_new

    for cell in Cells(mesh):
        value = ncells - cell.index()
        for i, facet in enumerate(FacetRange(cell)):
            assert value + i == g.get_value(cell.index(), i)
Exemplo n.º 11
0
def test_assign_2D_vertices():
    mesh = UnitSquareMesh(MPI.comm_world, 3, 3)
    mesh.create_connectivity(2, 0)
    ncells = mesh.num_cells()
    f = MeshValueCollection("int", mesh, 0)
    all_new = True
    for cell in Cells(mesh):
        value = ncells - cell.index()
        for i, vert in enumerate(VertexRange(cell)):
            all_new = all_new and f.set_value(cell.index(), i, value + i)

    g = MeshValueCollection("int", mesh, 0)
    g.assign(f)
    assert ncells * 3 == f.size()
    assert ncells * 3 == g.size()
    assert all_new

    for cell in Cells(mesh):
        value = ncells - cell.index()
        for i, vert in enumerate(VertexRange(cell)):
            assert value + i == g.get_value(cell.index(), i)
Exemplo n.º 12
0
def test_save_mesh_value_collection(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, 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)
Exemplo n.º 13
0
def CladdingR_solver(FC_mesh, FC_facets, FC_fs, FC_info, D_post, R_path):

    FC_fi, FC_fo = FC_fs
    h, Tfc_inner, Tb, FC_Tave = FC_info

    # Reading mesh data stored in .xdmf files.
    mesh = Mesh()
    with XDMFFile(FC_mesh) as infile:
        infile.read(mesh)

    mvc = MeshValueCollection("size_t", mesh, 1)
    with XDMFFile(FC_facets) as infile:
        infile.read(mvc, "name_to_read")
    mf = cpp.mesh.MeshFunctionSizet(mesh, mvc)
    #File("Circle_facet.pvd").write(mf)

    # Mesh data
    print('CladdingRod_mesh data\n', 'Number of cells: ', mesh.num_cells(),
          '\n Number of nodes: ', mesh.num_vertices())

    # Define variational problem
    V = FunctionSpace(mesh, 'P', 1)
    u = Function(V)
    v = TestFunction(V)

    # Define boundary conditions base on pygmsh mesh mark
    bc = DirichletBC(V, Constant(Tfc_inner), mf, FC_fi)
    ds = Measure("ds", domain=mesh, subdomain_data=mf, subdomain_id=FC_fo)

    # Variational formulation
    # Klbda_ZrO2 = 18/1000  # W/(m K) --> Nuclear reactor original source
    # Klbda_ZrO2 = Constant(K_ZrO2(FC_Tave))
    F = K_ZrO2(u) * dot(grad(u), grad(v)) * dx + h * (u - Tb) * v * ds

    # Compute solution
    du = TrialFunction(V)
    Gain = derivative(F, u, du)
    solve(F==0, u, bc, J=Gain, \
          solver_parameters={"newton_solver": {"linear_solver": "lu",
                                               "relative_tolerance": 1e-9}}, \
          form_compiler_parameters={"cpp_optimize": True,
                                    "representation": "uflacs",
                                    "quadrature_degree" : 2}
          )  # mumps

    # Save solution
    if D_post:
        fU_out = XDMFFile(os.path.join(R_path, 'FuelCladding', 'u.xdmf'))
        fU_out.write_checkpoint(u, "T", 0, XDMFFile.Encoding.HDF5, False)
        fU_out.close()
Exemplo n.º 14
0
def test_assign_2D_vertices():
    mesh = UnitSquareMesh(MPI.comm_world, 3, 3)
    mesh.create_connectivity(2, 0)
    ncells = mesh.num_cells()
    num_cell_vertices = cpp.mesh.cell_num_vertices(mesh.cell_type)

    f = MeshValueCollection("int", mesh, 0)
    all_new = True
    for c in range(ncells):
        value = ncells - c
        for i in range(num_cell_vertices):
            all_new = all_new and f.set_value(c, i, value + i)

    g = MeshValueCollection("int", mesh, 0)
    g.assign(f)
    assert ncells * 3 == f.size()
    assert ncells * 3 == g.size()
    assert all_new

    for c in range(ncells):
        value = ncells - c
        for i in range(num_cell_vertices):
            assert value + i == g.get_value(c, i)
Exemplo n.º 15
0
def FuelR_solver(FR_mesh, FR_facets, FR_f, FRod_info, D_post, R_path):

    Qv, Tfr_outer, FR_Tave = FRod_info

    # Reading mesh data stored in .xdmf files.
    mesh = Mesh()
    with XDMFFile(FR_mesh) as infile:
        infile.read(mesh)

    mvc = MeshValueCollection("size_t", mesh, 1)
    with XDMFFile(FR_facets) as infile:
        infile.read(mvc, "name_to_read")
    mf = cpp.mesh.MeshFunctionSizet(mesh, mvc)
    #File("Circle_facet.pvd").write(mf)

    # Mesh data
    print('FuelRod_mesh data\n', 'Number of cells: ', mesh.num_cells(),
          '\n Number of nodes: ', mesh.num_vertices())

    # Define variational problem
    V = FunctionSpace(mesh, 'P', 1)
    u = Function(V)
    v = TestFunction(V)

    f = Constant(Qv)

    # Define boundary conditions base on pygmsh mesh mark
    bc = DirichletBC(V, Constant(Tfr_outer), mf, FR_f)

    # Variational formulation
    # Klbda_UO2 = Constant(K_UO2(FR_Tave))
    F = K_UO2(u) * dot(grad(u), grad(v)) * dx - f * v * dx

    # Compute solution
    du = TrialFunction(V)
    Gain = derivative(F, u, du)
    solve(F==0, u, bc, J=Gain, \
          solver_parameters={"newton_solver": {"linear_solver": "lu",
                                               "relative_tolerance": 1e-9}}, \
          form_compiler_parameters={"cpp_optimize": True,
                                    "representation": "uflacs",
                                    "quadrature_degree" : 2}
          )  # mumps

    # Save solution
    if D_post:
        fU_out = XDMFFile(os.path.join(R_path, 'FuelRod', 'u.xdmf'))
        fU_out.write_checkpoint(u, "T", 0, XDMFFile.Encoding.HDF5, False)
        fU_out.close()
Exemplo n.º 16
0
def test_assign_2D_facets():
    mesh = UnitSquareMesh(MPI.comm_world, 3, 3)
    mesh.create_connectivity(2, 1)
    tdim = mesh.topology.dim
    num_cell_facets = cpp.mesh.cell_num_entities(mesh.cell_type, tdim - 1)
    ncells = mesh.num_cells()

    f = MeshValueCollection("int", mesh, 1)
    all_new = True
    for c in range(ncells):
        value = ncells - c
        for i in range(num_cell_facets):
            all_new = all_new and f.set_value(c, i, value + i)

    g = MeshValueCollection("int", mesh, 1)
    g.assign(f)
    assert ncells * 3 == f.size()
    assert ncells * 3 == g.size()
    assert all_new

    for c in range(ncells):
        value = ncells - c
        for i in range(num_cell_facets):
            assert value + i == g.get_value(c, i)
Exemplo n.º 17
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)
Exemplo n.º 18
0
def convert(msh_file, h5_file, save_mvc=False):
    '''Temporary version of convertin from msh to h5'''
    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')

    print('Mesh has %d cells' % mesh.num_cells())
    print('Mesh size %g %g' % (mesh.hmin(), mesh.hmax()))
    
    # Save ALL data as facet_functions
    names = ('surfaces', 'volumes')
    if not save_mvc:
        for name, region in zip(names, ('facet_region.xml', 'physical_region.xml')):
            r_xml_file = '_'.join([root, region])

            f = MeshFunction('size_t', mesh, r_xml_file)
            print('%d %s with 1' % (sum(1 for _ in SubsetIterator(f, 1)), name))
            out.write(f, name)

        return True

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

        f = MeshFunction('size_t', mesh, r_xml_file)
        # With mesh value collection we only store nonzero tags
        mvc = MeshValueCollection('size_t', mesh, f.dim())
        # Fill
        fill_mvc_from_mf(f, mvc)
        # And save
        out.write(mvc, name)
                    
    return True
Exemplo n.º 19
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) == len(f.values)
    assert mesh.num_cells() * 3 == g.size()

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

    num_cell_vertices = cpp.mesh.cell_num_vertices(mesh.cell_type)
    tdim = mesh.topology.dim
    connectivity = mesh.topology.connectivity(tdim, 0)
    for c in range(mesh.num_cells()):
        vertices = connectivity.connections(c)
        for i in range(num_cell_vertices):
            assert 25 == g.get_value(c, i)
            assert f2.values[vertices[i]] == g.get_value(c, i)
Exemplo n.º 20
0
def prolateGeometry(filename):

    from dolfin import XDMFFile, Mesh, MeshValueCollection, MeshTransformation
    xdmf_meshfile = "meshes/" + filename + ".xdmf"
    xdmf_meshfile_bm = "meshes/" + filename + "_bm.xdmf"
    mesh = Mesh()
    with XDMFFile(xdmf_meshfile) as infile:
        infile.read(mesh)
    mvc = MeshValueCollection("size_t", mesh, 2)
    with XDMFFile(xdmf_meshfile_bm) as infile:
        infile.read(mvc, "name_to_read")
    from dolfin import cpp
    markers = cpp.mesh.MeshFunctionSizet(mesh, mvc)

    ENDOCARD = 20
    EPICARD = 10
    BASE = 50
    NONE = 99

    MeshTransformation.scale(mesh, 1e-3)
    return mesh, markers, ENDOCARD, EPICARD, BASE, NONE
def test_mesh_function_assign_2D_facets():
    mesh = UnitSquareMesh(MPI.comm_world, 3, 3)
    mesh.init(1)
    f = MeshFunction("int", mesh, mesh.topology.dim - 1, 25)
    for cell in Cells(mesh):
        for i, facet in enumerate(FacetRange(cell)):
            assert 25 == f[facet]

    g = MeshValueCollection("int", mesh, 1)
    g.assign(f)
    assert mesh.num_facets() == f.size()
    assert mesh.num_cells() * 3 == g.size()
    for cell in Cells(mesh):
        for i, facet in enumerate(FacetRange(cell)):
            assert 25 == g.get_value(cell.index(), i)

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

    for cell in Cells(mesh):
        for i, facet in enumerate(FacetRange(cell)):
            assert f2[facet] == g.get_value(cell.index(), i)
Exemplo n.º 22
0
def test_save_and_read_mesh_value_collection_with_only_one_marked_entity(
        tempdir):
    ndiv = 2
    filename = os.path.join(tempdir, "mesh_value_collection.h5")
    mesh = UnitCubeMesh(MPI.comm_world, ndiv, ndiv, ndiv)
    mvc = MeshValueCollection("size_t", mesh, 3)
    mesh.create_entities(3)
    if MPI.rank(mesh.mpi_comm()) == 0:
        mvc.set_value(0, 1)

    # write to file
    with HDF5File(mesh.mpi_comm(), filename, 'w') as f:
        f.write(mvc, "/mesh_value_collection")

    # read from file
    with HDF5File(mesh.mpi_comm(), filename, 'r') as f:
        mvc = f.read_mvc_size_t(mesh, "/mesh_value_collection")
        assert MPI.sum(mesh.mpi_comm(), mvc.size()) == 1
        if MPI.rank(mesh.mpi_comm()) == 0:
            assert mvc.get_value(0, 0) == 1
Exemplo n.º 23
0
def test_append_and_load_mesh_value_collections(tempdir, encoding, data_type):
    dtype_str, dtype = data_type
    mesh = UnitCubeMesh(MPI.comm_world, 2, 2, 2)
    mesh.create_connectivity_all()
    for d in range(mesh.geometry.dim + 1):
        mesh.create_global_indices(d)

    mvc_v = MeshValueCollection(dtype_str, mesh, 0)
    mvc_v.name = "vertices"
    mvc_e = MeshValueCollection(dtype_str, mesh, 1)
    mvc_e.name = "edges"
    mvc_f = MeshValueCollection(dtype_str, mesh, 2)
    mvc_f.name = "facets"
    mvc_c = MeshValueCollection(dtype_str, mesh, 3)
    mvc_c.name = "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:
            global_indices = mesh.topology.global_indices(mvc.dim)
            for ent in range(mesh.num_entities(mvc.dim)):
                assert (mvc.set_value(ent, global_indices[ent]))
            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 = mf_in.values - mf.values
        assert numpy.all(diff == 0)
Exemplo n.º 24
0
geom.add_physical([p1, p2], label="POINT_RIGHT")
geom.add_physical([l0, l2], label="LINE_X")
geom.add_physical([l1, l3], label="LINE_Y")
geom.add_physical(ps, label="SURFACE")
geom.add_physical(box[1], label="BOX")

pygmsh_mesh = pygmsh.generate_mesh(geom, geo_filename="tetra.geo")
points, cells, cell_data = pygmsh_mesh.points, pygmsh_mesh.cells, pygmsh_mesh.cell_data

mesh = cpp.mesh.Mesh(MPI.comm_world, cpp.mesh.CellType.tetrahedron, points,
                     cells['tetra'], [], cpp.mesh.GhostMode.none)
assert mesh.degree() == 1
assert mesh.geometry.dim == 3
assert mesh.topology.dim == 3

mvc_vertex = MeshValueCollection("size_t", mesh, 0, cells["vertex"],
                                 cell_data["vertex"]['gmsh:physical'])
assert mvc_vertex.get_value(0, 0) == 1

mvc_line = MeshValueCollection("size_t", mesh, 1, cells["line"],
                               cell_data["line"]['gmsh:physical'])
assert mvc_line.get_value(0, 4) == 4

mvc_triangle = MeshValueCollection("size_t", mesh, 2, cells["triangle"],
                                   cell_data["triangle"]['gmsh:physical'])
assert mvc_triangle.get_value(0, 3) == 5

mvc_tetra = MeshValueCollection("size_t", mesh, 3, cells["tetra"],
                                cell_data["tetra"]['gmsh:physical'])
assert mvc_tetra.get_value(0, 0) == 6
pass
Exemplo n.º 25
0
def test_assign_2D_cells():
    mesh = UnitSquareMesh(MPI.comm_world, 3, 3)
    ncells = mesh.num_cells()
    f = MeshValueCollection("int", mesh, 2)
    all_new = True
    for c in range(ncells):
        value = ncells - c
        all_new = all_new and f.set_value(c, value)
    g = MeshValueCollection("int", mesh, 2)
    g.assign(f)
    assert ncells == f.size()
    assert ncells == g.size()
    assert all_new

    for c in range(ncells):
        value = ncells - c
        assert value, g.get_value(c == 0)

    old_value = g.get_value(0, 0)
    g.set_value(0, 0, old_value + 1)
    assert old_value + 1 == g.get_value(0, 0)
Exemplo n.º 26
0
mesh_ele_size = .5
p0 = geom.add_point([0, 0, 0], lcar=mesh_ele_size)
p1 = geom.add_point([1, 0, 0], lcar=mesh_ele_size)
p2 = geom.add_point([1, 1, 0], lcar=mesh_ele_size)
p3 = geom.add_point([0, 1, 0], lcar=mesh_ele_size)

l0 = geom.add_line(p0, p1)
l1 = geom.add_line(p1, p2)
l2 = geom.add_line(p2, p3)
l3 = geom.add_line(p3, p0)

ll = geom.add_line_loop(lines=[l0, l1, l2, l3])
ps = geom.add_plane_surface(ll)

# Tag line and surface
geom.add_physical(l3, label="LINE")
geom.add_physical(ps, label="SURFACE")

pygmsh_mesh = pygmsh.generate_mesh(geom)
points, cells, cell_data = pygmsh_mesh.points, pygmsh_mesh.cells, pygmsh_mesh.cell_data

mesh = cpp.mesh.Mesh(MPI.comm_world, cpp.mesh.CellType.Type.triangle, points,
                     cells['triangle'], [], cpp.mesh.GhostMode.none)
assert mesh.degree() == 1
assert mesh.geometry.dim == 3
assert mesh.topology.dim == 2

f = MeshValueCollection("size_t", mesh, 1, cells["line"],
                        cell_data["line"]['gmsh:physical'])
print(f.values())
Exemplo n.º 27
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.
Exemplo n.º 28
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.
Exemplo n.º 29
0
 def _load_mesh_data(self, path, name, dim):
     with XDMFFile(path) as fh:
         mvc = MeshValueCollection("size_t", self._fm.mesh, dim)
         fh.read(mvc, name)
         return cpp.mesh.MeshFunctionSizet(self._fm.mesh, mvc)
Exemplo n.º 30
0
def test_append_and_load_mesh_value_collections(tempdir, encoding, data_type):
    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)