Esempio n. 1
0
    def _retriangulate(self):
        """Triangulate the shape
        """
        if len(self.vertices) < 2:
            self._tri_edges = np.array([])
            self._tri_faces = np.array([])
            self._tri_vertices = self.vertices
            return

        if len(self.contour) > 1:
            n, _ = self.contour.shape
            contour_edges = np.vstack([np.arange(n), (np.arange(n) + 1) % n]).transpose()
            triangulation_vertices = np.vstack([self.vertices, self.contour])
            triangulation_segments = np.vstack([self.edges, contour_edges + len(self.edges)])
            triangulate_parameters = dict(vertices=triangulation_vertices, 
                segments=triangulation_segments, holes=self.get_interior_point(self.contour))

            self._tri = tr.triangulate(triangulate_parameters, "p")
        else:
            triangulate_parameters = dict(vertices=self.vertices, segments=self.edges)
            self._tri = tr.triangulate(triangulate_parameters, "p")

        if "segments" in self._tri.keys():
            self._tri_edges = self._tri["segments"]
        else:
            self._tri_edges = self.edges

        self._tri_faces = self._tri["triangles"]
        self._tri_vertices = self._tri["vertices"]
Esempio n. 2
0
def testSquare():

    ptlist = {
        "vertices": np.array(
            ((0.0, 0.0), (0.5, 0.0), (1.0, 0.0), (0.0, 0.5), (0.5, 0.5), (1.0, 0.5), (0.0, 1.0), (0.5, 1.0), (1.0, 1.0))
        )
    }
    t = triangle.triangulate(ptlist)
    t1 = triangle.triangulate(ptlist, "qa0.001")

    triangle.plot.compare(plt, t, t1)
    #    plt.show()

    L, M = FE.assembleMatrices(t)
    #    print L
    #    print '\n\n'
    #    print M

    np.savetxt("textL", L)
    np.savetxt("textM", M)

    eig = FE.eigenvalues(L, M)
    elist = eig[0]
    efunc = eig[1]
    print elist[0]
    print elist[1]
    print elist[2]

    #    vertices = np.asarray(t['vertices'])
    #    faces = np.asarray(t['triangles'])
    #    x = vertices[:,0]
    #    y = vertices[:,1]

    #    z = efunc[1]

    #    plt.figure()
    #    plt.tricontourf(x,y,faces,z,cmap='afmhot')
    #    plt.show()
    print "****************************"

    L, M = FE.assembleMatrices(t1)
    eig = FE.eigenvalues(L, M)
    elist = eig[0]
    efunc = eig[1]
    for j in range(10):
        print elist[j]

    vertices = np.asarray(t1["vertices"])
    faces = np.asarray(t1["triangles"])
    x = vertices[:, 0]
    y = vertices[:, 1]
    z = efunc[:, 5]

    plt.figure()
    plt.tricontourf(x, y, z, 100, cmap="afmhot")
    plt.show()

    print "***************************\n\n\n\n\n"
Esempio n. 3
0
def obtainFullTria(x, y):
    try:
        y_temp, x_temp = np.meshgrid(y, x)
        grid4 = np.array(zip(x_temp.ravel(), y_temp.ravel()))
        #        grid4 = np.array([(xx,yy) for xx in x for yy in y])
        myPloy_with_grid = dict({'vertices': grid4})
        #        raise

        # 画出PLSG
        plt.figure()
        ax1 = plt.subplot(221, aspect='equal')
        triplt.plot(ax1, **myPloy_with_grid)
        #        plt.show()

        # 进行网格剖分
        myMesh_tria = triangle.triangulate(myPloy_with_grid)
        ax2 = plt.subplot(222, aspect='equal')
        triplt.plot(ax2, **myMesh_tria)
        #        plt.show()

        d = list(itertools.permutations([0, 1, 2], r=2))
        e = [myMesh_tria['triangles'][:, d[ii]] for ii in xrange(len(d))]
        edges = np.vstack(e)
        diff = edges[:, 0] - edges[:, 1]
        edges_2 = edges[diff > 0, :]

        frame = pd.DataFrame(edges_2)
        #        print frame
        #        print  frame[frame.duplicated()]
        dup = list(frame.duplicated() == False)
        dup = [ii for ii, _ in enumerate(dup)]
        edges_3 = edges_2[dup, :]
        #        print edges_3
        #        print dup

        myPloy_with_seg = myPloy_with_grid
        myPloy_with_seg['segments'] = edges_3
        ax3 = plt.subplot(223, aspect='equal')
        triplt.plot(ax3, **myPloy_with_seg)
        for ii in xrange(myPloy_with_seg['vertices'].shape[0]):
            ax1.text(myPloy_with_seg['vertices'][ii, 0],
                     myPloy_with_seg['vertices'][ii, 1], ii)


#        plt.show()
#
# 形成最终完整的mesh进行保存
        myMesh_tria_2 = triangle.triangulate(myPloy_with_seg, 'p')
        ax4 = plt.subplot(224, aspect='equal')
        triplt.plot(ax4, **myMesh_tria_2)
        plt.show()

        return myMesh_tria_2
    except Exception as e:
        print e
        print grid4.shape
        raise
Esempio n. 4
0
def testFE():
    ptlist = {"vertices": np.array(((0, 0), (1, 0), (1, 1), (0, 1)))}
    triang = triangle.triangulate(ptlist)

    print triang
    print "\n\n"
    print triang["vertices"]
    print triang["triangles"]

    triangle.plot.compare(plt, ptlist, triang)
    plt.show()

    print "\n\nNow testing the FE assembly ..."

    L, M = FE.assembleMatrices(triang)

    elist = FE.eigenvalues(L, M)[0]
    elist.sort()

    print "eigenvalues:"

    for j in elist:
        print j

    triangle.plot.compare(plt, ptlist, triang)
    plt.show()

    triang = triangle.triangulate(triang, "rqa0.1")

    L, M = FE.assembleMatrices(triang)

    elist = FE.eigenvalues(L, M)[0]
    elist.sort()

    print "\n\neigenvalues:"

    for j in elist:
        print j

    triangle.plot.compare(plt, ptlist, triang)
    plt.show()

    triang = triangle.triangulate(triang, "rqa0.01")

    L, M = FE.assembleMatrices(triang)

    elist = FE.eigenvalues(L, M)[0]
    elist.sort()

    print "\n\neigenvalues:"

    for j in elist:
        print j

    triangle.plot.compare(plt, ptlist, triang)
    plt.show()
Esempio n. 5
0
def create_mesh(
    points: List[List[float]],
    facets: List[List[float]],
    holes: List[List[float]],
    control_points: List[List[float]],
    mesh_sizes: Union[List[float], float],
    coarse: bool,
):
    """Creates a quadratic triangular mesh using the triangle 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 bool coarse: If set to True, will create a coarse mesh (no area or quality
        constraints)

    :return: Dictionary containing mesh data
    :rtype: dict()
    """

    if not isinstance(mesh_sizes, list):
        mesh_sizes = [mesh_sizes]

    tri = {}  # create tri dictionary
    tri["vertices"] = points  # set point
    tri["segments"] = facets  # set facets

    if holes:
        tri["holes"] = holes  # set holes

    # prepare regions
    regions = []

    for (i, cp) in enumerate(control_points):
        regions.append([cp[0], cp[1], i, mesh_sizes[i]])

    tri["regions"] = regions  # set regions

    # generate mesh
    if coarse:
        mesh = triangle.triangulate(tri, "pAo2")
    else:
        mesh = triangle.triangulate(tri, "pq30Aao2")

    return mesh
def init(points, params=None):
    if params:
        triangulation = tr.triangulate(dict(vertices=np.array(points)), params)
    else:
        triangulation = tr.triangulate(dict(vertices=np.array(points)))
    triangulation[SRC_POINT_MARKERS] = [
        i < len(points) for i in range(len(triangulation[VERTICES]))
    ]
    triangulation[VERTICES] = [*triangulation[VERTICES]]
    triangulation[VERTEX_MARKERS] = [*triangulation[VERTEX_MARKERS]]
    return triangulation
Esempio n. 7
0
def main():
    mopen = Dynearthsol(modelname)
    rho = mopen.read_field(nframe, 'density')
    conn = mopen.read_field(nframe, 'connectivity')
    coord = mopen.read_field(nframe, 'coordinate')
    bcflag = mopen.read_field(nframe, 'bcflag').astype(np.int16)
    node32 = coord[(bcflag & 32).astype(bool)]

    ###### create new vertice #######
    ## extend two walls
    xbtm = coord[bcflag == 17]
    xbtm2 = [[xbtm[0, 0] - 10000, xbtm[0, 1]]]
    xtop = coord[bcflag == 33]
    xtop2 = [[xtop[0, 0] - 10000, xtop[0, 1]]]
    x0 = np.vstack([xbtm, xbtm2, xtop, xtop2])
    tridict = dict(vertices=x0)
    B = tr.triangulate(tridict, 'qa1000000')
    n0 = coord.shape[0]
    coord = np.vstack([coord, B['vertices']])
    conn = np.vstack([conn, B['triangles'] + n0])
    rho = np.hstack([rho, np.ones(shape=B['triangles'].shape[0]) * 1750])
    bcflag = np.hstack([bcflag, np.zeros(shape=B['vertices'].shape[0])
                        ]).astype(np.int16)

    xbtm = coord[bcflag == 66]
    xbtm2 = [[xbtm[0, 0] + 10000, xbtm[0, 1]]]
    xtop = coord[bcflag == 34]
    xtop2 = [[xtop[0, 0] + 10000, xtop[0, 1]]]
    x0 = np.vstack([xbtm, xbtm2, xtop, xtop2])
    tridict = dict(vertices=x0)
    B = tr.triangulate(tridict, 'qa1000000')
    n0 = coord.shape[0]
    coord = np.vstack([coord, B['vertices']])
    conn = np.vstack([conn, B['triangles'] + n0])
    rho = np.hstack([rho, np.ones(shape=B['triangles'].shape[0]) * 1750])

    ################################

    measureX = np.arange(left, right, 500)
    measureY = np.ones(shape=measureX.shape) * height

    result = bouguer(measureX, measureY, coord, conn, rho) * 1e5

    ##### figure #####
    fig, ax = plt.subplots(figsize=(10, 2.5))
    ax.set_title(modelname)
    ax.plot(measureX, result)
    ax.set_ylabel('Bouguer gravity anomaly (mgal)(blue)')
    ax2 = ax.twinx()
    ax2.plot(node32[:, 0], node32[:, 1], 'r')
    ax2.set_ylabel('topography (m)(red)')
    # ax2.set_aspect('equal', adjustable="datalim")
    plt.show()
def calculate():
    print('Tapez Q pour quitter')
    print(
        'Je peut calculer l\'aire \n\n 1. rectangle \n\n 2. triangle \n\n 3. cercle'
    )
    choice = input('\nchoisi\n')
    os.system('clear')
    ready_to_quit(choice)
    if choice == '1':
        squared()
    if choice == '2':
        triangulate()
    if choice == '3':
        circulate()
Esempio n. 9
0
    def triMesh(self):
        '''Method to generate a triangles mesh in a polygon by using
        `Constrained Delaunay triangulation\
         <https://en.wikipedia.org/wiki/Constrained_Delaunay_triangulation>`_.

        Return:
            verts ((n, 3, 2) `numpy.ndarray`): Vertices of each triangle that\
                compose the triangular mesh. n means the number of triangles;\
                (3, 2) means the index vertices and the coordinates (x, y)\
                respectively.

        Examples:
            >>> from numpy import array
            >>> from circpacker.basegeom import Polygon
            >>> from circpacker.packer import CircPacking as cp
            >>> coordinates = array([[1, 1], [2, 5], [4.5, 6], [6, 4], [8, 3],
                                     [7, 1], [4.5, 1], [4, 0]])
            >>> polygon = Polygon(coordinates)
            >>> boundCoords = polygon.boundCoords
            >>> circPack = cp(boundCoords, depth=8)
            >>> verts = circPack.triMesh()

            >>> from numpy import array
            >>> from circpacker.basegeom import Polygon
            >>> from circpacker.packer import CircPacking as cp
            >>> coordinates = array([[2, 2], [2, 6], [8, 6], [8, 2]])
            >>> polygon = Polygon(coordinates)
            >>> boundCoords= polygon.boundCoords
            >>> circPack = cp(boundCoords, depth=3)
            >>> verts =  circPack.triMesh()
        '''

        index = np.arange(len(self.coordinates[:-1]))
        indexSegmts = np.column_stack((index, np.hstack((index[1:], [0]))))
        # constrained Delaunay triangulation
        if self.maxArea is None and self.minAngle is None:
            self.CDT = triangulate(tri={'vertices': self.coordinates[:-1],
                                        'segments': indexSegmts},
                                   opts='pq25S15')
        else:
            self.CDT = triangulate(tri={'vertices': self.coordinates[:-1],
                                        'segments': indexSegmts},
                                   opts='pq'+str(self.minAngle)+'a' +
                                   str(self.maxArea))
        vertsIndex = self.CDT['vertices']
        trianglesIndex = self.CDT['triangles']
        verts = vertsIndex[trianglesIndex]
        return verts
Esempio n. 10
0
def main():
    A = dict(vertices=np.array((
        (0, 0),
        (1, 0),
        (1, 1),
        (0.5, 0.5),
        (0, 1),
    )),
             segments=[
                 (0, 1),
                 (1, 2),
                 (2, 3),
                 (3, 4),
                 (4, 0),
             ])
    B = tr.triangulate(A, opts="pa0.03")

    print(B)

    print(len(B['vertices']))
    print(len(B['vertex_markers']))
    print(len(B['triangles']))

    tr.compare(plt, A, B)
    plt.savefig('tri.png')
Esempio n. 11
0
def test_triangulate():
    v = [[0, 0], [0, 1], [1, 1], [1, 0]]
    t = triangulate({"vertices": v}, "a0.2")
    assert np.allclose(
        t["vertices"],
        [
            [0.0, 0.0],
            [0.0, 1.0],
            [1.0, 1.0],
            [1.0, 0.0],
            [0.5, 0.5],
            [0.0, 0.5],
            [0.5, 0.0],
            [1.0, 0.5],
            [0.5, 1.0],
        ],
    )
    assert np.allclose(
        t["vertex_markers"],
        [[1], [1], [1], [1], [0], [1], [1], [1], [1]],
    )
    assert np.allclose(
        t["triangles"],
        [
            [7, 2, 4],
            [5, 0, 4],
            [4, 8, 1],
            [4, 1, 5],
            [4, 0, 6],
            [6, 3, 4],
            [4, 3, 7],
            [4, 2, 8],
        ],
    )
Esempio n. 12
0
def generate_embossing(height):
 
    embs = calc_embossing()
    keys = ['vertex1','vertex2','vertex3'] 
    
    for emb in embs:
        segs = simple_segs(emb)
        tri = triangle.triangulate({'vertices': np.array(emb),'segments' :segs }, 'pf' )
        
        for trian in tri['triangles']:
            point = {}
            ref = 0
            for vertex in trian:
                point[keys[ref]] = [emb[vertex][X], emb[vertex][Y], height]    
                ref = ref + 1
            object_data['points'].append(point)

        for trian in tri['triangles']:
            point = {}
            ref = 0
            for vertex in trian:
                point[keys[ref]] = [emb[vertex][X], emb[vertex][Y], height+embossing_height]    
                ref = ref + 1
            object_data['points'].append(point)
            
        for vertex in emb:
            vertex.append(height)
        make_3d(emb,height,True)  
def triangulate_regular_polygon(sides, radius, pos, size):
        x, y = pos
        angle = 2 * pi / sides
        all_verts = []
        all_verts_a = all_verts.append
        r = radius
        for s in range(sides):
            new_pos = x + r * sin(s * angle), y + r * cos(s * angle)
            all_verts_a(new_pos)
        A = {'vertices':array(all_verts)}
        command = 'cqa' + size + 'YY'
        B = triangle.triangulate(A, command)
        tri_indices = B['triangles']
        new_indices = []
        new_vertices = {}
        tri_verts = B['vertices']
        new_ex = new_indices.extend
        ind_count = 0
        for tri in tri_indices:
            new_ex((tri[0], tri[1], tri[2]))
            ind_count += 3
        vert_count = 0
        for i, tvert in enumerate(tri_verts):
            new_vertices[i] = {
                'pos': [tvert[0], tvert[1]], 
                'v_color': [255, 255, 255, 255]
                }
            vert_count += 1
        return {'indices': new_indices, 'vertices': new_vertices, 
            'vert_count': vert_count, 'ind_count': ind_count}
Esempio n. 14
0
    def _triangulate_raster_from_file(self):
        """
        Main function used to create the irregular TIN surface for Badlands based on
        a regular DEM file.
        """

        # Compute DEM edges
        self._raster_edges()

        # Compute TIN grid boundaries
        self._TIN_ghosts_bounds()

        # Create TIN
        tinPts = numpy.vstack(( self.bounds, self.edges))
        self.tinMesh = triangle.triangulate( dict(vertices=tinPts),'Dqa'+str(self.areaDel))
        ptsTIN = self.tinMesh['vertices']

        # Check extent
        checkXmin = ptsTIN[self.boundsPt:,0].min()
        checkXmax = ptsTIN[self.boundsPt:,0].max()
        checkYmin = ptsTIN[self.boundsPt:,1].min()
        checkYmax = ptsTIN[self.boundsPt:,1].max()

        if checkXmin < self.rectX.min() or checkXmax > self.rectX.max():
            raise ValueError('Error in defining the X boundary nodes, you will need to adjust the resolution value')
        if checkYmin < self.rectY.min() or checkYmax > self.rectY.max():
            raise ValueError('Error in defining the Y boundary nodes, you will need to adjust the resolution value')

        # Add masks
        self.bmask = numpy.zeros(len(ptsTIN[:,0]))
        self.bmask[:self.boundsPt] = 1

        return
def triangulate(P):
    n = len(P)
    S = np.repeat(np.arange(n + 1), 2)[1:-1]
    S[-2:] = n - 1, 0
    S = S.reshape((-1, 2))
    T = triangle.triangulate({'vertices': P[:, :2], 'segments': S}, "p")
    return T["triangles"].ravel()
Esempio n. 16
0
def delaunay_triangulation(points):
    """Construct a Delaunay triangulation of set of vertices.

    Parameters
    ----------
    points : list
        XY(Z) coordinates of the points to triangulate.

    Returns
    -------
    tuple
        * The vertices of the triangulation.
        * The faces of the triangulation.

    Examples
    --------
    >>>

    References
    ----------
    https://www.cs.cmu.edu/~quake/triangle.delaunay.html

    """
    data = {'vertices': [point[0:2] for point in points]}
    result = triangulate(data, opts='c')
    vertices = [[x, y, 0] for x, y in result['vertices']]
    faces = result['triangles']
    return vertices, faces
Esempio n. 17
0
	def curve_to_mesh(self,curve):
		M=len(curve)
		segs = np.zeros((M,2)).astype(np.int32)
		segs[:,0] = np.linspace(0,M-1,M).astype(np.int32)
		segs[:,1] = segs[:,0]+1
		segs[-1,-1] = 0
		
		face={"vertices": np.array(curve).astype(np.float32),"segments": np.array(segs).astype(np.int32)}
		
		tri = triangle.triangulate(face,'pq10')
		
		verts_2d     = tri["vertices"]
		trinagles_2d = tri["triangles"]
		
		verts     = np.zeros((len(verts_2d),4),dtype=np.float32)
		trinagles = np.zeros((len(trinagles_2d),3),dtype=np.float32)
		
		
		verts[:,0]     = verts_2d[:,0]
		trinagles[:,0] = trinagles_2d[:,0]
		verts[:,1]     = verts_2d[:,1]
		trinagles[:,1] = trinagles_2d[:,1]
		trinagles[:,2] = trinagles_2d[:,2]
		
		return GeoObject(verts=verts,tris=trinagles)
Esempio n. 18
0
def obtainFullTria():
    try:
        a = 1
        b = 1
        
        # 预定义的格子店
        x = np.array([0,-a,a,a,-a])
        y = np.array([0,b,b,-b,-b])
        
        grid4 = np.array([(xx,yy) for xx,yy in zip(x,y)])
        edges = np.array([[0,1],[1,2],[2,0],\
                          [0,3],[3,4],[4,0]])
        myPloy_with_grid = dict({'vertices':grid4,'segments':edges})
        
        # 画出PLSG
        plt.figure()
        ax1 = plt.subplot(221, aspect='equal')
        triplt.plot(ax1,**myPloy_with_grid)
        
        # 进行网格剖分
        myMesh_tria = triangle.triangulate(myPloy_with_grid,'pq30a0.01')
        ax2 = plt.subplot(222, aspect='equal')
        triplt.plot(ax2,**myMesh_tria)
        plt.show()
                
        return myMesh_tria
    except Exception as e:
        print e
Esempio n. 19
0
 def areaRefiner(this,model,norm):
     X1 = 'X1'
     X2 = 'Y1'
     X3 = 'X2'
     X4 = 'Y2'
     X5 = 'X2'
     X6 = 'Y3'
     X7 = 'X4'
     X8 = 'Y4'
     X9 = 'X5'
     X10 = 'Y5'
     X11 = 'X6'
     X12 = 'Y6'
     X13 = 'CX'
     X14 = 'CY'
     X15 = 'XE1'
     X16 = 'YE1'
     X17 = 'XE2'
     X18 = 'YE2'
     X19 = 'XE3'
     X20 = 'YE3'
     X21 = 'CB'
     dt = pd.DataFrame.from_records(this.generarDatos())
     dt.columns = [X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,X13,X14,X15,X16,X17,X18,X19,X20,X21]
     xs = norm(dt)
     ys = model(xs.values)
     this.triangular['triangle_max_area'] = ys
     tnueva = tr.triangulate(this.triangular,'ra')
     tr.compare(plt,this.triangular,tnueva)
     this.triangular = tnueva
     this.diccionarios = this.triangular['triangles'].tolist()
     this.tipos = np.zeros([len(this.diccionarios)]).astype(str)
     this.tipos[:] = 'T1V'
     this.gdls = this.triangular['vertices'].tolist()
     this.cbe = this.generarCB(this.bordesCBE,this.valorCBE)
Esempio n. 20
0
 def __init__(this, vertices, params,cbe = [],valorCBE=10, plot=False):
     this.bordesCBE = cbe
     this.valorCBE= valorCBE 
     this.params = params
     super().__init__(vertices)
     this.seg = []
     for i in range(len(this.vertices)-1):
         this.seg.append([i,i+1])
     this.seg.append([i+1,0])
     this.original = dict(vertices=np.array(this.vertices),segments=np.array(this.seg))
     this.triangular = tr.triangulate(this.original,this.params)
     if plot:
         tr.compare(plt, this.original, this.triangular)
     count = 0
     for i in this.triangular['segments']:
         if count > 1:
             if np.sum(np.isin(np.array(this.cbe)[:,0], i[0]))<1:
                 this.cbe.append([i[0],0])
             if np.sum(np.isin(np.array(this.cbe)[:,0], i[1]))<1:
                 this.cbe.append([i[1],0])
         else:
             this.cbe.append([i[0],0])
         if np.sum(np.isin(np.array(this.cbe)[:,0], i[1]))<1:
                 this.cbe.append([i[1],0])
         count+=1
     this.diccionarios = this.triangular['triangles'].tolist()
     this.tipos = np.zeros([len(this.diccionarios)]).astype(str)
     this.tipos[:] = 'T1V'
     this.gdls = this.triangular['vertices'].tolist()
Esempio n. 21
0
def create_collision_object_polygon(polygon,
                                    params=None,
                                    collision_object_func=None):
    if len(polygon.vertices) == 3:
        return pycrcc.Triangle(polygon.vertices[0][0], polygon.vertices[0][1],
                               polygon.vertices[1][0], polygon.vertices[1][1],
                               polygon.vertices[2][0], polygon.vertices[2][1])
    else:
        if all(np.equal(polygon.vertices[0], polygon.vertices[-1])):
            vertices = polygon.vertices[:-1]
        else:
            vertices = polygon.vertices
        number_of_vertices = len(vertices)
        segments = list(
            zip(range(0, number_of_vertices - 1), range(1,
                                                        number_of_vertices)))
        segments.append((0, number_of_vertices - 1))
        triangles = triangle.triangulate(
            {
                'vertices': vertices,
                'segments': segments
            }, opts='pqS2.4')
        mesh = list()
        for t in triangles['triangles']:
            v0 = triangles['vertices'][t[0]]
            v1 = triangles['vertices'][t[1]]
            v2 = triangles['vertices'][t[2]]
            mesh.append(
                pycrcc.Triangle(v0[0], v0[1], v1[0], v1[1], v2[0], v2[1]))
        return pycrcc.Polygon(polygon.vertices.tolist(), list(), mesh)
Esempio n. 22
0
def triangulate_face(data):
    """Determines the triangulation of the face of a shape.

    Parameters
    ----------
    data : np.ndarray
        Nx2 array of vertices of shape to be triangulated

    Returns
    -------
    vertices : np.ndarray
        Mx2 array vertices of the triangles.
    triangles : np.ndarray
        Px3 array of the indices of the vertices that will form the
        triangles of the triangulation
    """

    if triangulate is not None:
        len_data = len(data)

        edges = np.empty((len_data, 2), dtype=np.uint32)
        edges[:, 0] = np.arange(len_data)
        edges[:, 1] = np.arange(1, len_data + 1)
        # connect last with first vertex
        edges[-1, 1] = 0

        res = triangulate(dict(vertices=data, segments=edges), "p")
        vertices, triangles = res['vertices'], res['triangles']
    else:
        vertices, triangles = PolygonData(vertices=data).triangulate()

    triangles = triangles.astype(np.uint32)

    return vertices, triangles
Esempio n. 23
0
    def _triangulate_raster_from_file(self):
        """
        Main function used to create the irregular TIN surface for Badlands based on
        a regular DEM file.
        """

        # Compute DEM edges
        self._raster_edges()

        # Compute TIN grid boundaries
        self._TIN_ghosts_bounds()

        # Create TIN
        tinPts = numpy.vstack(( self.bounds, self.edges))
        self.tinMesh = triangle.triangulate( dict(vertices=tinPts),'Dqa'+str(self.areaDel))
        ptsTIN = self.tinMesh['vertices']

        # Check extent
        checkXmin = ptsTIN[self.boundsPt:,0].min()
        checkXmax = ptsTIN[self.boundsPt:,0].max()
        checkYmin = ptsTIN[self.boundsPt:,1].min()
        checkYmax = ptsTIN[self.boundsPt:,1].max()

        if checkXmin < self.rectX.min() or checkXmax > self.rectX.max():
            raise ValueError('Error in defining the X boundary nodes, you will need to adjust the resolution value')
        if checkYmin < self.rectY.min() or checkYmax > self.rectY.max():
            raise ValueError('Error in defining the Y boundary nodes, you will need to adjust the resolution value')

        # Add masks
        self.bmask = numpy.zeros(len(ptsTIN[:,0]))
        self.bmask[:self.boundsPt] = 1

        return
Esempio n. 24
0
def tess(polys, holes):
    indices = {}
    vertices = []
    segments = []

    for i, poly in enumerate(polys):
        for v in poly:
            assert isinstance(v, tuple)
            if v not in indices:
                pos = len(vertices)
                indices[v] = pos
                vertices.append(v)

        for v0, v1 in doubles(poly):
            # TODO: check for duplicate segment
            index0 = indices[v0]
            index1 = indices[v1]

            segments.append((index0, index1))

    A = dict(
        vertices=vertices,
        segments=segments,
    )
    if holes:
        A['holes'] = holes

    B = tr.triangulate(A, opts="pq")

    return B, A
Esempio n. 25
0
 def __init__(this, vertices, params, plot=False,**kargs):
     this.params = params
     this.cbe = []
     this.cbn = []
     this.seg = []
     for i in range(len(vertices)-1):
         this.seg.append([i,i+1])
     this.seg.append([i+1,0])
     this.original = dict(vertices=np.array(vertices),segments=np.array(this.seg))
     this.triangular = tr.triangulate(this.original,this.params)
     diccionarios = this.triangular['triangles'].tolist()
     tipos = np.zeros([len(diccionarios)]).astype(str)
     if 'o2' in params:
         tipos[:] = 'T2V'
     else:
         tipos[:] = 'T1V'
     gdls = this.triangular['vertices'].tolist()
     super().__init__(vertices,diccionarios,gdls,tipos,segmentos=this.seg)
     if tipos[0] == 'T2V':
         for dicc in this.diccionarios:
                 a1 = dicc[5]
                 a2 = dicc[3]
                 a3 = dicc[4]
                 dicc[3] = a1
                 dicc[4] = a2
                 dicc[5] = a3
     if plot:
         this.dibujarse(**kargs)
Esempio n. 26
0
def triangleMesh(x,y,refinement):
	

	domain = {'vertices':np.array([[0.,0.],[1.,0.],[x,y]]),'triangles':np.array([[0,1,2]])}
	mesh = triangle.triangulate(domain, 'qa'+str(refinement))

	return mesh
Esempio n. 27
0
def _sludge_pattern(resolution=128):
    """Random sludge pattern at bottom of tank."""
    x_pos = np.linspace(1, 25, num=resolution)
    y_pos = .0625 * x_pos - 6.0625
    y_pos[1:-1] += np.random.normal(loc=.25, scale=.1, size=resolution - 2)

    vertices = np.zeros((2 * resolution, 3))
    vertices[:, 0] = np.concatenate((x_pos, x_pos[::-1]))
    vertices[:, 1] = np.concatenate((y_pos, y_pos[::-1]))
    vertices[resolution:, 2] = resolution * [-.5]

    vert_id = np.array(range(2 * resolution))
    triags = tr.triangulate(
        dict(vertices=vertices[:, [0, 2]],
             segments=np.stack((vert_id, (vert_id + 1) % len(vert_id))).T),
        'pq')
    faces = triags['triangles']

    sludge = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))
    for i, face in enumerate(faces):
        for j in range(3):
            sludge.vectors[i][j] = vertices[face[j], :]

    sludge.save('../foam/sim/constant/triSurface/sludge.stl')
    return True
Esempio n. 28
0
def triangulate(P):
    n = len(P)
    S = np.repeat(np.arange(n+1),2)[1:-1]
    S[-2:] = n-1,0
    S = S.reshape((-1, 2))
    T = triangle.triangulate({'vertices': P[:,:2], 'segments': S}, "p")
    return  T["triangles"].ravel()
Esempio n. 29
0
    def triangulate(self):
        #create the data structure required by the triangle library
        n = len(self.points)
        points = self.points
        edges = [[i, (i + 1) % n] for i in range(n)]
        hole_pts = []
        for hole in self.holes:
            offset = len(points)
            hn = len(hole.points)
            edges += [[i + offset, ((i + 1) % n) + offset] for i in range(hn)]
            points = np.concatenate((points, hole.points), axis=0)
            hole_pts.append(hole.get_interior_point())

        tri_dict = {'vertices': points, 'segments': edges}
        if len(self.holes) > 0:
            tri_dict['holes'] = hole_pts

        #triangulate with the triangle library
        assert len(
            points
        ) > 2, 'Trying to triangulate fewer than 2 points: ' + str(self)
        t = triangle.triangulate(tri_dict)
        t_verts = t['vertices'].tolist()
        tris = t['triangles'].tolist()
        partition = [Poly(np.array([t_verts[vi] for vi in tr])) for tr in tris]

        #remove triangles corresponding to holes/areas outside of the polygon
        filtered = []
        for poly in partition:
            pt = poly.get_interior_point()
            if self.contains_point(pt):
                filtered.append(poly)
        return filtered
Esempio n. 30
0
    def refineMesh(self, args):
        """
		See the API <http://dzhelil.info/triangle> for information on optional arguments.
		Common arguments (use any combination):
			p - triangulates a Planar Straight Line Graph.
			a - imposes a maximum area for each triangle.
			q - quality mesh generation no angles smaller than specified degrees (default: 20).
			c - encloses convex hull with line segments
		"""
        t = clock()
        args = str(args)  #ensure string
        tri = triangle.triangulate(self.meshDict, args)

        self.x = tri['vertices'][:, 0]
        self.y = tri['vertices'][:, 1]
        self.simplicies = tri['triangles']
        self.centroids = (tri['vertices'][tri['triangles'][:, 0]] +
                          tri['vertices'][tri['triangles'][:, 1]] +
                          tri['vertices'][tri['triangles'][:, 2]]) / 3
        self.bmask = self.boundary_mask(tri)

        if self.verbose:
            print " - Mesh refinement complete. %i vertices in %f secs with arguments '%s'" % (
                len(tri['vertices']), clock() - t, args)

        return
Esempio n. 31
0
 def draw_triangulated_regular_polygon(self, sides, radius, pos, octaves, persistance, scale, size):
     x, y = pos
     angle = 2 * pi / sides
     all_verts = []
     all_verts_a = all_verts.append
     r = radius
     for s in range(sides):
         new_pos = x + r * sin(s * angle), y + r * cos(s * angle)
         all_verts_a(new_pos)
     A = {"vertices": array(all_verts)}
     command = "cqa" + size + "YY"
     B = triangle.triangulate(A, command)
     tri_indices = B["triangles"]
     new_triangles = []
     new_vertices = []
     tri_verts = B["vertices"]
     nv_ap = new_vertices.append
     new_ap = new_triangles.append
     tri_count = 0
     for tri in tri_indices:
         new_ap((tri[0], tri[1], tri[2]))
         tri_count += 1
     vert_count = 0
     for tvert in tri_verts:
         nv_ap([tvert[0], tvert[1], octaves, persistance, scale])
         vert_count += 1
     return {
         "triangles": new_triangles,
         "vertices": new_vertices,
         "vert_count": vert_count,
         "tri_count": tri_count,
         "vert_data_count": 5,
     }
Esempio n. 32
0
def triangulate_polygon(polygon, triangle_args=None, **kwargs):
    """
    Given a shapely polygon create a triangulation using a
    python interface to `triangle.c`:
    > `pip install triangle`

    Parameters
    ---------
    polygon : Shapely.geometry.Polygon
        Polygon object to be triangulated
    triangle_args : str or None
        Passed to triangle.triangulate i.e: 'p', 'pq30'

    Returns
    --------------
    vertices : (n, 2) float
       Points in space
    faces : (n, 3) int
       Index of vertices that make up triangles
    """
    # do the import here for soft requirement
    from triangle import triangulate
    # set default triangulation arguments if not specified
    if triangle_args is None:
        triangle_args = 'p'
    # turn the polygon in to vertices, segments, and hole points
    arg = _polygon_to_kwargs(polygon)
    # run the triangulation
    result = triangulate(arg, triangle_args)

    return result['vertices'], result['triangles']
Esempio n. 33
0
 def draw_triangulated_rectangle(self, width, height, pos, octaves, persistance, scale, size):
     x, y = pos
     all_verts = [(x, y), (x, y + height), (x + width, y + height), (x + width, y)]
     A = {"vertices": array(all_verts)}
     command = "cqa" + size
     B = triangle.triangulate(A, command)
     tri_indices = B["triangles"]
     new_triangles = []
     new_vertices = []
     tri_verts = B["vertices"]
     nv_ap = new_vertices.append
     new_ap = new_triangles.append
     tri_count = 0
     for tri in tri_indices:
         new_ap((tri[0], tri[1], tri[2]))
         tri_count += 1
     vert_count = 0
     for tvert in tri_verts:
         nv_ap([tvert[0], tvert[1], octaves, persistance, scale])
         vert_count += 1
     print vert_count, tri_count
     return {
         "triangles": new_triangles,
         "vertices": new_vertices,
         "vert_count": vert_count,
         "tri_count": tri_count,
         "vert_data_count": 5,
     }
Esempio n. 34
0
def calculate_mesh(a, bbox, target, get_t=False):
    # FIXME target/get_t is ugly
    """triangulate a mesh based on a Planar Straight Line Graph with
    mesh constraints.  Return either the Delaunay triangulation or a
    difference in number of triangles from a target.

    Parameters
    ----------
    a : float
        global maximum triangular area constraint
    bbox : dict
        dictionary with keys vertices and segments representing PSLG
    target : int
        number of triangles to which the triangulation will be compared if
        get_t is False
    get_t : boolean
        whether to return a Delaunay Triangulation rather than a
        comparison to target

    Returns
    -------
    val : scipy.spatial.Delaunay or int
        Delaunay triangulation if get_t is True, otherwise the number of
        vertices in the triangulation subtracted from the target
    """
    t = triangle.triangulate(bbox, 'pqa%0.1f' % a)
    if get_t:
        # scipy.Delaunay has nice find_simplex method,
        # but, no obvious way to iteratively refine meshes, like triangle
        # numbering is different, so, switch here
        return Delaunay(t['vertices'])
    return target - len(t['vertices'])
Esempio n. 35
0
def spherePolygon(mesh, points, radius=1, color=None):
    offset = len(mesh.vertices)

    if points[0][0] == points[-1][0]:
        points.pop()

    sphere_pts = []
    for point in points:
        sphere_pts.append(point)
        v = toSphere(point, radius)
        normal = normalize(v)

        mesh.vertices_texcoords([.5 + point[0] / 360., .5 + point[1] / 180.])
        # mesh.addNormal( normal )

        mesh.addVertex(v)

        if color:
            mesh.addColor(color)

    segments = []
    for i in range(len(points)):
        segments.append([i, (i + 1) % len(points)])

    cndt = triangulate(dict(vertices=sphere_pts, segments=segments), 'p')
    for face in cndt['triangles']:
        mesh.addTriangle(offset + (face[0] % len(sphere_pts)),
                         offset + (face[1] % len(sphere_pts)),
                         offset + (face[2] % len(sphere_pts)))
    offset += len(points)

    return mesh
    def getHolePoint(self, ring):
        segments = []
        vertmarks = []
        segmarks = []

        for i in range(len(ring) - 1):
            segments.append([int(i), int(i + 1)])
            vertmarks.append([0])
            segmarks.append([0])
        segments.append([int(i + 1), int(0)])
        vertmarks.append([0])
        segmarks.append([0])

        pol = {
            'vertices': ring,
            'segments': segments,
            'vertex_markers': vertmarks,
            'segment_markers': segmarks
        }
        tris = triangle.triangulate(pol, opts="p")
        tri = tris['triangles'][0]
        v = tris['vertices']

        # De gemiddelde waarde van de coordinaten van een driehoek ligt altijd binnen de driehoek
        a = v[tri[0]]
        b = v[tri[1]]
        c = v[tri[2]]

        return [(a[0] + b[0] + c[0]) / 3, (a[1] + b[1] + c[1]) / 3]
Esempio n. 37
0
def _triangulate_cpp(vertices_2d, segments):
    import triangle
    T = triangle.triangulate({'vertices': vertices_2d,
                              'segments': segments}, "p")
    vertices_2d = T["vertices"]
    triangles = T["triangles"]
    return vertices_2d, triangles
Esempio n. 38
0
def STLWrite(faces, filename, thickness=0):
  import triangle

  shape = None
  shells = []
  triangles = []
  for f in faces:
    r = f[0]
    A = f[1]

    facets = []
    B = triangle.triangulate(A, opts='p')
    if not 'triangles' in B:
      print "No triangles in " + B
      continue

    if thickness:
      for t in [np.transpose(np.array([list(B['vertices'][x]) + [0,1] for x in (face[0], face[1], face[2])])) for face in B['triangles']]:
        facets.extend([np.dot(r, x) for x in inflate(t, thickness=thickness)])
      for t in [np.transpose(np.array([list(A['vertices'][x]) + [0,1] for x in (edge[0], edge[1])])) for edge in A['segments']]:
        facets.extend([np.dot(r, x) for x in inflate(t, thickness=thickness, edges=True)])
    else:
      for t in [np.transpose(np.array([list(B['vertices'][x]) + [0,1] for x in (face[0], face[1], face[2])])) for face in B['triangles']]:
        facets.append(np.dot(r, t))

    triangles.extend(facets)

    if thickness:
      FREECADPATH = '/usr/lib64/freecad/lib'
      import sys
      sys.path.append(FREECADPATH)
      import FreeCAD
      import Part
      meshes = []
      for f in (np.transpose(t[0:3,:]) for t in facets):
        try:
          meshes.append(Part.Face(Part.Wire([Part.makeLine(tuple(f[x]), tuple(f[x-1])) for x in range(3)])))
        except RuntimeError:
          print "Skipping face: " + repr(f)
      shell = Part.makeShell(meshes)
      shells.append(shell)
      if shape is None:
        shape = shell
      else:
        shape = shape.fuse(shell)

  if shape:
    with open("freecad" + filename, 'wb') as fp:
      shape.exportStl("freecad" + filename)

  from stlwriter import Binary_STL_Writer
  faces = triangles

  with open(filename, 'wb') as fp:
    writer = Binary_STL_Writer(fp)
    writer.add_faces(faces)
    writer.close()
Esempio n. 39
0
def triangulate(geometry, max_area=None):
    """Use the triangle library to triangulate a polygon

    Args:
        polygon (shapely.*): shapely geometry representing the area to
            triangulate
        max_area (float): If provided, the triangulation will be refined
            until all triangles have area less than this maximum.

    Returns:
        list: list of triangular polygons
    """
    if not geometry.is_valid:
        raise ValueError("Tried to triangulate invalid geometry", geometry)

    if hasattr(geometry, "geoms"): # polygon is a MultiPolygon
        polygons = list(geometry.geoms)
    else:
        polygons = [geometry]

    vertices = []
    segments = []
    for polygon in polygons:
        offset = len(vertices)
        vertices.extend(polygon.exterior.coords[0:-1])
        segments.extend(circular_pairs(
            range(offset, offset+len(polygon.exterior.coords)-1)))
        for ring in polygon.interiors:
            offset = len(vertices)
            vertices.extend(ring.coords[0:-1])
            segments.extend(circular_pairs(
                range(offset, offset+len(ring.coords)-1)))

    shape = {'vertices': numpy.array(vertices),
             'segments': numpy.array(segments, dtype=numpy.int32)}

    # Find the holes in the geometry
    buffer_by = numpy.sqrt(geometry.envelope.area)
    complement = geometry.envelope.buffer(
        buffer_by, cap_style=2, join_style=2).difference(geometry)
    if complement.geom_type == "MultiPolygon":
        shape['holes'] = numpy.array([interior.representative_point().coords[0]
                                      for interior in complement.geoms])
    elif complement.geom_type == "Polygon":
        shape['holes'] = numpy.array(complement.representative_point().coords[0])

    if max_area is None:
        opts = "p"
    else:
        opts = "pa{}".format(max_area)

    triangulation = triangle.triangulate(shape, opts)
    return [shapely.geometry.Polygon([triangulation['vertices'][i]
                                      for i in triplet])
            for triplet in triangulation['triangles']]
Esempio n. 40
0
def cycles2triangles(polygon):
    triangleSet = []

    vertices = []
    stringVertices = set()
    for cycle in polygon:
        for vertex in cycle:
            stringVertex = str(vertex)
            if (stringVertex not in stringVertices):
                vertices.append(vertex)
                stringVertices.add(stringVertex)

    edges = []
    externalCycle = polygon[0]
    edges += face2edge([[vertices.index(vertex) for vertex in externalCycle]])

    holeEdges = []
    holeInnerPoints = []
    internalCycles = polygon[1:]
    for hole in internalCycles:
        holeEdges += face2edge([[vertices.index(vertex) for vertex in hole]])
        holeInnerPoints.append(internalTo(hole,holeEdges))
        edges += holeEdges

    if holeInnerPoints != []:
        triangulation = triangulate({"vertices":vertices,"segments":edges,"holes":holeInnerPoints},'p')
    else:
        triangulation = triangulate({"vertices": vertices, "segments": edges}, 'p')

    vertices = triangulation['vertices'].tolist()
    triangles = triangulation['triangles'].tolist()

    trias = [[vertices[index] for index in triangle] for triangle in triangles]
    trias = [[[vertex[0], vertex[1], 0.0] for vertex in tri] for tri in trias]

    triangleSet += [trias]
    
    return triangleSet
Esempio n. 41
0
def RMS_calc(lons,lats,rotation):
    #Define an equal area projection around the plate
    m = pyproj.Proj("+proj=aea +lat_1="+`min(lats)`+" +lat_2="+`max(lats)`+" +lat_0="+`(min(lats)+max(lats))/2`+" +lon_0="+`(min(lons)+max(lons))/2`)
    #Create irregular triangular mesh for the plate polygon
    data={}
    data['vertices']=np.column_stack((lons,lats))
    segs=[[0,len(lons)-1]]
    for i in np.arange(0,len(lons)-1): segs.append([i,i+1])
    data['segments']=np.array(segs)
    t = triangulate(data, 'pa50q30') #starting off with too small an area can cause crashes
    #can refine further using r switch - note I do so right now but the difference in the overall result is small
    t2= triangulate(t, 'ra10q30')
    f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
    tplot.plot(ax1, **t)
    plt.title('1st Triangulation - min area 50, min angle 30')
    tplot.plot(ax2, **t2)
    plt.title('Refined mesh - min area 10, min angle 30')
    plt.tight_layout()
    units=t2['vertices'][t2['triangles']]
    vel_lat,vel_lon,vel_mag,vel_az= [],[],[],[]
    totvelsquared=0.
    totarea=0.
    for unit in units:
        tlon,tlat=m(unit[:,0],unit[:,1])
        thing=Polygon(np.column_stack((tlon,tlat)))
        area=thing.area/1e6
        x,y=thing.centroid.xy
        x,y=m(x,y,inverse=True)
        platevel=get_plate_velocity(([y[0],x[0]]),rotation)
        totvelsquared=totvelsquared+(area*platevel[0]**2)
        totarea=totarea+area
        vel_lon.append(x)
        vel_lat.append(y)
        vel_mag.append(platevel[0])
        vel_az.append(platevel[1])
    rms=np.sqrt(totvelsquared/totarea)
    velgrid=pd.DataFrame(np.column_stack((vel_lon,vel_lat,vel_mag,vel_az)), columns=['Lons','Lats','Rate','Azimuth'])
    return rms, totarea, velgrid
Esempio n. 42
0
def foo3():
    import triangle
    import triangle.plot as plot

    node_list, crease_list, crease_types = load_creasepattern('test.creasepattern')
    #print node_list
    #print crease_list

    paper = {}
    paper['vertices'] = node_list 
    paper['segments'] = crease_list

    ax1 = mpl.subplot(121, aspect='equal')
    plot.plot(ax1, **paper)
    
    t = triangle.triangulate(paper, 'p')
    print t

    ax2 = mpl.subplot(122, sharex=ax1, sharey=ax1)
    plot.plot(ax2, **t)

    nodes = t['vertices']
    triangles = t['triangles']
    #offset = 0.01
    for i in range(triangles.shape[0]):
        mean_x = np.mean(nodes[triangles[i,:],0])
        mean_y = np.mean(nodes[triangles[i,:],1])
        mpl.text(mean_x, mean_y, '%d' % i)

    edge2triangle = get_edge2triangle(t['triangles'])
    print 'edge2triangle'
    print edge2triangle

    neighbors, neighbor_angles = get_neighbors(node_list, crease_list) 
    i = 4
    angle = 15
    crease_angles = [angle, 180, angle, None, angle, 180, angle, None]
    ans = solve_node(neighbor_angles[i], crease_angles)
    crease_angles = ans[0]
    known_creases = {}
    known_creases = add_node_creases(known_creases, i, neighbors[i], crease_angles)
    known_creases = add_flat_creases(known_creases, triangles)
    print known_creases

    frames, nodes3d = propagate_frames(nodes, triangles, known_creases, triangle_index=0)
    for i, n in enumerate(nodes3d):
        print i, n

    plot_creasepattern(nodes, crease_list, crease_types=crease_types, triangles=triangles)
Esempio n. 43
0
    def Triangulate(self):
        delaunay = triangle.triangulate({'vertices' : self.vertices})
        self.segments_vertices = {}
        self.vertices_segments = {}
        self.delaunay_triangles = {}

        for tri in delaunay['triangles']:
            for ind in range(3):
                a, b, c = tri[ind], tri[(ind + 1) % 3], tri[(ind + 2) % 3]
                self.InsertSegments_Vertices(a, b, c)
                self.InsertVertices_Segments(a, b, c)
        
        for tri in delaunay['triangles']:
            a, b, c = sorted((tri[0], tri[1], tri[2]))
            self.delaunay_triangles[(a, b, c)] = True
def triangulate(vertices):
    n = len(vertices)
    vertices = np.array(vertices)
    zmean = vertices[:,2].mean()
    vertices_2d = vertices[:,:2]
    segments = np.repeat(np.arange(n+1),2)[1:-1]
    segments[-2:] = n-1,0
    T = triangle.triangulate({'vertices': vertices_2d,
                              'segments': segments}, "p")
    vertices_2d = T["vertices"]
    triangles   = T["triangles"]
    vertices = np.empty((len(vertices_2d),3))
    vertices[:,:2] = vertices_2d
    vertices[:,2] = zmean
    return vertices, triangles
Esempio n. 45
0
def foo2():
    # From http://dzhelil.info/triangle/delaunay.html
    # (not my code)
    import triangle
    import triangle.plot as plot

    face = triangle.get_data('face')
    print face

    ax1 = mpl.subplot(121, aspect='equal')
    plot.plot(ax1, **face)

    t = triangle.triangulate(face, 'p')

    ax2 = mpl.subplot(122, sharex=ax1, sharey=ax1)
    triangle.plot.plot(ax2, **t)

    mpl.show()
Esempio n. 46
0
def triangulate(polygon):
    """
    Triangulates 3D polygons
    """
    vect1 = [polygon[1][0] - polygon[0][0],
             polygon[1][1] - polygon[0][1],
             polygon[1][2] - polygon[0][2]]
    vect2 = [polygon[2][0] - polygon[0][0],
             polygon[2][1] - polygon[0][1],
             polygon[2][2] - polygon[0][2]]
    vectProd = [vect1[1] * vect2[2] - vect1[2] * vect2[1],
                vect1[2] * vect2[0] - vect1[0] * vect2[2],
                vect1[0] * vect2[1] - vect1[1] * vect2[0]]
    polygon2D = []
    segments = list(range(len(polygon)))
    segments.append(0)
    # triangulation of the polygon projected on planes (xy) (zx) or (yz)
    if(math.fabs(vectProd[0]) > math.fabs(vectProd[1]) and math.fabs(vectProd[0]) > math.fabs(vectProd[2])):
        # (yz) projection
        for v in range(0,len(polygon)):
            polygon2D.append([polygon[v][1], polygon[v][2]])
    elif(math.fabs(vectProd[1]) > math.fabs(vectProd[2])):
        # (zx) projection
        for v in range(0,len(polygon)):
            polygon2D.append([polygon[v][0], polygon[v][2]])
    else:
        # (xy) projextion
        for v in range(0,len(polygon)):
            polygon2D.append([polygon[v][0], polygon[v][1]])

    triangulation = triangle.triangulate({'vertices': polygon2D, 'segments': segments})
    if 'triangles' not in triangulation:    # if polygon is degenerate
        return []
    trianglesIdx = triangulation['triangles']
    triangles = []

    for t in trianglesIdx:
        # triangulation may break triangle orientation, test it before adding triangles
        if(t[0] > t[1] > t[2] or t[2] > t[0] > t[1] or t[1] > t[2] > t[0]):
            triangles.append([polygon[t[1]], polygon[t[0]],polygon[t[2]]])
        else:
            triangles.append([polygon[t[0]], polygon[t[1]],polygon[t[2]]])

    return triangles
def triangulate(game_objects, scenario_width, scenario_height):
    points = []
    segments = []
    holes = []

    for obj in game_objects:
        if obj.getRole() == GOBJ.MAN:
            continue
        offset = len(points)
        vertices = obj.getPosScr()
        points = points + vertices

        #if obj.getRole() == GOBJ.IMMOVEABLE:

        hole = ((vertices[0][0] + vertices[2][0])/2, (vertices[0][1] + vertices[2][1])/2)
        holes.append(hole)
        edges = obj.getEdges()
        edges = [ [edge[0] + offset, edge[1] + offset] for edge in edges]
        segments = segments + edges

    ## add frames 
    points = points + [[0,0],[0,scenario_height],[scenario_width,scenario_height],[scenario_width,0]]
    points = np.array(points)
    segments = np.array(segments)
    holes = np.array(holes)

    dic = {}
    dic["vertices"] = points
    dic["segments"] = segments
    dic["holes"] = holes


    tri = triangle.triangulate(dic,'pc')

    
    zones = [Polygon(tri["vertices"][t]) for t in tri["triangles"]]
    graph = createGraph(tri["triangles"], tri["vertices"], tri["segments"])

    #graph = create_graph_advanced(tri["triangles"], tri["vertices"], tri["segments"])
    return graph, zones
Esempio n. 48
0
	def refineMesh(self, args):
		"""
		See the API <http://dzhelil.info/triangle> for information on optional arguments.
		Common arguments (use any combination):
			p - triangulates a Planar Straight Line Graph.
			a - imposes a maximum area for each triangle.
			q - quality mesh generation no angles smaller than specified degrees (default: 20).
			c - encloses convex hull with line segments
		"""
		t = clock()
		args = str(args) #ensure string
		tri = triangle.triangulate(self.meshDict, args)

		self.x = tri['vertices'][:,0]
		self.y = tri['vertices'][:,1]
		self.simplicies = tri['triangles']
		self.centroids = (tri['vertices'][tri['triangles'][:,0]] + tri['vertices'][tri['triangles'][:,1]] + tri['vertices'][tri['triangles'][:,2]])/3
		self.bmask = self.boundary_mask(tri)

		if self.verbose:
			print " - Mesh refinement complete. %i vertices in %f secs with arguments '%s'" % (len(tri['vertices']), clock()-t, args)

		return
    def triangulatePolygon(self, poly):
        poly = self.stripLastCoordinate(poly)

        segments = []
        vertmarks = []
        segmarks = []
        holes = []
        c = 0
        for p in range(len(poly)):
            for i in range(len(poly[p]) - 1):
                segments.append([int(c+i), int(c+i+1)])
            segments.append([int(c+i+1),int(c)])
            c = len(segments)
            
            # Vertex en segment markers
            # Nummer bij vertexes en segments moet overeen komen
            for i in range(len(poly[p])):
                vertmarks.append([p])
                segmarks.append([p])
            
            if p > 0:
                # Gat
                holes.append(self.getHolePoint(poly[p]))

        allverts = list(itertools.chain.from_iterable(poly))       
                
        if len(holes) > 0:
            pol = {'vertices': allverts, 'segments': segments, 'vertex_markers': vertmarks, 'segment_markers': segmarks, 'holes': holes}
        else:
            pol = {'vertices': allverts, 'segments': segments, 'vertex_markers': vertmarks, 'segment_markers': segmarks}
        result = triangle.triangulate(pol, opts="p")

        result['triangles'] = self.correctTriangles(result['triangles'], result['vertices'])
        result['segments'] = self.correctSegments(result['segments'])
        
        return result
    def getHolePoint(self, ring):
        segments = []
        vertmarks = []
        segmarks = []
        
        for i in range(len(ring) - 1):
            segments.append([int(i), int(i+1)])
            vertmarks.append([0])
            segmarks.append([0])
        segments.append([int(i+1),int(0)])
        vertmarks.append([0])
        segmarks.append([0])

        pol = {'vertices': ring, 'segments': segments, 'vertex_markers': vertmarks, 'segment_markers': segmarks}
        tris = triangle.triangulate(pol, opts="p")
        tri = tris['triangles'][0]
        v = tris['vertices']

        # De gemiddelde waarde van de coordinaten van een driehoek ligt altijd binnen de driehoek
        a = v[tri[0]]
        b = v[tri[1]]
        c = v[tri[2]]
        
        return [(a[0]+b[0]+c[0])/3,(a[1]+b[1]+c[1])/3]
import triangle
import triangle.plot as plot
import matplotlib.pyplot as plt


face = triangle.get_data('face')
ax1 = plt.subplot(121, aspect='equal')
plot.plot(ax1, **face)

t = triangle.triangulate(face, 'pq10')

ax2 = plt.subplot(122, sharex=ax1, sharey=ax1)
plot.plot(ax2, **t)

plt.show()
Esempio n. 52
0
import matplotlib.pyplot as plt
import triangle
import triangle.plot

spiral = triangle.get_data("spiral")

t = triangle.triangulate(spiral, "a.2")
ax1 = plt.subplot(111, aspect="equal")
triangle.plot.plot(ax1, **t)

plt.show()
Esempio n. 53
0
vertices = [(0,0), (12,0), (12,8), (0,8), (1,1), (3,1), (3,3), (1,3), (4,2), (10,2), 
			(10,3), (4,3), (2,4), (7,4), (7,6), (2,6), (8,5), (11,5), (11,7), (8,7), 
			(6,3.5)]

segments = [(0,1), (1,2), (2,3), (3,0), (4,5), (5,6), (6,7), (7,4), (8,9), (9,10), 
			(10,11), (11,8), (12,13), (13,14), (14,15), (15,12), (16,17), (17,18), 
			(18,19), (19,16)]

holes = [(2,2), (7,2.5), (10,6), (4,5)]

room = {}
room['vertices'] = array(vertices)
room['segments'] = array(segments)
room['holes'] = array(holes)

tri = triangulate(room,  'pq20a0.1D')
X = tri['triangles'][:,0]
Y = tri['triangles'][:,1]
Z = tri['triangles'][:,2]
Xvert = [tri['vertices'][x] for x in X]
Yvert = [tri['vertices'][x] for x in Y]
Zvert = [tri['vertices'][x] for x in Z]
dataXY = minkowski_distance(Xvert, Yvert)
dataXZ = minkowski_distance(Xvert, Zvert)
dataYZ = minkowski_distance(Yvert, Zvert)

nvert = len(tri['vertices'])
G = lil_matrix((nvert, nvert))
for k in range(len(X)):
	G[X[k], Y[k]] = G[Y[k], X[k]] = dataXY[k]
	G[X[k], Z[k]] = G[Z[k], X[k]] = dataXZ[k]
Esempio n. 54
0
 def triangulate(self):
     return triangulate(self.triangle_data, 'p')
def triangulate(q, dic):
    tri = triangle.triangulate(dic, 'pc')
    #q.put(tri)
    q.send(tri)
    q.close()
Esempio n. 56
0
def triangulate(points_array):

	input_dict = dict(vertices=np.array(points_array), segments=ccw_segments(points_array))
	tri = triangle.triangulate(input_dict, 'p')

	return {'original':input_dict, 'tri':tri}
Esempio n. 57
0
def _triangulate_cpp(vertices_2d, segments):
    T = triangle.triangulate({'vertices': vertices_2d,
                              'segments': segments}, "p")
    vertices_2d = T["vertices"]
    triangles = T["triangles"]
    return vertices_2d, triangles
Esempio n. 58
0
import triangle
import triangle.plot
from numpy import *
import matplotlib.pyplot as plt

A = dict(vertices=array(((0,0), (1,0), (1, 1), (0, 1))))
B = triangle.triangulate(A, 'qa0.1')
triangle.plot.compare(plt, A, B)
plt.show()