1
0
mirror of https://github.com/Ahp06/SUMO_Emissions.git synced 2024-11-22 11:36:29 +00:00
sumo-emissions/sumo_project/emissions.py

246 lines
9.4 KiB
Python
Raw Normal View History

2018-12-10 12:33:53 +00:00
import argparse
2018-12-16 14:33:10 +00:00
import csv
2018-12-16 20:43:21 +00:00
import datetime
2018-12-16 20:35:37 +00:00
import itertools
2018-12-16 20:43:21 +00:00
import os
import sys
import time
from typing import List
2018-12-07 15:30:23 +00:00
2018-12-16 20:43:21 +00:00
import traci
2018-12-07 16:40:16 +00:00
from parse import search
from shapely.geometry import LineString
import actions
2018-12-10 12:33:53 +00:00
from config import Config
2018-12-16 20:43:21 +00:00
from model import Area, Vehicle, Lane, TrafficLight, Phase, Logic, Emission
2018-12-16 20:35:37 +00:00
# Absolute path of the directory the script is in
SCRIPTDIR = os.path.dirname(__file__)
2018-12-16 20:43:21 +00:00
def init_grid(simulation_bounds, areas_number, window_size):
grid = list()
width = simulation_bounds[1][0] / areas_number
height = simulation_bounds[1][1] / areas_number
for i in range(areas_number):
for j in range(areas_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))
2018-12-14 14:50:26 +00:00
name = 'Area ({},{})'.format(i, j)
area = Area(ar_bounds, name, window_size)
grid.append(area)
2018-12-14 14:50:26 +00:00
traci.polygon.add(area.name, ar_bounds, (255, 0, 0))
return grid
2018-12-12 09:13:33 +00:00
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)
2018-12-03 20:05:01 +00:00
lanes.append(Lane(lane_id, polygon_lane, initial_max_speed))
return lanes
2018-12-12 09:13:33 +00:00
2018-12-07 16:16:26 +00:00
def parse_phase(phase_repr):
2018-12-03 20:05:01 +00:00
duration = search('duration: {:f}', phase_repr)
2018-12-18 09:57:11 +00:00
min_duration = search('minDuration: {:f}', phase_repr)
max_duration = search('maxDuration: {:f}', phase_repr)
phase_def = search('phaseDef: {}\n', phase_repr)
2018-12-03 20:05:01 +00:00
2018-12-16 20:43:21 +00:00
if phase_def is None:
phase_def = ''
else:
phase_def = phase_def[0]
2018-12-03 20:05:01 +00:00
2018-12-16 20:43:21 +00:00
return Phase(duration[0], min_duration[0], max_duration[0], phase_def)
2018-12-12 09:13:33 +00:00
def add_data_to_areas(areas: List[Area]):
lanes = get_all_lanes()
for area in areas:
2018-12-03 20:05:01 +00:00
for lane in lanes: # add lanes
if area.rectangle.intersects(lane.polygon):
2018-12-03 20:05:01 +00:00
area.add_lane(lane)
for tl_id in traci.trafficlight.getIDList(): # add traffic lights
if lane.lane_id in traci.trafficlight.getControlledLanes(tl_id):
2018-12-03 20:05:01 +00:00
logics = []
2018-12-12 09:13:33 +00:00
for l in traci.trafficlight.getCompleteRedYellowGreenDefinition(tl_id): # add logics
2018-12-03 20:05:01 +00:00
phases = []
2018-12-12 09:13:33 +00:00
for phase in traci.trafficlight.Logic.getPhases(l): # add phases to logics
2018-12-07 16:16:26 +00:00
phases.append(parse_phase(phase.__repr__()))
2018-12-16 20:43:21 +00:00
logics.append(Logic(l, phases))
2018-12-12 09:13:33 +00:00
area.add_tl(TrafficLight(tl_id, logics))
2018-12-07 15:30:23 +00:00
def compute_vehicle_emissions(veh_id):
co2 = traci.vehicle.getCO2Emission(veh_id)
co = traci.vehicle.getCOEmission(veh_id)
nox = traci.vehicle.getNOxEmission(veh_id)
hc = traci.vehicle.getHCEmission(veh_id)
pmx = traci.vehicle.getPMxEmission(veh_id)
2018-12-16 20:43:21 +00:00
return Emission(co2, co, nox, hc, pmx)
2018-12-07 15:30:23 +00:00
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
2018-12-12 09:13:33 +00:00
2018-12-10 15:26:14 +00:00
def get_emissions(grid: List[Area], vehicles: List[Vehicle], current_step, config, logger):
2018-12-07 15:30:23 +00:00
for area in grid:
total_emissions = Emission()
2018-12-07 15:30:23 +00:00
for vehicle in vehicles:
if vehicle.pos in area:
total_emissions += vehicle.emissions
2018-12-16 20:43:21 +00:00
area.emissions_by_step.append(total_emissions)
2018-12-16 20:43:21 +00:00
if area.sum_emissions_into_window(current_step, config.window_size) >= config.emissions_threshold:
2018-12-07 15:30:23 +00:00
if config.limit_speed_mode and not area.limited_speed:
2018-12-16 20:43:21 +00:00
logger.info(f'Action - Decreased max speed into {area.name} by {config.speed_rf * 100}%')
2018-12-07 15:30:23 +00:00
actions.limit_speed_into_area(area, vehicles, config.speed_rf)
if config.adjust_traffic_light_mode and not area.tls_adjusted:
2018-12-16 20:43:21 +00:00
logger.info(
f'Action - Decreased traffic lights duration by {config.trafficLights_duration_rf * 100}%')
2018-12-07 15:30:23 +00:00
actions.adjust_traffic_light_phase_duration(area, config.trafficLights_duration_rf)
2018-12-16 20:43:21 +00:00
2018-12-07 15:30:23 +00:00
if config.lock_area_mode and not area.locked:
if actions.count_vehicles_in_area(area):
logger.info(f'Action - {area.name} blocked')
actions.lock_area(area)
2018-12-16 20:43:21 +00:00
2018-12-14 14:50:26 +00:00
if config.weight_routing_mode and not area.weight_adjusted:
actions.adjust_edges_weights(area)
2018-12-16 20:43:21 +00:00
2018-12-10 15:26:14 +00:00
traci.polygon.setFilled(area.name, True)
2018-12-16 20:43:21 +00:00
2018-12-09 14:05:33 +00:00
else:
actions.reverse_actions(area)
2018-12-14 14:50:26 +00:00
traci.polygon.setFilled(area.name, False)
2018-12-07 15:30:23 +00:00
2018-12-16 20:43:21 +00:00
def get_reduction_percentage(ref, total):
return (ref - total) / ref * 100
2018-12-16 14:33:10 +00:00
2018-12-16 20:35:37 +00:00
2018-12-16 14:33:10 +00:00
def export_data_to_csv(config, grid):
2018-12-16 20:35:37 +00:00
csv_dir = os.path.join(SCRIPTDIR, 'csv')
if not os.path.exists(csv_dir):
os.mkdir(csv_dir)
now = datetime.datetime.utcnow().isoformat()
with open(os.path.join(csv_dir, f'{now}.csv'), 'w') as f:
writer = csv.writer(f)
# Write CSV headers
writer.writerow(itertools.chain(('Step',), (a.name for a in grid)))
2018-12-19 10:02:19 +00:00
# Write all areas emission value for each step
for step in range(config.n_steps):
em_for_step = (f'{a.emissions_by_step[step].value():.3f}' for a in grid)
writer.writerow(itertools.chain((step,), em_for_step))
2018-12-16 20:35:37 +00:00
2018-12-10 15:26:14 +00:00
def run(config, logger):
grid = list()
try:
traci.start(config.sumo_cmd)
logger.info(f'Loaded simulation file : {config._SUMOCFG}')
2018-12-07 15:30:23 +00:00
logger.info('Loading data for the simulation')
start = time.perf_counter()
2018-12-16 20:43:21 +00:00
2018-12-14 14:50:26 +00:00
grid = init_grid(traci.simulation.getNetBoundary(), config.areas_number, config.window_size)
add_data_to_areas(grid)
2018-12-16 20:43:21 +00:00
2018-12-12 09:13:33 +00:00
loading_time = round(time.perf_counter() - start, 2)
2018-12-07 15:30:23 +00:00
logger.info(f'Data loaded ({loading_time}s)')
2018-12-16 20:43:21 +00:00
2018-12-14 14:50:26 +00:00
logger.info('Simulation started...')
2018-12-16 20:43:21 +00:00
step = 0
while step < config.n_steps: # traci.simulation.getMinExpectedNumber() > 0:
traci.simulationStep()
2018-12-16 20:43:21 +00:00
vehicles = get_all_vehicles()
2018-12-12 09:13:33 +00:00
get_emissions(grid, vehicles, step, config, logger)
step += 1
2018-12-16 20:43:21 +00:00
2018-12-14 14:50:26 +00:00
print(f'step = {step}/{config.n_steps}', end='\r')
2018-12-16 20:43:21 +00:00
finally:
traci.close(False)
2018-12-16 20:43:21 +00:00
export_data_to_csv(config, grid)
2018-12-12 09:13:33 +00:00
simulation_time = round(time.perf_counter() - start, 2)
2018-12-07 15:46:54 +00:00
logger.info(f'End of the simulation ({simulation_time}s)')
2018-12-16 20:43:21 +00:00
logger.info(f'Real-time factor : {config.n_steps / simulation_time}')
total_emissions = Emission()
for area in grid:
total_emissions += area.sum_all_emissions()
2018-12-16 20:43:21 +00:00
logger.info(f'Total emissions = {total_emissions.value()} mg')
2018-12-16 20:43:21 +00:00
if not config.without_actions_mode:
ref = config.get_ref_emissions()
if not (ref is None):
2018-12-16 20:43:21 +00:00
global_diff = (ref.value() - total_emissions.value()) / ref.value()
logger.info(f'Global reduction percentage of emissions = {global_diff * 100} %')
logger.info(f'-> CO2 emissions = {get_reduction_percentage(ref.co2, total_emissions.co2)} %')
logger.info(f'-> CO emissions = {get_reduction_percentage(ref.co, total_emissions.co)} %')
2018-12-16 20:43:21 +00:00
logger.info(f'-> Nox emissions = {get_reduction_percentage(ref.nox, total_emissions.nox)} %')
logger.info(f'-> HC emissions = {get_reduction_percentage(ref.hc, total_emissions.hc)} %')
logger.info(f'-> PMx emissions = {get_reduction_percentage(ref.pmx, total_emissions.pmx)} %')
2018-12-14 14:50:26 +00:00
def add_options(parser):
parser.add_argument("-f", "--configfile", type=str, default='configs/default_config.json', required=False,
help='Choose your configuration file from your working directory')
2018-12-16 20:43:21 +00:00
parser.add_argument("-save", "--save", action="store_true",
help='Save the logs into the logs folder')
parser.add_argument("-steps", "--steps", type=int, default=200, required=False,
help='Choose the simulated time (in seconds)')
parser.add_argument("-ref", "--ref", action="store_true",
2018-12-14 14:50:26 +00:00
help='Launch a reference simulation (without acting on areas)')
2018-12-16 20:43:21 +00:00
parser.add_argument("-gui", "--gui", action="store_true",
help="Set GUI mode")
2018-12-10 15:26:14 +00:00
def main(args):
parser = argparse.ArgumentParser(description="")
2018-12-14 14:50:26 +00:00
add_options(parser)
2018-12-10 15:26:14 +00:00
args = parser.parse_args(args)
2018-12-16 20:43:21 +00:00
2018-12-10 15:26:14 +00:00
config = Config()
config.import_config_file(args.configfile)
config.init_traci()
2018-12-12 09:13:33 +00:00
logger = config.init_logger(save_logs=args.save)
2018-12-16 20:43:21 +00:00
if args.ref:
config.without_actions_mode = True
logger.info(f'Reference simulation')
2018-12-16 20:43:21 +00:00
if args.steps:
config.n_steps = args.steps
2018-12-14 14:50:26 +00:00
if args.gui:
config._SUMOCMD = "sumo-gui"
2018-12-16 20:43:21 +00:00
2018-12-14 14:50:26 +00:00
config.check_config()
2018-12-16 20:43:21 +00:00
2018-12-14 14:50:26 +00:00
logger.info(f'Loaded configuration file : {args.configfile}')
2018-12-16 14:33:10 +00:00
logger.info(f'Simulated time : {args.steps}s')
2018-12-10 15:26:14 +00:00
run(config, logger)
2018-12-12 09:13:33 +00:00
2018-12-16 20:43:21 +00:00
if __name__ == '__main__':
2018-12-10 12:33:53 +00:00
main(sys.argv[1:])