From 7972f4d794bcf15f0f8bab51937813d96dbf0062 Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Fri, 23 Nov 2018 13:53:20 +0100 Subject: [PATCH 01/13] Changed code structure --- sumo_project/actions.py | 86 +++++++++++++++++++-------------------- sumo_project/config.py | 57 ++++++++++++++------------ sumo_project/emissions.py | 33 ++++++++------- 3 files changed, 91 insertions(+), 85 deletions(-) diff --git a/sumo_project/actions.py b/sumo_project/actions.py index 7c61488..298ebe2 100644 --- a/sumo_project/actions.py +++ b/sumo_project/actions.py @@ -1,44 +1,42 @@ -""" -Created on 17 oct. 2018 - -@author: Axel Huynh-Phuc, Thibaud Gasser -""" -from typing import Iterable - -import traci -from shapely.geometry.linestring import LineString - -from model import Area, Vehicle - - -def remove_vehicle(veh_id): - traci.vehicle.remove(veh_id, traci.constants.REMOVE_PARKING) - - -def lanes_in_area(area): - for lane_id in traci.lane.getIDList(): - polygon_lane = LineString(traci.lane.getShape(lane_id)) - if area.rectangle.intersects(polygon_lane): - yield lane_id - - -def compute_edge_weight(edge_id): - return (traci.edge.getCOEmission(edge_id) - + traci.edge.getNOxEmission(edge_id) - + traci.edge.getHCEmission(edge_id) - + traci.edge.getPMxEmission(edge_id) - + traci.edge.getCO2Emission(edge_id)) - - -def adjust_edges_weights(): - for edge_id in traci.edge.getIDList(): - weight = compute_edge_weight(edge_id) # by default edges weight = length/mean speed - traci.edge.adaptTraveltime(edge_id, weight) - - -def lock_area(area: Area): - max_speed = 30 - print(f'Setting max speed into {area.name} to {max_speed} km/h') - area.locked = True - for lane in area._lanes: - traci.lane.setMaxSpeed(lane.lane_id, max_speed / 3.6) +""" +Created on 17 oct. 2018 + +@author: Axel Huynh-Phuc, Thibaud Gasser +""" +from typing import Iterable + +import traci +from shapely.geometry.linestring import LineString + +from model import Area, Vehicle + + +def remove_vehicle(veh_id): + traci.vehicle.remove(veh_id, traci.constants.REMOVE_PARKING) + + +def compute_edge_weight(edge_id): + return (traci.edge.getCOEmission(edge_id) + + traci.edge.getNOxEmission(edge_id) + + traci.edge.getHCEmission(edge_id) + + traci.edge.getPMxEmission(edge_id) + + traci.edge.getCO2Emission(edge_id)) + + +def adjust_edges_weights(): + for edge_id in traci.edge.getIDList(): + weight = compute_edge_weight(edge_id) # by default edges weight = length/mean speed + traci.edge.adaptTraveltime(edge_id, weight) + + +def limit_speed_into_area(area: Area, vehicles: Iterable[Vehicle], max_speed): + print(f'Setting max speed into {area.name} to {max_speed} km/h') + area.locked = True + for lane in area._lanes: + traci.lane.setMaxSpeed(lane.lane_id, max_speed/3.6) + + +def adjust_traffic_light_phase_duration(): + '''for tl_id in traci.trafficlight.getIDList(): + print(traci.trafficlight.getCompleteRedYellowGreenDefinition(tl_id))''' + \ No newline at end of file diff --git a/sumo_project/config.py b/sumo_project/config.py index a27bd0f..5b1beb8 100644 --- a/sumo_project/config.py +++ b/sumo_project/config.py @@ -1,26 +1,31 @@ -""" -Global configuration for the simulation -""" - -import os -import sys - -if 'SUMO_HOME' in os.environ: - tools = os.path.join(os.environ['SUMO_HOME'], 'tools') - sys.path.append(tools) -else: - sys.exit("please declare environment variable 'SUMO_HOME'") - -_SUMOCMD = 'sumo' # use 'sumo-gui' cmd for UI -_SUMOCFG = "mulhouse_simulation/osm.sumocfg" -CELLS_NUMBER = 10 -EMISSIONS_THRESHOLD = 500000 -n_steps = 200 - -lock_mode = True -routing_mode = False - -sumo_binary = os.path.join(os.environ['SUMO_HOME'], 'bin', _SUMOCMD) -sumo_cmd = [sumo_binary, "-c", _SUMOCFG] - - +""" +Global configuration for the simulation +""" + +import os +import sys + +if 'SUMO_HOME' in os.environ: + tools = os.path.join(os.environ['SUMO_HOME'], 'tools') + sys.path.append(tools) +else: + sys.exit("please declare environment variable 'SUMO_HOME'") + +_SUMOCMD = 'sumo' # use 'sumo-gui' cmd for UI +_SUMOCFG = "mulhouse_simulation/osm.sumocfg" +CELLS_NUMBER = 10 +EMISSIONS_THRESHOLD = 500000 +n_steps = 200 + +lock_mode = True +routing_mode = False + +sumo_binary = os.path.join(os.environ['SUMO_HOME'], 'bin', _SUMOCMD) +sumo_cmd = [sumo_binary, "-c", _SUMOCFG] + +def showConfig(): + return (str(f'Grid : {CELLS_NUMBER}x{CELLS_NUMBER}\n') + + str(f'step number = {n_steps}\n') + + str(f'lock mode = {lock_mode}\n') + + str(f'routing mode = {routing_mode}\n')) + diff --git a/sumo_project/emissions.py b/sumo_project/emissions.py index 2c390c7..f199357 100644 --- a/sumo_project/emissions.py +++ b/sumo_project/emissions.py @@ -39,7 +39,6 @@ def get_all_vehicles() -> List[Vehicle]: veh_pos = traci.vehicle.getPosition(veh_id) vehicle = Vehicle(veh_id, veh_pos) vehicle.emissions = compute_vehicle_emissions(veh_id) - traci.vehicle.setRoutingMode(veh_id, traci.constants.ROUTING_MODE_AGGREGATED) vehicles.append(vehicle) return vehicles @@ -58,7 +57,7 @@ def get_emissions(grid: List[Area], vehicles: List[Vehicle]): if vehicle.pos in area: area.emissions += vehicle.emissions if config.lock_mode and area.emissions > config.EMISSIONS_THRESHOLD and not area.locked: - actions.lock_area(area) + actions.limit_speed_into_area(area, vehicles,30) traci.polygon.setColor(area.name, (255, 0, 0)) traci.polygon.setFilled(area.name, True) @@ -77,9 +76,11 @@ def main(): traci.start(config.sumo_cmd) grid = init_grid(traci.simulation.getNetBoundary(), config.CELLS_NUMBER) add_lanes_to_areas(grid) - - step = 0 - while step < config.n_steps: # traci.simulation.getMinExpectedNumber() > 0: + + actions.adjust_traffic_light_phase_duration() + + step = 0 + while step < config.n_steps : #traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() vehicles = get_all_vehicles() @@ -90,7 +91,8 @@ def main(): # actions.rerouteAllVehicles() step += 1 - sys.stdout.write(f'Simulation step = {step}/{config.n_steps}' + '\r') + progress = round(step/config.n_steps*100,2) + sys.stdout.write(f'Progress : {progress}%'+'\r') sys.stdout.flush() finally: @@ -99,14 +101,15 @@ def main(): total_emissions = 0 for area in grid: total_emissions += area.emissions - - # Total of emissions of all pollutants in mg for 200 steps of simulation without locking areas - total_emissions200 = 43970763.15084749 - - print(f'\n**** Total emissions = {total_emissions} mg ****') - diff_with_lock = (total_emissions200 - total_emissions) / total_emissions200 - print(f'**** Reduction percentage of emissions = {diff_with_lock*100} % ****\n') - - + + #Total of emissions of all pollutants in mg for 200 steps of simulation without locking areas + total_emissions200 = 43970763.15084749 + + print("\n**** RESULTS ****") + print(f'Total emissions = {total_emissions} mg') + diff_with_lock = (total_emissions200 - total_emissions)/total_emissions200 + print(f'Reduction percentage of emissions = {diff_with_lock*100} %') + print("With the configuration :\n" + str(config.showConfig())) + if __name__ == '__main__': main() From 0df0897c7206d14c96cba9767a7b4016be8ddf9c Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Fri, 23 Nov 2018 14:40:47 +0100 Subject: [PATCH 02/13] Added TrafficLight model and actions on traffic lights --- sumo_project/actions.py | 8 +- sumo_project/emissions.py | 236 +++++++++++++++++++------------------- sumo_project/model.py | 141 ++++++++++++----------- 3 files changed, 203 insertions(+), 182 deletions(-) diff --git a/sumo_project/actions.py b/sumo_project/actions.py index 298ebe2..a0f6df9 100644 --- a/sumo_project/actions.py +++ b/sumo_project/actions.py @@ -36,7 +36,9 @@ def limit_speed_into_area(area: Area, vehicles: Iterable[Vehicle], max_speed): traci.lane.setMaxSpeed(lane.lane_id, max_speed/3.6) -def adjust_traffic_light_phase_duration(): - '''for tl_id in traci.trafficlight.getIDList(): - print(traci.trafficlight.getCompleteRedYellowGreenDefinition(tl_id))''' +def adjust_traffic_light_phase_duration(area,reduction_factor): + for tl in area._tls: + phaseDuration = traci.trafficlight.getPhaseDuration(tl.tl_id) + traci.trafficlight.setPhaseDuration(tl.tl_id, phaseDuration*reduction_factor) + \ No newline at end of file diff --git a/sumo_project/emissions.py b/sumo_project/emissions.py index f199357..c4f7742 100644 --- a/sumo_project/emissions.py +++ b/sumo_project/emissions.py @@ -1,115 +1,121 @@ -from typing import List - -import traci -from shapely.geometry import LineString - -import actions -import config -import sys -from model import Area, Vehicle, Lane - - -def init_grid(simulation_bounds, cells_number): - grid = list() - width = simulation_bounds[1][0] / cells_number - height = simulation_bounds[1][1] / cells_number - for i in range(cells_number): - for j in range(cells_number): - # bounds coordinates for the area : (xmin, ymin, xmax, ymax) - ar_bounds = ((i * width, j * height), (i * width, (j + 1) * height), - ((i + 1) * width, (j + 1) * height), ((i + 1) * width, j * height)) - area = Area(ar_bounds) - area.name = 'area ({},{})'.format(i, j) - grid.append(area) - traci.polygon.add(area.name, ar_bounds, (0, 255, 0)) - return grid - - -def compute_vehicle_emissions(veh_id): - return (traci.vehicle.getCOEmission(veh_id) - + traci.vehicle.getNOxEmission(veh_id) - + traci.vehicle.getHCEmission(veh_id) - + traci.vehicle.getPMxEmission(veh_id) - + traci.vehicle.getCO2Emission(veh_id)) - - -def get_all_vehicles() -> List[Vehicle]: - vehicles = list() - for veh_id in traci.vehicle.getIDList(): - veh_pos = traci.vehicle.getPosition(veh_id) - vehicle = Vehicle(veh_id, veh_pos) - vehicle.emissions = compute_vehicle_emissions(veh_id) - vehicles.append(vehicle) - return vehicles - - -def get_all_lanes() -> List[Lane]: - lanes = [] - for lane_id in traci.lane.getIDList(): - polygon_lane = LineString(traci.lane.getShape(lane_id)) - lanes.append(Lane(lane_id, polygon_lane)) - return lanes - - -def get_emissions(grid: List[Area], vehicles: List[Vehicle]): - for area in grid: - for vehicle in vehicles: - if vehicle.pos in area: - area.emissions += vehicle.emissions - if config.lock_mode and area.emissions > config.EMISSIONS_THRESHOLD and not area.locked: - actions.limit_speed_into_area(area, vehicles,30) - traci.polygon.setColor(area.name, (255, 0, 0)) - traci.polygon.setFilled(area.name, True) - - -def add_lanes_to_areas(areas: List[Area]): - lanes = get_all_lanes() - for area in areas: - for lane in lanes: - if area.rectangle.intersects(lane.polygon): - area.add_lane(lane) - - -def main(): - grid = list() - try: - traci.start(config.sumo_cmd) - grid = init_grid(traci.simulation.getNetBoundary(), config.CELLS_NUMBER) - add_lanes_to_areas(grid) - - actions.adjust_traffic_light_phase_duration() - - step = 0 - while step < config.n_steps : #traci.simulation.getMinExpectedNumber() > 0: - traci.simulationStep() - - vehicles = get_all_vehicles() - get_emissions(grid, vehicles) - - if config.routing_mode: - actions.adjust_edges_weights() - # actions.rerouteAllVehicles() - - step += 1 - progress = round(step/config.n_steps*100,2) - sys.stdout.write(f'Progress : {progress}%'+'\r') - sys.stdout.flush() - - finally: - traci.close(False) - - total_emissions = 0 - for area in grid: - total_emissions += area.emissions - - #Total of emissions of all pollutants in mg for 200 steps of simulation without locking areas - total_emissions200 = 43970763.15084749 - - print("\n**** RESULTS ****") - print(f'Total emissions = {total_emissions} mg') - diff_with_lock = (total_emissions200 - total_emissions)/total_emissions200 - print(f'Reduction percentage of emissions = {diff_with_lock*100} %') - print("With the configuration :\n" + str(config.showConfig())) - -if __name__ == '__main__': - main() +from typing import List + +import traci +from shapely.geometry import LineString + +import actions +import config +import sys +from model import Area, Vehicle, Lane , TrafficLight +from traci import trafficlight + + +def init_grid(simulation_bounds, cells_number): + grid = list() + width = simulation_bounds[1][0] / cells_number + height = simulation_bounds[1][1] / cells_number + for i in range(cells_number): + for j in range(cells_number): + # bounds coordinates for the area : (xmin, ymin, xmax, ymax) + ar_bounds = ((i * width, j * height), (i * width, (j + 1) * height), + ((i + 1) * width, (j + 1) * height), ((i + 1) * width, j * height)) + area = Area(ar_bounds) + area.name = 'area ({},{})'.format(i, j) + grid.append(area) + traci.polygon.add(area.name, ar_bounds, (0, 255, 0)) + return grid + + +def compute_vehicle_emissions(veh_id): + return (traci.vehicle.getCOEmission(veh_id) + + traci.vehicle.getNOxEmission(veh_id) + + traci.vehicle.getHCEmission(veh_id) + + traci.vehicle.getPMxEmission(veh_id) + + traci.vehicle.getCO2Emission(veh_id)) + + +def get_all_vehicles() -> List[Vehicle]: + vehicles = list() + for veh_id in traci.vehicle.getIDList(): + veh_pos = traci.vehicle.getPosition(veh_id) + vehicle = Vehicle(veh_id, veh_pos) + vehicle.emissions = compute_vehicle_emissions(veh_id) + vehicles.append(vehicle) + return vehicles + + +def get_all_lanes() -> List[Lane]: + lanes = [] + for lane_id in traci.lane.getIDList(): + polygon_lane = LineString(traci.lane.getShape(lane_id)) + lanes.append(Lane(lane_id, polygon_lane)) + return lanes + + +def get_emissions(grid: List[Area], vehicles: List[Vehicle]): + for area in grid: + for vehicle in vehicles: + if vehicle.pos in area: + area.emissions += vehicle.emissions + if config.lock_mode and area.emissions > config.EMISSIONS_THRESHOLD and not area.locked: + + actions.limit_speed_into_area(area, vehicles,30) + actions.adjust_traffic_light_phase_duration(area, 0.5) + + traci.polygon.setColor(area.name, (255, 0, 0)) + traci.polygon.setFilled(area.name, True) + + +def add_data_to_areas(areas: List[Area]): + lanes = get_all_lanes() + for area in areas: + for lane in lanes: + if area.rectangle.intersects(lane.polygon): + area.add_lane(lane) + for tl_id in traci.trafficlight.getIDList(): + if lane.lane_id in traci.trafficlight.getControlledLanes(tl_id): + area.add_tl(TrafficLight(tl_id)) + + + +def main(): + grid = list() + try: + traci.start(config.sumo_cmd) + grid = init_grid(traci.simulation.getNetBoundary(), config.CELLS_NUMBER) + add_data_to_areas(grid) + + step = 0 + while step < config.n_steps : #traci.simulation.getMinExpectedNumber() > 0: + traci.simulationStep() + + vehicles = get_all_vehicles() + get_emissions(grid, vehicles) + + if config.routing_mode: + actions.adjust_edges_weights() + # actions.rerouteAllVehicles() + + step += 1 + progress = round(step/config.n_steps*100,2) + sys.stdout.write(f'Progress : {progress}%'+'\r') + sys.stdout.flush() + + finally: + traci.close(False) + + total_emissions = 0 + for area in grid: + total_emissions += area.emissions + + #Total of emissions of all pollutants in mg for 200 steps of simulation without locking areas + total_emissions200 = 43970763.15084749 + + print("\n**** RESULTS ****") + print(f'Total emissions = {total_emissions} mg') + diff_with_lock = (total_emissions200 - total_emissions)/total_emissions200 + print(f'Reduction percentage of emissions = {diff_with_lock*100} %') + print("With the configuration :\n" + str(config.showConfig())) + +if __name__ == '__main__': + main() diff --git a/sumo_project/model.py b/sumo_project/model.py index 3fe8afc..9c3e9eb 100644 --- a/sumo_project/model.py +++ b/sumo_project/model.py @@ -1,64 +1,77 @@ -from typing import Tuple, Set - -from shapely.geometry import Point, LineString -from shapely.geometry import Polygon -from shapely.geometry.base import BaseGeometry - - -class Lane: - - def __init__(self, lane_id: str, polygon: LineString): - self.polygon = polygon - self.lane_id = lane_id - - def __hash__(self): - """Overrides the default implementation""" - return hash(self.lane_id) - - -class Area: - - def __init__(self, coords, name=''): - self.locked = False - self.rectangle = Polygon(coords) - self.name = name - self.emissions = 0.0 - self._lanes: Set[Lane] = set() - - def __eq__(self, other): - return self.rectangle.__eq__(other) - - def __contains__(self, item): - return self.rectangle.contains(item) - - @property - def bounds(self): - return self.rectangle.bounds - - def intersects(self, other: BaseGeometry) -> bool: - return self.rectangle.intersects(other) - - def add_lane(self, lane: Lane): - self._lanes.add(lane) - - def remove_lane(self, lane: Lane): - self._lanes.remove(lane) - - @classmethod - def from_bounds(cls, xmin, ymin, xmax, ymax): - return cls(( - (xmin, ymin), - (xmin, ymax), - (xmax, ymax), - (xmax, ymin))) - - -class Vehicle: - - def __init__(self, veh_id: int, pos: Tuple[float, float]): - self.emissions: float = 0.0 - self.veh_id = veh_id - self.pos = Point(pos) - - def __repr__(self) -> str: - return str(self.__dict__) +from typing import Tuple, Set + +from shapely.geometry import Point, LineString +from shapely.geometry import Polygon +from shapely.geometry.base import BaseGeometry + + +class Lane: + + def __init__(self, lane_id: str, polygon: LineString): + self.polygon = polygon + self.lane_id = lane_id + + def __hash__(self): + """Overrides the default implementation""" + return hash(self.lane_id) + +class TrafficLight: + + def __init__(self, tl_id: str): + self.tl_id = tl_id + + def __hash__(self): + """Overrides the default implementation""" + return hash(self.tl_id) + + +class Area: + + def __init__(self, coords, name=''): + self.locked = False + self.rectangle = Polygon(coords) + self.name = name + self.emissions = 0.0 + self._lanes: Set[Lane] = set() + self._tls: Set[TrafficLight] = set() + + def __eq__(self, other): + return self.rectangle.__eq__(other) + + def __contains__(self, item): + return self.rectangle.contains(item) + + @property + def bounds(self): + return self.rectangle.bounds + + def intersects(self, other: BaseGeometry) -> bool: + return self.rectangle.intersects(other) + + def add_lane(self, lane: Lane): + self._lanes.add(lane) + + def add_tl(self, tl: TrafficLight): + self._tls.add(tl) + + def remove_lane(self, lane: Lane): + self._lanes.remove(lane) + + @classmethod + def from_bounds(cls, xmin, ymin, xmax, ymax): + return cls(( + (xmin, ymin), + (xmin, ymax), + (xmax, ymax), + (xmax, ymin))) + + +class Vehicle: + + def __init__(self, veh_id: int, pos: Tuple[float, float]): + self.emissions: float = 0.0 + self.veh_id = veh_id + self.pos = Point(pos) + + def __repr__(self) -> str: + return str(self.__dict__) From 9a964c97e9469e30fa02411da03b51181029b8c1 Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Fri, 23 Nov 2018 19:40:14 +0100 Subject: [PATCH 03/13] Added initial max speed information into Lane class --- sumo_project/actions.py | 1 - sumo_project/config.py | 10 ++++++---- sumo_project/emissions.py | 19 +++++++++---------- sumo_project/model.py | 3 ++- 4 files changed, 17 insertions(+), 16 deletions(-) diff --git a/sumo_project/actions.py b/sumo_project/actions.py index a0f6df9..5453e1b 100644 --- a/sumo_project/actions.py +++ b/sumo_project/actions.py @@ -22,7 +22,6 @@ def compute_edge_weight(edge_id): + traci.edge.getPMxEmission(edge_id) + traci.edge.getCO2Emission(edge_id)) - def adjust_edges_weights(): for edge_id in traci.edge.getIDList(): weight = compute_edge_weight(edge_id) # by default edges weight = length/mean speed diff --git a/sumo_project/config.py b/sumo_project/config.py index 5b1beb8..ae002a2 100644 --- a/sumo_project/config.py +++ b/sumo_project/config.py @@ -17,8 +17,9 @@ CELLS_NUMBER = 10 EMISSIONS_THRESHOLD = 500000 n_steps = 200 -lock_mode = True -routing_mode = False +limit_speed_mode = True +weight_routing_mode = False +adjust_traffic_light_mode = True sumo_binary = os.path.join(os.environ['SUMO_HOME'], 'bin', _SUMOCMD) sumo_cmd = [sumo_binary, "-c", _SUMOCFG] @@ -26,6 +27,7 @@ sumo_cmd = [sumo_binary, "-c", _SUMOCFG] def showConfig(): return (str(f'Grid : {CELLS_NUMBER}x{CELLS_NUMBER}\n') + str(f'step number = {n_steps}\n') - + str(f'lock mode = {lock_mode}\n') - + str(f'routing mode = {routing_mode}\n')) + + str(f'limit speed mode = {limit_speed_mode}\n') + + str(f'weight routing mode= {weight_routing_mode}\n') + + str(f'adjust traffic light mode = {adjust_traffic_light_mode}\n')) diff --git a/sumo_project/emissions.py b/sumo_project/emissions.py index c4f7742..ad461e8 100644 --- a/sumo_project/emissions.py +++ b/sumo_project/emissions.py @@ -48,7 +48,8 @@ def get_all_lanes() -> List[Lane]: lanes = [] for lane_id in traci.lane.getIDList(): polygon_lane = LineString(traci.lane.getShape(lane_id)) - lanes.append(Lane(lane_id, polygon_lane)) + initial_max_speed = traci.lane.getMaxSpeed(lane_id) + lanes.append(Lane(lane_id, polygon_lane,initial_max_speed)) return lanes @@ -57,22 +58,21 @@ def get_emissions(grid: List[Area], vehicles: List[Vehicle]): for vehicle in vehicles: if vehicle.pos in area: area.emissions += vehicle.emissions - if config.lock_mode and area.emissions > config.EMISSIONS_THRESHOLD and not area.locked: - + if config.limit_speed_mode and area.emissions > config.EMISSIONS_THRESHOLD and not area.locked: actions.limit_speed_into_area(area, vehicles,30) - actions.adjust_traffic_light_phase_duration(area, 0.5) - traci.polygon.setColor(area.name, (255, 0, 0)) traci.polygon.setFilled(area.name, True) + if config.adjust_traffic_light_mode: + actions.adjust_traffic_light_phase_duration(area, 0.75) def add_data_to_areas(areas: List[Area]): lanes = get_all_lanes() for area in areas: - for lane in lanes: + for lane in lanes: #add lanes if area.rectangle.intersects(lane.polygon): - area.add_lane(lane) - for tl_id in traci.trafficlight.getIDList(): + area.add_lane(lane) + for tl_id in traci.trafficlight.getIDList(): #add traffic lights if lane.lane_id in traci.trafficlight.getControlledLanes(tl_id): area.add_tl(TrafficLight(tl_id)) @@ -92,9 +92,8 @@ def main(): vehicles = get_all_vehicles() get_emissions(grid, vehicles) - if config.routing_mode: + if config.weight_routing_mode: actions.adjust_edges_weights() - # actions.rerouteAllVehicles() step += 1 progress = round(step/config.n_steps*100,2) diff --git a/sumo_project/model.py b/sumo_project/model.py index 9c3e9eb..5a90846 100644 --- a/sumo_project/model.py +++ b/sumo_project/model.py @@ -7,9 +7,10 @@ from shapely.geometry.base import BaseGeometry class Lane: - def __init__(self, lane_id: str, polygon: LineString): + def __init__(self, lane_id: str, polygon: LineString, initial_max_speed: float): self.polygon = polygon self.lane_id = lane_id + self.initial_max_speed = initial_max_speed def __hash__(self): """Overrides the default implementation""" From 635004bcb9444aa52db3e7475611ff55d5dc14f3 Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Thu, 29 Nov 2018 11:48:07 +0100 Subject: [PATCH 04/13] Added logic program list into trafic lights --- sumo_project/actions.py | 16 ++++++++++------ sumo_project/emissions.py | 3 ++- sumo_project/model.py | 6 ++++-- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/sumo_project/actions.py b/sumo_project/actions.py index 5453e1b..739a8cb 100644 --- a/sumo_project/actions.py +++ b/sumo_project/actions.py @@ -9,12 +9,12 @@ import traci from shapely.geometry.linestring import LineString from model import Area, Vehicle +from traci._trafficlight import Logic def remove_vehicle(veh_id): traci.vehicle.remove(veh_id, traci.constants.REMOVE_PARKING) - def compute_edge_weight(edge_id): return (traci.edge.getCOEmission(edge_id) + traci.edge.getNOxEmission(edge_id) @@ -27,17 +27,21 @@ def adjust_edges_weights(): weight = compute_edge_weight(edge_id) # by default edges weight = length/mean speed traci.edge.adaptTraveltime(edge_id, weight) - def limit_speed_into_area(area: Area, vehicles: Iterable[Vehicle], max_speed): print(f'Setting max speed into {area.name} to {max_speed} km/h') area.locked = True for lane in area._lanes: traci.lane.setMaxSpeed(lane.lane_id, max_speed/3.6) - + + def adjust_traffic_light_phase_duration(area,reduction_factor): - for tl in area._tls: - phaseDuration = traci.trafficlight.getPhaseDuration(tl.tl_id) - traci.trafficlight.setPhaseDuration(tl.tl_id, phaseDuration*reduction_factor) + tl_first = area._tls[0] + #phaseDuration = traci.trafficlight.getPhaseDuration(tl.tl_id) + #traci.trafficlight.setPhaseDuration(tl.tl_id, phaseDuration*reduction_factor) + first_logic = tl_first._logics[0] + print('first logic of tl_first : ' + first_logic) + + first_logic = Logic() \ No newline at end of file diff --git a/sumo_project/emissions.py b/sumo_project/emissions.py index ad461e8..bd6b913 100644 --- a/sumo_project/emissions.py +++ b/sumo_project/emissions.py @@ -73,8 +73,9 @@ def add_data_to_areas(areas: List[Area]): if area.rectangle.intersects(lane.polygon): area.add_lane(lane) for tl_id in traci.trafficlight.getIDList(): #add traffic lights + logics = traci.trafficlight.getCompleteRedYellowGreenDefinition(tl_id) if lane.lane_id in traci.trafficlight.getControlledLanes(tl_id): - area.add_tl(TrafficLight(tl_id)) + area.add_tl(TrafficLight(tl_id,logics)) diff --git a/sumo_project/model.py b/sumo_project/model.py index 5a90846..3e8da99 100644 --- a/sumo_project/model.py +++ b/sumo_project/model.py @@ -3,6 +3,7 @@ from typing import Tuple, Set from shapely.geometry import Point, LineString from shapely.geometry import Polygon from shapely.geometry.base import BaseGeometry +from traci._trafficlight import Logic class Lane: @@ -18,8 +19,9 @@ class Lane: class TrafficLight: - def __init__(self, tl_id: str): - self.tl_id = tl_id + def __init__(self, tl_id: str, logics: Set[Logic]): + self.tl_id = tl_id + self._logics: Set[Logic] = logics def __hash__(self): """Overrides the default implementation""" From 27ecd5c78035e6b751a75d6576e093072baf0ff6 Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Thu, 29 Nov 2018 17:00:13 +0100 Subject: [PATCH 05/13] Added logic program list into trafic lights --- sumo_project/actions.py | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/sumo_project/actions.py b/sumo_project/actions.py index 739a8cb..b21cba4 100644 --- a/sumo_project/actions.py +++ b/sumo_project/actions.py @@ -6,10 +6,11 @@ Created on 17 oct. 2018 from typing import Iterable import traci +import inspect from shapely.geometry.linestring import LineString from model import Area, Vehicle -from traci._trafficlight import Logic +from traci._trafficlight import Logic, Phase def remove_vehicle(veh_id): @@ -36,12 +37,13 @@ def limit_speed_into_area(area: Area, vehicles: Iterable[Vehicle], max_speed): def adjust_traffic_light_phase_duration(area,reduction_factor): - tl_first = area._tls[0] + #attributes = inspect.getmembers(Phase, lambda a:not(inspect.isroutine(a))) + #print ([a[0] for a in attributes]) + for tl in area._tls: + for logic in tl._logics: + phases = traci.trafficlight.Logic.getPhases(logic) + for phase in phases: + print(phase) + #phaseDuration = traci.trafficlight.getPhaseDuration(tl.tl_id) - #traci.trafficlight.setPhaseDuration(tl.tl_id, phaseDuration*reduction_factor) - first_logic = tl_first._logics[0] - print('first logic of tl_first : ' + first_logic) - - first_logic = Logic() - - \ No newline at end of file + #traci.trafficlight.setPhaseDuration(tl.tl_id, phaseDuration*reduction_factor) \ No newline at end of file From 07155c639f244885067ff7e7c20dbfade522cf52 Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Mon, 3 Dec 2018 21:05:01 +0100 Subject: [PATCH 06/13] Fixed tls duration mode --- sumo_project/actions.py | 20 ++++++++------- sumo_project/config.py | 11 +++++++- sumo_project/emissions.py | 53 ++++++++++++++++++++++++++------------- sumo_project/model.py | 22 +++++++++++++--- 4 files changed, 75 insertions(+), 31 deletions(-) diff --git a/sumo_project/actions.py b/sumo_project/actions.py index b21cba4..596a788 100644 --- a/sumo_project/actions.py +++ b/sumo_project/actions.py @@ -6,11 +6,10 @@ Created on 17 oct. 2018 from typing import Iterable import traci -import inspect from shapely.geometry.linestring import LineString from model import Area, Vehicle -from traci._trafficlight import Logic, Phase +from traci._trafficlight import Logic def remove_vehicle(veh_id): @@ -34,16 +33,19 @@ def limit_speed_into_area(area: Area, vehicles: Iterable[Vehicle], max_speed): for lane in area._lanes: traci.lane.setMaxSpeed(lane.lane_id, max_speed/3.6) - +def modifyLogic(logic, rf): #rf for "reduction factor" + new_phases = [] + for phase in logic._phases: + new_phase = traci.trafficlight.Phase(phase.duration*rf,phase.minDuration*rf,phase.maxDuration*rf,phase.phaseDef) + new_phases.append(new_phase) -def adjust_traffic_light_phase_duration(area,reduction_factor): - #attributes = inspect.getmembers(Phase, lambda a:not(inspect.isroutine(a))) - #print ([a[0] for a in attributes]) + return traci.trafficlight.Logic("new-program", 0 , 0 , 0 , new_phases) + +def adjust_traffic_light_phase_duration(area, reduction_factor): + print(f'Decrease of traffic lights duration by a factor of {reduction_factor}') for tl in area._tls: for logic in tl._logics: - phases = traci.trafficlight.Logic.getPhases(logic) - for phase in phases: - print(phase) + traci.trafficlights.setCompleteRedYellowGreenDefinition(tl.tl_id, modifyLogic(logic,reduction_factor)) #phaseDuration = traci.trafficlight.getPhaseDuration(tl.tl_id) #traci.trafficlight.setPhaseDuration(tl.tl_id, phaseDuration*reduction_factor) \ No newline at end of file diff --git a/sumo_project/config.py b/sumo_project/config.py index ae002a2..c2061f4 100644 --- a/sumo_project/config.py +++ b/sumo_project/config.py @@ -17,10 +17,19 @@ CELLS_NUMBER = 10 EMISSIONS_THRESHOLD = 500000 n_steps = 200 +#Limit the speed into areas when the threshold is exceeded limit_speed_mode = True +#Vehicles are routed according to the less polluted route weight_routing_mode = False +#Decrease all traffic lights duration into the area when the threshold is exceeded +rf_trafficLights_duration = 0.2 adjust_traffic_light_mode = True +#Weight routing mode cannot be combinated with other actions +if weight_routing_mode: + limit_speed_mode = False + adjust_traffic_light_mode = False + sumo_binary = os.path.join(os.environ['SUMO_HOME'], 'bin', _SUMOCMD) sumo_cmd = [sumo_binary, "-c", _SUMOCFG] @@ -29,5 +38,5 @@ def showConfig(): + str(f'step number = {n_steps}\n') + str(f'limit speed mode = {limit_speed_mode}\n') + str(f'weight routing mode= {weight_routing_mode}\n') - + str(f'adjust traffic light mode = {adjust_traffic_light_mode}\n')) + + str(f'adjust traffic light mode = {adjust_traffic_light_mode} , RF = {rf_trafficLights_duration}\n')) diff --git a/sumo_project/emissions.py b/sumo_project/emissions.py index bd6b913..4cfdf76 100644 --- a/sumo_project/emissions.py +++ b/sumo_project/emissions.py @@ -2,11 +2,12 @@ from typing import List import traci from shapely.geometry import LineString +from parse import * import actions import config import sys -from model import Area, Vehicle, Lane , TrafficLight +from model import Area, Vehicle, Lane , TrafficLight , Phase , Logic from traci import trafficlight @@ -28,10 +29,10 @@ def init_grid(simulation_bounds, cells_number): def compute_vehicle_emissions(veh_id): return (traci.vehicle.getCOEmission(veh_id) - + traci.vehicle.getNOxEmission(veh_id) - + traci.vehicle.getHCEmission(veh_id) - + traci.vehicle.getPMxEmission(veh_id) - + traci.vehicle.getCO2Emission(veh_id)) + +traci.vehicle.getNOxEmission(veh_id) + +traci.vehicle.getHCEmission(veh_id) + +traci.vehicle.getPMxEmission(veh_id) + +traci.vehicle.getCO2Emission(veh_id)) def get_all_vehicles() -> List[Vehicle]: @@ -49,7 +50,7 @@ def get_all_lanes() -> List[Lane]: for lane_id in traci.lane.getIDList(): polygon_lane = LineString(traci.lane.getShape(lane_id)) initial_max_speed = traci.lane.getMaxSpeed(lane_id) - lanes.append(Lane(lane_id, polygon_lane,initial_max_speed)) + lanes.append(Lane(lane_id, polygon_lane, initial_max_speed)) return lanes @@ -59,26 +60,42 @@ def get_emissions(grid: List[Area], vehicles: List[Vehicle]): if vehicle.pos in area: area.emissions += vehicle.emissions if config.limit_speed_mode and area.emissions > config.EMISSIONS_THRESHOLD and not area.locked: - actions.limit_speed_into_area(area, vehicles,30) + actions.limit_speed_into_area(area, vehicles, 30) traci.polygon.setColor(area.name, (255, 0, 0)) traci.polygon.setFilled(area.name, True) if config.adjust_traffic_light_mode: - actions.adjust_traffic_light_phase_duration(area, 0.75) + actions.adjust_traffic_light_phase_duration(area, config.rf_trafficLights_duration) + + +def parsePhase(phase_repr): + duration = search('duration: {:f}', phase_repr) + minDuration = search('minDuration: {:f}', phase_repr) + maxDuration = search('maxDuration: {:f}', phase_repr) + phaseDef = search('phaseDef: {}\n', phase_repr) + + if phaseDef is None: phaseDef = '' + else : phaseDef = phaseDef[0] + + return Phase(duration[0], minDuration[0], maxDuration[0], phaseDef) def add_data_to_areas(areas: List[Area]): lanes = get_all_lanes() for area in areas: - for lane in lanes: #add lanes + for lane in lanes: # add lanes if area.rectangle.intersects(lane.polygon): - area.add_lane(lane) - for tl_id in traci.trafficlight.getIDList(): #add traffic lights - logics = traci.trafficlight.getCompleteRedYellowGreenDefinition(tl_id) + area.add_lane(lane) + for tl_id in traci.trafficlight.getIDList(): # add traffic lights if lane.lane_id in traci.trafficlight.getControlledLanes(tl_id): + logics = [] + for l in traci.trafficlight.getCompleteRedYellowGreenDefinition(tl_id): #add logics + phases = [] + for phase in traci.trafficlight.Logic.getPhases(l): #add phases to logics + phases.append(parsePhase(phase.__repr__())) + logics.append(Logic(l,phases)) area.add_tl(TrafficLight(tl_id,logics)) + - - def main(): grid = list() try: @@ -100,7 +117,7 @@ def main(): progress = round(step/config.n_steps*100,2) sys.stdout.write(f'Progress : {progress}%'+'\r') sys.stdout.flush() - + finally: traci.close(False) @@ -108,14 +125,16 @@ def main(): for area in grid: total_emissions += area.emissions - #Total of emissions of all pollutants in mg for 200 steps of simulation without locking areas + # Total of emissions of all pollutants in mg for n steps of simulation without locking areas total_emissions200 = 43970763.15084749 + total_emissions300 = 87382632.08217141 print("\n**** RESULTS ****") print(f'Total emissions = {total_emissions} mg') - diff_with_lock = (total_emissions200 - total_emissions)/total_emissions200 + diff_with_lock = (total_emissions200 - total_emissions) / total_emissions200 print(f'Reduction percentage of emissions = {diff_with_lock*100} %') print("With the configuration :\n" + str(config.showConfig())) + if __name__ == '__main__': main() diff --git a/sumo_project/model.py b/sumo_project/model.py index 3e8da99..9fde8eb 100644 --- a/sumo_project/model.py +++ b/sumo_project/model.py @@ -3,7 +3,7 @@ from typing import Tuple, Set from shapely.geometry import Point, LineString from shapely.geometry import Polygon from shapely.geometry.base import BaseGeometry -from traci._trafficlight import Logic +from traci._trafficlight import Logic as SUMO_Logic class Lane: @@ -17,17 +17,32 @@ class Lane: """Overrides the default implementation""" return hash(self.lane_id) +class Phase: + def __init__(self, duration: float, minDuration: float, maxDuration : float, phaseDef: str): + self.duration = duration + self.minDuration = minDuration + self.maxDuration = maxDuration + self.phaseDef = phaseDef + + def __repr__(self) -> str: + repr = f'Phase(duration:{self.duration},minDuration:{self.minDuration},maxDuration:{self.maxDuration},phaseDef:{self.phaseDef})' + return str(repr) + +class Logic: + def __init__(self, logic: SUMO_Logic, phases: Set[Phase]): + self._logic = logic + self._phases: Set[Phase] = phases + class TrafficLight: def __init__(self, tl_id: str, logics: Set[Logic]): self.tl_id = tl_id self._logics: Set[Logic] = logics - + def __hash__(self): """Overrides the default implementation""" return hash(self.tl_id) - class Area: def __init__(self, coords, name=''): @@ -68,7 +83,6 @@ class Area: (xmax, ymax), (xmax, ymin))) - class Vehicle: def __init__(self, veh_id: int, pos: Tuple[float, float]): From e249fbe30c00ce2b114f973d307ab2fc14c5688f Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Mon, 3 Dec 2018 21:17:19 +0100 Subject: [PATCH 07/13] Changed configuration file --- sumo_project/config.py | 7 +++++-- sumo_project/emissions.py | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/sumo_project/config.py b/sumo_project/config.py index c2061f4..6fcbc5d 100644 --- a/sumo_project/config.py +++ b/sumo_project/config.py @@ -17,10 +17,13 @@ CELLS_NUMBER = 10 EMISSIONS_THRESHOLD = 500000 n_steps = 200 -#Limit the speed into areas when the threshold is exceeded -limit_speed_mode = True #Vehicles are routed according to the less polluted route weight_routing_mode = False + +#Limit the speed into areas when the threshold is exceeded +limited_speed = 30 +limit_speed_mode = True + #Decrease all traffic lights duration into the area when the threshold is exceeded rf_trafficLights_duration = 0.2 adjust_traffic_light_mode = True diff --git a/sumo_project/emissions.py b/sumo_project/emissions.py index 4cfdf76..b0753ca 100644 --- a/sumo_project/emissions.py +++ b/sumo_project/emissions.py @@ -60,7 +60,7 @@ def get_emissions(grid: List[Area], vehicles: List[Vehicle]): if vehicle.pos in area: area.emissions += vehicle.emissions if config.limit_speed_mode and area.emissions > config.EMISSIONS_THRESHOLD and not area.locked: - actions.limit_speed_into_area(area, vehicles, 30) + actions.limit_speed_into_area(area, vehicles, config.limited_speed) traci.polygon.setColor(area.name, (255, 0, 0)) traci.polygon.setFilled(area.name, True) if config.adjust_traffic_light_mode: From 30cd4eb72e984400505a35503a267e23016a5323 Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Mon, 3 Dec 2018 21:46:31 +0100 Subject: [PATCH 08/13] Added 'remove vehicles from simulation' into actions --- sumo_project/actions.py | 7 ++++--- sumo_project/config.py | 9 ++++++--- sumo_project/emissions.py | 17 ++++++++++------- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/sumo_project/actions.py b/sumo_project/actions.py index 596a788..2a9dc60 100644 --- a/sumo_project/actions.py +++ b/sumo_project/actions.py @@ -11,9 +11,10 @@ from shapely.geometry.linestring import LineString from model import Area, Vehicle from traci._trafficlight import Logic - -def remove_vehicle(veh_id): - traci.vehicle.remove(veh_id, traci.constants.REMOVE_PARKING) +def remove_vehicles(vehicles): + print(f'Removed {vehicles.size} vehicles from the simulation') + for vehicle in vehicles: + traci.vehicle.remove(vehicle.veh_id, traci.constants.REMOVE_PARKING) def compute_edge_weight(edge_id): return (traci.edge.getCOEmission(edge_id) diff --git a/sumo_project/config.py b/sumo_project/config.py index 6fcbc5d..1538099 100644 --- a/sumo_project/config.py +++ b/sumo_project/config.py @@ -22,11 +22,14 @@ weight_routing_mode = False #Limit the speed into areas when the threshold is exceeded limited_speed = 30 -limit_speed_mode = True +limit_speed_mode = False #Decrease all traffic lights duration into the area when the threshold is exceeded rf_trafficLights_duration = 0.2 -adjust_traffic_light_mode = True +adjust_traffic_light_mode = False + +#Immediately delete all vehicles in the simulation area +remove_vehicles_mode = True #Weight routing mode cannot be combinated with other actions if weight_routing_mode: @@ -39,7 +42,7 @@ sumo_cmd = [sumo_binary, "-c", _SUMOCFG] def showConfig(): return (str(f'Grid : {CELLS_NUMBER}x{CELLS_NUMBER}\n') + str(f'step number = {n_steps}\n') - + str(f'limit speed mode = {limit_speed_mode}\n') + str(f'weight routing mode= {weight_routing_mode}\n') + + str(f'limit speed mode = {limit_speed_mode}, limited speed to {limited_speed}\n') + str(f'adjust traffic light mode = {adjust_traffic_light_mode} , RF = {rf_trafficLights_duration}\n')) diff --git a/sumo_project/emissions.py b/sumo_project/emissions.py index b0753ca..127cfa6 100644 --- a/sumo_project/emissions.py +++ b/sumo_project/emissions.py @@ -59,12 +59,15 @@ def get_emissions(grid: List[Area], vehicles: List[Vehicle]): for vehicle in vehicles: if vehicle.pos in area: area.emissions += vehicle.emissions - if config.limit_speed_mode and area.emissions > config.EMISSIONS_THRESHOLD and not area.locked: - actions.limit_speed_into_area(area, vehicles, config.limited_speed) - traci.polygon.setColor(area.name, (255, 0, 0)) - traci.polygon.setFilled(area.name, True) - if config.adjust_traffic_light_mode: - actions.adjust_traffic_light_phase_duration(area, config.rf_trafficLights_duration) + if area.emissions > config.EMISSIONS_THRESHOLD and not area.locked: + if config.limit_speed_mode: + actions.limit_speed_into_area(area, vehicles, config.limited_speed) + traci.polygon.setColor(area.name, (255, 0, 0)) + traci.polygon.setFilled(area.name, True) + if config.adjust_traffic_light_mode: + actions.adjust_traffic_light_phase_duration(area, config.rf_trafficLights_duration) + '''if config.remove_vehicles_mode: + actions.remove_vehicles(vehicles)''' #Véhicules à mettre en donnée membre car variable def parsePhase(phase_repr): @@ -133,7 +136,7 @@ def main(): print(f'Total emissions = {total_emissions} mg') diff_with_lock = (total_emissions200 - total_emissions) / total_emissions200 print(f'Reduction percentage of emissions = {diff_with_lock*100} %') - print("With the configuration :\n" + str(config.showConfig())) + print("**** With the configuration : ****\n" + str(config.showConfig())) if __name__ == '__main__': From 70b29c47b25f538272c4d0c4277e974ffc9f1344 Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Thu, 6 Dec 2018 21:49:01 +0100 Subject: [PATCH 09/13] Changed config and added lock area mode --- sumo_project/actions.py | 27 ++++++++++++++++++++------- sumo_project/config.py | 23 ++++++++++++++++++----- sumo_project/emissions.py | 25 ++++++++++++++----------- sumo_project/model.py | 1 + 4 files changed, 53 insertions(+), 23 deletions(-) diff --git a/sumo_project/actions.py b/sumo_project/actions.py index 2a9dc60..483abb4 100644 --- a/sumo_project/actions.py +++ b/sumo_project/actions.py @@ -21,16 +21,19 @@ def compute_edge_weight(edge_id): + traci.edge.getNOxEmission(edge_id) + traci.edge.getHCEmission(edge_id) + traci.edge.getPMxEmission(edge_id) - + traci.edge.getCO2Emission(edge_id)) + + traci.edge.getCO2Emission(edge_id))/(traci.edge.getLaneNumber(edge_id)) -def adjust_edges_weights(): +def adjust_edges_weights(): for edge_id in traci.edge.getIDList(): weight = compute_edge_weight(edge_id) # by default edges weight = length/mean speed - traci.edge.adaptTraveltime(edge_id, weight) - + traci.edge.setEffort(edge_id, weight) + + for veh_id in traci.vehicle.getIDList(): + traci.vehicle.rerouteEffort(veh_id) + def limit_speed_into_area(area: Area, vehicles: Iterable[Vehicle], max_speed): print(f'Setting max speed into {area.name} to {max_speed} km/h') - area.locked = True + area.limited_speed = True for lane in area._lanes: traci.lane.setMaxSpeed(lane.lane_id, max_speed/3.6) @@ -48,5 +51,15 @@ def adjust_traffic_light_phase_duration(area, reduction_factor): for logic in tl._logics: traci.trafficlights.setCompleteRedYellowGreenDefinition(tl.tl_id, modifyLogic(logic,reduction_factor)) - #phaseDuration = traci.trafficlight.getPhaseDuration(tl.tl_id) - #traci.trafficlight.setPhaseDuration(tl.tl_id, phaseDuration*reduction_factor) \ No newline at end of file +def lock_area(area): + #Trying to lock area + vehicles_in_area = 0 + for lane in area._lanes: + vehicles_in_area += traci.lane.getLastStepVehicleNumber(lane.lane_id) + + #Waiting for the area to be empty before blocking it + if vehicles_in_area == 0: + area.locked = True + print(f'Area locked : {area.name}') + for lane in area._lanes: + traci.lane.setDisallowed(lane.lane_id, 'passenger') \ No newline at end of file diff --git a/sumo_project/config.py b/sumo_project/config.py index 1538099..51fe185 100644 --- a/sumo_project/config.py +++ b/sumo_project/config.py @@ -17,19 +17,22 @@ CELLS_NUMBER = 10 EMISSIONS_THRESHOLD = 500000 n_steps = 200 -#Vehicles are routed according to the less polluted route -weight_routing_mode = False - #Limit the speed into areas when the threshold is exceeded limited_speed = 30 limit_speed_mode = False #Decrease all traffic lights duration into the area when the threshold is exceeded -rf_trafficLights_duration = 0.2 +rf_trafficLights_duration = 1.4 adjust_traffic_light_mode = False #Immediately delete all vehicles in the simulation area -remove_vehicles_mode = True +remove_vehicles_mode = False + +#Vehicles are routed according to the less polluted route (HEAVY) +weight_routing_mode = True + +#Lock the area when the threshold is exceeded (NOT FIXED) +lock_area_mode = False #Weight routing mode cannot be combinated with other actions if weight_routing_mode: @@ -39,6 +42,16 @@ if weight_routing_mode: sumo_binary = os.path.join(os.environ['SUMO_HOME'], 'bin', _SUMOCMD) sumo_cmd = [sumo_binary, "-c", _SUMOCFG] +# Total of emissions of all pollutants in mg for n steps of simulation without locking areas +total_emissions200 = 43970763.15084749 +total_emissions300 = 87382632.08217141 + +def get_basics_emissions(): + if n_steps == 200: + return total_emissions200 + if n_steps == 300: + return total_emissions300 + def showConfig(): return (str(f'Grid : {CELLS_NUMBER}x{CELLS_NUMBER}\n') + str(f'step number = {n_steps}\n') diff --git a/sumo_project/emissions.py b/sumo_project/emissions.py index 127cfa6..be52a1f 100644 --- a/sumo_project/emissions.py +++ b/sumo_project/emissions.py @@ -1,3 +1,5 @@ +# -*- coding: latin-1 -*- + from typing import List import traci @@ -59,15 +61,17 @@ def get_emissions(grid: List[Area], vehicles: List[Vehicle]): for vehicle in vehicles: if vehicle.pos in area: area.emissions += vehicle.emissions - if area.emissions > config.EMISSIONS_THRESHOLD and not area.locked: - if config.limit_speed_mode: + if area.emissions > config.EMISSIONS_THRESHOLD: + + if config.limit_speed_mode and not area.limited_speed: actions.limit_speed_into_area(area, vehicles, config.limited_speed) traci.polygon.setColor(area.name, (255, 0, 0)) traci.polygon.setFilled(area.name, True) if config.adjust_traffic_light_mode: actions.adjust_traffic_light_phase_duration(area, config.rf_trafficLights_duration) - '''if config.remove_vehicles_mode: - actions.remove_vehicles(vehicles)''' #Véhicules à mettre en donnée membre car variable + + if config.lock_area_mode and not area.locked: + actions.lock_area(area) def parsePhase(phase_repr): @@ -127,15 +131,14 @@ def main(): total_emissions = 0 for area in grid: total_emissions += area.emissions - - # Total of emissions of all pollutants in mg for n steps of simulation without locking areas - total_emissions200 = 43970763.15084749 - total_emissions300 = 87382632.08217141 - + print("\n**** RESULTS ****") print(f'Total emissions = {total_emissions} mg') - diff_with_lock = (total_emissions200 - total_emissions) / total_emissions200 - print(f'Reduction percentage of emissions = {diff_with_lock*100} %') + + ref = config.get_basics_emissions() + diff_with_actions = (ref - total_emissions)/ref + + print(f'Reduction percentage of emissions = {diff_with_actions*100} %') print("**** With the configuration : ****\n" + str(config.showConfig())) diff --git a/sumo_project/model.py b/sumo_project/model.py index 9fde8eb..736e3e6 100644 --- a/sumo_project/model.py +++ b/sumo_project/model.py @@ -46,6 +46,7 @@ class TrafficLight: class Area: def __init__(self, coords, name=''): + self.limited_speed = False self.locked = False self.rectangle = Polygon(coords) self.name = name From 342320bd4ac1a25d8125838e8e9fe3aa76e0ad61 Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Fri, 7 Dec 2018 16:30:23 +0100 Subject: [PATCH 10/13] Added a logs file output --- sumo_project/actions.py | 21 +++--- sumo_project/config.py | 48 +++++++++++--- sumo_project/emissions.py | 131 ++++++++++++++++++++++---------------- sumo_project/model.py | 1 + 4 files changed, 125 insertions(+), 76 deletions(-) diff --git a/sumo_project/actions.py b/sumo_project/actions.py index 483abb4..1758d6c 100644 --- a/sumo_project/actions.py +++ b/sumo_project/actions.py @@ -31,11 +31,10 @@ def adjust_edges_weights(): for veh_id in traci.vehicle.getIDList(): traci.vehicle.rerouteEffort(veh_id) -def limit_speed_into_area(area: Area, vehicles: Iterable[Vehicle], max_speed): - print(f'Setting max speed into {area.name} to {max_speed} km/h') +def limit_speed_into_area(area: Area, vehicles: Iterable[Vehicle], speed_rf): area.limited_speed = True for lane in area._lanes: - traci.lane.setMaxSpeed(lane.lane_id, max_speed/3.6) + traci.lane.setMaxSpeed(lane.lane_id, speed_rf * lane.initial_max_speed) def modifyLogic(logic, rf): #rf for "reduction factor" new_phases = [] @@ -46,20 +45,20 @@ def modifyLogic(logic, rf): #rf for "reduction factor" return traci.trafficlight.Logic("new-program", 0 , 0 , 0 , new_phases) def adjust_traffic_light_phase_duration(area, reduction_factor): - print(f'Decrease of traffic lights duration by a factor of {reduction_factor}') + area.tls_adjusted = True for tl in area._tls: for logic in tl._logics: traci.trafficlights.setCompleteRedYellowGreenDefinition(tl.tl_id, modifyLogic(logic,reduction_factor)) -def lock_area(area): +def count_vehicles_in_area(area): #Trying to lock area vehicles_in_area = 0 for lane in area._lanes: vehicles_in_area += traci.lane.getLastStepVehicleNumber(lane.lane_id) - #Waiting for the area to be empty before blocking it - if vehicles_in_area == 0: - area.locked = True - print(f'Area locked : {area.name}') - for lane in area._lanes: - traci.lane.setDisallowed(lane.lane_id, 'passenger') \ No newline at end of file + return vehicles_in_area + +def lock_area(area): + area.locked = True + for lane in area._lanes: + traci.lane.setDisallowed(lane.lane_id, 'passenger') \ No newline at end of file diff --git a/sumo_project/config.py b/sumo_project/config.py index 51fe185..1fc819b 100644 --- a/sumo_project/config.py +++ b/sumo_project/config.py @@ -4,6 +4,11 @@ Global configuration for the simulation import os import sys +import datetime + +############################################################################### +############################# SIMULATION FILE ################################# +############################################################################### if 'SUMO_HOME' in os.environ: tools = os.path.join(os.environ['SUMO_HOME'], 'tools') @@ -13,39 +18,63 @@ else: _SUMOCMD = 'sumo' # use 'sumo-gui' cmd for UI _SUMOCFG = "mulhouse_simulation/osm.sumocfg" +sumo_binary = os.path.join(os.environ['SUMO_HOME'], 'bin', _SUMOCMD) +sumo_cmd = [sumo_binary, "-c", _SUMOCFG] + +############################################################################### +############################# LOGS OUTPUT ##################################### +############################################################################### + +now = datetime.datetime.now() +current_date = now.strftime("%Y_%m_%d_%H_%M") +LOG_FILENAME = f'sumo_logs_{current_date}.log' + +############################################################################### +########################## SIMULATION CONFIGURATION ########################### +############################################################################### + CELLS_NUMBER = 10 EMISSIONS_THRESHOLD = 500000 n_steps = 200 +############################################################################### +########################## ACTIONS CONFIGURATION ############################## +############################################################################### + #Limit the speed into areas when the threshold is exceeded -limited_speed = 30 +speed_rf = 0.1 limit_speed_mode = False #Decrease all traffic lights duration into the area when the threshold is exceeded -rf_trafficLights_duration = 1.4 +trafficLights_duration_rf = 0.2 adjust_traffic_light_mode = False #Immediately delete all vehicles in the simulation area remove_vehicles_mode = False #Vehicles are routed according to the less polluted route (HEAVY) -weight_routing_mode = True +weight_routing_mode = False #Lock the area when the threshold is exceeded (NOT FIXED) -lock_area_mode = False +lock_area_mode = True #Weight routing mode cannot be combinated with other actions if weight_routing_mode: limit_speed_mode = False adjust_traffic_light_mode = False -sumo_binary = os.path.join(os.environ['SUMO_HOME'], 'bin', _SUMOCMD) -sumo_cmd = [sumo_binary, "-c", _SUMOCFG] +############################################################################### +########################## SIMULATION REFERENCES ############################## +############################################################################### # Total of emissions of all pollutants in mg for n steps of simulation without locking areas total_emissions200 = 43970763.15084749 total_emissions300 = 87382632.08217141 +############################################################################### +########################## CONFIGURATION METHODS ############################## +############################################################################### + def get_basics_emissions(): if n_steps == 200: return total_emissions200 @@ -55,7 +84,8 @@ def get_basics_emissions(): def showConfig(): return (str(f'Grid : {CELLS_NUMBER}x{CELLS_NUMBER}\n') + str(f'step number = {n_steps}\n') - + str(f'weight routing mode= {weight_routing_mode}\n') - + str(f'limit speed mode = {limit_speed_mode}, limited speed to {limited_speed}\n') - + str(f'adjust traffic light mode = {adjust_traffic_light_mode} , RF = {rf_trafficLights_duration}\n')) + + str(f'weight routing mode = {weight_routing_mode}\n') + + str(f'lock area mode = {lock_area_mode}\n') + + str(f'limit speed mode = {limit_speed_mode}, RF = {speed_rf*100}%\n') + + str(f'adjust traffic light mode = {adjust_traffic_light_mode} , RF = {trafficLights_duration_rf*100}%\n')) diff --git a/sumo_project/emissions.py b/sumo_project/emissions.py index be52a1f..24c22f3 100644 --- a/sumo_project/emissions.py +++ b/sumo_project/emissions.py @@ -1,8 +1,9 @@ -# -*- coding: latin-1 -*- - from typing import List import traci +import logging +import time + from shapely.geometry import LineString from parse import * @@ -12,6 +13,18 @@ import sys from model import Area, Vehicle, Lane , TrafficLight , Phase , Logic from traci import trafficlight +# create logger +logger = logging.getLogger("sumo_logger") +logger.setLevel(logging.INFO) +# create console handler and set level to info +handler = logging.FileHandler(config.LOG_FILENAME) +# create formatter +formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") +# add formatter to handler +handler.setFormatter(formatter) +# add handler to logger +logger.addHandler(handler) + def init_grid(simulation_bounds, cells_number): grid = list() @@ -23,11 +36,47 @@ def init_grid(simulation_bounds, cells_number): ar_bounds = ((i * width, j * height), (i * width, (j + 1) * height), ((i + 1) * width, (j + 1) * height), ((i + 1) * width, j * height)) area = Area(ar_bounds) - area.name = 'area ({},{})'.format(i, j) + area.name = 'Area ({},{})'.format(i, j) grid.append(area) traci.polygon.add(area.name, ar_bounds, (0, 255, 0)) return grid +def get_all_lanes() -> List[Lane]: + lanes = [] + for lane_id in traci.lane.getIDList(): + polygon_lane = LineString(traci.lane.getShape(lane_id)) + initial_max_speed = traci.lane.getMaxSpeed(lane_id) + lanes.append(Lane(lane_id, polygon_lane, initial_max_speed)) + return lanes + +def parsePhase(phase_repr): + duration = search('duration: {:f}', phase_repr) + minDuration = search('minDuration: {:f}', phase_repr) + maxDuration = search('maxDuration: {:f}', phase_repr) + phaseDef = search('phaseDef: {}\n', phase_repr) + + if phaseDef is None: phaseDef = '' + else : phaseDef = phaseDef[0] + + return Phase(duration[0], minDuration[0], maxDuration[0], phaseDef) + +def add_data_to_areas(areas: List[Area]): + + + lanes = get_all_lanes() + for area in areas: + for lane in lanes: # add lanes + if area.rectangle.intersects(lane.polygon): + area.add_lane(lane) + for tl_id in traci.trafficlight.getIDList(): # add traffic lights + if lane.lane_id in traci.trafficlight.getControlledLanes(tl_id): + logics = [] + for l in traci.trafficlight.getCompleteRedYellowGreenDefinition(tl_id): #add logics + phases = [] + for phase in traci.trafficlight.Logic.getPhases(l): #add phases to logics + phases.append(parsePhase(phase.__repr__())) + logics.append(Logic(l,phases)) + area.add_tl(TrafficLight(tl_id,logics)) def compute_vehicle_emissions(veh_id): return (traci.vehicle.getCOEmission(veh_id) @@ -46,16 +95,6 @@ def get_all_vehicles() -> List[Vehicle]: vehicles.append(vehicle) return vehicles - -def get_all_lanes() -> List[Lane]: - lanes = [] - for lane_id in traci.lane.getIDList(): - polygon_lane = LineString(traci.lane.getShape(lane_id)) - initial_max_speed = traci.lane.getMaxSpeed(lane_id) - lanes.append(Lane(lane_id, polygon_lane, initial_max_speed)) - return lanes - - def get_emissions(grid: List[Area], vehicles: List[Vehicle]): for area in grid: for vehicle in vehicles: @@ -64,52 +103,34 @@ def get_emissions(grid: List[Area], vehicles: List[Vehicle]): if area.emissions > config.EMISSIONS_THRESHOLD: if config.limit_speed_mode and not area.limited_speed: - actions.limit_speed_into_area(area, vehicles, config.limited_speed) + logger.info(f'Action - Decrease of max speed into {area.name} by {config.speed_rf*100}%') + actions.limit_speed_into_area(area, vehicles, config.speed_rf) traci.polygon.setColor(area.name, (255, 0, 0)) traci.polygon.setFilled(area.name, True) - if config.adjust_traffic_light_mode: - actions.adjust_traffic_light_phase_duration(area, config.rf_trafficLights_duration) + if config.adjust_traffic_light_mode and not area.tls_adjusted: + logger.info(f'Action - Decrease of traffic lights duration by {config.trafficLights_duration_rf*100}%') + actions.adjust_traffic_light_phase_duration(area, config.trafficLights_duration_rf) if config.lock_area_mode and not area.locked: - actions.lock_area(area) + if actions.count_vehicles_in_area(area): + logger.info(f'Action - {area.name} blocked') + actions.lock_area(area) - -def parsePhase(phase_repr): - duration = search('duration: {:f}', phase_repr) - minDuration = search('minDuration: {:f}', phase_repr) - maxDuration = search('maxDuration: {:f}', phase_repr) - phaseDef = search('phaseDef: {}\n', phase_repr) - - if phaseDef is None: phaseDef = '' - else : phaseDef = phaseDef[0] - - return Phase(duration[0], minDuration[0], maxDuration[0], phaseDef) - - -def add_data_to_areas(areas: List[Area]): - lanes = get_all_lanes() - for area in areas: - for lane in lanes: # add lanes - if area.rectangle.intersects(lane.polygon): - area.add_lane(lane) - for tl_id in traci.trafficlight.getIDList(): # add traffic lights - if lane.lane_id in traci.trafficlight.getControlledLanes(tl_id): - logics = [] - for l in traci.trafficlight.getCompleteRedYellowGreenDefinition(tl_id): #add logics - phases = [] - for phase in traci.trafficlight.Logic.getPhases(l): #add phases to logics - phases.append(parsePhase(phase.__repr__())) - logics.append(Logic(l,phases)) - area.add_tl(TrafficLight(tl_id,logics)) - - def main(): grid = list() try: traci.start(config.sumo_cmd) + + logger.info('Loading data for the simulation') + start = time.perf_counter() + grid = init_grid(traci.simulation.getNetBoundary(), config.CELLS_NUMBER) add_data_to_areas(grid) - + + loading_time = round(time.perf_counter() - start,2) + logger.info(f'Data loaded ({loading_time}s)') + + logger.info('Start of the simulation') step = 0 while step < config.n_steps : #traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() @@ -118,28 +139,26 @@ def main(): get_emissions(grid, vehicles) if config.weight_routing_mode: + logger.info('Action - Lane weights adjusted') actions.adjust_edges_weights() step += 1 - progress = round(step/config.n_steps*100,2) - sys.stdout.write(f'Progress : {progress}%'+'\r') - sys.stdout.flush() finally: traci.close(False) - + logger.info('End of the simulation') total_emissions = 0 for area in grid: total_emissions += area.emissions - print("\n**** RESULTS ****") - print(f'Total emissions = {total_emissions} mg') + logger.info(f'Total emissions = {total_emissions} mg') ref = config.get_basics_emissions() diff_with_actions = (ref - total_emissions)/ref - print(f'Reduction percentage of emissions = {diff_with_actions*100} %') - print("**** With the configuration : ****\n" + str(config.showConfig())) + logger.info(f'Reduction percentage of emissions = {diff_with_actions*100} %') + logger.info('With the configuration : \n' + str(config.showConfig())) + logger.info('Logs END') if __name__ == '__main__': diff --git a/sumo_project/model.py b/sumo_project/model.py index 736e3e6..888cef7 100644 --- a/sumo_project/model.py +++ b/sumo_project/model.py @@ -48,6 +48,7 @@ class Area: def __init__(self, coords, name=''): self.limited_speed = False self.locked = False + self.tls_adjusted = False self.rectangle = Polygon(coords) self.name = name self.emissions = 0.0 From c07748f3402c0ec84d1c342fae4043dd458a875a Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Fri, 7 Dec 2018 16:46:54 +0100 Subject: [PATCH 11/13] Added info logs --- sumo_project/actions.py | 2 -- sumo_project/config.py | 8 ++++---- sumo_project/emissions.py | 6 +++--- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/sumo_project/actions.py b/sumo_project/actions.py index 1758d6c..8efdd61 100644 --- a/sumo_project/actions.py +++ b/sumo_project/actions.py @@ -51,11 +51,9 @@ def adjust_traffic_light_phase_duration(area, reduction_factor): traci.trafficlights.setCompleteRedYellowGreenDefinition(tl.tl_id, modifyLogic(logic,reduction_factor)) def count_vehicles_in_area(area): - #Trying to lock area vehicles_in_area = 0 for lane in area._lanes: vehicles_in_area += traci.lane.getLastStepVehicleNumber(lane.lane_id) - return vehicles_in_area def lock_area(area): diff --git a/sumo_project/config.py b/sumo_project/config.py index 1fc819b..25ff6fd 100644 --- a/sumo_project/config.py +++ b/sumo_project/config.py @@ -26,7 +26,7 @@ sumo_cmd = [sumo_binary, "-c", _SUMOCFG] ############################################################################### now = datetime.datetime.now() -current_date = now.strftime("%Y_%m_%d_%H_%M") +current_date = now.strftime("%Y_%m_%d_%H_%M_%S") LOG_FILENAME = f'sumo_logs_{current_date}.log' ############################################################################### @@ -43,11 +43,11 @@ n_steps = 200 #Limit the speed into areas when the threshold is exceeded speed_rf = 0.1 -limit_speed_mode = False +limit_speed_mode = True #Decrease all traffic lights duration into the area when the threshold is exceeded trafficLights_duration_rf = 0.2 -adjust_traffic_light_mode = False +adjust_traffic_light_mode = True #Immediately delete all vehicles in the simulation area remove_vehicles_mode = False @@ -56,7 +56,7 @@ remove_vehicles_mode = False weight_routing_mode = False #Lock the area when the threshold is exceeded (NOT FIXED) -lock_area_mode = True +lock_area_mode = False #Weight routing mode cannot be combinated with other actions if weight_routing_mode: diff --git a/sumo_project/emissions.py b/sumo_project/emissions.py index 24c22f3..f49f910 100644 --- a/sumo_project/emissions.py +++ b/sumo_project/emissions.py @@ -61,8 +61,6 @@ def parsePhase(phase_repr): return Phase(duration[0], minDuration[0], maxDuration[0], phaseDef) def add_data_to_areas(areas: List[Area]): - - lanes = get_all_lanes() for area in areas: for lane in lanes: # add lanes @@ -146,7 +144,9 @@ def main(): finally: traci.close(False) - logger.info('End of the simulation') + simulation_time = round(time.perf_counter() - start,2) + logger.info(f'End of the simulation ({simulation_time}s)') + total_emissions = 0 for area in grid: total_emissions += area.emissions From e25a95250013ceb810024c4912a3e66b10391a12 Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Fri, 7 Dec 2018 17:16:26 +0100 Subject: [PATCH 12/13] Added reverse_actions method --- sumo_project/actions.py | 28 ++++++++++++++++++++++------ sumo_project/config.py | 21 +++++++++++++++++---- sumo_project/emissions.py | 15 ++++++++------- 3 files changed, 47 insertions(+), 17 deletions(-) diff --git a/sumo_project/actions.py b/sumo_project/actions.py index 8efdd61..69705db 100644 --- a/sumo_project/actions.py +++ b/sumo_project/actions.py @@ -11,11 +11,6 @@ from shapely.geometry.linestring import LineString from model import Area, Vehicle from traci._trafficlight import Logic -def remove_vehicles(vehicles): - print(f'Removed {vehicles.size} vehicles from the simulation') - for vehicle in vehicles: - traci.vehicle.remove(vehicle.veh_id, traci.constants.REMOVE_PARKING) - def compute_edge_weight(edge_id): return (traci.edge.getCOEmission(edge_id) + traci.edge.getNOxEmission(edge_id) @@ -59,4 +54,25 @@ def count_vehicles_in_area(area): def lock_area(area): area.locked = True for lane in area._lanes: - traci.lane.setDisallowed(lane.lane_id, 'passenger') \ No newline at end of file + traci.lane.setDisallowed(lane.lane_id, 'passenger') + +def reverse_actions(area): + #Reset max speed to original + if not area.limited_speed: + area.limited_speed = False + for lane in area.lanes: + traci.lane.setMaxSpeed(lane.lane_id, lane.initial_max_speed / 3.6) + + #Reset traffic lights initial duration + if not area.tls_adjusted: + area.tls_adjusted = False + for initial_logic in tl._logics: + traci.trafficlights.setCompleteRedYellowGreenDefinition(tl.tl_id, initial_logic) + + #Unlock the area + if not area.locked: + area.locked = False + for lane in area._lanes: + traci.lane.setAllowed(lane.lane_id, '') #empty means all classes are allowed + + \ No newline at end of file diff --git a/sumo_project/config.py b/sumo_project/config.py index 25ff6fd..13e8430 100644 --- a/sumo_project/config.py +++ b/sumo_project/config.py @@ -41,6 +41,9 @@ n_steps = 200 ########################## ACTIONS CONFIGURATION ############################## ############################################################################### +#Set this mode to True if you want running a basic simulation without actions +without_actions_mode = False + #Limit the speed into areas when the threshold is exceeded speed_rf = 0.1 limit_speed_mode = True @@ -49,9 +52,6 @@ limit_speed_mode = True trafficLights_duration_rf = 0.2 adjust_traffic_light_mode = True -#Immediately delete all vehicles in the simulation area -remove_vehicles_mode = False - #Vehicles are routed according to the less polluted route (HEAVY) weight_routing_mode = False @@ -62,6 +62,13 @@ lock_area_mode = False if weight_routing_mode: limit_speed_mode = False adjust_traffic_light_mode = False + +#If without_actions_mode is choosen +if without_actions_mode: + limit_speed_mode = False + adjust_traffic_light_mode = False + weight_routing_mode = False + lock_area_mode = False ############################################################################### ########################## SIMULATION REFERENCES ############################## @@ -70,6 +77,8 @@ if weight_routing_mode: # Total of emissions of all pollutants in mg for n steps of simulation without locking areas total_emissions200 = 43970763.15084749 total_emissions300 = 87382632.08217141 +total_emissions400 = 140757491.8489904 +total_emissions500 = 202817535.43856794 ############################################################################### ########################## CONFIGURATION METHODS ############################## @@ -80,8 +89,12 @@ def get_basics_emissions(): return total_emissions200 if n_steps == 300: return total_emissions300 + if n_steps == 400: + return total_emissions400 + if n_steps == 500: + return total_emissions500 -def showConfig(): +def show_config(): return (str(f'Grid : {CELLS_NUMBER}x{CELLS_NUMBER}\n') + str(f'step number = {n_steps}\n') + str(f'weight routing mode = {weight_routing_mode}\n') diff --git a/sumo_project/emissions.py b/sumo_project/emissions.py index f49f910..37a70be 100644 --- a/sumo_project/emissions.py +++ b/sumo_project/emissions.py @@ -49,7 +49,7 @@ def get_all_lanes() -> List[Lane]: lanes.append(Lane(lane_id, polygon_lane, initial_max_speed)) return lanes -def parsePhase(phase_repr): +def parse_phase(phase_repr): duration = search('duration: {:f}', phase_repr) minDuration = search('minDuration: {:f}', phase_repr) maxDuration = search('maxDuration: {:f}', phase_repr) @@ -72,7 +72,7 @@ def add_data_to_areas(areas: List[Area]): for l in traci.trafficlight.getCompleteRedYellowGreenDefinition(tl_id): #add logics phases = [] for phase in traci.trafficlight.Logic.getPhases(l): #add phases to logics - phases.append(parsePhase(phase.__repr__())) + phases.append(parse_phase(phase.__repr__())) logics.append(Logic(l,phases)) area.add_tl(TrafficLight(tl_id,logics)) @@ -153,11 +153,12 @@ def main(): logger.info(f'Total emissions = {total_emissions} mg') - ref = config.get_basics_emissions() - diff_with_actions = (ref - total_emissions)/ref - - logger.info(f'Reduction percentage of emissions = {diff_with_actions*100} %') - logger.info('With the configuration : \n' + str(config.showConfig())) + if not config.without_actions_mode: + ref = config.get_basics_emissions() + diff_with_actions = (ref - total_emissions)/ref + logger.info(f'Reduction percentage of emissions = {diff_with_actions*100} %') + + logger.info('With the configuration : \n' + str(config.show_config())) logger.info('Logs END') From 20a1c11628e539c05479ac3ad83744324d69f0cf Mon Sep 17 00:00:00 2001 From: Ahp06 Date: Fri, 7 Dec 2018 17:40:16 +0100 Subject: [PATCH 13/13] Put logger into config.py --- sumo_project/config.py | 15 ++++++++++++++- sumo_project/emissions.py | 20 ++++---------------- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/sumo_project/config.py b/sumo_project/config.py index 13e8430..decf4d5 100644 --- a/sumo_project/config.py +++ b/sumo_project/config.py @@ -5,6 +5,7 @@ Global configuration for the simulation import os import sys import datetime +import logging ############################################################################### ############################# SIMULATION FILE ################################# @@ -22,13 +23,25 @@ sumo_binary = os.path.join(os.environ['SUMO_HOME'], 'bin', _SUMOCMD) sumo_cmd = [sumo_binary, "-c", _SUMOCFG] ############################################################################### -############################# LOGS OUTPUT ##################################### +################################## LOGS ####################################### ############################################################################### now = datetime.datetime.now() current_date = now.strftime("%Y_%m_%d_%H_%M_%S") LOG_FILENAME = f'sumo_logs_{current_date}.log' +# create logger +logger = logging.getLogger("sumo_logger") +logger.setLevel(logging.INFO) +# create console handler and set level to info +handler = logging.FileHandler(LOG_FILENAME) +# create formatter +formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") +# add formatter to handler +handler.setFormatter(formatter) +# add handler to logger +logger.addHandler(handler) + ############################################################################### ########################## SIMULATION CONFIGURATION ########################### ############################################################################### diff --git a/sumo_project/emissions.py b/sumo_project/emissions.py index 37a70be..21d4cb3 100644 --- a/sumo_project/emissions.py +++ b/sumo_project/emissions.py @@ -1,11 +1,10 @@ from typing import List import traci -import logging import time from shapely.geometry import LineString -from parse import * +from parse import search import actions import config @@ -13,18 +12,7 @@ import sys from model import Area, Vehicle, Lane , TrafficLight , Phase , Logic from traci import trafficlight -# create logger -logger = logging.getLogger("sumo_logger") -logger.setLevel(logging.INFO) -# create console handler and set level to info -handler = logging.FileHandler(config.LOG_FILENAME) -# create formatter -formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") -# add formatter to handler -handler.setFormatter(formatter) -# add handler to logger -logger.addHandler(handler) - +logger = config.logger def init_grid(simulation_bounds, cells_number): grid = list() @@ -101,12 +89,12 @@ def get_emissions(grid: List[Area], vehicles: List[Vehicle]): if area.emissions > config.EMISSIONS_THRESHOLD: if config.limit_speed_mode and not area.limited_speed: - logger.info(f'Action - Decrease of max speed into {area.name} by {config.speed_rf*100}%') + logger.info(f'Action - Decreased max speed into {area.name} by {config.speed_rf*100}%') actions.limit_speed_into_area(area, vehicles, config.speed_rf) traci.polygon.setColor(area.name, (255, 0, 0)) traci.polygon.setFilled(area.name, True) if config.adjust_traffic_light_mode and not area.tls_adjusted: - logger.info(f'Action - Decrease of traffic lights duration by {config.trafficLights_duration_rf*100}%') + logger.info(f'Action - Decreased traffic lights duration by {config.trafficLights_duration_rf*100}%') actions.adjust_traffic_light_phase_duration(area, config.trafficLights_duration_rf) if config.lock_area_mode and not area.locked: