예제 #1
0
    def test_zero_distance(self):
        XG = nx.DiGraph()
        XG.add_weighted_edges_from([
            ("s", "u", 10),
            ("s", "x", 5),
            ("u", "v", 1),
            ("u", "x", 2),
            ("v", "y", 1),
            ("x", "u", 3),
            ("x", "v", 5),
            ("x", "y", 2),
            ("y", "s", 7),
            ("y", "v", 6),
        ])
        path, dist = nx.floyd_warshall_predecessor_and_distance(XG)

        for u in XG:
            assert dist[u][u] == 0

        GG = XG.to_undirected()
        # make sure we get lower weight
        # to_undirected might choose either edge with weight 2 or weight 3
        GG["u"]["x"]["weight"] = 2
        path, dist = nx.floyd_warshall_predecessor_and_distance(GG)

        for u in GG:
            dist[u][u] = 0
예제 #2
0
    def test_floyd_warshall_predecessor_and_distance(self):
        XG=nx.DiGraph()
        XG.add_weighted_edges_from([('s','u',10) ,('s','x',5) ,
                                    ('u','v',1) ,('u','x',2) ,
                                    ('v','y',1) ,('x','u',3) ,
                                    ('x','v',5) ,('x','y',2) ,
                                    ('y','s',7) ,('y','v',6)])
        path, dist =nx.floyd_warshall_predecessor_and_distance(XG)
        assert_equal(dist['s']['v'],9)
        assert_equal(path['s']['v'],'u')
        assert_equal(dist,
                     {'y': {'y': 0, 'x': 12, 's': 7, 'u': 15, 'v': 6}, 
                      'x': {'y': 2, 'x': 0, 's': 9, 'u': 3, 'v': 4}, 
                      's': {'y': 7, 'x': 5, 's': 0, 'u': 8, 'v': 9}, 
                      'u': {'y': 2, 'x': 2, 's': 9, 'u': 0, 'v': 1}, 
                      'v': {'y': 1, 'x': 13, 's': 8, 'u': 16, 'v': 0}})


        GG=XG.to_undirected()
        path, dist = nx.floyd_warshall_predecessor_and_distance(GG)
        assert_equal(dist['s']['v'],8)
        assert_equal(path['s']['v'],'y')

        G=nx.DiGraph()  # no weights
        G.add_edges_from([('s','u'), ('s','x'), 
                          ('u','v'), ('u','x'), 
                          ('v','y'), ('x','u'), 
                          ('x','v'), ('x','y'), 
                          ('y','s'), ('y','v')])
        path, dist = nx.floyd_warshall_predecessor_and_distance(G)
        assert_equal(dist['s']['v'],2)
        assert_equal(path['s']['v'],'x')
예제 #3
0
    def test_floyd_warshall_predecessor_and_distance(self):
        XG=nx.DiGraph()
        XG.add_weighted_edges_from([('s','u',10) ,('s','x',5) ,
                                    ('u','v',1) ,('u','x',2) ,
                                    ('v','y',1) ,('x','u',3) ,
                                    ('x','v',5) ,('x','y',2) ,
                                    ('y','s',7) ,('y','v',6)])
        path, dist =nx.floyd_warshall_predecessor_and_distance(XG)
        assert_equal(dist['s']['v'],9)
        assert_equal(path['s']['v'],'u')
        assert_equal(dist,
                     {'y': {'y': 0, 'x': 12, 's': 7, 'u': 15, 'v': 6}, 
                      'x': {'y': 2, 'x': 0, 's': 9, 'u': 3, 'v': 4}, 
                      's': {'y': 7, 'x': 5, 's': 0, 'u': 8, 'v': 9}, 
                      'u': {'y': 2, 'x': 2, 's': 9, 'u': 0, 'v': 1}, 
                      'v': {'y': 1, 'x': 13, 's': 8, 'u': 16, 'v': 0}})


        GG=XG.to_undirected()
        path, dist = nx.floyd_warshall_predecessor_and_distance(GG)
        assert_equal(dist['s']['v'],8)
        assert_equal(path['s']['v'],'y')

        G=nx.DiGraph()  # no weights
        G.add_edges_from([('s','u'), ('s','x'), 
                          ('u','v'), ('u','x'), 
                          ('v','y'), ('x','u'), 
                          ('x','v'), ('x','y'), 
                          ('y','s'), ('y','v')])
        path, dist = nx.floyd_warshall_predecessor_and_distance(G)
        assert_equal(dist['s']['v'],2)
        assert_equal(path['s']['v'],'x')
예제 #4
0
    def test_floyd_warshall_predecessor_and_distance(self):
        XG = nx.DiGraph()
        XG.add_weighted_edges_from([('s', 'u', 10), ('s', 'x', 5),
                                    ('u', 'v', 1), ('u', 'x', 2),
                                    ('v', 'y', 1), ('x', 'u', 3),
                                    ('x', 'v', 5), ('x', 'y', 2),
                                    ('y', 's', 7), ('y', 'v', 6)])
        path, dist = nx.floyd_warshall_predecessor_and_distance(XG)
        assert dist['s']['v'] == 9
        assert path['s']['v'] == 'u'
        assert (dist ==
                {'y': {'y': 0, 'x': 12, 's': 7, 'u': 15, 'v': 6},
                 'x': {'y': 2, 'x': 0, 's': 9, 'u': 3, 'v': 4},
                 's': {'y': 7, 'x': 5, 's': 0, 'u': 8, 'v': 9},
                 'u': {'y': 2, 'x': 2, 's': 9, 'u': 0, 'v': 1},
                 'v': {'y': 1, 'x': 13, 's': 8, 'u': 16, 'v': 0}})

        GG = XG.to_undirected()
        # make sure we get lower weight
        # to_undirected might choose either edge with weight 2 or weight 3
        GG['u']['x']['weight'] = 2
        path, dist = nx.floyd_warshall_predecessor_and_distance(GG)
        assert dist['s']['v'] == 8
        # skip this test, could be alternate path s-u-v
#        assert_equal(path['s']['v'],'y')

        G = nx.DiGraph()  # no weights
        G.add_edges_from([('s', 'u'), ('s', 'x'),
                          ('u', 'v'), ('u', 'x'),
                          ('v', 'y'), ('x', 'u'),
                          ('x', 'v'), ('x', 'y'),
                          ('y', 's'), ('y', 'v')])
        path, dist = nx.floyd_warshall_predecessor_and_distance(G)
        assert dist['s']['v'] == 2
        # skip this test, could be alternate path s-u-v
        # assert_equal(path['s']['v'],'x')

        # alternate interface
        dist = nx.floyd_warshall(G)
        assert dist['s']['v'] == 2

        # floyd_warshall_predecessor_and_distance returns
        # dicts-of-defautdicts
        # make sure we don't get empty dictionary
        XG = nx.DiGraph()
        XG.add_weighted_edges_from([('v', 'x', 5.0), ('y', 'x', 5.0),
                                    ('v', 'y', 6.0), ('x', 'u', 2.0)])
        path, dist = nx.floyd_warshall_predecessor_and_distance(XG)
        inf = float("inf")
        assert (dist ==
                {'v': {'v': 0, 'x': 5.0, 'y': 6.0, 'u': 7.0},
                 'x': {'x': 0, 'u': 2.0, 'v': inf, 'y': inf},
                 'y': {'y': 0, 'x': 5.0, 'v': inf, 'u': 7.0},
                 'u': {'u': 0, 'v': inf, 'x': inf, 'y': inf}})
        assert (path ==
                {'v': {'x': 'v', 'y': 'v', 'u': 'x'},
                 'x': {'u': 'x'},
                 'y': {'x': 'y', 'u': 'x'}})
    def sp_router(self, router_type='dijkstra', weight='delay', savesteps=False):
        if str.lower(router_type) != 'dijkstra':
            if weight == 'delay':
                self.preds, _ = nx.floyd_warshall_predecessor_and_distance(self.dynetwork._network, weight='edge_delay')
            else:
                self.preds, _ = nx.floyd_warshall_predecessor_and_distance(self.dynetwork._network)
        temp_node_queue_lens = [0]
        temp_num_nodes_at_capacity = 0
        temp_num_nonEmpty_node = 0
        self.update_queues(True)
        self.update_time(True)

        '''iterate all nodes'''
        for node in self.dynetwork._network.nodes:
            '''provides pointer for queue of current node'''
            curr_queue = self.dynetwork._network.nodes[node]['sp_sending_queue']
            sending_capacity = self.dynetwork._network.nodes[node]['max_send_capacity']
            queue_size = len(curr_queue)

            '''Congestion Measure #1: max queue length'''
            if(queue_size > self.dynetwork.sp_max_queue_length):
                self.dynetwork.sp_max_queue_length = queue_size
            '''Congestion Measure #2: average queue length'''
            if(queue_size > 0):
                temp_node_queue_lens.append(queue_size)
                temp_num_nonEmpty_node += 1

                '''Congestion Measure #3: average percentage of active nodes at capacity'''
                if(queue_size > sending_capacity):
                    temp_num_nodes_at_capacity += 1

            '''stores packets which currently have no path to destination'''
            remaining = []
            sendctr = 0

            for i in range(queue_size):
                '''when node cannot send anymore packets, break and move on to next node'''
                if sendctr == sending_capacity:
                    self.dynetwork.sp_rejections +=(len(self.dynetwork._network.nodes[node]['sp_sending_queue']))
                    break
                remaining, curr_queue, sent = self.handle_node_packet(curr_queue, remaining, router_type, weight, savesteps)
                if sent:
                    sendctr += 1
            self.dynetwork._network.nodes[node]['sp_sending_queue'] = remaining + self.dynetwork._network.nodes[node]['sp_sending_queue']

        '''Congestion Measure #2: average queue length'''
        if len(temp_node_queue_lens) > 1:
            self.dynetwork.sp_avg_q_len_arr.append(np.average(temp_node_queue_lens[1:]))

        '''Congestion Measure #3: percentage of nodes at capacity'''
        self.dynetwork.sp_num_capacity_node.append(temp_num_nodes_at_capacity)
        self.dynetwork.sp_num_working_node.append(temp_num_nonEmpty_node)
        self.dynetwork.sp_num_empty_node.append((self.nnodes - temp_num_nonEmpty_node)/self.nnodes)
예제 #6
0
def main():

    # sets up basic graph, noting that nodes will be added implicitly
    g = nx.DiGraph()

    g.add_edge("AUS", "USA", weight=4)
    g.add_edge("USA", "AUS", weight=3)
    g.add_edge("AUS", "FRN", weight=5)
    g.add_edge("AUS", "CHN", weight=-1)
    g.add_edge("FRN", "USA", weight=7)
    g.add_edge("FRN", "CHN", weight=6)
    g.add_edge("UK", "CHN", weight=7)
    g.add_edge("USA", "UK", weight=2)
    g.add_edge("UK", "OMG", weight=-3)
    g.add_edge("USA", "FRN", weight=1)

    predecessors, distances = nx.floyd_warshall_predecessor_and_distance(
        g, weight='weight')
    one = tree("AUS", predecessors, g)
    two = single("AUS", "OMG", predecessors, g)
    three = planet("AUS", distances)

    # graph all the graphs
    print(one.nodes())
    print(one.edges())
    print("one")
    print(two.nodes())
    print(two.edges())
    print("two")
    print(three.nodes())
    print(three.edges())
    print("three")
예제 #7
0
def main():
    cont=0
    g=nx.DiGraph()
    while cont < len(ciudades):
        g.add_edge(ciudades[cont][0],ciudades[cont][1],weight=int(ciudades[cont][2]))
        cont=+1
    inicial=raw_input("Ingrese la ciudad de origen:")
    final=raw_input("Igrese la ciudad de llegada: ")
    Fin = final
    
    predecesor, distance = nx.floyd_warshall_predecessor_and_distance(g)
    distancia = predecesor[inicial].keys()
    
    n=0
    recorrido = []
    recorrido.append(final)
    
    while n < len(distancia):
        if distancia[n] == Fin:
            recorrido.append(predecesor[inicial][distancia[n]])
            if predecesor[inicial][distancia[n]] != inicial:
                Fin=predecesor[inicial][distancia[n]]
                n=-1
    print
    print ("Distancia: ")
    print (distance[inicial][final])
    print ("Camino más corto: ")
    n = len(recorrido) - 1
    while n>=0:
        print (recorrido[n])
        n=-1
    print ("Centro del grafo: ")
    print
    print (Fin)
예제 #8
0
def findPath(graph, src, dest):
    # finds node predecessors using a function imported from networkx
    predecessors, _ = nx.floyd_warshall_predecessor_and_distance(graph)

    try:
        # finds the shortest path through the Floyd-Warshall algorithm by using a function imported from networkx
        path = nx.reconstruct_path(src, dest, predecessors)
        dpath = nx.dijkstra_path(graph, src, dest)
        bfpath = nx.bellman_ford_path(graph, src, dest)

        # prints the shortest path
        print("Path:", path)
        # print("Dijkstra's Path:", dpath)
        # print("Bellman-Ford Path:", bfpath)

        # prints the number of hops from source to destination
        print("Number of Hops:", len(path) - 1)
        # print("Dijkstra's Number of Hops:", len(dpath)-1)
        # print("Bellman-Ford Number of Hops:", len(bfpath)-1)

        # gets the total cost
        edge = 0
        for i in range(1, len(path)):
            edge += graph.edges[path[i - 1], path[i]]['weight']
        dpathcost = nx.dijkstra_path_length(graph, src, dest)
        bfpathcost = nx.bellman_ford_path_length(graph, src, dest)
        print("Total Cost:", edge)
        # print("Dijkstra's Total Cost:", dpathcost)
        # print("Bellman-Ford Total Cost:", bfpathcost)
        print()

    except:
        # Print to the terminal if no path exists.
        print("ERROR: No available path from source: node", src,
              "to destination: node", dest)
예제 #9
0
파일: main.py 프로젝트: Sergiodeleon/Hdt10
def programa():
    Inicio = raw_input("Ingrese la ciudad de partida: ")
    Final = raw_input("Ingrese la ciudad de llegada: ")
    FinalAlt = Final
    predecesor, distance = nx.floyd_warshall_predecessor_and_distance(g)
    distancias = predecesor[Inicio].keys()

    n=0
    recorrido = []
    recorrido.append(Final)
    while n < len(distancias) :
            if distancias[n] == FinalAlt:
                recorrido.append(predecesor[Inicio][distancias[n]])
                if predecesor[Inicio][distancias[n]] != Inicio:
                    FinalAlt = predecesor[Inicio][distancias[n]]
                    n=-1
            n=n+1
    print
    print "Disancia: "
    print distance[Inicio][Final]
    print "Camino mas corto:"
    n = len(recorrido) - 1
    while n >= 0:
        print recorrido[n]
        n=n-1
    print "CENTRO DEL GRAFO"
    print
    print FinalAlt
예제 #10
0
 def test_weighted(self):
     XG3=nx.Graph()
     XG3.add_weighted_edges_from([ [0,1,2],[1,2,12],[2,3,1],
                                   [3,4,5],[4,5,1],[5,0,10] ])
     path, dist = nx.floyd_warshall_predecessor_and_distance(XG3)
     assert_equal(dist[0][3],15)
     assert_equal(path[0][3],2)
예제 #11
0
def floyd_warshall_all(G):
    pred, dist = nx.floyd_warshall_predecessor_and_distance(G)
    def path(u, v): # doesn't include v
        while u != v:
            yield u
            u = pred[v][u]
    return pred, dist, path
def solve(list_of_kingdom_names,
          starting_kingdom,
          adjacency_matrix,
          params=[]):
    """
    Write your algorithm here.
    Input:
        list_of_kingdom_names: An list of kingdom names such that node i of the graph corresponds to name index i in the list
        starting_kingdom: The name of the starting kingdom for the walk
        adjacency_matrix: The adjacency matrix from the input file
    Output:
        Return 2 things. The first is a list of kingdoms representing the walk, and the second is the set of kingdoms that are conquered
    """
    # raise Exception('"solve" function not defined')
    # return closed_walk, conquered_kingdoms

    graph = adjacency_matrix_to_graph(adjacency_matrix)
    for i in range(len(list_of_kingdom_names)):
        if list_of_kingdom_names[i] == starting_kingdom:
            start = i
            break
    dominating_set = new_min_weighted_dominating_set(graph, weight='weight')
    path_dict, dist_dict = nx.floyd_warshall_predecessor_and_distance(
        graph, weight='weight')
    shortest_path_through_dom_set = best_set_permutation(
        dominating_set, start, dist_dict)
    path = final_tour_creator(shortest_path_through_dom_set, path_dict, start)
    return path, list(dominating_set)
예제 #13
0
 def path_generate_for_truck_greedy(self, truck: Truck):
     """
     通过贪心算法,生成一个车辆的次优回路,时间复杂度为O(n^2)
     :param truck: 待生成回路的车辆
     :return: None
     """
     # Floyd预处理
     subgraph = truck.subgraph
     predecessors, dists = nx.floyd_warshall_predecessor_and_distance(subgraph)
     d = 0
     path = []
     visited = {u: False for u in subgraph}
     visited[0] = True
     # 从配送中心出发开始贪心
     u = 0
     for i in range(len(subgraph) - 1):
         v_opt = 0
         dist_opt = np.inf
         for v in subgraph:
             if not visited[v] and dists[u][v] < dist_opt:
                 v_opt = v
                 dist_opt = dists[u][v]
         visited[v_opt] = True
         d += dists[u][v_opt]
         path += nx.reconstruct_path(u, v_opt, predecessors)[:-1]
         u = v_opt
     # 更新车辆路径
     truck.d = d + dists[u][0]
     truck.path = path + [u, 0]
예제 #14
0
def rutaMasCorta(ciudad1,ciudad2):
    ciudadesIntermedias = []
    control = True 
    path = nx.floyd_warshall_predecessor_and_distance(grafo)    
    try: 
        #Ruta a traves de nodos
        intermedia = path[0][ciudad1][ciudad2]
        distancia = path[1][ciudad1][ciudad2]
        ciudadesIntermedias.append(intermedia)
        
        while control:
            #Se crea una lista para saber por donde pasa a traves de los nodos
            if not(intermedia == ciudad1):
                intermedia1 = path[0][ciudad1][intermedia]
                ciudadesIntermedias.append(intermedia1)
                intermedia = intermedia1    
            else:
                control = False

        #Ordenamos la lista
        ciudadesIntermedias.reverse()
        #Se hace la impresion
        print ("\nLa ruta mas corta entre es pasando por: ")
        print (", ".join(ciudadesIntermedias),",",ciudad2)
        print ("\nLa distancia total es de", distancia, "km")
        
    except KeyError:
        print ("No hay ruta directa entre las ciudades\n")                
예제 #15
0
def establecerRuta(ciudad1, ciudad2, distancia):
    
    paths = nx.floyd_warshall_predecessor_and_distance(grafo)

    grafo.add_edge(ciudad1,ciudad2,weight=distancia)

    print("Se ha realizado la conecxion entre las ciudades")
예제 #16
0
파일: pdpt.py 프로젝트: ScorpJD/PDP-T
    def __init__(self,
                 number_of_vehicles=0,
                 deposts=[],
                 limit=[],
                 transfer_points=(),
                 requests={},
                 graph=None):
        """init method for PDPT class

        This method construct an PDPT instance

        Parameters:
            number_of_vehicles  (int): The total numbers of vehicles in the
                                       instance.
            deposts            (list): The vehicles initial position, must have
                                       a length of N
            transfer_points   (tuple): Transfer Points
            requests           (dict): The Problem request
            graph          (nx.Graph): The Graph with all the posible routes
        """
        self.N = number_of_vehicles
        self.time = 0
        self.vehicles = []
        for i in range(self.N):
            self.vehicles.append(Vehicle(deposts))
        self.transfer_points = transfer_points
        self.requests = requests
        self.origins = tuple(requests.keys())
        self.destinations = tuple(requests.values())
        self.routes = graph
        self.floyd = nx.floyd_warshall_predecessor_and_distance(self.routes)
        self.solution = None
예제 #17
0
    def test_reconstruct_path(self):
        with pytest.raises(KeyError):
            XG = nx.DiGraph()
            XG.add_weighted_edges_from([
                ("s", "u", 10),
                ("s", "x", 5),
                ("u", "v", 1),
                ("u", "x", 2),
                ("v", "y", 1),
                ("x", "u", 3),
                ("x", "v", 5),
                ("x", "y", 2),
                ("y", "s", 7),
                ("y", "v", 6),
            ])
            predecessors, _ = nx.floyd_warshall_predecessor_and_distance(XG)

            path = nx.reconstruct_path("s", "v", predecessors)
            assert path == ["s", "x", "u", "v"]

            path = nx.reconstruct_path("s", "s", predecessors)
            assert path == []

            # this part raises the keyError
            nx.reconstruct_path("1", "2", predecessors)
예제 #18
0
def greedy_solver(DTHGraph, timeout=40):
    def path(u, v):
        return nx.reconstruct_path(u, v, predecessors)

    t0, curr_min = time.time(), float('inf')
    solution = []
    predecessors, _ = nx.floyd_warshall_predecessor_and_distance(
        DTHGraph.nxgraph)
    solution.append(DTHGraph.start)
    curr_loc = DTHGraph.start
    remaining_loc = DTHGraph.homes[:]

    while len(remaining_loc) != 0:
        distances = [DTHGraph.dist[curr_loc][v] for v in remaining_loc]
        best = remaining_loc.pop(np.argmin(distances))
        if best == curr_loc:
            continue
        walk = path(curr_loc, best)
        solution += walk[1:]
        curr_loc = best

    walk = path(curr_loc, DTHGraph.start)
    solution += walk[1:]

    DTHGraph.solution = solution
예제 #19
0
def createAndInitNetwork():
    #draw and show graph
    mapper['color'] = np.array(map(ord, mapper['group']))
    nx.draw_kamada_kawai(graph,
                         with_labels=True,
                         node_color=mapper['color'],
                         cmap=plt.cm.Greens)
    plt.show()
    #plt.savefig('../networks/network'+ sys.argv[1] +'.png')
    #calculate shortest path between all nodes
    pred, dist = nx.floyd_warshall_predecessor_and_distance(graph)
    for p in pred:
        commandCreate = 'python node.py ' + str(p) + ' ' + mapper['group'][
            p] + ' ' + sys.argv[1] + ' ' + sys.argv[2] + ' ' + str(pred[p])
        commandList.append(commandCreate)

    #clear ports to create nodes
    clearPort = 'sudo fuser -k -n tcp '
    for g in nx.nodes(graph):
        clearPort = clearPort + str(8090 + g) + ' '
    print clearPort
    os.system(clearPort)

    t = threading.Thread(target=(createNodes), args=())
    t.start()
    time.sleep(1)
예제 #20
0
 def test_weight_parameter(self):
     XG4 = nx.Graph()
     XG4.add_edges_from([
         (0, 1, {
             "heavy": 2
         }),
         (1, 2, {
             "heavy": 2
         }),
         (2, 3, {
             "heavy": 1
         }),
         (3, 4, {
             "heavy": 1
         }),
         (4, 5, {
             "heavy": 1
         }),
         (5, 6, {
             "heavy": 1
         }),
         (6, 7, {
             "heavy": 1
         }),
         (7, 0, {
             "heavy": 1
         }),
     ])
     path, dist = nx.floyd_warshall_predecessor_and_distance(XG4,
                                                             weight="heavy")
     assert dist[0][2] == 4
     assert path[0][2] == 1
예제 #21
0
 def test_weighted(self):
     XG3 = nx.Graph()
     XG3.add_weighted_edges_from([[0, 1, 2], [1, 2, 12], [2, 3, 1],
                                  [3, 4, 5], [4, 5, 1], [5, 0, 10]])
     path, dist = nx.floyd_warshall_predecessor_and_distance(XG3)
     assert dist[0][3] == 15
     assert path[0][3] == 2
예제 #22
0
 def test_weighted2(self):
     XG4 = nx.Graph()
     XG4.add_weighted_edges_from([[0, 1, 2], [1, 2, 2], [2, 3, 1],
                                  [3, 4, 1], [4, 5, 1], [5, 6, 1],
                                  [6, 7, 1], [7, 0, 1]])
     path, dist = nx.floyd_warshall_predecessor_and_distance(XG4)
     assert dist[0][2] == 4
     assert path[0][2] == 1
예제 #23
0
 def test_weighted2(self):
     XG4=nx.Graph()
     XG4.add_weighted_edges_from([ [0,1,2],[1,2,2],[2,3,1],
                                   [3,4,1],[4,5,1],[5,6,1],
                                   [6,7,1],[7,0,1] ])
     path, dist = nx.floyd_warshall_predecessor_and_distance(XG4)
     assert_equal(dist[0][2],4)
     assert_equal(path[0][2],1)
예제 #24
0
def steiner_find(list_of_locations, list_of_homes, starting_car_location,
                 adjacency_matrix):
    G = nx.Graph(incoming_graph_data=adjacency_matrix, cutoff=1000)
    predecessors, distances = nx.floyd_warshall_predecessor_and_distance(G)
    homeIndices = []
    for h in list_of_homes:
        homeIndices.append(list_of_locations.index(h))
    # homeIndices.append(list_of_locations.index(starting_car_location))
    tree = apxa.steiner_tree(
        G, homeIndices + [list_of_locations.index(starting_car_location)])
    # print(list(tree.nodes))
    # print(homeIndices)
    # print(starting_car_location)
    # treematrix = nx.adjacency_matrix(tree)
    # return greedyAllPairs(list(tree.nodes), homeIndices, int(starting_car_location), treematrix)
    nodelist = list(tree.nodes())
    currIndex = list_of_locations.index(starting_car_location)
    visitedNodes = []
    path = [list_of_locations.index(starting_car_location)]
    dropoff_mapping = {}
    added = False
    # print(currIndex)
    nodelist = nodelist[
        nodelist.index(currIndex):] + nodelist[:nodelist.index(currIndex)]
    # print(nodelist)
    dropped = False
    allHomes = set(homeIndices)
    homeSet = set(homeIndices)
    length = len(nodelist) - 1
    i = 0
    while i in range(0, length):
        dropped = False
        homeNeighbors = list(
            homeSet.intersection(list(tree.neighbors(nodelist[i]))))
        if len(homeNeighbors) >= 3:
            dropped = True
            homeNeighbors = [j for j in homeNeighbors if j in homeSet]
            if (nodelist[i] in homeSet):
                homeNeighbors = homeNeighbors + [nodelist[i]]
            dropoff_mapping[nodelist[i]] = homeNeighbors
            homeSet = set([j for j in homeSet if j not in homeNeighbors])
        n = 1
        while i + n in range(0, length) and nodelist[
                i + n] in allHomes and nodelist[i + n] not in homeSet:
            n = n + 1
        path_to_next = nx.reconstruct_path(nodelist[i], nodelist[i + n],
                                           predecessors)
        path.extend(path_to_next[1:])
        if nodelist[i] in homeSet and not dropped:
            dropoff_mapping[nodelist[i]] = [nodelist[i]]
            homeSet.remove(nodelist[i])
        i = i + n
    if nodelist[-1] in homeSet:
        dropoff_mapping[nodelist[-1]] = [nodelist[-1]]
    path_to_start = nx.reconstruct_path(nodelist[-1], nodelist[0],
                                        predecessors)
    path.extend(path_to_start[1:])
    return path, dropoff_mapping
예제 #25
0
파일: funciones.py 프로젝트: ElGutiz/HT10
def ruta():

    graf = nx.DiGraph()

    archivo = open("guategrafo.txt", "r")
    contenido = archivo.readlines()
    archivo.close()

    for lineas in contenido:
        string = lineas.split(" ")
        graf.add_node(string[0])
        graf.add_node(string[1])
        graf.add_edge(string[0], string[1], weight=float(string[2]))

    path = nx.floyd_warshall_predecessor_and_distance(graf)
    nodos = graf.nodes()

    ciudadI = input("Ingrese la ciudad de la cual desea partir: ")
    while ciudadI not in graf.nodes():
        print("La ciudad que ingreso no se encuentra en la base de datos")
        ciudadI = input("Ingrese la ciudad de la cual desea partir: ")

    ciudadD = input("Indique la ciudad de destino: ")

    while ciudadD not in graf.nodes():
        print("La ciudad que ingreso no se encuentra en la base de datos")
        ciudadD = input("Indique la ciudad de destino: ")

    try:
        predecesor1 = path[0][ciudadI][ciudadD]
        ciudades = []
        ciudades.append(predecesor1)
        #print predecesor1
        cont = 0
        if predecesor1 != ciudadI:
            while cont == 0:
                predecesor = path[0][ciudadI][predecesor1]
                ciudades.append(predecesor)
                predecesor1 = predecesor
                if predecesor1 == ciudadI:
                    cont = 1
                else:
                    predecesor1 = predecesor
                    #print predecesor1

        imprimir = []
        for i in reversed(ciudades):
            if ciudadI != i:
                imprimir.append(i)

        print("La ruta mas corta de ", ciudadI, " a ", ciudadD, " es por: ")
        print(ciudadI, "-> " + "-> ".join(imprimir), "->", ciudadD)

        print("La distancia en kilometros es: ")
        print(path[1][ciudadI][ciudadD])
    except:
        print("No existen rutas entre esas ciudades")
예제 #26
0
 def __init__(self, request=[], path=[], floyd=None, instance=None):
     self.request = request
     self.path = []
     if not floyd:
         self.minPath, self.minDist =\
                 nx.floyd_warshall_predecessor_and_distance(instance.routes)
     else:
         self.minPath, self.minDist = floyd
     self.f()
예제 #27
0
def floyd_warshall(distance):
    '''
    :param distance: distance model with maxsize
    :return: shortest_dis, predecessors
    '''
    G = nx.DiGraph(distance)
    shortest_dis = nx.floyd_warshall(G)
    predecessors, _ = nx.floyd_warshall_predecessor_and_distance(G)
    return shortest_dis, predecessors
예제 #28
0
 def test_weight_parameter(self):
     XG4 = nx.Graph()
     XG4.add_edges_from([ (0, 1, {'heavy': 2}), (1, 2, {'heavy': 2}),
                          (2, 3, {'heavy': 1}), (3, 4, {'heavy': 1}),
                          (4, 5, {'heavy': 1}), (5, 6, {'heavy': 1}),
                          (6, 7, {'heavy': 1}), (7, 0, {'heavy': 1}) ])
     path, dist = nx.floyd_warshall_predecessor_and_distance(XG4,
                                                         weight='heavy')
     assert_equal(dist[0][2], 4)
     assert_equal(path[0][2], 1)
예제 #29
0
파일: staplegraph.py 프로젝트: vdt/cadnano2
 def floydWarshall(self):
     """
     This finds all-pairs of shortest path lengths using Floyd's algorithm 
     and sets self.min_path_dict to [predecessor_dict, distance_dict] where 
     the two dictionaries 2D dictionaries keyed on node index.
     predecessor is the ordered list of visited nodes when going from node
     A to node B along a shortest path.
     """
     # self.min_path_dict = nx.floyd_warshall(self.G)
     self.min_path_dict = nx.floyd_warshall_predecessor_and_distance(self.G)
예제 #30
0
def all_pairs_shortest_paths(graph):
    """Returns a dictionary of dictionaries. Each inner dictionary is indexed by a node
	and value is distance between outer key and inner key."""
    predecessors, lengths = nx.floyd_warshall_predecessor_and_distance(graph)
    paths = dict()
    for i in range(len(graph.nodes)):
        paths[i] = dict()
        for j in range(len(graph.nodes)):
            paths[i][j] = nx.reconstruct_path(i, j, predecessors)
    return lengths, paths
예제 #31
0
 def floydWarshall(self):
     """
     This finds all-pairs of shortest path lengths using Floyd's algorithm 
     and sets self.min_path_dict to [predecessor_dict, distance_dict] where 
     the two dictionaries 2D dictionaries keyed on node index.
     predecessor is the ordered list of visited nodes when going from node
     A to node B along a shortest path.
     """
     # self.min_path_dict = nx.floyd_warshall(self.G)
     self.min_path_dict = nx.floyd_warshall_predecessor_and_distance(self.G)
예제 #32
0
 def test_weight_parameter(self):
     XG4 = nx.Graph()
     XG4.add_edges_from([ (0, 1, {'heavy': 2}), (1, 2, {'heavy': 2}),
                          (2, 3, {'heavy': 1}), (3, 4, {'heavy': 1}),
                          (4, 5, {'heavy': 1}), (5, 6, {'heavy': 1}),
                          (6, 7, {'heavy': 1}), (7, 0, {'heavy': 1}) ])
     path, dist = nx.floyd_warshall_predecessor_and_distance(XG4,
                                                         weight='heavy')
     assert_equal(dist[0][2], 4)
     assert_equal(path[0][2], 1)
예제 #33
0
    def test_zero_distance(self):
        XG=nx.DiGraph()
        XG.add_weighted_edges_from([('s','u',10) ,('s','x',5) ,
                                    ('u','v',1) ,('u','x',2) ,
                                    ('v','y',1) ,('x','u',3) ,
                                    ('x','v',5) ,('x','y',2) ,
                                    ('y','s',7) ,('y','v',6)])
        path, dist =nx.floyd_warshall_predecessor_and_distance(XG)

        for u in XG:
            assert_equal(dist[u][u], 0)

        GG=XG.to_undirected()
        # make sure we get lower weight
        # to_undirected might choose either edge with weight 2 or weight 3
        GG['u']['x']['weight']=2
        path, dist = nx.floyd_warshall_predecessor_and_distance(GG)

        for u in GG:
            dist[u][u] = 0
예제 #34
0
def solve_from_file(input_file, output_directory, params=[]):
    print('Processing', input_file)

    input_data = utils.read_file(input_file)
    num_of_locations, num_houses, list_locations, list_houses, starting_car_location, adjacency_matrix = data_parser(
        input_data)
    car_path, drop_offs, homeList = solve(list_locations,
                                          list_houses,
                                          starting_car_location,
                                          adjacency_matrix,
                                          params=params)

    G = nx.Graph(incoming_graph_data=adjacency_matrix, cutoff=1000)
    predecessors, distances = nx.floyd_warshall_predecessor_and_distance(G)
    print(list(distances.items())[0][1][0])

    prev_dropoff = list_locations.index(starting_car_location)

    list_houses = homeList

    def cost(h, i, j, k):
        '''
        h : place you are coming from
        i : place to drop off person
        j : actual house for person dropped off at i
        k : next place to drive to
        '''
        return ((2 / 3) * list(distances.items())[h][1][i]) + (list(
            distances.items())[i][1][j]) + (
                (2 / 3) * list(distances.items())[i][1][k])

    #how do i access the next index in the list of houses?
    #ask eric and calvin to check the code and see if it has correct syntax
    i = 0
    drop_to_home = {}
    dropoff_list = []
    while (i < num_houses - 1):
        i_ind = list_houses.index(list_houses[i])
        i_ind_next = list_houses.index(list_houses[i + 1])
        total_cost = list(distances.items())[prev_dropoff][1][i_ind]
        best_dropoff = i_ind
        for x in list_locations:
            x_ind = list_locations.index(x)
            challenge = cost(prev_dropoff, x, i_ind, i_ind_next)
            if challenge < total_cost:
                total_cost = challenge
                best_dropoff = x_ind
        prev_dropoff = best_dropoff
        best_dropoff_location = list_locations[best_dropoff]
        drop_to_home[best_dropoff] = [i_ind]
        dropoff_list.append(best_dropoff_location)
        i += 1
    return greedyAllPairs(list_locations, dropoff_list, drop_to_home,
                          starting_car_location, adjacency_matrix)
예제 #35
0
    def test_zero_distance(self):
        XG = nx.DiGraph()
        XG.add_weighted_edges_from([('s', 'u', 10), ('s', 'x', 5),
                                    ('u', 'v', 1), ('u', 'x', 2),
                                    ('v', 'y', 1), ('x', 'u', 3),
                                    ('x', 'v', 5), ('x', 'y', 2),
                                    ('y', 's', 7), ('y', 'v', 6)])
        path, dist = nx.floyd_warshall_predecessor_and_distance(XG)

        for u in XG:
            assert dist[u][u] == 0

        GG = XG.to_undirected()
        # make sure we get lower weight
        # to_undirected might choose either edge with weight 2 or weight 3
        GG['u']['x']['weight'] = 2
        path, dist = nx.floyd_warshall_predecessor_and_distance(GG)

        for u in GG:
            dist[u][u] = 0
예제 #36
0
    def calculate_many_marginals(self, projections):
        """ Calculates marginals for all the projections in the list using
            Algorithm for answering many out-of-clique queries (section 10.3 in Koller and Friedman)
    
        This method may be faster than calling project many times
        
        :param projections: a list of projections, where 
            each projection is a subset of attributes (represented as a list or tuple)
        :return: a list of marginals, where each marginal is represented as a Factor
        """

        self.marginals = self.belief_propagation(self.potentials)
        sep = self.sep_axes
        neighbors = self.neighbors
        # first calculate P(Cj | Ci) for all neighbors Ci, Cj
        conditional = {}
        for Ci in neighbors:
            for Cj in neighbors[Ci]:
                Sij = sep[(Cj, Ci)]
                Z = self.marginals[Cj]
                conditional[(Cj, Ci)] = Z / Z.project(Sij)

        # now iterate through pairs of cliques in order of distance
        pred, dist = nx.floyd_warshall_predecessor_and_distance(
            self.junction_tree.tree, weight=False)
        results = {}
        for Ci, Cj in sorted(itertools.combinations(self.cliques, 2),
                             key=lambda X: dist[X[0]][X[1]]):
            Cl = pred[Ci][Cj]
            Y = conditional[(Cj, Cl)]
            if Cl == Ci:
                X = self.marginals[Ci]
                results[(Ci, Cj)] = results[(Cj, Ci)] = X * Y
            else:
                X = results[(Ci, Cl)]
                S = set(Cl) - set(Ci) - set(Cj)
                results[(Ci, Cj)] = results[(Cj, Ci)] = (X * Y).sum(S)

        results = {
            self.domain.canonical(key[0] + key[1]): results[key]
            for key in results
        }

        answers = {}
        for proj in projections:
            for attr in results:
                if set(proj) <= set(attr):
                    answers[proj] = results[attr].project(proj)
                    break
            if proj not in answers:
                # just use variable elimination
                answers[proj] = self.project(proj)

        return answers
예제 #37
0
    def test_floyd_warshall_predecessor_and_distance(self):
        XG=nx.DiGraph()
        XG.add_weighted_edges_from([('s','u',10) ,('s','x',5) ,
                                    ('u','v',1) ,('u','x',2) ,
                                    ('v','y',1) ,('x','u',3) ,
                                    ('x','v',5) ,('x','y',2) ,
                                    ('y','s',7) ,('y','v',6)])
        path, dist =nx.floyd_warshall_predecessor_and_distance(XG)
        assert_equal(dist['s']['v'],9)
        assert_equal(path['s']['v'],'u')
        assert_equal(dist,
                     {'y': {'y': 0, 'x': 12, 's': 7, 'u': 15, 'v': 6},
                      'x': {'y': 2, 'x': 0, 's': 9, 'u': 3, 'v': 4},
                      's': {'y': 7, 'x': 5, 's': 0, 'u': 8, 'v': 9},
                      'u': {'y': 2, 'x': 2, 's': 9, 'u': 0, 'v': 1},
                      'v': {'y': 1, 'x': 13, 's': 8, 'u': 16, 'v': 0}})


        GG=XG.to_undirected()
        # make sure we get lower weight
        # to_undirected might choose either edge with weight 2 or weight 3
        GG['u']['x']['weight']=2
        path, dist = nx.floyd_warshall_predecessor_and_distance(GG)
        assert_equal(dist['s']['v'],8)
        # skip this test, could be alternate path s-u-v
#        assert_equal(path['s']['v'],'y')

        G=nx.DiGraph()  # no weights
        G.add_edges_from([('s','u'), ('s','x'),
                          ('u','v'), ('u','x'),
                          ('v','y'), ('x','u'),
                          ('x','v'), ('x','y'),
                          ('y','s'), ('y','v')])
        path, dist = nx.floyd_warshall_predecessor_and_distance(G)
        assert_equal(dist['s']['v'],2)
        # skip this test, could be alternate path s-u-v
 #       assert_equal(path['s']['v'],'x')

        # alternate interface
        dist = nx.floyd_warshall(G)
        assert_equal(dist['s']['v'],2)
예제 #38
0
    def test_floyd_warshall_predecessor_and_distance(self):
        XG=nx.DiGraph()
        XG.add_weighted_edges_from([('s','u',10) ,('s','x',5) ,
                                    ('u','v',1) ,('u','x',2) ,
                                    ('v','y',1) ,('x','u',3) ,
                                    ('x','v',5) ,('x','y',2) ,
                                    ('y','s',7) ,('y','v',6)])
        path, dist =nx.floyd_warshall_predecessor_and_distance(XG)
        assert_equal(dist['s']['v'],9)
        assert_equal(path['s']['v'],'u')
        assert_equal(dist,
                     {'y': {'y': 0, 'x': 12, 's': 7, 'u': 15, 'v': 6},
                      'x': {'y': 2, 'x': 0, 's': 9, 'u': 3, 'v': 4},
                      's': {'y': 7, 'x': 5, 's': 0, 'u': 8, 'v': 9},
                      'u': {'y': 2, 'x': 2, 's': 9, 'u': 0, 'v': 1},
                      'v': {'y': 1, 'x': 13, 's': 8, 'u': 16, 'v': 0}})


        GG=XG.to_undirected()
        # make sure we get lower weight
        # to_undirected might choose either edge with weight 2 or weight 3
        GG['u']['x']['weight']=2
        path, dist = nx.floyd_warshall_predecessor_and_distance(GG)
        assert_equal(dist['s']['v'],8)
        # skip this test, could be alternate path s-u-v
#        assert_equal(path['s']['v'],'y')

        G=nx.DiGraph()  # no weights
        G.add_edges_from([('s','u'), ('s','x'),
                          ('u','v'), ('u','x'),
                          ('v','y'), ('x','u'),
                          ('x','v'), ('x','y'),
                          ('y','s'), ('y','v')])
        path, dist = nx.floyd_warshall_predecessor_and_distance(G)
        assert_equal(dist['s']['v'],2)
        # skip this test, could be alternate path s-u-v
 #       assert_equal(path['s']['v'],'x')

        # alternate interface
        dist = nx.floyd_warshall(G)
        assert_equal(dist['s']['v'],2)
예제 #39
0
    def test_reconstruct_path(self):
        XG = nx.DiGraph()
        XG.add_weighted_edges_from([('s', 'u', 10), ('s', 'x', 5),
                                    ('u', 'v', 1), ('u', 'x', 2),
                                    ('v', 'y', 1), ('x', 'u', 3),
                                    ('x', 'v', 5), ('x', 'y', 2),
                                    ('y', 's', 7), ('y', 'v', 6)])
        predecessors, _ = nx.floyd_warshall_predecessor_and_distance(XG)

        path = nx.reconstruct_path('s', 'v', predecessors)
        assert_equal(path, ['s', 'x', 'u', 'v'])

        path = nx.reconstruct_path('s', 's', predecessors)
        assert_equal(path, [])

        # this part raises the keyError
        nx.reconstruct_path('1', '2', predecessors)
예제 #40
0
 def test_directed_cycle_numpy(self):
     G = nx.DiGraph()
     G.add_cycle([0,1,2,3])
     pred,dist = nx.floyd_warshall_predecessor_and_distance(G)
     D = nx.utils.dict_to_numpy_array(dist)
     assert_equal(nx.floyd_warshall_numpy(G),D)
예제 #41
0
	def approximate_line_segments(self, TRAINING_MIN_AREA = 60, TRAINING_MAX_AREA = 20576, MAX_FAIL_COUNTER = 20, NEIGHBOR_TRESHOLD = 6):

		obj_area = len(self.FOOTPRINT_initial[self.FOOTPRINT_initial != 0])
		if obj_area < TRAINING_MIN_AREA:
			obj_area = TRAINING_MIN_AREA
		elif obj_area > TRAINING_MAX_AREA:
			obj_area = TRAINING_MAX_AREA

		lin_area = [60,86,113,137,140,146,152,155,158,176,183,187,191,194,198,202,209,221,231,240,247,254,265,280,289,290,293,294,299,307,317,332,344,369,386,398,415,424,446,256,472,485,517,532,571,590,611,634,671,689,713,722,755,781,796,893,938,970,1004,1050,1050,1107,1114,1153,1164,1226,1518,1598,1762,1830,1875,1985,2045,2212,2574,2829,2895,3038,3610,4299,5088,5261,5312,5961,10616,12586,20576]
		lin_min_e = [0.4,0.4,0.4,0.4,0.6,0.4,0.425,0.5,0.425,0.4,0.475,0.5,0.475,0.475,0.5,0.6,0.625,0.7,0.6,0.6,0.6,0.725,0.725,0.7,0.7,0.7,0.6,0.6,0.7,0.7,0.75,0.75,0.75,0.775,0.76,0.75,0.8,0.775,0.7,0.725,0.725,0.8,0.83,0.805,0.82,0.8,0.85,0.85,0.9,0.87,0.9,0.9,0.9,0.92,1.0,1.0,1.0,0.95,1.0,0.9,0.95,1.0,1.0,1.0,1.0,1.0,0.9,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0]
	
		FXN_min_e = interp1d(lin_area, lin_min_e)

		MIN_E_DISTANCE = FXN_min_e(obj_area)

		G=nx.DiGraph()
		E=nx.DiGraph()
		len_ordered_points = len(self.POINTS_ordered)

		for idx in xrange(0,len_ordered_points):

			
			next_idx = (idx+1) % len_ordered_points
			dist = math.hypot(self.POINTS_ordered[idx][0] - self.POINTS_ordered[next_idx][0], self.POINTS_ordered[idx][1] - self.POINTS_ordered[next_idx][1])
			G.add_edge(idx,next_idx,weight=dist)
			G.add_edge(idx,str(next_idx),weight=dist)
			E.add_edge(idx,next_idx,weight=0)
			E.add_edge(idx,str(next_idx),weight=0)

			idx2 = (idx + 2) % len_ordered_points
			fail_counter = 0

			while((idx2 + 1) % len_ordered_points != idx and fail_counter < MAX_FAIL_COUNTER):  #?

				counter = 0
				average_distance = 0.0
				base   = math.hypot(self.POINTS_ordered[idx][0] - self.POINTS_ordered[idx2][0], self.POINTS_ordered[idx][1] - self.POINTS_ordered[idx2][1])
				idx3 = (idx + 1) % len_ordered_points

				while(idx2 != idx3): #?

					side_1 = math.hypot(self.POINTS_ordered[idx][0] - self.POINTS_ordered[idx3][0], self.POINTS_ordered[idx][1] - self.POINTS_ordered[idx3][1])
					side_2 = math.hypot(self.POINTS_ordered[idx2][0] - self.POINTS_ordered[idx3][0], self.POINTS_ordered[idx2][1] - self.POINTS_ordered[idx3][1])
					semi_perimeter = (side_1 + side_2 + base) / 2.0
					temp = semi_perimeter * (semi_perimeter - side_1) * (semi_perimeter - side_2) * (semi_perimeter - base)
					if temp < 0:
						temp = 0
					area   = math.sqrt(temp)
					height = (2.0 * area) / base
					average_distance += height
					counter += 1
					idx3 = (idx3 + 1) % len_ordered_points

				average_distance /= counter

				if average_distance <= MIN_E_DISTANCE:
					G.add_edge(idx,idx2,weight=base)
					G.add_edge(idx,str(idx2),weight=base)
					E.add_edge(idx,idx2,weight=average_distance)
					E.add_edge(idx,str(idx2),weight=average_distance)
					fail_counter = 0
				else:
					fail_counter += 1

				idx2 = (idx2 + 1) % len_ordered_points


		F = nx.floyd_warshall_predecessor_and_distance(G)

		best_route = []
		for target in xrange(0,len_ordered_points):
			pointer = str(target)
			route = []
			route.append(pointer)

			while pointer != target:
				pointer = F[0][target][pointer]
				route.append(pointer)
			
			if len(best_route) == 0 or len(best_route) > len(route):
				best_route = copy.deepcopy(route)

		valid_nodes = []
		best_route = best_route[::-1]
		best_route.pop()

		for point in best_route:
			point = int(point)
			valid_nodes.append([point])
			for i in xrange(1, (NEIGHBOR_TRESHOLD / 2) + 1):
				valid_nodes[-1].append((point + i) % len_ordered_points)
				valid_nodes[-1].append((point - i) % len_ordered_points)

		len_valid_nodes = len(valid_nodes)
		simplified_E=nx.DiGraph()

		for node_idx in xrange(0, len_valid_nodes):
			next_node = (node_idx + 1) % len_valid_nodes
			for point in valid_nodes[node_idx]:
				for adj_point in valid_nodes[next_node]:
					curr_edge = E.get_edge_data(point, adj_point, False)

					if next_node != 0:
						next_node_name = str(next_node) + '_' + str(adj_point)
					else:
						next_node_name = adj_point

					if curr_edge != False:
						simplified_E.add_edge(str(node_idx) + '_' + str(point), next_node_name, weight = curr_edge['weight'])
					elif point == adj_point:
						simplified_E.add_edge(str(node_idx) + '_' + str(point), next_node_name, weight = 0)

		SHORTEST_E = nx.floyd_warshall_predecessor_and_distance(simplified_E)
		best_cost = "notset"
		best_route = []
		for target in valid_nodes[0]:
			pointer = target
			target = '0_' + str(target)
			route = []
			route.append(pointer)
			route_cost = 0

			while pointer != target:
				try:
					route_cost += SHORTEST_E[1][target][pointer]
					pointer = SHORTEST_E[0][target][pointer]
				except KeyError:
					break
				route.append(pointer)

			if len(route) == (len_valid_nodes + 1) and (best_cost == "notset" or best_cost > route_cost):
				best_route = copy.deepcopy(route)
				best_cost = route_cost

		best_route = best_route[::-1]
		best_route.pop()

		critical_points = []
		for point in best_route:
			critical_points.append(list(self.POINTS_ordered[int(point.split("_")[1])]))
		critical_points = np.array(critical_points)

		return critical_points
예제 #42
0
 def test_cycle(self):
     path, dist = nx.floyd_warshall_predecessor_and_distance(nx.cycle_graph(7))
     assert_equal(dist[0][3],3)
     assert_equal(path[0][3],2)
     assert_equal(dist[0][4],3)
def regularizeBoundary(indexedObject):

	t0 = time.time()
	obj = indexedObject[1]

	CIRCLE_RADIUS = 5
	MINIMUM_BOUNDARY = 70
	MAXIMUM_DISTANCE = 15
	MINIMUM_SIDES = 4

	obj_length = obj.shape
	obj_area = len(obj[obj != 0])

	lin_area = [60,86,113,137,140,146,152,155,158,176,183,187,191,194,198,202,209,221,231,240,247,254,265,280,289,290,293,294,299,307,317,332,344,369,386,398,415,424,446,256,472,485,517,532,571,590,611,634,671,689,713,722,755,781,796,893,938,970,1004,1050,1050,1107,1114,1153,1164,1226,1518,1598,1762,1830,1875,1985,2045,2212,2574,2829,2895,3038,3610,4299,5088,5261,5312,5961,10616,12586,20576]
	lin_min_e = [0.4,0.4,0.4,0.4,0.6,0.4,0.425,0.5,0.425,0.4,0.475,0.5,0.475,0.475,0.5,0.6,0.625,0.7,0.6,0.6,0.6,0.725,0.725,0.7,0.7,0.7,0.6,0.6,0.7,0.7,0.75,0.75,0.75,0.775,0.76,0.75,0.8,0.775,0.7,0.725,0.725,0.8,0.83,0.805,0.82,0.8,0.85,0.85,0.9,0.87,0.9,0.9,0.9,0.92,1.0,1.0,1.0,0.95,1.0,0.9,0.95,1.0,1.0,1.0,1.0,1.0,0.9,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0]
	lin_temp = [1.0,1.0,1.0,1.0,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.5,2.5,2.5,2.5,2.5,2.5,2.5,2.5,2.5,2.5,3.0,3.0,3.0,3.0,3.0,3.0,3.5,3.5,3.5,3.5]

	f1_min_e = interp1d(lin_area, lin_min_e)
	f2_temp = interp1d(lin_area, lin_temp)

	if obj_area < TRAINING_MIN_AREA:
		obj_area = TRAINING_MIN_AREA
	elif obj_area > TRAINING_MAX_AREA:
		obj_area = TRAINING_MAX_AREA

	MIN_E_DISTANCE = f1_min_e(obj_area)
	CURR_MAX_TEMP = f2_temp(obj_area)

	if CURR_MAX_TEMP % 0.5 != 0.0:
		CURR_MAX_TEMP = round(CURR_MAX_TEMP * 2.0) / 2.0


	original_image = np.zeros((obj_length[0]+CIRCLE_RADIUS*2,obj_length[1]+CIRCLE_RADIUS*2),dtype=np.uint)
	original_image[CIRCLE_RADIUS:obj_length[0]+CIRCLE_RADIUS,CIRCLE_RADIUS:obj_length[1]+CIRCLE_RADIUS] = obj

	#REMOVE TAILS
	cleaned_image = opening(original_image, square(5))

	labeled_image, num_of_labels = ndimage.measurements.label(cleaned_image, [[1,1,1],[1,1,1],[1,1,1]])
	
	if num_of_labels > 1:
		b_slices = ndimage.find_objects(labeled_image)
		area = []
		for idx,s in enumerate(b_slices):
			area.append(len(cleaned_image[cleaned_image[s] != 0]))
		cleaned_image[labeled_image != (area.index( max(area))) + 1] = 0


	# area = np.bincount(obj.flatten())[indexedObject[0]]
	area = len(cleaned_image[cleaned_image!=0])

	if area < 10:

		zeros = np.zeros(original_image.shape,dtype=np.uint8)
		return indexedObject[0],zeros,indexedObject[2]


	boundary_image = find_boundaries(cleaned_image, mode='inner').astype(np.uint8) #value = 1
	# orig_rough_building = copy.deepcopy(boundary_image)
	orig_rough_boundaries = find_boundaries(original_image, mode='inner').astype(np.uint8)
	orig_rough_building = copy.deepcopy(orig_rough_boundaries)
	# pickle.dump( orig_rough_building, open( "orig_footprint_1003.p", "wb" ) )
	orig_rough_building = ndimage.binary_fill_holes(orig_rough_building)
	orig_rough_building = orig_rough_building * 1


	nonzero_x, nonzero_y = np.nonzero(boundary_image)
	zip_nonzero = zip(nonzero_x, nonzero_y)

	#SUBJECT TO CHANGE!!!!!!!!!!!!!!!!!!!!!!!!!
	# ordered_points = moore_neighbor_tracing(zip_nonzero, boundary_image)
	ordered_points = neighbor_tracing(zip_nonzero)

	# exit()
	for point in zip_nonzero:
		segments = []
		circle_x, circle_y = circle_perimeter(point[0],point[1],CIRCLE_RADIUS)
		circle_points = np.array(list(sorted(set(zip(circle_x,circle_y)))))

		sortedpoints = np.empty([len(circle_points), 2], dtype=int)

		test1 = circle_points[circle_points[:,0] == point[0] - CIRCLE_RADIUS]
		start = len(test1)
		end = len_cpoints = len(sortedpoints)
		sortedpoints[0:start] = test1

		for x in xrange(point[0] - CIRCLE_RADIUS + 1, point[0] + CIRCLE_RADIUS):
			test1 = circle_points[circle_points[:,0] == x]
			testlen = len(test1)
			if x <= point[0]:
				sortedpoints[start:start+testlen/2] = test1[testlen/2:]
				sortedpoints[end-testlen/2:end] = test1[:testlen/2]
			else:
				sortedpoints[start:start+testlen/2] = test1[testlen/2:][::-1]
				sortedpoints[end-testlen/2:end] = test1[:testlen/2][::-1]
			start += testlen/2
			end -= testlen/2

		test1 = circle_points[circle_points[:,0] == point[0] + CIRCLE_RADIUS]
		sortedpoints[start:start + len(test1)] = test1[::-1]

		for c_perimeter in sortedpoints:
			segments.append(True)
			line_x, line_y = line(point[0], point[1], c_perimeter[0], c_perimeter[1])
			for line_points in zip(line_x,line_y)[1:]:
				# if original_image[line_points[0]][line_points[1]] != 0:
				if cleaned_image[line_points[0]][line_points[1]] != 0:
					segments[-1] = False
					break

		min_boundpoints = (MINIMUM_BOUNDARY / 360.0) * len_cpoints

		seg_sizes = []
		new_segment = True
		for segment in segments:
			if segment:
				if new_segment:
					seg_sizes.append(1)
					new_segment = False
				else:
					seg_sizes[-1] += 1
			else:
				new_segment = True

		if segments[0] == True and segments[-1] == True and len(seg_sizes) > 1:
			seg_sizes[0] = seg_sizes[0] + seg_sizes[-1]
			seg_sizes.pop()
		
		if(len(seg_sizes) == 0 or max(seg_sizes) < min_boundpoints):
			boundary_image[point[0]][point[1]] = 0

			if (point[0],point[1]) in ordered_points:  ## IDENTIFY KUNG BAKIT NAGKA-ERRROR, EXAMPLE pt000120_merged4.py obj 1301
				ordered_points.remove((point[0],point[1]))


	# print "Obtaining All Possible Edges..."
	G=nx.DiGraph()
	E=nx.DiGraph()
	len_ordered_points = len(ordered_points)

	for idx in xrange(0,len_ordered_points):

		
		next_idx = (idx+1) % len_ordered_points
		dist = math.hypot(ordered_points[idx][0] - ordered_points[next_idx][0], ordered_points[idx][1] - ordered_points[next_idx][1])
		G.add_edge(idx,next_idx,weight=dist)
		G.add_edge(idx,str(next_idx),weight=dist)
		E.add_edge(idx,next_idx,weight=0)
		E.add_edge(idx,str(next_idx),weight=0)

		# idx2 = idx - 2
		idx2 = (idx + 2) % len_ordered_points
		fail_counter = 0

		while((idx2 + 1) % len_ordered_points != idx and fail_counter < 20):  #?

			counter = 0
			total_distance = 0.0
			average_distance = 0.0
			base   = math.hypot(ordered_points[idx][0] - ordered_points[idx2][0], ordered_points[idx][1] - ordered_points[idx2][1])
			idx3 = (idx + 1) % len_ordered_points

			while(idx2 != idx3): #?

				side_1 = math.hypot(ordered_points[idx][0] - ordered_points[idx3][0], ordered_points[idx][1] - ordered_points[idx3][1])
				side_2 = math.hypot(ordered_points[idx2][0] - ordered_points[idx3][0], ordered_points[idx2][1] - ordered_points[idx3][1])
				semi_perimeter = (side_1 + side_2 + base) / 2.0
				temp = semi_perimeter * (semi_perimeter - side_1) * (semi_perimeter - side_2) * (semi_perimeter - base)
				if temp < 0:
					temp = 0
				area   = math.sqrt(temp)
				height = (2.0 * area) / base
				Ax = ordered_points[idx][0]           
				Ay = ordered_points[idx][1]
				Bx = ordered_points[idx2][0]
				By = ordered_points[idx2][1]
				Cx = ordered_points[idx3][0]
				Cy = ordered_points[idx3][1]
				position = np.sign((Bx-Ax)*(Cy-Ay) - (By-Ay)*(Cx-Ax))
				total_distance += height * position
				average_distance += height
				counter += 1
				idx3 = (idx3 + 1) % len_ordered_points

			average_distance /= counter

			# if average_distance <= MIN_E_DISTANCE and total_distance >= -MIN_E_DISTANCE and total_distance < 30:
			if average_distance <= MIN_E_DISTANCE:
				G.add_edge(idx,idx2,weight=base)
				G.add_edge(idx,str(idx2),weight=base)
				E.add_edge(idx,idx2,weight=average_distance)
				E.add_edge(idx,str(idx2),weight=average_distance)
				fail_counter = 0
			else:
				fail_counter += 1

			idx2 = (idx2 + 1) % len_ordered_points


	F = nx.floyd_warshall_predecessor_and_distance(G)

	best_route = []
	count = 0
	for target in xrange(0,len_ordered_points):
		pointer = str(target)
		route = []
		route.append(pointer)

		while pointer != target:
			pointer = F[0][target][pointer]
			route.append(pointer)
		if len(route) == 7:
			count += 1
		if len(best_route) == 0 or len(best_route) > len(route):
			best_route = copy.deepcopy(route)
	#print best_route

	#######################################CODE 4/29/16
	#######################################CODE 4/29/16
	NEIGHBOR_TRESHOLD = 6

	valid_nodes = []
	best_route = best_route[::-1]
	best_route.pop()

	for point in best_route:
		point = int(point)
		valid_nodes.append([point])
		for i in xrange(1, (NEIGHBOR_TRESHOLD / 2) + 1):
			valid_nodes[-1].append((point + i) % len_ordered_points)
			valid_nodes[-1].append((point - i) % len_ordered_points)
	#print "VALID", valid_nodes
	#print len(valid_nodes)
	len_valid_nodes = len(valid_nodes)
	simplified_E=nx.DiGraph()

	for node_idx in xrange(0, len(valid_nodes)):
		next_node = (node_idx + 1) % len(valid_nodes)
		for point in valid_nodes[node_idx]:
			# print "2ndLOOP: ",point
			for adj_point in valid_nodes[next_node]:
				# print "3rdLOOP:", adj_point
				curr_edge = E.get_edge_data(point, adj_point, False)

				if next_node != 0:
					next_node_name = str(next_node) + '_' + str(adj_point)
				else:
					next_node_name = adj_point

				if curr_edge != False:
					simplified_E.add_edge(str(node_idx) + '_' + str(point), next_node_name, weight = curr_edge['weight'])
					# print "1: ", str(node_idx) + '_' + str(point), next_node_name
				elif point == adj_point:
					simplified_E.add_edge(str(node_idx) + '_' + str(point), next_node_name, weight = 0)	
					# print "2: ", str(node_idx) + '_' + str(point), next_node_name

	SHORTEST_E = nx.floyd_warshall_predecessor_and_distance(simplified_E)
	# print SHORTEST_E
	best_cost = "notset"
	best_route = []
	for target in valid_nodes[0]:
		pointer = target
		target = '0_' + str(target)
		route = []
		route.append(pointer)
		route_cost = 0

		while pointer != target:
			try:
				route_cost += SHORTEST_E[1][target][pointer]
				pointer = SHORTEST_E[0][target][pointer]
			except KeyError:
				break
			route.append(pointer)

		if len(route) == (len_valid_nodes + 1) and (best_cost == "notset" or best_cost > route_cost):
		# if best_cost == False or (best_cost > route_cost and len(best_route) == len(route)):
			#print 'HEHEHEHEY'
			#print best_route, route
			#print best_cost
			#print best_cost, ">", route_cost, best_cost > route_cost
			#print len(route), "==", (len_valid_nodes + 1), len(route) == (len_valid_nodes + 1)
			best_route = copy.deepcopy(route)
			best_cost = route_cost

	best_route = best_route[::-1]
	best_route.pop()

	footprint = []
	for point in best_route:
		footprint.append(list(ordered_points[int(point.split("_")[1])]))

	
	critical_points = copy.deepcopy(boundary_image)

	for point in footprint:
		critical_points[point[0], point[1]] = 5

	#print "JEJEJEJEJEJJEJEJEJE", MIN_E_DISTANCE

	adjusted_route = adjust_route_v2(np.array(footprint)) 	
	# adjusted_route = adjust_route(np.array(footprint),mask_BR, max_temp = CURR_MAX_TEMP) 		
	# print np.array(footprint)
	# print "nyahahahaha"
	# print adjusted_route
	# 
	# 
	SA_building = np.zeros(boundary_image.shape, dtype=np.uint8)
	# print adjusted_route
	for idx in xrange(0, len(adjusted_route)):
		rr, cc = line(adjusted_route[idx][0], adjusted_route[idx][1], adjusted_route[idx-1][0], adjusted_route[idx-1][1])
		SA_building[rr,cc] = 1

	SA_building = ndimage.binary_fill_holes(SA_building)
	SA_building = SA_building * 1

	for idx in xrange(0, len(adjusted_route)):
		SA_building[adjusted_route[idx][0], adjusted_route[idx][1]] = 2


	final_route = copy.deepcopy(adjusted_route)

	try:

		adjust_itr = 1
		MAX_ITR_FOR_ADJUSTING = 2
		while adjust_itr <= MAX_ITR_FOR_ADJUSTING:
			adjusted_sides = adjust_sides(final_route, orig_rough_building)
			adjusted_rotation = adjust_rotation(adjusted_sides, orig_rough_building)
			# print "POTOTOY",adjust_itr, (final_route == adjusted_rotation)
			if np.array_equal(final_route,adjusted_rotation):
				# final_route = copy.deepcopy(adjusted_rotation)
				break
			else:
				final_route = copy.deepcopy(adjusted_rotation)
				adjust_itr += 1
	except:
		print "Something went terribly wrong. Sht. I was working on index ", indexedObject[0]

	# final_route = copy.deepcopy(adjusted_route)
	# adjust_itr = 1
	# MAX_ITR_FOR_ADJUSTING = 2
	# while adjust_itr <= MAX_ITR_FOR_ADJUSTING:
	# 	adjusted_rotation = adjust_rotation(final_route, orig_rough_building)
	# 	adjusted_sides = adjust_sides(adjusted_rotation, orig_rough_building)
	# 	# print "POTOTOY",adjust_itr, (final_route == adjusted_rotation)
	# 	if np.array_equal(final_route,adjusted_sides):
	# 		# final_route = copy.deepcopy(adjusted_rotation)
	# 		break
	# 	else:
	# 		final_route = copy.deepcopy(adjusted_sides)
	# 		adjust_itr += 1
			
	# adjusted_sides = adjust_sides(adjusted_route, orig_rough_building)
	# adjusted_rotation = adjust_rotation(adjusted_sides, orig_rough_building)
	# final_route = adjust_sides(adjusted_rotation, orig_rough_building)
	#print "ADJUSTING ITERATION", adjust_itr
	Adjusted_building = np.zeros(boundary_image.shape, dtype=np.uint8)

	for idx in xrange(0, len(final_route)):
		rr, cc = line(final_route[idx][0], final_route[idx][1], final_route[idx-1][0], final_route[idx-1][1])
		Adjusted_building[rr,cc] = 1

	Adjusted_building = ndimage.binary_fill_holes(Adjusted_building)
	Adjusted_building = Adjusted_building * 1

	for idx in xrange(0, len(final_route)):
		Adjusted_building[final_route[idx][0], final_route[idx][1]] = 2

	patong = copy.deepcopy(orig_rough_boundaries)
	patong[Adjusted_building > 0] = 2
	patong[orig_rough_boundaries != 0] = 1

	# approx_image = copy.deepcopy(boundary_image)
	# approx_image[approx_image > 0] = 0

	# len_points = len(final_route)
	# for idx in xrange(0,len_points-1):
	# 	rr,cc = line(final_route[idx][0], final_route[idx][1], final_route[idx+1][0], final_route[idx+1][1])
	# 	approx_image[rr,cc] = 4
	# 	approx_image[final_route[idx][0], final_route[idx][1]] = 5
	# 	approx_image[final_route[(idx+1)% len_points][0], final_route[(idx+1)% len_points][1]] = 5
	# rr,cc = line(final_route[len_points-1][0], final_route[len_points-1][1], final_route[0][0], final_route[0][1])
	# approx_image[rr,cc] = 4

	# approx_image[approx_image>0] = 1
	# filled = ndimage.binary_fill_holes(approx_image)
	# filled = filled*1	
	# filled[filled==1] = indexedObject[0] 
	
	# test = copy.deepcopy(boundary_image)
	# test[filled > 0] = 2
	# test[boundary_image != 0] = 1

	Adjusted_building[Adjusted_building!=0] = indexedObject[0]

	t1=time.time()
	print "Finished processing index",indexedObject[0],"in",round(t1-t0,2),"s."		
	# return indexedObject[0],filled,indexedObject[2]
	# return indexedObject[0],filled,indexedObject[2]
	# 
	

	return indexedObject[0],Adjusted_building,indexedObject[2]
예제 #44
0
G=nx.Graph()

print "Reading category file"
with open(categoryLinksFile, 'rb') as f:
    reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_ALL, quotechar ='"', escapechar='\\', doublequote=False)
    for row in reader:
        G.add_node(row[0])
        G.add_node(row[1])
        G.add_edge(row[0], row[1])
	    #G.add_edge(row[1], row[0])

print "Floyd-Warshall"
#path = nx.all_pairs_dijkstra_path(G)
#path = nx.all_pairs_shortest_path_length(G)
#path = nx.floyd_warshall(G)
path = nx.floyd_warshall_predecessor_and_distance(G)


#print G.nodes()
#print path

print "Generating categories for each page"
with open(pageFile, 'rb') as f:
    reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_ALL, quotechar ='"', escapechar='\\', doublequote=False)
    
    for (page, cat) in reader:


        if cat not in path:
            #print "Page: ", row[0], " has category ", row[1], " which is not in paths map"
            continue