Ejemplo n.º 1
0
def demo_facetfunction(mesh):
    try:
        import dolfinplot as dfp
    except:
        raise IOError(
            "Misssing dolfinplot. git clone https://bitbucket.org/finsberg/dolfinplot.git"
        )
    import dolfin as df
    ffun = df.MeshFunction("size_t", mesh, 2, mesh.domains())
    bmesh = df.BoundaryMesh(mesh, "exterior")

    Vb = df.FunctionSpace(bmesh, "DG", 0)
    fb = df.Function(Vb)
    mapping = bmesh.entity_map(2)

    for cell in df.cells(bmesh):
        # fb.vector()[cell.index()] = ffun[mapping[cell.index()]]
        if ffun[mapping[cell.index()]] == 10:
            fb.vector()[cell.index()] = 1
        elif ffun[mapping[cell.index()]] == 30:
            fb.vector()[cell.index()] = 2
        elif ffun[mapping[cell.index()]] == 40:
            fb.vector()[cell.index()] = 0

    vtkfun = dfp.VTK_DolfinScalar(fb)
    vtkfun.SetEdgeColor((0, 0, 0))
    focal = (mesh.coordinates().T[0].max()) / 2.0
    vtkfun.Render(view="side", dpi=300, size=(1200, 800), focal=focal)
    #vtkfun.Show()
    return vtkfun
Ejemplo n.º 2
0
    def __init__(self, name: str, spec: FieldSpec, mesh: df.Mesh):

        self._boundary_mesh = df.BoundaryMesh(mesh, "exterior")
        self._boundary_function_space = df.FunctionSpace(
            self._boundary_mesh, "CG", 1)
        self._data = df.Function(self._boundary_function_space)
        super().__init__(name, spec)
Ejemplo n.º 3
0
    def __init__(self, *inputobj, **options):

        c = options.pop("c", "gold")
        alpha = options.pop("alpha", 1)
        exterior = options.pop("exterior", False)
        fast = options.pop("fast", False)
        computeNormals = options.pop("computeNormals", False)

        mesh, u = _inputsort(inputobj)
        if not mesh:
            return

        if exterior:
            import dolfin
            meshc = dolfin.BoundaryMesh(mesh, 'exterior')
        else:
            meshc = mesh

        poly = utils.buildPolyData(meshc.coordinates(),
                                   meshc.cells(),
                                   fast=fast)

        Actor.__init__(
            self,
            poly,
            c=c,
            alpha=alpha,
            computeNormals=computeNormals,
        )

        self.mesh = mesh  # holds a dolfin Mesh obj
        self.u = u  # holds a dolfin function_data
        # holds the actual values of u on the mesh
        self.u_values = _compute_uvalues(u, mesh)
Ejemplo n.º 4
0
def loadDolfin(filename, exterior=False):
    """Reads a `Fenics/Dolfin` file format (.xml or .xdmf).
    Return an ``Actor(vtkActor)`` object."""
    import sys
    if sys.version_info[0] < 3:
        return _loadDolfin_old(filename)

    import dolfin

    if filename.lower().endswith('.xdmf'):
        f = dolfin.XDMFFile(filename)
        m = dolfin.Mesh()
        f.read(m)
    else:
        m = dolfin.Mesh(filename)

    bm = dolfin.BoundaryMesh(m, "exterior")

    if exterior:
        poly = utils.buildPolyData(bm.coordinates(), bm.cells(), fast=True)
    else:
        polyb = utils.buildPolyData(bm.coordinates(), bm.cells(), fast=True)
        polym = utils.buildPolyData(m.coordinates(), m.cells(), fast=True)
        app = vtk.vtkAppendPolyData()
        app.AddInputData(polym)
        app.AddInputData(polyb)
        app.Update()
        poly = app.GetOutput()
    return Actor(poly).lw(0.1)
Ejemplo n.º 5
0
def p1_trace(fenics_space):
    """
    Return the P1 trace operator.

    This function returns a pair (space, trace_matrix),
    where space is a BEM++ space object and trace_matrix is the corresponding
    matrix that maps the coefficients of a FEniCS function to its boundary
    trace coefficients in the corresponding BEM++ space.

    """

    import dolfin  #pylint: disable=import-error
    from bempp.api.fenics_interface.coupling import fenics_space_info
    from bempp.api import function_space, grid_from_element_data
    import numpy as np

    family, degree = fenics_space_info(fenics_space)
    if not (family == 'Lagrange' and degree == 1):
        raise ValueError("fenics_space must be a p1 Lagrange space")

    mesh = fenics_space.mesh()

    boundary_mesh = dolfin.BoundaryMesh(mesh, "exterior", False)
    bm_nodes = boundary_mesh.entity_map(0).array().astype(np.int64)
    bm_coords = boundary_mesh.coordinates()
    bm_cells = boundary_mesh.cells()
    bempp_boundary_grid = grid_from_element_data(bm_coords.transpose(),
                                                 bm_cells.transpose())

    # First get trace space
    space = function_space(bempp_boundary_grid, "P", 1)

    # Now compute the mapping from FEniCS dofs to BEM++ dofs.

    # First the BEM++ dofs from the boundary vertices
    from scipy.sparse import coo_matrix
    bempp_dofs_from_b_vertices = p1_dof_to_vertex_matrix(space).transpose()

    # Now FEniCS vertices to boundary dofs
    b_vertices_from_vertices = coo_matrix(
        (np.ones(len(bm_nodes)), (np.arange(len(bm_nodes)), bm_nodes)),
        shape=(len(bm_nodes), mesh.num_vertices()),
        dtype='float64').tocsc()

    # Finally FEniCS dofs to vertices.
    vertices_from_fenics_dofs = coo_matrix(
        (np.ones(mesh.num_vertices()), (dolfin.dof_to_vertex_map(fenics_space),
                                        np.arange(mesh.num_vertices()))),
        shape=(mesh.num_vertices(), mesh.num_vertices()),
        dtype='float64').tocsc()

    # Get trace matrix by multiplication
    trace_matrix = bempp_dofs_from_b_vertices * \
        b_vertices_from_vertices * vertices_from_fenics_dofs

    # Now return everything
    return space, trace_matrix
Ejemplo n.º 6
0
 def test_bem_perf(self):
     mesh = df.UnitCubeMesh(15, 15, 15)
     boundary_mesh = df.BoundaryMesh(mesh, 'exterior', False)
     c = time_counter.counter()
     while c.next():
         df.BoundaryMesh(mesh, 'exterior', False)
     print "Boundary mesh computation for %s: %s" % (mesh, c)
     c = time_counter.counter()
     while c.next():
         bem, _ = compute_bem_fk(boundary_mesh)
         n = bem.shape[0]
     print "FK BEM computation for %dx%d (%.2f Mnodes/sec): %s" % (
         n, n, c.calls_per_sec(n * n / 1e6), c)
     c = time_counter.counter()
     while c.next():
         bem, _ = compute_bem_gcr(boundary_mesh)
     print "GCR BEM computation for %dx%d (%.2f Mnodes/sec): %s" % (
         n, n, c.calls_per_sec(n * n / 1e6), c)
Ejemplo n.º 7
0
    def test_snap_nearest(self):
        mesh = df.UnitCubeMesh(10, 10, 10)
        mesh = df.BoundaryMesh(mesh, 'exterior')
        V = df.FunctionSpace(mesh, 'CG', 2)
        f = df.interpolate(df.Expression('sin(x[0]+x[1]+x[2])', degree=2), V)

        # A proxy expression whose action at x eval f at closest point dof to x
        f_ = snap_to_nearest(f)
        self.assertTrue(abs(f_(1., 1., 1.) - f(1., 1., 1.)) < 1E-13)
        self.assertTrue(abs(f_(1.1, 1.1, 1.1) - f(1., 1., 1.)) < 1E-13)
Ejemplo n.º 8
0
    def calculate_residual(self, mesh2):
        boundmesh = dolfin.BoundaryMesh(mesh2, "exterior")
        d = max(
            [
                self.bbtree.query(dolfin.Vertex(boundmesh, v_idx).point().array())[0]
                for v_idx in range(boundmesh.num_vertices())
            ]
        )

        return dolfin.MPI.max(mpi_comm_world(), d)
Ejemplo n.º 9
0
def p1_trace(fenics_space):
    """
    Return the P1 trace operator.

    This function returns a pair (space, trace_matrix),
    where space is a Bempp space object and trace_matrix is the corresponding
    matrix that maps the coefficients of a FEniCS function to its boundary
    trace coefficients in the corresponding Bempp space.

    """

    import dolfin
    import bempp.api
    from scipy.sparse import coo_matrix
    import numpy as np

    family, degree = fenics_space_info(fenics_space)
    if not (family == "Lagrange" and degree == 1):
        raise ValueError("fenics_space must be a p1 Lagrange space")

    mesh = fenics_space.mesh()

    boundary_mesh = dolfin.BoundaryMesh(mesh, "exterior", False)
    bm_nodes = boundary_mesh.entity_map(0).array().astype(np.int64)
    bm_coords = boundary_mesh.coordinates()
    bm_cells = boundary_mesh.cells()
    bempp_boundary_grid = bempp.api.Grid(bm_coords.transpose(),
                                         bm_cells.transpose())

    # First get trace space
    space = bempp.api.function_space(bempp_boundary_grid, "P", 1)

    # Now FEniCS vertices to boundary dofs
    b_vertices_from_vertices = coo_matrix(
        (np.ones(len(bm_nodes)), (np.arange(len(bm_nodes)), bm_nodes)),
        shape=(len(bm_nodes), mesh.num_vertices()),
        dtype="float64",
    ).tocsc()

    # Finally FEniCS dofs to vertices.
    vertices_from_fenics_dofs = coo_matrix(
        (
            np.ones(mesh.num_vertices()),
            (dolfin.dof_to_vertex_map(fenics_space),
             np.arange(mesh.num_vertices())),
        ),
        shape=(mesh.num_vertices(), mesh.num_vertices()),
        dtype="float64",
    ).tocsc()

    # Get trace matrix by multiplication
    trace_matrix = b_vertices_from_vertices @ vertices_from_fenics_dofs

    # Now return everything
    return space, trace_matrix
Ejemplo n.º 10
0
 def calculate_residual(self, mesh2):
     boundmesh = df.BoundaryMesh(mesh2, "exterior")
     d = max(
         [
             self.bbtree.compute_closest_point(df.Vertex(boundmesh, v_idx).point())[
                 1
             ]
             for v_idx in range(boundmesh.num_vertices())
         ]
     )
     return df.MPI.max(df.mpi_comm_world(), d)
Ejemplo n.º 11
0
def boundary_grid_from_fenics_mesh(fenics_mesh):
    """
    Return a boundary grid from a FEniCS Mesh.
    """
    from bempp import grid_from_element_data

    bm = _dolfin.BoundaryMesh(fenics_mesh, "exterior", False)
    bm_coords = bm.coordinates()
    bm_cells  = bm.cells()
    bempp_boundary_grid = grid_from_element_data(bm_coords.transpose(),bm_cells.transpose())
    return bempp_boundary_grid
Ejemplo n.º 12
0
def _1d2d_mesh(n, m=None):
    '''Line mesh in 2d'''
    if m is None: m = n
    mesh1d = df.UnitSquareMesh(n, m)
    mesh1d = df.BoundaryMesh(mesh1d, 'exterior')

    cell_f = df.MeshFunction('size_t', mesh1d, 1, 0)
    df.CompiledSubDomain('near(x[0], 0) || near(x[1], 0)').mark(cell_f, 1)
    mesh1d = df.SubMesh(mesh1d, cell_f, 1)

    return mesh1d
Ejemplo n.º 13
0
    def __init__(self, *inputobj, **options):

        c = options.pop("c", "gold")
        alpha = options.pop("alpha", 1)
        wire = options.pop("wire", True)
        bc = options.pop("bc", None)
        exterior = options.pop("exterior", False)
        fast = options.pop("fast", False)
        computeNormals = options.pop("computeNormals", False)

        mesh, u = _inputsort(inputobj)
        if not mesh:
            return

        if exterior:
            import dolfin
            meshc = dolfin.BoundaryMesh(mesh, 'exterior')
        else:
            meshc = mesh

        poly = utils.buildPolyData(meshc.coordinates(),
                                   meshc.cells(),
                                   fast=fast)

        Actor.__init__(
            self,
            poly,
            c=c,
            alpha=alpha,
            wire=wire,
            bc=bc,
            computeNormals=computeNormals,
        )

        self.mesh = mesh  # holds a dolfin Mesh obj
        self.u = u  # holds a dolfin function_data
        self.u_values = None  # holds the actual values of u on the mesh
        u_values = None

        if u:
            u_values = np.array([u(p) for p in self.mesh.coordinates()])
            #print(u_values)

        if u_values is not None:  # colorize if a dolfin function is passed
            if len(u_values.shape) == 2:
                if u_values.shape[1] in [2, 3]:  # u_values is 2D or 3D
                    self.u_values = u_values
                    dispsizes = utils.mag(u_values)
            else:  # u_values is 1D
                dispsizes = u_values

            self.addPointScalars(dispsizes, "u_values")  #.mapPointsToCells()
Ejemplo n.º 14
0
def p1_trace(fenics_space):

    import dolfin
    from .coupling import fenics_space_info
    from bempp import function_space, grid_from_element_data
    import numpy as np

    family, degree = fenics_space_info(fenics_space)
    if not (family == 'Lagrange' and degree == 1):
        raise ValueError("fenics_space must be a p1 Lagrange space")

    mesh = fenics_space.mesh()

    bm = dolfin.BoundaryMesh(mesh, "exterior", False)
    bm_nodes = bm.entity_map(0).array().astype(np.int64)
    bm_coords = bm.coordinates()
    bm_cells = bm.cells()
    bempp_boundary_grid = grid_from_element_data(bm_coords.transpose(),
                                                 bm_cells.transpose())

    # First get trace space
    space = function_space(bempp_boundary_grid, "P", 1)

    # Now compute the mapping from BEM++ dofs to FEniCS dofs

    # First the BEM++ dofs to the boundary vertices
    from ._lagrange_coupling import p1_vertex_map
    from scipy.sparse import coo_matrix
    vertex_to_dof_map = p1_vertex_map(space)
    vertex_indices = np.arange(space.global_dof_count)
    data = np.ones(space.global_dof_count)
    bempp_dofs_from_b_vertices = coo_matrix(
        (data, (vertex_to_dof_map, vertex_indices)), dtype='float64').tocsr()

    # Now the boundary vertices to all the vertices
    b_vertices_from_vertices = coo_matrix(
        (np.ones(len(bm_nodes)), (np.arange(len(bm_nodes)), bm_nodes)),
        shape=(len(bm_nodes), mesh.num_vertices()),
        dtype='float64').tocsr()

    # Finally the vertices to FEniCS dofs
    vertices_from_fenics_dofs = coo_matrix(
        (np.ones(mesh.num_vertices()), (dolfin.dof_to_vertex_map(fenics_space),
                                        np.arange(mesh.num_vertices()))),
        shape=(mesh.num_vertices(), mesh.num_vertices()),
        dtype='float64').tocsr()

    # Get trace matrix by multiplication
    trace_matrix = bempp_dofs_from_b_vertices * b_vertices_from_vertices * vertices_from_fenics_dofs

    # Now return everything
    return (space, trace_matrix)
Ejemplo n.º 15
0
def _1d3d_mesh(n):
    '''Line mesh in 3d'''
    mesh1d = df.UnitCubeMesh(n, n, n)

    cell_f = df.MeshFunction('size_t', mesh1d, 3, 0)
    df.CompiledSubDomain('x[0] > x[1] - DOLFIN_EPS').mark(cell_f, 1)#
    mesh1d = df.BoundaryMesh(df.SubMesh(mesh1d, cell_f, 1), 'exterior')
    
    cell_f = df.MeshFunction('size_t', mesh1d, 2, 0)
    df.CompiledSubDomain('near(x[0], x[1])').mark(cell_f, 1)
    mesh1d = df.SubMesh(mesh1d, cell_f, 1)

    cell_f = df.MeshFunction('size_t', mesh1d, 2, 0)
    df.CompiledSubDomain('x[2] < x[1] + DOLFIN_EPS').mark(cell_f, 1)
    mesh1d = df.BoundaryMesh(df.SubMesh(mesh1d, cell_f, 1), 'exterior')
    
    cell_f = df.MeshFunction('size_t', mesh1d, 1, 0)
    df.CompiledSubDomain('near(x[2], x[1])').mark(cell_f, 1)
    mesh1d = df.SubMesh(mesh1d, cell_f, 1)


    return mesh1d
Ejemplo n.º 16
0
 def test_cell_ordering(self):
     mesh = df.UnitCubeMesh(1, 1, 1)
     centre = np.array([0.5, 0.5, 0.5])
     boundary_mesh = df.BoundaryMesh(mesh, 'exterior', False)
     coordinates = boundary_mesh.coordinates()
     for i in xrange(boundary_mesh.num_cells()):
         cell = df.Cell(boundary_mesh, i)
         p1 = coordinates[cell.entities(0)[0]]
         p2 = coordinates[cell.entities(0)[1]]
         p3 = coordinates[cell.entities(0)[2]]
         n = np.cross(p2 - p1, p3 - p1)
         print "Boundary face %d, normal orientation %g" % (
             i, np.sign(np.dot(n, p1 - centre)))
Ejemplo n.º 17
0
def check_boundaries_are_marked(
    mesh: df.Mesh,
    ffun: df.MeshFunction,
    markers: Dict[str, int],
    boundaries: List[str],
) -> None:
    # Check that all boundary faces are marked
    num_boundary_facets = df.BoundaryMesh(mesh, "exterior").num_cells()
    if num_boundary_facets != sum(
        [np.sum(ffun.array() == markers[boundary])
         for boundary in boundaries], ):

        raise RuntimeError(
            ("Not all boundary faces are marked correctly. Make sure all "
             "boundary facets are marked as: {}"
             "").format(", ".join(
                 ["{} = {}".format(k, v) for k, v in markers.items()])), )
Ejemplo n.º 18
0
def boundary_grid_from_fenics_mesh(fenics_mesh):
    """
    Create a Bempp boundary grid from a FEniCS Mesh.

    Return the Bempp grid and a map from the node numberings of the FEniCS
    mesh to the node numbers of the boundary grid.
    """
    import bempp.api
    import numpy as np

    boundary_mesh = _dolfin.BoundaryMesh(fenics_mesh, "exterior", False)
    bm_coords = boundary_mesh.coordinates()
    bm_cells = boundary_mesh.cells()
    bm_nodes = boundary_mesh.entity_map(0).array().astype(np.int64)
    bempp_boundary_grid = bempp.api.Grid(bm_coords.transpose(),
                                         bm_cells.transpose())
    return bempp_boundary_grid, bm_nodes
Ejemplo n.º 19
0
    def __init__(self,mesh,m, parameters=sb.default_parameters , degree=1, element="CG",
                 project_method='magpar', unit_length=1,Ms = 1.0,bench = False,
                 mac=0.3,p=3,num_limit=100):
        
        sb.FemBemDeMagSolver.__init__(self,mesh,m, parameters, degree, element=element,
                                      project_method = project_method,
                                      unit_length = unit_length,Ms = Ms,bench = bench)
        self.__name__ = "Treecode Demag Solver"
        
        
        #Linear Solver parameters
        method = parameters["poisson_solver"]["method"]
        pc = parameters["poisson_solver"]["preconditioner"]
        
        self.poisson_solver = df.KrylovSolver(self.poisson_matrix, method, pc)

        self.phi1 = df.Function(self.V)
        self.phi2 = df.Function(self.V)

        # Eq (1) and code-block 2 - two first lines.
        b = self.Ms*df.inner(self.w, df.grad(self.v))*df.dx
        self.D = df.assemble(b)

        self.p=p
        self.mac=mac
        self.num_limit=num_limit
        
        self.mesh=mesh
        
        self.bmesh = df.BoundaryMesh(mesh,False)
        self.b2g_map = self.bmesh.vertex_map().array()
        
        self.compute_triangle_normal()

        self.__compute_bsa()
        
        fast_sum=FastSum(p=self.p,mac=self.mac,num_limit=self.num_limit)

        coords=self.bmesh.coordinates()
        face_nodes=np.array(self.bmesh.cells(),dtype=np.int32)
        
        fast_sum.init_mesh(coords,self.t_normals,face_nodes,self.vert_bsa)
        self.fast_sum=fast_sum
        
        self.phi2_b = np.zeros(self.bmesh.num_vertices())
Ejemplo n.º 20
0
def run_measurements(m, mesh, unit_length, tol, repetitions=10, H_expected=None, name="", skip=[]):
    S3 = df.VectorFunctionSpace(mesh, "CG", 1)
    m = vector_valued_function(m, S3)
    Ms = 1
    bem, boundary_to_global = compute_bem_fk(df.BoundaryMesh(mesh, 'exterior', False))

    if H_expected is not None:
        H = vector_valued_function(H_expected, S3)
        H_expected = H.vector().array()
    else:
        # use default/default as reference then.
        demag = fk.FKDemag()
        demag.precomputed_bem(bem, boundary_to_global)
        demag.setup(S3, m, Ms, unit_length)
        H_expected = demag.compute_field()
        del(demag)

    if name == "":
        pass
    else:
        name = name + "_"

    runner = create_measurement_runner(S3, m, Ms, unit_length,
                                       H_expected, tol, repetitions,
                                       bem, boundary_to_global)

    solvers = [s[0] for s in df.krylov_solver_methods()]
    preconditioners = [p[0] for p in df.krylov_solver_preconditioners()]

    results_1, failed_1 = runner("first linear solve",
                                 "phi_1_solver", solvers,
                                 "phi_1_preconditioner", preconditioners,
                                 skip,
                                 "{}timings_log_1.txt".format(name),
                                 "{}results_1.pickled".format(name))

    results_2, failed_2 = runner("second linear solve",
                                 "phi_2_solver", solvers,
                                 "phi_2_preconditioner", preconditioners,
                                 skip,
                                 "{}timings_log_2.txt".format(name),
                                 "{}results_2.pickled".format(name))

    return solvers, preconditioners, results_1, failed_1, results_2, failed_2
Ejemplo n.º 21
0
def run_demag_benchmark(m,
                        mesh,
                        unit_length,
                        tol,
                        repetitions=10,
                        name="bench",
                        H_expected=None):
    S3 = df.VectorFunctionSpace(mesh, "CG", 1)
    m = vector_valued_function(m, S3)
    Ms = 1

    # pre-compute BEM to save time
    bem, boundary_to_global = compute_bem_fk(
        df.BoundaryMesh(mesh, 'exterior', False))

    if H_expected is not None:
        H = vector_valued_function(H_expected, S3)
        H_expected = H.vector().array()
    else:  # if no H_expected was passed, use default/default as reference
        demag = fk.FKDemag()
        demag.precomputed_bem(bem, boundary_to_global)
        demag.setup(S3, m, Ms, unit_length)
        H_expected = demag.compute_field()
        del (demag)

    # gather all solvers and preconditioners
    solvers = [s[0] for s in df.krylov_solver_methods()]
    preconditioners = [p[0] for p in df.krylov_solver_preconditioners()]

    benchmark = prepare_benchmark(S3, m, Ms, unit_length, H_expected, tol,
                                  repetitions, bem, boundary_to_global)
    results_1 = benchmark("first linear solve",
                          "phi_1_solver",
                          solvers,
                          "phi_1_preconditioner",
                          preconditioners,
                          name=name + "_1")
    results_2 = benchmark("second linear solve",
                          "phi_2_solver",
                          solvers,
                          "phi_2_preconditioner",
                          preconditioners,
                          name=name + "_2")
    return solvers, preconditioners, results_1, results_2
Ejemplo n.º 22
0
    def __init__(self, mesh, bnd, bnd_id, tol=df.DOLFIN_EPS):

        df.SubDomain.__init__(self)
        self.mesh = mesh
        self.bnd = bnd
        self.bnd_id = bnd_id
        self.tol = tol

        # Pick a random vertex on the bnd (assuming this vertex is a node)
        facet_id = bnd.where_equal(bnd_id)[0]
        facet = list(facets(mesh))[facet_id]
        vertex_id = facet.entities(0)[0]
        self.vertex = mesh.coordinates()[vertex_id]

        self.bnd_facets = bnd.where_equal(bnd_id)

        self.bmesh = df.BoundaryMesh(mesh, 'exterior')
        facet_dim = self.bmesh.topology().dim()
        self.cell_map = self.bmesh.entity_map(facet_dim)
Ejemplo n.º 23
0
    def run_bem_computation_test(self, mesh):
        S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=3)
        m = df.interpolate(df.Constant((1, 0, 0)), S3)
        Ms = 1.0

        bem_magpar, g2finmag = belement.BEM_matrix(mesh)
        bem_finmag = np.zeros(bem_magpar.shape)
        bem, b2g = compute_bem_fk(df.BoundaryMesh(mesh, 'exterior', False))
        for i_dolfin in xrange(bem.shape[0]):
            i_finmag = g2finmag[b2g[i_dolfin]]

            for j_dolfin in xrange(bem.shape[0]):
                j_finmag = g2finmag[b2g[j_dolfin]]
                bem_finmag[i_finmag, j_finmag] = bem[i_dolfin, j_dolfin]
        if np.max(np.abs(bem_finmag - bem_magpar)) > 1e-12:
            print "Finmag:", np.round(bem_finmag, 4)
            print "Magpar:", np.round(bem_magpar, 4)
            print "Difference:", np.round(bem_magpar - bem_finmag, 4)
            self.fail("Finmag and magpar computation of BEM differ, mesh: " +
                      str(mesh))
Ejemplo n.º 24
0
def method(L=3., H=1., R=0.3, n_segments=40, res=60, show=False, **kwargs):
    """
    Generates mesh of Snausen/Snoevsen.
    """
    info("Generating mesh of Snoevsen.")

    # Define points:
    pt_A = df.Point(0., 0.)
    pt_B = df.Point(L, H)
    pt_C = df.Point(L / 2 - 2 * R, 0.)
    pt_D = df.Point(L / 2 + 2 * R, 0.)
    pt_E = df.Point(L / 2 - 2 * R, -R)
    pt_F = df.Point(L / 2 + 2 * R, -R)
    pt_G = df.Point(L / 2, -R)

    tube = mshr.Rectangle(pt_A, pt_B)
    add_rect = mshr.Rectangle(pt_E, pt_D)
    neg_circ_L = mshr.Circle(pt_E, R, segments=n_segments)
    neg_circ_R = mshr.Circle(pt_F, R, segments=n_segments)
    pos_circ = mshr.Circle(pt_G, R, segments=n_segments)

    domain = tube + add_rect - neg_circ_L - neg_circ_R + pos_circ

    mesh = mshr.generate_mesh(domain, res)

    # check that mesh is periodic along x
    boun = df.BoundaryMesh(mesh, "exterior")
    y = boun.coordinates()[:, 1]
    y = y[y < 1.]
    y = y[y > 0.]
    n_y = len(y)
    n_y_unique = len(np.unique(y))

    assert (n_y == 2 * n_y_unique)

    mesh_path = os.path.join(MESHES_DIR, "snoevsen_res" + str(res))
    store_mesh_HDF5(mesh, mesh_path)

    if show:
        df.plot(mesh, "Mesh")
        plt.show()
def main():
    resolution = 32  # 32 * 3
    # filename = 'data/mesh_res_%d_boundary.xml' % resolution
    filename = 'data/mesh_res_%d_boundary.xml' % resolution

    if os.path.exists(filename):
        print '=' * 60
        print 'Mesh file exists, loading from file'
        print '=' * 60
        mesh_3d = dolfin.Mesh(filename)
    else:
        geometry_3d = get_geometry()
        dolfin.info(geometry_3d, True)
        print '=' * 60
        print 'Creating mesh'
        print '=' * 60
        mesh_3d = dolfin.Mesh(geometry_3d, resolution)

        print '=' * 60
        print 'Converting to a boundary mesh'
        print '=' * 60
        mesh_3d = dolfin.BoundaryMesh(mesh_3d, 'exterior')
        # Since much smaller, it's much easier to refine the boundary mesh
        # as well. It may be worth doing this via:
        #     mesh_3d = dolfin.mesh.refine(mesh_3d)

        print '=' * 60
        print 'Saving to file:', filename
        print '=' * 60
        data_file = dolfin.File(filename)
        data_file << mesh_3d

    # Plot in either case.
    print '=' * 60
    print 'Plotting in interactive mode'
    print '=' * 60
    fh = dolfin.plot(mesh_3d,
                     '3D mesh',
                     interactive=True,
                     window_width=900,
                     window_height=700)
Ejemplo n.º 26
0
def mplot_mesh(ax, mesh, **kwargs):
    tdim = mesh.topology().dim()
    gdim = mesh.geometry().dim()
    if gdim == 2 and tdim == 2:
        return ax.triplot(mesh2triang(mesh), color='#808080')
    elif gdim == 3 and tdim == 3:
        bmesh = dolfin.BoundaryMesh(mesh, "exterior", order=False)
        mplot_mesh(ax, bmesh, **kwargs)
    elif gdim == 3 and tdim == 2:
        xy = mesh.coordinates()
        return ax.plot_trisurf(*[xy[:, i] for i in range(gdim)],
                               triangles=mesh.cells())
    elif tdim == 1 and gdim == 1:
        x = mesh.coordinates()[:, 0]
        return ax.plot(x, 0 * x, 'o')
    elif tdim == 1:
        x = [mesh.coordinates()[:, i] for i in range(gdim)]
        return ax.plot(*x)
    else:
        raise AttributeError(
            'Matplotlib plotting backend only supports 2D mesh.')
Ejemplo n.º 27
0
    def __init__(self, *inputobj, **options):

        c = options.pop("c", None)
        alpha = options.pop("alpha", 1)
        exterior = options.pop("exterior", False)
        fast = options.pop("fast", False)
        computeNormals = options.pop("computeNormals", False)

        mesh, u = _inputsort(inputobj)
        if not mesh:
            return

        if exterior:
            import dolfin
            meshc = dolfin.BoundaryMesh(mesh, 'exterior')
        else:
            meshc = mesh

        if hasattr(mesh, "coordinates"):
            coords = mesh.coordinates()
        else:
            coords = mesh.geometry.points

        poly = utils.buildPolyData(coords,
                                   meshc.cells(),
                                   fast=fast,
                                   tetras=True)

        Mesh.__init__(
            self,
            poly,
            c=c,
            alpha=alpha,
            computeNormals=computeNormals,
        )

        self.mesh = mesh  # holds a dolfin Mesh obj
        self.u = u  # holds a dolfin function_data
        # holds the actual values of u on the mesh
        self.u_values = _compute_uvalues(u, mesh)
Ejemplo n.º 28
0
def mplot_mesh(ax, mesh, **kwargs):
    tdim = mesh.topology().dim()
    gdim = mesh.geometry().dim()
    if gdim == 2 and tdim == 2:
        color = kwargs.pop("color", '#808080')
        return ax.triplot(mesh2triang(mesh), color=color, **kwargs)
    elif gdim == 3 and tdim == 3:
        bmesh = dolfin.BoundaryMesh(mesh, "exterior", order=False)
        mplot_mesh(ax, bmesh, **kwargs)
    elif gdim == 3 and tdim == 2:
        xy = mesh.coordinates()
        return ax.plot_trisurf(*[xy[:,i] for i in range(gdim)],
                triangles=mesh.cells(), **kwargs)
    elif tdim == 1:
        x = [mesh.coordinates()[:,i] for i in range(gdim)]
        if gdim == 1:
            x.append(np.zeros_like(x[0]))
            ax.set_yticks([])
        marker = kwargs.pop('marker', 'o')
        return ax.plot(*x, marker=marker, **kwargs)
    else:
        assert False, "this code should not be reached"
def selfsimilarprofiles(u, nu_t, x_coord, u_cl, y_half, mesh):
    """
    This routine computes
    - the adimensional y-coord y_hat = y / y_1/2
    - the adimensional velocity u_hat = u/u_cl
    - the adimensional viscosity nu_t_hat = nu_t / (u_hat * y_hat)
    
    INPUTS:
    - the velocity field u
    - the turbulent viscosity field nu_t
    - the list of x coordinates x_coord
    - the centerline velocities u_cl
    - the jet thickness y_1/2
    - the mesh
    """
    boundary_mesh = dl.BoundaryMesh(mesh, "exterior")
    x = boundary_mesh.coordinates()
    y_coord = x[np.abs(x[:, 0] - x_coord[0]) < 1e-9, 1]
    u1, u2 = u.split(deepcopy=True)

    u_hat = np.zeros((y_coord.shape[0], x_coord.shape[0]))
    y_hat = np.zeros((y_coord.shape[0], x_coord.shape[0]))
    nu_t_hat = np.zeros((y_coord.shape[0], x_coord.shape[0]))

    j = 0
    for xj in x_coord:
        u_clj = u_cl[j]
        y_halfj = y_half[j]
        i = 0
        for yi in y_coord:
            y_hat[i, j] = yi / y_halfj
            u_hat[i, j] = u1((xj, yi)) / u_clj
            nu_t_hat[i, j] = nu_t((xj, yi)) / (u_clj * y_halfj)
            i += 1
        j += 1

    return y_hat, u_hat, nu_t_hat
def spreadFunction(u, mesh, x_max=None):
    """
    This routine computes the following quantities as a function of the distance x from the inflow:
    - The centerline velocity: u_cl
    - The integral jet thickness: L
    - The spread function (derivative of jet thickness): S
    - The jet thickness: y_1/2
    
    INPUTS:
    - the velocity u
    - the mesh mesh
    """
    boundary_mesh = dl.BoundaryMesh(mesh, "exterior")
    x = boundary_mesh.coordinates()
    x_coord = x[np.abs(x[:, 1]) < 1e-9, 0]
    if x_max is not None:
        x_coord = x_coord[x_coord <= x_max]
    e1 = dl.Expression(("1.", "0."))
    u1, u2 = u.split(deepcopy=True)

    Vh_grad = dl.FunctionSpace(mesh, 'RT', 1)
    grad_u1 = dl.Function(Vh_grad)
    test = dl.TestFunction(Vh_grad)
    n = dl.FacetNormal(mesh)
    dl.solve(
        dl.inner(grad_u1, test) * dl.dx + u1 * dl.div(test) * dl.dx -
        u1 * dl.dot(test, n) * dl.ds == 0, grad_u1)

    axis = dl.AutoSubDomain(lambda x: dl.near(x[1], 0.))
    axis_mesh = dl.SubMesh(boundary_mesh, axis)
    Vh_axis = dl.FunctionSpace(axis_mesh, "CG", 2)
    u1_axis = dl.interpolate(u1, Vh_axis)
    Vh_axis_grad = dl.FunctionSpace(axis_mesh, 'CG', 1)
    du1_dx = dl.Function(Vh_axis_grad)
    test_axis = dl.TestFunction(Vh_axis_grad)
    left_point = dl.AutoSubDomain(
        lambda x, on_boundary: dl.near(x[0], x_coord[0]) and on_boundary)
    right_point = dl.AutoSubDomain(
        lambda x, on_boundary: dl.near(x[0], x_coord[-1]) and on_boundary)
    bb_marker = dl.FacetFunction("size_t", axis_mesh)
    bb_marker.set_all(0)
    left_point.mark(bb_marker, 1)
    right_point.mark(bb_marker, 2)
    dss = dl.Measure("ds")[bb_marker]

    dl.solve(
        du1_dx * test_axis * dl.dx + u1_axis * test_axis.dx(0) * dl.dx +
        u1_axis * test_axis * dss(1) - u1_axis * test_axis * dss(2) == 0,
        du1_dx)

    u_cl = np.zeros(x_coord.shape)
    L = np.zeros(x_coord.shape)
    S = np.zeros(x_coord.shape)
    y_half = np.zeros(x_coord.shape)

    i = 0
    for xi in x_coord:
        line_segment = dl.AutoSubDomain(lambda x: dl.near(x[0], xi))
        markers = dl.FacetFunction("size_t", mesh)
        markers.set_all(0)
        line_segment.mark(markers, 1)

        if i == 0 or (i == (x_coord.shape[0] - 1) and x_max is None):
            ds = dl.ds[markers]
            int_u1 = dl.assemble(u1 * ds(1))
            int_du1_dx = dl.assemble(dl.dot(grad_u1, e1) * ds(1))
        else:
            dS = dl.dS[markers]
            int_u1 = dl.assemble(dl.avg(u1) * dS(1))
            int_du1_dx = dl.assemble(dl.avg(dl.dot(grad_u1, e1)) * dS(1))

        u_cl[i] = u1((xi, 0.))
        du_cl_dx = du1_dx((xi, 0.))
        L[i] = int_u1 / u_cl[i]
        S[i] = (int_du1_dx * u_cl[i] - int_u1 * du_cl_dx) / (u_cl[i] * u_cl[i])
        y_half[i] = _bisection(u1, 9., 0., .5 * u_cl[i], xi)

        i += 1

    out = np.zeros((x_coord.shape[0], 5), dtype=x_coord.dtype)
    out[:, 0] = x_coord
    out[:, 1] = u_cl
    out[:, 2] = L
    out[:, 3] = S
    out[:, 4] = y_half

    return out