示例#1
0
def main():
    points = [(1, 0), (1, 1), (-1, 1), (-1, -1), (1, -1), (1, 0)]
    facets = round_trip_connect(0, len(points) - 1)

    circ_start = len(points)
    points.extend((3 * np.cos(angle), 3 * np.sin(angle))
                  for angle in np.linspace(0, 2 * np.pi, 30, endpoint=False))

    facets.extend(round_trip_connect(circ_start, len(points) - 1))

    def needs_refinement(vertices, area):
        bary = np.sum(np.array(vertices), axis=0) / 3
        max_area = 0.001 + (la.norm(bary, np.inf) - 1) * 0.01
        return bool(area > max_area)

    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_holes([(0, 0)])
    info.set_facets(facets)

    mesh = triangle.build(info, refinement_func=needs_refinement)

    mesh_points = np.array(mesh.points)
    mesh_tris = np.array(mesh.elements)

    import matplotlib.pyplot as pt

    pt.triplot(mesh_points[:, 0], mesh_points[:, 1], mesh_tris)
    pt.show()
示例#2
0
def main():
    import meshpy.triangle as triangle
    import math
    import pickle

    segments = 50

    points = [(-5, -1), (-1, -1), (0, -1), (0, 0), (1, 0), (5, 0), (5, 1),
              (1, 1), (-1, 1), (-5, 1)]

    def round_trip_connect(seq):
        result = []
        for i in range(len(seq)):
            result.append((seq[i], seq[(i + 1) % len(seq)]))
        return result

    info = triangle.MeshInfo()
    info.set_points(points)

    info.set_facets(
        round_trip_connect([0, 1, 8, 9]) +
        round_trip_connect([1, 2, 3, 4, 7, 8]) +
        round_trip_connect([4, 5, 6, 7]))
    info.regions.resize(3)
    info.regions[0] = (-2, 0, 1, 0.1)
    info.regions[1] = (-0.5, 0, 0, 0.01)
    info.regions[2] = (1.5, 0.5, 1, 0.1)

    mesh = triangle.build(info)

    triangle.write_gnuplot_mesh("triangles.dat", mesh)

    mesh.write_neu(open("tri_pml.neu", "w"))
示例#3
0
def main():
    import meshpy.triangle as triangle
    import math

    points = [ (1,1),(-1,1),(-1,-1),(1,-1) ]

    def round_trip_connect(start, end):
      result = []
      for i in range(start, end):
        result.append((i, i+1))
      result.append((end, start))
      return result

    def needs_refinement(vertices, area ):
        vert_origin, vert_destination, vert_apex = vertices
        bary_x = (vert_origin.x + vert_destination.x + vert_apex.x) / 3
        bary_y = (vert_origin.y + vert_destination.y + vert_apex.y) / 3

        dist_center = math.sqrt( (bary_x-1)**2 + (bary_y-1)**2 )
        max_area = math.fabs( 0.05 * (dist_center-0.5) ) + 0.01
        return area > max_area

    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_facets(round_trip_connect(0, len(points)-1))

    mesh = triangle.build(info, refinement_func=needs_refinement)

    mesh.write_neu(open("nico.neu", "w"))
    triangle.write_gnuplot_mesh("triangles.dat", mesh)
示例#4
0
def create_mesh(WSP_points, max_volume=10000, min_angle=25):
    outer_polygon, *inner_polygons = simplify(WSP_points)
    inner_points_of_holes = [inner_point(pol) for pol in inner_polygons]

    points = outer_polygon

    last_point_number = len(outer_polygon) - 1
    facets = round_trip_connect(0, last_point_number)

    for pol in inner_polygons:
        points.extend(pol)
        facets.extend(
            round_trip_connect(last_point_number + 1,
                               last_point_number + len(pol)))
        last_point_number = last_point_number + len(pol)

    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_holes(inner_points_of_holes)
    info.set_facets(facets)

    mesh = triangle.build(info, max_volume=max_volume, min_angle=min_angle)

    mesh_points = np.array(mesh.points)
    mesh_tris = np.array(mesh.elements)
    mesh_facets = np.array(mesh.facets)

    return mesh_points, mesh_tris
示例#5
0
def main():
    import meshpy.triangle as triangle

    info = triangle.MeshInfo()
    info.set_points([ (1.5,1),(-1.2,1),(-1,-1),(1,-1)])
    info.set_facets([(0, 1), (1, 2), (2, 3), (3, 0)])

    mesh = triangle.build(info, max_volume=1e-3, min_angle=25)

    print("""
        <?xml version="1.0" encoding="UTF-8"?>

        <dolfin xmlns:dolfin="http://www.fenics.org/dolfin/">
          <mesh celltype="triangle" dim="2">
            <vertices size="%d">
        """ % len(mesh.points))

    for i, pt in enumerate(mesh.points):
      print('<vertex index="%d" x="%g" y="%g"/>' % (
              i, pt[0], pt[1]))

    print("""
        </vertices>
        <cells size="%d">
        """ % len(mesh.elements))

    for i, element in enumerate(mesh.elements):
      print('<triangle index="%d" v0="%d" v1="%d" v2="%d"/>' % (
              i, element[0], element[1], element[2]))

    print("""
            </cells>
          </mesh>
        </dolfin>
        """)
def main():
    import meshpy.triangle as triangle
    import numpy as np

    points = [(1, 1), (-1, 1), (-1, -1), (1, -1)]

    for pt in np.random.randn(100, 2):
        points.append(pt * 0.1)

    def round_trip_connect(start, end):
        result = []
        for i in range(start, end):
            result.append((i, i + 1))
        result.append((end, start))
        return result

    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_facets(round_trip_connect(0, 3))

    mesh = triangle.build(
        info, allow_volume_steiner=False, allow_boundary_steiner=False
    )

    triangle.write_gnuplot_mesh("triangles.dat", mesh)
示例#7
0
def method(Lx=1.,
           Ly=1.,
           scale=0.75,
           dx=0.02,
           show=False,
           polygon="flipper",
           center=(0.5, 0.5),
           **kwargs):
    edges = np.loadtxt(os.path.join(MESHES_DIR, polygon + ".edges"),
                       dtype=int).tolist()
    nodes = np.loadtxt(os.path.join(MESHES_DIR, polygon + ".nodes"))

    nodes[:, 0] -= 0.5 * np.max(nodes[:, 0])
    nodes[:, 1] -= 0.5 * np.max(nodes[:, 1])
    nodes[:, :] *= scale
    nodes[:, 0] += center[0] * Lx
    nodes[:, 1] += center[1] * Ly

    nodes = nodes.tolist()

    x_min, x_max = 0., Lx
    y_min, y_max = 0., Ly

    corner_pts = [(x_min, y_min), (x_max, y_min), (x_max, y_max),
                  (x_min, y_max)]

    outer_nodes, outer_edges = make_polygon(corner_pts, dx, len(nodes))
    nodes.extend(outer_nodes)
    edges.extend(outer_edges)

    if show:
        plot_edges(nodes, edges)

    mi = tri.MeshInfo()
    mi.set_points(nodes)
    mi.set_facets(edges)
    mi.set_holes([(center[0] * Lx, center[1] * Ly)])

    max_area = 0.5 * dx**2

    mesh = tri.build(mi,
                     max_volume=max_area,
                     min_angle=25,
                     allow_boundary_steiner=False)

    coords = np.array(mesh.points)
    faces = np.array(mesh.elements)

    if show:
        plot_faces(coords, faces)

    mesh = numpy_to_dolfin(coords, faces)

    if show:
        df.plot(mesh)
        plt.show()

    mesh_path = os.path.join(MESHES_DIR,
                             "{}_dx{}_Lx{}_Ly{}".format(polygon, dx, Lx, Ly))
    store_mesh_HDF5(mesh, mesh_path)
示例#8
0
def triang_export(path_to_ocean_scale,polygon_nu):
    """ Parameters: 
            path_to_ocean_scale:File name or path to IHO World Seas shapefile as 
            distributed in marineregions.org by Flanders Marine Institute. No 
            direct download is permitted as per License, hence no direct 
            availability through code. 
            Download the latest shapefile and use as input for this code.
            
            polygon_nu: Integer
            
            The polygon number as defined in the IHO World Seas 
            Shapefile from 0 to 21.
        
        Returns: 
            File of Numpy Arrays that includes an array of the 
            points and an array of the point combinations by index, that creates 
            every triangle mesh.
        
        Description:
            1. A shapefile with the IHO world seas polygons is read.
            2. An individual polygon from the former shapefile is used as basis
            for the creation of an exterior linering and facets .
            (order of linereings connection) that serves as input for 
            meshpy.triangle.
            3. Meshpy triangle result (points,facets) given as numpy arrays
            4. Refinement of meshpy triangles into 4 subdivisions for every 
            triangle taking the former point results.
            5.Values exported as numpy files with the number of the polygon as 
            the name.
            """
    gdf=gpd.read_file("{}.shp".format(path_to_ocean_scale))
    polygon=gdf.geometry.iloc[polygon_nu]
        
    linering=list(polygon.exterior.coords)
          
    facets=round_trip_connect(0,len(linering)-1)
    
    info=triangle.MeshInfo()
    info.set_points(linering)
    info.set_facets(facets)
    
    mesh=triangle.build(info,max_volume=0.2,min_angle=30)
    
    mesh_points=np.array(mesh.points)
    mesh_facets=np.array(mesh.facets)
    
    sub=triangle.subdivide_facets(4,mesh_points.tolist(),mesh_facets.tolist())
    
    sub_points=np.array(sub[0])
    sub_facets=np.array(sub[1])
    
    info.set_points(sub_points)
    info.set_facets(sub_facets)
    
    mesh2=triangle.build(info,max_volume=0.5,min_angle=30)
    
    mesh_points2=np.array(mesh2.points)
    mesh_tris2=np.array(mesh2.elements)
    
    np.savez("{}.npz".format(polygon_nu),mesh_points2,mesh_tris2)
示例#9
0
def create_hole_mesh(num_unknowns):
    def round_trip_connect(start, end):
        return [(i, i + 1) for i in range(start, end)] + [(end, start)]

    points = [(1 / 4, 0), (1 / 4, 1 / 4), (-1 / 4, 1 / 4), (-1 / 4, -1 / 4),
              (1 / 4, -1 / 4), (1 / 4, 0)]
    facets = round_trip_connect(0, len(points) - 1)

    circ_start = len(points)
    points.extend((1.5 * np.cos(angle), 1.5 * np.sin(angle))
                  for angle in np.linspace(0, 2 * np.pi, 30, endpoint=False))

    facets.extend(round_trip_connect(circ_start, len(points) - 1))
    maximum_area = 0.5 / num_unknowns

    def needs_refinement(vertices, area):
        bary = np.sum(np.array(vertices), axis=0) / 3
        max_area = maximum_area + (np.linalg.norm(bary, np.inf) -
                                   1 / 4) * maximum_area * 10
        return bool(area > max_area)

    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_holes([(0, 0)])
    info.set_facets(facets)

    mesh = triangle.build(info, refinement_func=needs_refinement)
    return mesh
示例#10
0
def test_tri_refinefunc(rfunc=None):
    from meshpy import triangle
    L = np.array([2., 2.])
    points = np.array([
        [0., 0.], [L[0], 0.], [L[0], L[1]], [0., L[1]]
    ])
    edges = np.array([
        [0, 1], [1, 2], [2, 3], [3, 0]
    ])
    mesh_data = triangle.MeshInfo()
    mesh_data.set_points(points)
    mesh_data.set_facets(edges.tolist())

    max_volume = 0.2**2
    min_angle = 20.

    mesh = triangle.build(
        mesh_data,
        max_volume=max_volume,
        min_angle=min_angle,
        refinement_func=rfunc
    )

    # Extract triangle vertices from triangulation adding back x coord
    points = np.column_stack((
        np.zeros(len(mesh.points)), np.array(mesh.points))
    )
    tris = np.array(mesh.elements, dtype=np.int32)
    holes = np.empty((0,3), dtype=np.float64)

    return points, tris, holes
示例#11
0
    def make_mesh(self, A=1):
        self.getpoints()

        # build the triangles
        info = triangle.MeshInfo()
        info.set_points(self.points)
        info.set_holes([self.l.loc])  #the lumen is clear, it's a "hole"
        info.set_facets(self.facets, facet_markers=self.markers)

        info.regions.resize(len(self.parts))

        j = 1

        wall_out_avg_x = (np.min(np.array(self.a.draw_inner())[:, 0]) + np.min(
            np.array(self.a.draw_outer())[:, 0])) / float(2)
        wall_in_avg_x = (np.min(np.array(self.a.draw_inner())[:, 0]) +
                         np.min(np.array(self.l.draw())[:, 0])) / float(2)
        avgs = [wall_out_avg_x, wall_in_avg_x]

        for part in self.parts:
            if j > 2:
                info.regions[j - 1] = [part.loc[0], part.loc[1], j, A]
                j = j + 1
            else:
                info.regions[j - 1] = [avgs[j - 1], 0, j, A]
                j = j + 1
        self.mesh_ = triangle.build(info,
                                    refinement_func=refinement_func,
                                    attributes=True)

        return self.mesh_
示例#12
0
def make_disk_mesh(r=0.5, faces=50, max_area=4e-3,
        boundary_tagger=(lambda fvi, el, fn, all_v: [])):
    from math import cos, sin, pi

    def needs_refinement(vertices, area):
        return area > max_area

    points = [(r*cos(angle), r*sin(angle))
            for angle in numpy.linspace(0, 2*pi, faces, endpoint=False)]

    import meshpy.triangle as triangle

    mesh_info = triangle.MeshInfo()
    mesh_info.set_points(points)
    mesh_info.set_facets(
            list(_round_trip_connect(0, faces-1)),
            faces*[1]
            )

    generated_mesh = triangle.build(mesh_info, refinement_func=needs_refinement)

    from hedge.mesh import make_conformal_mesh_ext
    from hedge.mesh.element import Triangle
    vertices = numpy.asarray(generated_mesh.points, dtype=float, order="C")
    return make_conformal_mesh_ext(
            vertices,
            [Triangle(i, el_idx, vertices)
                for i, el_idx in enumerate(generated_mesh.elements)],
            boundary_tagger)
示例#13
0
def fractal_1_square_rough_mesh(b, dx):
    if b == 0.0:
        pts_low = [(0.0, 0.0), (0.1, 0.0)]
    else:
        pts_low = [(0.0, -b / 6), (b / 6, -b / 6), (b / 6, -b / 2),
                   (b / 2, -b / 2), (b / 2, b / 2), (5 * b / 6, b / 2),
                   (5 * b / 6, b / 6), (7 * b / 6, b / 6), (7 * b / 6, b / 2),
                   (3 * b / 2, b / 2), (3 * b / 2, -b / 2),
                   (11 * b / 6, -b / 2), (11 * b / 6, -b / 6), (2 * b, -b / 6)]

    nodes = dict()
    edges = []

    pts = []
    for pt_low in pts_low:
        pts.append((pt_low[0], pt_low[1] - 1))

    for pt_low in pts_low[::-1]:
        pts.append((pt_low[0], -pt_low[1] + 1))
    pts.append(pts[0])

    for pta, ptb in zip(pts[:-1], pts[1:]):
        ra = np.array(pta)
        rb = np.array(ptb)
        dr = ra - rb
        drabs = np.sqrt(sum(dr**2))
        Nseg = int(np.ceil(drabs / dx))

        beta = np.linspace(0., 1., Nseg)
        rs = [tuple(betai * rb + (1 - betai) * ra) for betai in beta]
        for r in rs:
            if r not in nodes:
                nodes[r] = len(nodes)

        for ri, rj in zip(rs[:-1], rs[1:]):
            edge = [nodes[ri], nodes[rj]]
            edges.append(edge)

    nodes = dict2list(nodes)

    mi = tri.MeshInfo()
    mi.set_points(nodes)
    mi.set_facets(edges)

    max_area = 0.5 * dx**2

    mesh = tri.build(mi,
                     max_volume=max_area,
                     min_angle=25,
                     allow_boundary_steiner=False)

    coords = np.array(mesh.points)
    faces = np.array(mesh.elements)

    msh = numpy_to_dolfin(coords, faces)

    return msh
示例#14
0
def create_quality_mesh(num_unknowns):
    mesh_info = triangle.MeshInfo()
    points = [(1.5, 1.5), (-1.5, 1.5), (-1.5, -1.5), (1.5, -1.5)]
    segments = [(i, i + 1) for i in range(3)] + [(3, 0)]
    mesh_info.set_points(points)
    mesh_info.set_facets(segments)
    mesh = triangle.build(mesh_info,
                          max_volume=3 / (num_unknowns * 2**2),
                          min_angle=30)
    return mesh
示例#15
0
def make_poly_mesh(points, facets, facet_markers, refinement_func=None):
    import meshpy.triangle as triangle
    mesh_info = triangle.MeshInfo()
    mesh_info.set_points(points)
    mesh_info.set_facets(facets, facet_markers)
    mesh_info.holes.resize(1)
    mesh_info.holes[0] = [0, 0]
    return triangle.build(mesh_info,
                          refinement_func=refinement_func,
                          generate_edges=True)
示例#16
0
文件: section.py 项目: osolmaz/strut
    def generate_mesh(self, max_volume=None):
        info = triangle.MeshInfo()
        info.set_points(self.vertices)
        info.set_facets(round_trip_connect(0, len(self.vertices) - 1))

        if max_volume:
            self.mesh = triangle.build(info,
                                       max_volume=max_volume,
                                       min_angle=25)
        else:
            self.mesh = triangle.build(info, min_angle=25)
示例#17
0
def make_rect_mesh_with_corner(a=(0, 0), b=(1, 1), max_area=None,
        boundary_tagger=(lambda fvi, el, fn, all_v: []),
        corner_fraction=(0.3, 0.3),
        refine_func=None):
    """Create an unstructured rectangular mesh with a reentrant
    corner at (-x, -y).

    :param a: the lower left hand point of the rectangle
    :param b: the upper right hand point of the rectangle
    :param max_area: maximum area of each triangle.
    :param refine_func: A refinement function as taken by
      :func:`meshpy.triangle.build`.
    :param corner_fraction: Tuple of fraction of the width taken up by
      the rentrant corner.
    """
    if max_area is not None:
        if refine_func is not None:
            raise ValueError("cannot specify both refine_func and max_area")

        def refine_func(vertices, area):
            return area > max_area

    a = numpy.asarray(a)
    b = numpy.asarray(b)
    diag = b-a
    w = diag.copy()
    w[1] = 0
    h = diag.copy()
    h[0] = 0

    points = [
            a+h*corner_fraction[1],
            a+h*corner_fraction[1]+w*corner_fraction[0],
            a+w*corner_fraction[0],
            a+w,
            a+w+h,
            a+h,
            ]
    facets = list(_round_trip_connect(0, 5))
    facet_markers = [5, 6, 2, 3, 4, 1]

    import meshpy.triangle as triangle
    mesh_info = triangle.MeshInfo()
    mesh_info.set_points(points)
    mesh_info.set_facets(facets, facet_markers)

    generated_mesh = triangle.build(mesh_info,
            refinement_func=refine_func)

    from hedge.mesh import make_conformal_mesh
    return make_conformal_mesh(
            generated_mesh.points,
            generated_mesh.elements,
            boundary_tagger)
示例#18
0
def main():
    import meshpy.triangle as triangle
    import math
    import pickle

    segments = 50

    points = [(1, 0), (1, 1), (-1, 1), (-1, -1), (1, -1), (1, 0)]

    for i in range(0, segments + 1):
        angle = i * 2 * math.pi / segments
        points.append((0.5 * math.cos(angle), 0.5 * math.sin(angle)))

    def round_trip_connect(start, end):
        result = []
        for i in range(start, end):
            result.append((i, i + 1))
        result.append((end, start))
        return result

    def needs_refinement(vertices, area):
        vert_origin, vert_destination, vert_apex = vertices
        bary_x = (vert_origin.x + vert_destination.x + vert_apex.x) / 3
        bary_y = (vert_origin.y + vert_destination.y + vert_apex.y) / 3

        dist_center = math.sqrt(bary_x**2 + bary_y**2)
        max_area = 100 * (math.fabs(0.002 * (dist_center - 0.5)) + 0.0001)
        return area > max_area

    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_holes([(0, 0)])
    info.set_facets(round_trip_connect(0, len(points) - 1))

    mesh = triangle.build(
        info,
        refinement_func=needs_refinement,
    )

    triangle.write_gnuplot_mesh("triangles-unrefined.dat", mesh)
    print len(mesh.elements)

    mesh.element_volumes.setup()

    for i in range(len(mesh.elements)):
        mesh.element_volumes[i] = -1
    for i in range(0, len(mesh.elements), 10):
        mesh.element_volumes[i] = 1e-8

    mesh = triangle.refine(mesh)
    print len(mesh.elements)

    triangle.write_gnuplot_mesh("triangles.dat", mesh)
def triangulate_PSLGs(pslgs, area_constraints):
    """Triangulates lower boundaries along each coordinate axis using Shewchuk's
    Triangle library.
    :param pslgs list: list of PSLG objects for the boundaries.
    :param area_constraints AreaConstraints: object storing area constraint grids for
    quality triangulation.
    :return: list of BoundaryPLC objects for the triangulated boundaries.
    :rtype: list.
    """
    triangulated_boundaries = []
    for i, pslg in enumerate(pslgs):

        target_area_grid = area_constraints.grid[i]
        inv_dx = area_constraints.inv_dx[i]
        inv_dy = area_constraints.inv_dy[i]

        def rfunc(vertices, area):
            (ox, oy), (dx, dy), (ax, ay) = vertices
            cx = ONE_THIRD * (ox + dx + ax)  # Triangle center x coord.
            cy = ONE_THIRD * (oy + dy + ay)  # Triangle center y coord.
            ix = int(cx * inv_dx)
            iy = int(cy * inv_dy)
            target_area = target_area_grid[iy][ix]
            return int(area > target_area)  # True -> 1 means refine

        # Set mesh info for triangulation
        mesh_data = triangle.MeshInfo()
        mesh_data.set_points(pslg.points)
        mesh_data.set_facets(pslg.edges.tolist())
        if len(pslg.holes):
            mesh_data.set_holes(pslg.holes)

        # Call triangle library to perform Delaunay triangulation
        max_volume = area_constraints.dA_max
        min_angle = 20.

        mesh = triangle.build(mesh_data,
                              max_volume=max_volume,
                              min_angle=min_angle,
                              allow_boundary_steiner=False,
                              refinement_func=rfunc)

        # Extract triangle vertices from triangulation adding back x coord
        points = np.column_stack(
            (np.zeros(len(mesh.points)), np.array(mesh.points)))
        points = points[:, (-i % 3, (1 - i) % 3, (2 - i) % 3)]
        tris = np.array(mesh.elements)
        holes = np.column_stack(
            (np.zeros(len(mesh.holes)), np.array(mesh.holes)))
        holes = holes[:, (-i % 3, (1 - i) % 3, (2 - i) % 3)]

        triangulated_boundaries.append(BoundaryPLC(points, tris, holes))
    return triangulated_boundaries
示例#20
0
def create_mesh(points,
                facets,
                holes,
                control_points,
                mesh_sizes,
                atol=1.0e-8):
    """Creates a quadratic triangular mesh using the meshpy module, which utilises the code
    'Triangle', by Jonathan Shewchuk.

    :param points: List of points *(x, y)* defining the vertices of the cross-section
    :type points: list[list[float, float]]
    :param facets: List of point index pairs *(p1, p2)* defining the edges of the cross-section
    :type points: list[list[int, int]]
    :param holes: List of points *(x, y)* defining the locations of holes within the cross-section.
        If there are no holes, provide an empty list [].
    :type holes: list[list[float, float]]
    :param control_points: A list of points *(x, y)* that define different regions of the
        cross-section. A control point is an arbitrary point within a region enclosed by facets.
    :type control_points: list[list[float, float]]
    :param mesh_sizes: List of maximum element areas for each region defined by a control point
    :type mesh_sizes: list[float]
    :param atol: minimum permissable point distance from any section facet
    :type atol: float

    :return: Object containing generated mesh data
    :rtype: :class:`meshpy.triangle.MeshInfo`
    """

    check_geometry(points, facets, holes, control_points, atol=atol)

    mesh = triangle.MeshInfo()  # create mesh info object
    mesh.set_points(points)  # set points
    mesh.set_facets(facets)  # set facets
    mesh.set_holes(holes)  # set holes

    # set regions
    mesh.regions.resize(len(control_points))  # resize regions list
    region_id = 0  # initialise region ID variable

    for (i, cp) in enumerate(control_points):
        mesh.regions[i] = [cp[0], cp[1], region_id, mesh_sizes[i]]
        region_id += 1

    mesh = triangle.build(mesh,
                          min_angle=30,
                          mesh_order=2,
                          quality_meshing=True,
                          attributes=True,
                          volume_constraints=True)

    return mesh
示例#21
0
文件: mesh.py 项目: johnjohndoe/c3nav
def triangulate_rings(rings, holes=None):
    return (
        np.zeros((0, 2), dtype=np.uint32),
        np.zeros((0, 3), dtype=np.uint32),
    )

    rings = tuple(
        tuple(
            tuple(vertex) for vertex in np.rint(np.array(ring.coords) *
                                                1000).astype(np.int32))
        for ring in rings)

    if not rings:
        return np.empty((0, 2), dtype=np.int32), np.empty((0, 3),
                                                          dtype=np.uint32)

    vertices = tuple(set(chain(*rings)))
    vertices_lookup = {vertex: i for i, vertex in enumerate(vertices)}

    segments = set()
    for ring in rings:
        indices = tuple(vertices_lookup[vertex] for vertex in ring[:-1])
        segments.update(
            tuple(sorted((a, b)))
            for a, b in zip(indices, indices[1:] + indices[:1]) if a != b)

    if len(segments) < 3:
        return np.empty((0, 2), dtype=np.int32), np.empty((0, 3),
                                                          dtype=np.uint32)

    # noinspection PyArgumentList
    info = triangle.MeshInfo()
    info.set_points(np.array(vertices).tolist())
    info.set_facets(segments)

    if holes is not None:
        info.set_holes(np.rint(np.array(holes) * 1000))

    mesh = triangle.build(info, quality_meshing=False)

    mesh_points = np.rint(np.array(mesh.points)).astype(np.int32)
    mesh_elements = np.array(mesh.elements, dtype=np.uint32)

    # remove triangles with no area
    facets = np.dstack(
        (np.zeros(mesh_elements.shape), mesh_points[mesh_elements]))
    ok_index = np.cross(facets[:, 1] - facets[:, 0],
                        facets[:, 2] - facets[:, 1]).max(axis=1) != 0
    mesh_elements = mesh_elements[ok_index]

    return mesh_points, mesh_elements
示例#22
0
def createMesh(points, facets, holes=[], maxArea=[], minAngle=30, meshOrder=2,
               qualityMeshing=True):
    '''
    This function creates a quadratic triangular mesh using the meshpy module,
    which utilises the code 'Triangle', by Jonathan Shewchuk.
    '''
    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_holes(holes)
    info.set_facets(facets)

    return triangle.build(
        info, max_volume=maxArea, min_angle=minAngle, mesh_order=meshOrder,
        quality_meshing=qualityMeshing)
示例#23
0
def finish_2d_rect_mesh(points, facets, facet_markers, marker2tag, refine_func,
        periodicity, boundary_tagger):
    """Semi-internal bottom-half routine for generation of rectangular 2D meshes."""
    import meshpy.triangle as triangle

    mesh_info = triangle.MeshInfo()
    mesh_info.set_points(points)
    mesh_info.set_facets(facets, facet_markers)

    #triangle.write_gnuplot_mesh("mesh.dat", mesh_info, True)

    if periodicity is None:
        periodicity = (False, False)

    axes = ["x", "y"]
    mesh_periodicity = []
    periodic_tags = set()
    for i, axis in enumerate(axes):
        if periodicity[i]:
            minus_tag = "minus_"+axis
            plus_tag = "plus_"+axis
            mesh_periodicity.append((minus_tag, plus_tag))
            periodic_tags.add(minus_tag)
            periodic_tags.add(plus_tag)
        else:
            mesh_periodicity.append(None)

    generated_mesh = triangle.build(mesh_info,
            refinement_func=refine_func,
            allow_boundary_steiner=not (periodicity[0] or periodicity[1]))

    fmlookup = MeshPyFaceMarkerLookup(generated_mesh)

    def wrapped_boundary_tagger(fvi, el, fn, all_v):
        btag = marker2tag[fmlookup(fvi)]
        if btag in periodic_tags:
            return [btag]
        else:
            return [btag] + boundary_tagger(fvi, el, fn, all_v)

    vertices = numpy.asarray(generated_mesh.points, dtype=float, order="C")

    from hedge.mesh import make_conformal_mesh_ext
    from hedge.mesh.element import Triangle
    return make_conformal_mesh_ext(
            vertices,
            [Triangle(i, el_idx, vertices)
                for i, el_idx in enumerate(generated_mesh.elements)],
            wrapped_boundary_tagger,
            periodicity=mesh_periodicity)
示例#24
0
def test_point_attributes():
    import meshpy.triangle as triangle

    points = [(1, 1), (-1, 1), (-1, -1), (1, -1)]
    info = triangle.MeshInfo()
    info.set_points(points)

    info.number_of_point_attributes = 2

    info.point_attributes.setup()

    for i in range(len(points)):
        info.point_attributes[i] = [0, 0]

    triangle.build(info)
示例#25
0
def triangulate_polygon(polygon, **kwargs):
    """
    Given a shapely polygon create a triangulation using
    meshpy.triangle

    Parameters
    ---------
    polygon: Shapely.geometry.Polygon
    kwargs: passed directly to meshpy.triangle.build:
            triangle.build(mesh_info,
                           verbose=False,
                           refinement_func=None,
                           attributes=False,
                           volume_constraints=True,
                           max_volume=None,
                           allow_boundary_steiner=True,
                           allow_volume_steiner=True,
                           quality_meshing=True,
                           generate_edges=None,
                           generate_faces=False,
                           min_angle=None)
    Returns
    --------
    mesh_vertices: (n, 2) float array of 2D points
    mesh_faces:    (n, 3) int array of vertex indexes
    """
    # do the import here, as sometimes this import can segfault
    # which is not catchable with a try/except block
    import meshpy.triangle as triangle

    # turn the polygon in to vertices, segments, and hole points
    arg = _polygon_to_kwargs(polygon)
    # call meshpy.triangle on our cleaned representation of
    # the Shapely polygon
    info = triangle.MeshInfo()
    info.set_points(arg['vertices'])
    info.set_facets(arg['segments'])
    info.set_holes(arg['holes'])

    # build mesh and pass kwargs to triangle
    mesh = triangle.build(info, **kwargs)

    # (n, 2) float vertices
    vertices = np.array(mesh.points, dtype=np.float64)
    # (m, 3) int faces
    faces = np.array(mesh.elements, dtype=np.int64)

    return vertices, faces
示例#26
0
def main():
    points = []
    facets = []

    circ_start = len(points)
    points.extend(
            (3 * np.cos(angle), 3 * np.sin(angle))
            for angle in np.linspace(0, 2*np.pi, 30, endpoint=False))

    #boundaryPts1 = points[0:20]
    #boundaryFacets1 = []
    #boundaryFacets1.extend(round_trip_connect(21,31))
    boundaryPts1 = points[0:31]
    boundaryFacets1 = []
    facets.extend(round_trip_connect(circ_start, len(points)-1))

    def needs_refinement(vertices, area):
        bary = np.sum(np.array(vertices), axis=0)/3
        max_area = 0.001 + (la.norm(bary, np.inf)-1)*0.1
        return bool(area > max_area)

    def refinement2(vertices, area):
        return(area > 0.5)

    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_facets(facets)

    mesh = triangle.build(info, refinement_func = refinement2)

    mesh_points = np.array(mesh.points)
    mesh_tris = np.array(mesh.elements)
    boundary_points1 = []
    i = 0
    for meshPt in mesh_points:
        for point in boundaryPts1:
            if point == tuple(meshPt):
                boundary_points1.append(i)
                break
        i+=1

    mesh_out = [mesh_points, mesh_tris, [boundary_points1],[boundaryFacets1]]
    with open('mesh2.msh','wb') as outFile:
        pickle.dump(mesh_out,outFile)

    pt.triplot(mesh_points[:, 0], mesh_points[:, 1], mesh_tris)
    pt.show()
示例#27
0
文件: mesh.py 项目: hpc12/lec13-demo
def make_mesh():
    outline = np.loadtxt(sys.argv[1])

    def round_trip_connect(start, end):
        result = []
        for i in range(start, end):
            result.append((i, i + 1))
        result.append((end, start))
        return result

    info = triangle.MeshInfo()
    info.set_points(outline)
    info.set_facets(round_trip_connect(0, len(outline) - 1))

    return triangle.build(info,
                          refinement_func=getattr(
                              Refiners, "needs_refinement_%s" % sys.argv[2]))
示例#28
0
def main():
    points = [(1, 0), (1, 1), (-1, 1), (-1, -1), (1, -1), (1, 0)]
    facets = round_trip_connect(0, len(points) - 1)
    markers = [2, 2, 2, 2, 2, 2]

    outter_start = len(points)
    points.extend([(2, 0), (2, 2), (-2, 2), (-2, -2), (2, -2), (2, 0)])
    facets.extend(round_trip_connect(outter_start, len(points) - 1))
    markers.extend([3, 3, 3, 3, 3, 3])

    # build
    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_holes([(0, 0)])
    info.set_facets(facets, facet_markers=markers)

    #
    mesh = triangle.build(info, refinement_func=refinement_func)

    #
    mesh_points = np.array(mesh.points)
    mesh_tris = np.array(mesh.elements)
    mesh_attr = np.array(mesh.point_markers)

    print(mesh_attr)

    import matplotlib.pyplot as plt

    plt.triplot(mesh_points[:, 0], mesh_points[:, 1], mesh_tris)
    plt.xlabel("x")
    plt.ylabel("y")
    #
    n = np.size(mesh_attr)
    inner_nodes = [i for i in range(n) if mesh_attr[i] == 2]
    outer_nodes = [i for i in range(n) if mesh_attr[i] == 3]
    plt.plot(mesh_points[inner_nodes, 0], mesh_points[inner_nodes, 1], "ro")
    plt.plot(mesh_points[outer_nodes, 0], mesh_points[outer_nodes, 1], "go")
    plt.axis([-2.5, 2.5, -2.5, 2.5])
    # plt.show()
    #
    fig = plt.gcf()
    fig.set_size_inches(4.2, 4.2)
    plt.savefig("sec5-meshpy-triangle-ex5.pdf")
示例#29
0
def DoTriMesh(points, vertices, edge_length=-1, holes=[], tri_refine=None):
    info = triangle.MeshInfo()
    info.set_points(points)
    if len(holes) > 0:
        info.set_holes(holes)
    info.set_facets(vertices)

    if tri_refine != None:
        mesh = triangle.build(info, refinement_func=tri_refine)
    elif edge_length <= 0:
        mesh = triangle.build(info)
    else:
        mesh = triangle.build(info, max_volume=0.5 * edge_length**2)

    mesh_points = np.array(mesh.points)
    mesh_elements = np.array(mesh.elements)

    #plt.triplot(mesh_points[:, 0], mesh_points[:, 1], mesh_elements,)
    #plt.show()
    return mesh_points, mesh_elements
示例#30
0
def main():
    import meshpy.triangle as triangle

    points = [(1, 1), (-1, 1), (-1, -1), (1, -1)]

    def round_trip_connect(start, end):
        result = []
        for i in range(start, end):
            result.append((i, i + 1))
        result.append((end, start))
        return result

    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_facets(round_trip_connect(0, len(points) - 1))

    mesh = triangle.build(info, max_volume=1e-3, min_angle=25)

    print("A")
    triangle.write_gnuplot_mesh("triangles.dat", mesh)