Spaces:
Running on Zero
Running on Zero
Commit ·
4c70ed5
1
Parent(s): 1e9a99a
chore: remove root-level duplicate simulation files and Dockerfile
Browse files- Dockerfile +0 -27
- baseline.py +0 -20
- build_network.py +0 -125
- demand.py +0 -186
- env.py +0 -255
- model.py +0 -60
- runner.py +0 -154
Dockerfile
DELETED
|
@@ -1,27 +0,0 @@
|
|
| 1 |
-
FROM python:3.11-slim
|
| 2 |
-
|
| 3 |
-
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 4 |
-
sumo sumo-tools \
|
| 5 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 6 |
-
|
| 7 |
-
ENV SUMO_HOME=/usr/share/sumo
|
| 8 |
-
ENV PYTHONUNBUFFERED=1
|
| 9 |
-
|
| 10 |
-
WORKDIR /app
|
| 11 |
-
|
| 12 |
-
COPY requirements.txt .
|
| 13 |
-
ENV PIP_DEFAULT_TIMEOUT=1000
|
| 14 |
-
RUN pip install --no-cache-dir -r requirements.txt
|
| 15 |
-
|
| 16 |
-
COPY . .
|
| 17 |
-
|
| 18 |
-
# Build the (fixed) network + phase strings once, at image build time,
|
| 19 |
-
# not on every request. sumo_config/*.xml and phases.json get baked in.
|
| 20 |
-
RUN python simulation/build_network.py
|
| 21 |
-
|
| 22 |
-
# Place your downloaded checkpoint at model_files/ppo_bangalore.pt before
|
| 23 |
-
# building, OR set BANTREL_CHECKPOINT to a path you fetch at container
|
| 24 |
-
# startup (e.g. via huggingface_hub.hf_hub_download in an entrypoint script).
|
| 25 |
-
|
| 26 |
-
EXPOSE 7860
|
| 27 |
-
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
baseline.py
DELETED
|
@@ -1,20 +0,0 @@
|
|
| 1 |
-
"""Fixed-cycle baseline controller — verbatim port of BanTRel.py Cell 9."""
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
class FixedCyclePolicy:
|
| 5 |
-
"""
|
| 6 |
-
Deterministic fixed-cycle traffic signal controller.
|
| 7 |
-
cycle_steps=3, step_length=10s -> 30s per phase, 60s full cycle.
|
| 8 |
-
"""
|
| 9 |
-
|
| 10 |
-
def __init__(self, cycle_steps: int = 3) -> None:
|
| 11 |
-
self.cycle_steps = cycle_steps
|
| 12 |
-
self.step_counter = 0
|
| 13 |
-
|
| 14 |
-
def choose_action(self, state) -> int:
|
| 15 |
-
phase = (self.step_counter // self.cycle_steps) % 2
|
| 16 |
-
self.step_counter += 1
|
| 17 |
-
return int(phase)
|
| 18 |
-
|
| 19 |
-
def reset(self) -> None:
|
| 20 |
-
self.step_counter = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
build_network.py
DELETED
|
@@ -1,125 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Builds the fixed 4-arm intersection network and derives the traffic-light
|
| 3 |
-
phase strings, exactly as done in BanTRel.py Cells 2-3.
|
| 4 |
-
|
| 5 |
-
This only depends on the intersection GEOMETRY (which never changes per
|
| 6 |
-
request), so it is run ONCE — at Docker image build time — rather than on
|
| 7 |
-
every simulation. Its output (sumo_config/intersection.net.xml and
|
| 8 |
-
sumo_config/phases.json) is committed into the image and just read by
|
| 9 |
-
env.py at request time. This avoids re-invoking netconvert + sumolib on
|
| 10 |
-
every single API call.
|
| 11 |
-
|
| 12 |
-
Run manually with: python simulation/build_network.py
|
| 13 |
-
"""
|
| 14 |
-
|
| 15 |
-
import json
|
| 16 |
-
import os
|
| 17 |
-
import subprocess
|
| 18 |
-
import sys
|
| 19 |
-
|
| 20 |
-
SUMO_CONFIG_DIR = os.path.join(os.path.dirname(__file__), "..", "sumo_config")
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
def build_network() -> None:
|
| 24 |
-
os.makedirs(SUMO_CONFIG_DIR, exist_ok=True)
|
| 25 |
-
|
| 26 |
-
NODES_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
| 27 |
-
<nodes>
|
| 28 |
-
<node id="center" x="0" y="0" type="traffic_light"/>
|
| 29 |
-
<node id="north" x="0" y="500" type="priority"/>
|
| 30 |
-
<node id="south" x="0" y="-500" type="priority"/>
|
| 31 |
-
<node id="east" x="500" y="0" type="priority"/>
|
| 32 |
-
<node id="west" x="-500" y="0" type="priority"/>
|
| 33 |
-
</nodes>"""
|
| 34 |
-
|
| 35 |
-
EDGES_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
| 36 |
-
<edges>
|
| 37 |
-
<edge id="N2C" from="north" to="center" numLanes="2" speed="13.89"/>
|
| 38 |
-
<edge id="S2C" from="south" to="center" numLanes="2" speed="13.89"/>
|
| 39 |
-
<edge id="E2C" from="east" to="center" numLanes="2" speed="13.89"/>
|
| 40 |
-
<edge id="W2C" from="west" to="center" numLanes="2" speed="13.89"/>
|
| 41 |
-
<edge id="C2N" from="center" to="north" numLanes="2" speed="13.89"/>
|
| 42 |
-
<edge id="C2S" from="center" to="south" numLanes="2" speed="13.89"/>
|
| 43 |
-
<edge id="C2E" from="center" to="east" numLanes="2" speed="13.89"/>
|
| 44 |
-
<edge id="C2W" from="center" to="west" numLanes="2" speed="13.89"/>
|
| 45 |
-
</edges>"""
|
| 46 |
-
|
| 47 |
-
nod_path = os.path.join(SUMO_CONFIG_DIR, "intersection.nod.xml")
|
| 48 |
-
edg_path = os.path.join(SUMO_CONFIG_DIR, "intersection.edg.xml")
|
| 49 |
-
net_path = os.path.join(SUMO_CONFIG_DIR, "intersection.net.xml")
|
| 50 |
-
|
| 51 |
-
with open(nod_path, "w") as f:
|
| 52 |
-
f.write(NODES_XML)
|
| 53 |
-
with open(edg_path, "w") as f:
|
| 54 |
-
f.write(EDGES_XML)
|
| 55 |
-
|
| 56 |
-
result = subprocess.run(
|
| 57 |
-
[
|
| 58 |
-
"netconvert",
|
| 59 |
-
f"--node-files={nod_path}",
|
| 60 |
-
f"--edge-files={edg_path}",
|
| 61 |
-
f"--output-file={net_path}",
|
| 62 |
-
"--tls.guess=true",
|
| 63 |
-
"--tls.guess-signals=true",
|
| 64 |
-
"--no-warnings",
|
| 65 |
-
],
|
| 66 |
-
capture_output=True,
|
| 67 |
-
text=True,
|
| 68 |
-
)
|
| 69 |
-
|
| 70 |
-
net_size = os.path.getsize(net_path) if os.path.exists(net_path) else 0
|
| 71 |
-
if net_size < 5000:
|
| 72 |
-
raise RuntimeError(
|
| 73 |
-
f"netconvert failed to produce a valid network "
|
| 74 |
-
f"({net_size} bytes). stderr:\n{result.stderr[:600]}"
|
| 75 |
-
)
|
| 76 |
-
# NOTE: netconvert is known to segfault (-11) on some builds *after*
|
| 77 |
-
# successfully writing the file — same caveat as the original notebook.
|
| 78 |
-
print(f"netconvert return code: {result.returncode} "
|
| 79 |
-
f"(-11 after a valid file is a known harmless segfault)")
|
| 80 |
-
print(f"Network written: {net_path} ({net_size:,} bytes)")
|
| 81 |
-
|
| 82 |
-
# ---- derive phase strings from the compiled network ----
|
| 83 |
-
sumo_home = os.environ.get("SUMO_HOME", "/usr/share/sumo")
|
| 84 |
-
sys.path.append(os.path.join(sumo_home, "tools"))
|
| 85 |
-
import sumolib # noqa: E402
|
| 86 |
-
|
| 87 |
-
def _build_phase_strings(green_indices, length):
|
| 88 |
-
green = ["r"] * length
|
| 89 |
-
yellow = ["r"] * length
|
| 90 |
-
for i in green_indices:
|
| 91 |
-
green[i] = "G"
|
| 92 |
-
yellow[i] = "y"
|
| 93 |
-
return "".join(green), "".join(yellow)
|
| 94 |
-
|
| 95 |
-
net = sumolib.net.readNet(net_path)
|
| 96 |
-
tls = net.getTrafficLights()[0]
|
| 97 |
-
conns = tls.getConnections()
|
| 98 |
-
n = len(conns)
|
| 99 |
-
|
| 100 |
-
ns_indices, ew_indices = [], []
|
| 101 |
-
for idx, (from_lane, _to_lane, _link) in enumerate(conns):
|
| 102 |
-
edge_id = from_lane.getEdge().getID()
|
| 103 |
-
if edge_id in ("N2C", "S2C"):
|
| 104 |
-
ns_indices.append(idx)
|
| 105 |
-
elif edge_id in ("E2C", "W2C"):
|
| 106 |
-
ew_indices.append(idx)
|
| 107 |
-
|
| 108 |
-
ns_green, ns_yellow = _build_phase_strings(ns_indices, n)
|
| 109 |
-
ew_green, ew_yellow = _build_phase_strings(ew_indices, n)
|
| 110 |
-
|
| 111 |
-
phases = {
|
| 112 |
-
"tls_id": tls.getID(),
|
| 113 |
-
"NS_GREEN": ns_green, "NS_YELLOW": ns_yellow,
|
| 114 |
-
"EW_GREEN": ew_green, "EW_YELLOW": ew_yellow,
|
| 115 |
-
}
|
| 116 |
-
phases_path = os.path.join(SUMO_CONFIG_DIR, "phases.json")
|
| 117 |
-
with open(phases_path, "w") as f:
|
| 118 |
-
json.dump(phases, f, indent=2)
|
| 119 |
-
|
| 120 |
-
print(f"Phases written: {phases_path}")
|
| 121 |
-
print(phases)
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
if __name__ == "__main__":
|
| 125 |
-
build_network()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
demand.py
DELETED
|
@@ -1,186 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Route-file generation, generalized from BanTRel.py Cell 4.
|
| 3 |
-
|
| 4 |
-
The original notebook hardcoded one schedule (the 16,400 veh/day Bangalore
|
| 5 |
-
split) and one mix (60/30/10 car/bike/auto). This module keeps that as the
|
| 6 |
-
"preset" option, and adds a "custom" path that scales the SAME 7-period
|
| 7 |
-
day-shape (so the model still sees a realistic time-of-day pattern it was
|
| 8 |
-
trained on) by a user-chosen total volume, with a user-chosen vehicle mix.
|
| 9 |
-
|
| 10 |
-
Scaling the known shape (rather than inventing an arbitrary schedule) keeps
|
| 11 |
-
state normalisation (MAX_QUEUE=80, MAX_WAIT=600 in env.py) meaningful —
|
| 12 |
-
wildly different shapes would push the model into state regions it never
|
| 13 |
-
saw during training.
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
import os
|
| 17 |
-
from typing import Literal
|
| 18 |
-
|
| 19 |
-
SECONDS_PER_HOUR = 3600
|
| 20 |
-
|
| 21 |
-
# Each entry: (begin_s, end_s, total_vehicles, label) — verbatim from BanTRel.py
|
| 22 |
-
DEFAULT_SCHEDULE = [
|
| 23 |
-
(0, 8 * SECONDS_PER_HOUR, 550, "Night (00:00-08:00)"),
|
| 24 |
-
(8 * SECONDS_PER_HOUR, 11 * SECONDS_PER_HOUR, 4000, "Morning rush (08:00-11:00)"),
|
| 25 |
-
(11 * SECONDS_PER_HOUR, 13 * SECONDS_PER_HOUR, 2850, "Mid-morning (11:00-13:00)"),
|
| 26 |
-
(13 * SECONDS_PER_HOUR, 16 * SECONDS_PER_HOUR, 2100, "Afternoon (13:00-16:00)"),
|
| 27 |
-
(16 * SECONDS_PER_HOUR, 20 * SECONDS_PER_HOUR, 4400, "Evening rush (16:00-20:00)"),
|
| 28 |
-
(20 * SECONDS_PER_HOUR, 23 * SECONDS_PER_HOUR, 2500, "Evening (20:00-23:00)"),
|
| 29 |
-
(23 * SECONDS_PER_HOUR, 86400, 550, "Night (23:00-24:00)"),
|
| 30 |
-
]
|
| 31 |
-
DEFAULT_TOTAL = sum(t for _, _, t, _ in DEFAULT_SCHEDULE) # 16,400
|
| 32 |
-
DEFAULT_MIX = {"car": 0.60, "bike": 0.30, "auto": 0.10}
|
| 33 |
-
|
| 34 |
-
PRESET_PERIOD_IDS = {
|
| 35 |
-
"night": DEFAULT_SCHEDULE[0],
|
| 36 |
-
"morning_rush": DEFAULT_SCHEDULE[1],
|
| 37 |
-
"mid_morning": DEFAULT_SCHEDULE[2],
|
| 38 |
-
"afternoon": DEFAULT_SCHEDULE[3],
|
| 39 |
-
"evening_rush": DEFAULT_SCHEDULE[4],
|
| 40 |
-
"evening": DEFAULT_SCHEDULE[5],
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
ALL_ROUTES = [
|
| 44 |
-
("route_ns", "N2C C2S"), ("route_nw", "N2C C2W"), ("route_ne", "N2C C2E"),
|
| 45 |
-
("route_sn", "S2C C2N"), ("route_sw", "S2C C2W"), ("route_se", "S2C C2E"),
|
| 46 |
-
("route_en", "E2C C2N"), ("route_ew", "E2C C2W"), ("route_es", "E2C C2S"),
|
| 47 |
-
("route_wn", "W2C C2N"), ("route_we", "W2C C2E"), ("route_ws", "W2C C2S"),
|
| 48 |
-
]
|
| 49 |
-
|
| 50 |
-
VEHICLE_TYPES_XML = (
|
| 51 |
-
' <vType id="car" accel="2.6" decel="4.5" sigma="0.5" '
|
| 52 |
-
'length="5" minGap="2.5" maxSpeed="13.89"/>\n'
|
| 53 |
-
' <vType id="bike" accel="3.0" decel="5.0" sigma="0.6" '
|
| 54 |
-
'length="2" minGap="1.5" maxSpeed="11.11" vClass="motorcycle"/>\n'
|
| 55 |
-
' <vType id="auto" accel="2.0" decel="4.0" sigma="0.5" '
|
| 56 |
-
'length="4" minGap="2.0" maxSpeed="11.11"/>'
|
| 57 |
-
)
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
def build_schedule(
|
| 61 |
-
mode: Literal["preset", "custom"],
|
| 62 |
-
total_vehicles: int | None = None,
|
| 63 |
-
period: str | None = None,
|
| 64 |
-
) -> list[tuple[int, int, int, str]]:
|
| 65 |
-
"""
|
| 66 |
-
mode="preset", period=None -> full 24h canonical Bangalore day
|
| 67 |
-
mode="preset", period="morning_rush" -> just that one period, run in isolation
|
| 68 |
-
mode="custom", total_vehicles=N -> full 24h shape, each period scaled so
|
| 69 |
-
the day sums to N vehicles instead of 16,400
|
| 70 |
-
"""
|
| 71 |
-
if mode == "preset":
|
| 72 |
-
if period is None:
|
| 73 |
-
return DEFAULT_SCHEDULE
|
| 74 |
-
if period not in PRESET_PERIOD_IDS:
|
| 75 |
-
raise ValueError(f"Unknown period '{period}'. Options: {list(PRESET_PERIOD_IDS)}")
|
| 76 |
-
begin, end, total, label = PRESET_PERIOD_IDS[period]
|
| 77 |
-
# Re-anchor to start at t=0 so the episode is just this period's length.
|
| 78 |
-
return [(0, end - begin, total, label)]
|
| 79 |
-
|
| 80 |
-
if mode == "custom":
|
| 81 |
-
if not total_vehicles or total_vehicles <= 0:
|
| 82 |
-
raise ValueError("custom mode requires total_vehicles > 0")
|
| 83 |
-
scale = total_vehicles / DEFAULT_TOTAL
|
| 84 |
-
return [
|
| 85 |
-
(begin, end, max(1, round(total * scale)), label)
|
| 86 |
-
for begin, end, total, label in DEFAULT_SCHEDULE
|
| 87 |
-
]
|
| 88 |
-
|
| 89 |
-
raise ValueError(f"Unknown mode '{mode}'")
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
def make_route_file(
|
| 93 |
-
filepath: str,
|
| 94 |
-
schedule: list[tuple[int, int, int, str]],
|
| 95 |
-
mix: dict[str, float] | None = None,
|
| 96 |
-
) -> int:
|
| 97 |
-
"""Writes the SUMO route file. Returns the number of <flow> entries written."""
|
| 98 |
-
mix = mix or DEFAULT_MIX
|
| 99 |
-
total_pct = sum(mix.values())
|
| 100 |
-
if abs(total_pct - 1.0) > 0.01:
|
| 101 |
-
raise ValueError(f"Vehicle mix must sum to 1.0 (got {total_pct:.3f})")
|
| 102 |
-
|
| 103 |
-
route_tags = "\n".join(
|
| 104 |
-
f' <route id="{rid}" edges="{edges}"/>' for rid, edges in ALL_ROUTES
|
| 105 |
-
)
|
| 106 |
-
|
| 107 |
-
flow_tags = []
|
| 108 |
-
flow_id = 0
|
| 109 |
-
for begin, end, total_veh, _label in schedule:
|
| 110 |
-
duration_hr = max((end - begin) / SECONDS_PER_HOUR, 1e-6)
|
| 111 |
-
total_per_hr = total_veh / duration_hr
|
| 112 |
-
per_route_hr = total_per_hr / len(ALL_ROUTES)
|
| 113 |
-
|
| 114 |
-
for route_id, _ in ALL_ROUTES:
|
| 115 |
-
tag = route_id.removeprefix("route_")
|
| 116 |
-
for vtype, proportion in mix.items():
|
| 117 |
-
rate = per_route_hr * proportion
|
| 118 |
-
if rate <= 0:
|
| 119 |
-
continue
|
| 120 |
-
flow_tags.append(
|
| 121 |
-
f' <flow id="f{flow_id:04d}_{vtype}_{tag}" '
|
| 122 |
-
f'route="{route_id}" type="{vtype}" '
|
| 123 |
-
f'begin="{begin}" end="{end}" '
|
| 124 |
-
f'vehsPerHour="{rate:.1f}" '
|
| 125 |
-
f'departSpeed="max" departPos="base" departLane="best"/>'
|
| 126 |
-
)
|
| 127 |
-
flow_id += 1
|
| 128 |
-
|
| 129 |
-
xml = (
|
| 130 |
-
'<?xml version="1.0" encoding="UTF-8"?>\n<routes>\n'
|
| 131 |
-
+ VEHICLE_TYPES_XML + "\n\n"
|
| 132 |
-
+ route_tags + "\n\n"
|
| 133 |
-
+ "\n".join(flow_tags) + "\n</routes>"
|
| 134 |
-
)
|
| 135 |
-
with open(filepath, "w") as f:
|
| 136 |
-
f.write(xml)
|
| 137 |
-
return flow_id
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
def make_sumocfg(route_filename: str, net_filename: str, cfg_path: str,
|
| 141 |
-
duration: int, step_length: int = 10) -> None:
|
| 142 |
-
xml = f"""<?xml version="1.0" encoding="UTF-8"?>
|
| 143 |
-
<configuration>
|
| 144 |
-
<input>
|
| 145 |
-
<net-file value="{net_filename}"/>
|
| 146 |
-
<route-files value="{route_filename}"/>
|
| 147 |
-
</input>
|
| 148 |
-
<time>
|
| 149 |
-
<begin value="0"/>
|
| 150 |
-
<end value="{duration}"/>
|
| 151 |
-
<step-length value="{step_length}"/>
|
| 152 |
-
</time>
|
| 153 |
-
</configuration>"""
|
| 154 |
-
with open(cfg_path, "w") as f:
|
| 155 |
-
f.write(xml)
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
def prepare_run_config(
|
| 159 |
-
run_dir: str,
|
| 160 |
-
net_path: str,
|
| 161 |
-
mode: Literal["preset", "custom"],
|
| 162 |
-
total_vehicles: int | None = None,
|
| 163 |
-
period: str | None = None,
|
| 164 |
-
mix: dict[str, float] | None = None,
|
| 165 |
-
step_length: int = 10,
|
| 166 |
-
) -> str:
|
| 167 |
-
"""
|
| 168 |
-
Builds a fresh .rou.xml + .sumocfg for one simulation run inside run_dir
|
| 169 |
-
(a per-job temp directory, so concurrent requests never collide on files).
|
| 170 |
-
Returns the .sumocfg path.
|
| 171 |
-
"""
|
| 172 |
-
os.makedirs(run_dir, exist_ok=True)
|
| 173 |
-
schedule = build_schedule(mode, total_vehicles, period)
|
| 174 |
-
duration = schedule[-1][1] # end time of the last period
|
| 175 |
-
|
| 176 |
-
route_path = os.path.join(run_dir, "routes.rou.xml")
|
| 177 |
-
cfg_path = os.path.join(run_dir, "sim.sumocfg")
|
| 178 |
-
|
| 179 |
-
n_flows = make_route_file(route_path, schedule, mix)
|
| 180 |
-
if n_flows == 0:
|
| 181 |
-
raise ValueError("Generated route file has zero flows — check demand/mix inputs.")
|
| 182 |
-
|
| 183 |
-
# sumocfg references the shared, pre-built network by relative path.
|
| 184 |
-
net_filename = os.path.relpath(net_path, run_dir)
|
| 185 |
-
make_sumocfg("routes.rou.xml", net_filename, cfg_path, duration, step_length)
|
| 186 |
-
return cfg_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
env.py
DELETED
|
@@ -1,255 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
SUMO/TraCI environment — ported near-verbatim from BanTRel.py Cell 8
|
| 3 |
-
(BangaloreSumoEnv). Behaviour, state vector, reward, and metric definitions
|
| 4 |
-
are kept identical to the source notebook so the trained model sees exactly
|
| 5 |
-
the observation distribution it was trained on.
|
| 6 |
-
|
| 7 |
-
Only change from the original: phase strings (NS_GREEN/EW_GREEN/etc.) are
|
| 8 |
-
loaded from sumo_config/phases.json (built once by build_network.py) instead
|
| 9 |
-
of being recomputed via sumolib on every episode.
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
-
import json
|
| 13 |
-
import os
|
| 14 |
-
import socket
|
| 15 |
-
import subprocess
|
| 16 |
-
import time
|
| 17 |
-
import xml.etree.ElementTree as ET
|
| 18 |
-
|
| 19 |
-
import numpy as np
|
| 20 |
-
import traci
|
| 21 |
-
|
| 22 |
-
STEP_LENGTH = 10 # simulated seconds per simulation step
|
| 23 |
-
|
| 24 |
-
FREE_FLOW_TIME = {
|
| 25 |
-
"car": 500.0 / 13.89,
|
| 26 |
-
"bike": 500.0 / 11.11,
|
| 27 |
-
"auto": 500.0 / 11.11,
|
| 28 |
-
}
|
| 29 |
-
DEFAULT_FREE_FLOW = 500.0 / 13.89
|
| 30 |
-
|
| 31 |
-
_PHASES_CACHE = None
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def _load_phases(sumo_config_dir: str) -> dict:
|
| 35 |
-
global _PHASES_CACHE
|
| 36 |
-
if _PHASES_CACHE is None:
|
| 37 |
-
path = os.path.join(sumo_config_dir, "phases.json")
|
| 38 |
-
with open(path) as f:
|
| 39 |
-
_PHASES_CACHE = json.load(f)
|
| 40 |
-
return _PHASES_CACHE
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def _get_free_port() -> int:
|
| 44 |
-
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
| 45 |
-
s.bind(("", 0))
|
| 46 |
-
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
| 47 |
-
return s.getsockname()[1]
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
class BangaloreSumoEnv:
|
| 51 |
-
"""SUMO gym-style environment for the single signalised intersection."""
|
| 52 |
-
|
| 53 |
-
YELLOW_DURATION = 1 # 1 step = 10 s
|
| 54 |
-
MIN_GREEN = 8 # 8 steps = 80 s
|
| 55 |
-
|
| 56 |
-
MAX_QUEUE = 80.0
|
| 57 |
-
MAX_WAIT = 600.0
|
| 58 |
-
MAX_SPEED = 13.89
|
| 59 |
-
|
| 60 |
-
INCOMING_EDGES = ("N2C", "S2C", "E2C", "W2C")
|
| 61 |
-
|
| 62 |
-
def __init__(self, cfg_path: str, sumo_config_dir: str) -> None:
|
| 63 |
-
self.cfg_path = os.path.abspath(cfg_path)
|
| 64 |
-
phases = _load_phases(sumo_config_dir)
|
| 65 |
-
self.tls_id = phases["tls_id"]
|
| 66 |
-
self.PHASES = {
|
| 67 |
-
0: (phases["NS_GREEN"], phases["NS_YELLOW"]),
|
| 68 |
-
1: (phases["EW_GREEN"], phases["EW_YELLOW"]),
|
| 69 |
-
}
|
| 70 |
-
self.current_step = 0
|
| 71 |
-
self.current_phase = 0
|
| 72 |
-
self._running = False
|
| 73 |
-
self._proc = None
|
| 74 |
-
self.max_steps = self._parse_max_steps()
|
| 75 |
-
self._reset_metric_buffers()
|
| 76 |
-
|
| 77 |
-
def _parse_max_steps(self) -> int:
|
| 78 |
-
tree = ET.parse(self.cfg_path)
|
| 79 |
-
end_tag = tree.find(".//end")
|
| 80 |
-
step_tag = tree.find(".//step-length")
|
| 81 |
-
end_val = int(end_tag.get("value", 86400)) if end_tag is not None else 86400
|
| 82 |
-
step_val = int(step_tag.get("value", 10)) if step_tag is not None else 10
|
| 83 |
-
return end_val // step_val
|
| 84 |
-
|
| 85 |
-
def _reset_metric_buffers(self) -> None:
|
| 86 |
-
self._buf_total_stopped: list = []
|
| 87 |
-
self._buf_total_waiting_time: list = []
|
| 88 |
-
self._buf_mean_waiting_time: list = []
|
| 89 |
-
self._buf_mean_speed: list = []
|
| 90 |
-
self._buf_queue_length: list = []
|
| 91 |
-
self._buf_throughput: list = []
|
| 92 |
-
self._buf_avg_travel_time: list = []
|
| 93 |
-
self._buf_delay: list = []
|
| 94 |
-
self._vehicles_arrived: int = 0
|
| 95 |
-
self._total_travel_time: float = 0.0
|
| 96 |
-
self._vehicle_entry_step: dict = {}
|
| 97 |
-
|
| 98 |
-
def reset(self) -> np.ndarray:
|
| 99 |
-
self._safe_close()
|
| 100 |
-
self._reset_metric_buffers()
|
| 101 |
-
|
| 102 |
-
port = _get_free_port()
|
| 103 |
-
cmd = [
|
| 104 |
-
"sumo", "-c", self.cfg_path,
|
| 105 |
-
"--no-step-log", "--no-warnings", "--random", "--quit-on-end",
|
| 106 |
-
"--remote-port", str(port),
|
| 107 |
-
]
|
| 108 |
-
self._proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
| 109 |
-
time.sleep(1.0)
|
| 110 |
-
|
| 111 |
-
if self._proc.poll() is not None:
|
| 112 |
-
stderr = self._proc.stderr.read().decode()
|
| 113 |
-
raise RuntimeError(f"SUMO crashed on startup:\n{stderr}")
|
| 114 |
-
|
| 115 |
-
traci.init(port=port, numRetries=10)
|
| 116 |
-
self._running = True
|
| 117 |
-
self.current_step = 0
|
| 118 |
-
self.current_phase = 0
|
| 119 |
-
traci.trafficlight.setRedYellowGreenState(self.tls_id, self.PHASES[0][0])
|
| 120 |
-
return self._observe()
|
| 121 |
-
|
| 122 |
-
def step(self, action: int):
|
| 123 |
-
if action != self.current_phase:
|
| 124 |
-
traci.trafficlight.setRedYellowGreenState(
|
| 125 |
-
self.tls_id, self.PHASES[self.current_phase][1]
|
| 126 |
-
)
|
| 127 |
-
for _ in range(self.YELLOW_DURATION):
|
| 128 |
-
traci.simulationStep()
|
| 129 |
-
self._record()
|
| 130 |
-
self.current_step += 1
|
| 131 |
-
|
| 132 |
-
traci.trafficlight.setRedYellowGreenState(self.tls_id, self.PHASES[action][0])
|
| 133 |
-
self.current_phase = action
|
| 134 |
-
|
| 135 |
-
reward = 0.0
|
| 136 |
-
for _ in range(self.MIN_GREEN):
|
| 137 |
-
traci.simulationStep()
|
| 138 |
-
self._record()
|
| 139 |
-
self.current_step += 1
|
| 140 |
-
reward -= sum(traci.edge.getWaitingTime(e) for e in self.INCOMING_EDGES)
|
| 141 |
-
|
| 142 |
-
done = self.current_step >= self.max_steps
|
| 143 |
-
return self._observe(), reward, done
|
| 144 |
-
|
| 145 |
-
def close(self) -> None:
|
| 146 |
-
self._safe_close()
|
| 147 |
-
|
| 148 |
-
def _observe(self) -> np.ndarray:
|
| 149 |
-
ns_queue = sum(traci.edge.getLastStepHaltingNumber(e) for e in ("N2C", "S2C"))
|
| 150 |
-
ew_queue = sum(traci.edge.getLastStepHaltingNumber(e) for e in ("E2C", "W2C"))
|
| 151 |
-
ns_wait = sum(traci.edge.getWaitingTime(e) for e in ("N2C", "S2C"))
|
| 152 |
-
ew_wait = sum(traci.edge.getWaitingTime(e) for e in ("E2C", "W2C"))
|
| 153 |
-
ns_speed = float(np.mean([traci.edge.getLastStepMeanSpeed(e) for e in ("N2C", "S2C")]))
|
| 154 |
-
ew_speed = float(np.mean([traci.edge.getLastStepMeanSpeed(e) for e in ("E2C", "W2C")]))
|
| 155 |
-
time_of_day = self.current_step / max(self.max_steps, 1)
|
| 156 |
-
|
| 157 |
-
return np.array([
|
| 158 |
-
min(ns_queue / self.MAX_QUEUE, 1.0),
|
| 159 |
-
min(ew_queue / self.MAX_QUEUE, 1.0),
|
| 160 |
-
min(ns_wait / self.MAX_WAIT, 1.0),
|
| 161 |
-
min(ew_wait / self.MAX_WAIT, 1.0),
|
| 162 |
-
min(ns_speed / self.MAX_SPEED, 1.0),
|
| 163 |
-
min(ew_speed / self.MAX_SPEED, 1.0),
|
| 164 |
-
float(self.current_phase),
|
| 165 |
-
float(time_of_day),
|
| 166 |
-
], dtype=np.float32)
|
| 167 |
-
|
| 168 |
-
def _record(self) -> None:
|
| 169 |
-
incoming_vids: list = []
|
| 170 |
-
for edge in self.INCOMING_EDGES:
|
| 171 |
-
incoming_vids.extend(traci.edge.getLastStepVehicleIDs(edge))
|
| 172 |
-
|
| 173 |
-
for vid in traci.vehicle.getIDList():
|
| 174 |
-
if vid not in self._vehicle_entry_step:
|
| 175 |
-
self._vehicle_entry_step[vid] = self.current_step
|
| 176 |
-
|
| 177 |
-
arrived = traci.simulation.getArrivedIDList()
|
| 178 |
-
for vid in arrived:
|
| 179 |
-
if vid in self._vehicle_entry_step:
|
| 180 |
-
travel = (self.current_step - self._vehicle_entry_step[vid]) * STEP_LENGTH
|
| 181 |
-
self._total_travel_time += travel
|
| 182 |
-
self._vehicles_arrived += 1
|
| 183 |
-
self._buf_throughput.append(len(arrived))
|
| 184 |
-
|
| 185 |
-
avg_travel = self._total_travel_time / max(self._vehicles_arrived, 1)
|
| 186 |
-
n = len(incoming_vids)
|
| 187 |
-
|
| 188 |
-
if n == 0:
|
| 189 |
-
self._buf_total_stopped.append(0)
|
| 190 |
-
self._buf_total_waiting_time.append(0.0)
|
| 191 |
-
self._buf_mean_waiting_time.append(0.0)
|
| 192 |
-
self._buf_mean_speed.append(0.0)
|
| 193 |
-
self._buf_queue_length.append(0)
|
| 194 |
-
self._buf_avg_travel_time.append(avg_travel)
|
| 195 |
-
self._buf_delay.append(0.0)
|
| 196 |
-
return
|
| 197 |
-
|
| 198 |
-
speeds = [traci.vehicle.getSpeed(v) for v in incoming_vids]
|
| 199 |
-
waits = [traci.vehicle.getWaitingTime(v) for v in incoming_vids]
|
| 200 |
-
|
| 201 |
-
delays = []
|
| 202 |
-
for vid in incoming_vids:
|
| 203 |
-
try:
|
| 204 |
-
ff = FREE_FLOW_TIME.get(traci.vehicle.getTypeID(vid), DEFAULT_FREE_FLOW)
|
| 205 |
-
delays.append(max(0.0, traci.vehicle.getWaitingTime(vid) - ff))
|
| 206 |
-
except Exception:
|
| 207 |
-
delays.append(0.0)
|
| 208 |
-
|
| 209 |
-
total_queue = sum(traci.edge.getLastStepHaltingNumber(e) for e in self.INCOMING_EDGES)
|
| 210 |
-
|
| 211 |
-
self._buf_total_stopped.append(int(sum(1 for s in speeds if s < 0.1)))
|
| 212 |
-
self._buf_total_waiting_time.append(float(sum(waits)))
|
| 213 |
-
self._buf_mean_waiting_time.append(float(np.mean(waits)))
|
| 214 |
-
self._buf_mean_speed.append(float(np.mean(speeds)))
|
| 215 |
-
self._buf_queue_length.append(int(total_queue))
|
| 216 |
-
self._buf_avg_travel_time.append(avg_travel)
|
| 217 |
-
self._buf_delay.append(float(np.mean(delays)) if delays else 0.0)
|
| 218 |
-
|
| 219 |
-
def _safe_close(self) -> None:
|
| 220 |
-
if self._running:
|
| 221 |
-
try:
|
| 222 |
-
traci.close()
|
| 223 |
-
except Exception:
|
| 224 |
-
pass
|
| 225 |
-
self._running = False
|
| 226 |
-
if self._proc is not None:
|
| 227 |
-
try:
|
| 228 |
-
self._proc.kill()
|
| 229 |
-
self._proc.wait()
|
| 230 |
-
except Exception:
|
| 231 |
-
pass
|
| 232 |
-
self._proc = None
|
| 233 |
-
subprocess.run(["pkill", "-9", "-f", "sumo"], capture_output=True)
|
| 234 |
-
time.sleep(0.5)
|
| 235 |
-
|
| 236 |
-
def get_metrics(self) -> dict:
|
| 237 |
-
return {
|
| 238 |
-
"system_total_stopped": np.array(self._buf_total_stopped),
|
| 239 |
-
"system_total_waiting_time": np.array(self._buf_total_waiting_time),
|
| 240 |
-
"system_mean_waiting_time": np.array(self._buf_mean_waiting_time),
|
| 241 |
-
"system_mean_speed": np.array(self._buf_mean_speed),
|
| 242 |
-
"avg_waiting_time": np.array(self._buf_mean_waiting_time),
|
| 243 |
-
"avg_travel_time": np.array(self._buf_avg_travel_time),
|
| 244 |
-
"queue_length": np.array(self._buf_queue_length),
|
| 245 |
-
"throughput": np.array(self._buf_throughput),
|
| 246 |
-
"delay": np.array(self._buf_delay),
|
| 247 |
-
}
|
| 248 |
-
|
| 249 |
-
@property
|
| 250 |
-
def n_actions(self) -> int:
|
| 251 |
-
return 2
|
| 252 |
-
|
| 253 |
-
@property
|
| 254 |
-
def state_dim(self) -> int:
|
| 255 |
-
return 8
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
model.py
DELETED
|
@@ -1,60 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
ActorCritic architecture — verbatim port of network.py, so `torch.load`ing
|
| 3 |
-
your `best_ppo_bangalore.pt` / HF checkpoint state_dict works unmodified.
|
| 4 |
-
|
| 5 |
-
PPOPolicy wraps it for serving:
|
| 6 |
-
- deterministic=True -> argmax over action logits (default for the web
|
| 7 |
-
demo: reproducible, same input always gives the same output).
|
| 8 |
-
- deterministic=False -> samples from Categorical(logits), matching the
|
| 9 |
-
exact `run_evaluation` protocol used in BanTRel.py Cell 13. Pass a seed
|
| 10 |
-
for reproducible sampling.
|
| 11 |
-
"""
|
| 12 |
-
|
| 13 |
-
import numpy as np
|
| 14 |
-
import torch
|
| 15 |
-
import torch.nn as nn
|
| 16 |
-
from torch.distributions import Categorical
|
| 17 |
-
|
| 18 |
-
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
class ActorCritic(nn.Module):
|
| 22 |
-
def __init__(self, state_dim: int = 8, action_dim: int = 2, hidden: int = 64) -> None:
|
| 23 |
-
super().__init__()
|
| 24 |
-
self.backbone = nn.Sequential(
|
| 25 |
-
nn.Linear(state_dim, hidden), nn.Tanh(),
|
| 26 |
-
nn.Linear(hidden, hidden), nn.Tanh(),
|
| 27 |
-
)
|
| 28 |
-
self.actor = nn.Linear(hidden, action_dim)
|
| 29 |
-
self.critic = nn.Linear(hidden, 1)
|
| 30 |
-
|
| 31 |
-
def forward(self, x: torch.Tensor):
|
| 32 |
-
features = self.backbone(x)
|
| 33 |
-
return self.actor(features), self.critic(features)
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
class PPOPolicy:
|
| 37 |
-
"""Inference-only wrapper. Has .choose_action(state) + .reset() like FixedCyclePolicy,
|
| 38 |
-
so runner.py can treat both policies identically."""
|
| 39 |
-
|
| 40 |
-
def __init__(self, checkpoint_path: str, deterministic: bool = True, seed: int | None = None):
|
| 41 |
-
self.net = ActorCritic().to(DEVICE)
|
| 42 |
-
state_dict = torch.load(checkpoint_path, map_location=DEVICE)
|
| 43 |
-
self.net.load_state_dict(state_dict)
|
| 44 |
-
self.net.eval()
|
| 45 |
-
self.deterministic = deterministic
|
| 46 |
-
self._rng = np.random.default_rng(seed) if seed is not None else None
|
| 47 |
-
if seed is not None:
|
| 48 |
-
torch.manual_seed(seed)
|
| 49 |
-
|
| 50 |
-
def choose_action(self, state: np.ndarray) -> int:
|
| 51 |
-
with torch.no_grad():
|
| 52 |
-
tensor = torch.FloatTensor(state).unsqueeze(0).to(DEVICE)
|
| 53 |
-
logits, _value = self.net(tensor)
|
| 54 |
-
if self.deterministic:
|
| 55 |
-
return int(torch.argmax(logits, dim=-1).item())
|
| 56 |
-
dist = Categorical(logits=logits)
|
| 57 |
-
return int(dist.sample().item())
|
| 58 |
-
|
| 59 |
-
def reset(self) -> None:
|
| 60 |
-
pass # stateless across steps — nothing to reset
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
runner.py
DELETED
|
@@ -1,154 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Orchestrates one "simulate" job: builds demand -> runs the requested
|
| 3 |
-
policy/policies -> aggregates metrics -> (optionally) produces a
|
| 4 |
-
PPO-vs-Fixed-Cycle verdict table, using the exact metric definitions and
|
| 5 |
-
tie-thresholds from BanTRel.py Cell 17.
|
| 6 |
-
"""
|
| 7 |
-
|
| 8 |
-
import shutil
|
| 9 |
-
import tempfile
|
| 10 |
-
from typing import Literal
|
| 11 |
-
|
| 12 |
-
import numpy as np
|
| 13 |
-
|
| 14 |
-
from . import demand
|
| 15 |
-
from .baseline import FixedCyclePolicy
|
| 16 |
-
from .env import BangaloreSumoEnv
|
| 17 |
-
from .model import PPOPolicy
|
| 18 |
-
|
| 19 |
-
ALL_METRICS_DEF = [
|
| 20 |
-
# (key, label, higher_is_better, unit)
|
| 21 |
-
("system_total_stopped", "Total Stopped Vehicles", False, "vehicles"),
|
| 22 |
-
("system_total_waiting_time", "Total Waiting Time", False, "seconds"),
|
| 23 |
-
("system_mean_waiting_time", "Mean Waiting Time", False, "s / vehicle"),
|
| 24 |
-
("system_mean_speed", "Mean Speed", True, "m/s"),
|
| 25 |
-
("avg_waiting_time", "Avg Waiting Time", False, "s / vehicle"),
|
| 26 |
-
("avg_travel_time", "Avg Travel Time", False, "seconds"),
|
| 27 |
-
("queue_length", "Queue Length", False, "vehicles"),
|
| 28 |
-
("throughput", "Throughput", True, "veh / step"),
|
| 29 |
-
("delay", "Delay vs Free-Flow", False, "seconds"),
|
| 30 |
-
]
|
| 31 |
-
|
| 32 |
-
TIE_THRESHOLD = {
|
| 33 |
-
"system_total_stopped": 0.05, "system_total_waiting_time": 1.0,
|
| 34 |
-
"system_mean_waiting_time": 0.5, "system_mean_speed": 0.005,
|
| 35 |
-
"avg_waiting_time": 0.5, "avg_travel_time": 1.0,
|
| 36 |
-
"queue_length": 0.05, "throughput": 0.01, "delay": 0.5,
|
| 37 |
-
}
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
def _run_policy_episodes(policy, cfg_path: str, sumo_config_dir: str, n_runs: int) -> dict:
|
| 41 |
-
"""Ported from Cell 13's run_evaluation()."""
|
| 42 |
-
buffers = {k: [] for k, *_ in ALL_METRICS_DEF}
|
| 43 |
-
|
| 44 |
-
for _run in range(n_runs):
|
| 45 |
-
env = BangaloreSumoEnv(cfg_path, sumo_config_dir)
|
| 46 |
-
state = env.reset()
|
| 47 |
-
if hasattr(policy, "reset"):
|
| 48 |
-
policy.reset()
|
| 49 |
-
done = False
|
| 50 |
-
try:
|
| 51 |
-
while not done:
|
| 52 |
-
action = policy.choose_action(state)
|
| 53 |
-
state, _reward, done = env.step(action)
|
| 54 |
-
m = env.get_metrics()
|
| 55 |
-
for k, *_ in ALL_METRICS_DEF:
|
| 56 |
-
if k in m and len(m[k]):
|
| 57 |
-
buffers[k].append(m[k])
|
| 58 |
-
finally:
|
| 59 |
-
env.close()
|
| 60 |
-
|
| 61 |
-
averaged = {}
|
| 62 |
-
for k, runs in buffers.items():
|
| 63 |
-
if not runs:
|
| 64 |
-
continue
|
| 65 |
-
min_len = min(len(r) for r in runs)
|
| 66 |
-
averaged[k] = np.mean([r[:min_len] for r in runs], axis=0)
|
| 67 |
-
return averaged
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
def _summarize(metrics: dict) -> dict:
|
| 71 |
-
"""Scalar table: mean of each per-step array (what Cell 17 prints)."""
|
| 72 |
-
out = {}
|
| 73 |
-
for key, label, higher_better, unit in ALL_METRICS_DEF:
|
| 74 |
-
arr = metrics.get(key)
|
| 75 |
-
if arr is None or not len(arr):
|
| 76 |
-
continue
|
| 77 |
-
out[key] = {
|
| 78 |
-
"label": label, "unit": unit, "higher_is_better": higher_better,
|
| 79 |
-
"value": round(float(np.mean(arr)), 3),
|
| 80 |
-
}
|
| 81 |
-
return out
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
def _verdict(ppo_summary: dict, fc_summary: dict) -> dict:
|
| 85 |
-
wins_ppo = wins_fixed = ties = 0
|
| 86 |
-
rows = []
|
| 87 |
-
for key, label, higher_better, unit in ALL_METRICS_DEF:
|
| 88 |
-
if key not in ppo_summary or key not in fc_summary:
|
| 89 |
-
continue
|
| 90 |
-
pm, fcm = ppo_summary[key]["value"], fc_summary[key]["value"]
|
| 91 |
-
delta = pm - fcm
|
| 92 |
-
threshold = TIE_THRESHOLD.get(key, 0.01)
|
| 93 |
-
if abs(delta) < threshold:
|
| 94 |
-
outcome = "tie"; ties += 1
|
| 95 |
-
elif (delta > 0) if higher_better else (delta < 0):
|
| 96 |
-
outcome = "ppo"; wins_ppo += 1
|
| 97 |
-
else:
|
| 98 |
-
outcome = "fixed_cycle"; wins_fixed += 1
|
| 99 |
-
rows.append({"key": key, "label": label, "unit": unit,
|
| 100 |
-
"ppo": pm, "fixed_cycle": fcm, "delta": round(delta, 3),
|
| 101 |
-
"outcome": outcome})
|
| 102 |
-
overall = ("ppo" if wins_ppo > wins_fixed
|
| 103 |
-
else "fixed_cycle" if wins_fixed > wins_ppo else "draw")
|
| 104 |
-
return {"rows": rows, "wins_ppo": wins_ppo, "wins_fixed_cycle": wins_fixed,
|
| 105 |
-
"ties": ties, "overall": overall}
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
def run_simulation(
|
| 109 |
-
*,
|
| 110 |
-
net_path: str,
|
| 111 |
-
sumo_config_dir: str,
|
| 112 |
-
checkpoint_path: str,
|
| 113 |
-
policy: Literal["ppo", "fixed_cycle", "both"],
|
| 114 |
-
demand_mode: Literal["preset", "custom"],
|
| 115 |
-
total_vehicles: int | None,
|
| 116 |
-
period: str | None,
|
| 117 |
-
mix: dict[str, float] | None,
|
| 118 |
-
n_runs: int = 1,
|
| 119 |
-
deterministic: bool = True,
|
| 120 |
-
seed: int | None = None,
|
| 121 |
-
) -> dict:
|
| 122 |
-
run_dir = tempfile.mkdtemp(prefix="bantrel_job_")
|
| 123 |
-
try:
|
| 124 |
-
cfg_path = demand.prepare_run_config(
|
| 125 |
-
run_dir=run_dir, net_path=net_path, mode=demand_mode,
|
| 126 |
-
total_vehicles=total_vehicles, period=period, mix=mix,
|
| 127 |
-
)
|
| 128 |
-
|
| 129 |
-
result = {"policy_requested": policy, "n_runs": n_runs}
|
| 130 |
-
|
| 131 |
-
if policy in ("ppo", "both"):
|
| 132 |
-
ppo_policy = PPOPolicy(checkpoint_path, deterministic=deterministic, seed=seed)
|
| 133 |
-
ppo_metrics = _run_policy_episodes(ppo_policy, cfg_path, sumo_config_dir, n_runs)
|
| 134 |
-
result["ppo"] = {
|
| 135 |
-
"summary": _summarize(ppo_metrics),
|
| 136 |
-
"timeseries": {k: v.tolist() for k, v in ppo_metrics.items()},
|
| 137 |
-
}
|
| 138 |
-
|
| 139 |
-
if policy in ("fixed_cycle", "both"):
|
| 140 |
-
fc_policy = FixedCyclePolicy(cycle_steps=3)
|
| 141 |
-
fc_metrics = _run_policy_episodes(fc_policy, cfg_path, sumo_config_dir, n_runs)
|
| 142 |
-
result["fixed_cycle"] = {
|
| 143 |
-
"summary": _summarize(fc_metrics),
|
| 144 |
-
"timeseries": {k: v.tolist() for k, v in fc_metrics.items()},
|
| 145 |
-
}
|
| 146 |
-
|
| 147 |
-
if policy == "both":
|
| 148 |
-
result["comparison"] = _verdict(
|
| 149 |
-
result["ppo"]["summary"], result["fixed_cycle"]["summary"]
|
| 150 |
-
)
|
| 151 |
-
|
| 152 |
-
return result
|
| 153 |
-
finally:
|
| 154 |
-
shutil.rmtree(run_dir, ignore_errors=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|