def processAlgorithm(self, progress): layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT)) buf = self.getParameterValue(self.BUFFER) writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( layer.pendingFields().toList(), QGis.WKBPolygon, layer.crs()) inFeat = QgsFeature() outFeat = QgsFeature() extent = layer.extent() extraX = extent.height() * (buf / 100.0) extraY = extent.width() * (buf / 100.0) height = extent.height() width = extent.width() c = voronoi.Context() pts = [] ptDict = {} ptNdx = -1 features = vector.features(layer) for inFeat in features: geom = QgsGeometry(inFeat.geometry()) point = geom.asPoint() x = point.x() - extent.xMinimum() y = point.y() - extent.yMinimum() pts.append((x, y)) ptNdx += 1 ptDict[ptNdx] = inFeat.id() if len(pts) < 3: raise GeoAlgorithmExecutionException( self.tr('Input file should contain at least 3 points. Choose ' 'another file and try again.')) uniqueSet = Set(item for item in pts) ids = [pts.index(item) for item in uniqueSet] sl = voronoi.SiteList([voronoi.Site(i[0], i[1], sitenum=j) for (j, i) in enumerate(uniqueSet)]) voronoi.voronoi(sl, c) inFeat = QgsFeature() current = 0 total = 100.0 / float(len(c.polygons)) for (site, edges) in c.polygons.iteritems(): request = QgsFeatureRequest().setFilterFid(ptDict[ids[site]]) inFeat = layer.getFeatures(request).next() lines = self.clip_voronoi(edges, c, width, height, extent, extraX, extraY) geom = QgsGeometry.fromMultiPoint(lines) geom = QgsGeometry(geom.convexHull()) outFeat.setGeometry(geom) outFeat.setAttributes(inFeat.attributes()) writer.addFeature(outFeat) current += 1 progress.setPercentage(int(current * total)) del writer
def delaunay_triangulation(self): import voronoi from sets import Set vprovider = self.vlayer.dataProvider() allAttrs = vprovider.attributeIndexes() vprovider.select(allAttrs) fields = { 0: QgsField("POINTA", QVariant.Double), 1: QgsField("POINTB", QVariant.Double), 2: QgsField("POINTC", QVariant.Double) } writer = QgsVectorFileWriter(self.myName, self.myEncoding, fields, QGis.WKBPolygon, vprovider.crs()) inFeat = QgsFeature() c = voronoi.Context() pts = [] ptDict = {} ptNdx = -1 while vprovider.nextFeature(inFeat): geom = QgsGeometry(inFeat.geometry()) point = geom.asPoint() x = point.x() y = point.y() pts.append((x, y)) ptNdx += 1 ptDict[ptNdx] = inFeat.id() if len(pts) < 3: return False uniqueSet = Set(item for item in pts) ids = [pts.index(item) for item in uniqueSet] sl = voronoi.SiteList([voronoi.Site(*i) for i in uniqueSet]) c.triangulate = True voronoi.voronoi(sl, c) triangles = c.triangles feat = QgsFeature() nFeat = len(triangles) nElement = 0 self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0) self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, nFeat)) for triangle in triangles: indicies = list(triangle) indicies.append(indicies[0]) polygon = [] step = 0 for index in indicies: vprovider.featureAtId(ptDict[ids[index]], inFeat, True, allAttrs) geom = QgsGeometry(inFeat.geometry()) point = QgsPoint(geom.asPoint()) polygon.append(point) if step <= 3: feat.addAttribute(step, QVariant(ids[index])) step += 1 geometry = QgsGeometry().fromPolygon([polygon]) feat.setGeometry(geometry) writer.addFeature(feat) nElement += 1 self.emit(SIGNAL("runStatus(PyQt_PyObject)"), nElement) del writer return True
def delaunay_triangulation( self ): import voronoi from sets import Set vprovider = self.vlayer.dataProvider() fields = QgsFields() fields.append( QgsField( "POINTA", QVariant.Double ) ) fields.append( QgsField( "POINTB", QVariant.Double ) ) fields.append( QgsField( "POINTC", QVariant.Double ) ) writer = QgsVectorFileWriter( self.myName, self.myEncoding, fields, QGis.WKBPolygon, vprovider.crs() ) inFeat = QgsFeature() c = voronoi.Context() pts = [] ptDict = {} ptNdx = -1 fit = vprovider.getFeatures() while fit.nextFeature( inFeat ): geom = QgsGeometry( inFeat.geometry() ) point = geom.asPoint() x = point.x() y = point.y() pts.append( ( x, y ) ) ptNdx +=1 ptDict[ptNdx] = inFeat.id() if len(pts) < 3: return False uniqueSet = Set( item for item in pts ) ids = [ pts.index( item ) for item in uniqueSet ] sl = voronoi.SiteList( [ voronoi.Site( *i ) for i in uniqueSet ] ) c.triangulate = True voronoi.voronoi( sl, c ) triangles = c.triangles feat = QgsFeature() nFeat = len( triangles ) nElement = 0 self.emit( SIGNAL( "runStatus( PyQt_PyObject )" ), 0 ) self.emit( SIGNAL( "runRange( PyQt_PyObject )" ), ( 0, nFeat ) ) for triangle in triangles: indicies = list( triangle ) indicies.append( indicies[ 0 ] ) polygon = [] step = 0 for index in indicies: vprovider.getFeatures( QgsFeatureRequest().setFilterFid( ptDict[ ids[ index ] ] ) ).nextFeature( inFeat ) geom = QgsGeometry( inFeat.geometry() ) point = QgsPoint( geom.asPoint() ) polygon.append( point ) if step <= 3: feat.setAttribute( step, QVariant( ids[ index ] ) ) step += 1 geometry = QgsGeometry().fromPolygon( [ polygon ] ) feat.setGeometry( geometry ) writer.addFeature( feat ) nElement += 1 self.emit( SIGNAL( "runStatus( PyQt_PyObject )" ), nElement ) del writer return True
def processAlgorithm(self, progress): vlayer = QGisLayers.getObjectFromUri( self.getParameterValue(Delaunay.INPUT)) vprovider = vlayer.dataProvider() allAttrs = vprovider.attributeIndexes() vprovider.select(allAttrs) fields = { 0: QgsField("POINTA", QVariant.Double), 1: QgsField("POINTB", QVariant.Double), 2: QgsField("POINTC", QVariant.Double) } writer = self.getOutputFromName(Delaunay.OUTPUT).getVectorWriter( fields, QGis.WKBPolygon, vprovider.crs()) inFeat = QgsFeature() c = voronoi.Context() pts = [] ptDict = {} ptNdx = -1 while vprovider.nextFeature(inFeat): geom = QgsGeometry(inFeat.geometry()) point = geom.asPoint() x = point.x() y = point.y() pts.append((x, y)) ptNdx += 1 ptDict[ptNdx] = inFeat.id() if len(pts) < 3: return False uniqueSet = Set(item for item in pts) ids = [pts.index(item) for item in uniqueSet] sl = voronoi.SiteList([voronoi.Site(*i) for i in uniqueSet]) c.triangulate = True voronoi.voronoi(sl, c) triangles = c.triangles feat = QgsFeature() nFeat = len(triangles) nElement = 0 for triangle in triangles: indicies = list(triangle) indicies.append(indicies[0]) polygon = [] step = 0 for index in indicies: vprovider.featureAtId(ptDict[ids[index]], inFeat, True, allAttrs) geom = QgsGeometry(inFeat.geometry()) point = QgsPoint(geom.asPoint()) polygon.append(point) if step <= 3: feat.addAttribute(step, QVariant(ids[index])) step += 1 geometry = QgsGeometry().fromPolygon([polygon]) feat.setGeometry(geometry) writer.addFeature(feat) nElement += 1 progress.setPercentage(nElement / nFeat * 100) del writer
def voronoi_polygons(self): vprovider = self.vlayer.dataProvider() writer = QgsVectorFileWriter(self.myName, self.myEncoding, vprovider.fields(), QGis.WKBPolygon, vprovider.crs()) inFeat = QgsFeature() outFeat = QgsFeature() extent = self.vlayer.extent() extraX = extent.height() * (self.myParam / 100.00) extraY = extent.width() * (self.myParam / 100.00) height = extent.height() width = extent.width() c = voronoi.Context() pts = [] ptDict = {} ptNdx = -1 fit = vprovider.getFeatures() while fit.nextFeature(inFeat): geom = QgsGeometry(inFeat.geometry()) point = geom.asPoint() x = point.x() - extent.xMinimum() y = point.y() - extent.yMinimum() pts.append((x, y)) ptNdx += 1 ptDict[ptNdx] = inFeat.id() self.vlayer = None if len(pts) < 3: return False uniqueSet = Set(item for item in pts) ids = [pts.index(item) for item in uniqueSet] sl = voronoi.SiteList([ voronoi.Site(i[0], i[1], sitenum=j) for j, i in enumerate(uniqueSet) ]) voronoi.voronoi(sl, c) inFeat = QgsFeature() nFeat = len(c.polygons) nElement = 0 self.emit(SIGNAL("runStatus( PyQt_PyObject )"), 0) self.emit(SIGNAL("runRange( PyQt_PyObject )"), (0, nFeat)) for site, edges in c.polygons.iteritems(): vprovider.getFeatures(QgsFeatureRequest().setFilterFid( ptDict[ids[site]])).nextFeature(inFeat) lines = self.clip_voronoi(edges, c, width, height, extent, extraX, extraY) geom = QgsGeometry.fromMultiPoint(lines) geom = QgsGeometry(geom.convexHull()) outFeat.setGeometry(geom) outFeat.setAttributes(inFeat.attributes()) writer.addFeature(outFeat) nElement += 1 self.emit(SIGNAL("runStatus( PyQt_PyObject )"), nElement) del writer return True
def processAlgorithm(self, progress): vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(Delaunay.INPUT)) vprovider = vlayer.dataProvider() allAttrs = vprovider.attributeIndexes() vprovider.select( allAttrs ) fields = { 0 : QgsField( "POINTA", QVariant.Double ), 1 : QgsField( "POINTB", QVariant.Double ), 2 : QgsField( "POINTC", QVariant.Double ) } writer = self.getOutputFromName(Delaunay.OUTPUT).getVectorWriter(fields, QGis.WKBPolygon, vprovider.crs() ) inFeat = QgsFeature() c = voronoi.Context() pts = [] ptDict = {} ptNdx = -1 while vprovider.nextFeature(inFeat): geom = QgsGeometry(inFeat.geometry()) point = geom.asPoint() x = point.x() y = point.y() pts.append((x, y)) ptNdx +=1 ptDict[ptNdx] = inFeat.id() if len(pts) < 3: return False uniqueSet = Set(item for item in pts) ids = [pts.index(item) for item in uniqueSet] sl = voronoi.SiteList([voronoi.Site(*i) for i in uniqueSet]) c.triangulate = True voronoi.voronoi(sl, c) triangles = c.triangles feat = QgsFeature() nFeat = len( triangles ) nElement = 0 for triangle in triangles: indicies = list(triangle) indicies.append(indicies[0]) polygon = [] step = 0 for index in indicies: vprovider.featureAtId(ptDict[ids[index]], inFeat, True, allAttrs) geom = QgsGeometry(inFeat.geometry()) point = QgsPoint(geom.asPoint()) polygon.append(point) if step <= 3: feat.addAttribute(step, QVariant(ids[index])) step += 1 geometry = QgsGeometry().fromPolygon([polygon]) feat.setGeometry(geometry) writer.addFeature(feat) nElement += 1 progress.setPercentage(nElement/nFeat * 100) del writer
def voronoi_polygons( self ): vprovider = self.vlayer.dataProvider() allAttrs = vprovider.attributeIndexes() vprovider.select( allAttrs ) writer = QgsVectorFileWriter( self.myName, self.myEncoding, vprovider.fields(), QGis.WKBPolygon, vprovider.crs() ) inFeat = QgsFeature() outFeat = QgsFeature() extent = self.vlayer.extent() extraX = extent.height() * ( self.myParam / 100.00 ) extraY = extent.width() * ( self.myParam / 100.00 ) height = extent.height() width = extent.width() c = voronoi.Context() pts = [] ptDict = {} ptNdx = -1 while vprovider.nextFeature( inFeat ): geom = QgsGeometry( inFeat.geometry() ) point = geom.asPoint() x = point.x() - extent.xMinimum() y = point.y() - extent.yMinimum() pts.append( ( x, y ) ) ptNdx +=1 ptDict[ ptNdx ] = inFeat.id() self.vlayer = None if len( pts ) < 3: return False uniqueSet = Set( item for item in pts ) ids = [ pts.index( item ) for item in uniqueSet ] sl = voronoi.SiteList( [ voronoi.Site( i[ 0 ], i[ 1 ], sitenum = j ) for j, i in enumerate( uniqueSet ) ] ) voronoi.voronoi( sl, c ) inFeat = QgsFeature() nFeat = len( c.polygons ) nElement = 0 self.emit( SIGNAL( "runStatus( PyQt_PyObject )" ), 0 ) self.emit( SIGNAL( "runRange( PyQt_PyObject )" ), ( 0, nFeat ) ) for site, edges in c.polygons.iteritems(): vprovider.featureAtId( ptDict[ ids[ site ] ], inFeat, True, allAttrs ) lines = self.clip_voronoi( edges, c, width, height, extent, extraX, extraY ) geom = QgsGeometry.fromMultiPoint( lines ) geom = QgsGeometry( geom.convexHull() ) outFeat.setGeometry( geom ) outFeat.setAttributeMap( inFeat.attributeMap() ) writer.addFeature( outFeat ) nElement += 1 self.emit( SIGNAL( "runStatus( PyQt_PyObject )" ), nElement ) del writer return True
def display(network): """Display with matplotlib""" import matplotlib import matplotlib.pyplot as plt try: from voronoi import voronoi except: voronoi = None fig = plt.figure(figsize=(10,10)) axes = fig.add_subplot(1,1,1) # Draw samples x, y = samples[:,0], samples[:,1] plt.scatter(x, y, s=1.0, color='b', alpha=0.1, zorder=1) # Draw network x, y = network.nodes[...,0], network.nodes[...,1] if len(network.nodes.shape) > 2: for i in range(network.nodes.shape[0]): plt.plot (x[i,:], y[i,:], 'k', alpha=0.85, lw=1.5, zorder=2) for i in range(network.nodes.shape[1]): plt.plot (x[:,i], y[:,i], 'k', alpha=0.85, lw=1.5, zorder=2) else: plt.plot (x, y, 'k', alpha=0.85, lw=1.5, zorder=2) plt.scatter (x, y, s=50, c='w', edgecolors='k', zorder=3) if voronoi is not None: segments = voronoi(x.ravel(), y.ravel()) lines = matplotlib.collections.LineCollection(segments, color='0.65') axes.add_collection(lines) plt.axis([0,1,0,1]) plt.xticks([]), plt.yticks([]) plt.show()
def learn(network, samples, epochs=25000, sigma=(10, 0.01), lrate=(0.5,0.005)): network.learn(samples, epochs) fig = plt.figure(figsize=(10,10)) axes = fig.add_subplot(1,1,1) # Draw samples x,y = samples[:,0], samples[:,1] plt.scatter(x, y, s=1.0, color='b', alpha=0.1, zorder=1) # Draw network x,y = network.codebook[...,0], network.codebook[...,1] if len(network.codebook.shape) > 2: for i in range(network.codebook.shape[0]): plt.plot (x[i,:], y[i,:], 'k', alpha=0.85, lw=1.5, zorder=2) for i in range(network.codebook.shape[1]): plt.plot (x[:,i], y[:,i], 'k', alpha=0.85, lw=1.5, zorder=2) else: plt.plot (x, y, 'k', alpha=0.85, lw=1.5, zorder=2) plt.scatter (x, y, s=50, c='w', edgecolors='k', zorder=3) if voronoi is not None: segments = voronoi(x.ravel(),y.ravel()) lines = matplotlib.collections.LineCollection(segments, color='0.65') axes.add_collection(lines) plt.axis([0,1,0,1]) plt.xticks([]), plt.yticks([]) plt.show() time.sleep(5)
def processAlgorithm(self, progress): vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(VoronoiPolygons.INPUT)) vprovider = vlayer.dataProvider() allAttrs = vprovider.attributeIndexes() vprovider.select( allAttrs ) writer = self.getOutputFromName(VoronoiPolygons.OUTPUT).getVectorWriter(vprovider.fields(), QGis.WKBPolygon, vprovider.crs() ) inFeat = QgsFeature() outFeat = QgsFeature() extent = vlayer.extent() height = extent.height() width = extent.width() c = voronoi.Context() pts = [] ptDict = {} ptNdx = -1 while vprovider.nextFeature(inFeat): geom = QgsGeometry(inFeat.geometry()) point = geom.asPoint() x = point.x()-extent.xMinimum() y = point.y()-extent.yMinimum() pts.append((x, y)) ptNdx +=1 ptDict[ptNdx] = inFeat.id() #self.vlayer = None if len(pts) < 3: return False uniqueSet = Set(item for item in pts) ids = [pts.index(item) for item in uniqueSet] sl = voronoi.SiteList([voronoi.Site(i[0], i[1], sitenum=j) for j, i in enumerate(uniqueSet)]) voronoi.voronoi(sl, c) inFeat = QgsFeature() nFeat = len(c.polygons) nElement = 0 for site, edges in c.polygons.iteritems(): vprovider.featureAtId(ptDict[ids[site]], inFeat, True, allAttrs) lines = self.clip_voronoi(edges, c, width, height, extent, 0, 0) geom = QgsGeometry.fromMultiPoint(lines) geom = QgsGeometry(geom.convexHull()) outFeat.setGeometry(geom) outFeat.setAttributeMap(inFeat.attributeMap()) writer.addFeature(outFeat) nElement += 1 progress.setPercentage(nElement/nFeat * 100) del writer return True
def delaunay(X): """Return a Delaunay triangulation of the specified Coords. While the Coords are 3d, only the first 2 components are used. Returns a TriSurface with the Delaunay trinagulation in the x-y plane. """ from voronoi import voronoi return TriSurface(X,voronoi(X[:,:2]).triangles)
def delaunay(X): """Return a Delaunay triangulation of the specified Coords. While the Coords are 3d, only the first 2 components are used. Returns a TriSurface with the Delaunay trinagulation in the x-y plane. """ from voronoi import voronoi return TriSurface(X, voronoi(X[:, :2]).triangles)
def computeWalls(self): nodes = self.graph.nodes() # Poached from voronoi.computeVoronoiDiagram # http://stackoverflow.com/questions/9441007/how-can-i-get-a-dictionary-of-cells-from-this-voronoi-diagram-data site_list = SiteList(nodes) context = Context() voronoi(site_list, context) verts = context.vertices walls = [None for _ in context.edges] for i, v1, v2 in context.edges: path = context.bisectors[i] if all(v != -1 and not self.pointOutsideBounds(*verts[v]) for v in (v1, v2)): # edge has a vertex at either end, easy walls[i] = WallCrossing((Coords(*verts[v1]), Coords(*verts[v2])), path) continue if self.pointOutsideBounds(*verts[v1]): v1 = -1 elif self.pointOutsideBounds(*verts[v2]): v2 = -1 # apparently v1, v2 go left to right # calculate an edge point using slope = -a/b a, b, _ = context.lines[i] p0 = Coords(*verts[v1 if v1 != -1 else v2]) if self.pointOutsideBounds(*p0): continue # need to handle case where b is 0 p1 = Coords(*constrain(p0, (-a / b) if b else (-a * float('inf')), self.dims, rightward=(v1 != -1))) walls[i] = WallCrossing((p0, p1), path) wall_dict = dict() for site, edge_list in context.polygons.items(): wall_dict[nodes[site]] = [walls[i].wall for i, _, _ in edge_list if walls[i] is not None] return [wall for wall in walls if wall is not None], wall_dict
def compute(self, points): import voronoi self.mcontext = voronoi.voronoi(points) self.medges = self.buildtriforedges() self.mvertices = self.buildtriforvertices(self.medges) self.mexts = self.buildextseqsforvertices(self.mvertices) # centers = buildcentersfortri(context) self.mpolygons = self.buildpolygonsfromexts(self.mpoints, self.mexts)
def draw_voronoi(ax, X, Y): from voronoi import voronoi from matplotlib.path import Path from matplotlib.patches import PathPatch cells, triangles, circles = voronoi(X, Y) for i, cell in enumerate(cells): codes = [Path.MOVETO] \ + [Path.LINETO] * (len(cell)-2) \ + [Path.CLOSEPOLY] path = Path(cell, codes) patch = PathPatch(path, facecolor="none", edgecolor="0.5", linewidth=0.5) ax.add_patch(patch)
def compute(self,points): import voronoi self.mcontext = voronoi.voronoi(points) self.medges = self.buildtriforedges() self.mvertices = self.buildtriforvertices(self.medges) self.mexts = self.buildextseqsforvertices(self.mvertices) # centers = buildcentersfortri(context) self.mpolygons = self.buildpolygonsfromexts(self.mpoints,self.mexts)
def VoronoiLineEdges(PointsMap): Sitepts = [] pts = {} #print CurrentDate, PointsMap[PointsMap.keys()[0]] for grid, stn in PointsMap.items(): x=float(stn[0]) y=float(stn[1]) station=grid #station.extend( stn[3:]) #print x,y,station pts[ (x,y) ]=station stncounts=len(pts.keys()) #print stncounts, "points" site_points=[] for pt in pts.keys(): Sitepts.append(voronoi.Site(pt[0],pt[1])) site_points.append( (pt[0],pt[1]) ) #print "Calculating Voronoi Lattice", siteList = voronoi.SiteList(Sitepts) context = voronoi.Context() voronoi.Edge.EDGE_NUM=0 voronoi.voronoi(siteList,context) vertices=context.vertices lines=context.lines edges=context.edges triangles=context.triangles has_edge=context.has_edge return vertices, lines, edges, has_edge
def findWeightedCentroids(seeds, stepsize, sigma, heighpar, bnd, X, Y, plot): aimax = 30 ai = aimax stepsize = 10 decFactor = 0.5 print("Start finding weighted centroids") stdevs = [maxsize] sumdists = [maxsize] centroids = seeds minseeds = seeds while True: seeds = allMoveSafeTowards(seeds, centroids, stepsize, bnd) cells = voronoi(seeds, bnd) areas = poly_areas(cells) stdev = np.round(np.std(areas), 4) heights = gauss_heights(areas, heighpar) phi = init_phi(X, Y, seeds, heights, sigma) centroids = wCentroids(cells, phi, X, Y) sumdist = sumDist(seeds, centroids) # plot the result if (plot): plot_voronoi(cells, seeds, centroids, X, Y, phi) if sumdist >= min(sumdists): ai -= 1 else: ai = aimax minseeds = seeds if ai == 0: seeds = minseeds centroids = minseeds stdevs.append(min(stdevs)) sumdists.append(min(sumdists)) stepsize = decFactor * stepsize ai = aimax continue if np.array_equal(np.round(seeds, 2), np.round(centroids, 2)): break stdevs.append(stdev) sumdists.append(sumdist) return stdevs[1:]
def run(filename): with open(filename, 'r') as in_file: file = in_file.read() points = [pair.split("\t") for pair in file.split("\n")] for i in range(len(points)): points[i] = [float(points[i][0]), float(points[i][1])] points.pop() fig, ax = plt.subplots() tri = voronoi.Delaunay(points) points = tri.points v_points, v_edges = voronoi.voronoi(tri) edges = shape(tri, v_points) voronoi.plot(v_points, ax, 'y.') voronoi.plot(points, ax, 'b.') for edge in edges: voronoi.drawline(edge[0], edge[1], ax, 'r-') plt.show()
def learn(network, samples, epochs=25000, sigma=(10, 0.01), lrate=(0.5,0.005)): network.learn(samples, epochs) fig = plt.figure(figsize=(10,10)) axes = fig.add_subplot(1,1,1) # Draw samples x,y = samples[:,0], samples[:,1] plt.scatter(x, y, s=1.0, color='b', alpha=0.1, zorder=1) # Draw network x,y = network.codebook[...,0], network.codebook[...,1] plt.scatter (x, y, s=50, c='w', edgecolors='k', zorder=3) if voronoi is not None: segments = voronoi(x.ravel(),y.ravel()) lines = matplotlib.collections.LineCollection(segments, color='0.65') axes.add_collection(lines) plt.axis([0,1,0,1]) plt.xticks([]), plt.yticks([]) plt.show()
def eaStepsizeControl(seeds, sigma, heighpar, bnd, X, Y, plot): aimax = 10 ai = aimax stepsize = 10 decFactor = 0.5 minStepsize = 0.5 print("Start equalizing areas with stepsize control") stdevs = [maxsize] centroids = seeds minseeds = seeds while True: if stepsize < minStepsize: break seeds = allMoveSafeTowards(seeds, centroids, stepsize, bnd) cells = voronoi(seeds, bnd) areas = poly_areas(cells) stdev = np.round(np.std(areas), 4) heights = gauss_heights(areas, heighpar) phi = init_phi(X, Y, seeds, heights, sigma) centroids = wCentroids(cells, phi, X, Y) # plot the result if (plot): plot_voronoi(cells, seeds, centroids, X, Y, phi) if stdev >= min(stdevs): ai -= 1 else: ai = aimax minseeds = seeds if ai == 0: seeds = minseeds centroids = minseeds stdevs.append(min(stdevs)) stepsize = decFactor * stepsize ai = aimax continue stdevs.append(stdev) return stdevs[1:]
def voronoi_polygons(points): """Return series of polygons for given coordinates. """ c = voronoi(points) # For each point find triangles (vertices) of a cell point_in_triangles = defaultdict(set) for t_ind, ps in enumerate(c.triangles): for p in ps: point_in_triangles[p].add(t_ind) # Vertex connectivity graph vertex_graph = defaultdict(set) for e_ind, (_, r, l) in enumerate(c.edges): vertex_graph[r].add(l) vertex_graph[l].add(r) # Calculate cells def cell(point): if point not in point_in_triangles: return None vertices = set(point_in_triangles[point]) # copy v_cell = [vertices.pop()] # vertices.add(-1) # Simulate infinity :-) while vertices: neighbours = vertex_graph[v_cell[-1]] & vertices if not neighbours: break v_cell.append(neighbours.pop()) vertices.discard(v_cell[-1]) return v_cell # Finally, produces polygons polygons = [] for i, p in enumerate(points): vertices = [] point_cell = cell(i) for j in point_cell: vertices.append(c.vertices[j]) polygons.append(tuple(vertices)) return tuple(polygons)
def __graphData(self, figure, img, samples, labels, centers, orderedFeatures, subplot, verbose): ndim = len(orderedFeatures) if not 1 <= ndim <= 3: return clustersLabel = np.unique(labels) rgbSamples = img.reshape((-1, 3)) ax = figure.add_subplot(subplot) if ndim <= 2 else figure.add_subplot(subplot, projection="3d") for clusterLabel in clustersLabel: if verbose: print "Graph cluster {}...".format(clusterLabel) cluster = samples[labels.ravel() == clusterLabel] color = rgbSamples[labels.ravel() == clusterLabel] / 255. color[:,[0, 2]] = color[:,[2, 0]] # BGR to RGB length = cluster.shape[0] limit = 8000 if ndim == 2 else 800 limit *= 1. / ndim keep = np.random.permutation(length)[:limit] cluster = cluster[keep] color = color[keep] if ndim == 2: ax.scatter(cluster[:,0], cluster[:,1], c=color, lw=0) elif ndim == 1: ax.hist(cluster[:,0], color=color[0]) else: ax.scatter(cluster[:,0], cluster[:,1], cluster[:,2], c=color, lw=0) if ndim == 2: ax.scatter(centers[:,0], centers[:,1], c='y', marker='s', lw=1) segments = voronoi(centers) lines = matplotlib.collections.LineCollection(segments, color='k') ax.add_collection(lines) elif ndim == 3: ax.scatter(centers[:,0], centers[:,1], centers[:,2], s=80, c='y', marker='s', lw=1) ax.set_zlabel(Clusterer.getFeatureName(orderedFeatures[2])) if ndim == 1: ax.set_ylabel('Reduced samples') if 2 <= ndim <= 3: ax.set_ylabel(Clusterer.getFeatureName(orderedFeatures[1])) ax.set_xlabel(Clusterer.getFeatureName(orderedFeatures[0]))
def lloyd(seeds,stepsize, bnd, X, Y, plot): print("Start Lloyd algorithm") stdevs = [maxsize] centroids = seeds while True: seeds = allMoveSafeTowards(seeds, centroids, stepsize, bnd) cells = voronoi(seeds,bnd) areas = poly_areas(cells) centroids = uCentroids(cells) # plot the result if(plot): plot_voronoi(cells, seeds, centroids, X, Y, phi) stdev = np.round(np.std(areas),4) if np.array_equal(np.round(seeds,3),np.round(centroids,3)): break if len(stdevs) > 6 and len(set(stdevs[-6:])) < 3: break stdevs.append(stdev) return stdevs[1:]
def quantize(data, cutoff, numRegions=8, tolerance=0.0001): newData = data[::4, ::4] # Downsample data to speed up by a factor of 16 # Next remove clouds poorly represented data cleanData = newData[np.logical_and(newData > 0, newData < cutoff)] tess = voronoi(cleanData, numRegions, tolerance, data) thresh = [] for val in tess.values(): thresh.append(np.min(val)) thresh = np.sort(thresh) (rows, cols) = data.shape qData = np.ndarray((rows, cols), dtype='uint8') qData.fill(255) for val, t in enumerate(thresh): qData[data > t] = val + 1 qData[data == 0] = 0 # Put back the land values qData[data == -1] = 255 # Put back the cloud values return qData
def processAlgorithm(self, progress): layer = dataobjects.getObjectFromUri( self.getParameterValue(self.INPUT)) fields = [QgsField('POINTA', QVariant.Double, '', 24, 15), QgsField('POINTB', QVariant.Double, '', 24, 15), QgsField('POINTC', QVariant.Double, '', 24, 15)] writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields, QGis.WKBPolygon, layer.crs()) pts = [] ptDict = {} ptNdx = -1 c = voronoi.Context() features = vector.features(layer) total = 100.0 / len(features) for current, inFeat in enumerate(features): geom = QgsGeometry(inFeat.geometry()) point = geom.asPoint() x = point.x() y = point.y() pts.append((x, y)) ptNdx += 1 ptDict[ptNdx] = inFeat.id() progress.setPercentage(int(current * total)) if len(pts) < 3: raise GeoAlgorithmExecutionException( self.tr('Input file should contain at least 3 points. Choose ' 'another file and try again.')) uniqueSet = set(item for item in pts) ids = [pts.index(item) for item in uniqueSet] sl = voronoi.SiteList([voronoi.Site(*i) for i in uniqueSet]) c.triangulate = True voronoi.voronoi(sl, c) triangles = c.triangles feat = QgsFeature() total = 100.0 / len(triangles) for current, triangle in enumerate(triangles): indicies = list(triangle) indicies.append(indicies[0]) polygon = [] attrs = [] step = 0 for index in indicies: request = QgsFeatureRequest().setFilterFid(ptDict[ids[index]]) inFeat = layer.getFeatures(request).next() geom = QgsGeometry(inFeat.geometry()) point = QgsPoint(geom.asPoint()) polygon.append(point) if step <= 3: attrs.append(ids[index]) step += 1 feat.setAttributes(attrs) geometry = QgsGeometry().fromPolygon([polygon]) feat.setGeometry(geometry) writer.addFeature(feat) progress.setPercentage(int(current * total)) del writer
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib import numpy as np from voronoi import voronoi import matplotlib.pyplot as plt X, Y = np.meshgrid(np.linspace(-0.1, 1.1, 25), np.linspace(-0.1, 1.1, 25)) X = X.ravel() + np.random.uniform(-0.025, 0.025, X.size) Y = Y.ravel() + np.random.uniform(-0.025, 0.025, Y.size) cells, triangles, circles = voronoi(X, Y) fig = plt.figure(figsize=(8, 6)) axes = plt.subplot(111, aspect=1) for cell in cells: codes = [matplotlib.path.Path.MOVETO] \ + [matplotlib.path.Path.LINETO] * (len(cell)-2) \ + [matplotlib.path.Path.CLOSEPOLY] path = matplotlib.path.Path(cell, codes) color = np.random.uniform(.4, .9, 3) patch = matplotlib.patches.PathPatch(path, facecolor=color, edgecolor='w', zorder=-1) axes.add_patch(patch) plt.axis([0, 1, 0, 1]) plt.xticks([]), plt.yticks([]) plt.show()
def generate_map(): screen.fill((0, 0, 0)) points = generate_random_points(num_points, width, height, buf) #for x, y in points: # pygame.draw.circle(screen, WHITE, (x,y), 2, 1) voronoi_context = voronoi(points) voronoi_point_dict = {} point_to_segment_dict = {} segments = [] vertices = [] top_l = Point(0, 0) top_r = Point(width, 0) bottom_l = Point(0, height) bottom_r = Point(width, height) top = Line(top_l, top_r) left = Line(top_l, bottom_l) right = Line(top_r, bottom_r) bottom = Line(bottom_l, bottom_r) boundaries = [top, right, bottom, left] for edge in voronoi_context.edges: il, i1, i2 = edge # index of line, index of vertex 1, index of vertex 2 line_color = RED vert1 = None vert2 = None print_line = True if i1 is not -1 and i2 is not -1: vert1 = voronoi_context.vertices[i1] vert2 = voronoi_context.vertices[i2] else: line_point = None if i1 is -1: line_p = voronoi_context.vertices[i2] if i2 is -1: line_p = voronoi_context.vertices[i1] line_point = Point(line_p[0], line_p[1]) line = voronoi_context.lines[il] p1 = None p2 = None if line[1] == 0: p1 = line_point p2 = Point(line[0] / line[2], 1) else: p1 = Point(0, line[2] / line[1]) p2 = line_point l = Line(p1, p2) top_intersect = l.intersection(top) bottom_intersect = l.intersection(bottom) right_intersect = l.intersection(right) left_intersect = l.intersection(left) distances = [] top_dist = None bottom_dist = None right_dist = None left_dist = None if len(top_intersect) != 0: top_dist = abs(line_point.distance(top_intersect[0])) distances.append(top_dist) if len(bottom_intersect) != 0: bottom_dist = abs(line_point.distance(bottom_intersect[0])) distances.append(bottom_dist) if len(right_intersect) != 0: right_dist = abs(line_point.distance(right_intersect[0])) distances.append(right_dist) if len(left_intersect) != 0: left_dist = abs(line_point.distance(left_intersect[0])) distances.append(left_dist) vert1 = line_p v2 = None if top_dist == min(distances): v2 = top_intersect[0] elif bottom_dist == min(distances): v2 = bottom_intersect[0] elif right_dist == min(distances): v2 = right_intersect[0] elif left_dist == min(distances): v2 = left_intersect[0] else: v2 = Point(0, 0) vert2 = (v2.x, v2.y) if vert1[0] < 0 or vert1[1] < 0 or vert2[0] < 0 or vert2[ 1] < 0 or vert1[0] > width or vert1[1] > height or vert2[ 0] > width or vert2[1] > height: print_line = False if print_line: vert1, vert2 = adjust_out_of_bounds_points(vert1, vert2, boundaries) seg = None if vert1 == None or vert2 == None: print_line = False if print_line: vert1_p = Point(vert1) vert2_p = Point(vert2) seg = Segment(vert1_p, vert2_p) segments.append(seg) if not vert1_p in voronoi_point_dict: voronoi_point_dict[vert1_p] = [] if not vert2_p in voronoi_point_dict: voronoi_point_dict[vert2_p] = [] voronoi_point_dict[vert1_p].append(vert2_p) voronoi_point_dict[vert2_p].append(vert1_p) if not vert1_p in point_to_segment_dict: point_to_segment_dict[vert1_p] = [] if not vert2_p in point_to_segment_dict: point_to_segment_dict[vert2_p] = [] point_to_segment_dict[vert1_p].append(seg) point_to_segment_dict[vert2_p].append(seg) pygame.draw.line(screen, line_color, vert1, vert2, 1) pygame.display.flip() top_intersects = [] bottom_intersects = [] right_intersects = [] left_intersects = [] for seg in segments: if seg.p1.y <= 1: top_intersects.append(seg.p1) if seg.p2.y <= 1: top_intersects.append(seg.p2) if seg.p1.x >= width - 1: right_intersects.append(seg.p1) if seg.p2.x >= width - 1: right_intersects.append(seg.p2) if seg.p1.x <= 1: left_intersects.append(seg.p1) if seg.p2.x <= 1: left_intersects.append(seg.p2) if seg.p1.y >= height - 1: bottom_intersects.append(seg.p1) if seg.p2.y >= height - 1: bottom_intersects.append(seg.p2) top_intersects = sorted(top_intersects, key=lambda point: point.x) bottom_intersects = sorted(bottom_intersects, key=lambda point: point.x) left_intersects = sorted(left_intersects, key=lambda point: point.y) right_intersects = sorted(right_intersects, key=lambda point: point.y) for i in range(0, 4): intersect = None prev_vertex = None final_vertex = None if i == 0: prev_vertex = top_l intersect = top_intersects intersect.append(top_r) if i == 1: prev_vertex = bottom_l intersect = bottom_intersects intersect.append(bottom_r) if i == 2: prev_vertex = top_l intersect = left_intersects intersect.append(bottom_l) if i == 3: prev_vertex = top_r intersect = right_intersects intersect.append(bottom_r) if not prev_vertex in voronoi_point_dict: voronoi_point_dict[prev_vertex] = [] if not final_vertex in voronoi_point_dict: voronoi_point_dict[final_vertex] = [] if not prev_vertex in point_to_segment_dict: point_to_segment_dict[prev_vertex] = [] if not final_vertex in point_to_segment_dict: point_to_segment_dict[final_vertex] = [] for vertex in intersect: if not vertex in voronoi_point_dict: voronoi_point_dict[vertex] = [] if not prev_vertex in voronoi_point_dict: voronoi_point_dict[prev_vertex] = [] s = Segment(prev_vertex, vertex) voronoi_point_dict[vertex].append(prev_vertex) voronoi_point_dict[prev_vertex].append(vertex) if not vertex in point_to_segment_dict: point_to_segment_dict[vertex] = [] if not prev_vertex in point_to_segment_dict: point_to_segment_dict[prev_vertex] = [] point_to_segment_dict[vertex].append(s) point_to_segment_dict[prev_vertex].append(s) prev_vertex = vertex try: polygons, segments_to_polygons = generate_polygons( voronoi_point_dict, segments, points, point_to_segment_dict) except Exception as e: print e print "crashed" while 1: """ helllo""" for seg, gons in segments_to_polygons.iteritems(): for gon in gons: gon.connect_adjacent_nodes(gons) for polygon in polygons: for node in polygon.adjacent_nodes: s = Segment(node.center, polygon.center) draw_segment(s, WHITE) highest_points_of_elevation = [] frontiers = [] for i in range(0, number_of_peaks): p = random.choice(polygons) p.elevation = max_elevation highest_points_of_elevation.append(p) frontiers.append(set(p.adjacent_nodes)) marked_polygons = set([]) elevation = max_elevation while len(marked_polygons) < num_points: elevation -= 1 for i in range(0, number_of_peaks): new_frontier = set([]) while len(frontiers[i]) > 0: node = frontiers[i].pop() node.elevation = elevation draw_point(node.center, ORANGE) for n in node.adjacent_nodes: if n not in marked_polygons: new_frontier.add(n) marked_polygons.add(node) frontiers[i] = new_frontier for polygon in polygons: if polygon.elevation <= 0: vertices = [] for edge in polygon.edge_list: p = (edge.x, edge.y) vertices.append(p) pygame.draw.polygon(screen, BLUE, vertices, 0) pygame.display.flip() pygame.display.flip()
# Draw contour map of potential im = grid[gk].contourf(X,Y,V,clines,cmap=my_cmap) # Draw circles defining state boundaries cirA = plt.Circle((-3,0), radius=1.0, ec='k', fill=False, lw=0.5) cirB = plt.Circle((3,0), radius=1.0, ec='k', fill=False, lw=0.5) grid[gk].add_patch(cirA) grid[gk].add_patch(cirB) if k == 0: cen = centers[:ncenters,:] else: cen = centers[ncenters:,:] grid[gk].plot(cen[:,0],cen[:,1],'k.-',lw=1,ms=2,marker='o') segments = voronoi.voronoi(cen[:,0],cen[:,1]) lines = mpl.collections.LineCollection(segments, color='k',lw=0.5) grid[gk].add_collection(lines) grid[gk].axis([-5,5,-5,5]) grid[2].cax.colorbar(im) grid[2].cax.toggle_label(True) #plt.show() plt.savefig('potential_string.eps',dpi=600,format='eps',bbox_inches='tight')
def generate_map(): screen.fill((0, 0, 0)) points = generate_random_points(num_points, width, height, buf) #for x, y in points: # pygame.draw.circle(screen, WHITE, (x,y), 2, 1) voronoi_context = voronoi(points) voronoi_point_dict = {} point_to_segment_dict = {} segments = [] vertices = [] top_l = Point(0,0) top_r = Point(width,0) bottom_l = Point(0, height) bottom_r = Point(width, height) top = Line(top_l, top_r) left = Line(top_l, bottom_l) right = Line(top_r, bottom_r) bottom = Line(bottom_l, bottom_r) boundaries = [top, right, bottom, left] for edge in voronoi_context.edges: il, i1, i2 = edge # index of line, index of vertex 1, index of vertex 2 line_color = RED vert1 = None vert2 = None print_line = True if i1 is not -1 and i2 is not -1: vert1 = voronoi_context.vertices[i1] vert2 = voronoi_context.vertices[i2] else: line_point = None if i1 is -1: line_p = voronoi_context.vertices[i2] if i2 is -1: line_p = voronoi_context.vertices[i1] line_point = Point(line_p[0], line_p[1]) line = voronoi_context.lines[il] p1 = None p2 = None if line[1] == 0: p1 = line_point p2 = Point(line[0]/line[2], 1) else: p1 = Point(0, line[2]/line[1]) p2 = line_point l = Line(p1, p2) top_intersect = l.intersection(top) bottom_intersect = l.intersection(bottom) right_intersect = l.intersection(right) left_intersect = l.intersection(left) distances = [] top_dist = None bottom_dist = None right_dist = None left_dist = None if len(top_intersect) != 0: top_dist = abs(line_point.distance(top_intersect[0])) distances.append(top_dist) if len(bottom_intersect) != 0 : bottom_dist = abs(line_point.distance(bottom_intersect[0])) distances.append(bottom_dist) if len(right_intersect) != 0: right_dist = abs(line_point.distance(right_intersect[0])) distances.append(right_dist) if len(left_intersect) != 0: left_dist = abs(line_point.distance(left_intersect[0])) distances.append(left_dist) vert1 = line_p v2 = None if top_dist == min(distances): v2 = top_intersect[0] elif bottom_dist == min(distances): v2 = bottom_intersect[0] elif right_dist == min(distances): v2 = right_intersect[0] elif left_dist == min(distances): v2 = left_intersect[0] else: v2 = Point(0, 0) vert2 = (v2.x, v2.y) if vert1[0] < 0 or vert1[1] < 0 or vert2[0] < 0 or vert2[1] < 0 or vert1[0] > width or vert1[1] > height or vert2[0] > width or vert2[1] > height: print_line = False if print_line: vert1, vert2 = adjust_out_of_bounds_points(vert1, vert2, boundaries) seg = None if vert1 == None or vert2 == None: print_line = False if print_line: vert1_p = Point(vert1) vert2_p = Point(vert2) seg = Segment(vert1_p, vert2_p) segments.append(seg) if not vert1_p in voronoi_point_dict: voronoi_point_dict[vert1_p] = [] if not vert2_p in voronoi_point_dict: voronoi_point_dict[vert2_p] = [] voronoi_point_dict[vert1_p].append(vert2_p) voronoi_point_dict[vert2_p].append(vert1_p) if not vert1_p in point_to_segment_dict: point_to_segment_dict[vert1_p] = [] if not vert2_p in point_to_segment_dict: point_to_segment_dict[vert2_p] = [] point_to_segment_dict[vert1_p].append(seg) point_to_segment_dict[vert2_p].append(seg) pygame.draw.line(screen, line_color, vert1, vert2, 1) pygame.display.flip() top_intersects = [] bottom_intersects = [] right_intersects = [] left_intersects = [] for seg in segments: if seg.p1.y <= 1: top_intersects.append(seg.p1) if seg.p2.y <= 1: top_intersects.append(seg.p2) if seg.p1.x >= width -1: right_intersects.append(seg.p1) if seg.p2.x >= width-1: right_intersects.append(seg.p2) if seg.p1.x <= 1: left_intersects.append(seg.p1) if seg.p2.x <= 1: left_intersects.append(seg.p2) if seg.p1.y >= height-1: bottom_intersects.append(seg.p1) if seg.p2.y >= height-1: bottom_intersects.append(seg.p2) top_intersects = sorted(top_intersects, key=lambda point: point.x) bottom_intersects = sorted(bottom_intersects, key=lambda point: point.x) left_intersects = sorted(left_intersects, key=lambda point: point.y) right_intersects = sorted(right_intersects, key=lambda point: point.y) for i in range(0, 4): intersect = None prev_vertex = None final_vertex = None if i == 0: prev_vertex = top_l intersect = top_intersects intersect.append(top_r) if i == 1: prev_vertex = bottom_l intersect = bottom_intersects intersect.append(bottom_r) if i == 2: prev_vertex = top_l intersect = left_intersects intersect.append(bottom_l) if i == 3: prev_vertex = top_r intersect = right_intersects intersect.append(bottom_r) if not prev_vertex in voronoi_point_dict: voronoi_point_dict[prev_vertex] = [] if not final_vertex in voronoi_point_dict: voronoi_point_dict[final_vertex] = [] if not prev_vertex in point_to_segment_dict: point_to_segment_dict[prev_vertex] = [] if not final_vertex in point_to_segment_dict: point_to_segment_dict[final_vertex] = [] for vertex in intersect: if not vertex in voronoi_point_dict: voronoi_point_dict[vertex] = [] if not prev_vertex in voronoi_point_dict: voronoi_point_dict[prev_vertex] = [] s = Segment(prev_vertex, vertex) voronoi_point_dict[vertex].append(prev_vertex) voronoi_point_dict[prev_vertex].append(vertex) if not vertex in point_to_segment_dict: point_to_segment_dict[vertex] = [] if not prev_vertex in point_to_segment_dict: point_to_segment_dict[prev_vertex] = [] point_to_segment_dict[vertex].append(s) point_to_segment_dict[prev_vertex].append(s) prev_vertex = vertex try: polygons, segments_to_polygons = generate_polygons(voronoi_point_dict, segments, points, point_to_segment_dict) except Exception as e: print e print "crashed" while 1: """ helllo""" for seg, gons in segments_to_polygons.iteritems(): for gon in gons: gon.connect_adjacent_nodes(gons) for polygon in polygons: for node in polygon.adjacent_nodes: s = Segment(node.center, polygon.center) draw_segment(s, WHITE) highest_points_of_elevation = [] frontiers = [] for i in range(0, number_of_peaks): p = random.choice(polygons) p.elevation = max_elevation highest_points_of_elevation.append(p) frontiers.append(set(p.adjacent_nodes)) marked_polygons = set([]) elevation = max_elevation while len(marked_polygons) < num_points: elevation -= 1 for i in range(0, number_of_peaks): new_frontier = set([]) while len(frontiers[i]) > 0: node = frontiers[i].pop() node.elevation = elevation draw_point(node.center, ORANGE) for n in node.adjacent_nodes: if n not in marked_polygons: new_frontier.add(n) marked_polygons.add(node) frontiers[i] = new_frontier for polygon in polygons: if polygon.elevation <= 0: vertices = [] for edge in polygon.edge_list: p = (edge.x, edge.y) vertices.append(p) pygame.draw.polygon(screen, BLUE, vertices, 0) pygame.display.flip() pygame.display.flip()
# ----------------------------------------------------------------------------------- # Algorithm # ----------------------------------------------------------------------------------- stdevs = [] stdevs.append(maxsize) centroids = seeds # Moves seeds towards the weighted centroids until the voronoi tesselation yields # a higher standard deviation of the areas while True: # iteration seeds = allMoveSafeTowards(seeds, centroids, stepsize, bnd) cells = voronoi(seeds, bnd) areas = poly_areas(cells) heights = gauss_heights(areas, heighPar) phi = init_phi(X, Y, seeds, heights, sigma) centroids = wCentroids(cells, phi, X, Y) # plot the result # plot_voronoi(cells, seeds,centroids, X, Y, phi) stdev = np.round(np.std(areas), 4) print(stdev) if stdev >= stdevs[-1]: break stdevs.append(stdev) plt.clf()
num_points = min(ii.size,500) jj = ii[:num_points] if k % 2 == 0: cc = '0.8' else: cc = '0.4' grid[0].plot(crd[jj,0],crd[jj,1],c=cc,mec=cc,mfc=cc,marker='.',ms=3,ls='None',zorder=1) # Plot string grid[0].plot(centers[:,0],centers[:,1],ms=3,marker='o',color='k',ls='None',zorder=2) # Plot Voronoi Cells segments = voronoi.voronoi(cen_rep[:,0],cen_rep[:,1]) lines = mpl.collections.LineCollection(segments, color='k',lw=1.0,zorder=3) grid[0].add_collection(lines) grid[0].set_xlabel('X') grid[0].set_ylabel('Y') grid[0].axis([-1,1,0,1]) grid[0].cax.colorbar(im) grid[0].cax.toggle_label(True) fig.set_size_inches(fsize) plt.tight_layout() plt.savefig('potential_string.eps',dpi=600,format='eps',bbox_inches='tight') plt.show()
import numpy as np from scipy.spatial import ConvexHull import matplotlib.pyplot as plt from voronoi import voronoi # points in R^2 pins = np.random.rand(100, 2) # boundary points in R^2 bnd = np.random.rand(30, 2) # create the polytope bounded voronoi diagram pnts, vorn = voronoi(pins, bnd) # plot the result... pntsv = [[] for row in pnts] plt.plot(pnts[:, 0], pnts[:, 1], 'o') for i, obj in enumerate(pnts): pntsv[i] = np.array(vorn[i]) if len(pntsv[i]) >= 3: vorhull = ConvexHull(pntsv[i]) plt.plot(pntsv[i][:, 0], pntsv[i][:, 1], 'x') for simplex in vorhull.simplices: plt.plot(pntsv[i][simplex, 0], pntsv[i][simplex, 1], 'k-') plt.axis('equal') plt.show()
def effect(self): if not self.options.ids: inkex.errormsg(_("Please select an object")) exit() scale = self.unittouu('1px') # convert to document units self.options.size *= scale self.options.border *= scale q = { 'x': 0, 'y': 0, 'width': 0, 'height': 0 } # query the bounding box of ids[0] for query in q.keys(): p = Popen('inkscape --query-%s --query-id=%s "%s"' % (query, self.options.ids[0], self.args[-1]), shell=True, stdout=PIPE, stderr=PIPE) rc = p.wait() q[query] = scale * float(p.stdout.read()) # generate random pattern of points node = self.selected.values()[0] path_string = node.attrib[u'd'] svg_path = simplepath.parsePath(path_string) pts = self.generatePoints(svg_path, self.options.size) self.display_pts(pts) c = voronoi.Context() pts_to_trig = [] for point in pts: pts_to_trig.append(voronoi.Site(point.loc[0], point.loc[1])) # triangulate with library sl = voronoi.SiteList(pts_to_trig) c.triangulate = True voronoi.voronoi(sl, c) edge_to_triangle = {} triangle_timestamps = [0] * len(c.triangles) triangle_used = [False] * len(c.triangles) quads = [] def getTriangularMidPoint(pt1, pt2, pt3): mid_2_3 = pt2.loc + 0.5 * (pt3.loc - pt2.loc) mid_1_3 = pt1.loc + 0.5 * (pt3.loc - pt1.loc) return curve_utils.intersect_line_line([pt1.loc, mid_2_3], [pt2.loc, mid_1_3])[0] def rejectOutofRangeTringl(): for trngl_indx in range(len(c.triangles)): triangle = c.triangles[trngl_indx] if pts[triangle[0]].type != 3 and pts[ triangle[1]].type != 3 and pts[triangle[2]].type != 3: triangle_midpt = getTriangularMidPoint( pts[triangle[0]], pts[triangle[1]], pts[triangle[2]]) if not pointInPath(self.paths, triangle_midpt): triangle_used[trngl_indx] = True rejectOutofRangeTringl() for trngl_indx in range(len(c.triangles)): triangle = c.triangles[trngl_indx] # compute timestamp for each triangle verts = [pts[triangle[i]] for i in range(3)] min_tstmp = min([vert.timestamp for vert in verts]) triangle_timestamps[trngl_indx] = min_tstmp # build edge_to_triangle for j in range(0, 3): id1 = triangle[j] id2 = triangle[(j + 1) % 3] if id1 < id2: edge = (id1, id2) else: edge = (id2, id1) if edge in edge_to_triangle: edge_to_triangle[edge].append(trngl_indx) else: edge_to_triangle[edge] = [trngl_indx] def getThirdInkex(triangle, edge): for id in triangle: if id not in edge: return id def getEdgeLen(pt1, pt2): return np.linalg.norm(pt1.loc - pt2.loc) def getAngle(pt1, pt2, pt3): vec1 = pt1.loc - pt2.loc vec2 = pt3.loc - pt2.loc angle = np.dot( vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2)) return math.acos(angle) def matchLongestEdge(matchTimestamp): # process triangles for edge in edge_to_triangle: if len(edge_to_triangle[edge]) == 2: tringl1, tringl2 = edge_to_triangle[edge] # skip if either triangle used if triangle_used[tringl1] or triangle_used[tringl2]: continue if matchTimestamp and triangle_timestamps[ tringl1] != triangle_timestamps[tringl2]: continue # get third index of triangle third_id1 = getThirdInkex(c.triangles[tringl1], edge) third_id2 = getThirdInkex(c.triangles[tringl2], edge) # get edge length edge_len = getEdgeLen(pts[edge[0]], pts[edge[1]]) # get other edges length trigl1_edge_len = [ getEdgeLen(pts[edge[0]], pts[third_id1]), getEdgeLen(pts[edge[1]], pts[third_id1]) ] trigl2_edge_len = [ getEdgeLen(pts[edge[0]], pts[third_id2]), getEdgeLen(pts[edge[1]], pts[third_id2]) ] # check if the connecting edge is longest edge of both triangles if all(edge_len >= el for el in trigl1_edge_len) and all( edge_len >= el for el in trigl2_edge_len): # if yes, create quadrilateral quads.append([edge[0], third_id1, edge[1], third_id2]) triangle_used[tringl1] = True triangle_used[tringl2] = True def createNiceQuads(matchTimestamp): # process triangles for edge in edge_to_triangle: if len(edge_to_triangle[edge]) == 2: tringl1, tringl2 = edge_to_triangle[edge] # skip if either triangle used if triangle_used[tringl1] or triangle_used[tringl2]: continue if matchTimestamp and triangle_timestamps[ tringl1] != triangle_timestamps[tringl2]: continue # get third index of triangle third_id1 = getThirdInkex(c.triangles[tringl1], edge) third_id2 = getThirdInkex(c.triangles[tringl2], edge) # get edge length quad_lens = [] edge_len = getEdgeLen(pts[edge[0]], pts[edge[1]]) # get other edges length quad_lens.extend([ getEdgeLen(pts[edge[0]], pts[third_id1]), getEdgeLen(pts[edge[1]], pts[third_id1]) ]) quad_lens.extend([ getEdgeLen(pts[edge[0]], pts[third_id2]), getEdgeLen(pts[edge[1]], pts[third_id2]) ]) avg_quad_len = sum(quad_lens) / len(quad_lens) len_diff = 0 for quad_len in quad_lens: len_diff += abs(quad_len - avg_quad_len) / avg_quad_len angles = [] angles.append( getAngle(pts[edge[0]], pts[third_id1], pts[edge[1]])) angles.append( getAngle(pts[third_id1], pts[edge[1]], pts[third_id2])) angles.append( getAngle(pts[edge[1]], pts[third_id2], pts[edge[0]])) angles.append( getAngle(pts[third_id2], pts[edge[0]], pts[third_id1])) angle_diff = 0 for angle in angles: angle_diff += abs(angle - 3.14159 / 2.0) / (3.14159 / 2) # check if the connecting edge is longest edge of both triangles if len_diff + angle_diff <= threshold: # if yes, create quadrilateral quads.append([edge[0], third_id1, edge[1], third_id2]) triangle_used[tringl1] = True triangle_used[tringl2] = True matchLongestEdge(True) matchLongestEdge(False) createNiceQuads(True) createNiceQuads(False) self.display_triangles(pts, triangle_used, c.triangles) self.display_quads(pts, quads)
def Fortune(self, points): """Generate polygons. points: Input point sets return list is: vertices: All vertices of all the polygon polygons: A list of lists, where polygons[i] is a list of vertices for station i.""" voronoi.Edge.LE = 0 voronoi.Edge.RE = 1 voronoi.Edge.EDGE_NUM = 0 voronoi.Edge.DELETED = {} # marker value siteList = voronoi.SiteList(points) context = voronoi.Context() voronoi.voronoi(siteList,context) vertices = context.vertices lines = context.lines edges = context.edges has_edge = context.has_edge #print(vertices) #print(lines) #print(edges) #Empty vertices if len(lines) == 0: vts = [(points[0].x,points[0].y)] polygons = [[(0,0),(1000,0),(1000,1000),(0,1000)]] self.edges = edges self.lines = lines self.has_edge = has_edge self.vertices = list(vts) self.polygons = polygons self.points = points return edgedict = dict(); for e in edges: edgedict[e[0]] = (e[1],e[2], True) vts = set() #Delete edges that are outside the bounding box for v in vertices: if self.Inrange(v): vts.add(v) polygons = list() for i in range(len(points)): cand = set() pset = set() #Add to candidates. -1 means does not associate with a line cand.add((self.rec[0],self.rec[1])) cand.add((self.rec[0],self.rec[3])) cand.add((self.rec[2],self.rec[1])) cand.add((self.rec[2],self.rec[3])) #print(has_edge[i]) for j in range(len(has_edge[i])): #Scanning over the lines to determine intersects or candidates edge = edgedict[has_edge[i][j]] line = lines[has_edge[i][j]] #Edge endpoints outside and points to outside where #if edge[0] == -1 and edge[1] != -1 and not self.Inrange(vertices[edge[1]]) or (edge[0] != -1 and edge[1] == -1 and not self.Inrange(vertices[edge[0]])): #continue #Edge endpoints outside if edge[0] != -1 and (not self.Inrange(vertices[edge[0]])): edge = (-1, edge[1]) if edge[1] != -1 and (not self.Inrange(vertices[edge[1]])): edge = (edge[0], -1) if edge[0] == -1 and edge[1] == -1: #Add to point sets because this is the right one pt1,pt2 = self.Intersect(line) #print((points[i],line,edge,pt1,pt2)) cand.add(pt1) cand.add(pt2) elif edge[0] == -1 or edge[1] == -1: #Add to candidates because one has to be gone. With edge index. pt1,pt2 = self.Intersect(line) #print((points[i],line,edge,pt1,pt2)) cand.add(pt1) cand.add(pt2) if edge[0] == -1: cand.add(vertices[edge[1]]) else: cand.add(vertices[edge[0]]) else: #Add both points to cand, if both the points are valid cand.add(vertices[edge[0]]) cand.add(vertices[edge[1]]) #Iterate over all the candidates, determine whether they can be saved for c in cand: valid = True #Iterate through all the lines associated with point i for j in range(len(has_edge[i])): line = lines[has_edge[i][j]] if not Voronoi.Sameside(line, (points[i].x,points[i].y),c): valid = False #print((points[i],line,c,valid)) break #print((points[i],line,c,valid)) if valid == True: pset.add(c) vts.add(c) #Update polygons polygons.append(sorted(list(pset), key = lambda p: Voronoi.Direction((points[i].x,points[i].y),p))) self.edges = edges self.lines = lines self.has_edge = has_edge self.vertices = list(vts) self.polygons = polygons self.points = points
def VoronoiPolygons(PointsMap, BoundingBox="W", PlotMap=False): global PlotIt global WorldRange global WorldRanges if type(BoundingBox) == type([]): if len(BoundingBox) == 4: WorldRange = BoundingBox else: return "Error in Bounding Box" else: WorldRange = WorldRanges[BoundingBox] PlotIt = PlotMap currenttime = time.time() Sitepts = [] pts = {} #print CurrentDate, PointsMap[PointsMap.keys()[0]] for grid, stn in PointsMap.items(): x = float(stn[0]) y = float(stn[1]) station = grid #station.extend( stn[3:]) #print x,y,station pts[(x, y)] = station stncounts = len(pts.keys()) #print stncounts, "points" site_points = [] for pt in pts.keys(): Sitepts.append(voronoi.Site(pt[0], pt[1])) site_points.append((pt[0], pt[1])) #print "Calculating Voronoi Lattice", siteList = voronoi.SiteList(Sitepts) context = voronoi.Context() voronoi.Edge.EDGE_NUM = 0 voronoi.voronoi(siteList, context) vertices = context.vertices lines = context.lines edges = context.edges #print edges #For Faster Access edge_dic = {} for edge in edges: edge_dic[edge[0]] = edge[1:] triangles = context.triangles has_edge = context.has_edge voronoi_lattice = {} m_range = {} m_range["max_x"] = -9999999999 m_range["max_y"] = -9999999999 m_range["min_x"] = 9999999999 m_range["min_y"] = 9999999999 #Get the range!! for pnt in site_points: m_range = update_maxmin(m_range, pnt[0], pnt[1]) #print "Getting the Polygons" prev_percent = 0 for station, ls in has_edge.items(): voronoi_lattice[station] = {} voronoi_lattice[station]["coordinate"] = site_points[station] voronoi_lattice[station]["info"] = pts[site_points[station]] polygon = [] prev_extreme = [] Verbose = True if Verbose: current_percent = int(station / float(stncounts) * 100) if current_percent != prev_percent: #print station,"/", stncounts, current_percent, "% Done" timeelapse = time.time() - currenttime #print station, timeelapse currenttime = time.time() prev_percent = current_percent #For every lines that the station owns for l in ls: e = edge_dic[l] v1 = vertices[e[0]] v2 = vertices[e[1]] if e[0] < 0 and checkInRange(WorldRange, v2[0], v2[1]) == False: continue if e[1] < 0 and checkInRange(WorldRange, v1[0], v1[1]) == False: continue if e[0] > -1 and e[1] > -1 and checkInRange( WorldRange, v1[0], v1[1]) == False and checkInRange( WorldRange, v2[0], v2[1]) == False: continue if e[0] < 0 or checkInRange(WorldRange, v1[0], v1[1]) == False: v1 = getExtreme(lines[l], v2, LR=0) if len(prev_extreme) == 0: prev_extreme = v1 else: extreme_points = linkExtremes(prev_extreme, v1, m_range) for extreme_pair in extreme_points: polygon.append(extreme_pair) if e[1] < 0 or checkInRange(WorldRange, v2[0], v2[1]) == False: v2 = getExtreme(lines[l], v1, LR=1) if len(prev_extreme) == 0: prev_extreme = v2 else: extreme_points = linkExtremes(prev_extreme, v2, m_range) for extreme_pair in extreme_points: polygon.append(extreme_pair) if v1 != v2: polygon.append((v1, v2)) if len(polygon) == 0: sys.stderr.write( "\nThis station does not have meaningful polygon:") sys.stderr.write( str(pts[site_points[station]]) + " at " + str(site_points[station]) + "\n") for l in ls: e = edge_dic[l] v1 = vertices[e[0]] v2 = vertices[e[1]] sys.stderr.write(str(e[0]) + "," + str(e[1]) + "\n") sys.stderr.write(str(v1) + "," + str(v2) + "\n") voronoi_lattice.pop(station) continue #print polygon try: result = list(polygonize(polygon)) except ValueError: #print "Wrong:", polygon #Delete invisible short lines point_to_replace = [] for line in polygon: d = math.hypot(line[0][0] - line[1][0], line[0][1] - line[1][1]) if d < 1: polygon.remove(line) point_to_replace = line i = 0 New_Lines = [] for line in polygon: New_Lines.append(list(line)) j = 0 for point in line: if point == point_to_replace[0]: #print line, point_to_replace New_Lines[i][j] = point_to_replace[1] j += 1 i += 1 polygon = tuple(New_Lines) #I could not figure out why sometimes it fails to draw a polygon. try: result = list(polygonize(polygon)) except: voronoi_lattice.pop(station) continue finalpoly = result[0] #print list(finalpoly.exterior.coords) #voronoi_lattice[station]["polygon"]=list(finalpoly.exterior.coords) voronoi_lattice[station]["obj_polygon"] = finalpoly #print polygon if (PlotIt): for station, data in voronoi_lattice.items(): x = [] y = [] #print data try: polygon_data = data["obj_polygon"] #print polygon_data for point in list(polygon_data.exterior.coords): x.append(point[0]) y.append(point[1]) except: print "Error", data["name"] #if station == 8 : #plot(x,y) fill(x, y, alpha=0.6) plot(data["coordinate"][0], data["coordinate"][1]) #text(data["coordinate"][0],data["coordinate"][1],data["info"]) show() return voronoi_lattice
def effect(self): if not self.options.ids: return inkex.errormsg(_("Please select an object")) scale = self.svg.unittouu('1px') # convert to document units self.options.size *= scale self.options.border *= scale obj = self.svg.selection.first() bbox = obj.bounding_box() mat = obj.composed_transform().matrix pattern = self.svg.defs.add(Pattern()) pattern.set_random_id('Voronoi') pattern.set('width', str(bbox.width)) pattern.set('height', str(bbox.height)) pattern.set('patternUnits', 'userSpaceOnUse') pattern.patternTransform.add_translate(bbox.left - mat[0][2], bbox.top - mat[1][2]) # generate random pattern of points c = voronoi.Context() pts = [] b = float(self.options.border) # width of border for i in range(int(bbox.width * bbox.height / self.options.size / self.options.size)): x = random.random() * bbox.width y = random.random() * bbox.height if b > 0: # duplicate border area pts.append(voronoi.Site(x, y)) if x < b: pts.append(voronoi.Site(x + bbox.width, y)) if y < b: pts.append(voronoi.Site(x + bbox.width, y + bbox.height)) if y > bbox.height - b: pts.append(voronoi.Site(x + bbox.width, y - bbox.height)) if x > bbox.width - b: pts.append(voronoi.Site(x - bbox.width, y)) if y < b: pts.append(voronoi.Site(x - bbox.width, y + bbox.height)) if y > bbox.height - b: pts.append(voronoi.Site(x - bbox.width, y - bbox.height)) if y < b: pts.append(voronoi.Site(x, y + bbox.height)) if y > bbox.height - b: pts.append(voronoi.Site(x, y - bbox.height)) elif x > -b and y > -b and x < bbox.width + b and y < bbox.height + b: pts.append(voronoi.Site(x, y)) # leave border area blank # dot = pattern.add(inkex.Rectangle()) # dot.set('x', str(x-1)) # dot.set('y', str(y-1)) # dot.set('width', '2') # dot.set('height', '2') if len(pts) < 3: return inkex.errormsg("Please choose a larger object, or smaller cell size") # plot Voronoi diagram sl = voronoi.SiteList(pts) voronoi.voronoi(sl, c) path = "" for edge in c.edges: if edge[1] >= 0 and edge[2] >= 0: # two vertices [x1, y1, x2, y2] = clip_line(c.vertices[edge[1]][0], c.vertices[edge[1]][1], c.vertices[edge[2]][0], c.vertices[edge[2]][1], bbox.width, bbox.height) elif edge[1] >= 0: # only one vertex if c.lines[edge[0]][1] == 0: # vertical line xtemp = c.lines[edge[0]][2] / c.lines[edge[0]][0] if c.vertices[edge[1]][1] > bbox.height / 2: ytemp = bbox.height else: ytemp = 0 else: xtemp = bbox.width ytemp = (c.lines[edge[0]][2] - bbox.width * c.lines[edge[0]][0]) / c.lines[edge[0]][1] [x1, y1, x2, y2] = clip_line(c.vertices[edge[1]][0], c.vertices[edge[1]][1], xtemp, ytemp, bbox.width, bbox.height) elif edge[2] >= 0: # only one vertex if edge[0] >= len(c.lines): xtemp = 0 ytemp = 0 elif c.lines[edge[0]][1] == 0: # vertical line xtemp = c.lines[edge[0]][2] / c.lines[edge[0]][0] if c.vertices[edge[2]][1] > bbox.height / 2: ytemp = bbox.height else: ytemp = 0 else: xtemp = 0 ytemp = c.lines[edge[0]][2] / c.lines[edge[0]][1] [x1, y1, x2, y2] = clip_line(xtemp, ytemp, c.vertices[edge[2]][0], c.vertices[edge[2]][1], bbox.width, bbox.height) if x1 or x2 or y1 or y2: path += 'M %.3f,%.3f %.3f,%.3f ' % (x1, y1, x2, y2) patternstyle = {'stroke': '#000000', 'stroke-width': str(scale)} attribs = {'d': path, 'style': str(inkex.Style(patternstyle))} pattern.append(PathElement(**attribs)) # link selected object to pattern style = {} if 'style' in obj.attrib: style = dict(inkex.Style.parse_str(obj.attrib['style'])) style['fill'] = 'url(#%s)' % pattern.get('id') obj.attrib['style'] = str(inkex.Style(style)) if isinstance(obj, inkex.Group): for node in obj: style = {} if 'style' in node.attrib: style = dict(inkex.Style.parse_str(node.attrib['style'])) style['fill'] = 'url(#%s)' % pattern.get('id') node.attrib['style'] = str(inkex.Style(style))
def processAlgorithm(self, progress): layer = dataobjects.getObjectFromUri(self.getParameterValue( self.INPUT)) fields = [ QgsField('POINTA', QVariant.Double, '', 24, 15), QgsField('POINTB', QVariant.Double, '', 24, 15), QgsField('POINTC', QVariant.Double, '', 24, 15) ] writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( fields, QGis.WKBPolygon, layer.crs()) pts = [] ptDict = {} ptNdx = -1 c = voronoi.Context() features = vector.features(layer) for inFeat in features: geom = QgsGeometry(inFeat.geometry()) point = geom.asPoint() x = point.x() y = point.y() pts.append((x, y)) ptNdx += 1 ptDict[ptNdx] = inFeat.id() if len(pts) < 3: raise GeoAlgorithmExecutionException( 'Input file should contain at least 3 points. Choose \ another file and try again.') uniqueSet = Set(item for item in pts) ids = [pts.index(item) for item in uniqueSet] sl = voronoi.SiteList([voronoi.Site(*i) for i in uniqueSet]) c.triangulate = True voronoi.voronoi(sl, c) triangles = c.triangles feat = QgsFeature() current = 0 total = 100.0 / float(len(triangles)) for triangle in triangles: indicies = list(triangle) indicies.append(indicies[0]) polygon = [] attrs = [] step = 0 for index in indicies: request = QgsFeatureRequest().setFilterFid(ptDict[ids[index]]) inFeat = layer.getFeatures(request).next() geom = QgsGeometry(inFeat.geometry()) point = QgsPoint(geom.asPoint()) polygon.append(point) if step <= 3: attrs.append(ids[index]) step += 1 feat.setAttributes(attrs) geometry = QgsGeometry().fromPolygon([polygon]) feat.setGeometry(geometry) writer.addFeature(feat) current += 1 progress.setPercentage(int(current * total)) del writer
from scipy import misc from voronoi import voronoi from matplotlib.path import Path from matplotlib.patches import PathPatch import matplotlib.pyplot as plt img = misc.imread("starry-night-detail.jpg") height, width, depth = img.shape fig = plt.figure(figsize=(10, 10*(height/width))) ax = fig.add_axes([0.0, 0.0, 1.0, 1.0], frameon=False, aspect=1) radius = 7 P = poisson_disk_sample(width=width-0.1, height=height-0.1, radius=radius, k=30) ax.set_xlim(0, width) ax.set_ylim(0, height) ax.set_xticks([]) ax.set_yticks([]) X, Y = P[:, 0], P[:, 1] cells, triangles, circles = voronoi(X, height-Y) for i, cell in enumerate(cells): codes = [Path.MOVETO] + [Path.LINETO]*(len(cell)-2) + [Path.CLOSEPOLY] path = Path(cell, codes) color = img[int(np.floor(Y[i])), int(np.floor(X[i]))] / 255.0 patch = PathPatch(path, facecolor=color, edgecolor="none") ax.add_patch(patch) plt.savefig("../data/mosaic.png") plt.show()
def Fortune(self, points): """Generate polygons. points: Input point sets return list is: vertices: All vertices of all the polygon polygons: A list of lists, where polygons[i] is a list of vertices for station i.""" voronoi.Edge.LE = 0 voronoi.Edge.RE = 1 voronoi.Edge.EDGE_NUM = 0 voronoi.Edge.DELETED = {} # marker value siteList = voronoi.SiteList(points) context = voronoi.Context() voronoi.voronoi(siteList, context) vertices = context.vertices lines = context.lines edges = context.edges has_edge = context.has_edge #print(vertices) #print(lines) #print(edges) #Empty vertices if len(lines) == 0: vts = [(points[0].x, points[0].y)] polygons = [[(0, 0), (1000, 0), (1000, 1000), (0, 1000)]] self.edges = edges self.lines = lines self.has_edge = has_edge self.vertices = list(vts) self.polygons = polygons self.points = points return edgedict = dict() for e in edges: edgedict[e[0]] = (e[1], e[2], True) vts = set() #Delete edges that are outside the bounding box for v in vertices: if self.Inrange(v): vts.add(v) polygons = list() for i in range(len(points)): cand = set() pset = set() #Add to candidates. -1 means does not associate with a line cand.add((self.rec[0], self.rec[1])) cand.add((self.rec[0], self.rec[3])) cand.add((self.rec[2], self.rec[1])) cand.add((self.rec[2], self.rec[3])) #print(has_edge[i]) for j in range(len(has_edge[i])): #Scanning over the lines to determine intersects or candidates edge = edgedict[has_edge[i][j]] line = lines[has_edge[i][j]] #Edge endpoints outside and points to outside where #if edge[0] == -1 and edge[1] != -1 and not self.Inrange(vertices[edge[1]]) or (edge[0] != -1 and edge[1] == -1 and not self.Inrange(vertices[edge[0]])): #continue #Edge endpoints outside if edge[0] != -1 and (not self.Inrange(vertices[edge[0]])): edge = (-1, edge[1]) if edge[1] != -1 and (not self.Inrange(vertices[edge[1]])): edge = (edge[0], -1) if edge[0] == -1 and edge[1] == -1: #Add to point sets because this is the right one pt1, pt2 = self.Intersect(line) #print((points[i],line,edge,pt1,pt2)) cand.add(pt1) cand.add(pt2) elif edge[0] == -1 or edge[1] == -1: #Add to candidates because one has to be gone. With edge index. pt1, pt2 = self.Intersect(line) #print((points[i],line,edge,pt1,pt2)) cand.add(pt1) cand.add(pt2) if edge[0] == -1: cand.add(vertices[edge[1]]) else: cand.add(vertices[edge[0]]) else: #Add both points to cand, if both the points are valid cand.add(vertices[edge[0]]) cand.add(vertices[edge[1]]) #Iterate over all the candidates, determine whether they can be saved for c in cand: valid = True #Iterate through all the lines associated with point i for j in range(len(has_edge[i])): line = lines[has_edge[i][j]] if not Voronoi.Sameside(line, (points[i].x, points[i].y), c): valid = False #print((points[i],line,c,valid)) break #print((points[i],line,c,valid)) if valid == True: pset.add(c) vts.add(c) #Update polygons polygons.append( sorted(list(pset), key=lambda p: Voronoi.Direction( (points[i].x, points[i].y), p))) self.edges = edges self.lines = lines self.has_edge = has_edge self.vertices = list(vts) self.polygons = polygons self.points = points
def effect(self): if not self.options.ids: inkex.errormsg(_("Please select an object")) exit() scale = self.unittouu('1px') # convert to document units self.options.size *= scale self.options.border *= scale q = {'x':0,'y':0,'width':0,'height':0} # query the bounding box of ids[0] for query in q.keys(): p = Popen('inkscape --query-%s --query-id=%s "%s"' % (query, self.options.ids[0], self.args[-1]), shell=True, stdout=PIPE, stderr=PIPE) rc = p.wait() q[query] = scale*float(p.stdout.read()) mat = simpletransform.composeParents(self.selected[self.options.ids[0]], [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) defs = self.xpathSingle('/svg:svg//svg:defs') pattern = inkex.etree.SubElement(defs ,inkex.addNS('pattern','svg')) pattern.set('id', 'Voronoi' + str(random.randint(1, 9999))) pattern.set('width', str(q['width'])) pattern.set('height', str(q['height'])) pattern.set('patternTransform', 'translate(%s,%s)' % (q['x'] - mat[0][2], q['y'] - mat[1][2])) pattern.set('patternUnits', 'userSpaceOnUse') # generate random pattern of points c = voronoi.Context() pts = [] b = float(self.options.border) # width of border for i in range(int(q['width']*q['height']/self.options.size/self.options.size)): x = random.random()*q['width'] y = random.random()*q['height'] if b > 0: # duplicate border area pts.append(voronoi.Site(x, y)) if x < b: pts.append(voronoi.Site(x + q['width'], y)) if y < b: pts.append(voronoi.Site(x + q['width'], y + q['height'])) if y > q['height'] - b: pts.append(voronoi.Site(x + q['width'], y - q['height'])) if x > q['width'] - b: pts.append(voronoi.Site(x - q['width'], y)) if y < b: pts.append(voronoi.Site(x - q['width'], y + q['height'])) if y > q['height'] - b: pts.append(voronoi.Site(x - q['width'], y - q['height'])) if y < b: pts.append(voronoi.Site(x, y + q['height'])) if y > q['height'] - b: pts.append(voronoi.Site(x, y - q['height'])) elif x > -b and y > -b and x < q['width'] + b and y < q['height'] + b: pts.append(voronoi.Site(x, y)) # leave border area blank # dot = inkex.etree.SubElement(pattern, inkex.addNS('rect','svg')) # dot.set('x', str(x-1)) # dot.set('y', str(y-1)) # dot.set('width', '2') # dot.set('height', '2') if len(pts) < 3: inkex.errormsg("Please choose a larger object, or smaller cell size") exit() # plot Voronoi diagram sl = voronoi.SiteList(pts) voronoi.voronoi(sl, c) path = "" for edge in c.edges: if edge[1] >= 0 and edge[2] >= 0: # two vertices [x1, y1, x2, y2] = clip_line(c.vertices[edge[1]][0], c.vertices[edge[1]][1], c.vertices[edge[2]][0], c.vertices[edge[2]][1], q['width'], q['height']) elif edge[1] >= 0: # only one vertex if c.lines[edge[0]][1] == 0: # vertical line xtemp = c.lines[edge[0]][2]/c.lines[edge[0]][0] if c.vertices[edge[1]][1] > q['height']/2: ytemp = q['height'] else: ytemp = 0 else: xtemp = q['width'] ytemp = (c.lines[edge[0]][2] - q['width']*c.lines[edge[0]][0])/c.lines[edge[0]][1] [x1, y1, x2, y2] = clip_line(c.vertices[edge[1]][0], c.vertices[edge[1]][1], xtemp, ytemp, q['width'], q['height']) elif edge[2] >= 0: # only one vertex if c.lines[edge[0]][1] == 0: # vertical line xtemp = c.lines[edge[0]][2]/c.lines[edge[0]][0] if c.vertices[edge[2]][1] > q['height']/2: ytemp = q['height'] else: ytemp = 0 else: xtemp = 0 ytemp = c.lines[edge[0]][2]/c.lines[edge[0]][1] [x1, y1, x2, y2] = clip_line(xtemp, ytemp, c.vertices[edge[2]][0], c.vertices[edge[2]][1], q['width'], q['height']) if x1 or x2 or y1 or y2: path += 'M %.3f,%.3f %.3f,%.3f ' % (x1, y1, x2, y2) patternstyle = {'stroke': '#000000', 'stroke-width': str(scale)} attribs = {'d': path, 'style': simplestyle.formatStyle(patternstyle)} inkex.etree.SubElement(pattern, inkex.addNS('path', 'svg'), attribs) # link selected object to pattern obj = self.selected[self.options.ids[0]] style = {} if obj.attrib.has_key('style'): style = simplestyle.parseStyle(obj.attrib['style']) style['fill'] = 'url(#%s)' % pattern.get('id') obj.attrib['style'] = simplestyle.formatStyle(style) if obj.tag == inkex.addNS('g', 'svg'): for node in obj: style = {} if node.attrib.has_key('style'): style = simplestyle.parseStyle(node.attrib['style']) style['fill'] = 'url(#%s)' % pattern.get('id') node.attrib['style'] = simplestyle.formatStyle(style)
def VoronoiPolygons(PointsMap, BoundingBox="W", PlotMap=False): global PlotIt global WorldRange global WorldRanges if type(BoundingBox)==type([]): if len(BoundingBox)==4: WorldRange=BoundingBox else: return "Error in Bounding Box" else: WorldRange=WorldRanges[BoundingBox] PlotIt=PlotMap currenttime=time.time() Sitepts = [] pts = {} #print CurrentDate, PointsMap[PointsMap.keys()[0]] for grid, stn in PointsMap.items(): x=float(stn[0]) y=float(stn[1]) station=grid #station.extend( stn[3:]) #print x,y,station pts[ (x,y) ]=station stncounts=len(pts.keys()) #print stncounts, "points" site_points=[] for pt in pts.keys(): Sitepts.append(voronoi.Site(pt[0],pt[1])) site_points.append( (pt[0],pt[1]) ) #print "Calculating Voronoi Lattice", siteList = voronoi.SiteList(Sitepts) context = voronoi.Context() voronoi.Edge.EDGE_NUM=0 voronoi.voronoi(siteList,context) vertices=context.vertices lines=context.lines edges=context.edges #print edges #For Faster Access edge_dic={} for edge in edges: edge_dic[edge[0]]=edge[1:] triangles=context.triangles has_edge=context.has_edge voronoi_lattice={} m_range={} m_range["max_x"]=-9999999999 m_range["max_y"]=-9999999999 m_range["min_x"]=9999999999 m_range["min_y"]=9999999999 #Get the range!! for pnt in site_points: m_range=update_maxmin(m_range, pnt[0], pnt[1]) #print "Getting the Polygons" prev_percent=0 for station, ls in has_edge.items(): voronoi_lattice[station]={} voronoi_lattice[station]["coordinate"]=site_points[station] voronoi_lattice[station]["info"]=pts[ site_points[station] ] polygon=[] prev_extreme=[] Verbose=True if Verbose: current_percent=int(station/float(stncounts)*100) if current_percent!=prev_percent: #print station,"/", stncounts, current_percent, "% Done" timeelapse=time.time()-currenttime #print station, timeelapse currenttime=time.time() prev_percent=current_percent #For every lines that the station owns for l in ls: e=edge_dic[l] v1=vertices[e[0]] v2=vertices[e[1]] if e[0] < 0 and checkInRange(WorldRange,v2[0],v2[1])==False: continue if e[1] < 0 and checkInRange(WorldRange,v1[0],v1[1])==False: continue if e[0] > -1 and e[1] > -1 and checkInRange(WorldRange,v1[0],v1[1])==False and checkInRange(WorldRange,v2[0],v2[1])==False: continue if e[0] < 0 or checkInRange(WorldRange,v1[0],v1[1])==False: v1=getExtreme(lines[l],v2, LR=0) if len(prev_extreme)==0: prev_extreme=v1 else: extreme_points=linkExtremes(prev_extreme, v1, m_range) for extreme_pair in extreme_points: polygon.append(extreme_pair) if e[1] < 0 or checkInRange(WorldRange,v2[0],v2[1])==False : v2=getExtreme(lines[l],v1, LR=1) if len(prev_extreme)==0: prev_extreme=v2 else: extreme_points=linkExtremes(prev_extreme, v2, m_range) for extreme_pair in extreme_points: polygon.append(extreme_pair) if v1!=v2: polygon.append( (v1,v2) ) if len(polygon)==0: sys.stderr.write ("\nThis station does not have meaningful polygon:") sys.stderr.write (str(pts[ site_points[station] ])+" at "+str(site_points[station])+"\n") for l in ls: e=edge_dic[l] v1=vertices[e[0]] v2=vertices[e[1]] sys.stderr.write(str(e[0])+","+str(e[1])+"\n") sys.stderr.write(str(v1)+","+str(v2)+"\n") voronoi_lattice.pop(station) continue #print polygon try: result = list(polygonize( polygon )) except ValueError: #print "Wrong:", polygon #Delete invisible short lines point_to_replace=[] for line in polygon: d=math.hypot( line[0][0]-line[1][0], line[0][1]-line[1][1]) if d<1: polygon.remove(line) point_to_replace=line i=0 New_Lines=[] for line in polygon: New_Lines.append(list(line)) j=0 for point in line: if point==point_to_replace[0]: #print line, point_to_replace New_Lines[i][j]=point_to_replace[1] j+=1 i+=1 polygon=tuple(New_Lines) #I could not figure out why sometimes it fails to draw a polygon. try: result = list(polygonize( polygon )) except: voronoi_lattice.pop(station) continue finalpoly=result[0] #print list(finalpoly.exterior.coords) #voronoi_lattice[station]["polygon"]=list(finalpoly.exterior.coords) voronoi_lattice[station]["obj_polygon"]=finalpoly #print polygon if (PlotIt): for station, data in voronoi_lattice.items(): x=[] y=[] #print data try: polygon_data=data["obj_polygon"] #print polygon_data for point in list(polygon_data.exterior.coords): x.append(point[0]) y.append(point[1]) except: print "Error", data["name"] #if station == 8 : #plot(x,y) fill(x,y, alpha=0.6) plot(data["coordinate"][0],data["coordinate"][1]) #text(data["coordinate"][0],data["coordinate"][1],data["info"]) show() return voronoi_lattice
def GenerateVoronoi(CurrentDate, PointsMap): currenttime=time.time() Sitepts = [] pts = {} #print CurrentDate, PointsMap[PointsMap.keys()[0]] for grid, stations in PointsMap.items(): for stn in stations: x=int(stn[2]) y=int(stn[1]) station=[stn[0]] station.extend( stn[3:]) #print x,y,station if checkInRange(WorldRange,x,y)==False: #print x,y continue pts[ (x,y) ]=station stncounts=len(pts.keys()) #print stncounts, "points" site_points=[] for pt in pts.keys(): Sitepts.append(voronoi.Site(pt[0],pt[1])) site_points.append( (pt[0],pt[1]) ) #print "Calculating Voronoi Lattice", siteList = voronoi.SiteList(Sitepts) context = voronoi.Context() voronoi.Edge.EDGE_NUM=0 #what the hell why should I initialize it? voronoi.voronoi(siteList,context) vertices=context.vertices lines=context.lines edges=context.edges #print edges #For Faster Access edge_dic={} for edge in edges: edge_dic[edge[0]]=edge[1:] triangles=context.triangles has_edge=context.has_edge voronoi_lattice={} m_range={} m_range["max_x"]=-9999999999 m_range["max_y"]=-9999999999 m_range["min_x"]=9999999999 m_range["min_y"]=9999999999 #Get the range!! for pnt in site_points: m_range=update_maxmin(m_range, pnt[0], pnt[1]) #print "Getting the Polygons" prev_percent=0 for station, ls in has_edge.items(): voronoi_lattice[station]={} voronoi_lattice[station]["coordinate"]=site_points[station] voronoi_lattice[station]["info"]=pts[ site_points[station] ] polygon=[] prev_extreme=[] Verbose=True if Verbose: current_percent=int(station/float(stncounts)*100) if current_percent!=prev_percent: #print station,"/", stncounts, current_percent, "% Done" timeelapse=time.time()-currenttime #print station, timeelapse currenttime=time.time() prev_percent=current_percent #For every lines that the station owns for l in ls: e=edge_dic[l] v1=vertices[e[0]] v2=vertices[e[1]] if e[0] < 0 and checkInRange(WorldRange,v2[0],v2[1])==False: continue if e[1] < 0 and checkInRange(WorldRange,v1[0],v1[1])==False: continue if e[0] > -1 and e[1] > -1 and checkInRange(WorldRange,v1[0],v1[1])==False and checkInRange(WorldRange,v2[0],v2[1])==False: continue if e[0] < 0 or checkInRange(WorldRange,v1[0],v1[1])==False: v1=getExtreme(lines[l],v2, LR=0) if len(prev_extreme)==0: prev_extreme=v1 else: extreme_points=linkExtremes(prev_extreme, v1, m_range) for extreme_pair in extreme_points: polygon.append(extreme_pair) if e[1] < 0 or checkInRange(WorldRange,v2[0],v2[1])==False : v2=getExtreme(lines[l],v1, LR=1) if len(prev_extreme)==0: prev_extreme=v2 else: extreme_points=linkExtremes(prev_extreme, v2, m_range) for extreme_pair in extreme_points: polygon.append(extreme_pair) if v1!=v2: polygon.append( (v1,v2) ) #This happened only once for 195612: ['999999-68601', 'BEARDMORE CAMP', 'AY', 'AY'] at (-164667, -85033) if len(polygon)==0: voronoi_lattice.pop(station) continue #print polygon try: result = list(polygonize( polygon )) except ValueError: #print "Wrong:", polygon #Delete invisible short lines point_to_replace=[] for line in polygon: d=math.hypot( line[0][0]-line[1][0], line[0][1]-line[1][1]) if d<1: polygon.remove(line) point_to_replace=line i=0 New_Lines=[] for line in polygon: New_Lines.append(list(line)) j=0 for point in line: if point==point_to_replace[0]: #print line, point_to_replace New_Lines[i][j]=point_to_replace[1] j+=1 i+=1 sys.stderr.write(str(polygon)) polygon=tuple(New_Lines) sys.stderr.write(str(polygon)) result = list(polygonize( polygon )) finalpoly=result[0] #print list(finalpoly.exterior.coords) #voronoi_lattice[station]["polygon"]=list(finalpoly.exterior.coords) voronoi_lattice[station]["obj_polygon"]=finalpoly #print polygon return voronoi_lattice
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib import numpy as np from voronoi import voronoi import matplotlib.pyplot as plt X, Y = np.meshgrid(np.linspace(-0.1, 1.1, 25), np.linspace(-0.1, 1.1, 25)) X = X.ravel() + np.random.uniform(-0.025, 0.025, X.size) Y = Y.ravel() + np.random.uniform(-0.025, 0.025, Y.size) cells, triangles, circles = voronoi(X, Y) fig = plt.figure(figsize=(8, 6)) axes = plt.subplot(111, aspect=1) for cell in cells: codes = ( [matplotlib.path.Path.MOVETO] + [matplotlib.path.Path.LINETO] * (len(cell) - 2) + [matplotlib.path.Path.CLOSEPOLY] ) path = matplotlib.path.Path(cell, codes) color = np.random.uniform(0.4, 0.9, 3) patch = matplotlib.patches.PathPatch(path, facecolor=color, edgecolor="w", zorder=-1) axes.add_patch(patch) plt.axis([0, 1, 0, 1]) plt.xticks([]), plt.yticks([]) plt.show()
def processAlgorithm(self, progress): layer = dataobjects.getObjectFromUri(self.getParameterValue( self.INPUT)) buf = self.getParameterValue(self.BUFFER) writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( layer.pendingFields().toList(), QGis.WKBPolygon, layer.crs()) inFeat = QgsFeature() outFeat = QgsFeature() extent = layer.extent() extraX = extent.height() * (buf / 100.0) extraY = extent.width() * (buf / 100.0) height = extent.height() width = extent.width() c = voronoi.Context() pts = [] ptDict = {} ptNdx = -1 features = vector.features(layer) for inFeat in features: geom = QgsGeometry(inFeat.geometry()) point = geom.asPoint() x = point.x() - extent.xMinimum() y = point.y() - extent.yMinimum() pts.append((x, y)) ptNdx += 1 ptDict[ptNdx] = inFeat.id() if len(pts) < 3: raise GeoAlgorithmExecutionException( 'Input file should contain at least 3 points. Choose \ another file and try again.') uniqueSet = Set(item for item in pts) ids = [pts.index(item) for item in uniqueSet] sl = voronoi.SiteList([ voronoi.Site(i[0], i[1], sitenum=j) for (j, i) in enumerate(uniqueSet) ]) voronoi.voronoi(sl, c) inFeat = QgsFeature() current = 0 total = 100.0 / float(len(c.polygons)) for (site, edges) in c.polygons.iteritems(): request = QgsFeatureRequest().setFilterFid(ptDict[ids[site]]) inFeat = layer.getFeatures(request).next() lines = self.clip_voronoi(edges, c, width, height, extent, extraX, extraY) geom = QgsGeometry.fromMultiPoint(lines) geom = QgsGeometry(geom.convexHull()) outFeat.setGeometry(geom) outFeat.setAttributes(inFeat.attributes()) writer.addFeature(outFeat) current += 1 progress.setPercentage(int(current * total)) del writer
# Plot string for k, gk in enumerate(xrange(1, 3)): # Draw contour map of potential im = grid[gk].contourf(X, Y, V, clines, cmap=my_cmap) # Draw circles defining state boundaries cirA = plt.Circle((-3, 0), radius=1.0, ec='k', fill=False, lw=0.5) cirB = plt.Circle((3, 0), radius=1.0, ec='k', fill=False, lw=0.5) grid[gk].add_patch(cirA) grid[gk].add_patch(cirB) if k == 0: cen = centers[:ncenters, :] else: cen = centers[ncenters:, :] grid[gk].plot(cen[:, 0], cen[:, 1], 'k.-', lw=1, ms=2, marker='o') segments = voronoi.voronoi(cen[:, 0], cen[:, 1]) lines = mpl.collections.LineCollection(segments, color='k', lw=0.5) grid[gk].add_collection(lines) grid[gk].axis([-5, 5, -5, 5]) grid[2].cax.colorbar(im) grid[2].cax.toggle_label(True) #plt.show() plt.savefig('potential_string.eps', dpi=600, format='eps', bbox_inches='tight')