コード例 #1
0
    def covers(self, this, that):
        """Return true if the given quadrants does intersects each other."""

        # Convert quadrants ((x,y),w) as box ((a,b),(c,d)).
        this_box = as_box(this)
        that_box = as_box(that)

        # Convert boxes as list of edges.
        this_segments = tuple(utils.tour(as_rect(this)))
        that_segments = tuple(utils.tour(as_rect(that)))

        # If at least one of the segment of "this" intersects with "that".
        intersects = any(
            geometry.segment_intersection(s0, s1) for s0 in this_segments
            for s1 in that_segments)

        # Transform nested list of segments in flat list of points without any duplicates.
        this_points = as_rect(this)
        that_points = as_rect(that)

        # If all the points of "this" are inside "that".
        # Note: what we would want to test here is if ALL the points are comprised,
        #       as the case where at least one is already tested by the "intersects" stage.
        #       But we use an "any" anyway, because it is sufficient in this case and
        #       that testing all the points takes more time.
        this_in = any(geometry.in_box(p, this_box) for p in that_points)
        that_in = any(geometry.in_box(p, that_box) for p in this_points)

        return intersects or this_in or that_in
コード例 #2
0
ファイル: quadtree.py プロジェクト: nojhan/ubergeekism
    def covers( self, this, that ):
        """Return true if the given quadrants does intersects each other."""

        # Convert quadrants ((x,y),w) as box ((a,b),(c,d)).
        this_box = as_box(this)
        that_box = as_box(that)

        # Convert boxes as list of edges.
        this_segments = tuple(utils.tour(as_rect(this)))
        that_segments = tuple(utils.tour(as_rect(that)))

        # If at least one of the segment of "this" intersects with "that".
        intersects = any( geometry.segment_intersection(s0,s1) for s0 in this_segments for s1 in that_segments )

        # Transform nested list of segments in flat list of points without any duplicates.
        this_points = as_rect(this)
        that_points = as_rect(that)

        # If all the points of "this" are inside "that".
        # Note: what we would want to test here is if ALL the points are comprised,
        #       as the case where at least one is already tested by the "intersects" stage.
        #       But we use an "any" anyway, because it is sufficient in this case and
        #       that testing all the points takes more time.
        this_in = any( geometry.in_box(p,this_box) for p in that_points )
        that_in = any( geometry.in_box(p,that_box) for p in this_points )

        return intersects or this_in or that_in
コード例 #3
0
def edges_of(triangulation):
    """Return a list containing the edges of the given list of 3-tuples of points"""
    edges = []
    for t in triangulation:
        for e in tour(list(t)):
            edges.append(e)
    return edges
コード例 #4
0
def update_local_neighbors( pheromones, candidate, graph, w_pheromone, init_pheromone ):
    for ci,cj in tour(candidate["permutation"]):
        p,c = path.astar( graph, ci, cj )
        for i,j in zip(p,p[1:]):
            value = ((1.0 - w_pheromone) * pheromones[i][j]) + (w_pheromone * init_pheromone)
            pheromones[i][j] = value
            pheromones[j][i] = value
コード例 #5
0
ファイル: triangulation.py プロジェクト: nojhan/ubergeekism
def edges_of( triangulation ):
    """Return a list containing the edges of the given list of 3-tuples of points"""
    edges = []
    for t in triangulation:
        for e in tour(list(t)):
            edges.append( e )
    return edges
コード例 #6
0
def update_global_neighbors( pheromones, candidate, graph, decay ):
    for ci,cj in tour(candidate["permutation"]):
        # subpath between ci and cj
        p,c = path.astar( graph, ci, cj )
        # deposit pheromones on each edges of the subpath
        for i,j in zip(p,p[1:]):
            value = ((1.0 - decay) * pheromones[i][j]) + (decay * (1.0/candidate["cost"]))
            pheromones[i][j] = value
            pheromones[j][i] = value
コード例 #7
0
def edges_neighbours(candidate, polygons):
    """Returns the set of candidates in polygons that have an edge in common with the given candidate."""
    for polygon in polygons:
        if polygon == candidate:
            continue

        # Convert list of points to list of edges, because we want to find EDGE neighbours.
        edges_poly = list(tour(list(polygon)))
        assert (len(list(edges_poly)) > 0)
        edges_can = list(tour(list(candidate)))
        assert (len(list(edges_can)) > 0)

        # If at least one of the edge that are in availables polygons are also in the given candidate.
        # Beware the symetric edges.
        for edge in edges_poly:
            # We use yield within the loop, because we want to test all the candidate edges and
            # return all the matching ones.
            if edge_in(edge, edges_can):
                yield polygon
                break
コード例 #8
0
ファイル: voronoi.py プロジェクト: nojhan/ubergeekism
def edges_neighbours( candidate, polygons ):
    """Returns the set of candidates in polygons that have an edge in common with the given candidate."""
    for polygon in polygons:
        if polygon == candidate:
            continue

        # Convert list of points to list of edges, because we want to find EDGE neighbours.
        edges_poly = list(tour(list(polygon)))
        assert( len(list(edges_poly)) > 0 )
        edges_can  = list(tour(list(candidate)))
        assert( len(list(edges_can)) > 0 )

        # If at least one of the edge that are in availables polygons are also in the given candidate.
        # Beware the symetric edges.
        for edge in edges_poly:
            # We use yield within the loop, because we want to test all the candidate edges and
            # return all the matching ones.
            if edge_in( edge, edges_can ):
                yield polygon
                break
コード例 #9
0
ファイル: triangulation.py プロジェクト: nojhan/ubergeekism
 def plot_base(ax,vi = len(vertices), vertex = None):
     ax.set_aspect('equal')
     # regular points
     scatter_x = [ p[0] for p in vertices[:vi]]
     scatter_y = [ p[1] for p in vertices[:vi]]
     ax.scatter( scatter_x,scatter_y, s=30, marker='o', facecolor="black")
     # super-triangle vertices
     scatter_x = [ p[0] for p in list(supertri)]
     scatter_y = [ p[1] for p in list(supertri)]
     ax.scatter( scatter_x,scatter_y, s=30, marker='o', facecolor="lightgrey", edgecolor="lightgrey")
     # current vertex
     if vertex:
         ax.scatter( vertex[0],vertex[1], s=30, marker='o', facecolor="red", edgecolor="red")
     # current triangulation
     uberplot.plot_segments( ax, edges_of(triangles), edgecolor = "blue", alpha=0.5, linestyle='solid' )
     # bounding box
     (xmin,ymin),(xmax,ymax) = bounds(vertices)
     uberplot.plot_segments( ax, tour([(xmin,ymin),(xmin,ymax),(xmax,ymax),(xmax,ymin)]), edgecolor = "magenta", alpha=0.2, linestyle='dotted' )
コード例 #10
0
 def plot_base(ax, vi=len(vertices), vertex=None):
     ax.set_aspect('equal')
     # regular points
     scatter_x = [p[0] for p in vertices[:vi]]
     scatter_y = [p[1] for p in vertices[:vi]]
     ax.scatter(scatter_x, scatter_y, s=30, marker='o', facecolor="black")
     # super-triangle vertices
     scatter_x = [p[0] for p in list(supertri)]
     scatter_y = [p[1] for p in list(supertri)]
     ax.scatter(scatter_x,
                scatter_y,
                s=30,
                marker='o',
                facecolor="lightgrey",
                edgecolor="lightgrey")
     # current vertex
     if vertex:
         ax.scatter(vertex[0],
                    vertex[1],
                    s=30,
                    marker='o',
                    facecolor="red",
                    edgecolor="red")
     # current triangulation
     uberplot.plot_segments(ax,
                            edges_of(triangles),
                            edgecolor="blue",
                            alpha=0.5,
                            linestyle='solid')
     # bounding box
     (xmin, ymin), (xmax, ymax) = bounds(vertices)
     uberplot.plot_segments(ax,
                            tour([(xmin, ymin), (xmin, ymax), (xmax, ymax),
                                  (xmax, ymin)]),
                            edgecolor="magenta",
                            alpha=0.2,
                            linestyle='dotted')
コード例 #11
0
ファイル: hull.py プロジェクト: skeptycal/ubergeekism
    import random
    import utils
    import uberplot
    import matplotlib.pyplot as plot

    if len(sys.argv) > 1:
        scale = 100
        nb = int(sys.argv[1])
        points = [(scale * random.random(), scale * random.random())
                  for i in range(nb)]
    else:
        points = [
            (0, 40),
            (100, 60),
            (40, 0),
            (50, 100),
            (90, 10),
            (50, 50),
        ]

    fig = plot.figure()

    hull = convex_hull(points)
    edges = list(utils.tour(hull))

    ax = fig.add_subplot(111)
    ax.set_aspect('equal')
    ax.scatter([i[0] for i in points], [i[1] for i in points], facecolor="red")
    uberplot.plot_segments(ax, edges, edgecolor="blue")
    plot.show()
コード例 #12
0
ファイル: run_all.py プロジェクト: skeptycal/ubergeekism
    best, phero = ants.search(G,
                              max_it,
                              num_ants,
                              decay,
                              w_heur,
                              w_local_phero,
                              w_history,
                              c_greed,
                              cost_func=ants.graph_distance)

    LOGN(
        "\tTransform the resulting nodes permutation into a path on the graph")
    # by finding the shortest path between two cities.
    traj = []
    for start, end in utils.tour(best["permutation"]):
        p, c = shortpath.astar(G, start, end)
        traj += p
    trajs.append(traj)

    with open("d%i_tour.points" % depth, "w") as fd:
        utils.write_points(traj, fd)

    with open("d%i_pheromones.mat" % depth, "w") as fd:
        utils.write_matrix(phero, fd)

########################################################################
# TRIANGULATION
########################################################################

triangulated = []
コード例 #13
0
ファイル: geometry.py プロジェクト: nojhan/ubergeekism
            # forced collinear
            t = [ [scale*random.random(),scale*random.random()] for i in range(2)]
            triangles.append( [t[0],t[1],t[0]] )

    else:
        triangles = [
                [(-60.45085, -24.898983), (-68.54102, -30.776835), (-58.54102, -30.776835)],
                [(-68.54102, -0.0), (-65.45085, -9.510565), (-58.54102, -0.0)],
                [(-65.45085, 9.510565), (-68.54102, -0.0), (-58.54102, -0.0)],
                [(-68.54102, 30.776835), (-60.45085, 24.898983), (-58.54102, 30.776835)],
                [(-58.54102, -0.0), (-65.45085, -9.510565), (-55.45085, -9.510565)],
                [(-65.45085, -9.510565), (-57.36068, -15.388418), (-55.45085, -9.510565)],
                [(-65.45085, 9.510565), (-58.54102, -0.0), (-55.45085, 9.510565)],
                [(-65.45085, 9.510565), (-65.45085, 9.510565), (-55.45085, 9.510565)], # is collinear
            ]

    ax = fig.add_subplot(122)

    for triangle in triangles:
        status="green"
        if collinear(*triangle):
            status="red"
        uberplot.plot_segments( ax, utils.tour(triangle), edgecolor = status )

    # ax.set_aspect('equal')
    ax.axis('auto')


    plot.show()

コード例 #14
0
    else:
        triangles = [
            [(-60.45085, -24.898983), (-68.54102, -30.776835),
             (-58.54102, -30.776835)],
            [(-68.54102, -0.0), (-65.45085, -9.510565), (-58.54102, -0.0)],
            [(-65.45085, 9.510565), (-68.54102, -0.0), (-58.54102, -0.0)],
            [(-68.54102, 30.776835), (-60.45085, 24.898983),
             (-58.54102, 30.776835)],
            [(-58.54102, -0.0), (-65.45085, -9.510565),
             (-55.45085, -9.510565)],
            [(-65.45085, -9.510565), (-57.36068, -15.388418),
             (-55.45085, -9.510565)],
            [(-65.45085, 9.510565), (-58.54102, -0.0), (-55.45085, 9.510565)],
            [(-65.45085, 9.510565), (-65.45085, 9.510565),
             (-55.45085, 9.510565)],  # is collinear
        ]

    ax = fig.add_subplot(122)

    for triangle in triangles:
        status = "green"
        if collinear(*triangle):
            status = "red"
        uberplot.plot_segments(ax, utils.tour(triangle), edgecolor=status)

    # ax.set_aspect('equal')
    ax.axis('auto')

    plot.show()
コード例 #15
0
def delaunay_bowyer_watson(points,
                           supertri=None,
                           superdelta=0.1,
                           epsilon=sys.float_info.epsilon,
                           do_plot=None,
                           plot_filename="Bowyer-Watson_%i.png"):
    """Return the Delaunay triangulation of the given points

    epsilon: used for floating point comparisons, two points are considered equals if their distance is < epsilon.
    do_plot: if not None, plot intermediate steps on this matplotlib object and save them as images named: plot_filename % i
    """

    if do_plot and len(points) > 10:
        print "WARNING it is a bad idea to plot each steps of a triangulation of many points"

    # Sort points first on the x-axis, then on the y-axis.
    vertices = sorted(points)

    # LOGN( "super-triangle",supertri )
    if not supertri:
        supertri = supertriangle(vertices, superdelta)

    # It is the first triangle of the list.
    triangles = [supertri]

    completed = {supertri: False}

    # The predicate returns true if at least one of the vertices
    # is also found in the supertriangle.
    def match_supertriangle(tri):
        if tri[0] in supertri or \
           tri[1] in supertri or \
           tri[2] in supertri:
            return True

    # Returns the base of each plots, with points, current triangulation, super-triangle and bounding box.
    def plot_base(ax, vi=len(vertices), vertex=None):
        ax.set_aspect('equal')
        # regular points
        scatter_x = [p[0] for p in vertices[:vi]]
        scatter_y = [p[1] for p in vertices[:vi]]
        ax.scatter(scatter_x, scatter_y, s=30, marker='o', facecolor="black")
        # super-triangle vertices
        scatter_x = [p[0] for p in list(supertri)]
        scatter_y = [p[1] for p in list(supertri)]
        ax.scatter(scatter_x,
                   scatter_y,
                   s=30,
                   marker='o',
                   facecolor="lightgrey",
                   edgecolor="lightgrey")
        # current vertex
        if vertex:
            ax.scatter(vertex[0],
                       vertex[1],
                       s=30,
                       marker='o',
                       facecolor="red",
                       edgecolor="red")
        # current triangulation
        uberplot.plot_segments(ax,
                               edges_of(triangles),
                               edgecolor="blue",
                               alpha=0.5,
                               linestyle='solid')
        # bounding box
        (xmin, ymin), (xmax, ymax) = bounds(vertices)
        uberplot.plot_segments(ax,
                               tour([(xmin, ymin), (xmin, ymax), (xmax, ymax),
                                     (xmax, ymin)]),
                               edgecolor="magenta",
                               alpha=0.2,
                               linestyle='dotted')

    # Insert vertices one by one.
    LOG("Insert vertices: ")
    if do_plot:
        it = 0
    for vi, vertex in enumerate(vertices):
        # LOGN( "\tvertex",vertex )
        assert (len(vertex) == 2)

        if do_plot:
            ax = do_plot.add_subplot(111)
            plot_base(ax, vi, vertex)

        # All the triangles whose circumcircle encloses the point to be added are identified,
        # the outside edges of those triangles form an enclosing polygon.

        # Forget previous candidate polygon's edges.
        enclosing = []

        removed = []
        for triangle in triangles:
            # LOGN( "\t\ttriangle",triangle )
            assert (len(triangle) == 3)

            # Do not consider triangles already tested.
            # If completed has a key, test it, else return False.
            if completed.get(triangle, False):
                # LOGN( "\t\t\tAlready completed" )
                # if do_plot:
                # uberplot.plot_segments( ax, tour(list(triangle)), edgecolor = "magenta", alpha=1, lw=1, linestyle='dotted' )
                continue

            # LOGN( "\t\t\tCircumcircle" )
            assert (triangle[0] != triangle[1] and triangle[1] != triangle[2]
                    and triangle[2] != triangle[0])
            center, radius = circumcircle(triangle, epsilon)

            # If it match Delaunay's conditions.
            if x(center) < x(vertex) and math.sqrt(
                (x(vertex) - x(center))**2) > radius:
                # LOGN( "\t\t\tMatch Delaunay, mark as completed" )
                completed[triangle] = True

            # If the current vertex is inside the circumscribe circle of the current triangle,
            # add the current triangle's edges to the candidate polygon.
            if in_circle(vertex, center, radius, epsilon):
                # LOGN( "\t\t\tIn circumcircle, add to enclosing polygon",triangle )
                if do_plot:
                    circ = plot.Circle(center,
                                       radius,
                                       facecolor='yellow',
                                       edgecolor="orange",
                                       alpha=0.2,
                                       clip_on=False)
                    ax.add_patch(circ)

                for p0, p1 in tour(list(triangle)):
                    # Then add this edge to the polygon enclosing the vertex,
                    enclosing.append((p0, p1))
                # and remove the corresponding triangle from the current triangulation.
                removed.append(triangle)
                completed.pop(triangle, None)

            elif do_plot:
                circ = plot.Circle(center,
                                   radius,
                                   facecolor='lightgrey',
                                   edgecolor="grey",
                                   alpha=0.2,
                                   clip_on=False)
                ax.add_patch(circ)

        # end for triangle in triangles

        # The triangles in the enclosing polygon are deleted and
        # new triangles are formed between the point to be added and
        # each outside edge of the enclosing polygon.

        # Actually remove triangles.
        for triangle in removed:
            triangles.remove(triangle)

        # Remove duplicated edges.
        # This leaves the edges of the enclosing polygon only,
        # because enclosing edges are only in a single triangle,
        # but edges inside the polygon are at least in two triangles.
        hull = []
        for i, (p0, p1) in enumerate(enclosing):
            # Clockwise edges can only be in the remaining part of the list.
            # Search for counter-clockwise edges as well.
            if (p0, p1) not in enclosing[i + 1:] and (p1, p0) not in enclosing:
                hull.append((p0, p1))
            elif do_plot:
                uberplot.plot_segments(ax, [(p0, p1)],
                                       edgecolor="white",
                                       alpha=1,
                                       lw=1,
                                       linestyle='dotted')

        if do_plot:
            uberplot.plot_segments(ax,
                                   hull,
                                   edgecolor="red",
                                   alpha=1,
                                   lw=1,
                                   linestyle='solid')

        # Create new triangles using the current vertex and the enclosing hull.
        # LOGN( "\t\tCreate new triangles" )
        for p0, p1 in hull:
            assert (p0 != p1)
            triangle = tuple([p0, p1, vertex])
            # LOGN("\t\t\tNew triangle",triangle)
            triangles.append(triangle)
            completed[triangle] = False

            if do_plot:
                uberplot.plot_segments(ax, [(p0, vertex), (p1, vertex)],
                                       edgecolor="green",
                                       alpha=1,
                                       linestyle='solid')

        if do_plot:
            plot.savefig(plot_filename % it, dpi=150)
            plot.clf()

            it += 1
        LOG(".")

    # end for vertex in vertices
    LOGN(" done")

    # Remove triangles that have at least one of the supertriangle vertices.
    # LOGN( "\tRemove super-triangles" )

    # Filter out elements for which the predicate is False,
    # here: *keep* elements that *do not* have a common vertex.
    # The filter is a generator, so we must make a list with it to actually get the data.
    triangulation = list(filter_if_not(match_supertriangle, triangles))

    if do_plot:
        ax = do_plot.add_subplot(111)
        plot_base(ax)
        uberplot.plot_segments(ax,
                               edges_of(triangles),
                               edgecolor="red",
                               alpha=0.5,
                               linestyle='solid')
        uberplot.plot_segments(ax,
                               edges_of(triangulation),
                               edgecolor="blue",
                               alpha=1,
                               linestyle='solid')
        plot.savefig(plot_filename % it, dpi=150)
        plot.clf()

    return triangulation
コード例 #16
0
ファイル: triangulation.py プロジェクト: nojhan/ubergeekism
def delaunay_bowyer_watson( points, supertri = None, superdelta = 0.1, epsilon = sys.float_info.epsilon,
        do_plot = None, plot_filename = "Bowyer-Watson_%i.png" ):
    """Return the Delaunay triangulation of the given points

    epsilon: used for floating point comparisons, two points are considered equals if their distance is < epsilon.
    do_plot: if not None, plot intermediate steps on this matplotlib object and save them as images named: plot_filename % i
    """

    if do_plot and len(points) > 10:
        print "WARNING it is a bad idea to plot each steps of a triangulation of many points"

    # Sort points first on the x-axis, then on the y-axis.
    vertices = sorted( points )

    # LOGN( "super-triangle",supertri )
    if not supertri:
        supertri = supertriangle( vertices, superdelta )

    # It is the first triangle of the list.
    triangles = [ supertri ]

    completed = { supertri: False }

    # The predicate returns true if at least one of the vertices
    # is also found in the supertriangle.
    def match_supertriangle( tri ):
        if tri[0] in supertri or \
           tri[1] in supertri or \
           tri[2] in supertri:
            return True

    # Returns the base of each plots, with points, current triangulation, super-triangle and bounding box.
    def plot_base(ax,vi = len(vertices), vertex = None):
        ax.set_aspect('equal')
        # regular points
        scatter_x = [ p[0] for p in vertices[:vi]]
        scatter_y = [ p[1] for p in vertices[:vi]]
        ax.scatter( scatter_x,scatter_y, s=30, marker='o', facecolor="black")
        # super-triangle vertices
        scatter_x = [ p[0] for p in list(supertri)]
        scatter_y = [ p[1] for p in list(supertri)]
        ax.scatter( scatter_x,scatter_y, s=30, marker='o', facecolor="lightgrey", edgecolor="lightgrey")
        # current vertex
        if vertex:
            ax.scatter( vertex[0],vertex[1], s=30, marker='o', facecolor="red", edgecolor="red")
        # current triangulation
        uberplot.plot_segments( ax, edges_of(triangles), edgecolor = "blue", alpha=0.5, linestyle='solid' )
        # bounding box
        (xmin,ymin),(xmax,ymax) = bounds(vertices)
        uberplot.plot_segments( ax, tour([(xmin,ymin),(xmin,ymax),(xmax,ymax),(xmax,ymin)]), edgecolor = "magenta", alpha=0.2, linestyle='dotted' )


    # Insert vertices one by one.
    LOG("Insert vertices: ")
    if do_plot:
        it=0
    for vi,vertex in enumerate(vertices):
        # LOGN( "\tvertex",vertex )
        assert( len(vertex) == 2 )

        if do_plot:
            ax = do_plot.add_subplot(111)
            plot_base(ax,vi,vertex)

        # All the triangles whose circumcircle encloses the point to be added are identified,
        # the outside edges of those triangles form an enclosing polygon.

        # Forget previous candidate polygon's edges.
        enclosing = []

        removed = []
        for triangle in triangles:
            # LOGN( "\t\ttriangle",triangle )
            assert( len(triangle) == 3 )

            # Do not consider triangles already tested.
            # If completed has a key, test it, else return False.
            if completed.get( triangle, False ):
                # LOGN( "\t\t\tAlready completed" )
                # if do_plot:
                    # uberplot.plot_segments( ax, tour(list(triangle)), edgecolor = "magenta", alpha=1, lw=1, linestyle='dotted' )
                continue

            # LOGN( "\t\t\tCircumcircle" ) 
            assert( triangle[0] != triangle[1] and triangle[1] != triangle [2] and triangle[2] != triangle[0] )
            center,radius = circumcircle( triangle, epsilon )

            # If it match Delaunay's conditions.
            if x(center) < x(vertex) and math.sqrt((x(vertex)-x(center))**2) > radius:
                # LOGN( "\t\t\tMatch Delaunay, mark as completed" ) 
                completed[triangle] = True

            # If the current vertex is inside the circumscribe circle of the current triangle,
            # add the current triangle's edges to the candidate polygon.
            if in_circle( vertex, center, radius, epsilon ):
                # LOGN( "\t\t\tIn circumcircle, add to enclosing polygon",triangle )
                if do_plot:
                    circ = plot.Circle(center, radius, facecolor='yellow', edgecolor="orange", alpha=0.2, clip_on=False)
                    ax.add_patch(circ)

                for p0,p1 in tour(list(triangle)):
                    # Then add this edge to the polygon enclosing the vertex,
                    enclosing.append( (p0,p1) )
                # and remove the corresponding triangle from the current triangulation.
                removed.append( triangle )
                completed.pop(triangle,None)

            elif do_plot:
                circ = plot.Circle(center, radius, facecolor='lightgrey', edgecolor="grey", alpha=0.2, clip_on=False)
                ax.add_patch(circ)

        # end for triangle in triangles

        # The triangles in the enclosing polygon are deleted and
        # new triangles are formed between the point to be added and
        # each outside edge of the enclosing polygon. 

        # Actually remove triangles.
        for triangle in removed:
            triangles.remove(triangle)


        # Remove duplicated edges.
        # This leaves the edges of the enclosing polygon only,
        # because enclosing edges are only in a single triangle,
        # but edges inside the polygon are at least in two triangles.
        hull = []
        for i,(p0,p1) in enumerate(enclosing):
            # Clockwise edges can only be in the remaining part of the list.
            # Search for counter-clockwise edges as well.
            if (p0,p1) not in enclosing[i+1:] and (p1,p0) not in enclosing:
                hull.append((p0,p1))
            elif do_plot:
                uberplot.plot_segments( ax, [(p0,p1)], edgecolor = "white", alpha=1, lw=1, linestyle='dotted' )



        if do_plot:
            uberplot.plot_segments( ax, hull, edgecolor = "red", alpha=1, lw=1, linestyle='solid' )


        # Create new triangles using the current vertex and the enclosing hull.
        # LOGN( "\t\tCreate new triangles" )
        for p0,p1 in hull:
            assert( p0 != p1 )
            triangle = tuple([p0,p1,vertex])
            # LOGN("\t\t\tNew triangle",triangle)
            triangles.append( triangle )
            completed[triangle] = False

            if do_plot:
                uberplot.plot_segments( ax, [(p0,vertex),(p1,vertex)], edgecolor = "green", alpha=1, linestyle='solid' )

        if do_plot:
            plot.savefig( plot_filename % it, dpi=150)
            plot.clf()

            it+=1
        LOG(".")

    # end for vertex in vertices
    LOGN(" done")


    # Remove triangles that have at least one of the supertriangle vertices.
    # LOGN( "\tRemove super-triangles" ) 

    # Filter out elements for which the predicate is False,
    # here: *keep* elements that *do not* have a common vertex.
    # The filter is a generator, so we must make a list with it to actually get the data.
    triangulation = list(filter_if_not( match_supertriangle, triangles ))

    if do_plot:
            ax = do_plot.add_subplot(111)
            plot_base(ax)
            uberplot.plot_segments( ax, edges_of(triangles), edgecolor = "red", alpha=0.5, linestyle='solid' )
            uberplot.plot_segments( ax, edges_of(triangulation), edgecolor = "blue", alpha=1, linestyle='solid' )
            plot.savefig( plot_filename % it, dpi=150)
            plot.clf()

    return triangulation
コード例 #17
0
def update_local_whole( pheromones, candidate, graph, w_pheromone, init_pheromone ):
    for i,j in tour(candidate["permutation"]):
        value = ((1.0 - w_pheromone) * pheromones[i][j]) + (w_pheromone * init_pheromone)
        pheromones[i][j] = value
        pheromones[j][i] = value
コード例 #18
0
def update_global_whole( pheromones, candidate, graph, decay ):
    for i,j in tour(candidate["permutation"]):
        value = ((1.0 - decay) * pheromones[i][j]) + (decay * (1.0/candidate["cost"]))
        pheromones[i][j] = value
        pheromones[j][i] = value
コード例 #19
0
def cost( permutation, cost_func, cities ):
    dist = 0
    for ci,cj in tour(permutation):
        dist += cost_func( ci, cj, cities )
    return dist
コード例 #20
0
    # sys.stderr.write( "%i points in the quadtree / %i points\n" % (len(quad), len(points)) )

    fig = plot.figure()

    ax = fig.add_subplot(111)
    ax.set_aspect('equal')

    # Plot the whole quad tree and its points.
    # Iterating over the quadtree will generate points, thus list(quad) is equivalent to quad.points()
    uberplot.scatter_points(ax,
                            list(quad),
                            facecolor="green",
                            edgecolor="None")

    for q in quad.quadrants:
        edges = list(utils.tour(as_rect(q)))
        uberplot.plot_segments(ax,
                               edges,
                               edgecolor="blue",
                               alpha=0.1,
                               linewidth=2)

    # Plot a random query on the quad tree.
    # Remember a quadrant is ( (orig_y,orig_y), width )
    minp = (round(random.uniform(-n, n), 2), round(random.uniform(-n, n), 2))
    rand_quad = (minp, round(random.uniform(0, n), 2))
    # Asking for a quadrant will query the quad tree and return the corresponding points.
    uberplot.scatter_points(ax,
                            quad[rand_quad],
                            facecolor="None",
                            edgecolor="red",
コード例 #21
0
ファイル: run_all.py プロジェクト: nojhan/ubergeekism
    # max_it = 10
    max_it = 2
    # num_ants = 10 #* depth
    num_ants = 2 #* depth
    decay = 0.1
    w_heur = 2.5
    w_local_phero = 0.1
    c_greed = 0.9
    w_history = 1.0

    best,phero = ants.search( G, max_it, num_ants, decay, w_heur, w_local_phero, w_history, c_greed, cost_func = ants.graph_distance )

    LOGN( "\tTransform the resulting nodes permutation into a path on the graph" )
    # by finding the shortest path between two cities.
    traj = []
    for start,end in utils.tour(best["permutation"]):
        p,c = shortpath.astar( G, start, end )
        traj += p
    trajs.append(traj)

    with open("d%i_tour.points" % depth, "w") as fd:
        utils.write_points( traj, fd )

    with open("d%i_pheromones.mat" % depth, "w") as fd:
        utils.write_matrix( phero, fd )


########################################################################
# TRIANGULATION
########################################################################
コード例 #22
0
ファイル: quadtree.py プロジェクト: nojhan/ubergeekism
    quad = QuadTree( points )
    # print(quad)
    # sys.stderr.write( "%i points in the quadtree / %i points\n" % (len(quad), len(points)) )


    fig = plot.figure()

    ax = fig.add_subplot(111)
    ax.set_aspect('equal')

    # Plot the whole quad tree and its points.
    # Iterating over the quadtree will generate points, thus list(quad) is equivalent to quad.points()
    uberplot.scatter_points( ax, list(quad), facecolor="green", edgecolor="None")

    for q in quad.quadrants:
        edges = list( utils.tour(as_rect(q)) )
        uberplot.plot_segments( ax, edges, edgecolor = "blue", alpha = 0.1, linewidth = 2 )

    # Plot a random query on the quad tree.
    # Remember a quadrant is ( (orig_y,orig_y), width )
    minp = ( round(random.uniform(-n,n),2), round(random.uniform(-n,n),2) )
    rand_quad = ( minp, round(random.uniform(0,n),2) )
    # Asking for a quadrant will query the quad tree and return the corresponding points.
    uberplot.scatter_points( ax, quad[rand_quad], facecolor="None", edgecolor="red", alpha=0.5, linewidth = 2 )
    edges = list( utils.tour(as_rect(rand_quad)) )
    uberplot.plot_segments( ax, edges, edgecolor = "red", alpha = 0.5, linewidth = 2 )

    plot.show()

    assert(len(points) == len(quad))
コード例 #23
0
ファイル: hull.py プロジェクト: nojhan/ubergeekism
    import random
    import utils
    import uberplot
    import matplotlib.pyplot as plot

    if len(sys.argv) > 1:
        scale = 100
        nb = int(sys.argv[1])
        points = [ (scale*random.random(),scale*random.random()) for i in range(nb)]
    else:
        points = [
                (0,40),
                (100,60),
                (40,0),
                (50,100),
                (90,10),
                (50,50),
                ]

    fig = plot.figure()

    hull = convex_hull( points )
    edges = list(utils.tour(hull))

    ax = fig.add_subplot(111)
    ax.set_aspect('equal')
    ax.scatter( [i[0] for i in points],[i[1] for i in points], facecolor="red")
    uberplot.plot_segments( ax, edges, edgecolor = "blue" )
    plot.show()