Ejemplo n.º 1
1
def plot_2d_clusters(X, labels, centers):
    """
    Given an observation array, a label vector, and the location of the centers
    plot the clusters
    """

    clabels = set(labels)
    K = len(clabels)

    if len(centers) != K:
        raise ValueError("Expecting the number of unique labels and centres to"
                         " be the same!")

    # Plot the true clusters
    figure(figsize=(10, 10))
    ax = gca()

    vor = Voronoi(centers)

    voronoi_plot_2d(vor, ax)

    colors = cm.hsv(np.arange(K)/float(K))
    for k, col in enumerate(colors):
        my_members = labels == k
        scatter(X[my_members, 0], X[my_members, 1], c=col, marker='o', s=20)

    for k, col in enumerate(colors):
        cluster_center = centers[k]
        scatter(cluster_center[0], cluster_center[1], c=col, marker='o', s=200)

    axis('tight')
    axis('equal')
    title('Clusters')
Ejemplo n.º 2
0
def plot_cs_voronoi_scipy():
    """
    CubeGridRemap.get_voronoi(): Plot with voronoi_plot_2d
    """
    from cube_remap import CubeGridRemap
    from scipy.spatial import voronoi_plot_2d
    import matplotlib.pyplot as plt

    # ne, ngq = 30, 4
    ne, ngq = 3, 4
    rotated = False
    cube = CubeGridRemap(ne, ngq, rotated)

    print "ne=%d, ngq=%d" % (ne, ngq)

    for uid in xrange(20):
        xy_vertices, vor = cube.get_voronoi(uid)

        print ""
        print "uid", uid
        print "vor.vertices\n", vor.vertices
        print "vor.ridge_points\n", vor.ridge_points
        print "vor.ridge_vertices\n", vor.ridge_vertices
        print ""
        print "xy_vertices\n", xy_vertices
        voronoi_plot_2d(vor)
        # plt.savefig('voronoi_%d.png'%uid)
        plt.show()
    def test_BorderBuilder(self):
        plt.clf()
        polygon = self.generatePolygon(0, 0, 5, 0.1, 0.1, 50)
        polygon.append(polygon[0])
        x, y = zip(*polygon)
        # plt.plot(x, y)
        x, y = self._addRandomPoints(x, y, 10)
        points = zip(x, y)

        vor = Voronoi(points)
        voronoi_plot_2d(vor)
        # plt.show()

        labels = map(int, mplPath.Path(polygon).contains_points(points))
        waterX, waterY, insideX, insideY = [], [], [], []
        for i in range(len(x)):
            if labels[i]:
                insideX.append(x[i])
                insideY.append(y[i])
            else:
                waterX.append(x[i])
                waterY.append(y[i])
        # plt.scatter(insideX, insideY, c="g")
        # plt.scatter(waterX, waterY, c="b")
        # plt.show()
        borders = self.TestBorderBuilder(x, y, labels).build()
        region = borders[0]
        for section in region:
            section.append(section[0])
            x, y = zip(*section)
            plt.plot(x, y)
        plt.show()
Ejemplo n.º 4
0
 def nn_vor(self):
     coords = self.atom_coords()
     vor = Voronoi(coords)
     print(vor.vertices)
     print(vor.regions)
     voronoi_plot_2d(vor)
     plt.show()
Ejemplo n.º 5
0
def plot_cs_voronoi():
    '''
    CubeGridRemap.get_voronoi(): Plot
    '''
    from cube_remap import CubeGridRemap
    from scipy.spatial import voronoi_plot_2d
    import matplotlib.pyplot as plt

    #ne, ngq = 30, 4
    ne, ngq = 3, 4
    rotated = False
    cube = CubeGridRemap(ne, ngq, rotated)

    print 'ne=%d, ngq=%d'%(ne, ngq)

    for uid in xrange(20):
        xy_vertices, vor = cube.get_voronoi(uid)

        print ''
        print 'uid', uid
        print 'vor.vertices\n', vor.vertices
        print 'vor.ridge_points\n', vor.ridge_points
        print 'vor.ridge_vertices\n', vor.ridge_vertices
        print ''
        print 'xy_vertices\n', xy_vertices
        voronoi_plot_2d(vor)
        #plt.savefig('voronoi_%d.png'%uid)
        plt.show()
Ejemplo n.º 6
0
def main():
    
    lati = coordGrab('Latitude')
    longi = coordGrab('Longitude')
    '''
    map = Basemap(projection='merc', lat_0 = 57, lon_0 = -135,
    resolution = 'h', area_thresh = 0.1,
    llcrnrlon=-74.359150, llcrnrlat=40.530479,
    urcrnrlon=-73.585905,  urcrnrlat=40.983567)'''
    
    points = zip(lati,longi)
    
    vor = Voronoi(points)
    voronoi_plot_2d(vor)
    
    '''
    x,y = map(longi, lati)
    map.plot(x, y, 'bo', markersize=7, alpha=.7)
  
    map.drawcoastlines()
    map.drawcountries()
    map.drawcounties()
    map.fillcontinents(color = 'red')
    map.drawmapboundary() '''
    plt.title("Location of CUNY campuses in NY")
    
 
    plt.show()
Ejemplo n.º 7
0
 def test_voronoi(self):
     # Smoke test
     fig = plt.figure()
     obj = Voronoi(self.points)
     r = voronoi_plot_2d(obj, ax=fig.gca())
     assert_(r is fig)
     voronoi_plot_2d(obj)
Ejemplo n.º 8
0
def voronoi(dataName,dataType,value):
	v_arr=genfromtxt(dataName + str(value) + dataType,delimiter=',' )
	data = [[row[0],row[1]] for row in v_arr]
	vor = Voronoi(data)
	voronoi_plot_2d(vor)
	plt.xlim(300,700);plt.ylim(300,700);
	plt.savefig('voronoi_' + str(value) + '.png',dpi=200)
	print 'Saved Voronoi @ t=' + str(value)
Ejemplo n.º 9
0
 def __init__(self, seed=0):
     if seed:
         np.random.seed(seed)
     self.beach = 0
     self.index = []
     self.coords = random_numbers()
     self.vor = Voronoi(self.coords)
     voronoi_plot_2d(self.vor)
Ejemplo n.º 10
0
def greeting(board):
    print "Hello, and welcome to gravitational voronoi!"
    print "currently the board looks like this."
    points = np.array(board)
    vor = Voronoi(points)
    voronoi_plot_2d(vor)
    plt.show()
    return points
Ejemplo n.º 11
0
 def test_voronoi(self):
     # Smoke test
     fig = plt.figure()
     obj = Voronoi(self.points)
     with suppress_warnings() as sup:
         # filter can be removed when matplotlib 1.x is dropped
         sup.filter(message="The ishold function was deprecated in version")
         r = voronoi_plot_2d(obj, ax=fig.gca())
     assert_(r is fig)
     voronoi_plot_2d(obj)
     voronoi_plot_2d(obj, show_vertices=False)
Ejemplo n.º 12
0
def player1(points,p1_stones_placed):
    x = int(raw_input("Please enter the x-coordinate for your move"))
    y = int(raw_input("Please enter the y-coordinate for your move"))
    vor = Voronoi(points,incremental=True) #needed or you can't add points
    move = np.array([[x,y]])
    vor.add_points(move)
    print "You're new move looks like this:"
    voronoi_plot_2d(vor)
    plt.show()
    p1_stones_placed += 1
    return move, p1_stones_placed
Ejemplo n.º 13
0
def plotting(DIR, z_name, opos):
    colours = ['#313695', '#4575b4', '#74add1',\
               '#abd9e9', '#fdae61', '#f46d43', '#d73027', '#a50026',\
               '#313695', '#4575b4', '#74add1',\
               '#abd9e9', '#fdae61', '#f46d43', '#d73027', '#a50026',\
               '#313695', '#4575b4', '#74add1',\
               '#abd9e9', '#fdae61', '#f46d43', '#d73027', '#a50026']


    xlo, xhi, ylo, yhi, zlo, zhi = coords(DIR, z_name)
    vor = Voronoi(opos)
    fig = voronoi_plot_2d(vor, show_vertices=False, point_size=0.1)

    # add colours
    for region in vor.regions:
        if not -1 in region:
            polygon = [vor.vertices[i] for i in region]
            plt.fill(*zip(*polygon), c=colours[2*len(region)+1])
            #plt.fill
    plt.xlim(0, xhi)
    plt.ylim(ylo, yhi)
    plt.xlabel('$x$ (\AA)')
    plt.ylabel('$y$ (\AA)')
    plt.savefig('PLOTS_C/{}/voronoi_2d_{}.pdf'.format(DIR,z_name),
                bbox_inches='tight')
    #plt.show()

    return 
Ejemplo n.º 14
0
def _tri_demo(tri_type='Delaunay'):
    """Triangulation demo.
    """
    from scipy.spatial import delaunay_plot_2d, voronoi_plot_2d
    import matplotlib.pyplot as plt
    xs =[ 48,   8, 623, 615, 196, 368, 112, 918, 318, 316, 427,
         364, 849, 827, 438, 957, 495, 317, 985, 534]
    ys = [674, 215, 834, 235, 748, 630, 876, 407,  33, 872, 893,
          360, 397, 902, 420, 430, 678, 523, 604, 292]
    aa = np.array(list(zip(xs, ys)))
    c = infinity_circle(aa, fac=0)
    a = np.vstack((aa, c))
    d = v = None  # initialize the output to None
    if tri_type == 'Delaunay':
        d = Delaunay(aa)
        plot = delaunay_plot_2d(d)
        x0, y0 = [0., 0.]
        x1, y1 = [1000., 1000.]
    else:
        c = infinity_circle(a, fac=2)
#        a = np.vstack((a, c))
        x0, y0 = a.min(axis=0)
        x1, y1 = a.max(axis=0)
        v = Voronoi(a, qhull_options='Qbb Qc Qx')
        plot = voronoi_plot_2d(v, show_vertices=True, line_colors='y',
                               line_alpha=0.8, point_size=5)
    # ----
    plot.set_figheight(10)
    plot.set_figwidth(10)
    plt.axis([0, 1000, 0, 1000])
#    plt.axis([x0, x1, y0, y1])
    plt.show()
    return aa, (d or v)
Ejemplo n.º 15
0
def Vor_pnts(pnts, testing=True, plot=True):
    """Requires a set of points deemed to be a cluster to delineate as a
    Voronoi diagram. You can do multiple point groupings by using this within
    a loop to return the geometries.
    """
    avg = np.mean(pnts, axis=0)
    p = pnts - avg
    tri = Voronoi(p)
    out = []
    for region in tri.regions:
        if not -1 in region:
            polygon = np.array([tri.vertices[i] + avg for i in region])
            out.append(polygon)
            if testing:
                print("{}".format(polygon.T))
    if plot:
        voronoi_plot_2d(tri)
    return out
Ejemplo n.º 16
0
def model2mesh(coord):#,stp,tolerance,lng):
    #This function performs a medial axis transform to a non-branching axis
    #Takes the outline coordinates, step size on the final centerline,
    #tolerance to non-centrality, and the length of the ribs. The last
    #parameter should be longer than the ribs, but should not be too long to
    #intersect the countour agan: though most cases of >1 intersection will
    #be resolved by the function, some will not. Outputs the coordinates of
    #the centerline points.

    delta = 1E-10;
    
    #voronoi transform
    vor = Voronoi(coords)
    print vor.vertices
    print type(vor.vertices)
    print dir(vor.vertices)
    print len(vor.vertices)
    voronoi_plot_2d(vor)
    plt.show()
    
#     % remove vertices crossing the boundary
#     vx = reshape(vx,[],1);
#     vy = reshape(vy,[],1);
#     q = intxy2(vx,vy,coord([1:end 1],1),coord([1:end 1],2));
#     vx = reshape(vx(~[q;q]),2,[]);
#     vy = reshape(vy(~[q;q]),2,[]);
    
#     % remove vertices outside [of the cell?]
#     q = logical(inpolygon(vx(1,:),vy(1,:),coord(:,1),coord(:,2))...
#              .* inpolygon(vx(2,:),vy(2,:),coord(:,1),coord(:,2)));
#     vx = reshape(vx([q;q]),2,[]);
#     vy = reshape(vy([q;q]),2,[]);
    
#     % remove isolated points
#     if isempty(vx), res=0;return; end
#     t = ~((abs(vx(1,:)-vx(2,:))<delta)&(abs(vy(1,:)-vy(2,:))<delta));
#     vx = reshape(vx([t;t]),2,[]);
#     vy = reshape(vy([t;t]),2,[]);
         
    #remove branches
    vx2=[];
    vy2=[];
Ejemplo n.º 17
0
def doSom():
    conn = pymongo_utill.getConnectionToMongoDB()
    db = conn['TwitterInsert']
    #users,labels,screen_names = pymongo_utill.byTimeFreq(db=db,sample=225)
    users,labels,screen_names = pymongo_utill.byTimeFreq(db=db,sample=10)

    conn.disconnect()
    #vectorizer = WordVectorizer()
    #users = vectorizer.fit_transform(users)

    clusterid, celldata = somcluster(data=users, nxgrid=21, nygrid=31, niter=500)
    plt.xlim((-5,25))
    plt.ylim((-5,35))
    """
    print(len(clusterid))
    for i,v in enumerate(clusterid):
        print("number:%s coordinates:%s name:%s class:%s" % (i, v, screen_names[i], labels[i]))

    for i, (x,y) in enumerate(clusterid):
        if labels[i] == 0:
            plt.plot(x,y,'-bo')
        if labels[i] == 1:
            plt.plot(x,y,'-ro')

    plt.show()

    for i, v in enumerate(clusterid):
        plt.annotate(xy=v, s=int(i/7))
    """
    vor = Voronoi(clusterid)
    voronoi_plot_2d(vor)

    for region in vor.regions:
        if not -1 in region:
            polygon = [vor.vertices[i] for i in region]
            plt.fill(*zip(*polygon))

    plt.show()
Ejemplo n.º 18
0
 def plot(self):
     import matplotlib.pyplot as plt
     from scipy.spatial import Voronoi, voronoi_plot_2d
     # print "self.X:"
     # print self.X
     # print "self.size:"
     # print self.size
     fig = plt.figure(figsize=(10,8), dpi=96)
     ax = fig.add_subplot(111)
     # self.fig, self.ax = plt.subplots(1, 1)
     # self.fig.set_size_inches(10, 8)
     vor = Voronoi(self.mu)
     vor_plot = voronoi_plot_2d(vor, ax=ax)
     # remove the markers for each cluster and for the vertices
     ax.get_lines()[1].remove()
     #ax.get_lines()[0].remove()
     ax.scatter(x=self.X[:,0], y=self.X[:,1], c=self.cluster_id, s=self.size, alpha=0.75)
     ax.set_xlim(min(self.X[:,0]), max(self.X[:,0]))
     ax.set_ylim(min(self.X[:,1]), max(self.X[:,1]))
     # canvas.draw()   # may not be needed? see http://stackoverflow.com/questions/26783843/redrawing-a-plot-in-ipython-matplotlib
     
Ejemplo n.º 19
0
def _imshow_grid_values(grid, values, var_name=None, var_units=None,
                        grid_units=(None, None), symmetric_cbar=False,
                        cmap='jet', limits=None, allow_colorbar=True):
    
    gridtypes = inspect.getmro(grid.__class__)

    if RasterModelGrid in gridtypes:
        if len(values.shape) != 2:
            raise ValueError('dimension of values must be 2 (%s)' % values.shape)
        y = np.arange(values.shape[0] + 1) - grid.dx * .5
        x = np.arange(values.shape[1] + 1) - grid.dx * .5
    
        kwds = dict(cmap=cmap)
        if limits is None:
            if symmetric_cbar:
                (var_min, var_max) = (values.min(), values.max())
                limit = max(abs(var_min), abs(var_max))
                (kwds['vmin'], kwds['vmax']) = (- limit, limit)
        else:
            (kwds['vmin'], kwds['vmax']) = (limits[0], limits[1])
    
    
        myimage = plt.pcolormesh(x, y, values, **kwds)
    
        plt.gca().set_aspect(1.)
        plt.autoscale(tight=True)
        
        if allow_colorbar:
            plt.colorbar()
    
        plt.xlabel('X (%s)' % grid_units[1])
        plt.ylabel('Y (%s)' % grid_units[0])
    
        if var_name is not None:
            plt.title('%s (%s)' % (var_name, var_units))
    
        #plt.show()
        
    elif VoronoiDelaunayGrid in gridtypes:
        """
        This is still very much ad-hoc, and needs prettifying.
        We should save the modifications needed to plot color all the way
        to the diagram edge *into* the grid, for faster plotting.
        (see http://stackoverflow.com/questions/20515554/colorize-voronoi-diagram)
        (This technique is not implemented yet)
        """
        from scipy.spatial import voronoi_plot_2d
        import matplotlib.colors as colors
        import matplotlib.cm as cmx
        cm = plt.get_cmap(cmap)
        if limits is None:
            if symmetric_cbar:
                (var_min, var_max) = (values.min(), values.max())
                limit = max(abs(var_min), abs(var_max))
                (vmin, vmax) = (- limit, limit)
            else:
                (vmin, vmax) = (values.min(), values.max())
        else:
            (vmin, vmax) = (limits[0], limits[1])
        cNorm = colors.Normalize(vmin,vmax)
        scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
        colorVal = scalarMap.to_rgba(values)
        
        myimage = voronoi_plot_2d(grid.vor)
        mycolors = (i for i in colorVal)
        for order in grid.vor.point_region:
            region = grid.vor.regions[order]
            colortouse = next(mycolors)
            if not -1 in region:
                polygon = [grid.vor.vertices[i] for i in region]
                #print "polygon:"
                #print polygon
                #print len(polygon)
                #print "colortouse:"
                #print next(colortouse)
                #print len(colortouse)
                plt.fill(*zip(*polygon),color=colortouse)
                #must be TOTALLY sure the ordering is right

        plt.gca().set_aspect(1.)
        #plt.autoscale(tight=True)
        plt.xlim((np.min(grid.node_x), np.max(grid.node_x)))
        plt.ylim((np.min(grid.node_y), np.max(grid.node_y)))
    
        scalarMap.set_array(values)
        plt.colorbar(scalarMap)
    
        plt.xlabel('X (%s)' % grid_units[1])
        plt.ylabel('Y (%s)' % grid_units[0])
    
        if var_name is not None:
            plt.title('%s (%s)' % (var_name, var_units))
        
    return myimage
Ejemplo n.º 20
0
  plt.show()

if False:

  x = np.random.randn(50)
  y = np.random.randn(50)

  cc = voronoi_plot(x, y, field_lim = [-2.5, 2.5, -2.5, 2.5])

  import matplotlib.pyplot as plt

  fig = plt.figure(figsize = (15., 6.))
  ax = fig.add_subplot(1, 2, 1)
  ax2 = fig.add_subplot(1, 2, 2)
  vd = spt.Voronoi(np.vstack((x, y)).T)
  spt.voronoi_plot_2d(vd, ax2)
  ax.set_xlim(-3., 3.)
  ax.set_ylim(-3., 3.)
  ax.axvline(x = -2.5, linestyle = 'dashed')
  ax.axvline(x = 2.5, linestyle = 'dashed')
  ax.axhline(y = -2.5, linestyle = 'dashed')
  ax.axhline(y = 2.5, linestyle = 'dashed')
  ax2.set_xlim(-3., 3.)
  ax2.set_ylim(-3., 3.)
  ax2.axvline(x = -2.5, linestyle = 'dashed')
  ax2.axvline(x = 2.5, linestyle = 'dashed')
  ax2.axhline(y = -2.5, linestyle = 'dashed')
  ax2.axhline(y = 2.5, linestyle = 'dashed')

  for icc in cc:
Ejemplo n.º 21
0
def _imshow_grid_values(grid, values, var_name=None, var_units=None,
                        grid_units=(None, None), symmetric_cbar=False,
                        cmap='pink', limits=None, allow_colorbar=True,
                        vmin=None, vmax=None,
                        norm=None, shrink=1., color_for_closed='black'):

    gridtypes = inspect.getmro(grid.__class__)

    cmap = plt.get_cmap(cmap)
    cmap.set_bad(color=color_for_closed)

    if RasterModelGrid in gridtypes:
        if len(values.shape) != 2:
            raise ValueError('dimension of values must be 2 (%s)' % values.shape)

        y = np.arange(values.shape[0] + 1) * grid.dx - grid.dx * .5
        x = np.arange(values.shape[1] + 1) * grid.dx - grid.dx * .5

        kwds = dict(cmap=cmap)
        (kwds['vmin'], kwds['vmax']) = (values.min(), values.max())
        # ^default condition
        if (limits is None) and ((vmin is None) and (vmax is None)):
            if symmetric_cbar:
                (var_min, var_max) = (values.min(), values.max())
                limit = max(abs(var_min), abs(var_max))
                (kwds['vmin'], kwds['vmax']) = (- limit, limit)
            else:
                pass
        elif limits is not None:
            (kwds['vmin'], kwds['vmax']) = (limits[0], limits[1])
        else:
            if vmin is not None:
                kwds['vmin'] = vmin
            if vmax is not None:
                kwds['vmax'] = vmax

        myimage = plt.pcolormesh(x, y, values, **kwds)

        plt.gca().set_aspect(1.)
        plt.autoscale(tight=True)

        if allow_colorbar:
            plt.colorbar(norm=norm, shrink=shrink)

        plt.xlabel('X (%s)' % grid_units[1])
        plt.ylabel('Y (%s)' % grid_units[0])

        if var_name is not None:
            plt.title('%s (%s)' % (var_name, var_units))

        #plt.show()

    elif VoronoiDelaunayGrid in gridtypes:
        # This is still very much ad-hoc, and needs prettifying.
        # We should save the modifications needed to plot color all the way
        # to the diagram edge *into* the grid, for faster plotting.
        # (see http://stackoverflow.com/questions/20515554/colorize-voronoi-diagram)
        # (This technique is not implemented yet)
        from scipy.spatial import voronoi_plot_2d
        import matplotlib.colors as colors
        import matplotlib.cm as cmx
        cm = plt.get_cmap(cmap)
        if limits is None:
            #only want to work with NOT CLOSED nodes
            open_nodes = grid.node_status!=4
            if symmetric_cbar:
                (var_min, var_max) = (values.flat[open_nodes].min(), values.flat[open_nodes].max())
                limit = max(abs(var_min), abs(var_max))
                (vmin, vmax) = (- limit, limit)
            else:
                (vmin, vmax) = (values.flat[open_nodes].min(), values.flat[open_nodes].max())
        else:
            (vmin, vmax) = (limits[0], limits[1])
        cNorm = colors.Normalize(vmin,vmax)
        scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
        colorVal = scalarMap.to_rgba(values)

        myimage = voronoi_plot_2d(grid.vor)
        mycolors = (i for i in colorVal)
        for order in grid.vor.point_region:
            region = grid.vor.regions[order]
            colortouse = next(mycolors)
            if -1 not in region:
                polygon = [grid.vor.vertices[i] for i in region]
                plt.fill(*zip(*polygon),color=colortouse)
                #must be TOTALLY sure the ordering is right

        plt.gca().set_aspect(1.)
        #plt.autoscale(tight=True)
        plt.xlim((np.min(grid.node_x), np.max(grid.node_x)))
        plt.ylim((np.min(grid.node_y), np.max(grid.node_y)))

        scalarMap.set_array(values)
        plt.colorbar(scalarMap)

        plt.xlabel('X (%s)' % grid_units[1])
        plt.ylabel('Y (%s)' % grid_units[0])

        if var_name is not None:
            plt.title('%s (%s)' % (var_name, var_units))

    return myimage
Ejemplo n.º 22
0
        indices = np.where(labeled_particles == num)
        x_pos = np.average(indices[1])
        y_pos = np.average(indices[0])
        centers.append((x_pos, y_pos))
    return centers


centers = centersParticle()

# make up data points
points = np.random.rand(15, 2)

vor = Voronoi(points)

# Plot it:
voronoi_plot_2d(vor)
plt.show()

regions = vor.regions
reg_coords = []
for region in regions:
    if not -1 in region and len(region) > 0:
        coords = vor.vertices[region]
        reg_coords.append(coords)

import numba


@numba.jit(nopython=True)
def areaPolygon(vertices):
    area = 0
Ejemplo n.º 23
0
def voronoi_prune_region(nodes, alpha_cut, keep=0.05, draw=None):
    """ Takes as input a list of points

    First computes the concave hull and removes
    all points outside it.

    Then remove all those points completely contained.
    In other words, only return those which are on
    the boundary of the hull.
    """

    nodes_list = list(nodes)

    log.info("Pruning %i nodes", len(nodes_list))

    points = np.array([(x.lon, x.lat) for x in nodes_list], dtype=float)

    # get the concave hull around these points
    hull = get_concave_hull(points, alpha_cut)
    if not hull:
        log.warning("Concave hull is null, using convex!")
        hull = get_convex_hull(points)
    # buffer hull by about 5% for determining membership
    hull_distance_scale = math.sqrt(hull.area)
    buffered_hull = prep(hull.buffer(hull_distance_scale * 0.05))
    hull_boundary = hull.boundary

    # Remove any outlier points around these nodes.
    # Mark the good nodes.
    nodes_in_hull = []
    nodes_outside_hull = []
    for point, node in itertools.izip(points, nodes_list):
        if buffered_hull.contains(Point(point)):
            nodes_in_hull.append(node)
        else:
            nodes_outside_hull.append(node)

    # We only care about interior points now.
    del nodes_list
    points = np.array([(x.lon, x.lat) for x in nodes_in_hull], dtype=float)

    log.info("After hull cleaning, %i nodes remain",
             len(points))

    voronoi = Voronoi(points)

    edge_regions = set([])

    # find all regions which have a vertex outside the hull
    prepped_hull = prep(hull)
    for region_idx, region in enumerate(voronoi.regions):
        exterior_region = False
        # keep a random collection of interior points
        if random.random() < keep:
            exterior_region = True
        else:
            for vtx_idx in region:
                # indicates an exterior region, we always keep these
                if vtx_idx == -1:
                    exterior_region = True
                    break
                else:
                    point = Point(voronoi.vertices[vtx_idx])
                    if not prepped_hull.contains(point):
                        exterior_region = True
                        break
                    # Keep 20% of points very close to the border
                    if random.random() < 0.2 and (
                            point.distance(hull_boundary)
                            < hull_distance_scale * 0.03):
                        exterior_region = True
                        break
        if exterior_region:
            edge_regions.add(region_idx)

    output = []

    point_region_map = voronoi.point_region
    for node_idx, node in enumerate(nodes_in_hull):
        region_idx = point_region_map[node_idx]
        if region_idx in edge_regions:
            output.append(node)

    log.info("There are %i nodes after pruning", len(output))

    if draw is not None:
        log.info("Drawing prune plot")
        fig = plt.figure(figsize=(20, 20))
        voronoi_plot_2d(voronoi)
        plt.plot(
            [x.lon for x in output],
            [x.lat for x in output],
            'x', color='red', hold=1)
        plt.plot(
            [x.lon for x in nodes_outside_hull],
            [x.lat for x in nodes_outside_hull],
            'D', color='orange', hold=1)
        plt.gca().add_patch(PolygonPatch(hull, alpha=0.2))
        plt.savefig(draw)
        del fig

    return output
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from scipy.spatial import Voronoi, voronoi_plot_2d
from scipy.spatial import Delaunay, delaunay_plot_2d


#%% Delaunay and Voronoi
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
np.random.seed(3)
x, y = np.mgrid[0:1:10j, 0:1:10j]
x[:, 1::2] = x[:, 1::2] + 0.05
x.shape = (100, 1)
y.shape = (100, 1)
pts = np.hstack([x, y]) + 0.02*np.random.normal(size=(100, 2))
vor = Voronoi(pts)
voronoi_plot_2d(vor, ax=ax)
tri = Delaunay(pts)
delaunay_plot_2d(tri, ax=ax)
scal = 0.9
for triang in tri.simplices:
    A = triang[0]
    B = triang[1]
    C = triang[2]
    vertices = np.array([pts[A], pts[B], pts[C]])
    centroid, semi_minor, semi_major, ang = steiner_inellipse(vertices)
    ellipse = Ellipse(centroid, 2*scal*semi_major, 2*scal*semi_minor,
                      angle=ang, facecolor="red", alpha=0.4)
    ax.add_artist(ellipse)

plt.show()
Ejemplo n.º 25
0
# Point process parameters
lambda0 = 10
# intensity (ie mean density) of the Poisson process

# Simulate a Poisson point process
numbPoints = np.random.poisson(lambda0 * areaTotal)
# Poisson number of points
xx = xDelta * np.random.uniform(0, 1, numbPoints) + xMin
# x coordinates of Poisson points
yy = yDelta * np.random.uniform(0, 1, numbPoints) + yMin
# y coordinates of Poisson points

xxyy = np.stack((xx, yy), axis=1)
#combine x and y coordinates
##Perform Voroin tesseslation using built-in function
voronoiData = Voronoi(xxyy)
vertexAll = voronoiData.vertices
#retrieve x/y coordinates of all vertices
cellAll = voronoiData.regions
#may contain empty array/set

####START -- Plotting section -- START###
#create voronoi diagram on the point pattern
voronoi_plot_2d(voronoiData, show_points=False, show_vertices=False)
#plot underlying point pattern (ie a realization of a Poisson point process)
plt.scatter(xx, yy, edgecolor='b', facecolor='b')
#number the points
for ii in range(numbPoints):
    plt.text(xx[ii] + xDelta / 50, yy[ii] + yDelta / 50, ii)

####END -- Plotting section -- END###
Ejemplo n.º 26
0
    def create_links_and_faces_from_voronoi_diagram(vor):
        """
        From a Voronoi diagram object created by scipy.spatial.Voronoi(),
        builds and returns:
        1. Arrays of link "from" and "to" nodes
        2. Array of link IDs for each active link
        3. Array containing with of each face
        
        Parameters
        ----------
        vor : scipy.spatial.Voronoi
            Voronoi object initialized with the grid nodes.

        Returns
        -------
        out : tuple of ndarrays
            - link_fromnode = "from" node for each link (len=num_links)
            - link_tonode   = "to" node for each link (len=num_links)
            - active_links  = link ID for each active link (len=num_active_links)
            - face_width    = width of each face (len=num_active_links

        Examples
        --------
        >>> import numpy as np
        >>> from landlab.grid import VoronoiDelaunayGrid
        >>> pts = np.array([[ 0., 0.],[  1., 0.],[  1.5, 0.87],[-0.5, 0.87],[ 0.5, 0.87],[  0., 1.73],[  1., 1.73]])
        >>> from scipy.spatial import Voronoi
        >>> vor = Voronoi(pts)
        >>> [fr,to,al,fw] = VoronoiDelaunayGrid.create_links_and_faces_from_voronoi_diagram(vor)
        >>> fr
        array([0, 0, 0, 1, 1, 3, 3, 6, 6, 6, 4, 4])
        >>> to
        array([3, 1, 4, 2, 4, 4, 5, 4, 2, 5, 2, 5])
        >>> al
        array([ 2,  4,  5,  7, 10, 11])
        >>> fw
        array([ 0.57669199,  0.57669199,  0.575973  ,  0.57836419,  0.575973  ,
                0.57836419])
        """
        # Each Voronoi "ridge" corresponds to a link. The Voronoi object has an
        # attribute ridge_points that contains the IDs of the nodes on either
        # side (including ridges that have one of their endpoints undefined).
        # So, we set the number of links equal to the number of ridges.
        num_links = len(vor.ridge_points)
        
        # Create the arrays for link from and to nodes
        link_fromnode = -numpy.ones(num_links, dtype=int)
        link_tonode = -numpy.ones(num_links, dtype=int)
        
        # Ridges along the perimeter of the grid will have one of their 
        # endpoints undefined. The endpoints of each ridge are contained in
        # vor.ridge_vertices, and an undefined vertex is flagged with -1.
        # Ridges with both vertices defined correspond to faces and active 
        # links, while ridges with an undefined vertex correspond to inactive
        # links. So, to find the number of active links, we subtract from the
        # total number of links the number of occurrences of an undefined
        # vertex.
        num_active_links = num_links \
                    - numpy.count_nonzero(numpy.array(vor.ridge_vertices)==-1)
        
        # Create arrays for active links and width of faces (which are Voronoi
        # ridges).
        active_links = -numpy.ones(num_active_links, dtype=int)
        face_width = -numpy.ones(num_active_links)
    
        # Loop through the list of ridges. For each ridge, there is a link, and
        # its "from" and "to" nodes are the associated "points". In addition, if
        # the ridge endpoints are defined, we have a face and an active link,
        # so we add them to our arrays as well.
        j = 0
        for i in range(num_links):
            link_fromnode[i] = vor.ridge_points[i,0]
            link_tonode[i] = vor.ridge_points[i,1]
            face_corner1 = vor.ridge_vertices[i][0]
            face_corner2 = vor.ridge_vertices[i][1]
            if VoronoiDelaunayGrid.is_valid_voronoi_ridge(vor, i):  # means it's a valid face
                dx = vor.vertices[face_corner2,0]-vor.vertices[face_corner1,0]
                dy = vor.vertices[face_corner2,1]-vor.vertices[face_corner1,1]
                face_width[j] = numpy.sqrt(dx*dx+dy*dy)
                if abs(face_width[j])>=40000.0:
                    six.print_('link ' + i + ' from ' + link_fromnode[i] +
                               ' to ' + link_tonode[i] + ' has face width ' +
                               face_width[j])
                    six.print_(vor.ridge_vertices[i])
                    six.print_(vor.vertices[vor.ridge_vertices[i]])

                    from scipy.spatial import voronoi_plot_2d
                    voronoi_plot_2d(vor)
                assert face_width[j] < 40000., 'face width must be less than earth circumference!'
                active_links[j] = i
                j += 1
        
        #save the data
        #self.node_at_link_tail = link_fromnode
        #self.node_at_link_head = link_tonode
        #self.active_link_ids = active_links
        #self._face_widths = face_width
        #self._num_faces = face_width.size
        #self._num_active_links = active_links.size
        
        return link_fromnode, link_tonode, active_links, face_width
Ejemplo n.º 27
0
points = np.random.rand(111, 2)
print(points)
for k in range(111):
    points[k][0]=output['lat'][k]
    points[k][1]=output['lon'][k]

print(points)

#points = np.random.rand(15, 2)
#print points
# compute Voronoi tesselation
vor = Voronoi(points)
print(vor)
# plot
regions, vertices = voronoi_plot_2d(vor)
# print "--"
# print regions
# print "--"
# print vertices

# colorize
for region in regions:
    polygon = vertices[region]
    plt.fill(*zip(*polygon), alpha=0.6)

plt.plot(points[:,0], points[:,1], 'ko',markersize=2)
plt.xlim(vor.min_bound[0] - 0.1, vor.max_bound[0] + 0.1)
plt.ylim(vor.min_bound[1] - 0.1, vor.max_bound[1] + 0.1)

plt.show()
Ejemplo n.º 28
0
    def draw_kmeans_clusters(self, filename, figsize=(4,3)):
        import matplotlib as mpl
        mpl.use('Agg')
        import matplotlib.patches as mpatches
        import matplotlib.pyplot as plt
        from sklearn.cluster import KMeans
        from scipy.spatial import Voronoi, voronoi_plot_2d
        from mpl_toolkits.basemap import Basemap, cm, maskoceans
        #from matplotlib import style
        #import seaborn as sns
        #sns.set_style("white")
        #plt.rc('text', usetex=True)
        #plt.rc('font', family='serif')
        #plt.rcParams['axes.facecolor']='white'
        fig = plt.figure(figsize=figsize)
        lllat = 24.396308
        lllon = -124.848974
        urlat =  49.384358
        urlon = -66.885444
        m = Basemap(llcrnrlat=lllat,
        urcrnrlat=urlat,
        llcrnrlon=lllon,
        urcrnrlon=urlon,
        resolution='c', projection='cyl')
        m.drawmapboundary(fill_color = 'white')
        m.drawcoastlines(linewidth=0.2)
        m.drawcountries(linewidth=0.2)
        
        ax = plt.gca()
        ax.xaxis.set_visible(False) 
        ax.yaxis.set_visible(False) 
        for spine in ax.spines.itervalues(): 
            spine.set_visible(False) 

        #fig = plt.figure()  # figsize=(4,4.2)

        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.spines['left'].set_visible(False)
        train_locs = self.df_train[['lat', 'lon']].values
        n_clusters = int(np.ceil(train_locs.shape[0] / self.bucket_size)) 
        n_clusters = 128
        logging.info('n_cluster %d' %n_clusters)
        clusterer = KMeans(n_clusters=n_clusters, n_jobs=10)
        clusterer.fit(train_locs)
        centroids = clusterer.cluster_centers_
        centroids[:,[0, 1]] = centroids[:,[1, 0]]
        mlon, mlat = m(*(centroids[:,0], centroids[:,1]))
        centroids = np.transpose(np.vstack((mlon, mlat)))
        
        vor = Voronoi(centroids)
        
        
        #ax.set_xlim([-125, -60])  # pylab.xlim([-400, 400])
        #ax.set_ylim([25, 50])

        plt.setp(ax.get_yticklabels(), visible=False)
        plt.setp(ax.get_xticklabels(), visible=False)
        ax.yaxis.set_tick_params(size=0)
        ax.xaxis.set_tick_params(size=0)
        #plt.tick_params(axis='both', which='major', labelsize=25)
        #ax.labelsize = '25'
        #plt.subplots_adjust(bottom=0.2)
        voronoi_plot_2d(vor, show_points=False, show_vertices=False, ax=ax, line_width=0.7)
        m.drawlsmask(land_color='lightgray',ocean_color="#b0c4de", lakes=True)
        plt.tight_layout()
        plt.savefig(filename)
        #plt.close()
        print("the plot saved in " + filename) 
Ejemplo n.º 29
0
def _imshow_grid_values(grid, values, plot_name=None, var_name=None,
                        var_units=None, grid_units=(None, None),
                        symmetric_cbar=False, cmap='pink', limits=None,
                        colorbar_label = None, 
                        allow_colorbar=True, vmin=None, vmax=None,
                        norm=None, shrink=1., color_for_closed='black',
                        color_for_background=None, show_elements=False,
                        output=None):

    gridtypes = inspect.getmro(grid.__class__)

    cmap = plt.get_cmap(cmap)
    if color_for_closed is not None:
        cmap.set_bad(color=color_for_closed)
    else:
        cmap.set_bad(alpha=0.)

    if isinstance(grid, RasterModelGrid):
        if values.ndim != 2:
            raise ValueError('values must have ndim == 2')

        y = np.arange(values.shape[0] + 1) * grid.dy - grid.dy * .5
        x = np.arange(values.shape[1] + 1) * grid.dx - grid.dx * .5

        kwds = dict(cmap=cmap)
        (kwds['vmin'], kwds['vmax']) = (values.min(), values.max())
        if (limits is None) and ((vmin is None) and (vmax is None)):
            if symmetric_cbar:
                (var_min, var_max) = (values.min(), values.max())
                limit = max(abs(var_min), abs(var_max))
                (kwds['vmin'], kwds['vmax']) = (- limit, limit)
        elif limits is not None:
            (kwds['vmin'], kwds['vmax']) = (limits[0], limits[1])
        else:
            if vmin is not None:
                kwds['vmin'] = vmin
            if vmax is not None:
                kwds['vmax'] = vmax

        if np.isclose(grid.dx, grid.dy):
            if values.size == grid.number_of_nodes:
                myimage = plt.imshow(
                    values.reshape(grid.shape), origin='lower',
                    extent=(x[0], x[-1], y[0], y[-1]), **kwds)
            else:  # this is a cell grid, and has been reshaped already...
                myimage = plt.imshow(values, origin='lower',
                                     extent=(x[0], x[-1], y[0], y[-1]), **kwds)
        myimage = plt.pcolormesh(x, y, values, **kwds)

        plt.gca().set_aspect(1.)
        plt.autoscale(tight=True)

        if allow_colorbar:
            cb = plt.colorbar(norm=norm, shrink=shrink)
            if colorbar_label:
                cb.set_label(colorbar_label)
    elif VoronoiDelaunayGrid in gridtypes:
        # This is still very much ad-hoc, and needs prettifying.
        # We should save the modifications needed to plot color all the way
        # to the diagram edge *into* the grid, for faster plotting.
        # (see http://stackoverflow.com/questions/20515554/...
        # colorize-voronoi-diagram)
        # (This technique is not implemented yet)
        from scipy.spatial import voronoi_plot_2d
        import matplotlib.colors as colors
        import matplotlib.cm as cmx
        cm = plt.get_cmap(cmap)

        if (limits is None) and ((vmin is None) and (vmax is None)):
            # only want to work with NOT CLOSED nodes
            open_nodes = grid.status_at_node != 4
            if symmetric_cbar:
                (var_min, var_max) = (values.flat[
                    open_nodes].min(), values.flat[open_nodes].max())
                limit = max(abs(var_min), abs(var_max))
                (vmin, vmax) = (- limit, limit)
            else:
                (vmin, vmax) = (values.flat[
                    open_nodes].min(), values.flat[open_nodes].max())
        elif limits is not None:
            (vmin, vmax) = (limits[0], limits[1])
        else:
            open_nodes = grid.status_at_node != 4
            if vmin is None:
                vmin = values.flat[open_nodes].min()
            if vmax is None:
                vmax = values.flat[open_nodes].max()

        cNorm = colors.Normalize(vmin, vmax)
        scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
        colorVal = scalarMap.to_rgba(values)

        if show_elements:
            myimage = voronoi_plot_2d(grid.vor, show_vertices=False,
                                      show_points=False)
        # show_points to be supported in scipy0.18, but harmless for now
        mycolors = (i for i in colorVal)
        for order in grid.vor.point_region:
            region = grid.vor.regions[order]
            colortouse = next(mycolors)
            if -1 not in region:
                polygon = [grid.vor.vertices[i] for i in region]
                plt.fill(*zip(*polygon), color=colortouse)

        plt.gca().set_aspect(1.)
        # plt.autoscale(tight=True)
        # Tempting though it is to move the boundary outboard of the outermost
        # nodes (e.g., to the outermost corners), this is a bad idea, as the
        # outermost cells tend to have highly elongated shapes which make the
        # plot look stupid
        plt.xlim((np.min(grid.node_x), np.max(grid.node_x)))
        plt.ylim((np.min(grid.node_y), np.max(grid.node_y)))

        scalarMap.set_array(values)
        if allow_colorbar:
            cb = plt.colorbar(scalarMap, shrink=shrink)

    if grid_units[1] is None and grid_units[0] is None:
        grid_units = grid.axis_units
        if grid_units[1] == '-' and grid_units[0] == '-':
            plt.xlabel('X')
            plt.ylabel('Y')
        else:
            plt.xlabel('X (%s)' % grid_units[1])
            plt.ylabel('Y (%s)' % grid_units[0])
    else:
        plt.xlabel('X (%s)' % grid_units[1])
        plt.ylabel('Y (%s)' % grid_units[0])

    if plot_name is not None:
        plt.title('%s' % (plot_name))

    if var_name is not None or var_units is not None:
        if var_name is not None:
            assert type(var_name) is str
            if var_units is not None:
                assert type(var_units) is str
                colorbar_label = var_name + ' (' + var_units + ')'
            else:
                colorbar_label = var_name
        else:
            assert type(var_units) is str
            colorbar_label = '(' + var_units + ')'
        assert type(colorbar_label) is str
        assert allow_colorbar
        cb.set_label(colorbar_label)

    if color_for_background is not None:
        plt.gca().set_axis_bgcolor(color_for_background)

    if output is not None:
        if type(output) is str:
            plt.savefig(output)
            plt.clf()
        elif output:
            plt.show()
Ejemplo n.º 30
0
import numpy as np
from scipy.spatial import Voronoi, voronoi_plot_2d
import matplotlib.pyplot as plt
from numpy.random import rand



points = np.array([[0,0], [0,2], [2,2]])
#points = rand(10).reshape((5,2))
'''
points = np.array(
        [[ 0.22403616,  0.39571284],
         [ 0.85056796,  0.34780449],
          [ 0.36541502,  0.30568376],
           [ 0.38902664,  0.80566618],
            [ 0.66418705,  0.08285052]])
'''

vor = Voronoi(points)
print 'points\n', vor.points
print 'vertices\n', vor.vertices
print 'ridge_points\n', vor.ridge_points
print 'ridge_vertices\n', vor.ridge_vertices
print 'regions\n', vor.regions
print 'point_region\n', vor.point_region


voronoi_plot_2d(vor)
plt.show()
Ejemplo n.º 31
0
import numpy as np
from scipy.spatial import Voronoi, voronoi_plot_2d
from numpy.random import uniform
from matplotlib import pyplot as plt

p = uniform(0, 5, (20,2))
vor = Voronoi(p)
voronoi_plot_2d(vor); plt.axes().set_aspect('equal'); plt.show()
Ejemplo n.º 32
0
def get_skeleton_from_outline(outline):
    fig, ax = plt.subplots()
    vor = Voronoi(outline)
    if vor.points.shape[1] != 2:
        raise ValueError("Voronoi diagram is not 2-D")

    points=outline
    plt.scatter(points[:,0],points[:,1],c='g')
    edges_x11=[]
    edges_y11=[]
    #plt.scatter(vor.vertices[:,0],vor.vertices[:,1],c='r')
    for vpair in vor.ridge_vertices:
        if -1 in vpair:
            continue
        v0=vor.vertices[vpair[0]]
        v1=vor.vertices[vpair[1]]  
        if not is_point_inside_polygon(v0[0],v0[1],outline):
            continue
        if not is_point_inside_polygon(v1[0],v1[1],outline):
            continue
        #plt.plot([v0[0],v1[0]],[v0[1],v1[1]])
        edges_x11.append(v0)
        edges_y11.append(v1)

    edges_x1=np.array(edges_x11)
    edges_y1=np.array(edges_y11)

    #detect branch
    [edges_x3,edges_y3]=remove_branches(edges_x1,edges_y1)
    print "edgesx3"
    print edges_x3
    for i in range(len(edges_x3)):
        plt.plot([edges_x3[i][0],edges_y3[i][0]],[edges_x3[i][1],edges_y3[i][1]])
    plt.show()
    
    sys.exit()
    
    voronoi_plot_2d(vor)
    plt.show()
    sys.exit()
    edges_x=[]
    edges_y=[]
    for vpair in vor.ridge_vertices:
        if vpair[0] >= 0  and vpair[1] >= 0:
            v0=vor.vertices[vpair[0]]
            v1=vor.vertices[vpair[1]]
            edges_x.append([v0[0],v1[0]])
            edges_y.append([v1[0],v1[1]])
            #ax.plot([v0[0], v1[0]], [v0[1], v1[1]], 'k', linewidth=2)
    #ax.scatter(outline[:,0],outline[:,1])
    #ax.scatter(edges_x,edges_y)
    #plt.show()
    #sys.exit()
    #print "number of edges",len(edges_x)
    #print "First edge:",edges_x[0],edges_y[0]
    #sys.exit()
    # remove vertices crossing the boundary
    print "len edges_x",len(edges_x)
        
    ptp_bound = vor.points.ptp(axis=0)
    center = vor.points.mean(axis=0)
    print "center",center
    sys.exit()
    #https://docs.scipy.org/doc/scipy-0.12.0/reference/tutorial/spatial.html
    ind=-1
    for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices):
        simplex = np.asarray(simplex)
        ind=ind+1
        if np.any(simplex < 0):
            i = simplex[simplex >= 0][0]  # finite end Voronoi vertex

            t = vor.points[pointidx[1]] - vor.points[pointidx[0]]  # tangent
            t /= np.linalg.norm(t)
            n = np.array([-t[1], t[0]])  # normal

            midpoint = vor.points[pointidx].mean(axis=0)
            direction = np.sign(np.dot(midpoint - center, n)) * n
            far_point = vor.vertices[i] + direction * ptp_bound.max()
            edges_x.append([vor.vertices[i,0], far_point[0]])
            edges_y.append([vor.vertices[i,1], far_point[1]])
            
    edges_x1=[]
    edges_y1=[]
    for i in range(len(edges_x)):
        if point_inside_polygon(edges_x[i][0],edges_y[i][0],outline) and point_inside_polygon(edges_x[i][1],edges_y[i][1],outline):
            edges_x1.append(edges_x[i])
            edges_y1.append(edges_y[i])
    edges_x1=np.array(edges_x1)
    edges_y1=np.array(edges_y1)

    #detect branch
    delta=0.0001
    edges_x2=[];
    edges_y2=[];
    while True:
        for i in range(len(edges_x1)):
            p1=np.sum((abs(edges_x1-edges_x1[i][0])<delta) & (abs(edges_y1-edges_y1[i][0])<delta))>1
            p2=np.sum((abs(edges_x1-edges_x1[i][1])<delta) & (abs(edges_y1-edges_y1[i][1])<delta))>1
            if p1 and p2:
                edges_x2.append([edges_x1[i][0],edges_x1[i][1]])
                edges_y2.append([edges_y1[i][0],edges_y1[i][1]])
        if (len(edges_x1)-len(edges_x2))<=2:
            edges_x3=np.array(edges_x2)
            edges_y3=np.array(edges_y2)
            break
        else:
            edges_x1 = np.array(edges_x2)
            edges_y1 = np.array(edges_y2)
            edges_x2=[];
            edges_y2=[];
    edges_x3=np.array(edges_x1)
    edges_y3=np.array(edges_y1)


    #TODO - missing removing cycles
    edges_x=edges_x3
    edges_y=edges_y3

    #sort the points
    vx2=[]
    vy2=[]


    colorline(edges_x,edges_y)
    adjust_bounds(ax, outline)
    plt.show()

    for i in range(len(edges_x2)): #find the first point
        if np.sum(np.sum((abs(edges_x-edges_x[i][0])<delta) & (abs(edges_y-edges_y[i][0])<delta)))==1:
            vx2=edges_x[i]
            vy2=edges_y[i]
            break
        elif np.sum(np.sum((abs(edges_x-edges_x[i][1])<delta) & (abs(edges_y-edges_y[i][1])<delta)))==1:
            vx2=np.fliplr(edges_x[i])
            vy2=np.fliplr(edges_x[i])
            break
    k=1


    
    '''
    FIND THE ERROR HERE:File "utils.py", line 119, in get_skeleton_from_outline
    f1=np.where((abs(edges_x[:,0]-vx2[k])<delta) & (abs(edges_y[:,0]-vy2[k])<delta) & ((abs(edges_x[:,1]-vx2[k-1])>=delta) | (abs(edges_y[:,1]-vy2[k-1])>    =delta)))
    IndexError: too many indices for array
    compare to test.py

    Things left:
    I know how to segment
    get the polygon
    find the outline
    find the skeleton
    find the mesh
    now i need to find how to get a slice of the mesh and sum all pixels there
    '''



    
    
   
    while True: # in this cycle sort all points after the first one
        f1=np.where((abs(edges_x[:,0]-vx2[k])<delta) & (abs(edges_y[:,0]-vy2[k])<delta) & ((abs(edges_x[:,1]-vx2[k-1])>=delta) | (abs(edges_y[:,1]-vy2[k-1])>=delta)))
        f2=np.where((abs(edges_x[:,1]-vx2[k])<delta) & (abs(edges_y[:,1]-vy2[k])<delta) & ((abs(edges_x[:,0]-vx2[k-1])>=delta) | (abs(edges_y[:,0]-vy2[k-1])>=delta)))
        if len(f1[0])>0:
            vx2=np.append(vx2,edges_x[f1[0],1])
            vy2=np.append(vy2,edges_y[f1[0],1])
        elif len(f2[0])>0:
            vx2=np.append(vx2,edges_x[f2[0],0])
            vy2=np.append(vy2,edges_y[f2[0],0])
        else:
            break
        k=k+1

    stp=1
    skel=np.zeros([len(vx2),2])
    skel_diff=np.zeros([len(vx2)-1,2])
    skel[0,0]=vx2[0]
    skel[0,1]=vy2[0]
    for i in range(1,len(vx2)):
        skel[i,0]=vx2[i]
        skel[i,1]=vy2[i]
        skel_diff[i-1,0]=vx2[i]-vx2[i-1]
        skel_diff[i-1,1]=vy2[i]-vy2[i-1]
    #interpolate skeleton to equal step, extend outside of the cell and smooth
    l=np.cumsum(np.append(0,np.sum(skel_diff*skel_diff,1)))

    skelx_interp = np.interp(np.linspace(0,l[-1],l[-1]/stp),l,vx2)
    skely_interp = np.interp(np.linspace(0,l[-1],l[-1]/stp),l,vy2)

    skel_interp=np.zeros([len(skelx_interp),2])
    
    for i in range(len(skelx_interp)):
        skel_interp[i,0]=skelx_interp[i]
        skel_interp[i,1]=skely_interp[i]

    colorline(vx2,vy2)
    colorline(skelx_interp,skely_interp)
    adjust_bounds(ax, points)
    plt.show()
   
    lng0 = l[-1]
    lng=15
    sz = lng0/stp
    coord = np.append(points,points[0])
    coord=coord.reshape(len(points)+1,2)
    skel2 = np.append(np.append(skel_interp[0]*(lng/stp+1) - skel_interp[1]*lng/stp,skel_interp),skel_interp[-1]*(lng/stp+1) - skel_interp[-2]*lng/stp)
    skel2=skel2.reshape(2+len(skel_interp),2)

    skel2_diff=np.zeros([len(skel2[:,0])-1,2])
    for i in range(1,len(skel2[:,0])):
        skel2_diff[i-1,0]=skel2[i,0]-skel2[i-1,0]
        skel2_diff[i-1,1]=skel2[i,1]-skel2[i-1,1]
    l=np.cumsum(np.append(0,np.sum(skel2_diff*skel2_diff,1)))
    l,i = np.unique(l,return_index=True);
    skel2 = skel2[i,:];

    L=80
    [tmp1,tmp2,indS,indC]=skeleton_to_mesh.intxyMulti(skel2[2:,0],skel2[2:,1],coord[:,0],coord[:,1])
    aa=np.array([min(skeleton_to_mesh.modL(indC,1)),min(skeleton_to_mesh.modL(indC,L/2+1))])
    tmp1=aa.argmin()
    prevpoint=aa[tmp1]
    if prevpoint==1:
        prevpoint=L/2
    lng=15
    return skel
Ejemplo n.º 33
0
#!/Users/simurgh/anaconda/bin/python
import json
import os

import matplotlib.pyplot as plt
from scipy.spatial import Voronoi, voronoi_plot_2d
import numpy as np

import mplleaflet

# Load up the geojson data
filename = ('probes.geojson')
with open(filename) as f:
    gj = json.load(f)

# Grab the coordinates (longitude, latitude) from the features, which we
# know are Points
xy = np.array([feat['geometry']['coordinates'] for feat in gj['features']])

#plt.hold(True)
# Plot the ixp as red dots
#plot(xy[:,0], xy[:,1], 'rx')

vor_polygon = Voronoi(xy)
voronoi_plot_2d(vor_polygon, show_vertices=False)

mapfile = 'probe-voronoi-cells.html'
# Create the map. Save the file to html
mplleaflet.show(path=mapfile)
Ejemplo n.º 34
0
 def show(self):
     voronoi_plot_2d(self)
Ejemplo n.º 35
0
 def plot_cells_2d(self):
     voronoi_plot_2d(self.vor)
Ejemplo n.º 36
0
	#ax1.triplot(cmy,cmx,tri.simplices.copy())
	ax2.scatter(cmy,cmx,s=rga,c=aratio,alpha = 0.6)
ax2.set_xlim([0,len_lum[1]])
ax2.set_ylim([0,len_lum[0]])
ax2.invert_yaxis()
ax2.set_aspect('equal',adjustable='box')

ax3.set_title('Connectivity')
if len(cmx) > 0:
	ax3.triplot(cmy,cmx,tri.simplices.copy())
ax3.set_xlim([0,len_lum[1]])
ax3.set_ylim([0,len_lum[0]])
ax3.invert_yaxis()
ax3.set_aspect('equal',adjustable='box')

ax4.set_title('Voronoi')
if len(cmx) > 0:
	voronoi_plot_2d(vor,ax4)
ax4.set_xlim([0,len_lum[1]])
ax4.set_ylim([0,len_lum[0]])
ax4.invert_yaxis()
ax4.set_aspect('equal',adjustable='box')


plt.tight_layout()
#plt.show()
new_file_name = "voronoi_cluster_cutoff_"+ str(cutoff) +"_"+magfile
out_file = os.path.join(directory,new_file_name) 
fig.savefig(out_file,dpi=300)