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

81 lines
2.5 KiB
Python
Raw Normal View History

from typing import List
2018-11-14 13:56:54 +00:00
import traci
2018-11-15 21:15:43 +00:00
from shapely.geometry import LineString
2018-11-15 21:15:43 +00:00
import actions
import config
2018-11-15 21:15:43 +00:00
from model import Area, Vehicle, Lane
def init_grid(simulation_bounds, cells_number):
width = simulation_bounds[1][0] / cells_number
height = simulation_bounds[1][1] / cells_number
areas = list()
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)
areas.append(area)
traci.polygon.add(area.name, ar_bounds, (0, 255, 0))
return areas
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)
2018-11-15 21:15:43 +00:00
vehicle.co2 = traci.vehicle.getCO2Emission(vehicle.veh_id)
vehicles.append(vehicle)
return vehicles
2018-11-15 21:15:43 +00:00
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.co2
2018-11-14 13:56:54 +00:00
if area.emissions > config.CO2_THRESHOLD:
# print(f'Threshold exceeded in {area.name} : {area.emissions}')
2018-11-15 21:15:43 +00:00
if not area.locked:
actions.lock_area(area, vehicles)
traci.polygon.setColor(area.name, (255, 0, 0))
traci.polygon.setFilled(area.name, True)
2018-11-15 21:15:43 +00:00
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():
try:
2018-11-14 13:56:54 +00:00
traci.start(config.sumo_cmd)
grid = init_grid(traci.simulation.getNetBoundary(), config.CELLS_NUMBER)
2018-11-15 21:15:43 +00:00
add_lanes_to_areas(grid)
while traci.simulation.getMinExpectedNumber() > 0:
traci.simulationStep()
vehicles = get_all_vehicles()
get_emissions(grid, vehicles)
finally:
traci.close(False)
if __name__ == '__main__':
main()