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

176 lines
6.3 KiB
Python
Raw Normal View History

2019-01-19 18:56:59 +00:00
'''
Created on 19 janv. 2019
@author: Admin
'''
import argparse
import os
import sys
import time
import traci
import jsonpickle
from config import Config
from data import Data
import emissions
from model import Emission
def add_options(parser):
"""
Add command line options
:param parser: The command line parser
:return:
"""
parser.add_argument("-new_dump", "--new_dump", metavar=('config_file', 'dump_name'), nargs=2, type=str,
2019-01-20 08:43:21 +00:00
required=False, help='Load and create a new data dump with the configuration file chosen')
2019-01-19 18:56:59 +00:00
parser.add_argument("-run", "--run", type=str, required=False,
help='Run a simulation with the dump chosen')
parser.add_argument("-save", "--save", action="store_true",
help='Save the logs into the logs folder')
parser.add_argument("-csv", "--csv", action="store_true",
help="Export all data emissions into a CSV file")
2019-01-20 10:42:08 +00:00
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",
help='Launch a reference simulation (without acting on areas)')
parser.add_argument("-gui", "--gui", action="store_true",
help="Set GUI mode")
2019-01-19 18:56:59 +00:00
def create_dump(config_file, dump_name):
2019-01-20 10:42:08 +00:00
"""
Create a new dump with config file and dump_name chosen
:param config_file: The configuration file
:param dump_name: The dump name
:return:
"""
2019-01-19 18:56:59 +00:00
config = Config()
config.import_config_file(config_file)
config.check_config()
config.init_traci()
2019-01-19 20:26:37 +00:00
sumo_binary = os.path.join(os.environ['SUMO_HOME'], 'bin', 'sumo')
sumo_cmd = [sumo_binary, "-c", config._SUMOCFG]
traci.start(sumo_cmd)
2019-01-19 18:56:59 +00:00
if not os.path.isfile(f'files/dump/{dump_name}.json'):
start = time.perf_counter()
data = Data(traci.simulation.getNetBoundary(), config)
data.init_grid()
data.add_data_to_areas()
data.save(dump_name)
loading_time = round(time.perf_counter() - start, 2)
print(f'Data loaded ({loading_time}s)')
print(f'Dump {dump_name} created')
else:
print(f'Dump with name {dump_name} already exist')
traci.close(False)
2019-01-20 10:42:08 +00:00
def run(data : Data, logger):
"""
Run a data set
:param data: The data instance
:param logger: The logger instance
"""
2019-01-19 18:56:59 +00:00
try:
2019-01-20 10:42:08 +00:00
traci.start(data.config.sumo_cmd)
2019-01-19 20:26:37 +00:00
for area in data.grid:
traci.polygon.add(area.name, area.rectangle.exterior.coords, (255, 0, 0)) # Add polygon for UI
2019-01-20 10:42:08 +00:00
logger.info(f'Loaded simulation file : {data.config._SUMOCFG}')
2019-01-19 18:56:59 +00:00
logger.info('Loading data for the simulation')
start = time.perf_counter()
logger.info('Simulation started...')
step = 0
2019-01-20 10:42:08 +00:00
while step < data.config.n_steps:
2019-01-19 18:56:59 +00:00
traci.simulationStep()
vehicles = emissions.get_all_vehicles()
2019-01-20 10:42:08 +00:00
emissions.get_emissions(data.grid, vehicles, step, data.config, logger)
2019-01-19 18:56:59 +00:00
step += 1
2019-01-20 10:42:08 +00:00
print(f'step = {step}/{data.config.n_steps}', end='\r')
2019-01-19 18:56:59 +00:00
finally:
traci.close(False)
def main(args):
"""
The entry point of the application
:param args: Command line options
:return:
"""
parser = argparse.ArgumentParser()
add_options(parser)
args = parser.parse_args(args)
if args.new_dump is not None:
2019-01-20 10:42:08 +00:00
create_dump(args.new_dump[0], args.new_dump[1]) # (config_file, dump_name)
2019-01-19 18:56:59 +00:00
if args.run is not None:
dump_path = f'files/dump/{args.run}.json'
2019-01-19 20:26:37 +00:00
if os.path.isfile(dump_path):
2019-01-19 18:56:59 +00:00
with open(dump_path, 'r') as f:
data = jsonpickle.decode(f.read())
2019-01-20 10:42:08 +00:00
data.config.init_traci()
logger = data.config.init_logger(dump_name=args.run, save_logs=args.save)
if args.gui:
data.config._SUMOCMD = "sumo-gui"
if args.ref:
data.config.without_actions_mode = True
logger.info(f'Reference simulation')
if args.steps:
data.config.n_steps = args.steps
data.config.check_config()
2019-01-19 20:26:37 +00:00
logger.info(f'Running simulation dump {args.run}...')
start = time.perf_counter()
2019-01-20 10:42:08 +00:00
run(data, logger)
simulation_time = round(time.perf_counter() - start, 2)
logger.info(f'End of the simulation ({simulation_time}s)')
2019-01-19 18:56:59 +00:00
if args.csv:
2019-01-20 10:42:08 +00:00
emissions.export_data_to_csv(data.config, data.grid, dump_name=args.run)
2019-01-19 18:56:59 +00:00
logger.info(f'Exported data into the csv folder')
2019-01-19 20:26:37 +00:00
# 1 step is equal to one second simulated
2019-01-20 10:42:08 +00:00
logger.info(f'Real-time factor : {data.config.n_steps / simulation_time}')
2019-01-19 18:56:59 +00:00
2019-01-19 20:26:37 +00:00
total_emissions = Emission()
for area in data.grid:
total_emissions += area.sum_all_emissions()
2019-01-19 18:56:59 +00:00
2019-01-19 20:26:37 +00:00
logger.info(f'Total emissions = {total_emissions.value()} mg')
2019-01-19 18:56:59 +00:00
2019-01-20 10:42:08 +00:00
if not data.config.without_actions_mode: # If it's not a simulation without actions
ref = data.config.get_ref_emissions()
2019-01-19 20:26:37 +00:00
if not (ref is None): # If a reference value exist (add yours into config.py)
global_diff = (ref.value() - total_emissions.value()) / ref.value()
2019-01-19 18:56:59 +00:00
2019-01-19 20:26:37 +00:00
logger.info(f'Global reduction percentage of emissions = {global_diff * 100} %')
logger.info(f'-> CO2 emissions = {emissions.get_reduction_percentage(ref.co2, total_emissions.co2)} %')
logger.info(f'-> CO emissions = {emissions.get_reduction_percentage(ref.co, total_emissions.co)} %')
logger.info(f'-> Nox emissions = {emissions.get_reduction_percentage(ref.nox, total_emissions.nox)} %')
logger.info(f'-> HC emissions = {emissions.get_reduction_percentage(ref.hc, total_emissions.hc)} %')
logger.info(f'-> PMx emissions = {emissions.get_reduction_percentage(ref.pmx, total_emissions.pmx)} %')
2019-01-19 18:56:59 +00:00
if __name__ == '__main__':
main(sys.argv[1:])