signallab-rl 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,26 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SignalLab contributors
4
+
5
+ This license applies to the new SignalLab application, documentation, and
6
+ presentation assets in this directory. Files in original/ are supplied by the
7
+ project owner, retain their existing rights, and are excluded from this grant.
8
+ Third-party dependencies remain subject to their own licenses.
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ include tools/train_policy_models.py
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: signallab-rl
3
+ Version: 0.2.0
4
+ Summary: Compare fixed-time and Q-learning traffic signals at a simulated intersection.
5
+ Author: Punith Dewangan
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://punith030.pythonanywhere.com/
8
+ Project-URL: Source, https://github.com/Punith-0/SignalLab
9
+ Keywords: traffic simulation,reinforcement learning,q-learning,education
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: numpy>=1.24
14
+ Requires-Dist: matplotlib>=3.7
15
+ Provides-Extra: dashboard
16
+ Requires-Dist: Flask>=3.1; extra == "dashboard"
17
+ Provides-Extra: training
18
+ Requires-Dist: scikit-learn>=1.4; extra == "training"
19
+ Dynamic: license-file
20
+
21
+ # SignalLab Python
22
+
23
+ Compare a fixed-time traffic light and a Q-learning traffic light in a simulated intersection. Both controllers receive the same seeded arrivals.
24
+
25
+ Install from a local source checkout with `python -m pip install .`. To include the browser dashboard, use `python -m pip install ".[dashboard]"`. The dashboard and simulator run locally.
26
+
27
+ ```python
28
+ from signallab_rl import bengaluru_traffic_joke, policy_choice, simulate, traffic_presets
29
+
30
+ run = simulate(**traffic_presets()["ns_rush"], seed=42)
31
+ print(run["summary"])
32
+ print(policy_choice(2, 4, green="ew"))
33
+ print(bengaluru_traffic_joke())
34
+ ```
35
+
36
+ ## Run the local dashboard
37
+
38
+ ```python
39
+ from signallab_rl import build_simulator
40
+
41
+ if __name__ == "__main__":
42
+ app = build_simulator(theme="midnight", preset="ew_rush", seed=42)
43
+ app.run(port=8769)
44
+ ```
45
+
46
+ Open `http://127.0.0.1:8769/`. The dashboard opens with the selected combination. Change the theme, preset, arrival rates or seed, then choose **Run comparison**. You can download a CSV trace for either controller. The dashboard runs on your computer and requires no account.
47
+
48
+ Four themes are available: `garden`, `midnight`, `sunset`, and `monochrome`. The six traffic presets are `default`, `balanced`, `ns_rush`, `ew_rush`, `heavy`, and `quiet`. Pass `p_ns=` or `p_ew=` to override either starting probability.
49
+
50
+ ## API reference
51
+
52
+ | Function | Use |
53
+ |---|---|
54
+ | `simulate(p_ns, p_ew, seed)` | Run both controllers for 200 steps. Read `summary` for the comparison or `fixed` and `adaptive` for the step-by-step traces. |
55
+ | `evaluate(p_ns, p_ew)` | Compare results over 50 matched seeds and report mean and standard deviation. |
56
+ | `policy_choice(ns_queue, ew_queue, green=...)` | Read both Q-values and the learned keep or switch request for a given traffic state. |
57
+ | `load_q_table()` | Get an independent NumPy copy of the learned table with shape `(5, 5, 2, 2)`. |
58
+ | `plot_q_table(table=None, path=None)` | Show all 100 Q-values in four annotated heatmaps with one shared color scale. Pass a path to save the figure as an image. |
59
+ | `render_q_table_image(table=None, path=None)` | Create a printable table image with Keep and Switch values side by side for NS green and EW green. |
60
+ | `simulate_with_model(model, p_ns=..., p_ew=..., seed=...)` | Compare a fitted estimator against the fixed timer using matched arrivals. Returns the usual two traces and summary. |
61
+ | `available_policy_models()` | List the bundled model names, roles, source Q-table fingerprint and agreement across the 50 source states. |
62
+ | `load_policy_model(name="q_learning")` | Load a bundled model ready for `predict()` or `simulate_with_model()`, with no local training step. |
63
+ | `queue_bin(queue)` | Convert a nonnegative car count to the model's queue-bin index from 0 to 4. |
64
+ | `summarize_trace(frames)` | Calculate queue, reward, switch, arrival and departure statistics from a trace. |
65
+ | `trace_to_csv(frames)` | Convert a controller trace into a CSV string. |
66
+ | `traffic_presets()` | Get six ready-to-use sets of arrival probabilities for `simulate()`. |
67
+ | `available_themes()` | List the valid theme names for the dashboard. |
68
+ | `bengaluru_traffic_joke(seed=None)` | Get a Bengaluru traffic joke. Pass the same seed to repeat the selection. |
69
+ | `project_info()` | Get the project description, author, and GitHub links. |
70
+ | `build_simulator(theme=..., preset=..., p_ns=..., p_ew=..., seed=...)` | Create a Flask app that launches the dashboard with `.run()`. |
71
+
72
+ ## How the simulation works
73
+
74
+ Generate a PNG of the Q-table and display the same figure in a notebook:
75
+
76
+ ```python
77
+ from signallab_rl import plot_q_table, render_q_table_image
78
+
79
+ plot_q_table(path="q-table-heatmap.png")
80
+ render_q_table_image(path="q-table.png")
81
+ ```
82
+
83
+ ## Try a fitted machine-learning model
84
+
85
+ The original Q-table is the reference. The three bundled estimators were fitted offline from that same table and ship with their learned parameters.
86
+
87
+ To regenerate the bundled model parameters from the source distribution, install `.[training]` and run `python tools/train_policy_models.py` before building.
88
+
89
+ | Model | Role | Action agreement across the 50 source states |
90
+ |---|---|---:|
91
+ | `q_learning` | Look up the original values and choose the higher-scoring action. | 100% |
92
+ | `logistic` | Predict the reference action with a simple logistic classifier. | 76% |
93
+ | `linear_q` | Approximate the two numeric Q-values with linear regression, then choose the higher value. | 48% |
94
+ | `decision_tree` | Reproduce the reference action through splits on queue bins and phase. | 100% |
95
+
96
+ Agreement is measured across the Q-table states used for fitting. It measures fidelity to the table, including any zero-valued entries, and says nothing by itself about traffic performance. Run the simulator to compare actual queue and reward outcomes.
97
+
98
+ ```python
99
+ from signallab_rl import load_policy_model, simulate_with_model
100
+
101
+ model = load_policy_model("logistic")
102
+ run = simulate_with_model(model, p_ns=0.8, p_ew=0.2, seed=42)
103
+ print(run["summary"])
104
+ ```
105
+
106
+ The `q_learning` and `linear_q` models also provide `predict_q_values(states)`, returning Keep and Switch scores side by side.
107
+
108
+ You can also supply your own fitted model with a `predict(X)` method. Each feature row contains `[ns_bin, ew_bin, phase]`, and each prediction must be the integer `0` (keep) or `1` (request switch). The original simulation rules still determine whether a requested switch can execute.
109
+
110
+ This example uses scikit-learn to train a decision tree to imitate the supplied Q-table. Install scikit-learn separately if using this example.
111
+
112
+ ```python
113
+ import numpy as np
114
+ from sklearn.tree import DecisionTreeClassifier
115
+ from signallab_rl import load_q_table, simulate_with_model
116
+
117
+ table = load_q_table()
118
+ states = list(np.ndindex(table.shape[:3]))
119
+ actions = [int(table[state].argmax()) for state in states]
120
+ model = DecisionTreeClassifier(random_state=42).fit(states, actions)
121
+
122
+ run = simulate_with_model(model, p_ns=0.8, p_ew=0.2, seed=42)
123
+ print(run["summary"])
124
+ ```
125
+
126
+ Arrival probabilities range from 0 to 1 per direction per step. The Q-table uses the NS queue bin, EW queue bin, the phase (`0` for NS green or `1` for EW green), and the action (`0` for keep or `1` for request switch). Queue bins represent `0`, `1–2`, `3–5`, `6–9`, and `10+` cars. The simulator may block a switch request during the first three steps of green.
127
+
128
+ The package ships with SignalLab's supplied Q-table. Its results describe a simulated intersection. See the [SignalLab GitHub repository](https://github.com/Punith-0/SignalLab) for the web project.
@@ -0,0 +1,108 @@
1
+ # SignalLab Python
2
+
3
+ Compare a fixed-time traffic light and a Q-learning traffic light in a simulated intersection. Both controllers receive the same seeded arrivals.
4
+
5
+ Install from a local source checkout with `python -m pip install .`. To include the browser dashboard, use `python -m pip install ".[dashboard]"`. The dashboard and simulator run locally.
6
+
7
+ ```python
8
+ from signallab_rl import bengaluru_traffic_joke, policy_choice, simulate, traffic_presets
9
+
10
+ run = simulate(**traffic_presets()["ns_rush"], seed=42)
11
+ print(run["summary"])
12
+ print(policy_choice(2, 4, green="ew"))
13
+ print(bengaluru_traffic_joke())
14
+ ```
15
+
16
+ ## Run the local dashboard
17
+
18
+ ```python
19
+ from signallab_rl import build_simulator
20
+
21
+ if __name__ == "__main__":
22
+ app = build_simulator(theme="midnight", preset="ew_rush", seed=42)
23
+ app.run(port=8769)
24
+ ```
25
+
26
+ Open `http://127.0.0.1:8769/`. The dashboard opens with the selected combination. Change the theme, preset, arrival rates or seed, then choose **Run comparison**. You can download a CSV trace for either controller. The dashboard runs on your computer and requires no account.
27
+
28
+ Four themes are available: `garden`, `midnight`, `sunset`, and `monochrome`. The six traffic presets are `default`, `balanced`, `ns_rush`, `ew_rush`, `heavy`, and `quiet`. Pass `p_ns=` or `p_ew=` to override either starting probability.
29
+
30
+ ## API reference
31
+
32
+ | Function | Use |
33
+ |---|---|
34
+ | `simulate(p_ns, p_ew, seed)` | Run both controllers for 200 steps. Read `summary` for the comparison or `fixed` and `adaptive` for the step-by-step traces. |
35
+ | `evaluate(p_ns, p_ew)` | Compare results over 50 matched seeds and report mean and standard deviation. |
36
+ | `policy_choice(ns_queue, ew_queue, green=...)` | Read both Q-values and the learned keep or switch request for a given traffic state. |
37
+ | `load_q_table()` | Get an independent NumPy copy of the learned table with shape `(5, 5, 2, 2)`. |
38
+ | `plot_q_table(table=None, path=None)` | Show all 100 Q-values in four annotated heatmaps with one shared color scale. Pass a path to save the figure as an image. |
39
+ | `render_q_table_image(table=None, path=None)` | Create a printable table image with Keep and Switch values side by side for NS green and EW green. |
40
+ | `simulate_with_model(model, p_ns=..., p_ew=..., seed=...)` | Compare a fitted estimator against the fixed timer using matched arrivals. Returns the usual two traces and summary. |
41
+ | `available_policy_models()` | List the bundled model names, roles, source Q-table fingerprint and agreement across the 50 source states. |
42
+ | `load_policy_model(name="q_learning")` | Load a bundled model ready for `predict()` or `simulate_with_model()`, with no local training step. |
43
+ | `queue_bin(queue)` | Convert a nonnegative car count to the model's queue-bin index from 0 to 4. |
44
+ | `summarize_trace(frames)` | Calculate queue, reward, switch, arrival and departure statistics from a trace. |
45
+ | `trace_to_csv(frames)` | Convert a controller trace into a CSV string. |
46
+ | `traffic_presets()` | Get six ready-to-use sets of arrival probabilities for `simulate()`. |
47
+ | `available_themes()` | List the valid theme names for the dashboard. |
48
+ | `bengaluru_traffic_joke(seed=None)` | Get a Bengaluru traffic joke. Pass the same seed to repeat the selection. |
49
+ | `project_info()` | Get the project description, author, and GitHub links. |
50
+ | `build_simulator(theme=..., preset=..., p_ns=..., p_ew=..., seed=...)` | Create a Flask app that launches the dashboard with `.run()`. |
51
+
52
+ ## How the simulation works
53
+
54
+ Generate a PNG of the Q-table and display the same figure in a notebook:
55
+
56
+ ```python
57
+ from signallab_rl import plot_q_table, render_q_table_image
58
+
59
+ plot_q_table(path="q-table-heatmap.png")
60
+ render_q_table_image(path="q-table.png")
61
+ ```
62
+
63
+ ## Try a fitted machine-learning model
64
+
65
+ The original Q-table is the reference. The three bundled estimators were fitted offline from that same table and ship with their learned parameters.
66
+
67
+ To regenerate the bundled model parameters from the source distribution, install `.[training]` and run `python tools/train_policy_models.py` before building.
68
+
69
+ | Model | Role | Action agreement across the 50 source states |
70
+ |---|---|---:|
71
+ | `q_learning` | Look up the original values and choose the higher-scoring action. | 100% |
72
+ | `logistic` | Predict the reference action with a simple logistic classifier. | 76% |
73
+ | `linear_q` | Approximate the two numeric Q-values with linear regression, then choose the higher value. | 48% |
74
+ | `decision_tree` | Reproduce the reference action through splits on queue bins and phase. | 100% |
75
+
76
+ Agreement is measured across the Q-table states used for fitting. It measures fidelity to the table, including any zero-valued entries, and says nothing by itself about traffic performance. Run the simulator to compare actual queue and reward outcomes.
77
+
78
+ ```python
79
+ from signallab_rl import load_policy_model, simulate_with_model
80
+
81
+ model = load_policy_model("logistic")
82
+ run = simulate_with_model(model, p_ns=0.8, p_ew=0.2, seed=42)
83
+ print(run["summary"])
84
+ ```
85
+
86
+ The `q_learning` and `linear_q` models also provide `predict_q_values(states)`, returning Keep and Switch scores side by side.
87
+
88
+ You can also supply your own fitted model with a `predict(X)` method. Each feature row contains `[ns_bin, ew_bin, phase]`, and each prediction must be the integer `0` (keep) or `1` (request switch). The original simulation rules still determine whether a requested switch can execute.
89
+
90
+ This example uses scikit-learn to train a decision tree to imitate the supplied Q-table. Install scikit-learn separately if using this example.
91
+
92
+ ```python
93
+ import numpy as np
94
+ from sklearn.tree import DecisionTreeClassifier
95
+ from signallab_rl import load_q_table, simulate_with_model
96
+
97
+ table = load_q_table()
98
+ states = list(np.ndindex(table.shape[:3]))
99
+ actions = [int(table[state].argmax()) for state in states]
100
+ model = DecisionTreeClassifier(random_state=42).fit(states, actions)
101
+
102
+ run = simulate_with_model(model, p_ns=0.8, p_ew=0.2, seed=42)
103
+ print(run["summary"])
104
+ ```
105
+
106
+ Arrival probabilities range from 0 to 1 per direction per step. The Q-table uses the NS queue bin, EW queue bin, the phase (`0` for NS green or `1` for EW green), and the action (`0` for keep or `1` for request switch). Queue bins represent `0`, `1–2`, `3–5`, `6–9`, and `10+` cars. The simulator may block a switch request during the first three steps of green.
107
+
108
+ The package ships with SignalLab's supplied Q-table. Its results describe a simulated intersection. See the [SignalLab GitHub repository](https://github.com/Punith-0/SignalLab) for the web project.
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "signallab-rl"
7
+ version = "0.2.0"
8
+ description = "Compare fixed-time and Q-learning traffic signals at a simulated intersection."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{name = "Punith Dewangan"}]
14
+ keywords = ["traffic simulation", "reinforcement learning", "q-learning", "education"]
15
+ dependencies = ["numpy>=1.24", "matplotlib>=3.7"]
16
+
17
+ [project.urls]
18
+ Homepage = "https://punith030.pythonanywhere.com/"
19
+ Source = "https://github.com/Punith-0/SignalLab"
20
+
21
+ [project.optional-dependencies]
22
+ dashboard = ["Flask>=3.1"]
23
+ training = ["scikit-learn>=1.4"]
24
+
25
+ [tool.setuptools.packages.find]
26
+ where = ["src"]
27
+
28
+ [tool.setuptools.package-data]
29
+ signallab_rl = ["original/q_table.npy", "policy_models.json", "templates/*.html"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,34 @@
1
+ """Run and inspect SignalLab traffic-light simulations."""
2
+ from . import _engine
3
+ from ._dashboard import build_simulator
4
+ from ._engine import simulate
5
+ from ._models import available_policy_models, load_policy_model, simulate_with_model
6
+ from ._plots import plot_q_table, render_q_table_image
7
+ from ._tools import (available_themes, bengaluru_traffic_joke, load_q_table, project_info,
8
+ queue_bin, summarize_trace, trace_to_csv, traffic_presets)
9
+
10
+ __all__ = ["simulate", "evaluate", "policy_choice", "load_q_table", "queue_bin",
11
+ "summarize_trace", "trace_to_csv", "traffic_presets", "available_themes",
12
+ "bengaluru_traffic_joke", "project_info", "build_simulator", "plot_q_table",
13
+ "render_q_table_image", "simulate_with_model", "available_policy_models",
14
+ "load_policy_model"]
15
+
16
+
17
+ def evaluate(p_ns: float = 0.4, p_ew: float = 0.2) -> dict:
18
+ """Compare both controllers over the same 50 seeds and summarize variability."""
19
+ return _engine.evaluate_scenarios(p_ns, p_ew)
20
+
21
+
22
+ def policy_choice(ns_queue: int, ew_queue: int, *, green: str) -> dict:
23
+ """Return both Q-values and the learned action for the observed queues.
24
+
25
+ ``green`` is ``"ns"`` or ``"ew"``. The action ``"request_switch"`` can
26
+ still be blocked by the simulator's three-step minimum green.
27
+ """
28
+ if green not in ("ns", "ew"):
29
+ raise ValueError('green must be "ns" or "ew".')
30
+ ns_bin, ew_bin = map(queue_bin, (ns_queue, ew_queue))
31
+ table = load_q_table()
32
+ keep, switch = map(float, table[ns_bin, ew_bin, int(green == "ew")])
33
+ return {"action": "request_switch" if switch > keep else "keep",
34
+ "q_keep": keep, "q_switch": switch}
@@ -0,0 +1,60 @@
1
+ """Factory for the optional local dashboard."""
2
+ from ._engine import _validate_inputs, simulate
3
+ from ._tools import (available_themes, bengaluru_traffic_joke, project_info,
4
+ trace_to_csv, traffic_presets)
5
+
6
+
7
+ def build_simulator(*, theme: str = "garden", preset: str = "default",
8
+ p_ns: float | None = None, p_ew: float | None = None, seed: int = 42):
9
+ """Build a Flask dashboard. Call app.run() to start a localhost preview.
10
+
11
+ Explicit arrival probabilities override the selected preset's starting values.
12
+ Install the dashboard extra to use this factory.
13
+ """
14
+ presets = traffic_presets()
15
+ themes = available_themes()
16
+ if theme not in themes:
17
+ raise ValueError(f"Choose a theme from: {', '.join(themes)}.")
18
+ if preset not in presets:
19
+ raise ValueError(f"Choose a preset from: {', '.join(presets)}.")
20
+ rates = presets[preset]
21
+ ns, ew, seed = _validate_inputs(rates["p_ns"] if p_ns is None else p_ns,
22
+ rates["p_ew"] if p_ew is None else p_ew, seed)
23
+ try:
24
+ from flask import Flask, Response, render_template, request
25
+ except ModuleNotFoundError as error:
26
+ if error.name != "flask":
27
+ raise
28
+ raise RuntimeError('Install the dashboard extra to launch the preview.') from error
29
+
30
+ app = Flask(__name__)
31
+ app.config["TRUSTED_HOSTS"] = ["localhost", "127.0.0.1", "[::1]"]
32
+
33
+ @app.get("/")
34
+ def dashboard():
35
+ selected_theme = request.args.get("theme", theme)
36
+ selected_preset = request.args.get("preset", preset)
37
+ selected_rates = presets.get(selected_preset, rates)
38
+ entered_ns = request.args.get("p_ns", ns if selected_preset == preset else selected_rates["p_ns"])
39
+ entered_ew = request.args.get("p_ew", ew if selected_preset == preset else selected_rates["p_ew"])
40
+ entered_seed = request.args.get("seed", seed)
41
+ result = None
42
+ error = None
43
+ try:
44
+ if selected_theme not in themes or selected_preset not in presets:
45
+ raise ValueError("Choose a listed theme and traffic preset.")
46
+ result = simulate(entered_ns, entered_ew, int(entered_seed))
47
+ download = request.args.get("download")
48
+ if download in ("fixed", "adaptive"):
49
+ return Response(trace_to_csv(result[download]), mimetype="text/csv", headers={
50
+ "Content-Disposition": f'attachment; filename="signallab-{download}.csv"',
51
+ })
52
+ except ValueError as failure:
53
+ error = str(failure)
54
+ return render_template("dashboard.html", result=result, error=error,
55
+ theme=selected_theme if selected_theme in themes else theme,
56
+ preset=selected_preset, themes=themes, presets=presets,
57
+ ns=entered_ns, ew=entered_ew, seed=entered_seed,
58
+ info=project_info(), joke=bengaluru_traffic_joke()), 400 if error else 200
59
+
60
+ return app
@@ -0,0 +1,214 @@
1
+ """SignalLab's simulation engine and supplied Q-table, packaged for local use."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import hashlib
6
+ import json
7
+ import math
8
+ from pathlib import Path
9
+ import threading
10
+
11
+ import numpy as np
12
+
13
+ from .original import traffic_rl as _original
14
+
15
+ ROOT = Path(__file__).resolve().parent
16
+ ORIGINAL = ROOT / "original"
17
+ DATA = ROOT / "data"
18
+ SOURCE_SHA256 = hashlib.sha256((ORIGINAL / "traffic_rl.py").read_bytes()).hexdigest()
19
+ _model_lock = threading.RLock()
20
+ _agent = None
21
+ _metadata = None
22
+ _evaluation_cache = {}
23
+ _SEED_UNSET = object()
24
+
25
+ def _validate_inputs(p_ns, p_ew, seed=_SEED_UNSET):
26
+ for name, value in (("p_ns", p_ns), ("p_ew", p_ew)):
27
+ if isinstance(value, bool):
28
+ raise ValueError(f"{name} must be a number between 0 and 1.")
29
+ try:
30
+ value = float(value)
31
+ except (TypeError, ValueError):
32
+ raise ValueError(f"{name} must be a number between 0 and 1.") from None
33
+ if not math.isfinite(value) or not 0 <= value <= 1:
34
+ raise ValueError(f"{name} must be between 0 and 1.")
35
+ if seed is not _SEED_UNSET:
36
+ if isinstance(seed, bool) or not isinstance(seed, (int, np.integer)):
37
+ raise ValueError("Seed must be a whole number between 0 and 4294967295.")
38
+ if not 0 <= seed <= 2 ** 32 - 1:
39
+ raise ValueError("Seed must be a whole number between 0 and 4294967295.")
40
+ return float(p_ns), float(p_ew), int(seed) if seed is not _SEED_UNSET else None
41
+
42
+
43
+ def _valid_q(table):
44
+ return table.shape == (5, 5, 2, 2) and np.isfinite(table).all()
45
+
46
+
47
+ def _ensure_model():
48
+ """Load a verified local training cache, otherwise the supplied model."""
49
+ global _agent, _metadata
50
+ with _model_lock:
51
+ if _agent is not None:
52
+ return
53
+ table = None
54
+ metadata = None
55
+ try:
56
+ metadata = json.loads((DATA / "training.json").read_text(encoding="utf-8"))
57
+ cached = np.load(DATA / "q_table.npy", allow_pickle=False)
58
+ digest = hashlib.sha256(cached.tobytes()).hexdigest()
59
+ if (metadata.get("source_sha256") == SOURCE_SHA256
60
+ and metadata.get("q_sha256") == digest
61
+ and len(metadata.get("returns", [])) == _original.EPISODES
62
+ and _valid_q(cached)):
63
+ table = cached
64
+ except (OSError, ValueError, TypeError, KeyError):
65
+ pass
66
+ if table is None:
67
+ supplied = ORIGINAL / "q_table.npy"
68
+ if not supplied.exists():
69
+ raise RuntimeError("The bundled SignalLab Q-table is missing. Reinstall the package.")
70
+ table = np.load(supplied, allow_pickle=False)
71
+ if not _valid_q(table):
72
+ raise ValueError("The supplied Q-table must contain 100 finite values with shape (5,5,2,2).")
73
+ metadata = {
74
+ "source": "supplied", "label": "Supplied Q-table; training provenance unavailable",
75
+ "source_sha256": SOURCE_SHA256,
76
+ "q_sha256": hashlib.sha256(table.tobytes()).hexdigest(),
77
+ "returns": [], "episodes": None, "trained_at": None,
78
+ "notes": "The supplied table is used as-is. Its training history is not known or reconstructed.",
79
+ }
80
+ loaded = _original.QAgent()
81
+ loaded.Q = table.copy()
82
+ _agent, _metadata = loaded, metadata
83
+
84
+
85
+ def _model_snapshot():
86
+ _ensure_model()
87
+ with _model_lock:
88
+ return _agent.Q.copy(), copy.deepcopy(_metadata)
89
+
90
+
91
+ def _trace(table, adaptive, p_ns, p_ew, seed, choose_action=None):
92
+ env = _original.Intersection(seed=seed, p_ns=p_ns, p_ew=p_ew)
93
+ state = env.reset()
94
+ frames = []
95
+ done = False
96
+ while not done:
97
+ before = list(env.q)
98
+ phase_before = env.phase
99
+ timer_before = env.t_in_phase
100
+ q_values = table[state].tolist() if table is not None else None
101
+ if adaptive and choose_action is not None:
102
+ action = choose_action(state)
103
+ elif adaptive:
104
+ action = int(np.argmax(table[state]))
105
+ else:
106
+ action = _original.fixed_policy(state, env)
107
+ # A separate generator observes the same two draws without advancing the
108
+ # environment RNG. Intersection.step remains the sole transition logic.
109
+ observer = np.random.default_rng()
110
+ observer.bit_generator.state = copy.deepcopy(env.rng.bit_generator.state)
111
+ arrivals = [int(observer.random() < probability) for probability in (p_ns, p_ew)]
112
+ next_state, reward, done = env.step(action)
113
+ switched = phase_before != env.phase
114
+ frames.append({
115
+ "t": int(env.t), "phase": int(env.phase), "q_ns": int(env.q[0]),
116
+ "q_ew": int(env.q[1]), "t_in_phase": int(env.t_in_phase),
117
+ "state": list(state), "next_state": list(next_state),
118
+ "action": int(action), "switched": bool(switched), "reward": int(reward),
119
+ "q_values": q_values, "arrivals": arrivals,
120
+ "departures": int(min(before[env.phase], _original.DISCHARGE)),
121
+ "queues_before": before, "phase_before": int(phase_before),
122
+ "timer_before": int(timer_before),
123
+ "switch_blocked": bool(action == 1 and not switched),
124
+ })
125
+ state = next_state
126
+ return frames
127
+
128
+
129
+ def _summary(frames):
130
+ queues = [frame["q_ns"] + frame["q_ew"] for frame in frames]
131
+ return {
132
+ "avg_queue": float(np.mean(queues)), "max_queue": int(max(queues)),
133
+ "return": int(sum(frame["reward"] for frame in frames)),
134
+ "switches": int(sum(frame["switched"] for frame in frames)),
135
+ "arrivals": int(sum(sum(frame["arrivals"]) for frame in frames)),
136
+ "departures": int(sum(frame["departures"] for frame in frames)),
137
+ }
138
+
139
+
140
+ def _gain(fixed, adaptive):
141
+ baseline = fixed["avg_queue"]
142
+ return (baseline - adaptive["avg_queue"]) / baseline * 100 if baseline else None
143
+
144
+
145
+ def simulate(p_ns=_original.P_NS, p_ew=_original.P_EW, seed=42):
146
+ """Return paired 200-step traces from the real original environment."""
147
+ p_ns, p_ew, seed = _validate_inputs(p_ns, p_ew, seed)
148
+ table, metadata = _model_snapshot()
149
+ return _compare(table, metadata["q_sha256"], p_ns, p_ew, seed)
150
+
151
+
152
+ def _compare(table, model_id, p_ns, p_ew, seed, choose_action=None):
153
+ fixed = _trace(table, False, p_ns, p_ew, seed)
154
+ adaptive = _trace(table, True, p_ns, p_ew, seed, choose_action)
155
+ fixed_summary, adaptive_summary = _summary(fixed), _summary(adaptive)
156
+ return {
157
+ "seed": seed, "p_ns": p_ns, "p_ew": p_ew, "steps": _original.STEPS,
158
+ "fixed": fixed, "adaptive": adaptive,
159
+ "summary": {"fixed": fixed_summary, "adaptive": adaptive_summary,
160
+ "improvement_pct": _gain(fixed_summary, adaptive_summary)},
161
+ "model_id": model_id,
162
+ "note": "Identical seeded arrivals; both controllers use original Intersection.step().",
163
+ }
164
+
165
+
166
+ def evaluate_scenarios(p_ns=_original.P_NS, p_ew=_original.P_EW):
167
+ """Evaluate requested rates over the original 50 seeds; report actual spread."""
168
+ p_ns, p_ew, _ = _validate_inputs(p_ns, p_ew)
169
+ table, metadata = _model_snapshot()
170
+ cache_key = (metadata["q_sha256"], p_ns, p_ew)
171
+ with _model_lock:
172
+ cached = _evaluation_cache.get(cache_key)
173
+ if cached is not None:
174
+ return copy.deepcopy(cached)
175
+ learned = _original.QAgent()
176
+ learned.Q = table
177
+ metrics = {}
178
+ for name, policy in (("fixed", _original.fixed_policy),
179
+ ("adaptive", _original.greedy_policy(learned))):
180
+ episodes = []
181
+ for seed in range(50000, 50000 + _original.EVAL_EPISODES):
182
+ history = _original.run_episode(policy, seed, p_ns, p_ew)
183
+ queues = [ns + ew for _, ns, ew in history]
184
+ switches = sum(history[i][0] != history[i - 1][0] for i in range(1, len(history)))
185
+ episodes.append({"avg_queue": float(np.mean(queues)), "max_queue": max(queues),
186
+ "return": -sum(queues) - switches, "switches": switches})
187
+ metrics[name] = {}
188
+ for key in ("avg_queue", "max_queue", "return", "switches"):
189
+ values = [episode[key] for episode in episodes]
190
+ metrics[name][key] = float(np.mean(values))
191
+ metrics[name][key + "_std"] = float(np.std(values, ddof=0))
192
+ improvement = _gain(metrics["fixed"], metrics["adaptive"])
193
+ result = {
194
+ "p_ns": p_ns, "p_ew": p_ew, "episodes": _original.EVAL_EPISODES,
195
+ "seed_start": 50000, "seed_end": 50000 + _original.EVAL_EPISODES - 1,
196
+ **metrics, "improvement_pct": improvement,
197
+ "summary": {**metrics, "improvement_pct": improvement},
198
+ "model_id": metadata["q_sha256"],
199
+ "metric_notes": {
200
+ "std": "Population standard deviation across 50 episode metrics (ddof=0).",
201
+ "max_queue": "Mean of each episode's maximum total queue; not a worst-ever maximum.",
202
+ "return": "Episode reward = negative sum of post-step queue lengths minus executed switches.",
203
+ "improvement_pct": "Percent reduction in mean queue relative to fixed timer; null if baseline is zero.",
204
+ "fairness": "Matched seeds 50000–50049 give both controllers identical arrival streams.",
205
+ },
206
+ }
207
+ with _model_lock:
208
+ # Keep the cache bounded if sliders send many evaluation requests.
209
+ if len(_evaluation_cache) >= 32:
210
+ _evaluation_cache.clear()
211
+ _evaluation_cache[cache_key] = copy.deepcopy(result)
212
+ return result
213
+
214
+