示例#1
0
def path_menu(graph):
    done = False
    while not done:
        response = input("(1) Shortest Path, (2) Route Information, (Q)uit: ")
        if response == "Q":
            done = True
        elif response == "1":
            graph.shortest_path()
        elif response == "2":
            print(graph.route_info())
        elif response == "99": #debug only
            graph.dijkstra(graph.g, "FIH", "CAI")
示例#2
0
def run(edges, connections, speedChanges, optimalization, nogui):
    '''execute the TraCI control loop'''
    traci.init(PORT)
    if not nogui:
        traci.gui.trackVehicle('View #0', '0')
    #print 'route: {0}'.format(traci.vehicle.getRoute('0'))
    destination = traci.vehicle.getRoute('0')[-1]
    edgesPoll = list(edges)

    time = traci.simulation.getCurrentTime()
    while traci.simulation.getMinExpectedNumber() > 0:
        if optimalization:
            change_edge_speed(edgesPoll, edges, speedChanges)
            edge = traci.vehicle.getRoadID('0')
            if edge in edges and traci.vehicle.getLanePosition(
                    '0') >= 0.9 * traci.lane.getLength(
                        traci.vehicle.getLaneID('0')):
                shortestPath = graph.dijkstra(edge, destination, edges,
                                              get_costs(edges), connections)
                #print 'dijkstra: {0}'.format(shortestPath)
                traci.vehicle.setRoute('0', shortestPath)
        else:
            if len(speedChanges) > 0:
                edge, speed = speedChanges.pop()
                traci.edge.setMaxSpeed(edge, speed)
            else:
                change_edge_speed(edgesPoll, edges, [])
        traci.simulationStep()
    time = traci.simulation.getCurrentTime() - time
    traci.close()
    sys.stdout.flush()
    return time
示例#3
0
文件: main.py 项目: Szagrat/Project
def run(edges, connections, speedChanges, optimalization, nogui):
    '''execute the TraCI control loop'''
    traci.init(PORT)
    if not nogui:
        traci.gui.trackVehicle('View #0', '0')
    #print 'route: {0}'.format(traci.vehicle.getRoute('0'))
    destination = traci.vehicle.getRoute('0')[-1]
    edgesPoll = list(edges)

    time = traci.simulation.getCurrentTime()
    while traci.simulation.getMinExpectedNumber() > 0:
        if optimalization:
            change_edge_speed(edgesPoll, edges, speedChanges)
            edge = traci.vehicle.getRoadID('0')
            if edge in edges and traci.vehicle.getLanePosition('0') >= 0.9 * traci.lane.getLength(traci.vehicle.getLaneID('0')):
                shortestPath = graph.dijkstra(edge, destination, edges, get_costs(edges), connections)
                #print 'dijkstra: {0}'.format(shortestPath)
                traci.vehicle.setRoute('0', shortestPath)
        else:
            if len(speedChanges) > 0:
                edge, speed = speedChanges.pop()
                traci.edge.setMaxSpeed(edge, speed)
            else:
                change_edge_speed(edgesPoll, edges, [])
        traci.simulationStep()
    time = traci.simulation.getCurrentTime() - time
    traci.close()
    sys.stdout.flush()
    return time
示例#4
0
 def __stabilize_children(self, parent_node, subset):
     self.__steiner_distances[parent_node][tuple(subset)].sort()
     child = self.__steiner_distances[parent_node][tuple(subset)][0]
     while child[5] == 'E':
         child_node = child[1]
         distances, paths = dijkstra(self.__graph, parent_node,
                                     [child_node])
         # for k, v in distances.iteritems():
         #     self.__distances[tuple(sorted([parent_node, k]))] = (v, 'N')
         # for k, v in paths.iteritems():
         #     self.__paths[tuple(sorted([parent_node, k]))] = v
         # try:
         #     self.__paths[tuple(sorted([parent_node, child_node]))] = paths[child_node]
         # except KeyError:
         #     pass
         #     # print("KeyError!")
         try:
             # Update total cost of the parent node for this candidate child.
             self.__steiner_distances[parent_node][tuple(
                 subset)][0][0] = child[4] + distances[child_node]
             # Update distance between the parent and this candidate child.
             self.__steiner_distances[parent_node][tuple(
                 subset)][0][3] = distances[child_node]
         except KeyError:
             self.__steiner_distances[parent_node][tuple(
                 subset)][0][0] = sys.maxint
             self.__steiner_distances[parent_node][tuple(
                 subset)][0][3] = sys.maxint
         # Advise the distance between nodes is a network distance.
         self.__steiner_distances[parent_node][tuple(subset)][0][5] = 'N'
         # Sort the candidates list to check if priorities have changed.
         self.__steiner_distances[parent_node][tuple(subset)].sort()
         # Retrieve new best candidate.
         child = self.__steiner_distances[parent_node][tuple(subset)][0]
示例#5
0
    def steiner_tree(self):
        subtrees = []
        _, paths = dijkstra(self.__graph, self.__poi, self.__terminals)
        for t in self.__terminals:
            path = paths[t]
            subtree = SuitabilityGraph()
            # j = 0
            # for i in range(len(path_to_poi)):
            #     if path_to_poi[i] in self.__graph.contracted_regions:
            #         region_id = path_to_poi[i]
            #         subtree.append_from_path(path_to_poi[j:i], self.__original_graph)
            #         closest_node = self.__find_closest_node_to_poi_within_region(region_id)
            #         path_endpoint_1 = self.__dist_paths_node_within_region_node[closest_node][1][path_to_poi[i - 1]]
            #         subtree.append_from_path(path_endpoint_1, self.__original_graph)
            #         path_endpoint_2 = self.__dist_paths_node_within_region_node[closest_node][1][path_to_poi[i + 1]]
            #         subtree.append_from_path(path_endpoint_2, self.__original_graph)
            #         j = i + 1
            # subtree.append_from_path(path_to_poi[j:], self.__original_graph)
            subtree.append_path(path, self.__graph)
            subtrees.append(subtree)

        steiner_tree = self.__merge_subtrees(subtrees)
        self.__prune_steiner_tree(steiner_tree)

        if self.__contract_graph:
            self.__decontract_steiner_tree(steiner_tree)

        return steiner_tree
示例#6
0
def search(filename, origin, destination):
	origin = origin.upper()
	destination = destination.upper()
	#print("origin: " + origin)
	#print("destination: " + destination)
	stops = get_stops(filename)
	#print(stops)

	if(origin in stops and destination in stops):
		if(origin == destination):
			return "<p>Lähtö- ja päätepysäkki ovat samat!</p>"
		else:
			data = parse.parse(filename)		
			g = graph.create(data)
			#print_graph(g)		

			dijkstra = graph.dijkstra(g, g.get_vertex(origin), g.get_vertex(destination))

			target = g.get_vertex(destination)
			path = [target.id]
			graph.shortest(target, path)
			#print("The shortest path: {}".format(path[::-1]))

			return finder.find_lines_from_route(path[::-1], data)
	else:
		return None
示例#7
0
def solve(file):
	values = parse_file(file)
	ymax = max([value[1] for value in values.keys()])
	xmax = max([value[0] for value in values.keys()])
	print "max:",xmax,ymax
	graph = matrix_graph(xmax,ymax,values)
	dresult = dijkstra(graph,(1,1))
	print values[(1,1)]+dresult[(xmax,ymax)]
示例#8
0
def build_path(g, start, end):
    p = graph.dijkstra(g, start)
    node = p[1][end]
    path = [end]
    while node != start:
        path.insert(0, node)
        node = p[1][node]
    path.insert(0, start)
    return path
示例#9
0
 def __find_closest_node_to_node_within_region(self, node, region_id):
     region = self.__graph.contracted_regions[region_id][0]
     min_dist = sys.maxint
     closest_node = None
     distances, paths = dijkstra(self.__original_graph, node, region.keys())
     for n in region:
         if distances[n] < min_dist:
             closest_node = n
             min_dist = distances[n]
     return closest_node, paths[closest_node]
示例#10
0
def solve(file):
	values = parse_file(file)
	ymax = max([value[1] for value in values.keys()])
	xmax = max([value[0] for value in values.keys()])
	print "max:",xmax,ymax
	graph = matrix_graph(xmax,ymax,values)
	for key in sorted(graph.keys()):
		print key,graph[key]
	sums = []
	for y in range(1,ymax+1):
		dresult = dijkstra(graph,(1,y))
		for yp in range(1,ymax+1):
			sums.append(values[(1,y)]+dresult[(xmax,yp)])
	print min(sums)
示例#11
0
def run(waze: Waze, source: str, dest: str) -> Result:
    """função de resolução do grafo Waze e tratamento do resultado"""

    # deepcopy pra esquecer as velocidades assumidas
    graph = deepcopy(waze)

    path = dijkstra(graph, source, dest)
    if not path:
        # caminho não encontrado
        return None

    # montagem do resultado
    keys = map(attrgetter('key'), path[1])
    return tuple(keys), path[0].time
示例#12
0
    def __init__(self,
                 graph,
                 terminals,
                 poi,
                 dist_paths_suitable_nodes_contracted_graph=None):
        self.__graph = graph
        self.__terminals = terminals
        self.__poi = poi

        terminals_poi = list(terminals)
        terminals_poi.append(poi)

        self.__dist_paths = None
        if dist_paths_suitable_nodes_contracted_graph is not None:
            self.__dist_paths = dict(
                dist_paths_suitable_nodes_contracted_graph)
            for e in terminals_poi:
                self.__dist_paths[e] = dijkstra(self.__graph, e)
示例#13
0
 def __build_steiner_tree(self, node, subset):
     steiner_tree = SuitabilityGraph()
     next_node = self.__s_d[node][subset][0][3]
     print(node, self.__s_d[node][subset])
     # pdb.set_trace()
     if next_node is not None:
         try:
             steiner_tree.append_path(
                 self.__paths[tuple(sorted([node, next_node]))],
                 self.__graph)
         except KeyError:
             _, paths = dijkstra(self.__graph, node, [next_node])
             steiner_tree.append_path(paths[next_node], self.__graph)
     (set_e, set_f) = self.__s_d[node][subset][0][4]
     steiner_branch_e = SuitabilityGraph()
     if set_e is not None and set_e != [next_node]:
         steiner_branch_e = self.__build_steiner_tree(next_node, set_e)
     steiner_branch_f = SuitabilityGraph()
     if set_f is not None and set_f != [next_node] and len(set_f) > 0:
         steiner_branch_f = self.__build_steiner_tree(next_node, set_f)
     steiner_tree.append_graph(steiner_branch_e)
     steiner_tree.append_graph(steiner_branch_f)
     return steiner_tree
示例#14
0
 def __build_steiner_tree_bactracking(self, node, subset):
     steiner_tree = SuitabilityGraph()
     next_node = self.__steiner_distances[node][tuple(subset)][3]
     # pdb.set_trace()
     if next_node is not None:
         try:
             steiner_tree.append_path(
                 self.__paths[tuple(sorted([node, next_node]))],
                 self.__graph)
         except KeyError:
             _, paths = dijkstra(self.__graph, node, [next_node])
             steiner_tree.append_path(paths[next_node], self.__graph)
     (best_e, best_f) = self.__steiner_distances[node][tuple(subset)][4]
     steiner_branch_e = SuitabilityGraph()
     if best_e is not None and best_e != [next_node]:
         steiner_branch_e = self.__build_steiner_tree_bactracking(
             next_node, best_e)
     steiner_branch_f = SuitabilityGraph()
     if best_f is not None and best_f != [next_node] and len(best_f) > 0:
         steiner_branch_f = self.__build_steiner_tree_bactracking(
             next_node, best_f)
     steiner_tree.append_graph(steiner_branch_e)
     steiner_tree.append_graph(steiner_branch_f)
     return steiner_tree
示例#15
0
文件: readGraph.py 项目: s4boys/s4m
import graph
from collections import namedtuple
import re, sys

infile = sys.argv[1]
infile = open(infile, "r")

graph = graph.Graph()

for i, line in enumerate(infile):
    if i == 1:
        s = line.split(', ')
    if i > 2:
        nodes = graph.get_nodes()
        words = line.split()
        if words[0] not in graph.get_nodes():
            graph.add_node(words[0])
        elif words[1] not in graph.get_nodes():
            graph.add_node(words[1])
        graph.add_edge(int(words[0]), int(words[1]), int(words[2]))
print(graph.get_nodes())
graph.dijkstra(1, 10)
示例#16
0
        x_3.append(xk[2, 0])
        u_1.append(uk[0, 0])
        u_2.append(uk[1, 0])
        u_3.append(uk[2, 0])
        xk = A_lqr * xk + B_lqr * uk

    return x_1, x_2, x_3, u_1, u_2, u_3


time_start = time.time()
graph = generate_qraph()
graph.create_csv()
time_graph_end = time.time()
print("graph generation time: ", time_graph_end - time_start)

path = gr.dijkstra(graph, initial_state, end_state)
time_dijkstra_end = time.time()
print("graph solving time: ", time_dijkstra_end - time_graph_end)

lqr_initial_state = (initial_state[0] - end_state[0],
                     initial_state[1] - end_state[1],
                     initial_state[2] - end_state[2])
x1_lqr, x2_lqr, x3_lqr, u1_lqr, u2_lqr, u3_lqr = solve_lqr(lqr_initial_state)

h1_lqr = [i + end_state[0] for i in x1_lqr]
h2_lqr = [i + end_state[1] for i in x2_lqr]
h3_lqr = [i + end_state[2] for i in x3_lqr]

u1_lqr = [i + u_end[0] for i in u1_lqr]
u2_lqr = [i + u_end[1] for i in u2_lqr]
u3_lqr = [i + u_end[2] for i in u3_lqr]
示例#17
0
    def __init__(self,
                 graph,
                 terminals,
                 poi,
                 max_level_attraction=2,
                 contract_graph=True,
                 contracted_graph=None,
                 within_convex_hull=False,
                 dist_paths_suitable_nodes=None):

        if not graph.is_node_weighted():
            raise (
                ValueError,
                "Gravitation algorithm only works with node-weighted graphs.")

        # Store class variables for future references.
        self.__original_graph = graph
        self.__terminals = terminals
        self.__poi = poi
        self.__contract_graph = contract_graph

        #
        terminals_poi = list(terminals)
        terminals_poi.append(poi)

        generator = SuitableNodeWeightGenerator()

        # Contracted graph...
        if contract_graph:
            if contracted_graph is not None:
                self.__graph = contracted_graph.copy()
            else:
                self.__graph = SuitabilityGraph()
                self.__graph.append_graph(graph)
                self.__graph.contract_suitable_regions(
                    generator, excluded_nodes=terminals_poi)
        else:
            self.__graph = SuitabilityGraph()
            self.__graph.append_graph(graph)

        # #
        # ngh = NetworkXGraphHelper(self.__original_graph)
        # ngh.draw_graph(nodes_1=terminals,
        #                nodes_2=[poi],
        #                subgraphs_1=[r for _, (r, _, _) in self.__graph.contracted_regions.iteritems()],
        #                node_weight_generator=generator,
        #                node_size=25)
        # #
        # ngh = NetworkXGraphHelper(self.__graph)
        # ngh.draw_graph(node_weight_generator=generator, node_size=25, node_labels=True)

        # Copy distances and paths dictionary since it will be changed.
        dist_paths = None
        if dist_paths_suitable_nodes is not None:
            dist_paths = dict(dist_paths_suitable_nodes)
            for e in terminals_poi:
                dist_paths[e] = dijkstra(self.__graph, e)

        # Get the suitable nodes.
        if within_convex_hull:
            self.__suitable_nodes = self.__graph.get_suitable_nodes_within_convex_set(
                terminals_poi, generator, dist_paths)
        else:
            self.__suitable_nodes = self.__graph.get_suitable_nodes(
                generator, excluded_nodes=terminals_poi)
        # print(self.__suitable_nodes)

        #
        self.__dist_paths_node_node = {}
        if dist_paths is not None:
            self.__dist_paths_node_node = {
                n: dist_paths[n]
                for n in self.__suitable_nodes
            }
        else:
            self.__dist_paths_node_node = \
                {n: dijkstra(self.__graph, n) for n in self.__suitable_nodes}
        for e in terminals_poi:
            if e not in self.__dist_paths_node_node:
                self.__dist_paths_node_node[e] = dijkstra(self.__graph, e)

        #
        max_distances = [
            max(self.__dist_paths_node_node[n][0].values())
            for n in self.__suitable_nodes
            if len(self.__dist_paths_node_node[n][0].values()) > 0
        ]
        if len(max_distances) > 0:
            self.__max_dist = max(max_distances)
        else:
            self.__max_dist = 0

        # #
        # max_level_attraction_poi = 0
        # for t in terminals:
        #     max_level_attraction_poi = max(max_level_attraction_poi, len(self.__dist_paths_node_node[poi][1][t]))
        # mass = self.__calculate_mass_suitable_node(poi)
        # self.__attract_nodes_to(poi, mass, poi, max_level_attraction_poi, 0, [])

        #
        dist_to_poi = {}
        for n in self.__suitable_nodes:
            try:
                dist_to_poi[n] = self.__dist_paths_node_node[n][0][poi]
            except KeyError:
                dist_to_poi[n] = sys.maxint
        # dist_to_poi = {n: self.__dist_paths_node_node[n][0][poi] for n in self.__suitable_nodes}
        # ord_suit_nodes = sorted(dist_to_poi.iteritems(), key=operator.itemgetter(1), reverse=True)
        ord_suit_nodes = sorted(dist_to_poi.iteritems(),
                                key=operator.itemgetter(1))
        for n, _ in ord_suit_nodes:
            mass = self.__calculate_mass_suitable_node(n)
            self.__attract_nodes_to(n, mass, n, max_level_attraction, 0, [])
示例#18
0
from random import Random
from draw import drawGraph, drawDijkstraGraph

rng = Random()
rng.seed = "A"
# Gen random nodes
NODECOUNT = 20
EXTRAEDGECOUNT = 2
MAXX, MAXY = 1000, 1000

nodes = []
for i in range(NODECOUNT):
    nodes += [Node(rng.randint(0, MAXX), rng.randint(0, MAXY))]

edges = []
for i in nodes:
    while True:
        a = rng.choice(nodes)
        if a != i:
            break
    edges += [(i, a)]
for i in range(EXTRAEDGECOUNT):
    a, b = None, None
    while a == b and not (a, b) in edges:
        a, b = rng.choice(nodes), rng.choice(nodes)
    edges += [(a, b)]
for n in nodes:
    n.calc_adjacent(edges)
dijkstra(nodes, edges, nodes[0], nodes[-1])
drawDijkstraGraph(nodes, edges, nodes[-1].get_path_to_root())
input()
示例#19
0
        edge_weighted=True,
        node_weighted=True,
        node_weight_generator=generator,
        # node_weights=node_weights,
        seed=seed)

    terminals = [
        1265, 1134, 1482, 1721, 677, 1567, 814, 1879, 635, 838, 2077, 2227, 911
    ]
    poi = 1226
    # terminals = [25, 85, 33, 67]
    # poi = 55

    suitability_graph = SuitabilityGraph()
    suitability_graph.append_graph(graph)

    # suitability_graph.contract_suitable_regions(generator)
    suitable_nodes = suitability_graph.get_suitable_nodes(generator)
    dist_paths = {n: dijkstra(suitability_graph, n) for n in suitable_nodes}

    start_time = time.clock()
    ch = ConvexHull(suitability_graph, terminals, poi, dist_paths)
    convex_hull = ch.compute(generator)
    print("time elapsed:", time.clock() - start_time)

    ngh = NetworkXGraphHelper(suitability_graph)
    ngh.draw_graph(nodes_2=terminals,
                   nodes_1=convex_hull,
                   node_weight_generator=generator,
                   print_edge_labels=False,
                   print_node_labels=False)
示例#20
0
 def testDijkstra(self):
     self.assertEqual([0, 7, 9, 20, 20, 11], dijkstra(self.graph_weighed, 0))
示例#21
0
    def __correct_j_s(self, i, subset):
        #
        # self.__s_d[i][subset].sort()
        j = self.__s_d[i][subset][0][3]
        old_j = j
        old_set_e, old_set_f = self.__s_d[i][subset][0][4]
        dd_t = self.__s_d[i][subset][0][5]
        count = 0
        #
        while dd_t == 'E':
            # ----------------------------------------------------------------------------------------------------------
            delta_dist = 0
            d_t_1 = self.__s_d[i][subset][0][6]
            if d_t_1 == 'E':
                #
                i_j_tuple = tuple(sorted([i, j]))
                if self.__distances[i_j_tuple][1] == 'N':
                    dist = self.__distances[i_j_tuple][0]
                else:
                    try:
                        distances, _ = dijkstra(self.__graph, i, [j])
                        dist = distances[j]
                        self.__distances[i_j_tuple] = (dist, 'N')
                    except KeyError:
                        dist = sys.maxint
                old_dist = self.__s_d[i][subset][0][2]
                delta_dist = dist - old_dist
                #
                self.__s_d[i][subset][0][0] += delta_dist
                self.__s_d[i][subset][0][2] = dist
                self.__s_d[i][subset][0][6] = 'N'
            # ----------------------------------------------------------------------------------------------------------
            delta_u = 0
            d_t_2 = self.__s_d[i][subset][0][7]
            d_t_3 = self.__s_d[i][subset][0][8]
            if d_t_2 == 'E' or d_t_3 == 'E':
                # if i == 3073194802L and subset == (30287961, 313278858, 1011956802, 1655220587):
                #     pdb.set_trace()
                u, set_e, set_f, delta_e, delta_f = self.__correct_e_f(
                    j, subset)
                self.__s_d[i][subset][0][4] = (set_e, set_f)
                delta_u = delta_e + delta_f
                #
                if u != self.__s_d[i][subset][0][1]:
                    delta_u = u - self.__s_d[i][subset][0][1]
                    self.__s_d[i][subset][0][0] += delta_u
                    self.__s_d[i][subset][0][1] += delta_u
                self.__s_d[i][subset][0][7] = 'N'
                self.__s_d[i][subset][0][8] = 'N'
            # ----------------------------------------------------------------------------------------------------------
            d_t_1 = self.__s_d[i][subset][0][6]
            d_t_2 = self.__s_d[i][subset][0][7]
            d_t_3 = self.__s_d[i][subset][0][8]
            if d_t_1 == 'N' and d_t_2 == 'N' and d_t_3 == 'N':
                self.__s_d[i][subset][0][5] = 'N'
            #
            delta = delta_dist + delta_u
            self.__s_d[i][subset][0][9] = delta
            if delta > 0 and count == 0:
                self.__propagate(delta, i, subset)
                if self.__s_d[i][subset][0][5] == 'N':
                    try:
                        del self.__refs[i][subset]
                    except KeyError:
                        pass
            count += 1
            #
            self.__s_d[i][subset].sort()
            j = self.__s_d[i][subset][0][3]
            dd_t = self.__s_d[i][subset][0][5]

        # Update refs
        j = self.__s_d[i][subset][0][3]
        set_e, set_f = self.__s_d[i][subset][0][4]
        if j != old_j or set_e != old_set_e or set_f != old_set_f:
            #
            try:
                self.__refs[old_j][old_set_e].remove((i, subset))
                self.__refs[old_j][old_set_f].remove((i, subset))
            except KeyError:
                pass
            #
            if j in self.__refs:
                if set_e in self.__refs[j]:
                    self.__refs[j][set_e].add((i, subset))
                else:
                    self.__refs[j][set_e] = {(i, subset)}
                if set_f in self.__refs[j]:
                    self.__refs[j][set_f].add((i, subset))
                else:
                    self.__refs[j][set_f] = {(i, subset)}
            else:
                self.__refs[j] = {set_e: {(i, subset)}, set_f: {(i, subset)}}

        return self.__s_d[i][subset][0][9]
示例#22
0
    def __stabilize_candidates_set(self, candidates, subset):
        candidates.sort()
        candidate = candidates[0]
        while candidate[5] == 'E':
            d_type_1 = candidate[6]
            d_type_2 = candidate[7]
            d_type_3 = candidate[8]
            n1 = candidate[3]
            n2 = candidate[4]
            # pdb.set_trace()
            if d_type_1 == 'E' and d_type_2 == 'N' and d_type_3 == 'N':
                dist_poi_and_cost = candidate[0]
                cost = candidate[1]
                dist = candidate[2]
                if self.__distances[tuple(sorted([n1, n2]))][1] == 'N':
                    dist_n2 = self.__distances[tuple(sorted([n1, n2]))][0]
                else:
                    distances, _ = dijkstra(self.__graph, n1, [n2])
                    try:
                        dist_n2 = distances[n2]
                    except KeyError:
                        print("Distance couldn't be found between:", n1, n2)
                        break

                self.__steiner_distances[n1][tuple(
                    subset)][0] = cost - dist + dist_n2
                self.__steiner_distances[n1][tuple(subset)][2] = dist_n2
                self.__steiner_distances[n1][tuple(subset)][5] = 'N'
                self.__steiner_distances[n1][tuple(subset)][6] = 'N'

                candidates[0][0] = dist_poi_and_cost - dist + dist_n2
                candidates[0][2] = dist_n2
                candidates[0][5] = 'N'
                candidates[0][6] = 'N'

                candidates.sort()
                candidate = candidates[0]

            elif not (d_type_1 == 'N' and d_type_2 == 'N' and d_type_3 == 'N'):
                # pdb.set_trace()
                best_e, best_f = candidate[9]

                print('----BEST E----')
                print(self.__steiner_distances[n2][tuple(best_e)])

                # hold_e = False
                # hold_f = False

                j_e = self.__steiner_distances[n2][tuple(best_e)][3]
                d_typ_1_e = self.__steiner_distances[n2][tuple(best_e)][6]
                d_typ_2_e = self.__steiner_distances[n2][tuple(best_e)][7]
                d_typ_3_e = self.__steiner_distances[n2][tuple(best_e)][8]

                if d_typ_1_e == 'E' and d_typ_2_e == 'N' and d_typ_3_e == 'N':
                    if self.__distances[tuple(sorted([n2, j_e]))][1] == 'N':
                        dist_j_e = self.__distances[tuple(sorted([n2,
                                                                  j_e]))][0]
                    else:
                        distances, _ = dijkstra(self.__graph, n2, [j_e])
                        try:
                            dist_j_e = distances[j_e]
                        except KeyError:
                            break

                    u_e = self.__steiner_distances[n2][tuple(best_e)][1]
                    self.__steiner_distances[n2][tuple(
                        best_e)][0] = u_e + dist_j_e
                    self.__steiner_distances[n2][tuple(best_e)][2] = dist_j_e
                    self.__steiner_distances[n2][tuple(best_e)][5] = 'N'
                    self.__steiner_distances[n2][tuple(best_e)][6] = 'N'

                    hold_e = True

                elif d_typ_1_e == 'N' and d_typ_2_e == 'N' and d_typ_3_e == 'N':
                    hold_e = True
                else:
                    print('Bad news!', n2, j_e, best_e)
                    break

                print('----BEST F----')
                print(self.__steiner_distances[n2][tuple(best_f)])

                j_f = self.__steiner_distances[n2][tuple(best_f)][3]
                d_typ_1_f = self.__steiner_distances[n2][tuple(best_f)][6]
                d_typ_2_f = self.__steiner_distances[n2][tuple(best_f)][7]
                d_typ_3_f = self.__steiner_distances[n2][tuple(best_f)][8]

                if d_typ_1_f == 'E' and d_typ_2_f == 'N' and d_typ_3_f == 'N':
                    if self.__distances[tuple(sorted([n2, j_f]))][1] == 'N':
                        dist_j_f = self.__distances[tuple(sorted([n2,
                                                                  j_f]))][0]
                    else:
                        distances, _ = dijkstra(self.__graph, n2, [j_f])
                        try:
                            dist_j_f = distances[j_f]
                        except KeyError:
                            break

                    u_f = self.__steiner_distances[n2][tuple(best_f)][1]
                    self.__steiner_distances[n2][tuple(
                        best_f)][0] = u_f + dist_j_f
                    self.__steiner_distances[n2][tuple(best_f)][2] = dist_j_f
                    self.__steiner_distances[n2][tuple(best_f)][5] = 'N'
                    self.__steiner_distances[n2][tuple(best_f)][6] = 'N'

                    hold_f = True

                elif d_typ_1_f == 'N' and d_typ_2_f == 'N' and d_typ_3_f == 'N':
                    hold_f = True
                else:
                    print('Bad news!', n2, j_f, best_f)
                    break

                # Update every node that is pointing to n2
                if hold_e and hold_f:
                    new_u = self.__steiner_distances[n2][tuple(best_e)][0] + \
                            self.__steiner_distances[n2][tuple(best_f)][0]
                    for i in self.__nodes:
                        if self.__steiner_distances[i][tuple(subset)][3] == n2 and \
                                        self.__steiner_distances[i][tuple(subset)][4][0] == best_e and \
                                        self.__steiner_distances[i][tuple(subset)][4][1] == best_f:
                            # pdb.set_trace()
                            dist = self.__steiner_distances[i][tuple(
                                subset)][2]
                            self.__steiner_distances[i][tuple(
                                subset)][0] = dist + new_u
                            self.__steiner_distances[i][tuple(
                                subset)][1] = new_u
                            self.__steiner_distances[i][tuple(subset)][7] = 'N'
                            self.__steiner_distances[i][tuple(subset)][8] = 'N'

                    # Update candidates
                    for i in range(len(candidates)):
                        c = candidates[i]
                        if c[3] == n1 and c[4] == n2 and candidate[9][
                                0] == best_e and candidate[9][1] == best_f:
                            # pdb.set_trace()
                            dist_poi_and_cost = candidates[i][0]
                            cost = candidates[i][1]
                            candidates[i][0] = dist_poi_and_cost - cost + new_u
                            candidates[i][1] = new_u
                            candidates[i][7] = 'N'
                            candidates[i][8] = 'N'

            elif d_type_1 == 'N' and d_type_2 == 'N' and d_type_3 == 'N':
                candidates[0][5] = 'N'

        print(candidates)
示例#23
0
    def compute(self, generator):

        # list_1 = set()
        # list_2 = list(self.__terminals)
        # if self.__poi not in list_2:
        #     list_2.append(self.__poi)
        #
        # while len(list_2) > 0:
        #     temp = set()
        #     for i in list_1:
        #         _, paths = dijkstra(self.__graph, i, list_2, consider_node_weights=False)
        #         paths_ = [paths[j] for j in list_2]
        #         for p in paths_:
        #             for n in p:
        #                 if n not in list_1 and n not in list_2 and self.__graph[n][0] in generator.suitable_weights:
        #                     temp.add(n)
        #     for i in range(len(list_2) - 1):
        #         _, paths = dijkstra(self.__graph, list_2[i], list_2[i + 1:], consider_node_weights=False)
        #         paths_ = [paths[j] for j in list_2[i + 1:]]
        #         for p in paths_:
        #             for n in p:
        #                 if n not in list_1 and n not in list_2 and self.__graph[n][0] in generator.suitable_weights:
        #                     temp.add(n)
        #     list_1.update(list_2)
        #     list_2 = list(temp)
        #
        # return list(list_1)

        list_1 = set()
        list_2 = list(self.__terminals)
        if self.__poi not in list_2:
            list_2.append(self.__poi)

        while len(list_2) > 0:
            temp = set()
            if self.__dist_paths is not None:
                for i in list_1:
                    paths_i_ = [self.__dist_paths[i][1][j] for j in list_2]
                    for p in paths_i_:
                        for n in p:
                            if n not in list_1 and n not in list_2 and self.__graph[
                                    n][0] in generator.suitable_weights:
                                temp.add(n)
                for i in range(len(list_2) - 1):
                    paths_i_ = [
                        self.__dist_paths[list_2[i]][1][j]
                        for j in list_2[i + 1:]
                    ]
                    for p in paths_i_:
                        for n in p:
                            if n not in list_1 and n not in list_2 and self.__graph[
                                    n][0] in generator.suitable_weights:
                                temp.add(n)
            else:
                for i in list_1:
                    _, paths_i = dijkstra(self, i, list_2)
                    paths_i_ = [paths_i[j] for j in list_2]
                    for p in paths_i_:
                        for n in p:
                            if n not in list_1 and n not in list_2 and self.__graph[
                                    n][0] in generator.suitable_weights:
                                temp.add(n)
                for i in range(len(list_2) - 1):
                    _, paths_i = dijkstra(self, list_2[i], list_2[i + 1:])
                    paths_i_ = [paths_i[j] for j in list_2[i + 1:]]
                    for p in paths_i_:
                        for n in p:
                            if n not in list_1 and n not in list_2 and self.__graph[
                                    n][0] in generator.suitable_weights:
                                temp.add(n)
            list_1.update(list_2)
            list_2 = list(temp)
        return list(list_1)
示例#24
0
文件: WNGraph.py 项目: The-Blitz/BSDT
def generateGraph():
    fileName = 'WordNetEdges/ili-wnet30g_rels.txt'
    file1 = readFile(fileName, 'utf-8')

    fileName = 'WordNetEdges/ili-wnet30_rels.txt'
    file2 = readFile(fileName, 'utf-8')

    gr = g.Graph()

    for i in file1:
        gr.addEdge(i[0], i[1], 1)
        gr.addEdge(i[1], i[0], 1)

    for i in file2:
        gr.addEdge(i[0], i[1], 1)
        gr.addEdge(i[1], i[0], 1)
    return gr


gr = generateGraph()

fileV = open('vertList.txt', 'r')

for v in fileV:
    v = v[:len(v) - 1]  # remove '\n'
    f = open("Distances/" + v + '.txt', 'w')
    delta, previous = g.dijkstra(gr, v)
    for key, value in delta.items():
        f.write("%s %s\n" % (key, value))
    f.close()
示例#25
0
 def __init__(self,
              graph,
              terminals,
              hot_spots=None,
              generator=None,
              distances=None):
     # Check whether graph is node-weighted.
     if not graph.is_node_weighted():
         raise (ValueError,
                "Lazy Steiner Tree only works with node-weighted graphs.")
     # Extract POI from the terminals list.
     if len(terminals) > 0:
         self.__poi = terminals[0]
     else:
         return
     # Set object variables.
     self.__graph = SuitabilityGraph()
     self.__graph.append_graph(graph)
     self.__terminals = terminals
     self.__hot_spots = None
     self.__nodes = None
     self.__s_d = {}
     self.__paths = {}
     self.__refs = {}
     # Set hot spots.
     if hot_spots is None:
         if generator is None:
             generator = SuitableNodeWeightGenerator()
         self.__hot_spots = self.__graph.get_suitable_nodes(
             generator, excluded_nodes=terminals)
     else:
         self.__hot_spots = list(hot_spots)
     # Set nodes = hot spots + terminals.
     self.__nodes = list(self.__hot_spots)
     for t in terminals:
         self.__nodes.append(t)
     # Set distances.
     if distances is None:
         len_hot_spots = len(self.__hot_spots)
         self.__distances = {}
         for t in self.__terminals:
             dist, paths = dijkstra(self.__graph, t, self.__nodes)
             for n in self.__nodes:
                 try:
                     self.__distances[tuple(sorted([t,
                                                    n]))] = (dist[n], 'N')
                     self.__paths[tuple(sorted([t, n]))] = paths[n]
                 except KeyError:
                     self.__distances[tuple(sorted([t, n]))] = (sys.maxint,
                                                                'N')
                     self.__paths[tuple(sorted([t, n]))] = []
         for h1 in self.__hot_spots:
             for i in range(self.__hot_spots.index(h1), len_hot_spots):
                 h2 = self.__hot_spots[i]
                 distance = 0
                 d_type = 'E'
                 if h1 == h2:
                     d_type = 'N'
                 else:
                     distance = haversine(self.__graph[h1][2]['lat'],
                                          self.__graph[h1][2]['lon'],
                                          self.__graph[h2][2]['lat'],
                                          self.__graph[h2][2]['lon'])
                 self.__distances[tuple(sorted([h1,
                                                h2]))] = (distance, d_type)
     else:
         self.__distances = dict(distances)
示例#26
0
    terminals = [742, 870, 776, 578]

    suitability_graph = SuitabilityGraph()
    suitability_graph.append_graph(node_weighted)

    suitability_graph.extend_suitable_regions(seed, generator)
    suitability_graph.extend_suitable_regions(seed, generator)
    suitability_graph.extend_suitable_regions(seed, generator)
    suitability_graph.extend_suitable_regions(seed, generator)

    regions = suitability_graph.get_suitable_regions(generator)

    suitable_nodes = suitability_graph.get_suitable_nodes(
        generator, excluded_nodes=terminals)

    dist, _ = dijkstra(suitability_graph, terminals[0], terminals[1:])
    upper_bound = sum([dist[t] for t in terminals[1:]])

    c = []
    for s in suitable_nodes:
        dist_s, _ = dijkstra(suitability_graph, s, terminals)
        total_s = sum([dist_s[t] for t in terminals])
        if total_s <= upper_bound:
            c.append(s)

    # d = []
    # for s in c:
    #     dist_s, _ = dijkstra(suitability_graph, s, c[c.index(s) + 1:], consider_node_weights=False)
    #     d.extend(dist_s[s1] for s1 in c[c.index(s) + 1:])
    #
    # print(sorted(d, reverse=True)[0:len(terminals) - 2])
示例#27
0
文件: main.py 项目: Gajan-L/CSCI6511
import random
from graph import create_graph, dijkstra, a_star
from count_time import timeit

if __name__ == '__main__':
    # read graph file and create the graph
    data_dir = "./input/"
    graph = create_graph(data_dir)

    # get the start and end points
    start, end = random.sample(graph.nodes, 2)

    path_1 = dijkstra(start, end, graph)
    print(f"Shortest path from {start} to {end}:", path_1)
    print(" ")
    path_2 = a_star(start, end, graph)
    print(f"Shortest path from {start} to {end}:", path_2)

示例#28
0
                        edge_weighted=False,
                        node_weighted=True,
                        node_weight_generator=generator,
                        node_weights=node_weights,
                        seed=seed)

    suitability_graph = SuitabilityGraph()
    suitability_graph.append_graph(graph)

    terminals = [82, 182]
    poi = 173

    terminals_poi = list(terminals)
    terminals_poi.append(poi)

    dist_paths_node_node = {n: dijkstra(suitability_graph, n) for n in suitable_nodes}
    for e in terminals_poi:
        dist_paths_node_node[e] = dijkstra(suitability_graph, e)

    # suitable_nodes = suitability_graph.get_suitable_nodes_within_convex_set(terminals_poi, generator)
    # dist_paths_node_node = {n: dijkstra(suitability_graph, n, consider_node_weights=False) for n in suitable_nodes}
    # for e in terminals_poi:
    #     dist_paths_node_node[e] = dijkstra(suitability_graph, e, consider_node_weights=False)

    # max_distances = [max(dist_paths_node_node[n][0].values()) for n in suitable_nodes
    #                  if len(dist_paths_node_node[n][0].values()) > 0]
    # if len(max_distances) > 0:
    #     max_dist = max(max_distances)
    # else:
    #     max_dist = 0
    max_dist = 2
示例#29
0
    def __init__(self,
                 graph,
                 terminals,
                 poi,
                 contract_graph=True,
                 contracted_graph=None,
                 within_convex_hull=False,
                 dist_paths_suitable_nodes=None):

        # Check whether graph is node-weighted.
        if not graph.is_node_weighted():
            raise (ValueError,
                   "Spiders algorithm only works with node-weighted graphs.")

        # Store class variables for future references.
        self.__original_graph = graph
        self.__terminals = terminals
        self.__poi = poi
        self.__contract_graph = contract_graph

        terminals_poi = list(terminals)
        terminals_poi.append(poi)

        generator = SuitableNodeWeightGenerator()

        # Contracted graph...
        if contract_graph:
            if contracted_graph is not None:
                self.__graph = contracted_graph.copy()
            else:
                self.__graph = SuitabilityGraph()
                self.__graph.append_graph(graph)
                self.__graph.contract_suitable_regions(
                    generator, excluded_nodes=terminals_poi)
        else:
            self.__graph = SuitabilityGraph()
            self.__graph.append_graph(graph)

        # Copy distances and paths dictionary since it will be changed.
        dist_paths = None
        if dist_paths_suitable_nodes is not None:
            dist_paths = dict(dist_paths_suitable_nodes)
            for e in terminals_poi:
                dist_paths[e] = dijkstra(self.__graph, e)

        # Get the suitable nodes.
        if within_convex_hull:
            self.__suitable_nodes = self.__graph.get_suitable_nodes_within_convex_set(
                terminals_poi, generator, dist_paths)
        else:
            self.__suitable_nodes = self.__graph.get_suitable_nodes(
                generator, excluded_nodes=terminals_poi)
        # POI will be included in this list.
        self.__suitable_nodes.append(poi)

        # Calculate distances and paths between nodes. IMPORTANT: Only suitable nodes are regarded as start nodes.
        self.__dist_paths_node_node = {}
        # self.__dist_paths_node_within_region_node = {}

        if dist_paths is not None:
            self.__dist_paths_node_node = {
                n: dist_paths[n]
                for n in self.__suitable_nodes
            }
            # for n in self.__suitable_nodes:
            #     self.__dist_paths_node_node[n] = dist_paths[n]
            #     if n in self.__graph.contracted_regions:
            #         region = self.__graph.contracted_regions[n][0]
            #         for w in region:
            #             self.__dist_paths_node_within_region_node[w] = \
            #                 dijkstra(self.__original_graph, w, consider_node_weights=False)
        else:
            self.__dist_paths_node_node = \
                {n: dijkstra(self.__graph, n) for n in self.__suitable_nodes}
            # for n in self.__suitable_nodes:
            #     self.__dist_paths_node_node[n] = dijkstra(self.__graph, n, consider_node_weights=False)
            #     if n in self.__graph.contracted_regions:
            #         region = self.__graph.contracted_regions[n][0]
            #         for w in region:
            #             self.__dist_paths_node_within_region_node[w] = \
            #                 dijkstra(self.__original_graph, w, consider_node_weights=False)
        for e in terminals_poi:
            if e not in self.__dist_paths_node_node:
                self.__dist_paths_node_node[e] = dijkstra(self.__graph, e)

        # For every terminal create a subtree which has such terminal as the only node. Each subtree is digraph.
        self.__subtrees = {}
        for s in terminals:
            subtree = SuitabilityGraph()
            subtree[s] = (self.__graph[s][0], {})
            self.__subtrees[s] = subtree

        # IMPORTANT: This method calculates the distances and paths from suitable nodes only.
        self.__calculate_distances_paths_to_subtrees()