当前位置: 首页>>代码示例>>Python>>正文


Python voronoi.voronoi函数代码示例

本文整理汇总了Python中voronoi.voronoi函数的典型用法代码示例。如果您正苦于以下问题:Python voronoi函数的具体用法?Python voronoi怎么用?Python voronoi使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了voronoi函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: processAlgorithm

    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
开发者ID:Ariki,项目名称:QGIS,代码行数:60,代码来源:VoronoiPolygons.py

示例2: delaunay_triangulation

  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
开发者ID:geonux,项目名称:Quantum-GIS,代码行数:58,代码来源:doGeometry.py

示例3: processAlgorithm

 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
开发者ID:mokerjoke,项目名称:Quantum-GIS,代码行数:52,代码来源:Delaunay.py

示例4: voronoi_polygons

 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
开发者ID:afrigeo,项目名称:Quantum-GIS,代码行数:49,代码来源:doGeometry.py

示例5: display

 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()
开发者ID:brianhouse,项目名称:quotidio,代码行数:30,代码来源:science.py

示例6: processAlgorithm

 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
开发者ID:mokerjoke,项目名称:Quantum-GIS,代码行数:45,代码来源:VoronoiPolygons.py

示例7: delaunay

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)
开发者ID:dladd,项目名称:pyFormex,代码行数:9,代码来源:polygon.py

示例8: computeWalls

    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
开发者ID:valrus,项目名称:tone_poem,代码行数:40,代码来源:map.py

示例9: compute

    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)
开发者ID:JulienLeonard,项目名称:PVG,代码行数:13,代码来源:voronoiutils.py

示例10: VoronoiLineEdges

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
开发者ID:mbourqui,项目名称:py_geo_voronoi,代码行数:38,代码来源:voronoi_poly.py

示例11: learn

    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()
开发者ID:CLLAR117,项目名称:neural-networks,代码行数:18,代码来源:neural_gas.py

示例12: voronoi_polygons

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)
开发者ID:kadubarbosa,项目名称:hydra1,代码行数:39,代码来源:voronoi_polygons.py

示例13: quantize

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
开发者ID:mathnathan,项目名称:smartQuantization,代码行数:24,代码来源:preprocessing.py

示例14: effect

    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)
#.........这里部分代码省略.........
开发者ID:AakashDabas,项目名称:inkscape,代码行数:101,代码来源:generate_voronoi.py

示例15: processAlgorithm

    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
开发者ID:Jesonchang12,项目名称:QGIS,代码行数:63,代码来源:Delaunay.py


注:本文中的voronoi.voronoi函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。