Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions GreenWave_ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,12 @@ With `green_wave_mode: "DISABLED"` the route and the open-road motion are exactl
$$\frac{d}{v} + C_{\mathrm{remaining}} \cdot \frac{d}{L_{\mathrm{remaining}}},$$
so the speed is at least $v_f$ (on edges whose limit is above it), never above $v$, and carries across edge ends.

A later stop line replaces an active crossing with its own decision (a fresh crossing if it is not green). Each intersection's route signals share one cycle phase, so the lines of one through movement show the same colour. The crossing is a modelling boundary (the ETL has no junction exit geometry), and $c$, $L_c$, $C_{\max}$, $v_f$ are PoC assumptions, not measured Kraków values; $L_c$ and $v_f$ are strictly positive and all are finite (ADR 0010). The pre-run standard estimate is a dry run of this motion: `standard_run_seconds` drives `move_one_second` in disabled mode against the pure ordinary programme (deterministic from $t = 0$, no ITS) until arrival, so `estimated_standard_time_sec` (start response) and `standard_seconds` (each ranked candidate) equal the disabled run's arrival exactly before rounding (ADR 0011; at most about 12 ms per route on the Kraków sample). $T_{\mathrm{normal}}$ stays the product's normal-traffic baseline: `current_time_saved_sec` compares the run's elapsed time with it in either mode, and the dashboard labels that number "vs normal traffic" in a disabled run. Implementation: `backend/src/greenwave/simulation/motion.py`.
A later stop line replaces an active crossing with its own decision (a fresh crossing if it is not green). Each intersection's route signals share one cycle phase, so the lines of one through movement show the same colour. The crossing is a modelling boundary (the ETL has no junction exit geometry), and $c$, $L_c$, $C_{\max}$, $v_f$ are PoC assumptions, not measured Kraków values; $L_c$ and $v_f$ are strictly positive and all are finite (ADR 0010). The pre-run standard estimate is a dry run of this motion: `standard_run_seconds` drives `move_one_second` in disabled mode against the pure ordinary programme (deterministic from $t = 0$, no ITS) until arrival, so `estimated_standard_time_sec` (start response) and `standard_seconds` (each ranked candidate) equal the disabled run's arrival exactly before rounding (ADR 0011; at most about 12 ms per route on the Kraków sample). `current_time_saved_sec` compares Green Wave elapsed time with this same standard run at the
same route position, interpolated between its one-second dry-run samples. At arrival it is
`round(T_standard) - round(T_actual)` so it agrees with the displayed whole-second totals;
post-arrival recovery never changes it. Disabled runs report zero and the UI hides savings.
`T_normal` and `estimated_normal_time_sec` remain legacy analytical estimates, not the savings
baseline (2026-10-29 correction: `docs/engineering/standard-mode-fix.md`). Implementation: `backend/src/greenwave/simulation/motion.py`.

---

Expand Down Expand Up @@ -624,7 +629,7 @@ technology), instead of disappearing.
"tick": 383,
"timestamp": "2026-10-25T14:37:51Z",
"kpi_metrics": {
"current_time_saved_sec": 396,
"current_time_saved_sec": 72,
"total_time_elapsed_sec": 383
}
}
Expand Down
3 changes: 1 addition & 2 deletions backend/src/greenwave/simulation/assembly.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
from greenwave.simulation.cascade_check import find_cascade_mismatches
from greenwave.simulation.engine import SimulationEngine
from greenwave.simulation.route_model import build_route_model, to_start_response
from greenwave.simulation.standard_estimate import standard_run_seconds
from greenwave.simulation_settings import SimulationSettings

logger = logging.getLogger("greenwave.simulation.cascade_check")
Expand Down Expand Up @@ -83,7 +82,7 @@ def plan_simulation(
estimates,
index,
green_wave_mode=mode,
standard_seconds=standard_run_seconds(route, route_model, density, settings),
standard_seconds=engine.standard_profile.total_seconds,
)
response.its_scenario = scenario
return PlannedSimulation(engine, response)
8 changes: 5 additions & 3 deletions backend/src/greenwave/simulation/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
from greenwave.simulation.priority_requests import PriorityRequestLedger
from greenwave.simulation.route_model import RouteModel
from greenwave.simulation.route_track import RouteTrack
from greenwave.simulation.standard_estimate import standard_run_profile
from greenwave.simulation.state import EngineState, initial_engine_state
from greenwave.simulation.telemetry import (
ambulance_telemetry,
Expand Down Expand Up @@ -87,6 +88,9 @@ def __init__(
self._last_phases: tuple[SignalPhaseIndicator, ...] = ()
self._closed = False
self._track = RouteTrack.from_route(route, settings)
self.standard_profile = standard_run_profile(
route, route_model, traffic_density_multiplier, settings
)
# Intersections controlling each stop-line position, for the hold at the line.
self._stop_line_ids: dict[float, set[str]] = {}
for stop in route.stop_lines:
Expand Down Expand Up @@ -195,9 +199,7 @@ def step(
if selected:
state, dispatch = self._dispatch(state, selected, wall_clock_utc)
events.append(dispatch)
kpi = kpi_metrics(
self.route, self.route_model, state, self.traffic_density_multiplier, self.settings
)
kpi = kpi_metrics(state, self.standard_profile, self.green_wave_mode)
ambulance = ambulance_telemetry(self.vehicle_type, state, actual_speed, self._track)
intersections = intersection_telemetry(self.route_model, state)
tick = tick_event(
Expand Down
48 changes: 46 additions & 2 deletions backend/src/greenwave/simulation/standard_estimate.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Exact pre-run standard-traffic estimate: a dry run of disabled motion (spec D4)."""

from bisect import bisect_left
from dataclasses import dataclass
from math import ceil, inf

from greenwave.its.controller import SimulatedItsController
Expand All @@ -12,18 +14,53 @@
from greenwave.simulation_settings import SimulationSettings


@dataclass(frozen=True, slots=True)
class StandardRunProfile:
"""Disabled motion sampled each second, with an exact final arrival sample."""

distances_m: tuple[float, ...]
seconds: tuple[float, ...]

@property
def total_seconds(self) -> float:
return self.seconds[-1]

def seconds_at(self, distance_m: float) -> float:
"""Time to the same route position; interpolate within a one-second sample."""
if distance_m <= 0:
return 0.0
right = bisect_left(self.distances_m, distance_m)
if right >= len(self.distances_m):
return self.total_seconds
left = right - 1
fraction = (distance_m - self.distances_m[left]) / (
self.distances_m[right] - self.distances_m[left]
)
return self.seconds[left] + fraction * (self.seconds[right] - self.seconds[left])


def standard_run_seconds(
route: PlannedRoute,
route_model: RouteModel,
density: float,
settings: SimulationSettings,
) -> float:
"""Exact pre-run standard arrival time, shared with ranking and the start response."""
return standard_run_profile(route, route_model, density, settings).total_seconds


def standard_run_profile(
route: PlannedRoute,
route_model: RouteModel,
density: float,
settings: SimulationSettings,
) -> StandardRunProfile:
"""Simulated seconds a run with ER Green Wave disabled takes to arrive.

Disabled motion never requests priority, so its every stop-line decision comes from the
ordinary programme, which is deterministic from t = 0: this drives the same
:func:`move_one_second` as the engine, against an untouched controller's ordinary queries,
and returns the engine's ``arrived_at_s`` exactly.
and records the engine's ``arrived_at_s`` exactly.
"""
track = RouteTrack.from_route(route, settings)
controller = SimulatedItsController(route_model, settings, ItsScenario.NOMINAL)
Expand All @@ -36,6 +73,8 @@ def standard_run_seconds(
if bound_s == inf:
raise RuntimeError("standard run cannot arrive: a route edge has no positive speed")
max_iterations = ceil(bound_s) + 1
distances = [0.0]
seconds = [0.0]
for _ in range(max_iterations):
state, _moved = move_one_second(
state,
Expand All @@ -47,8 +86,13 @@ def standard_run_seconds(
controller.ordinary_route_color_at,
route_seconds_until_green=controller.ordinary_route_seconds_until_green,
)
distances.append(state.distance_travelled_m)
seconds.append(
state.arrived_at_s if state.arrived_at_s is not None else float(state.simulated_time_s)
)
if state.arrived_at_s is not None:
return state.arrived_at_s
controller.close()
return StandardRunProfile(tuple(distances), tuple(seconds))
raise RuntimeError(f"standard run did not arrive within {max_iterations} simulated seconds")


Expand Down
32 changes: 9 additions & 23 deletions backend/src/greenwave/simulation/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@

from datetime import datetime

from greenwave.routing.edge_times import normal_edge_seconds
from greenwave.routing.planner import PlannedRoute
from greenwave.schemas import (
AmbulanceStatus,
AmbulanceTelemetry,
GreenWaveMode,
IntersectionTelemetry,
KpiMetrics,
SignalPhaseIndicator,
Expand All @@ -17,8 +16,8 @@
from greenwave.simulation.corridor import ACTIVE_STATES, route_runtimes, time_to_intersection
from greenwave.simulation.route_model import RouteModel
from greenwave.simulation.route_track import RouteTrack
from greenwave.simulation.standard_estimate import StandardRunProfile
from greenwave.simulation.state import EngineState
from greenwave.simulation_settings import SimulationSettings

# Simulated vehicle ids shown by the dashboard; the mock transport uses the same ones.
VEHICLE_IDS: dict[VehicleType, str] = {
Expand Down Expand Up @@ -75,30 +74,17 @@ def intersection_telemetry(


def kpi_metrics(
route: PlannedRoute,
route_model: RouteModel,
state: EngineState,
traffic_density_multiplier: float,
settings: SimulationSettings,
standard_profile: StandardRunProfile,
mode: GreenWaveMode,
) -> KpiMetrics:
normal = sum(
# Same normal-mode edge times as estimate_times, for the share of each edge covered.
normal_edge_seconds(edge, traffic_density_multiplier, settings)
* min(edge.length_m, max(0.0, state.distance_travelled_m - start))
/ edge.length_m
for edge, start in zip(route.edges, route.cumulative_m, strict=True)
)
# Credited once the vehicle reaches the last stop line, whenever its priority is released.
normal += sum(
item.delay_seconds
for item in route_model.intersections
if item.last_stop_line_m <= state.distance_travelled_m
)
# Saved time compares with this simulated normal-traffic baseline in either mode.
# The trip ends on arrival (D15); post-arrival recovery ticks (D19) do not add trip time.
# Recovery after arrival cannot add trip time or erode the saving.
elapsed = state.arrived_at_s if state.arrived_at_s is not None else state.simulated_time_s
standard = standard_profile.seconds_at(state.distance_travelled_m)
return KpiMetrics(
current_time_saved_sec=round(normal - elapsed),
current_time_saved_sec=0
if mode is GreenWaveMode.DISABLED
else round(standard) - round(elapsed),
total_time_elapsed_sec=round(elapsed),
)

Expand Down
Loading
Loading