Example #1
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)
Example #2
0
    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)
Example #3
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)
Example #4
0
    def meshpy(self):
        # Call meshpy and create the delaunay triangulation.

        def centroid(vs):
            return np.mean(vs, axis = 0)

        def distance_to_boundary(pt):
            d, l = self.kdtree.query([pt[0] / self.xy_scaling, pt[1]], k = 1)
            return d

        def refine_func(vertices, area):
            center = centroid(vertices)
            d_bndry = distance_to_boundary(center)
            return bool(area > min(self.refine_area, d_bndry * self.near_edge_factor))

        info = triangle.MeshInfo()

        # Enter triangulation coordinates (so that delaunay angles are
        # reasonable) by multiplying by xy_scaling
        internal_points = map(lambda x: (x[0] * self.xy_scaling, x[1]),
                                   copy(self.meshpy_vs))
        info.set_points(internal_points)
        info.set_facets(self.meshpy_es, facet_markers = self.meshpy_markers)

        mesh = triangle.build(info,
                              refinement_func = refine_func,
                              generate_faces = True)
        self.meshpy = mesh

        self.meshpy_pts = np.array(mesh.points)
        # Exit triangulation coordinates
        self.meshpy_pts[:, 0] /= self.xy_scaling
        self.meshpy_tris = np.array(mesh.elements, dtype = np.int)
Example #5
0
def buildMesh(geometry, algorithm="EasyMesh", triangleAngle=0, triangleArea=0):
    if algorithm=="EasyMesh":
        tempFileFD, tempFileName = tempfile.mkstemp(suffix=".d", text=True)
        tempFileBaseName, tempFileExtension = os.path.splitext(tempFileName)
        writeEasyMeshInput(geometry, tempFileName)
        runEasyMesh(tempFileName)
        mesh = readEasyMeshOutput(tempFileBaseName)
        return mesh
    elif algorithm=="Triangle":
        import meshpy.triangle as tri
        info = tri.MeshInfo()
        info.set_points(geometry.nodesList())
        info.set_facets(geometry.asNodeIndices())
        info.regions.resize(len(geometry.regions))
        for i,region in enumerate(geometry.regions):
            info.regions[i] = list(region)
        if len(info.regions)>0:
            volConstraints=True
            triangleArea=0
        else:
            volConstraints=False
        triMesh = tri.build(info,min_angle=triangleAngle, max_volume=triangleArea, attributes=True,
                            volume_constraints=volConstraints)
        mesh = triangleMesh()
        mesh.nodes.coordinates = np.array(triMesh.points)
        mesh.nodes.numbers = range(len(mesh.nodes.coordinates))
        mesh.elements.nodes = np.array(triMesh.elements)
        mesh.elements.numbers = range(len(mesh.elements.nodes))
        mesh.elements.markers = [1]*len(mesh.elements.nodes)
        return mesh
    elif algorithm=="Netgen":
        tempFileFD, tempFileName = tempfile.mkstemp(suffix=".in2d", text=True)
        writeNetgenInput(geometry, tempFileName)
        mesh = runNetgen(tempFileName)
        return mesh
Example #6
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()
Example #7
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
Example #8
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 """
Example #9
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

    marker2tag = {
            1: "minus_x",
            2: "minus_y",
            3: "plus_x",
            4: "plus_y",
            4: "plus_y",
            5: "corner_plus_y",
            6: "corner_plus_x",
            }

    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)
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)
Example #11
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()
Example #12
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"))
Example #13
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)
Example #14
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_
Example #15
0
 def generate_mesh(self, mesh_size=5):
     """Setup Mesh Object and Properties
     Go through generation Builder -> MeshInfo -> Mesh"""
     # TODO Look into section-properties on github?
     # TODO Are the values from meshpy.triangle accurate?
     mesh_info = MeshInfo()
     self.builder.set(mesh_info)
     self.mesh = build(mesh_info, max_volume=mesh_size)
     # Calculate Element Centroids
     # C = [(x1+x2+x3)/3 , (y1+y2+y3)/3]
     for i, e in enumerate(self.mesh.elements):
         p1 = self.mesh.points[e[0]]
         p2 = self.mesh.points[e[1]]
         p3 = self.mesh.points[e[2]]
         self.mesh_centroids[i] = ((p1[0] + p2[0] + p3[0]) / 3,
                                   (p1[1] + p2[1] + p3[1]) / 3)
     # Calculate Element Areas
     # A = abs(x1*y2 + x2*y3 + x3*y1 - y1*x2 - y2*x3 - y3*x1)/2
     for i, e in enumerate(self.mesh.elements):
         p1 = self.mesh.points[e[0]]
         p2 = self.mesh.points[e[1]]
         p3 = self.mesh.points[e[2]]
         self.mesh_areas[i] = abs(p1[0] * p2[1] + p2[0] * p3[1] +
                                  p3[0] * p1[1] - p1[1] * p2[0] -
                                  p2[1] * p3[0] - p3[1] * p1[0]) / 2
     # Assign material ids to elements
     # A bit verbose just to show calculations - might change later
     # this only accounts for circle assignments
     for primitive in self.ele_mat_primitive:
         r = primitive[0]
         prim_c = primitive[1]
         mat_id = primitive[2]
         for n, c in self.mesh_centroids.items():
             if hypot(c[0] - prim_c[0], c[1] - prim_c[1]) < r:
                 self.ele_mat[n] = mat_id
Example #16
0
def circle(r,h0,n):
    # define the vertices on the circle
    points = []
    for i in range(n):
        x = r*np.cos(i*2*np.pi/n)
        y = r*np.sin(i*2*np.pi/n)
        points.append([x,y])
    # define the four edges between the four vertices of the square
    facets = round_trip_connect(0, len(points)-1)
    # initialize the mesh and set the vertices and the edges of the domain
    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_facets(facets)
    # define a function that returns a boolean that is true if the triangle with
    # vertices vtx and area a has maximal edge length larger than the desired
    # maximal mesh width h0.
    def needs_refinement(vtx, a):
        return bool(max_edge_length(vtx) > h0)
    # create the mesh giving the mesh information info and the refinement
    # function needs_refinement as input
    mesh = triangle.build(info, refinement_func=needs_refinement)
    #mesh = triangle.build(info)
    # read vertices and triangles of the mesh and convert the arrays to numpy
    # arrays
    p = np.array(mesh.points)
    t = np.array(mesh.elements)
    # return the vertices and triangles of the mesh
    return (p, t)
Example #17
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
def par_mesh(h, n):
    mesh_info = MeshInfo()

    # Set the vertices of the domain [0, 1]^2
    mesh_info.set_points([
        (0,0), (1,0), (1,1), (0,1)])

    # Set the facets of the domain [0, 1]^2
    mesh_info.set_facets([
        [0,1],
        [1,2],
        [2,3],
        [3,0]
        ])

    # Generate the tet mesh
    mesh = build(mesh_info, max_volume=(h)**2)

    node = np.array(mesh.points, dtype=np.float)
    cell = np.array(mesh.elements, dtype=np.int)

    tmesh = TriangleMesh(node, cell)

    # Partition the mesh cells into n parts 
    if n > 1:
        edgecuts, parts = metis.part_mesh(tmesh, nparts=n, entity='node')
    else:
        NN = tmesh.number_of_nodes()
        parts = np.zeros(NN, dtype=np.int)
    tmesh.nodedata['partition'] = parts
    return tmesh
Example #19
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"))
Example #20
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)
Example #21
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>
        """)
Example #22
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)
Example #23
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)
Example #24
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
Example #25
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
Example #26
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
Example #27
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)
Example #28
0
def triangle(box, h):
    from meshpy.triangle import MeshInfo, build
    mesh_info = MeshInfo()
    mesh_info.set_points([(box[0], box[2]), (box[1], box[2]), (box[1], box[3]),
                          (box[0], box[3])])
    mesh_info.set_facets([[0, 1], [1, 2], [2, 3], [3, 0]])
    mesh = build(mesh_info, max_volume=h**2)
    point = np.array(mesh.points, dtype=np.float)
    cell = np.array(mesh.elements, dtype=np.int)
    return TriangleMesh(point, cell)
Example #29
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)
Example #30
0
def circle(r,h0,n):
  n = max(n,int(np.ceil(2.0*np.pi*r/h0)))
  points = [(r*np.cos(2*np.pi*i/float(n)), r*np.sin(2*np.pi*i/float(n))) for i in range(0, n)]
  facets = round_trip_connect(0, len(points)-1)
  info = triangle.MeshInfo()
  info.set_points(points)
  info.set_facets(facets)
  def needs_refinement(vertices, area):
    return bool(max_edge_length(vertices) > h0)
  mesh = triangle.build(info, refinement_func=needs_refinement)
  return (np.array(mesh.points), np.array(mesh.elements))
Example #31
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)
Example #32
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
Example #33
0
 def init_mesh(self, meshtype='tri', h=0.1):
     """ generate the initial mesh
     """
     from meshpy.triangle import build
     domain = self.domain()
     mesh = build(domain, max_volume=h**2)
     node = np.array(mesh.points, dtype=np.float)
     cell = np.array(mesh.elements, dtype=np.int)
     if meshtype is 'tri':
         mesh = TriangleMesh(node, cell)
         return 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
Example #35
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 main():
    import meshpy.triangle as triangle

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

    left_points = [(0.2, 0.25), (0.4, 0.25), (0.4, 0.5), (0.2, 0.5)]
    right_points = [(0.8, 0.25), (0.6, 0.25), (0.6, 0.5), (0.8, 0.5)]

    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 + left_points + right_points)
    outer_facets = round_trip_connect(0, len(points)-1)
    left_facets = round_trip_connect(len(points), len(points) + len(left_points) - 1)
    right_facets = round_trip_connect(len(points) + len(left_points), len(points) + len(left_points) + len(right_points) - 1)
    info.set_facets(outer_facets + left_facets + right_facets)
    info.set_holes([(0.3, 0.3)] + [(0.7, 0.3)])

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

    f = open('output.xml', 'w')

    f.write("""
        <?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):
      f.write('<vertex index="%d" x="%g" y="%g"/>' % (
              i, pt[0], pt[1]))

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

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

    f.write("""
            </cells>
          </mesh>
        </dolfin>
        """)
Example #37
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;  
Example #38
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
Example #39
0
def make_mesh(max_volume):
    def round_trip_connect(seq):
        result = []
        for i in range(len(seq)):
            result.append((i, (i+1)%len(seq)))
        return result

    shapes = read_shape()

    #from matplotlib.pyplot import plot,show
    #plot(shapes[0][:,0], shapes[0][:,1])
    #show()

    from meshpy.geometry import GeometryBuilder, Marker
    builder = GeometryBuilder()

    for shape in shapes:
        from meshpy.geometry import make_box
        points = shape
        facets = round_trip_connect(range(len(points)))
        builder.add_geometry(points=points, facets=facets,
                facet_markers=Marker.FIRST_USER_MARKER)

    points, facets, facet_markers = make_box((-200, -600), (400, -300))
    builder.add_geometry(points=points, facets=facets,
            facet_markers=facet_markers)

    def transform(pt):
        x, y = pt
        return -0.01*x, -0.01*y

    builder.apply_transform(transform)

    from meshpy.triangle import MeshInfo, build
    mi = MeshInfo()
    builder.set(mi)
    holes = []
    for shape, sign, frac in zip(shapes, [1, 1, -1, 1, 1, 1], [0.5, 0, 0, 0, 0, 0]):
        avg = np.average(shape, axis=0)
        start_idx = int(frac*shape.shape[0])
        start = shape[start_idx]
        holes.append(transform(start + sign*0.01*(avg-start)))

    mi.set_holes(holes)

    mesh = build(mi,
            allow_boundary_steiner=True,
            generate_faces=True,
            max_volume=max_volume)

    return mesh
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)
Example #41
0
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
Example #42
0
def triangle_polygon_domain(points, facets, h, meshtype='tri'):
    from meshpy.triangle import MeshInfo, build
    mesh_info = MeshInfo()
    mesh_info.set_points(points)
    mesh_info.set_facets(facets)
    mesh = build(mesh_info, max_volume=h**2)
    node = np.array(mesh.points, dtype=np.float)
    cell = np.array(mesh.elements, dtype=np.int)
    if meshtype is 'tri':
        return TriangleMesh(node, cell)
    elif meshtype is 'polygon':
        mesh = TriangleMeshWithInfinityNode(TriangleMesh(node, cell))
        pnode, pcell, pcellLocation = mesh.to_polygonmesh()
        return PolygonMesh(pnode, pcell, pcellLocation)
Example #43
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)
Example #44
0
def main():
    import meshpy.triangle as triangle
    import math

    segments = 10

    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 = 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)

    import numpy as np
    #np.set_printoptions(threshold=100000)
    print repr(np.array(mesh.points))
    print repr(np.array(mesh.elements))

    #import pickle
    #pickled = pickle.dumps(mesh)
    #mesh_2 = pickle.loads(pickled)

    triangle.write_gnuplot_mesh("triangles.dat", mesh)
Example #45
0
File: mesh.py Project: jpitre/poro
 def build(self):
     if self.h:
         V0 = (self.h**2)/2.0
     else:
         hauto = min(self.geom.width/10.0, self.geom.height/10.0)
         V0 = (hauto**2)/2.0
     info = triangle.MeshInfo()
     info.set_points(self.geom.points)
     info.set_facets(self.geom.facets)
     mesh = triangle.build(info, max_volume=V0)
     self.nodes = np.array(mesh.points)
     self.elmCon = np.array(mesh.elements).astype("int32")
     self.boundary = np.array(mesh.facets).astype("int32")
     self.nNodes = self.nodes.shape[0]
     self.nElm = self.elmCon.shape[0]
     self.nBoundary = self.boundary.shape[0]
     self.compute_quadpoints()
     print self.nodes.shape, self.elmCon.shape, self.boundary.shape
Example #46
0
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]))
Example #47
0
def main():
    def round_trip_connect(start, end):
      result = []
      for i in range(start, end):
        result.append((i, i+1))
      result.append((end, start))
      return result

    corners, mesh1, mesh2 = generate_meshes(2, 1, 0.3)
    points = get_vertices(corners, mesh1, mesh2)
    print "points", np.array(points)

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

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

    if False:
        print "vertices:"
        for i, p in enumerate(mesh.points):
            print i, p
        print "point numbers in triangles:"
        for i, t in enumerate(mesh.elements):
            print i, t

    finemesh = Mesh()
    ME = MeshEditor()
    ME.open(finemesh,2,2)
    ME.init_vertices(len(mesh.points))
    ME.init_cells(len(mesh.elements))
    for i,v in enumerate(mesh.points):
        ME.add_vertex(i,v[0],v[1])
    for i,c in enumerate(mesh.elements):
        ME.add_cell(i,c[0],c[1],c[2])
    ME.close()

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

    plot(mesh1)
    plot(mesh2)
    plot(finemesh)
    interactive()
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')
Example #49
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)
Example #50
0
def get_mesh_example():
	area = rect((0.,0.),(1.,1.))
	init = rect((0.1,0.1),(0.2,0.2))
	goal1 = rect((0.8,0.8),(0.9,0.9))
	goal2 = rect((0.2,0.8),(0.3,0.9))

	env = area + goal1 + goal2 + init

	info = MeshInfo()
	info.set_points(env)
	info.set_facets(loop(0,4) + loop(4,8) + loop(8,12) + loop(12,16), facet_markers = [0]*4 + [1]*4 + [2]*4 + [3]*4) # Create 8 facets and apply markers 1-8 on them
	info.regions.resize(4)
	s = 0.05
	info.regions[0] = [0.15, 0.15, 0, s] # Replace 0.1 by a smaller value to produce a finer mesh
	info.regions[1] = [0.25, 0.85, 1, s] # Fourth item specifies maximum area of triangles as a region attribute
	info.regions[2] = [0.85, 0.85, 2, s] # Replace 0.1 by a smaller value to produce a finer mesh
	info.regions[3] = [0.5, 0.5, 3, s] # Fourth item specifies maximum area of triangles as a region attribute

	mesh = build(info, volume_constraints=True, attributes=True,
	generate_faces=True, min_angle=20, mesh_order=1)
	return mesh
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))

    markers = [2,2,2,2,2,2]
    markers.extend(list(np.ones(30, dtype='int')))
    markers = [int(i) for i in markers]

    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_facets(facets, facet_markers=markers)
    #
    info.regions.resize(1)
    # points [x,y] in region, + region number, + regional area constraints
    info.regions[0] = ([0,0] + [1,0.05])

    mesh = triangle.build(info, volume_constraints=True, max_volume=0.1)

    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')
    #
    fig = plt.gcf()
    fig.set_size_inches(4.2, 4.2)
    plt.savefig('sec5-meshpy-triangle-ex4.pdf')
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)
Example #53
0
def triangulate_polygon(polygon, **kwargs):
    '''
    Given a shapely polygon, create a triangulation using meshpy.triangle

    Arguments
    ---------
    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 indicies representing triangles
    '''
    import meshpy.triangle as triangle

    def round_trip(start, length):
        '''
        Given a start index and length, create a series of (n, 2) edges which
        create a closed traversal. 

        Example:
        start, length = 0, 3
        returns:  [(0,1), (1,2), (2,0)]
        '''
        tiled = np.tile(np.arange(start, start+length).reshape((-1,1)), 2)
        tiled = tiled.reshape(-1)[1:-1].reshape((-1,2))
        tiled = np.vstack((tiled, [tiled[-1][-1], tiled[0][0]]))
        return tiled

    def add_boundary(boundary, start):
        # coords is an (n, 2) ordered list of points on the polygon boundary
        # the first and last points are the same, and there are no
        # guarentees on points not being duplicated (which will 
        # later cause meshpy/triangle to shit a brick)
        coords  = np.array(boundary.coords)
        # find indices points which occur only once, and sort them
        # to maintain order
        unique  = np.sort(unique_rows(coords)[0])
        cleaned = coords[unique]

        vertices.append(cleaned)
        facets.append(round_trip(start, len(cleaned)))

        # holes require points inside the region of the hole, which we find
        # by creating a polygon from the cleaned boundary region, and then
        # using a representative point. You could do things like take the mean of 
        # the points, but this is more robust (to things like concavity), if slower. 
        test = Polygon(cleaned)
        holes.append(np.array(test.representative_point().coords)[0])

        return len(cleaned)

    #sequence of (n,2) points in space
    vertices = deque()
    #sequence of (n,2) indices of vertices
    facets   = deque()
    #list of (2) vertices in interior of hole regions
    holes    = deque()

    start = add_boundary(polygon.exterior, 0)
    for interior in polygon.interiors:
        try: start += add_boundary(interior, start)
        except: 
            log.warn('invalid interior, continuing')
            continue

    # create clean (n,2) float array of vertices
    # and (m, 2) int array of facets
    # by stacking the sequence of (p,2) arrays
    vertices = np.vstack(vertices)
    facets   = np.vstack(facets)
    
    # holes in meshpy lingo are a (h, 2) list of (x,y) points
    # which are inside the region of the hole
    # we added a hole for the exterior, which we slice away here
    holes    = np.array(holes)[1:]

    # call meshpy.triangle on our cleaned representation of the Shapely polygon
    info = triangle.MeshInfo()
    info.set_points(vertices)
    info.set_facets(facets)
    info.set_holes(holes)

    # uses kwargs
    mesh = triangle.build(info, **kwargs)
  
    mesh_vertices = np.array(mesh.points)
    mesh_faces    = np.array(mesh.elements)

    return mesh_vertices, mesh_faces
Example #54
0
w_min = min([wj for wi in w for wj in wi])
w_max = max([wj for wi in w for wj in wi])

plt.subplot(2, 1, 1)
plot = plt.contourf(x, y, w)
plt.colorbar(plot, orientation='vertical')

edges = np.array(range(len(points)))
edges = np.array([edges, edges + 1]).T
edges[-1, -1] = 0

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

mesh = triangle.build(info, max_volume=0.01)
mesh_points = list(mesh.points)
triangles = list(mesh.elements)

femCase = stVenant.TorsionFemCase(mesh_points, triangles)
femCase.run()


print("number of elements: ", len(triangles))
print("torsion-moment", femCase.get_torsion_moment())
print("polar-moment", femCase.get_polar_moment())

x, y = np.array(mesh_points).T
triang = mtri.Triangulation(x, y, triangles)

plt.subplot(2, 1, 2)
Example #55
0
    previous_step = step

"""
Triangulation:
        - set the points we want to triangulate
        - mark the holes we want to ignore by their interior points
        - triangulation: no interior steiner points, we want triangles to fill
          the whole space between two boundaries. Allowing for quality meshing
          would also mess with the triangulation we want.
"""
info = triangle.MeshInfo()									                   #Create triangulation object.
info.set_points(mesh_points)									               #Set points to be triangulated.
if(len(hole_points) > 0):									     
	info.set_holes(hole_points)                                                #Set holes (contours) to be ignored.
info.set_facets(mesh_facets)       						                       #Set facets.
triangulation = triangle.build(info,verbose=False,allow_boundary_steiner=False,#Build Triangulation.
       allow_volume_steiner=False,quality_meshing=False)

if verbose:
    step = time.clock()                                                        #progress output
    print pa + "Done in %1.2f sec."%(step-previous_step)
    print "\n" + pa + "Current step: Setup of triangles and neighborhood relations."
    previous_step = step

"""
Triangle classification:
        - build triangle-objects from the triangulation
        - set the type of each triangle (junction, normal, end or isolated)
          depending on how many neighbors it has
        - set the radius of each triangle by looking up its "midpoint"
          in the distance map
        - get rid of isolated triangles
Example #56
0
# Utility function to create lists of the form [(1,2), (2,3), (3,4),
# (4,1)], given two numbers 1 and 4
from itertools import islice, cycle
from six.moves import range
from six.moves import zip

loop = lambda a, b: list(zip(list(range(a, b)), islice(cycle(list(range(a, b))), 1, None)))

info = MeshInfo()
info.set_points([(0, 0), (1, 0), (1, 1), (0, 1), (2, 0), (3, 0), (3, 1), (2, 1)])
info.set_facets(loop(0, 4) + loop(4, 8), list(range(1, 9)))  # Create 8 facets and apply markers 1-8 on them
info.regions.resize(2)
info.regions[0] = [0.5, 0.5, 1, 0.1]  # Fourth item specifies maximum area of triangles as a region attribute
info.regions[1] = [2.5, 0.5, 2, 0.1]  # Replace 0.1 by a smaller value to produce a finer mesh

mesh = build(info, volume_constraints=True, attributes=True, generate_faces=True, min_angle=33, mesh_order=2)

pts = vstack(mesh.points)  # (npoints, 2)-array of points
elements = vstack(mesh.elements)  # (ntriangles, 6)-array specifying element connectivity

# Matplotlib's Triangulation module uses only linear elements, so use only first 3 columns when plotting
triplot(pts[:, 0], pts[:, 1], elements[:, :3])

plot(pts[:, 0], pts[:, 1], "ko")  # Manually plot all points including the ones at the midpoints of triangle faces

# Plot a filled contour plot of the function (x - 1.5)^2 + y^2 over
# the mesh. Note tricontourf interpolation uses only linear elements
tricontourf(pts[:, 0], pts[:, 1], elements[:, :3], (pts[:, 0] - 1.5) ** 2 + pts[:, 1] ** 2, 100)

axis([-0.1, 3.1, -0.8, 1.8])
show()
Example #57
0
def triangulate_polygon(polygon,
                        triangle_args='pq30',
                        engine='auto',
                        **kwargs):
    """
    Given a shapely polygon create a triangulation using one
    of the python interfaces to triangle.c:
    > pip install meshpy
    > pip install triangle

    Parameters
    ---------
    polygon : Shapely.geometry.Polygon
        Polygon object to be triangulated
    triangle_args : str
        Passed to triangle.triangulate
    engine : str
        'meshpy', 'triangle', or 'auto'
    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
    --------------
    vertices : (n, 2) float
       Points in space
    faces :    (n, 3) int
       Index of vertices that make up triangles
    """

    # turn the polygon in to vertices, segments, and hole points
    arg = _polygon_to_kwargs(polygon)

    try:
        if str(engine).strip() in ['auto', 'triangle']:
            from triangle import triangulate
            result = triangulate(arg, triangle_args)
            return result['vertices'], result['triangles']
    except ImportError:
        # no `triangle` so move on to `meshpy`
        pass
    except BaseException as E:
        # if we see an exception log it and move on
        log.error('failed to triangulate using triangle!',
                  exc_info=True)
        # if we are running unit tests exit here and fail
        if tol.strict:
            raise E

    # do the import here, as sometimes this import can segfault
    # which is not catchable with a try/except block
    from meshpy import triangle
    # call meshpy.triangle on our cleaned representation
    info = triangle.MeshInfo()
    info.set_points(arg['vertices'])
    info.set_facets(arg['segments'])
    # not all polygons have holes
    if 'holes' in arg:
        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