Commit 559cddf5 authored by Runar Borge's avatar Runar Borge
Browse files

Merge branch 'python3' into 'master'

Python3

See merge request !14
parents b32bdde8 9305c0de
This diff is collapsed.
#!/usr/bin/env python
#!/usr/bin/env python3
"""
PyMetric is a network simulation and visualisation tool. It
allows the user to trace paths through his network, given a
......@@ -31,7 +31,7 @@ if __name__ == '__main__':
import sys
if not len(sys.argv) > 1:
print "Please specify topology-file"
print("Please specify topology-file")
sys.exit(1)
infile = sys.argv[1]
......@@ -48,7 +48,7 @@ if __name__ == '__main__':
outpng = None
if sys.argv[2] == "-s":
if not len(sys.argv) == 4:
print "-s requires a script-file"
print("-s requires a script-file")
sys.exit(1)
else:
scriptFile = sys.argv[3]
......
This diff is collapsed.
......@@ -37,7 +37,7 @@ def parse_pajek(lines):
directed=True # assume this is a directed network for now
while lines:
try:
l=lines.next()
l=next(lines)
l=l.lower()
except: #EOF
break
......@@ -51,11 +51,11 @@ def parse_pajek(lines):
l,nnodes=l.split()
while not l.startswith("*arcs"):
if l.startswith('#'):
l = lines.next()
l = next(lines)
l = l.lower()
continue
if l.startswith('*'):
l = lines.next()
l = next(lines)
l = l.lower()
continue
splitline=shlex.split(l)
......@@ -67,10 +67,10 @@ def parse_pajek(lines):
if len(splitline) > 2:
id,label,x,y=splitline[0:4]
G.node_attr[label]={'id':id,'x':x,'y':y}
extra_attr=zip(splitline[4::2],splitline[5::2])
extra_attr=list(zip(splitline[4::2],splitline[5::2]))
#print extra_attr
G.node_attr[label].update(extra_attr)
l = lines.next()
l = next(lines)
l = l.lower()
if l.startswith("*arcs"):
for l in lines:
......@@ -81,7 +81,7 @@ def parse_pajek(lines):
u=nodelabels.get(ui,ui)
v=nodelabels.get(vi,vi)
edge_data={'value':float(w)}
extra_attr=zip(splitline[3::2],splitline[4::2])
extra_attr=list(zip(splitline[3::2],splitline[4::2]))
edge_data.update(extra_attr)
if G.has_edge(u,v):
if G[u][v]['value'] > float(w):
......
......@@ -34,7 +34,7 @@ class PlotUI:
'normalstop' : '#dd7777',
'normalpath' : '#77aaff',
'normalopath' : '#cccc99',
'normalupath' : '#4477cc'}
'normalupath' : '#4477cc'}
edgewidths = {'main' : 4,
'mainpath' : 5,
......@@ -42,7 +42,7 @@ class PlotUI:
'mainopath' : 4,
'mainupath' : 5,
'mainoaltpath' : 4,
'mainualtpath' : 5,
'mainualtpath' : 5,
'normal' : 1,
'normalpath' : 2.5,
'normalaltpath' : 2.5,
......@@ -58,22 +58,22 @@ class PlotUI:
100000 : 1.5,
34010 : 1.0,
34000 : 1.9,
1984 : 0.75}
1984 : 0.75}
edgecolors = {'main' : '#bbbbbb',
'mainpath' : '#77aaff',
'mainaltpath' : '#77aaff',
'mainaltpath' : '#77aaff',
'mainopath' : '#aaaa77',
'mainupath' : '#4477cc',
'mainoaltpath' : '#aaaa77',
'mainualtpath' : '#2255aa',
'mainualtpath' : '#2255aa',
'normal' : '#dddddd',
'normalpath' : '#77aaff',
'normalaltpath' : '#77aaff',
'normalaltpath' : '#77aaff',
'normalopath' : '#aaaa77',
'normalupath' : '#4477cc',
'normaloaltpath' : '#bbbb88',
'normalualtpath' : '#2255aa'}
'normalualtpath' : '#2255aa'}
edgestyles = {'main' : 'solid',
'mainpath' : 'solid',
......@@ -81,14 +81,14 @@ class PlotUI:
'mainopath' : 'solid',
'mainupath' : 'solid',
'mainoaltpath' : 'dotted',
'mainualtpath' : 'dotted',
'mainualtpath' : 'dotted',
'normal' : 'solid',
'normalpath' : 'solid',
'normalaltpath' : 'dotted',
'normalopath' : 'solid',
'normalupath' : 'solid',
'normaloaltpath' : 'dotted',
'normalualtpath' : 'dotted'}
'normalualtpath' : 'dotted'}
areacolors = [(0.65,0.5,0,1), (0.5,0.75,0.35,1), (0.28,0.8,0.68,1),
......@@ -98,7 +98,7 @@ class PlotUI:
(0.3,0.4,0.8,1), (0.1,0.9,0.85,1), (0.35,0.83,0.68,1),
(0.3,0.83,0.69,1), (0.95,0.95,0.8,1), (0.14,0.78,0.87,1),
(0.74,0.23,0.95,1)]
def __init__(self, command):
self.has_plotted = False
......@@ -116,7 +116,7 @@ class PlotUI:
if not self.command: return
if not event.artist in self.plottednodes: return
nodes = self.plottednodes[event.artist]
for i in event.ind:
......@@ -154,7 +154,7 @@ class PlotUI:
if edge_cmap:
nodecolors = '#444488'
nodealpha = 0.9
if areagroups:
areas = [data['areagroups'][nodes[i]] for i in range(len(nodes))]
......@@ -166,7 +166,7 @@ class PlotUI:
ci += 1
else:
PlotUI.nodecolors[a] = random.choice(PlotUI.areacolors)
nodecolors = [PlotUI.nodecolors[data['areagroups'][nodes[i]]]
for i in range(len(nodes))]
......@@ -211,12 +211,12 @@ class PlotUI:
for (edges, type) in data['edgegroups']:
edgecolors = PlotUI.edgecolors[type]
#print "colors:", edgecolors
if nx.__version__ > "0.36":
edgecolors = [PlotUI.edgecolors[type]] * len(edges)
ealpha = self._get_alpha(type, opacity)
if anycast:
ealpha = 0.5
......@@ -248,7 +248,7 @@ class PlotUI:
edgewidths = [PlotUI.edgewidths[edge_capa[(edges[i][0], edges[i][1])]]
for i in range(len(edges))]
except KeyError:
print "Error: Unknown or missing capacity information provided to plot command"
print("Error: Unknown or missing capacity information provided to plot command")
return
self.edgec = nx.draw_networkx_edges(graph, pos=data['pos'],
......@@ -270,7 +270,7 @@ class PlotUI:
style=PlotUI.edgestyles[type],
alpha=ealpha,
arrows=False,
hold=True)
hold=True)
if 'labels' in data:
color = 'k'
......@@ -278,26 +278,26 @@ class PlotUI:
if edge_cmap:
color = '#bbbbbb'
fsize = 8.5
self.nlabelc = nx.draw_networkx_labels(graph, pos=data['pos'],
labels=data['labels'],
font_size=fsize,
font_color=color,
alpha=1,
hold=True)
if 'edgelabels' in data and not edge_cmap:
self.elabelc = self._plot_edge_labels(graph,
data['edgelabels'],
pos=data['pos'])
plt.axis("off")
plt.axis("off")
plt.subplots_adjust(0,0,1,1)
ax.set_xbound(-10, 210)
ax.set_ybound(0, 200)
plt.xlim(-10, 210)
plt.ylim(0,200)
f = plt.gcf()
if not edge_cmap:
f.set_facecolor('w')
......@@ -306,20 +306,20 @@ class PlotUI:
fraction=0.10, pad=0)
for t in cb.ax.get_yticklabels():
t.set_color('#bbbbbb')
cb.set_label("Link utilization", color='#bbbbbb')
fm = plt.get_current_fig_manager()
cb.set_label("Link utilization", color='#bbbbbb')
fm = plt.get_current_fig_manager()
if (not self.has_plotted) and interactive:
f.set_figheight(13)
f.set_figheight(13)
f.set_size_inches(8,13)
if matplotlib.get_backend() == 'TkAgg':
maxh = fm.window.winfo_screenheight() - 60
fm.window.minsize(600,maxh)
fm.window.minsize(600,maxh)
if interactive:
fm.set_window_title("PyMetric - " + data['title'])
f.canvas.mpl_connect('pick_event', self.picktest)
plt.draw()
plt.draw()
self.has_plotted = True
def _get_alpha(self, type, opacity):
......@@ -329,7 +329,7 @@ class PlotUI:
return opacity
else:
return 1
def _plot_edge_labels(self, G, edgelabels, pos):
from math import sqrt
......@@ -338,10 +338,10 @@ class PlotUI:
(x1, y1) = pos[u]
(x2, y2) = pos[v]
x_diff = (x2 - x1)
y_diff = (y2 - y1)
d = sqrt( x_diff**2 + y_diff**2 )
x = (x1+x2) / 2
......@@ -364,7 +364,7 @@ class PlotUI:
wx = -10
else:
wx = 10
if x_diff == 0:
y = y1 + wy
elif y_diff == 0:
......@@ -373,14 +373,14 @@ class PlotUI:
x = x1 + wx
y = y1 + wy
lpos.append((x,y))
ax = plt.gca()
text_items = {}
for (i, label, bold) in edgelabels:
label = str(label)
(x,y) = lpos[i]
......
......@@ -34,7 +34,7 @@ PYTHONPATH=$PYTHONPATH:$PYMETRIC_HOME
if [ ! -z "$1" ]
then
python $PYMETRIC_HOME/metrics.py "$@"
python3 $PYMETRIC_HOME/metrics.py "$@"
else
python $PYMETRIC_HOME/metrics.py "$DEFAULTMODEL"
fi;
\ No newline at end of file
python3 $PYMETRIC_HOME/metrics.py "$DEFAULTMODEL"
fi;
from __future__ import print_function
import os.path
import sys
......@@ -24,12 +25,12 @@ class ScriptEngine():
def run(self, script):
if not os.path.isfile(script):
print >> sys.stderr, "No such file: %s" % script
print("No such file: %s" % script, file=sys.stderr)
return 1
try:
fh = open(script, "r")
except:
print >> sys.stderr, "Something went wrong when trying to open scriptfile"
print("Something went wrong when trying to open scriptfile", file=sys.stderr)
return 1
self.state = self.STATE_OPEN
self.current_script = script
......@@ -49,7 +50,7 @@ class ScriptEngine():
elif line.startswith('end'): self._do_end()
else:
self.state = self.STATE_ERROR
print >> sys.stderr, "Syntax error at line %d: Unknown keyword" % self.current_line
print("Syntax error at line %d: Unknown keyword" % self.current_line, file=sys.stderr)
if self.state == self.STATE_END:
self.current_script = None
......@@ -66,7 +67,7 @@ class ScriptEngine():
def _do_begin(self):
if self.state > self.STATE_OPEN:
print >> sys.stderr, "Syntax error at line %d: 'begin' allready specified" % self.current_line
print("Syntax error at line %d: 'begin' allready specified" % self.current_line, file=sys.stderr)
self.state = self.STATE_ERROR
return
self.cli.onecmd("sim")
......@@ -75,7 +76,7 @@ class ScriptEngine():
def _do_reset(self):
if self.state <= self.STATE_BEGIN:
print >> sys.stderr, "Warning: 'reset' without changes ignored (line %d)" % self.current_line
print("Warning: 'reset' without changes ignored (line %d)" % self.current_line, file=sys.stderr)
return
self.cli.onecmd("stop")
assert not self.simulation.is_active()
......@@ -87,11 +88,11 @@ class ScriptEngine():
def _do_linkfail(self, line):
args = self._get_args(line)
if not len(args) == 2:
print >> sys.stderr, "Syntax error at line %d: Wrong number of arguments for 'linkfail'" % self.current_line
print("Syntax error at line %d: Wrong number of arguments for 'linkfail'" % self.current_line, file=sys.stderr)
self.state = self.STATE_ERROR
return
if not self.state > self.STATE_OPEN:
print >> sys.stderr, "Syntax error at line %d: Missing 'begin' statement before 'linkfail'" % self.current_line
print("Syntax error at line %d: Missing 'begin' statement before 'linkfail'" % self.current_line, file=sys.stderr)
self.state = self.STATE_ERROR
return
self.cli.onecmd("linkfail %s %s" % (args[0], args[1]))
......@@ -101,11 +102,11 @@ class ScriptEngine():
def _do_assert(self, line):
args = self._get_args(line)
if not len(args) >= 5:
print >> sys.stderr, "Syntax error at line %d: Wrong number of arguments for 'assert'" % self.current_line
print("Syntax error at line %d: Wrong number of arguments for 'assert'" % self.current_line, file=sys.stderr)
self.state = self.STATE_ERROR
return
if not self.state > self.STATE_OPEN:
print >> sys.stderr, "Syntax error at line %d: Missing 'begin' statement before 'assert'" % self.current_line
print("Syntax error at line %d: Missing 'begin' statement before 'assert'" % self.current_line, file=sys.stderr)
self.state = self.STATE_ERROR
return
#if not self.state == self.STATE_SIM:
......@@ -115,48 +116,48 @@ class ScriptEngine():
self.loaddata = self._read_savedata()
link_key = "%s###%s" % (args[1], args[2])
if not self.loaddata or link_key not in self.loaddata:
print >> sys.stderr, "Warning: assertion not computed, no save data to compare with (line %d)" % self.current_line
print("Warning: assertion not computed, no save data to compare with (line %d)" % self.current_line, file=sys.stderr)
return
else:
simpaths = self.simulation.path(args[1], args[2])[1]
if not self.loaddata[link_key] == simpaths:
print >> sys.stderr, " FAIL: Assertion failed for %s -> %s (line %d)" % (self.current_line, args[1], args[2])
print >> sys.stderr, " Got: %s" % ("\n ".join(map(str, simpaths)))
print >> sys.stderr, " Expected: %s" % ("\n ".join(map(str, self.loaddata[link_key])))
print(" FAIL: Assertion failed for %s -> %s (line %d)" % (self.current_line, args[1], args[2]), file=sys.stderr)
print(" Got: %s" % ("\n ".join(map(str, simpaths))), file=sys.stderr)
print(" Expected: %s" % ("\n ".join(map(str, self.loaddata[link_key]))), file=sys.stderr)
self.state = self.STATE_FAIL
return
elif args[3] == 'eq':
expected = eval(" ".join(args[4:]))
simpaths = self.simulation.path(args[1], args[2])[1]
if not expected == simpaths:
print >> sys.stderr, " FAIL: Assertion failed (line %d)" % self.current_line
print >> sys.stderr, " Got: %s" % ("\n ".join(map(str, simpaths)))
print >> sys.stderr, " Expected: %s" % ("\n ".join(map(str, expected)))
print(" FAIL: Assertion failed (line %d)" % self.current_line, file=sys.stderr)
print(" Got: %s" % ("\n ".join(map(str, simpaths))), file=sys.stderr)
print(" Expected: %s" % ("\n ".join(map(str, expected))), file=sys.stderr)
self.state = self.STATE_FAIL
return
else:
print >> sys.stderr, "Error: Not implemented.... (line %d)" % (self.current_line)
print("Error: Not implemented.... (line %d)" % (self.current_line), file=sys.stderr)
return
def _do_save(self, line):
args = self._get_args(line)
if not len(args) == 3:
print >> sys.stderr, "Syntax error at line %d: Wrong number of arguments for 'save'" % self.current_line
print("Syntax error at line %d: Wrong number of arguments for 'save'" % self.current_line, file=sys.stderr)
self.state = self.STATE_ERROR
return
if not self.state == self.STATE_SIM:
print >> sys.stderr, "Warning: Not saving (line %d)" % self.current_line
print("Warning: Not saving (line %d)" % self.current_line, file=sys.stderr)
return
simpaths = self.simulation.path(args[1], args[2])[1]
if not simpaths:
print >> sys.stderr, "Warning: Ignoring 'save' for non-existant path at line %d" % self.current_line
print("Warning: Ignoring 'save' for non-existant path at line %d" % self.current_line, file=sys.stderr)
return
link_key = "%s###%s" % (args[1], args[2])
self.savedata[link_key] = simpaths
def _do_end(self):
if not self.state >= self.STATE_BEGIN:
print >> sys.stderr, "Syntax error at line %d: Missing 'begin' before 'end'" % self.current_line
print("Syntax error at line %d: Missing 'begin' before 'end'" % self.current_line, file=sys.stderr)
self.state = self.STATE_ERROR
return
if self.savedata:
......@@ -170,7 +171,7 @@ class ScriptEngine():
try:
fh = open(self.current_script + ".save", "r")
except IOError:
print >> sys.stderr, "Warning: Could not open savefile"
print("Warning: Could not open savefile", file=sys.stderr)
return {}
retdata = {}
for line in fh.readlines():
......@@ -183,7 +184,7 @@ class ScriptEngine():
try:
fh = open(self.current_script + ".save", "w")
except IOError:
print >> sys.stderr, "Warning: Could not open savefile for writing"
print("Warning: Could not open savefile for writing", file=sys.stderr)
return
for key in self.savedata:
fh.write("%s %s\n" % (key, self.savedata[key].__repr__()))
......
......@@ -24,7 +24,7 @@ __ALL__ = [ 'colored', 'colored2', 'colored3' ]
ATTRIBUTES = dict(
zip([
list(zip([
'normal',
'bold',
'dark',
......@@ -35,14 +35,14 @@ ATTRIBUTES = dict(
'reverse',
'concealed'
],
range(0, 9)
)
list(range(0, 9))
))
)
del ATTRIBUTES['']
HIGHLIGHTS = dict(
zip([
list(zip([
'on_grey',
'on_red',
'on_green',
......@@ -52,13 +52,13 @@ HIGHLIGHTS = dict(
'on_cyan',
'on_white'
],
range(40, 48)
)
list(range(40, 48))
))
)
COLORS = dict(
zip([
list(zip([
'grey',
'red',
'green',
......@@ -68,8 +68,8 @@ COLORS = dict(
'cyan',
'white',
],
range(30, 38)
)
list(range(30, 38))
))
)
SAVE = '\033[s'
......@@ -174,44 +174,44 @@ def colored3(text, color=None, on_color=None, attrs=None):
if __name__ == '__main__':
print 'Current terminal type: ', os.getenv('TERM')
print 'Test basic colors:'
print colored('Grey color', 'grey')
print colored('Red color', 'red')
print colored('Green color', 'green')
print colored('Yellow color', 'yellow')
print colored('Blue color', 'blue')
print colored('Magenta color', 'magenta')
print colored('Cyan color', 'cyan')
print colored('White color', 'white')
print '-' * 78
print 'Test highlights:'
print colored('On grey color', on_color='on_grey')
print colored('On red color', on_color='on_red')
print colored('On green color', on_color='on_green')
print colored('On yellow color', on_color='on_yellow')
print colored('On blue color', on_color='on_blue')
print colored('On magenta color', on_color='on_magenta')
print colored('On cyan color', on_color='on_cyan')
print colored('On white color', color='grey', on_color='on_white')
print '-' * 78
print 'Test attributes:'
print colored('Bold grey color', 'grey', attrs=['bold'])
print colored('Dark red color', 'red', attrs=['dark'])
print colored('Underline green color', 'green', attrs=['underline'])
print colored('Blink yellow color', 'yellow', attrs=['blink'])
print colored('Reversed blue color', 'blue', attrs=['reverse'])
print colored('Concealed Magenta color', 'magenta', attrs=['concealed'])
print colored('Bold underline reverse cyan color', 'cyan',
attrs=['bold', 'underline', 'reverse'])
print colored('Dark blink concealed white color', 'white',
attrs=['dark', 'blink', 'concealed'])
print '-' * 78
print 'Test mixing:'
print colored('Underline red on grey color', 'red', 'on_grey',
['underline'])
print colored('Reversed green on red color', 'green', 'on_red', ['reverse'])
print('Current terminal type: ', os.getenv('TERM'))
print('Test basic colors:')
print(colored('Grey color', 'grey'))
print(colored('Red color', 'red'))
print(colored('Green color', 'green'))
print(colored('Yellow color', 'yellow'))
print(colored('Blue color', 'blue'))
print(colored('Magenta color', 'magenta'))
print(colored('Cyan color', 'cyan'))
print(colored('White color', 'white'))
print('-' * 78)
print('Test highlights:')
print(colored('On grey color', on_color='on_grey'))
print(colored('On red color', on_color='on_red'))
print(colored('On green color', on_color='on_green'))
print(colored('On yellow color', on_color='on_yellow'))
print(colored('On blue color', on_color='on_blue'))
print(colored('On magenta color', on_color='on_magenta'))
print(colored('On cyan color', on_color='on_cyan'))
print(colored('On white color', color='grey', on_color='on_white'))
print('-' * 78)
print('Test attributes:')
print(colored('Bold grey color', 'grey', attrs=['bold']))
print(colored('Dark red color', 'red', attrs=['dark']))
print(colored('Underline green color', 'green', attrs=['underline']))
print(colored('Blink yellow color', 'yellow', attrs=['blink']))
print(colored('Reversed blue color', 'blue', attrs=['reverse']))
print(colored('Concealed Magenta color', 'magenta', attrs=['concealed']))
print(colored('Bold underline reverse cyan color', 'cyan',
attrs=['bold', 'underline', 'reverse']))
print(colored('Dark blink concealed white color', 'white',
attrs=['dark', 'blink', 'concealed']))
print('-' * 78)
print('Test mixing:')
print(colored('Underline red on grey color', 'red', 'on_grey',
['underline']))
print(colored('Reversed green on red color', 'green', 'on_red', ['reverse']))
import networkx as nx
import httplib
import sys