diff --git a/tools/contributed/sumopy/agilepy/lib_base/arrayman.py b/tools/contributed/sumopy/agilepy/lib_base/arrayman.py
index 6f0c4c23a692..774aa8fe5817 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/arrayman.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/arrayman.py
@@ -16,7 +16,7 @@
# @author Joerg Schweizer
# @date 2012
-from classman import *
+from .classman import *
import numpy as np
@@ -494,7 +494,7 @@ def _write_xml_value(self, val, fd):
# don't even write empty lists
pass
- elif type(self._default) in (types.UnicodeType, types.StringType):
+ elif type(self._default) in (str, bytes):
if len(val) > 0:
fd.write(xm.num(self.xmltag, val))
@@ -529,7 +529,7 @@ def init_postload_internal(self, man, obj):
AttrConf.init_postload_internal(self, man, obj)
# print 'IdsConf.init_postload_internal',self.attrname,self.get_value().dtype,self.get_value().dtype == np.int64
if self.get_value().dtype == np.int64:
- print 'WARNING in init_postload_internal: convert ids array to 32 bit'
+ print('WARNING in init_postload_internal: convert ids array to 32 bit')
self.set_value(np.array(self.get_value(), dtype=np.int32))
# if self._is_child:
# print ' make sure children get initialized'
@@ -890,7 +890,7 @@ def get_ids(self, inds=None):
return
def __getitem__(self, args):
- if type(args) == types.TupleType:
+ if type(args) == tuple:
attrnames = args[0]
ids = args[1]
else:
@@ -908,7 +908,7 @@ def __getitem__(self, args):
# TODO: detect dtype by adding numbers or use fields!!!
dtype = np.float32
out = np.zeros((n_rows, n_cols), dtype=dtype)
- for i, attrname in zip(xrange(n_cols), attrnames):
+ for i, attrname in zip(range(n_cols), attrnames):
out[:, i] = getattr(self, attrname)[ids]
return out
else:
@@ -1052,7 +1052,7 @@ def add_rows(self, n=None, ids=[], **attrs):
ids = self.suggest_ids(n)
elif (len(ids) == 0) & (len(attrs) > 0):
# get number of rows from any value vector provided
- ids = self.suggest_ids(len(attrs.values()[0]))
+ ids = self.suggest_ids(len(list(attrs.values())[0]))
elif (n is None) & (len(ids) == 0) & (len(attrs) > 0):
# nothing given really-> do nothing
return np.zeros((0), np.int)
@@ -1226,7 +1226,7 @@ def init_postload_internal(self, parent):
# this should no longer happen in the future as ind and ids
# have been formatted propperly
if attrman._inds.dtype != np.int32:
- print 'WARNING: 64 bit ids and inds...will adjust to 32 bit'
+ print('WARNING: 64 bit ids and inds...will adjust to 32 bit')
attrman._inds = np.array(attrman._inds, dtype=np.int32)
attrman._ids = np.array(attrman._ids, dtype=np.int32)
diff --git a/tools/contributed/sumopy/agilepy/lib_base/classman.py b/tools/contributed/sumopy/agilepy/lib_base/classman.py
index 884733fbe350..541135f6cdd9 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/classman.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/classman.py
@@ -42,9 +42,9 @@
from collections import OrderedDict
from datetime import datetime
#import numpy as np
-import xmlman as xm
-from logger import Logger
-from misc import get_inversemap
+from . import xmlman as xm
+from .logger import Logger
+from .misc import get_inversemap
##########
@@ -71,8 +71,8 @@
STRUCTS_COL = ('odict', 'array')
STRUCTS_SCALAR = ('scalar', 'list', 'matrix', 'scalar.func')
-NUMERICTYPES = (types.BooleanType, types.FloatType, types.IntType, types.LongType, types.ComplexType)
-STRINGTYPES = (types.StringType, types.UnicodeType)
+NUMERICTYPES = (bool, float, int, int, complex)
+STRINGTYPES = (bytes, str)
NODATATYPES = (types.FunctionType, types.InstanceType, types.LambdaType)
@@ -86,7 +86,7 @@ def save_obj(obj, filename, is_not_save_parent=False):
try:
f = open(filename, 'wb')
except:
- print 'WARNING in save: could not open', filename
+ print('WARNING in save: could not open', filename)
return False
if is_not_save_parent:
@@ -110,7 +110,7 @@ def load_obj(filename, parent=None, is_throw_error=False):
Filename may also include absolute or relative path.
If operation fails a None object is returned.
"""
- print 'load_obj', filename
+ print('load_obj', filename)
if is_throw_error:
f = open(filename, 'rb')
@@ -118,7 +118,7 @@ def load_obj(filename, parent=None, is_throw_error=False):
try:
f = open(filename, 'rb')
except:
- print 'WARNING in load_obj: could not open', filename
+ print('WARNING in load_obj: could not open', filename)
return None
# try:
@@ -168,7 +168,7 @@ def add_event(self, trigger, function):
Standard plug types are automatically set but the system:
"""
- if not self._events.has_key(trigger):
+ if trigger not in self._events:
self._events[trigger] = []
self._events[trigger].append(function)
self._has_events = True
@@ -269,7 +269,7 @@ def __init__(self, attrname, default,
# set rest of attributes passed as keyword args
# no matter what they are used for
- for attr, value in attrs.iteritems():
+ for attr, value in attrs.items():
setattr(self, attr, value)
def is_save(self):
@@ -331,7 +331,7 @@ def get_value_from_xmlattr(self, xmlattrs):
then None is returned.
"""
if (self.xmltag is not None):
- if xmlattrs.has_key(self.xmltag):
+ if self.xmltag in xmlattrs:
return self.get_value_from_string(xmlattrs[self.xmltag])
else:
return None
@@ -362,7 +362,7 @@ def get_value_from_string(self, s, sep=','):
elif self.xmlmap is not None:
imap = get_inversemap(self.xmlmap)
# print 'get_value_from_string',s,imap
- if imap.has_key(s):
+ if s in imap:
return imap[s]
else:
return self.get_numvalue_from_string(s)
@@ -376,19 +376,19 @@ def get_numvalue_from_string(self, s, valtype=None):
else:
t = valtype
- if t in (types.UnicodeType, types.StringType):
+ if t in (str, bytes):
return s
- elif t in (types.UnicodeType, types.StringType):
+ elif t in (str, bytes):
return s
- elif t in (types.LongType, types.IntType):
+ elif t in (int, int):
return int(s)
- elif t in (types.FloatType, types.ComplexType):
+ elif t in (float, complex):
return float(s)
- elif t == types.BooleanType: # use default and hope it is no a numpy bool!!!
+ elif t == bool: # use default and hope it is no a numpy bool!!!
if s in ('1', 'True'):
return True
else:
@@ -421,27 +421,27 @@ def _write_xml_value(self, val, fd):
pass
elif self.xmlmap is not None:
- if self.xmlmap.has_key(val):
+ if val in self.xmlmap:
fd.write(xm.num(self.xmltag, self.xmlmap[val]))
else:
fd.write(xm.num(self.xmltag, val))
elif hasattr(self, 'choices'):
- if type(self.choices) == types.ListType:
+ if type(self.choices) == list:
fd.write(xm.num(self.xmltag, val))
else:
# print '_write_xml_value',self.attrname
# print ' val,self.choices.values()',val,self.choices.values()
- i = self.choices.values().index(val)
- fd.write(xm.num(self.xmltag, self.choices.keys()[i]))
+ i = list(self.choices.values()).index(val)
+ fd.write(xm.num(self.xmltag, list(self.choices.keys())[i]))
- elif type(self._default) == types.BooleanType: # use default and hope it is no a numpy bool!!!
+ elif type(self._default) == bool: # use default and hope it is no a numpy bool!!!
if val:
fd.write(xm.num(self.xmltag, 1))
else:
fd.write(xm.num(self.xmltag, 0))
- elif type(self._default) in (types.UnicodeType, types.StringType):
+ elif type(self._default) in (str, bytes):
if len(val) > 0:
fd.write(xm.num(self.xmltag, val))
@@ -680,9 +680,9 @@ def __getstate__(self):
# print ' self.__dict__=\n',self.__dict__.keys()
if self._is_saved:
# this message indicates a loop!!
- print 'WARNING in __getstate__: Attribute already saved:', self.get_obj().format_ident_abs(), self.attrname
+ print('WARNING in __getstate__: Attribute already saved:', self.get_obj().format_ident_abs(), self.attrname)
state = {}
- for attr in self.__dict__.keys():
+ for attr in list(self.__dict__.keys()):
if attr == 'plugin':
plugin = self.__dict__[attr]
@@ -708,7 +708,7 @@ def __setstate__(self, state):
# this is always required, but will not be saved
self.plugins = {}
- for attr in state.keys():
+ for attr in list(state.keys()):
# print ' state key',attr, state[attr]
# done in init_postload_internal...
# if attr=='plugin':
@@ -783,7 +783,7 @@ def __init__(self, attrname, default,
if len(default) > 0:
valtype = type(default[0])
else:
- valtype = types.UnicodeType
+ valtype = str
AttrConf.__init__(self, attrname, default,
struct='scalar',
@@ -874,7 +874,7 @@ def _getstate_specific(self, state):
# print ' found object',self.get_value().get_ident_abs()
state['_ident_value'] = self.get_value().get_ident_abs()
else:
- print 'WARNING in ObjConf._getstate_specific', self.attrname, 'lost linked object'
+ print('WARNING in ObjConf._getstate_specific', self.attrname, 'lost linked object')
state['_ident_value'] = []
# print ' ',
@@ -924,7 +924,7 @@ def init_postload_external(self):
# print ' linkobj',linkobj.ident
self.set_value(linkobj)
else:
- print 'WARNING in ObjConf._getstate_specific', self.attrname, 'lost linked object'
+ print('WARNING in ObjConf._getstate_specific', self.attrname, 'lost linked object')
self.set_value(BaseObjman('lost_object'))
# def get_valueobj(self):
@@ -1023,13 +1023,13 @@ def get_id_from_index(self, index):
def has_indices(self, indices):
ans = len(indices)*[False]
for i in range(len(indices)):
- if self._index_to_id.has_key(indices[i]):
+ if indices[i] in self._index_to_id:
ans[i] = True
return ans
def has_index(self, index):
- return self._index_to_id.has_key(index)
+ return index in self._index_to_id
def get_ids_from_indices(self, indices):
ids = len(indices)*[0]
@@ -1043,7 +1043,7 @@ def get_ids_from_indices(self, indices):
def get_ids_from_indices_save(self, indices):
ids = len(indices)*[0]
for i in range(len(indices)):
- if not self._index_to_id.has_key(indices[i]):
+ if indices[i] not in self._index_to_id:
ids[i] = -1
else:
ids[i] = self._index_to_id[indices[i]]
@@ -1059,7 +1059,7 @@ def add_index(self, _id, index):
self._index_to_id[index] = _id
def rebuild_indices(self):
- for idx in self._index_to_id.keys():
+ for idx in list(self._index_to_id.keys()):
del self._index_to_id[idx]
ids = self.get_obj().get_ids()
self.add_indices(ids, self[ids])
@@ -1083,14 +1083,14 @@ def set_indices(self, ids, indices):
def del_index(self, _id):
index = self[_id]
# when index is added (with set) no previous index value exists
- if self._index_to_id.has_key(index):
+ if index in self._index_to_id:
del self._index_to_id[index]
def get_ids_sorted(self):
# print 'get_ids_sorted',self.value
# print ' _index_to_id',self._index_to_id
# print ' sorted',sorted(self._index_to_id.iteritems())
- return OrderedDict(sorted(self._index_to_id.iteritems())).values()
+ return list(OrderedDict(sorted(self._index_to_id.items())).values())
# def indexset(self, indices, values):
# no! set made with respective attribute
@@ -1375,10 +1375,10 @@ def format_value(self, _id, show_unit=False, show_parentesis=False):
val = self[_id]
tt = type(val)
- if tt in (types.LongType, types.IntType):
+ if tt in (int, int):
return str(val)+unit
- elif tt in (types.FloatType, types.ComplexType):
+ elif tt in (float, complex):
if hasattr(attrconf, 'digits_fraction'):
digits_fraction = self.digits_fraction
else:
@@ -1492,7 +1492,7 @@ def _write_xml_value(self, val, fd):
# don't even write empty lists
pass
- elif type(self._default) in (types.UnicodeType, types.StringType):
+ elif type(self._default) in (str, bytes):
if len(val) > 0:
fd.write(xm.num(self.xmltag, val))
@@ -1984,7 +1984,7 @@ def insert_groupnames(self, attrconf):
if len(attrconf.groupnames) > 0:
for groupname in attrconf.groupnames:
- if not self._groups.has_key(groupname):
+ if groupname not in self._groups:
self._groups[groupname] = []
if attrconf not in self._groups[groupname]:
@@ -1992,7 +1992,7 @@ def insert_groupnames(self, attrconf):
def del_groupname(self, attrconf):
if len(attrconf.groupnames) > 0:
- for groupname in self._groups.keys():
+ for groupname in list(self._groups.keys()):
attrconfigs = self._groups[groupname]
if attrconf in attrconfigs:
if groupname not in attrconf.groupnames:
@@ -2002,10 +2002,10 @@ def get_groups(self):
return self._groups
def get_groupnames(self):
- return self._groups.keys()
+ return list(self._groups.keys())
def has_group(self, groupname):
- return self._groups.has_key(groupname)
+ return groupname in self._groups
def get_group(self, name):
"""
@@ -2021,7 +2021,7 @@ def get_group_attrs(self, name):
"""
# print 'get_group_attrs', self._groups
attrs = OrderedDict()
- if not self._groups.has_key(name):
+ if name not in self._groups:
return attrs
for attrconf in self._groups[name]:
# print ' attrconf.attrname',attrconf.attrname
@@ -2050,7 +2050,7 @@ def write_csv(self, fd, sep=',',
show_parentesis), sep, attrconf.format_value()))
def print_attrs(self, show_unit=True, show_parentesis=False, attrconfigs=None):
- print 'Attributes of', self._obj._name, 'ident_abs=', self._obj.get_ident_abs()
+ print('Attributes of', self._obj._name, 'ident_abs=', self._obj.get_ident_abs())
if attrconfigs is None:
attrconfigs = self.get_configs(structs=STRUCTS_SCALAR)
@@ -2099,7 +2099,7 @@ def __getstate__(self):
# print 'WARNING in Attrsman.__getstate__',self,'attrname missing','id',id(self),'id obj',id(self._obj)
if not hasattr(self, '_obj'):
- print 'WARNING: unknown obj in attrman', self, type(self)
+ print('WARNING: unknown obj in attrman', self, type(self))
# print ' dir',dir(self)
# if hasattr(self,'attrname'):
# print ' No attrman but attribute',self.attrname
@@ -2115,7 +2115,7 @@ def __getstate__(self):
# print ' self.__dict__=\n',self.__dict__.keys()
state = {}
- for attr in self.__dict__.keys():
+ for attr in list(self.__dict__.keys()):
# print ' attr',attr,self.__dict__[attr]
# TODO: optimize and put this at the end
if attr == 'plugin':
@@ -2149,7 +2149,7 @@ def __setstate__(self, state):
# this is always required, but will not be saved
# self.plugins={}
- for attr in state.keys():
+ for attr in list(state.keys()):
# print ' set state',attr
# plugin set in init_postload_internal
# if attr=='plugin':
@@ -2304,7 +2304,7 @@ def suggest_id(self, is_zeroid=False):
else:
id_max = max(id_set)
# print 'suggest_id',id0,
- return list(id_set.symmetric_difference(xrange(id0, id_max+id0+1)))[0]
+ return list(id_set.symmetric_difference(range(id0, id_max+id0+1)))[0]
def suggest_ids(self, n, is_zeroid=False):
"""
@@ -2324,14 +2324,14 @@ def suggest_ids(self, n, is_zeroid=False):
else:
id_max = max(id_set)
- return list(id_set.symmetric_difference(xrange(id0, id_max+id0+n)))[:n]
+ return list(id_set.symmetric_difference(range(id0, id_max+id0+n)))[:n]
def add_rows(self, n=None, ids=[], **attrs):
if n is not None:
ids = self.suggest_ids(n)
elif len(ids) == 0:
# get number of rows from any valye vector provided
- ids = self.suggest_ids(len(attrs.values()[0]))
+ ids = self.suggest_ids(len(list(attrs.values())[0]))
else:
# ids already given , no ids to create
pass
@@ -2412,7 +2412,7 @@ def print_attrs(self, ids=None, **kwargs):
for _id in ids:
for attrconf in self.get_configs(structs=STRUCTS_COL):
- print ' %s[%d] =\t %s' % (attrconf.attrname, _id, attrconf.format_value(_id, show_unit=True))
+ print(' %s[%d] =\t %s' % (attrconf.attrname, _id, attrconf.format_value(_id, show_unit=True)))
def write_csv(self, fd, sep=',', ids=None,
attrconfigs=None,
@@ -2681,7 +2681,7 @@ def export_csv(self, filepath, sep=',',
"""
Export scalars to file feed in csv format.
"""
- print 'BaseObjman.export_csv', filepath, "*"+sep+"*", 'attrconfigs', attrconfigs, self.get_attrsman()
+ print('BaseObjman.export_csv', filepath, "*"+sep+"*", 'attrconfigs', attrconfigs, self.get_attrsman())
fd = open(filepath, 'w')
# header
@@ -2786,7 +2786,7 @@ def get_childobj(self, attrname):
"""
Return child instance
"""
- if self.childs.has_key(attrname):
+ if attrname in self.childs:
config = self.childs[attrname]
return config.get_value()
else:
@@ -2867,7 +2867,7 @@ def __setstate__(self, state):
# this is always required, but will not be saved
# self.plugins={}
- for key in state.keys():
+ for key in list(state.keys()):
# print ' set state',key
self.__dict__[key] = state[key]
@@ -2887,7 +2887,7 @@ def init_postload_internal(self, parent):
Called after set state.
Link internal states and call constant settings.
"""
- print 'BaseObjman.init_postload_internal', self.ident, 'parent:'
+ print('BaseObjman.init_postload_internal', self.ident, 'parent:')
# if parent is not None:
# print parent.ident
# else:
@@ -2995,7 +2995,7 @@ def __getstate__(self):
self._is_saved = True
else:
- print 'WARNING in __getstate__: object %s already saved' % self.ident
+ print('WARNING in __getstate__: object %s already saved' % self.ident)
return state
def __setstate__(self, state):
@@ -3004,7 +3004,7 @@ def __setstate__(self, state):
# this is always required, but will not be saved
self.plugins = {}
- for attr in state.keys():
+ for attr in list(state.keys()):
# print ' set state',key
if attr == 'plugin':
if state[attr] == True:
@@ -3063,7 +3063,7 @@ def export_csv(self, filepath, sep=',',
"""
Export scalars to file feed in csv format.
"""
- print 'TableMixin.export_csv', filepath, "*"+sep+"*" # ,'attrconfigs',attrconfigs,self.get_attrsman()
+ print('TableMixin.export_csv', filepath, "*"+sep+"*") # ,'attrconfigs',attrconfigs,self.get_attrsman()
fd = open(filepath, 'w')
# header
diff --git a/tools/contributed/sumopy/agilepy/lib_base/exports.py b/tools/contributed/sumopy/agilepy/lib_base/exports.py
index 8e86f4fe15de..7847cc8e7d5c 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/exports.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/exports.py
@@ -36,7 +36,7 @@
except:
- print 'WARNING: No Exel export possible. Install openpyxl python package.'
+ print('WARNING: No Exel export possible. Install openpyxl python package.')
IS_EXCEL = False
# if 'Workbook' in dir():
@@ -45,14 +45,14 @@
# else:
# IS_EXCEL = False
-print 'IS_EXCEL', IS_EXCEL
+print('IS_EXCEL', IS_EXCEL)
def export_excel(filepath, obj, ids=None, attrconfigs=None, groupnames=None,
is_header=True, is_ident=False, is_timestamp=True,
show_parentesis=True, name_id='ID', is_export_not_save=True):
- print 'export_excel' # ,attrconfigs,'groupnames',groupnames,
+ print('export_excel') # ,attrconfigs,'groupnames',groupnames,
wb = Workbook()
if (wb.worksheets) >= 1:
@@ -78,7 +78,7 @@ def export_excel(filepath, obj, ids=None, attrconfigs=None, groupnames=None,
tv = type(value)
if tv in cm.NODATATYPES:
value = str(value)
- elif tv in (types.ListType, types.TupleType, np.ndarray):
+ elif tv in (list, tuple, np.ndarray):
value = str(value)
cell.value = value
@@ -129,7 +129,7 @@ def export_excel(filepath, obj, ids=None, attrconfigs=None, groupnames=None,
elif mt == 'id':
value = attrconf.get_linktab().format_ids([value])
- elif tv in (types.ListType, types.TupleType, np.ndarray):
+ elif tv in (list, tuple, np.ndarray):
value = str(value)
cell.value = value
ind_col += 1
@@ -141,7 +141,7 @@ class CsvExporter(Process):
def __init__(self, obj, ident='csvexporter', name='CSV exporter',
info='Export data from a CSV file into object',
logger=None, **kwargs):
- print 'CsvExporter.__init__'
+ print('CsvExporter.__init__')
self._init_common(ident,
parent=obj,
name=name,
@@ -187,7 +187,7 @@ def __init__(self, obj, ident='csvexporter', name='CSV exporter',
# ))
def do(self):
- print 'CsvExporter.do',
+ print('CsvExporter.do', end=' ')
obj = self.parent
attrsman = self.get_attrsman()
sep = self.sep
diff --git a/tools/contributed/sumopy/agilepy/lib_base/geometry.py b/tools/contributed/sumopy/agilepy/lib_base/geometry.py
index 93e8034d5500..2cba2293c473 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/geometry.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/geometry.py
@@ -118,7 +118,7 @@ def get_vec_on_polyline_from_pos(polyline, pos, length, angle=0.0):
pos_edge_pre = 0.0
x1, y1, z1 = polyline[0]
- for j in xrange(1, len(polyline)):
+ for j in range(1, len(polyline)):
x2, y2, z2 = polyline[j]
seglength = np.linalg.norm([x2-x1, y2-y1])
pos_edge += seglength
@@ -148,7 +148,7 @@ def get_coord_on_polyline_from_pos(polyline, pos):
pos_edge_pre = 0.0
x1, y1, z1 = polyline[0]
- for j in xrange(1, len(polyline)):
+ for j in range(1, len(polyline)):
x2, y2, z2 = polyline[j]
length = np.linalg.norm([x2-x1, y2-y1])
pos_edge += length
@@ -174,7 +174,7 @@ def get_coord_angle_on_polyline_from_pos(polyline, pos):
pos_edge_pre = 0.0
x1, y1, z1 = polyline[0]
- for j in xrange(1, len(polyline)):
+ for j in range(1, len(polyline)):
x2, y2, z2 = polyline[j]
length = np.linalg.norm([x2-x1, y2-y1])
pos_edge += length
@@ -206,7 +206,7 @@ def get_pos_on_polyline_from_coord(polyline, coord):
p_min = 0.0
pos = 0.0
x1, y1, z1 = polyline[0]
- for j in xrange(1, n_segs):
+ for j in range(1, n_segs):
x2, y2, z2 = polyline[j]
d, xp, yp = shortest_dist(x1, y1, x2, y2, xc, yc)
# print ' x1,y1=(%d,%d)'%(x1,y1),',x2,y2=(%d,%d)'%(x2,y2),',xc,yc=(%d,%d)'%(xc,yc)
@@ -629,7 +629,7 @@ def anglediffs(a1, a2, deg=False):
out : np.ndarray
The difference between a1 and a2
"""
- print 'anglediffs', a1, a2
+ print('anglediffs', a1, a2)
return wrapanglediffs(a1 - a2, deg=deg)
@@ -704,6 +704,6 @@ def is_point_within_polygon(pos, shape):
if __name__ == '__main__':
a1 = 0.0
a2 = +0.1
- print 'a1', a1/np.pi*180
- print 'a2', a2/np.pi*180
- print 'anglediff(a1, a2)', anglediff(a1, a2)/np.pi*180
+ print('a1', a1/np.pi*180)
+ print('a2', a2/np.pi*180)
+ print('anglediff(a1, a2)', anglediff(a1, a2)/np.pi*180)
diff --git a/tools/contributed/sumopy/agilepy/lib_base/imports.py b/tools/contributed/sumopy/agilepy/lib_base/imports.py
index 425f74b95acf..1e8669267273 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/imports.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/imports.py
@@ -31,7 +31,7 @@ class CsvImporter(Process):
def __init__(self, obj, ident='csvimporter', name='CSV importer',
info='Import data from a CSV file into object',
logger=None, **kwargs):
- print 'CsvImporter.__init__'
+ print('CsvImporter.__init__')
self._init_common(ident,
parent=obj,
name=name,
@@ -78,7 +78,7 @@ def _get_colattrname(self, attrname):
return 'colname_'+attrname
def do(self):
- print 'CsvImporter.do',
+ print('CsvImporter.do', end=' ')
obj = self.parent
attrsman = self.get_attrsman()
sep = self.sep
@@ -98,9 +98,9 @@ def do(self):
filepath = self.csvfilepath
f = open(filepath, 'r')
- INTTYPES = (types.IntType, np.int, np.int32, np.int64)
- FLOATTYPES = (types.FloatType, types.LongType, types.ComplexType, np.float, np.float32, np.float64)
- BOOLTYPES = (types.BooleanType, np.bool_)
+ INTTYPES = (int, np.int, np.int32, np.int64)
+ FLOATTYPES = (float, int, complex, np.float, np.float32, np.float64)
+ BOOLTYPES = (bool, np.bool_)
#line = f.readline()
# print ' line[:-1] = *%s*'%(line[:-1],)
@@ -146,7 +146,7 @@ def do(self):
for line in f.readlines():
cols = line.split(sep)
if len(cols) > ind_max: # restrictive!
- for ind, vals, valtype in zip(index_to_value.keys(), index_to_value.values(), index_to_type.values()):
+ for ind, vals, valtype in zip(list(index_to_value.keys()), list(index_to_value.values()), list(index_to_type.values())):
val = cols[ind].strip()
if val not in emptycol:
if valtype == INTTYPE:
@@ -173,7 +173,7 @@ def do(self):
n_imported += 1
ids = obj.add_rows(n_imported)
- for ind, values in index_to_value.iteritems():
+ for ind, values in index_to_value.items():
getattr(obj, index_to_attrname[ind])[ids] = values
f.close()
diff --git a/tools/contributed/sumopy/agilepy/lib_base/logger.py b/tools/contributed/sumopy/agilepy/lib_base/logger.py
index 8ee85e6d6628..7e0469614dc4 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/logger.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/logger.py
@@ -36,7 +36,7 @@ def start(self, text="Start logging."):
self._logfile = open(self._filepath, 'w')
self._logfile.write(ttext+'\n')
if self._is_stdout:
- print text
+ print(text)
def add_callback(self, function, key='message'):
self._callbacks[key] = function
@@ -62,13 +62,13 @@ def w(self, data, key='message', **kwargs):
if self._logfile is not None:
self._logfile.write(strftime(self._timeformat, gmtime())+' '+text+'\n')
- elif self._callbacks.has_key(key):
+ elif key in self._callbacks:
kwargs['key'] = key
self._callbacks[key](data, **kwargs)
# elif type(data)==types.StringType:
# print data
if self._is_stdout:
- print text
+ print(text)
def stop(self, text="End logging."):
@@ -79,4 +79,4 @@ def stop(self, text="End logging."):
self._logfile = None
if self._is_stdout:
- print text
+ print(text)
diff --git a/tools/contributed/sumopy/agilepy/lib_base/misc.py b/tools/contributed/sumopy/agilepy/lib_base/misc.py
index 203b9c849406..22f8fdb48fb3 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/misc.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/misc.py
@@ -47,7 +47,7 @@ def string_to_float(s):
def get_inversemap(m):
- return {v: k for k, v in m.items()}
+ return {v: k for k, v in list(m.items())}
def random_choice_dist2(n, b):
@@ -133,7 +133,7 @@ def ff(filepath):
def filepathlist_to_filepathstring(filepathlist, sep=','):
- if type(filepathlist) == types.ListType:
+ if type(filepathlist) == list:
if len(filepathlist) == 0:
return ''
else:
@@ -157,7 +157,7 @@ def filepathstring_to_filepathlist(filepathstring, sep=','):
def dict_to_str(d, intend=0):
s = ''
- for key, value in d.iteritems():
+ for key, value in d.items():
s += intend*" "+"%s: %s\n" % (key, value)
return s
diff --git a/tools/contributed/sumopy/agilepy/lib_base/processes.py b/tools/contributed/sumopy/agilepy/lib_base/processes.py
index c017d4e61224..01e2b5c83d26 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/processes.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/processes.py
@@ -30,8 +30,8 @@
#APPDIR = os.path.join(os.path.dirname(__file__),"..")
-import classman as cm
-from misc import filepathlist_to_filepathstring, filepathstring_to_filepathlist, ff, P
+from . import classman as cm
+from .misc import filepathlist_to_filepathstring, filepathstring_to_filepathlist, ff, P
# p = psutil.Process(the_pid_you_want) !!
@@ -162,7 +162,7 @@ def save_options(self, filepath):
try:
f = open(filepath, 'wb')
except:
- print 'WARNING in save: could not open', filepath
+ print('WARNING in save: could not open', filepath)
return False
# print ' before',is_not_save_parent,parent,obj.parent
@@ -173,7 +173,7 @@ def load_options(self, filepath):
try:
f = open(filepath, 'rb')
except:
- print 'WARNING in load_options: could not open', filepath
+ print('WARNING in load_options: could not open', filepath)
return None
# try:
@@ -182,7 +182,7 @@ def load_options(self, filepath):
f.close()
attrsman = self.get_attrsman()
- for attrname, value in optiondata.iteritems():
+ for attrname, value in optiondata.items():
if attrsman.has_attrname(attrname):
attrsman.get_config(attrname).set_value(value)
@@ -197,7 +197,7 @@ def __init__(self, **kwargs):
self._cmlvaluemaps = []
self._transdir = {}
self._filepathattrs = []
- for attr, value in kwargs.iteritems():
+ for attr, value in kwargs.items():
self.add_option(attr, value)
def add_option(self, attr='', value='', cml=None,
@@ -231,7 +231,7 @@ def get_optionstring(self):
cmlattr = self._transdir.get(attr, attr)
is_continue = True
if cmlvaluemap is not None:
- if cmlvaluemap.has_key(value):
+ if value in cmlvaluemap:
is_continue = False # take value from mapping
if P == '"': # windows
s += ' '+cmlattr+' "%s"' % cmlvaluemap[value]
@@ -244,10 +244,10 @@ def get_optionstring(self):
if attr in self._filepathattrs:
if value != '':
s += ' '+cmlattr+' %s' % filepathlist_to_filepathstring(value.split(','))
- elif type(value) == types.BooleanType:
+ elif type(value) == bool:
if value:
s += ' '+cmlattr
- elif type(value) in [types.StringTypes, types.UnicodeType]:
+ elif type(value) in [(str,), str]:
if P == '"': # windows
s += ' '+cmlattr+' "%s"' % value
else:
@@ -314,14 +314,14 @@ def add_option(self, option, value, **kwargs):
setattr(self, option, default)
def get_options(self):
- print '\nget_options'
+ print('\nget_options')
options = Options()
for attrconfig in self.get_attrsman().get_configs(is_all=True):
if self.optiongroupname in attrconfig.groupnames:
- print ' option', attrconfig.attrname, attrconfig.groupnames, 'is path', attrconfig.get_metatype() in self.pathmetatypes, 'has cmlmap', hasattr(attrconfig, 'cmlvaluemap')
+ print(' option', attrconfig.attrname, attrconfig.groupnames, 'is path', attrconfig.get_metatype() in self.pathmetatypes, 'has cmlmap', hasattr(attrconfig, 'cmlvaluemap'))
is_enabled = True
if hasattr(attrconfig, 'is_enabled'):
- print ' is_enabled=', attrconfig.is_enabled(self), attrconfig.get_value()
+ print(' is_enabled=', attrconfig.is_enabled(self), attrconfig.get_value())
is_enabled = attrconfig.is_enabled(self)
if is_enabled: # disabeled options are simply not added
if hasattr(attrconfig, 'cmlvaluemap'):
@@ -335,10 +335,10 @@ def get_options(self):
return options
def print_options(self):
- print 'Options of process ident:', self.ident
- print ' Keywordoptions:'
+ print('Options of process ident:', self.ident)
+ print(' Keywordoptions:')
for attrconfig in self.get_attrsman().get_configs(filtergroupnames=[self.optiongroupname]):
- print ' ', attrconfig.attrname, '=', attrconfig.get_value()
+ print(' ', attrconfig.attrname, '=', attrconfig.get_value())
def reset_cml(self, cml):
self._command = cml
@@ -352,7 +352,7 @@ def get_cml(self, is_changecwd=False, is_without_command=False):
# if self.workdirpath is not None
options = self.get_options()
optionstr = options.get_optionstring()
- print 'get_cml command', self._command, 'workdirpath', self.workdirpath
+ print('get_cml command', self._command, 'workdirpath', self.workdirpath)
if True: # self.workdirpath is None:
if is_without_command:
cml = optionstr
@@ -380,8 +380,8 @@ def run_cml(self, cml=None):
attrsman.pid.set(self._subprocess.pid)
attrsman.status.set('running')
- print 'run_cml cml=', cml
- print ' pid = ', self.pid, 'cwd', wd
+ print('run_cml cml=', cml)
+ print(' pid = ', self.pid, 'cwd', wd)
if not self.is_run_background:
self._subprocess.wait()
# if self.workdirpath is not None:
diff --git a/tools/contributed/sumopy/agilepy/lib_base/test_classman_classes.py b/tools/contributed/sumopy/agilepy/lib_base/test_classman_classes.py
index ec811d2eb065..a3650f39fe05 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/test_classman_classes.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/test_classman_classes.py
@@ -21,37 +21,37 @@
Provides test classes and some test functions for plugin.
"""
-from classman import *
-from arrayman import *
-import xmlman as xm
+from .classman import *
+from .arrayman import *
+from . import xmlman as xm
def on_event_delattr(attrconfig):
- print 'EVENT: Attribute', attrconfig.attrname, 'will be deleted!!'
+ print('EVENT: Attribute', attrconfig.attrname, 'will be deleted!!')
def on_event_setattr(attrconfig):
- print 'EVENT: Attribute', attrconfig.attrname, 'has been set to a new value', attrconfig.format_value()
+ print('EVENT: Attribute', attrconfig.attrname, 'has been set to a new value', attrconfig.format_value())
def on_event_getattr(attrconfig):
- print 'EVENT: Attribute', attrconfig.attrname, 'has been retrieved the value', attrconfig.format_value()
+ print('EVENT: Attribute', attrconfig.attrname, 'has been retrieved the value', attrconfig.format_value())
def on_event_additem(attrconfig, keys):
- print 'EVENT: Attribute', attrconfig.attrname, ':added keys:', keys
+ print('EVENT: Attribute', attrconfig.attrname, ':added keys:', keys)
def on_event_delitem(attrconfig, keys):
- print 'EVENT: Attribute', attrconfig.attrname, ':delete keys:', keys
+ print('EVENT: Attribute', attrconfig.attrname, ':delete keys:', keys)
def on_event_setitem(attrconfig, keys):
- print 'EVENT: Attribute', attrconfig.attrname, ':set keys:', keys
+ print('EVENT: Attribute', attrconfig.attrname, ':set keys:', keys)
def on_event_getitem(attrconfig, keys):
- print 'EVENT: Attribute', attrconfig.attrname, ':get keys:', keys
+ print('EVENT: Attribute', attrconfig.attrname, ':get keys:', keys)
class Segments(ArrayObjman):
@@ -125,15 +125,15 @@ def draw(self, pointvertices, id_osm):
]
"""
vertices = []
- print 'draw', self.ident
- for i in xrange(1, len(pointvertices)):
+ print('draw', self.ident)
+ for i in range(1, len(pointvertices)):
vertices.append([pointvertices[i-1], pointvertices[i]])
n_vert = len(vertices)
_id = self.add_row(ids_osm=id_osm)
cod = []
#import string
clist = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'], np.object)
- print ' ', len(vertices), clist[:len(vertices)]
+ print(' ', len(vertices), clist[:len(vertices)])
ids = self.segments.value.suggest_ids(len(vertices))
ids_segs = self.segments.value.add_rows(ids=ids, vertices=vertices, ids_parent=n_vert*[_id], ids_ref=clist[ids])
self.ids_segments[_id] = list(ids_segs) # put here list, otherwise numpy thinks it is a numeric array
@@ -300,7 +300,7 @@ def on_is_pos_ok(self):
"""
True if position greater than thhreshold.
"""
- print 'on_is_pos_ok', self.x > self.x_thresh
+ print('on_is_pos_ok', self.x > self.x_thresh)
return self.x > self.x_thresh
@@ -331,7 +331,7 @@ def __init__(self, ident='testobj2', parent=None, name='Test Object2', xmltag='
self.child1 = attrsman.add(ObjConf(TestClass('child1', self))
)
- print 'TestClass2.child1', self.child1
+ print('TestClass2.child1', self.child1)
self.child3 = attrsman.add(ObjConf(TestClass3('child3', self))
)
@@ -368,7 +368,7 @@ def __init__(self, ident='test_tabman', parent=None, name='Test Table manage'):
attrsman.add_rows(5)
attrsman.streetname[3] = 'ssss'
attrsman.streetname[[1, 2]] = ['aa', 55]
- print 'test get', attrsman.streetname[[1, 2]]
+ print('test get', attrsman.streetname[[1, 2]])
# self.streetname[1]+='zzz'
attrsman.del_rows([1, 3])
attrsman.del_row(5)
@@ -485,9 +485,9 @@ def on_del_row(self, id_row):
"""
True if position greater than thhreshold.
"""
- print 'on_del_row', id_row
+ print('on_del_row', id_row)
self.del_row(id_row)
- print ' ids after del', self.get_ids()
+ print(' ids after del', self.get_ids())
class TestTableObjManNocols(TableObjman):
diff --git a/tools/contributed/sumopy/agilepy/lib_base/test_classman_misc.py b/tools/contributed/sumopy/agilepy/lib_base/test_classman_misc.py
index 2da0986fb5ee..627a17e957b8 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/test_classman_misc.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/test_classman_misc.py
@@ -17,7 +17,7 @@
# @date 2012
-from classman import *
+from .classman import *
c = ColConf('streetname', 'xxx',
groupnames=['state'],
perm='rw',
diff --git a/tools/contributed/sumopy/agilepy/lib_base/test_classman_save.py b/tools/contributed/sumopy/agilepy/lib_base/test_classman_save.py
index dca9c1218e4b..1ca52cee9b76 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/test_classman_save.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/test_classman_save.py
@@ -18,9 +18,9 @@
#from classman import *
-from test_classman_classes import *
-from arrayman import *
-import xmlman as xm
+from .test_classman_classes import *
+from .arrayman import *
+from . import xmlman as xm
# TODOD: create a test object with all tests
is_all = 0
@@ -105,17 +105,17 @@ def __init__(self, ident, parent=None, xmltag=('lines', 'line', 'ids_sumo'), **
# save/load
save_obj(lines, 'test_lines.obj')
del lines
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
lines = load_obj('test_lines.obj')
lines.print_attrs()
- print 'direct access vertex=\n', lines.vertices.value
- print 'direct access polygons=\n', lines.polygons.value
- print 'id for index bb22=', lines.ids_sumo.get_id_from_index('bb22')
- print 'ids for index bb22,cc333=', lines.ids_sumo.get_ids_from_indices(['bb22', 'cc333'])
+ print('direct access vertex=\n', lines.vertices.value)
+ print('direct access polygons=\n', lines.polygons.value)
+ print('id for index bb22=', lines.ids_sumo.get_id_from_index('bb22'))
+ print('ids for index bb22,cc333=', lines.ids_sumo.get_ids_from_indices(['bb22', 'cc333']))
lines.del_row(2)
lines.print_attrs()
- print 'id for index bb22=', lines.ids_sumo.get_id_from_index('cc333')
+ print('id for index bb22=', lines.ids_sumo.get_id_from_index('cc333'))
if 0 | is_all:
class Lines(ArrayObjman):
@@ -166,19 +166,19 @@ def __init__(self, ident, parent=None, **kwargs):
# lines.add_rows(3)
lines.add_rows(3, vertices=vertices, polygons=polygons)
lines.print_attrs()
- print 'direct access vertex=\n', lines.vertices.value
- print 'direct access polygons=\n', lines.polygons.value
+ print('direct access vertex=\n', lines.vertices.value)
+ print('direct access polygons=\n', lines.polygons.value)
# save/load
save_obj(lines, 'test_lines.obj')
del lines
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
lines = load_obj('test_lines.obj')
# print
lines.print_attrs()
- print 'direct access vertex=\n', lines.vertices.value
- print 'direct access polygons=\n', lines.polygons.value
+ print('direct access vertex=\n', lines.vertices.value)
+ print('direct access polygons=\n', lines.polygons.value)
vertices2 = [
[[0.0, 0.0, 0.0], [0.2, 0.0, 0.0]], # 0
@@ -325,9 +325,9 @@ def __init__(self, ident, parent=None, **kwargs):
demand.get_attrsman().print_attrs()
odintervals.print_attrs()
for id_odmodes in odintervals.get_ids():
- print '\nMODE:'
+ print('\nMODE:')
odintervals.odmodes[id_odmodes].print_attrs()
- print '\nTRIPS:'
+ print('\nTRIPS:')
for id_odtrips in odmodes.get_ids():
odmodes.odtrips[id_odtrips].print_attrs()
@@ -335,16 +335,16 @@ def __init__(self, ident, parent=None, **kwargs):
# save/load
save_obj(demand, 'test_demand_array.obj')
del demand
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
demand = load_obj('test_demand_array.obj')
# print
demand.get_attrsman().print_attrs()
odintervals.print_attrs()
for id_odmodes in odintervals.get_ids():
- print '\nMODE:'
+ print('\nMODE:')
odintervals.odmodes[id_odmodes].print_attrs()
- print '\nTRIPS:'
+ print('\nTRIPS:')
for id_odtrips in odmodes.get_ids():
odmodes.odtrips[id_odtrips].print_attrs()
@@ -457,25 +457,25 @@ def __init__(self, ident, parent=None, **kwargs):
demand.get_attrsman().print_attrs()
odintervals.print_attrs()
for id_odmodes in odintervals.get_ids():
- print '\nMODE:'
+ print('\nMODE:')
odintervals.odmodes[id_odmodes].print_attrs()
- print '\nTRIPS:'
+ print('\nTRIPS:')
for id_odtrips in odmodes.get_ids():
odmodes.odtrips[id_odtrips].print_attrs()
# save/load
save_obj(demand, 'test_demand.obj')
del demand
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
demand = load_obj('test_demand.obj')
# print
demand.get_attrsman().print_attrs()
odintervals.print_attrs()
for id_odmodes in odintervals.get_ids():
- print '\nMODE:'
+ print('\nMODE:')
odintervals.odmodes[id_odmodes].print_attrs()
- print '\nTRIPS:'
+ print('\nTRIPS:')
for id_odtrips in odmodes.get_ids():
odmodes.odtrips[id_odtrips].print_attrs()
@@ -534,7 +534,7 @@ def __init__(self, ident, parent=None, **kwargs):
net.nodes.print_attrs()
save_obj(net, 'test_net.obj')
del net
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
net_new = load_obj('test_net.obj')
net_new.get_attrsman().print_attrs()
net_new.edges.print_attrs()
@@ -564,23 +564,23 @@ def __init__(self, ident, parent=None, **kwargs):
streetname=['a', 'bb', 'ccc', 'dddd'],
)
- print 'direct access: tab1.surname.value', tab1.surname.value
- print 'direct access: tab1.streetname.value', tab1.streetname.value
+ print('direct access: tab1.surname.value', tab1.surname.value)
+ print('direct access: tab1.streetname.value', tab1.streetname.value)
tab1.print_attrs()
save_obj(tab1, 'test_tab.obj')
del tab1
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
tab1_new = load_obj('test_tab.obj')
tab1_new.print_attrs()
- print 'direct access: tab1_new.surname.value', tab1_new.surname.value
- print 'direct access: tab1_new.streetname.value', tab1_new.streetname.value
+ print('direct access: tab1_new.surname.value', tab1_new.surname.value)
+ print('direct access: tab1_new.streetname.value', tab1_new.streetname.value)
if 0 | is_all:
tab1 = TableObjman('tab1')
- print '\ntab1.ident', tab1.ident
+ print('\ntab1.ident', tab1.ident)
tab2 = TableObjman('tab2', parent=tab1)
- print '\ntab2.ident', tab2.ident
+ print('\ntab2.ident', tab2.ident)
# TODO: seperate attrname from linked obj ident because restrictive and makes problems with multiple tab destinations
# this should be possible ...following the path of attrnames of absident
@@ -620,24 +620,24 @@ def __init__(self, ident, parent=None, **kwargs):
save_obj(tab1, 'test_tab.obj')
del tab1
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
tab1_new = load_obj('test_tab.obj')
tab1_new.print_attrs()
tab2_new = tab1_new.tab2.get_valueobj()
tab2_new.print_attrs()
- print tab2_new.get_ident_abs()
+ print(tab2_new.get_ident_abs())
if False | is_all: # False:#True:
obj = TestTabman()
- print 'obj.ident', obj.ident
+ print('obj.ident', obj.ident)
obj.attrsman.print_attrs()
save_obj(obj, 'test_obj.obj')
del obj
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
obj_new = load_obj('test_obj.obj')
obj_new.attrsman.print_attrs()
# streetname
@@ -648,7 +648,7 @@ def __init__(self, ident, parent=None, **kwargs):
if 0 | is_all: # False:#True: ###!!!!!!!!!!!!!!!!check this : failed to reload!!
obj = TestTableObjMan()
- print 'obj.ident', obj.ident
+ print('obj.ident', obj.ident)
obj.x.set(1.0/3)
# obj.is_pos_ok.set(True)
@@ -656,7 +656,7 @@ def __init__(self, ident, parent=None, **kwargs):
obj.print_attrs()
save_obj(obj, 'test_obj.obj')
del obj
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
obj_new = load_obj('test_obj.obj')
obj_new.x.set(2.0/3)
obj_new.print_attrs()
@@ -667,12 +667,12 @@ def __init__(self, ident, parent=None, **kwargs):
#
if 0 | is_all:
- print 'TestTableObjMan export'
+ print('TestTableObjMan export')
obj = TestTableObjMan()
obj.get_attrsman().print_attrs()
xm.write_obj_to_xml(obj, 'test_obj.xml')
del obj
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
obj_new = load_obj('test_obj.obj')
obj_new.get_attrsman().print_attrs()
# sys.exit()
@@ -689,7 +689,7 @@ def __init__(self, ident, parent=None, **kwargs):
save_obj(obj2, 'test_obj2.obj')
xm.write_obj_to_xml(obj2, 'test_obj2.xml')
del obj2
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
obj2_new = load_obj('test_obj2.obj')
obj2_new.get_attrsman().print_attrs()
@@ -699,9 +699,9 @@ def __init__(self, ident, parent=None, **kwargs):
if 0 | is_all: # False:#True:
obj = TestClass()
- print 'obj.ident', obj.ident
+ print('obj.ident', obj.ident)
- print 'This is the value of the attribute: obj.x=', obj.x
+ print('This is the value of the attribute: obj.x=', obj.x)
# print 'This is the configuration instance of the attribute x',obj.attrsman.x
obj.get_attrsman().print_attrs()
# obj.get_attrsman().x.plugin.add_event(EVTSET,on_event_setattr)
@@ -712,16 +712,16 @@ def __init__(self, ident, parent=None, **kwargs):
# print 'Test func...',obj.attrsman.testfunc.get()
# obj.get_attrsman().testfunc.add_event(EVTGET,on_event_getattr)
# obj.get_attrsman().testfunc.get()
- print 'obj.get_attrsman().x.get()', obj.get_attrsman().x.get(), 'is_modified', obj.is_modified()
+ print('obj.get_attrsman().x.get()', obj.get_attrsman().x.get(), 'is_modified', obj.is_modified())
obj.get_attrsman().x.set(1.0)
- print 'obj.get_attrsman().x.get()', obj.get_attrsman().x.get(), 'is_modified', obj.is_modified()
+ print('obj.get_attrsman().x.get()', obj.get_attrsman().x.get(), 'is_modified', obj.is_modified())
# obj.attrsman.delete('x')
obj.get_attrsman().print_attrs()
save_obj(obj, 'test_obj.obj')
xm.write_obj_to_xml(obj, 'test_obj.xml')
del obj
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
obj_new = load_obj('test_obj.obj')
obj_new.get_attrsman().print_attrs()
# print 'obj.get_attrsman().x.get_formatted()=',obj.get_attrsman().x.get_formatted()
@@ -729,12 +729,12 @@ def __init__(self, ident, parent=None, **kwargs):
if 1 | is_all:
save_obj(drawing, 'test_drawing.obj')
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
obj_new = load_obj('test_drawing.obj')
obj_new.get_attrsman().print_attrs()
obj_new.collections.print_attrs()
tab_check, ids_check = obj_new.collections.tab_id_lists[1][1]
- print ' check tab, ids=', tab_check, ids_check
+ print(' check tab, ids=', tab_check, ids_check)
tab_check.print_attrs()
diff --git a/tools/contributed/sumopy/agilepy/lib_base/test_classman_tables.py b/tools/contributed/sumopy/agilepy/lib_base/test_classman_tables.py
index 254ae67b12d3..ceae8b2f4033 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/test_classman_tables.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/test_classman_tables.py
@@ -18,14 +18,14 @@
#from classman import *
-from test_classman_classes import *
-from classman import *
-from arrayman import *
+from .test_classman_classes import *
+from .classman import *
+from .arrayman import *
is_all = 0
if 1 | is_all:
pass
if 1 | is_all:
- print 'Lines, Poly example'
+ print('Lines, Poly example')
###########################################################################
# Instance creation
@@ -54,17 +54,17 @@
# lines.add_rows(3)
lines.add_rows(3, vertices=vertices, polygons=polygons, ids_sumo=ids_sumo)
lines.print_attrs()
- print '\n indexmap', lines.ids_sumo.get_indexmap()
- print 'direct access vertex=\n', lines.vertices.value
- print 'id for index bb22=', lines.ids_sumo.get_id_from_index('bb22')
- print 'ids for index bb22,cc333=', lines.ids_sumo.get_ids_from_indices(['bb22', 'cc333'])
+ print('\n indexmap', lines.ids_sumo.get_indexmap())
+ print('direct access vertex=\n', lines.vertices.value)
+ print('id for index bb22=', lines.ids_sumo.get_id_from_index('bb22'))
+ print('ids for index bb22,cc333=', lines.ids_sumo.get_ids_from_indices(['bb22', 'cc333']))
# lines.del_row(2)
lines.print_attrs()
- print 'id for index bb22=', lines.ids_sumo.get_id_from_index('cc333')
+ print('id for index bb22=', lines.ids_sumo.get_id_from_index('cc333'))
lines.ids_sumo[2] = 'xy'
- print '\n indexmap', lines.ids_sumo.get_indexmap()
+ print('\n indexmap', lines.ids_sumo.get_indexmap())
lines.print_attrs()
if 0 | is_all:
class Lines(TableObjman):
@@ -124,13 +124,13 @@ def __init__(self, ident, parent=None, **kwargs):
# lines.add_rows(3)
lines.add_rows(3, vertices=vertices, polygons=polygons, ids_sumo=ids_sumo)
lines.print_attrs()
- print 'direct access vertex=\n', lines.vertices.value
- print 'direct access polygons=\n', lines.polygons.value
- print 'id for index bb22=', lines.ids_sumo.get_id_from_index('bb22')
- print 'ids for index bb22,cc333=', lines.ids_sumo.get_ids_from_indices(['bb22', 'cc333'])
+ print('direct access vertex=\n', lines.vertices.value)
+ print('direct access polygons=\n', lines.polygons.value)
+ print('id for index bb22=', lines.ids_sumo.get_id_from_index('bb22'))
+ print('ids for index bb22,cc333=', lines.ids_sumo.get_ids_from_indices(['bb22', 'cc333']))
lines.del_row(2)
lines.print_attrs()
- print 'id for index bb22=', lines.ids_sumo.get_id_from_index('cc333')
+ print('id for index bb22=', lines.ids_sumo.get_id_from_index('cc333'))
if 0 | is_all:
class Lines(ArrayObjman):
@@ -180,8 +180,8 @@ def __init__(self, ident, parent=None, **kwargs):
# lines.add_rows(3)
lines.add_rows(3, vertices=vertices, polygons=polygons)
lines.print_attrs()
- print 'direct access vertex=\n', lines.vertices.value
- print 'direct access polygons=\n', lines.polygons.value
+ print('direct access vertex=\n', lines.vertices.value)
+ print('direct access polygons=\n', lines.polygons.value)
if 0 | is_all:
class ZonesTab(ArrayObjman):
@@ -292,9 +292,9 @@ def __init__(self, ident, parent=None, **kwargs):
odintervals.print_attrs()
for id_odmodes in odintervals.get_ids():
- print '\nMODE:'
+ print('\nMODE:')
odintervals.odmodes[id_odmodes].print_attrs()
- print '\nTRIPS:'
+ print('\nTRIPS:')
for id_odtrips in odmodes.get_ids():
odmodes.odtrips[id_odtrips].print_attrs()
@@ -408,9 +408,9 @@ def __init__(self, ident, parent=None, **kwargs):
odintervals.print_attrs()
for id_odmodes in odintervals.get_ids():
- print '\nMODE:'
+ print('\nMODE:')
odintervals.odmodes[id_odmodes].print_attrs()
- print '\nTRIPS:'
+ print('\nTRIPS:')
for id_odtrips in odmodes.get_ids():
odmodes.odtrips[id_odtrips].print_attrs()
@@ -483,16 +483,16 @@ def __init__(self, ident, parent=None, **kwargs):
streetname=['a', 'bb', 'ccc', 'dddd'],
)
- print 'direct access: tab1.surname.value', tab1.surname.value
+ print('direct access: tab1.surname.value', tab1.surname.value)
tab1.print_attrs()
if 0 | is_all:
tab1 = TableObjman('tab1')
- print '\ntab1.ident', tab1.ident
+ print('\ntab1.ident', tab1.ident)
tab2 = TableObjman('tab2', parent=tab1)
- print '\ntab2.ident', tab2.ident
+ print('\ntab2.ident', tab2.ident)
# TODO: seperate attrname from linked obj ident because restrictive and makes problems with multiple tab destinations
# this should be possible ...following the path of attrnames of absident
@@ -534,7 +534,7 @@ def __init__(self, ident, parent=None, **kwargs):
if 0 | is_all:
obj = TestTabman()
- print '\nobj.ident', obj.ident
+ print('\nobj.ident', obj.ident)
# streetname
# print 'This is the value of the attribute: obj.streetname=',obj.streetname
@@ -545,7 +545,7 @@ def __init__(self, ident, parent=None, **kwargs):
if 0 | is_all:
obj = TestTableObjMan()
- print '\nobj.ident', obj.ident
+ print('\nobj.ident', obj.ident)
# streetname
# print 'This is the value of the attribute: obj.streetname=',obj.streetname
diff --git a/tools/contributed/sumopy/agilepy/lib_base/xmlman.py b/tools/contributed/sumopy/agilepy/lib_base/xmlman.py
index 277b0b473ede..ed4ad29bc05b 100644
--- a/tools/contributed/sumopy/agilepy/lib_base/xmlman.py
+++ b/tools/contributed/sumopy/agilepy/lib_base/xmlman.py
@@ -31,7 +31,7 @@ def write_obj_to_xml(obj, filepath,
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in write_obj_to_xml: could not open', filepath
+ print('WARNING in write_obj_to_xml: could not open', filepath)
return False
fd.write('\n' % encoding)
indent = 0
@@ -81,7 +81,7 @@ def arr(attr, a, sep=' '):
if len(a) > 0:
format = '%s'
s += '%s="' % attr
- for i in xrange(len(a)):
+ for i in range(len(a)):
# print ' a[i]',a[i],type(a[i]),str(a[i]),type(str(a[i]))
#ss = str(a[i])
# print ' ',type(s),type(ss),type(sep)
@@ -101,9 +101,9 @@ def mat(attr, m):
s = ' '
if len(m) > 0:
s += '%s="' % attr
- for i in xrange(len(m)):
+ for i in range(len(m)):
r = m[i]
- for j in xrange(len(r)-1):
+ for j in range(len(r)-1):
s += '%s,' % r[j]
s += '%s ' % r[-1]
return s[:-1]+'"'
diff --git a/tools/contributed/sumopy/agilepy/lib_misc/docgen.py b/tools/contributed/sumopy/agilepy/lib_misc/docgen.py
index 602402800a21..50768d00daac 100644
--- a/tools/contributed/sumopy/agilepy/lib_misc/docgen.py
+++ b/tools/contributed/sumopy/agilepy/lib_misc/docgen.py
@@ -29,7 +29,7 @@
##
import numpy as np
-from matplotlibtools import save_fig, init_plot
+from .matplotlibtools import save_fig, init_plot
# needed for doc gen + import numpy as np
from os import system, path, getcwd, chdir
@@ -37,9 +37,9 @@
##############################################################################
# convenience functions for Doc
-ARRAYTYPES = (types.TupleType, np.ndarray, types.ListType, types.XRangeType)
-INTTYPES = (types.IntType, np.int32, np.int64, np.int0, np.int16, np.int8, types.LongType)
-FLOATTYPES = (types.FloatType, np.float64)
+ARRAYTYPES = (tuple, np.ndarray, list, range)
+INTTYPES = (int, np.int32, np.int64, np.int0, np.int16, np.int8, int)
+FLOATTYPES = (float, np.float64)
def is_arraytype(obj):
@@ -322,8 +322,8 @@ def matrix(self, matrix, format=None, is_math=True, leftbrace='(', rightbrace=')
n_row = len(matrix)
n_col = len(matrix[0])
self.begin_array(n_col, leftbrace, arraystretch)
- for row in xrange(0, n_row):
- for col in xrange(0, n_col):
+ for row in range(0, n_row):
+ for col in range(0, n_col):
# print ' ',col,row,matrix[row,col]
if col == (n_col-1):
sep = "\\\\ \n"
@@ -340,7 +340,7 @@ def colvec(self, vec, format=None, is_math=True):
n_row = len(vec)
sep = "\\\\ \n"
self.begin_array(1)
- for col in xrange(0, n_row):
+ for col in range(0, n_row):
self._write_arrayelement(vec[col], sep, format_default=format, is_math=is_math)
self.end_array()
@@ -349,7 +349,7 @@ def rowvec(self, vec, format=None, is_math=True):
n_row = len(vec)
self.begin_array(n_row)
- for row in xrange(0, n_row):
+ for row in range(0, n_row):
# print ' ',col,row,matrix[row,col]
if row == (n_row-1):
sep = "\\\\ \n"
@@ -400,7 +400,7 @@ def end_center(self):
def include_graphics(self, filename, options=None, is_centered=True,
method='matplotlib', label=None, caption=None, envoptions='h!'):
- print 'include_graphics ', filename
+ print('include_graphics ', filename)
path_file = path.join(self.workdir, filename)
if options is None:
options = 'width = \\textwidth'
@@ -459,7 +459,7 @@ def end(self):
self.f.write("""\\end{document}\n""")
self.f.close()
if self.is_compile:
- print 'compile latex ', self.path_file
+ print('compile latex ', self.path_file)
system('pdflatex ' + self.path_file)
diff --git a/tools/contributed/sumopy/agilepy/lib_wx/mainframe.py b/tools/contributed/sumopy/agilepy/lib_wx/mainframe.py
index ce5b719a28a9..1c616f99daa9 100644
--- a/tools/contributed/sumopy/agilepy/lib_wx/mainframe.py
+++ b/tools/contributed/sumopy/agilepy/lib_wx/mainframe.py
@@ -25,13 +25,13 @@
import time
from collections import OrderedDict
-from wxmisc import KEYMAP, AgileMenuMixin, AgileToolbarFrameMixin, AgileStatusbar, AgileMenubar
+from .wxmisc import KEYMAP, AgileMenuMixin, AgileToolbarFrameMixin, AgileStatusbar, AgileMenubar
from os.path import *
from os import getcwd
-import objpanel
+from . import objpanel
from agilepy.lib_base.logger import Logger
# We first have to set an application-wide help provider. Normally you
@@ -295,7 +295,7 @@ def __init__(self, parent=None, title='mainframe', appname=None,
#################################################################
self._moduleguis = make_moduleguis(appdir, moduledirs)
- for modulename, modulegui in self._moduleguis.iteritems():
+ for modulename, modulegui in self._moduleguis.items():
# print ' init gui of module',modulename
modulegui.init_widgets(self)
#################################################################
@@ -311,7 +311,7 @@ def set_title(self, titlename):
def refresh_moduleguis(self):
# print 'refresh_moduleguis',len(self._moduleguis)
self.browse_obj(None)
- for modulename, modulegui in self._moduleguis.iteritems():
+ for modulename, modulegui in self._moduleguis.items():
# print ' refresh gui of module',modulename
modulegui.refresh_widgets()
@@ -392,12 +392,12 @@ def on_size(self, event=None):
# event.Skip()
def on_save(self, event):
- print 'save it!!'
+ print('save it!!')
def on_open(self, event):
"""Open a document"""
#wildcards = CreateWildCards() + "All files (*.*)|*.*"
- print 'open it!!'
+ print('open it!!')
def destroy(self):
"""Destroy this object"""
@@ -408,7 +408,7 @@ def destroy(self):
def on_close(self, event):
# self.Close(True)
- print 'Mainframe.on_close'
+ print('Mainframe.on_close')
# pass
self.destroy()
diff --git a/tools/contributed/sumopy/agilepy/lib_wx/objbrowser.py b/tools/contributed/sumopy/agilepy/lib_wx/objbrowser.py
index b17b40bb943c..f5a5bf0e5d1b 100644
--- a/tools/contributed/sumopy/agilepy/lib_wx/objbrowser.py
+++ b/tools/contributed/sumopy/agilepy/lib_wx/objbrowser.py
@@ -17,8 +17,8 @@
# @date 2012
import wx
-from objpanel import *
-from mainframe import AgileMainframe, AgileStatusbar, AgileMenubar
+from .objpanel import *
+from .mainframe import AgileMainframe, AgileStatusbar, AgileMenubar
class ObjBrowserMainframe(AgileMainframe):
diff --git a/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py b/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py
index 6ca39d76e4c8..96b78ce9312a 100644
--- a/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py
+++ b/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py
@@ -23,7 +23,7 @@
import string
import random
from agilepy.lib_base.misc import filepathlist_to_filepathstring, filepathstring_to_filepathlist
-from wxmisc import KEYMAP, AgilePopupMenu, AgileToolbarMixin, get_tablecolors
+from .wxmisc import KEYMAP, AgilePopupMenu, AgileToolbarMixin, get_tablecolors
import agilepy.lib_base.exports as ex
import time
from agilepy.lib_base.logger import Logger
@@ -83,13 +83,13 @@ def list_to_str(l, lb='', rb='', sep=','):
else:
s = lb
for e in l[:-1]:
- s += unicode(e)+sep
+ s += str(e)+sep
# print ' returns',s+unicode(l[-1])+rb
- return s+unicode(l[-1])+rb
+ return s+str(l[-1])+rb
def is_list_flat(l):
- if type(l) not in (types.ListType, types.TupleType): # STRINGTYPES:
+ if type(l) not in (list, tuple): # STRINGTYPES:
# not a list
return False
@@ -608,7 +608,7 @@ def get_valuewidget_write(self):
"""
value = self.get_value_obj()
# strange way to convert numpy type numbers into native python numbers
- if type(value) not in (types.IntType, types.LongType, types.FloatType, types.ComplexType):
+ if type(value) not in (int, int, float, complex):
value = value.tolist()
# print 'NumericWidgetContainer.get_valuewidget_write ',value,type(value),self._attrconf.digits_fraction
@@ -725,7 +725,7 @@ def set_widgetvalue(self, value):
# set value to label
# numpy returns dtype... even for scalars
# make sure to convert value in a native python scalar
- if type(value) not in (types.IntType, types.LongType, types.FloatType):
+ if type(value) not in (int, int, float):
value = value.tolist()
self.valuewidget.SetValue(str(value))
@@ -826,9 +826,9 @@ def define_widgetset(self):
"""
Generates the widgets representing this attribute.
"""
- if type(self._attrconf.choices) in (OrderedDict, types.DictionaryType):
- self._choicevalues = self._attrconf.choices.values()
- self._choicenames = self._attrconf.choices.keys()
+ if type(self._attrconf.choices) in (OrderedDict, dict):
+ self._choicevalues = list(self._attrconf.choices.values())
+ self._choicenames = list(self._attrconf.choices.keys())
else:
self._choicevalues = list(self._attrconf.choices)
self._choicenames = list(self._attrconf.choices)
@@ -851,7 +851,7 @@ def get_valuewidget_read(self):
# print 'ChoiceWidgetContainer.get_valuewidget_read',value,type(value)
# print ' choices',self._attrconf.choices
- if type(self._attrconf.choices) in (OrderedDict, types.DictionaryType):
+ if type(self._attrconf.choices) in (OrderedDict, dict):
#value = self._attrconf.choices[value]
value = self._choicenames[self._choicevalues.index(value)]
# print ' value =',value
@@ -910,7 +910,7 @@ def set_widgetvalue(self, val):
#ind = self._choicenames.index(value)
ind = self._choicevalues.index(val)
except:
- print 'WARNING in ChoiceWidgetContainer.set_widgetvalue: %s with value "%s" not in choice list' % (self._attrconf.attrname, val)
+ print('WARNING in ChoiceWidgetContainer.set_widgetvalue: %s with value "%s" not in choice list' % (self._attrconf.attrname, val))
return
# print ' ind',ind,self.valuewidget
if self._attrconf.is_writable():
@@ -936,7 +936,7 @@ def get_valuewidget_read(self):
# print ' choices',self._attrconf.choices
# mal values in list with .choices dictionary
- if (len(values) > 0) & (type(self._attrconf.choices) in (OrderedDict, types.DictionaryType)):
+ if (len(values) > 0) & (type(self._attrconf.choices) in (OrderedDict, dict)):
#value = self._attrconf.choices[value]
values = []
for val in self.get_value_obj():
@@ -1809,14 +1809,14 @@ def get_widgetcontainer(self, attrconf, **args):
return DatetimeWidgetContainer(self, attrconf, **args)
# elif mt == 'number':
- if tt in (types.IntType, types.LongType):
+ if tt in (int, int):
return IntegerWidgetContainer(self, attrconf, **args)
- elif tt in (types.FloatType, types.ComplexType):
+ elif tt in (float, complex):
return NumericWidgetContainer(self, attrconf, **args)
# check now native types
- elif tt in (types.BooleanType,):
+ elif tt in (bool,):
return BooleanWidgetContainer(self, attrconf, **args)
elif tt in STRINGTYPES:
@@ -1825,7 +1825,7 @@ def get_widgetcontainer(self, attrconf, **args):
# elif tt in (types.InstanceType,types.ClassType):
# return ObjWidgetContainer(self,attrconf,**args)
- elif tt in (types.ListType, types.TupleType):
+ elif tt in (list, tuple):
return ListWidgetContainer(self, attrconf, **args)
else:
@@ -2032,9 +2032,9 @@ def get_celltype(self, attrconf):
if len(attrconf.choices) < 200:
# print ' choices=',attrconf.choices
# (types.ListType, types.TupleType):
- if type(attrconf.choices) in (OrderedDict, types.DictionaryType):
+ if type(attrconf.choices) in (OrderedDict, dict):
# print ' GridCellChoiceEditor',attrconf.choices,':'+','.join(attrconf.choices.keys())
- return gridlib.GRID_VALUE_CHOICE+':'+','.join(attrconf.choices.keys())
+ return gridlib.GRID_VALUE_CHOICE+':'+','.join(list(attrconf.choices.keys()))
else:
# print ' GridCellChoiceEditor',attrconf.choices,':'+','.join(attrconf.choices)
return gridlib.GRID_VALUE_CHOICE+':'+','.join(attrconf.choices)
@@ -2062,9 +2062,9 @@ def get_celltype(self, attrconf):
if len(attrconf.choices) < 200:
# print ' dir(gridlib)',dir(gridlib)
# (types.ListType, types.TupleType):
- if type(attrconf.choices) in (OrderedDict, types.DictionaryType):
+ if type(attrconf.choices) in (OrderedDict, dict):
# print ' GridCellChoiceEditor',attrconf.choices,':'+','.join(attrconf.choices.keys())
- return gridlib.GRID_VALUE_CHOICE+':'+','.join(attrconf.choices.keys())
+ return gridlib.GRID_VALUE_CHOICE+':'+','.join(list(attrconf.choices.keys()))
else:
# print ' GridCellChoiceEditor',attrconf.choices,':'+','.join(attrconf.choices)
return gridlib.GRID_VALUE_CHOICE+':'+','.join(attrconf.choices)
@@ -2075,14 +2075,14 @@ def get_celltype(self, attrconf):
else:
return gridlib.GRID_VALUE_STRING
- elif tt in (types.LongType, types.IntType):
+ elif tt in (int, int):
if (hasattr(attrconf, 'min') & hasattr(attrconf, 'max')):
return gridlib.GRID_VALUE_NUMBER+':'\
+ str(attrconf.min)+','+str(attrconf.max)
else:
return gridlib.GRID_VALUE_NUMBER
- elif tt in (types.FloatType, types.ComplexType):
+ elif tt in (float, complex):
if (hasattr(attrconf, 'digits_integer') & hasattr(attrconf, 'digits_fraction')):
return gridlib.GRID_VALUE_FLOAT+':'\
+ str(attrconf.digits_integer)+','\
@@ -2093,7 +2093,7 @@ def get_celltype(self, attrconf):
elif tt in STRINGTYPES:
return gridlib.GRID_VALUE_STRING
- elif tt in (types.BooleanType,):
+ elif tt in (bool,):
return gridlib.GRID_VALUE_BOOL
else:
@@ -2139,11 +2139,11 @@ def GetValue(self, row, col):
# choices should no longer osed to index id
# instead, the format_ids method should be used
# (types.ListType, types.TupleType):
- if type(attrconf.choices) in (OrderedDict, types.DictionaryType):
- if attrconf.choices.values().count(val) > 0:
- ind = attrconf.choices.values().index(val)
+ if type(attrconf.choices) in (OrderedDict, dict):
+ if list(attrconf.choices.values()).count(val) > 0:
+ ind = list(attrconf.choices.values()).index(val)
# print ' return',attrconf.choices.keys()[ind]
- return attrconf.choices.keys()[ind]
+ return list(attrconf.choices.keys())[ind]
else:
return attrconf.get_linktab().format_ids([val])
else:
@@ -2170,11 +2170,11 @@ def GetValue(self, row, col):
elif hasattr(attrconf, 'choices'):
# print ' attrconf.choices',attrconf.choices
- if type(attrconf.choices) in (OrderedDict, types.DictionaryType): # (types.ListType, types.TupleType):
- if attrconf.choices.values().count(val) > 0:
- ind = attrconf.choices.values().index(val)
+ if type(attrconf.choices) in (OrderedDict, dict): # (types.ListType, types.TupleType):
+ if list(attrconf.choices.values()).count(val) > 0:
+ ind = list(attrconf.choices.values()).index(val)
# print ' return',attrconf.choices.keys()[ind]
- return attrconf.choices.keys()[ind]
+ return list(attrconf.choices.keys())[ind]
else:
return val
else:
@@ -2249,9 +2249,9 @@ def SetValue(self, row, col, value):
if hasattr(attrconf, 'choices'):
# print ' type(attrconf.choices)',type(attrconf.choices),type(attrconf.choices) in (OrderedDict, types.DictionaryType)
# (types.ListType, types.TupleType):
- if type(attrconf.choices) in (OrderedDict, types.DictionaryType):
+ if type(attrconf.choices) in (OrderedDict, dict):
# print ' set choices[value]',attrconf.choices[value]
- if attrconf.choices.has_key(value):
+ if value in attrconf.choices:
attrconf[id] = attrconf.choices[value]
else:
attrconf[id] = value
@@ -2268,7 +2268,7 @@ def SetValue(self, row, col, value):
attrconf[id] = value
else:
# TODO: for other types, like color or arrays, this must be done beforehand
- print 'WARNING in SetValue: cannot write to this type:', tt
+ print('WARNING in SetValue: cannot write to this type:', tt)
else:
# readonly
pass
@@ -2692,7 +2692,7 @@ def on_export_csv(self, event):
if dlg.ShowModal() == wx.ID_OK:
# This returns a Python list of files that were selected.
path = dlg.GetPath()
- print 'on_export_csv', type(path), path
+ print('on_export_csv', type(path), path)
if type(path) in STRINGTYPES:
self.tab.export_csv(path, sep=',',
attrconfigs=self.GetTable().get_valueconfigs(),
@@ -2914,7 +2914,7 @@ def on_edit_cell_miniframe(self, event):
table = self.GetTable()
id, attrconf = table.get_id_attrconf(event.GetRow(), event.GetCol())
#miniframe=DataMiniFrame( self, table.obj, id =id, attrs = [attr])
- print 'on_edit_cell_miniframe EventObject=', id, attrconf
+ print('on_edit_cell_miniframe EventObject=', id, attrconf)
dlg = ObjPanelDialog(self, table.obj, id, attrconfigs=[attrconf], size=(350, 200),
#style = wxCAPTION | wxSYSTEM_MENU | wxTHICK_FRAME
func_apply=self.func_apply,
@@ -2984,7 +2984,7 @@ def OnLabelLeftDoubleClick(self, evt):
evt.Skip()
def OnRightDown(self, event):
- print "hello", self.GetSelectedRows()
+ print("hello", self.GetSelectedRows())
def apply(self):
"""
@@ -4315,7 +4315,7 @@ def popup_menu(self, event):
event.Skip()
def on_export_excel(self, event):
- print 'on_export_excel'
+ print('on_export_excel')
obj = self.objpanel.get_obj()
#dirpath = self.get_scenario().get_workdirpath()
@@ -4334,7 +4334,7 @@ def on_export_excel(self, event):
return
def on_export_csv(self, event):
- print 'on_export_csv'
+ print('on_export_csv')
obj = self.objpanel.get_obj()
#dirpath = self.get_scenario().get_workdirpath()
@@ -4678,7 +4678,7 @@ def objbrowser(obj, _id=None):
if n_test == 0:
# simple scalar parameters, no table
obj = TestClass()
- print 'obj.ident', obj.ident
+ print('obj.ident', obj.ident)
elif n_test == 1:
obj = TestTableObjMan()
@@ -4699,7 +4699,7 @@ def objbrowser(obj, _id=None):
obj = drawing
elif n_test == -5:
save_obj(drawing, 'test_drawing.obj')
- print '\nreload'+60*'.'
+ print('\nreload'+60*'.')
obj = load_obj('test_drawing.obj')
obj.get_attrsman().print_attrs()
diff --git a/tools/contributed/sumopy/agilepy/lib_wx/ogleditor.py b/tools/contributed/sumopy/agilepy/lib_wx/ogleditor.py
index a40eb938d0e0..33e0fe9e694a 100644
--- a/tools/contributed/sumopy/agilepy/lib_wx/ogleditor.py
+++ b/tools/contributed/sumopy/agilepy/lib_wx/ogleditor.py
@@ -21,8 +21,8 @@
import types
import os
import sys
-from toolbox import *
-from wxmisc import *
+from .toolbox import *
+from .wxmisc import *
from agilepy.lib_base.geometry import *
import agilepy.lib_base.arrayman as am
import agilepy.lib_base.classman as cm
@@ -44,7 +44,7 @@
use for debugging
python ogleditor.py --debug > debug.txt 2>&1
"""
- print __copyright__
+ print(__copyright__)
###############################################################################
# IMPORTS
@@ -63,7 +63,7 @@
import numpy as np
except ImportError:
- raise ImportError, "Required dependencies numpy or OpenGL not present"
+ raise ImportError("Required dependencies numpy or OpenGL not present")
if __name__ == '__main__':
try:
@@ -447,7 +447,7 @@ def pick_all(self, event):
# calculate detectwidth based on current resolution
self.detectwidth = self._canvas.get_resolution()*self.detectpix
- print 'pick_all', self.detectwidth, self.detectpix, self._canvas.get_resolution()
+ print('pick_all', self.detectwidth, self.detectpix, self._canvas.get_resolution())
self._idcounter = 0
is_draw = False
@@ -1420,7 +1420,7 @@ def on_execute_selection(self, event):
"""
Definively execute operation on currently selected drawobjects.
"""
- print 'Stretch', self.is_tool_allowed_on_selection()
+ print('Stretch', self.is_tool_allowed_on_selection())
if self.is_tool_allowed_on_selection():
if not self.is_animated:
return self.begin_animation(event)
@@ -1792,7 +1792,7 @@ def get_vbo(self, ident):
return self._vbos[ident]
def get_vbos(self):
- return self._vbos.values()
+ return list(self._vbos.values())
def del_vbo(self, key):
del self._vbos[key]
@@ -2649,7 +2649,7 @@ def __init__(self, ident, parent, name='Fancy lines',
if is_fill:
self.add_vbo(Vbo('line_fill', GL_QUADS, 4, objtype='fill'))
- for style in LINEHEADS.keys():
+ for style in list(LINEHEADS.keys()):
self.add_vbo(Vbo(('begin', 'fill', style), GL_TRIANGLES, 3, objtype='fill'))
self.add_vbo(Vbo(('end', 'fill', style), GL_TRIANGLES, 3, objtype='fill'))
@@ -2826,7 +2826,7 @@ def _update_vertexvbo(self):
# print ' x1_new=',x1_new,x1_new.dtype
# print ' x2_new=',x2_new,x2_new.dtype
if self._is_fill.value:
- for style, id_style in LINEHEADS.iteritems():
+ for style, id_style in LINEHEADS.items():
# begin
inds_style = np.flatnonzero(self.beginstyles.value == id_style)
@@ -3235,7 +3235,7 @@ def _make_lines(self):
# print ' polyline\n',polyline
if n_seg > 1:
- polyvinds = range(n_seg)
+ polyvinds = list(range(n_seg))
# print ' polyvinds\n',polyvinds
vi = np.zeros((2*n_seg-2), np.int32)
vi[0] = polyvinds[0]
@@ -3251,7 +3251,7 @@ def _make_lines(self):
n_lines = len(v)/2
# print ' v\n',v
- inds_polyline = range(ind_line, ind_line+n_lines)
+ inds_polyline = list(range(ind_line, ind_line+n_lines))
polyinds[inds_polyline] = ind
@@ -3308,7 +3308,7 @@ def _update_vertexvbo(self):
# print ' x1_new=',x1_new,x1_new.dtype
# print ' x2_new=',x2_new,x2_new.dtype
if self._is_fill.value:
- for style, id_style in LINEHEADS.iteritems():
+ for style, id_style in LINEHEADS.items():
# begin
inds_style = np.flatnonzero(self._linebeginstyles == id_style)
@@ -3874,7 +3874,7 @@ def _make_lines(self):
# print ' ======='
# print ' polyline\n',polyline
- polyvinds = range(len(polyline))
+ polyvinds = list(range(len(polyline)))
# print ' polyvinds\n',polyvinds
vi = np.zeros((2*len(polyline)), np.int32)
vi[0] = polyvinds[0]
@@ -3893,7 +3893,7 @@ def _make_lines(self):
vi[1:-1] = np.repeat(polyvinds[1:], 2)
n_lines = len(v)/2
# print ' v\n',v
- inds_polyline = range(ind_line, ind_line+n_lines)
+ inds_polyline = list(range(ind_line, ind_line+n_lines))
polyinds[inds_polyline] = ind
linevertices[inds_polyline] = v.reshape((-1, 2, 3))
@@ -4274,7 +4274,7 @@ def showhide_drawobjs(self, event):
event.Skip()
def on_test(self, event=None):
- print 'this is a test'
+ print('this is a test')
class OGLcanvas(glcanvas.GLCanvas):
@@ -4523,7 +4523,7 @@ def draw(self, *args, **kwargs):
self.OnDraw(*args, **kwargs)
# print 'draw',self.lastx,self.lasty,self.x,self.y
except:
- print 'WARNING in draw: unable to set context'
+ print('WARNING in draw: unable to set context')
def set_drawing(self, drawing):
if self._drawing != drawing:
@@ -4884,7 +4884,7 @@ def __init__(self, parent,
#wx.EVT_SIZE(self, self.on_size)
def on_test(self, event=None, drawing=None):
- print '\non_test'
+ print('\non_test')
if drawing is None:
drawing = OGLdrawing()
@@ -5016,7 +5016,7 @@ def on_test(self, event=None, drawing=None):
[[0.0, -2.0, 0.0], [-2.0, -2.0, 0.0], [-2.0, 0.0, 0.0]], # 1 red
]
- print ' vertices_polygon\n', vertices_poly
+ print(' vertices_polygon\n', vertices_poly)
polygons.add_drawobjs(vertices_poly,
colors_poly)
polygons.add_drawobj([[5.0, -2.0, 0.0], [3.0, -2.0, 0.0], [3.0, 0.0, 0.0]],
@@ -5135,7 +5135,7 @@ def get_mainframe(self):
###############################################################################
# MAIN FRAME
- from mainframe import AgileToolbarFrameMixin
+ from .mainframe import AgileToolbarFrameMixin
class OGLeditorMainframe(AgileToolbarFrameMixin, wx.Frame):
"""
@@ -5169,7 +5169,7 @@ def make_menu(self, event=None):
# shortkey='Ctrl+t',info='Draw test objects')
def on_test(self, event=None):
- print '\non_test'
+ print('\non_test')
vertices = np.array([
[[0.0, 0.0, 0.0], [0.2, 0.0, 0.0]], # 0 green
[[0.0, 0.0, 0.0], [0.0, 0.9, 0.0]], # 1 red
@@ -5309,7 +5309,7 @@ def on_test(self, event=None):
[[0.0, -2.0, 0.0], [-2.0, -2.0, 0.0], [-2.0, 0.0, 0.0]], # 1 red
]
- print ' vertices_polygon\n', vertices_poly
+ print(' vertices_polygon\n', vertices_poly)
polygons.add_drawobjs(vertices_poly,
colors_poly)
polygons.add_drawobj([[5.0, -2.0, 0.0], [3.0, -2.0, 0.0], [3.0, 0.0, 0.0]],
diff --git a/tools/contributed/sumopy/agilepy/lib_wx/processdialog.py b/tools/contributed/sumopy/agilepy/lib_wx/processdialog.py
index 4744cc74c58c..5d8a7a135c2d 100644
--- a/tools/contributed/sumopy/agilepy/lib_wx/processdialog.py
+++ b/tools/contributed/sumopy/agilepy/lib_wx/processdialog.py
@@ -19,8 +19,8 @@
import wx
import os
-import objpanel
-from wxmisc import AgileStatusbar
+from . import objpanel
+from .wxmisc import AgileStatusbar
class ProcessDialogMixin:
@@ -392,7 +392,7 @@ def on_step(self, event=None):
# print 'call step'
self.process.step()
else:
- print ' Simulation finished'
+ print(' Simulation finished')
self.timer.Stop()
def on_stop(self, event=None):
@@ -451,7 +451,7 @@ def show_progress(self, percent, **kwargs):
# self.Update()
def write_message(self, text, **kwargs):
- print 'write_message', text
+ print('write_message', text)
self.statusbar.write_message(text)
def make_browser(self):
diff --git a/tools/contributed/sumopy/agilepy/lib_wx/test_app.py b/tools/contributed/sumopy/agilepy/lib_wx/test_app.py
index 4b724c2545d6..0f67a53597fb 100644
--- a/tools/contributed/sumopy/agilepy/lib_wx/test_app.py
+++ b/tools/contributed/sumopy/agilepy/lib_wx/test_app.py
@@ -16,8 +16,8 @@
# @author Joerg Schweizer
# @date 2012
-from ogleditor import *
-from mainframe import *
+from .ogleditor import *
+from .mainframe import *
import os
import sys
@@ -31,11 +31,11 @@
except:
APPDIR = os.path.dirname(os.path.abspath(sys.argv[0]))
AGILEDIR = os.path.join(APPDIR, '..')
- print 'APPDIR,AGILEDIR', APPDIR, AGILEDIR
+ print('APPDIR,AGILEDIR', APPDIR, AGILEDIR)
sys.path.append(AGILEDIR)
libpaths = [AGILEDIR, os.path.join(AGILEDIR, "lib_base"), os.path.join(AGILEDIR, "lib_wx"), ]
for libpath in libpaths:
- print ' libpath=', libpath
+ print(' libpath=', libpath)
lp = os.path.abspath(libpath)
if not lp in sys.path:
# print ' append',lp
@@ -108,15 +108,15 @@ def make_menu(self):
shortkey='Ctrl+s', info='save it out')
def on_save(self, event):
- print 'save it!!'
+ print('save it!!')
def on_open(self, event):
"""Open a document"""
#wildcards = CreateWildCards() + "All files (*.*)|*.*"
- print 'open it!!'
+ print('open it!!')
def on_test(self, event=None):
- print '\non_test'
+ print('\non_test')
vertices = np.array([
[[0.0, 0.0, 0.0], [0.2, 0.0, 0.0]], # 0 green
[[0.0, 0.0, 0.0], [0.0, 0.9, 0.0]], # 1 red
@@ -202,7 +202,7 @@ def on_test(self, event=None):
[[0.0, -2.0, 0.0], [-2.0, -2.0, 0.0], [-2.0, 0.0, 0.0]], # 1 red
], np.object)
- print ' vertices_polygon\n', vertices_poly
+ print(' vertices_polygon\n', vertices_poly)
polygons.add_drawobjs(vertices_poly,
colors_poly)
drawing.add_drawobj(polygons)
diff --git a/tools/contributed/sumopy/agilepy/lib_wx/test_glcanvas.py b/tools/contributed/sumopy/agilepy/lib_wx/test_glcanvas.py
index 2db3af0743f5..c853fa6bf7f2 100644
--- a/tools/contributed/sumopy/agilepy/lib_wx/test_glcanvas.py
+++ b/tools/contributed/sumopy/agilepy/lib_wx/test_glcanvas.py
@@ -25,9 +25,9 @@
#import wxversion
# wxversion.select('2.8')
-import wxmisc
-import objpanel
-from wxmisc import *
+from . import wxmisc
+from . import objpanel
+from .wxmisc import *
import classman as cm
import math
import wx
@@ -45,7 +45,7 @@
import numpy as np
except ImportError:
- raise ImportError, "Required dependency OpenGL not present"
+ raise ImportError("Required dependency OpenGL not present")
import sys
import os
@@ -280,7 +280,7 @@ def set_handles(self):
Set handles to selected object sets which can be connected.
"""
# put handles on all section objects
- for name_set in self.targetsets.keys():
+ for name_set in list(self.targetsets.keys()):
self.metacanvas.set_handles(name_set=name_set)
def get_bitmap_from_file(self, name_bitmap):
@@ -309,8 +309,8 @@ def set_options(self, event):
"""
Called from options panel.
"""
- print 'set_options', self.ident
- print ' event=', event
+ print('set_options', self.ident)
+ print(' event=', event)
pass
def set_statusbar(self, key, info):
@@ -482,7 +482,7 @@ def get_tools(self):
Returns lins with all toll instances
"""
tools = []
- for (tool, b) in self._id_to_tool.values():
+ for (tool, b) in list(self._id_to_tool.values()):
tools.append(tool)
return tools
@@ -496,12 +496,12 @@ def refresh(self):
def on_select(self, event):
_id = event.GetEventObject().GetId()
- print '\n on_select', _id, self._id # ,self._id_to_tool[_id]
+ print('\n on_select', _id, self._id) # ,self._id_to_tool[_id]
if _id != self._id:
- if self._id_to_tool.has_key(_id):
+ if _id in self._id_to_tool:
(tool, button) = self._id_to_tool[_id]
- print ' new tool', tool.get_name()
+ print(' new tool', tool.get_name())
self.unselect()
self._id = _id
self.GetParent().set_options(tool)
@@ -512,7 +512,7 @@ def unselect(self):
"""
Unselect currently selected tool.
"""
- if self._id_to_tool.has_key(self._id):
+ if self._id in self._id_to_tool:
(tool, button) = self._id_to_tool[self._id]
if hasattr(button, 'SetToggle'):
button.SetToggle(False)
@@ -525,10 +525,10 @@ def select(self, id):
"""
Select explicitelt a tool.
"""
- print '\n select', id, self._id, self._id_to_tool
+ print('\n select', id, self._id, self._id_to_tool)
if id != self._id:
- if self._id_to_tool.has_key(id):
+ if id in self._id_to_tool:
# unselect previous
self.unselect()
@@ -740,7 +740,7 @@ def OnDraw(self, event):
y = radius*math.cos(0)
glColor(0.0, 1.0, 0.0)
glBegin(GL_LINE_STRIP)
- for deg in xrange(1000):
+ for deg in range(1000):
glVertex(x, y, 0.0)
rad = math.radians(deg)
radius -= 0.001
@@ -757,7 +757,7 @@ def OnDraw(self, event):
x = radius*math.sin(0)
y = radius*math.cos(0)
glColor(1.0, 0.0, 0.0)
- for deg in xrange(820):
+ for deg in range(820):
spiral_array.append([x, y])
rad = math.radians(deg)
radius -= 0.001
@@ -805,7 +805,7 @@ def OnMouseMotion(self, event):
y = event.GetY()
def OnDestroy(self, event):
- print "Destroying Window"
+ print("Destroying Window")
class Lines:
@@ -982,7 +982,7 @@ def __init__(self, parent, id=-1, title='', pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE,
name='frame', mainframe=None):
- print '\n\nGLFrame!!'
+ print('\n\nGLFrame!!')
if mainframe is None:
self._mainframe = parent
else:
@@ -1622,7 +1622,7 @@ def OnSashChanged(self, evt):
pass
def OnSashChanging(self, evt):
- print("sash changing to %s\n" % str(evt.GetSashPosition()))
+ print(("sash changing to %s\n" % str(evt.GetSashPosition())))
# uncomment this to not allow the change
# evt.SetSashPosition(-1)
# evt.SetSashPosition(210)
@@ -1893,7 +1893,7 @@ def add_view(self, name, ViewClass, **args):
return view
def on_size(self, event=None):
- print 'Mainframe.on_size'
+ print('Mainframe.on_size')
# self.tc.SetSize(self.GetSize())
# self.tc.SetSize(self.GetSize())
# self._viewtabs.SetSize(self.GetSize())
@@ -1908,12 +1908,12 @@ def on_size(self, event=None):
event.Skip()
def on_save(self, event):
- print 'save it!!'
+ print('save it!!')
def on_open(self, event):
"""Open a document"""
#wildcards = CreateWildCards() + "All files (*.*)|*.*"
- print 'open it!!'
+ print('open it!!')
def destroy(self):
"""Destroy this object"""
diff --git a/tools/contributed/sumopy/agilepy/lib_wx/test_notebook.py b/tools/contributed/sumopy/agilepy/lib_wx/test_notebook.py
index b47cdfd40654..c66bd2f64c3a 100644
--- a/tools/contributed/sumopy/agilepy/lib_wx/test_notebook.py
+++ b/tools/contributed/sumopy/agilepy/lib_wx/test_notebook.py
@@ -111,14 +111,14 @@ def OnPageChanged(self, event):
old = event.GetOldSelection()
new = event.GetSelection()
sel = self.GetSelection()
- print 'OnPageChanged, old:%d, new:%d, sel:%d\n' % (old, new, sel)
+ print('OnPageChanged, old:%d, new:%d, sel:%d\n' % (old, new, sel))
event.Skip()
def OnPageChanging(self, event):
old = event.GetOldSelection()
new = event.GetSelection()
sel = self.GetSelection()
- print 'OnPageChanging, old:%d, new:%d, sel:%d\n' % (old, new, sel)
+ print('OnPageChanging, old:%d, new:%d, sel:%d\n' % (old, new, sel))
event.Skip()
diff --git a/tools/contributed/sumopy/agilepy/lib_wx/toolbox.py b/tools/contributed/sumopy/agilepy/lib_wx/toolbox.py
index 418ca75ba9ef..d63430320130 100644
--- a/tools/contributed/sumopy/agilepy/lib_wx/toolbox.py
+++ b/tools/contributed/sumopy/agilepy/lib_wx/toolbox.py
@@ -18,7 +18,7 @@
import agilepy.lib_base.arrayman as am
import agilepy.lib_base.classman as cm
-from objpanel import ObjPanel, NaviPanel
+from .objpanel import ObjPanel, NaviPanel
from wx.lib.buttons import GenBitmapTextButton, GenBitmapButton
import wx
import sys
@@ -260,14 +260,14 @@ def __init__(self, parent, tools=[], callback=None, n_buttoncolumns=3):
# self.SetMaxSize((300,-1))
def has_tool(self, newtool):
- for tool, b in self._id_to_tool.values():
+ for tool, b in list(self._id_to_tool.values()):
if tool.get_ident() == newtool.get_ident():
return True
return False
def get_tool_by_ident(self, ident):
# print 'get_tool_by_ident',ident
- for tool, b in self._id_to_tool.values():
+ for tool, b in list(self._id_to_tool.values()):
# print ' tool',tool.get_ident()
if tool.get_ident() == ident:
return tool
@@ -303,7 +303,7 @@ def get_tools(self):
Returns lins with all toll instances
"""
tools = []
- for (tool, b) in self._id_to_tool.values():
+ for (tool, b) in list(self._id_to_tool.values()):
tools.append(tool)
return tools
@@ -322,7 +322,7 @@ def on_select(self, event):
# print '\n on_select',_id,self._id#,self._id_to_tool[_id]
if _id != self._id:
- if self._id_to_tool.has_key(_id):
+ if _id in self._id_to_tool:
(tool, button) = self._id_to_tool[_id]
# print ' new tool',tool.get_name()
@@ -346,7 +346,7 @@ def select(self, _id):
# print '\nselect',_id,self._id,self._id_to_tool
if _id != self._id:
- if self._id_to_tool.has_key(_id):
+ if _id in self._id_to_tool:
(tool, button) = self._id_to_tool[_id]
@@ -373,7 +373,7 @@ def unselect(self):
"""
Unselect currently selected tool.
"""
- if self._id_to_tool.has_key(self._id):
+ if self._id in self._id_to_tool:
(tool, button) = self._id_to_tool[self._id]
if tool.is_active() == True:
diff --git a/tools/contributed/sumopy/agilepy/lib_wx/wxmisc.py b/tools/contributed/sumopy/agilepy/lib_wx/wxmisc.py
index d6b67933b7ff..3dade85c3553 100644
--- a/tools/contributed/sumopy/agilepy/lib_wx/wxmisc.py
+++ b/tools/contributed/sumopy/agilepy/lib_wx/wxmisc.py
@@ -18,7 +18,7 @@
import zlib
-import cPickle
+import pickle
import sys
import os
import types
@@ -110,7 +110,7 @@ def add_tool(self, key, func=None, bitmap=None, info='', widget=None, **args):
# print 'add_tool',self,key,func
id = wx.NewId()
- if not args.has_key('name'):
+ if 'name' not in args:
name = string.capitalize(key)
else:
name = args['name']
@@ -140,15 +140,15 @@ def add_tool(self, key, func=None, bitmap=None, info='', widget=None, **args):
return id
def enable_tool(self, key, enable=True):
- if self._tools.has_key(key):
+ if key in self._tools:
# self._tools[key].Show(False)
self.toolbar.EnableTool(self._tools[key], enable)
else:
- print 'enable_tool: no tool named:', key
+ print('enable_tool: no tool named:', key)
def del_tool(self, key):
- if self._tools.has_key(key):
+ if key in self._tools:
# self._tools[key].Show(False)
self.toolbar.RemoveTool(self._tools[key])
del self._tools[key]
@@ -157,7 +157,7 @@ def del_tool(self, key):
# causes it to render (more or less, that is).
self.toolbar.Realize()
else:
- print 'del_tool: no tool named:', key
+ print('del_tool: no tool named:', key)
class AgileToolbarFrameMixin(AgileToolbarMixin):
@@ -209,7 +209,7 @@ def get_menu(self, path):
# print 'get_menu',path
for key in path:
# print ' ',key,items
- if items.has_key(key):
+ if key in items:
val = items[key]
# print val
if len(val) == 3:
@@ -217,7 +217,7 @@ def get_menu(self, path):
else:
return None, None, -1
else:
- print 'WARNING in get_menu: invalid menu key', key, 'in path'
+ print('WARNING in get_menu: invalid menu key', key, 'in path')
return None, None, -1
return val[0], val[1], val[2]
@@ -279,7 +279,7 @@ def _create_menu(self, parentmenu, key, menu=None, **args):
# overwrite with args
data.update(args)
- if not data.has_key('name'):
+ if 'name' not in data:
data['name'] = string.capitalize(key)
if data['alt']:
@@ -332,7 +332,7 @@ def append_item(self, path, function, **args):
# append item
# print ' menu',menu,type(menu),dir(menu)
menu.AppendItem(item)
- if args.has_key('check'):
+ if 'check' in args:
menu.Check(item.GetId(), args['check'])
# if (args.has_key('check'))&(args.has_key('checked')):
# menu.Check(item.GetId(), args['checked'])
@@ -340,7 +340,7 @@ def append_item(self, path, function, **args):
menu_dict[key] = (item, id)
return item, id
else:
- print 'WARNING: in append_item: invalid menu path', menupath
+ print('WARNING: in append_item: invalid menu path', menupath)
return None, None
def _create_item(self, key, menu, function=None, **args):
@@ -353,10 +353,10 @@ def _create_item(self, key, menu, function=None, **args):
# overwrite with args
data.update(args)
- if not data.has_key('name'):
+ if 'name' not in data:
data['name'] = string.capitalize(key)
- if not data.has_key('info'):
+ if 'info' not in data:
if function.__doc__ is not None:
data['info'] = function.__doc__.replace('\n', ' ').strip()
else:
@@ -374,12 +374,12 @@ def _create_item(self, key, menu, function=None, **args):
if data['shortkey'] != '':
itemtext += '\t'+data['shortkey']
- if data.has_key('radio'):
+ if 'radio' in data:
item = wx.MenuItem(menu, id, itemtext, data['info'], wx.ITEM_RADIO)
# print ' radio item'
- elif data.has_key('check'):
+ elif 'check' in data:
item = wx.MenuItem(menu, id, itemtext, data['info'], wx.ITEM_CHECK)
# check boxes AFTER append
@@ -387,7 +387,7 @@ def _create_item(self, key, menu, function=None, **args):
item = wx.MenuItem(menu, id, itemtext, data['info'], wx.ITEM_NORMAL)
# print ' normal item'
- if data.has_key('bitmap'):
+ if 'bitmap' in data:
# print '_create_item bitmap',data['bitmap']
# TODO: allow more image formats in menuitem
# item.SetBitmap(images.getSmilesBitmap())
@@ -406,7 +406,7 @@ def del_item(self, path):
menu, menu_dict, menuid = self.get_menu(menupath)
if menu:
- if menu_dict.has_key(key):
+ if key in menu_dict:
menu.RemoveItem(menu_dict[key][0])
# menu_dict[key][0].Remove()
del menu_dict[key]
@@ -429,9 +429,9 @@ def del_menu(self, path):
def __setitem__(self, menupath, **data):
# print 'set menue',menupath,'to',data
- if type(name) != types.TupleType:
+ if type(name) != tuple:
# create main menue entry, if necessary
- if not self.menus.has_key(name):
+ if name not in self.menus:
newmenue = wx.Menu()
self.Append(newmenue, '&'+name)
self.menus[name] = (-1, {})
@@ -439,14 +439,14 @@ def __setitem__(self, menupath, **data):
elif len(name) == 2:
# create submenu entry, if necessary
name1, name2 = name
- if not self.menus.has_key(name1):
+ if name1 not in self.menus:
newmenue = wx.Menu()
self.Append(newmenue, '&'+name1)
self.menus[name] = (-1, {})
menuid, submenus = self.menus[name1]
- if not submenus.has_key(name2):
+ if name2 not in submenus:
id = wx.NewId()
get_menu_item()
newmenue = wx.Menu()
@@ -456,7 +456,7 @@ def __setitem__(self, menupath, **data):
submenu = self.menus
parentmenu = None
for m in menu:
- if not submenu.has_key(m):
+ if m not in submenu:
newmenue = wx.Menu()
def get_menu_item(self, id):
@@ -657,7 +657,7 @@ def on_key_up(self, event):
"""
# print 'on_key_up'
self.del_keypress()
- print ' key_pressed', self.key_pressed
+ print(' key_pressed', self.key_pressed)
def del_keypress(self):
"""
@@ -831,7 +831,7 @@ def __setitem__(self, key, message):
self.Update()
def has_key(self, key):
- return self._ind_fields.has_key(key)
+ return key in self._ind_fields
def OnSize(self, evt):
self.Reposition() # for normal size events
@@ -872,7 +872,7 @@ def get_bitmap(name, size=22):
try:
return imgImages.catalog[name].getBitmap()
except:
- print 'WARNING in get_bitmap: failed to return image', name
+ print('WARNING in get_bitmap: failed to return image', name)
return wx.NullBitmap
@@ -880,7 +880,7 @@ def get_bitmap(name, size=22):
def GetHandData():
- return cPickle.loads(zlib.decompress(
+ return pickle.loads(zlib.decompress(
'x\xda\xd3\xc8)0\xe4\nV72T\x00!\x05Cu\xae\xc4`u=\x85d\x05\xa7\x9c\xc4\xe4l0O\
\x01\xc8S\xb6t\x06A(\x1f\x0b\xa0\xa9\x8c\x9e\x1e6\x19\xa0\xa8\x1e\x88\xd4C\
\x97\xd1\x83\xe8\x80 \x9c2zh\xa6\xc1\x11X\n\xab\x8c\x02\x8a\x0cD!\x92\x12\
@@ -895,7 +895,7 @@ def GetHandBitmap():
def GetPlusData():
- return cPickle.loads(zlib.decompress(
+ return pickle.loads(zlib.decompress(
'x\xda\xd3\xc8)0\xe4\nV72T\x00!\x05Cu\xae\xc4`u=\x85d\x05\xa7\x9c\xc4\xe4l0O\
\x01\xc8S\xb6t\x06A(\x1f\x0b RF\x0f\x08\xb0\xc9@D\xe1r\x08\x19\xb8j=l2`\r\
\xe82HF\xe9a\xc8\xe8\xe9A\x9c@\x8a\x0c\x0e\xd3p\xbb\x00\x8f\xab\xe1>\xd5\xd3\
@@ -910,7 +910,7 @@ def GetPlusBitmap():
def GetMinusData():
- return cPickle.loads(zlib.decompress(
+ return pickle.loads(zlib.decompress(
'x\xda\xd3\xc8)0\xe4\nV72T\x00!\x05Cu\xae\xc4`u=\x85d\x05\xa7\x9c\xc4\xe4l0O\
\x01\xc8S\xb6t\x06A(\x1f\x0b RF\x0f\x08\xb0\xc9@D\xe1r\x08\x19\xb8j=\xa2e\
\x10\x16@\x99\xc82zz\x10\'\x90"\x83\xc34r\xdc\x86\xf0\xa9\x9e\x1e\xae\xd0\
diff --git a/tools/contributed/sumopy/coremodules/demand/__init__.py b/tools/contributed/sumopy/coremodules/demand/__init__.py
index cab987aa8f9c..02fdf630fcec 100644
--- a/tools/contributed/sumopy/coremodules/demand/__init__.py
+++ b/tools/contributed/sumopy/coremodules/demand/__init__.py
@@ -18,12 +18,12 @@
__version__ = "0.0"
-print 'init', __name__
+print('init', __name__)
def get_wxgui():
# try:
- from wxgui import WxGui
+ from .wxgui import WxGui
return WxGui(__name__)
# except:
# return None
diff --git a/tools/contributed/sumopy/coremodules/demand/demand.py b/tools/contributed/sumopy/coremodules/demand/demand.py
index b9c9c0101d5f..e73e1799a3eb 100644
--- a/tools/contributed/sumopy/coremodules/demand/demand.py
+++ b/tools/contributed/sumopy/coremodules/demand/demand.py
@@ -16,14 +16,14 @@
# @author Joerg Schweizer
# @date 2012
-import detectorflows
-import turnflows
-import virtualpop
-import origin_to_destination
-import vehicles
+from . import detectorflows
+from . import turnflows
+from . import virtualpop
+from . import origin_to_destination
+from . import vehicles
from coremodules.network.network import SumoIdsConf, MODES
-from demandbase import *
-import publictransportservices as pt
+from .demandbase import *
+from . import publictransportservices as pt
from coremodules.simulation import results as res
from coremodules.network import routing
from agilepy.lib_base.processes import Process
@@ -69,7 +69,7 @@
class Demand(cm.BaseObjman):
def __init__(self, scenario=None, net=None, zones=None, name='Demand', info='Transport demand', **kwargs):
- print 'Demand.__init__', name, kwargs
+ print('Demand.__init__', name, kwargs)
# we need a network from somewhere
if net is None:
@@ -98,7 +98,7 @@ def _init_attributes(self):
attrsman = self.get_attrsman()
scenario = self.parent
- print 'Demand._init_attributes', scenario
+ print('Demand._init_attributes', scenario)
if scenario is not None:
self.detectorflows = attrsman.add(cm.ObjConf(detectorflows.Detectorflows('detectorflows', self),
@@ -189,11 +189,11 @@ def get_demandobjects(self):
# for ident, conf in self.get_group_attrs('').iteritems():
# demandobjects.add(conf.get_value())
demandobjects_clean = []
- for attrname, demandobject in self.get_attrsman().get_group_attrs('demand objects').iteritems():
+ for attrname, demandobject in self.get_attrsman().get_group_attrs('demand objects').items():
if demandobject is not None:
demandobjects_clean.append(demandobject)
else:
- print 'WARNING in get_demandobjects: found None as object', attrname
+ print('WARNING in get_demandobjects: found None as object', attrname)
self.get_attrsman().delete(attrname)
return demandobjects_clean
@@ -226,15 +226,15 @@ def import_routes_xml(self, filepath=None, demandobjects=None,
if filepath is None:
filepath = self.get_routefilepath()
- print 'import_routes_xml', filepath, demandobjects
+ print('import_routes_xml', filepath, demandobjects)
try:
fd = open(filepath, 'r')
except:
- print 'WARNING in import_routes_xml: could not open', filepath
+ print('WARNING in import_routes_xml: could not open', filepath)
return False
for demandobj in demandobjects:
- print ' try to import routes from demandobj', demandobj
+ print(' try to import routes from demandobj', demandobj)
demandobj.import_routes_xml(filepath,
is_clear_trips=is_clear_trips,
is_generate_ids=is_generate_ids,
@@ -259,11 +259,11 @@ def export_routes_xml(self, filepath=None, encoding='UTF-8',
if filepath is None:
filepath = self.get_routefilepath()
- print 'export_routes_xml', filepath, demandobjects
+ print('export_routes_xml', filepath, demandobjects)
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in export_routes_xml: could not open', filepath
+ print('WARNING in export_routes_xml: could not open', filepath)
return False
fd.write('\n' % encoding)
@@ -277,11 +277,11 @@ def export_routes_xml(self, filepath=None, encoding='UTF-8',
ids_vtype = set()
for exportobj in demandobjects:
- print ' exportobj', exportobj
+ print(' exportobj', exportobj)
times, funcs, ids = exportobj.get_writexmlinfo(is_route=is_route,
is_plain=is_plain,
is_exclude_pedestrians=is_exclude_pedestrians)
- print ' n_trips', len(times), 'has vtypes', hasattr(exportobj, 'get_vtypes')
+ print(' n_trips', len(times), 'has vtypes', hasattr(exportobj, 'get_vtypes'))
if len(times) > 0:
times_begin = np.concatenate((times_begin, times), 0)
writefuncs = np.concatenate((writefuncs, funcs), 0)
@@ -630,7 +630,7 @@ def duaroute(self, is_export_net=False, is_export_trips=True,
"""
Simple fastest path routing using duarouter.
"""
- print 'duaroute'
+ print('duaroute')
exectime_start = time.clock()
#routesattrname = self.get_routesattrname(routesindex)
@@ -661,7 +661,7 @@ def duaroute(self, is_export_net=False, is_export_trips=True,
is_overwrite_only=True,
is_add=False)
- print ' exectime', time.clock()-exectime_start
+ print(' exectime', time.clock()-exectime_start)
return routefilepath
else:
@@ -677,7 +677,7 @@ def route(self, is_check_lanes=True, is_del_disconnected=False, is_set_current=F
"""
Fastest path python router.
"""
- print 'route is_check_lanes', is_check_lanes
+ print('route is_check_lanes', is_check_lanes)
# TODO: if too mant vtypes, better go through id_modes
exectime_start = time.clock()
@@ -697,7 +697,7 @@ def route(self, is_check_lanes=True, is_del_disconnected=False, is_set_current=F
# no routing for pedestrians
if id_mode != net.modes.get_id_mode('pedestrian'):
ids_trip_vtype = self.get_trips_for_vtype(id_vtype)
- print ' id_vtype, id_mode', id_vtype, id_mode # ,ids_trip_vtype
+ print(' id_vtype, id_mode', id_vtype, id_mode) # ,ids_trip_vtype
weights = edges.get_times(id_mode=id_mode,
speed_max=vtypes.speeds_max[id_vtype],
@@ -741,7 +741,7 @@ def route(self, is_check_lanes=True, is_del_disconnected=False, is_set_current=F
else:
self.add_routes(ids_trip, ids_route)
- print ' exectime', time.clock()-exectime_start
+ print(' exectime', time.clock()-exectime_start)
if is_del_disconnected:
self.del_rows(ids_trip_disconnected)
@@ -774,7 +774,7 @@ def import_trips_from_scenario(self, scenario2):
"""
Import trips from another scenario.
"""
- print 'import_trips_from_scenario', scenario2.ident
+ print('import_trips_from_scenario', scenario2.ident)
if not is_pyproj:
print("WARNING in import_trips_from_scenario: pyproj module not installed")
return None
@@ -841,7 +841,7 @@ def import_trips_from_scenario(self, scenario2):
proj_params2 = str(net2.get_projparams())
if (proj_params == '!') | (proj_params2 == '!'):
- print 'WARNING in import_trips_from_scenario: unknown projections, use only offsets.', proj_params, proj_params2
+ print('WARNING in import_trips_from_scenario: unknown projections, use only offsets.', proj_params, proj_params2)
is_proj = False
elif proj_params == proj_params2:
@@ -867,16 +867,16 @@ def import_trips_from_scenario(self, scenario2):
for id_mode in ids_modeset:
# make_segment_edge_map for all edges of this mode
- print ' make segment_edge_map for mode', id_mode
+ print(' make segment_edge_map for mode', id_mode)
ids_edge_access, inds_lane_access = edges.select_accessible_mode(id_mode)
- print ' found accessible edges', len(ids_edge_access), len(edges.get_ids())
+ print(' found accessible edges', len(ids_edge_access), len(edges.get_ids()))
# dict(zip(ids_edge,inds_lane))
edges.make_segment_edge_map(ids_edge_access)
# select trips with id_mode
ind_trips = np.flatnonzero(ids_mode == id_mode)
- print ' number of trips for this mode:', len(ind_trips)
+ print(' number of trips for this mode:', len(ind_trips))
for id_trip, id_edge_depart2, id_edge_arrival2 in zip(ids_trips[ind_trips],
demand2.trips.ids_edge_depart[ids_trip2[ind_trips]],
demand2.trips.ids_edge_arrival[ids_trip2[ind_trips]]
@@ -905,7 +905,7 @@ def import_trips_from_scenario(self, scenario2):
# check eucledian distance
#d = edges.get_dist_point_to_edge(coord, id_edge_depart)
# print ' id_edge_depart,d,id_mode',id_edge_depart,d,id_mode
- print ' id_edge_depart', id_edge_depart, id_edge_depart in ids_edge_access
+ print(' id_edge_depart', id_edge_depart, id_edge_depart in ids_edge_access)
ids_edge_depart[id_trip] = id_edge_depart
@@ -931,7 +931,7 @@ def import_trips_from_scenario(self, scenario2):
# check eucledian distance
#d = edges.get_dist_point_to_edge(coord, id_edge_arrival)
- print ' id_edge_arrival', id_edge_arrival, id_edge_arrival in ids_edge_access
+ print(' id_edge_arrival', id_edge_arrival, id_edge_arrival in ids_edge_access)
ids_edge_arrival[id_trip] = id_edge_arrival
@@ -957,7 +957,7 @@ def make_trip(self, is_generate_ids=True, **kwargs):
else:
self.ids_sumo[id_trip] = kwargs.get('id_sumo', str(id_trip)) # id
- if kwargs.has_key('route'):
+ if 'route' in kwargs:
route = kwargs['route']
if len(route) > 0:
id_route = self.routes.get_value().add_row(ids_trip=id_trip,
@@ -969,7 +969,7 @@ def make_trip(self, is_generate_ids=True, **kwargs):
return id_trip
def make_trips(self, ids_vtype, is_generate_ids=True, **kwargs):
- print 'make_trips len(ids_vtype) =', len(ids_vtype)
+ print('make_trips len(ids_vtype) =', len(ids_vtype))
# print ' kwargs=',kwargs
ids_trip = self.add_rows(n=len(ids_vtype),
ids_vtype=ids_vtype,
@@ -1002,28 +1002,28 @@ def make_routes(self, ids_vtype, is_generate_ids=True, routes=None, ids_trip=Non
is_generate_ids: depricated, fully controlled by ids_trip
"""
- print 'make_routes is_generate_ids', ids_trip is None, 'is_add', is_add
+ print('make_routes is_generate_ids', ids_trip is None, 'is_add', is_add)
# print ' ids_trip',ids_trip
if ids_trip is None: # is_generate_ids = is_generate_ids,
- print ' generate new trip IDs'
+ print(' generate new trip IDs')
ids_trip = self.make_trips(ids_vtype, is_generate_ids=is_generate_ids, **kwargs)
is_generate_ids = True
else:
if not is_add:
- print ' replace current route and create if not existent'
+ print(' replace current route and create if not existent')
ids_routes = self.ids_route_current[ids_trip]
inds_new = np.flatnonzero(ids_routes == -1)
# print ' inds_new',inds_new
if len(inds_new) > 0:
- print ' complete %d non pre-existant route ids of %d trips' % (len(inds_new), len(ids_trip))
+ print(' complete %d non pre-existant route ids of %d trips' % (len(inds_new), len(ids_trip)))
# create new routes
ids_routes[inds_new] = self.routes.get_value().add_rows(n=len(inds_new),
ids_trip=ids_trip[inds_new],
#ids_edges = routes[inds_new],
)
else:
- print ' all new routes have pre-existing routes'
+ print(' all new routes have pre-existing routes')
else:
# make new route IDs
ids_routes = self.routes.get_value().add_rows(n=len(ids_trip),
@@ -1032,14 +1032,14 @@ def make_routes(self, ids_vtype, is_generate_ids=True, routes=None, ids_trip=Non
)
is_generate_ids = False
- print ' set new routes to routes database', len(ids_routes), 'routes set'
+ print(' set new routes to routes database', len(ids_routes), 'routes set')
self.routes.get_value().ids_edges[ids_routes] = routes
if not is_add:
- print ' replace current route IDs', len(inds_new), 'routes replaced'
+ print(' replace current route IDs', len(inds_new), 'routes replaced')
self.ids_route_current[ids_trip[inds_new]] = ids_routes[inds_new]
else:
- print ' add new route IDs to alternatives', len(ids_trip), 'routes added'
+ print(' add new route IDs to alternatives', len(ids_trip), 'routes added')
self.add_routes(ids_trip, ids_routes)
# if np.any(ids_routes == -1):
@@ -1047,7 +1047,7 @@ def make_routes(self, ids_vtype, is_generate_ids=True, routes=None, ids_trip=Non
# print ' ids_trip =',ids_trip
if is_generate_ids:
- print ' generate new route IDs'
+ print(' generate new route IDs')
ids_routes = self.routes.get_value().add_rows(n=len(ids_trip),
ids_trip=ids_trip,
#ids_edges = routes,
@@ -1056,10 +1056,10 @@ def make_routes(self, ids_vtype, is_generate_ids=True, routes=None, ids_trip=Non
# print ' ids_routes',ids_routes
if not is_add:
- print ' set new current routes'
+ print(' set new current routes')
self.ids_route_current[ids_trip] = ids_routes
else:
- print ' add new route IDs to alternatives'
+ print(' add new route IDs to alternatives')
self.add_routes(ids_trip, ids_routes)
# no!:self.ids_routes[ids_trip] = ids_routes.reshape((-1,1)).tolist()# this makes an array of lists
@@ -1093,11 +1093,11 @@ def export_trips_xml(self, filepath=None, encoding='UTF-8',
"""
if filepath is None:
filepath = self.get_tripfilepath()
- print 'export_trips_xml', filepath
+ print('export_trips_xml', filepath)
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in write_obj_to_xml: could not open', filepath
+ print('WARNING in write_obj_to_xml: could not open', filepath)
return False
xmltag, xmltag_item, attrname_id = self.xmltag
@@ -1315,7 +1315,7 @@ def get_route_first(self, id_trip):
def import_routes_xml(self, filepath, is_clear_trips=False,
is_generate_ids=True, is_add=False,
is_overwrite_only=False):
- print 'import_routes_xml from %s generate new routes %s, clear trips %s add trips %s' % (filepath, is_generate_ids, is_clear_trips, is_add)
+ print('import_routes_xml from %s generate new routes %s, clear trips %s add trips %s' % (filepath, is_generate_ids, is_clear_trips, is_add))
if is_clear_trips:
self.clear_trips()
@@ -1324,28 +1324,28 @@ def import_routes_xml(self, filepath, is_clear_trips=False,
reader = RouteReader(self, counter)
try:
parse(filepath, reader)
- print ' call insert_routes', is_generate_ids, 'is_add', is_add, 'is_overwrite_only', is_overwrite_only
+ print(' call insert_routes', is_generate_ids, 'is_add', is_add, 'is_overwrite_only', is_overwrite_only)
reader.insert_routes(is_generate_ids=is_generate_ids,
is_add=is_add, is_overwrite_only=is_overwrite_only)
except KeyError:
- print >> sys.stderr, "Error: Problems with reading routes!"
+ print("Error: Problems with reading routes!", file=sys.stderr)
raise
def import_trips_xml(self, filepath, is_clear_trips=False, is_generate_ids=True):
- print 'import_trips_xml from %s generate own trip ' % (filepath)
+ print('import_trips_xml from %s generate own trip ' % (filepath))
if is_clear_trips:
self.clear_trips()
counter = TripCounter()
parse(filepath, counter)
reader = TripReader(self, counter.n_trip)
- print ' n_trip=', counter.n_trip
+ print(' n_trip=', counter.n_trip)
try:
parse(filepath, reader)
reader.insert_trips(is_generate_ids=is_generate_ids)
except KeyError:
- print >> sys.stderr, "Error: Problems with reading trips!"
+ print("Error: Problems with reading trips!", file=sys.stderr)
raise
def config_results(self, results):
@@ -1509,7 +1509,7 @@ def generate_taxi(self):
#id_orig = self.ids_orig[id_od]
#id_dest = self.ids_dest[id_od]
- print ' check id_zone', id_zone
+ print(' check id_zone', id_zone)
ids_edges_orig_raw = zones.ids_edges_orig[id_zone]
#prob_edges_orig_raw = zones.probs_edges_orig[id_orig]
@@ -1519,7 +1519,7 @@ def generate_taxi(self):
#prob_edges_orig = []
#inds_lane_orig = []
- for i in xrange(len(ids_edges_orig_raw)):
+ for i in range(len(ids_edges_orig_raw)):
id_edge = ids_edges_orig_raw[i]
# if check accessibility...
ind_lane_depart_taxi = edges.get_laneindex_allowed(id_edge, id_mode_taxi)
@@ -1534,14 +1534,14 @@ def generate_taxi(self):
n_edges_orig = len(ids_edges_orig)
- print '\n found', n_edges_orig, 'valid zone edges'
+ print('\n found', n_edges_orig, 'valid zone edges')
# now create taxi trips
if (n_edges_orig > 0) & (tripnumber > 0):
# normalize weights
edgeprops = np.zeros(n_edges_orig, dtype=np.float32)
- for i, id_edge in zip(xrange(n_edges_orig), ids_edges_orig):
+ for i, id_edge in zip(range(n_edges_orig), ids_edges_orig):
edgeprops[i] = edgeprops_all[id_edge]
edgeprops = edgeprops/np.sum(edgeprops)
@@ -1549,9 +1549,9 @@ def generate_taxi(self):
# debug
if 0:
for id_edge, prob in zip(ids_edges_orig, edgeprops):
- print ' orig id_edge', id_edge, 'has prob', prob
+ print(' orig id_edge', id_edge, 'has prob', prob)
- for d in xrange(int(tripnumber+0.5)):
+ for d in range(int(tripnumber+0.5)):
# print ' ------------'
# print ' generte trip',d
time_depart = np.random.uniform(time_start, time_end)
@@ -1601,11 +1601,11 @@ def generate_taxi(self):
n_trips_generated += 1
- print ' n_trips_generated', n_trips_generated, 'of', self.n_taxi
+ print(' n_trips_generated', n_trips_generated, 'of', self.n_taxi)
return True
else:
- print ' no taxi created n_edges_orig', n_edges_orig, 'tripnumber', tripnumber
+ print(' no taxi created n_edges_orig', n_edges_orig, 'tripnumber', tripnumber)
return False
def do(self):
diff --git a/tools/contributed/sumopy/coremodules/demand/demandbase.py b/tools/contributed/sumopy/coremodules/demand/demandbase.py
index 86a57316a308..519d646cb7ee 100755
--- a/tools/contributed/sumopy/coremodules/demand/demandbase.py
+++ b/tools/contributed/sumopy/coremodules/demand/demandbase.py
@@ -489,19 +489,19 @@ def startElement(self, name, attrs):
self.ids_vtype[self._ind_trip] = self._get_id_vtype(attrs)
self.times_depart[self._ind_trip] = int(float(attrs['depart']))
- if attrs.has_key('from'):
+ if 'from' in attrs:
self.ids_edge_depart[self._ind_trip] = self._ids_edge_sumo.get_id_from_index(str(attrs['from']))
- if attrs.has_key('to'):
+ if 'to' in attrs:
self.ids_edge_arrival[self._ind_trip] = self._ids_edge_sumo.get_id_from_index(str(attrs['to']))
ind_lane_depart_raw = attrs.get('departLane', 'free')
- if OPTIONMAP_LANE_DEPART.has_key(ind_lane_depart_raw):
+ if ind_lane_depart_raw in OPTIONMAP_LANE_DEPART:
self.inds_lane_depart[self._ind_trip] = OPTIONMAP_LANE_DEPART[ind_lane_depart_raw]
else:
self.inds_lane_depart[self._ind_trip] = int(ind_lane_depart_raw)
positions_depart_raw = attrs.get('departPos', 'base')
- if OPTIONMAP_POS_DEPARTURE.has_key(positions_depart_raw):
+ if positions_depart_raw in OPTIONMAP_POS_DEPARTURE:
self.positions_depart[self._ind_trip] = OPTIONMAP_POS_DEPARTURE[positions_depart_raw]
else:
self.positions_depart[self._ind_trip] = float(positions_depart_raw)
@@ -509,13 +509,13 @@ def startElement(self, name, attrs):
self.speeds_depart[self._ind_trip] = attrs.get('departSpeed', 0.0)
ind_lane_arrival_raw = attrs.get('arrivalLane', 'current')
- if OPTIONMAP_LANE_ARRIVAL.has_key(ind_lane_arrival_raw):
+ if ind_lane_arrival_raw in OPTIONMAP_LANE_ARRIVAL:
self.inds_lane_arrival[self._ind_trip] = OPTIONMAP_LANE_ARRIVAL[ind_lane_arrival_raw]
else:
self.inds_lane_arrival[self._ind_trip] = int(ind_lane_arrival_raw)
positions_arrival_raw = attrs.get('arrivalPos', 'max')
- if OPTIONMAP_POS_ARRIVAL.has_key(positions_arrival_raw):
+ if positions_arrival_raw in OPTIONMAP_POS_ARRIVAL:
self.positions_arrival[self._ind_trip] = OPTIONMAP_POS_ARRIVAL[positions_arrival_raw]
else:
self.positions_arrival[self._ind_trip] = float(positions_arrival_raw)
@@ -626,50 +626,50 @@ def startElement(self, name, attrs):
self.ids_vtype[self._ind_trip] = self.ids_vtype[self._ind_trip] = self._get_id_vtype(attrs)
self.times_depart[self._ind_trip] = int(float(attrs['depart']))
- if attrs.has_key('arrival'):
+ if 'arrival' in attrs:
self.times_arrival[self._ind_trip] = int(float(attrs['arrival']))
else:
# duarouter is not calculating arrival time in results!
self.times_arrival[self._ind_trip] = 0.0
self.type[self._ind_trip] = attrs['type']
- if attrs.has_key('from'):
+ if 'from' in attrs:
self.ids_edge_depart[self._ind_trip] = self._ids_edge_sumo.get_id_from_index(str(attrs['from']))
- if attrs.has_key('to'):
+ if 'to' in attrs:
self.ids_edge_arrival[self._ind_trip] = self._ids_edge_sumo.get_id_from_index(str(attrs['to']))
ind_lane_depart_raw = attrs.get('departLane', 'free')
- if OPTIONMAP_LANE_DEPART.has_key(ind_lane_depart_raw):
+ if ind_lane_depart_raw in OPTIONMAP_LANE_DEPART:
self.inds_lane_depart[self._ind_trip] = OPTIONMAP_LANE_DEPART[ind_lane_depart_raw]
else:
self.inds_lane_depart[self._ind_trip] = int(ind_lane_depart_raw)
positions_depart_raw = attrs.get('departPos', 'base')
- if OPTIONMAP_POS_DEPARTURE.has_key(positions_depart_raw):
+ if positions_depart_raw in OPTIONMAP_POS_DEPARTURE:
self.positions_depart[self._ind_trip] = OPTIONMAP_POS_DEPARTURE[positions_depart_raw]
else:
self.positions_depart[self._ind_trip] = float(positions_depart_raw)
speed_depart_raw = attrs.get('departSpeed', 'max')
- if OPTIONMAP_SPEED_DEPARTURE.has_key(speed_depart_raw):
+ if speed_depart_raw in OPTIONMAP_SPEED_DEPARTURE:
self.speeds_depart[self._ind_trip] = OPTIONMAP_SPEED_DEPARTURE[speed_depart_raw]
else:
self.speeds_depart[self._ind_trip] = float(speed_depart_raw)
ind_lane_arrival_raw = attrs.get('arrivalLane', 'current')
- if OPTIONMAP_LANE_ARRIVAL.has_key(ind_lane_arrival_raw):
+ if ind_lane_arrival_raw in OPTIONMAP_LANE_ARRIVAL:
self.inds_lane_arrival[self._ind_trip] = OPTIONMAP_LANE_ARRIVAL[ind_lane_arrival_raw]
else:
self.inds_lane_arrival[self._ind_trip] = int(ind_lane_arrival_raw)
positions_arrival_raw = attrs.get('arrivalPos', 'max')
- if OPTIONMAP_POS_ARRIVAL.has_key(positions_arrival_raw):
+ if positions_arrival_raw in OPTIONMAP_POS_ARRIVAL:
self.positions_arrival[self._ind_trip] = OPTIONMAP_POS_ARRIVAL[positions_arrival_raw]
else:
self.positions_arrival[self._ind_trip] = float(positions_arrival_raw)
speed_arrival_raw = attrs.get('arrivalSpeed', 'current')
- if OPTIONMAP_SPEED_ARRIVAL.has_key(speed_arrival_raw):
+ if speed_arrival_raw in OPTIONMAP_SPEED_ARRIVAL:
self.speeds_arrival[self._ind_trip] = OPTIONMAP_SPEED_ARRIVAL[speed_arrival_raw]
else:
self.speeds_arrival[self._ind_trip] = float(speed_arrival_raw)
@@ -735,7 +735,7 @@ def _get_kwargs(self, inds=None):
}
def insert_routes(self, is_generate_ids=True, is_add=False, is_overwrite_only=False):
- print 'TripReader.make_routes is_generate_ids', is_generate_ids, 'is_add', is_add, 'is_overwrite_only', is_overwrite_only
+ print('TripReader.make_routes is_generate_ids', is_generate_ids, 'is_add', is_add, 'is_overwrite_only', is_overwrite_only)
# self._trips is scenario trip database
# self.ids_sumo is a list of SUMO IDs read from xml file
diff --git a/tools/contributed/sumopy/coremodules/demand/detectorflows.py b/tools/contributed/sumopy/coremodules/demand/detectorflows.py
index 3c25bfdf383b..f974e9518a72 100644
--- a/tools/contributed/sumopy/coremodules/demand/detectorflows.py
+++ b/tools/contributed/sumopy/coremodules/demand/detectorflows.py
@@ -35,7 +35,7 @@ class Detectorflows(cm.BaseObjman):
def __init__(self, ident='detectorflows', demand=None, name='Detector flows',
info='Flows measured by detectors, which can be used to generate vehicle routes using the DFRouter.',
**kwargs):
- print 'Detectorflows.__init__', name, kwargs
+ print('Detectorflows.__init__', name, kwargs)
self._init_objman(ident=ident,
parent=demand,
@@ -77,7 +77,7 @@ def add_flows_to_edgeresults(self, edgeresults):
# more result attributes can be added ex. heavy duty flows
])
- for attrname, kwargs in attrinfos.iteritems():
+ for attrname, kwargs in attrinfos.items():
edgeresults.add_resultattr(attrname, **kwargs)
# reset Detector flow attributes
@@ -197,7 +197,7 @@ def match_detectors_to_lane(self, modename='passenger',
ids = self.get_ids()
for id_detect, point, phi in zip(ids, self.coords[ids], self.directions[ids]/180.0*np.pi+np.pi/2.0):
- print ' Detector id_detect', id_detect, 'point', point
+ print(' Detector id_detect', id_detect, 'point', point)
ids_edge_target, dists = get_closest_edge(point, n_best=n_targetedge,
d_max=d_max,
is_ending=True,
@@ -206,15 +206,15 @@ def match_detectors_to_lane(self, modename='passenger',
accesslevels=accesslevels
)
- print ' ids_edge_target', ids_edge_target
- print ' dists', dists
+ print(' ids_edge_target', ids_edge_target)
+ print(' dists', dists)
if is_check_direction:
id_edge_found = -1
i = 0
n = len(ids_edge_target)
while (id_edge_found < 0) & (i < n):
- print ' check ids_edge', ids_edge_target[i], dists[i]
+ print(' check ids_edge', ids_edge_target[i], dists[i])
dist_point_edge, segment = get_dist_point_to_edge(point, ids_edge_target[i],
is_ending=True,
is_detect_initial=False,
@@ -235,9 +235,9 @@ def match_detectors_to_lane(self, modename='passenger',
if id_edge_found >= 0:
# select lane
ids_lane = edges.ids_lanes[id_edge_found]
- print ' id_edge_found', id_edge_found, 'ids_lane', edges.ids_lanes[id_edge_found]
+ print(' id_edge_found', id_edge_found, 'ids_lane', edges.ids_lanes[id_edge_found])
ids_lane_access = ids_lane[lanes.get_laneindexes_allowed(ids_lane, id_mode)]
- print ' ids_lane_access', ids_lane_access
+ print(' ids_lane_access', ids_lane_access)
if len(ids_lane_access) > 0:
if is_edgedetectors:
@@ -253,7 +253,7 @@ def write_xml(self, fd=None, indent=0):
#
# ... further detectors ...
#
- print 'Detectors.write_xml'
+ print('Detectors.write_xml')
fd.write(xm.begin('detectors', indent))
ids = self.get_ids()
@@ -265,7 +265,7 @@ def write_xml(self, fd=None, indent=0):
self.positions[ids],
):
- print ' write id_detector', id_detector, 'ids_lane', ids_lane
+ print(' write id_detector', id_detector, 'ids_lane', ids_lane)
if ids_lane is not None:
ind_lane = 0
for id_lane in ids_lane:
@@ -397,7 +397,7 @@ def export_csv(self, filepath, t_offset=0, sep=";"):
f.write('Detector'+sep+'Time'+sep+'qPKW'+sep+'qLKW'+sep+'vPKW'+sep+'vLKW'+'\n')
#ids_flow = self.select_ids(self.flows_passenger.get_value()>=0)
- print ' flows_passenger', self.flows_passenger.get_value()
+ print(' flows_passenger', self.flows_passenger.get_value())
ids_flow = self.get_ids()
for id_detector, t, flow_passenger, flow_heavyduty, speed_passenger, speed_heavyduty in \
zip(
@@ -410,11 +410,11 @@ def export_csv(self, filepath, t_offset=0, sep=";"):
ids_lane = detectors.ids_lanes[id_detector]
if (ids_lane is not None) & (flow_passenger >= 0):
- print ' id_detector', id_detector, 't', t, 'flow_passenger', flow_passenger, len(ids_lane)
+ print(' id_detector', id_detector, 't', t, 'flow_passenger', flow_passenger, len(ids_lane))
n_lane = len(ids_lane)
for ind_lane, passengerflow_lane, heavyflow_lane in\
- zip(xrange(n_lane),
+ zip(range(n_lane),
self.distribute_passengerflow_over_lanes(ids_lane, flow_passenger),
self.distribute_heavyflow_over_lanes(ids_lane, flow_heavyduty)
):
@@ -529,7 +529,7 @@ def import_csv(self, filepath, t_offset=0, t_start=0, t_end=24*3600, sep=";"):
# myDet1;0;10;2;100;80
# ... further entries ...
- print 'import_csv', filepath
+ print('import_csv', filepath)
ind_col = 0
cols = f.readline().strip()
ind_col = 0
@@ -652,14 +652,14 @@ def turnflows_to_routes(self, is_clear_trips=True, is_export_network=True,
scenario.net.export_netxml()
ids_mode = self.get_modes()
- print 'turnflows_to_routes', ids_mode # scenario.net.modes.get_ids()
- print ' cmloptions', cmloptions
+ print('turnflows_to_routes', ids_mode) # scenario.net.modes.get_ids()
+ print(' cmloptions', cmloptions)
# route for all modes and read in routes
for id_mode in ids_mode:
# write flow and turns xml file for this mode
time_start, time_end = self.export_flows_and_turns(flowfilepath, turnfilepath, id_mode)
- print ' time_start, time_end =', time_start, time_end
+ print(' time_start, time_end =', time_start, time_end)
if time_end > time_start: # means there exist some flows for this mode
cmd = 'jtrrouter --route-files=%s --turn-ratio-files=%s --net-file=%s --output-file=%s --begin %s --end %s %s'\
% (P+flowfilepath+P,
@@ -677,7 +677,7 @@ def turnflows_to_routes(self, is_clear_trips=True, is_export_network=True,
os.remove(routefilepath)
else:
- print 'jtrroute: no flows generated for id_mode', id_mode
+ print('jtrroute: no flows generated for id_mode', id_mode)
# self.simfiles.set_modified_data('rou',True)
# self.simfiles.set_modified_data('trip',True)
@@ -686,7 +686,7 @@ def turnflows_to_routes(self, is_clear_trips=True, is_export_network=True,
class DetectorMatcher(Process):
def __init__(self, ident, detectors, logger=None, **kwargs):
- print 'DetectorMatcher.__init__'
+ print('DetectorMatcher.__init__')
# TODO: let this be independent, link to it or child??
@@ -703,12 +703,12 @@ def __init__(self, ident, detectors, logger=None, **kwargs):
self.modename = attrsman.add(cm.AttrConf('modename', kwargs.get('modename', 'passenger'),
groupnames=['options'],
- choices=net.modes.names.get_indexmap().keys(),
+ choices=list(net.modes.names.get_indexmap().keys()),
name='Mode name',
info='Matched lanes must be accessible at least for this mode.',
))
- print 'net.modes.names.get_indexmap().keys()', net.modes.names.get_indexmap().keys(), self.modename
+ print('net.modes.names.get_indexmap().keys()', list(net.modes.names.get_indexmap().keys()), self.modename)
self.is_edgedetectors = attrsman.add(cm.AttrConf('is_edgedetectors', kwargs.get('is_edgedetectors', False),
groupnames=['options'],
@@ -756,7 +756,7 @@ def __init__(self, ident, detectors, logger=None, **kwargs):
))
def do(self):
- print 'DetectorMatcher.do'
+ print('DetectorMatcher.do')
self.parent.match_detectors_to_lane(modename=self.modename,
is_edgedetectors=self.is_edgedetectors,
is_check_direction=self.is_check_direction,
@@ -946,8 +946,8 @@ def do(self):
if self.is_export_network:
scenario.net.export_netxml()
- print 'DFRouter.do'
- print ' cmloptions', cmloptions
+ print('DFRouter.do')
+ print(' cmloptions', cmloptions)
# dfrouter --net-file bonet190614_ms_dflows.net --routes-output bonet190614_ms_dflows.rou.xml --emitters-output vehicles.xml --detector-files detectors.xml --measure-files bonet190614_ms_dflows.dflows2.csv
cmd = cmloptions + ' --net-file %s --detector-files %s --measure-files %s --routes-output %s --emitters-output %s'\
diff --git a/tools/contributed/sumopy/coremodules/demand/detectorflows_wxgui.py b/tools/contributed/sumopy/coremodules/demand/detectorflows_wxgui.py
index 9fd41646e16b..ba4b4af81b55 100644
--- a/tools/contributed/sumopy/coremodules/demand/detectorflows_wxgui.py
+++ b/tools/contributed/sumopy/coremodules/demand/detectorflows_wxgui.py
@@ -24,7 +24,7 @@
from agilepy.lib_base.processes import Process
from agilepy.lib_wx.processdialog import ProcessDialog
from coremodules.network.network import SumoIdsConf, MODES
-import detectorflows
+from . import detectorflows
class DetectorflowsWxGuiMixin:
diff --git a/tools/contributed/sumopy/coremodules/demand/origin_to_destination.py b/tools/contributed/sumopy/coremodules/demand/origin_to_destination.py
index fc0885ff399c..e03b9a6276eb 100644
--- a/tools/contributed/sumopy/coremodules/demand/origin_to_destination.py
+++ b/tools/contributed/sumopy/coremodules/demand/origin_to_destination.py
@@ -27,8 +27,8 @@
from coremodules.network import routing
from agilepy.lib_base.processes import Process, CmlMixin
-import demand as dm
-import demandbase as db
+from . import demand as dm
+from . import demandbase as db
from agilepy.lib_base.geometry import is_polyline_intersect_polygon
@@ -220,7 +220,7 @@ def _init_constants(self):
def _get_fstar(self, id_mode, is_return_arrays=True, is_ignor_connections=False):
- if not self._fstars.has_key(id_mode):
+ if id_mode not in self._fstars:
self._fstars[id_mode] = self.get_edges().get_fstar(id_mode,
is_ignor_connections=is_ignor_connections,
is_return_arrays=is_return_arrays,)
@@ -228,7 +228,7 @@ def _get_fstar(self, id_mode, is_return_arrays=True, is_ignor_connections=False
def _get_times(self, id_mode, is_check_lanes=False):
- if not self._times.has_key(id_mode):
+ if id_mode not in self._times:
self._times[id_mode] = self.get_edges().get_times(id_mode=id_mode,
is_check_lanes=is_check_lanes,
)
@@ -239,10 +239,10 @@ def get_zone_edgeinfo(self, id_mode, id_zone,
priority_max, speed_max,
id_mode_fallback=None):
- if not self._mode_to_edgeinfo.has_key(id_mode):
+ if id_mode not in self._mode_to_edgeinfo:
self._mode_to_edgeinfo[id_mode] = {}
- if not self._mode_to_edgeinfo[id_mode].has_key(id_zone):
+ if id_zone not in self._mode_to_edgeinfo[id_mode]:
zones = self.get_zones()
ids_edge = zones.get_zoneedges_by_mode_fast(id_zone, id_mode,
weights=self._get_times(id_mode),
@@ -277,7 +277,7 @@ def on_del_row(self, id_row=None):
self.del_row(id_row)
def on_add_row(self, id_row=None):
- print 'on_add_row'
+ print('on_add_row')
if len(self) > 0:
# copy previous
@@ -324,7 +324,7 @@ def generate_trips(self, demand, time_start, time_end, id_mode_primary,
"""
Generates trips in demand.trip table.
"""
- print 'generate_trips', time_start, time_end, 'id_mode_primary', id_mode_primary, 'id_mode_fallback', id_mode_fallback
+ print('generate_trips', time_start, time_end, 'id_mode_primary', id_mode_primary, 'id_mode_fallback', id_mode_fallback)
id_mode_ped = MODES['pedestrian']
zones = self.get_zones()
edges = self.get_edges()
@@ -352,7 +352,7 @@ def generate_trips(self, demand, time_start, time_end, id_mode_primary,
# in case there is a secondary mode, the secondary mode is chosen
ids_vtype_mode_primary, prob_vtype_mode_primary = demand.vtypes.select_by_mode(
id_mode_primary, is_share=True)
- print ' ids_vtype_mode_primary', ids_vtype_mode_primary, prob_vtype_mode_primary
+ print(' ids_vtype_mode_primary', ids_vtype_mode_primary, prob_vtype_mode_primary)
n_vtypes_primary = len(ids_vtype_mode_primary)
n_vtypes_fallback = 0
@@ -368,7 +368,7 @@ def generate_trips(self, demand, time_start, time_end, id_mode_primary,
is_fallback = False
# print ' n_vtypes_primary',n_vtypes_primary,'n_vtypes_fallback',n_vtypes_fallback,'is_fallback',is_fallback
if n_vtypes_primary == 0:
- print 'WARNING: no vehicle types for this mode with ID', id_mode_primary
+ print('WARNING: no vehicle types for this mode with ID', id_mode_primary)
return False
ids_od = self.get_ids()
@@ -378,7 +378,7 @@ def generate_trips(self, demand, time_start, time_end, id_mode_primary,
np.array(self.tripnumbers[ids_od]+random.rand(len(ids_od)), dtype=np.int32),
):
- print ' generate', tripnumber, ' trips from id_orig', id_orig, 'to id_dest', id_dest
+ print(' generate', tripnumber, ' trips from id_orig', id_orig, 'to id_dest', id_dest)
ids_edge_orig, weights_orig = self.get_zone_edgeinfo(
id_mode_primary, id_orig, n_edges_min_length, n_edges_max_length, priority_max, speed_max)
@@ -390,7 +390,7 @@ def generate_trips(self, demand, time_start, time_end, id_mode_primary,
# print ' n_edges_orig',n_edges_orig,len(weights_orig),'n_edges_dest',n_edges_dest,len(weights_dest)
if 1: # (n_edges_orig > 0) & (n_edges_dest > 0):
- for i_trip in xrange(tripnumber):
+ for i_trip in range(tripnumber):
time_depart = random.uniform(time_start, time_end)
@@ -414,9 +414,9 @@ def generate_trips(self, demand, time_start, time_end, id_mode_primary,
n_trips_generated += 1
- print ' -----'
- print ' n_trips_generated', n_trips_generated
- print ' n_trips_failed', np.sum(self.tripnumbers[ids_od])-n_trips_generated
+ print(' -----')
+ print(' n_trips_generated', n_trips_generated)
+ print(' n_trips_failed', np.sum(self.tripnumbers[ids_od])-n_trips_generated)
return True
def add_od_trips(self, scale, names_orig, names_dest, tripnumbers,
@@ -428,7 +428,7 @@ def add_od_trips(self, scale, names_orig, names_dest, tripnumbers,
is_filter_cross = len(ids_zone_cross_filter) > 0
is_dist_min = dist_min > 0
is_dist_max = dist_max > 0
- print 'OdTrips.add_od_trips', is_filter_orig, is_filter_dest, is_filter_cross
+ print('OdTrips.add_od_trips', is_filter_orig, is_filter_dest, is_filter_cross)
# print ' filter',ids_zone_orig_filter,ids_zone_dest_filter
# print ' scale, names_orig, names_dest, tripnumbers',scale, names_orig, names_dest, tripnumbers,len(tripnumbers)
zones = self.get_zones()
@@ -477,15 +477,15 @@ def add_od_trips(self, scale, names_orig, names_dest, tripnumbers,
else:
n_trips_scale_fin = int(n_trips_scale_int + 1)
# -----
- print ' add from', name_orig, 'to', name_dest, 'tripnumber', n_trips_scale_fin
+ print(' add from', name_orig, 'to', name_dest, 'tripnumber', n_trips_scale_fin)
self.add_row(ids_orig=id_zone_orig,
ids_dest=id_zone_dest,
tripnumbers=n_trips_scale_fin) # prima c'era (tripnumbers = scale*tripnumber)
else:
if not ((zones.ids_sumo.has_index(name_orig)) & (zones.ids_sumo.has_index(name_dest))):
- print ' WARNING: zone named %s or %s not known' % (
- name_orig, name_dest)
+ print(' WARNING: zone named %s or %s not known' % (
+ name_orig, name_dest))
# print ' zones indexmap', zones.get_indexmap()
# print ' ids_sumo', zones.ids_sumo.get_value()
# print ' ids_sumo._index_to_id', zones.ids_sumo._index_to_id
@@ -678,7 +678,7 @@ def export_amitranxml(self, filepath=None, encoding='UTF-8'):
"""
Export flows to Amitran format that defines the demand per OD pair in time slices for every vehicle type.
"""
- print 'export_amitranxml', filepath, len(self)
+ print('export_amitranxml', filepath, len(self))
if len(self) == 0:
return None
@@ -689,7 +689,7 @@ def export_amitranxml(self, filepath=None, encoding='UTF-8'):
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in export_sumoxml: could not open', filepath
+ print('WARNING in export_sumoxml: could not open', filepath)
return False
indent = 0
@@ -745,7 +745,7 @@ def export_sumoxml(self, filepath=None, encoding='UTF-8'):
"""
Export flows to SUMO xml file formate.
"""
- print 'export_sumoxml', filepath, len(self)
+ print('export_sumoxml', filepath, len(self))
if len(self) == 0:
return None
@@ -755,7 +755,7 @@ def export_sumoxml(self, filepath=None, encoding='UTF-8'):
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in export_sumoxml: could not open', filepath
+ print('WARNING in export_sumoxml: could not open', filepath)
return False
#xmltag, xmltag_item, attrname_id = self.xmltag
#fd.write('\n'%encoding)
diff --git a/tools/contributed/sumopy/coremodules/demand/origin_to_destination_mpl.py b/tools/contributed/sumopy/coremodules/demand/origin_to_destination_mpl.py
index 83c535a07a55..5dd5029a45cb 100644
--- a/tools/contributed/sumopy/coremodules/demand/origin_to_destination_mpl.py
+++ b/tools/contributed/sumopy/coremodules/demand/origin_to_destination_mpl.py
@@ -33,7 +33,7 @@
class OdPlots(PlotoptionsMixin, Process):
def __init__(self, ident, demand, logger=None, **kwargs):
- print 'OdPlots.__init__'
+ print('OdPlots.__init__')
self._init_common(ident,
parent=demand,
name='OD plots',
@@ -70,7 +70,7 @@ def __init__(self, ident, demand, logger=None, **kwargs):
intervalchoices[str(int(time_start/60.0))+'min-'+str(int(time_end/60.0)) +
'min'] = (int(time_start), int(time_end))
- self.intervals = attrsman.add(cm.ListConf('intervals', intervalchoices.values(),
+ self.intervals = attrsman.add(cm.ListConf('intervals', list(intervalchoices.values()),
groupnames=['options'],
choices=intervalchoices,
name='Intervals',
@@ -155,7 +155,7 @@ def __init__(self, ident, demand, logger=None, **kwargs):
self.add_save_options(**kwargs)
def show(self):
- print 'OdPlots.show'
+ print('OdPlots.show')
# if self.axis is None:
scenario = self.parent.get_scenario()
zones = scenario.landuse.zones
@@ -192,7 +192,7 @@ def show(self):
outflows[id_zone_orig] += n_trips
inflows[id_zone_dest] += n_trips
od = (id_zone_orig, id_zone_dest)
- if odflows.has_key(od):
+ if od in odflows:
odflows[od] += n_trips
else:
odflows[od] = n_trips
@@ -201,7 +201,7 @@ def show(self):
balance[id_zone] = inflows[id_zone] - outflows[id_zone]
totals[id_zone] = inflows[id_zone] + outflows[id_zone]
# debug
- print ' id_zone', id_zone, 'in', inflows[id_zone], 'out', outflows[id_zone], 'balance', balance[id_zone], 'totals', totals[id_zone]
+ print(' id_zone', id_zone, 'in', inflows[id_zone], 'out', outflows[id_zone], 'balance', balance[id_zone], 'totals', totals[id_zone])
unit = self.unit_mapscale
mapscale = self.get_attrsman().get_config('unit_mapscale').mapscales[unit]
@@ -211,21 +211,21 @@ def show(self):
#self.zonefillmode = ['zone color','flows in - flows out','flows in + flows out','flows in','flows out'],
if self.zonefillmode == 'flows in - flows out':
- ids_zone = balance.keys()
- values = balance.values()
+ ids_zone = list(balance.keys())
+ values = list(balance.values())
elif self.zonefillmode == 'flows in + flows out':
- ids_zone = totals.keys()
- values = totals.values()
+ ids_zone = list(totals.keys())
+ values = list(totals.values())
elif self.zonefillmode == 'flows in':
- ids_zone = inflows.keys()
- values = inflows.values()
+ ids_zone = list(inflows.keys())
+ values = list(inflows.values())
elif self.zonefillmode == 'flows out':
- ids_zone = outflows.keys()
- values = outflows.values()
+ ids_zone = list(outflows.keys())
+ values = list(outflows.values())
else:
# dummy
- ids_zone = balance.keys()
- values = balance.values()
+ ids_zone = list(balance.keys())
+ values = list(balance.values())
ppatches = []
for id_zone, shape, value in zip(ids_zone, zones.shapes[ids_zone], values):
@@ -268,7 +268,7 @@ def show(self):
else:
cmap = mpl.cm.jet
patchcollection = PatchCollection(ppatches, cmap=cmap, alpha=self.alpha_zones)
- print ' values', values
+ print(' values', values)
patchcollection.set_array(np.array(values, dtype=np.float32))
ax.add_collection(patchcollection)
@@ -284,11 +284,11 @@ def show(self):
ax.add_patch(patch)
if self.is_show_flows:
- values_raw = np.array(odflows.values(), dtype=np.float32)
+ values_raw = np.array(list(odflows.values()), dtype=np.float32)
widthcoeff = self.width_flows_max/np.max(values_raw)
apatches = []
- for od, flow in odflows.iteritems():
+ for od, flow in odflows.items():
id_zone_orig, id_zone_dest = od
x1, y1 = zones.coords[id_zone_orig][:2]
x2, y2 = zones.coords[id_zone_dest][:2]
@@ -298,7 +298,7 @@ def show(self):
# text = str(int(flow))
# else:
# text = ''
- print ' x1, y1', x1, y1, 'x2, y2', x2, y2
+ print(' x1, y1', x1, y1, 'x2, y2', x2, y2)
if id_zone_orig != id_zone_dest:
patch = FancyArrow(x1*mapscale, y1*mapscale, (x2-x1)*mapscale, (y2-y1)*mapscale,
width=width,
diff --git a/tools/contributed/sumopy/coremodules/demand/origin_to_destination_wxgui.py b/tools/contributed/sumopy/coremodules/demand/origin_to_destination_wxgui.py
index c742f7e97373..5eff3f6d9146 100644
--- a/tools/contributed/sumopy/coremodules/demand/origin_to_destination_wxgui.py
+++ b/tools/contributed/sumopy/coremodules/demand/origin_to_destination_wxgui.py
@@ -26,12 +26,12 @@
from agilepy.lib_wx.ogleditor import *
from agilepy.lib_wx.objpanel import ObjPanel
from coremodules.network.network import SumoIdsConf, MODES
-import origin_to_destination as od
+from . import origin_to_destination as od
class OdCommonMixin:
def add_odoptions_common(self, modes=None, activitytypes=None, **kwargs):
- print 'add_odoptions_common', modes
+ print('add_odoptions_common', modes)
self.add(am.AttrConf('t_start', kwargs.get('t_start', 0),
groupnames=['options'],
perm='rw',
@@ -630,7 +630,7 @@ def add_demand(self):
"""
Add demand to scenario.
"""
- print 'AddOdm.add_demand'
+ print('AddOdm.add_demand')
# print ' ids_zone_orig_filter',self.ids_zone_orig_filter.get_value()
# print ' ids_zone_dest_filter',self.ids_zone_dest_filter.get_value()
odintervals = self.parent
@@ -677,11 +677,11 @@ def import_csv(self, filepath, sep=",", n_firstline=1):
tripnumbers=int(tripnumbers_str)
)
else:
- print 'WARNING: unknown zonename in line %d of file %s' % (i_line, filepath)
+ print('WARNING: unknown zonename in line %d of file %s' % (i_line, filepath))
else:
if len(cols) != 0:
- print 'WARNING: inconsistent o,d,trips info in line %d of file %s' % (i_line, filepath)
+ print('WARNING: inconsistent o,d,trips info in line %d of file %s' % (i_line, filepath))
i_line += 1
# self.odtab.print_rows()
f.close()
diff --git a/tools/contributed/sumopy/coremodules/demand/publictransportservices.py b/tools/contributed/sumopy/coremodules/demand/publictransportservices.py
index 0d12bf9bc83c..cf1eaa30773d 100644
--- a/tools/contributed/sumopy/coremodules/demand/publictransportservices.py
+++ b/tools/contributed/sumopy/coremodules/demand/publictransportservices.py
@@ -174,7 +174,7 @@ def check_initial_stops(self):
if len(ids_edge) > 0:
if id_stopedge not in ids_edge:
id_edge = ids_edge[0]
- print ' initial stop edge %d of line %d disconnected from route edge %d' % (id_stopedge, id_line, id_edge)
+ print(' initial stop edge %d of line %d disconnected from route edge %d' % (id_stopedge, id_line, id_edge))
# print ' before:',ids_edge
if id_mode not in map_mode_to_times:
map_mode_to_times[id_mode] = get_times(id_mode=id_mode,
@@ -188,7 +188,7 @@ def check_initial_stops(self):
if len(ids_edges_connect) > 0:
if ids_edges_connect[-1] == id_edge:
- print ' prepend connection', ids_edges_connect
+ print(' prepend connection', ids_edges_connect)
self.ids_edges[id_line] = ids_edges_connect[:-1] + ids_edge
# print ' after:',self.ids_edges[id_line]
@@ -281,7 +281,7 @@ def guess_routes(self, is_keep_existing=False, ids_line=None):
# complete route between stops
ids_edge = []
duration = 0
- for i in xrange(1, len(ids_stop)):
+ for i in range(1, len(ids_stop)):
# print ' route',ids_stopedge[i-1],ids_stopedge[i]
time, ids_edges_current = get_mincostroute_edge2edge(
ids_stopedge[i-1],
@@ -545,23 +545,23 @@ def print_link(self, id_link, ident=2, is_edges=True, is_link_forward=False):
id_line = self.ids_line[id_link]
time_interval = self.parent.periods[id_line]
- print ident*' ', 'PtLink:', id_link, 'line', id_line, '(%s)' % (self.parent.linenames[id_line]), 'from stop', self.ids_fromstop[id_link], 'to stop', self.ids_tostop[id_link], 'T=%ds I=%ds' % (self.durations[id_link], time_interval)
+ print(ident*' ', 'PtLink:', id_link, 'line', id_line, '(%s)' % (self.parent.linenames[id_line]), 'from stop', self.ids_fromstop[id_link], 'to stop', self.ids_tostop[id_link], 'T=%ds I=%ds' % (self.durations[id_link], time_interval))
#id_link_board = self.get_link_board(id_link)
# print ident*' ', 'check interval: I=%d, I_board=%d, id_link_board=%d'%(time_interval, self.durations[id_link_board], id_link_board),'ids_link_forward',self.ids_links_forward[id_link_board]
if is_edges:
- print ident*' ', ' ids_edge=', self.get_ids_edge(id_link)
+ print(ident*' ', ' ids_edge=', self.get_ids_edge(id_link))
elif linktype == 'board':
id_line = self.ids_line[id_link]
- print ident*' ', 'PtLink:', id_link, 'type', linktype, 'T=%ds' % (self.durations[id_link]), 'line', id_line, '(%s)' % (self.parent.linenames[id_line]), 'at stop', self.ids_fromstop[id_link]
+ print(ident*' ', 'PtLink:', id_link, 'type', linktype, 'T=%ds' % (self.durations[id_link]), 'line', id_line, '(%s)' % (self.parent.linenames[id_line]), 'at stop', self.ids_fromstop[id_link])
elif linktype == 'walk':
- print ident*' ', 'PtLink:', id_link, 'type', linktype, 'T=%ds' % (self.durations[id_link]), 'from stop', self.ids_fromstop[id_link], 'to stop', self.ids_tostop[id_link]
+ print(ident*' ', 'PtLink:', id_link, 'type', linktype, 'T=%ds' % (self.durations[id_link]), 'from stop', self.ids_fromstop[id_link], 'to stop', self.ids_tostop[id_link])
else:
- print ident*' ', 'PtLink:', id_link, 'type', linktype, 'T=%ds' % (self.durations[id_link]), 'at stop', self.ids_fromstop[id_link]
+ print(ident*' ', 'PtLink:', id_link, 'type', linktype, 'T=%ds' % (self.durations[id_link]), 'at stop', self.ids_fromstop[id_link])
if is_link_forward:
# print ident*' ',' ids_link_forward=',self.ids_links_forward[id_link]
@@ -609,7 +609,7 @@ def build(self, dist_walk_los=150.0, speed_walk_los=0.5,
speed_walk_los is the assumed line of sight walking speed
between two stops
"""
- print 'build', self.ident, dist_walk_los, speed_walk_los
+ print('build', self.ident, dist_walk_los, speed_walk_los)
id_stop_debug = 459
@@ -659,15 +659,15 @@ def build(self, dist_walk_los=150.0, speed_walk_los=0.5,
):
n_edge = len(ids_edge)
n_stop = len(ids_stop)
- print 79*'-'
- print 'Build links of line', linename, 'id_line', id_line, 'n_edge', n_edge, 'n_stop', n_stop
+ print(79*'-')
+ print('Build links of line', linename, 'id_line', id_line, 'n_edge', n_edge, 'n_stop', n_stop)
if (len(ids_edge) > 1) & (len(ids_stop) > 2):
# check if all stop edges are on route and in the correct order:
ind_edge = 0
id_stopedge_next = ids_laneedge[ids_stoplane[ids_stop[1]]]
- for ind_stop in xrange(1, n_stop):
+ for ind_stop in range(1, n_stop):
id_fromstop = ids_stop[ind_stop-1]
id_tostop = ids_stop[ind_stop]
if id_fromstop != id_tostop:
@@ -686,7 +686,7 @@ def build(self, dist_walk_los=150.0, speed_walk_los=0.5,
# print ' ind_edge,id_stopedge_next,ids_edge[ind_edge]',ind_edge,id_stopedge_next,ids_edge[ind_edge],len(ids_edge)
#is_mismatch = (ind_edge == (n_edge-1)) & (ind_stop != (n_stop-1))
- print ' ind_stop', ind_stop, 'ind_edge', ind_edge, is_mismatch
+ print(' ind_stop', ind_stop, 'ind_edge', ind_edge, is_mismatch)
if is_mismatch:
break
@@ -705,12 +705,12 @@ def build(self, dist_walk_los=150.0, speed_walk_los=0.5,
ids_link = []
ind_edge = 0
- for ind_stop in xrange(1, len(ids_stop)):
+ for ind_stop in range(1, len(ids_stop)):
id_fromstop = ids_stop[ind_stop-1]
id_tostop = ids_stop[ind_stop]
# if id_fromstop == id_stop_debug:
- print ' ind_stop', ind_stop, 'id_fromstop,id_tostop', id_fromstop, id_tostop, 'ind_edge', ind_edge
+ print(' ind_stop', ind_stop, 'id_fromstop,id_tostop', id_fromstop, id_tostop, 'ind_edge', ind_edge)
# this prevents error in case two successive stops have
# (by editing error) the same ID
@@ -719,7 +719,7 @@ def build(self, dist_walk_los=150.0, speed_walk_los=0.5,
# compute length and time between fromstop and tostop
while id_stopedge_next != ids_edge[ind_edge]:
# if id_fromstop == id_stop_debug:
- print ' ind_edge', ind_edge, ',id_stopedge_next,ids_edge[ind_edge]', id_stopedge_next, ids_edge[ind_edge]
+ print(' ind_edge', ind_edge, ',id_stopedge_next,ids_edge[ind_edge]', id_stopedge_next, ids_edge[ind_edge])
ind_edge += 1
length_edge = edgelengths[ids_edge[ind_edge]]
length += length_edge
@@ -745,7 +745,7 @@ def build(self, dist_walk_los=150.0, speed_walk_los=0.5,
# debugging
if id_fromstop == id_stop_debug:
- print ' append transit link', id_link
+ print(' append transit link', id_link)
stoplinks[id_fromstop]['ids_transit_out'].append(id_link)
stoplinks[id_tostop]['ids_transit_in'].append(id_link)
@@ -757,14 +757,14 @@ def build(self, dist_walk_los=150.0, speed_walk_los=0.5,
duration = 0.0
# create forward links for this line
- for i in xrange(1, len(ids_link)):
+ for i in range(1, len(ids_link)):
self.ids_links_forward[ids_link[i-1]] = [ids_link[i]]
# put empty link list to line end-stop
self.ids_links_forward[ids_link[i]] = []
else:
- print 'WARNING in line', linename, 'id_line', id_line
- print ' stop edges not on route, line will not build.'
+ print('WARNING in line', linename, 'id_line', id_line)
+ print(' stop edges not on route, line will not build.')
ids_ptlines_failed.append(id_line)
# complete stoplink database
@@ -870,15 +870,15 @@ def build(self, dist_walk_los=150.0, speed_walk_los=0.5,
# debugging
if id_stop == id_stop_debug:
- print ' Parameters of id_stop', id_stop
- for key, val in stoplinks[id_stop].iteritems():
+ print(' Parameters of id_stop', id_stop)
+ for key, val in stoplinks[id_stop].items():
if key in ['ids_transit_out', 'ids_transit_in', 'ids_board', 'ids_alight']:
- print ' ', key, ':'
+ print(' ', key, ':')
for id_link in val:
self.print_link(id_link, ident=6)
else:
- print ' ', key, ':', val
+ print(' ', key, ':', val)
# connect walk links from one stop to board and transfer
for id_stop in net.ptstops.get_ids():
@@ -887,32 +887,32 @@ def build(self, dist_walk_los=150.0, speed_walk_los=0.5,
self.ids_links_forward[id_walk] = [stoplinks[id_tostop]['id_enter']]
if 0:
# debugging
- print 79*'='
+ print(79*'=')
ids_link = self.get_ids()
for id_link, linktype, id_fromstop, id_tostop, id_line, duration, ids_link_forward in zip(
ids_link, self.types[ids_link], self.ids_fromstop[ids_link], self.ids_tostop[ids_link], self.ids_line[ids_link], self.durations[ids_link], self.ids_links_forward[ids_link]):
if id_fromstop == id_stop_debug:
- print ' FROM', id_stop_debug, 'TO', id_tostop
+ print(' FROM', id_stop_debug, 'TO', id_tostop)
self.print_link(id_link, ident=4)
- print ' ids_link_forward=', ids_link_forward
+ print(' ids_link_forward=', ids_link_forward)
- print 79*'='
+ print(79*'=')
for id_link, linktype, id_fromstop, id_tostop, id_line, duration, ids_link_forward in zip(
ids_link, self.types[ids_link], self.ids_fromstop[ids_link], self.ids_tostop[ids_link], self.ids_line[ids_link], self.durations[ids_link], self.ids_links_forward[ids_link]):
if id_tostop == id_stop_debug:
- print ' FROM', id_fromstop, 'TO', id_stop_debug
+ print(' FROM', id_fromstop, 'TO', id_stop_debug)
self.print_link(id_link, ident=4)
- print ' ids_link_forward=', ids_link_forward
+ print(' ids_link_forward=', ids_link_forward)
# debug
- print 'Number of failed Ptlines', len(ids_ptlines_failed), 'of', len(ptlines)
+ print('Number of failed Ptlines', len(ids_ptlines_failed), 'of', len(ptlines))
for id_line, linename, period in zip(
ids_ptlines_failed,
ptlines.linenames[ids_ptlines_failed],
ptlines.periods[ids_ptlines_failed],
):
- print ' Failed to build line', linename, 'id_line', id_line, 'period', period, 's'
+ print(' Failed to build line', linename, 'id_line', id_line, 'period', period, 's')
return ids_ptlines_failed
@@ -937,7 +937,7 @@ def get_map_stop_to_ptlinks(self, is_fromstop=True, is_tostop=False, linktype=2)
if is_fromstop:
for id_link, linktype_stop, id_stop in zip(ids, self.types[ids], self.ids_fromstop[ids]):
if linktype == linktype_stop:
- if map_id_stop_to_ids_link.has_key(id_stop):
+ if id_stop in map_id_stop_to_ids_link:
# print ' append id_transitlink',id_link,linktype,'to id_stop',id_stop
map_id_stop_to_ids_link[id_stop].append(id_link)
else:
@@ -946,7 +946,7 @@ def get_map_stop_to_ptlinks(self, is_fromstop=True, is_tostop=False, linktype=2)
if is_tostop:
for id_link, linktype_stop, id_stop in zip(ids, self.types[ids], self.ids_tostop[ids]):
if linktype == linktype_stop:
- if map_id_stop_to_ids_link.has_key(id_stop):
+ if id_stop in map_id_stop_to_ids_link:
# print ' append id_transitlink',id_link,linktype,'to id_stop',id_stop
map_id_stop_to_ids_link[id_stop].append(id_link)
else:
@@ -1046,7 +1046,7 @@ def print_route(self, ids_link):
line = self.parent.linenames[id_line]
else:
line = 'X'
- print '%4d %06s fromstop=%3d tostop=%3d %06s' % (id_link, line, id_fromstop, id_tostop, typemap[id_type])
+ print('%4d %06s fromstop=%3d tostop=%3d %06s' % (id_link, line, id_fromstop, id_tostop, typemap[id_type]))
def route(self, id_fromstop, id_tostop,
stops_to_enter=None, stops_to_exit=None,
@@ -1060,7 +1060,7 @@ def route(self, id_fromstop, id_tostop,
ids_tostop : IDs of stops where each stage ends
durations : Duration of each stage in secs
"""
- print 'route id_fromstop, id_tostop', id_fromstop, id_tostop
+ print('route id_fromstop, id_tostop', id_fromstop, id_tostop)
if times is None:
times = self.get_times()
@@ -1166,7 +1166,7 @@ def route(self, id_fromstop, id_tostop,
class PtLinefilter(Process):
def __init__(self, ident='ptlinefilter', ptlines=None, logger=None, **kwargs):
- print 'PtLinefilter.__init__'
+ print('PtLinefilter.__init__')
# TODO: let this be independent, link to it or child??
@@ -1194,7 +1194,7 @@ def __init__(self, ident='ptlinefilter', ptlines=None, logger=None, **kwargs):
))
def do(self):
- print 'PtLinefilter.do'
+ print('PtLinefilter.do')
# links
ptlines = self.parent
@@ -1215,14 +1215,14 @@ def do(self):
elif period > self.period_max:
ids_remove.append(id_line)
- print ' Eliminated %d lines:' % (len(ids_remove))
+ print(' Eliminated %d lines:' % (len(ids_remove)))
for id_line, name, ids_stop, period in zip(ids_remove,
ptlines.linenames[ids_remove],
ptlines.ids_stops[ids_remove],
ptlines.periods[ids_remove]
):
- print ' id_line', id_line, 'name', name, 'period', period, 'n_stops', len(ids_stop)
+ print(' id_line', id_line, 'name', name, 'period', period, 'n_stops', len(ids_stop))
ptlines.del_rows(ids_remove)
@@ -1231,7 +1231,7 @@ def do(self):
class PtNetbuilder(Process):
def __init__(self, ident='ptnetbuilder', ptlinks=None, logger=None, **kwargs):
- print 'PtNetbuilder.__init__'
+ print('PtNetbuilder.__init__')
# TODO: let this be independent, link to it or child??
@@ -1294,7 +1294,7 @@ def __init__(self, ident='ptnetbuilder', ptlinks=None, logger=None, **kwargs):
))
def do(self):
- print 'VehicleProvider.do'
+ print('VehicleProvider.do')
# links
#virtualpop = self.parent
diff --git a/tools/contributed/sumopy/coremodules/demand/publictransportservices_wxgui.py b/tools/contributed/sumopy/coremodules/demand/publictransportservices_wxgui.py
index 6366b30fdabf..8e9a8decbffe 100644
--- a/tools/contributed/sumopy/coremodules/demand/publictransportservices_wxgui.py
+++ b/tools/contributed/sumopy/coremodules/demand/publictransportservices_wxgui.py
@@ -24,7 +24,7 @@
from agilepy.lib_base.processes import Process
from agilepy.lib_wx.processdialog import ProcessDialog
from coremodules.network.network import SumoIdsConf, MODES
-import publictransportservices as pt
+from . import publictransportservices as pt
class PublicTransportWxGuiMixin:
diff --git a/tools/contributed/sumopy/coremodules/demand/turnflows.py b/tools/contributed/sumopy/coremodules/demand/turnflows.py
index 69f5b2520b1e..c75c54b42212 100644
--- a/tools/contributed/sumopy/coremodules/demand/turnflows.py
+++ b/tools/contributed/sumopy/coremodules/demand/turnflows.py
@@ -27,7 +27,7 @@
#from coremodules.modules_common import *
from coremodules.network.network import SumoIdsConf, MODES
from agilepy.lib_base.processes import Process, P, call, CmlMixin
-import demandbase as db
+from . import demandbase as db
class Flows(am.ArrayObjman):
@@ -250,7 +250,7 @@ def normalize_turnprobabilities(self):
flows_total = {}
for _id in self.get_ids():
id_fromedge = self.ids_fromedge[_id]
- if not flows_total.has_key(id_fromedge):
+ if id_fromedge not in flows_total:
flows_total[id_fromedge] = 0.0
flows_total[id_fromedge] += self.flows[_id]
@@ -259,7 +259,7 @@ def normalize_turnprobabilities(self):
self.probabilities[_id] = self.flows[_id] / flows_total[self.ids_fromedge[_id]]
def add_turn(self, id_fromedge, id_toedge, flow):
- print 'Turns.add_turn'
+ print('Turns.add_turn')
return self.add_row(ids_fromedge=id_fromedge,
ids_toedge=id_toedge,
flows=flow,
@@ -295,14 +295,14 @@ def export_xml(self, fd, indent=0):
fromedge_to_turnprobs = {}
for _id in self.get_ids():
id_fromedge = self.ids_fromedge[_id]
- if not fromedge_to_turnprobs.has_key(id_fromedge):
+ if id_fromedge not in fromedge_to_turnprobs:
fromedge_to_turnprobs[id_fromedge] = []
fromedge_to_turnprobs[id_fromedge].append((self.ids_toedge[_id], self.probabilities[_id]))
ids_sumoeges = self.get_edges().ids_sumo
fd.write(xm.begin('edgeRelations', indent))
- for id_fromedge in fromedge_to_turnprobs.keys():
+ for id_fromedge in list(fromedge_to_turnprobs.keys()):
for id_toedge, turnprob in fromedge_to_turnprobs[id_fromedge]:
fd.write(xm.start('edgeRelation', indent+2))
@@ -321,7 +321,7 @@ def __init__(self, ident, parent, modes, edges, **kwargs):
info='Contains for each transport mode an OD trip table.',
xmltag=('modesods', 'modeods', 'ids_mode'), **kwargs)
- print 'TurnflowModes.__init__', modes
+ print('TurnflowModes.__init__', modes)
self.add_col(am.IdsArrayConf('ids_mode', modes,
groupnames=['state'],
choices=MODES,
@@ -330,7 +330,7 @@ def __init__(self, ident, parent, modes, edges, **kwargs):
#xmltag = 'vClass',
info='ID of transport mode.',
))
- print ' self.ids_mode.is_index', self.ids_mode.is_index()
+ print(' self.ids_mode.is_index', self.ids_mode.is_index())
self.add_col(cm.ObjsConf('flowtables',
groupnames=['state'],
@@ -366,7 +366,7 @@ def normalize_turnprobabilities(self):
def add_mode(self, id_mode):
id_tf_modes = self.add_row(ids_mode=id_mode)
- print ' add_mode', id_mode, id_tf_modes
+ print(' add_mode', id_mode, id_tf_modes)
flows = Flows((self.flowtables.attrname, id_tf_modes), self, self.edges.get_value())
self.flowtables[id_tf_modes] = flows
@@ -381,8 +381,8 @@ def add_flow(self, id_mode, id_edge, flow):
Sets a demand flows between from-Edge and toEdge pairs for mode where flows is a dictionary
with (fromEdgeID,toEdgeID) pair as key and number of trips as values.
"""
- print 'TurnflowModes.add_turnflows', id_mode # ,flows,kwargs
- print ' self.ids_mode.is_index()', self.ids_mode.is_index()
+ print('TurnflowModes.add_turnflows', id_mode) # ,flows,kwargs
+ print(' self.ids_mode.is_index()', self.ids_mode.is_index())
if self.ids_mode.has_index(id_mode):
id_tf_modes = self.ids_mode.get_id_from_index(id_mode)
else:
@@ -394,7 +394,7 @@ def add_turn(self, id_mode, id_fromedge, id_toedge, turnflow):
"""
Sets turn probability between from-edge and to-edge.
"""
- print 'TurnflowModes.add_turn', id_mode # ,turnflow,kwargs
+ print('TurnflowModes.add_turn', id_mode) # ,turnflow,kwargs
# if scale!=1.0:
# for od in odm.iterkeys():
# odm[od] *= scale
@@ -413,7 +413,7 @@ def export_flows_xml(self, fd, id_mode, id_flow=0, indent=0):
Export flow data of desired mode to xml file.
Returns list with edge IDs with non zero flows and a flow ID counter.
"""
- print 'TurnflowModes.export_flows_xml id_mode, id_flow', id_mode, id_flow, self.ids_mode.has_index(id_mode)
+ print('TurnflowModes.export_flows_xml id_mode, id_flow', id_mode, id_flow, self.ids_mode.has_index(id_mode))
ids_sourceedge = []
if not self.ids_mode.has_index(id_mode):
@@ -432,7 +432,7 @@ def export_flows_xml(self, fd, id_mode, id_flow=0, indent=0):
# # TODO: can we put some distributen here?
# vtype = vtypes[0]
for vtype, share in zip(vtypes, shares):
- print ' write flows for vtype', vtype, share
+ print(' write flows for vtype', vtype, share)
if self.ids_mode.has_index(id_mode):
id_tf_modes = self.ids_mode.get_id_from_index(id_mode)
ids_sourceedge, id_flow = self.flowtables[id_tf_modes].export_xml(
@@ -446,7 +446,7 @@ def export_turns_xml(self, fd, id_mode, indent=0):
Export flow data of desired mode to xml file.
Returns list with edge IDs with non zero flows and a flow ID counter.
"""
- print 'TurnflowModes.export_turns_xml'
+ print('TurnflowModes.export_turns_xml')
if self.ids_mode.has_index(id_mode):
id_tf_modes = self.ids_mode.get_id_from_index(id_mode)
@@ -502,7 +502,7 @@ def normalize_turnprobabilities(self):
"""
Makes sure that sum of turn probabilities from an edge equals 1.
"""
- print 'Turnflows.normalize_turnprobabilities'
+ print('Turnflows.normalize_turnprobabilities')
# for turnflowmode in self.turnflowmodes.get_value():
# turnflowmode.normalize_turnprobabilities() # no! it's a dict!!
# print ' ',self.turnflowmodes.get_value()
@@ -589,9 +589,9 @@ def export_flows_and_turns(self, flowfilepath, turnsfilepath, id_mode, indent=0)
In the SUMOpy tunflow data structure, each mode has its own
flow and turnratio data.
"""
- print '\n\n'+79*'_'
- print 'export_flows_and_turns id_mode=', id_mode, 'ids_vtype=', self.parent.vtypes.select_by_mode(id_mode)
- print ' write flows', flowfilepath
+ print('\n\n'+79*'_')
+ print('export_flows_and_turns id_mode=', id_mode, 'ids_vtype=', self.parent.vtypes.select_by_mode(id_mode))
+ print(' write flows', flowfilepath)
fd = open(flowfilepath, 'w')
fd.write(xm.begin('flows', indent))
@@ -707,14 +707,14 @@ def turnflows_to_routes(self, is_clear_trips=True, is_export_network=True,
scenario.net.export_netxml()
ids_mode = self.get_modes()
- print 'turnflows_to_routes', ids_mode # scenario.net.modes.get_ids()
- print ' cmloptions', cmloptions
+ print('turnflows_to_routes', ids_mode) # scenario.net.modes.get_ids()
+ print(' cmloptions', cmloptions)
# route for all modes and read in routes
for id_mode in ids_mode:
# write flow and turns xml file for this mode
time_start, time_end = self.export_flows_and_turns(flowfilepath, turnfilepath, id_mode)
- print ' time_start, time_end =', time_start, time_end
+ print(' time_start, time_end =', time_start, time_end)
if time_end > time_start: # means there exist some flows for this mode
cmd = 'jtrrouter --route-files=%s --turn-ratio-files=%s --net-file=%s --output-file=%s --begin %s --end %s %s'\
@@ -733,7 +733,7 @@ def turnflows_to_routes(self, is_clear_trips=True, is_export_network=True,
os.remove(routefilepath)
else:
- print 'jtrroute: no flows generated for id_mode', id_mode
+ print('jtrroute: no flows generated for id_mode', id_mode)
# self.simfiles.set_modified_data('rou',True)
# self.simfiles.set_modified_data('trip',True)
@@ -872,9 +872,9 @@ def __init__(self, turnflows, logger=None, **kwargs):
# )
def do(self):
- print 'do'
+ print('do')
cml = self.get_cml(is_without_command=True) # only options, not the command #
- print ' cml=', cml
+ print(' cml=', cml)
self.parent.turnflows_to_routes(is_clear_trips=self.is_clear_trips,
is_export_network=self.is_export_network,
is_make_probabilities=True,
@@ -972,7 +972,7 @@ def import_pat_csv(self, sep=","):
ids_sumoedge_notexist = []
pairs_sumoedge_unconnected = []
- print 'import_pat_csv', self.tffilepath
+ print('import_pat_csv', self.tffilepath)
i_line = 1
for line in f.readlines():
cols = line.split(sep)
@@ -1006,12 +1006,12 @@ def import_pat_csv(self, sep=","):
id_fromedge, id_toedge, turnflow)
else:
- print 'WARNING: inconsistent row in line %d, file %s' % (i_line, self.tffilepath)
+ print('WARNING: inconsistent row in line %d, file %s' % (i_line, self.tffilepath))
i_line += 1
f.close()
if len(ids_sumoedge_notexist) > 0:
- print 'WARNING: inexistant edge IDs:', ids_sumoedge_notexist
+ print('WARNING: inexistant edge IDs:', ids_sumoedge_notexist)
if len(pairs_sumoedge_unconnected) > 0:
- print 'WARNING: unconnected edge pairs:', pairs_sumoedge_unconnected
+ print('WARNING: unconnected edge pairs:', pairs_sumoedge_unconnected)
return ids_sumoedge_notexist, pairs_sumoedge_unconnected
diff --git a/tools/contributed/sumopy/coremodules/demand/turnflows_wxgui.py b/tools/contributed/sumopy/coremodules/demand/turnflows_wxgui.py
index 3a063ecf6098..8fcaa08a882c 100644
--- a/tools/contributed/sumopy/coremodules/demand/turnflows_wxgui.py
+++ b/tools/contributed/sumopy/coremodules/demand/turnflows_wxgui.py
@@ -24,7 +24,7 @@
from agilepy.lib_base.processes import Process
from agilepy.lib_wx.processdialog import ProcessDialog
from coremodules.network.network import SumoIdsConf, MODES
-import turnflows
+from . import turnflows
class TurnflowWxGuiMixin:
diff --git a/tools/contributed/sumopy/coremodules/demand/vehicles.py b/tools/contributed/sumopy/coremodules/demand/vehicles.py
index 0f1151ba9597..df3e1753ea0d 100644
--- a/tools/contributed/sumopy/coremodules/demand/vehicles.py
+++ b/tools/contributed/sumopy/coremodules/demand/vehicles.py
@@ -117,7 +117,7 @@
class Electricalprofiles(am.ArrayObjman):
def __init__(self, ident, parent, **kwargs):
- print 'Electricalprofiles.__init__'
+ print('Electricalprofiles.__init__')
self._init_objman(ident=ident,
parent=parent,
name='Electrical profiles',
@@ -129,7 +129,7 @@ def __init__(self, ident, parent, **kwargs):
self.add_profiles_default()
def _init_attributes(self):
- print 'Electricalprofiles._init_attributes'
+ print('Electricalprofiles._init_attributes')
self.add_col(SumoIdsConf('profilename', name='Electric profile', perm='rw'))
self.add_col(am.ArrayConf('capacities_battery', 0.8,
groupnames=['parameters', 'key'],
@@ -189,7 +189,7 @@ def add_profile(self, profilename, **kwargs):
class VehicleTypes(am.ArrayObjman):
def __init__(self, parent, net, is_add_default=True, **kwargs):
- print 'VehicleTypes.__init__ is_add_default', is_add_default
+ print('VehicleTypes.__init__ is_add_default', is_add_default)
self._init_objman(ident='vtypes',
parent=parent,
name='Vehicle Types',
@@ -205,7 +205,7 @@ def __init__(self, parent, net, is_add_default=True, **kwargs):
self.set_version(0.3)
def _init_attributes(self):
- print 'VehicleTypes._init_attributes', len(self), self.get_ident_abs()
+ print('VehicleTypes._init_attributes', len(self), self.get_ident_abs())
net = self.parent.get_net()
demand = self.parent
@@ -530,7 +530,7 @@ def _init_attributes(self):
))
emissionclasses_xml = {}
- for key in EMISSIONCLASSES.keys():
+ for key in list(EMISSIONCLASSES.keys()):
emissionclasses_xml[key] = key # yes, map onto itself, otherwise choice values are taken
self.add_col(am.ArrayConf('emissionclasses', 'HBEFA3/HDV_D_EU4',
@@ -758,7 +758,7 @@ def on_add_row(self, id_row=None):
_id = self.add_row(**row_last)
# print ' _id',_id
else:
- print ' clone last'
+ print(' clone last')
i = 1
row_last = self.get_row(self.get_ids()[-1])
row_last['ids_sumo'] += '_%03d' % i # important for all indexed attrs!!
@@ -780,17 +780,17 @@ def add_vtype_parser(self, vtype, **kwargs):
return id_vtype
def add_vtype(self, vtype, **kwargs):
- print 'add_vtype', vtype, kwargs
+ print('add_vtype', vtype, kwargs)
if self.ids_sumo.has_index(vtype):
# vtype already exist
_id = self.ids_sumo.get_id_from_index(vtype)
else:
_id = self.add_row(ids_sumo=vtype)
- if kwargs.has_key('mode'):
+ if 'mode' in kwargs:
id_mode = MODES.get(kwargs['mode'], 1)
del kwargs['mode']
- elif kwargs.has_key('id_mode'):
+ elif 'id_mode' in kwargs:
id_mode = kwargs['id_mode']
del kwargs['id_mode']
else:
@@ -798,7 +798,7 @@ def add_vtype(self, vtype, **kwargs):
#_id = self.add_row( ids_sumo = vtype, ids_mode = id_mode,**kwargs)
- if kwargs.has_key('eprofile'):
+ if 'eprofile' in kwargs:
eprofiles = self.eprofiles.get_value()
eprofile = kwargs['eprofile']
eprofiles.add_profile(eprofile, **kwargs)
@@ -861,7 +861,7 @@ def add_vtype(self, vtype, **kwargs):
return _id
def add_vtypes_default(self):
- print 'add_vtypes_default'
+ print('add_vtypes_default')
# self.del_rows(self.get_ids())
self.add_vtype('pedestrian',
accel=1.5,
@@ -1411,7 +1411,7 @@ def get_modechoices(self):
"""
mode_vtypes = self.get_modes()
mode_choice = OrderedDict()
- for mode, id_mode in MODES.iteritems():
+ for mode, id_mode in MODES.items():
if id_mode in mode_vtypes:
mode_choice[mode] = id_mode
return mode_choice
@@ -1516,12 +1516,12 @@ def _write_xml_body(self, fd, indent, objconfigs, idcolconfig_include_tab, colc
# print ' _write_xml_body: done'
def export_xml(self, filepath, encoding='UTF-8'):
- print 'export_xml to %s' % (filepath)
+ print('export_xml to %s' % (filepath))
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in vtypes.export_xml: could not open', filepath
+ print('WARNING in vtypes.export_xml: could not open', filepath)
return False
fd.write('\n' % encoding)
@@ -1539,7 +1539,7 @@ def export_xml(self, filepath, encoding='UTF-8'):
# attrconfigs_excluded.append('lanechangemodel')
def import_xml(self, filepath):
- print 'import_xml from %s' % (filepath)
+ print('import_xml from %s' % (filepath))
reader = VtypeReader(self)
parse(filepath, reader)
self.normalize_shares()
@@ -1566,20 +1566,20 @@ def startElement(self, name, attrs):
params = {}
# print 'startElement',attrs['id'],self._id_vclass_dist
- if attrs.has_key('laneChangeModel'):
+ if 'laneChangeModel' in attrs:
lanechangemodel = attrs['laneChangeModel']
if lanechangemodel in LANECHANGEMODELS:
self._vtypes.lanechangemodel.set_value(lanechangemodel)
- if attrs.has_key('vClass'):
+ if 'vClass' in attrs:
if self._id_vclass_dist is None:
params['ids_mode'] = self._vtypes.ids_mode.get_value_from_string(attrs['vClass'])
else:
params['ids_mode'] = self._id_vclass_dist # set vclass to distribution id
# for xmltag, xmlval in self._xmlattrmap.iteritems():
- for xmltag in attrs.keys():
- if self._xmlattrmap.has_key(xmltag):
+ for xmltag in list(attrs.keys()):
+ if xmltag in self._xmlattrmap:
attrconfig = self._xmlattrmap[xmltag]
params[attrconfig.attrname] = attrconfig.get_value_from_xmlattr(attrs)
diff --git a/tools/contributed/sumopy/coremodules/demand/virtualpop.py b/tools/contributed/sumopy/coremodules/demand/virtualpop.py
index aca82a1caf80..60871592b625 100644
--- a/tools/contributed/sumopy/coremodules/demand/virtualpop.py
+++ b/tools/contributed/sumopy/coremodules/demand/virtualpop.py
@@ -30,8 +30,8 @@
from coremodules.network.network import SumoIdsConf, MODES
from coremodules.network import routing
from coremodules.simulation import results as res
-from demandbase import *
-import virtualpop_results as res
+from .demandbase import *
+from . import virtualpop_results as res
GENDERS = {'male': 0, 'female': 1, 'unknown': -1}
@@ -1202,7 +1202,7 @@ def preevaluate(self, ids_person):
activities = vp.get_activities()
ids_pers_filter = ids_person[persons.ids_mode_preferred[ids_person] != self._id_mode_ped]
- for i, ids_activity in zip(xrange(len(ids_pers_filter)), vp.activitypatterns[ids_pers_filter]):
+ for i, ids_activity in zip(range(len(ids_pers_filter)), vp.activitypatterns[ids_pers_filter]):
id_act1 = ids_activity[0]
id_act2 = ids_activity[1]
@@ -1212,7 +1212,7 @@ def preevaluate(self, ids_person):
if dist_fac_sqr > max_dist_fac_sqr:
preeval[i] = -1
- print ' WalkStrategy.preevaluate', len(np.flatnonzero(preeval >= 0))
+ print(' WalkStrategy.preevaluate', len(np.flatnonzero(preeval >= 0)))
return preeval
def plan(self, ids_person, logger=None, **kwargs):
@@ -1220,7 +1220,7 @@ def plan(self, ids_person, logger=None, **kwargs):
Generates a plan for these person according to this strategie.
Overriden by specific strategy.
"""
- print 'WalkStrategy.pan', len(ids_person)
+ print('WalkStrategy.pan', len(ids_person))
#make_plans_private(self, ids_person = None, mode = 'passenger')
# routing necessary?
virtualpop = self.get_virtualpop()
@@ -1258,7 +1258,7 @@ def plan(self, ids_person, logger=None, **kwargs):
= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
if len(ids_person_act) == 0:
- print 'WARNING in WalkStrategy.plan: no eligible persons found.'
+ print('WARNING in WalkStrategy.plan: no eligible persons found.')
return False
# temporary maps from ids_person to other parameters
@@ -1277,7 +1277,7 @@ def plan(self, ids_person, logger=None, **kwargs):
map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]
n_plans = len(ids_person_act)
- print 'TrasitStrategy.plan n_plans=', n_plans
+ print('TrasitStrategy.plan n_plans=', n_plans)
# make initial activity stage
ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]
@@ -1362,8 +1362,8 @@ def plan(self, ids_person, logger=None, **kwargs):
if logger:
logger.progress(i/n_pers*100)
i += 1.0
- print 79*'_'
- print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)
+ print(79*'_')
+ print(' id_plan=%d, id_person=%d, ' % (id_plan, id_person))
id_stage_walk1, time = walkstages.append_stage(id_plan, time_from,
id_edge_from=id_edge_from,
@@ -1473,24 +1473,24 @@ def preevaluate(self, ids_person):
"""
n_pers = len(ids_person)
- print 'Autostrategy.preevaluate', n_pers, 'persons'
+ print('Autostrategy.preevaluate', n_pers, 'persons')
persons = self.get_virtualpop()
preeval = np.zeros(n_pers, dtype=np.int32)
# put -1 for persons without car access
preeval[persons.ids_iauto[ids_person] == -1] = -1
- print ' persons having no auto', len(np.flatnonzero(persons.ids_iauto[ids_person] == -1))
+ print(' persons having no auto', len(np.flatnonzero(persons.ids_iauto[ids_person] == -1)))
# put 0 for persons with car but with a different preferred mode
preeval[(persons.ids_iauto[ids_person] > -1)
& (persons.ids_mode_preferred[ids_person] != self._id_mode_auto)] = 0
- print ' persons with car but with a different preferred mode', len(np.flatnonzero((persons.ids_iauto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_auto)))
+ print(' persons with car but with a different preferred mode', len(np.flatnonzero((persons.ids_iauto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_auto))))
# put 2 for persons with car access and who prefer the car
preeval[(persons.ids_iauto[ids_person] > -1)
& (persons.ids_mode_preferred[ids_person] == self._id_mode_auto)] = 2
- print ' persons with car access and who prefer the car', len(np.flatnonzero((persons.ids_iauto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_auto)))
+ print(' persons with car access and who prefer the car', len(np.flatnonzero((persons.ids_iauto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_auto))))
return preeval
@@ -1549,7 +1549,7 @@ def plan(self, ids_person, logger=None, **kwargs):
= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
if len(ids_person_act) == 0:
- print 'WARNING in Autostrategy.plan: no eligible persons found.'
+ print('WARNING in Autostrategy.plan: no eligible persons found.')
return False
# ok
@@ -1591,7 +1591,7 @@ def plan(self, ids_person, logger=None, **kwargs):
map_are_fallback[ids_person_act] = are_fallback
n_plans = len(ids_person_act)
- print 'AutoStrategy.plan n_plans=', n_plans
+ print('AutoStrategy.plan n_plans=', n_plans)
# print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape
# set initial activity
# this is because the following steps start with travel
@@ -1730,7 +1730,7 @@ def plan(self, ids_person, logger=None, **kwargs):
position_edge_to=pos_edge_parking_from-1.5, # wait 1.5 m before nose of parked car
)
- print ' id_person,id_veh', id_person, id_veh
+ print(' id_person,id_veh', id_person, id_veh)
# ride from car parking to road edge near activity
id_stage_car, time, is_fallback = ridestages.append_stage(
id_plan,
@@ -1891,24 +1891,24 @@ def preevaluate(self, ids_person):
"""
n_pers = len(ids_person)
- print 'BikeStrategy.preevaluate', n_pers, 'persons'
+ print('BikeStrategy.preevaluate', n_pers, 'persons')
persons = self.get_virtualpop()
preeval = np.zeros(n_pers, dtype=np.int32)
# put -1 for persons without car access
preeval[persons.ids_ibike[ids_person] == -1] = -1
- print ' persons having no bike', len(np.flatnonzero(persons.ids_ibike[ids_person] == -1))
+ print(' persons having no bike', len(np.flatnonzero(persons.ids_ibike[ids_person] == -1)))
# put 0 for persons with bike but with a different preferred mode
preeval[(persons.ids_ibike[ids_person] > -1)
& (persons.ids_mode_preferred[ids_person] != self._id_mode_bike)] = 0
- print ' persons with bike but with a different preferred mode', len(np.flatnonzero((persons.ids_ibike[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_bike)))
+ print(' persons with bike but with a different preferred mode', len(np.flatnonzero((persons.ids_ibike[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_bike))))
# put 2 for persons with bike access and who prefer the bike
preeval[(persons.ids_ibike[ids_person] > -1)
& (persons.ids_mode_preferred[ids_person] == self._id_mode_bike)] = 2
- print ' persons with car access and who prefer the car', len(np.flatnonzero((persons.ids_ibike[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_bike)))
+ print(' persons with car access and who prefer the car', len(np.flatnonzero((persons.ids_ibike[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_bike))))
return preeval
@@ -1993,7 +1993,7 @@ def get_edge_bikeaccess(self, id_edge, is_search_backward=False, is_get_route=Fa
pos = 0.5*self.length_edge_min
if id_bikeedge == -1:
- print 'WARNING in get_edge_bikeaccess no access for', id_edge, self._edges.ids_sumo[id_edge]
+ print('WARNING in get_edge_bikeaccess no access for', id_edge, self._edges.ids_sumo[id_edge])
if is_get_route:
return id_bikeedge, pos, route
@@ -2175,7 +2175,7 @@ def plan(self, ids_person, logger=None, **kwargs):
= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
if len(ids_person_act) == 0:
- print 'WARNING in BikeStrategy.plan: no eligible persons found.'
+ print('WARNING in BikeStrategy.plan: no eligible persons found.')
return False
# ok
@@ -2205,7 +2205,7 @@ def plan(self, ids_person, logger=None, **kwargs):
#map_ids_parking_from[ids_person_act] = ids_parking_from
n_plans = len(ids_person_act)
- print 'BikeStrategy.plan n_plans=', n_plans
+ print('BikeStrategy.plan n_plans=', n_plans)
# print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape
# set initial activity
# this is because the following steps start with travel
@@ -2313,9 +2313,9 @@ def plan(self, ids_person, logger=None, **kwargs):
if logger:
logger.progress(i/n_pers*100)
i += 1.0
- print 79*'*'
- print ' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to
- print ' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to]
+ print(79*'*')
+ print(' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to)
+ print(' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to])
time = self.plan_bikeride(id_plan, time_from, id_veh,
id_edge_from, pos_edge_from,
@@ -2446,14 +2446,14 @@ def preevaluate(self, ids_person):
# put 2 for persons with car access and who prefer cars
preeval[persons.ids_mode_preferred[ids_person] == self._id_mode_taxi] = 2
- print ' TaxiStrategy.preevaluate', len(np.flatnonzero(preeval))
+ print(' TaxiStrategy.preevaluate', len(np.flatnonzero(preeval)))
return preeval
def get_edge_access(self, id_edge, is_search_backward=False, is_get_route=False, is_star=False, bstar=0, fstar=0, n_iter_acces_max=None):
# get firts edge allowing bikes and pedestrian, saving route, frontward or backward. You can include bstar or fstar:
# check only connected links. You can obtain also the route.
# print 'get_edge_bikeaccess',id_edge, is_search_backward,'id_sumo',self._edges.ids_sumo[id_edge]
- print 'get_edge_access id_edge', id_edge, 'is_search_backward', is_search_backward, 'n_iter_acces_max', self.n_iter_acces_max
+ print('get_edge_access id_edge', id_edge, 'is_search_backward', is_search_backward, 'n_iter_acces_max', self.n_iter_acces_max)
if n_iter_acces_max is None:
n_iter_acces_max = self.n_iter_acces_max
@@ -2480,15 +2480,15 @@ def get_edge_access(self, id_edge, is_search_backward=False, is_get_route=False,
ids = [id_edge]
coll_ids = [0]
route = []
- print 'start id_modeedge', id_modeedge, 'n', n, 'n_iter_acces_max', n_iter_acces_max, (id_modeedge < 0), (n < n_iter_acces_max)
+ print('start id_modeedge', id_modeedge, 'n', n, 'n_iter_acces_max', n_iter_acces_max, (id_modeedge < 0), (n < n_iter_acces_max))
while (id_modeedge < 0) & (n < n_iter_acces_max):
- print ' while id_modeedge', id_modeedge, 'n', n
+ print(' while id_modeedge', id_modeedge, 'n', n)
n += 1
ids_new = []
for id_edge_test, is_long_enough in zip(ids_current, edgelengths[ids_current] > self.length_edge_min):
- print ' check id', id_edge_test, is_long_enough, 'taxi access', get_accesslevel(id_edge_test, id_mode), 'ped access', get_accesslevel(id_edge_test, id_mode_ped)
+ print(' check id', id_edge_test, is_long_enough, 'taxi access', get_accesslevel(id_edge_test, id_mode), 'ped access', get_accesslevel(id_edge_test, id_mode_ped))
if is_long_enough & (get_accesslevel(id_edge_test, id_mode) >= 0) & (get_accesslevel(id_edge_test, id_mode_ped) >= 0):
id_modeedge = id_edge_test
@@ -2505,7 +2505,7 @@ def get_edge_access(self, id_edge, is_search_backward=False, is_get_route=False,
if is_search_backward is not True:
route.reverse()
- print ' found', id_modeedge, self._edges.ids_sumo[id_modeedge]
+ print(' found', id_modeedge, self._edges.ids_sumo[id_modeedge])
break
else:
@@ -2532,7 +2532,7 @@ def get_edge_access(self, id_edge, is_search_backward=False, is_get_route=False,
pos = 0.5*self.length_edge_min
if id_modeedge == -1:
- print 'WARNING in TaxiStrategy.get_edge_access no access at id_edge', id_edge, self._edges.ids_sumo[id_edge]
+ print('WARNING in TaxiStrategy.get_edge_access no access at id_edge', id_edge, self._edges.ids_sumo[id_edge])
if is_get_route:
return id_modeedge, pos, route
@@ -2553,7 +2553,7 @@ def plan_taxiride(self, id_plan, time_from, id_veh,
id_edge_to_taxi, pos_to_taxi = self.get_edge_access(id_edge_to, is_search_backward=True)
if (dist_from_to < dist_walk_max) | (id_edge_from_taxi == -1) | (id_edge_to_taxi == -1):
- print ' go by foot because distance is too short or no taxi access', dist_from_to, id_edge_from_taxi, id_edge_to_taxi
+ print(' go by foot because distance is too short or no taxi access', dist_from_to, id_edge_from_taxi, id_edge_to_taxi)
id_stage_walk1, time = walkstages.append_stage(
id_plan, time_from,
id_edge_from=id_edge_from,
@@ -2563,12 +2563,12 @@ def plan_taxiride(self, id_plan, time_from, id_veh,
)
else:
- print ' try to take the taxi'
+ print(' try to take the taxi')
# print ' id_edge_from_taxi',edges.ids_sumo[id_edge_from_taxi],pos_from_taxi
# print ' id_edge_to_taxi',edges.ids_sumo[id_edge_to_taxi],pos_to_taxi
if id_edge_from_taxi != id_edge_from:
- print ' must walk from origin to taxi accessible edge, time_from', time_from
+ print(' must walk from origin to taxi accessible edge, time_from', time_from)
# walk to taxi edge
id_stage_walk1, time = walkstages.append_stage(
id_plan, time_from,
@@ -2579,7 +2579,7 @@ def plan_taxiride(self, id_plan, time_from, id_veh,
)
if id_edge_to_taxi != id_edge_to:
- print ' must walk from taxi accessible edge to dest, time_from', time
+ print(' must walk from taxi accessible edge to dest, time_from', time)
# take taxi
id_stage_taxi, time = ridestages.append_stage(
id_plan, time,
@@ -2602,7 +2602,7 @@ def plan_taxiride(self, id_plan, time_from, id_veh,
)
else:
- print ' ride taxi from taxi edge to destination', time
+ print(' ride taxi from taxi edge to destination', time)
# take taxi
id_stage_taxi, time = ridestages.append_stage(
id_plan, time,
@@ -2615,9 +2615,9 @@ def plan_taxiride(self, id_plan, time_from, id_veh,
position_edge_to=pos_edge_to,
)
else:
- print ' take taxi directly from edge of origin', time_from
+ print(' take taxi directly from edge of origin', time_from)
if id_edge_to_taxi != id_edge_to:
- print ' must walk from taxi accessible destination to destination', time_from
+ print(' must walk from taxi accessible destination to destination', time_from)
id_stage_taxi, time = ridestages.append_stage(
id_plan, time_from,
@@ -2638,7 +2638,7 @@ def plan_taxiride(self, id_plan, time_from, id_veh,
position_edge_to=pos_edge_to,
)
else:
- print ' take taxi directly from origin to destination', time_from
+ print(' take taxi directly from origin to destination', time_from)
id_stage_taxi, time = ridestages.append_stage(
id_plan, time_from,
id_veh=id_veh,
@@ -2654,7 +2654,7 @@ def plan_taxiride(self, id_plan, time_from, id_veh,
# if not, for whatever reason,
# we walk from origin to destination
if id_stage_taxi == -1:
- print ' walk because no ride stage has been planned', time_from
+ print(' walk because no ride stage has been planned', time_from)
if id_stage_walk1 == -1:
# no walk stage has been planned
id_stage_walk1, time = walkstages.append_stage(
@@ -2715,7 +2715,7 @@ def plan(self, ids_person, logger=None):
= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
if len(ids_person_act) == 0:
- print 'WARNING in TaxiStrategy.plan: no eligible persons found.'
+ print('WARNING in TaxiStrategy.plan: no eligible persons found.')
return False
# ok
@@ -2745,7 +2745,7 @@ def plan(self, ids_person, logger=None):
#map_ids_parking_from[ids_person_act] = ids_parking_from
n_plans = len(ids_person_act)
- print 'TaxiStrategy.plan n_plans=', n_plans
+ print('TaxiStrategy.plan n_plans=', n_plans)
# print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape
# set initial activity
# this is because the following steps start with travel
@@ -2832,9 +2832,9 @@ def plan(self, ids_person, logger=None):
if logger:
logger.progress(i/n_pers*100)
i += 1.0
- print 79*'*'
- print ' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to
- print ' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to]
+ print(79*'*')
+ print(' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to)
+ print(' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to])
time = self.plan_taxiride(id_plan, time_from, id_veh,
id_edge_from, pos_edge_from,
@@ -2955,24 +2955,24 @@ def preevaluate(self, ids_person):
"""
n_pers = len(ids_person)
- print 'MotorcycleStrategy.preevaluate', n_pers, 'persons'
+ print('MotorcycleStrategy.preevaluate', n_pers, 'persons')
persons = self.get_virtualpop()
preeval = np.zeros(n_pers, dtype=np.int32)
# put -1 for persons without motorcycle access
preeval[persons.ids_imoto[ids_person] == -1] = -1
- print ' persons having no motorcycle', len(np.flatnonzero(persons.ids_imoto[ids_person] == -1))
+ print(' persons having no motorcycle', len(np.flatnonzero(persons.ids_imoto[ids_person] == -1)))
# put 0 for persons with motorcycle but with a different preferred mode
preeval[(persons.ids_imoto[ids_person] > -1)
& (persons.ids_mode_preferred[ids_person] != self._id_mode_moto)] = 0
- print ' persons with motorcycle but with a different preferred mode', len(np.flatnonzero((persons.ids_imoto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_moto)))
+ print(' persons with motorcycle but with a different preferred mode', len(np.flatnonzero((persons.ids_imoto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_moto))))
# put 2 for persons with motorcycle access and who prefer the car
preeval[(persons.ids_imoto[ids_person] > -1)
& (persons.ids_mode_preferred[ids_person] == self._id_mode_moto)] = 2
- print ' persons with motorcycle access and who prefer the car', len(np.flatnonzero((persons.ids_imoto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_moto)))
+ print(' persons with motorcycle access and who prefer the car', len(np.flatnonzero((persons.ids_imoto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_moto))))
return preeval
@@ -3056,7 +3056,7 @@ def get_edge_motoaccess(self, id_edge, is_search_backward=False, is_get_route=Fa
pos = 0.5*self.length_edge_min
if id_motoedge == -1:
- print 'WARNING in get_edge_motoaccess no access for', id_edge, self._edges.ids_sumo[id_edge]
+ print('WARNING in get_edge_motoaccess no access for', id_edge, self._edges.ids_sumo[id_edge])
if is_get_route:
return id_motoedge, pos, route
@@ -3238,7 +3238,7 @@ def plan(self, ids_person, logger=None):
= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
if len(ids_person_act) == 0:
- print 'WARNING in MotorcycleStrategy.plan: no eligible persons found.'
+ print('WARNING in MotorcycleStrategy.plan: no eligible persons found.')
return False
# ok
@@ -3268,7 +3268,7 @@ def plan(self, ids_person, logger=None):
#map_ids_parking_from[ids_person_act] = ids_parking_from
n_plans = len(ids_person_act)
- print 'MotorcycleStrategy.plan n_plans=', n_plans
+ print('MotorcycleStrategy.plan n_plans=', n_plans)
# print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape
# set initial activity
# this is because the following steps start with travel
@@ -3376,9 +3376,9 @@ def plan(self, ids_person, logger=None):
if logger:
logger.progress(i/n_pers*100)
i += 1.0
- print 79*'*'
- print ' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to
- print ' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to]
+ print(79*'*')
+ print(' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to)
+ print(' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to])
time = self.plan_motoride(id_plan, time_from, id_veh,
id_edge_from, pos_edge_from,
@@ -3489,7 +3489,7 @@ def preevaluate(self, ids_person):
# put 2 for persons with car access and who prefer cars
preeval[persons.ids_mode_preferred[ids_person] == self._id_mode_bus] = 2
- print ' TransitStrategy.preevaluate', len(np.flatnonzero(preeval))
+ print(' TransitStrategy.preevaluate', len(np.flatnonzero(preeval)))
return preeval
def plan_transit(self, id_plan, time_from,
@@ -3504,14 +3504,14 @@ def plan_transit(self, id_plan, time_from,
ids_laneedge, ids_stoplane, ptstops):
edges = self.get_scenario().net.edges
- print 'plan_transit id_plan', id_plan, 'id_edge_from %d (%s)' % (id_edge_from, edges.ids_sumo[id_edge_from]), 'id_edge_to %d (%s)' % (id_edge_to, edges.ids_sumo[id_edge_to])
+ print('plan_transit id_plan', id_plan, 'id_edge_from %d (%s)' % (id_edge_from, edges.ids_sumo[id_edge_from]), 'id_edge_to %d (%s)' % (id_edge_to, edges.ids_sumo[id_edge_to]))
# debug?
is_debug = False # id_plan == 14983
if is_debug:
- print ' id_stop_from', id_stop_from, 'id_stop_to', id_stop_to
+ print(' id_stop_from', id_stop_from, 'id_stop_to', id_stop_to)
ptlinks = ptlines.get_ptlinks()
ptlinktypes = ptlinks.types.choices
@@ -3527,9 +3527,9 @@ def plan_transit(self, id_plan, time_from,
time = time_from
id_stage_walk1 = None
if is_debug:
- print ' no initial walk required.'
- print ' id_edge_from', id_edge_from, edges.ids_sumo[id_edge_from]
- print ' pos_edge_from', pos_edge_from
+ print(' no initial walk required.')
+ print(' id_edge_from', id_edge_from, edges.ids_sumo[id_edge_from])
+ print(' pos_edge_from', pos_edge_from)
else:
id_stage_walk1, time = walkstages.append_stage(id_plan, time_from,
id_edge_from=id_edge_from,
@@ -3538,20 +3538,20 @@ def plan_transit(self, id_plan, time_from,
position_edge_to=pos_stop_from, # -7.0,
)
if is_debug:
- print ' add initial walk stage'
- print ' id_edge_from', id_edge_from, edges.ids_sumo[id_edge_from]
- print ' pos_edge_from', pos_edge_from
- print ' IIIInitial walk'
- print ' id_stopedge_from', id_stopedge_from, edges.ids_sumo[id_stopedge_from]
- print ' pos_stop_from', pos_stop_from
+ print(' add initial walk stage')
+ print(' id_edge_from', id_edge_from, edges.ids_sumo[id_edge_from])
+ print(' pos_edge_from', pos_edge_from)
+ print(' IIIInitial walk')
+ print(' id_stopedge_from', id_stopedge_from, edges.ids_sumo[id_stopedge_from])
+ print(' pos_stop_from', pos_stop_from)
if is_debug:
- print ' TTTransit'
- print ' id_stopedge_to', id_stopedge_to, edges.ids_sumo[id_stopedge_to]
- print ' pos_stop_to', pos_stop_to
- print ' ----------------------------------'
- print ' id_stop_from', id_stop_from
- print ' id_stop_to', id_stop_to
+ print(' TTTransit')
+ print(' id_stopedge_to', id_stopedge_to, edges.ids_sumo[id_stopedge_to])
+ print(' pos_stop_to', pos_stop_to)
+ print(' ----------------------------------')
+ print(' id_stop_from', id_stop_from)
+ print(' id_stop_to', id_stop_to)
durations, linktypes, ids_line, ids_fromstop, ids_tostop =\
ptlinks.route(id_stop_from, id_stop_to,
@@ -3560,12 +3560,12 @@ def plan_transit(self, id_plan, time_from,
stops_to_exit=stops_to_exit)
if is_debug:
- print ' routing done. make plan, success', len(linktypes) > 0
+ print(' routing done. make plan, success', len(linktypes) > 0)
if is_debug:
- print ' ids_line ', ids_line
- print ' ids_fromstop', ids_fromstop
- print ' ids_tostop ', ids_tostop
+ print(' ids_line ', ids_line)
+ print(' ids_fromstop', ids_fromstop)
+ print(' ids_tostop ', ids_tostop)
if (type_transit in linktypes): # is there any public transport line to take?
@@ -3584,7 +3584,7 @@ def plan_transit(self, id_plan, time_from,
# check if initial walk needs to be modified
if (id_stage_walk1 is not None) & (linktypes[0] == type_walk):
if is_debug:
- print ' Modify initial walk from stop fromedge %d (%s) toedge %d (%s)' % (id_edge_from, edges.ids_sumo[id_edge_from], ids_stopedge_from[0], edges.ids_sumo[ids_stopedge_from[0]])
+ print(' Modify initial walk from stop fromedge %d (%s) toedge %d (%s)' % (id_edge_from, edges.ids_sumo[id_edge_from], ids_stopedge_from[0], edges.ids_sumo[ids_stopedge_from[0]]))
is_initial_walk_done = True
time = walkstages.modify_stage(
@@ -3601,7 +3601,7 @@ def plan_transit(self, id_plan, time_from,
for i, linktype, id_line, duration,\
id_stopedge_from, pos_fromstop,\
id_stopedge_to, pos_tostop in\
- zip(xrange(len(linktypes)),
+ zip(range(len(linktypes)),
linktypes,
ids_line,
durations,
@@ -3609,16 +3609,16 @@ def plan_transit(self, id_plan, time_from,
ids_stopedge_to, poss_stop_to,
):
if is_debug:
- print ' ...........................'
- print ' stage for linktype %2d fromedge %s toedge %s' % (linktype, edges.ids_sumo[id_stopedge_from], edges.ids_sumo[id_stopedge_to])
- print ' id_stopedge_from,id_stopedge_to', id_stopedge_from, id_stopedge_to
+ print(' ...........................')
+ print(' stage for linktype %2d fromedge %s toedge %s' % (linktype, edges.ids_sumo[id_stopedge_from], edges.ids_sumo[id_stopedge_to]))
+ print(' id_stopedge_from,id_stopedge_to', id_stopedge_from, id_stopedge_to)
if linktype == type_transit: # transit!
# check if last link type has also been a transit
if i > 0:
if linktypes[i-1] == type_transit:
if is_debug:
- print ' add inter-transit walk stage'
+ print(' add inter-transit walk stage')
# introdice a walk stage to be sure that
# person gets to the middle of the stop
id_stage_transfer, time = walkstages.append_stage(
@@ -3631,7 +3631,7 @@ def plan_transit(self, id_plan, time_from,
)
if is_debug:
- print ' add transit stage id_line', id_line
+ print(' add transit stage id_line', id_line)
id_stage_transit, time = transitstages.append_stage(
id_plan, time,
id_line=id_line,
@@ -3644,7 +3644,7 @@ def plan_transit(self, id_plan, time_from,
elif (linktype == type_walk) & ((i > 0) | (not is_initial_walk_done)):
# walk to transfer, no initial walk if done
if is_debug:
- print ' add walk to transfer'
+ print(' add walk to transfer')
id_stage_transfer, time = walkstages.append_stage(
id_plan, time,
id_edge_from=id_stopedge_from,
@@ -3658,18 +3658,18 @@ def plan_transit(self, id_plan, time_from,
else: # all other link time are no modelld
# do not do anything , just add wait time to next stage
if is_debug:
- print ' do noting add duration', duration
+ print(' do noting add duration', duration)
duration_wait += duration
# walk from final stop to activity
i = len(linktypes)-1 # last link index
if is_debug:
- print ' linktypes', linktypes, 'i', i, 'linktypes[i]', linktypes[i], linktypes[i] == type_walk
+ print(' linktypes', linktypes, 'i', i, 'linktypes[i]', linktypes[i], linktypes[i] == type_walk)
if linktypes[i] == type_walk:
if is_debug:
- print ' Modify final walk from stop fromedge %d (%s) toedge %d (%s)' % (id_stopedge_to, edges.ids_sumo[id_stopedge_to], id_edge_to, edges.ids_sumo[id_edge_to])
+ print(' Modify final walk from stop fromedge %d (%s) toedge %d (%s)' % (id_stopedge_to, edges.ids_sumo[id_stopedge_to], id_edge_to, edges.ids_sumo[id_edge_to]))
time = walkstages.modify_stage(
id_stage_transfer,
@@ -3681,7 +3681,7 @@ def plan_transit(self, id_plan, time_from,
else:
if is_debug:
- print ' Add final walk stage fromedge %d (%s) toedge %d (%s)' % (id_stopedge_to, edges.ids_sumo[id_stopedge_to], id_edge_to, edges.ids_sumo[id_edge_to])
+ print(' Add final walk stage fromedge %d (%s) toedge %d (%s)' % (id_stopedge_to, edges.ids_sumo[id_stopedge_to], id_edge_to, edges.ids_sumo[id_edge_to]))
id_stage_walk2, time = walkstages.append_stage(id_plan, time,
id_edge_from=id_stopedge_to,
@@ -3693,7 +3693,7 @@ def plan_transit(self, id_plan, time_from,
else:
# there is no public transport line linking these nodes.
if is_debug:
- print ' No PT lines used create direct walk stage'
+ print(' No PT lines used create direct walk stage')
if id_stage_walk1 is None:
# Create first walk directly from home to activity
@@ -3720,7 +3720,7 @@ def plan(self, ids_person, logger=None, **kwargs):
Generates a plan for these person according to this strategie.
Overriden by specific strategy.
"""
- print 'TransitStrategy.plan', len(ids_person)
+ print('TransitStrategy.plan', len(ids_person))
#make_plans_private(self, ids_person = None, mode = 'passenger')
# routing necessary?
virtualpop = self.get_virtualpop()
@@ -3752,12 +3752,12 @@ def plan(self, ids_person, logger=None, **kwargs):
# print ' demand.virtualpop',demand.virtualpop,dir(demand.virtualpop)
# print ' demand.trips',demand.trips,dir(demand.trips)
if len(ptlines) == 0:
- print 'WARNING in TrasitStrategy.plan: no transit services available. Create public trasit services by connecting stops.'
+ print('WARNING in TrasitStrategy.plan: no transit services available. Create public trasit services by connecting stops.')
return False
ptlinks = ptlines.get_ptlinks()
if len(ptlinks) == 0:
- print 'WARNING in TrasitStrategy.plan: no public transport links. Run methods: "create routes" and "build links" from public trasport services.'
+ print('WARNING in TrasitStrategy.plan: no public transport links. Run methods: "create routes" and "build links" from public trasport services.')
return False
ptlinktypes = ptlinks.types.choices
@@ -3779,7 +3779,7 @@ def plan(self, ids_person, logger=None, **kwargs):
= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
if len(ids_person_act) == 0:
- print 'WARNING in TrasitStrategy.plan: no eligible persons found.'
+ print('WARNING in TrasitStrategy.plan: no eligible persons found.')
return False
# temporary maps from ids_person to other parameters
@@ -3798,7 +3798,7 @@ def plan(self, ids_person, logger=None, **kwargs):
map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]
n_plans = len(ids_person_act)
- print 'TrasitStrategy.plan n_plans=', n_plans
+ print('TrasitStrategy.plan n_plans=', n_plans)
# make initial activity stage
ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]
@@ -3883,8 +3883,8 @@ def plan(self, ids_person, logger=None, **kwargs):
if logger:
logger.progress(i/n_pers*100)
i += 1.0
- print 79*'_'
- print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)
+ print(79*'_')
+ print(' id_plan=%d, id_person=%d, ' % (id_plan, id_person))
time = self.plan_transit(id_plan, time_from,
id_edge_from, pos_edge_from,
@@ -3973,7 +3973,7 @@ def preevaluate(self, ids_person):
# put 2 for persons with bike access and who prefer bike or bus
preeval[inds_avail & inds_prefer] = 1
- print ' BikeTransitStrategy.preevaluate', len(np.flatnonzero(preeval))
+ print(' BikeTransitStrategy.preevaluate', len(np.flatnonzero(preeval)))
return preeval
def plan(self, ids_person, logger=None, **kwargs):
@@ -3981,7 +3981,7 @@ def plan(self, ids_person, logger=None, **kwargs):
Generates a plan for these person according to this strategie.
Overriden by specific strategy.
"""
- print 'TransitStrategy.plan', len(ids_person)
+ print('TransitStrategy.plan', len(ids_person))
#make_plans_private(self, ids_person = None, mode = 'passenger')
# routing necessary?
virtualpop = self.get_virtualpop()
@@ -4014,7 +4014,7 @@ def plan(self, ids_person, logger=None, **kwargs):
# print ' demand.virtualpop',demand.virtualpop,dir(demand.virtualpop)
# print ' demand.trips',demand.trips,dir(demand.trips)
if len(ptlines) == 0:
- print 'WARNING in TrasitStrategy.plan: no transit services available.'
+ print('WARNING in TrasitStrategy.plan: no transit services available.')
return False
ptlinks = ptlines.get_ptlinks()
@@ -4037,7 +4037,7 @@ def plan(self, ids_person, logger=None, **kwargs):
= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
if len(ids_person_act) == 0:
- print 'WARNING in TrasitStrategy.plan: no eligible persons found.'
+ print('WARNING in TrasitStrategy.plan: no eligible persons found.')
return False
# temporary maps from ids_person to other parameters
@@ -4056,7 +4056,7 @@ def plan(self, ids_person, logger=None, **kwargs):
map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]
n_plans = len(ids_person_act)
- print 'TrasitStrategy.plan n_plans=', n_plans
+ print('TrasitStrategy.plan n_plans=', n_plans)
# make initial activity stage
ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]
@@ -4149,8 +4149,8 @@ def plan(self, ids_person, logger=None, **kwargs):
if logger:
logger.progress(i/n_pers*100)
i += 1.0
- print 79*'_'
- print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)
+ print(79*'_')
+ print(' id_plan=%d, id_person=%d, ' % (id_plan, id_person))
#dist_from_stop_from, dist_stop_to_to
time = self.plan_bikeride(id_plan, time_from, id_veh,
@@ -4291,8 +4291,8 @@ def _set_colors_default(self):
'motorcycle': np.array([170, 200, 0, 220], np.float32)/255,
'taxi': np.array([40, 240, 240, 220], np.float32)/255,
}
- ids = self.names.get_ids_from_indices_save(colors_default.keys())
- self.colors[ids] = colors_default.values() # np.array(colors_default.values(), np.float32).reshape(-1,4)
+ ids = self.names.get_ids_from_indices_save(list(colors_default.keys()))
+ self.colors[ids] = list(colors_default.values()) # np.array(colors_default.values(), np.float32).reshape(-1,4)
#self.colors.indexset(colors_default.keys(), colors_default.values())
@@ -4323,14 +4323,14 @@ def preevaluate(self, ids_person):
2 : Strategy uses predomunantly preferred mode
"""
- print 'preevaluate strategies'
+ print('preevaluate strategies')
ids_strat = self.get_ids()
n_pers = len(ids_person)
n_strat = len(ids_strat)
preeval = np.zeros((n_pers, n_strat), dtype=np.int32)
- for i, strategy in zip(range(n_strat), self.strategies[ids_strat]):
- print ' preevaluate strategiy', strategy.ident
+ for i, strategy in zip(list(range(n_strat)), self.strategies[ids_strat]):
+ print(' preevaluate strategiy', strategy.ident)
preeval[i, :] = strategy.preevaluate(ids_person)
return ids_strat, preeval
@@ -4389,7 +4389,7 @@ def get_ids_from_ids_plan(self, ids_plan):
ids = self.get_ids()
#ids_plan_part = self.ids_plan[ids]
are_selected = np.zeros(len(ids), dtype=np.bool)
- for ind, id_plan_part in zip(xrange(len(ids)), self.ids_plan[ids]):
+ for ind, id_plan_part in zip(range(len(ids)), self.ids_plan[ids]):
are_selected[ind] = id_plan_part in ids_plan
return ids[are_selected]
# print ' ids_plan_part',type(ids_plan_part),ids_plan_part
@@ -4437,9 +4437,9 @@ def get_times(self, id_mode):
Returns a vector mapping id_edge to edge travel times
for given mode id_mode
"""
- print 'get_times', self._timesmap.keys()
+ print('get_times', list(self._timesmap.keys()))
- if not self._timesmap.has_key(id_mode):
+ if id_mode not in self._timesmap:
edges = self.get_virtualpop().get_scenario().net.edges
self._timesmap[id_mode] = edges.get_times(id_mode=id_mode,
is_check_lanes=True,
@@ -4452,9 +4452,9 @@ def get_distances(self, id_mode):
Returns a vector mapping id_edge to edge distances
for given mode id_mode
"""
- print 'get_distances', self._distancesmap.keys()
+ print('get_distances', list(self._distancesmap.keys()))
- if not self._distancesmap.has_key(id_mode):
+ if id_mode not in self._distancesmap:
edges = self.get_virtualpop().get_scenario().net.edges
self._distancesmap[id_mode] = edges.get_distances(id_mode=id_mode,
is_check_lanes=True,
@@ -4467,9 +4467,9 @@ def get_fstar(self, id_mode, is_return_arrays=True, is_ignor_connections=False)
Returns a fstar
for given mode id_mode
"""
- print 'get_fstar', self._fstarmap.keys()
+ print('get_fstar', list(self._fstarmap.keys()))
- if not self._fstarmap.has_key(id_mode):
+ if id_mode not in self._fstarmap:
edges = self.get_virtualpop().get_scenario().net.edges
self._fstarmap[id_mode] = edges.get_fstar(id_mode=id_mode,
is_ignor_connections=is_ignor_connections,
@@ -4659,13 +4659,13 @@ def append_stage(self, id_plan, id_mode,
If not feasible -1 and start time will be returned.
"""
- print 'Rides.append_stage id_plan', id_plan, is_fallback
+ print('Rides.append_stage id_plan', id_plan, is_fallback)
route, dist, duration, is_fallback = self.get_route_between_parking(
id_parking_from, id_parking_to, id_mode,
is_fallback, id_mode_fallback,)
- print ' after routing: is_fallback', is_fallback, 'route', route
+ print(' after routing: is_fallback', is_fallback, 'route', route)
if (len(route) > 0): # |(dist > self.dist_ride_min.get_value()): # is there a connection
# create stage
@@ -4697,7 +4697,7 @@ def get_route_between_parking(self, id_parking_from, id_parking_to, id_mode,
"""
- print 'get_route_between_parking', id_parking_from, id_parking_to, 'is_fallback', is_fallback, 'id_mode_fallback', id_mode_fallback
+ print('get_route_between_parking', id_parking_from, id_parking_to, 'is_fallback', is_fallback, 'id_mode_fallback', id_mode_fallback)
scenario = self.get_virtualpop().get_scenario()
edges = scenario.net.edges
lanes = scenario.net.lanes
@@ -4711,11 +4711,11 @@ def get_route_between_parking(self, id_parking_from, id_parking_to, id_mode,
pos_from, pos_to = parking.positions[[id_parking_from, id_parking_to]]
if is_fallback & (id_mode_fallback is not None):
- print ' use id_mode_fallback', id_mode_fallback
+ print(' use id_mode_fallback', id_mode_fallback)
id_mode_current = id_mode_fallback
else:
- print ' use id_mode', id_mode
+ print(' use id_mode', id_mode)
id_mode_current = id_mode
# print ' id_edge_from, id_edge_to=',id_edge_from, id_edge_to
@@ -4729,7 +4729,7 @@ def get_route_between_parking(self, id_parking_from, id_parking_to, id_mode,
if (len(route) == 0) & (not is_fallback) & (id_mode_fallback is not None):
is_fallback = True
id_mode_current = id_mode_fallback
- print ' no route found with normal mode, try fallback', is_fallback
+ print(' no route found with normal mode, try fallback', is_fallback)
# now retry with fallback
duration_approx, route = routing.get_mincostroute_edge2edge(
id_edge_from,
@@ -4738,7 +4738,7 @@ def get_route_between_parking(self, id_parking_from, id_parking_to, id_mode,
fstar=self.get_fstar(id_mode_current),
)
if len(route) > 0:
- print ' fallback has been successful'
+ print(' fallback has been successful')
# here is a big problem: starting with the successive node of edge_from
# may result that the first edge of the route is not connected with edge_from
@@ -4762,7 +4762,7 @@ def get_route_between_parking(self, id_parking_from, id_parking_to, id_mode,
# return str(self.ids_veh[id_stage])+'.'+str(i_ride)
def get_writexmlinfo(self, ids_plan, is_route=True, is_plain=False):
- print 'AutorideStages.get_writexmlinfo', len(ids_plan), is_route, 'is_plain', is_plain
+ print('AutorideStages.get_writexmlinfo', len(ids_plan), is_route, 'is_plain', is_plain)
iautos = self.get_virtualpop().get_iautos()
writefunc = iautos.prepare_write_xml(is_route, is_plain)
@@ -4936,7 +4936,7 @@ def append_stage(self, id_plan, time_start=-1.0, id_veh=-1,
return -1, time_start # no stage creation took place
def get_writexmlinfo(self, ids_plan, is_route=True, is_plain=False):
- print 'BikerideStages.get_writexmlinfo', len(ids_plan), is_plain
+ print('BikerideStages.get_writexmlinfo', len(ids_plan), is_plain)
ibikes = self.get_virtualpop().get_ibikes()
bikewritefunc = ibikes.prepare_write_xml(is_plain=is_plain)
ids = self.get_ids_from_ids_plan(ids_plan)
@@ -5110,7 +5110,7 @@ def append_stage(self, id_plan, time_start=-1.0, id_veh=-1,
return -1, time_start # no stage creation took place
def get_writexmlinfo(self, ids_plan, is_route=True, is_plain=False):
- print 'MotorcyclerideStages.get_writexmlinfo', len(ids_plan), is_plain
+ print('MotorcyclerideStages.get_writexmlinfo', len(ids_plan), is_plain)
imotos = self.get_virtualpop().get_imotos()
motowritefunc = imotos.prepare_write_xml(is_plain=is_plain)
ids = self.get_ids_from_ids_plan(ids_plan)
@@ -5324,7 +5324,7 @@ def append_stage(self, id_plan, time_start=-1.0,
position_edge_from=0.1, position_edge_to=0.0,
**kwargs):
# print 'WalkStages.append_stage',id_stage
- if kwargs.has_key('duration'):
+ if 'duration' in kwargs:
duration = kwargs['duration']
else:
dist, duration = self.plan_walk(id_edge_from, id_edge_to,
@@ -5652,7 +5652,7 @@ def _init_constants(self):
pass
def clear_plans(self):
- print 'Plans.clear_plans'
+ print('Plans.clear_plans')
for stagetable in self.get_stagetables():
# print ' stagetable',stagetable
stagetable.clear()
@@ -5918,7 +5918,7 @@ def clear_population(self):
self.clear_rows()
def del_persons(self, ids_pers_delete):
- print 'delete', len(ids_pers_delete), 'persons'
+ print('delete', len(ids_pers_delete), 'persons')
ids_plans_all = set()
ids_activity_del = set()
lists_ids_plan = self.lists_ids_plan[ids_pers_delete]
@@ -5967,7 +5967,7 @@ def clear_ivehicles(self):
"""
Clear all individually owned vehicles.
"""
- print 'clear_ivehicles'
+ print('clear_ivehicles')
self.get_iautos().clear_vehicles()
self.get_ibikes().clear_vehicles()
self.get_imotos().clear_vehicles()
@@ -6009,7 +6009,7 @@ def get_ptstops(self):
return self.get_net().ptstops
def get_id_sumo_from_id(self, id_sumo):
- return u'vp.%s' % id_sumo
+ return 'vp.%s' % id_sumo
def get_id_from_id_sumo(self, id_veh_sumo):
if len(id_veh_sumo.split('.')) == 2:
@@ -6098,9 +6098,9 @@ def disaggregate_odflow(self, time_start, time_end, id_mode,
"""
tripnumber = int(scale*tripnumber_tot)
- print 'disaggregate_odflow', time_start, time_end, id_mode, tripnumber
+ print('disaggregate_odflow', time_start, time_end, id_mode, tripnumber)
- print ' id_activitytype_orig,id_activitytype_dest', id_activitytype_orig, id_activitytype_dest
+ print(' id_activitytype_orig,id_activitytype_dest', id_activitytype_orig, id_activitytype_dest)
# print ' probs_orig',sum(probs_fac_orig)#,'\n',probs_fac_orig
# print ' probs_dest',sum(probs_fac_dest)#,'\n',probs_fac_dest
@@ -6195,7 +6195,7 @@ def disaggregate_odflow(self, time_start, time_end, id_mode,
return ids_person
else:
- print 'WARNING in disaggregate_odflow: no probabilities', np.sum(probs_fac_orig), np.sum(probs_fac_dest)
+ print('WARNING in disaggregate_odflow: no probabilities', np.sum(probs_fac_orig), np.sum(probs_fac_dest))
return []
@@ -6208,7 +6208,7 @@ def create_pop_from_odflows(self, is_use_landusetypes=False, **kwargs):
if landusetype_orig and landusetype_dest also landuse types
of facilities of origin and destination are taken into account.
"""
- print 'create_pop_from_odflows'
+ print('create_pop_from_odflows')
demand = self.parent
odflowtab = demand.odintervals.generate_odflows()
@@ -6320,7 +6320,7 @@ def create_pop_from_odflows(self, is_use_landusetypes=False, **kwargs):
# return odflowtab
def add_plans(self, ids_person, id_strategy=-1):
- print 'add_plans n, id_strategy', len(ids_person), id_strategy
+ print('add_plans n, id_strategy', len(ids_person), id_strategy)
n_plans = len(ids_person)
# print ' get_plans',self.get_plans()
# print ' stagetables',self.get_plans().get_stagetables().get_ident_abs()
@@ -6361,7 +6361,7 @@ def plan_with_strategy(self, id_strategy, evalcrit=0, is_plan_no_preferred=False
# if id_strat_pers
ids_person_preeval = ids_person[inds_preeval]
- print 'plan_with_strategy', strategy.ident, 'n_pers', len(ids_person_preeval)
+ print('plan_with_strategy', strategy.ident, 'n_pers', len(ids_person_preeval))
# TODO: is_substitute = is_substitute could be an argument to plan()
# and then passed to the centralized add_plan() method of the VP.
@@ -6444,7 +6444,7 @@ def select_plans_preferred_mode(self, fraction=0.1, **kwargs):
ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]
n_pers = len(ids_pers)
preevals = -1*np.ones((np.max(ids_pers)+1, np.max(ids_strat)+1), dtype=np.int32)
- for ind, id_strategy, strategy in zip(range(n_strat), ids_strat, strategies.strategies[ids_strat]):
+ for ind, id_strategy, strategy in zip(list(range(n_strat)), ids_strat, strategies.strategies[ids_strat]):
preevals[ids_pers, id_strategy] = strategy.preevaluate(ids_pers)
preferred = 2
@@ -6453,10 +6453,10 @@ def select_plans_preferred_mode(self, fraction=0.1, **kwargs):
for id_pers, ids_plan in zip(ids_pers, self.lists_ids_plan[ids_pers]):
if ids_plan is not None:
if len(ids_plan) > 0:
- print ' id_pers,ids_plan', id_pers, ids_plan
- print ' ids_strat, preeval', plans.ids_strategy[ids_plan], preevals[id_pers, plans.ids_strategy[ids_plan]]
+ print(' id_pers,ids_plan', id_pers, ids_plan)
+ print(' ids_strat, preeval', plans.ids_strategy[ids_plan], preevals[id_pers, plans.ids_strategy[ids_plan]])
inds_sel = np.flatnonzero(preevals[id_pers, plans.ids_strategy[ids_plan]] == preferred)
- print ' inds_sel', inds_sel, inds_sel.dtype
+ print(' inds_sel', inds_sel, inds_sel.dtype)
if len(inds_sel) > 0:
#ids_plan_sel = np.array(ids_plan)[inds_sel]
# print ' ids_plan_sel',ids_plan_sel
@@ -6485,7 +6485,7 @@ def select_plans_min_time_est(self, fraction=1.0, timedev=-1.0, c_probit=-1.0, *
times_rand = np.random.normal(0.0, timedev, len(ids_plan))
elif c_probit > 0:
times_rand = np.zeros(len(ids_plan), dtype=np.float32)
- for i, t in zip(xrange(len(ids_plan)), times_est[ids_plan]):
+ for i, t in zip(range(len(ids_plan)), times_est[ids_plan]):
times_rand[i] = np.random.normal(0.0, c_probit * t, 1)
else:
@@ -6500,13 +6500,13 @@ def select_plans_random(self, fraction=0.1, **kwargs):
"""
ids_pers_all = self.get_ids()
- print 'select_plans_random', len(ids_pers_all), fraction
+ print('select_plans_random', len(ids_pers_all), fraction)
times_est = self.get_plans().times_est
# self.ids_plan.reset()
# ids_mode[random_choice(n,shares/np.sum(shares))]
ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]
- print ' ids_pers', ids_pers
+ print(' ids_pers', ids_pers)
for id_pers, ids_plan in zip(ids_pers, self.lists_ids_plan[ids_pers]):
if len(ids_plan) > 0:
# print ' id_pers,ids_plan',id_pers,ids_plan
@@ -6531,7 +6531,7 @@ def select_plans_min_time_exec(self, fraction=0.1, timedev=-1, c_probit=-1, **kw
times_rand = np.random.normal(0.0, timedev, len(ids_plan))
elif c_probit > 0:
times_rand = np.zeros(len(ids_plan), dtype=np.float32)
- for i, t in zip(xrange(len(ids_plan)), times_exec[ids_plan]):
+ for i, t in zip(range(len(ids_plan)), times_exec[ids_plan]):
times_rand[i] = np.random.normal(0.0, c_probit * t, 1)
else:
@@ -6576,11 +6576,11 @@ def select_plans_min_time_exec_est(self, fraction=0.1, timedev=-1, c_probit=-1,
elif c_probit > 0:
if len(ids_plan_est) > 0:
times_rand_est = np.zeros(len(ids_plan_est), dtype=np.float32)
- for i, t in zip(xrange(len(ids_plan_est)), times_est[ids_plan_est]):
+ for i, t in zip(range(len(ids_plan_est)), times_est[ids_plan_est]):
times_rand_est[i] = np.random.normal(0.0, c_probit * t, 1)
if len(ids_plan_exec) > 0:
times_rand_exec = np.zeros(len(ids_plan_exec), dtype=np.float32)
- for i, t in zip(xrange(len(ids_plan_exec)), times_exec[ids_plan_exec]):
+ for i, t in zip(range(len(ids_plan_exec)), times_exec[ids_plan_exec]):
times_rand_exec[i] = np.random.normal(0.0, c_probit * t, 1)
else:
@@ -6604,7 +6604,7 @@ def select_plans_min_time_exec_est(self, fraction=0.1, timedev=-1, c_probit=-1,
self.ids_plan[id_pers] = np.array(ids_plan_exec)[np.argmin(
times_exec[ids_plan_exec]+times_rand_exec)]
- print 'were analyzed %d persons' % (n_analyzed_persons)
+ print('were analyzed %d persons' % (n_analyzed_persons))
return True
def select_plans_next(self, fraction=0.1, **kwargs):
@@ -6645,7 +6645,7 @@ def select_plans_utility_function(self, fraction=0.1, timedev=-1, c_probit=-1,
plans = self.get_plans()
ids_pers_all = self.get_ids()
- print 'select_plans_utility_function', len(ids_pers_all)
+ print('select_plans_utility_function', len(ids_pers_all))
ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]
times_exec = self.get_plans().times_exec
@@ -6710,7 +6710,7 @@ def get_writexmlinfo(self, is_route=False, is_plain=False, **kwargs):
Method used to sort trips when exporting to route or trip xml file
"""
- print 'Virtualpop.get_writexmlinfo is_plain', is_plain
+ print('Virtualpop.get_writexmlinfo is_plain', is_plain)
plans = self.get_plans()
ids_pers = self.select_ids(self.ids_plan.get_value() >= 0)
@@ -6741,9 +6741,9 @@ def get_writexmlinfo(self, is_route=False, is_plain=False, **kwargs):
writefuncs_pers[:] = self.write_person_xml
# assemble vectors
- print ' times_depart_pers.shape', times_depart_pers.shape
- print ' times_depart_bike.shape', times_depart_bike.shape
- print ' times_depart_auto.shape', times_depart_auto.shape
+ print(' times_depart_pers.shape', times_depart_pers.shape)
+ print(' times_depart_bike.shape', times_depart_bike.shape)
+ print(' times_depart_auto.shape', times_depart_auto.shape)
times_depart = np.concatenate((times_depart_pers,
times_depart_auto,
times_depart_bike,
@@ -6850,7 +6850,7 @@ def update_results(self, personresults):
"""
ids_res = personresults.get_ids()
- print 'update_results', len(ids_res)
+ print('update_results', len(ids_res))
ids_person = personresults.ids_person[ids_res]
ids_plan = self.ids_plan[ids_person]
self.get_plans().times_exec[ids_plan] = personresults.times_travel_total[ids_res]
@@ -6864,7 +6864,7 @@ def import_routes_xml(self, filepath, is_clear_trips=False,
"""Reads route information of vehicles, and overwrites existing routes in stages.
Used for example read results from Duaiterate process.
"""
- print 'Virtualop.import_routes_xml from %s' % (filepath)
+ print('Virtualop.import_routes_xml from %s' % (filepath))
if is_clear_trips:
self.clear_trips()
@@ -6873,11 +6873,11 @@ def import_routes_xml(self, filepath, is_clear_trips=False,
reader = RouteReaderVp(self, counter)
if 1: # try:
parse(filepath, reader)
- print ' call make_routes', is_generate_ids, 'is_add', is_add
+ print(' call make_routes', is_generate_ids, 'is_add', is_add)
reader.insert_routes(ids_strategy=ids_strategy)
else: # except KeyError:
- print >> sys.stderr, "Error: Problems with reading routes!"
+ print("Error: Problems with reading routes!", file=sys.stderr)
raise
@@ -6890,7 +6890,7 @@ def __init__(self, ident='vpduarouter', virtualpop=None,
is_export_trips=True,
logger=None,
**kwargs):
- print 'DuarouterVp.__init__ '
+ print('DuarouterVp.__init__ ')
self._init_common(ident, name='Virtual Population DUA router',
parent=virtualpop,
@@ -6908,7 +6908,7 @@ def __init__(self, ident='vpduarouter', virtualpop=None,
if routefilepaths is None:
routefilepaths = demand.get_routefilepath()
- print ' default routefilepaths', routefilepaths
+ print(' default routefilepaths', routefilepaths)
self.add_option('routefilepaths', routefilepaths,
groupnames=['files'],
cml='--route-files',
@@ -6931,7 +6931,7 @@ def __init__(self, ident='vpduarouter', virtualpop=None,
# for id_strat, name_strat in zip(ids_strat, strategies.names[ids_strat]):
# strategychoices[name_strat] = id_strat
strategychoices = strategies.names.get_indexmap()
- self.ids_strategy = attrsman.add(cm.ListConf('ids_strategy', kwargs.get('ids_strategy', strategychoices.values()),
+ self.ids_strategy = attrsman.add(cm.ListConf('ids_strategy', kwargs.get('ids_strategy', list(strategychoices.values())),
choices=strategychoices,
groupnames=['options'],
name='Rerouted strategies',
@@ -6999,9 +6999,9 @@ def do(self):
self.run_cml(cml)
if self.status == 'success':
- print ' DUA routing done.'
+ print(' DUA routing done.')
if os.path.isfile(self.outfilepath):
- print ' outfile exists, start importing routes'
+ print(' outfile exists, start importing routes')
virtualpop.import_routes_xml(self.outfilepath, ids_strategy=self.ids_strategy)
return True
@@ -7014,7 +7014,7 @@ class RouteReaderVp(RouteReader):
def insert_routes(self, ids_strategy=None):
virtualpop = self._trips # parent is called trips here need to be changed
- print 'RouteReaderVp.insert_routes found %d routes.' % (len(self.ids_sumo))
+ print('RouteReaderVp.insert_routes found %d routes.' % (len(self.ids_sumo)))
plans = virtualpop.get_plans()
strategies = virtualpop.get_strategies()
id_strat_auto = strategies.names.get_id_from_index('auto')
@@ -7034,7 +7034,7 @@ def insert_routes(self, ids_strategy=None):
# print ' before:',stages.ids_edges[id_stage]
if stages.ids_edges[id_stage] != ids_edge:
n_change_route += 1
- print ' route change of id_veh', id_veh, 'id_stage', id_stage
+ print(' route change of id_veh', id_veh, 'id_stage', id_stage)
stages.ids_edges[id_stage] = ids_edge
# print ' after :',stages.ids_edges[id_stage]
@@ -7048,7 +7048,7 @@ def insert_routes(self, ids_strategy=None):
# print ' before:',stages.ids_edges[id_stage]
if stages.ids_edges[id_stage] != ids_edge:
n_change_route += 1
- print ' route change of id_veh', id_veh, 'id_stage', id_stage
+ print(' route change of id_veh', id_veh, 'id_stage', id_stage)
stages.ids_edges[id_stage] = ids_edge
# print ' after :',stages.ids_edges[id_stage]
@@ -7062,15 +7062,15 @@ def insert_routes(self, ids_strategy=None):
# print ' before:',stages.ids_edges[id_stage]
if stages.ids_edges[id_stage] != ids_edge:
n_change_route += 1
- print ' route change of id_veh', id_veh, 'id_stage', id_stage
+ print(' route change of id_veh', id_veh, 'id_stage', id_stage)
stages.ids_edges[id_stage] = ids_edge
# print ' after :',stages.ids_edges[id_stage]
- print ' RouteReaderVp: Total number of changed routes:', n_change_route
+ print(' RouteReaderVp: Total number of changed routes:', n_change_route)
class PopGenerator(Process):
def __init__(self, ident='virtualpopgenerator', virtualpop=None, logger=None, **kwargs):
- print 'PopFromOdfGenerator.__init__ ', ident, virtualpop
+ print('PopFromOdfGenerator.__init__ ', ident, virtualpop)
# TODO: let this be independent, link to it or child??
#
@@ -7170,7 +7170,7 @@ def __init__(self, ident='virtualpopgenerator', virtualpop=None, logger=None, *
#self.modeshares = attrsman.add( cm.ObjConf(ModeShares('modeshares',self,scenario.net.modes),groupnames = ['options']) )
def do(self):
- print 'PopGenerator.do'
+ print('PopGenerator.do')
# links
virtualpop = self.parent
@@ -7186,7 +7186,7 @@ def do(self):
ids_fac = facilities.get_ids()
map_id_edge_to_ids_fac = {}
for id_fac, id_edge in zip(ids_fac, facilities.ids_roadedge_closest[ids_fac]):
- if map_id_edge_to_ids_fac.has_key(id_edge):
+ if id_edge in map_id_edge_to_ids_fac:
map_id_edge_to_ids_fac[id_edge].append(id_fac)
else:
map_id_edge_to_ids_fac[id_edge] = [id_fac, ]
@@ -7250,7 +7250,7 @@ def do(self):
# id_from_check = btree[id_from_check]
# #print ' id_edge = ',id_from_check
# print ' success = ',id_from_check==id_edge_to
- if map_id_edge_to_ids_fac.has_key(id_edge_from):
+ if id_edge_from in map_id_edge_to_ids_fac:
ids_fac_lim += map_id_edge_to_ids_fac[id_edge_from]
if len(ids_fac_lim) == 0:
@@ -7259,7 +7259,7 @@ def do(self):
# this will reduce travel time
for id_edge_from in ids_edge_from:
# verify if id_edge_from has facilities.
- while not map_id_edge_to_ids_fac.has_key(id_edge_from):
+ while id_edge_from not in map_id_edge_to_ids_fac:
# print ' no facility, go backward'
id_edge_from = btree[id_edge_from]
@@ -7343,7 +7343,7 @@ def get_ttb(self, ids_pers):
class PopFromOdfGenerator(Process):
def __init__(self, ident, virtualpop, logger=None, **kwargs):
- print 'PopFromOdfGenerator.__init__'
+ print('PopFromOdfGenerator.__init__')
# TODO: let this be independent, link to it or child??
@@ -7417,7 +7417,7 @@ def __init__(self, ident, virtualpop, logger=None, **kwargs):
))
def do(self):
- print 'PopFromOdfGenerator.do'
+ print('PopFromOdfGenerator.do')
# links
virtualpop = self.parent
@@ -7438,7 +7438,7 @@ def do(self):
class Planner(Process):
def __init__(self, ident='planner', virtualpop=None, ids_strategy=None, logger=None, **kwargs):
- print 'Planner.__init__'
+ print('Planner.__init__')
# TODO: let this be independent, link to it or child??
self._init_common(ident,
@@ -7457,12 +7457,12 @@ def __init__(self, ident='planner', virtualpop=None, ids_strategy=None, logger=
if (ids_strategy is None):
# no info given, select all
- ids_strategy_default = strategychoices.values()
+ ids_strategy_default = list(strategychoices.values())
elif ids_strategy is not None:
ids_strategy_default = ids_strategy
- print ' ids_strategy_default', ids_strategy_default
+ print(' ids_strategy_default', ids_strategy_default)
self.ids_strategy = attrsman.add(cm.ListConf('ids_strategy', ids_strategy_default,
groupnames=['options'],
choices=strategychoices,
@@ -7496,7 +7496,7 @@ def __init__(self, ident='planner', virtualpop=None, ids_strategy=None, logger=
))
def do(self):
- print 'Planner.do', len(self.ids_strategy)
+ print('Planner.do', len(self.ids_strategy))
# links
virtualpop = self.parent
@@ -7511,12 +7511,12 @@ def do(self):
i = 1
strategies = virtualpop.get_strategies()
- print ' strategies:', self.ids_strategy, strategies.names[self.ids_strategy]
- print ' instances', strategies.strategies[self.ids_strategy]
+ print(' strategies:', self.ids_strategy, strategies.names[self.ids_strategy])
+ print(' instances', strategies.strategies[self.ids_strategy])
n_strat = len(self.ids_strategy)
for id_strategy, strategy in zip(self.ids_strategy, strategies.strategies[self.ids_strategy]):
- print ' current strategy', strategy, id(strategy)
+ print(' current strategy', strategy, id(strategy))
logger.w('Plan with '+strategy.get_name()+' (%d/%d)' % (i, n_strat))
virtualpop.plan_with_strategy(id_strategy, evalcrit=self.evalcrit,
is_plan_no_preferred=self.is_plan_no_preferred, logger=logger)
@@ -7531,7 +7531,7 @@ def __init__(self, ident='planselector', virtualpop=None,
methodname='plan with shortest estim. time',
logger=None, **kwargs):
- print 'PlanSelector.__init__'
+ print('PlanSelector.__init__')
# TODO: let this be independent, link to it or child??
@@ -7610,7 +7610,7 @@ def __init__(self, ident='planselector', virtualpop=None,
))
def do(self):
- print 'Planner.do'
+ print('Planner.do')
# links
#virtualpop = self.parent
@@ -7624,7 +7624,7 @@ def do(self):
class VehicleProvider(Process):
def __init__(self, ident='vehicleprovider', virtualpop=None, logger=None, **kwargs):
- print 'VehicleProvider.__init__'
+ print('VehicleProvider.__init__')
# TODO: let this be independent, link to it or child??
@@ -7667,7 +7667,7 @@ def __init__(self, ident='vehicleprovider', virtualpop=None, logger=None, **kwa
))
def do(self):
- print 'VehicleProvider.do'
+ print('VehicleProvider.do')
# links
virtualpop = self.parent
@@ -7699,7 +7699,7 @@ def do(self):
ids_pers_assign = np.random.choice(ids_pers_miss, n_need, replace=False)
ids_iauto = iautos.assign_to_persons(ids_pers_assign)
- print ' created %d autos, target share=%.2f, share = %.2f' % (iautos.get_share(is_abs=True), iautos.get_share(), self.share_autoowner)
+ print(' created %d autos, target share=%.2f, share = %.2f' % (iautos.get_share(is_abs=True), iautos.get_share(), self.share_autoowner))
ids_prefer_bike = virtualpop.select_ids(
(virtualpop.ids_mode_preferred.get_value() == id_mode_bike) & (virtualpop.ids_ibike.get_value() == -1))
@@ -7713,7 +7713,7 @@ def do(self):
ids_pers_assign = np.random.choice(ids_pers_miss, n_need, replace=False)
ids_ibike = ibikes.assign_to_persons(ids_pers_assign)
- print ' created %d bikes, target share=%.2f, share = %.2f' % (ibikes.get_share(is_abs=True), ibikes.get_share(), self.share_bikeowner)
+ print(' created %d bikes, target share=%.2f, share = %.2f' % (ibikes.get_share(is_abs=True), ibikes.get_share(), self.share_bikeowner))
ids_prefer_moto = virtualpop.select_ids(
(virtualpop.ids_mode_preferred.get_value() == id_mode_moto) & (virtualpop.ids_imoto.get_value() == -1))
@@ -7726,7 +7726,7 @@ def do(self):
ids_pers_assign = np.random.choice(ids_pers_miss, n_need, replace=False)
ids_imoto = imotos.assign_to_persons(ids_pers_assign)
- print ' created %d moto, target share=%.2f, share = %.2f' % (imotos.get_share(is_abs=True), imotos.get_share(), self.share_motorcycleowner)
+ print(' created %d moto, target share=%.2f, share = %.2f' % (imotos.get_share(is_abs=True), imotos.get_share(), self.share_motorcycleowner))
return True
# TODO: generate and assign additional vehicles
diff --git a/tools/contributed/sumopy/coremodules/demand/virtualpop_results.py b/tools/contributed/sumopy/coremodules/demand/virtualpop_results.py
index 4949309671d7..0b4f31d3e73d 100644
--- a/tools/contributed/sumopy/coremodules/demand/virtualpop_results.py
+++ b/tools/contributed/sumopy/coremodules/demand/virtualpop_results.py
@@ -129,7 +129,7 @@ def get_stratestutilattr(self, strategy):
return 'estutils_'+strategy.get_ident()
def add_results(self, scenario, ids_plan_before, ids_plan_after):
- print 'add_results iteration:', len(self)+1
+ print('add_results iteration:', len(self)+1)
# print ' ids_plan_before',ids_plan_before
# print ' ids_plan_after',ids_plan_after
# print ' changes',np.sum(ids_plan_before != ids_plan_after)
@@ -169,7 +169,7 @@ def add_results(self, scenario, ids_plan_before, ids_plan_after):
for id_strat, strategy in zip(ids_strat, strategies.strategies[ids_strat]):
inds_thisstrat_before = ids_strat_before == id_strat
inds_thisstrat_after = ids_strat_after == id_strat
- print ' check', id_strat, strategy, np.sum(inds_thisstrat_before), np.sum(inds_thisstrat_after)
+ print(' check', id_strat, strategy, np.sum(inds_thisstrat_before), np.sum(inds_thisstrat_after))
stratcountattr = self.get_stratcountattr(strategy)
getattr(self, stratcountattr)[id_run] = np.sum(inds_thisstrat_after)
@@ -233,7 +233,7 @@ def __init__(self, ident, parent, persons, edges, datapathkey='tripdatapath',
'default': 0.0, 'info': 'Time ending last trip or activity.', 'groupnames': ['tripdata']}),
])
- for attrname, kwargs in attrinfos.iteritems():
+ for attrname, kwargs in attrinfos.items():
self.add_resultattr(attrname, **kwargs)
# this is a special for route info
@@ -252,7 +252,7 @@ def add_resultattr(self, attrname, **kwargs):
# default cannot be kwarg
default = kwargs['default']
del kwargs['default']
- if kwargs.has_key('groupnames'):
+ if 'groupnames' in kwargs:
kwargs['groupnames'].append('results')
else:
kwargs['groupnames'] = ['results']
@@ -261,12 +261,12 @@ def add_resultattr(self, attrname, **kwargs):
def import_xml(self, sumo, datapaths):
datapathkey = self.datapathkey.get_value()
- if datapaths.has_key(datapathkey):
+ if datapathkey in datapaths:
self.import_sumoxml(datapaths[datapathkey], sumo)
self.get_persons().update_results(self)
def import_sumoxml(self, filepath, sumo):
- print 'Personresults.import_sumoxml', self.get_persons().ident, filepath
+ print('Personresults.import_sumoxml', self.get_persons().ident, filepath)
reader = PersonReader(self.get_persons(), sumo)
parse(filepath, reader)
diff --git a/tools/contributed/sumopy/coremodules/demand/virtualpop_results_mpl.py b/tools/contributed/sumopy/coremodules/demand/virtualpop_results_mpl.py
index ba350c7eadeb..86f9b8a4aeab 100644
--- a/tools/contributed/sumopy/coremodules/demand/virtualpop_results_mpl.py
+++ b/tools/contributed/sumopy/coremodules/demand/virtualpop_results_mpl.py
@@ -40,7 +40,7 @@ def __init__(self, scenario, name='Virtualpopulation Iterate Matplotlob Plotter'
name=name,
info=info, logger=logger)
- print 'VirtualpopIteratePlotter.__init__', self.parent
+ print('VirtualpopIteratePlotter.__init__', self.parent)
attrsman = self.get_attrsman()
self.is_strategy_share = attrsman.add(cm.AttrConf('is_strategy_share', kwargs.get('is_strategy_share', True),
@@ -75,7 +75,7 @@ def __init__(self, scenario, name='Virtualpopulation Iterate Matplotlob Plotter'
self.add_save_options(**kwargs)
def show(self):
- print 'show'
+ print('show')
# if self.axis is None:
self.init_figures()
plt.rc('lines', linewidth=self.width_line)
@@ -83,7 +83,7 @@ def show(self):
# cycler('linestyle', ['-', '--', ':', '-.'])))
for plotattr in self.get_attrsman().get_group('plots'):
- print ' ', plotattr.attrname, plotattr.get_value()
+ print(' ', plotattr.attrname, plotattr.get_value())
if plotattr.get_value():
plotattr.plotfunction()
@@ -103,7 +103,7 @@ def plot_strategy_share(self):
"""
Plot total est times for each stategy over iterations.
"""
- print 'plot_strategy_share'
+ print('plot_strategy_share')
scenario = self.get_scenario()
simresults = scenario.simulation.results
vpiterstats = simresults.get_resultobj('vpiterstats')
@@ -126,7 +126,7 @@ def plot_strategy_share(self):
ident_strat = strategy.get_ident()
name_strat = strategy.get_name()
counts = self.get_resultattrconf(vpiterstats.get_stratcountattr(strategy))
- print ' name_strat', name_strat, 'counts', counts
+ print(' name_strat', name_strat, 'counts', counts)
if np.any(counts[iters] > 0):
ax.plot(iters, 1.0*counts[iters]/trips_tot*100,
label=name_strat,
@@ -157,7 +157,7 @@ def plot_strategy_share(self):
def plot_strategy_changes(self):
"""'Plot strategy changes over iterations."""
- print 'plot_strategy_changes'
+ print('plot_strategy_changes')
scenario = self.get_scenario()
simresults = scenario.simulation.results
vpiterstats = simresults.get_resultobj('vpiterstats')
@@ -188,7 +188,7 @@ def plot_strategy_changes(self):
self.save_fig('fig_changes')
def plot_strategy_time_tot_est(self):
- print 'plot_strategy_time_tot_est'
+ print('plot_strategy_time_tot_est')
scenario = self.get_scenario()
simresults = scenario.simulation.results
vpiterstats = simresults.get_resultobj('vpiterstats')
@@ -244,7 +244,7 @@ def plot_strategy_time_tot_est(self):
self.save_fig('fig_time_tot_est')
def plot_strategy_time_tot(self):
- print 'plot_strategy_time_tot'
+ print('plot_strategy_time_tot')
scenario = self.get_scenario()
simresults = scenario.simulation.results
vpiterstats = simresults.get_resultobj('vpiterstats')
@@ -307,7 +307,7 @@ def __init__(self, virtualpop, name='Plot strategy results with Matplotlib',
self._init_common('strategyresultplotter', parent=virtualpop, name=name,
info=info, logger=logger)
- print 'StrategyPlotter.__init__', self.parent
+ print('StrategyPlotter.__init__', self.parent)
attrsman = self.get_attrsman()
self.is_strategy_share = attrsman.add(cm.AttrConf('is_strategy_share', kwargs.get('is_strategy_share', True),
@@ -364,7 +364,7 @@ def __init__(self, virtualpop, name='Plot strategy results with Matplotlib',
self.add_save_options(**kwargs)
def show(self):
- print 'show'
+ print('show')
# if self.axis is None:
self.init_figures()
plt.rc('lines', linewidth=self.width_line)
@@ -372,7 +372,7 @@ def show(self):
# cycler('linestyle', ['-', '--', ':', '-.'])))
for plotattr in self.get_attrsman().get_group('plots'):
- print ' ', plotattr.attrname, plotattr.get_value()
+ print(' ', plotattr.attrname, plotattr.get_value())
if plotattr.get_value():
plotattr.plotfunction()
@@ -380,7 +380,7 @@ def show(self):
show_plot()
def plot_strategy_share(self):
- print 'plot_strategy_share'
+ print('plot_strategy_share')
fig = self.create_figure()
ax = fig.add_subplot(111)
@@ -437,7 +437,7 @@ def plot_strategy_share(self):
self.save_fig('virtualpop_strategy_share_current')
def plot_strategy_times_est(self):
- print 'plot_strategy_times_est'
+ print('plot_strategy_times_est')
fig = self.create_figure()
ax = fig.add_subplot(111)
@@ -503,7 +503,7 @@ def plot_strategy_timefactors_est(self):
"""
For each strategy plot its estimated travel time factor with respect to the fastest strategy of the same person
"""
- print 'plot_strategy_timefactors_est'
+ print('plot_strategy_timefactors_est')
fig = self.create_figure()
ax = fig.add_subplot(111)
@@ -545,14 +545,14 @@ def plot_strategy_timefactors_est(self):
x_min = 0.0
x_max = 0.0
- for id_strat, timefactors in strategytimefactors.iteritems():
+ for id_strat, timefactors in strategytimefactors.items():
if len(timefactors) > 0:
x_max = max(x_max, np.max(timefactors))
#bins = np.linspace(x_min,x_max,self.n_bins)
bins = np.arange(x_min, x_max, self.timeint_bins)
if len(bins) > 0:
- for id_strat, timefactors in strategytimefactors.iteritems():
+ for id_strat, timefactors in strategytimefactors.items():
if len(timefactors) > 0:
self.plot_hist(ax, np.array(timefactors, dtype=np.float32),
bins=bins,
@@ -583,7 +583,7 @@ def plot_strategy_timefactors_exec(self):
"""
For each strategy plot its travel executive time factor with respect to the fastest strategy of the same person
"""
- print 'plot_strategy_timefactors_est'
+ print('plot_strategy_timefactors_est')
fig = self.create_figure()
ax = fig.add_subplot(111)
@@ -627,17 +627,17 @@ def plot_strategy_timefactors_exec(self):
n_nonexistant += 1
if n_nonexistant > 0:
- print ' WARNING: only %d of %d persons have not completed all strategies' % (n_nonexistant, n_pers)
+ print(' WARNING: only %d of %d persons have not completed all strategies' % (n_nonexistant, n_pers))
x_min = 0.0
x_max = 0.0
- for id_strat, timefactors in strategytimefactors.iteritems():
+ for id_strat, timefactors in strategytimefactors.items():
if len(timefactors) > 0:
x_max = max(x_max, np.max(timefactors))
#bins = np.linspace(x_min,x_max,self.n_bins)
bins = np.arange(x_min, x_max, self.timeint_bins)
if len(bins) > 0:
- for id_strat, timefactors in strategytimefactors.iteritems():
+ for id_strat, timefactors in strategytimefactors.items():
if len(timefactors) > 0:
self.plot_hist(ax, np.array(timefactors, dtype=np.float32),
bins=bins,
diff --git a/tools/contributed/sumopy/coremodules/demand/virtualpop_wxgui.py b/tools/contributed/sumopy/coremodules/demand/virtualpop_wxgui.py
index 5c8c70a5871e..bb2da5fabbc0 100644
--- a/tools/contributed/sumopy/coremodules/demand/virtualpop_wxgui.py
+++ b/tools/contributed/sumopy/coremodules/demand/virtualpop_wxgui.py
@@ -24,13 +24,13 @@
from agilepy.lib_base.misc import get_inversemap
from agilepy.lib_wx.ogleditor import *
try:
- import virtualpop_results_mpl as results_mpl
+ from . import virtualpop_results_mpl as results_mpl
is_mpl = True # we have matplotlib support
except:
- print "WARNING: python matplotlib package not installed, no matplotlib plots."
+ print("WARNING: python matplotlib package not installed, no matplotlib plots.")
is_mpl = False
-import virtualpop
+from . import virtualpop
from agilepy.lib_wx.processdialog import ProcessDialog, ProcessDialogInteractive
@@ -199,7 +199,7 @@ def on_generate(self, event=None):
# this does not return until the dialog is closed.
#val = dlg.ShowModal()
- print 'on_create_pop_from_odflows'
+ print('on_create_pop_from_odflows')
dlg.Show()
dlg.MakeModal(True)
@@ -221,7 +221,7 @@ def on_import_plans(self, event=None):
# print 'You selected %d files:' % len(paths)
if len(paths) > 0:
filepath = paths[0]
- print 'call import_routes_xml', filepath
+ print('call import_routes_xml', filepath)
self._demand.virtualpop.import_routes_xml(filepath)
self._mainframe.browse_obj(self._demand.virtualpop.get_plans())
@@ -274,7 +274,7 @@ def on_create_pop_from_odflows(self, event=None):
# this does not return until the dialog is closed.
#val = dlg.ShowModal()
- print 'on_create_pop_from_odflows'
+ print('on_create_pop_from_odflows')
dlg.Show()
dlg.MakeModal(True)
@@ -300,7 +300,7 @@ def on_provide_vehicles(self, event=None):
# this does not return until the dialog is closed.
#val = dlg.ShowModal()
- print 'on_provide_vehicles'
+ print('on_provide_vehicles')
dlg.Show()
dlg.MakeModal(True)
@@ -327,7 +327,7 @@ def on_generate_plan(self, event=None):
# this does not return until the dialog is closed.
#val = dlg.ShowModal()
- print 'on_generate_plan'
+ print('on_generate_plan')
dlg.Show()
dlg.MakeModal(True)
if self.proc.status == 'success':
@@ -444,8 +444,8 @@ def on_plot_iterations(self, event=None):
scenario = self._demand.parent
vpiterstats = scenario.simulation.results.get_resultobj('vpiterstats')
- print 'on_plot_iterations '
- print ' vpiterstats ', vpiterstats
+ print('on_plot_iterations ')
+ print(' vpiterstats ', vpiterstats)
if is_mpl & (vpiterstats is not None):
resultplotter = results_mpl.IteratePlotter(scenario,
logger=self._mainframe.get_logger()
diff --git a/tools/contributed/sumopy/coremodules/demand/wxgui.py b/tools/contributed/sumopy/coremodules/demand/wxgui.py
index c97a9c9beb0b..1d54b546e710 100644
--- a/tools/contributed/sumopy/coremodules/demand/wxgui.py
+++ b/tools/contributed/sumopy/coremodules/demand/wxgui.py
@@ -28,13 +28,13 @@
from coremodules.network import routing
from coremodules.scenario.scenario import load_scenario
-import demand
-import turnflows
-import origin_to_destination_wxgui as odgui
-import turnflows_wxgui as turnflowsgui
-import virtualpop_wxgui as virtualpopgui
-import detectorflows_wxgui as detectorflowsgui
-import publictransportservices_wxgui as pt
+from . import demand
+from . import turnflows
+from . import origin_to_destination_wxgui as odgui
+from . import turnflows_wxgui as turnflowsgui
+from . import virtualpop_wxgui as virtualpopgui
+from . import detectorflows_wxgui as detectorflowsgui
+from . import publictransportservices_wxgui as pt
class TripDrawings(Polygons):
diff --git a/tools/contributed/sumopy/coremodules/landuse/CREATE_ZONES.py b/tools/contributed/sumopy/coremodules/landuse/CREATE_ZONES.py
index 96e04ab2d2c7..e7776a85ba01 100644
--- a/tools/contributed/sumopy/coremodules/landuse/CREATE_ZONES.py
+++ b/tools/contributed/sumopy/coremodules/landuse/CREATE_ZONES.py
@@ -45,22 +45,22 @@ def create_zones(n_zones, x_min, x_max, y_min, y_max):
# CREATE ZONES by CLUSTER OF POINTS
- print 'k-value cluster'
+ print('k-value cluster')
# k-value cluster
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.html
features = np.array(origin_dest_points)
- print 'features', features
+ print('features', features)
# Whiten data
st_dev_x = np.std(features[:][0])
st_dev_y = np.std(features[:][1])
- print 'st_dev_x', st_dev_x
- print 'st_dev_y', st_dev_y
+ print('st_dev_x', st_dev_x)
+ print('st_dev_y', st_dev_y)
whitened = whiten(features)
# Find 2 clusters in the data
codebook, distortion = kmeans(features, n_zones)
- print 'codebook', codebook
+ print('codebook', codebook)
features[:, 0] = features[:, 0]*st_dev_x
features[:, 1] = features[:, 1]*st_dev_y
@@ -79,8 +79,8 @@ def create_zones(n_zones, x_min, x_max, y_min, y_max):
# myscenario.landuse.zones.clear()
vertices = vor.vertices
regions = vor.regions
- print vertices
- print regions
+ print(vertices)
+ print(regions)
zone_name = 1
for region in regions:
if region != []:
@@ -88,11 +88,11 @@ def create_zones(n_zones, x_min, x_max, y_min, y_max):
for vertice in region:
shape.append([vertices[vertice][0], vertices[vertice][1], 0.])
ids_zone = myscenario.landuse.zones.get_ids()
- print 'n_zones =', len(ids_zone)
- print shape
+ print('n_zones =', len(ids_zone))
+ print(shape)
zone_name += 1
# np.concatenate(shape).astype(None)
- print shape
+ print(shape)
myscenario.landuse.zones.make(zonename='zone_name', coord=np.zeros(
3, dtype=np.float32), shape=shape, id_landusetype=6)
ids_zone = myscenario.landuse.zones.get_ids()
diff --git a/tools/contributed/sumopy/coremodules/landuse/__init__.py b/tools/contributed/sumopy/coremodules/landuse/__init__.py
index cab987aa8f9c..02fdf630fcec 100644
--- a/tools/contributed/sumopy/coremodules/landuse/__init__.py
+++ b/tools/contributed/sumopy/coremodules/landuse/__init__.py
@@ -18,12 +18,12 @@
__version__ = "0.0"
-print 'init', __name__
+print('init', __name__)
def get_wxgui():
# try:
- from wxgui import WxGui
+ from .wxgui import WxGui
return WxGui(__name__)
# except:
# return None
diff --git a/tools/contributed/sumopy/coremodules/landuse/landuse.py b/tools/contributed/sumopy/coremodules/landuse/landuse.py
index 6803b092ac58..4a5c71ff9869 100644
--- a/tools/contributed/sumopy/coremodules/landuse/landuse.py
+++ b/tools/contributed/sumopy/coremodules/landuse/landuse.py
@@ -16,7 +16,7 @@
# @author Joerg Schweizer
# @date 2012
-import maps
+from . import maps
from agilepy.lib_base.processes import Process, CmlMixin
from collections import OrderedDict
from numpy import random
@@ -64,7 +64,7 @@ def clean_osm(filepath_in, filepath_out):
fd_in = open(filepath_in, 'r')
fd_out = open(filepath_out, 'w')
for line in fd_in.readlines():
- for oldstr, newstr in substitutes.iteritems():
+ for oldstr, newstr in substitutes.items():
line = line.replace(oldstr, newstr)
fd_out.write(line)
fd_in.close()
@@ -453,7 +453,7 @@ def update_netoffset(self, deltaoffset):
# self.zones.update_netoffset(deltaoffset)
self.coords.value[:, :2] = self.coords.value[:, :2] + deltaoffset
shapes = self.shapes.value
- for i in xrange(len(shapes)):
+ for i in range(len(shapes)):
s = np.array(shapes[i])
s[:, :2] = s[:, :2] + deltaoffset
shapes[i] = list(s)
@@ -464,7 +464,7 @@ def identify_zonearea(self, id_zone):
self.areas[id_zone] = find_area(shape)/1000000.0
def identify_zoneedges(self, id_zone):
- print 'identify_zoneedges of id_zone', id_zone
+ print('identify_zoneedges of id_zone', id_zone)
if len(self.shapes[id_zone]) >= 3:
# must have at least 3 vertices to be an area
@@ -492,9 +492,9 @@ def identify_zoneedges(self, id_zone):
# select and determine weights
self.ids_edges_inside[id_zone] = self.get_edges().get_ids(inds_within)
- print ' found', len(self.ids_edges_inside[id_zone]), 'edges'
+ print(' found', len(self.ids_edges_inside[id_zone]), 'edges')
if len(self.ids_edges_inside[id_zone]) == 0:
- print 'WARNING in identify_zoneedges: no edges found in zone', id_zone
+ print('WARNING in identify_zoneedges: no edges found in zone', id_zone)
def get_zoneedges_by_mode_fast(self, id_zone, id_mode, speed_max=None,
modeconst_excl=0.0, modeconst_mix=0.0,
@@ -509,10 +509,10 @@ def get_zoneedges_by_mode_fast(self, id_zone, id_mode, speed_max=None,
"""
# print 'get_zoneedges_by_mode_fast id_zone',id_zone,'id_mode',id_mode
- if not self._mode_to_edges_inside.has_key(id_mode):
+ if id_mode not in self._mode_to_edges_inside:
self._mode_to_edges_inside[id_mode] = {}
- if not self._mode_to_edges_inside[id_mode].has_key(id_zone):
+ if id_zone not in self._mode_to_edges_inside[id_mode]:
self._mode_to_edges_inside[id_mode][id_zone] = self.get_zoneedges_by_mode(
id_zone, id_mode, weights=weights, fstar=fstar)
# print ' found edges',len(self._mode_to_edges_inside[id_mode][id_zone])
@@ -552,7 +552,7 @@ def get_egdeprobs(self, id_zone, n_edges_min_length, n_edges_max_length, priorit
# todo: rename ids_edges_orig to simply ids_edges
ids_edge_orig = self.ids_edges_orig[id_zone]
if ids_edge_orig is None:
- print 'WARNING: no edges in zone', id_zone, '. Run edge detection first.'
+ print('WARNING: no edges in zone', id_zone, '. Run edge detection first.')
if is_dict:
return {}
else:
@@ -647,7 +647,7 @@ def write_kml(self, fd=None, indent=0):
fd.write(xm.end('Placemark', indent + 2))
def write_xml(self, fd=None, indent=0):
- print 'Zones.write_xml'
+ print('Zones.write_xml')
net = self.parent.parent.net
ids_edge_sumo = net.edges.ids_sumo
ids_zone = self.get_ids()
@@ -715,7 +715,7 @@ def export_kml(self, filepath=None, encoding='UTF-8'):
"""
Export zones to Google kml file formate.
"""
- print 'export_sumoxml', filepath, len(self)
+ print('export_sumoxml', filepath, len(self))
if len(self) == 0:
return None
@@ -725,7 +725,7 @@ def export_kml(self, filepath=None, encoding='UTF-8'):
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in write_obj_to_xml: could not open', filepath
+ print('WARNING in write_obj_to_xml: could not open', filepath)
return False
#xmltag, xmltag_item, attrname_id = self.xmltag
fd.write('\n' % encoding)
@@ -746,7 +746,7 @@ def export_sumoxml(self, filepath=None, encoding='UTF-8'):
"""
Export zones to SUMO xml file formate.
"""
- print 'export_sumoxml', filepath, len(self)
+ print('export_sumoxml', filepath, len(self))
if len(self) == 0:
return None
@@ -756,7 +756,7 @@ def export_sumoxml(self, filepath=None, encoding='UTF-8'):
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in export_sumoxml: could not open', filepath
+ print('WARNING in export_sumoxml: could not open', filepath)
return False
#xmltag, xmltag_item, attrname_id = self.xmltag
#fd.write('\n'%encoding)
@@ -1372,7 +1372,7 @@ def update_netoffset(self, deltaoffset):
# self.zones.update_netoffset(deltaoffset)
self.centroids.value[:, :2] = self.centroids.value[:, :2] + deltaoffset
shapes = self.shapes.value
- for i in xrange(len(shapes)):
+ for i in range(len(shapes)):
s = np.array(shapes[i])
s[:, :2] = s[:, :2] + deltaoffset
shapes[i] = list(s)
@@ -1437,7 +1437,7 @@ def get_departure_probabilities_landuse2(self, ids_landusetype):
The ids_fac is an array that contains the facility ids in correspondence
to the probability vector.
"""
- print 'get_departure_probabilities_landuse2 ids_landusetype', ids_landusetype
+ print('get_departure_probabilities_landuse2 ids_landusetype', ids_landusetype)
probabilities = {}
zones = self.ids_zone.get_linktab()
inds_fac = self.get_inds()
@@ -1466,13 +1466,13 @@ def get_departure_probabilities_landuse2(self, ids_landusetype):
probabilities[id_zone] = utils # all zero prob
if 0: # debug
- print ' sum(probs)', np.sum(probabilities[id_zone])
+ print(' sum(probs)', np.sum(probabilities[id_zone]))
if np.sum(probabilities[id_zone]) > 0:
ids_fac = self.get_ids(inds_fac)
for id_fac, id_landusetype, id_thiszone, prob in zip(ids_fac, self.ids_landusetype[ids_fac], self.ids_zone[ids_fac], probabilities[id_zone]):
if (id_thiszone == id_zone): # & (id_landusetype in ids_landusetype):
if prob > 0:
- print ' id_fac', id_fac, 'id_landusetype', id_landusetype, 'prob', prob
+ print(' id_fac', id_fac, 'id_landusetype', id_landusetype, 'prob', prob)
return probabilities, self.get_ids(inds_fac)
@@ -1486,14 +1486,14 @@ def get_departure_probabilities_landuse(self):
The ids_fac is an array that contains the facility ids in correspondence
to the probability vector.
"""
- print 'get_departure_probabilities_landuse'
+ print('get_departure_probabilities_landuse')
probabilities = {}
zones = self.ids_zone.get_linktab()
inds_fac = self.get_inds()
for id_zone in zones.get_ids():
probabilities[id_zone] = {}
for id_landusetype in set(self.ids_landusetype.value):
- print ' id_zone,id_landusetype', id_zone, id_landusetype
+ print(' id_zone,id_landusetype', id_zone, id_landusetype)
# print ' ids_landusetype',self.ids_landusetype.value[inds_fac]
# print ' ids_zone',self.ids_zone.value[inds_fac]
# print ''
@@ -1548,7 +1548,7 @@ def get_ids_building(self, ids=None):
def identify_landuse_from_area(self, ids_fac=None):
"""Determines the landuse of facilities from the landuse of areas in which their are located"""
- print 'identify_landuse_from_area', ids_fac
+ print('identify_landuse_from_area', ids_fac)
# TODO:
landusetypes = self.get_landusetypes()
ids_area = self.get_ids_area(ids_fac)
@@ -1560,8 +1560,8 @@ def identify_landuse_from_area(self, ids_fac=None):
if osmkey == 'building.yes':
if is_point_in_polygon(coord[:2], np.array(shape, dtype=np.float32)[:, :2], is_use_shapely=IS_SHAPELY):
- print ' found id_fac', id_fac, osmkey, 'in id_area', id_area
- print ' id_landusetype', self.ids_landusetype[id_fac], 'is_area', landusetypes.are_area[self.ids_landusetype[id_fac]], '->', id_landusetype_fac
+ print(' found id_fac', id_fac, osmkey, 'in id_area', id_area)
+ print(' id_landusetype', self.ids_landusetype[id_fac], 'is_area', landusetypes.are_area[self.ids_landusetype[id_fac]], '->', id_landusetype_fac)
self.ids_landusetype[id_fac] = id_landusetype_fac
def update_centroid(self, _id):
@@ -1605,7 +1605,7 @@ def identify_closest_edge(self, ids=None, priority_max=5, has_sidewalk=True, n_b
is closest to the centoid of each facility and the satisfies certain
conditions.
"""
- print 'identify_closest_edge'
+ print('identify_closest_edge')
edges = self.get_edges()
id_ped = self.get_net().modes.get_id_mode('pedestrian')
# select edges...if (edges.priorities[id_edge]<=priority_max) & edges.has_sidewalk(id_edge):
@@ -1635,7 +1635,7 @@ def identify_closest_edge(self, ids=None, priority_max=5, has_sidewalk=True, n_b
pos = 0.0
x1, y1, z1 = shape[0]
edgelength = edges.lengths[id_edge]
- for j in xrange(1, n_segs):
+ for j in range(1, n_segs):
x2, y2, z2 = shape[j]
d, xp, yp = shortest_dist(x1, y1, x2, y2, xc, yc)
# print ' x1,y1=(%d,%d)'%(x1,y1),',x2,y2=(%d,%d)'%(x2,y2),',xc,yc=(%d,%d)'%(xc,yc)
@@ -1713,7 +1713,7 @@ def set_shapes(self, ids, vertices):
self.update(ids)
def import_poly(self, polyfilepath, is_remove_xmlfiles=False, is_clear=True, **kwargs):
- print 'import_poly from %s ' % (polyfilepath,)
+ print('import_poly from %s ' % (polyfilepath,))
if is_clear:
self.clear()
# let's read first the offset information, which are in the
@@ -1749,7 +1749,7 @@ def import_poly(self, polyfilepath, is_remove_xmlfiles=False, is_clear=True, **k
# self.update()
# timeit
- print ' exec time=', time.clock() - exectime_start
+ print(' exec time=', time.clock() - exectime_start)
# print ' self.shapes',self.shapes.value
@@ -1806,7 +1806,7 @@ def export_sumokml(self, filepath=None, encoding='UTF-8'):
"""
Export stops to SUMO stop xml file.
"""
- print 'export_sumoxml', filepath, len(self)
+ print('export_sumoxml', filepath, len(self))
if len(self) == 0:
return None
@@ -1816,7 +1816,7 @@ def export_sumokml(self, filepath=None, encoding='UTF-8'):
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in write_obj_to_xml: could not open', filepath
+ print('WARNING in write_obj_to_xml: could not open', filepath)
return False
#xmltag, xmltag_item, attrname_id = self.xmltag
fd.write('\n' % encoding)
@@ -1908,7 +1908,7 @@ def startElement(self, name, attrs):
def get_landuse(self, osmkey):
keyvec = osmkey.split('.')
len_keyvec = len(keyvec)
- print 'get_landuse', len_keyvec, keyvec
+ print('get_landuse', len_keyvec, keyvec)
#is_match = False
for id_landusetype in self._ids_landusetype_all:
# print ' id_landusetype',id_landusetype
@@ -1918,7 +1918,7 @@ def get_landuse(self, osmkey):
for osmfilter in self._osmfilters[id_landusetype]:
# print ' ?osmfiltervec',osmfilter,osmkey==osmfilter
if osmkey == osmfilter: # exact match of filter
- print ' exact', osmkey
+ print(' exact', osmkey)
return id_landusetype
# now check for wildcards
@@ -1931,7 +1931,7 @@ def get_landuse(self, osmkey):
if (len(osmfiltervec) == 2) & (len_keyvec == 2):
if osmfiltervec[0] == keyvec[0]:
if osmfiltervec[1] == '*':
- print ' *', keyvec[0]
+ print(' *', keyvec[0])
return id_landusetype
return -1
@@ -2132,7 +2132,7 @@ def make_parking(self, id_mode=MODES['passenger'],
is_clear=True,
logger=None,
**kwargs):
- print 'make_parking'
+ print('make_parking')
if is_clear:
self.clear()
edges = self.edges.get_value()
@@ -2162,7 +2162,7 @@ def make_parking(self, id_mode=MODES['passenger'],
pos_offset = length_noparking
pos = pos_offset
if n_spaces > 0:
- for i in xrange(n_spaces):
+ for i in range(n_spaces):
#id_park = self.suggest_id()
# print ' pos=',pos,pos/edges.lengths[id_edge]
@@ -2180,7 +2180,7 @@ def make_parking(self, id_mode=MODES['passenger'],
ids_parking.append(id_park)
pos = pos_offset+(i+1)*length_lot
- print ' created %d parking spaces' % n_parking
+ print(' created %d parking spaces' % n_parking)
return ids_parking
def clear_booking(self):
@@ -2194,7 +2194,7 @@ def get_closest_parking(self, id_veh, coord, c_spread=2.0):
"""
#inds_person = self.persons.get_inds(ids_person)
- print 'get_closest_parking'
+ print('get_closest_parking')
ind_parking_closest = self.get_inds()[np.argmin(
np.sum((coord-self.vertices.value[:, 1, :])**2, 1) + c_spread*lengths*self.lengths.get_value())]
self.numbers_booking.get_value()[ind_parking_closest] += 1
@@ -2215,7 +2215,7 @@ def get_closest_parkings(self, ids_veh, ids_mode, coords, dists_walk_max, c_spre
# print 'get_closest_parking',n,len(self),'n_retrials',n_retrials
if len(self) == 0:
- print 'WARNING in get_closest_parkings: there is no parking.'
+ print('WARNING in get_closest_parkings: there is no parking.')
return [], []
#parking = self.get_landuse().parking
@@ -2274,8 +2274,8 @@ def get_closest_parkings(self, ids_veh, ids_mode, coords, dists_walk_max, c_spre
# print ' fallback n_search',n_search,'is_search',is_search
if is_search:
- print 'WARNING: inaccessible parking for id_veh', id_veh, 'is_fallback', is_fallback
- print ' dist=%.1f' % (np.sqrt(dists[ind_parking_closest])), 'id_lane', ids_lane[ind_parking_closest], 'al', lanes.get_accesslevel([ids_lane[ind_parking_closest]], id_mode_fallback)
+ print('WARNING: inaccessible parking for id_veh', id_veh, 'is_fallback', is_fallback)
+ print(' dist=%.1f' % (np.sqrt(dists[ind_parking_closest])), 'id_lane', ids_lane[ind_parking_closest], 'al', lanes.get_accesslevel([ids_lane[ind_parking_closest]], id_mode_fallback))
inds_vehparking[i] = ind_parking_closest
are_fallback[i] = is_fallback
@@ -2387,11 +2387,11 @@ def export_polyxml(self, filepath=None, encoding='UTF-8', delta=np.zeros(3, dtyp
else:
filepath = os.path.join(os.getcwd(), 'landuse.poly.xml')
- print 'export_polyxml', filepath
+ print('export_polyxml', filepath)
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in export_poly_xml: could not open', filepath
+ print('WARNING in export_poly_xml: could not open', filepath)
return None
#xmltag, xmltag_item, attrname_id = self.xmltag
@@ -2442,7 +2442,7 @@ def import_polyxml(self, rootname=None, dirname='', filepath=None, is_clear=True
class FacilityGenerator(Process):
def __init__(self, ident='facilitygenerator', facilities=None, logger=None, **kwargs):
- print 'FacilityGenerator.__init__'
+ print('FacilityGenerator.__init__')
# TODO: let this be independent, link to it or child??
@@ -2503,7 +2503,7 @@ def __init__(self, ident='facilitygenerator', facilities=None, logger=None, **k
# ))
def do(self):
- print self.get_name()+'.do'
+ print(self.get_name()+'.do')
# links
facilities = self.parent
net = facilities.parent.get_net()
@@ -2637,7 +2637,7 @@ def do(self):
# check if positions on parallel shape are closest to
# this edge or closer to another edge
- print ' Done, generated %d facilities' % n_fac
+ print(' Done, generated %d facilities' % n_fac)
return True
def get_segind_closest_edge(self, p, x1, y1, x2, y2, inds_seg_exclude=None):
@@ -2650,7 +2650,7 @@ def get_segind_closest_edge(self, p, x1, y1, x2, y2, inds_seg_exclude=None):
class ParkingGenerator(Process):
def __init__(self, ident='parkinggenerator', parking=None, logger=None, **kwargs):
- print 'ParkingGenerator.__init__'
+ print('ParkingGenerator.__init__')
# TODO: let this be independent, link to it or child??
@@ -2724,7 +2724,7 @@ def __init__(self, ident='parkinggenerator', parking=None, logger=None, **kwarg
))
def do(self):
- print self.get_name()+'.do'
+ print(self.get_name()+'.do')
# links
# print ' self.id_mode',self.id_mode
# print ' self.get_kwoptions()',self.get_kwoptions()
@@ -2749,7 +2749,7 @@ def __init__(self, landuse=None,
is_clean_osmfile=True,
is_merge=False,
logger=None, **kwargs):
- print 'OsmPolyImporter.__init__', landuse, landuse.parent.get_rootfilename()
+ print('OsmPolyImporter.__init__', landuse, landuse.parent.get_rootfilename())
self._init_common('osmpolyimporter', name='OSM Poly import',
logger=logger,
info='Converts a OSM file to a SUMO Poly file and read facilities into scenario.',
@@ -2945,12 +2945,12 @@ def do(self):
self.run_cml(cml)
if self.status == 'success':
if os.path.isfile(self.polyfilepath):
- print ' OSM->poly.xml successful, start importing xml files'
+ print(' OSM->poly.xml successful, start importing xml files')
self._landuse.import_polyxml(self.rootname, self.rootdirpath,
is_clear=not self.is_merge,
type_default=self.type_default,
height_default=self.height_default)
- print ' import poly in sumopy done.'
+ print(' import poly in sumopy done.')
return True
return False
else:
diff --git a/tools/contributed/sumopy/coremodules/landuse/maps.py b/tools/contributed/sumopy/coremodules/landuse/maps.py
index 527d7138abef..d840566dcf83 100644
--- a/tools/contributed/sumopy/coremodules/landuse/maps.py
+++ b/tools/contributed/sumopy/coremodules/landuse/maps.py
@@ -23,7 +23,7 @@
import sys
import numpy as np
import wx
-import urllib
+import urllib.request, urllib.parse, urllib.error
from collections import OrderedDict
import agilepy.lib_base.classman as cm
import agilepy.lib_base.arrayman as am
@@ -50,7 +50,7 @@
try:
from PIL import ImageFilter, Image, ImageChops, ImagePath, ImageDraw
except:
- print "WARNING: Maps requires PIL module."
+ print("WARNING: Maps requires PIL module.")
IS_MAPSUPPORT = False
try:
@@ -61,7 +61,7 @@
from mpl_toolkits.basemap import pyproj
except:
- print "WARNING: Maps requires pyproj module."
+ print("WARNING: Maps requires pyproj module.")
IS_MAPSUPPORT = False
# print __doc__
# raise
@@ -71,7 +71,7 @@
def download_googlemap(filepath, bbox, proj, size=640, filetype='gif', maptype='satellite'):
- print 'download_googlemap', bbox
+ print('download_googlemap', bbox)
# https://developers.google.com/maps/documentation/static-maps/intro#Paths
x_sw, y_sw = bbox[0]
x_ne, y_ne = bbox[1]
@@ -88,15 +88,15 @@ def download_googlemap(filepath, bbox, proj, size=640, filetype='gif', maptype='
size_x = size_y = size/2
url = URL_GOOGLEMAP+"size=%dx%d&visible=%.6f,%.6f|%.6f,%.6f&format=%s&maptype=%s&scale=2"\
% (size_x, size_y, lat00, lon00, lat11, lon11, filetype.upper(), maptype)
- print ' url=', url
- urllib.urlretrieve(url, filepath)
+ print(' url=', url)
+ urllib.request.urlretrieve(url, filepath)
bbox_lonlat = np.array([[lon00, lat00], [lon11, lat11]])
return bbox_lonlat
def download_googlemap_bb(filepath, bbox, proj, apikey, size=640, filetype='gif', maptype='satellite', color="0xff0000ff"):
- print 'download_googlemap_bb', bbox
+ print('download_googlemap_bb', bbox)
# https://developers.google.com/maps/documentation/static-maps/intro#Paths
x_sw, y_sw = bbox[0]
x_ne, y_ne = bbox[1]
@@ -146,8 +146,8 @@ def download_googlemap_bb(filepath, bbox, proj, apikey, size=640, filetype='gif'
# urllib.urlretrieve (URL_GOOGLEMAP+"size=%dx%d&format=%s&maptype=%s&scale=2&path=color:0xff0000ff|weight:1|%.5f,%.5f|%.5f,%.5f|%.5f,%.5f|%.5f,%.5f"\
# %(size_x,size_y,filetype,maptype,lat00,lon00, lat11,lon11, lat01,lon01, lat10,lon10), filepath)
- print ' url=', url
- urllib.urlretrieve(url, filepath)
+ print(' url=', url)
+ urllib.request.urlretrieve(url, filepath)
bbox_lonlat = np.array([[lon00, lat00], [lon11, lat11]])
return bbox_lonlat
@@ -155,7 +155,7 @@ def download_googlemap_bb(filepath, bbox, proj, apikey, size=640, filetype='gif'
def estimate_angle(filepath):
im = Image.open(filepath).convert("RGB")
- print 'estimate_angle image', filepath, "%dx%d" % im.size, im.mode, im.getbands()
+ print('estimate_angle image', filepath, "%dx%d" % im.size, im.mode, im.getbands())
imr, img, imb = im.split()
# calculate width and height of bbox in pixel from measured rectangle
@@ -184,7 +184,7 @@ def estimate_angle(filepath):
# which contains a geo-referenced red rectangle
angles = np.arange(-3.0, 3.0, 0.01)
matches = np.zeros(len(angles))
- for i in xrange(len(angles)):
+ for i in range(len(angles)):
im_bbox_rot = im_bbox.rotate(angles[i]) # gimp 1.62
im_corr = ImageChops.multiply(imr, im_bbox_rot)
# im_corr.show()
@@ -193,11 +193,11 @@ def estimate_angle(filepath):
# print ' angles[i],matches[i]',angles[i],matches[i]
angle_opt = angles[np.argmax(matches)]
- print ' angle_opt', angle_opt
+ print(' angle_opt', angle_opt)
ys = np.arange(0, int(0.2*wy), 1)
matches = np.zeros(len(ys))
- for y in xrange(len(ys)):
+ for y in range(len(ys)):
im_bbox = ImageChops.constant(im, 0)
draw = ImageDraw.Draw(im_bbox)
draw.line([(0, y), (wx, y)], fill=255)
@@ -211,7 +211,7 @@ def estimate_angle(filepath):
# print ' y,matches[y]',y,matches[y]
y_opt = ys[np.argmax(matches)]
- print ' y_opt', y_opt
+ print(' y_opt', y_opt)
if 0:
im_bbox = ImageChops.constant(im, 0)
@@ -224,13 +224,13 @@ def estimate_angle(filepath):
# assuming rectangle:
bbox = [(y_opt, y_opt), (wx-y_opt, y_opt), (wx-y_opt, wy-y_opt), (y_opt, wy-y_opt), (y_opt, y_opt)]
- print ' bbox', bbox
+ print(' bbox', bbox)
return -angle_opt, bbox
class MapsImporter(Process):
def __init__(self, maps, logger=None, **kwargs):
- print 'MapsImporter.__init__', maps, maps.parent.get_ident()
+ print('MapsImporter.__init__', maps, maps.parent.get_ident())
self._init_common('mapsimporter', name='Background maps importer',
logger=logger,
info='Downloads and converts background maps.',
@@ -329,7 +329,7 @@ def get_n_tiles(self):
def do(self):
self.update_params()
- print 'MapsImporter.do'
+ print('MapsImporter.do')
# self._maps.download(maptype = self.maptype, mapserver = self.mapserver,
# filetype = 'png', rootfilepath = None,
# width_tile = self.width_tile, size_tile = self.size_tile,
@@ -407,7 +407,7 @@ def _init_attributes(self):
))
def write_decals(self, fd, indent=4, rootdir=None, delta=np.zeros(3, dtype=np.float32)):
- print 'write_decals', len(self)
+ print('write_decals', len(self))
net = self.parent.get_net()
if rootdir is None:
rootdir = os.path.dirname(net.parent.get_rootfilepath())
@@ -494,7 +494,7 @@ def download(self, maptype='satellite', mapserver='google', apikey=None,
width = bbox_sumo[2]-x0
height = bbox_sumo[3]-y0
- print 'download to', rootfilepath
+ print('download to', rootfilepath)
# '+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs'
#params_proj="+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"
@@ -507,10 +507,10 @@ def download(self, maptype='satellite', mapserver='google', apikey=None,
nx = int(width/width_tile+0.5)
ny = int(height/width_tile+0.5)
- print ' offset', offset
- print ' bbox_sumo', bbox_sumo
- print ' width_tile', width_tile, 'm'
- print ' Will download %dx%d= %d maps' % (nx, ny, nx*ny)
+ print(' offset', offset)
+ print(' bbox_sumo', bbox_sumo)
+ print(' width_tile', width_tile, 'm')
+ print(' Will download %dx%d= %d maps' % (nx, ny, nx*ny))
#latlon_tile = np.array([(latlon_ne[0]-latlon_sw[0])/ny, (latlon_ne[1]-latlon_sw[1])/nx])
#filepaths = []
#centers = []
@@ -524,13 +524,13 @@ def download(self, maptype='satellite', mapserver='google', apikey=None,
angle = None
bbox = None
ids_map = []
- for ix in xrange(nx):
- for iy in xrange(ny):
+ for ix in range(nx):
+ for iy in range(ny):
# tile in SUMO network coords. These are the saved coords
x_tile = x0+ix*width_tile
y_tile = y0+iy*width_tile
- print ' x_tile,y_tile', x_tile, y_tile
+ print(' x_tile,y_tile', x_tile, y_tile)
bb = np.array([[x_tile, y_tile], [x_tile+width_tile, y_tile+width_tile]], np.float32)
# tile in absolute coordinates. Coords used for download
@@ -552,7 +552,7 @@ def download(self, maptype='satellite', mapserver='google', apikey=None,
angle, bbox = estimate_angle(filepath)
# sys.exit(0)
else:
- print 'WARNING in download: no file downloaded from mapserver'
+ print('WARNING in download: no file downloaded from mapserver')
return ids_map
bbox_tile_lonlat = download_googlemap_bb(filepath, bbox_tile, proj, apikey,
@@ -560,24 +560,24 @@ def download(self, maptype='satellite', mapserver='google', apikey=None,
maptype=maptype, color="0x0000000f")
if os.path.getsize(filepath) < 2000: # download failed
- print 'WARNING in download: no file downloaded from mapserver'
+ print('WARNING in download: no file downloaded from mapserver')
return ids_map
- print ' bbox_tile', bbox_tile
- print ' bbox_tile_lonlat', bbox_tile_lonlat
+ print(' bbox_tile', bbox_tile)
+ print(' bbox_tile_lonlat', bbox_tile_lonlat)
im = Image.open(filepath).convert("RGB")
if 1:
- print ' downloaded image', filepath, "%dx%d" % im.size, im.mode, im.getbands()
- print ' x_sw,y_sw', x_sw, y_sw
- print ' x_ne,y_ne', x_ne, y_ne
+ print(' downloaded image', filepath, "%dx%d" % im.size, im.mode, im.getbands())
+ print(' x_sw,y_sw', x_sw, y_sw)
+ print(' x_ne,y_ne', x_ne, y_ne)
# print ' start rotation'
im_rot = im.rotate(angle) # gimp 1.62
# im_rot.show()
region = im_rot.crop([bbox[0][0], bbox[0][1], bbox[2][0], bbox[2][1]])
regsize = region.size
- print ' regsize', regsize
+ print(' regsize', regsize)
im_crop = Image.new('RGB', (regsize[0], regsize[1]), (0, 0, 0))
im_crop.paste(region, (0, 0, regsize[0], regsize[1]))
im_tile = im_crop.resize((1024, 1024))
@@ -588,7 +588,7 @@ def download(self, maptype='satellite', mapserver='google', apikey=None,
im_tile.save(outfilepath, filetype.upper())
# print ' bb_orig=',bb
- print ' bb_orig', bb
+ print(' bb_orig', bb)
#lon0, lat0 = proj(x_tile-offset[0], y_tile-offset[1])
#lon1, lat1 = proj(x_tile+width_tile-offset[0], y_tile+width_tile-offset[1])
@@ -777,7 +777,7 @@ def do(self):
shapes = nodes.shapes[ids_node]
for shape, id_node in zip(shapes, ids_node):
- for coord, i in zip(shape, range(len(shape))):
+ for coord, i in zip(shape, list(range(len(shape)))):
# print coord
# print np.stack((longitudes, latitudes), axis = -1)
quote = self.evaluate_quote(longitudes, latitudes, elevations, coord[0], coord[1])
@@ -794,13 +794,13 @@ def do(self):
for shape, id_edge in zip(shapes, ids_edge):
positive_climb = 0.
negative_climb = 0.
- for coord, i in zip(shape, range(len(shape))):
+ for coord, i in zip(shape, list(range(len(shape)))):
# print coord
# print np.stack((longitudes, latitudes), axis = -1)
quote = self.evaluate_quote(longitudes, latitudes, elevations, coord[0], coord[1])
edges.shapes[id_edge][i] = [coord[0], coord[1], quote]
- print edges.shapes[id_edge][i]
+ print(edges.shapes[id_edge][i])
if i > 0 and (quote-quote_pre) > 0:
positive_climb += (quote-quote_pre)
elif i > 0 and (quote-quote_pre) < 0:
@@ -841,7 +841,7 @@ def evaluate_quote(self, longitudes, latitudes, elevations, x_point, y_point):
dists = np.sqrt(np.sum((np.stack((longitudes, latitudes), axis=-1) - [x_point, y_point])**2, 1))
if is_scipy:
- print 'use scipy to interpolate'
+ print('use scipy to interpolate')
#tck = interpolate.splrep(x, y, s=0)
#xnew = np.linspace(np.min(x), np.max(x), 200)
#ynew = interpolate.splev(xnew, tck, der=0)
@@ -853,7 +853,7 @@ def evaluate_quote(self, longitudes, latitudes, elevations, x_point, y_point):
## nearest_longitudes = longitudes[(longitudes < x_point + self.interpolation_radius)&(longitudes > x_point - self.interpolation_radius)&(latitudes < y_point + self.interpolation_radius)&(latitudes > y_point - self.interpolation_radius)]
## nearest_latitudes = latitudes[(longitudes < x_point + self.interpolation_radius)&(longitudes > x_point - self.interpolation_radius)&(latitudes < y_point + self.interpolation_radius)&(latitudes > y_point - self.interpolation_radius)]
## nearest_elevations = elevations[(longitudes < x_point + self.interpolation_radius)&(longitudes > x_point - self.interpolation_radius)&(latitudes < y_point + self.interpolation_radius)&(latitudes > y_point - self.interpolation_radius)]
- print[x_point, y_point], nearest_longitudes, nearest_latitudes, nearest_elevations
+ print([x_point, y_point], nearest_longitudes, nearest_latitudes, nearest_elevations)
if len(nearest_longitudes) > 15:
f_inter = interpolate.SmoothBivariateSpline(
@@ -880,7 +880,7 @@ def evaluate_quote(self, longitudes, latitudes, elevations, x_point, y_point):
quote = f_inter(x_point, y_point)
else:
quote = elevations[np.argmin(dists)]
- print 'nearest quote'
+ print('nearest quote')
else:
nearest_quotes = elevations[(dists < 100)]
@@ -895,7 +895,7 @@ def evaluate_quote(self, longitudes, latitudes, elevations, x_point, y_point):
quote = numerator/denominator
else:
quote = elevations[np.argmin(dists)]
- print 'nearest quote'
+ print('nearest quote')
return quote
diff --git a/tools/contributed/sumopy/coremodules/landuse/wxgui.py b/tools/contributed/sumopy/coremodules/landuse/wxgui.py
index 61144e13d8b9..f3a529a0a4e6 100644
--- a/tools/contributed/sumopy/coremodules/landuse/wxgui.py
+++ b/tools/contributed/sumopy/coremodules/landuse/wxgui.py
@@ -25,8 +25,8 @@
from agilepy.lib_wx.modulegui import ModuleGui
from agilepy.lib_wx.ogleditor import *
from agilepy.lib_wx.processdialog import ProcessDialog, ProcessDialogInteractive
-import landuse
-import maps
+from . import landuse
+from . import maps
from coremodules.misc import shapeformat
@@ -170,7 +170,7 @@ def make_zone(self, shape, zonename='', id_landusetype=-1):
id_landusetype=id_landusetype)
def on_add_element(self, shapes, ids):
- print 'on_add_element', shapes.attrname, ids
+ print('on_add_element', shapes.attrname, ids)
if shapes == self._zones.shapes:
self._id_target = ids[0]
self.add_row(_id=self._id_target,
@@ -1112,7 +1112,7 @@ def on_generate_facilities(self, event=None):
def close_process_facilities(self, dlg):
# called before destroying the process dialog
- print 'close_process_facilities', self.proc.status
+ print('close_process_facilities', self.proc.status)
if self.proc.status == 'success':
self._mainframe.browse_obj(self._landuse.facilities)
self._is_needs_refresh = True
diff --git a/tools/contributed/sumopy/coremodules/misc/__init__.py b/tools/contributed/sumopy/coremodules/misc/__init__.py
index b36f5878f6f7..120901128ab3 100644
--- a/tools/contributed/sumopy/coremodules/misc/__init__.py
+++ b/tools/contributed/sumopy/coremodules/misc/__init__.py
@@ -18,7 +18,7 @@
__version__ = "0.0"
-print 'init', __name__
+print('init', __name__)
def get_wxgui():
diff --git a/tools/contributed/sumopy/coremodules/misc/matplottools.py b/tools/contributed/sumopy/coremodules/misc/matplottools.py
index 3762178f394e..04b2dc28e845 100644
--- a/tools/contributed/sumopy/coremodules/misc/matplottools.py
+++ b/tools/contributed/sumopy/coremodules/misc/matplottools.py
@@ -38,7 +38,7 @@
gui_env = ['WXAgg', 'GTKAgg', 'Qt4Agg', 'TKAgg', ]
for gui in gui_env:
try:
- print "Try Matplotlib backend:", gui
+ print("Try Matplotlib backend:", gui)
mpl.use(gui, warn=False, force=True)
from mpl.patches import Arrow, Circle, Wedge, Polygon, FancyArrow
from mpl.mpl import PatchCollection
@@ -51,13 +51,13 @@
break
except:
continue
- print "Using Matplotlib backend", mpl.get_backend()
+ print("Using Matplotlib backend", mpl.get_backend())
try:
import wx
except:
- print 'WARNING: no wxwindows support'
+ print('WARNING: no wxwindows support')
COLORS = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c',
@@ -282,7 +282,7 @@ def plot_zone(ax, zone_shape, color_zone="gray",
is_fill = True
shape = (np.array(zone_shape)[:, :2]*mapscale).tolist()
- print shape
+ print(shape)
ax.add_patch(Polygon(shape,
linewidth=width_line,
edgecolor=color_outline,
@@ -485,7 +485,7 @@ def plot_edgevalues_arrows(ax, ids_result=None, config_ids_edge=None, values=[],
mapscale=1.0):
# ATTENTION: do not change order of args for backwards compatibility
- print 'plot_edgevalues_arrows ids_result width_max', width_max
+ print('plot_edgevalues_arrows ids_result width_max', width_max)
# print ' ids_result',ids_result
# print ' ids_edge',ids_edge
if ids_edge is None:
@@ -574,7 +574,7 @@ def plot_connectionvalues_arrows(ax, ids_result=None, config_ids_edge=None, valu
mapscale=1.0):
# ATTENTION: do not change order of args for backwards compatibility
- print 'plot_connectionvalues_arrows ids_result'
+ print('plot_connectionvalues_arrows ids_result')
head_width = headwidthstretch*width_max
fontsize_ticks = int(0.8*fontsize)
@@ -664,7 +664,7 @@ def plot_nodevalues(ax, ids_result=None, config_ids_edge=None, values=[],
mapscale=1.0):
# ATTENTION: do not change order of args for backwards compatibility
- print 'plot_nodevalues ids_result'
+ print('plot_nodevalues ids_result')
fontsize_ticks = int(0.8*fontsize)
patches = []
@@ -717,7 +717,7 @@ def plot_pointvalues(ax, x_coords, y_coords, values,
):
# ATTENTION: do not change order of args for backwards compatibility
- print 'plot_pointvalues ids_result'
+ print('plot_pointvalues ids_result')
fontsize_ticks = int(0.8*fontsize)
## i = 0
patches = []
@@ -776,7 +776,7 @@ def get_resultshape_connections(net, id_connection, dispacement):
"""
Return resultshape coords for this edge.
"""
- print 'get_resultshape', 'connections', 'id_connection', id_connection, 'dispacement', dispacement
+ print('get_resultshape', 'connections', 'id_connection', id_connection, 'dispacement', dispacement)
x0 = net.edges.shapes[net.lanes.ids_edge[net.connections.ids_fromlane[id_connection]]][-1, 0]
y0 = net.edges.shapes[net.lanes.ids_edge[net.connections.ids_fromlane[id_connection]]][-1, 1]
x1 = net.edges.shapes[net.lanes.ids_edge[net.connections.ids_tolane[id_connection]]][0, 0]
@@ -785,7 +785,7 @@ def get_resultshape_connections(net, id_connection, dispacement):
shape = np.array([[x0, y0, 0.], [x1, y1, 0.]])
else:
shape = np.array([[x0, y0, 0.], [x1 + 1., y1 + 1., 0.]])
- print 'connection', id_connection, 'has no shape'
+ print('connection', id_connection, 'has no shape')
n_vert = len(shape)
resultshape = np.zeros(shape.shape, np.float32)
#laneshapes = np.zeros((n_lanes,n_vert,3), np.float32)
@@ -1231,7 +1231,7 @@ def save_fig(self, figname):
rootfilepath = self.get_scenario().get_rootfilepath()
filepath = "%s_%s.%s" % (rootfilepath, figname, self.figformat)
- print 'save_fig', filepath
+ print('save_fig', filepath)
plt.savefig(filepath, format=self.figformat,
dpi=self.resolution,
# orientation='landscape',
@@ -1473,7 +1473,7 @@ def configure_map(self, axis, title=None, unit='m'):
# axis.set_ylim([y_min,y_max])
def plot_net(self, axis=None, title="", unit='', mapscale=None, is_configure=True):
- print 'plot_net mapscale', mapscale
+ print('plot_net mapscale', mapscale)
if mapscale is None:
unit = self.unit_mapscale
mapscale = self.get_attrsman().get_config('unit_mapscale').mapscales[unit]
diff --git a/tools/contributed/sumopy/coremodules/misc/shapefile.py b/tools/contributed/sumopy/coremodules/misc/shapefile.py
index 53f80bf8b7a9..e20469e0112b 100644
--- a/tools/contributed/sumopy/coremodules/misc/shapefile.py
+++ b/tools/contributed/sumopy/coremodules/misc/shapefile.py
@@ -86,7 +86,7 @@ def is_string(v):
if PYTHON3:
return isinstance(v, str)
else:
- return isinstance(v, basestring)
+ return isinstance(v, str)
class _Array(array.array):
@@ -160,17 +160,17 @@ def __init__(self, *args, **kwargs):
# print '\n\nReader.__init__: load',args[0]
self.load(args[0])
return
- if "shp" in kwargs.keys():
+ if "shp" in list(kwargs.keys()):
if hasattr(kwargs["shp"], "read"):
self.shp = kwargs["shp"]
if hasattr(self.shp, "seek"):
self.shp.seek(0)
- if "shx" in kwargs.keys():
+ if "shx" in list(kwargs.keys()):
if hasattr(kwargs["shx"], "read"):
self.shx = kwargs["shx"]
if hasattr(self.shx, "seek"):
self.shx.seek(0)
- if "dbf" in kwargs.keys():
+ if "dbf" in list(kwargs.keys()):
if hasattr(kwargs["dbf"], "read"):
self.dbf = kwargs["dbf"]
if hasattr(self.dbf, "seek"):
@@ -224,7 +224,7 @@ def __restrictIndex(self, i):
if abs(i) > rmax:
raise IndexError("Shape or Record index out of range.")
if i < 0:
- i = range(self.numRecords)[i]
+ i = list(range(self.numRecords))[i]
return i
def __shpHeader(self):
diff --git a/tools/contributed/sumopy/coremodules/misc/shapeformat.py b/tools/contributed/sumopy/coremodules/misc/shapeformat.py
index 1b1fa3a77bc4..0577b3fe4052 100644
--- a/tools/contributed/sumopy/coremodules/misc/shapeformat.py
+++ b/tools/contributed/sumopy/coremodules/misc/shapeformat.py
@@ -29,7 +29,7 @@
from agilepy.lib_base.processes import Process # ,CmlMixin,ff,call
#from coremodules.scenario import scenario
from agilepy.lib_base.misc import get_inversemap
-import shapefile
+from . import shapefile
try:
@@ -42,10 +42,10 @@
except:
IS_PROJ = False
- print 'Import error: in order to run the traces plugin please install the following modules:'
- print ' mpl_toolkits.basemap and shapely'
- print 'Please install these modules if you want to use it.'
- print __doc__
+ print('Import error: in order to run the traces plugin please install the following modules:')
+ print(' mpl_toolkits.basemap and shapely')
+ print('Please install these modules if you want to use it.')
+ print(__doc__)
raise
@@ -54,7 +54,7 @@
IS_GDAL = True
except:
IS_GDAL = False
- print 'WARNING: GDAL module is not installed.'
+ print('WARNING: GDAL module is not installed.')
# Value Shape Type
@@ -153,7 +153,7 @@ def get_shapeproj(projparams):
+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs
+init=EPSG:23032
"""
- import urllib
+ import urllib.request, urllib.parse, urllib.error
# print 'get_shapeproj',projparams
params = {}
for elem in projparams.split('+'):
@@ -162,13 +162,13 @@ def get_shapeproj(projparams):
params[attr.strip()] = val.strip()
# print 'params',params
- if params.has_key('init'):
+ if 'init' in params:
if params['init'].lower().find('epsg') >= 0:
epgs, number = params['init'].lower().split(':')
# print epgs,number
html = 'http://spatialreference.org/ref/epsg/%s/prj/' % number
- elif params.has_key('datum'):
+ elif 'datum' in params:
if params['datum'].lower().find('wgs') >= 0:
number = params['datum'][3:]
# print 'wgs', params['zone']+'n'
@@ -176,7 +176,7 @@ def get_shapeproj(projparams):
number, params['proj'], params['zone'])
# print 'html=',html
- f = urllib.urlopen(html)
+ f = urllib.request.urlopen(html)
return (f.read())
@@ -221,7 +221,7 @@ def get_proj4_from_shapefile(filepath):
gcs, proj, date = groups
proj4 = '+proj=longlat +datum=%s%s +no_defs' % (proj, date[2:])
else:
- print 'WARNING: found no prj file', projfilepath
+ print('WARNING: found no prj file', projfilepath)
return proj4
# return "+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"
# return '+proj=longlat +datum=WGS84 +ellps=WGS84 +a=6378137.0 +f=298.257223563 +pm=0.0 +no_defs'
@@ -241,7 +241,7 @@ def get_shapefile(filepath):
shapefilepath = os.path.join(dirname, basename)
- print 'import_shapefile *%s*' % (shapefilepath), type(str(shapefilepath))
+ print('import_shapefile *%s*' % (shapefilepath), type(str(shapefilepath)))
sf = shapefile.Reader(str(shapefilepath))
return sf
@@ -285,7 +285,7 @@ def __init__(self, ident='shapefileimporter', parent=None,
logger=None,
**kwargs):
- print 'ShapefileImporter.__init__', filepath # ,projparams_target_default, projparams_shape
+ print('ShapefileImporter.__init__', filepath) # ,projparams_target_default, projparams_shape
self._init_common(ident,
parent=parent,
name=name,
@@ -308,7 +308,7 @@ def __init__(self, ident='shapefileimporter', parent=None,
attrsman_parent = parent.get_attrsman()
self._coordsconfig = attrsman_parent.get_config(coordsattr)
- for attrname, shapeattr_default in attrnames_to_shapeattrs.iteritems():
+ for attrname, shapeattr_default in attrnames_to_shapeattrs.items():
config = attrsman_parent.get_config(attrname)
fieldname = 'fieldname_'+attrname
setattr(self, fieldname,
@@ -461,25 +461,25 @@ def make_fieldinfo(self):
self._fieldinfo = {}
fields = self._sf.fields
#records = sf.records()
- for ind_field, field in zip(xrange(1, len(fields)), fields[1:]):
+ for ind_field, field in zip(range(1, len(fields)), fields[1:]):
attrname, default, dtype, digits_fraction = get_fieldinfo(field)
self._fieldinfo[attrname] = (ind_field-1, default, dtype, digits_fraction)
def get_projections(self):
- print 'get_projections IS_PROJ', IS_PROJ
- print 'self.projparams_shape', self.projparams_shape, 'self._projparams_target', self._projparams_target
+ print('get_projections IS_PROJ', IS_PROJ)
+ print('self.projparams_shape', self.projparams_shape, 'self._projparams_target', self._projparams_target)
proj_shape = None
proj_target = None
if self.is_use_shapeproj & (self.projparams_shape == ''):
- print ' no shape projection given'
+ print(' no shape projection given')
self.projparams_shape = get_proj4_from_shapefile(self.filepath)
- print ' from prj file projparams_shape', self.projparams_shape
+ print(' from prj file projparams_shape', self.projparams_shape)
if self.projparams_shape == '':
# no results from shapefile info, let's try to guess
self.projparams_shape = self.guess_shapeproj()
- print ' from guessing projparams_shape', self.projparams_shape
+ print(' from guessing projparams_shape', self.projparams_shape)
# if self.is_guess_targetproj:
# self.projparams_target = self.guess_targetproj()
@@ -490,14 +490,14 @@ def get_projections(self):
if self.is_use_shapeproj:
try:
- print ' use projparams_shape =*%s*' % self.projparams_shape, type(str(self.projparams_shape)), pyproj.Proj(str(self.projparams_shape))
+ print(' use projparams_shape =*%s*' % self.projparams_shape, type(str(self.projparams_shape)), pyproj.Proj(str(self.projparams_shape)))
proj_shape = pyproj.Proj(str(self.projparams_shape))
except:
proj_shape = None
if self.is_use_targetproj:
try:
- print ' use projparams_target =*%s*' % self._projparams_target, type(str(self._projparams_target)), pyproj.Proj(str(self._projparams_target))
+ print(' use projparams_target =*%s*' % self._projparams_target, type(str(self._projparams_target)), pyproj.Proj(str(self._projparams_target)))
proj_target = pyproj.Proj(str(self._projparams_target))
except:
proj_target = None
@@ -525,7 +525,7 @@ def _get_attrconfs_shapeinds(self):
shapeattrname = fieldconf.get_value()
attrconf = attrsman_parent.get_config(fieldconf.attrname_orig)
- if self._fieldinfo.has_key(shapeattrname):
+ if shapeattrname in self._fieldinfo:
attrconfs.append(attrconf)
shapeinds.append(self._fieldinfo[shapeattrname][0])
@@ -538,7 +538,7 @@ def is_ready(self):
return True
def import_shapes(self):
- print 'import_shapes'
+ print('import_shapes')
shapes = self._sf.shapes()
shapetype = shapes[3].shapeType
@@ -551,10 +551,10 @@ def import_shapes(self):
# print ' proj_shape',proj_shape,'proj_target',proj_target
if self.is_use_shapeproj & (proj_shape is None):
- print 'WARNING: import_shapes, no shape projection'
+ print('WARNING: import_shapes, no shape projection')
return [], 0
if self.is_use_targetproj & (proj_target is None):
- print 'WARNING: import_shapes, no target projection'
+ print('WARNING: import_shapes, no target projection')
return [], 0
offset = np.array([0.0, 0.0, 0.0], dtype=np.float32)
@@ -572,10 +572,10 @@ def import_shapes(self):
# print ' offset_target',offset_target
coordsconfig = self._coordsconfig
ids = coordsconfig.get_manager().add_rows(n_records)
- print ' n_records', n_records, shapetype
+ print(' n_records', n_records, shapetype)
if (shapetype == 3) | (shapetype == 5): # poliline = 3, polygon = 5
- for ind_rec, id_attr in zip(xrange(n_records), ids):
+ for ind_rec, id_attr in zip(range(n_records), ids):
# print ' ind_rec',ind_rec,'id_attr',id_attr
shape_rec = self._sf.shapeRecord(ind_rec)
points = shape_rec.shape.points
@@ -583,26 +583,26 @@ def import_shapes(self):
n_points = len(points)
shape = np.zeros((n_points, 3), dtype=np.float32) + offset
if self.is_use_targetproj & self.is_use_shapeproj:
- for ind, point in zip(xrange(n_points), points):
+ for ind, point in zip(range(n_points), points):
shape[ind, 0:2] += np.array(pyproj.transform(proj_shape, proj_target, point[0], point[1]))
elif self.is_use_targetproj:
- for ind, point in zip(xrange(n_points), points):
+ for ind, point in zip(range(n_points), points):
shape[ind, 0:2] += proj_target(point[0], point[1])
elif self.is_use_shapeproj:
- for ind, point in zip(xrange(n_points), points):
+ for ind, point in zip(range(n_points), points):
shape[ind, 0:2] += proj_shape(point[0], point[1])
else: # no projection
- for ind, point in zip(xrange(n_points), points):
+ for ind, point in zip(range(n_points), points):
shape[ind, 0:2] += (point[0], point[1])
coordsconfig[id_attr] = list(shape)
# print ' coords=',coordsconfig[id_attr]
elif shapetype == 1:
- for ind_rec, id_attr in zip(xrange(n_records), ids):
+ for ind_rec, id_attr in zip(range(n_records), ids):
# print ' ind_rec',ind_rec,id_attr
shape_rec = self._sf.shapeRecord(ind_rec)
points = shape_rec.shape.points
@@ -642,7 +642,7 @@ def import_shapes(self):
return ids, shapetype
def do(self):
- print self.ident+'.do'
+ print(self.ident+'.do')
#fields = self._sf.fields
#records = self._sf.records()
@@ -661,7 +661,7 @@ def do(self):
ids, shapetype = self.import_shapes()
if len(ids) == 0:
- print 'WARNING: import_shapes failed'
+ print('WARNING: import_shapes failed')
return False
n_attrs = len(attrconfs)
@@ -669,7 +669,7 @@ def do(self):
# import no attributes from table
if (n_attrs == 0) | (n_records == 0):
- print 'WARNING: successfully imported no data'
+ print('WARNING: successfully imported no data')
return True
shaperecords = self._sf.shapeRecord
@@ -693,17 +693,17 @@ def do(self):
if not np.any(self.inboundaries(np.array(shape, dtype=np.float32))):
ids_outside.append(id_shape)
- print ' ids_outside', ids_outside
+ print(' ids_outside', ids_outside)
self.parent.del_rows(ids_outside)
return True
def import_data(self, shaperecords, ids, attrconfs, shapeinds):
- print 'import_data'
+ print('import_data')
n_records = len(ids)
objecttype = np.dtype(np.object) # np.dtype(np.zeros(1,dtype = np.object))
values_invalid = ['NULL', '\n']
- for ind_rec, id_attr in zip(xrange(n_records), ids):
+ for ind_rec, id_attr in zip(range(n_records), ids):
shape_rec = shaperecords(ind_rec)
# print ' shape_rec',id_attr,shape_rec.record
@@ -861,7 +861,7 @@ def export_shapefile(self, filepath=None):
If no file is given, the default file path will be selected.
"""
# https://code.google.com/p/pyshp/
- print '\nexport_shapefile', filepath
+ print('\nexport_shapefile', filepath)
#proj_target, offset_target = self.parent.get_proj_offset()
if len(self) == 0:
return False
@@ -940,8 +940,8 @@ def export_shapefile(self, filepath=None):
prjfile.close()
return True
except:
- print 'WARNING in export_shapefile:\n no projection file written (probably no Internet connection).'
- print 'Open shapefile with projection: %s.' % self._projparams.get_value()
+ print('WARNING in export_shapefile:\n no projection file written (probably no Internet connection).')
+ print('Open shapefile with projection: %s.' % self._projparams.get_value())
# raise
return False
@@ -987,7 +987,7 @@ def import_shapefile(self, filepath=None, projparams=None, projparams_target=Non
self.filepath.set_value(filepath)
basefilepath = self.get_basefilepath(filepath)
- print 'import_shapefile *%s*' % (basefilepath), type(str(basefilepath))
+ print('import_shapefile *%s*' % (basefilepath), type(str(basefilepath)))
sf = shapefile.Reader(str(basefilepath))
shapes = sf.shapes()
@@ -1023,18 +1023,18 @@ def import_shapefile(self, filepath=None, projparams=None, projparams_target=Non
# print ' fields',len(fields),fields
n = len(attrnames)
- for ind in xrange(len(records)):
+ for ind in range(len(records)):
shape_rec = sf.shapeRecord(ind)
# use first field as id, but will also be a regular attribute
id_egde = shape_rec.record[0]
attrrow = {}
- print '\n id_egde', id_egde
- for i, field in zip(xrange(n), fields[1:]):
+ print('\n id_egde', id_egde)
+ for i, field in zip(range(n), fields[1:]):
val = shape_rec.record[i]
# print ' ',i,attrnames[i],'>>'+repr(val)+'<<', type(val)
if field[1] == 'N':
- if type(val) == types.StringType:
+ if type(val) == bytes:
val = -1
attrrow[attrnames[i]] = val
@@ -1053,7 +1053,7 @@ def import_shapefile(self, filepath=None, projparams=None, projparams_target=Non
#self.set_row(id_egde, **attrrow)
id = self.add_row(key=id_egde)
- for attrname, val in attrrow.iteritems():
+ for attrname, val in attrrow.items():
# print ' ',attrname,'>>'+repr(val)+'<<', type(val)
getattr(self, attrname)[id] = val
@@ -1082,9 +1082,9 @@ def nodes_to_shapefile(net, filepath, dataname='nodeshapedata',
map_nodetypes = get_inversemap(nodes.types.choices)
nodetypes = np.zeros(max(map_nodetypes.keys())+1, dtype=np.object)
- nodetypes[map_nodetypes.keys()] = map_nodetypes.values()
+ nodetypes[list(map_nodetypes.keys())] = list(map_nodetypes.values())
- print 'nodes_to_shapefile', filepath
+ print('nodes_to_shapefile', filepath)
for attr in attrlist:
shapedata.add_field(attr[2:])
@@ -1131,7 +1131,7 @@ def edges_to_shapefile(net, filepath, dataname='edgeshapedata',
('speeds_max', 'val', 'SPEED_MAX', 'N', 6, 3),
]
- print 'edges_to_shapefile', filepath
+ print('edges_to_shapefile', filepath)
for attr in attrlist:
shapedata.add_field(attr[2:])
@@ -1153,10 +1153,10 @@ def edges_to_shapefile(net, filepath, dataname='edgeshapedata',
if is_access:
accesses = np.zeros(len(ids_edge), dtype=object)
accesses[:] = ''
- for mode, shapemode in VEHICLECLASSCODE.iteritems():
+ for mode, shapemode in VEHICLECLASSCODE.items():
# here we select this mode for access level 1 and 2
# -1 0 1 2
- accessvec = np.array(['', 'X', shapemode, shapemode], dtype=np.unicode)
+ accessvec = np.array(['', 'X', shapemode, shapemode], dtype=np.str)
if net.modes.has_modename(mode):
accesslevels = edges.get_accesslevels(net.modes.get_id_mode(mode))
@@ -1196,7 +1196,7 @@ def facilities_to_shapefile(facilities, filepath, dataname='facilitydata',
('osmkeys', 'val', 'OSMKEY', 'C', 32, 0),
]
- print 'facilities_to_shapefile', filepath
+ print('facilities_to_shapefile', filepath)
for attr in attrlist:
shapedata.add_field(attr[2:])
@@ -1250,7 +1250,7 @@ def zones_to_shapefile(zones, filepath, dataname='zonedata',
# ('entropies','id','ENTROPY','N',12,5),
]
- print 'zones_to_shapefile', filepath
+ print('zones_to_shapefile', filepath)
for attr in attrlist:
shapedata.add_field(attr[2:])
diff --git a/tools/contributed/sumopy/coremodules/network/__init__.py b/tools/contributed/sumopy/coremodules/network/__init__.py
index cab987aa8f9c..02fdf630fcec 100644
--- a/tools/contributed/sumopy/coremodules/network/__init__.py
+++ b/tools/contributed/sumopy/coremodules/network/__init__.py
@@ -18,12 +18,12 @@
__version__ = "0.0"
-print 'init', __name__
+print('init', __name__)
def get_wxgui():
# try:
- from wxgui import WxGui
+ from .wxgui import WxGui
return WxGui(__name__)
# except:
# return None
diff --git a/tools/contributed/sumopy/coremodules/network/netconvert.py b/tools/contributed/sumopy/coremodules/network/netconvert.py
index 224fe145da86..7ed9512845ef 100644
--- a/tools/contributed/sumopy/coremodules/network/netconvert.py
+++ b/tools/contributed/sumopy/coremodules/network/netconvert.py
@@ -852,13 +852,13 @@ def do(self):
# print 'SumonetImporter.do',cml
self.run_cml(cml)
if self.status == 'success':
- print ' Netconvert done.'
+ print(' Netconvert done.')
if os.path.isfile(self.netfilepath):
- print ' sumo.net.xml exists, start generation of xml files'
+ print(' sumo.net.xml exists, start generation of xml files')
net.import_netxml(self.netfilepath)
if self.is_import_ptstops:
if os.path.isfile(ptstopfilepath):
- print ' ptfilepath exists, start importing ptstops'
+ print(' ptfilepath exists, start importing ptstops')
net.ptstops.import_sumostops(ptstopfilepath)
# print ' import in sumopy done.'
@@ -908,7 +908,7 @@ def __init__(self, net, netfilepath=None,
self.init_options_tls()
def import_tlsxml(self, is_remove_xmlfiles=False):
- print 'import_tlsxml'
+ print('import_tlsxml')
filepath = self.netfilepath
net = self.parent
rootname = net.get_rootfilename()
@@ -922,13 +922,13 @@ def import_tlsxml(self, is_remove_xmlfiles=False):
+ ' --plain-output-prefix '+filepathlist_to_filepathstring(os.path.join(dirname, rootname))
proc = subprocess.Popen(cml, shell=True)
- print ' run_cml cml=', cml
- print ' pid = ', proc.pid
+ print(' run_cml cml=', cml)
+ print(' pid = ', proc.pid)
proc.wait()
if not proc.returncode:
tlsfilepath = os.path.join(dirname, rootname+'.tll.xml')
- print ' import_sumotls', tlsfilepath
+ print(' import_sumotls', tlsfilepath)
net.import_sumotls_to_net(tlsfilepath, is_remove_xmlfiles=is_remove_xmlfiles)
return True
@@ -949,7 +949,7 @@ def do(self):
+ ' --connection-files '+filepathlist_to_filepathstring(filepath_connections)\
#+' --output-file '+filepathlist_to_filepathstring(filepath)
- print ' cmlbase', cmlbase
+ print(' cmlbase', cmlbase)
self.reset_cml(cmlbase)
# apply netconvert and reimport
@@ -960,7 +960,7 @@ def do(self):
# print 'SumonetImporter.do',cml
self.run_cml(cml)
if self.status == 'success':
- print ' Netconvert done.'
+ print(' Netconvert done.')
if os.path.isfile(self.netfilepath):
# print ' sumo.net.xml exists, start generation of xml files'
# self.parent.import_netxml(self.netfilepath)
diff --git a/tools/contributed/sumopy/coremodules/network/netgenerate.py b/tools/contributed/sumopy/coremodules/network/netgenerate.py
index 324554ce2a4a..6dae9f64abaa 100644
--- a/tools/contributed/sumopy/coremodules/network/netgenerate.py
+++ b/tools/contributed/sumopy/coremodules/network/netgenerate.py
@@ -27,7 +27,7 @@
#from coremodules.modules_common import *
#from coremodules.network.network import SumoIdsConf, MODES
from agilepy.lib_base.processes import Process, CmlMixin
-import netconvert
+from . import netconvert
from agilepy.lib_base.geometry import get_length_polypoints, get_dist_point_to_segs, get_diff_angle_clockwise
@@ -43,7 +43,7 @@ def init_common_netgen(self, ident, nettype, net, name, info,
logger=logger,
cml='netgenerate')
- print 'init_common_netgen', nettype
+ print('init_common_netgen', nettype)
self.add_option('nettype', '--'+nettype,
groupnames=['_private'],
diff --git a/tools/contributed/sumopy/coremodules/network/network.py b/tools/contributed/sumopy/coremodules/network/network.py
index 1cf8481c3f01..2f7721b731f3 100644
--- a/tools/contributed/sumopy/coremodules/network/network.py
+++ b/tools/contributed/sumopy/coremodules/network/network.py
@@ -18,9 +18,9 @@
from agilepy.lib_base.processes import Process, CmlMixin, P
-from routing import get_mincostroute_edge2edges
-import publictransportnet as pt
-import netconvert
+from .routing import get_mincostroute_edge2edges
+from . import publictransportnet as pt
+from . import netconvert
from agilepy.lib_base.geometry import *
from agilepy.lib_base.misc import filepathlist_to_filepathstring, filepathstring_to_filepathlist
import agilepy.lib_base.xmlman as xm
@@ -162,7 +162,7 @@ def add_default(self):
Sets the default maximum possible speed for certain modes.
"""
# print 'MODES.add_default'
- self.add_rows(ids=MODES.values(), names=MODES.keys())
+ self.add_rows(ids=list(MODES.values()), names=list(MODES.keys()))
# these speeds are used to estimate free flow link travel times
# mainly for routing purposes
@@ -197,7 +197,7 @@ def add_default(self):
('rail_fast', 350),
])
- for mode, speed_kmph in speeds_max_kmph.iteritems():
+ for mode, speed_kmph in speeds_max_kmph.items():
self.speeds_max[self.get_id_mode(mode)] = float(speed_kmph)/3.6
# print ' self.speeds_max',self.speeds_max.get_value()
@@ -449,11 +449,11 @@ def export_sumoxml(self, filepath=None, encoding='UTF-8'):
if filepath is None:
filepath = self.parent.get_rootfilepath()+'.tll.xml'
- print 'export_sumoxml', filepath
+ print('export_sumoxml', filepath)
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in export_sumoxml: could not open', filepath
+ print('WARNING in export_sumoxml: could not open', filepath)
return False
fd.write('\n' % encoding)
@@ -715,7 +715,7 @@ def make(self, **kwargs):
def analyze_connections(self, **kwargs):
- print 'Analyze connections'
+ print('Analyze connections')
network = self.parent
edges = network.edges
@@ -744,7 +744,7 @@ def analyze_connections(self, **kwargs):
coord_incoming_penultimate = incoming_edge_shape[-2]
coord_outgoing_first = outgoing_edge_shape[0]
coord_outgoing_second = outgoing_edge_shape[1]
- print 'connection', connection
+ print('connection', connection)
# print 'coord_node:',coord_node, 'coord_incoming:',coord_incoming, 'coord_outgoing:',coord_outgoing
azimut_incoming = self.get_azimut(coord_incoming_last, coord_incoming_penultimate)
azimut_outgoing = self.get_azimut(coord_outgoing_first, coord_outgoing_second)
@@ -761,19 +761,19 @@ def analyze_connections(self, **kwargs):
# Right turn
if np.pi*3/4 <= np.absolute(diff_azimut) and np.absolute(diff_azimut) <= np.pi*5/4:
connections.turns_type[connection] = 'crossing'
- print 'crossing'
+ print('crossing')
nodes.n_left_turns[node] += 1
elif np.absolute(diff_azimut) <= np.pi/18 or np.absolute(diff_azimut) >= np.pi*35/18:
connections.turns_type[connection] = 'u_turn'
- print 'u_turn'
+ print('u_turn')
nodes.n_right_turns[node] += 1
elif (-3*np.pi/4 < diff_azimut and diff_azimut < -np.pi/18) or (5*np.pi/4 < diff_azimut and diff_azimut < np.pi*35/18):
connections.turns_type[connection] = 'right_turn'
- print 'right turn'
+ print('right turn')
nodes.n_crossings[node] += 1
elif (np.pi/18 < diff_azimut and diff_azimut < 3*np.pi/4) or (-np.pi*35/18 < diff_azimut and diff_azimut < -5*np.pi/4):
connections.turns_type[connection] = 'left_turn'
- print 'left turn'
+ print('left turn')
nodes.n_u_turns[node] += 1
init_point = incoming_edge_shape[-1]
@@ -807,7 +807,7 @@ def get_azimut(self, point1, point2):
elif (x_inc-x_nod) < 0 and (y_inc-y_nod) >= 0:
azimut_incoming = np.pi*3/2 + np.arctan((y_inc-y_nod)/(x_nod-x_inc))
else:
- print 'Warning, the two points are the same'
+ print('Warning, the two points are the same')
# print point1, point2
azimut_incoming = 0
@@ -836,7 +836,7 @@ def export_sumoxml(self, filepath, encoding='UTF-8'):
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in export_sumoxml: could not open', filepath
+ print('WARNING in export_sumoxml: could not open', filepath)
return False
fd.write('\n' % encoding)
@@ -1091,7 +1091,7 @@ def reshape_edgelanes(self, id_edge):
edges = self.parent.edges
ids_lane = edges.ids_lanes[id_edge]
- print 'reshape_edgelanes id_edge', id_edge, 'id_edge_sumo', edges.ids_sumo[id_edge], len(ids_lane)
+ print('reshape_edgelanes id_edge', id_edge, 'id_edge_sumo', edges.ids_sumo[id_edge], len(ids_lane))
shape = np.array(edges.shapes[id_edge], np.float32)
@@ -1153,7 +1153,7 @@ def get_laneindexes_allowed(self, ids_lane, id_mode):
else:
indexes.append(ind)
ind += 1
- print 'WARNING: ignoring mode has no access on footpath'
+ print('WARNING: ignoring mode has no access on footpath')
return []
# return len(ids_lane)-1
@@ -1199,7 +1199,7 @@ def get_laneindex_allowed(self, ids_lane, id_mode):
else:
return ind
- print 'WARNING: ignoring mode has no access on footpath'
+ print('WARNING: ignoring mode has no access on footpath')
return -1
# return len(ids_lane)-1
@@ -1253,7 +1253,7 @@ def get_accesslevel_lanes(self, ids_lane, id_mode):
is_mode_mixed = False
is_modes_all = False
- for i, id_lane, ids_modes_allow, ids_modes_disallow in zip(xrange(len(ids_lane)), ids_lane, self.ids_modes_allow[ids_lane], self.ids_modes_disallow[ids_lane]):
+ for i, id_lane, ids_modes_allow, ids_modes_disallow in zip(range(len(ids_lane)), ids_lane, self.ids_modes_allow[ids_lane], self.ids_modes_disallow[ids_lane]):
is_mode_only = False
is_mode_mixed = False
is_modes_all = False
@@ -1759,7 +1759,7 @@ def get_fstar(self, is_return_lists=False, is_return_arrays=False,
are considered, disregarding the actual connections
"""
- print 'get_fstar id_mode', id_mode, 'is_return_lists', is_return_lists, 'is_return_arrays', is_return_arrays
+ print('get_fstar id_mode', id_mode, 'is_return_lists', is_return_lists, 'is_return_arrays', is_return_arrays)
#ids_edge = self.get_ids()
#fstar = np.array(np.zeros(np.max(ids_edge)+1, np.obj))
fstar = {}
@@ -2017,7 +2017,7 @@ def get_distances(self, id_mode=0, is_check_lanes=False, is_precise=True, modeco
If not allowed on a particular edge,
then the respective edge distance is nan.
"""
- print 'get_distances id_mode,is_check_lanes,speed_max', id_mode, is_check_lanes, is_precise
+ print('get_distances id_mode,is_check_lanes,speed_max', id_mode, is_check_lanes, is_precise)
ids_edge = self.get_ids()
dists = np.zeros(np.max(ids_edge)+1, np.float32)
#speeds = self.speeds_max[ids_edge]
@@ -2140,7 +2140,7 @@ def select_accessible_mode(self, id_mode):
ids_edges = self.get_ids()
are_allowed = np.zeros(len(ids_edges), dtype=np.bool)
inds_lane = np.zeros(len(ids_edges), dtype=np.int32)
- for i, id_edge in zip(xrange(len(ids_edges)), ids_edges):
+ for i, id_edge in zip(range(len(ids_edges)), ids_edges):
ind_lane = get_laneindex_allowed(ids_lanes[id_edge], id_mode)
are_allowed[i] = ind_lane >= 0
inds_lane[i] = ind_lane
@@ -2247,7 +2247,7 @@ def make_segment_edge_map(self, ids=None, is_laneshapes=True):
inds = self.get_inds()
else:
inds = self.get_inds(ids)
- print 'make_linevertices', len(inds)
+ print('make_linevertices', len(inds))
linevertices = np.zeros((0, 2, 3), np.float32)
vertexinds = np.zeros((0, 2), np.int32)
@@ -2281,7 +2281,7 @@ def make_segment_edge_map(self, ids=None, is_laneshapes=True):
# print ' =======',n_seg#,polyline
if n_seg > 1:
- polyvinds = range(n_seg)
+ polyvinds = list(range(n_seg))
# print ' polyvinds\n',polyvinds
vi = np.zeros((2*n_seg-2), np.int32)
vi[0] = polyvinds[0]
@@ -2518,7 +2518,7 @@ def export_sumoxml(self, filepath, encoding='UTF-8'):
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in export_sumoxml: could not open', filepath
+ print('WARNING in export_sumoxml: could not open', filepath)
return False
fd.write('\n' % encoding)
@@ -2531,7 +2531,7 @@ def export_sumoxml(self, filepath, encoding='UTF-8'):
return True
def export_edgeweights_xml(self, filepath=None, weights=None, time_begin=0, time_end=3600, ident='w1', encoding='UTF-8'):
- print 'export_edgeweights_xml', time_begin, time_end, 'filepath', filepath
+ print('export_edgeweights_xml', time_begin, time_end, 'filepath', filepath)
#
#
#
@@ -2545,7 +2545,7 @@ def export_edgeweights_xml(self, filepath=None, weights=None, time_begin=0, time
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in export_edgeweights_xml: could not open', filepath
+ print('WARNING in export_edgeweights_xml: could not open', filepath)
return ''
if weights is None:
@@ -2574,7 +2574,7 @@ def export_edgeweights_xml(self, filepath=None, weights=None, time_begin=0, time
return filepath
def update(self, ids=None, is_update_lanes=False):
- print 'Edges.update'
+ print('Edges.update')
if ids is None:
self.widths.value = self.nums_lanes.value * self.widths_lanes_default.value \
@@ -2640,7 +2640,7 @@ def update_lanes(self, id_edge, ids_lane):
# no lanes given...make some with default values
ids_lane = []
lanes = self.get_lanes()
- for i in xrange(self.nums_lanes[id_edge]):
+ for i in range(self.nums_lanes[id_edge]):
id_lane = lanes.make(index=i, id_edge=id_edge)
ids_lane.append(id_lane)
@@ -2720,7 +2720,7 @@ def correct_spread(self):
def analyze_edges(self, **kwargs):
# TODO: this should feed into a temporary field
- print 'Analyze edges'
+ print('Analyze edges')
# individuate edge typologies (pedestrian, bike lane, bike/pedestrian,
# one-way road, 2-way road)
network = self.parent
@@ -2739,10 +2739,10 @@ def analyze_edges(self, **kwargs):
if len(lanes.ids_mode[id_lanes]) == 1:
if lanes.ids_mode[id_lanes] == [id_ped]:
pedestrian_edges.append(id_edge)
- print 'edge', id_edge, 'ped'
+ print('edge', id_edge, 'ped')
if lanes.ids_mode[id_lanes] == [id_bike]:
cycling_edges.append(id_edge)
- print 'edge', id_edge, 'cycl'
+ print('edge', id_edge, 'cycl')
edges.edge_typology[pedestrian_edges] = 'Pedestrian'
edges.edge_typology[cycling_edges] = 'bike lane'
@@ -2757,14 +2757,14 @@ def analyze_edges(self, **kwargs):
if len(lanes.ids_modes_allow[id_lanes][0]) == 2 and len(id_lanes) == 1:
if id_bike in np.array(lanes.ids_modes_allow[id_lanes][0]) and id_ped in np.array(lanes.ids_modes_allow[id_lanes][0]):
cycling_ped_edges.append(id_edge)
- print 'edge', id_edge, 'cycl_ped'
+ print('edge', id_edge, 'cycl_ped')
elif len(id_lanes) == 2:
if lanes.ids_mode[id_lanes[0]] == id_bike and lanes.ids_mode[id_lanes[1]] == id_ped:
cycling_ped_edges.append(id_edge)
- print 'edge', id_edge, 'cycl_ped'
+ print('edge', id_edge, 'cycl_ped')
if lanes.ids_mode[id_lanes[0]] == id_ped and lanes.ids_mode[id_lanes[1]] == id_bike:
cycling_ped_edges.append(id_edge)
- print 'edge', id_edge, 'cycl_ped'
+ print('edge', id_edge, 'cycl_ped')
edges.edge_typology[cycling_ped_edges] = 'Bike/Pedestrian'
ids_edge_car = ids_edge
@@ -3051,7 +3051,7 @@ def export_sumoxml(self, filepath, encoding='UTF-8'):
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in export_sumoxml: could not open', filepath
+ print('WARNING in export_sumoxml: could not open', filepath)
return False
fd.write('\n' % encoding)
indent = 0
@@ -3116,7 +3116,7 @@ def write_xml(self, fd, indent):
def clean(self, is_reshape_edgelanes=False, nodestretchfactor=1.2, n_min_nodeedges=2):
# is_reshape_edgelanes = False, nodestretchfactor = 2.8
- print 'Nodes.clean', len(self), 'is_reshape_edgelanes', is_reshape_edgelanes
+ print('Nodes.clean', len(self), 'is_reshape_edgelanes', is_reshape_edgelanes)
edges = self.parent.edges
lanes = self.parent.lanes
@@ -3173,7 +3173,7 @@ def clean(self, is_reshape_edgelanes=False, nodestretchfactor=1.2, n_min_nodeedg
shape = edges.shapes[id_edge]
n_shape = len(shape)
# edges.shapes[id_edge][::-1]:
- for i in xrange(n_shape-1, -1, -1):
+ for i in range(n_shape-1, -1, -1):
d = get_norm_2d(np.array([shape[i]-coords]))[0]
# print ' i,d,r',i , d, radius,d>radius
if d > radius:
@@ -3208,7 +3208,7 @@ def clean(self, is_reshape_edgelanes=False, nodestretchfactor=1.2, n_min_nodeedg
shape = edges.shapes[id_edge]
n_shape = len(shape)
# edges.shapes[id_edge][::-1]:
- for i in xrange(n_shape):
+ for i in range(n_shape):
d = get_norm_2d(np.array([shape[i]-coords]))[0]
# print ' i,d,r',i , d, radius,d>radius
if d > radius:
@@ -3242,7 +3242,7 @@ def clean(self, is_reshape_edgelanes=False, nodestretchfactor=1.2, n_min_nodeedg
class Network(cm.BaseObjman):
def __init__(self, parent=None, name='Network', **kwargs):
- print 'Network.__init__', parent, name
+ print('Network.__init__', parent, name)
self._init_objman(ident='net', parent=parent, name=name,
# xmltag = 'net',# no, done by netconvert
version=0.1,
@@ -3495,7 +3495,7 @@ def clear_net(self):
# do other cleanup jobs
def call_netedit(self, filepath=None, is_maps=False, is_poly=True, command='netedit'):
- print 'call_netedit'
+ print('call_netedit')
#filepath = self.export_netxml(filepath)
if filepath is None:
filepath = self.get_filepath()
@@ -3539,23 +3539,23 @@ def call_netedit(self, filepath=None, is_maps=False, is_poly=True, command='nete
cml += ' --tllogic-files '+filepathlist_to_filepathstring(filepath_tlss)
proc = subprocess.Popen(cml, shell=True)
- print ' run_cml cml=', cml
+ print(' run_cml cml=', cml)
# print ' pid = ',proc.pid
proc.wait()
if proc.returncode == 0:
- print ' ', command, ':success'
+ print(' ', command, ':success')
return self.import_netxml()
# return self.import_xml() # use if netedit exports to plain xml files
else:
- print ' ', command, ':error'
+ print(' ', command, ':error')
return False
else:
- print ' netconvert:error'
+ print(' netconvert:error')
return False
def call_sumogui(self, filepath=None, is_maps=True, is_poly=True):
- print 'call_sumogui', filepath, is_maps, is_poly
+ print('call_sumogui', filepath, is_maps, is_poly)
if filepath is None:
filepath = self.get_filepath()
@@ -3606,8 +3606,8 @@ def call_sumogui(self, filepath=None, is_maps=True, is_poly=True):
+ option_addfiles
proc = subprocess.Popen(cml, shell=True)
- print ' run_cml cml=', cml
- print ' pid = ', proc.pid
+ print(' run_cml cml=', cml)
+ print(' pid = ', proc.pid)
proc.wait()
return proc.returncode
@@ -3642,7 +3642,7 @@ def write_guiconfig(self, rootname=None, dirname=None, is_maps=False, delta=np.z
else:
configfilepath = self.get_rootfilepath()+'.netedit.xml'
- print 'write_guiconfig', configfilepath, is_maps & (maps is not None), maps
+ print('write_guiconfig', configfilepath, is_maps & (maps is not None), maps)
fd_config = open(configfilepath, 'w')
for line in fd_template.readlines():
if line.count('') == 1:
@@ -3658,7 +3658,7 @@ def write_guiconfig(self, rootname=None, dirname=None, is_maps=False, delta=np.z
return configfilepath
def import_netxml(self, filepath=None, rootname=None, is_clean_nodes=False, is_remove_xmlfiles=False):
- print 'import_netxml', filepath
+ print('import_netxml', filepath)
if rootname is None:
rootname = self.get_rootfilename()
@@ -3674,11 +3674,11 @@ def import_netxml(self, filepath=None, rootname=None, is_clean_nodes=False, is_r
+ ' --sumo-net-file '+filepathlist_to_filepathstring(filepath)\
+ ' --plain-output-prefix '+filepathlist_to_filepathstring(os.path.join(dirname, rootname))
proc = subprocess.Popen(cml, shell=True)
- print ' run_cml cml=', cml
- print ' pid = ', proc.pid
+ print(' run_cml cml=', cml)
+ print(' pid = ', proc.pid)
proc.wait()
if not proc.returncode:
- print ' modes.names', self.modes.names
+ print(' modes.names', self.modes.names)
return self.import_xml(rootname, dirname)
else:
return False
@@ -3698,7 +3698,7 @@ def export_addxml(self, filepath=None,
fd = open(filepath, 'w')
except:
- print 'WARNING in write_obj_to_xml: could not open', filepath
+ print('WARNING in write_obj_to_xml: could not open', filepath)
return False
#xmltag, xmltag_item, attrname_id = self.xmltag
@@ -3764,7 +3764,7 @@ def export_netxml(self, filepath=None, is_export_tlss=True, is_netconvert=True,
if filepath is None:
filepath = self.get_filepath()
- print 'Net.export_netxml', filepath
+ print('Net.export_netxml', filepath)
filepath_edges, filepath_nodes, filepath_connections, filepath_tlss = self.export_painxml(
filepath=filepath, is_export_tlss=is_export_tlss)
@@ -3781,11 +3781,11 @@ def export_netxml(self, filepath=None, is_export_tlss=True, is_netconvert=True,
if is_netconvert:
proc = subprocess.Popen(cml, shell=True)
- print 'run_cml cml=', cml
- print ' pid = ', proc.pid
+ print('run_cml cml=', cml)
+ print(' pid = ', proc.pid)
proc.wait()
if proc.returncode == 0:
- print ' success'
+ print(' success')
if is_return_delta:
delta = self._get_delta_netconvert(filepath)
@@ -3793,7 +3793,7 @@ def export_netxml(self, filepath=None, is_export_tlss=True, is_netconvert=True,
else:
return filepath
else:
- print ' success'
+ print(' success')
return ''
else:
return ''
@@ -3835,7 +3835,7 @@ def import_xml(self, rootname=None, dirname=None, is_clean_nodes=False, is_remov
oldoffset = self.get_offset()
else:
oldoffset = None
- print 'Network.import_xml oldoffset', oldoffset
+ print('Network.import_xml oldoffset', oldoffset)
# remove current network
# print ' remove current network'
self.clear_net()
@@ -3903,7 +3903,7 @@ def import_xml(self, rootname=None, dirname=None, is_clean_nodes=False, is_remov
return False
def import_sumonodes(self, filename, is_remove_xmlfiles=False, logger=None, **others):
- print 'import_sumonodes', filename
+ print('import_sumonodes', filename)
# print ' parent',self.parent
self.get_logger().w('import_sumonodes', key='message')
@@ -3923,11 +3923,11 @@ def import_sumonodes(self, filename, is_remove_xmlfiles=False, logger=None, **ot
fastreader.write_to_net()
# timeit
- print ' exec time=', time.clock() - exectime_start
+ print(' exec time=', time.clock() - exectime_start)
return fastreader
def import_sumoedges(self, filename, is_remove_xmlfiles=False, logger=None, **others):
- print 'import_sumoedges', filename
+ print('import_sumoedges', filename)
logger = self.get_logger()
logger.w('import_sumoedges', key='message')
# timeit
@@ -3949,7 +3949,7 @@ def import_sumoedges(self, filename, is_remove_xmlfiles=False, logger=None, **ot
if is_remove_xmlfiles:
os.remove(filename)
# timeit
- print ' exec time=', time.clock() - exectime_start
+ print(' exec time=', time.clock() - exectime_start)
# except KeyError:
# print >> sys.stderr, "Please mind that the network format has changed in 0.16.0, you may need to update your network!"
@@ -3957,7 +3957,7 @@ def import_sumoedges(self, filename, is_remove_xmlfiles=False, logger=None, **ot
return fastreader
def import_sumoconnections(self, filename, is_remove_xmlfiles=False, logger=None, **others):
- print 'import_sumoedges', filename
+ print('import_sumoedges', filename)
logger = self.get_logger()
logger.w('import_sumoconnections', key='message')
@@ -3974,7 +3974,7 @@ def import_sumoconnections(self, filename, is_remove_xmlfiles=False, logger=None
# timeit
exectime_end = time.clock()
- print ' exec time=', exectime_end - exectime_start
+ print(' exec time=', exectime_end - exectime_start)
return fastreader
def import_sumotls(self, filename, is_remove_xmlfiles=False, logger=None, **others):
@@ -3982,7 +3982,7 @@ def import_sumotls(self, filename, is_remove_xmlfiles=False, logger=None, **othe
Import traffic ligh signals from tll.xml file
as part of a complete import net process.
"""
- print 'import_sumotls', filename
+ print('import_sumotls', filename)
if logger is None:
logger = self.get_logger()
@@ -3996,14 +3996,14 @@ def import_sumotls(self, filename, is_remove_xmlfiles=False, logger=None, **othe
# timeit
exectime_end = time.clock()
- print ' exec time=', exectime_end - exectime_start
+ print(' exec time=', exectime_end - exectime_start)
return reader
def import_sumotls_to_net(self, filename, is_remove_xmlfiles=False, logger=None, **others):
"""
Import traffic ligh signals from tll.xml file into an existing network.
"""
- print 'import_sumotls_to_net', filename
+ print('import_sumotls_to_net', filename)
# associate nodes with sumo tls ID
#map_id_node_to_id_tlss_sumo = {}
@@ -4028,7 +4028,7 @@ def import_sumotls_to_net(self, filename, is_remove_xmlfiles=False, logger=None,
# timeit
exectime_end = time.clock()
- print ' exec time=', exectime_end - exectime_start
+ print(' exec time=', exectime_end - exectime_start)
# reestablish TLS IDs of nodes
@@ -4191,7 +4191,7 @@ def __init__(self):
def startElement(self, name, attrs):
if name == 'connection':
- if attrs.has_key('to'):
+ if 'to' in attrs:
self.n_con += 1
if name == 'crossing':
@@ -4233,7 +4233,7 @@ def startElement(self, name, attrs):
if name == 'connection':
#
- if attrs.has_key('to'):
+ if 'to' in attrs:
self._ind_con += 1
i = self._ind_con
# print 'startElement',name,i
@@ -4376,7 +4376,7 @@ def startElement(self, name, attrs):
if self._isNew | (version == attrs['version']):
self._net.set_version(attrs['version'])
else:
- print 'WARNING: merge with incompatible net versions %s versus %s.' % (version, attrs['version'])
+ print('WARNING: merge with incompatible net versions %s versus %s.' % (version, attrs['version']))
elif name == 'location': # j.s
# print 'startElement',name,self._isNew
@@ -4418,12 +4418,12 @@ def startElement(self, name, attrs):
float(origBoundaryStr[3])]
)
if self._isNew:
- if attrs.has_key('projParameter'):
+ if 'projParameter' in attrs:
self._net.set_projparams(attrs['projParameter'])
else:
- if attrs.has_key('projParameter'):
+ if 'projParameter' in attrs:
if self._net.get_projparams() != attrs['projParameter']:
- print 'WARNING: merge with incompatible projections %s versus %s.' % (self._net.getprojparams(), attrs['projparams'])
+ print('WARNING: merge with incompatible projections %s versus %s.' % (self._net.getprojparams(), attrs['projparams']))
elif name == 'node':
if attrs['id'][0] != ':': # no internal node
@@ -4476,7 +4476,7 @@ def startElement(self, name, attrs):
# the jointly controlled nodes
# problem: we do not know yet the edge IDs
#
- if attrs.has_key('controlledInner'):
+ if 'controlledInner' in attrs:
self.ids_sumo_controlled[i] = attrs['controlledInner'].strip().split(' ')
else:
self.ids_sumo_controlled[i] = []
@@ -4547,7 +4547,7 @@ def startElement(self, name, attrs):
# print 'startElement',name,id_sumo_tls,int(attrs['linkIndex'])
# print ' self.tlsconnections',self.tlsconnections
- if not self.tlsconnections.has_key(id_sumo_tls):
+ if id_sumo_tls not in self.tlsconnections:
self.tlsconnections[id_sumo_tls] = {}
id_con = self.connections.get_id_from_sumoinfo(attrs['from'],
@@ -4583,15 +4583,15 @@ def endElement(self, name):
# end of scanning. Write controlled connections to tlss
# print ' tlsconnections',self.tlsconnections
- for id_sumo_tls, conmap in self.tlsconnections.iteritems():
+ for id_sumo_tls, conmap in self.tlsconnections.items():
if self.tlss.ids_sumo.has_index(id_sumo_tls):
- inds_con = np.array(conmap.keys(), dtype=np.int32)
+ inds_con = np.array(list(conmap.keys()), dtype=np.int32)
ids_con = np.zeros(np.max(inds_con)+1, np.int32)
# print ' cons for',id_sumo_tls,conmap
# print ' inds',inds_con,len(ids_con)
# print ' values',conmap.values(),len(ids_con)
- ids_con[inds_con] = conmap.values() # <<<<<<<<<<<
+ ids_con[inds_con] = list(conmap.values()) # <<<<<<<<<<<
id_tls = self.tlss.ids_sumo.get_id_from_index(id_sumo_tls)
self.tlss.set_connections(id_tls, ids_con)
@@ -4735,7 +4735,7 @@ def startElement(self, name, attrs):
self.speeds_max[ind] = float(attrs.get('speed', 13.888))
self.priorities[ind] = int(attrs.get('priority', 9))
- self.names[ind] = unicode(attrs.get('name', ''))
+ self.names[ind] = str(attrs.get('name', ''))
self.offsets_end[ind] = float(attrs.get('endOffset', 0.0))
# this lanewidth will be used as default if no lane width attribute
@@ -4756,20 +4756,20 @@ def startElement(self, name, attrs):
ind_edge = self._ind_edge
speed_max_default = -1
- if attrs.has_key('allow'):
+ if 'allow' in attrs:
modes_access = attrs['allow'].split(' ')
if len(modes_access) == 1:
- if modes_access[0] == u'all':
- modes_access = MODES.keys()
+ if modes_access[0] == 'all':
+ modes_access = list(MODES.keys())
ids_modes_allow = list(self._modenames.get_ids_from_indices(modes_access))
ids_modes_disallow = []
- elif attrs.has_key('disallow'):
+ elif 'disallow' in attrs:
modes_access = attrs['disallow'].split(' ')
if len(modes_access) == 1:
- if modes_access[0] == u'all':
- modes_access = MODES.keys()
+ if modes_access[0] == 'all':
+ modes_access = list(MODES.keys())
# print ' startElement id_edge_sumo',self.ids_edge_sumo[ind_edge],'disallow',modes_access
ids_modes_disallow = list(self._modenames.get_ids_from_indices(modes_access))
@@ -4779,7 +4779,7 @@ def startElement(self, name, attrs):
# guess allow from edge type
edgetype = self.types_edge[self._ind_edge]
- if OSMEDGETYPE_TO_MODES.has_key(edgetype):
+ if edgetype in OSMEDGETYPE_TO_MODES:
ids_modes_allow, speed_max_default = OSMEDGETYPE_TO_MODES[edgetype]
else:
ids_modes_allow = []
@@ -4832,7 +4832,7 @@ def endElement(self, name):
if self._allow_egdeattr is not None:
ids_modes_allow = list(self._modenames.get_ids_from_indices(self._allow_egdeattr.split(' ')))
else:
- if OSMEDGETYPE_TO_MODES.has_key(edgetype):
+ if edgetype in OSMEDGETYPE_TO_MODES:
ids_modes_allow, speed_max_default = OSMEDGETYPE_TO_MODES[edgetype]
else:
ids_modes_allow = []
@@ -5094,7 +5094,7 @@ def __init__(self, net, rootname=None, rootdirpath=None, netfilepaths="",
def do(self):
self.netfilepaths = self.netfilepath+','+self.netfilepaths
- print 'merging netfilepaths', self.netfilepaths
+ print('merging netfilepaths', self.netfilepaths)
cml = self.get_cml()+' --ignore-errors -o %s' % (filepathlist_to_filepathstring(self.filepath_out))
# print 'SumonetImporter.do',cml
#import_xml(self, rootname, dirname, is_clean_nodes = True)
diff --git a/tools/contributed/sumopy/coremodules/network/network_editor.py b/tools/contributed/sumopy/coremodules/network/network_editor.py
index 88fd3921faa4..1444074d4da2 100644
--- a/tools/contributed/sumopy/coremodules/network/network_editor.py
+++ b/tools/contributed/sumopy/coremodules/network/network_editor.py
@@ -414,7 +414,7 @@ def get_edges(self):
def on_add_crossing(self, event=None):
self._optionspanel.apply()
#edges = self.get_edges().ids_sumo
- print 'add crossing'
+ print('add crossing')
# print ' id_node',self.id_node.get_value()
# print ' ids_edge',self.ids_edge.get_value()
crossings = self.get_scenario().net.crossings
@@ -717,7 +717,7 @@ def __init__(self, ident, edges, parent, **kwargs):
'delivery': ('highway.delivery', [0.4, 0.2, 0.8, 0.9]),
}
- for edgeclass, cdata in self.edgeclasses.iteritems():
+ for edgeclass, cdata in self.edgeclasses.items():
edgetype, color = cdata
self.add(cm.AttrConf('color_'+edgeclass, np.array(color, np.float32),
groupnames=['options', 'edgecolors'],
@@ -802,7 +802,7 @@ def update(self, is_update=True):
#self.colors.value = np.ones((n,1),np.float32)*np.array([0.9,0.9,0.9,0.9])
#self.colors_highl.value = self._get_colors_highl(self.colors.value)
self.colors_fill.value[:] = np.ones((n, 1), np.float32)*self.color_edge_default.value
- for edgeclass, cdata in self.edgeclasses.iteritems():
+ for edgeclass, cdata in self.edgeclasses.items():
edgetype, color = cdata
# print ' ',edgeclass, np.sum(self._edges.types.value==edgetype)
# print ' color',getattr(self,'color_'+edgeclass).value
@@ -848,7 +848,7 @@ def __init__(self, ident, lanes, parent, **kwargs):
}
net = lanes.parent
- for typename, color in typecolors.iteritems():
+ for typename, color in typecolors.items():
id_mode = net.get_id_mode(typename)
self.add(cm.AttrConf('color_'+typename, np.array(color, np.float32),
groupnames=['options', 'typecolors'],
@@ -1504,7 +1504,7 @@ def netediting(net):
if __name__ == '__main__':
###########################################################################
# MAINLOOP
- import network
+ from . import network
from agilepy.lib_base.logger import Logger
net = network.Network(logger=Logger())
net.import_xml('facsp2', 'testnet')
diff --git a/tools/contributed/sumopy/coremodules/network/networktools.py b/tools/contributed/sumopy/coremodules/network/networktools.py
index d485b10ca256..8a712793c3ee 100755
--- a/tools/contributed/sumopy/coremodules/network/networktools.py
+++ b/tools/contributed/sumopy/coremodules/network/networktools.py
@@ -28,8 +28,8 @@
import agilepy.lib_base.arrayman as am
import agilepy.lib_base.xmlman as xm
from agilepy.lib_base.processes import Process, CmlMixin
-import netconvert
-import routing
+from . import netconvert
+from . import routing
#from agilepy.lib_base.geometry import get_length_polypoints,get_dist_point_to_segs, get_diff_angle_clockwise
from agilepy.lib_base.geometry import *
@@ -37,7 +37,7 @@
class ActuatedTlsConfigurator(Process):
def __init__(self, net, logger=None, **kwargs):
- print 'ActuatedTlsConfigurator.__init__'
+ print('ActuatedTlsConfigurator.__init__')
self._init_common('sctuatedtlsconfigurator',
parent=net,
name='Actuated Tls Configurator',
@@ -76,7 +76,7 @@ def do(self):
tlss = self.parent.tlss # traffic light systems
tlls = tlss.tlls.get_value() # traffic light logics = programs
ids_node = nodes.get_ids()
- print 'ActuatedTlsConfigurator.do, len(ids_node)', len(ids_node), self.is_set_actuated
+ print('ActuatedTlsConfigurator.do, len(ids_node)', len(ids_node), self.is_set_actuated)
if self.is_set_actuated:
type_tls = 2
@@ -92,7 +92,7 @@ def do(self):
# go through logics of traffic light
for id_tll in tlss.ids_tlls[id_tls]:
- print ' set logic id_tll', id_tll
+ print(' set logic id_tll', id_tll)
tlls.ptypes[id_tll] = type_tls
# go through phases of program and adjust min max durations
@@ -110,7 +110,7 @@ def do(self):
class TlsGenerator(netconvert.NetConvertMixin):
def __init__(self, net, logger=None, **kwargs):
- print 'TlsGenerate.__init__'
+ print('TlsGenerate.__init__')
self._init_common('tlsgenerator',
parent=net,
name='Trafficlight system generator',
@@ -148,7 +148,7 @@ def get_routecost(self, route):
return np.sum(self.parent.edges.lengths[route])
def do(self):
- print 'TlsGenerator.do'
+ print('TlsGenerator.do')
net = self.parent
edges = net.edges
@@ -178,7 +178,7 @@ def do(self):
edges.ids_tonode[ids_edge],
edges.speeds_max[ids_edge],
):
- print ' is_major_road', id_edge, self.is_major_road(priority, n_lanes, speed_max), id_edge not in ids_edges_major
+ print(' is_major_road', id_edge, self.is_major_road(priority, n_lanes, speed_max), id_edge not in ids_edges_major)
if self.is_major_road(priority, n_lanes, speed_max):
if id_edge not in ids_edges_major:
#dist = 0
@@ -190,11 +190,11 @@ def do(self):
self.majorroutes = majorroutes
- print ' majorroutes:' # ,majorroutes
+ print(' majorroutes:') # ,majorroutes
# mapping with id_edge as key ind index of majorroutes
edges_major = {}
- for i, route in zip(xrange(len(majorroutes)), majorroutes):
- print ' route', i, len(route), route
+ for i, route in zip(range(len(majorroutes)), majorroutes):
+ print(' route', i, len(route), route)
for id_edge in route:
edges_major[id_edge] = i
@@ -213,14 +213,14 @@ def do(self):
# identify major junctions
majorjuntions = {}
- for i_route1, ids_node1 in zip(xrange(len(majorroutes)), majornodes):
+ for i_route1, ids_node1 in zip(range(len(majorroutes)), majornodes):
ids_nodeset1 = set(ids_node1)
- for i_route2, ids_node2 in zip(xrange(len(majorroutes)), majornodes):
+ for i_route2, ids_node2 in zip(range(len(majorroutes)), majornodes):
if i_route2 != i_route1:
- print ' check routes', i_route1, i_route2, 'ids_node_inter', ids_nodeset1.intersection(ids_node2)
+ print(' check routes', i_route1, i_route2, 'ids_node_inter', ids_nodeset1.intersection(ids_node2))
for id_node_inter in ids_nodeset1.intersection(ids_node2):
# go through all nodes that route1 and route2 have in common
- if majorjuntions.has_key(id_node_inter):
+ if id_node_inter in majorjuntions:
# add route index to already existing junction
if i_route1 not in majorjuntions[id_node_inter]:
majorjuntions[id_node_inter].append(i_route1)
@@ -234,13 +234,13 @@ def do(self):
self.ids_majornodes_used = set()
# create mojor TLS
- print ' major junctions:'
- for id_node, inds_route in majorjuntions.iteritems():
+ print(' major junctions:')
+ for id_node, inds_route in majorjuntions.items():
if id_node not in self.ids_majornodes_used:
# debug
- print ' Next majornode', id_node
+ print(' Next majornode', id_node)
for ind in inds_route:
- print ' majorroute', majorroutes[ind]
+ print(' majorroute', majorroutes[ind])
self.make_majortls(id_node, inds_route)
# print ' junction', id_node
@@ -250,8 +250,8 @@ def do(self):
return True
def make_majortls(self, id_node_major, inds_route):
- print 79*'-'
- print 'make_majortls for', id_node_major, inds_route
+ print(79*'-')
+ print('make_majortls for', id_node_major, inds_route)
edges = self.parent.edges
nodes = self.parent.nodes
lanes = self.parent.lanes
@@ -301,8 +301,8 @@ def make_majortls(self, id_node_major, inds_route):
# enrich node attributes: is_cycleped, is_crossing
# detect all connections, lanes and everything else
- for id_node, nodeattrs in nodes_tls.iteritems():
- print ' check all in id_node', id_node
+ for id_node, nodeattrs in nodes_tls.items():
+ print(' check all in id_node', id_node)
is_cycleped = True
n_cycleped = 0 # count incomin and outgoing cycleped edges
n_nocycleped_in = 0 # count normal incoming road edges
@@ -311,7 +311,7 @@ def make_majortls(self, id_node_major, inds_route):
# make lists with incoming edges
for id_edge in nodes.ids_incoming[id_node]:
- print ' check incoming', id_edge
+ print(' check incoming', id_edge)
ids_lane = edges.ids_lanes[id_edge]
#is_cycleped_edge = True
#is_ped_edge = True
@@ -342,7 +342,7 @@ def make_majortls(self, id_node_major, inds_route):
# detect incoming edges
# ,not is_ped_edge,'not from TLS',edges.ids_fromnode[id_edge] not in ids_nodes_tls
- print ' is external', edges.ids_fromnode[id_edge] not in ids_nodes_tls, 'is_cycle_edge', is_cycle_edge, 'is_major', id_edge in edges_major, 'is_noped'
+ print(' is external', edges.ids_fromnode[id_edge] not in ids_nodes_tls, 'is_cycle_edge', is_cycle_edge, 'is_major', id_edge in edges_major, 'is_noped')
if edges.ids_fromnode[id_edge] not in ids_nodes_tls:
# from node is not part of the TLS
# so it comes from external
@@ -396,25 +396,25 @@ def make_majortls(self, id_node_major, inds_route):
# debug
if 1:
- print ' nodes_tls:'
- for id_node, nodeattrs in nodes_tls.iteritems():
- print ' id_node', id_node
- for key, val in nodeattrs.iteritems():
- print ' ', key, val
+ print(' nodes_tls:')
+ for id_node, nodeattrs in nodes_tls.items():
+ print(' id_node', id_node)
+ for key, val in nodeattrs.items():
+ print(' ', key, val)
n_cons = len(ids_con_tls)
ids_con_tls = np.array(ids_con_tls, dtype=np.int32)
ids_connodes = np.array(ids_connodes, dtype=np.int32)
- print ' ids_incoming_major_tls', ids_incoming_major_tls
- print ' ids_outgoing_major_tls', ids_outgoing_major_tls
- print ' ids_incoming_tls', ids_incoming_tls
- print ' ids_outgoing_tls', ids_outgoing_tls
+ print(' ids_incoming_major_tls', ids_incoming_major_tls)
+ print(' ids_outgoing_major_tls', ids_outgoing_major_tls)
+ print(' ids_incoming_tls', ids_incoming_tls)
+ print(' ids_outgoing_tls', ids_outgoing_tls)
if len(ids_incoming_tls)+len(ids_incoming_major_tls) < 2:
- print ' Need at least 2 incoming edges. Abandon.'
+ print(' Need at least 2 incoming edges. Abandon.')
return False
- print ' connectors detected:', n_cons
+ print(' connectors detected:', n_cons)
#ids_conlane = np.array(ids_conlane, dtype = np.int32 )
#convecs = np.array(convecs, dtype = np.float32 )
vertices_fromcon = np.zeros((n_cons, 2, 2), dtype=np.float32)
@@ -425,7 +425,7 @@ def make_majortls(self, id_node_major, inds_route):
ids_fromlane_tls = connections.ids_fromlane[ids_con_tls]
ids_tolane_tls = connections.ids_tolane[ids_con_tls]
for i, shape_fromlane, shape_tolane in zip(
- xrange(n_cons),
+ range(n_cons),
lanes.shapes[ids_fromlane_tls],
lanes.shapes[ids_tolane_tls]
):
@@ -464,7 +464,7 @@ def make_majortls(self, id_node_major, inds_route):
centroids = nodes.coords[ids_connodes][:, :2]
dist_intercheck = 5.0
for i, id_con, vertex_fromcon, vertex_tocon, id_node, id_edge_from, id_edge_to in zip(
- xrange(n_cons), ids_con_tls,
+ range(n_cons), ids_con_tls,
vertices_fromcon, vertices_tocon,
ids_connodes, ids_conedges_from, ids_conedges_to):
@@ -511,7 +511,7 @@ def make_majortls(self, id_node_major, inds_route):
dists_to < dist_intercheck,
(ids_connodes == id_node), (ids_conedges_from != id_edge_from),
inds):
- print ' id_con:%d d_from %.2f, d_to %.2f' % (id_con1, df, dt), df < dist_intercheck, dt < dist_intercheck, id_node1 == id_node, id_edge1 != id_edge_from, crit
+ print(' id_con:%d d_from %.2f, d_to %.2f' % (id_con1, df, dt), df < dist_intercheck, dt < dist_intercheck, id_node1 == id_node, id_edge1 != id_edge_from, crit)
# print ' vf',vf,'vt',vt,'cent',cent,cent-vt
dists_fromcon_node[id_con] = np.array(dists_from[inds], dtype=np.int32)
@@ -522,9 +522,9 @@ def make_majortls(self, id_node_major, inds_route):
inds_cons_merge[id_con] = inds & np.isnan(dists_to)
if 1: # debug
- print ' show conflicts:', len(inds_cons_conflict)
- for id_con_tls, inds_con_conflict, id_connode in zip(ids_con_tls, inds_cons_conflict.values(), ids_connodes):
- print ' id_connode:%d id_con:%d' % (id_connode, id_con_tls), 'ids_conf', ids_con_tls[inds_con_conflict]
+ print(' show conflicts:', len(inds_cons_conflict))
+ for id_con_tls, inds_con_conflict, id_connode in zip(ids_con_tls, list(inds_cons_conflict.values()), ids_connodes):
+ print(' id_connode:%d id_con:%d' % (id_connode, id_con_tls), 'ids_conf', ids_con_tls[inds_con_conflict])
# print ' id_node %d, id_con %d confl:'%(id_node,id_con)
# print ' ids_con_conflict',ids_con_tls[inds_con_conflict]
@@ -540,7 +540,7 @@ def make_majortls(self, id_node_major, inds_route):
#self.id_mode_ped = net.modes.get_id_mode("pedestrian")
#self.id_mode_car = net.modes.get_id_mode("passenger")
- print '\n generate routes across the TLS'
+ print('\n generate routes accross the TLS')
#costs = edges.get_times( id_mode = self.id_mode_car , is_check_lanes = True, speed_max = None)
# use bus here so we can route also on reserved lanes
costs = edges.get_times(id_mode=self.id_mode_bus, is_check_lanes=True, speed_max=None)
@@ -554,7 +554,7 @@ def make_majortls(self, id_node_major, inds_route):
routes_tls = []
routes_tls_cost = []
ids_routeedge_tls = set()
- print ' create major routes for ids_incoming_major_tls', ids_incoming_major_tls, 'ids_outgoing_major_tls', ids_outgoing_major_tls
+ print(' create major routes for ids_incoming_major_tls', ids_incoming_major_tls, 'ids_outgoing_major_tls', ids_outgoing_major_tls)
for id_incoming_tls in ids_incoming_major_tls:
# ind_route =
# print ' major:id_incoming_tls',id_incoming_tls,type(id_incoming_tls), edges_major.has_key(id_incoming_tls)
@@ -564,10 +564,10 @@ def make_majortls(self, id_node_major, inds_route):
# select major route
route_major = self.majorroutes[edges_major[id_incoming_tls]]
costs_major_tot = self.majorroutecosts[edges_major[id_incoming_tls]]
- print ' id_incoming_tls', id_incoming_tls, 'costs_major_tot', costs_major_tot
+ print(' id_incoming_tls', id_incoming_tls, 'costs_major_tot', costs_major_tot)
ind_from = route_major.index(id_incoming_tls)
for id_outgoing_tls in ids_outgoing_major_tls:
- print ' id_incoming_tls -> id_outgoing_tls', id_incoming_tls, '->', id_outgoing_tls
+ print(' id_incoming_tls -> id_outgoing_tls', id_incoming_tls, '->', id_outgoing_tls)
route = []
if (id_outgoing_tls in route_major) & (ind_from < (len(route_major)-1)):
@@ -586,7 +586,7 @@ def make_majortls(self, id_node_major, inds_route):
if len(route) == 0:
# major route does not connects id_incoming_tls and id_outgoing_tls
- print ' try to find a route between both edges'
+ print(' try to find a route between both edges')
dur, route_raw = routing.get_mincostroute_edge2edge(
id_incoming_tls, id_outgoing_tls,
weights=costs, fstar=fstar)
@@ -613,7 +613,7 @@ def make_majortls(self, id_node_major, inds_route):
route = []
costs_major = 0.0
- print ' =>costs_major,route_major tls', costs_major, route
+ print(' =>costs_major,route_major tls', costs_major, route)
if len(route) > 0:
routes_tls.append(route)
# costs to decide which phase is first
@@ -623,15 +623,15 @@ def make_majortls(self, id_node_major, inds_route):
ids_routeedge_tls.update(route)
if 1: # sp
- print ' major routes_tls', routes_tls, ids_outgoing_bike_tls
- print ' create bike routes for ids_incoming_bike_tls', ids_incoming_bike_tls, ids_outgoing_bike_tls
+ print(' major routes_tls', routes_tls, ids_outgoing_bike_tls)
+ print(' create bike routes for ids_incoming_bike_tls', ids_incoming_bike_tls, ids_outgoing_bike_tls)
for id_incoming_tls in ids_incoming_bike_tls: # +ids_incoming_tls+ids_incoming_major_tls:
D, P = routing.edgedijkstra(id_incoming_tls, ids_edge_target=set(ids_outgoing_bike_tls),
weights=costs_bike, fstar=fstar)
for id_outgoing_tls in ids_outgoing_bike_tls: # +ids_outgoing_tls+ids_outgoing_major_tls:
- print ' bike route from %d to %d' % (id_incoming_tls, id_outgoing_tls), 'can route?', (id_incoming_tls in D) & (id_outgoing_tls in D)
+ print(' bike route from %d to %d' % (id_incoming_tls, id_outgoing_tls), 'can route?', (id_incoming_tls in D) & (id_outgoing_tls in D))
if (id_incoming_tls in D) & (id_outgoing_tls in D):
# avoid route with turnaround
@@ -656,10 +656,10 @@ def make_majortls(self, id_node_major, inds_route):
routes_tls_cost.append(routecost)
ids_routeedge_tls.update(route)
- print ' withbike routes_tls', routes_tls
+ print(' withbike routes_tls', routes_tls)
ids_outgoing_tls_rest = ids_outgoing_tls+ids_outgoing_major_tls # +ids_outgoing_bike_tls
- print ' create rest of routes for ids_incoming_tls', ids_incoming_tls, ids_outgoing_tls_rest
+ print(' create rest of routes for ids_incoming_tls', ids_incoming_tls, ids_outgoing_tls_rest)
for id_incoming_tls in ids_incoming_tls+ids_incoming_major_tls: # +ids_incoming_bike_tls:
D, P = routing.edgedijkstra(id_incoming_tls, ids_edge_target=set(ids_outgoing_tls_rest),
@@ -669,7 +669,7 @@ def make_majortls(self, id_node_major, inds_route):
if not ((id_incoming_tls in ids_outgoing_major_tls) & (id_outgoing_tls in ids_outgoing_major_tls)):
# major incoming and outgoing already done with major routes
- print ' rest route from id_incoming_tls,', id_incoming_tls, 'id_outgoing_tls', id_outgoing_tls
+ print(' rest route from id_incoming_tls,', id_incoming_tls, 'id_outgoing_tls', id_outgoing_tls)
# avoid route with turnaround
if edges.ids_tonode[id_outgoing_tls] != edges.ids_fromnode[id_incoming_tls]:
@@ -690,7 +690,7 @@ def make_majortls(self, id_node_major, inds_route):
routes_tls_cost.append(routecost)
ids_routeedge_tls.update(route)
- print '\n all routes_tls', routes_tls
+ print('\n all routes_tls', routes_tls)
# add bicycle routes
@@ -717,7 +717,7 @@ def make_majortls(self, id_node_major, inds_route):
routecost = routes_tls_cost[ind_route]
#ids_edges = self.majorroutes[ind_route]
#ids_edges = np.array(ids_edges_list, dtype = np.int32)
- print ' Determine connectors for route ind_route', ind_route, ids_edges
+ print(' Determine connectors for route ind_route', ind_route, ids_edges)
# print ' ids_node',edges.ids_fromnode[ids_edges[:-1]]
# print ' nodes_tls',nodes_tls.keys()
# for id_edge, id_innode, id_outnode in zip(ids_edges, edges.ids_fromnode[ids_edges], edges.ids_tonode[ids_edges]):
@@ -744,7 +744,7 @@ def make_majortls(self, id_node_major, inds_route):
inds_con_route |= (lanes.ids_edge[ids_fromlane_tls] == id_edge_from) & (
lanes.ids_edge[ids_tolane_tls] == id_edge_to)
- print ' id_node,prio', id_node, prio, id_node in nodes_tls, 'n_cons_route', len(np.flatnonzero(inds_con_route))
+ print(' id_node,prio', id_node, prio, id_node in nodes_tls, 'n_cons_route', len(np.flatnonzero(inds_con_route)))
# make phase for ids_edges
if prio != -1:
@@ -755,9 +755,9 @@ def make_majortls(self, id_node_major, inds_route):
for id_con, ind_con in zip(ids_con_tls_route, np.flatnonzero(inds_con_route)):
inds_cons_conflict_route |= inds_cons_conflict[id_con] & np.logical_not(inds_cons_merge[id_con])
inds_cons_merge_route |= inds_cons_merge[id_con]
- print ' ids_con_alloc', ids_con_tls[inds_con_route]
- print ' ids_con_confl', ids_con_tls[inds_cons_conflict_route]
- print ' ids_con_merge', ids_con_tls[inds_cons_merge_route]
+ print(' ids_con_alloc', ids_con_tls[inds_con_route])
+ print(' ids_con_confl', ids_con_tls[inds_cons_conflict_route])
+ print(' ids_con_merge', ids_con_tls[inds_cons_merge_route])
routeconnectordata.append((ind_route, inds_con_route, prio,
inds_cons_conflict_route, inds_cons_merge_route))
@@ -768,7 +768,7 @@ def make_majortls(self, id_node_major, inds_route):
for data in routeconnectordata: # data is sorted by routecosts
ind_tlsroute, inds_con_route, prio, inds_cons_conflict_route, inds_cons_merge_route = data
- print ' ind_tlsroute', ind_tlsroute, 'c=%.1f' % routes_tls_cost[ind_tlsroute], 'ids_edge', routes_tls[ind_tlsroute]
+ print(' ind_tlsroute', ind_tlsroute, 'c=%.1f' % routes_tls_cost[ind_tlsroute], 'ids_edge', routes_tls[ind_tlsroute])
# group non-conflicting routes
n_routes = len(routeconnectordata)
@@ -790,7 +790,7 @@ def make_majortls(self, id_node_major, inds_route):
i_group = 0
i_route = 0
while i_route < n_routes:
- print ' try i_route', i_route, phasegroups[i_route], phasegroups[i_route] == -1
+ print(' try i_route', i_route, phasegroups[i_route], phasegroups[i_route] == -1)
if phasegroups[i_route] == -1:
phasegroups[i_route] = i_group
@@ -798,7 +798,7 @@ def make_majortls(self, id_node_major, inds_route):
i_route]
#inds_cons_conflict_group = inds_cons_conflict.copy()
- print ' Check group', i_group, 'for ind_tlsroute', ind_tlsroute, 'c=%.1f' % routes_tls_cost[ind_tlsroute]
+ print(' Check group', i_group, 'for ind_tlsroute', ind_tlsroute, 'c=%.1f' % routes_tls_cost[ind_tlsroute])
# print ' inds_cons_conflict',inds_cons_conflict
# check whether there are other, compatible
@@ -807,21 +807,21 @@ def make_majortls(self, id_node_major, inds_route):
inds_confict_group = inds_cons_conflict_route.copy()
inds_merge_group = inds_cons_merge_route.copy()
prio_group = 1*prio
- print ' init ids_confict_group=', ids_con_tls[inds_confict_group]
+ print(' init ids_confict_group=', ids_con_tls[inds_confict_group])
while j_route < n_routes:
if phasegroups[j_route] == -1:
# no phase group associated with
ind_tlsroute2, inds_con_route2, prio2, inds_cons_conflict_route2, inds_cons_merge_route2 = routeconnectordata[
j_route]
- print ' check with ind_tlsroute2', ind_tlsroute2, np.any(inds_cons_conflict_route2 & inds_con_route), np.any(inds_cons_conflict_route & inds_con_route2)
+ print(' check with ind_tlsroute2', ind_tlsroute2, np.any(inds_cons_conflict_route2 & inds_con_route), np.any(inds_cons_conflict_route & inds_con_route2))
# print ' c',inds_con_route
# print ' x',inds_cons_conflict_route2
if (not np.any(inds_cons_conflict_route2 & inds_alloc_group)) & (not np.any(inds_confict_group & inds_con_route2)):
# no mutual conflict connections between route j_route
# and current route i_route
- print ' ids_cons_conflict_route2', ids_con_tls[inds_cons_conflict_route2]
- print ' inds_con_route ', ids_con_tls[inds_con_route]
+ print(' ids_cons_conflict_route2', ids_con_tls[inds_cons_conflict_route2])
+ print(' inds_con_route ', ids_con_tls[inds_con_route])
# make this route a part of the current group
phasegroups[j_route] = i_group
inds_confict_group |= inds_cons_conflict_route2
@@ -830,8 +830,8 @@ def make_majortls(self, id_node_major, inds_route):
if prio2 > prio_group:
prio_group = prio
- print ' group', phasegroups[j_route], ':put route', ind_tlsroute2, 'to route', ind_tlsroute
- print ' ids_confict_group=', ids_con_tls[inds_confict_group]
+ print(' group', phasegroups[j_route], ':put route', ind_tlsroute2, 'to route', ind_tlsroute)
+ print(' ids_confict_group=', ids_con_tls[inds_confict_group])
j_route += 1
@@ -847,7 +847,7 @@ def make_majortls(self, id_node_major, inds_route):
# debug:
for i_group, data in zip(phasegroups, routeconnectordata):
ind_tlsroute, inds_con_route, prio, inds_cons_conflict_route, inds_cons_merge_route = data
- print ' i_group', i_group, 'ind_tlsroute', ind_tlsroute, 'ids_edge', routes_tls[ind_tlsroute]
+ print(' i_group', i_group, 'ind_tlsroute', ind_tlsroute, 'ids_edge', routes_tls[ind_tlsroute])
# return
# create signal phases
@@ -871,11 +871,11 @@ def make_majortls(self, id_node_major, inds_route):
# print '\n **inds_cons_conflict',inds_cons_conflict
if len(phasegroups) == 0:
- print ' WARNING: a TLS without signal groups. Abandone.'
+ print(' WARNING: a TLS without signal groups. Abandone.')
return
- for i_group, inds_alloc_groups, inds_confict_groups, inds_merge_groups, prio_group in zip(xrange(max(phasegroups)+1), inds_alloc_groups, inds_confict_groups, inds_merge_groups, prios_group):
- print ' allocate slots for group', i_group
+ for i_group, inds_alloc_groups, inds_confict_groups, inds_merge_groups, prio_group in zip(range(max(phasegroups)+1), inds_alloc_groups, inds_confict_groups, inds_merge_groups, prios_group):
+ print(' allocate slots for group', i_group)
phaseallocations.append(inds_alloc_groups)
phaseconflicts.append(2*inds_confict_groups + 1 * (inds_merge_groups & np.logical_not(inds_confict_groups)))
@@ -891,13 +891,13 @@ def make_majortls(self, id_node_major, inds_route):
n_phase = len(phaseconflicts)
if n_phase < 2:
- print ' WARNING: a TLS with just one phase makes no sense. Abandone.'
+ print(' WARNING: a TLS with just one phase makes no sense. Abandone.')
return
if 1: # debug
- print ' Show phases n_phase', n_phase
- for i, inds_phaseconflict, prio in zip(xrange(n_phase), phaseconflicts, phasepriorities):
- print ' phase', i, 'prio', prio
+ print(' Show phases n_phase', n_phase)
+ for i, inds_phaseconflict, prio in zip(range(n_phase), phaseconflicts, phasepriorities):
+ print(' phase', i, 'prio', prio)
#ids_con_conf_phase = ids_con_tls[inds_phaseconflict==2]
# print ' ids_con_conf_phase',ids_con_conf_phase
#ids_con_merge_phase = ids_con_tls[inds_phaseconflict==1]
@@ -906,16 +906,16 @@ def make_majortls(self, id_node_major, inds_route):
ids_node_phase = set(ids_connodes[inds_phaseconflict > 0])
for id_node in ids_node_phase:
- print ' id_node', id_node
- print ' ids_conflicts', ids_con_tls[(inds_phaseconflict == 2) & (ids_connodes == id_node)]
- print ' ids_merge', ids_con_tls[(inds_phaseconflict == 1) & (ids_connodes == id_node)]
+ print(' id_node', id_node)
+ print(' ids_conflicts', ids_con_tls[(inds_phaseconflict == 2) & (ids_connodes == id_node)])
+ print(' ids_merge', ids_con_tls[(inds_phaseconflict == 1) & (ids_connodes == id_node)])
# make sure that all connetors between two edges have the equal signal
for id_fromedge in set(ids_conedges_from):
for id_toedge in set(ids_conedges_to):
# extract index of connections, connecting id_fromedge with id_toedge
inds_con_check = np.flatnonzero((ids_conedges_from == id_fromedge) & (ids_conedges_to == id_toedge))
- for i in xrange(n_phase):
+ for i in range(n_phase):
# now if any of those connections is red than make them all red
if np.any(phaseconflicts[i][inds_con_check] == 2):
phaseconflicts[i][inds_con_check] = 2
@@ -942,8 +942,8 @@ def make_majortls(self, id_node_major, inds_route):
#
if 1:
# go though all nodes of this TLS
- for id_node, nodeattrs in nodes_tls.iteritems():
- print ' safecheck id_node', id_node, 'is_crossing', nodeattrs['is_crossing'], 'is_cycleped', nodeattrs['is_cycleped']
+ for id_node, nodeattrs in nodes_tls.items():
+ print(' safecheck id_node', id_node, 'is_crossing', nodeattrs['is_crossing'], 'is_cycleped', nodeattrs['is_cycleped'])
#nodeattrs['is_cycleped'] = is_cycleped
# nodeattrs['is_crossing'] =
@@ -959,14 +959,14 @@ def make_majortls(self, id_node_major, inds_route):
for id_edge_from in nodeattrs['ids_cycleped_incoming']: # nodes.ids_incoming[id_node]:
for id_edge_to in nodeattrs['ids_cycleped_outgoing']:
- print ' safecheck cycleped from edge %d to edge %d id_edge' % (id_edge_from, id_edge_to)
+ print(' safecheck cycleped from edge %d to edge %d id_edge' % (id_edge_from, id_edge_to))
# connector index vector with all connectors for this edge
inds_con_edge = inds_con_node & (lanes.ids_edge[ids_fromlane_tls] == id_edge_from) & (
lanes.ids_edge[ids_tolane_tls] == id_edge_to)
ids_con_edge = ids_con_tls[inds_con_edge]
- print ' ids_con_edge', ids_con_edge, np.any(inds_con_edge)
+ print(' ids_con_edge', ids_con_edge, np.any(inds_con_edge))
if np.any(inds_con_edge):
# get conflicts for these connections
for id_con, ind_con in zip(ids_con_edge, np.flatnonzero(inds_con_edge)):
@@ -975,19 +975,19 @@ def make_majortls(self, id_node_major, inds_route):
# conflicts valid to connector does NOT point to toedge
inds_con_check |= inds_cons_conflict[id_con] & are_enabeled & (
lanes.ids_edge[ids_tolane_tls] != id_edge_to)
- print ' id_con %d: inds_con_check' % id_con, ids_con_tls[inds_con_check]
+ print(' id_con %d: inds_con_check' % id_con, ids_con_tls[inds_con_check])
- print ' ids_con_check', ids_con_tls[inds_con_check]
+ print(' ids_con_check', ids_con_tls[inds_con_check])
# check if there is a dedicated phase with assigned
# cycleped edges
prio_green = -1
- for i, prio in zip(xrange(n_phase), phasepriorities):
+ for i, prio in zip(range(n_phase), phasepriorities):
is_alloc_allgreen = np.all(phaseallocations[i][inds_con_node])
if is_alloc_allgreen:
# cycleped path is allocated, so make all conflicts red
- print ' found cycleped green phase', i
+ print(' found cycleped green phase', i)
# make all conflicting red, but this should already
# be the case
@@ -1000,7 +1000,7 @@ def make_majortls(self, id_node_major, inds_route):
# search suitable phase where conflicts are red
prio_red = -1
i_red = -1
- for i, prio in zip(xrange(n_phase), phasepriorities):
+ for i, prio in zip(range(n_phase), phasepriorities):
is_conflict_allred = np.all(phaseconflicts[i][inds_con_check] == 2)
if is_conflict_allred & (prio > prio_red):
i_red = i
@@ -1009,8 +1009,8 @@ def make_majortls(self, id_node_major, inds_route):
# react and make cycleped red (and leave others)
# and make cycleped green only in phase i_red
# when conflicts are all red
- for i, prio in zip(xrange(n_phase), phasepriorities):
- print ' adjust phase', i, 'green', i == i_red
+ for i, prio in zip(range(n_phase), phasepriorities):
+ print(' adjust phase', i, 'green', i == i_red)
if i == i_red:
phaseconflicts[i][inds_con_node] = 0
else:
@@ -1022,7 +1022,7 @@ def make_majortls(self, id_node_major, inds_route):
# go through all incoming edges of this node
for id_edge in nodes.ids_incoming[id_node]:
- print ' safecheck icoming id_edge', id_edge
+ print(' safecheck icoming id_edge', id_edge)
# connector index vector with all connectors for this edge
inds_con_node = (ids_connodes == id_node) & are_enabeled
@@ -1042,16 +1042,16 @@ def make_majortls(self, id_node_major, inds_route):
# if id_con is green, then these must be red in all phases
inds_con_confcheck = inds_cons_conflict[id_con]
- print '\n safecheck id_con', id_con, 'ids_con_confcheck', ids_con_tls[inds_con_confcheck]
+ print('\n safecheck id_con', id_con, 'ids_con_confcheck', ids_con_tls[inds_con_confcheck])
# go through all phases
- for i, prio in zip(xrange(n_phase), phasepriorities):
+ for i, prio in zip(range(n_phase), phasepriorities):
inds_noconfmerge = phaseconflicts[i] <= 1
#inds_noconfmerge_last = phaseconflicts[i-1] <= 1
inds_noconf = phaseconflicts[i] == 0
inds_noconf_last = phaseconflicts[i-1] == 0
- print ' safecheck phase', i, 'inds_noconf', inds_noconf[ind_con], 'inds_noconf_last', inds_noconf_last[ind_con]
+ print(' safecheck phase', i, 'inds_noconf', inds_noconf[ind_con], 'inds_noconf_last', inds_noconf_last[ind_con])
if inds_noconfmerge[ind_con]: # no red at ind_con
@@ -1066,7 +1066,7 @@ def make_majortls(self, id_node_major, inds_route):
# ambiguous cons = green cons inds & inds where cons should be red
inds_con_ambiqu = inds_noconf & (inds_con_confcheck > 0) & are_enabeled
- print ' inds_con_ambiqu', ids_con_tls[inds_con_ambiqu], 'resolve ambig', (inds_noconf_last[ind_con]) & np.any(inds_con_ambiqu)
+ print(' inds_con_ambiqu', ids_con_tls[inds_con_ambiqu], 'resolve ambig', (inds_noconf_last[ind_con]) & np.any(inds_con_ambiqu))
# any ambiguous connector found?
if np.any(inds_con_ambiqu):
@@ -1082,10 +1082,10 @@ def make_majortls(self, id_node_major, inds_route):
# of connectors, it can happen
# that allocated connectors are in conflict
if np.any(phaseallocations[i][inds_con_ambiqu]):
- print ' set thiscon', id_con, 'to red, instead of allocated.'
+ print(' set thiscon', id_con, 'to red, instead of allocated.')
phaseconflicts[i][ind_con] = 2
else:
- print ' set confcons', ids_con_tls[inds_con_ambiqu], 'to red'
+ print(' set confcons', ids_con_tls[inds_con_ambiqu], 'to red')
phaseconflicts[i][inds_con_ambiqu] = 2
# for ind_con_ambiqu, raw in zip(inds_con_ambiqu, phaseconflicts[i][inds_con_ambiqu]):
@@ -1094,13 +1094,13 @@ def make_majortls(self, id_node_major, inds_route):
# during the last phase this signal
# has been red so let it red
# these should be blocked!!
- print ' set thiscon', id_con, 'to red'
+ print(' set thiscon', id_con, 'to red')
phaseconflicts[i][ind_con] = 2
#self.block_connection(ind_con, 2 , phaseconflicts[i], ids_fromlane_tls, ids_tolane_tls, ids_con_tls,are_enabeled)
else:
- print ' no ambiguity.'
+ print(' no ambiguity.')
else:
- print ' signal is already red. Try make it green'
+ print(' signal is already red. Try make it green')
# make signal green, if signal has been green in the past and
# if all conflicting connectors are red
#inds_con_ambiqu = (phaseconflicts[i] == 2) & (inds_con_confcheck>0) & are_enabeled
@@ -1108,9 +1108,9 @@ def make_majortls(self, id_node_major, inds_route):
phaseconflicts[i][ind_con] = 0
if 0: # debug
- print ' After safetycheck: Show phases n_phase', n_phase
- for i, inds_phaseconflict, prio in zip(xrange(n_phase), phaseconflicts, phasepriorities):
- print ' phase', i, 'prio', prio
+ print(' After safetycheck: Show phases n_phase', n_phase)
+ for i, inds_phaseconflict, prio in zip(range(n_phase), phaseconflicts, phasepriorities):
+ print(' phase', i, 'prio', prio)
#ids_con_conf_phase = ids_con_tls[inds_phaseconflict==2]
# print ' ids_con_conf_phase',ids_con_conf_phase
#ids_con_merge_phase = ids_con_tls[inds_phaseconflict==1]
@@ -1119,9 +1119,9 @@ def make_majortls(self, id_node_major, inds_route):
ids_node_phase = set(ids_connodes[inds_phaseconflict > 0])
for id_node in ids_node_phase:
- print ' id_node', id_node
- print ' ids_conflicts', ids_con_tls[(inds_phaseconflict == 2) & (ids_connodes == id_node)]
- print ' ids_merge', ids_con_tls[(inds_phaseconflict == 1) & (ids_connodes == id_node)]
+ print(' id_node', id_node)
+ print(' ids_conflicts', ids_con_tls[(inds_phaseconflict == 2) & (ids_connodes == id_node)])
+ print(' ids_merge', ids_con_tls[(inds_phaseconflict == 1) & (ids_connodes == id_node)])
# push red signs back over short edges
if 1:
@@ -1132,7 +1132,7 @@ def make_majortls(self, id_node_major, inds_route):
slots_raw = phaseconflicts[i]
# index with all merge and red signals
inds = np.flatnonzero(slots_raw == 2)
- print '\n Phase', i, 'block ids_con', ids_con_tls[inds]
+ print('\n Phase', i, 'block ids_con', ids_con_tls[inds])
# print ' red ',ids_con_tls[phaseconflicts[i]==2]
# print ' merge',ids_con_tls[phaseconflicts[i]==1]
# go though all connectors with merge and red signals
@@ -1144,9 +1144,9 @@ def make_majortls(self, id_node_major, inds_route):
phaseconflicts[i] = slots
if 1: # debug
- print ' After push back reds: Show phases n_phase', n_phase
- for i, inds_phaseconflict, prio in zip(xrange(n_phase), phaseconflicts, phasepriorities):
- print ' phase', i, 'prio', prio
+ print(' After push back reds: Show phases n_phase', n_phase)
+ for i, inds_phaseconflict, prio in zip(range(n_phase), phaseconflicts, phasepriorities):
+ print(' phase', i, 'prio', prio)
#ids_con_conf_phase = ids_con_tls[inds_phaseconflict==2]
# print ' ids_con_conf_phase',ids_con_conf_phase
#ids_con_merge_phase = ids_con_tls[inds_phaseconflict==1]
@@ -1155,14 +1155,14 @@ def make_majortls(self, id_node_major, inds_route):
ids_node_phase = set(ids_connodes[inds_phaseconflict > 0])
for id_node in ids_node_phase:
- print ' id_node', id_node
- print ' ids_conflicts', ids_con_tls[(inds_phaseconflict == 2) & (ids_connodes == id_node)]
- print ' ids_merge', ids_con_tls[(inds_phaseconflict == 1) & (ids_connodes == id_node)]
+ print(' id_node', id_node)
+ print(' ids_conflicts', ids_con_tls[(inds_phaseconflict == 2) & (ids_connodes == id_node)])
+ print(' ids_merge', ids_con_tls[(inds_phaseconflict == 1) & (ids_connodes == id_node)])
# create traffic light system in SUMO net
n_phase = len(phaseconflicts)
if n_phase <= 1:
- print ' Less than one phase => abbandon.'
+ print(' Less than one phase => abbandon.')
return False
inds_con_controlled = np.zeros(n_cons, dtype=np.bool)
@@ -1170,7 +1170,7 @@ def make_majortls(self, id_node_major, inds_route):
inds_con_off = np.zeros(n_cons, dtype=np.bool)
states = []
ids_node_sumotls = []
- for id_node, nodeattrs in nodes_tls.iteritems():
+ for id_node, nodeattrs in nodes_tls.items():
# if nodeattrs['is_crossing']
# print ' tlscheck id_node',id_node,'is_cycleped',nodeattrs['is_cycleped']
if not nodeattrs['is_cycleped']:
@@ -1226,18 +1226,18 @@ def make_majortls(self, id_node_major, inds_route):
inds_con_sumotls = np.flatnonzero(inds_con_off | inds_con_controlled)
ids_con_sumotls = ids_con_tls[inds_con_sumotls]
- print ' ids_con_notls', ids_con_tls[inds_con_notls]
- print ' are_enabeled', ids_con_tls[are_enabeled]
- print ' ids_con_controlled', ids_con_tls[inds_con_controlled]
+ print(' ids_con_notls', ids_con_tls[inds_con_notls])
+ print(' are_enabeled', ids_con_tls[are_enabeled])
+ print(' ids_con_controlled', ids_con_tls[inds_con_controlled])
- print ' ids_node_sumotls', ids_node_sumotls
- print ' ids_con_sumotls', ids_con_sumotls
- print ' ids_con_off', ids_con_tls[inds_con_off]
+ print(' ids_node_sumotls', ids_node_sumotls)
+ print(' ids_con_sumotls', ids_con_sumotls)
+ print(' ids_con_off', ids_con_tls[inds_con_off])
#n_cons_sumotls = len(inds_con_sumotls)
states = []
weights = []
- for i, prio in zip(xrange(n_phase), phasepriorities):
+ for i, prio in zip(range(n_phase), phasepriorities):
#state = np.zeros(n_cons_sumotls, dtype = np.int32)
conflicts_last = phaseconflicts[i-1][inds_con_sumotls]
conflicts = phaseconflicts[i][inds_con_sumotls]
@@ -1262,7 +1262,7 @@ def make_majortls(self, id_node_major, inds_route):
states_sumotls = []
for state in states:
states_sumotls.append(string.join(signals[state], ''))
- print ' state=', states_sumotls[-1]
+ print(' state=', states_sumotls[-1])
id_tls = tlss.suggest_id()
weights = np.array(weights, dtype=np.float32)
@@ -1285,7 +1285,7 @@ def make_majortls(self, id_node_major, inds_route):
tlss.set_connections(id_tls, ids_con_sumotls)
# link controlled nodes to id_tls
- for id_node, nodeattrs in nodes_tls.iteritems():
+ for id_node, nodeattrs in nodes_tls.items():
# define controlled connections
# for id_con in ids_con_tls[(ids_connodes == id_node) & np.logical_not(are_enabeled)]:
# connections.are_uncontrolled[id_con] = id_con# not in ids_con_sumotls
@@ -1308,7 +1308,7 @@ def init_slots(self, inds_con_route, ids_con_tls,
ids_con_tls_route = ids_con_tls[inds_con_route]
for id_con, ind_con in zip(ids_con_tls_route, np.flatnonzero(inds_con_route)):
- print '\ninit_slots for id_con', id_con # ,ids_con_tls[ind_con],ind_con
+ print('\ninit_slots for id_con', id_con) # ,ids_con_tls[ind_con],ind_con
# print ' inds_cons_conflict\n',inds_cons_conflict[id_con]
# print ' inds_cons_merge\n',inds_cons_merge[id_con]
@@ -1321,7 +1321,7 @@ def init_slots(self, inds_con_route, ids_con_tls,
slots_raw = 2*(inds_cons_conflict[id_con] &
np.logical_not(inds_cons_merge[id_con])) + 1 * inds_cons_merge[id_con]
inds = np.flatnonzero(slots_raw)
- print ' block', ids_con_tls[inds]
+ print(' block', ids_con_tls[inds])
for ind_confl, slot_raw in zip(inds, slots_raw[inds]):
self.block_connection(ind_confl, slot_raw, slots, ids_fromlane_tls,
ids_tolane_tls, ids_con_tls, are_enabeled)
@@ -1344,8 +1344,8 @@ def init_slots(self, inds_con_route, ids_con_tls,
# inds_con_crit = inds_con_conf_check & np.logical_not(slots_blocked>0)
# inds_con_crit = inds_con_crit & are_enabeled
#
- print ' =>3stopslots for cons\n', ids_con_tls[slots == 2]
- print ' =>3mergeslots for cons\n', ids_con_tls[slots == 1]
+ print(' =>3stopslots for cons\n', ids_con_tls[slots == 2])
+ print(' =>3mergeslots for cons\n', ids_con_tls[slots == 1])
return slots, slots_blocked
@@ -1362,11 +1362,11 @@ def block_connection(self, ind_con_block, slot_raw, slots, ids_fromlane_tls, ids
id_fromlane = ids_fromlane_tls[ind_con_block]
is_disabled = not are_enabeled[ind_con_block]
- print 'block_connection id %d id_fromlane %d' % (ids_con_tls[ind_con_block], id_fromlane), 'nocycleped', lanes.ids_mode[ids_fromlane_tls[ind_con_block]] not in self.ids_cycleped, 'slot', slots[ind_con_block], 'L=%dm' % edges.lengths[lanes.ids_edge[id_fromlane]],
+ print('block_connection id %d id_fromlane %d' % (ids_con_tls[ind_con_block], id_fromlane), 'nocycleped', lanes.ids_mode[ids_fromlane_tls[ind_con_block]] not in self.ids_cycleped, 'slot', slots[ind_con_block], 'L=%dm' % edges.lengths[lanes.ids_edge[id_fromlane]], end=' ')
if (slots[ind_con_block] > 0) | is_disabled:
# ind_con_block has already been tuned to red
- print '*'
+ print('*')
return
# do not block across cycleped edges
@@ -1382,28 +1382,28 @@ def block_connection(self, ind_con_block, slot_raw, slots, ids_fromlane_tls, ids
# all connectors have not been visited
if (len(inds_con) > 0) & np.all(slots[inds_con] >= 0):
slots[ind_con_block] = -1 # sign as visited
- print
- print '->', ids_con_tls[inds_con]
+ print()
+ print('->', ids_con_tls[inds_con])
for ind_con in inds_con:
self.block_connection(ind_con, 2, slots, ids_fromlane_tls,
ids_tolane_tls, ids_con_tls, are_enabeled)
- print '.'
+ print('.')
slots[ind_con_block] = 0 # remove sign as visited
else:
# from lane is connected from outside the TLS:
slots[ind_con_block] = 2 # put red light
- print '-r'
+ print('-r')
else:
# road length acceptable
slots[ind_con_block] = slot_raw
- print '-s', slot_raw
+ print('-s', slot_raw)
else:
# to lane is bikeway or footpath
slots[ind_con_block] = slot_raw
- print '-b', slot_raw
+ print('-b', slot_raw)
# print ' stopslots %d for cons\n'%ids_con_tls[ind_con_block],ids_con_tls[slots == 2]
# print ' mergeslots %d for cons\n'%ids_con_tls[ind_con_block],ids_con_tls[slots == 1]
@@ -1418,7 +1418,7 @@ def add_timeslot(self, inds_con_route, inds_confict_groups, inds_merge_groups, p
Allocates a phase for a particular route though the TLS.
The route is represented by the connector indexes along the route.
"""
- print '\nadd_timeslot for', ids_con_tls[inds_con_route]
+ print('\nadd_timeslot for', ids_con_tls[inds_con_route])
# go through all connections used by this route and
# signalize all conflicts
# for id_con in ids_con_tls[inds_con_route]:
@@ -1432,40 +1432,40 @@ def add_timeslot(self, inds_con_route, inds_confict_groups, inds_merge_groups, p
ids_tolane_tls,
are_enabeled)
n_slots = len(np.flatnonzero(slots))
- print ' n_slots', n_slots, 'n_phases', len(phaseconflicts)
+ print(' n_slots', n_slots, 'n_phases', len(phaseconflicts))
if n_slots == 0:
- print ' no conflicts detected'
+ print(' no conflicts detected')
pass
elif len(phaseconflicts) == 0:
- print ' append first phase'
+ print(' append first phase')
phaseallocations.append(inds_con_route)
phaseconflicts.append(slots)
phaseblocks.append(slots_blocked)
phasepriorities.append(prio)
else:
- print ' search phase with minimum signal difference n_phases=', len(phaseallocations)
+ print(' search phase with minimum signal difference n_phases=', len(phaseallocations))
n_diff_min = 10**8
i_phase = 0
i_phase_min = -1
for inds_phaseallocation, inds_phaseconflict in zip(phaseallocations, phaseconflicts):
# check if slots overlap with allocated connections this phase
- print ' compare phase', i_phase
- print ' new allocations', ids_con_tls[inds_con_route]
- print ' phaseallocations', ids_con_tls[inds_phaseallocation]
- print ' new conflicts', ids_con_tls[slots == 2]
- print ' phase conflicts', ids_con_tls[inds_phaseconflict == 2]
+ print(' compare phase', i_phase)
+ print(' new allocations', ids_con_tls[inds_con_route])
+ print(' phaseallocations', ids_con_tls[inds_phaseallocation])
+ print(' new conflicts', ids_con_tls[slots == 2])
+ print(' phase conflicts', ids_con_tls[inds_phaseconflict == 2])
# print ' allocations',ids_con_tls[inds_phaseallocation]
- print ' n_diff =', np.sum(np.any((slots == 2) & inds_phaseallocation))
+ print(' n_diff =', np.sum(np.any((slots == 2) & inds_phaseallocation)))
if not np.any((slots == 2) & inds_phaseallocation):
- print ' no conflict in this phase go for a merge'
+ print(' no conflict in this phase go for a merge')
i_phase_min = i_phase
n_diff_min = -1 # indicate phase merge
else:
- print ' there are conflicts with this phase...count'
+ print(' there are conflicts with this phase...count')
n_diff = np.sum(np.any((slots == 2) & inds_phaseallocation))
#n_diff = np.sum(np.abs(slots - inds_phaseconflict)!=0)
# print ' ',inds_phaseconflict,n_diff
@@ -1475,14 +1475,14 @@ def add_timeslot(self, inds_con_route, inds_confict_groups, inds_merge_groups, p
i_phase += 1
- print ' finished comparing phases i_phase_min,n_diff_min', i_phase_min, n_diff_min
+ print(' finished comparing phases i_phase_min,n_diff_min', i_phase_min, n_diff_min)
if n_diff_min == 0:
- print ' already a phase with suitable signalling, nothing to do'
+ print(' already a phase with suitable signalling, nothing to do')
pass
elif n_diff_min == -1:
- print ' there are no phase conflicts, so merge'
+ print(' there are no phase conflicts, so merge')
phaseallocations[i_phase_min] = phaseallocations[i_phase_min] | inds_con_route
phaseconflicts[i_phase_min] = np.max([slots, phaseconflicts[i_phase_min]], 0)
phaseblocks[i_phase_min] = phaseblocks[i_phase_min] | slots_blocked
@@ -1498,14 +1498,14 @@ def add_timeslot(self, inds_con_route, inds_confict_groups, inds_merge_groups, p
# get number of cons which are less restrictive signals
n_diff_neg = np.sum((slots - phaseconflicts[i_phase_min]) < 0)
- print ' n_diff_min', n_diff_min, 'n_diff_pos', n_diff_pos, 'n_diff_neg', n_diff_neg, 'i_phase_min', i_phase_min
+ print(' n_diff_min', n_diff_min, 'n_diff_pos', n_diff_pos, 'n_diff_neg', n_diff_neg, 'i_phase_min', i_phase_min)
# print ' inds_phaseconflict_min',ids_con_tls[phaseconflicts[i_phase_min] >0]
# print ' inds_phaseconflict',ids_con_tls[slots>0]
#inds_diff = np.abs(slots - inds_phaseconflict)!=0
# if (n_diff_pos>0) & (n_diff_neg == 0):
if (n_diff_pos >= n_diff_neg) & (n_diff_pos <= 2):
# only more restrictive
- print ' put new phase after the phase with minimum difference'
+ print(' put new phase after the phase with minimum difference')
phaseallocations.insert(i_phase_min+1, inds_con_route)
phaseconflicts.insert(i_phase_min+1, slots)
phaseblocks.insert(i_phase_min+1, slots_blocked)
@@ -1514,7 +1514,7 @@ def add_timeslot(self, inds_con_route, inds_confict_groups, inds_merge_groups, p
# elif (n_diff_pos==0) & (n_diff_neg > 0):
if (n_diff_pos < n_diff_neg) & (n_diff_neg <= 2):
# only less restrictive
- print ' put new phase before the phase with minimum difference'
+ print(' put new phase before the phase with minimum difference')
phaseallocations.insert(i_phase_min, inds_con_route)
phaseconflicts.insert(i_phase_min, slots)
phaseblocks.insert(i_phase_min, slots_blocked)
@@ -1522,13 +1522,13 @@ def add_timeslot(self, inds_con_route, inds_confict_groups, inds_merge_groups, p
else:
# mixed changes
- print ' append en entirely new phase'
+ print(' append en entirely new phase')
phaseconflicts.append(slots)
phaseblocks.append(slots_blocked)
phasepriorities.append(prio)
def init_tlsnode(self, id_node, nodes_tls):
- print 'init_tlsnode', id_node, 'is in TLS'
+ print('init_tlsnode', id_node, 'is in TLS')
nodeattrs = {}
if id_node in self.ids_majornodes:
self.ids_majornodes_used.add(id_node)
@@ -1543,7 +1543,7 @@ def init_tlsnode(self, id_node, nodes_tls):
nodes_tls[id_node] = nodeattrs
def find_neighbour_nodes(self, id_node, dist, nodes_tls, edges, nodes):
- print 'find_neighbour_nodes', id_node, dist
+ print('find_neighbour_nodes', id_node, dist)
dist_tls_max = self.dist_tls_max
#ids_edge = nodes.ids_outgoing[id_node]
@@ -1556,23 +1556,23 @@ def find_neighbour_nodes(self, id_node, dist, nodes_tls, edges, nodes):
if len(ids_edge_out) == 1:
# one incoming one outgoing only, check if bidir link
if edges.ids_fromnode[ids_edge[0]] == edges.ids_tonode[ids_edge_out[0]]:
- print ' it is a turnaround only node -> remove node', id_node
+ print(' it is a turnaround only node -> remove node', id_node)
del nodes_tls[id_node]
return
elif len(ids_edge) == 0: # no input??
- print ' no input -> remove node', id_node
+ print(' no input -> remove node', id_node)
del nodes_tls[id_node]
return
for id_edge, length, id_edgenode in zip(ids_edge, edges.lengths[ids_edge], edges.ids_fromnode[ids_edge]):
- print ' check in id_edge', id_edge, dist+length, dist_tls_max, (dist+length < dist_tls_max), (length < self.dist_tls_internode_max)
+ print(' check in id_edge', id_edge, dist+length, dist_tls_max, (dist+length < dist_tls_max), (length < self.dist_tls_internode_max))
if (dist+length < dist_tls_max) & (length < self.dist_tls_internode_max):
if id_edgenode not in nodes_tls:
self.init_tlsnode(id_edgenode, nodes_tls)
self.find_neighbour_nodes(id_edgenode, dist+length, nodes_tls, edges, nodes)
else:
# node without incoming??
- print ' node without incoming -> remove node', id_node
+ print(' node without incoming -> remove node', id_node)
del nodes_tls[id_node]
return
@@ -1602,7 +1602,7 @@ def correct_tls_route(self, route, nodes_tls, is_check_angle=True,
that no turnarounds are used,
and for not major routes that the route follows a straight line.
"""
- print 'correct_tls_route', route
+ print('correct_tls_route', route)
net = self.parent
edges = net.edges
#ids_edges_major = self.ids_edges_major
@@ -1652,7 +1652,7 @@ def correct_tls_route(self, route, nodes_tls, is_check_angle=True,
# determine angle change
angle = get_diff_angle_clockwise(dir1, dir2)
angle_abs = min(angle, 2*np.pi-angle)
- print ' id_edge:%d, angle_abs:%.1f, angle_max: %.1f' % (id_edge, angle_abs/np.pi*180, angle_max/np.pi*180), id_fromnode in nodes_tls, (angle_abs < angle_max)
+ print(' id_edge:%d, angle_abs:%.1f, angle_max: %.1f' % (id_edge, angle_abs/np.pi*180, angle_max/np.pi*180), id_fromnode in nodes_tls, (angle_abs < angle_max))
if id_fromnode in nodes_tls:
# route is still in TLS
p01 = shape_curr[-2][:2]
@@ -1688,11 +1688,11 @@ def correct_tls_route(self, route, nodes_tls, is_check_angle=True,
newroutes.append(newroute)
routecosts.append(self.get_routecost(newroute))
- print ' ind_route', ind_route, len(route), 'newroutes', newroutes, 'routecosts', routecosts
+ print(' ind_route', ind_route, len(route), 'newroutes', newroutes, 'routecosts', routecosts)
return newroutes, routecosts
def follow_major_route_backward(self, id_edge_next, shape):
- print 'follow_major_route_backward', id_edge_next
+ print('follow_major_route_backward', id_edge_next)
net = self.parent
edges = net.edges
ids_edges_major = self.ids_edges_major
@@ -1787,7 +1787,7 @@ def follow_major_route_backward(self, id_edge_next, shape):
return route
def follow_major_route_foreward(self, id_edge_next, shape):
- print 'follow_major_route_foreward', id_edge_next
+ print('follow_major_route_foreward', id_edge_next)
net = self.parent
edges = net.edges
ids_edges_major = self.ids_edges_major
@@ -1833,7 +1833,7 @@ def follow_major_route_foreward(self, id_edge_next, shape):
angle = get_diff_angle_clockwise(dir1, dir2)
angle_abs = min(angle, 2*np.pi-angle)
edgedirection2 = shape[:2]
- print ' |angle|=%d' % (angle_abs/np.pi*180), angle/np.pi*180, dir1, dir2
+ print(' |angle|=%d' % (angle_abs/np.pi*180), angle/np.pi*180, dir1, dir2)
if angle_abs < angle_max:
if id_edge not in self.ids_edges_major:
@@ -1874,7 +1874,7 @@ def follow_major_route_foreward(self, id_edge_next, shape):
p01 = shape_next[-2][:2]
p11 = shape_next[-1][:2]
dir1 = p11-p01
- print ' **winner:', id_edge_next, 'dir1=', dir1
+ print(' **winner:', id_edge_next, 'dir1=', dir1)
route.append(id_edge_next)
ids_edges_major.add(id_edge_next)
@@ -1887,7 +1887,7 @@ def follow_major_route_foreward(self, id_edge_next, shape):
class BikenetworkCompleter(Process):
def __init__(self, net, logger=None, **kwargs):
- print 'Bikenetworkcompleter.__init__'
+ print('Bikenetworkcompleter.__init__')
self._init_common('bikenetworkcompleter',
parent=net,
name='Bike network completer',
@@ -1959,7 +1959,7 @@ def __init__(self, net, logger=None, **kwargs):
[modes.get_id_mode("pedestrian"), modes.get_id_mode("delivery"), modes.get_id_mode("bus")])
def do(self):
- print 'BikenetworkCompleter.do'
+ print('BikenetworkCompleter.do')
edges = self.parent.edges
nodes = self.parent.nodes
lanes = self.parent.lanes
@@ -2187,7 +2187,7 @@ def _make_bike_on_ped(self, id_lane, lanes):
class TlsjunctionGenerator_old(netconvert.NetConvertMixin):
def __init__(self, net, logger=None, **kwargs):
- print 'TlsjunctionGenerator.__init__'
+ print('TlsjunctionGenerator.__init__')
self._init_common('tlsjunctiongenerator',
parent=net,
name='Trafficlight Junction generator',
@@ -2215,7 +2215,7 @@ def __init__(self, net, logger=None, **kwargs):
))
def do(self):
- print 'TlsjunctionGenerator.do'
+ print('TlsjunctionGenerator.do')
net = self.parent
edges = self.parent.edges
nodes = self.parent.nodes
diff --git a/tools/contributed/sumopy/coremodules/network/networkxtools.py b/tools/contributed/sumopy/coremodules/network/networkxtools.py
index 62759e127ef0..2e6959db3947 100644
--- a/tools/contributed/sumopy/coremodules/network/networkxtools.py
+++ b/tools/contributed/sumopy/coremodules/network/networkxtools.py
@@ -32,7 +32,8 @@
from collections import OrderedDict
from copy import deepcopy
import sys
-reload(sys)
+import importlib
+importlib.reload(sys)
sys.setdefaultencoding('utf8')
try:
@@ -63,7 +64,7 @@ def load_objfile(filepath):
try:
f = open(filepath, 'rb')
except:
- print 'WARNING in load_obj: could not open', filepath
+ print('WARNING in load_obj: could not open', filepath)
return None
# try:
@@ -74,18 +75,18 @@ def load_objfile(filepath):
def print_attrs(attrs):
- for key, val in attrs.iteritems():
- print ' %s=\t%s' % (key, val)
- print
+ for key, val in attrs.items():
+ print(' %s=\t%s' % (key, val))
+ print()
def get_loop(digraph, ids_node, ids_nodepairs=[], n_node_max=4):
- print 'get_loop ids_node', ids_node
+ print('get_loop ids_node', ids_node)
if (ids_node[-1] == ids_node[0]):
- print ' success.'
+ print(' success.')
return ids_nodepairs
elif (len(ids_node) == n_node_max):
- print ' no loop reached.'
+ print(' no loop reached.')
return []
else:
id_node = ids_node[-1]
@@ -94,7 +95,7 @@ def get_loop(digraph, ids_node, ids_nodepairs=[], n_node_max=4):
id_nbnode = ids_node[-2]
# print ' node_to_dirind.keys()',node_to_dirind.keys(),node_to_dirind.has_key(id_nbnode)
- if node_to_dirind.has_key(id_nbnode):
+ if id_nbnode in node_to_dirind:
ind = node['node_to_dirind'][id_nbnode]
else:
ind = node['node_to_dirind'][-id_nbnode]
@@ -106,11 +107,11 @@ def get_loop(digraph, ids_node, ids_nodepairs=[], n_node_max=4):
id_nbnode_new = node['dirind_to_node'][ind]
if id_nbnode == id_nbnode_new:
- print ' simple bidir return link'
+ print(' simple bidir return link')
return []
elif abs(id_nbnode_new) in ids_node[1:]:
- print ' complex bidir return link'
+ print(' complex bidir return link')
return []
if id_nbnode_new < 0:
@@ -166,7 +167,7 @@ def config(self):
"""
Make defaults to be overridden
"""
- print 'config'
+ print('config')
# pass here either road type specific defaults
# or global defaults from parent process
@@ -272,7 +273,7 @@ def get_osmattr(self, key, is_int=False, is_float=False, default=None):
def make_sumoattrs(self):
osmattrs = self._osmattrs
- print 'make_sumoattrs'
+ print('make_sumoattrs')
print_attrs(osmattrs)
#self._highway = osmattrs.get('highway','road')
@@ -292,7 +293,7 @@ def make_lanestructure(self):
n_lane_backward_osm = -1
is_lanes_forward_rigid = False
is_lanes_backward_rigid = False
- if osmattrs.has_key('lanes'):
+ if 'lanes' in osmattrs:
# print ' total number of lanes provided n_lane_osm_str',osmattrs['lanes']
n_lane_osm_str = osmattrs['lanes']
# if type(n_lane_osm_str) in cm.STRINGTYPES:
@@ -317,10 +318,10 @@ def make_lanestructure(self):
else:
# in case of bidir
- if osmattrs.has_key('lanes:forward'):
+ if 'lanes:forward' in osmattrs:
n_lane_forward_osm = int(osmattrs['lanes:forward'])
is_lanes_forward_rigid = True
- if osmattrs.has_key('lanes:backward'):
+ if 'lanes:backward' in osmattrs:
n_lane_backward_osm = int(osmattrs['lanes:backward'])
is_lanes_backward_rigid = True
else:
@@ -330,7 +331,7 @@ def make_lanestructure(self):
n_lane_backward_osm = 1
n_lane_osm = n_lane_forward_osm+n_lane_backward_osm
- elif osmattrs.has_key('lanes:backward'):
+ elif 'lanes:backward' in osmattrs:
n_lane_backward_osm = int(osmattrs['lanes:backward'])
n_lane_forward_osm = n_lane_osm-n_lane_backward_osm
is_lanes_backward_rigid = True
@@ -352,23 +353,23 @@ def make_lanestructure(self):
if is_oneway_osm:
# in cas of (declared) oneway
n_lane_backward_osm = 0
- if osmattrs.has_key('lanes:forward'):
+ if 'lanes:forward' in osmattrs:
n_lane_forward_osm = int(osmattrs['lanes:forward'])
is_lanes_forward_rigid = True
else:
n_lane_forward_osm = self.n_lane # default
else:
# bidir
- if osmattrs.has_key('lanes:forward'):
+ if 'lanes:forward' in osmattrs:
n_lane_forward_osm = int(osmattrs['lanes:forward'])
is_lanes_forward_rigid = True
- if osmattrs.has_key('lanes:backward'):
+ if 'lanes:backward' in osmattrs:
n_lane_backward_osm = int(osmattrs['lanes:backward'])
is_lanes_backward_rigid = True
else:
n_lane_backward_osm = self.n_lane # default
- elif osmattrs.has_key('lanes:backward'):
+ elif 'lanes:backward' in osmattrs:
n_lane_backward_osm = int(osmattrs['lanes:backward'])
is_lanes_backward_rigid = True
n_lane_forward_osm = self.n_lane # default
@@ -386,7 +387,7 @@ def make_lanestructure(self):
self._n_lane_forward_osm = n_lane_forward_osm
self._n_lane_backward_osm = n_lane_backward_osm
self._n_lane_osm = n_lane_osm
- print ' lane numbers: n_lane_forward_osm=%d, n_lane_backward_osm=%d n_default=%d' % (n_lane_forward_osm, n_lane_backward_osm, self.n_lane), 'rigid fb', is_lanes_forward_rigid, is_lanes_backward_rigid
+ print(' lane numbers: n_lane_forward_osm=%d, n_lane_backward_osm=%d n_default=%d' % (n_lane_forward_osm, n_lane_backward_osm, self.n_lane), 'rigid fb', is_lanes_forward_rigid, is_lanes_backward_rigid)
def _get_access(self, access_str):
access_data = np.array(access_str.split('|'), dtype=np.object)[::-1]
@@ -446,12 +447,12 @@ def make_road(self):
#lanes = []
#lanes_opp = []
- print ' realoneway', self.is_oneway()
+ print(' realoneway', self.is_oneway())
#self._lanes = []
#self._lanes_opp = []
- print ' Main Dir ^^^^^^^^^^^', self._is_lanes_forward_rigid, self._is_lanes_backward_rigid
+ print(' Main Dir ^^^^^^^^^^^', self._is_lanes_forward_rigid, self._is_lanes_backward_rigid)
if self._is_lanes_forward_rigid:
self.make_lanes_rigid(is_opp=False, n_lane_osm=self._n_lane_forward_osm)
else:
@@ -459,15 +460,15 @@ def make_road(self):
if not self.is_oneway():
- print ' Opp Dir vvvvvvvvvvv'
+ print(' Opp Dir vvvvvvvvvvv')
if self._is_lanes_backward_rigid:
self.make_lanes_rigid(is_opp=True, n_lane_osm=self._n_lane_backward_osm)
else:
self.make_lanes(is_opp=True, n_lane_osm=self._n_lane_backward_osm)
- print ' id', id(self)
- print ' len(self._lanes)', len(self._lanes)
- print ' len(self._lanes_opp)', len(self._lanes_opp)
+ print(' id', id(self))
+ print(' len(self._lanes)', len(self._lanes))
+ print(' len(self._lanes_opp)', len(self._lanes_opp))
def _get_speedinfo(self, speed_max_str):
speed_max_data = speed_max_str.split(' ')
@@ -490,7 +491,7 @@ def _get_speedinfo(self, speed_max_str):
def make_speed(self, speed_max_default):
# estimate speed max in m/s
- if self._osmattrs.has_key('maxspeed'):
+ if 'maxspeed' in self._osmattrs:
speed_max_str = self._osmattrs['maxspeed']
# print 'make_speed speed_max_str',speed_max_str
if speed_max_str.count(';') > 0:
@@ -511,7 +512,7 @@ def make_speed(self, speed_max_default):
self.speed_max = speed_max
def _is_opposite(self, osmattrs, tag):
- if osmattrs.has_key(tag):
+ if tag in osmattrs:
elems = osmattrs[tag].split('_')
return elems[0] == 'opposite'
else:
@@ -527,7 +528,7 @@ def make_oneway(self):
if osmattrs.get('junction', '') == 'roundabout':
self._is_oneway = True
- elif osmattrs.has_key('oneway'):
+ elif 'oneway' in osmattrs:
if osmattrs['oneway'] == 'no':
self._is_oneway = False
@@ -538,13 +539,13 @@ def make_oneway(self):
elif self._is_opposite(osmattrs, 'busway:right'):
self._is_oneway = False
- elif osmattrs.has_key('lanes:bus:backward'):
+ elif 'lanes:bus:backward' in osmattrs:
self._is_oneway = False
- elif osmattrs.has_key('trolley_wire:both'):
+ elif 'trolley_wire:both' in osmattrs:
self._is_oneway = False
- elif osmattrs.has_key('lanes:psv:backward'):
+ elif 'lanes:psv:backward' in osmattrs:
self._is_oneway = False
elif self._is_opposite(osmattrs, 'cycleway'):
@@ -563,7 +564,7 @@ def make_oneway(self):
# elif osmattrs.get('sidewalk','') == 'both':
# self._is_oneway = False
- elif osmattrs.has_key('oneway:bicycle'):
+ elif 'oneway:bicycle' in osmattrs:
if osmattrs['oneway:bicycle'] == 'no':
self._is_oneway = False
@@ -607,7 +608,7 @@ def add_sidewalk(self, road, is_opp=False):
else:
ind = 1
- print 'add_sidewalk', is_opp, self._sidewalkattrs[ind]['n_lane'], self._sidewalkattrs[ind]['n_lane'] == 0
+ print('add_sidewalk', is_opp, self._sidewalkattrs[ind]['n_lane'], self._sidewalkattrs[ind]['n_lane'] == 0)
if self._sidewalkattrs[ind]['n_lane'] == 0:
self.make_sidewalk(is_opp=is_opp, is_rightside=True, width=road.lanewidth)
self.make_road()
@@ -629,7 +630,7 @@ def make_sidewalk(self, is_opp=False, is_rightside=True,
# to mark that sidewalks are mapped separately.
# Also, sidewalk=separate
- print 'make_sidewalk', ind, is_rightside
+ print('make_sidewalk', ind, is_rightside)
# needed to merge access?
self._sidewalkattrs[ind]['is_share'] = len(ids_modes_allow) > 0
@@ -657,7 +658,7 @@ def make_sidewalk(self, is_opp=False, is_rightside=True,
print_attrs(self._sidewalkattrs[ind])
def make_sidewalkattrs(self):
- print 'make_sidewalkattrs'
+ print('make_sidewalkattrs')
if self.get_priority() < 7:
return self.make_sidewalkattrs_smallroads()
@@ -665,7 +666,7 @@ def make_sidewalkattrs(self):
return self.make_sidewalkattrs_largeroads()
def make_sidewalkattrs_largeroads(self):
- print 'make_sidewalkattrs_largeroads'
+ print('make_sidewalkattrs_largeroads')
osmattrs = self._osmattrs
self._sidewalkattrs = (deepcopy(LANEATTRS_DEFAULT),
@@ -678,11 +679,11 @@ def make_sidewalkattrs_largeroads(self):
if sidewalk not in ['no', 'none', 'auto']:
# there is a sidewalk, make sure there is at least one
- if osmattrs.has_key('sidewalk:width'):
+ if 'sidewalk:width' in osmattrs:
width_left = float(osmattrs['sidewalk:width'])
width_right = width_left
- elif osmattrs.has_key('sidewalk:both:width'):
+ elif 'sidewalk:both:width' in osmattrs:
width_left = float(osmattrs['sidewalk:both:width'])
width_right = width_left
else:
@@ -742,7 +743,7 @@ def make_sidewalkattrs_largeroads(self):
# print_attrs(attrs)
def make_sidewalkattrs_smallroads(self):
- print 'make_sidewalkattrs_smallroads'
+ print('make_sidewalkattrs_smallroads')
osmattrs = self._osmattrs
self._sidewalkattrs = (deepcopy(LANEATTRS_DEFAULT),
deepcopy(LANEATTRS_DEFAULT))
@@ -754,11 +755,11 @@ def make_sidewalkattrs_smallroads(self):
if sidewalk not in ['no', 'none', 'auto']:
# there is a sidewalk, make sure there is at least one
- if osmattrs.has_key('sidewalk:width'):
+ if 'sidewalk:width' in osmattrs:
width_left = float(osmattrs['sidewalk:width'])
width_right = width_left
- elif osmattrs.has_key('sidewalk:both:width'):
+ elif 'sidewalk:both:width' in osmattrs:
width_left = float(osmattrs['sidewalk:both:width'])
width_right = width_left
else:
@@ -808,20 +809,20 @@ def make_sidewalkattrs_smallroads(self):
if self.is_oneway():
if osmattrs.get('junction', '') == 'roundabout':
- print ' put a sidewalk around roundabouts, not inside'
+ print(' put a sidewalk around roundabouts, not inside')
self.make_sidewalk(is_opp=False, is_rightside=True, width=self.width_sidewalk)
else:
- print ' put a sidewalk on both sides of the oneway'
+ print(' put a sidewalk on both sides of the oneway')
self.make_sidewalk(is_opp=False, is_rightside=True, width=self.width_sidewalk)
self.make_sidewalk(is_opp=False, is_rightside=False, width=self.width_sidewalk)
else:
- print ' put a sidewalk on both sides of the road'
+ print(' put a sidewalk on both sides of the road')
self.make_sidewalk(is_opp=False, is_rightside=True, width=self.width_sidewalk)
self.make_sidewalk(is_opp=True, is_rightside=True, width=self.width_sidewalk)
def make_bikelane(self, is_opp=False, is_rightside=True,
ids_modes_allow=[], width=1.5, n_lane=1):
- print 'make_bikelane', is_opp, is_rightside, ids_modes_allow
+ print('make_bikelane', is_opp, is_rightside, ids_modes_allow)
if is_opp:
ind = 0
else:
@@ -857,7 +858,7 @@ def make_bikewayattrs(self):
widths: is a tuple with sidewalk widths of left and right sidewalk.
if values are less than 0 means no sidewalk.
"""
- print 'make_bikewayattrs'
+ print('make_bikewayattrs')
self._bikewayattrs = (deepcopy(LANEATTRS_DEFAULT),
deepcopy(LANEATTRS_DEFAULT))
@@ -866,11 +867,11 @@ def make_bikewayattrs(self):
cycleway_left = osmattrs.get('cycleway:left', '')
cycleway_right = osmattrs.get('cycleway:right', '')
- if osmattrs.has_key('cycleway:width'):
+ if 'cycleway:width' in osmattrs:
width_left = float(osmattrs['cycleway:width'])
width_right = width_left
- elif osmattrs.has_key('cycleway:both:width'):
+ elif 'cycleway:both:width' in osmattrs:
width_left = float(osmattrs['cycleway:both:width'])
width_right = width_left
@@ -942,7 +943,7 @@ def make_bikewayattrs(self):
# general bicycle tag if all from abive fails but share with pedestrians
# Moved to main lane attr except if segragated
elif (osmattrs.get('bicycle', 'no') in YES_OR_DESIGNATED) & (osmattrs.get('segregated', '') == 'yes'):
- print ' check if there are cycle lanes already', self._bikewayattrs[0]['n_lane'] == 0, self._bikewayattrs[1]['n_lane'] == 0
+ print(' check if there are cycle lanes already', self._bikewayattrs[0]['n_lane'] == 0, self._bikewayattrs[1]['n_lane'] == 0)
if (self._bikewayattrs[0]['n_lane'] == 0) & (self._bikewayattrs[1]['n_lane'] == 0):
# no bikelanes in both dir
@@ -1003,7 +1004,7 @@ def make_bikewayattrs(self):
# Moved to main lane attr except segregated
elif (osmattrs.get('bicycle', 'no') in YES_OR_DESIGNATED) & (osmattrs.get('segregated', '') == 'yes'):
- print ' check if there are cycle lanes already', self._bikewayattrs[1]['n_lane'] == 0
+ print(' check if there are cycle lanes already', self._bikewayattrs[1]['n_lane'] == 0)
if (self._bikewayattrs[1]['n_lane'] == 0):
self.make_bikelane(is_opp=False, is_rightside=True, width=width_left)
@@ -1014,7 +1015,7 @@ def make_bikewayattrs(self):
def make_buslane(self, is_opp=False, is_rightside=True,
ids_modes_allow=[], width=3.5, n_lane=1):
- print 'make_buslane', is_opp, is_rightside, width
+ print('make_buslane', is_opp, is_rightside, width)
if is_opp:
ind = 0
else:
@@ -1052,17 +1053,17 @@ def _get_psv_from_str(self, psv_str):
return 0
def make_buswayattrs(self):
- print 'make_buswayattrs'
+ print('make_buswayattrs')
self._buswayattrs = (deepcopy(LANEATTRS_DEFAULT),
deepcopy(LANEATTRS_DEFAULT))
osmattrs = self._osmattrs
- if osmattrs.has_key('busway:width'):
+ if 'busway:width' in osmattrs:
width_left = float(osmattrs['busway:width'])
width_right = width_left
- elif osmattrs.has_key('busway:both:width'):
+ elif 'busway:both:width' in osmattrs:
width_left = float(osmattrs['busway:both:width'])
width_right = width_left
else:
@@ -1075,7 +1076,7 @@ def make_buswayattrs(self):
# busway scheme
if osmattrs.get('oneway', 'no') == 'no':
# bidir
- print ' buslane bidir', busway
+ print(' buslane bidir', busway)
if busway == 'lane':
self.make_buslane(is_opp=False)
self.make_buslane(is_opp=True)
@@ -1125,7 +1126,7 @@ def make_buswayattrs(self):
else:
# cycle lanes on oneway road
- print ' buslane oneway', busway, busway in ('opposite', 'opposite_lane')
+ print(' buslane oneway', busway, busway in ('opposite', 'opposite_lane'))
if busway == 'lane':
self.make_buslane(is_opp=False, width=width_right)
@@ -1151,7 +1152,7 @@ def make_buswayattrs(self):
return
- elif osmattrs.has_key('lanes:psv'):
+ elif 'lanes:psv' in osmattrs:
# lanes:psv=* scheme
if osmattrs.get('oneway', 'no') == 'no':
# bidir
@@ -1173,7 +1174,7 @@ def make_buswayattrs(self):
self.make_buslane(is_opp=False, n_lane=psv, width=width_right)
return
- elif osmattrs.has_key('lanes:bus'):
+ elif 'lanes:bus' in osmattrs:
# lanes:psv=* scheme
if osmattrs.get('oneway', 'no') == 'no':
# bidir
@@ -1189,25 +1190,25 @@ def make_buswayattrs(self):
self.make_buslane(is_opp=False, n_lane=psv, width=width_right)
return
- if osmattrs.has_key('lanes:psv:forward'):
+ if 'lanes:psv:forward' in osmattrs:
psv = self._get_psv_from_str(osmattrs['lanes:psv:forward'])
self.make_buslane(is_opp=False, n_lane=psv, width=width_right)
- if osmattrs.has_key('lanes:psv:backward'):
+ if 'lanes:psv:backward' in osmattrs:
psv = self._get_psv_from_str(osmattrs['lanes:psv:backward'])
self.make_buslane(is_opp=True, n_lane=psv, width=width_left)
- if osmattrs.has_key('lanes:bus:forward'):
+ if 'lanes:bus:forward' in osmattrs:
n_lane = self._get_psv_from_str(osmattrs['lanes:bus:forward'])
self.make_buslane(is_opp=False, n_lane=n_lane, width=width_right)
- if osmattrs.has_key('lanes:bus:backward'):
+ if 'lanes:bus:backward' in osmattrs:
n_lane = self._get_psv_from_str(osmattrs['lanes:bus:backward'])
self.make_buslane(is_opp=True, n_lane=n_lane, width=width_left)
if osmattrs.get('oneway', 'no') == 'yes':
# special check of opposite bus lane
- if osmattrs.has_key('trolley_wire:both') | osmattrs.has_key('trolley_wire:backward'):
+ if ('trolley_wire:both' in osmattrs) | ('trolley_wire:backward' in osmattrs):
# if way is oneway withot reserved access,
# but there are wires in both ways,
# then there is probably a reserved bus lane in opposite
@@ -1289,7 +1290,7 @@ def get_priority(self, is_opp=False):
return 10
def merge_laneattrs(self, laneattrs_dest, laneattrs_merge, is_rightside=False, is_leftside=False):
- print 'merge_laneattrs'
+ print('merge_laneattrs')
# print ' laneattrs_dest',laneattrs_dest
# print ' laneattrs_merge',laneattrs_merge
#self._buswayattrs[ind]['ids_modes_allow'] = ids_allowed
@@ -1297,7 +1298,7 @@ def merge_laneattrs(self, laneattrs_dest, laneattrs_merge, is_rightside=False, i
#self._buswayattrs[ind]['is_rightside'] = is_rightside
# if laneattrs_merge['width']>laneattrs_dest['width']:
width_dest = 0.0
- if laneattrs_dest.has_key('width'):
+ if 'width' in laneattrs_dest:
width_dest = laneattrs_dest['width']
else:
if is_rightside:
@@ -1305,7 +1306,7 @@ def merge_laneattrs(self, laneattrs_dest, laneattrs_merge, is_rightside=False, i
else:
width_dest = laneattrs_dest['width_leftside']
- if laneattrs_merge.has_key('width'):
+ if 'width' in laneattrs_merge:
width_merge = laneattrs_merge['width']
else:
if is_rightside:
@@ -1335,8 +1336,8 @@ def append_lane(self, lanes, laneattrs, is_rightside=False, is_leftside=False):
def set_lane(self, lanes, laneattrs, ind):
lanes[ind] = deepcopy(laneattrs)
- if not laneattrs.has_key('width'):
- if laneattrs.has_key('width_rightside'):
+ if 'width' not in laneattrs:
+ if 'width_rightside' in laneattrs:
lanes[ind]['width'] = laneattrs['width_rightside']
else:
lanes[ind]['width'] = laneattrs['width_rightside']
@@ -1362,7 +1363,7 @@ def allow_on_lane(self, laneattrs, ids_allow):
laneattrs['ids_modes_allow'].append(id_allow)
def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
- print 'make_lanes_rigid', is_opp, n_lane_osm
+ print('make_lanes_rigid', is_opp, n_lane_osm)
osmattrs = self._osmattrs
if is_opp:
@@ -1386,7 +1387,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
attrs = self._buswayattrs[ind]
if attrs['n_lane'] > 0:
- print ' busways n_lane', attrs['n_lane']
+ print(' busways n_lane', attrs['n_lane'])
n_lane = len(lanes)
@@ -1396,7 +1397,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
n_allow = len(allowed)
if n_allow > 0:
- for i, a, d in zip(xrange(n_allow), allowed, disallowed):
+ for i, a, d in zip(range(n_allow), allowed, disallowed):
if ind < n_lane:
if a & (i < n_lane):
self.set_lane(lanes, attrs, i)
@@ -1418,7 +1419,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
# do bikeways
attrs = self._bikewayattrs[ind]
if attrs['n_lane'] > 0:
- print ' bikeways n_lane', attrs['n_lane']
+ print(' bikeways n_lane', attrs['n_lane'])
n_lane = len(lanes)
@@ -1426,7 +1427,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
n_allow = len(allowed)
if n_allow > 0:
- for i, a, d in zip(xrange(n_allow), allowed, disallowed):
+ for i, a, d in zip(range(n_allow), allowed, disallowed):
if i < n_lane:
if a & i < n_lane:
self.set_lane(lanes, attrs, i)
@@ -1448,7 +1449,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
# do sidewalks
attrs = self._sidewalkattrs[ind]
if attrs['n_lane'] > 0:
- print ' sidewalks n_lane', attrs['n_lane']
+ print(' sidewalks n_lane', attrs['n_lane'])
n_lane_assig = attrs['n_lane']
n_lane = len(lanes)
# sidewalks are not considered lanes in osm
@@ -1477,14 +1478,14 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
self._lanes_opp = lanes
else:
self._lanes = lanes
- print ' created %d lanes' % len(lanes)
+ print(' created %d lanes' % len(lanes))
# print ' lanes', lanes
for laneattrs in lanes:
print_attrs(laneattrs)
return True
def make_lanes(self, is_opp=False, n_lane_osm=0):
- print 'make_lanes', is_opp, n_lane_osm
+ print('make_lanes', is_opp, n_lane_osm)
osmattrs = self._osmattrs
is_lanes_rigid = False
@@ -1503,7 +1504,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
# do busways
attrs = self._buswayattrs[ind]
if attrs['n_lane'] > 0:
- print ' busways n_lane', attrs['n_lane']
+ print(' busways n_lane', attrs['n_lane'])
n_lane_assig = attrs['n_lane']
n_lane = len(lanes)
@@ -1518,7 +1519,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
# do bikeways
attrs = self._bikewayattrs[ind]
if attrs['n_lane'] > 0:
- print ' bikeways n_lane', attrs['n_lane']
+ print(' bikeways n_lane', attrs['n_lane'])
n_lane_assig = attrs['n_lane']
n_lane = len(lanes)
@@ -1541,7 +1542,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
attrs = self._sidewalkattrs[ind]
if attrs['n_lane'] > 0:
- print ' sidewalks n_lane', attrs['n_lane']
+ print(' sidewalks n_lane', attrs['n_lane'])
n_lane_assig = attrs['n_lane']
n_lane = len(lanes)
# sidewalks are not considered lanes in osm
@@ -1570,7 +1571,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
self._lanes_opp = lanes
else:
self._lanes = lanes
- print ' created %d lanes' % len(lanes)
+ print(' created %d lanes' % len(lanes))
# print ' lanes', lanes
for laneattrs in lanes:
print_attrs(laneattrs)
@@ -1597,7 +1598,7 @@ def configure_edge(self, id_edge, net, is_opp=False, is_remove_sidewalk=0):
ind = 1
lanes = np.array(self._lanes)
- print 'configure_edge', id_edge, net.edges.ids_sumo[id_edge], self.highway, 'is_opp', is_opp, 'n_lanes', len(lanes), 'is_remove_sidewalk', is_remove_sidewalk
+ print('configure_edge', id_edge, net.edges.ids_sumo[id_edge], self.highway, 'is_opp', is_opp, 'n_lanes', len(lanes), 'is_remove_sidewalk', is_remove_sidewalk)
if self._is_oneway: # & (not self.is_roundabout()):
type_spread = 1 # centered
@@ -1628,11 +1629,11 @@ def configure_edge(self, id_edge, net, is_opp=False, is_remove_sidewalk=0):
for laneattrs in lanes:
# &lanes[-1]['is_sidewalk']:
if (ind == 0) & laneattrs['is_sidewalk'] & (is_remove_sidewalk == 2) & (ind_lastlane > 0):
- print ' sidewalk removed on right side'
+ print(' sidewalk removed on right side')
pass
# &lanes[0]['is_sidewalk']:
elif (ind == ind_lastlane) & laneattrs['is_sidewalk'] & (is_remove_sidewalk == 1) & (ind_lastlane > 0):
- print ' sidewalk removed on left side'
+ print(' sidewalk removed on left side')
pass
else:
inds_valid.append(ind)
@@ -1667,12 +1668,12 @@ def configure_edge(self, id_edge, net, is_opp=False, is_remove_sidewalk=0):
# add lanes
if n_lane == 0:
- print 'WARNING: no lane for this direction!!'
+ print('WARNING: no lane for this direction!!')
else:
- print ' inds_valid', inds_valid
+ print(' inds_valid', inds_valid)
ids_lane = net.lanes.add_rows(n_lane)
- for id_lane, ind_lane, laneattrs in zip(ids_lane, xrange(n_lane), lanes[inds_valid]):
+ for id_lane, ind_lane, laneattrs in zip(ids_lane, range(n_lane), lanes[inds_valid]):
if len(laneattrs['ids_modes_allow']) == 0:
id_mode_main = self.id_mode
else:
@@ -1753,7 +1754,7 @@ def get_priority(self, is_opp=False):
return 10
def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
- print 'make_lanes_rigid', is_opp, n_lane_osm
+ print('make_lanes_rigid', is_opp, n_lane_osm)
osmattrs = self._osmattrs
if is_opp:
@@ -1777,7 +1778,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
attrs = self._buswayattrs[ind]
if attrs['n_lane'] > 0:
- print ' busways n_lane', attrs['n_lane']
+ print(' busways n_lane', attrs['n_lane'])
n_lane = len(lanes)
@@ -1787,7 +1788,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
n_allow = len(allowed)
if n_allow > 0:
- for i, a, d in zip(xrange(n_allow), allowed, disallowed):
+ for i, a, d in zip(range(n_allow), allowed, disallowed):
if ind < n_lane:
if a & (i < n_lane):
self.set_lane(lanes, attrs, i)
@@ -1809,7 +1810,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
# do bikeways
attrs = self._bikewayattrs[ind]
if attrs['n_lane'] > 0:
- print ' bikeways n_lane', attrs['n_lane']
+ print(' bikeways n_lane', attrs['n_lane'])
n_lane = len(lanes)
@@ -1817,7 +1818,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
n_allow = len(allowed)
if n_allow > 0:
- for i, a, d in zip(xrange(n_allow), allowed, disallowed):
+ for i, a, d in zip(range(n_allow), allowed, disallowed):
if i < n_lane:
if a & i < n_lane:
self.set_lane(lanes, attrs, i)
@@ -1846,7 +1847,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
# do sidewalks
attrs = self._sidewalkattrs[ind]
if attrs['n_lane'] > 0:
- print ' sidewalks n_lane', attrs['n_lane']
+ print(' sidewalks n_lane', attrs['n_lane'])
n_lane_assig = attrs['n_lane']
n_lane = len(lanes)
# sidewalks are not considered lanes in osm
@@ -1876,14 +1877,14 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
self._lanes_opp = lanes
else:
self._lanes = lanes
- print ' created %d lanes' % len(lanes)
+ print(' created %d lanes' % len(lanes))
# print ' lanes', lanes
for laneattrs in lanes:
print_attrs(laneattrs)
return True
def make_lanes(self, is_opp=False, n_lane_osm=0):
- print 'make_lanes primary', is_opp, n_lane_osm
+ print('make_lanes primary', is_opp, n_lane_osm)
osmattrs = self._osmattrs
#is_lanes_rigid = False
@@ -1902,7 +1903,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
# do busways
attrs = self._buswayattrs[ind]
if attrs['n_lane'] > 0:
- print ' busways n_lane', attrs['n_lane']
+ print(' busways n_lane', attrs['n_lane'])
n_lane_assig = attrs['n_lane']
n_lane = len(lanes)
@@ -1917,7 +1918,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
# do bikeways
attrs = self._bikewayattrs[ind]
if attrs['n_lane'] > 0:
- print ' bikeways n_lane', attrs['n_lane']
+ print(' bikeways n_lane', attrs['n_lane'])
n_lane_assig = attrs['n_lane']
n_lane = len(lanes)
@@ -1947,7 +1948,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
# do sidewalks
attrs = self._sidewalkattrs[ind]
if attrs['n_lane'] > 0:
- print ' sidewalks n_lane', attrs['n_lane']
+ print(' sidewalks n_lane', attrs['n_lane'])
n_lane_assig = attrs['n_lane']
n_lane = len(lanes)
# sidewalks are not considered lanes in osm
@@ -1976,7 +1977,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
self._lanes_opp = lanes
else:
self._lanes = lanes
- print ' created %d lanes' % len(lanes)
+ print(' created %d lanes' % len(lanes))
# print ' lanes', lanes
for laneattrs in lanes:
print_attrs(laneattrs)
@@ -2025,7 +2026,7 @@ def get_priority(self, is_opp=False):
return 10
def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
- print 'make_lanes_rigid', is_opp, n_lane_osm
+ print('make_lanes_rigid', is_opp, n_lane_osm)
osmattrs = self._osmattrs
if is_opp:
@@ -2048,14 +2049,14 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
self._lanes_opp = lanes
else:
self._lanes = lanes
- print ' created %d lanes' % len(lanes)
+ print(' created %d lanes' % len(lanes))
# print ' lanes', lanes
for laneattrs in lanes:
print_attrs(laneattrs)
return True
def make_lanes(self, is_opp=False, n_lane_osm=0):
- print 'make_lanes primary', is_opp, n_lane_osm
+ print('make_lanes primary', is_opp, n_lane_osm)
osmattrs = self._osmattrs
#is_lanes_rigid = False
@@ -2078,7 +2079,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
self._lanes_opp = lanes
else:
self._lanes = lanes
- print ' created %d lanes' % len(lanes)
+ print(' created %d lanes' % len(lanes))
# print ' lanes', lanes
for laneattrs in lanes:
print_attrs(laneattrs)
@@ -2119,7 +2120,7 @@ def get_priority(self, is_opp=False):
return 3
def make_sidewalkattrs(self):
- print 'make_sidewalkattrs'
+ print('make_sidewalkattrs')
self.make_sidewalkattrs_smallroads()
@@ -2217,7 +2218,7 @@ def make_sidewalkattrs(self):
# but there will be no sidewalk of sidewalk
def make_bikewayattrs(self):
- print 'Footpath.make_bikewayattrs'
+ print('Footpath.make_bikewayattrs')
osmattrs = self._osmattrs
self._bikewayattrs = (deepcopy(LANEATTRS_DEFAULT),
deepcopy(LANEATTRS_DEFAULT))
@@ -2244,7 +2245,7 @@ def make_bikewayattrs(self):
self.make_bikelane(is_opp=False, is_rightside=False, width=width_right)
def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
- print 'Footpath.make_lanes_rigid ped', is_opp, n_lane_osm
+ print('Footpath.make_lanes_rigid ped', is_opp, n_lane_osm)
osmattrs = self._osmattrs
if is_opp:
@@ -2273,7 +2274,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
attrs = self._buswayattrs[ind]
if attrs['n_lane'] > 0:
- print ' busways n_lane', attrs['n_lane']
+ print(' busways n_lane', attrs['n_lane'])
n_lane = len(lanes)
@@ -2283,7 +2284,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
n_allow = len(allowed)
if n_allow > 0:
- for i, a, d in zip(xrange(n_allow), allowed, disallowed):
+ for i, a, d in zip(range(n_allow), allowed, disallowed):
if ind < n_lane:
if a & (i < n_lane):
self.set_lane(lanes, attrs, i)
@@ -2305,7 +2306,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
# do bikeways
attrs = self._bikewayattrs[ind]
if attrs['n_lane'] > 0:
- print ' bikeways n_lane', attrs['n_lane']
+ print(' bikeways n_lane', attrs['n_lane'])
n_lane = len(lanes)
@@ -2313,7 +2314,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
n_allow = len(allowed)
if n_allow > 0:
- for i, a, d in zip(xrange(n_allow), allowed, disallowed):
+ for i, a, d in zip(range(n_allow), allowed, disallowed):
if i < n_lane:
if a & i < n_lane:
self.set_lane(lanes, attrs, i)
@@ -2333,10 +2334,10 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
n_lane_assig -= 1
def make_lanes(self, is_opp=False, n_lane_osm=0):
- print 'Footpath.make_lanes', is_opp, n_lane_osm, 'n_bikelane', len(self._bikewayattrs)
+ print('Footpath.make_lanes', is_opp, n_lane_osm, 'n_bikelane', len(self._bikewayattrs))
osmattrs = self._osmattrs
- print ' main lane attrs'
+ print(' main lane attrs')
print_attrs(self._laneattrs_main)
if is_opp:
@@ -2357,7 +2358,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
# do busways
attrs = self._buswayattrs[ind]
if attrs['n_lane'] > 0:
- print ' busways n_lane', attrs['n_lane']
+ print(' busways n_lane', attrs['n_lane'])
n_lane_assig = attrs['n_lane']
n_lane = len(lanes)
@@ -2371,11 +2372,11 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
# do bikeways
- print ' bikewayattrs:'
+ print(' bikewayattrs:')
attrs = self._bikewayattrs[ind]
print_attrs(attrs)
if attrs['n_lane'] > 0:
- print ' bikeways n_lane', attrs['n_lane']
+ print(' bikeways n_lane', attrs['n_lane'])
n_lane_assig = attrs['n_lane']
n_lane = len(lanes)
@@ -2399,7 +2400,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
else:
self._lanes = lanes
- print ' created %d lanes' % len(lanes)
+ print(' created %d lanes' % len(lanes))
# print ' lanes', lanes
for laneattrs in lanes:
print_attrs(laneattrs)
@@ -2412,7 +2413,7 @@ def config(self):
"""
Make defaults to be overridden
"""
- print 'config cycleway'
+ print('config cycleway')
# pass here either road type specific defaults
# or global defaults from parent process
@@ -2444,7 +2445,7 @@ def config(self):
self.ids_modes_disallow = []
self.make_speed(self.parent.speed_max_bike)
- print ' ids_modes_allow', self.ids_modes_allow
+ print(' ids_modes_allow', self.ids_modes_allow)
#self.speed_max_bus = self.parent.speed_max_bus
#self.speed_max_bike = self.parent.speed_max_bike
self.speed_max_ped = self.parent.speed_max_ped
@@ -2479,12 +2480,12 @@ def make_bikewayattrs(self):
pass
def make_sidewalkattrs(self):
- print 'make_sidewalkattrs'
+ print('make_sidewalkattrs')
# put sidewalks only if sidewalk attributes are given
return self.make_sidewalkattrs_largeroads()
def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
- print 'make_lanes_rigid cycle', is_opp, n_lane_osm
+ print('make_lanes_rigid cycle', is_opp, n_lane_osm)
osmattrs = self._osmattrs
if is_opp:
@@ -2502,7 +2503,7 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
# do sidewalks
attrs = self._sidewalkattrs[ind]
if attrs['n_lane'] > 0:
- print ' sidewalks n_lane', attrs['n_lane']
+ print(' sidewalks n_lane', attrs['n_lane'])
n_lane_assig = attrs['n_lane']
n_lane = len(lanes)
# sidewalks are not considered lanes in osm
@@ -2531,14 +2532,14 @@ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
self._lanes_opp = lanes
else:
self._lanes = lanes
- print ' created %d lanes' % len(lanes)
+ print(' created %d lanes' % len(lanes))
# print ' lanes', lanes
for laneattrs in lanes:
print_attrs(laneattrs)
return True
def make_lanes(self, is_opp=False, n_lane_osm=0):
- print 'make_lanes cycle', is_opp, n_lane_osm
+ print('make_lanes cycle', is_opp, n_lane_osm)
osmattrs = self._osmattrs
is_lanes_rigid = False
@@ -2557,7 +2558,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
# do sidewalks
attrs = self._sidewalkattrs[ind]
if attrs['n_lane'] > 0:
- print ' sidewalks n_lane', attrs['n_lane']
+ print(' sidewalks n_lane', attrs['n_lane'])
n_lane_assig = attrs['n_lane']
n_lane = len(lanes)
# sidewalks are not considered lanes in osm
@@ -2586,7 +2587,7 @@ def make_lanes(self, is_opp=False, n_lane_osm=0):
self._lanes_opp = lanes
else:
self._lanes = lanes
- print ' created %d lanes' % len(lanes)
+ print(' created %d lanes' % len(lanes))
# print ' lanes', lanes
for laneattrs in lanes:
print_attrs(laneattrs)
@@ -2637,7 +2638,7 @@ def __init__(self, scenario,
info='Import of network imported with the help of osmnx.',
logger=None, **kwargs):
- print 'OxImporter.__init__'
+ print('OxImporter.__init__')
self._init_common(ident,
parent=scenario,
@@ -2797,10 +2798,10 @@ def get_scenario(self):
return self.parent
def do(self):
- print self.ident+'.do'
+ print(self.ident+'.do')
- print ' osmdatafilepaths', self.osmdatafilepaths
- print ' nxnetworkpaths', self.nxnetworkpaths
+ print(' osmdatafilepaths', self.osmdatafilepaths)
+ print(' nxnetworkpaths', self.nxnetworkpaths)
net = self.get_scenario().net
self._net = net
self._map_id_edge_sumo_to_doubles = {}
@@ -2830,19 +2831,19 @@ def import_osmdata(self, osmdata):
# {u'lat': 47.6038005, u'type': u'node', u'lon': 7.6006465, u'id': 453208, u'tags': {u'ref': u'69', u'name': u'Weil am Rhein / H\xfcningen', u'highway': u'motorway_junction'}}
# print ' parse element',element['id'],element['type']
if element['type'] == 'way':
- if element.has_key('tags'):
+ if 'tags' in element:
highway = element['tags'].get('highway', 'road')
else:
highway = 'road'
- print ' '+70*'-'
- print ' way', element['id'], type(element['id']), highway
+ print(' '+70*'-')
+ print(' way', element['id'], type(element['id']), highway)
edges_osm[str(element['id'])] = ROADCLASSES.get(highway, Road)(element, self)
- print ' done with way', element['id'], id(self.edges_osm[str(element['id'])])
+ print(' done with way', element['id'], id(self.edges_osm[str(element['id'])]))
if element['type'] == 'node':
nodes_osm[element['id']] = element.get('tags', {})
- print ' import_osmdata:done'
+ print(' import_osmdata:done')
# def get_id_edge_sumo(self, osmid):
# idmap = self._map_id_edge_sumo_to_doubles
@@ -2855,7 +2856,7 @@ def import_osmdata(self, osmdata):
def get_edgenumber(self, osmid_dir):
idmap = self._map_id_edge_sumo_to_doubles
- if idmap.has_key(osmid_dir):
+ if osmid_dir in idmap:
idmap[osmid_dir] += 1
else:
idmap[osmid_dir] = 0
@@ -2879,13 +2880,13 @@ def get_id_edge_osm_from_id_sumo(self, id_sumo):
def is_edge_eligible(self, id_osm, id_fromnode_sumo, id_tonode_sumo):
# print 'is_edge_eligible',id_osm,type(id_osm),id_fromnode_sumo, id_tonode_sumo,self.edges_osm.has_key(id_osm),self._edgelookup.has_key(id_osm)
- if not self.edges_osm.has_key(id_osm):
+ if id_osm not in self.edges_osm:
# for some reason, nx network has edges that are not in jason
return False
edgelookup = self._edgelookup
- if edgelookup.has_key(id_osm):
+ if id_osm in edgelookup:
# is reverse already in database
# print ' check',edgelookup[id_osm], (id_tonode_sumo, id_fromnode_sumo) in edgelookup[id_osm]
edgelookup[id_osm].add((id_fromnode_sumo, id_tonode_sumo))
@@ -2907,7 +2908,7 @@ def make_segment_edge_map(self):
n_edges = len(polylines)
inds = np.arange(n_edges)
#ids = inds+1
- print 'make_linevertices', n_edges
+ print('make_linevertices', n_edges)
linevertices = np.zeros((0, 2, 3), np.float32)
vertexinds = np.zeros((0, 2), np.int32)
@@ -2931,7 +2932,7 @@ def make_segment_edge_map(self):
# print ' =======',n_seg#,polyline
if n_seg > 1:
- polyvinds = range(n_seg)
+ polyvinds = list(range(n_seg))
# print ' polyvinds\n',polyvinds
vi = np.zeros((2*n_seg-2), np.int32)
vi[0] = polyvinds[0]
@@ -3001,7 +3002,7 @@ def get_closest_edge_dist(self, p, ind_shape, n_best=0, d_min=0.5, alpha_min=1.0
elif d_max is None:
dists2_min = np.zeros(n_best, dtype=np.float32)
inds_min = np.zeros(n_best, dtype=np.int)
- for i in xrange(n_best):
+ for i in range(n_best):
ind = np.argmin(d2)
inds_min[i] = ind
dists2_min[i] = d2[ind]
@@ -3024,7 +3025,7 @@ def get_closest_edge_dist(self, p, ind_shape, n_best=0, d_min=0.5, alpha_min=1.0
return self._edgeinds[inds_min], np.sqrt(dists2_min), angles[inds_min]
def configure_sidewalks(self):
- print 'configure_sidewalks'
+ print('configure_sidewalks')
nodes = self._net.nodes
#are_remove_sidewalk = np.zeros(len(self._are_edge_valid), dtype = np.int32)
@@ -3044,11 +3045,11 @@ def configure_sidewalks(self):
for ind, id_edge_osm, shape, id_fromnode, id_tonode in zip(np.arange(len(ids_edge_osm)), ids_edge_osm, self._edgeshapes, ids_fromnode, ids_tonode):
road = edges_osm[id_edge_osm]
# if road.is_roundabout():# & (len(shape)>2):
- print ' check edge id_edge_osm', ids_edge_sumo[ind], 'no cycleped', (road.highway not in ['cycleway', 'path', 'pedestrian', 'stairs', 'steps', 'platform']), 'has sidewalk', (road.has_sidewalks(False) | road.has_sidewalks(True))
+ print(' check edge id_edge_osm', ids_edge_sumo[ind], 'no cycleped', (road.highway not in ['cycleway', 'path', 'pedestrian', 'stairs', 'steps', 'platform']), 'has sidewalk', (road.has_sidewalks(False) | road.has_sidewalks(True)))
# if (road.has_sidewalks(False)|road.has_sidewalks(True))\
# &(road.highway not in ['cycleway','path','pedestrian','stairs','steps','platform']):
if 1: # (road.highway not in ['path','pedestrian','stairs','steps','platform','footway']):
- print ' add_edge', ids_edge_sumo[ind], 'id_fromnode', id_fromnode, 'id_tonode', id_tonode, 'ind', ind
+ print(' add_edge', ids_edge_sumo[ind], 'id_fromnode', id_fromnode, 'id_tonode', id_tonode, 'ind', ind)
shapearray = np.array(shape, dtype=np.float32)
delta_out = shapearray[1]-shapearray[0]
@@ -3066,13 +3067,13 @@ def configure_sidewalks(self):
#digraph.add_edge(id_fromnode, id_tonode )
# print ' graph.nodes()',graph.nodes()
- for id_fromnode, tonodes in digraph.adj.items():
- print ' investigate id_fromnode', id_fromnode
+ for id_fromnode, tonodes in list(digraph.adj.items()):
+ print(' investigate id_fromnode', id_fromnode)
# dictionary with id_nnode as key and outgoing angle as value
# if id_nnode is negative then the direction if from
# incoming edge from node -id_nnode
directiondata = []
- for id_tonode, edge in tonodes.items():
+ for id_tonode, edge in list(tonodes.items()):
# print ' id_tonode',id_tonode
directiondata.append((edge['angle_out'], id_tonode, edge['id_edge_sumo']))
@@ -3085,7 +3086,7 @@ def configure_sidewalks(self):
node_to_dirind = OrderedDict()
i = 0
for angle, id_node, id_edge_sumo in directiondata:
- print ' ', i, 'id_node', id_node, 'angle', angle, 'id_edge_sumo', id_edge_sumo
+ print(' ', i, 'id_node', id_node, 'angle', angle, 'id_edge_sumo', id_edge_sumo)
dirind_to_node[i] = id_node
node_to_dirind[id_node] = i
i += 1
@@ -3097,8 +3098,8 @@ def configure_sidewalks(self):
for id_node in list(digraph.nodes_iter()):
node = digraph.node[id_node]
- print '\n find loops for node', id_node # ,node['dirind_to_node']
- for ind, id_nbnode in node['dirind_to_node'].iteritems():
+ print('\n find loops for node', id_node) # ,node['dirind_to_node']
+ for ind, id_nbnode in node['dirind_to_node'].items():
if id_nbnode < 0:
# incoming
@@ -3126,7 +3127,7 @@ def configure_sidewalks(self):
are_remove_sidewalk[id_sumo] = 1 # remove sidewalk from left
else:
- if are_remove_sidewalk.has_key(id_sumo):
+ if id_sumo in are_remove_sidewalk:
pass
# if are_remove_sidewalk[id_sumo] == 1:
# # let remove from left
@@ -3137,10 +3138,10 @@ def configure_sidewalks(self):
else:
are_remove_sidewalk[id_sumo] = 2 # remove sidewalk from right
- print ' found edge', id_sumo, id_fromnode, id_tonone, id_node, 'is_remove_sidewalk', are_remove_sidewalk[id_sumo]
+ print(' found edge', id_sumo, id_fromnode, id_tonone, id_node, 'is_remove_sidewalk', are_remove_sidewalk[id_sumo])
def configure_roundabouts(self):
- print 'configure_roundabouts'
+ print('configure_roundabouts')
nodes = self._net.nodes
roundabouts = []
edges_osm = self.edges_osm
@@ -3213,13 +3214,13 @@ def get_id_osm_maindir(self, id_osm):
return id_osm
def check_consistency(self):
- print 'check_consistency'
+ print('check_consistency')
nodelookup = {}
for ind, id_fromnode, id_tonode, id_edge_sumo in zip(np.arange(len(self._ids_edge_sumo)), self._ids_fromnode, self._ids_tonode, self._ids_edge_sumo):
ids_fromtonode = (id_fromnode, id_tonode)
- if nodelookup.has_key(ids_fromtonode):
- print ' WARNING: %s double edge to %s detected' % (id_edge_sumo, nodelookup[ids_fromtonode]), 'from', id_fromnode, 'to', id_tonode, 'id_edge_sumo', id_edge_sumo, nodelookup[ids_fromtonode] == id_edge_sumo
+ if ids_fromtonode in nodelookup:
+ print(' WARNING: %s double edge to %s detected' % (id_edge_sumo, nodelookup[ids_fromtonode]), 'from', id_fromnode, 'to', id_tonode, 'id_edge_sumo', id_edge_sumo, nodelookup[ids_fromtonode] == id_edge_sumo)
if nodelookup[ids_fromtonode] == id_edge_sumo:
# meand 2 edges with identical ID
self._are_edge_valid[ind] = False
@@ -3247,7 +3248,7 @@ def configure_footpath(self):
alpha_crit = 30.0*np.pi/180.0
alpha_crit_cross = 30.0*np.pi/180.0
- print 'configure_footpath alpha_crit', alpha_crit
+ print('configure_footpath alpha_crit', alpha_crit)
#self.id_mode = ID_MODE_PED
# highway=footway|path
#self.highway = self._osmattrs.get('highway','footway')
@@ -3258,7 +3259,7 @@ def configure_footpath(self):
road = edges_osm[id_edge_osm]
if road.highway in footpath_condig:
- print ' check edge', ids_edge_sumo[ind], road.footway, (road.get_osmattr('tunnel') != 'yes'), (length > dist_min_remove), length
+ print(' check edge', ids_edge_sumo[ind], road.footway, (road.get_osmattr('tunnel') != 'yes'), (length > dist_min_remove), length)
#(road.footway != 'crossing') (road.footway != 'sidewalk')
ids_osm_main = set()
is_remove = True
@@ -3273,16 +3274,16 @@ def configure_footpath(self):
inds_edge_main, dists, angles = self.get_closest_edge_dist(
point, ind, n_best=20, d_max=dist_min_detect)
#matchdata = {}
- print ' check sidewalk point (%d/%d)' % (i+1, len(shape))
+ print(' check sidewalk point (%d/%d)' % (i+1, len(shape)))
for ind_edge_main, dist, angle in zip(inds_edge_main, dists, angles):
id_edge_osm_main, is_opp, nr = self.get_id_edge_osm_from_id_sumo(
ids_edge_sumo[ind_edge_main])
road_main = edges_osm[id_edge_osm_main]
prio = road_main.get_priority(is_opp)
- print ' check medge %s d=%.1fm al=%.1f' % (ids_edge_sumo[ind_edge_main], dist, angle/np.pi*180), prio, road_main.highway, (angle < alpha_crit), (dist < 2*dist_min_detect), (road_main.highway not in footpath_nomerge)
+ print(' check medge %s d=%.1fm al=%.1f' % (ids_edge_sumo[ind_edge_main], dist, angle/np.pi*180), prio, road_main.highway, (angle < alpha_crit), (dist < 2*dist_min_detect), (road_main.highway not in footpath_nomerge))
# print ' p1',shape[i-1],'pc',point,'p2',shape[i]
if (angle < 2*alpha_crit) & (dist < dist_min_detect) & (road_main.highway not in footpath_nomerge):
- print ' add edge main edge %s' % ids_edge_sumo[ind_edge_main], (id_edge_osm_main, is_opp)
+ print(' add edge main edge %s' % ids_edge_sumo[ind_edge_main], (id_edge_osm_main, is_opp))
ids_osm_main.add((id_edge_osm_main, is_opp))
is_foundmatch = True
break
@@ -3299,16 +3300,16 @@ def configure_footpath(self):
is_foundmatch = False
inds_edge_main, dists, angles = self.get_closest_edge_dist(
point, ind, n_best=20, d_max=dist_min_detect)
- print ' check footpath point (%d/%d)' % (i+1, len(shape))
+ print(' check footpath point (%d/%d)' % (i+1, len(shape)))
for ind_edge_main, dist, angle in zip(inds_edge_main, dists, angles):
id_edge_osm_main, is_opp, nr = self.get_id_edge_osm_from_id_sumo(
ids_edge_sumo[ind_edge_main])
road_main = edges_osm[id_edge_osm_main]
prio = road_main.get_priority(is_opp)
- print ' check medge %s d=%.1fm al=%.1f,%.2f' % (ids_edge_sumo[ind_edge_main], dist, angle/np.pi*180, angle), prio, road_main.highway, (angle < alpha_crit), (dist < dist_min_detect), (road_main.highway not in footpath_nomerge)
+ print(' check medge %s d=%.1fm al=%.1f,%.2f' % (ids_edge_sumo[ind_edge_main], dist, angle/np.pi*180, angle), prio, road_main.highway, (angle < alpha_crit), (dist < dist_min_detect), (road_main.highway not in footpath_nomerge))
# print ' p1',shape[i-1],'pc',point,'p2',shape[i]
if (prio <= prio_max) & (angle < alpha_crit) & (dist < dist_min_detect) & (road_main.highway not in footpath_nomerge):
- print ' add edge main edge %s' % ids_edge_sumo[ind_edge_main], (id_edge_osm_main, is_opp)
+ print(' add edge main edge %s' % ids_edge_sumo[ind_edge_main], (id_edge_osm_main, is_opp))
ids_osm_main.add((id_edge_osm_main, is_opp))
is_foundmatch = True
break
@@ -3329,17 +3330,17 @@ def configure_footpath(self):
is_foundmatch = False
inds_edge_main, dists, angles = self.get_closest_edge_dist(
point, ind, n_best=20, d_max=dist_min_detect_cross)
- print ' check crossing point (%d/%d)' % (i+1, len(shape))
+ print(' check crossing point (%d/%d)' % (i+1, len(shape)))
for ind_edge_main, dist, angle in zip(inds_edge_main, dists, angles):
id_edge_osm_main, is_opp, nr = self.get_id_edge_osm_from_id_sumo(
ids_edge_sumo[ind_edge_main])
road_main = edges_osm[id_edge_osm_main]
prio = road_main.get_priority(is_opp)
- print ' check medge %s d=%.1fm al=%.1f' % (ids_edge_sumo[ind_edge_main], dist, angle/np.pi*180), prio, road_main.highway, (angle < alpha_crit_cross), (dist < dist_min_detect_cross), (road_main.highway in footpath_merge_cross)
+ print(' check medge %s d=%.1fm al=%.1f' % (ids_edge_sumo[ind_edge_main], dist, angle/np.pi*180), prio, road_main.highway, (angle < alpha_crit_cross), (dist < dist_min_detect_cross), (road_main.highway in footpath_merge_cross))
# print ' p1',shape[i-1],'pc',point,'p2',shape[i]
# if (prio<=prio_max)&(((angle '-': # it is not an opposite edge
road = edges_osm[id_edge_osm]
- print ' configure way id_edge_osm', id_edge_osm, id_sumo, are_remove_sidewalk.get(id_sumo, 0)
+ print(' configure way id_edge_osm', id_edge_osm, id_sumo, are_remove_sidewalk.get(id_sumo, 0))
road.configure_edge(id_edge, net, is_remove_sidewalk=are_remove_sidewalk.get(id_sumo, 0))
#id_edge_opp = self.get_id_edge_opp
id_sumo_opp = '-'+id_sumo
if edges.ids_sumo.has_index(id_sumo_opp):
- print ' configure opposite way id_edge_osm', id_edge_osm, id_sumo_opp, are_remove_sidewalk.get(id_sumo_opp, 0)
+ print(' configure opposite way id_edge_osm', id_edge_osm, id_sumo_opp, are_remove_sidewalk.get(id_sumo_opp, 0))
road.configure_edge(edges.ids_sumo.get_id_from_index(id_sumo_opp),
net, is_opp=True,
is_remove_sidewalk=are_remove_sidewalk.get(id_sumo_opp, 0))
diff --git a/tools/contributed/sumopy/coremodules/network/osmnx_import.py b/tools/contributed/sumopy/coremodules/network/osmnx_import.py
index fef64244de73..d1f7b124c97a 100644
--- a/tools/contributed/sumopy/coremodules/network/osmnx_import.py
+++ b/tools/contributed/sumopy/coremodules/network/osmnx_import.py
@@ -26,7 +26,7 @@
import agilepy.lib_base.xmlman as xm
-from netconvert import *
+from .netconvert import *
from coremodules.misc.shapeformat import guess_utm_from_coord
@@ -36,9 +36,9 @@ def import_nx(graphx, net, projparams=''):
"""
for id_node_sumo, nbrsdict in graphx.adjacency():
- print ' id_node_sumo', id_node_sumo
- for nbr, eattr in nbrsdict.items():
- print ' nbr, eattr', nbr, eattr
+ print(' id_node_sumo', id_node_sumo)
+ for nbr, eattr in list(nbrsdict.items()):
+ print(' nbr, eattr', nbr, eattr)
if projparams == "":
projparams_target = guess_utm_from_coord()
@@ -51,7 +51,7 @@ def __init__(self, scenario,
info='Import of network imported with the help of osmnx.',
logger=None, **kwargs):
- print 'OxImporter.__init__'
+ print('OxImporter.__init__')
self._init_common(ident,
parent=scenario,
@@ -96,7 +96,7 @@ def get_scenario(self):
return self.parent
def do(self):
- print self.ident+'.do'
+ print(self.ident+'.do')
net = self.get_scenario().net
projparams_target = net.get_projparams()
diff --git a/tools/contributed/sumopy/coremodules/network/publictransportnet.py b/tools/contributed/sumopy/coremodules/network/publictransportnet.py
index c6a31467101d..144086cb44fd 100644
--- a/tools/contributed/sumopy/coremodules/network/publictransportnet.py
+++ b/tools/contributed/sumopy/coremodules/network/publictransportnet.py
@@ -42,8 +42,8 @@
except:
pyproj = None
- print 'Some of the functions cannot be executed because module pypro or mpl_toolkits.basemap is missing.'
- print 'Please install these modules if you want to use it.'
+ print('Some of the functions cannot be executed because module pypro or mpl_toolkits.basemap is missing.')
+ print('Please install these modules if you want to use it.')
# print __doc__
@@ -52,7 +52,7 @@
class StopAccessProvider(Process):
def __init__(self, net, logger=None, **kwargs):
- print 'StopAccessProvider.__init__'
+ print('StopAccessProvider.__init__')
self._init_common('stopaccessprovider',
parent=net,
name='Stop access provider',
@@ -75,7 +75,7 @@ def init_accessprovider(self, **kwargs):
#self.ids_modes_tocomplete = set([MODES["pedestrian"], MODES["delivery"], MODES["bus"]])
def do(self):
- print 'StopAccessProvider.do'
+ print('StopAccessProvider.do')
self.provide_access()
@@ -107,21 +107,21 @@ def provide_access(self):
# print ' Check access at stop %s lane %d. al='%(id_stop,id_lane)
if lanes.get_accesslevel([id_lane], id_mode_ped) == -1:
# no pedaccess
- print ' add ped access at stop %s lane %d, ID edge SUMO "%s".' % (id_stop, id_lane, edges.ids_sumo[id_edge])
+ print(' add ped access at stop %s lane %d, ID edge SUMO "%s".' % (id_stop, id_lane, edges.ids_sumo[id_edge]))
lanes.add_access(id_lane, id_mode_ped)
n_add_access += 1
if self.is_bikeaccess:
if lanes.get_accesslevel([id_lane], id_mode_bike) == -1:
- print ' add bike access at stop %s lane %d, ID edge SUMO "%s".' % (id_stop, id_lane, edges.ids_sumo[id_edge])
+ print(' add bike access at stop %s lane %d, ID edge SUMO "%s".' % (id_stop, id_lane, edges.ids_sumo[id_edge]))
lanes.add_access(id_lane, id_mode_bike)
n_add_access += 1
else:
- print 'WARNING: stop %s at edge %d, SUMO ID %s with without access lane.' % (id_stop, id_edge, edges.ids_sumo[id_edge])
+ print('WARNING: stop %s at edge %d, SUMO ID %s with without access lane.' % (id_stop, id_edge, edges.ids_sumo[id_edge]))
# return False
- print ' Added access to %d stops' % n_add_access
+ print(' Added access to %d stops' % n_add_access)
return True
@@ -346,7 +346,7 @@ def export_sumoxml(self, filepath=None, encoding='UTF-8'):
"""
Export stops to SUMO stop xml file.
"""
- print 'export_sumoxml', filepath, len(self)
+ print('export_sumoxml', filepath, len(self))
if len(self) == 0:
return None
@@ -356,7 +356,7 @@ def export_sumoxml(self, filepath=None, encoding='UTF-8'):
try:
fd = open(filepath, 'w')
except:
- print 'WARNING in write_obj_to_xml: could not open', filepath
+ print('WARNING in write_obj_to_xml: could not open', filepath)
return False
#xmltag, xmltag_item, attrname_id = self.xmltag
fd.write('\n' % encoding)
@@ -375,7 +375,7 @@ def import_sumostops(self, filepath=None, logger=None, is_remove_xmlfiles=False)
if filepath is None:
filepath = self.get_stopfilepath()
- print 'import_sumostops %s ' % (filepath,)
+ print('import_sumostops %s ' % (filepath,))
fd = open(filepath, 'r')
@@ -388,7 +388,7 @@ def import_sumostops(self, filepath=None, logger=None, is_remove_xmlfiles=False)
os.remove(filepath)
except KeyError:
- print >> sys.stderr, "Error: Problems with reading file %s" % filepath
+ print("Error: Problems with reading file %s" % filepath, file=sys.stderr)
raise
def update_centroids(self):
@@ -431,12 +431,12 @@ def startElement(self, name, attrs):
id_lane = self._get_id_lane_from_sumoinfo(id_edge_sumo, int(ind_lane_str.strip()))
if id_lane != -1:
- if attrs.has_key('startPos'):
+ if 'startPos' in attrs:
pos_from = float(attrs['startPos'])
else:
pos_from = None
- if attrs.has_key('endPos'):
+ if 'endPos' in attrs:
pos_to = float(attrs['endPos'])
else:
pos_to = None
@@ -462,4 +462,4 @@ def startElement(self, name, attrs):
)
else:
- print 'WARNING in StopReader: stop %s has non-existant lane %s' % (id_stop, attrs['lane'])
+ print('WARNING in StopReader: stop %s has non-existant lane %s' % (id_stop, attrs['lane']))
diff --git a/tools/contributed/sumopy/coremodules/network/publictransportnet_wxgui.py b/tools/contributed/sumopy/coremodules/network/publictransportnet_wxgui.py
index 3b2bfe46c342..b5379d0ce3dd 100644
--- a/tools/contributed/sumopy/coremodules/network/publictransportnet_wxgui.py
+++ b/tools/contributed/sumopy/coremodules/network/publictransportnet_wxgui.py
@@ -24,8 +24,8 @@
from agilepy.lib_wx.objpanel import ObjPanel
from agilepy.lib_base.processes import Process
from agilepy.lib_wx.processdialog import ProcessDialog
-from network import SumoIdsConf, MODES
-import publictransportnet as pt
+from .network import SumoIdsConf, MODES
+from . import publictransportnet as pt
class PtStopDrawings(Rectangles):
@@ -300,7 +300,7 @@ def on_import_ptstops(self, event=None):
# Finally, if the directory is changed in the process of getting files, this
# dialog is set up to change the current working directory to the path chosen.
defaultfilepath = self._net.ptstops.get_stopfilepath()
- print ' defaultfilepath', defaultfilepath
+ print(' defaultfilepath', defaultfilepath)
dlg = wx.FileDialog(
self._mainframe, message="Open stops XML file",
@@ -357,11 +357,11 @@ def on_gtfsstop_importer(self, event=None):
# print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL
# print ' status =',dlg.get_status()
if dlg.get_status() != 'success': # val == wx.ID_CANCEL:
- print ">>>>>>>>>Unsuccessful\n"
+ print(">>>>>>>>>Unsuccessful\n")
dlg.Destroy()
if dlg.get_status() == 'success':
- print ">>>>>>>>>successful\n"
+ print(">>>>>>>>>successful\n")
# apply current widget values to scenario instance
dlg.apply()
dlg.Destroy()
diff --git a/tools/contributed/sumopy/coremodules/network/routing.py b/tools/contributed/sumopy/coremodules/network/routing.py
index d0cd6a17e389..2720861a8ea4 100644
--- a/tools/contributed/sumopy/coremodules/network/routing.py
+++ b/tools/contributed/sumopy/coremodules/network/routing.py
@@ -41,7 +41,7 @@ def __init__(self):
def smallest(self):
'''Find smallest item after removing deleted items from heap.'''
if len(self) == 0:
- raise IndexError, "smallest of empty priorityDictionary"
+ raise IndexError("smallest of empty priorityDictionary")
heap = self.__heap
while heap[0][1] not in self or self[heap[0][1]] != heap[0][0]:
lastItem = heap.pop()
@@ -74,7 +74,7 @@ def __setitem__(self, key, val):
dict.__setitem__(self, key, val)
heap = self.__heap
if len(heap) > 2 * len(self):
- self.__heap = [(v, k) for k, v in self.iteritems()]
+ self.__heap = [(v, k) for k, v in self.items()]
self.__heap.sort() # builtin sort likely faster than O(n) heapify
else:
newPair = (val, key)
@@ -92,7 +92,7 @@ def setdefault(self, key, val):
return self[key]
def update(self, other):
- for key in other.keys():
+ for key in list(other.keys()):
self[key] = other[key]
@@ -150,7 +150,7 @@ def edgedijkstra_backwards(id_edge_start, cost_limit,
# est.dist. of non-final vert.
if np.isnan(weights[id_edge_start]):
- print ' no access id_edge_start, weights', id_edge_start, weights[id_edge_start]
+ print(' no access id_edge_start, weights', id_edge_start, weights[id_edge_start])
return ([], {}, {})
Q = priorityDictionary()
@@ -166,9 +166,9 @@ def edgedijkstra_backwards(id_edge_start, cost_limit,
# print ' toedge',e,'ids_bedge',bstar[e]
# print ' D=',D
# print ' Q=',Q
- if not bstar.has_key(e):
- print 'WARNING in edgedijkstra: bstar has no edge', e
- print 'routes = \n', P
+ if e not in bstar:
+ print('WARNING in edgedijkstra: bstar has no edge', e)
+ print('routes = \n', P)
return ([], None, P)
for id_edge in bstar[e]:
@@ -183,7 +183,7 @@ def edgedijkstra_backwards(id_edge_start, cost_limit,
newstate += 'Q|'
- print ' id_bedge', id_edge, 'w=%.2f,w_tot=%.2f' % (weights[id_edge], weight_tot), weights[id_edge] >= 0, D[e] + weights[id_edge] < cost_limit, id_edge not in D, (id_edge not in Q or weight_tot < Q[id_edge]), newstate
+ print(' id_bedge', id_edge, 'w=%.2f,w_tot=%.2f' % (weights[id_edge], weight_tot), weights[id_edge] >= 0, D[e] + weights[id_edge] < cost_limit, id_edge not in D, (id_edge not in Q or weight_tot < Q[id_edge]), newstate)
if not np.isnan(weights[id_edge]): # edge accessible?
weight_tot = D[e] + weights[id_edge]
@@ -213,8 +213,8 @@ def get_edges_orig_from_tree(id_edge_dest, tree):
ids_orig = []
ids_edge = [id_edge_dest]
is_cont = True
- ids_edge_from = np.array(tree.keys(), dtype=np.int32)
- ids_edge_to = np.array(tree.values(), dtype=np.int32)
+ ids_edge_from = np.array(list(tree.keys()), dtype=np.int32)
+ ids_edge_to = np.array(list(tree.values()), dtype=np.int32)
if id_edge_dest not in ids_edge_to:
return ids_orig
while len(ids_edge) > 0:
@@ -252,7 +252,7 @@ def edgedijkstra(id_edge_start, ids_edge_target=None,
# est.dist. of non-final vert.
if np.isnan(weights[id_edge_start]):
- print ' WARNING in edgedijkstra: no access id_edge_start, weights', id_edge_start, weights[id_edge_start]
+ print(' WARNING in edgedijkstra: no access id_edge_start, weights', id_edge_start, weights[id_edge_start])
return ({}, {})
Q = priorityDictionary()
@@ -265,9 +265,9 @@ def edgedijkstra(id_edge_start, ids_edge_target=None,
ids_target.discard(e)
if len(ids_target) == 0:
return (D, P)
- if not fstar.has_key(e):
- print 'WARNING in edgedijkstra: fstar has no edge', e
- print 'routes = \n', P
+ if e not in fstar:
+ print('WARNING in edgedijkstra: fstar has no edge', e)
+ print('routes = \n', P)
return (None, P)
for id_edge in fstar[e]:
if not np.isnan(weights[id_edge]): # edge accessible?
@@ -292,7 +292,7 @@ def get_mincostroute_edge2edges(id_rootedge, ids_targetedge, D=None, P=None,
routes = []
costs = []
for id_targetedge in ids_targetedge:
- if P.has_key(id_targetedge):
+ if id_targetedge in P:
route = [id_targetedge]
e = id_targetedge
while e != id_rootedge:
@@ -324,7 +324,7 @@ def get_mincostroute_edge2edge(id_rootedge, id_targetedge, D=None, P=None,
weights=weights, fstar=fstar)
route = [id_targetedge]
- if not P.has_key(id_targetedge):
+ if id_targetedge not in P:
return 0.0, []
e = id_targetedge
@@ -347,7 +347,7 @@ def get_mincostroute_node2node(id_rootnode, id_targetnode, D, P, edges):
# print 'getMinCostRoute node_start=%s, edge_end =%s node_end=%s'%(rootnode.getID(),P[targetnode].getID(),targetnode.getID())
id_node = id_targetnode
route = []
- if not P.has_key(id_targetnode):
+ if id_targetnode not in P:
return 0.0, []
while id_node != id_rootnode:
@@ -615,11 +615,11 @@ def do(self):
# print 'SumonetImporter.do',cml
self.run_cml(cml)
if self.status == 'success':
- print ' Routing done.'
+ print(' Routing done.')
if os.path.isfile(self.outfilepath):
# print ' outfile exists, start importing routes'
if self.is_update_current_routes:
- print ' update current routes'
+ print(' update current routes')
self._trips.import_routes_xml(self.outfilepath,
is_clear_trips=False,
is_generate_ids=False,
@@ -627,7 +627,7 @@ def do(self):
is_add=False
)
else:
- print ' create route alternatives'
+ print(' create route alternatives')
self._trips.import_routes_xml(self.outfilepath,
is_clear_trips=False,
is_generate_ids=True,
@@ -645,7 +645,7 @@ def __init__(self, net, trips,
is_export_net=True,
logger=None,
**kwargs):
- print 'DuaRouter.__init__ net, trips', net, trips
+ print('DuaRouter.__init__ net, trips', net, trips)
self.init_tripsrouter('duarouter', net, # net becomes parent
trips,
outfilepath=outfilepath,
@@ -662,7 +662,7 @@ def __init__(self, net, trips,
else:
self.is_export_trips = False
- print ' tripfilepaths', tripfilepaths
+ print(' tripfilepaths', tripfilepaths)
if tripfilepaths is not None:
self.add_option('tripfilepaths', tripfilepaths,
groupnames=['_private'],
@@ -1075,7 +1075,7 @@ def import_results(self, results=None):
"""
Imports simulation resuts into results object.
"""
- print 'import_results of marouter'
+ print('import_results of marouter')
if results is None:
results = self._results
diff --git a/tools/contributed/sumopy/coremodules/network/wxgui.py b/tools/contributed/sumopy/coremodules/network/wxgui.py
index ac79d297b8cf..ae2999ba8d1b 100644
--- a/tools/contributed/sumopy/coremodules/network/wxgui.py
+++ b/tools/contributed/sumopy/coremodules/network/wxgui.py
@@ -23,16 +23,16 @@
from agilepy.lib_wx.processdialog import ProcessDialog
-import network
-import routing
-import netgenerate
-import netconvert
-import networktools
-import networkxtools # IS_NX = True if available
+from . import network
+from . import routing
+from . import netgenerate
+from . import netconvert
+from . import networktools
+from . import networkxtools # IS_NX = True if available
-from publictransportnet_wxgui import PtWxGuiMixin
-from network_editor import *
+from .publictransportnet_wxgui import PtWxGuiMixin
+from .network_editor import *
from coremodules.misc import shapeformat
from coremodules.misc.matplottools import *
@@ -399,14 +399,14 @@ def on_plot_network(self, event=None):
def on_test_routing(self, event=None):
D, P = routing.dijkstra(54, self._net.nodes, self._net.edges, set([42, 82]))
cost, route = routing.get_mincostroute_node2node(54, 42, D, P, self._net.edges)
- print ' route:', route
- print ' cost', cost
- print ' firstnode, lastnode', self._net.edges.ids_fromnode[route[0]], self._net.edges.ids_tonode[route[-1]]
+ print(' route:', route)
+ print(' cost', cost)
+ print(' firstnode, lastnode', self._net.edges.ids_fromnode[route[0]], self._net.edges.ids_tonode[route[-1]])
D, P = routing.edgedijkstra(29, self._net.nodes, self._net.edges, set([106, 82]))
cost, route = routing.get_mincostroute_edge2edge(29, 82, D, P)
- print ' route:', route
- print ' cost', cost
+ print(' route:', route)
+ print(' cost', cost)
# print ' firstnode, lastnode',self._net.edges.ids_fromnode[route[0]],self._net.edges.ids_tonode[route[-1]]
def on_clean_codes(self, event=None):
@@ -804,7 +804,7 @@ def on_generate_tls(self, event=None):
self._mainframe.refresh_moduleguis()
def on_export_sumonet(self, event=None):
- print 'on_export_sumonet'
+ print('on_export_sumonet')
if self._net.parent is not None:
rootname = self._net.parent.get_rootfilename()
rootdirpath = self._net.parent.get_workdirpath()
@@ -854,7 +854,7 @@ def on_nodes_to_shapefile(self, event=None):
"""
Export Network nodes data to shape file.
"""
- print 'on_nodes_to_shapefile'
+ print('on_nodes_to_shapefile')
dirpath = self._net.parent.get_workdirpath()
defaultFile = self._net.parent.get_rootfilename()+'.nodes.shp'
diff --git a/tools/contributed/sumopy/coremodules/scenario/__init__.py b/tools/contributed/sumopy/coremodules/scenario/__init__.py
index cab987aa8f9c..02fdf630fcec 100644
--- a/tools/contributed/sumopy/coremodules/scenario/__init__.py
+++ b/tools/contributed/sumopy/coremodules/scenario/__init__.py
@@ -18,12 +18,12 @@
__version__ = "0.0"
-print 'init', __name__
+print('init', __name__)
def get_wxgui():
# try:
- from wxgui import WxGui
+ from .wxgui import WxGui
return WxGui(__name__)
# except:
# return None
diff --git a/tools/contributed/sumopy/coremodules/scenario/scenario.py b/tools/contributed/sumopy/coremodules/scenario/scenario.py
index 596ea76593dc..e2765f110ecd 100644
--- a/tools/contributed/sumopy/coremodules/scenario/scenario.py
+++ b/tools/contributed/sumopy/coremodules/scenario/scenario.py
@@ -222,7 +222,7 @@ def __init__(self, rootname, name_scenario='myscenario',
self._init_attributes()
def _init_attributes(self):
- print 'Scenario._init_attributes' # ,dir(self)
+ print('Scenario._init_attributes') # ,dir(self)
attrsman = self.get_attrsman()
self.simulation = attrsman.add(cm.ObjConf(simulation.Simulation(self)))
@@ -288,7 +288,7 @@ def import_xml(self, is_clean_nodes=False):
try:
self.demand.import_xml(self.get_rootfilename(), self.get_workdirpath())
except:
- print 'WARNING: import of demand data failed. Please check for inconsistency with trip/route and network edge IDs.'
+ print('WARNING: import of demand data failed. Please check for inconsistency with trip/route and network edge IDs.')
def update_netoffset(self, deltaoffset):
"""
diff --git a/tools/contributed/sumopy/coremodules/scenario/wxgui.py b/tools/contributed/sumopy/coremodules/scenario/wxgui.py
index 0125da82f08e..2f83fa5a710b 100644
--- a/tools/contributed/sumopy/coremodules/scenario/wxgui.py
+++ b/tools/contributed/sumopy/coremodules/scenario/wxgui.py
@@ -25,7 +25,7 @@
from agilepy.lib_wx.modulegui import ModuleGui
from agilepy.lib_wx.processdialog import ProcessDialog
-import scenario
+from . import scenario
class WxGui(ModuleGui):
diff --git a/tools/contributed/sumopy/coremodules/simulation/__init__.py b/tools/contributed/sumopy/coremodules/simulation/__init__.py
index cab987aa8f9c..02fdf630fcec 100644
--- a/tools/contributed/sumopy/coremodules/simulation/__init__.py
+++ b/tools/contributed/sumopy/coremodules/simulation/__init__.py
@@ -18,12 +18,12 @@
__version__ = "0.0"
-print 'init', __name__
+print('init', __name__)
def get_wxgui():
# try:
- from wxgui import WxGui
+ from .wxgui import WxGui
return WxGui(__name__)
# except:
# return None
diff --git a/tools/contributed/sumopy/coremodules/simulation/result_oglviewer.py b/tools/contributed/sumopy/coremodules/simulation/result_oglviewer.py
index 5457d346121b..89fc189bcf7a 100644
--- a/tools/contributed/sumopy/coremodules/simulation/result_oglviewer.py
+++ b/tools/contributed/sumopy/coremodules/simulation/result_oglviewer.py
@@ -323,7 +323,7 @@ def set_results(self, results):
edgeresults = results.edgeresults
attrnames_edgeresults = OrderedDict()
edgeresultattrconfigs = edgeresults.get_group_attrs('results')
- edgeresultattrnames = edgeresultattrconfigs.keys()
+ edgeresultattrnames = list(edgeresultattrconfigs.keys())
# edgeresultattrnames.sort()
for attrname in edgeresultattrnames:
attrconfig = edgeresultattrconfigs[attrname]
@@ -728,7 +728,7 @@ def configure(self, attrname,
Called by tool.
"""
self.resultsattr = getattr(self._edgeresults, attrname)
- print 'configure', self.resultsattr.attrname, is_widthvalue, is_colorvalue
+ print('configure', self.resultsattr.attrname, is_widthvalue, is_colorvalue)
# used for normalization
if len(self.resultsattr.get_value()) == 0:
return
@@ -796,7 +796,7 @@ def __init__(self,
is_menu=False, # create menu items
Debug=0,
):
- print 'Resultviewer.__init__ parent', parent
+ print('Resultviewer.__init__ parent', parent)
self._drawing = None
self.prefix_anim = 'anim_'
self.layer_anim = 1000.0
diff --git a/tools/contributed/sumopy/coremodules/simulation/results.py b/tools/contributed/sumopy/coremodules/simulation/results.py
index 78891b4ca6be..9edc4642c18a 100644
--- a/tools/contributed/sumopy/coremodules/simulation/results.py
+++ b/tools/contributed/sumopy/coremodules/simulation/results.py
@@ -303,43 +303,43 @@ def evaluate_results(self, sumo, datapaths):
elif routeresults.ids_ptline[trip] > 0:
mode = self._edges.parent.modes.names[self._trips.parent.vtypes.ids_mode[self._trips.parent.ptlines.ids_vtype[routeresults.ids_ptline[trip]]]]
else:
- print 'WARNING: there is a not considered route typology'
+ print('WARNING: there is a not considered route typology')
modes_tot.append(mode)
- print 'n route', len(modes_tot)
+ print('n route', len(modes_tot))
if len(modes_tot) != len(ids_edges):
- print 'WARNING: modes and ids_edges have a different length - total flow'
- print 'n car routes', len(modes_car)
+ print('WARNING: modes and ids_edges have a different length - total flow')
+ print('n car routes', len(modes_car))
if len(modes_car) != len(ids_edges_car):
- print 'WARNING: modes and ids_edges have a different length - car'
- print 'n bike routes', len(modes_bike)
+ print('WARNING: modes and ids_edges have a different length - car')
+ print('n bike routes', len(modes_bike))
if len(modes_bike) != len(ids_edges_bike):
- print 'WARNING: modes and ids_edges have a different length - bike'
- print 'n moto routes', len(modes_moto)
+ print('WARNING: modes and ids_edges have a different length - bike')
+ print('n moto routes', len(modes_moto))
if len(modes_moto) != len(ids_edges_moto):
- print 'WARNING: modes and ids_edges have a different length - moto'
- print 'n od routes', len(modes_od)
+ print('WARNING: modes and ids_edges have a different length - moto')
+ print('n od routes', len(modes_od))
if len(modes_od) != len(ids_edges_od):
- print 'WARNING: modes and ids_edges have a different length - od'
- print 'n od car routes', modes_od.count('passenger')
- print 'n od taxi routes', modes_od.count('taxi')
- print 'n od bike routes', modes_od.count('bicycle')
- print 'n od moto routes', modes_od.count('motorcycle')
- print 'n vp routes', len(modes_vp)
+ print('WARNING: modes and ids_edges have a different length - od')
+ print('n od car routes', modes_od.count('passenger'))
+ print('n od taxi routes', modes_od.count('taxi'))
+ print('n od bike routes', modes_od.count('bicycle'))
+ print('n od moto routes', modes_od.count('motorcycle'))
+ print('n vp routes', len(modes_vp))
if len(modes_vp) != len(ids_edges_vp):
- print 'WARNING: modes and ids_edges have a different length - vp'
- print 'n iauto routes', len(modes_iauto)
+ print('WARNING: modes and ids_edges have a different length - vp')
+ print('n iauto routes', len(modes_iauto))
if len(modes_iauto) != len(ids_edges_iauto):
- print 'WARNING: modes and ids_edges have a different length - iauto'
- print 'n ibike routes', len(modes_ibike)
+ print('WARNING: modes and ids_edges have a different length - iauto')
+ print('n ibike routes', len(modes_ibike))
if len(modes_ibike) != len(ids_edges_ibike):
- print 'WARNING: modes and ids_edges have a different length - ibike'
- print 'n imoto routes', len(modes_imoto)
+ print('WARNING: modes and ids_edges have a different length - ibike')
+ print('n imoto routes', len(modes_imoto))
if len(modes_imoto) != len(ids_edges_imoto):
- print 'WARNING: modes and ids_edges have a different length - imoto'
- print 'n pt routes', len(modes_ptline)
+ print('WARNING: modes and ids_edges have a different length - imoto')
+ print('n pt routes', len(modes_ptline))
if len(modes_ptline) != len(ids_edges_ptline):
- print 'WARNING: modes and ids_edges have a different length - bus'
+ print('WARNING: modes and ids_edges have a different length - bus')
ids_connections_tot, flows_tot = self.evaluate_connection_flows('tot', modes_tot, ids_edges)
self.add_rows(ids_connection=ids_connections_tot, total_flows=flows_tot)
@@ -389,7 +389,7 @@ def evaluate_connection_flows(self, ident, modes, routes):
the available maneuvers, between the connections allowed for the specific MODE.
Return both the traveled connections and the related flows
'''
- print 'analyzing', ident, 'routes'
+ print('analyzing', ident, 'routes')
edges = self._edges
lanes = edges.parent.lanes
connections = edges.parent.connections
@@ -451,9 +451,9 @@ def evaluate_connection_flows(self, ident, modes, routes):
connections_list.append(element)
if connections_list == []:
- print 'Warning: no connections between a couple of successive edges for mode', mode
- print 'ids_lane_from_all', ids_lane_from_all
- print 'ids_lane_to_all', ids_lane_to_all
+ print('Warning: no connections between a couple of successive edges for mode', mode)
+ print('ids_lane_from_all', ids_lane_from_all)
+ print('ids_lane_to_all', ids_lane_to_all)
n_wrong_connections += 1
if mode == 'motorcycle':
n_wrong_connections_moto += 1
@@ -477,7 +477,7 @@ def evaluate_connection_flows(self, ident, modes, routes):
elif mode == 'taxi':
keep_right = self._is_keep_right_taxi
else:
- print 'WARNING - Not recognized mode'
+ print('WARNING - Not recognized mode')
keep_right = True
n_good_connections += 1
@@ -495,8 +495,8 @@ def evaluate_connection_flows(self, ident, modes, routes):
ids_traveled_connections.append(connection)
connection_flows[connection] += 1.
# print ids_traveled_connections, connection_flows[ids_traveled_connections]
- print 'n_good_connections:', n_good_connections
- print 'n_wrong_connections:', n_wrong_connections
+ print('n_good_connections:', n_good_connections)
+ print('n_wrong_connections:', n_wrong_connections)
# print 'n_wrong_connections_moto:', n_wrong_connections_moto
# print 'n_wrong_connections_auto:', n_wrong_connections_auto
# print 'n_wrong_connections_bike:', n_wrong_connections_bike
@@ -595,7 +595,7 @@ def __init__(self, ident, parent, trips, edges, datapathkey='routesdatapath',
'default': 0.0, 'info': 'Arrival speed', 'groupnames': ['routedata']}),
])
- for attrname, kwargs in attrinfos.iteritems():
+ for attrname, kwargs in attrinfos.items():
self.add_resultattr(attrname, **kwargs)
# this is special for route info
@@ -611,7 +611,7 @@ def add_resultattr(self, attrname, **kwargs):
# default cannot be kwarg
default = kwargs['default']
del kwargs['default']
- if kwargs.has_key('groupnames'):
+ if 'groupnames' in kwargs:
kwargs['groupnames'].append('results')
else:
kwargs['groupnames'] = ['results']
@@ -628,7 +628,7 @@ def add_resultattr(self, attrname, **kwargs):
def import_xml(self, sumo, datapaths):
datapathkey = self.datapathkey.get_value()
- if datapaths.has_key(datapathkey):
+ if datapathkey in datapaths:
self.import_sumoxml(datapaths[datapathkey], sumo, self.get_group('routedata'))
def import_sumoxml(self, filepath, sumo, attrconfigs):
@@ -674,13 +674,13 @@ def import_sumoxml(self, filepath, sumo, attrconfigs):
attrname = attrconfig.attrname
if attrname != 'ids_sumo':
default = attrconfig.get_default()
- if type(default) in (types.IntType, types.LongType):
+ if type(default) in (int, int):
conversion = 'i' # int
values_attr = np.zeros(n, int)
- elif type(default) in (types.FloatType, types.ComplexType):
+ elif type(default) in (float, complex):
conversion = 'f' # float
values_attr = np.zeros(n, dtype=np.float32)
- if type(default) in (types.BooleanType,):
+ if type(default) in (bool,):
conversion = 'b' # str
values_attr = np.zeros(n, dtype=np.bool)
else:
@@ -774,7 +774,7 @@ def __init__(self, ident, parent, trips, edges, # datapathkey = 'tripdatapath',
#('speeds_av', {'name':'Average speeds', 'xmltag':'speed', 'unit':'m/s', 'default':0, 'info':'Average speed','groupnames':['tripdata'],'is_average' : True}),
])
- for attrname, kwargs in attrinfos.iteritems():
+ for attrname, kwargs in attrinfos.items():
self.add_resultattr(attrname, **kwargs)
# this is special for route info
@@ -793,7 +793,7 @@ def add_resultattr(self, attrname, **kwargs):
# default cannot be kwarg
default = kwargs['default']
del kwargs['default']
- if kwargs.has_key('groupnames'):
+ if 'groupnames' in kwargs:
kwargs['groupnames'].append('results')
else:
kwargs['groupnames'] = ['results']
@@ -809,9 +809,9 @@ def add_resultattr(self, attrname, **kwargs):
# self.import_sumoxml(filepath,self.get_group('tripdata'))
def import_xml(self, sumo, datapaths):
- print 'Tripresults.import_xml datapaths', datapaths
+ print('Tripresults.import_xml datapaths', datapaths)
datapathkey = 'tripdatapath'
- if datapaths.has_key(datapathkey):
+ if datapathkey in datapaths:
self.import_tripdata_sumoxml(datapaths[datapathkey], sumo)
#datapathkey = 'electricenergypath'
@@ -820,7 +820,7 @@ def import_xml(self, sumo, datapaths):
def import_electricenergy_sumoxml_broke(self, filepath, sumo):
element = 'vehicle'
- print 'Tripresults.import_electricenergy_sumoxml', self.get_trips().ident, element, filepath
+ print('Tripresults.import_electricenergy_sumoxml', self.get_trips().ident, element, filepath)
#id_type = 'edge',
#reader = 'interval',
attrconfigs = self.get_group('electricenergydata')
@@ -859,10 +859,10 @@ def import_electricenergy_sumoxml_broke(self, filepath, sumo):
attrname = attrconfig.attrname
default = attrconfig.get_default()
- if type(default) in (types.IntType, types.LongType):
+ if type(default) in (int, int):
conversion = 'i' # int
values_attr = np.zeros(n, int)
- elif type(default) in (types.FloatType, types.ComplexType):
+ elif type(default) in (float, complex):
conversion = 'f' # float
values_attr = np.zeros(n, float)
else:
@@ -897,7 +897,7 @@ def import_electricenergy_sumoxml_broke(self, filepath, sumo):
def import_tripdata_sumoxml(self, filepath, sumo):
element = 'tripinfo'
- print 'Tripresults.import_tripdata_sumoxml', self.get_trips().ident, 'element', element, filepath
+ print('Tripresults.import_tripdata_sumoxml', self.get_trips().ident, 'element', element, filepath)
#id_type = 'edge',
#reader = 'interval',
attrconfigs = self.get_group('tripdata')
@@ -924,13 +924,13 @@ def import_tripdata_sumoxml(self, filepath, sumo):
for attrconfig in attrconfigs:
attrname = attrconfig.attrname
default = attrconfig.get_default()
- if type(default) in (types.IntType, types.LongType):
+ if type(default) in (int, int):
conversion = 'i' # int
values_attr = np.zeros(n, int)
- elif type(default) in (types.FloatType, types.ComplexType):
+ elif type(default) in (float, complex):
conversion = 'f' # float
values_attr = np.zeros(n, dtype=np.float32)
- if type(default) in (types.BooleanType,):
+ if type(default) in (bool,):
conversion = 'b' # str
values_attr = np.zeros(n, dtype=np.bool)
else:
@@ -1065,7 +1065,7 @@ def _init_attributes(self):
#
])
- for attrname, kwargs in attrinfos.iteritems():
+ for attrname, kwargs in attrinfos.items():
self.add_resultattr(attrname, **kwargs)
def add_resultattr(self, attrname, **kwargs):
@@ -1073,7 +1073,7 @@ def add_resultattr(self, attrname, **kwargs):
# default cannot be kwarg
default = kwargs['default']
del kwargs['default']
- if kwargs.has_key('groupnames'):
+ if 'groupnames' in kwargs:
kwargs['groupnames'].append('results')
else:
kwargs['groupnames'] = ['results']
@@ -1110,7 +1110,7 @@ def filter_zoneedges(self, ids_zone, is_invert=False):
"""
Keep only results of edges that belong to zone id_zone
"""
- print 'filter_zoneedges', ids_zone
+ print('filter_zoneedges', ids_zone)
zones = self.parent.parent.parent.landuse.zones
ids_zoneedge = set()
@@ -1122,7 +1122,7 @@ def filter_zoneedges(self, ids_zone, is_invert=False):
ids_res = self.get_ids()
inds = np.zeros(len(ids_res), dtype=np.bool)
- for i, id_res, id_edge in zip(xrange(len(ids_res)), ids_res, self.ids_edge[ids_res]):
+ for i, id_res, id_edge in zip(range(len(ids_res)), ids_res, self.ids_edge[ids_res]):
inds[i] = id_edge in ids_zoneedge
if not is_invert:
inds = np.logical_not(inds)
@@ -1130,7 +1130,7 @@ def filter_zoneedges(self, ids_zone, is_invert=False):
self.del_rows(ids_res[inds])
def import_edgedata(self, sumo, filepath):
- print 'import_edgedata', filepath
+ print('import_edgedata', filepath)
# print ' group',self.get_group('edgedata')
#attrnames_data = ['entered','left','arrived','departed']
#attrnames_averaged = ['traveltime','density','waitingTime','speed',]
@@ -1242,11 +1242,11 @@ def import_edgeflows(self, sumo, filepath):
return True
def import_edgenoise(self, sumo, filepath):
- print 'import_edgenoise', filepath
+ print('import_edgenoise', filepath)
self.import_sumoxml(filepath, sumo, self.get_group('edgenoise'))
def import_edgeemissions(self, sumo, filepath):
- print 'import_edgeemissions', filepath
+ print('import_edgeemissions', filepath)
#attrnames_data = ['fuel_abs','CO_abs','CO2_abs','NOx_abs','PMx_abs']
#attrnames_averaged = ['fuel_normed','CO_normed','CO2_normed',]
self.import_sumoxml(filepath, sumo, self.get_group('edgeemissions'))
@@ -1288,10 +1288,10 @@ def import_sumoxml(self, filepath, sumo, attrconfigs):
attrname = attrconfig.attrname
default = attrconfig.get_default()
- if type(default) in (types.IntType, types.LongType):
+ if type(default) in (int, int):
conversion = 'i' # int
values_attr = np.zeros(n, int)
- elif type(default) in (types.FloatType, types.ComplexType):
+ elif type(default) in (float, complex):
conversion = 'f' # float
values_attr = np.zeros(n, float)
else:
@@ -1355,7 +1355,7 @@ def import_marouterxml(self, filepath, marouter):
}),
])
- for attrname, kwargs in attrinfos.iteritems():
+ for attrname, kwargs in attrinfos.items():
self.add_resultattr(attrname, **kwargs)
attrconfigs = self.get_group('marouter')
@@ -1365,7 +1365,7 @@ def import_marouterxml(self, filepath, marouter):
class EdgeresultFilter(Process):
def __init__(self, edgeresults, logger=None, **kwargs):
- print 'EdgeresultFilter.__init__'
+ print('EdgeresultFilter.__init__')
# TODO: let this be independent, link to it or child??
@@ -1382,7 +1382,7 @@ def __init__(self, edgeresults, logger=None, **kwargs):
zonechoices = {}
for id_zone, name_zone in zip(ids_zone, zones.ids_sumo[ids_zone]):
zonechoices[name_zone] = id_zone
- print ' zonechoices', zonechoices
+ print(' zonechoices', zonechoices)
# make for each possible pattern a field for prob
# if len(zonechoices) > 0:
self.ids_zone = attrsman.add(cm.ListConf('ids_zone', [],
@@ -1408,7 +1408,7 @@ def __init__(self, edgeresults, logger=None, **kwargs):
))
def do(self):
- print 'EdgeresultFilter'
+ print('EdgeresultFilter')
# links
edgeresults = self.parent
edgeresults.filter_zoneedges(self.ids_zone, self.is_invert)
@@ -1477,13 +1477,13 @@ def __init__(self, parent, datapathkey='trajectorypath',
def import_xml(self, sumo, datapaths):
datapathkey = self.datapathkey.get_value()
- print 'TrajectoryResults.import_xml datapathkey', datapathkey, datapaths.has_key(datapathkey)
- if datapaths.has_key(datapathkey):
+ print('TrajectoryResults.import_xml datapathkey', datapathkey, datapathkey in datapaths)
+ if datapathkey in datapaths:
self.import_trajectories_sumoxml(datapaths[datapathkey], sumo)
def import_trajectories_sumoxml(self, filepath, sumo):
element = 'vehicle'
- print 'TrajectoryResults.import_trajectories_sumoxml', element, filepath
+ print('TrajectoryResults.import_trajectories_sumoxml', element, filepath)
ids_sumo, times, trajectories, angles, speeds = read_trajectories(
filepath, sumo, element)
@@ -1499,15 +1499,15 @@ def import_trajectories_sumoxml(self, filepath, sumo):
def print_trajectories(self):
ids_res = self.get_ids()
times = self.times.get_value()
- for i, t in zip(xrange(len(times)), times):
- print 79*'-'
- print 'time=', t, 's', len(times)
+ for i, t in zip(range(len(times)), times):
+ print(79*'-')
+ print('time=', t, 's', len(times))
for id_res, id_sumo_veh, traj, a, v in zip(ids_res, self.ids_sumo[ids_res], self.trajectories[ids_res], self.angles[ids_res], self.speeds[ids_res]):
# print ' id_sumo_veh',id_sumo_veh,id_res
# print ' v',v[i]
# print ' traj',traj[i]
# print ' a',a[i]
- print ' id_sumo_veh', id_sumo_veh, ': (x,y)', traj[i], 'a=%.2f', a[i], ' v=%.2fm/s' % v[i], len(a), len(v), len(traj)
+ print(' id_sumo_veh', id_sumo_veh, ': (x,y)', traj[i], 'a=%.2f', a[i], ' v=%.2fm/s' % v[i], len(a), len(v), len(traj))
class ElectricEnergyVehicleResults(am.ArrayObjman):
@@ -1566,7 +1566,7 @@ def __init__(self, parent, datapathkey='electricenergypath',
'info': 'Average speed', 'groupnames': ['electricenergydata'], 'is_average': True}),
])
- for attrname, kwargs in attrinfos.iteritems():
+ for attrname, kwargs in attrinfos.items():
self.add_resultattr(attrname, **kwargs)
def on_energy_total(self):
@@ -1578,7 +1578,7 @@ def add_resultattr(self, attrname, **kwargs):
# default cannot be kwarg
default = kwargs['default']
del kwargs['default']
- if kwargs.has_key('groupnames'):
+ if 'groupnames' in kwargs:
kwargs['groupnames'].append('results')
else:
kwargs['groupnames'] = ['results']
@@ -1595,12 +1595,12 @@ def add_resultattr(self, attrname, **kwargs):
def import_xml(self, sumo, datapaths):
datapathkey = self.datapathkey.get_value()
- if datapaths.has_key(datapathkey):
+ if datapathkey in datapaths:
self.import_electricenergy_sumoxml(datapaths[datapathkey], sumo)
def import_electricenergy_sumoxml(self, filepath, sumo):
element = 'vehicle'
- print 'ElectricEnergyresults.import_electricenergy_sumoxml', element, filepath
+ print('ElectricEnergyresults.import_electricenergy_sumoxml', element, filepath)
#id_type = 'edge',
#reader = 'interval',
attrconfigs = self.get_group('electricenergydata')
@@ -1613,8 +1613,8 @@ def import_electricenergy_sumoxml(self, filepath, sumo):
self.times.set_value(times)
self.energies.set_value(energies)
- print ' times=\n', self.times.get_value()
- print ' energies=\n', self.energies.get_value()
+ print(' times=\n', self.times.get_value())
+ print(' energies=\n', self.energies.get_value())
# print ' ids_sumo',ids_sumo
# print ' results.keys()',results.keys()
@@ -1627,7 +1627,7 @@ def import_electricenergy_sumoxml(self, filepath, sumo):
#ids_sumotrip = self.ids_trip.get_linktab().ids_sumo
n = len(ids_sumo)
ids = self.add_rows(n=n, ids_sumo=ids_sumo)
- print ' n', n
+ print(' n', n)
ind_range = np.arange(n, dtype=np.int32)
#ids = np.zeros(n, dtype=np.int32)
@@ -1648,10 +1648,10 @@ def import_electricenergy_sumoxml(self, filepath, sumo):
attrname = attrconfig.attrname
default = attrconfig.get_default()
- if type(default) in (types.IntType, types.LongType):
+ if type(default) in (int, int):
conversion = 'i' # int
values_attr = np.zeros(n, int)
- elif type(default) in (types.FloatType, types.ComplexType):
+ elif type(default) in (float, complex):
conversion = 'f' # float
values_attr = np.zeros(n, float)
else:
@@ -1719,8 +1719,8 @@ def _init_attributes(self):
self.routeresults = attrsman.add(cm.ObjConf(Routeresults('routeresults', self, scenario.demand.trips,
scenario.net.edges), groupnames=['Route results']))
# add trip results from all demand objects
- print 'Simresults._init_attributes'
- print ' scenario.demand.get_demandobjects()', scenario.demand.get_demandobjects()
+ print('Simresults._init_attributes')
+ print(' scenario.demand.get_demandobjects()', scenario.demand.get_demandobjects())
for demandobj in scenario.demand.get_demandobjects():
demandobj.config_results(self)
@@ -1759,7 +1759,7 @@ def add_resultobj(self, resultobj, **kwargs):
getattr(self, resultobj.get_ident()).clear()
if not hasattr(self, resultobj.get_ident()):
- if kwargs.has_key('groupnames'):
+ if 'groupnames' in kwargs:
kwargs['groupnames'].append('Results')
else:
kwargs['groupnames'] = ['Results']
@@ -1776,32 +1776,32 @@ def add_resultobj(self, resultobj, **kwargs):
# #edgedatapath=None, edgenoisepath=None, edgeemissionspath = None, routesdatapath=None, tripdatapath=None
def import_xml(self, sumo, **datapaths):
- print 'Simresults.import_xml', self.get_ident_abs()
+ print('Simresults.import_xml', self.get_ident_abs())
# print ' datapaths',datapaths
# import first all edge oriented results for the whole net
- if datapaths.has_key('edgedatapath'):
- print 'import edge data'
+ if 'edgedatapath' in datapaths:
+ print('import edge data')
self.edgeresults.import_edgedata(sumo, datapaths['edgedatapath'])
- if datapaths.has_key('edgenoisepath'):
- print 'import edge noise'
+ if 'edgenoisepath' in datapaths:
+ print('import edge noise')
self.edgeresults.import_edgenoise(sumo, datapaths['edgenoisepath'])
- if datapaths.has_key('edgeemissionspath'):
- print 'import edge emissons'
+ if 'edgeemissionspath' in datapaths:
+ print('import edge emissons')
self.edgeresults.import_edgeemissions(sumo, datapaths['edgeemissionspath'])
# import all other resultobjects
- for resultobj in self.get_attrsman().get_group_attrs('Results').values():
- print ' import other resultobject', resultobj.ident
+ for resultobj in list(self.get_attrsman().get_group_attrs('Results').values()):
+ print(' import other resultobject', resultobj.ident)
resultobj.import_xml(sumo, datapaths)
- if datapaths.has_key('routesdatapath'):
- print 'import route results'
+ if 'routesdatapath' in datapaths:
+ print('import route results')
self.routeresults.import_xml(sumo, datapaths)
- print 'importedge flows'
+ print('importedge flows')
self.edgeresults.import_edgeflows(sumo, datapaths['edgedatapath'])
- print 'import connection flows'
+ print('import connection flows')
self.connectionresults.evaluate_results(sumo, datapaths)
# def process(self, process = None):
@@ -1811,7 +1811,7 @@ def import_xml(self, sumo, **datapaths):
# demandobj.process_results(self, process)
def get_tripresults(self):
- return self.get_attrsman().get_group_attrs('Trip results').values()
+ return list(self.get_attrsman().get_group_attrs('Trip results').values())
# def import_routesdata(self, routesdatapath):
# for tripresult in self.get_tripresults():
@@ -1885,12 +1885,12 @@ def startElement(self, name, attrs):
xmltag = attrsconfig.xmltag
attrname = attrsconfig.attrname
- if attrs.has_key(xmltag):
+ if xmltag in attrs:
# print ' attrname cum',attrname,attrs.has_key(attrname),'*'+attrs[attrname]+'*'
a = attrs[xmltag]
if a.strip() != '':
- if self._values[attrname].has_key(id_elem):
+ if id_elem in self._values[attrname]:
self._values[attrname][id_elem] += float(a)
# print ' added val',xmltag,attrname,self._values[attrname][id_elem],'val',float(a)
else:
@@ -1908,12 +1908,12 @@ def startElement(self, name, attrs):
for attrsconfig in self._attrsconfigs_average:
xmltag = attrsconfig.xmltag
attrname = attrsconfig.attrname
- if attrs.has_key(xmltag):
+ if xmltag in attrs:
# print ' attrname',attrname,attrs.has_key(attrname),'*'+attrs[attrname]+'*'
# n=float(self.n_inter)
a = attrs[xmltag]
if a.strip() != '':
- if self._values[attrname].has_key(id_elem):
+ if id_elem in self._values[attrname]:
valcum, n = self._values[attrname][id_elem]
valcum += float(a)
n += 1
@@ -1942,7 +1942,7 @@ def __init__(self, element, sumo, attrsconfigs_cumulative, attrsconfigs_average
element is "lane" or "edge" or "tripinfo"
attrnames is a list of attribute names to read.
"""
- print 'IntervalAvReader2', element
+ print('IntervalAvReader2', element)
# print ' attrsconfigs_cumulative'
# for attrconfig in attrsconfigs_cumulative: print ' ',attrconfig.attrname
@@ -2020,12 +2020,12 @@ def startElement(self, name, attrs):
xmltag = attrsconfig.xmltag
attrname = attrsconfig.attrname
- if attrs.has_key(xmltag):
+ if xmltag in attrs:
# print ' attrname cum',attrname,attrs.has_key(attrname),'*'+attrs[attrname]+'*'
a = attrs[xmltag]
if a.strip() != '':
- if self._values[attrname].has_key(id_elem):
+ if id_elem in self._values[attrname]:
self._values[attrname][id_elem] += float(a)
# print ' added val',xmltag,attrname,self._values[attrname][id_elem],'val',float(a)
else:
@@ -2043,12 +2043,12 @@ def startElement(self, name, attrs):
for attrsconfig in self._attrsconfigs_average:
xmltag = attrsconfig.xmltag
attrname = attrsconfig.attrname
- if attrs.has_key(xmltag):
+ if xmltag in attrs:
# print ' attrname',attrname,attrs.has_key(attrname),'*'+attrs[attrname]+'*'
# n=float(self.n_inter)
a = attrs[xmltag]
if a.strip() != '':
- if self._values[attrname].has_key(id_elem):
+ if id_elem in self._values[attrname]:
valcum, n = self._values[attrname][id_elem]
valcum += float(a)
n += 1
@@ -2085,7 +2085,7 @@ def __init__(self, element, sumo, attrsconfigs_cumulative, attrsconfigs_average
element is "lane" or "edge" or "tripinfo"
attrnames is a list of attribute names to read.
"""
- print 'ElectricalEnergyReader', element
+ print('ElectricalEnergyReader', element)
# print ' attrsconfigs_cumulative',attrsconfigs_cumulative
# print ' attrsconfigs_average',attrsconfigs_average
IntervalAvReader2.__init__(self, element, sumo, attrsconfigs_cumulative, attrsconfigs_average)
@@ -2142,13 +2142,13 @@ def startElement(self, name, attrs):
xmltag = attrsconfig.xmltag
attrname = attrsconfig.attrname
# print ' attrname (cum)',attrname,xmltag,attrs.has_key(xmltag)
- if attrs.has_key(xmltag):
+ if xmltag in attrs:
a = attrs[xmltag]
if a.strip() != '':
a = float(a)
- if self._values[attrname].has_key(id_elem):
+ if id_elem in self._values[attrname]:
self._values[attrname][id_elem] += a
# print ' added val',xmltag,attrname,self._values[attrname][id_elem],'val',float(a)
else:
@@ -2162,12 +2162,12 @@ def startElement(self, name, attrs):
xmltag = attrsconfig.xmltag
attrname = attrsconfig.attrname
# print ' attrname (av)',attrname,xmltag,attrs.has_key(xmltag)
- if attrs.has_key(xmltag):
+ if xmltag in attrs:
a = attrs[xmltag]
if a.strip() != '':
a = float(a)
- if self._values[attrname].has_key(id_elem):
+ if id_elem in self._values[attrname]:
valcum, n = self._values[attrname][id_elem]
# print ' add val', float(a),'to',valcum
valcum += a
@@ -2244,15 +2244,15 @@ def startElement(self, name, attrs):
xmltag = attrsconfig.xmltag
attrname = attrsconfig.attrname
- if attrs.has_key(xmltag):
+ if xmltag in attrs:
# print ' attrname',attrname,attrs.has_key(attrname)
- if attrs.has_key(attrname):
+ if attrname in attrs:
# print ' val *'+attrs[xmltag]+'*'
a = attrs[xmltag]
if a.strip() != '':
- if self._values[attrname].has_key(id_elem):
+ if id_elem in self._values[attrname]:
self._values[attrname][id_elem] += float(a)
else:
self._values[attrname][id_elem] = float(a)
@@ -2268,11 +2268,11 @@ def startElement(self, name, attrs):
for attrsconfig in self._attrsconfigs_average:
xmltag = attrsconfig.xmltag
attrname = attrsconfig.attrname
- if attrs.has_key(xmltag):
+ if xmltag in attrs:
# n=float(self.n_inter)
a = attrs[xmltag]
if a.strip() != '':
- if self._values[attrname].has_key(id_elem):
+ if id_elem in self._values[attrname]:
valcum, n = self._values[attrname][id_elem]
valcum += float(a)
n += 1
@@ -2295,7 +2295,7 @@ def get_ids(self):
def read_electrical_energy(filepath, sumo, element, attrsconfigs):
- print 'read_electrical_energy'
+ print('read_electrical_energy')
attrsconfigs_cumulative = []
attrsconfigs_average = []
for attrsconfig in attrsconfigs:
@@ -2323,7 +2323,7 @@ def __init__(self, element, sumo, attrsconfigs_cumulative, attrsconfigs_average
element is "lane" or "edge" or "tripinfo"
attrnames is a list of attribute names to read.
"""
- print 'ElectricalEnergyReader', element
+ print('ElectricalEnergyReader', element)
# print ' attrsconfigs_cumulative',attrsconfigs_cumulative
# print ' attrsconfigs_average',attrsconfigs_average
IntervalAvReader2.__init__(self, element, sumo, attrsconfigs_cumulative, attrsconfigs_average)
@@ -2380,13 +2380,13 @@ def startElement(self, name, attrs):
xmltag = attrsconfig.xmltag
attrname = attrsconfig.attrname
# print ' attrname (cum)',attrname,xmltag,attrs.has_key(xmltag)
- if attrs.has_key(xmltag):
+ if xmltag in attrs:
a = attrs[xmltag]
if a.strip() != '':
a = float(a)
- if self._values[attrname].has_key(id_elem):
+ if id_elem in self._values[attrname]:
self._values[attrname][id_elem] += a
# print ' added val',xmltag,attrname,self._values[attrname][id_elem],'val',float(a)
else:
@@ -2400,12 +2400,12 @@ def startElement(self, name, attrs):
xmltag = attrsconfig.xmltag
attrname = attrsconfig.attrname
# print ' attrname (av)',attrname,xmltag,attrs.has_key(xmltag)
- if attrs.has_key(xmltag):
+ if xmltag in attrs:
a = attrs[xmltag]
if a.strip() != '':
a = float(a)
- if self._values[attrname].has_key(id_elem):
+ if id_elem in self._values[attrname]:
valcum, n = self._values[attrname][id_elem]
# print ' add val', float(a),'to',valcum
valcum += a
@@ -2435,7 +2435,7 @@ def __init__(self, element, sumo):
element is "lane" or "edge" or "tripinfo"
attrnames is a list of attribute names to read.
"""
- print 'TrajectoryReader', element
+ print('TrajectoryReader', element)
# print ' attrsconfigs_cumulative',attrsconfigs_cumulative
# print ' attrsconfigs_average',attrsconfigs_average
IntervalAvReader2.__init__(self, element, sumo, [], [])
@@ -2518,7 +2518,7 @@ def endElement(self, name):
def read_trajectories(filepath, sumo, element):
- print 'read_trajectories', element
+ print('read_trajectories', element)
reader = TrajectoryReader(element, sumo)
parse(filepath, reader)
@@ -2529,7 +2529,7 @@ def read_trajectories(filepath, sumo, element):
angles = np.ones(n_veh, dtype=np.object)
speeds = np.ones(n_veh, dtype=np.object)
- for i, id_sumo in zip(xrange(n_veh), ids_sumo):
+ for i, id_sumo in zip(range(n_veh), ids_sumo):
trajectories[i] = reader.trajectories[id_sumo]
angles[i] = reader.angles[id_sumo]
speeds[i] = reader.speeds[id_sumo]
@@ -2563,7 +2563,7 @@ def read_interval2(filepath, sumo, element, attrsconfigs):
def read_tripresult(filepath, sumo, trips, element, attrsconfigs):
- print 'read_tripresult', filepath, trips.ident, 'element', element
+ print('read_tripresult', filepath, trips.ident, 'element', element)
attrsconfigs_cumulative = []
attrsconfigs_average = []
for attrsconfig in attrsconfigs:
diff --git a/tools/contributed/sumopy/coremodules/simulation/results_mpl.py b/tools/contributed/sumopy/coremodules/simulation/results_mpl.py
index 52382b288a6f..cdff8ad1963d 100644
--- a/tools/contributed/sumopy/coremodules/simulation/results_mpl.py
+++ b/tools/contributed/sumopy/coremodules/simulation/results_mpl.py
@@ -50,7 +50,7 @@ def __init__(self, results, name='Plot results with Matplotlib',
# edgeresultes....
attrnames_edgeresults = OrderedDict()
edgeresultattrconfigs = self.parent.edgeresults.get_group_attrs('results')
- edgeresultattrnames = edgeresultattrconfigs.keys()
+ edgeresultattrnames = list(edgeresultattrconfigs.keys())
# edgeresultattrnames.sort()
for attrname in edgeresultattrnames:
attrconfig = edgeresultattrconfigs[attrname]
@@ -117,7 +117,7 @@ def __init__(self, results, name='Electrical energy plotter',
self._init_common('electricalenergyresultsplotter', parent=results, name=name,
info=info, logger=logger)
- print 'ElectricalEnergyResultsPlotter.__init__', results, self.parent, len(self.get_eneryresults())
+ print('ElectricalEnergyResultsPlotter.__init__', results, self.parent, len(self.get_eneryresults()))
attrsman = self.get_attrsman()
self.add_plotoptions_lineplot(**kwargs)
@@ -128,16 +128,16 @@ def get_eneryresults(self):
def show(self):
eneryresults = self.get_eneryresults()
- print 'show', eneryresults
+ print('show', eneryresults)
# print ' dir(vehicleman)',dir(vehicleman)
- print ' len(eneryresults)', len(eneryresults)
+ print(' len(eneryresults)', len(eneryresults))
if len(eneryresults) > 0:
plt.close("all")
self.plot_power()
def plot_power(self):
- print 'plot_power'
+ print('plot_power')
eneryresults = self.get_eneryresults()
times = eneryresults.times.get_value()
@@ -193,7 +193,7 @@ def __init__(self, results, name='Speed profile plotter',
self._init_common('speedprofileplotter', parent=results, name=name,
info=info, logger=logger)
- print 'SpeedprofilePlotter.__init__', results, self.parent, len(self.get_results())
+ print('SpeedprofilePlotter.__init__', results, self.parent, len(self.get_results()))
attrsman = self.get_attrsman()
self.id_veh_sumo = attrsman.add(cm.AttrConf('id_veh_sumo', kwargs.get('id_veh_sumo', ''),
@@ -211,10 +211,10 @@ def get_results(self):
def show(self):
results = self.get_results()
- print 'show', results
+ print('show', results)
id_res = results.ids_sumo.get_id_from_index(self.id_veh_sumo)
- print ' len(results)', len(results), results.ids_sumo.has_index(self.id_veh_sumo)
+ print(' len(results)', len(results), results.ids_sumo.has_index(self.id_veh_sumo))
if results.ids_sumo.has_index(self.id_veh_sumo):
id_res = results.ids_sumo.get_id_from_index(self.id_veh_sumo)
plt.close("all")
@@ -224,7 +224,7 @@ def show(self):
return False
def plot_speedprofile(self, times, speeds):
- print 'plot_speedprofile'
+ print('plot_speedprofile')
if len(times) < 2:
return False
@@ -278,13 +278,13 @@ def __init__(self, results, name='XY edge result plotter',
self._init_common('xyedgeresultsplotter', parent=results, name=name,
info=info, logger=logger)
- print 'XYResultsPlotter.__init__', results
+ print('XYResultsPlotter.__init__', results)
attrsman = self.get_attrsman()
# edgeresultes....
attrnames_edgeresults = OrderedDict()
edgeresultattrconfigs = self.parent.edgeresults.get_group_attrs('results')
- edgeresultattrnames = edgeresultattrconfigs.keys()
+ edgeresultattrnames = list(edgeresultattrconfigs.keys())
# edgeresultattrnames.sort()
for attrname in edgeresultattrnames:
attrconfig = edgeresultattrconfigs[attrname]
@@ -315,13 +315,13 @@ def __init__(self, results, name='XY edge result plotter',
self.add_save_options(**kwargs)
def show(self):
- print 'show'
+ print('show')
plt.close("all")
self.plot_xy()
def plot_xy(self):
- print 'plot_xy', self.edgeattrname_y, 'vs', self.edgeattrname_x
+ print('plot_xy', self.edgeattrname_y, 'vs', self.edgeattrname_x)
if (self.edgeattrname_x is not "") & (self.edgeattrname_x is not ""):
resultattrconf_x = getattr(self.parent.edgeresults, self.edgeattrname_x)
@@ -363,7 +363,7 @@ def plot_xy(self):
offset = my - (m*mx)
x_linreg = np.array([np.min(x[inds]), np.max(x[inds])], dtype=np.float)
- print ' m', m, 'offset', offset
+ print(' m', m, 'offset', offset)
# print ' x_linreg',offset * x_linreg
ax.plot(x_linreg, offset + m*x_linreg,
label=r'$%.3f+%.3fx$, $R^2=%.3f$' % (offset, m, R2),
@@ -431,7 +431,7 @@ def __init__(self, results, name='Travel time plotter',
self._init_common('isochoneplotter', parent=results, name=name,
info=info, logger=logger)
- print 'TraveltimePlotter.__init__', results, self.parent
+ print('TraveltimePlotter.__init__', results, self.parent)
attrsman = self.get_attrsman()
scenario = self.get_scenario()
@@ -549,8 +549,8 @@ def show(self):
)
elif self.direction == 'destination':
title = 'Accumulated travel times to edge ID %d' % (self.id_edge_reference)
- ids_edge = np.array(edgetimestree.keys(), dtype=np.int32)
- edgetimes = np.array(edgetimestree.values(), dtype=np.float32)
+ ids_edge = np.array(list(edgetimestree.keys()), dtype=np.int32)
+ edgetimes = np.array(list(edgetimestree.values()), dtype=np.float32)
self.plot_results_on_map(ax, ids_edge=ids_edge,
values=edgetimes,
@@ -559,7 +559,7 @@ def show(self):
if 0: # self.is_isochrone:
- print 'isochrone plot not yet implemented'
+ print('isochrone plot not yet implemented')
times_point = np.zeros(np.max(ids_point)+1)
for id_point in ids_point:
@@ -620,7 +620,7 @@ def plot_isochrone(self, ax, ids_point, zone_shape, times_point):
else:
isochrone_shapes[i].append([(points.coords[iso_points[np.argmax(iso_points[:, 3]), 1]][0]),
(points.coords[iso_points[np.argmax(iso_points[:, 3]), 1]][1])])
- print isochrone_shapes
+ print(isochrone_shapes)
for isochrone_shape in isochrone_shapes:
verts = np.array(isochrone_shape)[:, :2].tolist()
verts.append([0, 0])
@@ -637,9 +637,9 @@ def plot_isochrone(self, ax, ids_point, zone_shape, times_point):
if len(isochrone_shape) > 4:
zone_shape = isochrone_shape
- print zone_shape
- for zone_shape_coords, i in zip(isochrone_shape, range(len(isochrone_shape))):
- print i, len(isochrone_shape)
+ print(zone_shape)
+ for zone_shape_coords, i in zip(isochrone_shape, list(range(len(isochrone_shape)))):
+ print(i, len(isochrone_shape))
if i == 0:
zone_shape[i] = ((np.array(isochrone_shape[i])+np.array(isochrone_shape[i+1])+np.array(
isochrone_shape[-1])+np.array(isochrone_shape[i+2])+np.array(isochrone_shape[-2]))/5.).tolist()
diff --git a/tools/contributed/sumopy/coremodules/simulation/simplaconfig.py b/tools/contributed/sumopy/coremodules/simulation/simplaconfig.py
index 92746d671678..8325c5764d26 100644
--- a/tools/contributed/sumopy/coremodules/simulation/simplaconfig.py
+++ b/tools/contributed/sumopy/coremodules/simulation/simplaconfig.py
@@ -42,7 +42,7 @@
import simpla
except:
- print 'WARNING: No module simpla in syspath. Please provide SUMO_HOME.'
+ print('WARNING: No module simpla in syspath. Please provide SUMO_HOME.')
simpla = None
@@ -287,7 +287,7 @@ def prepare_sim(self):
if self.is_enabled:
# self.add_vtypes()# done in get_writexmlinfo means in get_vtypes()
self.export_config()
- print 'Simplaconfig.prepare_sim', self.configfilepath, self.is_enabled
+ print('Simplaconfig.prepare_sim', self.configfilepath, self.is_enabled)
simpla.load(self.configfilepath)
def finish_sim(self):
@@ -303,7 +303,7 @@ def write_xml(self, fd, indent=0):
"""
Write simpla xml config file
"""
- print 'Simplaconfig.write_xml'
+ print('Simplaconfig.write_xml')
fd.write(xm.begin(self.xmltag, indent))
attrsman = self.get_attrsman()
vtypes = self.parent.get_scenario().demand.vtypes
@@ -329,7 +329,7 @@ def write_xml(self, fd, indent=0):
# #if id_vtype_sumo.split('_')[-1] not in plattypes:
# ids_vtypes_plat_sumo.append(id_vtype_sumo)
- ids_vtypes_plat_sumo = ids_sumo_vtypes[self._typemap.keys()]
+ ids_vtypes_plat_sumo = ids_sumo_vtypes[list(self._typemap.keys())]
fd.write(xm.start('vehicleSelectors', indent+2))
fd.write(xm.arr('value', ids_vtypes_plat_sumo, sep=','))
fd.write(xm.stopit())
@@ -349,9 +349,9 @@ def write_xml(self, fd, indent=0):
fd.write(xm.num('catchupFollower', self.speedfactor_catchup_follower))
fd.write(xm.stopit())
- for plattypes in self._typemap.values():
+ for plattypes in list(self._typemap.values()):
fd.write(xm.start('vTypeMap', indent+2))
- for plattype, id_vtype in plattypes.iteritems():
+ for plattype, id_vtype in plattypes.items():
fd.write(xm.num(plattype, ids_sumo_vtypes[id_vtype]))
fd.write(xm.stopit())
@@ -372,7 +372,7 @@ def add_vtypes(self):
This function is called before writing vtypes.
These vtypes should be deleted after the export.
"""
- print 'Simplaconfig.add_vtypes'
+ print('Simplaconfig.add_vtypes')
self._typemap = {}
vtypes = self.get_scenario().demand.vtypes
for id_mode in self.ids_platoonmodes:
@@ -433,14 +433,14 @@ def get_vtypes(self):
if not self.is_enabled:
return []
- print 'Simpla.get_vtypes'
+ print('Simpla.get_vtypes')
plattype_original = 'original'
# add vtypes for platooning here
self.add_vtypes()
# here we return only the additional vtypes
ids_vtypes_plat = []
- for plattypes in self._typemap.values():
- for plattype, id_vtype in plattypes.iteritems():
+ for plattypes in list(self._typemap.values()):
+ for plattype, id_vtype in plattypes.items():
if plattype != plattype_original:
ids_vtypes_plat.append(id_vtype)
# print ' ids_vtypes_plat',ids_vtypes_plat
@@ -452,12 +452,12 @@ def del_vtypes(self):
vtypes = self.get_scenario().demand.vtypes
plattype_original = 'original'
ids_vtypes_plat = []
- for plattypes in self._typemap.values():
- for plattype, id_vtype in plattypes.iteritems():
+ for plattypes in list(self._typemap.values()):
+ for plattype, id_vtype in plattypes.items():
if plattype != plattype_original:
ids_vtypes_plat.append(id_vtype)
- print 'del_vtypes', ids_vtypes_plat
+ print('del_vtypes', ids_vtypes_plat)
vtypes.del_rows(ids_vtypes_plat)
self._typemap = {}
@@ -467,7 +467,7 @@ def _add_vtypes(self, vtypes, ids, plattype,
coloroffset=np.zeros(4, np.float32),
colorfactor=np.ones(4, np.float32),
carfollowermodel='Krauss'):
- print '_add_vtypes', ids, plattype
+ print('_add_vtypes', ids, plattype)
n = len(ids)
ids_new = vtypes.add_rows(n=len(ids))
for colconfig in vtypes.get_attrsman()._colconfigs:
@@ -499,7 +499,7 @@ def _add_vtypes(self, vtypes, ids, plattype,
vtypes.decels_emergency[ids_new] = vtypes.decels[ids_new]+0.1
# update typemap database
for _id, _id_new in zip(ids, ids_new):
- if self._typemap.has_key(_id):
+ if _id in self._typemap:
self._typemap[_id][plattype] = _id_new
else:
self._typemap[_id] = {plattype: _id_new}
diff --git a/tools/contributed/sumopy/coremodules/simulation/simulation.py b/tools/contributed/sumopy/coremodules/simulation/simulation.py
index bff8f2fcd628..134e4096ee5f 100644
--- a/tools/contributed/sumopy/coremodules/simulation/simulation.py
+++ b/tools/contributed/sumopy/coremodules/simulation/simulation.py
@@ -22,9 +22,9 @@
import agilepy.lib_base.arrayman as am
import agilepy.lib_base.xmlman as xm
from agilepy.lib_base.misc import random_choice, get_inversemap
-import results
-from simplaconfig import SimplaConfig
-from taxi import TaxiService
+from . import results
+from .simplaconfig import SimplaConfig
+from .taxi import TaxiService
class Simulation(cm.BaseObjman):
@@ -42,7 +42,7 @@ def __init__(self, scenario, name='Simulation',
self._init_constants()
def _init_attributes(self):
- print 'Simulation._init_attributes id', id(self), self.parent.rootname # ,dir(self)
+ print('Simulation._init_attributes id', id(self), self.parent.rootname) # ,dir(self)
attrsman = self.get_attrsman()
# if self.get_version()<0.2:
@@ -107,4 +107,4 @@ def get_simobjects(self):
#demandobjects = set([])
# for ident, conf in self.get_group_attrs('').iteritems():
# demandobjects.add(conf.get_value())
- return self.get_attrsman().get_group_attrs('simulation objects').values()
+ return list(self.get_attrsman().get_group_attrs('simulation objects').values())
diff --git a/tools/contributed/sumopy/coremodules/simulation/sumo.py b/tools/contributed/sumopy/coremodules/simulation/sumo.py
index f9b251353859..c912373499a9 100644
--- a/tools/contributed/sumopy/coremodules/simulation/sumo.py
+++ b/tools/contributed/sumopy/coremodules/simulation/sumo.py
@@ -18,7 +18,7 @@
from agilepy.lib_base.processes import Process, CmlMixin, ff, call, P, filepathlist_to_filepathstring, Options
from coremodules.scenario.scenario import load_scenario
-from results import Simresults
+from .results import Simresults
from coremodules.network.network import SumoIdsConf
import agilepy.lib_base.xmlman as xm
import agilepy.lib_base.arrayman as am
@@ -51,7 +51,7 @@
except:
- print 'WARNING: No module traci in syspath. Please provide SUMO_HOME.'
+ print('WARNING: No module traci in syspath. Please provide SUMO_HOME.')
traci = None
@@ -896,7 +896,7 @@ def do(self):
Called by run after is_ready verification
"""
- print 'do... '
+ print('do... ')
scenario = self.parent
@@ -1047,10 +1047,10 @@ def do(self):
)
if self._cmlfilepath is None:
- print ' call run_cml'
+ print(' call run_cml')
return self.run_cml(cml=self.get_cml())
else:
- print ' do not simulate but write cml to', self._cmlfilepath
+ print(' do not simulate but write cml to', self._cmlfilepath)
f = open(self._cmlfilepath, "w+")
f.write(self.get_cml()+'\n')
@@ -1065,7 +1065,7 @@ def import_results(self, results=None):
"""
Imports simulation resuts into results object.
"""
- print 'import_results'
+ print('import_results')
# first a dict is created with available dataname as key
# and filepath as value
@@ -1125,7 +1125,7 @@ def get_cml(self, is_primed=True):
p = P
else:
p = ''
- print 'get_cml p=%s=' % p
+ print('get_cml p=%s=' % p)
# print ' self.configfilepath=%s='%self.configfilepath
# print ' self.logfilepath=%s='%self.logfilepath
if self.guimode is 'nogui':
@@ -1249,7 +1249,7 @@ def do(self):
def run_cml(self, cml):
scenario = self.parent
cmllist = cml.split(' ')
- print 'SumoTraci.run_cml', cmllist
+ print('SumoTraci.run_cml', cmllist)
traci.start(cmllist)
simplaconfig = self.parent.simulation.simplaconfig
@@ -1259,7 +1259,7 @@ def run_cml(self, cml):
self.simtime = self.simtime_start
self.duration = 1.0+self.simtime_end-self.simtime_start
self.get_attrsman().status.set('running')
- print ' traci started', self.get_attrsman().status.get()
+ print(' traci started', self.get_attrsman().status.get())
simobjects = []
for simobj in self.parent.simulation.get_simobjects():
@@ -1288,10 +1288,10 @@ def aboard(self):
def step(self):
# called interactively
# when gui it is called through the timer function
- print 79*'='
- print "simstep", self.simtime, self.simtime_end, self.simtime >= self.simtime_end
+ print(79*'=')
+ print("simstep", self.simtime, self.simtime_end, self.simtime >= self.simtime_end)
traci.simulationStep()
- for i in xrange(len(self.simobjects)):
+ for i in range(len(self.simobjects)):
# for time_last, time_sample, simfunc in self.simobjects:
time_last, time_sample, simfunc = self.simobjects[i]
# print ' simfunc',simfunc,'time_last',time_last,'dt',self.simtime-time_last,'sim?',self.simtime-time_last > time_sample
@@ -1303,18 +1303,18 @@ def step(self):
if self.simtime >= self.simtime_end: # | (not (traci.simulation.getMinExpectedNumber() > 0)):
# if self.simtime >= self.simtime_end:
- print ' end of simulation reached at', self.simtime
+ print(' end of simulation reached at', self.simtime)
return self.finish_sim()
self.simtime += self.time_step
def finish_sim(self):
- print 'finish_sim'
+ print('finish_sim')
# for demandobj in self.parent.demand.get_demandobjects():
# print ' finish_sim',demandobj.ident
# #demandobj.finish_sim(self) # why not for sim objects?
traci.close()
- print ' traci closed.'
+ print(' traci closed.')
self.get_attrsman().status.set('success')
simplaconfig = self.parent.simulation.simplaconfig
@@ -1841,13 +1841,13 @@ def do(self):
# print ' new since 1.8.0 ?'
# print ' workdirpath',self.workdirpath,'step_last',step_last
resultdir = os.path.join(self.workdirpath, str(step_last))
- print ' resultdir', resultdir
+ print(' resultdir', resultdir)
filename = self.parent.get_rootfilename() + "_%03d.rou.xml" % (self.get_last_step(),)
- print ' filename', filename
+ print(' filename', filename)
#routefilepath_final = os.path.join(self.workdirpath, str(step_last),'.'.join(self.routefilepath.split('.')[:-2]) + "_%03d.rou.xml"%(step_last,))
routefilepath_final = os.path.join(resultdir, filename)
- print ' load routes from file ', routefilepath_final
+ print(' load routes from file ', routefilepath_final)
if os.path.isfile(routefilepath_final):
scenario.demand.import_routes_xml(routefilepath_final)
@@ -1867,15 +1867,15 @@ def do(self):
os.remove(os.path.join(self.workdirpath, filename))
else: # new since 1.8.0 ?'
- for step in xrange(self.step_first, step_last):
+ for step in range(self.step_first, step_last):
filepath = os.path.join(self.workdirpath, str(step))
- print ' delete dir', filepath
+ print(' delete dir', filepath)
if os.path.isdir(filepath):
# print ' delete now'
try:
shutil.rmtree(filepath)
except OSError as e:
- print("Error: %s - %s." % (e.filename, e.strerror))
+ print(("Error: %s - %s." % (e.filename, e.strerror)))
return True
@@ -1886,7 +1886,7 @@ def import_results(self, results=None):
"""
Imports simulation resuts into results object.
"""
- print 'import_results'
+ print('import_results')
# currently nothing is imported in results only routs are
# reimported in trip database
diff --git a/tools/contributed/sumopy/coremodules/simulation/sumo_virtualpop.py b/tools/contributed/sumopy/coremodules/simulation/sumo_virtualpop.py
index edd9884be36c..59b435fef072 100644
--- a/tools/contributed/sumopy/coremodules/simulation/sumo_virtualpop.py
+++ b/tools/contributed/sumopy/coremodules/simulation/sumo_virtualpop.py
@@ -51,7 +51,7 @@
else:
filepath_simstats = None
-print 'sys.path', sys.path
+print('sys.path', sys.path)
#from coremodules.demand import vehicles as ve
@@ -76,7 +76,7 @@
logfilepath = 'log.txt'
sumologfilepath = 'log_sumo.txt'
###########################################################
-print 'script_vp: initialize sim cmlfilepath=', cmlfilepath
+print('script_vp: initialize sim cmlfilepath=', cmlfilepath)
# Load the scenario
@@ -168,7 +168,7 @@
if is_not_first_iter:
# load previous results, if cmlfilepath is present
- print ' importing and procerroessing previous results'
+ print(' importing and procerroessing previous results')
# store plans before reselection
ids_plan_before = virtualpop.ids_plan[ids_pers].copy()
@@ -180,7 +180,7 @@
# decrease c_probit and fraction for the nex iteration
c_probit = c_probit/(decrease+1)**n_iter
fraction = fraction/(decrease+1)**n_iter
- print 'n_iter:', n_iter, 'c_probit:', c_probit, 'fraction:', fraction
+ print('n_iter:', n_iter, 'c_probit:', c_probit, 'fraction:', fraction)
# select plans according to last simulation results
sim.import_results() # will update plan travel times
virtualpop.select_plans_min_time_exec_est(fraction=fraction,
@@ -193,7 +193,7 @@
else:
- print ' first iteration'
+ print(' first iteration')
# select all plans with the minimum estimated time
virtualpop.select_plans_min_time_est(fraction=1.0,
c_probit=c_probit_ini)
diff --git a/tools/contributed/sumopy/coremodules/simulation/sumo_virtualpop_iterate.py b/tools/contributed/sumopy/coremodules/simulation/sumo_virtualpop_iterate.py
index 78ac0c668c77..216e4edb4fcd 100644
--- a/tools/contributed/sumopy/coremodules/simulation/sumo_virtualpop_iterate.py
+++ b/tools/contributed/sumopy/coremodules/simulation/sumo_virtualpop_iterate.py
@@ -32,7 +32,7 @@
def start_iterations(scenariofilepath, n_iter, simscriptfilepath):
- print 'sumo_virtualpop_iterate.run', scenariofilepath
+ print('sumo_virtualpop_iterate.run', scenariofilepath)
cmlfilepath = os.path.join(os.path.dirname(simscriptfilepath), 'sumo_virtualpop_cml.bash')
P = '"'
@@ -43,37 +43,37 @@ def start_iterations(scenariofilepath, n_iter, simscriptfilepath):
for i in range(1, n_iter+1):
- print ' Start preparation of iteration %d.' % i
+ print(' Start preparation of iteration %d.' % i)
proc = subprocess.Popen(cml_script, shell=True)
proc.wait()
if proc.returncode == 0:
- print ' Preparation of iteration %d successful' % i
+ print(' Preparation of iteration %d successful' % i)
f = open(cmlfilepath, "r")
cml = f.readline()
f.close()
# time.sleep(10)
- print ' Start SUMO microsimulator'
- print ' cml=', cml
+ print(' Start SUMO microsimulator')
+ print(' cml=', cml)
proc = subprocess.Popen(cml, shell=True)
proc.wait()
if proc.returncode == 0:
- print ' Microsimulation of iteration %d successful.' % i
+ print(' Microsimulation of iteration %d successful.' % i)
else:
- print ' Error in microsimulation of iteration %d.' % i
+ print(' Error in microsimulation of iteration %d.' % i)
else:
- print ' Error in preparation of iteration %d successful' % i
- print ' Start preparation of iteration %d.' % i
+ print(' Error in preparation of iteration %d successful' % i)
+ print(' Start preparation of iteration %d.' % i)
proc = subprocess.Popen(cml_script, shell=True)
proc.wait()
if proc.returncode == 0:
- print 'Save last results.'
+ print('Save last results.')
f = open(cmlfilepath, "r")
cml = f.readline()
f.close()
else:
- print'error on the last data backup'
+ print('error on the last data backup')
# time.sleep(10)
diff --git a/tools/contributed/sumopy/coremodules/simulation/taxi.py b/tools/contributed/sumopy/coremodules/simulation/taxi.py
index 7d7b0fc3c04a..1716a2f4ff03 100644
--- a/tools/contributed/sumopy/coremodules/simulation/taxi.py
+++ b/tools/contributed/sumopy/coremodules/simulation/taxi.py
@@ -133,7 +133,7 @@ def write_config(self, fd, ident=0):
"""
Write taxi configuration to sumo configuration file feed.
"""
- print 'TaxiService.write_config is_enabled', self.is_enabled
+ print('TaxiService.write_config is_enabled', self.is_enabled)
if self.is_enabled:
attrsman = self.get_attrsman()
diff --git a/tools/contributed/sumopy/coremodules/simulation/wxgui.py b/tools/contributed/sumopy/coremodules/simulation/wxgui.py
index 9d7e9672957f..c1a590c46a45 100644
--- a/tools/contributed/sumopy/coremodules/simulation/wxgui.py
+++ b/tools/contributed/sumopy/coremodules/simulation/wxgui.py
@@ -24,16 +24,16 @@
from coremodules.scenario.scenario import Scenario
from coremodules.network import routing
from coremodules.misc.matplottools import ResultDialog
-import sumo
-import results
+from . import sumo
+from . import results
-from result_oglviewer import Resultviewer
+from .result_oglviewer import Resultviewer
try:
- import results_mpl as results_mpl
+ from . import results_mpl as results_mpl
is_mpl = True # we have matplotlib support
except:
- print "WARNING: python matplotlib package not installed, no matplotlib plots."
+ print("WARNING: python matplotlib package not installed, no matplotlib plots.")
is_mpl = False
@@ -82,12 +82,12 @@ def init_widgets(self, mainframe):
Set mainframe and initialize widgets to various places.
"""
self._mainframe = mainframe
- print 'SimulationGui.init_widgets'
+ print('SimulationGui.init_widgets')
# mainframe.browse_obj(self._net)
self.make_menu()
self.make_toolbar()
self._resultviewer = mainframe.add_view("Result viewer", Resultviewer)
- print ' self._resultviewer', self._resultviewer, self._resultviewer.get_drawing()
+ print(' self._resultviewer', self._resultviewer, self._resultviewer.get_drawing())
def refresh_widgets(self):
"""
@@ -96,11 +96,11 @@ def refresh_widgets(self):
dependent on the availability of data.
"""
scenario = self.get_scenario()
- print 'simulation.WxGui.refresh_widgets', self._simulation != scenario.simulation
+ print('simulation.WxGui.refresh_widgets', self._simulation != scenario.simulation)
is_refresh = False
if self._simulation != scenario.simulation:
- print ' id(self._simulation)', id(self._simulation), 'id(scenario.simulation)', id(scenario.simulation), scenario.rootname
+ print(' id(self._simulation)', id(self._simulation), 'id(scenario.simulation)', id(scenario.simulation), scenario.rootname)
del self._simulation
self._simulation = scenario.simulation
is_refresh = True
@@ -110,11 +110,11 @@ def refresh_widgets(self):
# if is_refresh
if self._simulation.results.is_modified():
#
- print ' refresh of _resultviewer'
+ print(' refresh of _resultviewer')
drawing = self._resultviewer.set_results(self._simulation.results)
# canvas = self._neteditor.get_canvas()
else:
- print ' no refresh of _resultviewer :('
+ print(' no refresh of _resultviewer :(')
def make_menu(self):
# print 'make_menu'
@@ -750,7 +750,7 @@ def open_sumodialog_interactive(self):
# this does not return until the dialog is closed.
#val = dlg.ShowModal()
- print 'open_sumodialog_interactive'
+ print('open_sumodialog_interactive')
dlg.Show()
dlg.MakeModal(True)
# print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL
@@ -789,9 +789,9 @@ def on_estimate_entered_turnflows(self, event=None):
results = self._simulation.results
turnflows = self.get_scenario().demand.turnflows
ids_edge, flows = turnflows.estimate_entered()
- print 'on_estimate_entered_turnflows'
- print 'ids_edge', ids_edge
- print 'flows', flows
+ print('on_estimate_entered_turnflows')
+ print('ids_edge', ids_edge)
+ print('flows', flows)
results.edgeresults.add_entered_est(*turnflows.estimate_entered())
self._mainframe.browse_obj(results.edgeresults)
self._mainframe.select_view(name="Result viewer") # !!!!!!!!tricky, crashes without
diff --git a/tools/contributed/sumopy/examples/scripts/sumopy_sim.py b/tools/contributed/sumopy/examples/scripts/sumopy_sim.py
index 996585f7768e..46c81e9fdb42 100644
--- a/tools/contributed/sumopy/examples/scripts/sumopy_sim.py
+++ b/tools/contributed/sumopy/examples/scripts/sumopy_sim.py
@@ -39,7 +39,7 @@
if len(sys.argv) == 3:
resultfilepath = sys.argv[2]
else:
- print __doc__
+ print(__doc__)
sys.exit(0)
myscenario = scenario.load_scenario(simfilepath)
@@ -111,7 +111,7 @@
if resultfilepath is not None:
- print 'saving results in', resultfilepath
+ print('saving results in', resultfilepath)
myscenario.simulation.results.save(resultfilepath)
# import all results from xml and put them into myscenario.simulation.results
@@ -135,9 +135,9 @@
# do some analyses
ids_tripres = tripres.get_ids()
-print 'numer of arrived vehicles:', len(ids_tripres)
-print 'Total triplength: %.2fKm' % (0.001*np.mean(tripres.routeLength[ids_tripres]))
-print 'Average speed: %.2fKm/s' % (3.6*np.mean(tripres.routeLength[ids_tripres]/tripres.duration[ids_tripres]))
+print('numer of arrived vehicles:', len(ids_tripres))
+print('Total triplength: %.2fKm' % (0.001*np.mean(tripres.routeLength[ids_tripres])))
+print('Average speed: %.2fKm/s' % (3.6*np.mean(tripres.routeLength[ids_tripres]/tripres.duration[ids_tripres])))
ids_edgeres = edgeres.get_ids()
-print 'Total fuel consumption: %.2f liter' % (0.001*np.sum(edgeres.fuel_abs[ids_edgeres]))
+print('Total fuel consumption: %.2f liter' % (0.001*np.sum(edgeres.fuel_abs[ids_edgeres])))
diff --git a/tools/contributed/sumopy/migration_changes.txt b/tools/contributed/sumopy/migration_changes.txt
new file mode 100644
index 000000000000..6eed31d1d8b8
--- /dev/null
+++ b/tools/contributed/sumopy/migration_changes.txt
@@ -0,0 +1,22703 @@
+--- tools/contributed/sumopy/sumopy_gui.py (original)
++++ tools/contributed/sumopy/sumopy_gui.py (refactored)
+@@ -40,13 +40,13 @@
+ wxversion.select("3")
+ except:
+ #sys.exit('ERROR: wxPython versions 2.8 or 3.x not available.')
+- print 'No wxversion module available, try import default wx version'
+- print 'If wx import shall fail, please install wxPython versions 2.8 or 3.x together with the wxversion module.'
++ print('No wxversion module available, try import default wx version')
++ print('If wx import shall fail, please install wxPython versions 2.8 or 3.x together with the wxversion module.')
+ sys.exit(0)
+
+
+
+-from agilepy.lib_wx.mainframe import AgileMainframe
++from .agilepy.lib_wx.mainframe import AgileMainframe
+ import wx
+ __usage__ = """USAGE:
+ from command line:
+@@ -65,20 +65,20 @@
+ use for debugging:
+ python sumopy_gui.py --debug > debug.txt 2>&1
+ """
+-print ' _ '
+-print ' ____________|______|||___________________ '
+-print ' / _ | / \ _ _ _ _ _ \ '
+-print ' / | / | \ v / _ \ _|_|_|_|_ / '
+-print ' \ __o-o__/ | \ \ | / / / \ \ ____/ '
+-print ' \ / \|o|/ \ \|/ / / o/\ \ | _|__/_ '
+-print ' \ / \|o|/ \ | / / /| \ \ | | | '
+-print ' | | | | | / \|0|/ \ v / \_/ \_/ \_| | '
+-print ' | | | | |/_____________\_/____________/ ____/ '
+-print ' |/ '
+-print ''
+-print __appname__+' version '+__version__+'\n'+__copyright__
++print(' _ ')
++print(' ____________|______|||___________________ ')
++print(' / _ | / \ _ _ _ _ _ \ ')
++print(' / | / | \ v / _ \ _|_|_|_|_ / ')
++print(' \ __o-o__/ | \ \ | / / / \ \ ____/ ')
++print(' \ / \|o|/ \ \|/ / / o/\ \ | _|__/_ ')
++print(' \ / \|o|/ \ | / / /| \ \ | | | ')
++print(' | | | | | / \|0|/ \ v / \_/ \_/ \_| | ')
++print(' | | | | |/_____________\_/____________/ ____/ ')
++print(' |/ ')
++print('')
++print(__appname__+' version '+__version__+'\n'+__copyright__)
+
+-print '\n using wx python version', wx.__version__
++print('\n using wx python version', wx.__version__)
+
+ ###############################################################################
+ # IMPORTS
+--- tools/contributed/sumopy/agilepy/lib_base/arrayman.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/arrayman.py (refactored)
+@@ -16,7 +16,7 @@
+ # @author Joerg Schweizer
+ # @date 2012
+
+-from classman import *
++from .classman import *
+ import numpy as np
+
+
+@@ -494,7 +494,7 @@
+ # don't even write empty lists
+ pass
+
+- elif type(self._default) in (types.UnicodeType, types.StringType):
++ elif type(self._default) in (str, bytes):
+ if len(val) > 0:
+ fd.write(xm.num(self.xmltag, val))
+
+@@ -529,7 +529,7 @@
+ AttrConf.init_postload_internal(self, man, obj)
+ # print 'IdsConf.init_postload_internal',self.attrname,self.get_value().dtype,self.get_value().dtype == np.int64
+ if self.get_value().dtype == np.int64:
+- print 'WARNING in init_postload_internal: convert ids array to 32 bit'
++ print('WARNING in init_postload_internal: convert ids array to 32 bit')
+ self.set_value(np.array(self.get_value(), dtype=np.int32))
+ # if self._is_child:
+ # print ' make sure children get initialized'
+@@ -890,7 +890,7 @@
+ return
+
+ def __getitem__(self, args):
+- if type(args) == types.TupleType:
++ if type(args) == tuple:
+ attrnames = args[0]
+ ids = args[1]
+ else:
+@@ -908,7 +908,7 @@
+ # TODO: detect dtype by adding numbers or use fields!!!
+ dtype = np.float32
+ out = np.zeros((n_rows, n_cols), dtype=dtype)
+- for i, attrname in zip(xrange(n_cols), attrnames):
++ for i, attrname in zip(range(n_cols), attrnames):
+ out[:, i] = getattr(self, attrname)[ids]
+ return out
+ else:
+@@ -1052,7 +1052,7 @@
+ ids = self.suggest_ids(n)
+ elif (len(ids) == 0) & (len(attrs) > 0):
+ # get number of rows from any value vector provided
+- ids = self.suggest_ids(len(attrs.values()[0]))
++ ids = self.suggest_ids(len(list(attrs.values())[0]))
+ elif (n is None) & (len(ids) == 0) & (len(attrs) > 0):
+ # nothing given really-> do nothing
+ return np.zeros((0), np.int)
+@@ -1226,7 +1226,7 @@
+ # this should no longer happen in the future as ind and ids
+ # have been formatted propperly
+ if attrman._inds.dtype != np.int32:
+- print 'WARNING: 64 bit ids and inds...will adjust to 32 bit'
++ print('WARNING: 64 bit ids and inds...will adjust to 32 bit')
+ attrman._inds = np.array(attrman._inds, dtype=np.int32)
+ attrman._ids = np.array(attrman._ids, dtype=np.int32)
+
+--- tools/contributed/sumopy/agilepy/lib_base/classman.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/classman.py (refactored)
+@@ -42,9 +42,9 @@
+ from collections import OrderedDict
+ from datetime import datetime
+ #import numpy as np
+-import xmlman as xm
+-from logger import Logger
+-from misc import get_inversemap
++from . import xmlman as xm
++from .logger import Logger
++from .misc import get_inversemap
+
+ ##########
+
+@@ -71,8 +71,8 @@
+ STRUCTS_COL = ('odict', 'array')
+ STRUCTS_SCALAR = ('scalar', 'list', 'matrix', 'scalar.func')
+
+-NUMERICTYPES = (types.BooleanType, types.FloatType, types.IntType, types.LongType, types.ComplexType)
+-STRINGTYPES = (types.StringType, types.UnicodeType)
++NUMERICTYPES = (bool, float, int, int, complex)
++STRINGTYPES = (bytes, str)
+ NODATATYPES = (types.FunctionType, types.InstanceType, types.LambdaType)
+
+
+@@ -86,7 +86,7 @@
+ try:
+ f = open(filename, 'wb')
+ except:
+- print 'WARNING in save: could not open', filename
++ print('WARNING in save: could not open', filename)
+ return False
+
+ if is_not_save_parent:
+@@ -110,7 +110,7 @@
+ Filename may also include absolute or relative path.
+ If operation fails a None object is returned.
+ """
+- print 'load_obj', filename
++ print('load_obj', filename)
+
+ if is_throw_error:
+ f = open(filename, 'rb')
+@@ -118,7 +118,7 @@
+ try:
+ f = open(filename, 'rb')
+ except:
+- print 'WARNING in load_obj: could not open', filename
++ print('WARNING in load_obj: could not open', filename)
+ return None
+
+ # try:
+@@ -168,7 +168,7 @@
+ Standard plug types are automatically set but the system:
+
+ """
+- if not self._events.has_key(trigger):
++ if trigger not in self._events:
+ self._events[trigger] = []
+ self._events[trigger].append(function)
+ self._has_events = True
+@@ -269,7 +269,7 @@
+
+ # set rest of attributes passed as keyword args
+ # no matter what they are used for
+- for attr, value in attrs.iteritems():
++ for attr, value in attrs.items():
+ setattr(self, attr, value)
+
+ def is_save(self):
+@@ -331,7 +331,7 @@
+ then None is returned.
+ """
+ if (self.xmltag is not None):
+- if xmlattrs.has_key(self.xmltag):
++ if self.xmltag in xmlattrs:
+ return self.get_value_from_string(xmlattrs[self.xmltag])
+ else:
+ return None
+@@ -362,7 +362,7 @@
+ elif self.xmlmap is not None:
+ imap = get_inversemap(self.xmlmap)
+ # print 'get_value_from_string',s,imap
+- if imap.has_key(s):
++ if s in imap:
+ return imap[s]
+ else:
+ return self.get_numvalue_from_string(s)
+@@ -376,19 +376,19 @@
+ else:
+ t = valtype
+
+- if t in (types.UnicodeType, types.StringType):
++ if t in (str, bytes):
+ return s
+
+- elif t in (types.UnicodeType, types.StringType):
++ elif t in (str, bytes):
+ return s
+
+- elif t in (types.LongType, types.IntType):
++ elif t in (int, int):
+ return int(s)
+
+- elif t in (types.FloatType, types.ComplexType):
++ elif t in (float, complex):
+ return float(s)
+
+- elif t == types.BooleanType: # use default and hope it is no a numpy bool!!!
++ elif t == bool: # use default and hope it is no a numpy bool!!!
+ if s in ('1', 'True'):
+ return True
+ else:
+@@ -421,27 +421,27 @@
+ pass
+
+ elif self.xmlmap is not None:
+- if self.xmlmap.has_key(val):
++ if val in self.xmlmap:
+ fd.write(xm.num(self.xmltag, self.xmlmap[val]))
+ else:
+ fd.write(xm.num(self.xmltag, val))
+
+ elif hasattr(self, 'choices'):
+- if type(self.choices) == types.ListType:
++ if type(self.choices) == list:
+ fd.write(xm.num(self.xmltag, val))
+ else:
+ # print '_write_xml_value',self.attrname
+ # print ' val,self.choices.values()',val,self.choices.values()
+- i = self.choices.values().index(val)
+- fd.write(xm.num(self.xmltag, self.choices.keys()[i]))
+-
+- elif type(self._default) == types.BooleanType: # use default and hope it is no a numpy bool!!!
++ i = list(self.choices.values()).index(val)
++ fd.write(xm.num(self.xmltag, list(self.choices.keys())[i]))
++
++ elif type(self._default) == bool: # use default and hope it is no a numpy bool!!!
+ if val:
+ fd.write(xm.num(self.xmltag, 1))
+ else:
+ fd.write(xm.num(self.xmltag, 0))
+
+- elif type(self._default) in (types.UnicodeType, types.StringType):
++ elif type(self._default) in (str, bytes):
+ if len(val) > 0:
+ fd.write(xm.num(self.xmltag, val))
+
+@@ -680,9 +680,9 @@
+ # print ' self.__dict__=\n',self.__dict__.keys()
+ if self._is_saved:
+ # this message indicates a loop!!
+- print 'WARNING in __getstate__: Attribute already saved:', self.get_obj().format_ident_abs(), self.attrname
++ print('WARNING in __getstate__: Attribute already saved:', self.get_obj().format_ident_abs(), self.attrname)
+ state = {}
+- for attr in self.__dict__.keys():
++ for attr in list(self.__dict__.keys()):
+
+ if attr == 'plugin':
+ plugin = self.__dict__[attr]
+@@ -708,7 +708,7 @@
+ # this is always required, but will not be saved
+ self.plugins = {}
+
+- for attr in state.keys():
++ for attr in list(state.keys()):
+ # print ' state key',attr, state[attr]
+ # done in init_postload_internal...
+ # if attr=='plugin':
+@@ -783,7 +783,7 @@
+ if len(default) > 0:
+ valtype = type(default[0])
+ else:
+- valtype = types.UnicodeType
++ valtype = str
+
+ AttrConf.__init__(self, attrname, default,
+ struct='scalar',
+@@ -874,7 +874,7 @@
+ # print ' found object',self.get_value().get_ident_abs()
+ state['_ident_value'] = self.get_value().get_ident_abs()
+ else:
+- print 'WARNING in ObjConf._getstate_specific', self.attrname, 'lost linked object'
++ print('WARNING in ObjConf._getstate_specific', self.attrname, 'lost linked object')
+ state['_ident_value'] = []
+ # print ' ',
+
+@@ -924,7 +924,7 @@
+ # print ' linkobj',linkobj.ident
+ self.set_value(linkobj)
+ else:
+- print 'WARNING in ObjConf._getstate_specific', self.attrname, 'lost linked object'
++ print('WARNING in ObjConf._getstate_specific', self.attrname, 'lost linked object')
+ self.set_value(BaseObjman('lost_object'))
+
+ # def get_valueobj(self):
+@@ -1023,13 +1023,13 @@
+ def has_indices(self, indices):
+ ans = len(indices)*[False]
+ for i in range(len(indices)):
+- if self._index_to_id.has_key(indices[i]):
++ if indices[i] in self._index_to_id:
+ ans[i] = True
+
+ return ans
+
+ def has_index(self, index):
+- return self._index_to_id.has_key(index)
++ return index in self._index_to_id
+
+ def get_ids_from_indices(self, indices):
+ ids = len(indices)*[0]
+@@ -1043,7 +1043,7 @@
+ def get_ids_from_indices_save(self, indices):
+ ids = len(indices)*[0]
+ for i in range(len(indices)):
+- if not self._index_to_id.has_key(indices[i]):
++ if indices[i] not in self._index_to_id:
+ ids[i] = -1
+ else:
+ ids[i] = self._index_to_id[indices[i]]
+@@ -1059,7 +1059,7 @@
+ self._index_to_id[index] = _id
+
+ def rebuild_indices(self):
+- for idx in self._index_to_id.keys():
++ for idx in list(self._index_to_id.keys()):
+ del self._index_to_id[idx]
+ ids = self.get_obj().get_ids()
+ self.add_indices(ids, self[ids])
+@@ -1083,14 +1083,14 @@
+ def del_index(self, _id):
+ index = self[_id]
+ # when index is added (with set) no previous index value exists
+- if self._index_to_id.has_key(index):
++ if index in self._index_to_id:
+ del self._index_to_id[index]
+
+ def get_ids_sorted(self):
+ # print 'get_ids_sorted',self.value
+ # print ' _index_to_id',self._index_to_id
+ # print ' sorted',sorted(self._index_to_id.iteritems())
+- return OrderedDict(sorted(self._index_to_id.iteritems())).values()
++ return list(OrderedDict(sorted(self._index_to_id.items())).values())
+
+ # def indexset(self, indices, values):
+ # no! set made with respective attribute
+@@ -1375,10 +1375,10 @@
+ val = self[_id]
+ tt = type(val)
+
+- if tt in (types.LongType, types.IntType):
++ if tt in (int, int):
+ return str(val)+unit
+
+- elif tt in (types.FloatType, types.ComplexType):
++ elif tt in (float, complex):
+ if hasattr(attrconf, 'digits_fraction'):
+ digits_fraction = self.digits_fraction
+ else:
+@@ -1492,7 +1492,7 @@
+ # don't even write empty lists
+ pass
+
+- elif type(self._default) in (types.UnicodeType, types.StringType):
++ elif type(self._default) in (str, bytes):
+ if len(val) > 0:
+ fd.write(xm.num(self.xmltag, val))
+
+@@ -1984,7 +1984,7 @@
+ if len(attrconf.groupnames) > 0:
+ for groupname in attrconf.groupnames:
+
+- if not self._groups.has_key(groupname):
++ if groupname not in self._groups:
+ self._groups[groupname] = []
+
+ if attrconf not in self._groups[groupname]:
+@@ -1992,7 +1992,7 @@
+
+ def del_groupname(self, attrconf):
+ if len(attrconf.groupnames) > 0:
+- for groupname in self._groups.keys():
++ for groupname in list(self._groups.keys()):
+ attrconfigs = self._groups[groupname]
+ if attrconf in attrconfigs:
+ if groupname not in attrconf.groupnames:
+@@ -2002,10 +2002,10 @@
+ return self._groups
+
+ def get_groupnames(self):
+- return self._groups.keys()
++ return list(self._groups.keys())
+
+ def has_group(self, groupname):
+- return self._groups.has_key(groupname)
++ return groupname in self._groups
+
+ def get_group(self, name):
+ """
+@@ -2021,7 +2021,7 @@
+ """
+ # print 'get_group_attrs', self._groups
+ attrs = OrderedDict()
+- if not self._groups.has_key(name):
++ if name not in self._groups:
+ return attrs
+ for attrconf in self._groups[name]:
+ # print ' attrconf.attrname',attrconf.attrname
+@@ -2050,7 +2050,7 @@
+ show_parentesis), sep, attrconf.format_value()))
+
+ def print_attrs(self, show_unit=True, show_parentesis=False, attrconfigs=None):
+- print 'Attributes of', self._obj._name, 'ident_abs=', self._obj.get_ident_abs()
++ print('Attributes of', self._obj._name, 'ident_abs=', self._obj.get_ident_abs())
+ if attrconfigs is None:
+ attrconfigs = self.get_configs(structs=STRUCTS_SCALAR)
+
+@@ -2099,7 +2099,7 @@
+ # print 'WARNING in Attrsman.__getstate__',self,'attrname missing','id',id(self),'id obj',id(self._obj)
+
+ if not hasattr(self, '_obj'):
+- print 'WARNING: unknown obj in attrman', self, type(self)
++ print('WARNING: unknown obj in attrman', self, type(self))
+ # print ' dir',dir(self)
+ # if hasattr(self,'attrname'):
+ # print ' No attrman but attribute',self.attrname
+@@ -2115,7 +2115,7 @@
+ # print ' self.__dict__=\n',self.__dict__.keys()
+
+ state = {}
+- for attr in self.__dict__.keys():
++ for attr in list(self.__dict__.keys()):
+ # print ' attr',attr,self.__dict__[attr]
+ # TODO: optimize and put this at the end
+ if attr == 'plugin':
+@@ -2149,7 +2149,7 @@
+ # this is always required, but will not be saved
+ # self.plugins={}
+
+- for attr in state.keys():
++ for attr in list(state.keys()):
+ # print ' set state',attr
+ # plugin set in init_postload_internal
+ # if attr=='plugin':
+@@ -2304,7 +2304,7 @@
+ else:
+ id_max = max(id_set)
+ # print 'suggest_id',id0,
+- return list(id_set.symmetric_difference(xrange(id0, id_max+id0+1)))[0]
++ return list(id_set.symmetric_difference(range(id0, id_max+id0+1)))[0]
+
+ def suggest_ids(self, n, is_zeroid=False):
+ """
+@@ -2324,14 +2324,14 @@
+ else:
+ id_max = max(id_set)
+
+- return list(id_set.symmetric_difference(xrange(id0, id_max+id0+n)))[:n]
++ return list(id_set.symmetric_difference(range(id0, id_max+id0+n)))[:n]
+
+ def add_rows(self, n=None, ids=[], **attrs):
+ if n is not None:
+ ids = self.suggest_ids(n)
+ elif len(ids) == 0:
+ # get number of rows from any valye vector provided
+- ids = self.suggest_ids(len(attrs.values()[0]))
++ ids = self.suggest_ids(len(list(attrs.values())[0]))
+ else:
+ # ids already given , no ids to create
+ pass
+@@ -2412,7 +2412,7 @@
+
+ for _id in ids:
+ for attrconf in self.get_configs(structs=STRUCTS_COL):
+- print ' %s[%d] =\t %s' % (attrconf.attrname, _id, attrconf.format_value(_id, show_unit=True))
++ print(' %s[%d] =\t %s' % (attrconf.attrname, _id, attrconf.format_value(_id, show_unit=True)))
+
+ def write_csv(self, fd, sep=',', ids=None,
+ attrconfigs=None,
+@@ -2681,7 +2681,7 @@
+ """
+ Export scalars to file feed in csv format.
+ """
+- print 'BaseObjman.export_csv', filepath, "*"+sep+"*", 'attrconfigs', attrconfigs, self.get_attrsman()
++ print('BaseObjman.export_csv', filepath, "*"+sep+"*", 'attrconfigs', attrconfigs, self.get_attrsman())
+ fd = open(filepath, 'w')
+
+ # header
+@@ -2786,7 +2786,7 @@
+ """
+ Return child instance
+ """
+- if self.childs.has_key(attrname):
++ if attrname in self.childs:
+ config = self.childs[attrname]
+ return config.get_value()
+ else:
+@@ -2867,7 +2867,7 @@
+ # this is always required, but will not be saved
+ # self.plugins={}
+
+- for key in state.keys():
++ for key in list(state.keys()):
+ # print ' set state',key
+ self.__dict__[key] = state[key]
+
+@@ -2887,7 +2887,7 @@
+ Called after set state.
+ Link internal states and call constant settings.
+ """
+- print 'BaseObjman.init_postload_internal', self.ident, 'parent:'
++ print('BaseObjman.init_postload_internal', self.ident, 'parent:')
+ # if parent is not None:
+ # print parent.ident
+ # else:
+@@ -2995,7 +2995,7 @@
+ self._is_saved = True
+
+ else:
+- print 'WARNING in __getstate__: object %s already saved' % self.ident
++ print('WARNING in __getstate__: object %s already saved' % self.ident)
+ return state
+
+ def __setstate__(self, state):
+@@ -3004,7 +3004,7 @@
+ # this is always required, but will not be saved
+ self.plugins = {}
+
+- for attr in state.keys():
++ for attr in list(state.keys()):
+ # print ' set state',key
+ if attr == 'plugin':
+ if state[attr] == True:
+@@ -3063,7 +3063,7 @@
+ """
+ Export scalars to file feed in csv format.
+ """
+- print 'TableMixin.export_csv', filepath, "*"+sep+"*" # ,'attrconfigs',attrconfigs,self.get_attrsman()
++ print('TableMixin.export_csv', filepath, "*"+sep+"*") # ,'attrconfigs',attrconfigs,self.get_attrsman()
+ fd = open(filepath, 'w')
+
+ # header
+--- tools/contributed/sumopy/agilepy/lib_base/exports.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/exports.py (refactored)
+@@ -36,7 +36,7 @@
+
+
+ except:
+- print 'WARNING: No Exel export possible. Install openpyxl python package.'
++ print('WARNING: No Exel export possible. Install openpyxl python package.')
+ IS_EXCEL = False
+
+ # if 'Workbook' in dir():
+@@ -45,14 +45,14 @@
+ # else:
+ # IS_EXCEL = False
+
+-print 'IS_EXCEL', IS_EXCEL
++print('IS_EXCEL', IS_EXCEL)
+
+
+ def export_excel(filepath, obj, ids=None, attrconfigs=None, groupnames=None,
+ is_header=True, is_ident=False, is_timestamp=True,
+ show_parentesis=True, name_id='ID', is_export_not_save=True):
+
+- print 'export_excel' # ,attrconfigs,'groupnames',groupnames,
++ print('export_excel') # ,attrconfigs,'groupnames',groupnames,
+
+ wb = Workbook()
+ if (wb.worksheets) >= 1:
+@@ -78,7 +78,7 @@
+ tv = type(value)
+ if tv in cm.NODATATYPES:
+ value = str(value)
+- elif tv in (types.ListType, types.TupleType, np.ndarray):
++ elif tv in (list, tuple, np.ndarray):
+ value = str(value)
+
+ cell.value = value
+@@ -129,7 +129,7 @@
+
+ elif mt == 'id':
+ value = attrconf.get_linktab().format_ids([value])
+- elif tv in (types.ListType, types.TupleType, np.ndarray):
++ elif tv in (list, tuple, np.ndarray):
+ value = str(value)
+ cell.value = value
+ ind_col += 1
+@@ -141,7 +141,7 @@
+ def __init__(self, obj, ident='csvexporter', name='CSV exporter',
+ info='Export data from a CSV file into object',
+ logger=None, **kwargs):
+- print 'CsvExporter.__init__'
++ print('CsvExporter.__init__')
+ self._init_common(ident,
+ parent=obj,
+ name=name,
+@@ -187,7 +187,7 @@
+ # ))
+
+ def do(self):
+- print 'CsvExporter.do',
++ print('CsvExporter.do', end=' ')
+ obj = self.parent
+ attrsman = self.get_attrsman()
+ sep = self.sep
+--- tools/contributed/sumopy/agilepy/lib_base/geometry.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/geometry.py (refactored)
+@@ -118,7 +118,7 @@
+ pos_edge_pre = 0.0
+ x1, y1, z1 = polyline[0]
+
+- for j in xrange(1, len(polyline)):
++ for j in range(1, len(polyline)):
+ x2, y2, z2 = polyline[j]
+ seglength = np.linalg.norm([x2-x1, y2-y1])
+ pos_edge += seglength
+@@ -148,7 +148,7 @@
+ pos_edge_pre = 0.0
+ x1, y1, z1 = polyline[0]
+
+- for j in xrange(1, len(polyline)):
++ for j in range(1, len(polyline)):
+ x2, y2, z2 = polyline[j]
+ length = np.linalg.norm([x2-x1, y2-y1])
+ pos_edge += length
+@@ -174,7 +174,7 @@
+ pos_edge_pre = 0.0
+ x1, y1, z1 = polyline[0]
+
+- for j in xrange(1, len(polyline)):
++ for j in range(1, len(polyline)):
+ x2, y2, z2 = polyline[j]
+ length = np.linalg.norm([x2-x1, y2-y1])
+ pos_edge += length
+@@ -206,7 +206,7 @@
+ p_min = 0.0
+ pos = 0.0
+ x1, y1, z1 = polyline[0]
+- for j in xrange(1, n_segs):
++ for j in range(1, n_segs):
+ x2, y2, z2 = polyline[j]
+ d, xp, yp = shortest_dist(x1, y1, x2, y2, xc, yc)
+ # print ' x1,y1=(%d,%d)'%(x1,y1),',x2,y2=(%d,%d)'%(x2,y2),',xc,yc=(%d,%d)'%(xc,yc)
+@@ -629,7 +629,7 @@
+ out : np.ndarray
+ The difference between a1 and a2
+ """
+- print 'anglediffs', a1, a2
++ print('anglediffs', a1, a2)
+ return wrapanglediffs(a1 - a2, deg=deg)
+
+
+@@ -704,6 +704,6 @@
+ if __name__ == '__main__':
+ a1 = 0.0
+ a2 = +0.1
+- print 'a1', a1/np.pi*180
+- print 'a2', a2/np.pi*180
+- print 'anglediff(a1, a2)', anglediff(a1, a2)/np.pi*180
++ print('a1', a1/np.pi*180)
++ print('a2', a2/np.pi*180)
++ print('anglediff(a1, a2)', anglediff(a1, a2)/np.pi*180)
+--- tools/contributed/sumopy/agilepy/lib_base/imports.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/imports.py (refactored)
+@@ -31,7 +31,7 @@
+ def __init__(self, obj, ident='csvimporter', name='CSV importer',
+ info='Import data from a CSV file into object',
+ logger=None, **kwargs):
+- print 'CsvImporter.__init__'
++ print('CsvImporter.__init__')
+ self._init_common(ident,
+ parent=obj,
+ name=name,
+@@ -78,7 +78,7 @@
+ return 'colname_'+attrname
+
+ def do(self):
+- print 'CsvImporter.do',
++ print('CsvImporter.do', end=' ')
+ obj = self.parent
+ attrsman = self.get_attrsman()
+ sep = self.sep
+@@ -98,9 +98,9 @@
+ filepath = self.csvfilepath
+ f = open(filepath, 'r')
+
+- INTTYPES = (types.IntType, np.int, np.int32, np.int64)
+- FLOATTYPES = (types.FloatType, types.LongType, types.ComplexType, np.float, np.float32, np.float64)
+- BOOLTYPES = (types.BooleanType, np.bool_)
++ INTTYPES = (int, np.int, np.int32, np.int64)
++ FLOATTYPES = (float, int, complex, np.float, np.float32, np.float64)
++ BOOLTYPES = (bool, np.bool_)
+
+ #line = f.readline()
+ # print ' line[:-1] = *%s*'%(line[:-1],)
+@@ -146,7 +146,7 @@
+ for line in f.readlines():
+ cols = line.split(sep)
+ if len(cols) > ind_max: # restrictive!
+- for ind, vals, valtype in zip(index_to_value.keys(), index_to_value.values(), index_to_type.values()):
++ for ind, vals, valtype in zip(list(index_to_value.keys()), list(index_to_value.values()), list(index_to_type.values())):
+ val = cols[ind].strip()
+ if val not in emptycol:
+ if valtype == INTTYPE:
+@@ -173,7 +173,7 @@
+ n_imported += 1
+
+ ids = obj.add_rows(n_imported)
+- for ind, values in index_to_value.iteritems():
++ for ind, values in index_to_value.items():
+ getattr(obj, index_to_attrname[ind])[ids] = values
+
+ f.close()
+--- tools/contributed/sumopy/agilepy/lib_base/logger.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/logger.py (refactored)
+@@ -36,7 +36,7 @@
+ self._logfile = open(self._filepath, 'w')
+ self._logfile.write(ttext+'\n')
+ if self._is_stdout:
+- print text
++ print(text)
+
+ def add_callback(self, function, key='message'):
+ self._callbacks[key] = function
+@@ -62,13 +62,13 @@
+ if self._logfile is not None:
+ self._logfile.write(strftime(self._timeformat, gmtime())+' '+text+'\n')
+
+- elif self._callbacks.has_key(key):
++ elif key in self._callbacks:
+ kwargs['key'] = key
+ self._callbacks[key](data, **kwargs)
+ # elif type(data)==types.StringType:
+ # print data
+ if self._is_stdout:
+- print text
++ print(text)
+
+ def stop(self, text="End logging."):
+
+@@ -79,4 +79,4 @@
+ self._logfile = None
+
+ if self._is_stdout:
+- print text
++ print(text)
+--- tools/contributed/sumopy/agilepy/lib_base/misc.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/misc.py (refactored)
+@@ -47,7 +47,7 @@
+
+
+ def get_inversemap(m):
+- return {v: k for k, v in m.items()}
++ return {v: k for k, v in list(m.items())}
+
+
+ def random_choice_dist2(n, b):
+@@ -133,7 +133,7 @@
+
+
+ def filepathlist_to_filepathstring(filepathlist, sep=','):
+- if type(filepathlist) == types.ListType:
++ if type(filepathlist) == list:
+ if len(filepathlist) == 0:
+ return ''
+ else:
+@@ -157,7 +157,7 @@
+
+ def dict_to_str(d, intend=0):
+ s = ''
+- for key, value in d.iteritems():
++ for key, value in d.items():
+ s += intend*" "+"%s: %s\n" % (key, value)
+
+ return s
+--- tools/contributed/sumopy/agilepy/lib_base/processes.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/processes.py (refactored)
+@@ -30,8 +30,8 @@
+ #APPDIR = os.path.join(os.path.dirname(__file__),"..")
+
+
+-import classman as cm
+-from misc import filepathlist_to_filepathstring, filepathstring_to_filepathlist, ff, P
++from . import classman as cm
++from .misc import filepathlist_to_filepathstring, filepathstring_to_filepathlist, ff, P
+
+
+ # p = psutil.Process(the_pid_you_want) !!
+@@ -162,7 +162,7 @@
+ try:
+ f = open(filepath, 'wb')
+ except:
+- print 'WARNING in save: could not open', filepath
++ print('WARNING in save: could not open', filepath)
+ return False
+
+ # print ' before',is_not_save_parent,parent,obj.parent
+@@ -173,7 +173,7 @@
+ try:
+ f = open(filepath, 'rb')
+ except:
+- print 'WARNING in load_options: could not open', filepath
++ print('WARNING in load_options: could not open', filepath)
+ return None
+
+ # try:
+@@ -182,7 +182,7 @@
+ f.close()
+
+ attrsman = self.get_attrsman()
+- for attrname, value in optiondata.iteritems():
++ for attrname, value in optiondata.items():
+ if attrsman.has_attrname(attrname):
+ attrsman.get_config(attrname).set_value(value)
+
+@@ -197,7 +197,7 @@
+ self._cmlvaluemaps = []
+ self._transdir = {}
+ self._filepathattrs = []
+- for attr, value in kwargs.iteritems():
++ for attr, value in kwargs.items():
+ self.add_option(attr, value)
+
+ def add_option(self, attr='', value='', cml=None,
+@@ -231,7 +231,7 @@
+ cmlattr = self._transdir.get(attr, attr)
+ is_continue = True
+ if cmlvaluemap is not None:
+- if cmlvaluemap.has_key(value):
++ if value in cmlvaluemap:
+ is_continue = False # take value from mapping
+ if P == '"': # windows
+ s += ' '+cmlattr+' "%s"' % cmlvaluemap[value]
+@@ -244,10 +244,10 @@
+ if attr in self._filepathattrs:
+ if value != '':
+ s += ' '+cmlattr+' %s' % filepathlist_to_filepathstring(value.split(','))
+- elif type(value) == types.BooleanType:
++ elif type(value) == bool:
+ if value:
+ s += ' '+cmlattr
+- elif type(value) in [types.StringTypes, types.UnicodeType]:
++ elif type(value) in [(str,), str]:
+ if P == '"': # windows
+ s += ' '+cmlattr+' "%s"' % value
+ else:
+@@ -314,14 +314,14 @@
+ setattr(self, option, default)
+
+ def get_options(self):
+- print '\nget_options'
++ print('\nget_options')
+ options = Options()
+ for attrconfig in self.get_attrsman().get_configs(is_all=True):
+ if self.optiongroupname in attrconfig.groupnames:
+- print ' option', attrconfig.attrname, attrconfig.groupnames, 'is path', attrconfig.get_metatype() in self.pathmetatypes, 'has cmlmap', hasattr(attrconfig, 'cmlvaluemap')
++ print(' option', attrconfig.attrname, attrconfig.groupnames, 'is path', attrconfig.get_metatype() in self.pathmetatypes, 'has cmlmap', hasattr(attrconfig, 'cmlvaluemap'))
+ is_enabled = True
+ if hasattr(attrconfig, 'is_enabled'):
+- print ' is_enabled=', attrconfig.is_enabled(self), attrconfig.get_value()
++ print(' is_enabled=', attrconfig.is_enabled(self), attrconfig.get_value())
+ is_enabled = attrconfig.is_enabled(self)
+ if is_enabled: # disabeled options are simply not added
+ if hasattr(attrconfig, 'cmlvaluemap'):
+@@ -335,10 +335,10 @@
+ return options
+
+ def print_options(self):
+- print 'Options of process ident:', self.ident
+- print ' Keywordoptions:'
++ print('Options of process ident:', self.ident)
++ print(' Keywordoptions:')
+ for attrconfig in self.get_attrsman().get_configs(filtergroupnames=[self.optiongroupname]):
+- print ' ', attrconfig.attrname, '=', attrconfig.get_value()
++ print(' ', attrconfig.attrname, '=', attrconfig.get_value())
+
+ def reset_cml(self, cml):
+ self._command = cml
+@@ -352,7 +352,7 @@
+ # if self.workdirpath is not None
+ options = self.get_options()
+ optionstr = options.get_optionstring()
+- print 'get_cml command', self._command, 'workdirpath', self.workdirpath
++ print('get_cml command', self._command, 'workdirpath', self.workdirpath)
+ if True: # self.workdirpath is None:
+ if is_without_command:
+ cml = optionstr
+@@ -380,8 +380,8 @@
+
+ attrsman.pid.set(self._subprocess.pid)
+ attrsman.status.set('running')
+- print 'run_cml cml=', cml
+- print ' pid = ', self.pid, 'cwd', wd
++ print('run_cml cml=', cml)
++ print(' pid = ', self.pid, 'cwd', wd)
+ if not self.is_run_background:
+ self._subprocess.wait()
+ # if self.workdirpath is not None:
+--- tools/contributed/sumopy/agilepy/lib_base/test_classman_classes.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/test_classman_classes.py (refactored)
+@@ -21,37 +21,37 @@
+ Provides test classes and some test functions for plugin.
+ """
+
+-from classman import *
+-from arrayman import *
+-import xmlman as xm
++from .classman import *
++from .arrayman import *
++from . import xmlman as xm
+
+
+ def on_event_delattr(attrconfig):
+- print 'EVENT: Attribute', attrconfig.attrname, 'will be deleted!!'
++ print('EVENT: Attribute', attrconfig.attrname, 'will be deleted!!')
+
+
+ def on_event_setattr(attrconfig):
+- print 'EVENT: Attribute', attrconfig.attrname, 'has been set to a new value', attrconfig.format_value()
++ print('EVENT: Attribute', attrconfig.attrname, 'has been set to a new value', attrconfig.format_value())
+
+
+ def on_event_getattr(attrconfig):
+- print 'EVENT: Attribute', attrconfig.attrname, 'has been retrieved the value', attrconfig.format_value()
++ print('EVENT: Attribute', attrconfig.attrname, 'has been retrieved the value', attrconfig.format_value())
+
+
+ def on_event_additem(attrconfig, keys):
+- print 'EVENT: Attribute', attrconfig.attrname, ':added keys:', keys
++ print('EVENT: Attribute', attrconfig.attrname, ':added keys:', keys)
+
+
+ def on_event_delitem(attrconfig, keys):
+- print 'EVENT: Attribute', attrconfig.attrname, ':delete keys:', keys
++ print('EVENT: Attribute', attrconfig.attrname, ':delete keys:', keys)
+
+
+ def on_event_setitem(attrconfig, keys):
+- print 'EVENT: Attribute', attrconfig.attrname, ':set keys:', keys
++ print('EVENT: Attribute', attrconfig.attrname, ':set keys:', keys)
+
+
+ def on_event_getitem(attrconfig, keys):
+- print 'EVENT: Attribute', attrconfig.attrname, ':get keys:', keys
++ print('EVENT: Attribute', attrconfig.attrname, ':get keys:', keys)
+
+
+ class Segments(ArrayObjman):
+@@ -125,15 +125,15 @@
+ ]
+ """
+ vertices = []
+- print 'draw', self.ident
+- for i in xrange(1, len(pointvertices)):
++ print('draw', self.ident)
++ for i in range(1, len(pointvertices)):
+ vertices.append([pointvertices[i-1], pointvertices[i]])
+ n_vert = len(vertices)
+ _id = self.add_row(ids_osm=id_osm)
+ cod = []
+ #import string
+ clist = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'], np.object)
+- print ' ', len(vertices), clist[:len(vertices)]
++ print(' ', len(vertices), clist[:len(vertices)])
+ ids = self.segments.value.suggest_ids(len(vertices))
+ ids_segs = self.segments.value.add_rows(ids=ids, vertices=vertices, ids_parent=n_vert*[_id], ids_ref=clist[ids])
+ self.ids_segments[_id] = list(ids_segs) # put here list, otherwise numpy thinks it is a numeric array
+@@ -300,7 +300,7 @@
+ """
+ True if position greater than thhreshold.
+ """
+- print 'on_is_pos_ok', self.x > self.x_thresh
++ print('on_is_pos_ok', self.x > self.x_thresh)
+ return self.x > self.x_thresh
+
+
+@@ -331,7 +331,7 @@
+ self.child1 = attrsman.add(ObjConf(TestClass('child1', self))
+ )
+
+- print 'TestClass2.child1', self.child1
++ print('TestClass2.child1', self.child1)
+
+ self.child3 = attrsman.add(ObjConf(TestClass3('child3', self))
+ )
+@@ -368,7 +368,7 @@
+ attrsman.add_rows(5)
+ attrsman.streetname[3] = 'ssss'
+ attrsman.streetname[[1, 2]] = ['aa', 55]
+- print 'test get', attrsman.streetname[[1, 2]]
++ print('test get', attrsman.streetname[[1, 2]])
+ # self.streetname[1]+='zzz'
+ attrsman.del_rows([1, 3])
+ attrsman.del_row(5)
+@@ -485,9 +485,9 @@
+ """
+ True if position greater than thhreshold.
+ """
+- print 'on_del_row', id_row
++ print('on_del_row', id_row)
+ self.del_row(id_row)
+- print ' ids after del', self.get_ids()
++ print(' ids after del', self.get_ids())
+
+
+ class TestTableObjManNocols(TableObjman):
+--- tools/contributed/sumopy/agilepy/lib_base/test_classman_misc.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/test_classman_misc.py (refactored)
+@@ -17,7 +17,7 @@
+ # @date 2012
+
+
+-from classman import *
++from .classman import *
+ c = ColConf('streetname', 'xxx',
+ groupnames=['state'],
+ perm='rw',
+--- tools/contributed/sumopy/agilepy/lib_base/test_classman_save.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/test_classman_save.py (refactored)
+@@ -18,9 +18,9 @@
+
+ #from classman import *
+
+-from test_classman_classes import *
+-from arrayman import *
+-import xmlman as xm
++from .test_classman_classes import *
++from .arrayman import *
++from . import xmlman as xm
+ # TODOD: create a test object with all tests
+ is_all = 0
+
+@@ -105,17 +105,17 @@
+ # save/load
+ save_obj(lines, 'test_lines.obj')
+ del lines
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ lines = load_obj('test_lines.obj')
+ lines.print_attrs()
+
+- print 'direct access vertex=\n', lines.vertices.value
+- print 'direct access polygons=\n', lines.polygons.value
+- print 'id for index bb22=', lines.ids_sumo.get_id_from_index('bb22')
+- print 'ids for index bb22,cc333=', lines.ids_sumo.get_ids_from_indices(['bb22', 'cc333'])
++ print('direct access vertex=\n', lines.vertices.value)
++ print('direct access polygons=\n', lines.polygons.value)
++ print('id for index bb22=', lines.ids_sumo.get_id_from_index('bb22'))
++ print('ids for index bb22,cc333=', lines.ids_sumo.get_ids_from_indices(['bb22', 'cc333']))
+ lines.del_row(2)
+ lines.print_attrs()
+- print 'id for index bb22=', lines.ids_sumo.get_id_from_index('cc333')
++ print('id for index bb22=', lines.ids_sumo.get_id_from_index('cc333'))
+
+ if 0 | is_all:
+ class Lines(ArrayObjman):
+@@ -166,19 +166,19 @@
+ # lines.add_rows(3)
+ lines.add_rows(3, vertices=vertices, polygons=polygons)
+ lines.print_attrs()
+- print 'direct access vertex=\n', lines.vertices.value
+- print 'direct access polygons=\n', lines.polygons.value
++ print('direct access vertex=\n', lines.vertices.value)
++ print('direct access polygons=\n', lines.polygons.value)
+
+ # save/load
+ save_obj(lines, 'test_lines.obj')
+ del lines
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ lines = load_obj('test_lines.obj')
+
+ # print
+ lines.print_attrs()
+- print 'direct access vertex=\n', lines.vertices.value
+- print 'direct access polygons=\n', lines.polygons.value
++ print('direct access vertex=\n', lines.vertices.value)
++ print('direct access polygons=\n', lines.polygons.value)
+
+ vertices2 = [
+ [[0.0, 0.0, 0.0], [0.2, 0.0, 0.0]], # 0
+@@ -325,9 +325,9 @@
+ demand.get_attrsman().print_attrs()
+ odintervals.print_attrs()
+ for id_odmodes in odintervals.get_ids():
+- print '\nMODE:'
++ print('\nMODE:')
+ odintervals.odmodes[id_odmodes].print_attrs()
+- print '\nTRIPS:'
++ print('\nTRIPS:')
+ for id_odtrips in odmodes.get_ids():
+ odmodes.odtrips[id_odtrips].print_attrs()
+
+@@ -335,16 +335,16 @@
+ # save/load
+ save_obj(demand, 'test_demand_array.obj')
+ del demand
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ demand = load_obj('test_demand_array.obj')
+
+ # print
+ demand.get_attrsman().print_attrs()
+ odintervals.print_attrs()
+ for id_odmodes in odintervals.get_ids():
+- print '\nMODE:'
++ print('\nMODE:')
+ odintervals.odmodes[id_odmodes].print_attrs()
+- print '\nTRIPS:'
++ print('\nTRIPS:')
+ for id_odtrips in odmodes.get_ids():
+ odmodes.odtrips[id_odtrips].print_attrs()
+
+@@ -457,25 +457,25 @@
+ demand.get_attrsman().print_attrs()
+ odintervals.print_attrs()
+ for id_odmodes in odintervals.get_ids():
+- print '\nMODE:'
++ print('\nMODE:')
+ odintervals.odmodes[id_odmodes].print_attrs()
+- print '\nTRIPS:'
++ print('\nTRIPS:')
+ for id_odtrips in odmodes.get_ids():
+ odmodes.odtrips[id_odtrips].print_attrs()
+
+ # save/load
+ save_obj(demand, 'test_demand.obj')
+ del demand
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ demand = load_obj('test_demand.obj')
+
+ # print
+ demand.get_attrsman().print_attrs()
+ odintervals.print_attrs()
+ for id_odmodes in odintervals.get_ids():
+- print '\nMODE:'
++ print('\nMODE:')
+ odintervals.odmodes[id_odmodes].print_attrs()
+- print '\nTRIPS:'
++ print('\nTRIPS:')
+ for id_odtrips in odmodes.get_ids():
+ odmodes.odtrips[id_odtrips].print_attrs()
+
+@@ -534,7 +534,7 @@
+ net.nodes.print_attrs()
+ save_obj(net, 'test_net.obj')
+ del net
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ net_new = load_obj('test_net.obj')
+ net_new.get_attrsman().print_attrs()
+ net_new.edges.print_attrs()
+@@ -564,23 +564,23 @@
+ streetname=['a', 'bb', 'ccc', 'dddd'],
+ )
+
+- print 'direct access: tab1.surname.value', tab1.surname.value
+- print 'direct access: tab1.streetname.value', tab1.streetname.value
++ print('direct access: tab1.surname.value', tab1.surname.value)
++ print('direct access: tab1.streetname.value', tab1.streetname.value)
+ tab1.print_attrs()
+
+ save_obj(tab1, 'test_tab.obj')
+ del tab1
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ tab1_new = load_obj('test_tab.obj')
+ tab1_new.print_attrs()
+- print 'direct access: tab1_new.surname.value', tab1_new.surname.value
+- print 'direct access: tab1_new.streetname.value', tab1_new.streetname.value
++ print('direct access: tab1_new.surname.value', tab1_new.surname.value)
++ print('direct access: tab1_new.streetname.value', tab1_new.streetname.value)
+ if 0 | is_all:
+ tab1 = TableObjman('tab1')
+- print '\ntab1.ident', tab1.ident
++ print('\ntab1.ident', tab1.ident)
+
+ tab2 = TableObjman('tab2', parent=tab1)
+- print '\ntab2.ident', tab2.ident
++ print('\ntab2.ident', tab2.ident)
+
+ # TODO: seperate attrname from linked obj ident because restrictive and makes problems with multiple tab destinations
+ # this should be possible ...following the path of attrnames of absident
+@@ -620,24 +620,24 @@
+
+ save_obj(tab1, 'test_tab.obj')
+ del tab1
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ tab1_new = load_obj('test_tab.obj')
+
+ tab1_new.print_attrs()
+ tab2_new = tab1_new.tab2.get_valueobj()
+ tab2_new.print_attrs()
+- print tab2_new.get_ident_abs()
++ print(tab2_new.get_ident_abs())
+
+
+ if False | is_all: # False:#True:
+ obj = TestTabman()
+
+- print 'obj.ident', obj.ident
++ print('obj.ident', obj.ident)
+
+ obj.attrsman.print_attrs()
+ save_obj(obj, 'test_obj.obj')
+ del obj
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ obj_new = load_obj('test_obj.obj')
+ obj_new.attrsman.print_attrs()
+ # streetname
+@@ -648,7 +648,7 @@
+ if 0 | is_all: # False:#True: ###!!!!!!!!!!!!!!!!check this : failed to reload!!
+ obj = TestTableObjMan()
+
+- print 'obj.ident', obj.ident
++ print('obj.ident', obj.ident)
+
+ obj.x.set(1.0/3)
+ # obj.is_pos_ok.set(True)
+@@ -656,7 +656,7 @@
+ obj.print_attrs()
+ save_obj(obj, 'test_obj.obj')
+ del obj
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ obj_new = load_obj('test_obj.obj')
+ obj_new.x.set(2.0/3)
+ obj_new.print_attrs()
+@@ -667,12 +667,12 @@
+ #
+
+ if 0 | is_all:
+- print 'TestTableObjMan export'
++ print('TestTableObjMan export')
+ obj = TestTableObjMan()
+ obj.get_attrsman().print_attrs()
+ xm.write_obj_to_xml(obj, 'test_obj.xml')
+ del obj
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ obj_new = load_obj('test_obj.obj')
+ obj_new.get_attrsman().print_attrs()
+ # sys.exit()
+@@ -689,7 +689,7 @@
+ save_obj(obj2, 'test_obj2.obj')
+ xm.write_obj_to_xml(obj2, 'test_obj2.xml')
+ del obj2
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ obj2_new = load_obj('test_obj2.obj')
+ obj2_new.get_attrsman().print_attrs()
+
+@@ -699,9 +699,9 @@
+
+ if 0 | is_all: # False:#True:
+ obj = TestClass()
+- print 'obj.ident', obj.ident
+-
+- print 'This is the value of the attribute: obj.x=', obj.x
++ print('obj.ident', obj.ident)
++
++ print('This is the value of the attribute: obj.x=', obj.x)
+ # print 'This is the configuration instance of the attribute x',obj.attrsman.x
+ obj.get_attrsman().print_attrs()
+ # obj.get_attrsman().x.plugin.add_event(EVTSET,on_event_setattr)
+@@ -712,16 +712,16 @@
+ # print 'Test func...',obj.attrsman.testfunc.get()
+ # obj.get_attrsman().testfunc.add_event(EVTGET,on_event_getattr)
+ # obj.get_attrsman().testfunc.get()
+- print 'obj.get_attrsman().x.get()', obj.get_attrsman().x.get(), 'is_modified', obj.is_modified()
++ print('obj.get_attrsman().x.get()', obj.get_attrsman().x.get(), 'is_modified', obj.is_modified())
+ obj.get_attrsman().x.set(1.0)
+- print 'obj.get_attrsman().x.get()', obj.get_attrsman().x.get(), 'is_modified', obj.is_modified()
++ print('obj.get_attrsman().x.get()', obj.get_attrsman().x.get(), 'is_modified', obj.is_modified())
+
+ # obj.attrsman.delete('x')
+ obj.get_attrsman().print_attrs()
+ save_obj(obj, 'test_obj.obj')
+ xm.write_obj_to_xml(obj, 'test_obj.xml')
+ del obj
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ obj_new = load_obj('test_obj.obj')
+ obj_new.get_attrsman().print_attrs()
+ # print 'obj.get_attrsman().x.get_formatted()=',obj.get_attrsman().x.get_formatted()
+@@ -729,12 +729,12 @@
+
+ if 1 | is_all:
+ save_obj(drawing, 'test_drawing.obj')
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ obj_new = load_obj('test_drawing.obj')
+ obj_new.get_attrsman().print_attrs()
+
+ obj_new.collections.print_attrs()
+
+ tab_check, ids_check = obj_new.collections.tab_id_lists[1][1]
+- print ' check tab, ids=', tab_check, ids_check
++ print(' check tab, ids=', tab_check, ids_check)
+ tab_check.print_attrs()
+--- tools/contributed/sumopy/agilepy/lib_base/test_classman_tables.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/test_classman_tables.py (refactored)
+@@ -18,14 +18,14 @@
+
+ #from classman import *
+
+-from test_classman_classes import *
+-from classman import *
+-from arrayman import *
++from .test_classman_classes import *
++from .classman import *
++from .arrayman import *
+ is_all = 0
+ if 1 | is_all:
+ pass
+ if 1 | is_all:
+- print 'Lines, Poly example'
++ print('Lines, Poly example')
+
+ ###########################################################################
+ # Instance creation
+@@ -54,17 +54,17 @@
+ # lines.add_rows(3)
+ lines.add_rows(3, vertices=vertices, polygons=polygons, ids_sumo=ids_sumo)
+ lines.print_attrs()
+- print '\n indexmap', lines.ids_sumo.get_indexmap()
+- print 'direct access vertex=\n', lines.vertices.value
+- print 'id for index bb22=', lines.ids_sumo.get_id_from_index('bb22')
+- print 'ids for index bb22,cc333=', lines.ids_sumo.get_ids_from_indices(['bb22', 'cc333'])
++ print('\n indexmap', lines.ids_sumo.get_indexmap())
++ print('direct access vertex=\n', lines.vertices.value)
++ print('id for index bb22=', lines.ids_sumo.get_id_from_index('bb22'))
++ print('ids for index bb22,cc333=', lines.ids_sumo.get_ids_from_indices(['bb22', 'cc333']))
+ # lines.del_row(2)
+ lines.print_attrs()
+- print 'id for index bb22=', lines.ids_sumo.get_id_from_index('cc333')
++ print('id for index bb22=', lines.ids_sumo.get_id_from_index('cc333'))
+
+ lines.ids_sumo[2] = 'xy'
+
+- print '\n indexmap', lines.ids_sumo.get_indexmap()
++ print('\n indexmap', lines.ids_sumo.get_indexmap())
+ lines.print_attrs()
+ if 0 | is_all:
+ class Lines(TableObjman):
+@@ -124,13 +124,13 @@
+ # lines.add_rows(3)
+ lines.add_rows(3, vertices=vertices, polygons=polygons, ids_sumo=ids_sumo)
+ lines.print_attrs()
+- print 'direct access vertex=\n', lines.vertices.value
+- print 'direct access polygons=\n', lines.polygons.value
+- print 'id for index bb22=', lines.ids_sumo.get_id_from_index('bb22')
+- print 'ids for index bb22,cc333=', lines.ids_sumo.get_ids_from_indices(['bb22', 'cc333'])
++ print('direct access vertex=\n', lines.vertices.value)
++ print('direct access polygons=\n', lines.polygons.value)
++ print('id for index bb22=', lines.ids_sumo.get_id_from_index('bb22'))
++ print('ids for index bb22,cc333=', lines.ids_sumo.get_ids_from_indices(['bb22', 'cc333']))
+ lines.del_row(2)
+ lines.print_attrs()
+- print 'id for index bb22=', lines.ids_sumo.get_id_from_index('cc333')
++ print('id for index bb22=', lines.ids_sumo.get_id_from_index('cc333'))
+ if 0 | is_all:
+ class Lines(ArrayObjman):
+
+@@ -180,8 +180,8 @@
+ # lines.add_rows(3)
+ lines.add_rows(3, vertices=vertices, polygons=polygons)
+ lines.print_attrs()
+- print 'direct access vertex=\n', lines.vertices.value
+- print 'direct access polygons=\n', lines.polygons.value
++ print('direct access vertex=\n', lines.vertices.value)
++ print('direct access polygons=\n', lines.polygons.value)
+
+ if 0 | is_all:
+ class ZonesTab(ArrayObjman):
+@@ -292,9 +292,9 @@
+ odintervals.print_attrs()
+
+ for id_odmodes in odintervals.get_ids():
+- print '\nMODE:'
++ print('\nMODE:')
+ odintervals.odmodes[id_odmodes].print_attrs()
+- print '\nTRIPS:'
++ print('\nTRIPS:')
+ for id_odtrips in odmodes.get_ids():
+ odmodes.odtrips[id_odtrips].print_attrs()
+
+@@ -408,9 +408,9 @@
+ odintervals.print_attrs()
+
+ for id_odmodes in odintervals.get_ids():
+- print '\nMODE:'
++ print('\nMODE:')
+ odintervals.odmodes[id_odmodes].print_attrs()
+- print '\nTRIPS:'
++ print('\nTRIPS:')
+ for id_odtrips in odmodes.get_ids():
+ odmodes.odtrips[id_odtrips].print_attrs()
+
+@@ -483,16 +483,16 @@
+ streetname=['a', 'bb', 'ccc', 'dddd'],
+ )
+
+- print 'direct access: tab1.surname.value', tab1.surname.value
++ print('direct access: tab1.surname.value', tab1.surname.value)
+ tab1.print_attrs()
+
+ if 0 | is_all:
+
+ tab1 = TableObjman('tab1')
+- print '\ntab1.ident', tab1.ident
++ print('\ntab1.ident', tab1.ident)
+
+ tab2 = TableObjman('tab2', parent=tab1)
+- print '\ntab2.ident', tab2.ident
++ print('\ntab2.ident', tab2.ident)
+
+ # TODO: seperate attrname from linked obj ident because restrictive and makes problems with multiple tab destinations
+ # this should be possible ...following the path of attrnames of absident
+@@ -534,7 +534,7 @@
+ if 0 | is_all:
+ obj = TestTabman()
+
+- print '\nobj.ident', obj.ident
++ print('\nobj.ident', obj.ident)
+
+ # streetname
+ # print 'This is the value of the attribute: obj.streetname=',obj.streetname
+@@ -545,7 +545,7 @@
+ if 0 | is_all:
+ obj = TestTableObjMan()
+
+- print '\nobj.ident', obj.ident
++ print('\nobj.ident', obj.ident)
+
+ # streetname
+ # print 'This is the value of the attribute: obj.streetname=',obj.streetname
+--- tools/contributed/sumopy/agilepy/lib_base/xmlman.py (original)
++++ tools/contributed/sumopy/agilepy/lib_base/xmlman.py (refactored)
+@@ -31,7 +31,7 @@
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in write_obj_to_xml: could not open', filepath
++ print('WARNING in write_obj_to_xml: could not open', filepath)
+ return False
+ fd.write('\n' % encoding)
+ indent = 0
+@@ -81,7 +81,7 @@
+ if len(a) > 0:
+ format = '%s'
+ s += '%s="' % attr
+- for i in xrange(len(a)):
++ for i in range(len(a)):
+ # print ' a[i]',a[i],type(a[i]),str(a[i]),type(str(a[i]))
+ #ss = str(a[i])
+ # print ' ',type(s),type(ss),type(sep)
+@@ -101,9 +101,9 @@
+ s = ' '
+ if len(m) > 0:
+ s += '%s="' % attr
+- for i in xrange(len(m)):
++ for i in range(len(m)):
+ r = m[i]
+- for j in xrange(len(r)-1):
++ for j in range(len(r)-1):
+ s += '%s,' % r[j]
+ s += '%s ' % r[-1]
+ return s[:-1]+'"'
+--- tools/contributed/sumopy/agilepy/lib_misc/docgen.py (original)
++++ tools/contributed/sumopy/agilepy/lib_misc/docgen.py (refactored)
+@@ -29,7 +29,7 @@
+ ##
+
+ import numpy as np
+-from matplotlibtools import save_fig, init_plot
++from .matplotlibtools import save_fig, init_plot
+
+ # needed for doc gen + import numpy as np
+ from os import system, path, getcwd, chdir
+@@ -37,9 +37,9 @@
+
+ ##############################################################################
+ # convenience functions for Doc
+-ARRAYTYPES = (types.TupleType, np.ndarray, types.ListType, types.XRangeType)
+-INTTYPES = (types.IntType, np.int32, np.int64, np.int0, np.int16, np.int8, types.LongType)
+-FLOATTYPES = (types.FloatType, np.float64)
++ARRAYTYPES = (tuple, np.ndarray, list, range)
++INTTYPES = (int, np.int32, np.int64, np.int0, np.int16, np.int8, int)
++FLOATTYPES = (float, np.float64)
+
+
+ def is_arraytype(obj):
+@@ -322,8 +322,8 @@
+ n_row = len(matrix)
+ n_col = len(matrix[0])
+ self.begin_array(n_col, leftbrace, arraystretch)
+- for row in xrange(0, n_row):
+- for col in xrange(0, n_col):
++ for row in range(0, n_row):
++ for col in range(0, n_col):
+ # print ' ',col,row,matrix[row,col]
+ if col == (n_col-1):
+ sep = "\\\\ \n"
+@@ -340,7 +340,7 @@
+ n_row = len(vec)
+ sep = "\\\\ \n"
+ self.begin_array(1)
+- for col in xrange(0, n_row):
++ for col in range(0, n_row):
+ self._write_arrayelement(vec[col], sep, format_default=format, is_math=is_math)
+
+ self.end_array()
+@@ -349,7 +349,7 @@
+ n_row = len(vec)
+
+ self.begin_array(n_row)
+- for row in xrange(0, n_row):
++ for row in range(0, n_row):
+ # print ' ',col,row,matrix[row,col]
+ if row == (n_row-1):
+ sep = "\\\\ \n"
+@@ -400,7 +400,7 @@
+
+ def include_graphics(self, filename, options=None, is_centered=True,
+ method='matplotlib', label=None, caption=None, envoptions='h!'):
+- print 'include_graphics ', filename
++ print('include_graphics ', filename)
+ path_file = path.join(self.workdir, filename)
+ if options is None:
+ options = 'width = \\textwidth'
+@@ -459,7 +459,7 @@
+ self.f.write("""\\end{document}\n""")
+ self.f.close()
+ if self.is_compile:
+- print 'compile latex ', self.path_file
++ print('compile latex ', self.path_file)
+ system('pdflatex ' + self.path_file)
+
+
+--- tools/contributed/sumopy/agilepy/lib_wx/mainframe.py (original)
++++ tools/contributed/sumopy/agilepy/lib_wx/mainframe.py (refactored)
+@@ -25,13 +25,13 @@
+ import time
+ from collections import OrderedDict
+
+-from wxmisc import KEYMAP, AgileMenuMixin, AgileToolbarFrameMixin, AgileStatusbar, AgileMenubar
++from .wxmisc import KEYMAP, AgileMenuMixin, AgileToolbarFrameMixin, AgileStatusbar, AgileMenubar
+
+
+ from os.path import *
+ from os import getcwd
+
+-import objpanel
++from . import objpanel
+ from agilepy.lib_base.logger import Logger
+
+ # We first have to set an application-wide help provider. Normally you
+@@ -295,7 +295,7 @@
+ #################################################################
+ self._moduleguis = make_moduleguis(appdir, moduledirs)
+
+- for modulename, modulegui in self._moduleguis.iteritems():
++ for modulename, modulegui in self._moduleguis.items():
+ # print ' init gui of module',modulename
+ modulegui.init_widgets(self)
+ #################################################################
+@@ -311,7 +311,7 @@
+ def refresh_moduleguis(self):
+ # print 'refresh_moduleguis',len(self._moduleguis)
+ self.browse_obj(None)
+- for modulename, modulegui in self._moduleguis.iteritems():
++ for modulename, modulegui in self._moduleguis.items():
+ # print ' refresh gui of module',modulename
+ modulegui.refresh_widgets()
+
+@@ -392,12 +392,12 @@
+ # event.Skip()
+
+ def on_save(self, event):
+- print 'save it!!'
++ print('save it!!')
+
+ def on_open(self, event):
+ """Open a document"""
+ #wildcards = CreateWildCards() + "All files (*.*)|*.*"
+- print 'open it!!'
++ print('open it!!')
+
+ def destroy(self):
+ """Destroy this object"""
+@@ -408,7 +408,7 @@
+
+ def on_close(self, event):
+ # self.Close(True)
+- print 'Mainframe.on_close'
++ print('Mainframe.on_close')
+ # pass
+ self.destroy()
+
+--- tools/contributed/sumopy/agilepy/lib_wx/objbrowser.py (original)
++++ tools/contributed/sumopy/agilepy/lib_wx/objbrowser.py (refactored)
+@@ -17,8 +17,8 @@
+ # @date 2012
+
+ import wx
+-from objpanel import *
+-from mainframe import AgileMainframe, AgileStatusbar, AgileMenubar
++from .objpanel import *
++from .mainframe import AgileMainframe, AgileStatusbar, AgileMenubar
+
+
+ class ObjBrowserMainframe(AgileMainframe):
+--- tools/contributed/sumopy/agilepy/lib_wx/objpanel.py (original)
++++ tools/contributed/sumopy/agilepy/lib_wx/objpanel.py (refactored)
+@@ -23,7 +23,7 @@
+ import string
+ import random
+ from agilepy.lib_base.misc import filepathlist_to_filepathstring, filepathstring_to_filepathlist
+-from wxmisc import KEYMAP, AgilePopupMenu, AgileToolbarMixin, get_tablecolors
++from .wxmisc import KEYMAP, AgilePopupMenu, AgileToolbarMixin, get_tablecolors
+ import agilepy.lib_base.exports as ex
+ import time
+ from agilepy.lib_base.logger import Logger
+@@ -83,13 +83,13 @@
+ else:
+ s = lb
+ for e in l[:-1]:
+- s += unicode(e)+sep
++ s += str(e)+sep
+ # print ' returns',s+unicode(l[-1])+rb
+- return s+unicode(l[-1])+rb
++ return s+str(l[-1])+rb
+
+
+ def is_list_flat(l):
+- if type(l) not in (types.ListType, types.TupleType): # STRINGTYPES:
++ if type(l) not in (list, tuple): # STRINGTYPES:
+ # not a list
+ return False
+
+@@ -608,7 +608,7 @@
+ """
+ value = self.get_value_obj()
+ # strange way to convert numpy type numbers into native python numbers
+- if type(value) not in (types.IntType, types.LongType, types.FloatType, types.ComplexType):
++ if type(value) not in (int, int, float, complex):
+ value = value.tolist()
+ # print 'NumericWidgetContainer.get_valuewidget_write ',value,type(value),self._attrconf.digits_fraction
+
+@@ -725,7 +725,7 @@
+ # set value to label
+ # numpy returns dtype... even for scalars
+ # make sure to convert value in a native python scalar
+- if type(value) not in (types.IntType, types.LongType, types.FloatType):
++ if type(value) not in (int, int, float):
+ value = value.tolist()
+ self.valuewidget.SetValue(str(value))
+
+@@ -826,9 +826,9 @@
+ """
+ Generates the widgets representing this attribute.
+ """
+- if type(self._attrconf.choices) in (OrderedDict, types.DictionaryType):
+- self._choicevalues = self._attrconf.choices.values()
+- self._choicenames = self._attrconf.choices.keys()
++ if type(self._attrconf.choices) in (OrderedDict, dict):
++ self._choicevalues = list(self._attrconf.choices.values())
++ self._choicenames = list(self._attrconf.choices.keys())
+ else:
+ self._choicevalues = list(self._attrconf.choices)
+ self._choicenames = list(self._attrconf.choices)
+@@ -851,7 +851,7 @@
+ # print 'ChoiceWidgetContainer.get_valuewidget_read',value,type(value)
+ # print ' choices',self._attrconf.choices
+
+- if type(self._attrconf.choices) in (OrderedDict, types.DictionaryType):
++ if type(self._attrconf.choices) in (OrderedDict, dict):
+ #value = self._attrconf.choices[value]
+ value = self._choicenames[self._choicevalues.index(value)]
+ # print ' value =',value
+@@ -910,7 +910,7 @@
+ #ind = self._choicenames.index(value)
+ ind = self._choicevalues.index(val)
+ except:
+- print 'WARNING in ChoiceWidgetContainer.set_widgetvalue: %s with value "%s" not in choice list' % (self._attrconf.attrname, val)
++ print('WARNING in ChoiceWidgetContainer.set_widgetvalue: %s with value "%s" not in choice list' % (self._attrconf.attrname, val))
+ return
+ # print ' ind',ind,self.valuewidget
+ if self._attrconf.is_writable():
+@@ -936,7 +936,7 @@
+ # print ' choices',self._attrconf.choices
+
+ # mal values in list with .choices dictionary
+- if (len(values) > 0) & (type(self._attrconf.choices) in (OrderedDict, types.DictionaryType)):
++ if (len(values) > 0) & (type(self._attrconf.choices) in (OrderedDict, dict)):
+ #value = self._attrconf.choices[value]
+ values = []
+ for val in self.get_value_obj():
+@@ -1809,14 +1809,14 @@
+ return DatetimeWidgetContainer(self, attrconf, **args)
+
+ # elif mt == 'number':
+- if tt in (types.IntType, types.LongType):
++ if tt in (int, int):
+ return IntegerWidgetContainer(self, attrconf, **args)
+- elif tt in (types.FloatType, types.ComplexType):
++ elif tt in (float, complex):
+ return NumericWidgetContainer(self, attrconf, **args)
+
+ # check now native types
+
+- elif tt in (types.BooleanType,):
++ elif tt in (bool,):
+ return BooleanWidgetContainer(self, attrconf, **args)
+
+ elif tt in STRINGTYPES:
+@@ -1825,7 +1825,7 @@
+ # elif tt in (types.InstanceType,types.ClassType):
+ # return ObjWidgetContainer(self,attrconf,**args)
+
+- elif tt in (types.ListType, types.TupleType):
++ elif tt in (list, tuple):
+ return ListWidgetContainer(self, attrconf, **args)
+
+ else:
+@@ -2032,9 +2032,9 @@
+ if len(attrconf.choices) < 200:
+ # print ' choices=',attrconf.choices
+ # (types.ListType, types.TupleType):
+- if type(attrconf.choices) in (OrderedDict, types.DictionaryType):
++ if type(attrconf.choices) in (OrderedDict, dict):
+ # print ' GridCellChoiceEditor',attrconf.choices,':'+','.join(attrconf.choices.keys())
+- return gridlib.GRID_VALUE_CHOICE+':'+','.join(attrconf.choices.keys())
++ return gridlib.GRID_VALUE_CHOICE+':'+','.join(list(attrconf.choices.keys()))
+ else:
+ # print ' GridCellChoiceEditor',attrconf.choices,':'+','.join(attrconf.choices)
+ return gridlib.GRID_VALUE_CHOICE+':'+','.join(attrconf.choices)
+@@ -2062,9 +2062,9 @@
+ if len(attrconf.choices) < 200:
+ # print ' dir(gridlib)',dir(gridlib)
+ # (types.ListType, types.TupleType):
+- if type(attrconf.choices) in (OrderedDict, types.DictionaryType):
++ if type(attrconf.choices) in (OrderedDict, dict):
+ # print ' GridCellChoiceEditor',attrconf.choices,':'+','.join(attrconf.choices.keys())
+- return gridlib.GRID_VALUE_CHOICE+':'+','.join(attrconf.choices.keys())
++ return gridlib.GRID_VALUE_CHOICE+':'+','.join(list(attrconf.choices.keys()))
+ else:
+ # print ' GridCellChoiceEditor',attrconf.choices,':'+','.join(attrconf.choices)
+ return gridlib.GRID_VALUE_CHOICE+':'+','.join(attrconf.choices)
+@@ -2075,14 +2075,14 @@
+ else:
+ return gridlib.GRID_VALUE_STRING
+
+- elif tt in (types.LongType, types.IntType):
++ elif tt in (int, int):
+ if (hasattr(attrconf, 'min') & hasattr(attrconf, 'max')):
+ return gridlib.GRID_VALUE_NUMBER+':'\
+ + str(attrconf.min)+','+str(attrconf.max)
+ else:
+ return gridlib.GRID_VALUE_NUMBER
+
+- elif tt in (types.FloatType, types.ComplexType):
++ elif tt in (float, complex):
+ if (hasattr(attrconf, 'digits_integer') & hasattr(attrconf, 'digits_fraction')):
+ return gridlib.GRID_VALUE_FLOAT+':'\
+ + str(attrconf.digits_integer)+','\
+@@ -2093,7 +2093,7 @@
+ elif tt in STRINGTYPES:
+ return gridlib.GRID_VALUE_STRING
+
+- elif tt in (types.BooleanType,):
++ elif tt in (bool,):
+ return gridlib.GRID_VALUE_BOOL
+
+ else:
+@@ -2139,11 +2139,11 @@
+ # choices should no longer osed to index id
+ # instead, the format_ids method should be used
+ # (types.ListType, types.TupleType):
+- if type(attrconf.choices) in (OrderedDict, types.DictionaryType):
+- if attrconf.choices.values().count(val) > 0:
+- ind = attrconf.choices.values().index(val)
++ if type(attrconf.choices) in (OrderedDict, dict):
++ if list(attrconf.choices.values()).count(val) > 0:
++ ind = list(attrconf.choices.values()).index(val)
+ # print ' return',attrconf.choices.keys()[ind]
+- return attrconf.choices.keys()[ind]
++ return list(attrconf.choices.keys())[ind]
+ else:
+ return attrconf.get_linktab().format_ids([val])
+ else:
+@@ -2170,11 +2170,11 @@
+
+ elif hasattr(attrconf, 'choices'):
+ # print ' attrconf.choices',attrconf.choices
+- if type(attrconf.choices) in (OrderedDict, types.DictionaryType): # (types.ListType, types.TupleType):
+- if attrconf.choices.values().count(val) > 0:
+- ind = attrconf.choices.values().index(val)
++ if type(attrconf.choices) in (OrderedDict, dict): # (types.ListType, types.TupleType):
++ if list(attrconf.choices.values()).count(val) > 0:
++ ind = list(attrconf.choices.values()).index(val)
+ # print ' return',attrconf.choices.keys()[ind]
+- return attrconf.choices.keys()[ind]
++ return list(attrconf.choices.keys())[ind]
+ else:
+ return val
+ else:
+@@ -2249,9 +2249,9 @@
+ if hasattr(attrconf, 'choices'):
+ # print ' type(attrconf.choices)',type(attrconf.choices),type(attrconf.choices) in (OrderedDict, types.DictionaryType)
+ # (types.ListType, types.TupleType):
+- if type(attrconf.choices) in (OrderedDict, types.DictionaryType):
++ if type(attrconf.choices) in (OrderedDict, dict):
+ # print ' set choices[value]',attrconf.choices[value]
+- if attrconf.choices.has_key(value):
++ if value in attrconf.choices:
+ attrconf[id] = attrconf.choices[value]
+ else:
+ attrconf[id] = value
+@@ -2268,7 +2268,7 @@
+ attrconf[id] = value
+ else:
+ # TODO: for other types, like color or arrays, this must be done beforehand
+- print 'WARNING in SetValue: cannot write to this type:', tt
++ print('WARNING in SetValue: cannot write to this type:', tt)
+ else:
+ # readonly
+ pass
+@@ -2692,7 +2692,7 @@
+ if dlg.ShowModal() == wx.ID_OK:
+ # This returns a Python list of files that were selected.
+ path = dlg.GetPath()
+- print 'on_export_csv', type(path), path
++ print('on_export_csv', type(path), path)
+ if type(path) in STRINGTYPES:
+ self.tab.export_csv(path, sep=',',
+ attrconfigs=self.GetTable().get_valueconfigs(),
+@@ -2914,7 +2914,7 @@
+ table = self.GetTable()
+ id, attrconf = table.get_id_attrconf(event.GetRow(), event.GetCol())
+ #miniframe=DataMiniFrame( self, table.obj, id =id, attrs = [attr])
+- print 'on_edit_cell_miniframe EventObject=', id, attrconf
++ print('on_edit_cell_miniframe EventObject=', id, attrconf)
+ dlg = ObjPanelDialog(self, table.obj, id, attrconfigs=[attrconf], size=(350, 200),
+ #style = wxCAPTION | wxSYSTEM_MENU | wxTHICK_FRAME
+ func_apply=self.func_apply,
+@@ -2984,7 +2984,7 @@
+ evt.Skip()
+
+ def OnRightDown(self, event):
+- print "hello", self.GetSelectedRows()
++ print("hello", self.GetSelectedRows())
+
+ def apply(self):
+ """
+@@ -4315,7 +4315,7 @@
+ event.Skip()
+
+ def on_export_excel(self, event):
+- print 'on_export_excel'
++ print('on_export_excel')
+ obj = self.objpanel.get_obj()
+
+ #dirpath = self.get_scenario().get_workdirpath()
+@@ -4334,7 +4334,7 @@
+ return
+
+ def on_export_csv(self, event):
+- print 'on_export_csv'
++ print('on_export_csv')
+ obj = self.objpanel.get_obj()
+
+ #dirpath = self.get_scenario().get_workdirpath()
+@@ -4678,7 +4678,7 @@
+ if n_test == 0:
+ # simple scalar parameters, no table
+ obj = TestClass()
+- print 'obj.ident', obj.ident
++ print('obj.ident', obj.ident)
+
+ elif n_test == 1:
+ obj = TestTableObjMan()
+@@ -4699,7 +4699,7 @@
+ obj = drawing
+ elif n_test == -5:
+ save_obj(drawing, 'test_drawing.obj')
+- print '\nreload'+60*'.'
++ print('\nreload'+60*'.')
+ obj = load_obj('test_drawing.obj')
+ obj.get_attrsman().print_attrs()
+
+--- tools/contributed/sumopy/agilepy/lib_wx/ogleditor.py (original)
++++ tools/contributed/sumopy/agilepy/lib_wx/ogleditor.py (refactored)
+@@ -21,8 +21,8 @@
+ import types
+ import os
+ import sys
+-from toolbox import *
+-from wxmisc import *
++from .toolbox import *
++from .wxmisc import *
+ from agilepy.lib_base.geometry import *
+ import agilepy.lib_base.arrayman as am
+ import agilepy.lib_base.classman as cm
+@@ -44,7 +44,7 @@
+ use for debugging
+ python ogleditor.py --debug > debug.txt 2>&1
+ """
+- print __copyright__
++ print(__copyright__)
+
+ ###############################################################################
+ # IMPORTS
+@@ -63,7 +63,7 @@
+ import numpy as np
+
+ except ImportError:
+- raise ImportError, "Required dependencies numpy or OpenGL not present"
++ raise ImportError("Required dependencies numpy or OpenGL not present")
+
+ if __name__ == '__main__':
+ try:
+@@ -447,7 +447,7 @@
+ # calculate detectwidth based on current resolution
+ self.detectwidth = self._canvas.get_resolution()*self.detectpix
+
+- print 'pick_all', self.detectwidth, self.detectpix, self._canvas.get_resolution()
++ print('pick_all', self.detectwidth, self.detectpix, self._canvas.get_resolution())
+
+ self._idcounter = 0
+ is_draw = False
+@@ -1420,7 +1420,7 @@
+ """
+ Definively execute operation on currently selected drawobjects.
+ """
+- print 'Stretch', self.is_tool_allowed_on_selection()
++ print('Stretch', self.is_tool_allowed_on_selection())
+ if self.is_tool_allowed_on_selection():
+ if not self.is_animated:
+ return self.begin_animation(event)
+@@ -1792,7 +1792,7 @@
+ return self._vbos[ident]
+
+ def get_vbos(self):
+- return self._vbos.values()
++ return list(self._vbos.values())
+
+ def del_vbo(self, key):
+ del self._vbos[key]
+@@ -2649,7 +2649,7 @@
+
+ if is_fill:
+ self.add_vbo(Vbo('line_fill', GL_QUADS, 4, objtype='fill'))
+- for style in LINEHEADS.keys():
++ for style in list(LINEHEADS.keys()):
+ self.add_vbo(Vbo(('begin', 'fill', style), GL_TRIANGLES, 3, objtype='fill'))
+ self.add_vbo(Vbo(('end', 'fill', style), GL_TRIANGLES, 3, objtype='fill'))
+
+@@ -2826,7 +2826,7 @@
+ # print ' x1_new=',x1_new,x1_new.dtype
+ # print ' x2_new=',x2_new,x2_new.dtype
+ if self._is_fill.value:
+- for style, id_style in LINEHEADS.iteritems():
++ for style, id_style in LINEHEADS.items():
+
+ # begin
+ inds_style = np.flatnonzero(self.beginstyles.value == id_style)
+@@ -3235,7 +3235,7 @@
+ # print ' polyline\n',polyline
+
+ if n_seg > 1:
+- polyvinds = range(n_seg)
++ polyvinds = list(range(n_seg))
+ # print ' polyvinds\n',polyvinds
+ vi = np.zeros((2*n_seg-2), np.int32)
+ vi[0] = polyvinds[0]
+@@ -3251,7 +3251,7 @@
+
+ n_lines = len(v)/2
+ # print ' v\n',v
+- inds_polyline = range(ind_line, ind_line+n_lines)
++ inds_polyline = list(range(ind_line, ind_line+n_lines))
+
+ polyinds[inds_polyline] = ind
+
+@@ -3308,7 +3308,7 @@
+ # print ' x1_new=',x1_new,x1_new.dtype
+ # print ' x2_new=',x2_new,x2_new.dtype
+ if self._is_fill.value:
+- for style, id_style in LINEHEADS.iteritems():
++ for style, id_style in LINEHEADS.items():
+
+ # begin
+ inds_style = np.flatnonzero(self._linebeginstyles == id_style)
+@@ -3874,7 +3874,7 @@
+ # print ' ======='
+
+ # print ' polyline\n',polyline
+- polyvinds = range(len(polyline))
++ polyvinds = list(range(len(polyline)))
+ # print ' polyvinds\n',polyvinds
+ vi = np.zeros((2*len(polyline)), np.int32)
+ vi[0] = polyvinds[0]
+@@ -3893,7 +3893,7 @@
+ vi[1:-1] = np.repeat(polyvinds[1:], 2)
+ n_lines = len(v)/2
+ # print ' v\n',v
+- inds_polyline = range(ind_line, ind_line+n_lines)
++ inds_polyline = list(range(ind_line, ind_line+n_lines))
+
+ polyinds[inds_polyline] = ind
+ linevertices[inds_polyline] = v.reshape((-1, 2, 3))
+@@ -4274,7 +4274,7 @@
+ event.Skip()
+
+ def on_test(self, event=None):
+- print 'this is a test'
++ print('this is a test')
+
+
+ class OGLcanvas(glcanvas.GLCanvas):
+@@ -4523,7 +4523,7 @@
+ self.OnDraw(*args, **kwargs)
+ # print 'draw',self.lastx,self.lasty,self.x,self.y
+ except:
+- print 'WARNING in draw: unable to set context'
++ print('WARNING in draw: unable to set context')
+
+ def set_drawing(self, drawing):
+ if self._drawing != drawing:
+@@ -4884,7 +4884,7 @@
+ #wx.EVT_SIZE(self, self.on_size)
+
+ def on_test(self, event=None, drawing=None):
+- print '\non_test'
++ print('\non_test')
+
+ if drawing is None:
+ drawing = OGLdrawing()
+@@ -5016,7 +5016,7 @@
+ [[0.0, -2.0, 0.0], [-2.0, -2.0, 0.0], [-2.0, 0.0, 0.0]], # 1 red
+ ]
+
+- print ' vertices_polygon\n', vertices_poly
++ print(' vertices_polygon\n', vertices_poly)
+ polygons.add_drawobjs(vertices_poly,
+ colors_poly)
+ polygons.add_drawobj([[5.0, -2.0, 0.0], [3.0, -2.0, 0.0], [3.0, 0.0, 0.0]],
+@@ -5135,7 +5135,7 @@
+ ###############################################################################
+ # MAIN FRAME
+
+- from mainframe import AgileToolbarFrameMixin
++ from .mainframe import AgileToolbarFrameMixin
+
+ class OGLeditorMainframe(AgileToolbarFrameMixin, wx.Frame):
+ """
+@@ -5169,7 +5169,7 @@
+ # shortkey='Ctrl+t',info='Draw test objects')
+
+ def on_test(self, event=None):
+- print '\non_test'
++ print('\non_test')
+ vertices = np.array([
+ [[0.0, 0.0, 0.0], [0.2, 0.0, 0.0]], # 0 green
+ [[0.0, 0.0, 0.0], [0.0, 0.9, 0.0]], # 1 red
+@@ -5309,7 +5309,7 @@
+ [[0.0, -2.0, 0.0], [-2.0, -2.0, 0.0], [-2.0, 0.0, 0.0]], # 1 red
+ ]
+
+- print ' vertices_polygon\n', vertices_poly
++ print(' vertices_polygon\n', vertices_poly)
+ polygons.add_drawobjs(vertices_poly,
+ colors_poly)
+ polygons.add_drawobj([[5.0, -2.0, 0.0], [3.0, -2.0, 0.0], [3.0, 0.0, 0.0]],
+--- tools/contributed/sumopy/agilepy/lib_wx/processdialog.py (original)
++++ tools/contributed/sumopy/agilepy/lib_wx/processdialog.py (refactored)
+@@ -19,8 +19,8 @@
+
+ import wx
+ import os
+-import objpanel
+-from wxmisc import AgileStatusbar
++from . import objpanel
++from .wxmisc import AgileStatusbar
+
+
+ class ProcessDialogMixin:
+@@ -392,7 +392,7 @@
+ # print 'call step'
+ self.process.step()
+ else:
+- print ' Simulation finished'
++ print(' Simulation finished')
+ self.timer.Stop()
+
+ def on_stop(self, event=None):
+@@ -451,7 +451,7 @@
+ # self.Update()
+
+ def write_message(self, text, **kwargs):
+- print 'write_message', text
++ print('write_message', text)
+ self.statusbar.write_message(text)
+
+ def make_browser(self):
+--- tools/contributed/sumopy/agilepy/lib_wx/test_app.py (original)
++++ tools/contributed/sumopy/agilepy/lib_wx/test_app.py (refactored)
+@@ -16,8 +16,8 @@
+ # @author Joerg Schweizer
+ # @date 2012
+
+-from ogleditor import *
+-from mainframe import *
++from .ogleditor import *
++from .mainframe import *
+ import os
+ import sys
+
+@@ -31,11 +31,11 @@
+ except:
+ APPDIR = os.path.dirname(os.path.abspath(sys.argv[0]))
+ AGILEDIR = os.path.join(APPDIR, '..')
+- print 'APPDIR,AGILEDIR', APPDIR, AGILEDIR
++ print('APPDIR,AGILEDIR', APPDIR, AGILEDIR)
+ sys.path.append(AGILEDIR)
+ libpaths = [AGILEDIR, os.path.join(AGILEDIR, "lib_base"), os.path.join(AGILEDIR, "lib_wx"), ]
+ for libpath in libpaths:
+- print ' libpath=', libpath
++ print(' libpath=', libpath)
+ lp = os.path.abspath(libpath)
+ if not lp in sys.path:
+ # print ' append',lp
+@@ -108,15 +108,15 @@
+ shortkey='Ctrl+s', info='save it out')
+
+ def on_save(self, event):
+- print 'save it!!'
++ print('save it!!')
+
+ def on_open(self, event):
+ """Open a document"""
+ #wildcards = CreateWildCards() + "All files (*.*)|*.*"
+- print 'open it!!'
++ print('open it!!')
+
+ def on_test(self, event=None):
+- print '\non_test'
++ print('\non_test')
+ vertices = np.array([
+ [[0.0, 0.0, 0.0], [0.2, 0.0, 0.0]], # 0 green
+ [[0.0, 0.0, 0.0], [0.0, 0.9, 0.0]], # 1 red
+@@ -202,7 +202,7 @@
+ [[0.0, -2.0, 0.0], [-2.0, -2.0, 0.0], [-2.0, 0.0, 0.0]], # 1 red
+ ], np.object)
+
+- print ' vertices_polygon\n', vertices_poly
++ print(' vertices_polygon\n', vertices_poly)
+ polygons.add_drawobjs(vertices_poly,
+ colors_poly)
+ drawing.add_drawobj(polygons)
+--- tools/contributed/sumopy/agilepy/lib_wx/test_glcanvas.py (original)
++++ tools/contributed/sumopy/agilepy/lib_wx/test_glcanvas.py (refactored)
+@@ -25,9 +25,9 @@
+ #import wxversion
+ # wxversion.select('2.8')
+
+-import wxmisc
+-import objpanel
+-from wxmisc import *
++from . import wxmisc
++from . import objpanel
++from .wxmisc import *
+ import classman as cm
+ import math
+ import wx
+@@ -45,7 +45,7 @@
+ import numpy as np
+
+ except ImportError:
+- raise ImportError, "Required dependency OpenGL not present"
++ raise ImportError("Required dependency OpenGL not present")
+
+ import sys
+ import os
+@@ -280,7 +280,7 @@
+ Set handles to selected object sets which can be connected.
+ """
+ # put handles on all section objects
+- for name_set in self.targetsets.keys():
++ for name_set in list(self.targetsets.keys()):
+ self.metacanvas.set_handles(name_set=name_set)
+
+ def get_bitmap_from_file(self, name_bitmap):
+@@ -309,8 +309,8 @@
+ """
+ Called from options panel.
+ """
+- print 'set_options', self.ident
+- print ' event=', event
++ print('set_options', self.ident)
++ print(' event=', event)
+ pass
+
+ def set_statusbar(self, key, info):
+@@ -482,7 +482,7 @@
+ Returns lins with all toll instances
+ """
+ tools = []
+- for (tool, b) in self._id_to_tool.values():
++ for (tool, b) in list(self._id_to_tool.values()):
+ tools.append(tool)
+ return tools
+
+@@ -496,12 +496,12 @@
+ def on_select(self, event):
+
+ _id = event.GetEventObject().GetId()
+- print '\n on_select', _id, self._id # ,self._id_to_tool[_id]
++ print('\n on_select', _id, self._id) # ,self._id_to_tool[_id]
+ if _id != self._id:
+- if self._id_to_tool.has_key(_id):
++ if _id in self._id_to_tool:
+
+ (tool, button) = self._id_to_tool[_id]
+- print ' new tool', tool.get_name()
++ print(' new tool', tool.get_name())
+ self.unselect()
+ self._id = _id
+ self.GetParent().set_options(tool)
+@@ -512,7 +512,7 @@
+ """
+ Unselect currently selected tool.
+ """
+- if self._id_to_tool.has_key(self._id):
++ if self._id in self._id_to_tool:
+ (tool, button) = self._id_to_tool[self._id]
+ if hasattr(button, 'SetToggle'):
+ button.SetToggle(False)
+@@ -525,10 +525,10 @@
+ """
+ Select explicitelt a tool.
+ """
+- print '\n select', id, self._id, self._id_to_tool
++ print('\n select', id, self._id, self._id_to_tool)
+
+ if id != self._id:
+- if self._id_to_tool.has_key(id):
++ if id in self._id_to_tool:
+ # unselect previous
+ self.unselect()
+
+@@ -740,7 +740,7 @@
+ y = radius*math.cos(0)
+ glColor(0.0, 1.0, 0.0)
+ glBegin(GL_LINE_STRIP)
+- for deg in xrange(1000):
++ for deg in range(1000):
+ glVertex(x, y, 0.0)
+ rad = math.radians(deg)
+ radius -= 0.001
+@@ -757,7 +757,7 @@
+ x = radius*math.sin(0)
+ y = radius*math.cos(0)
+ glColor(1.0, 0.0, 0.0)
+- for deg in xrange(820):
++ for deg in range(820):
+ spiral_array.append([x, y])
+ rad = math.radians(deg)
+ radius -= 0.001
+@@ -805,7 +805,7 @@
+ y = event.GetY()
+
+ def OnDestroy(self, event):
+- print "Destroying Window"
++ print("Destroying Window")
+
+
+ class Lines:
+@@ -982,7 +982,7 @@
+ size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE,
+ name='frame', mainframe=None):
+
+- print '\n\nGLFrame!!'
++ print('\n\nGLFrame!!')
+ if mainframe is None:
+ self._mainframe = parent
+ else:
+@@ -1622,7 +1622,7 @@
+ pass
+
+ def OnSashChanging(self, evt):
+- print("sash changing to %s\n" % str(evt.GetSashPosition()))
++ print(("sash changing to %s\n" % str(evt.GetSashPosition())))
+ # uncomment this to not allow the change
+ # evt.SetSashPosition(-1)
+ # evt.SetSashPosition(210)
+@@ -1893,7 +1893,7 @@
+ return view
+
+ def on_size(self, event=None):
+- print 'Mainframe.on_size'
++ print('Mainframe.on_size')
+ # self.tc.SetSize(self.GetSize())
+ # self.tc.SetSize(self.GetSize())
+ # self._viewtabs.SetSize(self.GetSize())
+@@ -1908,12 +1908,12 @@
+ event.Skip()
+
+ def on_save(self, event):
+- print 'save it!!'
++ print('save it!!')
+
+ def on_open(self, event):
+ """Open a document"""
+ #wildcards = CreateWildCards() + "All files (*.*)|*.*"
+- print 'open it!!'
++ print('open it!!')
+
+ def destroy(self):
+ """Destroy this object"""
+--- tools/contributed/sumopy/agilepy/lib_wx/test_notebook.py (original)
++++ tools/contributed/sumopy/agilepy/lib_wx/test_notebook.py (refactored)
+@@ -111,14 +111,14 @@
+ old = event.GetOldSelection()
+ new = event.GetSelection()
+ sel = self.GetSelection()
+- print 'OnPageChanged, old:%d, new:%d, sel:%d\n' % (old, new, sel)
++ print('OnPageChanged, old:%d, new:%d, sel:%d\n' % (old, new, sel))
+ event.Skip()
+
+ def OnPageChanging(self, event):
+ old = event.GetOldSelection()
+ new = event.GetSelection()
+ sel = self.GetSelection()
+- print 'OnPageChanging, old:%d, new:%d, sel:%d\n' % (old, new, sel)
++ print('OnPageChanging, old:%d, new:%d, sel:%d\n' % (old, new, sel))
+ event.Skip()
+
+
+--- tools/contributed/sumopy/agilepy/lib_wx/toolbox.py (original)
++++ tools/contributed/sumopy/agilepy/lib_wx/toolbox.py (refactored)
+@@ -18,7 +18,7 @@
+
+ import agilepy.lib_base.arrayman as am
+ import agilepy.lib_base.classman as cm
+-from objpanel import ObjPanel, NaviPanel
++from .objpanel import ObjPanel, NaviPanel
+ from wx.lib.buttons import GenBitmapTextButton, GenBitmapButton
+ import wx
+ import sys
+@@ -260,14 +260,14 @@
+ # self.SetMaxSize((300,-1))
+
+ def has_tool(self, newtool):
+- for tool, b in self._id_to_tool.values():
++ for tool, b in list(self._id_to_tool.values()):
+ if tool.get_ident() == newtool.get_ident():
+ return True
+ return False
+
+ def get_tool_by_ident(self, ident):
+ # print 'get_tool_by_ident',ident
+- for tool, b in self._id_to_tool.values():
++ for tool, b in list(self._id_to_tool.values()):
+ # print ' tool',tool.get_ident()
+ if tool.get_ident() == ident:
+ return tool
+@@ -303,7 +303,7 @@
+ Returns lins with all toll instances
+ """
+ tools = []
+- for (tool, b) in self._id_to_tool.values():
++ for (tool, b) in list(self._id_to_tool.values()):
+ tools.append(tool)
+ return tools
+
+@@ -322,7 +322,7 @@
+ # print '\n on_select',_id,self._id#,self._id_to_tool[_id]
+
+ if _id != self._id:
+- if self._id_to_tool.has_key(_id):
++ if _id in self._id_to_tool:
+
+ (tool, button) = self._id_to_tool[_id]
+ # print ' new tool',tool.get_name()
+@@ -346,7 +346,7 @@
+ # print '\nselect',_id,self._id,self._id_to_tool
+
+ if _id != self._id:
+- if self._id_to_tool.has_key(_id):
++ if _id in self._id_to_tool:
+
+ (tool, button) = self._id_to_tool[_id]
+
+@@ -373,7 +373,7 @@
+ """
+ Unselect currently selected tool.
+ """
+- if self._id_to_tool.has_key(self._id):
++ if self._id in self._id_to_tool:
+ (tool, button) = self._id_to_tool[self._id]
+
+ if tool.is_active() == True:
+--- tools/contributed/sumopy/agilepy/lib_wx/wxmisc.py (original)
++++ tools/contributed/sumopy/agilepy/lib_wx/wxmisc.py (refactored)
+@@ -18,7 +18,7 @@
+
+
+ import zlib
+-import cPickle
++import pickle
+ import sys
+ import os
+ import types
+@@ -110,7 +110,7 @@
+ # print 'add_tool',self,key,func
+
+ id = wx.NewId()
+- if not args.has_key('name'):
++ if 'name' not in args:
+ name = string.capitalize(key)
+ else:
+ name = args['name']
+@@ -140,15 +140,15 @@
+ return id
+
+ def enable_tool(self, key, enable=True):
+- if self._tools.has_key(key):
++ if key in self._tools:
+ # self._tools[key].Show(False)
+ self.toolbar.EnableTool(self._tools[key], enable)
+
+ else:
+- print 'enable_tool: no tool named:', key
++ print('enable_tool: no tool named:', key)
+
+ def del_tool(self, key):
+- if self._tools.has_key(key):
++ if key in self._tools:
+ # self._tools[key].Show(False)
+ self.toolbar.RemoveTool(self._tools[key])
+ del self._tools[key]
+@@ -157,7 +157,7 @@
+ # causes it to render (more or less, that is).
+ self.toolbar.Realize()
+ else:
+- print 'del_tool: no tool named:', key
++ print('del_tool: no tool named:', key)
+
+
+ class AgileToolbarFrameMixin(AgileToolbarMixin):
+@@ -209,7 +209,7 @@
+ # print 'get_menu',path
+ for key in path:
+ # print ' ',key,items
+- if items.has_key(key):
++ if key in items:
+ val = items[key]
+ # print val
+ if len(val) == 3:
+@@ -217,7 +217,7 @@
+ else:
+ return None, None, -1
+ else:
+- print 'WARNING in get_menu: invalid menu key', key, 'in path'
++ print('WARNING in get_menu: invalid menu key', key, 'in path')
+ return None, None, -1
+
+ return val[0], val[1], val[2]
+@@ -279,7 +279,7 @@
+ # overwrite with args
+ data.update(args)
+
+- if not data.has_key('name'):
++ if 'name' not in data:
+ data['name'] = string.capitalize(key)
+
+ if data['alt']:
+@@ -332,7 +332,7 @@
+ # append item
+ # print ' menu',menu,type(menu),dir(menu)
+ menu.AppendItem(item)
+- if args.has_key('check'):
++ if 'check' in args:
+ menu.Check(item.GetId(), args['check'])
+ # if (args.has_key('check'))&(args.has_key('checked')):
+ # menu.Check(item.GetId(), args['checked'])
+@@ -340,7 +340,7 @@
+ menu_dict[key] = (item, id)
+ return item, id
+ else:
+- print 'WARNING: in append_item: invalid menu path', menupath
++ print('WARNING: in append_item: invalid menu path', menupath)
+ return None, None
+
+ def _create_item(self, key, menu, function=None, **args):
+@@ -353,10 +353,10 @@
+ # overwrite with args
+ data.update(args)
+
+- if not data.has_key('name'):
++ if 'name' not in data:
+ data['name'] = string.capitalize(key)
+
+- if not data.has_key('info'):
++ if 'info' not in data:
+ if function.__doc__ is not None:
+ data['info'] = function.__doc__.replace('\n', ' ').strip()
+ else:
+@@ -374,12 +374,12 @@
+ if data['shortkey'] != '':
+ itemtext += '\t'+data['shortkey']
+
+- if data.has_key('radio'):
++ if 'radio' in data:
+
+ item = wx.MenuItem(menu, id, itemtext, data['info'], wx.ITEM_RADIO)
+ # print ' radio item'
+
+- elif data.has_key('check'):
++ elif 'check' in data:
+ item = wx.MenuItem(menu, id, itemtext, data['info'], wx.ITEM_CHECK)
+ # check boxes AFTER append
+
+@@ -387,7 +387,7 @@
+ item = wx.MenuItem(menu, id, itemtext, data['info'], wx.ITEM_NORMAL)
+ # print ' normal item'
+
+- if data.has_key('bitmap'):
++ if 'bitmap' in data:
+ # print '_create_item bitmap',data['bitmap']
+ # TODO: allow more image formats in menuitem
+ # item.SetBitmap(images.getSmilesBitmap())
+@@ -406,7 +406,7 @@
+
+ menu, menu_dict, menuid = self.get_menu(menupath)
+ if menu:
+- if menu_dict.has_key(key):
++ if key in menu_dict:
+ menu.RemoveItem(menu_dict[key][0])
+ # menu_dict[key][0].Remove()
+ del menu_dict[key]
+@@ -429,9 +429,9 @@
+ def __setitem__(self, menupath, **data):
+ # print 'set menue',menupath,'to',data
+
+- if type(name) != types.TupleType:
++ if type(name) != tuple:
+ # create main menue entry, if necessary
+- if not self.menus.has_key(name):
++ if name not in self.menus:
+ newmenue = wx.Menu()
+ self.Append(newmenue, '&'+name)
+ self.menus[name] = (-1, {})
+@@ -439,14 +439,14 @@
+ elif len(name) == 2:
+ # create submenu entry, if necessary
+ name1, name2 = name
+- if not self.menus.has_key(name1):
++ if name1 not in self.menus:
+ newmenue = wx.Menu()
+ self.Append(newmenue, '&'+name1)
+ self.menus[name] = (-1, {})
+
+ menuid, submenus = self.menus[name1]
+
+- if not submenus.has_key(name2):
++ if name2 not in submenus:
+ id = wx.NewId()
+ get_menu_item()
+ newmenue = wx.Menu()
+@@ -456,7 +456,7 @@
+ submenu = self.menus
+ parentmenu = None
+ for m in menu:
+- if not submenu.has_key(m):
++ if m not in submenu:
+ newmenue = wx.Menu()
+
+ def get_menu_item(self, id):
+@@ -657,7 +657,7 @@
+ """
+ # print 'on_key_up'
+ self.del_keypress()
+- print ' key_pressed', self.key_pressed
++ print(' key_pressed', self.key_pressed)
+
+ def del_keypress(self):
+ """
+@@ -831,7 +831,7 @@
+ self.Update()
+
+ def has_key(self, key):
+- return self._ind_fields.has_key(key)
++ return key in self._ind_fields
+
+ def OnSize(self, evt):
+ self.Reposition() # for normal size events
+@@ -872,7 +872,7 @@
+ try:
+ return imgImages.catalog[name].getBitmap()
+ except:
+- print 'WARNING in get_bitmap: failed to return image', name
++ print('WARNING in get_bitmap: failed to return image', name)
+ return wx.NullBitmap
+
+
+@@ -880,7 +880,7 @@
+
+
+ def GetHandData():
+- return cPickle.loads(zlib.decompress(
++ return pickle.loads(zlib.decompress(
+ 'x\xda\xd3\xc8)0\xe4\nV72T\x00!\x05Cu\xae\xc4`u=\x85d\x05\xa7\x9c\xc4\xe4l0O\
+ \x01\xc8S\xb6t\x06A(\x1f\x0b\xa0\xa9\x8c\x9e\x1e6\x19\xa0\xa8\x1e\x88\xd4C\
+ \x97\xd1\x83\xe8\x80 \x9c2zh\xa6\xc1\x11X\n\xab\x8c\x02\x8a\x0cD!\x92\x12\
+@@ -895,7 +895,7 @@
+
+
+ def GetPlusData():
+- return cPickle.loads(zlib.decompress(
++ return pickle.loads(zlib.decompress(
+ 'x\xda\xd3\xc8)0\xe4\nV72T\x00!\x05Cu\xae\xc4`u=\x85d\x05\xa7\x9c\xc4\xe4l0O\
+ \x01\xc8S\xb6t\x06A(\x1f\x0b RF\x0f\x08\xb0\xc9@D\xe1r\x08\x19\xb8j=l2`\r\
+ \xe82HF\xe9a\xc8\xe8\xe9A\x9c@\x8a\x0c\x0e\xd3p\xbb\x00\x8f\xab\xe1>\xd5\xd3\
+@@ -910,7 +910,7 @@
+
+
+ def GetMinusData():
+- return cPickle.loads(zlib.decompress(
++ return pickle.loads(zlib.decompress(
+ 'x\xda\xd3\xc8)0\xe4\nV72T\x00!\x05Cu\xae\xc4`u=\x85d\x05\xa7\x9c\xc4\xe4l0O\
+ \x01\xc8S\xb6t\x06A(\x1f\x0b RF\x0f\x08\xb0\xc9@D\xe1r\x08\x19\xb8j=\xa2e\
+ \x10\x16@\x99\xc82zz\x10\'\x90"\x83\xc34r\xdc\x86\xf0\xa9\x9e\x1e\xae\xd0\
+--- tools/contributed/sumopy/coremodules/demand/__init__.py (original)
++++ tools/contributed/sumopy/coremodules/demand/__init__.py (refactored)
+@@ -18,12 +18,12 @@
+
+ __version__ = "0.0"
+
+-print 'init', __name__
++print('init', __name__)
+
+
+ def get_wxgui():
+ # try:
+- from wxgui import WxGui
++ from .wxgui import WxGui
+ return WxGui(__name__)
+ # except:
+ # return None
+--- tools/contributed/sumopy/coremodules/demand/demand.py (original)
++++ tools/contributed/sumopy/coremodules/demand/demand.py (refactored)
+@@ -16,14 +16,14 @@
+ # @author Joerg Schweizer
+ # @date 2012
+
+-import detectorflows
+-import turnflows
+-import virtualpop
+-import origin_to_destination
+-import vehicles
++from . import detectorflows
++from . import turnflows
++from . import virtualpop
++from . import origin_to_destination
++from . import vehicles
+ from coremodules.network.network import SumoIdsConf, MODES
+-from demandbase import *
+-import publictransportservices as pt
++from .demandbase import *
++from . import publictransportservices as pt
+ from coremodules.simulation import results as res
+ from coremodules.network import routing
+ from agilepy.lib_base.processes import Process
+@@ -69,7 +69,7 @@
+
+ class Demand(cm.BaseObjman):
+ def __init__(self, scenario=None, net=None, zones=None, name='Demand', info='Transport demand', **kwargs):
+- print 'Demand.__init__', name, kwargs
++ print('Demand.__init__', name, kwargs)
+
+ # we need a network from somewhere
+ if net is None:
+@@ -98,7 +98,7 @@
+ attrsman = self.get_attrsman()
+
+ scenario = self.parent
+- print 'Demand._init_attributes', scenario
++ print('Demand._init_attributes', scenario)
+
+ if scenario is not None:
+ self.detectorflows = attrsman.add(cm.ObjConf(detectorflows.Detectorflows('detectorflows', self),
+@@ -189,11 +189,11 @@
+ # for ident, conf in self.get_group_attrs('').iteritems():
+ # demandobjects.add(conf.get_value())
+ demandobjects_clean = []
+- for attrname, demandobject in self.get_attrsman().get_group_attrs('demand objects').iteritems():
++ for attrname, demandobject in self.get_attrsman().get_group_attrs('demand objects').items():
+ if demandobject is not None:
+ demandobjects_clean.append(demandobject)
+ else:
+- print 'WARNING in get_demandobjects: found None as object', attrname
++ print('WARNING in get_demandobjects: found None as object', attrname)
+ self.get_attrsman().delete(attrname)
+ return demandobjects_clean
+
+@@ -226,15 +226,15 @@
+
+ if filepath is None:
+ filepath = self.get_routefilepath()
+- print 'import_routes_xml', filepath, demandobjects
++ print('import_routes_xml', filepath, demandobjects)
+ try:
+ fd = open(filepath, 'r')
+ except:
+- print 'WARNING in import_routes_xml: could not open', filepath
++ print('WARNING in import_routes_xml: could not open', filepath)
+ return False
+
+ for demandobj in demandobjects:
+- print ' try to import routes from demandobj', demandobj
++ print(' try to import routes from demandobj', demandobj)
+ demandobj.import_routes_xml(filepath,
+ is_clear_trips=is_clear_trips,
+ is_generate_ids=is_generate_ids,
+@@ -259,11 +259,11 @@
+
+ if filepath is None:
+ filepath = self.get_routefilepath()
+- print 'export_routes_xml', filepath, demandobjects
++ print('export_routes_xml', filepath, demandobjects)
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in export_routes_xml: could not open', filepath
++ print('WARNING in export_routes_xml: could not open', filepath)
+ return False
+
+ fd.write('\n' % encoding)
+@@ -277,11 +277,11 @@
+
+ ids_vtype = set()
+ for exportobj in demandobjects:
+- print ' exportobj', exportobj
++ print(' exportobj', exportobj)
+ times, funcs, ids = exportobj.get_writexmlinfo(is_route=is_route,
+ is_plain=is_plain,
+ is_exclude_pedestrians=is_exclude_pedestrians)
+- print ' n_trips', len(times), 'has vtypes', hasattr(exportobj, 'get_vtypes')
++ print(' n_trips', len(times), 'has vtypes', hasattr(exportobj, 'get_vtypes'))
+ if len(times) > 0:
+ times_begin = np.concatenate((times_begin, times), 0)
+ writefuncs = np.concatenate((writefuncs, funcs), 0)
+@@ -630,7 +630,7 @@
+ """
+ Simple fastest path routing using duarouter.
+ """
+- print 'duaroute'
++ print('duaroute')
+ exectime_start = time.clock()
+
+ #routesattrname = self.get_routesattrname(routesindex)
+@@ -661,7 +661,7 @@
+ is_overwrite_only=True,
+ is_add=False)
+
+- print ' exectime', time.clock()-exectime_start
++ print(' exectime', time.clock()-exectime_start)
+ return routefilepath
+
+ else:
+@@ -677,7 +677,7 @@
+ """
+ Fastest path python router.
+ """
+- print 'route is_check_lanes', is_check_lanes
++ print('route is_check_lanes', is_check_lanes)
+ # TODO: if too mant vtypes, better go through id_modes
+ exectime_start = time.clock()
+
+@@ -697,7 +697,7 @@
+ # no routing for pedestrians
+ if id_mode != net.modes.get_id_mode('pedestrian'):
+ ids_trip_vtype = self.get_trips_for_vtype(id_vtype)
+- print ' id_vtype, id_mode', id_vtype, id_mode # ,ids_trip_vtype
++ print(' id_vtype, id_mode', id_vtype, id_mode) # ,ids_trip_vtype
+
+ weights = edges.get_times(id_mode=id_mode,
+ speed_max=vtypes.speeds_max[id_vtype],
+@@ -741,7 +741,7 @@
+ else:
+ self.add_routes(ids_trip, ids_route)
+
+- print ' exectime', time.clock()-exectime_start
++ print(' exectime', time.clock()-exectime_start)
+
+ if is_del_disconnected:
+ self.del_rows(ids_trip_disconnected)
+@@ -774,7 +774,7 @@
+ """
+ Import trips from another scenario.
+ """
+- print 'import_trips_from_scenario', scenario2.ident
++ print('import_trips_from_scenario', scenario2.ident)
+ if not is_pyproj:
+ print("WARNING in import_trips_from_scenario: pyproj module not installed")
+ return None
+@@ -841,7 +841,7 @@
+ proj_params2 = str(net2.get_projparams())
+
+ if (proj_params == '!') | (proj_params2 == '!'):
+- print 'WARNING in import_trips_from_scenario: unknown projections, use only offsets.', proj_params, proj_params2
++ print('WARNING in import_trips_from_scenario: unknown projections, use only offsets.', proj_params, proj_params2)
+ is_proj = False
+
+ elif proj_params == proj_params2:
+@@ -867,16 +867,16 @@
+
+ for id_mode in ids_modeset:
+ # make_segment_edge_map for all edges of this mode
+- print ' make segment_edge_map for mode', id_mode
++ print(' make segment_edge_map for mode', id_mode)
+ ids_edge_access, inds_lane_access = edges.select_accessible_mode(id_mode)
+- print ' found accessible edges', len(ids_edge_access), len(edges.get_ids())
++ print(' found accessible edges', len(ids_edge_access), len(edges.get_ids()))
+ # dict(zip(ids_edge,inds_lane))
+ edges.make_segment_edge_map(ids_edge_access)
+
+ # select trips with id_mode
+ ind_trips = np.flatnonzero(ids_mode == id_mode)
+
+- print ' number of trips for this mode:', len(ind_trips)
++ print(' number of trips for this mode:', len(ind_trips))
+ for id_trip, id_edge_depart2, id_edge_arrival2 in zip(ids_trips[ind_trips],
+ demand2.trips.ids_edge_depart[ids_trip2[ind_trips]],
+ demand2.trips.ids_edge_arrival[ids_trip2[ind_trips]]
+@@ -905,7 +905,7 @@
+ # check eucledian distance
+ #d = edges.get_dist_point_to_edge(coord, id_edge_depart)
+ # print ' id_edge_depart,d,id_mode',id_edge_depart,d,id_mode
+- print ' id_edge_depart', id_edge_depart, id_edge_depart in ids_edge_access
++ print(' id_edge_depart', id_edge_depart, id_edge_depart in ids_edge_access)
+
+ ids_edge_depart[id_trip] = id_edge_depart
+
+@@ -931,7 +931,7 @@
+
+ # check eucledian distance
+ #d = edges.get_dist_point_to_edge(coord, id_edge_arrival)
+- print ' id_edge_arrival', id_edge_arrival, id_edge_arrival in ids_edge_access
++ print(' id_edge_arrival', id_edge_arrival, id_edge_arrival in ids_edge_access)
+
+ ids_edge_arrival[id_trip] = id_edge_arrival
+
+@@ -957,7 +957,7 @@
+ else:
+ self.ids_sumo[id_trip] = kwargs.get('id_sumo', str(id_trip)) # id
+
+- if kwargs.has_key('route'):
++ if 'route' in kwargs:
+ route = kwargs['route']
+ if len(route) > 0:
+ id_route = self.routes.get_value().add_row(ids_trip=id_trip,
+@@ -969,7 +969,7 @@
+ return id_trip
+
+ def make_trips(self, ids_vtype, is_generate_ids=True, **kwargs):
+- print 'make_trips len(ids_vtype) =', len(ids_vtype)
++ print('make_trips len(ids_vtype) =', len(ids_vtype))
+ # print ' kwargs=',kwargs
+ ids_trip = self.add_rows(n=len(ids_vtype),
+ ids_vtype=ids_vtype,
+@@ -1002,28 +1002,28 @@
+
+ is_generate_ids: depricated, fully controlled by ids_trip
+ """
+- print 'make_routes is_generate_ids', ids_trip is None, 'is_add', is_add
++ print('make_routes is_generate_ids', ids_trip is None, 'is_add', is_add)
+ # print ' ids_trip',ids_trip
+
+ if ids_trip is None: # is_generate_ids = is_generate_ids,
+- print ' generate new trip IDs'
++ print(' generate new trip IDs')
+ ids_trip = self.make_trips(ids_vtype, is_generate_ids=is_generate_ids, **kwargs)
+ is_generate_ids = True
+ else:
+ if not is_add:
+- print ' replace current route and create if not existent'
++ print(' replace current route and create if not existent')
+ ids_routes = self.ids_route_current[ids_trip]
+ inds_new = np.flatnonzero(ids_routes == -1)
+ # print ' inds_new',inds_new
+ if len(inds_new) > 0:
+- print ' complete %d non pre-existant route ids of %d trips' % (len(inds_new), len(ids_trip))
++ print(' complete %d non pre-existant route ids of %d trips' % (len(inds_new), len(ids_trip)))
+ # create new routes
+ ids_routes[inds_new] = self.routes.get_value().add_rows(n=len(inds_new),
+ ids_trip=ids_trip[inds_new],
+ #ids_edges = routes[inds_new],
+ )
+ else:
+- print ' all new routes have pre-existing routes'
++ print(' all new routes have pre-existing routes')
+ else:
+ # make new route IDs
+ ids_routes = self.routes.get_value().add_rows(n=len(ids_trip),
+@@ -1032,14 +1032,14 @@
+ )
+
+ is_generate_ids = False
+- print ' set new routes to routes database', len(ids_routes), 'routes set'
++ print(' set new routes to routes database', len(ids_routes), 'routes set')
+ self.routes.get_value().ids_edges[ids_routes] = routes
+
+ if not is_add:
+- print ' replace current route IDs', len(inds_new), 'routes replaced'
++ print(' replace current route IDs', len(inds_new), 'routes replaced')
+ self.ids_route_current[ids_trip[inds_new]] = ids_routes[inds_new]
+ else:
+- print ' add new route IDs to alternatives', len(ids_trip), 'routes added'
++ print(' add new route IDs to alternatives', len(ids_trip), 'routes added')
+ self.add_routes(ids_trip, ids_routes)
+
+ # if np.any(ids_routes == -1):
+@@ -1047,7 +1047,7 @@
+
+ # print ' ids_trip =',ids_trip
+ if is_generate_ids:
+- print ' generate new route IDs'
++ print(' generate new route IDs')
+ ids_routes = self.routes.get_value().add_rows(n=len(ids_trip),
+ ids_trip=ids_trip,
+ #ids_edges = routes,
+@@ -1056,10 +1056,10 @@
+
+ # print ' ids_routes',ids_routes
+ if not is_add:
+- print ' set new current routes'
++ print(' set new current routes')
+ self.ids_route_current[ids_trip] = ids_routes
+ else:
+- print ' add new route IDs to alternatives'
++ print(' add new route IDs to alternatives')
+ self.add_routes(ids_trip, ids_routes)
+
+ # no!:self.ids_routes[ids_trip] = ids_routes.reshape((-1,1)).tolist()# this makes an array of lists
+@@ -1093,11 +1093,11 @@
+ """
+ if filepath is None:
+ filepath = self.get_tripfilepath()
+- print 'export_trips_xml', filepath
++ print('export_trips_xml', filepath)
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in write_obj_to_xml: could not open', filepath
++ print('WARNING in write_obj_to_xml: could not open', filepath)
+ return False
+
+ xmltag, xmltag_item, attrname_id = self.xmltag
+@@ -1315,7 +1315,7 @@
+ def import_routes_xml(self, filepath, is_clear_trips=False,
+ is_generate_ids=True, is_add=False,
+ is_overwrite_only=False):
+- print 'import_routes_xml from %s generate new routes %s, clear trips %s add trips %s' % (filepath, is_generate_ids, is_clear_trips, is_add)
++ print('import_routes_xml from %s generate new routes %s, clear trips %s add trips %s' % (filepath, is_generate_ids, is_clear_trips, is_add))
+ if is_clear_trips:
+ self.clear_trips()
+
+@@ -1324,28 +1324,28 @@
+ reader = RouteReader(self, counter)
+ try:
+ parse(filepath, reader)
+- print ' call insert_routes', is_generate_ids, 'is_add', is_add, 'is_overwrite_only', is_overwrite_only
++ print(' call insert_routes', is_generate_ids, 'is_add', is_add, 'is_overwrite_only', is_overwrite_only)
+ reader.insert_routes(is_generate_ids=is_generate_ids,
+ is_add=is_add, is_overwrite_only=is_overwrite_only)
+ except KeyError:
+- print >> sys.stderr, "Error: Problems with reading routes!"
++ print("Error: Problems with reading routes!", file=sys.stderr)
+ raise
+
+ def import_trips_xml(self, filepath, is_clear_trips=False, is_generate_ids=True):
+- print 'import_trips_xml from %s generate own trip ' % (filepath)
++ print('import_trips_xml from %s generate own trip ' % (filepath))
+ if is_clear_trips:
+ self.clear_trips()
+
+ counter = TripCounter()
+ parse(filepath, counter)
+ reader = TripReader(self, counter.n_trip)
+- print ' n_trip=', counter.n_trip
++ print(' n_trip=', counter.n_trip)
+
+ try:
+ parse(filepath, reader)
+ reader.insert_trips(is_generate_ids=is_generate_ids)
+ except KeyError:
+- print >> sys.stderr, "Error: Problems with reading trips!"
++ print("Error: Problems with reading trips!", file=sys.stderr)
+ raise
+
+ def config_results(self, results):
+@@ -1509,7 +1509,7 @@
+ #id_orig = self.ids_orig[id_od]
+ #id_dest = self.ids_dest[id_od]
+
+- print ' check id_zone', id_zone
++ print(' check id_zone', id_zone)
+ ids_edges_orig_raw = zones.ids_edges_orig[id_zone]
+
+ #prob_edges_orig_raw = zones.probs_edges_orig[id_orig]
+@@ -1519,7 +1519,7 @@
+ #prob_edges_orig = []
+ #inds_lane_orig = []
+
+- for i in xrange(len(ids_edges_orig_raw)):
++ for i in range(len(ids_edges_orig_raw)):
+ id_edge = ids_edges_orig_raw[i]
+ # if check accessibility...
+ ind_lane_depart_taxi = edges.get_laneindex_allowed(id_edge, id_mode_taxi)
+@@ -1534,14 +1534,14 @@
+
+ n_edges_orig = len(ids_edges_orig)
+
+- print '\n found', n_edges_orig, 'valid zone edges'
++ print('\n found', n_edges_orig, 'valid zone edges')
+
+ # now create taxi trips
+ if (n_edges_orig > 0) & (tripnumber > 0):
+ # normalize weights
+ edgeprops = np.zeros(n_edges_orig, dtype=np.float32)
+
+- for i, id_edge in zip(xrange(n_edges_orig), ids_edges_orig):
++ for i, id_edge in zip(range(n_edges_orig), ids_edges_orig):
+ edgeprops[i] = edgeprops_all[id_edge]
+
+ edgeprops = edgeprops/np.sum(edgeprops)
+@@ -1549,9 +1549,9 @@
+ # debug
+ if 0:
+ for id_edge, prob in zip(ids_edges_orig, edgeprops):
+- print ' orig id_edge', id_edge, 'has prob', prob
+-
+- for d in xrange(int(tripnumber+0.5)):
++ print(' orig id_edge', id_edge, 'has prob', prob)
++
++ for d in range(int(tripnumber+0.5)):
+ # print ' ------------'
+ # print ' generte trip',d
+ time_depart = np.random.uniform(time_start, time_end)
+@@ -1601,11 +1601,11 @@
+
+ n_trips_generated += 1
+
+- print ' n_trips_generated', n_trips_generated, 'of', self.n_taxi
++ print(' n_trips_generated', n_trips_generated, 'of', self.n_taxi)
+ return True
+
+ else:
+- print ' no taxi created n_edges_orig', n_edges_orig, 'tripnumber', tripnumber
++ print(' no taxi created n_edges_orig', n_edges_orig, 'tripnumber', tripnumber)
+ return False
+
+ def do(self):
+--- tools/contributed/sumopy/coremodules/demand/demandbase.py (original)
++++ tools/contributed/sumopy/coremodules/demand/demandbase.py (refactored)
+@@ -489,19 +489,19 @@
+ self.ids_vtype[self._ind_trip] = self._get_id_vtype(attrs)
+ self.times_depart[self._ind_trip] = int(float(attrs['depart']))
+
+- if attrs.has_key('from'):
++ if 'from' in attrs:
+ self.ids_edge_depart[self._ind_trip] = self._ids_edge_sumo.get_id_from_index(str(attrs['from']))
+- if attrs.has_key('to'):
++ if 'to' in attrs:
+ self.ids_edge_arrival[self._ind_trip] = self._ids_edge_sumo.get_id_from_index(str(attrs['to']))
+
+ ind_lane_depart_raw = attrs.get('departLane', 'free')
+- if OPTIONMAP_LANE_DEPART.has_key(ind_lane_depart_raw):
++ if ind_lane_depart_raw in OPTIONMAP_LANE_DEPART:
+ self.inds_lane_depart[self._ind_trip] = OPTIONMAP_LANE_DEPART[ind_lane_depart_raw]
+ else:
+ self.inds_lane_depart[self._ind_trip] = int(ind_lane_depart_raw)
+
+ positions_depart_raw = attrs.get('departPos', 'base')
+- if OPTIONMAP_POS_DEPARTURE.has_key(positions_depart_raw):
++ if positions_depart_raw in OPTIONMAP_POS_DEPARTURE:
+ self.positions_depart[self._ind_trip] = OPTIONMAP_POS_DEPARTURE[positions_depart_raw]
+ else:
+ self.positions_depart[self._ind_trip] = float(positions_depart_raw)
+@@ -509,13 +509,13 @@
+ self.speeds_depart[self._ind_trip] = attrs.get('departSpeed', 0.0)
+
+ ind_lane_arrival_raw = attrs.get('arrivalLane', 'current')
+- if OPTIONMAP_LANE_ARRIVAL.has_key(ind_lane_arrival_raw):
++ if ind_lane_arrival_raw in OPTIONMAP_LANE_ARRIVAL:
+ self.inds_lane_arrival[self._ind_trip] = OPTIONMAP_LANE_ARRIVAL[ind_lane_arrival_raw]
+ else:
+ self.inds_lane_arrival[self._ind_trip] = int(ind_lane_arrival_raw)
+
+ positions_arrival_raw = attrs.get('arrivalPos', 'max')
+- if OPTIONMAP_POS_ARRIVAL.has_key(positions_arrival_raw):
++ if positions_arrival_raw in OPTIONMAP_POS_ARRIVAL:
+ self.positions_arrival[self._ind_trip] = OPTIONMAP_POS_ARRIVAL[positions_arrival_raw]
+ else:
+ self.positions_arrival[self._ind_trip] = float(positions_arrival_raw)
+@@ -626,50 +626,50 @@
+ self.ids_vtype[self._ind_trip] = self.ids_vtype[self._ind_trip] = self._get_id_vtype(attrs)
+
+ self.times_depart[self._ind_trip] = int(float(attrs['depart']))
+- if attrs.has_key('arrival'):
++ if 'arrival' in attrs:
+ self.times_arrival[self._ind_trip] = int(float(attrs['arrival']))
+ else:
+ # duarouter is not calculating arrival time in results!
+ self.times_arrival[self._ind_trip] = 0.0
+
+ self.type[self._ind_trip] = attrs['type']
+- if attrs.has_key('from'):
++ if 'from' in attrs:
+ self.ids_edge_depart[self._ind_trip] = self._ids_edge_sumo.get_id_from_index(str(attrs['from']))
+- if attrs.has_key('to'):
++ if 'to' in attrs:
+ self.ids_edge_arrival[self._ind_trip] = self._ids_edge_sumo.get_id_from_index(str(attrs['to']))
+
+ ind_lane_depart_raw = attrs.get('departLane', 'free')
+- if OPTIONMAP_LANE_DEPART.has_key(ind_lane_depart_raw):
++ if ind_lane_depart_raw in OPTIONMAP_LANE_DEPART:
+ self.inds_lane_depart[self._ind_trip] = OPTIONMAP_LANE_DEPART[ind_lane_depart_raw]
+ else:
+ self.inds_lane_depart[self._ind_trip] = int(ind_lane_depart_raw)
+
+ positions_depart_raw = attrs.get('departPos', 'base')
+- if OPTIONMAP_POS_DEPARTURE.has_key(positions_depart_raw):
++ if positions_depart_raw in OPTIONMAP_POS_DEPARTURE:
+ self.positions_depart[self._ind_trip] = OPTIONMAP_POS_DEPARTURE[positions_depart_raw]
+ else:
+ self.positions_depart[self._ind_trip] = float(positions_depart_raw)
+
+ speed_depart_raw = attrs.get('departSpeed', 'max')
+- if OPTIONMAP_SPEED_DEPARTURE.has_key(speed_depart_raw):
++ if speed_depart_raw in OPTIONMAP_SPEED_DEPARTURE:
+ self.speeds_depart[self._ind_trip] = OPTIONMAP_SPEED_DEPARTURE[speed_depart_raw]
+ else:
+ self.speeds_depart[self._ind_trip] = float(speed_depart_raw)
+
+ ind_lane_arrival_raw = attrs.get('arrivalLane', 'current')
+- if OPTIONMAP_LANE_ARRIVAL.has_key(ind_lane_arrival_raw):
++ if ind_lane_arrival_raw in OPTIONMAP_LANE_ARRIVAL:
+ self.inds_lane_arrival[self._ind_trip] = OPTIONMAP_LANE_ARRIVAL[ind_lane_arrival_raw]
+ else:
+ self.inds_lane_arrival[self._ind_trip] = int(ind_lane_arrival_raw)
+
+ positions_arrival_raw = attrs.get('arrivalPos', 'max')
+- if OPTIONMAP_POS_ARRIVAL.has_key(positions_arrival_raw):
++ if positions_arrival_raw in OPTIONMAP_POS_ARRIVAL:
+ self.positions_arrival[self._ind_trip] = OPTIONMAP_POS_ARRIVAL[positions_arrival_raw]
+ else:
+ self.positions_arrival[self._ind_trip] = float(positions_arrival_raw)
+
+ speed_arrival_raw = attrs.get('arrivalSpeed', 'current')
+- if OPTIONMAP_SPEED_ARRIVAL.has_key(speed_arrival_raw):
++ if speed_arrival_raw in OPTIONMAP_SPEED_ARRIVAL:
+ self.speeds_arrival[self._ind_trip] = OPTIONMAP_SPEED_ARRIVAL[speed_arrival_raw]
+ else:
+ self.speeds_arrival[self._ind_trip] = float(speed_arrival_raw)
+@@ -735,7 +735,7 @@
+ }
+
+ def insert_routes(self, is_generate_ids=True, is_add=False, is_overwrite_only=False):
+- print 'TripReader.make_routes is_generate_ids', is_generate_ids, 'is_add', is_add, 'is_overwrite_only', is_overwrite_only
++ print('TripReader.make_routes is_generate_ids', is_generate_ids, 'is_add', is_add, 'is_overwrite_only', is_overwrite_only)
+
+ # self._trips is scenario trip database
+ # self.ids_sumo is a list of SUMO IDs read from xml file
+--- tools/contributed/sumopy/coremodules/demand/detectorflows.py (original)
++++ tools/contributed/sumopy/coremodules/demand/detectorflows.py (refactored)
+@@ -35,7 +35,7 @@
+ def __init__(self, ident='detectorflows', demand=None, name='Detector flows',
+ info='Flows measured by detectors, which can be used to generate vehicle routes using the DFRouter.',
+ **kwargs):
+- print 'Detectorflows.__init__', name, kwargs
++ print('Detectorflows.__init__', name, kwargs)
+
+ self._init_objman(ident=ident,
+ parent=demand,
+@@ -77,7 +77,7 @@
+ # more result attributes can be added ex. heavy duty flows
+ ])
+
+- for attrname, kwargs in attrinfos.iteritems():
++ for attrname, kwargs in attrinfos.items():
+ edgeresults.add_resultattr(attrname, **kwargs)
+
+ # reset Detector flow attributes
+@@ -197,7 +197,7 @@
+
+ ids = self.get_ids()
+ for id_detect, point, phi in zip(ids, self.coords[ids], self.directions[ids]/180.0*np.pi+np.pi/2.0):
+- print ' Detector id_detect', id_detect, 'point', point
++ print(' Detector id_detect', id_detect, 'point', point)
+ ids_edge_target, dists = get_closest_edge(point, n_best=n_targetedge,
+ d_max=d_max,
+ is_ending=True,
+@@ -206,15 +206,15 @@
+ accesslevels=accesslevels
+ )
+
+- print ' ids_edge_target', ids_edge_target
+- print ' dists', dists
++ print(' ids_edge_target', ids_edge_target)
++ print(' dists', dists)
+
+ if is_check_direction:
+ id_edge_found = -1
+ i = 0
+ n = len(ids_edge_target)
+ while (id_edge_found < 0) & (i < n):
+- print ' check ids_edge', ids_edge_target[i], dists[i]
++ print(' check ids_edge', ids_edge_target[i], dists[i])
+ dist_point_edge, segment = get_dist_point_to_edge(point, ids_edge_target[i],
+ is_ending=True,
+ is_detect_initial=False,
+@@ -235,9 +235,9 @@
+ if id_edge_found >= 0:
+ # select lane
+ ids_lane = edges.ids_lanes[id_edge_found]
+- print ' id_edge_found', id_edge_found, 'ids_lane', edges.ids_lanes[id_edge_found]
++ print(' id_edge_found', id_edge_found, 'ids_lane', edges.ids_lanes[id_edge_found])
+ ids_lane_access = ids_lane[lanes.get_laneindexes_allowed(ids_lane, id_mode)]
+- print ' ids_lane_access', ids_lane_access
++ print(' ids_lane_access', ids_lane_access)
+
+ if len(ids_lane_access) > 0:
+ if is_edgedetectors:
+@@ -253,7 +253,7 @@
+ #
+ # ... further detectors ...
+ #
+- print 'Detectors.write_xml'
++ print('Detectors.write_xml')
+ fd.write(xm.begin('detectors', indent))
+
+ ids = self.get_ids()
+@@ -265,7 +265,7 @@
+ self.positions[ids],
+ ):
+
+- print ' write id_detector', id_detector, 'ids_lane', ids_lane
++ print(' write id_detector', id_detector, 'ids_lane', ids_lane)
+ if ids_lane is not None:
+ ind_lane = 0
+ for id_lane in ids_lane:
+@@ -397,7 +397,7 @@
+
+ f.write('Detector'+sep+'Time'+sep+'qPKW'+sep+'qLKW'+sep+'vPKW'+sep+'vLKW'+'\n')
+ #ids_flow = self.select_ids(self.flows_passenger.get_value()>=0)
+- print ' flows_passenger', self.flows_passenger.get_value()
++ print(' flows_passenger', self.flows_passenger.get_value())
+ ids_flow = self.get_ids()
+ for id_detector, t, flow_passenger, flow_heavyduty, speed_passenger, speed_heavyduty in \
+ zip(
+@@ -410,11 +410,11 @@
+
+ ids_lane = detectors.ids_lanes[id_detector]
+ if (ids_lane is not None) & (flow_passenger >= 0):
+- print ' id_detector', id_detector, 't', t, 'flow_passenger', flow_passenger, len(ids_lane)
++ print(' id_detector', id_detector, 't', t, 'flow_passenger', flow_passenger, len(ids_lane))
+
+ n_lane = len(ids_lane)
+ for ind_lane, passengerflow_lane, heavyflow_lane in\
+- zip(xrange(n_lane),
++ zip(range(n_lane),
+ self.distribute_passengerflow_over_lanes(ids_lane, flow_passenger),
+ self.distribute_heavyflow_over_lanes(ids_lane, flow_heavyduty)
+ ):
+@@ -529,7 +529,7 @@
+ # myDet1;0;10;2;100;80
+ # ... further entries ...
+
+- print 'import_csv', filepath
++ print('import_csv', filepath)
+ ind_col = 0
+ cols = f.readline().strip()
+ ind_col = 0
+@@ -652,14 +652,14 @@
+ scenario.net.export_netxml()
+
+ ids_mode = self.get_modes()
+- print 'turnflows_to_routes', ids_mode # scenario.net.modes.get_ids()
+- print ' cmloptions', cmloptions
++ print('turnflows_to_routes', ids_mode) # scenario.net.modes.get_ids()
++ print(' cmloptions', cmloptions)
+
+ # route for all modes and read in routes
+ for id_mode in ids_mode:
+ # write flow and turns xml file for this mode
+ time_start, time_end = self.export_flows_and_turns(flowfilepath, turnfilepath, id_mode)
+- print ' time_start, time_end =', time_start, time_end
++ print(' time_start, time_end =', time_start, time_end)
+ if time_end > time_start: # means there exist some flows for this mode
+ cmd = 'jtrrouter --route-files=%s --turn-ratio-files=%s --net-file=%s --output-file=%s --begin %s --end %s %s'\
+ % (P+flowfilepath+P,
+@@ -677,7 +677,7 @@
+ os.remove(routefilepath)
+
+ else:
+- print 'jtrroute: no flows generated for id_mode', id_mode
++ print('jtrroute: no flows generated for id_mode', id_mode)
+
+ # self.simfiles.set_modified_data('rou',True)
+ # self.simfiles.set_modified_data('trip',True)
+@@ -686,7 +686,7 @@
+
+ class DetectorMatcher(Process):
+ def __init__(self, ident, detectors, logger=None, **kwargs):
+- print 'DetectorMatcher.__init__'
++ print('DetectorMatcher.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -703,12 +703,12 @@
+
+ self.modename = attrsman.add(cm.AttrConf('modename', kwargs.get('modename', 'passenger'),
+ groupnames=['options'],
+- choices=net.modes.names.get_indexmap().keys(),
++ choices=list(net.modes.names.get_indexmap().keys()),
+ name='Mode name',
+ info='Matched lanes must be accessible at least for this mode.',
+ ))
+
+- print 'net.modes.names.get_indexmap().keys()', net.modes.names.get_indexmap().keys(), self.modename
++ print('net.modes.names.get_indexmap().keys()', list(net.modes.names.get_indexmap().keys()), self.modename)
+
+ self.is_edgedetectors = attrsman.add(cm.AttrConf('is_edgedetectors', kwargs.get('is_edgedetectors', False),
+ groupnames=['options'],
+@@ -756,7 +756,7 @@
+ ))
+
+ def do(self):
+- print 'DetectorMatcher.do'
++ print('DetectorMatcher.do')
+ self.parent.match_detectors_to_lane(modename=self.modename,
+ is_edgedetectors=self.is_edgedetectors,
+ is_check_direction=self.is_check_direction,
+@@ -946,8 +946,8 @@
+ if self.is_export_network:
+ scenario.net.export_netxml()
+
+- print 'DFRouter.do'
+- print ' cmloptions', cmloptions
++ print('DFRouter.do')
++ print(' cmloptions', cmloptions)
+
+ # dfrouter --net-file bonet190614_ms_dflows.net --routes-output bonet190614_ms_dflows.rou.xml --emitters-output vehicles.xml --detector-files detectors.xml --measure-files bonet190614_ms_dflows.dflows2.csv
+ cmd = cmloptions + ' --net-file %s --detector-files %s --measure-files %s --routes-output %s --emitters-output %s'\
+--- tools/contributed/sumopy/coremodules/demand/detectorflows_wxgui.py (original)
++++ tools/contributed/sumopy/coremodules/demand/detectorflows_wxgui.py (refactored)
+@@ -24,7 +24,7 @@
+ from agilepy.lib_base.processes import Process
+ from agilepy.lib_wx.processdialog import ProcessDialog
+ from coremodules.network.network import SumoIdsConf, MODES
+-import detectorflows
++from . import detectorflows
+
+
+ class DetectorflowsWxGuiMixin:
+--- tools/contributed/sumopy/coremodules/demand/origin_to_destination.py (original)
++++ tools/contributed/sumopy/coremodules/demand/origin_to_destination.py (refactored)
+@@ -27,8 +27,8 @@
+ from coremodules.network import routing
+ from agilepy.lib_base.processes import Process, CmlMixin
+
+-import demand as dm
+-import demandbase as db
++from . import demand as dm
++from . import demandbase as db
+ from agilepy.lib_base.geometry import is_polyline_intersect_polygon
+
+
+@@ -220,7 +220,7 @@
+
+ def _get_fstar(self, id_mode, is_return_arrays=True, is_ignor_connections=False):
+
+- if not self._fstars.has_key(id_mode):
++ if id_mode not in self._fstars:
+ self._fstars[id_mode] = self.get_edges().get_fstar(id_mode,
+ is_ignor_connections=is_ignor_connections,
+ is_return_arrays=is_return_arrays,)
+@@ -228,7 +228,7 @@
+
+ def _get_times(self, id_mode, is_check_lanes=False):
+
+- if not self._times.has_key(id_mode):
++ if id_mode not in self._times:
+ self._times[id_mode] = self.get_edges().get_times(id_mode=id_mode,
+ is_check_lanes=is_check_lanes,
+ )
+@@ -239,10 +239,10 @@
+ priority_max, speed_max,
+ id_mode_fallback=None):
+
+- if not self._mode_to_edgeinfo.has_key(id_mode):
++ if id_mode not in self._mode_to_edgeinfo:
+ self._mode_to_edgeinfo[id_mode] = {}
+
+- if not self._mode_to_edgeinfo[id_mode].has_key(id_zone):
++ if id_zone not in self._mode_to_edgeinfo[id_mode]:
+ zones = self.get_zones()
+ ids_edge = zones.get_zoneedges_by_mode_fast(id_zone, id_mode,
+ weights=self._get_times(id_mode),
+@@ -277,7 +277,7 @@
+ self.del_row(id_row)
+
+ def on_add_row(self, id_row=None):
+- print 'on_add_row'
++ print('on_add_row')
+ if len(self) > 0:
+
+ # copy previous
+@@ -324,7 +324,7 @@
+ """
+ Generates trips in demand.trip table.
+ """
+- print 'generate_trips', time_start, time_end, 'id_mode_primary', id_mode_primary, 'id_mode_fallback', id_mode_fallback
++ print('generate_trips', time_start, time_end, 'id_mode_primary', id_mode_primary, 'id_mode_fallback', id_mode_fallback)
+ id_mode_ped = MODES['pedestrian']
+ zones = self.get_zones()
+ edges = self.get_edges()
+@@ -352,7 +352,7 @@
+ # in case there is a secondary mode, the secondary mode is chosen
+ ids_vtype_mode_primary, prob_vtype_mode_primary = demand.vtypes.select_by_mode(
+ id_mode_primary, is_share=True)
+- print ' ids_vtype_mode_primary', ids_vtype_mode_primary, prob_vtype_mode_primary
++ print(' ids_vtype_mode_primary', ids_vtype_mode_primary, prob_vtype_mode_primary)
+ n_vtypes_primary = len(ids_vtype_mode_primary)
+
+ n_vtypes_fallback = 0
+@@ -368,7 +368,7 @@
+ is_fallback = False
+ # print ' n_vtypes_primary',n_vtypes_primary,'n_vtypes_fallback',n_vtypes_fallback,'is_fallback',is_fallback
+ if n_vtypes_primary == 0:
+- print 'WARNING: no vehicle types for this mode with ID', id_mode_primary
++ print('WARNING: no vehicle types for this mode with ID', id_mode_primary)
+ return False
+
+ ids_od = self.get_ids()
+@@ -378,7 +378,7 @@
+ np.array(self.tripnumbers[ids_od]+random.rand(len(ids_od)), dtype=np.int32),
+ ):
+
+- print ' generate', tripnumber, ' trips from id_orig', id_orig, 'to id_dest', id_dest
++ print(' generate', tripnumber, ' trips from id_orig', id_orig, 'to id_dest', id_dest)
+
+ ids_edge_orig, weights_orig = self.get_zone_edgeinfo(
+ id_mode_primary, id_orig, n_edges_min_length, n_edges_max_length, priority_max, speed_max)
+@@ -390,7 +390,7 @@
+ # print ' n_edges_orig',n_edges_orig,len(weights_orig),'n_edges_dest',n_edges_dest,len(weights_dest)
+
+ if 1: # (n_edges_orig > 0) & (n_edges_dest > 0):
+- for i_trip in xrange(tripnumber):
++ for i_trip in range(tripnumber):
+
+ time_depart = random.uniform(time_start, time_end)
+
+@@ -414,9 +414,9 @@
+
+ n_trips_generated += 1
+
+- print ' -----'
+- print ' n_trips_generated', n_trips_generated
+- print ' n_trips_failed', np.sum(self.tripnumbers[ids_od])-n_trips_generated
++ print(' -----')
++ print(' n_trips_generated', n_trips_generated)
++ print(' n_trips_failed', np.sum(self.tripnumbers[ids_od])-n_trips_generated)
+ return True
+
+ def add_od_trips(self, scale, names_orig, names_dest, tripnumbers,
+@@ -428,7 +428,7 @@
+ is_filter_cross = len(ids_zone_cross_filter) > 0
+ is_dist_min = dist_min > 0
+ is_dist_max = dist_max > 0
+- print 'OdTrips.add_od_trips', is_filter_orig, is_filter_dest, is_filter_cross
++ print('OdTrips.add_od_trips', is_filter_orig, is_filter_dest, is_filter_cross)
+ # print ' filter',ids_zone_orig_filter,ids_zone_dest_filter
+ # print ' scale, names_orig, names_dest, tripnumbers',scale, names_orig, names_dest, tripnumbers,len(tripnumbers)
+ zones = self.get_zones()
+@@ -477,15 +477,15 @@
+ else:
+ n_trips_scale_fin = int(n_trips_scale_int + 1)
+ # -----
+- print ' add from', name_orig, 'to', name_dest, 'tripnumber', n_trips_scale_fin
++ print(' add from', name_orig, 'to', name_dest, 'tripnumber', n_trips_scale_fin)
+
+ self.add_row(ids_orig=id_zone_orig,
+ ids_dest=id_zone_dest,
+ tripnumbers=n_trips_scale_fin) # prima c'era (tripnumbers = scale*tripnumber)
+ else:
+ if not ((zones.ids_sumo.has_index(name_orig)) & (zones.ids_sumo.has_index(name_dest))):
+- print ' WARNING: zone named %s or %s not known' % (
+- name_orig, name_dest)
++ print(' WARNING: zone named %s or %s not known' % (
++ name_orig, name_dest))
+ # print ' zones indexmap', zones.get_indexmap()
+ # print ' ids_sumo', zones.ids_sumo.get_value()
+ # print ' ids_sumo._index_to_id', zones.ids_sumo._index_to_id
+@@ -678,7 +678,7 @@
+ """
+ Export flows to Amitran format that defines the demand per OD pair in time slices for every vehicle type.
+ """
+- print 'export_amitranxml', filepath, len(self)
++ print('export_amitranxml', filepath, len(self))
+
+ if len(self) == 0:
+ return None
+@@ -689,7 +689,7 @@
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in export_sumoxml: could not open', filepath
++ print('WARNING in export_sumoxml: could not open', filepath)
+ return False
+
+ indent = 0
+@@ -745,7 +745,7 @@
+ """
+ Export flows to SUMO xml file formate.
+ """
+- print 'export_sumoxml', filepath, len(self)
++ print('export_sumoxml', filepath, len(self))
+ if len(self) == 0:
+ return None
+
+@@ -755,7 +755,7 @@
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in export_sumoxml: could not open', filepath
++ print('WARNING in export_sumoxml: could not open', filepath)
+ return False
+ #xmltag, xmltag_item, attrname_id = self.xmltag
+ #fd.write('\n'%encoding)
+--- tools/contributed/sumopy/coremodules/demand/origin_to_destination_mpl.py (original)
++++ tools/contributed/sumopy/coremodules/demand/origin_to_destination_mpl.py (refactored)
+@@ -33,7 +33,7 @@
+
+ class OdPlots(PlotoptionsMixin, Process):
+ def __init__(self, ident, demand, logger=None, **kwargs):
+- print 'OdPlots.__init__'
++ print('OdPlots.__init__')
+ self._init_common(ident,
+ parent=demand,
+ name='OD plots',
+@@ -70,7 +70,7 @@
+ intervalchoices[str(int(time_start/60.0))+'min-'+str(int(time_end/60.0)) +
+ 'min'] = (int(time_start), int(time_end))
+
+- self.intervals = attrsman.add(cm.ListConf('intervals', intervalchoices.values(),
++ self.intervals = attrsman.add(cm.ListConf('intervals', list(intervalchoices.values()),
+ groupnames=['options'],
+ choices=intervalchoices,
+ name='Intervals',
+@@ -155,7 +155,7 @@
+ self.add_save_options(**kwargs)
+
+ def show(self):
+- print 'OdPlots.show'
++ print('OdPlots.show')
+ # if self.axis is None:
+ scenario = self.parent.get_scenario()
+ zones = scenario.landuse.zones
+@@ -192,7 +192,7 @@
+ outflows[id_zone_orig] += n_trips
+ inflows[id_zone_dest] += n_trips
+ od = (id_zone_orig, id_zone_dest)
+- if odflows.has_key(od):
++ if od in odflows:
+ odflows[od] += n_trips
+ else:
+ odflows[od] = n_trips
+@@ -201,7 +201,7 @@
+ balance[id_zone] = inflows[id_zone] - outflows[id_zone]
+ totals[id_zone] = inflows[id_zone] + outflows[id_zone]
+ # debug
+- print ' id_zone', id_zone, 'in', inflows[id_zone], 'out', outflows[id_zone], 'balance', balance[id_zone], 'totals', totals[id_zone]
++ print(' id_zone', id_zone, 'in', inflows[id_zone], 'out', outflows[id_zone], 'balance', balance[id_zone], 'totals', totals[id_zone])
+
+ unit = self.unit_mapscale
+ mapscale = self.get_attrsman().get_config('unit_mapscale').mapscales[unit]
+@@ -211,21 +211,21 @@
+
+ #self.zonefillmode = ['zone color','flows in - flows out','flows in + flows out','flows in','flows out'],
+ if self.zonefillmode == 'flows in - flows out':
+- ids_zone = balance.keys()
+- values = balance.values()
++ ids_zone = list(balance.keys())
++ values = list(balance.values())
+ elif self.zonefillmode == 'flows in + flows out':
+- ids_zone = totals.keys()
+- values = totals.values()
++ ids_zone = list(totals.keys())
++ values = list(totals.values())
+ elif self.zonefillmode == 'flows in':
+- ids_zone = inflows.keys()
+- values = inflows.values()
++ ids_zone = list(inflows.keys())
++ values = list(inflows.values())
+ elif self.zonefillmode == 'flows out':
+- ids_zone = outflows.keys()
+- values = outflows.values()
++ ids_zone = list(outflows.keys())
++ values = list(outflows.values())
+ else:
+ # dummy
+- ids_zone = balance.keys()
+- values = balance.values()
++ ids_zone = list(balance.keys())
++ values = list(balance.values())
+ ppatches = []
+ for id_zone, shape, value in zip(ids_zone, zones.shapes[ids_zone], values):
+
+@@ -268,7 +268,7 @@
+ else:
+ cmap = mpl.cm.jet
+ patchcollection = PatchCollection(ppatches, cmap=cmap, alpha=self.alpha_zones)
+- print ' values', values
++ print(' values', values)
+ patchcollection.set_array(np.array(values, dtype=np.float32))
+
+ ax.add_collection(patchcollection)
+@@ -284,11 +284,11 @@
+ ax.add_patch(patch)
+
+ if self.is_show_flows:
+- values_raw = np.array(odflows.values(), dtype=np.float32)
++ values_raw = np.array(list(odflows.values()), dtype=np.float32)
+ widthcoeff = self.width_flows_max/np.max(values_raw)
+
+ apatches = []
+- for od, flow in odflows.iteritems():
++ for od, flow in odflows.items():
+ id_zone_orig, id_zone_dest = od
+ x1, y1 = zones.coords[id_zone_orig][:2]
+ x2, y2 = zones.coords[id_zone_dest][:2]
+@@ -298,7 +298,7 @@
+ # text = str(int(flow))
+ # else:
+ # text = ''
+- print ' x1, y1', x1, y1, 'x2, y2', x2, y2
++ print(' x1, y1', x1, y1, 'x2, y2', x2, y2)
+ if id_zone_orig != id_zone_dest:
+ patch = FancyArrow(x1*mapscale, y1*mapscale, (x2-x1)*mapscale, (y2-y1)*mapscale,
+ width=width,
+--- tools/contributed/sumopy/coremodules/demand/origin_to_destination_wxgui.py (original)
++++ tools/contributed/sumopy/coremodules/demand/origin_to_destination_wxgui.py (refactored)
+@@ -26,12 +26,12 @@
+ from agilepy.lib_wx.ogleditor import *
+ from agilepy.lib_wx.objpanel import ObjPanel
+ from coremodules.network.network import SumoIdsConf, MODES
+-import origin_to_destination as od
++from . import origin_to_destination as od
+
+
+ class OdCommonMixin:
+ def add_odoptions_common(self, modes=None, activitytypes=None, **kwargs):
+- print 'add_odoptions_common', modes
++ print('add_odoptions_common', modes)
+ self.add(am.AttrConf('t_start', kwargs.get('t_start', 0),
+ groupnames=['options'],
+ perm='rw',
+@@ -630,7 +630,7 @@
+ """
+ Add demand to scenario.
+ """
+- print 'AddOdm.add_demand'
++ print('AddOdm.add_demand')
+ # print ' ids_zone_orig_filter',self.ids_zone_orig_filter.get_value()
+ # print ' ids_zone_dest_filter',self.ids_zone_dest_filter.get_value()
+ odintervals = self.parent
+@@ -677,11 +677,11 @@
+ tripnumbers=int(tripnumbers_str)
+ )
+ else:
+- print 'WARNING: unknown zonename in line %d of file %s' % (i_line, filepath)
++ print('WARNING: unknown zonename in line %d of file %s' % (i_line, filepath))
+
+ else:
+ if len(cols) != 0:
+- print 'WARNING: inconsistent o,d,trips info in line %d of file %s' % (i_line, filepath)
++ print('WARNING: inconsistent o,d,trips info in line %d of file %s' % (i_line, filepath))
+ i_line += 1
+ # self.odtab.print_rows()
+ f.close()
+--- tools/contributed/sumopy/coremodules/demand/publictransportservices.py (original)
++++ tools/contributed/sumopy/coremodules/demand/publictransportservices.py (refactored)
+@@ -174,7 +174,7 @@
+ if len(ids_edge) > 0:
+ if id_stopedge not in ids_edge:
+ id_edge = ids_edge[0]
+- print ' initial stop edge %d of line %d disconnected from route edge %d' % (id_stopedge, id_line, id_edge)
++ print(' initial stop edge %d of line %d disconnected from route edge %d' % (id_stopedge, id_line, id_edge))
+ # print ' before:',ids_edge
+ if id_mode not in map_mode_to_times:
+ map_mode_to_times[id_mode] = get_times(id_mode=id_mode,
+@@ -188,7 +188,7 @@
+
+ if len(ids_edges_connect) > 0:
+ if ids_edges_connect[-1] == id_edge:
+- print ' prepend connection', ids_edges_connect
++ print(' prepend connection', ids_edges_connect)
+ self.ids_edges[id_line] = ids_edges_connect[:-1] + ids_edge
+ # print ' after:',self.ids_edges[id_line]
+
+@@ -281,7 +281,7 @@
+ # complete route between stops
+ ids_edge = []
+ duration = 0
+- for i in xrange(1, len(ids_stop)):
++ for i in range(1, len(ids_stop)):
+ # print ' route',ids_stopedge[i-1],ids_stopedge[i]
+ time, ids_edges_current = get_mincostroute_edge2edge(
+ ids_stopedge[i-1],
+@@ -545,23 +545,23 @@
+ id_line = self.ids_line[id_link]
+ time_interval = self.parent.periods[id_line]
+
+- print ident*' ', 'PtLink:', id_link, 'line', id_line, '(%s)' % (self.parent.linenames[id_line]), 'from stop', self.ids_fromstop[id_link], 'to stop', self.ids_tostop[id_link], 'T=%ds I=%ds' % (self.durations[id_link], time_interval)
++ print(ident*' ', 'PtLink:', id_link, 'line', id_line, '(%s)' % (self.parent.linenames[id_line]), 'from stop', self.ids_fromstop[id_link], 'to stop', self.ids_tostop[id_link], 'T=%ds I=%ds' % (self.durations[id_link], time_interval))
+ #id_link_board = self.get_link_board(id_link)
+ # print ident*' ', 'check interval: I=%d, I_board=%d, id_link_board=%d'%(time_interval, self.durations[id_link_board], id_link_board),'ids_link_forward',self.ids_links_forward[id_link_board]
+
+ if is_edges:
+- print ident*' ', ' ids_edge=', self.get_ids_edge(id_link)
++ print(ident*' ', ' ids_edge=', self.get_ids_edge(id_link))
+
+ elif linktype == 'board':
+ id_line = self.ids_line[id_link]
+- print ident*' ', 'PtLink:', id_link, 'type', linktype, 'T=%ds' % (self.durations[id_link]), 'line', id_line, '(%s)' % (self.parent.linenames[id_line]), 'at stop', self.ids_fromstop[id_link]
++ print(ident*' ', 'PtLink:', id_link, 'type', linktype, 'T=%ds' % (self.durations[id_link]), 'line', id_line, '(%s)' % (self.parent.linenames[id_line]), 'at stop', self.ids_fromstop[id_link])
+
+ elif linktype == 'walk':
+- print ident*' ', 'PtLink:', id_link, 'type', linktype, 'T=%ds' % (self.durations[id_link]), 'from stop', self.ids_fromstop[id_link], 'to stop', self.ids_tostop[id_link]
++ print(ident*' ', 'PtLink:', id_link, 'type', linktype, 'T=%ds' % (self.durations[id_link]), 'from stop', self.ids_fromstop[id_link], 'to stop', self.ids_tostop[id_link])
+
+ else:
+
+- print ident*' ', 'PtLink:', id_link, 'type', linktype, 'T=%ds' % (self.durations[id_link]), 'at stop', self.ids_fromstop[id_link]
++ print(ident*' ', 'PtLink:', id_link, 'type', linktype, 'T=%ds' % (self.durations[id_link]), 'at stop', self.ids_fromstop[id_link])
+
+ if is_link_forward:
+ # print ident*' ',' ids_link_forward=',self.ids_links_forward[id_link]
+@@ -609,7 +609,7 @@
+ speed_walk_los is the assumed line of sight walking speed
+ between two stops
+ """
+- print 'build', self.ident, dist_walk_los, speed_walk_los
++ print('build', self.ident, dist_walk_los, speed_walk_los)
+
+ id_stop_debug = 459
+
+@@ -659,15 +659,15 @@
+ ):
+ n_edge = len(ids_edge)
+ n_stop = len(ids_stop)
+- print 79*'-'
+- print 'Build links of line', linename, 'id_line', id_line, 'n_edge', n_edge, 'n_stop', n_stop
++ print(79*'-')
++ print('Build links of line', linename, 'id_line', id_line, 'n_edge', n_edge, 'n_stop', n_stop)
+ if (len(ids_edge) > 1) & (len(ids_stop) > 2):
+
+ # check if all stop edges are on route and in the correct order:
+ ind_edge = 0
+
+ id_stopedge_next = ids_laneedge[ids_stoplane[ids_stop[1]]]
+- for ind_stop in xrange(1, n_stop):
++ for ind_stop in range(1, n_stop):
+ id_fromstop = ids_stop[ind_stop-1]
+ id_tostop = ids_stop[ind_stop]
+ if id_fromstop != id_tostop:
+@@ -686,7 +686,7 @@
+ # print ' ind_edge,id_stopedge_next,ids_edge[ind_edge]',ind_edge,id_stopedge_next,ids_edge[ind_edge],len(ids_edge)
+
+ #is_mismatch = (ind_edge == (n_edge-1)) & (ind_stop != (n_stop-1))
+- print ' ind_stop', ind_stop, 'ind_edge', ind_edge, is_mismatch
++ print(' ind_stop', ind_stop, 'ind_edge', ind_edge, is_mismatch)
+ if is_mismatch:
+ break
+
+@@ -705,12 +705,12 @@
+
+ ids_link = []
+ ind_edge = 0
+- for ind_stop in xrange(1, len(ids_stop)):
++ for ind_stop in range(1, len(ids_stop)):
+ id_fromstop = ids_stop[ind_stop-1]
+ id_tostop = ids_stop[ind_stop]
+
+ # if id_fromstop == id_stop_debug:
+- print ' ind_stop', ind_stop, 'id_fromstop,id_tostop', id_fromstop, id_tostop, 'ind_edge', ind_edge
++ print(' ind_stop', ind_stop, 'id_fromstop,id_tostop', id_fromstop, id_tostop, 'ind_edge', ind_edge)
+
+ # this prevents error in case two successive stops have
+ # (by editing error) the same ID
+@@ -719,7 +719,7 @@
+ # compute length and time between fromstop and tostop
+ while id_stopedge_next != ids_edge[ind_edge]:
+ # if id_fromstop == id_stop_debug:
+- print ' ind_edge', ind_edge, ',id_stopedge_next,ids_edge[ind_edge]', id_stopedge_next, ids_edge[ind_edge]
++ print(' ind_edge', ind_edge, ',id_stopedge_next,ids_edge[ind_edge]', id_stopedge_next, ids_edge[ind_edge])
+ ind_edge += 1
+ length_edge = edgelengths[ids_edge[ind_edge]]
+ length += length_edge
+@@ -745,7 +745,7 @@
+
+ # debugging
+ if id_fromstop == id_stop_debug:
+- print ' append transit link', id_link
++ print(' append transit link', id_link)
+
+ stoplinks[id_fromstop]['ids_transit_out'].append(id_link)
+ stoplinks[id_tostop]['ids_transit_in'].append(id_link)
+@@ -757,14 +757,14 @@
+ duration = 0.0
+
+ # create forward links for this line
+- for i in xrange(1, len(ids_link)):
++ for i in range(1, len(ids_link)):
+ self.ids_links_forward[ids_link[i-1]] = [ids_link[i]]
+ # put empty link list to line end-stop
+ self.ids_links_forward[ids_link[i]] = []
+
+ else:
+- print 'WARNING in line', linename, 'id_line', id_line
+- print ' stop edges not on route, line will not build.'
++ print('WARNING in line', linename, 'id_line', id_line)
++ print(' stop edges not on route, line will not build.')
+ ids_ptlines_failed.append(id_line)
+
+ # complete stoplink database
+@@ -870,15 +870,15 @@
+
+ # debugging
+ if id_stop == id_stop_debug:
+- print ' Parameters of id_stop', id_stop
+- for key, val in stoplinks[id_stop].iteritems():
++ print(' Parameters of id_stop', id_stop)
++ for key, val in stoplinks[id_stop].items():
+ if key in ['ids_transit_out', 'ids_transit_in', 'ids_board', 'ids_alight']:
+- print ' ', key, ':'
++ print(' ', key, ':')
+ for id_link in val:
+ self.print_link(id_link, ident=6)
+
+ else:
+- print ' ', key, ':', val
++ print(' ', key, ':', val)
+
+ # connect walk links from one stop to board and transfer
+ for id_stop in net.ptstops.get_ids():
+@@ -887,32 +887,32 @@
+ self.ids_links_forward[id_walk] = [stoplinks[id_tostop]['id_enter']]
+ if 0:
+ # debugging
+- print 79*'='
++ print(79*'=')
+ ids_link = self.get_ids()
+ for id_link, linktype, id_fromstop, id_tostop, id_line, duration, ids_link_forward in zip(
+ ids_link, self.types[ids_link], self.ids_fromstop[ids_link], self.ids_tostop[ids_link], self.ids_line[ids_link], self.durations[ids_link], self.ids_links_forward[ids_link]):
+ if id_fromstop == id_stop_debug:
+- print ' FROM', id_stop_debug, 'TO', id_tostop
++ print(' FROM', id_stop_debug, 'TO', id_tostop)
+ self.print_link(id_link, ident=4)
+- print ' ids_link_forward=', ids_link_forward
+-
+- print 79*'='
++ print(' ids_link_forward=', ids_link_forward)
++
++ print(79*'=')
+ for id_link, linktype, id_fromstop, id_tostop, id_line, duration, ids_link_forward in zip(
+ ids_link, self.types[ids_link], self.ids_fromstop[ids_link], self.ids_tostop[ids_link], self.ids_line[ids_link], self.durations[ids_link], self.ids_links_forward[ids_link]):
+
+ if id_tostop == id_stop_debug:
+- print ' FROM', id_fromstop, 'TO', id_stop_debug
++ print(' FROM', id_fromstop, 'TO', id_stop_debug)
+ self.print_link(id_link, ident=4)
+- print ' ids_link_forward=', ids_link_forward
++ print(' ids_link_forward=', ids_link_forward)
+
+ # debug
+- print 'Number of failed Ptlines', len(ids_ptlines_failed), 'of', len(ptlines)
++ print('Number of failed Ptlines', len(ids_ptlines_failed), 'of', len(ptlines))
+ for id_line, linename, period in zip(
+ ids_ptlines_failed,
+ ptlines.linenames[ids_ptlines_failed],
+ ptlines.periods[ids_ptlines_failed],
+ ):
+- print ' Failed to build line', linename, 'id_line', id_line, 'period', period, 's'
++ print(' Failed to build line', linename, 'id_line', id_line, 'period', period, 's')
+
+ return ids_ptlines_failed
+
+@@ -937,7 +937,7 @@
+ if is_fromstop:
+ for id_link, linktype_stop, id_stop in zip(ids, self.types[ids], self.ids_fromstop[ids]):
+ if linktype == linktype_stop:
+- if map_id_stop_to_ids_link.has_key(id_stop):
++ if id_stop in map_id_stop_to_ids_link:
+ # print ' append id_transitlink',id_link,linktype,'to id_stop',id_stop
+ map_id_stop_to_ids_link[id_stop].append(id_link)
+ else:
+@@ -946,7 +946,7 @@
+ if is_tostop:
+ for id_link, linktype_stop, id_stop in zip(ids, self.types[ids], self.ids_tostop[ids]):
+ if linktype == linktype_stop:
+- if map_id_stop_to_ids_link.has_key(id_stop):
++ if id_stop in map_id_stop_to_ids_link:
+ # print ' append id_transitlink',id_link,linktype,'to id_stop',id_stop
+ map_id_stop_to_ids_link[id_stop].append(id_link)
+ else:
+@@ -1046,7 +1046,7 @@
+ line = self.parent.linenames[id_line]
+ else:
+ line = 'X'
+- print '%4d %06s fromstop=%3d tostop=%3d %06s' % (id_link, line, id_fromstop, id_tostop, typemap[id_type])
++ print('%4d %06s fromstop=%3d tostop=%3d %06s' % (id_link, line, id_fromstop, id_tostop, typemap[id_type]))
+
+ def route(self, id_fromstop, id_tostop,
+ stops_to_enter=None, stops_to_exit=None,
+@@ -1060,7 +1060,7 @@
+ ids_tostop : IDs of stops where each stage ends
+ durations : Duration of each stage in secs
+ """
+- print 'route id_fromstop, id_tostop', id_fromstop, id_tostop
++ print('route id_fromstop, id_tostop', id_fromstop, id_tostop)
+ if times is None:
+ times = self.get_times()
+
+@@ -1166,7 +1166,7 @@
+
+ class PtLinefilter(Process):
+ def __init__(self, ident='ptlinefilter', ptlines=None, logger=None, **kwargs):
+- print 'PtLinefilter.__init__'
++ print('PtLinefilter.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -1194,7 +1194,7 @@
+ ))
+
+ def do(self):
+- print 'PtLinefilter.do'
++ print('PtLinefilter.do')
+ # links
+ ptlines = self.parent
+
+@@ -1215,14 +1215,14 @@
+ elif period > self.period_max:
+ ids_remove.append(id_line)
+
+- print ' Eliminated %d lines:' % (len(ids_remove))
++ print(' Eliminated %d lines:' % (len(ids_remove)))
+
+ for id_line, name, ids_stop, period in zip(ids_remove,
+ ptlines.linenames[ids_remove],
+ ptlines.ids_stops[ids_remove],
+ ptlines.periods[ids_remove]
+ ):
+- print ' id_line', id_line, 'name', name, 'period', period, 'n_stops', len(ids_stop)
++ print(' id_line', id_line, 'name', name, 'period', period, 'n_stops', len(ids_stop))
+
+ ptlines.del_rows(ids_remove)
+
+@@ -1231,7 +1231,7 @@
+
+ class PtNetbuilder(Process):
+ def __init__(self, ident='ptnetbuilder', ptlinks=None, logger=None, **kwargs):
+- print 'PtNetbuilder.__init__'
++ print('PtNetbuilder.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -1294,7 +1294,7 @@
+ ))
+
+ def do(self):
+- print 'VehicleProvider.do'
++ print('VehicleProvider.do')
+ # links
+
+ #virtualpop = self.parent
+--- tools/contributed/sumopy/coremodules/demand/publictransportservices_wxgui.py (original)
++++ tools/contributed/sumopy/coremodules/demand/publictransportservices_wxgui.py (refactored)
+@@ -24,7 +24,7 @@
+ from agilepy.lib_base.processes import Process
+ from agilepy.lib_wx.processdialog import ProcessDialog
+ from coremodules.network.network import SumoIdsConf, MODES
+-import publictransportservices as pt
++from . import publictransportservices as pt
+
+
+ class PublicTransportWxGuiMixin:
+--- tools/contributed/sumopy/coremodules/demand/turnflows.py (original)
++++ tools/contributed/sumopy/coremodules/demand/turnflows.py (refactored)
+@@ -27,7 +27,7 @@
+ #from coremodules.modules_common import *
+ from coremodules.network.network import SumoIdsConf, MODES
+ from agilepy.lib_base.processes import Process, P, call, CmlMixin
+-import demandbase as db
++from . import demandbase as db
+
+
+ class Flows(am.ArrayObjman):
+@@ -250,7 +250,7 @@
+ flows_total = {}
+ for _id in self.get_ids():
+ id_fromedge = self.ids_fromedge[_id]
+- if not flows_total.has_key(id_fromedge):
++ if id_fromedge not in flows_total:
+ flows_total[id_fromedge] = 0.0
+ flows_total[id_fromedge] += self.flows[_id]
+
+@@ -259,7 +259,7 @@
+ self.probabilities[_id] = self.flows[_id] / flows_total[self.ids_fromedge[_id]]
+
+ def add_turn(self, id_fromedge, id_toedge, flow):
+- print 'Turns.add_turn'
++ print('Turns.add_turn')
+ return self.add_row(ids_fromedge=id_fromedge,
+ ids_toedge=id_toedge,
+ flows=flow,
+@@ -295,14 +295,14 @@
+ fromedge_to_turnprobs = {}
+ for _id in self.get_ids():
+ id_fromedge = self.ids_fromedge[_id]
+- if not fromedge_to_turnprobs.has_key(id_fromedge):
++ if id_fromedge not in fromedge_to_turnprobs:
+ fromedge_to_turnprobs[id_fromedge] = []
+ fromedge_to_turnprobs[id_fromedge].append((self.ids_toedge[_id], self.probabilities[_id]))
+
+ ids_sumoeges = self.get_edges().ids_sumo
+
+ fd.write(xm.begin('edgeRelations', indent))
+- for id_fromedge in fromedge_to_turnprobs.keys():
++ for id_fromedge in list(fromedge_to_turnprobs.keys()):
+
+ for id_toedge, turnprob in fromedge_to_turnprobs[id_fromedge]:
+ fd.write(xm.start('edgeRelation', indent+2))
+@@ -321,7 +321,7 @@
+ info='Contains for each transport mode an OD trip table.',
+ xmltag=('modesods', 'modeods', 'ids_mode'), **kwargs)
+
+- print 'TurnflowModes.__init__', modes
++ print('TurnflowModes.__init__', modes)
+ self.add_col(am.IdsArrayConf('ids_mode', modes,
+ groupnames=['state'],
+ choices=MODES,
+@@ -330,7 +330,7 @@
+ #xmltag = 'vClass',
+ info='ID of transport mode.',
+ ))
+- print ' self.ids_mode.is_index', self.ids_mode.is_index()
++ print(' self.ids_mode.is_index', self.ids_mode.is_index())
+
+ self.add_col(cm.ObjsConf('flowtables',
+ groupnames=['state'],
+@@ -366,7 +366,7 @@
+
+ def add_mode(self, id_mode):
+ id_tf_modes = self.add_row(ids_mode=id_mode)
+- print ' add_mode', id_mode, id_tf_modes
++ print(' add_mode', id_mode, id_tf_modes)
+
+ flows = Flows((self.flowtables.attrname, id_tf_modes), self, self.edges.get_value())
+ self.flowtables[id_tf_modes] = flows
+@@ -381,8 +381,8 @@
+ Sets a demand flows between from-Edge and toEdge pairs for mode where flows is a dictionary
+ with (fromEdgeID,toEdgeID) pair as key and number of trips as values.
+ """
+- print 'TurnflowModes.add_turnflows', id_mode # ,flows,kwargs
+- print ' self.ids_mode.is_index()', self.ids_mode.is_index()
++ print('TurnflowModes.add_turnflows', id_mode) # ,flows,kwargs
++ print(' self.ids_mode.is_index()', self.ids_mode.is_index())
+ if self.ids_mode.has_index(id_mode):
+ id_tf_modes = self.ids_mode.get_id_from_index(id_mode)
+ else:
+@@ -394,7 +394,7 @@
+ """
+ Sets turn probability between from-edge and to-edge.
+ """
+- print 'TurnflowModes.add_turn', id_mode # ,turnflow,kwargs
++ print('TurnflowModes.add_turn', id_mode) # ,turnflow,kwargs
+ # if scale!=1.0:
+ # for od in odm.iterkeys():
+ # odm[od] *= scale
+@@ -413,7 +413,7 @@
+ Export flow data of desired mode to xml file.
+ Returns list with edge IDs with non zero flows and a flow ID counter.
+ """
+- print 'TurnflowModes.export_flows_xml id_mode, id_flow', id_mode, id_flow, self.ids_mode.has_index(id_mode)
++ print('TurnflowModes.export_flows_xml id_mode, id_flow', id_mode, id_flow, self.ids_mode.has_index(id_mode))
+ ids_sourceedge = []
+
+ if not self.ids_mode.has_index(id_mode):
+@@ -432,7 +432,7 @@
+ # # TODO: can we put some distributen here?
+ # vtype = vtypes[0]
+ for vtype, share in zip(vtypes, shares):
+- print ' write flows for vtype', vtype, share
++ print(' write flows for vtype', vtype, share)
+ if self.ids_mode.has_index(id_mode):
+ id_tf_modes = self.ids_mode.get_id_from_index(id_mode)
+ ids_sourceedge, id_flow = self.flowtables[id_tf_modes].export_xml(
+@@ -446,7 +446,7 @@
+ Export flow data of desired mode to xml file.
+ Returns list with edge IDs with non zero flows and a flow ID counter.
+ """
+- print 'TurnflowModes.export_turns_xml'
++ print('TurnflowModes.export_turns_xml')
+
+ if self.ids_mode.has_index(id_mode):
+ id_tf_modes = self.ids_mode.get_id_from_index(id_mode)
+@@ -502,7 +502,7 @@
+ """
+ Makes sure that sum of turn probabilities from an edge equals 1.
+ """
+- print 'Turnflows.normalize_turnprobabilities'
++ print('Turnflows.normalize_turnprobabilities')
+ # for turnflowmode in self.turnflowmodes.get_value():
+ # turnflowmode.normalize_turnprobabilities() # no! it's a dict!!
+ # print ' ',self.turnflowmodes.get_value()
+@@ -589,9 +589,9 @@
+ In the SUMOpy tunflow data structure, each mode has its own
+ flow and turnratio data.
+ """
+- print '\n\n'+79*'_'
+- print 'export_flows_and_turns id_mode=', id_mode, 'ids_vtype=', self.parent.vtypes.select_by_mode(id_mode)
+- print ' write flows', flowfilepath
++ print('\n\n'+79*'_')
++ print('export_flows_and_turns id_mode=', id_mode, 'ids_vtype=', self.parent.vtypes.select_by_mode(id_mode))
++ print(' write flows', flowfilepath)
+ fd = open(flowfilepath, 'w')
+ fd.write(xm.begin('flows', indent))
+
+@@ -707,14 +707,14 @@
+ scenario.net.export_netxml()
+
+ ids_mode = self.get_modes()
+- print 'turnflows_to_routes', ids_mode # scenario.net.modes.get_ids()
+- print ' cmloptions', cmloptions
++ print('turnflows_to_routes', ids_mode) # scenario.net.modes.get_ids()
++ print(' cmloptions', cmloptions)
+
+ # route for all modes and read in routes
+ for id_mode in ids_mode:
+ # write flow and turns xml file for this mode
+ time_start, time_end = self.export_flows_and_turns(flowfilepath, turnfilepath, id_mode)
+- print ' time_start, time_end =', time_start, time_end
++ print(' time_start, time_end =', time_start, time_end)
+
+ if time_end > time_start: # means there exist some flows for this mode
+ cmd = 'jtrrouter --route-files=%s --turn-ratio-files=%s --net-file=%s --output-file=%s --begin %s --end %s %s'\
+@@ -733,7 +733,7 @@
+ os.remove(routefilepath)
+
+ else:
+- print 'jtrroute: no flows generated for id_mode', id_mode
++ print('jtrroute: no flows generated for id_mode', id_mode)
+
+ # self.simfiles.set_modified_data('rou',True)
+ # self.simfiles.set_modified_data('trip',True)
+@@ -872,9 +872,9 @@
+ # )
+
+ def do(self):
+- print 'do'
++ print('do')
+ cml = self.get_cml(is_without_command=True) # only options, not the command #
+- print ' cml=', cml
++ print(' cml=', cml)
+ self.parent.turnflows_to_routes(is_clear_trips=self.is_clear_trips,
+ is_export_network=self.is_export_network,
+ is_make_probabilities=True,
+@@ -972,7 +972,7 @@
+ ids_sumoedge_notexist = []
+ pairs_sumoedge_unconnected = []
+
+- print 'import_pat_csv', self.tffilepath
++ print('import_pat_csv', self.tffilepath)
+ i_line = 1
+ for line in f.readlines():
+ cols = line.split(sep)
+@@ -1006,12 +1006,12 @@
+ id_fromedge, id_toedge, turnflow)
+
+ else:
+- print 'WARNING: inconsistent row in line %d, file %s' % (i_line, self.tffilepath)
++ print('WARNING: inconsistent row in line %d, file %s' % (i_line, self.tffilepath))
+ i_line += 1
+ f.close()
+ if len(ids_sumoedge_notexist) > 0:
+- print 'WARNING: inexistant edge IDs:', ids_sumoedge_notexist
++ print('WARNING: inexistant edge IDs:', ids_sumoedge_notexist)
+ if len(pairs_sumoedge_unconnected) > 0:
+- print 'WARNING: unconnected edge pairs:', pairs_sumoedge_unconnected
++ print('WARNING: unconnected edge pairs:', pairs_sumoedge_unconnected)
+
+ return ids_sumoedge_notexist, pairs_sumoedge_unconnected
+--- tools/contributed/sumopy/coremodules/demand/turnflows_wxgui.py (original)
++++ tools/contributed/sumopy/coremodules/demand/turnflows_wxgui.py (refactored)
+@@ -24,7 +24,7 @@
+ from agilepy.lib_base.processes import Process
+ from agilepy.lib_wx.processdialog import ProcessDialog
+ from coremodules.network.network import SumoIdsConf, MODES
+-import turnflows
++from . import turnflows
+
+
+ class TurnflowWxGuiMixin:
+--- tools/contributed/sumopy/coremodules/demand/vehicles.py (original)
++++ tools/contributed/sumopy/coremodules/demand/vehicles.py (refactored)
+@@ -117,7 +117,7 @@
+
+ class Electricalprofiles(am.ArrayObjman):
+ def __init__(self, ident, parent, **kwargs):
+- print 'Electricalprofiles.__init__'
++ print('Electricalprofiles.__init__')
+ self._init_objman(ident=ident,
+ parent=parent,
+ name='Electrical profiles',
+@@ -129,7 +129,7 @@
+ self.add_profiles_default()
+
+ def _init_attributes(self):
+- print 'Electricalprofiles._init_attributes'
++ print('Electricalprofiles._init_attributes')
+ self.add_col(SumoIdsConf('profilename', name='Electric profile', perm='rw'))
+ self.add_col(am.ArrayConf('capacities_battery', 0.8,
+ groupnames=['parameters', 'key'],
+@@ -189,7 +189,7 @@
+
+ class VehicleTypes(am.ArrayObjman):
+ def __init__(self, parent, net, is_add_default=True, **kwargs):
+- print 'VehicleTypes.__init__ is_add_default', is_add_default
++ print('VehicleTypes.__init__ is_add_default', is_add_default)
+ self._init_objman(ident='vtypes',
+ parent=parent,
+ name='Vehicle Types',
+@@ -205,7 +205,7 @@
+ self.set_version(0.3)
+
+ def _init_attributes(self):
+- print 'VehicleTypes._init_attributes', len(self), self.get_ident_abs()
++ print('VehicleTypes._init_attributes', len(self), self.get_ident_abs())
+ net = self.parent.get_net()
+ demand = self.parent
+
+@@ -530,7 +530,7 @@
+ ))
+
+ emissionclasses_xml = {}
+- for key in EMISSIONCLASSES.keys():
++ for key in list(EMISSIONCLASSES.keys()):
+ emissionclasses_xml[key] = key # yes, map onto itself, otherwise choice values are taken
+
+ self.add_col(am.ArrayConf('emissionclasses', 'HBEFA3/HDV_D_EU4',
+@@ -758,7 +758,7 @@
+ _id = self.add_row(**row_last)
+ # print ' _id',_id
+ else:
+- print ' clone last'
++ print(' clone last')
+ i = 1
+ row_last = self.get_row(self.get_ids()[-1])
+ row_last['ids_sumo'] += '_%03d' % i # important for all indexed attrs!!
+@@ -780,17 +780,17 @@
+ return id_vtype
+
+ def add_vtype(self, vtype, **kwargs):
+- print 'add_vtype', vtype, kwargs
++ print('add_vtype', vtype, kwargs)
+ if self.ids_sumo.has_index(vtype):
+ # vtype already exist
+ _id = self.ids_sumo.get_id_from_index(vtype)
+ else:
+ _id = self.add_row(ids_sumo=vtype)
+
+- if kwargs.has_key('mode'):
++ if 'mode' in kwargs:
+ id_mode = MODES.get(kwargs['mode'], 1)
+ del kwargs['mode']
+- elif kwargs.has_key('id_mode'):
++ elif 'id_mode' in kwargs:
+ id_mode = kwargs['id_mode']
+ del kwargs['id_mode']
+ else:
+@@ -798,7 +798,7 @@
+
+ #_id = self.add_row( ids_sumo = vtype, ids_mode = id_mode,**kwargs)
+
+- if kwargs.has_key('eprofile'):
++ if 'eprofile' in kwargs:
+ eprofiles = self.eprofiles.get_value()
+ eprofile = kwargs['eprofile']
+ eprofiles.add_profile(eprofile, **kwargs)
+@@ -861,7 +861,7 @@
+ return _id
+
+ def add_vtypes_default(self):
+- print 'add_vtypes_default'
++ print('add_vtypes_default')
+ # self.del_rows(self.get_ids())
+ self.add_vtype('pedestrian',
+ accel=1.5,
+@@ -1411,7 +1411,7 @@
+ """
+ mode_vtypes = self.get_modes()
+ mode_choice = OrderedDict()
+- for mode, id_mode in MODES.iteritems():
++ for mode, id_mode in MODES.items():
+ if id_mode in mode_vtypes:
+ mode_choice[mode] = id_mode
+ return mode_choice
+@@ -1516,12 +1516,12 @@
+ # print ' _write_xml_body: done'
+
+ def export_xml(self, filepath, encoding='UTF-8'):
+- print 'export_xml to %s' % (filepath)
++ print('export_xml to %s' % (filepath))
+
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in vtypes.export_xml: could not open', filepath
++ print('WARNING in vtypes.export_xml: could not open', filepath)
+ return False
+
+ fd.write('\n' % encoding)
+@@ -1539,7 +1539,7 @@
+ # attrconfigs_excluded.append('lanechangemodel')
+
+ def import_xml(self, filepath):
+- print 'import_xml from %s' % (filepath)
++ print('import_xml from %s' % (filepath))
+ reader = VtypeReader(self)
+ parse(filepath, reader)
+ self.normalize_shares()
+@@ -1566,20 +1566,20 @@
+ params = {}
+
+ # print 'startElement',attrs['id'],self._id_vclass_dist
+- if attrs.has_key('laneChangeModel'):
++ if 'laneChangeModel' in attrs:
+ lanechangemodel = attrs['laneChangeModel']
+ if lanechangemodel in LANECHANGEMODELS:
+ self._vtypes.lanechangemodel.set_value(lanechangemodel)
+
+- if attrs.has_key('vClass'):
++ if 'vClass' in attrs:
+ if self._id_vclass_dist is None:
+ params['ids_mode'] = self._vtypes.ids_mode.get_value_from_string(attrs['vClass'])
+ else:
+ params['ids_mode'] = self._id_vclass_dist # set vclass to distribution id
+
+ # for xmltag, xmlval in self._xmlattrmap.iteritems():
+- for xmltag in attrs.keys():
+- if self._xmlattrmap.has_key(xmltag):
++ for xmltag in list(attrs.keys()):
++ if xmltag in self._xmlattrmap:
+ attrconfig = self._xmlattrmap[xmltag]
+ params[attrconfig.attrname] = attrconfig.get_value_from_xmlattr(attrs)
+
+--- tools/contributed/sumopy/coremodules/demand/virtualpop.py (original)
++++ tools/contributed/sumopy/coremodules/demand/virtualpop.py (refactored)
+@@ -30,8 +30,8 @@
+ from coremodules.network.network import SumoIdsConf, MODES
+ from coremodules.network import routing
+ from coremodules.simulation import results as res
+-from demandbase import *
+-import virtualpop_results as res
++from .demandbase import *
++from . import virtualpop_results as res
+
+
+ GENDERS = {'male': 0, 'female': 1, 'unknown': -1}
+@@ -1202,7 +1202,7 @@
+ activities = vp.get_activities()
+
+ ids_pers_filter = ids_person[persons.ids_mode_preferred[ids_person] != self._id_mode_ped]
+- for i, ids_activity in zip(xrange(len(ids_pers_filter)), vp.activitypatterns[ids_pers_filter]):
++ for i, ids_activity in zip(range(len(ids_pers_filter)), vp.activitypatterns[ids_pers_filter]):
+
+ id_act1 = ids_activity[0]
+ id_act2 = ids_activity[1]
+@@ -1212,7 +1212,7 @@
+ if dist_fac_sqr > max_dist_fac_sqr:
+ preeval[i] = -1
+
+- print ' WalkStrategy.preevaluate', len(np.flatnonzero(preeval >= 0))
++ print(' WalkStrategy.preevaluate', len(np.flatnonzero(preeval >= 0)))
+ return preeval
+
+ def plan(self, ids_person, logger=None, **kwargs):
+@@ -1220,7 +1220,7 @@
+ Generates a plan for these person according to this strategie.
+ Overriden by specific strategy.
+ """
+- print 'WalkStrategy.pan', len(ids_person)
++ print('WalkStrategy.pan', len(ids_person))
+ #make_plans_private(self, ids_person = None, mode = 'passenger')
+ # routing necessary?
+ virtualpop = self.get_virtualpop()
+@@ -1258,7 +1258,7 @@
+ = virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
+
+ if len(ids_person_act) == 0:
+- print 'WARNING in WalkStrategy.plan: no eligible persons found.'
++ print('WARNING in WalkStrategy.plan: no eligible persons found.')
+ return False
+
+ # temporary maps from ids_person to other parameters
+@@ -1277,7 +1277,7 @@
+ map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]
+
+ n_plans = len(ids_person_act)
+- print 'TrasitStrategy.plan n_plans=', n_plans
++ print('TrasitStrategy.plan n_plans=', n_plans)
+
+ # make initial activity stage
+ ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]
+@@ -1362,8 +1362,8 @@
+ if logger:
+ logger.progress(i/n_pers*100)
+ i += 1.0
+- print 79*'_'
+- print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)
++ print(79*'_')
++ print(' id_plan=%d, id_person=%d, ' % (id_plan, id_person))
+
+ id_stage_walk1, time = walkstages.append_stage(id_plan, time_from,
+ id_edge_from=id_edge_from,
+@@ -1473,24 +1473,24 @@
+
+ """
+ n_pers = len(ids_person)
+- print 'Autostrategy.preevaluate', n_pers, 'persons'
++ print('Autostrategy.preevaluate', n_pers, 'persons')
+ persons = self.get_virtualpop()
+ preeval = np.zeros(n_pers, dtype=np.int32)
+
+ # put -1 for persons without car access
+ preeval[persons.ids_iauto[ids_person] == -1] = -1
+- print ' persons having no auto', len(np.flatnonzero(persons.ids_iauto[ids_person] == -1))
++ print(' persons having no auto', len(np.flatnonzero(persons.ids_iauto[ids_person] == -1)))
+
+ # put 0 for persons with car but with a different preferred mode
+ preeval[(persons.ids_iauto[ids_person] > -1)
+ & (persons.ids_mode_preferred[ids_person] != self._id_mode_auto)] = 0
+
+- print ' persons with car but with a different preferred mode', len(np.flatnonzero((persons.ids_iauto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_auto)))
++ print(' persons with car but with a different preferred mode', len(np.flatnonzero((persons.ids_iauto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_auto))))
+
+ # put 2 for persons with car access and who prefer the car
+ preeval[(persons.ids_iauto[ids_person] > -1)
+ & (persons.ids_mode_preferred[ids_person] == self._id_mode_auto)] = 2
+- print ' persons with car access and who prefer the car', len(np.flatnonzero((persons.ids_iauto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_auto)))
++ print(' persons with car access and who prefer the car', len(np.flatnonzero((persons.ids_iauto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_auto))))
+
+ return preeval
+
+@@ -1549,7 +1549,7 @@
+ = virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
+
+ if len(ids_person_act) == 0:
+- print 'WARNING in Autostrategy.plan: no eligible persons found.'
++ print('WARNING in Autostrategy.plan: no eligible persons found.')
+ return False
+
+ # ok
+@@ -1591,7 +1591,7 @@
+ map_are_fallback[ids_person_act] = are_fallback
+
+ n_plans = len(ids_person_act)
+- print 'AutoStrategy.plan n_plans=', n_plans
++ print('AutoStrategy.plan n_plans=', n_plans)
+ # print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape
+ # set initial activity
+ # this is because the following steps start with travel
+@@ -1730,7 +1730,7 @@
+ position_edge_to=pos_edge_parking_from-1.5, # wait 1.5 m before nose of parked car
+ )
+
+- print ' id_person,id_veh', id_person, id_veh
++ print(' id_person,id_veh', id_person, id_veh)
+ # ride from car parking to road edge near activity
+ id_stage_car, time, is_fallback = ridestages.append_stage(
+ id_plan,
+@@ -1891,24 +1891,24 @@
+
+ """
+ n_pers = len(ids_person)
+- print 'BikeStrategy.preevaluate', n_pers, 'persons'
++ print('BikeStrategy.preevaluate', n_pers, 'persons')
+ persons = self.get_virtualpop()
+ preeval = np.zeros(n_pers, dtype=np.int32)
+
+ # put -1 for persons without car access
+ preeval[persons.ids_ibike[ids_person] == -1] = -1
+- print ' persons having no bike', len(np.flatnonzero(persons.ids_ibike[ids_person] == -1))
++ print(' persons having no bike', len(np.flatnonzero(persons.ids_ibike[ids_person] == -1)))
+
+ # put 0 for persons with bike but with a different preferred mode
+ preeval[(persons.ids_ibike[ids_person] > -1)
+ & (persons.ids_mode_preferred[ids_person] != self._id_mode_bike)] = 0
+
+- print ' persons with bike but with a different preferred mode', len(np.flatnonzero((persons.ids_ibike[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_bike)))
++ print(' persons with bike but with a different preferred mode', len(np.flatnonzero((persons.ids_ibike[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_bike))))
+
+ # put 2 for persons with bike access and who prefer the bike
+ preeval[(persons.ids_ibike[ids_person] > -1)
+ & (persons.ids_mode_preferred[ids_person] == self._id_mode_bike)] = 2
+- print ' persons with car access and who prefer the car', len(np.flatnonzero((persons.ids_ibike[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_bike)))
++ print(' persons with car access and who prefer the car', len(np.flatnonzero((persons.ids_ibike[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_bike))))
+
+ return preeval
+
+@@ -1993,7 +1993,7 @@
+ pos = 0.5*self.length_edge_min
+
+ if id_bikeedge == -1:
+- print 'WARNING in get_edge_bikeaccess no access for', id_edge, self._edges.ids_sumo[id_edge]
++ print('WARNING in get_edge_bikeaccess no access for', id_edge, self._edges.ids_sumo[id_edge])
+
+ if is_get_route:
+ return id_bikeedge, pos, route
+@@ -2175,7 +2175,7 @@
+ = virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
+
+ if len(ids_person_act) == 0:
+- print 'WARNING in BikeStrategy.plan: no eligible persons found.'
++ print('WARNING in BikeStrategy.plan: no eligible persons found.')
+ return False
+
+ # ok
+@@ -2205,7 +2205,7 @@
+ #map_ids_parking_from[ids_person_act] = ids_parking_from
+
+ n_plans = len(ids_person_act)
+- print 'BikeStrategy.plan n_plans=', n_plans
++ print('BikeStrategy.plan n_plans=', n_plans)
+ # print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape
+ # set initial activity
+ # this is because the following steps start with travel
+@@ -2313,9 +2313,9 @@
+ if logger:
+ logger.progress(i/n_pers*100)
+ i += 1.0
+- print 79*'*'
+- print ' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to
+- print ' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to]
++ print(79*'*')
++ print(' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to)
++ print(' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to])
+
+ time = self.plan_bikeride(id_plan, time_from, id_veh,
+ id_edge_from, pos_edge_from,
+@@ -2446,14 +2446,14 @@
+ # put 2 for persons with car access and who prefer cars
+ preeval[persons.ids_mode_preferred[ids_person] == self._id_mode_taxi] = 2
+
+- print ' TaxiStrategy.preevaluate', len(np.flatnonzero(preeval))
++ print(' TaxiStrategy.preevaluate', len(np.flatnonzero(preeval)))
+ return preeval
+
+ def get_edge_access(self, id_edge, is_search_backward=False, is_get_route=False, is_star=False, bstar=0, fstar=0, n_iter_acces_max=None):
+ # get firts edge allowing bikes and pedestrian, saving route, frontward or backward. You can include bstar or fstar:
+ # check only connected links. You can obtain also the route.
+ # print 'get_edge_bikeaccess',id_edge, is_search_backward,'id_sumo',self._edges.ids_sumo[id_edge]
+- print 'get_edge_access id_edge', id_edge, 'is_search_backward', is_search_backward, 'n_iter_acces_max', self.n_iter_acces_max
++ print('get_edge_access id_edge', id_edge, 'is_search_backward', is_search_backward, 'n_iter_acces_max', self.n_iter_acces_max)
+ if n_iter_acces_max is None:
+ n_iter_acces_max = self.n_iter_acces_max
+
+@@ -2480,15 +2480,15 @@
+ ids = [id_edge]
+ coll_ids = [0]
+ route = []
+- print 'start id_modeedge', id_modeedge, 'n', n, 'n_iter_acces_max', n_iter_acces_max, (id_modeedge < 0), (n < n_iter_acces_max)
++ print('start id_modeedge', id_modeedge, 'n', n, 'n_iter_acces_max', n_iter_acces_max, (id_modeedge < 0), (n < n_iter_acces_max))
+
+ while (id_modeedge < 0) & (n < n_iter_acces_max):
+- print ' while id_modeedge', id_modeedge, 'n', n
++ print(' while id_modeedge', id_modeedge, 'n', n)
+ n += 1
+
+ ids_new = []
+ for id_edge_test, is_long_enough in zip(ids_current, edgelengths[ids_current] > self.length_edge_min):
+- print ' check id', id_edge_test, is_long_enough, 'taxi access', get_accesslevel(id_edge_test, id_mode), 'ped access', get_accesslevel(id_edge_test, id_mode_ped)
++ print(' check id', id_edge_test, is_long_enough, 'taxi access', get_accesslevel(id_edge_test, id_mode), 'ped access', get_accesslevel(id_edge_test, id_mode_ped))
+ if is_long_enough & (get_accesslevel(id_edge_test, id_mode) >= 0) & (get_accesslevel(id_edge_test, id_mode_ped) >= 0):
+ id_modeedge = id_edge_test
+
+@@ -2505,7 +2505,7 @@
+ if is_search_backward is not True:
+ route.reverse()
+
+- print ' found', id_modeedge, self._edges.ids_sumo[id_modeedge]
++ print(' found', id_modeedge, self._edges.ids_sumo[id_modeedge])
+ break
+ else:
+
+@@ -2532,7 +2532,7 @@
+ pos = 0.5*self.length_edge_min
+
+ if id_modeedge == -1:
+- print 'WARNING in TaxiStrategy.get_edge_access no access at id_edge', id_edge, self._edges.ids_sumo[id_edge]
++ print('WARNING in TaxiStrategy.get_edge_access no access at id_edge', id_edge, self._edges.ids_sumo[id_edge])
+
+ if is_get_route:
+ return id_modeedge, pos, route
+@@ -2553,7 +2553,7 @@
+ id_edge_to_taxi, pos_to_taxi = self.get_edge_access(id_edge_to, is_search_backward=True)
+
+ if (dist_from_to < dist_walk_max) | (id_edge_from_taxi == -1) | (id_edge_to_taxi == -1):
+- print ' go by foot because distance is too short or no taxi access', dist_from_to, id_edge_from_taxi, id_edge_to_taxi
++ print(' go by foot because distance is too short or no taxi access', dist_from_to, id_edge_from_taxi, id_edge_to_taxi)
+ id_stage_walk1, time = walkstages.append_stage(
+ id_plan, time_from,
+ id_edge_from=id_edge_from,
+@@ -2563,12 +2563,12 @@
+ )
+
+ else:
+- print ' try to take the taxi'
++ print(' try to take the taxi')
+ # print ' id_edge_from_taxi',edges.ids_sumo[id_edge_from_taxi],pos_from_taxi
+ # print ' id_edge_to_taxi',edges.ids_sumo[id_edge_to_taxi],pos_to_taxi
+
+ if id_edge_from_taxi != id_edge_from:
+- print ' must walk from origin to taxi accessible edge, time_from', time_from
++ print(' must walk from origin to taxi accessible edge, time_from', time_from)
+ # walk to taxi edge
+ id_stage_walk1, time = walkstages.append_stage(
+ id_plan, time_from,
+@@ -2579,7 +2579,7 @@
+ )
+
+ if id_edge_to_taxi != id_edge_to:
+- print ' must walk from taxi accessible edge to dest, time_from', time
++ print(' must walk from taxi accessible edge to dest, time_from', time)
+ # take taxi
+ id_stage_taxi, time = ridestages.append_stage(
+ id_plan, time,
+@@ -2602,7 +2602,7 @@
+ )
+
+ else:
+- print ' ride taxi from taxi edge to destination', time
++ print(' ride taxi from taxi edge to destination', time)
+ # take taxi
+ id_stage_taxi, time = ridestages.append_stage(
+ id_plan, time,
+@@ -2615,9 +2615,9 @@
+ position_edge_to=pos_edge_to,
+ )
+ else:
+- print ' take taxi directly from edge of origin', time_from
++ print(' take taxi directly from edge of origin', time_from)
+ if id_edge_to_taxi != id_edge_to:
+- print ' must walk from taxi accessible destination to destination', time_from
++ print(' must walk from taxi accessible destination to destination', time_from)
+
+ id_stage_taxi, time = ridestages.append_stage(
+ id_plan, time_from,
+@@ -2638,7 +2638,7 @@
+ position_edge_to=pos_edge_to,
+ )
+ else:
+- print ' take taxi directly from origin to destination', time_from
++ print(' take taxi directly from origin to destination', time_from)
+ id_stage_taxi, time = ridestages.append_stage(
+ id_plan, time_from,
+ id_veh=id_veh,
+@@ -2654,7 +2654,7 @@
+ # if not, for whatever reason,
+ # we walk from origin to destination
+ if id_stage_taxi == -1:
+- print ' walk because no ride stage has been planned', time_from
++ print(' walk because no ride stage has been planned', time_from)
+ if id_stage_walk1 == -1:
+ # no walk stage has been planned
+ id_stage_walk1, time = walkstages.append_stage(
+@@ -2715,7 +2715,7 @@
+ = virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
+
+ if len(ids_person_act) == 0:
+- print 'WARNING in TaxiStrategy.plan: no eligible persons found.'
++ print('WARNING in TaxiStrategy.plan: no eligible persons found.')
+ return False
+
+ # ok
+@@ -2745,7 +2745,7 @@
+ #map_ids_parking_from[ids_person_act] = ids_parking_from
+
+ n_plans = len(ids_person_act)
+- print 'TaxiStrategy.plan n_plans=', n_plans
++ print('TaxiStrategy.plan n_plans=', n_plans)
+ # print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape
+ # set initial activity
+ # this is because the following steps start with travel
+@@ -2832,9 +2832,9 @@
+ if logger:
+ logger.progress(i/n_pers*100)
+ i += 1.0
+- print 79*'*'
+- print ' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to
+- print ' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to]
++ print(79*'*')
++ print(' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to)
++ print(' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to])
+
+ time = self.plan_taxiride(id_plan, time_from, id_veh,
+ id_edge_from, pos_edge_from,
+@@ -2955,24 +2955,24 @@
+
+ """
+ n_pers = len(ids_person)
+- print 'MotorcycleStrategy.preevaluate', n_pers, 'persons'
++ print('MotorcycleStrategy.preevaluate', n_pers, 'persons')
+ persons = self.get_virtualpop()
+ preeval = np.zeros(n_pers, dtype=np.int32)
+
+ # put -1 for persons without motorcycle access
+ preeval[persons.ids_imoto[ids_person] == -1] = -1
+- print ' persons having no motorcycle', len(np.flatnonzero(persons.ids_imoto[ids_person] == -1))
++ print(' persons having no motorcycle', len(np.flatnonzero(persons.ids_imoto[ids_person] == -1)))
+
+ # put 0 for persons with motorcycle but with a different preferred mode
+ preeval[(persons.ids_imoto[ids_person] > -1)
+ & (persons.ids_mode_preferred[ids_person] != self._id_mode_moto)] = 0
+
+- print ' persons with motorcycle but with a different preferred mode', len(np.flatnonzero((persons.ids_imoto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_moto)))
++ print(' persons with motorcycle but with a different preferred mode', len(np.flatnonzero((persons.ids_imoto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_moto))))
+
+ # put 2 for persons with motorcycle access and who prefer the car
+ preeval[(persons.ids_imoto[ids_person] > -1)
+ & (persons.ids_mode_preferred[ids_person] == self._id_mode_moto)] = 2
+- print ' persons with motorcycle access and who prefer the car', len(np.flatnonzero((persons.ids_imoto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_moto)))
++ print(' persons with motorcycle access and who prefer the car', len(np.flatnonzero((persons.ids_imoto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_moto))))
+
+ return preeval
+
+@@ -3056,7 +3056,7 @@
+ pos = 0.5*self.length_edge_min
+
+ if id_motoedge == -1:
+- print 'WARNING in get_edge_motoaccess no access for', id_edge, self._edges.ids_sumo[id_edge]
++ print('WARNING in get_edge_motoaccess no access for', id_edge, self._edges.ids_sumo[id_edge])
+
+ if is_get_route:
+ return id_motoedge, pos, route
+@@ -3238,7 +3238,7 @@
+ = virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
+
+ if len(ids_person_act) == 0:
+- print 'WARNING in MotorcycleStrategy.plan: no eligible persons found.'
++ print('WARNING in MotorcycleStrategy.plan: no eligible persons found.')
+ return False
+
+ # ok
+@@ -3268,7 +3268,7 @@
+ #map_ids_parking_from[ids_person_act] = ids_parking_from
+
+ n_plans = len(ids_person_act)
+- print 'MotorcycleStrategy.plan n_plans=', n_plans
++ print('MotorcycleStrategy.plan n_plans=', n_plans)
+ # print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape
+ # set initial activity
+ # this is because the following steps start with travel
+@@ -3376,9 +3376,9 @@
+ if logger:
+ logger.progress(i/n_pers*100)
+ i += 1.0
+- print 79*'*'
+- print ' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to
+- print ' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to]
++ print(79*'*')
++ print(' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to)
++ print(' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to])
+
+ time = self.plan_motoride(id_plan, time_from, id_veh,
+ id_edge_from, pos_edge_from,
+@@ -3489,7 +3489,7 @@
+ # put 2 for persons with car access and who prefer cars
+ preeval[persons.ids_mode_preferred[ids_person] == self._id_mode_bus] = 2
+
+- print ' TransitStrategy.preevaluate', len(np.flatnonzero(preeval))
++ print(' TransitStrategy.preevaluate', len(np.flatnonzero(preeval)))
+ return preeval
+
+ def plan_transit(self, id_plan, time_from,
+@@ -3504,14 +3504,14 @@
+ ids_laneedge, ids_stoplane, ptstops):
+
+ edges = self.get_scenario().net.edges
+- print 'plan_transit id_plan', id_plan, 'id_edge_from %d (%s)' % (id_edge_from, edges.ids_sumo[id_edge_from]), 'id_edge_to %d (%s)' % (id_edge_to, edges.ids_sumo[id_edge_to])
++ print('plan_transit id_plan', id_plan, 'id_edge_from %d (%s)' % (id_edge_from, edges.ids_sumo[id_edge_from]), 'id_edge_to %d (%s)' % (id_edge_to, edges.ids_sumo[id_edge_to]))
+
+ # debug?
+ is_debug = False # id_plan == 14983
+
+ if is_debug:
+
+- print ' id_stop_from', id_stop_from, 'id_stop_to', id_stop_to
++ print(' id_stop_from', id_stop_from, 'id_stop_to', id_stop_to)
+
+ ptlinks = ptlines.get_ptlinks()
+ ptlinktypes = ptlinks.types.choices
+@@ -3527,9 +3527,9 @@
+ time = time_from
+ id_stage_walk1 = None
+ if is_debug:
+- print ' no initial walk required.'
+- print ' id_edge_from', id_edge_from, edges.ids_sumo[id_edge_from]
+- print ' pos_edge_from', pos_edge_from
++ print(' no initial walk required.')
++ print(' id_edge_from', id_edge_from, edges.ids_sumo[id_edge_from])
++ print(' pos_edge_from', pos_edge_from)
+ else:
+ id_stage_walk1, time = walkstages.append_stage(id_plan, time_from,
+ id_edge_from=id_edge_from,
+@@ -3538,20 +3538,20 @@
+ position_edge_to=pos_stop_from, # -7.0,
+ )
+ if is_debug:
+- print ' add initial walk stage'
+- print ' id_edge_from', id_edge_from, edges.ids_sumo[id_edge_from]
+- print ' pos_edge_from', pos_edge_from
+- print ' IIIInitial walk'
+- print ' id_stopedge_from', id_stopedge_from, edges.ids_sumo[id_stopedge_from]
+- print ' pos_stop_from', pos_stop_from
++ print(' add initial walk stage')
++ print(' id_edge_from', id_edge_from, edges.ids_sumo[id_edge_from])
++ print(' pos_edge_from', pos_edge_from)
++ print(' IIIInitial walk')
++ print(' id_stopedge_from', id_stopedge_from, edges.ids_sumo[id_stopedge_from])
++ print(' pos_stop_from', pos_stop_from)
+
+ if is_debug:
+- print ' TTTransit'
+- print ' id_stopedge_to', id_stopedge_to, edges.ids_sumo[id_stopedge_to]
+- print ' pos_stop_to', pos_stop_to
+- print ' ----------------------------------'
+- print ' id_stop_from', id_stop_from
+- print ' id_stop_to', id_stop_to
++ print(' TTTransit')
++ print(' id_stopedge_to', id_stopedge_to, edges.ids_sumo[id_stopedge_to])
++ print(' pos_stop_to', pos_stop_to)
++ print(' ----------------------------------')
++ print(' id_stop_from', id_stop_from)
++ print(' id_stop_to', id_stop_to)
+
+ durations, linktypes, ids_line, ids_fromstop, ids_tostop =\
+ ptlinks.route(id_stop_from, id_stop_to,
+@@ -3560,12 +3560,12 @@
+ stops_to_exit=stops_to_exit)
+
+ if is_debug:
+- print ' routing done. make plan, success', len(linktypes) > 0
++ print(' routing done. make plan, success', len(linktypes) > 0)
+
+ if is_debug:
+- print ' ids_line ', ids_line
+- print ' ids_fromstop', ids_fromstop
+- print ' ids_tostop ', ids_tostop
++ print(' ids_line ', ids_line)
++ print(' ids_fromstop', ids_fromstop)
++ print(' ids_tostop ', ids_tostop)
+
+ if (type_transit in linktypes): # is there any public transport line to take?
+
+@@ -3584,7 +3584,7 @@
+ # check if initial walk needs to be modified
+ if (id_stage_walk1 is not None) & (linktypes[0] == type_walk):
+ if is_debug:
+- print ' Modify initial walk from stop fromedge %d (%s) toedge %d (%s)' % (id_edge_from, edges.ids_sumo[id_edge_from], ids_stopedge_from[0], edges.ids_sumo[ids_stopedge_from[0]])
++ print(' Modify initial walk from stop fromedge %d (%s) toedge %d (%s)' % (id_edge_from, edges.ids_sumo[id_edge_from], ids_stopedge_from[0], edges.ids_sumo[ids_stopedge_from[0]]))
+
+ is_initial_walk_done = True
+ time = walkstages.modify_stage(
+@@ -3601,7 +3601,7 @@
+ for i, linktype, id_line, duration,\
+ id_stopedge_from, pos_fromstop,\
+ id_stopedge_to, pos_tostop in\
+- zip(xrange(len(linktypes)),
++ zip(range(len(linktypes)),
+ linktypes,
+ ids_line,
+ durations,
+@@ -3609,16 +3609,16 @@
+ ids_stopedge_to, poss_stop_to,
+ ):
+ if is_debug:
+- print ' ...........................'
+- print ' stage for linktype %2d fromedge %s toedge %s' % (linktype, edges.ids_sumo[id_stopedge_from], edges.ids_sumo[id_stopedge_to])
+- print ' id_stopedge_from,id_stopedge_to', id_stopedge_from, id_stopedge_to
++ print(' ...........................')
++ print(' stage for linktype %2d fromedge %s toedge %s' % (linktype, edges.ids_sumo[id_stopedge_from], edges.ids_sumo[id_stopedge_to]))
++ print(' id_stopedge_from,id_stopedge_to', id_stopedge_from, id_stopedge_to)
+
+ if linktype == type_transit: # transit!
+ # check if last link type has also been a transit
+ if i > 0:
+ if linktypes[i-1] == type_transit:
+ if is_debug:
+- print ' add inter-transit walk stage'
++ print(' add inter-transit walk stage')
+ # introdice a walk stage to be sure that
+ # person gets to the middle of the stop
+ id_stage_transfer, time = walkstages.append_stage(
+@@ -3631,7 +3631,7 @@
+ )
+
+ if is_debug:
+- print ' add transit stage id_line', id_line
++ print(' add transit stage id_line', id_line)
+ id_stage_transit, time = transitstages.append_stage(
+ id_plan, time,
+ id_line=id_line,
+@@ -3644,7 +3644,7 @@
+ elif (linktype == type_walk) & ((i > 0) | (not is_initial_walk_done)):
+ # walk to transfer, no initial walk if done
+ if is_debug:
+- print ' add walk to transfer'
++ print(' add walk to transfer')
+ id_stage_transfer, time = walkstages.append_stage(
+ id_plan, time,
+ id_edge_from=id_stopedge_from,
+@@ -3658,18 +3658,18 @@
+ else: # all other link time are no modelld
+ # do not do anything , just add wait time to next stage
+ if is_debug:
+- print ' do noting add duration', duration
++ print(' do noting add duration', duration)
+ duration_wait += duration
+
+ # walk from final stop to activity
+ i = len(linktypes)-1 # last link index
+
+ if is_debug:
+- print ' linktypes', linktypes, 'i', i, 'linktypes[i]', linktypes[i], linktypes[i] == type_walk
++ print(' linktypes', linktypes, 'i', i, 'linktypes[i]', linktypes[i], linktypes[i] == type_walk)
+
+ if linktypes[i] == type_walk:
+ if is_debug:
+- print ' Modify final walk from stop fromedge %d (%s) toedge %d (%s)' % (id_stopedge_to, edges.ids_sumo[id_stopedge_to], id_edge_to, edges.ids_sumo[id_edge_to])
++ print(' Modify final walk from stop fromedge %d (%s) toedge %d (%s)' % (id_stopedge_to, edges.ids_sumo[id_stopedge_to], id_edge_to, edges.ids_sumo[id_edge_to]))
+
+ time = walkstages.modify_stage(
+ id_stage_transfer,
+@@ -3681,7 +3681,7 @@
+
+ else:
+ if is_debug:
+- print ' Add final walk stage fromedge %d (%s) toedge %d (%s)' % (id_stopedge_to, edges.ids_sumo[id_stopedge_to], id_edge_to, edges.ids_sumo[id_edge_to])
++ print(' Add final walk stage fromedge %d (%s) toedge %d (%s)' % (id_stopedge_to, edges.ids_sumo[id_stopedge_to], id_edge_to, edges.ids_sumo[id_edge_to]))
+
+ id_stage_walk2, time = walkstages.append_stage(id_plan, time,
+ id_edge_from=id_stopedge_to,
+@@ -3693,7 +3693,7 @@
+ else:
+ # there is no public transport line linking these nodes.
+ if is_debug:
+- print ' No PT lines used create direct walk stage'
++ print(' No PT lines used create direct walk stage')
+
+ if id_stage_walk1 is None:
+ # Create first walk directly from home to activity
+@@ -3720,7 +3720,7 @@
+ Generates a plan for these person according to this strategie.
+ Overriden by specific strategy.
+ """
+- print 'TransitStrategy.plan', len(ids_person)
++ print('TransitStrategy.plan', len(ids_person))
+ #make_plans_private(self, ids_person = None, mode = 'passenger')
+ # routing necessary?
+ virtualpop = self.get_virtualpop()
+@@ -3752,12 +3752,12 @@
+ # print ' demand.virtualpop',demand.virtualpop,dir(demand.virtualpop)
+ # print ' demand.trips',demand.trips,dir(demand.trips)
+ if len(ptlines) == 0:
+- print 'WARNING in TrasitStrategy.plan: no transit services available. Create public trasit services by connecting stops.'
++ print('WARNING in TrasitStrategy.plan: no transit services available. Create public trasit services by connecting stops.')
+ return False
+
+ ptlinks = ptlines.get_ptlinks()
+ if len(ptlinks) == 0:
+- print 'WARNING in TrasitStrategy.plan: no public transport links. Run methods: "create routes" and "build links" from public trasport services.'
++ print('WARNING in TrasitStrategy.plan: no public transport links. Run methods: "create routes" and "build links" from public trasport services.')
+ return False
+
+ ptlinktypes = ptlinks.types.choices
+@@ -3779,7 +3779,7 @@
+ = virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
+
+ if len(ids_person_act) == 0:
+- print 'WARNING in TrasitStrategy.plan: no eligible persons found.'
++ print('WARNING in TrasitStrategy.plan: no eligible persons found.')
+ return False
+
+ # temporary maps from ids_person to other parameters
+@@ -3798,7 +3798,7 @@
+ map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]
+
+ n_plans = len(ids_person_act)
+- print 'TrasitStrategy.plan n_plans=', n_plans
++ print('TrasitStrategy.plan n_plans=', n_plans)
+
+ # make initial activity stage
+ ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]
+@@ -3883,8 +3883,8 @@
+ if logger:
+ logger.progress(i/n_pers*100)
+ i += 1.0
+- print 79*'_'
+- print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)
++ print(79*'_')
++ print(' id_plan=%d, id_person=%d, ' % (id_plan, id_person))
+
+ time = self.plan_transit(id_plan, time_from,
+ id_edge_from, pos_edge_from,
+@@ -3973,7 +3973,7 @@
+ # put 2 for persons with bike access and who prefer bike or bus
+ preeval[inds_avail & inds_prefer] = 1
+
+- print ' BikeTransitStrategy.preevaluate', len(np.flatnonzero(preeval))
++ print(' BikeTransitStrategy.preevaluate', len(np.flatnonzero(preeval)))
+ return preeval
+
+ def plan(self, ids_person, logger=None, **kwargs):
+@@ -3981,7 +3981,7 @@
+ Generates a plan for these person according to this strategie.
+ Overriden by specific strategy.
+ """
+- print 'TransitStrategy.plan', len(ids_person)
++ print('TransitStrategy.plan', len(ids_person))
+ #make_plans_private(self, ids_person = None, mode = 'passenger')
+ # routing necessary?
+ virtualpop = self.get_virtualpop()
+@@ -4014,7 +4014,7 @@
+ # print ' demand.virtualpop',demand.virtualpop,dir(demand.virtualpop)
+ # print ' demand.trips',demand.trips,dir(demand.trips)
+ if len(ptlines) == 0:
+- print 'WARNING in TrasitStrategy.plan: no transit services available.'
++ print('WARNING in TrasitStrategy.plan: no transit services available.')
+ return False
+
+ ptlinks = ptlines.get_ptlinks()
+@@ -4037,7 +4037,7 @@
+ = virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
+
+ if len(ids_person_act) == 0:
+- print 'WARNING in TrasitStrategy.plan: no eligible persons found.'
++ print('WARNING in TrasitStrategy.plan: no eligible persons found.')
+ return False
+
+ # temporary maps from ids_person to other parameters
+@@ -4056,7 +4056,7 @@
+ map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]
+
+ n_plans = len(ids_person_act)
+- print 'TrasitStrategy.plan n_plans=', n_plans
++ print('TrasitStrategy.plan n_plans=', n_plans)
+
+ # make initial activity stage
+ ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]
+@@ -4149,8 +4149,8 @@
+ if logger:
+ logger.progress(i/n_pers*100)
+ i += 1.0
+- print 79*'_'
+- print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)
++ print(79*'_')
++ print(' id_plan=%d, id_person=%d, ' % (id_plan, id_person))
+ #dist_from_stop_from, dist_stop_to_to
+
+ time = self.plan_bikeride(id_plan, time_from, id_veh,
+@@ -4291,8 +4291,8 @@
+ 'motorcycle': np.array([170, 200, 0, 220], np.float32)/255,
+ 'taxi': np.array([40, 240, 240, 220], np.float32)/255,
+ }
+- ids = self.names.get_ids_from_indices_save(colors_default.keys())
+- self.colors[ids] = colors_default.values() # np.array(colors_default.values(), np.float32).reshape(-1,4)
++ ids = self.names.get_ids_from_indices_save(list(colors_default.keys()))
++ self.colors[ids] = list(colors_default.values()) # np.array(colors_default.values(), np.float32).reshape(-1,4)
+
+ #self.colors.indexset(colors_default.keys(), colors_default.values())
+
+@@ -4323,14 +4323,14 @@
+ 2 : Strategy uses predomunantly preferred mode
+
+ """
+- print 'preevaluate strategies'
++ print('preevaluate strategies')
+ ids_strat = self.get_ids()
+ n_pers = len(ids_person)
+ n_strat = len(ids_strat)
+
+ preeval = np.zeros((n_pers, n_strat), dtype=np.int32)
+- for i, strategy in zip(range(n_strat), self.strategies[ids_strat]):
+- print ' preevaluate strategiy', strategy.ident
++ for i, strategy in zip(list(range(n_strat)), self.strategies[ids_strat]):
++ print(' preevaluate strategiy', strategy.ident)
+ preeval[i, :] = strategy.preevaluate(ids_person)
+
+ return ids_strat, preeval
+@@ -4389,7 +4389,7 @@
+ ids = self.get_ids()
+ #ids_plan_part = self.ids_plan[ids]
+ are_selected = np.zeros(len(ids), dtype=np.bool)
+- for ind, id_plan_part in zip(xrange(len(ids)), self.ids_plan[ids]):
++ for ind, id_plan_part in zip(range(len(ids)), self.ids_plan[ids]):
+ are_selected[ind] = id_plan_part in ids_plan
+ return ids[are_selected]
+ # print ' ids_plan_part',type(ids_plan_part),ids_plan_part
+@@ -4437,9 +4437,9 @@
+ Returns a vector mapping id_edge to edge travel times
+ for given mode id_mode
+ """
+- print 'get_times', self._timesmap.keys()
+-
+- if not self._timesmap.has_key(id_mode):
++ print('get_times', list(self._timesmap.keys()))
++
++ if id_mode not in self._timesmap:
+ edges = self.get_virtualpop().get_scenario().net.edges
+ self._timesmap[id_mode] = edges.get_times(id_mode=id_mode,
+ is_check_lanes=True,
+@@ -4452,9 +4452,9 @@
+ Returns a vector mapping id_edge to edge distances
+ for given mode id_mode
+ """
+- print 'get_distances', self._distancesmap.keys()
+-
+- if not self._distancesmap.has_key(id_mode):
++ print('get_distances', list(self._distancesmap.keys()))
++
++ if id_mode not in self._distancesmap:
+ edges = self.get_virtualpop().get_scenario().net.edges
+ self._distancesmap[id_mode] = edges.get_distances(id_mode=id_mode,
+ is_check_lanes=True,
+@@ -4467,9 +4467,9 @@
+ Returns a fstar
+ for given mode id_mode
+ """
+- print 'get_fstar', self._fstarmap.keys()
+-
+- if not self._fstarmap.has_key(id_mode):
++ print('get_fstar', list(self._fstarmap.keys()))
++
++ if id_mode not in self._fstarmap:
+ edges = self.get_virtualpop().get_scenario().net.edges
+ self._fstarmap[id_mode] = edges.get_fstar(id_mode=id_mode,
+ is_ignor_connections=is_ignor_connections,
+@@ -4659,13 +4659,13 @@
+
+ If not feasible -1 and start time will be returned.
+ """
+- print 'Rides.append_stage id_plan', id_plan, is_fallback
++ print('Rides.append_stage id_plan', id_plan, is_fallback)
+
+ route, dist, duration, is_fallback = self.get_route_between_parking(
+ id_parking_from, id_parking_to, id_mode,
+ is_fallback, id_mode_fallback,)
+
+- print ' after routing: is_fallback', is_fallback, 'route', route
++ print(' after routing: is_fallback', is_fallback, 'route', route)
+
+ if (len(route) > 0): # |(dist > self.dist_ride_min.get_value()): # is there a connection
+ # create stage
+@@ -4697,7 +4697,7 @@
+
+
+ """
+- print 'get_route_between_parking', id_parking_from, id_parking_to, 'is_fallback', is_fallback, 'id_mode_fallback', id_mode_fallback
++ print('get_route_between_parking', id_parking_from, id_parking_to, 'is_fallback', is_fallback, 'id_mode_fallback', id_mode_fallback)
+ scenario = self.get_virtualpop().get_scenario()
+ edges = scenario.net.edges
+ lanes = scenario.net.lanes
+@@ -4711,11 +4711,11 @@
+ pos_from, pos_to = parking.positions[[id_parking_from, id_parking_to]]
+
+ if is_fallback & (id_mode_fallback is not None):
+- print ' use id_mode_fallback', id_mode_fallback
++ print(' use id_mode_fallback', id_mode_fallback)
+ id_mode_current = id_mode_fallback
+
+ else:
+- print ' use id_mode', id_mode
++ print(' use id_mode', id_mode)
+ id_mode_current = id_mode
+
+ # print ' id_edge_from, id_edge_to=',id_edge_from, id_edge_to
+@@ -4729,7 +4729,7 @@
+ if (len(route) == 0) & (not is_fallback) & (id_mode_fallback is not None):
+ is_fallback = True
+ id_mode_current = id_mode_fallback
+- print ' no route found with normal mode, try fallback', is_fallback
++ print(' no route found with normal mode, try fallback', is_fallback)
+ # now retry with fallback
+ duration_approx, route = routing.get_mincostroute_edge2edge(
+ id_edge_from,
+@@ -4738,7 +4738,7 @@
+ fstar=self.get_fstar(id_mode_current),
+ )
+ if len(route) > 0:
+- print ' fallback has been successful'
++ print(' fallback has been successful')
+
+ # here is a big problem: starting with the successive node of edge_from
+ # may result that the first edge of the route is not connected with edge_from
+@@ -4762,7 +4762,7 @@
+ # return str(self.ids_veh[id_stage])+'.'+str(i_ride)
+
+ def get_writexmlinfo(self, ids_plan, is_route=True, is_plain=False):
+- print 'AutorideStages.get_writexmlinfo', len(ids_plan), is_route, 'is_plain', is_plain
++ print('AutorideStages.get_writexmlinfo', len(ids_plan), is_route, 'is_plain', is_plain)
+ iautos = self.get_virtualpop().get_iautos()
+ writefunc = iautos.prepare_write_xml(is_route, is_plain)
+
+@@ -4936,7 +4936,7 @@
+ return -1, time_start # no stage creation took place
+
+ def get_writexmlinfo(self, ids_plan, is_route=True, is_plain=False):
+- print 'BikerideStages.get_writexmlinfo', len(ids_plan), is_plain
++ print('BikerideStages.get_writexmlinfo', len(ids_plan), is_plain)
+ ibikes = self.get_virtualpop().get_ibikes()
+ bikewritefunc = ibikes.prepare_write_xml(is_plain=is_plain)
+ ids = self.get_ids_from_ids_plan(ids_plan)
+@@ -5110,7 +5110,7 @@
+ return -1, time_start # no stage creation took place
+
+ def get_writexmlinfo(self, ids_plan, is_route=True, is_plain=False):
+- print 'MotorcyclerideStages.get_writexmlinfo', len(ids_plan), is_plain
++ print('MotorcyclerideStages.get_writexmlinfo', len(ids_plan), is_plain)
+ imotos = self.get_virtualpop().get_imotos()
+ motowritefunc = imotos.prepare_write_xml(is_plain=is_plain)
+ ids = self.get_ids_from_ids_plan(ids_plan)
+@@ -5324,7 +5324,7 @@
+ position_edge_from=0.1, position_edge_to=0.0,
+ **kwargs):
+ # print 'WalkStages.append_stage',id_stage
+- if kwargs.has_key('duration'):
++ if 'duration' in kwargs:
+ duration = kwargs['duration']
+ else:
+ dist, duration = self.plan_walk(id_edge_from, id_edge_to,
+@@ -5652,7 +5652,7 @@
+ pass
+
+ def clear_plans(self):
+- print 'Plans.clear_plans'
++ print('Plans.clear_plans')
+ for stagetable in self.get_stagetables():
+ # print ' stagetable',stagetable
+ stagetable.clear()
+@@ -5918,7 +5918,7 @@
+ self.clear_rows()
+
+ def del_persons(self, ids_pers_delete):
+- print 'delete', len(ids_pers_delete), 'persons'
++ print('delete', len(ids_pers_delete), 'persons')
+ ids_plans_all = set()
+ ids_activity_del = set()
+ lists_ids_plan = self.lists_ids_plan[ids_pers_delete]
+@@ -5967,7 +5967,7 @@
+ """
+ Clear all individually owned vehicles.
+ """
+- print 'clear_ivehicles'
++ print('clear_ivehicles')
+ self.get_iautos().clear_vehicles()
+ self.get_ibikes().clear_vehicles()
+ self.get_imotos().clear_vehicles()
+@@ -6009,7 +6009,7 @@
+ return self.get_net().ptstops
+
+ def get_id_sumo_from_id(self, id_sumo):
+- return u'vp.%s' % id_sumo
++ return 'vp.%s' % id_sumo
+
+ def get_id_from_id_sumo(self, id_veh_sumo):
+ if len(id_veh_sumo.split('.')) == 2:
+@@ -6098,9 +6098,9 @@
+
+ """
+ tripnumber = int(scale*tripnumber_tot)
+- print 'disaggregate_odflow', time_start, time_end, id_mode, tripnumber
+-
+- print ' id_activitytype_orig,id_activitytype_dest', id_activitytype_orig, id_activitytype_dest
++ print('disaggregate_odflow', time_start, time_end, id_mode, tripnumber)
++
++ print(' id_activitytype_orig,id_activitytype_dest', id_activitytype_orig, id_activitytype_dest)
+
+ # print ' probs_orig',sum(probs_fac_orig)#,'\n',probs_fac_orig
+ # print ' probs_dest',sum(probs_fac_dest)#,'\n',probs_fac_dest
+@@ -6195,7 +6195,7 @@
+
+ return ids_person
+ else:
+- print 'WARNING in disaggregate_odflow: no probabilities', np.sum(probs_fac_orig), np.sum(probs_fac_dest)
++ print('WARNING in disaggregate_odflow: no probabilities', np.sum(probs_fac_orig), np.sum(probs_fac_dest))
+
+ return []
+
+@@ -6208,7 +6208,7 @@
+ if landusetype_orig and landusetype_dest also landuse types
+ of facilities of origin and destination are taken into account.
+ """
+- print 'create_pop_from_odflows'
++ print('create_pop_from_odflows')
+
+ demand = self.parent
+ odflowtab = demand.odintervals.generate_odflows()
+@@ -6320,7 +6320,7 @@
+ # return odflowtab
+
+ def add_plans(self, ids_person, id_strategy=-1):
+- print 'add_plans n, id_strategy', len(ids_person), id_strategy
++ print('add_plans n, id_strategy', len(ids_person), id_strategy)
+ n_plans = len(ids_person)
+ # print ' get_plans',self.get_plans()
+ # print ' stagetables',self.get_plans().get_stagetables().get_ident_abs()
+@@ -6361,7 +6361,7 @@
+ # if id_strat_pers
+
+ ids_person_preeval = ids_person[inds_preeval]
+- print 'plan_with_strategy', strategy.ident, 'n_pers', len(ids_person_preeval)
++ print('plan_with_strategy', strategy.ident, 'n_pers', len(ids_person_preeval))
+
+ # TODO: is_substitute = is_substitute could be an argument to plan()
+ # and then passed to the centralized add_plan() method of the VP.
+@@ -6444,7 +6444,7 @@
+ ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]
+ n_pers = len(ids_pers)
+ preevals = -1*np.ones((np.max(ids_pers)+1, np.max(ids_strat)+1), dtype=np.int32)
+- for ind, id_strategy, strategy in zip(range(n_strat), ids_strat, strategies.strategies[ids_strat]):
++ for ind, id_strategy, strategy in zip(list(range(n_strat)), ids_strat, strategies.strategies[ids_strat]):
+ preevals[ids_pers, id_strategy] = strategy.preevaluate(ids_pers)
+
+ preferred = 2
+@@ -6453,10 +6453,10 @@
+ for id_pers, ids_plan in zip(ids_pers, self.lists_ids_plan[ids_pers]):
+ if ids_plan is not None:
+ if len(ids_plan) > 0:
+- print ' id_pers,ids_plan', id_pers, ids_plan
+- print ' ids_strat, preeval', plans.ids_strategy[ids_plan], preevals[id_pers, plans.ids_strategy[ids_plan]]
++ print(' id_pers,ids_plan', id_pers, ids_plan)
++ print(' ids_strat, preeval', plans.ids_strategy[ids_plan], preevals[id_pers, plans.ids_strategy[ids_plan]])
+ inds_sel = np.flatnonzero(preevals[id_pers, plans.ids_strategy[ids_plan]] == preferred)
+- print ' inds_sel', inds_sel, inds_sel.dtype
++ print(' inds_sel', inds_sel, inds_sel.dtype)
+ if len(inds_sel) > 0:
+ #ids_plan_sel = np.array(ids_plan)[inds_sel]
+ # print ' ids_plan_sel',ids_plan_sel
+@@ -6485,7 +6485,7 @@
+ times_rand = np.random.normal(0.0, timedev, len(ids_plan))
+ elif c_probit > 0:
+ times_rand = np.zeros(len(ids_plan), dtype=np.float32)
+- for i, t in zip(xrange(len(ids_plan)), times_est[ids_plan]):
++ for i, t in zip(range(len(ids_plan)), times_est[ids_plan]):
+ times_rand[i] = np.random.normal(0.0, c_probit * t, 1)
+
+ else:
+@@ -6500,13 +6500,13 @@
+ """
+
+ ids_pers_all = self.get_ids()
+- print 'select_plans_random', len(ids_pers_all), fraction
++ print('select_plans_random', len(ids_pers_all), fraction)
+ times_est = self.get_plans().times_est
+ # self.ids_plan.reset()
+ # ids_mode[random_choice(n,shares/np.sum(shares))]
+
+ ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]
+- print ' ids_pers', ids_pers
++ print(' ids_pers', ids_pers)
+ for id_pers, ids_plan in zip(ids_pers, self.lists_ids_plan[ids_pers]):
+ if len(ids_plan) > 0:
+ # print ' id_pers,ids_plan',id_pers,ids_plan
+@@ -6531,7 +6531,7 @@
+ times_rand = np.random.normal(0.0, timedev, len(ids_plan))
+ elif c_probit > 0:
+ times_rand = np.zeros(len(ids_plan), dtype=np.float32)
+- for i, t in zip(xrange(len(ids_plan)), times_exec[ids_plan]):
++ for i, t in zip(range(len(ids_plan)), times_exec[ids_plan]):
+ times_rand[i] = np.random.normal(0.0, c_probit * t, 1)
+
+ else:
+@@ -6576,11 +6576,11 @@
+ elif c_probit > 0:
+ if len(ids_plan_est) > 0:
+ times_rand_est = np.zeros(len(ids_plan_est), dtype=np.float32)
+- for i, t in zip(xrange(len(ids_plan_est)), times_est[ids_plan_est]):
++ for i, t in zip(range(len(ids_plan_est)), times_est[ids_plan_est]):
+ times_rand_est[i] = np.random.normal(0.0, c_probit * t, 1)
+ if len(ids_plan_exec) > 0:
+ times_rand_exec = np.zeros(len(ids_plan_exec), dtype=np.float32)
+- for i, t in zip(xrange(len(ids_plan_exec)), times_exec[ids_plan_exec]):
++ for i, t in zip(range(len(ids_plan_exec)), times_exec[ids_plan_exec]):
+ times_rand_exec[i] = np.random.normal(0.0, c_probit * t, 1)
+
+ else:
+@@ -6604,7 +6604,7 @@
+ self.ids_plan[id_pers] = np.array(ids_plan_exec)[np.argmin(
+ times_exec[ids_plan_exec]+times_rand_exec)]
+
+- print 'were analyzed %d persons' % (n_analyzed_persons)
++ print('were analyzed %d persons' % (n_analyzed_persons))
+ return True
+
+ def select_plans_next(self, fraction=0.1, **kwargs):
+@@ -6645,7 +6645,7 @@
+ plans = self.get_plans()
+ ids_pers_all = self.get_ids()
+
+- print 'select_plans_utility_function', len(ids_pers_all)
++ print('select_plans_utility_function', len(ids_pers_all))
+
+ ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]
+ times_exec = self.get_plans().times_exec
+@@ -6710,7 +6710,7 @@
+
+ Method used to sort trips when exporting to route or trip xml file
+ """
+- print 'Virtualpop.get_writexmlinfo is_plain', is_plain
++ print('Virtualpop.get_writexmlinfo is_plain', is_plain)
+ plans = self.get_plans()
+
+ ids_pers = self.select_ids(self.ids_plan.get_value() >= 0)
+@@ -6741,9 +6741,9 @@
+ writefuncs_pers[:] = self.write_person_xml
+
+ # assemble vectors
+- print ' times_depart_pers.shape', times_depart_pers.shape
+- print ' times_depart_bike.shape', times_depart_bike.shape
+- print ' times_depart_auto.shape', times_depart_auto.shape
++ print(' times_depart_pers.shape', times_depart_pers.shape)
++ print(' times_depart_bike.shape', times_depart_bike.shape)
++ print(' times_depart_auto.shape', times_depart_auto.shape)
+ times_depart = np.concatenate((times_depart_pers,
+ times_depart_auto,
+ times_depart_bike,
+@@ -6850,7 +6850,7 @@
+ """
+
+ ids_res = personresults.get_ids()
+- print 'update_results', len(ids_res)
++ print('update_results', len(ids_res))
+ ids_person = personresults.ids_person[ids_res]
+ ids_plan = self.ids_plan[ids_person]
+ self.get_plans().times_exec[ids_plan] = personresults.times_travel_total[ids_res]
+@@ -6864,7 +6864,7 @@
+ """Reads route information of vehicles, and overwrites existing routes in stages.
+ Used for example read results from Duaiterate process.
+ """
+- print 'Virtualop.import_routes_xml from %s' % (filepath)
++ print('Virtualop.import_routes_xml from %s' % (filepath))
+ if is_clear_trips:
+ self.clear_trips()
+
+@@ -6873,11 +6873,11 @@
+ reader = RouteReaderVp(self, counter)
+ if 1: # try:
+ parse(filepath, reader)
+- print ' call make_routes', is_generate_ids, 'is_add', is_add
++ print(' call make_routes', is_generate_ids, 'is_add', is_add)
+ reader.insert_routes(ids_strategy=ids_strategy)
+
+ else: # except KeyError:
+- print >> sys.stderr, "Error: Problems with reading routes!"
++ print("Error: Problems with reading routes!", file=sys.stderr)
+ raise
+
+
+@@ -6890,7 +6890,7 @@
+ is_export_trips=True,
+ logger=None,
+ **kwargs):
+- print 'DuarouterVp.__init__ '
++ print('DuarouterVp.__init__ ')
+
+ self._init_common(ident, name='Virtual Population DUA router',
+ parent=virtualpop,
+@@ -6908,7 +6908,7 @@
+ if routefilepaths is None:
+ routefilepaths = demand.get_routefilepath()
+
+- print ' default routefilepaths', routefilepaths
++ print(' default routefilepaths', routefilepaths)
+ self.add_option('routefilepaths', routefilepaths,
+ groupnames=['files'],
+ cml='--route-files',
+@@ -6931,7 +6931,7 @@
+ # for id_strat, name_strat in zip(ids_strat, strategies.names[ids_strat]):
+ # strategychoices[name_strat] = id_strat
+ strategychoices = strategies.names.get_indexmap()
+- self.ids_strategy = attrsman.add(cm.ListConf('ids_strategy', kwargs.get('ids_strategy', strategychoices.values()),
++ self.ids_strategy = attrsman.add(cm.ListConf('ids_strategy', kwargs.get('ids_strategy', list(strategychoices.values())),
+ choices=strategychoices,
+ groupnames=['options'],
+ name='Rerouted strategies',
+@@ -6999,9 +6999,9 @@
+
+ self.run_cml(cml)
+ if self.status == 'success':
+- print ' DUA routing done.'
++ print(' DUA routing done.')
+ if os.path.isfile(self.outfilepath):
+- print ' outfile exists, start importing routes'
++ print(' outfile exists, start importing routes')
+ virtualpop.import_routes_xml(self.outfilepath, ids_strategy=self.ids_strategy)
+
+ return True
+@@ -7014,7 +7014,7 @@
+ def insert_routes(self, ids_strategy=None):
+
+ virtualpop = self._trips # parent is called trips here need to be changed
+- print 'RouteReaderVp.insert_routes found %d routes.' % (len(self.ids_sumo))
++ print('RouteReaderVp.insert_routes found %d routes.' % (len(self.ids_sumo)))
+ plans = virtualpop.get_plans()
+ strategies = virtualpop.get_strategies()
+ id_strat_auto = strategies.names.get_id_from_index('auto')
+@@ -7034,7 +7034,7 @@
+ # print ' before:',stages.ids_edges[id_stage]
+ if stages.ids_edges[id_stage] != ids_edge:
+ n_change_route += 1
+- print ' route change of id_veh', id_veh, 'id_stage', id_stage
++ print(' route change of id_veh', id_veh, 'id_stage', id_stage)
+ stages.ids_edges[id_stage] = ids_edge
+ # print ' after :',stages.ids_edges[id_stage]
+
+@@ -7048,7 +7048,7 @@
+ # print ' before:',stages.ids_edges[id_stage]
+ if stages.ids_edges[id_stage] != ids_edge:
+ n_change_route += 1
+- print ' route change of id_veh', id_veh, 'id_stage', id_stage
++ print(' route change of id_veh', id_veh, 'id_stage', id_stage)
+ stages.ids_edges[id_stage] = ids_edge
+ # print ' after :',stages.ids_edges[id_stage]
+
+@@ -7062,15 +7062,15 @@
+ # print ' before:',stages.ids_edges[id_stage]
+ if stages.ids_edges[id_stage] != ids_edge:
+ n_change_route += 1
+- print ' route change of id_veh', id_veh, 'id_stage', id_stage
++ print(' route change of id_veh', id_veh, 'id_stage', id_stage)
+ stages.ids_edges[id_stage] = ids_edge
+ # print ' after :',stages.ids_edges[id_stage]
+- print ' RouteReaderVp: Total number of changed routes:', n_change_route
++ print(' RouteReaderVp: Total number of changed routes:', n_change_route)
+
+
+ class PopGenerator(Process):
+ def __init__(self, ident='virtualpopgenerator', virtualpop=None, logger=None, **kwargs):
+- print 'PopFromOdfGenerator.__init__ ', ident, virtualpop
++ print('PopFromOdfGenerator.__init__ ', ident, virtualpop)
+
+ # TODO: let this be independent, link to it or child??
+ #
+@@ -7170,7 +7170,7 @@
+ #self.modeshares = attrsman.add( cm.ObjConf(ModeShares('modeshares',self,scenario.net.modes),groupnames = ['options']) )
+
+ def do(self):
+- print 'PopGenerator.do'
++ print('PopGenerator.do')
+ # links
+
+ virtualpop = self.parent
+@@ -7186,7 +7186,7 @@
+ ids_fac = facilities.get_ids()
+ map_id_edge_to_ids_fac = {}
+ for id_fac, id_edge in zip(ids_fac, facilities.ids_roadedge_closest[ids_fac]):
+- if map_id_edge_to_ids_fac.has_key(id_edge):
++ if id_edge in map_id_edge_to_ids_fac:
+ map_id_edge_to_ids_fac[id_edge].append(id_fac)
+ else:
+ map_id_edge_to_ids_fac[id_edge] = [id_fac, ]
+@@ -7250,7 +7250,7 @@
+ # id_from_check = btree[id_from_check]
+ # #print ' id_edge = ',id_from_check
+ # print ' success = ',id_from_check==id_edge_to
+- if map_id_edge_to_ids_fac.has_key(id_edge_from):
++ if id_edge_from in map_id_edge_to_ids_fac:
+ ids_fac_lim += map_id_edge_to_ids_fac[id_edge_from]
+
+ if len(ids_fac_lim) == 0:
+@@ -7259,7 +7259,7 @@
+ # this will reduce travel time
+ for id_edge_from in ids_edge_from:
+ # verify if id_edge_from has facilities.
+- while not map_id_edge_to_ids_fac.has_key(id_edge_from):
++ while id_edge_from not in map_id_edge_to_ids_fac:
+ # print ' no facility, go backward'
+ id_edge_from = btree[id_edge_from]
+
+@@ -7343,7 +7343,7 @@
+
+ class PopFromOdfGenerator(Process):
+ def __init__(self, ident, virtualpop, logger=None, **kwargs):
+- print 'PopFromOdfGenerator.__init__'
++ print('PopFromOdfGenerator.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -7417,7 +7417,7 @@
+ ))
+
+ def do(self):
+- print 'PopFromOdfGenerator.do'
++ print('PopFromOdfGenerator.do')
+ # links
+
+ virtualpop = self.parent
+@@ -7438,7 +7438,7 @@
+
+ class Planner(Process):
+ def __init__(self, ident='planner', virtualpop=None, ids_strategy=None, logger=None, **kwargs):
+- print 'Planner.__init__'
++ print('Planner.__init__')
+ # TODO: let this be independent, link to it or child??
+
+ self._init_common(ident,
+@@ -7457,12 +7457,12 @@
+
+ if (ids_strategy is None):
+ # no info given, select all
+- ids_strategy_default = strategychoices.values()
++ ids_strategy_default = list(strategychoices.values())
+
+ elif ids_strategy is not None:
+ ids_strategy_default = ids_strategy
+
+- print ' ids_strategy_default', ids_strategy_default
++ print(' ids_strategy_default', ids_strategy_default)
+ self.ids_strategy = attrsman.add(cm.ListConf('ids_strategy', ids_strategy_default,
+ groupnames=['options'],
+ choices=strategychoices,
+@@ -7496,7 +7496,7 @@
+ ))
+
+ def do(self):
+- print 'Planner.do', len(self.ids_strategy)
++ print('Planner.do', len(self.ids_strategy))
+ # links
+
+ virtualpop = self.parent
+@@ -7511,12 +7511,12 @@
+
+ i = 1
+ strategies = virtualpop.get_strategies()
+- print ' strategies:', self.ids_strategy, strategies.names[self.ids_strategy]
+- print ' instances', strategies.strategies[self.ids_strategy]
++ print(' strategies:', self.ids_strategy, strategies.names[self.ids_strategy])
++ print(' instances', strategies.strategies[self.ids_strategy])
+
+ n_strat = len(self.ids_strategy)
+ for id_strategy, strategy in zip(self.ids_strategy, strategies.strategies[self.ids_strategy]):
+- print ' current strategy', strategy, id(strategy)
++ print(' current strategy', strategy, id(strategy))
+ logger.w('Plan with '+strategy.get_name()+' (%d/%d)' % (i, n_strat))
+ virtualpop.plan_with_strategy(id_strategy, evalcrit=self.evalcrit,
+ is_plan_no_preferred=self.is_plan_no_preferred, logger=logger)
+@@ -7531,7 +7531,7 @@
+ methodname='plan with shortest estim. time',
+ logger=None, **kwargs):
+
+- print 'PlanSelector.__init__'
++ print('PlanSelector.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -7610,7 +7610,7 @@
+ ))
+
+ def do(self):
+- print 'Planner.do'
++ print('Planner.do')
+ # links
+
+ #virtualpop = self.parent
+@@ -7624,7 +7624,7 @@
+
+ class VehicleProvider(Process):
+ def __init__(self, ident='vehicleprovider', virtualpop=None, logger=None, **kwargs):
+- print 'VehicleProvider.__init__'
++ print('VehicleProvider.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -7667,7 +7667,7 @@
+ ))
+
+ def do(self):
+- print 'VehicleProvider.do'
++ print('VehicleProvider.do')
+ # links
+
+ virtualpop = self.parent
+@@ -7699,7 +7699,7 @@
+ ids_pers_assign = np.random.choice(ids_pers_miss, n_need, replace=False)
+ ids_iauto = iautos.assign_to_persons(ids_pers_assign)
+
+- print ' created %d autos, target share=%.2f, share = %.2f' % (iautos.get_share(is_abs=True), iautos.get_share(), self.share_autoowner)
++ print(' created %d autos, target share=%.2f, share = %.2f' % (iautos.get_share(is_abs=True), iautos.get_share(), self.share_autoowner))
+
+ ids_prefer_bike = virtualpop.select_ids(
+ (virtualpop.ids_mode_preferred.get_value() == id_mode_bike) & (virtualpop.ids_ibike.get_value() == -1))
+@@ -7713,7 +7713,7 @@
+ ids_pers_assign = np.random.choice(ids_pers_miss, n_need, replace=False)
+ ids_ibike = ibikes.assign_to_persons(ids_pers_assign)
+
+- print ' created %d bikes, target share=%.2f, share = %.2f' % (ibikes.get_share(is_abs=True), ibikes.get_share(), self.share_bikeowner)
++ print(' created %d bikes, target share=%.2f, share = %.2f' % (ibikes.get_share(is_abs=True), ibikes.get_share(), self.share_bikeowner))
+
+ ids_prefer_moto = virtualpop.select_ids(
+ (virtualpop.ids_mode_preferred.get_value() == id_mode_moto) & (virtualpop.ids_imoto.get_value() == -1))
+@@ -7726,7 +7726,7 @@
+ ids_pers_assign = np.random.choice(ids_pers_miss, n_need, replace=False)
+ ids_imoto = imotos.assign_to_persons(ids_pers_assign)
+
+- print ' created %d moto, target share=%.2f, share = %.2f' % (imotos.get_share(is_abs=True), imotos.get_share(), self.share_motorcycleowner)
++ print(' created %d moto, target share=%.2f, share = %.2f' % (imotos.get_share(is_abs=True), imotos.get_share(), self.share_motorcycleowner))
+ return True
+
+ # TODO: generate and assign additional vehicles
+--- tools/contributed/sumopy/coremodules/demand/virtualpop_results.py (original)
++++ tools/contributed/sumopy/coremodules/demand/virtualpop_results.py (refactored)
+@@ -129,7 +129,7 @@
+ return 'estutils_'+strategy.get_ident()
+
+ def add_results(self, scenario, ids_plan_before, ids_plan_after):
+- print 'add_results iteration:', len(self)+1
++ print('add_results iteration:', len(self)+1)
+ # print ' ids_plan_before',ids_plan_before
+ # print ' ids_plan_after',ids_plan_after
+ # print ' changes',np.sum(ids_plan_before != ids_plan_after)
+@@ -169,7 +169,7 @@
+ for id_strat, strategy in zip(ids_strat, strategies.strategies[ids_strat]):
+ inds_thisstrat_before = ids_strat_before == id_strat
+ inds_thisstrat_after = ids_strat_after == id_strat
+- print ' check', id_strat, strategy, np.sum(inds_thisstrat_before), np.sum(inds_thisstrat_after)
++ print(' check', id_strat, strategy, np.sum(inds_thisstrat_before), np.sum(inds_thisstrat_after))
+ stratcountattr = self.get_stratcountattr(strategy)
+ getattr(self, stratcountattr)[id_run] = np.sum(inds_thisstrat_after)
+
+@@ -233,7 +233,7 @@
+ 'default': 0.0, 'info': 'Time ending last trip or activity.', 'groupnames': ['tripdata']}),
+ ])
+
+- for attrname, kwargs in attrinfos.iteritems():
++ for attrname, kwargs in attrinfos.items():
+ self.add_resultattr(attrname, **kwargs)
+
+ # this is a special for route info
+@@ -252,7 +252,7 @@
+ # default cannot be kwarg
+ default = kwargs['default']
+ del kwargs['default']
+- if kwargs.has_key('groupnames'):
++ if 'groupnames' in kwargs:
+ kwargs['groupnames'].append('results')
+ else:
+ kwargs['groupnames'] = ['results']
+@@ -261,12 +261,12 @@
+
+ def import_xml(self, sumo, datapaths):
+ datapathkey = self.datapathkey.get_value()
+- if datapaths.has_key(datapathkey):
++ if datapathkey in datapaths:
+ self.import_sumoxml(datapaths[datapathkey], sumo)
+ self.get_persons().update_results(self)
+
+ def import_sumoxml(self, filepath, sumo):
+- print 'Personresults.import_sumoxml', self.get_persons().ident, filepath
++ print('Personresults.import_sumoxml', self.get_persons().ident, filepath)
+
+ reader = PersonReader(self.get_persons(), sumo)
+ parse(filepath, reader)
+--- tools/contributed/sumopy/coremodules/demand/virtualpop_results_mpl.py (original)
++++ tools/contributed/sumopy/coremodules/demand/virtualpop_results_mpl.py (refactored)
+@@ -40,7 +40,7 @@
+ name=name,
+ info=info, logger=logger)
+
+- print 'VirtualpopIteratePlotter.__init__', self.parent
++ print('VirtualpopIteratePlotter.__init__', self.parent)
+ attrsman = self.get_attrsman()
+
+ self.is_strategy_share = attrsman.add(cm.AttrConf('is_strategy_share', kwargs.get('is_strategy_share', True),
+@@ -75,7 +75,7 @@
+ self.add_save_options(**kwargs)
+
+ def show(self):
+- print 'show'
++ print('show')
+ # if self.axis is None:
+ self.init_figures()
+ plt.rc('lines', linewidth=self.width_line)
+@@ -83,7 +83,7 @@
+ # cycler('linestyle', ['-', '--', ':', '-.'])))
+
+ for plotattr in self.get_attrsman().get_group('plots'):
+- print ' ', plotattr.attrname, plotattr.get_value()
++ print(' ', plotattr.attrname, plotattr.get_value())
+ if plotattr.get_value():
+ plotattr.plotfunction()
+
+@@ -103,7 +103,7 @@
+ """
+ Plot total est times for each stategy over iterations.
+ """
+- print 'plot_strategy_share'
++ print('plot_strategy_share')
+ scenario = self.get_scenario()
+ simresults = scenario.simulation.results
+ vpiterstats = simresults.get_resultobj('vpiterstats')
+@@ -126,7 +126,7 @@
+ ident_strat = strategy.get_ident()
+ name_strat = strategy.get_name()
+ counts = self.get_resultattrconf(vpiterstats.get_stratcountattr(strategy))
+- print ' name_strat', name_strat, 'counts', counts
++ print(' name_strat', name_strat, 'counts', counts)
+ if np.any(counts[iters] > 0):
+ ax.plot(iters, 1.0*counts[iters]/trips_tot*100,
+ label=name_strat,
+@@ -157,7 +157,7 @@
+
+ def plot_strategy_changes(self):
+ """'Plot strategy changes over iterations."""
+- print 'plot_strategy_changes'
++ print('plot_strategy_changes')
+ scenario = self.get_scenario()
+ simresults = scenario.simulation.results
+ vpiterstats = simresults.get_resultobj('vpiterstats')
+@@ -188,7 +188,7 @@
+ self.save_fig('fig_changes')
+
+ def plot_strategy_time_tot_est(self):
+- print 'plot_strategy_time_tot_est'
++ print('plot_strategy_time_tot_est')
+ scenario = self.get_scenario()
+ simresults = scenario.simulation.results
+ vpiterstats = simresults.get_resultobj('vpiterstats')
+@@ -244,7 +244,7 @@
+ self.save_fig('fig_time_tot_est')
+
+ def plot_strategy_time_tot(self):
+- print 'plot_strategy_time_tot'
++ print('plot_strategy_time_tot')
+ scenario = self.get_scenario()
+ simresults = scenario.simulation.results
+ vpiterstats = simresults.get_resultobj('vpiterstats')
+@@ -307,7 +307,7 @@
+ self._init_common('strategyresultplotter', parent=virtualpop, name=name,
+ info=info, logger=logger)
+
+- print 'StrategyPlotter.__init__', self.parent
++ print('StrategyPlotter.__init__', self.parent)
+ attrsman = self.get_attrsman()
+
+ self.is_strategy_share = attrsman.add(cm.AttrConf('is_strategy_share', kwargs.get('is_strategy_share', True),
+@@ -364,7 +364,7 @@
+ self.add_save_options(**kwargs)
+
+ def show(self):
+- print 'show'
++ print('show')
+ # if self.axis is None:
+ self.init_figures()
+ plt.rc('lines', linewidth=self.width_line)
+@@ -372,7 +372,7 @@
+ # cycler('linestyle', ['-', '--', ':', '-.'])))
+
+ for plotattr in self.get_attrsman().get_group('plots'):
+- print ' ', plotattr.attrname, plotattr.get_value()
++ print(' ', plotattr.attrname, plotattr.get_value())
+ if plotattr.get_value():
+ plotattr.plotfunction()
+
+@@ -380,7 +380,7 @@
+ show_plot()
+
+ def plot_strategy_share(self):
+- print 'plot_strategy_share'
++ print('plot_strategy_share')
+ fig = self.create_figure()
+ ax = fig.add_subplot(111)
+
+@@ -437,7 +437,7 @@
+ self.save_fig('virtualpop_strategy_share_current')
+
+ def plot_strategy_times_est(self):
+- print 'plot_strategy_times_est'
++ print('plot_strategy_times_est')
+ fig = self.create_figure()
+ ax = fig.add_subplot(111)
+
+@@ -503,7 +503,7 @@
+ """
+ For each strategy plot its estimated travel time factor with respect to the fastest strategy of the same person
+ """
+- print 'plot_strategy_timefactors_est'
++ print('plot_strategy_timefactors_est')
+ fig = self.create_figure()
+ ax = fig.add_subplot(111)
+
+@@ -545,14 +545,14 @@
+
+ x_min = 0.0
+ x_max = 0.0
+- for id_strat, timefactors in strategytimefactors.iteritems():
++ for id_strat, timefactors in strategytimefactors.items():
+ if len(timefactors) > 0:
+ x_max = max(x_max, np.max(timefactors))
+
+ #bins = np.linspace(x_min,x_max,self.n_bins)
+ bins = np.arange(x_min, x_max, self.timeint_bins)
+ if len(bins) > 0:
+- for id_strat, timefactors in strategytimefactors.iteritems():
++ for id_strat, timefactors in strategytimefactors.items():
+ if len(timefactors) > 0:
+ self.plot_hist(ax, np.array(timefactors, dtype=np.float32),
+ bins=bins,
+@@ -583,7 +583,7 @@
+ """
+ For each strategy plot its travel executive time factor with respect to the fastest strategy of the same person
+ """
+- print 'plot_strategy_timefactors_est'
++ print('plot_strategy_timefactors_est')
+ fig = self.create_figure()
+ ax = fig.add_subplot(111)
+
+@@ -627,17 +627,17 @@
+ n_nonexistant += 1
+
+ if n_nonexistant > 0:
+- print ' WARNING: only %d of %d persons have not completed all strategies' % (n_nonexistant, n_pers)
++ print(' WARNING: only %d of %d persons have not completed all strategies' % (n_nonexistant, n_pers))
+ x_min = 0.0
+ x_max = 0.0
+- for id_strat, timefactors in strategytimefactors.iteritems():
++ for id_strat, timefactors in strategytimefactors.items():
+ if len(timefactors) > 0:
+ x_max = max(x_max, np.max(timefactors))
+
+ #bins = np.linspace(x_min,x_max,self.n_bins)
+ bins = np.arange(x_min, x_max, self.timeint_bins)
+ if len(bins) > 0:
+- for id_strat, timefactors in strategytimefactors.iteritems():
++ for id_strat, timefactors in strategytimefactors.items():
+ if len(timefactors) > 0:
+ self.plot_hist(ax, np.array(timefactors, dtype=np.float32),
+ bins=bins,
+--- tools/contributed/sumopy/coremodules/demand/virtualpop_wxgui.py (original)
++++ tools/contributed/sumopy/coremodules/demand/virtualpop_wxgui.py (refactored)
+@@ -24,13 +24,13 @@
+ from agilepy.lib_base.misc import get_inversemap
+ from agilepy.lib_wx.ogleditor import *
+ try:
+- import virtualpop_results_mpl as results_mpl
++ from . import virtualpop_results_mpl as results_mpl
+ is_mpl = True # we have matplotlib support
+ except:
+- print "WARNING: python matplotlib package not installed, no matplotlib plots."
++ print("WARNING: python matplotlib package not installed, no matplotlib plots.")
+ is_mpl = False
+
+-import virtualpop
++from . import virtualpop
+
+
+ from agilepy.lib_wx.processdialog import ProcessDialog, ProcessDialogInteractive
+@@ -199,7 +199,7 @@
+
+ # this does not return until the dialog is closed.
+ #val = dlg.ShowModal()
+- print 'on_create_pop_from_odflows'
++ print('on_create_pop_from_odflows')
+ dlg.Show()
+ dlg.MakeModal(True)
+
+@@ -221,7 +221,7 @@
+ # print 'You selected %d files:' % len(paths)
+ if len(paths) > 0:
+ filepath = paths[0]
+- print 'call import_routes_xml', filepath
++ print('call import_routes_xml', filepath)
+ self._demand.virtualpop.import_routes_xml(filepath)
+ self._mainframe.browse_obj(self._demand.virtualpop.get_plans())
+
+@@ -274,7 +274,7 @@
+
+ # this does not return until the dialog is closed.
+ #val = dlg.ShowModal()
+- print 'on_create_pop_from_odflows'
++ print('on_create_pop_from_odflows')
+ dlg.Show()
+ dlg.MakeModal(True)
+
+@@ -300,7 +300,7 @@
+
+ # this does not return until the dialog is closed.
+ #val = dlg.ShowModal()
+- print 'on_provide_vehicles'
++ print('on_provide_vehicles')
+ dlg.Show()
+ dlg.MakeModal(True)
+
+@@ -327,7 +327,7 @@
+
+ # this does not return until the dialog is closed.
+ #val = dlg.ShowModal()
+- print 'on_generate_plan'
++ print('on_generate_plan')
+ dlg.Show()
+ dlg.MakeModal(True)
+ if self.proc.status == 'success':
+@@ -444,8 +444,8 @@
+ scenario = self._demand.parent
+
+ vpiterstats = scenario.simulation.results.get_resultobj('vpiterstats')
+- print 'on_plot_iterations '
+- print ' vpiterstats ', vpiterstats
++ print('on_plot_iterations ')
++ print(' vpiterstats ', vpiterstats)
+ if is_mpl & (vpiterstats is not None):
+ resultplotter = results_mpl.IteratePlotter(scenario,
+ logger=self._mainframe.get_logger()
+--- tools/contributed/sumopy/coremodules/demand/wxgui.py (original)
++++ tools/contributed/sumopy/coremodules/demand/wxgui.py (refactored)
+@@ -28,13 +28,13 @@
+ from coremodules.network import routing
+ from coremodules.scenario.scenario import load_scenario
+
+-import demand
+-import turnflows
+-import origin_to_destination_wxgui as odgui
+-import turnflows_wxgui as turnflowsgui
+-import virtualpop_wxgui as virtualpopgui
+-import detectorflows_wxgui as detectorflowsgui
+-import publictransportservices_wxgui as pt
++from . import demand
++from . import turnflows
++from . import origin_to_destination_wxgui as odgui
++from . import turnflows_wxgui as turnflowsgui
++from . import virtualpop_wxgui as virtualpopgui
++from . import detectorflows_wxgui as detectorflowsgui
++from . import publictransportservices_wxgui as pt
+
+
+ class TripDrawings(Polygons):
+--- tools/contributed/sumopy/coremodules/landuse/CREATE_ZONES.py (original)
++++ tools/contributed/sumopy/coremodules/landuse/CREATE_ZONES.py (refactored)
+@@ -45,22 +45,22 @@
+
+ # CREATE ZONES by CLUSTER OF POINTS
+
+- print 'k-value cluster'
++ print('k-value cluster')
+ # k-value cluster
+ # https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.html
+
+ features = np.array(origin_dest_points)
+- print 'features', features
++ print('features', features)
+ # Whiten data
+ st_dev_x = np.std(features[:][0])
+ st_dev_y = np.std(features[:][1])
+- print 'st_dev_x', st_dev_x
+- print 'st_dev_y', st_dev_y
++ print('st_dev_x', st_dev_x)
++ print('st_dev_y', st_dev_y)
+
+ whitened = whiten(features)
+ # Find 2 clusters in the data
+ codebook, distortion = kmeans(features, n_zones)
+- print 'codebook', codebook
++ print('codebook', codebook)
+
+ features[:, 0] = features[:, 0]*st_dev_x
+ features[:, 1] = features[:, 1]*st_dev_y
+@@ -79,8 +79,8 @@
+ # myscenario.landuse.zones.clear()
+ vertices = vor.vertices
+ regions = vor.regions
+- print vertices
+- print regions
++ print(vertices)
++ print(regions)
+ zone_name = 1
+ for region in regions:
+ if region != []:
+@@ -88,11 +88,11 @@
+ for vertice in region:
+ shape.append([vertices[vertice][0], vertices[vertice][1], 0.])
+ ids_zone = myscenario.landuse.zones.get_ids()
+- print 'n_zones =', len(ids_zone)
+- print shape
++ print('n_zones =', len(ids_zone))
++ print(shape)
+ zone_name += 1
+ # np.concatenate(shape).astype(None)
+- print shape
++ print(shape)
+ myscenario.landuse.zones.make(zonename='zone_name', coord=np.zeros(
+ 3, dtype=np.float32), shape=shape, id_landusetype=6)
+ ids_zone = myscenario.landuse.zones.get_ids()
+--- tools/contributed/sumopy/coremodules/landuse/__init__.py (original)
++++ tools/contributed/sumopy/coremodules/landuse/__init__.py (refactored)
+@@ -18,12 +18,12 @@
+
+ __version__ = "0.0"
+
+-print 'init', __name__
++print('init', __name__)
+
+
+ def get_wxgui():
+ # try:
+- from wxgui import WxGui
++ from .wxgui import WxGui
+ return WxGui(__name__)
+ # except:
+ # return None
+--- tools/contributed/sumopy/coremodules/landuse/landuse.py (original)
++++ tools/contributed/sumopy/coremodules/landuse/landuse.py (refactored)
+@@ -16,7 +16,7 @@
+ # @author Joerg Schweizer
+ # @date 2012
+
+-import maps
++from . import maps
+ from agilepy.lib_base.processes import Process, CmlMixin
+ from collections import OrderedDict
+ from numpy import random
+@@ -64,7 +64,7 @@
+ fd_in = open(filepath_in, 'r')
+ fd_out = open(filepath_out, 'w')
+ for line in fd_in.readlines():
+- for oldstr, newstr in substitutes.iteritems():
++ for oldstr, newstr in substitutes.items():
+ line = line.replace(oldstr, newstr)
+ fd_out.write(line)
+ fd_in.close()
+@@ -453,7 +453,7 @@
+ # self.zones.update_netoffset(deltaoffset)
+ self.coords.value[:, :2] = self.coords.value[:, :2] + deltaoffset
+ shapes = self.shapes.value
+- for i in xrange(len(shapes)):
++ for i in range(len(shapes)):
+ s = np.array(shapes[i])
+ s[:, :2] = s[:, :2] + deltaoffset
+ shapes[i] = list(s)
+@@ -464,7 +464,7 @@
+ self.areas[id_zone] = find_area(shape)/1000000.0
+
+ def identify_zoneedges(self, id_zone):
+- print 'identify_zoneedges of id_zone', id_zone
++ print('identify_zoneedges of id_zone', id_zone)
+
+ if len(self.shapes[id_zone]) >= 3:
+ # must have at least 3 vertices to be an area
+@@ -492,9 +492,9 @@
+
+ # select and determine weights
+ self.ids_edges_inside[id_zone] = self.get_edges().get_ids(inds_within)
+- print ' found', len(self.ids_edges_inside[id_zone]), 'edges'
++ print(' found', len(self.ids_edges_inside[id_zone]), 'edges')
+ if len(self.ids_edges_inside[id_zone]) == 0:
+- print 'WARNING in identify_zoneedges: no edges found in zone', id_zone
++ print('WARNING in identify_zoneedges: no edges found in zone', id_zone)
+
+ def get_zoneedges_by_mode_fast(self, id_zone, id_mode, speed_max=None,
+ modeconst_excl=0.0, modeconst_mix=0.0,
+@@ -509,10 +509,10 @@
+ """
+
+ # print 'get_zoneedges_by_mode_fast id_zone',id_zone,'id_mode',id_mode
+- if not self._mode_to_edges_inside.has_key(id_mode):
++ if id_mode not in self._mode_to_edges_inside:
+ self._mode_to_edges_inside[id_mode] = {}
+
+- if not self._mode_to_edges_inside[id_mode].has_key(id_zone):
++ if id_zone not in self._mode_to_edges_inside[id_mode]:
+ self._mode_to_edges_inside[id_mode][id_zone] = self.get_zoneedges_by_mode(
+ id_zone, id_mode, weights=weights, fstar=fstar)
+ # print ' found edges',len(self._mode_to_edges_inside[id_mode][id_zone])
+@@ -552,7 +552,7 @@
+ # todo: rename ids_edges_orig to simply ids_edges
+ ids_edge_orig = self.ids_edges_orig[id_zone]
+ if ids_edge_orig is None:
+- print 'WARNING: no edges in zone', id_zone, '. Run edge detection first.'
++ print('WARNING: no edges in zone', id_zone, '. Run edge detection first.')
+ if is_dict:
+ return {}
+ else:
+@@ -647,7 +647,7 @@
+ fd.write(xm.end('Placemark', indent + 2))
+
+ def write_xml(self, fd=None, indent=0):
+- print 'Zones.write_xml'
++ print('Zones.write_xml')
+ net = self.parent.parent.net
+ ids_edge_sumo = net.edges.ids_sumo
+ ids_zone = self.get_ids()
+@@ -715,7 +715,7 @@
+ """
+ Export zones to Google kml file formate.
+ """
+- print 'export_sumoxml', filepath, len(self)
++ print('export_sumoxml', filepath, len(self))
+ if len(self) == 0:
+ return None
+
+@@ -725,7 +725,7 @@
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in write_obj_to_xml: could not open', filepath
++ print('WARNING in write_obj_to_xml: could not open', filepath)
+ return False
+ #xmltag, xmltag_item, attrname_id = self.xmltag
+ fd.write('\n' % encoding)
+@@ -746,7 +746,7 @@
+ """
+ Export zones to SUMO xml file formate.
+ """
+- print 'export_sumoxml', filepath, len(self)
++ print('export_sumoxml', filepath, len(self))
+ if len(self) == 0:
+ return None
+
+@@ -756,7 +756,7 @@
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in export_sumoxml: could not open', filepath
++ print('WARNING in export_sumoxml: could not open', filepath)
+ return False
+ #xmltag, xmltag_item, attrname_id = self.xmltag
+ #fd.write('\n'%encoding)
+@@ -1372,7 +1372,7 @@
+ # self.zones.update_netoffset(deltaoffset)
+ self.centroids.value[:, :2] = self.centroids.value[:, :2] + deltaoffset
+ shapes = self.shapes.value
+- for i in xrange(len(shapes)):
++ for i in range(len(shapes)):
+ s = np.array(shapes[i])
+ s[:, :2] = s[:, :2] + deltaoffset
+ shapes[i] = list(s)
+@@ -1437,7 +1437,7 @@
+ The ids_fac is an array that contains the facility ids in correspondence
+ to the probability vector.
+ """
+- print 'get_departure_probabilities_landuse2 ids_landusetype', ids_landusetype
++ print('get_departure_probabilities_landuse2 ids_landusetype', ids_landusetype)
+ probabilities = {}
+ zones = self.ids_zone.get_linktab()
+ inds_fac = self.get_inds()
+@@ -1466,13 +1466,13 @@
+ probabilities[id_zone] = utils # all zero prob
+
+ if 0: # debug
+- print ' sum(probs)', np.sum(probabilities[id_zone])
++ print(' sum(probs)', np.sum(probabilities[id_zone]))
+ if np.sum(probabilities[id_zone]) > 0:
+ ids_fac = self.get_ids(inds_fac)
+ for id_fac, id_landusetype, id_thiszone, prob in zip(ids_fac, self.ids_landusetype[ids_fac], self.ids_zone[ids_fac], probabilities[id_zone]):
+ if (id_thiszone == id_zone): # & (id_landusetype in ids_landusetype):
+ if prob > 0:
+- print ' id_fac', id_fac, 'id_landusetype', id_landusetype, 'prob', prob
++ print(' id_fac', id_fac, 'id_landusetype', id_landusetype, 'prob', prob)
+
+ return probabilities, self.get_ids(inds_fac)
+
+@@ -1486,14 +1486,14 @@
+ The ids_fac is an array that contains the facility ids in correspondence
+ to the probability vector.
+ """
+- print 'get_departure_probabilities_landuse'
++ print('get_departure_probabilities_landuse')
+ probabilities = {}
+ zones = self.ids_zone.get_linktab()
+ inds_fac = self.get_inds()
+ for id_zone in zones.get_ids():
+ probabilities[id_zone] = {}
+ for id_landusetype in set(self.ids_landusetype.value):
+- print ' id_zone,id_landusetype', id_zone, id_landusetype
++ print(' id_zone,id_landusetype', id_zone, id_landusetype)
+ # print ' ids_landusetype',self.ids_landusetype.value[inds_fac]
+ # print ' ids_zone',self.ids_zone.value[inds_fac]
+ # print ''
+@@ -1548,7 +1548,7 @@
+
+ def identify_landuse_from_area(self, ids_fac=None):
+ """Determines the landuse of facilities from the landuse of areas in which their are located"""
+- print 'identify_landuse_from_area', ids_fac
++ print('identify_landuse_from_area', ids_fac)
+ # TODO:
+ landusetypes = self.get_landusetypes()
+ ids_area = self.get_ids_area(ids_fac)
+@@ -1560,8 +1560,8 @@
+
+ if osmkey == 'building.yes':
+ if is_point_in_polygon(coord[:2], np.array(shape, dtype=np.float32)[:, :2], is_use_shapely=IS_SHAPELY):
+- print ' found id_fac', id_fac, osmkey, 'in id_area', id_area
+- print ' id_landusetype', self.ids_landusetype[id_fac], 'is_area', landusetypes.are_area[self.ids_landusetype[id_fac]], '->', id_landusetype_fac
++ print(' found id_fac', id_fac, osmkey, 'in id_area', id_area)
++ print(' id_landusetype', self.ids_landusetype[id_fac], 'is_area', landusetypes.are_area[self.ids_landusetype[id_fac]], '->', id_landusetype_fac)
+ self.ids_landusetype[id_fac] = id_landusetype_fac
+
+ def update_centroid(self, _id):
+@@ -1605,7 +1605,7 @@
+ is closest to the centoid of each facility and the satisfies certain
+ conditions.
+ """
+- print 'identify_closest_edge'
++ print('identify_closest_edge')
+ edges = self.get_edges()
+ id_ped = self.get_net().modes.get_id_mode('pedestrian')
+ # select edges...if (edges.priorities[id_edge]<=priority_max) & edges.has_sidewalk(id_edge):
+@@ -1635,7 +1635,7 @@
+ pos = 0.0
+ x1, y1, z1 = shape[0]
+ edgelength = edges.lengths[id_edge]
+- for j in xrange(1, n_segs):
++ for j in range(1, n_segs):
+ x2, y2, z2 = shape[j]
+ d, xp, yp = shortest_dist(x1, y1, x2, y2, xc, yc)
+ # print ' x1,y1=(%d,%d)'%(x1,y1),',x2,y2=(%d,%d)'%(x2,y2),',xc,yc=(%d,%d)'%(xc,yc)
+@@ -1713,7 +1713,7 @@
+ self.update(ids)
+
+ def import_poly(self, polyfilepath, is_remove_xmlfiles=False, is_clear=True, **kwargs):
+- print 'import_poly from %s ' % (polyfilepath,)
++ print('import_poly from %s ' % (polyfilepath,))
+ if is_clear:
+ self.clear()
+ # let's read first the offset information, which are in the
+@@ -1749,7 +1749,7 @@
+ # self.update()
+
+ # timeit
+- print ' exec time=', time.clock() - exectime_start
++ print(' exec time=', time.clock() - exectime_start)
+
+ # print ' self.shapes',self.shapes.value
+
+@@ -1806,7 +1806,7 @@
+ """
+ Export stops to SUMO stop xml file.
+ """
+- print 'export_sumoxml', filepath, len(self)
++ print('export_sumoxml', filepath, len(self))
+ if len(self) == 0:
+ return None
+
+@@ -1816,7 +1816,7 @@
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in write_obj_to_xml: could not open', filepath
++ print('WARNING in write_obj_to_xml: could not open', filepath)
+ return False
+ #xmltag, xmltag_item, attrname_id = self.xmltag
+ fd.write('\n' % encoding)
+@@ -1908,7 +1908,7 @@
+ def get_landuse(self, osmkey):
+ keyvec = osmkey.split('.')
+ len_keyvec = len(keyvec)
+- print 'get_landuse', len_keyvec, keyvec
++ print('get_landuse', len_keyvec, keyvec)
+ #is_match = False
+ for id_landusetype in self._ids_landusetype_all:
+ # print ' id_landusetype',id_landusetype
+@@ -1918,7 +1918,7 @@
+ for osmfilter in self._osmfilters[id_landusetype]:
+ # print ' ?osmfiltervec',osmfilter,osmkey==osmfilter
+ if osmkey == osmfilter: # exact match of filter
+- print ' exact', osmkey
++ print(' exact', osmkey)
+ return id_landusetype
+
+ # now check for wildcards
+@@ -1931,7 +1931,7 @@
+ if (len(osmfiltervec) == 2) & (len_keyvec == 2):
+ if osmfiltervec[0] == keyvec[0]:
+ if osmfiltervec[1] == '*':
+- print ' *', keyvec[0]
++ print(' *', keyvec[0])
+ return id_landusetype
+ return -1
+
+@@ -2132,7 +2132,7 @@
+ is_clear=True,
+ logger=None,
+ **kwargs):
+- print 'make_parking'
++ print('make_parking')
+ if is_clear:
+ self.clear()
+ edges = self.edges.get_value()
+@@ -2162,7 +2162,7 @@
+ pos_offset = length_noparking
+ pos = pos_offset
+ if n_spaces > 0:
+- for i in xrange(n_spaces):
++ for i in range(n_spaces):
+ #id_park = self.suggest_id()
+ # print ' pos=',pos,pos/edges.lengths[id_edge]
+
+@@ -2180,7 +2180,7 @@
+ ids_parking.append(id_park)
+ pos = pos_offset+(i+1)*length_lot
+
+- print ' created %d parking spaces' % n_parking
++ print(' created %d parking spaces' % n_parking)
+ return ids_parking
+
+ def clear_booking(self):
+@@ -2194,7 +2194,7 @@
+ """
+
+ #inds_person = self.persons.get_inds(ids_person)
+- print 'get_closest_parking'
++ print('get_closest_parking')
+ ind_parking_closest = self.get_inds()[np.argmin(
+ np.sum((coord-self.vertices.value[:, 1, :])**2, 1) + c_spread*lengths*self.lengths.get_value())]
+ self.numbers_booking.get_value()[ind_parking_closest] += 1
+@@ -2215,7 +2215,7 @@
+
+ # print 'get_closest_parking',n,len(self),'n_retrials',n_retrials
+ if len(self) == 0:
+- print 'WARNING in get_closest_parkings: there is no parking.'
++ print('WARNING in get_closest_parkings: there is no parking.')
+ return [], []
+
+ #parking = self.get_landuse().parking
+@@ -2274,8 +2274,8 @@
+ # print ' fallback n_search',n_search,'is_search',is_search
+
+ if is_search:
+- print 'WARNING: inaccessible parking for id_veh', id_veh, 'is_fallback', is_fallback
+- print ' dist=%.1f' % (np.sqrt(dists[ind_parking_closest])), 'id_lane', ids_lane[ind_parking_closest], 'al', lanes.get_accesslevel([ids_lane[ind_parking_closest]], id_mode_fallback)
++ print('WARNING: inaccessible parking for id_veh', id_veh, 'is_fallback', is_fallback)
++ print(' dist=%.1f' % (np.sqrt(dists[ind_parking_closest])), 'id_lane', ids_lane[ind_parking_closest], 'al', lanes.get_accesslevel([ids_lane[ind_parking_closest]], id_mode_fallback))
+
+ inds_vehparking[i] = ind_parking_closest
+ are_fallback[i] = is_fallback
+@@ -2387,11 +2387,11 @@
+ else:
+ filepath = os.path.join(os.getcwd(), 'landuse.poly.xml')
+
+- print 'export_polyxml', filepath
++ print('export_polyxml', filepath)
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in export_poly_xml: could not open', filepath
++ print('WARNING in export_poly_xml: could not open', filepath)
+ return None
+
+ #xmltag, xmltag_item, attrname_id = self.xmltag
+@@ -2442,7 +2442,7 @@
+
+ class FacilityGenerator(Process):
+ def __init__(self, ident='facilitygenerator', facilities=None, logger=None, **kwargs):
+- print 'FacilityGenerator.__init__'
++ print('FacilityGenerator.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -2503,7 +2503,7 @@
+ # ))
+
+ def do(self):
+- print self.get_name()+'.do'
++ print(self.get_name()+'.do')
+ # links
+ facilities = self.parent
+ net = facilities.parent.get_net()
+@@ -2637,7 +2637,7 @@
+
+ # check if positions on parallel shape are closest to
+ # this edge or closer to another edge
+- print ' Done, generated %d facilities' % n_fac
++ print(' Done, generated %d facilities' % n_fac)
+ return True
+
+ def get_segind_closest_edge(self, p, x1, y1, x2, y2, inds_seg_exclude=None):
+@@ -2650,7 +2650,7 @@
+
+ class ParkingGenerator(Process):
+ def __init__(self, ident='parkinggenerator', parking=None, logger=None, **kwargs):
+- print 'ParkingGenerator.__init__'
++ print('ParkingGenerator.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -2724,7 +2724,7 @@
+ ))
+
+ def do(self):
+- print self.get_name()+'.do'
++ print(self.get_name()+'.do')
+ # links
+ # print ' self.id_mode',self.id_mode
+ # print ' self.get_kwoptions()',self.get_kwoptions()
+@@ -2749,7 +2749,7 @@
+ is_clean_osmfile=True,
+ is_merge=False,
+ logger=None, **kwargs):
+- print 'OsmPolyImporter.__init__', landuse, landuse.parent.get_rootfilename()
++ print('OsmPolyImporter.__init__', landuse, landuse.parent.get_rootfilename())
+ self._init_common('osmpolyimporter', name='OSM Poly import',
+ logger=logger,
+ info='Converts a OSM file to a SUMO Poly file and read facilities into scenario.',
+@@ -2945,12 +2945,12 @@
+ self.run_cml(cml)
+ if self.status == 'success':
+ if os.path.isfile(self.polyfilepath):
+- print ' OSM->poly.xml successful, start importing xml files'
++ print(' OSM->poly.xml successful, start importing xml files')
+ self._landuse.import_polyxml(self.rootname, self.rootdirpath,
+ is_clear=not self.is_merge,
+ type_default=self.type_default,
+ height_default=self.height_default)
+- print ' import poly in sumopy done.'
++ print(' import poly in sumopy done.')
+ return True
+ return False
+ else:
+--- tools/contributed/sumopy/coremodules/landuse/maps.py (original)
++++ tools/contributed/sumopy/coremodules/landuse/maps.py (refactored)
+@@ -23,7 +23,7 @@
+ import sys
+ import numpy as np
+ import wx
+-import urllib
++import urllib.request, urllib.parse, urllib.error
+ from collections import OrderedDict
+ import agilepy.lib_base.classman as cm
+ import agilepy.lib_base.arrayman as am
+@@ -50,7 +50,7 @@
+ try:
+ from PIL import ImageFilter, Image, ImageChops, ImagePath, ImageDraw
+ except:
+- print "WARNING: Maps requires PIL module."
++ print("WARNING: Maps requires PIL module.")
+ IS_MAPSUPPORT = False
+
+ try:
+@@ -61,7 +61,7 @@
+ from mpl_toolkits.basemap import pyproj
+
+ except:
+- print "WARNING: Maps requires pyproj module."
++ print("WARNING: Maps requires pyproj module.")
+ IS_MAPSUPPORT = False
+ # print __doc__
+ # raise
+@@ -71,7 +71,7 @@
+
+
+ def download_googlemap(filepath, bbox, proj, size=640, filetype='gif', maptype='satellite'):
+- print 'download_googlemap', bbox
++ print('download_googlemap', bbox)
+ # https://developers.google.com/maps/documentation/static-maps/intro#Paths
+ x_sw, y_sw = bbox[0]
+ x_ne, y_ne = bbox[1]
+@@ -88,15 +88,15 @@
+ size_x = size_y = size/2
+ url = URL_GOOGLEMAP+"size=%dx%d&visible=%.6f,%.6f|%.6f,%.6f&format=%s&maptype=%s&scale=2"\
+ % (size_x, size_y, lat00, lon00, lat11, lon11, filetype.upper(), maptype)
+- print ' url=', url
+- urllib.urlretrieve(url, filepath)
++ print(' url=', url)
++ urllib.request.urlretrieve(url, filepath)
+
+ bbox_lonlat = np.array([[lon00, lat00], [lon11, lat11]])
+ return bbox_lonlat
+
+
+ def download_googlemap_bb(filepath, bbox, proj, apikey, size=640, filetype='gif', maptype='satellite', color="0xff0000ff"):
+- print 'download_googlemap_bb', bbox
++ print('download_googlemap_bb', bbox)
+ # https://developers.google.com/maps/documentation/static-maps/intro#Paths
+ x_sw, y_sw = bbox[0]
+ x_ne, y_ne = bbox[1]
+@@ -146,8 +146,8 @@
+
+ # urllib.urlretrieve (URL_GOOGLEMAP+"size=%dx%d&format=%s&maptype=%s&scale=2&path=color:0xff0000ff|weight:1|%.5f,%.5f|%.5f,%.5f|%.5f,%.5f|%.5f,%.5f"\
+ # %(size_x,size_y,filetype,maptype,lat00,lon00, lat11,lon11, lat01,lon01, lat10,lon10), filepath)
+- print ' url=', url
+- urllib.urlretrieve(url, filepath)
++ print(' url=', url)
++ urllib.request.urlretrieve(url, filepath)
+ bbox_lonlat = np.array([[lon00, lat00], [lon11, lat11]])
+ return bbox_lonlat
+
+@@ -155,7 +155,7 @@
+ def estimate_angle(filepath):
+
+ im = Image.open(filepath).convert("RGB")
+- print 'estimate_angle image', filepath, "%dx%d" % im.size, im.mode, im.getbands()
++ print('estimate_angle image', filepath, "%dx%d" % im.size, im.mode, im.getbands())
+ imr, img, imb = im.split()
+
+ # calculate width and height of bbox in pixel from measured rectangle
+@@ -184,7 +184,7 @@
+ # which contains a geo-referenced red rectangle
+ angles = np.arange(-3.0, 3.0, 0.01)
+ matches = np.zeros(len(angles))
+- for i in xrange(len(angles)):
++ for i in range(len(angles)):
+ im_bbox_rot = im_bbox.rotate(angles[i]) # gimp 1.62
+ im_corr = ImageChops.multiply(imr, im_bbox_rot)
+ # im_corr.show()
+@@ -193,11 +193,11 @@
+ # print ' angles[i],matches[i]',angles[i],matches[i]
+
+ angle_opt = angles[np.argmax(matches)]
+- print ' angle_opt', angle_opt
++ print(' angle_opt', angle_opt)
+
+ ys = np.arange(0, int(0.2*wy), 1)
+ matches = np.zeros(len(ys))
+- for y in xrange(len(ys)):
++ for y in range(len(ys)):
+ im_bbox = ImageChops.constant(im, 0)
+ draw = ImageDraw.Draw(im_bbox)
+ draw.line([(0, y), (wx, y)], fill=255)
+@@ -211,7 +211,7 @@
+ # print ' y,matches[y]',y,matches[y]
+
+ y_opt = ys[np.argmax(matches)]
+- print ' y_opt', y_opt
++ print(' y_opt', y_opt)
+
+ if 0:
+ im_bbox = ImageChops.constant(im, 0)
+@@ -224,13 +224,13 @@
+
+ # assuming rectangle:
+ bbox = [(y_opt, y_opt), (wx-y_opt, y_opt), (wx-y_opt, wy-y_opt), (y_opt, wy-y_opt), (y_opt, y_opt)]
+- print ' bbox', bbox
++ print(' bbox', bbox)
+ return -angle_opt, bbox
+
+
+ class MapsImporter(Process):
+ def __init__(self, maps, logger=None, **kwargs):
+- print 'MapsImporter.__init__', maps, maps.parent.get_ident()
++ print('MapsImporter.__init__', maps, maps.parent.get_ident())
+ self._init_common('mapsimporter', name='Background maps importer',
+ logger=logger,
+ info='Downloads and converts background maps.',
+@@ -329,7 +329,7 @@
+ def do(self):
+ self.update_params()
+
+- print 'MapsImporter.do'
++ print('MapsImporter.do')
+ # self._maps.download(maptype = self.maptype, mapserver = self.mapserver,
+ # filetype = 'png', rootfilepath = None,
+ # width_tile = self.width_tile, size_tile = self.size_tile,
+@@ -407,7 +407,7 @@
+ ))
+
+ def write_decals(self, fd, indent=4, rootdir=None, delta=np.zeros(3, dtype=np.float32)):
+- print 'write_decals', len(self)
++ print('write_decals', len(self))
+ net = self.parent.get_net()
+ if rootdir is None:
+ rootdir = os.path.dirname(net.parent.get_rootfilepath())
+@@ -494,7 +494,7 @@
+ width = bbox_sumo[2]-x0
+ height = bbox_sumo[3]-y0
+
+- print 'download to', rootfilepath
++ print('download to', rootfilepath)
+
+ # '+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs'
+ #params_proj="+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"
+@@ -507,10 +507,10 @@
+
+ nx = int(width/width_tile+0.5)
+ ny = int(height/width_tile+0.5)
+- print ' offset', offset
+- print ' bbox_sumo', bbox_sumo
+- print ' width_tile', width_tile, 'm'
+- print ' Will download %dx%d= %d maps' % (nx, ny, nx*ny)
++ print(' offset', offset)
++ print(' bbox_sumo', bbox_sumo)
++ print(' width_tile', width_tile, 'm')
++ print(' Will download %dx%d= %d maps' % (nx, ny, nx*ny))
+ #latlon_tile = np.array([(latlon_ne[0]-latlon_sw[0])/ny, (latlon_ne[1]-latlon_sw[1])/nx])
+ #filepaths = []
+ #centers = []
+@@ -524,13 +524,13 @@
+ angle = None
+ bbox = None
+ ids_map = []
+- for ix in xrange(nx):
+- for iy in xrange(ny):
++ for ix in range(nx):
++ for iy in range(ny):
+
+ # tile in SUMO network coords. These are the saved coords
+ x_tile = x0+ix*width_tile
+ y_tile = y0+iy*width_tile
+- print ' x_tile,y_tile', x_tile, y_tile
++ print(' x_tile,y_tile', x_tile, y_tile)
+ bb = np.array([[x_tile, y_tile], [x_tile+width_tile, y_tile+width_tile]], np.float32)
+
+ # tile in absolute coordinates. Coords used for download
+@@ -552,7 +552,7 @@
+ angle, bbox = estimate_angle(filepath)
+ # sys.exit(0)
+ else:
+- print 'WARNING in download: no file downloaded from mapserver'
++ print('WARNING in download: no file downloaded from mapserver')
+ return ids_map
+
+ bbox_tile_lonlat = download_googlemap_bb(filepath, bbox_tile, proj, apikey,
+@@ -560,24 +560,24 @@
+ maptype=maptype, color="0x0000000f")
+
+ if os.path.getsize(filepath) < 2000: # download failed
+- print 'WARNING in download: no file downloaded from mapserver'
++ print('WARNING in download: no file downloaded from mapserver')
+ return ids_map
+
+- print ' bbox_tile', bbox_tile
+- print ' bbox_tile_lonlat', bbox_tile_lonlat
++ print(' bbox_tile', bbox_tile)
++ print(' bbox_tile_lonlat', bbox_tile_lonlat)
+
+ im = Image.open(filepath).convert("RGB")
+ if 1:
+- print ' downloaded image', filepath, "%dx%d" % im.size, im.mode, im.getbands()
+- print ' x_sw,y_sw', x_sw, y_sw
+- print ' x_ne,y_ne', x_ne, y_ne
++ print(' downloaded image', filepath, "%dx%d" % im.size, im.mode, im.getbands())
++ print(' x_sw,y_sw', x_sw, y_sw)
++ print(' x_ne,y_ne', x_ne, y_ne)
+
+ # print ' start rotation'
+ im_rot = im.rotate(angle) # gimp 1.62
+ # im_rot.show()
+ region = im_rot.crop([bbox[0][0], bbox[0][1], bbox[2][0], bbox[2][1]])
+ regsize = region.size
+- print ' regsize', regsize
++ print(' regsize', regsize)
+ im_crop = Image.new('RGB', (regsize[0], regsize[1]), (0, 0, 0))
+ im_crop.paste(region, (0, 0, regsize[0], regsize[1]))
+ im_tile = im_crop.resize((1024, 1024))
+@@ -588,7 +588,7 @@
+ im_tile.save(outfilepath, filetype.upper())
+
+ # print ' bb_orig=',bb
+- print ' bb_orig', bb
++ print(' bb_orig', bb)
+ #lon0, lat0 = proj(x_tile-offset[0], y_tile-offset[1])
+ #lon1, lat1 = proj(x_tile+width_tile-offset[0], y_tile+width_tile-offset[1])
+
+@@ -777,7 +777,7 @@
+
+ shapes = nodes.shapes[ids_node]
+ for shape, id_node in zip(shapes, ids_node):
+- for coord, i in zip(shape, range(len(shape))):
++ for coord, i in zip(shape, list(range(len(shape)))):
+ # print coord
+ # print np.stack((longitudes, latitudes), axis = -1)
+ quote = self.evaluate_quote(longitudes, latitudes, elevations, coord[0], coord[1])
+@@ -794,13 +794,13 @@
+ for shape, id_edge in zip(shapes, ids_edge):
+ positive_climb = 0.
+ negative_climb = 0.
+- for coord, i in zip(shape, range(len(shape))):
++ for coord, i in zip(shape, list(range(len(shape)))):
+ # print coord
+ # print np.stack((longitudes, latitudes), axis = -1)
+ quote = self.evaluate_quote(longitudes, latitudes, elevations, coord[0], coord[1])
+
+ edges.shapes[id_edge][i] = [coord[0], coord[1], quote]
+- print edges.shapes[id_edge][i]
++ print(edges.shapes[id_edge][i])
+ if i > 0 and (quote-quote_pre) > 0:
+ positive_climb += (quote-quote_pre)
+ elif i > 0 and (quote-quote_pre) < 0:
+@@ -841,7 +841,7 @@
+ dists = np.sqrt(np.sum((np.stack((longitudes, latitudes), axis=-1) - [x_point, y_point])**2, 1))
+
+ if is_scipy:
+- print 'use scipy to interpolate'
++ print('use scipy to interpolate')
+ #tck = interpolate.splrep(x, y, s=0)
+ #xnew = np.linspace(np.min(x), np.max(x), 200)
+ #ynew = interpolate.splev(xnew, tck, der=0)
+@@ -853,7 +853,7 @@
+ ## nearest_longitudes = longitudes[(longitudes < x_point + self.interpolation_radius)&(longitudes > x_point - self.interpolation_radius)&(latitudes < y_point + self.interpolation_radius)&(latitudes > y_point - self.interpolation_radius)]
+ ## nearest_latitudes = latitudes[(longitudes < x_point + self.interpolation_radius)&(longitudes > x_point - self.interpolation_radius)&(latitudes < y_point + self.interpolation_radius)&(latitudes > y_point - self.interpolation_radius)]
+ ## nearest_elevations = elevations[(longitudes < x_point + self.interpolation_radius)&(longitudes > x_point - self.interpolation_radius)&(latitudes < y_point + self.interpolation_radius)&(latitudes > y_point - self.interpolation_radius)]
+- print[x_point, y_point], nearest_longitudes, nearest_latitudes, nearest_elevations
++ print([x_point, y_point], nearest_longitudes, nearest_latitudes, nearest_elevations)
+ if len(nearest_longitudes) > 15:
+
+ f_inter = interpolate.SmoothBivariateSpline(
+@@ -880,7 +880,7 @@
+ quote = f_inter(x_point, y_point)
+ else:
+ quote = elevations[np.argmin(dists)]
+- print 'nearest quote'
++ print('nearest quote')
+ else:
+
+ nearest_quotes = elevations[(dists < 100)]
+@@ -895,7 +895,7 @@
+ quote = numerator/denominator
+ else:
+ quote = elevations[np.argmin(dists)]
+- print 'nearest quote'
++ print('nearest quote')
+
+ return quote
+
+--- tools/contributed/sumopy/coremodules/landuse/wxgui.py (original)
++++ tools/contributed/sumopy/coremodules/landuse/wxgui.py (refactored)
+@@ -25,8 +25,8 @@
+ from agilepy.lib_wx.modulegui import ModuleGui
+ from agilepy.lib_wx.ogleditor import *
+ from agilepy.lib_wx.processdialog import ProcessDialog, ProcessDialogInteractive
+-import landuse
+-import maps
++from . import landuse
++from . import maps
+
+ from coremodules.misc import shapeformat
+
+@@ -170,7 +170,7 @@
+ id_landusetype=id_landusetype)
+
+ def on_add_element(self, shapes, ids):
+- print 'on_add_element', shapes.attrname, ids
++ print('on_add_element', shapes.attrname, ids)
+ if shapes == self._zones.shapes:
+ self._id_target = ids[0]
+ self.add_row(_id=self._id_target,
+@@ -1112,7 +1112,7 @@
+
+ def close_process_facilities(self, dlg):
+ # called before destroying the process dialog
+- print 'close_process_facilities', self.proc.status
++ print('close_process_facilities', self.proc.status)
+ if self.proc.status == 'success':
+ self._mainframe.browse_obj(self._landuse.facilities)
+ self._is_needs_refresh = True
+--- tools/contributed/sumopy/coremodules/misc/__init__.py (original)
++++ tools/contributed/sumopy/coremodules/misc/__init__.py (refactored)
+@@ -18,7 +18,7 @@
+
+ __version__ = "0.0"
+
+-print 'init', __name__
++print('init', __name__)
+
+
+ def get_wxgui():
+--- tools/contributed/sumopy/coremodules/misc/matplottools.py (original)
++++ tools/contributed/sumopy/coremodules/misc/matplottools.py (refactored)
+@@ -38,7 +38,7 @@
+ gui_env = ['WXAgg', 'GTKAgg', 'Qt4Agg', 'TKAgg', ]
+ for gui in gui_env:
+ try:
+- print "Try Matplotlib backend:", gui
++ print("Try Matplotlib backend:", gui)
+ mpl.use(gui, warn=False, force=True)
+ from mpl.patches import Arrow, Circle, Wedge, Polygon, FancyArrow
+ from mpl.mpl import PatchCollection
+@@ -51,13 +51,13 @@
+ break
+ except:
+ continue
+- print "Using Matplotlib backend", mpl.get_backend()
++ print("Using Matplotlib backend", mpl.get_backend())
+
+
+ try:
+ import wx
+ except:
+- print 'WARNING: no wxwindows support'
++ print('WARNING: no wxwindows support')
+
+
+ COLORS = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c',
+@@ -282,7 +282,7 @@
+ is_fill = True
+
+ shape = (np.array(zone_shape)[:, :2]*mapscale).tolist()
+- print shape
++ print(shape)
+ ax.add_patch(Polygon(shape,
+ linewidth=width_line,
+ edgecolor=color_outline,
+@@ -485,7 +485,7 @@
+ mapscale=1.0):
+
+ # ATTENTION: do not change order of args for backwards compatibility
+- print 'plot_edgevalues_arrows ids_result width_max', width_max
++ print('plot_edgevalues_arrows ids_result width_max', width_max)
+ # print ' ids_result',ids_result
+ # print ' ids_edge',ids_edge
+ if ids_edge is None:
+@@ -574,7 +574,7 @@
+ mapscale=1.0):
+
+ # ATTENTION: do not change order of args for backwards compatibility
+- print 'plot_connectionvalues_arrows ids_result'
++ print('plot_connectionvalues_arrows ids_result')
+
+ head_width = headwidthstretch*width_max
+ fontsize_ticks = int(0.8*fontsize)
+@@ -664,7 +664,7 @@
+ mapscale=1.0):
+
+ # ATTENTION: do not change order of args for backwards compatibility
+- print 'plot_nodevalues ids_result'
++ print('plot_nodevalues ids_result')
+ fontsize_ticks = int(0.8*fontsize)
+
+ patches = []
+@@ -717,7 +717,7 @@
+ ):
+
+ # ATTENTION: do not change order of args for backwards compatibility
+- print 'plot_pointvalues ids_result'
++ print('plot_pointvalues ids_result')
+ fontsize_ticks = int(0.8*fontsize)
+ ## i = 0
+ patches = []
+@@ -776,7 +776,7 @@
+ """
+ Return resultshape coords for this edge.
+ """
+- print 'get_resultshape', 'connections', 'id_connection', id_connection, 'dispacement', dispacement
++ print('get_resultshape', 'connections', 'id_connection', id_connection, 'dispacement', dispacement)
+ x0 = net.edges.shapes[net.lanes.ids_edge[net.connections.ids_fromlane[id_connection]]][-1, 0]
+ y0 = net.edges.shapes[net.lanes.ids_edge[net.connections.ids_fromlane[id_connection]]][-1, 1]
+ x1 = net.edges.shapes[net.lanes.ids_edge[net.connections.ids_tolane[id_connection]]][0, 0]
+@@ -785,7 +785,7 @@
+ shape = np.array([[x0, y0, 0.], [x1, y1, 0.]])
+ else:
+ shape = np.array([[x0, y0, 0.], [x1 + 1., y1 + 1., 0.]])
+- print 'connection', id_connection, 'has no shape'
++ print('connection', id_connection, 'has no shape')
+ n_vert = len(shape)
+ resultshape = np.zeros(shape.shape, np.float32)
+ #laneshapes = np.zeros((n_lanes,n_vert,3), np.float32)
+@@ -1231,7 +1231,7 @@
+
+ rootfilepath = self.get_scenario().get_rootfilepath()
+ filepath = "%s_%s.%s" % (rootfilepath, figname, self.figformat)
+- print 'save_fig', filepath
++ print('save_fig', filepath)
+ plt.savefig(filepath, format=self.figformat,
+ dpi=self.resolution,
+ # orientation='landscape',
+@@ -1473,7 +1473,7 @@
+ # axis.set_ylim([y_min,y_max])
+
+ def plot_net(self, axis=None, title="", unit='', mapscale=None, is_configure=True):
+- print 'plot_net mapscale', mapscale
++ print('plot_net mapscale', mapscale)
+ if mapscale is None:
+ unit = self.unit_mapscale
+ mapscale = self.get_attrsman().get_config('unit_mapscale').mapscales[unit]
+--- tools/contributed/sumopy/coremodules/misc/shapefile.py (original)
++++ tools/contributed/sumopy/coremodules/misc/shapefile.py (refactored)
+@@ -86,7 +86,7 @@
+ if PYTHON3:
+ return isinstance(v, str)
+ else:
+- return isinstance(v, basestring)
++ return isinstance(v, str)
+
+
+ class _Array(array.array):
+@@ -160,17 +160,17 @@
+ # print '\n\nReader.__init__: load',args[0]
+ self.load(args[0])
+ return
+- if "shp" in kwargs.keys():
++ if "shp" in list(kwargs.keys()):
+ if hasattr(kwargs["shp"], "read"):
+ self.shp = kwargs["shp"]
+ if hasattr(self.shp, "seek"):
+ self.shp.seek(0)
+- if "shx" in kwargs.keys():
++ if "shx" in list(kwargs.keys()):
+ if hasattr(kwargs["shx"], "read"):
+ self.shx = kwargs["shx"]
+ if hasattr(self.shx, "seek"):
+ self.shx.seek(0)
+- if "dbf" in kwargs.keys():
++ if "dbf" in list(kwargs.keys()):
+ if hasattr(kwargs["dbf"], "read"):
+ self.dbf = kwargs["dbf"]
+ if hasattr(self.dbf, "seek"):
+@@ -224,7 +224,7 @@
+ if abs(i) > rmax:
+ raise IndexError("Shape or Record index out of range.")
+ if i < 0:
+- i = range(self.numRecords)[i]
++ i = list(range(self.numRecords))[i]
+ return i
+
+ def __shpHeader(self):
+--- tools/contributed/sumopy/coremodules/misc/shapeformat.py (original)
++++ tools/contributed/sumopy/coremodules/misc/shapeformat.py (refactored)
+@@ -29,7 +29,7 @@
+ from agilepy.lib_base.processes import Process # ,CmlMixin,ff,call
+ #from coremodules.scenario import scenario
+ from agilepy.lib_base.misc import get_inversemap
+-import shapefile
++from . import shapefile
+
+
+ try:
+@@ -42,10 +42,10 @@
+
+ except:
+ IS_PROJ = False
+- print 'Import error: in order to run the traces plugin please install the following modules:'
+- print ' mpl_toolkits.basemap and shapely'
+- print 'Please install these modules if you want to use it.'
+- print __doc__
++ print('Import error: in order to run the traces plugin please install the following modules:')
++ print(' mpl_toolkits.basemap and shapely')
++ print('Please install these modules if you want to use it.')
++ print(__doc__)
+ raise
+
+
+@@ -54,7 +54,7 @@
+ IS_GDAL = True
+ except:
+ IS_GDAL = False
+- print 'WARNING: GDAL module is not installed.'
++ print('WARNING: GDAL module is not installed.')
+
+
+ # Value Shape Type
+@@ -153,7 +153,7 @@
+ +proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs
+ +init=EPSG:23032
+ """
+- import urllib
++ import urllib.request, urllib.parse, urllib.error
+ # print 'get_shapeproj',projparams
+ params = {}
+ for elem in projparams.split('+'):
+@@ -162,13 +162,13 @@
+ params[attr.strip()] = val.strip()
+ # print 'params',params
+
+- if params.has_key('init'):
++ if 'init' in params:
+ if params['init'].lower().find('epsg') >= 0:
+ epgs, number = params['init'].lower().split(':')
+ # print epgs,number
+ html = 'http://spatialreference.org/ref/epsg/%s/prj/' % number
+
+- elif params.has_key('datum'):
++ elif 'datum' in params:
+ if params['datum'].lower().find('wgs') >= 0:
+ number = params['datum'][3:]
+ # print 'wgs', params['zone']+'n'
+@@ -176,7 +176,7 @@
+ number, params['proj'], params['zone'])
+
+ # print 'html=',html
+- f = urllib.urlopen(html)
++ f = urllib.request.urlopen(html)
+ return (f.read())
+
+
+@@ -221,7 +221,7 @@
+ gcs, proj, date = groups
+ proj4 = '+proj=longlat +datum=%s%s +no_defs' % (proj, date[2:])
+ else:
+- print 'WARNING: found no prj file', projfilepath
++ print('WARNING: found no prj file', projfilepath)
+ return proj4
+ # return "+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"
+ # return '+proj=longlat +datum=WGS84 +ellps=WGS84 +a=6378137.0 +f=298.257223563 +pm=0.0 +no_defs'
+@@ -241,7 +241,7 @@
+
+ shapefilepath = os.path.join(dirname, basename)
+
+- print 'import_shapefile *%s*' % (shapefilepath), type(str(shapefilepath))
++ print('import_shapefile *%s*' % (shapefilepath), type(str(shapefilepath)))
+ sf = shapefile.Reader(str(shapefilepath))
+
+ return sf
+@@ -285,7 +285,7 @@
+ logger=None,
+ **kwargs):
+
+- print 'ShapefileImporter.__init__', filepath # ,projparams_target_default, projparams_shape
++ print('ShapefileImporter.__init__', filepath) # ,projparams_target_default, projparams_shape
+ self._init_common(ident,
+ parent=parent,
+ name=name,
+@@ -308,7 +308,7 @@
+ attrsman_parent = parent.get_attrsman()
+ self._coordsconfig = attrsman_parent.get_config(coordsattr)
+
+- for attrname, shapeattr_default in attrnames_to_shapeattrs.iteritems():
++ for attrname, shapeattr_default in attrnames_to_shapeattrs.items():
+ config = attrsman_parent.get_config(attrname)
+ fieldname = 'fieldname_'+attrname
+ setattr(self, fieldname,
+@@ -461,25 +461,25 @@
+ self._fieldinfo = {}
+ fields = self._sf.fields
+ #records = sf.records()
+- for ind_field, field in zip(xrange(1, len(fields)), fields[1:]):
++ for ind_field, field in zip(range(1, len(fields)), fields[1:]):
+ attrname, default, dtype, digits_fraction = get_fieldinfo(field)
+ self._fieldinfo[attrname] = (ind_field-1, default, dtype, digits_fraction)
+
+ def get_projections(self):
+- print 'get_projections IS_PROJ', IS_PROJ
+- print 'self.projparams_shape', self.projparams_shape, 'self._projparams_target', self._projparams_target
++ print('get_projections IS_PROJ', IS_PROJ)
++ print('self.projparams_shape', self.projparams_shape, 'self._projparams_target', self._projparams_target)
+
+ proj_shape = None
+ proj_target = None
+
+ if self.is_use_shapeproj & (self.projparams_shape == ''):
+- print ' no shape projection given'
++ print(' no shape projection given')
+ self.projparams_shape = get_proj4_from_shapefile(self.filepath)
+- print ' from prj file projparams_shape', self.projparams_shape
++ print(' from prj file projparams_shape', self.projparams_shape)
+ if self.projparams_shape == '':
+ # no results from shapefile info, let's try to guess
+ self.projparams_shape = self.guess_shapeproj()
+- print ' from guessing projparams_shape', self.projparams_shape
++ print(' from guessing projparams_shape', self.projparams_shape)
+
+ # if self.is_guess_targetproj:
+ # self.projparams_target = self.guess_targetproj()
+@@ -490,14 +490,14 @@
+ if self.is_use_shapeproj:
+
+ try:
+- print ' use projparams_shape =*%s*' % self.projparams_shape, type(str(self.projparams_shape)), pyproj.Proj(str(self.projparams_shape))
++ print(' use projparams_shape =*%s*' % self.projparams_shape, type(str(self.projparams_shape)), pyproj.Proj(str(self.projparams_shape)))
+ proj_shape = pyproj.Proj(str(self.projparams_shape))
+ except:
+ proj_shape = None
+
+ if self.is_use_targetproj:
+ try:
+- print ' use projparams_target =*%s*' % self._projparams_target, type(str(self._projparams_target)), pyproj.Proj(str(self._projparams_target))
++ print(' use projparams_target =*%s*' % self._projparams_target, type(str(self._projparams_target)), pyproj.Proj(str(self._projparams_target)))
+ proj_target = pyproj.Proj(str(self._projparams_target))
+ except:
+ proj_target = None
+@@ -525,7 +525,7 @@
+ shapeattrname = fieldconf.get_value()
+ attrconf = attrsman_parent.get_config(fieldconf.attrname_orig)
+
+- if self._fieldinfo.has_key(shapeattrname):
++ if shapeattrname in self._fieldinfo:
+ attrconfs.append(attrconf)
+ shapeinds.append(self._fieldinfo[shapeattrname][0])
+
+@@ -538,7 +538,7 @@
+ return True
+
+ def import_shapes(self):
+- print 'import_shapes'
++ print('import_shapes')
+
+ shapes = self._sf.shapes()
+ shapetype = shapes[3].shapeType
+@@ -551,10 +551,10 @@
+
+ # print ' proj_shape',proj_shape,'proj_target',proj_target
+ if self.is_use_shapeproj & (proj_shape is None):
+- print 'WARNING: import_shapes, no shape projection'
++ print('WARNING: import_shapes, no shape projection')
+ return [], 0
+ if self.is_use_targetproj & (proj_target is None):
+- print 'WARNING: import_shapes, no target projection'
++ print('WARNING: import_shapes, no target projection')
+ return [], 0
+
+ offset = np.array([0.0, 0.0, 0.0], dtype=np.float32)
+@@ -572,10 +572,10 @@
+ # print ' offset_target',offset_target
+ coordsconfig = self._coordsconfig
+ ids = coordsconfig.get_manager().add_rows(n_records)
+- print ' n_records', n_records, shapetype
++ print(' n_records', n_records, shapetype)
+
+ if (shapetype == 3) | (shapetype == 5): # poliline = 3, polygon = 5
+- for ind_rec, id_attr in zip(xrange(n_records), ids):
++ for ind_rec, id_attr in zip(range(n_records), ids):
+ # print ' ind_rec',ind_rec,'id_attr',id_attr
+ shape_rec = self._sf.shapeRecord(ind_rec)
+ points = shape_rec.shape.points
+@@ -583,26 +583,26 @@
+ n_points = len(points)
+ shape = np.zeros((n_points, 3), dtype=np.float32) + offset
+ if self.is_use_targetproj & self.is_use_shapeproj:
+- for ind, point in zip(xrange(n_points), points):
++ for ind, point in zip(range(n_points), points):
+ shape[ind, 0:2] += np.array(pyproj.transform(proj_shape, proj_target, point[0], point[1]))
+
+ elif self.is_use_targetproj:
+- for ind, point in zip(xrange(n_points), points):
++ for ind, point in zip(range(n_points), points):
+ shape[ind, 0:2] += proj_target(point[0], point[1])
+
+ elif self.is_use_shapeproj:
+- for ind, point in zip(xrange(n_points), points):
++ for ind, point in zip(range(n_points), points):
+ shape[ind, 0:2] += proj_shape(point[0], point[1])
+
+ else: # no projection
+- for ind, point in zip(xrange(n_points), points):
++ for ind, point in zip(range(n_points), points):
+ shape[ind, 0:2] += (point[0], point[1])
+
+ coordsconfig[id_attr] = list(shape)
+ # print ' coords=',coordsconfig[id_attr]
+
+ elif shapetype == 1:
+- for ind_rec, id_attr in zip(xrange(n_records), ids):
++ for ind_rec, id_attr in zip(range(n_records), ids):
+ # print ' ind_rec',ind_rec,id_attr
+ shape_rec = self._sf.shapeRecord(ind_rec)
+ points = shape_rec.shape.points
+@@ -642,7 +642,7 @@
+ return ids, shapetype
+
+ def do(self):
+- print self.ident+'.do'
++ print(self.ident+'.do')
+ #fields = self._sf.fields
+ #records = self._sf.records()
+
+@@ -661,7 +661,7 @@
+ ids, shapetype = self.import_shapes()
+
+ if len(ids) == 0:
+- print 'WARNING: import_shapes failed'
++ print('WARNING: import_shapes failed')
+ return False
+
+ n_attrs = len(attrconfs)
+@@ -669,7 +669,7 @@
+
+ # import no attributes from table
+ if (n_attrs == 0) | (n_records == 0):
+- print 'WARNING: successfully imported no data'
++ print('WARNING: successfully imported no data')
+ return True
+ shaperecords = self._sf.shapeRecord
+
+@@ -693,17 +693,17 @@
+ if not np.any(self.inboundaries(np.array(shape, dtype=np.float32))):
+ ids_outside.append(id_shape)
+
+- print ' ids_outside', ids_outside
++ print(' ids_outside', ids_outside)
+ self.parent.del_rows(ids_outside)
+
+ return True
+
+ def import_data(self, shaperecords, ids, attrconfs, shapeinds):
+- print 'import_data'
++ print('import_data')
+ n_records = len(ids)
+ objecttype = np.dtype(np.object) # np.dtype(np.zeros(1,dtype = np.object))
+ values_invalid = ['NULL', '\n']
+- for ind_rec, id_attr in zip(xrange(n_records), ids):
++ for ind_rec, id_attr in zip(range(n_records), ids):
+ shape_rec = shaperecords(ind_rec)
+
+ # print ' shape_rec',id_attr,shape_rec.record
+@@ -861,7 +861,7 @@
+ If no file is given, the the default file path will be selected.
+ """
+ # https://code.google.com/p/pyshp/
+- print '\nexport_shapefile', filepath
++ print('\nexport_shapefile', filepath)
+ #proj_target, offset_target = self.parent.get_proj_offset()
+ if len(self) == 0:
+ return False
+@@ -940,8 +940,8 @@
+ prjfile.close()
+ return True
+ except:
+- print 'WARNING in export_shapefile:\n no projection file written (probably no Internet connection).'
+- print 'Open shapefile with projection: %s.' % self._projparams.get_value()
++ print('WARNING in export_shapefile:\n no projection file written (probably no Internet connection).')
++ print('Open shapefile with projection: %s.' % self._projparams.get_value())
+ # raise
+ return False
+
+@@ -987,7 +987,7 @@
+ self.filepath.set_value(filepath)
+
+ basefilepath = self.get_basefilepath(filepath)
+- print 'import_shapefile *%s*' % (basefilepath), type(str(basefilepath))
++ print('import_shapefile *%s*' % (basefilepath), type(str(basefilepath)))
+ sf = shapefile.Reader(str(basefilepath))
+
+ shapes = sf.shapes()
+@@ -1023,18 +1023,18 @@
+ # print ' fields',len(fields),fields
+
+ n = len(attrnames)
+- for ind in xrange(len(records)):
++ for ind in range(len(records)):
+ shape_rec = sf.shapeRecord(ind)
+
+ # use first field as id, but will also be a regular attribute
+ id_egde = shape_rec.record[0]
+ attrrow = {}
+- print '\n id_egde', id_egde
+- for i, field in zip(xrange(n), fields[1:]):
++ print('\n id_egde', id_egde)
++ for i, field in zip(range(n), fields[1:]):
+ val = shape_rec.record[i]
+ # print ' ',i,attrnames[i],'>>'+repr(val)+'<<', type(val)
+ if field[1] == 'N':
+- if type(val) == types.StringType:
++ if type(val) == bytes:
+ val = -1
+
+ attrrow[attrnames[i]] = val
+@@ -1053,7 +1053,7 @@
+ #self.set_row(id_egde, **attrrow)
+ id = self.add_row(key=id_egde)
+
+- for attrname, val in attrrow.iteritems():
++ for attrname, val in attrrow.items():
+ # print ' ',attrname,'>>'+repr(val)+'<<', type(val)
+ getattr(self, attrname)[id] = val
+
+@@ -1082,9 +1082,9 @@
+
+ map_nodetypes = get_inversemap(nodes.types.choices)
+ nodetypes = np.zeros(max(map_nodetypes.keys())+1, dtype=np.object)
+- nodetypes[map_nodetypes.keys()] = map_nodetypes.values()
+-
+- print 'nodes_to_shapefile', filepath
++ nodetypes[list(map_nodetypes.keys())] = list(map_nodetypes.values())
++
++ print('nodes_to_shapefile', filepath)
+
+ for attr in attrlist:
+ shapedata.add_field(attr[2:])
+@@ -1131,7 +1131,7 @@
+ ('speeds_max', 'val', 'SPEED_MAX', 'N', 6, 3),
+ ]
+
+- print 'edges_to_shapefile', filepath
++ print('edges_to_shapefile', filepath)
+
+ for attr in attrlist:
+ shapedata.add_field(attr[2:])
+@@ -1153,10 +1153,10 @@
+ if is_access:
+ accesses = np.zeros(len(ids_edge), dtype=object)
+ accesses[:] = ''
+- for mode, shapemode in VEHICLECLASSCODE.iteritems():
++ for mode, shapemode in VEHICLECLASSCODE.items():
+ # here we select this mode for access level 1 and 2
+ # -1 0 1 2
+- accessvec = np.array(['', 'X', shapemode, shapemode], dtype=np.unicode)
++ accessvec = np.array(['', 'X', shapemode, shapemode], dtype=np.str)
+
+ if net.modes.has_modename(mode):
+ accesslevels = edges.get_accesslevels(net.modes.get_id_mode(mode))
+@@ -1196,7 +1196,7 @@
+ ('osmkeys', 'val', 'OSMKEY', 'C', 32, 0),
+ ]
+
+- print 'facilities_to_shapefile', filepath
++ print('facilities_to_shapefile', filepath)
+
+ for attr in attrlist:
+ shapedata.add_field(attr[2:])
+@@ -1250,7 +1250,7 @@
+ # ('entropies','id','ENTROPY','N',12,5),
+ ]
+
+- print 'zones_to_shapefile', filepath
++ print('zones_to_shapefile', filepath)
+
+ for attr in attrlist:
+ shapedata.add_field(attr[2:])
+--- tools/contributed/sumopy/coremodules/network/__init__.py (original)
++++ tools/contributed/sumopy/coremodules/network/__init__.py (refactored)
+@@ -18,12 +18,12 @@
+
+ __version__ = "0.0"
+
+-print 'init', __name__
++print('init', __name__)
+
+
+ def get_wxgui():
+ # try:
+- from wxgui import WxGui
++ from .wxgui import WxGui
+ return WxGui(__name__)
+ # except:
+ # return None
+--- tools/contributed/sumopy/coremodules/network/netconvert.py (original)
++++ tools/contributed/sumopy/coremodules/network/netconvert.py (refactored)
+@@ -852,13 +852,13 @@
+ # print 'SumonetImporter.do',cml
+ self.run_cml(cml)
+ if self.status == 'success':
+- print ' Netconvert done.'
++ print(' Netconvert done.')
+ if os.path.isfile(self.netfilepath):
+- print ' sumo.net.xml exists, start generation of xml files'
++ print(' sumo.net.xml exists, start generation of xml files')
+ net.import_netxml(self.netfilepath)
+ if self.is_import_ptstops:
+ if os.path.isfile(ptstopfilepath):
+- print ' ptfilepath exists, start importing ptstops'
++ print(' ptfilepath exists, start importing ptstops')
+ net.ptstops.import_sumostops(ptstopfilepath)
+
+ # print ' import in sumopy done.'
+@@ -908,7 +908,7 @@
+ self.init_options_tls()
+
+ def import_tlsxml(self, is_remove_xmlfiles=False):
+- print 'import_tlsxml'
++ print('import_tlsxml')
+ filepath = self.netfilepath
+ net = self.parent
+ rootname = net.get_rootfilename()
+@@ -922,13 +922,13 @@
+ + ' --plain-output-prefix '+filepathlist_to_filepathstring(os.path.join(dirname, rootname))
+
+ proc = subprocess.Popen(cml, shell=True)
+- print ' run_cml cml=', cml
+- print ' pid = ', proc.pid
++ print(' run_cml cml=', cml)
++ print(' pid = ', proc.pid)
+ proc.wait()
+ if not proc.returncode:
+
+ tlsfilepath = os.path.join(dirname, rootname+'.tll.xml')
+- print ' import_sumotls', tlsfilepath
++ print(' import_sumotls', tlsfilepath)
+ net.import_sumotls_to_net(tlsfilepath, is_remove_xmlfiles=is_remove_xmlfiles)
+
+ return True
+@@ -949,7 +949,7 @@
+ + ' --connection-files '+filepathlist_to_filepathstring(filepath_connections)\
+ #+' --output-file '+filepathlist_to_filepathstring(filepath)
+
+- print ' cmlbase', cmlbase
++ print(' cmlbase', cmlbase)
+ self.reset_cml(cmlbase)
+
+ # apply netconvert and reimport
+@@ -960,7 +960,7 @@
+ # print 'SumonetImporter.do',cml
+ self.run_cml(cml)
+ if self.status == 'success':
+- print ' Netconvert done.'
++ print(' Netconvert done.')
+ if os.path.isfile(self.netfilepath):
+ # print ' sumo.net.xml exists, start generation of xml files'
+ # self.parent.import_netxml(self.netfilepath)
+--- tools/contributed/sumopy/coremodules/network/netgenerate.py (original)
++++ tools/contributed/sumopy/coremodules/network/netgenerate.py (refactored)
+@@ -27,7 +27,7 @@
+ #from coremodules.modules_common import *
+ #from coremodules.network.network import SumoIdsConf, MODES
+ from agilepy.lib_base.processes import Process, CmlMixin
+-import netconvert
++from . import netconvert
+ from agilepy.lib_base.geometry import get_length_polypoints, get_dist_point_to_segs, get_diff_angle_clockwise
+
+
+@@ -43,7 +43,7 @@
+ logger=logger,
+ cml='netgenerate')
+
+- print 'init_common_netgen', nettype
++ print('init_common_netgen', nettype)
+
+ self.add_option('nettype', '--'+nettype,
+ groupnames=['_private'],
+--- tools/contributed/sumopy/coremodules/network/network.py (original)
++++ tools/contributed/sumopy/coremodules/network/network.py (refactored)
+@@ -18,9 +18,9 @@
+
+
+ from agilepy.lib_base.processes import Process, CmlMixin, P
+-from routing import get_mincostroute_edge2edges
+-import publictransportnet as pt
+-import netconvert
++from .routing import get_mincostroute_edge2edges
++from . import publictransportnet as pt
++from . import netconvert
+ from agilepy.lib_base.geometry import *
+ from agilepy.lib_base.misc import filepathlist_to_filepathstring, filepathstring_to_filepathlist
+ import agilepy.lib_base.xmlman as xm
+@@ -162,7 +162,7 @@
+ Sets the default maximum possible speed for certain modes.
+ """
+ # print 'MODES.add_default'
+- self.add_rows(ids=MODES.values(), names=MODES.keys())
++ self.add_rows(ids=list(MODES.values()), names=list(MODES.keys()))
+
+ # these speeds are used to estimate free flow link travel times
+ # mainly for routig purposes
+@@ -197,7 +197,7 @@
+ ('rail_fast', 350),
+ ])
+
+- for mode, speed_kmph in speeds_max_kmph.iteritems():
++ for mode, speed_kmph in speeds_max_kmph.items():
+ self.speeds_max[self.get_id_mode(mode)] = float(speed_kmph)/3.6
+
+ # print ' self.speeds_max',self.speeds_max.get_value()
+@@ -449,11 +449,11 @@
+ if filepath is None:
+ filepath = self.parent.get_rootfilepath()+'.tll.xml'
+
+- print 'export_sumoxml', filepath
++ print('export_sumoxml', filepath)
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in export_sumoxml: could not open', filepath
++ print('WARNING in export_sumoxml: could not open', filepath)
+ return False
+
+ fd.write('\n' % encoding)
+@@ -715,7 +715,7 @@
+
+ def analyze_connections(self, **kwargs):
+
+- print 'Analyze connections'
++ print('Analyze connections')
+
+ network = self.parent
+ edges = network.edges
+@@ -744,7 +744,7 @@
+ coord_incoming_penultimate = incoming_edge_shape[-2]
+ coord_outgoing_first = outgoing_edge_shape[0]
+ coord_outgoing_second = outgoing_edge_shape[1]
+- print 'connection', connection
++ print('connection', connection)
+ # print 'coord_node:',coord_node, 'coord_incoming:',coord_incoming, 'coord_outgoing:',coord_outgoing
+ azimut_incoming = self.get_azimut(coord_incoming_last, coord_incoming_penultimate)
+ azimut_outgoing = self.get_azimut(coord_outgoing_first, coord_outgoing_second)
+@@ -761,19 +761,19 @@
+ # Right turn
+ if np.pi*3/4 <= np.absolute(diff_azimut) and np.absolute(diff_azimut) <= np.pi*5/4:
+ connections.turns_type[connection] = 'crossing'
+- print 'crossing'
++ print('crossing')
+ nodes.n_left_turns[node] += 1
+ elif np.absolute(diff_azimut) <= np.pi/18 or np.absolute(diff_azimut) >= np.pi*35/18:
+ connections.turns_type[connection] = 'u_turn'
+- print 'u_turn'
++ print('u_turn')
+ nodes.n_right_turns[node] += 1
+ elif (-3*np.pi/4 < diff_azimut and diff_azimut < -np.pi/18) or (5*np.pi/4 < diff_azimut and diff_azimut < np.pi*35/18):
+ connections.turns_type[connection] = 'right_turn'
+- print 'right turn'
++ print('right turn')
+ nodes.n_crossings[node] += 1
+ elif (np.pi/18 < diff_azimut and diff_azimut < 3*np.pi/4) or (-np.pi*35/18 < diff_azimut and diff_azimut < -5*np.pi/4):
+ connections.turns_type[connection] = 'left_turn'
+- print 'left turn'
++ print('left turn')
+ nodes.n_u_turns[node] += 1
+
+ init_point = incoming_edge_shape[-1]
+@@ -807,7 +807,7 @@
+ elif (x_inc-x_nod) < 0 and (y_inc-y_nod) >= 0:
+ azimut_incoming = np.pi*3/2 + np.arctan((y_inc-y_nod)/(x_nod-x_inc))
+ else:
+- print 'Warning, the two points are the same'
++ print('Warning, the two points are the same')
+ # print point1, point2
+ azimut_incoming = 0
+
+@@ -836,7 +836,7 @@
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in export_sumoxml: could not open', filepath
++ print('WARNING in export_sumoxml: could not open', filepath)
+ return False
+
+ fd.write('\n' % encoding)
+@@ -1091,7 +1091,7 @@
+ edges = self.parent.edges
+
+ ids_lane = edges.ids_lanes[id_edge]
+- print 'reshape_edgelanes id_edge', id_edge, 'id_edge_sumo', edges.ids_sumo[id_edge], len(ids_lane)
++ print('reshape_edgelanes id_edge', id_edge, 'id_edge_sumo', edges.ids_sumo[id_edge], len(ids_lane))
+
+ shape = np.array(edges.shapes[id_edge], np.float32)
+
+@@ -1153,7 +1153,7 @@
+ else:
+ indexes.append(ind)
+ ind += 1
+- print 'WARNING: ignoring mode has no access on footpath'
++ print('WARNING: ignoring mode has no access on footpath')
+ return []
+
+ # return len(ids_lane)-1
+@@ -1199,7 +1199,7 @@
+
+ else:
+ return ind
+- print 'WARNING: ignoring mode has no access on footpath'
++ print('WARNING: ignoring mode has no access on footpath')
+ return -1
+
+ # return len(ids_lane)-1
+@@ -1253,7 +1253,7 @@
+ is_mode_mixed = False
+ is_modes_all = False
+
+- for i, id_lane, ids_modes_allow, ids_modes_disallow in zip(xrange(len(ids_lane)), ids_lane, self.ids_modes_allow[ids_lane], self.ids_modes_disallow[ids_lane]):
++ for i, id_lane, ids_modes_allow, ids_modes_disallow in zip(range(len(ids_lane)), ids_lane, self.ids_modes_allow[ids_lane], self.ids_modes_disallow[ids_lane]):
+ is_mode_only = False
+ is_mode_mixed = False
+ is_modes_all = False
+@@ -1759,7 +1759,7 @@
+ are considered, disregarding the actual connections
+
+ """
+- print 'get_fstar id_mode', id_mode, 'is_return_lists', is_return_lists, 'is_return_arrays', is_return_arrays
++ print('get_fstar id_mode', id_mode, 'is_return_lists', is_return_lists, 'is_return_arrays', is_return_arrays)
+ #ids_edge = self.get_ids()
+ #fstar = np.array(np.zeros(np.max(ids_edge)+1, np.obj))
+ fstar = {}
+@@ -2017,7 +2017,7 @@
+ If not allowed on a particular edge,
+ then the respective edge distance is nan.
+ """
+- print 'get_distances id_mode,is_check_lanes,speed_max', id_mode, is_check_lanes, is_precise
++ print('get_distances id_mode,is_check_lanes,speed_max', id_mode, is_check_lanes, is_precise)
+ ids_edge = self.get_ids()
+ dists = np.zeros(np.max(ids_edge)+1, np.float32)
+ #speeds = self.speeds_max[ids_edge]
+@@ -2140,7 +2140,7 @@
+ ids_edges = self.get_ids()
+ are_allowed = np.zeros(len(ids_edges), dtype=np.bool)
+ inds_lane = np.zeros(len(ids_edges), dtype=np.int32)
+- for i, id_edge in zip(xrange(len(ids_edges)), ids_edges):
++ for i, id_edge in zip(range(len(ids_edges)), ids_edges):
+ ind_lane = get_laneindex_allowed(ids_lanes[id_edge], id_mode)
+ are_allowed[i] = ind_lane >= 0
+ inds_lane[i] = ind_lane
+@@ -2247,7 +2247,7 @@
+ inds = self.get_inds()
+ else:
+ inds = self.get_inds(ids)
+- print 'make_linevertices', len(inds)
++ print('make_linevertices', len(inds))
+
+ linevertices = np.zeros((0, 2, 3), np.float32)
+ vertexinds = np.zeros((0, 2), np.int32)
+@@ -2281,7 +2281,7 @@
+ # print ' =======',n_seg#,polyline
+
+ if n_seg > 1:
+- polyvinds = range(n_seg)
++ polyvinds = list(range(n_seg))
+ # print ' polyvinds\n',polyvinds
+ vi = np.zeros((2*n_seg-2), np.int32)
+ vi[0] = polyvinds[0]
+@@ -2518,7 +2518,7 @@
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in export_sumoxml: could not open', filepath
++ print('WARNING in export_sumoxml: could not open', filepath)
+ return False
+ fd.write('\n' % encoding)
+
+@@ -2531,7 +2531,7 @@
+ return True
+
+ def export_edgeweights_xml(self, filepath=None, weights=None, time_begin=0, time_end=3600, ident='w1', encoding='UTF-8'):
+- print 'export_edgeweights_xml', time_begin, time_end, 'filepath', filepath
++ print('export_edgeweights_xml', time_begin, time_end, 'filepath', filepath)
+ #
+ #
+ #
+@@ -2545,7 +2545,7 @@
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in export_edgeweights_xml: could not open', filepath
++ print('WARNING in export_edgeweights_xml: could not open', filepath)
+ return ''
+
+ if weights is None:
+@@ -2574,7 +2574,7 @@
+ return filepath
+
+ def update(self, ids=None, is_update_lanes=False):
+- print 'Edges.update'
++ print('Edges.update')
+
+ if ids is None:
+ self.widths.value = self.nums_lanes.value * self.widths_lanes_default.value \
+@@ -2640,7 +2640,7 @@
+ # no lanes given...make some with default values
+ ids_lane = []
+ lanes = self.get_lanes()
+- for i in xrange(self.nums_lanes[id_edge]):
++ for i in range(self.nums_lanes[id_edge]):
+ id_lane = lanes.make(index=i, id_edge=id_edge)
+ ids_lane.append(id_lane)
+
+@@ -2720,7 +2720,7 @@
+
+ def analyze_edges(self, **kwargs):
+ # TODO: this should feed into a temporary field
+- print 'Analyze edges'
++ print('Analyze edges')
+ # individuate edge typologies (pedestrian, bike lane, bike/pedestrian,
+ # one-way road, 2-way road)
+ network = self.parent
+@@ -2739,10 +2739,10 @@
+ if len(lanes.ids_mode[id_lanes]) == 1:
+ if lanes.ids_mode[id_lanes] == [id_ped]:
+ pedestrian_edges.append(id_edge)
+- print 'edge', id_edge, 'ped'
++ print('edge', id_edge, 'ped')
+ if lanes.ids_mode[id_lanes] == [id_bike]:
+ cycling_edges.append(id_edge)
+- print 'edge', id_edge, 'cycl'
++ print('edge', id_edge, 'cycl')
+ edges.edge_typology[pedestrian_edges] = 'Pedestrian'
+ edges.edge_typology[cycling_edges] = 'bike lane'
+
+@@ -2757,14 +2757,14 @@
+ if len(lanes.ids_modes_allow[id_lanes][0]) == 2 and len(id_lanes) == 1:
+ if id_bike in np.array(lanes.ids_modes_allow[id_lanes][0]) and id_ped in np.array(lanes.ids_modes_allow[id_lanes][0]):
+ cycling_ped_edges.append(id_edge)
+- print 'edge', id_edge, 'cycl_ped'
++ print('edge', id_edge, 'cycl_ped')
+ elif len(id_lanes) == 2:
+ if lanes.ids_mode[id_lanes[0]] == id_bike and lanes.ids_mode[id_lanes[1]] == id_ped:
+ cycling_ped_edges.append(id_edge)
+- print 'edge', id_edge, 'cycl_ped'
++ print('edge', id_edge, 'cycl_ped')
+ if lanes.ids_mode[id_lanes[0]] == id_ped and lanes.ids_mode[id_lanes[1]] == id_bike:
+ cycling_ped_edges.append(id_edge)
+- print 'edge', id_edge, 'cycl_ped'
++ print('edge', id_edge, 'cycl_ped')
+
+ edges.edge_typology[cycling_ped_edges] = 'Bike/Pedestrian'
+ ids_edge_car = ids_edge
+@@ -3051,7 +3051,7 @@
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in export_sumoxml: could not open', filepath
++ print('WARNING in export_sumoxml: could not open', filepath)
+ return False
+ fd.write('\n' % encoding)
+ indent = 0
+@@ -3116,7 +3116,7 @@
+
+ def clean(self, is_reshape_edgelanes=False, nodestretchfactor=1.2, n_min_nodeedges=2):
+ # is_reshape_edgelanes = False, nodestretchfactor = 2.8
+- print 'Nodes.clean', len(self), 'is_reshape_edgelanes', is_reshape_edgelanes
++ print('Nodes.clean', len(self), 'is_reshape_edgelanes', is_reshape_edgelanes)
+
+ edges = self.parent.edges
+ lanes = self.parent.lanes
+@@ -3173,7 +3173,7 @@
+ shape = edges.shapes[id_edge]
+ n_shape = len(shape)
+ # edges.shapes[id_edge][::-1]:
+- for i in xrange(n_shape-1, -1, -1):
++ for i in range(n_shape-1, -1, -1):
+ d = get_norm_2d(np.array([shape[i]-coords]))[0]
+ # print ' i,d,r',i , d, radius,d>radius
+ if d > radius:
+@@ -3208,7 +3208,7 @@
+ shape = edges.shapes[id_edge]
+ n_shape = len(shape)
+ # edges.shapes[id_edge][::-1]:
+- for i in xrange(n_shape):
++ for i in range(n_shape):
+ d = get_norm_2d(np.array([shape[i]-coords]))[0]
+ # print ' i,d,r',i , d, radius,d>radius
+ if d > radius:
+@@ -3242,7 +3242,7 @@
+
+ class Network(cm.BaseObjman):
+ def __init__(self, parent=None, name='Network', **kwargs):
+- print 'Network.__init__', parent, name
++ print('Network.__init__', parent, name)
+ self._init_objman(ident='net', parent=parent, name=name,
+ # xmltag = 'net',# no, done by netconvert
+ version=0.1,
+@@ -3495,7 +3495,7 @@
+ # do other cleanup jobs
+
+ def call_netedit(self, filepath=None, is_maps=False, is_poly=True, command='netedit'):
+- print 'call_netedit'
++ print('call_netedit')
+ #filepath = self.export_netxml(filepath)
+ if filepath is None:
+ filepath = self.get_filepath()
+@@ -3539,23 +3539,23 @@
+ cml += ' --tllogic-files '+filepathlist_to_filepathstring(filepath_tlss)
+
+ proc = subprocess.Popen(cml, shell=True)
+- print ' run_cml cml=', cml
++ print(' run_cml cml=', cml)
+ # print ' pid = ',proc.pid
+ proc.wait()
+ if proc.returncode == 0:
+- print ' ', command, ':success'
++ print(' ', command, ':success')
+
+ return self.import_netxml()
+ # return self.import_xml() # use if netedit exports to plain xml files
+ else:
+- print ' ', command, ':error'
++ print(' ', command, ':error')
+ return False
+ else:
+- print ' netconvert:error'
++ print(' netconvert:error')
+ return False
+
+ def call_sumogui(self, filepath=None, is_maps=True, is_poly=True):
+- print 'call_sumogui', filepath, is_maps, is_poly
++ print('call_sumogui', filepath, is_maps, is_poly)
+
+ if filepath is None:
+ filepath = self.get_filepath()
+@@ -3606,8 +3606,8 @@
+ + option_addfiles
+
+ proc = subprocess.Popen(cml, shell=True)
+- print ' run_cml cml=', cml
+- print ' pid = ', proc.pid
++ print(' run_cml cml=', cml)
++ print(' pid = ', proc.pid)
+ proc.wait()
+ return proc.returncode
+
+@@ -3642,7 +3642,7 @@
+ else:
+ configfilepath = self.get_rootfilepath()+'.netedit.xml'
+
+- print 'write_guiconfig', configfilepath, is_maps & (maps is not None), maps
++ print('write_guiconfig', configfilepath, is_maps & (maps is not None), maps)
+ fd_config = open(configfilepath, 'w')
+ for line in fd_template.readlines():
+ if line.count('') == 1:
+@@ -3658,7 +3658,7 @@
+ return configfilepath
+
+ def import_netxml(self, filepath=None, rootname=None, is_clean_nodes=False, is_remove_xmlfiles=False):
+- print 'import_netxml', filepath
++ print('import_netxml', filepath)
+
+ if rootname is None:
+ rootname = self.get_rootfilename()
+@@ -3674,11 +3674,11 @@
+ + ' --sumo-net-file '+filepathlist_to_filepathstring(filepath)\
+ + ' --plain-output-prefix '+filepathlist_to_filepathstring(os.path.join(dirname, rootname))
+ proc = subprocess.Popen(cml, shell=True)
+- print ' run_cml cml=', cml
+- print ' pid = ', proc.pid
++ print(' run_cml cml=', cml)
++ print(' pid = ', proc.pid)
+ proc.wait()
+ if not proc.returncode:
+- print ' modes.names', self.modes.names
++ print(' modes.names', self.modes.names)
+ return self.import_xml(rootname, dirname)
+ else:
+ return False
+@@ -3698,7 +3698,7 @@
+ fd = open(filepath, 'w')
+
+ except:
+- print 'WARNING in write_obj_to_xml: could not open', filepath
++ print('WARNING in write_obj_to_xml: could not open', filepath)
+ return False
+
+ #xmltag, xmltag_item, attrname_id = self.xmltag
+@@ -3764,7 +3764,7 @@
+ if filepath is None:
+ filepath = self.get_filepath()
+
+- print 'Net.export_netxml', filepath
++ print('Net.export_netxml', filepath)
+ filepath_edges, filepath_nodes, filepath_connections, filepath_tlss = self.export_painxml(
+ filepath=filepath, is_export_tlss=is_export_tlss)
+
+@@ -3781,11 +3781,11 @@
+
+ if is_netconvert:
+ proc = subprocess.Popen(cml, shell=True)
+- print 'run_cml cml=', cml
+- print ' pid = ', proc.pid
++ print('run_cml cml=', cml)
++ print(' pid = ', proc.pid)
+ proc.wait()
+ if proc.returncode == 0:
+- print ' success'
++ print(' success')
+ if is_return_delta:
+ delta = self._get_delta_netconvert(filepath)
+
+@@ -3793,7 +3793,7 @@
+ else:
+ return filepath
+ else:
+- print ' success'
++ print(' success')
+ return ''
+ else:
+ return ''
+@@ -3835,7 +3835,7 @@
+ oldoffset = self.get_offset()
+ else:
+ oldoffset = None
+- print 'Network.import_xml oldoffset', oldoffset
++ print('Network.import_xml oldoffset', oldoffset)
+ # remove current network
+ # print ' remove current network'
+ self.clear_net()
+@@ -3903,7 +3903,7 @@
+ return False
+
+ def import_sumonodes(self, filename, is_remove_xmlfiles=False, logger=None, **others):
+- print 'import_sumonodes', filename
++ print('import_sumonodes', filename)
+ # print ' parent',self.parent
+ self.get_logger().w('import_sumonodes', key='message')
+
+@@ -3923,11 +3923,11 @@
+ fastreader.write_to_net()
+
+ # timeit
+- print ' exec time=', time.clock() - exectime_start
++ print(' exec time=', time.clock() - exectime_start)
+ return fastreader
+
+ def import_sumoedges(self, filename, is_remove_xmlfiles=False, logger=None, **others):
+- print 'import_sumoedges', filename
++ print('import_sumoedges', filename)
+ logger = self.get_logger()
+ logger.w('import_sumoedges', key='message')
+ # timeit
+@@ -3949,7 +3949,7 @@
+ if is_remove_xmlfiles:
+ os.remove(filename)
+ # timeit
+- print ' exec time=', time.clock() - exectime_start
++ print(' exec time=', time.clock() - exectime_start)
+
+ # except KeyError:
+ # print >> sys.stderr, "Please mind that the network format has changed in 0.16.0, you may need to update your network!"
+@@ -3957,7 +3957,7 @@
+ return fastreader
+
+ def import_sumoconnections(self, filename, is_remove_xmlfiles=False, logger=None, **others):
+- print 'import_sumoedges', filename
++ print('import_sumoedges', filename)
+ logger = self.get_logger()
+ logger.w('import_sumoconnections', key='message')
+
+@@ -3974,7 +3974,7 @@
+
+ # timeit
+ exectime_end = time.clock()
+- print ' exec time=', exectime_end - exectime_start
++ print(' exec time=', exectime_end - exectime_start)
+ return fastreader
+
+ def import_sumotls(self, filename, is_remove_xmlfiles=False, logger=None, **others):
+@@ -3982,7 +3982,7 @@
+ Import traffic ligh signals from tll.xml file
+ as part of a complete import net process.
+ """
+- print 'import_sumotls', filename
++ print('import_sumotls', filename)
+
+ if logger is None:
+ logger = self.get_logger()
+@@ -3996,14 +3996,14 @@
+
+ # timeit
+ exectime_end = time.clock()
+- print ' exec time=', exectime_end - exectime_start
++ print(' exec time=', exectime_end - exectime_start)
+ return reader
+
+ def import_sumotls_to_net(self, filename, is_remove_xmlfiles=False, logger=None, **others):
+ """
+ Import traffic ligh signals from tll.xml file into an existing network.
+ """
+- print 'import_sumotls_to_net', filename
++ print('import_sumotls_to_net', filename)
+
+ # associate nodes with sumo tls ID
+ #map_id_node_to_id_tlss_sumo = {}
+@@ -4028,7 +4028,7 @@
+
+ # timeit
+ exectime_end = time.clock()
+- print ' exec time=', exectime_end - exectime_start
++ print(' exec time=', exectime_end - exectime_start)
+
+ # reestablish TLS IDs of nodes
+
+@@ -4191,7 +4191,7 @@
+
+ def startElement(self, name, attrs):
+ if name == 'connection':
+- if attrs.has_key('to'):
++ if 'to' in attrs:
+ self.n_con += 1
+
+ if name == 'crossing':
+@@ -4233,7 +4233,7 @@
+ if name == 'connection':
+ #
+
+- if attrs.has_key('to'):
++ if 'to' in attrs:
+ self._ind_con += 1
+ i = self._ind_con
+ # print 'startElement',name,i
+@@ -4376,7 +4376,7 @@
+ if self._isNew | (version == attrs['version']):
+ self._net.set_version(attrs['version'])
+ else:
+- print 'WARNING: merge with incompatible net versions %s versus %s.' % (version, attrs['version'])
++ print('WARNING: merge with incompatible net versions %s versus %s.' % (version, attrs['version']))
+
+ elif name == 'location': # j.s
+ # print 'startElement',name,self._isNew
+@@ -4418,12 +4418,12 @@
+ float(origBoundaryStr[3])]
+ )
+ if self._isNew:
+- if attrs.has_key('projParameter'):
++ if 'projParameter' in attrs:
+ self._net.set_projparams(attrs['projParameter'])
+ else:
+- if attrs.has_key('projParameter'):
++ if 'projParameter' in attrs:
+ if self._net.get_projparams() != attrs['projParameter']:
+- print 'WARNING: merge with incompatible projections %s versus %s.' % (self._net.getprojparams(), attrs['projparams'])
++ print('WARNING: merge with incompatible projections %s versus %s.' % (self._net.getprojparams(), attrs['projparams']))
+
+ elif name == 'node':
+ if attrs['id'][0] != ':': # no internal node
+@@ -4476,7 +4476,7 @@
+ # the jointly controlled nodes
+ # problem: we do not know yet the edge IDs
+ #
+- if attrs.has_key('controlledInner'):
++ if 'controlledInner' in attrs:
+ self.ids_sumo_controlled[i] = attrs['controlledInner'].strip().split(' ')
+ else:
+ self.ids_sumo_controlled[i] = []
+@@ -4547,7 +4547,7 @@
+ # print 'startElement',name,id_sumo_tls,int(attrs['linkIndex'])
+ # print ' self.tlsconnections',self.tlsconnections
+
+- if not self.tlsconnections.has_key(id_sumo_tls):
++ if id_sumo_tls not in self.tlsconnections:
+ self.tlsconnections[id_sumo_tls] = {}
+
+ id_con = self.connections.get_id_from_sumoinfo(attrs['from'],
+@@ -4583,15 +4583,15 @@
+ # end of scanning. Write controlled connections to tlss
+ # print ' tlsconnections',self.tlsconnections
+
+- for id_sumo_tls, conmap in self.tlsconnections.iteritems():
++ for id_sumo_tls, conmap in self.tlsconnections.items():
+
+ if self.tlss.ids_sumo.has_index(id_sumo_tls):
+- inds_con = np.array(conmap.keys(), dtype=np.int32)
++ inds_con = np.array(list(conmap.keys()), dtype=np.int32)
+ ids_con = np.zeros(np.max(inds_con)+1, np.int32)
+ # print ' cons for',id_sumo_tls,conmap
+ # print ' inds',inds_con,len(ids_con)
+ # print ' values',conmap.values(),len(ids_con)
+- ids_con[inds_con] = conmap.values() # <<<<<<<<<<<
++ ids_con[inds_con] = list(conmap.values()) # <<<<<<<<<<<
+
+ id_tls = self.tlss.ids_sumo.get_id_from_index(id_sumo_tls)
+ self.tlss.set_connections(id_tls, ids_con)
+@@ -4735,7 +4735,7 @@
+
+ self.speeds_max[ind] = float(attrs.get('speed', 13.888))
+ self.priorities[ind] = int(attrs.get('priority', 9))
+- self.names[ind] = unicode(attrs.get('name', ''))
++ self.names[ind] = str(attrs.get('name', ''))
+ self.offsets_end[ind] = float(attrs.get('endOffset', 0.0))
+
+ # this lanewidth will be used as default if no lane width attribute
+@@ -4756,20 +4756,20 @@
+ ind_edge = self._ind_edge
+ speed_max_default = -1
+
+- if attrs.has_key('allow'):
++ if 'allow' in attrs:
+ modes_access = attrs['allow'].split(' ')
+ if len(modes_access) == 1:
+- if modes_access[0] == u'all':
+- modes_access = MODES.keys()
++ if modes_access[0] == 'all':
++ modes_access = list(MODES.keys())
+
+ ids_modes_allow = list(self._modenames.get_ids_from_indices(modes_access))
+ ids_modes_disallow = []
+
+- elif attrs.has_key('disallow'):
++ elif 'disallow' in attrs:
+ modes_access = attrs['disallow'].split(' ')
+ if len(modes_access) == 1:
+- if modes_access[0] == u'all':
+- modes_access = MODES.keys()
++ if modes_access[0] == 'all':
++ modes_access = list(MODES.keys())
+
+ # print ' startElement id_edge_sumo',self.ids_edge_sumo[ind_edge],'disallow',modes_access
+ ids_modes_disallow = list(self._modenames.get_ids_from_indices(modes_access))
+@@ -4779,7 +4779,7 @@
+ # guess allow from edge type
+ edgetype = self.types_edge[self._ind_edge]
+
+- if OSMEDGETYPE_TO_MODES.has_key(edgetype):
++ if edgetype in OSMEDGETYPE_TO_MODES:
+ ids_modes_allow, speed_max_default = OSMEDGETYPE_TO_MODES[edgetype]
+ else:
+ ids_modes_allow = []
+@@ -4832,7 +4832,7 @@
+ if self._allow_egdeattr is not None:
+ ids_modes_allow = list(self._modenames.get_ids_from_indices(self._allow_egdeattr.split(' ')))
+ else:
+- if OSMEDGETYPE_TO_MODES.has_key(edgetype):
++ if edgetype in OSMEDGETYPE_TO_MODES:
+ ids_modes_allow, speed_max_default = OSMEDGETYPE_TO_MODES[edgetype]
+ else:
+ ids_modes_allow = []
+@@ -5094,7 +5094,7 @@
+
+ def do(self):
+ self.netfilepaths = self.netfilepath+','+self.netfilepaths
+- print 'merging netfilepaths', self.netfilepaths
++ print('merging netfilepaths', self.netfilepaths)
+ cml = self.get_cml()+' --ignore-errors -o %s' % (filepathlist_to_filepathstring(self.filepath_out))
+ # print 'SumonetImporter.do',cml
+ #import_xml(self, rootname, dirname, is_clean_nodes = True)
+--- tools/contributed/sumopy/coremodules/network/network_editor.py (original)
++++ tools/contributed/sumopy/coremodules/network/network_editor.py (refactored)
+@@ -414,7 +414,7 @@
+ def on_add_crossing(self, event=None):
+ self._optionspanel.apply()
+ #edges = self.get_edges().ids_sumo
+- print 'add crossing'
++ print('add crossing')
+ # print ' id_node',self.id_node.get_value()
+ # print ' ids_edge',self.ids_edge.get_value()
+ crossings = self.get_scenario().net.crossings
+@@ -717,7 +717,7 @@
+ 'delivery': ('highway.delivery', [0.4, 0.2, 0.8, 0.9]),
+ }
+
+- for edgeclass, cdata in self.edgeclasses.iteritems():
++ for edgeclass, cdata in self.edgeclasses.items():
+ edgetype, color = cdata
+ self.add(cm.AttrConf('color_'+edgeclass, np.array(color, np.float32),
+ groupnames=['options', 'edgecolors'],
+@@ -802,7 +802,7 @@
+ #self.colors.value = np.ones((n,1),np.float32)*np.array([0.9,0.9,0.9,0.9])
+ #self.colors_highl.value = self._get_colors_highl(self.colors.value)
+ self.colors_fill.value[:] = np.ones((n, 1), np.float32)*self.color_edge_default.value
+- for edgeclass, cdata in self.edgeclasses.iteritems():
++ for edgeclass, cdata in self.edgeclasses.items():
+ edgetype, color = cdata
+ # print ' ',edgeclass, np.sum(self._edges.types.value==edgetype)
+ # print ' color',getattr(self,'color_'+edgeclass).value
+@@ -848,7 +848,7 @@
+ }
+
+ net = lanes.parent
+- for typename, color in typecolors.iteritems():
++ for typename, color in typecolors.items():
+ id_mode = net.get_id_mode(typename)
+ self.add(cm.AttrConf('color_'+typename, np.array(color, np.float32),
+ groupnames=['options', 'typecolors'],
+@@ -1504,7 +1504,7 @@
+ if __name__ == '__main__':
+ ###########################################################################
+ # MAINLOOP
+- import network
++ from . import network
+ from agilepy.lib_base.logger import Logger
+ net = network.Network(logger=Logger())
+ net.import_xml('facsp2', 'testnet')
+--- tools/contributed/sumopy/coremodules/network/networktools.py (original)
++++ tools/contributed/sumopy/coremodules/network/networktools.py (refactored)
+@@ -28,8 +28,8 @@
+ import agilepy.lib_base.arrayman as am
+ import agilepy.lib_base.xmlman as xm
+ from agilepy.lib_base.processes import Process, CmlMixin
+-import netconvert
+-import routing
++from . import netconvert
++from . import routing
+ #from agilepy.lib_base.geometry import get_length_polypoints,get_dist_point_to_segs, get_diff_angle_clockwise
+ from agilepy.lib_base.geometry import *
+
+@@ -37,7 +37,7 @@
+ class ActuatedTlsConfigurator(Process):
+
+ def __init__(self, net, logger=None, **kwargs):
+- print 'ActuatedTlsConfigurator.__init__'
++ print('ActuatedTlsConfigurator.__init__')
+ self._init_common('sctuatedtlsconfigurator',
+ parent=net,
+ name='Actuated Tls Configurator',
+@@ -76,7 +76,7 @@
+ tlss = self.parent.tlss # traffic light systems
+ tlls = tlss.tlls.get_value() # traffic light logics = programs
+ ids_node = nodes.get_ids()
+- print 'ActuatedTlsConfigurator.do, len(ids_node)', len(ids_node), self.is_set_actuated
++ print('ActuatedTlsConfigurator.do, len(ids_node)', len(ids_node), self.is_set_actuated)
+
+ if self.is_set_actuated:
+ type_tls = 2
+@@ -92,7 +92,7 @@
+
+ # go through logics of traffic light
+ for id_tll in tlss.ids_tlls[id_tls]:
+- print ' set logic id_tll', id_tll
++ print(' set logic id_tll', id_tll)
+ tlls.ptypes[id_tll] = type_tls
+
+ # go through phases of program and adjust min max durations
+@@ -110,7 +110,7 @@
+
+ class TlsGenerator(netconvert.NetConvertMixin):
+ def __init__(self, net, logger=None, **kwargs):
+- print 'TlsGenerate.__init__'
++ print('TlsGenerate.__init__')
+ self._init_common('tlsgenerator',
+ parent=net,
+ name='Trafficlight system generator',
+@@ -148,7 +148,7 @@
+ return np.sum(self.parent.edges.lengths[route])
+
+ def do(self):
+- print 'TlsGenerator.do'
++ print('TlsGenerator.do')
+ net = self.parent
+
+ edges = net.edges
+@@ -178,7 +178,7 @@
+ edges.ids_tonode[ids_edge],
+ edges.speeds_max[ids_edge],
+ ):
+- print ' is_major_road', id_edge, self.is_major_road(priority, n_lanes, speed_max), id_edge not in ids_edges_major
++ print(' is_major_road', id_edge, self.is_major_road(priority, n_lanes, speed_max), id_edge not in ids_edges_major)
+ if self.is_major_road(priority, n_lanes, speed_max):
+ if id_edge not in ids_edges_major:
+ #dist = 0
+@@ -190,11 +190,11 @@
+
+ self.majorroutes = majorroutes
+
+- print ' majorroutes:' # ,majorroutes
++ print(' majorroutes:') # ,majorroutes
+ # mapping with id_edge as key ind index of majorroutes
+ edges_major = {}
+- for i, route in zip(xrange(len(majorroutes)), majorroutes):
+- print ' route', i, len(route), route
++ for i, route in zip(range(len(majorroutes)), majorroutes):
++ print(' route', i, len(route), route)
+ for id_edge in route:
+ edges_major[id_edge] = i
+
+@@ -213,14 +213,14 @@
+
+ # identify major junctions
+ majorjuntions = {}
+- for i_route1, ids_node1 in zip(xrange(len(majorroutes)), majornodes):
++ for i_route1, ids_node1 in zip(range(len(majorroutes)), majornodes):
+ ids_nodeset1 = set(ids_node1)
+- for i_route2, ids_node2 in zip(xrange(len(majorroutes)), majornodes):
++ for i_route2, ids_node2 in zip(range(len(majorroutes)), majornodes):
+ if i_route2 != i_route1:
+- print ' check routes', i_route1, i_route2, 'ids_node_inter', ids_nodeset1.intersection(ids_node2)
++ print(' check routes', i_route1, i_route2, 'ids_node_inter', ids_nodeset1.intersection(ids_node2))
+ for id_node_inter in ids_nodeset1.intersection(ids_node2):
+ # go through all nodes that route1 and route2 have in common
+- if majorjuntions.has_key(id_node_inter):
++ if id_node_inter in majorjuntions:
+ # add route index to already existing junction
+ if i_route1 not in majorjuntions[id_node_inter]:
+ majorjuntions[id_node_inter].append(i_route1)
+@@ -234,13 +234,13 @@
+ self.ids_majornodes_used = set()
+
+ # create mojor TLS
+- print ' major junctions:'
+- for id_node, inds_route in majorjuntions.iteritems():
++ print(' major junctions:')
++ for id_node, inds_route in majorjuntions.items():
+ if id_node not in self.ids_majornodes_used:
+ # debug
+- print ' Next majornode', id_node
++ print(' Next majornode', id_node)
+ for ind in inds_route:
+- print ' majorroute', majorroutes[ind]
++ print(' majorroute', majorroutes[ind])
+
+ self.make_majortls(id_node, inds_route)
+ # print ' junction', id_node
+@@ -250,8 +250,8 @@
+ return True
+
+ def make_majortls(self, id_node_major, inds_route):
+- print 79*'-'
+- print 'make_majortls for', id_node_major, inds_route
++ print(79*'-')
++ print('make_majortls for', id_node_major, inds_route)
+ edges = self.parent.edges
+ nodes = self.parent.nodes
+ lanes = self.parent.lanes
+@@ -301,8 +301,8 @@
+
+ # enrich node attributes: is_cycleped, is_crossing
+ # detect all connections, lanes and everything else
+- for id_node, nodeattrs in nodes_tls.iteritems():
+- print ' check all in id_node', id_node
++ for id_node, nodeattrs in nodes_tls.items():
++ print(' check all in id_node', id_node)
+ is_cycleped = True
+ n_cycleped = 0 # count incomin and outgoing cycleped edges
+ n_nocycleped_in = 0 # count normal incoming road edges
+@@ -311,7 +311,7 @@
+ # make lists with incoming edges
+ for id_edge in nodes.ids_incoming[id_node]:
+
+- print ' check incoming', id_edge
++ print(' check incoming', id_edge)
+ ids_lane = edges.ids_lanes[id_edge]
+ #is_cycleped_edge = True
+ #is_ped_edge = True
+@@ -342,7 +342,7 @@
+
+ # detect incoming edges
+ # ,not is_ped_edge,'not from TLS',edges.ids_fromnode[id_edge] not in ids_nodes_tls
+- print ' is external', edges.ids_fromnode[id_edge] not in ids_nodes_tls, 'is_cycle_edge', is_cycle_edge, 'is_major', id_edge in edges_major, 'is_noped'
++ print(' is external', edges.ids_fromnode[id_edge] not in ids_nodes_tls, 'is_cycle_edge', is_cycle_edge, 'is_major', id_edge in edges_major, 'is_noped')
+ if edges.ids_fromnode[id_edge] not in ids_nodes_tls:
+ # from node is not part of the TLS
+ # so it comes from external
+@@ -396,25 +396,25 @@
+
+ # debug
+ if 1:
+- print ' nodes_tls:'
+- for id_node, nodeattrs in nodes_tls.iteritems():
+- print ' id_node', id_node
+- for key, val in nodeattrs.iteritems():
+- print ' ', key, val
++ print(' nodes_tls:')
++ for id_node, nodeattrs in nodes_tls.items():
++ print(' id_node', id_node)
++ for key, val in nodeattrs.items():
++ print(' ', key, val)
+
+ n_cons = len(ids_con_tls)
+ ids_con_tls = np.array(ids_con_tls, dtype=np.int32)
+ ids_connodes = np.array(ids_connodes, dtype=np.int32)
+- print ' ids_incoming_major_tls', ids_incoming_major_tls
+- print ' ids_outgoing_major_tls', ids_outgoing_major_tls
+- print ' ids_incoming_tls', ids_incoming_tls
+- print ' ids_outgoing_tls', ids_outgoing_tls
++ print(' ids_incoming_major_tls', ids_incoming_major_tls)
++ print(' ids_outgoing_major_tls', ids_outgoing_major_tls)
++ print(' ids_incoming_tls', ids_incoming_tls)
++ print(' ids_outgoing_tls', ids_outgoing_tls)
+
+ if len(ids_incoming_tls)+len(ids_incoming_major_tls) < 2:
+- print ' Need at least 2 incoming edges. Abandon.'
++ print(' Need at least 2 incoming edges. Abandon.')
+ return False
+
+- print ' connectors detected:', n_cons
++ print(' connectors detected:', n_cons)
+ #ids_conlane = np.array(ids_conlane, dtype = np.int32 )
+ #convecs = np.array(convecs, dtype = np.float32 )
+ vertices_fromcon = np.zeros((n_cons, 2, 2), dtype=np.float32)
+@@ -425,7 +425,7 @@
+ ids_fromlane_tls = connections.ids_fromlane[ids_con_tls]
+ ids_tolane_tls = connections.ids_tolane[ids_con_tls]
+ for i, shape_fromlane, shape_tolane in zip(
+- xrange(n_cons),
++ range(n_cons),
+ lanes.shapes[ids_fromlane_tls],
+ lanes.shapes[ids_tolane_tls]
+ ):
+@@ -464,7 +464,7 @@
+ centroids = nodes.coords[ids_connodes][:, :2]
+ dist_intercheck = 5.0
+ for i, id_con, vertex_fromcon, vertex_tocon, id_node, id_edge_from, id_edge_to in zip(
+- xrange(n_cons), ids_con_tls,
++ range(n_cons), ids_con_tls,
+ vertices_fromcon, vertices_tocon,
+ ids_connodes, ids_conedges_from, ids_conedges_to):
+
+@@ -511,7 +511,7 @@
+ dists_to < dist_intercheck,
+ (ids_connodes == id_node), (ids_conedges_from != id_edge_from),
+ inds):
+- print ' id_con:%d d_from %.2f, d_to %.2f' % (id_con1, df, dt), df < dist_intercheck, dt < dist_intercheck, id_node1 == id_node, id_edge1 != id_edge_from, crit
++ print(' id_con:%d d_from %.2f, d_to %.2f' % (id_con1, df, dt), df < dist_intercheck, dt < dist_intercheck, id_node1 == id_node, id_edge1 != id_edge_from, crit)
+ # print ' vf',vf,'vt',vt,'cent',cent,cent-vt
+
+ dists_fromcon_node[id_con] = np.array(dists_from[inds], dtype=np.int32)
+@@ -522,9 +522,9 @@
+ inds_cons_merge[id_con] = inds & np.isnan(dists_to)
+
+ if 1: # debug
+- print ' show conflicts:', len(inds_cons_conflict)
+- for id_con_tls, inds_con_conflict, id_connode in zip(ids_con_tls, inds_cons_conflict.values(), ids_connodes):
+- print ' id_connode:%d id_con:%d' % (id_connode, id_con_tls), 'ids_conf', ids_con_tls[inds_con_conflict]
++ print(' show conflicts:', len(inds_cons_conflict))
++ for id_con_tls, inds_con_conflict, id_connode in zip(ids_con_tls, list(inds_cons_conflict.values()), ids_connodes):
++ print(' id_connode:%d id_con:%d' % (id_connode, id_con_tls), 'ids_conf', ids_con_tls[inds_con_conflict])
+
+ # print ' id_node %d, id_con %d confl:'%(id_node,id_con)
+ # print ' ids_con_conflict',ids_con_tls[inds_con_conflict]
+@@ -540,7 +540,7 @@
+ #self.id_mode_ped = net.modes.get_id_mode("pedestrian")
+ #self.id_mode_car = net.modes.get_id_mode("passenger")
+
+- print '\n generate routes accross the TLS'
++ print('\n generate routes accross the TLS')
+ #costs = edges.get_times( id_mode = self.id_mode_car , is_check_lanes = True, speed_max = None)
+ # use bus here so we can route also on reserved lanes
+ costs = edges.get_times(id_mode=self.id_mode_bus, is_check_lanes=True, speed_max=None)
+@@ -554,7 +554,7 @@
+ routes_tls = []
+ routes_tls_cost = []
+ ids_routeedge_tls = set()
+- print ' create major routes for ids_incoming_major_tls', ids_incoming_major_tls, 'ids_outgoing_major_tls', ids_outgoing_major_tls
++ print(' create major routes for ids_incoming_major_tls', ids_incoming_major_tls, 'ids_outgoing_major_tls', ids_outgoing_major_tls)
+ for id_incoming_tls in ids_incoming_major_tls:
+ # ind_route =
+ # print ' major:id_incoming_tls',id_incoming_tls,type(id_incoming_tls), edges_major.has_key(id_incoming_tls)
+@@ -564,10 +564,10 @@
+ # select major route
+ route_major = self.majorroutes[edges_major[id_incoming_tls]]
+ costs_major_tot = self.majorroutecosts[edges_major[id_incoming_tls]]
+- print ' id_incoming_tls', id_incoming_tls, 'costs_major_tot', costs_major_tot
++ print(' id_incoming_tls', id_incoming_tls, 'costs_major_tot', costs_major_tot)
+ ind_from = route_major.index(id_incoming_tls)
+ for id_outgoing_tls in ids_outgoing_major_tls:
+- print ' id_incoming_tls -> id_outgoing_tls', id_incoming_tls, '->', id_outgoing_tls
++ print(' id_incoming_tls -> id_outgoing_tls', id_incoming_tls, '->', id_outgoing_tls)
+ route = []
+
+ if (id_outgoing_tls in route_major) & (ind_from < (len(route_major)-1)):
+@@ -586,7 +586,7 @@
+
+ if len(route) == 0:
+ # major route does not connects id_incoming_tls and id_outgoing_tls
+- print ' try to find a route between both edges'
++ print(' try to find a route between both edges')
+ dur, route_raw = routing.get_mincostroute_edge2edge(
+ id_incoming_tls, id_outgoing_tls,
+ weights=costs, fstar=fstar)
+@@ -613,7 +613,7 @@
+ route = []
+ costs_major = 0.0
+
+- print ' =>costs_major,route_major tls', costs_major, route
++ print(' =>costs_major,route_major tls', costs_major, route)
+ if len(route) > 0:
+ routes_tls.append(route)
+ # costs to decide which phase is first
+@@ -623,15 +623,15 @@
+ ids_routeedge_tls.update(route)
+
+ if 1: # sp
+- print ' major routes_tls', routes_tls, ids_outgoing_bike_tls
+- print ' create bike routes for ids_incoming_bike_tls', ids_incoming_bike_tls, ids_outgoing_bike_tls
++ print(' major routes_tls', routes_tls, ids_outgoing_bike_tls)
++ print(' create bike routes for ids_incoming_bike_tls', ids_incoming_bike_tls, ids_outgoing_bike_tls)
+ for id_incoming_tls in ids_incoming_bike_tls: # +ids_incoming_tls+ids_incoming_major_tls:
+
+ D, P = routing.edgedijkstra(id_incoming_tls, ids_edge_target=set(ids_outgoing_bike_tls),
+ weights=costs_bike, fstar=fstar)
+
+ for id_outgoing_tls in ids_outgoing_bike_tls: # +ids_outgoing_tls+ids_outgoing_major_tls:
+- print ' bike route from %d to %d' % (id_incoming_tls, id_outgoing_tls), 'can route?', (id_incoming_tls in D) & (id_outgoing_tls in D)
++ print(' bike route from %d to %d' % (id_incoming_tls, id_outgoing_tls), 'can route?', (id_incoming_tls in D) & (id_outgoing_tls in D))
+ if (id_incoming_tls in D) & (id_outgoing_tls in D):
+
+ # avoid route with turnaround
+@@ -656,10 +656,10 @@
+ routes_tls_cost.append(routecost)
+ ids_routeedge_tls.update(route)
+
+- print ' withbike routes_tls', routes_tls
++ print(' withbike routes_tls', routes_tls)
+
+ ids_outgoing_tls_rest = ids_outgoing_tls+ids_outgoing_major_tls # +ids_outgoing_bike_tls
+- print ' create rest of routes for ids_incoming_tls', ids_incoming_tls, ids_outgoing_tls_rest
++ print(' create rest of routes for ids_incoming_tls', ids_incoming_tls, ids_outgoing_tls_rest)
+ for id_incoming_tls in ids_incoming_tls+ids_incoming_major_tls: # +ids_incoming_bike_tls:
+
+ D, P = routing.edgedijkstra(id_incoming_tls, ids_edge_target=set(ids_outgoing_tls_rest),
+@@ -669,7 +669,7 @@
+ if not ((id_incoming_tls in ids_outgoing_major_tls) & (id_outgoing_tls in ids_outgoing_major_tls)):
+ # major incoming and outgoing already done with major routes
+
+- print ' rest route from id_incoming_tls,', id_incoming_tls, 'id_outgoing_tls', id_outgoing_tls
++ print(' rest route from id_incoming_tls,', id_incoming_tls, 'id_outgoing_tls', id_outgoing_tls)
+ # avoid route with turnaround
+ if edges.ids_tonode[id_outgoing_tls] != edges.ids_fromnode[id_incoming_tls]:
+
+@@ -690,7 +690,7 @@
+ routes_tls_cost.append(routecost)
+ ids_routeedge_tls.update(route)
+
+- print '\n all routes_tls', routes_tls
++ print('\n all routes_tls', routes_tls)
+
+ # add bicycle routes
+
+@@ -717,7 +717,7 @@
+ routecost = routes_tls_cost[ind_route]
+ #ids_edges = self.majorroutes[ind_route]
+ #ids_edges = np.array(ids_edges_list, dtype = np.int32)
+- print ' Determine connectors for route ind_route', ind_route, ids_edges
++ print(' Determine connectors for route ind_route', ind_route, ids_edges)
+ # print ' ids_node',edges.ids_fromnode[ids_edges[:-1]]
+ # print ' nodes_tls',nodes_tls.keys()
+ # for id_edge, id_innode, id_outnode in zip(ids_edges, edges.ids_fromnode[ids_edges], edges.ids_tonode[ids_edges]):
+@@ -744,7 +744,7 @@
+ inds_con_route |= (lanes.ids_edge[ids_fromlane_tls] == id_edge_from) & (
+ lanes.ids_edge[ids_tolane_tls] == id_edge_to)
+
+- print ' id_node,prio', id_node, prio, id_node in nodes_tls, 'n_cons_route', len(np.flatnonzero(inds_con_route))
++ print(' id_node,prio', id_node, prio, id_node in nodes_tls, 'n_cons_route', len(np.flatnonzero(inds_con_route)))
+
+ # make phase for ids_edges
+ if prio != -1:
+@@ -755,9 +755,9 @@
+ for id_con, ind_con in zip(ids_con_tls_route, np.flatnonzero(inds_con_route)):
+ inds_cons_conflict_route |= inds_cons_conflict[id_con] & np.logical_not(inds_cons_merge[id_con])
+ inds_cons_merge_route |= inds_cons_merge[id_con]
+- print ' ids_con_alloc', ids_con_tls[inds_con_route]
+- print ' ids_con_confl', ids_con_tls[inds_cons_conflict_route]
+- print ' ids_con_merge', ids_con_tls[inds_cons_merge_route]
++ print(' ids_con_alloc', ids_con_tls[inds_con_route])
++ print(' ids_con_confl', ids_con_tls[inds_cons_conflict_route])
++ print(' ids_con_merge', ids_con_tls[inds_cons_merge_route])
+ routeconnectordata.append((ind_route, inds_con_route, prio,
+ inds_cons_conflict_route, inds_cons_merge_route))
+
+@@ -768,7 +768,7 @@
+ for data in routeconnectordata: # data is sorted by routecosts
+ ind_tlsroute, inds_con_route, prio, inds_cons_conflict_route, inds_cons_merge_route = data
+
+- print ' ind_tlsroute', ind_tlsroute, 'c=%.1f' % routes_tls_cost[ind_tlsroute], 'ids_edge', routes_tls[ind_tlsroute]
++ print(' ind_tlsroute', ind_tlsroute, 'c=%.1f' % routes_tls_cost[ind_tlsroute], 'ids_edge', routes_tls[ind_tlsroute])
+
+ # group non-conflicting routes
+ n_routes = len(routeconnectordata)
+@@ -790,7 +790,7 @@
+ i_group = 0
+ i_route = 0
+ while i_route < n_routes:
+- print ' try i_route', i_route, phasegroups[i_route], phasegroups[i_route] == -1
++ print(' try i_route', i_route, phasegroups[i_route], phasegroups[i_route] == -1)
+ if phasegroups[i_route] == -1:
+
+ phasegroups[i_route] = i_group
+@@ -798,7 +798,7 @@
+ i_route]
+
+ #inds_cons_conflict_group = inds_cons_conflict.copy()
+- print ' Check group', i_group, 'for ind_tlsroute', ind_tlsroute, 'c=%.1f' % routes_tls_cost[ind_tlsroute]
++ print(' Check group', i_group, 'for ind_tlsroute', ind_tlsroute, 'c=%.1f' % routes_tls_cost[ind_tlsroute])
+
+ # print ' inds_cons_conflict',inds_cons_conflict
+ # check whether there are other, compatible
+@@ -807,21 +807,21 @@
+ inds_confict_group = inds_cons_conflict_route.copy()
+ inds_merge_group = inds_cons_merge_route.copy()
+ prio_group = 1*prio
+- print ' init ids_confict_group=', ids_con_tls[inds_confict_group]
++ print(' init ids_confict_group=', ids_con_tls[inds_confict_group])
+ while j_route < n_routes:
+ if phasegroups[j_route] == -1:
+ # no phase group associated with
+ ind_tlsroute2, inds_con_route2, prio2, inds_cons_conflict_route2, inds_cons_merge_route2 = routeconnectordata[
+ j_route]
+- print ' check with ind_tlsroute2', ind_tlsroute2, np.any(inds_cons_conflict_route2 & inds_con_route), np.any(inds_cons_conflict_route & inds_con_route2)
++ print(' check with ind_tlsroute2', ind_tlsroute2, np.any(inds_cons_conflict_route2 & inds_con_route), np.any(inds_cons_conflict_route & inds_con_route2))
+ # print ' c',inds_con_route
+ # print ' x',inds_cons_conflict_route2
+ if (not np.any(inds_cons_conflict_route2 & inds_alloc_group)) & (not np.any(inds_confict_group & inds_con_route2)):
+ # no mutual conflict connections between route j_route
+ # and current route i_route
+
+- print ' ids_cons_conflict_route2', ids_con_tls[inds_cons_conflict_route2]
+- print ' inds_con_route ', ids_con_tls[inds_con_route]
++ print(' ids_cons_conflict_route2', ids_con_tls[inds_cons_conflict_route2])
++ print(' inds_con_route ', ids_con_tls[inds_con_route])
+ # make this route a part of the current group
+ phasegroups[j_route] = i_group
+ inds_confict_group |= inds_cons_conflict_route2
+@@ -830,8 +830,8 @@
+
+ if prio2 > prio_group:
+ prio_group = prio
+- print ' group', phasegroups[j_route], ':put route', ind_tlsroute2, 'to route', ind_tlsroute
+- print ' ids_confict_group=', ids_con_tls[inds_confict_group]
++ print(' group', phasegroups[j_route], ':put route', ind_tlsroute2, 'to route', ind_tlsroute)
++ print(' ids_confict_group=', ids_con_tls[inds_confict_group])
+
+ j_route += 1
+
+@@ -847,7 +847,7 @@
+ # debug:
+ for i_group, data in zip(phasegroups, routeconnectordata):
+ ind_tlsroute, inds_con_route, prio, inds_cons_conflict_route, inds_cons_merge_route = data
+- print ' i_group', i_group, 'ind_tlsroute', ind_tlsroute, 'ids_edge', routes_tls[ind_tlsroute]
++ print(' i_group', i_group, 'ind_tlsroute', ind_tlsroute, 'ids_edge', routes_tls[ind_tlsroute])
+
+ # return
+ # create signal phases
+@@ -871,11 +871,11 @@
+
+ # print '\n **inds_cons_conflict',inds_cons_conflict
+ if len(phasegroups) == 0:
+- print ' WARNING: a TLS without signal groups. Abandone.'
++ print(' WARNING: a TLS without signal groups. Abandone.')
+ return
+
+- for i_group, inds_alloc_groups, inds_confict_groups, inds_merge_groups, prio_group in zip(xrange(max(phasegroups)+1), inds_alloc_groups, inds_confict_groups, inds_merge_groups, prios_group):
+- print ' allocate slots for group', i_group
++ for i_group, inds_alloc_groups, inds_confict_groups, inds_merge_groups, prio_group in zip(range(max(phasegroups)+1), inds_alloc_groups, inds_confict_groups, inds_merge_groups, prios_group):
++ print(' allocate slots for group', i_group)
+ phaseallocations.append(inds_alloc_groups)
+
+ phaseconflicts.append(2*inds_confict_groups + 1 * (inds_merge_groups & np.logical_not(inds_confict_groups)))
+@@ -891,13 +891,13 @@
+ n_phase = len(phaseconflicts)
+
+ if n_phase < 2:
+- print ' WARNING: a TLS with just one phase makes no sense. Abandone.'
++ print(' WARNING: a TLS with just one phase makes no sense. Abandone.')
+ return
+
+ if 1: # debug
+- print ' Show phases n_phase', n_phase
+- for i, inds_phaseconflict, prio in zip(xrange(n_phase), phaseconflicts, phasepriorities):
+- print ' phase', i, 'prio', prio
++ print(' Show phases n_phase', n_phase)
++ for i, inds_phaseconflict, prio in zip(range(n_phase), phaseconflicts, phasepriorities):
++ print(' phase', i, 'prio', prio)
+ #ids_con_conf_phase = ids_con_tls[inds_phaseconflict==2]
+ # print ' ids_con_conf_phase',ids_con_conf_phase
+ #ids_con_merge_phase = ids_con_tls[inds_phaseconflict==1]
+@@ -906,16 +906,16 @@
+ ids_node_phase = set(ids_connodes[inds_phaseconflict > 0])
+
+ for id_node in ids_node_phase:
+- print ' id_node', id_node
+- print ' ids_conflicts', ids_con_tls[(inds_phaseconflict == 2) & (ids_connodes == id_node)]
+- print ' ids_merge', ids_con_tls[(inds_phaseconflict == 1) & (ids_connodes == id_node)]
++ print(' id_node', id_node)
++ print(' ids_conflicts', ids_con_tls[(inds_phaseconflict == 2) & (ids_connodes == id_node)])
++ print(' ids_merge', ids_con_tls[(inds_phaseconflict == 1) & (ids_connodes == id_node)])
+
+ # make sure that all connetors between two edges have the equal signal
+ for id_fromedge in set(ids_conedges_from):
+ for id_toedge in set(ids_conedges_to):
+ # extract index of connections, connecting id_fromedge with id_toedge
+ inds_con_check = np.flatnonzero((ids_conedges_from == id_fromedge) & (ids_conedges_to == id_toedge))
+- for i in xrange(n_phase):
++ for i in range(n_phase):
+ # now if any of those connections is red than make them all red
+ if np.any(phaseconflicts[i][inds_con_check] == 2):
+ phaseconflicts[i][inds_con_check] = 2
+@@ -942,8 +942,8 @@
+ #
+ if 1:
+ # go though all nodes of this TLS
+- for id_node, nodeattrs in nodes_tls.iteritems():
+- print ' safecheck id_node', id_node, 'is_crossing', nodeattrs['is_crossing'], 'is_cycleped', nodeattrs['is_cycleped']
++ for id_node, nodeattrs in nodes_tls.items():
++ print(' safecheck id_node', id_node, 'is_crossing', nodeattrs['is_crossing'], 'is_cycleped', nodeattrs['is_cycleped'])
+
+ #nodeattrs['is_cycleped'] = is_cycleped
+ # nodeattrs['is_crossing'] =
+@@ -959,14 +959,14 @@
+
+ for id_edge_from in nodeattrs['ids_cycleped_incoming']: # nodes.ids_incoming[id_node]:
+ for id_edge_to in nodeattrs['ids_cycleped_outgoing']:
+- print ' safecheck cycleped from edge %d to edge %d id_edge' % (id_edge_from, id_edge_to)
++ print(' safecheck cycleped from edge %d to edge %d id_edge' % (id_edge_from, id_edge_to))
+
+ # connector index vector with all connectors for this edge
+
+ inds_con_edge = inds_con_node & (lanes.ids_edge[ids_fromlane_tls] == id_edge_from) & (
+ lanes.ids_edge[ids_tolane_tls] == id_edge_to)
+ ids_con_edge = ids_con_tls[inds_con_edge]
+- print ' ids_con_edge', ids_con_edge, np.any(inds_con_edge)
++ print(' ids_con_edge', ids_con_edge, np.any(inds_con_edge))
+ if np.any(inds_con_edge):
+ # get conflicts for these connections
+ for id_con, ind_con in zip(ids_con_edge, np.flatnonzero(inds_con_edge)):
+@@ -975,19 +975,19 @@
+ # conflicts valid to connector does NOT point to toedge
+ inds_con_check |= inds_cons_conflict[id_con] & are_enabeled & (
+ lanes.ids_edge[ids_tolane_tls] != id_edge_to)
+- print ' id_con %d: inds_con_check' % id_con, ids_con_tls[inds_con_check]
+-
+- print ' ids_con_check', ids_con_tls[inds_con_check]
++ print(' id_con %d: inds_con_check' % id_con, ids_con_tls[inds_con_check])
++
++ print(' ids_con_check', ids_con_tls[inds_con_check])
+
+ # check if there is a dedicated phase with assigned
+ # cycleped edges
+ prio_green = -1
+- for i, prio in zip(xrange(n_phase), phasepriorities):
++ for i, prio in zip(range(n_phase), phasepriorities):
+ is_alloc_allgreen = np.all(phaseallocations[i][inds_con_node])
+
+ if is_alloc_allgreen:
+ # cycleped path is allocated, so make all conflicts red
+- print ' found cycleped green phase', i
++ print(' found cycleped green phase', i)
+
+ # make all conflicting red, but this should already
+ # be the case
+@@ -1000,7 +1000,7 @@
+ # search suitable phase where conflicts are red
+ prio_red = -1
+ i_red = -1
+- for i, prio in zip(xrange(n_phase), phasepriorities):
++ for i, prio in zip(range(n_phase), phasepriorities):
+ is_conflict_allred = np.all(phaseconflicts[i][inds_con_check] == 2)
+ if is_conflict_allred & (prio > prio_red):
+ i_red = i
+@@ -1009,8 +1009,8 @@
+ # react and make cycleped red (and leave others)
+ # and make cycleped green only in phase i_red
+ # when conflicts are all red
+- for i, prio in zip(xrange(n_phase), phasepriorities):
+- print ' adjust phase', i, 'green', i == i_red
++ for i, prio in zip(range(n_phase), phasepriorities):
++ print(' adjust phase', i, 'green', i == i_red)
+ if i == i_red:
+ phaseconflicts[i][inds_con_node] = 0
+ else:
+@@ -1022,7 +1022,7 @@
+
+ # go through all incoming edges of this node
+ for id_edge in nodes.ids_incoming[id_node]:
+- print ' safecheck icoming id_edge', id_edge
++ print(' safecheck icoming id_edge', id_edge)
+
+ # connector index vector with all connectors for this edge
+ inds_con_node = (ids_connodes == id_node) & are_enabeled
+@@ -1042,16 +1042,16 @@
+
+ # if id_con is green, then these must be red in all phases
+ inds_con_confcheck = inds_cons_conflict[id_con]
+- print '\n safecheck id_con', id_con, 'ids_con_confcheck', ids_con_tls[inds_con_confcheck]
++ print('\n safecheck id_con', id_con, 'ids_con_confcheck', ids_con_tls[inds_con_confcheck])
+
+ # go through all phases
+- for i, prio in zip(xrange(n_phase), phasepriorities):
++ for i, prio in zip(range(n_phase), phasepriorities):
+ inds_noconfmerge = phaseconflicts[i] <= 1
+ #inds_noconfmerge_last = phaseconflicts[i-1] <= 1
+
+ inds_noconf = phaseconflicts[i] == 0
+ inds_noconf_last = phaseconflicts[i-1] == 0
+- print ' safecheck phase', i, 'inds_noconf', inds_noconf[ind_con], 'inds_noconf_last', inds_noconf_last[ind_con]
++ print(' safecheck phase', i, 'inds_noconf', inds_noconf[ind_con], 'inds_noconf_last', inds_noconf_last[ind_con])
+
+ if inds_noconfmerge[ind_con]: # no red at ind_con
+
+@@ -1066,7 +1066,7 @@
+
+ # ambiguous cons = green cons inds & inds where cons should be red
+ inds_con_ambiqu = inds_noconf & (inds_con_confcheck > 0) & are_enabeled
+- print ' inds_con_ambiqu', ids_con_tls[inds_con_ambiqu], 'resolve ambig', (inds_noconf_last[ind_con]) & np.any(inds_con_ambiqu)
++ print(' inds_con_ambiqu', ids_con_tls[inds_con_ambiqu], 'resolve ambig', (inds_noconf_last[ind_con]) & np.any(inds_con_ambiqu))
+
+ # any ambiguous connector found?
+ if np.any(inds_con_ambiqu):
+@@ -1082,10 +1082,10 @@
+ # of connectors, it can happen
+ # that allocated connectors are in conflict
+ if np.any(phaseallocations[i][inds_con_ambiqu]):
+- print ' set thiscon', id_con, 'to red, instead of allocated.'
++ print(' set thiscon', id_con, 'to red, instead of allocated.')
+ phaseconflicts[i][ind_con] = 2
+ else:
+- print ' set confcons', ids_con_tls[inds_con_ambiqu], 'to red'
++ print(' set confcons', ids_con_tls[inds_con_ambiqu], 'to red')
+ phaseconflicts[i][inds_con_ambiqu] = 2
+
+ # for ind_con_ambiqu, raw in zip(inds_con_ambiqu, phaseconflicts[i][inds_con_ambiqu]):
+@@ -1094,13 +1094,13 @@
+ # during the last phase this signal
+ # has been red so let it red
+ # these should be blocked!!
+- print ' set thiscon', id_con, 'to red'
++ print(' set thiscon', id_con, 'to red')
+ phaseconflicts[i][ind_con] = 2
+ #self.block_connection(ind_con, 2 , phaseconflicts[i], ids_fromlane_tls, ids_tolane_tls, ids_con_tls,are_enabeled)
+ else:
+- print ' no ambiguity.'
++ print(' no ambiguity.')
+ else:
+- print ' signal is already red. Try make it green'
++ print(' signal is already red. Try make it green')
+ # make signal green, if signal has been green in the past and
+ # if all conflicting connectors are red
+ #inds_con_ambiqu = (phaseconflicts[i] == 2) & (inds_con_confcheck>0) & are_enabeled
+@@ -1108,9 +1108,9 @@
+ phaseconflicts[i][ind_con] = 0
+
+ if 0: # debug
+- print ' After safetycheck: Show phases n_phase', n_phase
+- for i, inds_phaseconflict, prio in zip(xrange(n_phase), phaseconflicts, phasepriorities):
+- print ' phase', i, 'prio', prio
++ print(' After safetycheck: Show phases n_phase', n_phase)
++ for i, inds_phaseconflict, prio in zip(range(n_phase), phaseconflicts, phasepriorities):
++ print(' phase', i, 'prio', prio)
+ #ids_con_conf_phase = ids_con_tls[inds_phaseconflict==2]
+ # print ' ids_con_conf_phase',ids_con_conf_phase
+ #ids_con_merge_phase = ids_con_tls[inds_phaseconflict==1]
+@@ -1119,9 +1119,9 @@
+ ids_node_phase = set(ids_connodes[inds_phaseconflict > 0])
+
+ for id_node in ids_node_phase:
+- print ' id_node', id_node
+- print ' ids_conflicts', ids_con_tls[(inds_phaseconflict == 2) & (ids_connodes == id_node)]
+- print ' ids_merge', ids_con_tls[(inds_phaseconflict == 1) & (ids_connodes == id_node)]
++ print(' id_node', id_node)
++ print(' ids_conflicts', ids_con_tls[(inds_phaseconflict == 2) & (ids_connodes == id_node)])
++ print(' ids_merge', ids_con_tls[(inds_phaseconflict == 1) & (ids_connodes == id_node)])
+
+ # push red signs back over short edges
+ if 1:
+@@ -1132,7 +1132,7 @@
+ slots_raw = phaseconflicts[i]
+ # index with all merge and red signals
+ inds = np.flatnonzero(slots_raw == 2)
+- print '\n Phase', i, 'block ids_con', ids_con_tls[inds]
++ print('\n Phase', i, 'block ids_con', ids_con_tls[inds])
+ # print ' red ',ids_con_tls[phaseconflicts[i]==2]
+ # print ' merge',ids_con_tls[phaseconflicts[i]==1]
+ # go though all connectors with merge and red signals
+@@ -1144,9 +1144,9 @@
+ phaseconflicts[i] = slots
+
+ if 1: # debug
+- print ' After push back reds: Show phases n_phase', n_phase
+- for i, inds_phaseconflict, prio in zip(xrange(n_phase), phaseconflicts, phasepriorities):
+- print ' phase', i, 'prio', prio
++ print(' After push back reds: Show phases n_phase', n_phase)
++ for i, inds_phaseconflict, prio in zip(range(n_phase), phaseconflicts, phasepriorities):
++ print(' phase', i, 'prio', prio)
+ #ids_con_conf_phase = ids_con_tls[inds_phaseconflict==2]
+ # print ' ids_con_conf_phase',ids_con_conf_phase
+ #ids_con_merge_phase = ids_con_tls[inds_phaseconflict==1]
+@@ -1155,14 +1155,14 @@
+ ids_node_phase = set(ids_connodes[inds_phaseconflict > 0])
+
+ for id_node in ids_node_phase:
+- print ' id_node', id_node
+- print ' ids_conflicts', ids_con_tls[(inds_phaseconflict == 2) & (ids_connodes == id_node)]
+- print ' ids_merge', ids_con_tls[(inds_phaseconflict == 1) & (ids_connodes == id_node)]
++ print(' id_node', id_node)
++ print(' ids_conflicts', ids_con_tls[(inds_phaseconflict == 2) & (ids_connodes == id_node)])
++ print(' ids_merge', ids_con_tls[(inds_phaseconflict == 1) & (ids_connodes == id_node)])
+
+ # create traffic light system in SUMO net
+ n_phase = len(phaseconflicts)
+ if n_phase <= 1:
+- print ' Less than one phase => abbandon.'
++ print(' Less than one phase => abbandon.')
+ return False
+
+ inds_con_controlled = np.zeros(n_cons, dtype=np.bool)
+@@ -1170,7 +1170,7 @@
+ inds_con_off = np.zeros(n_cons, dtype=np.bool)
+ states = []
+ ids_node_sumotls = []
+- for id_node, nodeattrs in nodes_tls.iteritems():
++ for id_node, nodeattrs in nodes_tls.items():
+ # if nodeattrs['is_crossing']
+ # print ' tlscheck id_node',id_node,'is_cycleped',nodeattrs['is_cycleped']
+ if not nodeattrs['is_cycleped']:
+@@ -1226,18 +1226,18 @@
+ inds_con_sumotls = np.flatnonzero(inds_con_off | inds_con_controlled)
+ ids_con_sumotls = ids_con_tls[inds_con_sumotls]
+
+- print ' ids_con_notls', ids_con_tls[inds_con_notls]
+- print ' are_enabeled', ids_con_tls[are_enabeled]
+- print ' ids_con_controlled', ids_con_tls[inds_con_controlled]
+-
+- print ' ids_node_sumotls', ids_node_sumotls
+- print ' ids_con_sumotls', ids_con_sumotls
+- print ' ids_con_off', ids_con_tls[inds_con_off]
++ print(' ids_con_notls', ids_con_tls[inds_con_notls])
++ print(' are_enabeled', ids_con_tls[are_enabeled])
++ print(' ids_con_controlled', ids_con_tls[inds_con_controlled])
++
++ print(' ids_node_sumotls', ids_node_sumotls)
++ print(' ids_con_sumotls', ids_con_sumotls)
++ print(' ids_con_off', ids_con_tls[inds_con_off])
+
+ #n_cons_sumotls = len(inds_con_sumotls)
+ states = []
+ weights = []
+- for i, prio in zip(xrange(n_phase), phasepriorities):
++ for i, prio in zip(range(n_phase), phasepriorities):
+ #state = np.zeros(n_cons_sumotls, dtype = np.int32)
+ conflicts_last = phaseconflicts[i-1][inds_con_sumotls]
+ conflicts = phaseconflicts[i][inds_con_sumotls]
+@@ -1262,7 +1262,7 @@
+ states_sumotls = []
+ for state in states:
+ states_sumotls.append(string.join(signals[state], ''))
+- print ' state=', states_sumotls[-1]
++ print(' state=', states_sumotls[-1])
+
+ id_tls = tlss.suggest_id()
+ weights = np.array(weights, dtype=np.float32)
+@@ -1285,7 +1285,7 @@
+ tlss.set_connections(id_tls, ids_con_sumotls)
+
+ # link controlled nodes to id_tls
+- for id_node, nodeattrs in nodes_tls.iteritems():
++ for id_node, nodeattrs in nodes_tls.items():
+ # define controlled connections
+ # for id_con in ids_con_tls[(ids_connodes == id_node) & np.logical_not(are_enabeled)]:
+ # connections.are_uncontrolled[id_con] = id_con# not in ids_con_sumotls
+@@ -1308,7 +1308,7 @@
+ ids_con_tls_route = ids_con_tls[inds_con_route]
+ for id_con, ind_con in zip(ids_con_tls_route, np.flatnonzero(inds_con_route)):
+
+- print '\ninit_slots for id_con', id_con # ,ids_con_tls[ind_con],ind_con
++ print('\ninit_slots for id_con', id_con) # ,ids_con_tls[ind_con],ind_con
+ # print ' inds_cons_conflict\n',inds_cons_conflict[id_con]
+ # print ' inds_cons_merge\n',inds_cons_merge[id_con]
+
+@@ -1321,7 +1321,7 @@
+ slots_raw = 2*(inds_cons_conflict[id_con] &
+ np.logical_not(inds_cons_merge[id_con])) + 1 * inds_cons_merge[id_con]
+ inds = np.flatnonzero(slots_raw)
+- print ' block', ids_con_tls[inds]
++ print(' block', ids_con_tls[inds])
+ for ind_confl, slot_raw in zip(inds, slots_raw[inds]):
+ self.block_connection(ind_confl, slot_raw, slots, ids_fromlane_tls,
+ ids_tolane_tls, ids_con_tls, are_enabeled)
+@@ -1344,8 +1344,8 @@
+ # inds_con_crit = inds_con_conf_check & np.logical_not(slots_blocked>0)
+ # inds_con_crit = inds_con_crit & are_enabeled
+ #
+- print ' =>3stopslots for cons\n', ids_con_tls[slots == 2]
+- print ' =>3mergeslots for cons\n', ids_con_tls[slots == 1]
++ print(' =>3stopslots for cons\n', ids_con_tls[slots == 2])
++ print(' =>3mergeslots for cons\n', ids_con_tls[slots == 1])
+
+ return slots, slots_blocked
+
+@@ -1362,11 +1362,11 @@
+
+ id_fromlane = ids_fromlane_tls[ind_con_block]
+ is_disabled = not are_enabeled[ind_con_block]
+- print 'block_connection id %d id_fromlane %d' % (ids_con_tls[ind_con_block], id_fromlane), 'nocycleped', lanes.ids_mode[ids_fromlane_tls[ind_con_block]] not in self.ids_cycleped, 'slot', slots[ind_con_block], 'L=%dm' % edges.lengths[lanes.ids_edge[id_fromlane]],
++ print('block_connection id %d id_fromlane %d' % (ids_con_tls[ind_con_block], id_fromlane), 'nocycleped', lanes.ids_mode[ids_fromlane_tls[ind_con_block]] not in self.ids_cycleped, 'slot', slots[ind_con_block], 'L=%dm' % edges.lengths[lanes.ids_edge[id_fromlane]], end=' ')
+
+ if (slots[ind_con_block] > 0) | is_disabled:
+ # ind_con_block has already been tuned to red
+- print '*'
++ print('*')
+ return
+
+ # do not block accross cycleped edges
+@@ -1382,28 +1382,28 @@
+ # all connectors have not been visited
+ if (len(inds_con) > 0) & np.all(slots[inds_con] >= 0):
+ slots[ind_con_block] = -1 # sign as visited
+- print
+- print '->', ids_con_tls[inds_con]
++ print()
++ print('->', ids_con_tls[inds_con])
+
+ for ind_con in inds_con:
+ self.block_connection(ind_con, 2, slots, ids_fromlane_tls,
+ ids_tolane_tls, ids_con_tls, are_enabeled)
+- print '.'
++ print('.')
+ slots[ind_con_block] = 0 # remove sign as visited
+
+ else:
+ # from lane is connected from outside the TLS:
+ slots[ind_con_block] = 2 # put red light
+- print '-r'
++ print('-r')
+ else:
+ # road length acceptable
+ slots[ind_con_block] = slot_raw
+- print '-s', slot_raw
++ print('-s', slot_raw)
+
+ else:
+ # to lane is bikeway or footpath
+ slots[ind_con_block] = slot_raw
+- print '-b', slot_raw
++ print('-b', slot_raw)
+
+ # print ' stopslots %d for cons\n'%ids_con_tls[ind_con_block],ids_con_tls[slots == 2]
+ # print ' mergeslots %d for cons\n'%ids_con_tls[ind_con_block],ids_con_tls[slots == 1]
+@@ -1418,7 +1418,7 @@
+ Allocates a phase for a particular route though the TLS.
+ The route is represented by the connector indexes along the route.
+ """
+- print '\nadd_timeslot for', ids_con_tls[inds_con_route]
++ print('\nadd_timeslot for', ids_con_tls[inds_con_route])
+ # go through all connections used by this route and
+ # signalize all conflicts
+ # for id_con in ids_con_tls[inds_con_route]:
+@@ -1432,40 +1432,40 @@
+ ids_tolane_tls,
+ are_enabeled)
+ n_slots = len(np.flatnonzero(slots))
+- print ' n_slots', n_slots, 'n_phases', len(phaseconflicts)
++ print(' n_slots', n_slots, 'n_phases', len(phaseconflicts))
+
+ if n_slots == 0:
+- print ' no conflicts detected'
++ print(' no conflicts detected')
+ pass
+
+ elif len(phaseconflicts) == 0:
+- print ' append first phase'
++ print(' append first phase')
+ phaseallocations.append(inds_con_route)
+ phaseconflicts.append(slots)
+ phaseblocks.append(slots_blocked)
+ phasepriorities.append(prio)
+ else:
+- print ' search phase with minimum signal difference n_phases=', len(phaseallocations)
++ print(' search phase with minimum signal difference n_phases=', len(phaseallocations))
+ n_diff_min = 10**8
+ i_phase = 0
+ i_phase_min = -1
+ for inds_phaseallocation, inds_phaseconflict in zip(phaseallocations, phaseconflicts):
+ # check if slots overlap with allocated connections this phase
+- print ' compare phase', i_phase
+- print ' new allocations', ids_con_tls[inds_con_route]
+- print ' phaseallocations', ids_con_tls[inds_phaseallocation]
+- print ' new conflicts', ids_con_tls[slots == 2]
+- print ' phase conflicts', ids_con_tls[inds_phaseconflict == 2]
++ print(' compare phase', i_phase)
++ print(' new allocations', ids_con_tls[inds_con_route])
++ print(' phaseallocations', ids_con_tls[inds_phaseallocation])
++ print(' new conflicts', ids_con_tls[slots == 2])
++ print(' phase conflicts', ids_con_tls[inds_phaseconflict == 2])
+ # print ' allocations',ids_con_tls[inds_phaseallocation]
+- print ' n_diff =', np.sum(np.any((slots == 2) & inds_phaseallocation))
++ print(' n_diff =', np.sum(np.any((slots == 2) & inds_phaseallocation)))
+
+ if not np.any((slots == 2) & inds_phaseallocation):
+- print ' no conflict in this phase go for a merge'
++ print(' no conflict in this phase go for a merge')
+ i_phase_min = i_phase
+ n_diff_min = -1 # indicate phase merge
+
+ else:
+- print ' there are conflicts with this phase...count'
++ print(' there are conflicts with this phase...count')
+ n_diff = np.sum(np.any((slots == 2) & inds_phaseallocation))
+ #n_diff = np.sum(np.abs(slots - inds_phaseconflict)!=0)
+ # print ' ',inds_phaseconflict,n_diff
+@@ -1475,14 +1475,14 @@
+
+ i_phase += 1
+
+- print ' finished comparing phases i_phase_min,n_diff_min', i_phase_min, n_diff_min
++ print(' finished comparing phases i_phase_min,n_diff_min', i_phase_min, n_diff_min)
+
+ if n_diff_min == 0:
+- print ' already a phase with suitable signalling, nothing to do'
++ print(' already a phase with suitable signalling, nothing to do')
+ pass
+
+ elif n_diff_min == -1:
+- print ' there are no phase conflicts, so merge'
++ print(' there are no phase conflicts, so merge')
+ phaseallocations[i_phase_min] = phaseallocations[i_phase_min] | inds_con_route
+ phaseconflicts[i_phase_min] = np.max([slots, phaseconflicts[i_phase_min]], 0)
+ phaseblocks[i_phase_min] = phaseblocks[i_phase_min] | slots_blocked
+@@ -1498,14 +1498,14 @@
+ # get number of cons which are less restrictive signals
+ n_diff_neg = np.sum((slots - phaseconflicts[i_phase_min]) < 0)
+
+- print ' n_diff_min', n_diff_min, 'n_diff_pos', n_diff_pos, 'n_diff_neg', n_diff_neg, 'i_phase_min', i_phase_min
++ print(' n_diff_min', n_diff_min, 'n_diff_pos', n_diff_pos, 'n_diff_neg', n_diff_neg, 'i_phase_min', i_phase_min)
+ # print ' inds_phaseconflict_min',ids_con_tls[phaseconflicts[i_phase_min] >0]
+ # print ' inds_phaseconflict',ids_con_tls[slots>0]
+ #inds_diff = np.abs(slots - inds_phaseconflict)!=0
+ # if (n_diff_pos>0) & (n_diff_neg == 0):
+ if (n_diff_pos >= n_diff_neg) & (n_diff_pos <= 2):
+ # only more restrictive
+- print ' put new phase after the phase with minimum difference'
++ print(' put new phase after the phase with minimum difference')
+ phaseallocations.insert(i_phase_min+1, inds_con_route)
+ phaseconflicts.insert(i_phase_min+1, slots)
+ phaseblocks.insert(i_phase_min+1, slots_blocked)
+@@ -1514,7 +1514,7 @@
+ # elif (n_diff_pos==0) & (n_diff_neg > 0):
+ if (n_diff_pos < n_diff_neg) & (n_diff_neg <= 2):
+ # only less restrictive
+- print ' put new phase before the phase with minimum difference'
++ print(' put new phase before the phase with minimum difference')
+ phaseallocations.insert(i_phase_min, inds_con_route)
+ phaseconflicts.insert(i_phase_min, slots)
+ phaseblocks.insert(i_phase_min, slots_blocked)
+@@ -1522,13 +1522,13 @@
+
+ else:
+ # mixed changes
+- print ' append en entirely new phase'
++ print(' append en entirely new phase')
+ phaseconflicts.append(slots)
+ phaseblocks.append(slots_blocked)
+ phasepriorities.append(prio)
+
+ def init_tlsnode(self, id_node, nodes_tls):
+- print 'init_tlsnode', id_node, 'is in TLS'
++ print('init_tlsnode', id_node, 'is in TLS')
+ nodeattrs = {}
+ if id_node in self.ids_majornodes:
+ self.ids_majornodes_used.add(id_node)
+@@ -1543,7 +1543,7 @@
+ nodes_tls[id_node] = nodeattrs
+
+ def find_neighbour_nodes(self, id_node, dist, nodes_tls, edges, nodes):
+- print 'find_neighbour_nodes', id_node, dist
++ print('find_neighbour_nodes', id_node, dist)
+ dist_tls_max = self.dist_tls_max
+ #ids_edge = nodes.ids_outgoing[id_node]
+
+@@ -1556,23 +1556,23 @@
+ if len(ids_edge_out) == 1:
+ # one incoming one outgoing only, check if bidir link
+ if edges.ids_fromnode[ids_edge[0]] == edges.ids_tonode[ids_edge_out[0]]:
+- print ' it is a turnaround only node -> remove node', id_node
++ print(' it is a turnaround only node -> remove node', id_node)
+ del nodes_tls[id_node]
+ return
+ elif len(ids_edge) == 0: # no input??
+- print ' no input -> remove node', id_node
++ print(' no input -> remove node', id_node)
+ del nodes_tls[id_node]
+ return
+
+ for id_edge, length, id_edgenode in zip(ids_edge, edges.lengths[ids_edge], edges.ids_fromnode[ids_edge]):
+- print ' check in id_edge', id_edge, dist+length, dist_tls_max, (dist+length < dist_tls_max), (length < self.dist_tls_internode_max)
++ print(' check in id_edge', id_edge, dist+length, dist_tls_max, (dist+length < dist_tls_max), (length < self.dist_tls_internode_max))
+ if (dist+length < dist_tls_max) & (length < self.dist_tls_internode_max):
+ if id_edgenode not in nodes_tls:
+ self.init_tlsnode(id_edgenode, nodes_tls)
+ self.find_neighbour_nodes(id_edgenode, dist+length, nodes_tls, edges, nodes)
+ else:
+ # node without incoming??
+- print ' node without incoming -> remove node', id_node
++ print(' node without incoming -> remove node', id_node)
+ del nodes_tls[id_node]
+ return
+
+@@ -1602,7 +1602,7 @@
+ that no turnarounds are used,
+ and for not major routes that the route follows a straight line.
+ """
+- print 'correct_tls_route', route
++ print('correct_tls_route', route)
+ net = self.parent
+ edges = net.edges
+ #ids_edges_major = self.ids_edges_major
+@@ -1652,7 +1652,7 @@
+ # determine angle change
+ angle = get_diff_angle_clockwise(dir1, dir2)
+ angle_abs = min(angle, 2*np.pi-angle)
+- print ' id_edge:%d, angle_abs:%.1f, angle_max: %.1f' % (id_edge, angle_abs/np.pi*180, angle_max/np.pi*180), id_fromnode in nodes_tls, (angle_abs < angle_max)
++ print(' id_edge:%d, angle_abs:%.1f, angle_max: %.1f' % (id_edge, angle_abs/np.pi*180, angle_max/np.pi*180), id_fromnode in nodes_tls, (angle_abs < angle_max))
+ if id_fromnode in nodes_tls:
+ # route is still in TLS
+ p01 = shape_curr[-2][:2]
+@@ -1688,11 +1688,11 @@
+ newroutes.append(newroute)
+ routecosts.append(self.get_routecost(newroute))
+
+- print ' ind_route', ind_route, len(route), 'newroutes', newroutes, 'routecosts', routecosts
++ print(' ind_route', ind_route, len(route), 'newroutes', newroutes, 'routecosts', routecosts)
+ return newroutes, routecosts
+
+ def follow_major_route_backward(self, id_edge_next, shape):
+- print 'follow_major_route_backward', id_edge_next
++ print('follow_major_route_backward', id_edge_next)
+ net = self.parent
+ edges = net.edges
+ ids_edges_major = self.ids_edges_major
+@@ -1787,7 +1787,7 @@
+ return route
+
+ def follow_major_route_foreward(self, id_edge_next, shape):
+- print 'follow_major_route_foreward', id_edge_next
++ print('follow_major_route_foreward', id_edge_next)
+ net = self.parent
+ edges = net.edges
+ ids_edges_major = self.ids_edges_major
+@@ -1833,7 +1833,7 @@
+ angle = get_diff_angle_clockwise(dir1, dir2)
+ angle_abs = min(angle, 2*np.pi-angle)
+ edgedirection2 = shape[:2]
+- print ' |angle|=%d' % (angle_abs/np.pi*180), angle/np.pi*180, dir1, dir2
++ print(' |angle|=%d' % (angle_abs/np.pi*180), angle/np.pi*180, dir1, dir2)
+
+ if angle_abs < angle_max:
+ if id_edge not in self.ids_edges_major:
+@@ -1874,7 +1874,7 @@
+ p01 = shape_next[-2][:2]
+ p11 = shape_next[-1][:2]
+ dir1 = p11-p01
+- print ' **winner:', id_edge_next, 'dir1=', dir1
++ print(' **winner:', id_edge_next, 'dir1=', dir1)
+ route.append(id_edge_next)
+ ids_edges_major.add(id_edge_next)
+
+@@ -1887,7 +1887,7 @@
+
+ class BikenetworkCompleter(Process):
+ def __init__(self, net, logger=None, **kwargs):
+- print 'Bikenetworkcompleter.__init__'
++ print('Bikenetworkcompleter.__init__')
+ self._init_common('bikenetworkcompleter',
+ parent=net,
+ name='Bike network completer',
+@@ -1959,7 +1959,7 @@
+ [modes.get_id_mode("pedestrian"), modes.get_id_mode("delivery"), modes.get_id_mode("bus")])
+
+ def do(self):
+- print 'BikenetworkCompleter.do'
++ print('BikenetworkCompleter.do')
+ edges = self.parent.edges
+ nodes = self.parent.nodes
+ lanes = self.parent.lanes
+@@ -2187,7 +2187,7 @@
+
+ class TlsjunctionGenerator_old(netconvert.NetConvertMixin):
+ def __init__(self, net, logger=None, **kwargs):
+- print 'TlsjunctionGenerator.__init__'
++ print('TlsjunctionGenerator.__init__')
+ self._init_common('tlsjunctiongenerator',
+ parent=net,
+ name='Trafficlight Junction generator',
+@@ -2215,7 +2215,7 @@
+ ))
+
+ def do(self):
+- print 'TlsjunctionGenerator.do'
++ print('TlsjunctionGenerator.do')
+ net = self.parent
+ edges = self.parent.edges
+ nodes = self.parent.nodes
+--- tools/contributed/sumopy/coremodules/network/networkxtools.py (original)
++++ tools/contributed/sumopy/coremodules/network/networkxtools.py (refactored)
+@@ -32,7 +32,8 @@
+ from collections import OrderedDict
+ from copy import deepcopy
+ import sys
+-reload(sys)
++import importlib
++importlib.reload(sys)
+ sys.setdefaultencoding('utf8')
+
+ try:
+@@ -63,7 +64,7 @@
+ try:
+ f = open(filepath, 'rb')
+ except:
+- print 'WARNING in load_obj: could not open', filepath
++ print('WARNING in load_obj: could not open', filepath)
+ return None
+
+ # try:
+@@ -74,18 +75,18 @@
+
+
+ def print_attrs(attrs):
+- for key, val in attrs.iteritems():
+- print ' %s=\t%s' % (key, val)
+- print
++ for key, val in attrs.items():
++ print(' %s=\t%s' % (key, val))
++ print()
+
+
+ def get_loop(digraph, ids_node, ids_nodepairs=[], n_node_max=4):
+- print 'get_loop ids_node', ids_node
++ print('get_loop ids_node', ids_node)
+ if (ids_node[-1] == ids_node[0]):
+- print ' success.'
++ print(' success.')
+ return ids_nodepairs
+ elif (len(ids_node) == n_node_max):
+- print ' no loop reached.'
++ print(' no loop reached.')
+ return []
+ else:
+ id_node = ids_node[-1]
+@@ -94,7 +95,7 @@
+ id_nbnode = ids_node[-2]
+ # print ' node_to_dirind.keys()',node_to_dirind.keys(),node_to_dirind.has_key(id_nbnode)
+
+- if node_to_dirind.has_key(id_nbnode):
++ if id_nbnode in node_to_dirind:
+ ind = node['node_to_dirind'][id_nbnode]
+ else:
+ ind = node['node_to_dirind'][-id_nbnode]
+@@ -106,11 +107,11 @@
+
+ id_nbnode_new = node['dirind_to_node'][ind]
+ if id_nbnode == id_nbnode_new:
+- print ' simple bidir return link'
++ print(' simple bidir return link')
+ return []
+
+ elif abs(id_nbnode_new) in ids_node[1:]:
+- print ' complex bidir return link'
++ print(' complex bidir return link')
+ return []
+
+ if id_nbnode_new < 0:
+@@ -166,7 +167,7 @@
+ """
+ Make defaults to be overridden
+ """
+- print 'config'
++ print('config')
+ # pass here either road type specific defaults
+ # or global defaults from parent process
+
+@@ -272,7 +273,7 @@
+ def make_sumoattrs(self):
+
+ osmattrs = self._osmattrs
+- print 'make_sumoattrs'
++ print('make_sumoattrs')
+ print_attrs(osmattrs)
+ #self._highway = osmattrs.get('highway','road')
+
+@@ -292,7 +293,7 @@
+ n_lane_backward_osm = -1
+ is_lanes_forward_rigid = False
+ is_lanes_backward_rigid = False
+- if osmattrs.has_key('lanes'):
++ if 'lanes' in osmattrs:
+ # print ' total number of lanes provided n_lane_osm_str',osmattrs['lanes']
+ n_lane_osm_str = osmattrs['lanes']
+ # if type(n_lane_osm_str) in cm.STRINGTYPES:
+@@ -317,10 +318,10 @@
+
+ else:
+ # in case of bidir
+- if osmattrs.has_key('lanes:forward'):
++ if 'lanes:forward' in osmattrs:
+ n_lane_forward_osm = int(osmattrs['lanes:forward'])
+ is_lanes_forward_rigid = True
+- if osmattrs.has_key('lanes:backward'):
++ if 'lanes:backward' in osmattrs:
+ n_lane_backward_osm = int(osmattrs['lanes:backward'])
+ is_lanes_backward_rigid = True
+ else:
+@@ -330,7 +331,7 @@
+ n_lane_backward_osm = 1
+ n_lane_osm = n_lane_forward_osm+n_lane_backward_osm
+
+- elif osmattrs.has_key('lanes:backward'):
++ elif 'lanes:backward' in osmattrs:
+ n_lane_backward_osm = int(osmattrs['lanes:backward'])
+ n_lane_forward_osm = n_lane_osm-n_lane_backward_osm
+ is_lanes_backward_rigid = True
+@@ -352,23 +353,23 @@
+ if is_oneway_osm:
+ # in cas of (declared) oneway
+ n_lane_backward_osm = 0
+- if osmattrs.has_key('lanes:forward'):
++ if 'lanes:forward' in osmattrs:
+ n_lane_forward_osm = int(osmattrs['lanes:forward'])
+ is_lanes_forward_rigid = True
+ else:
+ n_lane_forward_osm = self.n_lane # default
+ else:
+ # bidir
+- if osmattrs.has_key('lanes:forward'):
++ if 'lanes:forward' in osmattrs:
+ n_lane_forward_osm = int(osmattrs['lanes:forward'])
+ is_lanes_forward_rigid = True
+- if osmattrs.has_key('lanes:backward'):
++ if 'lanes:backward' in osmattrs:
+ n_lane_backward_osm = int(osmattrs['lanes:backward'])
+ is_lanes_backward_rigid = True
+ else:
+ n_lane_backward_osm = self.n_lane # default
+
+- elif osmattrs.has_key('lanes:backward'):
++ elif 'lanes:backward' in osmattrs:
+ n_lane_backward_osm = int(osmattrs['lanes:backward'])
+ is_lanes_backward_rigid = True
+ n_lane_forward_osm = self.n_lane # default
+@@ -386,7 +387,7 @@
+ self._n_lane_forward_osm = n_lane_forward_osm
+ self._n_lane_backward_osm = n_lane_backward_osm
+ self._n_lane_osm = n_lane_osm
+- print ' lane numbers: n_lane_forward_osm=%d, n_lane_backward_osm=%d n_default=%d' % (n_lane_forward_osm, n_lane_backward_osm, self.n_lane), 'rigid fb', is_lanes_forward_rigid, is_lanes_backward_rigid
++ print(' lane numbers: n_lane_forward_osm=%d, n_lane_backward_osm=%d n_default=%d' % (n_lane_forward_osm, n_lane_backward_osm, self.n_lane), 'rigid fb', is_lanes_forward_rigid, is_lanes_backward_rigid)
+
+ def _get_access(self, access_str):
+ access_data = np.array(access_str.split('|'), dtype=np.object)[::-1]
+@@ -446,12 +447,12 @@
+
+ #lanes = []
+ #lanes_opp = []
+- print ' realoneway', self.is_oneway()
++ print(' realoneway', self.is_oneway())
+
+ #self._lanes = []
+ #self._lanes_opp = []
+
+- print ' Main Dir ^^^^^^^^^^^', self._is_lanes_forward_rigid, self._is_lanes_backward_rigid
++ print(' Main Dir ^^^^^^^^^^^', self._is_lanes_forward_rigid, self._is_lanes_backward_rigid)
+ if self._is_lanes_forward_rigid:
+ self.make_lanes_rigid(is_opp=False, n_lane_osm=self._n_lane_forward_osm)
+ else:
+@@ -459,15 +460,15 @@
+
+ if not self.is_oneway():
+
+- print ' Opp Dir vvvvvvvvvvv'
++ print(' Opp Dir vvvvvvvvvvv')
+ if self._is_lanes_backward_rigid:
+ self.make_lanes_rigid(is_opp=True, n_lane_osm=self._n_lane_backward_osm)
+ else:
+ self.make_lanes(is_opp=True, n_lane_osm=self._n_lane_backward_osm)
+
+- print ' id', id(self)
+- print ' len(self._lanes)', len(self._lanes)
+- print ' len(self._lanes_opp)', len(self._lanes_opp)
++ print(' id', id(self))
++ print(' len(self._lanes)', len(self._lanes))
++ print(' len(self._lanes_opp)', len(self._lanes_opp))
+
+ def _get_speedinfo(self, speed_max_str):
+ speed_max_data = speed_max_str.split(' ')
+@@ -490,7 +491,7 @@
+
+ def make_speed(self, speed_max_default):
+ # estimate speed max in m/s
+- if self._osmattrs.has_key('maxspeed'):
++ if 'maxspeed' in self._osmattrs:
+ speed_max_str = self._osmattrs['maxspeed']
+ # print 'make_speed speed_max_str',speed_max_str
+ if speed_max_str.count(';') > 0:
+@@ -511,7 +512,7 @@
+ self.speed_max = speed_max
+
+ def _is_opposite(self, osmattrs, tag):
+- if osmattrs.has_key(tag):
++ if tag in osmattrs:
+ elems = osmattrs[tag].split('_')
+ return elems[0] == 'opposite'
+ else:
+@@ -527,7 +528,7 @@
+ if osmattrs.get('junction', '') == 'roundabout':
+ self._is_oneway = True
+
+- elif osmattrs.has_key('oneway'):
++ elif 'oneway' in osmattrs:
+ if osmattrs['oneway'] == 'no':
+ self._is_oneway = False
+
+@@ -538,13 +539,13 @@
+ elif self._is_opposite(osmattrs, 'busway:right'):
+ self._is_oneway = False
+
+- elif osmattrs.has_key('lanes:bus:backward'):
++ elif 'lanes:bus:backward' in osmattrs:
+ self._is_oneway = False
+
+- elif osmattrs.has_key('trolley_wire:both'):
++ elif 'trolley_wire:both' in osmattrs:
+ self._is_oneway = False
+
+- elif osmattrs.has_key('lanes:psv:backward'):
++ elif 'lanes:psv:backward' in osmattrs:
+ self._is_oneway = False
+
+ elif self._is_opposite(osmattrs, 'cycleway'):
+@@ -563,7 +564,7 @@
+ # elif osmattrs.get('sidewalk','') == 'both':
+ # self._is_oneway = False
+
+- elif osmattrs.has_key('oneway:bicycle'):
++ elif 'oneway:bicycle' in osmattrs:
+ if osmattrs['oneway:bicycle'] == 'no':
+ self._is_oneway = False
+
+@@ -607,7 +608,7 @@
+ else:
+ ind = 1
+
+- print 'add_sidewalk', is_opp, self._sidewalkattrs[ind]['n_lane'], self._sidewalkattrs[ind]['n_lane'] == 0
++ print('add_sidewalk', is_opp, self._sidewalkattrs[ind]['n_lane'], self._sidewalkattrs[ind]['n_lane'] == 0)
+ if self._sidewalkattrs[ind]['n_lane'] == 0:
+ self.make_sidewalk(is_opp=is_opp, is_rightside=True, width=road.lanewidth)
+ self.make_road()
+@@ -629,7 +630,7 @@
+ # to mark that sidewalks are mapped separately.
+ # Also, sidewalk=separate
+
+- print 'make_sidewalk', ind, is_rightside
++ print('make_sidewalk', ind, is_rightside)
+ # needed to merge access?
+ self._sidewalkattrs[ind]['is_share'] = len(ids_modes_allow) > 0
+
+@@ -657,7 +658,7 @@
+ print_attrs(self._sidewalkattrs[ind])
+
+ def make_sidewalkattrs(self):
+- print 'make_sidewalkattrs'
++ print('make_sidewalkattrs')
+
+ if self.get_priority() < 7:
+ return self.make_sidewalkattrs_smallroads()
+@@ -665,7 +666,7 @@
+ return self.make_sidewalkattrs_largeroads()
+
+ def make_sidewalkattrs_largeroads(self):
+- print 'make_sidewalkattrs_largeroads'
++ print('make_sidewalkattrs_largeroads')
+
+ osmattrs = self._osmattrs
+ self._sidewalkattrs = (deepcopy(LANEATTRS_DEFAULT),
+@@ -678,11 +679,11 @@
+ if sidewalk not in ['no', 'none', 'auto']:
+ # there is a sidewalk, make sure there is at least one
+
+- if osmattrs.has_key('sidewalk:width'):
++ if 'sidewalk:width' in osmattrs:
+ width_left = float(osmattrs['sidewalk:width'])
+ width_right = width_left
+
+- elif osmattrs.has_key('sidewalk:both:width'):
++ elif 'sidewalk:both:width' in osmattrs:
+ width_left = float(osmattrs['sidewalk:both:width'])
+ width_right = width_left
+ else:
+@@ -742,7 +743,7 @@
+ # print_attrs(attrs)
+
+ def make_sidewalkattrs_smallroads(self):
+- print 'make_sidewalkattrs_smallroads'
++ print('make_sidewalkattrs_smallroads')
+ osmattrs = self._osmattrs
+ self._sidewalkattrs = (deepcopy(LANEATTRS_DEFAULT),
+ deepcopy(LANEATTRS_DEFAULT))
+@@ -754,11 +755,11 @@
+ if sidewalk not in ['no', 'none', 'auto']:
+ # there is a sidewalk, make sure there is at least one
+
+- if osmattrs.has_key('sidewalk:width'):
++ if 'sidewalk:width' in osmattrs:
+ width_left = float(osmattrs['sidewalk:width'])
+ width_right = width_left
+
+- elif osmattrs.has_key('sidewalk:both:width'):
++ elif 'sidewalk:both:width' in osmattrs:
+ width_left = float(osmattrs['sidewalk:both:width'])
+ width_right = width_left
+ else:
+@@ -808,20 +809,20 @@
+ if self.is_oneway():
+
+ if osmattrs.get('junction', '') == 'roundabout':
+- print ' put a sidewalk around roundabouts, not inside'
++ print(' put a sidewalk around roundabouts, not inside')
+ self.make_sidewalk(is_opp=False, is_rightside=True, width=self.width_sidewalk)
+ else:
+- print ' put a sidewalk on both sides of the oneway'
++ print(' put a sidewalk on both sides of the oneway')
+ self.make_sidewalk(is_opp=False, is_rightside=True, width=self.width_sidewalk)
+ self.make_sidewalk(is_opp=False, is_rightside=False, width=self.width_sidewalk)
+ else:
+- print ' put a sidewalk on both sides of the road'
++ print(' put a sidewalk on both sides of the road')
+ self.make_sidewalk(is_opp=False, is_rightside=True, width=self.width_sidewalk)
+ self.make_sidewalk(is_opp=True, is_rightside=True, width=self.width_sidewalk)
+
+ def make_bikelane(self, is_opp=False, is_rightside=True,
+ ids_modes_allow=[], width=1.5, n_lane=1):
+- print 'make_bikelane', is_opp, is_rightside, ids_modes_allow
++ print('make_bikelane', is_opp, is_rightside, ids_modes_allow)
+ if is_opp:
+ ind = 0
+ else:
+@@ -857,7 +858,7 @@
+ widths: is a tuple with sidewalk widths of left and right sidewalk.
+ if values are less than 0 means no sidewalk.
+ """
+- print 'make_bikewayattrs'
++ print('make_bikewayattrs')
+ self._bikewayattrs = (deepcopy(LANEATTRS_DEFAULT),
+ deepcopy(LANEATTRS_DEFAULT))
+
+@@ -866,11 +867,11 @@
+ cycleway_left = osmattrs.get('cycleway:left', '')
+ cycleway_right = osmattrs.get('cycleway:right', '')
+
+- if osmattrs.has_key('cycleway:width'):
++ if 'cycleway:width' in osmattrs:
+ width_left = float(osmattrs['cycleway:width'])
+ width_right = width_left
+
+- elif osmattrs.has_key('cycleway:both:width'):
++ elif 'cycleway:both:width' in osmattrs:
+ width_left = float(osmattrs['cycleway:both:width'])
+ width_right = width_left
+
+@@ -942,7 +943,7 @@
+ # general bicycle tag if all from abive fails but share with pedestrians
+ # Moved to main lane attr except if segragated
+ elif (osmattrs.get('bicycle', 'no') in YES_OR_DESIGNATED) & (osmattrs.get('segregated', '') == 'yes'):
+- print ' check if there are cycle lanes already', self._bikewayattrs[0]['n_lane'] == 0, self._bikewayattrs[1]['n_lane'] == 0
++ print(' check if there are cycle lanes already', self._bikewayattrs[0]['n_lane'] == 0, self._bikewayattrs[1]['n_lane'] == 0)
+
+ if (self._bikewayattrs[0]['n_lane'] == 0) & (self._bikewayattrs[1]['n_lane'] == 0):
+ # no bikelanes in both dir
+@@ -1003,7 +1004,7 @@
+ # Moved to main lane attr except segregated
+ elif (osmattrs.get('bicycle', 'no') in YES_OR_DESIGNATED) & (osmattrs.get('segregated', '') == 'yes'):
+
+- print ' check if there are cycle lanes already', self._bikewayattrs[1]['n_lane'] == 0
++ print(' check if there are cycle lanes already', self._bikewayattrs[1]['n_lane'] == 0)
+ if (self._bikewayattrs[1]['n_lane'] == 0):
+ self.make_bikelane(is_opp=False, is_rightside=True, width=width_left)
+
+@@ -1014,7 +1015,7 @@
+
+ def make_buslane(self, is_opp=False, is_rightside=True,
+ ids_modes_allow=[], width=3.5, n_lane=1):
+- print 'make_buslane', is_opp, is_rightside, width
++ print('make_buslane', is_opp, is_rightside, width)
+ if is_opp:
+ ind = 0
+ else:
+@@ -1052,17 +1053,17 @@
+ return 0
+
+ def make_buswayattrs(self):
+- print 'make_buswayattrs'
++ print('make_buswayattrs')
+ self._buswayattrs = (deepcopy(LANEATTRS_DEFAULT),
+ deepcopy(LANEATTRS_DEFAULT))
+
+ osmattrs = self._osmattrs
+
+- if osmattrs.has_key('busway:width'):
++ if 'busway:width' in osmattrs:
+ width_left = float(osmattrs['busway:width'])
+ width_right = width_left
+
+- elif osmattrs.has_key('busway:both:width'):
++ elif 'busway:both:width' in osmattrs:
+ width_left = float(osmattrs['busway:both:width'])
+ width_right = width_left
+ else:
+@@ -1075,7 +1076,7 @@
+ # busway scheme
+ if osmattrs.get('oneway', 'no') == 'no':
+ # bidir
+- print ' buslane bidir', busway
++ print(' buslane bidir', busway)
+ if busway == 'lane':
+ self.make_buslane(is_opp=False)
+ self.make_buslane(is_opp=True)
+@@ -1125,7 +1126,7 @@
+
+ else:
+ # cycle lanes on oneway road
+- print ' buslane oneway', busway, busway in ('opposite', 'opposite_lane')
++ print(' buslane oneway', busway, busway in ('opposite', 'opposite_lane'))
+ if busway == 'lane':
+ self.make_buslane(is_opp=False, width=width_right)
+
+@@ -1151,7 +1152,7 @@
+
+ return
+
+- elif osmattrs.has_key('lanes:psv'):
++ elif 'lanes:psv' in osmattrs:
+ # lanes:psv=* scheme
+ if osmattrs.get('oneway', 'no') == 'no':
+ # bidir
+@@ -1173,7 +1174,7 @@
+ self.make_buslane(is_opp=False, n_lane=psv, width=width_right)
+ return
+
+- elif osmattrs.has_key('lanes:bus'):
++ elif 'lanes:bus' in osmattrs:
+ # lanes:psv=* scheme
+ if osmattrs.get('oneway', 'no') == 'no':
+ # bidir
+@@ -1189,25 +1190,25 @@
+ self.make_buslane(is_opp=False, n_lane=psv, width=width_right)
+ return
+
+- if osmattrs.has_key('lanes:psv:forward'):
++ if 'lanes:psv:forward' in osmattrs:
+ psv = self._get_psv_from_str(osmattrs['lanes:psv:forward'])
+ self.make_buslane(is_opp=False, n_lane=psv, width=width_right)
+
+- if osmattrs.has_key('lanes:psv:backward'):
++ if 'lanes:psv:backward' in osmattrs:
+ psv = self._get_psv_from_str(osmattrs['lanes:psv:backward'])
+ self.make_buslane(is_opp=True, n_lane=psv, width=width_left)
+
+- if osmattrs.has_key('lanes:bus:forward'):
++ if 'lanes:bus:forward' in osmattrs:
+ n_lane = self._get_psv_from_str(osmattrs['lanes:bus:forward'])
+ self.make_buslane(is_opp=False, n_lane=n_lane, width=width_right)
+
+- if osmattrs.has_key('lanes:bus:backward'):
++ if 'lanes:bus:backward' in osmattrs:
+ n_lane = self._get_psv_from_str(osmattrs['lanes:bus:backward'])
+ self.make_buslane(is_opp=True, n_lane=n_lane, width=width_left)
+
+ if osmattrs.get('oneway', 'no') == 'yes':
+ # special check of opposite bus lane
+- if osmattrs.has_key('trolley_wire:both') | osmattrs.has_key('trolley_wire:backward'):
++ if ('trolley_wire:both' in osmattrs) | ('trolley_wire:backward' in osmattrs):
+ # if way is oneway withot reserved access,
+ # but there are wires in both ways,
+ # then there is probably a reserved bus lane in opposite
+@@ -1289,7 +1290,7 @@
+ return 10
+
+ def merge_laneattrs(self, laneattrs_dest, laneattrs_merge, is_rightside=False, is_leftside=False):
+- print 'merge_laneattrs'
++ print('merge_laneattrs')
+ # print ' laneattrs_dest',laneattrs_dest
+ # print ' laneattrs_merge',laneattrs_merge
+ #self._buswayattrs[ind]['ids_modes_allow'] = ids_allowed
+@@ -1297,7 +1298,7 @@
+ #self._buswayattrs[ind]['is_rightside'] = is_rightside
+ # if laneattrs_merge['width']>laneattrs_dest['width']:
+ width_dest = 0.0
+- if laneattrs_dest.has_key('width'):
++ if 'width' in laneattrs_dest:
+ width_dest = laneattrs_dest['width']
+ else:
+ if is_rightside:
+@@ -1305,7 +1306,7 @@
+ else:
+ width_dest = laneattrs_dest['width_leftside']
+
+- if laneattrs_merge.has_key('width'):
++ if 'width' in laneattrs_merge:
+ width_merge = laneattrs_merge['width']
+ else:
+ if is_rightside:
+@@ -1335,8 +1336,8 @@
+
+ def set_lane(self, lanes, laneattrs, ind):
+ lanes[ind] = deepcopy(laneattrs)
+- if not laneattrs.has_key('width'):
+- if laneattrs.has_key('width_rightside'):
++ if 'width' not in laneattrs:
++ if 'width_rightside' in laneattrs:
+ lanes[ind]['width'] = laneattrs['width_rightside']
+ else:
+ lanes[ind]['width'] = laneattrs['width_rightside']
+@@ -1362,7 +1363,7 @@
+ laneattrs['ids_modes_allow'].append(id_allow)
+
+ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
+- print 'make_lanes_rigid', is_opp, n_lane_osm
++ print('make_lanes_rigid', is_opp, n_lane_osm)
+ osmattrs = self._osmattrs
+
+ if is_opp:
+@@ -1386,7 +1387,7 @@
+ attrs = self._buswayattrs[ind]
+
+ if attrs['n_lane'] > 0:
+- print ' busways n_lane', attrs['n_lane']
++ print(' busways n_lane', attrs['n_lane'])
+
+ n_lane = len(lanes)
+
+@@ -1396,7 +1397,7 @@
+
+ n_allow = len(allowed)
+ if n_allow > 0:
+- for i, a, d in zip(xrange(n_allow), allowed, disallowed):
++ for i, a, d in zip(range(n_allow), allowed, disallowed):
+ if ind < n_lane:
+ if a & (i < n_lane):
+ self.set_lane(lanes, attrs, i)
+@@ -1418,7 +1419,7 @@
+ # do bikeways
+ attrs = self._bikewayattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' bikeways n_lane', attrs['n_lane']
++ print(' bikeways n_lane', attrs['n_lane'])
+
+ n_lane = len(lanes)
+
+@@ -1426,7 +1427,7 @@
+
+ n_allow = len(allowed)
+ if n_allow > 0:
+- for i, a, d in zip(xrange(n_allow), allowed, disallowed):
++ for i, a, d in zip(range(n_allow), allowed, disallowed):
+ if i < n_lane:
+ if a & i < n_lane:
+ self.set_lane(lanes, attrs, i)
+@@ -1448,7 +1449,7 @@
+ # do sidewalks
+ attrs = self._sidewalkattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' sidewalks n_lane', attrs['n_lane']
++ print(' sidewalks n_lane', attrs['n_lane'])
+ n_lane_assig = attrs['n_lane']
+ n_lane = len(lanes)
+ # sidewalks are not considered lanes in osm
+@@ -1477,14 +1478,14 @@
+ self._lanes_opp = lanes
+ else:
+ self._lanes = lanes
+- print ' created %d lanes' % len(lanes)
++ print(' created %d lanes' % len(lanes))
+ # print ' lanes', lanes
+ for laneattrs in lanes:
+ print_attrs(laneattrs)
+ return True
+
+ def make_lanes(self, is_opp=False, n_lane_osm=0):
+- print 'make_lanes', is_opp, n_lane_osm
++ print('make_lanes', is_opp, n_lane_osm)
+ osmattrs = self._osmattrs
+ is_lanes_rigid = False
+
+@@ -1503,7 +1504,7 @@
+ # do busways
+ attrs = self._buswayattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' busways n_lane', attrs['n_lane']
++ print(' busways n_lane', attrs['n_lane'])
+ n_lane_assig = attrs['n_lane']
+ n_lane = len(lanes)
+
+@@ -1518,7 +1519,7 @@
+ # do bikeways
+ attrs = self._bikewayattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' bikeways n_lane', attrs['n_lane']
++ print(' bikeways n_lane', attrs['n_lane'])
+ n_lane_assig = attrs['n_lane']
+ n_lane = len(lanes)
+
+@@ -1541,7 +1542,7 @@
+ attrs = self._sidewalkattrs[ind]
+
+ if attrs['n_lane'] > 0:
+- print ' sidewalks n_lane', attrs['n_lane']
++ print(' sidewalks n_lane', attrs['n_lane'])
+ n_lane_assig = attrs['n_lane']
+ n_lane = len(lanes)
+ # sidewalks are not considered lanes in osm
+@@ -1570,7 +1571,7 @@
+ self._lanes_opp = lanes
+ else:
+ self._lanes = lanes
+- print ' created %d lanes' % len(lanes)
++ print(' created %d lanes' % len(lanes))
+ # print ' lanes', lanes
+ for laneattrs in lanes:
+ print_attrs(laneattrs)
+@@ -1597,7 +1598,7 @@
+ ind = 1
+ lanes = np.array(self._lanes)
+
+- print 'configure_edge', id_edge, net.edges.ids_sumo[id_edge], self.highway, 'is_opp', is_opp, 'n_lanes', len(lanes), 'is_remove_sidewalk', is_remove_sidewalk
++ print('configure_edge', id_edge, net.edges.ids_sumo[id_edge], self.highway, 'is_opp', is_opp, 'n_lanes', len(lanes), 'is_remove_sidewalk', is_remove_sidewalk)
+
+ if self._is_oneway: # & (not self.is_roundabout()):
+ type_spread = 1 # centered
+@@ -1628,11 +1629,11 @@
+ for laneattrs in lanes:
+ # &lanes[-1]['is_sidewalk']:
+ if (ind == 0) & laneattrs['is_sidewalk'] & (is_remove_sidewalk == 2) & (ind_lastlane > 0):
+- print ' sidewalk removed on right side'
++ print(' sidewalk removed on right side')
+ pass
+ # &lanes[0]['is_sidewalk']:
+ elif (ind == ind_lastlane) & laneattrs['is_sidewalk'] & (is_remove_sidewalk == 1) & (ind_lastlane > 0):
+- print ' sidewalk removed on left side'
++ print(' sidewalk removed on left side')
+ pass
+ else:
+ inds_valid.append(ind)
+@@ -1667,12 +1668,12 @@
+ # add lanes
+
+ if n_lane == 0:
+- print 'WARNING: no lane for this direction!!'
+- else:
+- print ' inds_valid', inds_valid
++ print('WARNING: no lane for this direction!!')
++ else:
++ print(' inds_valid', inds_valid)
+ ids_lane = net.lanes.add_rows(n_lane)
+
+- for id_lane, ind_lane, laneattrs in zip(ids_lane, xrange(n_lane), lanes[inds_valid]):
++ for id_lane, ind_lane, laneattrs in zip(ids_lane, range(n_lane), lanes[inds_valid]):
+ if len(laneattrs['ids_modes_allow']) == 0:
+ id_mode_main = self.id_mode
+ else:
+@@ -1753,7 +1754,7 @@
+ return 10
+
+ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
+- print 'make_lanes_rigid', is_opp, n_lane_osm
++ print('make_lanes_rigid', is_opp, n_lane_osm)
+ osmattrs = self._osmattrs
+
+ if is_opp:
+@@ -1777,7 +1778,7 @@
+ attrs = self._buswayattrs[ind]
+
+ if attrs['n_lane'] > 0:
+- print ' busways n_lane', attrs['n_lane']
++ print(' busways n_lane', attrs['n_lane'])
+
+ n_lane = len(lanes)
+
+@@ -1787,7 +1788,7 @@
+
+ n_allow = len(allowed)
+ if n_allow > 0:
+- for i, a, d in zip(xrange(n_allow), allowed, disallowed):
++ for i, a, d in zip(range(n_allow), allowed, disallowed):
+ if ind < n_lane:
+ if a & (i < n_lane):
+ self.set_lane(lanes, attrs, i)
+@@ -1809,7 +1810,7 @@
+ # do bikeways
+ attrs = self._bikewayattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' bikeways n_lane', attrs['n_lane']
++ print(' bikeways n_lane', attrs['n_lane'])
+
+ n_lane = len(lanes)
+
+@@ -1817,7 +1818,7 @@
+
+ n_allow = len(allowed)
+ if n_allow > 0:
+- for i, a, d in zip(xrange(n_allow), allowed, disallowed):
++ for i, a, d in zip(range(n_allow), allowed, disallowed):
+ if i < n_lane:
+ if a & i < n_lane:
+ self.set_lane(lanes, attrs, i)
+@@ -1846,7 +1847,7 @@
+ # do sidewalks
+ attrs = self._sidewalkattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' sidewalks n_lane', attrs['n_lane']
++ print(' sidewalks n_lane', attrs['n_lane'])
+ n_lane_assig = attrs['n_lane']
+ n_lane = len(lanes)
+ # sidewalks are not considered lanes in osm
+@@ -1876,14 +1877,14 @@
+ self._lanes_opp = lanes
+ else:
+ self._lanes = lanes
+- print ' created %d lanes' % len(lanes)
++ print(' created %d lanes' % len(lanes))
+ # print ' lanes', lanes
+ for laneattrs in lanes:
+ print_attrs(laneattrs)
+ return True
+
+ def make_lanes(self, is_opp=False, n_lane_osm=0):
+- print 'make_lanes primary', is_opp, n_lane_osm
++ print('make_lanes primary', is_opp, n_lane_osm)
+ osmattrs = self._osmattrs
+ #is_lanes_rigid = False
+
+@@ -1902,7 +1903,7 @@
+ # do busways
+ attrs = self._buswayattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' busways n_lane', attrs['n_lane']
++ print(' busways n_lane', attrs['n_lane'])
+ n_lane_assig = attrs['n_lane']
+ n_lane = len(lanes)
+
+@@ -1917,7 +1918,7 @@
+ # do bikeways
+ attrs = self._bikewayattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' bikeways n_lane', attrs['n_lane']
++ print(' bikeways n_lane', attrs['n_lane'])
+ n_lane_assig = attrs['n_lane']
+ n_lane = len(lanes)
+
+@@ -1947,7 +1948,7 @@
+ # do sidewalks
+ attrs = self._sidewalkattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' sidewalks n_lane', attrs['n_lane']
++ print(' sidewalks n_lane', attrs['n_lane'])
+ n_lane_assig = attrs['n_lane']
+ n_lane = len(lanes)
+ # sidewalks are not considered lanes in osm
+@@ -1976,7 +1977,7 @@
+ self._lanes_opp = lanes
+ else:
+ self._lanes = lanes
+- print ' created %d lanes' % len(lanes)
++ print(' created %d lanes' % len(lanes))
+ # print ' lanes', lanes
+ for laneattrs in lanes:
+ print_attrs(laneattrs)
+@@ -2025,7 +2026,7 @@
+ return 10
+
+ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
+- print 'make_lanes_rigid', is_opp, n_lane_osm
++ print('make_lanes_rigid', is_opp, n_lane_osm)
+ osmattrs = self._osmattrs
+
+ if is_opp:
+@@ -2048,14 +2049,14 @@
+ self._lanes_opp = lanes
+ else:
+ self._lanes = lanes
+- print ' created %d lanes' % len(lanes)
++ print(' created %d lanes' % len(lanes))
+ # print ' lanes', lanes
+ for laneattrs in lanes:
+ print_attrs(laneattrs)
+ return True
+
+ def make_lanes(self, is_opp=False, n_lane_osm=0):
+- print 'make_lanes primary', is_opp, n_lane_osm
++ print('make_lanes primary', is_opp, n_lane_osm)
+ osmattrs = self._osmattrs
+ #is_lanes_rigid = False
+
+@@ -2078,7 +2079,7 @@
+ self._lanes_opp = lanes
+ else:
+ self._lanes = lanes
+- print ' created %d lanes' % len(lanes)
++ print(' created %d lanes' % len(lanes))
+ # print ' lanes', lanes
+ for laneattrs in lanes:
+ print_attrs(laneattrs)
+@@ -2119,7 +2120,7 @@
+ return 3
+
+ def make_sidewalkattrs(self):
+- print 'make_sidewalkattrs'
++ print('make_sidewalkattrs')
+ self.make_sidewalkattrs_smallroads()
+
+
+@@ -2217,7 +2218,7 @@
+ # but there will be no sidewalk of sidewalk
+
+ def make_bikewayattrs(self):
+- print 'Footpath.make_bikewayattrs'
++ print('Footpath.make_bikewayattrs')
+ osmattrs = self._osmattrs
+ self._bikewayattrs = (deepcopy(LANEATTRS_DEFAULT),
+ deepcopy(LANEATTRS_DEFAULT))
+@@ -2244,7 +2245,7 @@
+ self.make_bikelane(is_opp=False, is_rightside=False, width=width_right)
+
+ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
+- print 'Footpath.make_lanes_rigid ped', is_opp, n_lane_osm
++ print('Footpath.make_lanes_rigid ped', is_opp, n_lane_osm)
+ osmattrs = self._osmattrs
+
+ if is_opp:
+@@ -2273,7 +2274,7 @@
+ attrs = self._buswayattrs[ind]
+
+ if attrs['n_lane'] > 0:
+- print ' busways n_lane', attrs['n_lane']
++ print(' busways n_lane', attrs['n_lane'])
+
+ n_lane = len(lanes)
+
+@@ -2283,7 +2284,7 @@
+
+ n_allow = len(allowed)
+ if n_allow > 0:
+- for i, a, d in zip(xrange(n_allow), allowed, disallowed):
++ for i, a, d in zip(range(n_allow), allowed, disallowed):
+ if ind < n_lane:
+ if a & (i < n_lane):
+ self.set_lane(lanes, attrs, i)
+@@ -2305,7 +2306,7 @@
+ # do bikeways
+ attrs = self._bikewayattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' bikeways n_lane', attrs['n_lane']
++ print(' bikeways n_lane', attrs['n_lane'])
+
+ n_lane = len(lanes)
+
+@@ -2313,7 +2314,7 @@
+
+ n_allow = len(allowed)
+ if n_allow > 0:
+- for i, a, d in zip(xrange(n_allow), allowed, disallowed):
++ for i, a, d in zip(range(n_allow), allowed, disallowed):
+ if i < n_lane:
+ if a & i < n_lane:
+ self.set_lane(lanes, attrs, i)
+@@ -2333,10 +2334,10 @@
+ n_lane_assig -= 1
+
+ def make_lanes(self, is_opp=False, n_lane_osm=0):
+- print 'Footpath.make_lanes', is_opp, n_lane_osm, 'n_bikelane', len(self._bikewayattrs)
++ print('Footpath.make_lanes', is_opp, n_lane_osm, 'n_bikelane', len(self._bikewayattrs))
+ osmattrs = self._osmattrs
+
+- print ' main lane attrs'
++ print(' main lane attrs')
+ print_attrs(self._laneattrs_main)
+
+ if is_opp:
+@@ -2357,7 +2358,7 @@
+ # do busways
+ attrs = self._buswayattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' busways n_lane', attrs['n_lane']
++ print(' busways n_lane', attrs['n_lane'])
+ n_lane_assig = attrs['n_lane']
+ n_lane = len(lanes)
+
+@@ -2371,11 +2372,11 @@
+
+ # do bikeways
+
+- print ' bikewayattrs:'
++ print(' bikewayattrs:')
+ attrs = self._bikewayattrs[ind]
+ print_attrs(attrs)
+ if attrs['n_lane'] > 0:
+- print ' bikeways n_lane', attrs['n_lane']
++ print(' bikeways n_lane', attrs['n_lane'])
+ n_lane_assig = attrs['n_lane']
+ n_lane = len(lanes)
+
+@@ -2399,7 +2400,7 @@
+ else:
+ self._lanes = lanes
+
+- print ' created %d lanes' % len(lanes)
++ print(' created %d lanes' % len(lanes))
+ # print ' lanes', lanes
+ for laneattrs in lanes:
+ print_attrs(laneattrs)
+@@ -2412,7 +2413,7 @@
+ """
+ Make defaults to be overridden
+ """
+- print 'config cycleway'
++ print('config cycleway')
+ # pass here either road type specific defaults
+ # or global defaults from parent process
+
+@@ -2444,7 +2445,7 @@
+ self.ids_modes_disallow = []
+ self.make_speed(self.parent.speed_max_bike)
+
+- print ' ids_modes_allow', self.ids_modes_allow
++ print(' ids_modes_allow', self.ids_modes_allow)
+ #self.speed_max_bus = self.parent.speed_max_bus
+ #self.speed_max_bike = self.parent.speed_max_bike
+ self.speed_max_ped = self.parent.speed_max_ped
+@@ -2479,12 +2480,12 @@
+ pass
+
+ def make_sidewalkattrs(self):
+- print 'make_sidewalkattrs'
++ print('make_sidewalkattrs')
+ # put sidewalks only if sidewalk attributes are given
+ return self.make_sidewalkattrs_largeroads()
+
+ def make_lanes_rigid(self, is_opp=False, n_lane_osm=0):
+- print 'make_lanes_rigid cycle', is_opp, n_lane_osm
++ print('make_lanes_rigid cycle', is_opp, n_lane_osm)
+ osmattrs = self._osmattrs
+
+ if is_opp:
+@@ -2502,7 +2503,7 @@
+ # do sidewalks
+ attrs = self._sidewalkattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' sidewalks n_lane', attrs['n_lane']
++ print(' sidewalks n_lane', attrs['n_lane'])
+ n_lane_assig = attrs['n_lane']
+ n_lane = len(lanes)
+ # sidewalks are not considered lanes in osm
+@@ -2531,14 +2532,14 @@
+ self._lanes_opp = lanes
+ else:
+ self._lanes = lanes
+- print ' created %d lanes' % len(lanes)
++ print(' created %d lanes' % len(lanes))
+ # print ' lanes', lanes
+ for laneattrs in lanes:
+ print_attrs(laneattrs)
+ return True
+
+ def make_lanes(self, is_opp=False, n_lane_osm=0):
+- print 'make_lanes cycle', is_opp, n_lane_osm
++ print('make_lanes cycle', is_opp, n_lane_osm)
+ osmattrs = self._osmattrs
+ is_lanes_rigid = False
+
+@@ -2557,7 +2558,7 @@
+ # do sidewalks
+ attrs = self._sidewalkattrs[ind]
+ if attrs['n_lane'] > 0:
+- print ' sidewalks n_lane', attrs['n_lane']
++ print(' sidewalks n_lane', attrs['n_lane'])
+ n_lane_assig = attrs['n_lane']
+ n_lane = len(lanes)
+ # sidewalks are not considered lanes in osm
+@@ -2586,7 +2587,7 @@
+ self._lanes_opp = lanes
+ else:
+ self._lanes = lanes
+- print ' created %d lanes' % len(lanes)
++ print(' created %d lanes' % len(lanes))
+ # print ' lanes', lanes
+ for laneattrs in lanes:
+ print_attrs(laneattrs)
+@@ -2637,7 +2638,7 @@
+ info='Import of network imported with the help of osmnx.',
+ logger=None, **kwargs):
+
+- print 'OxImporter.__init__'
++ print('OxImporter.__init__')
+
+ self._init_common(ident,
+ parent=scenario,
+@@ -2797,10 +2798,10 @@
+ return self.parent
+
+ def do(self):
+- print self.ident+'.do'
+-
+- print ' osmdatafilepaths', self.osmdatafilepaths
+- print ' nxnetworkpaths', self.nxnetworkpaths
++ print(self.ident+'.do')
++
++ print(' osmdatafilepaths', self.osmdatafilepaths)
++ print(' nxnetworkpaths', self.nxnetworkpaths)
+ net = self.get_scenario().net
+ self._net = net
+ self._map_id_edge_sumo_to_doubles = {}
+@@ -2830,19 +2831,19 @@
+ # {u'lat': 47.6038005, u'type': u'node', u'lon': 7.6006465, u'id': 453208, u'tags': {u'ref': u'69', u'name': u'Weil am Rhein / H\xfcningen', u'highway': u'motorway_junction'}}
+ # print ' parse element',element['id'],element['type']
+ if element['type'] == 'way':
+- if element.has_key('tags'):
++ if 'tags' in element:
+ highway = element['tags'].get('highway', 'road')
+ else:
+ highway = 'road'
+- print ' '+70*'-'
+- print ' way', element['id'], type(element['id']), highway
++ print(' '+70*'-')
++ print(' way', element['id'], type(element['id']), highway)
+ edges_osm[str(element['id'])] = ROADCLASSES.get(highway, Road)(element, self)
+- print ' done with way', element['id'], id(self.edges_osm[str(element['id'])])
++ print(' done with way', element['id'], id(self.edges_osm[str(element['id'])]))
+
+ if element['type'] == 'node':
+ nodes_osm[element['id']] = element.get('tags', {})
+
+- print ' import_osmdata:done'
++ print(' import_osmdata:done')
+
+ # def get_id_edge_sumo(self, osmid):
+ # idmap = self._map_id_edge_sumo_to_doubles
+@@ -2855,7 +2856,7 @@
+
+ def get_edgenumber(self, osmid_dir):
+ idmap = self._map_id_edge_sumo_to_doubles
+- if idmap.has_key(osmid_dir):
++ if osmid_dir in idmap:
+ idmap[osmid_dir] += 1
+ else:
+ idmap[osmid_dir] = 0
+@@ -2879,13 +2880,13 @@
+ def is_edge_eligible(self, id_osm, id_fromnode_sumo, id_tonode_sumo):
+
+ # print 'is_edge_eligible',id_osm,type(id_osm),id_fromnode_sumo, id_tonode_sumo,self.edges_osm.has_key(id_osm),self._edgelookup.has_key(id_osm)
+- if not self.edges_osm.has_key(id_osm):
++ if id_osm not in self.edges_osm:
+ # for some reason, nx network has edges that are not in jason
+ return False
+
+ edgelookup = self._edgelookup
+
+- if edgelookup.has_key(id_osm):
++ if id_osm in edgelookup:
+ # is reverse already in database
+ # print ' check',edgelookup[id_osm], (id_tonode_sumo, id_fromnode_sumo) in edgelookup[id_osm]
+ edgelookup[id_osm].add((id_fromnode_sumo, id_tonode_sumo))
+@@ -2907,7 +2908,7 @@
+ n_edges = len(polylines)
+ inds = np.arange(n_edges)
+ #ids = inds+1
+- print 'make_linevertices', n_edges
++ print('make_linevertices', n_edges)
+
+ linevertices = np.zeros((0, 2, 3), np.float32)
+ vertexinds = np.zeros((0, 2), np.int32)
+@@ -2931,7 +2932,7 @@
+ # print ' =======',n_seg#,polyline
+
+ if n_seg > 1:
+- polyvinds = range(n_seg)
++ polyvinds = list(range(n_seg))
+ # print ' polyvinds\n',polyvinds
+ vi = np.zeros((2*n_seg-2), np.int32)
+ vi[0] = polyvinds[0]
+@@ -3001,7 +3002,7 @@
+ elif d_max is None:
+ dists2_min = np.zeros(n_best, dtype=np.float32)
+ inds_min = np.zeros(n_best, dtype=np.int)
+- for i in xrange(n_best):
++ for i in range(n_best):
+ ind = np.argmin(d2)
+ inds_min[i] = ind
+ dists2_min[i] = d2[ind]
+@@ -3024,7 +3025,7 @@
+ return self._edgeinds[inds_min], np.sqrt(dists2_min), angles[inds_min]
+
+ def configure_sidewalks(self):
+- print 'configure_sidewalks'
++ print('configure_sidewalks')
+ nodes = self._net.nodes
+
+ #are_remove_sidewalk = np.zeros(len(self._are_edge_valid), dtype = np.int32)
+@@ -3044,11 +3045,11 @@
+ for ind, id_edge_osm, shape, id_fromnode, id_tonode in zip(np.arange(len(ids_edge_osm)), ids_edge_osm, self._edgeshapes, ids_fromnode, ids_tonode):
+ road = edges_osm[id_edge_osm]
+ # if road.is_roundabout():# & (len(shape)>2):
+- print ' check edge id_edge_osm', ids_edge_sumo[ind], 'no cycleped', (road.highway not in ['cycleway', 'path', 'pedestrian', 'stairs', 'steps', 'platform']), 'has sidewalk', (road.has_sidewalks(False) | road.has_sidewalks(True))
++ print(' check edge id_edge_osm', ids_edge_sumo[ind], 'no cycleped', (road.highway not in ['cycleway', 'path', 'pedestrian', 'stairs', 'steps', 'platform']), 'has sidewalk', (road.has_sidewalks(False) | road.has_sidewalks(True)))
+ # if (road.has_sidewalks(False)|road.has_sidewalks(True))\
+ # &(road.highway not in ['cycleway','path','pedestrian','stairs','steps','platform']):
+ if 1: # (road.highway not in ['path','pedestrian','stairs','steps','platform','footway']):
+- print ' add_edge', ids_edge_sumo[ind], 'id_fromnode', id_fromnode, 'id_tonode', id_tonode, 'ind', ind
++ print(' add_edge', ids_edge_sumo[ind], 'id_fromnode', id_fromnode, 'id_tonode', id_tonode, 'ind', ind)
+
+ shapearray = np.array(shape, dtype=np.float32)
+ delta_out = shapearray[1]-shapearray[0]
+@@ -3066,13 +3067,13 @@
+ #digraph.add_edge(id_fromnode, id_tonode )
+
+ # print ' graph.nodes()',graph.nodes()
+- for id_fromnode, tonodes in digraph.adj.items():
+- print ' investigate id_fromnode', id_fromnode
++ for id_fromnode, tonodes in list(digraph.adj.items()):
++ print(' investigate id_fromnode', id_fromnode)
+ # dictionary with id_nnode as key and outgoing angle as value
+ # if id_nnode is negative then the direction if from
+ # incoming edge from node -id_nnode
+ directiondata = []
+- for id_tonode, edge in tonodes.items():
++ for id_tonode, edge in list(tonodes.items()):
+ # print ' id_tonode',id_tonode
+ directiondata.append((edge['angle_out'], id_tonode, edge['id_edge_sumo']))
+
+@@ -3085,7 +3086,7 @@
+ node_to_dirind = OrderedDict()
+ i = 0
+ for angle, id_node, id_edge_sumo in directiondata:
+- print ' ', i, 'id_node', id_node, 'angle', angle, 'id_edge_sumo', id_edge_sumo
++ print(' ', i, 'id_node', id_node, 'angle', angle, 'id_edge_sumo', id_edge_sumo)
+ dirind_to_node[i] = id_node
+ node_to_dirind[id_node] = i
+ i += 1
+@@ -3097,8 +3098,8 @@
+ for id_node in list(digraph.nodes_iter()):
+
+ node = digraph.node[id_node]
+- print '\n find loops for node', id_node # ,node['dirind_to_node']
+- for ind, id_nbnode in node['dirind_to_node'].iteritems():
++ print('\n find loops for node', id_node) # ,node['dirind_to_node']
++ for ind, id_nbnode in node['dirind_to_node'].items():
+
+ if id_nbnode < 0:
+ # incoming
+@@ -3126,7 +3127,7 @@
+ are_remove_sidewalk[id_sumo] = 1 # remove sidewalk from left
+
+ else:
+- if are_remove_sidewalk.has_key(id_sumo):
++ if id_sumo in are_remove_sidewalk:
+ pass
+ # if are_remove_sidewalk[id_sumo] == 1:
+ # # let remove from left
+@@ -3137,10 +3138,10 @@
+ else:
+ are_remove_sidewalk[id_sumo] = 2 # remove sidewalk from right
+
+- print ' found edge', id_sumo, id_fromnode, id_tonone, id_node, 'is_remove_sidewalk', are_remove_sidewalk[id_sumo]
++ print(' found edge', id_sumo, id_fromnode, id_tonone, id_node, 'is_remove_sidewalk', are_remove_sidewalk[id_sumo])
+
+ def configure_roundabouts(self):
+- print 'configure_roundabouts'
++ print('configure_roundabouts')
+ nodes = self._net.nodes
+ roundabouts = []
+ edges_osm = self.edges_osm
+@@ -3213,13 +3214,13 @@
+ return id_osm
+
+ def check_consistency(self):
+- print 'check_consistency'
++ print('check_consistency')
+ nodelookup = {}
+
+ for ind, id_fromnode, id_tonode, id_edge_sumo in zip(np.arange(len(self._ids_edge_sumo)), self._ids_fromnode, self._ids_tonode, self._ids_edge_sumo):
+ ids_fromtonode = (id_fromnode, id_tonode)
+- if nodelookup.has_key(ids_fromtonode):
+- print ' WARNING: %s double edge to %s detected' % (id_edge_sumo, nodelookup[ids_fromtonode]), 'from', id_fromnode, 'to', id_tonode, 'id_edge_sumo', id_edge_sumo, nodelookup[ids_fromtonode] == id_edge_sumo
++ if ids_fromtonode in nodelookup:
++ print(' WARNING: %s double edge to %s detected' % (id_edge_sumo, nodelookup[ids_fromtonode]), 'from', id_fromnode, 'to', id_tonode, 'id_edge_sumo', id_edge_sumo, nodelookup[ids_fromtonode] == id_edge_sumo)
+ if nodelookup[ids_fromtonode] == id_edge_sumo:
+ # meand 2 edges with identical ID
+ self._are_edge_valid[ind] = False
+@@ -3247,7 +3248,7 @@
+
+ alpha_crit = 30.0*np.pi/180.0
+ alpha_crit_cross = 30.0*np.pi/180.0
+- print 'configure_footpath alpha_crit', alpha_crit
++ print('configure_footpath alpha_crit', alpha_crit)
+ #self.id_mode = ID_MODE_PED
+ # highway=footway|path
+ #self.highway = self._osmattrs.get('highway','footway')
+@@ -3258,7 +3259,7 @@
+ road = edges_osm[id_edge_osm]
+
+ if road.highway in footpath_condig:
+- print ' check edge', ids_edge_sumo[ind], road.footway, (road.get_osmattr('tunnel') != 'yes'), (length > dist_min_remove), length
++ print(' check edge', ids_edge_sumo[ind], road.footway, (road.get_osmattr('tunnel') != 'yes'), (length > dist_min_remove), length)
+ #(road.footway != 'crossing') (road.footway != 'sidewalk')
+ ids_osm_main = set()
+ is_remove = True
+@@ -3273,16 +3274,16 @@
+ inds_edge_main, dists, angles = self.get_closest_edge_dist(
+ point, ind, n_best=20, d_max=dist_min_detect)
+ #matchdata = {}
+- print ' check sidewalk point (%d/%d)' % (i+1, len(shape))
++ print(' check sidewalk point (%d/%d)' % (i+1, len(shape)))
+ for ind_edge_main, dist, angle in zip(inds_edge_main, dists, angles):
+ id_edge_osm_main, is_opp, nr = self.get_id_edge_osm_from_id_sumo(
+ ids_edge_sumo[ind_edge_main])
+ road_main = edges_osm[id_edge_osm_main]
+ prio = road_main.get_priority(is_opp)
+- print ' check medge %s d=%.1fm al=%.1f' % (ids_edge_sumo[ind_edge_main], dist, angle/np.pi*180), prio, road_main.highway, (angle < alpha_crit), (dist < 2*dist_min_detect), (road_main.highway not in footpath_nomerge)
++ print(' check medge %s d=%.1fm al=%.1f' % (ids_edge_sumo[ind_edge_main], dist, angle/np.pi*180), prio, road_main.highway, (angle < alpha_crit), (dist < 2*dist_min_detect), (road_main.highway not in footpath_nomerge))
+ # print ' p1',shape[i-1],'pc',point,'p2',shape[i]
+ if (angle < 2*alpha_crit) & (dist < dist_min_detect) & (road_main.highway not in footpath_nomerge):
+- print ' add edge main edge %s' % ids_edge_sumo[ind_edge_main], (id_edge_osm_main, is_opp)
++ print(' add edge main edge %s' % ids_edge_sumo[ind_edge_main], (id_edge_osm_main, is_opp))
+ ids_osm_main.add((id_edge_osm_main, is_opp))
+ is_foundmatch = True
+ break
+@@ -3299,16 +3300,16 @@
+ is_foundmatch = False
+ inds_edge_main, dists, angles = self.get_closest_edge_dist(
+ point, ind, n_best=20, d_max=dist_min_detect)
+- print ' check footpath point (%d/%d)' % (i+1, len(shape))
++ print(' check footpath point (%d/%d)' % (i+1, len(shape)))
+ for ind_edge_main, dist, angle in zip(inds_edge_main, dists, angles):
+ id_edge_osm_main, is_opp, nr = self.get_id_edge_osm_from_id_sumo(
+ ids_edge_sumo[ind_edge_main])
+ road_main = edges_osm[id_edge_osm_main]
+ prio = road_main.get_priority(is_opp)
+- print ' check medge %s d=%.1fm al=%.1f,%.2f' % (ids_edge_sumo[ind_edge_main], dist, angle/np.pi*180, angle), prio, road_main.highway, (angle < alpha_crit), (dist < dist_min_detect), (road_main.highway not in footpath_nomerge)
++ print(' check medge %s d=%.1fm al=%.1f,%.2f' % (ids_edge_sumo[ind_edge_main], dist, angle/np.pi*180, angle), prio, road_main.highway, (angle < alpha_crit), (dist < dist_min_detect), (road_main.highway not in footpath_nomerge))
+ # print ' p1',shape[i-1],'pc',point,'p2',shape[i]
+ if (prio <= prio_max) & (angle < alpha_crit) & (dist < dist_min_detect) & (road_main.highway not in footpath_nomerge):
+- print ' add edge main edge %s' % ids_edge_sumo[ind_edge_main], (id_edge_osm_main, is_opp)
++ print(' add edge main edge %s' % ids_edge_sumo[ind_edge_main], (id_edge_osm_main, is_opp))
+ ids_osm_main.add((id_edge_osm_main, is_opp))
+ is_foundmatch = True
+ break
+@@ -3329,17 +3330,17 @@
+ is_foundmatch = False
+ inds_edge_main, dists, angles = self.get_closest_edge_dist(
+ point, ind, n_best=20, d_max=dist_min_detect_cross)
+- print ' check crossing point (%d/%d)' % (i+1, len(shape))
++ print(' check crossing point (%d/%d)' % (i+1, len(shape)))
+ for ind_edge_main, dist, angle in zip(inds_edge_main, dists, angles):
+ id_edge_osm_main, is_opp, nr = self.get_id_edge_osm_from_id_sumo(
+ ids_edge_sumo[ind_edge_main])
+ road_main = edges_osm[id_edge_osm_main]
+ prio = road_main.get_priority(is_opp)
+- print ' check medge %s d=%.1fm al=%.1f' % (ids_edge_sumo[ind_edge_main], dist, angle/np.pi*180), prio, road_main.highway, (angle < alpha_crit_cross), (dist < dist_min_detect_cross), (road_main.highway in footpath_merge_cross)
++ print(' check medge %s d=%.1fm al=%.1f' % (ids_edge_sumo[ind_edge_main], dist, angle/np.pi*180), prio, road_main.highway, (angle < alpha_crit_cross), (dist < dist_min_detect_cross), (road_main.highway in footpath_merge_cross))
+ # print ' p1',shape[i-1],'pc',point,'p2',shape[i]
+ # if (prio<=prio_max)&(((angle '-': # it is not an opposite edge
+ road = edges_osm[id_edge_osm]
+
+- print ' configure way id_edge_osm', id_edge_osm, id_sumo, are_remove_sidewalk.get(id_sumo, 0)
++ print(' configure way id_edge_osm', id_edge_osm, id_sumo, are_remove_sidewalk.get(id_sumo, 0))
+ road.configure_edge(id_edge, net, is_remove_sidewalk=are_remove_sidewalk.get(id_sumo, 0))
+ #id_edge_opp = self.get_id_edge_opp
+ id_sumo_opp = '-'+id_sumo
+ if edges.ids_sumo.has_index(id_sumo_opp):
+- print ' configure opposite way id_edge_osm', id_edge_osm, id_sumo_opp, are_remove_sidewalk.get(id_sumo_opp, 0)
++ print(' configure opposite way id_edge_osm', id_edge_osm, id_sumo_opp, are_remove_sidewalk.get(id_sumo_opp, 0))
+ road.configure_edge(edges.ids_sumo.get_id_from_index(id_sumo_opp),
+ net, is_opp=True,
+ is_remove_sidewalk=are_remove_sidewalk.get(id_sumo_opp, 0))
+--- tools/contributed/sumopy/coremodules/network/osmnx_import.py (original)
++++ tools/contributed/sumopy/coremodules/network/osmnx_import.py (refactored)
+@@ -26,7 +26,7 @@
+ import agilepy.lib_base.xmlman as xm
+
+
+-from netconvert import *
++from .netconvert import *
+ from coremodules.misc.shapeformat import guess_utm_from_coord
+
+
+@@ -36,9 +36,9 @@
+ """
+
+ for id_node_sumo, nbrsdict in graphx.adjacency():
+- print ' id_node_sumo', id_node_sumo
+- for nbr, eattr in nbrsdict.items():
+- print ' nbr, eattr', nbr, eattr
++ print(' id_node_sumo', id_node_sumo)
++ for nbr, eattr in list(nbrsdict.items()):
++ print(' nbr, eattr', nbr, eattr)
+
+ if projparams == "":
+ projparams_target = guess_utm_from_coord()
+@@ -51,7 +51,7 @@
+ info='Import of network imported with the help of osmnx.',
+ logger=None, **kwargs):
+
+- print 'OxImporter.__init__'
++ print('OxImporter.__init__')
+
+ self._init_common(ident,
+ parent=scenario,
+@@ -96,7 +96,7 @@
+ return self.parent
+
+ def do(self):
+- print self.ident+'.do'
++ print(self.ident+'.do')
+
+ net = self.get_scenario().net
+ projparams_target = net.get_projparams()
+--- tools/contributed/sumopy/coremodules/network/publictransportnet.py (original)
++++ tools/contributed/sumopy/coremodules/network/publictransportnet.py (refactored)
+@@ -42,8 +42,8 @@
+
+ except:
+ pyproj = None
+- print 'Some of the functions cannot be executed because module pypro or mpl_toolkits.basemap is missing.'
+- print 'Please install these modules if you want to use it.'
++ print('Some of the functions cannot be executed because module pypro or mpl_toolkits.basemap is missing.')
++ print('Please install these modules if you want to use it.')
+ # print __doc__
+
+
+@@ -52,7 +52,7 @@
+
+ class StopAccessProvider(Process):
+ def __init__(self, net, logger=None, **kwargs):
+- print 'StopAccessProvider.__init__'
++ print('StopAccessProvider.__init__')
+ self._init_common('stopaccessprovider',
+ parent=net,
+ name='Stop access provider',
+@@ -75,7 +75,7 @@
+ #self.ids_modes_tocomplete = set([MODES["pedestrian"], MODES["delivery"], MODES["bus"]])
+
+ def do(self):
+- print 'StopAccessProvider.do'
++ print('StopAccessProvider.do')
+
+ self.provide_access()
+
+@@ -107,21 +107,21 @@
+ # print ' Check access at stop %s lane %d. al='%(id_stop,id_lane)
+ if lanes.get_accesslevel([id_lane], id_mode_ped) == -1:
+ # no pedaccess
+- print ' add ped access at stop %s lane %d, ID edge SUMO "%s".' % (id_stop, id_lane, edges.ids_sumo[id_edge])
++ print(' add ped access at stop %s lane %d, ID edge SUMO "%s".' % (id_stop, id_lane, edges.ids_sumo[id_edge]))
+ lanes.add_access(id_lane, id_mode_ped)
+ n_add_access += 1
+
+ if self.is_bikeaccess:
+ if lanes.get_accesslevel([id_lane], id_mode_bike) == -1:
+- print ' add bike access at stop %s lane %d, ID edge SUMO "%s".' % (id_stop, id_lane, edges.ids_sumo[id_edge])
++ print(' add bike access at stop %s lane %d, ID edge SUMO "%s".' % (id_stop, id_lane, edges.ids_sumo[id_edge]))
+ lanes.add_access(id_lane, id_mode_bike)
+ n_add_access += 1
+
+ else:
+- print 'WARNING: stop %s at edge %d, SUMO ID %s with without access lane.' % (id_stop, id_edge, edges.ids_sumo[id_edge])
++ print('WARNING: stop %s at edge %d, SUMO ID %s with without access lane.' % (id_stop, id_edge, edges.ids_sumo[id_edge]))
+ # return False
+
+- print ' Added access to %d stops' % n_add_access
++ print(' Added access to %d stops' % n_add_access)
+ return True
+
+
+@@ -346,7 +346,7 @@
+ """
+ Export stops to SUMO stop xml file.
+ """
+- print 'export_sumoxml', filepath, len(self)
++ print('export_sumoxml', filepath, len(self))
+ if len(self) == 0:
+ return None
+
+@@ -356,7 +356,7 @@
+ try:
+ fd = open(filepath, 'w')
+ except:
+- print 'WARNING in write_obj_to_xml: could not open', filepath
++ print('WARNING in write_obj_to_xml: could not open', filepath)
+ return False
+ #xmltag, xmltag_item, attrname_id = self.xmltag
+ fd.write('\n' % encoding)
+@@ -375,7 +375,7 @@
+ if filepath is None:
+ filepath = self.get_stopfilepath()
+
+- print 'import_sumostops %s ' % (filepath,)
++ print('import_sumostops %s ' % (filepath,))
+
+ fd = open(filepath, 'r')
+
+@@ -388,7 +388,7 @@
+ os.remove(filepath)
+
+ except KeyError:
+- print >> sys.stderr, "Error: Problems with reading file %s" % filepath
++ print("Error: Problems with reading file %s" % filepath, file=sys.stderr)
+ raise
+
+ def update_centroids(self):
+@@ -431,12 +431,12 @@
+ id_lane = self._get_id_lane_from_sumoinfo(id_edge_sumo, int(ind_lane_str.strip()))
+ if id_lane != -1:
+
+- if attrs.has_key('startPos'):
++ if 'startPos' in attrs:
+ pos_from = float(attrs['startPos'])
+ else:
+ pos_from = None
+
+- if attrs.has_key('endPos'):
++ if 'endPos' in attrs:
+ pos_to = float(attrs['endPos'])
+ else:
+ pos_to = None
+@@ -462,4 +462,4 @@
+ )
+
+ else:
+- print 'WARNING in StopReader: stop %s has non-existant lane %s' % (id_stop, attrs['lane'])
++ print('WARNING in StopReader: stop %s has non-existant lane %s' % (id_stop, attrs['lane']))
+--- tools/contributed/sumopy/coremodules/network/publictransportnet_wxgui.py (original)
++++ tools/contributed/sumopy/coremodules/network/publictransportnet_wxgui.py (refactored)
+@@ -24,8 +24,8 @@
+ from agilepy.lib_wx.objpanel import ObjPanel
+ from agilepy.lib_base.processes import Process
+ from agilepy.lib_wx.processdialog import ProcessDialog
+-from network import SumoIdsConf, MODES
+-import publictransportnet as pt
++from .network import SumoIdsConf, MODES
++from . import publictransportnet as pt
+
+
+ class PtStopDrawings(Rectangles):
+@@ -300,7 +300,7 @@
+ # Finally, if the directory is changed in the process of getting files, this
+ # dialog is set up to change the current working directory to the path chosen.
+ defaultfilepath = self._net.ptstops.get_stopfilepath()
+- print ' defaultfilepath', defaultfilepath
++ print(' defaultfilepath', defaultfilepath)
+
+ dlg = wx.FileDialog(
+ self._mainframe, message="Open stops XML file",
+@@ -357,11 +357,11 @@
+ # print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL
+ # print ' status =',dlg.get_status()
+ if dlg.get_status() != 'success': # val == wx.ID_CANCEL:
+- print ">>>>>>>>>Unsuccessful\n"
++ print(">>>>>>>>>Unsuccessful\n")
+ dlg.Destroy()
+
+ if dlg.get_status() == 'success':
+- print ">>>>>>>>>successful\n"
++ print(">>>>>>>>>successful\n")
+ # apply current widget values to scenario instance
+ dlg.apply()
+ dlg.Destroy()
+--- tools/contributed/sumopy/coremodules/network/routing.py (original)
++++ tools/contributed/sumopy/coremodules/network/routing.py (refactored)
+@@ -41,7 +41,7 @@
+ def smallest(self):
+ '''Find smallest item after removing deleted items from heap.'''
+ if len(self) == 0:
+- raise IndexError, "smallest of empty priorityDictionary"
++ raise IndexError("smallest of empty priorityDictionary")
+ heap = self.__heap
+ while heap[0][1] not in self or self[heap[0][1]] != heap[0][0]:
+ lastItem = heap.pop()
+@@ -74,7 +74,7 @@
+ dict.__setitem__(self, key, val)
+ heap = self.__heap
+ if len(heap) > 2 * len(self):
+- self.__heap = [(v, k) for k, v in self.iteritems()]
++ self.__heap = [(v, k) for k, v in self.items()]
+ self.__heap.sort() # builtin sort likely faster than O(n) heapify
+ else:
+ newPair = (val, key)
+@@ -92,7 +92,7 @@
+ return self[key]
+
+ def update(self, other):
+- for key in other.keys():
++ for key in list(other.keys()):
+ self[key] = other[key]
+
+
+@@ -150,7 +150,7 @@
+ # est.dist. of non-final vert.
+
+ if np.isnan(weights[id_edge_start]):
+- print ' no access id_edge_start, weights', id_edge_start, weights[id_edge_start]
++ print(' no access id_edge_start, weights', id_edge_start, weights[id_edge_start])
+ return ([], {}, {})
+
+ Q = priorityDictionary()
+@@ -166,9 +166,9 @@
+ # print ' toedge',e,'ids_bedge',bstar[e]
+ # print ' D=',D
+ # print ' Q=',Q
+- if not bstar.has_key(e):
+- print 'WARNING in edgedijkstra: bstar has no edge', e
+- print 'routes = \n', P
++ if e not in bstar:
++ print('WARNING in edgedijkstra: bstar has no edge', e)
++ print('routes = \n', P)
+ return ([], None, P)
+
+ for id_edge in bstar[e]:
+@@ -183,7 +183,7 @@
+ newstate += 'Q|'
+- print ' id_bedge', id_edge, 'w=%.2f,w_tot=%.2f' % (weights[id_edge], weight_tot), weights[id_edge] >= 0, D[e] + weights[id_edge] < cost_limit, id_edge not in D, (id_edge not in Q or weight_tot < Q[id_edge]), newstate
++ print(' id_bedge', id_edge, 'w=%.2f,w_tot=%.2f' % (weights[id_edge], weight_tot), weights[id_edge] >= 0, D[e] + weights[id_edge] < cost_limit, id_edge not in D, (id_edge not in Q or weight_tot < Q[id_edge]), newstate)
+
+ if not np.isnan(weights[id_edge]): # edge accessible?
+ weight_tot = D[e] + weights[id_edge]
+@@ -213,8 +213,8 @@
+ ids_orig = []
+ ids_edge = [id_edge_dest]
+ is_cont = True
+- ids_edge_from = np.array(tree.keys(), dtype=np.int32)
+- ids_edge_to = np.array(tree.values(), dtype=np.int32)
++ ids_edge_from = np.array(list(tree.keys()), dtype=np.int32)
++ ids_edge_to = np.array(list(tree.values()), dtype=np.int32)
+ if id_edge_dest not in ids_edge_to:
+ return ids_orig
+ while len(ids_edge) > 0:
+@@ -252,7 +252,7 @@
+ # est.dist. of non-final vert.
+
+ if np.isnan(weights[id_edge_start]):
+- print ' WARNING in edgedijkstra: no access id_edge_start, weights', id_edge_start, weights[id_edge_start]
++ print(' WARNING in edgedijkstra: no access id_edge_start, weights', id_edge_start, weights[id_edge_start])
+ return ({}, {})
+
+ Q = priorityDictionary()
+@@ -265,9 +265,9 @@
+ ids_target.discard(e)
+ if len(ids_target) == 0:
+ return (D, P)
+- if not fstar.has_key(e):
+- print 'WARNING in edgedijkstra: fstar has no edge', e
+- print 'routes = \n', P
++ if e not in fstar:
++ print('WARNING in edgedijkstra: fstar has no edge', e)
++ print('routes = \n', P)
+ return (None, P)
+ for id_edge in fstar[e]:
+ if not np.isnan(weights[id_edge]): # edge accessible?
+@@ -292,7 +292,7 @@
+ routes = []
+ costs = []
+ for id_targetedge in ids_targetedge:
+- if P.has_key(id_targetedge):
++ if id_targetedge in P:
+ route = [id_targetedge]
+ e = id_targetedge
+ while e != id_rootedge:
+@@ -324,7 +324,7 @@
+ weights=weights, fstar=fstar)
+
+ route = [id_targetedge]
+- if not P.has_key(id_targetedge):
++ if id_targetedge not in P:
+ return 0.0, []
+
+ e = id_targetedge
+@@ -347,7 +347,7 @@
+ # print 'getMinCostRoute node_start=%s, edge_end =%s node_end=%s'%(rootnode.getID(),P[targetnode].getID(),targetnode.getID())
+ id_node = id_targetnode
+ route = []
+- if not P.has_key(id_targetnode):
++ if id_targetnode not in P:
+ return 0.0, []
+
+ while id_node != id_rootnode:
+@@ -615,11 +615,11 @@
+ # print 'SumonetImporter.do',cml
+ self.run_cml(cml)
+ if self.status == 'success':
+- print ' Routing done.'
++ print(' Routing done.')
+ if os.path.isfile(self.outfilepath):
+ # print ' outfile exists, start importing routes'
+ if self.is_update_current_routes:
+- print ' update current routes'
++ print(' update current routes')
+ self._trips.import_routes_xml(self.outfilepath,
+ is_clear_trips=False,
+ is_generate_ids=False,
+@@ -627,7 +627,7 @@
+ is_add=False
+ )
+ else:
+- print ' create route alternatives'
++ print(' create route alternatives')
+ self._trips.import_routes_xml(self.outfilepath,
+ is_clear_trips=False,
+ is_generate_ids=True,
+@@ -645,7 +645,7 @@
+ is_export_net=True,
+ logger=None,
+ **kwargs):
+- print 'DuaRouter.__init__ net, trips', net, trips
++ print('DuaRouter.__init__ net, trips', net, trips)
+ self.init_tripsrouter('duarouter', net, # net becomes parent
+ trips,
+ outfilepath=outfilepath,
+@@ -662,7 +662,7 @@
+
+ else:
+ self.is_export_trips = False
+- print ' tripfilepaths', tripfilepaths
++ print(' tripfilepaths', tripfilepaths)
+ if tripfilepaths is not None:
+ self.add_option('tripfilepaths', tripfilepaths,
+ groupnames=['_private'],
+@@ -1075,7 +1075,7 @@
+ """
+ Imports simulation resuts into results object.
+ """
+- print 'import_results of marouter'
++ print('import_results of marouter')
+
+ if results is None:
+ results = self._results
+--- tools/contributed/sumopy/coremodules/network/wxgui.py (original)
++++ tools/contributed/sumopy/coremodules/network/wxgui.py (refactored)
+@@ -23,16 +23,16 @@
+ from agilepy.lib_wx.processdialog import ProcessDialog
+
+
+-import network
+-import routing
+-import netgenerate
+-import netconvert
+-import networktools
+-import networkxtools # IS_NX = True if available
+-
+-
+-from publictransportnet_wxgui import PtWxGuiMixin
+-from network_editor import *
++from . import network
++from . import routing
++from . import netgenerate
++from . import netconvert
++from . import networktools
++from . import networkxtools # IS_NX = True if available
++
++
++from .publictransportnet_wxgui import PtWxGuiMixin
++from .network_editor import *
+ from coremodules.misc import shapeformat
+
+ from coremodules.misc.matplottools import *
+@@ -399,14 +399,14 @@
+ def on_test_routing(self, event=None):
+ D, P = routing.dijkstra(54, self._net.nodes, self._net.edges, set([42, 82]))
+ cost, route = routing.get_mincostroute_node2node(54, 42, D, P, self._net.edges)
+- print ' route:', route
+- print ' cost', cost
+- print ' firstnode, lastnode', self._net.edges.ids_fromnode[route[0]], self._net.edges.ids_tonode[route[-1]]
++ print(' route:', route)
++ print(' cost', cost)
++ print(' firstnode, lastnode', self._net.edges.ids_fromnode[route[0]], self._net.edges.ids_tonode[route[-1]])
+
+ D, P = routing.edgedijkstra(29, self._net.nodes, self._net.edges, set([106, 82]))
+ cost, route = routing.get_mincostroute_edge2edge(29, 82, D, P)
+- print ' route:', route
+- print ' cost', cost
++ print(' route:', route)
++ print(' cost', cost)
+ # print ' firstnode, lastnode',self._net.edges.ids_fromnode[route[0]],self._net.edges.ids_tonode[route[-1]]
+
+ def on_clean_codes(self, event=None):
+@@ -804,7 +804,7 @@
+ self._mainframe.refresh_moduleguis()
+
+ def on_export_sumonet(self, event=None):
+- print 'on_export_sumonet'
++ print('on_export_sumonet')
+ if self._net.parent is not None:
+ rootname = self._net.parent.get_rootfilename()
+ rootdirpath = self._net.parent.get_workdirpath()
+@@ -854,7 +854,7 @@
+ """
+ Export Network nodes data to shape file.
+ """
+- print 'on_nodes_to_shapefile'
++ print('on_nodes_to_shapefile')
+
+ dirpath = self._net.parent.get_workdirpath()
+ defaultFile = self._net.parent.get_rootfilename()+'.nodes.shp'
+--- tools/contributed/sumopy/coremodules/scenario/__init__.py (original)
++++ tools/contributed/sumopy/coremodules/scenario/__init__.py (refactored)
+@@ -18,12 +18,12 @@
+
+ __version__ = "0.0"
+
+-print 'init', __name__
++print('init', __name__)
+
+
+ def get_wxgui():
+ # try:
+- from wxgui import WxGui
++ from .wxgui import WxGui
+ return WxGui(__name__)
+ # except:
+ # return None
+--- tools/contributed/sumopy/coremodules/scenario/scenario.py (original)
++++ tools/contributed/sumopy/coremodules/scenario/scenario.py (refactored)
+@@ -222,7 +222,7 @@
+ self._init_attributes()
+
+ def _init_attributes(self):
+- print 'Scenario._init_attributes' # ,dir(self)
++ print('Scenario._init_attributes') # ,dir(self)
+
+ attrsman = self.get_attrsman()
+ self.simulation = attrsman.add(cm.ObjConf(simulation.Simulation(self)))
+@@ -288,7 +288,7 @@
+ try:
+ self.demand.import_xml(self.get_rootfilename(), self.get_workdirpath())
+ except:
+- print 'WARNING: import of demand data failed. Please check for inconsistency with trip/route and network edge IDs.'
++ print('WARNING: import of demand data failed. Please check for inconsistency with trip/route and network edge IDs.')
+
+ def update_netoffset(self, deltaoffset):
+ """
+--- tools/contributed/sumopy/coremodules/scenario/wxgui.py (original)
++++ tools/contributed/sumopy/coremodules/scenario/wxgui.py (refactored)
+@@ -25,7 +25,7 @@
+ from agilepy.lib_wx.modulegui import ModuleGui
+ from agilepy.lib_wx.processdialog import ProcessDialog
+
+-import scenario
++from . import scenario
+
+
+ class WxGui(ModuleGui):
+--- tools/contributed/sumopy/coremodules/simulation/__init__.py (original)
++++ tools/contributed/sumopy/coremodules/simulation/__init__.py (refactored)
+@@ -18,12 +18,12 @@
+
+ __version__ = "0.0"
+
+-print 'init', __name__
++print('init', __name__)
+
+
+ def get_wxgui():
+ # try:
+- from wxgui import WxGui
++ from .wxgui import WxGui
+ return WxGui(__name__)
+ # except:
+ # return None
+--- tools/contributed/sumopy/coremodules/simulation/result_oglviewer.py (original)
++++ tools/contributed/sumopy/coremodules/simulation/result_oglviewer.py (refactored)
+@@ -323,7 +323,7 @@
+ edgeresults = results.edgeresults
+ attrnames_edgeresults = OrderedDict()
+ edgeresultattrconfigs = edgeresults.get_group_attrs('results')
+- edgeresultattrnames = edgeresultattrconfigs.keys()
++ edgeresultattrnames = list(edgeresultattrconfigs.keys())
+ # edgeresultattrnames.sort()
+ for attrname in edgeresultattrnames:
+ attrconfig = edgeresultattrconfigs[attrname]
+@@ -728,7 +728,7 @@
+ Called by tool.
+ """
+ self.resultsattr = getattr(self._edgeresults, attrname)
+- print 'configure', self.resultsattr.attrname, is_widthvalue, is_colorvalue
++ print('configure', self.resultsattr.attrname, is_widthvalue, is_colorvalue)
+ # used for normalization
+ if len(self.resultsattr.get_value()) == 0:
+ return
+@@ -796,7 +796,7 @@
+ is_menu=False, # create menu items
+ Debug=0,
+ ):
+- print 'Resultviewer.__init__ parent', parent
++ print('Resultviewer.__init__ parent', parent)
+ self._drawing = None
+ self.prefix_anim = 'anim_'
+ self.layer_anim = 1000.0
+--- tools/contributed/sumopy/coremodules/simulation/results.py (original)
++++ tools/contributed/sumopy/coremodules/simulation/results.py (refactored)
+@@ -303,43 +303,43 @@
+ elif routeresults.ids_ptline[trip] > 0:
+ mode = self._edges.parent.modes.names[self._trips.parent.vtypes.ids_mode[self._trips.parent.ptlines.ids_vtype[routeresults.ids_ptline[trip]]]]
+ else:
+- print 'WARNING: there is a not considered route typology'
++ print('WARNING: there is a not considered route typology')
+ modes_tot.append(mode)
+
+- print 'n route', len(modes_tot)
++ print('n route', len(modes_tot))
+ if len(modes_tot) != len(ids_edges):
+- print 'WARNING: modes and ids_edges have a different length - total flow'
+- print 'n car routes', len(modes_car)
++ print('WARNING: modes and ids_edges have a different length - total flow')
++ print('n car routes', len(modes_car))
+ if len(modes_car) != len(ids_edges_car):
+- print 'WARNING: modes and ids_edges have a different length - car'
+- print 'n bike routes', len(modes_bike)
++ print('WARNING: modes and ids_edges have a different length - car')
++ print('n bike routes', len(modes_bike))
+ if len(modes_bike) != len(ids_edges_bike):
+- print 'WARNING: modes and ids_edges have a different length - bike'
+- print 'n moto routes', len(modes_moto)
++ print('WARNING: modes and ids_edges have a different length - bike')
++ print('n moto routes', len(modes_moto))
+ if len(modes_moto) != len(ids_edges_moto):
+- print 'WARNING: modes and ids_edges have a different length - moto'
+- print 'n od routes', len(modes_od)
++ print('WARNING: modes and ids_edges have a different length - moto')
++ print('n od routes', len(modes_od))
+ if len(modes_od) != len(ids_edges_od):
+- print 'WARNING: modes and ids_edges have a different length - od'
+- print 'n od car routes', modes_od.count('passenger')
+- print 'n od taxi routes', modes_od.count('taxi')
+- print 'n od bike routes', modes_od.count('bicycle')
+- print 'n od moto routes', modes_od.count('motorcycle')
+- print 'n vp routes', len(modes_vp)
++ print('WARNING: modes and ids_edges have a different length - od')
++ print('n od car routes', modes_od.count('passenger'))
++ print('n od taxi routes', modes_od.count('taxi'))
++ print('n od bike routes', modes_od.count('bicycle'))
++ print('n od moto routes', modes_od.count('motorcycle'))
++ print('n vp routes', len(modes_vp))
+ if len(modes_vp) != len(ids_edges_vp):
+- print 'WARNING: modes and ids_edges have a different length - vp'
+- print 'n iauto routes', len(modes_iauto)
++ print('WARNING: modes and ids_edges have a different length - vp')
++ print('n iauto routes', len(modes_iauto))
+ if len(modes_iauto) != len(ids_edges_iauto):
+- print 'WARNING: modes and ids_edges have a different length - iauto'
+- print 'n ibike routes', len(modes_ibike)
++ print('WARNING: modes and ids_edges have a different length - iauto')
++ print('n ibike routes', len(modes_ibike))
+ if len(modes_ibike) != len(ids_edges_ibike):
+- print 'WARNING: modes and ids_edges have a different length - ibike'
+- print 'n imoto routes', len(modes_imoto)
++ print('WARNING: modes and ids_edges have a different length - ibike')
++ print('n imoto routes', len(modes_imoto))
+ if len(modes_imoto) != len(ids_edges_imoto):
+- print 'WARNING: modes and ids_edges have a different length - imoto'
+- print 'n pt routes', len(modes_ptline)
++ print('WARNING: modes and ids_edges have a different length - imoto')
++ print('n pt routes', len(modes_ptline))
+ if len(modes_ptline) != len(ids_edges_ptline):
+- print 'WARNING: modes and ids_edges have a different length - bus'
++ print('WARNING: modes and ids_edges have a different length - bus')
+
+ ids_connections_tot, flows_tot = self.evaluate_connection_flows('tot', modes_tot, ids_edges)
+ self.add_rows(ids_connection=ids_connections_tot, total_flows=flows_tot)
+@@ -389,7 +389,7 @@
+ the available maneuvers, between the connections allowed for the specific MODE.
+ Return both the traveled connections and the related flows
+ '''
+- print 'analyzing', ident, 'routes'
++ print('analyzing', ident, 'routes')
+ edges = self._edges
+ lanes = edges.parent.lanes
+ connections = edges.parent.connections
+@@ -451,9 +451,9 @@
+ connections_list.append(element)
+
+ if connections_list == []:
+- print 'Warning: no connections between a couple of successive edges for mode', mode
+- print 'ids_lane_from_all', ids_lane_from_all
+- print 'ids_lane_to_all', ids_lane_to_all
++ print('Warning: no connections between a couple of successive edges for mode', mode)
++ print('ids_lane_from_all', ids_lane_from_all)
++ print('ids_lane_to_all', ids_lane_to_all)
+ n_wrong_connections += 1
+ if mode == 'motorcycle':
+ n_wrong_connections_moto += 1
+@@ -477,7 +477,7 @@
+ elif mode == 'taxi':
+ keep_right = self._is_keep_right_taxi
+ else:
+- print 'WARNING - Not recognized mode'
++ print('WARNING - Not recognized mode')
+ keep_right = True
+
+ n_good_connections += 1
+@@ -495,8 +495,8 @@
+ ids_traveled_connections.append(connection)
+ connection_flows[connection] += 1.
+ # print ids_traveled_connections, connection_flows[ids_traveled_connections]
+- print 'n_good_connections:', n_good_connections
+- print 'n_wrong_connections:', n_wrong_connections
++ print('n_good_connections:', n_good_connections)
++ print('n_wrong_connections:', n_wrong_connections)
+ # print 'n_wrong_connections_moto:', n_wrong_connections_moto
+ # print 'n_wrong_connections_auto:', n_wrong_connections_auto
+ # print 'n_wrong_connections_bike:', n_wrong_connections_bike
+@@ -595,7 +595,7 @@
+ 'default': 0.0, 'info': 'Arrival speed', 'groupnames': ['routedata']}),
+ ])
+
+- for attrname, kwargs in attrinfos.iteritems():
++ for attrname, kwargs in attrinfos.items():
+ self.add_resultattr(attrname, **kwargs)
+
+ # this is special for route info
+@@ -611,7 +611,7 @@
+ # default cannot be kwarg
+ default = kwargs['default']
+ del kwargs['default']
+- if kwargs.has_key('groupnames'):
++ if 'groupnames' in kwargs:
+ kwargs['groupnames'].append('results')
+ else:
+ kwargs['groupnames'] = ['results']
+@@ -628,7 +628,7 @@
+
+ def import_xml(self, sumo, datapaths):
+ datapathkey = self.datapathkey.get_value()
+- if datapaths.has_key(datapathkey):
++ if datapathkey in datapaths:
+ self.import_sumoxml(datapaths[datapathkey], sumo, self.get_group('routedata'))
+
+ def import_sumoxml(self, filepath, sumo, attrconfigs):
+@@ -674,13 +674,13 @@
+ attrname = attrconfig.attrname
+ if attrname != 'ids_sumo':
+ default = attrconfig.get_default()
+- if type(default) in (types.IntType, types.LongType):
++ if type(default) in (int, int):
+ conversion = 'i' # int
+ values_attr = np.zeros(n, int)
+- elif type(default) in (types.FloatType, types.ComplexType):
++ elif type(default) in (float, complex):
+ conversion = 'f' # float
+ values_attr = np.zeros(n, dtype=np.float32)
+- if type(default) in (types.BooleanType,):
++ if type(default) in (bool,):
+ conversion = 'b' # str
+ values_attr = np.zeros(n, dtype=np.bool)
+ else:
+@@ -774,7 +774,7 @@
+ #('speeds_av', {'name':'Average speeds', 'xmltag':'speed', 'unit':'m/s', 'default':0, 'info':'Average speed','groupnames':['tripdata'],'is_average' : True}),
+ ])
+
+- for attrname, kwargs in attrinfos.iteritems():
++ for attrname, kwargs in attrinfos.items():
+ self.add_resultattr(attrname, **kwargs)
+
+ # this is special for route info
+@@ -793,7 +793,7 @@
+ # default cannot be kwarg
+ default = kwargs['default']
+ del kwargs['default']
+- if kwargs.has_key('groupnames'):
++ if 'groupnames' in kwargs:
+ kwargs['groupnames'].append('results')
+ else:
+ kwargs['groupnames'] = ['results']
+@@ -809,9 +809,9 @@
+ # self.import_sumoxml(filepath,self.get_group('tripdata'))
+
+ def import_xml(self, sumo, datapaths):
+- print 'Tripresults.import_xml datapaths', datapaths
++ print('Tripresults.import_xml datapaths', datapaths)
+ datapathkey = 'tripdatapath'
+- if datapaths.has_key(datapathkey):
++ if datapathkey in datapaths:
+ self.import_tripdata_sumoxml(datapaths[datapathkey], sumo)
+
+ #datapathkey = 'electricenergypath'
+@@ -820,7 +820,7 @@
+
+ def import_electricenergy_sumoxml_broke(self, filepath, sumo):
+ element = 'vehicle'
+- print 'Tripresults.import_electricenergy_sumoxml', self.get_trips().ident, element, filepath
++ print('Tripresults.import_electricenergy_sumoxml', self.get_trips().ident, element, filepath)
+ #id_type = 'edge',
+ #reader = 'interval',
+ attrconfigs = self.get_group('electricenergydata')
+@@ -859,10 +859,10 @@
+ attrname = attrconfig.attrname
+
+ default = attrconfig.get_default()
+- if type(default) in (types.IntType, types.LongType):
++ if type(default) in (int, int):
+ conversion = 'i' # int
+ values_attr = np.zeros(n, int)
+- elif type(default) in (types.FloatType, types.ComplexType):
++ elif type(default) in (float, complex):
+ conversion = 'f' # float
+ values_attr = np.zeros(n, float)
+ else:
+@@ -897,7 +897,7 @@
+
+ def import_tripdata_sumoxml(self, filepath, sumo):
+ element = 'tripinfo'
+- print 'Tripresults.import_tripdata_sumoxml', self.get_trips().ident, 'element', element, filepath
++ print('Tripresults.import_tripdata_sumoxml', self.get_trips().ident, 'element', element, filepath)
+ #id_type = 'edge',
+ #reader = 'interval',
+ attrconfigs = self.get_group('tripdata')
+@@ -924,13 +924,13 @@
+ for attrconfig in attrconfigs:
+ attrname = attrconfig.attrname
+ default = attrconfig.get_default()
+- if type(default) in (types.IntType, types.LongType):
++ if type(default) in (int, int):
+ conversion = 'i' # int
+ values_attr = np.zeros(n, int)
+- elif type(default) in (types.FloatType, types.ComplexType):
++ elif type(default) in (float, complex):
+ conversion = 'f' # float
+ values_attr = np.zeros(n, dtype=np.float32)
+- if type(default) in (types.BooleanType,):
++ if type(default) in (bool,):
+ conversion = 'b' # str
+ values_attr = np.zeros(n, dtype=np.bool)
+ else:
+@@ -1065,7 +1065,7 @@
+ #
+ ])
+
+- for attrname, kwargs in attrinfos.iteritems():
++ for attrname, kwargs in attrinfos.items():
+ self.add_resultattr(attrname, **kwargs)
+
+ def add_resultattr(self, attrname, **kwargs):
+@@ -1073,7 +1073,7 @@
+ # default cannot be kwarg
+ default = kwargs['default']
+ del kwargs['default']
+- if kwargs.has_key('groupnames'):
++ if 'groupnames' in kwargs:
+ kwargs['groupnames'].append('results')
+ else:
+ kwargs['groupnames'] = ['results']
+@@ -1110,7 +1110,7 @@
+ """
+ Keep only results of edges that belong to zone id_zone
+ """
+- print 'filter_zoneedges', ids_zone
++ print('filter_zoneedges', ids_zone)
+
+ zones = self.parent.parent.parent.landuse.zones
+ ids_zoneedge = set()
+@@ -1122,7 +1122,7 @@
+
+ ids_res = self.get_ids()
+ inds = np.zeros(len(ids_res), dtype=np.bool)
+- for i, id_res, id_edge in zip(xrange(len(ids_res)), ids_res, self.ids_edge[ids_res]):
++ for i, id_res, id_edge in zip(range(len(ids_res)), ids_res, self.ids_edge[ids_res]):
+ inds[i] = id_edge in ids_zoneedge
+ if not is_invert:
+ inds = np.logical_not(inds)
+@@ -1130,7 +1130,7 @@
+ self.del_rows(ids_res[inds])
+
+ def import_edgedata(self, sumo, filepath):
+- print 'import_edgedata', filepath
++ print('import_edgedata', filepath)
+ # print ' group',self.get_group('edgedata')
+ #attrnames_data = ['entered','left','arrived','departed']
+ #attrnames_averaged = ['traveltime','density','waitingTime','speed',]
+@@ -1242,11 +1242,11 @@
+ return True
+
+ def import_edgenoise(self, sumo, filepath):
+- print 'import_edgenoise', filepath
++ print('import_edgenoise', filepath)
+ self.import_sumoxml(filepath, sumo, self.get_group('edgenoise'))
+
+ def import_edgeemissions(self, sumo, filepath):
+- print 'import_edgeemissions', filepath
++ print('import_edgeemissions', filepath)
+ #attrnames_data = ['fuel_abs','CO_abs','CO2_abs','NOx_abs','PMx_abs']
+ #attrnames_averaged = ['fuel_normed','CO_normed','CO2_normed',]
+ self.import_sumoxml(filepath, sumo, self.get_group('edgeemissions'))
+@@ -1288,10 +1288,10 @@
+ attrname = attrconfig.attrname
+
+ default = attrconfig.get_default()
+- if type(default) in (types.IntType, types.LongType):
++ if type(default) in (int, int):
+ conversion = 'i' # int
+ values_attr = np.zeros(n, int)
+- elif type(default) in (types.FloatType, types.ComplexType):
++ elif type(default) in (float, complex):
+ conversion = 'f' # float
+ values_attr = np.zeros(n, float)
+ else:
+@@ -1355,7 +1355,7 @@
+ }),
+ ])
+
+- for attrname, kwargs in attrinfos.iteritems():
++ for attrname, kwargs in attrinfos.items():
+ self.add_resultattr(attrname, **kwargs)
+
+ attrconfigs = self.get_group('marouter')
+@@ -1365,7 +1365,7 @@
+
+ class EdgeresultFilter(Process):
+ def __init__(self, edgeresults, logger=None, **kwargs):
+- print 'EdgeresultFilter.__init__'
++ print('EdgeresultFilter.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -1382,7 +1382,7 @@
+ zonechoices = {}
+ for id_zone, name_zone in zip(ids_zone, zones.ids_sumo[ids_zone]):
+ zonechoices[name_zone] = id_zone
+- print ' zonechoices', zonechoices
++ print(' zonechoices', zonechoices)
+ # make for each possible pattern a field for prob
+ # if len(zonechoices) > 0:
+ self.ids_zone = attrsman.add(cm.ListConf('ids_zone', [],
+@@ -1408,7 +1408,7 @@
+ ))
+
+ def do(self):
+- print 'EdgeresultFilter'
++ print('EdgeresultFilter')
+ # links
+ edgeresults = self.parent
+ edgeresults.filter_zoneedges(self.ids_zone, self.is_invert)
+@@ -1477,13 +1477,13 @@
+
+ def import_xml(self, sumo, datapaths):
+ datapathkey = self.datapathkey.get_value()
+- print 'TrajectoryResults.import_xml datapathkey', datapathkey, datapaths.has_key(datapathkey)
+- if datapaths.has_key(datapathkey):
++ print('TrajectoryResults.import_xml datapathkey', datapathkey, datapathkey in datapaths)
++ if datapathkey in datapaths:
+ self.import_trajectories_sumoxml(datapaths[datapathkey], sumo)
+
+ def import_trajectories_sumoxml(self, filepath, sumo):
+ element = 'vehicle'
+- print 'TrajectoryResults.import_trajectories_sumoxml', element, filepath
++ print('TrajectoryResults.import_trajectories_sumoxml', element, filepath)
+
+ ids_sumo, times, trajectories, angles, speeds = read_trajectories(
+ filepath, sumo, element)
+@@ -1499,15 +1499,15 @@
+ def print_trajectories(self):
+ ids_res = self.get_ids()
+ times = self.times.get_value()
+- for i, t in zip(xrange(len(times)), times):
+- print 79*'-'
+- print 'time=', t, 's', len(times)
++ for i, t in zip(range(len(times)), times):
++ print(79*'-')
++ print('time=', t, 's', len(times))
+ for id_res, id_sumo_veh, traj, a, v in zip(ids_res, self.ids_sumo[ids_res], self.trajectories[ids_res], self.angles[ids_res], self.speeds[ids_res]):
+ # print ' id_sumo_veh',id_sumo_veh,id_res
+ # print ' v',v[i]
+ # print ' traj',traj[i]
+ # print ' a',a[i]
+- print ' id_sumo_veh', id_sumo_veh, ': (x,y)', traj[i], 'a=%.2f', a[i], ' v=%.2fm/s' % v[i], len(a), len(v), len(traj)
++ print(' id_sumo_veh', id_sumo_veh, ': (x,y)', traj[i], 'a=%.2f', a[i], ' v=%.2fm/s' % v[i], len(a), len(v), len(traj))
+
+
+ class ElectricEnergyVehicleResults(am.ArrayObjman):
+@@ -1566,7 +1566,7 @@
+ 'info': 'Average speed', 'groupnames': ['electricenergydata'], 'is_average': True}),
+ ])
+
+- for attrname, kwargs in attrinfos.iteritems():
++ for attrname, kwargs in attrinfos.items():
+ self.add_resultattr(attrname, **kwargs)
+
+ def on_energy_total(self):
+@@ -1578,7 +1578,7 @@
+ # default cannot be kwarg
+ default = kwargs['default']
+ del kwargs['default']
+- if kwargs.has_key('groupnames'):
++ if 'groupnames' in kwargs:
+ kwargs['groupnames'].append('results')
+ else:
+ kwargs['groupnames'] = ['results']
+@@ -1595,12 +1595,12 @@
+
+ def import_xml(self, sumo, datapaths):
+ datapathkey = self.datapathkey.get_value()
+- if datapaths.has_key(datapathkey):
++ if datapathkey in datapaths:
+ self.import_electricenergy_sumoxml(datapaths[datapathkey], sumo)
+
+ def import_electricenergy_sumoxml(self, filepath, sumo):
+ element = 'vehicle'
+- print 'ElectricEnergyresults.import_electricenergy_sumoxml', element, filepath
++ print('ElectricEnergyresults.import_electricenergy_sumoxml', element, filepath)
+ #id_type = 'edge',
+ #reader = 'interval',
+ attrconfigs = self.get_group('electricenergydata')
+@@ -1613,8 +1613,8 @@
+ self.times.set_value(times)
+ self.energies.set_value(energies)
+
+- print ' times=\n', self.times.get_value()
+- print ' energies=\n', self.energies.get_value()
++ print(' times=\n', self.times.get_value())
++ print(' energies=\n', self.energies.get_value())
+
+ # print ' ids_sumo',ids_sumo
+ # print ' results.keys()',results.keys()
+@@ -1627,7 +1627,7 @@
+ #ids_sumotrip = self.ids_trip.get_linktab().ids_sumo
+ n = len(ids_sumo)
+ ids = self.add_rows(n=n, ids_sumo=ids_sumo)
+- print ' n', n
++ print(' n', n)
+ ind_range = np.arange(n, dtype=np.int32)
+
+ #ids = np.zeros(n, dtype=np.int32)
+@@ -1648,10 +1648,10 @@
+ attrname = attrconfig.attrname
+
+ default = attrconfig.get_default()
+- if type(default) in (types.IntType, types.LongType):
++ if type(default) in (int, int):
+ conversion = 'i' # int
+ values_attr = np.zeros(n, int)
+- elif type(default) in (types.FloatType, types.ComplexType):
++ elif type(default) in (float, complex):
+ conversion = 'f' # float
+ values_attr = np.zeros(n, float)
+ else:
+@@ -1719,8 +1719,8 @@
+ self.routeresults = attrsman.add(cm.ObjConf(Routeresults('routeresults', self, scenario.demand.trips,
+ scenario.net.edges), groupnames=['Route results']))
+ # add trip results from all demand objects
+- print 'Simresults._init_attributes'
+- print ' scenario.demand.get_demandobjects()', scenario.demand.get_demandobjects()
++ print('Simresults._init_attributes')
++ print(' scenario.demand.get_demandobjects()', scenario.demand.get_demandobjects())
+ for demandobj in scenario.demand.get_demandobjects():
+ demandobj.config_results(self)
+
+@@ -1759,7 +1759,7 @@
+ getattr(self, resultobj.get_ident()).clear()
+
+ if not hasattr(self, resultobj.get_ident()):
+- if kwargs.has_key('groupnames'):
++ if 'groupnames' in kwargs:
+ kwargs['groupnames'].append('Results')
+ else:
+ kwargs['groupnames'] = ['Results']
+@@ -1776,32 +1776,32 @@
+ # #edgedatapath=None, edgenoisepath=None, edgeemissionspath = None, routesdatapath=None, tripdatapath=None
+
+ def import_xml(self, sumo, **datapaths):
+- print 'Simresults.import_xml', self.get_ident_abs()
++ print('Simresults.import_xml', self.get_ident_abs())
+ # print ' datapaths',datapaths
+ # import first all edge oriented results for the whole net
+- if datapaths.has_key('edgedatapath'):
+- print 'import edge data'
++ if 'edgedatapath' in datapaths:
++ print('import edge data')
+ self.edgeresults.import_edgedata(sumo, datapaths['edgedatapath'])
+
+- if datapaths.has_key('edgenoisepath'):
+- print 'import edge noise'
++ if 'edgenoisepath' in datapaths:
++ print('import edge noise')
+ self.edgeresults.import_edgenoise(sumo, datapaths['edgenoisepath'])
+
+- if datapaths.has_key('edgeemissionspath'):
+- print 'import edge emissons'
++ if 'edgeemissionspath' in datapaths:
++ print('import edge emissons')
+ self.edgeresults.import_edgeemissions(sumo, datapaths['edgeemissionspath'])
+
+ # import all other resultobjects
+- for resultobj in self.get_attrsman().get_group_attrs('Results').values():
+- print ' import other resultobject', resultobj.ident
++ for resultobj in list(self.get_attrsman().get_group_attrs('Results').values()):
++ print(' import other resultobject', resultobj.ident)
+ resultobj.import_xml(sumo, datapaths)
+
+- if datapaths.has_key('routesdatapath'):
+- print 'import route results'
++ if 'routesdatapath' in datapaths:
++ print('import route results')
+ self.routeresults.import_xml(sumo, datapaths)
+- print 'importedge flows'
++ print('importedge flows')
+ self.edgeresults.import_edgeflows(sumo, datapaths['edgedatapath'])
+- print 'import connection flows'
++ print('import connection flows')
+ self.connectionresults.evaluate_results(sumo, datapaths)
+
+ # def process(self, process = None):
+@@ -1811,7 +1811,7 @@
+ # demandobj.process_results(self, process)
+
+ def get_tripresults(self):
+- return self.get_attrsman().get_group_attrs('Trip results').values()
++ return list(self.get_attrsman().get_group_attrs('Trip results').values())
+
+ # def import_routesdata(self, routesdatapath):
+ # for tripresult in self.get_tripresults():
+@@ -1885,12 +1885,12 @@
+ xmltag = attrsconfig.xmltag
+ attrname = attrsconfig.attrname
+
+- if attrs.has_key(xmltag):
++ if xmltag in attrs:
+ # print ' attrname cum',attrname,attrs.has_key(attrname),'*'+attrs[attrname]+'*'
+ a = attrs[xmltag]
+
+ if a.strip() != '':
+- if self._values[attrname].has_key(id_elem):
++ if id_elem in self._values[attrname]:
+ self._values[attrname][id_elem] += float(a)
+ # print ' added val',xmltag,attrname,self._values[attrname][id_elem],'val',float(a)
+ else:
+@@ -1908,12 +1908,12 @@
+ for attrsconfig in self._attrsconfigs_average:
+ xmltag = attrsconfig.xmltag
+ attrname = attrsconfig.attrname
+- if attrs.has_key(xmltag):
++ if xmltag in attrs:
+ # print ' attrname',attrname,attrs.has_key(attrname),'*'+attrs[attrname]+'*'
+ # n=float(self.n_inter)
+ a = attrs[xmltag]
+ if a.strip() != '':
+- if self._values[attrname].has_key(id_elem):
++ if id_elem in self._values[attrname]:
+ valcum, n = self._values[attrname][id_elem]
+ valcum += float(a)
+ n += 1
+@@ -1942,7 +1942,7 @@
+ element is "lane" or "edge" or "tripinfo"
+ attrnames is a list of attribute names to read.
+ """
+- print 'IntervalAvReader2', element
++ print('IntervalAvReader2', element)
+ # print ' attrsconfigs_cumulative'
+ # for attrconfig in attrsconfigs_cumulative: print ' ',attrconfig.attrname
+
+@@ -2020,12 +2020,12 @@
+ xmltag = attrsconfig.xmltag
+ attrname = attrsconfig.attrname
+
+- if attrs.has_key(xmltag):
++ if xmltag in attrs:
+ # print ' attrname cum',attrname,attrs.has_key(attrname),'*'+attrs[attrname]+'*'
+ a = attrs[xmltag]
+
+ if a.strip() != '':
+- if self._values[attrname].has_key(id_elem):
++ if id_elem in self._values[attrname]:
+ self._values[attrname][id_elem] += float(a)
+ # print ' added val',xmltag,attrname,self._values[attrname][id_elem],'val',float(a)
+ else:
+@@ -2043,12 +2043,12 @@
+ for attrsconfig in self._attrsconfigs_average:
+ xmltag = attrsconfig.xmltag
+ attrname = attrsconfig.attrname
+- if attrs.has_key(xmltag):
++ if xmltag in attrs:
+ # print ' attrname',attrname,attrs.has_key(attrname),'*'+attrs[attrname]+'*'
+ # n=float(self.n_inter)
+ a = attrs[xmltag]
+ if a.strip() != '':
+- if self._values[attrname].has_key(id_elem):
++ if id_elem in self._values[attrname]:
+ valcum, n = self._values[attrname][id_elem]
+ valcum += float(a)
+ n += 1
+@@ -2085,7 +2085,7 @@
+ element is "lane" or "edge" or "tripinfo"
+ attrnames is a list of attribute names to read.
+ """
+- print 'ElectricalEnergyReader', element
++ print('ElectricalEnergyReader', element)
+ # print ' attrsconfigs_cumulative',attrsconfigs_cumulative
+ # print ' attrsconfigs_average',attrsconfigs_average
+ IntervalAvReader2.__init__(self, element, sumo, attrsconfigs_cumulative, attrsconfigs_average)
+@@ -2142,13 +2142,13 @@
+ xmltag = attrsconfig.xmltag
+ attrname = attrsconfig.attrname
+ # print ' attrname (cum)',attrname,xmltag,attrs.has_key(xmltag)
+- if attrs.has_key(xmltag):
++ if xmltag in attrs:
+
+ a = attrs[xmltag]
+
+ if a.strip() != '':
+ a = float(a)
+- if self._values[attrname].has_key(id_elem):
++ if id_elem in self._values[attrname]:
+ self._values[attrname][id_elem] += a
+ # print ' added val',xmltag,attrname,self._values[attrname][id_elem],'val',float(a)
+ else:
+@@ -2162,12 +2162,12 @@
+ xmltag = attrsconfig.xmltag
+ attrname = attrsconfig.attrname
+ # print ' attrname (av)',attrname,xmltag,attrs.has_key(xmltag)
+- if attrs.has_key(xmltag):
++ if xmltag in attrs:
+
+ a = attrs[xmltag]
+ if a.strip() != '':
+ a = float(a)
+- if self._values[attrname].has_key(id_elem):
++ if id_elem in self._values[attrname]:
+ valcum, n = self._values[attrname][id_elem]
+ # print ' add val', float(a),'to',valcum
+ valcum += a
+@@ -2244,15 +2244,15 @@
+ xmltag = attrsconfig.xmltag
+ attrname = attrsconfig.attrname
+
+- if attrs.has_key(xmltag):
++ if xmltag in attrs:
+ # print ' attrname',attrname,attrs.has_key(attrname)
+- if attrs.has_key(attrname):
++ if attrname in attrs:
+
+ # print ' val *'+attrs[xmltag]+'*'
+ a = attrs[xmltag]
+
+ if a.strip() != '':
+- if self._values[attrname].has_key(id_elem):
++ if id_elem in self._values[attrname]:
+ self._values[attrname][id_elem] += float(a)
+ else:
+ self._values[attrname][id_elem] = float(a)
+@@ -2268,11 +2268,11 @@
+ for attrsconfig in self._attrsconfigs_average:
+ xmltag = attrsconfig.xmltag
+ attrname = attrsconfig.attrname
+- if attrs.has_key(xmltag):
++ if xmltag in attrs:
+ # n=float(self.n_inter)
+ a = attrs[xmltag]
+ if a.strip() != '':
+- if self._values[attrname].has_key(id_elem):
++ if id_elem in self._values[attrname]:
+ valcum, n = self._values[attrname][id_elem]
+ valcum += float(a)
+ n += 1
+@@ -2295,7 +2295,7 @@
+
+
+ def read_electrical_energy(filepath, sumo, element, attrsconfigs):
+- print 'read_electrical_energy'
++ print('read_electrical_energy')
+ attrsconfigs_cumulative = []
+ attrsconfigs_average = []
+ for attrsconfig in attrsconfigs:
+@@ -2323,7 +2323,7 @@
+ element is "lane" or "edge" or "tripinfo"
+ attrnames is a list of attribute names to read.
+ """
+- print 'ElectricalEnergyReader', element
++ print('ElectricalEnergyReader', element)
+ # print ' attrsconfigs_cumulative',attrsconfigs_cumulative
+ # print ' attrsconfigs_average',attrsconfigs_average
+ IntervalAvReader2.__init__(self, element, sumo, attrsconfigs_cumulative, attrsconfigs_average)
+@@ -2380,13 +2380,13 @@
+ xmltag = attrsconfig.xmltag
+ attrname = attrsconfig.attrname
+ # print ' attrname (cum)',attrname,xmltag,attrs.has_key(xmltag)
+- if attrs.has_key(xmltag):
++ if xmltag in attrs:
+
+ a = attrs[xmltag]
+
+ if a.strip() != '':
+ a = float(a)
+- if self._values[attrname].has_key(id_elem):
++ if id_elem in self._values[attrname]:
+ self._values[attrname][id_elem] += a
+ # print ' added val',xmltag,attrname,self._values[attrname][id_elem],'val',float(a)
+ else:
+@@ -2400,12 +2400,12 @@
+ xmltag = attrsconfig.xmltag
+ attrname = attrsconfig.attrname
+ # print ' attrname (av)',attrname,xmltag,attrs.has_key(xmltag)
+- if attrs.has_key(xmltag):
++ if xmltag in attrs:
+
+ a = attrs[xmltag]
+ if a.strip() != '':
+ a = float(a)
+- if self._values[attrname].has_key(id_elem):
++ if id_elem in self._values[attrname]:
+ valcum, n = self._values[attrname][id_elem]
+ # print ' add val', float(a),'to',valcum
+ valcum += a
+@@ -2435,7 +2435,7 @@
+ element is "lane" or "edge" or "tripinfo"
+ attrnames is a list of attribute names to read.
+ """
+- print 'TrajectoryReader', element
++ print('TrajectoryReader', element)
+ # print ' attrsconfigs_cumulative',attrsconfigs_cumulative
+ # print ' attrsconfigs_average',attrsconfigs_average
+ IntervalAvReader2.__init__(self, element, sumo, [], [])
+@@ -2518,7 +2518,7 @@
+
+
+ def read_trajectories(filepath, sumo, element):
+- print 'read_trajectories', element
++ print('read_trajectories', element)
+
+ reader = TrajectoryReader(element, sumo)
+ parse(filepath, reader)
+@@ -2529,7 +2529,7 @@
+ angles = np.ones(n_veh, dtype=np.object)
+ speeds = np.ones(n_veh, dtype=np.object)
+
+- for i, id_sumo in zip(xrange(n_veh), ids_sumo):
++ for i, id_sumo in zip(range(n_veh), ids_sumo):
+ trajectories[i] = reader.trajectories[id_sumo]
+ angles[i] = reader.angles[id_sumo]
+ speeds[i] = reader.speeds[id_sumo]
+@@ -2563,7 +2563,7 @@
+
+
+ def read_tripresult(filepath, sumo, trips, element, attrsconfigs):
+- print 'read_tripresult', filepath, trips.ident, 'element', element
++ print('read_tripresult', filepath, trips.ident, 'element', element)
+ attrsconfigs_cumulative = []
+ attrsconfigs_average = []
+ for attrsconfig in attrsconfigs:
+--- tools/contributed/sumopy/coremodules/simulation/results_mpl.py (original)
++++ tools/contributed/sumopy/coremodules/simulation/results_mpl.py (refactored)
+@@ -50,7 +50,7 @@
+ # edgeresultes....
+ attrnames_edgeresults = OrderedDict()
+ edgeresultattrconfigs = self.parent.edgeresults.get_group_attrs('results')
+- edgeresultattrnames = edgeresultattrconfigs.keys()
++ edgeresultattrnames = list(edgeresultattrconfigs.keys())
+ # edgeresultattrnames.sort()
+ for attrname in edgeresultattrnames:
+ attrconfig = edgeresultattrconfigs[attrname]
+@@ -117,7 +117,7 @@
+ self._init_common('electricalenergyresultsplotter', parent=results, name=name,
+ info=info, logger=logger)
+
+- print 'ElectricalEnergyResultsPlotter.__init__', results, self.parent, len(self.get_eneryresults())
++ print('ElectricalEnergyResultsPlotter.__init__', results, self.parent, len(self.get_eneryresults()))
+ attrsman = self.get_attrsman()
+
+ self.add_plotoptions_lineplot(**kwargs)
+@@ -128,16 +128,16 @@
+
+ def show(self):
+ eneryresults = self.get_eneryresults()
+- print 'show', eneryresults
++ print('show', eneryresults)
+ # print ' dir(vehicleman)',dir(vehicleman)
+
+- print ' len(eneryresults)', len(eneryresults)
++ print(' len(eneryresults)', len(eneryresults))
+ if len(eneryresults) > 0:
+ plt.close("all")
+ self.plot_power()
+
+ def plot_power(self):
+- print 'plot_power'
++ print('plot_power')
+ eneryresults = self.get_eneryresults()
+
+ times = eneryresults.times.get_value()
+@@ -193,7 +193,7 @@
+ self._init_common('speedprofileplotter', parent=results, name=name,
+ info=info, logger=logger)
+
+- print 'SpeedprofilePlotter.__init__', results, self.parent, len(self.get_results())
++ print('SpeedprofilePlotter.__init__', results, self.parent, len(self.get_results()))
+ attrsman = self.get_attrsman()
+
+ self.id_veh_sumo = attrsman.add(cm.AttrConf('id_veh_sumo', kwargs.get('id_veh_sumo', ''),
+@@ -211,10 +211,10 @@
+
+ def show(self):
+ results = self.get_results()
+- print 'show', results
++ print('show', results)
+ id_res = results.ids_sumo.get_id_from_index(self.id_veh_sumo)
+
+- print ' len(results)', len(results), results.ids_sumo.has_index(self.id_veh_sumo)
++ print(' len(results)', len(results), results.ids_sumo.has_index(self.id_veh_sumo))
+ if results.ids_sumo.has_index(self.id_veh_sumo):
+ id_res = results.ids_sumo.get_id_from_index(self.id_veh_sumo)
+ plt.close("all")
+@@ -224,7 +224,7 @@
+ return False
+
+ def plot_speedprofile(self, times, speeds):
+- print 'plot_speedprofile'
++ print('plot_speedprofile')
+
+ if len(times) < 2:
+ return False
+@@ -278,13 +278,13 @@
+ self._init_common('xyedgeresultsplotter', parent=results, name=name,
+ info=info, logger=logger)
+
+- print 'XYResultsPlotter.__init__', results
++ print('XYResultsPlotter.__init__', results)
+ attrsman = self.get_attrsman()
+
+ # edgeresultes....
+ attrnames_edgeresults = OrderedDict()
+ edgeresultattrconfigs = self.parent.edgeresults.get_group_attrs('results')
+- edgeresultattrnames = edgeresultattrconfigs.keys()
++ edgeresultattrnames = list(edgeresultattrconfigs.keys())
+ # edgeresultattrnames.sort()
+ for attrname in edgeresultattrnames:
+ attrconfig = edgeresultattrconfigs[attrname]
+@@ -315,13 +315,13 @@
+ self.add_save_options(**kwargs)
+
+ def show(self):
+- print 'show'
++ print('show')
+
+ plt.close("all")
+ self.plot_xy()
+
+ def plot_xy(self):
+- print 'plot_xy', self.edgeattrname_y, 'vs', self.edgeattrname_x
++ print('plot_xy', self.edgeattrname_y, 'vs', self.edgeattrname_x)
+
+ if (self.edgeattrname_x is not "") & (self.edgeattrname_x is not ""):
+ resultattrconf_x = getattr(self.parent.edgeresults, self.edgeattrname_x)
+@@ -363,7 +363,7 @@
+ offset = my - (m*mx)
+
+ x_linreg = np.array([np.min(x[inds]), np.max(x[inds])], dtype=np.float)
+- print ' m', m, 'offset', offset
++ print(' m', m, 'offset', offset)
+ # print ' x_linreg',offset * x_linreg
+ ax.plot(x_linreg, offset + m*x_linreg,
+ label=r'$%.3f+%.3fx$, $R^2=%.3f$' % (offset, m, R2),
+@@ -431,7 +431,7 @@
+ self._init_common('isochoneplotter', parent=results, name=name,
+ info=info, logger=logger)
+
+- print 'TraveltimePlotter.__init__', results, self.parent
++ print('TraveltimePlotter.__init__', results, self.parent)
+ attrsman = self.get_attrsman()
+ scenario = self.get_scenario()
+
+@@ -549,8 +549,8 @@
+ )
+ elif self.direction == 'destination':
+ title = 'Accumulated travel times to edge ID %d' % (self.id_edge_reference)
+- ids_edge = np.array(edgetimestree.keys(), dtype=np.int32)
+- edgetimes = np.array(edgetimestree.values(), dtype=np.float32)
++ ids_edge = np.array(list(edgetimestree.keys()), dtype=np.int32)
++ edgetimes = np.array(list(edgetimestree.values()), dtype=np.float32)
+
+ self.plot_results_on_map(ax, ids_edge=ids_edge,
+ values=edgetimes,
+@@ -559,7 +559,7 @@
+
+ if 0: # self.is_isochrone:
+
+- print 'isochrone plot not yet implemented'
++ print('isochrone plot not yet implemented')
+
+ times_point = np.zeros(np.max(ids_point)+1)
+ for id_point in ids_point:
+@@ -620,7 +620,7 @@
+ else:
+ isochrone_shapes[i].append([(points.coords[iso_points[np.argmax(iso_points[:, 3]), 1]][0]),
+ (points.coords[iso_points[np.argmax(iso_points[:, 3]), 1]][1])])
+- print isochrone_shapes
++ print(isochrone_shapes)
+ for isochrone_shape in isochrone_shapes:
+ verts = np.array(isochrone_shape)[:, :2].tolist()
+ verts.append([0, 0])
+@@ -637,9 +637,9 @@
+
+ if len(isochrone_shape) > 4:
+ zone_shape = isochrone_shape
+- print zone_shape
+- for zone_shape_coords, i in zip(isochrone_shape, range(len(isochrone_shape))):
+- print i, len(isochrone_shape)
++ print(zone_shape)
++ for zone_shape_coords, i in zip(isochrone_shape, list(range(len(isochrone_shape)))):
++ print(i, len(isochrone_shape))
+ if i == 0:
+ zone_shape[i] = ((np.array(isochrone_shape[i])+np.array(isochrone_shape[i+1])+np.array(
+ isochrone_shape[-1])+np.array(isochrone_shape[i+2])+np.array(isochrone_shape[-2]))/5.).tolist()
+--- tools/contributed/sumopy/coremodules/simulation/simplaconfig.py (original)
++++ tools/contributed/sumopy/coremodules/simulation/simplaconfig.py (refactored)
+@@ -42,7 +42,7 @@
+ import simpla
+
+ except:
+- print 'WARNING: No module simpla in syspath. Please provide SUMO_HOME.'
++ print('WARNING: No module simpla in syspath. Please provide SUMO_HOME.')
+
+ simpla = None
+
+@@ -287,7 +287,7 @@
+ if self.is_enabled:
+ # self.add_vtypes()# done in get_writexmlinfo means in get_vtypes()
+ self.export_config()
+- print 'Simplaconfig.prepare_sim', self.configfilepath, self.is_enabled
++ print('Simplaconfig.prepare_sim', self.configfilepath, self.is_enabled)
+ simpla.load(self.configfilepath)
+
+ def finish_sim(self):
+@@ -303,7 +303,7 @@
+ """
+ Write simpla xml config file
+ """
+- print 'Simplaconfig.write_xml'
++ print('Simplaconfig.write_xml')
+ fd.write(xm.begin(self.xmltag, indent))
+ attrsman = self.get_attrsman()
+ vtypes = self.parent.get_scenario().demand.vtypes
+@@ -329,7 +329,7 @@
+ # #if id_vtype_sumo.split('_')[-1] not in plattypes:
+ # ids_vtypes_plat_sumo.append(id_vtype_sumo)
+
+- ids_vtypes_plat_sumo = ids_sumo_vtypes[self._typemap.keys()]
++ ids_vtypes_plat_sumo = ids_sumo_vtypes[list(self._typemap.keys())]
+ fd.write(xm.start('vehicleSelectors', indent+2))
+ fd.write(xm.arr('value', ids_vtypes_plat_sumo, sep=','))
+ fd.write(xm.stopit())
+@@ -349,9 +349,9 @@
+ fd.write(xm.num('catchupFollower', self.speedfactor_catchup_follower))
+ fd.write(xm.stopit())
+
+- for plattypes in self._typemap.values():
++ for plattypes in list(self._typemap.values()):
+ fd.write(xm.start('vTypeMap', indent+2))
+- for plattype, id_vtype in plattypes.iteritems():
++ for plattype, id_vtype in plattypes.items():
+ fd.write(xm.num(plattype, ids_sumo_vtypes[id_vtype]))
+ fd.write(xm.stopit())
+
+@@ -372,7 +372,7 @@
+ This function is called before writing vtypes.
+ These vtypes should be deleted after the export.
+ """
+- print 'Simplaconfig.add_vtypes'
++ print('Simplaconfig.add_vtypes')
+ self._typemap = {}
+ vtypes = self.get_scenario().demand.vtypes
+ for id_mode in self.ids_platoonmodes:
+@@ -433,14 +433,14 @@
+ if not self.is_enabled:
+ return []
+
+- print 'Simpla.get_vtypes'
++ print('Simpla.get_vtypes')
+ plattype_original = 'original'
+ # add vtypes for platooning here
+ self.add_vtypes()
+ # here we return only the additional vtypes
+ ids_vtypes_plat = []
+- for plattypes in self._typemap.values():
+- for plattype, id_vtype in plattypes.iteritems():
++ for plattypes in list(self._typemap.values()):
++ for plattype, id_vtype in plattypes.items():
+ if plattype != plattype_original:
+ ids_vtypes_plat.append(id_vtype)
+ # print ' ids_vtypes_plat',ids_vtypes_plat
+@@ -452,12 +452,12 @@
+ vtypes = self.get_scenario().demand.vtypes
+ plattype_original = 'original'
+ ids_vtypes_plat = []
+- for plattypes in self._typemap.values():
+- for plattype, id_vtype in plattypes.iteritems():
++ for plattypes in list(self._typemap.values()):
++ for plattype, id_vtype in plattypes.items():
+ if plattype != plattype_original:
+ ids_vtypes_plat.append(id_vtype)
+
+- print 'del_vtypes', ids_vtypes_plat
++ print('del_vtypes', ids_vtypes_plat)
+ vtypes.del_rows(ids_vtypes_plat)
+ self._typemap = {}
+
+@@ -467,7 +467,7 @@
+ coloroffset=np.zeros(4, np.float32),
+ colorfactor=np.ones(4, np.float32),
+ carfollowermodel='Krauss'):
+- print '_add_vtypes', ids, plattype
++ print('_add_vtypes', ids, plattype)
+ n = len(ids)
+ ids_new = vtypes.add_rows(n=len(ids))
+ for colconfig in vtypes.get_attrsman()._colconfigs:
+@@ -499,7 +499,7 @@
+ vtypes.decels_emergency[ids_new] = vtypes.decels[ids_new]+0.1
+ # update typemap database
+ for _id, _id_new in zip(ids, ids_new):
+- if self._typemap.has_key(_id):
++ if _id in self._typemap:
+ self._typemap[_id][plattype] = _id_new
+ else:
+ self._typemap[_id] = {plattype: _id_new}
+--- tools/contributed/sumopy/coremodules/simulation/simulation.py (original)
++++ tools/contributed/sumopy/coremodules/simulation/simulation.py (refactored)
+@@ -22,9 +22,9 @@
+ import agilepy.lib_base.arrayman as am
+ import agilepy.lib_base.xmlman as xm
+ from agilepy.lib_base.misc import random_choice, get_inversemap
+-import results
+-from simplaconfig import SimplaConfig
+-from taxi import TaxiService
++from . import results
++from .simplaconfig import SimplaConfig
++from .taxi import TaxiService
+
+
+ class Simulation(cm.BaseObjman):
+@@ -42,7 +42,7 @@
+ self._init_constants()
+
+ def _init_attributes(self):
+- print 'Simulation._init_attributes id', id(self), self.parent.rootname # ,dir(self)
++ print('Simulation._init_attributes id', id(self), self.parent.rootname) # ,dir(self)
+ attrsman = self.get_attrsman()
+
+ # if self.get_version()<0.2:
+@@ -107,4 +107,4 @@
+ #demandobjects = set([])
+ # for ident, conf in self.get_group_attrs('').iteritems():
+ # demandobjects.add(conf.get_value())
+- return self.get_attrsman().get_group_attrs('simulation objects').values()
++ return list(self.get_attrsman().get_group_attrs('simulation objects').values())
+--- tools/contributed/sumopy/coremodules/simulation/sumo.py (original)
++++ tools/contributed/sumopy/coremodules/simulation/sumo.py (refactored)
+@@ -18,7 +18,7 @@
+
+ from agilepy.lib_base.processes import Process, CmlMixin, ff, call, P, filepathlist_to_filepathstring, Options
+ from coremodules.scenario.scenario import load_scenario
+-from results import Simresults
++from .results import Simresults
+ from coremodules.network.network import SumoIdsConf
+ import agilepy.lib_base.xmlman as xm
+ import agilepy.lib_base.arrayman as am
+@@ -51,7 +51,7 @@
+
+
+ except:
+- print 'WARNING: No module traci in syspath. Please provide SUMO_HOME.'
++ print('WARNING: No module traci in syspath. Please provide SUMO_HOME.')
+
+ traci = None
+
+@@ -896,7 +896,7 @@
+ Called by run after is_ready verification
+ """
+
+- print 'do... '
++ print('do... ')
+
+ scenario = self.parent
+
+@@ -1047,10 +1047,10 @@
+ )
+
+ if self._cmlfilepath is None:
+- print ' call run_cml'
++ print(' call run_cml')
+ return self.run_cml(cml=self.get_cml())
+ else:
+- print ' do not simulate but write cml to', self._cmlfilepath
++ print(' do not simulate but write cml to', self._cmlfilepath)
+ f = open(self._cmlfilepath, "w+")
+ f.write(self.get_cml()+'\n')
+
+@@ -1065,7 +1065,7 @@
+ """
+ Imports simulation resuts into results object.
+ """
+- print 'import_results'
++ print('import_results')
+
+ # first a dict is created with available dataname as key
+ # and filepath as value
+@@ -1125,7 +1125,7 @@
+ p = P
+ else:
+ p = ''
+- print 'get_cml p=%s=' % p
++ print('get_cml p=%s=' % p)
+ # print ' self.configfilepath=%s='%self.configfilepath
+ # print ' self.logfilepath=%s='%self.logfilepath
+ if self.guimode is 'nogui':
+@@ -1249,7 +1249,7 @@
+ def run_cml(self, cml):
+ scenario = self.parent
+ cmllist = cml.split(' ')
+- print 'SumoTraci.run_cml', cmllist
++ print('SumoTraci.run_cml', cmllist)
+ traci.start(cmllist)
+
+ simplaconfig = self.parent.simulation.simplaconfig
+@@ -1259,7 +1259,7 @@
+ self.simtime = self.simtime_start
+ self.duration = 1.0+self.simtime_end-self.simtime_start
+ self.get_attrsman().status.set('running')
+- print ' traci started', self.get_attrsman().status.get()
++ print(' traci started', self.get_attrsman().status.get())
+ simobjects = []
+
+ for simobj in self.parent.simulation.get_simobjects():
+@@ -1288,10 +1288,10 @@
+ def step(self):
+ # called interactively
+ # when gui it is called through the timer function
+- print 79*'='
+- print "simstep", self.simtime, self.simtime_end, self.simtime >= self.simtime_end
++ print(79*'=')
++ print("simstep", self.simtime, self.simtime_end, self.simtime >= self.simtime_end)
+ traci.simulationStep()
+- for i in xrange(len(self.simobjects)):
++ for i in range(len(self.simobjects)):
+ # for time_last, time_sample, simfunc in self.simobjects:
+ time_last, time_sample, simfunc = self.simobjects[i]
+ # print ' simfunc',simfunc,'time_last',time_last,'dt',self.simtime-time_last,'sim?',self.simtime-time_last > time_sample
+@@ -1303,18 +1303,18 @@
+
+ if self.simtime >= self.simtime_end: # | (not (traci.simulation.getMinExpectedNumber() > 0)):
+ # if self.simtime >= self.simtime_end:
+- print ' end of simulation reached at', self.simtime
++ print(' end of simulation reached at', self.simtime)
+ return self.finish_sim()
+
+ self.simtime += self.time_step
+
+ def finish_sim(self):
+- print 'finish_sim'
++ print('finish_sim')
+ # for demandobj in self.parent.demand.get_demandobjects():
+ # print ' finish_sim',demandobj.ident
+ # #demandobj.finish_sim(self) # why not for sim objects?
+ traci.close()
+- print ' traci closed.'
++ print(' traci closed.')
+ self.get_attrsman().status.set('success')
+
+ simplaconfig = self.parent.simulation.simplaconfig
+@@ -1841,13 +1841,13 @@
+ # print ' new since 1.8.0 ?'
+ # print ' workdirpath',self.workdirpath,'step_last',step_last
+ resultdir = os.path.join(self.workdirpath, str(step_last))
+- print ' resultdir', resultdir
++ print(' resultdir', resultdir)
+ filename = self.parent.get_rootfilename() + "_%03d.rou.xml" % (self.get_last_step(),)
+- print ' filename', filename
++ print(' filename', filename)
+ #routefilepath_final = os.path.join(self.workdirpath, str(step_last),'.'.join(self.routefilepath.split('.')[:-2]) + "_%03d.rou.xml"%(step_last,))
+ routefilepath_final = os.path.join(resultdir, filename)
+
+- print ' load routes from file ', routefilepath_final
++ print(' load routes from file ', routefilepath_final)
+ if os.path.isfile(routefilepath_final):
+ scenario.demand.import_routes_xml(routefilepath_final)
+
+@@ -1867,15 +1867,15 @@
+ os.remove(os.path.join(self.workdirpath, filename))
+
+ else: # new since 1.8.0 ?'
+- for step in xrange(self.step_first, step_last):
++ for step in range(self.step_first, step_last):
+ filepath = os.path.join(self.workdirpath, str(step))
+- print ' delete dir', filepath
++ print(' delete dir', filepath)
+ if os.path.isdir(filepath):
+ # print ' delete now'
+ try:
+ shutil.rmtree(filepath)
+ except OSError as e:
+- print("Error: %s - %s." % (e.filename, e.strerror))
++ print(("Error: %s - %s." % (e.filename, e.strerror)))
+
+ return True
+
+@@ -1886,7 +1886,7 @@
+ """
+ Imports simulation resuts into results object.
+ """
+- print 'import_results'
++ print('import_results')
+
+ # currently nothing is imported in results only routs are
+ # reimported in trip database
+--- tools/contributed/sumopy/coremodules/simulation/sumo_virtualpop.py (original)
++++ tools/contributed/sumopy/coremodules/simulation/sumo_virtualpop.py (refactored)
+@@ -51,7 +51,7 @@
+ else:
+ filepath_simstats = None
+
+-print 'sys.path', sys.path
++print('sys.path', sys.path)
+
+
+ #from coremodules.demand import vehicles as ve
+@@ -76,7 +76,7 @@
+ logfilepath = 'log.txt'
+ sumologfilepath = 'log_sumo.txt'
+ ###########################################################
+-print 'script_vp: initialize sim cmlfilepath=', cmlfilepath
++print('script_vp: initialize sim cmlfilepath=', cmlfilepath)
+
+ # Load the scenario
+
+@@ -168,7 +168,7 @@
+
+ if is_not_first_iter:
+ # load previous results, if cmlfilepath is present
+- print ' importing and procerroessing previous results'
++ print(' importing and procerroessing previous results')
+
+ # store plans before reselection
+ ids_plan_before = virtualpop.ids_plan[ids_pers].copy()
+@@ -180,7 +180,7 @@
+ # decrease c_probit and fraction for the nex iteration
+ c_probit = c_probit/(decrease+1)**n_iter
+ fraction = fraction/(decrease+1)**n_iter
+- print 'n_iter:', n_iter, 'c_probit:', c_probit, 'fraction:', fraction
++ print('n_iter:', n_iter, 'c_probit:', c_probit, 'fraction:', fraction)
+ # select plans according to last simulation results
+ sim.import_results() # will update plan travel times
+ virtualpop.select_plans_min_time_exec_est(fraction=fraction,
+@@ -193,7 +193,7 @@
+
+
+ else:
+- print ' first iteration'
++ print(' first iteration')
+ # select all plans with the minimum estimated time
+ virtualpop.select_plans_min_time_est(fraction=1.0,
+ c_probit=c_probit_ini)
+--- tools/contributed/sumopy/coremodules/simulation/sumo_virtualpop_iterate.py (original)
++++ tools/contributed/sumopy/coremodules/simulation/sumo_virtualpop_iterate.py (refactored)
+@@ -32,7 +32,7 @@
+
+
+ def start_iterations(scenariofilepath, n_iter, simscriptfilepath):
+- print 'sumo_virtualpop_iterate.run', scenariofilepath
++ print('sumo_virtualpop_iterate.run', scenariofilepath)
+ cmlfilepath = os.path.join(os.path.dirname(simscriptfilepath), 'sumo_virtualpop_cml.bash')
+
+ P = '"'
+@@ -43,37 +43,37 @@
+
+ for i in range(1, n_iter+1):
+
+- print ' Start preparation of iteration %d.' % i
++ print(' Start preparation of iteration %d.' % i)
+ proc = subprocess.Popen(cml_script, shell=True)
+ proc.wait()
+ if proc.returncode == 0:
+- print ' Preparation of iteration %d successful' % i
++ print(' Preparation of iteration %d successful' % i)
+ f = open(cmlfilepath, "r")
+ cml = f.readline()
+ f.close()
+
+ # time.sleep(10)
+
+- print ' Start SUMO microsimulator'
+- print ' cml=', cml
++ print(' Start SUMO microsimulator')
++ print(' cml=', cml)
+ proc = subprocess.Popen(cml, shell=True)
+ proc.wait()
+ if proc.returncode == 0:
+- print ' Microsimulation of iteration %d successful.' % i
++ print(' Microsimulation of iteration %d successful.' % i)
+ else:
+- print ' Error in microsimulation of iteration %d.' % i
++ print(' Error in microsimulation of iteration %d.' % i)
+ else:
+- print ' Error in preparation of iteration %d successful' % i
+- print ' Start preparation of iteration %d.' % i
++ print(' Error in preparation of iteration %d successful' % i)
++ print(' Start preparation of iteration %d.' % i)
+ proc = subprocess.Popen(cml_script, shell=True)
+ proc.wait()
+ if proc.returncode == 0:
+- print 'Save last results.'
++ print('Save last results.')
+ f = open(cmlfilepath, "r")
+ cml = f.readline()
+ f.close()
+ else:
+- print'error on the last data backup'
++ print('error on the last data backup')
+
+ # time.sleep(10)
+
+--- tools/contributed/sumopy/coremodules/simulation/taxi.py (original)
++++ tools/contributed/sumopy/coremodules/simulation/taxi.py (refactored)
+@@ -133,7 +133,7 @@
+ """
+ Write taxi configuration to sumo configuration file feed.
+ """
+- print 'TaxiService.write_config is_enabled', self.is_enabled
++ print('TaxiService.write_config is_enabled', self.is_enabled)
+ if self.is_enabled:
+ attrsman = self.get_attrsman()
+
+--- tools/contributed/sumopy/coremodules/simulation/wxgui.py (original)
++++ tools/contributed/sumopy/coremodules/simulation/wxgui.py (refactored)
+@@ -24,16 +24,16 @@
+ from coremodules.scenario.scenario import Scenario
+ from coremodules.network import routing
+ from coremodules.misc.matplottools import ResultDialog
+-import sumo
+-import results
+-
+-from result_oglviewer import Resultviewer
++from . import sumo
++from . import results
++
++from .result_oglviewer import Resultviewer
+
+ try:
+- import results_mpl as results_mpl
++ from . import results_mpl as results_mpl
+ is_mpl = True # we have matplotlib support
+ except:
+- print "WARNING: python matplotlib package not installed, no matplotlib plots."
++ print("WARNING: python matplotlib package not installed, no matplotlib plots.")
+ is_mpl = False
+
+
+@@ -82,12 +82,12 @@
+ Set mainframe and initialize widgets to various places.
+ """
+ self._mainframe = mainframe
+- print 'SimulationGui.init_widgets'
++ print('SimulationGui.init_widgets')
+ # mainframe.browse_obj(self._net)
+ self.make_menu()
+ self.make_toolbar()
+ self._resultviewer = mainframe.add_view("Result viewer", Resultviewer)
+- print ' self._resultviewer', self._resultviewer, self._resultviewer.get_drawing()
++ print(' self._resultviewer', self._resultviewer, self._resultviewer.get_drawing())
+
+ def refresh_widgets(self):
+ """
+@@ -96,11 +96,11 @@
+ dependent on the availability of data.
+ """
+ scenario = self.get_scenario()
+- print 'simulation.WxGui.refresh_widgets', self._simulation != scenario.simulation
++ print('simulation.WxGui.refresh_widgets', self._simulation != scenario.simulation)
+ is_refresh = False
+
+ if self._simulation != scenario.simulation:
+- print ' id(self._simulation)', id(self._simulation), 'id(scenario.simulation)', id(scenario.simulation), scenario.rootname
++ print(' id(self._simulation)', id(self._simulation), 'id(scenario.simulation)', id(scenario.simulation), scenario.rootname)
+ del self._simulation
+ self._simulation = scenario.simulation
+ is_refresh = True
+@@ -110,11 +110,11 @@
+ # if is_refresh
+ if self._simulation.results.is_modified():
+ #
+- print ' refresh of _resultviewer'
++ print(' refresh of _resultviewer')
+ drawing = self._resultviewer.set_results(self._simulation.results)
+ # canvas = self._neteditor.get_canvas()
+ else:
+- print ' no refresh of _resultviewer :('
++ print(' no refresh of _resultviewer :(')
+
+ def make_menu(self):
+ # print 'make_menu'
+@@ -750,7 +750,7 @@
+
+ # this does not return until the dialog is closed.
+ #val = dlg.ShowModal()
+- print 'open_sumodialog_interactive'
++ print('open_sumodialog_interactive')
+ dlg.Show()
+ dlg.MakeModal(True)
+ # print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL
+@@ -789,9 +789,9 @@
+ results = self._simulation.results
+ turnflows = self.get_scenario().demand.turnflows
+ ids_edge, flows = turnflows.estimate_entered()
+- print 'on_estimate_entered_turnflows'
+- print 'ids_edge', ids_edge
+- print 'flows', flows
++ print('on_estimate_entered_turnflows')
++ print('ids_edge', ids_edge)
++ print('flows', flows)
+ results.edgeresults.add_entered_est(*turnflows.estimate_entered())
+ self._mainframe.browse_obj(results.edgeresults)
+ self._mainframe.select_view(name="Result viewer") # !!!!!!!!tricky, crashes without
+--- tools/contributed/sumopy/examples/scripts/sumopy_sim.py (original)
++++ tools/contributed/sumopy/examples/scripts/sumopy_sim.py (refactored)
+@@ -39,7 +39,7 @@
+ if len(sys.argv) == 3:
+ resultfilepath = sys.argv[2]
+ else:
+- print __doc__
++ print(__doc__)
+ sys.exit(0)
+
+ myscenario = scenario.load_scenario(simfilepath)
+@@ -111,7 +111,7 @@
+
+
+ if resultfilepath is not None:
+- print 'saving results in', resultfilepath
++ print('saving results in', resultfilepath)
+ myscenario.simulation.results.save(resultfilepath)
+
+ # import all results from xml and put them into myscenario.simulation.results
+@@ -135,9 +135,9 @@
+
+ # do some analyses
+ ids_tripres = tripres.get_ids()
+-print 'numer of arrived vehicles:', len(ids_tripres)
+-print 'Total triplength: %.2fKm' % (0.001*np.mean(tripres.routeLength[ids_tripres]))
+-print 'Average speed: %.2fKm/s' % (3.6*np.mean(tripres.routeLength[ids_tripres]/tripres.duration[ids_tripres]))
++print('numer of arrived vehicles:', len(ids_tripres))
++print('Total triplength: %.2fKm' % (0.001*np.mean(tripres.routeLength[ids_tripres])))
++print('Average speed: %.2fKm/s' % (3.6*np.mean(tripres.routeLength[ids_tripres]/tripres.duration[ids_tripres])))
+
+ ids_edgeres = edgeres.get_ids()
+-print 'Total fuel consumption: %.2f liter' % (0.001*np.sum(edgeres.fuel_abs[ids_edgeres]))
++print('Total fuel consumption: %.2f liter' % (0.001*np.sum(edgeres.fuel_abs[ids_edgeres])))
+--- tools/contributed/sumopy/plugins/common/__init__.py (original)
++++ tools/contributed/sumopy/plugins/common/__init__.py (refactored)
+@@ -18,12 +18,12 @@
+
+ __version__ = "0.0"
+
+-print 'init', __name__
++print('init', __name__)
+
+
+ def get_wxgui():
+ # try:
+- from wxgui import WxGui
++ from .wxgui import WxGui
+ return WxGui(__name__)
+ # except:
+ # return None
+--- tools/contributed/sumopy/plugins/hcprt/__init__.py (original)
++++ tools/contributed/sumopy/plugins/hcprt/__init__.py (refactored)
+@@ -18,12 +18,12 @@
+
+ __version__ = "0.0"
+
+-print 'init', __name__
++print('init', __name__)
+
+
+ def get_wxgui():
+ # try:
+- from wxgui import WxGui
++ from .wxgui import WxGui
+ return WxGui(__name__)
+ # except:
+ # return None
+--- tools/contributed/sumopy/plugins/hcprt/hcprt.py (original)
++++ tools/contributed/sumopy/plugins/hcprt/hcprt.py (refactored)
+@@ -148,7 +148,7 @@
+ ])
+
+ def make(self, id_detectoredge=None, **kwargs):
+- print 'make', kwargs
++ print('make', kwargs)
+ # print ' ids_shuntedge',kwargs.get('ids_shuntedge',None),type(kwargs.get('ids_shuntedge',None)[0])
+ id_comp = self.add_row(ids_shuntedges=kwargs.get('ids_shuntedge', None),
+ ids_detectoredge=id_detectoredge
+@@ -158,13 +158,13 @@
+ return id_comp
+
+ def update(self, id_comp):
+- print 'update id_comp', id_comp
++ print('update id_comp', id_comp)
+ edges = self.get_scenario().net.edges
+
+ self.ids_detectoredge[id_comp] = edges.get_incoming(self.ids_shuntedges[id_comp][0])[0]
+
+ def update_all(self):
+- print 'update_all'
++ print('update_all')
+ for id_comp in self.get_ids():
+ self.update(id_comp)
+
+@@ -172,7 +172,7 @@
+ return self.parent.get_scenario()
+
+ def prepare_sim(self, process):
+- print 'Compressors.prepare_sim'
++ print('Compressors.prepare_sim')
+ net = self.get_scenario().net
+ nodes = net.nodes
+ edges = net.edges
+@@ -220,14 +220,14 @@
+ self.ids_vehs_detect_sumo = np.zeros(n_id_max, dtype=np.object)
+
+ for id_comp, ids_shuntedge in zip(ids, self.ids_shuntedges[ids]):
+- print ' id_comp', id_comp
++ print(' id_comp', id_comp)
+ n_shunts = len(ids_shuntedge) # first edge is not a real shunt!!
+
+ queues = n_shunts*[None]
+ queues_alloc = n_shunts*[None]
+ capacities = n_shunts*[None]
+
+- for i, length_edge in zip(range(n_shunts), edges.lengths[ids_shuntedge]):
++ for i, length_edge in zip(list(range(n_shunts)), edges.lengths[ids_shuntedge]):
+ capacities[i] = max(2, int((length_edge-30.0)/(self.length_veh+0.5)))
+ queues[i] = []
+ queues_alloc[i] = []
+@@ -240,16 +240,16 @@
+ self.releasetimes_queues[id_comp] = n_shunts*[0]
+
+ self.ids_vehs_detect_sumo[id_comp] = set()
+- print ' capacities', self.capacitiess[id_comp]
+- print ' queues', self.queuess[id_comp]
++ print(' capacities', self.capacitiess[id_comp])
++ print(' queues', self.queuess[id_comp])
+
+ return [(self.time_update.get_value(), self.process_step),
+ ]
+
+ def process_step(self, process):
+ simtime = process.simtime
+- print 79*'_'
+- print 'Compressors.process_step at', simtime
++ print(79*'_')
++ print('Compressors.process_step at', simtime)
+ net = self.get_scenario().net
+ edges = net.edges
+ vehicles = self.parent.prtvehicles
+@@ -276,19 +276,19 @@
+ self.releasetimes_queues[ids],
+ ):
+ n_queues = len(queues)
+- print ' '+30*'><'
+- print ' Compressor id_comp', id_comp, 'n_queues', n_queues
++ print(' '+30*'><')
++ print(' Compressor id_comp', id_comp, 'n_queues', n_queues)
+ # check for new vehicle arrivals/departures
+
+ ids_veh_entered_sumo, ids_veh_left_sumo, ids_veh_new_sumo = vehicles.get_entered_left(
+ id_detectedge_sumo, ids_veh_detect_sumo)
+
+ if 1:
+- print ' id_detectedge_sumo', id_detectedge_sumo
+- print ' ids_veh_detect_sumo', ids_veh_detect_sumo
+- print ' ids_veh_new_sumo', ids_veh_new_sumo
+- print ' ids_veh_entered_sumo=', ids_veh_entered_sumo
+- print ' ids_veh_left_sumo=', ids_veh_left_sumo
++ print(' id_detectedge_sumo', id_detectedge_sumo)
++ print(' ids_veh_detect_sumo', ids_veh_detect_sumo)
++ print(' ids_veh_new_sumo', ids_veh_new_sumo)
++ print(' ids_veh_entered_sumo=', ids_veh_entered_sumo)
++ print(' ids_veh_left_sumo=', ids_veh_left_sumo)
+
+ if len(ids_veh_entered_sumo) > 0:
+
+@@ -306,7 +306,7 @@
+ # no platoon, it is a single vehicle
+ id_targetedge_sumo = traci.vehicle.getRoute(id_veh_entered_sumo)[-1]
+ ids_shuntedge_sumo = edges.ids_sumo[ids_shuntedge]
+- print ' dispatch id_veh_entered_sumo %s' % id_veh_entered_sumo, id_targetedge_sumo, ids_edge_sumo_target
++ print(' dispatch id_veh_entered_sumo %s' % id_veh_entered_sumo, id_targetedge_sumo, ids_edge_sumo_target)
+
+ is_found_queue = False
+ inds_queue = np.flatnonzero((np.array(ids_edge_sumo_target, object)
+@@ -339,7 +339,7 @@
+ # print ' no queue with target or specific queue is full, search for a new queue'
+
+ is_found_queue = False
+- for ind_queue, queue in zip(range(1, n_queues), queues[1:]):
++ for ind_queue, queue in zip(list(range(1, n_queues)), queues[1:]):
+ if len(queue) == 0:
+ is_found_queue = True
+ break
+@@ -354,7 +354,7 @@
+ # print ' all queues are busy, let vehicle %s go ahead'%id_veh_entered_sumo
+ pass
+ else:
+- print ' configure target of new queue', ind_queue, id_targetedge_sumo
++ print(' configure target of new queue', ind_queue, id_targetedge_sumo)
+ ids_edge_sumo_target[ind_queue] = id_targetedge_sumo
+ self._alloc_queue(queues[ind_queue],
+ queues_alloc[ind_queue],
+@@ -384,14 +384,14 @@
+ capacity, id_edge_sumo_target,\
+ id_shuntedge_sumo, releasetime_queue\
+ in zip(
+- range(n_queues), queues, queues_alloc,
++ list(range(n_queues)), queues, queues_alloc,
+ capacities, ids_edge_sumo_target,
+ edges.ids_sumo[ids_shuntedge], releasetime_queues):
+ if 0:
+- print ' OOOO shunt %s --> target %s' % (id_shuntedge_sumo, id_edge_sumo_target)
+- print ' simtime-releasetime_queue', simtime-releasetime_queue
+- print ' queue', queue, id(queue)
+- print ' queue_alloc', queue_alloc
++ print(' OOOO shunt %s --> target %s' % (id_shuntedge_sumo, id_edge_sumo_target))
++ print(' simtime-releasetime_queue', simtime-releasetime_queue)
++ print(' queue', queue, id(queue))
++ print(' queue_alloc', queue_alloc)
+
+ # check if allocated arrived
+ ids_veh_arrived = []
+@@ -411,7 +411,7 @@
+ # here we coukd also test timeout conditions
+ if ((len_queue == capacity) | ((simtime - releasetime_queue) > self.time_accumulation_max.get_value())) & (simtime - self.releasetimes[id_comp] > self.time_release_min.get_value()):
+ # queue is full
+- print ' platoon and send vehicles:', queue
++ print(' platoon and send vehicles:', queue)
+ # action 1
+ # platoon all vehicles in queue, starting from last in queue
+ for i in range(len_queue-1, 0, -1):
+@@ -472,7 +472,7 @@
+ ])
+
+ def prepare_sim(self, process):
+- print 'Decompressors.prepare_sim'
++ print('Decompressors.prepare_sim')
+ net = self.get_scenario().net
+ nodes = net.nodes
+ edges = net.edges
+@@ -521,14 +521,14 @@
+ self.ids_vehs_detect_sumo = np.zeros(n_id_max, dtype=np.object)
+
+ for id_comp, ids_shuntedge in zip(ids, self.ids_shuntedges[ids]):
+- print ' id_comp', id_comp
++ print(' id_comp', id_comp)
+ n_shunts = len(ids_shuntedge) # first edge is not a real shunt!!
+
+ queues = n_shunts*[None]
+ queues_alloc = n_shunts*[None]
+ capacities = n_shunts*[None]
+ ids_targetedges_sumo = n_shunts*[None]
+- for i, length_edge in zip(range(n_shunts), edges.lengths[ids_shuntedge]):
++ for i, length_edge in zip(list(range(n_shunts)), edges.lengths[ids_shuntedge]):
+ capacities[i] = int((length_edge-25.0)/(self.length_veh+0.5))
+ queues[i] = []
+ queues_alloc[i] = []
+@@ -551,8 +551,8 @@
+
+ def process_step(self, process):
+ simtime = process.simtime
+- print 79*'_'
+- print 'Deompressors.process_step at', simtime
++ print(79*'_')
++ print('Deompressors.process_step at', simtime)
+ net = self.get_scenario().net
+ edges = net.edges
+ vehicles = self.parent.prtvehicles
+@@ -580,17 +580,17 @@
+ ):
+ n_queues = len(queues)
+ ids_shuntedge_sumo = edges.ids_sumo[ids_shuntedge]
+- print ' '+60*'|'
+- print ' Decompressor id_comp', id_comp, 'n_queues', n_queues
++ print(' '+60*'|')
++ print(' Decompressor id_comp', id_comp, 'n_queues', n_queues)
+ # check for new vehicle arrivals/departures
+
+ ids_veh_sumo = set(traci.edge.getLastStepVehicleIDs(id_detectedge_sumo))
+ if 0:
+- print ' id_detectedge_sumo', id_detectedge_sumo
+- print ' ids_veh_detect_sumo', ids_veh_detect_sumo, ids_veh_detect_sumo != ids_veh_sumo
+- print ' ids_veh_sumo=', ids_veh_sumo
++ print(' id_detectedge_sumo', id_detectedge_sumo)
++ print(' ids_veh_detect_sumo', ids_veh_detect_sumo, ids_veh_detect_sumo != ids_veh_sumo)
++ print(' ids_veh_sumo=', ids_veh_sumo)
+ ids_veh_sumo_raw = traci.edge.getLastStepVehicleIDs(id_detectedge_sumo)
+- print ' ids_veh_sumo_raw=', ids_veh_sumo_raw
++ print(' ids_veh_sumo_raw=', ids_veh_sumo_raw)
+
+ if ids_veh_detect_sumo != ids_veh_sumo:
+ # there are new vehicles
+@@ -600,12 +600,12 @@
+ ids_veh_entered = vehicles.get_ids_from_ids_sumo(ids_veh_entered_sumo)
+
+ if 1:
+- print ' ids_veh_entered', ids_veh_entered, type(ids_veh_entered)
++ print(' ids_veh_entered', ids_veh_entered, type(ids_veh_entered))
+ # print ' poss',poss
+- print ' ids_veh_entered_sumo', ids_veh_entered_sumo
+- print ' ids_leader', vehicles.ids_leader[ids_veh_entered]
+- print ' ids_follower', vehicles.ids_follower[ids_veh_entered]
+- print ' lengths_plat', vehicles.lengths_plat[ids_veh_entered]
++ print(' ids_veh_entered_sumo', ids_veh_entered_sumo)
++ print(' ids_leader', vehicles.ids_leader[ids_veh_entered])
++ print(' ids_follower', vehicles.ids_follower[ids_veh_entered])
++ print(' lengths_plat', vehicles.lengths_plat[ids_veh_entered])
+
+ for id_veh_entered, id_veh_entered_sumo, id_leader, length_plat\
+ in zip(ids_veh_entered, ids_veh_entered_sumo,
+@@ -623,7 +623,7 @@
+
+ is_found_queue = False
+ costs = np.zeros(n_queues, dtype=np.float32)
+- for ind_queue, queue, is_avail, capa in zip(range(n_queues), queues, are_queue_avail, capacities):
++ for ind_queue, queue, is_avail, capa in zip(list(range(n_queues)), queues, are_queue_avail, capacities):
+
+ dl = (capa - len(queue)) * self.length_veh - 2*length_plat
+ # print ' ceck queue %d with capa %d, len = %d, dl=%d'%(ind_queue,capa,len(queue),dl)
+@@ -657,7 +657,7 @@
+ # shunt it to the same edge as its leader
+ id_targetedge_sumo = traci.vehicle.getRoute(id_veh_entered_sumo)[-1]
+ id_platoonleader = vehicles.get_platoonleader(id_leader)
+- for ind_queue, queue, capa_queue, in zip(range(n_queues), queues, capacities):
++ for ind_queue, queue, capa_queue, in zip(list(range(n_queues)), queues, capacities):
+ if id_platoonleader in queue:
+ # print ' found id_platoonleader prt.%d of prt.%d at queue %d'%(id_platoonleader,id_veh_entered,ind_queue)
+ self._alloc_queue_follower(
+@@ -688,16 +688,16 @@
+ ids_targetedge_sumo, capacity,\
+ id_shuntedge_sumo, releasetime_queue\
+ in zip(
+- range(n_queues), queues, queues_alloc,
++ list(range(n_queues)), queues, queues_alloc,
+ ids_targetedges_sumo, capacities,
+ edges.ids_sumo[ids_shuntedge], releasetime_queues):
+ if 0:
+- print ' QQQQQQQQQQQ shunt %s ' % (id_shuntedge_sumo)
+- print ' simtime-releasetime_queue', simtime-releasetime_queue, (simtime - releasetime_queue > 15), (simtime - self.releasetimes[id_comp] > 10)
+- print ' queue', queue, id(queue)
+- print ' ids_targetedge_sumo', ids_targetedge_sumo
+- print ' queue_alloc', queue_alloc
+- print ' releasetime_queue', releasetime_queue, simtime - releasetime_queue, simtime - releasetime_queue > self.time_accumulation_max.get_value()
++ print(' QQQQQQQQQQQ shunt %s ' % (id_shuntedge_sumo))
++ print(' simtime-releasetime_queue', simtime-releasetime_queue, (simtime - releasetime_queue > 15), (simtime - self.releasetimes[id_comp] > 10))
++ print(' queue', queue, id(queue))
++ print(' ids_targetedge_sumo', ids_targetedge_sumo)
++ print(' queue_alloc', queue_alloc)
++ print(' releasetime_queue', releasetime_queue, simtime - releasetime_queue, simtime - releasetime_queue > self.time_accumulation_max.get_value())
+ # here we could also test timeout conditions
+ if (simtime - self.releasetimes[id_comp] > self.time_release_min.get_value()) & (simtime - releasetime_queue > self.time_accumulation_max.get_value()):
+ # if (simtime - self.releasetimes[id_comp]> self.time_release_min.get_value()):
+@@ -725,7 +725,7 @@
+
+ if len_queue > ind_pl+1:
+
+- for i, id_veh in zip(range(ind_pl+1, len_queue), queue[ind_pl+1:]):
++ for i, id_veh in zip(list(range(ind_pl+1, len_queue)), queue[ind_pl+1:]):
+ # print ' check prt.%d with leader prt.%d'%(id_veh,vehicles.ids_leader[id_veh])
+ if vehicles.ids_leader[id_veh] != -1:
+ # print ' real lead prt.%d qlead prt.%d | plat lead prt.%d plat qlead prt.%d '%(vehicles.ids_leader[id_veh],queue[i-1],vehicles.get_platoonleader(id_veh),id_veh_arrived)
+@@ -776,7 +776,7 @@
+ del ids_targetedge_sumo[id_veh_arrived]
+
+ else:
+- print ' platoon incomplete'
++ print(' platoon incomplete')
+ else:
+ # print ' no leaders arrived in this quque'
+ pass
+@@ -924,7 +924,7 @@
+ """
+ Make merge node database from network.
+ """
+- print 'Mergenodes.make_from_net'
++ print('Mergenodes.make_from_net')
+ self.clear()
+ id_prtmode = self.parent.id_prtmode
+
+@@ -943,9 +943,9 @@
+
+ # debug
+ ids_edge = edges.get_ids()
+- print 'distances:'
++ print('distances:')
+ for id_edge, id_edge_sumo, length, dist in zip(ids_edge, edges.ids_sumo[ids_edge], edges.lengths[ids_edge], distances[ids_edge]):
+- print ' id_edge=%d id_edge_sumo=%s length=%.1f dist=%.1f' % (id_edge, id_edge_sumo, length, dist)
++ print(' id_edge=%d id_edge_sumo=%s length=%.1f dist=%.1f' % (id_edge, id_edge_sumo, length, dist))
+
+ ids_shuntedges = set()
+ ids_mainlinedges = set()
+@@ -953,9 +953,9 @@
+ ids = compressors.get_ids()
+ for id_unit, ids_edge in zip(ids, compressors.ids_shuntedges[ids]):
+ # put in all shunts except for the bypass
+- print ' bypass of compressor', id_unit, '=', ids_edge[0]
++ print(' bypass of compressor', id_unit, '=', ids_edge[0])
+ ids_mainlinedges.add(ids_edge[0])
+- print ' update ids_shuntedges with compressors', ids_edge[1:]
++ print(' update ids_shuntedges with compressors', ids_edge[1:])
+ ids_shuntedges.update(ids_edge[1:])
+
+ # collect decompressornodes, wich will not become entry merges
+@@ -963,12 +963,12 @@
+ ids_node_decompressorout = []
+ for id_unit, ids_edge in zip(ids, decompressors.ids_shuntedges[ids]):
+ # put in all shunts except for the bypass
+- print ' bypass of decompressor', id_unit, '=', ids_edge[0], 'id_tonode', edges.ids_tonode[ids_edge[0]]
++ print(' bypass of decompressor', id_unit, '=', ids_edge[0], 'id_tonode', edges.ids_tonode[ids_edge[0]])
+ ids_mainlinedges.add(ids_edge[0])
+ ids_node_decompressorout.append(edges.ids_tonode[ids_edge[0]])
+- print ' update ids_shuntedges with decompressors', ids_edge[1:]
++ print(' update ids_shuntedges with decompressors', ids_edge[1:])
+ ids_shuntedges.update(ids_edge[1:])
+- print ' ids_node_decompressorout', ids_node_decompressorout
++ print(' ids_node_decompressorout', ids_node_decompressorout)
+ ids_node_compressorout = edges.ids_tonode[list(ids_mainlinedges)]
+ ids_mainlinefromnodes = edges.ids_fromnode[list(ids_mainlinedges)]
+
+@@ -978,7 +978,7 @@
+ # print ' update ids_shuntedges with mainline incoming',edges.get_incoming(id_edge)
+ # ids_shuntedges.update(edges.get_incoming(id_edge))
+
+- print ' ids_shuntedges', ids_shuntedges
++ print(' ids_shuntedges', ids_shuntedges)
+ #ids_ptstop = ptstops.get_ids()
+ #id_mode_prt = self.parent.id_prtmode
+
+@@ -988,7 +988,7 @@
+ #edgelengths = net.edges.lengths
+
+ ids_node = nodes.get_ids()
+- print ' ids_node', ids_node
++ print(' ids_node', ids_node)
+ for id_node, ids_edge_from, ids_edge_to, id_type in zip(
+ ids_node,
+ nodes.ids_incoming[ids_node],
+@@ -999,15 +999,15 @@
+ if True:
+ #
+
+- print 79*'-'
+- print ' check node', id_node, nodes.ids_sumo[id_node], id_type, id_zippertype == id_type
+- print ' ids_edge_from', ids_edge_from
+- print ' ids_edge_to', ids_edge_to
++ print(79*'-')
++ print(' check node', id_node, nodes.ids_sumo[id_node], id_type, id_zippertype == id_type)
++ print(' ids_edge_from', ids_edge_from)
++ print(' ids_edge_to', ids_edge_to)
+ # id merge to be created, for debugging
+ id_merge = -1
+
+ if (ids_edge_from is None) | (ids_edge_to is None):
+- print ' WARNING: isolate node: ids_edge_from,ids_edge_to', ids_edge_from, ids_edge_to
++ print(' WARNING: isolate node: ids_edge_from,ids_edge_to', ids_edge_from, ids_edge_to)
+ pass
+
+ elif (len(ids_edge_from) == 2) & (len(ids_edge_to) == 1):
+@@ -1018,13 +1018,13 @@
+ # check accesslevels
+ id_edge1, id_edge2 = ids_edge_from
+ ids_lane1, ids_lane2 = edges.ids_lanes[ids_edge_from]
+- print ' id_edge1', id_edge1, 'ids_lane1', ids_lane1, self.is_prt_only(ids_lane1, lanes)
+- print ' id_edge2', id_edge2, 'ids_lane2', ids_lane2, self.is_prt_only(ids_lane2, lanes)
++ print(' id_edge1', id_edge1, 'ids_lane1', ids_lane1, self.is_prt_only(ids_lane1, lanes))
++ print(' id_edge2', id_edge2, 'ids_lane2', ids_lane2, self.is_prt_only(ids_lane2, lanes))
+ if self.is_prt_only(ids_lane1, lanes) & self.is_prt_only(ids_lane2, lanes):
+- print ' +PRT merge with 2 PRT lines entering'
++ print(' +PRT merge with 2 PRT lines entering')
+
+ if id_type != id_zippertype:
+- print 'WARNING: PRT network node %d %s is NOT in zipper mode!' % (id_node, nodes.ids_sumo[id_node])
++ print('WARNING: PRT network node %d %s is NOT in zipper mode!' % (id_node, nodes.ids_sumo[id_node]))
+
+ # elif not ids_mainlinedges.isdisjoint(ids_edge_from):
+ # print ' one incoming line is the bypass'
+@@ -1037,16 +1037,16 @@
+ # )
+
+ else:
+- print ' make regular merge'
+- print ' branch 1:'
++ print(' make regular merge')
++ print(' branch 1:')
+ id_node_up1, dist1 = self.search_upstream_merge(
+ id_edge1, edges, lanes, id_prtmode, distances=distances)
+- print ' id_node_up1', id_node_up1, 'dist1', dist1
+-
+- print '\n branch 2:'
++ print(' id_node_up1', id_node_up1, 'dist1', dist1)
++
++ print('\n branch 2:')
+ id_node_up2, dist2 = self.search_upstream_merge(
+ id_edge2, edges, lanes, id_prtmode, distances=distances)
+- print ' id_node_up2', id_node_up1, 'dist2', dist2, '\n'
++ print(' id_node_up2', id_node_up1, 'dist2', dist2, '\n')
+
+ ids_node_out = self.search_downstream_merges(
+ ids_edge_to[0], edges, lanes, id_prtmode, ids_sinkedge=ids_shuntedges)
+@@ -1066,7 +1066,7 @@
+ #al_in = lanes.get_accesslevel(edges.ids_lanes[id_edge_from], id_prtmode)
+ #is_prt_in = lanes.ids_modes_allow[edges.ids_lanes[id_edge_from]] == id_prtmode
+ is_prt_in = self.is_prt_only(ids_lane_in, lanes)
+- print ' one in, 2 out => diverge node, access is_prt_in', is_prt_in, 'is_platform_in', self.is_platform(ids_lane_in, lanes)
++ print(' one in, 2 out => diverge node, access is_prt_in', is_prt_in, 'is_platform_in', self.is_platform(ids_lane_in, lanes))
+
+ # if id_edge_from in ids_detectoredges:
+ # print ' fromnode is a detectoredge of a compressor'
+@@ -1081,7 +1081,7 @@
+ # check if node is outgoing node at a station
+ if 0: # no longer considered
+ if is_prt_in & (id_node in ids_mainlinefromnodes):
+- print ' Diverge node in front of a compressor/decompressorr.'
++ print(' Diverge node in front of a compressor/decompressorr.')
+ id_node_up, dist = self.search_upstream_merge(id_edge_from, edges, lanes, id_prtmode)
+
+ id_edge1, id_edge2 = ids_edge_to
+@@ -1100,19 +1100,19 @@
+ )
+
+ if self.is_platform(ids_lane_in, lanes):
+- print ' mixed access level of incoming edge, check for platform exit node'
++ print(' mixed access level of incoming edge, check for platform exit node')
+
+ id_edge1, id_edge2 = ids_edge_to
+ ids_lane1, ids_lane2 = edges.ids_lanes[ids_edge_to]
+
+ # here we could also decide on the number of lanes
+ # but this may not be robust in the future
+- print ' out id_edge1', id_edge1, 'ids_lane1', ids_lane1, 'is_prt_only', self.is_prt_only(ids_lane1, lanes)
+- print ' out id_edge2', id_edge2, 'ids_lane2', ids_lane2, 'is_prt_only', self.is_prt_only(ids_lane2, lanes)
++ print(' out id_edge1', id_edge1, 'ids_lane1', ids_lane1, 'is_prt_only', self.is_prt_only(ids_lane1, lanes))
++ print(' out id_edge2', id_edge2, 'ids_lane2', ids_lane2, 'is_prt_only', self.is_prt_only(ids_lane2, lanes))
+ # if self.is_prt_only(ids_lane1, lanes) & self.is_prt_only(ids_lane2, lanes):
+ if self.is_prt_only(ids_lane2, lanes):
+
+- print ' Ped exit on outedge 1'
++ print(' Ped exit on outedge 1')
+ #id_node_up, dist = self.search_upstream_merge(id_edge_from, edges, lanes, id_prtmode)
+ ids_node_out = self.search_downstream_merges(
+ id_edge2, edges, lanes, id_prtmode, ids_sinkedge=ids_shuntedges)
+@@ -1124,7 +1124,7 @@
+ )
+
+ elif self.is_prt_only(ids_lane1, lanes):
+- print ' Ped exit on outedge 2'
++ print(' Ped exit on outedge 2')
+ #id_node_up, dist = self.search_upstream_merge(id_edge_from, edges, lanes, id_prtmode)
+ ids_node_out = self.search_downstream_merges(
+ id_edge1, edges, lanes, id_prtmode, ids_sinkedge=ids_shuntedges)
+@@ -1137,7 +1137,7 @@
+
+ if id_merge >= 0:
+ self.print_attrs(ids=[id_merge, ])
+- print '\n now check if merge has entry line form stations or compressors'
++ print('\n now check if merge has entry line form stations or compressors')
+
+ ids = self.get_ids()
+ i = 0
+@@ -1146,21 +1146,21 @@
+
+ id_node_in1 = self.ids_node_in1[id_merge]
+ id_node_in2 = self.ids_node_in2[id_merge]
+- print 79*'-'
+- print ' check entry of id_merge', id_merge, 'id_node', self.ids_node[id_merge], ' no decomp', self.ids_node[id_merge] not in ids_node_decompressorout
++ print(79*'-')
++ print(' check entry of id_merge', id_merge, 'id_node', self.ids_node[id_merge], ' no decomp', self.ids_node[id_merge] not in ids_node_decompressorout)
+ if (id_node_in1 > -1) & (id_node_in2 > -1)\
+ & (self.ids_node[id_merge] not in ids_node_decompressorout):
+
+- print ' id_node_in1', self.ids_node_in1[id_merge], nodes.ids_sumo[self.ids_node_in1[id_merge]], self.ids_node.has_index(self.ids_node_in1[id_merge])
+- print ' id_node_in2', self.ids_node_in2[id_merge], nodes.ids_sumo[self.ids_node_in2[id_merge]], self.ids_node.has_index(self.ids_node_in2[id_merge])
++ print(' id_node_in1', self.ids_node_in1[id_merge], nodes.ids_sumo[self.ids_node_in1[id_merge]], self.ids_node.has_index(self.ids_node_in1[id_merge]))
++ print(' id_node_in2', self.ids_node_in2[id_merge], nodes.ids_sumo[self.ids_node_in2[id_merge]], self.ids_node.has_index(self.ids_node_in2[id_merge]))
+ if 1:
+
+- print ' self.ids_node._index_to_id', self.ids_node._index_to_id
++ print(' self.ids_node._index_to_id', self.ids_node._index_to_id)
+
+ id_merge_in1 = self.ids_node.get_id_from_index(self.ids_node_in1[id_merge])
+ id_merge_in2 = self.ids_node.get_id_from_index(self.ids_node_in2[id_merge])
+
+- print ' station check id_merge', id_merge, 'id_merge_in1', id_merge_in1, 'station', self.are_station[id_merge_in1], 'id_merge_in2', id_merge_in2, 'station', self.are_station[id_merge_in2]
++ print(' station check id_merge', id_merge, 'id_merge_in1', id_merge_in1, 'station', self.are_station[id_merge_in1], 'id_merge_in2', id_merge_in2, 'station', self.are_station[id_merge_in2])
+
+ if self.are_station[id_merge_in2]:
+ self.are_entry[id_merge] = True
+@@ -1186,7 +1186,7 @@
+ return self.parent.get_scenario()
+
+ def prepare_sim(self, process):
+- print 'Mergenodes.prepare_sim'
++ print('Mergenodes.prepare_sim')
+ net = self.get_scenario().net
+ nodes = net.nodes
+ edges = net.edges
+@@ -1294,8 +1294,8 @@
+
+ def process_step(self, process):
+ simtime = process.simtime
+- print 79*'_'
+- print 'Mergenodes.process_step at', simtime
++ print(79*'_')
++ print('Mergenodes.process_step at', simtime)
+ net = self.get_scenario().net
+ vehicles = self.parent.prtvehicles
+
+@@ -1311,7 +1311,7 @@
+ self.ids_vehs_out_sumo[ids],
+ self.are_entry[ids],
+ ):
+- print ' '+60*'.'
++ print(' '+60*'.')
+
+ ####
+ debug = False # id_merge in [24,22,19]
+@@ -1320,7 +1320,7 @@
+ #debug = debug | (id_merge==17)| ('gneJ29' in net.nodes.ids_sumo[ids_node_out])
+
+ ###
+- print ' process id_merge', id_merge, ',id_node', id_node, net.nodes.ids_sumo[id_node], 'debug', debug
++ print(' process id_merge', id_merge, ',id_node', id_node, net.nodes.ids_sumo[id_node], 'debug', debug)
+
+ # check for new vehicle arrivals/departures
+ ids_veh_sumo = set(traci.edge.getLastStepVehicleIDs(id_edge_out))
+@@ -1342,7 +1342,7 @@
+ #ids_veh_left = vehicles.get_ids_from_ids_sumo(list(ids_veh_sumo_prev.difference(ids_veh_sumo)))
+
+ if debug:
+- print ' ids_veh_entered', ids_veh_entered, type(ids_veh_entered)
++ print(' ids_veh_entered', ids_veh_entered, type(ids_veh_entered))
+ # print ' ids_veh_entered_sumo',ids_veh_entered_sumo
+ # print ' ids_leader',vehicles.ids_leader[ids_veh_entered]
+
+@@ -1367,11 +1367,11 @@
+ id_veh_first, id_veh_last = self.ids_plat_wait_exit[id_merge]
+ if id_veh_first > -1:
+ if debug > 0:
+- print ' platoon waiting for exit: id_veh_first prt.%d, id_veh_last prt.%d' % (id_veh_first, id_veh_last)
++ print(' platoon waiting for exit: id_veh_first prt.%d, id_veh_last prt.%d' % (id_veh_first, id_veh_last))
+ inds_entered = np.flatnonzero(vehicles.ids_leader[ids_veh_entered] > -1)
+ if np.any(id_veh_last == ids_veh_entered[inds_entered]):
+ if debug > 0:
+- print ' last vehicle of platoon left merge -> exit leader prt.%d' % id_veh_first
++ print(' last vehicle of platoon left merge -> exit leader prt.%d' % id_veh_first)
+ self.exit_veh(id_veh_first, vehicles.get_id_sumo(id_veh_first), id_merge, vehicles, debug=debug)
+ self.ids_plat_wait_exit[id_merge] = [-1, -1]
+
+@@ -1383,13 +1383,13 @@
+ inds_entered = []
+
+ if debug:
+- print ' inds_entered', inds_entered
++ print(' inds_entered', inds_entered)
+ if len(inds_entered) > 0:
+ for ind_entered, id_veh in zip(inds_entered, ids_veh_entered[inds_entered]):
+
+ id_veh_sumo = ids_veh_entered_sumo[ind_entered]
+ if debug > 0:
+- print ' >>try exiting vehicle', id_veh_sumo, 'is_leader', vehicles.ids_leader[id_veh] == -1, 'ids_node_out', ids_node_out, 'ids_merge_out', ids_merge_out
++ print(' >>try exiting vehicle', id_veh_sumo, 'is_leader', vehicles.ids_leader[id_veh] == -1, 'ids_node_out', ids_node_out, 'ids_merge_out', ids_merge_out)
+
+ # print ' route_sumo',route_sumo
+
+@@ -1400,15 +1400,15 @@
+ if (id_veh_last != id_veh):
+ if id_veh_last not in ids_veh_entered:
+ if debug:
+- print ' wait for last plat vehicle', id_veh_last
++ print(' wait for last plat vehicle', id_veh_last)
+ self.ids_plat_wait_exit[id_merge] = [id_veh, id_veh_last]
+ else:
+ if debug:
+- print ' last plat vehicle', id_veh_last, 'after merge node, exit', id_veh_sumo
++ print(' last plat vehicle', id_veh_last, 'after merge node, exit', id_veh_sumo)
+ self.exit_veh(id_veh, id_veh_sumo, id_merge, vehicles, debug=debug)
+ else:
+ if debug:
+- print ' vehicle', id_veh, 'has no platoon, exit', id_veh_sumo
++ print(' vehicle', id_veh, 'has no platoon, exit', id_veh_sumo)
+ self.exit_veh(id_veh, id_veh_sumo, id_merge, vehicles, debug=debug)
+
+ # exit from previous merge
+@@ -1416,7 +1416,7 @@
+ # print ' vehicle',id_veh_sumo,'exits id_merge',id_merge
+
+ if debug > 0:
+- print ' check which out mergenode are on the current route of the vehicle'
++ print(' check which out mergenode are on the current route of the vehicle')
+
+ if len(ids_merge_out) > 0:
+
+@@ -1438,23 +1438,23 @@
+ mergeind = np.argmin(routeinds)
+
+ if debug: # debug>0:
+- print ' route_sumo', route_sumo
+- print ' routeinds', routeinds, 'downstream merge', routeinds[mergeind] < INFINT
++ print(' route_sumo', route_sumo)
++ print(' routeinds', routeinds, 'downstream merge', routeinds[mergeind] < INFINT)
+ # print ' ids_edge_mergeout_sumo',ids_edge_mergeout_sumo
+ # print ' mergeind,routeinds',mergeind,routeinds
+ # print ' ids_merge_out[mergeind]',ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind]
+
+ if routeinds[mergeind] < INFINT:
+ if debug:
+- print ' next merge is on the route'
++ print(' next merge is on the route')
+ if self.are_entry[ids_merge_out[mergeind]]:
+ if debug:
+- print ' call enter_veh_entry id_merge_out', ids_merge_out[mergeind]
++ print(' call enter_veh_entry id_merge_out', ids_merge_out[mergeind])
+ self.enter_veh_entry(
+ id_veh, id_veh_sumo, id_merge, ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind], vehicles, debug=debug)
+ else:
+ if debug:
+- print ' call enter_veh id_merge_out', ids_merge_out[mergeind]
++ print(' call enter_veh id_merge_out', ids_merge_out[mergeind])
+ self.enter_veh(
+ id_veh, id_veh_sumo, id_merge, ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind], vehicles, debug=debug)
+ else:
+@@ -1467,8 +1467,8 @@
+ else:
+ # ids_node_out is None
+ if debug:
+- print ' There is a station or compressor shunt edges next'
+- print ' completely disconnect from all merge and ghost controlls'
++ print(' There is a station or compressor shunt edges next')
++ print(' completely disconnect from all merge and ghost controlls')
+
+ # exit from previous merge
+ self.exit_veh(id_veh, id_veh_sumo, id_merge, vehicles)
+@@ -1481,7 +1481,7 @@
+ self.process_step_entry(id_merge, vehicles, debug)
+
+ if 0:
+- print '========check mergeprocess'
++ print('========check mergeprocess')
+ for id_merge, id_node_sumo, ids_veh_merged_sumo, ids_veh_merged in\
+ zip(ids,
+ net.nodes.ids_sumo[self.ids_node[ids]],
+@@ -1489,11 +1489,11 @@
+ self.ids_vehs_merged[ids]
+ ):
+
+- print ' ', id_merge, id_node_sumo, ids_veh_merged_sumo
++ print(' ', id_merge, id_node_sumo, ids_veh_merged_sumo)
+ # print ' ids_veh_merged',ids_veh_merged
+
+ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_control=False, debug=0):
+- print 'exit_veh id_veh %s, id_merge_from %d ' % (id_veh_sumo, id_merge_from), 'entry', self.are_entry[id_merge_from], 'is_remove_from_control', is_remove_from_control
++ print('exit_veh id_veh %s, id_merge_from %d ' % (id_veh_sumo, id_merge_from), 'entry', self.are_entry[id_merge_from], 'is_remove_from_control', is_remove_from_control)
+
+ # print ' check for platooned vehicles:'
+ # vehicles.get_platoon(id_veh)
+@@ -1519,10 +1519,10 @@
+ id_veh_behind = self.ids_vehs_merged[id_merge_from][ind_pos+1]
+ id_veh_tail = vehicles.get_platoontail(id_veh) # get last in platoon
+ if debug > 0:
+- print ' del ghost from veh behind prt.%d to platoon tail prt.%d' % (id_veh_behind, id_veh_tail)
++ print(' del ghost from veh behind prt.%d to platoon tail prt.%d' % (id_veh_behind, id_veh_tail))
+ vehicles.del_ghost(id_veh_behind, id_veh_tail)
+ if debug > 0:
+- print ' check ghosts of behind prt.%d:' % id_veh_behind, vehicles.ids_ghosts[id_veh_behind]
++ print(' check ghosts of behind prt.%d:' % id_veh_behind, vehicles.ids_ghosts[id_veh_behind])
+ # is there a vehicle in front of the removed vehicle
+ # this happens if a vehicle is interactively deviated
+ if ind_pos > 0:
+@@ -1536,18 +1536,18 @@
+ dist_to_merge_infront = get_traci_distance(
+ vehicles.get_id_sumo(id_veh_infront), id_edge_mergeout_sumo, 3.0)
+ if debug:
+- print ' now let the vehicle behind %d, d=%.2f' % (id_veh_behind, dist_to_merge_behind), 'see the vehicle in front %d, d=%.2f' % (id_veh_infront, dist_to_merge_infront)
++ print(' now let the vehicle behind %d, d=%.2f' % (id_veh_behind, dist_to_merge_behind), 'see the vehicle in front %d, d=%.2f' % (id_veh_infront, dist_to_merge_infront))
+
+ vehicles.add_ghost(id_veh_behind, id_veh_tail, dist_to_merge_behind, dist_to_merge_infront)
+ if debug > 0:
+- print ' check ghosts of behind prt.%d:' % id_veh_behind, vehicles.ids_ghosts[id_veh_behind]
++ print(' check ghosts of behind prt.%d:' % id_veh_behind, vehicles.ids_ghosts[id_veh_behind])
+
+ # remove any possible ghosts from this vehicle to vehicles behind
+ # this can happen if this vehicle passed by its ghost vehicle
+ # should no longer happen
+ # vehicles.del_ghosts(id_veh)
+ if debug > 0:
+- print ' check ghosts of prt.%d (no ghosts from this merge?):' % id_veh, vehicles.ids_ghosts[id_veh]
++ print(' check ghosts of prt.%d (no ghosts from this merge?):' % id_veh, vehicles.ids_ghosts[id_veh])
+
+ self.ids_vehs_merged[id_merge_from].pop(ind_pos) # remove(id_veh)
+ self.ids_vehs_merged_sumo[id_merge_from].pop(ind_pos) # remove(id_veh_sumo)
+@@ -1561,31 +1561,31 @@
+ self.ids_vehs_in1_sumo[id_merge_from].remove(id_veh_sumo) # .pop()
+ if self.are_entry[id_merge_from]:
+ if debug:
+- print ' vehicle is involved in entry merge processes?', self.vehicles_mains[id_merge_from].has_key(id_veh)
+-
+- if self.vehicles_mains[id_merge_from].has_key(id_veh):
+- if self.vehicles_entries[id_merge_from].has_key(id_veh):
++ print(' vehicle is involved in entry merge processes?', id_veh in self.vehicles_mains[id_merge_from])
++
++ if id_veh in self.vehicles_mains[id_merge_from]:
++ if id_veh in self.vehicles_entries[id_merge_from]:
+ state_veh = self.vehicles_entries[id_merge_from][id_veh]
+- if state.has_key('id_veh_infront'):
++ if 'id_veh_infront' in state:
+ id_veh_infront = state['id_veh_infront']
+ id_veh_infront_sumo = vehicles.ids_sumo[id_veh_infront]
+ id_veh_infront_sumo_eff, dist_eff = getLeader(id_veh_infront_sumo)
+- print ' should have this veh in front:', id_veh_infront_sumo, 'leader', id_veh_infront_sumo_eff, 'd=%.1fm' % dist_eff
++ print(' should have this veh in front:', id_veh_infront_sumo, 'leader', id_veh_infront_sumo_eff, 'd=%.1fm' % dist_eff)
+ if id_veh_infront_sumo_eff != id_veh_infront_sumo:
+- print 'ERROR: faled merge of ', id_veh_sumo, 'exiting merge', id_merge_from
++ print('ERROR: faled merge of ', id_veh_sumo, 'exiting merge', id_merge_from)
+ sys.exit(1)
+ #
+ #id_veh_entry = self.vehicles_mains[id_merge_from][id_veh]
+
+ # TODO: this is still a lousy method, vehicles_mains neds to be improved
+- for id_veh_entry, state in zip(self.vehicles_entries[id_merge_from].keys(), self.vehicles_entries[id_merge_from].values()):
++ for id_veh_entry, state in zip(list(self.vehicles_entries[id_merge_from].keys()), list(self.vehicles_entries[id_merge_from].values())):
+ #state = self.vehicles_entries[id_merge_from][id_veh_entry]
+ # if debug:
+ # print ' state before',state
+- if state.has_key('id_veh_infront'):
++ if 'id_veh_infront' in state:
+ if state['id_veh_infront'] == id_veh:
+ del state['id_veh_infront']
+- if state.has_key('id_veh_behind'):
++ if 'id_veh_behind' in state:
+ if state['id_veh_behind'] == id_veh:
+ del state['id_veh_behind']
+ # if debug:
+@@ -1600,7 +1600,7 @@
+
+ if self.are_entry[id_merge_from]:
+ if debug:
+- print ' del veh prt.%s from vehicles_entries' % id_veh
++ print(' del veh prt.%s from vehicles_entries' % id_veh)
+ del self.vehicles_entries[id_merge_from][id_veh]
+ else:
+ pass
+@@ -1615,12 +1615,12 @@
+ # just be sure that the vehicle is not in any queue
+ # but actually this cannot happen
+ if id_veh in self.ids_vehs_in1[id_merge_from]:
+- print 'WARNING in exit_veh: new veh %d should not be in inqueue 1' % id_veh
++ print('WARNING in exit_veh: new veh %d should not be in inqueue 1' % id_veh)
+ self.ids_vehs_in1[id_merge_from].remove(id_veh)
+ self.ids_vehs_in1_sumo[id_merge_from].remove(id_veh_sumo)
+
+ if id_veh in self.ids_vehs_in2[id_merge_from]:
+- print 'WARNING in exit_veh: new veh %d should not be in inqueue 2' % id_veh
++ print('WARNING in exit_veh: new veh %d should not be in inqueue 2' % id_veh)
+ self.ids_vehs_in2[id_merge_from].remove(id_veh)
+ self.ids_vehs_in2_sumo[id_merge_from].remove(id_veh_sumo)
+
+@@ -1633,7 +1633,7 @@
+
+ def exit_veh_forced(self, id_veh, id_veh_sumo, vehicles):
+ """Used by decompressors to remove a vehicle from merge control"""
+- if self.vehicle_to_merge.has_key(id_veh):
++ if id_veh in self.vehicle_to_merge:
+ # exit vehicle from respective merge
+ self.exit_veh(id_veh, id_veh_sumo, self.vehicle_to_merge[id_veh], vehicles, is_remove_from_control=True)
+ else:
+@@ -1645,34 +1645,34 @@
+ dist_max = max(dist1_min, dist1_max, dist2_min, dist2_max)+1
+ #dist_min = min(dist1_min, dist1_max, dist2_min, dist2_max)
+ #dist_diff = dist_max-dist_min+10.0
+- print 'print_vehs id_veh1', id_veh1, 'id_veh2', id_veh2
++ print('print_vehs id_veh1', id_veh1, 'id_veh2', id_veh2)
+ # print ' dist1_min',dist1_min,'dist1_max',dist1_max
+ # print ' dist2_min',dist2_min,'dist2_max',dist2_max
+ # print ' min[dist1_min, dist1_max, dist2_min, dist2_max]>0.01',np.min([dist1_min, dist1_max, dist2_min, dist2_max])>0.01
+ if np.min([dist1_min, dist1_max, dist2_min, dist2_max]) > 0.01:
+ f = float(pos_max)/dist_max
+ # print ' f',f
+- print '________________________'
+- print 'vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max)
++ print('________________________')
++ print('vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max))
+ pos_min = int(dist1_min*f)
+ pos_max = int(dist1_max*f)
+- print max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|'
++ print(max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|')
+
+ pos_min = int(dist2_min*f)
+ pos_max = int(dist2_max*f)
+ # print ' pos_min',pos_min
+ # print ' pos_max',pos_max
+ # print ' max(pos_min-1,0)',max(pos_min-1,0),'(pos_max-pos_min)',(pos_max-pos_min)
+- print max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|'
+- print 'vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max)
+- print '________________________'
++ print(max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|')
++ print('vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max))
++ print('________________________')
+ else:
+- print 'WARNING: some negative distances:'
+- print 'vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max)
+- print 'vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max)
++ print('WARNING: some negative distances:')
++ print('vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max))
++ print('vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max))
+
+ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_merge_sumo, vehicles, debug=0):
+- print 'enter_veh id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to)
++ print('enter_veh id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to))
+
+ # in id_merge_from: take vehicle out of merged queue and input queue
+
+@@ -1709,7 +1709,7 @@
+
+ if indpos == -1:
+ # vehicle is new and must be merged into ids_vehs_merged
+- print ' merge prt.%d' % id_veh, 'lineind', lineind, 'dtm %.1fm' % dist_tomerge_head_new, 'n_plat', vehicles.get_platoonsize(id_veh), vehicles.lengths_plat[id_veh]/vehicles.length
++ print(' merge prt.%d' % id_veh, 'lineind', lineind, 'dtm %.1fm' % dist_tomerge_head_new, 'n_plat', vehicles.get_platoonsize(id_veh), vehicles.lengths_plat[id_veh]/vehicles.length)
+
+ ids_vehs_merged = self.ids_vehs_merged[id_merge_to]
+ ids_vehs_merged_sumo = self.ids_vehs_merged_sumo[id_merge_to]
+@@ -1720,11 +1720,11 @@
+ is_insert = False
+ id_veh_merged = -1
+ if debug > 0:
+- print ' ids_vehs_merged_sumo[%d]' % id_merge_to, ids_vehs_merged_sumo
+- print ' lineinds_vehs_merged[%d]' % id_merge_to, lineinds_vehs_merged
++ print(' ids_vehs_merged_sumo[%d]' % id_merge_to, ids_vehs_merged_sumo)
++ print(' lineinds_vehs_merged[%d]' % id_merge_to, lineinds_vehs_merged)
+ if (ind_insert == 0) | self.are_station[id_merge_to]:
+ if debug > 0:
+- print ' new vehicle is the only vehicle or station', ind_insert, self.are_station[id_merge_to]
++ print(' new vehicle is the only vehicle or station', ind_insert, self.are_station[id_merge_to])
+
+ # vehicles heading toward a station merge are not
+ # really merged because only one incoming line
+@@ -1740,7 +1740,7 @@
+
+ if debug > 0:
+ dist_tomerge_head_new2 = get_traci_distance(id_veh_sumo, id_edge_merge_sumo, 3.0)
+- print ' compare dist_tomerge_head_new', dist_tomerge_head_new, 'dist_tomerge_head_new2', dist_tomerge_head_new2
++ print(' compare dist_tomerge_head_new', dist_tomerge_head_new, 'dist_tomerge_head_new2', dist_tomerge_head_new2)
+
+ # get back to traci distance measurement
+ dist_tomerge_head_new = get_traci_distance(id_veh_sumo, id_edge_merge_sumo, 3.0)
+@@ -1752,11 +1752,11 @@
+ #dist_tomerge_tail_new = get_traci_distance(id_veh_tail_new_sumo, id_edge_merge_sumo, 3.0)
+
+ if debug > 0:
+- print ' new prt.%d arriving from in %d at dist head %.2f /__| tail prt.%d %.2fm' % (id_veh, lineind, dist_tomerge_head_new, id_veh_tail_new, dist_tomerge_tail_new)
+- print ' ids_vehs_merged_sumo', ids_vehs_merged_sumo
++ print(' new prt.%d arriving from in %d at dist head %.2f /__| tail prt.%d %.2fm' % (id_veh, lineind, dist_tomerge_head_new, id_veh_tail_new, dist_tomerge_tail_new))
++ print(' ids_vehs_merged_sumo', ids_vehs_merged_sumo)
+ for id_veh_merged, id_veh_merged_sumo, odo, lineind_merge in zip(ids_vehs_merged[::-1], ids_vehs_merged_sumo[::-1], odos_veh_merged[::-1], lineinds_vehs_merged[::-1]):
+ if debug > 0:
+- print ' id_veh_merged_sumo', id_veh_merged_sumo
++ print(' id_veh_merged_sumo', id_veh_merged_sumo)
+ # unprecise
+ #dist_tomerge_head2 = get_traci_distance(id_veh_merged_sumo, id_edge_merge_sumo, 3.0)
+
+@@ -1769,7 +1769,7 @@
+
+ if debug > 0:
+ dist_tomerge_head2 = get_traci_distance(id_veh_merged_sumo, id_edge_merge_sumo, 3.0)
+- print ' compare', id_veh_merged_sumo, ' dist_tomerge_head %.1f' % dist_tomerge_head, 'dist_tomerge_head2 %.1f' % dist_tomerge_head2
++ print(' compare', id_veh_merged_sumo, ' dist_tomerge_head %.1f' % dist_tomerge_head, 'dist_tomerge_head2 %.1f' % dist_tomerge_head2)
+
+ # get back to traci distance measurement
+ dist_tomerge_head = get_traci_distance(id_veh_merged_sumo, id_edge_merge_sumo, 3.0)
+@@ -1778,7 +1778,7 @@
+ else:
+ dist_node = self.distances_node_in2[id_merge_to]
+ if debug > 0:
+- print ' M:odo_enter=%.1f odo=%.1f delta=%.f dist_node=%.1f line%d platl=%d' % (odo, get_traci_odo(id_veh_merged_sumo), get_traci_odo(id_veh_merged_sumo)-odo, dist_node, lineind_merge, vehicles.lengths_plat[id_veh_merged])
++ print(' M:odo_enter=%.1f odo=%.1f delta=%.f dist_node=%.1f line%d platl=%d' % (odo, get_traci_odo(id_veh_merged_sumo), get_traci_odo(id_veh_merged_sumo)-odo, dist_node, lineind_merge, vehicles.lengths_plat[id_veh_merged]))
+
+ #stoppeddist_tomerge = dist-0.5/self.decel*get_traci_velocity(id_veh_merged_sumo)**2+vehicles.lengths_plat[id_veh]
+ #stoppeddist_tomerge = dist+vehicles.lengths_plat[id_veh]
+@@ -1789,7 +1789,7 @@
+ dist_tomerge_tail = get_traci_distance(id_veh_tail_sumo, id_edge_merge_sumo, 3.0)
+ #dist_tomerge_tail = dist_tomerge_head + vehicles.lengths_plat[id_veh_merged]+vehicles.length
+ if debug > 0:
+- print ' compare lineind_merge', lineind_merge, '=?', lineinds_vehs_merged[ind_insert-1]
++ print(' compare lineind_merge', lineind_merge, '=?', lineinds_vehs_merged[ind_insert-1])
+
+ if debug > 0:
+ self.print_vehs(id_veh, id_veh_merged,
+@@ -1803,13 +1803,13 @@
+
+ if lineind == lineinds_vehs_merged[ind_insert-1]: # get this from
+ if debug > 0:
+- print ' vehicle in front on same branch'
++ print(' vehicle in front on same branch')
+ is_insert = True
+ break
+
+ if dist_tomerge_tail_new > dist_tomerge_tail:
+ if debug > 0:
+- print ' distance of tail to merge of new vehicle is greater than existing'
++ print(' distance of tail to merge of new vehicle is greater than existing')
+ # print ' =>insert new %s after existing %s'%(id_veh_sumo,id_veh_merged_sumo)
+ is_insert = True
+ break
+@@ -1819,11 +1819,11 @@
+ if is_insert:
+ # at least one vehicle is in front
+ if debug > 0:
+- print ' insert veh %d behind veh %d, index %d' % (id_veh, id_veh_merged, ind_insert)
++ print(' insert veh %d behind veh %d, index %d' % (id_veh, id_veh_merged, ind_insert))
+ # send control info to involved vehicles
+ if ind_insert == len(ids_vehs_merged):
+ if debug > 0:
+- print ' appended vehicle after veh', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail
++ print(' appended vehicle after veh', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail)
+ # V
+ # |
+ # G ind_insert-1
+@@ -1847,7 +1847,7 @@
+ #id_ghost2 = ids_vehs_merged[ind_insert-1]
+ id_ghost2 = id_veh_tail
+ if debug > 0:
+- print ' vehicle will be inserted in front of', ids_vehs_merged_sumo[ind_insert], 'and in behind', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail
++ print(' vehicle will be inserted in front of', ids_vehs_merged_sumo[ind_insert], 'and in behind', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail)
+
+ vehicles.del_ghost(id_ghost1, id_ghost2)
+ if lineinds_vehs_merged[ind_insert] != lineind:
+@@ -1859,7 +1859,7 @@
+
+ else:
+ if debug > 0:
+- print ' prepend prt.%d in front of prt.%d, first index %d' % (id_veh, id_veh_merged, ind_insert)
++ print(' prepend prt.%d in front of prt.%d, first index %d' % (id_veh, id_veh_merged, ind_insert))
+ # is vehicle and ghost in the same input line?
+ if lineinds_vehs_merged[ind_insert] != lineind:
+ id_veh_behind = ids_vehs_merged[ind_insert] # last veh in queue
+@@ -1880,7 +1880,7 @@
+ # lineinds_vehs_merged[0] = lineind
+
+ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_merge_sumo, vehicles, debug=0):
+- print 'enter_veh_entry id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to)
++ print('enter_veh_entry id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to))
+
+ # in id_merge_from: take vehicle out of merged queue and input queue
+
+@@ -1913,8 +1913,8 @@
+ if lineind == 1:
+ # from line 1 (main line)
+ if debug > 0:
+- print ' Detected veh', id_veh_sumo, 'on mainline. Is new', indpos == -1
+- print ' check for platooned vehicles:', vehicles.get_platoon(id_veh)
++ print(' Detected veh', id_veh_sumo, 'on mainline. Is new', indpos == -1)
++ print(' check for platooned vehicles:', vehicles.get_platoon(id_veh))
+
+ id_edge_out_sumo = self.ids_merge_to_ids_edge_out_sumo[id_merge_to]
+ dist_tomerge = get_traci_distance(id_veh_sumo, id_edge_out_sumo, 3.0)
+@@ -1926,18 +1926,18 @@
+
+ id_veh2, state2 = self.get_mergeveh_entry(id_merge_to, debug)
+ if debug > 0:
+- print ' Conflict vehicle from entry line: prt.%d state' % (id_veh2,), state2
+- print ' Main line: ids_vehs_in1', ids_vehs_in1
+- print ' id_veh1_last', id_veh1_last
+- print ' dist_tomerge', dist_tomerge
++ print(' Conflict vehicle from entry line: prt.%d state' % (id_veh2,), state2)
++ print(' Main line: ids_vehs_in1', ids_vehs_in1)
++ print(' id_veh1_last', id_veh1_last)
++ print(' dist_tomerge', dist_tomerge)
+
+ if id_veh2 == -1:
+ if debug > 0:
+- print ' no vehicle to merge'
++ print(' no vehicle to merge')
+
+ if id_veh1_last != -1:
+ if debug > 0:
+- print ' control distance to last vehicle in main...by SUMO'
++ print(' control distance to last vehicle in main...by SUMO')
+ pass
+ #
+ #id_veh_tail = vehicles.get_platoontail(id_veh1_last)
+@@ -1949,15 +1949,15 @@
+
+ else:
+ if debug > 0:
+- print ' merge is empty'
++ print(' merge is empty')
+ pass
+
+ elif state2['status'] != 'wait':
+ # there is an approaching vehicle on entry line
+ if state2['status'] == 'accelerate':
+ if debug > 0:
+- print ' conflict vehicle in acceleration mode', 'is veh behind', state2.has_key('id_veh_behind')
+- if state2.has_key('id_veh_behind'):
++ print(' conflict vehicle in acceleration mode', 'is veh behind', 'id_veh_behind' in state2)
++ if 'id_veh_behind' in state2:
+ # accelerating vehicle has already a vehicle
+ # in front of which to merge
+ # => look at last vehicle
+@@ -1971,8 +1971,8 @@
+
+ if state2['status'] == 'sync':
+ if debug > 0:
+- print ' conflict vehicle in sync mode'
+- if state2.has_key('id_veh_behind'):
++ print(' conflict vehicle in sync mode')
++ if 'id_veh_behind' in state2:
+ # accelerating vehicle has already a vehicle
+ # in front of which to merge
+ # => look at last vehicle
+@@ -1987,7 +1987,7 @@
+ id_veh_tail = vehicles.get_platoontail(id_veh2)
+ id_veh_tail_sumo = vehicles.ids_sumo[id_veh_tail]
+ dist_tomerge_tail = get_traci_distance(id_veh_tail_sumo, id_edge_out_sumo, 3.0)
+- print ' let look the new vehicle prt.%d look at the tail of the entering vehicle prt.%d' % (id_veh, id_veh_tail)
++ print(' let look the new vehicle prt.%d look at the tail of the entering vehicle prt.%d' % (id_veh, id_veh_tail))
+ vehicles.add_ghost(id_veh, id_veh_tail, dist_tomerge, dist_tomerge_tail)
+
+ # let the entering vehicle see the new vehicle
+@@ -2004,12 +2004,12 @@
+
+ elif lineind == 2:
+ # from line 2 (entry line)
+- print ' Detected veh', id_veh_sumo, 'on entry line. Is new', indpos == -1
++ print(' Detected veh', id_veh_sumo, 'on entry line. Is new', indpos == -1)
+
+ self.ids_vehs_in2[id_merge_to].append(id_veh)
+ self.ids_vehs_in2_sumo[id_merge_to].append(id_veh_sumo)
+
+- print ' command vehicle to stop and wait further instructions'
++ print(' command vehicle to stop and wait further instructions')
+ #vehicles.control_slow_down(id_veh, speed = 6.0/3.6)
+ #traci.vehicle.setMaxSpeed(id_veh_sumo, 6.0/3.6)
+ # print ' set speed to',traci.vehicle.getMaxSpeed(id_veh_sumo)
+@@ -2019,9 +2019,9 @@
+
+ # prevent SUMO from reaccelerating vehicle
+ # vehicles.switch_off_control(id_veh)
+- print ' set veh id_veh prt.%d' % id_veh
++ print(' set veh id_veh prt.%d' % id_veh)
+ self.vehicles_entries[id_merge_to][id_veh] = {'status': 'wait'}
+- print ' vehicles_entries[', id_merge_to, ']=', self.vehicles_entries[id_merge_to]
++ print(' vehicles_entries[', id_merge_to, ']=', self.vehicles_entries[id_merge_to])
+ #
+ # self.vehicles_mains[id_merge_to][id_veh] = {}# later when used
+
+@@ -2038,14 +2038,14 @@
+
+ vehicles_entries = self.vehicles_entries[id_merge]
+ if debug > 0:
+- print 'get_mergeveh_entry vehicles_entries', vehicles_entries
++ print('get_mergeveh_entry vehicles_entries', vehicles_entries)
+ if len(vehicles_entries) == 0:
+ return -1, {'status': 'wait'}
+ else:
+- return vehicles_entries.keys()[0], vehicles_entries.values()[0]
++ return list(vehicles_entries.keys())[0], list(vehicles_entries.values())[0]
+
+ def process_step_entry(self, id_merge, vehicles, debug):
+- print 'process_step_entry id_merge', id_merge
++ print('process_step_entry id_merge', id_merge)
+
+ #self.vehicles_entries[id_merge]= OrderedDict()
+ # self.vehicles_mains[id_merge] = OrderedDict()
+@@ -2054,16 +2054,16 @@
+ # for id_veh, state in zip(self.vehicles_entries[id_merge].keys()[::-1],self.vehicles_entries[id_merge].values()[::-1]):
+ # for id_veh, state in self.vehicles_entries.iteritems():
+ # for id_veh, state in zip(self.vehicles_entries[id_merge].keys(),self.vehicles_entries[id_merge].values()):
+- ids_veh_entry = self.vehicles_entries[id_merge].keys()
+- states_veh_entry = self.vehicles_entries[id_merge].values()
++ ids_veh_entry = list(self.vehicles_entries[id_merge].keys())
++ states_veh_entry = list(self.vehicles_entries[id_merge].values())
+ id_edge_out_sumo = self.ids_merge_to_ids_edge_out_sumo[id_merge]
+ ids_veh_in1 = self.ids_vehs_in1[id_merge]
+ time_update = self.time_update.get_value()
+
+ if debug:
+- print ' vehicles_entries=', self.vehicles_entries[id_merge]
+- print ' vehicles_mains', self.vehicles_mains[id_merge]
+- print ' ids_veh_in1', ids_veh_in1
++ print(' vehicles_entries=', self.vehicles_entries[id_merge])
++ print(' vehicles_mains', self.vehicles_mains[id_merge])
++ print(' ids_veh_in1', ids_veh_in1)
+
+ i = 0
+ #is_cont = len(ids_veh_entry)>0
+@@ -2078,7 +2078,7 @@
+ lineinds_vehs_merged = self.lineinds_vehs_merged[id_merge]
+ odos_veh_merged = self.odos_vehs_merged[id_merge]
+ if debug:
+- print ' check id_veh_sumo', id_veh_sumo, 'status', state['status'], 'n vehs on main', len(ids_veh_in1)
++ print(' check id_veh_sumo', id_veh_sumo, 'status', state['status'], 'n vehs on main', len(ids_veh_in1))
+ if state['status'] == 'wait':
+ if traci.vehicle.isStopped(id_veh_sumo):
+ # check potential conflict vehicle on main line
+@@ -2086,7 +2086,7 @@
+ n1 = len(ids_veh_in1)
+ if n1 == 0:
+ if debug:
+- print ' main line is empty => accelerate immediately'
++ print(' main line is empty => accelerate immediately')
+ for id_veh_plat in vehicles.get_platoon(id_veh):
+ vehicles.control_speedup(id_veh_plat)
+ state['status'] = 'accelerate'
+@@ -2108,7 +2108,7 @@
+ id_veh1_sumo = ids_veh_in1_sumo[i]
+ id_veh1 = ids_veh_in1[i]
+ if debug:
+- print ' check', id_veh1_sumo, 'free', id_veh1 not in vehicles_main
++ print(' check', id_veh1_sumo, 'free', id_veh1 not in vehicles_main)
+
+ if True: # id_veh1 not in vehicles_main:
+
+@@ -2124,7 +2124,7 @@
+ dist_in1, dist_in2,
+ vehicles)
+ if debug:
+- print ' potential veh %s (tail %s)' % (id_veh1_sumo, id_veh1_tail_sumo), 'at pos1_tail=%.1f>p_to=%.1f' % (pos1_tail, p_to), pos1_tail > p_to
++ print(' potential veh %s (tail %s)' % (id_veh1_sumo, id_veh1_tail_sumo), 'at pos1_tail=%.1f>p_to=%.1f' % (pos1_tail, p_to), pos1_tail > p_to)
+
+ # here we check whether the tail of the vehicle on the main line
+ # has passed the critical point p_to
+@@ -2133,9 +2133,9 @@
+
+ if i == n1-1: # last vehicle on main
+ if debug:
+- print ' insert id_veh', id_veh_sumo, 'behind id_veh1', id_veh1_sumo, 'the only veh on main'
++ print(' insert id_veh', id_veh_sumo, 'behind id_veh1', id_veh1_sumo, 'the only veh on main')
+ state['id_veh_infront'] = id_veh1
+- if vehicles_main.has_key(id_veh1):
++ if id_veh1 in vehicles_main:
+ vehicles_main[id_veh1]['id_veh_behind'] = id_veh
+ else:
+ vehicles_main[id_veh1] = {'id_veh_behind': id_veh}
+@@ -2151,18 +2151,18 @@
+ id_veh_behind_sumo = vehicles.ids_sumo[id_veh_behind]
+ pos1 = dist_in1 - get_traci_distance(id_veh_behind_sumo, id_edge_out_sumo, 3.0)
+ if debug:
+- print ' vehicle behind', id_veh_behind_sumo, 'pos=%.1f, p_from=%.1f' % (pos1, p_from), 'ok', pos1 < p_from
++ print(' vehicle behind', id_veh_behind_sumo, 'pos=%.1f, p_from=%.1f' % (pos1, p_from), 'ok', pos1 < p_from)
+ if pos1 < p_from:
+ state['id_veh_infront'] = id_veh1
+ state['id_veh_behind'] = id_veh_behind
+
+ #vehicles_main[id_veh_behind] = id_veh
+- if vehicles_main.has_key(id_veh1):
++ if id_veh1 in vehicles_main:
+ vehicles_main[id_veh1]['id_veh_behind'] = id_veh
+ else:
+ vehicles_main[id_veh1] = {'id_veh_behind': id_veh}
+ #vehicles_main[id_veh1] = id_veh
+- if vehicles_main.has_key(id_veh_behind):
++ if id_veh_behind in vehicles_main:
+ vehicles_main[id_veh_behind]['id_veh_infront'] = id_veh
+ else:
+ vehicles_main[id_veh_behind] = {'id_veh_infront': id_veh}
+@@ -2170,7 +2170,7 @@
+ is_found = True
+ j = ids_vehs_merged.index(id_veh1)+1
+ if debug:
+- print ' j=', j
++ print(' j=', j)
+ ids_vehs_merged.insert(j, id_veh)
+ ids_vehs_merged_sumo.insert(j, id_veh_sumo)
+ lineinds_vehs_merged.insert(j, 2)
+@@ -2181,10 +2181,10 @@
+ elif pos1 < p_from:
+ if i == 0: # first vehicle on main
+ if debug:
+- print ' insert id_veh', id_veh_sumo, 'in front of id_veh1', id_veh1_sumo, 'the only veh on main'
++ print(' insert id_veh', id_veh_sumo, 'in front of id_veh1', id_veh1_sumo, 'the only veh on main')
+ state['id_veh_behind'] = id_veh1
+ #vehicles_main[id_veh1] = id_veh
+- if vehicles_main.has_key(id_veh1):
++ if id_veh1 in vehicles_main:
+ vehicles_main[id_veh1]['id_veh_infront'] = id_veh
+ else:
+ vehicles_main[id_veh1] = {'id_veh_infront': id_veh}
+@@ -2198,7 +2198,7 @@
+ lineinds_vehs_merged.insert(j, 2)
+ odos_veh_merged.insert(j, get_traci_odo(id_veh_sumo))
+ if debug:
+- print ' ids_vehs_merged_sumo', ids_vehs_merged_sumo
++ print(' ids_vehs_merged_sumo', ids_vehs_merged_sumo)
+ # elif i < n1-1: # there are others behind on main
+ # # ensure that gap is big enough
+ # id_veh_behind = ids_veh_in1[i+1]
+@@ -2214,7 +2214,7 @@
+
+ if is_found:
+ if debug:
+- print ' suitable vehicle after which entry vehicle can run has been found'
++ print(' suitable vehicle after which entry vehicle can run has been found')
+ # Note: if no vehicle has been found then
+ # nothing will happen and the vehicle will
+ # wait until the righ moment has arrived
+@@ -2226,12 +2226,12 @@
+ # test if speed reached
+ if traci.vehicle.getSpeed(id_veh_sumo) > 0.9*vehicles.speed_max.get_value():
+ if debug > 0:
+- print ' synchronization reached for veh', id_veh_sumo
++ print(' synchronization reached for veh', id_veh_sumo)
+ state['status'] = 'sync'
+ #id_veh_del = id_veh
+ # now create ghosts
+ # id_veh -> id_veh_infront_tail:
+- if state.has_key('id_veh_infront'):
++ if 'id_veh_infront' in state:
+ id_veh_in_front = state['id_veh_infront']
+ id_veh_infront_tail = vehicles.get_platoontail(id_veh_in_front)
+ id_veh_infront_tail_sumo = vehicles.ids_sumo[id_veh_infront_tail]
+@@ -2239,11 +2239,11 @@
+ dist_tomerge_tail = get_traci_distance(id_veh_infront_tail_sumo, id_edge_out_sumo, 3.0)
+
+ if debug > 0:
+- print ' add ghost to entering veh', id_veh_sumo, ' behind', id_veh_infront_tail_sumo, 'with leader', id_veh_in_front
++ print(' add ghost to entering veh', id_veh_sumo, ' behind', id_veh_infront_tail_sumo, 'with leader', id_veh_in_front)
+ vehicles.add_ghost(id_veh, id_veh_infront_tail, dist_tomerge,
+ dist_tomerge_tail, is_substitute=True)
+
+- if state.has_key('id_veh_behind'):
++ if 'id_veh_behind' in state:
+ id_veh_behind = state['id_veh_behind']
+ id_veh_behind_sumo = vehicles.ids_sumo[id_veh_behind]
+
+@@ -2254,16 +2254,16 @@
+ dist_tomerge_tail = get_traci_distance(id_veh_tail_sumo, id_edge_out_sumo, 3.0)
+
+ if debug > 0:
+- print ' add ghost to mainline veh', id_veh_behind_sumo, ' behind', id_veh_tail_sumo, 'with leader', id_veh_sumo
++ print(' add ghost to mainline veh', id_veh_behind_sumo, ' behind', id_veh_tail_sumo, 'with leader', id_veh_sumo)
+ vehicles.add_ghost(id_veh_behind, id_veh_tail, dist_tomerge_behind,
+ dist_tomerge_tail, is_substitute=True)
+
+ else:
+ if 0:
+ speed = traci.vehicle.getSpeed(id_veh_sumo)
+- print ' sync of veh', id_veh_sumo, ',v=%.1f, not yet reached: %.2f' % (speed, speed/vehicles.speed_max.get_value())
+-
+- if state.has_key('id_veh_behind'):
++ print(' sync of veh', id_veh_sumo, ',v=%.1f, not yet reached: %.2f' % (speed, speed/vehicles.speed_max.get_value()))
++
++ if 'id_veh_behind' in state:
+ id_veh_behind_sumo = vehicles.ids_sumo[state['id_veh_behind']]
+ info = traci.vehicle.getLeader(id_veh_behind_sumo, dist=200.0)
+ if (info is not None):
+@@ -2300,7 +2300,7 @@
+ pos_to refers to the position of the tail of the platoon on the main line.
+
+ """
+- print 'get_pos_crit_entry pos2=%.1f, v=%.1f, d1=%.1f, d2=%.1f' % (pos2, speed, dist1, dist2)
++ print('get_pos_crit_entry pos2=%.1f, v=%.1f, d1=%.1f, d2=%.1f' % (pos2, speed, dist1, dist2))
+ # see 191030
+ decel_emergency = vehicles.decel_emergency.get_value()
+ decel_comfort = vehicles.decel_comfort.get_value()
+@@ -2321,9 +2321,9 @@
+ Returns id_node, length to node
+
+ """
+- print 'search_upstream_merge id_edge_start', id_edge_start
++ print('search_upstream_merge id_edge_start', id_edge_start)
+ length = distances[id_edge_start]
+- print ' added id_edge', id_edge_start, 'dist', distances[id_edge_start], '=', length
++ print(' added id_edge', id_edge_start, 'dist', distances[id_edge_start], '=', length)
+ is_merge = False
+ id_edge_platform = -1
+ id_edge = id_edge_start
+@@ -2357,10 +2357,10 @@
+ if not is_merge:
+ id_edge = ids_edge_incoming[0]
+ length += distances[id_edge]
+- print ' added id_edge', id_edge, 'dist', distances[id_edge], '=', length
++ print(' added id_edge', id_edge, 'dist', distances[id_edge], '=', length)
+
+ # print ' id_edge,is_merge',id_edge,is_merge
+- print ' found node', edges.ids_fromnode[id_edge]
++ print(' found node', edges.ids_fromnode[id_edge])
+ return edges.ids_fromnode[id_edge], length
+
+ def search_downstream_merges(self, id_edge_start, edges, lanes, id_prtmode, ids_sinkedge=set()):
+@@ -2372,7 +2372,7 @@
+
+ ids_edge = set([id_edge_start])
+ ids_mergenode = set()
+- print 'search_downstream_merges id_edge_start', id_edge_start, 'is sinkedge', id_edge_start in ids_sinkedge
++ print('search_downstream_merges id_edge_start', id_edge_start, 'is sinkedge', id_edge_start in ids_sinkedge)
+
+ if id_edge_start in ids_sinkedge:
+ return None # np.array([], dtype = np.int32)
+@@ -2424,7 +2424,7 @@
+
+ # if not is_cont:
+ # print ' endless!!id_edge_start,ids_edge',id_edge_start,ids_edge
+- print ' found ids_mergenode', ids_mergenode
++ print(' found ids_mergenode', ids_mergenode)
+ return np.array(list(ids_mergenode), dtype=np.int32)
+
+ def is_prt_only(self, ids_lane, lanes):
+@@ -2554,7 +2554,7 @@
+ ))
+
+ def set_allocate(self, ids_berth):
+- print 'set_allocate ids_berth', ids_berth, self.ids_veh[ids_berth]
++ print('set_allocate ids_berth', ids_berth, self.ids_veh[ids_berth])
+ self.states[ids_berth] = BERTHSTATES['allocated']
+
+ def set_alighting(self, id_berth, id_veh):
+@@ -2572,7 +2572,7 @@
+
+ def set_waiting_routed(self, id_berth, simtime):
+
+- print 'set_waiting_routed', id_berth, 'prt.%d' % (self.ids_veh[id_berth]), 'simtime', simtime
++ print('set_waiting_routed', id_berth, 'prt.%d' % (self.ids_veh[id_berth]), 'simtime', simtime)
+ self.states[id_berth] = BERTHSTATES['waiting_routed']
+ self.times_routes[id_berth] = simtime
+
+@@ -2757,7 +2757,7 @@
+ ptstops = net.ptstops
+ lanes = net.lanes
+ n = len(coords_from)
+- print 'get_closest_for_trip', n
++ print('get_closest_for_trip', n)
+
+ times_stop_to_stop = self.parent.times_stop_to_stop[1:, 1:]
+
+@@ -2792,11 +2792,11 @@
+ # print ' walktimes_to',walktimes_to.shape
+ # print ' times_stop_to_stop',times_stop_to_stop.shape
+
+- print ' id_person', id_person
+- print ' coord_from, coord_to', coord_from, coord_to
+- print ' times_door_to_door\n', times_door_to_door
+- print ' ind_from, ind_to', ind_from, ind_to
+- print ' id_stop_from, id_stop_to', ids_prtstop[ind_from], ids_prtstop[ind_to]
++ print(' id_person', id_person)
++ print(' coord_from, coord_to', coord_from, coord_to)
++ print(' times_door_to_door\n', times_door_to_door)
++ print(' ind_from, ind_to', ind_from, ind_to)
++ print(' id_stop_from, id_stop_to', ids_prtstop[ind_from], ids_prtstop[ind_to])
+
+ i += 1
+
+@@ -2871,7 +2871,7 @@
+
+ def prepare_sim(self, process):
+ simtime = process.simtime
+- print 'PrtStops.prepare_sim', simtime
++ print('PrtStops.prepare_sim', simtime)
+ self.debug = True
+ net = self.get_scenario().net
+ ptstops = net.ptstops
+@@ -2927,11 +2927,11 @@
+ if (firstberthpos-stoplinegap) > 0:
+ self.stoplines_in[id_stop] = firstberthpos-stoplinegap
+
+- print ' OK:id_stop', id_stop, 'stoplines_in', self.stoplines_in[id_stop]
++ print(' OK:id_stop', id_stop, 'stoplines_in', self.stoplines_in[id_stop])
+ self.capas_inqueue[id_stop] = int(self.stoplines_in[id_stop]/vehicles.length)
+- print ' capa_inqueue', self.capas_inqueue[id_stop]
++ print(' capa_inqueue', self.capas_inqueue[id_stop])
+ else:
+- print 'WARNING in PrtStops.prepare_sim: stop ID %d has not enough space at before berth area.' % id_stop
++ print('WARNING in PrtStops.prepare_sim: stop ID %d has not enough space at before berth area.' % id_stop)
+
+ # Determine stopline position where vehicles actually start
+ # running off the station
+@@ -2946,14 +2946,14 @@
+ lastberthstoppos = berths.stoppositions[ids_board][-1]
+ if (length_stopedge-lastberthstoppos) > stoplinegap+1:
+ self.stoplines[id_stop] = length_stopedge-stoplinegap
+- print ' OK:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop]
++ print(' OK:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop])
+
+ elif length_stopedge > lastberthstoppos:
+ self.stoplines[id_stop] = 0.5*(length_stopedge+lastberthstoppos)
+- print ' Limit:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop]
++ print(' Limit:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop])
+
+ self.capas_outqueue[id_stop] = int((self.stoplines[id_stop]-lastberthstoppos)/vehicles.length)
+- print ' capa_outqueue', self.capas_outqueue[id_stop]
++ print(' capa_outqueue', self.capas_outqueue[id_stop])
+
+ self.ids_stop_to_ids_acceledge_sumo = np.zeros(np.max(ids)+1, dtype=np.object)
+ for id_stop, id_stopedge in zip(ids, ids_stopedge):
+@@ -3057,7 +3057,7 @@
+ id_toedge_sumo)
+
+ id_person_sumo = virtualpop.get_id_sumo_from_id(id_person)
+- if id_person_to_origs_dests.has_key(id_person_sumo):
++ if id_person_sumo in id_person_to_origs_dests:
+ id_person_to_origs_dests[id_person_sumo].append(data_orig_dest)
+ else:
+ id_person_to_origs_dests[id_person_sumo] = [data_orig_dest]
+@@ -3071,7 +3071,7 @@
+
+ # various initianilizations
+ for id_stop, id_edge_sumo in zip(ids, self.ids_stop_to_ids_edge_sumo[ids]):
+- print ' initialize stop', id_stop
++ print(' initialize stop', id_stop)
+
+ # initially all berth are avalable for allocation
+ # print ' type(self.ids_berths[id_stop])',type(self.ids_berths[id_stop])
+@@ -3112,14 +3112,14 @@
+
+ def get_waittime_max(self, id_stop, simtime):
+ if len(self.waittimes_persons[id_stop]) > 0:
+- return np.max(simtime - np.array(self.waittimes_persons[id_stop].values(), dtype=np.float32))
++ return np.max(simtime - np.array(list(self.waittimes_persons[id_stop].values()), dtype=np.float32))
+ else:
+ return 0.0
+
+ def process_step(self, process):
+ simtime = process.simtime
+- print 79*'_'
+- print 'PrtStops.process_step at', simtime
++ print(79*'_')
++ print('PrtStops.process_step at', simtime)
+
+ # vehicle station process:
+ # >forewarding (def enter)
+@@ -3142,9 +3142,9 @@
+ zip(ids, self.ids_stop_to_ids_edge_sumo[ids],
+ self.ids_vehs_sumo_prev[ids],
+ self.ids_persons_sumo_prev[ids]):
+- print ' '+60*'.'
++ print(' '+60*'.')
+ fase = self.fases[id_stop]
+- print ' process id_stop', id_stop, 'id_edge_sumo', id_edge_sumo, 'fase', fase
++ print(' process id_stop', id_stop, 'id_edge_sumo', id_edge_sumo, 'fase', fase)
+
+ if id_stop in [3]:
+ self.debug = 1
+@@ -3156,34 +3156,34 @@
+
+ if self.debug:
+
+- print ' ids_berths_to_allocate', type(self.ids_berths_to_allocate[id_stop]), self.ids_berths_to_allocate[id_stop]
+- print ' ind_berth_allocated', self.inds_berth_allocated[id_stop]
+- print ' ids_vehs_inqueue', self.ids_vehs_inqueue[id_stop]
+- print ' Capa', self.get_capacity(id_stop), 'per 10 seconds', self.get_capacity(id_stop)/3600*10
+- print
+-
+- print ' ids_vehs_alight_forward', self.ids_vehs_alight_forward[id_stop]
+- print ' ids_vehs_alight_aproach', self.ids_vehs_alight_aproach[id_stop]
+- print
+-
+- print ' ids_vehs_routed', self.ids_vehs_routed[id_stop]
+- print ' ids_berths_veh_wait_exit ', self.ids_berths_veh_wait_exit[id_stop]
+- print ' ids_vehs_pass_wait_exit ', self.ids_vehs_pass_wait_exit[id_stop]
+- print ' ids_vehs_berth_exit', self.ids_vehs_berth_exit[id_stop]
+- print ' ids_vehs_out', self.ids_vehs_out[id_stop]
+- print ' ids_veh_ready_for_departure', self.ids_vehs_ready_for_departure[id_stop]
+-
+- print ' Vehicles:'
++ print(' ids_berths_to_allocate', type(self.ids_berths_to_allocate[id_stop]), self.ids_berths_to_allocate[id_stop])
++ print(' ind_berth_allocated', self.inds_berth_allocated[id_stop])
++ print(' ids_vehs_inqueue', self.ids_vehs_inqueue[id_stop])
++ print(' Capa', self.get_capacity(id_stop), 'per 10 seconds', self.get_capacity(id_stop)/3600*10)
++ print()
++
++ print(' ids_vehs_alight_forward', self.ids_vehs_alight_forward[id_stop])
++ print(' ids_vehs_alight_aproach', self.ids_vehs_alight_aproach[id_stop])
++ print()
++
++ print(' ids_vehs_routed', self.ids_vehs_routed[id_stop])
++ print(' ids_berths_veh_wait_exit ', self.ids_berths_veh_wait_exit[id_stop])
++ print(' ids_vehs_pass_wait_exit ', self.ids_vehs_pass_wait_exit[id_stop])
++ print(' ids_vehs_berth_exit', self.ids_vehs_berth_exit[id_stop])
++ print(' ids_vehs_out', self.ids_vehs_out[id_stop])
++ print(' ids_veh_ready_for_departure', self.ids_vehs_ready_for_departure[id_stop])
++
++ print(' Vehicles:')
+ ids_veh = self.ids_vehs[id_stop]
+ for id_veh, state, id_berth, route in zip(ids_veh, vehicles.states[ids_veh], vehicles.ids_berth[ids_veh], vehicles.routes[ids_veh]):
+ # ,'len(route)',len(route)
+- print ' id_veh', id_veh, 'state', state, 'id_berth', id_berth, 'route', route
+-
+- print ' Berths:'
++ print(' id_veh', id_veh, 'state', state, 'id_berth', id_berth, 'route', route)
++
++ print(' Berths:')
+
+ ids_berth = self.ids_berths[id_stop]
+ for id_berth, state, id_veh in zip(ids_berth, berths.states[ids_berth], berths.ids_veh[ids_berth]):
+- print ' id_berth', id_berth, 'state', state, 'id_veh', id_veh
++ print(' id_berth', id_berth, 'state', state, 'id_veh', id_veh)
+ # print ' flow_person',self.flows_person[id_stop]
+ # print ' waittimes_persons',self.waittimes_persons[id_stop]
+
+@@ -3191,11 +3191,11 @@
+
+ # no longer print ' ids_persons_sumo_boarded',self.ids_persons_sumo_boarded[id_stop]
+ # print ' times_lastboard',self.times_lastboard[id_stop]
+- print
++ print()
+
+ if 0:
+ for id_veh_sumo in self.ids_vehs_sumo_prev[id_stop]:
+- print ' stopstate ', id_veh_sumo, bin(traci.vehicle.getStopState(id_veh_sumo))[2:], traci.vehicle.getRoute(id_veh_sumo)
++ print(' stopstate ', id_veh_sumo, bin(traci.vehicle.getStopState(id_veh_sumo))[2:], traci.vehicle.getRoute(id_veh_sumo))
+
+ # check for new vehicle arrivals/departures
+ ids_veh_sumo = set(traci.edge.getLastStepVehicleIDs(id_edge_sumo))
+@@ -3273,7 +3273,7 @@
+ ids_veh_remove.append(id_veh)
+ id_berth_alight = vehicles.ids_berth[id_veh]
+ if self.debug:
+- print ' %s stopped inside berth %d and alights' % (id_veh_sumo, id_berth_alight)
++ print(' %s stopped inside berth %d and alights' % (id_veh_sumo, id_berth_alight))
+
+ # vehicles.set_stop( id_veh,
+ # id_edge_sumo,
+@@ -3300,8 +3300,8 @@
+ if ids_person_sumo_prev != ids_person_sumo:
+
+ if 0:
+- print ' change\n id_person_sumo', ids_person_sumo
+- print ' ids_person_sumo_prev', ids_person_sumo_prev
++ print(' change\n id_person_sumo', ids_person_sumo)
++ print(' ids_person_sumo_prev', ids_person_sumo_prev)
+ # print ' dir(traci.person)',dir(traci.person)
+ # for id_person_sumo in ids_person_sumo:
+ # print ' id_person_sumo',id_person_sumo,traci.person.getRoadID(id_person_sumo),traci.person.getVehicle(id_person_sumo)
+@@ -3310,7 +3310,7 @@
+ ids_person_sumo_entered = ids_person_sumo.difference(ids_person_sumo_prev)
+ for id_person_sumo in ids_person_sumo_entered:
+ # print ' entered id_person_sumo',id_person_sumo,traci.person.getRoadID(id_person_sumo)
+- if self.id_person_to_origs_dests.has_key(id_person_sumo):
++ if id_person_sumo in self.id_person_to_origs_dests:
+ id_edge_sumo_dests = self.id_person_to_origs_dests[id_person_sumo]
+
+ # id_edge_sumo_dests[i] = ( id_stop_from,
+@@ -3324,7 +3324,7 @@
+ # check if next trip has origin edge equal to edge of this stop
+ if id_edge_sumo_dests[0][2] == id_edge_sumo:
+ if self.debug:
+- print ' add to waittimes_persons', id_person_sumo, 'id_stop_dest', id_edge_sumo_dests[0][1], 'id_toedge_sumo', id_edge_sumo_dests[0][3]
++ print(' add to waittimes_persons', id_person_sumo, 'id_stop_dest', id_edge_sumo_dests[0][1], 'id_toedge_sumo', id_edge_sumo_dests[0][3])
+ self.waittimes_persons[id_stop][id_person_sumo] = simtime
+ n_enter += 1
+
+@@ -3346,7 +3346,7 @@
+
+ if 0:
+ for id_person_sumo in ids_person_sumo_prev:
+- print ' ids_person_sumo=%s pos = %.2f ' % (id_person_sumo, traci.person.getLanePosition(id_person_sumo))
++ print(' ids_person_sumo=%s pos = %.2f ' % (id_person_sumo, traci.person.getLanePosition(id_person_sumo)))
+ # nomore print ' ids_persons_sumo_boarded',self.ids_persons_sumo_boarded[id_stop]
+
+ # if vehicles.id_follower_probe != vehicles.ids_follower[271]:
+@@ -3368,7 +3368,7 @@
+ # this will put the vehicle in waiting or boarding mode
+ if vehicles.is_completed_alighting(id_veh):
+ if self.debug:
+- print ' state of prt.%d: %d' % (id_veh, vehicles.states[id_veh])
++ print(' state of prt.%d: %d' % (id_veh, vehicles.states[id_veh]))
+ if vehicles.states[id_veh] == VEHICLESTATES['boarding']:
+ # print ' set id_berth_board',id_berth_board,'to state boarding'
+ berths.set_boarding(id_berth_board)
+@@ -3396,15 +3396,15 @@
+ if fase == FASE_MOVE_IN:
+ # stop is in move in fase
+ if self.debug:
+- print ' >>timeout fase 0: dt=%.2f timeout=%.2f' % ((simtime - self.times_phase_in[id_stop]), self.time_fase_in_max.get_value()),\
++ print(' >>timeout fase 0: dt=%.2f timeout=%.2f' % ((simtime - self.times_phase_in[id_stop]), self.time_fase_in_max.get_value()),\
+ 'TOUT', ((simtime - self.times_phase_in[id_stop]) > self.time_fase_in_max.get_value()
+- ), '|ALLOC', (len(self.ids_vehs_inqueue[id_stop]) > 0)
++ ), '|ALLOC', (len(self.ids_vehs_inqueue[id_stop]) > 0))
+ # print ' ap',(len(self.ids_vehs_alight_aproach[id_stop]) == 0)
+- print ' no forward, all vehicles moved into berth', (len(self.ids_vehs_alight_forward[id_stop]) == 0)
+- print ' ids_vehs_inqueue', self.ids_vehs_inqueue[id_stop]
+- print ' ids_veh_to_allocate', ids_veh_to_allocate
+- print ' ids_veh_to_pass', ids_veh_to_pass
+- print ' is_back_to_move_in ', self.are_back_to_move_in[id_stop]
++ print(' no forward, all vehicles moved into berth', (len(self.ids_vehs_alight_forward[id_stop]) == 0))
++ print(' ids_vehs_inqueue', self.ids_vehs_inqueue[id_stop])
++ print(' ids_veh_to_allocate', ids_veh_to_allocate)
++ print(' ids_veh_to_pass', ids_veh_to_pass)
++ print(' is_back_to_move_in ', self.are_back_to_move_in[id_stop])
+ # if np.isnan(self.times_phase_in[id_stop]):
+ # # only for initialization
+ # self.times_phase_in[id_stop] = simtime - self.time_fase_in_max.get_value()
+@@ -3430,15 +3430,15 @@
+ # which means that there are no more free berth to allocate
+ # and all forwarded vehicles reached their berth to alight
+ if self.debug:
+- print ' Switch from fase %d to fase %d' % (self.fases[id_stop], FASE_MOVE_OUT)
++ print(' Switch from fase %d to fase %d' % (self.fases[id_stop], FASE_MOVE_OUT))
+ self.fases[id_stop] = FASE_MOVE_OUT
+ self.times_phase_out[id_stop] = simtime
+
+ elif fase == FASE_MOVE_OUT:
+ # stop is in move out fase
+ if self.debug:
+- print ' >>timeout fase 1: dt=%.2f timeout=%.2f' % ((simtime - self.times_phase_out[id_stop]), self.time_fase_out_max.get_value()), 'move out of berth', len(self.ids_vehs_berth_exit[id_stop])
+- print ' n_berth_exit', len(self.ids_vehs_berth_exit[id_stop]), 'n_veh_pass', len(ids_veh_to_pass), 'ids_veh_to_pass', ids_veh_to_pass
++ print(' >>timeout fase 1: dt=%.2f timeout=%.2f' % ((simtime - self.times_phase_out[id_stop]), self.time_fase_out_max.get_value()), 'move out of berth', len(self.ids_vehs_berth_exit[id_stop]))
++ print(' n_berth_exit', len(self.ids_vehs_berth_exit[id_stop]), 'n_veh_pass', len(ids_veh_to_pass), 'ids_veh_to_pass', ids_veh_to_pass)
+ # check fase transition
+ # if np.isnan(self.times_phase_out[id_stop]):
+ # # only for initialization
+@@ -3453,7 +3453,7 @@
+ self.are_back_to_move_in[id_stop] = False
+
+ if self.debug:
+- print ' Switch from fase %d to fase %d' % (self.fases[id_stop], FASE_MOVE_IN), 'ind_berth_allocated', self.inds_berth_allocated[id_stop]
++ print(' Switch from fase %d to fase %d' % (self.fases[id_stop], FASE_MOVE_IN), 'ind_berth_allocated', self.inds_berth_allocated[id_stop])
+
+ self.fases[id_stop] = FASE_MOVE_IN
+ self.times_phase_in[id_stop] = simtime
+@@ -3478,7 +3478,7 @@
+ # command vehicle to go to berth for alighting
+ if id_berth > -1:
+ if self.debug:
+- print ' foreward queued vehicle id_veh prt.%d to id_berth %d at pos %.2fm' % (id_veh, id_berth, berths.stoppositions[id_berth])
++ print(' foreward queued vehicle id_veh prt.%d to id_berth %d at pos %.2fm' % (id_veh, id_berth, berths.stoppositions[id_berth]))
+ vehicles.control_berth_position_enter(id_veh, id_berth,
+ id_edge_sumo=self.ids_stop_to_ids_edge_sumo[id_stop],
+ # needs to stop a bit before to move in
+@@ -3522,7 +3522,7 @@
+ #id_veh_sumo = self.parent.prtvehicles.get_id_sumo(id_veh)
+ n_pax = traci.vehicle.getPersonNumber(id_veh_sumo)
+ if self.debug:
+- print 'route_trip_occupied id_stop', id_stop, 'id_berth', id_berth, 'veh=%s' % id_veh_sumo, 'simtime', simtime, 'n_pax', n_pax
++ print('route_trip_occupied id_stop', id_stop, 'id_berth', id_berth, 'veh=%s' % id_veh_sumo, 'simtime', simtime, 'n_pax', n_pax)
+
+ # identify which of the boarding persons is in the
+ # vehicle which completed boarding
+@@ -3535,14 +3535,14 @@
+ if len(ids_person_sumo_inveh) > 0:
+ id_person_sumo_inveh = ids_person_sumo_inveh[0]
+ if self.debug:
+- print ' found person %s in veh prt.%s' % (id_person_sumo_inveh, id_veh_sumo)
++ print(' found person %s in veh prt.%s' % (id_person_sumo_inveh, id_veh_sumo))
+
+ # program vehicle to person's destination
+ # print ' found person,origs_dests',id_person_sumo_inveh,self.id_person_to_origs_dests[id_person_sumo_inveh]
+ id_stop_orig, id_stop_dest, id_edge_sumo_from, id_edge_sumo_to = \
+ self.id_person_to_origs_dests[id_person_sumo_inveh].pop(0)
+ if self.debug:
+- print ' found person %s' % id_person_sumo_inveh, 'from', id_stop_orig, id_edge_sumo_from, ' to', id_edge_sumo_to, id_stop_dest
++ print(' found person %s' % id_person_sumo_inveh, 'from', id_stop_orig, id_edge_sumo_from, ' to', id_edge_sumo_to, id_stop_dest)
+
+ route, duration = self.route_stop_to_stop(id_stop_orig, id_stop_dest)
+
+@@ -3576,7 +3576,7 @@
+ self.numbers_person_wait[id_stop] -= len(ids_person_sumo_inveh)
+
+ else:
+- print 'WARNING: on stop %d edge %s, berth %d no person found inside vehicle prt.%d' % (id_stop, self.ids_stop_to_ids_edge_sumo[id_stop], id_berth, id_veh)
++ print('WARNING: on stop %d edge %s, berth %d no person found inside vehicle prt.%d' % (id_stop, self.ids_stop_to_ids_edge_sumo[id_stop], id_berth, id_veh))
+ return None
+
+ def get_surplus_veh(self, id_stop):
+@@ -3594,7 +3594,7 @@
+
+ def get_vehs_waiting(self, id_stop):
+ """Returns lists of empty and occupied waiting vehicles, as well as their respective berth IDs."""
+- print 'get_vehs_waiting id_stop', id_stop
++ print('get_vehs_waiting id_stop', id_stop)
+ ids_berth_waiting = self.get_berths_with_state(id_stop, BERTHSTATES['waiting'])
+
+ ids_veh_waiting = self.get_berths().ids_veh[ids_berth_waiting]
+@@ -3605,7 +3605,7 @@
+ for id_berth, id_veh, id_veh_sumo in zip(ids_berth_waiting, ids_veh_waiting, self.parent.prtvehicles.ids_sumo[ids_veh_waiting]):
+ # check here if these vehicles are still waiting or if
+ # there has bee a person sitting in
+- print ' check id_veh_sumo', id_veh_sumo, 'n_pers', traci.vehicle.getPersonNumber(id_veh_sumo)
++ print(' check id_veh_sumo', id_veh_sumo, 'n_pers', traci.vehicle.getPersonNumber(id_veh_sumo))
+ if traci.vehicle.getPersonNumber(id_veh_sumo) == 0:
+ ids_veh_waiting_empty.append(id_veh)
+ ids_berth_empty.append(id_berth)
+@@ -3613,7 +3613,7 @@
+ ids_veh_waiting_occup.append(id_veh)
+ ids_berth_occup.append(id_berth)
+
+- print ' ids_veh_waiting_empty', ids_veh_waiting_empty
++ print(' ids_veh_waiting_empty', ids_veh_waiting_empty)
+ return ids_veh_waiting_empty, ids_veh_waiting_occup, ids_berth_empty, ids_berth_occup
+
+ def route_empties(self, id_stop, id_stop_target, n_move, simtime):
+@@ -3622,19 +3622,19 @@
+ Route also newly occupied vehicles if present.
+ Called by vehman
+ """
+- print 'route_empties id_stop', id_stop, '>id_stop_target', id_stop_target, 'n_move', n_move
++ print('route_empties id_stop', id_stop, '>id_stop_target', id_stop_target, 'n_move', n_move)
+ berths = self.get_berths()
+ vehicles = self.parent.prtvehicles
+ ids_veh_empty, ids_veh_waiting_occup, ids_berth, ids_berth_occup = self.get_vehs_waiting(id_stop)
+ n_veh_empty = len(ids_veh_empty)
+ n_move_eff = min(n_move, n_veh_empty)
+- print ' =>n_veh_empty', n_veh_empty, 'n_move_eff', n_move_eff
++ print(' =>n_veh_empty', n_veh_empty, 'n_move_eff', n_move_eff)
+
+ # if n_move <= n_veh_empty:
+
+ for id_berth, id_veh in zip(ids_berth[:n_move], ids_veh_empty[:n_move]):
+ if self.debug:
+- print ' route empty veh prt.%d' % id_veh, 'at berth', id_berth, 'from stop', id_stop, ' to', id_stop_target
++ print(' route empty veh prt.%d' % id_veh, 'at berth', id_berth, 'from stop', id_stop, ' to', id_stop_target)
+
+ route, duration = self.route_stop_to_stop(id_stop, id_stop_target)
+
+@@ -3656,7 +3656,7 @@
+ if 0: # not necessary, process step will take care of it
+ for id_berth, id_veh in zip(ids_berth_occup, ids_veh_waiting_occup):
+ if self.debug:
+- print ' route occupied veh prt.%d' % id_veh, 'at berth', id_berth, 'from stop', id_stop, ' to', id_stop_target
++ print(' route occupied veh prt.%d' % id_veh, 'at berth', id_berth, 'from stop', id_stop, ' to', id_stop_target)
+
+ route, duration = self.route_stop_to_stop(id_stop, id_stop_target)
+
+@@ -3700,7 +3700,7 @@
+ ids_veh_out = self.ids_vehs_out[id_stop]
+ capa_out = self.capas_outqueue[id_stop]
+ n_veh = len(ids_veh_berth_exit)
+- print 'foreward_vehicles_exit check', n_veh
++ print('foreward_vehicles_exit check', n_veh)
+
+ if n_veh == 0:
+ return False
+@@ -3709,7 +3709,7 @@
+ vehicles = self.parent.prtvehicles
+
+ are_stopped = np.zeros(n_veh, dtype=np.bool)
+- for i, id_veh, state in zip(xrange(n_veh), ids_veh_berth_exit, vehicles.states[ids_veh_berth_exit]):
++ for i, id_veh, state in zip(range(n_veh), ids_veh_berth_exit, vehicles.states[ids_veh_berth_exit]):
+
+ # TODO: here we could also check vehicle position
+ id_veh_sumo = vehicles.get_id_sumo(id_veh)
+@@ -3729,14 +3729,14 @@
+
+ are_stopped[i] = is_stopped | (state == VEHICLESTATES['forewarding_passthrough'])
+ if self.debug:
+- print ' %s' % id_veh_sumo, 'are_stopped', are_stopped[i], 'stop', traci.vehicle.isStopped(id_veh_sumo), 'state', state, 'laneindex', traci.vehicle.getLaneIndex(id_veh_sumo)
++ print(' %s' % id_veh_sumo, 'are_stopped', are_stopped[i], 'stop', traci.vehicle.isStopped(id_veh_sumo), 'state', state, 'laneindex', traci.vehicle.getLaneIndex(id_veh_sumo))
+
+ if self.debug:
+- print ' are_stopped', are_stopped
++ print(' are_stopped', are_stopped)
+
+ if np.all(are_stopped):
+ if self.debug:
+- print ' all vehicles are moved out of the berth'
++ print(' all vehicles are moved out of the berth')
+
+ # foreward to exit
+ #ids_veh_out = self.ids_vehs_out[id_stop]
+@@ -3751,7 +3751,7 @@
+
+ if self.debug:
+ if (len(ids_veh_out) < capa_out):
+- print ' Out buffer capacity exceeded, left veh:', ids_veh_berth_exit
++ print(' Out buffer capacity exceeded, left veh:', ids_veh_berth_exit)
+
+ #self.ids_vehs_berth_exit[id_stop] = []
+
+@@ -3772,7 +3772,7 @@
+ laneindex=2,
+ )
+ if self.debug:
+- print ' append prt.%d to output queue' % id_veh
++ print(' append prt.%d to output queue' % id_veh)
+ ids_veh_out.append((id_veh, stoppos))
+
+ def get_vehicles_ready_for_departure(self, id_stop):
+@@ -3785,21 +3785,21 @@
+ n_veh = len(ids_veh_out)
+ ids_veh_ready = self.ids_vehs_ready_for_departure[id_stop]
+ is_veh_ready = len(ids_veh_ready) > 0
+- print 'get_vehicles_ready_for_departure check id_stop', id_stop, ' len(ids_vehs_out)', n_veh, 'capa', self.capas_outqueue[id_stop]
++ print('get_vehicles_ready_for_departure check id_stop', id_stop, ' len(ids_vehs_out)', n_veh, 'capa', self.capas_outqueue[id_stop])
+ if is_veh_ready:
+ if self.debug:
+- print ' there are still vehicles ready to be launched'
+- print ' ids_veh_ready', ids_veh_ready
++ print(' there are still vehicles ready to be launched')
++ print(' ids_veh_ready', ids_veh_ready)
+ return []
+
+ berths = self.get_berths()
+ vehicles = self.parent.prtvehicles
+ if self.debug:
+- print ' ids_berths_veh_wait_exit', type(self.ids_berths_veh_wait_exit[id_stop]), self.ids_berths_veh_wait_exit[id_stop], 'ids_veh_berth_wait', berths.ids_veh[self.ids_berths_veh_wait_exit[id_stop]]
++ print(' ids_berths_veh_wait_exit', type(self.ids_berths_veh_wait_exit[id_stop]), self.ids_berths_veh_wait_exit[id_stop], 'ids_veh_berth_wait', berths.ids_veh[self.ids_berths_veh_wait_exit[id_stop]])
+
+ if (n_veh == 0):
+ if self.debug:
+- print ' no vehicles in output queue'
++ print(' no vehicles in output queue')
+ return []
+
+ # search after ready vehicles, that will be launched shortly
+@@ -3814,11 +3814,11 @@
+ id_stopedge_target = vehicles.routes[id_veh][-1]
+ if self.debug:
+ # ,'is_stopped',is_stopped
+- print ' %d Leader prt.%d' % (i, id_veh), 'id_stopedge_target', id_stopedge_target
++ print(' %d Leader prt.%d' % (i, id_veh), 'id_stopedge_target', id_stopedge_target)
+
+ else:
+ if self.debug:
+- print ' %d Follower prt.%d' % (i, id_veh), 'is_cont next', vehicles.routes[id_veh][-1] == id_stopedge_target
++ print(' %d Follower prt.%d' % (i, id_veh), 'is_cont next', vehicles.routes[id_veh][-1] == id_stopedge_target)
+
+ if vehicles.routes[id_veh][-1] == id_stopedge_target:
+ ids_veh_platoon.append((id_veh, stoppos))
+@@ -3830,19 +3830,19 @@
+ if ((len(self.ids_berths_veh_wait_exit[id_stop]) > 0) | (len(self.ids_vehs_pass_wait_exit[id_stop]) > 0))\
+ & (i < self.capas_outqueue[id_stop]-1):
+ if self.debug:
+- print ' Maybe incomplete platoon, wait till all vehicles are kicked out of berths'
+- print ' len(ids_berths_veh_wait_exit)', len(self.ids_berths_veh_wait_exit[id_stop]), 'len(ids_vehs_pass_wait_exit)', len(self.ids_vehs_pass_wait_exit[id_stop]), "i", i
++ print(' Maybe incomplete platoon, wait till all vehicles are kicked out of berths')
++ print(' len(ids_berths_veh_wait_exit)', len(self.ids_berths_veh_wait_exit[id_stop]), 'len(ids_vehs_pass_wait_exit)', len(self.ids_vehs_pass_wait_exit[id_stop]), "i", i)
+ return []
+ else:
+ # the entire out queue has the same destination
+ # and will leave the stop
+ if self.debug:
+- print ' entire out queue same dest and ready for departure'
++ print(' entire out queue same dest and ready for departure')
+ #is_update_outqueue = False
+ else:
+ # only a part of te out-queue departs, update position of rest
+ if self.debug:
+- print ' partial out queue ready for departure'
++ print(' partial out queue ready for departure')
+ #is_update_outqueue = True
+
+ # Check if all vehicles in the platoon are stopped at the
+@@ -3852,13 +3852,13 @@
+ are_finalpos = True
+ ids_veh_ready_new = []
+ if self.debug:
+- print ' position check/update ids_veh_platoon', ids_veh_platoon
++ print(' position check/update ids_veh_platoon', ids_veh_platoon)
+ for id_veh, stoppos in ids_veh_platoon:
+
+ id_veh_sumo = vehicles.get_id_sumo(id_veh)
+ is_stopped = traci.vehicle.isStopped(id_veh_sumo)
+ if self.debug:
+- print ' stopcheck ', id_veh_sumo, 'are_stopped', are_stopped, 'is_stopped', is_stopped
++ print(' stopcheck ', id_veh_sumo, 'are_stopped', are_stopped, 'is_stopped', is_stopped)
+
+ if is_stopped:
+ # check if stopposition is correct
+@@ -3871,7 +3871,7 @@
+ # vehicle is stopped but not at correct position
+ are_stopped = False
+ if self.debug:
+- print ' update stoppos of prt.%s:' % id_veh_sumo, 'from curpos', pos_veh, 'stoppos', stoppos
++ print(' update stoppos of prt.%s:' % id_veh_sumo, 'from curpos', pos_veh, 'stoppos', stoppos)
+ # vehicle has stopped but not at the correct stop position
+ # =>foreward vehicle to the correct position
+ vehicles.control_forewarding_exit(id_veh,
+@@ -3886,26 +3886,26 @@
+ # print ' Veh',id_veh_sumo,'is_stopped',is_stopped
+ # if not is_veh_ready:# means that there are not already vehicles ready
+ if self.debug:
+- print ' append prt.%d to ids_veh_ready_new' % (id_veh)
++ print(' append prt.%d to ids_veh_ready_new' % (id_veh))
+ ids_veh_ready_new.append(id_veh)
+
+ if self.debug:
+- print ' ready? are_stopped %s,' % (are_stopped), 'ids_veh_ready_new', ids_veh_ready_new
++ print(' ready? are_stopped %s,' % (are_stopped), 'ids_veh_ready_new', ids_veh_ready_new)
+
+ # value if platoon is ready to leave
+ if (not is_veh_ready) & are_stopped:
+ if self.debug:
+- print ' all vehicles of the platoon are stopped, platoon ready.'
++ print(' all vehicles of the platoon are stopped, platoon ready.')
+ return ids_veh_ready_new
+
+ else:
+ if not are_finalpos:
+ self.are_reposition_out[id_stop] = True
+ if self.debug:
+- print ' vehicles of platoon not stopped at coorect position or previous ready vehicles not launched.'
++ print(' vehicles of platoon not stopped at coorect position or previous ready vehicles not launched.')
+ else:
+ if self.debug:
+- print ' not all vehicles of platoon stopped or previous ready vehicles not launched.'
++ print(' not all vehicles of platoon stopped or previous ready vehicles not launched.')
+ return []
+
+ def _reposition_outqueue(self, id_stop):
+@@ -3949,7 +3949,7 @@
+ """
+ #ids_veh_out = self.ids_vehs_out[id_stop]
+ n_veh = len(ids_veh)
+- print 'prepare_vehs_for_departure id_stop', id_stop, 'n_veh', n_veh
++ print('prepare_vehs_for_departure id_stop', id_stop, 'n_veh', n_veh)
+ ids_veh_out = self.ids_vehs_out[id_stop]
+ if n_veh == 0:
+ return False
+@@ -3962,10 +3962,10 @@
+ vehicles.concatenate(id_veh, id_veh_infront)
+
+ if self.debug:
+- print ' prepared:'
++ print(' prepared:')
+ for id_veh, route in zip(ids_veh, vehicles.routes[ids_veh]):
+ id_stopedge = route[-1]
+- print ' prep. prt.%d' % id_veh, 'with id_stopedge', id_stopedge, 'id_stop', self.id_edge_to_id_stop[id_stopedge]
++ print(' prep. prt.%d' % id_veh, 'with id_stopedge', id_stopedge, 'id_stop', self.id_edge_to_id_stop[id_stopedge])
+
+ id_veh_lead = ids_veh[0]
+ id_stopedge_target = vehicles.routes[id_veh_lead][-1]
+@@ -3975,16 +3975,16 @@
+
+ self.parent.vehicleman.note_vehs_ready_for_departure(id_stop, id_stop_target, time_est, n_veh)
+
+- for i in xrange(n_veh):
++ for i in range(n_veh):
+ ids_veh_out.pop(0)
+
+ if len(ids_veh_out) > 0:
+ if self.debug:
+- print ' position update for remaining ids_veh_out', ids_veh_out
++ print(' position update for remaining ids_veh_out', ids_veh_out)
+ # move foreward stoplines of remaining vehicles in output queue
+ stopline = self.stoplines[id_stop]
+ id_edge_sumo = self.ids_stop_to_ids_edge_sumo[id_stop]
+- for ind in xrange(len(ids_veh_out)):
++ for ind in range(len(ids_veh_out)):
+ id_veh, stoppos_prev = ids_veh_out[ind]
+ stoppos = stopline - ind * (vehicles.length+1.5*vehicles.dist_min)
+ # vehicles.control_forewarding_exit(id_veh,\
+@@ -3995,7 +3995,7 @@
+
+ if self.debug:
+ id_veh_sumo = 'prt.%s' % id_veh
+- print ' update stoppos of prt.%s:' % id_veh_sumo, 'from curpos', traci.vehicle.getLanePosition(id_veh_sumo), 'to stoppos', stoppos
++ print(' update stoppos of prt.%s:' % id_veh_sumo, 'from curpos', traci.vehicle.getLanePosition(id_veh_sumo), 'to stoppos', stoppos)
+ # print ' stopinfo:',traci.vehicle.getNextStops(id_veh_sumo)
+ ids_veh_out[ind] = (id_veh, stoppos)
+
+@@ -4006,16 +4006,16 @@
+ """
+ Method called from vehicle management when vehicles are allowed to depart.
+ """
+- print 'launch_vehs at id_stop', id_stop
++ print('launch_vehs at id_stop', id_stop)
+ ids_veh = self.ids_vehs_ready_for_departure[id_stop]
+ #ids_veh_out = self.ids_vehs_out[id_stop]
+ vehicles = self.parent.prtvehicles
+ #ids_veh = self.ids_vehs_ready_for_departure[id_stop]
+ # if self.debug:
+- print ' to launch: ids_veh', ids_veh # ,'with ids_stopedge_next',vehicles.routes[ids_veh]
++ print(' to launch: ids_veh', ids_veh) # ,'with ids_stopedge_next',vehicles.routes[ids_veh]
+
+ if len(ids_veh) == 0:
+- print 'WARNING in launch_vehs: there are no vehicles to lauche at id_stop', id_stop
++ print('WARNING in launch_vehs: there are no vehicles to lauche at id_stop', id_stop)
+
+ # here may check if destination stop is correct
+
+@@ -4024,7 +4024,7 @@
+
+ #id_veh_out, stoppos = ids_veh_out.pop(0)
+ # if self.debug:
+- print ' launched prt.%d to id_stopedge_target %d' % (id_veh, vehicles.routes[id_veh][-1])
++ print(' launched prt.%d to id_stopedge_target %d' % (id_veh, vehicles.routes[id_veh][-1]))
+ # if id_veh_out != id_veh:
+ # print 'WARNING: wrong vehicle from output queue'
+ # sys.exit(0)
+@@ -4046,7 +4046,7 @@
+ the last berth of the stop"""
+
+ pos_lastberth = self.get_berths().stoppositions[self.ids_berths[id_stop]][-1]
+- print 'is_outputqueue_compact n_outqueue', len(self.ids_vehs_out[id_stop]), 'pos_lastberth %.2f' % pos_lastberth
++ print('is_outputqueue_compact n_outqueue', len(self.ids_vehs_out[id_stop]), 'pos_lastberth %.2f' % pos_lastberth)
+
+ vehicles = self.parent.prtvehicles
+ is_compact = True
+@@ -4070,7 +4070,7 @@
+ break
+
+ if self.debug:
+- print ' is_compact', is_compact
++ print(' is_compact', is_compact)
+ return is_compact
+
+ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
+@@ -4079,42 +4079,42 @@
+ while maximizing platooning.
+ """
+
+- print 'try_start_vehicles id_stop', id_stop, 'veh exiting', len(self.ids_vehs_berth_exit[id_stop]),\
++ print('try_start_vehicles id_stop', id_stop, 'veh exiting', len(self.ids_vehs_berth_exit[id_stop]),\
+ 'wait from berth', len(self.ids_berths_veh_wait_exit[id_stop]), 'wait to pass', len(
+- self.ids_vehs_pass_wait_exit[id_stop])
++ self.ids_vehs_pass_wait_exit[id_stop]))
+
+ n_plat_max = self.capas_inqueue[id_stop] - \
+ (len(self.ids_vehs_out[id_stop])+len(self.ids_vehs_ready_for_departure[id_stop]))
+ if self.debug:
+- print ' n_plat_max', n_plat_max
++ print(' n_plat_max', n_plat_max)
+ if n_plat_max == 0:
+ if self.debug:
+- print ' insufficient sapce in output queue'
++ print(' insufficient sapce in output queue')
+ return False
+
+ if len(self.ids_vehs_berth_exit[id_stop]) > 0:
+ if self.debug:
+- print ' there are still vehicles moving out of berth'
++ print(' there are still vehicles moving out of berth')
+ return False
+
+ elif not self.is_outputqueue_compact(id_stop):
+ if self.debug:
+- print ' there are still vehicles in berth area toward exit queue'
++ print(' there are still vehicles in berth area toward exit queue')
+ return False
+
+ if self.debug:
+- print ' len(ids_veh_inqueue)', len(self.ids_vehs_inqueue[id_stop])
++ print(' len(ids_veh_inqueue)', len(self.ids_vehs_inqueue[id_stop]))
+ if len(self.ids_vehs_inqueue[id_stop]) > 0:
+ ids_veh_pass = self.get_ids_veh_to_pass(id_stop)
+ if self.debug:
+- print ' found ids_veh_pass', ids_veh_pass, 'not yet started!'
++ print(' found ids_veh_pass', ids_veh_pass, 'not yet started!')
+ else:
+ ids_veh_pass = []
+
+ n_veh_pass = len(ids_veh_pass)
+ n_veh_pass_wait = len(self.ids_vehs_pass_wait_exit[id_stop])
+ if self.debug:
+- print ' n_veh_pass', n_veh_pass, 'n_veh_pass_wait', n_veh_pass_wait
++ print(' n_veh_pass', n_veh_pass, 'n_veh_pass_wait', n_veh_pass_wait)
+
+ berths = self.get_berths()
+ vehicles = self.parent.prtvehicles
+@@ -4126,8 +4126,8 @@
+
+ if n_veh_pass_wait > 0:
+ if self.debug:
+- print ' there are passthrough vehicle in the input queue waiting to get started', self.ids_vehs_pass_wait_exit[id_stop]
+- print ' ids_veh_pass_wait_exit', self.ids_vehs_pass_wait_exit[id_stop]
++ print(' there are passthrough vehicle in the input queue waiting to get started', self.ids_vehs_pass_wait_exit[id_stop])
++ print(' ids_veh_pass_wait_exit', self.ids_vehs_pass_wait_exit[id_stop])
+ # these vehicles have a common target
+ ids_veh_pass_wait_exit = self.ids_vehs_pass_wait_exit[id_stop]
+ while len(ids_veh_pass_wait_exit) > 0:
+@@ -4142,7 +4142,7 @@
+ elif len(self.ids_berths_veh_wait_exit[id_stop]) > 0:
+ ids_berth_veh_wait_exit = self.ids_berths_veh_wait_exit[id_stop]
+ if self.debug:
+- print ' there are vehicles in berth which are listed to start.', ids_berth_veh_wait_exit
++ print(' there are vehicles in berth which are listed to start.', ids_berth_veh_wait_exit)
+ # do start them, sorted by final destination
+
+ # print ' ids_berth_veh_wait_exit',ids_berth_veh_wait_exit
+@@ -4154,7 +4154,7 @@
+ ids_stop_target = vehicles.ids_stop_target[ids_veh]
+ inds_start = ids_stop_target == ids_stop_target[0]
+ if self.debug:
+- print ' start waiting vehicles', ids_veh[inds_start], 'to final id_stop_target', ids_stop_target[0]
++ print(' start waiting vehicles', ids_veh[inds_start], 'to final id_stop_target', ids_stop_target[0])
+ self._kick_out_of_berth(id_stop, ids_veh[inds_start], np.array(
+ ids_berth_veh_wait_exit, dtype=np.int32)[inds_start], vehicles, berths)
+ for id_berth in np.array(ids_berth_veh_wait_exit, dtype=np.int32)[inds_start]:
+@@ -4164,7 +4164,7 @@
+ if ((simtime - self.times_phase_out[id_stop]) > self.time_fase_out_max.get_value()) & (n_veh_pass == 0):
+ # stop starting if move in phase is timed out
+ if self.debug:
+- print ' fase move out timeout, stop starting'
++ print(' fase move out timeout, stop starting')
+ return False
+
+ # berth in reverse order means that the berth closest to the exit comes first
+@@ -4186,7 +4186,7 @@
+ n_veh_all = n_veh+n_veh_pass
+
+ n_edge_max = 0
+- for i, id_veh, route in zip(xrange(n_veh_all), ids_veh_ready_all, vehicles.routes[ids_veh_ready_all]):
++ for i, id_veh, route in zip(range(n_veh_all), ids_veh_ready_all, vehicles.routes[ids_veh_ready_all]):
+ #ids_edge_target[i] = route[-1]
+ if len(route) > n_edge_max:
+ n_edge_max = len(route)
+@@ -4198,18 +4198,18 @@
+ overtime = simtime - berths.times_routes[ids_berth_ready]-self.time_wait_berth_max.get_value()
+ overtime_berth_ready = overtime * (overtime > 0)
+ if self.debug:
+- print ' vehicles ready to leave berth n_veh %d including input n_veh_all %d' % (n_veh, n_veh_all)
+- print ' ids_stop_target from berths', ids_stop_target
+- print ' ids_berth', berths.states[ids_berth]
+- print ' berths.state', berths.states[ids_berth]
+- print ' ids_berth_ready', ids_berth_ready
+- print ' ids_veh_ready', ids_veh_ready
+- print ' ids_veh_ready_all', ids_veh_ready_all
+- print
+- print ' simtime', simtime
+- print ' overtime_berth_ready', overtime_berth_ready
+- print ' berths.times_routes[ids_berth_ready]', berths.times_routes[ids_berth_ready]
+- print ' time_wait_berth_max', self.time_wait_berth_max.get_value()
++ print(' vehicles ready to leave berth n_veh %d including input n_veh_all %d' % (n_veh, n_veh_all))
++ print(' ids_stop_target from berths', ids_stop_target)
++ print(' ids_berth', berths.states[ids_berth])
++ print(' berths.state', berths.states[ids_berth])
++ print(' ids_berth_ready', ids_berth_ready)
++ print(' ids_veh_ready', ids_veh_ready)
++ print(' ids_veh_ready_all', ids_veh_ready_all)
++ print()
++ print(' simtime', simtime)
++ print(' overtime_berth_ready', overtime_berth_ready)
++ print(' berths.times_routes[ids_berth_ready]', berths.times_routes[ids_berth_ready])
++ print(' time_wait_berth_max', self.time_wait_berth_max.get_value())
+
+ # if 0: # deal with this case in platoon optimizarion
+ # print ' there are vehhicles in the input queue'
+@@ -4218,7 +4218,7 @@
+
+ if n_veh_pass > 0:
+ if self.debug:
+- print ' There is at least one passthrough vehicle which needs to get launched'
++ print(' There is at least one passthrough vehicle which needs to get launched')
+ #id_edge_target_max = vehicles.get_targetedge_current(ids_veh_pass[0])
+ id_stop_target_max = vehicles.ids_stop_target[ids_veh_pass[0]]
+
+@@ -4235,7 +4235,7 @@
+ ids_berth_plat = np.array([])
+
+ if self.debug:
+- print ' vehs with same dest as pass', ids_veh_plat
++ print(' vehs with same dest as pass', ids_veh_plat)
+
+ self._kick_out_of_berth(id_stop, ids_veh_plat, ids_berth_plat, vehicles, berths)
+
+@@ -4249,7 +4249,7 @@
+
+ elif (np.any(overtime_berth_ready) > 0) & (n_veh_pass == 0):
+ if self.debug:
+- print ' at some berth maximum wait time has been exceeded'
++ print(' at some berth maximum wait time has been exceeded')
+
+ # TODO: launche all vehicles with overtime putting them into self.ids_berths_veh_wait_exit[id_stop]
+ # take vehicle with maximum wait time and try to create a platoon
+@@ -4291,7 +4291,7 @@
+
+ else: # if n_veh > n_plat_min:
+
+- print ' Maximize platoon length'
++ print(' Maximize platoon length')
+
+ edgeutilities = self.get_scenario().net.edges.lengths
+ # utilities = np.sum(edgeutilities[routes_common],1)*counts_common
+@@ -4301,12 +4301,12 @@
+ # -1 is required to detect stop
+ ids_edges = -1*np.ones((n_veh_all, n_edge_max+1), dtype=np.int32)
+
+- for i, id_veh, route in zip(xrange(n_veh_all), ids_veh_ready_all, vehicles.routes[ids_veh_ready_all]):
++ for i, id_veh, route in zip(range(n_veh_all), ids_veh_ready_all, vehicles.routes[ids_veh_ready_all]):
+ # print ' get route prt.%d'%id_veh,'i',i,'route',route
+ ids_edges[i, :len(route)] = route
+
+ if self.debug > 9:
+- print ' ids_edges=\n', ids_edges
++ print(' ids_edges=\n', ids_edges)
+ n_veh_all, n_edge_max = ids_edges.shape
+
+ is_cont = True # not used
+@@ -4322,17 +4322,17 @@
+
+ inds_stop = np.flatnonzero(ids_edges[:, j] == -1)
+ if self.debug:
+- print ' j=', j, 'inds_stop', inds_stop
++ print(' j=', j, 'inds_stop', inds_stop)
+ if len(inds_stop) > 0:
+ if self.debug:
+- print ' create set of routes that lead to one of the stops'
++ print(' create set of routes that lead to one of the stops')
+ occurencies = OrderedDict()
+
+ for ids_edge, ind_stop in zip(ids_edges[inds_stop, 0:j-2], inds_stop):
+ # print ' ind_stop',ind_stop,'ids_edge',ids_edge
+ occurencies[tuple(ids_edge)] = 0
+
+- for ind, ids_edge in zip(xrange(n_veh_all), ids_edges[:, :]):
++ for ind, ids_edge in zip(range(n_veh_all), ids_edges[:, :]):
+ ids_edge_tuple = tuple(ids_edge[0:j-2])
+ # print ' check ids_edge',ids_edge
+ # print ' common?',ids_edge_tuple
+@@ -4348,8 +4348,8 @@
+ occurencies[ids_edge_tuple] += 1
+
+ # print ' occurencies',occurencies
+- routes_common = np.array(occurencies.keys(), dtype=np.int32)
+- counts_common = occurencies.values()
++ routes_common = np.array(list(occurencies.keys()), dtype=np.int32)
++ counts_common = list(occurencies.values())
+ utilities = np.sum(edgeutilities[routes_common], 1)*counts_common
+ ind_max = np.argmax(utilities)
+
+@@ -4369,8 +4369,8 @@
+
+ # print '-'*10
+ if self.debug:
+- print ' utility_max', utility_max
+- print ' route_common_max', route_common_max, type(route_common_max)
++ print(' utility_max', utility_max)
++ print(' route_common_max', route_common_max, type(route_common_max))
+
+ j_max = len(route_common_max)+2
+
+@@ -4384,12 +4384,12 @@
+ break
+
+ if self.debug:
+- print ' route_max', route_max
++ print(' route_max', route_max)
+
+ inds_veh_plat_deviate = []
+ inds_veh_plat_nodeviate = []
+ inds_veh_plat = []
+- for ind, ids_edge, is_stop in zip(xrange(n_veh_all), ids_edges[:, :], ids_edges[:, j_max] == -1):
++ for ind, ids_edge, is_stop in zip(range(n_veh_all), ids_edges[:, :], ids_edges[:, j_max] == -1):
+ if np.array_equal(ids_edge[0:j_max-2], route_common_max):
+ if self._is_stop(j_max, ids_edge):
+ inds_veh_plat.append(ind)
+@@ -4416,27 +4416,27 @@
+ iinds_plat_passthrough = inds_veh_plat >= n_veh
+ # print ' ids_edges_out\n',ids_edges_out
+ if self.debug:
+- print ' inds_veh_plat\n', inds_veh_plat
+- print ' inds_veh_plat_deviate\n', inds_veh_plat_deviate
+- print ' inds_veh_plat_nodeviate\n', inds_veh_plat_nodeviate
+- print ' inds_veh_plat_deviate_berth\n', inds_veh_plat_deviate[iinds_plat_deviate_berth]
+- print ' inds_veh_plat_nodeviate_berth\n', inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]
+- print ' iinds_plat_passthrough\n', iinds_plat_passthrough
+- print ' inds_veh_plat_passthrough\n', inds_veh_plat[iinds_plat_passthrough]
++ print(' inds_veh_plat\n', inds_veh_plat)
++ print(' inds_veh_plat_deviate\n', inds_veh_plat_deviate)
++ print(' inds_veh_plat_nodeviate\n', inds_veh_plat_nodeviate)
++ print(' inds_veh_plat_deviate_berth\n', inds_veh_plat_deviate[iinds_plat_deviate_berth])
++ print(' inds_veh_plat_nodeviate_berth\n', inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth])
++ print(' iinds_plat_passthrough\n', iinds_plat_passthrough)
++ print(' inds_veh_plat_passthrough\n', inds_veh_plat[iinds_plat_passthrough])
+
+ n_veh_plat = len(inds_veh_plat)
+ # print ' id_edge_target_max',id_edge_target_max,'n_veh_plat',n_veh_plat,n_veh_plat >= n_plat_min
+
+ if (n_veh_plat >= n_plat_min) | (np.max(inds_veh_plat) >= n_veh):
+ if self.debug:
+- print ' platoon formation long enough n_veh_plat', n_veh_plat, 'or passthrough', (np.max(inds_veh_plat) >= n_veh)
+-
+- print ' deviate vehicles berth', ids_veh_ready_all[inds_veh_plat_deviate[iinds_plat_deviate_berth]]
++ print(' platoon formation long enough n_veh_plat', n_veh_plat, 'or passthrough', (np.max(inds_veh_plat) >= n_veh))
++
++ print(' deviate vehicles berth', ids_veh_ready_all[inds_veh_plat_deviate[iinds_plat_deviate_berth]])
+ for id_veh in ids_veh_ready_all[inds_veh_plat_deviate[iinds_plat_deviate_berth]]:
+ # note that all routed vehicles are already disengaged
+ vehicles.set_route_target(id_veh, route_max, is_disengage_from_berth=False)
+ if self.debug:
+- print ' deviate vehicles passthrough', ids_veh_ready_all[inds_veh_plat_deviate[np.logical_not(iinds_plat_deviate_berth)]]
++ print(' deviate vehicles passthrough', ids_veh_ready_all[inds_veh_plat_deviate[np.logical_not(iinds_plat_deviate_berth)]])
+ for id_veh in ids_veh_ready_all[inds_veh_plat_deviate[np.logical_not(iinds_plat_deviate_berth)]]:
+ vehicles.set_route_target(id_veh, route_max)
+ # ?here next stop is identical with final route
+@@ -4446,8 +4446,8 @@
+
+ # start immediately vehicles with final destination from berths
+ if self.debug:
+- print ' kick out ids_veh', ids_veh_ready[inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]]
+- print ' from berths ', ids_berth_ready[inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]]
++ print(' kick out ids_veh', ids_veh_ready[inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]])
++ print(' from berths ', ids_berth_ready[inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]])
+ self._kick_out_of_berth(id_stop, ids_veh_ready[inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]],
+ ids_berth_ready[inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]], vehicles, berths)
+
+@@ -4455,17 +4455,17 @@
+ # they will be started later while being sorted by final
+ # destination
+ if self.debug:
+- print ' ids_berths_veh_wait_exit before', self.ids_berths_veh_wait_exit[id_stop]
++ print(' ids_berths_veh_wait_exit before', self.ids_berths_veh_wait_exit[id_stop])
+ self.ids_berths_veh_wait_exit[id_stop] += ids_berth_ready[inds_veh_plat_deviate[iinds_plat_deviate_berth]].tolist()
+ if self.debug:
+- print ' ids_berths_veh_wait_exit after ', self.ids_berths_veh_wait_exit[id_stop]
+- print ' ids_berth_ready', ids_berth_ready
++ print(' ids_berths_veh_wait_exit after ', self.ids_berths_veh_wait_exit[id_stop])
++ print(' ids_berth_ready', ids_berth_ready)
+ # ATTENTION: vehicles waiting in input queue cannot be sorted by destination...
+ # but they are supposed to be sorted already?
+
+ self.ids_vehs_pass_wait_exit[id_stop] += ids_veh_ready_all[inds_veh_plat[iinds_plat_passthrough]].tolist()
+ if self.debug:
+- print ' ids_vehs_pass_wait_exit after ', self.ids_vehs_pass_wait_exit[id_stop]
++ print(' ids_vehs_pass_wait_exit after ', self.ids_vehs_pass_wait_exit[id_stop])
+
+ # get the destination stop from final stop of the undevieted winner
+ id_stop_target_max = vehicles.ids_stop_target[ids_veh_ready_all[inds_veh_plat_nodeviate[0]]]
+@@ -4475,12 +4475,12 @@
+
+ else:
+ if self.debug:
+- print ' platoon too short'
++ print(' platoon too short')
+ return False
+
+ else:
+ if self.debug:
+- print ' no vehicles finished boarding'
++ print(' no vehicles finished boarding')
+ return False
+
+ def _is_stop(self, j, ids_edge):
+@@ -4493,7 +4493,7 @@
+
+ def _kick_out_of_berth(self, id_stop, ids_veh_plat, ids_berth_plat, vehicles, berths):
+ for id_veh, id_berth in zip(ids_veh_plat, ids_berth_plat):
+- print ' kick veh %d out of berth %d and set berth free' % (id_veh, id_berth)
++ print(' kick veh %d out of berth %d and set berth free' % (id_veh, id_berth))
+ berths.set_free(id_berth)
+ vehicles.control_berth_position_exit(id_veh,
+ id_edge_sumo=self.ids_stop_to_ids_edge_sumo[id_stop],\
+@@ -4518,7 +4518,7 @@
+ return ids_berth[self.get_berths().states[ids_berth] == state]
+
+ def enter(self, id_stop, ids_veh, fase, simtime):
+- print 'enter ids_veh', ids_veh
++ print('enter ids_veh', ids_veh)
+
+ vehicles = self.parent.prtvehicles
+
+@@ -4535,14 +4535,14 @@
+
+ self.numbers_veh[id_stop] += n_veh
+ are_completed = np.zeros(n_veh, dtype=np.bool)
+- for id_veh, i in zip(ids_veh, xrange(n_veh)):
++ for id_veh, i in zip(ids_veh, range(n_veh)):
+
+ vehicles.decatenate(id_veh)
+ # here we should check whether the vehicle needs to alight
+ # or wether it is a pass through
+ route = vehicles.routes[id_veh]
+ if self.debug:
+- print ' enter prt.%d' % id_veh, 'with id_stop_target', vehicles.ids_stop_target[id_veh], 'route', route
++ print(' enter prt.%d' % id_veh, 'with id_stop_target', vehicles.ids_stop_target[id_veh], 'route', route)
+ if len(route) == 0:
+ # vehicle just initialized
+ are_completed[i] = True
+@@ -4574,14 +4574,14 @@
+ n_veh_completed = len(ids_veh_completed)
+ ids_berth = -1*np.ones(n_veh, dtype=np.int32)
+ if self.debug:
+- print ' n_veh_completed', n_veh_completed, 'no Timeout', ((simtime - self.times_phase_in[id_stop]) < self.time_fase_in_max.get_value()), 'veh input', self.ids_vehs_inqueue[id_stop]
++ print(' n_veh_completed', n_veh_completed, 'no Timeout', ((simtime - self.times_phase_in[id_stop]) < self.time_fase_in_max.get_value()), 'veh input', self.ids_vehs_inqueue[id_stop])
+ # if fase == FASE_MOVE_IN:
+ # print ' timeout fase 0: dt=%.2f timeout=%.2f'%((simtime - self.times_phase_in[id_stop]), self.time_fase_in_max.get_value())
+ if n_veh_completed > 0:
+ # (simtime - self.times_phase_in[id_stop]), self.time_fase_in_max.get_value())
+ if self.debug:
+ # ,(len(self.ids_vehs_inqueue[id_stop]) == 0),((simtime - self.times_phase_in[id_stop]) > self.time_fase_in_max.get_value())
+- print ' fase', fase
++ print(' fase', fase)
+ if (fase == FASE_MOVE_IN) & (len(self.ids_vehs_inqueue[id_stop]) == 0)\
+ & ((simtime - self.times_phase_in[id_stop]) < self.time_fase_in_max.get_value()):
+ # here vehicles are sent to berth, if available
+@@ -4592,22 +4592,22 @@
+ # allocate berth only for vehicles which completed trip at this stop
+ ids_berth_completed = self.allocate_alight(id_stop, n_veh_completed)
+ if self.debug:
+- print ' ids_berth_completed', ids_berth_completed
++ print(' ids_berth_completed', ids_berth_completed)
+ ids_berth[are_completed] = ids_berth_completed
+
+ is_stop_moving_in = False
+ for id_veh, state, id_berth, is_completed in zip(ids_veh, vehicles.states[ids_veh], ids_berth, are_completed):
+ if self.debug:
+- print ' check id_veh', id_veh, 'id_berth', id_berth, 'is_completed', is_completed, 'state', state
++ print(' check id_veh', id_veh, 'id_berth', id_berth, 'is_completed', is_completed, 'state', state)
+
+ if not is_completed:
+ # will be send directly to output queue
+ if self.debug:
+- print ' passthrough, not final destination of vehicle.'
++ print(' passthrough, not final destination of vehicle.')
+
+ is_stop_moving_in = True
+ if self.debug:
+- print ' stop before first berths, wait for try_start at %.1fm' % (self.stoplines_in[id_stop])
++ print(' stop before first berths, wait for try_start at %.1fm' % (self.stoplines_in[id_stop]))
+
+ # this vehicle does not get allocated to a berth
+ # but will wait until vehicles with same destination move out
+@@ -4639,10 +4639,10 @@
+
+ elif id_berth == -1:
+ if self.debug:
+- print ' trip is completed but no berth => stop vehicles from moving in'
++ print(' trip is completed but no berth => stop vehicles from moving in')
+ is_stop_moving_in = True
+ if self.debug:
+- print ' stop before first berths and wait for allocation at %.1fm' % (self.stoplines_in[id_stop])
++ print(' stop before first berths and wait for allocation at %.1fm' % (self.stoplines_in[id_stop]))
+ self.ids_vehs_inqueue[id_stop].append(id_veh)
+ vehicles.control_stopline_enter(id_veh,
+ self.ids_stop_to_ids_edge_sumo[id_stop],
+@@ -4651,7 +4651,7 @@
+
+ elif (not is_stop_moving_in) & (id_berth != -1):
+ if self.debug:
+- print ' forewrard entering vehicle id_veh %d to id_berth_alight %d at pos %.2fm' % (id_veh, id_berth, self.get_berths().stoppositions[id_berth])
++ print(' forewrard entering vehicle id_veh %d to id_berth_alight %d at pos %.2fm' % (id_veh, id_berth, self.get_berths().stoppositions[id_berth]))
+ self.ids_vehs_alight_forward[id_stop].append(id_veh)
+ vehicles.control_berth_position_enter(
+ id_veh, id_berth,
+@@ -4660,7 +4660,7 @@
+ laneindex=2,
+ )
+ if self.debug:
+- print ' ids_vehs_inqueue (after)', self.ids_vehs_inqueue[id_stop]
++ print(' ids_vehs_inqueue (after)', self.ids_vehs_inqueue[id_stop])
+
+ def get_ids_veh_to_allocate(self, id_stop):
+ """Returns vehicle in input queue that needs berth allocation.
+@@ -4721,7 +4721,7 @@
+ return []
+
+ def exit(self, id_stop, id_veh, fase):
+- print 'exit prt.%d at stop %d fase %d' % (id_veh, id_stop, fase)
++ print('exit prt.%d at stop %d fase %d' % (id_veh, id_stop, fase))
+ self.ids_vehs[id_stop].remove(id_veh)
+ self.ids_vehs_ready_for_departure[id_stop].remove(id_veh)
+ #id_stop_target = self.parent.vehicleman.start_trip(id_veh, id_stop)
+@@ -4764,71 +4764,71 @@
+ # default berth ID is -1 means no merth available
+ ids_berth_alloc = -1*np.ones(n_alloc, dtype=np.int32)
+
+- print 'allocate_alight n_alloc', n_alloc, 'n_berth_to_allocate', n_berth_to_allocate, 'ind_berth_to_allocate', ind_berth_to_allocate
++ print('allocate_alight n_alloc', n_alloc, 'n_berth_to_allocate', n_berth_to_allocate, 'ind_berth_to_allocate', ind_berth_to_allocate)
+ if self.debug:
+- print ' ids_berth_to_allocate', ids_berth_to_allocate
++ print(' ids_berth_to_allocate', ids_berth_to_allocate)
+
+ if ind_berth_to_allocate == -1:
+ if self.debug:
+- print ' no free berth :('
++ print(' no free berth :(')
+ return ids_berth_alloc
+
+ elif n_berth_to_allocate <= n_alloc:
+ if self.debug:
+- print ' there is a less or equal number of free berth than requested'
++ print(' there is a less or equal number of free berth than requested')
+ # => use all berth available for allocatation
+ ids_berth_alloc[0:n_berth_to_allocate] = ids_berth_to_allocate[0:n_berth_to_allocate]
+ self.inds_berth_allocated[id_stop] = -1
+
+ else:
+ if self.debug:
+- print ' there are more berths available than vehicles to allocate'
++ print(' there are more berths available than vehicles to allocate')
+ # -> prefer berth with person queues
+ queues = self.get_berthqueues(id_stop, ids_berth_to_allocate)
+ #inds_nonzeroqueues = np.flatnonzero(ids_berth_to_allocate[::-1])
+
+ ind_alloc_eff = -1 # effective allocation index for result vector
+- for i, queue, id_berth in zip(xrange(n_berth_to_allocate), queues[::-1], ids_berth_to_allocate[::-1]):
+- print ' index i', i, 'id_berth', id_berth, 'queue', queue
++ for i, queue, id_berth in zip(range(n_berth_to_allocate), queues[::-1], ids_berth_to_allocate[::-1]):
++ print(' index i', i, 'id_berth', id_berth, 'queue', queue)
+ self.inds_berth_allocated[id_stop] -= 1
+ if queue == 0:
+ if self.debug:
+- print ' no passengers waiting'
++ print(' no passengers waiting')
+
+ # allocate this berth only if the number of the remaining
+ # available berth is less or equal the number of berth
+ # that remain to be allocated
+ is_allzero = not np.any(queues[::-1][i:])
+ if self.debug:
+- print ' remaining berth to alloc', ids_berth_to_allocate[::-1][i:]
+- print ' remaining queus to alloc', queues[::-1][i:]
+- print ' rem avail', n_berth_to_allocate-(i+1), 'rem to alloc', n_alloc-(ind_alloc_eff + 1), 'is_allzero', is_allzero
++ print(' remaining berth to alloc', ids_berth_to_allocate[::-1][i:])
++ print(' remaining queus to alloc', queues[::-1][i:])
++ print(' rem avail', n_berth_to_allocate-(i+1), 'rem to alloc', n_alloc-(ind_alloc_eff + 1), 'is_allzero', is_allzero)
+ if is_allzero | ((n_berth_to_allocate-(i+1)) < (n_alloc-(ind_alloc_eff + 1))):
+ ind_alloc_eff += 1
+ ids_berth_alloc[ind_alloc_eff] = id_berth
+ if self.debug:
+- print ' allocate id_berth', id_berth, 'at index', i
++ print(' allocate id_berth', id_berth, 'at index', i)
+ else:
+ if self.debug:
+- print ' passengers waiting, allocate'
++ print(' passengers waiting, allocate')
+ ind_alloc_eff += 1
+ ids_berth_alloc[ind_alloc_eff] = id_berth
+
+ if self.debug:
+- print ' allocate id_berth', id_berth, 'at index', i
++ print(' allocate id_berth', id_berth, 'at index', i)
+
+ if n_alloc == ind_alloc_eff + 1:
+ if self.debug:
+- print ' all vehicles allocated. Stop allocating.'
++ print(' all vehicles allocated. Stop allocating.')
+ break
+
+ if self.debug:
+- print ' finished allocating i', i, 'ind_berth_to_allocate', ind_berth_to_allocate, 'rem', n_berth_to_allocate-(i+1)
++ print(' finished allocating i', i, 'ind_berth_to_allocate', ind_berth_to_allocate, 'rem', n_berth_to_allocate-(i+1))
+
+ # print ' inds_berth_allocated',self.inds_berth_allocated [id_stop],n_berth_to_allocate-(i+1)
+ #self.inds_berth_allocated [id_stop] = n_berth_to_allocate-(i+1)
+ if self.debug:
+- print ' ids_berth_alloc', ids_berth_alloc
++ print(' ids_berth_alloc', ids_berth_alloc)
+ # set allocated to found berth only
+ self.get_berths().set_allocate(ids_berth_alloc[ids_berth_alloc > -1])
+
+@@ -4844,7 +4844,7 @@
+ stopposition = self.get_berths().stoppositions[id_berth]
+ # print ' stopposition',stopposition
+ is_queue = False
+- for id_person_sumo in self.waittimes_persons[id_stop].keys():
++ for id_person_sumo in list(self.waittimes_persons[id_stop].keys()):
+ is_queue = np.abs(stopposition-traci.person.getLanePosition(id_person_sumo)) < 0.8
+ if is_queue:
+ break
+@@ -4852,17 +4852,17 @@
+ return is_queue
+
+ def get_berthqueues(self, id_stop, ids_berth):
+- print 'get_berthqueues ids_berth', ids_berth
++ print('get_berthqueues ids_berth', ids_berth)
+ # currently not used
+ # print 'get_berthqueues',id_stop
+ # TODO: use stop angle and person angle to detect waiting persons
+ stoppositions = self.get_berths().stoppositions[ids_berth]
+ queues = np.zeros(len(ids_berth), dtype=np.int32)
+ # print ' stoppositions',stoppositions
+- for id_person_sumo in self.waittimes_persons[id_stop].keys():
++ for id_person_sumo in list(self.waittimes_persons[id_stop].keys()):
+ stage = traci.person.getStage(id_person_sumo, 0)
+ if self.debug:
+- print ' check id_person_sumo', id_person_sumo, 'Stagetype', stage.type, 'pos', traci.person.getLanePosition(id_person_sumo)
++ print(' check id_person_sumo', id_person_sumo, 'Stagetype', stage.type, 'pos', traci.person.getLanePosition(id_person_sumo))
+ # check if person is in wait pos! Actually this is stage type driving = 3
+ if stage.type == 3:
+ position = traci.person.getLanePosition(id_person_sumo)
+@@ -4880,7 +4880,7 @@
+ """
+ Make prt stop database from PT stops in network.
+ """
+- print 'make_from_net'
++ print('make_from_net')
+ self.clear()
+ net = self.get_scenario().net
+ ptstops = net.ptstops
+@@ -4906,7 +4906,7 @@
+ ptstops.positions_to[ids_ptstop],
+ edgelengths
+ ):
+- print ' check', id_stop, 'number of lanes', len(ids_lane), ids_lane
++ print(' check', id_stop, 'number of lanes', len(ids_lane), ids_lane)
+
+ ids_mode_allow = ids_modes_allow[ids_lane]
+ if len(ids_lane) == 3:
+@@ -4941,7 +4941,7 @@
+
+ class VehicleAdder(Process):
+ def __init__(self, vehicles, logger=None, **kwargs):
+- print 'VehicleAdder.__init__', vehicles, vehicles.parent.get_ident()
++ print('VehicleAdder.__init__', vehicles, vehicles.parent.get_ident())
+ self._init_common('vehicleadder', name='Vehicle adder',
+ logger=logger,
+ info='Add vehicles to PRT stops of network.',
+@@ -5091,7 +5091,7 @@
+
+ vtypes = self.get_scenario().demand.vtypes
+ prttype = 'HCPRT'
+- print 'make_vtype HPRT', prttype
++ print('make_vtype HPRT', prttype)
+ # speedmode
+ # https://sumo.dlr.de/docs/TraCI/Change_Vehicle_State.html
+ # bit0: Regard safe speed
+@@ -5129,10 +5129,10 @@
+ if vtypes.ids_sumo.has_index(prttype):
+ id_vtype = vtypes.ids_sumo.get_id_from_index(prttype)
+ vtypes.del_row(id_vtype)
+- print ' deleted', prttype, 'id_vtype', id_vtype
++ print(' deleted', prttype, 'id_vtype', id_vtype)
+
+ if (not vtypes.ids_sumo.has_index(prttype)) | is_reset_vtype:
+- print ' set default PRT values decel', self._decel_leader, 'decel_emergency', self._decel_emergency_leader
++ print(' set default PRT values decel', self._decel_leader, 'decel_emergency', self._decel_emergency_leader)
+ id_vtype = vtypes.add_vtype(prttype,
+ accel=self._accel_leader,
+ decel=self._decel_leader,
+@@ -5181,7 +5181,7 @@
+ speed_charging=0.03,
+ )
+ else:
+- print ' PRT type existing'
++ print(' PRT type existing')
+ id_vtype = vtypes.ids_sumo.get_id_from_index(prttype)
+ return id_vtype
+
+@@ -5194,7 +5194,7 @@
+ return vtypes.lengths[id_vtype]
+
+ def prepare_sim(self, process):
+- print 'PrtVehicles.prepare_sim'
++ print('PrtVehicles.prepare_sim')
+ if len(self) == 0:
+ return []
+
+@@ -5288,12 +5288,12 @@
+ # else:
+ # add new ghost
+ # ,self.ids_ghosts.shape
+- print 'add_ghost veh prt.%d ghost prt.%d dtm = %.1f dtmg = %.1f d0=%.1f' % (id_veh, id_ghost, dist_to_merge_veh, dist_to_merge_ghost, dist_to_merge_veh - dist_to_merge_ghost)
++ print('add_ghost veh prt.%d ghost prt.%d dtm = %.1f dtmg = %.1f d0=%.1f' % (id_veh, id_ghost, dist_to_merge_veh, dist_to_merge_ghost, dist_to_merge_veh - dist_to_merge_ghost))
+
+ if -1 not in ids_ghosts:
+- print 'ERROR: no more ghosts available, ids_ghosts', ids_ghosts
++ print('ERROR: no more ghosts available, ids_ghosts', ids_ghosts)
+ # sys.exit(1)
+- print ' overwrite last ghost'
++ print(' overwrite last ghost')
+ # here we could sunstitute the ghost with the longest distance
+ ind_ghost = len(ids_ghosts)-1
+ else:
+@@ -5307,7 +5307,7 @@
+ ind_ghost -= 1
+
+ if ind_ghost > 0:
+- print 'WARNING: unusual number of ghosts, ids_ghosts', ids_ghosts
++ print('WARNING: unusual number of ghosts, ids_ghosts', ids_ghosts)
+ # sys.exit(1)
+
+ self.ids_ghosts[id_veh][ind_ghost] = id_ghost
+@@ -5335,7 +5335,7 @@
+ self.del_ghost(id_veh, id_ghost)
+
+ def del_ghost(self, id_veh, id_ghost):
+- print 'del_ghost id_veh %d id_ghost %d' % (id_veh, id_ghost)
++ print('del_ghost id_veh %d id_ghost %d' % (id_veh, id_ghost))
+ if id_ghost in self.ids_ghosts[id_veh]:
+
+ ind_ghost = list(self.ids_ghosts[id_veh]).index(id_ghost)
+@@ -5368,12 +5368,12 @@
+
+ def switch_off_control(self, id_veh):
+ """Direct way to switch of SUMO control of vehicles"""
+- print 'switch_off_control id_veh', id_veh
++ print('switch_off_control id_veh', id_veh)
+ traci.vehicle.setSpeedMode(self.ids_sumo[id_veh], 6) # 6=respect max accel/decel
+
+ def switch_on_control(self, id_veh):
+ """Direct way to switch of SUMO control of vehicles"""
+- print 'switch_on_control id_veh', id_veh
++ print('switch_on_control id_veh', id_veh)
+ traci.vehicle.setSpeedMode(self.ids_sumo[id_veh], self._speedmode_leader)
+
+ def start_update(self, id_veh):
+@@ -5394,8 +5394,8 @@
+
+ def process_step(self, process):
+ simtime = process.simtime
+- print 79*'_'
+- print 'PrtVehicles.process_step at', simtime
++ print(79*'_')
++ print('PrtVehicles.process_step at', simtime)
+ net = self.get_scenario().net
+ vehicles = self.parent.prtvehicles
+ ids = self.get_ids()
+@@ -5403,24 +5403,24 @@
+ return
+ time_update = self.time_update.get_value()
+ decel_emergency = self.decel_emergency.get_value()
+- print ' update', len(np.flatnonzero(self.are_update[ids])), 'vehicles'
++ print(' update', len(np.flatnonzero(self.are_update[ids])), 'vehicles')
+ ids_update = ids[self.are_update[ids]]
+- print ' ids_update', ids_update
++ print(' ids_update', ids_update)
+ #ids_debug = [324,251,417,400]
+ #ids_debug = [182,133,204,170]
+ #ids_debug = [271, 304]
+ ids_debug = [482, 483, 484]
+ if 1:
+- print ' *Debug:'
++ print(' *Debug:')
+ #ids_debug = [307, 236, 41, 231, 208, 44, 249, 229, 136]
+ #ids_debug = [56, 271, 264, 244, 256, 253, 240, 251, 163, 150]
+ #ids_debug = [26,242,139,79,138]
+ #ids_debug = [2,482,44,63,67]
+ for id_veh, id_veh_sumo, id_follower, id_leader in zip(ids_debug, self.ids_sumo[ids_debug], self.ids_follower[ids_debug], self.ids_leader[ids_debug]):
+- print ' *id_veh prt.%d' % id_veh, 'id_follower', id_follower, 'id_leader', id_leader, 'ids_ghost', self.ids_ghosts[id_veh]
+- print ' id_stop_target', self.ids_stop_target[id_veh], 'lp=%.1fm' % self.lengths_plat[id_veh]
++ print(' *id_veh prt.%d' % id_veh, 'id_follower', id_follower, 'id_leader', id_leader, 'ids_ghost', self.ids_ghosts[id_veh])
++ print(' id_stop_target', self.ids_stop_target[id_veh], 'lp=%.1fm' % self.lengths_plat[id_veh])
+ if self.states[id_veh] > 0:
+- print ' pax', traci.vehicle.getPersonIDList(id_veh_sumo), 'isStopped', traci.vehicle.isStopped(id_veh_sumo), 'speed', traci.vehicle.getSpeed(id_veh_sumo)
++ print(' pax', traci.vehicle.getPersonIDList(id_veh_sumo), 'isStopped', traci.vehicle.isStopped(id_veh_sumo), 'speed', traci.vehicle.getSpeed(id_veh_sumo))
+
+ #self.id_follower_probe = self.ids_follower[271]
+
+@@ -5434,7 +5434,7 @@
+
+ if 0:
+ ids_ghost = self.ids_ghosts[id_veh]
+- print ' %7s' % id_veh_sumo, 'ghosts', ids_ghost, self.ids_leader[id_veh], "lp=%.1fm" % self.lengths_plat[id_veh]
++ print(' %7s' % id_veh_sumo, 'ghosts', ids_ghost, self.ids_leader[id_veh], "lp=%.1fm" % self.lengths_plat[id_veh])
+ #odo = self.odos[id_veh]
+ #delta_vehs = odo-self.odos0_vehicles[id_veh]
+ #delta_ghosts = self.odos[ids_ghost] - self.odos0_ghosts[id_veh]
+@@ -5548,9 +5548,9 @@
+ dist_min_check = dist0 + delta_ghost - delta_veh - \
+ self.lengths_plat[self.ids_ghosts[id_veh][0]] - self.length
+ # print ' %7s: v=%3.1f vg=%3.1f dh=%4.1f th=%4.1fs ds=%4.1f dc=%4.1f lp=%3.1f %s'%(id_sumo, velocity, velocitiy_ghost_min,dist_min,th,dist_safe,dist_comf,length_plat,a)
+- print ' %7s: v=%3.1f vg=%3.1f d0=%4.1f dh=%4.1f th=%3.1fs ds=%4.1f dc=%4.1f odo=%4.1f %s' % (id_sumo, velocity, velocitiy_ghost_min, dist0, dist_min, th, dist_safe, dist_comf, odo, a)
+- print ' dist_min', dist_min, 'dist_min_check', dist_min_check, 'id_ghost', self.ids_ghosts[id_veh][0]
+- print ' delta_veh', delta_veh, 'delta_ghost', delta_ghost, 'dist_rel', dist_rel
++ print(' %7s: v=%3.1f vg=%3.1f d0=%4.1f dh=%4.1f th=%3.1fs ds=%4.1f dc=%4.1f odo=%4.1f %s' % (id_sumo, velocity, velocitiy_ghost_min, dist0, dist_min, th, dist_safe, dist_comf, odo, a))
++ print(' dist_min', dist_min, 'dist_min_check', dist_min_check, 'id_ghost', self.ids_ghosts[id_veh][0])
++ print(' delta_veh', delta_veh, 'delta_ghost', delta_ghost, 'dist_rel', dist_rel)
+
+ fact_urgent = np.ones(dists_safe.shape, dtype=np.float32) # np.clip(dists_safe/diststomerge_min,0.0,1.0)
+
+@@ -5590,8 +5590,8 @@
+ """
+ This is the vehicle route to the next target, not necessary the final one.
+ """
+- print 'set_route_target prt.%d' % id_veh, 'id_stop_target', id_stop_target, 'is_disengage_from_berth', is_disengage_from_berth
+- print ' route', route
++ print('set_route_target prt.%d' % id_veh, 'id_stop_target', id_stop_target, 'is_disengage_from_berth', is_disengage_from_berth)
++ print(' route', route)
+
+ # set target only if valid target, otherwise set only route
+ if id_stop_target is not None:
+@@ -5625,7 +5625,7 @@
+ self.routes[id_veh] = []
+
+ def reset_speedmode(self, id_veh_sumo):
+- print 'reset_speedmode', id_veh_sumo
++ print('reset_speedmode', id_veh_sumo)
+ # speed mode (0xb3)
+ # Per default, the vehicle is using the given speed regarding the safe gap, the maximum acceleration, and the maximum deceleration. Furthermore, vehicles follow the right-of-way rules when approaching an intersection and if necessary they brake hard to avoid driving across a red light. One can control this behavior using the speed mode (0xb3) command, the given integer is a bitset (bit0 is the least significant bit) with the following fields:
+ # 1 bit0: Regard safe speed
+@@ -5641,7 +5641,7 @@
+ # pass
+
+ def concatenate(self, id_veh, id_veh_pre):
+- print 'concatenate prt.%d' % id_veh, 'behind prt.%d' % id_veh_pre
++ print('concatenate prt.%d' % id_veh, 'behind prt.%d' % id_veh_pre)
+ self.ids_leader[id_veh] = id_veh_pre
+ self.ids_follower[id_veh_pre] = id_veh
+
+@@ -5668,7 +5668,7 @@
+ else:
+ self._update_concatenate(id_veh, 0.0)
+
+- print ' length_plat=', self.lengths_plat[id_veh]
++ print(' length_plat=', self.lengths_plat[id_veh])
+
+ def _update_concatenate(self, id_veh, length_plat):
+ """
+@@ -5676,7 +5676,7 @@
+ """
+ # TODO: this is a very inefficient method because call each time a vehicle is added.
+ # Try to avoid altogether
+- print '_update_concatenate prt.%s, length_plat=%.1f, length=%.1f,' % (id_veh, length_plat, self.length), 'id_leader', self.ids_leader[id_veh]
++ print('_update_concatenate prt.%s, length_plat=%.1f, length=%.1f,' % (id_veh, length_plat, self.length), 'id_leader', self.ids_leader[id_veh])
+ if self.ids_leader[id_veh] == -1:
+ # first vehicle
+ # print ' first vehicle prt.%s'%id_veh,length_plat
+@@ -5687,7 +5687,7 @@
+ self._update_concatenate(self.ids_leader[id_veh], length_plat + self.length)
+
+ def decatenate(self, id_veh):
+- print 'decatenate prt.%d' % id_veh
++ print('decatenate prt.%d' % id_veh)
+
+ id_leader = self.ids_leader[id_veh]
+ # print ' id_leader',id_leader
+@@ -5734,7 +5734,7 @@
+ # remove platoon length
+ self.lengths_plat[id_veh] = 0.0
+
+- print ' length_plat=', self.lengths_plat[id_veh]
++ print(' length_plat=', self.lengths_plat[id_veh])
+
+ def get_platoonleader(self, id_veh_tail):
+ id_veh = 1*id_veh_tail
+@@ -5757,7 +5757,7 @@
+ return n
+
+ def get_platoon(self, id_veh_leader):
+- print 'get_platoon for leader prt.%d' % id_veh_leader
++ print('get_platoon for leader prt.%d' % id_veh_leader)
+ ids_veh = [id_veh_leader, ]
+ id_veh = self.ids_follower[id_veh_leader]
+ # print ' id_veh',id_veh
+@@ -5766,7 +5766,7 @@
+ id_veh = self.ids_follower[id_veh]
+ # print ' id_veh',id_veh
+
+- print ' ids_veh', ids_veh
++ print(' ids_veh', ids_veh)
+ return ids_veh
+
+ def get_entered_left(self, id_edge_sumo, ids_veh_previous_sumo):
+@@ -5779,7 +5779,7 @@
+ the first vehicle in the list entered/left first
+ """
+ ids_veh_new_sumo = traci.edge.getLastStepVehicleIDs(id_edge_sumo)
+- print 'get_entered_left ids_veh_new_sumo=', ids_veh_new_sumo
++ print('get_entered_left ids_veh_new_sumo=', ids_veh_new_sumo)
+ len_prev = len(ids_veh_previous_sumo)
+ len_new = len(ids_veh_new_sumo)
+
+@@ -5801,7 +5801,7 @@
+ break
+
+ ind_enter += 1
+- print ' ind_enter', ind_enter, ids_veh_new_sumo[0:ind_enter], ids_veh_new_sumo[ind_enter-1::-1]
++ print(' ind_enter', ind_enter, ids_veh_new_sumo[0:ind_enter], ids_veh_new_sumo[ind_enter-1::-1])
+ #ids_entered_sumo = ids_veh_new_sumo[0:ind_enter]
+
+ ind_leave = len_prev
+@@ -5811,7 +5811,7 @@
+ break
+
+ ind_leave -= 1
+- print ' ind_leave', ind_leave, ids_veh_previous_sumo[ind_leave:], ids_veh_previous_sumo[:ind_leave:-1]
++ print(' ind_leave', ind_leave, ids_veh_previous_sumo[ind_leave:], ids_veh_previous_sumo[:ind_leave:-1])
+ #ids_leave_sumo = ids_veh_previous_sumo[ind_leave:]
+
+ # return ids_entered_sumo, ids_leave_sumo, ids_veh_new_sumo
+@@ -5829,7 +5829,7 @@
+ stopline = pos + 3.0 + 0.5/self.decel*speed**2
+ #time_slowdown = np.abs((speed0-speed)/self.decel)
+
+- print 'control_stop', id_veh_sumo, 'v = %.2f at pos %.1fm to stop at %.1fm on %s' % (speed, pos, stopline, traci.vehicle.getRoadID(id_veh_sumo))
++ print('control_stop', id_veh_sumo, 'v = %.2f at pos %.1fm to stop at %.1fm on %s' % (speed, pos, stopline, traci.vehicle.getRoadID(id_veh_sumo)))
+ traci.vehicle.setStop(id_veh_sumo,
+ traci.vehicle.getRoadID(id_veh_sumo),
+ pos=stopline,
+@@ -5839,7 +5839,7 @@
+ def control_speedup(self, id_veh):
+
+ id_veh_sumo = self.get_id_sumo(id_veh)
+- print 'control_speedup', id_veh_sumo, 'isStopped', traci.vehicle.isStopped(id_veh_sumo), self.speed_max.get_value()
++ print('control_speedup', id_veh_sumo, 'isStopped', traci.vehicle.isStopped(id_veh_sumo), self.speed_max.get_value())
+
+ if traci.vehicle.isStopped(id_veh_sumo):
+ traci.vehicle.resume(id_veh_sumo)
+@@ -5848,13 +5848,13 @@
+ #self.control_slow_down(id_veh, self.speed_max.get_value())
+
+ def control_slow_down(self, id_veh, speed=1.0, time_slowdown=None):
+- print 'control_slow_down', self.get_id_sumo(id_veh), speed, time_slowdown
++ print('control_slow_down', self.get_id_sumo(id_veh), speed, time_slowdown)
+ id_veh_sumo = self.get_id_sumo(id_veh)
+ if time_slowdown is None:
+ speed0 = traci.vehicle.getSpeed(id_veh_sumo)
+
+ time_slowdown = np.abs((speed0-speed)/self.decel)
+- print ' speed0=%.2fm/s, time_slowdown = %.2fs, dv=%.2fm/s' % (speed0, time_slowdown, speed0-speed)
++ print(' speed0=%.2fm/s, time_slowdown = %.2fs, dv=%.2fm/s' % (speed0, time_slowdown, speed0-speed))
+
+ traci.vehicle.slowDown(id_veh_sumo, speed, time_slowdown)
+ #self.speed_max = vtypes.speeds_max[id_vtype]
+@@ -5873,9 +5873,9 @@
+ # state forewarding_exit_kickout was unknown!!!
+ id_veh_sumo = self.get_id_sumo(id_veh)
+ p = traci.vehicle.getLanePosition(id_veh_sumo)
+- print 'control_forewarding_exit', id_veh_sumo, p, '->', position, 'laneindex', laneindex
++ print('control_forewarding_exit', id_veh_sumo, p, '->', position, 'laneindex', laneindex)
+ if traci.vehicle.isStopped(id_veh_sumo):
+- print ' resume stop'
++ print(' resume stop')
+ traci.vehicle.resume(id_veh_sumo)
+
+ self.states[id_veh] = VEHICLESTATES['forewarding_exit_kickout']
+@@ -5884,7 +5884,7 @@
+ # print ' do not set a stop'
+ pass
+ else:
+- print ' set stop at pos', position
++ print(' set stop at pos', position)
+ traci.vehicle.setStop(id_veh_sumo,
+ id_edge_sumo,
+ pos=position,
+@@ -5898,7 +5898,7 @@
+ def control_stopline_enter(self, id_veh, id_edge_sumo, stopline, laneindex=1, flags=0):
+ # print 'control_stopline_enter',self.get_id_sumo(id_veh),stopline
+ id_veh_sumo = self.get_id_sumo(id_veh)
+- print 'control_stopline_enter', id_veh_sumo, 'lane %d, pos=%.2f->targetpos %.2f' % (laneindex, traci.vehicle.getLanePosition(id_veh_sumo), stopline)
++ print('control_stopline_enter', id_veh_sumo, 'lane %d, pos=%.2f->targetpos %.2f' % (laneindex, traci.vehicle.getLanePosition(id_veh_sumo), stopline))
+ traci.vehicle.setStop(id_veh_sumo,
+ id_edge_sumo,
+ pos=stopline,
+@@ -5919,13 +5919,13 @@
+ """
+ id_veh_sumo = self.get_id_sumo(id_veh)
+ p = traci.vehicle.getLanePosition(id_veh_sumo)
+- print 'control_berth_position_enter', id_veh_sumo, p, '->', position, 'id_berth', id_berth
++ print('control_berth_position_enter', id_veh_sumo, p, '->', position, 'id_berth', id_berth)
+
+ # here it can happen that vehicle has been programmed to stop in front
+ # of first berth to wait for allocation
+ # print ' getStopState',traci.vehicle.getStopState(id_veh_sumo)
+ # print ' getNextStops',traci.vehicle.getNextStops(id_veh_sumo)
+- print ' isStopped', traci.vehicle.isStopped(id_veh_sumo)
++ print(' isStopped', traci.vehicle.isStopped(id_veh_sumo))
+ # if len(traci.vehicle.getNextStops(id_veh_sumo))>0:
+
+ # already resumed
+@@ -5954,7 +5954,7 @@
+ p = traci.vehicle.getLanePosition(id_veh_sumo)
+ if position is None:
+ position = p+0.3
+- print 'control_berth_position_exit', id_veh_sumo, p, '->', position
++ print('control_berth_position_exit', id_veh_sumo, p, '->', position)
+ if traci.vehicle.isStopped(id_veh_sumo):
+ traci.vehicle.resume(id_veh_sumo)
+
+@@ -5972,7 +5972,7 @@
+
+ def control_berth_position_exit_slowdown(self, id_veh):
+ id_veh_sumo = self.get_id_sumo(id_veh)
+- print ' control_berth_position_exit_slowdown', id_veh_sumo
++ print(' control_berth_position_exit_slowdown', id_veh_sumo)
+ # function to stop vehicle after it moved out of the berth
+ if traci.vehicle.isStopped(id_veh_sumo):
+ traci.vehicle.resume(id_veh_sumo)
+@@ -5989,7 +5989,7 @@
+ """
+ id_veh_sumo = self.get_id_sumo(id_veh)
+ p = traci.vehicle.getLanePosition(id_veh_sumo)
+- print 'control_berth_stop', id_veh_sumo, p, '->', position
++ print('control_berth_stop', id_veh_sumo, p, '->', position)
+ #d = position - p
+ #v = traci.vehicle.getSpeed(id_veh_sumo)
+ #d_save = 1.0/(2*2.5)*(v**2)
+@@ -6012,8 +6012,8 @@
+
+ # NO LONGER USED
+ id_veh_sumo = self.get_id_sumo(id_veh)
+- print 'control_stop_board', id_veh_sumo, id_stop, id_berth, id_edge_sumo, 'pos=%.2f,target %.2f' % (traci.vehicle.getLanePosition(id_veh_sumo), position),
+- print ' v=', traci.vehicle.getSpeed(id_veh_sumo)
++ print('control_stop_board', id_veh_sumo, id_stop, id_berth, id_edge_sumo, 'pos=%.2f,target %.2f' % (traci.vehicle.getLanePosition(id_veh_sumo), position), end=' ')
++ print(' v=', traci.vehicle.getSpeed(id_veh_sumo))
+
+ # print 'control_stop_board',id_veh_sumo,traci.vehicle.getLanePosition(id_veh_sumo),'->',position,id_berth
+ self.ids_berth[id_veh] = id_berth
+@@ -6033,9 +6033,9 @@
+ def launch_from_stop(self, id_veh):
+
+ id_veh_sumo = self.get_id_sumo(id_veh)
+- print 'launch_from_stop', id_veh_sumo, 'is stopped', traci.vehicle.isStopped(id_veh_sumo)
++ print('launch_from_stop', id_veh_sumo, 'is stopped', traci.vehicle.isStopped(id_veh_sumo))
+ if traci.vehicle.isStopped(id_veh_sumo):
+- print ' resume!'
++ print(' resume!')
+ traci.vehicle.resume(id_veh_sumo)
+
+ route_sumo = self.get_scenario().net.edges.ids_sumo[self.routes[id_veh]]
+@@ -6044,7 +6044,7 @@
+ traci.vehicle.setMaxSpeed(id_veh_sumo, 6.0/3.6)
+ #traci.vehicle.setMaxSpeed(id_veh_sumo, self.speed_max.get_value())
+ #traci.vehicle.setMaxSpeed(id_veh_sumo, 0.66)
+- print ' after launch is stopped', traci.vehicle.isStopped(id_veh_sumo), 'getMaxSpeed', traci.vehicle.getMaxSpeed(id_veh_sumo)
++ print(' after launch is stopped', traci.vehicle.isStopped(id_veh_sumo), 'getMaxSpeed', traci.vehicle.getMaxSpeed(id_veh_sumo))
+
+ def alight(self, id_veh):
+ # print 'alight',self.get_id_sumo(id_veh)
+@@ -6077,7 +6077,7 @@
+
+ def init_passthrough(self, id_veh, id_edge_sumo, stopline, laneindex=1, flags=0):
+ id_veh_sumo = self.get_id_sumo(id_veh)
+- print 'init_passthrough', id_veh_sumo, 'lane %d, pos=%.2f->targetpos %.2f' % (laneindex, traci.vehicle.getLanePosition(id_veh_sumo), stopline)
++ print('init_passthrough', id_veh_sumo, 'lane %d, pos=%.2f->targetpos %.2f' % (laneindex, traci.vehicle.getLanePosition(id_veh_sumo), stopline))
+
+ # do n
+ #is_stop = True
+@@ -6099,7 +6099,7 @@
+ def foreward_passthrough(self, id_veh):
+
+ id_veh_sumo = self.get_id_sumo(id_veh)
+- print 'foreward_passthrough', id_veh_sumo
++ print('foreward_passthrough', id_veh_sumo)
+ if traci.vehicle.isStopped(id_veh_sumo):
+ # print ' resume!'
+ traci.vehicle.resume(id_veh_sumo)
+@@ -6108,16 +6108,16 @@
+
+ def reached_stop_sumo(self, id_veh_sumo):
+ state = traci.vehicle.getStopState(id_veh_sumo)
+- print 'reached_stop', id_veh_sumo, bin(state), bin(state)[-1] == '1'
++ print('reached_stop', id_veh_sumo, bin(state), bin(state)[-1] == '1')
+ return bin(state)[-1] == '1'
+
+ def is_completed_alighting(self, id_veh):
+- print 'is_completed_alighting', self.get_id_sumo(id_veh), self.states[id_veh], 'alighting', self.states[id_veh] == VEHICLESTATES['alighting'], 'pers on board', traci.vehicle.getPersonNumber(self.get_id_sumo(id_veh)), type(traci.vehicle.getPersonNumber(self.get_id_sumo(id_veh)))
++ print('is_completed_alighting', self.get_id_sumo(id_veh), self.states[id_veh], 'alighting', self.states[id_veh] == VEHICLESTATES['alighting'], 'pers on board', traci.vehicle.getPersonNumber(self.get_id_sumo(id_veh)), type(traci.vehicle.getPersonNumber(self.get_id_sumo(id_veh))))
+ if self.states[id_veh] == VEHICLESTATES['alighting']:
+ ids_persons_sumo_on_board = traci.vehicle.getPersonIDList(self.get_id_sumo(id_veh))
+ if self.ids_persons_sumo[id_veh].isdisjoint(ids_persons_sumo_on_board):
+ # if traci.vehicle.getPersonIDList(self.get_id_sumo(id_veh)) == 0:
+- print ' completed alighting ids_persons_sumo_on_board', ids_persons_sumo_on_board
++ print(' completed alighting ids_persons_sumo_on_board', ids_persons_sumo_on_board)
+ if len(ids_persons_sumo_on_board) > 0:
+ self.states[id_veh] = VEHICLESTATES['boarding']
+ else:
+@@ -6138,7 +6138,7 @@
+ if self.states[id_veh] in (VEHICLESTATES['boarding'], VEHICLESTATES['waiting']):
+ ids_person_sumo = traci.vehicle.getPersonIDList(self.get_id_sumo(id_veh))
+ if len(ids_person_sumo) == 1:
+- print ' completed boarding'
++ print(' completed boarding')
+ self.states[id_veh] = VEHICLESTATES['boarding_completed']
+ self.ids_persons_sumo[id_veh].add(ids_person_sumo)
+ return True
+@@ -6153,7 +6153,7 @@
+
+ def init_trip_occupied(self, id_veh, id_edge_sumo, stopline=None):
+ id_veh_sumo = self.get_id_sumo(id_veh)
+- print 'init_trip_occupied', self.get_id_sumo(id_veh), id_edge_sumo, stopline
++ print('init_trip_occupied', self.get_id_sumo(id_veh), id_edge_sumo, stopline)
+ # print ' current route:',traci.vehicle.getRoute(id_veh_sumo)
+ self.states[id_veh] = VEHICLESTATES['occupiedtrip']
+
+@@ -6174,7 +6174,7 @@
+ #traci.vehicle.slowDown(id_veh_sumo, speed_crawl, time_accel)
+
+ def init_trip_empty(self, id_veh, id_edge_sumo, stopline=None):
+- print 'Vehicles.init_trip_empty', self.get_id_sumo(id_veh), id_edge_sumo, stopline
++ print('Vehicles.init_trip_empty', self.get_id_sumo(id_veh), id_edge_sumo, stopline)
+ self.states[id_veh] = VEHICLESTATES['emptytrip']
+ id_veh_sumo = self.get_id_sumo(id_veh)
+ if traci.vehicle.isStopped(id_veh_sumo):
+@@ -6197,7 +6197,7 @@
+ #traci.vehicle.slowDown(id_veh_sumo, speed_crawl, time_accel)
+
+ def reschedule_trip(self, id_veh, id_edge_sumo_to=None, route_sumo=None):
+- print 'reschedule_trip', self.get_id_sumo(id_veh), id_edge_sumo_to, route_sumo
++ print('reschedule_trip', self.get_id_sumo(id_veh), id_edge_sumo_to, route_sumo)
+ id_veh_sumo = self.get_id_sumo(id_veh)
+ if traci.vehicle.isStopped(id_veh_sumo):
+ traci.vehicle.resume(id_veh_sumo)
+@@ -6288,7 +6288,7 @@
+ def get_ids_from_ids_sumo(self, ids_veh_sumo):
+ n = len(ids_veh_sumo)
+ ids = np.zeros(n, np.int32)
+- for i in xrange(n):
++ for i in range(n):
+ ids[i] = self.get_id_from_id_sumo(ids_veh_sumo[i])
+ return ids
+
+@@ -6364,7 +6364,7 @@
+ # put 2 for persons who prefer prt (probably few in pre PRT times)
+ preeval[persons.ids_mode_preferred[ids_person] == self.prtservice.id_prtmode] = 2
+
+- print ' HcPrtStrategy.preevaluate', len(np.flatnonzero(preeval))
++ print(' HcPrtStrategy.preevaluate', len(np.flatnonzero(preeval)))
+ return preeval
+
+ def plan(self, ids_person, logger=None):
+@@ -6372,7 +6372,7 @@
+ Generates a plan for these person according to this strategie.
+ Overriden by specific strategy.
+ """
+- print 'HcPrtStrategy.plan', len(ids_person)
++ print('HcPrtStrategy.plan', len(ids_person))
+ #make_plans_private(self, ids_person = None, mode = 'passenger')
+ # routing necessary?
+ virtualpop = self.get_virtualpop()
+@@ -6390,7 +6390,7 @@
+ prtstops = self.prtservice.prtstops
+
+ if len(prtstops) == 0:
+- print 'WARNING: no prt stops, no prt plans'
++ print('WARNING: no prt stops, no prt plans')
+ return True
+
+ net = scenario.net
+@@ -6411,14 +6411,14 @@
+
+ times_stop_to_stop = self.prtservice.times_stop_to_stop
+ if times_stop_to_stop is None:
+- print 'WARNING: stop to stop matrix not calculated. Please configure the PRT system.'
++ print('WARNING: stop to stop matrix not calculated. Please configure the PRT system.')
+ return True
+
+ ids_person_act, ids_act_from, ids_act_to\
+ = virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
+
+ if len(ids_person_act) == 0:
+- print 'WARNING in TrasitStrategy.plan: no eligible persons found.'
++ print('WARNING in TrasitStrategy.plan: no eligible persons found.')
+ return False
+
+ # temporary maps from ids_person to other parameters
+@@ -6437,7 +6437,7 @@
+ map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]
+
+ n_plans = len(ids_person_act)
+- print 'TrasitStrategy.plan n_plans=', n_plans
++ print('TrasitStrategy.plan n_plans=', n_plans)
+
+ # make initial activity stage
+ ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]
+@@ -6522,15 +6522,15 @@
+ if logger:
+ logger.progress(i/n_pers*100)
+ i += 1.0
+- print 79*'_'
+- print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)
++ print(79*'_')
++ print(' id_plan=%d, id_person=%d, ' % (id_plan, id_person))
+
+ if id_person == 17214:
+- print ' id_stop_from', id_stop_from, 'id_stop_to', id_stop_to
+- print ' id_stopedge_from', id_stopedge_from, 'id_stopedge_to', id_stopedge_to
++ print(' id_stop_from', id_stop_from, 'id_stop_to', id_stop_to)
++ print(' id_stopedge_from', id_stopedge_from, 'id_stopedge_to', id_stopedge_to)
+
+ if (dist_from_to < dist_walk_max) | (id_edge_from == -1) | (id_edge_to == -1) | (id_stop_from == id_stop_to):
+- print ' go by foot because distance is too short ', dist_from_to, 'edges', id_edge_from, id_edge_to, 'stops', id_stop_from, id_stop_to
++ print(' go by foot because distance is too short ', dist_from_to, 'edges', id_edge_from, id_edge_to, 'stops', id_stop_from, id_stop_to)
+
+ id_stage_walk1, time = walkstages.append_stage(
+ id_plan, time_from,
+@@ -6597,7 +6597,7 @@
+ # **kwargs,
+ ):
+
+- print 'HcPrtTransits.__init__', ident, stages
++ print('HcPrtTransits.__init__', ident, stages)
+ self.init_stagetable(ident,
+ stages, name=name,
+ info=info,
+@@ -6621,20 +6621,20 @@
+ ))
+
+ def set_prtservice(self, prtservice):
+- print 'HcPrtTransits.set_prtservice', prtservice, 'id(self)', id(self)
++ print('HcPrtTransits.set_prtservice', prtservice, 'id(self)', id(self))
+ self.add(cm.ObjConf(prtservice, is_child=False, groups=['_private']))
+
+ def get_prtservice(self):
+- print 'get_prtservice', self, id(self)
++ print('get_prtservice', self, id(self))
+ return self.hcprtservice.get_value()
+
+ def prepare_planning(self):
+
+ prtservice = self.get_prtservice()
+- print 'HcPrtTransits.prepare_planning', prtservice.times_stop_to_stop
++ print('HcPrtTransits.prepare_planning', prtservice.times_stop_to_stop)
+ if prtservice.times_stop_to_stop is None:
+ prtservice.make_times_stop_to_stop()
+- print prtservice.times_stop_to_stop
++ print(prtservice.times_stop_to_stop)
+
+ def append_stage(self, id_plan, time_start=-1.0,
+ duration=0.0,
+@@ -6781,7 +6781,7 @@
+ return self.parent.parent.get_scenario()
+
+ def prepare_sim(self, process):
+- print 'VehicleMan.prepare_sim'
++ print('VehicleMan.prepare_sim')
+ net = self.get_scenario().net
+
+ # station management
+@@ -6841,7 +6841,7 @@
+ self.ids_veh = self.get_vehicles().get_ids()
+
+ if len(self.ids_veh) == 0:
+- print 'WARNING: no PRT vehicles, please add PRT vehicles.'
++ print('WARNING: no PRT vehicles, please add PRT vehicles.')
+ return []
+
+ n_veharray = np.max(self.ids_veh)+1
+@@ -6872,7 +6872,7 @@
+ ]
+
+ def update_flows(self, process):
+- print 'HC VehicleMan update flow prediction'
++ print('HC VehicleMan update flow prediction')
+ self.inflows_sched[:, 0] = 0
+ self.inflows_sched = np.roll(self.inflows_sched, -1)
+ time_update_flows = self.time_update_flows.get_value()
+@@ -6902,8 +6902,8 @@
+ self.log_inflows_temp[:] = 0
+
+ def process_step(self, process):
+- print 79*'M'
+- print 'HC VehicleMan.process_step'
++ print(79*'M')
++ print('HC VehicleMan.process_step')
+
+ self.debug = 9
+
+@@ -6919,13 +6919,13 @@
+ is_cont = (n_move_eff_total > 0) & np.any(surpluses_veh_urgent > 0)
+ is_cont = False
+ if self.debug > 4:
+- print 79*'-'
+- print ' check equalize iteration', np.any(surpluses_veh > 0), np.any(balances_veh > 0), np.any(surpluses_veh_urgent > 0), 'is_cont', is_cont
+- print ' n_move_eff_total', n_move_eff_total
+- print ' surpluses_veh', surpluses_veh
+- print ' demands_veh', demands_veh
+- print ' balances_veh', balances_veh
+- print ' surpluses_veh_urgent', surpluses_veh_urgent
++ print(79*'-')
++ print(' check equalize iteration', np.any(surpluses_veh > 0), np.any(balances_veh > 0), np.any(surpluses_veh_urgent > 0), 'is_cont', is_cont)
++ print(' n_move_eff_total', n_move_eff_total)
++ print(' surpluses_veh', surpluses_veh)
++ print(' demands_veh', demands_veh)
++ print(' balances_veh', balances_veh)
++ print(' surpluses_veh_urgent', surpluses_veh_urgent)
+
+ if 0:
+ stops = self.get_stops()
+@@ -6961,7 +6961,7 @@
+ self.inflows_person[id_stop] += n_pax
+
+ def note_vehs_ready_for_departure(self, id_stop, id_stop_target, time_est, n_veh):
+- print 'note_vehs_ready_for_departure id_stop', id_stop, id_stop_target, time_est, n_veh
++ print('note_vehs_ready_for_departure id_stop', id_stop, id_stop_target, time_est, n_veh)
+ self.ids_stop_target_current[id_stop] = id_stop_target
+ self.duration_est_target_current[id_stop] = time_est
+ self.numbers_veh_target_current[id_stop] = n_veh
+@@ -6984,7 +6984,7 @@
+ # idea behind is that room for more slots are more difficult to find
+ n_slots_search = n_slots_search_empty + n_slots
+ if self.debug > 1:
+- print 'fit_vehicles n_veh', n_veh, 'n_slots', n_slots, 'capa_slots %.2f' % (capa * n_slots), 'at slot', ind_time_arrival, 'n_slots_search', n_slots_search
++ print('fit_vehicles n_veh', n_veh, 'n_slots', n_slots, 'capa_slots %.2f' % (capa * n_slots), 'at slot', ind_time_arrival, 'n_slots_search', n_slots_search)
+ ind_delay = 0
+ is_fit = False
+ while (ind_delay < n_slots_search) & (not is_fit) & (ind_time_arrival + ind_delay + n_slots < self.n_est_max):
+@@ -6993,15 +6993,15 @@
+ flows_sched = self.inflows_sched[id_stop, ind_time_arrival_sched:ind_time_arrival_sched+n_slots]
+
+ is_fit = np.sum(flows_sched) + n_veh < capa * n_slots
+- print ' ind_delay', ind_delay, 'is_fit', is_fit, 'from', ind_time_arrival_sched, 'to', ind_time_arrival_sched + n_slots, 'flows_sched', flows_sched, # 'max',self.n_est_max
++ print(' ind_delay', ind_delay, 'is_fit', is_fit, 'from', ind_time_arrival_sched, 'to', ind_time_arrival_sched + n_slots, 'flows_sched', flows_sched, end=' ') # 'max',self.n_est_max
+ ind_delay += 1
+
+ # check if sufficient time-slots in the future are available
+ # at estimated arrival time
+ if self.debug > 2:
+- print ' ind_time_arrival_sched', ind_time_arrival_sched, 'ind_delay', ind_delay
+- print ' flows_sched ', flows_sched
+- print ' n_slots ', n_slots, 'scheduled', np.sum(flows_sched), 'avail', capa * n_slots, 'is_fit', is_fit
++ print(' ind_time_arrival_sched', ind_time_arrival_sched, 'ind_delay', ind_delay)
++ print(' flows_sched ', flows_sched)
++ print(' n_slots ', n_slots, 'scheduled', np.sum(flows_sched), 'avail', capa * n_slots, 'is_fit', is_fit)
+
+ if self.debug > 5:
+ self.display_flows_est(id_stop, ind_time_arrival_sched, ind_time_arrival_sched+n_slots)
+@@ -7019,12 +7019,12 @@
+ capa_avail = capa_slot - flow_sched
+ n_alloc = min(int(capa_avail), n_veh-n_alloc_cum)
+ if self.debug > 5:
+- print ' i_slot', i_slot, 'capa_slot %.2f' % capa_slot, 'capa_avail %.2f' % capa_avail, 'n_alloc', n_alloc, 'n_alloc_cum', n_alloc_cum
++ print(' i_slot', i_slot, 'capa_slot %.2f' % capa_slot, 'capa_avail %.2f' % capa_avail, 'n_alloc', n_alloc, 'n_alloc_cum', n_alloc_cum)
+ if n_alloc > 0:
+ flows_alloc[i_slot] += n_alloc
+ n_alloc_cum += n_alloc
+ if self.debug > 5:
+- print ' add n_alloc', n_alloc, 'n_alloc_cum', n_alloc_cum
++ print(' add n_alloc', n_alloc, 'n_alloc_cum', n_alloc_cum)
+ # capacity of next slot is augmented by the
+ # rest capacity of the present slot
+ capa_slot = capa + (capa - n_alloc - flow_sched)
+@@ -7033,7 +7033,7 @@
+
+ # finally check whether all vehicle have been assigned
+ if self.debug > 2:
+- print ' n_alloc_cum', n_alloc_cum, 'n_veh', n_veh, 'flows_alloc', flows_alloc
++ print(' n_alloc_cum', n_alloc_cum, 'n_veh', n_veh, 'flows_alloc', flows_alloc)
+
+ # due to rounding errors the rest of the last slot may not be assigned
+ if n_alloc_cum < n_veh:
+@@ -7058,7 +7058,7 @@
+
+ n_slots = n_slots = np.ceil(float(n_veh)/capa)
+
+- print 'get_timeslot_occupation n_veh', n_veh, 'capa_int', capa_int, 'n_slots', n_slots, 'rem', n_veh - n_slots*capa_int
++ print('get_timeslot_occupation n_veh', n_veh, 'capa_int', capa_int, 'n_slots', n_slots, 'rem', n_veh - n_slots*capa_int)
+ if n_slots == 0:
+ flows = np.zeros(1, dtype=np.int32)
+ else:
+@@ -7080,7 +7080,7 @@
+ stops = self.get_stops()
+ ids_stop_all = stops.get_ids()
+ ids_stop = ids_stop_all[self.numbers_veh_target_current[ids_stop_all] > 0]
+- print 'HC push_out_vehicles of %d stops' % (len(ids_stop))
++ print('HC push_out_vehicles of %d stops' % (len(ids_stop)))
+ #vehicles = self.get_vehicles()
+
+ ids_stop_launched = []
+@@ -7092,10 +7092,10 @@
+ self.numbers_veh_target_current[ids_stop],
+ ):
+ time_depart = self.times_departure_sched[id_stop]
+- print '\n check id_stop', id_stop, 'id_stop_target', id_stop_target, 'n_veh', n_veh, 'dur %.2f' % duration_est, 't_dep', time_depart, 'simtime', simtime
++ print('\n check id_stop', id_stop, 'id_stop_target', id_stop_target, 'n_veh', n_veh, 'dur %.2f' % duration_est, 't_dep', time_depart, 'simtime', simtime)
+
+ if time_depart != -1:
+- print ' delay has been programmed is_launch', simtime > time_depart
++ print(' delay has been programmed is_launch', simtime > time_depart)
+ if (simtime > time_depart):
+ # simtime has reached scheduled departure time, so launch
+ self.times_departure_sched[id_stop] = -1
+@@ -7108,7 +7108,7 @@
+ time_arr_est = simtime + duration_est
+ ind_time_arrival = int(duration_est/time_update_flows+0.5)
+
+- print ' time_arr_est', time_arr_est, 'ind_time_arrival', ind_time_arrival, 'in range', ind_time_arrival < self.n_est_max
++ print(' time_arr_est', time_arr_est, 'ind_time_arrival', ind_time_arrival, 'in range', ind_time_arrival < self.n_est_max)
+
+ if ind_time_arrival < self.n_est_max:
+ # required number of free time slots for n_veh
+@@ -7118,24 +7118,24 @@
+ # allocation successful
+ self.inflows_sched[id_stop_target,
+ ind_time_arrival_sched:ind_time_arrival_sched+n_alloc] += flows_alloc
+- print ' schedule id_stop_target', id_stop_target, 'inflows_sched', self.inflows_sched[id_stop_target, ind_time_arrival_sched:ind_time_arrival_sched+n_alloc]
++ print(' schedule id_stop_target', id_stop_target, 'inflows_sched', self.inflows_sched[id_stop_target, ind_time_arrival_sched:ind_time_arrival_sched+n_alloc])
+ if ind_time_arrival_sched == ind_time_arrival:
+- print ' immediate launch'
++ print(' immediate launch')
+ self.times_departure_sched[id_stop] = -1
+ is_launch = True
+ else:
+ # delayed launch, determine scheduled launch time
+ self.times_departure_sched[id_stop] = simtime + \
+ ind_time_arrival_sched * time_update_flows - duration_est
+- print ' delayed launch: sched dep time', self.times_departure_sched[id_stop]
++ print(' delayed launch: sched dep time', self.times_departure_sched[id_stop])
+ is_launch = False
+
+ else:
+- print 'WARNING: no capacity available at id_stop_target', id_stop_target, ' at this arrival time.'
++ print('WARNING: no capacity available at id_stop_target', id_stop_target, ' at this arrival time.')
+ is_launch = False
+ else:
+ #
+- print'WARNING: arrival time out of measurement range for id_stop_target', id_stop_target
++ print('WARNING: arrival time out of measurement range for id_stop_target', id_stop_target)
+ is_launch = True
+
+ if is_launch:
+@@ -7172,7 +7172,7 @@
+ stops = self.get_stops()
+ ids_stop = stops.get_ids()
+ n_stops = len(ids_stop)
+- print 'equalize_empty_vehicles of %d stops' % n_stops
++ print('equalize_empty_vehicles of %d stops' % n_stops)
+
+ balances_veh = np.zeros(n_stops, dtype=np.float32)
+ demands_veh = np.zeros(n_stops, dtype=np.float32)
+@@ -7198,7 +7198,7 @@
+ surpluses_veh[i] = surplus_veh # this is current surplus, vehicles immediately available
+ surpluses_veh_urgent[i] = surplus_veh_urgent # number of vehicles that need to be kicked out
+ if self.debug > 2:
+- print '\n sssssssssseek destinations for id_stop', id_stop
++ print('\n sssssssssseek destinations for id_stop', id_stop)
+
+ if self.debug > 5:
+ self.display_flows_est(id_stop)
+@@ -7208,22 +7208,22 @@
+ surplus_veh + surplus_veh_future - n_pax_wait - n_pax_future
+
+ if self.debug > 2:
+- print ' surplus_veh', surplus_veh, 'surplus_future', surplus_veh_future, 'surplus_veh_urgent', surplus_veh_urgent
+- print ' n_pax_wait ', n_pax_wait, 'n_pax_future', n_pax_future
+- print ' balance ', balances_veh[i]
+- print ' waittime_max ', waittimes_max[i]
++ print(' surplus_veh', surplus_veh, 'surplus_future', surplus_veh_future, 'surplus_veh_urgent', surplus_veh_urgent)
++ print(' n_pax_wait ', n_pax_wait, 'n_pax_future', n_pax_future)
++ print(' balance ', balances_veh[i])
++ print(' waittime_max ', waittimes_max[i])
+ i += 1
+
+ inds_sorted = np.argsort(balances_veh)
+
+ #surpluses_veh_emitters = surpluses_veh[inds_sorted[::-1]]
+ if self.debug > 2:
+- print ' Emitters sorted:'
+- print ' ids_stop_sorted ', ids_stop[inds_sorted[::-1]]
+- print ' surpluses_veh', surpluses_veh[inds_sorted[::-1]]
+- print ' balances_sorted ', balances_veh[inds_sorted[::-1]]
+- print ' max(surpluses_veh)', max(surpluses_veh)
+- print ' >>>max(balances_veh)', max(balances_veh)
++ print(' Emitters sorted:')
++ print(' ids_stop_sorted ', ids_stop[inds_sorted[::-1]])
++ print(' surpluses_veh', surpluses_veh[inds_sorted[::-1]])
++ print(' balances_sorted ', balances_veh[inds_sorted[::-1]])
++ print(' max(surpluses_veh)', max(surpluses_veh))
++ print(' >>>max(balances_veh)', max(balances_veh))
+
+ if (np.max(balances_veh) > 0) & (max(surpluses_veh) > 0):
+
+@@ -7238,7 +7238,7 @@
+ if (surplus_from >= 1) & (balance_from >= 1):
+ if self.debug > 5:
+ # ,'ind_from',ind_from,'continue?',(surplus_from >= 1) & (balance_from >= 1)
+- print '\n potential emitter stop: id_stop_from', id_stop_from, 'surplus_from', surplus_from, 'balance_from', balance_from
++ print('\n potential emitter stop: id_stop_from', id_stop_from, 'surplus_from', surplus_from, 'balance_from', balance_from)
+ # there are empties to send away and positive balance
+ utilities = np.zeros(n_stops, dtype=np.float32)
+ numbers_move = np.zeros(n_stops, dtype=np.int32)
+@@ -7251,9 +7251,9 @@
+ time_to = times_stop_to_stop[id_stop_from, id_stop_to]
+
+ if self.debug > 5:
+- print ' j', j, 'id_stop_from ', id_stop_from, 'id_stop_to', id_stop_to
+- print ' balance_from', balance_from, 'balance_to', balance_to, 'min', -balance_to+0.5, surplus_from
+- print ' demand_to', demand_to, 'waittime_max_to', waittime_max_to
++ print(' j', j, 'id_stop_from ', id_stop_from, 'id_stop_to', id_stop_to)
++ print(' balance_from', balance_from, 'balance_to', balance_to, 'min', -balance_to+0.5, surplus_from)
++ print(' demand_to', demand_to, 'waittime_max_to', waittime_max_to)
+
+ if (surplus_from >= 1) & (balance_from >= 1) & (demand_to > 0):
+ # the demand of the station is positive
+@@ -7262,13 +7262,13 @@
+ # move the maximum possible number of available vehicles
+ n_move = min(int(demand_to+0.5), surplus_from, int(-demand_from+0.5))
+ if self.debug > 5:
+- print ' potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to
++ print(' potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to)
+ #utilities[j] = n_move+ self.constant_timeweight*time_to
+ utilities[j] = float(n_move)/float(time_to)
+ #utilities[j] = waittime_max_to/float(time_to)
+ numbers_move[j] = n_move
+ if self.debug > 5:
+- print ' =>U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to)
++ print(' =>U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to))
+
+ elif (surplus_veh_urgent_from > 0):
+ # we have a stop where we want to send out the maximum number of vehicles
+@@ -7282,13 +7282,13 @@
+ # high balance means vehicle needs to be kicked out
+
+ if self.debug > 5:
+- print ' forced potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to
++ print(' forced potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to)
+ #utilities[j] = n_move+ self.constant_timeweight*time_to
+ #utilities[j] = float(n_move)/float(time_to)
+ utilities[j] = n_move*(demand_to)/float(time_to)
+ numbers_move[j] = n_move
+ if self.debug > 5:
+- print ' =>U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to)
++ print(' =>U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to))
+
+ j += 1
+
+@@ -7306,7 +7306,7 @@
+ n_move_eff = stops.route_empties(
+ id_stop_from, ids_stop[inds_sorted][ind_max], numbers_move[ind_max], simtime)
+ if self.debug > 2:
+- print ' moved', n_move_eff, 'of', numbers_move[ind_max], 'empty vehs from', id_stop_from, 'to', ids_stop[inds_sorted][ind_max], 'utility_max', utility_max
++ print(' moved', n_move_eff, 'of', numbers_move[ind_max], 'empty vehs from', id_stop_from, 'to', ids_stop[inds_sorted][ind_max], 'utility_max', utility_max)
+
+ # continute till balance is zero?
+ # indeed need to update balances
+@@ -7336,7 +7336,7 @@
+ stops = self.get_stops()
+ ids_stop = stops.get_ids()
+ n_stops = len(ids_stop)
+- print 'equalize_empty_vehicles of %d stops' % n_stops
++ print('equalize_empty_vehicles of %d stops' % n_stops)
+
+ balances_veh = np.zeros(n_stops, dtype=np.float32)
+ demands_veh = np.zeros(n_stops, dtype=np.float32)
+@@ -7363,7 +7363,7 @@
+ surpluses_veh[i] = surplus_veh # this is current surplus, vehicles immediately available
+ surpluses_veh_urgent[i] = surplus_veh_urgent # number of vehicles that need to be kicked out
+ if self.debug > 2:
+- print '\n sssssssssseek destinations for id_stop', id_stop
++ print('\n sssssssssseek destinations for id_stop', id_stop)
+
+ if self.debug > 5:
+ self.display_flows_est(id_stop)
+@@ -7374,10 +7374,10 @@
+ #balances_veh[i] = 1000.0 *surplus_veh_urgent + 1.0*surplus_veh + surplus_veh_future - n_pax_wait - n_pax_future
+ balances_veh[i] = 1.0*surplus_veh + surplus_veh_future - n_pax_wait - n_pax_future
+ if self.debug > 2:
+- print ' surplus_veh', surplus_veh, 'surplus_future', surplus_veh_future, 'surplus_veh_urgent', surplus_veh_urgent
+- print ' n_pax_wait ', n_pax_wait, 'n_pax_future', n_pax_future
+- print ' balance ', balances_veh[i]
+- print ' waittime_max ', waittimes_max[i]
++ print(' surplus_veh', surplus_veh, 'surplus_future', surplus_veh_future, 'surplus_veh_urgent', surplus_veh_urgent)
++ print(' n_pax_wait ', n_pax_wait, 'n_pax_future', n_pax_future)
++ print(' balance ', balances_veh[i])
++ print(' waittime_max ', waittimes_max[i])
+ i += 1
+
+ # sort per surpluses, because this is the most critical quantity
+@@ -7386,30 +7386,30 @@
+ inds_sorted = np.argsort(surpluses_veh*(surpluses_veh_urgent+1))
+ #surpluses_veh_emitters = surpluses_veh[inds_sorted[::-1]]
+ if self.debug > 2:
+- print ' Emitters sorted:'
+- print ' ids_stop_sorted ', ids_stop[inds_sorted[::-1]]
+- print ' surpluses_veh', surpluses_veh[inds_sorted[::-1]]
+- print ' surpluses_veh_urgent', surpluses_veh_urgent[inds_sorted[::-1]]
+-
+- print ' balances_sorted ', balances_veh[inds_sorted[::-1]]
+- print ' max(surpluses_veh)', max(surpluses_veh)
+- print ' >>>max(balances_veh)', max(balances_veh)
++ print(' Emitters sorted:')
++ print(' ids_stop_sorted ', ids_stop[inds_sorted[::-1]])
++ print(' surpluses_veh', surpluses_veh[inds_sorted[::-1]])
++ print(' surpluses_veh_urgent', surpluses_veh_urgent[inds_sorted[::-1]])
++
++ print(' balances_sorted ', balances_veh[inds_sorted[::-1]])
++ print(' max(surpluses_veh)', max(surpluses_veh))
++ print(' >>>max(balances_veh)', max(balances_veh))
+
+ if (np.max(balances_veh) > 0) & (max(surpluses_veh) > 0):
+ if self.debug > 5:
+- print ' start optimizing target', len(inds_sorted[::-1])
++ print(' start optimizing target', len(inds_sorted[::-1]))
+ i = 0
+ for id_stop_from, ind_from in zip(ids_stop[inds_sorted[::-1]], inds_sorted[::-1]):
+ balance_from = balances_veh[ind_from]
+ surplus_from = surpluses_veh[ind_from]
+ surplus_veh_urgent_from = surpluses_veh_urgent[ind_from]
+ demand_from = demands_veh[ind_from]
+- print ' surplus_from', surplus_from, 'balance_from', balance_from
++ print(' surplus_from', surplus_from, 'balance_from', balance_from)
+ # distribute surplus on neares, most in need
+ if (surplus_from >= 1) & (balance_from >= 1):
+ if self.debug > 5:
+ # ,'ind_from',ind_from,'continue?',(surplus_from >= 1) & (balance_from >= 1)
+- print '\n potential emitter stop: id_stop_from', id_stop_from, 'surplus_from', surplus_from, 'balance_from', balance_from
++ print('\n potential emitter stop: id_stop_from', id_stop_from, 'surplus_from', surplus_from, 'balance_from', balance_from)
+ # there are empties to send away and positive balance
+ utilities = np.zeros(n_stops, dtype=np.float32)
+ numbers_move = np.zeros(n_stops, dtype=np.int32)
+@@ -7421,9 +7421,9 @@
+ time_to = times_stop_to_stop[id_stop_from, id_stop_to]
+
+ if self.debug > 5:
+- print ' id_stop_from ', id_stop_from, 'id_stop_to', id_stop_to
+- print ' balance_from', balance_from, 'balance_to', balance_to, 'min', -balance_to+0.5, surplus_from
+- print ' demand_to', demand_to, 'waittime_max_to', waittime_max_to
++ print(' id_stop_from ', id_stop_from, 'id_stop_to', id_stop_to)
++ print(' balance_from', balance_from, 'balance_to', balance_to, 'min', -balance_to+0.5, surplus_from)
++ print(' demand_to', demand_to, 'waittime_max_to', waittime_max_to)
+
+ if (surplus_from >= 1) & (balance_from >= 1) & (demand_to > 0):
+ # the demand of the station is positive
+@@ -7432,15 +7432,15 @@
+ # move the maximum possible number of available vehicles
+ n_move = min(int(demand_to+0.5), surplus_from, int(-demand_from+0.5))
+ if self.debug > 5:
+- print ' potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to
++ print(' potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to)
+ #utilities[j] = n_move+ self.constant_timeweight*time_to
+ #utilities[j] = float(n_move)/float(time_to)
+ utilities[j] = (waittime_max_to*demand_to)/float(time_to)
+ numbers_move[j] = n_move
+ if self.debug > 5:
+- print ' ********'
+- print ' U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to)
+- print ' ********'
++ print(' ********')
++ print(' U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to))
++ print(' ********')
+ j += 1
+
+ elif 0: # (surplus_veh_urgent_from> 0 ):
+@@ -7455,13 +7455,13 @@
+ # high balance means vehicle needs to be kicked out
+
+ if self.debug > 5:
+- print ' forced potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to
++ print(' forced potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to)
+ #utilities[j] = n_move+ self.constant_timeweight*time_to
+ #utilities[j] = float(n_move)/float(time_to)
+ utilities[j] = n_move*(demand_to)/float(time_to)
+ numbers_move[j] = n_move
+ if self.debug > 5:
+- print ' U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to)
++ print(' U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to))
+ j += 1
+
+ ind_max = np.argmax(utilities)
+@@ -7472,14 +7472,14 @@
+ # or is this done in the platoon formation?
+ n_move = min(numbers_move[ind_max], 8)
+ if self.debug > 2:
+- print ' utility_max %.0f' % utility_max, 'ind_max', ind_max, 'n_move', n_move
++ print(' utility_max %.0f' % utility_max, 'ind_max', ind_max, 'n_move', n_move)
+ #min(numbers_move[ind_max], self.flows_stop_max[ids_stop[inds_sorted][ind_max]])
+ if n_move > 0:
+ # there are some useful moves
+ n_move_eff = stops.route_empties(
+ id_stop_from, ids_stop[inds_sorted][ind_max], numbers_move[ind_max], simtime)
+ if self.debug > 2:
+- print ' => moved', n_move_eff, 'of', numbers_move[ind_max], 'empty vehs from', id_stop_from, 'to', ids_stop[inds_sorted][ind_max], 'utility_max', utility_max
++ print(' => moved', n_move_eff, 'of', numbers_move[ind_max], 'empty vehs from', id_stop_from, 'to', ids_stop[inds_sorted][ind_max], 'utility_max', utility_max)
+
+ # continute till balance is zero?
+ # indeed need to update balances
+@@ -7510,8 +7510,8 @@
+ inds_disp = np.array(inds*factor, dtype=np.int32)
+ disp[inds_disp] = self.inflows_sched[id_stop, inds]
+
+- print '%03d' % id_stop+(n_char-3)*'.'
+- print string.join(disp, '')
++ print('%03d' % id_stop+(n_char-3)*'.')
++ print(string.join(disp, ''))
+
+ disp = None
+ if timeind_begin is not None:
+@@ -7522,7 +7522,7 @@
+ disp[int(timeind_end*factor+0.5)] = '<'
+
+ if disp is not None:
+- print string.join(disp, '')
++ print(string.join(disp, ''))
+ # print ' flows',flows
+ # print ' inds',inds
+ # print ' inds_disp',inds_disp
+@@ -7538,7 +7538,7 @@
+ # & (stops.numbers_person_wait[self.ids_stop_current[ids_veh_lead]] == 0))
+ vehicles = self.get_vehicles()
+ stops = self.get_stops()
+- print 'pull_empty_leadvehs', ids_veh_lead
++ print('pull_empty_leadvehs', ids_veh_lead)
+ # print ' bordingstate',vehicles.states[ids_veh_lead] == VEHICLESTATES['boarding']
+ # print ' nowaits stop',stops.numbers_person_wait[self.ids_stop_current[ids_veh_lead]] ==0
+
+@@ -7575,7 +7575,7 @@
+ ids_stop_target = self.ids_stop[inds_valid]
+ demands = demands[inds_valid]
+
+- print ' ids_stop_current', ids_stop_current
++ print(' ids_stop_current', ids_stop_current)
+ # print ' ids_stop_target',ids_stop_target
+ # print ' demands',demands
+ # calculate cost matrix with id_stop_current in rows and id_stop_target
+@@ -7592,7 +7592,7 @@
+ costs = timeweight * demands
+ for id_stop_target, demand, number_veh, number_veh_arr\
+ in zip(ids_stop_target, demands, stops.numbers_veh[ids_stop_target], self.numbers_veh_arr[ids_stop_target]):
+- print ' id_stop_target', id_stop_target, 'dem', demand, 'n_veh', number_veh, 'n_veh_arr', number_veh_arr
++ print(' id_stop_target', id_stop_target, 'dem', demand, 'n_veh', number_veh, 'n_veh_arr', number_veh_arr)
+
+ #costs = np.zeros(costs.size, np.float32)-demands
+
+@@ -7622,7 +7622,7 @@
+ durations_est,
+ ):
+
+- print ' check veh prt.%d' % (id_veh_lead), state, 'id_stop_current', id_stop_current, 'id_stop_target', id_stop_target
++ print(' check veh prt.%d' % (id_veh_lead), state, 'id_stop_current', id_stop_current, 'id_stop_target', id_stop_target)
+
+ #VEHICLESTATES = {'init':0,'waiting':1,'boarding':2,'alighting':3,'emptytrip':4,'occupiedtrip':5,'forewarding':6}
+ # if state == VEHICLESTATES['occupiedtrip']:
+@@ -7657,7 +7657,7 @@
+ Called from the stop when a vehicle in the berth initiate a trip with
+ a the target destination of persons who entered
+ """
+- print 'init_trip_occupied to', id_stop_to
++ print('init_trip_occupied to', id_stop_to)
+ # search closest stop
+ #self.are_emptytrips[id_veh] = False
+
+@@ -7672,7 +7672,7 @@
+ Called from the stop when a vehicle in the berth initiate a trip with
+ a the target destination
+ """
+- print 'init_trip_empty to', id_stop_to
++ print('init_trip_empty to', id_stop_to)
+
+ self.numbers_veh_target_init[id_stop_to] += 1
+
+@@ -7681,7 +7681,7 @@
+ Called from the stop when a vehicle in the berth initiate a trip with
+ a the target destination defined by the vehicle management
+ """
+- print 'init_trip_empty to', id_stop_to
++ print('init_trip_empty to', id_stop_to)
+
+ self.numbers_veh_target_init[id_stop_to] += 1
+
+@@ -7741,7 +7741,7 @@
+ return self.parent.parent
+
+ def _init_attributes(self):
+- print 'HcPrtService._init_attributes'
++ print('HcPrtService._init_attributes')
+ attrsman = self.get_attrsman()
+ scenario = self.get_scenario()
+ # here we ged classes not vehicle type
+@@ -7774,7 +7774,7 @@
+ virtualpop = self.get_scenario().demand.virtualpop
+ prttransits = virtualpop.get_plans().add_stagetable('hcprttransits', HcPrtTransits)
+
+- print ' prttransits =', prttransits, id(prttransits)
++ print(' prttransits =', prttransits, id(prttransits))
+ # add attribute as link
+ # self.prttransits = attrsman.add(\
+ # cm.ObjConf(prttransits,is_child = False ),
+@@ -7818,7 +7818,7 @@
+
+ Method used to sort trips when exporting to route or trip xml file
+ """
+- print 'PRT.get_writexmlinfo'
++ print('PRT.get_writexmlinfo')
+
+ if is_plain:
+ return [], [], []
+@@ -7914,14 +7914,14 @@
+ # self.make_times_stop_to_stop()
+
+ def prepare_sim(self, process):
+- print 'prepare_sim', self.ident
++ print('prepare_sim', self.ident)
+ # print ' self.times_stop_to_stop',self.times_stop_to_stop
+
+ if self.fstar is None:
+ self.make_fstar()
+
+ if self.times_stop_to_stop is None:
+- print ' times_stop_to_stop'
++ print(' times_stop_to_stop')
+ self.make_times_stop_to_stop()
+
+ updatedata = self.prtvehicles.prepare_sim(process)
+@@ -7951,7 +7951,7 @@
+ return route, duration
+
+ def make_times_stop_to_stop(self, fstar=None, times=None):
+- print 'make_times_stop_to_stop'
++ print('make_times_stop_to_stop')
+ log = self.get_logger()
+ if fstar is None:
+ if self.fstar is None:
+@@ -7976,8 +7976,8 @@
+ is_incomplete_fstar = False
+ for id_edge, id_stop, id_ptstop in zip(ids_edge, ids_prtstop, ids_ptstop):
+ # print ' Found PRT stop %d, PT stop %d with id_edge %d '%(id_stop,id_ptstop, id_edge)
+- if not fstar.has_key(id_edge):
+- print 'WARNING in make_times_stop_to_stop: PRT stop %d, PT stop %d has no id_edge %d in fstar' % (id_stop, id_ptstop, id_edge)
++ if id_edge not in fstar:
++ print('WARNING in make_times_stop_to_stop: PRT stop %d, PT stop %d has no id_edge %d in fstar' % (id_stop, id_ptstop, id_edge))
+ is_incomplete_fstar = True
+
+ # check if fstar is complete (all to edges are in keys)
+@@ -7987,9 +7987,9 @@
+ if not ids_fromedge_set.issuperset(fstar[id_fromedge]):
+ is_incomplete_fstar = True
+ ids_miss = fstar[id_fromedge].difference(ids_fromedge_set)
+- print 'WARNING in make_times_stop_to_stop: incomplete fstar of id_fromedge = %d, %s' % (id_fromedge, ids_sumo[id_fromedge])
++ print('WARNING in make_times_stop_to_stop: incomplete fstar of id_fromedge = %d, %s' % (id_fromedge, ids_sumo[id_fromedge]))
+ for id_edge in ids_miss:
+- print ' missing', id_edge, ids_sumo[id_edge]
++ print(' missing', id_edge, ids_sumo[id_edge])
+
+ if is_incomplete_fstar:
+ return
+@@ -8036,7 +8036,7 @@
+ stop_to_stop[ids_edge_to_ids_prtstop[id_edge],
+ ids_edge_to_ids_prtstop[id_edge_target]] = costs[id_edge_target]
+ else:
+- print 'WARNING in make_times_stop_to_stop: unreacle station id_fromedge = %d, %s' % (id_edge_target, ids_sumo[id_edge_target])
++ print('WARNING in make_times_stop_to_stop: unreacle station id_fromedge = %d, %s' % (id_edge_target, ids_sumo[id_edge_target]))
+ is_incomplete_fstar = True
+
+ # put back origin to targets (probably not the best way)
+@@ -8051,7 +8051,7 @@
+
+ self.times_stop_to_stop = stop_to_stop
+ self.ids_edge_to_ids_prtstop = ids_edge_to_ids_prtstop
+- print ' times_stop_to_stop=\n', self.times_stop_to_stop
++ print(' times_stop_to_stop=\n', self.times_stop_to_stop)
+ return True
+
+ def get_fstar(self):
+@@ -8059,7 +8059,7 @@
+ Returns the forward star graph of the network as dictionary:
+ fstar[id_fromedge] = set([id_toedge1, id_toedge2,...])
+ """
+- print 'get_fstar'
++ print('get_fstar')
+ net = self.get_scenario().net
+ # prt mode
+ id_mode = self.id_prtmode
+@@ -8096,7 +8096,7 @@
+ if id_mode_allow_from == id_mode:
+ if id_mode_allow_to == id_mode:
+
+- if fstar.has_key(id_fromedge):
++ if id_fromedge in fstar:
+ fstar[id_fromedge].add(id_toedge)
+ else:
+ fstar[id_fromedge] = set([id_toedge])
+@@ -8133,7 +8133,7 @@
+ #id_mode = net.modes.get_id_mode(mode)
+ id_mode = self.id_prtmode
+ # print 'get_times id_mode,is_check_lanes,speed_max',id_mode,is_check_lanes,speed_max
+- ids_edge = np.array(fstar.keys(), dtype=np.int32)
++ ids_edge = np.array(list(fstar.keys()), dtype=np.int32)
+
+ times = np.array(np.zeros(np.max(ids_edge)+1, np.float32))
+ speeds = net.edges.speeds_max[ids_edge]
+@@ -8146,7 +8146,7 @@
+ return times
+
+ def config_results(self, results):
+- print 'HcPrtService.config_results', results, id(results)
++ print('HcPrtService.config_results', results, id(results))
+ # keep a link to results here because needed to
+ # log data during simulation
+ # this link should not be followed during save process
+@@ -8223,8 +8223,8 @@
+ # return self.ids_stop.get_linktab()
+
+ def init_recording(self, n_timesteps, time_step):
+- print 'HC init_recording n_timesteps, time_step', n_timesteps, time_step, len(self.ids_stop.get_linktab().get_ids())
+- print ' stops instance', self.prtstops.get_value(), self.ids_stop.get_linktab(), id(self.prtstops.get_value()), id(self.ids_stop.get_linktab())
++ print('HC init_recording n_timesteps, time_step', n_timesteps, time_step, len(self.ids_stop.get_linktab().get_ids()))
++ print(' stops instance', self.prtstops.get_value(), self.ids_stop.get_linktab(), id(self.prtstops.get_value()), id(self.ids_stop.get_linktab()))
+ self.clear()
+
+ self.time_step.set_value(time_step)
+@@ -8242,13 +8242,13 @@
+
+ inds = self.ids_stop.get_linktab().get_inds(ids)
+ timestep_int = int(timestep)
+- for attrname, values in kwargs.iteritems():
+- print ' record', attrname, 'dtype', values.dtype, values.shape, 'array', getattr(self, attrname).get_value().dtype, 'shape', getattr(self, attrname).get_value().shape
++ for attrname, values in kwargs.items():
++ print(' record', attrname, 'dtype', values.dtype, values.shape, 'array', getattr(self, attrname).get_value().dtype, 'shape', getattr(self, attrname).get_value().shape)
+ # print ' inds',type(inds),inds.dtype,
+ getattr(self, attrname).get_value()[inds, timestep_int] = values
+
+ def get_stopresultattrconfigs(self):
+- return self.get_attrsman().get_group_attrs('PRT results').values()
++ return list(self.get_attrsman().get_group_attrs('PRT results').values())
+
+ def get_persons(self):
+ return self.ids_person.get_linktab()
+--- tools/contributed/sumopy/plugins/hcprt/results_mpl.py (original)
++++ tools/contributed/sumopy/plugins/hcprt/results_mpl.py (refactored)
+@@ -42,11 +42,11 @@
+ self._init_common('stopresultsplotter', parent=results, name=name,
+ info=info, logger=logger)
+
+- print 'StopresultsPlotter.__init__', results, self.parent, len(self.get_stopresults())
++ print('StopresultsPlotter.__init__', results, self.parent, len(self.get_stopresults()))
+ attrsman = self.get_attrsman()
+
+ stops = self.get_stopresults().get_prtstops()
+- print ' prtstops', stops, len(stops), id(stops), self.get_stopresults().ids_stop.get_linktab(), id(self.get_stopresults().ids_stop.get_linktab())
++ print(' prtstops', stops, len(stops), id(stops), self.get_stopresults().ids_stop.get_linktab(), id(self.get_stopresults().ids_stop.get_linktab()))
+ choices_stop = {}
+ for id_stop in stops.get_ids():
+ choices_stop[str(id_stop)] = id_stop
+@@ -131,10 +131,10 @@
+
+ def show(self):
+ stopresults = self.get_stopresults()
+- print 'show', stopresults
++ print('show', stopresults)
+ # print ' dir(vehicleman)',dir(vehicleman)
+
+- print ' len(stopresults)', len(stopresults)
++ print(' len(stopresults)', len(stopresults))
+ if len(stopresults) > 0:
+ i_fig = 0
+ plt.close("all")
+@@ -166,7 +166,7 @@
+ plt.show()
+
+ def plot_flow_stop(self, fig):
+- print 'plot_flow_stop'
++ print('plot_flow_stop')
+ id_stop = self.id_stop_plot
+ stopresults = self.get_stopresults()
+ ax = fig.add_subplot(111)
+@@ -224,7 +224,7 @@
+ ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ def plot_waiting_person_time(self, fig):
+- print 'plot_waiting_person_time'
++ print('plot_waiting_person_time')
+ stopresults = self.get_stopresults()
+ ax = fig.add_subplot(111)
+
+@@ -251,7 +251,7 @@
+ ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ def plot_waiting_person_number_stop(self, fig):
+- print 'plot_waiting_person_number_stop'
++ print('plot_waiting_person_number_stop')
+ stopresults = self.get_stopresults()
+ #ax1 = fig.add_subplot(211)
+ #ax2 = fig.add_subplot(212)
+@@ -275,7 +275,7 @@
+ ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ def plot_waiting_person_number(self, fig):
+- print 'plot_waiting_person_number'
++ print('plot_waiting_person_number')
+ stopresults = self.get_stopresults()
+ #ax1 = fig.add_subplot(211)
+ #ax2 = fig.add_subplot(212)
+@@ -288,7 +288,7 @@
+ # works:ax.plot(time.reshape(n_steps,1),numbers_person_wait.reshape(n_steps,-1))
+ i = 0
+ for id_stop in stopresults.ids_stop.get_value():
+- print ' id_stop', id_stop
++ print(' id_stop', id_stop)
+ ax.plot(time, stopresults.numbers_person_wait[id_stop],
+ get_color(i), linewidth=self.width_line,
+ label='PRT Stop ID=%d' % id_stop)
+@@ -302,7 +302,7 @@
+ ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ def plot_flows_compare(self, fig):
+- print 'plot_flows_compare'
++ print('plot_flows_compare')
+ stopresults = self.get_stopresults()
+ #time_update_flows = self.parent.vehicleman.time_update_flows.get_value()
+ time_update_flows = 10
+@@ -315,7 +315,7 @@
+ i = 0
+ flowmatrix = np.zeros((10, 10), dtype=np.int32)
+ for id_stop in stopresults.ids_stop.get_value():
+- print ' id_stop', id_stop
++ print(' id_stop', id_stop)
+ # print ' sched',stopresults.inflows_veh_sched[id_stop]
+ # print ' eff ',stopresults.inflows_veh[id_stop]
+ flowmatrix[np.array(time_update_flows*stopresults.inflows_veh_sched[id_stop], dtype=np.int32),
+@@ -325,7 +325,7 @@
+ # label = 'PRT Stop ID=%d (effective)'%id_stop)
+
+ i += 1
+- print 'flowmatrix', flowmatrix
++ print('flowmatrix', flowmatrix)
+ # ax.matshow(flowmatrix)
+
+ cax = ax.matshow(flowmatrix, cmap=cmx.get_cmap('PuBu'))
+@@ -338,7 +338,7 @@
+ ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ def plot_flows_compare_stop(self, fig):
+- print 'plot_flows_compare_stop'
++ print('plot_flows_compare_stop')
+ stopresults = self.get_stopresults()
+ id_stop = self.id_stop_plot
+ #time_update_flows = self.parent.vehicleman.time_update_flows.get_value()
+@@ -358,7 +358,7 @@
+
+ time = np.arange(-n_steps+1, n_steps, dtype=np.float32)*t_step
+
+- print ' len(flowcorr),n_steps', len(flowcorr), len(time), n_steps
++ print(' len(flowcorr),n_steps', len(flowcorr), len(time), n_steps)
+
+ ax.plot(time, flowcorr,
+ get_color(i), linewidth=self.width_line,
+@@ -372,7 +372,7 @@
+ ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ def plot_flows(self, fig):
+- print 'plot_flows'
++ print('plot_flows')
+ stopresults = self.get_stopresults()
+ ax = fig.add_subplot(111)
+
+@@ -408,7 +408,7 @@
+ # ('inflows_person', {'name':'Person in-flows', 'unit':'1/s', 'dtype':np.float32, 'info':'Person flow into the stop over time.'}),
+
+ def plot_waiting_person(self, fig):
+- print 'plot_waiting_person'
++ print('plot_waiting_person')
+ stopresults = self.get_stopresults()
+ ax1 = fig.add_subplot(211)
+ ax2 = fig.add_subplot(212)
+--- tools/contributed/sumopy/plugins/hcprt/wxgui.py (original)
++++ tools/contributed/sumopy/plugins/hcprt/wxgui.py (refactored)
+@@ -28,13 +28,13 @@
+ from coremodules.network import routing
+ from coremodules.demand import demand
+ from coremodules.simulation import sumo, results
+-import hcprt
++from . import hcprt
+
+ try:
+- import results_mpl as results_mpl
++ from . import results_mpl as results_mpl
+ is_mpl = True # we have matplotlib support
+ except:
+- print "WARNING: python matplotlib package not installed, no matplotlib plots."
++ print("WARNING: python matplotlib package not installed, no matplotlib plots.")
+ is_mpl = False
+
+
+@@ -91,7 +91,7 @@
+ dependent on the availability of data.
+ """
+ scenario = self.get_scenario()
+- print 'prtgui.refresh_widgets', self._simulation != scenario.simulation
++ print('prtgui.refresh_widgets', self._simulation != scenario.simulation)
+
+ is_refresh = False
+ if self._simulation != scenario.simulation:
+@@ -214,7 +214,7 @@
+ self._mainframe.browse_obj(self._prtservice.prtvehicles)
+
+ def on_mpl_stopresults(self, event=None):
+- print 'on_mpl_stopresults', id(self._simulation.results) # ,id(self._prtservice.get_results())
++ print('on_mpl_stopresults', id(self._simulation.results)) # ,id(self._prtservice.get_results())
+ if self._prtservice is not None:
+ if self._simulation is not None:
+ resultplotter = results_mpl.StopresultsPlotter(self._simulation.results, # self._prtservice.get_results(),
+--- tools/contributed/sumopy/plugins/mapmatching/__init__.py (original)
++++ tools/contributed/sumopy/plugins/mapmatching/__init__.py (refactored)
+@@ -18,12 +18,12 @@
+
+ __version__ = "0.0"
+
+-print 'init', __name__
++print('init', __name__)
+
+
+ def get_wxgui():
+ # try:
+- from wxgui import WxGui
++ from .wxgui import WxGui
+ return WxGui(__name__)
+ # except:
+ # return None
+--- tools/contributed/sumopy/plugins/mapmatching/mapmatching.py (original)
++++ tools/contributed/sumopy/plugins/mapmatching/mapmatching.py (refactored)
+@@ -71,12 +71,12 @@
+ from shapely.geometry import Polygon, MultiPolygon, MultiLineString, Point, LineString, MultiPoint, asLineString, asMultiPoint
+ from shapely.ops import cascaded_union
+ except:
+- print 'Import error: No shapely module available.'
++ print('Import error: No shapely module available.')
+ except:
+- print 'Import error: in order to run the traces plugin please install the following modules:'
+- print ' mpl_toolkits.basemap and shapely'
+- print 'Please install these modules if you want to use it.'
+- print __doc__
++ print('Import error: in order to run the traces plugin please install the following modules:')
++ print(' mpl_toolkits.basemap and shapely')
++ print('Please install these modules if you want to use it.')
++ print(__doc__)
+ raise
+
+ AGES_STRAVA = {'unknown':0,
+@@ -409,7 +409,7 @@
+
+ class OdCreator(Process):
+ def __init__(self, ident, mapmatching, logger = None, **kwargs):
+- print 'VpCreator.__init__'
++ print('VpCreator.__init__')
+ self._init_common( ident,
+ parent = mapmatching,
+ name = 'Od routes creator from GPS trips',
+@@ -484,7 +484,7 @@
+ info='transport mode of the flow.',
+ ))
+ def do(self):
+- print 'OdCreator.__do__'
++ print('OdCreator.__do__')
+ #Preparation
+ logger = self.get_logger()
+ scenario = self.get_scenario()
+@@ -519,7 +519,7 @@
+ to_zone[id_trip] = id_zone
+ analyzedtrips += 0.5
+ break
+- print analyzedtrips
++ print(analyzedtrips)
+ i = 0
+ j= 0
+ for id_zonei in ids_zone:
+@@ -532,7 +532,7 @@
+ j = 0
+
+ n_trip = np.sum(od_matrix)
+- print ' number of trips', n_trip
++ print(' number of trips', n_trip)
+ generated = np.zeros(len(od_matrix[0,:]))
+ attracted = np.zeros(len(od_matrix[:,0]))
+
+@@ -563,8 +563,8 @@
+
+
+ re_allocates = generated - attracted
+- print 'generated',generated, 'attracted',attracted, 're_allocates', re_allocates
+- print 'od_matrix',od_matrix
++ print('generated',generated, 'attracted',attracted, 're_allocates', re_allocates)
++ print('od_matrix',od_matrix)
+ np.savetxt('od_matrix.csv', od_matrix)
+
+ return od_matrix, generated, attracted, re_allocates
+@@ -577,7 +577,7 @@
+
+ class OdRouteCreator(Process):
+ def __init__(self, ident, mapmatching, logger = None, **kwargs):
+- print 'OdRouteCreator.__init__'
++ print('OdRouteCreator.__init__')
+ self._init_common( ident,
+ parent = mapmatching,
+ name = 'Od routes creator from GPS trips',
+@@ -589,7 +589,7 @@
+
+
+ def do(self):
+- print 'OdRouteCreator.__do__'
++ print('OdRouteCreator.__do__')
+ #Preparation
+ logger = self.get_logger()
+ scenario = self.get_scenario()
+@@ -603,7 +603,7 @@
+ ids_trip = trips.get_ids()
+ ids_trip = ids_trip[trips.are_selected[ids_trip] & np.logical_not(np.equal(trips.ids_points[ids_trip],None))]
+ n_trips = len(ids_trip)
+- print ' len(ids_trip)',n_trips
++ print(' len(ids_trip)',n_trips)
+
+ trips_demand.clear_trips()
+ trips_demand.clear_routes()
+@@ -643,7 +643,7 @@
+
+ class VpCreator(Process):
+ def __init__(self, ident='vpcreator', mapmatching=None, logger = None, **kwargs):
+- print 'VpCreator.__init__'
++ print('VpCreator.__init__')
+ self._init_common( ident,
+ parent = mapmatching,
+ name = 'VP creator from GPS trips',
+@@ -795,7 +795,7 @@
+
+
+ def do(self):
+- print 'VpCreator.__do__'
++ print('VpCreator.__do__')
+ #Preparation
+ logger = self.get_logger()
+ scenario = self.get_scenario()
+@@ -831,8 +831,8 @@
+
+ persons = scenario.demand.mapmatching.persons
+ persons.analyze()
+- print 'id_strategy =',self.id_strategy
+- print 'is_first_method =',self.is_first_method
++ print('id_strategy =',self.id_strategy)
++ print('is_first_method =',self.is_first_method)
+ #select strategy
+ if self.is_first_method == True:
+ if self.id_strategy == -1:
+@@ -843,7 +843,7 @@
+ ids_trip = ids_trip_bike
+ ids_trip = np.append(ids_trip,ids_trip_bus)
+ ids_trip = np.append(ids_trip,ids_trip_ped)
+- print 'ids_trip =',ids_trip
++ print('ids_trip =',ids_trip)
+ # ids_trip = ids_trip_bike + ids_trip_ped + ids_trip_bus
+ if self.id_strategy == strategies.get_id_from_formatted('walk'):
+ ids_trip_ped = ids_trip[(ids_mode == modes.get_id_from_formatted('pedestrian'))]
+@@ -912,9 +912,9 @@
+
+ if self.is_first_method == True:
+ n_pers = int(n_pers*(float(self.scale - count))) #scale parameter based on people number
+- print 'new n_pers = ',n_pers
++ print('new n_pers = ',n_pers)
+
+- print 'old ids_trip = ',ids_trip
++ print('old ids_trip = ',ids_trip)
+
+ if self.id_strategy == -1:
+ ids_trip = np.array([],dtype = np.int32)
+@@ -947,14 +947,14 @@
+ #ids_trip = np.random.choice(ids_trip, n_pers, replace = False)
+ #ids_trip.sort()
+
+- print 'new ids_trip = ',ids_trip
++ print('new ids_trip = ',ids_trip)
+
+
+ elif self.is_first_method == False:
+ n_trips_tab = int(n_trips_for_scale*(float(self.scale - count))) # scale parameter based on trips number
+- print 'new n_pers = ',n_pers
++ print('new n_pers = ',n_pers)
+
+- print 'old ids_pers = ',ids_pers
++ print('old ids_pers = ',ids_pers)
+
+ if self.id_strategy == -1:
+
+@@ -1003,13 +1003,13 @@
+ #ids_pers = np.random.choice(ids_pers, n_pers, replace = False)
+ #ids_pers.sort()
+
+- print 'new ids_pers = ',ids_pers
++ print('new ids_pers = ',ids_pers)
+ elif count == max(range(int(self.scale + 1.0))) and difference == 0.0:
+ break
+
+ if self.is_first_method == True:
+ #create virtual person
+- print 'create virtal person'
++ print('create virtal person')
+ ids_person = virtualpop.make_multiple(n_pers)
+
+ ## localtime = time.localtime
+@@ -1024,7 +1024,7 @@
+ ## seconds_arrive = np.zeros(n_pers, dtype = np.float32)
+ ## duration_for_scale = np.zeros(n_pers, dtype = np.float32)
+
+- for id_trip, id_person, i in zip(ids_trip, ids_person, range(len(ids_trip))):
++ for id_trip, id_person, i in zip(ids_trip, ids_person, list(range(len(ids_trip)))):
+ #Population attributes
+ virtualpop.ids_mode_preferred[id_person] = scenario.demand.vtypes.ids_mode[trips.ids_vtype[id_trip]]
+ virtualpop.years_birth[id_person] = persons.years_birth[trips.ids_person[id_trip]]
+@@ -1052,9 +1052,9 @@
+
+ elif self.is_first_method == False:
+ #create virtual person
+- print 'create virtal person'
++ print('create virtal person')
+ ids_vppers = virtualpop.make_multiple(n_pers)
+- print 'ids_vppers',ids_vppers
++ print('ids_vppers',ids_vppers)
+ pers_vppers = np.zeros(np.max(ids_pers)+1, dtype = np.int32)
+ ## pers_vppers = []
+ for pers, vppers in zip(ids_pers, ids_vppers):
+@@ -1064,7 +1064,7 @@
+
+ for id_pers, id_vppers, ids_trip in zip(ids_pers, ids_vppers, ids_trips):
+ #Population attributes
+- print 'Add population attributes'
++ print('Add population attributes')
+ ids_mode = scenario.demand.vtypes.ids_mode[trips.ids_vtype[ids_trip]]
+ id_preferred_mode = np.argmax(np.bincount(ids_mode))
+ virtualpop.ids_mode_preferred[id_vppers] = id_preferred_mode
+@@ -1074,7 +1074,7 @@
+ virtualpop.identifications[id_vppers] = persons.ids_sumo[id_pers]
+
+ #Calculate trips departure and arrive times
+- print 'Calculate trips departure and arrive times'
++ print('Calculate trips departure and arrive times')
+
+ if self.id_strategy == strategies.get_id_from_formatted('bike') or self.id_strategy == -1:
+ seconds_departure_bike = np.zeros(len(ids_trip_bike), dtype = np.float32)
+@@ -1104,13 +1104,13 @@
+ seconds_arrive_bike[i] = seconds_departure_bike[i] + duration_for_scale_bike[i]
+
+ i+=1
+- print ' min_seconds_departure_bike: ',min_seconds_departure_bike
+- print ' max_seconds_arrive_bike: ',max_seconds_departure_bike
+- print
+- print ' ids_trip_bike: ',ids_trip_bike
+- print
+- print ' seconds_departure_bike: ', seconds_departure_bike
+- print
++ print(' min_seconds_departure_bike: ',min_seconds_departure_bike)
++ print(' max_seconds_arrive_bike: ',max_seconds_departure_bike)
++ print()
++ print(' ids_trip_bike: ',ids_trip_bike)
++ print()
++ print(' seconds_departure_bike: ', seconds_departure_bike)
++ print()
+
+
+ if self.id_strategy == strategies.get_id_from_formatted('transit') or self.id_strategy == -1:
+@@ -1144,7 +1144,7 @@
+
+ i+=1
+
+- print seconds_departure_bus, seconds_arrive_bus
++ print(seconds_departure_bus, seconds_arrive_bus)
+
+ if self.id_strategy == strategies.get_id_from_formatted('walk') or self.id_strategy == -1:
+ seconds_departure_ped = np.zeros(len(ids_trip_ped), dtype = np.float32)
+@@ -1177,7 +1177,7 @@
+ i+=1
+
+
+- print seconds_departure_ped, seconds_arrive_ped
++ print(seconds_departure_ped, seconds_arrive_ped)
+
+
+ # call Vehicle provider to give vehicles to persons
+@@ -1211,10 +1211,10 @@
+ fstar = net.edges.get_fstar()
+
+ #Preapare parameters for stages
+- print 'Preapare parameters for stages'
++ print('Preapare parameters for stages')
+
+ #bus
+- print 'Preapare parameters for BUS plans'
++ print('Preapare parameters for BUS plans')
+ if self.id_strategy == strategies.get_id_from_formatted('transit') or self.id_strategy == -1:
+ times_from_bus = seconds_departure_bus
+ durations_approx_bus = seconds_arrive_bus - seconds_departure_bus
+@@ -1261,13 +1261,13 @@
+
+ ## ids_route = trips.ids_route_matched[ids_trip]
+ #Identify closest edge for facilities
+- print 'Identify closest edge for facilities from'
++ print('Identify closest edge for facilities from')
+ facilities.identify_closest_edge(ids = ids_fac_from_bus, priority_max = 7, has_sidewalk = True)
+- print 'Identify closest edge for facilities to'
++ print('Identify closest edge for facilities to')
+ facilities.identify_closest_edge(ids = ids_fac_to_bus, priority_max = 7, has_sidewalk = True)
+
+ #bike
+- print 'Preapare parameters for BIKE plans'
++ print('Preapare parameters for BIKE plans')
+
+ if self.id_strategy == strategies.get_id_from_formatted('bike') or self.id_strategy == -1:
+ times_from_bike = seconds_departure_bike
+@@ -1325,16 +1325,16 @@
+ ids_fac_to_bike[i] = int(distance_fac_list_to[0,1])
+ i+=1
+
+- print 'ids_only_bike_trip', ids_only_bike_trip
++ print('ids_only_bike_trip', ids_only_bike_trip)
+ ## ids_route = trips.ids_route_matched[ids_trip]
+ #Identify closest edge for facilities
+- print 'Identify closest edge for facilities from'
++ print('Identify closest edge for facilities from')
+ facilities.identify_closest_edge(ids = ids_fac_from_bike, priority_max = 7, has_sidewalk = True)
+- print 'Identify closest edge for facilities to'
++ print('Identify closest edge for facilities to')
+ facilities.identify_closest_edge(ids = ids_fac_to_bike, priority_max = 7, has_sidewalk = True)
+
+ #pedestrian
+- print 'Preapare parameters for PEDESTRIAN plans'
++ print('Preapare parameters for PEDESTRIAN plans')
+
+ if self.id_strategy == strategies.get_id_from_formatted('walk') or self.id_strategy == -1:
+ times_from_ped = seconds_departure_ped
+@@ -1374,7 +1374,7 @@
+ available_strategies.append(strategies.get_id_from_formatted('transit'))
+
+ for strategy in available_strategies:
+- print 'init strategy', strategy
++ print('init strategy', strategy)
+
+
+ if strategy == strategies.get_id_from_formatted('bike'):
+@@ -1404,7 +1404,7 @@
+
+
+ #walk1
+- print 'Prepare parameters for Walk1'
++ print('Prepare parameters for Walk1')
+
+ ids_edge_from_walk1 = facilities.ids_roadedge_closest[ids_fac_from]
+ positions_edge_from_walk1 = facilities.positions_roadedge_closest[ids_fac_from]
+@@ -1424,7 +1424,7 @@
+ ids_edge_to_walk1 = facilities.ids_roadedge_closest[ids_fac_to]
+ if strategy == strategies.get_id_from_formatted('transit') or strategy == strategies.get_id_from_formatted('bike'):
+ #walk2
+- print 'Prepare parameters for Walk2'
++ print('Prepare parameters for Walk2')
+
+ times_from_walk2 = seconds_arrive +1.-1.
+
+@@ -1437,9 +1437,9 @@
+ ids_edge_from_walk2 = ids_edge_to_busstop
+ positions_edge_from_walk2 = positions_edge_to_busstop
+
+- print seconds_arrive
++ print(seconds_arrive)
+ #act1
+- print 'Prepare parameters for Act1'
++ print('Prepare parameters for Act1')
+
+ unitvec_int_act = np.ones(n_trips)
+ ids_edge_from_act1 = facilities.ids_roadedge_closest[ids_fac_from]
+@@ -1449,7 +1449,7 @@
+ times_from_act1 = seconds_departure-3600.0
+
+ #act2
+- print 'Prepare parameters for Act2'
++ print('Prepare parameters for Act2')
+
+ ids_edge_to_act2 = facilities.ids_roadedge_closest[ids_fac_to]
+ positions_edge_to = facilities.positions_roadedge_closest[ids_fac_to]
+@@ -1458,7 +1458,7 @@
+ durations_act_to = np.ones(n_trips)*3600.0
+
+ #Add activities
+- print 'Add activities '
++ print('Add activities ')
+ ## ids_fac_from = ids_facilities[ids_fac_from]
+ ## ids_fac_to = ids_facilities[ids_fac_to]
+
+@@ -1485,7 +1485,7 @@
+ virtualpop.activitypatterns[id_person] = [id_activity_from,id_activity_to, ]
+
+ #Create plans
+- print 'Create plans'
++ print('Create plans')
+ ids_plan = virtualpop.add_plans(ids_person, strategy)
+
+ # QUESTO METODO POTREBBE ESSERE VALIDO ANCHE PER VPCREATOR1???
+@@ -1493,18 +1493,18 @@
+ for id_person,id_activity_from,id_activity_to in zip(ids_person,ids_activity_from,ids_activity_to):
+ if virtualpop.activitypatterns[id_person] is not None:
+ patterns = virtualpop.activitypatterns[id_person]
+- print 'patterns', patterns
++ print('patterns', patterns)
+ patterns.append(id_activity_from)
+- print 'patterns', patterns
++ print('patterns', patterns)
+ patterns.append(id_activity_to)
+- print 'patterns', patterns
++ print('patterns', patterns)
+ virtualpop.activitypatterns[id_person] = patterns
+- print 'patterns', patterns
++ print('patterns', patterns)
+ else:
+ virtualpop.activitypatterns[id_person] = [id_activity_from, id_activity_to]
+
+ #Create plans
+- print 'Create plans'
++ print('Create plans')
+ if strategy == strategies.get_id_from_formatted('transit') or strategy ==strategies.get_id_from_formatted('bike'):
+ ids_plan = virtualpop.add_plans(ids_person, strategy)
+ elif strategy == strategies.get_id_from_formatted('walk'):
+@@ -1515,7 +1515,7 @@
+
+
+ #Add activity stages
+- print 'Add activity stages'
++ print('Add activity stages')
+
+ for id_plan,\
+ id_act_from,\
+@@ -1542,7 +1542,7 @@
+ )
+
+ #Add walk stages
+- print 'Add walk stages'
++ print('Add walk stages')
+ ids_walk1 = np.zeros(len(ids_trip), dtype = np.int32)
+ times_end_walk1 = np.zeros(len(ids_trip), dtype = np.int32)
+
+@@ -1562,11 +1562,11 @@
+ ids_edge_to_walk1,\
+ positions_edge_to_walk1,\
+ ids_person,\
+- range(len(ids_trip))):
++ list(range(len(ids_trip)))):
+ try:
+ ids_only_bike_trip.index(id_pers)
+ except:
+- print 'plan first walk'
++ print('plan first walk')
+ ids_walk1[i] , times_end_walk1[i] = virtualpop.get_plans().get_stagetable('walks').append_stage(\
+ id_plan, time_from,
+ id_edge_from = id_edge_from,
+@@ -1576,7 +1576,7 @@
+ )
+
+ durations_walk1 = np.zeros(len(ids_trip), dtype = np.int32)
+- for time_end, second_departure, i in zip(times_end_walk1, seconds_departure, range(len(ids_trip))) :
++ for time_end, second_departure, i in zip(times_end_walk1, seconds_departure, list(range(len(ids_trip)))) :
+ if time_end !=0:
+ durations_walk1[i] = virtualpop.get_plans().get_stagetable('walks').durations[ids_walk1[i]]
+ #bike
+@@ -1602,11 +1602,11 @@
+ positions_edge_to_walk1,\
+ ids_person,\
+ ids_trip,\
+- range(len(ids_trip))):
++ list(range(len(ids_trip)))):
+ try:
+ ids_only_bike_trip.index(id_trip)
+ except:
+- print 'plan first walk'
++ print('plan first walk')
+ ids_walk1[i] , times_end_walk1[i] = virtualpop.get_plans().get_stagetable('walks').append_stage(\
+ id_plan, time_from,
+ id_edge_from = id_edge_from,
+@@ -1616,10 +1616,10 @@
+ )
+
+ durations_walk1 = np.zeros(len(ids_trip), dtype = np.float32)
+- for time_end, second_departure, i in zip(times_end_walk1, seconds_departure, range(len(ids_trip))) :
++ for time_end, second_departure, i in zip(times_end_walk1, seconds_departure, list(range(len(ids_trip)))) :
+ if time_end !=0:
+ durations_walk1[i] = virtualpop.get_plans().get_stagetable('walks').durations[ids_walk1[i]]
+- print seconds_departure, durations_walk1
++ print(seconds_departure, durations_walk1)
+
+ if strategy ==strategies.get_id_from_formatted('bike'):
+ #bike
+@@ -1630,7 +1630,7 @@
+
+ if strat_for_stages == strategies.get_id_from_formatted('bike'):
+ #Add bikeride stages
+- print 'Add bikeride stages'
++ print('Add bikeride stages')
+ ## virtualpop.get_plans().get_stagetable('bikeride').prepare_planning()
+ ## duration_approx1, route1 = routing.get_mincostroute_edge2edge(
+ ## ids_edge_from_bike,
+@@ -1674,14 +1674,14 @@
+ if strat_for_stages == strategies.get_id_from_formatted('transit'):
+
+ #Add bus stages
+- print 'Add bus stages'
++ print('Add bus stages')
+ ids_route = trips.ids_route_matched[ids_trip]
+ ids_ptlinks = trips.get_routes().ids_ptlinks[ids_route]
+- for id_route, id_plan, time_from_bus, i in zip(ids_route, ids_plan,times_from_bus, range(len(ids_trip))):
++ for id_route, id_plan, time_from_bus, i in zip(ids_route, ids_plan,times_from_bus, list(range(len(ids_trip)))):
+ ids_ptlinks = trips.get_routes().ids_ptlinks[id_route]
+ types_ptlinks = scenario.demand.ptlines.get_ptlinks().types[ids_ptlinks]
+ board = 0
+- for type, id_ptlink, j in zip(types_ptlinks, ids_ptlinks, range(len(ids_ptlinks))):
++ for type, id_ptlink, j in zip(types_ptlinks, ids_ptlinks, list(range(len(ids_ptlinks)))):
+ #board
+ if type == 3:
+ if board ==1:
+@@ -1705,7 +1705,7 @@
+ duration = scenario.demand.ptlines.get_ptlinks().durations[id_ptlink]
+ id_fromstop = scenario.demand.ptlines.get_ptlinks().ids_fromstop[id_ptlink]
+ numb_links = j
+- print i, scenario.demand.ptlines.get_ptlinks().types[ids_ptlinks[numb_links+1]]
++ print(i, scenario.demand.ptlines.get_ptlinks().types[ids_ptlinks[numb_links+1]])
+ is_ok = True
+ if numb_links+2=2):
++ if (id_mode in distancesmap) & (id_mode != id_mode_ped) & (len(ids_point)>=2):
+
+
+ are_valid = distancesmap[id_mode] > self.dist_min_modespecific
+@@ -2103,11 +2103,11 @@
+ )
+ else:
+ logger.w(" Failed id_trip %d because pedestrian mode or id_mode %d does not occured in network"%(id_trip,id_mode))
+- print ' distancesmap.keys()',distancesmap.keys()
++ print(' distancesmap.keys()',list(distancesmap.keys()))
+
+ else:
+ logger.w(" Failed id_trip %d because no points"%(id_trip))
+- print ' ids_point',ids_point
++ print(' ids_point',ids_point)
+
+ n_trip_matched += 1
+
+@@ -2133,8 +2133,8 @@
+ # triplength
+
+ # TODO: check get_closest_edge everywhere if projecting properly
+- print 79*'='
+- print 'match_trip_birgil',id_trip,'n_points=',len(ids_point)
++ print(79*'=')
++ print('match_trip_birgil',id_trip,'n_points=',len(ids_point))
+ #print ' ids_point',ids_point
+ #print ' weights[26216]',weights[26216],accesslevels[26216]
+ #print ' weights[26217]',weights[26217],accesslevels[26217]
+@@ -2317,7 +2317,7 @@
+
+ routelist_new = []
+ n_routes = len(routelist)
+- for ind_route in xrange(n_routes):
++ for ind_route in range(n_routes):
+ #routeinfo = 1*routeinfo_orig
+ costs_tot, cost, length_partial, length_cum, accesslevel, length_edge, ids_edge, ids_point_edgeend = routelist[ind_route]
+ routeinfo = costs_tot, cost, length_partial, length_cum, accesslevel, length_edge, ids_edge, ids_point_edgeend
+@@ -2449,10 +2449,10 @@
+
+ # take only the chapest route that arrives at a specific edge
+ n_routes = len(routelist)
+- for route, i in zip(routelist[:-1],xrange(n_routes-1)):
++ for route, i in zip(routelist[:-1],range(n_routes-1)):
+ #cost_tot = route[0]
+ id_edge_last = route[6][-1]
+- for j in xrange(i+1,n_routes):
++ for j in range(i+1,n_routes):
+ if routelist[j][6][-1] == id_edge_last:
+ routelist[j][0] = np.inf
+ # this will throw all infinites to the tail
+@@ -2529,7 +2529,7 @@
+
+
+ # check dist error
+- inds_point = xrange(ind_point_initial,ind_point_final)
++ inds_point = range(ind_point_initial,ind_point_final)
+ n_points = len(inds_point)
+
+
+@@ -2773,7 +2773,7 @@
+
+ class PTMatcher(BirgilMatcher):
+ def __init__(self, ident, mapmatching, logger = None, **kwargs):
+- print 'PTMatcher.__init__'
++ print('PTMatcher.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -2959,7 +2959,7 @@
+ fstar = ptlinks.get_fstar()
+
+ if len(fstar) == 0:
+- print 'WARNING: no PT links built.'
++ print('WARNING: no PT links built.')
+ return False
+
+ ids_trip = trips.get_ids_selected()
+@@ -3025,8 +3025,8 @@
+
+ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances, busedgetimes, accesslevels):
+
+- print 79*'='
+- print 'match_trip',id_trip,'n_points=',len(ids_point)
++ print(79*'=')
++ print('match_trip',id_trip,'n_points=',len(ids_point))
+ tick = time.time()
+ routes = []
+ route = None
+@@ -3069,8 +3069,8 @@
+
+ ids_stop = ptstops.get_ids()
+ coords_stop = ptstops.centroids[ids_stop][:,:2]
+- print ' len(ids_stop)',len(ids_stop)
+- print ' coords_stop.shape',coords_stop.shape
++ print(' len(ids_stop)',len(ids_stop))
++ print(' coords_stop.shape',coords_stop.shape)
+
+
+ # map stop IDs to PT link IDs with specific type
+@@ -3108,7 +3108,7 @@
+ t_point_initial = -1
+ t_point_final = -1
+
+- print ' search initial stops'
++ print(' search initial stops')
+ ind_point = 0
+ for p in coords:
+ dists2 = np.sum((coords_stop-p)**2,1)
+@@ -3146,22 +3146,22 @@
+ dists2 = np.sum((coords_stop-coords_stop[ind_hit_initial])**2,1)
+ inds_hit = np.flatnonzero(dists2 < self.width_buffer_terminal_max**2)
+ for id_stop in ids_stop[inds_hit]:
+- if map_id_fromstop_to_ids_link.has_key(id_stop):
++ if id_stop in map_id_fromstop_to_ids_link:
+ ids_stop_initial.append(id_stop)
+ else:
+- print 'ABOARD: no initial stop found'
++ print('ABOARD: no initial stop found')
+ return [], [], 0.0, 0.0,-1.0,-1.0, -1.0, -1.0, 0.0, [], False
+
+ if ind_hit_final > -1:
+ dists2 = np.sum((coords_stop-coords_stop[ind_hit_final])**2,1)
+ inds_hit = np.flatnonzero(dists2 < self.width_buffer_terminal_max**2)
+ for id_stop in ids_stop[inds_hit]:
+- if map_id_tostop_to_ids_link.has_key(id_stop):
++ if id_stop in map_id_tostop_to_ids_link:
+ ids_stop_final.append(id_stop)
+
+
+ else:
+- print 'ABOARD: no final stop found'
++ print('ABOARD: no final stop found')
+ return [], [], 0.0, 0.0,-1.0,-1.0, -1.0, -1.0, 0.0, [], False
+
+ n_points_eff = ind_point_final - ind_point_initial
+@@ -3170,18 +3170,18 @@
+
+ #if self._logger:
+ # self._logger.w( '>>match_trip_birgil : n_points_eff=%d, len(ids_edge_initial)=%d,len(ids_edge_final)=%d'%(n_points_eff, len(ids_edge_initial),len(ids_edge_final)) )
+- print '\n completed init:'
+- print ' ids_stop_initial',ids_stop_initial
+- print ' ids_stop_final',ids_stop_final
++ print('\n completed init:')
++ print(' ids_stop_initial',ids_stop_initial)
++ print(' ids_stop_final',ids_stop_final)
+
+ #print ' ind_point_initial,ind_point_final,n_points_eff',ind_point_initial,ind_point_final,n_points_eff
+- print ' id_point_initial=%d,id_point_final=%d,n_points_eff=%d'%(ids_point[ind_point_initial],ids_point[ind_point_final],n_points_eff)
++ print(' id_point_initial=%d,id_point_final=%d,n_points_eff=%d'%(ids_point[ind_point_initial],ids_point[ind_point_final],n_points_eff))
+ if (ind_point_initial<0)|(ind_point_final<0) | (n_points_eff < self.n_points_min):
+- print 'ABOARD: insufficient valid points'
++ print('ABOARD: insufficient valid points')
+ return [], [], 0.0, 0.0,-1.0,-1.0, -1.0, -1.0, 0.0, [], False
+
+
+- print ' define initial and final pt links'
++ print(' define initial and final pt links')
+
+ ids_ptlink_initial = set()
+ for id_stop in ids_stop_initial:
+@@ -3191,8 +3191,8 @@
+ for id_stop in ids_stop_final:
+ ids_ptlink_final.update(map_id_tostop_to_ids_link[id_stop])
+
+- print ' ids_ptlink_initial',ids_ptlink_initial
+- print ' ids_ptlink_final',ids_ptlink_final
++ print(' ids_ptlink_initial',ids_ptlink_initial)
++ print(' ids_ptlink_final',ids_ptlink_final)
+
+
+ ##---------------------------------------------------------------------
+@@ -3214,8 +3214,8 @@
+ delta_point = point-coords[ind_point-1]
+ phi_point = np.arctan2(delta_point[1], delta_point[0])
+
+- print 79*'='
+- print ' point ind_point',ind_point,ind_point_final,' id_point',id_point,'coords',point
++ print(79*'=')
++ print(' point ind_point',ind_point,ind_point_final,' id_point',id_point,'coords',point)
+
+ ids_edge_buffer, dists = get_closest_edge( point, n_best = self.n_edge_max,
+ d_max = self.width_buffer_max,
+@@ -3227,10 +3227,10 @@
+
+
+ n_hits = len(ids_edge_buffer)
+- print ' n_hits',n_hits,'ids_edge_buffer',ids_edge_buffer
++ print(' n_hits',n_hits,'ids_edge_buffer',ids_edge_buffer)
+ if n_hits>0:
+ phis_delta = np.zeros(n_hits, dtype = np.float32)
+- for ind, id_edge in zip(xrange(n_hits), ids_edge_buffer):
++ for ind, id_edge in zip(range(n_hits), ids_edge_buffer):
+
+ dist_point_edge, segment = get_dist_point_to_edge(point, id_edge,
+ is_ending=True,
+@@ -3252,7 +3252,7 @@
+ for id_stop in ids_stops_near:
+ t_wait_point = min(pointtimes[ind_point]-pointtimes[ind_point-1],600.0)
+ #print ' near id_stop',id_stop,map_id_fromstop_to_ids_link.has_key(id_stop)
+- if map_id_fromstop_to_ids_link.has_key(id_stop):
++ if id_stop in map_id_fromstop_to_ids_link:
+ waittimes_stops[id_stop] += t_wait_point
+ #ptlinkhits[map_id_fromstop_to_ids_link[id_stop]] += self.weight_stop_hits/n_near
+ pttimes[map_id_fromstop_to_ids_link[id_stop]] -= self.weight_stop_hits*t_wait_point#/n_near
+@@ -3265,10 +3265,10 @@
+ ptlinkhits[id_ptlink] += np.sum(edgehits[ids_ptedge])
+
+ if 0: #debug
+- print ' Stop waittimes'
++ print(' Stop waittimes')
+ for id_stop, waits in zip(ids_stop, waittimes_stops[ids_stop]):
+ if waits>0:
+- print ' waits at id_stop %d = %.2fs'%(id_stop,waits)
++ print(' waits at id_stop %d = %.2fs'%(id_stop,waits))
+
+ # debug edgelinks
+ #ids_edge = edges.get_ids()
+@@ -3303,16 +3303,16 @@
+
+ ##--------------------------------------------------------------------
+ ## post matching analisis
+- print '\n'+79*'-'
++ print('\n'+79*'-')
+
+ #print ' ids_point_edgeend',len(ids_point_edgeend),ids_point_edgeend
+ if len(routelist) == 0:
+- print 'ABOARD: no routes found'
++ print('ABOARD: no routes found')
+ return [],[], 0.0, 0.0,-1.0,-1.0, -1.0, -1.0, 0.0, [], False
+ else:
+ ids_ptlink = routelist[0][1]
+ if len(ids_ptlink) == 0:
+- print 'ABOARD: route contains no edges ids_ptlink=',ids_ptlink
++ print('ABOARD: route contains no edges ids_ptlink=',ids_ptlink)
+ return [],[], 0.0, 0.0,-1.0,-1.0, -1.0, -1.0, 0.0, [], False
+ else:
+ is_connected = True
+@@ -3321,12 +3321,12 @@
+ ids_edge += ptlinks.get_ids_edge(id_ptlink)
+ route = ids_edge
+
+- print ' matched route: len(ids_edge)',len(ids_edge),'len(ids_ptlink)',len(ids_ptlink),'cost =%.2f'%routelist[0][0]
++ print(' matched route: len(ids_edge)',len(ids_edge),'len(ids_ptlink)',len(ids_ptlink),'cost =%.2f'%routelist[0][0])
+
+ if 1:
+ for id_ptlink in ids_ptlink:
+ ptlinks.print_link(id_ptlink, ident = 4, is_edges = False, is_link_forward = False)
+- print ' ids_edge',ids_edge
++ print(' ids_edge',ids_edge)
+
+
+
+@@ -3353,7 +3353,7 @@
+
+
+ # check dist error
+- inds_point = xrange(ind_point_initial,ind_point_final)
++ inds_point = range(ind_point_initial,ind_point_final)
+ n_points = len(inds_point)
+
+
+@@ -3381,10 +3381,10 @@
+ err_dist = dist_points_tot/float(n_points)
+
+ if ptlinks.ids_tostop[ids_ptlink[-1]] in ids_stop_final:
+- print 'SUCCESS: target id_stop',ptlinks.ids_tostop[ids_ptlink[-1]],'reached length %.2f, gps length %.2f$'%(length_route,length_gps)
++ print('SUCCESS: target id_stop',ptlinks.ids_tostop[ids_ptlink[-1]],'reached length %.2f, gps length %.2f$'%(length_route,length_gps))
+ is_connected = True
+ else:
+- print 'DISCONNECTED: last matched id_stop',ptlinks.ids_tostop[ids_ptlink[-1]],' does not reach final ids_stop',ids_stop_final
++ print('DISCONNECTED: last matched id_stop',ptlinks.ids_tostop[ids_ptlink[-1]],' does not reach final ids_stop',ids_stop_final)
+ is_connected = False
+
+
+@@ -3407,7 +3407,7 @@
+
+ class VirtualpopCreator(Process):
+ def __init__(self, mapmatching, logger = None, **kwargs):
+- print 'VirtualpopCreator.__init__'
++ print('VirtualpopCreator.__init__')
+ self._init_common( 'virtualpopcreator',
+ parent = mapmatching,
+ name = 'VirtualpopCreator',
+@@ -3448,7 +3448,7 @@
+
+ class ModeSelector(Process):
+ def __init__(self, mapmatching, logger = None, **kwargs):
+- print 'ModeSelector.__init__'
++ print('ModeSelector.__init__')
+ self._init_common( 'modeselector',
+ parent = mapmatching,
+ name = 'Mode Selector',
+@@ -3692,7 +3692,7 @@
+
+ class PostMatchfilter(FilterMixin):
+ def __init__(self, mapmatching, logger = None, **kwargs):
+- print 'PostMatchfilter.__init__'
++ print('PostMatchfilter.__init__')
+ self._init_common( 'postmatchfilter',
+ parent = mapmatching,
+ name = 'Post matchfilter',
+@@ -3797,7 +3797,7 @@
+ ids_trip = trips.get_ids()
+ ids_points = trips.ids_points[ids_trip]
+
+- print 'filter_ids',n_trips,'selected'
++ print('filter_ids',n_trips,'selected')
+ inds_eliminate = np.logical_or(\
+ trips.lengthindexes[ids_selected]self.lengthindex_max,
+@@ -3805,31 +3805,31 @@
+ #np.logical_not(trips.are_match_connected[ids_selected]),
+ #(trips.lengths_route_matched[ids_selected]<1.0), # too many args??
+ )
+- print ' after lengthindex remaining',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after lengthindex remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
+
+
+ inds_eliminate |= trips.errors_dist[ids_selected]>self.error_dist_max
+- print ' after distance error remaining',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after distance error remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
+
+
+ if self.is_connected:
+ inds_eliminate |= np.logical_not(trips.are_match_connected[ids_selected])
+
+- print ' after connected remaining',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after connected remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
+
+ if self.is_shortest:
+ inds_eliminate |= trips.ids_route_shortest[ids_selected] == -1
+ if self.is_matched:
+ inds_eliminate |= trips.ids_route_matched[ids_selected] == -1
+- print ' after is matched remaining',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after is matched remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
+
+ inds_eliminate |= trips.lengths_route_matched[ids_selected]<1.0
+- print ' after too short trips remaining:',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after too short trips remaining:',n_trips-len(np.flatnonzero(inds_eliminate)))
+
+
+ inds_eliminate |= trips.speeds_average[ids_selected] < self.speed_trip_min
+ inds_eliminate |= trips.speeds_average[ids_selected] > self.speed_trip_max
+- print ' after speed check remaining',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after speed check remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
+
+
+
+@@ -3850,7 +3850,7 @@
+ #print ' inds_eliminate',inds_eliminate
+
+ inds_eliminate |= self.filter_time(trips.timestamps[ids_selected])
+- print ' after time check trips remaining:',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after time check trips remaining:',n_trips-len(np.flatnonzero(inds_eliminate)))
+ #print ' inds_eliminate',inds_eliminate
+
+ if self.is_loopfree:
+@@ -3860,7 +3860,7 @@
+ # loop-free check
+ inds_eliminate[i] = len(ids_edge) != len(set(ids_edge))
+ i += 1
+- print ' after loop test trips remaining:',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after loop test trips remaining:',n_trips-len(np.flatnonzero(inds_eliminate)))
+
+ return ids_selected[inds_eliminate]
+
+@@ -3874,7 +3874,7 @@
+
+ class PersonFilter(FilterMixin):
+ def __init__(self, mapmatching, logger = None, **kwargs):
+- print 'Personfilter.__init__'
++ print('Personfilter.__init__')
+ self._init_common( 'personfilter',
+ parent = mapmatching,
+ name = 'Person filter',
+@@ -3979,18 +3979,18 @@
+ ids_trip = trips.get_ids()
+ ids_points = trips.ids_points[ids_trip]
+
+- print 'filter_ids',n_trips,'selected'
++ print('filter_ids',n_trips,'selected')
+ inds_eliminate = np.zeros(len(trips.ids_vtype[ids_selected]), dtype=bool)
+
+ if self.is_select_gender:
+ inds_eliminate |= persons.ids_gender[trips.ids_person[ids_selected]] != self.gender
+- print ' after gender check remaining',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after gender check remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
+
+ if self.is_select_age:
+ inds_eliminate |= np.logical_or(\
+ persons.years_birth[trips.ids_person[ids_selected]]<=self.birth_min,
+ persons.years_birth[trips.ids_person[ids_selected]]>=self.birth_max,)
+- print ' after age check remaining',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after age check remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
+
+ if len(self.zones)>0:
+ if self.is_select_od_trips:
+@@ -4002,7 +4002,7 @@
+ id_initial_point = ids_point[0]
+ od_trips[id_trip] = is_point_in_polygon(points.coords[id_initial_point], zone_shape_origin)*is_point_in_polygon(points.coords[id_final_point], zone_shape_dest)
+ inds_eliminate |= np.logical_not(od_trips[ids_selected])
+- print ' after od trips remaining ',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after od trips remaining ',n_trips-len(np.flatnonzero(inds_eliminate)))
+
+ if self.is_select_gen_trips:
+ zone_shape_origin = zones.shapes[zones.ids_sumo.get_id_from_index(self.origin_zone_name)]
+@@ -4011,7 +4011,7 @@
+ id_initial_point = ids_point[0]
+ od_trips[id_trip] = is_point_in_polygon(points.coords[id_initial_point], zone_shape_origin)
+ inds_eliminate |= np.logical_not(od_trips[ids_selected])
+- print ' after generated trips remaining ',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after generated trips remaining ',n_trips-len(np.flatnonzero(inds_eliminate)))
+
+ if self.is_select_attr_trips:
+ zone_shape_dest = zones.shapes[zones.ids_sumo.get_id_from_index(self.dest_zone_name)]
+@@ -4020,7 +4020,7 @@
+ id_final_point = ids_point[-1]
+ od_trips[id_trip] = is_point_in_polygon(points.coords[id_final_point], zone_shape_dest)
+ inds_eliminate |= np.logical_not(od_trips[ids_selected])
+- print ' after attracted trips remaining ',n_trips-len(np.flatnonzero(inds_eliminate))
++ print(' after attracted trips remaining ',n_trips-len(np.flatnonzero(inds_eliminate)))
+
+ return ids_selected[inds_eliminate]
+
+@@ -4039,7 +4039,7 @@
+
+ class TripGeomfilter(FilterMixin):
+ def __init__(self, mapmatching, logger = None, **kwargs):
+- print 'TripGeomfilter.__init__'
++ print('TripGeomfilter.__init__')
+ self._init_common( 'tripGeomfilter',
+ parent = mapmatching,
+ name = 'Geometry trip filter',
+@@ -4209,7 +4209,7 @@
+ """
+ Previews selected trips after filtering.
+ """
+- print 'TripGeomfilter.filterpreview'
++ print('TripGeomfilter.filterpreview')
+ trips = self.parent.trips
+ n_trips = len(trips)
+ if n_trips == 0:
+@@ -4221,7 +4221,7 @@
+ return '%d/%d (currently %d/%d)'%(n_sel_after,n_trips,n_sel_current,n_trips)
+
+ def do(self):
+- print 'TripGeomfilter.do'
++ print('TripGeomfilter.do')
+ # execute filtering
+ if len(self.parent.trips)>0:
+ self.parent.trips.are_selected[self.filter_ids(is_eliminate_points = True)] = False
+@@ -4253,7 +4253,7 @@
+ Returns an array of ids to be eliminated or deselected.
+ """
+ c_cutoff = 1.0 - self.const_return_max
+- print 'TripGeomfilter.filter_ids c_cutoff',c_cutoff,'is_eliminate_points',is_eliminate_points
++ print('TripGeomfilter.filter_ids c_cutoff',c_cutoff,'is_eliminate_points',is_eliminate_points)
+ dist_point_max = self.dist_point_max
+ dist_point_min = self.dist_point_min_extr
+ dist_point_min_inter = self.dist_point_min_inter
+@@ -4263,10 +4263,10 @@
+ ids_trip = trips.get_ids_selected()
+ ids_points = trips.ids_points[ids_trip]
+ speed_max = self.speed_max
+- print ' n_trips',len(ids_trip)
+- print ' n_points',len(ids_points)
++ print(' n_trips',len(ids_trip))
++ print(' n_points',len(ids_points))
+ if len(ids_points) == 0:
+- print 'WARNING: no points found, no traces'
++ print('WARNING: no points found, no traces')
+ return True
+ intersects_boundaries = self.parent.get_scenario().net.intersects_boundaries
+ in_boundaries = self.parent.get_scenario().net.in_boundaries
+@@ -4287,17 +4287,17 @@
+ surplus = 0
+
+ for id_trip, ids_point in zip(ids_trip, ids_points):
+- print 79*'-'
+- print ' filter id_trip ',id_trip,
++ print(79*'-')
++ print(' filter id_trip ',id_trip, end=' ')
+ if ids_point is None:
+ is_eliminate = True
+- print ' no points'
++ print(' no points')
+
+
+
+ elif (len(ids_point) < 2*self.num_external_points+2 and self.is_eliminate_external_points):
+ is_eliminate = True
+- print ' not enough points, only',len(ids_point)
++ print(' not enough points, only',len(ids_point))
+
+ else:
+ ## print 'ids_point',ids_point
+@@ -4325,16 +4325,16 @@
+ # this happens if the points of a trip in the workout file
+ # have not been imported for some reason
+ is_eliminate = True
+- print 'it has no points'
++ print('it has no points')
+ elif n<2:
+ is_eliminate = True
+- print 'less than 2 points'
++ print('less than 2 points')
+ elif not intersects_boundaries(get_boundary(coords)):
+ is_eliminate = True
+- print 'do not intersect boundaries'
++ print('do not intersect boundaries')
+ elif np.any(times<0):
+ is_eliminate = True
+- print 'has negative times'
++ print('has negative times')
+ else:
+ dist_max = 0.0
+ is_eliminate = False
+@@ -4370,7 +4370,7 @@
+ durations_inter = np.zeros(len(dists_to_end),dtype = np.float32)
+ speeds_inter = np.zeros(len(dists_to_end),dtype = np.float32)
+
+- for i, duration_inter, speed_inter in zip(range(len(durations_inter)), durations_inter, speeds_inter):
++ for i, duration_inter, speed_inter in zip(list(range(len(durations_inter))), durations_inter, speeds_inter):
+ if i>0:
+
+ durations_inter[i] = times[i]-times[i-1]
+@@ -4396,7 +4396,7 @@
+
+ #print ' ids_points_outside =',np.array(ids_point, dtype = np.int32)[are_outside]
+ ids_point_elim.update(np.array(ids_point, dtype = np.int32)[are_outside])
+- print len(ids_point_elim), 'points outside box'
++ print(len(ids_point_elim), 'points outside box')
+ i = 0
+ while (i<(n-2)):
+ i+=1
+@@ -4411,7 +4411,7 @@
+ if dists_to_start[i] < dist_point_min:
+ #print ' eliminate',ids_point[i], dist_check
+ ids_point_elim.add(ids_point[i])
+- print 'point', ids_point[i], dists_to_start[i], 'meters near start'
++ print('point', ids_point[i], dists_to_start[i], 'meters near start')
+
+
+
+@@ -4422,7 +4422,7 @@
+ if dists_to_end[i] < dist_point_min:
+ #print ' eliminate',ids_point[i], dist_check
+ ids_point_elim.add(ids_point[i])
+- print 'point', ids_point[i], dists_to_end[i], 'meters near end'
++ print('point', ids_point[i], dists_to_end[i], 'meters near end')
+ else:
+
+ #dist_check = np.sqrt( (coords[i,0]-coord_last[0])**2\
+@@ -4434,7 +4434,7 @@
+ dists_inter[i+1] = np.sqrt( (coords[i+1,0]-coords[i-surplus,0])**2\
+ + (coords[i+1,1]-coords[i-surplus,1])**2 )
+
+- print 'point', ids_point[i], (dists_inter[i]), 'meters near other point'
++ print('point', ids_point[i], (dists_inter[i]), 'meters near other point')
+ else:
+ surplus = 0
+ #else:
+@@ -4460,10 +4460,10 @@
+ speeds_average[id_trip] = distances_gps[id_trip]/durations_gps[id_trip]
+ else:
+ speeds_average[id_trip] = 0.0
+- print 'old dist', trips.distances_gps[id_trip], 'new dist', distances_gps[id_trip]
+- print 'old duration', trips.durations_gps[id_trip], 'new duration',durations_gps[id_trip]
+- print 'old speed', trips.speeds_average[id_trip], 'new speed', speeds_average[id_trip]
+- print 'old max speed', trips.speeds_max[id_trip], 'new max speed', max_speeds_intern[id_trip]
++ print('old dist', trips.distances_gps[id_trip], 'new dist', distances_gps[id_trip])
++ print('old duration', trips.durations_gps[id_trip], 'new duration',durations_gps[id_trip])
++ print('old speed', trips.speeds_average[id_trip], 'new speed', speeds_average[id_trip])
++ print('old max speed', trips.speeds_max[id_trip], 'new max speed', max_speeds_intern[id_trip])
+
+
+ else:
+@@ -4477,18 +4477,18 @@
+ speeds_average[id_trip] = distances_gps[id_trip]/durations_gps[id_trip]
+ else:
+ speeds_average[id_trip] = 0.0
+- print 'old dist', trips.distances_gps[id_trip], 'new dist', distances_gps[id_trip]
+- print 'old duration', trips.durations_gps[id_trip], 'new duration',durations_gps[id_trip]
+- print 'old speed', trips.speeds_average[id_trip], 'new speed', speeds_average[id_trip]
+- print 'old max speed', trips.speeds_max[id_trip], 'new max speed', max_speeds_intern[id_trip]
++ print('old dist', trips.distances_gps[id_trip], 'new dist', distances_gps[id_trip])
++ print('old duration', trips.durations_gps[id_trip], 'new duration',durations_gps[id_trip])
++ print('old speed', trips.speeds_average[id_trip], 'new speed', speeds_average[id_trip])
++ print('old max speed', trips.speeds_max[id_trip], 'new max speed', max_speeds_intern[id_trip])
+
+ elif len(np.unique(list(ids_point_elim)))>=len(ids_point2):
+ is_eliminate = True
+- print 'all points eliminated'
++ print('all points eliminated')
+ # no points left
+ elif len(ids_point2)<2:
+ is_eliminate = True
+- print 'no points left'
++ print('no points left')
+
+
+ ids_point_elim_perm += list(ids_point_elim)
+@@ -4501,7 +4501,7 @@
+ #print ' after elim ids_point',trips.ids_points[id_trip]
+
+ if is_eliminate:
+- print 'Deselected trace due to the point analysis'
++ print('Deselected trace due to the point analysis')
+ if self.is_deselect_traces and not is_eliminate:
+
+ #ricalculate dist_inter and duration_inter
+@@ -4529,13 +4529,13 @@
+
+
+ dist_to_start_max = np.max(dists_to_start)
+- print 'dist_to_start_max', dist_to_start_max
++ print('dist_to_start_max', dist_to_start_max)
+
+ ## print dists_to_start, dist_to_start_max
+ dists_to_end = np.sqrt( (coords[:,0]-coords[-1,0])**2\
+ + (coords[:,1]-coords[-1,1])**2 )
+
+- for i, duration_inter, speed_inter in zip(range(len(durations_inter)), durations_inter, speeds_inter):
++ for i, duration_inter, speed_inter in zip(list(range(len(durations_inter))), durations_inter, speeds_inter):
+ if i>0:
+
+ durations_inter[i] = times[i]-times[i-1]
+@@ -4550,22 +4550,22 @@
+
+ if np.any(dists_inter>dist_point_max):
+ is_eliminate = True
+- print 'one internal distance over the tollerance. Max value:', np.max(dists_inter), 'meters'
++ print('one internal distance over the tollerance. Max value:', np.max(dists_inter), 'meters')
+
+ if self.is_deselect_duplicate:
+ dist_duration = [trips.distances_gps[id_trip], trips.durations_gps[id_trip]]
+
+ if dist_duration in dists_durations and dist_duration != [0.,0.]:
+ n_duplicate_trips += 1
+- print dist_duration
+- print 'duplicated trip'
++ print(dist_duration)
++ print('duplicated trip')
+ is_eliminate = True
+ ## else:
+ dists_durations[id_trip] = [trips.distances_gps[id_trip], trips.durations_gps[id_trip]]
+
+ if np.any(durations_inter>duration_point_max):
+ is_eliminate = True
+- print 'one internal duration over the tollerance. Max value:', np.max(durations_inter), 'seconds'
++ print('one internal duration over the tollerance. Max value:', np.max(durations_inter), 'seconds')
+
+ n_invalid_speeds = 0
+ i = 0
+@@ -4577,11 +4577,11 @@
+
+ if n_invalid_speeds == self.n_overspeed_max:
+ is_eliminate = True
+- print 'invalid internal speeds'
++ print('invalid internal speeds')
+ i += 1
+ if dists_to_start[-1] <= c_cutoff*dist_to_start_max:
+ is_eliminate = True
+- print 'round trip: return distance over the tollerance'
++ print('round trip: return distance over the tollerance')
+
+ if len(self.zones) > 0 and not is_eliminate:
+ if self.is_od_select:
+@@ -4592,17 +4592,17 @@
+ if self.select_type == 1:
+ is_eliminate = not is_point_in_polygon(points.coords[id_initial_point], zone_shape_origin)
+ if is_eliminate == True:
+- print 'deselected for the zone filter'
++ print('deselected for the zone filter')
+ if self.select_type == 2:
+ is_eliminate = not is_point_in_polygon(points.coords[id_final_point], zone_shape_dest)
+ if is_eliminate == True:
+- print 'deselected for the zone filter'
++ print('deselected for the zone filter')
+ if self.select_type == 3:
+ is_eliminate = not is_point_in_polygon(points.coords[id_initial_point], zone_shape_origin)*is_point_in_polygon(points.coords[id_final_point], zone_shape_dest)
+ if is_eliminate == True:
+- print 'deselected for the zone filter'
++ print('deselected for the zone filter')
+ if is_eliminate:
+- print 'Deselected trace'
++ print('Deselected trace')
+ inds_elim[j] = is_eliminate
+ j +=1
+
+@@ -4615,12 +4615,12 @@
+
+
+
+- print ' permanently eliminated %d GPS points'%(len(ids_point_elim_perm))
++ print(' permanently eliminated %d GPS points'%(len(ids_point_elim_perm)))
+ if self.is_analyze_points:
+- print '%d Invalid GPS points'%(len(np.unique(ids_point_elim_perm)))
+- print '%d Invalid GPS traces'%(np.sum(inds_elim))
++ print('%d Invalid GPS points'%(len(np.unique(ids_point_elim_perm))))
++ print('%d Invalid GPS traces'%(np.sum(inds_elim)))
+ if self.is_deselect_duplicate:
+- print '%d Duplicated GPS traces'%(np.sum(n_duplicate_trips))
++ print('%d Duplicated GPS traces'%(np.sum(n_duplicate_trips)))
+ #print '+++++++++++ids_point_elim_perm',ids_point_elim_perm
+ #print ' eliminate points?',(len(ids_point_elim_perm)>0),is_eliminate_points,(len(ids_point_elim_perm)>0) & is_eliminate_points
+
+@@ -4629,7 +4629,7 @@
+
+ class MobikeImporter(FilterMixin):
+ def __init__(self, mapmatching, logger = None, **kwargs):
+- print 'MobikeImporter.__init__',mapmatching.get_ident()
++ print('MobikeImporter.__init__',mapmatching.get_ident())
+ self._init_common( 'mobikeimporter',
+ parent = mapmatching,
+ name = 'Mobike Importer',
+@@ -4780,7 +4780,7 @@
+ trips.durations_gps[id_trip] = timestamps[-1]-timestamps[0]
+
+ def do(self):
+- print 'TraceImporter.do'
++ print('TraceImporter.do')
+ log = self.get_logger()
+ #ID Bicicletta;Data e ora inizio;Data e ora fine;Latitudine inizio;Longitudine inizio;Latitudine fine;Longitudine fine;Durata;Distanza
+ # 0 1 2 3 4 5 6 7 8
+@@ -4827,7 +4827,7 @@
+ for line in f.readlines()[1:]:# first line contains header
+
+ cols = line.strip().split(sep)
+- print ' i_line',i_line,'len(cols)',len(cols),n_cols
++ print(' i_line',i_line,'len(cols)',len(cols),n_cols)
+ if len(cols)==n_cols:
+
+ # sep_date_clock = ' ', sep_date = '-', sep_clock = ':',
+@@ -4842,8 +4842,8 @@
+ )
+
+ else:
+- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath)
+- print ' cols =',cols
++ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath))
++ print(' cols =',cols)
+
+
+ i_line += 1
+@@ -4858,7 +4858,7 @@
+
+ class StravaImporter(FilterMixin):
+ def __init__(self, mapmatching, logger = None, **kwargs):
+- print 'StravaImporter.__init__',mapmatching.get_ident()
++ print('StravaImporter.__init__',mapmatching.get_ident())
+ self._init_common( 'traceimporter',
+ parent = mapmatching,
+ name = 'Strava Trace Importer',
+@@ -4964,7 +4964,7 @@
+
+
+ def do(self):
+- print 'TraceImporter.do'
++ print('TraceImporter.do')
+ if self.year == 2013:
+ self.import_points_2013()
+ self.import_users_2013()
+@@ -4979,7 +4979,7 @@
+ log = self.get_logger()
+
+
+- print 'import users'
++ print('import users')
+ if (self.userinfofilepath == ''):
+ return
+
+@@ -5057,17 +5057,17 @@
+ if hasattr(self,'home_zips'):
+ #print ' zips',self.zips.get_value().dtype,self.zips.get_value()
+ if self.home_zips.get_value().dtype in [np.dtype(np.int32),np.dtype(np.int64)]:
+- print 'WARNING: delete old person.home_zips'
++ print('WARNING: delete old person.home_zips')
+ self.delete('home_zips')
+ if hasattr(self,'school_zips'):
+ #print ' zips',self.zips.get_value().dtype,self.zips.get_value()
+ if self.school_zips.get_value().dtype in [np.dtype(np.int32),np.dtype(np.int64)]:
+- print 'WARNING: delete old person.school_zips'
++ print('WARNING: delete old person.school_zips')
+ self.delete('school_zips')
+ if hasattr(self,'work_zips'):
+ #print ' zips',self.zips.get_value().dtype,self.zips.get_value()
+ if self.work_zips.get_value().dtype in [np.dtype(np.int32),np.dtype(np.int64)]:
+- print 'WARNING: delete old person.work_zips'
++ print('WARNING: delete old person.work_zips')
+ self.delete('work_zips')
+
+ #if self.get_version()<0.2:
+@@ -5079,7 +5079,7 @@
+ #1 7561 35 Commute 2012-10-12 15:07:22 0 0 0 1 30316 -1 30308 3 1 2
+
+ n_cols = 15
+- j_id_line, j_tripid, j_userid, j_trip_type, j_created_date, j_age, j_gender, j_income, j_ethnicity, j_homeZIP, j_schoolZip, j_workZip, j_cyclingfreq, j_rider_history, j_rider_type = range(15)
++ j_id_line, j_tripid, j_userid, j_trip_type, j_created_date, j_age, j_gender, j_income, j_ethnicity, j_homeZIP, j_schoolZip, j_workZip, j_cyclingfreq, j_rider_history, j_rider_type = list(range(15))
+
+ #dd
+
+@@ -5129,10 +5129,10 @@
+
+
+ else:
+- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.userinfofilepath)
+- print ' cols =',cols
++ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.userinfofilepath))
++ print(' cols =',cols)
+ if i_line%1000 == 0:
+- print i_line,'/',len(lines), 'users imported'
++ print(i_line,'/',len(lines), 'users imported')
+ i_line += 1
+
+
+@@ -5172,7 +5172,7 @@
+ ids_vtype[i] = self.get_vtype_for_mode(id_mode)
+ i+=1
+ # create new trip
+- print 'add trips'
++ print('add trips')
+ ids_trip = trips.add_rows(ids_sumo = ids_trip_sumo,
+ timestamps = timestamps_trips,
+ ids_vtype = ids_vtype,
+@@ -5180,22 +5180,22 @@
+ distances_gps = distances_gps,
+ speeds_average = speeds_av,
+ )
+- print len(ids_trip), 'trips added'
++ print(len(ids_trip), 'trips added')
+
+
+ i_changes = [0]
+ current_id_trips_points = ids_trips_points[0]
+- for id_trips_points, i in zip(ids_trips_points, range(len(ids_trips_points))):
++ for id_trips_points, i in zip(ids_trips_points, list(range(len(ids_trips_points)))):
+ if id_trips_points != current_id_trips_points:
+ i_changes.append(i)
+ current_id_trips_points = id_trips_points
+ i_changes.append(len(ids_trips_points))
+- print len(i_changes)-1, len(ids_trip)
+- for i, id_trip in zip(range(len(i_changes)-1), ids_trip):
++ print(len(i_changes)-1, len(ids_trip))
++ for i, id_trip in zip(list(range(len(i_changes)-1)), ids_trip):
+ ids_trips_points[i_changes[i]:i_changes[i+1]] = id_trip*np.ones(len(ids_trips_points[i_changes[i]:i_changes[i+1]]))
+
+
+- print 'add points'
++ print('add points')
+
+ ## print timestamps_points, timestamps_trips
+ ids_point = points.add_rows(\
+@@ -5206,12 +5206,12 @@
+ altitudes = altitudes,
+ )
+
+- print len(ids_point), 'points added'
+- print 'add ids points'
++ print(len(ids_point), 'points added')
++ print('add ids points')
+
+ # bellamossa does provide no altitude
+ #points.coords[ids_point][:,:2] = coords
+- for i, id_trip in zip(range(len(i_changes)-1), ids_trip):
++ for i, id_trip in zip(list(range(len(i_changes)-1)), ids_trip):
+ ## print points.get_ids()[(points.ids_trip[points.get_ids()] == id_trip)]
+ trips.set_points(id_trip, ids_point[i_changes[i]:i_changes[i+1]])
+ #print ' timestamps',timestamps
+@@ -5297,7 +5297,7 @@
+ return is_valid, 0., 0., 0.
+
+ def import_points_2013(self):
+- print 'import_points_2013'
++ print('import_points_2013')
+ log = self.get_logger()
+ #pointDBNode, pointPathId, id, timestamp, latitude, longitude, altitude,distance, heartRate,instruction,speed
+ #4, 61565791, 23648171762,2013-05-01 06:33:58,44.501085, 11.372906, NULL, 0, NULL, 2, NULL
+@@ -5361,7 +5361,7 @@
+ lines = f.readlines()[1:]
+ n_lines = len(lines)
+ n_trips = len(lines)
+- print 'analyze', n_lines, 'points and', n_trips, 'trips'
++ print('analyze', n_lines, 'points and', n_trips, 'trips')
+
+ ids_trip_sumo = np.zeros(n_trips,dtype = 'object')
+ ids_mode = np.zeros(n_trips,dtype = np.int32)
+@@ -5461,11 +5461,11 @@
+
+
+ else:
+- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath)
+- print ' cols =',cols
++ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath))
++ print(' cols =',cols)
+
+ if i_line%500000 == 0:
+- print i_line,'/',len(lines), 'points imported'
++ print(i_line,'/',len(lines), 'points imported')
+ i_line += 1
+
+ # register points of last trip after loop ended
+@@ -5518,7 +5518,7 @@
+
+ class BellamossaImporter(FilterMixin):
+ def __init__(self, mapmatching, logger = None, **kwargs):
+- print 'BellamossaImporter.__init__',mapmatching.get_ident()
++ print('BellamossaImporter.__init__',mapmatching.get_ident())
+ self._init_common( 'traceimporter',
+ parent = mapmatching,
+ name = 'Bellamossa Trace Importer',
+@@ -5633,7 +5633,7 @@
+
+
+ def do(self):
+- print 'TraceImporter.do'
++ print('TraceImporter.do')
+ if self.year == 2017:
+ self.import_points_2017()
+ self.import_users_2017()
+@@ -5647,7 +5647,7 @@
+ def import_users_2017(self):
+ log = self.get_logger()
+
+- print 'import users'
++ print('import users')
+ if (self.tripinfofilepath == '') | (self.userinfofilepath == ''):
+ return
+
+@@ -5663,7 +5663,7 @@
+ #81511,Female,1981
+ #81507,Male,1983
+ n_cols = 3
+- j_id_user, j_sex, j_year = range(3)
++ j_id_user, j_sex, j_year = list(range(3))
+
+
+ #exist_id_person_sumo = persons.ids_sumo.has_index
+@@ -5693,10 +5693,10 @@
+
+
+ else:
+- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.userinfofilepath)
+- print ' cols =',cols
++ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.userinfofilepath))
++ print(' cols =',cols)
+ if i_line%1000 == 0:
+- print i_line,'/',len(lines), 'users imported'
++ print(i_line,'/',len(lines), 'users imported')
+ i_line += 1
+
+ f.close()
+@@ -5704,7 +5704,7 @@
+
+ ## read trip-user file
+ n_cols = 2
+- j_id_trip, j_id_user = range(2)
++ j_id_trip, j_id_user = list(range(2))
+ f = open(self.tripinfofilepath,'r')
+ if self._logger: self._logger.w('import_users_2017 import tripfile %s'%os.path.basename(self.tripinfofilepath))
+ sep = ','
+@@ -5739,10 +5739,10 @@
+
+
+ else:
+- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.tripinfofilepath)
+- print ' cols =',cols
++ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.tripinfofilepath))
++ print(' cols =',cols)
+ if i_line%500000 == 0:
+- print i_line,'/',len(lines), 'users imported'
++ print(i_line,'/',len(lines), 'users imported')
+ i_line += 1
+
+ def add_trips(self, trips, points, distances_gps, durations_gps, speeds_av, ids_trip_sumo, ids_trips_points,
+@@ -5758,7 +5758,7 @@
+ ids_vtype[i] = self.get_vtype_for_mode(id_mode)
+ i+=1
+ # create new trip
+- print 'add trips'
++ print('add trips')
+ ids_trip = trips.add_rows(ids_sumo = ids_trip_sumo,
+ timestamps = timestamps_trips,
+ ids_vtype = ids_vtype,
+@@ -5766,22 +5766,22 @@
+ distances_gps = distances_gps,
+ speeds_average = speeds_av,
+ )
+- print len(ids_trip), 'trips added'
++ print(len(ids_trip), 'trips added')
+
+
+ i_changes = [0]
+ current_id_trips_points = ids_trips_points[0]
+- for id_trips_points, i in zip(ids_trips_points, range(len(ids_trips_points))):
++ for id_trips_points, i in zip(ids_trips_points, list(range(len(ids_trips_points)))):
+ if id_trips_points != current_id_trips_points:
+ i_changes.append(i)
+ current_id_trips_points = id_trips_points
+ i_changes.append(len(ids_trips_points))
+- print len(i_changes)-1, len(ids_trip)
+- for i, id_trip in zip(range(len(i_changes)-1), ids_trip):
++ print(len(i_changes)-1, len(ids_trip))
++ for i, id_trip in zip(list(range(len(i_changes)-1)), ids_trip):
+ ids_trips_points[i_changes[i]:i_changes[i+1]] = id_trip*np.ones(len(ids_trips_points[i_changes[i]:i_changes[i+1]]))
+
+
+- print 'add points'
++ print('add points')
+
+ ## print timestamps_points, timestamps_trips
+ ids_point = points.add_rows(\
+@@ -5792,12 +5792,12 @@
+ altitudes = np.zeros(len(ids_trips_points), dtype = np.float32),
+ )
+
+- print len(ids_point), 'points added'
+- print 'add ids points'
++ print(len(ids_point), 'points added')
++ print('add ids points')
+
+ # bellamossa does provide no altitude
+ #points.coords[ids_point][:,:2] = coords
+- for i, id_trip in zip(range(len(i_changes)-1), ids_trip):
++ for i, id_trip in zip(list(range(len(i_changes)-1)), ids_trip):
+ ## print points.get_ids()[(points.ids_trip[points.get_ids()] == id_trip)]
+ trips.set_points(id_trip, ids_point[i_changes[i]:i_changes[i+1]])
+ #print ' timestamps',timestamps
+@@ -5863,7 +5863,7 @@
+ return is_valid, 0., 0., 0.
+
+ def import_points_2017(self):
+- print 'import_points_2017'
++ print('import_points_2017')
+ log = self.get_logger()
+ # 0 1 2 3 4 5 6 7 8
+ # ActivityId,ActivityType,Time,Latitude,Longitude,Accuracy,Speed,IdentifiedType,IdentifiedConfidence
+@@ -5926,7 +5926,7 @@
+ lines = f.readlines()[1:]
+ n_lines = len(lines)
+ n_trips = len(lines)
+- print 'analyze', n_lines, 'points and', n_trips, 'trips'
++ print('analyze', n_lines, 'points and', n_trips, 'trips')
+
+ ids_trip_sumo = np.zeros(n_trips,dtype = 'object')
+ ids_mode = np.zeros(n_trips,dtype = np.int32)
+@@ -6025,11 +6025,11 @@
+
+
+ else:
+- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath)
+- print ' cols =',cols
++ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath))
++ print(' cols =',cols)
+
+ if i_line%500000 == 0:
+- print i_line,'/',len(lines), 'points imported'
++ print(i_line,'/',len(lines), 'points imported')
+ i_line += 1
+
+ # register points of last trip after loop ended
+@@ -6078,7 +6078,7 @@
+
+ class EccTracesImporter(FilterMixin):
+ def __init__(self, mapmatching, logger = None, **kwargs):
+- print 'EccTracesImporter.__init__',mapmatching.get_ident()
++ print('EccTracesImporter.__init__',mapmatching.get_ident())
+ self._init_common( 'traceimporter',
+ parent = mapmatching,
+ name = 'ECC Trace Importer',
+@@ -6179,7 +6179,7 @@
+ & (speed_av < self.speed_trip_max)
+
+ def do(self):
+- print 'TraceImporter.do'
++ print('TraceImporter.do')
+ if self.year == 2014:
+ self.import_workouts_2014()
+ self.import_points_2014()
+@@ -6202,7 +6202,7 @@
+ #UserID TripID TimeStamp Start DT Distance ECC AvgSpeed TrackType Sex Year Profession Frequent User ZIP Source TypeOfBike TipeOfTrip Max Spd
+ #57249bcd88c537874f9fa1ae 57515edc88c537576ca3e16f 1464945480 2016-06-03T09:18:00.000Z 4.75 4.75 10.16 urban bicycle F 1999 Studente yes cy-web-gpx MyBike HomeToSchool 25.45
+
+- j_id_user, j_id_trip, j_timestamp, j_date, j_dist, j_dist_copy, j_speed_av, j_tracktype, j_sex, j_year, j_profession, j_frequent, j_zip, j_device, j_biketype, j_purpose, j_speedmax = range(17)
++ j_id_user, j_id_trip, j_timestamp, j_date, j_dist, j_dist_copy, j_speed_av, j_tracktype, j_sex, j_year, j_profession, j_frequent, j_zip, j_device, j_biketype, j_purpose, j_speedmax = list(range(17))
+ n_cols = 17
+ null = 'NULL'
+ trips = self.parent.trips
+@@ -6283,17 +6283,17 @@
+ #print
+
+ else:
+- print ' invalid trip',cols[j_id_trip]
++ print(' invalid trip',cols[j_id_trip])
+
+ else:
+- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.workoutsfilepath)
+- print ' cols =',cols
++ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.workoutsfilepath))
++ print(' cols =',cols)
+
+ i_line += 1
+
+
+ def import_points_2016(self):
+- print 'import_points_2016'
++ print('import_points_2016')
+ # 0 1 2 3 4 5 6 7
+ # TripID, TimeStamp,Latitude, Longitude, Altitude, Distance, Speed, Type
+ # 574e98c988c5378163a3e11f,1462347278,44.52606,11.27617,78,0.027255420500625783,5,,
+@@ -6385,8 +6385,8 @@
+
+
+ else:
+- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath)
+- print ' cols =',cols
++ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath))
++ print(' cols =',cols)
+
+
+ i_line += 1
+@@ -6421,7 +6421,7 @@
+ #54eb068de71f393530a9a74d 54eb0737e71f394c2fa9a74d 1424692504 Mon, 23 Feb 2015 11:55:04 GMT 0 0 urban bicycle M 1987 Developer no
+ #54eb9374e71f39f02fa9a750 5505cb04e71f39542e25e2d4 1426442994 Sun, 15 Mar 2015 18:09:54 GMT 0 0.7 urban bicycle M 1974 Worker yes 40128
+
+- j_id_user, j_id_trip, j_timestamp, j_date, j_dist, j_speed_av, j_tracktype, j_sex, j_year, j_profession, j_frequent, j_zip = range(12)
++ j_id_user, j_id_trip, j_timestamp, j_date, j_dist, j_speed_av, j_tracktype, j_sex, j_year, j_profession, j_frequent, j_zip = list(range(12))
+ n_cols = 12
+ null = 'NULL'
+ trips = self.parent.trips
+@@ -6498,13 +6498,13 @@
+ zip = zip,
+ )
+ else:
+- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.workoutsfilepath)
++ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.workoutsfilepath))
+ #print ' cols =',cols
+
+ i_line += 1
+
+ def import_points_2015(self):
+- print 'import_points_2015'
++ print('import_points_2015')
+ # 0 1 2 3 4 5 6 7 8
+ #TripID, TimeStamp,Date, Latitude, Longitude, Altitude, Distance, Speed, Type
+ #54eb0737e71f394c2fa9a74d,1424692509,"Mon, 23 Feb 2015 11:55:09 GMT",44.499096,11.361185,49.419395,0,0.000815,start
+@@ -6596,7 +6596,7 @@
+
+
+ else:
+- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath)
++ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath))
+ #print ' cols =',cols
+
+
+@@ -6626,13 +6626,13 @@
+
+
+ def import_workouts_2014(self):
+- print 'import_workouts_2014'
++ print('import_workouts_2014')
+ # 2014 ecomondo workouts
+ #id pointDBNode pointPathId startTime distance duration sport calories maxSpeed altitudeMin altitudeMax metersAscent metersDescent
+ #329308466 7 37073516 2014-05-01 19:00:00 26 15600 1 1182.64 NULL NULL NULL NULL NULL
+ # 0 1 2 3 4 5 6 7 8 9 10 11 12
+
+- j_id, j_node, j_id_trip, j_time, j_dist,j_duration = range(6)
++ j_id, j_node, j_id_trip, j_time, j_dist,j_duration = list(range(6))
+ j_v_max = 8
+ n_cols = 13
+ null = 'NULL'
+@@ -6686,7 +6686,7 @@
+
+
+ def import_points_2014(self):
+- print 'import_points_2014'
++ print('import_points_2014')
+ # csv2014
+ #pointDBNode,pointPathId,id,timestamp,latitude,longitude,altitude,distance,heartRate,instruction,speed
+ #4,61565791,23648171762,2013-05-01 06:33:58,44.501085,11.372906,NULL,0,NULL,2,NULL
+@@ -6782,7 +6782,7 @@
+
+
+ else:
+- print 'WARNING: inconsistent columns in line %d, file %s'%(i_line,os.path.basename(self.pointsfilepath))
++ print('WARNING: inconsistent columns in line %d, file %s'%(i_line,os.path.basename(self.pointsfilepath)))
+
+
+ i_line += 1
+@@ -6808,7 +6808,7 @@
+
+
+ def import_points_2013(self):
+- print 'import_points_2013'
++ print('import_points_2013')
+ #pointDBNode, pointPathId, id, timestamp, latitude, longitude, altitude,distance, heartRate,instruction,speed
+ #4, 61565791, 23648171762,2013-05-01 06:33:58,44.501085, 11.372906, NULL, 0, NULL, 2, NULL
+ #0 1 2 3 4 5 6 7 8 9 10
+@@ -6924,7 +6924,7 @@
+
+
+ else:
+- print 'WARNING: inconsistent columns in line %d, file %s'%(i_line,os.path.basename(self.pointsfilepath))
++ print('WARNING: inconsistent columns in line %d, file %s'%(i_line,os.path.basename(self.pointsfilepath)))
+
+
+ i_line += 1
+@@ -6952,7 +6952,7 @@
+
+ class GpxImporter(FilterMixin):
+ def __init__(self, mapmatching, logger = None, **kwargs):
+- print 'GpxImporter.__init__',mapmatching.get_ident()
++ print('GpxImporter.__init__',mapmatching.get_ident())
+ self._init_common( 'gpximporter',
+ parent = mapmatching,
+ name = 'GPX Importer',
+@@ -6996,7 +6996,7 @@
+ Reads endomondo gpx xml file and stores point data in traces table.
+ If there is no traces table, one will be initialized and returned
+ """
+- print 'GpxImporter.do',self.filepaths
++ print('GpxImporter.do',self.filepaths)
+ mapmatching = self.parent
+ #scenario = mapmatching.get_scenario()
+ logger = self.get_logger()
+@@ -7015,7 +7015,7 @@
+ speed_trip_max = self.speed_trip_max,
+ )
+ for filepath in self.filepaths.split(','):
+- print ' parse gpx file', filepath
++ print(' parse gpx file', filepath)
+ parse(filepath.strip(), parser)
+
+ ids_trips = parser.get_ids_trip()
+@@ -7207,7 +7207,7 @@
+
+ class GtfsShapeImporter(FilterMixin):
+ def __init__(self, mapmatching, logger = None, **kwargs):
+- print 'GtfsShapeImporter.__init__',mapmatching.get_ident()
++ print('GtfsShapeImporter.__init__',mapmatching.get_ident())
+ self._init_common( 'gtfsshapeimporter',
+ parent = mapmatching,
+ name = 'GTFS Importer',
+@@ -7250,7 +7250,7 @@
+ Reads endomondo gpx xml file and stores point data in traces table.
+ If there is no traces table, one will be initialized and returned
+ """
+- print 'GtfsShapeImporter.do',self.gtfsdirpath
++ print('GtfsShapeImporter.do',self.gtfsdirpath)
+ mapmatching = self.parent
+
+ mapmatching.get_attrsman().do_not_save_attrs(['gtfsdirpath'])
+@@ -7263,7 +7263,7 @@
+ net = self.parent
+ get_vtype_for_mode = scenario.demand.vtypes.get_vtype_for_mode#( id_mode)
+ id_vtype = get_vtype_for_mode(self.id_mode)
+- print ' self.id_mode',self.id_mode,'id_vtype',id_vtype
++ print(' self.id_mode',self.id_mode,'id_vtype',id_vtype)
+ tripshapes = mapmatching.trips
+ points = mapmatching.points
+
+@@ -7286,7 +7286,7 @@
+ for fileattr_raw in f.readline().split(sep):
+
+ fileattr = fileattr_raw.strip().strip(aa)
+- print ' check fileattr *%s*, %d'%(fileattr,i)
++ print(' check fileattr *%s*, %d'%(fileattr,i))
+ if fileattr == 'shape_id':
+ ind_shape_id = i
+
+@@ -7324,7 +7324,7 @@
+ id_shape = tripshapes.add_row( ids_sumo = cols[ind_shape_id].strip(aa),
+ ids_vtype = id_vtype)
+
+- print ' id_shape',id_shape,tripshapes.ids_vtype[id_shape],id_vtype
++ print(' id_shape',id_shape,tripshapes.ids_vtype[id_shape],id_vtype)
+ lons = []
+ lats = []
+ ind_shape = ind_shape_new
+@@ -7369,7 +7369,7 @@
+ self._results = Matchresults( 'matchresults',mapmatching)
+ else:
+ self._results = results
+- print 'GtfsGenerator.__init__'
++ print('GtfsGenerator.__init__')
+ self._init_common( ident,
+ parent = mapmatching,
+ name = 'GTFS Stop Generator',
+@@ -7458,7 +7458,7 @@
+ #def place_stop(self, id_stop, name_stop, lat_stop, lon_ stop, **kwargs):
+
+ def do(self):
+- print 'GtfsStopGenerator.do'
++ print('GtfsStopGenerator.do')
+ # go through shapes.txt and match shapes with id_edges
+ # > shape_id -> ids_edge
+ # done through mapmatching
+@@ -7544,7 +7544,7 @@
+ map_trip_to_shape[cols[ind_trip_id].strip().strip(aa)] = id_shape
+
+ id_service = cols[ind_service_id].strip().strip(aa)
+- if not map_service_to_trips.has_key(id_service):
++ if id_service not in map_service_to_trips:
+ map_service_to_trips[id_service] = []
+ else:
+ map_service_to_trips[id_service].append(id_trip)
+@@ -7558,11 +7558,11 @@
+ #else:
+ # map_service_to_route[id_service] = cols[ind_route_id].strip().strip(aa)
+ map_trip_to_route[id_trip] = cols[ind_route_id].strip().strip(aa)
+- print ' *id_trip',id_trip,'id_service',id_service,'id_route',cols[ind_route_id].strip().strip(aa),'-> id_shape',id_shape
++ print(' *id_trip',id_trip,'id_service',id_service,'id_route',cols[ind_route_id].strip().strip(aa),'-> id_shape',id_shape)
+
+ f.close()
+
+- print ' result: len(map_trip_to_shape)',len(map_trip_to_shape),'different shapes',len(set(map_trip_to_shape.values())),'of',len(ids_gtsshape_set)
++ print(' result: len(map_trip_to_shape)',len(map_trip_to_shape),'different shapes',len(set(map_trip_to_shape.values())),'of',len(ids_gtsshape_set))
+ #ids_trip = {}
+ #for id_shape in gpstrips.ids_sumo[gpstrips.get_ids()]:
+ # ids_trip[id_shape] = map_shape_to_trip[id_shape]
+@@ -7589,28 +7589,28 @@
+ id_stop = cols[ind_stop_id].strip().strip(aa)
+ #print ' id_trip',id_trip,map_trip_to_shape.has_key(id_trip),'found stop',id_stop
+
+- if map_trip_to_shape.has_key(id_trip):
+- if not trip_stops.has_key(id_trip):
++ if id_trip in map_trip_to_shape:
++ if id_trip not in trip_stops:
+ trip_stops[id_trip] = []
+ trip_times[id_trip] = []
+- print ' for id_trip',id_trip,'* found id_stop',id_stop,'at id_shape',map_trip_to_shape[id_trip]
++ print(' for id_trip',id_trip,'* found id_stop',id_stop,'at id_shape',map_trip_to_shape[id_trip])
+ trip_stops[id_trip].append(id_stop)
+ trip_times[id_trip].append(cols[ind_departure_time].strip().strip(aa))
+
+
+ f.close()
+- print ' result: len(trip_stops)',len(trip_stops)
++ print(' result: len(trip_stops)',len(trip_stops))
+
+ # dictionary to map stop ID to shape ID that will be used
+ # to identify edge of stop
+ stop_shapes = OrderedDict()
+- for id_trip, ids_stop in trip_stops.iteritems():
++ for id_trip, ids_stop in trip_stops.items():
+ #print ' id_trip',id_trip,'ids_stop',ids_stop
+ #print ' ',
+ for id_stop in ids_stop:
+ #print (map_trip_to_shape.has_key(id_trip),map_trip_to_shape.has_key(id_trip)),
+ # currently not all trips have shapes (unless include direction = 1)
+- if (map_trip_to_shape.has_key(id_trip)):
++ if (id_trip in map_trip_to_shape):
+ #print '*',
+ ids_edges = ids_edges_shape[gpstrips.ids_route_matched[get_id_gpstrip(map_trip_to_shape[id_trip])]]
+ # edges of shape of new trip
+@@ -7619,7 +7619,7 @@
+ else:
+ n_edges = 0
+
+- if stop_shapes.has_key(id_stop):
++ if id_stop in stop_shapes:
+ # use new shape if shape is longer than previous shape
+ if n_edges > len(ids_edges_shape[gpstrips.ids_route_matched[get_id_gpstrip(stop_shapes[id_stop])]]):
+ stop_shapes[id_stop] = map_trip_to_shape[id_trip]
+@@ -7658,7 +7658,7 @@
+ cols = line.split(sep)
+ id_stop = cols[ind_stop_id].strip().strip(aa)
+ #print ' found id_stop',id_stop,stop_shapes.has_key(id_stop)
+- if stop_shapes.has_key(id_stop):
++ if id_stop in stop_shapes:
+ ids_stop_gtfs.append(id_stop)
+
+ lats.append(float(cols[ind_stop_lat].strip().strip(aa)))
+@@ -7680,8 +7680,8 @@
+ accesslevelsmap = self.parent.get_accesslevelsmap()
+ #gtfsstop_to_simstop = {}
+ for id_stop, coord, stopname in zip(ids_stop_gtfs,coords, stopnames):
+- print '\n id_stop',id_stop, coord,'id_gpstrip',get_id_gpstrip(stop_shapes[id_stop])
+- print ' id_gpsroute',gpstrips.ids_route_matched[get_id_gpstrip(stop_shapes[id_stop])]
++ print('\n id_stop',id_stop, coord,'id_gpstrip',get_id_gpstrip(stop_shapes[id_stop]))
++ print(' id_gpsroute',gpstrips.ids_route_matched[get_id_gpstrip(stop_shapes[id_stop])])
+ ids_edge_target = ids_edges_shape[gpstrips.ids_route_matched[get_id_gpstrip(stop_shapes[id_stop])]]
+ #print ' ids_edge_target',ids_edge_target
+
+@@ -7697,12 +7697,12 @@
+ ind = 0
+ is_hit = False
+ n_hits = len(ids_edge_hit)
+- print ' n_hits',n_hits,'len(ids_edge_target)',len(ids_edge_target),'dists',dists
++ print(' n_hits',n_hits,'len(ids_edge_target)',len(ids_edge_target),'dists',dists)
+ while (not is_hit) & (ind=2):
+- print ' check ped access',lanes.get_accesslevel([ids_lane[0]], id_mode_ped)
++ print(' check ped access',lanes.get_accesslevel([ids_lane[0]], id_mode_ped))
+
+
+
+ if lanes.get_accesslevel([ids_lane[0]], id_mode_ped)>-1:
+- print ' check bus access',lanes.get_accesslevel([ids_lane[1]], id_mode_pt)
++ print(' check bus access',lanes.get_accesslevel([ids_lane[1]], id_mode_pt))
+ if lanes.get_accesslevel([ids_lane[1]], id_mode_pt)>-1:
+
+ ids_simstop_exist = ptstops.select_ids(ptstops.ids_lane.get_value() == ids_lane[1])
+ if len(ids_simstop_exist)>0:
+- print ' there are already stops ids_simstop_exist',ids_simstop_exist
++ print(' there are already stops ids_simstop_exist',ids_simstop_exist)
+ d_init = np.min(ptstops.positions_from[ids_simstop_exist])
+ d_end = edgelength-np.max(ptstops.positions_to[ids_simstop_exist])
+- print ' d_init,d_end',d_init,d_end
++ print(' d_init,d_end',d_init,d_end)
+ if d_init>d_end:
+- print ' place stop in front of previous stops'
++ print(' place stop in front of previous stops')
+ pos_from = d_init - self.length_stop
+ pos_to = d_init
+- print ' try pos_from',pos_from
++ print(' try pos_from',pos_from)
+ if pos_from < self.dist_edge_stop_min:
+ pos_from = d_init - self.length_stop_min
+- print ' try with shorter stop pos_from',pos_from
++ print(' try with shorter stop pos_from',pos_from)
+
+ is_hit = pos_from > self.dist_edge_stop_min
+
+ else:
+- print ' place stop in behind previous stops'
++ print(' place stop in behind previous stops')
+ pos_from = edgelength-d_end
+ pos_to = pos_from+self.length_stop
+- print ' try pos_to',pos_to
++ print(' try pos_to',pos_to)
+ if pos_to > edgelength-self.dist_edge_stop_min:
+ pos_to = pos_from+self.length_stop_min
+- print ' try with shorter stop pos_to',pos_to
++ print(' try with shorter stop pos_to',pos_to)
+
+ is_hit = pos_to < edgelength-self.dist_edge_stop_min
+
+@@ -7780,35 +7780,35 @@
+ else:
+
+ pos = edges.get_pos_from_coord(id_edge, coord)-0.5*self.dist_edge_stop_min
+- print ' place stop nearest to GPS coordinate pos',pos
++ print(' place stop nearest to GPS coordinate pos',pos)
+ if pos < self.dist_edge_stop_min:
+ pos_from = self.dist_edge_stop_min
+ pos_to = self.dist_edge_stop_min + self.length_stop
+- print ' try pos_to',pos_to
++ print(' try pos_to',pos_to)
+ if pos_to > edgelength-self.dist_edge_stop_min:
+ pos_to = self.dist_edge_stop_min + self.length_stop_min
+- print ' try with shorter stop pos_to',pos_to
++ print(' try with shorter stop pos_to',pos_to)
+ is_hit = pos_to < edgelength-self.dist_edge_stop_min
+
+ elif pos+ self.length_stop > edgelength-self.dist_edge_stop_min:
+ pos_from = edgelength-self.dist_edge_stop_min- self.length_stop
+ pos_to = edgelength-self.dist_edge_stop_min
+- print ' try pos_from',pos_from
++ print(' try pos_from',pos_from)
+ if pos_from < self.dist_edge_stop_min:
+ pos_from = edgelength-self.dist_edge_stop_min- self.length_stop_min
+- print ' try with shorter stop pos_from',pos_from
++ print(' try with shorter stop pos_from',pos_from)
+
+ is_hit = pos_from > self.dist_edge_stop_min
+
+ else:
+- print ' stop fits'
++ print(' stop fits')
+ pos_from = pos
+ pos_to = pos + self.length_stop
+ is_hit = True
+
+
+ if is_hit:
+- print ' Add stop',id_stop,'at id_edge',id_edge,'pos_from %d'%pos_from,'pos_to %d'%pos_to,'edgelength %d'%edgelength
++ print(' Add stop',id_stop,'at id_edge',id_edge,'pos_from %d'%pos_from,'pos_to %d'%pos_to,'edgelength %d'%edgelength)
+ id_simstop = ptstops.make( id_stop,
+ id_lane = ids_lane[1],
+ position_from = pos_from,
+@@ -7829,7 +7829,7 @@
+ self._results = Matchresults( 'matchresults',mapmatching)
+ else:
+ self._results = results
+- print 'GtfsServiceGenerator.__init__'
++ print('GtfsServiceGenerator.__init__')
+ self._init_common( ident,
+ parent = mapmatching,
+ name = 'GTFS Service Generator',
+@@ -7948,16 +7948,16 @@
+ date = cols[ind_date].strip().strip(aa)
+ year,month,day = (date[0:4],date[4:6],date[6:8])
+ id_service = cols[ind_service_id].strip().strip(aa)
+- print ' id_service',id_service,'year,month,day',year,month,day,(int(year) == self.year) ,(int(month) == self.month),(int(day) == self.day),
++ print(' id_service',id_service,'year,month,day',year,month,day,(int(year) == self.year) ,(int(month) == self.month),(int(day) == self.day), end=' ')
+ #service_to_date [cols[ind_service_id].strip().strip(aa)] = (date[0:4],date[4:6],date[6:8])
+
+
+
+ if (int(year) == self.year) & (int(month) == self.month) &(int(day) == self.day):
+- print 'valid'
++ print('valid')
+ ids_service_valid.append(cols[ind_service_id].strip().strip(aa))
+ else:
+- print 'not valid'
++ print('not valid')
+
+ f.close()
+
+@@ -7967,7 +7967,7 @@
+ else:
+ return self.schedule_simple(ids_service_valid)
+ else:
+- print 'WARNING: no services found on specified date.'
++ print('WARNING: no services found on specified date.')
+ return True
+
+ def schedule_frequ_est(self, ids_service_valid):
+@@ -8000,11 +8000,11 @@
+ ids_edges_shape = gpstrips.routes.get_value().ids_edges
+
+ if not hasattr(mapmatching,'trip_stops'):
+- print 'WARNING: no stops found, please run PT stop generation first'
++ print('WARNING: no stops found, please run PT stop generation first')
+ return False
+ ##
+ ## Generate timetables for ids_trip
+- ids_trip = mapmatching.trip_stops.keys()
++ ids_trip = list(mapmatching.trip_stops.keys())
+
+ time_inter_begin = self.hour_begin*3600.0
+ time_inter_end = self.hour_end*3600.0
+@@ -8013,12 +8013,12 @@
+ # maps stop sequences to a unique service ID
+ # which is different from the GTFS service ID
+ stopsequence_to_services = {}
+- for id_service, ids_trip in mapmatching.map_service_to_trips.iteritems():
++ for id_service, ids_trip in mapmatching.map_service_to_trips.items():
+ if id_service in ids_service_valid:
+ for id_trip in ids_trip:
+
+ hs,ms,ss = trip_times[id_trip][0].split(':')
+- print ' examin valid id_service',id_service,'id_trip',id_trip,'t',hs,ms,ss
++ print(' examin valid id_service',id_service,'id_trip',id_trip,'t',hs,ms,ss)
+ hs = int(hs)
+ if (hs >= self.hour_begin)&(hs 0:
+@@ -9649,7 +9649,7 @@
+ # get selected trips only
+ ids_trip = np.array(ids_trip_all)[trips.are_selected[ids_trip_all] ]
+
+- print ' analyze person',id_person,'ids_trip',ids_trip
++ print(' analyze person',id_person,'ids_trip',ids_trip)
+
+ if ids_trip is not None:
+ n_trips = len(ids_trip)
+@@ -9678,7 +9678,7 @@
+ self.ids_trips[id_pers].append(id_trip)
+
+ def make(self, id_sumo, **kwargs):
+- print 'make id_pers_sumo',id_sumo
++ print('make id_pers_sumo',id_sumo)
+
+ id_trip = kwargs.get('id_trip',-1)
+ if self.ids_sumo.has_index(id_sumo):
+@@ -9785,7 +9785,7 @@
+
+
+ def _init_attributes(self):
+- print 'Mapmatching._init_attributes'
++ print('Mapmatching._init_attributes')
+ attrsman = self.get_attrsman()
+
+ self.points = attrsman.add( cm.ObjConf(GpsPoints('points',self)))
+@@ -9911,7 +9911,7 @@
+ Returns a dictionary where key is id_mode and
+ value is a distance-lookup table, mapping id_edge to edge distance
+ """
+- print 'get_distancesmap',self._distancesmap is None
++ print('get_distancesmap',self._distancesmap is None)
+
+
+ if self._distancesmap is None:
+@@ -9920,7 +9920,7 @@
+ vtypes = self.get_scenario().demand.vtypes
+ ids_vtype = self.trips.ids_vtype[self.trips.get_ids()]
+ ids_mode = vtypes.ids_mode[ids_vtype]
+- print ' ids_mode',set(ids_mode),len(ids_mode)
++ print(' ids_mode',set(ids_mode),len(ids_mode))
+
+ self._distancesmap = {}
+ for id_mode in set(ids_mode):
+@@ -9939,7 +9939,7 @@
+ Returns a dictionary where key is id_mode and
+ value is the corrisponding fstar.
+ """
+- print 'get_fstarmap',self._fstarmap is None
++ print('get_fstarmap',self._fstarmap is None)
+
+
+ if self._fstarmap is None:
+@@ -9948,7 +9948,7 @@
+ vtypes = self.get_scenario().demand.vtypes
+ ids_vtype = self.trips.ids_vtype[self.trips.get_ids()]
+ ids_mode = vtypes.ids_mode[ids_vtype]
+- print ' ids_mode',set(ids_mode),len(ids_mode)
++ print(' ids_mode',set(ids_mode),len(ids_mode))
+
+ self._fstarmap = {}
+ for id_mode in set(ids_mode):
+@@ -9976,7 +9976,7 @@
+ vtypes = self.get_scenario().demand.vtypes
+ ids_vtype = self.trips.ids_vtype[self.trips.get_ids()]
+ ids_mode = vtypes.ids_mode[ids_vtype]
+- print ' ids_mode',set(ids_mode),len(ids_mode)
++ print(' ids_mode',set(ids_mode),len(ids_mode))
+
+
+
+@@ -10021,7 +10021,7 @@
+ # attention: need to check whether already set
+ # because setattr is set explicitely after add
+ if not hasattr(self, resultobj.get_ident()):
+- if kwargs.has_key('groupnames'):
++ if 'groupnames' in kwargs:
+ kwargs['groupnames'].append('Results')
+ else:
+ kwargs['groupnames'] = ['Results']
+@@ -10253,17 +10253,17 @@
+ the average wait tie at node id_node is
+ times_wait_est[id_node]
+ """
+- print 'get_times_wait_est'
++ print('get_times_wait_est')
+ nodes = self.ids_node.get_linktab()
+ ids_node = nodes.get_ids()
+ ids_node_signif = self.get_nodes_significant()
+ #nodetypes = nodes.types[ids_node_signif]
+ map_nodetype_to_times_wait = self.get_map_nodetype_to_times_wait()
+
+- print ' map_nodetype_to_times_wait',map_nodetype_to_times_wait
++ print(' map_nodetype_to_times_wait',map_nodetype_to_times_wait)
+
+ times_wait = np.zeros(max(ids_node)+1, dtype = np.int32)
+- print ' ',np.min(nodes.types[ids_node_signif]),np.max(nodes.types[ids_node_signif])
++ print(' ',np.min(nodes.types[ids_node_signif]),np.max(nodes.types[ids_node_signif]))
+
+ times_wait[ids_node_signif] = map_nodetype_to_times_wait[nodes.types[ids_node_signif]]
+
+@@ -10272,11 +10272,11 @@
+ return times_wait
+
+ def get_map_nodetype_to_times_wait(self):
+- print 'get_map_nodetype_to_times_wait'
++ print('get_map_nodetype_to_times_wait')
+ nodes = self.ids_node.get_linktab()
+ ids_res = self.get_ids()
+ nodetypes = nodes.types[self.ids_node[ids_res]]
+- nodetypeset = nodes.types.choices.values()
++ nodetypeset = list(nodes.types.choices.values())
+ #map_type_to_typename = get_inversemap(nodes.types.choices)
+ #map_type_to_times_wait = {}
+ map_type_to_times_wait = np.zeros(max(nodetypeset)+1,dtype = np.float32)
+@@ -10503,7 +10503,7 @@
+ # return result ids and respective edge ids
+ ids_edgeresmap = np.zeros(np.max(ids_edge_init)+1,dtype = np.int32)
+ ids_edgeresmap[ids_edge_init] = self.add_rows(n=len(ids_edge_init), ids_edge = ids_edge_init)
+- print 'init_for_routes: created',len(ids_edge_init),'entries for edgeresults max(ids_edge)', np.max(ids_edge_init)
++ print('init_for_routes: created',len(ids_edge_init),'entries for edgeresults max(ids_edge)', np.max(ids_edge_init))
+
+ return ids_edgeresmap
+
+@@ -10516,7 +10516,7 @@
+ # return result ids and respective edge ids
+ ids_edgeresmap = np.zeros(np.max(ids_edge_init)+1,dtype = np.int32)
+ ids_edgeresmap[ids_edge_init] = self.add_rows(n=len(ids_edge_init), ids_edge = ids_edge_init)
+- print 'init_for_routes: created',len(ids_edge_init),'entries for edgeresults max(ids_edge)', np.max(ids_edge_init)
++ print('init_for_routes: created',len(ids_edge_init),'entries for edgeresults max(ids_edge)', np.max(ids_edge_init))
+ return ids_edgeresmap
+
+ def get_edgeresmap(self):
+@@ -10753,7 +10753,7 @@
+ # return result ids and respective edge ids
+ ids_connectionresmap = np.zeros(np.max(ids_connection_init)+1,dtype = np.int32)
+ ids_connectionresmap[ids_connection_init] = self.add_rows(n=len(ids_connection_init), ids_connection = ids_connection_init)
+- print 'init_for_routes: created',len(ids_connection_init),'entries for connectionresults max(ids_connection)', np.max(ids_connection_init)
++ print('init_for_routes: created',len(ids_connection_init),'entries for connectionresults max(ids_connection)', np.max(ids_connection_init))
+ return ids_connectionresmap
+
+ def get_connectionresmap(self):
+@@ -11383,7 +11383,7 @@
+
+ class Shortestrouter(Process):
+ def __init__(self, ident, mapmatching, logger = None, **kwargs):
+- print 'Shortestrouter.__init__'
++ print('Shortestrouter.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -11441,7 +11441,7 @@
+ ))
+
+ def do(self):
+- print 'Shortestrouter.do'
++ print('Shortestrouter.do')
+ # links
+ mapmatching = self.parent
+ trips = mapmatching.trips
+@@ -11455,7 +11455,7 @@
+
+ class Fastestrouter(Process):
+ def __init__(self, ident, mapmatching, logger = None, matchresults = None, **kwargs):
+- print 'Fastestrouter.__init__'
++ print('Fastestrouter.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -11528,7 +11528,7 @@
+ def do(self):
+ mapmatching = self.parent
+ trips = mapmatching.trips
+- print 'Shortestrouter.do is_use_nodeswaittimes_est',self.is_use_nodeswaittimes_est,(self.matchresults is not None)
++ print('Shortestrouter.do is_use_nodeswaittimes_est',self.is_use_nodeswaittimes_est,(self.matchresults is not None))
+ # links
+
+ # map_nodetype_to_times_wait = get_map_nodetype_to_times_wait
+@@ -11698,7 +11698,7 @@
+
+ class AlternativeRoutesanalyzer(Process):
+ def __init__(self, ident, mapmatching, results = None, logger = None, **kwargs):
+- print 'AlternativeRoutesanalyzer.__init__'
++ print('AlternativeRoutesanalyzer.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -11792,7 +11792,7 @@
+ return self._results
+
+ def do(self):
+- print 'AlternativeRoutesanalyzer.do'
++ print('AlternativeRoutesanalyzer.do')
+ # results
+ results = self.get_results()
+ altroutesresults = results.altroutesresults
+@@ -11864,10 +11864,10 @@
+
+ #ind = 0
+ if len(ids_trip)==0:
+- print 'WARNING: no trips selected.'
++ print('WARNING: no trips selected.')
+ return True
+
+- print ' analyzing %d trips'%len(ids_trip)
++ print(' analyzing %d trips'%len(ids_trip))
+
+
+ #ids_res = routesresults_matched.add_rows(n=len(ids_trip),)
+@@ -11888,8 +11888,8 @@
+ routes.ids_edges[ids_route_fastest],
+ ids_mode,
+ ):
+- print 79*'*'
+- print ' id_trip',id_trip
++ print(79*'*')
++ print(' id_trip',id_trip)
+
+ # edge weights for routing, which is mode specific
+ # because non accessible edges are marked with weight = -1
+@@ -11925,7 +11925,7 @@
+ if id_edge_matched != id_edge_shortest:
+
+ dist = np.sum(weights[route_ol])
+- print ' overlapped route len',len(route_ol),'d',dist
++ print(' overlapped route len',len(route_ol),'d',dist)
+ if (len(route_ol) >= self.n_edge_min) & (dist > self.dist_alt_min):
+ #print ' store and finish route_ol',route_ol
+ routesets_overlap.append([route_ol,])
+@@ -11960,7 +11960,7 @@
+ # collect data of matched and shortest route section
+ dist_matched = np.sum(weights[route_matched_nol])
+ dist_shortest = np.sum(weights[route_shortest_nol])
+- print ' nonoverlapped route len',len(route_shortest_nol),'dm',dist_matched,'ds',dist_shortest,'dd',dist_matched-dist_shortest
++ print(' nonoverlapped route len',len(route_shortest_nol),'dm',dist_matched,'ds',dist_shortest,'dd',dist_matched-dist_shortest)
+ if (len(route_matched_nol)>=self.n_edge_min)\
+ &(len(route_shortest_nol)>=self.n_edge_min)\
+ &(dist_matched > self.dist_alt_min)\
+@@ -12014,7 +12014,7 @@
+
+
+
+- print ' create shortest routes around overlapping routes',len(routesets_overlap)
++ print(' create shortest routes around overlapping routes',len(routesets_overlap))
+ for routeset_overlap, routeset_overlap_dists in zip(routesets_overlap, routesets_overlap_dists):
+ # routesets_overlap has initially the onlu selected route
+ ids_edge = routeset_overlap[0]
+@@ -12048,32 +12048,32 @@
+
+
+ if 0:
+- print 79*'='
++ print(79*'=')
+ n_overl = 0
+ for routeset_nonoverlap, routeset_nonoverlap_dists in zip(routesets_nonoverlap,routesets_nonoverlap_dists):
+- print
++ print()
+ dist_min = np.min(routeset_nonoverlap_dists)
+ if len(routeset_nonoverlap)>0:
+ n_overl += 1
+ for ids_edge, dist in zip(routeset_nonoverlap, routeset_nonoverlap_dists):
+- print ' nonoverl d=%dfm, delta=%dm'%(dist,dist-dist_min),dist#,'ids_edge',ids_edge
+-
+- print ' len(routesets_nonoverlap)',len(routesets_nonoverlap),len(ids_trip_routesets_overlap),len(routesets_overlap_dists)
++ print(' nonoverl d=%dfm, delta=%dm'%(dist,dist-dist_min),dist)#,'ids_edge',ids_edge
++
++ print(' len(routesets_nonoverlap)',len(routesets_nonoverlap),len(ids_trip_routesets_overlap),len(routesets_overlap_dists))
+
+
+ if 0:
+- print 79*'='
++ print(79*'=')
+ n_overl = 0
+ for routeset_overlap, routeset_overlap_dists in zip(routesets_overlap,routesets_overlap_dists):
+- print
++ print()
+ dist_min = np.min(routeset_overlap_dists)
+ if len(routeset_overlap)>0:
+ n_overl += 1
+ for ids_edge, dist in zip(routeset_overlap, routeset_overlap_dists):
+- print ' overl d=%dfm, delta=%dm'%(dist,dist-dist_min),'ids_edge',ids_edge
+-
+-
+- print ' len(routesets_overlap)',n_overl,len(ids_trip_routesets_nonoverlap),len(routesets_nonoverlap_dists)
++ print(' overl d=%dfm, delta=%dm'%(dist,dist-dist_min),'ids_edge',ids_edge)
++
++
++ print(' len(routesets_overlap)',n_overl,len(ids_trip_routesets_nonoverlap),len(routesets_nonoverlap_dists))
+
+ self._samplecount = 0
+ self._id_alt_last = 10**8
+@@ -12083,13 +12083,13 @@
+ #print ' routesets_nonoverlap',routesets_nonoverlap
+ #print ' routesets_nonoverlap_dists',routesets_nonoverlap_dists
+
+- print 79*'*'
+- print ' create alternative routes database'
++ print(79*'*')
++ print(' create alternative routes database')
+
+ # do all non-overlap routes
+ for id_trip, routeset_nonoverlap, routeset_nonoverlap_dists, id_mode in zip(ids_trip_routesets_nonoverlap, routesets_nonoverlap,routesets_nonoverlap_dists,ids_mode_routesets_nonoverlap):
+- print 79*'-'
+- print ' id_trip NOL',id_trip,len(routeset_overlap)
++ print(79*'-')
++ print(' id_trip NOL',id_trip,len(routeset_overlap))
+ #print ' routeset_nonoverlap',routeset_nonoverlap
+ #print ' dists',routeset_nonoverlap_dists
+ if len(routeset_nonoverlap) >= 2:
+@@ -12101,8 +12101,8 @@
+
+ # do all overlap and generated routes
+ for id_trip, routeset_overlap, routeset_overlap_dists, id_mode in zip(ids_trip_routesets_overlap, routesets_overlap,routesets_overlap_dists, ids_mode_routesets_overlap):
+- print 79*'-'
+- print ' id_trip OL',id_trip,len(routeset_overlap)
++ print(79*'-')
++ print(' id_trip OL',id_trip,len(routeset_overlap))
+ if len(routeset_overlap) >= 2:
+ # add chosen, matched and overlapping route
+ self.add_alternative(id_trip,np.array(routeset_overlap[0], dtype=np.int32),1, True, routeset_overlap_dists[0], id_mode)
+@@ -12133,7 +12133,7 @@
+ #print ' ids_edge[accesses[ids_edge]==1]',ids_edge[accesses[ids_edge]==1]
+ #print ' edgelengths[ids_edge[accesses[ids_edge]==1]]',edgelengths[ids_edge[accesses[ids_edge]==1]]
+
+- print 'add_alternative',id_trip,id_alt,is_selected, 'dist',dist,np.sum(edgelengths[ids_edge]),'excl',np.sum(edgelengths[ids_edge[accesses[ids_edge]==2]])
++ print('add_alternative',id_trip,id_alt,is_selected, 'dist',dist,np.sum(edgelengths[ids_edge]),'excl',np.sum(edgelengths[ids_edge[accesses[ids_edge]==2]]))
+ id_res = self.altroutesresults.add_row(\
+ ids_trip = id_trip,
+ counter = self._samplecount,
+@@ -15122,7 +15122,7 @@
+ MA_real_vs_expected1_waiting_time = np.zeros(len(ids_person))
+ MA_real_vs_expected2_waiting_time = np.zeros(len(ids_person))
+
+- for id_person, i in zip(ids_person, range(len(ids_person))):
++ for id_person, i in zip(ids_person, list(range(len(ids_person)))):
+
+ ids_tripsdatabase_pers = ids_tripsdatabase[(tripsdatabase.ids_person[ids_tripsdatabase] == id_person)]
+ lengths = tripsdatabase.lengths_route_matched[ids_tripsdatabase_pers]
+@@ -16723,7 +16723,7 @@
+
+ ids_person = np.zeros(len(ids_routesresults_matched), dtype = np.int32)
+ ids_routesresults_shortest = np.zeros(len(ids_routesresults_matched), dtype = np.int32)
+- for i, id_routesresults_matched in zip(range(len(ids_routesresults_matched)),ids_routesresults_matched):
++ for i, id_routesresults_matched in zip(list(range(len(ids_routesresults_matched))),ids_routesresults_matched):
+ #if self.parent.trips.ids_person[self.parent.trips.get_routes().ids_trip[routesresults_matched.ids_route[id_routesresults_matched]]] > 0:
+ ## print id_routesresults_matched
+ id_route = routesresults_matched.ids_route[id_routesresults_matched]
+@@ -17001,7 +17001,7 @@
+
+ class Routesanalyzer(Process):
+ def __init__(self, ident, mapmatching, results = None, logger = None, **kwargs):
+- print 'Routesanalyzer.__init__'
++ print('Routesanalyzer.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -17178,7 +17178,7 @@
+
+
+ def do(self):
+- print 'Routesanalyzer.do'
++ print('Routesanalyzer.do')
+ # results
+ results = self.get_results()
+ routesresults_shortest = results.routesresults_shortest
+@@ -17243,10 +17243,10 @@
+
+ #ind = 0
+ if len(ids_trip)==0:
+- print 'WARNING: no trips selected.'
++ print('WARNING: no trips selected.')
+ return True
+
+- print ' analyzing %d trips'%len(ids_trip)
++ print(' analyzing %d trips'%len(ids_trip))
+
+ routesresults_shortest.clear()
+ routesresults_matched.clear()
+@@ -17320,8 +17320,8 @@
+
+
+ if 1:
+- print 70*'-'
+- print 'id_trip',id_trip,'Routes: id_matched',id_route_matched,'id_shortest',id_route_shortest,'id_fastest',id_route_fastest
++ print(70*'-')
++ print('id_trip',id_trip,'Routes: id_matched',id_route_matched,'id_shortest',id_route_shortest,'id_fastest',id_route_fastest)
+
+ #ids_point = trips.ids_points[id_trip]
+ distances = distancesmap[id_mode]
+@@ -17473,7 +17473,7 @@
+ if element in possible_connections:
+ connections_list.append(element)
+ if connections_list == []:
+- print 'Error: map matching process should be done without ignoring connections'
++ print('Error: map matching process should be done without ignoring connections')
+ break
+ lane_index_connections = lanes.indexes[connections.ids_fromlane[connections_list]] + lanes.indexes[connections.ids_tolane[connections_list]]
+ connection = connections_list[np.argmin(lane_index_connections)]
+@@ -17597,7 +17597,7 @@
+ else:
+ ## print '11'
+ is_adeguate = False
+- print 'too few or points or edges involved'
++ print('too few or points or edges involved')
+ break
+ ## #If the problem occour to the second points
+ ## else:
+@@ -17667,7 +17667,7 @@
+ #Match points to edge and connections
+ cumulative_dists = np.zeros(len(cumulative_dists_initial))
+ #Correct cumulative distances, adding a length to the connections from the backward
+- for is_connection, i in zip(are_connection, range(len(cumulative_dists_initial))):
++ for is_connection, i in zip(are_connection, list(range(len(cumulative_dists_initial)))):
+ if is_connection == 0 and i < len(cumulative_dists_initial)-1:
+ if i>0:
+ if cumulative_dists_initial[i] - self.junctionrange > cumulative_dists_initial[i-1]:
+@@ -17685,7 +17685,7 @@
+ ids_arc_point = np.zeros(len(point_positions_on_poly), dtype = np.int32)
+ are_connection_points = np.zeros(len(point_positions_on_poly), dtype = np.int32)
+ diffs = cumulative_dists-point_positions_on_poly[0]
+- for diff, i in zip(diffs, range(len(diffs))):
++ for diff, i in zip(diffs, list(range(len(diffs)))):
+ if diff < 0:
+ diffs[i] = np.max(diffs)+1
+ ids_arc_point[0] = ids_arc[np.argmin(diffs[(diffs>0)])]
+@@ -17725,7 +17725,7 @@
+
+
+ #calculate average edge speed
+- for i, id_arc, is_connection in zip(range(len(ids_arc)), ids_arc, are_connection):
++ for i, id_arc, is_connection in zip(list(range(len(ids_arc))), ids_arc, are_connection):
+ if i>0 and i0:
+ delta_time = point_times[i] - point_times[i-1]
+@@ -17807,7 +17807,7 @@
+
+ if id_arc_point != id_arc_pre:
+ n_wait_times_edge_at_int[lanes.ids_edge[connections.ids_fromlane[id_arc_point]]] += 1
+- print 'connection', id_arc_point, 'n +1'
++ print('connection', id_arc_point, 'n +1')
+ n_wait_times_node[edges.ids_tonode[lanes.ids_edge[connections.ids_fromlane[id_arc_point]]]] += 1
+ if connections.turns_type[id_arc_point] == 'left_turn':
+ number_wait_route_at_left_turns += 1
+@@ -17851,7 +17851,7 @@
+ if id_arc_point != id_arc_pre and last_conn > 0:
+ connections_waitingtimes[last_conn].append(current_waitingtime_total)
+ nodes_waitingtimes[edges.ids_tonode[lanes.ids_edge[connections.ids_fromlane[last_conn]]]].append(current_waitingtime_total)
+- print 'ADD', 'current_waitingtime_total', current_waitingtime_total, 'id_arc_point', last_conn
++ print('ADD', 'current_waitingtime_total', current_waitingtime_total, 'id_arc_point', last_conn)
+ current_waitingtime_total = 0.0
+
+ if is_connection_point:
+@@ -17863,7 +17863,7 @@
+ if id_arc_point != id_arc_pre:
+ current_waitingtime_total = 0.0
+ current_waitingtime_total += delta_time
+- print 'current_waitingtime_total', current_waitingtime_total, 'id_arc_point', id_arc_point
++ print('current_waitingtime_total', current_waitingtime_total, 'id_arc_point', id_arc_point)
+ id_arc_pre = id_arc_point
+
+
+@@ -17871,10 +17871,10 @@
+ if last_conn > 0:
+ connections_waitingtimes[last_conn].append(current_waitingtime_total)
+ nodes_waitingtimes[edges.ids_tonode[lanes.ids_edge[connections.ids_fromlane[last_conn]]]].append(current_waitingtime_total)
+- print 'ADD', 'current_waitingtime_total', current_waitingtime_total, 'id_arc_point', last_conn
++ print('ADD', 'current_waitingtime_total', current_waitingtime_total, 'id_arc_point', last_conn)
+ current_waitingtime_total = 0.0
+- print 'there were', len(irregular_indices), 'irregular indices'
+- print 'time_wait_route', time_wait_route,'time_wait_junction_route',time_wait_junction_route, 'time_wait_tls_route', time_wait_tls_route
++ print('there were', len(irregular_indices), 'irregular indices')
++ print('time_wait_route', time_wait_route,'time_wait_junction_route',time_wait_junction_route, 'time_wait_tls_route', time_wait_tls_route)
+ ## print 'GOOD TRACES', good_traces, 'OF',(good_traces+bad_traces) ,'/',len(ids_trip)
+
+ #Find all connection for the connection results
+@@ -17971,7 +17971,7 @@
+
+ ## plt.show()
+ bad_traces+=1
+- print 'trip', id_trip, 'is not adeguate for the speed analysis or too few points remained after point filtering, with', len(irregular_indices), 'irregular points'
++ print('trip', id_trip, 'is not adeguate for the speed analysis or too few points remained after point filtering, with', len(irregular_indices), 'irregular points')
+
+ routesresults_matched.times_inmotion[id_res]= -1.
+ routesresults_matched.n_times_wait[id_res] = -1.
+@@ -18001,7 +18001,7 @@
+
+
+
+- print 'There were', good_traces, 'good traces and', bad_traces, 'bad traces', 'of',(good_traces+bad_traces) ,'/',len(ids_trip)
++ print('There were', good_traces, 'good traces and', bad_traces, 'bad traces', 'of',(good_traces+bad_traces) ,'/',len(ids_trip))
+
+
+
+@@ -18109,7 +18109,7 @@
+ if element in possible_connections:
+ connections_list.append(element)
+ if connections_list == []:
+- print 'Error: map matching process should be done without ignoring connections'
++ print('Error: map matching process should be done without ignoring connections')
+ break
+ lane_index_connections = lanes.indexes[connections.ids_fromlane[connections_list]] + lanes.indexes[connections.ids_tolane[connections_list]]
+ connection = connections_list[np.argmin(lane_index_connections)]
+@@ -18146,20 +18146,20 @@
+ dist_shortest = np.sum(distances[ids_edge_shortest])
+
+ if 0:
+- print '\n shortest dist ana'
++ print('\n shortest dist ana')
+ d_cum = 0.0
+ l_cum = 0.0
+ for id_edge in ids_edge_shortest:
+ d_cum += distances[id_edge]
+ l_cum += edges.lengths[id_edge]
+- print ' id_edge_short',id_edge,'dist',distances[id_edge],'length',edges.lengths[id_edge],'c_cum',d_cum,'l_cum',l_cum
+- print
++ print(' id_edge_short',id_edge,'dist',distances[id_edge],'length',edges.lengths[id_edge],'c_cum',d_cum,'l_cum',l_cum)
++ print()
+ d_cum = 0.0
+ l_cum = 0.0
+ for id_edge in ids_edge:
+ d_cum += distances[id_edge]
+ l_cum += edges.lengths[id_edge]
+- print ' id_edge_matched',id_edge,'dist',distances[id_edge],'length',edges.lengths[id_edge],'c_cum',d_cum,'l_cum',l_cum
++ print(' id_edge_matched',id_edge,'dist',distances[id_edge],'length',edges.lengths[id_edge],'c_cum',d_cum,'l_cum',l_cum)
+
+
+ n_nodes_shortest = len(nodetypes_shortest)
+@@ -18531,7 +18531,7 @@
+ routesresults_matched.expected_waiting_times_tot_route_matched_tls_nodes[ids_routesresults_matched] = expected_waiting_times_tot_route_matched_tls_nodes[ids_routesresults_matched]
+ routesresults_matched.expected_waiting_times_tot_route_matched_edges[ids_routesresults_matched] = expected_waiting_times_tot_route_matched_edges[ids_routesresults_matched]
+
+- print ' Route analyses done.'
++ print(' Route analyses done.')
+ return True
+
+ def get_connectionsresults_map(self):
+@@ -18565,7 +18565,7 @@
+ """
+ Only overlap calculations.
+ """
+- print 'Routesanalyzer.do_overlap'
++ print('Routesanalyzer.do_overlap')
+ # results
+ results = self.get_results()
+ routesresults_shortest = results.routesresults_shortest
+@@ -18618,10 +18618,10 @@
+
+ #ind = 0
+ if len(ids_trip)==0:
+- print 'WARNING: no trips selected.'
++ print('WARNING: no trips selected.')
+ return True
+
+- print ' analyzing %d trips'%len(ids_trip)
++ print(' analyzing %d trips'%len(ids_trip))
+
+ routesresults_shortest.clear()
+ #routesresults_matched.clear()
+@@ -18644,8 +18644,8 @@
+
+
+ if 0:
+- print 70*'-'
+- print 'id_trip',id_trip,'Routes: id_matched',id_route_matched,'id_shortest',id_route_shortest,'id_fastest',id_route_fastest
++ print(70*'-')
++ print('id_trip',id_trip,'Routes: id_matched',id_route_matched,'id_shortest',id_route_shortest,'id_fastest',id_route_fastest)
+
+ #ids_point = trips.ids_points[id_trip]
+ distances = distancesmap[id_mode]
+@@ -18710,7 +18710,7 @@
+
+
+
+- print ' Route overlap analyses done.'
++ print(' Route overlap analyses done.')
+ return True
+
+ class PtRoutesresults(am.ArrayObjman):
+@@ -18872,7 +18872,7 @@
+
+ class PtRoutesanalyzer(Process):
+ def __init__(self, ident, mapmatching, results = None, logger = None, **kwargs):
+- print 'Routesanalyzer.__init__'
++ print('Routesanalyzer.__init__')
+
+ # TODO: let this be independent, link to it or child??
+
+@@ -18927,7 +18927,7 @@
+
+
+ def do(self):
+- print 'Routesanalyzer.do'
++ print('Routesanalyzer.do')
+ # results
+ results = self.get_results()
+ ptlinesresults = results.ptlinesresults
+@@ -18973,8 +18973,8 @@
+ ptlinks.lengths[ids_link],ptlinks.durations[ids_link]):
+
+ if type_link == type_transit:
+- if not numbercounter_lines.has_key(id_line):
+- print id_line
++ if id_line not in numbercounter_lines:
++ print(id_line)
+ numbercounter_lines[id_line] = 0
+ distancecounter_lines[id_line] = 0.0
+ timecounter_lines[id_line] = 0.0
+@@ -18983,12 +18983,12 @@
+ distancecounter_lines[id_line] += dist_link
+ timecounter_lines[id_line] += duration_link
+
+- if not numbercounter_links.has_key(id_link):
++ if id_link not in numbercounter_links:
+ numbercounter_links[id_link] = 0
+
+ numbercounter_links[id_link] += 1
+
+- ids_line = numbercounter_lines.keys()
++ ids_line = list(numbercounter_lines.keys())
+ ids_lineres = ptlinesresults.add_rows(n=len(ids_line),ids_line = ids_line)
+ id_line_to_id_lineres = {}
+
+@@ -19014,14 +19014,14 @@
+
+ id_line_to_id_lineres[id_line] = id_lineres
+
+- ids_link = numbercounter_links.keys()
++ ids_link = list(numbercounter_links.keys())
+ for id_link, id_line, id_fromstop, id_tostop, n in zip(\
+ ids_link, ptlinks.ids_line[ids_link],
+ ptlinks.ids_fromstop[ids_link],ptlinks.ids_tostop[ids_link],
+- numbercounter_links.values()):
++ list(numbercounter_links.values())):
+
+ ptrouteresults = ptlinesresults.ptroutesresults[id_line_to_id_lineres[id_line]]
+- if map_stops_to_routeres[id_line].has_key((id_fromstop, id_tostop)):
++ if (id_fromstop, id_tostop) in map_stops_to_routeres[id_line]:
+ id_routeres = map_stops_to_routeres[id_line][(id_fromstop, id_tostop)]
+ ## print ' Add',n,'trips to id_line %d (%s) id_fromstop %d id_tostop %d'%(id_line,ptlines.linenames[id_line],id_fromstop, id_tostop)
+ ptrouteresults.ids_link[id_routeres] = id_link
+@@ -19036,7 +19036,7 @@
+ """
+ Writes routes to file.
+ """
+- print '\n routes_to_shapefile for mapmatching'
++ print('\n routes_to_shapefile for mapmatching')
+ net = mapmatching.get_scenario().net
+ edges = net.edges
+ trips = mapmatching.trips
+@@ -19105,7 +19105,7 @@
+ """
+ Writes edge results of mapmatching to shape-file.
+ """
+- print '\n edgesresults_to_shapefile for mapmatching'
++ print('\n edgesresults_to_shapefile for mapmatching')
+ net = mapmatching.get_scenario().net
+ edges = net.edges
+ edgesresults = results.edgesresults
+@@ -19179,7 +19179,7 @@
+ #
+
+
+- print 'nodes_to_shapefile',filepath
++ print('nodes_to_shapefile',filepath)
+
+ for attr in attrlist:
+ shapedata.add_field(attr[2:])
+--- tools/contributed/sumopy/plugins/mapmatching/results_mpl.py (original)
++++ tools/contributed/sumopy/plugins/mapmatching/results_mpl.py (refactored)
+@@ -33,7 +33,7 @@
+ import agilepy.lib_base.arrayman as am
+ from agilepy.lib_base.geometry import *
+ from agilepy.lib_base.processes import Process
+-from mapmatching import COLOR_MATCHED_ROUTE, COLOR_SHORTEST_ROUTE, COLOR_FASTEST_ROUTE
++from .mapmatching import COLOR_MATCHED_ROUTE, COLOR_SHORTEST_ROUTE, COLOR_FASTEST_ROUTE
+ import time
+ try:
+ from scipy import interpolate
+@@ -257,7 +257,7 @@
+
+ # Plot net
+ if self.is_net:
+- print 'plot net'
++ print('plot net')
+ plot_net(ax, net, color_edge="gray", width_edge=2, color_node=None,
+ alpha=0.5)
+ # Plot zones
+@@ -280,7 +280,7 @@
+ # select points
+ ids_final_point = np.zeros((len(ids_trip)), dtype=np.int32)
+ ids_initial_point = np.zeros((len(ids_trip)), dtype=np.int32)
+- for id_trip, ids_point, i in zip(trips.get_ids(), ids_points, range(len(ids_trip))):
++ for id_trip, ids_point, i in zip(trips.get_ids(), ids_points, list(range(len(ids_trip)))):
+ ids_final_point[i] = ids_point[-1]
+ ids_initial_point[i] = ids_point[0]
+ if self.select_points == 1:
+@@ -306,7 +306,7 @@
+ # ids_final_point.tolist()
+ ids_point = ids_initial_point.tolist()
+ ids_point.extend(ids_final_point)
+- print ids_initial_point, ids_final_point, ids_points
++ print(ids_initial_point, ids_final_point, ids_points)
+ if self.points_type == 4:
+ ids_point = points.get_ids(points.are_selected.get_value() == True)
+ coords = points.coords[ids_point]
+@@ -325,7 +325,7 @@
+ for coord, id_point in zip(coords, ids_point):
+ coord = np.array([coord[0], coord[1]])
+ id_closest_edge = net.edges.get_closest_edge(coord)
+- print 'point', id_point
++ print('point', id_point)
+ if id_closest_edge > 0:
+ if self.select_points == 1:
+ time = (points.timestamps[id_point] - trips.timestamps[points.ids_trip[id_point]])/60.0
+@@ -346,10 +346,10 @@
+ # For the isochrone plot
+ # if self.is_isochrone:
+ ## times_point[id_point] = time
+- print 'number of points:', np.sum(count)
++ print('number of points:', np.sum(count))
+
+ # Plot result on map
+- print 'plot results on map'
++ print('plot results on map')
+ if self.select_points == 1:
+ title = 'Isochrone from the origin zone'
+ if self.select_points == 2:
+@@ -470,7 +470,7 @@
+ else:
+ isochrone_shapes[i].append([(points.coords[iso_points[np.argmax(iso_points[:, 3]), 1]][0]),
+ (points.coords[iso_points[np.argmax(iso_points[:, 3]), 1]][1])])
+- print isochrone_shapes
++ print(isochrone_shapes)
+ for isochrone_shape in isochrone_shapes:
+ verts = np.array(isochrone_shape)[:, :2].tolist()
+ verts.append([0, 0])
+@@ -487,9 +487,9 @@
+
+ if len(isochrone_shape) > 4:
+ zone_shape = isochrone_shape
+- print zone_shape
+- for zone_shape_coords, i in zip(isochrone_shape, range(len(isochrone_shape))):
+- print i, len(isochrone_shape)
++ print(zone_shape)
++ for zone_shape_coords, i in zip(isochrone_shape, list(range(len(isochrone_shape)))):
++ print(i, len(isochrone_shape))
+ if i == 0:
+ zone_shape[i] = ((np.array(isochrone_shape[i])+np.array(isochrone_shape[i+1])+np.array(
+ isochrone_shape[-1])+np.array(isochrone_shape[i+2])+np.array(isochrone_shape[-2]))/5.).tolist()
+@@ -539,7 +539,7 @@
+ ])
+ self.plottheme = attrsman.add(cm.AttrConf('plottheme', kwargs.get('plottheme', 'times wait'),
+ groupnames=['options'],
+- choices=self.plotthemefuncs.keys(),
++ choices=list(self.plotthemefuncs.keys()),
+ name='Plot theme',
+ info='Theme or edge attribute to be plottet.',
+ ))
+@@ -560,7 +560,7 @@
+ attrsman.delete('is_widthvalue')
+
+ def plot_all_themes(self):
+- for plottheme in self.plotthemefuncs.keys():
++ for plottheme in list(self.plotthemefuncs.keys()):
+ self.plottheme = plottheme
+ self.show()
+ ##
+@@ -599,7 +599,7 @@
+ return self.parent.nodesresults
+
+ def show(self):
+- print 'NoderesultPlotter.show', self.plottheme
++ print('NoderesultPlotter.show', self.plottheme)
+ # if self.axis is None:
+ #axis = init_plot()
+ self.init_figures()
+@@ -607,9 +607,9 @@
+ axis = fig.add_subplot(111)
+ self.plotthemefuncs[self.plottheme](axis)
+
+- print ' self.is_save', self.is_save
++ print(' self.is_save', self.is_save)
+ if not self.is_save:
+- print ' show_plot'
++ print(' show_plot')
+ show_plot()
+ else:
+ figname = 'nodeplot_'+self.plottheme
+@@ -628,7 +628,7 @@
+ plt.close(fig)
+
+ def plot_times_wait(self, ax):
+- print 'show noderesults', len(self.parent.nodesresults)
++ print('show noderesults', len(self.parent.nodesresults))
+ # if self.axis is None:
+
+ nodesresults = self.parent.nodesresults
+@@ -824,7 +824,7 @@
+
+ def plot_speed_over_time(self, ax, id_trip, id_route, edges, i_min=None, i_max=None,
+ is_pointlabel=True, alpha=1.0):
+- print 'plot_speed_over_time', id_trip, type(id_trip), self.parent.parent
++ print('plot_speed_over_time', id_trip, type(id_trip), self.parent.parent)
+
+ #mapmatching = self.parent.parent
+ #trips = mapmatching.trips
+@@ -868,7 +868,7 @@
+
+ if is_scipy & (not (self.method_interp == 'linear')):
+
+- print 'use scipy to interpolate'
++ print('use scipy to interpolate')
+ #tck = interpolate.splrep(x, y, s=0)
+ #xnew = np.linspace(np.min(x), np.max(x), 200)
+ #ynew = interpolate.splev(xnew, tck, der=0)
+@@ -895,7 +895,7 @@
+
+ def plot_speed_over_way(self, ax, id_trip, id_route, edges, i_min=None, i_max=None,
+ is_pointlabel=True, alpha=1.0):
+- print 'plot_speed_over_way', id_trip, type(id_trip), self.parent.parent
++ print('plot_speed_over_way', id_trip, type(id_trip), self.parent.parent)
+
+ #mapmatching = self.parent.parent
+ #trips = mapmatching.trips
+@@ -933,10 +933,10 @@
+ y = np.array(speeds, dtype=np.float32)*3.6 # in km/h
+
+ #ax = init_plot()
+- print ' ids_point', routeresults.ids_valid_point_speedana[id_routeres]
+- print ' position', pointspositions
+- print ' x', x
+- print ' y', y
++ print(' ids_point', routeresults.ids_valid_point_speedana[id_routeres])
++ print(' position', pointspositions)
++ print(' x', x)
++ print(' y', y)
+ #ax.plot(locations, speeds, color = self.color_line[:2], lw = self.width_line ,alpha=0.9 ,zorder = 0)
+
+ if is_scipy & (not (self.method_interp == 'linear')):
+@@ -964,7 +964,7 @@
+ fontsize=int(0.8*self.size_labelfont)) # baseline
+
+ def show(self):
+- print 'show', self.id_trip, type(self.id_trip), self.parent.parent
++ print('show', self.id_trip, type(self.id_trip), self.parent.parent)
+ # if self.axis is None:
+
+ if self.id_trip >= 0:
+@@ -1054,8 +1054,8 @@
+ id_arc_last = 0
+ i_point = 0
+ pointstime = routeresults.speedana_point_times[id_routeres]
+- print ' len(ids_pointedge)', len(ids_pointedge)
+- print ' len(pointstime)', len(pointstime)
++ print(' len(ids_pointedge)', len(ids_pointedge))
++ print(' len(pointstime)', len(pointstime))
+
+ # if len(pointstime)>1:
+ # t_last = pointstime[1]
+@@ -1076,7 +1076,7 @@
+ routeresults.speedana_point_pos[id_routeres],
+ ):
+
+- print ' id_arc_point', id_arc_point, 'is_connection_point', is_connection_point, 'id_arc_last', id_arc_last, id_arc_point != id_arc_last, 'pos=%.2fm, t=%.2fs, v=%.2fkm/h' % (pos, t, v*3.6),
++ print(' id_arc_point', id_arc_point, 'is_connection_point', is_connection_point, 'id_arc_last', id_arc_last, id_arc_point != id_arc_last, 'pos=%.2fm, t=%.2fs, v=%.2fkm/h' % (pos, t, v*3.6), end=' ')
+ color = 'k'
+ if (id_arc_point != id_arc_last):
+
+@@ -1181,7 +1181,7 @@
+ cumulative_dists = np.insert(cumulative_dists, 0, 0.).tolist()
+ ids_arc = routeresults.ids_arc[id_routeres]
+ are_connections = routeresults.is_connection[id_routeres]
+- print cumulative_dists, ids_arc
++ print(cumulative_dists, ids_arc)
+
+ for cumulative_dist, id_arc, is_connection in zip(cumulative_dists, ids_arc, are_connections):
+
+@@ -1210,7 +1210,7 @@
+ if self.is_waitslabel_tls & (time_wait_tls > 0):
+ label += ' $T_{\mathrm{TL}}=%ds$' % time_wait_tls
+
+- print ' id_edge', id_arc, 'pos=%df' % cumulative_dist, 'time_wait', time_wait, 'time_wait_junc', time_wait_junc, 'time_wait_tls', time_wait_tls
++ print(' id_edge', id_arc, 'pos=%df' % cumulative_dist, 'time_wait', time_wait, 'time_wait_junc', time_wait_junc, 'time_wait_tls', time_wait_tls)
+
+ ax.text(cumulative_dist, ymin, label,
+ verticalalignment='bottom',
+@@ -1219,7 +1219,7 @@
+ color=color,
+ fontsize=int(0.8*self.size_labelfont))
+ else:
+- print 'the edge', id_arc, 'is not in the edgeresult database'
++ print('the edge', id_arc, 'is not in the edgeresult database')
+ else:
+ if connectionsresults.ids_connection.has_index(id_arc):
+ id_connectionres = connectionsresults.ids_connection.get_id_from_index(id_arc)
+@@ -1237,7 +1237,7 @@
+ if self.is_waitslabel_tls & (time_wait_tls > 0):
+ label += ' $T_{\mathrm{TL}}=%ds$' % time_wait_tls
+
+- print ' id_connection', id_arc, 'pos=%df' % x, 'time_wait', time_wait, 'time_wait_junc', time_wait_junc, 'time_wait_tls', time_wait_tls
++ print(' id_connection', id_arc, 'pos=%df' % x, 'time_wait', time_wait, 'time_wait_junc', time_wait_junc, 'time_wait_tls', time_wait_tls)
+
+ ax.text(cumulative_dist, ymin, label,
+ verticalalignment='bottom',
+@@ -1246,7 +1246,7 @@
+ color=color,
+ fontsize=int(0.8*self.size_labelfont))
+ else:
+- print 'the connection', id_arc, 'is not in the connectionresult database'
++ print('the connection', id_arc, 'is not in the connectionresult database')
+
+ ax.plot([cumulative_dist, cumulative_dist], [ymin, ymax], color=color, linestyle=linestyle)
+
+@@ -1315,7 +1315,7 @@
+ ])
+ self.plottheme = attrsman.add(cm.AttrConf('plottheme', kwargs.get('plottheme', 'average speeds'),
+ groupnames=['options'],
+- choices=self.plotthemefuncs.keys(),
++ choices=list(self.plotthemefuncs.keys()),
+ name='Plot theme',
+ info='Theme or edge attribute to be plottet.',
+ ))
+@@ -1331,12 +1331,12 @@
+ self.add_save_options(**kwargs)
+
+ def plot_all_themes(self):
+- for plottheme in self.plotthemefuncs.keys():
++ for plottheme in list(self.plotthemefuncs.keys()):
+ self.plottheme = plottheme
+ self.show()
+
+ def show(self):
+- print 'EdgeresultPlotter.show', self.plottheme
++ print('EdgeresultPlotter.show', self.plottheme)
+ # if self.axis is None:
+ #axis = init_plot()
+ self.init_figures()
+@@ -1344,9 +1344,9 @@
+ axis = fig.add_subplot(111)
+ self.plotthemefuncs[self.plottheme](axis)
+
+- print ' self.is_save', self.is_save
++ print(' self.is_save', self.is_save)
+ if not self.is_save:
+- print ' show_plot'
++ print(' show_plot')
+ show_plot()
+ else:
+ figname = 'edgeplot_'+self.plottheme
+@@ -1373,7 +1373,7 @@
+ ids_edge = edges.get_ids()
+ #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
+ average_slopes = edges.average_slopes
+- print ids_edge, average_slopes[ids_edge]
++ print(ids_edge, average_slopes[ids_edge])
+ self.plot_results_on_map(ax,
+ values=average_slopes[ids_edge],
+ ids_edge=ids_edge,
+@@ -1387,7 +1387,7 @@
+ ids_edge = edges.get_ids()
+ #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
+ positive_climbs = edges.positive_climbs
+- print ids_edge, positive_climbs[ids_edge]
++ print(ids_edge, positive_climbs[ids_edge])
+ self.plot_results_on_map(ax,
+ values=positive_climbs[ids_edge],
+ ids_edge=ids_edge,
+@@ -1401,7 +1401,7 @@
+ ids_edge = edges.get_ids()
+ #resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
+ negative_climbs = edges.negative_climbs
+- print ids_edge, negative_climbs[ids_edge]
++ print(ids_edge, negative_climbs[ids_edge])
+ self.plot_results_on_map(ax,
+ values=negative_climbs[ids_edge],
+ ids_edge=ids_edge,
+@@ -1459,7 +1459,7 @@
+ def plot_speeds_average(self, ax):
+ edgesresults = self.parent.edgesresults
+
+- print 'plot_speeds_average'
++ print('plot_speeds_average')
+
+ #ids_result = edgesresults.get_ids()
+ ids_result = edgesresults.select_ids(
+@@ -1562,7 +1562,7 @@
+ ])
+ self.plottheme = attrsman.add(cm.AttrConf('plottheme', kwargs.get('plottheme', 'times wait'),
+ groupnames=['options'],
+- choices=self.plotthemefuncs.keys(),
++ choices=list(self.plotthemefuncs.keys()),
+ name='Plot theme',
+ info='Theme or edge attribute to be plottet.',
+ ))
+@@ -1578,12 +1578,12 @@
+ self.add_save_options(**kwargs)
+
+ def plot_all_themes(self):
+- for plottheme in self.plotthemefuncs.keys():
++ for plottheme in list(self.plotthemefuncs.keys()):
+ self.plottheme = plottheme
+ self.show()
+
+ def show(self):
+- print 'connectionresultPlotter.show', self.plottheme
++ print('connectionresultPlotter.show', self.plottheme)
+ # if self.axis is None:
+ #axis = init_plot()
+ self.init_figures()
+@@ -1591,9 +1591,9 @@
+ axis = fig.add_subplot(111)
+ self.plotthemefuncs[self.plottheme](axis)
+
+- print ' self.is_save', self.is_save
++ print(' self.is_save', self.is_save)
+ if not self.is_save:
+- print ' show_plot'
++ print(' show_plot')
+ show_plot()
+ else:
+ figname = 'connectionplot_'+self.plottheme
+@@ -1694,12 +1694,12 @@
+
+ # configure fixed options as privat (non visible for gui)
+ attrsman = self.get_attrsman()
+- for attrname in kwargs_fixed.keys():
++ for attrname in list(kwargs_fixed.keys()):
+ attrconf = attrsman.get_config(attrname)
+ attrconf.add_groupnames(['_private'])
+
+ def show(self):
+- print 'AlternativeRoutesPlotter.show'
++ print('AlternativeRoutesPlotter.show')
+ # if self.axis is None:
+ #axis = init_plot()
+ title = 'Route alternatives'
+@@ -1772,7 +1772,7 @@
+ is_colorbar=False,
+ )
+ else:
+- print 'WARNING in AlternativeRoutesPlotter.show ids_edge=', ids_edge_all, 'of id_trip', id_trip
++ print('WARNING in AlternativeRoutesPlotter.show ids_edge=', ids_edge_all, 'of id_trip', id_trip)
+
+ if self.is_show_title:
+ axis.set_title(title, fontsize=self.size_titlefont)
+@@ -1787,9 +1787,9 @@
+ axis.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ ## save or show
+- print ' self.is_save', self.is_save
++ print(' self.is_save', self.is_save)
+ if not self.is_save:
+- print ' show_plot'
++ print(' show_plot')
+ show_plot()
+ else:
+ self.save_fig('altroutesplot')
+@@ -1804,7 +1804,7 @@
+ self._init_common('routeresultplotter', parent=results, name=name,
+ info=info, logger=logger)
+
+- print 'Resultplotter.__init__', results, self.parent
++ print('Resultplotter.__init__', results, self.parent)
+ attrsman = self.get_attrsman()
+
+ mapmatching = self.parent.parent
+@@ -2158,20 +2158,20 @@
+ show_plot()
+
+ def plot_bike_availability_ffbss(self):
+- print 'plot_bike_availability_ffbss'
++ print('plot_bike_availability_ffbss')
+ # Print the number of bikes simultaneously used every 24h/n_bins hours by selecting traces of a particular day
+ fig = self.create_figure()
+ mapmatching = self.parent.parent
+ trips = mapmatching.trips
+ ids_trip = trips.get_ids()[(trips.are_selected[trips.get_ids()] == True)]
+ dep_arr_times = np.zeros((len(ids_trip), 2))
+- for i, id_trip in zip(range(len(ids_trip)), ids_trip):
++ for i, id_trip in zip(list(range(len(ids_trip))), ids_trip):
+ t = time.localtime(trips.timestamps[id_trip])
+ dep_arr_times[i, 0] = t.tm_hour + t.tm_min/60.0 + t.tm_sec/3600.0
+ dep_arr_times[i, 1] = dep_arr_times[i, 0] + trips.durations_gps[id_trip]/3600.0
+ self.n_bins
+ ## dep_arr_times = np.sort(dep_arr_times.sort, axis = 0)
+- print dep_arr_times[:1000]
++ print(dep_arr_times[:1000])
+ ax = fig.add_subplot(111)
+ x_min = min(dep_arr_times[:, 0])
+ x_max = max(dep_arr_times[:, 0])
+@@ -2179,10 +2179,10 @@
+ bike_usage = np.zeros(self.n_bins)
+
+ for id_trip, dep_arr_time in zip(ids_trip, dep_arr_times):
+- for bin, i in zip(bins, range(self.n_bins)):
++ for bin, i in zip(bins, list(range(self.n_bins))):
+ if dep_arr_time[0] < bin and dep_arr_time[1] > bin:
+ bike_usage[i-1] += 1
+- print bike_usage
++ print(bike_usage)
+ bincenters = plt.plot(bins, bike_usage, color=self.color_matched,
+ label='Bike usage distribution of GPS Mobike traces')
+ ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
+@@ -2197,7 +2197,7 @@
+ self.save_fig('bike_usage')
+
+ def plot_bike_availability_ffbss_zone(self):
+- print 'plot_bike_availability_ffbss_zone'
++ print('plot_bike_availability_ffbss_zone')
+ # Plot the difference between attracted and generated trips froma zone in a day every 24h/n_bins hours
+ fig = self.create_figure()
+ mapmatching = self.parent.parent
+@@ -2217,7 +2217,7 @@
+ for id_trip, ids_point in zip(ids_trip, ids_points):
+ id_initial_point = ids_point[0]
+ id_final_point = ids_point[-1]
+- print id_trip
++ print(id_trip)
+ starting_time = np.int(points.timestamps[id_initial_point] % 86400/86400.*np.float(n_bins))
+ arriving_time = np.int(points.timestamps[id_final_point] % 86400/86400.*np.float(n_bins))
+
+@@ -2271,7 +2271,7 @@
+ self.save_fig('bike_availability')
+
+ def analyze_bike_availability_ffbss_zones(self):
+- print 'analyze_bike_availability_ffbss_zones'
++ print('analyze_bike_availability_ffbss_zones')
+ # Save a .txt file with generated trips and attracted trips every 24h/n_bins hours for each zone with selected trips
+ fig = self.create_figure()
+ mapmatching = self.parent.parent
+@@ -2290,7 +2290,7 @@
+ for id_trip, ids_point in zip(ids_trip, ids_points):
+ id_initial_point = ids_point[0]
+ id_final_point = ids_point[-1]
+- print id_trip
++ print(id_trip)
+ starting_time = np.int(points.timestamps[id_initial_point] % 86400/86400.*np.float(n_bins))
+ arriving_time = np.int(points.timestamps[id_final_point] % 86400/86400.*np.float(n_bins))
+ i = 0
+@@ -2408,13 +2408,13 @@
+ self.save_fig('bike_availability')
+
+ def plot_deptimedistrib(self):
+- print 'plot_deptimedistrib'
++ print('plot_deptimedistrib')
+ fig = self.create_figure()
+ mapmatching = self.parent.parent
+ trips = mapmatching.trips
+ ids_trip = trips.get_ids()
+ hour_departure = np.zeros(len(ids_trip))
+- for i, id_trip in zip(range(len(ids_trip)), ids_trip):
++ for i, id_trip in zip(list(range(len(ids_trip))), ids_trip):
+ t = time.localtime(trips.timestamps[id_trip])
+ hour_departure[i] = t.tm_hour + t.tm_min/60.0 + t.tm_sec/3600.0
+ # print hour_departure[:1000]
+@@ -2451,7 +2451,7 @@
+ self.save_fig('plot_deptimedistrib')
+
+ def plot_tldensity(self):
+- print 'plot_tldensity'
++ print('plot_tldensity')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -2488,7 +2488,7 @@
+ self.save_fig('routeana_tldensity')
+
+ def plot_nodesdensity(self):
+- print 'plot_nodesdensity'
++ print('plot_nodesdensity')
+ fig = self.create_figure()
+ results = self.parent
+
+@@ -2526,7 +2526,7 @@
+ self.save_fig('routeana_nodesdensity')
+
+ def plot_prioritychangedensity(self):
+- print 'plot_prioritychangedensity'
++ print('plot_prioritychangedensity')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -2563,7 +2563,7 @@
+ self.save_fig('routeana_nodesdensity')
+
+ def plot_lowpriorityshare(self):
+- print 'plot_lowpriorityshare'
++ print('plot_lowpriorityshare')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -2600,7 +2600,7 @@
+ self.save_fig('routeana_lowpriorityshare')
+
+ def plot_exclusiveshare(self):
+- print 'plot_exclusiveshare'
++ print('plot_exclusiveshare')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -2637,7 +2637,7 @@
+ self.save_fig('routeana_exclusiveshare')
+
+ def plot_mixshare(self):
+- print 'plot_mixshare'
++ print('plot_mixshare')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -2675,7 +2675,7 @@
+ self.save_fig('routeana_mixshare')
+
+ def plot_lengthdistrib_by_class(self):
+- print 'plot_lengthdistrib_by_class'
++ print('plot_lengthdistrib_by_class')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -2700,7 +2700,7 @@
+ stds_shortest = np.zeros(n_class, dtype=np.float32)
+ xticklabels = []
+ ratiolabels = []
+- for dist_lower, dist_upper, i in zip(dists_class[:-1], dists_class[1:], range(n_class)):
++ for dist_lower, dist_upper, i in zip(dists_class[:-1], dists_class[1:], list(range(n_class))):
+ xticklabels.append('%d - %d' % (float(dist_lower)/1000, float(dist_upper)/1000))
+ inds = np.logical_and(dists_match > dist_lower, dists_match < dist_upper)
+ means_match[i] = np.mean(dists_match[inds])
+@@ -2716,11 +2716,11 @@
+ ratiolabel = '%d%%' % (means_shortest[i]/means_match[i]*100)
+ ratiolabels.append(ratiolabel)
+
+- print ' dists_class_center', dists_class_center
+- print ' means_match', means_match
+- print ' stds_match', stds_match
+- print ' means_shortest', means_shortest
+- print ' stds_shortest', stds_shortest
++ print(' dists_class_center', dists_class_center)
++ print(' means_match', means_match)
++ print(' stds_match', stds_match)
++ print(' means_shortest', means_shortest)
++ print(' stds_shortest', stds_shortest)
+
+ x = np.arange(n_class, dtype=np.float32) # the x locations for the groups
+ width = 0.35 # the width of the bars
+@@ -2779,7 +2779,7 @@
+ time. routesresults_matched.distances.get_value() > 0,
+ # routesresults_matched.distances.get_value()<20000)
+ ))
+- print 'plot_lengthdistrib', len(ids_valid)
++ print('plot_lengthdistrib', len(ids_valid))
+ # print ' ids_valid',ids_valid
+ if len(ids_valid) == 0:
+ return False
+@@ -2808,7 +2808,7 @@
+ return True
+
+ def plot_timedistrib(self):
+- print 'plot_timedistrib'
++ print('plot_timedistrib')
+ fig = self.create_figure()
+ results = self.parent
+ mapmatching = results.parent
+@@ -2856,7 +2856,7 @@
+ return True
+
+ def plot_lengthprob(self):
+- print 'plot_lengthprob'
++ print('plot_lengthprob')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -2901,7 +2901,7 @@
+ self.save_fig('routeana_lengthprob')
+
+ def plot_lengthoverlap(self):
+- print 'plot_lengthoverlap'
++ print('plot_lengthoverlap')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -2933,10 +2933,10 @@
+ self.save_fig('routeana_lengthoverlap')
+
+ def plot_lengthoverlap_fastest(self):
+- print 'plot_lengthoverlap_fastest'
++ print('plot_lengthoverlap_fastest')
+ fig = self.create_figure()
+ results = self.parent
+- print 'dir(results)', dir(results)
++ print('dir(results)', dir(results))
+ routesresults_fastest = results.routesresults_fastest
+ routesresults_matched = results.routesresults_matched
+ edgesresults = results.edgesresults
+@@ -2966,7 +2966,7 @@
+ self.save_fig('routeana_lengthoverlap_fastest')
+
+ def plot_lengthratio(self):
+- print 'plot_lengthratio'
++ print('plot_lengthratio')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -3002,7 +3002,7 @@
+ # non-overlap
+
+ def plot_lengthratio_nonoverlap(self):
+- print 'plot_lengthratio_nonoverlap'
++ print('plot_lengthratio_nonoverlap')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -3041,7 +3041,7 @@
+ self.save_fig('routeana_lengthratio_nonoverlap')
+
+ def plot_tldensity_nonoverlap(self):
+- print 'plot_tldensity_nonoverlap'
++ print('plot_tldensity_nonoverlap')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -3080,7 +3080,7 @@
+ self.save_fig('routeana_tldensity_nonoverlap')
+
+ def plot_nodesdensity_nonoverlap(self):
+- print 'plot_nodesdensity_nonoverlap'
++ print('plot_nodesdensity_nonoverlap')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -3119,7 +3119,7 @@
+ self.save_fig('routeana_nodesdensity_nonoverlap')
+
+ def plot_prioritychangedensity_nonoverlap(self):
+- print 'plot_prioritychangedensity_nonoverlap'
++ print('plot_prioritychangedensity_nonoverlap')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -3159,7 +3159,7 @@
+ self.save_fig('routeana_nodesdensity_nonoverlap')
+
+ def plot_lowpriorityshare_nonoverlap(self):
+- print 'plot_lowpriorityshare_nonoverlap'
++ print('plot_lowpriorityshare_nonoverlap')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -3199,7 +3199,7 @@
+ self.save_fig('routeana_lowpriorityshare_nonoverlap')
+
+ def plot_exclusiveshare_nonoverlap(self):
+- print 'plot_exclusiveshare_nonoverlap'
++ print('plot_exclusiveshare_nonoverlap')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -3239,7 +3239,7 @@
+ self.save_fig('routeana_exclusiveshare_nonoverlap')
+
+ def plot_mixshare_nonoverlap(self):
+- print 'plot_mixshare_nonoverlap'
++ print('plot_mixshare_nonoverlap')
+ fig = self.create_figure()
+ results = self.parent
+ routesresults_shortest = results.routesresults_shortest
+@@ -3295,7 +3295,7 @@
+ self._init_common('ptrouteresultplotter', parent=results, name=name,
+ info=info, logger=logger)
+
+- print 'PtFlowdigramPlotter.__init__', results, self.parent
++ print('PtFlowdigramPlotter.__init__', results, self.parent)
+ attrsman = self.get_attrsman()
+
+ self.id_line = attrsman.add(cm.AttrConf('id_line', kwargs.get('id_line', -1),
+@@ -3369,7 +3369,7 @@
+ self.add_save_options(**kwargs)
+
+ def show(self):
+- print 'show'
++ print('show')
+ # if self.axis is None:
+ self.init_figures()
+ plt.rc('lines', linewidth=self.width_line)
+@@ -3392,7 +3392,7 @@
+ ptlinks = ptlines.get_ptlinks()
+
+ if not self.id_line in ptlines:
+- print 'WARNING: line with ID', self.id_line, 'not found.'
++ print('WARNING: line with ID', self.id_line, 'not found.')
+ return False
+
+ #id_line = ptlines.linenames.get_id_from_index(self.linename)
+@@ -3404,7 +3404,7 @@
+ self.id_line, is_add_similar=self.is_add_similar)
+
+ n_stops = len(ids_stoptuple_line)
+- ax.bar(xrange(n_stops), tripnumbers_line,
++ ax.bar(range(n_stops), tripnumbers_line,
+ width=1.0, bottom=0, align='edge',
+ color=self.color_fill,
+ #linecolor = self.color_outline,
+@@ -3414,7 +3414,7 @@
+ for id_fromstop, id_tostop in ids_stoptuple_line:
+ stopnames.append(ptstops.stopnames_human[id_fromstop])
+ # print ' stopnames',stopnames
+- ax.set_xticks(xrange(n_stops))
++ ax.set_xticks(range(n_stops))
+ ax.set_xticklabels(stopnames)
+
+ #ax.legend(loc='best',shadow=True, fontsize=self.size_labelfont)
+--- tools/contributed/sumopy/plugins/mapmatching/wxgui.py (original)
++++ tools/contributed/sumopy/plugins/mapmatching/wxgui.py (refactored)
+@@ -28,15 +28,15 @@
+ from coremodules.network import routing
+ from coremodules.demand import demand
+
+-import mapmatching
++from . import mapmatching
+
+
+ #import results_mpl as results_mpl
+ try:
+- import results_mpl as results_mpl
++ from . import results_mpl as results_mpl
+ is_mpl = True # we have matplotlib support
+ except:
+- print "WARNING: python matplotlib package not installed, no matplotlib plots."
++ print("WARNING: python matplotlib package not installed, no matplotlib plots.")
+ is_mpl = False
+
+
+@@ -284,7 +284,7 @@
+ and reset widgets. For exampe enable/disable widgets
+ dependent on the availability of data.
+ """
+- print 'MapmatchingWxGui.refresh_widgets'
++ print('MapmatchingWxGui.refresh_widgets')
+ scenario = self.get_scenario()
+ is_refresh = False
+ if self._scenario != scenario:
+@@ -303,7 +303,7 @@
+
+ if is_refresh | self._is_needs_refresh:
+ self._is_needs_refresh = False
+- print ' is_refresh', is_refresh, self._is_needs_refresh
++ print(' is_refresh', is_refresh, self._is_needs_refresh)
+ neteditor = self.get_neteditor()
+ #canvas = self.get_canvas()
+ drawing = self.get_drawing() # canvas.get_drawing()
+@@ -947,7 +947,7 @@
+ """
+ Export edge results to shape file.
+ """
+- print 'on_nodes_to_shapefile'
++ print('on_nodes_to_shapefile')
+ scenario = self._mapmatching.get_scenario()
+ dirpath = scenario.get_workdirpath()
+ #defaultFile = scenario.get_rootfilename()+'.edgeres.shp'
+@@ -971,7 +971,7 @@
+ """
+ Export GPS points to shapefile.
+ """
+- print 'on_points_to_shapefile'
++ print('on_points_to_shapefile')
+ scenario = self._mapmatching.get_scenario()
+ dirpath = scenario.get_workdirpath()
+ defaultFile = scenario.get_rootfilename()+'.points.shp'
+@@ -1707,7 +1707,7 @@
+ self._mainframe.refresh_moduleguis()
+ self._is_needs_refresh = True
+ self.refresh_widgets()
+- print ' set browser to', self.get_scenario().net.ptstops
++ print(' set browser to', self.get_scenario().net.ptstops)
+ self._mainframe.browse_obj(self.get_scenario().net.ptstops)
+
+ def on_gtfsservicegenerate(self, event=None):
+@@ -1738,7 +1738,7 @@
+ # apply current widget values to scenario instance
+ dlg.apply()
+ dlg.Destroy()
+- print ' set browser to', self.get_scenario().demand.ptlines
++ print(' set browser to', self.get_scenario().demand.ptlines)
+ self._mainframe.browse_obj(self.get_scenario().demand.ptlines)
+ # self._mainframe.refresh_moduleguis()
+ #self._is_needs_refresh = True
+--- tools/contributed/sumopy/plugins/prt/__init__.py (original)
++++ tools/contributed/sumopy/plugins/prt/__init__.py (refactored)
+@@ -18,12 +18,12 @@
+
+ __version__ = "0.0"
+
+-print 'init', __name__
++print('init', __name__)
+
+
+ def get_wxgui():
+ # try:
+- from wxgui import WxGui
++ from .wxgui import WxGui
+ return WxGui(__name__)
+ # except:
+ # return None
+--- tools/contributed/sumopy/plugins/prt/prt.py (original)
++++ tools/contributed/sumopy/plugins/prt/prt.py (refactored)
+@@ -72,7 +72,7 @@
+ ids_veh_entered_sumo = np.array(list(ids_veh_sumo_current.difference(ids_veh_sumo_before)), dtype=np.object)
+ n_entered = len(ids_veh_entered_sumo)
+ positions = np.zeros(n_entered, dtype=np.float32)
+- for i, id_veh_sumo in zip(xrange(n_entered), ids_veh_entered_sumo):
++ for i, id_veh_sumo in zip(range(n_entered), ids_veh_entered_sumo):
+ positions[i] = traci.vehicle.getLanePosition(id_veh_sumo)
+
+ return list(ids_veh_entered_sumo[positions.argsort()])[::-1]
+@@ -148,7 +148,7 @@
+ ])
+
+ def make(self, id_detectoredge=None, **kwargs):
+- print 'make', kwargs
++ print('make', kwargs)
+ # print ' ids_shuntedge',kwargs.get('ids_shuntedge',None),type(kwargs.get('ids_shuntedge',None)[0])
+ id_comp = self.add_row(ids_shuntedges=kwargs.get('ids_shuntedge', None),
+ ids_detectoredge=id_detectoredge
+@@ -158,13 +158,13 @@
+ return id_comp
+
+ def update(self, id_comp):
+- print 'update id_comp', id_comp
++ print('update id_comp', id_comp)
+ edges = self.get_scenario().net.edges
+
+ self.ids_detectoredge[id_comp] = edges.get_incoming(self.ids_shuntedges[id_comp][0])[0]
+
+ def update_all(self):
+- print 'update_all'
++ print('update_all')
+ for id_comp in self.get_ids():
+ self.update(id_comp)
+
+@@ -172,7 +172,7 @@
+ return self.parent.get_scenario()
+
+ def prepare_sim(self, process):
+- print 'Compressors.prepare_sim'
++ print('Compressors.prepare_sim')
+ net = self.get_scenario().net
+ nodes = net.nodes
+ edges = net.edges
+@@ -227,7 +227,7 @@
+ queues_alloc = n_shunts*[None]
+ capacities = n_shunts*[None]
+
+- for i, length_edge in zip(range(n_shunts), edges.lengths[ids_shuntedge]):
++ for i, length_edge in zip(list(range(n_shunts)), edges.lengths[ids_shuntedge]):
+ capacities[i] = max(2, int((length_edge-30.0)/(self.length_veh+0.5)))
+ queues[i] = []
+ queues_alloc[i] = []
+@@ -248,8 +248,8 @@
+
+ def process_step(self, process):
+ simtime = process.simtime
+- print 79*'_'
+- print 'Compressors.process_step at', simtime
++ print(79*'_')
++ print('Compressors.process_step at', simtime)
+ net = self.get_scenario().net
+ edges = net.edges
+ vehicles = self.parent.prtvehicles
+@@ -284,11 +284,11 @@
+ id_detectedge_sumo, ids_veh_detect_sumo)
+
+ if 0:
+- print ' id_detectedge_sumo', id_detectedge_sumo
+- print ' ids_veh_detect_sumo', ids_veh_detect_sumo
+- print ' ids_veh_new_sumo', ids_veh_new_sumo
+- print ' ids_veh_entered_sumo=', ids_veh_entered_sumo
+- print ' ids_veh_left_sumo=', ids_veh_left_sumo
++ print(' id_detectedge_sumo', id_detectedge_sumo)
++ print(' ids_veh_detect_sumo', ids_veh_detect_sumo)
++ print(' ids_veh_new_sumo', ids_veh_new_sumo)
++ print(' ids_veh_entered_sumo=', ids_veh_entered_sumo)
++ print(' ids_veh_left_sumo=', ids_veh_left_sumo)
+
+ if len(ids_veh_entered_sumo) > 0:
+
+@@ -339,7 +339,7 @@
+ # print ' no queue with target or specific queue is full, search for a new queue'
+
+ is_found_queue = False
+- for ind_queue, queue in zip(range(1, n_queues), queues[1:]):
++ for ind_queue, queue in zip(list(range(1, n_queues)), queues[1:]):
+ if len(queue) == 0:
+ is_found_queue = True
+ break
+@@ -384,14 +384,14 @@
+ capacity, id_edge_sumo_target,\
+ id_shuntedge_sumo, releasetime_queue\
+ in zip(
+- range(n_queues), queues, queues_alloc,
++ list(range(n_queues)), queues, queues_alloc,
+ capacities, ids_edge_sumo_target,
+ edges.ids_sumo[ids_shuntedge], releasetime_queues):
+ if 0:
+- print ' OOOO shunt %s --> target %s' % (id_shuntedge_sumo, id_edge_sumo_target)
+- print ' simtime-releasetime_queue', simtime-releasetime_queue
+- print ' queue', queue, id(queue)
+- print ' queue_alloc', queue_alloc
++ print(' OOOO shunt %s --> target %s' % (id_shuntedge_sumo, id_edge_sumo_target))
++ print(' simtime-releasetime_queue', simtime-releasetime_queue)
++ print(' queue', queue, id(queue))
++ print(' queue_alloc', queue_alloc)
+
+ # check if allocated arrived
+ ids_veh_arrived = []
+@@ -472,7 +472,7 @@
+ ])
+
+ def prepare_sim(self, process):
+- print 'Decompressors.prepare_sim'
++ print('Decompressors.prepare_sim')
+ net = self.get_scenario().net
+ nodes = net.nodes
+ edges = net.edges
+@@ -528,7 +528,7 @@
+ queues_alloc = n_shunts*[None]
+ capacities = n_shunts*[None]
+ ids_targetedges_sumo = n_shunts*[None]
+- for i, length_edge in zip(range(n_shunts), edges.lengths[ids_shuntedge]):
++ for i, length_edge in zip(list(range(n_shunts)), edges.lengths[ids_shuntedge]):
+ capacities[i] = int((length_edge-25.0)/(self.length_veh+0.5))
+ queues[i] = []
+ queues_alloc[i] = []
+@@ -551,8 +551,8 @@
+
+ def process_step(self, process):
+ simtime = process.simtime
+- print 79*'_'
+- print 'Deompressors.process_step at', simtime
++ print(79*'_')
++ print('Deompressors.process_step at', simtime)
+ net = self.get_scenario().net
+ edges = net.edges
+ vehicles = self.parent.prtvehicles
+@@ -586,11 +586,11 @@
+
+ ids_veh_sumo = set(traci.edge.getLastStepVehicleIDs(id_detectedge_sumo))
+ if 0:
+- print ' id_detectedge_sumo', id_detectedge_sumo
+- print ' ids_veh_detect_sumo', ids_veh_detect_sumo, ids_veh_detect_sumo != ids_veh_sumo
+- print ' ids_veh_sumo=', ids_veh_sumo
++ print(' id_detectedge_sumo', id_detectedge_sumo)
++ print(' ids_veh_detect_sumo', ids_veh_detect_sumo, ids_veh_detect_sumo != ids_veh_sumo)
++ print(' ids_veh_sumo=', ids_veh_sumo)
+ ids_veh_sumo_raw = traci.edge.getLastStepVehicleIDs(id_detectedge_sumo)
+- print ' ids_veh_sumo_raw=', ids_veh_sumo_raw
++ print(' ids_veh_sumo_raw=', ids_veh_sumo_raw)
+
+ if ids_veh_detect_sumo != ids_veh_sumo:
+ # there are new vehicles
+@@ -601,12 +601,12 @@
+ ids_veh_entered = vehicles.get_ids_from_ids_sumo(ids_veh_entered_sumo)
+
+ if 0:
+- print ' ids_veh_entered', ids_veh_entered, type(ids_veh_entered)
++ print(' ids_veh_entered', ids_veh_entered, type(ids_veh_entered))
+ # print ' poss',poss
+- print ' ids_veh_entered_sumo', ids_veh_entered_sumo
+- print ' ids_leader', vehicles.ids_leader[ids_veh_entered]
+- print ' ids_follower', vehicles.ids_follower[ids_veh_entered]
+- print ' lengths_plat', vehicles.lengths_plat[ids_veh_entered]
++ print(' ids_veh_entered_sumo', ids_veh_entered_sumo)
++ print(' ids_leader', vehicles.ids_leader[ids_veh_entered])
++ print(' ids_follower', vehicles.ids_follower[ids_veh_entered])
++ print(' lengths_plat', vehicles.lengths_plat[ids_veh_entered])
+
+ for id_veh_entered, id_veh_entered_sumo, id_leader, length_plat\
+ in zip(ids_veh_entered, ids_veh_entered_sumo,
+@@ -624,7 +624,7 @@
+
+ is_found_queue = False
+ costs = np.zeros(n_queues, dtype=np.float32)
+- for ind_queue, queue, is_avail, capa in zip(range(n_queues), queues, are_queue_avail, capacities):
++ for ind_queue, queue, is_avail, capa in zip(list(range(n_queues)), queues, are_queue_avail, capacities):
+
+ dl = (capa - len(queue)) * self.length_veh - 2*length_plat
+ # print ' ceck queue %d with capa %d, len = %d, dl=%d'%(ind_queue,capa,len(queue),dl)
+@@ -658,7 +658,7 @@
+ # shunt it to the same edge as its leader
+ id_targetedge_sumo = traci.vehicle.getRoute(id_veh_entered_sumo)[-1]
+ id_platoonleader = vehicles.get_platoonleader(id_leader)
+- for ind_queue, queue, capa_queue, in zip(range(n_queues), queues, capacities):
++ for ind_queue, queue, capa_queue, in zip(list(range(n_queues)), queues, capacities):
+ if id_platoonleader in queue:
+ # print ' found id_platoonleader prt.%d of prt.%d at queue %d'%(id_platoonleader,id_veh_entered,ind_queue)
+ self._alloc_queue_follower(
+@@ -689,16 +689,16 @@
+ ids_targetedge_sumo, capacity,\
+ id_shuntedge_sumo, releasetime_queue\
+ in zip(
+- range(n_queues), queues, queues_alloc,
++ list(range(n_queues)), queues, queues_alloc,
+ ids_targetedges_sumo, capacities,
+ edges.ids_sumo[ids_shuntedge], releasetime_queues):
+ if 0:
+- print ' QQQQQQQQQQQ shunt %s ' % (id_shuntedge_sumo)
+- print ' simtime-releasetime_queue', simtime-releasetime_queue, (simtime - releasetime_queue > self.time_accumulation_max.get_value()), (simtime - self.releasetimes[id_comp] > 10)
+- print ' queue', queue, id(queue)
+- print ' ids_targetedge_sumo', ids_targetedge_sumo
+- print ' queue_alloc', queue_alloc
+- print ' releasetime_queue', releasetime_queue, simtime - releasetime_queue, simtime - releasetime_queue > self.time_accumulation_max.get_value()
++ print(' QQQQQQQQQQQ shunt %s ' % (id_shuntedge_sumo))
++ print(' simtime-releasetime_queue', simtime-releasetime_queue, (simtime - releasetime_queue > self.time_accumulation_max.get_value()), (simtime - self.releasetimes[id_comp] > 10))
++ print(' queue', queue, id(queue))
++ print(' ids_targetedge_sumo', ids_targetedge_sumo)
++ print(' queue_alloc', queue_alloc)
++ print(' releasetime_queue', releasetime_queue, simtime - releasetime_queue, simtime - releasetime_queue > self.time_accumulation_max.get_value())
+ # here we could also test timeout conditions
+ if (simtime - self.releasetimes[id_comp] > self.time_release_min.get_value()) & (simtime - releasetime_queue > self.time_accumulation_max.get_value()):
+ # if (simtime - self.releasetimes[id_comp]> self.time_release_min.get_value()):
+@@ -726,7 +726,7 @@
+
+ if len_queue > ind_pl+1:
+
+- for i, id_veh in zip(range(ind_pl+1, len_queue), queue[ind_pl+1:]):
++ for i, id_veh in zip(list(range(ind_pl+1, len_queue)), queue[ind_pl+1:]):
+ # print ' check prt.%d with leader prt.%d'%(id_veh,vehicles.ids_leader[id_veh])
+ if vehicles.ids_leader[id_veh] != -1:
+ # print ' real lead prt.%d qlead prt.%d | plat lead prt.%d plat qlead prt.%d '%(vehicles.ids_leader[id_veh],queue[i-1],vehicles.get_platoonleader(id_veh),id_veh_arrived)
+@@ -926,7 +926,7 @@
+ """
+ Make merge node database from network.
+ """
+- print 'Mergenodes.make_from_net'
++ print('Mergenodes.make_from_net')
+ self.clear()
+ id_prtmode = self.parent.id_prtmode
+
+@@ -947,9 +947,9 @@
+ ids = compressors.get_ids()
+ for id_unit, ids_edge in zip(ids, compressors.ids_shuntedges[ids]):
+ # put in all shunts except for the bypass
+- print ' bypass of compressor', id_unit, '=', ids_edge[0]
++ print(' bypass of compressor', id_unit, '=', ids_edge[0])
+ ids_mainlinedges.add(ids_edge[0])
+- print ' update ids_shuntedges with compressors', ids_edge[1:]
++ print(' update ids_shuntedges with compressors', ids_edge[1:])
+ ids_shuntedges.update(ids_edge[1:])
+
+ # collect decompressornodes, wich will not become entry merges
+@@ -957,12 +957,12 @@
+ ids_node_decompressorout = []
+ for id_unit, ids_edge in zip(ids, decompressors.ids_shuntedges[ids]):
+ # put in all shunts except for the bypass
+- print ' bypass of decompressor', id_unit, '=', ids_edge[0], 'id_tonode', edges.ids_tonode[ids_edge[0]]
++ print(' bypass of decompressor', id_unit, '=', ids_edge[0], 'id_tonode', edges.ids_tonode[ids_edge[0]])
+ ids_mainlinedges.add(ids_edge[0])
+ ids_node_decompressorout.append(edges.ids_tonode[ids_edge[0]])
+- print ' update ids_shuntedges with decompressors', ids_edge[1:]
++ print(' update ids_shuntedges with decompressors', ids_edge[1:])
+ ids_shuntedges.update(ids_edge[1:])
+- print ' ids_node_decompressorout', ids_node_decompressorout
++ print(' ids_node_decompressorout', ids_node_decompressorout)
+ ids_node_compressorout = edges.ids_tonode[list(ids_mainlinedges)]
+ ids_mainlinefromnodes = edges.ids_fromnode[list(ids_mainlinedges)]
+
+@@ -972,7 +972,7 @@
+ # print ' update ids_shuntedges with mainline incoming',edges.get_incoming(id_edge)
+ # ids_shuntedges.update(edges.get_incoming(id_edge))
+
+- print ' ids_shuntedges', ids_shuntedges
++ print(' ids_shuntedges', ids_shuntedges)
+ #ids_ptstop = ptstops.get_ids()
+ #id_mode_prt = self.parent.id_prtmode
+
+@@ -982,7 +982,7 @@
+ #edgelengths = net.edges.lengths
+
+ ids_node = nodes.get_ids()
+- print ' ids_node', ids_node
++ print(' ids_node', ids_node)
+ for id_node, ids_edge_from, ids_edge_to, id_type in zip(
+ ids_node,
+ nodes.ids_incoming[ids_node],
+@@ -993,14 +993,14 @@
+ if True:
+ #
+
+- print 60*'-'
+- print ' check node', id_node, nodes.ids_sumo[id_node], id_type, id_zippertype == id_type
++ print(60*'-')
++ print(' check node', id_node, nodes.ids_sumo[id_node], id_type, id_zippertype == id_type)
+
+ # id merge to be created, for debugging
+ id_merge = -1
+
+ if (ids_edge_from is None):
+- print ' WARNING: isolate node: ids_edge_from,ids_edge_to', ids_edge_from, ids_edge_to
++ print(' WARNING: isolate node: ids_edge_from,ids_edge_to', ids_edge_from, ids_edge_to)
+ pass
+
+ elif (len(ids_edge_from) == 2) & (len(ids_edge_to) == 1):
+@@ -1011,28 +1011,28 @@
+ # check accesslevels
+ id_edge1, id_edge2 = ids_edge_from
+ ids_lane1, ids_lane2 = edges.ids_lanes[ids_edge_from]
+- print ' id_edge1', id_edge1, 'ids_lane1', ids_lane1, self.is_prt_only(ids_lane1, lanes)
+- print ' id_edge2', id_edge2, 'ids_lane2', ids_lane2, self.is_prt_only(ids_lane2, lanes)
++ print(' id_edge1', id_edge1, 'ids_lane1', ids_lane1, self.is_prt_only(ids_lane1, lanes))
++ print(' id_edge2', id_edge2, 'ids_lane2', ids_lane2, self.is_prt_only(ids_lane2, lanes))
+ if self.is_prt_only(ids_lane1, lanes) & self.is_prt_only(ids_lane2, lanes):
+- print ' +PRT merge with 2 PRT lines entering'
++ print(' +PRT merge with 2 PRT lines entering')
+
+ if id_type != id_zippertype:
+- print 'WARNING: PRT network node %d %s is NOT in zipper mode!' % (id_node, nodes.ids_sumo[id_node])
++ print('WARNING: PRT network node %d %s is NOT in zipper mode!' % (id_node, nodes.ids_sumo[id_node]))
+
+ if not ids_shuntedges.isdisjoint(ids_edge_from):
+- print ' one incoming edge is a shunt edge. Detect last shunt node.'
++ print(' one incoming edge is a shunt edge. Detect last shunt node.')
+
+ # TODO: this should be a function of the compressor class
+ id_tonode_out = edges.ids_tonode[ids_edge_to[0]]
+ if id_tonode_out in ids_node_compressorout:
+- print ' output node of compressor => station merge node with output node', id_tonode_out
++ print(' output node of compressor => station merge node with output node', id_tonode_out)
+ # model this node as a platform end node of a station
+ id_merge = self.add_row(ids_node=id_node,
+ ids_nodes_out=[id_tonode_out],
+ are_station=True,
+ )
+ else:
+- print ' compressor internal node'
++ print(' compressor internal node')
+ pass
+
+ # elif not ids_mainlinedges.isdisjoint(ids_edge_from):
+@@ -1046,7 +1046,7 @@
+ # )
+
+ else:
+- print ' regular merge'
++ print(' regular merge')
+ id_node_up1, dist1 = self.search_upstream_merge(id_edge1, edges, lanes, id_prtmode)
+ id_node_up2, dist2 = self.search_upstream_merge(id_edge2, edges, lanes, id_prtmode)
+
+@@ -1068,7 +1068,7 @@
+ #al_in = lanes.get_accesslevel(edges.ids_lanes[id_edge_from], id_prtmode)
+ #is_prt_in = lanes.ids_modes_allow[edges.ids_lanes[id_edge_from]] == id_prtmode
+ is_prt_in = self.is_prt_only(ids_lane_in, lanes)
+- print ' one in, 2 out => diverge node, access is_prt_in', is_prt_in, 'is_platform_in', self.is_platform(ids_lane_in, lanes)
++ print(' one in, 2 out => diverge node, access is_prt_in', is_prt_in, 'is_platform_in', self.is_platform(ids_lane_in, lanes))
+
+ # if id_edge_from in ids_detectoredges:
+ # print ' fromnode is a detectoredge of a compressor'
+@@ -1083,7 +1083,7 @@
+ # check if node is outgoing node at a station
+ if 0: # no longer considered
+ if is_prt_in & (id_node in ids_mainlinefromnodes):
+- print ' Diverge node in front of a compressor/decompressorr.'
++ print(' Diverge node in front of a compressor/decompressorr.')
+ id_node_up, dist = self.search_upstream_merge(id_edge_from, edges, lanes, id_prtmode)
+
+ id_edge1, id_edge2 = ids_edge_to
+@@ -1102,19 +1102,19 @@
+ )
+
+ if self.is_platform(ids_lane_in, lanes):
+- print ' mixed access level of incoming edge, check for platform exit node'
++ print(' mixed access level of incoming edge, check for platform exit node')
+
+ id_edge1, id_edge2 = ids_edge_to
+ ids_lane1, ids_lane2 = edges.ids_lanes[ids_edge_to]
+
+ # here we could also decide on the number of lanes
+ # but this may not be robust in the future
+- print ' out id_edge1', id_edge1, 'ids_lane1', ids_lane1, 'is_prt_only', self.is_prt_only(ids_lane1, lanes)
+- print ' out id_edge2', id_edge2, 'ids_lane2', ids_lane2, 'is_prt_only', self.is_prt_only(ids_lane2, lanes)
++ print(' out id_edge1', id_edge1, 'ids_lane1', ids_lane1, 'is_prt_only', self.is_prt_only(ids_lane1, lanes))
++ print(' out id_edge2', id_edge2, 'ids_lane2', ids_lane2, 'is_prt_only', self.is_prt_only(ids_lane2, lanes))
+ # if self.is_prt_only(ids_lane1, lanes) & self.is_prt_only(ids_lane2, lanes):
+ if self.is_prt_only(ids_lane2, lanes):
+
+- print ' Ped exit on outedge 1'
++ print(' Ped exit on outedge 1')
+ #id_node_up, dist = self.search_upstream_merge(id_edge_from, edges, lanes, id_prtmode)
+ ids_node_out = self.search_downstream_merges(
+ id_edge2, edges, lanes, id_prtmode, ids_sinkedge=ids_shuntedges)
+@@ -1126,7 +1126,7 @@
+ )
+
+ elif self.is_prt_only(ids_lane1, lanes):
+- print ' Ped exit on outedge 2'
++ print(' Ped exit on outedge 2')
+ #id_node_up, dist = self.search_upstream_merge(id_edge_from, edges, lanes, id_prtmode)
+ ids_node_out = self.search_downstream_merges(
+ id_edge1, edges, lanes, id_prtmode, ids_sinkedge=ids_shuntedges)
+@@ -1148,16 +1148,16 @@
+
+ id_node_in1 = self.ids_node_in1[id_merge]
+ id_node_in2 = self.ids_node_in2[id_merge]
+- print ' check entry of id_merge', id_merge, 'id_node', self.ids_node[id_merge], ' no decomp', self.ids_node[id_merge] not in ids_node_decompressorout
++ print(' check entry of id_merge', id_merge, 'id_node', self.ids_node[id_merge], ' no decomp', self.ids_node[id_merge] not in ids_node_decompressorout)
+ if (id_node_in1 > -1) & (id_node_in2 > -1)\
+ & (self.ids_node[id_merge] not in ids_node_decompressorout):
+
+- print ' id_node_in1', self.ids_node_in1[id_merge], nodes.ids_sumo[self.ids_node_in1[id_merge]], self.ids_node.has_index(self.ids_node_in1[id_merge])
+- print ' id_node_in2', self.ids_node_in2[id_merge], nodes.ids_sumo[self.ids_node_in2[id_merge]], self.ids_node.has_index(self.ids_node_in2[id_merge])
++ print(' id_node_in1', self.ids_node_in1[id_merge], nodes.ids_sumo[self.ids_node_in1[id_merge]], self.ids_node.has_index(self.ids_node_in1[id_merge]))
++ print(' id_node_in2', self.ids_node_in2[id_merge], nodes.ids_sumo[self.ids_node_in2[id_merge]], self.ids_node.has_index(self.ids_node_in2[id_merge]))
+ if 1:
+ id_merge_in1 = self.ids_node.get_id_from_index(self.ids_node_in1[id_merge])
+ id_merge_in2 = self.ids_node.get_id_from_index(self.ids_node_in2[id_merge])
+- print ' station check id_merge', id_merge, 'id_merge_in1', id_merge_in1, 'station', self.are_station[id_merge_in1], 'id_merge_in2', id_merge_in2, 'station', self.are_station[id_merge_in2]
++ print(' station check id_merge', id_merge, 'id_merge_in1', id_merge_in1, 'station', self.are_station[id_merge_in1], 'id_merge_in2', id_merge_in2, 'station', self.are_station[id_merge_in2])
+
+ if self.are_station[id_merge_in2]:
+ self.are_entry[id_merge] = True
+@@ -1183,7 +1183,7 @@
+ return self.parent.get_scenario()
+
+ def prepare_sim(self, process):
+- print 'Mergenodes.prepare_sim'
++ print('Mergenodes.prepare_sim')
+ net = self.get_scenario().net
+ nodes = net.nodes
+ edges = net.edges
+@@ -1274,8 +1274,8 @@
+
+ def process_step(self, process):
+ simtime = process.simtime
+- print 79*'_'
+- print 'Mergenodes.process_step at', simtime
++ print(79*'_')
++ print('Mergenodes.process_step at', simtime)
+ net = self.get_scenario().net
+ vehicles = self.parent.prtvehicles
+ ids = self.get_ids()
+@@ -1287,8 +1287,8 @@
+ self.ids_vehs_out_sumo[ids],
+ self.are_entry[ids],
+ ):
+- print ' '+60*'.'
+- print ' process id_merge', id_merge, ',id_node', id_node, net.nodes.ids_sumo[id_node]
++ print(' '+60*'.')
++ print(' process id_merge', id_merge, ',id_node', id_node, net.nodes.ids_sumo[id_node])
+
+ ####
+ debug = 0 # id_merge in [3,4]
+@@ -1297,14 +1297,14 @@
+ ###
+
+ if debug > 0:
+- print ' ids_vehs_merged_sumo', self.ids_vehs_merged_sumo[id_merge]
++ print(' ids_vehs_merged_sumo', self.ids_vehs_merged_sumo[id_merge])
+
+ # check for new vehicle arrivals/departures
+ ids_veh_sumo = set(traci.edge.getLastStepVehicleIDs(id_edge_out))
+
+ if debug:
+- print ' ids_veh_sumo_prev=', ids_veh_out_sumo
+- print ' ids_veh_sumo=', ids_veh_sumo
++ print(' ids_veh_sumo_prev=', ids_veh_out_sumo)
++ print(' ids_veh_sumo=', ids_veh_sumo)
+
+ if ids_veh_out_sumo != ids_veh_sumo:
+
+@@ -1315,7 +1315,7 @@
+ ids_veh_entered = vehicles.get_ids_from_ids_sumo(ids_veh_entered_sumo)
+ #ids_veh_left = vehicles.get_ids_from_ids_sumo(list(ids_veh_sumo_prev.difference(ids_veh_sumo)))
+ if debug > 0:
+- print ' ids_veh_entered', ids_veh_entered, type(ids_veh_entered)
++ print(' ids_veh_entered', ids_veh_entered, type(ids_veh_entered))
+ # print ' ids_veh_entered_sumo',ids_veh_entered_sumo
+ # print ' ids_leader',vehicles.ids_leader[ids_veh_entered]
+
+@@ -1338,13 +1338,13 @@
+
+ id_veh_sumo = ids_veh_entered_sumo[ind_entered]
+ if debug > 0:
+- print ' >>exiting vehicle', id_veh_sumo, 'is_leader', vehicles.ids_leader[id_veh] == -1, 'ids_node_out', ids_node_out, 'ids_merge_out', ids_merge_out
++ print(' >>exiting vehicle', id_veh_sumo, 'is_leader', vehicles.ids_leader[id_veh] == -1, 'ids_node_out', ids_node_out, 'ids_merge_out', ids_merge_out)
+
+ # print ' route_sumo',route_sumo
+
+ if ids_node_out is not None:
+ if debug > 0:
+- print ' check which out mergenode are on the current route of the vehicle'
++ print(' check which out mergenode are on the current route of the vehicle')
+
+ # exit from previous merge
+ # if debug:
+@@ -1371,23 +1371,23 @@
+ mergeind = np.argmin(routeinds)
+
+ if debug > 0:
+- print ' route_sumo', route_sumo
+- print ' routeinds', routeinds, 'downstream merge', routeinds[mergeind] < INFINT
+- print ' ids_edge_mergeout_sumo', ids_edge_mergeout_sumo
+- print ' mergeind,routeinds', mergeind, routeinds
+- print ' ids_merge_out[mergeind]', ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind]
++ print(' route_sumo', route_sumo)
++ print(' routeinds', routeinds, 'downstream merge', routeinds[mergeind] < INFINT)
++ print(' ids_edge_mergeout_sumo', ids_edge_mergeout_sumo)
++ print(' mergeind,routeinds', mergeind, routeinds)
++ print(' ids_merge_out[mergeind]', ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind])
+
+ if routeinds[mergeind] < INFINT:
+ if debug > 0:
+- print ' merge %d is on the route is_entry' % (ids_merge_out[mergeind])
++ print(' merge %d is on the route is_entry' % (ids_merge_out[mergeind]))
+ if self.are_entry[ids_merge_out[mergeind]]:
+ if debug > 0:
+- print ' call enter_veh_entry'
++ print(' call enter_veh_entry')
+ self.enter_veh_entry(
+ id_veh, id_veh_sumo, id_merge, ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind], vehicles, debug=debug)
+ else:
+ if debug > 0:
+- print ' call enter_veh'
++ print(' call enter_veh')
+ self.enter_veh(
+ id_veh, id_veh_sumo, id_merge, ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind], vehicles, debug=debug)
+ else:
+@@ -1399,7 +1399,7 @@
+
+ else:
+ if debug:
+- print ' ids_node_out is None means that there is a station or compressor'
++ print(' ids_node_out is None means that there is a station or compressor')
+ # shunt edges behind.
+ # completely disconnect from all merge controlls
+ # including ghosts
+@@ -1414,7 +1414,7 @@
+ if is_entry:
+ self.process_step_entry(id_merge, vehicles, debug)
+ if 0:
+- print '========check mergeprocess'
++ print('========check mergeprocess')
+ for id_merge, id_node_sumo, ids_veh_merged_sumo, ids_veh_merged in\
+ zip(ids,
+ net.nodes.ids_sumo[self.ids_node[ids]],
+@@ -1422,11 +1422,11 @@
+ self.ids_vehs_merged[ids]
+ ):
+
+- print ' ', id_merge, id_node_sumo, ids_veh_merged_sumo
++ print(' ', id_merge, id_node_sumo, ids_veh_merged_sumo)
+ # print ' ids_veh_merged',ids_veh_merged
+
+ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_control=False, debug=0):
+- print 'exit_veh id_veh %s, id_merge_from %d ' % (id_veh_sumo, id_merge_from), 'entry', self.are_entry[id_merge_from]
++ print('exit_veh id_veh %s, id_merge_from %d ' % (id_veh_sumo, id_merge_from), 'entry', self.are_entry[id_merge_from])
+ # print ' check for platooned vehicles:'
+ # vehicles.get_platoon(id_veh)
+ # in id_merge_from: take vehicle out of merged queue and input queue
+@@ -1451,8 +1451,8 @@
+ id_veh_tail = vehicles.get_platoontail(id_veh) # get last in platoon
+ vehicles.del_ghost(id_veh_behind, id_veh_tail)
+ if debug > 0:
+- print ' del ghost from veh', id_veh_behind, 'ghost', id_veh_tail
+- print ' check ghosts:', vehicles.ids_ghosts[id_veh_behind]
++ print(' del ghost from veh', id_veh_behind, 'ghost', id_veh_tail)
++ print(' check ghosts:', vehicles.ids_ghosts[id_veh_behind])
+ # is there a vehicle in fron of the removed vehicle
+ # this happens if a vehicle is interactively deviated
+ if ind_pos > 0:
+@@ -1477,26 +1477,26 @@
+ self.ids_vehs_merged_sumo[id_merge_from].pop(ind_pos) # remove(id_veh_sumo)
+ self.lineinds_vehs_merged[id_merge_from].pop(ind_pos)
+ if debug > 0:
+- print ' vehicle has been on line index', lineind
++ print(' vehicle has been on line index', lineind)
+ # remove vehicle from line buffers
+ if lineind == 1:
+ self.ids_vehs_in1[id_merge_from].remove(id_veh) # pop()
+ self.ids_vehs_in1_sumo[id_merge_from].remove(id_veh_sumo) # .pop()
+ if self.are_entry[id_merge_from]:
+ if debug > 0:
+- print ' vehicle is involved in entry merge processes?', self.vehicles_mains[id_merge_from].has_key(id_veh)
+- if self.vehicles_mains[id_merge_from].has_key(id_veh):
++ print(' vehicle is involved in entry merge processes?', id_veh in self.vehicles_mains[id_merge_from])
++ if id_veh in self.vehicles_mains[id_merge_from]:
+ #
+ #id_veh_entry = self.vehicles_mains[id_merge_from][id_veh]
+
+ # TODO: this is still a lousy method, vehicles_mains neds to be improved
+- for id_veh_entry, state in zip(self.vehicles_entries[id_merge_from].keys(), self.vehicles_entries[id_merge_from].values()):
++ for id_veh_entry, state in zip(list(self.vehicles_entries[id_merge_from].keys()), list(self.vehicles_entries[id_merge_from].values())):
+ #state = self.vehicles_entries[id_merge_from][id_veh_entry]
+ # print ' state before',state
+- if state.has_key('id_veh_infront'):
++ if 'id_veh_infront' in state:
+ if state['id_veh_infront'] == id_veh:
+ del state['id_veh_infront']
+- if state.has_key('id_veh_behind'):
++ if 'id_veh_behind' in state:
+ if state['id_veh_behind'] == id_veh:
+ del state['id_veh_behind']
+ # print ' state after',state
+@@ -1509,7 +1509,7 @@
+
+ if self.are_entry[id_merge_from]:
+ if debug > 0:
+- print ' del veh prt.%s from vehicles_entries' % id_veh
++ print(' del veh prt.%s from vehicles_entries' % id_veh)
+ del self.vehicles_entries[id_merge_from][id_veh]
+ else:
+ pass
+@@ -1524,16 +1524,16 @@
+ # just be sure that the vehicle is not in any queue
+ # but actually this cannot happen
+ if id_veh in self.ids_vehs_in1[id_merge_from]:
+- print 'WARNING in exit_veh: new veh %d should not be in inqueue 1' % id_veh
++ print('WARNING in exit_veh: new veh %d should not be in inqueue 1' % id_veh)
+ self.ids_vehs_in1[id_merge_from].remove(id_veh)
+ self.ids_vehs_in1_sumo[id_merge_from].remove(id_veh_sumo)
+
+ if id_veh in self.ids_vehs_in2[id_merge_from]:
+- print 'WARNING in exit_veh: new veh %d should not be in inqueue 2' % id_veh
++ print('WARNING in exit_veh: new veh %d should not be in inqueue 2' % id_veh)
+ self.ids_vehs_in2[id_merge_from].remove(id_veh)
+ self.ids_vehs_in2_sumo[id_merge_from].remove(id_veh_sumo)
+
+- if self.vehicle_to_merge.has_key(id_veh):
++ if id_veh in self.vehicle_to_merge:
+ del self.vehicle_to_merge[id_veh]
+
+ if is_remove_from_control:
+@@ -1541,7 +1541,7 @@
+ vehicles.del_all_ghosts(id_veh)
+
+ def exit_veh_forced(self, id_veh, id_veh_sumo, vehicles):
+- if self.vehicle_to_merge.has_key(id_veh):
++ if id_veh in self.vehicle_to_merge:
+ # exit vehicle from respective merge
+ self.exit_veh(id_veh, id_veh_sumo, self.vehicle_to_merge[id_veh], vehicles, is_remove_from_control=True)
+ else:
+@@ -1555,24 +1555,24 @@
+ #dist_diff = dist_max-dist_min+10.0
+ if np.all([dist1_min, dist1_max, dist2_min, dist2_max]) > 0:
+ f = float(pos_max)/dist_max
+- print '________________________'
+- print 'vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max)
++ print('________________________')
++ print('vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max))
+ pos_min = int(dist1_min*f)
+ pos_max = int(dist1_max*f)
+- print max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|'
++ print(max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|')
+
+ pos_min = int(dist2_min*f)
+ pos_max = int(dist2_max*f)
+- print max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|'
+- print 'vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max)
+- print '________________________'
++ print(max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|')
++ print('vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max))
++ print('________________________')
+ else:
+- print 'WARNING: some negative distances:'
+- print 'vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max)
+- print 'vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max)
++ print('WARNING: some negative distances:')
++ print('vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max))
++ print('vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max))
+
+ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_merge_sumo, vehicles, debug=0):
+- print 'enter_veh id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to)
++ print('enter_veh id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to))
+
+ # in id_merge_from: take vehicle out of merged queue and input queue
+
+@@ -1610,7 +1610,7 @@
+ if indpos == -1:
+ # vehicle is new and must be merged into ids_vehs_merged
+ if debug > 0:
+- print ' merge veh %d arriving from in %d at dist %.2fm' % (id_veh, lineind, dist_tomerge_head_new)
++ print(' merge veh %d arriving from in %d at dist %.2fm' % (id_veh, lineind, dist_tomerge_head_new))
+
+ ids_vehs_merged = self.ids_vehs_merged[id_merge_to]
+ ids_vehs_merged_sumo = self.ids_vehs_merged_sumo[id_merge_to]
+@@ -1624,7 +1624,7 @@
+ # print ' lineinds_vehs_merged[%d]'%id_merge_to,lineinds_vehs_merged
+ if (ind_insert == 0) | self.are_station[id_merge_to]:
+ if debug > 0:
+- print ' new vehicle is the only vehicle or station', ind_insert, self.are_station[id_merge_to]
++ print(' new vehicle is the only vehicle or station', ind_insert, self.are_station[id_merge_to])
+
+ # vehicles heading toward a station merge are not
+ # really merged because only one incoming line
+@@ -1642,7 +1642,7 @@
+ dist_tomerge_tail_new = get_traci_distance(id_veh_tail_new_sumo, id_edge_merge_sumo, 3.0)
+ if debug > 0:
+ # print ' new veh %d arriving from in %d at dist head %.2f /__| tail %.2fm'%(id_veh,lineind,dist_tomerge_head_new,dist_tomerge_tail_new)
+- print ' ids_vehs_merged_sumo', ids_vehs_merged_sumo
++ print(' ids_vehs_merged_sumo', ids_vehs_merged_sumo)
+ for id_veh_merged, id_veh_merged_sumo in zip(ids_vehs_merged[::-1], ids_vehs_merged_sumo[::-1]):
+ dist_tomerge_head = get_traci_distance(id_veh_merged_sumo, id_edge_merge_sumo, 3.0)
+ #stoppeddist_tomerge = dist-0.5/self.decel*get_traci_velocity(id_veh_merged_sumo)**2+vehicles.lengths_plat[id_veh]
+@@ -1679,11 +1679,11 @@
+ if is_insert:
+ # at least one vehicle is in front
+ if debug > 0:
+- print ' insert veh %d behind veh %d, index %d' % (id_veh, id_veh_merged, ind_insert)
++ print(' insert veh %d behind veh %d, index %d' % (id_veh, id_veh_merged, ind_insert))
+ # send control info to involved vehicles
+ if ind_insert == len(ids_vehs_merged):
+ if debug > 0:
+- print ' appended vehicle after veh', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail
++ print(' appended vehicle after veh', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail)
+ # V
+ # |
+ # G ind_insert-1
+@@ -1698,7 +1698,7 @@
+ elif ind_insert > 0:
+ # there is at least 1 other veh in front
+ if debug > 0:
+- print ' vehicle will be inserted in front of', ids_vehs_merged_sumo[ind_insert], 'and in behind', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail
++ print(' vehicle will be inserted in front of', ids_vehs_merged_sumo[ind_insert], 'and in behind', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail)
+ # G1
+ # |
+ # V
+@@ -1718,7 +1718,7 @@
+
+ else:
+ if debug > 0:
+- print ' prepend veh %d in front of veh %d, first index %d' % (id_veh, id_veh_merged, ind_insert)
++ print(' prepend veh %d in front of veh %d, first index %d' % (id_veh, id_veh_merged, ind_insert))
+ # is vehicle and ghost in the same input line?
+ if lineinds_vehs_merged[ind_insert] != lineind:
+ id_veh_behind = ids_vehs_merged[ind_insert] # last veh in queue
+@@ -1738,7 +1738,7 @@
+ # lineinds_vehs_merged[0] = lineind
+
+ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_merge_sumo, vehicles, debug=0):
+- print 'enter_veh_entry id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to)
++ print('enter_veh_entry id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to))
+
+ # in id_merge_from: take vehicle out of merged queue and input queue
+
+@@ -1770,8 +1770,8 @@
+ if lineind == 1:
+ # from line 1 (main line)
+ if debug > 0:
+- print ' Detected veh', id_veh_sumo, 'on mainline. Is new', indpos == -1
+- print ' check for platooned vehicles:'
++ print(' Detected veh', id_veh_sumo, 'on mainline. Is new', indpos == -1)
++ print(' check for platooned vehicles:')
+ vehicles.get_platoon(id_veh)
+
+ id_edge_out_sumo = self.ids_merge_to_ids_edge_out_sumo[id_merge_to]
+@@ -1803,7 +1803,7 @@
+ # there is an approaching vehicle on entry line
+ if state2['status'] == 'accelerate':
+ # vehicle in acceleration mode
+- if state2.has_key('id_veh_behind'):
++ if 'id_veh_behind' in state2:
+ # accelerating vehicle has already a vehicle
+ # in front of which to merge
+ # => look at last vehicle
+@@ -1816,7 +1816,7 @@
+ state2['id_veh_behind'] = id_veh
+
+ if state2['status'] == 'sync':
+- if state2.has_key('id_veh_behind'):
++ if 'id_veh_behind' in state2:
+ # accelerating vehicle has already a vehicle
+ # in front of which to merge
+ # => look at last vehicle
+@@ -1845,12 +1845,12 @@
+ elif lineind == 2:
+ # from line 2 (entry line)
+ if debug > 0:
+- print ' Detected veh', id_veh_sumo, 'on entry line. Is new', indpos == -1
++ print(' Detected veh', id_veh_sumo, 'on entry line. Is new', indpos == -1)
+
+ self.ids_vehs_in2[id_merge_to].append(id_veh)
+ self.ids_vehs_in2_sumo[id_merge_to].append(id_veh_sumo)
+ if debug > 0:
+- print ' command vehicle to stop and wait further instructions'
++ print(' command vehicle to stop and wait further instructions')
+ #vehicles.control_slow_down(id_veh, speed = 6.0/3.6)
+ #traci.vehicle.setMaxSpeed(id_veh_sumo, 6.0/3.6)
+ # print ' set speed to',traci.vehicle.getMaxSpeed(id_veh_sumo)
+@@ -1861,10 +1861,10 @@
+ # prevent SUMO from reaccelerating vehicle
+ # vehicles.switch_off_control(id_veh)
+ if debug > 0:
+- print ' set veh id_veh prt.%d' % id_veh
++ print(' set veh id_veh prt.%d' % id_veh)
+ self.vehicles_entries[id_merge_to][id_veh] = {'status': 'wait'}
+ if debug > 0:
+- print ' vehicles_entries[', id_merge_to, ']=', self.vehicles_entries[id_merge_to]
++ print(' vehicles_entries[', id_merge_to, ']=', self.vehicles_entries[id_merge_to])
+ #
+ # self.vehicles_mains[id_merge_to][id_veh] = {}# later when used
+
+@@ -1882,13 +1882,13 @@
+ if len(vehicles_entries) == 0:
+ return -1, {'status': 'wait'}
+ else:
+- return vehicles_entries.keys()[0], vehicles_entries.values()[0]
++ return list(vehicles_entries.keys())[0], list(vehicles_entries.values())[0]
+
+ def process_step_entry(self, id_merge, vehicles, debug):
+- print 'process_step_entry id_merge', id_merge
++ print('process_step_entry id_merge', id_merge)
+ if debug > 0:
+- print ' vehicles_entries=', self.vehicles_entries[id_merge]
+- print ' vehicles_mains', self.vehicles_mains[id_merge]
++ print(' vehicles_entries=', self.vehicles_entries[id_merge])
++ print(' vehicles_mains', self.vehicles_mains[id_merge])
+ # print ' self.vehicles_entries',self.vehicles_entries
+ #self.vehicles_entries[id_merge]= OrderedDict()
+ # self.vehicles_mains[id_merge] = OrderedDict()
+@@ -1897,8 +1897,8 @@
+ # for id_veh, state in zip(self.vehicles_entries[id_merge].keys()[::-1],self.vehicles_entries[id_merge].values()[::-1]):
+ # for id_veh, state in self.vehicles_entries.iteritems():
+ # for id_veh, state in zip(self.vehicles_entries[id_merge].keys(),self.vehicles_entries[id_merge].values()):
+- ids_veh_entry = self.vehicles_entries[id_merge].keys()
+- states_veh_entry = self.vehicles_entries[id_merge].values()
++ ids_veh_entry = list(self.vehicles_entries[id_merge].keys())
++ states_veh_entry = list(self.vehicles_entries[id_merge].values())
+ id_edge_out_sumo = self.ids_merge_to_ids_edge_out_sumo[id_merge]
+ ids_veh_in1 = self.ids_vehs_in1[id_merge]
+ time_update = self.time_update.get_value()
+@@ -1914,7 +1914,7 @@
+ ids_vehs_merged_sumo = self.ids_vehs_merged_sumo[id_merge]
+ lineinds_vehs_merged = self.lineinds_vehs_merged[id_merge]
+ if debug > 0:
+- print ' check id_veh_sumo', id_veh_sumo, 'status', state['status'], 'n vehs on main', len(ids_veh_in1)
++ print(' check id_veh_sumo', id_veh_sumo, 'status', state['status'], 'n vehs on main', len(ids_veh_in1))
+ if state['status'] == 'wait':
+ if traci.vehicle.isStopped(id_veh_sumo):
+ # check potential conflict vehicle on main line
+@@ -1922,7 +1922,7 @@
+ n1 = len(ids_veh_in1)
+ if n1 == 0:
+ if debug > 0:
+- print ' main line is empty => accelerate immediately'
++ print(' main line is empty => accelerate immediately')
+ for id_veh_plat in vehicles.get_platoon(id_veh):
+ vehicles.control_speedup(id_veh_plat)
+ state['status'] = 'accelerate'
+@@ -1943,7 +1943,7 @@
+ id_veh1_sumo = ids_veh_in1_sumo[i]
+ id_veh1 = ids_veh_in1[i]
+ if debug > 0:
+- print ' check', id_veh1_sumo # ,'free',id_veh1 not in vehicles_main
++ print(' check', id_veh1_sumo) # ,'free',id_veh1 not in vehicles_main
+
+ if True: # id_veh1 not in vehicles_main:
+
+@@ -1959,9 +1959,9 @@
+ dist_in1, dist_in2,
+ vehicles)
+ if debug > 0:
+- print ' potential veh %s (tail %s)' % (id_veh1_sumo, id_veh1_tail_sumo), 'at pos1_tail=%.1f>p_to=%.1f' % (pos1_tail, p_to), pos1_tail > p_to
+-
+- print ' i=%d, n1=%d' % (i, n1), 'last vehicle on main', i == n1-1, 'more', i < n1-1
++ print(' potential veh %s (tail %s)' % (id_veh1_sumo, id_veh1_tail_sumo), 'at pos1_tail=%.1f>p_to=%.1f' % (pos1_tail, p_to), pos1_tail > p_to)
++
++ print(' i=%d, n1=%d' % (i, n1), 'last vehicle on main', i == n1-1, 'more', i < n1-1)
+
+ #self.print_vehs(id_veh1, id_veh2, dist1_min, dist1_max, dist2_min, dist2_max,lineind1, lineind2, pos_max = 79)
+
+@@ -1972,7 +1972,7 @@
+
+ if i == n1-1: # last vehicle on main
+ if debug > 0:
+- print ' insert id_veh', id_veh_sumo, 'behind id_veh1', id_veh1_sumo, 'the only veh on main'
++ print(' insert id_veh', id_veh_sumo, 'behind id_veh1', id_veh1_sumo, 'the only veh on main')
+ state['id_veh_infront'] = id_veh1
+ vehicles_main[id_veh1] = id_veh # no, it does not get a ghost
+ # vehicles_main[id_veh1] = { 'id_veh':id_veh,
+@@ -1989,7 +1989,7 @@
+ id_veh_behind_sumo = vehicles.ids_sumo[id_veh_behind]
+ pos1 = dist_in1 - get_traci_distance(id_veh_behind_sumo, id_edge_out_sumo, 3.0)
+ if debug > 0:
+- print ' vehicle behind', id_veh_behind_sumo, 'pos=%.1f, p_from=%.1f' % (pos1, p_from), 'ok', pos1 < p_from
++ print(' vehicle behind', id_veh_behind_sumo, 'pos=%.1f, p_from=%.1f' % (pos1, p_from), 'ok', pos1 < p_from)
+ if pos1 < p_from:
+ state['id_veh_infront'] = id_veh1
+ state['id_veh_behind'] = id_veh_behind
+@@ -2008,7 +2008,7 @@
+ elif pos1 < p_from:
+ if i == 0: # first vehicle on main
+ if debug > 0:
+- print ' insert id_veh', id_veh_sumo, 'in front of id_veh1', id_veh1_sumo, 'the only veh on main'
++ print(' insert id_veh', id_veh_sumo, 'in front of id_veh1', id_veh1_sumo, 'the only veh on main')
+ state['id_veh_behind'] = id_veh1
+ vehicles_main[id_veh1] = id_veh
+ is_found = True
+@@ -2034,7 +2034,7 @@
+
+ if is_found:
+ if debug > 0:
+- print ' suitable vehicle after which entry vehicle can run has been found'
++ print(' suitable vehicle after which entry vehicle can run has been found')
+ # Note: if no vehicle has been found then
+ # nothing will happen and the vehicle will
+ # wait until the righ moment has arrived
+@@ -2044,29 +2044,29 @@
+
+ else:
+ if debug > 0:
+- print ' nothing will happen and the vehicle will wait until the righ moment has arrived'
++ print(' nothing will happen and the vehicle will wait until the righ moment has arrived')
+
+ elif state['status'] == 'accelerate':
+ # test if speed reached
+ if traci.vehicle.getSpeed(id_veh_sumo) > 0.9*vehicles.speed_max:
+ if debug > 0:
+- print ' synchronization reached for veh', id_veh_sumo
++ print(' synchronization reached for veh', id_veh_sumo)
+ state['status'] = 'sync'
+ #id_veh_del = id_veh
+ # now create ghosts
+ # id_veh -> id_veh_infront_tail:
+- if state.has_key('id_veh_infront'):
++ if 'id_veh_infront' in state:
+ id_veh_in_front = state['id_veh_infront']
+ id_veh_infront_tail = vehicles.get_platoontail(id_veh_in_front)
+ id_veh_infront_tail_sumo = vehicles.ids_sumo[id_veh_infront_tail]
+ dist_tomerge = get_traci_distance(id_veh_sumo, id_edge_out_sumo, 3.0)
+ dist_tomerge_tail = get_traci_distance(id_veh_infront_tail_sumo, id_edge_out_sumo, 3.0)
+ if debug > 0:
+- print ' add ghost to entering veh', id_veh_sumo, ' behind', id_veh_infront_tail_sumo, 'with leader', id_veh_in_front
++ print(' add ghost to entering veh', id_veh_sumo, ' behind', id_veh_infront_tail_sumo, 'with leader', id_veh_in_front)
+ vehicles.add_ghost(id_veh, id_veh_infront_tail, dist_tomerge,
+ dist_tomerge_tail, is_substitute=True)
+
+- if state.has_key('id_veh_behind'):
++ if 'id_veh_behind' in state:
+ id_veh_behind = state['id_veh_behind']
+ id_veh_behind_sumo = vehicles.ids_sumo[id_veh_behind]
+
+@@ -2082,9 +2082,9 @@
+ else:
+ if debug > 0:
+ speed = traci.vehicle.getSpeed(id_veh_sumo)
+- print ' sync of veh', id_veh_sumo, ',v=%.1f, not yet reached: %.2f' % (speed, speed/vehicles.speed_max)
+-
+- if state.has_key('id_veh_behind'):
++ print(' sync of veh', id_veh_sumo, ',v=%.1f, not yet reached: %.2f' % (speed, speed/vehicles.speed_max))
++
++ if 'id_veh_behind' in state:
+ id_veh_behind_sumo = vehicles.ids_sumo[state['id_veh_behind']]
+ info = traci.vehicle.getLeader(id_veh_behind_sumo, dist=200.0)
+ if (info is not None):
+@@ -2095,17 +2095,17 @@
+ dist_safe = vehicles.tau*speed + 0.5*speed**2/vehicles.decel_emergency
+ dist_target = 2*dist_safe+vehicles.lengths_plat[id_veh]
+ if debug > 0:
+- print ' behind', id_veh_behind_sumo, 'with infront', id_leader_sumo, 'at dist=%.2f' % dist_leader, 'at ds=%.2f' % dist_safe, 'is_brake', dist_leader < dist_target
++ print(' behind', id_veh_behind_sumo, 'with infront', id_leader_sumo, 'at dist=%.2f' % dist_leader, 'at ds=%.2f' % dist_safe, 'is_brake', dist_leader < dist_target)
+ if dist_leader < dist_target:
+ dv = time_update*vehicles.decel
+ if (speed-dv) > 0:
+ if debug > 0:
+- print ' slowdown', id_veh_behind_sumo, 'from speed %.2f to %.2f' % (speed, speed-dv)
++ print(' slowdown', id_veh_behind_sumo, 'from speed %.2f to %.2f' % (speed, speed-dv))
+ traci.vehicle.slowDown(id_veh_behind_sumo, speed-dv, time_update)
+ else:
+ dv = time_update*vehicles.decel
+ if debug > 0:
+- print ' accel', id_veh_behind_sumo, 'from speed %.2f to %.2f' % (speed, speed+dv)
++ print(' accel', id_veh_behind_sumo, 'from speed %.2f to %.2f' % (speed, speed+dv))
+ traci.vehicle.slowDown(id_veh_behind_sumo, speed+dv, time_update)
+
+ elif state['status'] == 'sync':
+@@ -2584,7 +2584,7 @@
+ return positions+offset
+
+ def prepare_sim(self, process):
+- print 'PrtStops.prepare_sim'
++ print('PrtStops.prepare_sim')
+ net = self.get_scenario().net
+ ptstops = net.ptstops
+ ids_edge_sumo = net.edges.ids_sumo
+@@ -2620,11 +2620,11 @@
+ lastberthstoppos = berths.stoppositions[ids_berth_board][-1]
+ if (length_stopedge-lastberthstoppos) > stoplinegap+1:
+ self.stoplines[id_stop] = length_stopedge-stoplinegap
+- print ' LI:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop]
++ print(' LI:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop])
+
+ elif length_stopedge > lastberthstoppos:
+ self.stoplines[id_stop] = 0.5*(length_stopedge+lastberthstoppos)
+- print ' AV:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop]
++ print(' AV:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop])
+
+ self.ids_stop_to_ids_acceledge_sumo = np.zeros(np.max(ids)+1, dtype=np.object)
+ for id_stop, id_stopedge in zip(ids, ids_stopedge):
+@@ -2685,7 +2685,7 @@
+ id_toedge_sumo)
+
+ id_person_sumo = virtualpop.get_id_sumo_from_id(id_person)
+- if id_person_to_origs_dests.has_key(id_person_sumo):
++ if id_person_sumo in id_person_to_origs_dests:
+ id_person_to_origs_dests[id_person_sumo].append(data_orig_dest)
+ else:
+ id_person_to_origs_dests[id_person_sumo] = [data_orig_dest]
+@@ -2726,8 +2726,8 @@
+
+ def process_step(self, process):
+ simtime = process.simtime
+- print 79*'_'
+- print 'PrtStops.process_step at', simtime
++ print(79*'_')
++ print('PrtStops.process_step at', simtime)
+ net = self.get_scenario().net
+ ptstops = net.ptstops
+ berths = self.get_berths()
+@@ -2741,22 +2741,22 @@
+ zip(ids, self.ids_stop_to_ids_edge_sumo[ids],
+ self.ids_vehs_sumo_prev[ids],
+ self.ids_persons_sumo_prev[ids]):
+- print ' '+60*'.'
+- print ' process id_stop,id_edge_sumo', id_stop, id_edge_sumo
++ print(' '+60*'.')
++ print(' process id_stop,id_edge_sumo', id_stop, id_edge_sumo)
+ if 0: # id_stop==1:
+
+ # print ' ids_berth_alight',self.ids_berth_alight[id_stop]
+ # print ' ids_berth_board',self.ids_berth_board[id_stop]
+- print ' ids_vehs', self.ids_vehs[id_stop]
+- print ' ids_vehs_toallocate', self.ids_vehs_toallocate[id_stop]
+- print ' inds_berth_alight_allocated', self.inds_berth_alight_allocated[id_stop]
+- print ' ids_vehs_alight_allocated', self.ids_vehs_alight_allocated[id_stop]
+- print ' ids_vehs_board_allocated', self.ids_vehs_board_allocated[id_stop]
++ print(' ids_vehs', self.ids_vehs[id_stop])
++ print(' ids_vehs_toallocate', self.ids_vehs_toallocate[id_stop])
++ print(' inds_berth_alight_allocated', self.inds_berth_alight_allocated[id_stop])
++ print(' ids_vehs_alight_allocated', self.ids_vehs_alight_allocated[id_stop])
++ print(' ids_vehs_board_allocated', self.ids_vehs_board_allocated[id_stop])
+ # print ' id_veh_lead prt.%d'%self.ids_veh_lead[id_stop]
+ # print ' ids_vehs_prog',self.ids_vehs_prog[id_stop]
+
+- print ' iiinds_berth_alight_allocated', self.inds_berth_alight_allocated[id_stop]
+- print ' iiinds_berth_board_allocated', self.inds_berth_board_allocated[id_stop]
++ print(' iiinds_berth_alight_allocated', self.inds_berth_alight_allocated[id_stop])
++ print(' iiinds_berth_board_allocated', self.inds_berth_board_allocated[id_stop])
+ # print ' numbers_person_wait',self.numbers_person_wait[id_stop]
+
+ # print ' flow_person',self.flows_person[id_stop]
+@@ -2769,7 +2769,7 @@
+
+ if 0:
+ for id_veh_sumo in self.ids_vehs_sumo_prev[id_stop]:
+- print ' stopstate ', id_veh_sumo, bin(traci.vehicle.getStopState(id_veh_sumo))[2:], traci.vehicle.getRoute(id_veh_sumo)
++ print(' stopstate ', id_veh_sumo, bin(traci.vehicle.getStopState(id_veh_sumo))[2:], traci.vehicle.getRoute(id_veh_sumo))
+
+ if 0:
+ self.get_berthqueues(id_stop)
+@@ -2963,8 +2963,8 @@
+ if ids_person_sumo_prev != ids_person_sumo:
+
+ if 0:
+- print ' change\n id_person_sumo', ids_person_sumo
+- print ' ids_person_sumo_prev', ids_person_sumo_prev
++ print(' change\n id_person_sumo', ids_person_sumo)
++ print(' ids_person_sumo_prev', ids_person_sumo_prev)
+ # print ' dir(traci.person)',dir(traci.person)
+ # for id_person_sumo in ids_person_sumo:
+ # print ' id_person_sumo',id_person_sumo,traci.person.getRoadID(id_person_sumo),traci.person.getVehicle(id_person_sumo)
+@@ -2990,7 +2990,7 @@
+ ids_person_sumo_entered = ids_person_sumo.difference(ids_person_sumo_prev)
+ for id_person_sumo in ids_person_sumo_entered:
+ # print ' entered id_person_sumo',id_person_sumo,traci.person.getRoadID(id_person_sumo)
+- if self.id_person_to_origs_dests.has_key(id_person_sumo):
++ if id_person_sumo in self.id_person_to_origs_dests:
+ id_edge_sumo_dests = self.id_person_to_origs_dests[id_person_sumo]
+ # check if person still has a PRT trip
+
+@@ -3019,7 +3019,7 @@
+
+ if 0:
+ for id_person_sumo in ids_person_sumo_prev:
+- print ' ids_person_sumo=%s pos = %.2f ' % (id_person_sumo, traci.person.getLanePosition(id_person_sumo))
++ print(' ids_person_sumo=%s pos = %.2f ' % (id_person_sumo, traci.person.getLanePosition(id_person_sumo)))
+ # nomore print ' ids_persons_sumo_boarded',self.ids_persons_sumo_boarded[id_stop]
+
+ # check if boarding is completed in load area,
+@@ -3082,7 +3082,7 @@
+ self.start_vehicles(id_stop, process)
+
+ def start_vehicles(self, id_stop, process):
+- print 'start_vehicles=\n', self.ids_vehs_prog[id_stop]
++ print('start_vehicles=\n', self.ids_vehs_prog[id_stop])
+ i = 0
+ vehicles = self.parent.prtvehicles
+ ids_vehs_prog = self.ids_vehs_prog[id_stop]
+@@ -3191,7 +3191,7 @@
+ route_pre, traveltime = self.route_stop_to_stop(id_stop, id_stop_target_pre)
+ id_detectoredge_pre = self.get_decompressoredge(route_pre)
+
+- for i in xrange(1, len(inds_platoon)):
++ for i in range(1, len(inds_platoon)):
+ #time_start_pre, id_veh_pre, id_stop_target_pre, is_prog_pre = ids_vehs_prog[inds_platoon[i-1]]
+ time_start, id_veh, id_stop_target, is_prog = ids_vehs_prog[inds_platoon[i]]
+ route, traveltime = self.route_stop_to_stop(id_stop, id_stop_target)
+@@ -3319,7 +3319,7 @@
+ return True
+
+ else:
+- print ' no leader prt.%d exists' % (id_veh,)
++ print(' no leader prt.%d exists' % (id_veh,))
+ return False
+
+ def init_trip_occupied(self, id_stop, id_berth, id_veh, id_veh_sumo, simtime):
+@@ -3350,7 +3350,7 @@
+ # id_person_sumo_inveh = id_person_sumo
+
+ if id_person_sumo_inveh is not None:
+- print ' found person %s in veh %s' % (id_person_sumo_inveh, id_veh_sumo)
++ print(' found person %s in veh %s' % (id_person_sumo_inveh, id_veh_sumo))
+
+ # program vehicle to person's destination
+ # print ' found person,origs_dests',id_person_sumo_inveh,self.id_person_to_origs_dests[id_person_sumo_inveh]
+@@ -3376,7 +3376,7 @@
+ return id_person_sumo_inveh
+
+ else:
+- print 'WARNING: on stop %d edge %s, berth %d no person found inside vehicle prt.%d' % (id_stop, self.ids_stop_to_ids_edge_sumo[id_stop], id_berth, id_veh)
++ print('WARNING: on stop %d edge %s, berth %d no person found inside vehicle prt.%d' % (id_stop, self.ids_stop_to_ids_edge_sumo[id_stop], id_berth, id_veh))
+ return None
+
+ def _get_stopline(self, id_stop, simtime):
+@@ -3430,7 +3430,7 @@
+ # self.ids_vehs_outset[id_stop].add(id_veh)
+
+ def foreward_boardzone(self, id_stop, ids_berth_board, simtime):
+- print 'foreward_boardzone', id_stop, ids_berth_board, 'simtime', simtime
++ print('foreward_boardzone', id_stop, ids_berth_board, 'simtime', simtime)
+ berths = self.get_berths()
+ #ids_berth_board = self.ids_berth_board[id_stop][::-1]
+ # inds_o berths.states[ids_berth_board] != BERTHSTATES['free']
+@@ -3442,7 +3442,7 @@
+ self.times_lastboard[id_stop] = 10**4 # reset last board counter
+
+ def enter(self, id_stop, id_veh):
+- print 'enter id_stop, id_veh', id_stop, 'prt.%d' % id_veh
++ print('enter id_stop, id_veh', id_stop, 'prt.%d' % id_veh)
+
+ self.parent.prtvehicles.decatenate(id_veh)
+
+@@ -3464,10 +3464,10 @@
+ # print ' id_veh_sumo',id_veh_sumo
+ #pos = traci.vehicle.getLanePosition(id_veh_sumo)
+ if 0:
+- print ' send entering vehicle id_veh %d, pos=%.2f to id_berth_alight %d at pos %.2fm' % (id_veh, traci.vehicle.getLanePosition(id_veh_sumo), id_berth, self.get_berths().stoppositions[id_berth])
+- print ' ids_ghost', self.parent.prtvehicles.ids_ghosts[id_veh]
+- print ' ids_leader', self.parent.prtvehicles.ids_leader[id_veh]
+- print ' ids_follower', self.parent.prtvehicles.ids_follower[id_veh]
++ print(' send entering vehicle id_veh %d, pos=%.2f to id_berth_alight %d at pos %.2fm' % (id_veh, traci.vehicle.getLanePosition(id_veh_sumo), id_berth, self.get_berths().stoppositions[id_berth]))
++ print(' ids_ghost', self.parent.prtvehicles.ids_ghosts[id_veh])
++ print(' ids_leader', self.parent.prtvehicles.ids_leader[id_veh])
++ print(' ids_follower', self.parent.prtvehicles.ids_follower[id_veh])
+
+ self.parent.prtvehicles.control_stop_alight(id_veh, id_stop, id_berth,
+ id_edge_sumo=self.ids_stop_to_ids_edge_sumo[id_stop],
+@@ -3552,7 +3552,7 @@
+ stoppositions = self.get_berths().stoppositions[ids_berth_board]
+ counters = np.zeros(len(stoppositions), dtype=np.int32)
+ # print ' stoppositions',stoppositions
+- for id_person_sumo in self.waittimes_persons[id_stop].keys():
++ for id_person_sumo in list(self.waittimes_persons[id_stop].keys()):
+ position = traci.person.getLanePosition(id_person_sumo)
+ # print ' position',position
+ dists = np.abs(stoppositions-position)
+@@ -3572,7 +3572,7 @@
+ """
+ Make prt stop database from PT stops in network.
+ """
+- print 'make_from_net'
++ print('make_from_net')
+ self.clear()
+ net = self.get_scenario().net
+ ptstops = net.ptstops
+@@ -3620,7 +3620,7 @@
+
+ class VehicleAdder(Process):
+ def __init__(self, vehicles, logger=None, **kwargs):
+- print 'VehicleAdder.__init__', vehicles, vehicles.parent.get_ident()
++ print('VehicleAdder.__init__', vehicles, vehicles.parent.get_ident())
+ self._init_common('vehicleadder', name='Vehicle adder',
+ logger=logger,
+ info='Add vehicles to PRT stops of network.',
+@@ -3795,7 +3795,7 @@
+ return self.parent.get_scenario().net
+
+ def make_vtype(self, is_renew=False):
+- print 'make_vtype PRT'
++ print('make_vtype PRT')
+ vtypes = self.get_scenario().demand.vtypes
+ prttype = 'PRT'
+
+@@ -3901,7 +3901,7 @@
+ return self.length
+
+ def prepare_sim(self, process):
+- print 'PrtVehicles.prepare_sim'
++ print('PrtVehicles.prepare_sim')
+ if len(self) == 0:
+ return []
+
+@@ -3962,7 +3962,7 @@
+ # self.del_ghost(id_veh, id_ghost_old)
+ # else:
+ # add new ghost
+- print 'add_ghost id_veh %d id_ghost %d' % (id_veh, id_ghost) # ,self.ids_ghosts.shape
++ print('add_ghost id_veh %d id_ghost %d' % (id_veh, id_ghost)) # ,self.ids_ghosts.shape
+
+ if -1 not in ids_ghosts:
+ # print 'ERROR: no more ghosts available, ids_ghosts',ids_ghosts
+@@ -3981,7 +3981,7 @@
+ ind_ghost -= 1
+
+ if ind_ghost > 0:
+- print 'WARNING: unusual number of ghosts, ids_ghosts', ids_ghosts
++ print('WARNING: unusual number of ghosts, ids_ghosts', ids_ghosts)
+ # sys.exit(1)
+
+ self.ids_ghosts[id_veh][ind_ghost] = id_ghost
+@@ -4068,8 +4068,8 @@
+
+ def process_step(self, process):
+ simtime = process.simtime
+- print 79*'_'
+- print 'PrtVehicles.process_step at', simtime
++ print(79*'_')
++ print('PrtVehicles.process_step at', simtime)
+ net = self.get_scenario().net
+ vehicles = self.parent.prtvehicles
+ ids = self.get_ids()
+@@ -4098,7 +4098,7 @@
+
+ if 0:
+ ids_ghost = self.ids_ghosts[id_veh]
+- print ' %7s' % id_veh_sumo, 'ghosts', ids_ghost, self.ids_leader[id_veh], "lp=%.1fm" % self.lengths_plat[id_veh]
++ print(' %7s' % id_veh_sumo, 'ghosts', ids_ghost, self.ids_leader[id_veh], "lp=%.1fm" % self.lengths_plat[id_veh])
+ #odo = self.odos[id_veh]
+ #delta_vehs = odo-self.odos0_vehicles[id_veh]
+ #delta_ghosts = self.odos[ids_ghost] - self.odos0_ghosts[id_veh]
+@@ -4234,7 +4234,7 @@
+ #self.tau = vtypes.taus[id_vtype]
+
+ def reset_speedmode(self, id_veh_sumo):
+- print 'reset_speedmode', id_veh_sumo
++ print('reset_speedmode', id_veh_sumo)
+ # speed mode (0xb3)
+ # Per default, the vehicle is using the given speed regarding the safe gap, the maximum acceleration, and the maximum deceleration. Furthermore, vehicles follow the right-of-way rules when approaching an intersection and if necessary they brake hard to avoid driving across a red light. One can control this behavior using the speed mode (0xb3) command, the given integer is a bitset (bit0 is the least significant bit) with the following fields:
+ # 1 bit0: Regard safe speed
+@@ -4250,7 +4250,7 @@
+ # pass
+
+ def concatenate(self, id_veh, id_veh_pre):
+- print 'concatenate prt.%d' % id_veh, 'behind prt.%d' % id_veh_pre
++ print('concatenate prt.%d' % id_veh, 'behind prt.%d' % id_veh_pre)
+ # print ' >>'
+ self.ids_leader[id_veh] = id_veh_pre
+ self.ids_follower[id_veh_pre] = id_veh
+@@ -4258,13 +4258,13 @@
+ id_veh_sumo = self.get_id_sumo(id_veh)
+
+ if 0:
+- print 'follower params'
+- print ' speedmode', self._speedmode_follower
+- print ' factor_speed', self._factor_speed_follower
+- print ' decel', self._decel_emergency_follower, '= decel_emergency'
+- print ' accel_follower', self._accel_follower
+- print ' dist_min', self._dist_min_follower
+- print ' tau', self._tau_follower
++ print('follower params')
++ print(' speedmode', self._speedmode_follower)
++ print(' factor_speed', self._factor_speed_follower)
++ print(' decel', self._decel_emergency_follower, '= decel_emergency')
++ print(' accel_follower', self._accel_follower)
++ print(' dist_min', self._dist_min_follower)
++ print(' tau', self._tau_follower)
+
+ # if 0:
+ # traci.vehicle.setSpeedFactor(id_veh_sumo,2.0)# +random.uniform(-0.01,0.01)
+@@ -4302,7 +4302,7 @@
+ self._update_concatenate(self.ids_leader[id_veh], length_plat + self.length)
+
+ def decatenate(self, id_veh):
+- print 'decatenate prt.%d' % id_veh
++ print('decatenate prt.%d' % id_veh)
+
+ id_leader = self.ids_leader[id_veh]
+ # print ' id_leader',id_leader
+@@ -4317,7 +4317,7 @@
+ # TODO
+ self.lengths_plat[id_veh] = self.lengths_plat[id_leader]-self.length
+ else:
+- print 'WARNING in decatenate: platoon broken up in the middel at', id_veh_sumo
++ print('WARNING in decatenate: platoon broken up in the middel at', id_veh_sumo)
+ self.lengths_plat[id_veh] = 0.0
+
+ # this vehicle will become first in the platoon
+@@ -4357,16 +4357,16 @@
+ return id_veh
+
+ def get_platoon(self, id_veh):
+- print 'get_platoon', id_veh
++ print('get_platoon', id_veh)
+ ids_veh = [id_veh, ]
+ id_veh = self.ids_follower[id_veh]
+ # print ' id_veh',id_veh
+ while id_veh > -1:
+ ids_veh.append(id_veh)
+ id_veh = self.ids_follower[id_veh]
+- print ' id_veh', id_veh
+-
+- print ' ids_veh', ids_veh
++ print(' id_veh', id_veh)
++
++ print(' ids_veh', ids_veh)
+ return ids_veh
+
+ def get_entered_left(self, id_edge_sumo, ids_veh_previous_sumo):
+@@ -4429,7 +4429,7 @@
+ stopline = pos + 3.0 + 0.5/self.decel*speed**2
+ #time_slowdown = np.abs((speed0-speed)/self.decel)
+
+- print 'control_stop', id_veh_sumo, 'v = %.2f at pos %.1fm to stop at %.1fm on %s' % (speed, pos, stopline, traci.vehicle.getRoadID(id_veh_sumo))
++ print('control_stop', id_veh_sumo, 'v = %.2f at pos %.1fm to stop at %.1fm on %s' % (speed, pos, stopline, traci.vehicle.getRoadID(id_veh_sumo)))
+ traci.vehicle.setStop(id_veh_sumo,
+ traci.vehicle.getRoadID(id_veh_sumo),
+ pos=stopline,
+@@ -4439,7 +4439,7 @@
+ def control_speedup(self, id_veh):
+
+ id_veh_sumo = self.get_id_sumo(id_veh)
+- print 'control_speedup', id_veh_sumo, 'isStopped', traci.vehicle.isStopped(id_veh_sumo), self.speed_max
++ print('control_speedup', id_veh_sumo, 'isStopped', traci.vehicle.isStopped(id_veh_sumo), self.speed_max)
+
+ if traci.vehicle.isStopped(id_veh_sumo):
+ traci.vehicle.resume(id_veh_sumo)
+@@ -4448,7 +4448,7 @@
+ #self.control_slow_down(id_veh, self.speed_max)
+
+ def control_slow_down(self, id_veh, speed=1.0, time_slowdown=None):
+- print 'control_slow_down', self.get_id_sumo(id_veh), speed, time_slowdown
++ print('control_slow_down', self.get_id_sumo(id_veh), speed, time_slowdown)
+ id_veh_sumo = self.get_id_sumo(id_veh)
+ if time_slowdown is None:
+ speed0 = traci.vehicle.getSpeed(id_veh_sumo)
+@@ -4467,7 +4467,7 @@
+ ):
+ id_veh_sumo = self.get_id_sumo(id_veh)
+ p = traci.vehicle.getLanePosition(id_veh_sumo)
+- print 'control_stop_alight', id_veh_sumo, p, '->', position, 'id_berth', id_berth
++ print('control_stop_alight', id_veh_sumo, p, '->', position, 'id_berth', id_berth)
+ #d = position - p
+ #v = traci.vehicle.getSpeed(id_veh_sumo)
+ #d_save = 1.0/(2*2.5)*(v**2)
+@@ -4488,7 +4488,7 @@
+ ):
+
+ id_veh_sumo = self.get_id_sumo(id_veh)
+- print 'control_stop_board', id_veh_sumo, id_stop, id_berth, id_edge_sumo, 'pos=%.2f,target %.2f' % (traci.vehicle.getLanePosition(id_veh_sumo), position)
++ print('control_stop_board', id_veh_sumo, id_stop, id_berth, id_edge_sumo, 'pos=%.2f,target %.2f' % (traci.vehicle.getLanePosition(id_veh_sumo), position))
+ # print ' v=',traci.vehicle.getSpeed(id_veh_sumo)
+
+ # print 'control_stop_board',id_veh_sumo,traci.vehicle.getLanePosition(id_veh_sumo),'->',position,id_berth
+@@ -4535,7 +4535,7 @@
+ # print 'board ',id_veh_sumo, traci.vehicle.getStopState(id_veh_sumo )# bin(traci.vehicle.getStopState(id_veh_sumo ))[2:]
+
+ def set_stop(self, id_veh, id_edge_sumo, stopline, laneindex=1):
+- print 'set_stop', self.get_id_sumo(id_veh), stopline
++ print('set_stop', self.get_id_sumo(id_veh), stopline)
+ traci.vehicle.setStop(self.get_id_sumo(id_veh),
+ id_edge_sumo,
+ pos=stopline,
+@@ -4560,7 +4560,7 @@
+ elif self.states[id_veh] == VEHICLESTATES['await_forwarding']:
+ return True
+ else:
+- print 'WARNING: strange vehicle state %s while alighting prt.%d' % (self.states[id_veh], id_veh)
++ print('WARNING: strange vehicle state %s while alighting prt.%d' % (self.states[id_veh], id_veh))
+ return True
+
+ def is_completed_boarding(self, id_veh):
+@@ -4593,7 +4593,7 @@
+
+ def init_trip_occupied(self, id_veh, id_edge_sumo, stopline=None):
+ id_veh_sumo = self.get_id_sumo(id_veh)
+- print 'init_trip_occupied', self.get_id_sumo(id_veh), 'from edge', id_edge_sumo, stopline
++ print('init_trip_occupied', self.get_id_sumo(id_veh), 'from edge', id_edge_sumo, stopline)
+ # print ' current route:',traci.vehicle.getRoute(id_veh_sumo)
+ self.states[id_veh] = VEHICLESTATES['occupiedtrip']
+
+@@ -4614,7 +4614,7 @@
+ #traci.vehicle.slowDown(id_veh_sumo, speed_crawl, time_accel)
+
+ def init_trip_empty(self, id_veh, id_edge_sumo, stopline=None):
+- print 'Vehicles.init_trip_empty', self.get_id_sumo(id_veh), id_edge_sumo, stopline
++ print('Vehicles.init_trip_empty', self.get_id_sumo(id_veh), id_edge_sumo, stopline)
+ self.states[id_veh] = VEHICLESTATES['emptytrip']
+ id_veh_sumo = self.get_id_sumo(id_veh)
+ if traci.vehicle.isStopped(id_veh_sumo):
+@@ -4637,7 +4637,7 @@
+ #traci.vehicle.slowDown(id_veh_sumo, speed_crawl, time_accel)
+
+ def reschedule_trip_sumo(self, id_veh_sumo, id_edge_sumo_to=None, route_sumo=None):
+- print 'reschedule_trip_sumo', id_veh_sumo, id_edge_sumo_to, route_sumo
++ print('reschedule_trip_sumo', id_veh_sumo, id_edge_sumo_to, route_sumo)
+ if traci.vehicle.isStopped(id_veh_sumo):
+ traci.vehicle.resume(id_veh_sumo)
+
+@@ -4654,7 +4654,7 @@
+ #traci.vehicle.slowDown(id_veh_sumo, 13.0, 5.0)
+
+ def reschedule_trip(self, id_veh, id_edge_sumo_to=None, route_sumo=None):
+- print 'reschedule_trip', self.get_id_sumo(id_veh), id_edge_sumo_to, route_sumo
++ print('reschedule_trip', self.get_id_sumo(id_veh), id_edge_sumo_to, route_sumo)
+ id_veh_sumo = self.get_id_sumo(id_veh)
+ if traci.vehicle.isStopped(id_veh_sumo):
+ traci.vehicle.resume(id_veh_sumo)
+@@ -4743,7 +4743,7 @@
+ def get_ids_from_ids_sumo(self, ids_veh_sumo):
+ n = len(ids_veh_sumo)
+ ids = np.zeros(n, np.int32)
+- for i in xrange(n):
++ for i in range(n):
+ ids[i] = self.get_id_from_id_sumo(ids_veh_sumo[i])
+ return ids
+
+@@ -4819,7 +4819,7 @@
+ # put 2 for persons with car access and who prefer cars
+ preeval[persons.ids_mode_preferred[ids_person] == self.prtservice.id_prtmode] = 2
+
+- print ' PrtStrategy.preevaluate', len(np.flatnonzero(preeval))
++ print(' PrtStrategy.preevaluate', len(np.flatnonzero(preeval)))
+ return preeval
+
+ def plan(self, ids_person, logger=None):
+@@ -4827,7 +4827,7 @@
+ Generates a plan for these person according to this strategie.
+ Overriden by specific strategy.
+ """
+- print 'PrtStrategy.pan', len(ids_person)
++ print('PrtStrategy.pan', len(ids_person))
+ #make_plans_private(self, ids_person = None, mode = 'passenger')
+ # routing necessary?
+ virtualpop = self.get_virtualpop()
+@@ -4869,7 +4869,7 @@
+ = virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
+
+ if len(ids_person_act) == 0:
+- print 'WARNING in TrasitStrategy.plan: no eligible persons found.'
++ print('WARNING in TrasitStrategy.plan: no eligible persons found.')
+ return False
+
+ # temporary maps from ids_person to other parameters
+@@ -4888,7 +4888,7 @@
+ map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]
+
+ n_plans = len(ids_person_act)
+- print 'TrasitStrategy.plan n_plans=', n_plans
++ print('TrasitStrategy.plan n_plans=', n_plans)
+
+ # make initial activity stage
+ ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]
+@@ -4970,11 +4970,11 @@
+ if logger:
+ logger.progress(i/n_pers*100)
+ i += 1.0
+- print 79*'_'
+- print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)
++ print(79*'_')
++ print(' id_plan=%d, id_person=%d, ' % (id_plan, id_person))
+
+ if (dist_from_to < dist_walk_max) | (id_edge_from == -1) | (id_edge_to == -1) | (id_stop_from == id_stop_to):
+- print ' go by foot because distance is too short ', dist_from_to, 'edges', id_edge_from, id_edge_to, 'stops', id_stop_from, id_stop_to
++ print(' go by foot because distance is too short ', dist_from_to, 'edges', id_edge_from, id_edge_to, 'stops', id_stop_from, id_stop_to)
+
+ id_stage_walk1, time = walkstages.append_stage(
+ id_plan, time_from,
+@@ -5041,7 +5041,7 @@
+ # **kwargs,
+ ):
+
+- print 'PrtTransits.__init__', ident, stages
++ print('PrtTransits.__init__', ident, stages)
+ self.init_stagetable(ident,
+ stages, name=name,
+ info=info,
+@@ -5073,10 +5073,10 @@
+ def prepare_planning(self):
+
+ prtservice = self.get_prtservice()
+- print 'prttransits.prepare_planning', prtservice.times_stop_to_stop
++ print('prttransits.prepare_planning', prtservice.times_stop_to_stop)
+ if prtservice.times_stop_to_stop is None:
+ prtservice.make_times_stop_to_stop()
+- print prtservice.times_stop_to_stop
++ print(prtservice.times_stop_to_stop)
+
+ def append_stage(self, id_plan, time_start=-1.0,
+ duration=0.0,
+@@ -5216,7 +5216,7 @@
+ return self.parent.parent.get_scenario()
+
+ def prepare_sim(self, process):
+- print 'VehicleMan.prepare_sim'
++ print('VehicleMan.prepare_sim')
+ net = self.get_scenario().net
+ # station management
+ # self.ids_stop_to_ids_edge_sumo = np.zeros(np.max(ids)+1,dtype = np.object)
+@@ -5238,7 +5238,7 @@
+ self.ids_veh = self.get_vehicles().get_ids()
+
+ if len(self.ids_veh) == 0:
+- print 'WARNING: no PRT vehicles, please add PRT vehicles.'
++ print('WARNING: no PRT vehicles, please add PRT vehicles.')
+ return []
+
+ n_veharray = np.max(self.ids_veh)+1
+@@ -5293,8 +5293,8 @@
+ self.log_inflows_temp[:] = 0
+
+ def process_step(self, process):
+- print 79*'M'
+- print 'VehicleMan.process_step'
++ print(79*'M')
++ print('VehicleMan.process_step')
+
+ stops = self.get_stops()
+ #vehicles = self.get_vehicles()
+@@ -5339,7 +5339,7 @@
+ inds_valid = np.flatnonzero(vehicles.states[ids_veh_lead] == VEHICLESTATES['occupiedtrip'])
+ if len(inds_valid) == 0:
+ return False
+- print 'push_occupied_leadvehs ids_veh_lead', ids_veh_lead[inds_valid]
++ print('push_occupied_leadvehs ids_veh_lead', ids_veh_lead[inds_valid])
+ times_stop_to_stop = self.parent.times_stop_to_stop
+ ids_stop_current = self.ids_stop_current[ids_veh_lead[inds_valid]]
+ ids_stop_target = self.ids_stop_target[ids_veh_lead[inds_valid]]
+@@ -5365,7 +5365,7 @@
+ durations_est,
+ ):
+
+- print ' check veh', id_veh_lead, state, 'id_stop_current', id_stop_current, 'id_stop_target', id_stop_target
++ print(' check veh', id_veh_lead, state, 'id_stop_current', id_stop_current, 'id_stop_target', id_stop_target)
+
+ #VEHICLESTATES = {'init':0,'waiting':1,'boarding':2,'alighting':3,'emptytrip':4,'occupiedtrip':5,'forewarding':6}
+ # if state == VEHICLESTATES['occupiedtrip']:
+@@ -5398,7 +5398,7 @@
+ if len(inds_valid) == 0:
+ return False
+
+- print 'push_empty_leadvehs ids_veh_lead', ids_veh_lead[inds_valid]
++ print('push_empty_leadvehs ids_veh_lead', ids_veh_lead[inds_valid])
+ times_stop_to_stop = self.parent.times_stop_to_stop
+ ids_stop_current = self.ids_stop_current[ids_veh_lead[inds_valid]]
+
+@@ -5427,7 +5427,7 @@
+
+ durations_est = times_stop_to_stop[id_stop_current, ids_stop_target]
+ ind_stop_current = np.flatnonzero(durations_est == 0)[0]
+- print ' check veh', id_veh_lead, 'id_stop_current', id_stop_current, 'ind_stop_current', ind_stop_current
++ print(' check veh', id_veh_lead, 'id_stop_current', id_stop_current, 'ind_stop_current', ind_stop_current)
+ inds_time_min = np.array(np.clip(np.array(1.0*durations_est/self.time_update_flows.get_value(),
+ dtype=np.int32), 0, self.n_est_max-n_searchint), dtype=np.int32)
+ inds_search = inds_search_base + inds_time_min.reshape(n_stop_target, 1)
+@@ -5446,29 +5446,29 @@
+ #costs = (self.inflows_sched[ids_stop_target, inds_search]-flow_person_est)*timeweight
+ costs[ind_stop_current, :] = -999999
+ if 0:
+- for ind, id_stop in zip(range(n_stop_target), ids_stop_target):
+- print 40*'.'
+- print ' id_stop', id_stop
+- print ' waittimes_tot', stops.waittimes_tot[id_stop]
+- print ' numbers_person_wait', stops.numbers_person_wait[id_stop]
+- print ' flow_person_est', flow_person_est[ind]
+- print ' inflows_sched', self.inflows_sched[id_stop, inds_search[ind]]
+- print ' delta flow', (flow_person_est[ind]-self.inflows_sched[id_stop, inds_search[ind]])
+- print ' demandcomp', self.weight_demand.get_value() * stops.numbers_person_wait[id_stop]
+- print ' flowcomp', self.weight_flow.get_value() * (flow_person_est[ind]-self.inflows_sched[id_stop, inds_search[ind]])
+- print ' arrivaltime est', inds_search[ind]*self.time_update_flows.get_value()
+- print ' flow_person_est', flow_person_est[ind]
+- print
++ for ind, id_stop in zip(list(range(n_stop_target)), ids_stop_target):
++ print(40*'.')
++ print(' id_stop', id_stop)
++ print(' waittimes_tot', stops.waittimes_tot[id_stop])
++ print(' numbers_person_wait', stops.numbers_person_wait[id_stop])
++ print(' flow_person_est', flow_person_est[ind])
++ print(' inflows_sched', self.inflows_sched[id_stop, inds_search[ind]])
++ print(' delta flow', (flow_person_est[ind]-self.inflows_sched[id_stop, inds_search[ind]]))
++ print(' demandcomp', self.weight_demand.get_value() * stops.numbers_person_wait[id_stop])
++ print(' flowcomp', self.weight_flow.get_value() * (flow_person_est[ind]-self.inflows_sched[id_stop, inds_search[ind]]))
++ print(' arrivaltime est', inds_search[ind]*self.time_update_flows.get_value())
++ print(' flow_person_est', flow_person_est[ind])
++ print()
+
+ # print ' flow_person_est',flow_person_#est
+- print ' timeweight', timeweight[ind]
+- print ' durations_est', durations_est[ind]
+- print ' inds_search_base', inds_search_base[ind]
++ print(' timeweight', timeweight[ind])
++ print(' durations_est', durations_est[ind])
++ print(' inds_search_base', inds_search_base[ind])
+ # print ' inds_search unclipped\n',inds_search_base +np.array(1.0*durations_est/self.time_update_flows.get_value(),dtype=np.int32).reshape(n_stop_target,1)
+- print ' inds_search clipped \n', inds_search[ind]
+- print ' inds_time_min', inds_time_min[ind]
++ print(' inds_search clipped \n', inds_search[ind])
++ print(' inds_time_min', inds_time_min[ind])
+ # print ' ind_stop_current',ind_stop_current,durations_est[ind_stop_current]
+- print ' costs=\n', costs[ind]
++ print(' costs=\n', costs[ind])
+ # constant_timeweight
+
+ #
+@@ -5478,9 +5478,9 @@
+ ind_time_delta = ind_target % n_searchint
+ ind_time_arrive = inds_search[ind_stop_target, ind_time_delta]
+ if 0:
+- print ' ind_target,n_searchint,ind_stop_target,ind_time_delta', ind_target, n_searchint, ind_target/n_searchint, ind_time_delta
+- print ' ind_delta_depart,c_min', costs[ind_stop_target, ind_time_delta]
+- print ' inds_time_min,ind_time_arrive', inds_time_min[ind_stop_target], ind_time_arrive
++ print(' ind_target,n_searchint,ind_stop_target,ind_time_delta', ind_target, n_searchint, ind_target/n_searchint, ind_time_delta)
++ print(' ind_delta_depart,c_min', costs[ind_stop_target, ind_time_delta])
++ print(' inds_time_min,ind_time_arrive', inds_time_min[ind_stop_target], ind_time_arrive)
+
+ id_stop_target = ids_stop_target[ind_stop_target][0]
+ time_depart = process.simtime + ind_time_arrive * \
+@@ -5493,7 +5493,7 @@
+ self.numbers_veh_arr[id_stop_target] += 1
+ self.inflows_sched[id_stop_target, ind_time_arrive] += 1
+ else:
+- print 'WARNING in push_empty_leadvehs: no vehicle prt.%d in stop %d' % (id_veh_lead, id_stop_target)
++ print('WARNING in push_empty_leadvehs: no vehicle prt.%d in stop %d' % (id_veh_lead, id_stop_target))
+ return is_started
+
+ def pull_empty_leadvehs(self, ids_veh_lead, process):
+@@ -5507,7 +5507,7 @@
+ # & (stops.numbers_person_wait[self.ids_stop_current[ids_veh_lead]] == 0))
+ vehicles = self.get_vehicles()
+ stops = self.get_stops()
+- print 'pull_empty_leadvehs', ids_veh_lead
++ print('pull_empty_leadvehs', ids_veh_lead)
+ # print ' bordingstate',vehicles.states[ids_veh_lead] == VEHICLESTATES['boarding']
+ # print ' nowaits stop',stops.numbers_person_wait[self.ids_stop_current[ids_veh_lead]] ==0
+
+@@ -5544,7 +5544,7 @@
+ ids_stop_target = self.ids_stop[inds_valid]
+ demands = demands[inds_valid]
+
+- print ' ids_stop_current', ids_stop_current
++ print(' ids_stop_current', ids_stop_current)
+ # print ' ids_stop_target',ids_stop_target
+ # print ' demands',demands
+ # calculate cost matrix with id_stop_current in rows and id_stop_target
+@@ -5561,7 +5561,7 @@
+ costs = timeweight * demands
+ for id_stop_target, demand, number_veh, number_veh_arr\
+ in zip(ids_stop_target, demands, stops.numbers_veh[ids_stop_target], self.numbers_veh_arr[ids_stop_target]):
+- print ' id_stop_target', id_stop_target, 'dem', demand, 'n_veh', number_veh, 'n_veh_arr', number_veh_arr
++ print(' id_stop_target', id_stop_target, 'dem', demand, 'n_veh', number_veh, 'n_veh_arr', number_veh_arr)
+
+ #costs = np.zeros(costs.size, np.float32)-demands
+
+@@ -5591,7 +5591,7 @@
+ durations_est,
+ ):
+
+- print ' check veh prt.%d' % (id_veh_lead), state, 'id_stop_current', id_stop_current, 'id_stop_target', id_stop_target
++ print(' check veh prt.%d' % (id_veh_lead), state, 'id_stop_current', id_stop_current, 'id_stop_target', id_stop_target)
+
+ #VEHICLESTATES = {'init':0,'waiting':1,'boarding':2,'alighting':3,'emptytrip':4,'occupiedtrip':5,'forewarding':6}
+ # if state == VEHICLESTATES['occupiedtrip']:
+@@ -5764,7 +5764,7 @@
+
+ Method used to sort trips when exporting to route or trip xml file
+ """
+- print 'PRT.get_writexmlinfo'
++ print('PRT.get_writexmlinfo')
+
+ # time of first PRT vehicle(s) to be inserted
+ virtualpop = self.get_scenario().demand.virtualpop
+@@ -5855,14 +5855,14 @@
+ # self.make_times_stop_to_stop()
+
+ def prepare_sim(self, process):
+- print 'prepare_sim', self.ident
++ print('prepare_sim', self.ident)
+ # print ' self.times_stop_to_stop',self.times_stop_to_stop
+
+ if self.fstar is None:
+ self.make_fstar()
+
+ if self.times_stop_to_stop is None:
+- print ' times_stop_to_stop'
++ print(' times_stop_to_stop')
+ self.make_times_stop_to_stop()
+
+ updatedata = self.prtvehicles.prepare_sim(process)
+@@ -5892,7 +5892,7 @@
+ return route, duration
+
+ def make_times_stop_to_stop(self, fstar=None, times=None):
+- print 'make_times_stop_to_stop'
++ print('make_times_stop_to_stop')
+ log = self.get_logger()
+ if fstar is None:
+ if self.fstar is None:
+@@ -5917,8 +5917,8 @@
+ is_incomplete_fstar = False
+ for id_edge, id_stop, id_ptstop in zip(ids_edge, ids_prtstop, ids_ptstop):
+ # print ' Found PRT stop %d, PT stop %d with id_edge %d '%(id_stop,id_ptstop, id_edge)
+- if not fstar.has_key(id_edge):
+- print 'WARNING in make_times_stop_to_stop: PRT stop %d, PT stop %d has no id_edge %d in fstar' % (id_stop, id_ptstop, id_edge)
++ if id_edge not in fstar:
++ print('WARNING in make_times_stop_to_stop: PRT stop %d, PT stop %d has no id_edge %d in fstar' % (id_stop, id_ptstop, id_edge))
+ is_incomplete_fstar = True
+
+ # check if fstar is complete (all to edges are in keys)
+@@ -5928,9 +5928,9 @@
+ if not ids_fromedge_set.issuperset(fstar[id_fromedge]):
+ is_incomplete_fstar = True
+ ids_miss = fstar[id_fromedge].difference(ids_fromedge_set)
+- print 'WARNING in make_times_stop_to_stop: incomplete fstar of id_fromedge = %d, %s' % (id_fromedge, ids_sumo[id_fromedge])
++ print('WARNING in make_times_stop_to_stop: incomplete fstar of id_fromedge = %d, %s' % (id_fromedge, ids_sumo[id_fromedge]))
+ for id_edge in ids_miss:
+- print ' missing', id_edge, ids_sumo[id_edge]
++ print(' missing', id_edge, ids_sumo[id_edge])
+
+ if is_incomplete_fstar:
+ return
+@@ -5977,7 +5977,7 @@
+ stop_to_stop[ids_edge_to_ids_prtstop[id_edge],
+ ids_edge_to_ids_prtstop[id_edge_target]] = costs[id_edge_target]
+ else:
+- print 'WARNING in make_times_stop_to_stop: unreacle station id_fromedge = %d, %s' % (id_edge_target, ids_sumo[id_edge_target])
++ print('WARNING in make_times_stop_to_stop: unreacle station id_fromedge = %d, %s' % (id_edge_target, ids_sumo[id_edge_target]))
+ is_incomplete_fstar = True
+
+ # put back origin to targets (probably not the best way)
+@@ -5992,7 +5992,7 @@
+
+ self.times_stop_to_stop = stop_to_stop
+ self.ids_edge_to_ids_prtstop = ids_edge_to_ids_prtstop
+- print ' times_stop_to_stop=\n', self.times_stop_to_stop
++ print(' times_stop_to_stop=\n', self.times_stop_to_stop)
+ return True
+
+ def get_fstar(self):
+@@ -6000,7 +6000,7 @@
+ Returns the forward star graph of the network as dictionary:
+ fstar[id_fromedge] = set([id_toedge1, id_toedge2,...])
+ """
+- print 'get_fstar'
++ print('get_fstar')
+ net = self.get_scenario().net
+ # prt mode
+ id_mode = self.id_prtmode
+@@ -6037,7 +6037,7 @@
+ if id_mode_allow_from == id_mode:
+ if id_mode_allow_to == id_mode:
+
+- if fstar.has_key(id_fromedge):
++ if id_fromedge in fstar:
+ fstar[id_fromedge].add(id_toedge)
+ else:
+ fstar[id_fromedge] = set([id_toedge])
+@@ -6074,7 +6074,7 @@
+ #id_mode = net.modes.get_id_mode(mode)
+ id_mode = self.id_prtmode
+ # print 'get_times id_mode,is_check_lanes,speed_max',id_mode,is_check_lanes,speed_max
+- ids_edge = np.array(fstar.keys(), dtype=np.int32)
++ ids_edge = np.array(list(fstar.keys()), dtype=np.int32)
+
+ times = np.array(np.zeros(np.max(ids_edge)+1, np.float32))
+ speeds = net.edges.speeds_max[ids_edge]
+@@ -6087,7 +6087,7 @@
+ return times
+
+ def config_results(self, results):
+- print 'PrtService.config_results', results, id(results)
++ print('PrtService.config_results', results, id(results))
+ # keep a link to results here because needed to
+ # log data during simulation
+ # this link should not be followed during save process
+@@ -6164,7 +6164,7 @@
+ # return self.ids_stop.get_linktab()
+
+ def init_recording(self, n_timesteps, time_step):
+- print 'init_recording n_timesteps, time_step', n_timesteps, time_step, len(self.ids_stop.get_linktab().get_ids())
++ print('init_recording n_timesteps, time_step', n_timesteps, time_step, len(self.ids_stop.get_linktab().get_ids()))
+ self.clear()
+
+ self.time_step.set_value(time_step)
+@@ -6181,13 +6181,13 @@
+ def record(self, timestep, ids, **kwargs):
+ inds = self.ids_stop.get_linktab().get_inds(ids)
+ timestep_int = int(timestep)
+- for attrname, values in kwargs.iteritems():
++ for attrname, values in kwargs.items():
+ # print ' record',attrname,'dtype',values.dtype,values.shape, 'array',getattr(self,attrname).get_value().dtype,'shape', getattr(self,attrname).get_value().shape
+ # print ' inds',type(inds),inds.dtype,
+ getattr(self, attrname).get_value()[inds, timestep_int] = values
+
+ def get_stopresultattrconfigs(self):
+- return self.get_attrsman().get_group_attrs('PRT results').values()
++ return list(self.get_attrsman().get_group_attrs('PRT results').values())
+
+ def get_persons(self):
+ return self.ids_person.get_linktab()
+--- tools/contributed/sumopy/plugins/prt/results_mpl.py (original)
++++ tools/contributed/sumopy/plugins/prt/results_mpl.py (refactored)
+@@ -46,7 +46,7 @@
+ self._init_common('stopresultsplotter', parent=results, name=name,
+ info=info, logger=logger)
+
+- print 'StopresultsPlotter.__init__', results, self.parent, len(self.get_stopresults())
++ print('StopresultsPlotter.__init__', results, self.parent, len(self.get_stopresults()))
+ attrsman = self.get_attrsman()
+
+ stops = self.get_stopresults().get_prtstops()
+@@ -134,10 +134,10 @@
+
+ def show(self):
+ stopresults = self.get_stopresults()
+- print 'show', stopresults
++ print('show', stopresults)
+ # print ' dir(vehicleman)',dir(vehicleman)
+
+- print ' len(stopresults)', len(stopresults)
++ print(' len(stopresults)', len(stopresults))
+ if len(stopresults) > 0:
+ i_fig = 0
+ plt.close("all")
+@@ -169,7 +169,7 @@
+ plt.show()
+
+ def plot_flow_stop(self, fig):
+- print 'plot_flow_stop'
++ print('plot_flow_stop')
+ id_stop = self.id_stop_plot
+ stopresults = self.get_stopresults()
+ ax = fig.add_subplot(111)
+@@ -227,7 +227,7 @@
+ ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ def plot_waiting_person_time(self, fig):
+- print 'plot_waiting_person_time'
++ print('plot_waiting_person_time')
+ stopresults = self.get_stopresults()
+ ax = fig.add_subplot(111)
+
+@@ -254,7 +254,7 @@
+ ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ def plot_waiting_person_number_stop(self, fig):
+- print 'plot_waiting_person_number_stop'
++ print('plot_waiting_person_number_stop')
+ stopresults = self.get_stopresults()
+ #ax1 = fig.add_subplot(211)
+ #ax2 = fig.add_subplot(212)
+@@ -278,7 +278,7 @@
+ ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ def plot_waiting_person_number(self, fig):
+- print 'plot_waiting_person_number'
++ print('plot_waiting_person_number')
+ stopresults = self.get_stopresults()
+ #ax1 = fig.add_subplot(211)
+ #ax2 = fig.add_subplot(212)
+@@ -291,7 +291,7 @@
+ # works:ax.plot(time.reshape(n_steps,1),numbers_person_wait.reshape(n_steps,-1))
+ i = 0
+ for id_stop in stopresults.ids_stop.get_value():
+- print ' id_stop', id_stop
++ print(' id_stop', id_stop)
+ ax.plot(time, stopresults.numbers_person_wait[id_stop],
+ COLORS[i], linewidth=self.width_line,
+ label='PRT Stop ID=%d' % id_stop)
+@@ -305,7 +305,7 @@
+ ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ def plot_flows_compare(self, fig):
+- print 'plot_flows_compare'
++ print('plot_flows_compare')
+ stopresults = self.get_stopresults()
+ #time_update_flows = self.parent.vehicleman.time_update_flows.get_value()
+ time_update_flows = 10
+@@ -318,7 +318,7 @@
+ i = 0
+ flowmatrix = np.zeros((10, 10), dtype=np.int32)
+ for id_stop in stopresults.ids_stop.get_value():
+- print ' id_stop', id_stop
++ print(' id_stop', id_stop)
+ # print ' sched',stopresults.inflows_veh_sched[id_stop]
+ # print ' eff ',stopresults.inflows_veh[id_stop]
+ flowmatrix[np.array(time_update_flows*stopresults.inflows_veh_sched[id_stop], dtype=np.int32),
+@@ -328,7 +328,7 @@
+ # label = 'PRT Stop ID=%d (effective)'%id_stop)
+
+ i += 1
+- print 'flowmatrix', flowmatrix
++ print('flowmatrix', flowmatrix)
+ # ax.matshow(flowmatrix)
+
+ cax = ax.matshow(flowmatrix, cmap=cmx.get_cmap('PuBu'))
+@@ -341,7 +341,7 @@
+ ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ def plot_flows_compare_stop(self, fig):
+- print 'plot_flows_compare_stop'
++ print('plot_flows_compare_stop')
+ stopresults = self.get_stopresults()
+ id_stop = self.id_stop_plot
+ #time_update_flows = self.parent.vehicleman.time_update_flows.get_value()
+@@ -361,7 +361,7 @@
+
+ time = np.arange(-n_steps+1, n_steps, dtype=np.float32)*t_step
+
+- print ' len(flowcorr),n_steps', len(flowcorr), len(time), n_steps
++ print(' len(flowcorr),n_steps', len(flowcorr), len(time), n_steps)
+
+ ax.plot(time, flowcorr,
+ COLORS[i], linewidth=self.width_line,
+@@ -375,7 +375,7 @@
+ ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
+
+ def plot_flows(self, fig):
+- print 'plot_flows'
++ print('plot_flows')
+ stopresults = self.get_stopresults()
+ ax = fig.add_subplot(111)
+
+@@ -411,7 +411,7 @@
+ # ('inflows_person', {'name':'Person in-flows', 'unit':'1/s', 'dtype':np.float32, 'info':'Person flow into the stop over time.'}),
+
+ def plot_waiting_person(self, fig):
+- print 'plot_waiting_person'
++ print('plot_waiting_person')
+ stopresults = self.get_stopresults()
+ ax1 = fig.add_subplot(211)
+ ax2 = fig.add_subplot(212)
+--- tools/contributed/sumopy/plugins/prt/wxgui.py (original)
++++ tools/contributed/sumopy/plugins/prt/wxgui.py (refactored)
+@@ -28,13 +28,13 @@
+ from coremodules.network import routing
+ from coremodules.demand import demand
+ from coremodules.simulation import sumo, results
+-import prt
++from . import prt
+
+ try:
+- import results_mpl as results_mpl
++ from . import results_mpl as results_mpl
+ is_mpl = True # we have matplotlib support
+ except:
+- print "WARNING: python matplotlib package not installed, no matplotlib plots."
++ print("WARNING: python matplotlib package not installed, no matplotlib plots.")
+ is_mpl = False
+
+
+@@ -336,7 +336,7 @@
+ dependent on the availability of data.
+ """
+ scenario = self.get_scenario()
+- print 'prtgui.refresh_widgets', self._simulation != scenario.simulation
++ print('prtgui.refresh_widgets', self._simulation != scenario.simulation)
+
+ is_refresh = False
+ if self._simulation != scenario.simulation:
+@@ -499,7 +499,7 @@
+ self._mainframe.browse_obj(self._prtservice.prtvehicles)
+
+ def on_mpl_stopresults(self, event=None):
+- print 'on_mpl_stopresults', id(self._simulation.results) # ,id(self._prtservice.get_results())
++ print('on_mpl_stopresults', id(self._simulation.results)) # ,id(self._prtservice.get_results())
+ if self._prtservice is not None:
+ if self._simulation is not None:
+ resultplotter = results_mpl.StopresultsPlotter(self._simulation.results, # self._prtservice.get_results(),
diff --git a/tools/contributed/sumopy/plugins/common/__init__.py b/tools/contributed/sumopy/plugins/common/__init__.py
index cab987aa8f9c..02fdf630fcec 100644
--- a/tools/contributed/sumopy/plugins/common/__init__.py
+++ b/tools/contributed/sumopy/plugins/common/__init__.py
@@ -18,12 +18,12 @@
__version__ = "0.0"
-print 'init', __name__
+print('init', __name__)
def get_wxgui():
# try:
- from wxgui import WxGui
+ from .wxgui import WxGui
return WxGui(__name__)
# except:
# return None
diff --git a/tools/contributed/sumopy/plugins/hcprt/__init__.py b/tools/contributed/sumopy/plugins/hcprt/__init__.py
index cab987aa8f9c..02fdf630fcec 100644
--- a/tools/contributed/sumopy/plugins/hcprt/__init__.py
+++ b/tools/contributed/sumopy/plugins/hcprt/__init__.py
@@ -18,12 +18,12 @@
__version__ = "0.0"
-print 'init', __name__
+print('init', __name__)
def get_wxgui():
# try:
- from wxgui import WxGui
+ from .wxgui import WxGui
return WxGui(__name__)
# except:
# return None
diff --git a/tools/contributed/sumopy/plugins/hcprt/hcprt.py b/tools/contributed/sumopy/plugins/hcprt/hcprt.py
index bade0217eee3..66bddde99017 100644
--- a/tools/contributed/sumopy/plugins/hcprt/hcprt.py
+++ b/tools/contributed/sumopy/plugins/hcprt/hcprt.py
@@ -148,7 +148,7 @@ def _init_constants(self):
])
def make(self, id_detectoredge=None, **kwargs):
- print 'make', kwargs
+ print('make', kwargs)
# print ' ids_shuntedge',kwargs.get('ids_shuntedge',None),type(kwargs.get('ids_shuntedge',None)[0])
id_comp = self.add_row(ids_shuntedges=kwargs.get('ids_shuntedge', None),
ids_detectoredge=id_detectoredge
@@ -158,13 +158,13 @@ def make(self, id_detectoredge=None, **kwargs):
return id_comp
def update(self, id_comp):
- print 'update id_comp', id_comp
+ print('update id_comp', id_comp)
edges = self.get_scenario().net.edges
self.ids_detectoredge[id_comp] = edges.get_incoming(self.ids_shuntedges[id_comp][0])[0]
def update_all(self):
- print 'update_all'
+ print('update_all')
for id_comp in self.get_ids():
self.update(id_comp)
@@ -172,7 +172,7 @@ def get_scenario(self):
return self.parent.get_scenario()
def prepare_sim(self, process):
- print 'Compressors.prepare_sim'
+ print('Compressors.prepare_sim')
net = self.get_scenario().net
nodes = net.nodes
edges = net.edges
@@ -220,14 +220,14 @@ def prepare_sim(self, process):
self.ids_vehs_detect_sumo = np.zeros(n_id_max, dtype=np.object)
for id_comp, ids_shuntedge in zip(ids, self.ids_shuntedges[ids]):
- print ' id_comp', id_comp
+ print(' id_comp', id_comp)
n_shunts = len(ids_shuntedge) # first edge is not a real shunt!!
queues = n_shunts*[None]
queues_alloc = n_shunts*[None]
capacities = n_shunts*[None]
- for i, length_edge in zip(range(n_shunts), edges.lengths[ids_shuntedge]):
+ for i, length_edge in zip(list(range(n_shunts)), edges.lengths[ids_shuntedge]):
capacities[i] = max(2, int((length_edge-30.0)/(self.length_veh+0.5)))
queues[i] = []
queues_alloc[i] = []
@@ -240,16 +240,16 @@ def prepare_sim(self, process):
self.releasetimes_queues[id_comp] = n_shunts*[0]
self.ids_vehs_detect_sumo[id_comp] = set()
- print ' capacities', self.capacitiess[id_comp]
- print ' queues', self.queuess[id_comp]
+ print(' capacities', self.capacitiess[id_comp])
+ print(' queues', self.queuess[id_comp])
return [(self.time_update.get_value(), self.process_step),
]
def process_step(self, process):
simtime = process.simtime
- print 79*'_'
- print 'Compressors.process_step at', simtime
+ print(79*'_')
+ print('Compressors.process_step at', simtime)
net = self.get_scenario().net
edges = net.edges
vehicles = self.parent.prtvehicles
@@ -276,19 +276,19 @@ def process_step(self, process):
self.releasetimes_queues[ids],
):
n_queues = len(queues)
- print ' '+30*'><'
- print ' Compressor id_comp', id_comp, 'n_queues', n_queues
+ print(' '+30*'><')
+ print(' Compressor id_comp', id_comp, 'n_queues', n_queues)
# check for new vehicle arrivals/departures
ids_veh_entered_sumo, ids_veh_left_sumo, ids_veh_new_sumo = vehicles.get_entered_left(
id_detectedge_sumo, ids_veh_detect_sumo)
if 1:
- print ' id_detectedge_sumo', id_detectedge_sumo
- print ' ids_veh_detect_sumo', ids_veh_detect_sumo
- print ' ids_veh_new_sumo', ids_veh_new_sumo
- print ' ids_veh_entered_sumo=', ids_veh_entered_sumo
- print ' ids_veh_left_sumo=', ids_veh_left_sumo
+ print(' id_detectedge_sumo', id_detectedge_sumo)
+ print(' ids_veh_detect_sumo', ids_veh_detect_sumo)
+ print(' ids_veh_new_sumo', ids_veh_new_sumo)
+ print(' ids_veh_entered_sumo=', ids_veh_entered_sumo)
+ print(' ids_veh_left_sumo=', ids_veh_left_sumo)
if len(ids_veh_entered_sumo) > 0:
@@ -306,7 +306,7 @@ def process_step(self, process):
# no platoon, it is a single vehicle
id_targetedge_sumo = traci.vehicle.getRoute(id_veh_entered_sumo)[-1]
ids_shuntedge_sumo = edges.ids_sumo[ids_shuntedge]
- print ' dispatch id_veh_entered_sumo %s' % id_veh_entered_sumo, id_targetedge_sumo, ids_edge_sumo_target
+ print(' dispatch id_veh_entered_sumo %s' % id_veh_entered_sumo, id_targetedge_sumo, ids_edge_sumo_target)
is_found_queue = False
inds_queue = np.flatnonzero((np.array(ids_edge_sumo_target, object)
@@ -339,7 +339,7 @@ def process_step(self, process):
# print ' no queue with target or specific queue is full, search for a new queue'
is_found_queue = False
- for ind_queue, queue in zip(range(1, n_queues), queues[1:]):
+ for ind_queue, queue in zip(list(range(1, n_queues)), queues[1:]):
if len(queue) == 0:
is_found_queue = True
break
@@ -354,7 +354,7 @@ def process_step(self, process):
# print ' all queues are busy, let vehicle %s go ahead'%id_veh_entered_sumo
pass
else:
- print ' configure target of new queue', ind_queue, id_targetedge_sumo
+ print(' configure target of new queue', ind_queue, id_targetedge_sumo)
ids_edge_sumo_target[ind_queue] = id_targetedge_sumo
self._alloc_queue(queues[ind_queue],
queues_alloc[ind_queue],
@@ -384,14 +384,14 @@ def process_step(self, process):
capacity, id_edge_sumo_target,\
id_shuntedge_sumo, releasetime_queue\
in zip(
- range(n_queues), queues, queues_alloc,
+ list(range(n_queues)), queues, queues_alloc,
capacities, ids_edge_sumo_target,
edges.ids_sumo[ids_shuntedge], releasetime_queues):
if 0:
- print ' OOOO shunt %s --> target %s' % (id_shuntedge_sumo, id_edge_sumo_target)
- print ' simtime-releasetime_queue', simtime-releasetime_queue
- print ' queue', queue, id(queue)
- print ' queue_alloc', queue_alloc
+ print(' OOOO shunt %s --> target %s' % (id_shuntedge_sumo, id_edge_sumo_target))
+ print(' simtime-releasetime_queue', simtime-releasetime_queue)
+ print(' queue', queue, id(queue))
+ print(' queue_alloc', queue_alloc)
# check if allocated arrived
ids_veh_arrived = []
@@ -411,7 +411,7 @@ def process_step(self, process):
# here we coukd also test timeout conditions
if ((len_queue == capacity) | ((simtime - releasetime_queue) > self.time_accumulation_max.get_value())) & (simtime - self.releasetimes[id_comp] > self.time_release_min.get_value()):
# queue is full
- print ' platoon and send vehicles:', queue
+ print(' platoon and send vehicles:', queue)
# action 1
# platoon all vehicles in queue, starting from last in queue
for i in range(len_queue-1, 0, -1):
@@ -472,7 +472,7 @@ def _init_constants(self):
])
def prepare_sim(self, process):
- print 'Decompressors.prepare_sim'
+ print('Decompressors.prepare_sim')
net = self.get_scenario().net
nodes = net.nodes
edges = net.edges
@@ -521,14 +521,14 @@ def prepare_sim(self, process):
self.ids_vehs_detect_sumo = np.zeros(n_id_max, dtype=np.object)
for id_comp, ids_shuntedge in zip(ids, self.ids_shuntedges[ids]):
- print ' id_comp', id_comp
+ print(' id_comp', id_comp)
n_shunts = len(ids_shuntedge) # first edge is not a real shunt!!
queues = n_shunts*[None]
queues_alloc = n_shunts*[None]
capacities = n_shunts*[None]
ids_targetedges_sumo = n_shunts*[None]
- for i, length_edge in zip(range(n_shunts), edges.lengths[ids_shuntedge]):
+ for i, length_edge in zip(list(range(n_shunts)), edges.lengths[ids_shuntedge]):
capacities[i] = int((length_edge-25.0)/(self.length_veh+0.5))
queues[i] = []
queues_alloc[i] = []
@@ -551,8 +551,8 @@ def prepare_sim(self, process):
def process_step(self, process):
simtime = process.simtime
- print 79*'_'
- print 'Deompressors.process_step at', simtime
+ print(79*'_')
+ print('Deompressors.process_step at', simtime)
net = self.get_scenario().net
edges = net.edges
vehicles = self.parent.prtvehicles
@@ -580,17 +580,17 @@ def process_step(self, process):
):
n_queues = len(queues)
ids_shuntedge_sumo = edges.ids_sumo[ids_shuntedge]
- print ' '+60*'|'
- print ' Decompressor id_comp', id_comp, 'n_queues', n_queues
+ print(' '+60*'|')
+ print(' Decompressor id_comp', id_comp, 'n_queues', n_queues)
# check for new vehicle arrivals/departures
ids_veh_sumo = set(traci.edge.getLastStepVehicleIDs(id_detectedge_sumo))
if 0:
- print ' id_detectedge_sumo', id_detectedge_sumo
- print ' ids_veh_detect_sumo', ids_veh_detect_sumo, ids_veh_detect_sumo != ids_veh_sumo
- print ' ids_veh_sumo=', ids_veh_sumo
+ print(' id_detectedge_sumo', id_detectedge_sumo)
+ print(' ids_veh_detect_sumo', ids_veh_detect_sumo, ids_veh_detect_sumo != ids_veh_sumo)
+ print(' ids_veh_sumo=', ids_veh_sumo)
ids_veh_sumo_raw = traci.edge.getLastStepVehicleIDs(id_detectedge_sumo)
- print ' ids_veh_sumo_raw=', ids_veh_sumo_raw
+ print(' ids_veh_sumo_raw=', ids_veh_sumo_raw)
if ids_veh_detect_sumo != ids_veh_sumo:
# there are new vehicles
@@ -600,12 +600,12 @@ def process_step(self, process):
ids_veh_entered = vehicles.get_ids_from_ids_sumo(ids_veh_entered_sumo)
if 1:
- print ' ids_veh_entered', ids_veh_entered, type(ids_veh_entered)
+ print(' ids_veh_entered', ids_veh_entered, type(ids_veh_entered))
# print ' poss',poss
- print ' ids_veh_entered_sumo', ids_veh_entered_sumo
- print ' ids_leader', vehicles.ids_leader[ids_veh_entered]
- print ' ids_follower', vehicles.ids_follower[ids_veh_entered]
- print ' lengths_plat', vehicles.lengths_plat[ids_veh_entered]
+ print(' ids_veh_entered_sumo', ids_veh_entered_sumo)
+ print(' ids_leader', vehicles.ids_leader[ids_veh_entered])
+ print(' ids_follower', vehicles.ids_follower[ids_veh_entered])
+ print(' lengths_plat', vehicles.lengths_plat[ids_veh_entered])
for id_veh_entered, id_veh_entered_sumo, id_leader, length_plat\
in zip(ids_veh_entered, ids_veh_entered_sumo,
@@ -623,7 +623,7 @@ def process_step(self, process):
is_found_queue = False
costs = np.zeros(n_queues, dtype=np.float32)
- for ind_queue, queue, is_avail, capa in zip(range(n_queues), queues, are_queue_avail, capacities):
+ for ind_queue, queue, is_avail, capa in zip(list(range(n_queues)), queues, are_queue_avail, capacities):
dl = (capa - len(queue)) * self.length_veh - 2*length_plat
# print ' ceck queue %d with capa %d, len = %d, dl=%d'%(ind_queue,capa,len(queue),dl)
@@ -657,7 +657,7 @@ def process_step(self, process):
# shunt it to the same edge as its leader
id_targetedge_sumo = traci.vehicle.getRoute(id_veh_entered_sumo)[-1]
id_platoonleader = vehicles.get_platoonleader(id_leader)
- for ind_queue, queue, capa_queue, in zip(range(n_queues), queues, capacities):
+ for ind_queue, queue, capa_queue, in zip(list(range(n_queues)), queues, capacities):
if id_platoonleader in queue:
# print ' found id_platoonleader prt.%d of prt.%d at queue %d'%(id_platoonleader,id_veh_entered,ind_queue)
self._alloc_queue_follower(
@@ -688,16 +688,16 @@ def process_step(self, process):
ids_targetedge_sumo, capacity,\
id_shuntedge_sumo, releasetime_queue\
in zip(
- range(n_queues), queues, queues_alloc,
+ list(range(n_queues)), queues, queues_alloc,
ids_targetedges_sumo, capacities,
edges.ids_sumo[ids_shuntedge], releasetime_queues):
if 0:
- print ' QQQQQQQQQQQ shunt %s ' % (id_shuntedge_sumo)
- print ' simtime-releasetime_queue', simtime-releasetime_queue, (simtime - releasetime_queue > 15), (simtime - self.releasetimes[id_comp] > 10)
- print ' queue', queue, id(queue)
- print ' ids_targetedge_sumo', ids_targetedge_sumo
- print ' queue_alloc', queue_alloc
- print ' releasetime_queue', releasetime_queue, simtime - releasetime_queue, simtime - releasetime_queue > self.time_accumulation_max.get_value()
+ print(' QQQQQQQQQQQ shunt %s ' % (id_shuntedge_sumo))
+ print(' simtime-releasetime_queue', simtime-releasetime_queue, (simtime - releasetime_queue > 15), (simtime - self.releasetimes[id_comp] > 10))
+ print(' queue', queue, id(queue))
+ print(' ids_targetedge_sumo', ids_targetedge_sumo)
+ print(' queue_alloc', queue_alloc)
+ print(' releasetime_queue', releasetime_queue, simtime - releasetime_queue, simtime - releasetime_queue > self.time_accumulation_max.get_value())
# here we could also test timeout conditions
if (simtime - self.releasetimes[id_comp] > self.time_release_min.get_value()) & (simtime - releasetime_queue > self.time_accumulation_max.get_value()):
# if (simtime - self.releasetimes[id_comp]> self.time_release_min.get_value()):
@@ -725,7 +725,7 @@ def process_step(self, process):
if len_queue > ind_pl+1:
- for i, id_veh in zip(range(ind_pl+1, len_queue), queue[ind_pl+1:]):
+ for i, id_veh in zip(list(range(ind_pl+1, len_queue)), queue[ind_pl+1:]):
# print ' check prt.%d with leader prt.%d'%(id_veh,vehicles.ids_leader[id_veh])
if vehicles.ids_leader[id_veh] != -1:
# print ' real lead prt.%d qlead prt.%d | plat lead prt.%d plat qlead prt.%d '%(vehicles.ids_leader[id_veh],queue[i-1],vehicles.get_platoonleader(id_veh),id_veh_arrived)
@@ -776,7 +776,7 @@ def process_step(self, process):
del ids_targetedge_sumo[id_veh_arrived]
else:
- print ' platoon incomplete'
+ print(' platoon incomplete')
else:
# print ' no leaders arrived in this quque'
pass
@@ -924,7 +924,7 @@ def make_from_net(self):
"""
Make merge node database from network.
"""
- print 'Mergenodes.make_from_net'
+ print('Mergenodes.make_from_net')
self.clear()
id_prtmode = self.parent.id_prtmode
@@ -943,9 +943,9 @@ def make_from_net(self):
# debug
ids_edge = edges.get_ids()
- print 'distances:'
+ print('distances:')
for id_edge, id_edge_sumo, length, dist in zip(ids_edge, edges.ids_sumo[ids_edge], edges.lengths[ids_edge], distances[ids_edge]):
- print ' id_edge=%d id_edge_sumo=%s length=%.1f dist=%.1f' % (id_edge, id_edge_sumo, length, dist)
+ print(' id_edge=%d id_edge_sumo=%s length=%.1f dist=%.1f' % (id_edge, id_edge_sumo, length, dist))
ids_shuntedges = set()
ids_mainlinedges = set()
@@ -953,9 +953,9 @@ def make_from_net(self):
ids = compressors.get_ids()
for id_unit, ids_edge in zip(ids, compressors.ids_shuntedges[ids]):
# put in all shunts except for the bypass
- print ' bypass of compressor', id_unit, '=', ids_edge[0]
+ print(' bypass of compressor', id_unit, '=', ids_edge[0])
ids_mainlinedges.add(ids_edge[0])
- print ' update ids_shuntedges with compressors', ids_edge[1:]
+ print(' update ids_shuntedges with compressors', ids_edge[1:])
ids_shuntedges.update(ids_edge[1:])
# collect decompressornodes, wich will not become entry merges
@@ -963,12 +963,12 @@ def make_from_net(self):
ids_node_decompressorout = []
for id_unit, ids_edge in zip(ids, decompressors.ids_shuntedges[ids]):
# put in all shunts except for the bypass
- print ' bypass of decompressor', id_unit, '=', ids_edge[0], 'id_tonode', edges.ids_tonode[ids_edge[0]]
+ print(' bypass of decompressor', id_unit, '=', ids_edge[0], 'id_tonode', edges.ids_tonode[ids_edge[0]])
ids_mainlinedges.add(ids_edge[0])
ids_node_decompressorout.append(edges.ids_tonode[ids_edge[0]])
- print ' update ids_shuntedges with decompressors', ids_edge[1:]
+ print(' update ids_shuntedges with decompressors', ids_edge[1:])
ids_shuntedges.update(ids_edge[1:])
- print ' ids_node_decompressorout', ids_node_decompressorout
+ print(' ids_node_decompressorout', ids_node_decompressorout)
ids_node_compressorout = edges.ids_tonode[list(ids_mainlinedges)]
ids_mainlinefromnodes = edges.ids_fromnode[list(ids_mainlinedges)]
@@ -978,7 +978,7 @@ def make_from_net(self):
# print ' update ids_shuntedges with mainline incoming',edges.get_incoming(id_edge)
# ids_shuntedges.update(edges.get_incoming(id_edge))
- print ' ids_shuntedges', ids_shuntedges
+ print(' ids_shuntedges', ids_shuntedges)
#ids_ptstop = ptstops.get_ids()
#id_mode_prt = self.parent.id_prtmode
@@ -988,7 +988,7 @@ def make_from_net(self):
#edgelengths = net.edges.lengths
ids_node = nodes.get_ids()
- print ' ids_node', ids_node
+ print(' ids_node', ids_node)
for id_node, ids_edge_from, ids_edge_to, id_type in zip(
ids_node,
nodes.ids_incoming[ids_node],
@@ -999,15 +999,15 @@ def make_from_net(self):
if True:
#
- print 79*'-'
- print ' check node', id_node, nodes.ids_sumo[id_node], id_type, id_zippertype == id_type
- print ' ids_edge_from', ids_edge_from
- print ' ids_edge_to', ids_edge_to
+ print(79*'-')
+ print(' check node', id_node, nodes.ids_sumo[id_node], id_type, id_zippertype == id_type)
+ print(' ids_edge_from', ids_edge_from)
+ print(' ids_edge_to', ids_edge_to)
# id merge to be created, for debugging
id_merge = -1
if (ids_edge_from is None) | (ids_edge_to is None):
- print ' WARNING: isolate node: ids_edge_from,ids_edge_to', ids_edge_from, ids_edge_to
+ print(' WARNING: isolate node: ids_edge_from,ids_edge_to', ids_edge_from, ids_edge_to)
pass
elif (len(ids_edge_from) == 2) & (len(ids_edge_to) == 1):
@@ -1018,13 +1018,13 @@ def make_from_net(self):
# check accesslevels
id_edge1, id_edge2 = ids_edge_from
ids_lane1, ids_lane2 = edges.ids_lanes[ids_edge_from]
- print ' id_edge1', id_edge1, 'ids_lane1', ids_lane1, self.is_prt_only(ids_lane1, lanes)
- print ' id_edge2', id_edge2, 'ids_lane2', ids_lane2, self.is_prt_only(ids_lane2, lanes)
+ print(' id_edge1', id_edge1, 'ids_lane1', ids_lane1, self.is_prt_only(ids_lane1, lanes))
+ print(' id_edge2', id_edge2, 'ids_lane2', ids_lane2, self.is_prt_only(ids_lane2, lanes))
if self.is_prt_only(ids_lane1, lanes) & self.is_prt_only(ids_lane2, lanes):
- print ' +PRT merge with 2 PRT lines entering'
+ print(' +PRT merge with 2 PRT lines entering')
if id_type != id_zippertype:
- print 'WARNING: PRT network node %d %s is NOT in zipper mode!' % (id_node, nodes.ids_sumo[id_node])
+ print('WARNING: PRT network node %d %s is NOT in zipper mode!' % (id_node, nodes.ids_sumo[id_node]))
# elif not ids_mainlinedges.isdisjoint(ids_edge_from):
# print ' one incoming line is the bypass'
@@ -1037,16 +1037,16 @@ def make_from_net(self):
# )
else:
- print ' make regular merge'
- print ' branch 1:'
+ print(' make regular merge')
+ print(' branch 1:')
id_node_up1, dist1 = self.search_upstream_merge(
id_edge1, edges, lanes, id_prtmode, distances=distances)
- print ' id_node_up1', id_node_up1, 'dist1', dist1
+ print(' id_node_up1', id_node_up1, 'dist1', dist1)
- print '\n branch 2:'
+ print('\n branch 2:')
id_node_up2, dist2 = self.search_upstream_merge(
id_edge2, edges, lanes, id_prtmode, distances=distances)
- print ' id_node_up2', id_node_up1, 'dist2', dist2, '\n'
+ print(' id_node_up2', id_node_up1, 'dist2', dist2, '\n')
ids_node_out = self.search_downstream_merges(
ids_edge_to[0], edges, lanes, id_prtmode, ids_sinkedge=ids_shuntedges)
@@ -1066,7 +1066,7 @@ def make_from_net(self):
#al_in = lanes.get_accesslevel(edges.ids_lanes[id_edge_from], id_prtmode)
#is_prt_in = lanes.ids_modes_allow[edges.ids_lanes[id_edge_from]] == id_prtmode
is_prt_in = self.is_prt_only(ids_lane_in, lanes)
- print ' one in, 2 out => diverge node, access is_prt_in', is_prt_in, 'is_platform_in', self.is_platform(ids_lane_in, lanes)
+ print(' one in, 2 out => diverge node, access is_prt_in', is_prt_in, 'is_platform_in', self.is_platform(ids_lane_in, lanes))
# if id_edge_from in ids_detectoredges:
# print ' fromnode is a detectoredge of a compressor'
@@ -1081,7 +1081,7 @@ def make_from_net(self):
# check if node is outgoing node at a station
if 0: # no longer considered
if is_prt_in & (id_node in ids_mainlinefromnodes):
- print ' Diverge node in front of a compressor/decompressorr.'
+ print(' Diverge node in front of a compressor/decompressorr.')
id_node_up, dist = self.search_upstream_merge(id_edge_from, edges, lanes, id_prtmode)
id_edge1, id_edge2 = ids_edge_to
@@ -1100,19 +1100,19 @@ def make_from_net(self):
)
if self.is_platform(ids_lane_in, lanes):
- print ' mixed access level of incoming edge, check for platform exit node'
+ print(' mixed access level of incoming edge, check for platform exit node')
id_edge1, id_edge2 = ids_edge_to
ids_lane1, ids_lane2 = edges.ids_lanes[ids_edge_to]
# here we could also decide on the number of lanes
# but this may not be robust in the future
- print ' out id_edge1', id_edge1, 'ids_lane1', ids_lane1, 'is_prt_only', self.is_prt_only(ids_lane1, lanes)
- print ' out id_edge2', id_edge2, 'ids_lane2', ids_lane2, 'is_prt_only', self.is_prt_only(ids_lane2, lanes)
+ print(' out id_edge1', id_edge1, 'ids_lane1', ids_lane1, 'is_prt_only', self.is_prt_only(ids_lane1, lanes))
+ print(' out id_edge2', id_edge2, 'ids_lane2', ids_lane2, 'is_prt_only', self.is_prt_only(ids_lane2, lanes))
# if self.is_prt_only(ids_lane1, lanes) & self.is_prt_only(ids_lane2, lanes):
if self.is_prt_only(ids_lane2, lanes):
- print ' Ped exit on outedge 1'
+ print(' Ped exit on outedge 1')
#id_node_up, dist = self.search_upstream_merge(id_edge_from, edges, lanes, id_prtmode)
ids_node_out = self.search_downstream_merges(
id_edge2, edges, lanes, id_prtmode, ids_sinkedge=ids_shuntedges)
@@ -1124,7 +1124,7 @@ def make_from_net(self):
)
elif self.is_prt_only(ids_lane1, lanes):
- print ' Ped exit on outedge 2'
+ print(' Ped exit on outedge 2')
#id_node_up, dist = self.search_upstream_merge(id_edge_from, edges, lanes, id_prtmode)
ids_node_out = self.search_downstream_merges(
id_edge1, edges, lanes, id_prtmode, ids_sinkedge=ids_shuntedges)
@@ -1137,7 +1137,7 @@ def make_from_net(self):
if id_merge >= 0:
self.print_attrs(ids=[id_merge, ])
- print '\n now check if merge has entry line form stations or compressors'
+ print('\n now check if merge has entry line form stations or compressors')
ids = self.get_ids()
i = 0
@@ -1146,21 +1146,21 @@ def make_from_net(self):
id_node_in1 = self.ids_node_in1[id_merge]
id_node_in2 = self.ids_node_in2[id_merge]
- print 79*'-'
- print ' check entry of id_merge', id_merge, 'id_node', self.ids_node[id_merge], ' no decomp', self.ids_node[id_merge] not in ids_node_decompressorout
+ print(79*'-')
+ print(' check entry of id_merge', id_merge, 'id_node', self.ids_node[id_merge], ' no decomp', self.ids_node[id_merge] not in ids_node_decompressorout)
if (id_node_in1 > -1) & (id_node_in2 > -1)\
& (self.ids_node[id_merge] not in ids_node_decompressorout):
- print ' id_node_in1', self.ids_node_in1[id_merge], nodes.ids_sumo[self.ids_node_in1[id_merge]], self.ids_node.has_index(self.ids_node_in1[id_merge])
- print ' id_node_in2', self.ids_node_in2[id_merge], nodes.ids_sumo[self.ids_node_in2[id_merge]], self.ids_node.has_index(self.ids_node_in2[id_merge])
+ print(' id_node_in1', self.ids_node_in1[id_merge], nodes.ids_sumo[self.ids_node_in1[id_merge]], self.ids_node.has_index(self.ids_node_in1[id_merge]))
+ print(' id_node_in2', self.ids_node_in2[id_merge], nodes.ids_sumo[self.ids_node_in2[id_merge]], self.ids_node.has_index(self.ids_node_in2[id_merge]))
if 1:
- print ' self.ids_node._index_to_id', self.ids_node._index_to_id
+ print(' self.ids_node._index_to_id', self.ids_node._index_to_id)
id_merge_in1 = self.ids_node.get_id_from_index(self.ids_node_in1[id_merge])
id_merge_in2 = self.ids_node.get_id_from_index(self.ids_node_in2[id_merge])
- print ' station check id_merge', id_merge, 'id_merge_in1', id_merge_in1, 'station', self.are_station[id_merge_in1], 'id_merge_in2', id_merge_in2, 'station', self.are_station[id_merge_in2]
+ print(' station check id_merge', id_merge, 'id_merge_in1', id_merge_in1, 'station', self.are_station[id_merge_in1], 'id_merge_in2', id_merge_in2, 'station', self.are_station[id_merge_in2])
if self.are_station[id_merge_in2]:
self.are_entry[id_merge] = True
@@ -1186,7 +1186,7 @@ def get_scenario(self):
return self.parent.get_scenario()
def prepare_sim(self, process):
- print 'Mergenodes.prepare_sim'
+ print('Mergenodes.prepare_sim')
net = self.get_scenario().net
nodes = net.nodes
edges = net.edges
@@ -1294,8 +1294,8 @@ def prepare_sim(self, process):
def process_step(self, process):
simtime = process.simtime
- print 79*'_'
- print 'Mergenodes.process_step at', simtime
+ print(79*'_')
+ print('Mergenodes.process_step at', simtime)
net = self.get_scenario().net
vehicles = self.parent.prtvehicles
@@ -1311,7 +1311,7 @@ def process_step(self, process):
self.ids_vehs_out_sumo[ids],
self.are_entry[ids],
):
- print ' '+60*'.'
+ print(' '+60*'.')
####
debug = False # id_merge in [24,22,19]
@@ -1320,7 +1320,7 @@ def process_step(self, process):
#debug = debug | (id_merge==17)| ('gneJ29' in net.nodes.ids_sumo[ids_node_out])
###
- print ' process id_merge', id_merge, ',id_node', id_node, net.nodes.ids_sumo[id_node], 'debug', debug
+ print(' process id_merge', id_merge, ',id_node', id_node, net.nodes.ids_sumo[id_node], 'debug', debug)
# check for new vehicle arrivals/departures
ids_veh_sumo = set(traci.edge.getLastStepVehicleIDs(id_edge_out))
@@ -1342,7 +1342,7 @@ def process_step(self, process):
#ids_veh_left = vehicles.get_ids_from_ids_sumo(list(ids_veh_sumo_prev.difference(ids_veh_sumo)))
if debug:
- print ' ids_veh_entered', ids_veh_entered, type(ids_veh_entered)
+ print(' ids_veh_entered', ids_veh_entered, type(ids_veh_entered))
# print ' ids_veh_entered_sumo',ids_veh_entered_sumo
# print ' ids_leader',vehicles.ids_leader[ids_veh_entered]
@@ -1367,11 +1367,11 @@ def process_step(self, process):
id_veh_first, id_veh_last = self.ids_plat_wait_exit[id_merge]
if id_veh_first > -1:
if debug > 0:
- print ' platoon waiting for exit: id_veh_first prt.%d, id_veh_last prt.%d' % (id_veh_first, id_veh_last)
+ print(' platoon waiting for exit: id_veh_first prt.%d, id_veh_last prt.%d' % (id_veh_first, id_veh_last))
inds_entered = np.flatnonzero(vehicles.ids_leader[ids_veh_entered] > -1)
if np.any(id_veh_last == ids_veh_entered[inds_entered]):
if debug > 0:
- print ' last vehicle of platoon left merge -> exit leader prt.%d' % id_veh_first
+ print(' last vehicle of platoon left merge -> exit leader prt.%d' % id_veh_first)
self.exit_veh(id_veh_first, vehicles.get_id_sumo(id_veh_first), id_merge, vehicles, debug=debug)
self.ids_plat_wait_exit[id_merge] = [-1, -1]
@@ -1383,13 +1383,13 @@ def process_step(self, process):
inds_entered = []
if debug:
- print ' inds_entered', inds_entered
+ print(' inds_entered', inds_entered)
if len(inds_entered) > 0:
for ind_entered, id_veh in zip(inds_entered, ids_veh_entered[inds_entered]):
id_veh_sumo = ids_veh_entered_sumo[ind_entered]
if debug > 0:
- print ' >>try exiting vehicle', id_veh_sumo, 'is_leader', vehicles.ids_leader[id_veh] == -1, 'ids_node_out', ids_node_out, 'ids_merge_out', ids_merge_out
+ print(' >>try exiting vehicle', id_veh_sumo, 'is_leader', vehicles.ids_leader[id_veh] == -1, 'ids_node_out', ids_node_out, 'ids_merge_out', ids_merge_out)
# print ' route_sumo',route_sumo
@@ -1400,15 +1400,15 @@ def process_step(self, process):
if (id_veh_last != id_veh):
if id_veh_last not in ids_veh_entered:
if debug:
- print ' wait for last plat vehicle', id_veh_last
+ print(' wait for last plat vehicle', id_veh_last)
self.ids_plat_wait_exit[id_merge] = [id_veh, id_veh_last]
else:
if debug:
- print ' last plat vehicle', id_veh_last, 'after merge node, exit', id_veh_sumo
+ print(' last plat vehicle', id_veh_last, 'after merge node, exit', id_veh_sumo)
self.exit_veh(id_veh, id_veh_sumo, id_merge, vehicles, debug=debug)
else:
if debug:
- print ' vehicle', id_veh, 'has no platoon, exit', id_veh_sumo
+ print(' vehicle', id_veh, 'has no platoon, exit', id_veh_sumo)
self.exit_veh(id_veh, id_veh_sumo, id_merge, vehicles, debug=debug)
# exit from previous merge
@@ -1416,7 +1416,7 @@ def process_step(self, process):
# print ' vehicle',id_veh_sumo,'exits id_merge',id_merge
if debug > 0:
- print ' check which out mergenode are on the current route of the vehicle'
+ print(' check which out mergenode are on the current route of the vehicle')
if len(ids_merge_out) > 0:
@@ -1438,23 +1438,23 @@ def process_step(self, process):
mergeind = np.argmin(routeinds)
if debug: # debug>0:
- print ' route_sumo', route_sumo
- print ' routeinds', routeinds, 'downstream merge', routeinds[mergeind] < INFINT
+ print(' route_sumo', route_sumo)
+ print(' routeinds', routeinds, 'downstream merge', routeinds[mergeind] < INFINT)
# print ' ids_edge_mergeout_sumo',ids_edge_mergeout_sumo
# print ' mergeind,routeinds',mergeind,routeinds
# print ' ids_merge_out[mergeind]',ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind]
if routeinds[mergeind] < INFINT:
if debug:
- print ' next merge is on the route'
+ print(' next merge is on the route')
if self.are_entry[ids_merge_out[mergeind]]:
if debug:
- print ' call enter_veh_entry id_merge_out', ids_merge_out[mergeind]
+ print(' call enter_veh_entry id_merge_out', ids_merge_out[mergeind])
self.enter_veh_entry(
id_veh, id_veh_sumo, id_merge, ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind], vehicles, debug=debug)
else:
if debug:
- print ' call enter_veh id_merge_out', ids_merge_out[mergeind]
+ print(' call enter_veh id_merge_out', ids_merge_out[mergeind])
self.enter_veh(
id_veh, id_veh_sumo, id_merge, ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind], vehicles, debug=debug)
else:
@@ -1467,8 +1467,8 @@ def process_step(self, process):
else:
# ids_node_out is None
if debug:
- print ' There is a station or compressor shunt edges next'
- print ' completely disconnect from all merge and ghost controlls'
+ print(' There is a station or compressor shunt edges next')
+ print(' completely disconnect from all merge and ghost controlls')
# exit from previous merge
self.exit_veh(id_veh, id_veh_sumo, id_merge, vehicles)
@@ -1481,7 +1481,7 @@ def process_step(self, process):
self.process_step_entry(id_merge, vehicles, debug)
if 0:
- print '========check mergeprocess'
+ print('========check mergeprocess')
for id_merge, id_node_sumo, ids_veh_merged_sumo, ids_veh_merged in\
zip(ids,
net.nodes.ids_sumo[self.ids_node[ids]],
@@ -1489,11 +1489,11 @@ def process_step(self, process):
self.ids_vehs_merged[ids]
):
- print ' ', id_merge, id_node_sumo, ids_veh_merged_sumo
+ print(' ', id_merge, id_node_sumo, ids_veh_merged_sumo)
# print ' ids_veh_merged',ids_veh_merged
def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_control=False, debug=0):
- print 'exit_veh id_veh %s, id_merge_from %d ' % (id_veh_sumo, id_merge_from), 'entry', self.are_entry[id_merge_from], 'is_remove_from_control', is_remove_from_control
+ print('exit_veh id_veh %s, id_merge_from %d ' % (id_veh_sumo, id_merge_from), 'entry', self.are_entry[id_merge_from], 'is_remove_from_control', is_remove_from_control)
# print ' check for platooned vehicles:'
# vehicles.get_platoon(id_veh)
@@ -1519,10 +1519,10 @@ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_
id_veh_behind = self.ids_vehs_merged[id_merge_from][ind_pos+1]
id_veh_tail = vehicles.get_platoontail(id_veh) # get last in platoon
if debug > 0:
- print ' del ghost from veh behind prt.%d to platoon tail prt.%d' % (id_veh_behind, id_veh_tail)
+ print(' del ghost from veh behind prt.%d to platoon tail prt.%d' % (id_veh_behind, id_veh_tail))
vehicles.del_ghost(id_veh_behind, id_veh_tail)
if debug > 0:
- print ' check ghosts of behind prt.%d:' % id_veh_behind, vehicles.ids_ghosts[id_veh_behind]
+ print(' check ghosts of behind prt.%d:' % id_veh_behind, vehicles.ids_ghosts[id_veh_behind])
# is there a vehicle in front of the removed vehicle
# this happens if a vehicle is interactively deviated
if ind_pos > 0:
@@ -1536,18 +1536,18 @@ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_
dist_to_merge_infront = get_traci_distance(
vehicles.get_id_sumo(id_veh_infront), id_edge_mergeout_sumo, 3.0)
if debug:
- print ' now let the vehicle behind %d, d=%.2f' % (id_veh_behind, dist_to_merge_behind), 'see the vehicle in front %d, d=%.2f' % (id_veh_infront, dist_to_merge_infront)
+ print(' now let the vehicle behind %d, d=%.2f' % (id_veh_behind, dist_to_merge_behind), 'see the vehicle in front %d, d=%.2f' % (id_veh_infront, dist_to_merge_infront))
vehicles.add_ghost(id_veh_behind, id_veh_tail, dist_to_merge_behind, dist_to_merge_infront)
if debug > 0:
- print ' check ghosts of behind prt.%d:' % id_veh_behind, vehicles.ids_ghosts[id_veh_behind]
+ print(' check ghosts of behind prt.%d:' % id_veh_behind, vehicles.ids_ghosts[id_veh_behind])
# remove any possible ghosts from this vehicle to vehicles behind
# this can happen if this vehicle passed by its ghost vehicle
# should no longer happen
# vehicles.del_ghosts(id_veh)
if debug > 0:
- print ' check ghosts of prt.%d (no ghosts from this merge?):' % id_veh, vehicles.ids_ghosts[id_veh]
+ print(' check ghosts of prt.%d (no ghosts from this merge?):' % id_veh, vehicles.ids_ghosts[id_veh])
self.ids_vehs_merged[id_merge_from].pop(ind_pos) # remove(id_veh)
self.ids_vehs_merged_sumo[id_merge_from].pop(ind_pos) # remove(id_veh_sumo)
@@ -1561,31 +1561,31 @@ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_
self.ids_vehs_in1_sumo[id_merge_from].remove(id_veh_sumo) # .pop()
if self.are_entry[id_merge_from]:
if debug:
- print ' vehicle is involved in entry merge processes?', self.vehicles_mains[id_merge_from].has_key(id_veh)
+ print(' vehicle is involved in entry merge processes?', id_veh in self.vehicles_mains[id_merge_from])
- if self.vehicles_mains[id_merge_from].has_key(id_veh):
- if self.vehicles_entries[id_merge_from].has_key(id_veh):
+ if id_veh in self.vehicles_mains[id_merge_from]:
+ if id_veh in self.vehicles_entries[id_merge_from]:
state_veh = self.vehicles_entries[id_merge_from][id_veh]
- if state.has_key('id_veh_infront'):
+ if 'id_veh_infront' in state:
id_veh_infront = state['id_veh_infront']
id_veh_infront_sumo = vehicles.ids_sumo[id_veh_infront]
id_veh_infront_sumo_eff, dist_eff = getLeader(id_veh_infront_sumo)
- print ' should have this veh in front:', id_veh_infront_sumo, 'leader', id_veh_infront_sumo_eff, 'd=%.1fm' % dist_eff
+ print(' should have this veh in front:', id_veh_infront_sumo, 'leader', id_veh_infront_sumo_eff, 'd=%.1fm' % dist_eff)
if id_veh_infront_sumo_eff != id_veh_infront_sumo:
- print 'ERROR: faled merge of ', id_veh_sumo, 'exiting merge', id_merge_from
+ print('ERROR: faled merge of ', id_veh_sumo, 'exiting merge', id_merge_from)
sys.exit(1)
#
#id_veh_entry = self.vehicles_mains[id_merge_from][id_veh]
# TODO: this is still a lousy method, vehicles_mains neds to be improved
- for id_veh_entry, state in zip(self.vehicles_entries[id_merge_from].keys(), self.vehicles_entries[id_merge_from].values()):
+ for id_veh_entry, state in zip(list(self.vehicles_entries[id_merge_from].keys()), list(self.vehicles_entries[id_merge_from].values())):
#state = self.vehicles_entries[id_merge_from][id_veh_entry]
# if debug:
# print ' state before',state
- if state.has_key('id_veh_infront'):
+ if 'id_veh_infront' in state:
if state['id_veh_infront'] == id_veh:
del state['id_veh_infront']
- if state.has_key('id_veh_behind'):
+ if 'id_veh_behind' in state:
if state['id_veh_behind'] == id_veh:
del state['id_veh_behind']
# if debug:
@@ -1600,7 +1600,7 @@ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_
if self.are_entry[id_merge_from]:
if debug:
- print ' del veh prt.%s from vehicles_entries' % id_veh
+ print(' del veh prt.%s from vehicles_entries' % id_veh)
del self.vehicles_entries[id_merge_from][id_veh]
else:
pass
@@ -1615,12 +1615,12 @@ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_
# just be sure that the vehicle is not in any queue
# but actually this cannot happen
if id_veh in self.ids_vehs_in1[id_merge_from]:
- print 'WARNING in exit_veh: new veh %d should not be in inqueue 1' % id_veh
+ print('WARNING in exit_veh: new veh %d should not be in inqueue 1' % id_veh)
self.ids_vehs_in1[id_merge_from].remove(id_veh)
self.ids_vehs_in1_sumo[id_merge_from].remove(id_veh_sumo)
if id_veh in self.ids_vehs_in2[id_merge_from]:
- print 'WARNING in exit_veh: new veh %d should not be in inqueue 2' % id_veh
+ print('WARNING in exit_veh: new veh %d should not be in inqueue 2' % id_veh)
self.ids_vehs_in2[id_merge_from].remove(id_veh)
self.ids_vehs_in2_sumo[id_merge_from].remove(id_veh_sumo)
@@ -1633,7 +1633,7 @@ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_
def exit_veh_forced(self, id_veh, id_veh_sumo, vehicles):
"""Used by decompressors to remove a vehicle from merge control"""
- if self.vehicle_to_merge.has_key(id_veh):
+ if id_veh in self.vehicle_to_merge:
# exit vehicle from respective merge
self.exit_veh(id_veh, id_veh_sumo, self.vehicle_to_merge[id_veh], vehicles, is_remove_from_control=True)
else:
@@ -1645,34 +1645,34 @@ def print_vehs(self, id_veh1, id_veh2, dist1_min, dist1_max, dist2_min, dist2_ma
dist_max = max(dist1_min, dist1_max, dist2_min, dist2_max)+1
#dist_min = min(dist1_min, dist1_max, dist2_min, dist2_max)
#dist_diff = dist_max-dist_min+10.0
- print 'print_vehs id_veh1', id_veh1, 'id_veh2', id_veh2
+ print('print_vehs id_veh1', id_veh1, 'id_veh2', id_veh2)
# print ' dist1_min',dist1_min,'dist1_max',dist1_max
# print ' dist2_min',dist2_min,'dist2_max',dist2_max
# print ' min[dist1_min, dist1_max, dist2_min, dist2_max]>0.01',np.min([dist1_min, dist1_max, dist2_min, dist2_max])>0.01
if np.min([dist1_min, dist1_max, dist2_min, dist2_max]) > 0.01:
f = float(pos_max)/dist_max
# print ' f',f
- print '________________________'
- print 'vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max)
+ print('________________________')
+ print('vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max))
pos_min = int(dist1_min*f)
pos_max = int(dist1_max*f)
- print max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|'
+ print(max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|')
pos_min = int(dist2_min*f)
pos_max = int(dist2_max*f)
# print ' pos_min',pos_min
# print ' pos_max',pos_max
# print ' max(pos_min-1,0)',max(pos_min-1,0),'(pos_max-pos_min)',(pos_max-pos_min)
- print max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|'
- print 'vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max)
- print '________________________'
+ print(max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|')
+ print('vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max))
+ print('________________________')
else:
- print 'WARNING: some negative distances:'
- print 'vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max)
- print 'vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max)
+ print('WARNING: some negative distances:')
+ print('vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max))
+ print('vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max))
def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_merge_sumo, vehicles, debug=0):
- print 'enter_veh id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to)
+ print('enter_veh id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to))
# in id_merge_from: take vehicle out of merged queue and input queue
@@ -1709,7 +1709,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
if indpos == -1:
# vehicle is new and must be merged into ids_vehs_merged
- print ' merge prt.%d' % id_veh, 'lineind', lineind, 'dtm %.1fm' % dist_tomerge_head_new, 'n_plat', vehicles.get_platoonsize(id_veh), vehicles.lengths_plat[id_veh]/vehicles.length
+ print(' merge prt.%d' % id_veh, 'lineind', lineind, 'dtm %.1fm' % dist_tomerge_head_new, 'n_plat', vehicles.get_platoonsize(id_veh), vehicles.lengths_plat[id_veh]/vehicles.length)
ids_vehs_merged = self.ids_vehs_merged[id_merge_to]
ids_vehs_merged_sumo = self.ids_vehs_merged_sumo[id_merge_to]
@@ -1720,11 +1720,11 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
is_insert = False
id_veh_merged = -1
if debug > 0:
- print ' ids_vehs_merged_sumo[%d]' % id_merge_to, ids_vehs_merged_sumo
- print ' lineinds_vehs_merged[%d]' % id_merge_to, lineinds_vehs_merged
+ print(' ids_vehs_merged_sumo[%d]' % id_merge_to, ids_vehs_merged_sumo)
+ print(' lineinds_vehs_merged[%d]' % id_merge_to, lineinds_vehs_merged)
if (ind_insert == 0) | self.are_station[id_merge_to]:
if debug > 0:
- print ' new vehicle is the only vehicle or station', ind_insert, self.are_station[id_merge_to]
+ print(' new vehicle is the only vehicle or station', ind_insert, self.are_station[id_merge_to])
# vehicles heading toward a station merge are not
# really merged because only one incoming line
@@ -1740,7 +1740,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
if debug > 0:
dist_tomerge_head_new2 = get_traci_distance(id_veh_sumo, id_edge_merge_sumo, 3.0)
- print ' compare dist_tomerge_head_new', dist_tomerge_head_new, 'dist_tomerge_head_new2', dist_tomerge_head_new2
+ print(' compare dist_tomerge_head_new', dist_tomerge_head_new, 'dist_tomerge_head_new2', dist_tomerge_head_new2)
# get back to traci distance measurement
dist_tomerge_head_new = get_traci_distance(id_veh_sumo, id_edge_merge_sumo, 3.0)
@@ -1752,11 +1752,11 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
#dist_tomerge_tail_new = get_traci_distance(id_veh_tail_new_sumo, id_edge_merge_sumo, 3.0)
if debug > 0:
- print ' new prt.%d arriving from in %d at dist head %.2f /__| tail prt.%d %.2fm' % (id_veh, lineind, dist_tomerge_head_new, id_veh_tail_new, dist_tomerge_tail_new)
- print ' ids_vehs_merged_sumo', ids_vehs_merged_sumo
+ print(' new prt.%d arriving from in %d at dist head %.2f /__| tail prt.%d %.2fm' % (id_veh, lineind, dist_tomerge_head_new, id_veh_tail_new, dist_tomerge_tail_new))
+ print(' ids_vehs_merged_sumo', ids_vehs_merged_sumo)
for id_veh_merged, id_veh_merged_sumo, odo, lineind_merge in zip(ids_vehs_merged[::-1], ids_vehs_merged_sumo[::-1], odos_veh_merged[::-1], lineinds_vehs_merged[::-1]):
if debug > 0:
- print ' id_veh_merged_sumo', id_veh_merged_sumo
+ print(' id_veh_merged_sumo', id_veh_merged_sumo)
# unprecise
#dist_tomerge_head2 = get_traci_distance(id_veh_merged_sumo, id_edge_merge_sumo, 3.0)
@@ -1769,7 +1769,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
if debug > 0:
dist_tomerge_head2 = get_traci_distance(id_veh_merged_sumo, id_edge_merge_sumo, 3.0)
- print ' compare', id_veh_merged_sumo, ' dist_tomerge_head %.1f' % dist_tomerge_head, 'dist_tomerge_head2 %.1f' % dist_tomerge_head2
+ print(' compare', id_veh_merged_sumo, ' dist_tomerge_head %.1f' % dist_tomerge_head, 'dist_tomerge_head2 %.1f' % dist_tomerge_head2)
# get back to traci distance measurement
dist_tomerge_head = get_traci_distance(id_veh_merged_sumo, id_edge_merge_sumo, 3.0)
@@ -1778,7 +1778,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
else:
dist_node = self.distances_node_in2[id_merge_to]
if debug > 0:
- print ' M:odo_enter=%.1f odo=%.1f delta=%.f dist_node=%.1f line%d platl=%d' % (odo, get_traci_odo(id_veh_merged_sumo), get_traci_odo(id_veh_merged_sumo)-odo, dist_node, lineind_merge, vehicles.lengths_plat[id_veh_merged])
+ print(' M:odo_enter=%.1f odo=%.1f delta=%.f dist_node=%.1f line%d platl=%d' % (odo, get_traci_odo(id_veh_merged_sumo), get_traci_odo(id_veh_merged_sumo)-odo, dist_node, lineind_merge, vehicles.lengths_plat[id_veh_merged]))
#stoppeddist_tomerge = dist-0.5/self.decel*get_traci_velocity(id_veh_merged_sumo)**2+vehicles.lengths_plat[id_veh]
#stoppeddist_tomerge = dist+vehicles.lengths_plat[id_veh]
@@ -1789,7 +1789,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
dist_tomerge_tail = get_traci_distance(id_veh_tail_sumo, id_edge_merge_sumo, 3.0)
#dist_tomerge_tail = dist_tomerge_head + vehicles.lengths_plat[id_veh_merged]+vehicles.length
if debug > 0:
- print ' compare lineind_merge', lineind_merge, '=?', lineinds_vehs_merged[ind_insert-1]
+ print(' compare lineind_merge', lineind_merge, '=?', lineinds_vehs_merged[ind_insert-1])
if debug > 0:
self.print_vehs(id_veh, id_veh_merged,
@@ -1803,13 +1803,13 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
if lineind == lineinds_vehs_merged[ind_insert-1]: # get this from
if debug > 0:
- print ' vehicle in front on same branch'
+ print(' vehicle in front on same branch')
is_insert = True
break
if dist_tomerge_tail_new > dist_tomerge_tail:
if debug > 0:
- print ' distance of tail to merge of new vehicle is greater than existing'
+ print(' distance of tail to merge of new vehicle is greater than existing')
# print ' =>insert new %s after existing %s'%(id_veh_sumo,id_veh_merged_sumo)
is_insert = True
break
@@ -1819,11 +1819,11 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
if is_insert:
# at least one vehicle is in front
if debug > 0:
- print ' insert veh %d behind veh %d, index %d' % (id_veh, id_veh_merged, ind_insert)
+ print(' insert veh %d behind veh %d, index %d' % (id_veh, id_veh_merged, ind_insert))
# send control info to involved vehicles
if ind_insert == len(ids_vehs_merged):
if debug > 0:
- print ' appended vehicle after veh', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail
+ print(' appended vehicle after veh', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail)
# V
# |
# G ind_insert-1
@@ -1847,7 +1847,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
#id_ghost2 = ids_vehs_merged[ind_insert-1]
id_ghost2 = id_veh_tail
if debug > 0:
- print ' vehicle will be inserted in front of', ids_vehs_merged_sumo[ind_insert], 'and in behind', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail
+ print(' vehicle will be inserted in front of', ids_vehs_merged_sumo[ind_insert], 'and in behind', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail)
vehicles.del_ghost(id_ghost1, id_ghost2)
if lineinds_vehs_merged[ind_insert] != lineind:
@@ -1859,7 +1859,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
else:
if debug > 0:
- print ' prepend prt.%d in front of prt.%d, first index %d' % (id_veh, id_veh_merged, ind_insert)
+ print(' prepend prt.%d in front of prt.%d, first index %d' % (id_veh, id_veh_merged, ind_insert))
# is vehicle and ghost in the same input line?
if lineinds_vehs_merged[ind_insert] != lineind:
id_veh_behind = ids_vehs_merged[ind_insert] # last veh in queue
@@ -1880,7 +1880,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
# lineinds_vehs_merged[0] = lineind
def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_merge_sumo, vehicles, debug=0):
- print 'enter_veh_entry id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to)
+ print('enter_veh_entry id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to))
# in id_merge_from: take vehicle out of merged queue and input queue
@@ -1913,8 +1913,8 @@ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_ed
if lineind == 1:
# from line 1 (main line)
if debug > 0:
- print ' Detected veh', id_veh_sumo, 'on mainline. Is new', indpos == -1
- print ' check for platooned vehicles:', vehicles.get_platoon(id_veh)
+ print(' Detected veh', id_veh_sumo, 'on mainline. Is new', indpos == -1)
+ print(' check for platooned vehicles:', vehicles.get_platoon(id_veh))
id_edge_out_sumo = self.ids_merge_to_ids_edge_out_sumo[id_merge_to]
dist_tomerge = get_traci_distance(id_veh_sumo, id_edge_out_sumo, 3.0)
@@ -1926,18 +1926,18 @@ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_ed
id_veh2, state2 = self.get_mergeveh_entry(id_merge_to, debug)
if debug > 0:
- print ' Conflict vehicle from entry line: prt.%d state' % (id_veh2,), state2
- print ' Main line: ids_vehs_in1', ids_vehs_in1
- print ' id_veh1_last', id_veh1_last
- print ' dist_tomerge', dist_tomerge
+ print(' Conflict vehicle from entry line: prt.%d state' % (id_veh2,), state2)
+ print(' Main line: ids_vehs_in1', ids_vehs_in1)
+ print(' id_veh1_last', id_veh1_last)
+ print(' dist_tomerge', dist_tomerge)
if id_veh2 == -1:
if debug > 0:
- print ' no vehicle to merge'
+ print(' no vehicle to merge')
if id_veh1_last != -1:
if debug > 0:
- print ' control distance to last vehicle in main...by SUMO'
+ print(' control distance to last vehicle in main...by SUMO')
pass
#
#id_veh_tail = vehicles.get_platoontail(id_veh1_last)
@@ -1949,15 +1949,15 @@ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_ed
else:
if debug > 0:
- print ' merge is empty'
+ print(' merge is empty')
pass
elif state2['status'] != 'wait':
# there is an approaching vehicle on entry line
if state2['status'] == 'accelerate':
if debug > 0:
- print ' conflict vehicle in acceleration mode', 'is veh behind', state2.has_key('id_veh_behind')
- if state2.has_key('id_veh_behind'):
+ print(' conflict vehicle in acceleration mode', 'is veh behind', 'id_veh_behind' in state2)
+ if 'id_veh_behind' in state2:
# accelerating vehicle has already a vehicle
# in front of which to merge
# => look at last vehicle
@@ -1971,8 +1971,8 @@ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_ed
if state2['status'] == 'sync':
if debug > 0:
- print ' conflict vehicle in sync mode'
- if state2.has_key('id_veh_behind'):
+ print(' conflict vehicle in sync mode')
+ if 'id_veh_behind' in state2:
# accelerating vehicle has already a vehicle
# in front of which to merge
# => look at last vehicle
@@ -1987,7 +1987,7 @@ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_ed
id_veh_tail = vehicles.get_platoontail(id_veh2)
id_veh_tail_sumo = vehicles.ids_sumo[id_veh_tail]
dist_tomerge_tail = get_traci_distance(id_veh_tail_sumo, id_edge_out_sumo, 3.0)
- print ' let look the new vehicle prt.%d look at the tail of the entering vehicle prt.%d' % (id_veh, id_veh_tail)
+ print(' let look the new vehicle prt.%d look at the tail of the entering vehicle prt.%d' % (id_veh, id_veh_tail))
vehicles.add_ghost(id_veh, id_veh_tail, dist_tomerge, dist_tomerge_tail)
# let the entering vehicle see the new vehicle
@@ -2004,12 +2004,12 @@ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_ed
elif lineind == 2:
# from line 2 (entry line)
- print ' Detected veh', id_veh_sumo, 'on entry line. Is new', indpos == -1
+ print(' Detected veh', id_veh_sumo, 'on entry line. Is new', indpos == -1)
self.ids_vehs_in2[id_merge_to].append(id_veh)
self.ids_vehs_in2_sumo[id_merge_to].append(id_veh_sumo)
- print ' command vehicle to stop and wait further instructions'
+ print(' command vehicle to stop and wait further instructions')
#vehicles.control_slow_down(id_veh, speed = 6.0/3.6)
#traci.vehicle.setMaxSpeed(id_veh_sumo, 6.0/3.6)
# print ' set speed to',traci.vehicle.getMaxSpeed(id_veh_sumo)
@@ -2019,9 +2019,9 @@ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_ed
# prevent SUMO from reaccelerating vehicle
# vehicles.switch_off_control(id_veh)
- print ' set veh id_veh prt.%d' % id_veh
+ print(' set veh id_veh prt.%d' % id_veh)
self.vehicles_entries[id_merge_to][id_veh] = {'status': 'wait'}
- print ' vehicles_entries[', id_merge_to, ']=', self.vehicles_entries[id_merge_to]
+ print(' vehicles_entries[', id_merge_to, ']=', self.vehicles_entries[id_merge_to])
#
# self.vehicles_mains[id_merge_to][id_veh] = {}# later when used
@@ -2038,14 +2038,14 @@ def get_mergeveh_entry(self, id_merge, debug):
vehicles_entries = self.vehicles_entries[id_merge]
if debug > 0:
- print 'get_mergeveh_entry vehicles_entries', vehicles_entries
+ print('get_mergeveh_entry vehicles_entries', vehicles_entries)
if len(vehicles_entries) == 0:
return -1, {'status': 'wait'}
else:
- return vehicles_entries.keys()[0], vehicles_entries.values()[0]
+ return list(vehicles_entries.keys())[0], list(vehicles_entries.values())[0]
def process_step_entry(self, id_merge, vehicles, debug):
- print 'process_step_entry id_merge', id_merge
+ print('process_step_entry id_merge', id_merge)
#self.vehicles_entries[id_merge]= OrderedDict()
# self.vehicles_mains[id_merge] = OrderedDict()
@@ -2054,16 +2054,16 @@ def process_step_entry(self, id_merge, vehicles, debug):
# for id_veh, state in zip(self.vehicles_entries[id_merge].keys()[::-1],self.vehicles_entries[id_merge].values()[::-1]):
# for id_veh, state in self.vehicles_entries.iteritems():
# for id_veh, state in zip(self.vehicles_entries[id_merge].keys(),self.vehicles_entries[id_merge].values()):
- ids_veh_entry = self.vehicles_entries[id_merge].keys()
- states_veh_entry = self.vehicles_entries[id_merge].values()
+ ids_veh_entry = list(self.vehicles_entries[id_merge].keys())
+ states_veh_entry = list(self.vehicles_entries[id_merge].values())
id_edge_out_sumo = self.ids_merge_to_ids_edge_out_sumo[id_merge]
ids_veh_in1 = self.ids_vehs_in1[id_merge]
time_update = self.time_update.get_value()
if debug:
- print ' vehicles_entries=', self.vehicles_entries[id_merge]
- print ' vehicles_mains', self.vehicles_mains[id_merge]
- print ' ids_veh_in1', ids_veh_in1
+ print(' vehicles_entries=', self.vehicles_entries[id_merge])
+ print(' vehicles_mains', self.vehicles_mains[id_merge])
+ print(' ids_veh_in1', ids_veh_in1)
i = 0
#is_cont = len(ids_veh_entry)>0
@@ -2078,7 +2078,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
lineinds_vehs_merged = self.lineinds_vehs_merged[id_merge]
odos_veh_merged = self.odos_vehs_merged[id_merge]
if debug:
- print ' check id_veh_sumo', id_veh_sumo, 'status', state['status'], 'n vehs on main', len(ids_veh_in1)
+ print(' check id_veh_sumo', id_veh_sumo, 'status', state['status'], 'n vehs on main', len(ids_veh_in1))
if state['status'] == 'wait':
if traci.vehicle.isStopped(id_veh_sumo):
# check potential conflict vehicle on main line
@@ -2086,7 +2086,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
n1 = len(ids_veh_in1)
if n1 == 0:
if debug:
- print ' main line is empty => accelerate immediately'
+ print(' main line is empty => accelerate immediately')
for id_veh_plat in vehicles.get_platoon(id_veh):
vehicles.control_speedup(id_veh_plat)
state['status'] = 'accelerate'
@@ -2108,7 +2108,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
id_veh1_sumo = ids_veh_in1_sumo[i]
id_veh1 = ids_veh_in1[i]
if debug:
- print ' check', id_veh1_sumo, 'free', id_veh1 not in vehicles_main
+ print(' check', id_veh1_sumo, 'free', id_veh1 not in vehicles_main)
if True: # id_veh1 not in vehicles_main:
@@ -2124,7 +2124,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
dist_in1, dist_in2,
vehicles)
if debug:
- print ' potential veh %s (tail %s)' % (id_veh1_sumo, id_veh1_tail_sumo), 'at pos1_tail=%.1f>p_to=%.1f' % (pos1_tail, p_to), pos1_tail > p_to
+ print(' potential veh %s (tail %s)' % (id_veh1_sumo, id_veh1_tail_sumo), 'at pos1_tail=%.1f>p_to=%.1f' % (pos1_tail, p_to), pos1_tail > p_to)
# here we check whether the tail of the vehicle on the main line
# has passed the critical point p_to
@@ -2133,9 +2133,9 @@ def process_step_entry(self, id_merge, vehicles, debug):
if i == n1-1: # last vehicle on main
if debug:
- print ' insert id_veh', id_veh_sumo, 'behind id_veh1', id_veh1_sumo, 'the only veh on main'
+ print(' insert id_veh', id_veh_sumo, 'behind id_veh1', id_veh1_sumo, 'the only veh on main')
state['id_veh_infront'] = id_veh1
- if vehicles_main.has_key(id_veh1):
+ if id_veh1 in vehicles_main:
vehicles_main[id_veh1]['id_veh_behind'] = id_veh
else:
vehicles_main[id_veh1] = {'id_veh_behind': id_veh}
@@ -2151,18 +2151,18 @@ def process_step_entry(self, id_merge, vehicles, debug):
id_veh_behind_sumo = vehicles.ids_sumo[id_veh_behind]
pos1 = dist_in1 - get_traci_distance(id_veh_behind_sumo, id_edge_out_sumo, 3.0)
if debug:
- print ' vehicle behind', id_veh_behind_sumo, 'pos=%.1f, p_from=%.1f' % (pos1, p_from), 'ok', pos1 < p_from
+ print(' vehicle behind', id_veh_behind_sumo, 'pos=%.1f, p_from=%.1f' % (pos1, p_from), 'ok', pos1 < p_from)
if pos1 < p_from:
state['id_veh_infront'] = id_veh1
state['id_veh_behind'] = id_veh_behind
#vehicles_main[id_veh_behind] = id_veh
- if vehicles_main.has_key(id_veh1):
+ if id_veh1 in vehicles_main:
vehicles_main[id_veh1]['id_veh_behind'] = id_veh
else:
vehicles_main[id_veh1] = {'id_veh_behind': id_veh}
#vehicles_main[id_veh1] = id_veh
- if vehicles_main.has_key(id_veh_behind):
+ if id_veh_behind in vehicles_main:
vehicles_main[id_veh_behind]['id_veh_infront'] = id_veh
else:
vehicles_main[id_veh_behind] = {'id_veh_infront': id_veh}
@@ -2170,7 +2170,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
is_found = True
j = ids_vehs_merged.index(id_veh1)+1
if debug:
- print ' j=', j
+ print(' j=', j)
ids_vehs_merged.insert(j, id_veh)
ids_vehs_merged_sumo.insert(j, id_veh_sumo)
lineinds_vehs_merged.insert(j, 2)
@@ -2181,10 +2181,10 @@ def process_step_entry(self, id_merge, vehicles, debug):
elif pos1 < p_from:
if i == 0: # first vehicle on main
if debug:
- print ' insert id_veh', id_veh_sumo, 'in front of id_veh1', id_veh1_sumo, 'the only veh on main'
+ print(' insert id_veh', id_veh_sumo, 'in front of id_veh1', id_veh1_sumo, 'the only veh on main')
state['id_veh_behind'] = id_veh1
#vehicles_main[id_veh1] = id_veh
- if vehicles_main.has_key(id_veh1):
+ if id_veh1 in vehicles_main:
vehicles_main[id_veh1]['id_veh_infront'] = id_veh
else:
vehicles_main[id_veh1] = {'id_veh_infront': id_veh}
@@ -2198,7 +2198,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
lineinds_vehs_merged.insert(j, 2)
odos_veh_merged.insert(j, get_traci_odo(id_veh_sumo))
if debug:
- print ' ids_vehs_merged_sumo', ids_vehs_merged_sumo
+ print(' ids_vehs_merged_sumo', ids_vehs_merged_sumo)
# elif i < n1-1: # there are others behind on main
# # ensure that gap is big enough
# id_veh_behind = ids_veh_in1[i+1]
@@ -2214,7 +2214,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
if is_found:
if debug:
- print ' suitable vehicle after which entry vehicle can run has been found'
+ print(' suitable vehicle after which entry vehicle can run has been found')
# Note: if no vehicle has been found then
# nothing will happen and the vehicle will
# wait until the righ moment has arrived
@@ -2226,12 +2226,12 @@ def process_step_entry(self, id_merge, vehicles, debug):
# test if speed reached
if traci.vehicle.getSpeed(id_veh_sumo) > 0.9*vehicles.speed_max.get_value():
if debug > 0:
- print ' synchronization reached for veh', id_veh_sumo
+ print(' synchronization reached for veh', id_veh_sumo)
state['status'] = 'sync'
#id_veh_del = id_veh
# now create ghosts
# id_veh -> id_veh_infront_tail:
- if state.has_key('id_veh_infront'):
+ if 'id_veh_infront' in state:
id_veh_in_front = state['id_veh_infront']
id_veh_infront_tail = vehicles.get_platoontail(id_veh_in_front)
id_veh_infront_tail_sumo = vehicles.ids_sumo[id_veh_infront_tail]
@@ -2239,11 +2239,11 @@ def process_step_entry(self, id_merge, vehicles, debug):
dist_tomerge_tail = get_traci_distance(id_veh_infront_tail_sumo, id_edge_out_sumo, 3.0)
if debug > 0:
- print ' add ghost to entering veh', id_veh_sumo, ' behind', id_veh_infront_tail_sumo, 'with leader', id_veh_in_front
+ print(' add ghost to entering veh', id_veh_sumo, ' behind', id_veh_infront_tail_sumo, 'with leader', id_veh_in_front)
vehicles.add_ghost(id_veh, id_veh_infront_tail, dist_tomerge,
dist_tomerge_tail, is_substitute=True)
- if state.has_key('id_veh_behind'):
+ if 'id_veh_behind' in state:
id_veh_behind = state['id_veh_behind']
id_veh_behind_sumo = vehicles.ids_sumo[id_veh_behind]
@@ -2254,16 +2254,16 @@ def process_step_entry(self, id_merge, vehicles, debug):
dist_tomerge_tail = get_traci_distance(id_veh_tail_sumo, id_edge_out_sumo, 3.0)
if debug > 0:
- print ' add ghost to mainline veh', id_veh_behind_sumo, ' behind', id_veh_tail_sumo, 'with leader', id_veh_sumo
+ print(' add ghost to mainline veh', id_veh_behind_sumo, ' behind', id_veh_tail_sumo, 'with leader', id_veh_sumo)
vehicles.add_ghost(id_veh_behind, id_veh_tail, dist_tomerge_behind,
dist_tomerge_tail, is_substitute=True)
else:
if 0:
speed = traci.vehicle.getSpeed(id_veh_sumo)
- print ' sync of veh', id_veh_sumo, ',v=%.1f, not yet reached: %.2f' % (speed, speed/vehicles.speed_max.get_value())
+ print(' sync of veh', id_veh_sumo, ',v=%.1f, not yet reached: %.2f' % (speed, speed/vehicles.speed_max.get_value()))
- if state.has_key('id_veh_behind'):
+ if 'id_veh_behind' in state:
id_veh_behind_sumo = vehicles.ids_sumo[state['id_veh_behind']]
info = traci.vehicle.getLeader(id_veh_behind_sumo, dist=200.0)
if (info is not None):
@@ -2300,7 +2300,7 @@ def get_pos_crit_entry(self, pos2, len_veh2, speed, dist1, dist2, vehicles):
pos_to refers to the position of the tail of the platoon on the main line.
"""
- print 'get_pos_crit_entry pos2=%.1f, v=%.1f, d1=%.1f, d2=%.1f' % (pos2, speed, dist1, dist2)
+ print('get_pos_crit_entry pos2=%.1f, v=%.1f, d1=%.1f, d2=%.1f' % (pos2, speed, dist1, dist2))
# see 191030
decel_emergency = vehicles.decel_emergency.get_value()
decel_comfort = vehicles.decel_comfort.get_value()
@@ -2321,9 +2321,9 @@ def search_upstream_merge(self, id_edge_start, edges, lanes, id_prtmode, ids_mai
Returns id_node, length to node
"""
- print 'search_upstream_merge id_edge_start', id_edge_start
+ print('search_upstream_merge id_edge_start', id_edge_start)
length = distances[id_edge_start]
- print ' added id_edge', id_edge_start, 'dist', distances[id_edge_start], '=', length
+ print(' added id_edge', id_edge_start, 'dist', distances[id_edge_start], '=', length)
is_merge = False
id_edge_platform = -1
id_edge = id_edge_start
@@ -2357,10 +2357,10 @@ def search_upstream_merge(self, id_edge_start, edges, lanes, id_prtmode, ids_mai
if not is_merge:
id_edge = ids_edge_incoming[0]
length += distances[id_edge]
- print ' added id_edge', id_edge, 'dist', distances[id_edge], '=', length
+ print(' added id_edge', id_edge, 'dist', distances[id_edge], '=', length)
# print ' id_edge,is_merge',id_edge,is_merge
- print ' found node', edges.ids_fromnode[id_edge]
+ print(' found node', edges.ids_fromnode[id_edge])
return edges.ids_fromnode[id_edge], length
def search_downstream_merges(self, id_edge_start, edges, lanes, id_prtmode, ids_sinkedge=set()):
@@ -2372,7 +2372,7 @@ def search_downstream_merges(self, id_edge_start, edges, lanes, id_prtmode, ids_
ids_edge = set([id_edge_start])
ids_mergenode = set()
- print 'search_downstream_merges id_edge_start', id_edge_start, 'is sinkedge', id_edge_start in ids_sinkedge
+ print('search_downstream_merges id_edge_start', id_edge_start, 'is sinkedge', id_edge_start in ids_sinkedge)
if id_edge_start in ids_sinkedge:
return None # np.array([], dtype = np.int32)
@@ -2424,7 +2424,7 @@ def search_downstream_merges(self, id_edge_start, edges, lanes, id_prtmode, ids_
# if not is_cont:
# print ' endless!!id_edge_start,ids_edge',id_edge_start,ids_edge
- print ' found ids_mergenode', ids_mergenode
+ print(' found ids_mergenode', ids_mergenode)
return np.array(list(ids_mergenode), dtype=np.int32)
def is_prt_only(self, ids_lane, lanes):
@@ -2554,7 +2554,7 @@ def set_prtvehicles(self, prtvehicles):
))
def set_allocate(self, ids_berth):
- print 'set_allocate ids_berth', ids_berth, self.ids_veh[ids_berth]
+ print('set_allocate ids_berth', ids_berth, self.ids_veh[ids_berth])
self.states[ids_berth] = BERTHSTATES['allocated']
def set_alighting(self, id_berth, id_veh):
@@ -2572,7 +2572,7 @@ def set_waiting_empty(self, id_berth):
def set_waiting_routed(self, id_berth, simtime):
- print 'set_waiting_routed', id_berth, 'prt.%d' % (self.ids_veh[id_berth]), 'simtime', simtime
+ print('set_waiting_routed', id_berth, 'prt.%d' % (self.ids_veh[id_berth]), 'simtime', simtime)
self.states[id_berth] = BERTHSTATES['waiting_routed']
self.times_routes[id_berth] = simtime
@@ -2757,7 +2757,7 @@ def get_closest_for_trip(self, coords_from, coords_to, walkspeeds=None, ids_pers
ptstops = net.ptstops
lanes = net.lanes
n = len(coords_from)
- print 'get_closest_for_trip', n
+ print('get_closest_for_trip', n)
times_stop_to_stop = self.parent.times_stop_to_stop[1:, 1:]
@@ -2792,11 +2792,11 @@ def get_closest_for_trip(self, coords_from, coords_to, walkspeeds=None, ids_pers
# print ' walktimes_to',walktimes_to.shape
# print ' times_stop_to_stop',times_stop_to_stop.shape
- print ' id_person', id_person
- print ' coord_from, coord_to', coord_from, coord_to
- print ' times_door_to_door\n', times_door_to_door
- print ' ind_from, ind_to', ind_from, ind_to
- print ' id_stop_from, id_stop_to', ids_prtstop[ind_from], ids_prtstop[ind_to]
+ print(' id_person', id_person)
+ print(' coord_from, coord_to', coord_from, coord_to)
+ print(' times_door_to_door\n', times_door_to_door)
+ print(' ind_from, ind_to', ind_from, ind_to)
+ print(' id_stop_from, id_stop_to', ids_prtstop[ind_from], ids_prtstop[ind_to])
i += 1
@@ -2871,7 +2871,7 @@ def get_capacity(self, id_stop):
def prepare_sim(self, process):
simtime = process.simtime
- print 'PrtStops.prepare_sim', simtime
+ print('PrtStops.prepare_sim', simtime)
self.debug = True
net = self.get_scenario().net
ptstops = net.ptstops
@@ -2927,11 +2927,11 @@ def prepare_sim(self, process):
if (firstberthpos-stoplinegap) > 0:
self.stoplines_in[id_stop] = firstberthpos-stoplinegap
- print ' OK:id_stop', id_stop, 'stoplines_in', self.stoplines_in[id_stop]
+ print(' OK:id_stop', id_stop, 'stoplines_in', self.stoplines_in[id_stop])
self.capas_inqueue[id_stop] = int(self.stoplines_in[id_stop]/vehicles.length)
- print ' capa_inqueue', self.capas_inqueue[id_stop]
+ print(' capa_inqueue', self.capas_inqueue[id_stop])
else:
- print 'WARNING in PrtStops.prepare_sim: stop ID %d has not enough space at before berth area.' % id_stop
+ print('WARNING in PrtStops.prepare_sim: stop ID %d has not enough space at before berth area.' % id_stop)
# Determine stopline position where vehicles actually start
# running off the station
@@ -2946,14 +2946,14 @@ def prepare_sim(self, process):
lastberthstoppos = berths.stoppositions[ids_board][-1]
if (length_stopedge-lastberthstoppos) > stoplinegap+1:
self.stoplines[id_stop] = length_stopedge-stoplinegap
- print ' OK:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop]
+ print(' OK:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop])
elif length_stopedge > lastberthstoppos:
self.stoplines[id_stop] = 0.5*(length_stopedge+lastberthstoppos)
- print ' Limit:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop]
+ print(' Limit:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop])
self.capas_outqueue[id_stop] = int((self.stoplines[id_stop]-lastberthstoppos)/vehicles.length)
- print ' capa_outqueue', self.capas_outqueue[id_stop]
+ print(' capa_outqueue', self.capas_outqueue[id_stop])
self.ids_stop_to_ids_acceledge_sumo = np.zeros(np.max(ids)+1, dtype=np.object)
for id_stop, id_stopedge in zip(ids, ids_stopedge):
@@ -3057,7 +3057,7 @@ def prepare_sim(self, process):
id_toedge_sumo)
id_person_sumo = virtualpop.get_id_sumo_from_id(id_person)
- if id_person_to_origs_dests.has_key(id_person_sumo):
+ if id_person_sumo in id_person_to_origs_dests:
id_person_to_origs_dests[id_person_sumo].append(data_orig_dest)
else:
id_person_to_origs_dests[id_person_sumo] = [data_orig_dest]
@@ -3071,7 +3071,7 @@ def prepare_sim(self, process):
# various initianilizations
for id_stop, id_edge_sumo in zip(ids, self.ids_stop_to_ids_edge_sumo[ids]):
- print ' initialize stop', id_stop
+ print(' initialize stop', id_stop)
# initially all berth are avalable for allocation
# print ' type(self.ids_berths[id_stop])',type(self.ids_berths[id_stop])
@@ -3112,14 +3112,14 @@ def prepare_sim(self, process):
def get_waittime_max(self, id_stop, simtime):
if len(self.waittimes_persons[id_stop]) > 0:
- return np.max(simtime - np.array(self.waittimes_persons[id_stop].values(), dtype=np.float32))
+ return np.max(simtime - np.array(list(self.waittimes_persons[id_stop].values()), dtype=np.float32))
else:
return 0.0
def process_step(self, process):
simtime = process.simtime
- print 79*'_'
- print 'PrtStops.process_step at', simtime
+ print(79*'_')
+ print('PrtStops.process_step at', simtime)
# vehicle station process:
# >forewarding (def enter)
@@ -3142,9 +3142,9 @@ def process_step(self, process):
zip(ids, self.ids_stop_to_ids_edge_sumo[ids],
self.ids_vehs_sumo_prev[ids],
self.ids_persons_sumo_prev[ids]):
- print ' '+60*'.'
+ print(' '+60*'.')
fase = self.fases[id_stop]
- print ' process id_stop', id_stop, 'id_edge_sumo', id_edge_sumo, 'fase', fase
+ print(' process id_stop', id_stop, 'id_edge_sumo', id_edge_sumo, 'fase', fase)
if id_stop in [3]:
self.debug = 1
@@ -3156,34 +3156,34 @@ def process_step(self, process):
if self.debug:
- print ' ids_berths_to_allocate', type(self.ids_berths_to_allocate[id_stop]), self.ids_berths_to_allocate[id_stop]
- print ' ind_berth_allocated', self.inds_berth_allocated[id_stop]
- print ' ids_vehs_inqueue', self.ids_vehs_inqueue[id_stop]
- print ' Capa', self.get_capacity(id_stop), 'per 10 seconds', self.get_capacity(id_stop)/3600*10
- print
+ print(' ids_berths_to_allocate', type(self.ids_berths_to_allocate[id_stop]), self.ids_berths_to_allocate[id_stop])
+ print(' ind_berth_allocated', self.inds_berth_allocated[id_stop])
+ print(' ids_vehs_inqueue', self.ids_vehs_inqueue[id_stop])
+ print(' Capa', self.get_capacity(id_stop), 'per 10 seconds', self.get_capacity(id_stop)/3600*10)
+ print()
- print ' ids_vehs_alight_forward', self.ids_vehs_alight_forward[id_stop]
- print ' ids_vehs_alight_aproach', self.ids_vehs_alight_aproach[id_stop]
- print
+ print(' ids_vehs_alight_forward', self.ids_vehs_alight_forward[id_stop])
+ print(' ids_vehs_alight_aproach', self.ids_vehs_alight_aproach[id_stop])
+ print()
- print ' ids_vehs_routed', self.ids_vehs_routed[id_stop]
- print ' ids_berths_veh_wait_exit ', self.ids_berths_veh_wait_exit[id_stop]
- print ' ids_vehs_pass_wait_exit ', self.ids_vehs_pass_wait_exit[id_stop]
- print ' ids_vehs_berth_exit', self.ids_vehs_berth_exit[id_stop]
- print ' ids_vehs_out', self.ids_vehs_out[id_stop]
- print ' ids_veh_ready_for_departure', self.ids_vehs_ready_for_departure[id_stop]
+ print(' ids_vehs_routed', self.ids_vehs_routed[id_stop])
+ print(' ids_berths_veh_wait_exit ', self.ids_berths_veh_wait_exit[id_stop])
+ print(' ids_vehs_pass_wait_exit ', self.ids_vehs_pass_wait_exit[id_stop])
+ print(' ids_vehs_berth_exit', self.ids_vehs_berth_exit[id_stop])
+ print(' ids_vehs_out', self.ids_vehs_out[id_stop])
+ print(' ids_veh_ready_for_departure', self.ids_vehs_ready_for_departure[id_stop])
- print ' Vehicles:'
+ print(' Vehicles:')
ids_veh = self.ids_vehs[id_stop]
for id_veh, state, id_berth, route in zip(ids_veh, vehicles.states[ids_veh], vehicles.ids_berth[ids_veh], vehicles.routes[ids_veh]):
# ,'len(route)',len(route)
- print ' id_veh', id_veh, 'state', state, 'id_berth', id_berth, 'route', route
+ print(' id_veh', id_veh, 'state', state, 'id_berth', id_berth, 'route', route)
- print ' Berths:'
+ print(' Berths:')
ids_berth = self.ids_berths[id_stop]
for id_berth, state, id_veh in zip(ids_berth, berths.states[ids_berth], berths.ids_veh[ids_berth]):
- print ' id_berth', id_berth, 'state', state, 'id_veh', id_veh
+ print(' id_berth', id_berth, 'state', state, 'id_veh', id_veh)
# print ' flow_person',self.flows_person[id_stop]
# print ' waittimes_persons',self.waittimes_persons[id_stop]
@@ -3191,11 +3191,11 @@ def process_step(self, process):
# no longer print ' ids_persons_sumo_boarded',self.ids_persons_sumo_boarded[id_stop]
# print ' times_lastboard',self.times_lastboard[id_stop]
- print
+ print()
if 0:
for id_veh_sumo in self.ids_vehs_sumo_prev[id_stop]:
- print ' stopstate ', id_veh_sumo, bin(traci.vehicle.getStopState(id_veh_sumo))[2:], traci.vehicle.getRoute(id_veh_sumo)
+ print(' stopstate ', id_veh_sumo, bin(traci.vehicle.getStopState(id_veh_sumo))[2:], traci.vehicle.getRoute(id_veh_sumo))
# check for new vehicle arrivals/departures
ids_veh_sumo = set(traci.edge.getLastStepVehicleIDs(id_edge_sumo))
@@ -3273,7 +3273,7 @@ def process_step(self, process):
ids_veh_remove.append(id_veh)
id_berth_alight = vehicles.ids_berth[id_veh]
if self.debug:
- print ' %s stopped inside berth %d and alights' % (id_veh_sumo, id_berth_alight)
+ print(' %s stopped inside berth %d and alights' % (id_veh_sumo, id_berth_alight))
# vehicles.set_stop( id_veh,
# id_edge_sumo,
@@ -3300,8 +3300,8 @@ def process_step(self, process):
if ids_person_sumo_prev != ids_person_sumo:
if 0:
- print ' change\n id_person_sumo', ids_person_sumo
- print ' ids_person_sumo_prev', ids_person_sumo_prev
+ print(' change\n id_person_sumo', ids_person_sumo)
+ print(' ids_person_sumo_prev', ids_person_sumo_prev)
# print ' dir(traci.person)',dir(traci.person)
# for id_person_sumo in ids_person_sumo:
# print ' id_person_sumo',id_person_sumo,traci.person.getRoadID(id_person_sumo),traci.person.getVehicle(id_person_sumo)
@@ -3310,7 +3310,7 @@ def process_step(self, process):
ids_person_sumo_entered = ids_person_sumo.difference(ids_person_sumo_prev)
for id_person_sumo in ids_person_sumo_entered:
# print ' entered id_person_sumo',id_person_sumo,traci.person.getRoadID(id_person_sumo)
- if self.id_person_to_origs_dests.has_key(id_person_sumo):
+ if id_person_sumo in self.id_person_to_origs_dests:
id_edge_sumo_dests = self.id_person_to_origs_dests[id_person_sumo]
# id_edge_sumo_dests[i] = ( id_stop_from,
@@ -3324,7 +3324,7 @@ def process_step(self, process):
# check if next trip has origin edge equal to edge of this stop
if id_edge_sumo_dests[0][2] == id_edge_sumo:
if self.debug:
- print ' add to waittimes_persons', id_person_sumo, 'id_stop_dest', id_edge_sumo_dests[0][1], 'id_toedge_sumo', id_edge_sumo_dests[0][3]
+ print(' add to waittimes_persons', id_person_sumo, 'id_stop_dest', id_edge_sumo_dests[0][1], 'id_toedge_sumo', id_edge_sumo_dests[0][3])
self.waittimes_persons[id_stop][id_person_sumo] = simtime
n_enter += 1
@@ -3346,7 +3346,7 @@ def process_step(self, process):
if 0:
for id_person_sumo in ids_person_sumo_prev:
- print ' ids_person_sumo=%s pos = %.2f ' % (id_person_sumo, traci.person.getLanePosition(id_person_sumo))
+ print(' ids_person_sumo=%s pos = %.2f ' % (id_person_sumo, traci.person.getLanePosition(id_person_sumo)))
# nomore print ' ids_persons_sumo_boarded',self.ids_persons_sumo_boarded[id_stop]
# if vehicles.id_follower_probe != vehicles.ids_follower[271]:
@@ -3368,7 +3368,7 @@ def process_step(self, process):
# this will put the vehicle in waiting or boarding mode
if vehicles.is_completed_alighting(id_veh):
if self.debug:
- print ' state of prt.%d: %d' % (id_veh, vehicles.states[id_veh])
+ print(' state of prt.%d: %d' % (id_veh, vehicles.states[id_veh]))
if vehicles.states[id_veh] == VEHICLESTATES['boarding']:
# print ' set id_berth_board',id_berth_board,'to state boarding'
berths.set_boarding(id_berth_board)
@@ -3396,15 +3396,15 @@ def process_step(self, process):
if fase == FASE_MOVE_IN:
# stop is in move in fase
if self.debug:
- print ' >>timeout fase 0: dt=%.2f timeout=%.2f' % ((simtime - self.times_phase_in[id_stop]), self.time_fase_in_max.get_value()),\
+ print(' >>timeout fase 0: dt=%.2f timeout=%.2f' % ((simtime - self.times_phase_in[id_stop]), self.time_fase_in_max.get_value()),\
'TOUT', ((simtime - self.times_phase_in[id_stop]) > self.time_fase_in_max.get_value()
- ), '|ALLOC', (len(self.ids_vehs_inqueue[id_stop]) > 0)
+ ), '|ALLOC', (len(self.ids_vehs_inqueue[id_stop]) > 0))
# print ' ap',(len(self.ids_vehs_alight_aproach[id_stop]) == 0)
- print ' no forward, all vehicles moved into berth', (len(self.ids_vehs_alight_forward[id_stop]) == 0)
- print ' ids_vehs_inqueue', self.ids_vehs_inqueue[id_stop]
- print ' ids_veh_to_allocate', ids_veh_to_allocate
- print ' ids_veh_to_pass', ids_veh_to_pass
- print ' is_back_to_move_in ', self.are_back_to_move_in[id_stop]
+ print(' no forward, all vehicles moved into berth', (len(self.ids_vehs_alight_forward[id_stop]) == 0))
+ print(' ids_vehs_inqueue', self.ids_vehs_inqueue[id_stop])
+ print(' ids_veh_to_allocate', ids_veh_to_allocate)
+ print(' ids_veh_to_pass', ids_veh_to_pass)
+ print(' is_back_to_move_in ', self.are_back_to_move_in[id_stop])
# if np.isnan(self.times_phase_in[id_stop]):
# # only for initialization
# self.times_phase_in[id_stop] = simtime - self.time_fase_in_max.get_value()
@@ -3430,15 +3430,15 @@ def process_step(self, process):
# which means that there are no more free berth to allocate
# and all forwarded vehicles reached their berth to alight
if self.debug:
- print ' Switch from fase %d to fase %d' % (self.fases[id_stop], FASE_MOVE_OUT)
+ print(' Switch from fase %d to fase %d' % (self.fases[id_stop], FASE_MOVE_OUT))
self.fases[id_stop] = FASE_MOVE_OUT
self.times_phase_out[id_stop] = simtime
elif fase == FASE_MOVE_OUT:
# stop is in move out fase
if self.debug:
- print ' >>timeout fase 1: dt=%.2f timeout=%.2f' % ((simtime - self.times_phase_out[id_stop]), self.time_fase_out_max.get_value()), 'move out of berth', len(self.ids_vehs_berth_exit[id_stop])
- print ' n_berth_exit', len(self.ids_vehs_berth_exit[id_stop]), 'n_veh_pass', len(ids_veh_to_pass), 'ids_veh_to_pass', ids_veh_to_pass
+ print(' >>timeout fase 1: dt=%.2f timeout=%.2f' % ((simtime - self.times_phase_out[id_stop]), self.time_fase_out_max.get_value()), 'move out of berth', len(self.ids_vehs_berth_exit[id_stop]))
+ print(' n_berth_exit', len(self.ids_vehs_berth_exit[id_stop]), 'n_veh_pass', len(ids_veh_to_pass), 'ids_veh_to_pass', ids_veh_to_pass)
# check fase transition
# if np.isnan(self.times_phase_out[id_stop]):
# # only for initialization
@@ -3453,7 +3453,7 @@ def process_step(self, process):
self.are_back_to_move_in[id_stop] = False
if self.debug:
- print ' Switch from fase %d to fase %d' % (self.fases[id_stop], FASE_MOVE_IN), 'ind_berth_allocated', self.inds_berth_allocated[id_stop]
+ print(' Switch from fase %d to fase %d' % (self.fases[id_stop], FASE_MOVE_IN), 'ind_berth_allocated', self.inds_berth_allocated[id_stop])
self.fases[id_stop] = FASE_MOVE_IN
self.times_phase_in[id_stop] = simtime
@@ -3478,7 +3478,7 @@ def process_step(self, process):
# command vehicle to go to berth for alighting
if id_berth > -1:
if self.debug:
- print ' foreward queued vehicle id_veh prt.%d to id_berth %d at pos %.2fm' % (id_veh, id_berth, berths.stoppositions[id_berth])
+ print(' foreward queued vehicle id_veh prt.%d to id_berth %d at pos %.2fm' % (id_veh, id_berth, berths.stoppositions[id_berth]))
vehicles.control_berth_position_enter(id_veh, id_berth,
id_edge_sumo=self.ids_stop_to_ids_edge_sumo[id_stop],
# needs to stop a bit before to move in
@@ -3522,7 +3522,7 @@ def route_trip_occupied(self, id_stop, id_berth, id_veh, id_veh_sumo, simtime):
#id_veh_sumo = self.parent.prtvehicles.get_id_sumo(id_veh)
n_pax = traci.vehicle.getPersonNumber(id_veh_sumo)
if self.debug:
- print 'route_trip_occupied id_stop', id_stop, 'id_berth', id_berth, 'veh=%s' % id_veh_sumo, 'simtime', simtime, 'n_pax', n_pax
+ print('route_trip_occupied id_stop', id_stop, 'id_berth', id_berth, 'veh=%s' % id_veh_sumo, 'simtime', simtime, 'n_pax', n_pax)
# identify which of the boarding persons is in the
# vehicle which completed boarding
@@ -3535,14 +3535,14 @@ def route_trip_occupied(self, id_stop, id_berth, id_veh, id_veh_sumo, simtime):
if len(ids_person_sumo_inveh) > 0:
id_person_sumo_inveh = ids_person_sumo_inveh[0]
if self.debug:
- print ' found person %s in veh prt.%s' % (id_person_sumo_inveh, id_veh_sumo)
+ print(' found person %s in veh prt.%s' % (id_person_sumo_inveh, id_veh_sumo))
# program vehicle to person's destination
# print ' found person,origs_dests',id_person_sumo_inveh,self.id_person_to_origs_dests[id_person_sumo_inveh]
id_stop_orig, id_stop_dest, id_edge_sumo_from, id_edge_sumo_to = \
self.id_person_to_origs_dests[id_person_sumo_inveh].pop(0)
if self.debug:
- print ' found person %s' % id_person_sumo_inveh, 'from', id_stop_orig, id_edge_sumo_from, ' to', id_edge_sumo_to, id_stop_dest
+ print(' found person %s' % id_person_sumo_inveh, 'from', id_stop_orig, id_edge_sumo_from, ' to', id_edge_sumo_to, id_stop_dest)
route, duration = self.route_stop_to_stop(id_stop_orig, id_stop_dest)
@@ -3576,7 +3576,7 @@ def route_trip_occupied(self, id_stop, id_berth, id_veh, id_veh_sumo, simtime):
self.numbers_person_wait[id_stop] -= len(ids_person_sumo_inveh)
else:
- print 'WARNING: on stop %d edge %s, berth %d no person found inside vehicle prt.%d' % (id_stop, self.ids_stop_to_ids_edge_sumo[id_stop], id_berth, id_veh)
+ print('WARNING: on stop %d edge %s, berth %d no person found inside vehicle prt.%d' % (id_stop, self.ids_stop_to_ids_edge_sumo[id_stop], id_berth, id_veh))
return None
def get_surplus_veh(self, id_stop):
@@ -3594,7 +3594,7 @@ def get_surplus_veh(self, id_stop):
def get_vehs_waiting(self, id_stop):
"""Returns lists of empty and occupied waiting vehicles, as well as their respective berth IDs."""
- print 'get_vehs_waiting id_stop', id_stop
+ print('get_vehs_waiting id_stop', id_stop)
ids_berth_waiting = self.get_berths_with_state(id_stop, BERTHSTATES['waiting'])
ids_veh_waiting = self.get_berths().ids_veh[ids_berth_waiting]
@@ -3605,7 +3605,7 @@ def get_vehs_waiting(self, id_stop):
for id_berth, id_veh, id_veh_sumo in zip(ids_berth_waiting, ids_veh_waiting, self.parent.prtvehicles.ids_sumo[ids_veh_waiting]):
# check here if these vehicles are still waiting or if
# there has bee a person sitting in
- print ' check id_veh_sumo', id_veh_sumo, 'n_pers', traci.vehicle.getPersonNumber(id_veh_sumo)
+ print(' check id_veh_sumo', id_veh_sumo, 'n_pers', traci.vehicle.getPersonNumber(id_veh_sumo))
if traci.vehicle.getPersonNumber(id_veh_sumo) == 0:
ids_veh_waiting_empty.append(id_veh)
ids_berth_empty.append(id_berth)
@@ -3613,7 +3613,7 @@ def get_vehs_waiting(self, id_stop):
ids_veh_waiting_occup.append(id_veh)
ids_berth_occup.append(id_berth)
- print ' ids_veh_waiting_empty', ids_veh_waiting_empty
+ print(' ids_veh_waiting_empty', ids_veh_waiting_empty)
return ids_veh_waiting_empty, ids_veh_waiting_occup, ids_berth_empty, ids_berth_occup
def route_empties(self, id_stop, id_stop_target, n_move, simtime):
@@ -3622,19 +3622,19 @@ def route_empties(self, id_stop, id_stop_target, n_move, simtime):
Route also newly occupied vehicles if present.
Called by vehman
"""
- print 'route_empties id_stop', id_stop, '>id_stop_target', id_stop_target, 'n_move', n_move
+ print('route_empties id_stop', id_stop, '>id_stop_target', id_stop_target, 'n_move', n_move)
berths = self.get_berths()
vehicles = self.parent.prtvehicles
ids_veh_empty, ids_veh_waiting_occup, ids_berth, ids_berth_occup = self.get_vehs_waiting(id_stop)
n_veh_empty = len(ids_veh_empty)
n_move_eff = min(n_move, n_veh_empty)
- print ' =>n_veh_empty', n_veh_empty, 'n_move_eff', n_move_eff
+ print(' =>n_veh_empty', n_veh_empty, 'n_move_eff', n_move_eff)
# if n_move <= n_veh_empty:
for id_berth, id_veh in zip(ids_berth[:n_move], ids_veh_empty[:n_move]):
if self.debug:
- print ' route empty veh prt.%d' % id_veh, 'at berth', id_berth, 'from stop', id_stop, ' to', id_stop_target
+ print(' route empty veh prt.%d' % id_veh, 'at berth', id_berth, 'from stop', id_stop, ' to', id_stop_target)
route, duration = self.route_stop_to_stop(id_stop, id_stop_target)
@@ -3656,7 +3656,7 @@ def route_empties(self, id_stop, id_stop_target, n_move, simtime):
if 0: # not necessary, process step will take care of it
for id_berth, id_veh in zip(ids_berth_occup, ids_veh_waiting_occup):
if self.debug:
- print ' route occupied veh prt.%d' % id_veh, 'at berth', id_berth, 'from stop', id_stop, ' to', id_stop_target
+ print(' route occupied veh prt.%d' % id_veh, 'at berth', id_berth, 'from stop', id_stop, ' to', id_stop_target)
route, duration = self.route_stop_to_stop(id_stop, id_stop_target)
@@ -3700,7 +3700,7 @@ def foreward_vehicles_exit(self, id_stop):
ids_veh_out = self.ids_vehs_out[id_stop]
capa_out = self.capas_outqueue[id_stop]
n_veh = len(ids_veh_berth_exit)
- print 'foreward_vehicles_exit check', n_veh
+ print('foreward_vehicles_exit check', n_veh)
if n_veh == 0:
return False
@@ -3709,7 +3709,7 @@ def foreward_vehicles_exit(self, id_stop):
vehicles = self.parent.prtvehicles
are_stopped = np.zeros(n_veh, dtype=np.bool)
- for i, id_veh, state in zip(xrange(n_veh), ids_veh_berth_exit, vehicles.states[ids_veh_berth_exit]):
+ for i, id_veh, state in zip(range(n_veh), ids_veh_berth_exit, vehicles.states[ids_veh_berth_exit]):
# TODO: here we could also check vehicle position
id_veh_sumo = vehicles.get_id_sumo(id_veh)
@@ -3729,14 +3729,14 @@ def foreward_vehicles_exit(self, id_stop):
are_stopped[i] = is_stopped | (state == VEHICLESTATES['forewarding_passthrough'])
if self.debug:
- print ' %s' % id_veh_sumo, 'are_stopped', are_stopped[i], 'stop', traci.vehicle.isStopped(id_veh_sumo), 'state', state, 'laneindex', traci.vehicle.getLaneIndex(id_veh_sumo)
+ print(' %s' % id_veh_sumo, 'are_stopped', are_stopped[i], 'stop', traci.vehicle.isStopped(id_veh_sumo), 'state', state, 'laneindex', traci.vehicle.getLaneIndex(id_veh_sumo))
if self.debug:
- print ' are_stopped', are_stopped
+ print(' are_stopped', are_stopped)
if np.all(are_stopped):
if self.debug:
- print ' all vehicles are moved out of the berth'
+ print(' all vehicles are moved out of the berth')
# foreward to exit
#ids_veh_out = self.ids_vehs_out[id_stop]
@@ -3751,7 +3751,7 @@ def foreward_vehicles_exit(self, id_stop):
if self.debug:
if (len(ids_veh_out) < capa_out):
- print ' Out buffer capacity exceeded, left veh:', ids_veh_berth_exit
+ print(' Out buffer capacity exceeded, left veh:', ids_veh_berth_exit)
#self.ids_vehs_berth_exit[id_stop] = []
@@ -3772,7 +3772,7 @@ def append_to_outqueue(self, id_stop, id_veh):
laneindex=2,
)
if self.debug:
- print ' append prt.%d to output queue' % id_veh
+ print(' append prt.%d to output queue' % id_veh)
ids_veh_out.append((id_veh, stoppos))
def get_vehicles_ready_for_departure(self, id_stop):
@@ -3785,21 +3785,21 @@ def get_vehicles_ready_for_departure(self, id_stop):
n_veh = len(ids_veh_out)
ids_veh_ready = self.ids_vehs_ready_for_departure[id_stop]
is_veh_ready = len(ids_veh_ready) > 0
- print 'get_vehicles_ready_for_departure check id_stop', id_stop, ' len(ids_vehs_out)', n_veh, 'capa', self.capas_outqueue[id_stop]
+ print('get_vehicles_ready_for_departure check id_stop', id_stop, ' len(ids_vehs_out)', n_veh, 'capa', self.capas_outqueue[id_stop])
if is_veh_ready:
if self.debug:
- print ' there are still vehicles ready to be launched'
- print ' ids_veh_ready', ids_veh_ready
+ print(' there are still vehicles ready to be launched')
+ print(' ids_veh_ready', ids_veh_ready)
return []
berths = self.get_berths()
vehicles = self.parent.prtvehicles
if self.debug:
- print ' ids_berths_veh_wait_exit', type(self.ids_berths_veh_wait_exit[id_stop]), self.ids_berths_veh_wait_exit[id_stop], 'ids_veh_berth_wait', berths.ids_veh[self.ids_berths_veh_wait_exit[id_stop]]
+ print(' ids_berths_veh_wait_exit', type(self.ids_berths_veh_wait_exit[id_stop]), self.ids_berths_veh_wait_exit[id_stop], 'ids_veh_berth_wait', berths.ids_veh[self.ids_berths_veh_wait_exit[id_stop]])
if (n_veh == 0):
if self.debug:
- print ' no vehicles in output queue'
+ print(' no vehicles in output queue')
return []
# search after ready vehicles, that will be launched shortly
@@ -3814,11 +3814,11 @@ def get_vehicles_ready_for_departure(self, id_stop):
id_stopedge_target = vehicles.routes[id_veh][-1]
if self.debug:
# ,'is_stopped',is_stopped
- print ' %d Leader prt.%d' % (i, id_veh), 'id_stopedge_target', id_stopedge_target
+ print(' %d Leader prt.%d' % (i, id_veh), 'id_stopedge_target', id_stopedge_target)
else:
if self.debug:
- print ' %d Follower prt.%d' % (i, id_veh), 'is_cont next', vehicles.routes[id_veh][-1] == id_stopedge_target
+ print(' %d Follower prt.%d' % (i, id_veh), 'is_cont next', vehicles.routes[id_veh][-1] == id_stopedge_target)
if vehicles.routes[id_veh][-1] == id_stopedge_target:
ids_veh_platoon.append((id_veh, stoppos))
@@ -3830,19 +3830,19 @@ def get_vehicles_ready_for_departure(self, id_stop):
if ((len(self.ids_berths_veh_wait_exit[id_stop]) > 0) | (len(self.ids_vehs_pass_wait_exit[id_stop]) > 0))\
& (i < self.capas_outqueue[id_stop]-1):
if self.debug:
- print ' Maybe incomplete platoon, wait till all vehicles are kicked out of berths'
- print ' len(ids_berths_veh_wait_exit)', len(self.ids_berths_veh_wait_exit[id_stop]), 'len(ids_vehs_pass_wait_exit)', len(self.ids_vehs_pass_wait_exit[id_stop]), "i", i
+ print(' Maybe incomplete platoon, wait till all vehicles are kicked out of berths')
+ print(' len(ids_berths_veh_wait_exit)', len(self.ids_berths_veh_wait_exit[id_stop]), 'len(ids_vehs_pass_wait_exit)', len(self.ids_vehs_pass_wait_exit[id_stop]), "i", i)
return []
else:
# the entire out queue has the same destination
# and will leave the stop
if self.debug:
- print ' entire out queue same dest and ready for departure'
+ print(' entire out queue same dest and ready for departure')
#is_update_outqueue = False
else:
# only a part of te out-queue departs, update position of rest
if self.debug:
- print ' partial out queue ready for departure'
+ print(' partial out queue ready for departure')
#is_update_outqueue = True
# Check if all vehicles in the platoon are stopped at the
@@ -3852,13 +3852,13 @@ def get_vehicles_ready_for_departure(self, id_stop):
are_finalpos = True
ids_veh_ready_new = []
if self.debug:
- print ' position check/update ids_veh_platoon', ids_veh_platoon
+ print(' position check/update ids_veh_platoon', ids_veh_platoon)
for id_veh, stoppos in ids_veh_platoon:
id_veh_sumo = vehicles.get_id_sumo(id_veh)
is_stopped = traci.vehicle.isStopped(id_veh_sumo)
if self.debug:
- print ' stopcheck ', id_veh_sumo, 'are_stopped', are_stopped, 'is_stopped', is_stopped
+ print(' stopcheck ', id_veh_sumo, 'are_stopped', are_stopped, 'is_stopped', is_stopped)
if is_stopped:
# check if stopposition is correct
@@ -3871,7 +3871,7 @@ def get_vehicles_ready_for_departure(self, id_stop):
# vehicle is stopped but not at correct position
are_stopped = False
if self.debug:
- print ' update stoppos of prt.%s:' % id_veh_sumo, 'from curpos', pos_veh, 'stoppos', stoppos
+ print(' update stoppos of prt.%s:' % id_veh_sumo, 'from curpos', pos_veh, 'stoppos', stoppos)
# vehicle has stopped but not at the correct stop position
# =>foreward vehicle to the correct position
vehicles.control_forewarding_exit(id_veh,
@@ -3886,26 +3886,26 @@ def get_vehicles_ready_for_departure(self, id_stop):
# print ' Veh',id_veh_sumo,'is_stopped',is_stopped
# if not is_veh_ready:# means that there are not already vehicles ready
if self.debug:
- print ' append prt.%d to ids_veh_ready_new' % (id_veh)
+ print(' append prt.%d to ids_veh_ready_new' % (id_veh))
ids_veh_ready_new.append(id_veh)
if self.debug:
- print ' ready? are_stopped %s,' % (are_stopped), 'ids_veh_ready_new', ids_veh_ready_new
+ print(' ready? are_stopped %s,' % (are_stopped), 'ids_veh_ready_new', ids_veh_ready_new)
# value if platoon is ready to leave
if (not is_veh_ready) & are_stopped:
if self.debug:
- print ' all vehicles of the platoon are stopped, platoon ready.'
+ print(' all vehicles of the platoon are stopped, platoon ready.')
return ids_veh_ready_new
else:
if not are_finalpos:
self.are_reposition_out[id_stop] = True
if self.debug:
- print ' vehicles of platoon not stopped at coorect position or previous ready vehicles not launched.'
+ print(' vehicles of platoon not stopped at coorect position or previous ready vehicles not launched.')
else:
if self.debug:
- print ' not all vehicles of platoon stopped or previous ready vehicles not launched.'
+ print(' not all vehicles of platoon stopped or previous ready vehicles not launched.')
return []
def _reposition_outqueue(self, id_stop):
@@ -3949,7 +3949,7 @@ def prepare_vehs_for_departure(self, id_stop, ids_veh):
"""
#ids_veh_out = self.ids_vehs_out[id_stop]
n_veh = len(ids_veh)
- print 'prepare_vehs_for_departure id_stop', id_stop, 'n_veh', n_veh
+ print('prepare_vehs_for_departure id_stop', id_stop, 'n_veh', n_veh)
ids_veh_out = self.ids_vehs_out[id_stop]
if n_veh == 0:
return False
@@ -3962,10 +3962,10 @@ def prepare_vehs_for_departure(self, id_stop, ids_veh):
vehicles.concatenate(id_veh, id_veh_infront)
if self.debug:
- print ' prepared:'
+ print(' prepared:')
for id_veh, route in zip(ids_veh, vehicles.routes[ids_veh]):
id_stopedge = route[-1]
- print ' prep. prt.%d' % id_veh, 'with id_stopedge', id_stopedge, 'id_stop', self.id_edge_to_id_stop[id_stopedge]
+ print(' prep. prt.%d' % id_veh, 'with id_stopedge', id_stopedge, 'id_stop', self.id_edge_to_id_stop[id_stopedge])
id_veh_lead = ids_veh[0]
id_stopedge_target = vehicles.routes[id_veh_lead][-1]
@@ -3975,16 +3975,16 @@ def prepare_vehs_for_departure(self, id_stop, ids_veh):
self.parent.vehicleman.note_vehs_ready_for_departure(id_stop, id_stop_target, time_est, n_veh)
- for i in xrange(n_veh):
+ for i in range(n_veh):
ids_veh_out.pop(0)
if len(ids_veh_out) > 0:
if self.debug:
- print ' position update for remaining ids_veh_out', ids_veh_out
+ print(' position update for remaining ids_veh_out', ids_veh_out)
# move foreward stoplines of remaining vehicles in output queue
stopline = self.stoplines[id_stop]
id_edge_sumo = self.ids_stop_to_ids_edge_sumo[id_stop]
- for ind in xrange(len(ids_veh_out)):
+ for ind in range(len(ids_veh_out)):
id_veh, stoppos_prev = ids_veh_out[ind]
stoppos = stopline - ind * (vehicles.length+1.5*vehicles.dist_min)
# vehicles.control_forewarding_exit(id_veh,\
@@ -3995,7 +3995,7 @@ def prepare_vehs_for_departure(self, id_stop, ids_veh):
if self.debug:
id_veh_sumo = 'prt.%s' % id_veh
- print ' update stoppos of prt.%s:' % id_veh_sumo, 'from curpos', traci.vehicle.getLanePosition(id_veh_sumo), 'to stoppos', stoppos
+ print(' update stoppos of prt.%s:' % id_veh_sumo, 'from curpos', traci.vehicle.getLanePosition(id_veh_sumo), 'to stoppos', stoppos)
# print ' stopinfo:',traci.vehicle.getNextStops(id_veh_sumo)
ids_veh_out[ind] = (id_veh, stoppos)
@@ -4006,16 +4006,16 @@ def launch_vehs(self, id_stop, id_stop_target):
"""
Method called from vehicle management when vehicles are allowed to depart.
"""
- print 'launch_vehs at id_stop', id_stop
+ print('launch_vehs at id_stop', id_stop)
ids_veh = self.ids_vehs_ready_for_departure[id_stop]
#ids_veh_out = self.ids_vehs_out[id_stop]
vehicles = self.parent.prtvehicles
#ids_veh = self.ids_vehs_ready_for_departure[id_stop]
# if self.debug:
- print ' to launch: ids_veh', ids_veh # ,'with ids_stopedge_next',vehicles.routes[ids_veh]
+ print(' to launch: ids_veh', ids_veh) # ,'with ids_stopedge_next',vehicles.routes[ids_veh]
if len(ids_veh) == 0:
- print 'WARNING in launch_vehs: there are no vehicles to lauche at id_stop', id_stop
+ print('WARNING in launch_vehs: there are no vehicles to lauche at id_stop', id_stop)
# here may check if destination stop is correct
@@ -4024,7 +4024,7 @@ def launch_vehs(self, id_stop, id_stop_target):
#id_veh_out, stoppos = ids_veh_out.pop(0)
# if self.debug:
- print ' launched prt.%d to id_stopedge_target %d' % (id_veh, vehicles.routes[id_veh][-1])
+ print(' launched prt.%d to id_stopedge_target %d' % (id_veh, vehicles.routes[id_veh][-1]))
# if id_veh_out != id_veh:
# print 'WARNING: wrong vehicle from output queue'
# sys.exit(0)
@@ -4046,7 +4046,7 @@ def is_outputqueue_compact(self, id_stop):
the last berth of the stop"""
pos_lastberth = self.get_berths().stoppositions[self.ids_berths[id_stop]][-1]
- print 'is_outputqueue_compact n_outqueue', len(self.ids_vehs_out[id_stop]), 'pos_lastberth %.2f' % pos_lastberth
+ print('is_outputqueue_compact n_outqueue', len(self.ids_vehs_out[id_stop]), 'pos_lastberth %.2f' % pos_lastberth)
vehicles = self.parent.prtvehicles
is_compact = True
@@ -4070,7 +4070,7 @@ def is_outputqueue_compact(self, id_stop):
break
if self.debug:
- print ' is_compact', is_compact
+ print(' is_compact', is_compact)
return is_compact
def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
@@ -4079,42 +4079,42 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
while maximizing platooning.
"""
- print 'try_start_vehicles id_stop', id_stop, 'veh exiting', len(self.ids_vehs_berth_exit[id_stop]),\
+ print('try_start_vehicles id_stop', id_stop, 'veh exiting', len(self.ids_vehs_berth_exit[id_stop]),\
'wait from berth', len(self.ids_berths_veh_wait_exit[id_stop]), 'wait to pass', len(
- self.ids_vehs_pass_wait_exit[id_stop])
+ self.ids_vehs_pass_wait_exit[id_stop]))
n_plat_max = self.capas_inqueue[id_stop] - \
(len(self.ids_vehs_out[id_stop])+len(self.ids_vehs_ready_for_departure[id_stop]))
if self.debug:
- print ' n_plat_max', n_plat_max
+ print(' n_plat_max', n_plat_max)
if n_plat_max == 0:
if self.debug:
- print ' insufficient sapce in output queue'
+ print(' insufficient sapce in output queue')
return False
if len(self.ids_vehs_berth_exit[id_stop]) > 0:
if self.debug:
- print ' there are still vehicles moving out of berth'
+ print(' there are still vehicles moving out of berth')
return False
elif not self.is_outputqueue_compact(id_stop):
if self.debug:
- print ' there are still vehicles in berth area toward exit queue'
+ print(' there are still vehicles in berth area toward exit queue')
return False
if self.debug:
- print ' len(ids_veh_inqueue)', len(self.ids_vehs_inqueue[id_stop])
+ print(' len(ids_veh_inqueue)', len(self.ids_vehs_inqueue[id_stop]))
if len(self.ids_vehs_inqueue[id_stop]) > 0:
ids_veh_pass = self.get_ids_veh_to_pass(id_stop)
if self.debug:
- print ' found ids_veh_pass', ids_veh_pass, 'not yet started!'
+ print(' found ids_veh_pass', ids_veh_pass, 'not yet started!')
else:
ids_veh_pass = []
n_veh_pass = len(ids_veh_pass)
n_veh_pass_wait = len(self.ids_vehs_pass_wait_exit[id_stop])
if self.debug:
- print ' n_veh_pass', n_veh_pass, 'n_veh_pass_wait', n_veh_pass_wait
+ print(' n_veh_pass', n_veh_pass, 'n_veh_pass_wait', n_veh_pass_wait)
berths = self.get_berths()
vehicles = self.parent.prtvehicles
@@ -4126,8 +4126,8 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
if n_veh_pass_wait > 0:
if self.debug:
- print ' there are passthrough vehicle in the input queue waiting to get started', self.ids_vehs_pass_wait_exit[id_stop]
- print ' ids_veh_pass_wait_exit', self.ids_vehs_pass_wait_exit[id_stop]
+ print(' there are passthrough vehicle in the input queue waiting to get started', self.ids_vehs_pass_wait_exit[id_stop])
+ print(' ids_veh_pass_wait_exit', self.ids_vehs_pass_wait_exit[id_stop])
# these vehicles have a common target
ids_veh_pass_wait_exit = self.ids_vehs_pass_wait_exit[id_stop]
while len(ids_veh_pass_wait_exit) > 0:
@@ -4142,7 +4142,7 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
elif len(self.ids_berths_veh_wait_exit[id_stop]) > 0:
ids_berth_veh_wait_exit = self.ids_berths_veh_wait_exit[id_stop]
if self.debug:
- print ' there are vehicles in berth which are listed to start.', ids_berth_veh_wait_exit
+ print(' there are vehicles in berth which are listed to start.', ids_berth_veh_wait_exit)
# do start them, sorted by final destination
# print ' ids_berth_veh_wait_exit',ids_berth_veh_wait_exit
@@ -4154,7 +4154,7 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
ids_stop_target = vehicles.ids_stop_target[ids_veh]
inds_start = ids_stop_target == ids_stop_target[0]
if self.debug:
- print ' start waiting vehicles', ids_veh[inds_start], 'to final id_stop_target', ids_stop_target[0]
+ print(' start waiting vehicles', ids_veh[inds_start], 'to final id_stop_target', ids_stop_target[0])
self._kick_out_of_berth(id_stop, ids_veh[inds_start], np.array(
ids_berth_veh_wait_exit, dtype=np.int32)[inds_start], vehicles, berths)
for id_berth in np.array(ids_berth_veh_wait_exit, dtype=np.int32)[inds_start]:
@@ -4164,7 +4164,7 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
if ((simtime - self.times_phase_out[id_stop]) > self.time_fase_out_max.get_value()) & (n_veh_pass == 0):
# stop starting if move in phase is timed out
if self.debug:
- print ' fase move out timeout, stop starting'
+ print(' fase move out timeout, stop starting')
return False
# berth in reverse order means that the berth closest to the exit comes first
@@ -4186,7 +4186,7 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
n_veh_all = n_veh+n_veh_pass
n_edge_max = 0
- for i, id_veh, route in zip(xrange(n_veh_all), ids_veh_ready_all, vehicles.routes[ids_veh_ready_all]):
+ for i, id_veh, route in zip(range(n_veh_all), ids_veh_ready_all, vehicles.routes[ids_veh_ready_all]):
#ids_edge_target[i] = route[-1]
if len(route) > n_edge_max:
n_edge_max = len(route)
@@ -4198,18 +4198,18 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
overtime = simtime - berths.times_routes[ids_berth_ready]-self.time_wait_berth_max.get_value()
overtime_berth_ready = overtime * (overtime > 0)
if self.debug:
- print ' vehicles ready to leave berth n_veh %d including input n_veh_all %d' % (n_veh, n_veh_all)
- print ' ids_stop_target from berths', ids_stop_target
- print ' ids_berth', berths.states[ids_berth]
- print ' berths.state', berths.states[ids_berth]
- print ' ids_berth_ready', ids_berth_ready
- print ' ids_veh_ready', ids_veh_ready
- print ' ids_veh_ready_all', ids_veh_ready_all
- print
- print ' simtime', simtime
- print ' overtime_berth_ready', overtime_berth_ready
- print ' berths.times_routes[ids_berth_ready]', berths.times_routes[ids_berth_ready]
- print ' time_wait_berth_max', self.time_wait_berth_max.get_value()
+ print(' vehicles ready to leave berth n_veh %d including input n_veh_all %d' % (n_veh, n_veh_all))
+ print(' ids_stop_target from berths', ids_stop_target)
+ print(' ids_berth', berths.states[ids_berth])
+ print(' berths.state', berths.states[ids_berth])
+ print(' ids_berth_ready', ids_berth_ready)
+ print(' ids_veh_ready', ids_veh_ready)
+ print(' ids_veh_ready_all', ids_veh_ready_all)
+ print()
+ print(' simtime', simtime)
+ print(' overtime_berth_ready', overtime_berth_ready)
+ print(' berths.times_routes[ids_berth_ready]', berths.times_routes[ids_berth_ready])
+ print(' time_wait_berth_max', self.time_wait_berth_max.get_value())
# if 0: # deal with this case in platoon optimizarion
# print ' there are vehhicles in the input queue'
@@ -4218,7 +4218,7 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
if n_veh_pass > 0:
if self.debug:
- print ' There is at least one passthrough vehicle which needs to get launched'
+ print(' There is at least one passthrough vehicle which needs to get launched')
#id_edge_target_max = vehicles.get_targetedge_current(ids_veh_pass[0])
id_stop_target_max = vehicles.ids_stop_target[ids_veh_pass[0]]
@@ -4235,7 +4235,7 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
ids_berth_plat = np.array([])
if self.debug:
- print ' vehs with same dest as pass', ids_veh_plat
+ print(' vehs with same dest as pass', ids_veh_plat)
self._kick_out_of_berth(id_stop, ids_veh_plat, ids_berth_plat, vehicles, berths)
@@ -4249,7 +4249,7 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
elif (np.any(overtime_berth_ready) > 0) & (n_veh_pass == 0):
if self.debug:
- print ' at some berth maximum wait time has been exceeded'
+ print(' at some berth maximum wait time has been exceeded')
# TODO: launche all vehicles with overtime putting them into self.ids_berths_veh_wait_exit[id_stop]
# take vehicle with maximum wait time and try to create a platoon
@@ -4291,7 +4291,7 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
else: # if n_veh > n_plat_min:
- print ' Maximize platoon length'
+ print(' Maximize platoon length')
edgeutilities = self.get_scenario().net.edges.lengths
# utilities = np.sum(edgeutilities[routes_common],1)*counts_common
@@ -4301,12 +4301,12 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
# -1 is required to detect stop
ids_edges = -1*np.ones((n_veh_all, n_edge_max+1), dtype=np.int32)
- for i, id_veh, route in zip(xrange(n_veh_all), ids_veh_ready_all, vehicles.routes[ids_veh_ready_all]):
+ for i, id_veh, route in zip(range(n_veh_all), ids_veh_ready_all, vehicles.routes[ids_veh_ready_all]):
# print ' get route prt.%d'%id_veh,'i',i,'route',route
ids_edges[i, :len(route)] = route
if self.debug > 9:
- print ' ids_edges=\n', ids_edges
+ print(' ids_edges=\n', ids_edges)
n_veh_all, n_edge_max = ids_edges.shape
is_cont = True # not used
@@ -4322,17 +4322,17 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
inds_stop = np.flatnonzero(ids_edges[:, j] == -1)
if self.debug:
- print ' j=', j, 'inds_stop', inds_stop
+ print(' j=', j, 'inds_stop', inds_stop)
if len(inds_stop) > 0:
if self.debug:
- print ' create set of routes that lead to one of the stops'
+ print(' create set of routes that lead to one of the stops')
occurencies = OrderedDict()
for ids_edge, ind_stop in zip(ids_edges[inds_stop, 0:j-2], inds_stop):
# print ' ind_stop',ind_stop,'ids_edge',ids_edge
occurencies[tuple(ids_edge)] = 0
- for ind, ids_edge in zip(xrange(n_veh_all), ids_edges[:, :]):
+ for ind, ids_edge in zip(range(n_veh_all), ids_edges[:, :]):
ids_edge_tuple = tuple(ids_edge[0:j-2])
# print ' check ids_edge',ids_edge
# print ' common?',ids_edge_tuple
@@ -4348,8 +4348,8 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
occurencies[ids_edge_tuple] += 1
# print ' occurencies',occurencies
- routes_common = np.array(occurencies.keys(), dtype=np.int32)
- counts_common = occurencies.values()
+ routes_common = np.array(list(occurencies.keys()), dtype=np.int32)
+ counts_common = list(occurencies.values())
utilities = np.sum(edgeutilities[routes_common], 1)*counts_common
ind_max = np.argmax(utilities)
@@ -4369,8 +4369,8 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
# print '-'*10
if self.debug:
- print ' utility_max', utility_max
- print ' route_common_max', route_common_max, type(route_common_max)
+ print(' utility_max', utility_max)
+ print(' route_common_max', route_common_max, type(route_common_max))
j_max = len(route_common_max)+2
@@ -4384,12 +4384,12 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
break
if self.debug:
- print ' route_max', route_max
+ print(' route_max', route_max)
inds_veh_plat_deviate = []
inds_veh_plat_nodeviate = []
inds_veh_plat = []
- for ind, ids_edge, is_stop in zip(xrange(n_veh_all), ids_edges[:, :], ids_edges[:, j_max] == -1):
+ for ind, ids_edge, is_stop in zip(range(n_veh_all), ids_edges[:, :], ids_edges[:, j_max] == -1):
if np.array_equal(ids_edge[0:j_max-2], route_common_max):
if self._is_stop(j_max, ids_edge):
inds_veh_plat.append(ind)
@@ -4416,27 +4416,27 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
iinds_plat_passthrough = inds_veh_plat >= n_veh
# print ' ids_edges_out\n',ids_edges_out
if self.debug:
- print ' inds_veh_plat\n', inds_veh_plat
- print ' inds_veh_plat_deviate\n', inds_veh_plat_deviate
- print ' inds_veh_plat_nodeviate\n', inds_veh_plat_nodeviate
- print ' inds_veh_plat_deviate_berth\n', inds_veh_plat_deviate[iinds_plat_deviate_berth]
- print ' inds_veh_plat_nodeviate_berth\n', inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]
- print ' iinds_plat_passthrough\n', iinds_plat_passthrough
- print ' inds_veh_plat_passthrough\n', inds_veh_plat[iinds_plat_passthrough]
+ print(' inds_veh_plat\n', inds_veh_plat)
+ print(' inds_veh_plat_deviate\n', inds_veh_plat_deviate)
+ print(' inds_veh_plat_nodeviate\n', inds_veh_plat_nodeviate)
+ print(' inds_veh_plat_deviate_berth\n', inds_veh_plat_deviate[iinds_plat_deviate_berth])
+ print(' inds_veh_plat_nodeviate_berth\n', inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth])
+ print(' iinds_plat_passthrough\n', iinds_plat_passthrough)
+ print(' inds_veh_plat_passthrough\n', inds_veh_plat[iinds_plat_passthrough])
n_veh_plat = len(inds_veh_plat)
# print ' id_edge_target_max',id_edge_target_max,'n_veh_plat',n_veh_plat,n_veh_plat >= n_plat_min
if (n_veh_plat >= n_plat_min) | (np.max(inds_veh_plat) >= n_veh):
if self.debug:
- print ' platoon formation long enough n_veh_plat', n_veh_plat, 'or passthrough', (np.max(inds_veh_plat) >= n_veh)
+ print(' platoon formation long enough n_veh_plat', n_veh_plat, 'or passthrough', (np.max(inds_veh_plat) >= n_veh))
- print ' deviate vehicles berth', ids_veh_ready_all[inds_veh_plat_deviate[iinds_plat_deviate_berth]]
+ print(' deviate vehicles berth', ids_veh_ready_all[inds_veh_plat_deviate[iinds_plat_deviate_berth]])
for id_veh in ids_veh_ready_all[inds_veh_plat_deviate[iinds_plat_deviate_berth]]:
# note that all routed vehicles are already disengaged
vehicles.set_route_target(id_veh, route_max, is_disengage_from_berth=False)
if self.debug:
- print ' deviate vehicles passthrough', ids_veh_ready_all[inds_veh_plat_deviate[np.logical_not(iinds_plat_deviate_berth)]]
+ print(' deviate vehicles passthrough', ids_veh_ready_all[inds_veh_plat_deviate[np.logical_not(iinds_plat_deviate_berth)]])
for id_veh in ids_veh_ready_all[inds_veh_plat_deviate[np.logical_not(iinds_plat_deviate_berth)]]:
vehicles.set_route_target(id_veh, route_max)
# ?here next stop is identical with final route
@@ -4446,8 +4446,8 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
# start immediately vehicles with final destination from berths
if self.debug:
- print ' kick out ids_veh', ids_veh_ready[inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]]
- print ' from berths ', ids_berth_ready[inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]]
+ print(' kick out ids_veh', ids_veh_ready[inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]])
+ print(' from berths ', ids_berth_ready[inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]])
self._kick_out_of_berth(id_stop, ids_veh_ready[inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]],
ids_berth_ready[inds_veh_plat_nodeviate[iinds_plat_nodeviate_berth]], vehicles, berths)
@@ -4455,17 +4455,17 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
# they will be started later while being sorted by final
# destination
if self.debug:
- print ' ids_berths_veh_wait_exit before', self.ids_berths_veh_wait_exit[id_stop]
+ print(' ids_berths_veh_wait_exit before', self.ids_berths_veh_wait_exit[id_stop])
self.ids_berths_veh_wait_exit[id_stop] += ids_berth_ready[inds_veh_plat_deviate[iinds_plat_deviate_berth]].tolist()
if self.debug:
- print ' ids_berths_veh_wait_exit after ', self.ids_berths_veh_wait_exit[id_stop]
- print ' ids_berth_ready', ids_berth_ready
+ print(' ids_berths_veh_wait_exit after ', self.ids_berths_veh_wait_exit[id_stop])
+ print(' ids_berth_ready', ids_berth_ready)
# ATTENTION: vehicles waiting in input queue cannot be sorted by destination...
# but they are supposed to be sorted already?
self.ids_vehs_pass_wait_exit[id_stop] += ids_veh_ready_all[inds_veh_plat[iinds_plat_passthrough]].tolist()
if self.debug:
- print ' ids_vehs_pass_wait_exit after ', self.ids_vehs_pass_wait_exit[id_stop]
+ print(' ids_vehs_pass_wait_exit after ', self.ids_vehs_pass_wait_exit[id_stop])
# get the destination stop from final stop of the undevieted winner
id_stop_target_max = vehicles.ids_stop_target[ids_veh_ready_all[inds_veh_plat_nodeviate[0]]]
@@ -4475,12 +4475,12 @@ def try_start_vehicles(self, id_stop, simtime, n_plat_min=-1):
else:
if self.debug:
- print ' platoon too short'
+ print(' platoon too short')
return False
else:
if self.debug:
- print ' no vehicles finished boarding'
+ print(' no vehicles finished boarding')
return False
def _is_stop(self, j, ids_edge):
@@ -4493,7 +4493,7 @@ def _is_stop(self, j, ids_edge):
def _kick_out_of_berth(self, id_stop, ids_veh_plat, ids_berth_plat, vehicles, berths):
for id_veh, id_berth in zip(ids_veh_plat, ids_berth_plat):
- print ' kick veh %d out of berth %d and set berth free' % (id_veh, id_berth)
+ print(' kick veh %d out of berth %d and set berth free' % (id_veh, id_berth))
berths.set_free(id_berth)
vehicles.control_berth_position_exit(id_veh,
id_edge_sumo=self.ids_stop_to_ids_edge_sumo[id_stop],\
@@ -4518,7 +4518,7 @@ def get_berths_with_state(self, id_stop, state):
return ids_berth[self.get_berths().states[ids_berth] == state]
def enter(self, id_stop, ids_veh, fase, simtime):
- print 'enter ids_veh', ids_veh
+ print('enter ids_veh', ids_veh)
vehicles = self.parent.prtvehicles
@@ -4535,14 +4535,14 @@ def enter(self, id_stop, ids_veh, fase, simtime):
self.numbers_veh[id_stop] += n_veh
are_completed = np.zeros(n_veh, dtype=np.bool)
- for id_veh, i in zip(ids_veh, xrange(n_veh)):
+ for id_veh, i in zip(ids_veh, range(n_veh)):
vehicles.decatenate(id_veh)
# here we should check whether the vehicle needs to alight
# or wether it is a pass through
route = vehicles.routes[id_veh]
if self.debug:
- print ' enter prt.%d' % id_veh, 'with id_stop_target', vehicles.ids_stop_target[id_veh], 'route', route
+ print(' enter prt.%d' % id_veh, 'with id_stop_target', vehicles.ids_stop_target[id_veh], 'route', route)
if len(route) == 0:
# vehicle just initialized
are_completed[i] = True
@@ -4574,14 +4574,14 @@ def enter(self, id_stop, ids_veh, fase, simtime):
n_veh_completed = len(ids_veh_completed)
ids_berth = -1*np.ones(n_veh, dtype=np.int32)
if self.debug:
- print ' n_veh_completed', n_veh_completed, 'no Timeout', ((simtime - self.times_phase_in[id_stop]) < self.time_fase_in_max.get_value()), 'veh input', self.ids_vehs_inqueue[id_stop]
+ print(' n_veh_completed', n_veh_completed, 'no Timeout', ((simtime - self.times_phase_in[id_stop]) < self.time_fase_in_max.get_value()), 'veh input', self.ids_vehs_inqueue[id_stop])
# if fase == FASE_MOVE_IN:
# print ' timeout fase 0: dt=%.2f timeout=%.2f'%((simtime - self.times_phase_in[id_stop]), self.time_fase_in_max.get_value())
if n_veh_completed > 0:
# (simtime - self.times_phase_in[id_stop]), self.time_fase_in_max.get_value())
if self.debug:
# ,(len(self.ids_vehs_inqueue[id_stop]) == 0),((simtime - self.times_phase_in[id_stop]) > self.time_fase_in_max.get_value())
- print ' fase', fase
+ print(' fase', fase)
if (fase == FASE_MOVE_IN) & (len(self.ids_vehs_inqueue[id_stop]) == 0)\
& ((simtime - self.times_phase_in[id_stop]) < self.time_fase_in_max.get_value()):
# here vehicles are sent to berth, if available
@@ -4592,22 +4592,22 @@ def enter(self, id_stop, ids_veh, fase, simtime):
# allocate berth only for vehicles which completed trip at this stop
ids_berth_completed = self.allocate_alight(id_stop, n_veh_completed)
if self.debug:
- print ' ids_berth_completed', ids_berth_completed
+ print(' ids_berth_completed', ids_berth_completed)
ids_berth[are_completed] = ids_berth_completed
is_stop_moving_in = False
for id_veh, state, id_berth, is_completed in zip(ids_veh, vehicles.states[ids_veh], ids_berth, are_completed):
if self.debug:
- print ' check id_veh', id_veh, 'id_berth', id_berth, 'is_completed', is_completed, 'state', state
+ print(' check id_veh', id_veh, 'id_berth', id_berth, 'is_completed', is_completed, 'state', state)
if not is_completed:
# will be send directly to output queue
if self.debug:
- print ' passthrough, not final destination of vehicle.'
+ print(' passthrough, not final destination of vehicle.')
is_stop_moving_in = True
if self.debug:
- print ' stop before first berths, wait for try_start at %.1fm' % (self.stoplines_in[id_stop])
+ print(' stop before first berths, wait for try_start at %.1fm' % (self.stoplines_in[id_stop]))
# this vehicle does not get allocated to a berth
# but will wait until vehicles with same destination move out
@@ -4639,10 +4639,10 @@ def enter(self, id_stop, ids_veh, fase, simtime):
elif id_berth == -1:
if self.debug:
- print ' trip is completed but no berth => stop vehicles from moving in'
+ print(' trip is completed but no berth => stop vehicles from moving in')
is_stop_moving_in = True
if self.debug:
- print ' stop before first berths and wait for allocation at %.1fm' % (self.stoplines_in[id_stop])
+ print(' stop before first berths and wait for allocation at %.1fm' % (self.stoplines_in[id_stop]))
self.ids_vehs_inqueue[id_stop].append(id_veh)
vehicles.control_stopline_enter(id_veh,
self.ids_stop_to_ids_edge_sumo[id_stop],
@@ -4651,7 +4651,7 @@ def enter(self, id_stop, ids_veh, fase, simtime):
elif (not is_stop_moving_in) & (id_berth != -1):
if self.debug:
- print ' forewrard entering vehicle id_veh %d to id_berth_alight %d at pos %.2fm' % (id_veh, id_berth, self.get_berths().stoppositions[id_berth])
+ print(' forewrard entering vehicle id_veh %d to id_berth_alight %d at pos %.2fm' % (id_veh, id_berth, self.get_berths().stoppositions[id_berth]))
self.ids_vehs_alight_forward[id_stop].append(id_veh)
vehicles.control_berth_position_enter(
id_veh, id_berth,
@@ -4660,7 +4660,7 @@ def enter(self, id_stop, ids_veh, fase, simtime):
laneindex=2,
)
if self.debug:
- print ' ids_vehs_inqueue (after)', self.ids_vehs_inqueue[id_stop]
+ print(' ids_vehs_inqueue (after)', self.ids_vehs_inqueue[id_stop])
def get_ids_veh_to_allocate(self, id_stop):
"""Returns vehicle in input queue that needs berth allocation.
@@ -4721,7 +4721,7 @@ def get_ids_veh_to_pass(self, id_stop):
return []
def exit(self, id_stop, id_veh, fase):
- print 'exit prt.%d at stop %d fase %d' % (id_veh, id_stop, fase)
+ print('exit prt.%d at stop %d fase %d' % (id_veh, id_stop, fase))
self.ids_vehs[id_stop].remove(id_veh)
self.ids_vehs_ready_for_departure[id_stop].remove(id_veh)
#id_stop_target = self.parent.vehicleman.start_trip(id_veh, id_stop)
@@ -4764,71 +4764,71 @@ def allocate_alight(self, id_stop, n_alloc):
# default berth ID is -1 means no merth available
ids_berth_alloc = -1*np.ones(n_alloc, dtype=np.int32)
- print 'allocate_alight n_alloc', n_alloc, 'n_berth_to_allocate', n_berth_to_allocate, 'ind_berth_to_allocate', ind_berth_to_allocate
+ print('allocate_alight n_alloc', n_alloc, 'n_berth_to_allocate', n_berth_to_allocate, 'ind_berth_to_allocate', ind_berth_to_allocate)
if self.debug:
- print ' ids_berth_to_allocate', ids_berth_to_allocate
+ print(' ids_berth_to_allocate', ids_berth_to_allocate)
if ind_berth_to_allocate == -1:
if self.debug:
- print ' no free berth :('
+ print(' no free berth :(')
return ids_berth_alloc
elif n_berth_to_allocate <= n_alloc:
if self.debug:
- print ' there is a less or equal number of free berth than requested'
+ print(' there is a less or equal number of free berth than requested')
# => use all berth available for allocatation
ids_berth_alloc[0:n_berth_to_allocate] = ids_berth_to_allocate[0:n_berth_to_allocate]
self.inds_berth_allocated[id_stop] = -1
else:
if self.debug:
- print ' there are more berths available than vehicles to allocate'
+ print(' there are more berths available than vehicles to allocate')
# -> prefer berth with person queues
queues = self.get_berthqueues(id_stop, ids_berth_to_allocate)
#inds_nonzeroqueues = np.flatnonzero(ids_berth_to_allocate[::-1])
ind_alloc_eff = -1 # effective allocation index for result vector
- for i, queue, id_berth in zip(xrange(n_berth_to_allocate), queues[::-1], ids_berth_to_allocate[::-1]):
- print ' index i', i, 'id_berth', id_berth, 'queue', queue
+ for i, queue, id_berth in zip(range(n_berth_to_allocate), queues[::-1], ids_berth_to_allocate[::-1]):
+ print(' index i', i, 'id_berth', id_berth, 'queue', queue)
self.inds_berth_allocated[id_stop] -= 1
if queue == 0:
if self.debug:
- print ' no passengers waiting'
+ print(' no passengers waiting')
# allocate this berth only if the number of the remaining
# available berth is less or equal the number of berth
# that remain to be allocated
is_allzero = not np.any(queues[::-1][i:])
if self.debug:
- print ' remaining berth to alloc', ids_berth_to_allocate[::-1][i:]
- print ' remaining queus to alloc', queues[::-1][i:]
- print ' rem avail', n_berth_to_allocate-(i+1), 'rem to alloc', n_alloc-(ind_alloc_eff + 1), 'is_allzero', is_allzero
+ print(' remaining berth to alloc', ids_berth_to_allocate[::-1][i:])
+ print(' remaining queus to alloc', queues[::-1][i:])
+ print(' rem avail', n_berth_to_allocate-(i+1), 'rem to alloc', n_alloc-(ind_alloc_eff + 1), 'is_allzero', is_allzero)
if is_allzero | ((n_berth_to_allocate-(i+1)) < (n_alloc-(ind_alloc_eff + 1))):
ind_alloc_eff += 1
ids_berth_alloc[ind_alloc_eff] = id_berth
if self.debug:
- print ' allocate id_berth', id_berth, 'at index', i
+ print(' allocate id_berth', id_berth, 'at index', i)
else:
if self.debug:
- print ' passengers waiting, allocate'
+ print(' passengers waiting, allocate')
ind_alloc_eff += 1
ids_berth_alloc[ind_alloc_eff] = id_berth
if self.debug:
- print ' allocate id_berth', id_berth, 'at index', i
+ print(' allocate id_berth', id_berth, 'at index', i)
if n_alloc == ind_alloc_eff + 1:
if self.debug:
- print ' all vehicles allocated. Stop allocating.'
+ print(' all vehicles allocated. Stop allocating.')
break
if self.debug:
- print ' finished allocating i', i, 'ind_berth_to_allocate', ind_berth_to_allocate, 'rem', n_berth_to_allocate-(i+1)
+ print(' finished allocating i', i, 'ind_berth_to_allocate', ind_berth_to_allocate, 'rem', n_berth_to_allocate-(i+1))
# print ' inds_berth_allocated',self.inds_berth_allocated [id_stop],n_berth_to_allocate-(i+1)
#self.inds_berth_allocated [id_stop] = n_berth_to_allocate-(i+1)
if self.debug:
- print ' ids_berth_alloc', ids_berth_alloc
+ print(' ids_berth_alloc', ids_berth_alloc)
# set allocated to found berth only
self.get_berths().set_allocate(ids_berth_alloc[ids_berth_alloc > -1])
@@ -4844,7 +4844,7 @@ def is_queue(self, id_stop, id_berth):
stopposition = self.get_berths().stoppositions[id_berth]
# print ' stopposition',stopposition
is_queue = False
- for id_person_sumo in self.waittimes_persons[id_stop].keys():
+ for id_person_sumo in list(self.waittimes_persons[id_stop].keys()):
is_queue = np.abs(stopposition-traci.person.getLanePosition(id_person_sumo)) < 0.8
if is_queue:
break
@@ -4852,17 +4852,17 @@ def is_queue(self, id_stop, id_berth):
return is_queue
def get_berthqueues(self, id_stop, ids_berth):
- print 'get_berthqueues ids_berth', ids_berth
+ print('get_berthqueues ids_berth', ids_berth)
# currently not used
# print 'get_berthqueues',id_stop
# TODO: use stop angle and person angle to detect waiting persons
stoppositions = self.get_berths().stoppositions[ids_berth]
queues = np.zeros(len(ids_berth), dtype=np.int32)
# print ' stoppositions',stoppositions
- for id_person_sumo in self.waittimes_persons[id_stop].keys():
+ for id_person_sumo in list(self.waittimes_persons[id_stop].keys()):
stage = traci.person.getStage(id_person_sumo, 0)
if self.debug:
- print ' check id_person_sumo', id_person_sumo, 'Stagetype', stage.type, 'pos', traci.person.getLanePosition(id_person_sumo)
+ print(' check id_person_sumo', id_person_sumo, 'Stagetype', stage.type, 'pos', traci.person.getLanePosition(id_person_sumo))
# check if person is in wait pos! Actually this is stage type driving = 3
if stage.type == 3:
position = traci.person.getLanePosition(id_person_sumo)
@@ -4880,7 +4880,7 @@ def make_from_net(self):
"""
Make prt stop database from PT stops in network.
"""
- print 'make_from_net'
+ print('make_from_net')
self.clear()
net = self.get_scenario().net
ptstops = net.ptstops
@@ -4906,7 +4906,7 @@ def make_from_net(self):
ptstops.positions_to[ids_ptstop],
edgelengths
):
- print ' check', id_stop, 'number of lanes', len(ids_lane), ids_lane
+ print(' check', id_stop, 'number of lanes', len(ids_lane), ids_lane)
ids_mode_allow = ids_modes_allow[ids_lane]
if len(ids_lane) == 3:
@@ -4941,7 +4941,7 @@ def make(self, id_ptstop, position_from, position_to):
class VehicleAdder(Process):
def __init__(self, vehicles, logger=None, **kwargs):
- print 'VehicleAdder.__init__', vehicles, vehicles.parent.get_ident()
+ print('VehicleAdder.__init__', vehicles, vehicles.parent.get_ident())
self._init_common('vehicleadder', name='Vehicle adder',
logger=logger,
info='Add vehicles to PRT stops of network.',
@@ -5091,7 +5091,7 @@ def make_vtype(self, is_reset_vtype=False):
vtypes = self.get_scenario().demand.vtypes
prttype = 'HCPRT'
- print 'make_vtype HPRT', prttype
+ print('make_vtype HPRT', prttype)
# speedmode
# https://sumo.dlr.de/docs/TraCI/Change_Vehicle_State.html
# bit0: Regard safe speed
@@ -5129,10 +5129,10 @@ def make_vtype(self, is_reset_vtype=False):
if vtypes.ids_sumo.has_index(prttype):
id_vtype = vtypes.ids_sumo.get_id_from_index(prttype)
vtypes.del_row(id_vtype)
- print ' deleted', prttype, 'id_vtype', id_vtype
+ print(' deleted', prttype, 'id_vtype', id_vtype)
if (not vtypes.ids_sumo.has_index(prttype)) | is_reset_vtype:
- print ' set default PRT values decel', self._decel_leader, 'decel_emergency', self._decel_emergency_leader
+ print(' set default PRT values decel', self._decel_leader, 'decel_emergency', self._decel_emergency_leader)
id_vtype = vtypes.add_vtype(prttype,
accel=self._accel_leader,
decel=self._decel_leader,
@@ -5181,7 +5181,7 @@ def make_vtype(self, is_reset_vtype=False):
speed_charging=0.03,
)
else:
- print ' PRT type existing'
+ print(' PRT type existing')
id_vtype = vtypes.ids_sumo.get_id_from_index(prttype)
return id_vtype
@@ -5194,7 +5194,7 @@ def get_length(self):
return vtypes.lengths[id_vtype]
def prepare_sim(self, process):
- print 'PrtVehicles.prepare_sim'
+ print('PrtVehicles.prepare_sim')
if len(self) == 0:
return []
@@ -5288,12 +5288,12 @@ def add_ghost(self, id_veh, id_ghost, dist_to_merge_veh, dist_to_merge_ghost,
# else:
# add new ghost
# ,self.ids_ghosts.shape
- print 'add_ghost veh prt.%d ghost prt.%d dtm = %.1f dtmg = %.1f d0=%.1f' % (id_veh, id_ghost, dist_to_merge_veh, dist_to_merge_ghost, dist_to_merge_veh - dist_to_merge_ghost)
+ print('add_ghost veh prt.%d ghost prt.%d dtm = %.1f dtmg = %.1f d0=%.1f' % (id_veh, id_ghost, dist_to_merge_veh, dist_to_merge_ghost, dist_to_merge_veh - dist_to_merge_ghost))
if -1 not in ids_ghosts:
- print 'ERROR: no more ghosts available, ids_ghosts', ids_ghosts
+ print('ERROR: no more ghosts available, ids_ghosts', ids_ghosts)
# sys.exit(1)
- print ' overwrite last ghost'
+ print(' overwrite last ghost')
# here we could sunstitute the ghost with the longest distance
ind_ghost = len(ids_ghosts)-1
else:
@@ -5307,7 +5307,7 @@ def add_ghost(self, id_veh, id_ghost, dist_to_merge_veh, dist_to_merge_ghost,
ind_ghost -= 1
if ind_ghost > 0:
- print 'WARNING: unusual number of ghosts, ids_ghosts', ids_ghosts
+ print('WARNING: unusual number of ghosts, ids_ghosts', ids_ghosts)
# sys.exit(1)
self.ids_ghosts[id_veh][ind_ghost] = id_ghost
@@ -5335,7 +5335,7 @@ def del_ghosts(self, id_veh):
self.del_ghost(id_veh, id_ghost)
def del_ghost(self, id_veh, id_ghost):
- print 'del_ghost id_veh %d id_ghost %d' % (id_veh, id_ghost)
+ print('del_ghost id_veh %d id_ghost %d' % (id_veh, id_ghost))
if id_ghost in self.ids_ghosts[id_veh]:
ind_ghost = list(self.ids_ghosts[id_veh]).index(id_ghost)
@@ -5368,12 +5368,12 @@ def del_all_ghosts(self, id_veh):
def switch_off_control(self, id_veh):
"""Direct way to switch of SUMO control of vehicles"""
- print 'switch_off_control id_veh', id_veh
+ print('switch_off_control id_veh', id_veh)
traci.vehicle.setSpeedMode(self.ids_sumo[id_veh], 6) # 6=respect max accel/decel
def switch_on_control(self, id_veh):
"""Direct way to switch of SUMO control of vehicles"""
- print 'switch_on_control id_veh', id_veh
+ print('switch_on_control id_veh', id_veh)
traci.vehicle.setSpeedMode(self.ids_sumo[id_veh], self._speedmode_leader)
def start_update(self, id_veh):
@@ -5394,8 +5394,8 @@ def stop_update(self, id_veh):
def process_step(self, process):
simtime = process.simtime
- print 79*'_'
- print 'PrtVehicles.process_step at', simtime
+ print(79*'_')
+ print('PrtVehicles.process_step at', simtime)
net = self.get_scenario().net
vehicles = self.parent.prtvehicles
ids = self.get_ids()
@@ -5403,24 +5403,24 @@ def process_step(self, process):
return
time_update = self.time_update.get_value()
decel_emergency = self.decel_emergency.get_value()
- print ' update', len(np.flatnonzero(self.are_update[ids])), 'vehicles'
+ print(' update', len(np.flatnonzero(self.are_update[ids])), 'vehicles')
ids_update = ids[self.are_update[ids]]
- print ' ids_update', ids_update
+ print(' ids_update', ids_update)
#ids_debug = [324,251,417,400]
#ids_debug = [182,133,204,170]
#ids_debug = [271, 304]
ids_debug = [482, 483, 484]
if 1:
- print ' *Debug:'
+ print(' *Debug:')
#ids_debug = [307, 236, 41, 231, 208, 44, 249, 229, 136]
#ids_debug = [56, 271, 264, 244, 256, 253, 240, 251, 163, 150]
#ids_debug = [26,242,139,79,138]
#ids_debug = [2,482,44,63,67]
for id_veh, id_veh_sumo, id_follower, id_leader in zip(ids_debug, self.ids_sumo[ids_debug], self.ids_follower[ids_debug], self.ids_leader[ids_debug]):
- print ' *id_veh prt.%d' % id_veh, 'id_follower', id_follower, 'id_leader', id_leader, 'ids_ghost', self.ids_ghosts[id_veh]
- print ' id_stop_target', self.ids_stop_target[id_veh], 'lp=%.1fm' % self.lengths_plat[id_veh]
+ print(' *id_veh prt.%d' % id_veh, 'id_follower', id_follower, 'id_leader', id_leader, 'ids_ghost', self.ids_ghosts[id_veh])
+ print(' id_stop_target', self.ids_stop_target[id_veh], 'lp=%.1fm' % self.lengths_plat[id_veh])
if self.states[id_veh] > 0:
- print ' pax', traci.vehicle.getPersonIDList(id_veh_sumo), 'isStopped', traci.vehicle.isStopped(id_veh_sumo), 'speed', traci.vehicle.getSpeed(id_veh_sumo)
+ print(' pax', traci.vehicle.getPersonIDList(id_veh_sumo), 'isStopped', traci.vehicle.isStopped(id_veh_sumo), 'speed', traci.vehicle.getSpeed(id_veh_sumo))
#self.id_follower_probe = self.ids_follower[271]
@@ -5434,7 +5434,7 @@ def process_step(self, process):
if 0:
ids_ghost = self.ids_ghosts[id_veh]
- print ' %7s' % id_veh_sumo, 'ghosts', ids_ghost, self.ids_leader[id_veh], "lp=%.1fm" % self.lengths_plat[id_veh]
+ print(' %7s' % id_veh_sumo, 'ghosts', ids_ghost, self.ids_leader[id_veh], "lp=%.1fm" % self.lengths_plat[id_veh])
#odo = self.odos[id_veh]
#delta_vehs = odo-self.odos0_vehicles[id_veh]
#delta_ghosts = self.odos[ids_ghost] - self.odos0_ghosts[id_veh]
@@ -5548,9 +5548,9 @@ def process_step(self, process):
dist_min_check = dist0 + delta_ghost - delta_veh - \
self.lengths_plat[self.ids_ghosts[id_veh][0]] - self.length
# print ' %7s: v=%3.1f vg=%3.1f dh=%4.1f th=%4.1fs ds=%4.1f dc=%4.1f lp=%3.1f %s'%(id_sumo, velocity, velocitiy_ghost_min,dist_min,th,dist_safe,dist_comf,length_plat,a)
- print ' %7s: v=%3.1f vg=%3.1f d0=%4.1f dh=%4.1f th=%3.1fs ds=%4.1f dc=%4.1f odo=%4.1f %s' % (id_sumo, velocity, velocitiy_ghost_min, dist0, dist_min, th, dist_safe, dist_comf, odo, a)
- print ' dist_min', dist_min, 'dist_min_check', dist_min_check, 'id_ghost', self.ids_ghosts[id_veh][0]
- print ' delta_veh', delta_veh, 'delta_ghost', delta_ghost, 'dist_rel', dist_rel
+ print(' %7s: v=%3.1f vg=%3.1f d0=%4.1f dh=%4.1f th=%3.1fs ds=%4.1f dc=%4.1f odo=%4.1f %s' % (id_sumo, velocity, velocitiy_ghost_min, dist0, dist_min, th, dist_safe, dist_comf, odo, a))
+ print(' dist_min', dist_min, 'dist_min_check', dist_min_check, 'id_ghost', self.ids_ghosts[id_veh][0])
+ print(' delta_veh', delta_veh, 'delta_ghost', delta_ghost, 'dist_rel', dist_rel)
fact_urgent = np.ones(dists_safe.shape, dtype=np.float32) # np.clip(dists_safe/diststomerge_min,0.0,1.0)
@@ -5590,8 +5590,8 @@ def set_route_target(self, id_veh, route, id_stop_target=None, is_disengage_from
"""
This is the vehicle route to the next target, not necessary the final one.
"""
- print 'set_route_target prt.%d' % id_veh, 'id_stop_target', id_stop_target, 'is_disengage_from_berth', is_disengage_from_berth
- print ' route', route
+ print('set_route_target prt.%d' % id_veh, 'id_stop_target', id_stop_target, 'is_disengage_from_berth', is_disengage_from_berth)
+ print(' route', route)
# set target only if valid target, otherwise set only route
if id_stop_target is not None:
@@ -5625,7 +5625,7 @@ def set_route_completed(self, id_veh):
self.routes[id_veh] = []
def reset_speedmode(self, id_veh_sumo):
- print 'reset_speedmode', id_veh_sumo
+ print('reset_speedmode', id_veh_sumo)
# speed mode (0xb3)
# Per default, the vehicle is using the given speed regarding the safe gap, the maximum acceleration, and the maximum deceleration. Furthermore, vehicles follow the right-of-way rules when approaching an intersection and if necessary they brake hard to avoid driving across a red light. One can control this behavior using the speed mode (0xb3) command, the given integer is a bitset (bit0 is the least significant bit) with the following fields:
# 1 bit0: Regard safe speed
@@ -5641,7 +5641,7 @@ def reset_speedmode(self, id_veh_sumo):
# pass
def concatenate(self, id_veh, id_veh_pre):
- print 'concatenate prt.%d' % id_veh, 'behind prt.%d' % id_veh_pre
+ print('concatenate prt.%d' % id_veh, 'behind prt.%d' % id_veh_pre)
self.ids_leader[id_veh] = id_veh_pre
self.ids_follower[id_veh_pre] = id_veh
@@ -5668,7 +5668,7 @@ def concatenate(self, id_veh, id_veh_pre):
else:
self._update_concatenate(id_veh, 0.0)
- print ' length_plat=', self.lengths_plat[id_veh]
+ print(' length_plat=', self.lengths_plat[id_veh])
def _update_concatenate(self, id_veh, length_plat):
"""
@@ -5676,7 +5676,7 @@ def _update_concatenate(self, id_veh, length_plat):
"""
# TODO: this is a very inefficient method because call each time a vehicle is added.
# Try to avoid altogether
- print '_update_concatenate prt.%s, length_plat=%.1f, length=%.1f,' % (id_veh, length_plat, self.length), 'id_leader', self.ids_leader[id_veh]
+ print('_update_concatenate prt.%s, length_plat=%.1f, length=%.1f,' % (id_veh, length_plat, self.length), 'id_leader', self.ids_leader[id_veh])
if self.ids_leader[id_veh] == -1:
# first vehicle
# print ' first vehicle prt.%s'%id_veh,length_plat
@@ -5687,7 +5687,7 @@ def _update_concatenate(self, id_veh, length_plat):
self._update_concatenate(self.ids_leader[id_veh], length_plat + self.length)
def decatenate(self, id_veh):
- print 'decatenate prt.%d' % id_veh
+ print('decatenate prt.%d' % id_veh)
id_leader = self.ids_leader[id_veh]
# print ' id_leader',id_leader
@@ -5734,7 +5734,7 @@ def decatenate(self, id_veh):
# remove platoon length
self.lengths_plat[id_veh] = 0.0
- print ' length_plat=', self.lengths_plat[id_veh]
+ print(' length_plat=', self.lengths_plat[id_veh])
def get_platoonleader(self, id_veh_tail):
id_veh = 1*id_veh_tail
@@ -5757,7 +5757,7 @@ def get_platoonsize(self, id_veh_leader):
return n
def get_platoon(self, id_veh_leader):
- print 'get_platoon for leader prt.%d' % id_veh_leader
+ print('get_platoon for leader prt.%d' % id_veh_leader)
ids_veh = [id_veh_leader, ]
id_veh = self.ids_follower[id_veh_leader]
# print ' id_veh',id_veh
@@ -5766,7 +5766,7 @@ def get_platoon(self, id_veh_leader):
id_veh = self.ids_follower[id_veh]
# print ' id_veh',id_veh
- print ' ids_veh', ids_veh
+ print(' ids_veh', ids_veh)
return ids_veh
def get_entered_left(self, id_edge_sumo, ids_veh_previous_sumo):
@@ -5779,7 +5779,7 @@ def get_entered_left(self, id_edge_sumo, ids_veh_previous_sumo):
the first vehicle in the list entered/left first
"""
ids_veh_new_sumo = traci.edge.getLastStepVehicleIDs(id_edge_sumo)
- print 'get_entered_left ids_veh_new_sumo=', ids_veh_new_sumo
+ print('get_entered_left ids_veh_new_sumo=', ids_veh_new_sumo)
len_prev = len(ids_veh_previous_sumo)
len_new = len(ids_veh_new_sumo)
@@ -5801,7 +5801,7 @@ def get_entered_left(self, id_edge_sumo, ids_veh_previous_sumo):
break
ind_enter += 1
- print ' ind_enter', ind_enter, ids_veh_new_sumo[0:ind_enter], ids_veh_new_sumo[ind_enter-1::-1]
+ print(' ind_enter', ind_enter, ids_veh_new_sumo[0:ind_enter], ids_veh_new_sumo[ind_enter-1::-1])
#ids_entered_sumo = ids_veh_new_sumo[0:ind_enter]
ind_leave = len_prev
@@ -5811,7 +5811,7 @@ def get_entered_left(self, id_edge_sumo, ids_veh_previous_sumo):
break
ind_leave -= 1
- print ' ind_leave', ind_leave, ids_veh_previous_sumo[ind_leave:], ids_veh_previous_sumo[:ind_leave:-1]
+ print(' ind_leave', ind_leave, ids_veh_previous_sumo[ind_leave:], ids_veh_previous_sumo[:ind_leave:-1])
#ids_leave_sumo = ids_veh_previous_sumo[ind_leave:]
# return ids_entered_sumo, ids_leave_sumo, ids_veh_new_sumo
@@ -5829,7 +5829,7 @@ def control_stop(self, id_veh, laneindex=0):
stopline = pos + 3.0 + 0.5/self.decel*speed**2
#time_slowdown = np.abs((speed0-speed)/self.decel)
- print 'control_stop', id_veh_sumo, 'v = %.2f at pos %.1fm to stop at %.1fm on %s' % (speed, pos, stopline, traci.vehicle.getRoadID(id_veh_sumo))
+ print('control_stop', id_veh_sumo, 'v = %.2f at pos %.1fm to stop at %.1fm on %s' % (speed, pos, stopline, traci.vehicle.getRoadID(id_veh_sumo)))
traci.vehicle.setStop(id_veh_sumo,
traci.vehicle.getRoadID(id_veh_sumo),
pos=stopline,
@@ -5839,7 +5839,7 @@ def control_stop(self, id_veh, laneindex=0):
def control_speedup(self, id_veh):
id_veh_sumo = self.get_id_sumo(id_veh)
- print 'control_speedup', id_veh_sumo, 'isStopped', traci.vehicle.isStopped(id_veh_sumo), self.speed_max.get_value()
+ print('control_speedup', id_veh_sumo, 'isStopped', traci.vehicle.isStopped(id_veh_sumo), self.speed_max.get_value())
if traci.vehicle.isStopped(id_veh_sumo):
traci.vehicle.resume(id_veh_sumo)
@@ -5848,13 +5848,13 @@ def control_speedup(self, id_veh):
#self.control_slow_down(id_veh, self.speed_max.get_value())
def control_slow_down(self, id_veh, speed=1.0, time_slowdown=None):
- print 'control_slow_down', self.get_id_sumo(id_veh), speed, time_slowdown
+ print('control_slow_down', self.get_id_sumo(id_veh), speed, time_slowdown)
id_veh_sumo = self.get_id_sumo(id_veh)
if time_slowdown is None:
speed0 = traci.vehicle.getSpeed(id_veh_sumo)
time_slowdown = np.abs((speed0-speed)/self.decel)
- print ' speed0=%.2fm/s, time_slowdown = %.2fs, dv=%.2fm/s' % (speed0, time_slowdown, speed0-speed)
+ print(' speed0=%.2fm/s, time_slowdown = %.2fs, dv=%.2fm/s' % (speed0, time_slowdown, speed0-speed))
traci.vehicle.slowDown(id_veh_sumo, speed, time_slowdown)
#self.speed_max = vtypes.speeds_max[id_vtype]
@@ -5873,9 +5873,9 @@ def control_forewarding_exit(self, id_veh,
# state forewarding_exit_kickout was unknown!!!
id_veh_sumo = self.get_id_sumo(id_veh)
p = traci.vehicle.getLanePosition(id_veh_sumo)
- print 'control_forewarding_exit', id_veh_sumo, p, '->', position, 'laneindex', laneindex
+ print('control_forewarding_exit', id_veh_sumo, p, '->', position, 'laneindex', laneindex)
if traci.vehicle.isStopped(id_veh_sumo):
- print ' resume stop'
+ print(' resume stop')
traci.vehicle.resume(id_veh_sumo)
self.states[id_veh] = VEHICLESTATES['forewarding_exit_kickout']
@@ -5884,7 +5884,7 @@ def control_forewarding_exit(self, id_veh,
# print ' do not set a stop'
pass
else:
- print ' set stop at pos', position
+ print(' set stop at pos', position)
traci.vehicle.setStop(id_veh_sumo,
id_edge_sumo,
pos=position,
@@ -5898,7 +5898,7 @@ def control_forewarding_exit(self, id_veh,
def control_stopline_enter(self, id_veh, id_edge_sumo, stopline, laneindex=1, flags=0):
# print 'control_stopline_enter',self.get_id_sumo(id_veh),stopline
id_veh_sumo = self.get_id_sumo(id_veh)
- print 'control_stopline_enter', id_veh_sumo, 'lane %d, pos=%.2f->targetpos %.2f' % (laneindex, traci.vehicle.getLanePosition(id_veh_sumo), stopline)
+ print('control_stopline_enter', id_veh_sumo, 'lane %d, pos=%.2f->targetpos %.2f' % (laneindex, traci.vehicle.getLanePosition(id_veh_sumo), stopline))
traci.vehicle.setStop(id_veh_sumo,
id_edge_sumo,
pos=stopline,
@@ -5919,13 +5919,13 @@ def control_berth_position_enter(self, id_veh, id_berth,
"""
id_veh_sumo = self.get_id_sumo(id_veh)
p = traci.vehicle.getLanePosition(id_veh_sumo)
- print 'control_berth_position_enter', id_veh_sumo, p, '->', position, 'id_berth', id_berth
+ print('control_berth_position_enter', id_veh_sumo, p, '->', position, 'id_berth', id_berth)
# here it can happen that vehicle has been programmed to stop in front
# of first berth to wait for allocation
# print ' getStopState',traci.vehicle.getStopState(id_veh_sumo)
# print ' getNextStops',traci.vehicle.getNextStops(id_veh_sumo)
- print ' isStopped', traci.vehicle.isStopped(id_veh_sumo)
+ print(' isStopped', traci.vehicle.isStopped(id_veh_sumo))
# if len(traci.vehicle.getNextStops(id_veh_sumo))>0:
# already resumed
@@ -5954,7 +5954,7 @@ def control_berth_position_exit(self, id_veh,
p = traci.vehicle.getLanePosition(id_veh_sumo)
if position is None:
position = p+0.3
- print 'control_berth_position_exit', id_veh_sumo, p, '->', position
+ print('control_berth_position_exit', id_veh_sumo, p, '->', position)
if traci.vehicle.isStopped(id_veh_sumo):
traci.vehicle.resume(id_veh_sumo)
@@ -5972,7 +5972,7 @@ def control_berth_position_exit(self, id_veh,
def control_berth_position_exit_slowdown(self, id_veh):
id_veh_sumo = self.get_id_sumo(id_veh)
- print ' control_berth_position_exit_slowdown', id_veh_sumo
+ print(' control_berth_position_exit_slowdown', id_veh_sumo)
# function to stop vehicle after it moved out of the berth
if traci.vehicle.isStopped(id_veh_sumo):
traci.vehicle.resume(id_veh_sumo)
@@ -5989,7 +5989,7 @@ def control_berth_stop(self, id_veh,
"""
id_veh_sumo = self.get_id_sumo(id_veh)
p = traci.vehicle.getLanePosition(id_veh_sumo)
- print 'control_berth_stop', id_veh_sumo, p, '->', position
+ print('control_berth_stop', id_veh_sumo, p, '->', position)
#d = position - p
#v = traci.vehicle.getSpeed(id_veh_sumo)
#d_save = 1.0/(2*2.5)*(v**2)
@@ -6012,8 +6012,8 @@ def control_stop_board(self, id_veh, id_stop, id_berth,
# NO LONGER USED
id_veh_sumo = self.get_id_sumo(id_veh)
- print 'control_stop_board', id_veh_sumo, id_stop, id_berth, id_edge_sumo, 'pos=%.2f,target %.2f' % (traci.vehicle.getLanePosition(id_veh_sumo), position),
- print ' v=', traci.vehicle.getSpeed(id_veh_sumo)
+ print('control_stop_board', id_veh_sumo, id_stop, id_berth, id_edge_sumo, 'pos=%.2f,target %.2f' % (traci.vehicle.getLanePosition(id_veh_sumo), position), end=' ')
+ print(' v=', traci.vehicle.getSpeed(id_veh_sumo))
# print 'control_stop_board',id_veh_sumo,traci.vehicle.getLanePosition(id_veh_sumo),'->',position,id_berth
self.ids_berth[id_veh] = id_berth
@@ -6033,9 +6033,9 @@ def control_stop_board(self, id_veh, id_stop, id_berth,
def launch_from_stop(self, id_veh):
id_veh_sumo = self.get_id_sumo(id_veh)
- print 'launch_from_stop', id_veh_sumo, 'is stopped', traci.vehicle.isStopped(id_veh_sumo)
+ print('launch_from_stop', id_veh_sumo, 'is stopped', traci.vehicle.isStopped(id_veh_sumo))
if traci.vehicle.isStopped(id_veh_sumo):
- print ' resume!'
+ print(' resume!')
traci.vehicle.resume(id_veh_sumo)
route_sumo = self.get_scenario().net.edges.ids_sumo[self.routes[id_veh]]
@@ -6044,7 +6044,7 @@ def launch_from_stop(self, id_veh):
traci.vehicle.setMaxSpeed(id_veh_sumo, 6.0/3.6)
#traci.vehicle.setMaxSpeed(id_veh_sumo, self.speed_max.get_value())
#traci.vehicle.setMaxSpeed(id_veh_sumo, 0.66)
- print ' after launch is stopped', traci.vehicle.isStopped(id_veh_sumo), 'getMaxSpeed', traci.vehicle.getMaxSpeed(id_veh_sumo)
+ print(' after launch is stopped', traci.vehicle.isStopped(id_veh_sumo), 'getMaxSpeed', traci.vehicle.getMaxSpeed(id_veh_sumo))
def alight(self, id_veh):
# print 'alight',self.get_id_sumo(id_veh)
@@ -6077,7 +6077,7 @@ def board(self, id_veh, id_edge_sumo=None, position=None):
def init_passthrough(self, id_veh, id_edge_sumo, stopline, laneindex=1, flags=0):
id_veh_sumo = self.get_id_sumo(id_veh)
- print 'init_passthrough', id_veh_sumo, 'lane %d, pos=%.2f->targetpos %.2f' % (laneindex, traci.vehicle.getLanePosition(id_veh_sumo), stopline)
+ print('init_passthrough', id_veh_sumo, 'lane %d, pos=%.2f->targetpos %.2f' % (laneindex, traci.vehicle.getLanePosition(id_veh_sumo), stopline))
# do n
#is_stop = True
@@ -6099,7 +6099,7 @@ def init_passthrough(self, id_veh, id_edge_sumo, stopline, laneindex=1, flags=0)
def foreward_passthrough(self, id_veh):
id_veh_sumo = self.get_id_sumo(id_veh)
- print 'foreward_passthrough', id_veh_sumo
+ print('foreward_passthrough', id_veh_sumo)
if traci.vehicle.isStopped(id_veh_sumo):
# print ' resume!'
traci.vehicle.resume(id_veh_sumo)
@@ -6108,16 +6108,16 @@ def foreward_passthrough(self, id_veh):
def reached_stop_sumo(self, id_veh_sumo):
state = traci.vehicle.getStopState(id_veh_sumo)
- print 'reached_stop', id_veh_sumo, bin(state), bin(state)[-1] == '1'
+ print('reached_stop', id_veh_sumo, bin(state), bin(state)[-1] == '1')
return bin(state)[-1] == '1'
def is_completed_alighting(self, id_veh):
- print 'is_completed_alighting', self.get_id_sumo(id_veh), self.states[id_veh], 'alighting', self.states[id_veh] == VEHICLESTATES['alighting'], 'pers on board', traci.vehicle.getPersonNumber(self.get_id_sumo(id_veh)), type(traci.vehicle.getPersonNumber(self.get_id_sumo(id_veh)))
+ print('is_completed_alighting', self.get_id_sumo(id_veh), self.states[id_veh], 'alighting', self.states[id_veh] == VEHICLESTATES['alighting'], 'pers on board', traci.vehicle.getPersonNumber(self.get_id_sumo(id_veh)), type(traci.vehicle.getPersonNumber(self.get_id_sumo(id_veh))))
if self.states[id_veh] == VEHICLESTATES['alighting']:
ids_persons_sumo_on_board = traci.vehicle.getPersonIDList(self.get_id_sumo(id_veh))
if self.ids_persons_sumo[id_veh].isdisjoint(ids_persons_sumo_on_board):
# if traci.vehicle.getPersonIDList(self.get_id_sumo(id_veh)) == 0:
- print ' completed alighting ids_persons_sumo_on_board', ids_persons_sumo_on_board
+ print(' completed alighting ids_persons_sumo_on_board', ids_persons_sumo_on_board)
if len(ids_persons_sumo_on_board) > 0:
self.states[id_veh] = VEHICLESTATES['boarding']
else:
@@ -6138,7 +6138,7 @@ def is_completed_boarding(self, id_veh):
if self.states[id_veh] in (VEHICLESTATES['boarding'], VEHICLESTATES['waiting']):
ids_person_sumo = traci.vehicle.getPersonIDList(self.get_id_sumo(id_veh))
if len(ids_person_sumo) == 1:
- print ' completed boarding'
+ print(' completed boarding')
self.states[id_veh] = VEHICLESTATES['boarding_completed']
self.ids_persons_sumo[id_veh].add(ids_person_sumo)
return True
@@ -6153,7 +6153,7 @@ def is_completed_boarding(self, id_veh):
def init_trip_occupied(self, id_veh, id_edge_sumo, stopline=None):
id_veh_sumo = self.get_id_sumo(id_veh)
- print 'init_trip_occupied', self.get_id_sumo(id_veh), id_edge_sumo, stopline
+ print('init_trip_occupied', self.get_id_sumo(id_veh), id_edge_sumo, stopline)
# print ' current route:',traci.vehicle.getRoute(id_veh_sumo)
self.states[id_veh] = VEHICLESTATES['occupiedtrip']
@@ -6174,7 +6174,7 @@ def init_trip_occupied(self, id_veh, id_edge_sumo, stopline=None):
#traci.vehicle.slowDown(id_veh_sumo, speed_crawl, time_accel)
def init_trip_empty(self, id_veh, id_edge_sumo, stopline=None):
- print 'Vehicles.init_trip_empty', self.get_id_sumo(id_veh), id_edge_sumo, stopline
+ print('Vehicles.init_trip_empty', self.get_id_sumo(id_veh), id_edge_sumo, stopline)
self.states[id_veh] = VEHICLESTATES['emptytrip']
id_veh_sumo = self.get_id_sumo(id_veh)
if traci.vehicle.isStopped(id_veh_sumo):
@@ -6197,7 +6197,7 @@ def init_trip_empty(self, id_veh, id_edge_sumo, stopline=None):
#traci.vehicle.slowDown(id_veh_sumo, speed_crawl, time_accel)
def reschedule_trip(self, id_veh, id_edge_sumo_to=None, route_sumo=None):
- print 'reschedule_trip', self.get_id_sumo(id_veh), id_edge_sumo_to, route_sumo
+ print('reschedule_trip', self.get_id_sumo(id_veh), id_edge_sumo_to, route_sumo)
id_veh_sumo = self.get_id_sumo(id_veh)
if traci.vehicle.isStopped(id_veh_sumo):
traci.vehicle.resume(id_veh_sumo)
@@ -6288,7 +6288,7 @@ def get_id_from_id_sumo(self, id_veh_sumo):
def get_ids_from_ids_sumo(self, ids_veh_sumo):
n = len(ids_veh_sumo)
ids = np.zeros(n, np.int32)
- for i in xrange(n):
+ for i in range(n):
ids[i] = self.get_id_from_id_sumo(ids_veh_sumo[i])
return ids
@@ -6364,7 +6364,7 @@ def preevaluate(self, ids_person):
# put 2 for persons who prefer prt (probably few in pre PRT times)
preeval[persons.ids_mode_preferred[ids_person] == self.prtservice.id_prtmode] = 2
- print ' HcPrtStrategy.preevaluate', len(np.flatnonzero(preeval))
+ print(' HcPrtStrategy.preevaluate', len(np.flatnonzero(preeval)))
return preeval
def plan(self, ids_person, logger=None):
@@ -6372,7 +6372,7 @@ def plan(self, ids_person, logger=None):
Generates a plan for these person according to this strategie.
Overriden by specific strategy.
"""
- print 'HcPrtStrategy.plan', len(ids_person)
+ print('HcPrtStrategy.plan', len(ids_person))
#make_plans_private(self, ids_person = None, mode = 'passenger')
# routing necessary?
virtualpop = self.get_virtualpop()
@@ -6390,7 +6390,7 @@ def plan(self, ids_person, logger=None):
prtstops = self.prtservice.prtstops
if len(prtstops) == 0:
- print 'WARNING: no prt stops, no prt plans'
+ print('WARNING: no prt stops, no prt plans')
return True
net = scenario.net
@@ -6411,14 +6411,14 @@ def plan(self, ids_person, logger=None):
times_stop_to_stop = self.prtservice.times_stop_to_stop
if times_stop_to_stop is None:
- print 'WARNING: stop to stop matrix not calculated. Please configure the PRT system.'
+ print('WARNING: stop to stop matrix not calculated. Please configure the PRT system.')
return True
ids_person_act, ids_act_from, ids_act_to\
= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
if len(ids_person_act) == 0:
- print 'WARNING in TrasitStrategy.plan: no eligible persons found.'
+ print('WARNING in TrasitStrategy.plan: no eligible persons found.')
return False
# temporary maps from ids_person to other parameters
@@ -6437,7 +6437,7 @@ def plan(self, ids_person, logger=None):
map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]
n_plans = len(ids_person_act)
- print 'TrasitStrategy.plan n_plans=', n_plans
+ print('TrasitStrategy.plan n_plans=', n_plans)
# make initial activity stage
ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]
@@ -6522,15 +6522,15 @@ def plan(self, ids_person, logger=None):
if logger:
logger.progress(i/n_pers*100)
i += 1.0
- print 79*'_'
- print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)
+ print(79*'_')
+ print(' id_plan=%d, id_person=%d, ' % (id_plan, id_person))
if id_person == 17214:
- print ' id_stop_from', id_stop_from, 'id_stop_to', id_stop_to
- print ' id_stopedge_from', id_stopedge_from, 'id_stopedge_to', id_stopedge_to
+ print(' id_stop_from', id_stop_from, 'id_stop_to', id_stop_to)
+ print(' id_stopedge_from', id_stopedge_from, 'id_stopedge_to', id_stopedge_to)
if (dist_from_to < dist_walk_max) | (id_edge_from == -1) | (id_edge_to == -1) | (id_stop_from == id_stop_to):
- print ' go by foot because distance is too short ', dist_from_to, 'edges', id_edge_from, id_edge_to, 'stops', id_stop_from, id_stop_to
+ print(' go by foot because distance is too short ', dist_from_to, 'edges', id_edge_from, id_edge_to, 'stops', id_stop_from, id_stop_to)
id_stage_walk1, time = walkstages.append_stage(
id_plan, time_from,
@@ -6597,7 +6597,7 @@ def __init__(self, ident, stages,
# **kwargs,
):
- print 'HcPrtTransits.__init__', ident, stages
+ print('HcPrtTransits.__init__', ident, stages)
self.init_stagetable(ident,
stages, name=name,
info=info,
@@ -6621,20 +6621,20 @@ def _init_attributes(self):
))
def set_prtservice(self, prtservice):
- print 'HcPrtTransits.set_prtservice', prtservice, 'id(self)', id(self)
+ print('HcPrtTransits.set_prtservice', prtservice, 'id(self)', id(self))
self.add(cm.ObjConf(prtservice, is_child=False, groups=['_private']))
def get_prtservice(self):
- print 'get_prtservice', self, id(self)
+ print('get_prtservice', self, id(self))
return self.hcprtservice.get_value()
def prepare_planning(self):
prtservice = self.get_prtservice()
- print 'HcPrtTransits.prepare_planning', prtservice.times_stop_to_stop
+ print('HcPrtTransits.prepare_planning', prtservice.times_stop_to_stop)
if prtservice.times_stop_to_stop is None:
prtservice.make_times_stop_to_stop()
- print prtservice.times_stop_to_stop
+ print(prtservice.times_stop_to_stop)
def append_stage(self, id_plan, time_start=-1.0,
duration=0.0,
@@ -6781,7 +6781,7 @@ def get_scenario(self):
return self.parent.parent.get_scenario()
def prepare_sim(self, process):
- print 'VehicleMan.prepare_sim'
+ print('VehicleMan.prepare_sim')
net = self.get_scenario().net
# station management
@@ -6841,7 +6841,7 @@ def prepare_sim(self, process):
self.ids_veh = self.get_vehicles().get_ids()
if len(self.ids_veh) == 0:
- print 'WARNING: no PRT vehicles, please add PRT vehicles.'
+ print('WARNING: no PRT vehicles, please add PRT vehicles.')
return []
n_veharray = np.max(self.ids_veh)+1
@@ -6872,7 +6872,7 @@ def prepare_sim(self, process):
]
def update_flows(self, process):
- print 'HC VehicleMan update flow prediction'
+ print('HC VehicleMan update flow prediction')
self.inflows_sched[:, 0] = 0
self.inflows_sched = np.roll(self.inflows_sched, -1)
time_update_flows = self.time_update_flows.get_value()
@@ -6902,8 +6902,8 @@ def update_flows(self, process):
self.log_inflows_temp[:] = 0
def process_step(self, process):
- print 79*'M'
- print 'HC VehicleMan.process_step'
+ print(79*'M')
+ print('HC VehicleMan.process_step')
self.debug = 9
@@ -6919,13 +6919,13 @@ def process_step(self, process):
is_cont = (n_move_eff_total > 0) & np.any(surpluses_veh_urgent > 0)
is_cont = False
if self.debug > 4:
- print 79*'-'
- print ' check equalize iteration', np.any(surpluses_veh > 0), np.any(balances_veh > 0), np.any(surpluses_veh_urgent > 0), 'is_cont', is_cont
- print ' n_move_eff_total', n_move_eff_total
- print ' surpluses_veh', surpluses_veh
- print ' demands_veh', demands_veh
- print ' balances_veh', balances_veh
- print ' surpluses_veh_urgent', surpluses_veh_urgent
+ print(79*'-')
+ print(' check equalize iteration', np.any(surpluses_veh > 0), np.any(balances_veh > 0), np.any(surpluses_veh_urgent > 0), 'is_cont', is_cont)
+ print(' n_move_eff_total', n_move_eff_total)
+ print(' surpluses_veh', surpluses_veh)
+ print(' demands_veh', demands_veh)
+ print(' balances_veh', balances_veh)
+ print(' surpluses_veh_urgent', surpluses_veh_urgent)
if 0:
stops = self.get_stops()
@@ -6961,7 +6961,7 @@ def note_person_entered(self, id_stop, n_pax):
self.inflows_person[id_stop] += n_pax
def note_vehs_ready_for_departure(self, id_stop, id_stop_target, time_est, n_veh):
- print 'note_vehs_ready_for_departure id_stop', id_stop, id_stop_target, time_est, n_veh
+ print('note_vehs_ready_for_departure id_stop', id_stop, id_stop_target, time_est, n_veh)
self.ids_stop_target_current[id_stop] = id_stop_target
self.duration_est_target_current[id_stop] = time_est
self.numbers_veh_target_current[id_stop] = n_veh
@@ -6984,7 +6984,7 @@ def fit_vehicles(self, id_stop, n_veh, ind_time_arrival):
# idea behind is that room for more slots are more difficult to find
n_slots_search = n_slots_search_empty + n_slots
if self.debug > 1:
- print 'fit_vehicles n_veh', n_veh, 'n_slots', n_slots, 'capa_slots %.2f' % (capa * n_slots), 'at slot', ind_time_arrival, 'n_slots_search', n_slots_search
+ print('fit_vehicles n_veh', n_veh, 'n_slots', n_slots, 'capa_slots %.2f' % (capa * n_slots), 'at slot', ind_time_arrival, 'n_slots_search', n_slots_search)
ind_delay = 0
is_fit = False
while (ind_delay < n_slots_search) & (not is_fit) & (ind_time_arrival + ind_delay + n_slots < self.n_est_max):
@@ -6993,15 +6993,15 @@ def fit_vehicles(self, id_stop, n_veh, ind_time_arrival):
flows_sched = self.inflows_sched[id_stop, ind_time_arrival_sched:ind_time_arrival_sched+n_slots]
is_fit = np.sum(flows_sched) + n_veh < capa * n_slots
- print ' ind_delay', ind_delay, 'is_fit', is_fit, 'from', ind_time_arrival_sched, 'to', ind_time_arrival_sched + n_slots, 'flows_sched', flows_sched, # 'max',self.n_est_max
+ print(' ind_delay', ind_delay, 'is_fit', is_fit, 'from', ind_time_arrival_sched, 'to', ind_time_arrival_sched + n_slots, 'flows_sched', flows_sched, end=' ') # 'max',self.n_est_max
ind_delay += 1
# check if sufficient time-slots in the future are available
# at estimated arrival time
if self.debug > 2:
- print ' ind_time_arrival_sched', ind_time_arrival_sched, 'ind_delay', ind_delay
- print ' flows_sched ', flows_sched
- print ' n_slots ', n_slots, 'scheduled', np.sum(flows_sched), 'avail', capa * n_slots, 'is_fit', is_fit
+ print(' ind_time_arrival_sched', ind_time_arrival_sched, 'ind_delay', ind_delay)
+ print(' flows_sched ', flows_sched)
+ print(' n_slots ', n_slots, 'scheduled', np.sum(flows_sched), 'avail', capa * n_slots, 'is_fit', is_fit)
if self.debug > 5:
self.display_flows_est(id_stop, ind_time_arrival_sched, ind_time_arrival_sched+n_slots)
@@ -7019,12 +7019,12 @@ def fit_vehicles(self, id_stop, n_veh, ind_time_arrival):
capa_avail = capa_slot - flow_sched
n_alloc = min(int(capa_avail), n_veh-n_alloc_cum)
if self.debug > 5:
- print ' i_slot', i_slot, 'capa_slot %.2f' % capa_slot, 'capa_avail %.2f' % capa_avail, 'n_alloc', n_alloc, 'n_alloc_cum', n_alloc_cum
+ print(' i_slot', i_slot, 'capa_slot %.2f' % capa_slot, 'capa_avail %.2f' % capa_avail, 'n_alloc', n_alloc, 'n_alloc_cum', n_alloc_cum)
if n_alloc > 0:
flows_alloc[i_slot] += n_alloc
n_alloc_cum += n_alloc
if self.debug > 5:
- print ' add n_alloc', n_alloc, 'n_alloc_cum', n_alloc_cum
+ print(' add n_alloc', n_alloc, 'n_alloc_cum', n_alloc_cum)
# capacity of next slot is augmented by the
# rest capacity of the present slot
capa_slot = capa + (capa - n_alloc - flow_sched)
@@ -7033,7 +7033,7 @@ def fit_vehicles(self, id_stop, n_veh, ind_time_arrival):
# finally check whether all vehicle have been assigned
if self.debug > 2:
- print ' n_alloc_cum', n_alloc_cum, 'n_veh', n_veh, 'flows_alloc', flows_alloc
+ print(' n_alloc_cum', n_alloc_cum, 'n_veh', n_veh, 'flows_alloc', flows_alloc)
# due to rounding errors the rest of the last slot may not be assigned
if n_alloc_cum < n_veh:
@@ -7058,7 +7058,7 @@ def get_timeslot_occupation(self, id_stop, n_veh):
n_slots = n_slots = np.ceil(float(n_veh)/capa)
- print 'get_timeslot_occupation n_veh', n_veh, 'capa_int', capa_int, 'n_slots', n_slots, 'rem', n_veh - n_slots*capa_int
+ print('get_timeslot_occupation n_veh', n_veh, 'capa_int', capa_int, 'n_slots', n_slots, 'rem', n_veh - n_slots*capa_int)
if n_slots == 0:
flows = np.zeros(1, dtype=np.int32)
else:
@@ -7080,7 +7080,7 @@ def push_out_vehicles(self, process):
stops = self.get_stops()
ids_stop_all = stops.get_ids()
ids_stop = ids_stop_all[self.numbers_veh_target_current[ids_stop_all] > 0]
- print 'HC push_out_vehicles of %d stops' % (len(ids_stop))
+ print('HC push_out_vehicles of %d stops' % (len(ids_stop)))
#vehicles = self.get_vehicles()
ids_stop_launched = []
@@ -7092,10 +7092,10 @@ def push_out_vehicles(self, process):
self.numbers_veh_target_current[ids_stop],
):
time_depart = self.times_departure_sched[id_stop]
- print '\n check id_stop', id_stop, 'id_stop_target', id_stop_target, 'n_veh', n_veh, 'dur %.2f' % duration_est, 't_dep', time_depart, 'simtime', simtime
+ print('\n check id_stop', id_stop, 'id_stop_target', id_stop_target, 'n_veh', n_veh, 'dur %.2f' % duration_est, 't_dep', time_depart, 'simtime', simtime)
if time_depart != -1:
- print ' delay has been programmed is_launch', simtime > time_depart
+ print(' delay has been programmed is_launch', simtime > time_depart)
if (simtime > time_depart):
# simtime has reached scheduled departure time, so launch
self.times_departure_sched[id_stop] = -1
@@ -7108,7 +7108,7 @@ def push_out_vehicles(self, process):
time_arr_est = simtime + duration_est
ind_time_arrival = int(duration_est/time_update_flows+0.5)
- print ' time_arr_est', time_arr_est, 'ind_time_arrival', ind_time_arrival, 'in range', ind_time_arrival < self.n_est_max
+ print(' time_arr_est', time_arr_est, 'ind_time_arrival', ind_time_arrival, 'in range', ind_time_arrival < self.n_est_max)
if ind_time_arrival < self.n_est_max:
# required number of free time slots for n_veh
@@ -7118,24 +7118,24 @@ def push_out_vehicles(self, process):
# allocation successful
self.inflows_sched[id_stop_target,
ind_time_arrival_sched:ind_time_arrival_sched+n_alloc] += flows_alloc
- print ' schedule id_stop_target', id_stop_target, 'inflows_sched', self.inflows_sched[id_stop_target, ind_time_arrival_sched:ind_time_arrival_sched+n_alloc]
+ print(' schedule id_stop_target', id_stop_target, 'inflows_sched', self.inflows_sched[id_stop_target, ind_time_arrival_sched:ind_time_arrival_sched+n_alloc])
if ind_time_arrival_sched == ind_time_arrival:
- print ' immediate launch'
+ print(' immediate launch')
self.times_departure_sched[id_stop] = -1
is_launch = True
else:
# delayed launch, determine scheduled launch time
self.times_departure_sched[id_stop] = simtime + \
ind_time_arrival_sched * time_update_flows - duration_est
- print ' delayed launch: sched dep time', self.times_departure_sched[id_stop]
+ print(' delayed launch: sched dep time', self.times_departure_sched[id_stop])
is_launch = False
else:
- print 'WARNING: no capacity available at id_stop_target', id_stop_target, ' at this arrival time.'
+ print('WARNING: no capacity available at id_stop_target', id_stop_target, ' at this arrival time.')
is_launch = False
else:
#
- print'WARNING: arrival time out of measurement range for id_stop_target', id_stop_target
+ print('WARNING: arrival time out of measurement range for id_stop_target', id_stop_target)
is_launch = True
if is_launch:
@@ -7172,7 +7172,7 @@ def equalize_empty_vehicles(self, process):
stops = self.get_stops()
ids_stop = stops.get_ids()
n_stops = len(ids_stop)
- print 'equalize_empty_vehicles of %d stops' % n_stops
+ print('equalize_empty_vehicles of %d stops' % n_stops)
balances_veh = np.zeros(n_stops, dtype=np.float32)
demands_veh = np.zeros(n_stops, dtype=np.float32)
@@ -7198,7 +7198,7 @@ def equalize_empty_vehicles(self, process):
surpluses_veh[i] = surplus_veh # this is current surplus, vehicles immediately available
surpluses_veh_urgent[i] = surplus_veh_urgent # number of vehicles that need to be kicked out
if self.debug > 2:
- print '\n sssssssssseek destinations for id_stop', id_stop
+ print('\n sssssssssseek destinations for id_stop', id_stop)
if self.debug > 5:
self.display_flows_est(id_stop)
@@ -7208,22 +7208,22 @@ def equalize_empty_vehicles(self, process):
surplus_veh + surplus_veh_future - n_pax_wait - n_pax_future
if self.debug > 2:
- print ' surplus_veh', surplus_veh, 'surplus_future', surplus_veh_future, 'surplus_veh_urgent', surplus_veh_urgent
- print ' n_pax_wait ', n_pax_wait, 'n_pax_future', n_pax_future
- print ' balance ', balances_veh[i]
- print ' waittime_max ', waittimes_max[i]
+ print(' surplus_veh', surplus_veh, 'surplus_future', surplus_veh_future, 'surplus_veh_urgent', surplus_veh_urgent)
+ print(' n_pax_wait ', n_pax_wait, 'n_pax_future', n_pax_future)
+ print(' balance ', balances_veh[i])
+ print(' waittime_max ', waittimes_max[i])
i += 1
inds_sorted = np.argsort(balances_veh)
#surpluses_veh_emitters = surpluses_veh[inds_sorted[::-1]]
if self.debug > 2:
- print ' Emitters sorted:'
- print ' ids_stop_sorted ', ids_stop[inds_sorted[::-1]]
- print ' surpluses_veh', surpluses_veh[inds_sorted[::-1]]
- print ' balances_sorted ', balances_veh[inds_sorted[::-1]]
- print ' max(surpluses_veh)', max(surpluses_veh)
- print ' >>>max(balances_veh)', max(balances_veh)
+ print(' Emitters sorted:')
+ print(' ids_stop_sorted ', ids_stop[inds_sorted[::-1]])
+ print(' surpluses_veh', surpluses_veh[inds_sorted[::-1]])
+ print(' balances_sorted ', balances_veh[inds_sorted[::-1]])
+ print(' max(surpluses_veh)', max(surpluses_veh))
+ print(' >>>max(balances_veh)', max(balances_veh))
if (np.max(balances_veh) > 0) & (max(surpluses_veh) > 0):
@@ -7238,7 +7238,7 @@ def equalize_empty_vehicles(self, process):
if (surplus_from >= 1) & (balance_from >= 1):
if self.debug > 5:
# ,'ind_from',ind_from,'continue?',(surplus_from >= 1) & (balance_from >= 1)
- print '\n potential emitter stop: id_stop_from', id_stop_from, 'surplus_from', surplus_from, 'balance_from', balance_from
+ print('\n potential emitter stop: id_stop_from', id_stop_from, 'surplus_from', surplus_from, 'balance_from', balance_from)
# there are empties to send away and positive balance
utilities = np.zeros(n_stops, dtype=np.float32)
numbers_move = np.zeros(n_stops, dtype=np.int32)
@@ -7251,9 +7251,9 @@ def equalize_empty_vehicles(self, process):
time_to = times_stop_to_stop[id_stop_from, id_stop_to]
if self.debug > 5:
- print ' j', j, 'id_stop_from ', id_stop_from, 'id_stop_to', id_stop_to
- print ' balance_from', balance_from, 'balance_to', balance_to, 'min', -balance_to+0.5, surplus_from
- print ' demand_to', demand_to, 'waittime_max_to', waittime_max_to
+ print(' j', j, 'id_stop_from ', id_stop_from, 'id_stop_to', id_stop_to)
+ print(' balance_from', balance_from, 'balance_to', balance_to, 'min', -balance_to+0.5, surplus_from)
+ print(' demand_to', demand_to, 'waittime_max_to', waittime_max_to)
if (surplus_from >= 1) & (balance_from >= 1) & (demand_to > 0):
# the demand of the station is positive
@@ -7262,13 +7262,13 @@ def equalize_empty_vehicles(self, process):
# move the maximum possible number of available vehicles
n_move = min(int(demand_to+0.5), surplus_from, int(-demand_from+0.5))
if self.debug > 5:
- print ' potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to
+ print(' potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to)
#utilities[j] = n_move+ self.constant_timeweight*time_to
utilities[j] = float(n_move)/float(time_to)
#utilities[j] = waittime_max_to/float(time_to)
numbers_move[j] = n_move
if self.debug > 5:
- print ' =>U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to)
+ print(' =>U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to))
elif (surplus_veh_urgent_from > 0):
# we have a stop where we want to send out the maximum number of vehicles
@@ -7282,13 +7282,13 @@ def equalize_empty_vehicles(self, process):
# high balance means vehicle needs to be kicked out
if self.debug > 5:
- print ' forced potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to
+ print(' forced potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to)
#utilities[j] = n_move+ self.constant_timeweight*time_to
#utilities[j] = float(n_move)/float(time_to)
utilities[j] = n_move*(demand_to)/float(time_to)
numbers_move[j] = n_move
if self.debug > 5:
- print ' =>U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to)
+ print(' =>U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to))
j += 1
@@ -7306,7 +7306,7 @@ def equalize_empty_vehicles(self, process):
n_move_eff = stops.route_empties(
id_stop_from, ids_stop[inds_sorted][ind_max], numbers_move[ind_max], simtime)
if self.debug > 2:
- print ' moved', n_move_eff, 'of', numbers_move[ind_max], 'empty vehs from', id_stop_from, 'to', ids_stop[inds_sorted][ind_max], 'utility_max', utility_max
+ print(' moved', n_move_eff, 'of', numbers_move[ind_max], 'empty vehs from', id_stop_from, 'to', ids_stop[inds_sorted][ind_max], 'utility_max', utility_max)
# continute till balance is zero?
# indeed need to update balances
@@ -7336,7 +7336,7 @@ def equalize_empty_vehicles_broke(self, process):
stops = self.get_stops()
ids_stop = stops.get_ids()
n_stops = len(ids_stop)
- print 'equalize_empty_vehicles of %d stops' % n_stops
+ print('equalize_empty_vehicles of %d stops' % n_stops)
balances_veh = np.zeros(n_stops, dtype=np.float32)
demands_veh = np.zeros(n_stops, dtype=np.float32)
@@ -7363,7 +7363,7 @@ def equalize_empty_vehicles_broke(self, process):
surpluses_veh[i] = surplus_veh # this is current surplus, vehicles immediately available
surpluses_veh_urgent[i] = surplus_veh_urgent # number of vehicles that need to be kicked out
if self.debug > 2:
- print '\n sssssssssseek destinations for id_stop', id_stop
+ print('\n sssssssssseek destinations for id_stop', id_stop)
if self.debug > 5:
self.display_flows_est(id_stop)
@@ -7374,10 +7374,10 @@ def equalize_empty_vehicles_broke(self, process):
#balances_veh[i] = 1000.0 *surplus_veh_urgent + 1.0*surplus_veh + surplus_veh_future - n_pax_wait - n_pax_future
balances_veh[i] = 1.0*surplus_veh + surplus_veh_future - n_pax_wait - n_pax_future
if self.debug > 2:
- print ' surplus_veh', surplus_veh, 'surplus_future', surplus_veh_future, 'surplus_veh_urgent', surplus_veh_urgent
- print ' n_pax_wait ', n_pax_wait, 'n_pax_future', n_pax_future
- print ' balance ', balances_veh[i]
- print ' waittime_max ', waittimes_max[i]
+ print(' surplus_veh', surplus_veh, 'surplus_future', surplus_veh_future, 'surplus_veh_urgent', surplus_veh_urgent)
+ print(' n_pax_wait ', n_pax_wait, 'n_pax_future', n_pax_future)
+ print(' balance ', balances_veh[i])
+ print(' waittime_max ', waittimes_max[i])
i += 1
# sort per surpluses, because this is the most critical quantity
@@ -7386,30 +7386,30 @@ def equalize_empty_vehicles_broke(self, process):
inds_sorted = np.argsort(surpluses_veh*(surpluses_veh_urgent+1))
#surpluses_veh_emitters = surpluses_veh[inds_sorted[::-1]]
if self.debug > 2:
- print ' Emitters sorted:'
- print ' ids_stop_sorted ', ids_stop[inds_sorted[::-1]]
- print ' surpluses_veh', surpluses_veh[inds_sorted[::-1]]
- print ' surpluses_veh_urgent', surpluses_veh_urgent[inds_sorted[::-1]]
+ print(' Emitters sorted:')
+ print(' ids_stop_sorted ', ids_stop[inds_sorted[::-1]])
+ print(' surpluses_veh', surpluses_veh[inds_sorted[::-1]])
+ print(' surpluses_veh_urgent', surpluses_veh_urgent[inds_sorted[::-1]])
- print ' balances_sorted ', balances_veh[inds_sorted[::-1]]
- print ' max(surpluses_veh)', max(surpluses_veh)
- print ' >>>max(balances_veh)', max(balances_veh)
+ print(' balances_sorted ', balances_veh[inds_sorted[::-1]])
+ print(' max(surpluses_veh)', max(surpluses_veh))
+ print(' >>>max(balances_veh)', max(balances_veh))
if (np.max(balances_veh) > 0) & (max(surpluses_veh) > 0):
if self.debug > 5:
- print ' start optimizing target', len(inds_sorted[::-1])
+ print(' start optimizing target', len(inds_sorted[::-1]))
i = 0
for id_stop_from, ind_from in zip(ids_stop[inds_sorted[::-1]], inds_sorted[::-1]):
balance_from = balances_veh[ind_from]
surplus_from = surpluses_veh[ind_from]
surplus_veh_urgent_from = surpluses_veh_urgent[ind_from]
demand_from = demands_veh[ind_from]
- print ' surplus_from', surplus_from, 'balance_from', balance_from
+ print(' surplus_from', surplus_from, 'balance_from', balance_from)
# distribute surplus on neares, most in need
if (surplus_from >= 1) & (balance_from >= 1):
if self.debug > 5:
# ,'ind_from',ind_from,'continue?',(surplus_from >= 1) & (balance_from >= 1)
- print '\n potential emitter stop: id_stop_from', id_stop_from, 'surplus_from', surplus_from, 'balance_from', balance_from
+ print('\n potential emitter stop: id_stop_from', id_stop_from, 'surplus_from', surplus_from, 'balance_from', balance_from)
# there are empties to send away and positive balance
utilities = np.zeros(n_stops, dtype=np.float32)
numbers_move = np.zeros(n_stops, dtype=np.int32)
@@ -7421,9 +7421,9 @@ def equalize_empty_vehicles_broke(self, process):
time_to = times_stop_to_stop[id_stop_from, id_stop_to]
if self.debug > 5:
- print ' id_stop_from ', id_stop_from, 'id_stop_to', id_stop_to
- print ' balance_from', balance_from, 'balance_to', balance_to, 'min', -balance_to+0.5, surplus_from
- print ' demand_to', demand_to, 'waittime_max_to', waittime_max_to
+ print(' id_stop_from ', id_stop_from, 'id_stop_to', id_stop_to)
+ print(' balance_from', balance_from, 'balance_to', balance_to, 'min', -balance_to+0.5, surplus_from)
+ print(' demand_to', demand_to, 'waittime_max_to', waittime_max_to)
if (surplus_from >= 1) & (balance_from >= 1) & (demand_to > 0):
# the demand of the station is positive
@@ -7432,15 +7432,15 @@ def equalize_empty_vehicles_broke(self, process):
# move the maximum possible number of available vehicles
n_move = min(int(demand_to+0.5), surplus_from, int(-demand_from+0.5))
if self.debug > 5:
- print ' potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to
+ print(' potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to)
#utilities[j] = n_move+ self.constant_timeweight*time_to
#utilities[j] = float(n_move)/float(time_to)
utilities[j] = (waittime_max_to*demand_to)/float(time_to)
numbers_move[j] = n_move
if self.debug > 5:
- print ' ********'
- print ' U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to)
- print ' ********'
+ print(' ********')
+ print(' U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to))
+ print(' ********')
j += 1
elif 0: # (surplus_veh_urgent_from> 0 ):
@@ -7455,13 +7455,13 @@ def equalize_empty_vehicles_broke(self, process):
# high balance means vehicle needs to be kicked out
if self.debug > 5:
- print ' forced potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to
+ print(' forced potential n_move', n_move, 'vehs from stop', id_stop_from, 'to stop', id_stop_to)
#utilities[j] = n_move+ self.constant_timeweight*time_to
#utilities[j] = float(n_move)/float(time_to)
utilities[j] = n_move*(demand_to)/float(time_to)
numbers_move[j] = n_move
if self.debug > 5:
- print ' U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to)
+ print(' U=%.2f' % (utilities[j]), 'n_move', n_move, 'time_to %ds' % (time_to))
j += 1
ind_max = np.argmax(utilities)
@@ -7472,14 +7472,14 @@ def equalize_empty_vehicles_broke(self, process):
# or is this done in the platoon formation?
n_move = min(numbers_move[ind_max], 8)
if self.debug > 2:
- print ' utility_max %.0f' % utility_max, 'ind_max', ind_max, 'n_move', n_move
+ print(' utility_max %.0f' % utility_max, 'ind_max', ind_max, 'n_move', n_move)
#min(numbers_move[ind_max], self.flows_stop_max[ids_stop[inds_sorted][ind_max]])
if n_move > 0:
# there are some useful moves
n_move_eff = stops.route_empties(
id_stop_from, ids_stop[inds_sorted][ind_max], numbers_move[ind_max], simtime)
if self.debug > 2:
- print ' => moved', n_move_eff, 'of', numbers_move[ind_max], 'empty vehs from', id_stop_from, 'to', ids_stop[inds_sorted][ind_max], 'utility_max', utility_max
+ print(' => moved', n_move_eff, 'of', numbers_move[ind_max], 'empty vehs from', id_stop_from, 'to', ids_stop[inds_sorted][ind_max], 'utility_max', utility_max)
# continute till balance is zero?
# indeed need to update balances
@@ -7510,8 +7510,8 @@ def display_flows_est(self, id_stop, timeind_begin=None, timeind_end=None):
inds_disp = np.array(inds*factor, dtype=np.int32)
disp[inds_disp] = self.inflows_sched[id_stop, inds]
- print '%03d' % id_stop+(n_char-3)*'.'
- print string.join(disp, '')
+ print('%03d' % id_stop+(n_char-3)*'.')
+ print(string.join(disp, ''))
disp = None
if timeind_begin is not None:
@@ -7522,7 +7522,7 @@ def display_flows_est(self, id_stop, timeind_begin=None, timeind_end=None):
disp[int(timeind_end*factor+0.5)] = '<'
if disp is not None:
- print string.join(disp, '')
+ print(string.join(disp, ''))
# print ' flows',flows
# print ' inds',inds
# print ' inds_disp',inds_disp
@@ -7538,7 +7538,7 @@ def pull_empty_leadvehs_old(self, ids_veh_lead, process):
# & (stops.numbers_person_wait[self.ids_stop_current[ids_veh_lead]] == 0))
vehicles = self.get_vehicles()
stops = self.get_stops()
- print 'pull_empty_leadvehs', ids_veh_lead
+ print('pull_empty_leadvehs', ids_veh_lead)
# print ' bordingstate',vehicles.states[ids_veh_lead] == VEHICLESTATES['boarding']
# print ' nowaits stop',stops.numbers_person_wait[self.ids_stop_current[ids_veh_lead]] ==0
@@ -7575,7 +7575,7 @@ def pull_empty_leadvehs_old(self, ids_veh_lead, process):
ids_stop_target = self.ids_stop[inds_valid]
demands = demands[inds_valid]
- print ' ids_stop_current', ids_stop_current
+ print(' ids_stop_current', ids_stop_current)
# print ' ids_stop_target',ids_stop_target
# print ' demands',demands
# calculate cost matrix with id_stop_current in rows and id_stop_target
@@ -7592,7 +7592,7 @@ def pull_empty_leadvehs_old(self, ids_veh_lead, process):
costs = timeweight * demands
for id_stop_target, demand, number_veh, number_veh_arr\
in zip(ids_stop_target, demands, stops.numbers_veh[ids_stop_target], self.numbers_veh_arr[ids_stop_target]):
- print ' id_stop_target', id_stop_target, 'dem', demand, 'n_veh', number_veh, 'n_veh_arr', number_veh_arr
+ print(' id_stop_target', id_stop_target, 'dem', demand, 'n_veh', number_veh, 'n_veh_arr', number_veh_arr)
#costs = np.zeros(costs.size, np.float32)-demands
@@ -7622,7 +7622,7 @@ def pull_empty_leadvehs_old(self, ids_veh_lead, process):
durations_est,
):
- print ' check veh prt.%d' % (id_veh_lead), state, 'id_stop_current', id_stop_current, 'id_stop_target', id_stop_target
+ print(' check veh prt.%d' % (id_veh_lead), state, 'id_stop_current', id_stop_current, 'id_stop_target', id_stop_target)
#VEHICLESTATES = {'init':0,'waiting':1,'boarding':2,'alighting':3,'emptytrip':4,'occupiedtrip':5,'forewarding':6}
# if state == VEHICLESTATES['occupiedtrip']:
@@ -7657,7 +7657,7 @@ def init_trip_occupied(self, id_veh, id_stop_from, id_stop_to, time_order):
Called from the stop when a vehicle in the berth initiate a trip with
a the target destination of persons who entered
"""
- print 'init_trip_occupied to', id_stop_to
+ print('init_trip_occupied to', id_stop_to)
# search closest stop
#self.are_emptytrips[id_veh] = False
@@ -7672,7 +7672,7 @@ def init_trip(self, id_veh, id_stop, id_stop_to, time_order):
Called from the stop when a vehicle in the berth initiate a trip with
a the target destination
"""
- print 'init_trip_empty to', id_stop_to
+ print('init_trip_empty to', id_stop_to)
self.numbers_veh_target_init[id_stop_to] += 1
@@ -7681,7 +7681,7 @@ def init_trip_empty_old(self, id_veh, id_stop, id_stop_to, time_order):
Called from the stop when a vehicle in the berth initiate a trip with
a the target destination defined by the vehicle management
"""
- print 'init_trip_empty to', id_stop_to
+ print('init_trip_empty to', id_stop_to)
self.numbers_veh_target_init[id_stop_to] += 1
@@ -7741,7 +7741,7 @@ def get_scenario(self):
return self.parent.parent
def _init_attributes(self):
- print 'HcPrtService._init_attributes'
+ print('HcPrtService._init_attributes')
attrsman = self.get_attrsman()
scenario = self.get_scenario()
# here we ged classes not vehicle type
@@ -7774,7 +7774,7 @@ def _init_attributes(self):
virtualpop = self.get_scenario().demand.virtualpop
prttransits = virtualpop.get_plans().add_stagetable('hcprttransits', HcPrtTransits)
- print ' prttransits =', prttransits, id(prttransits)
+ print(' prttransits =', prttransits, id(prttransits))
# add attribute as link
# self.prttransits = attrsman.add(\
# cm.ObjConf(prttransits,is_child = False ),
@@ -7818,7 +7818,7 @@ def get_writexmlinfo(self, is_route=False, is_plain=False, **kwargs):
Method used to sort trips when exporting to route or trip xml file
"""
- print 'PRT.get_writexmlinfo'
+ print('PRT.get_writexmlinfo')
if is_plain:
return [], [], []
@@ -7914,14 +7914,14 @@ def write_prtvehicle_xml(self, fd, id_veh, time_begin, indent=2):
# self.make_times_stop_to_stop()
def prepare_sim(self, process):
- print 'prepare_sim', self.ident
+ print('prepare_sim', self.ident)
# print ' self.times_stop_to_stop',self.times_stop_to_stop
if self.fstar is None:
self.make_fstar()
if self.times_stop_to_stop is None:
- print ' times_stop_to_stop'
+ print(' times_stop_to_stop')
self.make_times_stop_to_stop()
updatedata = self.prtvehicles.prepare_sim(process)
@@ -7951,7 +7951,7 @@ def get_route(self, id_fromedge, id_toedge):
return route, duration
def make_times_stop_to_stop(self, fstar=None, times=None):
- print 'make_times_stop_to_stop'
+ print('make_times_stop_to_stop')
log = self.get_logger()
if fstar is None:
if self.fstar is None:
@@ -7976,8 +7976,8 @@ def make_times_stop_to_stop(self, fstar=None, times=None):
is_incomplete_fstar = False
for id_edge, id_stop, id_ptstop in zip(ids_edge, ids_prtstop, ids_ptstop):
# print ' Found PRT stop %d, PT stop %d with id_edge %d '%(id_stop,id_ptstop, id_edge)
- if not fstar.has_key(id_edge):
- print 'WARNING in make_times_stop_to_stop: PRT stop %d, PT stop %d has no id_edge %d in fstar' % (id_stop, id_ptstop, id_edge)
+ if id_edge not in fstar:
+ print('WARNING in make_times_stop_to_stop: PRT stop %d, PT stop %d has no id_edge %d in fstar' % (id_stop, id_ptstop, id_edge))
is_incomplete_fstar = True
# check if fstar is complete (all to edges are in keys)
@@ -7987,9 +7987,9 @@ def make_times_stop_to_stop(self, fstar=None, times=None):
if not ids_fromedge_set.issuperset(fstar[id_fromedge]):
is_incomplete_fstar = True
ids_miss = fstar[id_fromedge].difference(ids_fromedge_set)
- print 'WARNING in make_times_stop_to_stop: incomplete fstar of id_fromedge = %d, %s' % (id_fromedge, ids_sumo[id_fromedge])
+ print('WARNING in make_times_stop_to_stop: incomplete fstar of id_fromedge = %d, %s' % (id_fromedge, ids_sumo[id_fromedge]))
for id_edge in ids_miss:
- print ' missing', id_edge, ids_sumo[id_edge]
+ print(' missing', id_edge, ids_sumo[id_edge])
if is_incomplete_fstar:
return
@@ -8036,7 +8036,7 @@ def make_times_stop_to_stop(self, fstar=None, times=None):
stop_to_stop[ids_edge_to_ids_prtstop[id_edge],
ids_edge_to_ids_prtstop[id_edge_target]] = costs[id_edge_target]
else:
- print 'WARNING in make_times_stop_to_stop: unreacle station id_fromedge = %d, %s' % (id_edge_target, ids_sumo[id_edge_target])
+ print('WARNING in make_times_stop_to_stop: unreacle station id_fromedge = %d, %s' % (id_edge_target, ids_sumo[id_edge_target]))
is_incomplete_fstar = True
# put back origin to targets (probably not the best way)
@@ -8051,7 +8051,7 @@ def make_times_stop_to_stop(self, fstar=None, times=None):
self.times_stop_to_stop = stop_to_stop
self.ids_edge_to_ids_prtstop = ids_edge_to_ids_prtstop
- print ' times_stop_to_stop=\n', self.times_stop_to_stop
+ print(' times_stop_to_stop=\n', self.times_stop_to_stop)
return True
def get_fstar(self):
@@ -8059,7 +8059,7 @@ def get_fstar(self):
Returns the forward star graph of the network as dictionary:
fstar[id_fromedge] = set([id_toedge1, id_toedge2,...])
"""
- print 'get_fstar'
+ print('get_fstar')
net = self.get_scenario().net
# prt mode
id_mode = self.id_prtmode
@@ -8096,7 +8096,7 @@ def get_fstar(self):
if id_mode_allow_from == id_mode:
if id_mode_allow_to == id_mode:
- if fstar.has_key(id_fromedge):
+ if id_fromedge in fstar:
fstar[id_fromedge].add(id_toedge)
else:
fstar[id_fromedge] = set([id_toedge])
@@ -8133,7 +8133,7 @@ def get_times(self, fstar):
#id_mode = net.modes.get_id_mode(mode)
id_mode = self.id_prtmode
# print 'get_times id_mode,is_check_lanes,speed_max',id_mode,is_check_lanes,speed_max
- ids_edge = np.array(fstar.keys(), dtype=np.int32)
+ ids_edge = np.array(list(fstar.keys()), dtype=np.int32)
times = np.array(np.zeros(np.max(ids_edge)+1, np.float32))
speeds = net.edges.speeds_max[ids_edge]
@@ -8146,7 +8146,7 @@ def get_times(self, fstar):
return times
def config_results(self, results):
- print 'HcPrtService.config_results', results, id(results)
+ print('HcPrtService.config_results', results, id(results))
# keep a link to results here because needed to
# log data during simulation
# this link should not be followed during save process
@@ -8223,8 +8223,8 @@ def get_prtstops(self):
# return self.ids_stop.get_linktab()
def init_recording(self, n_timesteps, time_step):
- print 'HC init_recording n_timesteps, time_step', n_timesteps, time_step, len(self.ids_stop.get_linktab().get_ids())
- print ' stops instance', self.prtstops.get_value(), self.ids_stop.get_linktab(), id(self.prtstops.get_value()), id(self.ids_stop.get_linktab())
+ print('HC init_recording n_timesteps, time_step', n_timesteps, time_step, len(self.ids_stop.get_linktab().get_ids()))
+ print(' stops instance', self.prtstops.get_value(), self.ids_stop.get_linktab(), id(self.prtstops.get_value()), id(self.ids_stop.get_linktab()))
self.clear()
self.time_step.set_value(time_step)
@@ -8242,13 +8242,13 @@ def record(self, timestep, ids, **kwargs):
inds = self.ids_stop.get_linktab().get_inds(ids)
timestep_int = int(timestep)
- for attrname, values in kwargs.iteritems():
- print ' record', attrname, 'dtype', values.dtype, values.shape, 'array', getattr(self, attrname).get_value().dtype, 'shape', getattr(self, attrname).get_value().shape
+ for attrname, values in kwargs.items():
+ print(' record', attrname, 'dtype', values.dtype, values.shape, 'array', getattr(self, attrname).get_value().dtype, 'shape', getattr(self, attrname).get_value().shape)
# print ' inds',type(inds),inds.dtype,
getattr(self, attrname).get_value()[inds, timestep_int] = values
def get_stopresultattrconfigs(self):
- return self.get_attrsman().get_group_attrs('PRT results').values()
+ return list(self.get_attrsman().get_group_attrs('PRT results').values())
def get_persons(self):
return self.ids_person.get_linktab()
diff --git a/tools/contributed/sumopy/plugins/hcprt/results_mpl.py b/tools/contributed/sumopy/plugins/hcprt/results_mpl.py
index c8176ca1c2b2..09716f5f5aac 100644
--- a/tools/contributed/sumopy/plugins/hcprt/results_mpl.py
+++ b/tools/contributed/sumopy/plugins/hcprt/results_mpl.py
@@ -42,11 +42,11 @@ def __init__(self, results, name='Plot PRT stop results with Matplotlib',
self._init_common('stopresultsplotter', parent=results, name=name,
info=info, logger=logger)
- print 'StopresultsPlotter.__init__', results, self.parent, len(self.get_stopresults())
+ print('StopresultsPlotter.__init__', results, self.parent, len(self.get_stopresults()))
attrsman = self.get_attrsman()
stops = self.get_stopresults().get_prtstops()
- print ' prtstops', stops, len(stops), id(stops), self.get_stopresults().ids_stop.get_linktab(), id(self.get_stopresults().ids_stop.get_linktab())
+ print(' prtstops', stops, len(stops), id(stops), self.get_stopresults().ids_stop.get_linktab(), id(self.get_stopresults().ids_stop.get_linktab()))
choices_stop = {}
for id_stop in stops.get_ids():
choices_stop[str(id_stop)] = id_stop
@@ -131,10 +131,10 @@ def get_stopresults(self):
def show(self):
stopresults = self.get_stopresults()
- print 'show', stopresults
+ print('show', stopresults)
# print ' dir(vehicleman)',dir(vehicleman)
- print ' len(stopresults)', len(stopresults)
+ print(' len(stopresults)', len(stopresults))
if len(stopresults) > 0:
i_fig = 0
plt.close("all")
@@ -166,7 +166,7 @@ def show(self):
plt.show()
def plot_flow_stop(self, fig):
- print 'plot_flow_stop'
+ print('plot_flow_stop')
id_stop = self.id_stop_plot
stopresults = self.get_stopresults()
ax = fig.add_subplot(111)
@@ -224,7 +224,7 @@ def plot_flow_stop(self, fig):
ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
def plot_waiting_person_time(self, fig):
- print 'plot_waiting_person_time'
+ print('plot_waiting_person_time')
stopresults = self.get_stopresults()
ax = fig.add_subplot(111)
@@ -251,7 +251,7 @@ def plot_waiting_person_time(self, fig):
ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
def plot_waiting_person_number_stop(self, fig):
- print 'plot_waiting_person_number_stop'
+ print('plot_waiting_person_number_stop')
stopresults = self.get_stopresults()
#ax1 = fig.add_subplot(211)
#ax2 = fig.add_subplot(212)
@@ -275,7 +275,7 @@ def plot_waiting_person_number_stop(self, fig):
ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
def plot_waiting_person_number(self, fig):
- print 'plot_waiting_person_number'
+ print('plot_waiting_person_number')
stopresults = self.get_stopresults()
#ax1 = fig.add_subplot(211)
#ax2 = fig.add_subplot(212)
@@ -288,7 +288,7 @@ def plot_waiting_person_number(self, fig):
# works:ax.plot(time.reshape(n_steps,1),numbers_person_wait.reshape(n_steps,-1))
i = 0
for id_stop in stopresults.ids_stop.get_value():
- print ' id_stop', id_stop
+ print(' id_stop', id_stop)
ax.plot(time, stopresults.numbers_person_wait[id_stop],
get_color(i), linewidth=self.width_line,
label='PRT Stop ID=%d' % id_stop)
@@ -302,7 +302,7 @@ def plot_waiting_person_number(self, fig):
ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
def plot_flows_compare(self, fig):
- print 'plot_flows_compare'
+ print('plot_flows_compare')
stopresults = self.get_stopresults()
#time_update_flows = self.parent.vehicleman.time_update_flows.get_value()
time_update_flows = 10
@@ -315,7 +315,7 @@ def plot_flows_compare(self, fig):
i = 0
flowmatrix = np.zeros((10, 10), dtype=np.int32)
for id_stop in stopresults.ids_stop.get_value():
- print ' id_stop', id_stop
+ print(' id_stop', id_stop)
# print ' sched',stopresults.inflows_veh_sched[id_stop]
# print ' eff ',stopresults.inflows_veh[id_stop]
flowmatrix[np.array(time_update_flows*stopresults.inflows_veh_sched[id_stop], dtype=np.int32),
@@ -325,7 +325,7 @@ def plot_flows_compare(self, fig):
# label = 'PRT Stop ID=%d (effective)'%id_stop)
i += 1
- print 'flowmatrix', flowmatrix
+ print('flowmatrix', flowmatrix)
# ax.matshow(flowmatrix)
cax = ax.matshow(flowmatrix, cmap=cmx.get_cmap('PuBu'))
@@ -338,7 +338,7 @@ def plot_flows_compare(self, fig):
ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
def plot_flows_compare_stop(self, fig):
- print 'plot_flows_compare_stop'
+ print('plot_flows_compare_stop')
stopresults = self.get_stopresults()
id_stop = self.id_stop_plot
#time_update_flows = self.parent.vehicleman.time_update_flows.get_value()
@@ -358,7 +358,7 @@ def plot_flows_compare_stop(self, fig):
time = np.arange(-n_steps+1, n_steps, dtype=np.float32)*t_step
- print ' len(flowcorr),n_steps', len(flowcorr), len(time), n_steps
+ print(' len(flowcorr),n_steps', len(flowcorr), len(time), n_steps)
ax.plot(time, flowcorr,
get_color(i), linewidth=self.width_line,
@@ -372,7 +372,7 @@ def plot_flows_compare_stop(self, fig):
ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
def plot_flows(self, fig):
- print 'plot_flows'
+ print('plot_flows')
stopresults = self.get_stopresults()
ax = fig.add_subplot(111)
@@ -408,7 +408,7 @@ def plot_flows(self, fig):
# ('inflows_person', {'name':'Person in-flows', 'unit':'1/s', 'dtype':np.float32, 'info':'Person flow into the stop over time.'}),
def plot_waiting_person(self, fig):
- print 'plot_waiting_person'
+ print('plot_waiting_person')
stopresults = self.get_stopresults()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
diff --git a/tools/contributed/sumopy/plugins/hcprt/wxgui.py b/tools/contributed/sumopy/plugins/hcprt/wxgui.py
index 7ac8195b7c69..59a5e17c96e8 100644
--- a/tools/contributed/sumopy/plugins/hcprt/wxgui.py
+++ b/tools/contributed/sumopy/plugins/hcprt/wxgui.py
@@ -28,13 +28,13 @@
from coremodules.network import routing
from coremodules.demand import demand
from coremodules.simulation import sumo, results
-import hcprt
+from . import hcprt
try:
- import results_mpl as results_mpl
+ from . import results_mpl as results_mpl
is_mpl = True # we have matplotlib support
except:
- print "WARNING: python matplotlib package not installed, no matplotlib plots."
+ print("WARNING: python matplotlib package not installed, no matplotlib plots.")
is_mpl = False
@@ -91,7 +91,7 @@ def refresh_widgets(self):
dependent on the availability of data.
"""
scenario = self.get_scenario()
- print 'prtgui.refresh_widgets', self._simulation != scenario.simulation
+ print('prtgui.refresh_widgets', self._simulation != scenario.simulation)
is_refresh = False
if self._simulation != scenario.simulation:
@@ -214,7 +214,7 @@ def on_clear_vehicles(self, event=None):
self._mainframe.browse_obj(self._prtservice.prtvehicles)
def on_mpl_stopresults(self, event=None):
- print 'on_mpl_stopresults', id(self._simulation.results) # ,id(self._prtservice.get_results())
+ print('on_mpl_stopresults', id(self._simulation.results)) # ,id(self._prtservice.get_results())
if self._prtservice is not None:
if self._simulation is not None:
resultplotter = results_mpl.StopresultsPlotter(self._simulation.results, # self._prtservice.get_results(),
diff --git a/tools/contributed/sumopy/plugins/mapmatching/__init__.py b/tools/contributed/sumopy/plugins/mapmatching/__init__.py
index cab987aa8f9c..02fdf630fcec 100644
--- a/tools/contributed/sumopy/plugins/mapmatching/__init__.py
+++ b/tools/contributed/sumopy/plugins/mapmatching/__init__.py
@@ -18,12 +18,12 @@
__version__ = "0.0"
-print 'init', __name__
+print('init', __name__)
def get_wxgui():
# try:
- from wxgui import WxGui
+ from .wxgui import WxGui
return WxGui(__name__)
# except:
# return None
diff --git a/tools/contributed/sumopy/plugins/mapmatching/mapmatching.py b/tools/contributed/sumopy/plugins/mapmatching/mapmatching.py
index 32e9f110d921..d9f815a82e5f 100755
--- a/tools/contributed/sumopy/plugins/mapmatching/mapmatching.py
+++ b/tools/contributed/sumopy/plugins/mapmatching/mapmatching.py
@@ -71,12 +71,12 @@
from shapely.geometry import Polygon, MultiPolygon, MultiLineString, Point, LineString, MultiPoint, asLineString, asMultiPoint
from shapely.ops import cascaded_union
except:
- print 'Import error: No shapely module available.'
+ print('Import error: No shapely module available.')
except:
- print 'Import error: in order to run the traces plugin please install the following modules:'
- print ' mpl_toolkits.basemap and shapely'
- print 'Please install these modules if you want to use it.'
- print __doc__
+ print('Import error: in order to run the traces plugin please install the following modules:')
+ print(' mpl_toolkits.basemap and shapely')
+ print('Please install these modules if you want to use it.')
+ print(__doc__)
raise
AGES_STRAVA = {'unknown':0,
@@ -409,7 +409,7 @@ def get_boundary(coords):
class OdCreator(Process):
def __init__(self, ident, mapmatching, logger = None, **kwargs):
- print 'VpCreator.__init__'
+ print('VpCreator.__init__')
self._init_common( ident,
parent = mapmatching,
name = 'Od routes creator from GPS trips',
@@ -484,7 +484,7 @@ def __init__(self, ident, mapmatching, logger = None, **kwargs):
info='transport mode of the flow.',
))
def do(self):
- print 'OdCreator.__do__'
+ print('OdCreator.__do__')
#Preparation
logger = self.get_logger()
scenario = self.get_scenario()
@@ -519,7 +519,7 @@ def do(self):
to_zone[id_trip] = id_zone
analyzedtrips += 0.5
break
- print analyzedtrips
+ print(analyzedtrips)
i = 0
j= 0
for id_zonei in ids_zone:
@@ -532,7 +532,7 @@ def do(self):
j = 0
n_trip = np.sum(od_matrix)
- print ' number of trips', n_trip
+ print(' number of trips', n_trip)
generated = np.zeros(len(od_matrix[0,:]))
attracted = np.zeros(len(od_matrix[:,0]))
@@ -563,8 +563,8 @@ def do(self):
re_allocates = generated - attracted
- print 'generated',generated, 'attracted',attracted, 're_allocates', re_allocates
- print 'od_matrix',od_matrix
+ print('generated',generated, 'attracted',attracted, 're_allocates', re_allocates)
+ print('od_matrix',od_matrix)
np.savetxt('od_matrix.csv', od_matrix)
return od_matrix, generated, attracted, re_allocates
@@ -577,7 +577,7 @@ def get_scenario(self):
class OdRouteCreator(Process):
def __init__(self, ident, mapmatching, logger = None, **kwargs):
- print 'OdRouteCreator.__init__'
+ print('OdRouteCreator.__init__')
self._init_common( ident,
parent = mapmatching,
name = 'Od routes creator from GPS trips',
@@ -589,7 +589,7 @@ def __init__(self, ident, mapmatching, logger = None, **kwargs):
def do(self):
- print 'OdRouteCreator.__do__'
+ print('OdRouteCreator.__do__')
#Preparation
logger = self.get_logger()
scenario = self.get_scenario()
@@ -603,7 +603,7 @@ def do(self):
ids_trip = trips.get_ids()
ids_trip = ids_trip[trips.are_selected[ids_trip] & np.logical_not(np.equal(trips.ids_points[ids_trip],None))]
n_trips = len(ids_trip)
- print ' len(ids_trip)',n_trips
+ print(' len(ids_trip)',n_trips)
trips_demand.clear_trips()
trips_demand.clear_routes()
@@ -643,7 +643,7 @@ def get_scenario(self):
class VpCreator(Process):
def __init__(self, ident='vpcreator', mapmatching=None, logger = None, **kwargs):
- print 'VpCreator.__init__'
+ print('VpCreator.__init__')
self._init_common( ident,
parent = mapmatching,
name = 'VP creator from GPS trips',
@@ -795,7 +795,7 @@ def __init__(self, ident='vpcreator', mapmatching=None, logger = None, **kwargs)
def do(self):
- print 'VpCreator.__do__'
+ print('VpCreator.__do__')
#Preparation
logger = self.get_logger()
scenario = self.get_scenario()
@@ -831,8 +831,8 @@ def do(self):
persons = scenario.demand.mapmatching.persons
persons.analyze()
- print 'id_strategy =',self.id_strategy
- print 'is_first_method =',self.is_first_method
+ print('id_strategy =',self.id_strategy)
+ print('is_first_method =',self.is_first_method)
#select strategy
if self.is_first_method == True:
if self.id_strategy == -1:
@@ -843,7 +843,7 @@ def do(self):
ids_trip = ids_trip_bike
ids_trip = np.append(ids_trip,ids_trip_bus)
ids_trip = np.append(ids_trip,ids_trip_ped)
- print 'ids_trip =',ids_trip
+ print('ids_trip =',ids_trip)
# ids_trip = ids_trip_bike + ids_trip_ped + ids_trip_bus
if self.id_strategy == strategies.get_id_from_formatted('walk'):
ids_trip_ped = ids_trip[(ids_mode == modes.get_id_from_formatted('pedestrian'))]
@@ -912,9 +912,9 @@ def do(self):
if self.is_first_method == True:
n_pers = int(n_pers*(float(self.scale - count))) #scale parameter based on people number
- print 'new n_pers = ',n_pers
+ print('new n_pers = ',n_pers)
- print 'old ids_trip = ',ids_trip
+ print('old ids_trip = ',ids_trip)
if self.id_strategy == -1:
ids_trip = np.array([],dtype = np.int32)
@@ -947,14 +947,14 @@ def do(self):
#ids_trip = np.random.choice(ids_trip, n_pers, replace = False)
#ids_trip.sort()
- print 'new ids_trip = ',ids_trip
+ print('new ids_trip = ',ids_trip)
elif self.is_first_method == False:
n_trips_tab = int(n_trips_for_scale*(float(self.scale - count))) # scale parameter based on trips number
- print 'new n_pers = ',n_pers
+ print('new n_pers = ',n_pers)
- print 'old ids_pers = ',ids_pers
+ print('old ids_pers = ',ids_pers)
if self.id_strategy == -1:
@@ -1003,13 +1003,13 @@ def do(self):
#ids_pers = np.random.choice(ids_pers, n_pers, replace = False)
#ids_pers.sort()
- print 'new ids_pers = ',ids_pers
+ print('new ids_pers = ',ids_pers)
elif count == max(range(int(self.scale + 1.0))) and difference == 0.0:
break
if self.is_first_method == True:
#create virtual person
- print 'create virtal person'
+ print('create virtal person')
ids_person = virtualpop.make_multiple(n_pers)
## localtime = time.localtime
@@ -1024,7 +1024,7 @@ def do(self):
## seconds_arrive = np.zeros(n_pers, dtype = np.float32)
## duration_for_scale = np.zeros(n_pers, dtype = np.float32)
- for id_trip, id_person, i in zip(ids_trip, ids_person, range(len(ids_trip))):
+ for id_trip, id_person, i in zip(ids_trip, ids_person, list(range(len(ids_trip)))):
#Population attributes
virtualpop.ids_mode_preferred[id_person] = scenario.demand.vtypes.ids_mode[trips.ids_vtype[id_trip]]
virtualpop.years_birth[id_person] = persons.years_birth[trips.ids_person[id_trip]]
@@ -1052,9 +1052,9 @@ def do(self):
elif self.is_first_method == False:
#create virtual person
- print 'create virtal person'
+ print('create virtal person')
ids_vppers = virtualpop.make_multiple(n_pers)
- print 'ids_vppers',ids_vppers
+ print('ids_vppers',ids_vppers)
pers_vppers = np.zeros(np.max(ids_pers)+1, dtype = np.int32)
## pers_vppers = []
for pers, vppers in zip(ids_pers, ids_vppers):
@@ -1064,7 +1064,7 @@ def do(self):
for id_pers, id_vppers, ids_trip in zip(ids_pers, ids_vppers, ids_trips):
#Population attributes
- print 'Add population attributes'
+ print('Add population attributes')
ids_mode = scenario.demand.vtypes.ids_mode[trips.ids_vtype[ids_trip]]
id_preferred_mode = np.argmax(np.bincount(ids_mode))
virtualpop.ids_mode_preferred[id_vppers] = id_preferred_mode
@@ -1074,7 +1074,7 @@ def do(self):
virtualpop.identifications[id_vppers] = persons.ids_sumo[id_pers]
#Calculate trips departure and arrive times
- print 'Calculate trips departure and arrive times'
+ print('Calculate trips departure and arrive times')
if self.id_strategy == strategies.get_id_from_formatted('bike') or self.id_strategy == -1:
seconds_departure_bike = np.zeros(len(ids_trip_bike), dtype = np.float32)
@@ -1104,13 +1104,13 @@ def do(self):
seconds_arrive_bike[i] = seconds_departure_bike[i] + duration_for_scale_bike[i]
i+=1
- print ' min_seconds_departure_bike: ',min_seconds_departure_bike
- print ' max_seconds_arrive_bike: ',max_seconds_departure_bike
- print
- print ' ids_trip_bike: ',ids_trip_bike
- print
- print ' seconds_departure_bike: ', seconds_departure_bike
- print
+ print(' min_seconds_departure_bike: ',min_seconds_departure_bike)
+ print(' max_seconds_arrive_bike: ',max_seconds_departure_bike)
+ print()
+ print(' ids_trip_bike: ',ids_trip_bike)
+ print()
+ print(' seconds_departure_bike: ', seconds_departure_bike)
+ print()
if self.id_strategy == strategies.get_id_from_formatted('transit') or self.id_strategy == -1:
@@ -1144,7 +1144,7 @@ def do(self):
i+=1
- print seconds_departure_bus, seconds_arrive_bus
+ print(seconds_departure_bus, seconds_arrive_bus)
if self.id_strategy == strategies.get_id_from_formatted('walk') or self.id_strategy == -1:
seconds_departure_ped = np.zeros(len(ids_trip_ped), dtype = np.float32)
@@ -1177,7 +1177,7 @@ def do(self):
i+=1
- print seconds_departure_ped, seconds_arrive_ped
+ print(seconds_departure_ped, seconds_arrive_ped)
# call Vehicle provider to give vehicles to persons
@@ -1211,10 +1211,10 @@ def do(self):
fstar = net.edges.get_fstar()
#Preapare parameters for stages
- print 'Preapare parameters for stages'
+ print('Preapare parameters for stages')
#bus
- print 'Preapare parameters for BUS plans'
+ print('Preapare parameters for BUS plans')
if self.id_strategy == strategies.get_id_from_formatted('transit') or self.id_strategy == -1:
times_from_bus = seconds_departure_bus
durations_approx_bus = seconds_arrive_bus - seconds_departure_bus
@@ -1261,13 +1261,13 @@ def do(self):
## ids_route = trips.ids_route_matched[ids_trip]
#Identify closest edge for facilities
- print 'Identify closest edge for facilities from'
+ print('Identify closest edge for facilities from')
facilities.identify_closest_edge(ids = ids_fac_from_bus, priority_max = 7, has_sidewalk = True)
- print 'Identify closest edge for facilities to'
+ print('Identify closest edge for facilities to')
facilities.identify_closest_edge(ids = ids_fac_to_bus, priority_max = 7, has_sidewalk = True)
#bike
- print 'Preapare parameters for BIKE plans'
+ print('Preapare parameters for BIKE plans')
if self.id_strategy == strategies.get_id_from_formatted('bike') or self.id_strategy == -1:
times_from_bike = seconds_departure_bike
@@ -1325,16 +1325,16 @@ def do(self):
ids_fac_to_bike[i] = int(distance_fac_list_to[0,1])
i+=1
- print 'ids_only_bike_trip', ids_only_bike_trip
+ print('ids_only_bike_trip', ids_only_bike_trip)
## ids_route = trips.ids_route_matched[ids_trip]
#Identify closest edge for facilities
- print 'Identify closest edge for facilities from'
+ print('Identify closest edge for facilities from')
facilities.identify_closest_edge(ids = ids_fac_from_bike, priority_max = 7, has_sidewalk = True)
- print 'Identify closest edge for facilities to'
+ print('Identify closest edge for facilities to')
facilities.identify_closest_edge(ids = ids_fac_to_bike, priority_max = 7, has_sidewalk = True)
#pedestrian
- print 'Preapare parameters for PEDESTRIAN plans'
+ print('Preapare parameters for PEDESTRIAN plans')
if self.id_strategy == strategies.get_id_from_formatted('walk') or self.id_strategy == -1:
times_from_ped = seconds_departure_ped
@@ -1374,7 +1374,7 @@ def do(self):
available_strategies.append(strategies.get_id_from_formatted('transit'))
for strategy in available_strategies:
- print 'init strategy', strategy
+ print('init strategy', strategy)
if strategy == strategies.get_id_from_formatted('bike'):
@@ -1404,7 +1404,7 @@ def do(self):
#walk1
- print 'Prepare parameters for Walk1'
+ print('Prepare parameters for Walk1')
ids_edge_from_walk1 = facilities.ids_roadedge_closest[ids_fac_from]
positions_edge_from_walk1 = facilities.positions_roadedge_closest[ids_fac_from]
@@ -1424,7 +1424,7 @@ def do(self):
ids_edge_to_walk1 = facilities.ids_roadedge_closest[ids_fac_to]
if strategy == strategies.get_id_from_formatted('transit') or strategy == strategies.get_id_from_formatted('bike'):
#walk2
- print 'Prepare parameters for Walk2'
+ print('Prepare parameters for Walk2')
times_from_walk2 = seconds_arrive +1.-1.
@@ -1437,9 +1437,9 @@ def do(self):
ids_edge_from_walk2 = ids_edge_to_busstop
positions_edge_from_walk2 = positions_edge_to_busstop
- print seconds_arrive
+ print(seconds_arrive)
#act1
- print 'Prepare parameters for Act1'
+ print('Prepare parameters for Act1')
unitvec_int_act = np.ones(n_trips)
ids_edge_from_act1 = facilities.ids_roadedge_closest[ids_fac_from]
@@ -1449,7 +1449,7 @@ def do(self):
times_from_act1 = seconds_departure-3600.0
#act2
- print 'Prepare parameters for Act2'
+ print('Prepare parameters for Act2')
ids_edge_to_act2 = facilities.ids_roadedge_closest[ids_fac_to]
positions_edge_to = facilities.positions_roadedge_closest[ids_fac_to]
@@ -1458,7 +1458,7 @@ def do(self):
durations_act_to = np.ones(n_trips)*3600.0
#Add activities
- print 'Add activities '
+ print('Add activities ')
## ids_fac_from = ids_facilities[ids_fac_from]
## ids_fac_to = ids_facilities[ids_fac_to]
@@ -1485,7 +1485,7 @@ def do(self):
virtualpop.activitypatterns[id_person] = [id_activity_from,id_activity_to, ]
#Create plans
- print 'Create plans'
+ print('Create plans')
ids_plan = virtualpop.add_plans(ids_person, strategy)
# QUESTO METODO POTREBBE ESSERE VALIDO ANCHE PER VPCREATOR1???
@@ -1493,18 +1493,18 @@ def do(self):
for id_person,id_activity_from,id_activity_to in zip(ids_person,ids_activity_from,ids_activity_to):
if virtualpop.activitypatterns[id_person] is not None:
patterns = virtualpop.activitypatterns[id_person]
- print 'patterns', patterns
+ print('patterns', patterns)
patterns.append(id_activity_from)
- print 'patterns', patterns
+ print('patterns', patterns)
patterns.append(id_activity_to)
- print 'patterns', patterns
+ print('patterns', patterns)
virtualpop.activitypatterns[id_person] = patterns
- print 'patterns', patterns
+ print('patterns', patterns)
else:
virtualpop.activitypatterns[id_person] = [id_activity_from, id_activity_to]
#Create plans
- print 'Create plans'
+ print('Create plans')
if strategy == strategies.get_id_from_formatted('transit') or strategy ==strategies.get_id_from_formatted('bike'):
ids_plan = virtualpop.add_plans(ids_person, strategy)
elif strategy == strategies.get_id_from_formatted('walk'):
@@ -1515,7 +1515,7 @@ def do(self):
#Add activity stages
- print 'Add activity stages'
+ print('Add activity stages')
for id_plan,\
id_act_from,\
@@ -1542,7 +1542,7 @@ def do(self):
)
#Add walk stages
- print 'Add walk stages'
+ print('Add walk stages')
ids_walk1 = np.zeros(len(ids_trip), dtype = np.int32)
times_end_walk1 = np.zeros(len(ids_trip), dtype = np.int32)
@@ -1562,11 +1562,11 @@ def do(self):
ids_edge_to_walk1,\
positions_edge_to_walk1,\
ids_person,\
- range(len(ids_trip))):
+ list(range(len(ids_trip)))):
try:
ids_only_bike_trip.index(id_pers)
except:
- print 'plan first walk'
+ print('plan first walk')
ids_walk1[i] , times_end_walk1[i] = virtualpop.get_plans().get_stagetable('walks').append_stage(\
id_plan, time_from,
id_edge_from = id_edge_from,
@@ -1576,7 +1576,7 @@ def do(self):
)
durations_walk1 = np.zeros(len(ids_trip), dtype = np.int32)
- for time_end, second_departure, i in zip(times_end_walk1, seconds_departure, range(len(ids_trip))) :
+ for time_end, second_departure, i in zip(times_end_walk1, seconds_departure, list(range(len(ids_trip)))) :
if time_end !=0:
durations_walk1[i] = virtualpop.get_plans().get_stagetable('walks').durations[ids_walk1[i]]
#bike
@@ -1602,11 +1602,11 @@ def do(self):
positions_edge_to_walk1,\
ids_person,\
ids_trip,\
- range(len(ids_trip))):
+ list(range(len(ids_trip)))):
try:
ids_only_bike_trip.index(id_trip)
except:
- print 'plan first walk'
+ print('plan first walk')
ids_walk1[i] , times_end_walk1[i] = virtualpop.get_plans().get_stagetable('walks').append_stage(\
id_plan, time_from,
id_edge_from = id_edge_from,
@@ -1616,10 +1616,10 @@ def do(self):
)
durations_walk1 = np.zeros(len(ids_trip), dtype = np.float32)
- for time_end, second_departure, i in zip(times_end_walk1, seconds_departure, range(len(ids_trip))) :
+ for time_end, second_departure, i in zip(times_end_walk1, seconds_departure, list(range(len(ids_trip)))) :
if time_end !=0:
durations_walk1[i] = virtualpop.get_plans().get_stagetable('walks').durations[ids_walk1[i]]
- print seconds_departure, durations_walk1
+ print(seconds_departure, durations_walk1)
if strategy ==strategies.get_id_from_formatted('bike'):
#bike
@@ -1630,7 +1630,7 @@ def do(self):
if strat_for_stages == strategies.get_id_from_formatted('bike'):
#Add bikeride stages
- print 'Add bikeride stages'
+ print('Add bikeride stages')
## virtualpop.get_plans().get_stagetable('bikeride').prepare_planning()
## duration_approx1, route1 = routing.get_mincostroute_edge2edge(
## ids_edge_from_bike,
@@ -1674,14 +1674,14 @@ def do(self):
if strat_for_stages == strategies.get_id_from_formatted('transit'):
#Add bus stages
- print 'Add bus stages'
+ print('Add bus stages')
ids_route = trips.ids_route_matched[ids_trip]
ids_ptlinks = trips.get_routes().ids_ptlinks[ids_route]
- for id_route, id_plan, time_from_bus, i in zip(ids_route, ids_plan,times_from_bus, range(len(ids_trip))):
+ for id_route, id_plan, time_from_bus, i in zip(ids_route, ids_plan,times_from_bus, list(range(len(ids_trip)))):
ids_ptlinks = trips.get_routes().ids_ptlinks[id_route]
types_ptlinks = scenario.demand.ptlines.get_ptlinks().types[ids_ptlinks]
board = 0
- for type, id_ptlink, j in zip(types_ptlinks, ids_ptlinks, range(len(ids_ptlinks))):
+ for type, id_ptlink, j in zip(types_ptlinks, ids_ptlinks, list(range(len(ids_ptlinks)))):
#board
if type == 3:
if board ==1:
@@ -1705,7 +1705,7 @@ def do(self):
duration = scenario.demand.ptlines.get_ptlinks().durations[id_ptlink]
id_fromstop = scenario.demand.ptlines.get_ptlinks().ids_fromstop[id_ptlink]
numb_links = j
- print i, scenario.demand.ptlines.get_ptlinks().types[ids_ptlinks[numb_links+1]]
+ print(i, scenario.demand.ptlines.get_ptlinks().types[ids_ptlinks[numb_links+1]])
is_ok = True
if numb_links+2=2):
+ if (id_mode in distancesmap) & (id_mode != id_mode_ped) & (len(ids_point)>=2):
are_valid = distancesmap[id_mode] > self.dist_min_modespecific
@@ -2103,11 +2103,11 @@ def do(self):
)
else:
logger.w(" Failed id_trip %d because pedestrian mode or id_mode %d does not occured in network"%(id_trip,id_mode))
- print ' distancesmap.keys()',distancesmap.keys()
+ print(' distancesmap.keys()',list(distancesmap.keys()))
else:
logger.w(" Failed id_trip %d because no points"%(id_trip))
- print ' ids_point',ids_point
+ print(' ids_point',ids_point)
n_trip_matched += 1
@@ -2133,8 +2133,8 @@ def match_trip_birgil(self,id_trip, ids_point, fstar, weights, accesslevels):
# triplength
# TODO: check get_closest_edge everywhere if projecting properly
- print 79*'='
- print 'match_trip_birgil',id_trip,'n_points=',len(ids_point)
+ print(79*'=')
+ print('match_trip_birgil',id_trip,'n_points=',len(ids_point))
#print ' ids_point',ids_point
#print ' weights[26216]',weights[26216],accesslevels[26216]
#print ' weights[26217]',weights[26217],accesslevels[26217]
@@ -2317,7 +2317,7 @@ def match_trip_birgil(self,id_trip, ids_point, fstar, weights, accesslevels):
routelist_new = []
n_routes = len(routelist)
- for ind_route in xrange(n_routes):
+ for ind_route in range(n_routes):
#routeinfo = 1*routeinfo_orig
costs_tot, cost, length_partial, length_cum, accesslevel, length_edge, ids_edge, ids_point_edgeend = routelist[ind_route]
routeinfo = costs_tot, cost, length_partial, length_cum, accesslevel, length_edge, ids_edge, ids_point_edgeend
@@ -2449,10 +2449,10 @@ def match_trip_birgil(self,id_trip, ids_point, fstar, weights, accesslevels):
# take only the chapest route that arrives at a specific edge
n_routes = len(routelist)
- for route, i in zip(routelist[:-1],xrange(n_routes-1)):
+ for route, i in zip(routelist[:-1],range(n_routes-1)):
#cost_tot = route[0]
id_edge_last = route[6][-1]
- for j in xrange(i+1,n_routes):
+ for j in range(i+1,n_routes):
if routelist[j][6][-1] == id_edge_last:
routelist[j][0] = np.inf
# this will throw all infinites to the tail
@@ -2529,7 +2529,7 @@ def match_trip_birgil(self,id_trip, ids_point, fstar, weights, accesslevels):
# check dist error
- inds_point = xrange(ind_point_initial,ind_point_final)
+ inds_point = range(ind_point_initial,ind_point_final)
n_points = len(inds_point)
@@ -2773,7 +2773,7 @@ def _get_cost_birgil2(self, phi_point, accesslevel, dist, segment, is_reverse =
class PTMatcher(BirgilMatcher):
def __init__(self, ident, mapmatching, logger = None, **kwargs):
- print 'PTMatcher.__init__'
+ print('PTMatcher.__init__')
# TODO: let this be independent, link to it or child??
@@ -2959,7 +2959,7 @@ def do(self):
fstar = ptlinks.get_fstar()
if len(fstar) == 0:
- print 'WARNING: no PT links built.'
+ print('WARNING: no PT links built.')
return False
ids_trip = trips.get_ids_selected()
@@ -3025,8 +3025,8 @@ def get_scenario(self):
def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances, busedgetimes, accesslevels):
- print 79*'='
- print 'match_trip',id_trip,'n_points=',len(ids_point)
+ print(79*'=')
+ print('match_trip',id_trip,'n_points=',len(ids_point))
tick = time.time()
routes = []
route = None
@@ -3069,8 +3069,8 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
ids_stop = ptstops.get_ids()
coords_stop = ptstops.centroids[ids_stop][:,:2]
- print ' len(ids_stop)',len(ids_stop)
- print ' coords_stop.shape',coords_stop.shape
+ print(' len(ids_stop)',len(ids_stop))
+ print(' coords_stop.shape',coords_stop.shape)
# map stop IDs to PT link IDs with specific type
@@ -3108,7 +3108,7 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
t_point_initial = -1
t_point_final = -1
- print ' search initial stops'
+ print(' search initial stops')
ind_point = 0
for p in coords:
dists2 = np.sum((coords_stop-p)**2,1)
@@ -3146,22 +3146,22 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
dists2 = np.sum((coords_stop-coords_stop[ind_hit_initial])**2,1)
inds_hit = np.flatnonzero(dists2 < self.width_buffer_terminal_max**2)
for id_stop in ids_stop[inds_hit]:
- if map_id_fromstop_to_ids_link.has_key(id_stop):
+ if id_stop in map_id_fromstop_to_ids_link:
ids_stop_initial.append(id_stop)
else:
- print 'ABOARD: no initial stop found'
+ print('ABOARD: no initial stop found')
return [], [], 0.0, 0.0,-1.0,-1.0, -1.0, -1.0, 0.0, [], False
if ind_hit_final > -1:
dists2 = np.sum((coords_stop-coords_stop[ind_hit_final])**2,1)
inds_hit = np.flatnonzero(dists2 < self.width_buffer_terminal_max**2)
for id_stop in ids_stop[inds_hit]:
- if map_id_tostop_to_ids_link.has_key(id_stop):
+ if id_stop in map_id_tostop_to_ids_link:
ids_stop_final.append(id_stop)
else:
- print 'ABOARD: no final stop found'
+ print('ABOARD: no final stop found')
return [], [], 0.0, 0.0,-1.0,-1.0, -1.0, -1.0, 0.0, [], False
n_points_eff = ind_point_final - ind_point_initial
@@ -3170,18 +3170,18 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
#if self._logger:
# self._logger.w( '>>match_trip_birgil : n_points_eff=%d, len(ids_edge_initial)=%d,len(ids_edge_final)=%d'%(n_points_eff, len(ids_edge_initial),len(ids_edge_final)) )
- print '\n completed init:'
- print ' ids_stop_initial',ids_stop_initial
- print ' ids_stop_final',ids_stop_final
+ print('\n completed init:')
+ print(' ids_stop_initial',ids_stop_initial)
+ print(' ids_stop_final',ids_stop_final)
#print ' ind_point_initial,ind_point_final,n_points_eff',ind_point_initial,ind_point_final,n_points_eff
- print ' id_point_initial=%d,id_point_final=%d,n_points_eff=%d'%(ids_point[ind_point_initial],ids_point[ind_point_final],n_points_eff)
+ print(' id_point_initial=%d,id_point_final=%d,n_points_eff=%d'%(ids_point[ind_point_initial],ids_point[ind_point_final],n_points_eff))
if (ind_point_initial<0)|(ind_point_final<0) | (n_points_eff < self.n_points_min):
- print 'ABOARD: insufficient valid points'
+ print('ABOARD: insufficient valid points')
return [], [], 0.0, 0.0,-1.0,-1.0, -1.0, -1.0, 0.0, [], False
- print ' define initial and final pt links'
+ print(' define initial and final pt links')
ids_ptlink_initial = set()
for id_stop in ids_stop_initial:
@@ -3191,8 +3191,8 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
for id_stop in ids_stop_final:
ids_ptlink_final.update(map_id_tostop_to_ids_link[id_stop])
- print ' ids_ptlink_initial',ids_ptlink_initial
- print ' ids_ptlink_final',ids_ptlink_final
+ print(' ids_ptlink_initial',ids_ptlink_initial)
+ print(' ids_ptlink_final',ids_ptlink_final)
##---------------------------------------------------------------------
@@ -3214,8 +3214,8 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
delta_point = point-coords[ind_point-1]
phi_point = np.arctan2(delta_point[1], delta_point[0])
- print 79*'='
- print ' point ind_point',ind_point,ind_point_final,' id_point',id_point,'coords',point
+ print(79*'=')
+ print(' point ind_point',ind_point,ind_point_final,' id_point',id_point,'coords',point)
ids_edge_buffer, dists = get_closest_edge( point, n_best = self.n_edge_max,
d_max = self.width_buffer_max,
@@ -3227,10 +3227,10 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
n_hits = len(ids_edge_buffer)
- print ' n_hits',n_hits,'ids_edge_buffer',ids_edge_buffer
+ print(' n_hits',n_hits,'ids_edge_buffer',ids_edge_buffer)
if n_hits>0:
phis_delta = np.zeros(n_hits, dtype = np.float32)
- for ind, id_edge in zip(xrange(n_hits), ids_edge_buffer):
+ for ind, id_edge in zip(range(n_hits), ids_edge_buffer):
dist_point_edge, segment = get_dist_point_to_edge(point, id_edge,
is_ending=True,
@@ -3252,7 +3252,7 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
for id_stop in ids_stops_near:
t_wait_point = min(pointtimes[ind_point]-pointtimes[ind_point-1],600.0)
#print ' near id_stop',id_stop,map_id_fromstop_to_ids_link.has_key(id_stop)
- if map_id_fromstop_to_ids_link.has_key(id_stop):
+ if id_stop in map_id_fromstop_to_ids_link:
waittimes_stops[id_stop] += t_wait_point
#ptlinkhits[map_id_fromstop_to_ids_link[id_stop]] += self.weight_stop_hits/n_near
pttimes[map_id_fromstop_to_ids_link[id_stop]] -= self.weight_stop_hits*t_wait_point#/n_near
@@ -3265,10 +3265,10 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
ptlinkhits[id_ptlink] += np.sum(edgehits[ids_ptedge])
if 0: #debug
- print ' Stop waittimes'
+ print(' Stop waittimes')
for id_stop, waits in zip(ids_stop, waittimes_stops[ids_stop]):
if waits>0:
- print ' waits at id_stop %d = %.2fs'%(id_stop,waits)
+ print(' waits at id_stop %d = %.2fs'%(id_stop,waits))
# debug edgelinks
#ids_edge = edges.get_ids()
@@ -3303,16 +3303,16 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
##--------------------------------------------------------------------
## post matching analisis
- print '\n'+79*'-'
+ print('\n'+79*'-')
#print ' ids_point_edgeend',len(ids_point_edgeend),ids_point_edgeend
if len(routelist) == 0:
- print 'ABOARD: no routes found'
+ print('ABOARD: no routes found')
return [],[], 0.0, 0.0,-1.0,-1.0, -1.0, -1.0, 0.0, [], False
else:
ids_ptlink = routelist[0][1]
if len(ids_ptlink) == 0:
- print 'ABOARD: route contains no edges ids_ptlink=',ids_ptlink
+ print('ABOARD: route contains no edges ids_ptlink=',ids_ptlink)
return [],[], 0.0, 0.0,-1.0,-1.0, -1.0, -1.0, 0.0, [], False
else:
is_connected = True
@@ -3321,12 +3321,12 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
ids_edge += ptlinks.get_ids_edge(id_ptlink)
route = ids_edge
- print ' matched route: len(ids_edge)',len(ids_edge),'len(ids_ptlink)',len(ids_ptlink),'cost =%.2f'%routelist[0][0]
+ print(' matched route: len(ids_edge)',len(ids_edge),'len(ids_ptlink)',len(ids_ptlink),'cost =%.2f'%routelist[0][0])
if 1:
for id_ptlink in ids_ptlink:
ptlinks.print_link(id_ptlink, ident = 4, is_edges = False, is_link_forward = False)
- print ' ids_edge',ids_edge
+ print(' ids_edge',ids_edge)
@@ -3353,7 +3353,7 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
# check dist error
- inds_point = xrange(ind_point_initial,ind_point_final)
+ inds_point = range(ind_point_initial,ind_point_final)
n_points = len(inds_point)
@@ -3381,10 +3381,10 @@ def match_trip(self,id_trip, ids_point, ptfstar, ptstops, ptlines, busdistances
err_dist = dist_points_tot/float(n_points)
if ptlinks.ids_tostop[ids_ptlink[-1]] in ids_stop_final:
- print 'SUCCESS: target id_stop',ptlinks.ids_tostop[ids_ptlink[-1]],'reached length %.2f, gps length %.2f$'%(length_route,length_gps)
+ print('SUCCESS: target id_stop',ptlinks.ids_tostop[ids_ptlink[-1]],'reached length %.2f, gps length %.2f$'%(length_route,length_gps))
is_connected = True
else:
- print 'DISCONNECTED: last matched id_stop',ptlinks.ids_tostop[ids_ptlink[-1]],' does not reach final ids_stop',ids_stop_final
+ print('DISCONNECTED: last matched id_stop',ptlinks.ids_tostop[ids_ptlink[-1]],' does not reach final ids_stop',ids_stop_final)
is_connected = False
@@ -3407,7 +3407,7 @@ def get_colvalue(val, default = 0.0):
class VirtualpopCreator(Process):
def __init__(self, mapmatching, logger = None, **kwargs):
- print 'VirtualpopCreator.__init__'
+ print('VirtualpopCreator.__init__')
self._init_common( 'virtualpopcreator',
parent = mapmatching,
name = 'VirtualpopCreator',
@@ -3448,7 +3448,7 @@ def do(self):
class ModeSelector(Process):
def __init__(self, mapmatching, logger = None, **kwargs):
- print 'ModeSelector.__init__'
+ print('ModeSelector.__init__')
self._init_common( 'modeselector',
parent = mapmatching,
name = 'Mode Selector',
@@ -3692,7 +3692,7 @@ def filter_ids(self):
class PostMatchfilter(FilterMixin):
def __init__(self, mapmatching, logger = None, **kwargs):
- print 'PostMatchfilter.__init__'
+ print('PostMatchfilter.__init__')
self._init_common( 'postmatchfilter',
parent = mapmatching,
name = 'Post matchfilter',
@@ -3797,7 +3797,7 @@ def filter_ids(self):
ids_trip = trips.get_ids()
ids_points = trips.ids_points[ids_trip]
- print 'filter_ids',n_trips,'selected'
+ print('filter_ids',n_trips,'selected')
inds_eliminate = np.logical_or(\
trips.lengthindexes[ids_selected]self.lengthindex_max,
@@ -3805,31 +3805,31 @@ def filter_ids(self):
#np.logical_not(trips.are_match_connected[ids_selected]),
#(trips.lengths_route_matched[ids_selected]<1.0), # too many args??
)
- print ' after lengthindex remaining',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after lengthindex remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
inds_eliminate |= trips.errors_dist[ids_selected]>self.error_dist_max
- print ' after distance error remaining',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after distance error remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
if self.is_connected:
inds_eliminate |= np.logical_not(trips.are_match_connected[ids_selected])
- print ' after connected remaining',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after connected remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
if self.is_shortest:
inds_eliminate |= trips.ids_route_shortest[ids_selected] == -1
if self.is_matched:
inds_eliminate |= trips.ids_route_matched[ids_selected] == -1
- print ' after is matched remaining',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after is matched remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
inds_eliminate |= trips.lengths_route_matched[ids_selected]<1.0
- print ' after too short trips remaining:',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after too short trips remaining:',n_trips-len(np.flatnonzero(inds_eliminate)))
inds_eliminate |= trips.speeds_average[ids_selected] < self.speed_trip_min
inds_eliminate |= trips.speeds_average[ids_selected] > self.speed_trip_max
- print ' after speed check remaining',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after speed check remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
@@ -3850,7 +3850,7 @@ def filter_ids(self):
#print ' inds_eliminate',inds_eliminate
inds_eliminate |= self.filter_time(trips.timestamps[ids_selected])
- print ' after time check trips remaining:',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after time check trips remaining:',n_trips-len(np.flatnonzero(inds_eliminate)))
#print ' inds_eliminate',inds_eliminate
if self.is_loopfree:
@@ -3860,7 +3860,7 @@ def filter_ids(self):
# loop-free check
inds_eliminate[i] = len(ids_edge) != len(set(ids_edge))
i += 1
- print ' after loop test trips remaining:',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after loop test trips remaining:',n_trips-len(np.flatnonzero(inds_eliminate)))
return ids_selected[inds_eliminate]
@@ -3874,7 +3874,7 @@ def do(self):
class PersonFilter(FilterMixin):
def __init__(self, mapmatching, logger = None, **kwargs):
- print 'Personfilter.__init__'
+ print('Personfilter.__init__')
self._init_common( 'personfilter',
parent = mapmatching,
name = 'Person filter',
@@ -3979,18 +3979,18 @@ def filter_ids(self):
ids_trip = trips.get_ids()
ids_points = trips.ids_points[ids_trip]
- print 'filter_ids',n_trips,'selected'
+ print('filter_ids',n_trips,'selected')
inds_eliminate = np.zeros(len(trips.ids_vtype[ids_selected]), dtype=bool)
if self.is_select_gender:
inds_eliminate |= persons.ids_gender[trips.ids_person[ids_selected]] != self.gender
- print ' after gender check remaining',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after gender check remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
if self.is_select_age:
inds_eliminate |= np.logical_or(\
persons.years_birth[trips.ids_person[ids_selected]]<=self.birth_min,
persons.years_birth[trips.ids_person[ids_selected]]>=self.birth_max,)
- print ' after age check remaining',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after age check remaining',n_trips-len(np.flatnonzero(inds_eliminate)))
if len(self.zones)>0:
if self.is_select_od_trips:
@@ -4002,7 +4002,7 @@ def filter_ids(self):
id_initial_point = ids_point[0]
od_trips[id_trip] = is_point_in_polygon(points.coords[id_initial_point], zone_shape_origin)*is_point_in_polygon(points.coords[id_final_point], zone_shape_dest)
inds_eliminate |= np.logical_not(od_trips[ids_selected])
- print ' after od trips remaining ',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after od trips remaining ',n_trips-len(np.flatnonzero(inds_eliminate)))
if self.is_select_gen_trips:
zone_shape_origin = zones.shapes[zones.ids_sumo.get_id_from_index(self.origin_zone_name)]
@@ -4011,7 +4011,7 @@ def filter_ids(self):
id_initial_point = ids_point[0]
od_trips[id_trip] = is_point_in_polygon(points.coords[id_initial_point], zone_shape_origin)
inds_eliminate |= np.logical_not(od_trips[ids_selected])
- print ' after generated trips remaining ',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after generated trips remaining ',n_trips-len(np.flatnonzero(inds_eliminate)))
if self.is_select_attr_trips:
zone_shape_dest = zones.shapes[zones.ids_sumo.get_id_from_index(self.dest_zone_name)]
@@ -4020,7 +4020,7 @@ def filter_ids(self):
id_final_point = ids_point[-1]
od_trips[id_trip] = is_point_in_polygon(points.coords[id_final_point], zone_shape_dest)
inds_eliminate |= np.logical_not(od_trips[ids_selected])
- print ' after attracted trips remaining ',n_trips-len(np.flatnonzero(inds_eliminate))
+ print(' after attracted trips remaining ',n_trips-len(np.flatnonzero(inds_eliminate)))
return ids_selected[inds_eliminate]
@@ -4039,7 +4039,7 @@ def do(self):
class TripGeomfilter(FilterMixin):
def __init__(self, mapmatching, logger = None, **kwargs):
- print 'TripGeomfilter.__init__'
+ print('TripGeomfilter.__init__')
self._init_common( 'tripGeomfilter',
parent = mapmatching,
name = 'Geometry trip filter',
@@ -4209,7 +4209,7 @@ def filterpreview(self):
"""
Previews selected trips after filtering.
"""
- print 'TripGeomfilter.filterpreview'
+ print('TripGeomfilter.filterpreview')
trips = self.parent.trips
n_trips = len(trips)
if n_trips == 0:
@@ -4221,7 +4221,7 @@ def filterpreview(self):
return '%d/%d (currently %d/%d)'%(n_sel_after,n_trips,n_sel_current,n_trips)
def do(self):
- print 'TripGeomfilter.do'
+ print('TripGeomfilter.do')
# execute filtering
if len(self.parent.trips)>0:
self.parent.trips.are_selected[self.filter_ids(is_eliminate_points = True)] = False
@@ -4253,7 +4253,7 @@ def filter_ids(self, is_eliminate_points = True):
Returns an array of ids to be eliminated or deselected.
"""
c_cutoff = 1.0 - self.const_return_max
- print 'TripGeomfilter.filter_ids c_cutoff',c_cutoff,'is_eliminate_points',is_eliminate_points
+ print('TripGeomfilter.filter_ids c_cutoff',c_cutoff,'is_eliminate_points',is_eliminate_points)
dist_point_max = self.dist_point_max
dist_point_min = self.dist_point_min_extr
dist_point_min_inter = self.dist_point_min_inter
@@ -4263,10 +4263,10 @@ def filter_ids(self, is_eliminate_points = True):
ids_trip = trips.get_ids_selected()
ids_points = trips.ids_points[ids_trip]
speed_max = self.speed_max
- print ' n_trips',len(ids_trip)
- print ' n_points',len(ids_points)
+ print(' n_trips',len(ids_trip))
+ print(' n_points',len(ids_points))
if len(ids_points) == 0:
- print 'WARNING: no points found, no traces'
+ print('WARNING: no points found, no traces')
return True
intersects_boundaries = self.parent.get_scenario().net.intersects_boundaries
in_boundaries = self.parent.get_scenario().net.in_boundaries
@@ -4287,17 +4287,17 @@ def filter_ids(self, is_eliminate_points = True):
surplus = 0
for id_trip, ids_point in zip(ids_trip, ids_points):
- print 79*'-'
- print ' filter id_trip ',id_trip,
+ print(79*'-')
+ print(' filter id_trip ',id_trip, end=' ')
if ids_point is None:
is_eliminate = True
- print ' no points'
+ print(' no points')
elif (len(ids_point) < 2*self.num_external_points+2 and self.is_eliminate_external_points):
is_eliminate = True
- print ' not enough points, only',len(ids_point)
+ print(' not enough points, only',len(ids_point))
else:
## print 'ids_point',ids_point
@@ -4325,16 +4325,16 @@ def filter_ids(self, is_eliminate_points = True):
# this happens if the points of a trip in the workout file
# have not been imported for some reason
is_eliminate = True
- print 'it has no points'
+ print('it has no points')
elif n<2:
is_eliminate = True
- print 'less than 2 points'
+ print('less than 2 points')
elif not intersects_boundaries(get_boundary(coords)):
is_eliminate = True
- print 'do not intersect boundaries'
+ print('do not intersect boundaries')
elif np.any(times<0):
is_eliminate = True
- print 'has negative times'
+ print('has negative times')
else:
dist_max = 0.0
is_eliminate = False
@@ -4370,7 +4370,7 @@ def filter_ids(self, is_eliminate_points = True):
durations_inter = np.zeros(len(dists_to_end),dtype = np.float32)
speeds_inter = np.zeros(len(dists_to_end),dtype = np.float32)
- for i, duration_inter, speed_inter in zip(range(len(durations_inter)), durations_inter, speeds_inter):
+ for i, duration_inter, speed_inter in zip(list(range(len(durations_inter))), durations_inter, speeds_inter):
if i>0:
durations_inter[i] = times[i]-times[i-1]
@@ -4396,7 +4396,7 @@ def filter_ids(self, is_eliminate_points = True):
#print ' ids_points_outside =',np.array(ids_point, dtype = np.int32)[are_outside]
ids_point_elim.update(np.array(ids_point, dtype = np.int32)[are_outside])
- print len(ids_point_elim), 'points outside box'
+ print(len(ids_point_elim), 'points outside box')
i = 0
while (i<(n-2)):
i+=1
@@ -4411,7 +4411,7 @@ def filter_ids(self, is_eliminate_points = True):
if dists_to_start[i] < dist_point_min:
#print ' eliminate',ids_point[i], dist_check
ids_point_elim.add(ids_point[i])
- print 'point', ids_point[i], dists_to_start[i], 'meters near start'
+ print('point', ids_point[i], dists_to_start[i], 'meters near start')
@@ -4422,7 +4422,7 @@ def filter_ids(self, is_eliminate_points = True):
if dists_to_end[i] < dist_point_min:
#print ' eliminate',ids_point[i], dist_check
ids_point_elim.add(ids_point[i])
- print 'point', ids_point[i], dists_to_end[i], 'meters near end'
+ print('point', ids_point[i], dists_to_end[i], 'meters near end')
else:
#dist_check = np.sqrt( (coords[i,0]-coord_last[0])**2\
@@ -4434,7 +4434,7 @@ def filter_ids(self, is_eliminate_points = True):
dists_inter[i+1] = np.sqrt( (coords[i+1,0]-coords[i-surplus,0])**2\
+ (coords[i+1,1]-coords[i-surplus,1])**2 )
- print 'point', ids_point[i], (dists_inter[i]), 'meters near other point'
+ print('point', ids_point[i], (dists_inter[i]), 'meters near other point')
else:
surplus = 0
#else:
@@ -4460,10 +4460,10 @@ def filter_ids(self, is_eliminate_points = True):
speeds_average[id_trip] = distances_gps[id_trip]/durations_gps[id_trip]
else:
speeds_average[id_trip] = 0.0
- print 'old dist', trips.distances_gps[id_trip], 'new dist', distances_gps[id_trip]
- print 'old duration', trips.durations_gps[id_trip], 'new duration',durations_gps[id_trip]
- print 'old speed', trips.speeds_average[id_trip], 'new speed', speeds_average[id_trip]
- print 'old max speed', trips.speeds_max[id_trip], 'new max speed', max_speeds_intern[id_trip]
+ print('old dist', trips.distances_gps[id_trip], 'new dist', distances_gps[id_trip])
+ print('old duration', trips.durations_gps[id_trip], 'new duration',durations_gps[id_trip])
+ print('old speed', trips.speeds_average[id_trip], 'new speed', speeds_average[id_trip])
+ print('old max speed', trips.speeds_max[id_trip], 'new max speed', max_speeds_intern[id_trip])
else:
@@ -4477,18 +4477,18 @@ def filter_ids(self, is_eliminate_points = True):
speeds_average[id_trip] = distances_gps[id_trip]/durations_gps[id_trip]
else:
speeds_average[id_trip] = 0.0
- print 'old dist', trips.distances_gps[id_trip], 'new dist', distances_gps[id_trip]
- print 'old duration', trips.durations_gps[id_trip], 'new duration',durations_gps[id_trip]
- print 'old speed', trips.speeds_average[id_trip], 'new speed', speeds_average[id_trip]
- print 'old max speed', trips.speeds_max[id_trip], 'new max speed', max_speeds_intern[id_trip]
+ print('old dist', trips.distances_gps[id_trip], 'new dist', distances_gps[id_trip])
+ print('old duration', trips.durations_gps[id_trip], 'new duration',durations_gps[id_trip])
+ print('old speed', trips.speeds_average[id_trip], 'new speed', speeds_average[id_trip])
+ print('old max speed', trips.speeds_max[id_trip], 'new max speed', max_speeds_intern[id_trip])
elif len(np.unique(list(ids_point_elim)))>=len(ids_point2):
is_eliminate = True
- print 'all points eliminated'
+ print('all points eliminated')
# no points left
elif len(ids_point2)<2:
is_eliminate = True
- print 'no points left'
+ print('no points left')
ids_point_elim_perm += list(ids_point_elim)
@@ -4501,7 +4501,7 @@ def filter_ids(self, is_eliminate_points = True):
#print ' after elim ids_point',trips.ids_points[id_trip]
if is_eliminate:
- print 'Deselected trace due to the point analysis'
+ print('Deselected trace due to the point analysis')
if self.is_deselect_traces and not is_eliminate:
#ricalculate dist_inter and duration_inter
@@ -4529,13 +4529,13 @@ def filter_ids(self, is_eliminate_points = True):
dist_to_start_max = np.max(dists_to_start)
- print 'dist_to_start_max', dist_to_start_max
+ print('dist_to_start_max', dist_to_start_max)
## print dists_to_start, dist_to_start_max
dists_to_end = np.sqrt( (coords[:,0]-coords[-1,0])**2\
+ (coords[:,1]-coords[-1,1])**2 )
- for i, duration_inter, speed_inter in zip(range(len(durations_inter)), durations_inter, speeds_inter):
+ for i, duration_inter, speed_inter in zip(list(range(len(durations_inter))), durations_inter, speeds_inter):
if i>0:
durations_inter[i] = times[i]-times[i-1]
@@ -4550,22 +4550,22 @@ def filter_ids(self, is_eliminate_points = True):
if np.any(dists_inter>dist_point_max):
is_eliminate = True
- print 'one internal distance over the tollerance. Max value:', np.max(dists_inter), 'meters'
+ print('one internal distance over the tollerance. Max value:', np.max(dists_inter), 'meters')
if self.is_deselect_duplicate:
dist_duration = [trips.distances_gps[id_trip], trips.durations_gps[id_trip]]
if dist_duration in dists_durations and dist_duration != [0.,0.]:
n_duplicate_trips += 1
- print dist_duration
- print 'duplicated trip'
+ print(dist_duration)
+ print('duplicated trip')
is_eliminate = True
## else:
dists_durations[id_trip] = [trips.distances_gps[id_trip], trips.durations_gps[id_trip]]
if np.any(durations_inter>duration_point_max):
is_eliminate = True
- print 'one internal duration over the tollerance. Max value:', np.max(durations_inter), 'seconds'
+ print('one internal duration over the tollerance. Max value:', np.max(durations_inter), 'seconds')
n_invalid_speeds = 0
i = 0
@@ -4577,11 +4577,11 @@ def filter_ids(self, is_eliminate_points = True):
if n_invalid_speeds == self.n_overspeed_max:
is_eliminate = True
- print 'invalid internal speeds'
+ print('invalid internal speeds')
i += 1
if dists_to_start[-1] <= c_cutoff*dist_to_start_max:
is_eliminate = True
- print 'round trip: return distance over the tollerance'
+ print('round trip: return distance over the tollerance')
if len(self.zones) > 0 and not is_eliminate:
if self.is_od_select:
@@ -4592,17 +4592,17 @@ def filter_ids(self, is_eliminate_points = True):
if self.select_type == 1:
is_eliminate = not is_point_in_polygon(points.coords[id_initial_point], zone_shape_origin)
if is_eliminate == True:
- print 'deselected for the zone filter'
+ print('deselected for the zone filter')
if self.select_type == 2:
is_eliminate = not is_point_in_polygon(points.coords[id_final_point], zone_shape_dest)
if is_eliminate == True:
- print 'deselected for the zone filter'
+ print('deselected for the zone filter')
if self.select_type == 3:
is_eliminate = not is_point_in_polygon(points.coords[id_initial_point], zone_shape_origin)*is_point_in_polygon(points.coords[id_final_point], zone_shape_dest)
if is_eliminate == True:
- print 'deselected for the zone filter'
+ print('deselected for the zone filter')
if is_eliminate:
- print 'Deselected trace'
+ print('Deselected trace')
inds_elim[j] = is_eliminate
j +=1
@@ -4615,12 +4615,12 @@ def filter_ids(self, is_eliminate_points = True):
- print ' permanently eliminated %d GPS points'%(len(ids_point_elim_perm))
+ print(' permanently eliminated %d GPS points'%(len(ids_point_elim_perm)))
if self.is_analyze_points:
- print '%d Invalid GPS points'%(len(np.unique(ids_point_elim_perm)))
- print '%d Invalid GPS traces'%(np.sum(inds_elim))
+ print('%d Invalid GPS points'%(len(np.unique(ids_point_elim_perm))))
+ print('%d Invalid GPS traces'%(np.sum(inds_elim)))
if self.is_deselect_duplicate:
- print '%d Duplicated GPS traces'%(np.sum(n_duplicate_trips))
+ print('%d Duplicated GPS traces'%(np.sum(n_duplicate_trips)))
#print '+++++++++++ids_point_elim_perm',ids_point_elim_perm
#print ' eliminate points?',(len(ids_point_elim_perm)>0),is_eliminate_points,(len(ids_point_elim_perm)>0) & is_eliminate_points
@@ -4629,7 +4629,7 @@ def filter_ids(self, is_eliminate_points = True):
class MobikeImporter(FilterMixin):
def __init__(self, mapmatching, logger = None, **kwargs):
- print 'MobikeImporter.__init__',mapmatching.get_ident()
+ print('MobikeImporter.__init__',mapmatching.get_ident())
self._init_common( 'mobikeimporter',
parent = mapmatching,
name = 'Mobike Importer',
@@ -4780,7 +4780,7 @@ def validate_and_add_trip(self, bikes, trips, points, id_bici_sumo, id_trip_sumo
trips.durations_gps[id_trip] = timestamps[-1]-timestamps[0]
def do(self):
- print 'TraceImporter.do'
+ print('TraceImporter.do')
log = self.get_logger()
#ID Bicicletta;Data e ora inizio;Data e ora fine;Latitudine inizio;Longitudine inizio;Latitudine fine;Longitudine fine;Durata;Distanza
# 0 1 2 3 4 5 6 7 8
@@ -4827,7 +4827,7 @@ def do(self):
for line in f.readlines()[1:]:# first line contains header
cols = line.strip().split(sep)
- print ' i_line',i_line,'len(cols)',len(cols),n_cols
+ print(' i_line',i_line,'len(cols)',len(cols),n_cols)
if len(cols)==n_cols:
# sep_date_clock = ' ', sep_date = '-', sep_clock = ':',
@@ -4842,8 +4842,8 @@ def do(self):
)
else:
- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath)
- print ' cols =',cols
+ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath))
+ print(' cols =',cols)
i_line += 1
@@ -4858,7 +4858,7 @@ def do(self):
class StravaImporter(FilterMixin):
def __init__(self, mapmatching, logger = None, **kwargs):
- print 'StravaImporter.__init__',mapmatching.get_ident()
+ print('StravaImporter.__init__',mapmatching.get_ident())
self._init_common( 'traceimporter',
parent = mapmatching,
name = 'Strava Trace Importer',
@@ -4964,7 +4964,7 @@ def validate_trip(self, dist, duration, speed_av = -1):
def do(self):
- print 'TraceImporter.do'
+ print('TraceImporter.do')
if self.year == 2013:
self.import_points_2013()
self.import_users_2013()
@@ -4979,7 +4979,7 @@ def import_users_2013(self):
log = self.get_logger()
- print 'import users'
+ print('import users')
if (self.userinfofilepath == ''):
return
@@ -5057,17 +5057,17 @@ def import_users_2013(self):
if hasattr(self,'home_zips'):
#print ' zips',self.zips.get_value().dtype,self.zips.get_value()
if self.home_zips.get_value().dtype in [np.dtype(np.int32),np.dtype(np.int64)]:
- print 'WARNING: delete old person.home_zips'
+ print('WARNING: delete old person.home_zips')
self.delete('home_zips')
if hasattr(self,'school_zips'):
#print ' zips',self.zips.get_value().dtype,self.zips.get_value()
if self.school_zips.get_value().dtype in [np.dtype(np.int32),np.dtype(np.int64)]:
- print 'WARNING: delete old person.school_zips'
+ print('WARNING: delete old person.school_zips')
self.delete('school_zips')
if hasattr(self,'work_zips'):
#print ' zips',self.zips.get_value().dtype,self.zips.get_value()
if self.work_zips.get_value().dtype in [np.dtype(np.int32),np.dtype(np.int64)]:
- print 'WARNING: delete old person.work_zips'
+ print('WARNING: delete old person.work_zips')
self.delete('work_zips')
#if self.get_version()<0.2:
@@ -5079,7 +5079,7 @@ def import_users_2013(self):
#1 7561 35 Commute 2012-10-12 15:07:22 0 0 0 1 30316 -1 30308 3 1 2
n_cols = 15
- j_id_line, j_tripid, j_userid, j_trip_type, j_created_date, j_age, j_gender, j_income, j_ethnicity, j_homeZIP, j_schoolZip, j_workZip, j_cyclingfreq, j_rider_history, j_rider_type = range(15)
+ j_id_line, j_tripid, j_userid, j_trip_type, j_created_date, j_age, j_gender, j_income, j_ethnicity, j_homeZIP, j_schoolZip, j_workZip, j_cyclingfreq, j_rider_history, j_rider_type = list(range(15))
#dd
@@ -5129,10 +5129,10 @@ def import_users_2013(self):
else:
- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.userinfofilepath)
- print ' cols =',cols
+ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.userinfofilepath))
+ print(' cols =',cols)
if i_line%1000 == 0:
- print i_line,'/',len(lines), 'users imported'
+ print(i_line,'/',len(lines), 'users imported')
i_line += 1
@@ -5172,7 +5172,7 @@ def add_trips(self, trips, points, distances_gps, durations_gps, speeds_av, ids_
ids_vtype[i] = self.get_vtype_for_mode(id_mode)
i+=1
# create new trip
- print 'add trips'
+ print('add trips')
ids_trip = trips.add_rows(ids_sumo = ids_trip_sumo,
timestamps = timestamps_trips,
ids_vtype = ids_vtype,
@@ -5180,22 +5180,22 @@ def add_trips(self, trips, points, distances_gps, durations_gps, speeds_av, ids_
distances_gps = distances_gps,
speeds_average = speeds_av,
)
- print len(ids_trip), 'trips added'
+ print(len(ids_trip), 'trips added')
i_changes = [0]
current_id_trips_points = ids_trips_points[0]
- for id_trips_points, i in zip(ids_trips_points, range(len(ids_trips_points))):
+ for id_trips_points, i in zip(ids_trips_points, list(range(len(ids_trips_points)))):
if id_trips_points != current_id_trips_points:
i_changes.append(i)
current_id_trips_points = id_trips_points
i_changes.append(len(ids_trips_points))
- print len(i_changes)-1, len(ids_trip)
- for i, id_trip in zip(range(len(i_changes)-1), ids_trip):
+ print(len(i_changes)-1, len(ids_trip))
+ for i, id_trip in zip(list(range(len(i_changes)-1)), ids_trip):
ids_trips_points[i_changes[i]:i_changes[i+1]] = id_trip*np.ones(len(ids_trips_points[i_changes[i]:i_changes[i+1]]))
- print 'add points'
+ print('add points')
## print timestamps_points, timestamps_trips
ids_point = points.add_rows(\
@@ -5206,12 +5206,12 @@ def add_trips(self, trips, points, distances_gps, durations_gps, speeds_av, ids_
altitudes = altitudes,
)
- print len(ids_point), 'points added'
- print 'add ids points'
+ print(len(ids_point), 'points added')
+ print('add ids points')
# bellamossa does provide no altitude
#points.coords[ids_point][:,:2] = coords
- for i, id_trip in zip(range(len(i_changes)-1), ids_trip):
+ for i, id_trip in zip(list(range(len(i_changes)-1)), ids_trip):
## print points.get_ids()[(points.ids_trip[points.get_ids()] == id_trip)]
trips.set_points(id_trip, ids_point[i_changes[i]:i_changes[i+1]])
#print ' timestamps',timestamps
@@ -5297,7 +5297,7 @@ def check_trip(self, trips, points, id_trip_sumo,
return is_valid, 0., 0., 0.
def import_points_2013(self):
- print 'import_points_2013'
+ print('import_points_2013')
log = self.get_logger()
#pointDBNode, pointPathId, id, timestamp, latitude, longitude, altitude,distance, heartRate,instruction,speed
#4, 61565791, 23648171762,2013-05-01 06:33:58,44.501085, 11.372906, NULL, 0, NULL, 2, NULL
@@ -5361,7 +5361,7 @@ def import_points_2013(self):
lines = f.readlines()[1:]
n_lines = len(lines)
n_trips = len(lines)
- print 'analyze', n_lines, 'points and', n_trips, 'trips'
+ print('analyze', n_lines, 'points and', n_trips, 'trips')
ids_trip_sumo = np.zeros(n_trips,dtype = 'object')
ids_mode = np.zeros(n_trips,dtype = np.int32)
@@ -5461,11 +5461,11 @@ def import_points_2013(self):
else:
- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath)
- print ' cols =',cols
+ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath))
+ print(' cols =',cols)
if i_line%500000 == 0:
- print i_line,'/',len(lines), 'points imported'
+ print(i_line,'/',len(lines), 'points imported')
i_line += 1
# register points of last trip after loop ended
@@ -5518,7 +5518,7 @@ def import_points_2013(self):
class BellamossaImporter(FilterMixin):
def __init__(self, mapmatching, logger = None, **kwargs):
- print 'BellamossaImporter.__init__',mapmatching.get_ident()
+ print('BellamossaImporter.__init__',mapmatching.get_ident())
self._init_common( 'traceimporter',
parent = mapmatching,
name = 'Bellamossa Trace Importer',
@@ -5633,7 +5633,7 @@ def validate_trip(self, dist, duration, speed_av = -1):
def do(self):
- print 'TraceImporter.do'
+ print('TraceImporter.do')
if self.year == 2017:
self.import_points_2017()
self.import_users_2017()
@@ -5647,7 +5647,7 @@ def do(self):
def import_users_2017(self):
log = self.get_logger()
- print 'import users'
+ print('import users')
if (self.tripinfofilepath == '') | (self.userinfofilepath == ''):
return
@@ -5663,7 +5663,7 @@ def import_users_2017(self):
#81511,Female,1981
#81507,Male,1983
n_cols = 3
- j_id_user, j_sex, j_year = range(3)
+ j_id_user, j_sex, j_year = list(range(3))
#exist_id_person_sumo = persons.ids_sumo.has_index
@@ -5693,10 +5693,10 @@ def import_users_2017(self):
else:
- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.userinfofilepath)
- print ' cols =',cols
+ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.userinfofilepath))
+ print(' cols =',cols)
if i_line%1000 == 0:
- print i_line,'/',len(lines), 'users imported'
+ print(i_line,'/',len(lines), 'users imported')
i_line += 1
f.close()
@@ -5704,7 +5704,7 @@ def import_users_2017(self):
## read trip-user file
n_cols = 2
- j_id_trip, j_id_user = range(2)
+ j_id_trip, j_id_user = list(range(2))
f = open(self.tripinfofilepath,'r')
if self._logger: self._logger.w('import_users_2017 import tripfile %s'%os.path.basename(self.tripinfofilepath))
sep = ','
@@ -5739,10 +5739,10 @@ def import_users_2017(self):
else:
- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.tripinfofilepath)
- print ' cols =',cols
+ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.tripinfofilepath))
+ print(' cols =',cols)
if i_line%500000 == 0:
- print i_line,'/',len(lines), 'users imported'
+ print(i_line,'/',len(lines), 'users imported')
i_line += 1
def add_trips(self, trips, points, distances_gps, durations_gps, speeds_av, ids_trip_sumo, ids_trips_points,
@@ -5758,7 +5758,7 @@ def add_trips(self, trips, points, distances_gps, durations_gps, speeds_av, ids_
ids_vtype[i] = self.get_vtype_for_mode(id_mode)
i+=1
# create new trip
- print 'add trips'
+ print('add trips')
ids_trip = trips.add_rows(ids_sumo = ids_trip_sumo,
timestamps = timestamps_trips,
ids_vtype = ids_vtype,
@@ -5766,22 +5766,22 @@ def add_trips(self, trips, points, distances_gps, durations_gps, speeds_av, ids_
distances_gps = distances_gps,
speeds_average = speeds_av,
)
- print len(ids_trip), 'trips added'
+ print(len(ids_trip), 'trips added')
i_changes = [0]
current_id_trips_points = ids_trips_points[0]
- for id_trips_points, i in zip(ids_trips_points, range(len(ids_trips_points))):
+ for id_trips_points, i in zip(ids_trips_points, list(range(len(ids_trips_points)))):
if id_trips_points != current_id_trips_points:
i_changes.append(i)
current_id_trips_points = id_trips_points
i_changes.append(len(ids_trips_points))
- print len(i_changes)-1, len(ids_trip)
- for i, id_trip in zip(range(len(i_changes)-1), ids_trip):
+ print(len(i_changes)-1, len(ids_trip))
+ for i, id_trip in zip(list(range(len(i_changes)-1)), ids_trip):
ids_trips_points[i_changes[i]:i_changes[i+1]] = id_trip*np.ones(len(ids_trips_points[i_changes[i]:i_changes[i+1]]))
- print 'add points'
+ print('add points')
## print timestamps_points, timestamps_trips
ids_point = points.add_rows(\
@@ -5792,12 +5792,12 @@ def add_trips(self, trips, points, distances_gps, durations_gps, speeds_av, ids_
altitudes = np.zeros(len(ids_trips_points), dtype = np.float32),
)
- print len(ids_point), 'points added'
- print 'add ids points'
+ print(len(ids_point), 'points added')
+ print('add ids points')
# bellamossa does provide no altitude
#points.coords[ids_point][:,:2] = coords
- for i, id_trip in zip(range(len(i_changes)-1), ids_trip):
+ for i, id_trip in zip(list(range(len(i_changes)-1)), ids_trip):
## print points.get_ids()[(points.ids_trip[points.get_ids()] == id_trip)]
trips.set_points(id_trip, ids_point[i_changes[i]:i_changes[i+1]])
#print ' timestamps',timestamps
@@ -5863,7 +5863,7 @@ def check_trip(self, trips, points, id_trip_sumo,
return is_valid, 0., 0., 0.
def import_points_2017(self):
- print 'import_points_2017'
+ print('import_points_2017')
log = self.get_logger()
# 0 1 2 3 4 5 6 7 8
# ActivityId,ActivityType,Time,Latitude,Longitude,Accuracy,Speed,IdentifiedType,IdentifiedConfidence
@@ -5926,7 +5926,7 @@ def import_points_2017(self):
lines = f.readlines()[1:]
n_lines = len(lines)
n_trips = len(lines)
- print 'analyze', n_lines, 'points and', n_trips, 'trips'
+ print('analyze', n_lines, 'points and', n_trips, 'trips')
ids_trip_sumo = np.zeros(n_trips,dtype = 'object')
ids_mode = np.zeros(n_trips,dtype = np.int32)
@@ -6025,11 +6025,11 @@ def import_points_2017(self):
else:
- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath)
- print ' cols =',cols
+ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath))
+ print(' cols =',cols)
if i_line%500000 == 0:
- print i_line,'/',len(lines), 'points imported'
+ print(i_line,'/',len(lines), 'points imported')
i_line += 1
# register points of last trip after loop ended
@@ -6078,7 +6078,7 @@ def import_points_2017(self):
class EccTracesImporter(FilterMixin):
def __init__(self, mapmatching, logger = None, **kwargs):
- print 'EccTracesImporter.__init__',mapmatching.get_ident()
+ print('EccTracesImporter.__init__',mapmatching.get_ident())
self._init_common( 'traceimporter',
parent = mapmatching,
name = 'ECC Trace Importer',
@@ -6179,7 +6179,7 @@ def validate_trip(self, dist, duration, speed_av = -1):
& (speed_av < self.speed_trip_max)
def do(self):
- print 'TraceImporter.do'
+ print('TraceImporter.do')
if self.year == 2014:
self.import_workouts_2014()
self.import_points_2014()
@@ -6202,7 +6202,7 @@ def import_workouts_2016(self):
#UserID TripID TimeStamp Start DT Distance ECC AvgSpeed TrackType Sex Year Profession Frequent User ZIP Source TypeOfBike TipeOfTrip Max Spd
#57249bcd88c537874f9fa1ae 57515edc88c537576ca3e16f 1464945480 2016-06-03T09:18:00.000Z 4.75 4.75 10.16 urban bicycle F 1999 Studente yes cy-web-gpx MyBike HomeToSchool 25.45
- j_id_user, j_id_trip, j_timestamp, j_date, j_dist, j_dist_copy, j_speed_av, j_tracktype, j_sex, j_year, j_profession, j_frequent, j_zip, j_device, j_biketype, j_purpose, j_speedmax = range(17)
+ j_id_user, j_id_trip, j_timestamp, j_date, j_dist, j_dist_copy, j_speed_av, j_tracktype, j_sex, j_year, j_profession, j_frequent, j_zip, j_device, j_biketype, j_purpose, j_speedmax = list(range(17))
n_cols = 17
null = 'NULL'
trips = self.parent.trips
@@ -6283,17 +6283,17 @@ def import_workouts_2016(self):
#print
else:
- print ' invalid trip',cols[j_id_trip]
+ print(' invalid trip',cols[j_id_trip])
else:
- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.workoutsfilepath)
- print ' cols =',cols
+ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.workoutsfilepath))
+ print(' cols =',cols)
i_line += 1
def import_points_2016(self):
- print 'import_points_2016'
+ print('import_points_2016')
# 0 1 2 3 4 5 6 7
# TripID, TimeStamp,Latitude, Longitude, Altitude, Distance, Speed, Type
# 574e98c988c5378163a3e11f,1462347278,44.52606,11.27617,78,0.027255420500625783,5,,
@@ -6385,8 +6385,8 @@ def import_points_2016(self):
else:
- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath)
- print ' cols =',cols
+ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath))
+ print(' cols =',cols)
i_line += 1
@@ -6421,7 +6421,7 @@ def import_workouts_2015(self):
#54eb068de71f393530a9a74d 54eb0737e71f394c2fa9a74d 1424692504 Mon, 23 Feb 2015 11:55:04 GMT 0 0 urban bicycle M 1987 Developer no
#54eb9374e71f39f02fa9a750 5505cb04e71f39542e25e2d4 1426442994 Sun, 15 Mar 2015 18:09:54 GMT 0 0.7 urban bicycle M 1974 Worker yes 40128
- j_id_user, j_id_trip, j_timestamp, j_date, j_dist, j_speed_av, j_tracktype, j_sex, j_year, j_profession, j_frequent, j_zip = range(12)
+ j_id_user, j_id_trip, j_timestamp, j_date, j_dist, j_speed_av, j_tracktype, j_sex, j_year, j_profession, j_frequent, j_zip = list(range(12))
n_cols = 12
null = 'NULL'
trips = self.parent.trips
@@ -6498,13 +6498,13 @@ def import_workouts_2015(self):
zip = zip,
)
else:
- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.workoutsfilepath)
+ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.workoutsfilepath))
#print ' cols =',cols
i_line += 1
def import_points_2015(self):
- print 'import_points_2015'
+ print('import_points_2015')
# 0 1 2 3 4 5 6 7 8
#TripID, TimeStamp,Date, Latitude, Longitude, Altitude, Distance, Speed, Type
#54eb0737e71f394c2fa9a74d,1424692509,"Mon, 23 Feb 2015 11:55:09 GMT",44.499096,11.361185,49.419395,0,0.000815,start
@@ -6596,7 +6596,7 @@ def import_points_2015(self):
else:
- print 'WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath)
+ print('WARNING: inconsistent number of columns (%d) in line %d, file %s'%(len(cols),i_line,self.pointsfilepath))
#print ' cols =',cols
@@ -6626,13 +6626,13 @@ def import_points_2015(self):
def import_workouts_2014(self):
- print 'import_workouts_2014'
+ print('import_workouts_2014')
# 2014 ecomondo workouts
#id pointDBNode pointPathId startTime distance duration sport calories maxSpeed altitudeMin altitudeMax metersAscent metersDescent
#329308466 7 37073516 2014-05-01 19:00:00 26 15600 1 1182.64 NULL NULL NULL NULL NULL
# 0 1 2 3 4 5 6 7 8 9 10 11 12
- j_id, j_node, j_id_trip, j_time, j_dist,j_duration = range(6)
+ j_id, j_node, j_id_trip, j_time, j_dist,j_duration = list(range(6))
j_v_max = 8
n_cols = 13
null = 'NULL'
@@ -6686,7 +6686,7 @@ def import_workouts_2014(self):
def import_points_2014(self):
- print 'import_points_2014'
+ print('import_points_2014')
# csv2014
#pointDBNode,pointPathId,id,timestamp,latitude,longitude,altitude,distance,heartRate,instruction,speed
#4,61565791,23648171762,2013-05-01 06:33:58,44.501085,11.372906,NULL,0,NULL,2,NULL
@@ -6782,7 +6782,7 @@ def import_points_2014(self):
else:
- print 'WARNING: inconsistent columns in line %d, file %s'%(i_line,os.path.basename(self.pointsfilepath))
+ print('WARNING: inconsistent columns in line %d, file %s'%(i_line,os.path.basename(self.pointsfilepath)))
i_line += 1
@@ -6808,7 +6808,7 @@ def import_points_2014(self):
def import_points_2013(self):
- print 'import_points_2013'
+ print('import_points_2013')
#pointDBNode, pointPathId, id, timestamp, latitude, longitude, altitude,distance, heartRate,instruction,speed
#4, 61565791, 23648171762,2013-05-01 06:33:58,44.501085, 11.372906, NULL, 0, NULL, 2, NULL
#0 1 2 3 4 5 6 7 8 9 10
@@ -6924,7 +6924,7 @@ def import_points_2013(self):
else:
- print 'WARNING: inconsistent columns in line %d, file %s'%(i_line,os.path.basename(self.pointsfilepath))
+ print('WARNING: inconsistent columns in line %d, file %s'%(i_line,os.path.basename(self.pointsfilepath)))
i_line += 1
@@ -6952,7 +6952,7 @@ def import_points_2013(self):
class GpxImporter(FilterMixin):
def __init__(self, mapmatching, logger = None, **kwargs):
- print 'GpxImporter.__init__',mapmatching.get_ident()
+ print('GpxImporter.__init__',mapmatching.get_ident())
self._init_common( 'gpximporter',
parent = mapmatching,
name = 'GPX Importer',
@@ -6996,7 +6996,7 @@ def do(self):
Reads endomondo gpx xml file and stores point data in traces table.
If there is no traces table, one will be initialized and returned
"""
- print 'GpxImporter.do',self.filepaths
+ print('GpxImporter.do',self.filepaths)
mapmatching = self.parent
#scenario = mapmatching.get_scenario()
logger = self.get_logger()
@@ -7015,7 +7015,7 @@ def do(self):
speed_trip_max = self.speed_trip_max,
)
for filepath in self.filepaths.split(','):
- print ' parse gpx file', filepath
+ print(' parse gpx file', filepath)
parse(filepath.strip(), parser)
ids_trips = parser.get_ids_trip()
@@ -7207,7 +7207,7 @@ def endElement(self, name):
class GtfsShapeImporter(FilterMixin):
def __init__(self, mapmatching, logger = None, **kwargs):
- print 'GtfsShapeImporter.__init__',mapmatching.get_ident()
+ print('GtfsShapeImporter.__init__',mapmatching.get_ident())
self._init_common( 'gtfsshapeimporter',
parent = mapmatching,
name = 'GTFS Importer',
@@ -7250,7 +7250,7 @@ def do(self):
Reads endomondo gpx xml file and stores point data in traces table.
If there is no traces table, one will be initialized and returned
"""
- print 'GtfsShapeImporter.do',self.gtfsdirpath
+ print('GtfsShapeImporter.do',self.gtfsdirpath)
mapmatching = self.parent
mapmatching.get_attrsman().do_not_save_attrs(['gtfsdirpath'])
@@ -7263,7 +7263,7 @@ def do(self):
net = self.parent
get_vtype_for_mode = scenario.demand.vtypes.get_vtype_for_mode#( id_mode)
id_vtype = get_vtype_for_mode(self.id_mode)
- print ' self.id_mode',self.id_mode,'id_vtype',id_vtype
+ print(' self.id_mode',self.id_mode,'id_vtype',id_vtype)
tripshapes = mapmatching.trips
points = mapmatching.points
@@ -7286,7 +7286,7 @@ def do(self):
for fileattr_raw in f.readline().split(sep):
fileattr = fileattr_raw.strip().strip(aa)
- print ' check fileattr *%s*, %d'%(fileattr,i)
+ print(' check fileattr *%s*, %d'%(fileattr,i))
if fileattr == 'shape_id':
ind_shape_id = i
@@ -7324,7 +7324,7 @@ def do(self):
id_shape = tripshapes.add_row( ids_sumo = cols[ind_shape_id].strip(aa),
ids_vtype = id_vtype)
- print ' id_shape',id_shape,tripshapes.ids_vtype[id_shape],id_vtype
+ print(' id_shape',id_shape,tripshapes.ids_vtype[id_shape],id_vtype)
lons = []
lats = []
ind_shape = ind_shape_new
@@ -7369,7 +7369,7 @@ def __init__(self, ident='gtfsstopgenerator', mapmatching=None, results = None,
self._results = Matchresults( 'matchresults',mapmatching)
else:
self._results = results
- print 'GtfsGenerator.__init__'
+ print('GtfsGenerator.__init__')
self._init_common( ident,
parent = mapmatching,
name = 'GTFS Stop Generator',
@@ -7458,7 +7458,7 @@ def __init__(self, ident='gtfsstopgenerator', mapmatching=None, results = None,
#def place_stop(self, id_stop, name_stop, lat_stop, lon_ stop, **kwargs):
def do(self):
- print 'GtfsStopGenerator.do'
+ print('GtfsStopGenerator.do')
# go through shapes.txt and match shapes with id_edges
# > shape_id -> ids_edge
# done through mapmatching
@@ -7544,7 +7544,7 @@ def do(self):
map_trip_to_shape[cols[ind_trip_id].strip().strip(aa)] = id_shape
id_service = cols[ind_service_id].strip().strip(aa)
- if not map_service_to_trips.has_key(id_service):
+ if id_service not in map_service_to_trips:
map_service_to_trips[id_service] = []
else:
map_service_to_trips[id_service].append(id_trip)
@@ -7558,11 +7558,11 @@ def do(self):
#else:
# map_service_to_route[id_service] = cols[ind_route_id].strip().strip(aa)
map_trip_to_route[id_trip] = cols[ind_route_id].strip().strip(aa)
- print ' *id_trip',id_trip,'id_service',id_service,'id_route',cols[ind_route_id].strip().strip(aa),'-> id_shape',id_shape
+ print(' *id_trip',id_trip,'id_service',id_service,'id_route',cols[ind_route_id].strip().strip(aa),'-> id_shape',id_shape)
f.close()
- print ' result: len(map_trip_to_shape)',len(map_trip_to_shape),'different shapes',len(set(map_trip_to_shape.values())),'of',len(ids_gtsshape_set)
+ print(' result: len(map_trip_to_shape)',len(map_trip_to_shape),'different shapes',len(set(map_trip_to_shape.values())),'of',len(ids_gtsshape_set))
#ids_trip = {}
#for id_shape in gpstrips.ids_sumo[gpstrips.get_ids()]:
# ids_trip[id_shape] = map_shape_to_trip[id_shape]
@@ -7589,28 +7589,28 @@ def do(self):
id_stop = cols[ind_stop_id].strip().strip(aa)
#print ' id_trip',id_trip,map_trip_to_shape.has_key(id_trip),'found stop',id_stop
- if map_trip_to_shape.has_key(id_trip):
- if not trip_stops.has_key(id_trip):
+ if id_trip in map_trip_to_shape:
+ if id_trip not in trip_stops:
trip_stops[id_trip] = []
trip_times[id_trip] = []
- print ' for id_trip',id_trip,'* found id_stop',id_stop,'at id_shape',map_trip_to_shape[id_trip]
+ print(' for id_trip',id_trip,'* found id_stop',id_stop,'at id_shape',map_trip_to_shape[id_trip])
trip_stops[id_trip].append(id_stop)
trip_times[id_trip].append(cols[ind_departure_time].strip().strip(aa))
f.close()
- print ' result: len(trip_stops)',len(trip_stops)
+ print(' result: len(trip_stops)',len(trip_stops))
# dictionary to map stop ID to shape ID that will be used
# to identify edge of stop
stop_shapes = OrderedDict()
- for id_trip, ids_stop in trip_stops.iteritems():
+ for id_trip, ids_stop in trip_stops.items():
#print ' id_trip',id_trip,'ids_stop',ids_stop
#print ' ',
for id_stop in ids_stop:
#print (map_trip_to_shape.has_key(id_trip),map_trip_to_shape.has_key(id_trip)),
# currently not all trips have shapes (unless include direction = 1)
- if (map_trip_to_shape.has_key(id_trip)):
+ if (id_trip in map_trip_to_shape):
#print '*',
ids_edges = ids_edges_shape[gpstrips.ids_route_matched[get_id_gpstrip(map_trip_to_shape[id_trip])]]
# edges of shape of new trip
@@ -7619,7 +7619,7 @@ def do(self):
else:
n_edges = 0
- if stop_shapes.has_key(id_stop):
+ if id_stop in stop_shapes:
# use new shape if shape is longer than previous shape
if n_edges > len(ids_edges_shape[gpstrips.ids_route_matched[get_id_gpstrip(stop_shapes[id_stop])]]):
stop_shapes[id_stop] = map_trip_to_shape[id_trip]
@@ -7658,7 +7658,7 @@ def do(self):
cols = line.split(sep)
id_stop = cols[ind_stop_id].strip().strip(aa)
#print ' found id_stop',id_stop,stop_shapes.has_key(id_stop)
- if stop_shapes.has_key(id_stop):
+ if id_stop in stop_shapes:
ids_stop_gtfs.append(id_stop)
lats.append(float(cols[ind_stop_lat].strip().strip(aa)))
@@ -7680,8 +7680,8 @@ def do(self):
accesslevelsmap = self.parent.get_accesslevelsmap()
#gtfsstop_to_simstop = {}
for id_stop, coord, stopname in zip(ids_stop_gtfs,coords, stopnames):
- print '\n id_stop',id_stop, coord,'id_gpstrip',get_id_gpstrip(stop_shapes[id_stop])
- print ' id_gpsroute',gpstrips.ids_route_matched[get_id_gpstrip(stop_shapes[id_stop])]
+ print('\n id_stop',id_stop, coord,'id_gpstrip',get_id_gpstrip(stop_shapes[id_stop]))
+ print(' id_gpsroute',gpstrips.ids_route_matched[get_id_gpstrip(stop_shapes[id_stop])])
ids_edge_target = ids_edges_shape[gpstrips.ids_route_matched[get_id_gpstrip(stop_shapes[id_stop])]]
#print ' ids_edge_target',ids_edge_target
@@ -7697,12 +7697,12 @@ def do(self):
ind = 0
is_hit = False
n_hits = len(ids_edge_hit)
- print ' n_hits',n_hits,'len(ids_edge_target)',len(ids_edge_target),'dists',dists
+ print(' n_hits',n_hits,'len(ids_edge_target)',len(ids_edge_target),'dists',dists)
while (not is_hit) & (ind=2):
- print ' check ped access',lanes.get_accesslevel([ids_lane[0]], id_mode_ped)
+ print(' check ped access',lanes.get_accesslevel([ids_lane[0]], id_mode_ped))
if lanes.get_accesslevel([ids_lane[0]], id_mode_ped)>-1:
- print ' check bus access',lanes.get_accesslevel([ids_lane[1]], id_mode_pt)
+ print(' check bus access',lanes.get_accesslevel([ids_lane[1]], id_mode_pt))
if lanes.get_accesslevel([ids_lane[1]], id_mode_pt)>-1:
ids_simstop_exist = ptstops.select_ids(ptstops.ids_lane.get_value() == ids_lane[1])
if len(ids_simstop_exist)>0:
- print ' there are already stops ids_simstop_exist',ids_simstop_exist
+ print(' there are already stops ids_simstop_exist',ids_simstop_exist)
d_init = np.min(ptstops.positions_from[ids_simstop_exist])
d_end = edgelength-np.max(ptstops.positions_to[ids_simstop_exist])
- print ' d_init,d_end',d_init,d_end
+ print(' d_init,d_end',d_init,d_end)
if d_init>d_end:
- print ' place stop in front of previous stops'
+ print(' place stop in front of previous stops')
pos_from = d_init - self.length_stop
pos_to = d_init
- print ' try pos_from',pos_from
+ print(' try pos_from',pos_from)
if pos_from < self.dist_edge_stop_min:
pos_from = d_init - self.length_stop_min
- print ' try with shorter stop pos_from',pos_from
+ print(' try with shorter stop pos_from',pos_from)
is_hit = pos_from > self.dist_edge_stop_min
else:
- print ' place stop in behind previous stops'
+ print(' place stop in behind previous stops')
pos_from = edgelength-d_end
pos_to = pos_from+self.length_stop
- print ' try pos_to',pos_to
+ print(' try pos_to',pos_to)
if pos_to > edgelength-self.dist_edge_stop_min:
pos_to = pos_from+self.length_stop_min
- print ' try with shorter stop pos_to',pos_to
+ print(' try with shorter stop pos_to',pos_to)
is_hit = pos_to < edgelength-self.dist_edge_stop_min
@@ -7780,35 +7780,35 @@ def place_stop(self, id_stop, stopname, id_edge, coord, edges, lanes, ptstops, i
else:
pos = edges.get_pos_from_coord(id_edge, coord)-0.5*self.dist_edge_stop_min
- print ' place stop nearest to GPS coordinate pos',pos
+ print(' place stop nearest to GPS coordinate pos',pos)
if pos < self.dist_edge_stop_min:
pos_from = self.dist_edge_stop_min
pos_to = self.dist_edge_stop_min + self.length_stop
- print ' try pos_to',pos_to
+ print(' try pos_to',pos_to)
if pos_to > edgelength-self.dist_edge_stop_min:
pos_to = self.dist_edge_stop_min + self.length_stop_min
- print ' try with shorter stop pos_to',pos_to
+ print(' try with shorter stop pos_to',pos_to)
is_hit = pos_to < edgelength-self.dist_edge_stop_min
elif pos+ self.length_stop > edgelength-self.dist_edge_stop_min:
pos_from = edgelength-self.dist_edge_stop_min- self.length_stop
pos_to = edgelength-self.dist_edge_stop_min
- print ' try pos_from',pos_from
+ print(' try pos_from',pos_from)
if pos_from < self.dist_edge_stop_min:
pos_from = edgelength-self.dist_edge_stop_min- self.length_stop_min
- print ' try with shorter stop pos_from',pos_from
+ print(' try with shorter stop pos_from',pos_from)
is_hit = pos_from > self.dist_edge_stop_min
else:
- print ' stop fits'
+ print(' stop fits')
pos_from = pos
pos_to = pos + self.length_stop
is_hit = True
if is_hit:
- print ' Add stop',id_stop,'at id_edge',id_edge,'pos_from %d'%pos_from,'pos_to %d'%pos_to,'edgelength %d'%edgelength
+ print(' Add stop',id_stop,'at id_edge',id_edge,'pos_from %d'%pos_from,'pos_to %d'%pos_to,'edgelength %d'%edgelength)
id_simstop = ptstops.make( id_stop,
id_lane = ids_lane[1],
position_from = pos_from,
@@ -7829,7 +7829,7 @@ def __init__(self, ident='gtfsservicegenerator', mapmatching=None, results = Non
self._results = Matchresults( 'matchresults',mapmatching)
else:
self._results = results
- print 'GtfsServiceGenerator.__init__'
+ print('GtfsServiceGenerator.__init__')
self._init_common( ident,
parent = mapmatching,
name = 'GTFS Service Generator',
@@ -7948,16 +7948,16 @@ def do(self):
date = cols[ind_date].strip().strip(aa)
year,month,day = (date[0:4],date[4:6],date[6:8])
id_service = cols[ind_service_id].strip().strip(aa)
- print ' id_service',id_service,'year,month,day',year,month,day,(int(year) == self.year) ,(int(month) == self.month),(int(day) == self.day),
+ print(' id_service',id_service,'year,month,day',year,month,day,(int(year) == self.year) ,(int(month) == self.month),(int(day) == self.day), end=' ')
#service_to_date [cols[ind_service_id].strip().strip(aa)] = (date[0:4],date[4:6],date[6:8])
if (int(year) == self.year) & (int(month) == self.month) &(int(day) == self.day):
- print 'valid'
+ print('valid')
ids_service_valid.append(cols[ind_service_id].strip().strip(aa))
else:
- print 'not valid'
+ print('not valid')
f.close()
@@ -7967,7 +7967,7 @@ def do(self):
else:
return self.schedule_simple(ids_service_valid)
else:
- print 'WARNING: no services found on specified date.'
+ print('WARNING: no services found on specified date.')
return True
def schedule_frequ_est(self, ids_service_valid):
@@ -8000,11 +8000,11 @@ def schedule_frequ_est(self, ids_service_valid):
ids_edges_shape = gpstrips.routes.get_value().ids_edges
if not hasattr(mapmatching,'trip_stops'):
- print 'WARNING: no stops found, please run PT stop generation first'
+ print('WARNING: no stops found, please run PT stop generation first')
return False
##
## Generate timetables for ids_trip
- ids_trip = mapmatching.trip_stops.keys()
+ ids_trip = list(mapmatching.trip_stops.keys())
time_inter_begin = self.hour_begin*3600.0
time_inter_end = self.hour_end*3600.0
@@ -8013,12 +8013,12 @@ def schedule_frequ_est(self, ids_service_valid):
# maps stop sequences to a unique service ID
# which is different from the GTFS service ID
stopsequence_to_services = {}
- for id_service, ids_trip in mapmatching.map_service_to_trips.iteritems():
+ for id_service, ids_trip in mapmatching.map_service_to_trips.items():
if id_service in ids_service_valid:
for id_trip in ids_trip:
hs,ms,ss = trip_times[id_trip][0].split(':')
- print ' examin valid id_service',id_service,'id_trip',id_trip,'t',hs,ms,ss
+ print(' examin valid id_service',id_service,'id_trip',id_trip,'t',hs,ms,ss)
hs = int(hs)
if (hs >= self.hour_begin)&(hs 0:
@@ -9649,7 +9649,7 @@ def analyze(self):
# get selected trips only
ids_trip = np.array(ids_trip_all)[trips.are_selected[ids_trip_all] ]
- print ' analyze person',id_person,'ids_trip',ids_trip
+ print(' analyze person',id_person,'ids_trip',ids_trip)
if ids_trip is not None:
n_trips = len(ids_trip)
@@ -9678,7 +9678,7 @@ def add_trip(self, id_pers_sumo, id_trip):
self.ids_trips[id_pers].append(id_trip)
def make(self, id_sumo, **kwargs):
- print 'make id_pers_sumo',id_sumo
+ print('make id_pers_sumo',id_sumo)
id_trip = kwargs.get('id_trip',-1)
if self.ids_sumo.has_index(id_sumo):
@@ -9785,7 +9785,7 @@ def clear_all(self):
def _init_attributes(self):
- print 'Mapmatching._init_attributes'
+ print('Mapmatching._init_attributes')
attrsman = self.get_attrsman()
self.points = attrsman.add( cm.ObjConf(GpsPoints('points',self)))
@@ -9911,7 +9911,7 @@ def get_distancesmap(self, is_check_lanes = False, ids_mode = None):
Returns a dictionary where key is id_mode and
value is a distance-lookup table, mapping id_edge to edge distance
"""
- print 'get_distancesmap',self._distancesmap is None
+ print('get_distancesmap',self._distancesmap is None)
if self._distancesmap is None:
@@ -9920,7 +9920,7 @@ def get_distancesmap(self, is_check_lanes = False, ids_mode = None):
vtypes = self.get_scenario().demand.vtypes
ids_vtype = self.trips.ids_vtype[self.trips.get_ids()]
ids_mode = vtypes.ids_mode[ids_vtype]
- print ' ids_mode',set(ids_mode),len(ids_mode)
+ print(' ids_mode',set(ids_mode),len(ids_mode))
self._distancesmap = {}
for id_mode in set(ids_mode):
@@ -9939,7 +9939,7 @@ def get_fstarmap(self, ids_mode = None, is_return_arrays = True, is_ignor_connec
Returns a dictionary where key is id_mode and
value is the corrisponding fstar.
"""
- print 'get_fstarmap',self._fstarmap is None
+ print('get_fstarmap',self._fstarmap is None)
if self._fstarmap is None:
@@ -9948,7 +9948,7 @@ def get_fstarmap(self, ids_mode = None, is_return_arrays = True, is_ignor_connec
vtypes = self.get_scenario().demand.vtypes
ids_vtype = self.trips.ids_vtype[self.trips.get_ids()]
ids_mode = vtypes.ids_mode[ids_vtype]
- print ' ids_mode',set(ids_mode),len(ids_mode)
+ print(' ids_mode',set(ids_mode),len(ids_mode))
self._fstarmap = {}
for id_mode in set(ids_mode):
@@ -9976,7 +9976,7 @@ def get_accesslevelsmap(self, ids_mode = None):
vtypes = self.get_scenario().demand.vtypes
ids_vtype = self.trips.ids_vtype[self.trips.get_ids()]
ids_mode = vtypes.ids_mode[ids_vtype]
- print ' ids_mode',set(ids_mode),len(ids_mode)
+ print(' ids_mode',set(ids_mode),len(ids_mode))
@@ -10021,7 +10021,7 @@ def config(self, resultobj, **kwargs):
# attention: need to check whether already set
# because setattr is set explicitely after add
if not hasattr(self, resultobj.get_ident()):
- if kwargs.has_key('groupnames'):
+ if 'groupnames' in kwargs:
kwargs['groupnames'].append('Results')
else:
kwargs['groupnames'] = ['Results']
@@ -10253,17 +10253,17 @@ def get_times_wait_est(self):
the average wait tie at node id_node is
times_wait_est[id_node]
"""
- print 'get_times_wait_est'
+ print('get_times_wait_est')
nodes = self.ids_node.get_linktab()
ids_node = nodes.get_ids()
ids_node_signif = self.get_nodes_significant()
#nodetypes = nodes.types[ids_node_signif]
map_nodetype_to_times_wait = self.get_map_nodetype_to_times_wait()
- print ' map_nodetype_to_times_wait',map_nodetype_to_times_wait
+ print(' map_nodetype_to_times_wait',map_nodetype_to_times_wait)
times_wait = np.zeros(max(ids_node)+1, dtype = np.int32)
- print ' ',np.min(nodes.types[ids_node_signif]),np.max(nodes.types[ids_node_signif])
+ print(' ',np.min(nodes.types[ids_node_signif]),np.max(nodes.types[ids_node_signif]))
times_wait[ids_node_signif] = map_nodetype_to_times_wait[nodes.types[ids_node_signif]]
@@ -10272,11 +10272,11 @@ def get_times_wait_est(self):
return times_wait
def get_map_nodetype_to_times_wait(self):
- print 'get_map_nodetype_to_times_wait'
+ print('get_map_nodetype_to_times_wait')
nodes = self.ids_node.get_linktab()
ids_res = self.get_ids()
nodetypes = nodes.types[self.ids_node[ids_res]]
- nodetypeset = nodes.types.choices.values()
+ nodetypeset = list(nodes.types.choices.values())
#map_type_to_typename = get_inversemap(nodes.types.choices)
#map_type_to_times_wait = {}
map_type_to_times_wait = np.zeros(max(nodetypeset)+1,dtype = np.float32)
@@ -10503,7 +10503,7 @@ def init_for_routes(self, routes):
# return result ids and respective edge ids
ids_edgeresmap = np.zeros(np.max(ids_edge_init)+1,dtype = np.int32)
ids_edgeresmap[ids_edge_init] = self.add_rows(n=len(ids_edge_init), ids_edge = ids_edge_init)
- print 'init_for_routes: created',len(ids_edge_init),'entries for edgeresults max(ids_edge)', np.max(ids_edge_init)
+ print('init_for_routes: created',len(ids_edge_init),'entries for edgeresults max(ids_edge)', np.max(ids_edge_init))
return ids_edgeresmap
@@ -10516,7 +10516,7 @@ def init_for_edges(self, edges):
# return result ids and respective edge ids
ids_edgeresmap = np.zeros(np.max(ids_edge_init)+1,dtype = np.int32)
ids_edgeresmap[ids_edge_init] = self.add_rows(n=len(ids_edge_init), ids_edge = ids_edge_init)
- print 'init_for_routes: created',len(ids_edge_init),'entries for edgeresults max(ids_edge)', np.max(ids_edge_init)
+ print('init_for_routes: created',len(ids_edge_init),'entries for edgeresults max(ids_edge)', np.max(ids_edge_init))
return ids_edgeresmap
def get_edgeresmap(self):
@@ -10753,7 +10753,7 @@ def init_for_connections(self, connections):
# return result ids and respective edge ids
ids_connectionresmap = np.zeros(np.max(ids_connection_init)+1,dtype = np.int32)
ids_connectionresmap[ids_connection_init] = self.add_rows(n=len(ids_connection_init), ids_connection = ids_connection_init)
- print 'init_for_routes: created',len(ids_connection_init),'entries for connectionresults max(ids_connection)', np.max(ids_connection_init)
+ print('init_for_routes: created',len(ids_connection_init),'entries for connectionresults max(ids_connection)', np.max(ids_connection_init))
return ids_connectionresmap
def get_connectionresmap(self):
@@ -11383,7 +11383,7 @@ def get_speeds_inmotion_est(self):
class Shortestrouter(Process):
def __init__(self, ident, mapmatching, logger = None, **kwargs):
- print 'Shortestrouter.__init__'
+ print('Shortestrouter.__init__')
# TODO: let this be independent, link to it or child??
@@ -11441,7 +11441,7 @@ def __init__(self, ident, mapmatching, logger = None, **kwargs):
))
def do(self):
- print 'Shortestrouter.do'
+ print('Shortestrouter.do')
# links
mapmatching = self.parent
trips = mapmatching.trips
@@ -11455,7 +11455,7 @@ def do(self):
class Fastestrouter(Process):
def __init__(self, ident, mapmatching, logger = None, matchresults = None, **kwargs):
- print 'Fastestrouter.__init__'
+ print('Fastestrouter.__init__')
# TODO: let this be independent, link to it or child??
@@ -11528,7 +11528,7 @@ def __init__(self, ident, mapmatching, logger = None, matchresults = None, **kw
def do(self):
mapmatching = self.parent
trips = mapmatching.trips
- print 'Shortestrouter.do is_use_nodeswaittimes_est',self.is_use_nodeswaittimes_est,(self.matchresults is not None)
+ print('Shortestrouter.do is_use_nodeswaittimes_est',self.is_use_nodeswaittimes_est,(self.matchresults is not None))
# links
# map_nodetype_to_times_wait = get_map_nodetype_to_times_wait
@@ -11698,7 +11698,7 @@ def _init_attributes(self):
class AlternativeRoutesanalyzer(Process):
def __init__(self, ident, mapmatching, results = None, logger = None, **kwargs):
- print 'AlternativeRoutesanalyzer.__init__'
+ print('AlternativeRoutesanalyzer.__init__')
# TODO: let this be independent, link to it or child??
@@ -11792,7 +11792,7 @@ def get_results(self):
return self._results
def do(self):
- print 'AlternativeRoutesanalyzer.do'
+ print('AlternativeRoutesanalyzer.do')
# results
results = self.get_results()
altroutesresults = results.altroutesresults
@@ -11864,10 +11864,10 @@ def do(self):
#ind = 0
if len(ids_trip)==0:
- print 'WARNING: no trips selected.'
+ print('WARNING: no trips selected.')
return True
- print ' analyzing %d trips'%len(ids_trip)
+ print(' analyzing %d trips'%len(ids_trip))
#ids_res = routesresults_matched.add_rows(n=len(ids_trip),)
@@ -11888,8 +11888,8 @@ def do(self):
routes.ids_edges[ids_route_fastest],
ids_mode,
):
- print 79*'*'
- print ' id_trip',id_trip
+ print(79*'*')
+ print(' id_trip',id_trip)
# edge weights for routing, which is mode specific
# because non accessible edges are marked with weight = -1
@@ -11925,7 +11925,7 @@ def do(self):
if id_edge_matched != id_edge_shortest:
dist = np.sum(weights[route_ol])
- print ' overlapped route len',len(route_ol),'d',dist
+ print(' overlapped route len',len(route_ol),'d',dist)
if (len(route_ol) >= self.n_edge_min) & (dist > self.dist_alt_min):
#print ' store and finish route_ol',route_ol
routesets_overlap.append([route_ol,])
@@ -11960,7 +11960,7 @@ def do(self):
# collect data of matched and shortest route section
dist_matched = np.sum(weights[route_matched_nol])
dist_shortest = np.sum(weights[route_shortest_nol])
- print ' nonoverlapped route len',len(route_shortest_nol),'dm',dist_matched,'ds',dist_shortest,'dd',dist_matched-dist_shortest
+ print(' nonoverlapped route len',len(route_shortest_nol),'dm',dist_matched,'ds',dist_shortest,'dd',dist_matched-dist_shortest)
if (len(route_matched_nol)>=self.n_edge_min)\
&(len(route_shortest_nol)>=self.n_edge_min)\
&(dist_matched > self.dist_alt_min)\
@@ -12014,7 +12014,7 @@ def do(self):
- print ' create shortest routes around overlapping routes',len(routesets_overlap)
+ print(' create shortest routes around overlapping routes',len(routesets_overlap))
for routeset_overlap, routeset_overlap_dists in zip(routesets_overlap, routesets_overlap_dists):
# routesets_overlap has initially the onlu selected route
ids_edge = routeset_overlap[0]
@@ -12048,32 +12048,32 @@ def do(self):
if 0:
- print 79*'='
+ print(79*'=')
n_overl = 0
for routeset_nonoverlap, routeset_nonoverlap_dists in zip(routesets_nonoverlap,routesets_nonoverlap_dists):
- print
+ print()
dist_min = np.min(routeset_nonoverlap_dists)
if len(routeset_nonoverlap)>0:
n_overl += 1
for ids_edge, dist in zip(routeset_nonoverlap, routeset_nonoverlap_dists):
- print ' nonoverl d=%dfm, delta=%dm'%(dist,dist-dist_min),dist#,'ids_edge',ids_edge
+ print(' nonoverl d=%dfm, delta=%dm'%(dist,dist-dist_min),dist)#,'ids_edge',ids_edge
- print ' len(routesets_nonoverlap)',len(routesets_nonoverlap),len(ids_trip_routesets_overlap),len(routesets_overlap_dists)
+ print(' len(routesets_nonoverlap)',len(routesets_nonoverlap),len(ids_trip_routesets_overlap),len(routesets_overlap_dists))
if 0:
- print 79*'='
+ print(79*'=')
n_overl = 0
for routeset_overlap, routeset_overlap_dists in zip(routesets_overlap,routesets_overlap_dists):
- print
+ print()
dist_min = np.min(routeset_overlap_dists)
if len(routeset_overlap)>0:
n_overl += 1
for ids_edge, dist in zip(routeset_overlap, routeset_overlap_dists):
- print ' overl d=%dfm, delta=%dm'%(dist,dist-dist_min),'ids_edge',ids_edge
+ print(' overl d=%dfm, delta=%dm'%(dist,dist-dist_min),'ids_edge',ids_edge)
- print ' len(routesets_overlap)',n_overl,len(ids_trip_routesets_nonoverlap),len(routesets_nonoverlap_dists)
+ print(' len(routesets_overlap)',n_overl,len(ids_trip_routesets_nonoverlap),len(routesets_nonoverlap_dists))
self._samplecount = 0
self._id_alt_last = 10**8
@@ -12083,13 +12083,13 @@ def do(self):
#print ' routesets_nonoverlap',routesets_nonoverlap
#print ' routesets_nonoverlap_dists',routesets_nonoverlap_dists
- print 79*'*'
- print ' create alternative routes database'
+ print(79*'*')
+ print(' create alternative routes database')
# do all non-overlap routes
for id_trip, routeset_nonoverlap, routeset_nonoverlap_dists, id_mode in zip(ids_trip_routesets_nonoverlap, routesets_nonoverlap,routesets_nonoverlap_dists,ids_mode_routesets_nonoverlap):
- print 79*'-'
- print ' id_trip NOL',id_trip,len(routeset_overlap)
+ print(79*'-')
+ print(' id_trip NOL',id_trip,len(routeset_overlap))
#print ' routeset_nonoverlap',routeset_nonoverlap
#print ' dists',routeset_nonoverlap_dists
if len(routeset_nonoverlap) >= 2:
@@ -12101,8 +12101,8 @@ def do(self):
# do all overlap and generated routes
for id_trip, routeset_overlap, routeset_overlap_dists, id_mode in zip(ids_trip_routesets_overlap, routesets_overlap,routesets_overlap_dists, ids_mode_routesets_overlap):
- print 79*'-'
- print ' id_trip OL',id_trip,len(routeset_overlap)
+ print(79*'-')
+ print(' id_trip OL',id_trip,len(routeset_overlap))
if len(routeset_overlap) >= 2:
# add chosen, matched and overlapping route
self.add_alternative(id_trip,np.array(routeset_overlap[0], dtype=np.int32),1, True, routeset_overlap_dists[0], id_mode)
@@ -12133,7 +12133,7 @@ def add_alternative(self,id_trip, ids_edge_all, id_alt, is_selected, dist, id_mo
#print ' ids_edge[accesses[ids_edge]==1]',ids_edge[accesses[ids_edge]==1]
#print ' edgelengths[ids_edge[accesses[ids_edge]==1]]',edgelengths[ids_edge[accesses[ids_edge]==1]]
- print 'add_alternative',id_trip,id_alt,is_selected, 'dist',dist,np.sum(edgelengths[ids_edge]),'excl',np.sum(edgelengths[ids_edge[accesses[ids_edge]==2]])
+ print('add_alternative',id_trip,id_alt,is_selected, 'dist',dist,np.sum(edgelengths[ids_edge]),'excl',np.sum(edgelengths[ids_edge[accesses[ids_edge]==2]]))
id_res = self.altroutesresults.add_row(\
ids_trip = id_trip,
counter = self._samplecount,
@@ -15122,7 +15122,7 @@ def do(self):
MA_real_vs_expected1_waiting_time = np.zeros(len(ids_person))
MA_real_vs_expected2_waiting_time = np.zeros(len(ids_person))
- for id_person, i in zip(ids_person, range(len(ids_person))):
+ for id_person, i in zip(ids_person, list(range(len(ids_person)))):
ids_tripsdatabase_pers = ids_tripsdatabase[(tripsdatabase.ids_person[ids_tripsdatabase] == id_person)]
lengths = tripsdatabase.lengths_route_matched[ids_tripsdatabase_pers]
@@ -16723,7 +16723,7 @@ def do(self):
ids_person = np.zeros(len(ids_routesresults_matched), dtype = np.int32)
ids_routesresults_shortest = np.zeros(len(ids_routesresults_matched), dtype = np.int32)
- for i, id_routesresults_matched in zip(range(len(ids_routesresults_matched)),ids_routesresults_matched):
+ for i, id_routesresults_matched in zip(list(range(len(ids_routesresults_matched))),ids_routesresults_matched):
#if self.parent.trips.ids_person[self.parent.trips.get_routes().ids_trip[routesresults_matched.ids_route[id_routesresults_matched]]] > 0:
## print id_routesresults_matched
id_route = routesresults_matched.ids_route[id_routesresults_matched]
@@ -17001,7 +17001,7 @@ def do(self):
class Routesanalyzer(Process):
def __init__(self, ident, mapmatching, results = None, logger = None, **kwargs):
- print 'Routesanalyzer.__init__'
+ print('Routesanalyzer.__init__')
# TODO: let this be independent, link to it or child??
@@ -17178,7 +17178,7 @@ def get_results(self):
def do(self):
- print 'Routesanalyzer.do'
+ print('Routesanalyzer.do')
# results
results = self.get_results()
routesresults_shortest = results.routesresults_shortest
@@ -17243,10 +17243,10 @@ def do(self):
#ind = 0
if len(ids_trip)==0:
- print 'WARNING: no trips selected.'
+ print('WARNING: no trips selected.')
return True
- print ' analyzing %d trips'%len(ids_trip)
+ print(' analyzing %d trips'%len(ids_trip))
routesresults_shortest.clear()
routesresults_matched.clear()
@@ -17320,8 +17320,8 @@ def do(self):
if 1:
- print 70*'-'
- print 'id_trip',id_trip,'Routes: id_matched',id_route_matched,'id_shortest',id_route_shortest,'id_fastest',id_route_fastest
+ print(70*'-')
+ print('id_trip',id_trip,'Routes: id_matched',id_route_matched,'id_shortest',id_route_shortest,'id_fastest',id_route_fastest)
#ids_point = trips.ids_points[id_trip]
distances = distancesmap[id_mode]
@@ -17473,7 +17473,7 @@ def do(self):
if element in possible_connections:
connections_list.append(element)
if connections_list == []:
- print 'Error: map matching process should be done without ignoring connections'
+ print('Error: map matching process should be done without ignoring connections')
break
lane_index_connections = lanes.indexes[connections.ids_fromlane[connections_list]] + lanes.indexes[connections.ids_tolane[connections_list]]
connection = connections_list[np.argmin(lane_index_connections)]
@@ -17597,7 +17597,7 @@ def do(self):
else:
## print '11'
is_adeguate = False
- print 'too few or points or edges involved'
+ print('too few or points or edges involved')
break
## #If the problem occour to the second points
## else:
@@ -17667,7 +17667,7 @@ def do(self):
#Match points to edge and connections
cumulative_dists = np.zeros(len(cumulative_dists_initial))
#Correct cumulative distances, adding a length to the connections from the backward
- for is_connection, i in zip(are_connection, range(len(cumulative_dists_initial))):
+ for is_connection, i in zip(are_connection, list(range(len(cumulative_dists_initial)))):
if is_connection == 0 and i < len(cumulative_dists_initial)-1:
if i>0:
if cumulative_dists_initial[i] - self.junctionrange > cumulative_dists_initial[i-1]:
@@ -17685,7 +17685,7 @@ def do(self):
ids_arc_point = np.zeros(len(point_positions_on_poly), dtype = np.int32)
are_connection_points = np.zeros(len(point_positions_on_poly), dtype = np.int32)
diffs = cumulative_dists-point_positions_on_poly[0]
- for diff, i in zip(diffs, range(len(diffs))):
+ for diff, i in zip(diffs, list(range(len(diffs)))):
if diff < 0:
diffs[i] = np.max(diffs)+1
ids_arc_point[0] = ids_arc[np.argmin(diffs[(diffs>0)])]
@@ -17725,7 +17725,7 @@ def do(self):
#calculate average edge speed
- for i, id_arc, is_connection in zip(range(len(ids_arc)), ids_arc, are_connection):
+ for i, id_arc, is_connection in zip(list(range(len(ids_arc))), ids_arc, are_connection):
if i>0 and i0:
delta_time = point_times[i] - point_times[i-1]
@@ -17807,7 +17807,7 @@ def do(self):
if id_arc_point != id_arc_pre:
n_wait_times_edge_at_int[lanes.ids_edge[connections.ids_fromlane[id_arc_point]]] += 1
- print 'connection', id_arc_point, 'n +1'
+ print('connection', id_arc_point, 'n +1')
n_wait_times_node[edges.ids_tonode[lanes.ids_edge[connections.ids_fromlane[id_arc_point]]]] += 1
if connections.turns_type[id_arc_point] == 'left_turn':
number_wait_route_at_left_turns += 1
@@ -17851,7 +17851,7 @@ def do(self):
if id_arc_point != id_arc_pre and last_conn > 0:
connections_waitingtimes[last_conn].append(current_waitingtime_total)
nodes_waitingtimes[edges.ids_tonode[lanes.ids_edge[connections.ids_fromlane[last_conn]]]].append(current_waitingtime_total)
- print 'ADD', 'current_waitingtime_total', current_waitingtime_total, 'id_arc_point', last_conn
+ print('ADD', 'current_waitingtime_total', current_waitingtime_total, 'id_arc_point', last_conn)
current_waitingtime_total = 0.0
if is_connection_point:
@@ -17863,7 +17863,7 @@ def do(self):
if id_arc_point != id_arc_pre:
current_waitingtime_total = 0.0
current_waitingtime_total += delta_time
- print 'current_waitingtime_total', current_waitingtime_total, 'id_arc_point', id_arc_point
+ print('current_waitingtime_total', current_waitingtime_total, 'id_arc_point', id_arc_point)
id_arc_pre = id_arc_point
@@ -17871,10 +17871,10 @@ def do(self):
if last_conn > 0:
connections_waitingtimes[last_conn].append(current_waitingtime_total)
nodes_waitingtimes[edges.ids_tonode[lanes.ids_edge[connections.ids_fromlane[last_conn]]]].append(current_waitingtime_total)
- print 'ADD', 'current_waitingtime_total', current_waitingtime_total, 'id_arc_point', last_conn
+ print('ADD', 'current_waitingtime_total', current_waitingtime_total, 'id_arc_point', last_conn)
current_waitingtime_total = 0.0
- print 'there were', len(irregular_indices), 'irregular indices'
- print 'time_wait_route', time_wait_route,'time_wait_junction_route',time_wait_junction_route, 'time_wait_tls_route', time_wait_tls_route
+ print('there were', len(irregular_indices), 'irregular indices')
+ print('time_wait_route', time_wait_route,'time_wait_junction_route',time_wait_junction_route, 'time_wait_tls_route', time_wait_tls_route)
## print 'GOOD TRACES', good_traces, 'OF',(good_traces+bad_traces) ,'/',len(ids_trip)
#Find all connection for the connection results
@@ -17971,7 +17971,7 @@ def do(self):
## plt.show()
bad_traces+=1
- print 'trip', id_trip, 'is not adeguate for the speed analysis or too few points remained after point filtering, with', len(irregular_indices), 'irregular points'
+ print('trip', id_trip, 'is not adeguate for the speed analysis or too few points remained after point filtering, with', len(irregular_indices), 'irregular points')
routesresults_matched.times_inmotion[id_res]= -1.
routesresults_matched.n_times_wait[id_res] = -1.
@@ -18001,7 +18001,7 @@ def do(self):
- print 'There were', good_traces, 'good traces and', bad_traces, 'bad traces', 'of',(good_traces+bad_traces) ,'/',len(ids_trip)
+ print('There were', good_traces, 'good traces and', bad_traces, 'bad traces', 'of',(good_traces+bad_traces) ,'/',len(ids_trip))
@@ -18109,7 +18109,7 @@ def do(self):
if element in possible_connections:
connections_list.append(element)
if connections_list == []:
- print 'Error: map matching process should be done without ignoring connections'
+ print('Error: map matching process should be done without ignoring connections')
break
lane_index_connections = lanes.indexes[connections.ids_fromlane[connections_list]] + lanes.indexes[connections.ids_tolane[connections_list]]
connection = connections_list[np.argmin(lane_index_connections)]
@@ -18146,20 +18146,20 @@ def do(self):
dist_shortest = np.sum(distances[ids_edge_shortest])
if 0:
- print '\n shortest dist ana'
+ print('\n shortest dist ana')
d_cum = 0.0
l_cum = 0.0
for id_edge in ids_edge_shortest:
d_cum += distances[id_edge]
l_cum += edges.lengths[id_edge]
- print ' id_edge_short',id_edge,'dist',distances[id_edge],'length',edges.lengths[id_edge],'c_cum',d_cum,'l_cum',l_cum
- print
+ print(' id_edge_short',id_edge,'dist',distances[id_edge],'length',edges.lengths[id_edge],'c_cum',d_cum,'l_cum',l_cum)
+ print()
d_cum = 0.0
l_cum = 0.0
for id_edge in ids_edge:
d_cum += distances[id_edge]
l_cum += edges.lengths[id_edge]
- print ' id_edge_matched',id_edge,'dist',distances[id_edge],'length',edges.lengths[id_edge],'c_cum',d_cum,'l_cum',l_cum
+ print(' id_edge_matched',id_edge,'dist',distances[id_edge],'length',edges.lengths[id_edge],'c_cum',d_cum,'l_cum',l_cum)
n_nodes_shortest = len(nodetypes_shortest)
@@ -18531,7 +18531,7 @@ def do(self):
routesresults_matched.expected_waiting_times_tot_route_matched_tls_nodes[ids_routesresults_matched] = expected_waiting_times_tot_route_matched_tls_nodes[ids_routesresults_matched]
routesresults_matched.expected_waiting_times_tot_route_matched_edges[ids_routesresults_matched] = expected_waiting_times_tot_route_matched_edges[ids_routesresults_matched]
- print ' Route analyses done.'
+ print(' Route analyses done.')
return True
def get_connectionsresults_map(self):
@@ -18565,7 +18565,7 @@ def do_overlap(self):
"""
Only overlap calculations.
"""
- print 'Routesanalyzer.do_overlap'
+ print('Routesanalyzer.do_overlap')
# results
results = self.get_results()
routesresults_shortest = results.routesresults_shortest
@@ -18618,10 +18618,10 @@ def do_overlap(self):
#ind = 0
if len(ids_trip)==0:
- print 'WARNING: no trips selected.'
+ print('WARNING: no trips selected.')
return True
- print ' analyzing %d trips'%len(ids_trip)
+ print(' analyzing %d trips'%len(ids_trip))
routesresults_shortest.clear()
#routesresults_matched.clear()
@@ -18644,8 +18644,8 @@ def do_overlap(self):
if 0:
- print 70*'-'
- print 'id_trip',id_trip,'Routes: id_matched',id_route_matched,'id_shortest',id_route_shortest,'id_fastest',id_route_fastest
+ print(70*'-')
+ print('id_trip',id_trip,'Routes: id_matched',id_route_matched,'id_shortest',id_route_shortest,'id_fastest',id_route_fastest)
#ids_point = trips.ids_points[id_trip]
distances = distancesmap[id_mode]
@@ -18710,7 +18710,7 @@ def do_overlap(self):
- print ' Route overlap analyses done.'
+ print(' Route overlap analyses done.')
return True
class PtRoutesresults(am.ArrayObjman):
@@ -18872,7 +18872,7 @@ def get_flowdiagramm(self, id_line, is_add_similar = False):
class PtRoutesanalyzer(Process):
def __init__(self, ident, mapmatching, results = None, logger = None, **kwargs):
- print 'Routesanalyzer.__init__'
+ print('Routesanalyzer.__init__')
# TODO: let this be independent, link to it or child??
@@ -18927,7 +18927,7 @@ def get_results(self):
def do(self):
- print 'Routesanalyzer.do'
+ print('Routesanalyzer.do')
# results
results = self.get_results()
ptlinesresults = results.ptlinesresults
@@ -18973,8 +18973,8 @@ def do(self):
ptlinks.lengths[ids_link],ptlinks.durations[ids_link]):
if type_link == type_transit:
- if not numbercounter_lines.has_key(id_line):
- print id_line
+ if id_line not in numbercounter_lines:
+ print(id_line)
numbercounter_lines[id_line] = 0
distancecounter_lines[id_line] = 0.0
timecounter_lines[id_line] = 0.0
@@ -18983,12 +18983,12 @@ def do(self):
distancecounter_lines[id_line] += dist_link
timecounter_lines[id_line] += duration_link
- if not numbercounter_links.has_key(id_link):
+ if id_link not in numbercounter_links:
numbercounter_links[id_link] = 0
numbercounter_links[id_link] += 1
- ids_line = numbercounter_lines.keys()
+ ids_line = list(numbercounter_lines.keys())
ids_lineres = ptlinesresults.add_rows(n=len(ids_line),ids_line = ids_line)
id_line_to_id_lineres = {}
@@ -19014,14 +19014,14 @@ def do(self):
id_line_to_id_lineres[id_line] = id_lineres
- ids_link = numbercounter_links.keys()
+ ids_link = list(numbercounter_links.keys())
for id_link, id_line, id_fromstop, id_tostop, n in zip(\
ids_link, ptlinks.ids_line[ids_link],
ptlinks.ids_fromstop[ids_link],ptlinks.ids_tostop[ids_link],
- numbercounter_links.values()):
+ list(numbercounter_links.values())):
ptrouteresults = ptlinesresults.ptroutesresults[id_line_to_id_lineres[id_line]]
- if map_stops_to_routeres[id_line].has_key((id_fromstop, id_tostop)):
+ if (id_fromstop, id_tostop) in map_stops_to_routeres[id_line]:
id_routeres = map_stops_to_routeres[id_line][(id_fromstop, id_tostop)]
## print ' Add',n,'trips to id_line %d (%s) id_fromstop %d id_tostop %d'%(id_line,ptlines.linenames[id_line],id_fromstop, id_tostop)
ptrouteresults.ids_link[id_routeres] = id_link
@@ -19036,7 +19036,7 @@ def routes_to_shapefile(mapmatching,results, filepath,
"""
Writes routes to file.
"""
- print '\n routes_to_shapefile for mapmatching'
+ print('\n routes_to_shapefile for mapmatching')
net = mapmatching.get_scenario().net
edges = net.edges
trips = mapmatching.trips
@@ -19105,7 +19105,7 @@ def edgesresults_to_shapefile(mapmatching,results, filepath,
"""
Writes edge results of mapmatching to shape-file.
"""
- print '\n edgesresults_to_shapefile for mapmatching'
+ print('\n edgesresults_to_shapefile for mapmatching')
net = mapmatching.get_scenario().net
edges = net.edges
edgesresults = results.edgesresults
@@ -19179,7 +19179,7 @@ def points_to_shapefile(mapmatching, filepath, dataname= 'pointshapedata',
#
- print 'nodes_to_shapefile',filepath
+ print('nodes_to_shapefile',filepath)
for attr in attrlist:
shapedata.add_field(attr[2:])
diff --git a/tools/contributed/sumopy/plugins/mapmatching/results_mpl.py b/tools/contributed/sumopy/plugins/mapmatching/results_mpl.py
index 3d1dbc5c805a..81ab74973523 100644
--- a/tools/contributed/sumopy/plugins/mapmatching/results_mpl.py
+++ b/tools/contributed/sumopy/plugins/mapmatching/results_mpl.py
@@ -33,7 +33,7 @@
import agilepy.lib_base.arrayman as am
from agilepy.lib_base.geometry import *
from agilepy.lib_base.processes import Process
-from mapmatching import COLOR_MATCHED_ROUTE, COLOR_SHORTEST_ROUTE, COLOR_FASTEST_ROUTE
+from .mapmatching import COLOR_MATCHED_ROUTE, COLOR_SHORTEST_ROUTE, COLOR_FASTEST_ROUTE
import time
try:
from scipy import interpolate
@@ -257,7 +257,7 @@ def show(self):
# Plot net
if self.is_net:
- print 'plot net'
+ print('plot net')
plot_net(ax, net, color_edge="gray", width_edge=2, color_node=None,
alpha=0.5)
# Plot zones
@@ -280,7 +280,7 @@ def show(self):
# select points
ids_final_point = np.zeros((len(ids_trip)), dtype=np.int32)
ids_initial_point = np.zeros((len(ids_trip)), dtype=np.int32)
- for id_trip, ids_point, i in zip(trips.get_ids(), ids_points, range(len(ids_trip))):
+ for id_trip, ids_point, i in zip(trips.get_ids(), ids_points, list(range(len(ids_trip)))):
ids_final_point[i] = ids_point[-1]
ids_initial_point[i] = ids_point[0]
if self.select_points == 1:
@@ -306,7 +306,7 @@ def show(self):
# ids_final_point.tolist()
ids_point = ids_initial_point.tolist()
ids_point.extend(ids_final_point)
- print ids_initial_point, ids_final_point, ids_points
+ print(ids_initial_point, ids_final_point, ids_points)
if self.points_type == 4:
ids_point = points.get_ids(points.are_selected.get_value() == True)
coords = points.coords[ids_point]
@@ -325,7 +325,7 @@ def show(self):
for coord, id_point in zip(coords, ids_point):
coord = np.array([coord[0], coord[1]])
id_closest_edge = net.edges.get_closest_edge(coord)
- print 'point', id_point
+ print('point', id_point)
if id_closest_edge > 0:
if self.select_points == 1:
time = (points.timestamps[id_point] - trips.timestamps[points.ids_trip[id_point]])/60.0
@@ -346,10 +346,10 @@ def show(self):
# For the isochrone plot
# if self.is_isochrone:
## times_point[id_point] = time
- print 'number of points:', np.sum(count)
+ print('number of points:', np.sum(count))
# Plot result on map
- print 'plot results on map'
+ print('plot results on map')
if self.select_points == 1:
title = 'Isochrone from the origin zone'
if self.select_points == 2:
@@ -470,7 +470,7 @@ def plot_isochrone(self, ax, ids_point, zone_shape, times_point):
else:
isochrone_shapes[i].append([(points.coords[iso_points[np.argmax(iso_points[:, 3]), 1]][0]),
(points.coords[iso_points[np.argmax(iso_points[:, 3]), 1]][1])])
- print isochrone_shapes
+ print(isochrone_shapes)
for isochrone_shape in isochrone_shapes:
verts = np.array(isochrone_shape)[:, :2].tolist()
verts.append([0, 0])
@@ -487,9 +487,9 @@ def plot_isochrone(self, ax, ids_point, zone_shape, times_point):
if len(isochrone_shape) > 4:
zone_shape = isochrone_shape
- print zone_shape
- for zone_shape_coords, i in zip(isochrone_shape, range(len(isochrone_shape))):
- print i, len(isochrone_shape)
+ print(zone_shape)
+ for zone_shape_coords, i in zip(isochrone_shape, list(range(len(isochrone_shape)))):
+ print(i, len(isochrone_shape))
if i == 0:
zone_shape[i] = ((np.array(isochrone_shape[i])+np.array(isochrone_shape[i+1])+np.array(
isochrone_shape[-1])+np.array(isochrone_shape[i+2])+np.array(isochrone_shape[-2]))/5.).tolist()
@@ -539,7 +539,7 @@ def __init__(self, results, name='Node results plotter',
])
self.plottheme = attrsman.add(cm.AttrConf('plottheme', kwargs.get('plottheme', 'times wait'),
groupnames=['options'],
- choices=self.plotthemefuncs.keys(),
+ choices=list(self.plotthemefuncs.keys()),
name='Plot theme',
info='Theme or edge attribute to be plottet.',
))
@@ -560,7 +560,7 @@ def __init__(self, results, name='Node results plotter',
attrsman.delete('is_widthvalue')
def plot_all_themes(self):
- for plottheme in self.plotthemefuncs.keys():
+ for plottheme in list(self.plotthemefuncs.keys()):
self.plottheme = plottheme
self.show()
##
@@ -599,7 +599,7 @@ def get_noderesults(self):
return self.parent.nodesresults
def show(self):
- print 'NoderesultPlotter.show', self.plottheme
+ print('NoderesultPlotter.show', self.plottheme)
# if self.axis is None:
#axis = init_plot()
self.init_figures()
@@ -607,9 +607,9 @@ def show(self):
axis = fig.add_subplot(111)
self.plotthemefuncs[self.plottheme](axis)
- print ' self.is_save', self.is_save
+ print(' self.is_save', self.is_save)
if not self.is_save:
- print ' show_plot'
+ print(' show_plot')
show_plot()
else:
figname = 'nodeplot_'+self.plottheme
@@ -628,7 +628,7 @@ def show(self):
plt.close(fig)
def plot_times_wait(self, ax):
- print 'show noderesults', len(self.parent.nodesresults)
+ print('show noderesults', len(self.parent.nodesresults))
# if self.axis is None:
nodesresults = self.parent.nodesresults
@@ -824,7 +824,7 @@ def __init__(self, results, name='Speedprofile plotter with Matplotlib',
def plot_speed_over_time(self, ax, id_trip, id_route, edges, i_min=None, i_max=None,
is_pointlabel=True, alpha=1.0):
- print 'plot_speed_over_time', id_trip, type(id_trip), self.parent.parent
+ print('plot_speed_over_time', id_trip, type(id_trip), self.parent.parent)
#mapmatching = self.parent.parent
#trips = mapmatching.trips
@@ -868,7 +868,7 @@ def plot_speed_over_time(self, ax, id_trip, id_route, edges, i_min=None, i_max=N
if is_scipy & (not (self.method_interp == 'linear')):
- print 'use scipy to interpolate'
+ print('use scipy to interpolate')
#tck = interpolate.splrep(x, y, s=0)
#xnew = np.linspace(np.min(x), np.max(x), 200)
#ynew = interpolate.splev(xnew, tck, der=0)
@@ -895,7 +895,7 @@ def plot_speed_over_time(self, ax, id_trip, id_route, edges, i_min=None, i_max=N
def plot_speed_over_way(self, ax, id_trip, id_route, edges, i_min=None, i_max=None,
is_pointlabel=True, alpha=1.0):
- print 'plot_speed_over_way', id_trip, type(id_trip), self.parent.parent
+ print('plot_speed_over_way', id_trip, type(id_trip), self.parent.parent)
#mapmatching = self.parent.parent
#trips = mapmatching.trips
@@ -933,10 +933,10 @@ def plot_speed_over_way(self, ax, id_trip, id_route, edges, i_min=None, i_max=No
y = np.array(speeds, dtype=np.float32)*3.6 # in km/h
#ax = init_plot()
- print ' ids_point', routeresults.ids_valid_point_speedana[id_routeres]
- print ' position', pointspositions
- print ' x', x
- print ' y', y
+ print(' ids_point', routeresults.ids_valid_point_speedana[id_routeres])
+ print(' position', pointspositions)
+ print(' x', x)
+ print(' y', y)
#ax.plot(locations, speeds, color = self.color_line[:2], lw = self.width_line ,alpha=0.9 ,zorder = 0)
if is_scipy & (not (self.method_interp == 'linear')):
@@ -964,7 +964,7 @@ def plot_speed_over_way(self, ax, id_trip, id_route, edges, i_min=None, i_max=No
fontsize=int(0.8*self.size_labelfont)) # baseline
def show(self):
- print 'show', self.id_trip, type(self.id_trip), self.parent.parent
+ print('show', self.id_trip, type(self.id_trip), self.parent.parent)
# if self.axis is None:
if self.id_trip >= 0:
@@ -1054,8 +1054,8 @@ def show(self):
id_arc_last = 0
i_point = 0
pointstime = routeresults.speedana_point_times[id_routeres]
- print ' len(ids_pointedge)', len(ids_pointedge)
- print ' len(pointstime)', len(pointstime)
+ print(' len(ids_pointedge)', len(ids_pointedge))
+ print(' len(pointstime)', len(pointstime))
# if len(pointstime)>1:
# t_last = pointstime[1]
@@ -1076,7 +1076,7 @@ def show(self):
routeresults.speedana_point_pos[id_routeres],
):
- print ' id_arc_point', id_arc_point, 'is_connection_point', is_connection_point, 'id_arc_last', id_arc_last, id_arc_point != id_arc_last, 'pos=%.2fm, t=%.2fs, v=%.2fkm/h' % (pos, t, v*3.6),
+ print(' id_arc_point', id_arc_point, 'is_connection_point', is_connection_point, 'id_arc_last', id_arc_last, id_arc_point != id_arc_last, 'pos=%.2fm, t=%.2fs, v=%.2fkm/h' % (pos, t, v*3.6), end=' ')
color = 'k'
if (id_arc_point != id_arc_last):
@@ -1181,7 +1181,7 @@ def show(self):
cumulative_dists = np.insert(cumulative_dists, 0, 0.).tolist()
ids_arc = routeresults.ids_arc[id_routeres]
are_connections = routeresults.is_connection[id_routeres]
- print cumulative_dists, ids_arc
+ print(cumulative_dists, ids_arc)
for cumulative_dist, id_arc, is_connection in zip(cumulative_dists, ids_arc, are_connections):
@@ -1210,7 +1210,7 @@ def show(self):
if self.is_waitslabel_tls & (time_wait_tls > 0):
label += ' $T_{\mathrm{TL}}=%ds$' % time_wait_tls
- print ' id_edge', id_arc, 'pos=%df' % cumulative_dist, 'time_wait', time_wait, 'time_wait_junc', time_wait_junc, 'time_wait_tls', time_wait_tls
+ print(' id_edge', id_arc, 'pos=%df' % cumulative_dist, 'time_wait', time_wait, 'time_wait_junc', time_wait_junc, 'time_wait_tls', time_wait_tls)
ax.text(cumulative_dist, ymin, label,
verticalalignment='bottom',
@@ -1219,7 +1219,7 @@ def show(self):
color=color,
fontsize=int(0.8*self.size_labelfont))
else:
- print 'the edge', id_arc, 'is not in the edgeresult database'
+ print('the edge', id_arc, 'is not in the edgeresult database')
else:
if connectionsresults.ids_connection.has_index(id_arc):
id_connectionres = connectionsresults.ids_connection.get_id_from_index(id_arc)
@@ -1237,7 +1237,7 @@ def show(self):
if self.is_waitslabel_tls & (time_wait_tls > 0):
label += ' $T_{\mathrm{TL}}=%ds$' % time_wait_tls
- print ' id_connection', id_arc, 'pos=%df' % x, 'time_wait', time_wait, 'time_wait_junc', time_wait_junc, 'time_wait_tls', time_wait_tls
+ print(' id_connection', id_arc, 'pos=%df' % x, 'time_wait', time_wait, 'time_wait_junc', time_wait_junc, 'time_wait_tls', time_wait_tls)
ax.text(cumulative_dist, ymin, label,
verticalalignment='bottom',
@@ -1246,7 +1246,7 @@ def show(self):
color=color,
fontsize=int(0.8*self.size_labelfont))
else:
- print 'the connection', id_arc, 'is not in the connectionresult database'
+ print('the connection', id_arc, 'is not in the connectionresult database')
ax.plot([cumulative_dist, cumulative_dist], [ymin, ymax], color=color, linestyle=linestyle)
@@ -1315,7 +1315,7 @@ def __init__(self, results, name='Plot edge results with Matplotlib',
])
self.plottheme = attrsman.add(cm.AttrConf('plottheme', kwargs.get('plottheme', 'average speeds'),
groupnames=['options'],
- choices=self.plotthemefuncs.keys(),
+ choices=list(self.plotthemefuncs.keys()),
name='Plot theme',
info='Theme or edge attribute to be plottet.',
))
@@ -1331,12 +1331,12 @@ def __init__(self, results, name='Plot edge results with Matplotlib',
self.add_save_options(**kwargs)
def plot_all_themes(self):
- for plottheme in self.plotthemefuncs.keys():
+ for plottheme in list(self.plotthemefuncs.keys()):
self.plottheme = plottheme
self.show()
def show(self):
- print 'EdgeresultPlotter.show', self.plottheme
+ print('EdgeresultPlotter.show', self.plottheme)
# if self.axis is None:
#axis = init_plot()
self.init_figures()
@@ -1344,9 +1344,9 @@ def show(self):
axis = fig.add_subplot(111)
self.plotthemefuncs[self.plottheme](axis)
- print ' self.is_save', self.is_save
+ print(' self.is_save', self.is_save)
if not self.is_save:
- print ' show_plot'
+ print(' show_plot')
show_plot()
else:
figname = 'edgeplot_'+self.plottheme
@@ -1373,7 +1373,7 @@ def plot_average_slopes(self, ax):
ids_edge = edges.get_ids()
#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
average_slopes = edges.average_slopes
- print ids_edge, average_slopes[ids_edge]
+ print(ids_edge, average_slopes[ids_edge])
self.plot_results_on_map(ax,
values=average_slopes[ids_edge],
ids_edge=ids_edge,
@@ -1387,7 +1387,7 @@ def plot_positive_climbs(self, ax):
ids_edge = edges.get_ids()
#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
positive_climbs = edges.positive_climbs
- print ids_edge, positive_climbs[ids_edge]
+ print(ids_edge, positive_climbs[ids_edge])
self.plot_results_on_map(ax,
values=positive_climbs[ids_edge],
ids_edge=ids_edge,
@@ -1401,7 +1401,7 @@ def plot_negative_climbs(self, ax):
ids_edge = edges.get_ids()
#resultattrconf = getattr(self.parent.edgesresults, self.edgeattrname)
negative_climbs = edges.negative_climbs
- print ids_edge, negative_climbs[ids_edge]
+ print(ids_edge, negative_climbs[ids_edge])
self.plot_results_on_map(ax,
values=negative_climbs[ids_edge],
ids_edge=ids_edge,
@@ -1459,7 +1459,7 @@ def plot_numbers_tot_matched(self, ax):
def plot_speeds_average(self, ax):
edgesresults = self.parent.edgesresults
- print 'plot_speeds_average'
+ print('plot_speeds_average')
#ids_result = edgesresults.get_ids()
ids_result = edgesresults.select_ids(
@@ -1562,7 +1562,7 @@ def __init__(self, results, name='Plot connection results with Matplotlib',
])
self.plottheme = attrsman.add(cm.AttrConf('plottheme', kwargs.get('plottheme', 'times wait'),
groupnames=['options'],
- choices=self.plotthemefuncs.keys(),
+ choices=list(self.plotthemefuncs.keys()),
name='Plot theme',
info='Theme or edge attribute to be plottet.',
))
@@ -1578,12 +1578,12 @@ def __init__(self, results, name='Plot connection results with Matplotlib',
self.add_save_options(**kwargs)
def plot_all_themes(self):
- for plottheme in self.plotthemefuncs.keys():
+ for plottheme in list(self.plotthemefuncs.keys()):
self.plottheme = plottheme
self.show()
def show(self):
- print 'connectionresultPlotter.show', self.plottheme
+ print('connectionresultPlotter.show', self.plottheme)
# if self.axis is None:
#axis = init_plot()
self.init_figures()
@@ -1591,9 +1591,9 @@ def show(self):
axis = fig.add_subplot(111)
self.plotthemefuncs[self.plottheme](axis)
- print ' self.is_save', self.is_save
+ print(' self.is_save', self.is_save)
if not self.is_save:
- print ' show_plot'
+ print(' show_plot')
show_plot()
else:
figname = 'connectionplot_'+self.plottheme
@@ -1694,12 +1694,12 @@ def __init__(self, results, name='Plot edge of alternative routes with Matplotli
# configure fixed options as privat (non visible for gui)
attrsman = self.get_attrsman()
- for attrname in kwargs_fixed.keys():
+ for attrname in list(kwargs_fixed.keys()):
attrconf = attrsman.get_config(attrname)
attrconf.add_groupnames(['_private'])
def show(self):
- print 'AlternativeRoutesPlotter.show'
+ print('AlternativeRoutesPlotter.show')
# if self.axis is None:
#axis = init_plot()
title = 'Route alternatives'
@@ -1772,7 +1772,7 @@ def show(self):
is_colorbar=False,
)
else:
- print 'WARNING in AlternativeRoutesPlotter.show ids_edge=', ids_edge_all, 'of id_trip', id_trip
+ print('WARNING in AlternativeRoutesPlotter.show ids_edge=', ids_edge_all, 'of id_trip', id_trip)
if self.is_show_title:
axis.set_title(title, fontsize=self.size_titlefont)
@@ -1787,9 +1787,9 @@ def show(self):
axis.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
## save or show
- print ' self.is_save', self.is_save
+ print(' self.is_save', self.is_save)
if not self.is_save:
- print ' show_plot'
+ print(' show_plot')
show_plot()
else:
self.save_fig('altroutesplot')
@@ -1804,7 +1804,7 @@ def __init__(self, results, name='Plot route results with Matplotlib',
self._init_common('routeresultplotter', parent=results, name=name,
info=info, logger=logger)
- print 'Resultplotter.__init__', results, self.parent
+ print('Resultplotter.__init__', results, self.parent)
attrsman = self.get_attrsman()
mapmatching = self.parent.parent
@@ -2158,20 +2158,20 @@ def show(self):
show_plot()
def plot_bike_availability_ffbss(self):
- print 'plot_bike_availability_ffbss'
+ print('plot_bike_availability_ffbss')
# Print the number of bikes simultaneously used every 24h/n_bins hours by selecting traces of a particular day
fig = self.create_figure()
mapmatching = self.parent.parent
trips = mapmatching.trips
ids_trip = trips.get_ids()[(trips.are_selected[trips.get_ids()] == True)]
dep_arr_times = np.zeros((len(ids_trip), 2))
- for i, id_trip in zip(range(len(ids_trip)), ids_trip):
+ for i, id_trip in zip(list(range(len(ids_trip))), ids_trip):
t = time.localtime(trips.timestamps[id_trip])
dep_arr_times[i, 0] = t.tm_hour + t.tm_min/60.0 + t.tm_sec/3600.0
dep_arr_times[i, 1] = dep_arr_times[i, 0] + trips.durations_gps[id_trip]/3600.0
self.n_bins
## dep_arr_times = np.sort(dep_arr_times.sort, axis = 0)
- print dep_arr_times[:1000]
+ print(dep_arr_times[:1000])
ax = fig.add_subplot(111)
x_min = min(dep_arr_times[:, 0])
x_max = max(dep_arr_times[:, 0])
@@ -2179,10 +2179,10 @@ def plot_bike_availability_ffbss(self):
bike_usage = np.zeros(self.n_bins)
for id_trip, dep_arr_time in zip(ids_trip, dep_arr_times):
- for bin, i in zip(bins, range(self.n_bins)):
+ for bin, i in zip(bins, list(range(self.n_bins))):
if dep_arr_time[0] < bin and dep_arr_time[1] > bin:
bike_usage[i-1] += 1
- print bike_usage
+ print(bike_usage)
bincenters = plt.plot(bins, bike_usage, color=self.color_matched,
label='Bike usage distribution of GPS Mobike traces')
ax.legend(loc='best', shadow=True, fontsize=self.size_labelfont)
@@ -2197,7 +2197,7 @@ def plot_bike_availability_ffbss(self):
self.save_fig('bike_usage')
def plot_bike_availability_ffbss_zone(self):
- print 'plot_bike_availability_ffbss_zone'
+ print('plot_bike_availability_ffbss_zone')
# Plot the difference between attracted and generated trips froma zone in a day every 24h/n_bins hours
fig = self.create_figure()
mapmatching = self.parent.parent
@@ -2217,7 +2217,7 @@ def plot_bike_availability_ffbss_zone(self):
for id_trip, ids_point in zip(ids_trip, ids_points):
id_initial_point = ids_point[0]
id_final_point = ids_point[-1]
- print id_trip
+ print(id_trip)
starting_time = np.int(points.timestamps[id_initial_point] % 86400/86400.*np.float(n_bins))
arriving_time = np.int(points.timestamps[id_final_point] % 86400/86400.*np.float(n_bins))
@@ -2271,7 +2271,7 @@ def plot_bike_availability_ffbss_zone(self):
self.save_fig('bike_availability')
def analyze_bike_availability_ffbss_zones(self):
- print 'analyze_bike_availability_ffbss_zones'
+ print('analyze_bike_availability_ffbss_zones')
# Save a .txt file with generated trips and attracted trips every 24h/n_bins hours for each zone with selected trips
fig = self.create_figure()
mapmatching = self.parent.parent
@@ -2290,7 +2290,7 @@ def analyze_bike_availability_ffbss_zones(self):
for id_trip, ids_point in zip(ids_trip, ids_points):
id_initial_point = ids_point[0]
id_final_point = ids_point[-1]
- print id_trip
+ print(id_trip)
starting_time = np.int(points.timestamps[id_initial_point] % 86400/86400.*np.float(n_bins))
arriving_time = np.int(points.timestamps[id_final_point] % 86400/86400.*np.float(n_bins))
i = 0
@@ -2408,13 +2408,13 @@ def analyze_bike_availability_ffbss_zones(self):
self.save_fig('bike_availability')
def plot_deptimedistrib(self):
- print 'plot_deptimedistrib'
+ print('plot_deptimedistrib')
fig = self.create_figure()
mapmatching = self.parent.parent
trips = mapmatching.trips
ids_trip = trips.get_ids()
hour_departure = np.zeros(len(ids_trip))
- for i, id_trip in zip(range(len(ids_trip)), ids_trip):
+ for i, id_trip in zip(list(range(len(ids_trip))), ids_trip):
t = time.localtime(trips.timestamps[id_trip])
hour_departure[i] = t.tm_hour + t.tm_min/60.0 + t.tm_sec/3600.0
# print hour_departure[:1000]
@@ -2451,7 +2451,7 @@ def plot_deptimedistrib(self):
self.save_fig('plot_deptimedistrib')
def plot_tldensity(self):
- print 'plot_tldensity'
+ print('plot_tldensity')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -2488,7 +2488,7 @@ def plot_tldensity(self):
self.save_fig('routeana_tldensity')
def plot_nodesdensity(self):
- print 'plot_nodesdensity'
+ print('plot_nodesdensity')
fig = self.create_figure()
results = self.parent
@@ -2526,7 +2526,7 @@ def plot_nodesdensity(self):
self.save_fig('routeana_nodesdensity')
def plot_prioritychangedensity(self):
- print 'plot_prioritychangedensity'
+ print('plot_prioritychangedensity')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -2563,7 +2563,7 @@ def plot_prioritychangedensity(self):
self.save_fig('routeana_nodesdensity')
def plot_lowpriorityshare(self):
- print 'plot_lowpriorityshare'
+ print('plot_lowpriorityshare')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -2600,7 +2600,7 @@ def plot_lowpriorityshare(self):
self.save_fig('routeana_lowpriorityshare')
def plot_exclusiveshare(self):
- print 'plot_exclusiveshare'
+ print('plot_exclusiveshare')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -2637,7 +2637,7 @@ def plot_exclusiveshare(self):
self.save_fig('routeana_exclusiveshare')
def plot_mixshare(self):
- print 'plot_mixshare'
+ print('plot_mixshare')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -2675,7 +2675,7 @@ def plot_mixshare(self):
self.save_fig('routeana_mixshare')
def plot_lengthdistrib_by_class(self):
- print 'plot_lengthdistrib_by_class'
+ print('plot_lengthdistrib_by_class')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -2700,7 +2700,7 @@ def plot_lengthdistrib_by_class(self):
stds_shortest = np.zeros(n_class, dtype=np.float32)
xticklabels = []
ratiolabels = []
- for dist_lower, dist_upper, i in zip(dists_class[:-1], dists_class[1:], range(n_class)):
+ for dist_lower, dist_upper, i in zip(dists_class[:-1], dists_class[1:], list(range(n_class))):
xticklabels.append('%d - %d' % (float(dist_lower)/1000, float(dist_upper)/1000))
inds = np.logical_and(dists_match > dist_lower, dists_match < dist_upper)
means_match[i] = np.mean(dists_match[inds])
@@ -2716,11 +2716,11 @@ def plot_lengthdistrib_by_class(self):
ratiolabel = '%d%%' % (means_shortest[i]/means_match[i]*100)
ratiolabels.append(ratiolabel)
- print ' dists_class_center', dists_class_center
- print ' means_match', means_match
- print ' stds_match', stds_match
- print ' means_shortest', means_shortest
- print ' stds_shortest', stds_shortest
+ print(' dists_class_center', dists_class_center)
+ print(' means_match', means_match)
+ print(' stds_match', stds_match)
+ print(' means_shortest', means_shortest)
+ print(' stds_shortest', stds_shortest)
x = np.arange(n_class, dtype=np.float32) # the x locations for the groups
width = 0.35 # the width of the bars
@@ -2779,7 +2779,7 @@ def plot_lengthdistrib(self):
time. routesresults_matched.distances.get_value() > 0,
# routesresults_matched.distances.get_value()<20000)
))
- print 'plot_lengthdistrib', len(ids_valid)
+ print('plot_lengthdistrib', len(ids_valid))
# print ' ids_valid',ids_valid
if len(ids_valid) == 0:
return False
@@ -2808,7 +2808,7 @@ def plot_lengthdistrib(self):
return True
def plot_timedistrib(self):
- print 'plot_timedistrib'
+ print('plot_timedistrib')
fig = self.create_figure()
results = self.parent
mapmatching = results.parent
@@ -2856,7 +2856,7 @@ def plot_timedistrib(self):
return True
def plot_lengthprob(self):
- print 'plot_lengthprob'
+ print('plot_lengthprob')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -2901,7 +2901,7 @@ def plot_lengthprob(self):
self.save_fig('routeana_lengthprob')
def plot_lengthoverlap(self):
- print 'plot_lengthoverlap'
+ print('plot_lengthoverlap')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -2933,10 +2933,10 @@ def plot_lengthoverlap(self):
self.save_fig('routeana_lengthoverlap')
def plot_lengthoverlap_fastest(self):
- print 'plot_lengthoverlap_fastest'
+ print('plot_lengthoverlap_fastest')
fig = self.create_figure()
results = self.parent
- print 'dir(results)', dir(results)
+ print('dir(results)', dir(results))
routesresults_fastest = results.routesresults_fastest
routesresults_matched = results.routesresults_matched
edgesresults = results.edgesresults
@@ -2966,7 +2966,7 @@ def plot_lengthoverlap_fastest(self):
self.save_fig('routeana_lengthoverlap_fastest')
def plot_lengthratio(self):
- print 'plot_lengthratio'
+ print('plot_lengthratio')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -3002,7 +3002,7 @@ def plot_lengthratio(self):
# non-overlap
def plot_lengthratio_nonoverlap(self):
- print 'plot_lengthratio_nonoverlap'
+ print('plot_lengthratio_nonoverlap')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -3041,7 +3041,7 @@ def plot_lengthratio_nonoverlap(self):
self.save_fig('routeana_lengthratio_nonoverlap')
def plot_tldensity_nonoverlap(self):
- print 'plot_tldensity_nonoverlap'
+ print('plot_tldensity_nonoverlap')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -3080,7 +3080,7 @@ def plot_tldensity_nonoverlap(self):
self.save_fig('routeana_tldensity_nonoverlap')
def plot_nodesdensity_nonoverlap(self):
- print 'plot_nodesdensity_nonoverlap'
+ print('plot_nodesdensity_nonoverlap')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -3119,7 +3119,7 @@ def plot_nodesdensity_nonoverlap(self):
self.save_fig('routeana_nodesdensity_nonoverlap')
def plot_prioritychangedensity_nonoverlap(self):
- print 'plot_prioritychangedensity_nonoverlap'
+ print('plot_prioritychangedensity_nonoverlap')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -3159,7 +3159,7 @@ def plot_prioritychangedensity_nonoverlap(self):
self.save_fig('routeana_nodesdensity_nonoverlap')
def plot_lowpriorityshare_nonoverlap(self):
- print 'plot_lowpriorityshare_nonoverlap'
+ print('plot_lowpriorityshare_nonoverlap')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -3199,7 +3199,7 @@ def plot_lowpriorityshare_nonoverlap(self):
self.save_fig('routeana_lowpriorityshare_nonoverlap')
def plot_exclusiveshare_nonoverlap(self):
- print 'plot_exclusiveshare_nonoverlap'
+ print('plot_exclusiveshare_nonoverlap')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -3239,7 +3239,7 @@ def plot_exclusiveshare_nonoverlap(self):
self.save_fig('routeana_exclusiveshare_nonoverlap')
def plot_mixshare_nonoverlap(self):
- print 'plot_mixshare_nonoverlap'
+ print('plot_mixshare_nonoverlap')
fig = self.create_figure()
results = self.parent
routesresults_shortest = results.routesresults_shortest
@@ -3295,7 +3295,7 @@ def __init__(self, results, name='PT flowdiagram',
self._init_common('ptrouteresultplotter', parent=results, name=name,
info=info, logger=logger)
- print 'PtFlowdigramPlotter.__init__', results, self.parent
+ print('PtFlowdigramPlotter.__init__', results, self.parent)
attrsman = self.get_attrsman()
self.id_line = attrsman.add(cm.AttrConf('id_line', kwargs.get('id_line', -1),
@@ -3369,7 +3369,7 @@ def __init__(self, results, name='PT flowdiagram',
self.add_save_options(**kwargs)
def show(self):
- print 'show'
+ print('show')
# if self.axis is None:
self.init_figures()
plt.rc('lines', linewidth=self.width_line)
@@ -3392,7 +3392,7 @@ def show(self):
ptlinks = ptlines.get_ptlinks()
if not self.id_line in ptlines:
- print 'WARNING: line with ID', self.id_line, 'not found.'
+ print('WARNING: line with ID', self.id_line, 'not found.')
return False
#id_line = ptlines.linenames.get_id_from_index(self.linename)
@@ -3404,7 +3404,7 @@ def show(self):
self.id_line, is_add_similar=self.is_add_similar)
n_stops = len(ids_stoptuple_line)
- ax.bar(xrange(n_stops), tripnumbers_line,
+ ax.bar(range(n_stops), tripnumbers_line,
width=1.0, bottom=0, align='edge',
color=self.color_fill,
#linecolor = self.color_outline,
@@ -3414,7 +3414,7 @@ def show(self):
for id_fromstop, id_tostop in ids_stoptuple_line:
stopnames.append(ptstops.stopnames_human[id_fromstop])
# print ' stopnames',stopnames
- ax.set_xticks(xrange(n_stops))
+ ax.set_xticks(range(n_stops))
ax.set_xticklabels(stopnames)
#ax.legend(loc='best',shadow=True, fontsize=self.size_labelfont)
diff --git a/tools/contributed/sumopy/plugins/mapmatching/wxgui.py b/tools/contributed/sumopy/plugins/mapmatching/wxgui.py
index a4329e52205e..32fa2fb95114 100644
--- a/tools/contributed/sumopy/plugins/mapmatching/wxgui.py
+++ b/tools/contributed/sumopy/plugins/mapmatching/wxgui.py
@@ -28,15 +28,15 @@
from coremodules.network import routing
from coremodules.demand import demand
-import mapmatching
+from . import mapmatching
#import results_mpl as results_mpl
try:
- import results_mpl as results_mpl
+ from . import results_mpl as results_mpl
is_mpl = True # we have matplotlib support
except:
- print "WARNING: python matplotlib package not installed, no matplotlib plots."
+ print("WARNING: python matplotlib package not installed, no matplotlib plots.")
is_mpl = False
@@ -284,7 +284,7 @@ def refresh_widgets(self):
and reset widgets. For exampe enable/disable widgets
dependent on the availability of data.
"""
- print 'MapmatchingWxGui.refresh_widgets'
+ print('MapmatchingWxGui.refresh_widgets')
scenario = self.get_scenario()
is_refresh = False
if self._scenario != scenario:
@@ -303,7 +303,7 @@ def refresh_widgets(self):
if is_refresh | self._is_needs_refresh:
self._is_needs_refresh = False
- print ' is_refresh', is_refresh, self._is_needs_refresh
+ print(' is_refresh', is_refresh, self._is_needs_refresh)
neteditor = self.get_neteditor()
#canvas = self.get_canvas()
drawing = self.get_drawing() # canvas.get_drawing()
@@ -947,7 +947,7 @@ def on_edgesresults_to_shapefile(self, event=None):
"""
Export edge results to shape file.
"""
- print 'on_nodes_to_shapefile'
+ print('on_nodes_to_shapefile')
scenario = self._mapmatching.get_scenario()
dirpath = scenario.get_workdirpath()
#defaultFile = scenario.get_rootfilename()+'.edgeres.shp'
@@ -971,7 +971,7 @@ def on_points_to_shapefile(self, event=None):
"""
Export GPS points to shapefile.
"""
- print 'on_points_to_shapefile'
+ print('on_points_to_shapefile')
scenario = self._mapmatching.get_scenario()
dirpath = scenario.get_workdirpath()
defaultFile = scenario.get_rootfilename()+'.points.shp'
@@ -1707,7 +1707,7 @@ def on_gtfsstopgenerate(self, event=None):
self._mainframe.refresh_moduleguis()
self._is_needs_refresh = True
self.refresh_widgets()
- print ' set browser to', self.get_scenario().net.ptstops
+ print(' set browser to', self.get_scenario().net.ptstops)
self._mainframe.browse_obj(self.get_scenario().net.ptstops)
def on_gtfsservicegenerate(self, event=None):
@@ -1738,7 +1738,7 @@ def on_gtfsservicegenerate(self, event=None):
# apply current widget values to scenario instance
dlg.apply()
dlg.Destroy()
- print ' set browser to', self.get_scenario().demand.ptlines
+ print(' set browser to', self.get_scenario().demand.ptlines)
self._mainframe.browse_obj(self.get_scenario().demand.ptlines)
# self._mainframe.refresh_moduleguis()
#self._is_needs_refresh = True
diff --git a/tools/contributed/sumopy/plugins/prt/__init__.py b/tools/contributed/sumopy/plugins/prt/__init__.py
index cab987aa8f9c..02fdf630fcec 100644
--- a/tools/contributed/sumopy/plugins/prt/__init__.py
+++ b/tools/contributed/sumopy/plugins/prt/__init__.py
@@ -18,12 +18,12 @@
__version__ = "0.0"
-print 'init', __name__
+print('init', __name__)
def get_wxgui():
# try:
- from wxgui import WxGui
+ from .wxgui import WxGui
return WxGui(__name__)
# except:
# return None
diff --git a/tools/contributed/sumopy/plugins/prt/prt.py b/tools/contributed/sumopy/plugins/prt/prt.py
index 371d91d2883f..d32858e04190 100644
--- a/tools/contributed/sumopy/plugins/prt/prt.py
+++ b/tools/contributed/sumopy/plugins/prt/prt.py
@@ -72,7 +72,7 @@ def get_entered_vehs(ids_veh_sumo_current, ids_veh_sumo_before):
ids_veh_entered_sumo = np.array(list(ids_veh_sumo_current.difference(ids_veh_sumo_before)), dtype=np.object)
n_entered = len(ids_veh_entered_sumo)
positions = np.zeros(n_entered, dtype=np.float32)
- for i, id_veh_sumo in zip(xrange(n_entered), ids_veh_entered_sumo):
+ for i, id_veh_sumo in zip(range(n_entered), ids_veh_entered_sumo):
positions[i] = traci.vehicle.getLanePosition(id_veh_sumo)
return list(ids_veh_entered_sumo[positions.argsort()])[::-1]
@@ -148,7 +148,7 @@ def _init_constants(self):
])
def make(self, id_detectoredge=None, **kwargs):
- print 'make', kwargs
+ print('make', kwargs)
# print ' ids_shuntedge',kwargs.get('ids_shuntedge',None),type(kwargs.get('ids_shuntedge',None)[0])
id_comp = self.add_row(ids_shuntedges=kwargs.get('ids_shuntedge', None),
ids_detectoredge=id_detectoredge
@@ -158,13 +158,13 @@ def make(self, id_detectoredge=None, **kwargs):
return id_comp
def update(self, id_comp):
- print 'update id_comp', id_comp
+ print('update id_comp', id_comp)
edges = self.get_scenario().net.edges
self.ids_detectoredge[id_comp] = edges.get_incoming(self.ids_shuntedges[id_comp][0])[0]
def update_all(self):
- print 'update_all'
+ print('update_all')
for id_comp in self.get_ids():
self.update(id_comp)
@@ -172,7 +172,7 @@ def get_scenario(self):
return self.parent.get_scenario()
def prepare_sim(self, process):
- print 'Compressors.prepare_sim'
+ print('Compressors.prepare_sim')
net = self.get_scenario().net
nodes = net.nodes
edges = net.edges
@@ -227,7 +227,7 @@ def prepare_sim(self, process):
queues_alloc = n_shunts*[None]
capacities = n_shunts*[None]
- for i, length_edge in zip(range(n_shunts), edges.lengths[ids_shuntedge]):
+ for i, length_edge in zip(list(range(n_shunts)), edges.lengths[ids_shuntedge]):
capacities[i] = max(2, int((length_edge-30.0)/(self.length_veh+0.5)))
queues[i] = []
queues_alloc[i] = []
@@ -248,8 +248,8 @@ def prepare_sim(self, process):
def process_step(self, process):
simtime = process.simtime
- print 79*'_'
- print 'Compressors.process_step at', simtime
+ print(79*'_')
+ print('Compressors.process_step at', simtime)
net = self.get_scenario().net
edges = net.edges
vehicles = self.parent.prtvehicles
@@ -284,11 +284,11 @@ def process_step(self, process):
id_detectedge_sumo, ids_veh_detect_sumo)
if 0:
- print ' id_detectedge_sumo', id_detectedge_sumo
- print ' ids_veh_detect_sumo', ids_veh_detect_sumo
- print ' ids_veh_new_sumo', ids_veh_new_sumo
- print ' ids_veh_entered_sumo=', ids_veh_entered_sumo
- print ' ids_veh_left_sumo=', ids_veh_left_sumo
+ print(' id_detectedge_sumo', id_detectedge_sumo)
+ print(' ids_veh_detect_sumo', ids_veh_detect_sumo)
+ print(' ids_veh_new_sumo', ids_veh_new_sumo)
+ print(' ids_veh_entered_sumo=', ids_veh_entered_sumo)
+ print(' ids_veh_left_sumo=', ids_veh_left_sumo)
if len(ids_veh_entered_sumo) > 0:
@@ -339,7 +339,7 @@ def process_step(self, process):
# print ' no queue with target or specific queue is full, search for a new queue'
is_found_queue = False
- for ind_queue, queue in zip(range(1, n_queues), queues[1:]):
+ for ind_queue, queue in zip(list(range(1, n_queues)), queues[1:]):
if len(queue) == 0:
is_found_queue = True
break
@@ -384,14 +384,14 @@ def process_step(self, process):
capacity, id_edge_sumo_target,\
id_shuntedge_sumo, releasetime_queue\
in zip(
- range(n_queues), queues, queues_alloc,
+ list(range(n_queues)), queues, queues_alloc,
capacities, ids_edge_sumo_target,
edges.ids_sumo[ids_shuntedge], releasetime_queues):
if 0:
- print ' OOOO shunt %s --> target %s' % (id_shuntedge_sumo, id_edge_sumo_target)
- print ' simtime-releasetime_queue', simtime-releasetime_queue
- print ' queue', queue, id(queue)
- print ' queue_alloc', queue_alloc
+ print(' OOOO shunt %s --> target %s' % (id_shuntedge_sumo, id_edge_sumo_target))
+ print(' simtime-releasetime_queue', simtime-releasetime_queue)
+ print(' queue', queue, id(queue))
+ print(' queue_alloc', queue_alloc)
# check if allocated arrived
ids_veh_arrived = []
@@ -472,7 +472,7 @@ def _init_constants(self):
])
def prepare_sim(self, process):
- print 'Decompressors.prepare_sim'
+ print('Decompressors.prepare_sim')
net = self.get_scenario().net
nodes = net.nodes
edges = net.edges
@@ -528,7 +528,7 @@ def prepare_sim(self, process):
queues_alloc = n_shunts*[None]
capacities = n_shunts*[None]
ids_targetedges_sumo = n_shunts*[None]
- for i, length_edge in zip(range(n_shunts), edges.lengths[ids_shuntedge]):
+ for i, length_edge in zip(list(range(n_shunts)), edges.lengths[ids_shuntedge]):
capacities[i] = int((length_edge-25.0)/(self.length_veh+0.5))
queues[i] = []
queues_alloc[i] = []
@@ -551,8 +551,8 @@ def prepare_sim(self, process):
def process_step(self, process):
simtime = process.simtime
- print 79*'_'
- print 'Deompressors.process_step at', simtime
+ print(79*'_')
+ print('Deompressors.process_step at', simtime)
net = self.get_scenario().net
edges = net.edges
vehicles = self.parent.prtvehicles
@@ -586,11 +586,11 @@ def process_step(self, process):
ids_veh_sumo = set(traci.edge.getLastStepVehicleIDs(id_detectedge_sumo))
if 0:
- print ' id_detectedge_sumo', id_detectedge_sumo
- print ' ids_veh_detect_sumo', ids_veh_detect_sumo, ids_veh_detect_sumo != ids_veh_sumo
- print ' ids_veh_sumo=', ids_veh_sumo
+ print(' id_detectedge_sumo', id_detectedge_sumo)
+ print(' ids_veh_detect_sumo', ids_veh_detect_sumo, ids_veh_detect_sumo != ids_veh_sumo)
+ print(' ids_veh_sumo=', ids_veh_sumo)
ids_veh_sumo_raw = traci.edge.getLastStepVehicleIDs(id_detectedge_sumo)
- print ' ids_veh_sumo_raw=', ids_veh_sumo_raw
+ print(' ids_veh_sumo_raw=', ids_veh_sumo_raw)
if ids_veh_detect_sumo != ids_veh_sumo:
# there are new vehicles
@@ -601,12 +601,12 @@ def process_step(self, process):
ids_veh_entered = vehicles.get_ids_from_ids_sumo(ids_veh_entered_sumo)
if 0:
- print ' ids_veh_entered', ids_veh_entered, type(ids_veh_entered)
+ print(' ids_veh_entered', ids_veh_entered, type(ids_veh_entered))
# print ' poss',poss
- print ' ids_veh_entered_sumo', ids_veh_entered_sumo
- print ' ids_leader', vehicles.ids_leader[ids_veh_entered]
- print ' ids_follower', vehicles.ids_follower[ids_veh_entered]
- print ' lengths_plat', vehicles.lengths_plat[ids_veh_entered]
+ print(' ids_veh_entered_sumo', ids_veh_entered_sumo)
+ print(' ids_leader', vehicles.ids_leader[ids_veh_entered])
+ print(' ids_follower', vehicles.ids_follower[ids_veh_entered])
+ print(' lengths_plat', vehicles.lengths_plat[ids_veh_entered])
for id_veh_entered, id_veh_entered_sumo, id_leader, length_plat\
in zip(ids_veh_entered, ids_veh_entered_sumo,
@@ -624,7 +624,7 @@ def process_step(self, process):
is_found_queue = False
costs = np.zeros(n_queues, dtype=np.float32)
- for ind_queue, queue, is_avail, capa in zip(range(n_queues), queues, are_queue_avail, capacities):
+ for ind_queue, queue, is_avail, capa in zip(list(range(n_queues)), queues, are_queue_avail, capacities):
dl = (capa - len(queue)) * self.length_veh - 2*length_plat
# print ' ceck queue %d with capa %d, len = %d, dl=%d'%(ind_queue,capa,len(queue),dl)
@@ -658,7 +658,7 @@ def process_step(self, process):
# shunt it to the same edge as its leader
id_targetedge_sumo = traci.vehicle.getRoute(id_veh_entered_sumo)[-1]
id_platoonleader = vehicles.get_platoonleader(id_leader)
- for ind_queue, queue, capa_queue, in zip(range(n_queues), queues, capacities):
+ for ind_queue, queue, capa_queue, in zip(list(range(n_queues)), queues, capacities):
if id_platoonleader in queue:
# print ' found id_platoonleader prt.%d of prt.%d at queue %d'%(id_platoonleader,id_veh_entered,ind_queue)
self._alloc_queue_follower(
@@ -689,16 +689,16 @@ def process_step(self, process):
ids_targetedge_sumo, capacity,\
id_shuntedge_sumo, releasetime_queue\
in zip(
- range(n_queues), queues, queues_alloc,
+ list(range(n_queues)), queues, queues_alloc,
ids_targetedges_sumo, capacities,
edges.ids_sumo[ids_shuntedge], releasetime_queues):
if 0:
- print ' QQQQQQQQQQQ shunt %s ' % (id_shuntedge_sumo)
- print ' simtime-releasetime_queue', simtime-releasetime_queue, (simtime - releasetime_queue > self.time_accumulation_max.get_value()), (simtime - self.releasetimes[id_comp] > 10)
- print ' queue', queue, id(queue)
- print ' ids_targetedge_sumo', ids_targetedge_sumo
- print ' queue_alloc', queue_alloc
- print ' releasetime_queue', releasetime_queue, simtime - releasetime_queue, simtime - releasetime_queue > self.time_accumulation_max.get_value()
+ print(' QQQQQQQQQQQ shunt %s ' % (id_shuntedge_sumo))
+ print(' simtime-releasetime_queue', simtime-releasetime_queue, (simtime - releasetime_queue > self.time_accumulation_max.get_value()), (simtime - self.releasetimes[id_comp] > 10))
+ print(' queue', queue, id(queue))
+ print(' ids_targetedge_sumo', ids_targetedge_sumo)
+ print(' queue_alloc', queue_alloc)
+ print(' releasetime_queue', releasetime_queue, simtime - releasetime_queue, simtime - releasetime_queue > self.time_accumulation_max.get_value())
# here we could also test timeout conditions
if (simtime - self.releasetimes[id_comp] > self.time_release_min.get_value()) & (simtime - releasetime_queue > self.time_accumulation_max.get_value()):
# if (simtime - self.releasetimes[id_comp]> self.time_release_min.get_value()):
@@ -726,7 +726,7 @@ def process_step(self, process):
if len_queue > ind_pl+1:
- for i, id_veh in zip(range(ind_pl+1, len_queue), queue[ind_pl+1:]):
+ for i, id_veh in zip(list(range(ind_pl+1, len_queue)), queue[ind_pl+1:]):
# print ' check prt.%d with leader prt.%d'%(id_veh,vehicles.ids_leader[id_veh])
if vehicles.ids_leader[id_veh] != -1:
# print ' real lead prt.%d qlead prt.%d | plat lead prt.%d plat qlead prt.%d '%(vehicles.ids_leader[id_veh],queue[i-1],vehicles.get_platoonleader(id_veh),id_veh_arrived)
@@ -926,7 +926,7 @@ def make_from_net(self):
"""
Make merge node database from network.
"""
- print 'Mergenodes.make_from_net'
+ print('Mergenodes.make_from_net')
self.clear()
id_prtmode = self.parent.id_prtmode
@@ -947,9 +947,9 @@ def make_from_net(self):
ids = compressors.get_ids()
for id_unit, ids_edge in zip(ids, compressors.ids_shuntedges[ids]):
# put in all shunts except for the bypass
- print ' bypass of compressor', id_unit, '=', ids_edge[0]
+ print(' bypass of compressor', id_unit, '=', ids_edge[0])
ids_mainlinedges.add(ids_edge[0])
- print ' update ids_shuntedges with compressors', ids_edge[1:]
+ print(' update ids_shuntedges with compressors', ids_edge[1:])
ids_shuntedges.update(ids_edge[1:])
# collect decompressornodes, wich will not become entry merges
@@ -957,12 +957,12 @@ def make_from_net(self):
ids_node_decompressorout = []
for id_unit, ids_edge in zip(ids, decompressors.ids_shuntedges[ids]):
# put in all shunts except for the bypass
- print ' bypass of decompressor', id_unit, '=', ids_edge[0], 'id_tonode', edges.ids_tonode[ids_edge[0]]
+ print(' bypass of decompressor', id_unit, '=', ids_edge[0], 'id_tonode', edges.ids_tonode[ids_edge[0]])
ids_mainlinedges.add(ids_edge[0])
ids_node_decompressorout.append(edges.ids_tonode[ids_edge[0]])
- print ' update ids_shuntedges with decompressors', ids_edge[1:]
+ print(' update ids_shuntedges with decompressors', ids_edge[1:])
ids_shuntedges.update(ids_edge[1:])
- print ' ids_node_decompressorout', ids_node_decompressorout
+ print(' ids_node_decompressorout', ids_node_decompressorout)
ids_node_compressorout = edges.ids_tonode[list(ids_mainlinedges)]
ids_mainlinefromnodes = edges.ids_fromnode[list(ids_mainlinedges)]
@@ -972,7 +972,7 @@ def make_from_net(self):
# print ' update ids_shuntedges with mainline incoming',edges.get_incoming(id_edge)
# ids_shuntedges.update(edges.get_incoming(id_edge))
- print ' ids_shuntedges', ids_shuntedges
+ print(' ids_shuntedges', ids_shuntedges)
#ids_ptstop = ptstops.get_ids()
#id_mode_prt = self.parent.id_prtmode
@@ -982,7 +982,7 @@ def make_from_net(self):
#edgelengths = net.edges.lengths
ids_node = nodes.get_ids()
- print ' ids_node', ids_node
+ print(' ids_node', ids_node)
for id_node, ids_edge_from, ids_edge_to, id_type in zip(
ids_node,
nodes.ids_incoming[ids_node],
@@ -993,14 +993,14 @@ def make_from_net(self):
if True:
#
- print 60*'-'
- print ' check node', id_node, nodes.ids_sumo[id_node], id_type, id_zippertype == id_type
+ print(60*'-')
+ print(' check node', id_node, nodes.ids_sumo[id_node], id_type, id_zippertype == id_type)
# id merge to be created, for debugging
id_merge = -1
if (ids_edge_from is None):
- print ' WARNING: isolate node: ids_edge_from,ids_edge_to', ids_edge_from, ids_edge_to
+ print(' WARNING: isolate node: ids_edge_from,ids_edge_to', ids_edge_from, ids_edge_to)
pass
elif (len(ids_edge_from) == 2) & (len(ids_edge_to) == 1):
@@ -1011,28 +1011,28 @@ def make_from_net(self):
# check accesslevels
id_edge1, id_edge2 = ids_edge_from
ids_lane1, ids_lane2 = edges.ids_lanes[ids_edge_from]
- print ' id_edge1', id_edge1, 'ids_lane1', ids_lane1, self.is_prt_only(ids_lane1, lanes)
- print ' id_edge2', id_edge2, 'ids_lane2', ids_lane2, self.is_prt_only(ids_lane2, lanes)
+ print(' id_edge1', id_edge1, 'ids_lane1', ids_lane1, self.is_prt_only(ids_lane1, lanes))
+ print(' id_edge2', id_edge2, 'ids_lane2', ids_lane2, self.is_prt_only(ids_lane2, lanes))
if self.is_prt_only(ids_lane1, lanes) & self.is_prt_only(ids_lane2, lanes):
- print ' +PRT merge with 2 PRT lines entering'
+ print(' +PRT merge with 2 PRT lines entering')
if id_type != id_zippertype:
- print 'WARNING: PRT network node %d %s is NOT in zipper mode!' % (id_node, nodes.ids_sumo[id_node])
+ print('WARNING: PRT network node %d %s is NOT in zipper mode!' % (id_node, nodes.ids_sumo[id_node]))
if not ids_shuntedges.isdisjoint(ids_edge_from):
- print ' one incoming edge is a shunt edge. Detect last shunt node.'
+ print(' one incoming edge is a shunt edge. Detect last shunt node.')
# TODO: this should be a function of the compressor class
id_tonode_out = edges.ids_tonode[ids_edge_to[0]]
if id_tonode_out in ids_node_compressorout:
- print ' output node of compressor => station merge node with output node', id_tonode_out
+ print(' output node of compressor => station merge node with output node', id_tonode_out)
# model this node as a platform end node of a station
id_merge = self.add_row(ids_node=id_node,
ids_nodes_out=[id_tonode_out],
are_station=True,
)
else:
- print ' compressor internal node'
+ print(' compressor internal node')
pass
# elif not ids_mainlinedges.isdisjoint(ids_edge_from):
@@ -1046,7 +1046,7 @@ def make_from_net(self):
# )
else:
- print ' regular merge'
+ print(' regular merge')
id_node_up1, dist1 = self.search_upstream_merge(id_edge1, edges, lanes, id_prtmode)
id_node_up2, dist2 = self.search_upstream_merge(id_edge2, edges, lanes, id_prtmode)
@@ -1068,7 +1068,7 @@ def make_from_net(self):
#al_in = lanes.get_accesslevel(edges.ids_lanes[id_edge_from], id_prtmode)
#is_prt_in = lanes.ids_modes_allow[edges.ids_lanes[id_edge_from]] == id_prtmode
is_prt_in = self.is_prt_only(ids_lane_in, lanes)
- print ' one in, 2 out => diverge node, access is_prt_in', is_prt_in, 'is_platform_in', self.is_platform(ids_lane_in, lanes)
+ print(' one in, 2 out => diverge node, access is_prt_in', is_prt_in, 'is_platform_in', self.is_platform(ids_lane_in, lanes))
# if id_edge_from in ids_detectoredges:
# print ' fromnode is a detectoredge of a compressor'
@@ -1083,7 +1083,7 @@ def make_from_net(self):
# check if node is outgoing node at a station
if 0: # no longer considered
if is_prt_in & (id_node in ids_mainlinefromnodes):
- print ' Diverge node in front of a compressor/decompressorr.'
+ print(' Diverge node in front of a compressor/decompressorr.')
id_node_up, dist = self.search_upstream_merge(id_edge_from, edges, lanes, id_prtmode)
id_edge1, id_edge2 = ids_edge_to
@@ -1102,19 +1102,19 @@ def make_from_net(self):
)
if self.is_platform(ids_lane_in, lanes):
- print ' mixed access level of incoming edge, check for platform exit node'
+ print(' mixed access level of incoming edge, check for platform exit node')
id_edge1, id_edge2 = ids_edge_to
ids_lane1, ids_lane2 = edges.ids_lanes[ids_edge_to]
# here we could also decide on the number of lanes
# but this may not be robust in the future
- print ' out id_edge1', id_edge1, 'ids_lane1', ids_lane1, 'is_prt_only', self.is_prt_only(ids_lane1, lanes)
- print ' out id_edge2', id_edge2, 'ids_lane2', ids_lane2, 'is_prt_only', self.is_prt_only(ids_lane2, lanes)
+ print(' out id_edge1', id_edge1, 'ids_lane1', ids_lane1, 'is_prt_only', self.is_prt_only(ids_lane1, lanes))
+ print(' out id_edge2', id_edge2, 'ids_lane2', ids_lane2, 'is_prt_only', self.is_prt_only(ids_lane2, lanes))
# if self.is_prt_only(ids_lane1, lanes) & self.is_prt_only(ids_lane2, lanes):
if self.is_prt_only(ids_lane2, lanes):
- print ' Ped exit on outedge 1'
+ print(' Ped exit on outedge 1')
#id_node_up, dist = self.search_upstream_merge(id_edge_from, edges, lanes, id_prtmode)
ids_node_out = self.search_downstream_merges(
id_edge2, edges, lanes, id_prtmode, ids_sinkedge=ids_shuntedges)
@@ -1126,7 +1126,7 @@ def make_from_net(self):
)
elif self.is_prt_only(ids_lane1, lanes):
- print ' Ped exit on outedge 2'
+ print(' Ped exit on outedge 2')
#id_node_up, dist = self.search_upstream_merge(id_edge_from, edges, lanes, id_prtmode)
ids_node_out = self.search_downstream_merges(
id_edge1, edges, lanes, id_prtmode, ids_sinkedge=ids_shuntedges)
@@ -1148,16 +1148,16 @@ def make_from_net(self):
id_node_in1 = self.ids_node_in1[id_merge]
id_node_in2 = self.ids_node_in2[id_merge]
- print ' check entry of id_merge', id_merge, 'id_node', self.ids_node[id_merge], ' no decomp', self.ids_node[id_merge] not in ids_node_decompressorout
+ print(' check entry of id_merge', id_merge, 'id_node', self.ids_node[id_merge], ' no decomp', self.ids_node[id_merge] not in ids_node_decompressorout)
if (id_node_in1 > -1) & (id_node_in2 > -1)\
& (self.ids_node[id_merge] not in ids_node_decompressorout):
- print ' id_node_in1', self.ids_node_in1[id_merge], nodes.ids_sumo[self.ids_node_in1[id_merge]], self.ids_node.has_index(self.ids_node_in1[id_merge])
- print ' id_node_in2', self.ids_node_in2[id_merge], nodes.ids_sumo[self.ids_node_in2[id_merge]], self.ids_node.has_index(self.ids_node_in2[id_merge])
+ print(' id_node_in1', self.ids_node_in1[id_merge], nodes.ids_sumo[self.ids_node_in1[id_merge]], self.ids_node.has_index(self.ids_node_in1[id_merge]))
+ print(' id_node_in2', self.ids_node_in2[id_merge], nodes.ids_sumo[self.ids_node_in2[id_merge]], self.ids_node.has_index(self.ids_node_in2[id_merge]))
if 1:
id_merge_in1 = self.ids_node.get_id_from_index(self.ids_node_in1[id_merge])
id_merge_in2 = self.ids_node.get_id_from_index(self.ids_node_in2[id_merge])
- print ' station check id_merge', id_merge, 'id_merge_in1', id_merge_in1, 'station', self.are_station[id_merge_in1], 'id_merge_in2', id_merge_in2, 'station', self.are_station[id_merge_in2]
+ print(' station check id_merge', id_merge, 'id_merge_in1', id_merge_in1, 'station', self.are_station[id_merge_in1], 'id_merge_in2', id_merge_in2, 'station', self.are_station[id_merge_in2])
if self.are_station[id_merge_in2]:
self.are_entry[id_merge] = True
@@ -1183,7 +1183,7 @@ def get_scenario(self):
return self.parent.get_scenario()
def prepare_sim(self, process):
- print 'Mergenodes.prepare_sim'
+ print('Mergenodes.prepare_sim')
net = self.get_scenario().net
nodes = net.nodes
edges = net.edges
@@ -1274,8 +1274,8 @@ def prepare_sim(self, process):
def process_step(self, process):
simtime = process.simtime
- print 79*'_'
- print 'Mergenodes.process_step at', simtime
+ print(79*'_')
+ print('Mergenodes.process_step at', simtime)
net = self.get_scenario().net
vehicles = self.parent.prtvehicles
ids = self.get_ids()
@@ -1287,8 +1287,8 @@ def process_step(self, process):
self.ids_vehs_out_sumo[ids],
self.are_entry[ids],
):
- print ' '+60*'.'
- print ' process id_merge', id_merge, ',id_node', id_node, net.nodes.ids_sumo[id_node]
+ print(' '+60*'.')
+ print(' process id_merge', id_merge, ',id_node', id_node, net.nodes.ids_sumo[id_node])
####
debug = 0 # id_merge in [3,4]
@@ -1297,14 +1297,14 @@ def process_step(self, process):
###
if debug > 0:
- print ' ids_vehs_merged_sumo', self.ids_vehs_merged_sumo[id_merge]
+ print(' ids_vehs_merged_sumo', self.ids_vehs_merged_sumo[id_merge])
# check for new vehicle arrivals/departures
ids_veh_sumo = set(traci.edge.getLastStepVehicleIDs(id_edge_out))
if debug:
- print ' ids_veh_sumo_prev=', ids_veh_out_sumo
- print ' ids_veh_sumo=', ids_veh_sumo
+ print(' ids_veh_sumo_prev=', ids_veh_out_sumo)
+ print(' ids_veh_sumo=', ids_veh_sumo)
if ids_veh_out_sumo != ids_veh_sumo:
@@ -1315,7 +1315,7 @@ def process_step(self, process):
ids_veh_entered = vehicles.get_ids_from_ids_sumo(ids_veh_entered_sumo)
#ids_veh_left = vehicles.get_ids_from_ids_sumo(list(ids_veh_sumo_prev.difference(ids_veh_sumo)))
if debug > 0:
- print ' ids_veh_entered', ids_veh_entered, type(ids_veh_entered)
+ print(' ids_veh_entered', ids_veh_entered, type(ids_veh_entered))
# print ' ids_veh_entered_sumo',ids_veh_entered_sumo
# print ' ids_leader',vehicles.ids_leader[ids_veh_entered]
@@ -1338,13 +1338,13 @@ def process_step(self, process):
id_veh_sumo = ids_veh_entered_sumo[ind_entered]
if debug > 0:
- print ' >>exiting vehicle', id_veh_sumo, 'is_leader', vehicles.ids_leader[id_veh] == -1, 'ids_node_out', ids_node_out, 'ids_merge_out', ids_merge_out
+ print(' >>exiting vehicle', id_veh_sumo, 'is_leader', vehicles.ids_leader[id_veh] == -1, 'ids_node_out', ids_node_out, 'ids_merge_out', ids_merge_out)
# print ' route_sumo',route_sumo
if ids_node_out is not None:
if debug > 0:
- print ' check which out mergenode are on the current route of the vehicle'
+ print(' check which out mergenode are on the current route of the vehicle')
# exit from previous merge
# if debug:
@@ -1371,23 +1371,23 @@ def process_step(self, process):
mergeind = np.argmin(routeinds)
if debug > 0:
- print ' route_sumo', route_sumo
- print ' routeinds', routeinds, 'downstream merge', routeinds[mergeind] < INFINT
- print ' ids_edge_mergeout_sumo', ids_edge_mergeout_sumo
- print ' mergeind,routeinds', mergeind, routeinds
- print ' ids_merge_out[mergeind]', ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind]
+ print(' route_sumo', route_sumo)
+ print(' routeinds', routeinds, 'downstream merge', routeinds[mergeind] < INFINT)
+ print(' ids_edge_mergeout_sumo', ids_edge_mergeout_sumo)
+ print(' mergeind,routeinds', mergeind, routeinds)
+ print(' ids_merge_out[mergeind]', ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind])
if routeinds[mergeind] < INFINT:
if debug > 0:
- print ' merge %d is on the route is_entry' % (ids_merge_out[mergeind])
+ print(' merge %d is on the route is_entry' % (ids_merge_out[mergeind]))
if self.are_entry[ids_merge_out[mergeind]]:
if debug > 0:
- print ' call enter_veh_entry'
+ print(' call enter_veh_entry')
self.enter_veh_entry(
id_veh, id_veh_sumo, id_merge, ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind], vehicles, debug=debug)
else:
if debug > 0:
- print ' call enter_veh'
+ print(' call enter_veh')
self.enter_veh(
id_veh, id_veh_sumo, id_merge, ids_merge_out[mergeind], ids_edge_mergeout_sumo[mergeind], vehicles, debug=debug)
else:
@@ -1399,7 +1399,7 @@ def process_step(self, process):
else:
if debug:
- print ' ids_node_out is None means that there is a station or compressor'
+ print(' ids_node_out is None means that there is a station or compressor')
# shunt edges behind.
# completely disconnect from all merge controlls
# including ghosts
@@ -1414,7 +1414,7 @@ def process_step(self, process):
if is_entry:
self.process_step_entry(id_merge, vehicles, debug)
if 0:
- print '========check mergeprocess'
+ print('========check mergeprocess')
for id_merge, id_node_sumo, ids_veh_merged_sumo, ids_veh_merged in\
zip(ids,
net.nodes.ids_sumo[self.ids_node[ids]],
@@ -1422,11 +1422,11 @@ def process_step(self, process):
self.ids_vehs_merged[ids]
):
- print ' ', id_merge, id_node_sumo, ids_veh_merged_sumo
+ print(' ', id_merge, id_node_sumo, ids_veh_merged_sumo)
# print ' ids_veh_merged',ids_veh_merged
def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_control=False, debug=0):
- print 'exit_veh id_veh %s, id_merge_from %d ' % (id_veh_sumo, id_merge_from), 'entry', self.are_entry[id_merge_from]
+ print('exit_veh id_veh %s, id_merge_from %d ' % (id_veh_sumo, id_merge_from), 'entry', self.are_entry[id_merge_from])
# print ' check for platooned vehicles:'
# vehicles.get_platoon(id_veh)
# in id_merge_from: take vehicle out of merged queue and input queue
@@ -1451,8 +1451,8 @@ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_
id_veh_tail = vehicles.get_platoontail(id_veh) # get last in platoon
vehicles.del_ghost(id_veh_behind, id_veh_tail)
if debug > 0:
- print ' del ghost from veh', id_veh_behind, 'ghost', id_veh_tail
- print ' check ghosts:', vehicles.ids_ghosts[id_veh_behind]
+ print(' del ghost from veh', id_veh_behind, 'ghost', id_veh_tail)
+ print(' check ghosts:', vehicles.ids_ghosts[id_veh_behind])
# is there a vehicle in fron of the removed vehicle
# this happens if a vehicle is interactively deviated
if ind_pos > 0:
@@ -1477,26 +1477,26 @@ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_
self.ids_vehs_merged_sumo[id_merge_from].pop(ind_pos) # remove(id_veh_sumo)
self.lineinds_vehs_merged[id_merge_from].pop(ind_pos)
if debug > 0:
- print ' vehicle has been on line index', lineind
+ print(' vehicle has been on line index', lineind)
# remove vehicle from line buffers
if lineind == 1:
self.ids_vehs_in1[id_merge_from].remove(id_veh) # pop()
self.ids_vehs_in1_sumo[id_merge_from].remove(id_veh_sumo) # .pop()
if self.are_entry[id_merge_from]:
if debug > 0:
- print ' vehicle is involved in entry merge processes?', self.vehicles_mains[id_merge_from].has_key(id_veh)
- if self.vehicles_mains[id_merge_from].has_key(id_veh):
+ print(' vehicle is involved in entry merge processes?', id_veh in self.vehicles_mains[id_merge_from])
+ if id_veh in self.vehicles_mains[id_merge_from]:
#
#id_veh_entry = self.vehicles_mains[id_merge_from][id_veh]
# TODO: this is still a lousy method, vehicles_mains neds to be improved
- for id_veh_entry, state in zip(self.vehicles_entries[id_merge_from].keys(), self.vehicles_entries[id_merge_from].values()):
+ for id_veh_entry, state in zip(list(self.vehicles_entries[id_merge_from].keys()), list(self.vehicles_entries[id_merge_from].values())):
#state = self.vehicles_entries[id_merge_from][id_veh_entry]
# print ' state before',state
- if state.has_key('id_veh_infront'):
+ if 'id_veh_infront' in state:
if state['id_veh_infront'] == id_veh:
del state['id_veh_infront']
- if state.has_key('id_veh_behind'):
+ if 'id_veh_behind' in state:
if state['id_veh_behind'] == id_veh:
del state['id_veh_behind']
# print ' state after',state
@@ -1509,7 +1509,7 @@ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_
if self.are_entry[id_merge_from]:
if debug > 0:
- print ' del veh prt.%s from vehicles_entries' % id_veh
+ print(' del veh prt.%s from vehicles_entries' % id_veh)
del self.vehicles_entries[id_merge_from][id_veh]
else:
pass
@@ -1524,16 +1524,16 @@ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_
# just be sure that the vehicle is not in any queue
# but actually this cannot happen
if id_veh in self.ids_vehs_in1[id_merge_from]:
- print 'WARNING in exit_veh: new veh %d should not be in inqueue 1' % id_veh
+ print('WARNING in exit_veh: new veh %d should not be in inqueue 1' % id_veh)
self.ids_vehs_in1[id_merge_from].remove(id_veh)
self.ids_vehs_in1_sumo[id_merge_from].remove(id_veh_sumo)
if id_veh in self.ids_vehs_in2[id_merge_from]:
- print 'WARNING in exit_veh: new veh %d should not be in inqueue 2' % id_veh
+ print('WARNING in exit_veh: new veh %d should not be in inqueue 2' % id_veh)
self.ids_vehs_in2[id_merge_from].remove(id_veh)
self.ids_vehs_in2_sumo[id_merge_from].remove(id_veh_sumo)
- if self.vehicle_to_merge.has_key(id_veh):
+ if id_veh in self.vehicle_to_merge:
del self.vehicle_to_merge[id_veh]
if is_remove_from_control:
@@ -1541,7 +1541,7 @@ def exit_veh(self, id_veh, id_veh_sumo, id_merge_from, vehicles, is_remove_from_
vehicles.del_all_ghosts(id_veh)
def exit_veh_forced(self, id_veh, id_veh_sumo, vehicles):
- if self.vehicle_to_merge.has_key(id_veh):
+ if id_veh in self.vehicle_to_merge:
# exit vehicle from respective merge
self.exit_veh(id_veh, id_veh_sumo, self.vehicle_to_merge[id_veh], vehicles, is_remove_from_control=True)
else:
@@ -1555,24 +1555,24 @@ def print_vehs(self, id_veh1, id_veh2, dist1_min, dist1_max, dist2_min, dist2_ma
#dist_diff = dist_max-dist_min+10.0
if np.all([dist1_min, dist1_max, dist2_min, dist2_max]) > 0:
f = float(pos_max)/dist_max
- print '________________________'
- print 'vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max)
+ print('________________________')
+ print('vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max))
pos_min = int(dist1_min*f)
pos_max = int(dist1_max*f)
- print max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|'
+ print(max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|')
pos_min = int(dist2_min*f)
pos_max = int(dist2_max*f)
- print max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|'
- print 'vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max)
- print '________________________'
+ print(max(pos_min-1, 0)*' '+'<'+(pos_max-pos_min)*'X'+'|')
+ print('vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max))
+ print('________________________')
else:
- print 'WARNING: some negative distances:'
- print 'vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max)
- print 'vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max)
+ print('WARNING: some negative distances:')
+ print('vehicle %s from line %d: %.f--%2f' % (id_veh1, lineind1, dist1_min, dist1_max))
+ print('vehicle %s from line %d: %.f--%2f' % (id_veh2, lineind2, dist2_min, dist2_max))
def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_merge_sumo, vehicles, debug=0):
- print 'enter_veh id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to)
+ print('enter_veh id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to))
# in id_merge_from: take vehicle out of merged queue and input queue
@@ -1610,7 +1610,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
if indpos == -1:
# vehicle is new and must be merged into ids_vehs_merged
if debug > 0:
- print ' merge veh %d arriving from in %d at dist %.2fm' % (id_veh, lineind, dist_tomerge_head_new)
+ print(' merge veh %d arriving from in %d at dist %.2fm' % (id_veh, lineind, dist_tomerge_head_new))
ids_vehs_merged = self.ids_vehs_merged[id_merge_to]
ids_vehs_merged_sumo = self.ids_vehs_merged_sumo[id_merge_to]
@@ -1624,7 +1624,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
# print ' lineinds_vehs_merged[%d]'%id_merge_to,lineinds_vehs_merged
if (ind_insert == 0) | self.are_station[id_merge_to]:
if debug > 0:
- print ' new vehicle is the only vehicle or station', ind_insert, self.are_station[id_merge_to]
+ print(' new vehicle is the only vehicle or station', ind_insert, self.are_station[id_merge_to])
# vehicles heading toward a station merge are not
# really merged because only one incoming line
@@ -1642,7 +1642,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
dist_tomerge_tail_new = get_traci_distance(id_veh_tail_new_sumo, id_edge_merge_sumo, 3.0)
if debug > 0:
# print ' new veh %d arriving from in %d at dist head %.2f /__| tail %.2fm'%(id_veh,lineind,dist_tomerge_head_new,dist_tomerge_tail_new)
- print ' ids_vehs_merged_sumo', ids_vehs_merged_sumo
+ print(' ids_vehs_merged_sumo', ids_vehs_merged_sumo)
for id_veh_merged, id_veh_merged_sumo in zip(ids_vehs_merged[::-1], ids_vehs_merged_sumo[::-1]):
dist_tomerge_head = get_traci_distance(id_veh_merged_sumo, id_edge_merge_sumo, 3.0)
#stoppeddist_tomerge = dist-0.5/self.decel*get_traci_velocity(id_veh_merged_sumo)**2+vehicles.lengths_plat[id_veh]
@@ -1679,11 +1679,11 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
if is_insert:
# at least one vehicle is in front
if debug > 0:
- print ' insert veh %d behind veh %d, index %d' % (id_veh, id_veh_merged, ind_insert)
+ print(' insert veh %d behind veh %d, index %d' % (id_veh, id_veh_merged, ind_insert))
# send control info to involved vehicles
if ind_insert == len(ids_vehs_merged):
if debug > 0:
- print ' appended vehicle after veh', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail
+ print(' appended vehicle after veh', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail)
# V
# |
# G ind_insert-1
@@ -1698,7 +1698,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
elif ind_insert > 0:
# there is at least 1 other veh in front
if debug > 0:
- print ' vehicle will be inserted in front of', ids_vehs_merged_sumo[ind_insert], 'and in behind', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail
+ print(' vehicle will be inserted in front of', ids_vehs_merged_sumo[ind_insert], 'and in behind', id_veh_tail_sumo, 'with leader', ids_vehs_merged_sumo[ind_insert-1], 'dtm=%.2fm' % dist_tomerge_tail)
# G1
# |
# V
@@ -1718,7 +1718,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
else:
if debug > 0:
- print ' prepend veh %d in front of veh %d, first index %d' % (id_veh, id_veh_merged, ind_insert)
+ print(' prepend veh %d in front of veh %d, first index %d' % (id_veh, id_veh_merged, ind_insert))
# is vehicle and ghost in the same input line?
if lineinds_vehs_merged[ind_insert] != lineind:
id_veh_behind = ids_vehs_merged[ind_insert] # last veh in queue
@@ -1738,7 +1738,7 @@ def enter_veh(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_mer
# lineinds_vehs_merged[0] = lineind
def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_edge_merge_sumo, vehicles, debug=0):
- print 'enter_veh_entry id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to)
+ print('enter_veh_entry id_veh %s, id_merge_from %d to id_merge_to %d' % (id_veh_sumo, id_merge_from, id_merge_to))
# in id_merge_from: take vehicle out of merged queue and input queue
@@ -1770,8 +1770,8 @@ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_ed
if lineind == 1:
# from line 1 (main line)
if debug > 0:
- print ' Detected veh', id_veh_sumo, 'on mainline. Is new', indpos == -1
- print ' check for platooned vehicles:'
+ print(' Detected veh', id_veh_sumo, 'on mainline. Is new', indpos == -1)
+ print(' check for platooned vehicles:')
vehicles.get_platoon(id_veh)
id_edge_out_sumo = self.ids_merge_to_ids_edge_out_sumo[id_merge_to]
@@ -1803,7 +1803,7 @@ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_ed
# there is an approaching vehicle on entry line
if state2['status'] == 'accelerate':
# vehicle in acceleration mode
- if state2.has_key('id_veh_behind'):
+ if 'id_veh_behind' in state2:
# accelerating vehicle has already a vehicle
# in front of which to merge
# => look at last vehicle
@@ -1816,7 +1816,7 @@ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_ed
state2['id_veh_behind'] = id_veh
if state2['status'] == 'sync':
- if state2.has_key('id_veh_behind'):
+ if 'id_veh_behind' in state2:
# accelerating vehicle has already a vehicle
# in front of which to merge
# => look at last vehicle
@@ -1845,12 +1845,12 @@ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_ed
elif lineind == 2:
# from line 2 (entry line)
if debug > 0:
- print ' Detected veh', id_veh_sumo, 'on entry line. Is new', indpos == -1
+ print(' Detected veh', id_veh_sumo, 'on entry line. Is new', indpos == -1)
self.ids_vehs_in2[id_merge_to].append(id_veh)
self.ids_vehs_in2_sumo[id_merge_to].append(id_veh_sumo)
if debug > 0:
- print ' command vehicle to stop and wait further instructions'
+ print(' command vehicle to stop and wait further instructions')
#vehicles.control_slow_down(id_veh, speed = 6.0/3.6)
#traci.vehicle.setMaxSpeed(id_veh_sumo, 6.0/3.6)
# print ' set speed to',traci.vehicle.getMaxSpeed(id_veh_sumo)
@@ -1861,10 +1861,10 @@ def enter_veh_entry(self, id_veh, id_veh_sumo, id_merge_from, id_merge_to, id_ed
# prevent SUMO from reaccelerating vehicle
# vehicles.switch_off_control(id_veh)
if debug > 0:
- print ' set veh id_veh prt.%d' % id_veh
+ print(' set veh id_veh prt.%d' % id_veh)
self.vehicles_entries[id_merge_to][id_veh] = {'status': 'wait'}
if debug > 0:
- print ' vehicles_entries[', id_merge_to, ']=', self.vehicles_entries[id_merge_to]
+ print(' vehicles_entries[', id_merge_to, ']=', self.vehicles_entries[id_merge_to])
#
# self.vehicles_mains[id_merge_to][id_veh] = {}# later when used
@@ -1882,13 +1882,13 @@ def get_mergeveh_entry(self, id_merge):
if len(vehicles_entries) == 0:
return -1, {'status': 'wait'}
else:
- return vehicles_entries.keys()[0], vehicles_entries.values()[0]
+ return list(vehicles_entries.keys())[0], list(vehicles_entries.values())[0]
def process_step_entry(self, id_merge, vehicles, debug):
- print 'process_step_entry id_merge', id_merge
+ print('process_step_entry id_merge', id_merge)
if debug > 0:
- print ' vehicles_entries=', self.vehicles_entries[id_merge]
- print ' vehicles_mains', self.vehicles_mains[id_merge]
+ print(' vehicles_entries=', self.vehicles_entries[id_merge])
+ print(' vehicles_mains', self.vehicles_mains[id_merge])
# print ' self.vehicles_entries',self.vehicles_entries
#self.vehicles_entries[id_merge]= OrderedDict()
# self.vehicles_mains[id_merge] = OrderedDict()
@@ -1897,8 +1897,8 @@ def process_step_entry(self, id_merge, vehicles, debug):
# for id_veh, state in zip(self.vehicles_entries[id_merge].keys()[::-1],self.vehicles_entries[id_merge].values()[::-1]):
# for id_veh, state in self.vehicles_entries.iteritems():
# for id_veh, state in zip(self.vehicles_entries[id_merge].keys(),self.vehicles_entries[id_merge].values()):
- ids_veh_entry = self.vehicles_entries[id_merge].keys()
- states_veh_entry = self.vehicles_entries[id_merge].values()
+ ids_veh_entry = list(self.vehicles_entries[id_merge].keys())
+ states_veh_entry = list(self.vehicles_entries[id_merge].values())
id_edge_out_sumo = self.ids_merge_to_ids_edge_out_sumo[id_merge]
ids_veh_in1 = self.ids_vehs_in1[id_merge]
time_update = self.time_update.get_value()
@@ -1914,7 +1914,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
ids_vehs_merged_sumo = self.ids_vehs_merged_sumo[id_merge]
lineinds_vehs_merged = self.lineinds_vehs_merged[id_merge]
if debug > 0:
- print ' check id_veh_sumo', id_veh_sumo, 'status', state['status'], 'n vehs on main', len(ids_veh_in1)
+ print(' check id_veh_sumo', id_veh_sumo, 'status', state['status'], 'n vehs on main', len(ids_veh_in1))
if state['status'] == 'wait':
if traci.vehicle.isStopped(id_veh_sumo):
# check potential conflict vehicle on main line
@@ -1922,7 +1922,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
n1 = len(ids_veh_in1)
if n1 == 0:
if debug > 0:
- print ' main line is empty => accelerate immediately'
+ print(' main line is empty => accelerate immediately')
for id_veh_plat in vehicles.get_platoon(id_veh):
vehicles.control_speedup(id_veh_plat)
state['status'] = 'accelerate'
@@ -1943,7 +1943,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
id_veh1_sumo = ids_veh_in1_sumo[i]
id_veh1 = ids_veh_in1[i]
if debug > 0:
- print ' check', id_veh1_sumo # ,'free',id_veh1 not in vehicles_main
+ print(' check', id_veh1_sumo) # ,'free',id_veh1 not in vehicles_main
if True: # id_veh1 not in vehicles_main:
@@ -1959,9 +1959,9 @@ def process_step_entry(self, id_merge, vehicles, debug):
dist_in1, dist_in2,
vehicles)
if debug > 0:
- print ' potential veh %s (tail %s)' % (id_veh1_sumo, id_veh1_tail_sumo), 'at pos1_tail=%.1f>p_to=%.1f' % (pos1_tail, p_to), pos1_tail > p_to
+ print(' potential veh %s (tail %s)' % (id_veh1_sumo, id_veh1_tail_sumo), 'at pos1_tail=%.1f>p_to=%.1f' % (pos1_tail, p_to), pos1_tail > p_to)
- print ' i=%d, n1=%d' % (i, n1), 'last vehicle on main', i == n1-1, 'more', i < n1-1
+ print(' i=%d, n1=%d' % (i, n1), 'last vehicle on main', i == n1-1, 'more', i < n1-1)
#self.print_vehs(id_veh1, id_veh2, dist1_min, dist1_max, dist2_min, dist2_max,lineind1, lineind2, pos_max = 79)
@@ -1972,7 +1972,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
if i == n1-1: # last vehicle on main
if debug > 0:
- print ' insert id_veh', id_veh_sumo, 'behind id_veh1', id_veh1_sumo, 'the only veh on main'
+ print(' insert id_veh', id_veh_sumo, 'behind id_veh1', id_veh1_sumo, 'the only veh on main')
state['id_veh_infront'] = id_veh1
vehicles_main[id_veh1] = id_veh # no, it does not get a ghost
# vehicles_main[id_veh1] = { 'id_veh':id_veh,
@@ -1989,7 +1989,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
id_veh_behind_sumo = vehicles.ids_sumo[id_veh_behind]
pos1 = dist_in1 - get_traci_distance(id_veh_behind_sumo, id_edge_out_sumo, 3.0)
if debug > 0:
- print ' vehicle behind', id_veh_behind_sumo, 'pos=%.1f, p_from=%.1f' % (pos1, p_from), 'ok', pos1 < p_from
+ print(' vehicle behind', id_veh_behind_sumo, 'pos=%.1f, p_from=%.1f' % (pos1, p_from), 'ok', pos1 < p_from)
if pos1 < p_from:
state['id_veh_infront'] = id_veh1
state['id_veh_behind'] = id_veh_behind
@@ -2008,7 +2008,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
elif pos1 < p_from:
if i == 0: # first vehicle on main
if debug > 0:
- print ' insert id_veh', id_veh_sumo, 'in front of id_veh1', id_veh1_sumo, 'the only veh on main'
+ print(' insert id_veh', id_veh_sumo, 'in front of id_veh1', id_veh1_sumo, 'the only veh on main')
state['id_veh_behind'] = id_veh1
vehicles_main[id_veh1] = id_veh
is_found = True
@@ -2034,7 +2034,7 @@ def process_step_entry(self, id_merge, vehicles, debug):
if is_found:
if debug > 0:
- print ' suitable vehicle after which entry vehicle can run has been found'
+ print(' suitable vehicle after which entry vehicle can run has been found')
# Note: if no vehicle has been found then
# nothing will happen and the vehicle will
# wait until the righ moment has arrived
@@ -2044,29 +2044,29 @@ def process_step_entry(self, id_merge, vehicles, debug):
else:
if debug > 0:
- print ' nothing will happen and the vehicle will wait until the righ moment has arrived'
+ print(' nothing will happen and the vehicle will wait until the righ moment has arrived')
elif state['status'] == 'accelerate':
# test if speed reached
if traci.vehicle.getSpeed(id_veh_sumo) > 0.9*vehicles.speed_max:
if debug > 0:
- print ' synchronization reached for veh', id_veh_sumo
+ print(' synchronization reached for veh', id_veh_sumo)
state['status'] = 'sync'
#id_veh_del = id_veh
# now create ghosts
# id_veh -> id_veh_infront_tail:
- if state.has_key('id_veh_infront'):
+ if 'id_veh_infront' in state:
id_veh_in_front = state['id_veh_infront']
id_veh_infront_tail = vehicles.get_platoontail(id_veh_in_front)
id_veh_infront_tail_sumo = vehicles.ids_sumo[id_veh_infront_tail]
dist_tomerge = get_traci_distance(id_veh_sumo, id_edge_out_sumo, 3.0)
dist_tomerge_tail = get_traci_distance(id_veh_infront_tail_sumo, id_edge_out_sumo, 3.0)
if debug > 0:
- print ' add ghost to entering veh', id_veh_sumo, ' behind', id_veh_infront_tail_sumo, 'with leader', id_veh_in_front
+ print(' add ghost to entering veh', id_veh_sumo, ' behind', id_veh_infront_tail_sumo, 'with leader', id_veh_in_front)
vehicles.add_ghost(id_veh, id_veh_infront_tail, dist_tomerge,
dist_tomerge_tail, is_substitute=True)
- if state.has_key('id_veh_behind'):
+ if 'id_veh_behind' in state:
id_veh_behind = state['id_veh_behind']
id_veh_behind_sumo = vehicles.ids_sumo[id_veh_behind]
@@ -2082,9 +2082,9 @@ def process_step_entry(self, id_merge, vehicles, debug):
else:
if debug > 0:
speed = traci.vehicle.getSpeed(id_veh_sumo)
- print ' sync of veh', id_veh_sumo, ',v=%.1f, not yet reached: %.2f' % (speed, speed/vehicles.speed_max)
+ print(' sync of veh', id_veh_sumo, ',v=%.1f, not yet reached: %.2f' % (speed, speed/vehicles.speed_max))
- if state.has_key('id_veh_behind'):
+ if 'id_veh_behind' in state:
id_veh_behind_sumo = vehicles.ids_sumo[state['id_veh_behind']]
info = traci.vehicle.getLeader(id_veh_behind_sumo, dist=200.0)
if (info is not None):
@@ -2095,17 +2095,17 @@ def process_step_entry(self, id_merge, vehicles, debug):
dist_safe = vehicles.tau*speed + 0.5*speed**2/vehicles.decel_emergency
dist_target = 2*dist_safe+vehicles.lengths_plat[id_veh]
if debug > 0:
- print ' behind', id_veh_behind_sumo, 'with infront', id_leader_sumo, 'at dist=%.2f' % dist_leader, 'at ds=%.2f' % dist_safe, 'is_brake', dist_leader < dist_target
+ print(' behind', id_veh_behind_sumo, 'with infront', id_leader_sumo, 'at dist=%.2f' % dist_leader, 'at ds=%.2f' % dist_safe, 'is_brake', dist_leader < dist_target)
if dist_leader < dist_target:
dv = time_update*vehicles.decel
if (speed-dv) > 0:
if debug > 0:
- print ' slowdown', id_veh_behind_sumo, 'from speed %.2f to %.2f' % (speed, speed-dv)
+ print(' slowdown', id_veh_behind_sumo, 'from speed %.2f to %.2f' % (speed, speed-dv))
traci.vehicle.slowDown(id_veh_behind_sumo, speed-dv, time_update)
else:
dv = time_update*vehicles.decel
if debug > 0:
- print ' accel', id_veh_behind_sumo, 'from speed %.2f to %.2f' % (speed, speed+dv)
+ print(' accel', id_veh_behind_sumo, 'from speed %.2f to %.2f' % (speed, speed+dv))
traci.vehicle.slowDown(id_veh_behind_sumo, speed+dv, time_update)
elif state['status'] == 'sync':
@@ -2584,7 +2584,7 @@ def get_waitpositions(self, ids, is_alight=False, offset=-0.0):
return positions+offset
def prepare_sim(self, process):
- print 'PrtStops.prepare_sim'
+ print('PrtStops.prepare_sim')
net = self.get_scenario().net
ptstops = net.ptstops
ids_edge_sumo = net.edges.ids_sumo
@@ -2620,11 +2620,11 @@ def prepare_sim(self, process):
lastberthstoppos = berths.stoppositions[ids_berth_board][-1]
if (length_stopedge-lastberthstoppos) > stoplinegap+1:
self.stoplines[id_stop] = length_stopedge-stoplinegap
- print ' LI:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop]
+ print(' LI:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop])
elif length_stopedge > lastberthstoppos:
self.stoplines[id_stop] = 0.5*(length_stopedge+lastberthstoppos)
- print ' AV:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop]
+ print(' AV:id_stop', id_stop, 'length_stopedge', length_stopedge, 'stopline', self.stoplines[id_stop])
self.ids_stop_to_ids_acceledge_sumo = np.zeros(np.max(ids)+1, dtype=np.object)
for id_stop, id_stopedge in zip(ids, ids_stopedge):
@@ -2685,7 +2685,7 @@ def prepare_sim(self, process):
id_toedge_sumo)
id_person_sumo = virtualpop.get_id_sumo_from_id(id_person)
- if id_person_to_origs_dests.has_key(id_person_sumo):
+ if id_person_sumo in id_person_to_origs_dests:
id_person_to_origs_dests[id_person_sumo].append(data_orig_dest)
else:
id_person_to_origs_dests[id_person_sumo] = [data_orig_dest]
@@ -2726,8 +2726,8 @@ def prepare_sim(self, process):
def process_step(self, process):
simtime = process.simtime
- print 79*'_'
- print 'PrtStops.process_step at', simtime
+ print(79*'_')
+ print('PrtStops.process_step at', simtime)
net = self.get_scenario().net
ptstops = net.ptstops
berths = self.get_berths()
@@ -2741,22 +2741,22 @@ def process_step(self, process):
zip(ids, self.ids_stop_to_ids_edge_sumo[ids],
self.ids_vehs_sumo_prev[ids],
self.ids_persons_sumo_prev[ids]):
- print ' '+60*'.'
- print ' process id_stop,id_edge_sumo', id_stop, id_edge_sumo
+ print(' '+60*'.')
+ print(' process id_stop,id_edge_sumo', id_stop, id_edge_sumo)
if 0: # id_stop==1:
# print ' ids_berth_alight',self.ids_berth_alight[id_stop]
# print ' ids_berth_board',self.ids_berth_board[id_stop]
- print ' ids_vehs', self.ids_vehs[id_stop]
- print ' ids_vehs_toallocate', self.ids_vehs_toallocate[id_stop]
- print ' inds_berth_alight_allocated', self.inds_berth_alight_allocated[id_stop]
- print ' ids_vehs_alight_allocated', self.ids_vehs_alight_allocated[id_stop]
- print ' ids_vehs_board_allocated', self.ids_vehs_board_allocated[id_stop]
+ print(' ids_vehs', self.ids_vehs[id_stop])
+ print(' ids_vehs_toallocate', self.ids_vehs_toallocate[id_stop])
+ print(' inds_berth_alight_allocated', self.inds_berth_alight_allocated[id_stop])
+ print(' ids_vehs_alight_allocated', self.ids_vehs_alight_allocated[id_stop])
+ print(' ids_vehs_board_allocated', self.ids_vehs_board_allocated[id_stop])
# print ' id_veh_lead prt.%d'%self.ids_veh_lead[id_stop]
# print ' ids_vehs_prog',self.ids_vehs_prog[id_stop]
- print ' iiinds_berth_alight_allocated', self.inds_berth_alight_allocated[id_stop]
- print ' iiinds_berth_board_allocated', self.inds_berth_board_allocated[id_stop]
+ print(' iiinds_berth_alight_allocated', self.inds_berth_alight_allocated[id_stop])
+ print(' iiinds_berth_board_allocated', self.inds_berth_board_allocated[id_stop])
# print ' numbers_person_wait',self.numbers_person_wait[id_stop]
# print ' flow_person',self.flows_person[id_stop]
@@ -2769,7 +2769,7 @@ def process_step(self, process):
if 0:
for id_veh_sumo in self.ids_vehs_sumo_prev[id_stop]:
- print ' stopstate ', id_veh_sumo, bin(traci.vehicle.getStopState(id_veh_sumo))[2:], traci.vehicle.getRoute(id_veh_sumo)
+ print(' stopstate ', id_veh_sumo, bin(traci.vehicle.getStopState(id_veh_sumo))[2:], traci.vehicle.getRoute(id_veh_sumo))
if 0:
self.get_berthqueues(id_stop)
@@ -2963,8 +2963,8 @@ def process_step(self, process):
if ids_person_sumo_prev != ids_person_sumo:
if 0:
- print ' change\n id_person_sumo', ids_person_sumo
- print ' ids_person_sumo_prev', ids_person_sumo_prev
+ print(' change\n id_person_sumo', ids_person_sumo)
+ print(' ids_person_sumo_prev', ids_person_sumo_prev)
# print ' dir(traci.person)',dir(traci.person)
# for id_person_sumo in ids_person_sumo:
# print ' id_person_sumo',id_person_sumo,traci.person.getRoadID(id_person_sumo),traci.person.getVehicle(id_person_sumo)
@@ -2990,7 +2990,7 @@ def process_step(self, process):
ids_person_sumo_entered = ids_person_sumo.difference(ids_person_sumo_prev)
for id_person_sumo in ids_person_sumo_entered:
# print ' entered id_person_sumo',id_person_sumo,traci.person.getRoadID(id_person_sumo)
- if self.id_person_to_origs_dests.has_key(id_person_sumo):
+ if id_person_sumo in self.id_person_to_origs_dests:
id_edge_sumo_dests = self.id_person_to_origs_dests[id_person_sumo]
# check if person still has a PRT trip
@@ -3019,7 +3019,7 @@ def process_step(self, process):
if 0:
for id_person_sumo in ids_person_sumo_prev:
- print ' ids_person_sumo=%s pos = %.2f ' % (id_person_sumo, traci.person.getLanePosition(id_person_sumo))
+ print(' ids_person_sumo=%s pos = %.2f ' % (id_person_sumo, traci.person.getLanePosition(id_person_sumo)))
# nomore print ' ids_persons_sumo_boarded',self.ids_persons_sumo_boarded[id_stop]
# check if boarding is completed in load area,
@@ -3082,7 +3082,7 @@ def process_step(self, process):
self.start_vehicles(id_stop, process)
def start_vehicles(self, id_stop, process):
- print 'start_vehicles=\n', self.ids_vehs_prog[id_stop]
+ print('start_vehicles=\n', self.ids_vehs_prog[id_stop])
i = 0
vehicles = self.parent.prtvehicles
ids_vehs_prog = self.ids_vehs_prog[id_stop]
@@ -3191,7 +3191,7 @@ def _trigger_platoon(self, id_stop, inds_platoon):
route_pre, traveltime = self.route_stop_to_stop(id_stop, id_stop_target_pre)
id_detectoredge_pre = self.get_decompressoredge(route_pre)
- for i in xrange(1, len(inds_platoon)):
+ for i in range(1, len(inds_platoon)):
#time_start_pre, id_veh_pre, id_stop_target_pre, is_prog_pre = ids_vehs_prog[inds_platoon[i-1]]
time_start, id_veh, id_stop_target, is_prog = ids_vehs_prog[inds_platoon[i]]
route, traveltime = self.route_stop_to_stop(id_stop, id_stop_target)
@@ -3319,7 +3319,7 @@ def program_leadveh(self, id_stop, id_veh, id_stop_target, time_start):
return True
else:
- print ' no leader prt.%d exists' % (id_veh,)
+ print(' no leader prt.%d exists' % (id_veh,))
return False
def init_trip_occupied(self, id_stop, id_berth, id_veh, id_veh_sumo, simtime):
@@ -3350,7 +3350,7 @@ def init_trip_occupied(self, id_stop, id_berth, id_veh, id_veh_sumo, simtime):
# id_person_sumo_inveh = id_person_sumo
if id_person_sumo_inveh is not None:
- print ' found person %s in veh %s' % (id_person_sumo_inveh, id_veh_sumo)
+ print(' found person %s in veh %s' % (id_person_sumo_inveh, id_veh_sumo))
# program vehicle to person's destination
# print ' found person,origs_dests',id_person_sumo_inveh,self.id_person_to_origs_dests[id_person_sumo_inveh]
@@ -3376,7 +3376,7 @@ def init_trip_occupied(self, id_stop, id_berth, id_veh, id_veh_sumo, simtime):
return id_person_sumo_inveh
else:
- print 'WARNING: on stop %d edge %s, berth %d no person found inside vehicle prt.%d' % (id_stop, self.ids_stop_to_ids_edge_sumo[id_stop], id_berth, id_veh)
+ print('WARNING: on stop %d edge %s, berth %d no person found inside vehicle prt.%d' % (id_stop, self.ids_stop_to_ids_edge_sumo[id_stop], id_berth, id_veh))
return None
def _get_stopline(self, id_stop, simtime):
@@ -3430,7 +3430,7 @@ def init_trip_empty(self, id_stop, id_berth, id_veh, simtime, is_ask_vehman=True
# self.ids_vehs_outset[id_stop].add(id_veh)
def foreward_boardzone(self, id_stop, ids_berth_board, simtime):
- print 'foreward_boardzone', id_stop, ids_berth_board, 'simtime', simtime
+ print('foreward_boardzone', id_stop, ids_berth_board, 'simtime', simtime)
berths = self.get_berths()
#ids_berth_board = self.ids_berth_board[id_stop][::-1]
# inds_o berths.states[ids_berth_board] != BERTHSTATES['free']
@@ -3442,7 +3442,7 @@ def foreward_boardzone(self, id_stop, ids_berth_board, simtime):
self.times_lastboard[id_stop] = 10**4 # reset last board counter
def enter(self, id_stop, id_veh):
- print 'enter id_stop, id_veh', id_stop, 'prt.%d' % id_veh
+ print('enter id_stop, id_veh', id_stop, 'prt.%d' % id_veh)
self.parent.prtvehicles.decatenate(id_veh)
@@ -3464,10 +3464,10 @@ def enter(self, id_stop, id_veh):
# print ' id_veh_sumo',id_veh_sumo
#pos = traci.vehicle.getLanePosition(id_veh_sumo)
if 0:
- print ' send entering vehicle id_veh %d, pos=%.2f to id_berth_alight %d at pos %.2fm' % (id_veh, traci.vehicle.getLanePosition(id_veh_sumo), id_berth, self.get_berths().stoppositions[id_berth])
- print ' ids_ghost', self.parent.prtvehicles.ids_ghosts[id_veh]
- print ' ids_leader', self.parent.prtvehicles.ids_leader[id_veh]
- print ' ids_follower', self.parent.prtvehicles.ids_follower[id_veh]
+ print(' send entering vehicle id_veh %d, pos=%.2f to id_berth_alight %d at pos %.2fm' % (id_veh, traci.vehicle.getLanePosition(id_veh_sumo), id_berth, self.get_berths().stoppositions[id_berth]))
+ print(' ids_ghost', self.parent.prtvehicles.ids_ghosts[id_veh])
+ print(' ids_leader', self.parent.prtvehicles.ids_leader[id_veh])
+ print(' ids_follower', self.parent.prtvehicles.ids_follower[id_veh])
self.parent.prtvehicles.control_stop_alight(id_veh, id_stop, id_berth,
id_edge_sumo=self.ids_stop_to_ids_edge_sumo[id_stop],
@@ -3552,7 +3552,7 @@ def get_berthqueues(self, id_stop):
stoppositions = self.get_berths().stoppositions[ids_berth_board]
counters = np.zeros(len(stoppositions), dtype=np.int32)
# print ' stoppositions',stoppositions
- for id_person_sumo in self.waittimes_persons[id_stop].keys():
+ for id_person_sumo in list(self.waittimes_persons[id_stop].keys()):
position = traci.person.getLanePosition(id_person_sumo)
# print ' position',position
dists = np.abs(stoppositions-position)
@@ -3572,7 +3572,7 @@ def make_from_net(self):
"""
Make prt stop database from PT stops in network.
"""
- print 'make_from_net'
+ print('make_from_net')
self.clear()
net = self.get_scenario().net
ptstops = net.ptstops
@@ -3620,7 +3620,7 @@ def make(self, id_ptstop, position_from, position_to):
class VehicleAdder(Process):
def __init__(self, vehicles, logger=None, **kwargs):
- print 'VehicleAdder.__init__', vehicles, vehicles.parent.get_ident()
+ print('VehicleAdder.__init__', vehicles, vehicles.parent.get_ident())
self._init_common('vehicleadder', name='Vehicle adder',
logger=logger,
info='Add vehicles to PRT stops of network.',
@@ -3795,7 +3795,7 @@ def get_net(self):
return self.parent.get_scenario().net
def make_vtype(self, is_renew=False):
- print 'make_vtype PRT'
+ print('make_vtype PRT')
vtypes = self.get_scenario().demand.vtypes
prttype = 'PRT'
@@ -3901,7 +3901,7 @@ def get_length(self):
return self.length
def prepare_sim(self, process):
- print 'PrtVehicles.prepare_sim'
+ print('PrtVehicles.prepare_sim')
if len(self) == 0:
return []
@@ -3962,7 +3962,7 @@ def add_ghost(self, id_veh, id_ghost, dist_to_merge_veh, dist_to_merge_ghost,
# self.del_ghost(id_veh, id_ghost_old)
# else:
# add new ghost
- print 'add_ghost id_veh %d id_ghost %d' % (id_veh, id_ghost) # ,self.ids_ghosts.shape
+ print('add_ghost id_veh %d id_ghost %d' % (id_veh, id_ghost)) # ,self.ids_ghosts.shape
if -1 not in ids_ghosts:
# print 'ERROR: no more ghosts available, ids_ghosts',ids_ghosts
@@ -3981,7 +3981,7 @@ def add_ghost(self, id_veh, id_ghost, dist_to_merge_veh, dist_to_merge_ghost,
ind_ghost -= 1
if ind_ghost > 0:
- print 'WARNING: unusual number of ghosts, ids_ghosts', ids_ghosts
+ print('WARNING: unusual number of ghosts, ids_ghosts', ids_ghosts)
# sys.exit(1)
self.ids_ghosts[id_veh][ind_ghost] = id_ghost
@@ -4068,8 +4068,8 @@ def stop_update(self, id_veh):
def process_step(self, process):
simtime = process.simtime
- print 79*'_'
- print 'PrtVehicles.process_step at', simtime
+ print(79*'_')
+ print('PrtVehicles.process_step at', simtime)
net = self.get_scenario().net
vehicles = self.parent.prtvehicles
ids = self.get_ids()
@@ -4098,7 +4098,7 @@ def process_step(self, process):
if 0:
ids_ghost = self.ids_ghosts[id_veh]
- print ' %7s' % id_veh_sumo, 'ghosts', ids_ghost, self.ids_leader[id_veh], "lp=%.1fm" % self.lengths_plat[id_veh]
+ print(' %7s' % id_veh_sumo, 'ghosts', ids_ghost, self.ids_leader[id_veh], "lp=%.1fm" % self.lengths_plat[id_veh])
#odo = self.odos[id_veh]
#delta_vehs = odo-self.odos0_vehicles[id_veh]
#delta_ghosts = self.odos[ids_ghost] - self.odos0_ghosts[id_veh]
@@ -4234,7 +4234,7 @@ def process_step(self, process):
#self.tau = vtypes.taus[id_vtype]
def reset_speedmode(self, id_veh_sumo):
- print 'reset_speedmode', id_veh_sumo
+ print('reset_speedmode', id_veh_sumo)
# speed mode (0xb3)
# Per default, the vehicle is using the given speed regarding the safe gap, the maximum acceleration, and the maximum deceleration. Furthermore, vehicles follow the right-of-way rules when approaching an intersection and if necessary they brake hard to avoid driving across a red light. One can control this behavior using the speed mode (0xb3) command, the given integer is a bitset (bit0 is the least significant bit) with the following fields:
# 1 bit0: Regard safe speed
@@ -4250,7 +4250,7 @@ def reset_speedmode(self, id_veh_sumo):
# pass
def concatenate(self, id_veh, id_veh_pre):
- print 'concatenate prt.%d' % id_veh, 'behind prt.%d' % id_veh_pre
+ print('concatenate prt.%d' % id_veh, 'behind prt.%d' % id_veh_pre)
# print ' >>'
self.ids_leader[id_veh] = id_veh_pre
self.ids_follower[id_veh_pre] = id_veh
@@ -4258,13 +4258,13 @@ def concatenate(self, id_veh, id_veh_pre):
id_veh_sumo = self.get_id_sumo(id_veh)
if 0:
- print 'follower params'
- print ' speedmode', self._speedmode_follower
- print ' factor_speed', self._factor_speed_follower
- print ' decel', self._decel_emergency_follower, '= decel_emergency'
- print ' accel_follower', self._accel_follower
- print ' dist_min', self._dist_min_follower
- print ' tau', self._tau_follower
+ print('follower params')
+ print(' speedmode', self._speedmode_follower)
+ print(' factor_speed', self._factor_speed_follower)
+ print(' decel', self._decel_emergency_follower, '= decel_emergency')
+ print(' accel_follower', self._accel_follower)
+ print(' dist_min', self._dist_min_follower)
+ print(' tau', self._tau_follower)
# if 0:
# traci.vehicle.setSpeedFactor(id_veh_sumo,2.0)# +random.uniform(-0.01,0.01)
@@ -4302,7 +4302,7 @@ def _update_concatenate(self, id_veh, length_plat):
self._update_concatenate(self.ids_leader[id_veh], length_plat + self.length)
def decatenate(self, id_veh):
- print 'decatenate prt.%d' % id_veh
+ print('decatenate prt.%d' % id_veh)
id_leader = self.ids_leader[id_veh]
# print ' id_leader',id_leader
@@ -4317,7 +4317,7 @@ def decatenate(self, id_veh):
# TODO
self.lengths_plat[id_veh] = self.lengths_plat[id_leader]-self.length
else:
- print 'WARNING in decatenate: platoon broken up in the middel at', id_veh_sumo
+ print('WARNING in decatenate: platoon broken up in the middel at', id_veh_sumo)
self.lengths_plat[id_veh] = 0.0
# this vehicle will become first in the platoon
@@ -4357,16 +4357,16 @@ def get_platoontail(self, id_veh):
return id_veh
def get_platoon(self, id_veh):
- print 'get_platoon', id_veh
+ print('get_platoon', id_veh)
ids_veh = [id_veh, ]
id_veh = self.ids_follower[id_veh]
# print ' id_veh',id_veh
while id_veh > -1:
ids_veh.append(id_veh)
id_veh = self.ids_follower[id_veh]
- print ' id_veh', id_veh
+ print(' id_veh', id_veh)
- print ' ids_veh', ids_veh
+ print(' ids_veh', ids_veh)
return ids_veh
def get_entered_left(self, id_edge_sumo, ids_veh_previous_sumo):
@@ -4429,7 +4429,7 @@ def control_stop(self, id_veh, laneindex=0):
stopline = pos + 3.0 + 0.5/self.decel*speed**2
#time_slowdown = np.abs((speed0-speed)/self.decel)
- print 'control_stop', id_veh_sumo, 'v = %.2f at pos %.1fm to stop at %.1fm on %s' % (speed, pos, stopline, traci.vehicle.getRoadID(id_veh_sumo))
+ print('control_stop', id_veh_sumo, 'v = %.2f at pos %.1fm to stop at %.1fm on %s' % (speed, pos, stopline, traci.vehicle.getRoadID(id_veh_sumo)))
traci.vehicle.setStop(id_veh_sumo,
traci.vehicle.getRoadID(id_veh_sumo),
pos=stopline,
@@ -4439,7 +4439,7 @@ def control_stop(self, id_veh, laneindex=0):
def control_speedup(self, id_veh):
id_veh_sumo = self.get_id_sumo(id_veh)
- print 'control_speedup', id_veh_sumo, 'isStopped', traci.vehicle.isStopped(id_veh_sumo), self.speed_max
+ print('control_speedup', id_veh_sumo, 'isStopped', traci.vehicle.isStopped(id_veh_sumo), self.speed_max)
if traci.vehicle.isStopped(id_veh_sumo):
traci.vehicle.resume(id_veh_sumo)
@@ -4448,7 +4448,7 @@ def control_speedup(self, id_veh):
#self.control_slow_down(id_veh, self.speed_max)
def control_slow_down(self, id_veh, speed=1.0, time_slowdown=None):
- print 'control_slow_down', self.get_id_sumo(id_veh), speed, time_slowdown
+ print('control_slow_down', self.get_id_sumo(id_veh), speed, time_slowdown)
id_veh_sumo = self.get_id_sumo(id_veh)
if time_slowdown is None:
speed0 = traci.vehicle.getSpeed(id_veh_sumo)
@@ -4467,7 +4467,7 @@ def control_stop_alight(self, id_veh, id_stop, id_berth,
):
id_veh_sumo = self.get_id_sumo(id_veh)
p = traci.vehicle.getLanePosition(id_veh_sumo)
- print 'control_stop_alight', id_veh_sumo, p, '->', position, 'id_berth', id_berth
+ print('control_stop_alight', id_veh_sumo, p, '->', position, 'id_berth', id_berth)
#d = position - p
#v = traci.vehicle.getSpeed(id_veh_sumo)
#d_save = 1.0/(2*2.5)*(v**2)
@@ -4488,7 +4488,7 @@ def control_stop_board(self, id_veh, id_stop, id_berth,
):
id_veh_sumo = self.get_id_sumo(id_veh)
- print 'control_stop_board', id_veh_sumo, id_stop, id_berth, id_edge_sumo, 'pos=%.2f,target %.2f' % (traci.vehicle.getLanePosition(id_veh_sumo), position)
+ print('control_stop_board', id_veh_sumo, id_stop, id_berth, id_edge_sumo, 'pos=%.2f,target %.2f' % (traci.vehicle.getLanePosition(id_veh_sumo), position))
# print ' v=',traci.vehicle.getSpeed(id_veh_sumo)
# print 'control_stop_board',id_veh_sumo,traci.vehicle.getLanePosition(id_veh_sumo),'->',position,id_berth
@@ -4535,7 +4535,7 @@ def board(self, id_veh, id_edge_sumo=None, position=None):
# print 'board ',id_veh_sumo, traci.vehicle.getStopState(id_veh_sumo )# bin(traci.vehicle.getStopState(id_veh_sumo ))[2:]
def set_stop(self, id_veh, id_edge_sumo, stopline, laneindex=1):
- print 'set_stop', self.get_id_sumo(id_veh), stopline
+ print('set_stop', self.get_id_sumo(id_veh), stopline)
traci.vehicle.setStop(self.get_id_sumo(id_veh),
id_edge_sumo,
pos=stopline,
@@ -4560,7 +4560,7 @@ def is_completed_alighting(self, id_veh):
elif self.states[id_veh] == VEHICLESTATES['await_forwarding']:
return True
else:
- print 'WARNING: strange vehicle state %s while alighting prt.%d' % (self.states[id_veh], id_veh)
+ print('WARNING: strange vehicle state %s while alighting prt.%d' % (self.states[id_veh], id_veh))
return True
def is_completed_boarding(self, id_veh):
@@ -4593,7 +4593,7 @@ def get_veh_if_completed_boarding(self, id_veh):
def init_trip_occupied(self, id_veh, id_edge_sumo, stopline=None):
id_veh_sumo = self.get_id_sumo(id_veh)
- print 'init_trip_occupied', self.get_id_sumo(id_veh), 'from edge', id_edge_sumo, stopline
+ print('init_trip_occupied', self.get_id_sumo(id_veh), 'from edge', id_edge_sumo, stopline)
# print ' current route:',traci.vehicle.getRoute(id_veh_sumo)
self.states[id_veh] = VEHICLESTATES['occupiedtrip']
@@ -4614,7 +4614,7 @@ def init_trip_occupied(self, id_veh, id_edge_sumo, stopline=None):
#traci.vehicle.slowDown(id_veh_sumo, speed_crawl, time_accel)
def init_trip_empty(self, id_veh, id_edge_sumo, stopline=None):
- print 'Vehicles.init_trip_empty', self.get_id_sumo(id_veh), id_edge_sumo, stopline
+ print('Vehicles.init_trip_empty', self.get_id_sumo(id_veh), id_edge_sumo, stopline)
self.states[id_veh] = VEHICLESTATES['emptytrip']
id_veh_sumo = self.get_id_sumo(id_veh)
if traci.vehicle.isStopped(id_veh_sumo):
@@ -4637,7 +4637,7 @@ def init_trip_empty(self, id_veh, id_edge_sumo, stopline=None):
#traci.vehicle.slowDown(id_veh_sumo, speed_crawl, time_accel)
def reschedule_trip_sumo(self, id_veh_sumo, id_edge_sumo_to=None, route_sumo=None):
- print 'reschedule_trip_sumo', id_veh_sumo, id_edge_sumo_to, route_sumo
+ print('reschedule_trip_sumo', id_veh_sumo, id_edge_sumo_to, route_sumo)
if traci.vehicle.isStopped(id_veh_sumo):
traci.vehicle.resume(id_veh_sumo)
@@ -4654,7 +4654,7 @@ def reschedule_trip_sumo(self, id_veh_sumo, id_edge_sumo_to=None, route_sumo=Non
#traci.vehicle.slowDown(id_veh_sumo, 13.0, 5.0)
def reschedule_trip(self, id_veh, id_edge_sumo_to=None, route_sumo=None):
- print 'reschedule_trip', self.get_id_sumo(id_veh), id_edge_sumo_to, route_sumo
+ print('reschedule_trip', self.get_id_sumo(id_veh), id_edge_sumo_to, route_sumo)
id_veh_sumo = self.get_id_sumo(id_veh)
if traci.vehicle.isStopped(id_veh_sumo):
traci.vehicle.resume(id_veh_sumo)
@@ -4743,7 +4743,7 @@ def get_id_from_id_sumo(self, id_veh_sumo):
def get_ids_from_ids_sumo(self, ids_veh_sumo):
n = len(ids_veh_sumo)
ids = np.zeros(n, np.int32)
- for i in xrange(n):
+ for i in range(n):
ids[i] = self.get_id_from_id_sumo(ids_veh_sumo[i])
return ids
@@ -4819,7 +4819,7 @@ def preevaluate(self, ids_person):
# put 2 for persons with car access and who prefer cars
preeval[persons.ids_mode_preferred[ids_person] == self.prtservice.id_prtmode] = 2
- print ' PrtStrategy.preevaluate', len(np.flatnonzero(preeval))
+ print(' PrtStrategy.preevaluate', len(np.flatnonzero(preeval)))
return preeval
def plan(self, ids_person, logger=None):
@@ -4827,7 +4827,7 @@ def plan(self, ids_person, logger=None):
Generates a plan for these person according to this strategie.
Overriden by specific strategy.
"""
- print 'PrtStrategy.pan', len(ids_person)
+ print('PrtStrategy.pan', len(ids_person))
#make_plans_private(self, ids_person = None, mode = 'passenger')
# routing necessary?
virtualpop = self.get_virtualpop()
@@ -4869,7 +4869,7 @@ def plan(self, ids_person, logger=None):
= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)
if len(ids_person_act) == 0:
- print 'WARNING in TrasitStrategy.plan: no eligible persons found.'
+ print('WARNING in TrasitStrategy.plan: no eligible persons found.')
return False
# temporary maps from ids_person to other parameters
@@ -4888,7 +4888,7 @@ def plan(self, ids_person, logger=None):
map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]
n_plans = len(ids_person_act)
- print 'TrasitStrategy.plan n_plans=', n_plans
+ print('TrasitStrategy.plan n_plans=', n_plans)
# make initial activity stage
ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]
@@ -4970,11 +4970,11 @@ def plan(self, ids_person, logger=None):
if logger:
logger.progress(i/n_pers*100)
i += 1.0
- print 79*'_'
- print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)
+ print(79*'_')
+ print(' id_plan=%d, id_person=%d, ' % (id_plan, id_person))
if (dist_from_to < dist_walk_max) | (id_edge_from == -1) | (id_edge_to == -1) | (id_stop_from == id_stop_to):
- print ' go by foot because distance is too short ', dist_from_to, 'edges', id_edge_from, id_edge_to, 'stops', id_stop_from, id_stop_to
+ print(' go by foot because distance is too short ', dist_from_to, 'edges', id_edge_from, id_edge_to, 'stops', id_stop_from, id_stop_to)
id_stage_walk1, time = walkstages.append_stage(
id_plan, time_from,
@@ -5041,7 +5041,7 @@ def __init__(self, ident, stages,
# **kwargs,
):
- print 'PrtTransits.__init__', ident, stages
+ print('PrtTransits.__init__', ident, stages)
self.init_stagetable(ident,
stages, name=name,
info=info,
@@ -5073,10 +5073,10 @@ def get_prtservice(self):
def prepare_planning(self):
prtservice = self.get_prtservice()
- print 'prttransits.prepare_planning', prtservice.times_stop_to_stop
+ print('prttransits.prepare_planning', prtservice.times_stop_to_stop)
if prtservice.times_stop_to_stop is None:
prtservice.make_times_stop_to_stop()
- print prtservice.times_stop_to_stop
+ print(prtservice.times_stop_to_stop)
def append_stage(self, id_plan, time_start=-1.0,
duration=0.0,
@@ -5216,7 +5216,7 @@ def get_scenario(self):
return self.parent.parent.get_scenario()
def prepare_sim(self, process):
- print 'VehicleMan.prepare_sim'
+ print('VehicleMan.prepare_sim')
net = self.get_scenario().net
# station management
# self.ids_stop_to_ids_edge_sumo = np.zeros(np.max(ids)+1,dtype = np.object)
@@ -5238,7 +5238,7 @@ def prepare_sim(self, process):
self.ids_veh = self.get_vehicles().get_ids()
if len(self.ids_veh) == 0:
- print 'WARNING: no PRT vehicles, please add PRT vehicles.'
+ print('WARNING: no PRT vehicles, please add PRT vehicles.')
return []
n_veharray = np.max(self.ids_veh)+1
@@ -5293,8 +5293,8 @@ def update_flows(self, process):
self.log_inflows_temp[:] = 0
def process_step(self, process):
- print 79*'M'
- print 'VehicleMan.process_step'
+ print(79*'M')
+ print('VehicleMan.process_step')
stops = self.get_stops()
#vehicles = self.get_vehicles()
@@ -5339,7 +5339,7 @@ def push_occupied_leadvehs(self, ids_veh_lead, process):
inds_valid = np.flatnonzero(vehicles.states[ids_veh_lead] == VEHICLESTATES['occupiedtrip'])
if len(inds_valid) == 0:
return False
- print 'push_occupied_leadvehs ids_veh_lead', ids_veh_lead[inds_valid]
+ print('push_occupied_leadvehs ids_veh_lead', ids_veh_lead[inds_valid])
times_stop_to_stop = self.parent.times_stop_to_stop
ids_stop_current = self.ids_stop_current[ids_veh_lead[inds_valid]]
ids_stop_target = self.ids_stop_target[ids_veh_lead[inds_valid]]
@@ -5365,7 +5365,7 @@ def push_occupied_leadvehs(self, ids_veh_lead, process):
durations_est,
):
- print ' check veh', id_veh_lead, state, 'id_stop_current', id_stop_current, 'id_stop_target', id_stop_target
+ print(' check veh', id_veh_lead, state, 'id_stop_current', id_stop_current, 'id_stop_target', id_stop_target)
#VEHICLESTATES = {'init':0,'waiting':1,'boarding':2,'alighting':3,'emptytrip':4,'occupiedtrip':5,'forewarding':6}
# if state == VEHICLESTATES['occupiedtrip']:
@@ -5398,7 +5398,7 @@ def push_empty_leadvehs(self, ids_veh_lead, process):
if len(inds_valid) == 0:
return False
- print 'push_empty_leadvehs ids_veh_lead', ids_veh_lead[inds_valid]
+ print('push_empty_leadvehs ids_veh_lead', ids_veh_lead[inds_valid])
times_stop_to_stop = self.parent.times_stop_to_stop
ids_stop_current = self.ids_stop_current[ids_veh_lead[inds_valid]]
@@ -5427,7 +5427,7 @@ def push_empty_leadvehs(self, ids_veh_lead, process):
durations_est = times_stop_to_stop[id_stop_current, ids_stop_target]
ind_stop_current = np.flatnonzero(durations_est == 0)[0]
- print ' check veh', id_veh_lead, 'id_stop_current', id_stop_current, 'ind_stop_current', ind_stop_current
+ print(' check veh', id_veh_lead, 'id_stop_current', id_stop_current, 'ind_stop_current', ind_stop_current)
inds_time_min = np.array(np.clip(np.array(1.0*durations_est/self.time_update_flows.get_value(),
dtype=np.int32), 0, self.n_est_max-n_searchint), dtype=np.int32)
inds_search = inds_search_base + inds_time_min.reshape(n_stop_target, 1)
@@ -5446,29 +5446,29 @@ def push_empty_leadvehs(self, ids_veh_lead, process):
#costs = (self.inflows_sched[ids_stop_target, inds_search]-flow_person_est)*timeweight
costs[ind_stop_current, :] = -999999
if 0:
- for ind, id_stop in zip(range(n_stop_target), ids_stop_target):
- print 40*'.'
- print ' id_stop', id_stop
- print ' waittimes_tot', stops.waittimes_tot[id_stop]
- print ' numbers_person_wait', stops.numbers_person_wait[id_stop]
- print ' flow_person_est', flow_person_est[ind]
- print ' inflows_sched', self.inflows_sched[id_stop, inds_search[ind]]
- print ' delta flow', (flow_person_est[ind]-self.inflows_sched[id_stop, inds_search[ind]])
- print ' demandcomp', self.weight_demand.get_value() * stops.numbers_person_wait[id_stop]
- print ' flowcomp', self.weight_flow.get_value() * (flow_person_est[ind]-self.inflows_sched[id_stop, inds_search[ind]])
- print ' arrivaltime est', inds_search[ind]*self.time_update_flows.get_value()
- print ' flow_person_est', flow_person_est[ind]
- print
+ for ind, id_stop in zip(list(range(n_stop_target)), ids_stop_target):
+ print(40*'.')
+ print(' id_stop', id_stop)
+ print(' waittimes_tot', stops.waittimes_tot[id_stop])
+ print(' numbers_person_wait', stops.numbers_person_wait[id_stop])
+ print(' flow_person_est', flow_person_est[ind])
+ print(' inflows_sched', self.inflows_sched[id_stop, inds_search[ind]])
+ print(' delta flow', (flow_person_est[ind]-self.inflows_sched[id_stop, inds_search[ind]]))
+ print(' demandcomp', self.weight_demand.get_value() * stops.numbers_person_wait[id_stop])
+ print(' flowcomp', self.weight_flow.get_value() * (flow_person_est[ind]-self.inflows_sched[id_stop, inds_search[ind]]))
+ print(' arrivaltime est', inds_search[ind]*self.time_update_flows.get_value())
+ print(' flow_person_est', flow_person_est[ind])
+ print()
# print ' flow_person_est',flow_person_#est
- print ' timeweight', timeweight[ind]
- print ' durations_est', durations_est[ind]
- print ' inds_search_base', inds_search_base[ind]
+ print(' timeweight', timeweight[ind])
+ print(' durations_est', durations_est[ind])
+ print(' inds_search_base', inds_search_base[ind])
# print ' inds_search unclipped\n',inds_search_base +np.array(1.0*durations_est/self.time_update_flows.get_value(),dtype=np.int32).reshape(n_stop_target,1)
- print ' inds_search clipped \n', inds_search[ind]
- print ' inds_time_min', inds_time_min[ind]
+ print(' inds_search clipped \n', inds_search[ind])
+ print(' inds_time_min', inds_time_min[ind])
# print ' ind_stop_current',ind_stop_current,durations_est[ind_stop_current]
- print ' costs=\n', costs[ind]
+ print(' costs=\n', costs[ind])
# constant_timeweight
#
@@ -5478,9 +5478,9 @@ def push_empty_leadvehs(self, ids_veh_lead, process):
ind_time_delta = ind_target % n_searchint
ind_time_arrive = inds_search[ind_stop_target, ind_time_delta]
if 0:
- print ' ind_target,n_searchint,ind_stop_target,ind_time_delta', ind_target, n_searchint, ind_target/n_searchint, ind_time_delta
- print ' ind_delta_depart,c_min', costs[ind_stop_target, ind_time_delta]
- print ' inds_time_min,ind_time_arrive', inds_time_min[ind_stop_target], ind_time_arrive
+ print(' ind_target,n_searchint,ind_stop_target,ind_time_delta', ind_target, n_searchint, ind_target/n_searchint, ind_time_delta)
+ print(' ind_delta_depart,c_min', costs[ind_stop_target, ind_time_delta])
+ print(' inds_time_min,ind_time_arrive', inds_time_min[ind_stop_target], ind_time_arrive)
id_stop_target = ids_stop_target[ind_stop_target][0]
time_depart = process.simtime + ind_time_arrive * \
@@ -5493,7 +5493,7 @@ def push_empty_leadvehs(self, ids_veh_lead, process):
self.numbers_veh_arr[id_stop_target] += 1
self.inflows_sched[id_stop_target, ind_time_arrive] += 1
else:
- print 'WARNING in push_empty_leadvehs: no vehicle prt.%d in stop %d' % (id_veh_lead, id_stop_target)
+ print('WARNING in push_empty_leadvehs: no vehicle prt.%d in stop %d' % (id_veh_lead, id_stop_target))
return is_started
def pull_empty_leadvehs(self, ids_veh_lead, process):
@@ -5507,7 +5507,7 @@ def pull_empty_leadvehs(self, ids_veh_lead, process):
# & (stops.numbers_person_wait[self.ids_stop_current[ids_veh_lead]] == 0))
vehicles = self.get_vehicles()
stops = self.get_stops()
- print 'pull_empty_leadvehs', ids_veh_lead
+ print('pull_empty_leadvehs', ids_veh_lead)
# print ' bordingstate',vehicles.states[ids_veh_lead] == VEHICLESTATES['boarding']
# print ' nowaits stop',stops.numbers_person_wait[self.ids_stop_current[ids_veh_lead]] ==0
@@ -5544,7 +5544,7 @@ def pull_empty_leadvehs(self, ids_veh_lead, process):
ids_stop_target = self.ids_stop[inds_valid]
demands = demands[inds_valid]
- print ' ids_stop_current', ids_stop_current
+ print(' ids_stop_current', ids_stop_current)
# print ' ids_stop_target',ids_stop_target
# print ' demands',demands
# calculate cost matrix with id_stop_current in rows and id_stop_target
@@ -5561,7 +5561,7 @@ def pull_empty_leadvehs(self, ids_veh_lead, process):
costs = timeweight * demands
for id_stop_target, demand, number_veh, number_veh_arr\
in zip(ids_stop_target, demands, stops.numbers_veh[ids_stop_target], self.numbers_veh_arr[ids_stop_target]):
- print ' id_stop_target', id_stop_target, 'dem', demand, 'n_veh', number_veh, 'n_veh_arr', number_veh_arr
+ print(' id_stop_target', id_stop_target, 'dem', demand, 'n_veh', number_veh, 'n_veh_arr', number_veh_arr)
#costs = np.zeros(costs.size, np.float32)-demands
@@ -5591,7 +5591,7 @@ def pull_empty_leadvehs(self, ids_veh_lead, process):
durations_est,
):
- print ' check veh prt.%d' % (id_veh_lead), state, 'id_stop_current', id_stop_current, 'id_stop_target', id_stop_target
+ print(' check veh prt.%d' % (id_veh_lead), state, 'id_stop_current', id_stop_current, 'id_stop_target', id_stop_target)
#VEHICLESTATES = {'init':0,'waiting':1,'boarding':2,'alighting':3,'emptytrip':4,'occupiedtrip':5,'forewarding':6}
# if state == VEHICLESTATES['occupiedtrip']:
@@ -5764,7 +5764,7 @@ def get_writexmlinfo(self, is_route=False, is_plain=False, **kwargs):
Method used to sort trips when exporting to route or trip xml file
"""
- print 'PRT.get_writexmlinfo'
+ print('PRT.get_writexmlinfo')
# time of first PRT vehicle(s) to be inserted
virtualpop = self.get_scenario().demand.virtualpop
@@ -5855,14 +5855,14 @@ def write_prtvehicle_xml(self, fd, id_veh, time_begin, indent=2):
# self.make_times_stop_to_stop()
def prepare_sim(self, process):
- print 'prepare_sim', self.ident
+ print('prepare_sim', self.ident)
# print ' self.times_stop_to_stop',self.times_stop_to_stop
if self.fstar is None:
self.make_fstar()
if self.times_stop_to_stop is None:
- print ' times_stop_to_stop'
+ print(' times_stop_to_stop')
self.make_times_stop_to_stop()
updatedata = self.prtvehicles.prepare_sim(process)
@@ -5892,7 +5892,7 @@ def get_route(self, id_fromedge, id_toedge):
return route, duration
def make_times_stop_to_stop(self, fstar=None, times=None):
- print 'make_times_stop_to_stop'
+ print('make_times_stop_to_stop')
log = self.get_logger()
if fstar is None:
if self.fstar is None:
@@ -5917,8 +5917,8 @@ def make_times_stop_to_stop(self, fstar=None, times=None):
is_incomplete_fstar = False
for id_edge, id_stop, id_ptstop in zip(ids_edge, ids_prtstop, ids_ptstop):
# print ' Found PRT stop %d, PT stop %d with id_edge %d '%(id_stop,id_ptstop, id_edge)
- if not fstar.has_key(id_edge):
- print 'WARNING in make_times_stop_to_stop: PRT stop %d, PT stop %d has no id_edge %d in fstar' % (id_stop, id_ptstop, id_edge)
+ if id_edge not in fstar:
+ print('WARNING in make_times_stop_to_stop: PRT stop %d, PT stop %d has no id_edge %d in fstar' % (id_stop, id_ptstop, id_edge))
is_incomplete_fstar = True
# check if fstar is complete (all to edges are in keys)
@@ -5928,9 +5928,9 @@ def make_times_stop_to_stop(self, fstar=None, times=None):
if not ids_fromedge_set.issuperset(fstar[id_fromedge]):
is_incomplete_fstar = True
ids_miss = fstar[id_fromedge].difference(ids_fromedge_set)
- print 'WARNING in make_times_stop_to_stop: incomplete fstar of id_fromedge = %d, %s' % (id_fromedge, ids_sumo[id_fromedge])
+ print('WARNING in make_times_stop_to_stop: incomplete fstar of id_fromedge = %d, %s' % (id_fromedge, ids_sumo[id_fromedge]))
for id_edge in ids_miss:
- print ' missing', id_edge, ids_sumo[id_edge]
+ print(' missing', id_edge, ids_sumo[id_edge])
if is_incomplete_fstar:
return
@@ -5977,7 +5977,7 @@ def make_times_stop_to_stop(self, fstar=None, times=None):
stop_to_stop[ids_edge_to_ids_prtstop[id_edge],
ids_edge_to_ids_prtstop[id_edge_target]] = costs[id_edge_target]
else:
- print 'WARNING in make_times_stop_to_stop: unreacle station id_fromedge = %d, %s' % (id_edge_target, ids_sumo[id_edge_target])
+ print('WARNING in make_times_stop_to_stop: unreacle station id_fromedge = %d, %s' % (id_edge_target, ids_sumo[id_edge_target]))
is_incomplete_fstar = True
# put back origin to targets (probably not the best way)
@@ -5992,7 +5992,7 @@ def make_times_stop_to_stop(self, fstar=None, times=None):
self.times_stop_to_stop = stop_to_stop
self.ids_edge_to_ids_prtstop = ids_edge_to_ids_prtstop
- print ' times_stop_to_stop=\n', self.times_stop_to_stop
+ print(' times_stop_to_stop=\n', self.times_stop_to_stop)
return True
def get_fstar(self):
@@ -6000,7 +6000,7 @@ def get_fstar(self):
Returns the forward star graph of the network as dictionary:
fstar[id_fromedge] = set([id_toedge1, id_toedge2,...])
"""
- print 'get_fstar'
+ print('get_fstar')
net = self.get_scenario().net
# prt mode
id_mode = self.id_prtmode
@@ -6037,7 +6037,7 @@ def get_fstar(self):
if id_mode_allow_from == id_mode:
if id_mode_allow_to == id_mode:
- if fstar.has_key(id_fromedge):
+ if id_fromedge in fstar:
fstar[id_fromedge].add(id_toedge)
else:
fstar[id_fromedge] = set([id_toedge])
@@ -6074,7 +6074,7 @@ def get_times(self, fstar):
#id_mode = net.modes.get_id_mode(mode)
id_mode = self.id_prtmode
# print 'get_times id_mode,is_check_lanes,speed_max',id_mode,is_check_lanes,speed_max
- ids_edge = np.array(fstar.keys(), dtype=np.int32)
+ ids_edge = np.array(list(fstar.keys()), dtype=np.int32)
times = np.array(np.zeros(np.max(ids_edge)+1, np.float32))
speeds = net.edges.speeds_max[ids_edge]
@@ -6087,7 +6087,7 @@ def get_times(self, fstar):
return times
def config_results(self, results):
- print 'PrtService.config_results', results, id(results)
+ print('PrtService.config_results', results, id(results))
# keep a link to results here because needed to
# log data during simulation
# this link should not be followed during save process
@@ -6164,7 +6164,7 @@ def get_prtstops(self):
# return self.ids_stop.get_linktab()
def init_recording(self, n_timesteps, time_step):
- print 'init_recording n_timesteps, time_step', n_timesteps, time_step, len(self.ids_stop.get_linktab().get_ids())
+ print('init_recording n_timesteps, time_step', n_timesteps, time_step, len(self.ids_stop.get_linktab().get_ids()))
self.clear()
self.time_step.set_value(time_step)
@@ -6181,13 +6181,13 @@ def init_recording(self, n_timesteps, time_step):
def record(self, timestep, ids, **kwargs):
inds = self.ids_stop.get_linktab().get_inds(ids)
timestep_int = int(timestep)
- for attrname, values in kwargs.iteritems():
+ for attrname, values in kwargs.items():
# print ' record',attrname,'dtype',values.dtype,values.shape, 'array',getattr(self,attrname).get_value().dtype,'shape', getattr(self,attrname).get_value().shape
# print ' inds',type(inds),inds.dtype,
getattr(self, attrname).get_value()[inds, timestep_int] = values
def get_stopresultattrconfigs(self):
- return self.get_attrsman().get_group_attrs('PRT results').values()
+ return list(self.get_attrsman().get_group_attrs('PRT results').values())
def get_persons(self):
return self.ids_person.get_linktab()
diff --git a/tools/contributed/sumopy/plugins/prt/results_mpl.py b/tools/contributed/sumopy/plugins/prt/results_mpl.py
index 526c0142e78e..7efdb98c7bf2 100644
--- a/tools/contributed/sumopy/plugins/prt/results_mpl.py
+++ b/tools/contributed/sumopy/plugins/prt/results_mpl.py
@@ -46,7 +46,7 @@ def __init__(self, results, name='Plot PRT stop results with Matplotlib',
self._init_common('stopresultsplotter', parent=results, name=name,
info=info, logger=logger)
- print 'StopresultsPlotter.__init__', results, self.parent, len(self.get_stopresults())
+ print('StopresultsPlotter.__init__', results, self.parent, len(self.get_stopresults()))
attrsman = self.get_attrsman()
stops = self.get_stopresults().get_prtstops()
@@ -134,10 +134,10 @@ def get_stopresults(self):
def show(self):
stopresults = self.get_stopresults()
- print 'show', stopresults
+ print('show', stopresults)
# print ' dir(vehicleman)',dir(vehicleman)
- print ' len(stopresults)', len(stopresults)
+ print(' len(stopresults)', len(stopresults))
if len(stopresults) > 0:
i_fig = 0
plt.close("all")
@@ -169,7 +169,7 @@ def show(self):
plt.show()
def plot_flow_stop(self, fig):
- print 'plot_flow_stop'
+ print('plot_flow_stop')
id_stop = self.id_stop_plot
stopresults = self.get_stopresults()
ax = fig.add_subplot(111)
@@ -227,7 +227,7 @@ def plot_flow_stop(self, fig):
ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
def plot_waiting_person_time(self, fig):
- print 'plot_waiting_person_time'
+ print('plot_waiting_person_time')
stopresults = self.get_stopresults()
ax = fig.add_subplot(111)
@@ -254,7 +254,7 @@ def plot_waiting_person_time(self, fig):
ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
def plot_waiting_person_number_stop(self, fig):
- print 'plot_waiting_person_number_stop'
+ print('plot_waiting_person_number_stop')
stopresults = self.get_stopresults()
#ax1 = fig.add_subplot(211)
#ax2 = fig.add_subplot(212)
@@ -278,7 +278,7 @@ def plot_waiting_person_number_stop(self, fig):
ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
def plot_waiting_person_number(self, fig):
- print 'plot_waiting_person_number'
+ print('plot_waiting_person_number')
stopresults = self.get_stopresults()
#ax1 = fig.add_subplot(211)
#ax2 = fig.add_subplot(212)
@@ -291,7 +291,7 @@ def plot_waiting_person_number(self, fig):
# works:ax.plot(time.reshape(n_steps,1),numbers_person_wait.reshape(n_steps,-1))
i = 0
for id_stop in stopresults.ids_stop.get_value():
- print ' id_stop', id_stop
+ print(' id_stop', id_stop)
ax.plot(time, stopresults.numbers_person_wait[id_stop],
COLORS[i], linewidth=self.width_line,
label='PRT Stop ID=%d' % id_stop)
@@ -305,7 +305,7 @@ def plot_waiting_person_number(self, fig):
ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
def plot_flows_compare(self, fig):
- print 'plot_flows_compare'
+ print('plot_flows_compare')
stopresults = self.get_stopresults()
#time_update_flows = self.parent.vehicleman.time_update_flows.get_value()
time_update_flows = 10
@@ -318,7 +318,7 @@ def plot_flows_compare(self, fig):
i = 0
flowmatrix = np.zeros((10, 10), dtype=np.int32)
for id_stop in stopresults.ids_stop.get_value():
- print ' id_stop', id_stop
+ print(' id_stop', id_stop)
# print ' sched',stopresults.inflows_veh_sched[id_stop]
# print ' eff ',stopresults.inflows_veh[id_stop]
flowmatrix[np.array(time_update_flows*stopresults.inflows_veh_sched[id_stop], dtype=np.int32),
@@ -328,7 +328,7 @@ def plot_flows_compare(self, fig):
# label = 'PRT Stop ID=%d (effective)'%id_stop)
i += 1
- print 'flowmatrix', flowmatrix
+ print('flowmatrix', flowmatrix)
# ax.matshow(flowmatrix)
cax = ax.matshow(flowmatrix, cmap=cmx.get_cmap('PuBu'))
@@ -341,7 +341,7 @@ def plot_flows_compare(self, fig):
ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
def plot_flows_compare_stop(self, fig):
- print 'plot_flows_compare_stop'
+ print('plot_flows_compare_stop')
stopresults = self.get_stopresults()
id_stop = self.id_stop_plot
#time_update_flows = self.parent.vehicleman.time_update_flows.get_value()
@@ -361,7 +361,7 @@ def plot_flows_compare_stop(self, fig):
time = np.arange(-n_steps+1, n_steps, dtype=np.float32)*t_step
- print ' len(flowcorr),n_steps', len(flowcorr), len(time), n_steps
+ print(' len(flowcorr),n_steps', len(flowcorr), len(time), n_steps)
ax.plot(time, flowcorr,
COLORS[i], linewidth=self.width_line,
@@ -375,7 +375,7 @@ def plot_flows_compare_stop(self, fig):
ax.tick_params(axis='y', labelsize=int(0.8*self.size_labelfont))
def plot_flows(self, fig):
- print 'plot_flows'
+ print('plot_flows')
stopresults = self.get_stopresults()
ax = fig.add_subplot(111)
@@ -411,7 +411,7 @@ def plot_flows(self, fig):
# ('inflows_person', {'name':'Person in-flows', 'unit':'1/s', 'dtype':np.float32, 'info':'Person flow into the stop over time.'}),
def plot_waiting_person(self, fig):
- print 'plot_waiting_person'
+ print('plot_waiting_person')
stopresults = self.get_stopresults()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
diff --git a/tools/contributed/sumopy/plugins/prt/wxgui.py b/tools/contributed/sumopy/plugins/prt/wxgui.py
index f9f02faa59cf..3a51c57a17e8 100644
--- a/tools/contributed/sumopy/plugins/prt/wxgui.py
+++ b/tools/contributed/sumopy/plugins/prt/wxgui.py
@@ -28,13 +28,13 @@
from coremodules.network import routing
from coremodules.demand import demand
from coremodules.simulation import sumo, results
-import prt
+from . import prt
try:
- import results_mpl as results_mpl
+ from . import results_mpl as results_mpl
is_mpl = True # we have matplotlib support
except:
- print "WARNING: python matplotlib package not installed, no matplotlib plots."
+ print("WARNING: python matplotlib package not installed, no matplotlib plots.")
is_mpl = False
@@ -336,7 +336,7 @@ def refresh_widgets(self):
dependent on the availability of data.
"""
scenario = self.get_scenario()
- print 'prtgui.refresh_widgets', self._simulation != scenario.simulation
+ print('prtgui.refresh_widgets', self._simulation != scenario.simulation)
is_refresh = False
if self._simulation != scenario.simulation:
@@ -499,7 +499,7 @@ def on_clear_vehicles(self, event=None):
self._mainframe.browse_obj(self._prtservice.prtvehicles)
def on_mpl_stopresults(self, event=None):
- print 'on_mpl_stopresults', id(self._simulation.results) # ,id(self._prtservice.get_results())
+ print('on_mpl_stopresults', id(self._simulation.results)) # ,id(self._prtservice.get_results())
if self._prtservice is not None:
if self._simulation is not None:
resultplotter = results_mpl.StopresultsPlotter(self._simulation.results, # self._prtservice.get_results(),
diff --git a/tools/contributed/sumopy/sumopy_gui.py b/tools/contributed/sumopy/sumopy_gui.py
index f854df8b2a21..1b980416f7bc 100755
--- a/tools/contributed/sumopy/sumopy_gui.py
+++ b/tools/contributed/sumopy/sumopy_gui.py
@@ -40,13 +40,13 @@
wxversion.select("3")
except:
#sys.exit('ERROR: wxPython versions 2.8 or 3.x not available.')
- print 'No wxversion module available, try import default wx version'
- print 'If wx import shall fail, please install wxPython versions 2.8 or 3.x together with the wxversion module.'
+ print('No wxversion module available, try import default wx version')
+ print('If wx import shall fail, please install wxPython versions 2.8 or 3.x together with the wxversion module.')
sys.exit(0)
-from agilepy.lib_wx.mainframe import AgileMainframe
+from .agilepy.lib_wx.mainframe import AgileMainframe
import wx
__usage__ = """USAGE:
from command line:
@@ -65,20 +65,20 @@
use for debugging:
python sumopy_gui.py --debug > debug.txt 2>&1
"""
-print ' _ '
-print ' ____________|______|||___________________ '
-print ' / _ | / \ _ _ _ _ _ \ '
-print ' / | / | \ v / _ \ _|_|_|_|_ / '
-print ' \ __o-o__/ | \ \ | / / / \ \ ____/ '
-print ' \ / \|o|/ \ \|/ / / o/\ \ | _|__/_ '
-print ' \ / \|o|/ \ | / / /| \ \ | | | '
-print ' | | | | | / \|0|/ \ v / \_/ \_/ \_| | '
-print ' | | | | |/_____________\_/____________/ ____/ '
-print ' |/ '
-print ''
-print __appname__+' version '+__version__+'\n'+__copyright__
-
-print '\n using wx python version', wx.__version__
+print(' _ ')
+print(' ____________|______|||___________________ ')
+print(' / _ | / \ _ _ _ _ _ \ ')
+print(' / | / | \ v / _ \ _|_|_|_|_ / ')
+print(' \ __o-o__/ | \ \ | / / / \ \ ____/ ')
+print(' \ / \|o|/ \ \|/ / / o/\ \ | _|__/_ ')
+print(' \ / \|o|/ \ | / / /| \ \ | | | ')
+print(' | | | | | / \|0|/ \ v / \_/ \_/ \_| | ')
+print(' | | | | |/_____________\_/____________/ ____/ ')
+print(' |/ ')
+print('')
+print(__appname__+' version '+__version__+'\n'+__copyright__)
+
+print('\n using wx python version', wx.__version__)
###############################################################################
# IMPORTS