コード例 #1
0
    def draw(self):
        background(0, 0, 0)
        
        # clear grid lists
        for i in range(0, self.numrows):
            for j in range(0, self.numcols):
                #self.grid[i][j] = list()
                del self.grid[i][j][:]
        
        # register agents in grid
        for agent in self.agents:
            row = int(agent.pos.y/self.gridsize)
            col = int(agent.pos.x/self.gridsize)
            self.grid[row][col].append(agent)
            
        agent_positions = list()

        for agent in self.agents:
            agent_positions.append(agent.pos)

            agent.draw()
            
            nearby = list()
            row = int(agent.pos.y/self.gridsize)
            col = int(agent.pos.x/self.gridsize)
            nearby.extend(self.grid[row % self.numrows-1][col % self.numcols-1])
            nearby.extend(self.grid[row+1 % self.numrows-1][col+1 % self.numcols-1])
            nearby.extend(self.grid[row+1 % self.numrows-1][col % self.numcols-1])
            nearby.extend(self.grid[row % self.numrows-1][col+1 % self.numcols-1])
            nearby.extend(self.grid[row-1 % self.numrows-1][col-1 % self.numcols-1])
            nearby.extend(self.grid[row-1 % self.numrows-1][col % self.numcols-1])
            nearby.extend(self.grid[row % self.numrows-1][col-1 % self.numcols-1])
            nearby.extend(self.grid[row+1 % self.numrows-1][col-1 % self.numcols-1])
            nearby.extend(self.grid[row-1 % self.numrows-1][col+1 % self.numcols-1])

            if mousePressed:
                target = PVector(mouseX, mouseY)
                agent.seek(target)

            agent.cognate(nearby)
            
            agent.move()
            agent.reset_acceleration() # whoops
            
        v = voronoi.computeVoronoiDiagram(agent_positions)
        lines = v[1]
        vertices = v[0]
        stroke(255, 255, 255)
        for l in lines:
            v1index = l[1]
            v2index = l[2]
            if v1index != -1 and v2index != -1:
                p1 = vertices[v1index]
                p2 = vertices[v2index]
                line(p1[0], p1[1], p2[0], p2[1])
コード例 #2
0
ファイル: honey.py プロジェクト: lealbaugh/honeyclasps
def plotVoronoi(points):
	results = voronoi.computeVoronoiDiagram(preparePoints(points))
	curves = []
	print "number of edges: "+str(len(results[2]))
	for edge in results[2]:
		if edge[1] != -1 and edge[2] != -1:
			startx = decimate(results[0][edge[1]][0])
			starty = decimate(results[0][edge[1]][1])
			endx = decimate(results[0][edge[2]][0])
			endy = decimate(results[0][edge[2]][1])
			startpoint = [startx, starty, 0]
			endpoint = [endx, endy, 0]
			curves.append(rs.AddLine(startpoint, endpoint))
	return curves
コード例 #3
0
ファイル: voronoi2svg.py プロジェクト: suman95/inkscape
  def effect(self):

    #{{{ Check that elements have been selected

    if len(self.options.ids) == 0:
      inkex.errormsg(_("Please select objects!"))
      return

    #}}}

    #{{{ Drawing styles

    linestyle = {
        'stroke'       : '#000000',
        'stroke-width' : str(self.unittouu('1px')),
        'fill'         : 'none'
        }

    facestyle = {
        'stroke'       : '#ff0000',
        'stroke-width' : str(self.unittouu('1px')),
        'fill'         : 'none'
        }

    #}}}

    #{{{ Handle the transformation of the current group
    parentGroup = self.getParentNode(self.selected[self.options.ids[0]])

    trans = self.getGlobalTransform(parentGroup)
    invtrans = None
    if trans:
      invtrans = simpletransform.invertTransform(trans)

    #}}}

    #{{{ Recovery of the selected objects

    pts = []
    nodes = []
    seeds = []


    for id in self.options.ids:
      node = self.selected[id]
      nodes.append(node)
      bbox = simpletransform.computeBBox([node])
      if bbox:
        cx = 0.5*(bbox[0]+bbox[1])
        cy = 0.5*(bbox[2]+bbox[3])
        pt = [cx,cy]
        if trans:
          simpletransform.applyTransformToPoint(trans,pt)
        pts.append(Point(pt[0],pt[1]))
        seeds.append(Point(cx,cy))

    #}}}

    #{{{ Creation of groups to store the result

    if self.options.diagramType != 'Delaunay':
      # Voronoi
      groupVoronoi = inkex.etree.SubElement(parentGroup,inkex.addNS('g','svg'))
      groupVoronoi.set(inkex.addNS('label', 'inkscape'), 'Voronoi')
      if invtrans:
        simpletransform.applyTransformToNode(invtrans,groupVoronoi)
    if self.options.diagramType != 'Voronoi':
      # Delaunay
      groupDelaunay = inkex.etree.SubElement(parentGroup,inkex.addNS('g','svg'))
      groupDelaunay.set(inkex.addNS('label', 'inkscape'), 'Delaunay')

    #}}}

    #{{{ Clipping box handling

    if self.options.diagramType != 'Delaunay':
      #Clipping bounding box creation
      gBbox = simpletransform.computeBBox(nodes)

      #Clipbox is the box to which the Voronoi diagram is restricted
      clipBox = ()
      if self.options.clipBox == 'Page':
        svg = self.document.getroot()
        w = self.unittouu(svg.get('width'))
        h = self.unittouu(svg.get('height'))
        clipBox = (0,w,0,h)
      else:
        clipBox = (2*gBbox[0]-gBbox[1],
                   2*gBbox[1]-gBbox[0],
                   2*gBbox[2]-gBbox[3],
                   2*gBbox[3]-gBbox[2])
      
      #Safebox adds points so that no Voronoi edge in clipBox is infinite
      safeBox = (2*clipBox[0]-clipBox[1],
                 2*clipBox[1]-clipBox[0],
                 2*clipBox[2]-clipBox[3],
                 2*clipBox[3]-clipBox[2])
      pts.append(Point(safeBox[0],safeBox[2]))
      pts.append(Point(safeBox[1],safeBox[2]))
      pts.append(Point(safeBox[1],safeBox[3]))
      pts.append(Point(safeBox[0],safeBox[3]))

      if self.options.showClipBox:
        #Add the clip box to the drawing
        rect = inkex.etree.SubElement(groupVoronoi,inkex.addNS('rect','svg'))
        rect.set('x',str(clipBox[0]))
        rect.set('y',str(clipBox[2]))
        rect.set('width',str(clipBox[1]-clipBox[0]))
        rect.set('height',str(clipBox[3]-clipBox[2]))
        rect.set('style',simplestyle.formatStyle(linestyle))

    #}}}

    #{{{ Voronoi diagram generation

    if self.options.diagramType != 'Delaunay':
      vertices,lines,edges = voronoi.computeVoronoiDiagram(pts)
      for edge in edges:
        line = edge[0]
        vindex1 = edge[1]
        vindex2 = edge[2]
        if (vindex1 <0) or (vindex2 <0):
          continue # infinite lines have no need to be handled in the clipped box
        else:
          segment = self.clipEdge(vertices,lines,edge,clipBox)
          #segment = [vertices[vindex1],vertices[vindex2]] # deactivate clipping
          if len(segment)>1:
            v1 = segment[0]
            v2 = segment[1]
            cmds = [['M',[v1[0],v1[1]]],['L',[v2[0],v2[1]]]]
            path = inkex.etree.Element(inkex.addNS('path','svg'))
            path.set('d',simplepath.formatPath(cmds))
            path.set('style',simplestyle.formatStyle(linestyle))
            groupVoronoi.append(path)

    if self.options.diagramType != 'Voronoi':
      triangles = voronoi.computeDelaunayTriangulation(seeds)
      for triangle in triangles:
        p1 = seeds[triangle[0]]
        p2 = seeds[triangle[1]]
        p3 = seeds[triangle[2]]
        cmds = [['M',[p1.x,p1.y]],
                ['L',[p2.x,p2.y]],
                ['L',[p3.x,p3.y]],
                ['Z',[]]]
        path = inkex.etree.Element(inkex.addNS('path','svg'))
        path.set('d',simplepath.formatPath(cmds))
        path.set('style',simplestyle.formatStyle(facestyle))
        groupDelaunay.append(path)
コード例 #4
0
ファイル: doodle.py プロジェクト: keyolk/public
  def __init__(self, width, height):
    self.width = width
    self.height = height
    self.size = (width, height)

    spacing = 50
    num_points = ((width * 3 ) * (height * 3) / spacing / spacing)

    # Randomly choose points
    corners = [
      (0,0),
      (0, width - 1),
      (height - 1, width - 1),
      (height - 1, 0),
    ]
    points = set(corners)
    for _ in range(int(num_points * 5)):
      new_p = (random.randint(- width, width * 2),
          random.randint(- width, height * 2))
      if all((distance(new_p, p) > spacing for p in points)):
        points.add(new_p)
        print num_points - len(points)
      else:
        print '*',
    for corner in corners:
      points.remove(corner)
    points = list(points)
    points.extend(corners)
    num_points = len(points)

#    # Spread points out using inverse-square repulsion
#    multiplier = 1500.0
#    steps = int(num_points ** 2)
#    multiplier_step = 1.0 / steps
#    for _ in range(steps):
#      i = random.randint(0, num_points - 1 - len(corners))
#      point = points[i]
#      force = [0, 0]
#      for j in range(num_points):
#        if j != i:
#          other = points[j]
#          dist = float(distance(point, other))
#          other_force = 1.0 / float(dist * dist)
#          other_force = (
#            (point[0] - other[0]) / dist * other_force,
#            (point[1] - other[1]) / dist * other_force)
#          force[0] += other_force[0]
#          force[1] += other_force[1]
#      points[i] = (
#          point[0] + force[0] * multiplier,
#          point[1] + force[1] * multiplier)
#      multiplier -= multiplier_step
#    self.points = points

    # Generate voronoi diagram for points
    self.vpoints, self.vlines, self.vedges = voronoi.computeVoronoiDiagram(points)

    # # Generate Delaunay triangulation. Turns out that this doesn't
    # # look nearly as nice.
    # triangles = voronoi.computeDelaunayTriangulation(points)
    # self.vpoints = points
    # self.vedges = []
    # for a, b, c in triangles:
    #   self.vedges.append((None, a, b))
    #   self.vedges.append((None, b, c))
    #   self.vedges.append((None, c, a))

    # generate adjacency mapping
    adjacency_map = {}
    def addNeighbor(k, v):
      pk = self.vpoints[k]
      pv = self.vpoints[v]
      if inside(pk, vec_mul(-.5, self.size), vec_mul(1.5, self.size)):
        adjacency_map.setdefault(k, set()).add(v)
    for l, p1, p2 in self.vedges:
      addNeighbor(p1, p2)
      addNeighbor(p2, p1)

    # straighten edges
    npoints = self.vpoints[:]
    straigtenings = [0] * len(npoints)
    spaz = [0.0] * len(npoints)
    todo = set(adjacency_map.keys())
    spaz = []
    for _ in range(len(todo) ** 2):
      if not todo: break
      try:
        i = random.choice(tuple(todo))
        todo.remove(i)
        best = math.pi

        # Straighten any angle, even those that cut across another
        # angle. This can sometimes cause "straightening of the cross"
        neighbors = tuple(adjacency_map[i])
        for j in neighbors:
          for k in neighbors:
            if j == k: continue

#        # Straighten angles only between neighbors that are "adjacent"
#        # when going around the circle. ie: "pie slice" angles.
#        neighbors = list(adjacency_map[i])
#        neighbors.sort(key=lambda x:normangle(theta(npoints[i], npoints[x])))
#        neighbors = tuple(neighbors)
#        for j_idx, j in enumerate(neighbors):
#          for k_idx in ((j_idx +1) % len(neighbors)), ((j_idx - 1) % len(neighbors)):
#            k = neighbors[k_idx]

            th_j = theta(npoints[i], npoints[j])
            th_k = theta(npoints[i], npoints[k])
            bent = abs(normangle(th_j - th_k) - math.pi)
            if bent < best:
              best = bent
              best_j = j
              best_k = k

#        # Straighten random angle
#        neighbors = tuple(adjacency_map[i])
#        best_j, best_k = random.sample(neighbors, 2)

        new_point = project_on_segment(npoints[i], npoints[best_j], npoints[best_k])
        if distance(new_point, npoints[i]) > 0.1:
          straigtenings[i] += 1
          npoints[i] = new_point
          for neighbor in neighbors:
            if neighbor in adjacency_map:
              todo.add(neighbor)
          print len(todo)
      except KeyboardInterrupt:
        break
    self.npoints = npoints
    self.straigtenings = straigtenings
    self.todo = todo
コード例 #5
0
ファイル: voronoi_xfig.py プロジェクト: aziot/voronoi_xfig
def drawVoronoiDiagram(printToFile, gridSideLength,*highlightedPoints):
 global points;

 hPoints = []
 if len(highlightedPoints) > 0:
 assert 0 == len(highlightedPoints) % 2
 hPoints.append(Point(highlightedPoints[0],highlightedPoints[1]))
 hPoints.append(Point(highlightedPoints[2],highlightedPoints[3]))
 
 if printToFile:
 printMethod=goo(printToFile)
 else:
 printMethod=foo


 preamble(printMethod);
 
 printMethod('# SCALE %d' % (SCALE,))
 printMethod('# GRID_SIDE_LENGTH %d' % (gridSideLength))

 radius_x = SCALE/60;
 radius_y = radius_x;

 for point in points:
 if point in hPoints:
 printMethod('1 3 0 1 0 18 50 -1 20 0.000 1 0.0000 %d %d %d %d %d %d %d %d' % (SCALE*point.x, SCALE*point.y, radius_x, radius_y, SCALE*point.x-radius_x, SCALE*point.y, SCALE*point.x+radius_x, SCALE*point.y))
 else:
 printMethod('1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 %d %d %d %d %d %d %d %d' % (SCALE*point.x, SCALE*point.y, radius_x, radius_y, SCALE*point.x-radius_x, SCALE*point.y, SCALE*point.x+radius_x, SCALE*point.y))
 #printMethod('4 0 0 0 0 0 1 0 0 1 1 %d %d 65 66 65 66 \ 0 0 1' % (SCALE*point.x, SCALE*point.y))

 pencolorVoronoiEdge = 0
 linestyleVoronoiEdge = -1

 printMethod('2 1 %s 2 %s 7 50 -1 -1 0.000 0 0 -1 0 0 2' % (linestyleVoronoiEdge,pencolorVoronoiEdge))
 printMethod('\t 0 0 0 %d' % (SCALE*gridSideLength,))
 printMethod('2 1 %s 2 %s 7 50 -1 -1 0.000 0 0 -1 0 0 2' % (linestyleVoronoiEdge,pencolorVoronoiEdge))
 printMethod('\t 0 0 %d 0' % (SCALE*gridSideLength,))
 printMethod('2 1 %s 2 %s 7 50 -1 -1 0.000 0 0 -1 0 0 2' % (linestyleVoronoiEdge,pencolorVoronoiEdge))
 printMethod('\t %d %d %d 0' % (SCALE*gridSideLength,SCALE*gridSideLength,SCALE*gridSideLength))
 printMethod('2 1 %s 2 %s 7 50 -1 -1 0.000 0 0 -1 0 0 2' % (linestyleVoronoiEdge,pencolorVoronoiEdge))
 printMethod('\t %d %d 0 %d' % (SCALE*gridSideLength,SCALE*gridSideLength,SCALE*gridSideLength))

 vertices,lines,edges = voronoi.computeVoronoiDiagram(points)
 voronoiEdge = '2 1 %s 2 %s 7 50 -1 -1 0.000 0 0 -1 0 0 2' % (linestyleVoronoiEdge, pencolorVoronoiEdge)
 for line,v1,v2 in edges:
 if v1 != -1 and v2 != -1:
 printMethod(voronoiEdge)
 printMethod('\t %d %d %d %d' % (SCALE*vertices[v1][0], SCALE*vertices[v1][1], SCALE*vertices[v2][0], SCALE*vertices[v2][1]))

points = []

def readTopologyFromFile(inFile):
 global points

 inHandle = open(inFile, 'r')
 for line in inHandle:
 if line.startswith('1 '):
 lineSplit = line.split()
 points.append(Point(float(lineSplit[12])/float(SCALE),float(lineSplit[13])/float(SCALE)))

 inHandle.close()

def createTopology(numPoints,gridDimension):
 for point in range(numPoints):
 point = Point(default='yes')
 point.x = random.random()*gridDimension
 point.y = random.random()*gridDimension
 points.append(point)

if __name__ == "__main__":
 """ The format of .fig files is described in http://www.xfig.org/userman/fig-format.html"""

 createTopology(150,5)
 drawVoronoiDiagram(None,5)
コード例 #6
0
ファイル: voronoi_xfig.py プロジェクト: aziot/voronoi_xfig
def computeVoronoiDiagram():
 global points;
 return voronoi.computeVoronoiDiagram(points);
コード例 #7
0
ファイル: voronoi2svg.py プロジェクト: wachin/inkscape
    def effect(self):
        # Check that elements have been selected
        if not self.svg.selected:
            inkex.errormsg(_("Please select objects!"))
            return

        linestyle = {
            'stroke': '#000000',
            'stroke-width': str(self.svg.unittouu('1px')),
            'fill': 'none',
            'stroke-linecap': 'round',
            'stroke-linejoin': 'round'
        }

        facestyle = {
            'stroke': '#000000',
            'stroke-width': str(self.svg.unittouu('1px')),
            'fill': 'none',
            'stroke-linecap': 'round',
            'stroke-linejoin': 'round'
        }

        parent_group = self.svg.selection.first().getparent()
        trans = parent_group.composed_transform()

        invtrans = None
        if trans:
            invtrans = -trans

        # Recovery of the selected objects
        pts = []
        nodes = []
        seeds = []
        fills = []

        for node in self.svg.selected.values():
            nodes.append(node)
            bbox = node.bounding_box()
            if bbox:
                center_x, center_y = bbox.center
                point = [center_x, center_y]
                if trans:
                    point = trans.apply_to_point(point)
                pts.append(Point(*point))
                if self.options.delaunayFillOptions != "delaunay-no-fill":
                    fills.append(node.style.get('fill', 'none'))
                seeds.append(Point(center_x, center_y))

        # Creation of groups to store the result
        if self.options.diagramType != 'Delaunay':
            # Voronoi
            group_voronoi = parent_group.add(Group())
            group_voronoi.set('inkscape:label', 'Voronoi')
            if invtrans:
                group_voronoi.transform *= invtrans
        if self.options.diagramType != 'Voronoi':
            # Delaunay
            group_delaunay = parent_group.add(Group())
            group_delaunay.set('inkscape:label', 'Delaunay')

        # Clipping box handling
        if self.options.diagramType != 'Delaunay':
            # Clipping bounding box creation
            group_bbox = sum([node.bounding_box() for node in nodes], None)

            # Clipbox is the box to which the Voronoi diagram is restricted
            if self.options.clip_box == 'Page':
                svg = self.document.getroot()
                width = self.svg.unittouu(svg.get('width'))
                height = self.svg.unittouu(svg.get('height'))
                clip_box = (0, width, 0, height)
            else:
                clip_box = (group_bbox.left,
                            group_bbox.right,
                            group_bbox.top,
                            group_bbox.bottom)

            # Safebox adds points so that no Voronoi edge in clip_box is infinite
            safe_box = (2 * clip_box[0] - clip_box[1],
                        2 * clip_box[1] - clip_box[0],
                        2 * clip_box[2] - clip_box[3],
                        2 * clip_box[3] - clip_box[2])
            pts.append(Point(safe_box[0], safe_box[2]))
            pts.append(Point(safe_box[1], safe_box[2]))
            pts.append(Point(safe_box[1], safe_box[3]))
            pts.append(Point(safe_box[0], safe_box[3]))

            if self.options.showClipBox:
                # Add the clip box to the drawing
                rect = group_voronoi.add(Rectangle())
                rect.set('x', str(clip_box[0]))
                rect.set('y', str(clip_box[2]))
                rect.set('width', str(clip_box[1] - clip_box[0]))
                rect.set('height', str(clip_box[3] - clip_box[2]))
                rect.style = linestyle

        # Voronoi diagram generation
        if self.options.diagramType != 'Delaunay':
            vertices, lines, edges = voronoi.computeVoronoiDiagram(pts)
            for edge in edges:
                vindex1, vindex2 = edge[1:]
                if (vindex1 < 0) or (vindex2 < 0):
                    continue  # infinite lines have no need to be handled in the clipped box
                else:
                    segment = self.clip_edge(vertices, lines, edge, clip_box)
                    # segment = [vertices[vindex1],vertices[vindex2]] # deactivate clipping
                    if len(segment) > 1:
                        x1, y1 = segment[0]
                        x2, y2 = segment[1]
                        cmds = [['M', [x1, y1]], ['L', [x2, y2]]]
                        path = group_voronoi.add(PathElement())
                        path.set('d', str(inkex.Path(cmds)))
                        path.style = linestyle

        if self.options.diagramType != 'Voronoi':
            triangles = voronoi.computeDelaunayTriangulation(seeds)
            i = 0
            if self.options.delaunayFillOptions == "delaunay-fill":
                random.seed("inkscape")
            for triangle in triangles:
                pt1 = seeds[triangle[0]]
                pt2 = seeds[triangle[1]]
                pt3 = seeds[triangle[2]]
                cmds = [['M', [pt1.x, pt1.y]],
                        ['L', [pt2.x, pt2.y]],
                        ['L', [pt3.x, pt3.y]],
                        ['Z', []]]
                if self.options.delaunayFillOptions == "delaunay-fill" \
                    or self.options.delaunayFillOptions == "delaunay-fill-random":
                    facestyle = {
                        'stroke': fills[triangle[random.randrange(0, 2)]],
                        'stroke-width': str(self.svg.unittouu('0.005px')),
                        'fill': fills[triangle[random.randrange(0, 2)]],
                        'stroke-linecap': 'round',
                        'stroke-linejoin': 'round'
                    }
                path = group_delaunay.add(PathElement())
                path.set('d', str(inkex.Path(cmds)))
                path.style = facestyle
                i += 1
コード例 #8
0
ファイル: galaxy.py プロジェクト: magmun/client
 def computeVoronoi(self):
     self.coords, self.equation, self.edges, self.bounds = computeVoronoiDiagram(self.control_points)
     self.voronoi = computeVoronoiDiagram(self.control_points)
     self.computePolys()
コード例 #9
0
ファイル: node_Voronoi2D.py プロジェクト: ly29/sverchok
    def update(self):
        # inputs
        if 'Edges' in self.outputs and self.outputs['Edges'].links or \
            'Vertices' in self.outputs and self.outputs['Vertices'].links:
        
            if 'Vertices' in self.inputs and self.inputs['Vertices'].links:
                points_in = SvGetSocketAnyType(self,self.inputs['Vertices'])
        
            pts_out = []
    #        polys_out = []
            edges_out = []
            for obj in points_in:
                pt_list = []
                x_max = obj[0][0]
                x_min = obj[0][0]
                y_min = obj[0][1]
                y_max = obj[0][1]
                #creates points in format for voronoi library, throwing away z
                for pt in obj:     
                    x,y = pt[0],pt[1]
                    x_max = max(x,x_max)
                    x_min = min(x,x_min)
                    y_max = max(y,y_max)
                    y_min = min(x,x_min)
                    pt_list.append(Site(pt[0],pt[1]))
            
                res = computeVoronoiDiagram(pt_list)
                                
                edges = res[2]
                delta = self.clip
                x_max = x_max + delta
                y_max = y_max + delta
            
                x_min = x_min - delta
                y_min = y_min - delta
            
                #clipping box to bounding box.
                pts_tmp = []
                for pt in res[0]:
                    x,y=pt[0],pt[1]
                    if x < x_min:
                        x = x_min
                    if x > x_max:
                        x = x_max
                
                    if y < y_min:
                        y = y_min
                    if y > y_max:
                        y = y_max
                    pts_tmp.append((x,y,0))
                
                pts_out.append(pts_tmp)                 
                    
                edges_out.append([ (edge[1], edge[2]) for edge in edges if -1 not in edge ])
                     

            # outputs
            if 'Vertices' in self.outputs and self.outputs['Vertices'].links:
                SvSetSocketAnyType(self, 'Vertices', pts_out)
   
            if 'Edges' in self.outputs and self.outputs['Edges'].links:             
                SvSetSocketAnyType(self,'Edges',edges_out)
コード例 #10
0
ファイル: draw_germany_plz.py プロジェクト: FreeBugs/pyGeoDb
    y.append(lat)
ctx.init_geoscale(min(x), max(x) - min(x), min(y), max(y) - min(y))
ctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
ctx.set_line_width(0.3 * c.ctxscale)

# see http://lists.cairographics.org/archives/cairo/2009-June/017459.html for drawing points
for plz, (long, lat, name) in geoitems:
    ctx.move_to(*ctx.geoscale(long, lat))
    ctx.close_path()
ctx.stroke()

pts = []
for plz, (long, lat, name) in geoitems:
    pts.append(voronoi.Site(long, lat))

points, lines, edges = voronoi.computeVoronoiDiagram(pts)

pprint(points)
pprint(lines)
pprint(edges)

ctx.set_line_width(0.1 * c.ctxscale)

for (l, p1, p2) in edges:
    x1 = y1 = x2 = y2 = None
    if p1 > -1:
        x1, y1 = points[p1]
    if p2 > -1:
        x2, y2 = points[p2]
    if p1 > -1 and p2 > -1:
        print("(%f, %f) -> (%f, %f)" % (x1, y1, x2, y2))
コード例 #11
0
 def voronoi_tesselation(self, writer, provider, points):
     coords, equation, edges, bounds = voronoi.computeVoronoiDiagram(points)
     all_attrs = provider.attributeIndexes()
     provider.select(all_attrs)
     feat = QgsFeature()
     count = 0
     for index, v1, v2 in edges:
         a, b, c = equation[index]
         x_0, y_0 = coords[v1]
         x_1, y_1 = coords[v2]
         if (v1 < 0 and x_1 in bounds and y_1 in bounds) or (v2 < 0 and x_0 in bounds and y_0 in bounds):
             continue
         if v1 < 0:
             if a == 1.0:
                 if b < 0:
                     y = bounds[1]
                 else:
                     y = bounds[3]
                 x = c - b * y
                 if x < bounds[0] or x > bounds[2]:
                     if x < bounds[0]:
                         x = bounds[0]
                     elif x > bounds[2]:
                         x = bounds[2]
                     y = (c - a * x) / b
             else:  # b == 1.0
                 if a > 0:
                     y = bounds[3]
                 else:
                     y = bounds[1]
                 x = (c - b * y) / a
                 if x < bounds[0] or x > bounds[2]:
                     if x < bounds[0]:
                         x = bounds[0]
                     elif x > bounds[2]:
                         x = bounds[2]
                     y = (c - a * x) / b
             x_0 = x
             y_0 = y
         elif v2 < 0:
             if a == 1.0:
                 if b > 0:
                     y = bounds[1]
                 else:
                     y = bounds[3]
                 x = c - b * y
                 if x < bounds[0] or x > bounds[2]:
                     if x < bounds[0]:
                         x = bounds[0]
                     elif x > bounds[2]:
                         x = bounds[2]
                     y = (c - a * x) / b
             else:  # b == 1.0
                 if a < 0:
                     x = bounds[0]
                 else:
                     x = bounds[2]
                 y = (c - a * x) / b
                 if y < bounds[1] or y > bounds[3]:
                     if y < bounds[1]:
                         y = bounds[1]
                     elif y > bounds[3]:
                         y = bounds[3]
                     x = (c - y * b) / a
             x_1 = x
             y_1 = y
         line = [QgsPoint(x_0, y_0), QgsPoint(x_1, y_1)]
         geometry = QgsGeometry().fromPolyline(line)
         feat.addAttribute(0, QVariant(count))
         feat.addAttribute(1, QVariant(a))
         feat.addAttribute(2, QVariant(b))
         feat.addAttribute(3, QVariant(c))
         feat.addAttribute(4, QVariant(v1))
         feat.addAttribute(5, QVariant(v2))
         feat.setGeometry(geometry)
         writer.addFeature(feat)
         count += 1
     rect = [
         QgsPoint(bounds[0], bounds[1]),
         QgsPoint(bounds[2], bounds[1]),
         QgsPoint(bounds[2], bounds[3]),
         QgsPoint(bounds[0], bounds[3]),
         QgsPoint(bounds[0], bounds[1]),
     ]
     geometry = QgsGeometry().fromPolyline(rect)
     feat.setGeometry(geometry)
     writer.addFeature(feat)
     del writer
コード例 #12
0
ファイル: galaxy.py プロジェクト: quark036/client
 def computeVoronoi(self):
     self.coords, self.equation, self.edges, self.bounds = computeVoronoiDiagram(
         self.control_points)
     self.voronoi = computeVoronoiDiagram(self.control_points)
     self.computePolys()
コード例 #13
0
ファイル: node_Voronoi2D.py プロジェクト: wclyffe/sverchok
    def update(self):
        # inputs
        if 'Edges' in self.outputs and self.outputs['Edges'].links or \
            'Vertices' in self.outputs and self.outputs['Vertices'].links:

            if 'Vertices' in self.inputs and self.inputs['Vertices'].links:
                points_in = SvGetSocketAnyType(self, self.inputs['Vertices'])

            pts_out = []
            #        polys_out = []
            edges_out = []
            for obj in points_in:
                pt_list = []
                x_max = obj[0][0]
                x_min = obj[0][0]
                y_min = obj[0][1]
                y_max = obj[0][1]
                #creates points in format for voronoi library, throwing away z
                for pt in obj:
                    x, y = pt[0], pt[1]
                    x_max = max(x, x_max)
                    x_min = min(x, x_min)
                    y_max = max(y, y_max)
                    y_min = min(x, x_min)
                    pt_list.append(Site(pt[0], pt[1]))

                res = computeVoronoiDiagram(pt_list)

                edges = res[2]
                delta = self.clip
                x_max = x_max + delta
                y_max = y_max + delta

                x_min = x_min - delta
                y_min = y_min - delta

                #clipping box to bounding box.
                pts_tmp = []
                for pt in res[0]:
                    x, y = pt[0], pt[1]
                    if x < x_min:
                        x = x_min
                    if x > x_max:
                        x = x_max

                    if y < y_min:
                        y = y_min
                    if y > y_max:
                        y = y_max
                    pts_tmp.append((x, y, 0))

                pts_out.append(pts_tmp)

                edges_out.append([(edge[1], edge[2]) for edge in edges
                                  if -1 not in edge])

            # outputs
            if 'Vertices' in self.outputs and self.outputs['Vertices'].links:
                SvSetSocketAnyType(self, 'Vertices', pts_out)

            if 'Edges' in self.outputs and self.outputs['Edges'].links:
                SvSetSocketAnyType(self, 'Edges', edges_out)
コード例 #14
0
ファイル: node_Voronoi2D.py プロジェクト: ccamara/sverchok
    def update(self):
        # inputs
        points_in = []
        if 'Vertices' in self.inputs and len(self.inputs['Vertices'].links)>0:
            if not self.inputs['Vertices'].node.socket_value_update:
                self.inputs['Vertices'].node.update()
            points_in = eval(self.inputs['Vertices'].links[0].from_socket.VerticesProperty)
        
        pts_out = []
#        polys_out = []
        edges_out = []
        for obj in points_in:
            pt_list = []
            x_max = obj[0][0]
            x_min = obj[0][0]
            y_min = obj[0][1]
            y_max = obj[0][1]
            #creates points in format for voronoi library, throwing away z
            for pt in obj:     
                x,y = pt[0],pt[1]
                x_max = max(x,x_max)
                x_min = min(x,x_min)
                y_max = max(y,y_max)
                y_min = min(x,x_min)
                pt_list.append(Site(pt[0],pt[1]))
            
            res = computeVoronoiDiagram(pt_list)
                                
            edges = res[2]
            delta = self.clip
            x_max = x_max + delta
            y_max = y_max + delta
            
            x_min = x_min - delta
            y_min = y_min - delta
            
            #clipping box to bounding box I think.
            pts_tmp = []
            for pt in res[0]:
                x,y=pt[0],pt[1]
                if x < x_min:
                    x = x_min
                if x > x_max:
                    x = x_max
                
                if y < y_min:
                    y = y_min
                if y > y_max:
                    y = y_max
                pts_tmp.append((x,y,0))
                
            pts_out.append(pts_tmp)                 
                    
            edges_out.append([ (edge[1], edge[2]) for edge in edges if -1 not in edge ])
                     

        # outputs
        if 'Vertices' in self.outputs and len(self.outputs['Vertices'].links)>0:
            if not self.outputs['Vertices'].node.socket_value_update:
                self.outputs['Vertices'].node.update()
            
            self.outputs['Vertices'].VerticesProperty = str(pts_out)
   
            
   
        if 'Edges' in self.outputs and len(self.outputs['Edges'].links)>0:
            if not self.outputs['Edges'].node.socket_value_update:
                self.outputs['Edges'].node.update()
                
            self.outputs['Edges'].StringsProperty = str(edges_out)
コード例 #15
0
ファイル: VoronoiMap.py プロジェクト: HepcatNZ/VoronoiMap
 def calc_voronoi(self,points):
     v = voronoi.computeVoronoiDiagram(points)
     for l in v[2]:
         c = (v[0][l[1]][0], v[0][l[1]][1], v[0][l[2]][0], v[0][l[2]][1])
         if c[0] > 0 and c[0] < self.map_width and c[1] > 0 and c[1] < self.map_height and c[2] > 0 and c[2] < self.map_width and c[3] > 0 and c[3] < self.map_height:
             self.draw_line(c,(0,0,0))