예제 #1
0
 def Show(self):
     tri = self.delaunay
     planar = {'vertices' : self.vertices, 'segments' : self.segments}
     plot(plt.axes(), **planar)
     plot(plt.axes(), **tri)
     plt.show()
     plt.clf()
예제 #2
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
def draw_triangulation(graph, tri, zones):
	plot.plot(plt.axes(),**(tri[0]))
	################### Arrange graph according to the position of triangles #########

	#triangles_by_vertices = tri["vertices"][tri["triangles"]]
	pos = {}
	for index, triangle in enumerate(zones):
		pos[index] = (triangle.centroid.x, triangle.centroid.y)
	#triangle_center(*triangle)

	edge_text_labels = {}
	edge_lists = []

	for edge in graph.edges():
		edge_lists.append(edge)
		label =  graph.get_edge_data(*edge)
		edge_text_labels[edge] = [rel for rel in label['rel']]
################## END ##########################################


	nx.draw(graph,pos,node_size=200, node_color='g', edge_color='y')
	nx.draw_networkx_labels(graph, pos)
	plt.plot()

	plt.savefig('triangulation.png')
예제 #4
0
 def Show(self):
     planar = {'vertices' : np.array(self.vertices), 'segments' : np.array(self.segments.keys())}
     tri = {'vertices' : np.array(self.vertices), 'triangles' : np.array(self.delaunay_triangles.keys())}
     plot(plt.axes(), **planar)
     plot(plt.axes(), **tri)
     plt.show()
     plt.clf()
예제 #5
0
 def Show(self):
     tri = self.delaunay
     planar = {'vertices': self.vertices, 'segments': self.segments}
     plot(plt.axes(), **planar)
     plot(plt.axes(), **tri)
     plt.show()
     plt.clf()
예제 #6
0
 def Show(self):
     planar = {'vertices' : np.array(self.vertices), 'segments' : np.array(self.segments.keys())}
     tri = {'vertices' : np.array(self.vertices), 'triangles' : np.array(self.triangles.keys())}
     plot(plt.axes(), **planar)
     plot(plt.axes(), **tri)
     plt.plot(self.vertices[-1][0], self.vertices[-1][1], 'bo')
     plt.show()
     plt.clf()
예제 #7
0
 def Show(self):
     planar = {
         'vertices': np.array(self.vertices),
         'segments': np.array(self.segments.keys())
     }
     tri = {
         'vertices': np.array(self.vertices),
         'triangles': np.array(self.delaunay_triangles.keys())
     }
     plot(plt.axes(), **planar)
     plot(plt.axes(), **tri)
     plt.show()
     plt.clf()
예제 #8
0
def tri(x, y):
    # plot the plan
    box = triangle.get_data('box')
    #
    # ax1 = plt.subplot(121, aspect='equal')
    # triangle.plot.plot(ax1, **box)

    t = triangle.triangulate(box, 'pc')

    ax2 = plt.subplot(111)  # , sharex=ax1, sharey=ax1)
    plot.plot(ax2, **t)
    plt.plot(x, y, 'yo-')

    plt.show()
예제 #9
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)
예제 #10
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
예제 #11
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()
예제 #12
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
예제 #13
0
import triangle
import triangle.plot as plot
import matplotlib.pyplot as plt

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

t = triangle.triangulate(spiral)

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

plt.show()
예제 #14
0

import triangle
import triangle.plot as plot
import matplotlib.pyplot as plt

box = triangle.get_data('box')

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

t = triangle.triangulate(box, 'pc')

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

plt.show()
예제 #15
0
def show_data(name):
    import triangle.plot as plot
    import matplotlib.pyplot as plt
    d = get_data(name)
    plot.plot(plt.axes(), **d)
    plt.show()
예제 #16
0
def drawTriangles(map_data):
    tri_data = map_data.triangulate()
    plt.figure(figsize=(14, 14))
    ax = plt.subplot(111, aspect='equal')
    tplot.plot(ax, **tri_data)
    plt.show()
예제 #17
0
def show_data(name):
    import triangle.plot as plot
    import matplotlib.pyplot as plt
    d = get_data(name)
    plot.plot(plt.axes(), **d)
    plt.show()
예제 #18
0
    import numpy as np
    import matplotlib.pylab as plt
    grids = np.array(list(itertools.product(x, y)))
    theta = 0. / 180 * np.pi
    rot = np.array([[np.cos(theta), np.sin(theta)],
                    [-np.sin(theta), np.cos(theta)]])

    grids = np.dot(grids, rot)

    r = [[0.1, 0.1, 0], [0.9, 0.75, 0.1], [1.2, 0.6, 0]]
    r = np.array(r)
    #    print a
    plt.figure()
    ax1 = plt.subplot(111, aspect='equal')
    a = dict({'vertices': grids})
    triplt.plot(ax1, **a)
    ax1.plot(r[:, 0], r[:, 1], 'ro')
    b = triangle.triangulate(a)
    triplt.plot(ax1, **b)
    plt.show()

    grid3 = np.hstack([grids, np.zeros([grids.shape[0], 1])])
    trias = b['triangles']

    formPoly = lambda ii: grid3[trias[ii], :]
    poly = map(formPoly, xrange(trias.shape[0]))
    #    print grid3[trias[3]]
    #    print trias[3]
    poly = np.array(poly)

    sig_v = SiguralityInt_vec()
예제 #19
0
import triangle
import triangle.plot as plot
import matplotlib.pyplot as plt

dots = triangle.get_data('dots')
pts = dots['vertices']
segs = triangle.convex_hull(pts)

plot.plot(plt.axes(), vertices=pts, segments=segs)

plt.show()
import triangle
import triangle.plot as plot
import matplotlib.pyplot as plt

box = triangle.get_data('box')

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

t = triangle.triangulate(box, 'pc')

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

plt.show()
예제 #21
0
import triangle
from triangle.plot import plot
import matplotlib.pyplot as plt

A = triangle.get_data("A")
ax = plt.axes()
plot(ax, **A)
plt.show()
예제 #22
0
import triangle
import triangle.plot as plot
import matplotlib.pyplot as plt

A = triangle.get_data('A')
t = triangle.triangulate(A, 'pq0D')
plot.plot(plt.axes(), **t)
plt.show()
예제 #23
0
 def show(self):
     plt.figure(figsize=(8, 8))
     ax = plt.subplot(111, aspect='equal')
     tplot.plot(ax, **self.raw_splitting)
     plt.show()
예제 #24
0
파일: polyatest.py 프로젝트: necoleman/fepy
import matplotlib.tri as tri
from pylab import *

import triangle.plot as plot

dom = {'vertices':np.array([[0.,0.],[1.,0.],[1.,.49],[.9,.49],[.9,.1],[.1,.1],[.1,.9],[.9,.9],[.9,.51],[1.,.51],[1.,1.],[0.,1.]]),'triangles':np.array([[0,1,5],[0,5,6],[1,4,5],[1,4,2],[2,3,4],[0,6,11],[6,10,11],[6,7,10],[7,8,9],[7,9,10]])}#,'segments':np.array([[0,1],[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]])}

print len(dom['vertices'])
print dom['triangles']

mesh = triangle.triangulate(dom,'pqa0.05')

print mesh

ax1 = plt.subplot(111,aspect='equal')
plot.plot(ax1, **mesh)
plt.show()

L,M = FE.assembleMatrices(mesh)
evals,efunc = FE.sparseEigs(L,M)

fig = plt.figure()
vertices = np.asarray(mesh['vertices'])
faces = np.asarray(mesh['triangles'])
x = vertices[:,0]
y = vertices[:,1]
#for j in range(1,5):
#	z = efunc[:,j]
#	plt.tricontourf(x,y,z,0,cmap='afmhot')
#	axes().set_aspect('equal')
#	plt.show()
예제 #25
0
import triangle
from triangle.plot import plot
import matplotlib.pyplot as plt

A = triangle.get_data('A')
ax = plt.axes()
plot(ax, **A)
plt.show()
예제 #26
0

domain2 = {
    "vertices": np.array(
        [[2.0, 0.0], [2.5, -0.5], [3.0, 0.0], [2.5, 0.5], [3.0, 1.0], [3.0, 2.0], [2.5, 1.5], [2.0, 2.0], [2.0, 1.0]]
    ),
    "triangles": np.array([[0, 1, 2], [0, 2, 3], [0, 3, 8], [3, 4, 8], [4, 5, 6], [4, 6, 8], [6, 7, 8]]),
}


mesh1 = triangle.triangulate(domain1, "pqa0.02r")
mesh2 = triangle.triangulate(domain2, "pqa0.02r")

ax1 = plt.subplot(121, aspect="equal")
ax2 = plt.subplot(122, aspect="equal")
plot.plot(ax1, **mesh1)
plot.plot(ax2, **mesh2)
plt.show()

X1 = mesh1["vertices"][:, 0]
Y1 = mesh1["vertices"][:, 1]

X2 = mesh2["vertices"][:, 0]
Y2 = mesh2["vertices"][:, 1]

evals1, evecs1 = FE.findEigs(mesh1, 25)
evals2, evecs2 = FE.findEigs(mesh2, 25)

for j in range(25):
    x1 = evals1[j]
    x2 = evals2[j]
예제 #27
0
def visualize_triangulation(t):
    ax = plt.subplot()
    tr_plt.plot(ax, **t)
    plt.show()
예제 #28
0
import triangle
import triangle.plot as plot
import matplotlib.pyplot as plt

spiral = triangle.get_data('spiral')

ax1 = plt.subplot(221, aspect='equal')
triangle.plot.plot(ax1, vertices=spiral['vertices'])

a = triangle.triangulate(spiral)
ax2 = plt.subplot(222, sharex=ax1, sharey=ax1)
plot.plot(ax2, **a)

b = triangle.triangulate(spiral, 'q')
ax3 = plt.subplot(223, sharex=ax1, sharey=ax1)
plot.plot(ax3, **b)

c = triangle.triangulate(spiral, 'q32.5')
ax4 = plt.subplot(224, sharex=ax1, sharey=ax1)
plot.plot(ax4, **c)

plt.show()
from triangle_relation import printRels
from scenario_reader import loadScenario




#scenario_file = './scenarios/s3.json'
file_name = 's2'
scenario_width, scenario_height, immobile_objs, mobile_objs, manipulatable_obj, target_obj = loadScenario('./scenarios/' + file_name + '.json')
scenario = SG(scenario_width, scenario_height, immobile_objs, mobile_objs, manipulatable_obj, target_obj, showRender=True)
## get objects 
game_objects = scenario.getGameObjects()
tri = []
graph, edges_index, edges_dirs, edges_by_tri, vertices_of_edges, edges_surface_dic, tri_by_surface, surface_rel_dic, tri_neighbor_by_edge, edges_by_object_id, objects_id_by_edge, zones = triangulate_advanced(game_objects, scenario_width, scenario_height, tri)

plot.plot(plt.axes(),**(tri[0]))


################### Arrange graph according to the position of triangles #########

#triangles_by_vertices = tri["vertices"][tri["triangles"]]
pos = {}
for index, triangle in enumerate(zones):

	pos[index] = (triangle.centroid.x, triangle.centroid.y)
	#triangle_center(*triangle)
edge_text_labels = {}
edge_lists = []

for edge in graph.edges():
segments2 = [
    (120 + ii - 1, 120 + ii)
    for ii in range(np.array(außenlage.geometry.interiors[0]).shape[0])
]
segments2[0] = (120 + 95, 120)
segments2 = np.array(segments2)
#a =np.array([1,2])
t2 = triangle.triangulate(
    {
        'vertices': alle,
        'segments': np.vstack((
            segments,
            segments2,
        ))
    }, 'p')

#holes = np.array((1,1))
# In[1]:

segments, segments2

# In[12]:

import triangle.plot as plot
from matplotlib import pyplot as plt

fig = plt.figure(figsize=(25, 15))
ax = plt.subplot(111)
plot.plot(ax, **t2)
plt.show()
예제 #31
0
import triangle
import triangle.plot as plot
import matplotlib.pyplot as plt

box1 = triangle.get_data('bbox.1')
box2 = triangle.triangulate(box1, 'rpa0.2')
box3 = triangle.triangulate(box2, 'rpa0.05')
box4 = triangle.triangulate(box3, 'rpa0.0125')

plt.figure(figsize=(15, 5))

ax1 = plt.subplot(131, aspect='equal')
plot.plot(ax1, **box2)

ax2 = plt.subplot(132, sharex=ax1, sharey=ax1)
triangle.plot.plot(ax2, **box3)

ax2 = plt.subplot(133, sharex=ax1, sharey=ax1)
triangle.plot.plot(ax2, **box4)

plt.show()
예제 #32
0
    def plot(self, plotTriMesh=False):
        '''Method for show a graphic of the circles generated within of the
        polyhon.

        Parameters:
            plotTriMesh (`bool`): Variable to check if it also want to show\
                the graph of the triangles mesh. The default value is ``False``

        Examples:

            .. plot::

                from numpy import array
                from circpacker.basegeom import Polygon
                from circpacker.packer import CircPacking
                coordinates = array([[1, 1], [2, 5], [4.5, 6], [8, 3], [7, 1],
                                     [4, 0]])
                polygon = Polygon(coordinates)
                boundCoords = polygon.boundCoords
                CircPack = CircPacking(boundCoords, depth=10)
                CircPack.plot(plotTriMesh=True)


            >>> 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
            >>> pckCircles = cp(boundCoords, depth=8)
            >>> pckCircles.plot()

            >>> from circpacker.slopegeometry import AnthropicSlope
            >>> from circpacker.packer import CircPacking as cp
            >>> slopeGeometry = AnthropicSlope(12, [1, 1.5], 10, 10)
            >>> boundCoords = slopeGeometry.boundCoords
            >>> pckCircles = cp(boundCoords, depth=3)
            >>> pckCircles.plot(plotTriMesh=True)

            .. plot::

                from numpy import array
                from circpacker.slopegeometry import NaturalSlope
                from circpacker.packer import CircPacking as cp
                surfaceCoords = array([[-2.4900, 18.1614],
                                       [0.1022, 17.8824],
                                       [1.6975, 17.2845],
                                       [3.8909, 15.7301],
                                       [5.8963, 14.3090],
                                       [8.1183, 13.5779],
                                       [9.8663, 13.0027],
                                       [13.2865, 3.6058],
                                       [20.2865, 3.6058],
                                       [21.4347, 3.3231],
                                       [22.2823, 2.7114],
                                       [23.4751, 2.2252],
                                       [24.6522, 1.2056],
                                       [25.1701, 0.2488]])
                slopeGeometry = NaturalSlope(surfaceCoords)
                boundCoords = slopeGeometry.boundCoords
                pckCircles = cp(boundCoords, depth=6)
                pckCircles.plot(plotTriMesh=True)
        '''

        # plotting
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(np.hstack((self.coordinates[:, 0], self.coordinates[0, 0])),
                np.hstack((self.coordinates[:, 1], self.coordinates[0, 1])),
                '-k', lw=1.5, label='Polygon')
        ax.axis('equal')
        ax.set_xlabel('$x$ [m]')
        ax.set_ylabel('$y$ [m]')
        ax.grid(ls='--', lw=0.5)
        for circle in self.listCirc:
            ax.add_patch(plt.Circle(circle.center, circle.radius, fill=False,
                                    lw=1, ec='black'))
        # plotting triangular mesh
        if plotTriMesh:
            fig = plt.figure()
            ax = fig.add_subplot(111)
            ax.grid(ls='--', lw=0.5)
            tplot.plot(ax, **self.CDT)
            ax.axis('equal')
        return
예제 #33
0
import triangle
import triangle.plot as plot
import matplotlib.pyplot as plt

ax = plt.axes()
A = triangle.get_data("A")
t = triangle.triangulate(A, "p")
plot.plot(ax, **t)
plt.show()
예제 #34
0
import triangle
import triangle.plot as plot
import matplotlib.pyplot as plt

ax = plt.axes()
A = triangle.get_data('A')
t = triangle.triangulate(A, 'p')
plot.plot(ax, **t)
plt.show()
예제 #35
0
def triangulate(polygon, ordered_quality_matrix, recursive=True):
    set_edges = set(tuple(i) for i in get_contour_edges(polygon))
    interior_edges = set()
    set_elements = set()
    set_locked_vertices = set()
    set_forbidden_intersections = set()
    polygon_angles = get_polygon_angles(polygon)

    print("initial set edges:", set_edges)

    for edge in ordered_quality_matrix.keys():

        found_in_interior_set, found_in_set, index = check_edge_validity(
            edge, polygon, set_edges, interior_edges)

        for qualities_with_edges in ordered_quality_matrix[edge][0]:

            element_created = False

            target_vtx = qualities_with_edges[1]

            if target_vtx == edge[0] or target_vtx == edge[1]:
                continue

            print("Edge:", edge, "targeting:", target_vtx)

            if found_in_interior_set:
                element = (edge[0], edge[1], index)
                set_elements.add(element)
                print("Element inserted:", element)
                continue

            if found_in_set and not found_in_interior_set:
                if (index != target_vtx):
                    print('found', (edge[0], index), (edge[1], index),
                          "Canceling creation")
                    continue

            # Passed edges checking
            # Proceed to check vertices
            temp_element = (edge[0], edge[1], target_vtx)

            # Cehcking element normals to avoid inverted elements
            element_indices = np.asarray([edge[0], edge[1], target_vtx])
            if compute_triangle_normals(polygon[element_indices]) < 0:
                continue

            # Checking if the element contains other points of the polygon inside
            if contains_points(polygon[element_indices], polygon):
                continue

            p0, p1, p2 = edge[0], edge[1], target_vtx

            neighbor_points = connection_indices(p2,
                                                 get_contour_edges(polygon))

            # Checking if edges of connected poiints form an angle bigger than the polygon angles
            if (polygon_angles[p0] < calculate_angle(polygon[p0], polygon[p1],
                                                     polygon[p2])
                    or polygon_angles[p1] < calculate_angle(
                        polygon[p1], polygon[p0], polygon[p2])):
                #print("Spotted inverted triangle: {}".format([p0,p1,p2]))
                continue

            if (polygon_angles[p2] < calculate_angle(
                    polygon[p2], polygon[neighbor_points[0]], polygon[p0])
                    or polygon_angles[p2] < calculate_angle(
                        polygon[p2], polygon[neighbor_points[0]],
                        polygon[p1])):
                continue

            if (polygon_angles[p2] < calculate_angle(
                    polygon[p2], polygon[neighbor_points[1]], polygon[p0])
                    or polygon_angles[p2] < calculate_angle(
                        polygon[p2], polygon[neighbor_points[1]],
                        polygon[p1])):
                #print("Spotted inverted triangle: {}".format([p0,p1,p2]))
                continue
            quality = compute_minimum_quality_triangle(
                polygon[element_indices], polygon)
            if quality == 0 or quality < 1e-2:
                continue

            print(temp_element)
            existing_element = False
            for temp_element_permutation in tuple(permutations(temp_element)):
                if temp_element_permutation in set_elements:
                    print("Element {} already in set".format(element))
                    existing_element = True
                    break
            if existing_element:
                break

            if target_vtx in set_locked_vertices:
                print(" Target vertex {} is locked".format(target_vtx))
                continue
            set_elements.add(temp_element)

            # Check if a locked vertex was created after the creation of the element
            # If so, add it to the list
            #Tracer()()
            Found_locked_vertex = False
            for vertex in temp_element:
                _, isclosed = is_closed_ring(
                    vertex, set_elements,
                    *connection_indices(vertex, get_contour_edges(polygon)))
                if isclosed and vertex not in set_locked_vertices:
                    print("Vertex locked:", vertex)
                    Found_locked_vertex = True
                    set_locked_vertices.add(vertex)
            set_elements.remove(temp_element)

            # Locking the vertices and checking if the connection is with a locked vertex has been checked/
            # Proceeding to check if both internal edges intersect with other internal edges
            internal_edge1 = (edge[0], target_vtx)
            internal_edge2 = (edge[1], target_vtx)
            set_a, set_b = get_intermediate_indices(target_vtx, polygon,
                                                    edge[0], edge[1])

            internal_condition1 = internal_edge1 in set_forbidden_intersections or tuple(
                reversed(internal_edge1)) in set_forbidden_intersections

            internal_condition2 = internal_edge2 in set_forbidden_intersections or tuple(
                reversed(internal_edge2)) in set_forbidden_intersections

            internal_intersection = False
            if internal_condition1 or internal_condition2:
                print("edges :", internal_edge1, "and", internal_edge2,
                      "intersecting")
                print("Abandoning creation of element", temp_element)
                internal_intersection = True

            if internal_intersection:
                for vtx in temp_element:
                    if Found_locked_vertex and vtx in set_locked_vertices:
                        print("Unlocking vertex", vtx)
                        set_locked_vertices.remove(vtx)
                continue

            # Create the element
            element = temp_element

            # Add to set of edges all the forbidden intersections after the creation of the element

            for i in set_a:
                for j in set_b:
                    set_forbidden_intersections.add((i, j))
            #print("set of forbidden inter section edges updated:",set_forbidden_intersections)

        # New edges after creation of the element

            new_edge1 = (edge[0], target_vtx)
            new_edge2 = (edge[1], target_vtx)

            if new_edge1 not in set_edges and tuple(
                    reversed(new_edge1)) not in set_edges:
                set_edges.add(new_edge1)
                interior_edges.add(new_edge1)
                print("edges inserted:", new_edge1)
                print("set of interior edges updated:", interior_edges)
                print("set of edges updated:", set_edges)
            if new_edge2 not in set_edges and tuple(
                    reversed(new_edge2)) not in set_edges:
                set_edges.add(new_edge2)
                interior_edges.add(new_edge2)
                print("edges inserted:", new_edge2)
                print("set of interior edges updated:", interior_edges)
                print("set of edges updated:", set_edges)

            # Checking list of elements to see whether the were created or were already there
            for element_permutation in tuple(permutations(element)):
                if element_permutation in set_elements:
                    print("Element {} already in set".format(element))
                    break
            else:
                set_elements.add(element)
                indices = np.asarray(element)
                print("element inserted:", element)
                element_created = True
                break
        if element_created:
            continue

    triangulated = {
        'segment_markers': np.ones([polygon.shape[0]]),
        'segments': np.array(get_contour_edges(polygon)),
        'triangles': np.array(list(list(i) for i in set_elements)),
        'vertex_markers': np.ones([polygon.shape[0]]),
        'vertices': polygon
    }
    plot.plot(plt.axes(), **triangulated)
    print("Final edges:", set_edges)
    print("Elements created:", set_elements)
    print("Set of locked vertices:", set_locked_vertices)

    # find open vertices
    for element in set_elements:
        for vertex in element:
            _, isclosed = is_closed_ring(
                vertex, set_elements,
                *connection_indices(vertex, get_contour_edges(polygon)))
            if isclosed and vertex not in set_locked_vertices:
                print("Vertex locked:", vertex)
                Found_locked_vertex = True
                set_locked_vertices.add(vertex)
    set_open_vertices = set(range(len(polygon))) - set_locked_vertices
    print("Set of open vertices:", set_open_vertices)
    set_edges.clear(), set_locked_vertices.clear(
    ), set_forbidden_intersections.clear
    if recursive:
        sub_polygon_list = check_for_sub_polygon(set_open_vertices,
                                                 interior_edges, set_elements,
                                                 polygon)

        for sub_polygon_indices in sub_polygon_list:
            if len(sub_polygon_indices) >= 4:
                polygon_copy = polygon.copy()
                sub_polygon = np.array(polygon_copy[sub_polygon_indices])
                sub_quality, _ = quality_matrix(sub_polygon,
                                                compute_minimum=True,
                                                normalize=False)
                sub_order_matrix = order_quality_matrix(
                    sub_quality, sub_polygon)
                print(sub_quality, sub_order_matrix)
                triangulate(sub_polygon, sub_order_matrix)
예제 #36
0
파일: room.py 프로젝트: blancosilva/NAO
# ax = fig2.add_subplot(111, aspect='equal')
# tplot.plot(ax, **tri)

# # Plot #3
# fig3 = plt.figure()
# ax = fig3.add_subplot(111, aspect='equal')
# tplot.plot(ax, **tri)
# ax.plot(Xs, Ys, '-', linewidth=5, color='blue')

# # Plot #4
# fig4 = plt.figure()
# ax = fig4.add_subplot(111, aspect='equal')
# tplot.plot(ax, **room)
# ax.plot(Xs, Ys, '-', linewidth=2, color='blue')

# Plot #5
fig5 = plt.figure()
ax = fig5.add_subplot(111, aspect='equal')
tplot.plot(ax, **room)
ax.plot(Xs, Ys, '-', linewidth=2, color='blue')
for k in range(len(Xs)):
	ax.text(Xs[k], Ys[k], k)

# Plot #6
fig6 = plt.figure()
ax = fig6.add_subplot(111, aspect='equal')
tplot.plot(ax, **room)
ax.plot(x, interpolator(x), 'b-', linewidth=5)


plt.show()
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')


plot.plot(plt.axes(),**tri)

#triangle.plot.compare(plt, dic, tri)
#plt.show()
#print tri

# create the graph based on the scenario file
#graph = createGraph(tri["triangles"], tri["vertices"], tri["segments"])

segments_froset = [frozenset(v) for v in tri['segments']]
graph, edges_index, edges_dirs, edges_by_tri, vertices_of_edges, edges_surface_dic, tri_by_surface, tri_neighbor_by_edge = create_graph_advanced(tri["triangles"], tri["vertices"], segments_froset, scenario_width, scenario_height)

################### Arrange graph according to the position of triangles #########

triangles_by_vertices = tri["vertices"][tri["triangles"]]
pos = {}
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()
예제 #39
0
import triangle
import triangle.plot as plot
import matplotlib.pyplot as plt

spiral = triangle.get_data("spiral")

ax1 = plt.subplot(221, aspect="equal")
triangle.plot.plot(ax1, vertices=spiral["vertices"])

a = triangle.triangulate(spiral)
ax2 = plt.subplot(222, sharex=ax1, sharey=ax1)
plot.plot(ax2, **a)

b = triangle.triangulate(spiral, "q")
ax3 = plt.subplot(223, sharex=ax1, sharey=ax1)
plot.plot(ax3, **b)

c = triangle.triangulate(spiral, "q32.5")
ax4 = plt.subplot(224, sharex=ax1, sharey=ax1)
plot.plot(ax4, **c)

plt.show()

import triangle
import triangle.plot as plot
import matplotlib.pyplot as plt

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

t = triangle.triangulate(spiral)

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

plt.show()
예제 #41
0
    [grid4corner, grid4slot1, grid4slot2, grid4slot_inner_conner])
# 生成线段
segment1 = np.array([[0, 1], [1, 3], [3, 2], [2, 0]])
segment2 = np.array([[0, 1], [1, 9], [9, 7], [7, 6], [6, 11], [11, 3], [3, 2],
                     [2, 10], [10, 4], [4, 5], [5, 8], [8, 0]]) + 4
segment = np.vstack([segment1, segment2])

# 生成空洞
hole = np.array([0, 0]).reshape([1, -1])
# 完成PLSG的结构体
myPloy = dict({"vertices": vertices, 'holes': hole, 'segments': segment})

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

# 进行网格剖分
plt.figure()
myMesh = triangle.triangulate(myPloy, 'pq30a0.01')
ax1 = plt.subplot(111, aspect='equal')
triplt.plot(ax1, **myMesh)
plt.show()

# 将剖分网格进行保存
saveTriaPoly(myMesh, "plane_slot")

# 从文件中导入网格
C_copy = triangle.load('.', 'plane_slot')
C_copy = triangle.triangulate(C_copy, 'p')  # 由于PLSG文件中不包含三角形,故需要进行组合成三角形
예제 #42
0
    def plot(self, plotTriMesh=False):
        '''Method for show a graphic of the circles generated within of the
        polygon.

        Parameters
        ----------
            plotTriMesh : `bool`
                Variable to check if it also want to show the graph of the\
                triangles mesh. Default is ``False``

        Examples
        --------

            .. plot::

                from numpy import array
                from pc4bims.basegeom import Polygon
                from pc4bims.circlepacking import CirclePacking as CP
                coordinates = array([[1, 1], [2, 5], [4.5, 6], [8, 3], [7, 1],
                                     [4, 0]])
                polygon = Polygon(coordinates)
                boundCoords = polygon.boundCoords
                circlePacking = CP(boundCoords, depth=3)
                circlePacking.plot(plotTriMesh=True)

                from numpy import array
                from pc4bims.basegeom import Polygon
                from pc4bims.circlepacking import CirclePacking 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
                circlePacking = CP(boundCoords, 2)
                circlePacking.plot()

                from pc4bims.slope import AnthropicSlope
                from pc4bims.circlepacking import CirclePacking as CP
                slopeGeometry = AnthropicSlope(12, [1, 1.5], 10, 10)
                boundCoords = slopeGeometry.boundCoords
                circlePacking = CP(boundCoords, 5)
                circlePacking.plot(plotTriMesh=True)

                from numpy import array
                from pc4bims.slope import NaturalSlope
                from pc4bims.circlepacking import CirclePacking as CP
                surfaceCoords = array([[-2.4900, 18.1614],
                                       [0.1022, 17.8824],
                                       [1.6975, 17.2845],
                                       [3.8909, 15.7301],
                                       [5.8963, 14.3090],
                                       [8.1183, 13.5779],
                                       [9.8663, 13.0027],
                                       [13.2865, 3.6058],
                                       [20.2865, 3.6058],
                                       [21.4347, 3.3231],
                                       [22.2823, 2.7114],
                                       [23.4751, 2.2252],
                                       [24.6522, 1.2056],
                                       [25.1701, 0.2488]])
                slopeGeometry = NaturalSlope(surfaceCoords)
                boundCoords = slopeGeometry.boundCoords
                circlePacking = CP(boundCoords, 2)
                circlePacking.plot(plotTriMesh=True)
        '''

        # plotting
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(np.hstack((self.coordinates[:, 0], self.coordinates[0, 0])),
                np.hstack((self.coordinates[:, 1], self.coordinates[0, 1])),
                '-k', lw=1.5, label='Polygon')
        ax.axis('equal')
        ax.set_xlabel('$x$ distance')
        ax.set_ylabel('$y$ distance')
        for circle in self.circlesInPoly:
            ax.add_patch(plt.Circle(circle.center, circle.radius, fill=True,
                                    lw=1, ec='k', fc='k'))
        # plotting triangular mesh
        if plotTriMesh:
            fig = plt.figure()
            ax = fig.add_subplot(111)
            ax.grid(ls='--', lw=0.5)
            tplot.plot(ax, **self.CDT)
            ax.axis('equal')
        return
예제 #43
0
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, 'p')

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

plt.show()