Skip to content

Commit

Permalink
fixing style for asserts and type checking, removing useless asserts, #…
Browse files Browse the repository at this point in the history
  • Loading branch information
behrisch committed Oct 20, 2024
1 parent f58b652 commit f9d7ea2
Show file tree
Hide file tree
Showing 30 changed files with 58 additions and 73 deletions.
5 changes: 1 addition & 4 deletions tests/complex/jtrrouter/randomized_flow/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,7 @@ def get_depart_lines(route_file):
output_file1 = 'output1.rou.xml'
output_file2 = 'output2.rou.xml'

jtrrouter = checkBinary('jtrrouter')
assert(jtrrouter)

args = [jtrrouter,
args = [checkBinary('jtrrouter'),
'--net-file', 'input_net.net.xml',
'--route-files', 'input_flows.flows.xml',
'--turn-ratio-files', 'input_turns.turns.xml',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,13 @@
net_output = 'joined.net.xml'
trips_output = 'trips.log'

netconvert = checkBinary('netconvert')
assert(netconvert)
sumo = checkBinary('sumo')
assert(sumo)

args_netc = [netconvert,
args_netc = [checkBinary('netconvert'),
'--node-files', 'input_nodes.nod.xml',
'--edge-files', 'input_edges.edg.xml',
'--output', net_output,
'--offset.disable-normalization']

args_sumo = [sumo,
args_sumo = [checkBinary('sumo'),
'--net-file', net_output,
'--route-files', 'input_routes.rou.xml',
'--end', '50',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,13 @@
net_output = 'joined.net.xml'
trips_output = 'trips.log'

netconvert = checkBinary('netconvert')
assert(netconvert)
sumo = checkBinary('sumo')
assert(sumo)

args_netc = [netconvert,
args_netc = [checkBinary('netconvert'),
'--node-files', 'input_nodes.nod.xml',
'--edge-files', 'input_edges.edg.xml',
'--output', net_output,
'--offset.disable-normalization']

args_sumo = [sumo,
args_sumo = [checkBinary('sumo'),
'--net-file', net_output,
'--route-files', 'input_routes.rou.xml',
'--end', '50',
Expand Down
8 changes: 4 additions & 4 deletions tests/complex/sumo/envVarSubstitution/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@

files = list(sorted(os.listdir(".")))
print("uncheck:", files, os.curdir)
assert(files[0].endswith(".trips.xml"))
assert(int(files[0][:-10]) > 0)
assert("collision.xml" in files)
assert(len(files) == 11)
assert files[0].endswith(".trips.xml")
assert int(files[0][:-10]) > 0
assert "collision.xml" in files
assert len(files) == 11
3 changes: 2 additions & 1 deletion tests/complex/sumo/output/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ def generateDetectorDef(out, freq, enableLoop, laneIDs):
if enableLoop:
print(' <e1Detector id="e1_%s" lane="%s" pos="200" freq="%s" file="detector.xml"/>' %
(laneId, laneId, freq), file=out)
print(""" <e2Detector id="e2_%s" lane="%s" pos="0" length="30000" friendlyPos="true" freq="%s" file="detector.xml"/>
print("""
<e2Detector id="e2_%s" lane="%s" pos="0" length="30000" friendlyPos="true" freq="%s" file="detector.xml"/>
<e3Detector id="e3_%s" freq="%s" file="detector.xml">
<detEntry lane="%s" pos="0"/>
<detExit lane="%s" pos="30000" friendlyPos="true"/>
Expand Down
2 changes: 1 addition & 1 deletion tests/complex/traas/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
java = os.path.join(os.environ['JAVA_HOME'], "bin", java)

traasJar = os.path.join(os.environ['SUMO_HOME'], "bin", "TraaS.jar")
assert (os.path.exists(traasJar))
assert os.path.exists(traasJar)

for f in sys.argv[1:]:
subprocess.check_call([javac, "-cp", traasJar, "-Xlint:unchecked", "data/%s.java" % f])
Expand Down
2 changes: 1 addition & 1 deletion tests/complex/traci/person/person/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def check(personID):
traci.simulationStep()

remaining = traci.person.getRemainingStages("p3")
assert(remaining == 1)
assert remaining == 1
# replace current stage
print_remaining_plan("p3", "(before replacement of current stage)")
traci.person.replaceStage("p3", 0, stage2)
Expand Down
2 changes: 1 addition & 1 deletion tests/complex/traci/trafficlight/actuated/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
if cand.programID == programID:
logic = cand

assert(logic)
assert logic
numPhases = len(logic.phases)
print("current program '%s' has %s phases" % (programID, numPhases))

Expand Down
4 changes: 2 additions & 2 deletions tests/complex/traci/vehicle/distance_after_reroute/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ def main(args):
print(traci.vehicle.getDistance('Stapler_00'))
traci.vehicle.setRoute('Stapler_00', ('ed1', 'ed5'))
print(traci.vehicle.getRoute('Stapler_00'))
# assert(traci.vehicle.getRoute('Stapler_00') == ('ed0', 'ed1', 'ed5'))
# assert traci.vehicle.getRoute('Stapler_00') == ('ed0', 'ed1', 'ed5')
print(traci.vehicle.getDistance('Stapler_00'))
if step == 122:
# assert(traci.vehicle.getRoute('Stapler_00') == ('ed0', 'ed1', 'ed5'))
# assert traci.vehicle.getRoute('Stapler_00') == ('ed0', 'ed1', 'ed5')
print(traci.vehicle.getDistance('Stapler_00'))
traci.vehicle.setRouteID('Stapler_00', "short")
print(traci.vehicle.getRoute('Stapler_00'))
Expand Down
2 changes: 1 addition & 1 deletion tests/complex/traci/vehicle/setStop/abort/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
while traci.simulation.getMinExpectedNumber() > 0:
if traci.vehicle.isStopped(vehID):
stop = traci.vehicle.getStops(vehID, 1)[0]
assert(stop.stoppingPlaceID != "")
assert stop.stoppingPlaceID != ""
traci.vehicle.setBusStop(vehID, stop.stoppingPlaceID, duration=0)
traci.simulationStep()
traci.close()
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
# only update duration once
if traci.vehicle.getParameter(vehID, "updated") != "1" and traci.vehicle.isStopped(vehID):
stop = traci.vehicle.getStops(vehID, 1)[0]
assert(stop.stoppingPlaceID != "")
assert stop.stoppingPlaceID != ""
traci.vehicle.setBusStop(vehID, stop.stoppingPlaceID, duration=60)
traci.vehicle.setParameter(vehID, "updated", "1")
stop2 = traci.vehicle.getStops(vehID, 1)[0]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
vehID = "ego"

stop = traci.vehicle.getStops(vehID, 1)[0]
assert(stop.stoppingPlaceID != "")
assert stop.stoppingPlaceID != ""
traci.vehicle.setBusStop(vehID, stop.stoppingPlaceID, duration=60)
stop2 = traci.vehicle.getStops(vehID, 1)[0]
print("new duration=%s" % stop2.duration)
Expand Down
2 changes: 1 addition & 1 deletion tests/complex/traci_java/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
traciJar = max(files, key=os.path.getmtime)
# print("traciJar", traciJar)

assert(os.path.exists(traciJar))
assert os.path.exists(traciJar)

for f in sys.argv[1:]:
fname = "data/%s.java" % f
Expand Down
2 changes: 1 addition & 1 deletion tools/countEdgeUsage.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def getEdges(elem, taz, routeDict):
if elem.edges:
edges = elem.edges.split()
if elem.route:
if type(elem.route) != list:
if not isinstance(elem.route, list):
# named route
edges = routeDict.get(elem.route, [])
if not edges:
Expand Down
2 changes: 1 addition & 1 deletion tools/detector/flowrouter.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ def splitRoutes(self, stubs, currEdge, upstreamBackEdges, newRoutes, alteredRout
else:
if DEBUG:
print(" trying to split", routeStub)
assert (len(currEdge.routes) > 0)
assert currEdge.routes
for route in currEdge.routes + currEdge.newRoutes:
if route.newFrequency == 0:
continue
Expand Down
6 changes: 3 additions & 3 deletions tools/detector/plotFlows.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def main(options):
for edge, group in detReader.getGroups():
if options.idfilter is not None and options.idfilter not in group.ids[0]:
continue
assert (len(group.timeline) <= len(data))
assert len(group.timeline) <= len(data)
for i, (flow, speed) in enumerate(group.timeline):
addToDataList(data, i, flow)
allData.append(data)
Expand All @@ -169,7 +169,7 @@ def main(options):
for edge, group in detReader.getGroups():
if options.idfilter is not None and options.idfilter not in group.ids[0]:
continue
assert (len(group.timeline) <= len(data))
assert len(group.timeline) <= len(data)
if group.type == detType:
for i, (flow, speed) in enumerate(group.timeline):
addToDataList(data, i, flow)
Expand All @@ -186,7 +186,7 @@ def main(options):
continue
if options.idfilter is not None and options.idfilter not in group.ids[0]:
continue
assert (len(group.timeline) <= len(data))
assert len(group.timeline) <= len(data)
for i, (flow, speed) in enumerate(group.timeline):
addToDataList(data, i, flow)
allData.append(data)
Expand Down
2 changes: 1 addition & 1 deletion tools/district/stationDistricts.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def assignByDistance(options, net, stations):
edgeStation = dict()
for station in stations.values():
for edge in station.edges:
assert (edge not in edgeStation or not options.merge)
assert edge not in edgeStation or not options.merge
edgeStation[edge] = station.name

remaining = set()
Expand Down
2 changes: 1 addition & 1 deletion tools/import/citybrain/citybrain_road.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def main(options):

code = connections[edgeID]
lanes = edge.getLanes()
assert (len(code) == len(lanes) * 3)
assert len(code) == len(lanes) * 3
for laneIndex, lane in enumerate(lanes):
for index in [0, 1, 2]:
if code[3 * laneIndex + index] == 1:
Expand Down
6 changes: 3 additions & 3 deletions tools/net/net2jpsgeometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def __init__(self,
shape=None,
parentPolygon=None,
atLengthsOfParent=None):
assert (len(shape) == 2), "expected two positions for door (got %d instead)" % len(shape) # noqa
assert len(shape) == 2, "expected two positions for door (got %d instead)" % len(shape)
self._id = id
self._shape = shape
self._width = sumolib.geomhelper.polyLength(shape)
Expand Down Expand Up @@ -121,7 +121,7 @@ def calculateBoundingPolygon(shape, width):


def addInOutLaneToDoorList(polygon, inOutLane, net, doorInfoList, direction='in'):
assert (direction == 'in' or direction == 'out')
assert direction == 'in' or direction == 'out'
lane = net.getLane(polygon.attributes[KEY_SUMO_ID])
if DEBUG:
print("DEBUG: lane (%s) \'%s\' for current lane \'%s\'" % (direction, inOutLane.getID(), lane.getID()))
Expand Down Expand Up @@ -178,7 +178,7 @@ def subtractDoorsFromPolygon(polygon, doorInfoList):
print("DEBUG: doorInfo._atLengthsOfParent:", doorInfo._atLengthsOfParent)
len1 = doorInfo._atLengthsOfParent[0]
len2 = doorInfo._atLengthsOfParent[-1]
assert (len1 < len2), "len1 should be smaller than len2 (len1=%d, len2=%d)" % (len1, len2) # noqa
assert len1 < len2, "len1 should be smaller than len2 (len1=%d, len2=%d)" % (len1, len2)
if len2 - len1 > doorInfo._width:
# corner case with inversely oriented door and closed parent polygon
len1 = len2
Expand Down
18 changes: 9 additions & 9 deletions tools/osmWebWizard.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,13 @@ def getParams(vClass, prefix=None):
vehicleParameters = {
"passenger": CP + getParams("passenger", "veh") + ["--min-distance", "300", "--min-distance.fringe", "10",
"--allow-fringe.min-length", "1000", "--lanes"],
"truck": CP + getParams("truck") + ["--min-distance", "600", "--min-distance.fringe", "10"], # noqa
"bus": CP + getParams("bus") + ["--min-distance", "600", "--min-distance.fringe", "10"], # noqa
"motorcycle": CP + getParams("motorcycle") + ["--max-distance", "1200"], # noqa
"bicycle": CP + getParams("bicycle", "bike") + ["--max-distance", "8000"], # noqa
"tram": CP + getParams("tram") + ["--min-distance", "1200", "--min-distance.fringe", "10"], # noqa
"rail_urban": CP + getParams("rail_urban") + ["--min-distance", "1800", "--min-distance.fringe", "10"], # noqa
"rail": CP + getParams("rail") + ["--min-distance", "2400", "--min-distance.fringe", "10"], # noqa
"truck": CP + getParams("truck") + ["--min-distance", "600", "--min-distance.fringe", "10"], # noqa
"bus": CP + getParams("bus") + ["--min-distance", "600", "--min-distance.fringe", "10"], # noqa
"motorcycle": CP + getParams("motorcycle") + ["--max-distance", "1200"], # noqa
"bicycle": CP + getParams("bicycle", "bike") + ["--max-distance", "8000"], # noqa
"tram": CP + getParams("tram") + ["--min-distance", "1200", "--min-distance.fringe", "10"], # noqa
"rail_urban": CP + getParams("rail_urban") + ["--min-distance", "1800", "--min-distance.fringe", "10"], # noqa
"rail": CP + getParams("rail") + ["--min-distance", "2400", "--min-distance.fringe", "10"], # noqa
"ship": getParams("ship") + ["--fringe-start-attributes", 'departSpeed="max"', "--validate"],
"pedestrian": PP + ["--pedestrians", "--max-distance", "2000"],
"persontrips": PP + ["--persontrips", "--trip-attributes", 'modes="public"'],
Expand All @@ -121,9 +121,9 @@ def getParams(vClass, prefix=None):


def quoted_str(s):
if type(s) == float:
if isinstance(s, float):
return "%.6f" % s
elif type(s) != str:
elif not isinstance(s, str):
return str(s)
elif '"' in s or ' ' in s:
return '"' + s.replace('"', '\\"') + '"'
Expand Down
2 changes: 1 addition & 1 deletion tools/purgatory/dijkstra.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ def _getEdge(self, *ids):
"""retrieves edge objects based on their ids"""
result = []
for id in ids:
if type(id) == str:
if isinstance(id, str):
if self.net.hasEdge(id):
result.append(self.net.getEdge(id))
else:
Expand Down
9 changes: 5 additions & 4 deletions tools/route/driveways2poly.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from __future__ import absolute_import
import sys
import os
import random
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import sumolib # noqa
import route2poly # noqa
Expand Down Expand Up @@ -70,6 +71,7 @@ def parse_args(args=None):

return options


def getDriveWays(fname):
for rs in sumolib.xml.parse(fname, "railSignal"):
for link in rs.link:
Expand All @@ -78,9 +80,8 @@ def getDriveWays(fname):
for dw in link.driveWay:
yield rs.id, dw
for dj in sumolib.xml.parse(fname, "departJunction"):
for dw in dj.driveWay:
yield dj.id, dw

for dw in dj.driveWay:
yield dj.id, dw


def main(options):
Expand All @@ -94,7 +95,6 @@ def main(options):
if dw.id in options.filterFoes:
permittedFoes.update(dw.foes[0].driveWays.split())


with open(options.output, 'w') as outf:
sumolib.xml.writeHeader(outf, root='polygons', rootAttrs=None, options=options)
for signal, dw in getDriveWays(options.driveways):
Expand All @@ -107,5 +107,6 @@ def main(options):
route2poly.generate_poly(options, net, dw.id, colorgen(), dw.edges.split(), outf)
outf.write('</polygons>\n')


if __name__ == "__main__":
main(parse_args())
4 changes: 2 additions & 2 deletions tools/route/route2OD.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def addVehicle(vehID, fromEdge, toEdge, time, count=1, isTaz=False):
nl.end = max(nl.end, time)

for vehicle in sumolib.xml.parse(options.routefile, ['vehicle']):
if vehicle.route and type(vehicle.route) == list:
if vehicle.route and isinstance(vehicle.route, list):
edges = vehicle.route[0].edges.split()
addVehicle(vehicle.id, edges[0], edges[-1], parseTime(vehicle.depart))
else:
Expand Down Expand Up @@ -187,7 +187,7 @@ def addVehicle(vehID, fromEdge, toEdge, time, count=1, isTaz=False):
count = 1
if flow.attr_from and flow.to:
addVehicle(flow.id, flow.attr_from, flow.to, parseTime(flow.begin), count)
elif flow.route and type(flow.route) == list:
elif flow.route and isinstance(flow.route, list):
edges = flow.route[0].edges.split()
addVehicle(flow.id, edges[0], edges[-1], parseTime(flow.begin), count)
elif flow.fromTaz and flow.toTaz:
Expand Down
2 changes: 2 additions & 0 deletions tools/route/route2poly.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,14 @@ def getSpread(lanes, positive=False):
# print(i, [l.getID() for l in lanes])
assert False


def hasBidi(lanes):
for lane in lanes:
if lane.getEdge().getBidi():
return True
return False


def generate_poly(options, net, id, color, edges, outf, type="route", lineWidth=None, params=None):
if params is None:
params = {}
Expand Down
3 changes: 1 addition & 2 deletions tools/route/routeStats.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ def get_options():
def main():
options = get_options()
net = None
attribute_retriever = None
if options.attribute == "length":
net = sumolib.net.readNet(options.network)

Expand All @@ -94,7 +93,7 @@ def attribute_retriever(vehicle):
def attribute_retriever(vehicle):
return 3.6 * float(vehicle.routeLength) / (parseTime(vehicle.arrival) - parseTime(vehicle.depart))
else:
sys.exit("Invalid value '%s' for option --attribute" % options.attribute)
raise ValueError("Invalid value '%s' for option --attribute" % options.attribute)

lengths = {}
lengths2 = {}
Expand Down
Loading

0 comments on commit f9d7ea2

Please sign in to comment.