Commit 8ca79599 authored by Morten Knutsen's avatar Morten Knutsen
Browse files

Conform to 1.00-API

  * Use direct dictonary lookups instead of get_edge where possible.
  * Rewrite all metrics to be edge dictionaries with key=weight.
  * Use nx.average_shortest_path_length instead of homebrew version.
parent 7ee0c461
......@@ -78,8 +78,8 @@ class MetricShell(Cmd):
effects.keys())
multimulti = filter(lambda x: len(effects[x].keys()) >= 20,
effects.keys())
difflen = utils.mean_shortest_path_length(self.simulation.graph)\
- utils.mean_shortest_path_length(self.model.G)
difflen = nx.average_shortest_path_length(self.simulation.graph)\
- nx.average_shortest_path_length(self.model.G)
components = nx.connected_component_subgraphs(
self.simulation.graph.to_undirected())
......@@ -293,7 +293,8 @@ class MetricShell(Cmd):
% (len(uneven)/2)
print
for (u,v,w) in uneven:
x = G.get_edge(v,u)
w = w['weight']
x = G[v][u]['weight']
if (v,u) in printed: continue
print "%-15s -> %s: %s" % (u,v,w)
print "%-15s -> %s: %s" % (v,u,x)
......@@ -773,9 +774,9 @@ class MetricShell(Cmd):
G = self.simulation.graph
shown = {}
for e in sorted(ret[1]):
u,v,w = e[0], e[1], ret[1][e]
u,v,w = e[0], e[1], ret[1][e]['weight']
if (u,v) in shown: continue
w_old = G.get_edge(u,v)
w_old = G[u][v]['weight']
if w_old != w:
linkstr = "%s <-> %s" % (u,v)
oldstr = "%s" % int(w_old)
......@@ -793,7 +794,7 @@ class MetricShell(Cmd):
for e in ret[1]:
u,v,w = e[0], e[1], ret[1][e]
if (u,v) in applied: continue
w_old = G.get_edge(u,v)
w_old = G[u][v]['weight']
if w_old != w:
self.simulation.change_metric(u,v,w, True)
applied[(u,v)] = True
......@@ -819,7 +820,7 @@ class MetricShell(Cmd):
header = False
for (u,v,w) in sorted(H.edges(data=True)):
if (u,v) in shown: continue
w_old = G.get_edge(u,v)
w_old = G[u][v]['weight']
if w_old != w:
if not header:
print "The following metric changes are suggested:"
......@@ -839,7 +840,7 @@ class MetricShell(Cmd):
if apply.lower() == 'y':
for (u,v,w) in H.edges(data=True):
if (u,v) in applied: continue
w_old = G.get_edge(u,v)
w_old = G[u][v]['weight']
if w_old != w:
self.simulation.change_metric(u,v,w, True)
applied[(u,v)] = True
......
......@@ -267,7 +267,7 @@ class Model:
if not G.has_edge(u,v): return {}
bc = self.edge_betweenness
retinfo = {}
edgedata = self.graph.get_edge(u,v)
edgedata = self.graph[u][v]
name = ""
capacity = 0
if 'c' in edgedata:
......@@ -411,7 +411,7 @@ class Model:
if not self.graph.has_edge(u,v):
return False
linkinfo = self.graph.get_edge(u,v)
linkinfo = self.graph[u][v]
if not 'c' in linkinfo:
if as_string:
......@@ -551,7 +551,7 @@ class Model:
stats["periphery"] = nx.periphery(self.graph)
stats["density"] = nx.density(self.graph)
stats["reciprocity"] = utils.reciprocity(self.graph)
stats["mean length"] = utils.mean_shortest_path_length(self.graph)
stats["mean length"] = nx.average_shortest_path_length(self.graph)
stats["longest paths"] = self.get_max_cost_paths()
stats["top 20 transit"] = top
......@@ -596,8 +596,8 @@ class Model:
def _make_weighted_copy(self):
G = self.graph.copy()
for (u,v,d) in G.edges(data=True):
G.delete_edge(u,v)
G.add_edge(u,v,d['value'])
G.remove_edge(u,v)
G.add_edge(u,v,weight=d['value'])
return G
def _refresh_betweenness(self):
......@@ -692,7 +692,7 @@ class Simulation:
stats["periphery"] = nx.periphery(self.graph)
stats["density"] = nx.density(self.graph)
stats["reciprocity"] = utils.reciprocity(self.graph)
stats["mean length"] = utils.mean_shortest_path_length(self.graph)
stats["mean length"] = nx.average_shortest_path_length(self.graph)
stats["longest paths"] = self.get_max_cost_paths()
stats["top 20 transit"] = top[0:20]
......@@ -724,7 +724,7 @@ class Simulation:
retinfo = {}
retinfo['name'] = node
retinfo['degree'] = G.out_degree(node)
retinfo['links'] = map(lambda x: self.model.graph.get_edge(x[0], x[1])['l']\
retinfo['links'] = map(lambda x: self.model.graph.get_edge_data(x[0], x[1])['l']\
+ " (" + str(int(x[2])) + ")",
G.edges(node, data=True))
retinfo['neighbors'] = G.neighbors(node)
......@@ -746,7 +746,7 @@ class Simulation:
if not G.has_edge(u,v): return {}
bc = self.edge_betweenness
retinfo = {}
edgedata = self.model.graph.get_edge(u,v)
edgedata = self.model.graph[u][v]
name = ""
capacity = 0
if 'c' in edgedata:
......@@ -1363,14 +1363,14 @@ class Simulation:
if not self.graph.has_edge(n1,n2):
return False
metrics = (self.graph.get_edge(n1, n2), self.graph.get_edge(n2,n1))
metrics = (self.graph[n1][n2]['weight'], self.graph[n2][n1]['weight'])
if record:
self.changes.append({'type': Simulation.SC_LINKFAIL, 'pair': (n1,n2),
'metrics': metrics})
self.graph.delete_edge(n1, n2)
self.graph.delete_edge(n2, n1)
self.graph.remove_edge(n1, n2)
self.graph.remove_edge(n2, n1)
self._refresh_betweenness()
self._refresh_anycast()
......@@ -1385,12 +1385,12 @@ class Simulation:
removed_edges = []
for node in self.graph.neighbors(n1):
removed_edges.append((n1, node, self.graph.get_edge(n1, node)))
self.graph.delete_edge(n1, node)
removed_edges.append((node, n1, self.graph.get_edge(node, n1)))
self.graph.delete_edge(node, n1)
removed_edges.append((n1, node, self.graph[n1][node]))
self.graph.remove_edge(n1, node)
removed_edges.append((node, n1, self.graph[node][n1]))
self.graph.remove_edge(node, n1)
self.graph.delete_node(n1)
self.graph.remove_node(n1)
if record:
self.changes.append({'type': Simulation.SC_ROUTERFAIL, 'node': n1,
......@@ -1410,9 +1410,9 @@ class Simulation:
if not self.graph.has_edge(n1, n2):
return False
old_metric = self.graph.get_edge(n1, n2)
old_metric = self.graph[n1][n2]['weight']
if old_metric == self.graph.get_edge(n2,n1):
if old_metric == self.graph[n2][n1]['weight']:
bidirectional = True
if bidir == False:
......@@ -1420,12 +1420,12 @@ class Simulation:
if not record:
bidirectional = False
self.graph.delete_edge(n1, n2)
self.graph.add_edge(n1,n2, metric)
self.graph.remove_edge(n1, n2)
self.graph.add_edge(n1,n2, weight=metric)
if bidirectional or bidir:
self.graph.delete_edge(n2, n1)
self.graph.add_edge(n2,n1, metric)
self.graph.remove_edge(n2, n1)
self.graph.add_edge(n2,n1, weight=metric)
if record:
self.changes.append({'type': Simulation.SC_METRIC, 'pair': (n1, n2),
......@@ -1484,8 +1484,8 @@ class Simulation:
(u, v) = change['pair']
(m1, m2) = change['metrics']
self.graph.add_edge(u, v, m1)
self.graph.add_edge(v, u, m2)
self.graph.add_edge(u, v, weight=m1)
self.graph.add_edge(v, u, weight=m2)
elif change['type'] == Simulation.SC_ROUTERFAIL:
router = change['node']
......@@ -1493,7 +1493,7 @@ class Simulation:
self.graph.add_node(router)
for (u, v, w) in edges:
self.graph.add_edge(u, v, w)
self.graph.add_edge(u, v, weight=w)
del self.changes[idx]
......@@ -1540,7 +1540,7 @@ class Simulation:
return (success, results)
if node == via:
continue
H.delete_node(node)
H.remove_node(node)
J = H.copy()
cost2, paths2 = self.path(via, stop, H)
......@@ -1593,7 +1593,7 @@ class Simulation:
if debug: print "Negative adjustment loop"
for path1 in paths1:
for (u,v) in zip(path1, path1[1:]):
w = I.get_edge(u,v)
w = I[u][v]['weight']
if debug: print "Considering (%s,%s,%s) (-1)" % (u,v,w)
if u == start or u == stop or v == start or v == stop:
......@@ -1609,8 +1609,8 @@ class Simulation:
minmax = True
break
I.add_edge(u,v,w)
K.add_edge(u,v,w)
I.add_edge(u,v,weight=w)
K.add_edge(u,v,weight=w)
effects = self._refresh_effects(G, I)
......@@ -1645,8 +1645,8 @@ class Simulation:
if debug: print "Reached minimum metric..."
continue
I.add_edge(u,v,w)
K.add_edge(u,v,w)
I.add_edge(u,v,weight=w)
K.add_edge(u,v,weight=w)
effects = self._refresh_effects(G, I)
......@@ -1660,8 +1660,8 @@ class Simulation:
bad_effect = True
if bad_effect == True:
I.add_edge(u,v,w+1)
K.add_edge(u,v,w+1)
I.add_edge(u,v,weight=w+1)
K.add_edge(u,v,weight=w+1)
continue
elif bad_effect == 2:
continue
......@@ -1684,7 +1684,7 @@ class Simulation:
for opath in opaths:
for (u,v) in zip(opath, opath[1:]):
if u in V and v in V: continue
w = I.get_edge(u,v)
w = I[u][v]['weight']
if debug: print "Considering (%s,%s,%s) (+1)" % (u,v,w)
......@@ -1701,8 +1701,8 @@ class Simulation:
minmax = True
continue
I.add_edge(u,v,w)
K.add_edge(u,v,w)
I.add_edge(u,v,weight=w)
K.add_edge(u,v,weight=w)
effects = self._refresh_effects(G, I)
......@@ -1735,8 +1735,8 @@ class Simulation:
if w > max_metric:
if debug: print "Reached maximum metric..."
continue
I.add_edge(u,v,w)
K.add_edge(u,v,w)
I.add_edge(u,v,weight=w)
K.add_edge(u,v,weight=w)
effects = self._refresh_effects(G, I)
......@@ -1750,8 +1750,8 @@ class Simulation:
bad_effect = True
if bad_effect == True:
I.add_edge(u,v,w-1)
K.add_edge(u,v,w-1)
I.add_edge(u,v,weight=w-1)
K.add_edge(u,v,weight=w-1)
continue
elif bad_effect == 2:
continue
......@@ -1773,15 +1773,15 @@ class Simulation:
if debug: print "2nd negative adjustment loop"
for path2 in paths2:
for (u,v) in zip(path2, path2[1:]):
w = J.get_edge(u,v)
w = J[u][v]['weight']
if debug: print "Considering (%s,%s,%s) (-1)" % (u,v,w)
w = w - 1
if w < 1:
if debug: print "Reached minimum metric..."
continue
J.add_edge(u,v,w)
K.add_edge(u,v,w)
J.add_edge(u,v,weight=w)
K.add_edge(u,v,weight=w)
effects = self._refresh_effects(H, J)
......@@ -1795,8 +1795,8 @@ class Simulation:
bad_effect = True
if bad_effect:
J.add_edge(u,v,w+1)
K.add_edge(u,v,w+1)
J.add_edge(u,v,weight=w+1)
K.add_edge(u,v,weight=w+1)
continue
else:
if debug: print "C: nochange = False"
......@@ -1821,7 +1821,7 @@ class Simulation:
for (u,v,w) in K.edges(data=True):
if (u,v) in results: continue
old_w = G.get_edge(u,v)
old_w = G[u][v]['weight']
if old_w != w:
results[(u,v)] = w
results[(v,u)] = w
......@@ -1856,10 +1856,10 @@ class Simulation:
adjustment_found = False
for (u,v,w) in edges:
if not w == H.get_edge(v,u):
if not w == H[v][u]['weight']:
continue
old_w = G.get_edge(u,v)
old_w = G[u][v]['weight']
if debug: print "Considering (%s,%s)" % (u,v)
count = 1
......@@ -1869,16 +1869,16 @@ class Simulation:
if w < 1: continue
if debug: print "Trying metrics..",
H.add_edge(u,v,w)
H.add_edge(v,u,w)
H.add_edge(u,v,weight=w)
H.add_edge(v,u,weight=w)
effects = self._refresh_effects(G, H)
if effects:
if abs(old_w - w) < 2:
H.add_edge(u,v,old_w)
H.add_edge(v,u,old_w)
H.add_edge(u,v,weight=old_w)
H.add_edge(v,u,weight=old_w)
else:
H.add_edge(u,v,w+1)
H.add_edge(v,u,w+1)
H.add_edge(u,v,weight=w+1)
H.add_edge(v,u,weight=w+1)
if debug: print "failed! (%s->%s)" % (old_w, w+1)
else:
count = 1
......
......@@ -71,9 +71,7 @@ def parse_pajek(lines):
G.node_attr[label].update(extra_attr)
l = lines.next()
l = l.lower()
if l.startswith("*edges") or l.startswith("*arcs"):
if l.startswith("*edge"):
G=networkx.XGraph(G) # switch from digraph to graph
if l.startswith("*arcs"):
for l in lines:
if not l: break
if l.startswith('#'): continue
......@@ -85,7 +83,7 @@ def parse_pajek(lines):
extra_attr=zip(splitline[3::2],splitline[4::2])
edge_data.update(extra_attr)
if G.has_edge(u,v):
if G.get_edge(u,v)['value'] > float(w):
if G[u][v]['value'] > float(w):
G.add_edge(u,v,edge_data)
else:
G.add_edge(u,v,edge_data)
......
......@@ -343,7 +343,7 @@ class PlotUI:
x = (x1+x2) / 2
y = (y1+y2) / 2
if d < 70 and G.get_edge(v,u) == w:
if d < 70 and G[v][u]['weight'] == w['weight']:
pass
else:
......
import networkx as nx
import httplib
def mean_shortest_path_length(G):
"""Calculate mean shortest path lenght of graph."""
apspl = nx.path.all_pairs_shortest_path_length(G)
sum_of_paths = sum([sum(apspl[n].values()) for n in apspl])
num_of_paths = sum(map(len, apspl.values()))
return float(sum_of_paths) / num_of_paths
def reciprocity(G):
"""Calculate reciprocity of graph, i.e. the ratio of the edges in
one direction that have and edge going in the other direction."""
......@@ -38,7 +31,7 @@ def edge_labels(edges, edgegroups=[], suppress_default=True):
for (s,t,x) in el:
if (u,v) == (s,t):
if not (u,v) in edgedone:
metric = int(x)
metric = int(x['weight'])
m = str(metric)
if metric == 10 and suppress_default:
m = ""
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment