Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import timeit
- import matplotlib.pyplot as plt
- import networkx as nx
- import sys
- import math
- n_color = [] # node colors
- def get_edge_weight(G, i, j):
- return G.get_edge_data(i,j, key=0).get('c');
- def get_edge_name(G, i, j):
- return G.get_edge_data(i,j, key=0).get('n');
- def init(n):
- # START
- dist = [];
- prev = [];
- proc = [];
- for i in range(0,n):
- dist.append(500000);
- prev.append(-1);
- proc.append([False]);
- return [dist, prev, proc];
- # STOP
- def get_min_distance_index(n, dist, proc):
- # START
- j = 500000;
- index = -1;
- for i in range(0,n):
- if proc[i] == [False]:
- if j > dist[i]:
- j = dist[i];
- index = i;
- return index;
- # STOP
- def update_distance(G, u, v, dist, prev):
- # START
- #x = [];
- #x.append(get_edge_weight(G,u,v));
- #print(str(x[0]));
- x = dist[u] + get_edge_weight(G,u,v);
- #print(str(x) + str(u) + str(v));
- #print("dist" + str(dist[v]))
- if x < dist[v]:
- #print("Distanz" + str(dist[u]));
- dist[v] = dist[u] + get_edge_weight(G,u,v);
- #print("Distanz" + str(dist[v]));
- prev[v] = u;
- return [dist, prev];
- # STOP
- def has_unprocessed_nodes(proc):
- # START
- for i in range(0,len(proc)):
- if proc[i]==[False]:
- return True;
- return False;
- # STOP
- def dijkstra(G, start):
- # START
- [dist, prev, proc] = init(nx.number_of_nodes(G));
- dist[start] = 0;
- #print(dist);
- while has_unprocessed_nodes(proc):
- #print(has_unprocessed_nodes(proc));
- u = get_min_distance_index(nx.number_of_nodes(G),dist,proc);
- #print(proc)
- proc[u] = [True];
- for v in range(0,nx.number_of_nodes(G)):
- if(proc[v] == [True]):
- L = G.adjacency_list()
- for i in range(0,len(L[u])):
- [dist,prev] = update_distance(G,u,L[u][i],dist,prev);
- return [prev, dist];
- # STOP
- def bellman_ford(G, start):
- # START
- [dist, prev, proc] = init(nx.number_of_nodes(G));
- dist[start] = 0;
- #print(dist);
- for i in range(0,nx.number_of_nodes(G)-1):
- for u in range(0,nx.number_of_nodes(G)):
- L = G.adjacency_list()
- for v in range(0,len(L[u])):
- [dist,prev] = update_distance(G,u,L[u][v],dist,prev);
- for u in range(0,nx.number_of_nodes(G)):
- L = G.adjacency_list()
- for v in range(0,len(L[u])):
- if (dist[u] + get_edge_weight(G,u,L[u][v])) < dist[L[u][v]]:
- #print("Es existiert ein Zyklus mit negativem Gewicht")
- sys.exit()
- return [prev, dist]
- # STOP
- def heuristic(pos, i, j):
- x1 = pos[i][0]
- y1 = pos[i][1]
- x2 = pos[j][0]
- y2 = pos[j][1]
- # START
- abstand = math.sqrt((x1-x2)**2 + (y1-y2)**2);
- return abstand
- # STOP
- def get_lowest_f(openList, fscore):
- # START
- min = 500000;
- for i in range(0,len(openList)):
- if min > fscore[i]:
- min = fscore[i]
- index = openList[i];
- return index;
- # STOP
- def astar(G, pos, start, goal):
- # START
- prev = []
- gscore = []
- fscore = []
- for i in range(0,nx.number_of_nodes(G)):
- prev.append(-1)
- gscore.append(500000)
- fscore.append(500000)
- gscore[start] = 0
- fscore[start] = gscore[start] + heuristic(pos,start,goal)
- openList = []
- closedList = []
- openList.append(start)
- while len(openList) > 0:
- current = get_lowest_f(openList,fscore)
- if current == goal:
- #for i in range(0,len(closedList)):
- # print(str(closedList[i]))
- # n_color[closedList[i]] = 'r'
- #for i in range(0,len(openList)):
- # n_color[openList[i]] = 'g'
- #print(closedList)
- #print(openList)
- #print(gscore)
- #print(fscore)
- return prev
- #print(str(current))
- openList.remove(current)
- closedList.append(current)
- L = G.adjacency_list()
- for i in range(0,len(L[current])):
- bool = True
- for j in range(0,len(closedList)):
- if closedList[j] == L[current][i]:
- bool = False
- if bool:
- t = gscore[current] + heuristic(pos,current,L[current][i])
- if t < gscore[L[current][i]]:
- bool2 = True
- for k in range(0,len(openList)):
- if openList[k] == L[current][i]:
- bool2 = False
- if bool2:
- openList.append(L[current][i])
- prev[L[current][i]] = current
- gscore[L[current][i]] = t
- fscore[L[current][i]] = gscore[L[current][i]] + heuristic(pos,L[current][i],goal)
- #print(closedList)
- #print(openList)
- #print(gscore)
- #print(fscore)
- return prev
- # STOP
- def get_path(G, prev, goal):
- # START
- P = [];
- P.append(goal);
- while prev[goal] != -1:
- P.append(prev[goal]);
- goal = prev[goal];
- P1 = [];
- for i in range(0,len(P)):
- P1.append(P[len(P)-1-i])
- return P1;
- # STOP
- def build_graph():
- G = nx.MultiGraph()
- for i in range(0, 11):
- G.add_node(i)
- pos = { 0 : [ 4, 3] }
- pos.update( { 1 : [10, 1] } )
- pos.update( { 2 : [ 7, 5] } )
- pos.update( { 3 : [14, 4] } )
- pos.update( { 4 : [12, 6] } )
- pos.update( { 5 : [ 3, 8] } )
- pos.update( { 6 : [ 8, 9] } )
- pos.update( { 7 : [16, 9] } )
- pos.update( { 8 : [ 1,14] } )
- pos.update( { 9 : [ 5,13] } )
- pos.update( { 10 : [13,13] } )
- # n := nodename, c := cost
- G.add_edge( 0, 1, n='a', c=7 )
- G.add_edge( 1, 3, n='b', c=5 )
- G.add_edge( 0, 2, n='c', c=1 )
- G.add_edge( 2, 3, n='d', c=8 )
- G.add_edge( 2, 4, n='e', c=5 )
- G.add_edge( 4, 3, n='f', c=4 )
- G.add_edge( 3, 7, n='g', c=5 )
- G.add_edge(10, 7, n='h', c=5 )
- G.add_edge( 6,10, n='i', c=6 )
- G.add_edge( 5, 0, n='j', c=5 )
- G.add_edge( 5, 4, n='k', c=9 )
- G.add_edge( 5, 6, n='l', c=5 )
- G.add_edge( 9, 6, n='m', c=5 )
- G.add_edge( 5, 9, n='n', c=6 )
- G.add_edge( 8, 5, n='o', c=6 )
- G.add_edge( 8, 9, n='p', c=4 )
- G.add_edge( 4,10, n='q', c=7 )
- return [G, pos]
- def build_squre_lattice_graph(N):
- G = nx.MultiGraph()
- pos = { 0 : [0,0] }
- for i in range(0,N):
- for j in range(0,N):
- k = i*N+j
- G.add_node(k)
- pos.update( { k : [i,j] })
- for i in range(0,N):
- for j in range(0,N):
- u = (i)*N+(j)
- v = (i+1)*N+(j)
- if i+1<N and j<N:
- label = str(u) + '0'
- G.add_edge( u, v, n=label, c=1 )
- u = (i)*N+(j)
- v = (i)*N+(j+1)
- if i<N and j+1<N:
- label = str(u) + '1'
- G.add_edge( u, v, n=label, c=1 )
- u = (i)*N+(j)
- v = (i+1)*N+(j+1)
- if i+1<N and j+1<N:
- label = str(u) + '2'
- G.add_edge( u, v, n=label, c=1 )
- u = (i+1)*N+(j)
- v = (i)*N+(j+1)
- if i+1<N and j+1<N:
- label = str(u) + '3'
- G.add_edge( u, v, n=label, c=1 )
- return [G, pos]
- if __name__ == '__main__':
- #[G, pos] = build_graph()
- [G, pos] = build_squre_lattice_graph(10)
- #n_color = ['w'] * nx.number_of_nodes(G) # white color
- start = 0 # index of start node
- goal = 99 # index of end node
- time1 = timeit.default_timer()
- [prev, dist] = dijkstra(G, start)
- time2 = timeit.default_timer()
- print(str(time2-time1))
- #print(prev)
- #print(dist)
- time1 = timeit.default_timer()
- [prev, dist] = bellman_ford(G, start)
- time2 = timeit.default_timer()
- print(str(time2-time1))
- #print(prev)
- #print(dist)
- time1 = timeit.default_timer()
- prev = astar(G, pos, start, goal)
- time2 = timeit.default_timer()
- print(str(time2-time1))
- #print(prev)
- P = get_path(G, prev, goal)
- #print('path := ')
- #print(P)
- #cost = dist[ goal ]
- #print('cost := ' + str(cost))
- plt.clf()
- plt.title('Praktikum Graphentheorie: KWP')
- plt.gca().invert_yaxis()
- nx.draw_networkx(G, pos)
- nx.draw_networkx_nodes(G, pos, node_color=n_color)
- nx.draw_networkx_edges(G, pos)
- #nx.draw_networkx_edge_labels(G, pos)
- plt.show();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement