Beispiel #1
0
    def test_convert_diffpack(self):
        from dolfin import Mesh, MPI, MeshFunction
        if MPI.num_processes() != 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(mesh.domains().markers(3).size(), 48)
        self.assertEqual(mesh.domains().markers(2).size(), 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("uint", mesh, mf_name)
            self.assertEqual(sum(mf.array()==marker), num)
            os.unlink(mf_name)
        
        # Clean up
        os.unlink(dfname)
Beispiel #2
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)
Beispiel #3
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 test_convert_diffpack_2d(self):

        from dolfin import Mesh, MPI, MeshFunction, mpi_comm_world

        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)
Beispiel #5
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()
Beispiel #6
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()
Beispiel #7
0
class TestIonTag(unittest.TestCase):

    def setUp(self, *args, **kwargs):
        self.mesh = Mesh()
        editor = MeshEditor()
        editor.open(self.mesh, 2, 2) # topo_dim = 2, geom dim = 2

        editor.init_vertices(6)
        editor.init_cells(2)

        vertex_0 = Vertex(self.mesh, 0)
        vertex_1 = Vertex(self.mesh, 1)
        vertex_2 = Vertex(self.mesh, 2)
        vertex_3 = Vertex(self.mesh, 3)

        vertex_4 = Vertex(self.mesh, 4)
        vertex_5 = Vertex(self.mesh, 5)

        editor.add_cell(0,1,2,3)
        editor.add_cell(1,0,2,3)

        editor.close()


    def test_init(self):
        # test possible arguments and failure cases...
        #@todo implement the test once we have exception handling in the init method

        # pass in a string for values and see what happens
        values = 'i am just a string'

        t = IonTag('foo',3,'int', self.mesh)
        v = MeshEntity(self.mesh,0,1)

        try:
            t[v] = values
        except ValueError:
            pass
        else:
            raise AssertionError('It should have raised a value error!')


    def test_get_set_del(self):
        #Test the getter, setter and delete method

        values = [1,2,3]

        t = IonTag('foo',3,'int', self.mesh)

        for v in vertices(self.mesh):
            # test the setter
            t[v] = values

        # choose an entity in the mesh
        v = MeshEntity(self.mesh,0,1)

        # test the getter
        self.assertTrue((t[v] == values).all())

        #---------------------------------------------------------------------------------------
        # Check delete of a tag entry (for an entity)
        #---------------------------------------------------------------------------------------

        # choose an entity to delete
        entity_tuple = (v.dim(),v.index())

        # check that tag has the entity, v, in it
        self.assertTrue(t._entity_values.has_key(entity_tuple))

        # delete a tag entry for an entity
        del t[entity_tuple]

        # check that the tag no longer has the entity, v, in it
        self.assertFalse(t._entity_values.has_key(entity_tuple))

        #---------------------------------------------------------------------------------------
        # Add less number of values than the size defined in the tag object
        #---------------------------------------------------------------------------------------

        values = [1]
        t = IonTag('foo',3,'int', self.mesh)
        v = MeshEntity(self.mesh,0,1)

        #@todo check to see why self.assertRaises is not working for unittest:

#        with self.assertRaises(ValueError):
#            t[v] = values

        try:
            t[v] = values
        except ValueError:
            pass
        else:
            raise AssertionError('A Value Error should have been raised!')

        #---------------------------------------------------------------------------------------
        # Add more number of values that the size defined in the tag object
        #---------------------------------------------------------------------------------------

        values = [1,2,3,4]
        size = 2
        t = IonTag('foo',size,'int', self.mesh)
        v = MeshEntity(self.mesh,0,1)

        t[v] = values

        for key, value in t.iteritems():
            self.assertEqual(len(value), size)

    def test_len(self):

        t = IonTag('foo',3,'int', self.mesh)

        # we create a tag entry for every vertex of the mesh
        for v in vertices(self.mesh):
            # testing setter
            t[v] = [1,2,3]

        # we check that the number of tag entries is the same as the number we created
        self.assertEqual(len(t), self.mesh.num_vertices())


    def test_contains(self):

        values = [1,2,3]

        t = IonTag('foo',3,'int', self.mesh)

        for v in vertices(self.mesh):
            # testing setter
            t[v] = values

        v = MeshEntity(self.mesh,0,1)

        # testing getter
        self.assertTrue((t[v] == values).all())

        #---------------------------------------------------------------------------------------
        # Delete a tag entry (for an entity)
        #---------------------------------------------------------------------------------------

        # choose an entity to delete
        entity_tuple = (v.dim(),v.index())

        # check that tag has the entity, v, in it
        self.assertTrue(t.__contains__(entity_tuple))

        del t._entity_values[entity_tuple]

        # check that the tag no longer has the entity, v, in it
        self.assertFalse(t.__contains__(entity_tuple))

    def test_len(self):

        # Initial step: Feed in values to the vertices in the mesh
        t = IonTag('foo',1,'int', self.mesh)

        for x,v in enumerate(vertices(self.mesh)):
            t[v] = (x,)

        # test len
        self.assertEqual(len(t), self.mesh.num_vertices())

    def test_types(self):
        # test with different types:
        #@todo for each type check that input is cast to type

        #---------------------------------------------------------------------------------------
        # Ints
        #---------------------------------------------------------------------------------------

        t = IonTag('foo',3,'int', self.mesh)
        self.assertEqual(t._type, 'int')

        # Add some float values to the tag, and check if they are converted to
        # int tag values

        values = [1.23,2.232,3.323] # a list of int values
        v = MeshEntity(self.mesh,0,1)
        t[v] = values

        for key, item in t.iteritems():
            for num in item:
                self.assertTrue(isinstance(num, int))

        #---------------------------------------------------------------------------------------
        # Floats
        #---------------------------------------------------------------------------------------

        t = IonTag('foo',3,'float', self.mesh)
        self.assertEqual(t._type, 'float')

        # Add some int values to the tag, and check if they are converted to
        # float tag values

        values = [1,2,3] # a list of int values
        v = MeshEntity(self.mesh,0,1)
        t[v] = values

        for key, item in t.iteritems():
            for num in item:
                self.assertTrue(isinstance(num, float))

        # now pass in complex values
        values = [complex(1,2), complex(3,4), complex(5,6), complex(7,8)]

        try:
            t[v] = values
        except TypeError:
            pass
        else:
            raise AssertionError('Did not raise type error. Python should complain when converting from complex to float')

        for key, item in t.iteritems():
            for num in item:
                self.assertTrue(isinstance(num, float))

        #---------------------------------------------------------------------------------------
        # Complex
        #---------------------------------------------------------------------------------------

        t = IonTag('foo',3,'complex', self.mesh)
        self.assertEqual(t._type, 'complex')

        values = [1,2,3,4,5]

        v = MeshEntity(self.mesh,0,1)
        t[v] = values

        for key, item in t.iteritems():
            for num in item:
                self.assertTrue(isinstance(num, complex))

        #---------------------------------------------------------------------------------------
        # String
        #---------------------------------------------------------------------------------------

        #@todo: Strings cannot be passed in. This is because it is a variable sized data type, and numpy cannot handle it

#        t = IonTag('foo',3,'string', self.mesh)
#        self.assertEqual(t._type, 'string')
#
#        v = MeshEntity(self.mesh,0,1)
#
#        # passing in a string
#        values = ['string1', '   string2']
#        t[v] = values
#
#        # passing in a number
#        values = [3,4]
#        try:
#            t[v] = values
#        except ValueError:
#            pass
#        else:
#            raise AssertionError('Numpy should complain')
#
#
#        for key, item in t.iteritems():
#            for num in item:
#                self.assertTrue(isinstance(num, str))

        #---------------------------------------------------------------------------------------
        # User defined
        #---------------------------------------------------------------------------------------

        # t = IonTag('foo',3,'user_defined', self.mesh)
#        self.assertEqual(t._type, 'user_defined')

        #---------------------------------------------------------------------------------------
        # Object
        #---------------------------------------------------------------------------------------

        #@todo: numpy cannot create object arrays from iterator. so objects cannot be passed in as values
#        t = IonTag('foo',3,'object', self.mesh)
#        self.assertEqual(t._type, 'object')
#
#        values = [1,2,3,4]
#
#        v = MeshEntity(self.mesh,0,1)
#        t[v] = values
#
#        for key, item in t.iteritems():
#            for num in item:
#                self.assertTrue(isinstance(num, object))


    def test_iter(self):
        # test the iterator and verify that the correct type is passed back

        #------------------------------------------------------------
        # Initial step: Feed in values to the vertices in the mesh
        #------------------------------------------------------------

        t = IonTag('foo',1,'int', self.mesh)

        for x,v in enumerate(vertices(self.mesh)):
            t[v] = (x,)

        #------------------------------------------------------------
        # Test the iteration over the tags
        #------------------------------------------------------------

        for key, item in t.iteritems():
            self.assertEqual(t[ key ], item  )
            self.assertTrue(isinstance(key, MeshEntity))
            self.assertTrue(isinstance(item[0], int ))


    def test_properties(self):
        # contains, len etc...
        #@todo may be we can remove this test method as the contains() and len() methods have their own separate test methods
        pass
Beispiel #8
0
import numpy
from dolfin import Mesh

mesh = Mesh("mesh.xml.gz")

E = mesh.cells()
M = numpy.fromfile('materials.np')

I = -numpy.ones(mesh.num_vertices())

for i in range(6):
    edx = numpy.nonzero((M > 10 * (i + 1)) * (M < 10 * (i + 2)))[0]
    idx = (numpy.unique(E[edx, 0:3])).astype(int)
    I[idx] = i * 0.2

edx = numpy.nonzero(M == 7)[0]
idx = (numpy.unique(E[edx, 0:3])).astype(int)
I[idx] = -2

from viper import Viper

pv = Viper(mesh, I)
pv.interactive()
Beispiel #9
0
    def test_convert_triangle(self): # Disabled because it fails, see FIXME below
        # test no. 1
        from dolfin import Mesh, MPI
        if MPI.num_processes() != 1:
            return
        fname = os.path.join("data", "triangle")
        dfname = fname+".xml"
        
        # Read triangle file and convert to a dolfin xml mesh file
        meshconvert.triangle2xml(fname, dfname)

        # Read in dolfin mesh and check number of cells and vertices
        mesh = Mesh(dfname)
        self.assertEqual(mesh.num_vertices(), 96)
        self.assertEqual(mesh.num_cells(), 159)

        # Clean up
        os.unlink(dfname)


        # test no. 2
        from dolfin import MPI, Mesh, MeshFunction, \
                           edges, Edge, faces, Face, \
                           SubsetIterator, facets, CellFunction
        if MPI.num_processes() != 1:
            return
        fname = os.path.join("data", "test_Triangle_3")
        dfname = fname+".xml"
        dfname0 = fname+".attr0.xml"

        # Read triangle file and convert to a dolfin xml mesh file
        meshconvert.triangle2xml(fname, dfname)

        # Read in dolfin mesh and check number of cells and vertices
        mesh = Mesh(dfname)
        mesh.init()
        mfun = MeshFunction('double', mesh, dfname0)
        self.assertEqual(mesh.num_vertices(), 58)
        self.assertEqual(mesh.num_cells(), 58)

        # Create a size_t CellFunction and assign the values based on the
        # converted Meshfunction
        cf = CellFunction("size_t", mesh)
        cf.array()[mfun.array()==10.0] = 0
        cf.array()[mfun.array()==-10.0] = 1

        # Meassure total area of cells with 1 and 2 marker
        add = lambda x, y : x+y
        area0 = reduce(add, (Face(mesh, cell.index()).area() \
                             for cell in SubsetIterator(cf, 0)), 0.0)
        area1 = reduce(add, (Face(mesh, cell.index()).area() \
                             for cell in SubsetIterator(cf, 1)), 0.0)
        total_area = reduce(add, (face.area() for face in faces(mesh)), 0.0)

        # Check that all cells in the two domains are either above or below y=0
        self.assertTrue(all(cell.midpoint().y()<0 for cell in SubsetIterator(cf, 0)))
        self.assertTrue(all(cell.midpoint().y()>0 for cell in SubsetIterator(cf, 1)))
        
        # Check that the areas add up
        self.assertAlmostEqual(area0+area1, total_area)
        
        # Measure the edge length of the two edge domains
        edge_markers = mesh.domains().facet_domains()
        self.assertTrue(edge_markers is not None)
        length0 = reduce(add, (Edge(mesh, e.index()).length() \
                            for e in SubsetIterator(edge_markers, 0)), 0.0)
        length1 = reduce(add, (Edge(mesh, e.index()).length() \
                            for e in SubsetIterator(edge_markers, 1)), 0.0)
        
        # Total length of all edges and total length of boundary edges
        total_length = reduce(add, (e.length() for e in edges(mesh)), 0.0)
        boundary_length = reduce(add, (Edge(mesh, f.index()).length() \
                          for f in facets(mesh) if f.exterior()), 0.0)
        
        # Check that the edges add up
        self.assertAlmostEqual(length0+length1, total_length)
        self.assertAlmostEqual(length1, boundary_length)

        # Clean up
        os.unlink(dfname)
        os.unlink(dfname0)
Beispiel #10
0
    def test_convert_triangle(
            self):  # Disabled because it fails, see FIXME below

        # test no. 1
        from dolfin import Mesh, MPI

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

        # Read triangle file and convert to a dolfin xml mesh file
        meshconvert.triangle2xml(fname, dfname)

        # Read in dolfin mesh and check number of cells and vertices
        mesh = Mesh(dfname)
        self.assertEqual(mesh.num_vertices(), 96)
        self.assertEqual(mesh.num_cells(), 159)

        # Clean up
        os.unlink(dfname)

        # test no. 2
        from dolfin import MPI, Mesh, MeshFunction, \
                           edges, Edge, faces, Face, \
                           SubsetIterator, facets

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

        # Read triangle file and convert to a dolfin xml mesh file
        meshconvert.triangle2xml(fname, dfname)

        # Read in dolfin mesh and check number of cells and vertices
        mesh = Mesh(dfname)
        mesh.init()
        mfun = MeshFunction('double', mesh, dfname0)
        self.assertEqual(mesh.num_vertices(), 58)
        self.assertEqual(mesh.num_cells(), 58)

        # Create a size_t MeshFunction and assign the values based on the
        # converted Meshfunction
        cf = MeshFunction("size_t", mesh, mesh.topology().dim())
        cf.array()[mfun.array() == 10.0] = 0
        cf.array()[mfun.array() == -10.0] = 1

        # Meassure total area of cells with 1 and 2 marker
        add = lambda x, y: x + y
        area0 = reduce(add, (Face(mesh, cell.index()).area() \
                             for cell in SubsetIterator(cf, 0)), 0.0)
        area1 = reduce(add, (Face(mesh, cell.index()).area() \
                             for cell in SubsetIterator(cf, 1)), 0.0)
        total_area = reduce(add, (face.area() for face in faces(mesh)), 0.0)

        # Check that all cells in the two domains are either above or below y=0
        self.assertTrue(
            all(cell.midpoint().y() < 0 for cell in SubsetIterator(cf, 0)))
        self.assertTrue(
            all(cell.midpoint().y() > 0 for cell in SubsetIterator(cf, 1)))

        # Check that the areas add up
        self.assertAlmostEqual(area0 + area1, total_area)

        # Measure the edge length of the two edge domains
        #edge_markers = mesh.domains().facet_domains()
        edge_markers = mesh.domains().markers(mesh.topology().dim() - 1)
        self.assertTrue(edge_markers is not None)
        #length0 = reduce(add, (Edge(mesh, e.index()).length() \
        #                    for e in SubsetIterator(edge_markers, 0)), 0.0)
        length0, length1 = 0.0, 0.0
        for item in list(edge_markers.items()):
            if item[1] == 0:
                e = Edge(mesh, int(item[0]))
                length0 += Edge(mesh, int(item[0])).length()
            elif item[1] == 1:
                length1 += Edge(mesh, int(item[0])).length()

        # Total length of all edges and total length of boundary edges
        total_length = reduce(add, (e.length() for e in edges(mesh)), 0.0)
        boundary_length = reduce(add, (Edge(mesh, f.index()).length() \
                          for f in facets(mesh) if f.exterior()), 0.0)

        # Check that the edges add up
        self.assertAlmostEqual(length0 + length1, total_length)
        self.assertAlmostEqual(length1, boundary_length)

        # Clean up
        os.unlink(dfname)
        os.unlink(dfname0)
Beispiel #11
0

if __name__ == "__main__":

    xlim = 0.0, 3.0
    ylim = 0.0, 0.0127
    WAid = 12
    INid = 13
    BND_ids = WAid, INid
    meszf = 0.001  # mesh element size factor

    Domain, Facets = Generate_PBRpygmsh(xlim,
                                        ylim,
                                        BND_ids,
                                        meszf,
                                        folder='pygmeshio_test')

    mesh_D = Mesh()
    with XDMFFile(Domain) as infile:
        infile.read(mesh_D)

    mesh_F = Mesh()
    with XDMFFile(Facets) as infile:
        infile.read(mesh_F)

    print('num_cells   :', mesh_D.num_cells())
    print('num_vertices:', mesh_D.num_vertices())
    print('cell_type   :', mesh_D.ufl_cell())
    #print('num_facets:', mesh_F.num_facets())
    #print('num_edges:', mesh_F.num_edges())
Beispiel #12
0
def scalar_laplacians(
    mesh: df.Mesh,
    markers: Optional[Dict[str, int]] = None,
    ffun: Optional[MeshFunction] = None,
    use_krylov_solver: bool = False,
    krylov_solver_atol: Optional[float] = None,
    krylov_solver_rtol: Optional[float] = None,
    krylov_solver_max_its: Optional[int] = None,
    verbose: bool = False,
    strict: bool = False,
) -> Dict[str, df.Function]:
    """
    Calculate the laplacians

    Arguments
    ---------
    mesh : dolfin.Mesh
       A dolfin mesh
    markers : dict (optional)
        A dictionary with the markers for the
        different bondaries defined in the facet function
        or within the mesh itself.
        The follwing markers must be provided:
        'base', 'lv', 'epi, 'rv' (optional).
        If the markers are not provided the following default
        vales will be used: base = 10, rv = 20, lv = 30, epi = 40.
    fiber_space : str
        A string on the form {familiy}_{degree} which
        determines for what space the fibers should be calculated for.
    use_krylov_solver: bool
        If True use Krylov solver, by default False
    krylov_solver_atol: float (optional)
        If a Krylov solver is used, this option specifies a
        convergence criterion in terms of the absolute
        residual. Default: 1e-15.
    krylov_solver_rtol: float (optional)
        If a Krylov solver is used, this option specifies a
        convergence criterion in terms of the relative
        residual. Default: 1e-10.
    krylov_solver_max_its: int (optional)
        If a Krylov solver is used, this option specifies the
        maximum number of iterations to perform. Default: 10000.
    verbose: bool
        If true, print more info, by default False
    strict: bool
        If true raise RuntimeError if solutions does not sum to 1.0
    """

    if not isinstance(mesh, df.Mesh):
        raise TypeError("Expected a dolfin.Mesh as the mesh argument.")

    # Init connectivities
    mesh.init(2)
    if ffun is None:
        ffun = df.MeshFunction("size_t", mesh, 2, mesh.domains())

    # Boundary markers, solutions and cases
    cases, boundaries, markers = find_cases_and_boundaries(ffun, markers)
    markers_str = "\n".join(
        ["{}: {}".format(k, v) for k, v in markers.items()])
    df.info(("Compute scalar laplacian solutions with the markers: \n"
             "{}").format(markers_str, ), )

    check_boundaries_are_marked(
        mesh=mesh,
        ffun=ffun,
        markers=markers,
        boundaries=boundaries,
    )

    # Compte the apex to base solutons
    num_vertices = mesh.num_vertices()
    num_cells = mesh.num_cells()
    if mesh.mpi_comm().size > 1:
        num_vertices = mesh.mpi_comm().allreduce(num_vertices)
        num_cells = mesh.mpi_comm().allreduce(num_cells)
    df.info("  Num vertices: {0}".format(num_vertices))
    df.info("  Num cells: {0}".format(num_cells))

    if "mv" in cases and "av" in cases:
        # Use Doste approach
        pass

    # Else use the Bayer approach
    return bayer(
        cases=cases,
        mesh=mesh,
        markers=markers,
        ffun=ffun,
        verbose=verbose,
        use_krylov_solver=use_krylov_solver,
        strict=strict,
        krylov_solver_atol=krylov_solver_atol,
        krylov_solver_rtol=krylov_solver_rtol,
        krylov_solver_max_its=krylov_solver_max_its,
    )
Beispiel #13
0
import numpy
from dolfin import Mesh

mesh = Mesh("mesh.xml.gz")

E = mesh.cells()
M = numpy.fromfile('materials.np');




I = -numpy.ones(mesh.num_vertices())

for i in range(6):
    edx = numpy.nonzero((M>10*(i+1))*(M<10*(i+2)))[0]
    idx = (numpy.unique(E[edx,0:3])).astype(int)
    I[idx] = i*0.2

edx = numpy.nonzero(M==7)[0]
idx = (numpy.unique(E[edx,0:3])).astype(int)
I[idx] = -2;


from viper import Viper

pv = Viper(mesh, I)
pv.interactive()


Beispiel #14
0
                                  dest='mesh_size',
                                  action='store_false')
    parser.set_defaults(mesh_size=False)

    args = parser.parse_args()

    h5_file = convert(args.input)

    # VTK visualize tags
    if args.save_pvd or args.mesh_size:
        h5 = HDF5File(mpi_comm_world(), h5_file, 'r')
        mesh = Mesh()
        h5.read(mesh, 'mesh', False)

        info('Mesh has %d cells' % mesh.num_cells())
        info('Mesh has %d vertices' % mesh.num_vertices())
        info('Box size %s' %
             (mesh.coordinates().max(axis=0) - mesh.coordinates().min(axis=0)))

        hmin, hmax = mesh.hmin(), mesh.hmax()
        info('Mesh has sizes %g %g' % (hmin, hmax))

        root = os.path.splitext(args.input)[0]
        tdim = mesh.topology().dim()

        data_sets = ('curves', 'surfaces', 'volumes')
        dims = (1, tdim - 1, tdim)
        for ds, dim in zip(data_sets, dims):
            if h5.has_dataset(ds):
                f = MeshFunction('size_t', mesh, dim, 0)
                h5.read(f, ds)