Abineshsdata Claude Opus 5.5 commited on
Commit
8ad4728
·
1 Parent(s): bfc322c

NexusGrid v3: seeded scenarios, physics-based graders, baselines and training code

Browse files

Environment
- DC power flow per island (Kirchhoff B-matrix), primary frequency response,
inertia, relay protection (3-tick and instant trips), UFLS and island collapse
- Seeded scenario families per task with held-out evaluation seeds (>= 10000);
Task 2 draws from a validated contingency catalog split 80/20 train/eval
- Attack physics: phantom injection hides real generation loss behind falsified
SCADA, forced oscillation grows until damped by a matched counter-signal
- Hidden attack details never reach observations (debug_state() for observers)
- New action shed_load; out-of-service lines cannot be re-closed
- Dense reward = potential-based task progress + frequency/safety terms

Grading
- Rubrics redesigned so doing nothing or acting randomly scores low
- Served-load gate stops "fixing" frequency by cutting customers

Agents and tooling
- policies.py: no-op, random and an observation-only expert (DC flow checks)
- inference.py: pure LLM evaluation by default; fallback is opt-in and counted
- scripts/evaluate.py: held-out evaluation with confidence intervals
- gym_env.py + training/train_ppo.py: masked PPO with behaviour cloning
- training/train_grpo.py: GRPO with simulator-scored rewards for the model's
own actions; CPU smoke test and Windows GPU runner
- Dashboard: per-session environments, v3 reward panels
- 140+ tests, CI workflow, MIT license, .env.example

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01766oz3rCt9MnTWTMzSk7fR

This view is limited to 50 files because it contains too many changes.   See raw diff
.dockerignore CHANGED
@@ -1,19 +1,20 @@
1
- # NexusGrid Docker Ignore
2
  .env
3
  .git
 
4
  .gitignore
5
  __pycache__
6
  *.pyc
7
  *.pyo
8
  .pytest_cache
 
 
9
  .venv
10
  venv
11
- node_modules
12
- scores.json
13
- uv.lock
14
- *.egg-info
15
- .mypy_cache
16
- .ruff_cache
17
  *.log
 
 
18
  .server_pid
19
- tests/
 
 
1
  .env
2
  .git
3
+ .github
4
  .gitignore
5
  __pycache__
6
  *.pyc
7
  *.pyo
8
  .pytest_cache
9
+ .ruff_cache
10
+ .mypy_cache
11
  .venv
12
  venv
13
+ runs
14
+ results
15
+ docs
16
+ tests
 
 
17
  *.log
18
+ *.egg-info
19
+ unsloth_compiled_cache
20
  .server_pid
 
.env.example ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copy to .env and adjust. .env is git-ignored: never commit real keys.
2
+
3
+ # Any OpenAI-compatible endpoint (Ollama, vLLM, LM Studio, OpenAI, HF router ...)
4
+ API_BASE_URL=http://localhost:11434/v1
5
+ MODEL_NAME=qwen3:1.7b
6
+ API_KEY=ollama
7
+
8
+ # Only needed for gated models or `train_grpo.py --push-to-hub`
9
+ # HF_TOKEN=
10
+
11
+ # inference.py defaults
12
+ EPISODE_SEED=42
13
+ # USE_REMOTE_ENV=1
14
+ # ENV_URL=http://localhost:8000
.gitattributes ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ * text=auto eol=lf
2
+ *.ps1 text eol=crlf
3
+ *.png binary
4
+ *.jpg binary
5
+ *.zip binary
6
+ *.safetensors binary
.github/workflows/ci.yml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: ci
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ jobs:
8
+ test:
9
+ runs-on: ubuntu-latest
10
+ timeout-minutes: 20
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: actions/setup-python@v5
14
+ with:
15
+ python-version: "3.11"
16
+ cache: pip
17
+ - name: Install
18
+ run: |
19
+ python -m pip install --upgrade pip
20
+ pip install -r requirements.txt pytest pytest-asyncio httpx ruff
21
+ - name: Lint
22
+ run: ruff check --select F,E9 .
23
+ - name: Tests
24
+ run: pytest -q
25
+ - name: Baseline evaluation (held-out seeds)
26
+ run: python scripts/evaluate.py --seeds 10 --out /tmp/eval
.gitignore CHANGED
@@ -1,13 +1,22 @@
 
1
  .env
 
 
 
 
2
  __pycache__/
3
- *.pyc
4
- *.pyo
5
- .pytest_cache/
6
- scores.json
7
- uv.lock
8
  .venv/
9
  venv/
10
- *.egg-info/
11
  .ruff_cache/
12
  .mypy_cache/
13
  .server_pid
 
 
 
 
 
 
 
 
1
+ # Secrets and local configuration
2
  .env
3
+ .env.*
4
+ !.env.example
5
+
6
+ # Python
7
  __pycache__/
8
+ *.py[cod]
9
+ *.egg-info/
 
 
 
10
  .venv/
11
  venv/
12
+ .pytest_cache/
13
  .ruff_cache/
14
  .mypy_cache/
15
  .server_pid
16
+
17
+ # Training and evaluation artefacts (summaries and plots under results/ are tracked)
18
+ runs/
19
+ *.log
20
+ scores.json
21
+ unsloth_compiled_cache/
22
+ wandb/
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abinesh Senthilkumar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
client.py CHANGED
@@ -1,6 +1,6 @@
1
  """NexusGrid-CyberPhysEnv Environment Client."""
2
 
3
- from typing import Any, Dict, List
4
 
5
  from openenv.core import EnvClient
6
  from openenv.core.client_types import StepResult
@@ -23,12 +23,13 @@ class NexusgridEnv(
23
 
24
  Example:
25
  >>> with NexusgridEnv(base_url="http://localhost:8000").sync() as env:
26
- ... result = env.reset()
27
  ... result = env.step(GridAction(
28
  ... action_type="dispatch_generation",
29
  ... node_id="NODE_01",
30
  ... mw=100.0,
31
  ... ))
 
32
  """
33
 
34
  def _step_payload(self, action: GridAction) -> Dict:
@@ -55,30 +56,14 @@ class NexusgridEnv(
55
  return payload
56
 
57
  def _parse_result(self, payload: Dict) -> StepResult[GridObservation]:
58
- """Parse server response into StepResult[GridObservation]."""
59
- obs_data = payload.get("observation", payload)
60
-
61
- observation = GridObservation(
62
- topology_graph=obs_data.get("topology_graph", {}),
63
- telemetry_stream=obs_data.get("telemetry_stream", []),
64
- weather_forecast_matrix=obs_data.get("weather_forecast_matrix", []),
65
- network_packet_logs=obs_data.get("network_packet_logs", []),
66
- grid_frequency_hz=obs_data.get("grid_frequency_hz", 60.0),
67
- tick=obs_data.get("tick", 0),
68
- task_id=obs_data.get("task_id", 0),
69
- done=payload.get("done", obs_data.get("done", False)),
70
- reward=payload.get("reward", obs_data.get("reward", 0.0)),
71
- last_action_error=obs_data.get("last_action_error"),
72
- last_state_estimation=obs_data.get("last_state_estimation"),
73
- weather_summary=obs_data.get("weather_summary", ""),
74
- metadata=obs_data.get("metadata", {}),
75
- )
76
-
77
- return StepResult(
78
- observation=observation,
79
- reward=payload.get("reward", obs_data.get("reward", 0.0)),
80
- done=payload.get("done", obs_data.get("done", False)),
81
- )
82
 
83
  def _parse_state(self, payload: Dict) -> State:
84
  """Parse server response into State object."""
 
1
  """NexusGrid-CyberPhysEnv Environment Client."""
2
 
3
+ from typing import Dict
4
 
5
  from openenv.core import EnvClient
6
  from openenv.core.client_types import StepResult
 
23
 
24
  Example:
25
  >>> with NexusgridEnv(base_url="http://localhost:8000").sync() as env:
26
+ ... result = env.reset(seed=10_000, task_id=1)
27
  ... result = env.step(GridAction(
28
  ... action_type="dispatch_generation",
29
  ... node_id="NODE_01",
30
  ... mw=100.0,
31
  ... ))
32
+ ... print(result.observation.score, result.observation.grid_frequency_hz)
33
  """
34
 
35
  def _step_payload(self, action: GridAction) -> Dict:
 
56
  return payload
57
 
58
  def _parse_result(self, payload: Dict) -> StepResult[GridObservation]:
59
+ """Parse a server response into StepResult[GridObservation]."""
60
+ obs_data = dict(payload.get("observation", payload))
61
+ done = payload.get("done", obs_data.get("done", False))
62
+ reward = payload.get("reward", obs_data.get("reward", 0.0))
63
+ obs_data["done"] = bool(done)
64
+ obs_data["reward"] = float(reward or 0.0)
65
+ observation = GridObservation.model_validate(obs_data)
66
+ return StepResult(observation=observation, reward=observation.reward, done=observation.done)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  def _parse_state(self, payload: Dict) -> State:
69
  """Parse server response into State object."""
docs/blog-v2-hackathon.md ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ > **Archived write-up (v2, hackathon submission, May 2026).** The scores in this post came from the v2
2
+ > evaluation, which replaced invalid model actions with a scripted fallback and used fixed scenarios.
3
+ > NexusGrid v3 re-did the benchmark (seeded scenarios, held-out seeds, pure model evaluation); see the
4
+ > [README](../README.md) for current, reproducible results.
5
+
6
+ # ⚡ I Trained an LLM to Defend a Power Grid Against Cyberattacks — Here's What Happened
7
+
8
+ **Meta PyTorch OpenEnv Hackathon 2026 | Round 2 Submission**
9
+
10
+ *By Abinesh S | [Kaggle Notebook](https://www.kaggle.com/code/abineshsdataa/train-nexusgrid-grpo) · [Live Space](https://huggingface.co/spaces/Abineshsdata/Nexus-Grid)*
11
+
12
+ ---
13
+
14
+ ## The Problem Nobody Was Solving
15
+
16
+ On December 23, 2015, hackers remotely switched off 30 substations across western Ukraine. 230,000 homes went dark. The attackers didn't blow anything up — they just spoofed SCADA sensor readings until human operators couldn't tell what was real and what was a lie.
17
+
18
+ In 2021, Colonial Pipeline paid $4.4M in ransom after attackers paralyzed fuel distribution across the US east coast.
19
+
20
+ These aren't movie plots. They're the new normal in critical infrastructure attacks.
21
+
22
+ Here's the uncomfortable truth: **no public RL benchmark exists for training AI agents to reason under simultaneous cyber-physical grid attacks.** There are chess environments, coding environments, math environments — but nothing that simulates the exact scenario a real power grid operator faces: a live network where sensors lie, physics must be verified, and every wrong action might cascade into a blackout.
23
+
24
+ So I built one.
25
+
26
+ ---
27
+
28
+ ## What I Built: NexusGrid-CyberPhysEnv
29
+
30
+ NexusGrid is a 20-node DC power flow simulation wrapped in an OpenEnv-compatible RL environment. The agent isn't just answering questions — it's operating inside a running simulation where:
31
+
32
+ - **Kirchhoff's laws** govern every power flow in real time
33
+ - **SCADA telemetry can be spoofed** — the agent must distinguish sensor lies from real faults
34
+ - **Three attack vectors** are active: phantom injection, resonance attacks, and man-in-the-middle telemetry corruption
35
+ - **Every wrong action has physical consequences**: dispatch too much generation and frequency spikes; isolate the wrong breaker and you split the grid
36
+
37
+ The agent has access to six tools:
38
+
39
+ ```
40
+ dispatch_generation — inject MW into a generation node
41
+ toggle_circuit_breaker — open/close a line segment
42
+ run_state_estimation — verify Kirchhoff consistency on a subgraph
43
+ quarantine_scada_node — mark a sensor as untrusted
44
+ inject_counter_signal — overwrite spoofed telemetry with a corrected value
45
+ advance_tick — move time forward and observe consequences
46
+ ```
47
+
48
+ None of these are safe to call blindly. The environment enforces prerequisites — you cannot quarantine a node before running state estimation, you cannot dispatch generation above physical limits, and the grid terminates at 59 Hz if frequency collapses.
49
+
50
+ ### The 6-Task Curriculum
51
+
52
+ Rather than throwing the hardest scenario at the agent first, I built a curriculum from trivial to expert:
53
+
54
+ | Task | Name | What Happens | Pre-Training Score |
55
+ |------|------|--------------|-------------------|
56
+ | 0 | Smoke Test | Single-line fault, no attack | 1.000 |
57
+ | 1 | Fault Isolation | Physical fault + breaker isolation | 0.999 |
58
+ | 2 | Frequency Regulation | Generation imbalance, no deception | 0.800 |
59
+ | 3 | Phantom Injection | SCADA spoofing, forensic reasoning required | 0.600 |
60
+ | 4 | Resonance Attack | Multi-vector attack, timing-sensitive | 0.400 |
61
+ | 5 | Black Start | Full grid collapse, adversarial attacker | 0.060 |
62
+
63
+ The first two tasks were already solved before training — the model could handle them from pre-training. Tasks 3–5 are where things got interesting.
64
+
65
+ ---
66
+
67
+ ## The Training Setup
68
+
69
+ ### Why Qwen2.5-4B and Not Something Bigger?
70
+
71
+ Free Colab T4 gives you 16GB of VRAM. With Unsloth's 4-bit QLoRA, Qwen2.5-4B fits in ~10GB — giving just enough headroom for GRPO's 8 parallel rollouts per prompt without OOM crashes.
72
+
73
+ Could a larger model do better? Almost certainly yes. I'll cover that at the end.
74
+
75
+ **Stack:**
76
+ - **Model**: `Qwen2.5-4B-Instruct` (4-bit QLoRA via Unsloth)
77
+ - **Trainer**: TRL `GRPOTrainer`
78
+ - **Environment**: NexusGrid hosted on HuggingFace Spaces
79
+ - **Hardware**: Kaggle T4 (free tier)
80
+
81
+ ### GRPO: Why Not PPO?
82
+
83
+ GRPO (Group Relative Policy Optimization) was the right choice here for one key reason: **it removes the value model**. PPO needs a separate critic network to estimate baselines — that's 2x the memory. GRPO instead samples 8 rollouts per prompt and computes relative advantage within the group. On a T4 with a 4B model, that difference between fitting and not fitting in VRAM.
84
+
85
+ The training logic in plain English:
86
+ 1. Give the model a grid scenario prompt
87
+ 2. Generate 8 different response sequences (different action choices)
88
+ 3. Execute each sequence in the NexusGrid environment
89
+ 4. Score each sequence against the rubric verifiers
90
+ 5. The rollouts that scored higher get their probability increased; lower ones get decreased
91
+ 6. Repeat 300+ episodes
92
+
93
+ ---
94
+
95
+ ## Training Logs (Selected Episodes)
96
+
97
+ Here's what the training loop actually looked like. I logged every episode to JSONL:
98
+
99
+ ```
100
+ [Episode 001] task=0 seed=7 score=1.000 ticks=3 freq_min=60.32 Hz actions=[advance_tick, toggle_circuit_breaker, advance_tick]
101
+ [Episode 002] task=0 seed=12 score=1.000 ticks=3 freq_min=60.28 Hz ✓ curriculum unlock threshold: 1.0 ≥ 0.6
102
+ [Episode 003] task=1 seed=1 score=0.999 ticks=5 freq_min=60.11 Hz actions=[advance_tick, run_state_estimation, toggle_circuit_breaker, dispatch_generation, advance_tick]
103
+ [Episode 010] task=1 seed=4 score=0.999 ticks=4 freq_min=60.19 Hz ✓ curriculum unlock threshold: 0.999 ≥ 0.6 → advancing to Task 2
104
+ [Episode 011] task=2 seed=0 score=0.521 ticks=6 freq_min=59.81 Hz actions=[advance_tick, dispatch_generation, advance_tick, advance_tick, advance_tick, advance_tick]
105
+ rubrics: {freq_stable: 0.0, gen_balanced: 1.0, no_penalty: 1.0}
106
+ [Episode 015] task=2 seed=3 score=0.614 ticks=6 freq_min=59.93 Hz rubrics: {freq_stable: 0.5, gen_balanced: 1.0, no_penalty: 1.0}
107
+ [Episode 022] task=2 seed=8 score=0.800 ticks=5 freq_min=60.05 Hz ✓ curriculum advancing to Task 3
108
+ [Episode 023] task=3 seed=0 score=0.150 ticks=8 freq_min=59.62 Hz actions=[dispatch_generation ← WRONG ORDER, quarantine_scada_node ← BLOCKED]
109
+ rubrics: {log_inspection: 0.0, state_estimation: 0.0, correct_quarantine: 0.0, reroute_dispatch: 1.0}
110
+ ⚠ anti-hallucination gate: quarantine blocked (no prior state_estimation)
111
+ [Episode 031] task=3 seed=2 score=0.310 ticks=9 freq_min=59.71 Hz actions=[advance_tick, run_state_estimation, dispatch_generation ← still misordered]
112
+ rubrics: {log_inspection: 1.0, state_estimation: 1.0, correct_quarantine: 0.0, reroute_dispatch: 0.0}
113
+ [Episode 045] task=3 seed=5 score=0.600 ticks=8 freq_min=59.88 Hz actions=[advance_tick, run_state_estimation, quarantine_scada_node, dispatch_generation, advance_tick]
114
+ rubrics: {log_inspection: 1.0, state_estimation: 1.0, correct_quarantine: 1.0, reroute_dispatch: 1.0}
115
+ ✓ FIRST FULL RUBRIC PASS on Task 3
116
+ [Episode 060] task=3 seed=9 score=0.720 ticks=7 freq_min=60.02 Hz ✓ curriculum advancing to Task 4
117
+ [Episode 061] task=4 seed=0 score=0.000 ticks=6 freq_min=58.91 Hz ← grid collapse (below 59 Hz termination)
118
+ [Episode 071] task=4 seed=3 score=0.201 ticks=9 freq_min=59.12 Hz
119
+ [Episode 095] task=4 seed=7 score=0.388 ticks=10 freq_min=59.44 Hz
120
+ [Episode 120] task=4 seed=11 score=0.441 ticks=9 freq_min=59.61 Hz
121
+ [Episode 150] task=5 seed=0 score=0.000 ticks=3 freq_min=58.20 Hz ← collapse in 3 ticks
122
+ [Episode 175] task=5 seed=4 score=0.062 ticks=12 freq_min=59.08 Hz
123
+ [Episode 210] task=5 seed=7 score=0.140 ticks=14 freq_min=59.31 Hz
124
+ [Episode 241] task=5 seed=12 score=0.190 ticks=16 freq_min=59.48 Hz
125
+ [Episode 280] task=3 seed=33 score=0.850 ticks=7 freq_min=60.14 Hz ← curriculum cycling back, significantly improved
126
+ [Episode 300] task=4 seed=22 score=0.470 ticks=11 freq_min=59.67 Hz [FINAL]
127
+ ```
128
+
129
+ **Total training time**: ~4.5 hours on Kaggle T4 (2x accelerator)
130
+
131
+ ---
132
+
133
+ ## Results
134
+
135
+ ### Task Score Comparison
136
+
137
+ | Task | Pre-Training | Post-Training | Delta |
138
+ |------|-------------|---------------|-------|
139
+ | 0 — Smoke Test | 1.000 | 1.000 | +0.000 |
140
+ | 1 — Fault Isolation | 0.999 | 0.999 | +0.000 |
141
+ | 2 — Frequency Regulation | 0.800 | 0.800 | +0.000 |
142
+ | 3 — Phantom Injection | 0.600 | **0.850** | **+0.250** |
143
+ | 4 — Resonance Attack | 0.400 | **0.470** | **+0.070** |
144
+ | 5 — Black Start | 0.060 | **0.190** | **+0.130** |
145
+
146
+ Tasks 0–2 were already solved — the pre-trained model handled them from general instruction-following. The real improvement happened exactly where it was supposed to: the forensic reasoning tasks that require understanding *why* to run state estimation before dispatching generation.
147
+
148
+ ### Grid Frequency Stability
149
+
150
+ The frequency plot tells the clearest story. Before training, the model sometimes dispatched generation out of sequence, causing transient frequency spikes. After training, the agent had learned to verify the grid state before dispatching — keeping frequency stable within the nominal band (59.75–60.25 Hz) across all evaluated ticks.
151
+
152
+ *[See frequency stability chart above — before training (blue) vs after training (orange), against nominal band (yellow dotted) and failure floor at 59 Hz (red dashed)]*
153
+
154
+ The "Before vs After Training Scores" chart shows the second finding: the pre-trained model scored near-zero on Tasks 0–2 in early evaluation episodes — not because the tasks were hard, but because the evaluation harness was testing the *uninitialized* model before any formatting priming. After GRPO training, scores on all tasks rose above the baseline, with the largest gains on Tasks 3–5.
155
+
156
+ ---
157
+
158
+ ## Before vs After: A Real Rollout
159
+
160
+ Here's what the model actually did, for Task 3 (Phantom Injection), before and after training.
161
+
162
+ ### Before Training (Episode 023)
163
+
164
+ ```
165
+ SYSTEM: You are an AI grid defense operator. NODE_14 sensor may be spoofed.
166
+ Output JSON only.
167
+
168
+ [Tick 1]
169
+ Observation: freq=59.81 Hz, NODE_14 reporting +340 MW phantom generation
170
+ SCADA anomaly flag: NODE_14 packet timestamp mismatch
171
+
172
+ Model output:
173
+ {"action_type": "dispatch_generation", "node_id": "NODE_07", "mw": 200}
174
+
175
+ Environment response: ⚠ Dispatching without verification. Grid frequency now 59.71 Hz
176
+ Reward: -0.05 (wrong ordering penalty)
177
+
178
+ [Tick 2]
179
+ Model output:
180
+ {"action_type": "quarantine_scada_node", "node_id": "NODE_14"}
181
+
182
+ Environment response: ❌ BLOCKED — quarantine requires prior state_estimation
183
+ Reward: -0.10 (prerequisite violation)
184
+
185
+ Episode score: 0.150
186
+ Rubrics: log_inspection=0, state_estimation=0, correct_quarantine=0, reroute_dispatch=1
187
+ ```
188
+
189
+ The model jumped straight to action — like someone who sees a fire alarm and immediately starts rearranging furniture. It dispatched generation before verifying anything, then tried to quarantine a node without running the Kirchhoff consistency check first. The environment hard-blocked the quarantine (anti-hallucination gate), preventing the model from gaming the reward by skipping forensic steps.
190
+
191
+ ### After Training (Episode 280)
192
+
193
+ ```
194
+ SYSTEM: You are an AI grid defense operator. NODE_14 sensor may be spoofed.
195
+ Output JSON only.
196
+
197
+ [Tick 1]
198
+ Observation: freq=60.14 Hz, NODE_14 reporting +340 MW phantom generation
199
+ SCADA anomaly flag: NODE_14 packet timestamp mismatch
200
+
201
+ Model output:
202
+ {"action_type": "advance_tick"}
203
+
204
+ Environment response: Grid stable. Anomaly flag persists on NODE_14.
205
+ Reward: +0.01
206
+
207
+ [Tick 2]
208
+ Model output:
209
+ {"action_type": "run_state_estimation", "node_id": "NODE_14", "subgraph": ["NODE_13","NODE_14","NODE_15"]}
210
+
211
+ Environment response: ✓ Kirchhoff violation detected on NODE_14 subgraph.
212
+ Measured flow: +12 MW. Reported: +340 MW. MISMATCH CONFIRMED.
213
+ Reward: +0.15
214
+
215
+ [Tick 3]
216
+ Model output:
217
+ {"action_type": "quarantine_scada_node", "node_id": "NODE_14"}
218
+
219
+ Environment response: ✓ NODE_14 quarantined. Telemetry corrected. Freq: 60.09 Hz.
220
+ Reward: +0.20
221
+
222
+ [Tick 4]
223
+ Model output:
224
+ {"action_type": "dispatch_generation", "node_id": "NODE_07", "mw": 45}
225
+
226
+ Environment response: ✓ Generation balanced. Freq: 60.14 Hz.
227
+ Reward: +0.10
228
+
229
+ Episode score: 0.850
230
+ Rubrics: log_inspection=1, state_estimation=1, correct_quarantine=1, reroute_dispatch=1
231
+ ```
232
+
233
+ The trained model had internalized the correct forensic sequence: observe → verify physics → quarantine → then and only then dispatch. Nobody told it the order. GRPO learned it because skipping steps got penalized and the full sequence got rewarded.
234
+
235
+ ---
236
+
237
+ ## What the Model Actually Learned
238
+
239
+ The most surprising result wasn't the score improvement — it was *where* the model started spending its tick budget.
240
+
241
+ Before training, the model used an average of 5.2 ticks on Task 3, mostly on dispatch attempts. After training, it used an average of 7.1 ticks — but those extra ticks were `run_state_estimation` calls and `advance_tick` observations. The model learned to **slow down and verify** before acting.
242
+
243
+ In power grid operations, this is called "look before you switch." It's a fundamental safety principle that takes human operators months of training to internalize properly. The 4B model picked it up in ~300 episodes.
244
+
245
+ ---
246
+
247
+ ## Anti-Reward-Hacking Defenses
248
+
249
+ The judges specifically look for this, and it's worth explaining because I designed NexusGrid with several layers of protection:
250
+
251
+ **1. Seed Lock** — All environment randomness is seeded from `episode_seed` via NumPy PCG64. The model cannot memorize episodes because every seed produces a fresh topology configuration.
252
+
253
+ **2. Anti-Hallucination Gate** — Task 3's grader returns a hard `0.0` score if `dispatch_generation` is called before `run_state_estimation`. This prevents the model from discovering a shortcut where it ignores the forensic step and gets rewarded anyway.
254
+
255
+ **3. Kirchhoff Verification** — State estimation checks real power balance equations. The model cannot fake this with a nonsense response string — the server runs the actual math.
256
+
257
+ **4. One-Shot Fault Isolation Reward** — The `fault_isolation` rubric pays at most once per episode. The model cannot spam `toggle_circuit_breaker` for infinite reward.
258
+
259
+ **5. Frequency Termination** — The grid terminates at 59.0 Hz. Any action sequence that ignores physics and over-dispatches generation gets hard-stopped.
260
+
261
+ **6. Quarantine Prerequisite** — `quarantine_scada_node` returns an error if no prior `state_estimation` has been called. The environment enforces the reasoning order at the API level, not just at reward time.
262
+
263
+ **7. Score Epsilon Clamping** — Scores never reach exactly `0.0` or `1.0` (clamped to `[0.001, 0.999]`). This prevents grader edge-case exploitation.
264
+
265
+ When I adversarially tested these before training — trying to find exploits myself — the only ways to inflate reward required doing something physically sensible anyway. That's the goal.
266
+
267
+ ---
268
+
269
+ ## What Would a Bigger Model Have Done?
270
+
271
+ The 4B model hit a ceiling on Task 5 (Black Start) at ~0.190. Task 5 requires 16+ ticks of multi-step reasoning under an adaptive adversarial attacker, and the 4B context window starts struggling with long action histories.
272
+
273
+ Based on the architecture decision analysis:
274
+
275
+ **Qwen2.5-7B** (via HF Credits, A10G) would likely push Task 5 from 0.190 → ~0.35–0.45. The 7B model has significantly better long-horizon coherence and would benefit more from GRPO on the adversarial tasks.
276
+
277
+ **Qwen3-8B** (the 2026 generation, with native thinking mode) would be the strongest option — it matches Qwen2.5-14B-class reasoning and handles adversarial multi-step tasks significantly better. If you have A10G credits, this is where to spend them.
278
+
279
+ The training setup was designed so swapping models requires changing exactly one line:
280
+ ```python
281
+ model_name="unsloth/Qwen2.5-4B-Instruct-bnb-4bit"
282
+ # → "unsloth/Qwen2.5-7B-Instruct-bnb-4bit" (needs A10G)
283
+ # → "unsloth/Qwen3-8B-Instruct-bnb-4bit" (best results, A10G)
284
+ ```
285
+
286
+ The environment, reward functions, curriculum, and training loop stay identical.
287
+
288
+ ---
289
+
290
+ ## Limitations and What I'd Do Differently
291
+
292
+ **The scoring plateau on Task 5** is partly a model-size problem and partly a curriculum problem. I ran the curriculum with `unlock_threshold=0.6`, which let the model move to Task 5 at 0.190 pre-training score on Task 4. In hindsight, keeping it at Task 4 longer would have built stronger foundations for the black-start scenario.
293
+
294
+ **The "Before vs After" evaluation chart** shows near-zero scores across all tasks in early episodes. This isn't because the pre-trained model was bad at easy tasks — it's because the evaluation was run on the raw model without task-specific formatting priming, making the output parser fail silently. Post-training, the model had internalized the JSON-only output format through GRPO, so the parser succeeded on every episode. This is a real (and important) finding: a significant portion of the measured improvement is format compliance, not just task reasoning.
295
+
296
+ **300 episodes is small.** The reward curves are still rising at episode 300. A 1000-episode run on Tasks 3–5 would likely push scores substantially higher, especially with the 7B model.
297
+
298
+ ---
299
+
300
+ ## Try It Yourself
301
+
302
+ **Live Space**: https://huggingface.co/spaces/Abineshsdata/Nexus-Grid
303
+
304
+ **Training Notebook**: https://www.kaggle.com/code/abineshsdataa/train-nexusgrid-grpo
305
+
306
+ Quick API test (after the Space is running):
307
+
308
+ ```bash
309
+ # Reset the environment on Task 3 (Phantom Injection)
310
+ curl -X POST https://abineshsdata-nexus-grid.hf.space/reset \
311
+ -H "Content-Type: application/json" \
312
+ -d '{"task_id": 3, "seed": 42}'
313
+
314
+ # Step with the correct forensic action
315
+ curl -X POST https://abineshsdata-nexus-grid.hf.space/step \
316
+ -H "Content-Type: application/json" \
317
+ -d '{"action_type": "run_state_estimation", "node_id": "NODE_14", "subgraph": ["NODE_13","NODE_14","NODE_15"]}'
318
+ ```
319
+
320
+ ---
321
+
322
+ ## What's Next
323
+
324
+ **Multi-agent adversarial training** — The environment already has a `RuleBasedAttacker` skeleton. The next version will pit the trained LLM defender against an adaptive attacker that chooses which SCADA node to spoof based on the defender's previous responses. This creates a genuine cat-and-mouse dynamic.
325
+
326
+ **Scaling to 7B and 13B** — The results here suggest the performance ceiling on Task 5 is model-size limited, not environment-limited. Scaling the training to 7B should push the black-start task above 0.35.
327
+
328
+ **Publishing the environment** — NexusGrid doesn't exist anywhere in the public RL benchmark ecosystem. The plan is to clean it up post-hackathon and release it as a proper benchmark for critical infrastructure reasoning.
329
+
330
+ ---
331
+
332
+ *Built for the Meta PyTorch OpenEnv Hackathon India 2026, Round 2.*
333
+ *Environment: [NexusGrid on HF Spaces](https://huggingface.co/spaces/Abineshsdata/Nexus-Grid) · Training: [Kaggle Notebook](https://www.kaggle.com/code/abineshsdataa/train-nexusgrid-grpo)*
gym_env.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gymnasium wrapper for reinforcement-learning agents.
3
+
4
+ * Observation: a fixed-size ``float32`` feature vector built only from the
5
+ :class:`GridObservation` (topology, telemetry, forecasts, PMU and SCADA
6
+ signals). Hidden scenario parameters are never used.
7
+ * Action: ``Discrete(237)`` over a fixed catalogue (advance, dispatch steps per
8
+ unit, load shedding, breaker switching, state estimation around each bus,
9
+ quarantine, counter-signals) with action masks for ``sb3-contrib``'s
10
+ ``MaskablePPO``.
11
+ * Reward: the environment's dense reward (potential-based task progress plus
12
+ frequency and safety terms), so episode return tracks the graded score.
13
+
14
+ Training seeds are drawn below 10 000; seeds from 10 000 up are held out.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
20
+
21
+ import numpy as np
22
+
23
+ try:
24
+ import gymnasium as gym
25
+ from gymnasium import spaces
26
+ except ImportError: # pragma: no cover - gymnasium is an optional dependency
27
+ gym = None
28
+ spaces = None
29
+
30
+ from models import ActionType, GridAction
31
+ from policies import DISPATCHABLE, GridView
32
+ from server.nexusgrid_environment import NexusgridEnvironment
33
+ from server.scenarios import EVAL_SEED_START, MAX_TICKS
34
+
35
+ NODE_IDS = [f"NODE_{i:02d}" for i in range(1, 21)]
36
+ EDGE_IDS = [f"LINE_{i:02d}" for i in range(1, 41)]
37
+ NODE_TYPES = ("hydro", "solar", "gas", "battery", "load")
38
+ DISPATCH_UNITS = ["NODE_01", "NODE_02", "NODE_04", "NODE_06", "NODE_08", "NODE_09",
39
+ "NODE_13", "NODE_14", "NODE_16", "NODE_17", "NODE_20"]
40
+ BATTERIES = ["NODE_04", "NODE_08", "NODE_16", "NODE_20"]
41
+ SHEDDABLE_LOADS = ["NODE_07", "NODE_12", "NODE_19"]
42
+ DISPATCH_STEPS = (-250.0, -150.0, -50.0, 50.0, 150.0, 250.0)
43
+ COUNTER_MODES = tuple(round(0.30 + 0.05 * i, 2) for i in range(11))
44
+ SE_NEIGHBOURHOODS = {
45
+ # each bus plus its neighbours in the full network (at most six buses)
46
+ }
47
+
48
+
49
+ def _base_neighbourhoods() -> Dict[str, List[str]]:
50
+ from server.grid_engine import GridEngine
51
+ from server.scenarios import build_base_topology
52
+
53
+ engine = GridEngine(seed=0)
54
+ build_base_topology(engine)
55
+ adjacency: Dict[str, List[str]] = {nid: [] for nid in engine.nodes}
56
+ for e in engine.edges.values():
57
+ adjacency[e["source"]].append(e["target"])
58
+ adjacency[e["target"]].append(e["source"])
59
+ return {nid: [nid] + sorted(nbs)[:5] for nid, nbs in adjacency.items()}
60
+
61
+
62
+ SE_NEIGHBOURHOODS.update(_base_neighbourhoods())
63
+
64
+
65
+ class ActionCatalog:
66
+ """Fixed discrete action set shared by every task."""
67
+
68
+ def __init__(self) -> None:
69
+ entries: List[Tuple[str, Tuple[Any, ...]]] = [("advance", ())]
70
+ entries += [("dispatch", (u, d)) for u in DISPATCH_UNITS for d in DISPATCH_STEPS]
71
+ entries += [("shed", (n, kind)) for n in SHEDDABLE_LOADS for kind in ("shed25", "restore")]
72
+ entries += [("breaker", (e, s)) for e in EDGE_IDS for s in ("OPEN", "CLOSED")]
73
+ entries += [("estimate", (n,)) for n in NODE_IDS]
74
+ entries += [("quarantine", (n,)) for n in NODE_IDS]
75
+ entries += [("counter", (b, m)) for b in BATTERIES for m in COUNTER_MODES]
76
+ self.entries = entries
77
+ self.index = {entry: i for i, entry in enumerate(entries)}
78
+
79
+ def __len__(self) -> int:
80
+ return len(self.entries)
81
+
82
+ def describe(self, idx: int) -> str:
83
+ kind, args = self.entries[idx]
84
+ return f"{kind}({', '.join(str(a) for a in args)})"
85
+
86
+ def to_action(self, idx: int, view: GridView) -> GridAction:
87
+ kind, args = self.entries[int(idx)]
88
+ if kind == "dispatch":
89
+ return GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id=args[0], mw=args[1])
90
+ if kind == "shed":
91
+ node = view.nodes.get(args[0], {})
92
+ served = view.served_mw(args[0])
93
+ if args[1] == "shed25":
94
+ return GridAction(action_type=ActionType.SHED_LOAD, node_id=args[0], mw=round(max(1.0, 0.25 * served), 1))
95
+ ufls = node.get("ufls_shed_pct", 0.0) / 100.0
96
+ restorable = node.get("shed_mw", 0.0) + served * ufls / max(1e-6, 1.0 - ufls)
97
+ return GridAction(action_type=ActionType.SHED_LOAD, node_id=args[0], mw=-round(max(1.0, restorable), 1))
98
+ if kind == "breaker":
99
+ return GridAction(action_type=ActionType.TOGGLE_CIRCUIT_BREAKER, edge_id=args[0], status=args[1])
100
+ if kind == "estimate":
101
+ return GridAction(action_type=ActionType.RUN_STATE_ESTIMATION, subgraph=SE_NEIGHBOURHOODS[args[0]])
102
+ if kind == "quarantine":
103
+ return GridAction(action_type=ActionType.QUARANTINE_SCADA_NODE, node_id=args[0])
104
+ if kind == "counter":
105
+ return GridAction(action_type=ActionType.INJECT_COUNTER_SIGNAL, node_id=args[0], hz_offset=-args[1], duration=4)
106
+ return GridAction(action_type=ActionType.ADVANCE_TICK)
107
+
108
+ def mask(self, view: GridView) -> np.ndarray:
109
+ mask = np.zeros(len(self.entries), dtype=bool)
110
+ violation = None
111
+ se = view.last_se or {}
112
+ if not se.get("consistent", True):
113
+ violation = se.get("violation_node")
114
+ for i, (kind, args) in enumerate(self.entries):
115
+ if kind == "advance":
116
+ ok = True
117
+ elif kind == "dispatch":
118
+ n = view.nodes.get(args[0], {})
119
+ usable = n.get("energized") and not n.get("tripped") and not n.get("quarantined")
120
+ if args[1] > 0:
121
+ ok = usable and n.get("capacity_mw", 0) - n.get("setpoint_mw", 0) > 1.0
122
+ if n.get("node_type") == "battery":
123
+ ok = ok and n.get("soc_pct", 0.0) > 5.0
124
+ else:
125
+ ok = usable and n.get("setpoint_mw", 0) > 1.0
126
+ elif kind == "shed":
127
+ n = view.nodes.get(args[0], {})
128
+ if args[1] == "shed25":
129
+ ok = bool(n.get("energized")) and view.served_mw(args[0]) > 1.0
130
+ else:
131
+ ok = n.get("shed_mw", 0.0) > 1.0 or n.get("ufls_shed_pct", 0.0) > 0.0
132
+ elif kind == "breaker":
133
+ e = view.edges.get(args[0], {})
134
+ if args[1] == "OPEN":
135
+ ok = e.get("status") == "LIVE"
136
+ else:
137
+ ends = (view.nodes.get(e.get("source"), {}), view.nodes.get(e.get("target"), {}))
138
+ ok = (e.get("status") != "LIVE" and not e.get("out_of_service")
139
+ and any(x.get("energized") for x in ends))
140
+ elif kind == "estimate":
141
+ ok = bool(view.nodes.get(args[0], {}).get("energized"))
142
+ elif kind == "quarantine":
143
+ ok = args[0] == violation and not view.nodes.get(args[0], {}).get("quarantined")
144
+ else: # counter
145
+ n = view.nodes.get(args[0], {})
146
+ ok = bool(n.get("energized")) and n.get("soc_pct", 0.0) > 5.0
147
+ mask[i] = bool(ok)
148
+ return mask
149
+
150
+ def nearest(self, action: GridAction, view: GridView) -> int:
151
+ """Closest catalogue entry to an arbitrary action (used to imitate the expert)."""
152
+ t = action.action_type.value if hasattr(action.action_type, "value") else str(action.action_type)
153
+ if t == "dispatch_generation" and action.node_id in DISPATCH_UNITS and action.mw:
154
+ step = min(DISPATCH_STEPS, key=lambda d: (abs(d - action.mw), -abs(d)))
155
+ return self.index[("dispatch", (action.node_id, step))]
156
+ if t == "shed_load" and action.node_id in SHEDDABLE_LOADS and action.mw is not None:
157
+ return self.index[("shed", (action.node_id, "shed25" if action.mw > 0 else "restore"))]
158
+ if t == "toggle_circuit_breaker" and action.edge_id in EDGE_IDS and action.status in ("OPEN", "CLOSED"):
159
+ return self.index[("breaker", (action.edge_id, action.status))]
160
+ if t == "run_state_estimation" and action.subgraph:
161
+ target = action.subgraph[0]
162
+ return self.index[("estimate", (target,))] if target in NODE_IDS else 0
163
+ if t == "quarantine_scada_node" and action.node_id in NODE_IDS:
164
+ return self.index[("quarantine", (action.node_id,))]
165
+ if t == "inject_counter_signal" and action.node_id in BATTERIES and action.hz_offset is not None:
166
+ mode = min(COUNTER_MODES, key=lambda m: abs(m + action.hz_offset))
167
+ return self.index[("counter", (action.node_id, mode))]
168
+ return 0
169
+
170
+
171
+ CATALOG = ActionCatalog()
172
+
173
+
174
+ def featurize(view: GridView) -> np.ndarray:
175
+ """Fixed-size feature vector (float32) from an observation."""
176
+ feats: List[float] = []
177
+ task = [0.0] * 6
178
+ task[view.task_id] = 1.0
179
+ feats += task
180
+ feats.append(view.tick / max(1, view.max_ticks or MAX_TICKS.get(view.task_id, 20)))
181
+ feats.append(float(np.clip((view.frequency - 60.0) / 0.5, -3, 3)))
182
+ feats.append(len(view.islands) / 5.0)
183
+ main = view.main_island()
184
+ if main:
185
+ feats.append(float(np.clip(main["setpoint_mismatch_mw"] / 1000.0, -3, 3)))
186
+ feats.append(view.stiffness(main) / 2000.0)
187
+ feats.append(len(main["nodes"]) / 20.0)
188
+ else:
189
+ feats += [0.0, 0.0, 0.0]
190
+ demand = view.forecast.get("system_demand_mw") or []
191
+ solar = view.forecast.get("solar_available_mw") or []
192
+ served_now = sum(view.served_mw(n) for n, x in view.nodes.items() if x["node_type"] == "load")
193
+ solar_now = sum(view.telemetry.get(n, {}).get("generation_mw", 0.0)
194
+ for n, x in view.nodes.items() if x["node_type"] == "solar")
195
+ for k in range(3):
196
+ feats.append(float(np.clip(((demand[k] if k < len(demand) else served_now) - served_now) / 500.0, -4, 4)))
197
+ for k in range(3):
198
+ feats.append(float(np.clip(((solar[k] if k < len(solar) else solar_now) - solar_now) / 500.0, -4, 4)))
199
+ se = view.last_se or {}
200
+ feats.append(1.0 if se else 0.0)
201
+ feats.append(1.0 if se and not se.get("consistent", True) else 0.0)
202
+ feats.append(len(view.counter_signals) / 4.0)
203
+ feats.append(1.0 if view.raw.get("last_action_error") else 0.0)
204
+
205
+ flagged = {p["source_node"] for p in view.latest_packets() if p.get("anomaly_flag")}
206
+ violation = se.get("violation_node") if se and not se.get("consistent", True) else None
207
+ signal_nodes = {cs["node_id"] for cs in view.counter_signals}
208
+ for nid in NODE_IDS:
209
+ n = view.nodes.get(nid, {})
210
+ r = view.telemetry.get(nid, {})
211
+ onehot = [1.0 if n.get("node_type") == t else 0.0 for t in NODE_TYPES]
212
+ cap = float(n.get("capacity_mw", 0.0))
213
+ feats += onehot
214
+ feats += [
215
+ 1.0 if n.get("energized") else 0.0,
216
+ 1.0 if n.get("critical") else 0.0,
217
+ 1.0 if n.get("quarantined") else 0.0,
218
+ 1.0 if n.get("black_start_capable") else 0.0,
219
+ 1.0 if n.get("tripped") else 0.0,
220
+ cap / 1500.0,
221
+ float(n.get("setpoint_mw", 0.0)) / 1500.0,
222
+ float(r.get("generation_mw", 0.0)) / 1500.0,
223
+ float(r.get("consumption_mw", 0.0)) / 700.0,
224
+ float(n.get("peak_load_mw", 0.0)) / 700.0,
225
+ float(n.get("shed_mw", 0.0)) / 500.0,
226
+ float(n.get("ufls_shed_pct", 0.0)) / 100.0,
227
+ float(n.get("soc_pct", 0.0)) / 100.0,
228
+ float(n.get("ramp_mw_per_tick", 0.0) or 0.0) / 400.0,
229
+ float(np.clip((r.get("frequency_hz", 60.0) - 60.0) / 0.5, -3, 3)) if n.get("energized") else 0.0,
230
+ float(r.get("oscillation_amplitude_hz", 0.0)) * 10.0,
231
+ float(r.get("oscillation_hz", 0.0)),
232
+ 1.0 if nid in flagged else 0.0,
233
+ 1.0 if nid == violation else 0.0,
234
+ 1.0 if nid in signal_nodes else 0.0,
235
+ ]
236
+ for eid in EDGE_IDS:
237
+ e = view.edges.get(eid, {})
238
+ cap = max(float(e.get("capacity_mw", 1.0)), 1.0)
239
+ live = e.get("status") == "LIVE"
240
+ feats += [
241
+ 1.0 if live else 0.0,
242
+ 1.0 if e.get("out_of_service") else 0.0,
243
+ float(np.clip(e.get("flow_mw", 0.0) / cap, -2, 2)) if live else 0.0,
244
+ float(np.clip(abs(e.get("flow_mw", 0.0)) / cap, 0, 2)) if live else 0.0,
245
+ cap / 1200.0,
246
+ ]
247
+ return np.asarray(feats, dtype=np.float32)
248
+
249
+
250
+ FEATURE_SIZE = int(featurize(GridView(NexusgridEnvironment().reset(seed=0, task_id=1))).shape[0])
251
+
252
+
253
+ if gym is not None:
254
+
255
+ class NexusGridGymEnv(gym.Env):
256
+ """Single-agent Gymnasium environment over one or more NexusGrid tasks."""
257
+
258
+ metadata = {"render_modes": []}
259
+
260
+ def __init__(self, tasks: Sequence[int] = (1,), seed_range: Tuple[int, int] = (0, EVAL_SEED_START),
261
+ fixed_seeds: Optional[Sequence[int]] = None):
262
+ super().__init__()
263
+ self.tasks = list(tasks)
264
+ self.seed_range = seed_range
265
+ self.fixed_seeds = list(fixed_seeds) if fixed_seeds else None
266
+ self._fixed_cursor = 0
267
+ self.env = NexusgridEnvironment()
268
+ self.action_space = spaces.Discrete(len(CATALOG))
269
+ self.observation_space = spaces.Box(low=-10.0, high=10.0, shape=(FEATURE_SIZE,), dtype=np.float32)
270
+ self._view: Optional[GridView] = None
271
+ self._rng = np.random.default_rng()
272
+
273
+ def reset(self, *, seed: Optional[int] = None, options: Optional[Dict[str, Any]] = None):
274
+ if seed is not None:
275
+ self._rng = np.random.default_rng(seed)
276
+ options = options or {}
277
+ task_id = int(options.get("task_id", self._rng.choice(self.tasks)))
278
+ if "episode_seed" in options:
279
+ episode_seed = int(options["episode_seed"])
280
+ elif self.fixed_seeds:
281
+ episode_seed = self.fixed_seeds[self._fixed_cursor % len(self.fixed_seeds)]
282
+ self._fixed_cursor += 1
283
+ else:
284
+ episode_seed = int(self._rng.integers(*self.seed_range))
285
+ obs = self.env.reset(seed=episode_seed, task_id=task_id)
286
+ self._view = GridView(obs)
287
+ return featurize(self._view), {"task_id": task_id, "episode_seed": episode_seed}
288
+
289
+ def step(self, action: int):
290
+ grid_action = CATALOG.to_action(int(action), self._view)
291
+ obs = self.env.step(grid_action)
292
+ self._view = GridView(obs)
293
+ info: Dict[str, Any] = {"error": obs.last_action_error}
294
+ if obs.done:
295
+ info["score"] = self.env.get_score()
296
+ info["task_id"] = self.env.task_id
297
+ return featurize(self._view), float(obs.reward), bool(obs.done), False, info
298
+
299
+ def action_masks(self) -> np.ndarray:
300
+ return CATALOG.mask(self._view)
301
+
302
+
303
+ class PPOPolicy:
304
+ """Wraps a trained MaskablePPO model as a NexusGrid policy (for scripts/evaluate.py)."""
305
+
306
+ name = "ppo"
307
+
308
+ def __init__(self, path: str, deterministic: bool = True):
309
+ from sb3_contrib import MaskablePPO
310
+
311
+ self.model = MaskablePPO.load(path, device="cpu")
312
+ self.deterministic = deterministic
313
+
314
+ def reset(self, seed: Optional[int] = None) -> None:
315
+ return None
316
+
317
+ def act(self, obs: Any) -> GridAction:
318
+ view = GridView(obs)
319
+ action, _ = self.model.predict(featurize(view), action_masks=CATALOG.mask(view),
320
+ deterministic=self.deterministic)
321
+ return CATALOG.to_action(int(action), view)
322
+
323
+
324
+ class DiscretizedExpert:
325
+ """The expert restricted to the RL action catalogue (upper reference for PPO)."""
326
+
327
+ name = "expert_discrete"
328
+
329
+ def __init__(self) -> None:
330
+ from policies import ExpertPolicy
331
+
332
+ self.expert = ExpertPolicy()
333
+
334
+ def reset(self, seed: Optional[int] = None) -> None:
335
+ self.expert.reset(seed)
336
+
337
+ def act_index(self, obs: Any) -> int:
338
+ view = GridView(obs)
339
+ idx = CATALOG.nearest(self.expert.act(obs), view)
340
+ return idx if CATALOG.mask(view)[idx] else 0
341
+
342
+ def act(self, obs: Any) -> GridAction:
343
+ view = GridView(obs)
344
+ return CATALOG.to_action(self.act_index(obs), view)
345
+
346
+
347
+ __all__ = ["ActionCatalog", "CATALOG", "DISPATCHABLE", "DiscretizedExpert", "FEATURE_SIZE", "NexusGridGymEnv",
348
+ "PPOPolicy", "featurize"]
inference.py CHANGED
@@ -1,217 +1,299 @@
1
  """
2
- NexusGrid-CyberPhysEnv — Inference Script.
3
- Runs an LLM agent against all 6 tasks using the OpenAI-compatible client.
4
- Reads API_BASE_URL and MODEL_NAME from environment variables.
5
- Uses Ollama for local testing (API_KEY="ollama").
6
- Structured logging: [START] / [STEP] / [END] format.
7
- Per-task time budgets enforced. Total runtime < 20 minutes.
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  """
9
 
 
 
 
 
10
  import json
11
  import os
 
12
  import sys
13
  import time
14
- import ast
15
- import re
16
  from typing import Any, Dict, List, Optional
17
 
18
  try:
19
  from dotenv import load_dotenv
20
- # Load .env file
21
  load_dotenv()
22
- except ImportError:
23
- pass # In isolated grader containers, python-dotenv might not be available
24
 
25
- from openai import OpenAI
 
 
26
 
27
- # ---------------------------------------------------------------------------
28
- # Configuration from environment
29
- # ---------------------------------------------------------------------------
30
-
31
- API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"
32
- MODEL_NAME = os.getenv("MODEL_NAME") or "deepseek-ai/DeepSeek-R1-Distill-Llama-8B"
33
- API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY") or "ollama"
34
- # Per-task time budgets in seconds
35
- TASK_BUDGETS = {
36
- 0: 30,
37
- 1: 180,
38
- 2: 180,
39
- 3: 180,
40
- 4: 120,
41
- 5: 300,
42
- }
43
 
 
 
 
44
  EPISODE_SEED = int(os.getenv("EPISODE_SEED", "42"))
45
  DEBUG_LLM_OUTPUT = os.getenv("DEBUG_LLM_OUTPUT", "0") == "1"
46
  SCORE_EPSILON = 0.001
47
- MAX_LLM_CALL_SECONDS = 20
 
 
 
48
 
49
 
50
  def _env_flag_is_true(raw_value: Optional[str]) -> bool:
51
- """Interpret conventional truthy environment variable values."""
52
  return str(raw_value or "").strip().lower() in {"1", "true", "yes", "on"}
53
 
54
 
55
  def _is_ollama_backend(api_base_url: Optional[str], compat_override: Optional[str] = None) -> bool:
56
- """
57
- Detect Ollama-compatible backends.
58
-
59
- Local-hosted Ollama is auto-detected. Remote or tunneled OpenAI-compatible
60
- Ollama deployments can opt in with OLLAMA_COMPAT=1.
61
- """
62
  if _env_flag_is_true(compat_override):
63
  return True
64
-
65
  base_url = (api_base_url or "").lower()
66
- return any(
67
- host in base_url
68
- for host in ("localhost:11434", "127.0.0.1:11434", "host.docker.internal:11434")
69
- )
70
-
71
 
72
- IS_OLLAMA_BACKEND = _is_ollama_backend(API_BASE_URL, os.getenv("OLLAMA_COMPAT"))
73
 
74
  # ---------------------------------------------------------------------------
75
  # Structured logging
76
  # ---------------------------------------------------------------------------
77
 
78
  def log_start(task_id: int, episode_seed: int, model_name: str) -> None:
79
- print(f"[START] task={task_id} env=NexusGrid-CyberPhysEnv model={model_name}", flush=True)
80
-
81
-
82
- def log_step(
83
- task_id: int,
84
- tick: int,
85
- action: str,
86
- params: Dict[str, Any],
87
- reward: float,
88
- done: bool,
89
- error: Optional[str] = None
90
- ) -> None:
91
- # Build complete action dict and stringify
92
- action_dict = {"action_type": action, **params}
93
- action_str = json.dumps(action_dict, separators=(',', ':'))
94
  error_val = str(error) if error else "null"
95
- done_val = str(done).lower()
96
- print(
97
- f"[STEP] step={tick + 1} action={action_str} reward={reward:.2f} done={done_val} error={error_val}",
98
- flush=True,
99
- )
100
 
101
 
102
  def log_end(task_id: int, score: float, ticks: int, rewards: List[float]) -> None:
103
- success = score >= 0.1 # assuming anything > 0 handles some task constraints, or score > 0.0
104
  rewards_str = ",".join(f"{r:.2f}" for r in rewards) if rewards else "0.00"
105
- print(f"[END] success={str(success).lower()} steps={ticks} score={score:.3f} rewards={rewards_str}", flush=True)
 
106
 
107
 
108
  def clamp_submission_score(score: float) -> float:
109
- """Clamp reported scores into the strict open interval (0, 1)."""
110
  return max(SCORE_EPSILON, min(1.0 - SCORE_EPSILON, float(score)))
111
 
112
 
113
  # ---------------------------------------------------------------------------
114
- # System prompt — teaches the agent about the environment
115
  # ---------------------------------------------------------------------------
116
 
117
- SYSTEM_PROMPT = """You are an AI agent defending a national power grid against physical faults and SCADA cyberattacks.
118
- You interact with the NexusGrid-CyberPhysEnv through actions. Each turn, you receive an observation of the grid state and must choose exactly ONE action.
119
- AVAILABLE ACTIONS (respond with EXACTLY one JSON object):
120
- 1. dispatch_generation - Ramp a power plant up or down
121
- {"action_type": "dispatch_generation", "node_id": "NODE_XX", "mw": <float>}
122
- 2. toggle_circuit_breaker - Open or close a transmission line
123
- {"action_type": "toggle_circuit_breaker", "edge_id": "LINE_XX", "status": "OPEN" or "CLOSED"}
124
- 3. run_state_estimation - Check if telemetry is consistent with physics (Kirchhoff's laws)
125
- {"action_type": "run_state_estimation", "subgraph": ["NODE_XX", "NODE_YY"]}
126
- 4. quarantine_scada_node - Disconnect a spoofed sensor (MUST run state_estimation first!)
127
- {"action_type": "quarantine_scada_node", "node_id": "NODE_XX"}
128
- 5. inject_counter_signal - Inject destructive interference to counter resonance attack
129
- {"action_type": "inject_counter_signal", "node_id": "NODE_XX", "hz_offset": <float>, "duration": <int>}
130
- 6. advance_tick - Step the simulation forward one time unit
131
- {"action_type": "advance_tick"}
132
- KEY RULES:
133
- - grid_frequency_hz must stay above 59.0 Hz or the episode TERMINATES
134
- - Nominal frequency is 60.0 Hz; keep it between 59.7 and 60.3 Hz
135
- - ALWAYS run state_estimation before quarantining a node (anti-hallucination rule)
136
- - Check network_packet_logs for anomalies before running state_estimation
137
- - Battery nodes can inject power quickly — use them for emergencies
138
- - Respond with ONLY a valid JSON action object, nothing else"""
139
-
140
-
141
- # ---------------------------------------------------------------------------
142
- # Task-specific prompts
143
- # ---------------------------------------------------------------------------
144
-
145
- TASK_PROMPTS = {
146
- 0: """TASK 0 - SMOKE TEST (Trivial)
147
- Simply dispatch some generation to any node. Any valid dispatch_generation with positive mw scores 1.0.
148
- Just respond with a dispatch_generation action.""",
149
-
150
- 1: """TASK 1 - DUCK CURVE (Easy)
151
- Solar generation has dropped (sunset) and demand is spiking. Grid frequency is dropping.
152
- You need to dispatch battery reserves QUICKLY before frequency falls below 59.5 Hz.
153
- Battery nodes: NODE_04, NODE_08, NODE_16, NODE_20. Dispatch generation to at least 2 batteries.""",
154
-
155
- 2: """TASK 2 - CASCADE OVERLOAD (Medium)
156
- A storm has snapped the primary transmission line LINE_28 (NORTH-CENTRAL, 1200MW).
157
- Power is rerouting through secondary lines and may overload them.
158
- Strategy: 1) Identify and isolate overloaded lines 2) Shed non-critical industrial load
159
- 3) Protect critical nodes (hospitals NODE_03, NODE_11, NODE_15, data center NODE_18)
160
- 4) Restore supply through alternative paths.""",
161
-
162
- 3: """TASK 3 - PHANTOM INJECTION (Hard)
163
- SCADA telemetry in the western sector may be spoofed and packet logs may contain the first clue.
164
- Use evidence-first triage: inspect logs, verify suspicious telemetry with run_state_estimation,
165
- quarantine only after a violation is proven, then recover the missing power.
166
- WARNING: dispatching or quarantining before verification hard-fails this task.""",
167
-
168
- 4: """TASK 4 - STUXNET RESONANCE (Very Hard)
169
- A central turbine is being driven into mechanical resonance and will fail around tick 10.
170
- Do NOT cut the turbine off the grid.
171
- Use the telemetry to infer the oscillation, counter it with inject_counter_signal from a nearby battery,
172
- and only then rebalance generation gradually.""",
173
-
174
- 5: """TASK 5 - BLACK START (Expert)
175
- The grid is dark and only the hydro dam has black-start capability.
176
- Make cautious progress: build a starter island, avoid premature mergers, respect the phase-angle constraint,
177
- and prioritize critical infrastructure over total restoration.""",
178
- }
179
-
180
-
181
- # ---------------------------------------------------------------------------
182
- # Agent logic
183
- # ---------------------------------------------------------------------------
184
 
185
  ACTION_ALIASES = {
186
  "dispatch": "dispatch_generation",
187
  "dispatch_generation": "dispatch_generation",
 
 
 
188
  "toggle_breaker": "toggle_circuit_breaker",
189
  "toggle_circuit_breaker": "toggle_circuit_breaker",
190
  "run_state_estimation": "run_state_estimation",
191
  "state_estimation": "run_state_estimation",
192
  "quarantine_scada_node": "quarantine_scada_node",
193
  "quarantine_node": "quarantine_scada_node",
 
194
  "inject_counter_signal": "inject_counter_signal",
195
  "counter_signal": "inject_counter_signal",
196
  "advance_tick": "advance_tick",
197
  "wait": "advance_tick",
 
198
  }
199
 
200
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  def _strip_reasoning(text: str) -> str:
202
- """Remove common reasoning wrappers from local reasoning models."""
203
- cleaned = text.strip().replace("\ufeff", "")
204
  cleaned = re.sub(r"<think>[\s\S]*?</think>", "", cleaned, flags=re.IGNORECASE).strip()
205
- cleaned = cleaned.replace("“", '"').replace("”", '"').replace("’", "'").replace("‘", "'")
206
- return cleaned
207
 
208
 
209
  def _extract_balanced_candidates(text: str) -> List[str]:
210
- """Extract balanced JSON-like objects/lists from free-form model output."""
211
  candidates: List[str] = []
212
  stack: List[str] = []
213
  start_idx: Optional[int] = None
214
-
215
  for idx, ch in enumerate(text):
216
  if ch in "{[":
217
  if not stack:
@@ -221,752 +303,295 @@ def _extract_balanced_candidates(text: str) -> List[str]:
221
  if stack and ch == stack[-1]:
222
  stack.pop()
223
  if not stack and start_idx is not None:
224
- candidates.append(text[start_idx : idx + 1])
225
  start_idx = None
226
  else:
227
  stack = []
228
  start_idx = None
229
-
230
  return candidates
231
 
232
 
233
  def _normalize_action_dict(action: Dict[str, Any]) -> Optional[Dict[str, Any]]:
234
- """Normalize model-produced action shapes into the GridAction schema."""
235
  normalized = dict(action)
236
  action_type = normalized.get("action_type") or normalized.get("action") or normalized.get("type")
237
  if not action_type:
238
  return None
239
-
240
- canonical_type = ACTION_ALIASES.get(str(action_type).strip().lower())
241
- if canonical_type is None:
242
  return None
243
-
244
- normalized["action_type"] = canonical_type
245
-
246
- field_aliases = {
247
- "node": "node_id",
248
- "nodeId": "node_id",
249
- "target_node": "node_id",
250
- "edge": "edge_id",
251
- "edgeId": "edge_id",
252
- "target_edge": "edge_id",
253
- "nodes": "subgraph",
254
- "estimated_nodes": "subgraph",
255
- "hz": "hz_offset",
256
- "offset_hz": "hz_offset",
257
- "ticks": "duration",
258
- }
259
- for source_key, target_key in field_aliases.items():
260
- if source_key in normalized and target_key not in normalized:
261
- normalized[target_key] = normalized[source_key]
262
-
263
- if "status" in normalized and isinstance(normalized["status"], str):
264
  normalized["status"] = normalized["status"].strip().upper()
265
- if "node_id" in normalized and isinstance(normalized["node_id"], str):
266
- normalized["node_id"] = normalized["node_id"].strip().upper()
267
- if "edge_id" in normalized and isinstance(normalized["edge_id"], str):
268
- normalized["edge_id"] = normalized["edge_id"].strip().upper()
269
- if "subgraph" in normalized and isinstance(normalized["subgraph"], str):
270
  normalized["subgraph"] = re.findall(r"NODE_\d{2}", normalized["subgraph"].upper())
271
-
272
- for field in ("mw", "hz_offset", "duration"):
273
- value = normalized.get(field)
274
- if value is None:
275
- continue
276
  if isinstance(value, str):
277
  try:
278
- normalized[field] = float(value) if field != "duration" else int(float(value))
279
  except ValueError:
280
  return None
281
-
282
- allowed_keys = {
283
- "action_type",
284
- "node_id",
285
- "edge_id",
286
- "mw",
287
- "status",
288
- "subgraph",
289
- "hz_offset",
290
- "duration",
291
- }
292
- return {key: value for key, value in normalized.items() if key in allowed_keys}
293
 
294
 
295
  def _load_action_candidate(candidate: str) -> Optional[Dict[str, Any]]:
296
- """Try progressively looser decoders on a candidate JSON-ish blob."""
297
  candidate = candidate.strip()
298
  if not candidate:
299
  return None
300
-
301
  decoders = [
302
  lambda raw: json.loads(raw),
303
  lambda raw: json.loads(re.sub(r",(\s*[}\]])", r"\1", raw)),
304
  lambda raw: ast.literal_eval(raw),
305
  ]
306
-
307
  for decoder in decoders:
308
  try:
309
  parsed = decoder(candidate)
310
  except Exception:
311
  continue
312
-
313
- if isinstance(parsed, list):
314
- for item in parsed:
315
- if isinstance(item, dict):
316
- normalized = _normalize_action_dict(item)
317
- if normalized:
318
- return normalized
319
- elif isinstance(parsed, dict):
320
- normalized = _normalize_action_dict(parsed)
321
- if normalized:
322
- return normalized
323
-
324
- return None
325
-
326
-
327
- def _extract_action_heuristically(text: str) -> Optional[Dict[str, Any]]:
328
- """Best-effort parser for semi-structured local-model responses."""
329
- upper = text.upper()
330
- node_match = re.search(r"NODE_\d{2}", upper)
331
- edge_match = re.search(r"LINE_\d{2}", upper)
332
-
333
- def extract_number(pattern: str) -> Optional[float]:
334
- match = re.search(pattern, text, flags=re.IGNORECASE)
335
- if match:
336
- try:
337
- return float(match.group(1))
338
- except ValueError:
339
- return None
340
- return None
341
-
342
- if "ADVANCE_TICK" in upper:
343
- return {"action_type": "advance_tick"}
344
-
345
- if "DISPATCH_GENERATION" in upper and node_match:
346
- mw = extract_number(r'"?mw"?\s*[:=]\s*(-?\d+(?:\.\d+)?)')
347
- if mw is None:
348
- mw = extract_number(r'(-?\d+(?:\.\d+)?)\s*MW')
349
- if mw is not None:
350
- return {
351
- "action_type": "dispatch_generation",
352
- "node_id": node_match.group(0),
353
- "mw": mw,
354
- }
355
-
356
- if "TOGGLE_CIRCUIT_BREAKER" in upper and edge_match:
357
- status_match = re.search(r"\b(OPEN|CLOSED)\b", upper)
358
- if status_match:
359
- return {
360
- "action_type": "toggle_circuit_breaker",
361
- "edge_id": edge_match.group(0),
362
- "status": status_match.group(1),
363
- }
364
-
365
- if "RUN_STATE_ESTIMATION" in upper:
366
- nodes = re.findall(r"NODE_\d{2}", upper)
367
- if nodes:
368
- return {"action_type": "run_state_estimation", "subgraph": nodes[:4]}
369
-
370
- if "QUARANTINE_SCADA_NODE" in upper and node_match:
371
- return {"action_type": "quarantine_scada_node", "node_id": node_match.group(0)}
372
-
373
- if "INJECT_COUNTER_SIGNAL" in upper and node_match:
374
- hz_offset = extract_number(r'"?hz_offset"?\s*[:=]\s*(-?\d+(?:\.\d+)?)')
375
- duration = extract_number(r'"?duration"?\s*[:=]\s*(\d+(?:\.\d+)?)')
376
- if hz_offset is not None and duration is not None:
377
- return {
378
- "action_type": "inject_counter_signal",
379
- "node_id": node_match.group(0),
380
- "hz_offset": hz_offset,
381
- "duration": int(duration),
382
- }
383
-
384
  return None
385
 
386
 
387
  def parse_action(response_text: str) -> Optional[Dict[str, Any]]:
388
- """Parse LLM response into an action dict."""
389
- text = _strip_reasoning(response_text)
390
  if not text:
391
  return None
392
-
393
- code_fence_matches = re.findall(r"```(?:json)?\s*([\s\S]*?)```", text, flags=re.IGNORECASE)
394
- candidates = code_fence_matches + _extract_balanced_candidates(text) + [text]
395
-
396
- for candidate in candidates:
397
  action = _load_action_candidate(candidate)
398
  if action:
399
  return action
 
400
 
401
- return _extract_action_heuristically(text)
402
-
403
- def _latest_telemetry_by_node(obs_dict: Optional[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
404
- if not obs_dict:
405
- return {}
406
- telemetry_stream = obs_dict.get("telemetry_stream") or []
407
- if not telemetry_stream:
408
- return {}
409
- latest_tick = telemetry_stream[-1]
410
- return {
411
- reading.get("node_id"): reading
412
- for reading in latest_tick
413
- if isinstance(reading, dict) and reading.get("node_id")
414
- }
415
-
416
-
417
- def _topology_nodes_by_id(obs_dict: Optional[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
418
- topology = (obs_dict or {}).get("topology_graph", {})
419
- return {
420
- node.get("id"): node
421
- for node in topology.get("nodes", [])
422
- if isinstance(node, dict) and node.get("id")
423
- }
424
-
425
-
426
- def _topology_edges_by_id(obs_dict: Optional[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
427
- topology = (obs_dict or {}).get("topology_graph", {})
428
- return {
429
- edge.get("id"): edge
430
- for edge in topology.get("edges", [])
431
- if isinstance(edge, dict) and edge.get("id")
432
- }
433
-
434
-
435
- def _metadata_dict(obs_dict: Optional[Dict[str, Any]]) -> Dict[str, Any]:
436
- metadata = (obs_dict or {}).get("metadata", {})
437
- return metadata if isinstance(metadata, dict) else {}
438
-
439
-
440
- def _task3_phase(obs_dict: Optional[Dict[str, Any]]) -> str:
441
- """Track the evidence-first sequence for Task 3."""
442
- if not obs_dict:
443
- return "needs_logs"
444
-
445
- metadata = _metadata_dict(obs_dict)
446
- last_estimation = (
447
- obs_dict.get("last_state_estimation")
448
- or metadata.get("last_kirchhoff_result")
449
- or {}
450
- )
451
- packet_logs = obs_dict.get("network_packet_logs") or []
452
- active_spoofs = set(metadata.get("active_spoofs", []) or [])
453
- violation_found = isinstance(last_estimation, dict) and not last_estimation.get("consistent", True)
454
-
455
- if not packet_logs:
456
- return "needs_logs"
457
- if not violation_found:
458
- return "needs_estimation"
459
- if "NODE_14" in active_spoofs:
460
- return "needs_quarantine"
461
- return "secured"
462
-
463
-
464
- def _should_replace_with_fallback(
465
- task_id: int,
466
- tick: int,
467
- action_dict: Dict[str, Any],
468
- obs_dict: Optional[Dict[str, Any]],
469
- ) -> bool:
470
- """Replace obviously redundant or impossible actions with the scripted fallback."""
471
- if not obs_dict:
472
- return False
473
-
474
- action_type = action_dict.get("action_type")
475
- nodes = _topology_nodes_by_id(obs_dict)
476
- edges = _topology_edges_by_id(obs_dict)
477
- telemetry = _latest_telemetry_by_node(obs_dict)
478
- metadata = _metadata_dict(obs_dict)
479
-
480
- if task_id == 2:
481
- overloaded_edge_ids = {
482
- edge_id
483
- for edge_id, edge in edges.items()
484
- if edge.get("status") == "LIVE"
485
- and float(edge.get("current_load_mw", 0.0))
486
- >= 0.9 * max(float(edge.get("capacity_mw", 1.0)), 1.0)
487
- }
488
- if overloaded_edge_ids:
489
- if action_type != "toggle_circuit_breaker":
490
- return True
491
- status = str(action_dict.get("status", "")).upper()
492
- if status != "OPEN" or action_dict.get("edge_id") not in overloaded_edge_ids:
493
- return True
494
-
495
- if task_id == 3:
496
- task3_phase = _task3_phase(obs_dict)
497
- if task3_phase == "needs_logs":
498
- return action_type != "advance_tick"
499
- if task3_phase == "needs_estimation":
500
- if action_type != "run_state_estimation":
501
- return True
502
- subgraph = set(action_dict.get("subgraph") or [])
503
- return not {"NODE_14", "NODE_15"}.issubset(subgraph)
504
- if task3_phase == "needs_quarantine":
505
- return (
506
- action_type != "quarantine_scada_node"
507
- or action_dict.get("node_id") != "NODE_14"
508
- )
509
- if task3_phase == "secured" and action_type == "run_state_estimation":
510
- return True
511
-
512
- if action_type == "toggle_circuit_breaker":
513
- edge = edges.get(action_dict.get("edge_id", ""))
514
- if edge is None:
515
- return True
516
- status = str(action_dict.get("status", "")).upper()
517
- if status == "OPEN" and edge.get("status") == "TRIPPED":
518
- return True
519
- if status == "CLOSED" and edge.get("status") == "LIVE":
520
- return True
521
-
522
- if action_type == "dispatch_generation":
523
- node_id = action_dict.get("node_id", "")
524
- node = nodes.get(node_id)
525
- reading = telemetry.get(node_id, {})
526
- if node is None or not node.get("energized", False):
527
- return True
528
- requested_mw = float(action_dict.get("mw", 0.0) or 0.0)
529
- current_generation = float(reading.get("generation_mw", 0.0))
530
- capacity = float(node.get("capacity_mw", 0.0))
531
- if requested_mw > 0 and current_generation >= capacity:
532
- return True
533
- if requested_mw < 0 and current_generation <= 0:
534
- return True
535
-
536
- if action_type == "quarantine_scada_node":
537
- active_spoofs = set(metadata.get("active_spoofs", []) or [])
538
- if action_dict.get("node_id") not in active_spoofs:
539
- return True
540
-
541
- if task_id == 4:
542
- if tick == 0 and action_type != "inject_counter_signal":
543
- return True
544
- if tick > 0 and action_type == "inject_counter_signal":
545
- return True
546
-
547
- return False
548
-
549
-
550
- def get_fallback_action(task_id: int, tick: int, obs_dict: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
551
- """
552
- Scripted fallback strategies for when LLM fails to respond.
553
- These are intelligent strategies that will score reasonably on each task.
554
- """
555
- if task_id == 0:
556
- # Smoke test: any valid dispatch
557
- return {"action_type": "dispatch_generation", "node_id": "NODE_01", "mw": 100}
558
-
559
- elif task_id == 1:
560
- # Duck curve: dispatch all batteries in first 4 ticks, then advance
561
- batteries = ["NODE_04", "NODE_08", "NODE_16", "NODE_20"]
562
- if tick < len(batteries):
563
- return {"action_type": "dispatch_generation", "node_id": batteries[tick], "mw": 200}
564
- return {"action_type": "advance_tick"}
565
-
566
- elif task_id == 2:
567
- # Cascade overload: isolate the hottest live line, then let the model decide recovery.
568
- edges = _topology_edges_by_id(obs_dict)
569
-
570
- overloaded_edges = sorted(
571
- (
572
- edge for edge in edges.values()
573
- if edge.get("status") == "LIVE"
574
- and float(edge.get("current_load_mw", 0.0)) >= 0.9 * max(float(edge.get("capacity_mw", 1.0)), 1.0)
575
- ),
576
- key=lambda edge: (
577
- float(edge.get("current_load_mw", 0.0)) / max(float(edge.get("capacity_mw", 1.0)), 1.0),
578
- float(edge.get("capacity_mw", 0.0)),
579
- ),
580
- reverse=True,
581
- )
582
- if overloaded_edges:
583
- return {
584
- "action_type": "toggle_circuit_breaker",
585
- "edge_id": overloaded_edges[0]["id"],
586
- "status": "OPEN",
587
- }
588
- return {"action_type": "advance_tick"}
589
-
590
- elif task_id == 3:
591
- # Phantom injection: only guarantee the safe verification sequence.
592
- task3_phase = _task3_phase(obs_dict)
593
- if task3_phase == "needs_logs":
594
- return {"action_type": "advance_tick"}
595
- if task3_phase == "needs_estimation":
596
- return {"action_type": "run_state_estimation", "subgraph": ["NODE_14", "NODE_15"]}
597
- if task3_phase == "needs_quarantine":
598
- return {"action_type": "quarantine_scada_node", "node_id": "NODE_14"}
599
- return {"action_type": "advance_tick"}
600
-
601
- elif task_id == 4:
602
- # Stuxnet resonance: only guarantee the first defensive move.
603
- if tick == 0:
604
- return {"action_type": "inject_counter_signal", "node_id": "NODE_20",
605
- "hz_offset": -0.5, "duration": 5}
606
- return {"action_type": "advance_tick"}
607
-
608
- elif task_id == 5:
609
- # Black start: make minimal safe progress without solving the topology deterministically.
610
- nodes = _topology_nodes_by_id(obs_dict)
611
- edges = _topology_edges_by_id(obs_dict)
612
- telemetry = _latest_telemetry_by_node(obs_dict)
613
-
614
- def node_energized(node_id: str) -> bool:
615
- return bool(nodes.get(node_id, {}).get("energized"))
616
-
617
- def line_live(edge_id: str) -> bool:
618
- return edges.get(edge_id, {}).get("status") == "LIVE"
619
-
620
- def generation(node_id: str) -> float:
621
- return float(telemetry.get(node_id, {}).get("generation_mw", 0.0))
622
-
623
- if generation("NODE_01") <= 0:
624
- return {"action_type": "dispatch_generation", "node_id": "NODE_01", "mw": 400}
625
- if (
626
- "LINE_02" in edges
627
- and not line_live("LINE_02")
628
- and node_energized("NODE_01")
629
- and not node_energized("NODE_03")
630
- ):
631
- return {"action_type": "toggle_circuit_breaker", "edge_id": "LINE_02", "status": "CLOSED"}
632
- return {"action_type": "advance_tick"}
633
-
634
- return {"action_type": "advance_tick"}
635
-
636
-
637
- def build_observation_prompt(obs_dict: Dict[str, Any], task_id: int) -> str:
638
- """Build a concise observation prompt for the LLM."""
639
- parts = [TASK_PROMPTS.get(task_id, "Unknown task")]
640
- parts.append(f"\n--- CURRENT STATE (tick {obs_dict.get('tick', 0)}) ---")
641
- parts.append(f"Grid Frequency: {obs_dict.get('grid_frequency_hz', 60.0):.2f} Hz")
642
-
643
- # Topology summary
644
- topo = obs_dict.get("topology_graph", {})
645
- nodes = topo.get("nodes", [])
646
- edges = topo.get("edges", [])
647
-
648
- # Summarize generators and their output
649
- generators = [n for n in nodes if n.get("node_type") in ("hydro", "solar", "gas", "battery")]
650
- if generators:
651
- parts.append("\nGENERATORS:")
652
- for g in generators:
653
- energized = "✓" if g.get("energized", True) else "✗"
654
- cap = g.get("capacity_mw", 0)
655
- parts.append(f" {g['id']} ({g['node_type']}) cap={cap}MW {energized}")
656
-
657
- # Summarize loads
658
- loads = [n for n in nodes if n.get("node_type") == "load"]
659
- if loads:
660
- parts.append("\nLOADS:")
661
- for l in loads:
662
- crit = " [CRITICAL]" if l.get("critical") else ""
663
- energized = "✓" if l.get("energized", True) else "✗"
664
- parts.append(f" {l['id']} peak={l.get('peak_load_mw', 0)}MW{crit} {energized}")
665
-
666
- # Tripped/overloaded lines
667
- tripped = [e for e in edges if e.get("status") == "TRIPPED"]
668
- if tripped:
669
- parts.append("\nTRIPPED LINES:")
670
- for e in tripped:
671
- parts.append(f" {e['id']} ({e['source']}→{e['target']}) cap={e.get('capacity_mw', 0)}MW")
672
-
673
- overloaded = [
674
- e for e in edges
675
- if e.get("status") == "LIVE"
676
- and e.get("current_load_mw", 0) >= 0.9 * e.get("capacity_mw", 1)
677
- ]
678
- if overloaded:
679
- parts.append("\nOVERLOADED LINES (>90%):")
680
- for e in overloaded:
681
- load_pct = (e["current_load_mw"] / e["capacity_mw"]) * 100 if e["capacity_mw"] > 0 else 0
682
- parts.append(f" {e['id']} ({e['source']}→{e['target']}) {load_pct:.0f}%")
683
-
684
- # Packet log anomalies
685
- packet_logs = obs_dict.get("network_packet_logs", [])
686
- anomalies = [p for p in packet_logs if p.get("anomaly_flag")]
687
- if anomalies:
688
- parts.append("\n⚠ SCADA ANOMALIES DETECTED:")
689
- for a in anomalies[:5]:
690
- parts.append(f" {a['source_node']} latency={a['latency_ms']:.0f}ms")
691
-
692
- # State estimation result
693
- est = obs_dict.get("last_state_estimation")
694
- if est:
695
- if est.get("consistent"):
696
- parts.append("\nState estimation: CONSISTENT (no violations)")
697
- else:
698
- parts.append(f"\n⚠ KIRCHHOFF VIOLATION at {est.get('violation_node')}: "
699
- f"estimated true={est.get('estimated_true_mw', 0):.0f}MW")
700
-
701
- # Weather summary
702
- weather_summary = obs_dict.get("weather_summary", "")
703
- if weather_summary:
704
- parts.append(f"\nWeather: {weather_summary}")
705
-
706
- # Error from last action
707
- error = obs_dict.get("last_action_error")
708
- if error:
709
- parts.append(f"\n❌ Last action error: {error}")
710
-
711
- parts.append("\nRespond with exactly ONE JSON action object:")
712
-
713
- return "\n".join(parts)
714
-
715
-
716
- def run_task(client: OpenAI, task_id: int, seed: int, env) -> float:
717
- """
718
- Run a single task episode and return the grader score.
719
- Args:
720
- client: OpenAI client
721
- task_id: Task ID (0-5)
722
- seed: Episode seed
723
- env: NexusgridEnvironment instance
724
- Returns:
725
- Final grader score [0.0, 1.0]
726
- """
727
- from server.scenarios import MAX_TICKS
728
-
729
- max_ticks = MAX_TICKS.get(task_id, 20)
730
- budget = TASK_BUDGETS.get(task_id, 180)
731
- start_time = time.time()
732
-
733
- log_start(task_id, seed, MODEL_NAME)
734
 
735
- # Reset environment safely
 
 
736
  try:
737
- obs = env.reset(seed=seed, task_id=task_id)
738
- if hasattr(obs, "observation"):
739
- obs_obj = obs.observation
740
- else:
741
- obs_obj = obs
742
- obs_dict = obs_obj.model_dump() if hasattr(obs_obj, "model_dump") else obs_obj.__dict__
743
- except Exception as e:
744
- print(f"[DEBUG] env.reset failed: {e}", flush=True)
745
- failure_score = clamp_submission_score(0.0)
746
- log_end(task_id, failure_score, 0, [])
747
- return failure_score
748
-
749
- cumulative_reward = 0.0
750
- tick = 0
751
- done = False
752
- rewards_history = []
753
-
754
- conversation_history = [
755
- {"role": "system", "content": SYSTEM_PROMPT},
756
- ]
757
-
758
- while not done and tick < max_ticks:
759
- elapsed = time.time() - start_time
760
- if elapsed >= budget:
761
- print(f"[DEBUG] Task {task_id} budget exceeded ({elapsed:.0f}s >= {budget}s)", flush=True)
762
- break
763
- llm_timeout = max(1, min(MAX_LLM_CALL_SECONDS, int(budget - elapsed)))
764
 
765
- # Build observation prompt
766
- user_prompt = build_observation_prompt(obs_dict, task_id)
767
- conversation_history.append({"role": "user", "content": user_prompt})
768
 
769
- # Get LLM response
770
- action_dict = None
771
- response_text = ""
772
- if client is not None:
773
- try:
774
- completion_kwargs = {
775
- "model": MODEL_NAME,
776
- "messages": conversation_history[-6:], # Keep context window small
777
- "temperature": 0.2,
778
- "max_tokens": 160,
779
- "stream": False,
780
- "timeout": llm_timeout,
781
- }
782
- if IS_OLLAMA_BACKEND:
783
- # Enable Ollama-specific compatibility only for detected or
784
- # explicitly opted-in OpenAI-compatible Ollama backends.
785
- completion_kwargs["response_format"] = {"type": "json_object"}
786
- completion_kwargs["reasoning_effort"] = "none"
787
-
788
- completion = client.chat.completions.create(
789
- **completion_kwargs,
790
- )
791
- message = completion.choices[0].message
792
- response_text = (
793
- (message.content or "")
794
- or getattr(message, "reasoning", "")
795
- or getattr(message, "thinking", "")
796
- ).strip()
797
- conversation_history.append({"role": "assistant", "content": response_text})
798
- action_dict = parse_action(response_text)
799
- if action_dict is None and DEBUG_LLM_OUTPUT:
800
- print(
801
- f"[DEBUG] Unparseable LLM response task={task_id} tick={tick}: {response_text[:400]!r}",
802
- flush=True,
803
- )
804
- except Exception as e:
805
- print(f"[DEBUG] LLM call failed: {e}", flush=True)
806
-
807
- # Fallback if LLM failed
808
- if action_dict is None:
809
- print(f"[DEBUG] Using fallback action for task {task_id} tick {tick}", flush=True)
810
- action_dict = get_fallback_action(task_id, tick, obs_dict)
811
- elif _should_replace_with_fallback(task_id, tick, action_dict, obs_dict):
812
- print(
813
- f"[DEBUG] Replacing ineffective model action with fallback for task {task_id} tick {tick}",
814
- flush=True,
815
- )
816
- action_dict = get_fallback_action(task_id, tick, obs_dict)
817
-
818
- # Build GridAction
819
- from models import GridAction
820
- try:
821
- action = GridAction(**action_dict)
822
- except Exception as e:
823
- print(f"[DEBUG] Invalid action: {e}. Using fallback.", flush=True)
824
- action_dict = get_fallback_action(task_id, tick, obs_dict)
825
- action = GridAction(**action_dict)
826
 
827
- # Execute action
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
828
  try:
829
- obs = env.step(action)
830
- if hasattr(obs, "observation"):
831
- obs_obj = obs.observation
 
 
 
 
 
 
 
 
 
 
 
 
 
832
  else:
833
- obs_obj = obs
834
- obs_dict = obs_obj.model_dump() if hasattr(obs_obj, "model_dump") else obs_obj.__dict__
835
-
836
- reward = getattr(obs, "reward", obs_dict.get("reward", 0.0))
837
- done = getattr(obs, "done", obs_dict.get("done", False))
838
- except Exception as e:
839
- print(f"[DEBUG] env.step failed: {e}", flush=True)
840
- done = True
841
- reward = 0.0
842
-
843
- cumulative_reward += reward
844
- tick += 1
845
- rewards_history.append(reward)
846
-
847
- # Build action params for logging (exclude None values)
848
- log_params = {k: v for k, v in action_dict.items() if k != "action_type" and v is not None}
849
-
850
- log_step(
851
- task_id=task_id,
852
- tick=tick - 1,
853
- action=action_dict.get("action_type", "unknown"),
854
- params=log_params,
855
- reward=reward,
856
- done=done,
857
- error=obs_dict.get("last_action_error")
858
- )
859
-
860
- # Get grader score safely
861
- try:
862
- score = env.get_score() if hasattr(env, "get_score") else max(0.0, min(1.0, float(cumulative_reward)))
863
- except Exception as e:
864
- print(f"[DEBUG] Error getting score: {e}", flush=True)
865
- score = max(0.0, min(1.0, float(cumulative_reward)))
866
-
867
- # Clamp score to strictly (0, 1) — validator rejects exactly 0.0 and 1.0
868
- score = clamp_submission_score(float(score))
869
-
870
- log_end(task_id, score, tick, rewards_history)
871
-
872
- return score
873
 
874
 
875
  # ---------------------------------------------------------------------------
876
- # Main
877
  # ---------------------------------------------------------------------------
878
 
879
- def main():
880
- """Run inference on all 6 tasks."""
881
- print(f"[DEBUG] API_BASE_URL={API_BASE_URL}", flush=True)
882
- print(f"[DEBUG] MODEL_NAME={MODEL_NAME}", flush=True)
883
- print(f"[DEBUG] EPISODE_SEED={EPISODE_SEED}", flush=True)
884
-
885
- # Initialize OpenAI client safely
886
- try:
887
- client = OpenAI(
888
- base_url=API_BASE_URL,
889
- api_key=API_KEY or "dummy_key",
890
- )
891
- except Exception as e:
892
- print(f"[ERROR] Failed to initialize OpenAI client: {e}", flush=True)
893
- client = None
894
-
895
- # Connect to OpenEnv container on expected port or fallback locally
896
- env_url = os.getenv("ENV_URL", "http://localhost:8000")
897
- try:
898
- # Check if local server folder exists. If not, we are likely evaluated in OpenEnv.
899
- server_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "server")
900
- if os.path.exists(server_path) and not os.getenv("USE_REMOTE_ENV"):
901
- sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
902
- from server.nexusgrid_environment import NexusgridEnvironment
903
- print(f"[DEBUG] Using local NexusgridEnvironment", flush=True)
904
- env = NexusgridEnvironment()
905
- else:
906
- from client import NexusgridEnv
907
- print(f"[DEBUG] Connecting to remote environment at {env_url}", flush=True)
908
- env = NexusgridEnv(base_url=env_url).sync()
909
- except Exception as e:
910
- print(f"[DEBUG] Falling back to bare-minimum local NexusgridEnvironment: {e}", flush=True)
911
- sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
912
  from server.nexusgrid_environment import NexusgridEnvironment
913
  env = NexusgridEnvironment()
914
- scores = {}
915
-
916
- total_start = time.time()
917
-
918
- for task_id in range(6):
919
- print(f"\n{'='*60}", flush=True)
920
- print(f"[DEBUG] Starting Task {task_id} ({TASK_BUDGETS[task_id]}s budget)", flush=True)
921
- print(f"{'='*60}", flush=True)
922
-
923
- try:
924
- score = run_task(client, task_id, EPISODE_SEED, env)
925
- except Exception as e:
926
- print(f"[DEBUG] Task {task_id} failed with error: {e}", flush=True)
927
- import traceback
928
- traceback.print_exc()
929
- score = clamp_submission_score(0.0)
930
- log_end(task_id, score, 0, [])
931
-
932
- scores[task_id] = score
933
- print(f"[DEBUG] Task {task_id} score: {score:.2f}", flush=True)
934
-
935
- total_elapsed = time.time() - total_start
936
-
937
- # Print summary
938
- print(f"\n{'='*60}", flush=True)
939
- print("FINAL SCORES", flush=True)
940
- print(f"{'='*60}", flush=True)
941
- for tid, sc in scores.items():
942
- task_name = {
943
- 0: "Smoke test",
944
- 1: "Duck curve",
945
- 2: "Cascade overload",
946
- 3: "Phantom injection",
947
- 4: "Stuxnet resonance",
948
- 5: "Black start",
949
- }.get(tid, f"Task {tid}")
950
- print(f" Task {tid} ({task_name}): {sc:.2f}", flush=True)
951
-
952
- avg_score = sum(scores.values()) / len(scores) if scores else 0.0
953
- print(f"\n Average: {avg_score:.2f}", flush=True)
954
- print(f" Total time: {total_elapsed:.1f}s", flush=True)
955
-
956
- # Write scores to JSON
957
- scores_output = {
958
- "model": MODEL_NAME,
959
- "seed": EPISODE_SEED,
960
- "scores": {str(k): v for k, v in scores.items()},
961
- "average": avg_score,
962
- "total_time_seconds": round(total_elapsed, 1),
963
  }
964
-
965
- scores_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "scores.json")
966
- with open(scores_path, "w") as f:
967
- json.dump(scores_output, f, indent=2)
968
- print(f"\n[DEBUG] Scores written to {scores_path}", flush=True)
 
969
 
970
 
971
  if __name__ == "__main__":
972
- main()
 
1
  """
2
+ NexusGrid-CyberPhysEnv — LLM agent runner.
3
+
4
+ Runs a language model as the grid operator through any OpenAI-compatible
5
+ endpoint (Ollama, vLLM, LM Studio, Hugging Face router, OpenAI ...).
6
+
7
+ The model sees a compact text rendering of the observation and must answer
8
+ with one JSON action. By default the run is *pure*: unparseable answers
9
+ become ``advance_tick`` and are counted as invalid outputs. ``--fallback``
10
+ substitutes the expert policy's action instead and reports how often that
11
+ happened, so a fallback score is never mistaken for the model's own score.
12
+
13
+ Environment variables (also read from .env)
14
+ API_BASE_URL OpenAI-compatible base URL (default http://localhost:11434/v1)
15
+ MODEL_NAME model name (default qwen3:1.7b)
16
+ API_KEY / HF_TOKEN (default "ollama")
17
+ EPISODE_SEED seed for the default run (default 42)
18
+ ENV_URL + USE_REMOTE_ENV=1 drive a running server over WebSocket instead of in-process
19
+
20
+ Structured log lines: ``[START]``, ``[STEP]`` and ``[END]``.
21
  """
22
 
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import ast
27
  import json
28
  import os
29
+ import re
30
  import sys
31
  import time
 
 
32
  from typing import Any, Dict, List, Optional
33
 
34
  try:
35
  from dotenv import load_dotenv
36
+
37
  load_dotenv()
38
+ except ImportError: # pragma: no cover - optional dependency
39
+ pass
40
 
41
+ ROOT = os.path.dirname(os.path.abspath(__file__))
42
+ if ROOT not in sys.path:
43
+ sys.path.insert(0, ROOT)
44
 
45
+ from models import ActionType, GridAction # noqa: E402
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ API_BASE_URL = os.getenv("API_BASE_URL") or "http://localhost:11434/v1"
48
+ MODEL_NAME = os.getenv("MODEL_NAME") or "qwen3:1.7b"
49
+ API_KEY = os.getenv("API_KEY") or os.getenv("HF_TOKEN") or "ollama"
50
  EPISODE_SEED = int(os.getenv("EPISODE_SEED", "42"))
51
  DEBUG_LLM_OUTPUT = os.getenv("DEBUG_LLM_OUTPUT", "0") == "1"
52
  SCORE_EPSILON = 0.001
53
+ MAX_LLM_CALL_SECONDS = 60
54
+ TASK_BUDGETS = {0: 60, 1: 300, 2: 300, 3: 300, 4: 240, 5: 900}
55
+ TASK_NAMES = {0: "smoke_test", 1: "duck_curve", 2: "cascade_overload", 3: "phantom_inject",
56
+ 4: "stuxnet_resonance", 5: "black_start"}
57
 
58
 
59
  def _env_flag_is_true(raw_value: Optional[str]) -> bool:
 
60
  return str(raw_value or "").strip().lower() in {"1", "true", "yes", "on"}
61
 
62
 
63
  def _is_ollama_backend(api_base_url: Optional[str], compat_override: Optional[str] = None) -> bool:
64
+ """Local Ollama is detected automatically; remote Ollama can opt in with OLLAMA_COMPAT=1."""
 
 
 
 
 
65
  if _env_flag_is_true(compat_override):
66
  return True
 
67
  base_url = (api_base_url or "").lower()
68
+ return any(h in base_url for h in ("localhost:11434", "127.0.0.1:11434", "host.docker.internal:11434"))
 
 
 
 
69
 
 
70
 
71
  # ---------------------------------------------------------------------------
72
  # Structured logging
73
  # ---------------------------------------------------------------------------
74
 
75
  def log_start(task_id: int, episode_seed: int, model_name: str) -> None:
76
+ print(f"[START] task={task_id} seed={episode_seed} env=NexusGrid-CyberPhysEnv model={model_name}", flush=True)
77
+
78
+
79
+ def log_step(task_id: int, tick: int, action: str, params: Dict[str, Any], reward: float, done: bool,
80
+ error: Optional[str] = None) -> None:
81
+ action_str = json.dumps({"action_type": action, **params}, separators=(",", ":"))
 
 
 
 
 
 
 
 
 
82
  error_val = str(error) if error else "null"
83
+ print(f"[STEP] step={tick + 1} action={action_str} reward={reward:.2f} done={str(done).lower()} error={error_val}",
84
+ flush=True)
 
 
 
85
 
86
 
87
  def log_end(task_id: int, score: float, ticks: int, rewards: List[float]) -> None:
 
88
  rewards_str = ",".join(f"{r:.2f}" for r in rewards) if rewards else "0.00"
89
+ print(f"[END] success={str(score >= 0.5).lower()} steps={ticks} score={score:.3f} rewards={rewards_str}",
90
+ flush=True)
91
 
92
 
93
  def clamp_submission_score(score: float) -> float:
94
+ """Clamp a score into the open interval (0, 1) for validators that reject 0.0 and 1.0."""
95
  return max(SCORE_EPSILON, min(1.0 - SCORE_EPSILON, float(score)))
96
 
97
 
98
  # ---------------------------------------------------------------------------
99
+ # Prompting
100
  # ---------------------------------------------------------------------------
101
 
102
+ SYSTEM_PROMPT = """You are the control-room operator of a 20-bus transmission grid (DC power flow, one tick = 5 minutes).
103
+ Each turn you see the grid and send exactly ONE action as a JSON object.
104
+
105
+ ACTIONS
106
+ - {"action_type":"dispatch_generation","node_id":"NODE_01","mw":120}
107
+ Change a generator or battery setpoint by mw (+ raise, - lower). Limited by its ramp per tick and capacity.
108
+ - {"action_type":"shed_load","node_id":"NODE_07","mw":100}
109
+ Shed load at a non-critical load bus. Negative mw restores shed load (also load cut by UFLS relays).
110
+ - {"action_type":"toggle_circuit_breaker","edge_id":"LINE_12","status":"OPEN"} (status OPEN or CLOSED)
111
+ - {"action_type":"run_state_estimation","subgraph":["NODE_09","NODE_10"]}
112
+ Kirchhoff consistency check of up to 6 buses. A violation proves that bus's telemetry is falsified.
113
+ - {"action_type":"quarantine_scada_node","node_id":"NODE_09"}
114
+ Isolate a compromised SCADA channel. Refused (and penalised) unless state estimation proved that bus first.
115
+ - {"action_type":"inject_counter_signal","node_id":"NODE_20","hz_offset":-0.45,"duration":4}
116
+ Damping signal from a battery within 2 line hops of an oscillating unit; hz_offset must be the negative of the oscillation mode.
117
+ - {"action_type":"advance_tick"} Do nothing this tick.
118
+
119
+ GRID FACTS
120
+ - Keep frequency inside 59.8-60.2 Hz. Island frequency ~ 60 + mismatch / (0.25 x online dispatchable MW), where
121
+ mismatch = generation setpoints - demand. A mismatch of -300 MW is fixed by dispatching about +300 MW in total.
122
+ - Demand and solar change over time: the forecast shows what is coming, act before frequency moves.
123
+ - Below 59.2 Hz relays shed load automatically (UFLS). Below 59.0 Hz the episode ends.
124
+ - Lines above 100% loading trip after 3 ticks, instantly at 140%. Relieve them by raising generation near the
125
+ receiving end and lowering it near the sending end, or by shedding non-critical load. Lines marked out of service cannot be closed.
126
+ - Critical loads (hospitals, water, data centre) must stay energised.
127
+ - Closing a breaker between two live islands needs matching frequency (<=0.2 Hz) and phase angle (<=20 deg).
128
+ - In a blackout, energise lines outward from the black-start unit, raise generation before picking up load,
129
+ and restore critical loads first.
130
+
131
+ Answer with the JSON object only."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
  ACTION_ALIASES = {
134
  "dispatch": "dispatch_generation",
135
  "dispatch_generation": "dispatch_generation",
136
+ "shed": "shed_load",
137
+ "shed_load": "shed_load",
138
+ "load_shed": "shed_load",
139
  "toggle_breaker": "toggle_circuit_breaker",
140
  "toggle_circuit_breaker": "toggle_circuit_breaker",
141
  "run_state_estimation": "run_state_estimation",
142
  "state_estimation": "run_state_estimation",
143
  "quarantine_scada_node": "quarantine_scada_node",
144
  "quarantine_node": "quarantine_scada_node",
145
+ "quarantine": "quarantine_scada_node",
146
  "inject_counter_signal": "inject_counter_signal",
147
  "counter_signal": "inject_counter_signal",
148
  "advance_tick": "advance_tick",
149
  "wait": "advance_tick",
150
+ "noop": "advance_tick",
151
  }
152
 
153
 
154
+ def _obs_dict(obs: Any) -> Dict[str, Any]:
155
+ if hasattr(obs, "observation"):
156
+ obs = obs.observation
157
+ if hasattr(obs, "model_dump"):
158
+ return obs.model_dump()
159
+ return dict(obs)
160
+
161
+
162
+ def render_observation(obs: Any, history: Optional[List[str]] = None) -> str:
163
+ """Compact text rendering of an observation for language models."""
164
+ d = _obs_dict(obs)
165
+ topo = d.get("topology_graph") or {}
166
+ nodes = topo.get("nodes", [])
167
+ edges = topo.get("edges", [])
168
+ stream = d.get("telemetry_stream") or []
169
+ tele = {r["node_id"]: r for r in (stream[-1] if stream else [])}
170
+ task_id = int(d.get("task_id", 0))
171
+ lines: List[str] = []
172
+ lines.append(f"TASK {task_id} {TASK_NAMES.get(task_id, '')} | tick {d.get('tick', 0)}/{d.get('max_ticks', '?')} | "
173
+ f"system frequency {float(d.get('grid_frequency_hz', 60.0)):.3f} Hz (target 59.8-60.2)")
174
+ if d.get("task_brief"):
175
+ lines.append(f"BRIEF: {d['task_brief']}")
176
+
177
+ islands = d.get("islands") or []
178
+ if islands:
179
+ lines.append("ISLANDS:")
180
+ for isl in islands:
181
+ lines.append(f" #{isl['island']} {len(isl['nodes'])} buses f={isl['frequency_hz']:.3f} Hz "
182
+ f"gen {isl['generation_mw']:.0f} MW load {isl['load_mw']:.0f} MW "
183
+ f"mismatch {isl['setpoint_mismatch_mw']:+.0f} MW")
184
+ else:
185
+ lines.append("ISLANDS: none energised")
186
+ fc = d.get("forecast") or {}
187
+ if fc.get("system_demand_mw"):
188
+ dem = ", ".join(f"{v:.0f}" for v in fc["system_demand_mw"][:4])
189
+ sol = ", ".join(f"{v:.0f}" for v in (fc.get("solar_available_mw") or [])[:4])
190
+ lines.append(f"FORECAST next ticks: demand {dem} MW | solar {sol} MW")
191
+
192
+ lines.append("GENERATORS (id type region | capacity setpoint measured ramp):")
193
+ for n in nodes:
194
+ if n["node_type"] == "load":
195
+ continue
196
+ r = tele.get(n["id"], {})
197
+ flags = []
198
+ if not n.get("energized"):
199
+ flags.append("DARK")
200
+ if n.get("tripped"):
201
+ flags.append("TRIPPED")
202
+ if n.get("quarantined"):
203
+ flags.append("QUARANTINED")
204
+ if n.get("black_start_capable"):
205
+ flags.append("black-start")
206
+ if n["node_type"] == "battery":
207
+ flags.append(f"soc {n.get('soc_pct', 0):.0f}%")
208
+ lines.append(f" {n['id']} {n['node_type']} {n['region']} | cap {n['capacity_mw']:.0f} "
209
+ f"set {n.get('setpoint_mw', 0):.0f} meas {r.get('generation_mw', 0):.0f} "
210
+ f"ramp {n.get('ramp_mw_per_tick', 0):.0f}" + (f" [{', '.join(flags)}]" if flags else ""))
211
+ lines.append("LOADS (id region | served MW):")
212
+ for n in nodes:
213
+ if n["node_type"] != "load":
214
+ continue
215
+ r = tele.get(n["id"], {})
216
+ flags = ["CRITICAL"] if n.get("critical") else []
217
+ if not n.get("energized"):
218
+ flags.append(f"DARK, peak {n.get('peak_load_mw', 0):.0f}")
219
+ if n.get("shed_mw"):
220
+ flags.append(f"shed {n['shed_mw']:.0f}")
221
+ if n.get("ufls_shed_pct"):
222
+ flags.append(f"UFLS {n['ufls_shed_pct']:.0f}%")
223
+ lines.append(f" {n['id']} {n['region']} | {r.get('consumption_mw', 0):.0f}" +
224
+ (f" [{', '.join(flags)}]" if flags else ""))
225
+
226
+ adjacency: Dict[str, List[str]] = {n["id"]: [] for n in nodes}
227
+ for e in edges:
228
+ if e["status"] == "LIVE":
229
+ adjacency[e["source"]].append(e["target"])
230
+ adjacency[e["target"]].append(e["source"])
231
+ connected = [f"{nid}-{'/'.join(nbs)}" for nid, nbs in adjacency.items() if nbs]
232
+ lines.append("LIVE CONNECTIONS: " + ("; ".join(connected) if connected else "none"))
233
+
234
+ shown = []
235
+ for e in edges:
236
+ load = float(e.get("loading_pct", 0.0))
237
+ if e["status"] == "LIVE" and load < 80.0:
238
+ continue
239
+ state = "LIVE" if e["status"] == "LIVE" else ("OUT OF SERVICE" if e.get("out_of_service") else "OPEN")
240
+ detail = f" {load:.0f}% ({abs(e.get('flow_mw', 0)):.0f}/{e['capacity_mw']:.0f} MW)" if e["status"] == "LIVE" \
241
+ else f" cap {e['capacity_mw']:.0f}"
242
+ shown.append(f" {e['id']} {e['source']}-{e['target']} {state}{detail}")
243
+ if shown:
244
+ lines.append("LINES (loaded >= 80% or not live):")
245
+ lines.extend(shown)
246
+
247
+ packets = d.get("network_packet_logs") or []
248
+ if packets:
249
+ last = max(int(p["timestamp"]) // 300 for p in packets)
250
+ flagged = [p for p in packets if int(p["timestamp"]) // 300 == last and p.get("anomaly_flag")]
251
+ if flagged:
252
+ lines.append("SCADA PACKET ANOMALIES: " + ", ".join(
253
+ f"{p['source_node']} {p['latency_ms']:.0f} ms" for p in flagged))
254
+ se = d.get("last_state_estimation")
255
+ if se:
256
+ if se.get("consistent", True):
257
+ lines.append(f"LAST STATE ESTIMATION: consistent for {', '.join(se.get('checked_nodes', []))}")
258
+ else:
259
+ lines.append(f"LAST STATE ESTIMATION: VIOLATION at {se.get('violation_node')} - reported "
260
+ f"{se.get('reported_mw', 0):.0f} MW, physics says {se.get('estimated_true_mw', 0):.0f} MW")
261
+ osc = [(nid, r) for nid, r in tele.items() if r.get("oscillation_amplitude_hz", 0) > 0]
262
+ if osc:
263
+ osc.sort(key=lambda item: -item[1]["oscillation_amplitude_hz"])
264
+ lines.append("PMU OSCILLATION: " + "; ".join(
265
+ f"{nid} mode {r['oscillation_hz']:.2f} Hz amplitude {r['oscillation_amplitude_hz']:.3f} Hz" for nid, r in osc[:5]))
266
+ signals = d.get("active_counter_signals") or []
267
+ if signals:
268
+ lines.append("COUNTER-SIGNALS: " + "; ".join(
269
+ f"{s['node_id']} {s['hz_offset']:+.2f} Hz ({s['remaining_ticks']} ticks left)" for s in signals))
270
+ events = d.get("events") or []
271
+ if events:
272
+ lines.append("EVENTS LAST TICK: " + "; ".join(
273
+ f"{e['type']} {e.get('edge') or e.get('node') or ','.join(e.get('nodes', [])[:4])}" for e in events))
274
+ if d.get("last_action_error"):
275
+ lines.append(f"LAST ACTION ERROR: {d['last_action_error']}")
276
+ if history:
277
+ lines.append("YOUR RECENT ACTIONS: " + " | ".join(history[-4:]))
278
+ lines.append("Reply with one JSON action.")
279
+ return "\n".join(lines)
280
+
281
+
282
+ # ---------------------------------------------------------------------------
283
+ # Parsing model output
284
+ # ---------------------------------------------------------------------------
285
+
286
  def _strip_reasoning(text: str) -> str:
287
+ cleaned = text.strip().replace("", "")
 
288
  cleaned = re.sub(r"<think>[\s\S]*?</think>", "", cleaned, flags=re.IGNORECASE).strip()
289
+ cleaned = re.sub(r"^[\s\S]*?</think>", "", cleaned, flags=re.IGNORECASE).strip()
290
+ return cleaned.replace("“", '"').replace("”", '"').replace("’", "'").replace("‘", "'")
291
 
292
 
293
  def _extract_balanced_candidates(text: str) -> List[str]:
 
294
  candidates: List[str] = []
295
  stack: List[str] = []
296
  start_idx: Optional[int] = None
 
297
  for idx, ch in enumerate(text):
298
  if ch in "{[":
299
  if not stack:
 
303
  if stack and ch == stack[-1]:
304
  stack.pop()
305
  if not stack and start_idx is not None:
306
+ candidates.append(text[start_idx: idx + 1])
307
  start_idx = None
308
  else:
309
  stack = []
310
  start_idx = None
 
311
  return candidates
312
 
313
 
314
  def _normalize_action_dict(action: Dict[str, Any]) -> Optional[Dict[str, Any]]:
 
315
  normalized = dict(action)
316
  action_type = normalized.get("action_type") or normalized.get("action") or normalized.get("type")
317
  if not action_type:
318
  return None
319
+ canonical = ACTION_ALIASES.get(str(action_type).strip().lower())
320
+ if canonical is None:
 
321
  return None
322
+ normalized["action_type"] = canonical
323
+ aliases = {"node": "node_id", "nodeId": "node_id", "target_node": "node_id", "edge": "edge_id",
324
+ "edgeId": "edge_id", "line": "edge_id", "line_id": "edge_id", "target_edge": "edge_id",
325
+ "nodes": "subgraph", "buses": "subgraph", "hz": "hz_offset", "offset_hz": "hz_offset",
326
+ "ticks": "duration", "amount": "mw", "delta_mw": "mw"}
327
+ for source, target in aliases.items():
328
+ if source in normalized and target not in normalized:
329
+ normalized[target] = normalized[source]
330
+ if isinstance(normalized.get("status"), str):
 
 
 
 
 
 
 
 
 
 
 
 
331
  normalized["status"] = normalized["status"].strip().upper()
332
+ for key in ("node_id", "edge_id"):
333
+ if isinstance(normalized.get(key), str):
334
+ normalized[key] = normalized[key].strip().upper()
335
+ if isinstance(normalized.get("subgraph"), str):
 
336
  normalized["subgraph"] = re.findall(r"NODE_\d{2}", normalized["subgraph"].upper())
337
+ for key in ("mw", "hz_offset", "duration"):
338
+ value = normalized.get(key)
 
 
 
339
  if isinstance(value, str):
340
  try:
341
+ normalized[key] = float(value) if key != "duration" else int(float(value))
342
  except ValueError:
343
  return None
344
+ allowed = {"action_type", "node_id", "edge_id", "mw", "status", "subgraph", "hz_offset", "duration"}
345
+ return {k: v for k, v in normalized.items() if k in allowed}
 
 
 
 
 
 
 
 
 
 
346
 
347
 
348
  def _load_action_candidate(candidate: str) -> Optional[Dict[str, Any]]:
 
349
  candidate = candidate.strip()
350
  if not candidate:
351
  return None
 
352
  decoders = [
353
  lambda raw: json.loads(raw),
354
  lambda raw: json.loads(re.sub(r",(\s*[}\]])", r"\1", raw)),
355
  lambda raw: ast.literal_eval(raw),
356
  ]
 
357
  for decoder in decoders:
358
  try:
359
  parsed = decoder(candidate)
360
  except Exception:
361
  continue
362
+ items = parsed if isinstance(parsed, list) else [parsed]
363
+ for item in items:
364
+ if isinstance(item, dict):
365
+ normalized = _normalize_action_dict(item)
366
+ if normalized:
367
+ return normalized
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
  return None
369
 
370
 
371
  def parse_action(response_text: str) -> Optional[Dict[str, Any]]:
372
+ """Extract the first valid action object from free-form model output."""
373
+ text = _strip_reasoning(response_text or "")
374
  if not text:
375
  return None
376
+ fenced = re.findall(r"```(?:json)?\s*([\s\S]*?)```", text, flags=re.IGNORECASE)
377
+ for candidate in fenced + _extract_balanced_candidates(text) + [text]:
 
 
 
378
  action = _load_action_candidate(candidate)
379
  if action:
380
  return action
381
+ return None
382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
 
384
+ def to_grid_action(action_dict: Optional[Dict[str, Any]]) -> Optional[GridAction]:
385
+ if not action_dict:
386
+ return None
387
  try:
388
+ return GridAction(**action_dict)
389
+ except Exception:
390
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
 
 
 
 
392
 
393
+ # ---------------------------------------------------------------------------
394
+ # LLM policy
395
+ # ---------------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
396
 
397
+ class LLMPolicy:
398
+ """Language-model operator behind an OpenAI-compatible endpoint."""
399
+
400
+ name = "llm"
401
+
402
+ def __init__(self, model: str = MODEL_NAME, api_base: str = API_BASE_URL, api_key: Optional[str] = None,
403
+ temperature: float = 0.0, max_tokens: int = 256, fallback: bool = False,
404
+ timeout: float = MAX_LLM_CALL_SECONDS, client: Any = None):
405
+ self.model = model
406
+ self.api_base = api_base
407
+ self.temperature = temperature
408
+ self.max_tokens = max_tokens
409
+ self.fallback = fallback
410
+ self.timeout = timeout
411
+ self.is_ollama = _is_ollama_backend(api_base, os.getenv("OLLAMA_COMPAT"))
412
+ if client is None:
413
+ from openai import OpenAI
414
+ client = OpenAI(base_url=api_base, api_key=api_key or API_KEY or "none")
415
+ self.client = client
416
+ self._expert = None
417
+ if fallback:
418
+ from policies import ExpertPolicy
419
+ self._expert = ExpertPolicy()
420
+ self._history: List[str] = []
421
+ self._stats = {"calls": 0, "invalid_outputs": 0, "fallbacks": 0, "api_errors": 0, "latency_s": 0.0}
422
+ self.last_response = ""
423
+
424
+ def reset(self, seed: Optional[int] = None) -> None:
425
+ self._history = []
426
+ if self._expert is not None:
427
+ self._expert.reset()
428
+
429
+ def stats(self) -> Dict[str, Any]:
430
+ calls = max(1, self._stats["calls"])
431
+ return {**self._stats, "latency_s": round(self._stats["latency_s"], 2),
432
+ "mean_latency_s": round(self._stats["latency_s"] / calls, 3)}
433
+
434
+ def complete(self, prompt: str) -> str:
435
+ kwargs: Dict[str, Any] = {
436
+ "model": self.model,
437
+ "messages": [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}],
438
+ "temperature": self.temperature,
439
+ "max_tokens": self.max_tokens,
440
+ "timeout": self.timeout,
441
+ }
442
+ if self.is_ollama:
443
+ kwargs["response_format"] = {"type": "json_object"}
444
+ kwargs["reasoning_effort"] = "none"
445
+ completion = self.client.chat.completions.create(**kwargs)
446
+ message = completion.choices[0].message
447
+ return ((message.content or "") or getattr(message, "reasoning", "") or "").strip()
448
+
449
+ def act(self, obs: Any) -> GridAction:
450
+ expert_action = self._expert.act(obs) if self._expert is not None else None
451
+ prompt = render_observation(obs, self._history)
452
+ started = time.time()
453
+ text = ""
454
  try:
455
+ text = self.complete(prompt)
456
+ except Exception as exc: # network errors, timeouts
457
+ self._stats["api_errors"] += 1
458
+ if DEBUG_LLM_OUTPUT:
459
+ print(f"[DEBUG] LLM call failed: {exc}", flush=True)
460
+ self._stats["calls"] += 1
461
+ self._stats["latency_s"] += time.time() - started
462
+ self.last_response = text
463
+ action = to_grid_action(parse_action(text))
464
+ if action is None:
465
+ self._stats["invalid_outputs"] += 1
466
+ if DEBUG_LLM_OUTPUT:
467
+ print(f"[DEBUG] Unparseable output: {text[:300]!r}", flush=True)
468
+ if expert_action is not None:
469
+ self._stats["fallbacks"] += 1
470
+ action = expert_action
471
  else:
472
+ action = GridAction(action_type=ActionType.ADVANCE_TICK)
473
+ tick = _obs_dict(obs).get("tick", 0)
474
+ summary = {k: v for k, v in action.model_dump().items() if v is not None}
475
+ summary["action_type"] = action.action_type.value
476
+ self._history.append(f"t{tick} {json.dumps(summary, separators=(',', ':'))}")
477
+ return action
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478
 
479
 
480
  # ---------------------------------------------------------------------------
481
+ # Episode runner
482
  # ---------------------------------------------------------------------------
483
 
484
+ class RemoteEnvAdapter:
485
+ """Wraps the WebSocket client so it behaves like the in-process environment."""
486
+
487
+ def __init__(self, base_url: str):
488
+ from client import NexusgridEnv
489
+ self._env = NexusgridEnv(base_url=base_url).sync()
490
+ self._env.__enter__()
491
+ self._last = None
492
+
493
+ def reset(self, seed: int, task_id: int):
494
+ self._last = self._env.reset(seed=seed, task_id=task_id).observation
495
+ return self._last
496
+
497
+ def step(self, action: GridAction):
498
+ result = self._env.step(action)
499
+ obs = result.observation
500
+ obs.done = result.done
501
+ obs.reward = result.reward or 0.0
502
+ self._last = obs
503
+ return obs
504
+
505
+ def get_score(self) -> float:
506
+ return float(getattr(self._last, "score", 0.0) or 0.0)
507
+
508
+
509
+ def run_task(policy: Any, env: Any, task_id: int, seed: int, budget_s: Optional[float] = None,
510
+ verbose: bool = True) -> Dict[str, Any]:
511
+ """Run one episode and return the result record."""
512
+ budget_s = budget_s or TASK_BUDGETS.get(task_id, 300)
513
+ started = time.time()
514
+ if verbose:
515
+ log_start(task_id, seed, getattr(policy, "model", getattr(policy, "name", "policy")))
516
+ if hasattr(policy, "reset"):
517
+ policy.reset(seed)
518
+ obs = env.reset(seed=seed, task_id=task_id)
519
+ rewards: List[float] = []
520
+ ticks = 0
521
+ timed_out = False
522
+ while not obs.done:
523
+ if time.time() - started > budget_s:
524
+ timed_out = True
525
+ break
526
+ action = policy.act(obs)
527
+ obs = env.step(action)
528
+ rewards.append(float(obs.reward or 0.0))
529
+ if verbose:
530
+ params = {k: v for k, v in action.model_dump().items() if k != "action_type" and v is not None}
531
+ log_step(task_id, ticks, action.action_type.value, params, rewards[-1], obs.done, obs.last_action_error)
532
+ ticks += 1
533
+ score = float(env.get_score())
534
+ if verbose:
535
+ log_end(task_id, clamp_submission_score(score), ticks, rewards)
536
+ record = {"task_id": task_id, "task_name": TASK_NAMES[task_id], "seed": seed, "score": round(score, 6),
537
+ "steps": ticks, "total_reward": round(sum(rewards), 6), "timed_out": timed_out,
538
+ "seconds": round(time.time() - started, 2)}
539
+ if hasattr(policy, "stats"):
540
+ record["policy_stats"] = policy.stats()
541
+ return record
542
+
543
+
544
+ def main(argv: Optional[List[str]] = None) -> int:
545
+ parser = argparse.ArgumentParser(description="Run an LLM operator on NexusGrid")
546
+ parser.add_argument("--tasks", default="0,1,2,3,4,5")
547
+ parser.add_argument("--seeds", default=str(EPISODE_SEED), help="comma-separated seeds, e.g. 10000,10001")
548
+ parser.add_argument("--model", default=MODEL_NAME)
549
+ parser.add_argument("--api-base", default=API_BASE_URL)
550
+ parser.add_argument("--temperature", type=float, default=0.0)
551
+ parser.add_argument("--fallback", action="store_true", help="use the expert action when the output is invalid")
552
+ parser.add_argument("--out", default="scores.json")
553
+ args = parser.parse_args(argv)
554
+
555
+ if _env_flag_is_true(os.getenv("USE_REMOTE_ENV")):
556
+ env = RemoteEnvAdapter(os.getenv("ENV_URL", "http://localhost:8000"))
557
+ else:
558
  from server.nexusgrid_environment import NexusgridEnvironment
559
  env = NexusgridEnvironment()
560
+ policy = LLMPolicy(model=args.model, api_base=args.api_base, temperature=args.temperature,
561
+ fallback=args.fallback)
562
+ tasks = [int(t) for t in args.tasks.split(",")]
563
+ seeds = [int(s) for s in args.seeds.split(",")]
564
+ records = []
565
+ started = time.time()
566
+ for task_id in tasks:
567
+ for seed in seeds:
568
+ try:
569
+ records.append(run_task(policy, env, task_id, seed))
570
+ except Exception as exc: # keep going: one failing task must not abort the run
571
+ print(f"[DEBUG] task {task_id} seed {seed} failed: {exc}", flush=True)
572
+ log_end(task_id, clamp_submission_score(0.0), 0, [])
573
+ records.append({"task_id": task_id, "seed": seed, "score": 0.0, "error": str(exc)})
574
+ by_task: Dict[int, List[float]] = {}
575
+ for r in records:
576
+ by_task.setdefault(r["task_id"], []).append(r["score"])
577
+ summary = {
578
+ "model": args.model,
579
+ "api_base": args.api_base,
580
+ "fallback": args.fallback,
581
+ "seeds": seeds,
582
+ "scores": {str(t): round(sum(v) / len(v), 4) for t, v in by_task.items()},
583
+ "average": round(sum(r["score"] for r in records) / max(1, len(records)), 4),
584
+ "policy_stats": policy.stats(),
585
+ "episodes": records,
586
+ "total_time_seconds": round(time.time() - started, 1),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
587
  }
588
+ with open(args.out, "w", encoding="utf-8") as f:
589
+ json.dump(summary, f, indent=2)
590
+ print(f"\nAverage score {summary['average']:.3f} over {len(records)} episodes "
591
+ f"(invalid outputs {policy.stats()['invalid_outputs']}, fallbacks {policy.stats()['fallbacks']}) "
592
+ f"-> {args.out}", flush=True)
593
+ return 0
594
 
595
 
596
  if __name__ == "__main__":
597
+ raise SystemExit(main())
models.py CHANGED
@@ -32,6 +32,7 @@ class EdgeStatus(str, Enum):
32
 
33
  class ActionType(str, Enum):
34
  DISPATCH_GENERATION = "dispatch_generation"
 
35
  TOGGLE_CIRCUIT_BREAKER = "toggle_circuit_breaker"
36
  RUN_STATE_ESTIMATION = "run_state_estimation"
37
  QUARANTINE_SCADA_NODE = "quarantine_scada_node"
@@ -69,12 +70,15 @@ class GridEdge(BaseModel):
69
  # ---------------------------------------------------------------------------
70
 
71
  class NodeTelemetry(BaseModel):
72
- """Per-node telemetry reading (may be spoofed)."""
73
  node_id: str = Field(..., description="Node this reading belongs to")
74
- voltage_kv: float = Field(345.0, ge=0.0, le=765.0, description="Voltage in kV (nominal 345)")
75
- frequency_hz: float = Field(60.0, ge=58.0, le=62.0, description="Local frequency in Hz (nominal 60)")
 
76
  generation_mw: float = Field(0.0, ge=0.0, le=5000.0, description="Generation output in MW")
77
- consumption_mw: float = Field(0.0, ge=0.0, le=5000.0, description="Consumption demand in MW")
 
 
78
 
79
 
80
  class WeatherZone(BaseModel):
@@ -148,9 +152,30 @@ class GridObservation(BaseModel):
148
  description="Result of most recent run_state_estimation call"
149
  )
150
  weather_summary: str = Field("", description="Natural language weather summary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  metadata: Dict[str, Any] = Field(
152
  default_factory=dict,
153
- description="Auxiliary environment metadata such as reward/rubric breakdowns."
154
  )
155
 
156
 
@@ -171,7 +196,7 @@ class GridAction(BaseModel):
171
  )
172
  node_id: Optional[str] = Field(
173
  None,
174
- description="Target node ID (for dispatch_generation, quarantine_scada_node, inject_counter_signal)"
175
  )
176
  edge_id: Optional[str] = Field(
177
  None,
@@ -179,7 +204,7 @@ class GridAction(BaseModel):
179
  )
180
  mw: Optional[float] = Field(
181
  None, ge=-5000, le=5000,
182
- description="Megawatts to dispatch (for dispatch_generation)"
183
  )
184
  status: Optional[str] = Field(
185
  None,
@@ -204,15 +229,13 @@ class GridAction(BaseModel):
204
  # ---------------------------------------------------------------------------
205
 
206
  class GridReward(BaseModel):
207
- """Breakdown of reward signals for transparency."""
208
- fault_isolation: float = Field(0.0, description="Reward for isolating transmission faults")
209
- cyber_detection: float = Field(0.0, description="Reward for detecting spoofed sensors")
210
- frequency_stable: float = Field(0.0, description="Reward for keeping frequency in nominal band")
211
- proactive_dispatch: float = Field(0.0, description="Reward for proactive (early) dispatch")
212
- reasoning_order: float = Field(0.0, description="Reward for correct investigation order")
213
- stability_bonus: float = Field(0.0, description="Bonus for tight frequency control (±0.1Hz)")
214
- penalties: float = Field(0.0, description="Sum of all penalties (negative value)")
215
- total: float = Field(0.0, description="Total reward for this tick")
216
 
217
 
218
  # ---------------------------------------------------------------------------
@@ -228,7 +251,7 @@ class GridState(BaseModel):
228
  grid_frequency_hz: float = Field(60.0, ge=58.0, le=62.0, description="Current grid frequency")
229
  done: bool = Field(False, description="Whether episode is finished")
230
  total_reward: float = Field(0.0, description="Accumulated reward")
231
- active_spoofs: List[str] = Field(default_factory=list, description="Currently spoofed node IDs")
232
  quarantined_nodes: List[str] = Field(default_factory=list, description="Quarantined node IDs")
233
  state_estimation_run: bool = Field(False, description="Whether state estimation has been run this episode")
234
  action_history: List[Dict[str, Any]] = Field(default_factory=list, description="History of all actions taken")
 
32
 
33
  class ActionType(str, Enum):
34
  DISPATCH_GENERATION = "dispatch_generation"
35
+ SHED_LOAD = "shed_load"
36
  TOGGLE_CIRCUIT_BREAKER = "toggle_circuit_breaker"
37
  RUN_STATE_ESTIMATION = "run_state_estimation"
38
  QUARANTINE_SCADA_NODE = "quarantine_scada_node"
 
70
  # ---------------------------------------------------------------------------
71
 
72
  class NodeTelemetry(BaseModel):
73
+ """Per-node SCADA/PMU reading (generation may be falsified by an attacker)."""
74
  node_id: str = Field(..., description="Node this reading belongs to")
75
+ voltage_kv: float = Field(345.0, ge=0.0, le=765.0, description="Voltage in kV (nominal 345, 0 when dark)")
76
+ frequency_hz: float = Field(60.0, ge=0.0, le=62.0, description="Local frequency in Hz (nominal 60, 0 when dark)")
77
+ phase_angle_deg: float = Field(0.0, ge=-180.0, le=180.0, description="PMU: voltage phase angle relative to the island reference")
78
  generation_mw: float = Field(0.0, ge=0.0, le=5000.0, description="Generation output in MW")
79
+ consumption_mw: float = Field(0.0, ge=0.0, le=5000.0, description="Consumption in MW")
80
+ oscillation_hz: float = Field(0.0, ge=0.0, le=5.0, description="PMU: dominant oscillation mode at this bus (0 if none)")
81
+ oscillation_amplitude_hz: float = Field(0.0, ge=0.0, le=5.0, description="PMU: oscillation amplitude at this bus")
82
 
83
 
84
  class WeatherZone(BaseModel):
 
152
  description="Result of most recent run_state_estimation call"
153
  )
154
  weather_summary: str = Field("", description="Natural language weather summary")
155
+ task_brief: str = Field("", description="Operator briefing for the current scenario")
156
+ max_ticks: int = Field(0, ge=0, description="Episode horizon in ticks")
157
+ forecast: Dict[str, List[float]] = Field(
158
+ default_factory=dict,
159
+ description="Forecasts for the next ticks: system_demand_mw and solar_available_mw"
160
+ )
161
+ islands: List[Dict[str, Any]] = Field(
162
+ default_factory=list,
163
+ description="Energised electrical islands with their frequency, generation and load"
164
+ )
165
+ events: List[Dict[str, Any]] = Field(
166
+ default_factory=list,
167
+ description="Grid events during the last tick (relay trips, UFLS, collapses, attack outcomes)"
168
+ )
169
+ active_counter_signals: List[Dict[str, Any]] = Field(
170
+ default_factory=list,
171
+ description="Damping counter-signals currently injected by batteries"
172
+ )
173
+ score: float = Field(0.0, ge=0.0, le=1.0, description="Task score so far (final grade once done)")
174
+ rubric_scores: Dict[str, float] = Field(default_factory=dict, description="Per-rubric scores in [0, 1]")
175
+ reward_breakdown: Dict[str, float] = Field(default_factory=dict, description="Components of the last reward")
176
  metadata: Dict[str, Any] = Field(
177
  default_factory=dict,
178
+ description="In-process extras (episode summary, rubric details). Not sent over HTTP/WebSocket."
179
  )
180
 
181
 
 
196
  )
197
  node_id: Optional[str] = Field(
198
  None,
199
+ description="Target node ID (dispatch_generation, shed_load, quarantine_scada_node, inject_counter_signal)"
200
  )
201
  edge_id: Optional[str] = Field(
202
  None,
 
204
  )
205
  mw: Optional[float] = Field(
206
  None, ge=-5000, le=5000,
207
+ description="Setpoint change in MW (dispatch_generation) or MW to shed, negative to restore (shed_load)"
208
  )
209
  status: Optional[str] = Field(
210
  None,
 
229
  # ---------------------------------------------------------------------------
230
 
231
  class GridReward(BaseModel):
232
+ """Breakdown of the per-step reward (see server/reward.py)."""
233
+ progress: float = Field(0.0, description="Change in task score this step (sums to the final score)")
234
+ frequency_band: float = Field(0.0, description="+0.02 while frequency is inside 59.8-60.2 Hz")
235
+ overload: float = Field(0.0, description="-0.02 per line above its thermal rating")
236
+ events: float = Field(0.0, description="Penalties for relay trips, UFLS, collapses and similar events")
237
+ invalid_action: float = Field(0.0, description="-0.05 for a malformed or rejected action")
238
+ total: float = Field(0.0, description="Total reward for this step")
 
 
239
 
240
 
241
  # ---------------------------------------------------------------------------
 
251
  grid_frequency_hz: float = Field(60.0, ge=58.0, le=62.0, description="Current grid frequency")
252
  done: bool = Field(False, description="Whether episode is finished")
253
  total_reward: float = Field(0.0, description="Accumulated reward")
254
+ active_spoofs: List[str] = Field(default_factory=list, description="Debug only: spoofed node IDs (never shown to agents)")
255
  quarantined_nodes: List[str] = Field(default_factory=list, description="Quarantined node IDs")
256
  state_estimation_run: bool = Field(False, description="Whether state estimation has been run this episode")
257
  action_history: List[Dict[str, Any]] = Field(default_factory=list, description="History of all actions taken")
policies.py ADDED
@@ -0,0 +1,683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Baseline policies for NexusGrid.
3
+
4
+ Every policy acts from the observation alone (no access to hidden simulator
5
+ state), so the same code can drive a local environment or a remote server.
6
+
7
+ * :class:`NoopPolicy` - always ``advance_tick``; the do-nothing baseline.
8
+ * :class:`RandomPolicy` - a random action type with random arguments.
9
+ * :class:`ExpertPolicy` - a hand-written operator: forecast-aware frequency
10
+ control, DC power-flow checks before every redispatch or switching action,
11
+ evidence-first incident response, oscillation damping and staged
12
+ black-start restoration.
13
+
14
+ The expert is a reference point for what the scenarios demand, not an upper
15
+ bound: it only uses information that is in the observation.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import random
21
+ from dataclasses import dataclass, field
22
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple
23
+
24
+ import numpy as np
25
+
26
+ try:
27
+ from models import ActionType, GridAction
28
+ except ImportError: # pragma: no cover - package-relative import
29
+ from .models import ActionType, GridAction
30
+
31
+ DISPATCHABLE = ("hydro", "gas", "battery")
32
+ GENERATORS = ("hydro", "solar", "gas", "battery")
33
+ ACTION_TYPES = [a.value for a in ActionType]
34
+
35
+
36
+ # ---------------------------------------------------------------------------
37
+ # Observation helpers
38
+ # ---------------------------------------------------------------------------
39
+
40
+ def observation_dict(obs: Any) -> Dict[str, Any]:
41
+ if hasattr(obs, "model_dump"):
42
+ return obs.model_dump()
43
+ return dict(obs)
44
+
45
+
46
+ class GridView:
47
+ """Convenient read-only view of one observation."""
48
+
49
+ def __init__(self, obs: Any):
50
+ d = observation_dict(obs)
51
+ self.raw = d
52
+ topo = d.get("topology_graph") or {}
53
+ self.nodes: Dict[str, Dict[str, Any]] = {n["id"]: n for n in topo.get("nodes", [])}
54
+ self.edges: Dict[str, Dict[str, Any]] = {e["id"]: e for e in topo.get("edges", [])}
55
+ stream = d.get("telemetry_stream") or []
56
+ self.telemetry: Dict[str, Dict[str, Any]] = {r["node_id"]: r for r in (stream[-1] if stream else [])}
57
+ self.frequency = float(d.get("grid_frequency_hz", 60.0))
58
+ self.tick = int(d.get("tick", 0))
59
+ self.max_ticks = int(d.get("max_ticks", 0) or 0)
60
+ self.task_id = int(d.get("task_id", 0))
61
+ self.islands: List[Dict[str, Any]] = d.get("islands") or []
62
+ self.forecast: Dict[str, List[float]] = d.get("forecast") or {}
63
+ self.packets: List[Dict[str, Any]] = d.get("network_packet_logs") or []
64
+ self.last_se: Optional[Dict[str, Any]] = d.get("last_state_estimation")
65
+ self.counter_signals: List[Dict[str, Any]] = d.get("active_counter_signals") or []
66
+ self.island_of = {nid: isl["island"] for isl in self.islands for nid in isl["nodes"]}
67
+ self.adjacency: Dict[str, List[str]] = {nid: [] for nid in self.nodes}
68
+ for e in self.edges.values():
69
+ if e["status"] == "LIVE":
70
+ self.adjacency[e["source"]].append(e["target"])
71
+ self.adjacency[e["target"]].append(e["source"])
72
+
73
+ def main_island(self) -> Optional[Dict[str, Any]]:
74
+ if not self.islands:
75
+ return None
76
+ return max(self.islands, key=lambda isl: (isl["load_mw"], isl["generation_mw"], len(isl["nodes"])))
77
+
78
+ def stiffness(self, island: Dict[str, Any], extra_capacity: float = 0.0) -> float:
79
+ cap = sum(self.nodes[n]["capacity_mw"] for n in island["nodes"]
80
+ if self.nodes[n]["node_type"] in DISPATCHABLE and not self.nodes[n].get("tripped"))
81
+ return max(50.0, 0.25 * (cap + extra_capacity))
82
+
83
+ def hop_distance(self, a: str, b: str) -> int:
84
+ if a == b:
85
+ return 0
86
+ seen, frontier, dist = {a}, [a], 0
87
+ while frontier:
88
+ dist += 1
89
+ nxt = []
90
+ for cur in frontier:
91
+ for nb in self.adjacency.get(cur, []):
92
+ if nb == b:
93
+ return dist
94
+ if nb not in seen:
95
+ seen.add(nb)
96
+ nxt.append(nb)
97
+ frontier = nxt
98
+ return 99
99
+
100
+ def dispatchable_units(self, island_nodes: Iterable[str], exclude: Set[str] = frozenset()) -> List[str]:
101
+ units = []
102
+ for nid in island_nodes:
103
+ n = self.nodes[nid]
104
+ if (n["node_type"] in DISPATCHABLE and n.get("energized") and not n.get("tripped")
105
+ and not n.get("quarantined") and nid not in exclude and n["capacity_mw"] > 0):
106
+ units.append(nid)
107
+ return units
108
+
109
+ def latest_packets(self) -> List[Dict[str, Any]]:
110
+ if not self.packets:
111
+ return []
112
+ last = max(int(p["timestamp"]) // 300 for p in self.packets)
113
+ return [p for p in self.packets if int(p["timestamp"]) // 300 == last]
114
+
115
+ def served_mw(self, node_id: str) -> float:
116
+ return float(self.telemetry.get(node_id, {}).get("consumption_mw", 0.0))
117
+
118
+
119
+ def _reactance(edge: Dict[str, Any]) -> float:
120
+ x = edge.get("reactance_pu")
121
+ if not x:
122
+ x = 0.02 * 800.0 / max(float(edge["capacity_mw"]), 1.0)
123
+ return max(float(x), 1e-6)
124
+
125
+
126
+ def dc_flows(nodes: Sequence[str], edges: Sequence[Dict[str, Any]], injections: Dict[str, float]) -> Dict[str, float]:
127
+ """Solve a DC power flow on a connected set of buses; returns MW per edge (source -> target)."""
128
+ if len(nodes) < 2 or not edges:
129
+ return {e["id"]: 0.0 for e in edges}
130
+ index = {nid: i for i, nid in enumerate(nodes)}
131
+ size = len(nodes)
132
+ B = np.zeros((size, size))
133
+ for e in edges:
134
+ i, j = index[e["source"]], index[e["target"]]
135
+ b = 1.0 / _reactance(e)
136
+ B[i, i] += b
137
+ B[j, j] += b
138
+ B[i, j] -= b
139
+ B[j, i] -= b
140
+ P = np.array([injections.get(nid, 0.0) for nid in nodes], dtype=float)
141
+ P -= P.sum() / size
142
+ theta = np.zeros(size)
143
+ try:
144
+ theta[1:] = np.linalg.solve(B[1:, 1:], P[1:])
145
+ except np.linalg.LinAlgError:
146
+ theta[1:] = np.linalg.lstsq(B[1:, 1:], P[1:], rcond=None)[0]
147
+ return {e["id"]: float((theta[index[e["source"]]] - theta[index[e["target"]]]) / _reactance(e)) for e in edges}
148
+
149
+
150
+ class FlowModel:
151
+ """
152
+ DC power-flow predictor for one island, rebuilt from the observed topology.
153
+
154
+ Net bus injections are recovered from the metered line flows, so predictions
155
+ use only what the operator can see. Governors redistribute any imbalance in
156
+ proportion to the capacity of responsive units, as the simulator does.
157
+ """
158
+
159
+ def __init__(self, view: GridView, island_nodes: Iterable[str]):
160
+ self.view = view
161
+ self.nodes = list(island_nodes)
162
+ members = set(self.nodes)
163
+ self.edges = [e for e in view.edges.values()
164
+ if e["status"] == "LIVE" and e["source"] in members and e["target"] in members]
165
+ self.p0 = {nid: 0.0 for nid in self.nodes}
166
+ for e in self.edges:
167
+ self.p0[e["source"]] += e["flow_mw"]
168
+ self.p0[e["target"]] -= e["flow_mw"]
169
+ self.flows = {e["id"]: float(e["flow_mw"]) for e in self.edges}
170
+
171
+ def _weights(self, nodes: Iterable[str], imbalance: float) -> Dict[str, float]:
172
+ """Governor participation: units that can still move in the required direction, by capacity."""
173
+ weights = {}
174
+ for nid in nodes:
175
+ n = self.view.nodes[nid]
176
+ if n["node_type"] not in DISPATCHABLE or n.get("tripped") or n["capacity_mw"] <= 0:
177
+ continue
178
+ if not n.get("energized", True) and nid in self.p0:
179
+ continue
180
+ output = float(self.view.telemetry.get(nid, {}).get("generation_mw", n.get("setpoint_mw", 0.0)))
181
+ if imbalance > 0 and output <= 1.0 and nid in self.p0:
182
+ continue # surplus: units already at zero cannot back down further
183
+ if imbalance < 0:
184
+ if n["node_type"] == "battery" and n.get("soc_pct", 100.0) <= 0.5:
185
+ continue
186
+ if n["capacity_mw"] - output <= 1.0:
187
+ continue # deficit: units at their limit cannot pick up more
188
+ weights[nid] = float(n["capacity_mw"])
189
+ total = sum(weights.values()) or 1.0
190
+ return {k: v / total for k, v in weights.items()}
191
+
192
+ def predict(self, deltas: Optional[Dict[str, float]] = None, close: Sequence[str] = (),
193
+ new_buses: Optional[Dict[str, float]] = None) -> Dict[str, float]:
194
+ """Flows after setpoint changes, line closures and newly energised buses (MW injections)."""
195
+ deltas = deltas or {}
196
+ new_buses = new_buses or {}
197
+ nodes = self.nodes + [b for b in new_buses if b not in self.p0]
198
+ edges = self.edges + [self.view.edges[eid] for eid in close]
199
+ injections = dict(self.p0)
200
+ imbalance = 0.0
201
+ for nid, mw in list(deltas.items()) + list(new_buses.items()):
202
+ injections[nid] = injections.get(nid, 0.0) + mw
203
+ imbalance += mw
204
+ weights = self._weights(nodes, imbalance)
205
+ for nid, w in weights.items():
206
+ injections[nid] = injections.get(nid, 0.0) - imbalance * w
207
+ if not deltas and not new_buses and not close:
208
+ return dict(self.flows)
209
+ return dc_flows(nodes, edges, injections)
210
+
211
+ def loading(self, flows: Dict[str, float]) -> Dict[str, float]:
212
+ return {eid: abs(f) / max(float(self.view.edges[eid]["capacity_mw"]), 1.0) for eid, f in flows.items()}
213
+
214
+ def max_loading(self, flows: Optional[Dict[str, float]] = None) -> float:
215
+ loads = self.loading(self.flows if flows is None else flows)
216
+ return max(loads.values()) if loads else 0.0
217
+
218
+ def overload_mw(self, flows: Dict[str, float], margin: float = 0.97) -> float:
219
+ total = 0.0
220
+ for eid, f in flows.items():
221
+ cap = float(self.view.edges[eid]["capacity_mw"])
222
+ total += max(0.0, abs(f) - margin * cap)
223
+ return total
224
+
225
+
226
+ def advance() -> GridAction:
227
+ return GridAction(action_type=ActionType.ADVANCE_TICK)
228
+
229
+
230
+ def dispatch(node_id: str, mw: float) -> GridAction:
231
+ return GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id=node_id, mw=round(float(mw), 1))
232
+
233
+
234
+ def shed(node_id: str, mw: float) -> GridAction:
235
+ return GridAction(action_type=ActionType.SHED_LOAD, node_id=node_id, mw=round(float(mw), 1))
236
+
237
+
238
+ def close_line(edge_id: str) -> GridAction:
239
+ return GridAction(action_type=ActionType.TOGGLE_CIRCUIT_BREAKER, edge_id=edge_id, status="CLOSED")
240
+
241
+
242
+ # ---------------------------------------------------------------------------
243
+ # Simple baselines
244
+ # ---------------------------------------------------------------------------
245
+
246
+ class NoopPolicy:
247
+ """Always advances time without acting."""
248
+
249
+ name = "noop"
250
+
251
+ def reset(self, seed: Optional[int] = None) -> None:
252
+ return None
253
+
254
+ def act(self, obs: Any) -> GridAction:
255
+ return advance()
256
+
257
+
258
+ class RandomPolicy:
259
+ """Uniformly random action types with random (but well-formed) arguments."""
260
+
261
+ name = "random"
262
+
263
+ def __init__(self, seed: int = 0):
264
+ self._rng = random.Random(seed)
265
+
266
+ def reset(self, seed: Optional[int] = None) -> None:
267
+ if seed is not None:
268
+ self._rng = random.Random(seed)
269
+
270
+ def act(self, obs: Any) -> GridAction:
271
+ view = GridView(obs)
272
+ rng = self._rng
273
+ nodes = sorted(view.nodes) or ["NODE_01"]
274
+ edges = sorted(view.edges) or ["LINE_01"]
275
+ kind = rng.choice(ACTION_TYPES)
276
+ if kind == "dispatch_generation":
277
+ return dispatch(rng.choice(nodes), rng.uniform(-300.0, 300.0))
278
+ if kind == "shed_load":
279
+ return shed(rng.choice(nodes), rng.uniform(-100.0, 200.0))
280
+ if kind == "toggle_circuit_breaker":
281
+ return GridAction(action_type=ActionType.TOGGLE_CIRCUIT_BREAKER, edge_id=rng.choice(edges),
282
+ status=rng.choice(["OPEN", "CLOSED"]))
283
+ if kind == "run_state_estimation":
284
+ return GridAction(action_type=ActionType.RUN_STATE_ESTIMATION,
285
+ subgraph=rng.sample(nodes, k=rng.randint(1, min(6, len(nodes)))))
286
+ if kind == "quarantine_scada_node":
287
+ return GridAction(action_type=ActionType.QUARANTINE_SCADA_NODE, node_id=rng.choice(nodes))
288
+ if kind == "inject_counter_signal":
289
+ return GridAction(action_type=ActionType.INJECT_COUNTER_SIGNAL, node_id=rng.choice(nodes),
290
+ hz_offset=round(rng.uniform(-1.0, 1.0), 2), duration=rng.randint(1, 6))
291
+ return advance()
292
+
293
+
294
+ # ---------------------------------------------------------------------------
295
+ # Expert policy
296
+ # ---------------------------------------------------------------------------
297
+
298
+ @dataclass
299
+ class _Candidate:
300
+ action: GridAction
301
+ deltas: Dict[str, float] = field(default_factory=dict) # setpoint-side injection change per bus
302
+ mismatch_delta: float = 0.0 # change of island setpoint mismatch
303
+ shed_delta: float = 0.0 # change of manually shed MW
304
+ cost: float = 0.0 # preference cost
305
+ close: Tuple[str, ...] = () # lines closed by the action
306
+
307
+
308
+ class ExpertPolicy:
309
+ """
310
+ Observation-only reference operator.
311
+
312
+ Frequency control works like an operator running AGC with the published
313
+ forecasts: it drives the island's setpoint mismatch (generation setpoints
314
+ minus demand) to zero for the next tick. Every candidate action is checked
315
+ with a DC power flow so redispatch and switching never create overloads.
316
+ """
317
+
318
+ name = "expert"
319
+
320
+ ACTION_COST = 3.0
321
+ OVERLOAD_WEIGHT = 10.0
322
+ FREQUENCY_WEIGHT = 500.0 # per Hz of predicted deviation
323
+ SHED_WEIGHT = 2.0 # per MW of manually shed load
324
+ BATTERY_COST = 0.05 # per MW: keep batteries for fast or emergency support
325
+
326
+ def __init__(self) -> None:
327
+ self.reset()
328
+
329
+ def reset(self, seed: Optional[int] = None) -> None:
330
+ self._task: Optional[int] = None
331
+ self._prev_demand_forecast: Optional[float] = None
332
+ self._prev_solar_forecast: Optional[float] = None
333
+ self._initial_setpoints: Dict[str, float] = {}
334
+ self._se_calls = 0
335
+ self._cleared: Dict[str, int] = {}
336
+ self._dispatched_once = False
337
+
338
+ def act(self, obs: Any) -> GridAction:
339
+ view = GridView(obs)
340
+ if self._task != view.task_id or view.tick == 0:
341
+ self.reset()
342
+ self._task = view.task_id
343
+ self._initial_setpoints = {nid: float(n.get("setpoint_mw", 0.0)) for nid, n in view.nodes.items()}
344
+ handlers = {
345
+ 0: self._smoke_test,
346
+ 1: self._operate,
347
+ 2: self._operate,
348
+ 3: self._phantom,
349
+ 4: self._resonance,
350
+ 5: self._black_start,
351
+ }
352
+ action = handlers.get(view.task_id, self._operate)(view)
353
+ demand = view.forecast.get("system_demand_mw") or []
354
+ solar = view.forecast.get("solar_available_mw") or []
355
+ self._prev_demand_forecast = float(demand[0]) if demand else None
356
+ self._prev_solar_forecast = float(solar[0]) if solar else None
357
+ return action
358
+
359
+ # ------------------------------------------------------------------
360
+ # Shared: forecast-aware, flow-checked frequency control
361
+ # ------------------------------------------------------------------
362
+
363
+ def _net_change_next_tick(self, view: GridView) -> float:
364
+ """Expected change of the setpoint mismatch at the next tick from the forecasts."""
365
+ demand = view.forecast.get("system_demand_mw") or []
366
+ solar = view.forecast.get("solar_available_mw") or []
367
+ change = 0.0
368
+ if demand:
369
+ if self._prev_demand_forecast is not None:
370
+ now = self._prev_demand_forecast
371
+ else:
372
+ now = sum(view.served_mw(nid) + n.get("shed_mw", 0.0)
373
+ for nid, n in view.nodes.items() if n["node_type"] == "load" and n.get("energized"))
374
+ change -= float(demand[0]) - now
375
+ if solar:
376
+ if self._prev_solar_forecast is not None:
377
+ now = self._prev_solar_forecast
378
+ else:
379
+ now = sum(view.telemetry.get(nid, {}).get("generation_mw", 0.0)
380
+ for nid, n in view.nodes.items() if n["node_type"] == "solar")
381
+ change += float(solar[0]) - now
382
+ return change
383
+
384
+ def _operate(self, view: GridView, exclude: Set[str] = frozenset(), island: Optional[Dict[str, Any]] = None,
385
+ allow_shed: bool = True, include_forecast: bool = True,
386
+ extra: Optional[List[_Candidate]] = None) -> GridAction:
387
+ island = island or view.main_island()
388
+ if island is None:
389
+ return advance()
390
+ nodes = island["nodes"]
391
+ model = FlowModel(view, nodes)
392
+ stiffness = view.stiffness(island)
393
+ mismatch_next = float(island.get("setpoint_mismatch_mw", 0.0))
394
+ if include_forecast:
395
+ mismatch_next += self._net_change_next_tick(view)
396
+ loads = [nid for nid in nodes if view.nodes[nid]["node_type"] == "load"]
397
+ shed_total = sum(view.nodes[nid].get("shed_mw", 0.0) for nid in loads)
398
+
399
+ candidates = [_Candidate(advance())]
400
+ for unit in view.dispatchable_units(nodes, exclude):
401
+ n = view.nodes[unit]
402
+ ramp = float(n.get("ramp_mw_per_tick") or n["capacity_mw"])
403
+ setpoint = float(n.get("setpoint_mw", 0.0))
404
+ up = max(0.0, min(ramp, n["capacity_mw"] - setpoint))
405
+ down = max(0.0, min(ramp, setpoint))
406
+ if n["node_type"] == "battery" and n.get("soc_pct", 0.0) < 20.0:
407
+ up = 0.0
408
+ amounts = {round(min(up, max(-down, -mismatch_next)), 1)}
409
+ for frac in (1.0, 0.5, 0.25):
410
+ amounts.add(round(up * frac, 1))
411
+ amounts.add(round(-down * frac, 1))
412
+ for mw in amounts:
413
+ if abs(mw) < 1.0:
414
+ continue
415
+ cost = self.ACTION_COST + (self.BATTERY_COST * abs(mw) if n["node_type"] == "battery" else 0.0)
416
+ candidates.append(_Candidate(dispatch(unit, mw), {unit: mw}, mw, 0.0, cost))
417
+
418
+ overloaded = model.overload_mw(model.flows, margin=1.0) > 0.0
419
+ if allow_shed:
420
+ for nid in loads:
421
+ n = view.nodes[nid]
422
+ served = view.served_mw(nid)
423
+ if overloaded and not n.get("critical") and served > 1.0:
424
+ for frac in (0.25, 0.5, 1.0):
425
+ mw = round(served * frac, 1)
426
+ candidates.append(_Candidate(shed(nid, mw), {nid: mw}, mw, mw, self.ACTION_COST))
427
+ ufls = n.get("ufls_shed_pct", 0.0) / 100.0
428
+ restorable = n.get("shed_mw", 0.0) + (served * ufls / max(1e-6, 1.0 - ufls))
429
+ if restorable > 1.0:
430
+ mw = round(restorable, 1)
431
+ candidates.append(_Candidate(shed(nid, -mw), {nid: -mw}, -mw,
432
+ -min(mw, n.get("shed_mw", 0.0)), self.ACTION_COST - 2.0))
433
+ if extra:
434
+ candidates.extend(extra)
435
+
436
+ def objective(c: _Candidate) -> float:
437
+ flows = model.predict(c.deltas, close=c.close) if (c.deltas or c.close) else model.flows
438
+ freq_dev = abs(mismatch_next + c.mismatch_delta) / stiffness
439
+ return (self.OVERLOAD_WEIGHT * model.overload_mw(flows) + self.FREQUENCY_WEIGHT * freq_dev
440
+ + self.SHED_WEIGHT * (shed_total + c.shed_delta) + c.cost)
441
+
442
+ return min(candidates, key=objective).action
443
+
444
+ # ------------------------------------------------------------------
445
+ # Task 0
446
+ # ------------------------------------------------------------------
447
+
448
+ def _smoke_test(self, view: GridView) -> GridAction:
449
+ if not self._dispatched_once:
450
+ island = view.main_island()
451
+ if island:
452
+ units = [u for u in view.dispatchable_units(island["nodes"]) if view.nodes[u]["node_type"] != "battery"]
453
+ if units:
454
+ unit = max(units, key=lambda u: view.nodes[u]["capacity_mw"] - view.nodes[u].get("setpoint_mw", 0.0))
455
+ self._dispatched_once = True
456
+ return dispatch(unit, 40.0)
457
+ return self._operate(view)
458
+
459
+ # ------------------------------------------------------------------
460
+ # Task 3: false data injection
461
+ # ------------------------------------------------------------------
462
+
463
+ def _phantom(self, view: GridView) -> GridAction:
464
+ quarantined = {nid for nid, n in view.nodes.items() if n.get("quarantined")}
465
+ se = view.last_se or {}
466
+ violation = se.get("violation_node")
467
+ if not se.get("consistent", True) and violation and violation not in quarantined:
468
+ return GridAction(action_type=ActionType.QUARANTINE_SCADA_NODE, node_id=violation)
469
+
470
+ flagged = [p["source_node"] for p in view.latest_packets() if p.get("anomaly_flag")]
471
+ suspects = [nid for nid in dict.fromkeys(flagged)
472
+ if nid not in quarantined and view.tick - self._cleared.get(nid, -99) > 3]
473
+ if suspects and self._se_calls < 8:
474
+ subgraph = suspects[:6]
475
+ for nid in suspects:
476
+ for nb in view.adjacency.get(nid, []):
477
+ if len(subgraph) >= 6:
478
+ break
479
+ if nb not in subgraph and view.nodes[nb]["node_type"] in ("hydro", "gas"):
480
+ subgraph.append(nb)
481
+ self._se_calls += 1
482
+ for nid in subgraph:
483
+ self._cleared[nid] = view.tick
484
+ return GridAction(action_type=ActionType.RUN_STATE_ESTIMATION, subgraph=subgraph)
485
+ return self._operate(view, exclude=set(flagged) | quarantined)
486
+
487
+ # ------------------------------------------------------------------
488
+ # Task 4: forced oscillation
489
+ # ------------------------------------------------------------------
490
+
491
+ def _resonance(self, view: GridView) -> GridAction:
492
+ osc = {nid: r.get("oscillation_amplitude_hz", 0.0) for nid, r in view.telemetry.items()
493
+ if r.get("oscillation_amplitude_hz", 0.0) > 0.0}
494
+ if not osc:
495
+ return self._operate(view)
496
+ source = max(osc, key=osc.get)
497
+ mode = float(view.telemetry[source].get("oscillation_hz", 0.0))
498
+ matched = any(abs(cs["hz_offset"] + mode) <= 0.05 and cs.get("remaining_ticks", 0) >= 1
499
+ and view.hop_distance(cs["node_id"], source) <= 2 for cs in view.counter_signals)
500
+ if not matched and osc[source] >= 0.02:
501
+ batteries = [nid for nid, n in view.nodes.items()
502
+ if n["node_type"] == "battery" and n.get("energized") and n.get("soc_pct", 0.0) > 5.0
503
+ and view.hop_distance(nid, source) <= 2]
504
+ if batteries:
505
+ battery = min(batteries, key=lambda b: (view.hop_distance(b, source), -view.nodes[b]["capacity_mw"]))
506
+ return GridAction(action_type=ActionType.INJECT_COUNTER_SIGNAL, node_id=battery,
507
+ hz_offset=round(-mode, 3), duration=4)
508
+ node = view.nodes[source]
509
+ initial = self._initial_setpoints.get(source, float(node.get("setpoint_mw", 0.0)))
510
+ if node["node_type"] in ("hydro", "gas") and initial > 0 and node.get("setpoint_mw", 0.0) > 0.78 * initial:
511
+ ramp = float(node.get("ramp_mw_per_tick") or node["capacity_mw"])
512
+ return dispatch(source, -min(ramp, node["setpoint_mw"] - 0.75 * initial))
513
+ return self._operate(view, exclude={source})
514
+
515
+ # ------------------------------------------------------------------
516
+ # Task 5: black start
517
+ # ------------------------------------------------------------------
518
+
519
+ def _black_start(self, view: GridView) -> GridAction:
520
+ if not view.islands:
521
+ return advance()
522
+ anchors = [isl for isl in view.islands if any(view.nodes[n].get("black_start_capable") for n in isl["nodes"])]
523
+ island = max(anchors or view.islands, key=lambda isl: len(isl["nodes"]))
524
+ members = set(island["nodes"])
525
+ model = FlowModel(view, island["nodes"])
526
+ stiffness = view.stiffness(island)
527
+ mismatch = float(island.get("setpoint_mismatch_mw", 0.0))
528
+ freq = float(island.get("frequency_hz", 60.0))
529
+ target_hz = 60.0 + mismatch / stiffness
530
+
531
+ total_peak = sum(n.get("peak_load_mw", 0.0) for n in view.nodes.values() if n["node_type"] == "load")
532
+ demand_fc = view.forecast.get("system_demand_mw") or []
533
+ load_factor = (float(demand_fc[0]) / total_peak) if demand_fc and total_peak else 0.75
534
+
535
+ frontier: List[Tuple[str, str]] = []
536
+ mesh: List[str] = []
537
+ merges: List[Tuple[str, str, str]] = []
538
+ for e in view.edges.values():
539
+ if e["status"] == "LIVE" or e.get("out_of_service"):
540
+ continue
541
+ a, b = e["source"], e["target"]
542
+ a_in, b_in = a in members, b in members
543
+ if a_in and b_in:
544
+ mesh.append(e["id"])
545
+ elif a_in or b_in:
546
+ inside, outside = (a, b) if a_in else (b, a)
547
+ if not view.nodes[outside].get("energized"):
548
+ frontier.append((e["id"], outside))
549
+ else:
550
+ merges.append((e["id"], inside, outside))
551
+
552
+ mesh_candidates = [_Candidate(close_line(eid), close=(eid,), cost=self.ACTION_COST) for eid in mesh]
553
+
554
+ # 0. Relieve overloads first (redispatch or re-meshing, checked with a power flow).
555
+ if model.max_loading() > 0.95:
556
+ return self._operate(view, island=island, allow_shed=False, include_forecast=False, extra=mesh_candidates)
557
+
558
+ # 1. Frequency safety.
559
+ if target_hz < 59.75 or freq < 59.6 or target_hz > 60.45 or freq > 60.45:
560
+ pickup = self._pickup(view, model, frontier, mismatch, stiffness, load_factor, min_target=59.8)
561
+ if target_hz > 60.2 and pickup is not None:
562
+ return close_line(pickup[0])
563
+ return self._operate(view, island=island, allow_shed=False, include_forecast=False)
564
+
565
+ # 2. Energise adjacent dark generators: more stiffness and more units, no new load.
566
+ gens = [(eid, nid) for eid, nid in frontier if view.nodes[nid]["node_type"] in ("hydro", "gas")]
567
+ if gens:
568
+ return close_line(max(gens, key=lambda item: view.nodes[item[1]]["capacity_mw"])[0])
569
+
570
+ # 3. Pick up loads (critical first) once generation can carry them.
571
+ loads = [(eid, nid) for eid, nid in frontier if view.nodes[nid]["node_type"] == "load"]
572
+ loads.sort(key=lambda item: (not view.nodes[item[1]].get("critical", False),
573
+ -view.nodes[item[1]].get("peak_load_mw", 0.0)))
574
+ if loads:
575
+ pickup = self._pickup(view, model, loads, mismatch, stiffness, load_factor, min_target=59.7)
576
+ if pickup is not None:
577
+ return close_line(pickup[0])
578
+ eid, nid = loads[0]
579
+ demand = view.nodes[nid].get("peak_load_mw", 0.0) * load_factor * 1.04
580
+ room = 0.40 * stiffness - mismatch
581
+ if room > 20.0:
582
+ raise_action = self._raise_for_pickup(view, model, island, eid, nid, demand, min(room, demand - mismatch))
583
+ if raise_action is not None:
584
+ return raise_action
585
+ best_mesh = self._best_mesh(model, mesh, (eid,), {nid: -demand})
586
+ if best_mesh is not None:
587
+ return close_line(best_mesh)
588
+
589
+ # 4. Energise remaining buses (solar plants, batteries) that lead further into the dark grid.
590
+ rest = [(eid, nid) for eid, nid in frontier if view.nodes[nid]["node_type"] in ("solar", "battery")]
591
+ if rest:
592
+ return close_line(rest[0][0])
593
+
594
+ # 5. Merge other energised islands when synchronised.
595
+ for eid, inside, outside in merges:
596
+ if self._in_sync(view, inside, outside):
597
+ return close_line(eid)
598
+
599
+ # 6. Re-mesh the energised network when it lowers the peak loading.
600
+ best_mesh = self._best_mesh(model, mesh)
601
+ if best_mesh is not None and not loads:
602
+ return close_line(best_mesh)
603
+
604
+ # 7. Frequency control on the main island (also restores UFLS-shed load).
605
+ return self._operate(view, island=island, include_forecast=False)
606
+
607
+ def _pickup(self, view: GridView, model: FlowModel, loads: List[Tuple[str, str]], mismatch: float,
608
+ stiffness: float, load_factor: float, min_target: float) -> Optional[Tuple[str, str]]:
609
+ for eid, nid in loads:
610
+ if view.nodes[nid]["node_type"] != "load":
611
+ continue
612
+ demand = view.nodes[nid].get("peak_load_mw", 0.0) * load_factor * 1.04
613
+ if 60.0 + (mismatch - demand) / stiffness < min_target:
614
+ continue
615
+ flows = model.predict(close=(eid,), new_buses={nid: -demand})
616
+ if model.max_loading(flows) <= 0.90:
617
+ return eid, nid
618
+ return None
619
+
620
+ def _raise_for_pickup(self, view: GridView, model: FlowModel, island: Dict[str, Any], eid: str, nid: str,
621
+ demand: float, amount: float) -> Optional[GridAction]:
622
+ best, best_key = None, None
623
+ for unit in view.dispatchable_units(island["nodes"]):
624
+ n = view.nodes[unit]
625
+ if n["node_type"] not in ("hydro", "gas"):
626
+ continue
627
+ mw = min(float(n.get("ramp_mw_per_tick") or n["capacity_mw"]), n["capacity_mw"] - n.get("setpoint_mw", 0.0),
628
+ amount)
629
+ if mw < 10.0:
630
+ continue
631
+ flows = model.predict(deltas={unit: mw}, close=(eid,), new_buses={nid: -demand})
632
+ key = (round(model.max_loading(flows), 2), -mw)
633
+ if best_key is None or key < best_key:
634
+ best, best_key = dispatch(unit, mw), key
635
+ return best
636
+
637
+ def _best_mesh(self, model: FlowModel, mesh: List[str], close: Tuple[str, ...] = (),
638
+ new_buses: Optional[Dict[str, float]] = None) -> Optional[str]:
639
+ base = model.max_loading(model.predict(close=close, new_buses=new_buses)) if (close or new_buses) \
640
+ else model.max_loading()
641
+ best, best_loading = None, base - 0.02
642
+ for eid in mesh:
643
+ loading = model.max_loading(model.predict(close=close + (eid,), new_buses=new_buses))
644
+ if loading < best_loading and loading <= 0.95:
645
+ best, best_loading = eid, loading
646
+ return best
647
+
648
+ @staticmethod
649
+ def _in_sync(view: GridView, a: str, b: str) -> bool:
650
+ ta, tb = view.telemetry.get(a, {}), view.telemetry.get(b, {})
651
+ if not ta or not tb:
652
+ return False
653
+ delta_angle = abs(ta.get("phase_angle_deg", 0.0) - tb.get("phase_angle_deg", 0.0))
654
+ delta_angle = min(delta_angle, 360.0 - delta_angle)
655
+ return abs(ta.get("frequency_hz", 0.0) - tb.get("frequency_hz", 0.0)) <= 0.15 and delta_angle <= 15.0
656
+
657
+
658
+ POLICIES = {
659
+ "noop": NoopPolicy,
660
+ "random": RandomPolicy,
661
+ "expert": ExpertPolicy,
662
+ }
663
+
664
+
665
+ def make_policy(name: str, seed: int = 0):
666
+ """Create a baseline policy by name (``noop``, ``random`` or ``expert``)."""
667
+ if name == "random":
668
+ return RandomPolicy(seed)
669
+ if name not in POLICIES:
670
+ raise ValueError(f"Unknown policy {name!r}; choose from {sorted(POLICIES)}")
671
+ return POLICIES[name]()
672
+
673
+
674
+ __all__ = [
675
+ "ExpertPolicy",
676
+ "FlowModel",
677
+ "GridView",
678
+ "NoopPolicy",
679
+ "RandomPolicy",
680
+ "dc_flows",
681
+ "make_policy",
682
+ "observation_dict",
683
+ ]
pyproject.toml CHANGED
@@ -1,52 +1,51 @@
1
  [build-system]
2
- requires = ["setuptools>=45", "wheel"]
3
  build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "openenv-nexusgrid"
7
- version = "2.0.0"
8
- description = "NexusGrid-CyberPhysEnv: National power grid defense environment for OpenEnv"
 
 
 
9
  requires-python = ">=3.10"
10
  dependencies = [
11
- # Core OpenEnv runtime
12
- "openenv-core[core]>=0.2.2",
13
- # Physics simulation
14
- "numpy>=1.24.0",
15
- "networkx>=3.0",
16
- # API server
17
- "fastapi>=0.115.0",
18
- "uvicorn>=0.24.0",
19
- # Data models
20
- "pydantic>=2.0.0",
21
- # LLM client (for inference.py)
22
- "openai>=1.0.0",
23
- # Environment variable loading
24
- "python-dotenv>=1.0.0",
25
- # Dashboard for HF Spaces
26
- "gradio>=4.0.0",
27
- "plotly>=5.18.0",
28
  ]
29
 
30
  [project.optional-dependencies]
31
- dev = [
32
- "pytest>=8.0.0",
33
- "pytest-cov>=4.0.0",
34
- "pytest-asyncio>=0.23.0",
35
- "httpx>=0.27.0",
36
- ]
37
- dashboard = [
38
- "gradio>=4.0.0",
39
- "plotly>=5.18.0",
40
- ]
41
 
42
  [project.scripts]
43
- server = "server.app:main"
 
 
 
 
 
44
 
45
  [tool.setuptools]
46
- include-package-data = true
47
- packages = ["server"]
48
- py-modules = ["client", "inference", "models"]
 
 
49
 
50
  [tool.pytest.ini_options]
51
  testpaths = ["tests"]
52
  python_files = "test_*.py"
 
 
 
 
 
1
  [build-system]
2
+ requires = ["setuptools>=64", "wheel"]
3
  build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "openenv-nexusgrid"
7
+ version = "3.0.0"
8
+ description = "NexusGrid: a seeded power-grid operations benchmark (DC power flow, protection, cyber-physical attacks) for RL and LLM agents on OpenEnv"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ authors = [{ name = "Abinesh Senthilkumar" }]
12
  requires-python = ">=3.10"
13
  dependencies = [
14
+ "openenv-core[core]>=0.2.3,<0.4",
15
+ "numpy>=1.26,<3",
16
+ "pydantic>=2.7,<3",
17
+ "fastapi>=0.115",
18
+ "uvicorn>=0.30",
19
+ "openai>=1.40",
20
+ "python-dotenv>=1.0",
 
 
 
 
 
 
 
 
 
 
21
  ]
22
 
23
  [project.optional-dependencies]
24
+ dashboard = ["gradio>=5.30,<7", "plotly>=5.18"]
25
+ rl = ["torch>=2.3", "gymnasium>=0.29", "stable-baselines3>=2.3", "sb3-contrib>=2.3", "matplotlib>=3.8"]
26
+ grpo = ["torch>=2.3", "transformers>=4.51", "trl>=0.19", "peft>=0.13", "datasets>=3.0", "accelerate>=1.0",
27
+ "bitsandbytes>=0.45", "matplotlib>=3.8"]
28
+ dev = ["pytest>=8", "pytest-asyncio>=0.23", "httpx>=0.27", "ruff>=0.6", "gradio>=5.30,<7", "plotly>=5.18"]
 
 
 
 
 
29
 
30
  [project.scripts]
31
+ nexusgrid-server = "server.app:main"
32
+ nexusgrid-eval = "scripts.evaluate:main"
33
+
34
+ [project.urls]
35
+ Repository = "https://github.com/AbineshSenthil/NexusGrid-CyberPhysEnv"
36
+ Space = "https://huggingface.co/spaces/Abineshsdata/Nexus-Grid"
37
 
38
  [tool.setuptools]
39
+ packages = ["server", "scripts", "training"]
40
+ py-modules = ["client", "gym_env", "inference", "models", "policies"]
41
+
42
+ [tool.setuptools.package-data]
43
+ server = ["data/*.json"]
44
 
45
  [tool.pytest.ini_options]
46
  testpaths = ["tests"]
47
  python_files = "test_*.py"
48
+
49
+ [tool.ruff]
50
+ line-length = 120
51
+ extend-exclude = [".venv", "runs"]
requirements.txt CHANGED
@@ -1,13 +1,11 @@
1
- # NexusGrid-CyberPhysEnv — Pinned Dependencies
2
- # For Docker layer caching and reproducibility
3
-
4
- openenv-core[core]>=0.2.2
5
- numpy>=1.24.0
6
- networkx>=3.0
7
- fastapi>=0.115.0
8
- uvicorn>=0.24.0
9
- pydantic>=2.0.0
10
- openai>=1.0.0
11
- python-dotenv>=1.0.0
12
- gradio>=4.0.0
13
- plotly>=5.18.0
 
1
+ # Runtime dependencies for the server / Hugging Face Space (Docker).
2
+ # Optional extras for RL, GRPO and development are listed in pyproject.toml.
3
+ openenv-core[core]>=0.2.3,<0.4
4
+ numpy>=1.26,<3
5
+ pydantic>=2.7,<3
6
+ fastapi>=0.115
7
+ uvicorn>=0.30
8
+ gradio>=5.30,<7
9
+ plotly>=5.18
10
+ openai>=1.40
11
+ python-dotenv>=1.0
 
 
scripts/__init__.py ADDED
File without changes
scripts/build_scenario_catalog.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regenerate the validated Task 2 contingency catalog (server/data/cascade_catalog.json).
2
+
3
+ Run this after changing the network or the physics:
4
+
5
+ python scripts/build_scenario_catalog.py --count 240
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import sys
13
+ import time
14
+ from collections import Counter
15
+ from pathlib import Path
16
+
17
+ ROOT = Path(__file__).resolve().parents[1]
18
+ sys.path.insert(0, str(ROOT))
19
+
20
+ from server.scenarios import CATALOG_PATH, generate_cascade_catalog # noqa: E402
21
+
22
+
23
+ def main() -> None:
24
+ parser = argparse.ArgumentParser(description=__doc__)
25
+ parser.add_argument("--count", type=int, default=240)
26
+ parser.add_argument("--seed", type=int, default=2026)
27
+ args = parser.parse_args()
28
+
29
+ start = time.time()
30
+ configs = generate_cascade_catalog(count=args.count, seed=args.seed)
31
+ CATALOG_PATH.parent.mkdir(parents=True, exist_ok=True)
32
+ payload = {
33
+ "description": "Validated N-1 contingencies for Task 2 (cascade_overload). The first 80% serve "
34
+ "training seeds, the last 20% serve held-out evaluation seeds (>= 10000).",
35
+ "generator_seed": args.seed,
36
+ "count": len(configs),
37
+ "configs": configs,
38
+ }
39
+ CATALOG_PATH.write_text(json.dumps(payload, indent=1), encoding="utf-8")
40
+ trips = Counter(c["trip_line"] for c in configs)
41
+ print(f"wrote {len(configs)} configs to {CATALOG_PATH} in {time.time() - start:.1f}s")
42
+ print("trip lines:", dict(trips.most_common()))
43
+
44
+
45
+ if __name__ == "__main__":
46
+ main()
scripts/evaluate.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Evaluate policies on NexusGrid.
4
+
5
+ Runs every (policy, task, seed) episode in-process and reports the mean task
6
+ score with its standard deviation and a 95 % confidence interval. Training
7
+ seeds start at 0; held-out evaluation seeds start at 10 000 and draw from
8
+ parameter ranges (and, for Task 2, contingencies) never used in training.
9
+
10
+ Examples
11
+ --------
12
+ python scripts/evaluate.py # baselines, 50 held-out seeds per task
13
+ python scripts/evaluate.py --policies expert --tasks 2,3 --seeds 200
14
+ python scripts/evaluate.py --policies llm --seeds 5 --model qwen3:1.7b \\
15
+ --api-base http://localhost:11434/v1 # any OpenAI-compatible server
16
+ python scripts/evaluate.py --policies ppo --ppo-model runs/ppo/task2/final.zip
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import math
24
+ import statistics
25
+ import sys
26
+ import time
27
+ from concurrent.futures import ProcessPoolExecutor
28
+ from pathlib import Path
29
+ from typing import Any, Dict, List, Optional
30
+
31
+ ROOT = Path(__file__).resolve().parents[1]
32
+ if str(ROOT) not in sys.path:
33
+ sys.path.insert(0, str(ROOT))
34
+
35
+ from server.nexusgrid_environment import NexusgridEnvironment # noqa: E402
36
+ from server.scenarios import EVAL_SEED_START, TASK_NAMES # noqa: E402
37
+
38
+
39
+ def build_policy(name: str, seed: int, options: Dict[str, Any]):
40
+ if name in ("noop", "random", "expert"):
41
+ from policies import make_policy
42
+ return make_policy(name, seed)
43
+ if name == "llm":
44
+ from inference import LLMPolicy
45
+ return LLMPolicy(
46
+ model=options["model"],
47
+ api_base=options["api_base"],
48
+ api_key=options.get("api_key"),
49
+ fallback=options.get("fallback", False),
50
+ temperature=options.get("temperature", 0.0),
51
+ )
52
+ if name == "ppo":
53
+ from gym_env import PPOPolicy
54
+ return PPOPolicy(options["ppo_model"], deterministic=True)
55
+ raise ValueError(f"Unknown policy: {name}")
56
+
57
+
58
+ def run_episode(policy_name: str, task_id: int, seed: int, options: Dict[str, Any]) -> Dict[str, Any]:
59
+ env = NexusgridEnvironment()
60
+ policy = build_policy(policy_name, seed, options)
61
+ if hasattr(policy, "reset"):
62
+ policy.reset(seed)
63
+ started = time.time()
64
+ obs = env.reset(seed=seed, task_id=task_id)
65
+ while not obs.done:
66
+ obs = env.step(policy.act(obs))
67
+ summary = env.get_episode_summary()
68
+ record = {
69
+ "policy": policy_name,
70
+ "task_id": task_id,
71
+ "task_name": TASK_NAMES[task_id],
72
+ "seed": seed,
73
+ "split": summary["split"],
74
+ "score": round(summary["score"], 6),
75
+ "total_reward": summary["total_reward"],
76
+ "rubrics": {k: round(v, 4) for k, v in summary["rubrics"].items()},
77
+ "steps": summary["ticks_used"],
78
+ "invalid_actions": summary["invalid_actions"],
79
+ "events": summary["events"],
80
+ "seconds": round(time.time() - started, 3),
81
+ }
82
+ stats = getattr(policy, "stats", None)
83
+ if callable(stats):
84
+ record["policy_stats"] = stats()
85
+ return record
86
+
87
+
88
+ def summarise(records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
89
+ groups: Dict[tuple, List[Dict[str, Any]]] = {}
90
+ for r in records:
91
+ groups.setdefault((r["policy"], r["task_id"], r["split"]), []).append(r)
92
+ rows = []
93
+ for (policy, task_id, split), items in sorted(groups.items()):
94
+ scores = [r["score"] for r in items]
95
+ mean = statistics.mean(scores)
96
+ sd = statistics.pstdev(scores) if len(scores) > 1 else 0.0
97
+ ci = 1.96 * (statistics.stdev(scores) / math.sqrt(len(scores))) if len(scores) > 1 else 0.0
98
+ rows.append({
99
+ "policy": policy,
100
+ "task_id": task_id,
101
+ "task_name": TASK_NAMES[task_id],
102
+ "split": split,
103
+ "episodes": len(items),
104
+ "mean_score": round(mean, 4),
105
+ "std": round(sd, 4),
106
+ "ci95": round(ci, 4),
107
+ "success_rate": round(sum(1 for s in scores if s >= 0.8) / len(scores), 4),
108
+ "mean_invalid_actions": round(statistics.mean(r["invalid_actions"] for r in items), 3),
109
+ "mean_steps": round(statistics.mean(r["steps"] for r in items), 2),
110
+ })
111
+ return rows
112
+
113
+
114
+ def markdown_table(rows: List[Dict[str, Any]]) -> str:
115
+ policies = sorted({r["policy"] for r in rows}, key=lambda p: ["noop", "random", "expert"].index(p)
116
+ if p in ("noop", "random", "expert") else 10)
117
+ tasks = sorted({(r["task_id"], r["task_name"]) for r in rows})
118
+ splits = sorted({r["split"] for r in rows})
119
+ lookup = {(r["policy"], r["task_id"], r["split"]): r for r in rows}
120
+ lines = []
121
+ for split in splits:
122
+ lines.append(f"**{split} seeds**\n")
123
+ lines.append("| Task | " + " | ".join(policies) + " |")
124
+ lines.append("|---|" + "---|" * len(policies))
125
+ for task_id, name in tasks:
126
+ cells = []
127
+ for p in policies:
128
+ r = lookup.get((p, task_id, split))
129
+ cells.append(f"{r['mean_score']:.3f} ± {r['std']:.3f}" if r else "–")
130
+ lines.append(f"| {task_id} · {name} | " + " | ".join(cells) + " |")
131
+ means = []
132
+ for p in policies:
133
+ vals = [lookup[(p, t, split)]["mean_score"] for t, _ in tasks if (p, t, split) in lookup]
134
+ means.append(f"**{statistics.mean(vals):.3f}**" if vals else "–")
135
+ lines.append("| **Mean** | " + " | ".join(means) + " |")
136
+ lines.append("")
137
+ return "\n".join(lines)
138
+
139
+
140
+ def main(argv: Optional[List[str]] = None) -> int:
141
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
142
+ parser.add_argument("--policies", default="noop,random,expert")
143
+ parser.add_argument("--tasks", default="0,1,2,3,4,5")
144
+ parser.add_argument("--seeds", type=int, default=50, help="episodes per task and split")
145
+ parser.add_argument("--split", choices=["eval", "train", "both"], default="eval")
146
+ parser.add_argument("--workers", type=int, default=1)
147
+ parser.add_argument("--out", default="results/eval")
148
+ parser.add_argument("--model", default="qwen3:1.7b", help="LLM model name (llm policy)")
149
+ parser.add_argument("--api-base", default="http://localhost:11434/v1", help="OpenAI-compatible base URL")
150
+ parser.add_argument("--api-key", default=None)
151
+ parser.add_argument("--fallback", action="store_true", help="LLM: replace invalid outputs with the expert action")
152
+ parser.add_argument("--ppo-model", default=None, help="path to a trained MaskablePPO .zip")
153
+ args = parser.parse_args(argv)
154
+
155
+ policies = [p.strip() for p in args.policies.split(",") if p.strip()]
156
+ tasks = [int(t) for t in args.tasks.split(",")]
157
+ seed_sets = []
158
+ if args.split in ("train", "both"):
159
+ seed_sets.append(list(range(args.seeds)))
160
+ if args.split in ("eval", "both"):
161
+ seed_sets.append(list(range(EVAL_SEED_START, EVAL_SEED_START + args.seeds)))
162
+ options = {"model": args.model, "api_base": args.api_base, "api_key": args.api_key,
163
+ "fallback": args.fallback, "ppo_model": args.ppo_model}
164
+
165
+ jobs = [(p, t, s) for p in policies for t in tasks for seeds in seed_sets for s in seeds]
166
+ started = time.time()
167
+ records: List[Dict[str, Any]] = []
168
+ if args.workers > 1:
169
+ with ProcessPoolExecutor(max_workers=args.workers) as pool:
170
+ futures = [pool.submit(run_episode, p, t, s, options) for p, t, s in jobs]
171
+ for f in futures:
172
+ records.append(f.result())
173
+ else:
174
+ for i, (p, t, s) in enumerate(jobs, 1):
175
+ records.append(run_episode(p, t, s, options))
176
+ if p == "llm":
177
+ print(f"[{i}/{len(jobs)}] {p} task {t} seed {s}: {records[-1]['score']:.3f}", flush=True)
178
+
179
+ rows = summarise(records)
180
+ out = Path(args.out)
181
+ out.mkdir(parents=True, exist_ok=True)
182
+ (out / "episodes.jsonl").write_text("\n".join(json.dumps(r) for r in records) + "\n", encoding="utf-8")
183
+ (out / "summary.json").write_text(json.dumps({
184
+ "policies": policies, "tasks": tasks, "seeds_per_task": args.seeds, "split": args.split,
185
+ "eval_seed_start": EVAL_SEED_START, "rows": rows,
186
+ }, indent=2), encoding="utf-8")
187
+ table = markdown_table(rows)
188
+ (out / "summary.md").write_text(table + "\n", encoding="utf-8")
189
+ print(table)
190
+ print(f"{len(records)} episodes in {time.time() - started:.1f}s -> {out}/")
191
+ return 0
192
+
193
+
194
+ if __name__ == "__main__":
195
+ raise SystemExit(main())
server/app.py CHANGED
@@ -2,13 +2,12 @@
2
  FastAPI application for the NexusGrid-CyberPhysEnv.
3
 
4
  Endpoints:
5
- - POST /reset: Reset the environment
6
- - POST /step: Execute an action
7
- - GET /state: Get current environment state
8
- - GET /health: Health check (returns immediately)
9
- - GET /schema: Get action/observation schemas
10
- - GET /web: Gradio visual dashboard
11
- - WS /ws: WebSocket endpoint for persistent sessions
12
 
13
  Usage:
14
  uvicorn server.app:app --reload --host 0.0.0.0 --port 8000
@@ -16,6 +15,8 @@ Usage:
16
 
17
  from fastapi.responses import JSONResponse
18
 
 
 
19
  try:
20
  from openenv.core.env_server.http_server import create_app
21
  except Exception as e:
@@ -26,9 +27,13 @@ except Exception as e:
26
  try:
27
  from ..models import GridAction, GridObservation
28
  from .nexusgrid_environment import NexusgridEnvironment
 
 
29
  except (ImportError, ModuleNotFoundError):
30
  from models import GridAction, GridObservation
31
  from server.nexusgrid_environment import NexusgridEnvironment
 
 
32
 
33
 
34
  # Create the OpenEnv app
@@ -37,7 +42,7 @@ app = create_app(
37
  GridAction,
38
  GridObservation,
39
  env_name="nexusgrid",
40
- max_concurrent_envs=1,
41
  )
42
 
43
 
@@ -53,12 +58,31 @@ if not any(getattr(route, "path", None) == "/health" for route in app.routes):
53
  content={
54
  "status": "healthy",
55
  "environment": "NexusGrid-CyberPhysEnv",
56
- "version": "2.0.0",
57
  },
58
  status_code=200,
59
  )
60
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  @app.get("/manifest.json")
63
  async def manifest():
64
  return JSONResponse(content={
 
2
  FastAPI application for the NexusGrid-CyberPhysEnv.
3
 
4
  Endpoints:
5
+ - WS /ws: persistent sessions (reset/step/state) - use this for multi-step episodes
6
+ - POST /reset, POST /step: stateless HTTP calls (each request gets a fresh environment)
7
+ - GET /state, GET /schema, GET /metadata: OpenEnv introspection
8
+ - GET /health: health check (returns immediately)
9
+ - GET /tasks: task list with rubric weights and horizons
10
+ - GET /web: Gradio dashboard
 
11
 
12
  Usage:
13
  uvicorn server.app:app --reload --host 0.0.0.0 --port 8000
 
15
 
16
  from fastapi.responses import JSONResponse
17
 
18
+ ENV_VERSION = "3.0.0"
19
+
20
  try:
21
  from openenv.core.env_server.http_server import create_app
22
  except Exception as e:
 
27
  try:
28
  from ..models import GridAction, GridObservation
29
  from .nexusgrid_environment import NexusgridEnvironment
30
+ from .rubric import get_task_rubric_specs
31
+ from .scenarios import EVAL_SEED_START, MAX_TICKS, TASK_DIFFICULTIES, TASK_NAMES
32
  except (ImportError, ModuleNotFoundError):
33
  from models import GridAction, GridObservation
34
  from server.nexusgrid_environment import NexusgridEnvironment
35
+ from server.rubric import get_task_rubric_specs
36
+ from server.scenarios import EVAL_SEED_START, MAX_TICKS, TASK_DIFFICULTIES, TASK_NAMES
37
 
38
 
39
  # Create the OpenEnv app
 
42
  GridAction,
43
  GridObservation,
44
  env_name="nexusgrid",
45
+ max_concurrent_envs=16,
46
  )
47
 
48
 
 
58
  content={
59
  "status": "healthy",
60
  "environment": "NexusGrid-CyberPhysEnv",
61
+ "version": ENV_VERSION,
62
  },
63
  status_code=200,
64
  )
65
 
66
 
67
+ @app.get("/tasks")
68
+ async def tasks():
69
+ """Tasks, horizons and rubric weights. Seeds >= eval_seed_start are held out for evaluation."""
70
+ return JSONResponse(content={
71
+ "version": ENV_VERSION,
72
+ "eval_seed_start": EVAL_SEED_START,
73
+ "tasks": [
74
+ {
75
+ "id": task_id,
76
+ "name": TASK_NAMES[task_id],
77
+ "difficulty": TASK_DIFFICULTIES[task_id],
78
+ "max_ticks": MAX_TICKS[task_id],
79
+ "rubrics": get_task_rubric_specs(task_id),
80
+ }
81
+ for task_id in sorted(TASK_NAMES)
82
+ ],
83
+ })
84
+
85
+
86
  @app.get("/manifest.json")
87
  async def manifest():
88
  return JSONResponse(content={
server/dashboard.py CHANGED
The diff for this file is too large to render. See raw diff
 
server/data/cascade_catalog.json ADDED
The diff for this file is too large to render. See raw diff
 
server/graders.py CHANGED
@@ -1,25 +1,22 @@
1
  """
2
  NexusGrid — Task Graders.
3
 
4
- Six pure grader functions: (action_history, episode_state) → float [0.0, 1.0].
5
- No side effects, no global state.
6
- Each grader is deterministic and reproducible.
7
  """
8
 
9
  from __future__ import annotations
10
 
11
  from typing import Any, Dict, List
12
 
13
- from .rubric import evaluate_task_rubrics
14
 
 
 
15
 
16
- def grade_task(task_id: int, action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
17
- """
18
- Route to the appropriate grader.
19
 
20
- Returns:
21
- float in [0.0, 1.0]
22
- """
23
  graders = {
24
  0: grade_smoke_test,
25
  1: grade_duck_curve,
@@ -31,188 +28,65 @@ def grade_task(task_id: int, action_history: List[Dict[str, Any]], episode_state
31
  grader = graders.get(task_id)
32
  if grader is None:
33
  return 0.0
34
- score = grader(action_history, episode_state)
35
- return max(0.0, min(1.0, score))
36
 
37
 
38
- # ---------------------------------------------------------------------------
39
- # Task 0 — Smoke test (Trivial)
40
- # ---------------------------------------------------------------------------
41
 
42
- def grade_smoke_test(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
43
- """
44
- Any valid dispatch_generation call with positive mw → 1.0.
45
- Malformed or no action → 0.0.
46
 
47
- Purpose: infrastructure validation, not a benchmark.
48
  """
49
- rubric_eval = evaluate_task_rubrics(0, action_history, episode_state)
50
- return rubric_eval["weighted_score"]
51
-
52
-
53
- # ---------------------------------------------------------------------------
54
- # Task 1 — Duck curve (Easy)
55
- # ---------------------------------------------------------------------------
56
-
57
- def grade_duck_curve(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
58
  """
59
- Score based on:
60
- - 1.0: grid_frequency_hz stays above 59.5Hz throughout
61
- - 0.5: frequency dips but recovers above 59.5Hz within 3 ticks
62
- - 0.0: frequency crosses 59.0Hz
63
 
64
- Bonus: proactive dispatch (before frequency drop) earns +0.08.
65
- """
66
- rubric_eval = evaluate_task_rubrics(1, action_history, episode_state)
67
- rubrics = rubric_eval["rubrics"]
68
 
69
- if rubrics.get("avoid_collapse", 0.0) == 0.0:
70
- return 0.0
 
71
 
72
- return min(
73
- 1.0,
74
- rubric_eval["weighted_components"].get("avoid_collapse", 0.0)
75
- + rubric_eval["weighted_components"].get("recover_nominal_band", 0.0)
76
- + rubric_eval["weighted_components"].get("hold_nominal_band", 0.0)
77
- + rubric_eval["weighted_components"].get("proactive_dispatch", 0.0),
78
- )
79
 
 
 
 
 
 
 
80
 
81
- # ---------------------------------------------------------------------------
82
- # Task 2 — Cascade overload (Medium)
83
- # ---------------------------------------------------------------------------
84
 
85
  def grade_cascade_overload(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
86
  """
87
- Score breakdown:
88
- - 0.4 for correctly isolating the fault (toggle_circuit_breaker on overloaded line)
89
- - 0.4 for preserving all critical nodes (hospitals, water)
90
- - 0.2 for restoring full supply within 8 ticks
91
  """
92
- rubric_eval = evaluate_task_rubrics(2, action_history, episode_state)
93
- return rubric_eval["weighted_score"]
94
-
 
95
 
96
- # ---------------------------------------------------------------------------
97
- # Task 3 — Phantom injection (Hard)
98
- # ---------------------------------------------------------------------------
99
 
100
  def grade_phantom_injection(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
101
  """
102
- Anti-hallucination gate: quarantine or dispatch without state_estimation first → 0.0.
103
-
104
- Partial scores:
105
- - 0.3 for state_estimation returning Kirchhoff violation
106
- - 0.6 for quarantine_scada_node
107
- - 1.0 for rerouting the missing MW before tick 4
108
-
109
- All three steps must complete in order.
110
  """
111
- # Check action order
112
- has_estimation = False
113
- has_quarantine = False
114
- has_reroute = False
115
- estimation_tick = None
116
- quarantine_tick = None
117
- reroute_tick = None
118
-
119
- for action in action_history:
120
- action_type = action.get("action_type")
121
- tick = action.get("tick", 999)
122
-
123
- # Anti-hallucination gate:
124
- # Quarantine/dispatch before estimation → 0.0
125
- if not has_estimation:
126
- if action_type == "quarantine_scada_node":
127
- return 0.0
128
- if action_type == "dispatch_generation" and tick > 0:
129
- return 0.0
130
-
131
- if action_type == "run_state_estimation":
132
- result = action.get("result", {})
133
- if not result.get("consistent", True):
134
- has_estimation = True
135
- estimation_tick = tick
136
-
137
- if action_type == "quarantine_scada_node" and has_estimation:
138
- has_quarantine = True
139
- quarantine_tick = tick
140
 
141
- if action_type == "dispatch_generation" and has_quarantine:
142
- has_reroute = True
143
- reroute_tick = tick
144
-
145
- rubric_eval = evaluate_task_rubrics(3, action_history, episode_state)
146
- score = rubric_eval["weighted_score"]
147
-
148
- if has_reroute and reroute_tick is not None and reroute_tick > 4:
149
- return min(0.8, score)
150
-
151
- return score
152
-
153
-
154
- # ---------------------------------------------------------------------------
155
- # Task 4 — Stuxnet resonance (Very hard)
156
- # ---------------------------------------------------------------------------
157
 
158
  def grade_stuxnet_resonance(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
159
- """
160
- Correct: inject_counter_signal with hz_offset ≈ -0.5 (±0.05Hz tolerance).
161
- - 1.0 for correct injection + gradual ramp-down over 4 ticks
162
- - 0.4 for partial mitigation that shows some reasoning
163
- - 0.0 for cutting turbine or doing nothing
164
- """
165
- cut_turbine = False
166
-
167
- for action in action_history:
168
- action_type = action.get("action_type")
169
-
170
- # Check if turbine was cut (toggle_circuit_breaker on NODE_17's lines)
171
- if action_type == "toggle_circuit_breaker":
172
- edge_id = action.get("edge_id", "")
173
- if action.get("status") == "OPEN" and edge_id in ("LINE_22", "LINE_23", "LINE_24"):
174
- cut_turbine = True
175
-
176
- if cut_turbine:
177
- return 0.0 # Grid collapse
178
-
179
- rubric_eval = evaluate_task_rubrics(4, action_history, episode_state)
180
- rubrics = rubric_eval["rubrics"]
181
-
182
- if rubrics.get("counter_signal_attempted", 0.0) == 0.0:
183
- return 0.0 # Did nothing
184
-
185
- return rubric_eval["weighted_score"]
186
-
187
 
188
- # ---------------------------------------------------------------------------
189
- # Task 5 — Black start (Expert)
190
- # ---------------------------------------------------------------------------
191
 
192
  def grade_black_start(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
193
- """
194
- Four-checkpoint milestone grader:
195
- A (0.00–0.25): Any dispatch_generation on hydro dam with positive mw.
196
- B (0.25–0.50): Hydro generating + stable for 2+ ticks + another node energized.
197
- C (0.50–0.80): 3+ islands, first merger with |∆phase| ≤ 5°. Premature merger: -0.1.
198
- D (0.80–1.00): All critical infra restored.
199
-
200
- Final = checkpoint_score × load_restored_fraction.
201
- """
202
- rubric_eval = evaluate_task_rubrics(5, action_history, episode_state)
203
- checkpoint_score = rubric_eval["weighted_score"]
204
- premature_mergers = episode_state.get("premature_mergers", 0)
205
- checkpoint_score -= premature_mergers * 0.1
206
- checkpoint_score = max(0.0, checkpoint_score)
207
-
208
- # Apply transformer failure penalties
209
- transformer_failures = episode_state.get("transformer_failures", 0)
210
- checkpoint_score -= transformer_failures * 0.1
211
- checkpoint_score = max(0.0, checkpoint_score)
212
-
213
- # Apply load restoration fraction
214
- load_fraction = episode_state.get("load_restored_fraction", 0.0)
215
- final_score = checkpoint_score * max(load_fraction, 0.1) # Floor at 0.1 to not zero everything
216
-
217
- return max(0.0, min(1.0, final_score))
218
-
 
1
  """
2
  NexusGrid — Task Graders.
3
 
4
+ Pure functions ``(action_history, episode_state) -> score in [0, 1]``.
5
+ Each grader is the weighted rubric sum plus task-specific gates and penalties,
6
+ designed so that doing nothing or acting randomly scores low.
7
  """
8
 
9
  from __future__ import annotations
10
 
11
  from typing import Any, Dict, List
12
 
13
+ from .rubric import evaluate_task_rubrics, mean_served
14
 
15
+ SERVED_TARGET = 0.99
16
+ SERVED_PENALTY = 5.0
17
 
 
 
 
18
 
19
+ def grade_task(task_id: int, action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
 
 
20
  graders = {
21
  0: grade_smoke_test,
22
  1: grade_duck_curve,
 
28
  grader = graders.get(task_id)
29
  if grader is None:
30
  return 0.0
31
+ return max(0.0, min(1.0, float(grader(action_history, episode_state))))
 
32
 
33
 
34
+ def _score(task_id: int, actions: List[Dict[str, Any]], state: Dict[str, Any]) -> Dict[str, Any]:
35
+ state = {"done": True, **state}
36
+ return evaluate_task_rubrics(task_id, actions, state)
37
 
 
 
 
 
38
 
39
+ def served_factor(state: Dict[str, Any]) -> float:
40
  """
41
+ Multiplier that stops agents from "fixing" frequency by cutting customers:
42
+ every percentage point of average demand left unserved below 99 % costs
43
+ 5 % of the score.
 
 
 
 
 
 
44
  """
45
+ shortfall = max(0.0, SERVED_TARGET - mean_served(state))
46
+ return max(0.0, 1.0 - SERVED_PENALTY * shortfall)
 
 
47
 
 
 
 
 
48
 
49
+ def grade_smoke_test(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
50
+ """Any valid positive dispatch (0.7) that leaves frequency in band (0.3)."""
51
+ return _score(0, action_history, episode_state)["weighted_score"]
52
 
 
 
 
 
 
 
 
53
 
54
+ def grade_duck_curve(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
55
+ """Frequency regulation through the evening ramp; a collapse below 59.0 Hz scores 0."""
56
+ freqs = episode_state.get("frequency_history", [])
57
+ if freqs and min(freqs) < 59.0:
58
+ return 0.0
59
+ return _score(1, action_history, episode_state)["weighted_score"] * served_factor(episode_state)
60
 
 
 
 
61
 
62
  def grade_cascade_overload(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
63
  """
64
+ Relieve the post-contingency overloads. Without relief, the remaining
65
+ rubrics are capped at 40% so riding out the cascade cannot score well.
 
 
66
  """
67
+ result = _score(2, action_history, episode_state)
68
+ if result["rubrics"].get("relieve_overload", 0.0) == 0.0:
69
+ return 0.4 * result["weighted_score"]
70
+ return result["weighted_score"]
71
 
 
 
 
72
 
73
  def grade_phantom_injection(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
74
  """
75
+ Evidence-first incident response. Every refused quarantine attempt
76
+ (no prior proof for that bus) costs 0.1; unserved demand is penalised.
 
 
 
 
 
 
77
  """
78
+ result = _score(3, action_history, episode_state)
79
+ refused = int(episode_state.get("refused_quarantines", 0))
80
+ return max(0.0, result["weighted_score"] * served_factor(episode_state) - 0.1 * refused)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  def grade_stuxnet_resonance(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
84
+ """Damp, detune and rebalance; disconnecting or zeroing the unit scores 0."""
85
+ if episode_state.get("target_disconnected"):
86
+ return 0.0
87
+ return _score(4, action_history, episode_state)["weighted_score"] * served_factor(episode_state)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
 
 
 
89
 
90
  def grade_black_start(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
91
+ """Restore critical loads and demand without collapsing islands."""
92
+ return _score(5, action_history, episode_state)["weighted_score"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
server/grid_engine.py CHANGED
@@ -1,79 +1,91 @@
1
  """
2
  NexusGrid — Physical Grid Engine (Layer 1).
3
 
4
- 20-node transmission network with DC power flow (Kirchhoff B-matrix).
5
- This is the truth oracle — physics cannot lie.
6
- All randomness uses numpy.random.Generator(PCG64(seed)).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  """
8
 
9
  from __future__ import annotations
10
 
11
  import math
 
12
  from typing import Any, Dict, List, Optional, Tuple
13
 
14
  import numpy as np
15
 
16
- try:
17
- import networkx as nx
18
- except ImportError:
19
- nx = None # type: ignore
20
 
 
21
 
22
- class GridEngine:
23
- """
24
- Simplified DC power flow engine for the NexusGrid environment.
25
 
26
- Maintains a graph of substations (nodes) and transmission lines (edges).
27
- Computes ground-truth frequency from supply/demand balance.
28
- Provides state estimation (Kirchhoff check) as the anti-spoof mechanism.
29
- """
30
 
31
- # Physics constants
32
  NOMINAL_FREQUENCY_HZ = 60.0
33
- FREQUENCY_DROOP_COEFF = 0.05 # Hz per 100MW imbalance
34
- INERTIA_CONSTANT = 5.0 # seconds — how fast frequency responds
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  def __init__(self, seed: int = 42):
37
- self._rng = np.random.Generator(np.random.PCG64(seed))
38
- self._seed = seed
 
39
  self.tick = 0
40
 
41
- # Node storage: {node_id: {type, capacity_mw, peak_load_mw, generation_mw,
42
- # consumption_mw, region, critical, voltage_kv,
43
- # phase_angle_deg, ...}}
44
  self.nodes: Dict[str, Dict[str, Any]] = {}
45
-
46
- # Edge storage: {edge_id: {source, target, capacity_mw, current_load_mw, status, reactance}}
47
  self.edges: Dict[str, Dict[str, Any]] = {}
48
 
49
- # Current ground-truth frequency
50
  self.frequency_hz: float = self.NOMINAL_FREQUENCY_HZ
 
 
 
 
 
51
 
52
- # Telemetry history (list of per-tick snapshots, max 10)
53
- self.telemetry_history: List[List[Dict[str, Any]]] = []
54
-
55
- # Weather state per zone
56
  self.weather: Dict[str, Dict[str, float]] = {}
 
 
 
57
 
58
- # Counter-signal state
59
  self._counter_signals: List[Dict[str, Any]] = []
60
-
61
- # Track dispatches for proactive detection
62
  self._dispatch_ticks: List[int] = []
63
  self._first_frequency_drop_tick: Optional[int] = None
64
- self._forced_edge_loads: Dict[str, float] = {}
65
-
66
- def reset(self, seed: int = 42) -> None:
67
- """Reset engine to initial state with given seed."""
68
- self._rng = np.random.Generator(np.random.PCG64(seed))
69
- self._seed = seed
70
- self.tick = 0
71
- self.frequency_hz = self.NOMINAL_FREQUENCY_HZ
72
- self.telemetry_history = []
73
- self._counter_signals = []
74
- self._dispatch_ticks = []
75
- self._first_frequency_drop_tick = None
76
- self._forced_edge_loads = {}
77
 
78
  # ------------------------------------------------------------------
79
  # Topology builders
@@ -90,24 +102,44 @@ class GridEngine:
90
  generation_mw: float = 0.0,
91
  consumption_mw: float = 0.0,
92
  black_start_capable: bool = False,
 
 
93
  ) -> None:
94
- """Add a substation node to the grid."""
 
 
 
 
95
  self.nodes[node_id] = {
96
  "id": node_id,
97
  "node_type": node_type,
98
- "capacity_mw": capacity_mw,
99
- "peak_load_mw": peak_load_mw,
100
  "region": region,
101
- "critical": critical,
102
- "generation_mw": generation_mw,
103
- "base_generation_mw": generation_mw,
104
- "consumption_mw": consumption_mw,
105
- "base_consumption_mw": consumption_mw,
 
 
 
 
 
 
 
 
 
 
 
 
106
  "voltage_kv": 345.0,
107
  "phase_angle_deg": 0.0,
108
  "energized": True,
109
  "quarantined": False,
110
- "black_start_capable": black_start_capable,
 
 
111
  }
112
 
113
  def add_edge(
@@ -116,434 +148,667 @@ class GridEngine:
116
  source: str,
117
  target: str,
118
  capacity_mw: float,
119
- reactance: float = 0.01,
120
  ) -> None:
121
- """Add a transmission line edge to the grid."""
 
 
122
  self.edges[edge_id] = {
123
  "id": edge_id,
124
  "source": source,
125
  "target": target,
126
- "capacity_mw": capacity_mw,
 
 
127
  "current_load_mw": 0.0,
 
128
  "status": "LIVE",
129
- "reactance": reactance,
 
 
130
  }
131
 
132
- def _build_live_adjacency(self) -> Dict[str, List[str]]:
133
- """Build an undirected adjacency map for currently live lines."""
134
- adjacency: Dict[str, List[str]] = {node_id: [] for node_id in self.nodes}
135
- for edge in self.edges.values():
136
- if edge["status"] != "LIVE":
137
- continue
138
- adjacency[edge["source"]].append(edge["target"])
139
- adjacency[edge["target"]].append(edge["source"])
140
- return adjacency
141
 
142
- def _get_powered_components(self) -> Tuple[List[List[str]], List[List[str]]]:
143
  """
144
- Return (all_components, powered_components) over live topology.
145
 
146
- A component is considered powered if it contains a generator currently
147
- producing positive power.
 
148
  """
149
- adjacency = self._build_live_adjacency()
150
- visited: set[str] = set()
151
- components: List[List[str]] = []
152
- powered_components: List[List[str]] = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
- for start_node in self.nodes:
155
- if start_node in visited:
156
- continue
157
 
158
- stack = [start_node]
159
- component: List[str] = []
 
 
 
 
 
 
 
 
 
 
 
160
  while stack:
161
- node_id = stack.pop()
162
- if node_id in visited:
163
  continue
164
- visited.add(node_id)
165
- component.append(node_id)
166
- for neighbor in adjacency.get(node_id, []):
167
- if neighbor not in visited:
168
- stack.append(neighbor)
169
-
170
- if not component:
171
- continue
172
-
173
- components.append(component)
174
- if any(
175
- self.nodes[node_id]["node_type"] in ("hydro", "solar", "gas", "battery")
176
- and self.nodes[node_id]["generation_mw"] > 0
177
- for node_id in component
178
- ):
179
- powered_components.append(component)
180
-
181
- return components, powered_components
182
-
183
- def _recompute_energization(self) -> List[str]:
184
- """
185
- Propagate energized state through live lines from powered islands.
186
-
187
- Returns:
188
- List of node IDs that transitioned from de-energized to energized.
189
- """
190
- previous_state = {
191
- node_id: bool(node["energized"])
192
- for node_id, node in self.nodes.items()
193
- }
194
- components, powered_components = self._get_powered_components()
195
- powered_nodes = {
196
- node_id
197
- for component in powered_components
198
- for node_id in component
199
- }
200
-
201
- for component in components:
202
- component_powered = any(node_id in powered_nodes for node_id in component)
203
- for node_id in component:
204
- node = self.nodes[node_id]
205
- can_self_boot = node.get("black_start_capable", False) and previous_state[node_id]
206
- node["energized"] = component_powered or can_self_boot
207
- node["voltage_kv"] = 345.0 if component_powered else 0.0
208
- if can_self_boot and not component_powered:
209
- node["voltage_kv"] = 345.0
210
  if not node["energized"]:
 
211
  node["phase_angle_deg"] = 0.0
212
- if (
213
- node["energized"]
214
- and not previous_state[node_id]
215
- and node["node_type"] == "load"
216
- and node["consumption_mw"] <= 0
217
- and node.get("base_consumption_mw", 0) > 0
218
- ):
219
- node["consumption_mw"] = node["base_consumption_mw"]
220
-
221
- newly_energized = [
222
- node_id
223
- for node_id, was_energized in previous_state.items()
224
- if not was_energized and self.nodes[node_id]["energized"]
225
- ]
226
- return newly_energized
227
-
228
- # ------------------------------------------------------------------
229
- # Core physics
230
- # ------------------------------------------------------------------
231
 
232
- def compute_power_flow(self) -> None:
233
  """
234
- Simplified DC power flow: distribute generation to match loads
235
- through live transmission lines. Updates edge loads and node states.
 
236
  """
237
- self._recompute_energization()
 
238
 
239
- # Calculate total generation and consumption
240
- total_gen = sum(
241
- n["generation_mw"] for n in self.nodes.values()
242
- if n["node_type"] in ("hydro", "solar", "gas", "battery") and n["energized"]
243
- )
244
- total_load = sum(
245
- n["consumption_mw"] for n in self.nodes.values()
246
- if n["node_type"] == "load" and n["energized"]
247
- )
248
 
249
- # Reset all edge loads
250
  for edge in self.edges.values():
251
- if edge["status"] == "LIVE":
252
- edge["current_load_mw"] = 0.0
253
-
254
- # Distribute power through live edges using simplified DC flow
255
- live_edges = [e for e in self.edges.values() if e["status"] == "LIVE"]
256
- if not live_edges:
257
- return
258
-
259
- # Build adjacency and distribute loads proportionally
260
- # For each load node, find paths from generators and distribute
261
- generator_nodes = [
262
- n for n in self.nodes.values()
263
- if n["node_type"] in ("hydro", "solar", "gas", "battery")
264
- and n["generation_mw"] > 0 and n["energized"]
265
- ]
266
- load_nodes = [
267
- n for n in self.nodes.values()
268
- if n["node_type"] == "load"
269
- and n["consumption_mw"] > 0 and n["energized"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  ]
271
-
272
- if not generator_nodes or not load_nodes:
273
  return
274
-
275
- # Build adjacency map for live edges
276
- adj: Dict[str, List[Tuple[str, str]]] = {} # node -> [(neighbor, edge_id)]
277
  for e in live_edges:
278
- adj.setdefault(e["source"], []).append((e["target"], e["id"]))
279
- adj.setdefault(e["target"], []).append((e["source"], e["id"]))
280
-
281
- # Simple proportional flow: each edge carries its share
282
- total_capacity = sum(e["capacity_mw"] for e in live_edges)
283
- if total_capacity == 0:
284
- return
285
-
286
- flow_needed = min(total_gen, total_load)
287
- for edge in live_edges:
288
- # Distribute flow proportional to edge capacity
289
- edge["current_load_mw"] = (edge["capacity_mw"] / total_capacity) * flow_needed
290
-
291
- for edge_id, forced_load in self._forced_edge_loads.items():
292
- edge = self.edges.get(edge_id)
293
- if edge is not None and edge["status"] == "LIVE":
294
- edge["current_load_mw"] = forced_load
295
-
296
- # Update phase angles based on flow
297
- for i, node in enumerate(self.nodes.values()):
298
- if node["energized"]:
299
- node["phase_angle_deg"] = (i * 15.0) % 360.0 - 180.0
 
 
 
 
 
 
 
 
 
 
300
 
301
- def compute_frequency(self) -> float:
302
  """
303
- Compute grid frequency from supply/demand balance.
304
-
305
- frequency = 60.0 + (generation - load) * droop_coefficient / 100
306
- Subject to inertia smoothing.
307
  """
308
- total_gen = sum(
309
- n["generation_mw"] for n in self.nodes.values()
310
- if n["node_type"] in ("hydro", "solar", "gas", "battery") and n["energized"]
311
- )
312
- total_load = sum(
313
- n["consumption_mw"] for n in self.nodes.values()
314
- if n["node_type"] == "load" and n["energized"]
315
- )
316
-
317
- # Apply counter-signals
318
- for cs in self._counter_signals:
319
- if cs["remaining_ticks"] > 0:
320
- total_gen += cs.get("power_injection_mw", 0)
321
-
322
- imbalance_mw = total_gen - total_load
323
- target_freq = self.NOMINAL_FREQUENCY_HZ + (imbalance_mw * self.FREQUENCY_DROOP_COEFF / 100.0)
324
-
325
- # Inertia smoothing — frequency moves toward target gradually
326
- alpha = 1.0 / self.INERTIA_CONSTANT
327
- self.frequency_hz = self.frequency_hz + alpha * (target_freq - self.frequency_hz)
328
-
329
- # Clamp to physical bounds
330
- self.frequency_hz = max(58.0, min(62.0, self.frequency_hz))
331
-
332
- # Track first frequency drop
333
- if self.frequency_hz < 59.7 and self._first_frequency_drop_tick is None:
334
  self._first_frequency_drop_tick = self.tick
335
-
336
  return self.frequency_hz
337
 
338
- def advance_tick(self, weather_evolution: bool = True) -> float:
339
- """
340
- Advance simulation by one tick (~5 simulated minutes).
 
 
 
 
 
341
 
342
- Returns the new grid frequency.
 
 
 
 
 
343
  """
344
  self.tick += 1
 
 
 
 
 
 
 
 
 
345
 
346
- # Evolve weather (affects solar/wind generation)
347
- if weather_evolution:
348
- self._evolve_weather()
349
-
350
- # Update renewable generation based on weather
351
- self._update_renewable_generation()
352
 
353
- # Evolve load with small random fluctuation
354
- self._evolve_load()
 
 
 
 
 
 
 
355
 
356
- # Update counter-signals
357
  for cs in self._counter_signals:
358
  if cs["remaining_ticks"] > 0:
359
  cs["remaining_ticks"] -= 1
360
 
361
- # Compute power flow
362
- self.compute_power_flow()
363
-
364
- # Compute frequency
365
- freq = self.compute_frequency()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
 
367
- # Record telemetry snapshot
368
- self._record_telemetry()
 
 
 
 
369
 
370
- return freq
 
371
 
372
  # ------------------------------------------------------------------
373
  # Actions
374
  # ------------------------------------------------------------------
375
 
376
  def dispatch_generation(self, node_id: str, mw: float) -> Dict[str, Any]:
377
- """Ramp a generator or battery up/down by mw."""
378
  if node_id not in self.nodes:
379
  return {"success": False, "error": f"Unknown node: {node_id}"}
380
-
381
  node = self.nodes[node_id]
382
- if node["node_type"] not in ("hydro", "solar", "gas", "battery"):
383
- return {"success": False, "error": f"Node {node_id} is not a generator"}
384
-
385
  if not node["energized"]:
386
  return {"success": False, "error": f"Node {node_id} is not energized"}
387
-
388
- new_gen = node["generation_mw"] + mw
389
- new_gen = max(0.0, min(node["capacity_mw"], new_gen))
390
- node["generation_mw"] = new_gen
391
-
 
 
 
 
 
392
  self._dispatch_ticks.append(self.tick)
393
-
394
- # Recompute flow and frequency immediately so observations reflect the control action.
395
  self.compute_power_flow()
396
- self.compute_frequency()
 
 
 
 
 
 
397
 
398
- return {"success": True, "new_generation_mw": new_gen}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
399
 
400
  def toggle_circuit_breaker(self, edge_id: str, status: str) -> Dict[str, Any]:
401
- """Open or close a transmission line circuit breaker."""
402
  if edge_id not in self.edges:
403
  return {"success": False, "error": f"Unknown edge: {edge_id}"}
404
-
405
- edge = self.edges[edge_id]
406
  if status not in ("OPEN", "CLOSED"):
407
  return {"success": False, "error": f"Invalid status: {status}. Use OPEN or CLOSED."}
408
-
409
  old_status = edge["status"]
410
- pre_energized = {
411
- node_id for node_id, node in self.nodes.items()
412
- if node["energized"]
413
- }
414
- pre_components = self.get_stable_islands()
415
  if status == "OPEN":
416
  edge["status"] = "TRIPPED"
417
- edge["current_load_mw"] = 0.0
418
  else:
 
 
 
 
 
 
 
 
 
 
 
 
 
419
  edge["status"] = "LIVE"
420
-
421
- # Recompute flow and frequency after topology changes.
422
- self.compute_power_flow()
423
- self.compute_frequency()
424
- post_components = self.get_stable_islands()
425
- newly_energized = [
426
- node_id for node_id, node in self.nodes.items()
427
- if node["energized"] and node_id not in pre_energized
428
- ]
429
-
430
- return {
431
- "success": True,
432
- "old_status": old_status,
433
  "new_status": edge["status"],
434
- "newly_energized_nodes": newly_energized,
435
- "island_count_before": len(pre_components),
436
- "island_count_after": len(post_components),
437
- }
 
438
 
439
- def run_state_estimation(self, subgraph: List[str], spoofed_telemetry: Dict[str, Dict]) -> Dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
 
440
  """
441
- Apply Kirchhoff's laws to check telemetry consistency.
442
 
443
- Compares reported values against physics — the truth oracle.
444
- Returns {consistent, violation_node, estimated_true_mw}.
 
445
  """
446
- for node_id in subgraph:
447
- if node_id not in self.nodes:
 
 
 
448
  continue
449
-
450
- true_node = self.nodes[node_id]
451
- reported = spoofed_telemetry.get(node_id, {})
452
-
453
- true_gen = true_node["generation_mw"]
454
- reported_gen = reported.get("generation_mw", true_gen)
455
-
456
- # Check if reported generation deviates from truth significantly
457
- if abs(reported_gen - true_gen) > 5.0: # 5MW tolerance
458
- return {
459
- "consistent": False,
460
- "violation_node": node_id,
461
- "estimated_true_mw": true_gen,
462
- "reported_mw": reported_gen,
463
- }
464
-
465
- # Check voltage consistency
466
- true_v = true_node["voltage_kv"]
467
- reported_v = reported.get("voltage_kv", true_v)
468
- if abs(reported_v - true_v) > 10.0:
469
- return {
470
- "consistent": False,
471
- "violation_node": node_id,
472
- "estimated_true_mw": true_gen,
473
- "reported_mw": reported_gen,
474
- }
475
-
476
  return {
477
- "consistent": True,
478
- "violation_node": None,
479
- "estimated_true_mw": 0.0,
 
 
 
 
480
  }
481
 
 
 
 
 
482
  def quarantine_node(self, node_id: str) -> Dict[str, Any]:
483
- """Quarantine a node's SCADA sensor — replace with estimator values."""
484
  if node_id not in self.nodes:
485
  return {"success": False, "error": f"Unknown node: {node_id}"}
486
-
487
  if self.nodes[node_id]["quarantined"]:
488
- return {
489
- "success": False,
490
- "error": f"Node {node_id} is already quarantined",
491
- "already_quarantined": True,
492
- }
493
-
494
  self.nodes[node_id]["quarantined"] = True
495
  return {"success": True, "node_id": node_id, "already_quarantined": False}
496
 
497
- def inject_counter_signal(
498
- self, node_id: str, hz_offset: float, duration: int
499
- ) -> Dict[str, Any]:
500
- """
501
- Inject a counter-signal via adjacent battery at given frequency offset.
502
-
503
- The counter-signal creates destructive interference when hz_offset
504
- matches the attack frequency (within ±0.05Hz tolerance).
505
- """
506
  if node_id not in self.nodes:
507
  return {"success": False, "error": f"Unknown node: {node_id}"}
508
-
509
  node = self.nodes[node_id]
510
  if node["node_type"] != "battery":
511
  return {"success": False, "error": f"Node {node_id} is not a battery"}
512
  if not node["energized"]:
513
  return {"success": False, "error": f"Node {node_id} is not energized"}
 
 
 
 
 
 
 
 
 
 
 
514
 
515
- # Calculate effectiveness based on offset accuracy
516
- # Perfect offset = -0.5Hz (to counter +0.5Hz attack)
517
- target_offset = -0.5
518
- accuracy = 1.0 - min(abs(hz_offset - target_offset) / 0.5, 1.0)
519
-
520
- power_injection = node["capacity_mw"] * 0.5 * accuracy # Half capacity at full accuracy
521
 
522
- self._counter_signals.append({
523
- "node_id": node_id,
524
- "hz_offset": hz_offset,
525
- "duration": duration,
526
- "remaining_ticks": duration,
527
- "accuracy": accuracy,
528
- "power_injection_mw": power_injection,
529
- })
530
- self.compute_frequency()
531
 
532
- return {
533
- "success": True,
534
- "accuracy": accuracy,
535
- "power_injection_mw": power_injection,
536
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537
 
538
  # ------------------------------------------------------------------
539
- # Topology and telemetry getters
540
  # ------------------------------------------------------------------
541
 
542
  def get_topology(self) -> Dict[str, Any]:
543
- """Get the topology graph as a serializable dict."""
544
  nodes = []
545
  for n in self.nodes.values():
546
- nodes.append({
547
  "id": n["id"],
548
  "region": n["region"],
549
  "node_type": n["node_type"],
@@ -551,8 +816,19 @@ class GridEngine:
551
  "peak_load_mw": n["peak_load_mw"],
552
  "critical": n["critical"],
553
  "energized": n["energized"],
554
- })
555
-
 
 
 
 
 
 
 
 
 
 
 
556
  edges = []
557
  for e in self.edges.values():
558
  edges.append({
@@ -560,240 +836,139 @@ class GridEngine:
560
  "source": e["source"],
561
  "target": e["target"],
562
  "capacity_mw": e["capacity_mw"],
563
- "current_load_mw": e["current_load_mw"],
 
 
 
564
  "status": e["status"],
 
565
  })
566
-
567
  return {"nodes": nodes, "edges": edges}
568
 
569
  def get_ground_truth_telemetry(self) -> Dict[str, Dict[str, Any]]:
570
- """Get the true (unspoofed) telemetry for all nodes."""
571
  result = {}
572
  for n in self.nodes.values():
 
 
 
 
 
 
 
573
  result[n["id"]] = {
574
  "node_id": n["id"],
575
- "voltage_kv": n["voltage_kv"],
576
- "frequency_hz": self.frequency_hz if n["energized"] else 0.0,
577
- "generation_mw": n["generation_mw"],
578
- "consumption_mw": n["consumption_mw"],
 
579
  }
580
  return result
581
 
582
  def get_telemetry_history(self) -> List[List[Dict[str, Any]]]:
583
- """Get the last 10 ticks of telemetry history."""
584
- return self.telemetry_history[-10:]
 
 
 
 
 
 
 
585
 
586
  def get_weather(self) -> List[Dict[str, Any]]:
587
- """Get weather forecast as list of zone dicts."""
588
  result = []
589
- for zone_name, data in self.weather.items():
590
- result.append({
591
- "zone": zone_name,
592
  "solar_irradiance": round(data.get("solar_irradiance", 0.5), 3),
593
  "wind_speed_ms": round(data.get("wind_speed_ms", 5.0), 1),
594
  "cloud_cover": round(data.get("cloud_cover", 0.3), 3),
595
- })
 
 
 
596
  return result
597
 
598
  def get_weather_summary(self) -> str:
599
- """Get a natural language weather summary."""
600
  parts = []
601
- for zone_name, data in self.weather.items():
602
  solar = data.get("solar_irradiance", 0.5)
603
  wind = data.get("wind_speed_ms", 5.0)
604
  cloud = data.get("cloud_cover", 0.3)
605
-
606
- if solar > 0.7:
607
- sun_desc = "sunny"
608
- elif solar > 0.3:
609
- sun_desc = "partly cloudy"
610
- else:
611
- sun_desc = "overcast"
612
-
613
- if wind > 15:
614
- wind_desc = "strong winds"
615
- elif wind > 8:
616
- wind_desc = "moderate winds"
617
- else:
618
- wind_desc = "calm"
619
-
620
- parts.append(f"Zone {zone_name}: {sun_desc}, {wind_desc}, {cloud*100:.0f}% cloud cover")
621
-
622
  return "; ".join(parts) if parts else "Weather data unavailable"
623
 
624
  def get_total_generation(self) -> float:
625
- """Get total MW currently being generated."""
 
 
626
  return sum(
627
- n["generation_mw"] for n in self.nodes.values()
628
- if n["node_type"] in ("hydro", "solar", "gas", "battery") and n["energized"]
 
629
  )
630
 
631
  def get_total_load(self) -> float:
632
- """Get total MW demand."""
633
- return sum(
634
- n["consumption_mw"] for n in self.nodes.values()
635
- if n["node_type"] == "load" and n["energized"]
636
- )
 
637
 
638
  def get_total_possible_mwh(self) -> float:
639
- """Get total possible MW·h that could be served."""
640
- return sum(
641
- n["peak_load_mw"] for n in self.nodes.values()
642
- if n["node_type"] == "load"
643
- )
644
 
645
  def get_mwh_served(self) -> float:
646
- """Get actual MW·h served to loads."""
647
- return sum(
648
- n["consumption_mw"] for n in self.nodes.values()
649
- if n["node_type"] == "load" and n["energized"]
650
- )
651
 
652
- def get_critical_nodes_shed(self) -> int:
653
- """Count critical nodes that have been de-energized (load shed)."""
654
- return sum(
655
- 1 for n in self.nodes.values()
656
- if n["critical"] and not n["energized"]
657
- )
658
 
659
- def get_overloaded_edges(self) -> List[str]:
660
- """Get edges loaded at or above 95% capacity."""
661
- return [
662
- e["id"] for e in self.edges.values()
663
- if e["status"] == "LIVE" and e["current_load_mw"] >= 0.95 * e["capacity_mw"]
664
- ]
665
 
666
- def set_forced_edge_load(self, edge_id: str, load_mw: float) -> None:
667
- """Force an edge load after power-flow computation for scenario scripting."""
668
- if edge_id not in self.edges:
669
- raise ValueError(f"Unknown edge: {edge_id}")
670
- self._forced_edge_loads[edge_id] = load_mw
671
- edge = self.edges[edge_id]
672
- if edge["status"] == "LIVE":
673
- edge["current_load_mw"] = load_mw
674
 
675
- def clear_forced_edge_load(self, edge_id: str) -> None:
676
- """Remove a previously forced edge load override."""
677
- self._forced_edge_loads.pop(edge_id, None)
678
 
679
  def is_dispatch_proactive(self) -> bool:
680
- """Check if any dispatch happened before the first frequency drop."""
681
  if not self._dispatch_ticks:
682
  return False
683
  if self._first_frequency_drop_tick is None:
684
- return True # No drop yet, any dispatch is proactive
685
- return min(self._dispatch_ticks) < self._first_frequency_drop_tick
686
 
687
  def get_stable_islands(self) -> List[List[str]]:
688
- """
689
- Find connected components (power islands) of energized nodes.
690
- Returns list of node-id lists.
691
- """
692
- # Build adjacency for live edges between energized nodes
693
- adj: Dict[str, set] = {n_id: set() for n_id in self.nodes if self.nodes[n_id]["energized"]}
694
- for e in self.edges.values():
695
- if e["status"] == "LIVE":
696
- s, t = e["source"], e["target"]
697
- if s in adj and t in adj:
698
- adj[s].add(t)
699
- adj[t].add(s)
700
-
701
- visited: set = set()
702
- islands: List[List[str]] = []
703
- for start in adj:
704
- if start in visited:
705
- continue
706
- component: List[str] = []
707
- stack = [start]
708
- while stack:
709
- node = stack.pop()
710
- if node in visited:
711
- continue
712
- visited.add(node)
713
- component.append(node)
714
- for nb in adj.get(node, []):
715
- if nb not in visited:
716
- stack.append(nb)
717
- if component:
718
- islands.append(sorted(component))
719
-
720
- return islands
721
 
722
  def check_phase_angle_compatible(self, island_a: List[str], island_b: List[str]) -> bool:
723
- """Check if two islands can be merged (|∆phase| ≤ 5°)."""
724
  if not island_a or not island_b:
725
  return False
726
-
727
- # Average phase angle of each island
728
- avg_a = np.mean([self.nodes[n]["phase_angle_deg"] for n in island_a if n in self.nodes])
729
- avg_b = np.mean([self.nodes[n]["phase_angle_deg"] for n in island_b if n in self.nodes])
730
-
731
- diff = abs(avg_a - avg_b)
732
- if diff > 180:
733
- diff = 360 - diff
734
-
735
- return diff <= 5.0
736
-
737
- # ------------------------------------------------------------------
738
- # Internal helpers
739
- # ------------------------------------------------------------------
740
-
741
- def _evolve_weather(self) -> None:
742
- """Evolve weather with small random perturbations."""
743
- for zone in self.weather:
744
- w = self.weather[zone]
745
- # Solar irradiance changes slowly
746
- w["solar_irradiance"] = float(np.clip(
747
- w["solar_irradiance"] + self._rng.normal(0, 0.02), 0.0, 1.0
748
- ))
749
- # Wind speed fluctuates
750
- w["wind_speed_ms"] = float(np.clip(
751
- w["wind_speed_ms"] + self._rng.normal(0, 0.5), 0.0, 30.0
752
- ))
753
- # Cloud cover
754
- w["cloud_cover"] = float(np.clip(
755
- w["cloud_cover"] + self._rng.normal(0, 0.03), 0.0, 1.0
756
- ))
757
-
758
- def _update_renewable_generation(self) -> None:
759
- """Update solar and wind generation based on current weather."""
760
- for node in self.nodes.values():
761
- if not node["energized"]:
762
- continue
763
- region = node["region"]
764
- if region not in self.weather:
765
- continue
766
- w = self.weather[region]
767
-
768
- if node["node_type"] == "solar":
769
- # Solar output = capacity * irradiance * (1 - cloud_cover)
770
- solar_factor = w["solar_irradiance"] * (1.0 - w["cloud_cover"] * 0.7)
771
- node["generation_mw"] = node["capacity_mw"] * solar_factor
772
-
773
- # Wind can affect frequency stability (not modeled as wind turbines here)
774
-
775
- def _evolve_load(self) -> None:
776
- """Small random load fluctuations each tick."""
777
- for node in self.nodes.values():
778
- if node["node_type"] == "load" and node["energized"]:
779
- fluctuation = float(self._rng.normal(0, node["peak_load_mw"] * 0.01))
780
- node["consumption_mw"] = max(
781
- 0.0,
782
- min(node["peak_load_mw"], node["consumption_mw"] + fluctuation)
783
- )
784
-
785
- def _record_telemetry(self) -> None:
786
- """Record current telemetry snapshot to history."""
787
- snapshot = []
788
- for n in self.nodes.values():
789
- snapshot.append({
790
- "node_id": n["id"],
791
- "voltage_kv": n["voltage_kv"],
792
- "frequency_hz": self.frequency_hz if n["energized"] else 0.0,
793
- "generation_mw": n["generation_mw"],
794
- "consumption_mw": n["consumption_mw"],
795
  })
796
- self.telemetry_history.append(snapshot)
797
- # Keep only last 10
798
- if len(self.telemetry_history) > 10:
799
- self.telemetry_history = self.telemetry_history[-10:]
 
1
  """
2
  NexusGrid — Physical Grid Engine (Layer 1).
3
 
4
+ A 20-bus transmission network solved with a linear DC power flow
5
+ (Kirchhoff B-matrix) on every electrical island.
6
+
7
+ Physics summary
8
+ ---------------
9
+ * Every energized island is solved independently. Injections are balanced by
10
+ primary frequency response: the setpoint mismatch is shared by governor-
11
+ responsive units (hydro, gas, battery) in proportion to their capacity.
12
+ * Line flows come from solving ``B θ = P`` with a reference bus per island,
13
+ so flows obey Kirchhoff's current and voltage laws.
14
+ * Island frequency follows the setpoint mismatch through an effective
15
+ stiffness ``K = 0.25 MW/Hz per MW of online dispatchable capacity`` with
16
+ first-order inertia smoothing once per tick.
17
+ * Protection relays trip lines that stay above 100 % loading for three ticks
18
+ or exceed 140 % at the end of a tick. Under-frequency load shedding (UFLS)
19
+ acts below 59.2 Hz and an island collapses outside 58.8–61.2 Hz.
20
+
21
+ All randomness comes from ``numpy.random.Generator(PCG64(seed))`` streams so
22
+ identical seeds give identical trajectories.
23
  """
24
 
25
  from __future__ import annotations
26
 
27
  import math
28
+ from collections import deque
29
  from typing import Any, Dict, List, Optional, Tuple
30
 
31
  import numpy as np
32
 
33
+ DISPATCHABLE_TYPES = ("hydro", "gas", "battery")
34
+ GENERATOR_TYPES = ("hydro", "solar", "gas", "battery")
 
 
35
 
36
+ DEFAULT_RAMP_MW = {"hydro": 250.0, "gas": 150.0, "battery": None, "solar": None}
37
 
 
 
 
38
 
39
+ class GridEngine:
40
+ """DC power-flow grid simulator with islands, frequency and protection."""
 
 
41
 
 
42
  NOMINAL_FREQUENCY_HZ = 60.0
43
+ STIFFNESS_PER_MW = 0.25 # MW/Hz of stiffness per MW of online dispatchable capacity
44
+ MIN_STIFFNESS = 50.0 # MW/Hz floor for tiny islands
45
+ INERTIA_ALPHA = 0.6 # fraction of the gap to the target closed per tick
46
+ TICK_HOURS = 5.0 / 60.0 # one tick is five simulated minutes
47
+
48
+ UFLS_THRESHOLD_HZ = 59.2
49
+ UFLS_STEP = 0.10 # fraction of non-critical demand shed per UFLS stage
50
+ UFLS_MAX = 0.50
51
+ COLLAPSE_LOW_HZ = 58.8
52
+ COLLAPSE_HIGH_HZ = 61.2
53
+
54
+ OVERLOAD_TRIP_TICKS = 3 # consecutive ticks above 100 % before the relay trips
55
+ INSTANT_TRIP_LOADING = 1.40 # loading that trips the relay at the end of a tick
56
+
57
+ BASE_MVA = 100.0
58
+ REACTANCE_800MW = 0.02 # per-unit reactance of an 800 MW line
59
 
60
  def __init__(self, seed: int = 42):
61
+ self._seed = int(seed)
62
+ self._rng = np.random.Generator(np.random.PCG64(self._seed))
63
+ self._noise_rng = np.random.Generator(np.random.PCG64(self._seed + 7_919))
64
  self.tick = 0
65
 
 
 
 
66
  self.nodes: Dict[str, Dict[str, Any]] = {}
 
 
67
  self.edges: Dict[str, Dict[str, Any]] = {}
68
 
69
+ # System frequency (the island with the most demand), plus per-island state
70
  self.frequency_hz: float = self.NOMINAL_FREQUENCY_HZ
71
+ self.frequency_offset_hz: float = 0.0 # external oscillation added on top (attacks)
72
+ self._island_of: Dict[str, int] = {}
73
+ self._islands: List[List[str]] = []
74
+ self._island_target_hz: Dict[int, float] = {}
75
+ self._island_mismatch_mw: Dict[int, float] = {}
76
 
77
+ self.telemetry_history: deque = deque(maxlen=10)
 
 
 
78
  self.weather: Dict[str, Dict[str, float]] = {}
79
+ self.weather_forecast: Dict[str, List[float]] = {}
80
+ self.demand_forecast: List[float] = []
81
+ self.solar_forecast: List[float] = []
82
 
 
83
  self._counter_signals: List[Dict[str, Any]] = []
 
 
84
  self._dispatch_ticks: List[int] = []
85
  self._first_frequency_drop_tick: Optional[int] = None
86
+ self.events: List[Dict[str, Any]] = []
87
+ self.event_log: List[Dict[str, Any]] = []
88
+ self.measurement_noise_mw = 0.5
 
 
 
 
 
 
 
 
 
 
89
 
90
  # ------------------------------------------------------------------
91
  # Topology builders
 
102
  generation_mw: float = 0.0,
103
  consumption_mw: float = 0.0,
104
  black_start_capable: bool = False,
105
+ ramp_mw_per_tick: Optional[float] = None,
106
+ energy_mwh: Optional[float] = None,
107
  ) -> None:
108
+ """Add a substation (bus) to the grid."""
109
+ if ramp_mw_per_tick is None:
110
+ ramp_mw_per_tick = DEFAULT_RAMP_MW.get(node_type) or capacity_mw
111
+ is_battery = node_type == "battery"
112
+ max_energy = energy_mwh if energy_mwh is not None else (2.0 * capacity_mw if is_battery else 0.0)
113
  self.nodes[node_id] = {
114
  "id": node_id,
115
  "node_type": node_type,
116
+ "capacity_mw": float(capacity_mw),
117
+ "peak_load_mw": float(peak_load_mw),
118
  "region": region,
119
+ "critical": bool(critical),
120
+ # Generation: setpoint is what the operator commanded, actual is what flows.
121
+ "setpoint_mw": float(generation_mw),
122
+ "generation_mw": float(generation_mw),
123
+ "available_mw": float(capacity_mw), # solar availability / derates
124
+ "lost_mw": 0.0, # hidden physical loss (attacks, faults)
125
+ "compromised": False, # controller under attacker influence
126
+ "ramp_mw_per_tick": float(ramp_mw_per_tick),
127
+ "energy_mwh": float(max_energy * 0.8) if is_battery else 0.0,
128
+ "max_energy_mwh": float(max_energy),
129
+ # Load
130
+ "demand_mw": float(consumption_mw),
131
+ "consumption_mw": float(consumption_mw),
132
+ "base_consumption_mw": float(consumption_mw),
133
+ "shed_mw": 0.0,
134
+ "ufls_fraction": 0.0,
135
+ # Electrical state
136
  "voltage_kv": 345.0,
137
  "phase_angle_deg": 0.0,
138
  "energized": True,
139
  "quarantined": False,
140
+ "tripped": False,
141
+ "black_start_capable": bool(black_start_capable),
142
+ "frequency_hz": self.NOMINAL_FREQUENCY_HZ,
143
  }
144
 
145
  def add_edge(
 
148
  source: str,
149
  target: str,
150
  capacity_mw: float,
151
+ reactance: Optional[float] = None,
152
  ) -> None:
153
+ """Add a transmission line. Reactance defaults to scale inversely with rating."""
154
+ if reactance is None:
155
+ reactance = self.REACTANCE_800MW * (800.0 / max(capacity_mw, 1.0))
156
  self.edges[edge_id] = {
157
  "id": edge_id,
158
  "source": source,
159
  "target": target,
160
+ "capacity_mw": float(capacity_mw),
161
+ "reactance": float(reactance),
162
+ "flow_mw": 0.0,
163
  "current_load_mw": 0.0,
164
+ "loading": 0.0,
165
  "status": "LIVE",
166
+ "overload_ticks": 0,
167
+ "out_of_service": False, # damaged or under maintenance: cannot be closed
168
+ "outage_reason": None,
169
  }
170
 
171
+ # ------------------------------------------------------------------
172
+ # Dispatch helpers
173
+ # ------------------------------------------------------------------
 
 
 
 
 
 
174
 
175
+ def balance_dispatch(self, reserve_fraction: float = 0.0) -> None:
176
  """
177
+ Set dispatchable setpoints so generation matches demand (economic dispatch).
178
 
179
+ Solar runs at availability, batteries stay on standby, and the remaining
180
+ demand is shared by hydro and gas units in proportion to capacity.
181
+ ``reserve_fraction`` leaves that share of every unit's capacity unused.
182
  """
183
+ demand = sum(n["demand_mw"] for n in self.nodes.values() if n["node_type"] == "load" and n["energized"])
184
+ solar = 0.0
185
+ for n in self.nodes.values():
186
+ if n["node_type"] == "solar" and n["energized"]:
187
+ n["setpoint_mw"] = n["capacity_mw"]
188
+ solar += min(n["available_mw"], n["capacity_mw"])
189
+ thermal = [
190
+ n for n in self.nodes.values()
191
+ if n["node_type"] in ("hydro", "gas") and n["energized"] and not n["tripped"]
192
+ ]
193
+ for n in self.nodes.values():
194
+ if n["node_type"] == "battery":
195
+ n["setpoint_mw"] = 0.0
196
+ remaining = max(0.0, demand - solar)
197
+ usable = [(n, n["capacity_mw"] * (1.0 - reserve_fraction) - n["lost_mw"]) for n in thermal]
198
+ total_usable = sum(max(u, 0.0) for _, u in usable)
199
+ for n, usable_mw in usable:
200
+ share = (max(usable_mw, 0.0) / total_usable) if total_usable > 0 else 0.0
201
+ n["setpoint_mw"] = round(min(max(usable_mw, 0.0), remaining * share), 3)
202
+
203
+ def _unit_output_cap(self, node: Dict[str, Any]) -> float:
204
+ """Maximum physical output of a unit right now."""
205
+ if node["node_type"] == "solar":
206
+ return max(0.0, min(node["available_mw"], node["capacity_mw"]))
207
+ if node["node_type"] == "battery" and node["energy_mwh"] <= 1e-6:
208
+ return 0.0
209
+ return node["capacity_mw"]
210
 
211
+ # ------------------------------------------------------------------
212
+ # Core physics
213
+ # ------------------------------------------------------------------
214
 
215
+ def _build_islands(self) -> List[List[str]]:
216
+ """Connected components of the LIVE-line graph (all buses, energized or not)."""
217
+ adjacency: Dict[str, List[str]] = {node_id: [] for node_id in self.nodes}
218
+ for edge in self.edges.values():
219
+ if edge["status"] == "LIVE":
220
+ adjacency[edge["source"]].append(edge["target"])
221
+ adjacency[edge["target"]].append(edge["source"])
222
+ visited: set = set()
223
+ components: List[List[str]] = []
224
+ for start in self.nodes:
225
+ if start in visited:
226
+ continue
227
+ stack, comp = [start], []
228
  while stack:
229
+ cur = stack.pop()
230
+ if cur in visited:
231
  continue
232
+ visited.add(cur)
233
+ comp.append(cur)
234
+ stack.extend(nb for nb in adjacency[cur] if nb not in visited)
235
+ components.append(sorted(comp))
236
+ return components
237
+
238
+ def _recompute_energization(self, components: List[List[str]]) -> List[str]:
239
+ """A component is energized if it holds a running generator or a black-start unit."""
240
+ previously = {nid: n["energized"] for nid, n in self.nodes.items()}
241
+ newly: List[str] = []
242
+ for comp in components:
243
+ powered = any(
244
+ self.nodes[nid]["node_type"] in GENERATOR_TYPES
245
+ and not self.nodes[nid]["tripped"]
246
+ and (self.nodes[nid]["setpoint_mw"] > 0.0 or self.nodes[nid]["black_start_capable"])
247
+ and previously[nid]
248
+ for nid in comp
249
+ ) or any(
250
+ self.nodes[nid]["black_start_capable"] and previously[nid] for nid in comp
251
+ )
252
+ for nid in comp:
253
+ node = self.nodes[nid]
254
+ was = previously[nid]
255
+ node["energized"] = bool(powered)
256
+ if node["energized"] and not was:
257
+ newly.append(nid)
258
+ if node["node_type"] == "load":
259
+ # Cold-load pickup: demand returns at its base value.
260
+ node["demand_mw"] = max(node["demand_mw"], node["base_consumption_mw"])
261
+ node["ufls_fraction"] = 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
  if not node["energized"]:
263
+ node["voltage_kv"] = 0.0
264
  node["phase_angle_deg"] = 0.0
265
+ if node["node_type"] != "load":
266
+ node["generation_mw"] = 0.0
267
+ else:
268
+ node["consumption_mw"] = 0.0
269
+ else:
270
+ node["voltage_kv"] = 345.0
271
+ return newly
272
+
273
+ def _island_stiffness(self, comp: List[str]) -> float:
274
+ cap = sum(
275
+ self.nodes[nid]["capacity_mw"]
276
+ for nid in comp
277
+ if self.nodes[nid]["node_type"] in DISPATCHABLE_TYPES
278
+ and self.nodes[nid]["energized"]
279
+ and not self.nodes[nid]["tripped"]
280
+ )
281
+ return max(self.MIN_STIFFNESS, self.STIFFNESS_PER_MW * cap)
 
 
282
 
283
+ def compute_power_flow(self) -> List[str]:
284
  """
285
+ Solve every island: energization, primary response, DC flows, angles.
286
+
287
+ Returns the list of buses that became energized during this solve.
288
  """
289
+ components = self._build_islands()
290
+ newly = self._recompute_energization(components)
291
 
292
+ self._islands = [comp for comp in components if self.nodes[comp[0]]["energized"]]
293
+ self._island_of = {}
294
+ self._island_target_hz = {}
295
+ self._island_mismatch_mw = {}
 
 
 
 
 
296
 
 
297
  for edge in self.edges.values():
298
+ edge["flow_mw"] = 0.0
299
+ edge["current_load_mw"] = 0.0
300
+ edge["loading"] = 0.0
301
+
302
+ for idx, comp in enumerate(self._islands):
303
+ for nid in comp:
304
+ self._island_of[nid] = idx
305
+ self._solve_island(idx, comp)
306
+ return newly
307
+
308
+ def _solve_island(self, idx: int, comp: List[str]) -> None:
309
+ nodes = self.nodes
310
+ # Loads consume demand minus manual shedding and UFLS.
311
+ demand_total = 0.0
312
+ for nid in comp:
313
+ n = nodes[nid]
314
+ if n["node_type"] == "load":
315
+ served = max(0.0, n["demand_mw"] - n["shed_mw"]) * (1.0 - n["ufls_fraction"])
316
+ n["consumption_mw"] = served
317
+ demand_total += served
318
+
319
+ # Setpoint-side generation (what the operators commanded, limited by physics).
320
+ set_total = 0.0
321
+ responsive: List[str] = []
322
+ for nid in comp:
323
+ n = nodes[nid]
324
+ if n["node_type"] not in GENERATOR_TYPES or n["tripped"]:
325
+ continue
326
+ cap = self._unit_output_cap(n)
327
+ n["setpoint_mw"] = max(0.0, min(n["setpoint_mw"], n["capacity_mw"]))
328
+ effective = max(0.0, min(n["setpoint_mw"], cap) - n["lost_mw"])
329
+ n["generation_mw"] = effective
330
+ set_total += effective
331
+ if n["node_type"] in DISPATCHABLE_TYPES and cap > 0 and not n["compromised"] and n["lost_mw"] <= 0:
332
+ responsive.append(nid)
333
+
334
+ mismatch = set_total - demand_total
335
+ stiffness = self._island_stiffness(comp)
336
+ self._island_mismatch_mw[idx] = mismatch
337
+ self._island_target_hz[idx] = self.NOMINAL_FREQUENCY_HZ + mismatch / stiffness
338
+
339
+ # Primary frequency response: responsive units absorb the mismatch.
340
+ remaining = -mismatch
341
+ active = list(responsive)
342
+ for _ in range(6):
343
+ if abs(remaining) < 1e-6 or not active:
344
+ break
345
+ weight = sum(nodes[nid]["capacity_mw"] for nid in active)
346
+ next_active = []
347
+ spent = 0.0
348
+ for nid in active:
349
+ n = nodes[nid]
350
+ share = remaining * n["capacity_mw"] / weight
351
+ new_out = n["generation_mw"] + share
352
+ cap = self._unit_output_cap(n)
353
+ clipped = min(max(new_out, 0.0), cap)
354
+ spent += clipped - n["generation_mw"]
355
+ n["generation_mw"] = clipped
356
+ if 0.0 < clipped < cap:
357
+ next_active.append(nid)
358
+ remaining -= spent
359
+ active = next_active
360
+ if remaining > 1e-6 and demand_total > 0:
361
+ # Not enough upward response: the shortfall becomes unserved load (brownout).
362
+ scale = max(0.0, (demand_total - remaining) / demand_total)
363
+ for nid in comp:
364
+ if nodes[nid]["node_type"] == "load":
365
+ nodes[nid]["consumption_mw"] *= scale
366
+ elif remaining < -1e-6:
367
+ # Surplus that governors cannot absorb: solar plants curtail automatically.
368
+ solar = [nid for nid in comp if nodes[nid]["node_type"] == "solar" and nodes[nid]["generation_mw"] > 0]
369
+ solar_total = sum(nodes[nid]["generation_mw"] for nid in solar)
370
+ if solar_total > 0:
371
+ cut = min(solar_total, -remaining)
372
+ for nid in solar:
373
+ nodes[nid]["generation_mw"] -= cut * nodes[nid]["generation_mw"] / solar_total
374
+
375
+ # DC power flow on the island.
376
+ live_edges = [
377
+ e for e in self.edges.values()
378
+ if e["status"] == "LIVE" and e["source"] in comp and e["target"] in comp
379
  ]
380
+ if len(comp) < 2 or not live_edges:
381
+ nodes[comp[0]]["phase_angle_deg"] = 0.0
382
  return
383
+ index = {nid: i for i, nid in enumerate(comp)}
384
+ size = len(comp)
385
+ B = np.zeros((size, size))
386
  for e in live_edges:
387
+ i, j = index[e["source"]], index[e["target"]]
388
+ b = 1.0 / e["reactance"]
389
+ B[i, i] += b
390
+ B[j, j] += b
391
+ B[i, j] -= b
392
+ B[j, i] -= b
393
+ P = np.zeros(size)
394
+ for nid in comp:
395
+ n = nodes[nid]
396
+ inj = n["generation_mw"] if n["node_type"] in GENERATOR_TYPES else -n["consumption_mw"]
397
+ P[index[nid]] = inj / self.BASE_MVA
398
+ P -= P.sum() / size # remove numerical residue so the system is consistent
399
+ ref = max(
400
+ comp,
401
+ key=lambda nid: (nodes[nid]["node_type"] in DISPATCHABLE_TYPES, nodes[nid]["capacity_mw"], nid),
402
+ )
403
+ keep = [index[nid] for nid in comp if nid != ref]
404
+ theta = np.zeros(size)
405
+ try:
406
+ theta_red = np.linalg.solve(B[np.ix_(keep, keep)], P[keep])
407
+ except np.linalg.LinAlgError:
408
+ theta_red = np.linalg.lstsq(B[np.ix_(keep, keep)], P[keep], rcond=None)[0]
409
+ theta[keep] = theta_red
410
+ for nid in comp:
411
+ deg = math.degrees(theta[index[nid]])
412
+ nodes[nid]["phase_angle_deg"] = float(((deg + 180.0) % 360.0) - 180.0)
413
+ for e in live_edges:
414
+ flow_pu = (theta[index[e["source"]]] - theta[index[e["target"]]]) / e["reactance"]
415
+ flow = float(flow_pu * self.BASE_MVA)
416
+ e["flow_mw"] = flow
417
+ e["current_load_mw"] = abs(flow)
418
+ e["loading"] = abs(flow) / max(e["capacity_mw"], 1.0)
419
 
420
+ def compute_frequency(self, smooth: bool = True) -> float:
421
  """
422
+ Move each island's frequency toward its target (inertia) and update
423
+ the system frequency, which is the frequency of the island serving
424
+ the most demand.
 
425
  """
426
+ main_idx = self.main_island_index()
427
+ for idx, comp in enumerate(self._islands):
428
+ target = self._island_target_hz.get(idx, self.NOMINAL_FREQUENCY_HZ)
429
+ # Previous frequency: capacity-weighted over buses that were already running.
430
+ weights, values = [], []
431
+ for nid in comp:
432
+ f_prev = self.nodes[nid]["frequency_hz"]
433
+ if f_prev > 1.0:
434
+ weights.append(max(self.nodes[nid]["capacity_mw"], 1.0))
435
+ values.append(f_prev)
436
+ prev = float(np.average(values, weights=weights)) if values else target
437
+ new = prev + self.INERTIA_ALPHA * (target - prev) if smooth else target
438
+ for nid in comp:
439
+ self.nodes[nid]["frequency_hz"] = new
440
+ for nid, n in self.nodes.items():
441
+ if not n["energized"]:
442
+ n["frequency_hz"] = 0.0
443
+ if main_idx is not None:
444
+ base = self.nodes[self._islands[main_idx][0]]["frequency_hz"]
445
+ self.frequency_hz = float(min(62.0, max(58.0, base + self.frequency_offset_hz)))
446
+ else:
447
+ self.frequency_hz = self.NOMINAL_FREQUENCY_HZ
448
+ if self.frequency_hz < 59.8 and self._first_frequency_drop_tick is None:
 
 
 
449
  self._first_frequency_drop_tick = self.tick
 
450
  return self.frequency_hz
451
 
452
+ def settle(self) -> None:
453
+ """Solve the network and snap island frequencies to their targets (used at reset)."""
454
+ self.compute_power_flow()
455
+ for idx, comp in enumerate(self._islands):
456
+ target = self._island_target_hz.get(idx, self.NOMINAL_FREQUENCY_HZ)
457
+ for nid in comp:
458
+ self.nodes[nid]["frequency_hz"] = target
459
+ self.compute_frequency(smooth=False)
460
 
461
+ def advance_tick(self) -> List[Dict[str, Any]]:
462
+ """
463
+ Advance one tick: battery energy, flows, frequency, protection, UFLS,
464
+ island collapse. Returns the events that happened during the tick.
465
+ Scenario schedules (load and solar curves) are applied by the caller
466
+ before this method runs.
467
  """
468
  self.tick += 1
469
+ self.events = []
470
+ self._update_batteries()
471
+ self._update_counter_signals()
472
+ self.compute_power_flow()
473
+ self.compute_frequency(smooth=True)
474
+ self._apply_protection()
475
+ self._apply_frequency_protection()
476
+ self.event_log.extend(self.events)
477
+ return list(self.events)
478
 
479
+ # ------------------------------------------------------------------
480
+ # Protection and dynamics helpers
481
+ # ------------------------------------------------------------------
 
 
 
482
 
483
+ def _update_batteries(self) -> None:
484
+ for n in self.nodes.values():
485
+ if n["node_type"] != "battery" or not n["energized"]:
486
+ continue
487
+ used = n["generation_mw"] * self.TICK_HOURS
488
+ n["energy_mwh"] = max(0.0, n["energy_mwh"] - used)
489
+ if n["energy_mwh"] <= 1e-6 and n["setpoint_mw"] > 0:
490
+ n["setpoint_mw"] = 0.0
491
+ self._event("battery_depleted", node=n["id"])
492
 
493
+ def _update_counter_signals(self) -> None:
494
  for cs in self._counter_signals:
495
  if cs["remaining_ticks"] > 0:
496
  cs["remaining_ticks"] -= 1
497
 
498
+ def _apply_protection(self) -> None:
499
+ tripped_any = False
500
+ for e in self.edges.values():
501
+ if e["status"] != "LIVE":
502
+ e["overload_ticks"] = 0
503
+ continue
504
+ if e["loading"] > 1.0:
505
+ e["overload_ticks"] += 1
506
+ else:
507
+ e["overload_ticks"] = 0
508
+ if e["loading"] >= self.INSTANT_TRIP_LOADING or e["overload_ticks"] >= self.OVERLOAD_TRIP_TICKS:
509
+ self._event("protection_trip", edge=e["id"], loading=round(e["loading"], 3))
510
+ e["status"] = "TRIPPED"
511
+ e["flow_mw"] = 0.0
512
+ e["current_load_mw"] = 0.0
513
+ e["loading"] = 0.0
514
+ e["overload_ticks"] = 0
515
+ tripped_any = True
516
+ if tripped_any:
517
+ self.compute_power_flow()
518
+
519
+ def _apply_frequency_protection(self) -> None:
520
+ changed = False
521
+ for comp in list(self._islands):
522
+ freq = self.nodes[comp[0]]["frequency_hz"]
523
+ if freq < self.COLLAPSE_LOW_HZ or freq > self.COLLAPSE_HIGH_HZ:
524
+ self._collapse_island(comp, freq)
525
+ changed = True
526
+ continue
527
+ if freq < self.UFLS_THRESHOLD_HZ:
528
+ shed_nodes = []
529
+ for nid in comp:
530
+ n = self.nodes[nid]
531
+ if n["node_type"] == "load" and not n["critical"] and n["ufls_fraction"] < self.UFLS_MAX:
532
+ n["ufls_fraction"] = min(self.UFLS_MAX, n["ufls_fraction"] + self.UFLS_STEP)
533
+ shed_nodes.append(nid)
534
+ if shed_nodes:
535
+ self._event("ufls", nodes=shed_nodes, frequency_hz=round(freq, 3))
536
+ changed = True
537
+ if changed:
538
+ self.compute_power_flow()
539
+
540
+ def _collapse_island(self, comp: List[str], freq: float) -> None:
541
+ self._event("island_collapse", nodes=list(comp), frequency_hz=round(freq, 3))
542
+ for nid in comp:
543
+ n = self.nodes[nid]
544
+ if n["node_type"] in GENERATOR_TYPES:
545
+ n["setpoint_mw"] = 0.0
546
+ n["generation_mw"] = 0.0
547
+ n["energized"] = bool(n["black_start_capable"])
548
+ n["frequency_hz"] = self.NOMINAL_FREQUENCY_HZ if n["energized"] else 0.0
549
+ for e in self.edges.values():
550
+ if e["status"] == "LIVE" and e["source"] in comp and e["target"] in comp:
551
+ e["status"] = "TRIPPED"
552
 
553
+ def set_out_of_service(self, edge_id: str, reason: str) -> None:
554
+ """Open a line and lock it out (storm damage, maintenance)."""
555
+ edge = self.edges[edge_id]
556
+ edge["status"] = "TRIPPED"
557
+ edge["out_of_service"] = True
558
+ edge["outage_reason"] = reason
559
 
560
+ def _event(self, kind: str, **data: Any) -> None:
561
+ self.events.append({"type": kind, "tick": self.tick, **data})
562
 
563
  # ------------------------------------------------------------------
564
  # Actions
565
  # ------------------------------------------------------------------
566
 
567
  def dispatch_generation(self, node_id: str, mw: float) -> Dict[str, Any]:
568
+ """Change a unit's setpoint by ``mw`` (ramp-limited)."""
569
  if node_id not in self.nodes:
570
  return {"success": False, "error": f"Unknown node: {node_id}"}
 
571
  node = self.nodes[node_id]
572
+ if node["node_type"] not in GENERATOR_TYPES:
573
+ return {"success": False, "error": f"Node {node_id} is not a generator (use shed_load for loads)"}
 
574
  if not node["energized"]:
575
  return {"success": False, "error": f"Node {node_id} is not energized"}
576
+ if node["tripped"]:
577
+ return {"success": False, "error": f"Node {node_id} has tripped offline"}
578
+ if node["quarantined"]:
579
+ return {"success": False, "error": f"Node {node_id} control channel is quarantined"}
580
+ mw = float(mw)
581
+ ramp = node["ramp_mw_per_tick"]
582
+ clipped = max(-ramp, min(ramp, mw))
583
+ old = node["setpoint_mw"]
584
+ new = max(0.0, min(node["capacity_mw"], old + clipped))
585
+ node["setpoint_mw"] = new
586
  self._dispatch_ticks.append(self.tick)
 
 
587
  self.compute_power_flow()
588
+ return {
589
+ "success": True,
590
+ "old_setpoint_mw": round(old, 3),
591
+ "new_setpoint_mw": round(new, 3),
592
+ "new_generation_mw": round(new, 3),
593
+ "ramp_limited": abs(clipped - mw) > 1e-9,
594
+ }
595
 
596
+ def shed_load(self, node_id: str, mw: float) -> Dict[str, Any]:
597
+ """
598
+ Shed (mw > 0) or restore (mw < 0) demand at a load.
599
+
600
+ Restoring first returns manually shed MW, then load that under-frequency
601
+ relays (UFLS) disconnected. Critical loads cannot be shed manually.
602
+ """
603
+ if node_id not in self.nodes:
604
+ return {"success": False, "error": f"Unknown node: {node_id}"}
605
+ node = self.nodes[node_id]
606
+ if node["node_type"] != "load":
607
+ return {"success": False, "error": f"Node {node_id} is not a load (use dispatch_generation for generators)"}
608
+ mw = float(mw)
609
+ if mw > 0 and node["critical"]:
610
+ return {"success": False, "error": f"Node {node_id} is critical infrastructure and cannot be shed"}
611
+ old_shed, old_ufls = node["shed_mw"], node["ufls_fraction"]
612
+ if mw >= 0:
613
+ node["shed_mw"] = max(0.0, min(node["demand_mw"], old_shed + mw))
614
+ else:
615
+ restore = -mw
616
+ from_manual = min(restore, node["shed_mw"])
617
+ node["shed_mw"] -= from_manual
618
+ restore -= from_manual
619
+ if restore > 0 and node["ufls_fraction"] > 0 and node["demand_mw"] > 0:
620
+ node["ufls_fraction"] = max(0.0, node["ufls_fraction"] - restore / node["demand_mw"])
621
+ self.compute_power_flow()
622
+ return {
623
+ "success": True,
624
+ "old_shed_mw": round(old_shed, 3),
625
+ "new_shed_mw": round(node["shed_mw"], 3),
626
+ "old_ufls_pct": round(100.0 * old_ufls, 1),
627
+ "new_ufls_pct": round(100.0 * node["ufls_fraction"], 1),
628
+ }
629
 
630
  def toggle_circuit_breaker(self, edge_id: str, status: str) -> Dict[str, Any]:
631
+ """Open or close a line. Closing between islands requires synchronism."""
632
  if edge_id not in self.edges:
633
  return {"success": False, "error": f"Unknown edge: {edge_id}"}
634
+ status = str(status).upper()
 
635
  if status not in ("OPEN", "CLOSED"):
636
  return {"success": False, "error": f"Invalid status: {status}. Use OPEN or CLOSED."}
637
+ edge = self.edges[edge_id]
638
  old_status = edge["status"]
639
+ pre_islands = self.get_stable_islands()
640
+ result: Dict[str, Any] = {"success": True, "old_status": old_status}
 
 
 
641
  if status == "OPEN":
642
  edge["status"] = "TRIPPED"
643
+ edge["overload_ticks"] = 0
644
  else:
645
+ if edge["out_of_service"]:
646
+ result.update({"success": False, "new_status": edge["status"],
647
+ "error": f"{edge_id} is out of service ({edge['outage_reason']}) and cannot be closed"})
648
+ return result
649
+ sync = self.check_synchronism(edge["source"], edge["target"])
650
+ result["sync_check"] = sync
651
+ if sync["merging"] and not sync["in_sync"]:
652
+ # Out-of-phase closure: the breaker recloses open and damages equipment.
653
+ self._event("out_of_phase_close", edge=edge_id, **{k: v for k, v in sync.items() if k != "merging"})
654
+ result.update({"new_status": edge["status"], "out_of_phase": True,
655
+ "error": "Breaker reopened: islands were not synchronised"})
656
+ result["success"] = False
657
+ return result
658
  edge["status"] = "LIVE"
659
+ newly = self.compute_power_flow()
660
+ post_islands = self.get_stable_islands()
661
+ result.update({
 
 
 
 
 
 
 
 
 
 
662
  "new_status": edge["status"],
663
+ "newly_energized_nodes": newly,
664
+ "island_count_before": len(pre_islands),
665
+ "island_count_after": len(post_islands),
666
+ })
667
+ return result
668
 
669
+ def check_synchronism(self, a: str, b: str) -> Dict[str, Any]:
670
+ """Synchronism check across a breaker between buses ``a`` and ``b``."""
671
+ ia, ib = self._island_of.get(a), self._island_of.get(b)
672
+ if ia is None or ib is None or ia == ib:
673
+ return {"merging": False, "in_sync": True}
674
+ fa = self.nodes[a]["frequency_hz"]
675
+ fb = self.nodes[b]["frequency_hz"]
676
+ da = abs(self.nodes[a]["phase_angle_deg"] - self.nodes[b]["phase_angle_deg"])
677
+ da = min(da, 360.0 - da)
678
+ in_sync = abs(fa - fb) <= 0.20 and da <= 20.0
679
+ return {"merging": True, "in_sync": in_sync, "delta_hz": round(abs(fa - fb), 4), "delta_deg": round(da, 3)}
680
+
681
+ def run_state_estimation(self, subgraph: List[str], reported: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
682
  """
683
+ Kirchhoff current-law consistency check.
684
 
685
+ For every bus in ``subgraph`` the injection implied by the metered line
686
+ flows is compared with the injection reported by SCADA telemetry
687
+ (generation - consumption). Residuals above 15 MW are violations.
688
  """
689
+ residuals: Dict[str, float] = {}
690
+ worst: Tuple[Optional[str], float] = (None, 0.0)
691
+ for nid in subgraph:
692
+ n = self.nodes.get(nid)
693
+ if n is None or not n["energized"]:
694
  continue
695
+ implied = 0.0
696
+ for e in self.edges.values():
697
+ if e["status"] != "LIVE":
698
+ continue
699
+ if e["source"] == nid:
700
+ implied += e["flow_mw"]
701
+ elif e["target"] == nid:
702
+ implied -= e["flow_mw"]
703
+ rep = reported.get(nid, {})
704
+ rep_inj = float(rep.get("generation_mw", 0.0)) - float(rep.get("consumption_mw", 0.0))
705
+ if self._island_size(nid) < 2:
706
+ true_inj = (n["generation_mw"] if n["node_type"] in GENERATOR_TYPES else -n["consumption_mw"])
707
+ implied = true_inj
708
+ residual = rep_inj - implied
709
+ residuals[nid] = round(residual, 2)
710
+ if abs(residual) > abs(worst[1]):
711
+ worst = (nid, residual)
712
+ violation = worst[0] if abs(worst[1]) > 15.0 else None
713
+ if violation is None:
714
+ return {"consistent": True, "violation_node": None, "estimated_true_mw": 0.0,
715
+ "residual_mw": round(worst[1], 2), "residuals": residuals, "checked_nodes": list(residuals)}
716
+ n = self.nodes[violation]
717
+ reported_mw = float(reported.get(violation, {}).get("generation_mw", n["generation_mw"]))
 
 
 
 
718
  return {
719
+ "consistent": False,
720
+ "violation_node": violation,
721
+ "estimated_true_mw": round(n["generation_mw"], 2),
722
+ "reported_mw": round(reported_mw, 2),
723
+ "residual_mw": round(worst[1], 2),
724
+ "residuals": residuals,
725
+ "checked_nodes": list(residuals),
726
  }
727
 
728
+ def _island_size(self, nid: str) -> int:
729
+ idx = self._island_of.get(nid)
730
+ return len(self._islands[idx]) if idx is not None else 0
731
+
732
  def quarantine_node(self, node_id: str) -> Dict[str, Any]:
733
+ """Isolate a bus's SCADA channel; its telemetry is replaced by estimator values."""
734
  if node_id not in self.nodes:
735
  return {"success": False, "error": f"Unknown node: {node_id}"}
 
736
  if self.nodes[node_id]["quarantined"]:
737
+ return {"success": False, "error": f"Node {node_id} is already quarantined", "already_quarantined": True}
 
 
 
 
 
738
  self.nodes[node_id]["quarantined"] = True
739
  return {"success": True, "node_id": node_id, "already_quarantined": False}
740
 
741
+ def inject_counter_signal(self, node_id: str, hz_offset: float, duration: int) -> Dict[str, Any]:
742
+ """Start a damping counter-signal from a battery (effect handled by the attack model)."""
 
 
 
 
 
 
 
743
  if node_id not in self.nodes:
744
  return {"success": False, "error": f"Unknown node: {node_id}"}
 
745
  node = self.nodes[node_id]
746
  if node["node_type"] != "battery":
747
  return {"success": False, "error": f"Node {node_id} is not a battery"}
748
  if not node["energized"]:
749
  return {"success": False, "error": f"Node {node_id} is not energized"}
750
+ if node["energy_mwh"] <= 1e-6:
751
+ return {"success": False, "error": f"Battery {node_id} is depleted"}
752
+ signal = {
753
+ "node_id": node_id,
754
+ "hz_offset": float(hz_offset),
755
+ "duration": int(duration),
756
+ "remaining_ticks": int(duration),
757
+ "start_tick": self.tick,
758
+ }
759
+ self._counter_signals.append(signal)
760
+ return {"success": True, "node_id": node_id, "hz_offset": float(hz_offset), "duration": int(duration)}
761
 
762
+ def active_counter_signals(self) -> List[Dict[str, Any]]:
763
+ return [cs for cs in self._counter_signals if cs["remaining_ticks"] > 0]
 
 
 
 
764
 
765
+ # ------------------------------------------------------------------
766
+ # Graph helpers
767
+ # ------------------------------------------------------------------
 
 
 
 
 
 
768
 
769
+ def hop_distance(self, a: str, b: str, live_only: bool = True) -> int:
770
+ """Number of line hops between two buses (large number if disconnected)."""
771
+ if a == b:
772
+ return 0
773
+ adjacency: Dict[str, List[str]] = {nid: [] for nid in self.nodes}
774
+ for e in self.edges.values():
775
+ if live_only and e["status"] != "LIVE":
776
+ continue
777
+ adjacency[e["source"]].append(e["target"])
778
+ adjacency[e["target"]].append(e["source"])
779
+ frontier, seen, dist = [a], {a}, 0
780
+ while frontier:
781
+ dist += 1
782
+ nxt = []
783
+ for cur in frontier:
784
+ for nb in adjacency[cur]:
785
+ if nb == b:
786
+ return dist
787
+ if nb not in seen:
788
+ seen.add(nb)
789
+ nxt.append(nb)
790
+ frontier = nxt
791
+ return 99
792
+
793
+ def main_island_index(self) -> Optional[int]:
794
+ best, best_demand = None, -1.0
795
+ for idx, comp in enumerate(self._islands):
796
+ demand = sum(self.nodes[nid]["consumption_mw"] for nid in comp if self.nodes[nid]["node_type"] == "load")
797
+ gen = sum(self.nodes[nid]["generation_mw"] for nid in comp if self.nodes[nid]["node_type"] in GENERATOR_TYPES)
798
+ key = demand + 1e-3 * gen
799
+ if key > best_demand:
800
+ best, best_demand = idx, key
801
+ return best
802
 
803
  # ------------------------------------------------------------------
804
+ # Getters
805
  # ------------------------------------------------------------------
806
 
807
  def get_topology(self) -> Dict[str, Any]:
808
+ """Operator's single-line view (never spoofed)."""
809
  nodes = []
810
  for n in self.nodes.values():
811
+ item = {
812
  "id": n["id"],
813
  "region": n["region"],
814
  "node_type": n["node_type"],
 
816
  "peak_load_mw": n["peak_load_mw"],
817
  "critical": n["critical"],
818
  "energized": n["energized"],
819
+ "black_start_capable": n["black_start_capable"],
820
+ "quarantined": n["quarantined"],
821
+ }
822
+ if n["node_type"] in GENERATOR_TYPES:
823
+ item["setpoint_mw"] = round(n["setpoint_mw"], 2)
824
+ item["ramp_mw_per_tick"] = n["ramp_mw_per_tick"]
825
+ item["tripped"] = n["tripped"]
826
+ if n["node_type"] == "battery":
827
+ item["soc_pct"] = round(100.0 * n["energy_mwh"] / n["max_energy_mwh"], 1) if n["max_energy_mwh"] else 0.0
828
+ if n["node_type"] == "load":
829
+ item["shed_mw"] = round(n["shed_mw"], 2)
830
+ item["ufls_shed_pct"] = round(100.0 * n["ufls_fraction"], 1)
831
+ nodes.append(item)
832
  edges = []
833
  for e in self.edges.values():
834
  edges.append({
 
836
  "source": e["source"],
837
  "target": e["target"],
838
  "capacity_mw": e["capacity_mw"],
839
+ "reactance_pu": round(e["reactance"], 5),
840
+ "current_load_mw": round(min(e["current_load_mw"], 5000.0), 2),
841
+ "flow_mw": round(e["flow_mw"], 2),
842
+ "loading_pct": round(100.0 * e["loading"], 1),
843
  "status": e["status"],
844
+ "out_of_service": e["out_of_service"],
845
  })
 
846
  return {"nodes": nodes, "edges": edges}
847
 
848
  def get_ground_truth_telemetry(self) -> Dict[str, Dict[str, Any]]:
849
+ """True SCADA readings with small measurement noise (deterministic per seed)."""
850
  result = {}
851
  for n in self.nodes.values():
852
+ noise_g = float(self._noise_rng.normal(0.0, self.measurement_noise_mw))
853
+ noise_c = float(self._noise_rng.normal(0.0, self.measurement_noise_mw))
854
+ noise_f = float(self._noise_rng.normal(0.0, 0.002))
855
+ gen = n["generation_mw"] if n["node_type"] in GENERATOR_TYPES else 0.0
856
+ cons = n["consumption_mw"] if n["node_type"] == "load" else 0.0
857
+ energized = n["energized"]
858
+ freq = n["frequency_hz"] + self.frequency_offset_hz if energized else 0.0
859
  result[n["id"]] = {
860
  "node_id": n["id"],
861
+ "voltage_kv": 345.0 if energized else 0.0,
862
+ "frequency_hz": round(min(62.0, max(0.0, freq + (noise_f if energized else 0.0))), 4),
863
+ "phase_angle_deg": round(n["phase_angle_deg"], 2) if energized else 0.0,
864
+ "generation_mw": round(max(0.0, gen + (noise_g if gen > 0 else 0.0)), 2),
865
+ "consumption_mw": round(max(0.0, cons + (noise_c if cons > 0 else 0.0)), 2),
866
  }
867
  return result
868
 
869
  def get_telemetry_history(self) -> List[List[Dict[str, Any]]]:
870
+ return [list(snapshot) for snapshot in self.telemetry_history]
871
+
872
+ def push_telemetry_snapshot(self, snapshot: List[Dict[str, Any]]) -> None:
873
+ """Record a (possibly spoofed) telemetry snapshot for the observation history."""
874
+ self.telemetry_history.append(snapshot)
875
+
876
+ def _record_telemetry(self) -> None:
877
+ """Kept for compatibility; snapshots are recorded by the environment."""
878
+ return None
879
 
880
  def get_weather(self) -> List[Dict[str, Any]]:
 
881
  result = []
882
+ for zone, data in self.weather.items():
883
+ item = {
884
+ "zone": zone,
885
  "solar_irradiance": round(data.get("solar_irradiance", 0.5), 3),
886
  "wind_speed_ms": round(data.get("wind_speed_ms", 5.0), 1),
887
  "cloud_cover": round(data.get("cloud_cover", 0.3), 3),
888
+ }
889
+ if zone in self.weather_forecast:
890
+ item["irradiance_forecast"] = [round(v, 3) for v in self.weather_forecast[zone]]
891
+ result.append(item)
892
  return result
893
 
894
  def get_weather_summary(self) -> str:
 
895
  parts = []
896
+ for zone, data in self.weather.items():
897
  solar = data.get("solar_irradiance", 0.5)
898
  wind = data.get("wind_speed_ms", 5.0)
899
  cloud = data.get("cloud_cover", 0.3)
900
+ sun = "sunny" if solar > 0.7 else ("partly cloudy" if solar > 0.3 else "overcast")
901
+ wind_desc = "strong winds" if wind > 15 else ("moderate winds" if wind > 8 else "calm")
902
+ parts.append(f"Zone {zone}: {sun}, {wind_desc}, {cloud * 100:.0f}% cloud cover")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
903
  return "; ".join(parts) if parts else "Weather data unavailable"
904
 
905
  def get_total_generation(self) -> float:
906
+ return sum(n["generation_mw"] for n in self.nodes.values() if n["node_type"] in GENERATOR_TYPES and n["energized"])
907
+
908
+ def get_total_setpoint(self) -> float:
909
  return sum(
910
+ max(0.0, min(n["setpoint_mw"], self._unit_output_cap(n)) - n["lost_mw"])
911
+ for n in self.nodes.values()
912
+ if n["node_type"] in GENERATOR_TYPES and n["energized"] and not n["tripped"]
913
  )
914
 
915
  def get_total_load(self) -> float:
916
+ return sum(n["consumption_mw"] for n in self.nodes.values() if n["node_type"] == "load" and n["energized"])
917
+
918
+ def get_total_demand(self) -> float:
919
+ """Demand of all loads, energized or not (what customers want)."""
920
+ return sum(n["demand_mw"] if n["energized"] else n["base_consumption_mw"]
921
+ for n in self.nodes.values() if n["node_type"] == "load")
922
 
923
  def get_total_possible_mwh(self) -> float:
924
+ return sum(n["peak_load_mw"] for n in self.nodes.values() if n["node_type"] == "load")
 
 
 
 
925
 
926
  def get_mwh_served(self) -> float:
927
+ return self.get_total_load()
 
 
 
 
928
 
929
+ def get_served_fraction(self) -> float:
930
+ demand = self.get_total_demand()
931
+ return self.get_total_load() / demand if demand > 0 else 0.0
 
 
 
932
 
933
+ def get_critical_nodes_shed(self) -> int:
934
+ return sum(1 for n in self.nodes.values() if n["critical"] and not n["energized"])
 
 
 
 
935
 
936
+ def get_overloaded_edges(self, threshold: float = 1.0) -> List[str]:
937
+ return [e["id"] for e in self.edges.values() if e["status"] == "LIVE" and e["loading"] > threshold]
 
 
 
 
 
 
938
 
939
+ def get_max_loading(self) -> float:
940
+ live = [e["loading"] for e in self.edges.values() if e["status"] == "LIVE"]
941
+ return max(live) if live else 0.0
942
 
943
  def is_dispatch_proactive(self) -> bool:
 
944
  if not self._dispatch_ticks:
945
  return False
946
  if self._first_frequency_drop_tick is None:
947
+ return True
948
+ return min(self._dispatch_ticks) <= self._first_frequency_drop_tick
949
 
950
  def get_stable_islands(self) -> List[List[str]]:
951
+ """Energized islands (lists of bus IDs)."""
952
+ return [list(comp) for comp in self._islands]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
953
 
954
  def check_phase_angle_compatible(self, island_a: List[str], island_b: List[str]) -> bool:
 
955
  if not island_a or not island_b:
956
  return False
957
+ fa = self.nodes[island_a[0]]["frequency_hz"]
958
+ fb = self.nodes[island_b[0]]["frequency_hz"]
959
+ return abs(fa - fb) <= 0.20
960
+
961
+ def get_island_summary(self) -> List[Dict[str, Any]]:
962
+ summary = []
963
+ for idx, comp in enumerate(self._islands):
964
+ gen = sum(self.nodes[n]["generation_mw"] for n in comp if self.nodes[n]["node_type"] in GENERATOR_TYPES)
965
+ load = sum(self.nodes[n]["consumption_mw"] for n in comp if self.nodes[n]["node_type"] == "load")
966
+ summary.append({
967
+ "island": idx,
968
+ "nodes": list(comp),
969
+ "frequency_hz": round(self.nodes[comp[0]]["frequency_hz"], 4),
970
+ "generation_mw": round(gen, 2),
971
+ "load_mw": round(load, 2),
972
+ "setpoint_mismatch_mw": round(self._island_mismatch_mw.get(idx, 0.0), 2),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
973
  })
974
+ return summary
 
 
 
server/nexusgrid_environment.py CHANGED
@@ -1,597 +1,616 @@
1
  """
2
- NexusGrid-CyberPhysEnv — Core Environment Implementation.
3
 
4
- Full OpenEnv-compliant environment: step() / reset() / state().
5
- Wires together: GridEngine + SpoofEngine + RewardCalculator + Graders.
 
 
 
 
 
 
6
  """
7
 
8
  from __future__ import annotations
9
 
10
- from typing import Any, Dict, List, Optional
11
  from uuid import uuid4
12
 
13
  try:
14
  from openenv.core.env_server.interfaces import Environment
15
  from openenv.core.env_server.types import State
16
- except ImportError:
17
- class Environment: # type: ignore[override]
18
- """Lightweight fallback for local testing without openenv-core."""
19
 
20
- class State: # type: ignore[override]
21
- def __init__(self, episode_id: str, step_count: int):
22
  self.episode_id = episode_id
23
  self.step_count = step_count
 
 
 
 
 
 
 
24
 
25
  try:
26
- from ..models import GridAction, GridObservation, ActionType
27
  except ImportError:
28
- from models import GridAction, GridObservation, ActionType
29
 
 
30
  from .grid_engine import GridEngine
31
- from .scenarios import build_scenario, MAX_TICKS, TASK_NAMES
32
- from .spoof_engine import SpoofEngine
33
  from .reward import RewardCalculator
34
- from .graders import grade_task
35
  from .rubric import evaluate_task_rubrics
 
 
36
  from .training_logger import TrainingLogger
37
 
 
 
 
38
 
39
- class NexusgridEnvironment(Environment):
40
- """
41
- NexusGrid-CyberPhysEnv: National power grid defense under cyber-physical attack.
 
 
 
 
 
42
 
43
- A 20-node transmission network with DC power flow physics running alongside
44
- a deterministic SCADA sensor spoofing engine. The agent must distinguish
45
- real grid failures from adversarially fabricated telemetry.
46
 
47
- OpenEnv API:
48
- reset(seed) → GridObservation (initial state)
49
- step(action) → GridObservation (with reward, done, info embedded)
50
- state → GridState (full internal state for debugging)
51
- """
52
 
53
  SUPPORTS_CONCURRENT_SESSIONS: bool = True
54
 
55
- def __init__(self):
56
- """Initialize with default state."""
57
  self._episode_id = str(uuid4())
58
  self._seed = 42
59
  self._task_id = 0
60
  self._tick = 0
61
  self._done = False
62
- self._total_reward = 0.0
63
- self._max_ticks = 3
64
-
65
- # Core engines
66
  self._engine: Optional[GridEngine] = None
67
  self._spoof: Optional[SpoofEngine] = None
 
68
  self._reward_calc = RewardCalculator()
69
-
70
- # Action history for grading
71
  self._action_history: List[Dict[str, Any]] = []
 
 
72
 
73
- # Frequency history for grading
74
- self._frequency_history: List[float] = []
 
75
 
76
- # Spoofed telemetry cache
77
- self._current_spoofed_telemetry: Dict[str, Dict] = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
- # Attack config from scenario
80
- self._attack_config: Dict[str, Any] = {}
 
 
 
 
 
81
 
82
- # State estimation tracking
83
- self._state_estimation_run = False
84
- self._last_estimation_result: Optional[Dict] = None
 
 
 
85
 
86
- # Black Start tracking
87
- self._hydro_stable_ticks = 0
88
- self._max_island_count = 0
89
- self._successful_mergers = 0
90
- self._premature_mergers = 0
91
- self._transformer_failures = 0
92
- self._full_restoration_tick: Optional[int] = None
93
 
94
- # Track if packet logs have been "read" (agent called advance_tick to observe)
95
- self._logs_read_this_episode = False
96
- self._logs_read_before_estimation = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
- # Internal OpenEnv state
99
- self._state = State(episode_id=self._episode_id, step_count=0)
 
100
 
101
- def reset(self, seed: int = None, task_id: int = None, **kwargs) -> GridObservation:
102
- """
103
- Reset the environment for a new episode.
 
 
 
 
 
 
 
 
104
 
105
- Args:
106
- seed: Episode seed for reproducibility. Defaults to 42.
107
- task_id: Which task to run (0-5). Can also be passed in kwargs.
108
 
109
- Returns:
110
- Initial GridObservation with all fields freshly computed.
111
- """
112
- # Handle task_id from kwargs (OpenEnv may pass it there)
113
- if task_id is None:
114
- task_id = kwargs.get("task_id", self._task_id)
115
- if seed is None:
116
- seed = kwargs.get("seed", 42)
117
 
118
- self._seed = seed
119
- self._task_id = task_id
120
- self._tick = 0
121
- self._done = False
122
- self._total_reward = 0.0
123
- self._episode_id = str(uuid4())
124
- self._action_history = []
125
- self._frequency_history = []
126
- self._state_estimation_run = False
127
- self._last_estimation_result = None
128
- self._logs_read_this_episode = False
129
- self._logs_read_before_estimation = False
130
- self._full_restoration_tick = None
131
-
132
- # Black Start tracking
133
- self._hydro_stable_ticks = 0
134
- self._max_island_count = 0
135
- self._successful_mergers = 0
136
- self._premature_mergers = 0
137
- self._transformer_failures = 0
138
-
139
- # Build scenario
140
- scenario = build_scenario(task_id, seed)
141
- self._engine = scenario["engine"]
142
- self._max_ticks = scenario["max_ticks"]
143
- self._attack_config = scenario.get("attack_config", {})
144
-
145
- # Initialize spoof engine
146
- self._spoof = SpoofEngine(seed)
147
- if self._attack_config:
148
- self._spoof.configure_attack(self._attack_config)
149
-
150
- # Initialize reward calculator
151
- self._reward_calc = RewardCalculator()
152
 
153
- # Record initial frequency
154
- self._frequency_history.append(self._engine.frequency_hz)
 
155
 
156
- # Generate initial telemetry (may be spoofed)
157
- ground_truth = self._engine.get_ground_truth_telemetry()
158
- self._current_spoofed_telemetry = self._spoof.apply_spoofs(ground_truth, self._tick)
159
 
160
- # Update OpenEnv state
161
- self._state = State(episode_id=self._episode_id, step_count=0)
 
162
 
163
- return self._build_observation()
 
 
164
 
165
- def step(self, action: GridAction) -> GridObservation:
166
- """
167
- Execute an action in the environment.
168
 
169
- Returns GridObservation with reward, done, and info embedded.
170
- """
171
- if self._done:
172
- return self._build_observation(error="Episode already finished")
173
 
174
- if self._engine is None:
175
- return self._build_observation(error="Environment not initialized. Call reset() first.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
- # Parse the action
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  action_type = action.action_type.value if isinstance(action.action_type, ActionType) else str(action.action_type)
179
- action_record = {
180
  "action_type": action_type,
181
  "tick": self._tick,
182
  "node_id": action.node_id,
183
  "edge_id": action.edge_id,
184
  "mw": action.mw,
185
  "status": action.status,
186
- "subgraph": action.subgraph,
187
  "hz_offset": action.hz_offset,
188
  "duration": action.duration,
189
  }
 
 
 
190
 
191
- error_msg = None
192
- fault_isolated = False
193
- spoof_detected = False
194
- pre_islands = self._engine.get_stable_islands() if self._task_id == 5 else []
195
-
196
- # Execute the action
197
  if action_type == "dispatch_generation":
198
  if not action.node_id or action.mw is None:
199
- error_msg = "dispatch_generation requires node_id and mw"
200
  else:
201
- result = self._engine.dispatch_generation(action.node_id, action.mw)
202
- if not result["success"]:
203
- error_msg = result.get("error", "dispatch failed")
204
- action_record["result"] = result
205
-
 
206
  elif action_type == "toggle_circuit_breaker":
207
  if not action.edge_id or not action.status:
208
- error_msg = "toggle_circuit_breaker requires edge_id and status"
209
  else:
210
- result = self._engine.toggle_circuit_breaker(action.edge_id, action.status)
211
- if not result["success"]:
212
- error_msg = result.get("error", "toggle failed")
213
- else:
214
- if action.status == "OPEN" and result.get("old_status") == "LIVE":
215
- fault_isolated = True
216
- elif action.status == "CLOSED":
217
- self._track_black_start_merger(action.edge_id, pre_islands)
218
- action_record["result"] = result
219
-
220
  elif action_type == "run_state_estimation":
221
- if not action.subgraph:
222
- error_msg = "run_state_estimation requires subgraph (list of node IDs)"
223
- else:
224
- result = self._engine.run_state_estimation(
225
- action.subgraph,
226
- self._current_spoofed_telemetry,
227
- )
228
- self._state_estimation_run = True
229
- self._last_estimation_result = result
230
- action_record["result"] = result
231
-
232
- if not result.get("consistent", True):
233
- spoof_detected = True
234
-
235
- elif action_type == "quarantine_scada_node":
236
- if not action.node_id:
237
- error_msg = "quarantine_scada_node requires node_id"
238
  else:
239
- # Check anti-hallucination gate
240
- if not self._state_estimation_run:
241
- error_msg = "Must run state_estimation before quarantine (anti-hallucination penalty applies)"
242
- result = {
243
- "success": False,
244
- "error": error_msg,
245
- "skipped": True,
246
- }
247
  else:
248
- result = self._engine.quarantine_node(action.node_id)
249
- if result.get("success"):
250
- self._spoof.quarantine_node(action.node_id)
251
-
252
- if self._last_estimation_result and not self._last_estimation_result.get("consistent", True):
253
- if result.get("success") and not result.get("already_quarantined", False):
254
- spoof_detected = True
255
-
256
- action_record["result"] = result
257
-
258
  elif action_type == "inject_counter_signal":
259
  if not action.node_id or action.hz_offset is None or action.duration is None:
260
- error_msg = "inject_counter_signal requires node_id, hz_offset, duration"
261
  else:
262
- result = self._engine.inject_counter_signal(
263
- action.node_id, action.hz_offset, action.duration
264
- )
265
- if not result["success"]:
266
- error_msg = result.get("error", "injection failed")
267
- action_record["result"] = result
268
-
269
  elif action_type == "advance_tick":
270
- # Advance simulation (weather, load, frequency)
271
- self._engine.advance_tick()
272
- self._spoof.advance_tick()
273
- self._logs_read_this_episode = True # Agent observes packet logs
274
- if not self._state_estimation_run:
275
- self._logs_read_before_estimation = True
276
-
277
- # Apply resonance effect if active
278
- if self._spoof.is_resonance_active():
279
- resonance_effect = self._spoof.get_resonance_effect(self._tick)
280
- self._engine.frequency_hz += resonance_effect
281
- self._engine.frequency_hz = max(58.0, min(62.0, self._engine.frequency_hz))
282
-
283
  else:
284
- error_msg = f"Unknown action type: {action_type}"
285
-
286
- if action_type != "advance_tick":
287
- self._engine._record_telemetry()
288
-
289
- # Record action
290
- self._action_history.append(action_record)
291
-
292
- # Advance tick counter
293
- self._tick += 1
294
-
295
- # Update spoofed telemetry
296
- ground_truth = self._engine.get_ground_truth_telemetry()
297
- self._current_spoofed_telemetry = self._spoof.apply_spoofs(ground_truth, self._tick)
298
-
299
- # Generate packet logs
300
- all_node_ids = list(self._engine.nodes.keys())
301
- self._spoof.generate_packet_logs(all_node_ids, self._tick)
302
-
303
- # Compute reward
304
- reward_breakdown = self._reward_calc.compute_tick_reward(
305
- action_type=action_type,
306
- action_params={
307
- "subgraph": action.subgraph or [],
308
- "node_id": action.node_id,
309
- "mw": action.mw,
310
- },
311
- frequency_hz=self._engine.frequency_hz,
312
- overloaded_edges=self._engine.get_overloaded_edges(),
313
- critical_nodes_shed=self._engine.get_critical_nodes_shed(),
314
- is_proactive=self._engine.is_dispatch_proactive(),
315
- spoof_detected=spoof_detected,
316
- fault_isolated=fault_isolated,
317
- has_read_logs_before_estimation=(
318
- self._logs_read_this_episode
319
- and action_type == "run_state_estimation"
320
- ),
321
- )
322
-
323
- tick_reward = reward_breakdown["total"]
324
- self._total_reward += tick_reward
325
-
326
- # Record frequency
327
- self._frequency_history.append(self._engine.frequency_hz)
328
-
329
- # Update Black Start tracking
330
- self._update_black_start_tracking()
331
- self._update_full_restoration_tracking()
332
-
333
- # Check termination conditions
334
- if self._engine.frequency_hz < 59.0:
335
- self._done = True
336
- if self._tick >= self._max_ticks:
337
- self._done = True
338
-
339
- # Task 4 special: turbine destruction
340
- if self._task_id == 4:
341
- destruction_tick = self._attack_config.get("destruction_tick", 10)
342
- if self._tick >= destruction_tick and self._spoof.is_resonance_active():
343
- self._done = True # Turbine destroyed
344
-
345
- # Update OpenEnv state
346
- self._state = State(episode_id=self._episode_id, step_count=self._tick)
347
-
348
- return self._build_observation(
349
- reward=tick_reward,
350
- error=error_msg,
351
- reward_breakdown=reward_breakdown,
352
- )
353
-
354
- @property
355
- def state(self) -> State:
356
- """Get current OpenEnv state."""
357
- return self._state
358
 
359
  # ------------------------------------------------------------------
360
- # Grading
361
  # ------------------------------------------------------------------
362
 
363
- def get_score(self) -> float:
364
- """Get the final grader score for the current episode."""
365
- episode_state = self._build_episode_state()
366
- return grade_task(self._task_id, self._action_history, episode_state)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
 
368
  # ------------------------------------------------------------------
369
- # Internal helpers
370
  # ------------------------------------------------------------------
371
 
372
- def _build_observation(
373
- self,
374
- reward: float = 0.0,
375
- error: Optional[str] = None,
376
- reward_breakdown: Optional[Dict] = None,
377
- ) -> GridObservation:
378
- """Build a GridObservation from current engine state."""
379
- if self._engine is None:
380
- return GridObservation(done=True, last_action_error="Not initialized")
381
-
382
- # Build telemetry from spoofed readings for current tick
383
- current_telemetry = []
384
- for node_id, readings in self._current_spoofed_telemetry.items():
385
- current_telemetry.append(readings)
386
-
387
- # Telemetry history (includes spoofed values)
388
- telemetry_stream = self._engine.get_telemetry_history()
389
-
390
- # Add info dict fields
391
- info = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  "task_id": self._task_id,
393
  "tick": self._tick,
394
- "grid_frequency_hz": self._engine.frequency_hz,
395
- "active_spoofs": self._spoof.get_active_spoofs() if self._spoof else [],
396
- "last_kirchhoff_result": self._last_estimation_result,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
397
  "episode_seed": self._seed,
398
- "reward_breakdown": reward_breakdown or {},
399
- "rubric_breakdown": self.get_rubric_breakdown(),
400
- "curriculum_ready": True,
 
401
  }
402
  if self._done:
403
- info["episode_summary"] = self.get_episode_summary()
404
-
405
- obs = GridObservation(
406
- topology_graph=self._engine.get_topology(),
407
- telemetry_stream=telemetry_stream,
408
- weather_forecast_matrix=self._engine.get_weather(),
409
- network_packet_logs=self._spoof.get_recent_packet_logs() if self._spoof else [],
410
- grid_frequency_hz=self._engine.frequency_hz,
411
  tick=self._tick,
412
  task_id=self._task_id,
413
  done=self._done,
414
- reward=reward,
415
  last_action_error=error,
416
- last_state_estimation=self._last_estimation_result,
417
- weather_summary=self._engine.get_weather_summary(),
418
- metadata=info,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
419
  )
420
 
421
- return obs
422
-
423
- def _build_episode_state(self) -> Dict[str, Any]:
424
- """Build episode state dict for grading."""
425
- if self._engine is None:
426
- return {}
427
-
428
- # Compute load restoration fraction
429
- total_possible = self._engine.get_total_possible_mwh()
430
- total_served = self._engine.get_mwh_served()
431
- load_fraction = total_served / total_possible if total_possible > 0 else 0.0
432
-
433
- # Check if all critical nodes are restored
434
- critical_nodes = [n for n in self._engine.nodes.values() if n["critical"]]
435
- critical_restored = all(n["energized"] for n in critical_nodes)
436
- recovered_above_59_5_in_3_ticks = _check_recovery(self._frequency_history, threshold=59.5, window=3)
437
-
438
- return {
439
- "frequency_history": self._frequency_history,
440
- "is_proactive_dispatch": self._engine.is_dispatch_proactive(),
441
- "critical_nodes_shed": self._engine.get_critical_nodes_shed(),
442
- "full_restoration_tick": self._get_full_restoration_tick(),
443
- "load_restored_fraction": load_fraction,
444
- "hydro_stable_ticks": self._hydro_stable_ticks,
445
- "energized_node_count": sum(
446
- 1 for n in self._engine.nodes.values() if n["energized"]
447
- ),
448
- "max_island_count": self._max_island_count,
449
- "successful_mergers": self._successful_mergers,
450
- "premature_mergers": self._premature_mergers,
451
- "transformer_failures": self._transformer_failures,
452
- "critical_nodes_restored": critical_restored,
453
- "logs_read_before_estimation": self._logs_read_before_estimation,
454
- "spoof_target": self._attack_config.get("target_node"),
455
- "recovered_above_59_5_in_3_ticks": recovered_above_59_5_in_3_ticks,
456
- }
457
-
458
- def _track_black_start_merger(self, edge_id: str, pre_islands: List[List[str]]) -> None:
459
- """Record Task 5 island merger outcomes when a breaker is closed."""
460
- if self._task_id != 5 or self._engine is None:
461
- return
462
-
463
- edge = self._engine.edges.get(edge_id)
464
- if edge is None:
465
- return
466
-
467
- def find_island(node_id: str) -> Optional[List[str]]:
468
- for island in pre_islands:
469
- if node_id in island:
470
- return island
471
- return None
472
-
473
- source_island = find_island(edge["source"])
474
- target_island = find_island(edge["target"])
475
-
476
- if not source_island or not target_island or source_island == target_island:
477
- return
478
-
479
- if self._engine.check_phase_angle_compatible(source_island, target_island):
480
- self._successful_mergers += 1
481
- else:
482
- self._premature_mergers += 1
483
- self._transformer_failures += 1
484
-
485
- def _update_black_start_tracking(self) -> None:
486
- """Track Black Start milestones for Task 5 grading."""
487
- if self._task_id != 5 or self._engine is None:
488
- return
489
-
490
- # Track hydro stability
491
- hydro = self._engine.nodes.get("NODE_01")
492
- if hydro and hydro["energized"] and hydro["generation_mw"] > 0:
493
- self._hydro_stable_ticks += 1
494
- else:
495
- self._hydro_stable_ticks = 0
496
-
497
- # Track island count
498
- islands = self._engine.get_stable_islands()
499
- self._max_island_count = max(self._max_island_count, len(islands))
500
-
501
- def _update_full_restoration_tracking(self) -> None:
502
- """Persist the first tick where load restoration crosses the grading threshold."""
503
- if self._engine is None or self._full_restoration_tick is not None:
504
- return
505
-
506
- if self._task_id == 2:
507
- isolation_ticks = [
508
- action.get("tick", 999)
509
- for action in self._action_history
510
- if action.get("action_type") == "toggle_circuit_breaker"
511
- and str(action.get("status", "")).upper() == "OPEN"
512
- ]
513
- fault_isolated = bool(isolation_ticks)
514
- first_isolation_tick = min(isolation_ticks) if isolation_ticks else None
515
- restorative_dispatches = sum(
516
- 1
517
- for action in self._action_history
518
- if action.get("action_type") == "dispatch_generation"
519
- and (action.get("mw") or 0) > 0
520
- and first_isolation_tick is not None
521
- and action.get("tick", 999) > first_isolation_tick
522
- )
523
- frequency_stable = (
524
- len(self._frequency_history) >= 2
525
- and all(freq >= 59.7 for freq in self._frequency_history[-2:])
526
- )
527
- if (
528
- fault_isolated
529
- and restorative_dispatches >= 2
530
- and frequency_stable
531
- and not self._engine.get_overloaded_edges()
532
- and self._engine.get_critical_nodes_shed() == 0
533
- ):
534
- self._full_restoration_tick = self._tick
535
- return
536
-
537
- total_possible = self._engine.get_total_possible_mwh()
538
- total_served = self._engine.get_mwh_served()
539
- if total_possible > 0 and total_served >= total_possible * 0.95:
540
- self._full_restoration_tick = self._tick
541
-
542
- def _get_full_restoration_tick(self) -> Optional[int]:
543
- """Get the tick at which full load was restored (for Task 2)."""
544
- return self._full_restoration_tick
545
-
546
- def get_rubric_breakdown(self) -> Dict[str, Any]:
547
- """Return the current rubric breakdown for the active episode."""
548
- return evaluate_task_rubrics(self._task_id, self._action_history, self._build_episode_state())
549
-
550
- def get_episode_summary(self) -> Dict[str, Any]:
551
- """Build a compact summary suitable for training logs and dashboards."""
552
- rubric_eval = self.get_rubric_breakdown()
553
- frequency_history = self._frequency_history or [60.0]
554
- return {
555
- "task_id": self._task_id,
556
- "task_name": TASK_NAMES.get(self._task_id, f"task_{self._task_id}"),
557
- "seed": self._seed,
558
- "score": self.get_score(),
559
- "rubrics": rubric_eval["rubrics"],
560
- "weighted_rubric_score": rubric_eval["weighted_score"],
561
- "actions_taken": [action.get("action_type", "unknown") for action in self._action_history],
562
- "frequency_min": min(frequency_history),
563
- "ticks_used": self._tick,
564
- "done": self._done,
565
- }
566
-
567
- def emit_training_log(self, episode: int, logger: Optional[TrainingLogger] = None) -> str:
568
- """Write the current episode summary as one JSONL line."""
569
- summary = self.get_episode_summary()
570
- training_logger = logger or TrainingLogger()
571
- record = training_logger.build_record(
572
- episode=episode,
573
  task_id=self._task_id,
 
574
  seed=self._seed,
575
- score=summary["score"],
576
- rubrics=summary["rubrics"],
577
- actions_taken=summary["actions_taken"],
578
- frequency_min=summary["frequency_min"],
579
- ticks_used=summary["ticks_used"],
580
- extra={"task_name": summary["task_name"], "done": summary["done"]},
581
  )
582
- return training_logger.write_episode(record)
583
-
584
 
585
- def _check_recovery(freq_history: List[float], threshold: float, window: int) -> bool:
586
- """Check if frequency recovered above threshold within `window` ticks after dipping."""
587
- dip_started = False
588
- ticks_since_dip = 0
589
- for freq in freq_history:
590
- if freq < threshold:
591
- dip_started = True
592
- ticks_since_dip = 0
593
- elif dip_started:
594
- ticks_since_dip += 1
595
- if freq >= threshold and ticks_since_dip <= window:
596
- return True
597
- return False
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ NexusGrid-CyberPhysEnv — Core Environment.
3
 
4
+ OpenEnv-compliant ``reset()`` / ``step()`` / ``state``. Every ``step`` applies
5
+ one operator action and then advances the simulation by one tick (five
6
+ minutes): scenario schedule, attack physics, DC power flow, frequency,
7
+ protection relays and SCADA telemetry.
8
+
9
+ Hidden information (attack target, oscillation mode, hidden MW) never appears
10
+ in observations. It is used for grading and is available to local tooling
11
+ through :meth:`NexusgridEnvironment.debug_state`.
12
  """
13
 
14
  from __future__ import annotations
15
 
16
+ from typing import Any, Dict, List, Optional, Tuple
17
  from uuid import uuid4
18
 
19
  try:
20
  from openenv.core.env_server.interfaces import Environment
21
  from openenv.core.env_server.types import State
22
+ except ImportError: # pragma: no cover - lightweight fallback without openenv-core
23
+ class Environment: # type: ignore[no-redef]
24
+ """Fallback base class for local use without openenv-core."""
25
 
26
+ class State: # type: ignore[no-redef]
27
+ def __init__(self, episode_id: str = "", step_count: int = 0, **kwargs: Any):
28
  self.episode_id = episode_id
29
  self.step_count = step_count
30
+ for key, value in kwargs.items():
31
+ setattr(self, key, value)
32
+
33
+ try:
34
+ from openenv.core.env_server.types import EnvironmentMetadata
35
+ except ImportError: # pragma: no cover - older openenv-core releases
36
+ EnvironmentMetadata = None # type: ignore[assignment]
37
 
38
  try:
39
+ from ..models import ActionType, GridAction, GridObservation
40
  except ImportError:
41
+ from models import ActionType, GridAction, GridObservation
42
 
43
+ from .graders import grade_task
44
  from .grid_engine import GridEngine
 
 
45
  from .reward import RewardCalculator
 
46
  from .rubric import evaluate_task_rubrics
47
+ from .scenarios import MAX_TICKS, TASK_DIFFICULTIES, TASK_NAMES, build_scenario
48
+ from .spoof_engine import SpoofEngine
49
  from .training_logger import TrainingLogger
50
 
51
+ ENV_VERSION = "3.0.0"
52
+ MAX_ESTIMATION_BUSES = 6
53
+ COLLAPSE_TERMINATION_HZ = 59.0
54
 
55
+ # Forced-oscillation model (Task 4)
56
+ DAMPING_CORRECT = 0.40 # amplitude multiplier per tick with a matched counter-signal
57
+ DAMPING_PARTIAL = 0.90 # amplitude multiplier with a roughly matched counter-signal
58
+ DECAY_NEUTRALIZED = 0.30 # amplitude multiplier once the mode is neutralised
59
+ NEUTRALIZE_BELOW_HZ = 0.10 # amplitude below which a detuned unit is neutralised
60
+ DETUNE_FRACTION = 0.80 # setpoint must be at or below 80 % of the pre-attack value
61
+ COUNTER_SIGNAL_MAX_HOPS = 2
62
+ PMU_PROPAGATION = 0.5 # share of the amplitude seen one hop further away
63
 
 
 
 
64
 
65
+ class NexusgridEnvironment(Environment):
66
+ """National power-grid defence under cyber-physical attack."""
 
 
 
67
 
68
  SUPPORTS_CONCURRENT_SESSIONS: bool = True
69
 
70
+ def __init__(self) -> None:
 
71
  self._episode_id = str(uuid4())
72
  self._seed = 42
73
  self._task_id = 0
74
  self._tick = 0
75
  self._done = False
76
+ self._max_ticks = MAX_TICKS[0]
 
 
 
77
  self._engine: Optional[GridEngine] = None
78
  self._spoof: Optional[SpoofEngine] = None
79
+ self._scenario: Dict[str, Any] = {}
80
  self._reward_calc = RewardCalculator()
 
 
81
  self._action_history: List[Dict[str, Any]] = []
82
+ self._reset_trackers()
83
+ self._state = State(episode_id=self._episode_id, step_count=0)
84
 
85
+ # ------------------------------------------------------------------
86
+ # OpenEnv API
87
+ # ------------------------------------------------------------------
88
 
89
+ def reset(self, seed: Optional[int] = None, episode_id: Optional[str] = None,
90
+ task_id: Optional[int] = None, **kwargs: Any) -> GridObservation:
91
+ """Start a new episode of ``task_id`` (0-5) drawn from ``seed``."""
92
+ task_id = self._task_id if task_id is None else int(task_id)
93
+ if task_id not in MAX_TICKS:
94
+ raise ValueError(f"task_id must be 0-5, got {task_id}")
95
+ self._seed = 42 if seed is None else int(seed)
96
+ self._task_id = task_id
97
+ self._tick = 0
98
+ self._done = False
99
+ self._episode_id = episode_id or str(uuid4())
100
+ self._action_history = []
101
+ self._reset_trackers()
102
+
103
+ self._scenario = build_scenario(task_id, self._seed)
104
+ self._engine = self._scenario["engine"]
105
+ self._max_ticks = int(self._scenario["max_ticks"])
106
+ self._attack = dict(self._scenario.get("attack_config") or {})
107
+ self._spoof = SpoofEngine(self._seed)
108
+ if self._attack:
109
+ self._spoof.configure_attack(self._attack)
110
+ if self._attack.get("type") == "resonance_oscillation":
111
+ self._pre_attack_setpoint = float(self._engine.nodes[self._attack["target_node"]]["setpoint_mw"])
112
 
113
+ self._reward_calc = RewardCalculator()
114
+ self._capture_telemetry()
115
+ self._spoof.generate_packet_logs(list(self._engine.nodes), self._tick)
116
+ self._record_histories()
117
+ self._score_prev = self._current_score()
118
+ self._state = self._make_state()
119
+ return self._build_observation()
120
 
121
+ def step(self, action: GridAction, timeout_s: Optional[float] = None, **kwargs: Any) -> GridObservation:
122
+ """Apply one action, then advance the simulation by one tick."""
123
+ if self._engine is None:
124
+ return GridObservation(done=True, last_action_error="Environment not initialised. Call reset() first.")
125
+ if self._done:
126
+ return self._build_observation(error="Episode already finished")
127
 
128
+ record, error, action_events = self._apply_action(action)
129
+ self._action_history.append(record)
 
 
 
 
 
130
 
131
+ self._tick += 1
132
+ self._spoof.advance_tick()
133
+ self._scenario["schedule"].apply(self._engine, self._tick)
134
+ attack_events = self._update_attacks()
135
+ physics_events = self._engine.advance_tick()
136
+ self._tick_events = action_events + attack_events + physics_events
137
+ self._all_events.extend(self._tick_events)
138
+ self._capture_telemetry()
139
+ self._spoof.generate_packet_logs(list(self._engine.nodes), self._tick)
140
+ self._record_histories()
141
+ self._check_termination()
142
+
143
+ score_now = self._current_score()
144
+ breakdown = self._reward_calc.compute_tick_reward(
145
+ score_now=score_now,
146
+ score_prev=self._score_prev,
147
+ frequency_hz=self._engine.frequency_hz,
148
+ overloaded_count=len(self._engine.get_overloaded_edges(1.0)),
149
+ events=self._tick_events,
150
+ invalid_action=error is not None,
151
+ )
152
+ self._score_prev = score_now
153
+ self._state = self._make_state()
154
+ return self._build_observation(reward=breakdown["total"], error=error, reward_breakdown=breakdown)
155
 
156
+ @property
157
+ def state(self) -> State:
158
+ return self._state
159
 
160
+ def get_metadata(self): # type: ignore[override]
161
+ if EnvironmentMetadata is None:
162
+ return {"name": "NexusGrid-CyberPhysEnv", "version": ENV_VERSION}
163
+ return EnvironmentMetadata(
164
+ name="NexusGrid-CyberPhysEnv",
165
+ description=("Power-grid operations benchmark: DC power flow, protection relays, seeded "
166
+ "cyber-physical attacks and six graded operator tasks."),
167
+ version=ENV_VERSION,
168
+ author="Abinesh Senthilkumar",
169
+ documentation_url="https://github.com/AbineshSenthil/NexusGrid-CyberPhysEnv",
170
+ )
171
 
172
+ def close(self) -> None: # pragma: no cover - nothing to release
173
+ return None
 
174
 
175
+ # ------------------------------------------------------------------
176
+ # Grading API (in-process)
177
+ # ------------------------------------------------------------------
 
 
 
 
 
178
 
179
+ @property
180
+ def task_id(self) -> int:
181
+ return self._task_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
 
183
+ @property
184
+ def seed(self) -> int:
185
+ return self._seed
186
 
187
+ @property
188
+ def done(self) -> bool:
189
+ return self._done
190
 
191
+ @property
192
+ def engine(self) -> Optional[GridEngine]:
193
+ return self._engine
194
 
195
+ @property
196
+ def action_history(self) -> List[Dict[str, Any]]:
197
+ return list(self._action_history)
198
 
199
+ def get_score(self) -> float:
200
+ """Final grade for the episode so far, treating it as finished."""
201
+ return grade_task(self._task_id, self._action_history, self._build_episode_state(force_done=True))
202
 
203
+ def get_rubric_breakdown(self, force_done: bool = False) -> Dict[str, Any]:
204
+ return evaluate_task_rubrics(self._task_id, self._action_history, self._build_episode_state(force_done))
 
 
205
 
206
+ def get_episode_summary(self) -> Dict[str, Any]:
207
+ rubric_eval = self.get_rubric_breakdown(force_done=True)
208
+ freqs = self._frequency_history or [60.0]
209
+ return {
210
+ "task_id": self._task_id,
211
+ "task_name": TASK_NAMES[self._task_id],
212
+ "seed": self._seed,
213
+ "split": self._scenario.get("split"),
214
+ "score": self.get_score(),
215
+ "rubrics": rubric_eval["rubrics"],
216
+ "weighted_rubric_score": rubric_eval["weighted_score"],
217
+ "total_reward": round(self._reward_calc.total_reward, 6),
218
+ "actions_taken": [a.get("action_type", "unknown") for a in self._action_history],
219
+ "invalid_actions": sum(1 for a in self._action_history if a.get("error")),
220
+ "frequency_min": min(freqs),
221
+ "frequency_max": max(freqs),
222
+ "ticks_used": self._tick,
223
+ "events": [e["type"] for e in self._all_events],
224
+ "done": self._done,
225
+ }
226
+
227
+ def emit_training_log(self, episode: int, logger: Optional[TrainingLogger] = None) -> str:
228
+ summary = self.get_episode_summary()
229
+ training_logger = logger or TrainingLogger()
230
+ record = training_logger.build_record(
231
+ episode=episode,
232
+ task_id=self._task_id,
233
+ seed=self._seed,
234
+ score=summary["score"],
235
+ rubrics=summary["rubrics"],
236
+ actions_taken=summary["actions_taken"],
237
+ frequency_min=summary["frequency_min"],
238
+ ticks_used=summary["ticks_used"],
239
+ extra={"task_name": summary["task_name"], "done": summary["done"]},
240
+ )
241
+ return training_logger.write_episode(record)
242
 
243
+ def debug_state(self) -> Dict[str, Any]:
244
+ """Hidden scenario details for dashboards and tests (never sent to agents)."""
245
+ return {
246
+ "task_id": self._task_id,
247
+ "seed": self._seed,
248
+ "split": self._scenario.get("split"),
249
+ "params": dict(self._scenario.get("params", {})),
250
+ "attack": dict(self._attack),
251
+ "active_spoofs": self._spoof.get_active_spoofs(self._tick) if self._spoof else [],
252
+ "hidden_loss_mw": round(self._hidden_loss_mw, 3),
253
+ "resonance_amplitude_hz": round(self._resonance_amplitude, 5),
254
+ "attack_neutralized": self._attack_neutralized,
255
+ "turbine_destroyed": self._turbine_destroyed,
256
+ "quarantine_tick": self._quarantine_tick,
257
+ "refused_quarantines": self._refused_quarantines,
258
+ }
259
+
260
+ # ------------------------------------------------------------------
261
+ # Actions
262
+ # ------------------------------------------------------------------
263
+
264
+ def _apply_action(self, action: GridAction) -> Tuple[Dict[str, Any], Optional[str], List[Dict[str, Any]]]:
265
+ engine = self._engine
266
  action_type = action.action_type.value if isinstance(action.action_type, ActionType) else str(action.action_type)
267
+ record: Dict[str, Any] = {
268
  "action_type": action_type,
269
  "tick": self._tick,
270
  "node_id": action.node_id,
271
  "edge_id": action.edge_id,
272
  "mw": action.mw,
273
  "status": action.status,
274
+ "subgraph": list(action.subgraph) if action.subgraph else None,
275
  "hz_offset": action.hz_offset,
276
  "duration": action.duration,
277
  }
278
+ events_before = len(engine.events)
279
+ error: Optional[str] = None
280
+ result: Optional[Dict[str, Any]] = None
281
 
 
 
 
 
 
 
282
  if action_type == "dispatch_generation":
283
  if not action.node_id or action.mw is None:
284
+ error = "dispatch_generation requires node_id and mw"
285
  else:
286
+ result = engine.dispatch_generation(action.node_id, action.mw)
287
+ elif action_type == "shed_load":
288
+ if not action.node_id or action.mw is None:
289
+ error = "shed_load requires node_id and mw"
290
+ else:
291
+ result = engine.shed_load(action.node_id, action.mw)
292
  elif action_type == "toggle_circuit_breaker":
293
  if not action.edge_id or not action.status:
294
+ error = "toggle_circuit_breaker requires edge_id and status"
295
  else:
296
+ result = engine.toggle_circuit_breaker(action.edge_id, action.status)
 
 
 
 
 
 
 
 
 
297
  elif action_type == "run_state_estimation":
298
+ subgraph = list(dict.fromkeys(action.subgraph or []))
299
+ if not subgraph:
300
+ error = "run_state_estimation requires subgraph (a list of node IDs)"
301
+ elif len(subgraph) > MAX_ESTIMATION_BUSES:
302
+ error = f"run_state_estimation is limited to {MAX_ESTIMATION_BUSES} buses per call"
 
 
 
 
 
 
 
 
 
 
 
 
303
  else:
304
+ unknown = [nid for nid in subgraph if nid not in engine.nodes]
305
+ if unknown:
306
+ error = f"Unknown node(s) in subgraph: {', '.join(unknown)}"
 
 
 
 
 
307
  else:
308
+ result = engine.run_state_estimation(subgraph, self._reported)
309
+ self._last_estimation = result
310
+ if not result.get("consistent", True) and result.get("violation_node"):
311
+ self._flagged_nodes.add(result["violation_node"])
312
+ elif action_type == "quarantine_scada_node":
313
+ result, error = self._quarantine(action.node_id)
 
 
 
 
314
  elif action_type == "inject_counter_signal":
315
  if not action.node_id or action.hz_offset is None or action.duration is None:
316
+ error = "inject_counter_signal requires node_id, hz_offset and duration"
317
  else:
318
+ result = engine.inject_counter_signal(action.node_id, action.hz_offset, action.duration)
 
 
 
 
 
 
319
  elif action_type == "advance_tick":
320
+ result = {"success": True}
 
 
 
 
 
 
 
 
 
 
 
 
321
  else:
322
+ error = f"Unknown action type: {action_type}"
323
+
324
+ if result is not None:
325
+ record["result"] = result
326
+ if not result.get("success", True) and error is None:
327
+ error = result.get("error", "action failed")
328
+ if error:
329
+ record["error"] = error
330
+ action_events = list(engine.events[events_before:])
331
+ engine.event_log.extend(action_events)
332
+ return record, error, action_events
333
+
334
+ def _quarantine(self, node_id: Optional[str]) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
335
+ if not node_id:
336
+ return None, "quarantine_scada_node requires node_id"
337
+ if node_id not in self._engine.nodes:
338
+ return None, f"Unknown node: {node_id}"
339
+ if node_id not in self._flagged_nodes:
340
+ self._refused_quarantines += 1
341
+ error = (f"Quarantine refused: no state-estimation evidence against {node_id} yet. "
342
+ "Run run_state_estimation on a subgraph containing it first.")
343
+ return {"success": False, "refused": True, "error": error}, error
344
+ result = self._engine.quarantine_node(node_id)
345
+ if result.get("success"):
346
+ self._spoof.quarantine_node(node_id)
347
+ if node_id == self._attack.get("target_node") and self._quarantine_tick is None:
348
+ self._quarantine_tick = self._tick
349
+ self._engine.nodes[node_id]["compromised"] = False
350
+ return result, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
 
352
  # ------------------------------------------------------------------
353
+ # Attack physics
354
  # ------------------------------------------------------------------
355
 
356
+ def _update_attacks(self) -> List[Dict[str, Any]]:
357
+ kind = self._attack.get("type")
358
+ if kind == "phantom_injection":
359
+ return self._update_phantom()
360
+ if kind == "resonance_oscillation":
361
+ return self._update_resonance()
362
+ return []
363
+
364
+ def _update_phantom(self) -> List[Dict[str, Any]]:
365
+ """The compromised plant loses real output while SCADA keeps reporting it."""
366
+ attack = self._attack
367
+ target = attack["target_node"]
368
+ node = self._engine.nodes[target]
369
+ if self._tick < int(attack["start_tick"]) or self._quarantine_tick is not None:
370
+ return []
371
+ self._hidden_loss_mw = min(float(attack["max_loss_mw"]),
372
+ self._hidden_loss_mw + float(attack["loss_rate_mw"]))
373
+ node["lost_mw"] = self._hidden_loss_mw
374
+ node["compromised"] = True
375
+ self._spoof.set_hidden_mw(target, self._hidden_loss_mw)
376
+ return []
377
+
378
+ def _update_resonance(self) -> List[Dict[str, Any]]:
379
+ """Forced oscillation: grows each tick unless damped by a matched counter-signal."""
380
+ attack = self._attack
381
+ engine = self._engine
382
+ target = attack["target_node"]
383
+ node = engine.nodes[target]
384
+ events: List[Dict[str, Any]] = []
385
+ amp = self._resonance_amplitude
386
+
387
+ if self._turbine_destroyed or self._attack_neutralized:
388
+ amp *= DECAY_NEUTRALIZED
389
+ elif self._tick >= int(attack["start_tick"]):
390
+ if amp <= 0.0:
391
+ amp = float(attack["initial_amplitude_hz"])
392
+ else:
393
+ quality = self._counter_signal_quality(target, float(attack["mode_hz"]))
394
+ if quality == "correct":
395
+ amp *= DAMPING_CORRECT
396
+ elif quality == "partial":
397
+ amp *= DAMPING_PARTIAL
398
+ else:
399
+ amp *= float(attack["growth"])
400
+ if quality != "none":
401
+ self._damping_seen = True
402
+ detuned = node["setpoint_mw"] <= DETUNE_FRACTION * self._pre_attack_setpoint
403
+ if self._damping_seen and amp < NEUTRALIZE_BELOW_HZ and detuned and not node["tripped"]:
404
+ self._attack_neutralized = True
405
+ self._neutralized_tick = self._tick
406
+ events.append({"type": "oscillation_neutralized", "tick": self._tick, "node": target})
407
+ elif amp >= float(attack["destruction_amplitude_hz"]):
408
+ self._turbine_destroyed = True
409
+ node["tripped"] = True
410
+ node["setpoint_mw"] = 0.0
411
+ events.append({"type": "turbine_destroyed", "tick": self._tick, "node": target})
412
+ if amp < 1e-4:
413
+ amp = 0.0
414
+ self._resonance_amplitude = amp
415
+ # The oscillation shows up as an alternating deviation of the measured frequency.
416
+ engine.frequency_offset_hz = amp * (1.0 if self._tick % 2 == 0 else -1.0)
417
+ return events
418
+
419
+ def _counter_signal_quality(self, target: str, mode_hz: float) -> str:
420
+ best = "none"
421
+ for cs in self._engine.active_counter_signals():
422
+ if self._engine.hop_distance(cs["node_id"], target) > COUNTER_SIGNAL_MAX_HOPS:
423
+ continue
424
+ error = abs(cs["hz_offset"] + mode_hz)
425
+ if error <= 0.05:
426
+ best = "correct"
427
+ elif error <= 0.15 and best != "correct":
428
+ best = "partial"
429
+ rank = {"none": 0, "partial": 1, "correct": 2}
430
+ if rank[best] > rank[self._best_counter_signal]:
431
+ self._best_counter_signal = best
432
+ return best
433
 
434
  # ------------------------------------------------------------------
435
+ # Telemetry and histories
436
  # ------------------------------------------------------------------
437
 
438
+ def _capture_telemetry(self) -> None:
439
+ truth = self._engine.get_ground_truth_telemetry()
440
+ amplitudes = self._pmu_oscillation()
441
+ mode = float(self._attack.get("mode_hz", 0.0))
442
+ for node_id, reading in truth.items():
443
+ amp = amplitudes.get(node_id, 0.0)
444
+ reading["oscillation_hz"] = round(mode, 3) if amp >= 0.005 else 0.0
445
+ reading["oscillation_amplitude_hz"] = round(amp, 4) if amp >= 0.005 else 0.0
446
+ self._reported = self._spoof.apply_spoofs(truth, self._tick)
447
+ self._engine.push_telemetry_snapshot([self._reported[nid] for nid in self._engine.nodes])
448
+
449
+ def _pmu_oscillation(self) -> Dict[str, float]:
450
+ """Oscillation amplitude seen by each PMU: strongest at the source, weaker with distance."""
451
+ if self._attack.get("type") != "resonance_oscillation" or self._resonance_amplitude <= 0.0:
452
+ return {}
453
+ target = self._attack["target_node"]
454
+ if self._engine.nodes[target]["tripped"]:
455
+ return {}
456
+ result = {}
457
+ for nid, n in self._engine.nodes.items():
458
+ if not n["energized"]:
459
+ continue
460
+ hops = self._engine.hop_distance(target, nid)
461
+ if hops <= 3:
462
+ result[nid] = self._resonance_amplitude * (PMU_PROPAGATION ** hops)
463
+ return result
464
+
465
+ def _record_histories(self) -> None:
466
+ engine = self._engine
467
+ self._frequency_history.append(round(engine.frequency_hz, 5))
468
+ self._served_history.append(round(engine.get_served_fraction(), 5))
469
+ self._max_loading_history.append(round(engine.get_max_loading(), 5))
470
+ if self._tick > 0 and self._task_id != 5 and engine.get_critical_nodes_shed() > 0:
471
+ self._critical_lost_ever = True
472
+
473
+ def _check_termination(self) -> None:
474
+ if self._tick >= self._max_ticks:
475
+ self._done = True
476
+ return
477
+ if self._task_id != 5 and self._engine.frequency_hz < COLLAPSE_TERMINATION_HZ:
478
+ self._done = True
479
+ return
480
+ if self._task_id == 5:
481
+ state = self._build_episode_state()
482
+ recent = self._frequency_history[-3:]
483
+ if (state["load_restored_fraction"] >= 0.98 and state["critical_energized_fraction"] >= 1.0
484
+ and len(recent) == 3 and all(59.5 <= f <= 60.5 for f in recent)):
485
+ self._done = True
486
+
487
+ def _current_score(self) -> float:
488
+ return grade_task(self._task_id, self._action_history, self._build_episode_state())
489
+
490
+ def _build_episode_state(self, force_done: bool = False) -> Dict[str, Any]:
491
+ engine = self._engine
492
+ if engine is None:
493
+ return {}
494
+ loads = [n for n in engine.nodes.values() if n["node_type"] == "load"]
495
+ critical = [n for n in loads if n["critical"]]
496
+ total_base = sum(n["base_consumption_mw"] for n in loads) or 1.0
497
+ served = sum(n["consumption_mw"] for n in loads if n["energized"])
498
+ target = self._attack.get("target_node")
499
+ target_disconnected = False
500
+ if self._attack.get("type") == "resonance_oscillation" and target and not self._turbine_destroyed:
501
+ live = [e for e in engine.edges.values() if e["status"] == "LIVE" and target in (e["source"], e["target"])]
502
+ zeroed = engine.nodes[target]["setpoint_mw"] < 0.1 * self._pre_attack_setpoint
503
+ target_disconnected = (not live) or zeroed
504
+ return {
505
+ "done": self._done or force_done,
506
  "task_id": self._task_id,
507
  "tick": self._tick,
508
+ "max_ticks": self._max_ticks,
509
+ "frequency_history": list(self._frequency_history),
510
+ "served_history": list(self._served_history),
511
+ "max_loading_history": list(self._max_loading_history),
512
+ "events": list(self._all_events),
513
+ "critical_lost_ever": self._critical_lost_ever,
514
+ "critical_energized_fraction": (sum(1 for n in critical if n["energized"]) / len(critical)) if critical else 1.0,
515
+ "load_restored_fraction": min(1.0, served / total_base),
516
+ "attack_target": target,
517
+ "attack_start_tick": int(self._attack.get("start_tick", 0)),
518
+ "refused_quarantines": self._refused_quarantines,
519
+ "best_counter_signal": self._best_counter_signal,
520
+ "turbine_destroyed": self._turbine_destroyed,
521
+ "target_disconnected": target_disconnected,
522
+ "attack_neutralized": self._attack_neutralized,
523
+ "neutralized_tick": self._neutralized_tick,
524
+ "black_start_unit": self._scenario.get("params", {}).get("black_start_unit"),
525
+ }
526
+
527
+ # ------------------------------------------------------------------
528
+ # Observation
529
+ # ------------------------------------------------------------------
530
+
531
+ def _build_observation(self, reward: float = 0.0, error: Optional[str] = None,
532
+ reward_breakdown: Optional[Dict[str, float]] = None) -> GridObservation:
533
+ engine = self._engine
534
+ if engine is None:
535
+ return GridObservation(done=True, last_action_error="Not initialised")
536
+ rubric = self.get_rubric_breakdown()
537
+ metadata: Dict[str, Any] = {
538
+ "version": ENV_VERSION,
539
+ "task_name": TASK_NAMES[self._task_id],
540
+ "difficulty": TASK_DIFFICULTIES[self._task_id],
541
  "episode_seed": self._seed,
542
+ "split": self._scenario.get("split"),
543
+ "flagged_nodes": sorted(self._flagged_nodes),
544
+ "quarantined_nodes": self._spoof.get_quarantined() if self._spoof else [],
545
+ "rubric_breakdown": rubric,
546
  }
547
  if self._done:
548
+ metadata["episode_summary"] = self.get_episode_summary()
549
+ return GridObservation(
550
+ topology_graph=engine.get_topology(),
551
+ telemetry_stream=engine.get_telemetry_history(),
552
+ weather_forecast_matrix=engine.get_weather(),
553
+ network_packet_logs=self._spoof.get_recent_packet_logs(20) if self._spoof else [],
554
+ grid_frequency_hz=float(min(62.0, max(58.0, engine.frequency_hz))),
 
555
  tick=self._tick,
556
  task_id=self._task_id,
557
  done=self._done,
558
+ reward=float(reward),
559
  last_action_error=error,
560
+ last_state_estimation=self._last_estimation,
561
+ weather_summary=engine.get_weather_summary(),
562
+ task_brief=str(self._scenario.get("brief", "")),
563
+ max_ticks=self._max_ticks,
564
+ forecast={
565
+ "system_demand_mw": list(engine.demand_forecast),
566
+ "solar_available_mw": list(engine.solar_forecast),
567
+ },
568
+ islands=engine.get_island_summary(),
569
+ events=list(self._tick_events) if self._tick > 0 else [],
570
+ active_counter_signals=[
571
+ {"node_id": cs["node_id"], "hz_offset": cs["hz_offset"], "remaining_ticks": cs["remaining_ticks"]}
572
+ for cs in engine.active_counter_signals()
573
+ ],
574
+ score=round(max(0.0, min(1.0, self._score_prev)), 6),
575
+ rubric_scores={k: round(v, 4) for k, v in rubric["rubrics"].items()},
576
+ reward_breakdown=dict(reward_breakdown or {}),
577
+ metadata=metadata,
578
  )
579
 
580
+ def _make_state(self) -> State:
581
+ return State(
582
+ episode_id=self._episode_id,
583
+ step_count=self._tick,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
584
  task_id=self._task_id,
585
+ task_name=TASK_NAMES[self._task_id],
586
  seed=self._seed,
587
+ split=self._scenario.get("split"),
588
+ tick=self._tick,
589
+ max_ticks=self._max_ticks,
590
+ done=self._done,
591
+ score=round(max(0.0, min(1.0, self._score_prev)), 6),
592
+ total_reward=round(self._reward_calc.total_reward, 6),
593
  )
 
 
594
 
595
+ def _reset_trackers(self) -> None:
596
+ self._frequency_history: List[float] = []
597
+ self._served_history: List[float] = []
598
+ self._max_loading_history: List[float] = []
599
+ self._all_events: List[Dict[str, Any]] = []
600
+ self._tick_events: List[Dict[str, Any]] = []
601
+ self._critical_lost_ever = False
602
+ self._flagged_nodes: set = set()
603
+ self._refused_quarantines = 0
604
+ self._last_estimation: Optional[Dict[str, Any]] = None
605
+ self._reported: Dict[str, Dict[str, Any]] = {}
606
+ self._attack: Dict[str, Any] = {}
607
+ self._hidden_loss_mw = 0.0
608
+ self._quarantine_tick: Optional[int] = None
609
+ self._resonance_amplitude = 0.0
610
+ self._pre_attack_setpoint = 0.0
611
+ self._damping_seen = False
612
+ self._attack_neutralized = False
613
+ self._neutralized_tick: Optional[int] = None
614
+ self._turbine_destroyed = False
615
+ self._best_counter_signal = "none"
616
+ self._score_prev = 0.0
server/reward.py CHANGED
@@ -1,174 +1,66 @@
1
  """
2
- NexusGrid — Dense Reward Calculator.
3
 
4
- Per-tick reward computation with positive signals, penalties,
5
- graduated frequency deviation bands, and the stability bonus.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- from typing import Any, Dict, List, Optional
11
 
 
 
 
 
 
12
 
13
- # ---------------------------------------------------------------------------
14
- # Reward signal values
15
- # ---------------------------------------------------------------------------
 
16
 
17
- # Positive signals
18
- REWARD_FAULT_ISOLATION = 0.20 # Isolating a fault without dropping critical nodes
19
- REWARD_CYBER_DETECTION = 0.15 # Correctly classifying + quarantining a spoofed sensor
20
- REWARD_FREQUENCY_STABLE = 0.10 # Per-tick frequency in nominal band (59.7–60.3Hz)
21
- REWARD_PROACTIVE_DISPATCH = 0.08 # Dispatch before frequency deviation
22
- REWARD_REASONING_ORDER = 0.05 # Reading packet logs before state estimation
23
- REWARD_STABILITY_BONUS = 0.03 # Frequency within ±0.1Hz of 60.0Hz (tightest band)
24
 
25
- # Negative signals
26
- PENALTY_OVERLOAD_ROUTING = -0.20 # Routing through ≥95% capacity line
27
- PENALTY_QUARANTINE_NO_EST = -0.15 # Quarantine without preceding state estimation
28
- PENALTY_REDUNDANT_ESTIMATION = -0.05 # State estimation twice on same subgraph without action
29
 
30
- # Graduated frequency deviation penalties
31
- PENALTY_FREQ_59_2_TO_59_5 = -0.05 # Per tick in 59.2–59.5Hz band
32
- PENALTY_FREQ_59_0_TO_59_2 = -0.15 # Per tick in 59.0–59.2Hz band
 
 
 
 
 
 
 
 
33
 
34
 
35
  class RewardCalculator:
36
- """
37
- Computes per-tick rewards for the NexusGrid environment.
38
-
39
- Tracks action history to determine reward eligibility.
40
- Returns a breakdown dict and total for each tick.
41
- """
42
 
43
- def __init__(self):
44
  self._total_reward = 0.0
45
- self._has_read_logs = False
46
- self._has_run_estimation = False
47
- self._estimation_subgraphs: List[set] = []
48
- self._last_action_was_estimation = False
49
- self._actions_since_estimation = 0
50
- self._fault_isolation_awarded = False
51
 
52
  def reset(self) -> None:
53
- """Reset reward state for a new episode."""
54
  self._total_reward = 0.0
55
- self._has_read_logs = False
56
- self._has_run_estimation = False
57
- self._estimation_subgraphs = []
58
- self._last_action_was_estimation = False
59
- self._actions_since_estimation = 0
60
- self._fault_isolation_awarded = False
61
 
62
  def compute_tick_reward(
63
  self,
64
- action_type: str,
65
- action_params: Dict[str, Any],
66
  frequency_hz: float,
67
- overloaded_edges: List[str],
68
- critical_nodes_shed: int,
69
- is_proactive: bool,
70
- spoof_detected: bool,
71
- fault_isolated: bool,
72
- has_read_logs_before_estimation: bool,
73
  ) -> Dict[str, float]:
74
- """
75
- Compute all reward signals for a single tick.
76
-
77
- Returns:
78
- Dict with signal names as keys and values as floats.
79
- Includes 'total' key with the sum.
80
- """
81
- breakdown: Dict[str, float] = {
82
- "fault_isolation": 0.0,
83
- "cyber_detection": 0.0,
84
- "frequency_stable": 0.0,
85
- "proactive_dispatch": 0.0,
86
- "reasoning_order": 0.0,
87
- "stability_bonus": 0.0,
88
- "penalties": 0.0,
89
  }
90
-
91
- # --- Positive signals ---
92
-
93
- # Fault isolation (toggle_circuit_breaker that isolates without dropping critical)
94
- if fault_isolated and critical_nodes_shed == 0 and not self._fault_isolation_awarded:
95
- breakdown["fault_isolation"] = REWARD_FAULT_ISOLATION
96
- self._fault_isolation_awarded = True
97
-
98
- # Cyber detection (quarantine after state estimation found violation)
99
- if spoof_detected and action_type == "quarantine_scada_node":
100
- if self._has_run_estimation:
101
- breakdown["cyber_detection"] = REWARD_CYBER_DETECTION
102
-
103
- # Frequency stability — nominal band
104
- if 59.7 <= frequency_hz <= 60.3:
105
- breakdown["frequency_stable"] = REWARD_FREQUENCY_STABLE
106
-
107
- # Proactive dispatch
108
- if action_type == "dispatch_generation" and is_proactive:
109
- breakdown["proactive_dispatch"] = REWARD_PROACTIVE_DISPATCH
110
-
111
- # Reasoning order — read logs before estimation
112
- if action_type == "run_state_estimation" and has_read_logs_before_estimation:
113
- breakdown["reasoning_order"] = REWARD_REASONING_ORDER
114
-
115
- # Stability bonus — tight band
116
- if 59.9 <= frequency_hz <= 60.1:
117
- breakdown["stability_bonus"] = REWARD_STABILITY_BONUS
118
-
119
- # --- Negative signals (penalties) ---
120
-
121
- penalties = 0.0
122
-
123
- # Overload routing
124
- if overloaded_edges and action_type in ("dispatch_generation", "toggle_circuit_breaker"):
125
- penalties += PENALTY_OVERLOAD_ROUTING
126
-
127
- # Quarantine without state estimation
128
- if action_type == "quarantine_scada_node" and not self._has_run_estimation:
129
- penalties += PENALTY_QUARANTINE_NO_EST
130
-
131
- # Redundant state estimation
132
- if action_type == "run_state_estimation":
133
- subgraph_set = set(action_params.get("subgraph", []))
134
- if self._last_action_was_estimation and subgraph_set in self._estimation_subgraphs:
135
- if self._actions_since_estimation == 0:
136
- penalties += PENALTY_REDUNDANT_ESTIMATION
137
- self._estimation_subgraphs.append(subgraph_set)
138
- self._last_action_was_estimation = True
139
- self._has_run_estimation = True
140
- self._actions_since_estimation = 0
141
- else:
142
- self._last_action_was_estimation = False
143
- if self._has_run_estimation:
144
- self._actions_since_estimation += 1
145
-
146
- # Graduated frequency deviation penalties
147
- if 59.2 <= frequency_hz < 59.5:
148
- penalties += PENALTY_FREQ_59_2_TO_59_5
149
- elif 59.0 <= frequency_hz < 59.2:
150
- penalties += PENALTY_FREQ_59_0_TO_59_2
151
-
152
- breakdown["penalties"] = penalties
153
-
154
- # Total
155
- total = sum(breakdown.values())
156
- breakdown["total"] = total
157
-
158
- self._total_reward += total
159
-
160
  return breakdown
161
 
162
  @property
163
  def total_reward(self) -> float:
164
- """Get accumulated total reward."""
165
  return self._total_reward
166
-
167
- def mark_logs_read(self) -> None:
168
- """Mark that packet logs have been read (for reasoning order check)."""
169
- self._has_read_logs = True
170
-
171
- @property
172
- def has_read_logs(self) -> bool:
173
- """Whether packet logs have been read."""
174
- return self._has_read_logs
 
1
  """
2
+ NexusGrid — Dense Reward.
3
 
4
+ The per-step reward is a potential-based shaping of the task score plus a
5
+ few small physical terms:
 
 
 
 
 
6
 
7
+ r_t = (S_t - S_{t-1}) progress on the task rubrics
8
+ + 0.02 * [f in 59.8-60.2] frequency regulation
9
+ - 0.02 * overloaded lines thermal stress
10
+ - event penalties relay trips, load shedding, collapses
11
+ - 0.05 * invalid action malformed or rejected commands
12
 
13
+ Because the progress term telescopes, the sum of progress rewards over an
14
+ episode equals the final rubric score, so maximising return and maximising
15
+ the graded score point in the same direction.
16
+ """
17
 
18
+ from __future__ import annotations
 
 
 
 
 
 
19
 
20
+ from typing import Any, Dict, List
 
 
 
21
 
22
+ REWARD_IN_BAND = 0.02
23
+ PENALTY_PER_OVERLOAD = -0.02
24
+ PENALTY_INVALID_ACTION = -0.05
25
+ EVENT_PENALTIES = {
26
+ "protection_trip": -0.10,
27
+ "ufls": -0.05,
28
+ "island_collapse": -0.30,
29
+ "out_of_phase_close": -0.20,
30
+ "turbine_destroyed": -0.30,
31
+ "battery_depleted": -0.02,
32
+ }
33
 
34
 
35
  class RewardCalculator:
36
+ """Computes per-step rewards and keeps the running total."""
 
 
 
 
 
37
 
38
+ def __init__(self) -> None:
39
  self._total_reward = 0.0
 
 
 
 
 
 
40
 
41
  def reset(self) -> None:
 
42
  self._total_reward = 0.0
 
 
 
 
 
 
43
 
44
  def compute_tick_reward(
45
  self,
46
+ score_now: float,
47
+ score_prev: float,
48
  frequency_hz: float,
49
+ overloaded_count: int,
50
+ events: List[Dict[str, Any]],
51
+ invalid_action: bool,
 
 
 
52
  ) -> Dict[str, float]:
53
+ breakdown = {
54
+ "progress": round(score_now - score_prev, 6),
55
+ "frequency_band": REWARD_IN_BAND if 59.8 <= frequency_hz <= 60.2 else 0.0,
56
+ "overload": PENALTY_PER_OVERLOAD * int(overloaded_count),
57
+ "events": sum(EVENT_PENALTIES.get(e.get("type", ""), 0.0) for e in events),
58
+ "invalid_action": PENALTY_INVALID_ACTION if invalid_action else 0.0,
 
 
 
 
 
 
 
 
 
59
  }
60
+ breakdown["total"] = round(sum(breakdown.values()), 6)
61
+ self._total_reward += breakdown["total"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  return breakdown
63
 
64
  @property
65
  def total_reward(self) -> float:
 
66
  return self._total_reward
 
 
 
 
 
 
 
 
 
server/rubric.py CHANGED
@@ -1,13 +1,21 @@
1
- """Composable task rubrics for NexusGrid scoring and training feedback."""
 
 
 
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
5
  from dataclasses import dataclass
6
- from typing import Any, Callable, Dict, List
7
-
8
 
9
  CheckFn = Callable[[List[Dict[str, Any]], Dict[str, Any]], float]
10
 
 
 
11
 
12
  @dataclass(frozen=True)
13
  class Rubric:
@@ -17,9 +25,13 @@ class Rubric:
17
  weight: float
18
  description: str
19
  check: CheckFn
 
20
 
21
  def evaluate(self, action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> Dict[str, Any]:
22
- raw_score = float(self.check(action_history, episode_state))
 
 
 
23
  raw_score = max(0.0, min(1.0, raw_score))
24
  return {
25
  "name": self.name,
@@ -27,337 +39,314 @@ class Rubric:
27
  "weight": self.weight,
28
  "raw": raw_score,
29
  "weighted": raw_score * self.weight,
 
30
  }
31
 
32
 
33
  def evaluate_task_rubrics(task_id: int, action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> Dict[str, Any]:
34
  """Evaluate all rubrics for a task and return a serializable breakdown."""
35
- rubrics = TASK_RUBRICS.get(task_id, [])
36
- rubric_results = [rubric.evaluate(action_history, episode_state) for rubric in rubrics]
37
  return {
38
  "task_id": task_id,
39
- "rubrics": {item["name"]: item["raw"] for item in rubric_results},
40
- "weights": {item["name"]: item["weight"] for item in rubric_results},
41
- "descriptions": {item["name"]: item["description"] for item in rubric_results},
42
- "weighted_components": {item["name"]: item["weighted"] for item in rubric_results},
43
- "weighted_score": sum(item["weighted"] for item in rubric_results),
44
  }
45
 
46
 
47
  def get_task_rubric_specs(task_id: int) -> List[Dict[str, Any]]:
48
- """Return rubric metadata for OpenEnv discovery surfaces."""
49
  return [
50
- {"name": rubric.name, "weight": rubric.weight, "description": rubric.description}
51
- for rubric in TASK_RUBRICS.get(task_id, [])
52
  ]
53
 
54
 
55
- def _first_tick(action_history: List[Dict[str, Any]], action_type: str) -> int | None:
56
- for action in action_history:
57
- if action.get("action_type") == action_type:
58
- return action.get("tick")
59
- return None
60
 
 
 
61
 
62
- def _has_positive_dispatch(action_history: List[Dict[str, Any]]) -> bool:
63
- return any(
64
- action.get("action_type") == "dispatch_generation" and (action.get("mw") or 0.0) > 0.0
65
- for action in action_history
66
- )
67
 
 
 
 
68
 
69
- def _task0_valid_dispatch(action_history: List[Dict[str, Any]], _: Dict[str, Any]) -> float:
70
- return 1.0 if _has_positive_dispatch(action_history) else 0.0
71
 
 
 
 
 
72
 
73
- def _task1_avoid_collapse(_: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
74
- freq_history = episode_state.get("frequency_history", [])
75
- min_freq = min(freq_history) if freq_history else 60.0
76
- return 1.0 if min_freq >= 59.0 else 0.0
77
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
- def _task1_recover_nominal(_: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
80
- freq_history = episode_state.get("frequency_history", [])
81
- min_freq = min(freq_history) if freq_history else 60.0
82
- if min_freq >= 59.5:
83
- return 1.0
84
- return 1.0 if episode_state.get("recovered_above_59_5_in_3_ticks", False) else 0.0
85
 
 
 
86
 
87
- def _task1_hold_nominal(_: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
88
- freq_history = episode_state.get("frequency_history", [])
89
- min_freq = min(freq_history) if freq_history else 60.0
90
- return 1.0 if min_freq >= 59.5 else 0.0
91
 
 
 
 
 
 
92
 
93
- def _task1_proactive_dispatch(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
94
- early_dispatches = sum(
95
- 1
96
- for action in action_history
97
- if action.get("action_type") == "dispatch_generation" and action.get("tick", 999) <= 3
98
- )
99
- return 1.0 if early_dispatches >= 2 and episode_state.get("is_proactive_dispatch", False) else 0.0
100
 
 
 
 
 
 
101
 
102
- def _task2_fault_isolation(action_history: List[Dict[str, Any]], _: Dict[str, Any]) -> float:
103
- return 1.0 if any(
104
- action.get("action_type") == "toggle_circuit_breaker"
105
- and str(action.get("status", "")).upper() == "OPEN"
106
- for action in action_history
107
- ) else 0.0
108
 
 
 
 
109
 
110
- def _task2_protect_critical(_: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
111
- return 1.0 if episode_state.get("critical_nodes_shed", 0) == 0 else 0.0
112
 
113
 
114
- def _task2_fast_restore(_: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
115
- restored_tick = episode_state.get("full_restoration_tick")
116
- return 1.0 if restored_tick is not None and restored_tick <= 8 else 0.0
117
 
118
 
119
- def _task3_logs_read(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
120
- estimation_tick = _first_tick(action_history, "run_state_estimation")
121
- if estimation_tick is None:
122
- return 1.0 if episode_state.get("logs_read_before_estimation", False) else 0.0
123
- return 1.0 if any(
124
- action.get("action_type") == "advance_tick" and action.get("tick", 999) < estimation_tick
125
- for action in action_history
126
- ) else 0.0
127
 
 
 
128
 
129
- def _task3_estimation(action_history: List[Dict[str, Any]], _: Dict[str, Any]) -> float:
130
- for action in action_history:
131
- if action.get("action_type") == "run_state_estimation":
132
- result = action.get("result", {})
133
- if not result.get("consistent", True):
134
- return 1.0
135
- return 0.0
136
 
 
 
 
 
 
137
 
138
- def _task3_quarantine(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
139
- estimation_tick = _first_tick(action_history, "run_state_estimation")
140
- expected_node = episode_state.get("spoof_target", "NODE_14")
141
- for action in action_history:
142
- if action.get("action_type") != "quarantine_scada_node":
143
- continue
144
- if estimation_tick is None or action.get("tick", 999) <= estimation_tick:
145
- return 0.0
146
- if action.get("node_id") == expected_node:
147
- return 1.0
148
- return 0.0
149
 
 
 
 
150
 
151
- def _task3_reroute(action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
152
- quarantine_tick = None
153
- expected_node = episode_state.get("spoof_target", "NODE_14")
154
- for action in action_history:
155
- if action.get("action_type") == "quarantine_scada_node" and action.get("node_id") == expected_node:
156
- quarantine_tick = action.get("tick")
157
- break
158
- if quarantine_tick is None:
159
  return 0.0
160
- for action in action_history:
161
- if action.get("action_type") == "dispatch_generation" and action.get("tick", 999) > quarantine_tick:
162
- return 1.0 if action.get("tick", 999) <= 4 else 0.5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  return 0.0
164
 
165
 
166
- def _task4_injection_attempt(action_history: List[Dict[str, Any]], _: Dict[str, Any]) -> float:
167
- return 1.0 if any(action.get("action_type") == "inject_counter_signal" for action in action_history) else 0.0
168
 
169
 
170
- def _task4_correct_offset(action_history: List[Dict[str, Any]], _: Dict[str, Any]) -> float:
171
- for action in action_history:
172
- if action.get("action_type") != "inject_counter_signal":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  continue
174
- hz_offset = action.get("hz_offset", 0.0)
175
- if hz_offset is not None and abs(hz_offset - (-0.5)) <= 0.05:
176
- return 1.0
177
- return 0.0
178
 
179
 
180
- def _task4_target_ramp_down(action_history: List[Dict[str, Any]], _: Dict[str, Any]) -> float:
181
- injection_tick = _first_tick(action_history, "inject_counter_signal")
182
- if injection_tick is None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  return 0.0
184
- return 1.0 if any(
185
- action.get("action_type") == "dispatch_generation"
186
- and action.get("node_id") == "NODE_17"
187
- and (action.get("mw") or 0.0) < 0.0
188
- and action.get("tick", 999) > injection_tick
189
- for action in action_history
190
- ) else 0.0
191
-
192
-
193
- def _task4_support_reroute(action_history: List[Dict[str, Any]], _: Dict[str, Any]) -> float:
194
- injection_tick = _first_tick(action_history, "inject_counter_signal")
195
- if injection_tick is None:
 
 
196
  return 0.0
197
- return 1.0 if any(
198
- action.get("action_type") == "dispatch_generation"
199
- and action.get("node_id") != "NODE_17"
200
- and (action.get("mw") or 0.0) > 0.0
201
- and action.get("tick", 999) > injection_tick
202
- for action in action_history
203
- ) else 0.0
204
 
205
 
206
- def _task5_hydro_bootstrap(action_history: List[Dict[str, Any]], _: Dict[str, Any]) -> float:
207
- return 1.0 if any(
208
- action.get("action_type") == "dispatch_generation"
209
- and action.get("node_id") == "NODE_01"
210
- and (action.get("mw") or 0.0) > 0.0
211
- for action in action_history
212
- ) else 0.0
213
 
 
 
 
214
 
215
- def _task5_secondary_energized(_: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
216
- return 1.0 if episode_state.get("hydro_stable_ticks", 0) >= 2 and episode_state.get("energized_node_count", 0) >= 2 else 0.0
217
 
 
 
218
 
219
- def _task5_safe_islanding(_: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
220
- island_count = episode_state.get("max_island_count", 0)
221
- successful_mergers = episode_state.get("successful_mergers", 0)
222
- return 1.0 if island_count >= 3 and successful_mergers >= 1 else 0.0
223
 
 
 
224
 
225
- def _task5_restore_critical(_: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> float:
226
- has_safe_islanding = _task5_safe_islanding([], episode_state) == 1.0
227
- return 1.0 if has_safe_islanding and episode_state.get("critical_nodes_restored", False) else 0.0
 
 
 
 
 
 
 
 
 
228
 
229
 
230
  TASK_RUBRICS: Dict[int, List[Rubric]] = {
231
  0: [
232
- Rubric(
233
- name="valid_dispatch",
234
- weight=1.0,
235
- description="Agent issues any valid positive dispatch to prove the environment pipeline works.",
236
- check=_task0_valid_dispatch,
237
- ),
238
  ],
239
  1: [
240
- Rubric(
241
- name="avoid_collapse",
242
- weight=0.30,
243
- description="Grid frequency never crosses the 59.0Hz termination floor.",
244
- check=_task1_avoid_collapse,
245
- ),
246
- Rubric(
247
- name="recover_nominal_band",
248
- weight=0.20,
249
- description="Frequency stays or recovers above 59.5Hz quickly.",
250
- check=_task1_recover_nominal,
251
- ),
252
- Rubric(
253
- name="hold_nominal_band",
254
- weight=0.42,
255
- description="Grid frequency remains inside the nominal operating band.",
256
- check=_task1_hold_nominal,
257
- ),
258
- Rubric(
259
- name="proactive_dispatch",
260
- weight=0.08,
261
- description="Agent dispatches support resources before the main frequency dip.",
262
- check=_task1_proactive_dispatch,
263
- ),
264
  ],
265
  2: [
266
- Rubric(
267
- name="fault_isolation",
268
- weight=0.40,
269
- description="Agent isolates the overloaded line with a breaker action.",
270
- check=_task2_fault_isolation,
271
- ),
272
- Rubric(
273
- name="protect_critical_load",
274
- weight=0.40,
275
- description="No critical infrastructure nodes are shed during recovery.",
276
- check=_task2_protect_critical,
277
- ),
278
- Rubric(
279
- name="fast_restoration",
280
- weight=0.20,
281
- description="Service is restored within eight ticks of the incident.",
282
- check=_task2_fast_restore,
283
- ),
284
  ],
285
  3: [
286
- Rubric(
287
- name="log_inspection",
288
- weight=0.10,
289
- description="Agent inspects packet behavior before trusting SCADA telemetry.",
290
- check=_task3_logs_read,
291
- ),
292
- Rubric(
293
- name="state_estimation",
294
- weight=0.20,
295
- description="Agent runs a Kirchhoff consistency check and detects the violation.",
296
- check=_task3_estimation,
297
- ),
298
- Rubric(
299
- name="correct_quarantine",
300
- weight=0.30,
301
- description="Agent quarantines the spoofed SCADA node after confirming the anomaly.",
302
- check=_task3_quarantine,
303
- ),
304
- Rubric(
305
- name="reroute_dispatch",
306
- weight=0.40,
307
- description="Agent reroutes generation after quarantine to stabilize the grid.",
308
- check=_task3_reroute,
309
- ),
310
  ],
311
  4: [
312
- Rubric(
313
- name="counter_signal_attempted",
314
- weight=0.20,
315
- description="Agent attempts a counter-signal instead of cutting the turbine offline.",
316
- check=_task4_injection_attempt,
317
- ),
318
- Rubric(
319
- name="correct_frequency_match",
320
- weight=0.20,
321
- description="Counter-signal uses the resonance-canceling frequency offset.",
322
- check=_task4_correct_offset,
323
- ),
324
- Rubric(
325
- name="target_ramp_down",
326
- weight=0.30,
327
- description="Agent ramps down the resonating turbine after the counter-signal lands.",
328
- check=_task4_target_ramp_down,
329
- ),
330
- Rubric(
331
- name="support_reroute",
332
- weight=0.30,
333
- description="Agent dispatches alternate generation to carry the displaced load.",
334
- check=_task4_support_reroute,
335
- ),
336
  ],
337
  5: [
338
- Rubric(
339
- name="hydro_bootstrap",
340
- weight=0.25,
341
- description="Agent restarts the hydro source to begin the black-start sequence.",
342
- check=_task5_hydro_bootstrap,
343
- ),
344
- Rubric(
345
- name="secondary_energized",
346
- weight=0.25,
347
- description="A second energized node is sustained after hydro startup.",
348
- check=_task5_secondary_energized,
349
- ),
350
- Rubric(
351
- name="safe_islanding",
352
- weight=0.30,
353
- description="Agent forms stable islands and completes at least one safe merger.",
354
- check=_task5_safe_islanding,
355
- ),
356
- Rubric(
357
- name="critical_restoration",
358
- weight=0.20,
359
- description="All critical infrastructure is restored after safe synchronization.",
360
- check=_task5_restore_critical,
361
- ),
362
  ],
363
  }
 
1
+ """
2
+ Composable task rubrics for NexusGrid scoring and training feedback.
3
+
4
+ Each rubric is a named, weighted check ``(action_history, episode_state) -> [0, 1]``.
5
+ Rubrics marked ``final_only`` are only awarded once the episode is done, so
6
+ that intermediate scores (used for reward shaping) never hand out credit for
7
+ outcomes that have not happened yet.
8
+ """
9
 
10
  from __future__ import annotations
11
 
12
  from dataclasses import dataclass
13
+ from typing import Any, Callable, Dict, List, Optional
 
14
 
15
  CheckFn = Callable[[List[Dict[str, Any]], Dict[str, Any]], float]
16
 
17
+ BAND_LOW, BAND_HIGH = 59.8, 60.2
18
+
19
 
20
  @dataclass(frozen=True)
21
  class Rubric:
 
25
  weight: float
26
  description: str
27
  check: CheckFn
28
+ final_only: bool = False
29
 
30
  def evaluate(self, action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> Dict[str, Any]:
31
+ if self.final_only and not episode_state.get("done", True):
32
+ raw_score = 0.0
33
+ else:
34
+ raw_score = float(self.check(action_history, episode_state))
35
  raw_score = max(0.0, min(1.0, raw_score))
36
  return {
37
  "name": self.name,
 
39
  "weight": self.weight,
40
  "raw": raw_score,
41
  "weighted": raw_score * self.weight,
42
+ "final_only": self.final_only,
43
  }
44
 
45
 
46
  def evaluate_task_rubrics(task_id: int, action_history: List[Dict[str, Any]], episode_state: Dict[str, Any]) -> Dict[str, Any]:
47
  """Evaluate all rubrics for a task and return a serializable breakdown."""
48
+ results = [rubric.evaluate(action_history, episode_state) for rubric in TASK_RUBRICS.get(task_id, [])]
 
49
  return {
50
  "task_id": task_id,
51
+ "rubrics": {item["name"]: item["raw"] for item in results},
52
+ "weights": {item["name"]: item["weight"] for item in results},
53
+ "descriptions": {item["name"]: item["description"] for item in results},
54
+ "weighted_components": {item["name"]: item["weighted"] for item in results},
55
+ "weighted_score": sum(item["weighted"] for item in results),
56
  }
57
 
58
 
59
  def get_task_rubric_specs(task_id: int) -> List[Dict[str, Any]]:
 
60
  return [
61
+ {"name": r.name, "weight": r.weight, "description": r.description, "final_only": r.final_only}
62
+ for r in TASK_RUBRICS.get(task_id, [])
63
  ]
64
 
65
 
66
+ # ---------------------------------------------------------------------------
67
+ # Shared helpers
68
+ # ---------------------------------------------------------------------------
 
 
69
 
70
+ def _in_band(freq: float, low: float = BAND_LOW, high: float = BAND_HIGH) -> bool:
71
+ return low <= freq <= high
72
 
 
 
 
 
 
73
 
74
+ def _freqs_after_reset(state: Dict[str, Any]) -> List[float]:
75
+ history = state.get("frequency_history", [])
76
+ return list(history[1:]) if len(history) > 1 else []
77
 
 
 
78
 
79
+ def _band_fraction_of_horizon(state: Dict[str, Any], low: float = BAND_LOW, high: float = BAND_HIGH) -> float:
80
+ freqs = _freqs_after_reset(state)
81
+ horizon = max(1, int(state.get("max_ticks", len(freqs) or 1)))
82
+ return sum(1 for f in freqs if _in_band(f, low, high)) / horizon
83
 
 
 
 
 
84
 
85
+ def _last_k_band(state: Dict[str, Any], k: int, low: float = BAND_LOW, high: float = BAND_HIGH) -> float:
86
+ freqs = _freqs_after_reset(state)[-k:]
87
+ if not freqs:
88
+ return 0.0
89
+ return sum(1 for f in freqs if _in_band(f, low, high)) / len(freqs)
90
+
91
+
92
+ def mean_served(state: Dict[str, Any]) -> float:
93
+ """Average share of demand served after reset (1.0 when no history yet)."""
94
+ served = state.get("served_history", [])[1:]
95
+ return sum(served) / len(served) if served else 1.0
96
 
 
 
 
 
 
 
97
 
98
+ def _events(state: Dict[str, Any], kind: str) -> List[Dict[str, Any]]:
99
+ return [e for e in state.get("events", []) if e.get("type") == kind]
100
 
 
 
 
 
101
 
102
+ def _successful(actions: List[Dict[str, Any]], action_type: str) -> List[Dict[str, Any]]:
103
+ return [
104
+ a for a in actions
105
+ if a.get("action_type") == action_type and (a.get("result") or {}).get("success", a.get("result") is None)
106
+ ]
107
 
 
 
 
 
 
 
 
108
 
109
+ def _positive_dispatches(actions: List[Dict[str, Any]], exclude: Optional[str] = None) -> List[Dict[str, Any]]:
110
+ return [
111
+ a for a in _successful(actions, "dispatch_generation")
112
+ if (a.get("mw") or 0.0) > 0.0 and (exclude is None or a.get("node_id") != exclude)
113
+ ]
114
 
 
 
 
 
 
 
115
 
116
+ # ---------------------------------------------------------------------------
117
+ # Task 0 — smoke test
118
+ # ---------------------------------------------------------------------------
119
 
120
+ def _t0_valid_dispatch(actions: List[Dict[str, Any]], _: Dict[str, Any]) -> float:
121
+ return 1.0 if _positive_dispatches(actions) else 0.0
122
 
123
 
124
+ def _t0_stable(actions: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
125
+ freqs = state.get("frequency_history", [60.0])
126
+ return 1.0 if _positive_dispatches(actions) and _in_band(freqs[-1]) else 0.0
127
 
128
 
129
+ # ---------------------------------------------------------------------------
130
+ # Task 1 — duck curve
131
+ # ---------------------------------------------------------------------------
 
 
 
 
 
132
 
133
+ def _t1_band_time(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
134
+ return _band_fraction_of_horizon(state)
135
 
 
 
 
 
 
 
 
136
 
137
+ def _t1_no_emergency(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
138
+ freqs = _freqs_after_reset(state) or [60.0]
139
+ if _events(state, "ufls") or _events(state, "island_collapse"):
140
+ return 0.0
141
+ return 1.0 if min(freqs) >= 59.5 else 0.0
142
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
+ def _t1_no_overshoot(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
145
+ freqs = _freqs_after_reset(state) or [60.0]
146
+ return 1.0 if max(freqs) <= 60.3 and _band_fraction_of_horizon(state) >= 0.5 else 0.0
147
 
148
+
149
+ def _t1_proactive(actions: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
150
+ dispatches = _positive_dispatches(actions)
151
+ if not dispatches:
 
 
 
 
152
  return 0.0
153
+ first_dispatch = min(a.get("tick", 999) for a in dispatches)
154
+ freqs = state.get("frequency_history", [])
155
+ drop_ticks = [t for t, f in enumerate(freqs) if f < 59.9]
156
+ first_drop = drop_ticks[0] if drop_ticks else None
157
+ return 1.0 if first_drop is None or first_dispatch < first_drop else 0.0
158
+
159
+
160
+ # ---------------------------------------------------------------------------
161
+ # Task 2 — cascade overload
162
+ # ---------------------------------------------------------------------------
163
+
164
+ def _t2_cleared_from(state: Dict[str, Any], tick: int) -> bool:
165
+ history = state.get("max_loading_history", [])
166
+ tail = history[tick:]
167
+ return bool(tail) and all(x <= 1.0 + 1e-6 for x in tail)
168
+
169
+
170
+ def _t2_relieve(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
171
+ trips = len(_events(state, "protection_trip"))
172
+ if trips == 0 and _t2_cleared_from(state, 3):
173
+ return 1.0
174
+ if trips <= 1 and _t2_cleared_from(state, 6):
175
+ return 0.5
176
  return 0.0
177
 
178
 
179
+ def _t2_protect_critical(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
180
+ return 0.0 if state.get("critical_lost_ever", False) else 1.0
181
 
182
 
183
+ def _t2_serve_load(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
184
+ if not state.get("served_history", [])[1:]:
185
+ return 0.0
186
+ return max(0.0, min(1.0, (mean_served(state) - 0.85) / 0.15))
187
+
188
+
189
+ def _t2_frequency(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
190
+ return _last_k_band(state, 5)
191
+
192
+
193
+ # ---------------------------------------------------------------------------
194
+ # Task 3 — phantom injection (false data injection)
195
+ # ---------------------------------------------------------------------------
196
+
197
+ def _t3_evidence_tick(actions: List[Dict[str, Any]], state: Dict[str, Any]) -> Optional[int]:
198
+ target = state.get("attack_target")
199
+ for a in actions:
200
+ if a.get("action_type") != "run_state_estimation":
201
  continue
202
+ result = a.get("result") or {}
203
+ if not result.get("consistent", True) and result.get("violation_node") == target:
204
+ return a.get("tick")
205
+ return None
206
 
207
 
208
+ def _t3_quarantine_tick(actions: List[Dict[str, Any]], state: Dict[str, Any]) -> Optional[int]:
209
+ target = state.get("attack_target")
210
+ for a in _successful(actions, "quarantine_scada_node"):
211
+ if a.get("node_id") == target:
212
+ return a.get("tick")
213
+ return None
214
+
215
+
216
+ def _t3_evidence(actions: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
217
+ evidence = _t3_evidence_tick(actions, state)
218
+ quarantine = _t3_quarantine_tick(actions, state)
219
+ if evidence is None:
220
+ return 0.0
221
+ return 1.0 if quarantine is None or evidence <= quarantine else 0.0
222
+
223
+
224
+ def _t3_quarantine(actions: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
225
+ quarantine = _t3_quarantine_tick(actions, state)
226
+ evidence = _t3_evidence_tick(actions, state)
227
+ if quarantine is None or evidence is None or evidence > quarantine:
228
+ return 0.0
229
+ start = int(state.get("attack_start_tick", 0))
230
+ return 1.0 if quarantine <= start + 5 else 0.6
231
+
232
+
233
+ def _t3_recovery(actions: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
234
+ quarantine = _t3_quarantine_tick(actions, state)
235
+ if quarantine is None:
236
+ return 0.0
237
+ freqs = state.get("frequency_history", [])
238
+ after = freqs[quarantine + 2:]
239
+ if len(after) < 3:
240
+ return 0.0
241
+ return sum(1 for f in after if _in_band(f)) / len(after)
242
+
243
+
244
+ def _t3_triage(actions: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
245
+ evidence = _t3_evidence_tick(actions, state)
246
+ if evidence is None:
247
+ return 0.0
248
+ calls = sum(1 for a in actions if a.get("action_type") == "run_state_estimation" and a.get("tick", 999) <= evidence)
249
+ return 1.0 if calls <= 2 else (0.5 if calls <= 4 else 0.0)
250
+
251
+
252
+ # ---------------------------------------------------------------------------
253
+ # Task 4 — forced oscillation (Stuxnet-style resonance)
254
+ # ---------------------------------------------------------------------------
255
+
256
+ def _t4_mitigate(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
257
+ quality = state.get("best_counter_signal", "none")
258
+ return {"correct": 1.0, "partial": 0.4}.get(quality, 0.0)
259
+
260
+
261
+ def _t4_turbine_saved(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
262
+ if state.get("turbine_destroyed") or state.get("target_disconnected"):
263
  return 0.0
264
+ return 1.0
265
+
266
+
267
+ def _t4_detune(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
268
+ return 1.0 if state.get("attack_neutralized") else 0.0
269
+
270
+
271
+ def _t4_frequency(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
272
+ return _last_k_band(state, 4)
273
+
274
+
275
+ def _t4_support(actions: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
276
+ neutralized_tick = state.get("neutralized_tick")
277
+ if neutralized_tick is None:
278
  return 0.0
279
+ target = state.get("attack_target")
280
+ support = [a for a in _positive_dispatches(actions, exclude=target) if a.get("tick", -1) >= neutralized_tick - 1]
281
+ freqs = state.get("frequency_history", [60.0])
282
+ return 1.0 if support and _in_band(freqs[-1]) else 0.0
 
 
 
283
 
284
 
285
+ # ---------------------------------------------------------------------------
286
+ # Task 5 — black start
287
+ # ---------------------------------------------------------------------------
 
 
 
 
288
 
289
+ def _t5_bootstrap(actions: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
290
+ unit = state.get("black_start_unit")
291
+ return 1.0 if any(a.get("node_id") == unit for a in _positive_dispatches(actions)) else 0.0
292
 
 
 
293
 
294
+ def _t5_critical(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
295
+ return float(state.get("critical_energized_fraction", 0.0))
296
 
 
 
 
 
297
 
298
+ def _t5_load(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
299
+ return float(state.get("load_restored_fraction", 0.0))
300
 
301
+
302
+ def _t5_stability(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
303
+ if state.get("load_restored_fraction", 0.0) <= 0.0:
304
+ return 0.0
305
+ bad = len(_events(state, "island_collapse")) + len(_events(state, "out_of_phase_close"))
306
+ return 1.0 if bad == 0 else (0.5 if bad == 1 else 0.0)
307
+
308
+
309
+ def _t5_frequency(_: List[Dict[str, Any]], state: Dict[str, Any]) -> float:
310
+ if state.get("load_restored_fraction", 0.0) <= 0.0:
311
+ return 0.0
312
+ return _last_k_band(state, 5, low=59.5, high=60.5)
313
 
314
 
315
  TASK_RUBRICS: Dict[int, List[Rubric]] = {
316
  0: [
317
+ Rubric("valid_dispatch", 0.70, "Issue a valid positive dispatch on an energised generator.", _t0_valid_dispatch),
318
+ Rubric("stable_after_dispatch", 0.30, "Frequency is inside 59.8-60.2 Hz after the dispatch.", _t0_stable, final_only=True),
 
 
 
 
319
  ],
320
  1: [
321
+ Rubric("band_time", 0.50, "Share of the horizon with frequency inside 59.8-60.2 Hz.", _t1_band_time),
322
+ Rubric("no_emergency", 0.25, "Frequency never drops below 59.5 Hz and no UFLS or collapse occurs.", _t1_no_emergency, final_only=True),
323
+ Rubric("proactive_response", 0.15, "Support is dispatched before frequency first falls below 59.9 Hz.", _t1_proactive),
324
+ Rubric("no_overshoot", 0.10, "No over-dispatch above 60.3 Hz (requires at least half the horizon in band).", _t1_no_overshoot, final_only=True),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325
  ],
326
  2: [
327
+ Rubric("relieve_overload", 0.35, "All lines back under 100% by tick 3 with no relay trips (half credit by tick 6 with at most one trip).", _t2_relieve, final_only=True),
328
+ Rubric("protect_critical_load", 0.25, "No critical load is de-energised at any point.", _t2_protect_critical, final_only=True),
329
+ Rubric("serve_load", 0.20, "Average share of demand served stays high (85% -> 0, 100% -> 1).", _t2_serve_load, final_only=True),
330
+ Rubric("frequency_band", 0.20, "Frequency inside 59.8-60.2 Hz over the last five ticks.", _t2_frequency, final_only=True),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
  ],
332
  3: [
333
+ Rubric("evidence", 0.25, "State estimation proves the falsified bus before any quarantine.", _t3_evidence),
334
+ Rubric("correct_quarantine", 0.30, "The compromised bus is quarantined after evidence (full credit within five ticks of the attack).", _t3_quarantine),
335
+ Rubric("recovery", 0.30, "Frequency stays inside 59.8-60.2 Hz after the quarantine.", _t3_recovery, final_only=True),
336
+ Rubric("triage", 0.15, "Packet-log triage finds the compromised bus within two estimation calls.", _t3_triage),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
  ],
338
  4: [
339
+ Rubric("mitigate_oscillation", 0.35, "Counter-signal with the matching offset from a battery within two hops, before the unit fails.", _t4_mitigate),
340
+ Rubric("turbine_saved", 0.20, "The oscillating unit survives and stays connected.", _t4_turbine_saved, final_only=True),
341
+ Rubric("detune_unit", 0.15, "The unit is ramped down at least 20% while damped, neutralising the mode.", _t4_detune),
342
+ Rubric("frequency_band", 0.15, "Frequency inside 59.8-60.2 Hz over the last four ticks.", _t4_frequency, final_only=True),
343
+ Rubric("support_dispatch", 0.15, "Other units pick up the lost output and frequency ends in band.", _t4_support, final_only=True),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  ],
345
  5: [
346
+ Rubric("bootstrap", 0.10, "The black-start unit is brought online.", _t5_bootstrap),
347
+ Rubric("critical_restored", 0.30, "Share of critical loads energised.", _t5_critical),
348
+ Rubric("load_restored", 0.30, "Share of total demand served.", _t5_load),
349
+ Rubric("stability", 0.20, "No island collapse or out-of-phase closure during restoration.", _t5_stability, final_only=True),
350
+ Rubric("frequency_band", 0.10, "Main island inside 59.5-60.5 Hz over the last five ticks.", _t5_frequency, final_only=True),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
  ],
352
  }
server/scenarios.py CHANGED
@@ -1,18 +1,29 @@
1
  """
2
- NexusGrid — Scenario Definitions.
3
 
4
- Six hardcoded scenarios (one per task), fully deterministic from seed.
5
- Each scenario defines: topology, load profile, weather, attack vectors, max_ticks.
 
 
 
 
 
 
6
  """
7
 
8
  from __future__ import annotations
9
 
10
- from typing import Any, Dict, List
 
 
 
 
 
11
 
12
- from .grid_engine import GridEngine
13
 
 
14
 
15
- # Max ticks per task — matches openenv.yaml
16
  MAX_TICKS = {
17
  0: 3, # Smoke test
18
  1: 15, # Duck curve
@@ -40,305 +51,503 @@ TASK_DIFFICULTIES = {
40
  5: "expert",
41
  }
42
 
 
 
 
 
43
 
44
- def build_base_topology(engine: GridEngine) -> None:
45
- """
46
- Build the standard 20-node grid topology.
 
 
 
 
 
47
 
48
- Regions: NORTH, SOUTH, EAST, WEST, CENTRAL
49
- Node types mix: hydro, solar, gas, battery, load
50
- """
51
- # ---- NORTH region (nodes 01-04) ----
52
- engine.add_node("NODE_01", "hydro", capacity_mw=1200, region="NORTH", critical=False,
53
- generation_mw=800, peak_load_mw=0, black_start_capable=True)
54
- engine.add_node("NODE_02", "gas", capacity_mw=600, region="NORTH", critical=False,
55
- generation_mw=400, peak_load_mw=0)
56
- engine.add_node("NODE_03", "load", capacity_mw=0, region="NORTH", critical=True,
57
- peak_load_mw=500, consumption_mw=450) # Hospital complex
58
- engine.add_node("NODE_04", "battery", capacity_mw=300, region="NORTH", critical=False,
59
- generation_mw=0, peak_load_mw=0)
60
-
61
- # ---- SOUTH region (nodes 05-08) ----
62
- engine.add_node("NODE_05", "solar", capacity_mw=800, region="SOUTH", critical=False,
63
- generation_mw=600, peak_load_mw=0)
64
- engine.add_node("NODE_06", "gas", capacity_mw=500, region="SOUTH", critical=False,
65
- generation_mw=350, peak_load_mw=0)
66
- engine.add_node("NODE_07", "load", capacity_mw=0, region="SOUTH", critical=False,
67
- peak_load_mw=400, consumption_mw=380)
68
- engine.add_node("NODE_08", "battery", capacity_mw=250, region="SOUTH", critical=False,
69
- generation_mw=0, peak_load_mw=0)
70
-
71
- # ---- EAST region (nodes 09-12) ----
72
- engine.add_node("NODE_09", "gas", capacity_mw=900, region="EAST", critical=False,
73
- generation_mw=600, peak_load_mw=0)
74
- engine.add_node("NODE_10", "solar", capacity_mw=400, region="EAST", critical=False,
75
- generation_mw=300, peak_load_mw=0)
76
- engine.add_node("NODE_11", "load", capacity_mw=0, region="EAST", critical=True,
77
- peak_load_mw=600, consumption_mw=550) # Water treatment
78
- engine.add_node("NODE_12", "load", capacity_mw=0, region="EAST", critical=False,
79
- peak_load_mw=350, consumption_mw=320)
80
-
81
- # ---- WEST region (nodes 13-16) ----
82
- engine.add_node("NODE_13", "hydro", capacity_mw=1000, region="WEST", critical=False,
83
- generation_mw=700, peak_load_mw=0)
84
- engine.add_node("NODE_14", "gas", capacity_mw=700, region="WEST", critical=False,
85
- generation_mw=500, peak_load_mw=0) # This gets spoofed in Task 3
86
- engine.add_node("NODE_15", "load", capacity_mw=0, region="WEST", critical=True,
87
- peak_load_mw=450, consumption_mw=420) # Hospital
88
- engine.add_node("NODE_16", "battery", capacity_mw=350, region="WEST", critical=False,
89
- generation_mw=0, peak_load_mw=0)
90
-
91
- # ---- CENTRAL region (nodes 17-20) ----
92
- engine.add_node("NODE_17", "gas", capacity_mw=1500, region="CENTRAL", critical=False,
93
- generation_mw=1000, peak_load_mw=0) # Major turbine (Task 4 target)
94
- engine.add_node("NODE_18", "load", capacity_mw=0, region="CENTRAL", critical=True,
95
- peak_load_mw=700, consumption_mw=650) # Data center
96
- engine.add_node("NODE_19", "load", capacity_mw=0, region="CENTRAL", critical=False,
97
- peak_load_mw=300, consumption_mw=280)
98
- engine.add_node("NODE_20", "battery", capacity_mw=400, region="CENTRAL", critical=False,
99
- generation_mw=0, peak_load_mw=0)
100
-
101
- # ---- Transmission lines (40 edges) ----
102
- # NORTH internal
103
- engine.add_edge("LINE_01", "NODE_01", "NODE_02", capacity_mw=800)
104
- engine.add_edge("LINE_02", "NODE_01", "NODE_03", capacity_mw=600)
105
- engine.add_edge("LINE_03", "NODE_02", "NODE_03", capacity_mw=500)
106
- engine.add_edge("LINE_04", "NODE_02", "NODE_04", capacity_mw=400)
107
- engine.add_edge("LINE_05", "NODE_03", "NODE_04", capacity_mw=350)
108
-
109
- # SOUTH internal
110
- engine.add_edge("LINE_06", "NODE_05", "NODE_06", capacity_mw=600)
111
- engine.add_edge("LINE_07", "NODE_05", "NODE_07", capacity_mw=500)
112
- engine.add_edge("LINE_08", "NODE_06", "NODE_07", capacity_mw=450)
113
- engine.add_edge("LINE_09", "NODE_06", "NODE_08", capacity_mw=350)
114
- engine.add_edge("LINE_10", "NODE_07", "NODE_08", capacity_mw=300)
115
-
116
- # EAST internal
117
- engine.add_edge("LINE_11", "NODE_09", "NODE_10", capacity_mw=600)
118
- engine.add_edge("LINE_12", "NODE_09", "NODE_11", capacity_mw=700)
119
- engine.add_edge("LINE_13", "NODE_09", "NODE_12", capacity_mw=500)
120
- engine.add_edge("LINE_14", "NODE_10", "NODE_11", capacity_mw=450)
121
- engine.add_edge("LINE_15", "NODE_10", "NODE_12", capacity_mw=350)
122
- engine.add_edge("LINE_16", "NODE_11", "NODE_12", capacity_mw=400)
123
-
124
- # WEST internal
125
- engine.add_edge("LINE_17", "NODE_13", "NODE_14", capacity_mw=700)
126
- engine.add_edge("LINE_18", "NODE_13", "NODE_15", capacity_mw=600)
127
- engine.add_edge("LINE_19", "NODE_14", "NODE_15", capacity_mw=500)
128
- engine.add_edge("LINE_20", "NODE_14", "NODE_16", capacity_mw=450)
129
- engine.add_edge("LINE_21", "NODE_15", "NODE_16", capacity_mw=350)
130
-
131
- # CENTRAL internal
132
- engine.add_edge("LINE_22", "NODE_17", "NODE_18", capacity_mw=1000)
133
- engine.add_edge("LINE_23", "NODE_17", "NODE_19", capacity_mw=600)
134
- engine.add_edge("LINE_24", "NODE_17", "NODE_20", capacity_mw=500)
135
- engine.add_edge("LINE_25", "NODE_18", "NODE_19", capacity_mw=450)
136
- engine.add_edge("LINE_26", "NODE_18", "NODE_20", capacity_mw=400)
137
- engine.add_edge("LINE_27", "NODE_19", "NODE_20", capacity_mw=350)
138
-
139
- # Inter-region backbone lines
140
- engine.add_edge("LINE_28", "NODE_01", "NODE_17", capacity_mw=1200) # NORTH-CENTRAL (primary)
141
- engine.add_edge("LINE_29", "NODE_02", "NODE_09", capacity_mw=800) # NORTH-EAST
142
- engine.add_edge("LINE_30", "NODE_04", "NODE_13", capacity_mw=500) # NORTH-WEST
143
- engine.add_edge("LINE_31", "NODE_05", "NODE_17", capacity_mw=900) # SOUTH-CENTRAL
144
- engine.add_edge("LINE_32", "NODE_06", "NODE_09", capacity_mw=600) # SOUTH-EAST
145
- engine.add_edge("LINE_33", "NODE_08", "NODE_16", capacity_mw=400) # SOUTH-WEST
146
- engine.add_edge("LINE_34", "NODE_13", "NODE_17", capacity_mw=800) # WEST-CENTRAL
147
- engine.add_edge("LINE_35", "NODE_11", "NODE_18", capacity_mw=700) # EAST-CENTRAL
148
- engine.add_edge("LINE_36", "NODE_12", "NODE_19", capacity_mw=500) # EAST-CENTRAL2
149
- engine.add_edge("LINE_37", "NODE_14", "NODE_09", capacity_mw=600) # WEST-EAST
150
- engine.add_edge("LINE_38", "NODE_03", "NODE_15", capacity_mw=450) # NORTH-WEST (hospitals)
151
- engine.add_edge("LINE_39", "NODE_07", "NODE_12", capacity_mw=400) # SOUTH-EAST
152
- engine.add_edge("LINE_40", "NODE_16", "NODE_20", capacity_mw=500) # WEST-CENTRAL batteries
153
-
154
- # Set up weather zones
155
- engine.weather = {
156
- "NORTH": {"solar_irradiance": 0.6, "wind_speed_ms": 8.0, "cloud_cover": 0.3},
157
- "SOUTH": {"solar_irradiance": 0.8, "wind_speed_ms": 5.0, "cloud_cover": 0.2},
158
- "EAST": {"solar_irradiance": 0.5, "wind_speed_ms": 6.0, "cloud_cover": 0.4},
159
- "WEST": {"solar_irradiance": 0.7, "wind_speed_ms": 7.0, "cloud_cover": 0.25},
160
- "CENTRAL": {"solar_irradiance": 0.6, "wind_speed_ms": 4.0, "cloud_cover": 0.35},
161
- }
162
 
163
- # Initial power flow
164
- engine.compute_power_flow()
165
- engine.compute_frequency()
166
- engine._record_telemetry()
167
 
168
 
169
  # ---------------------------------------------------------------------------
170
- # Scenario-specific modifications
171
  # ---------------------------------------------------------------------------
172
 
173
- def build_scenario(task_id: int, seed: int = 42) -> Dict[str, Any]:
174
  """
175
- Build a complete scenario for the given task.
176
 
177
- Returns:
178
- Dict with keys: engine, attack_config, max_ticks, task_name, difficulty
179
  """
180
- engine = GridEngine(seed=seed)
181
- attack_config: Dict[str, Any] = {}
182
-
183
- if task_id == 0:
184
- # Task 0: Smoke test — basic topology, no modifications needed
185
- build_base_topology(engine)
186
-
187
- elif task_id == 1:
188
- # Task 1: Duck curve — solar ramp-down at sunset
189
- build_base_topology(engine)
190
- _setup_duck_curve(engine, seed)
191
-
192
- elif task_id == 2:
193
- # Task 2: Cascade overload — storm snaps primary line
194
- build_base_topology(engine)
195
- _setup_cascade_overload(engine, seed)
196
-
197
- elif task_id == 3:
198
- # Task 3: Phantom injection — NODE_14 spoofed
199
- build_base_topology(engine)
200
- attack_config = _setup_phantom_injection(engine, seed)
201
-
202
- elif task_id == 4:
203
- # Task 4: Stuxnet resonance — NODE_17 turbine under attack
204
- build_base_topology(engine)
205
- attack_config = _setup_stuxnet_resonance(engine, seed)
206
-
207
- elif task_id == 5:
208
- # Task 5: Black start — entire grid is dark
209
- build_base_topology(engine)
210
- _setup_black_start(engine, seed)
211
-
212
- else:
213
- raise ValueError(f"Unknown task_id: {task_id}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
 
215
- return {
216
- "engine": engine,
217
- "attack_config": attack_config,
218
- "max_ticks": MAX_TICKS[task_id],
219
- "task_name": TASK_NAMES[task_id],
220
- "difficulty": TASK_DIFFICULTIES[task_id],
221
  }
 
 
 
 
222
 
223
 
224
- def _setup_duck_curve(engine: GridEngine, seed: int) -> None:
225
- """
226
- Task 1: Solar generation drops rapidly (sunset) while demand spikes.
227
- The agent must proactively dispatch battery reserves.
228
- """
229
- # Reduce solar irradiance to simulate sunset
230
- for zone in engine.weather:
231
- engine.weather[zone]["solar_irradiance"] = 0.1 # Sunset
232
- engine.weather[zone]["cloud_cover"] = 0.8
233
 
234
- # Solar nodes drop to near-zero
235
- for node in engine.nodes.values():
236
- if node["node_type"] == "solar":
237
- node["generation_mw"] = node["capacity_mw"] * 0.05 # 5% residual
238
 
239
- # Spike demand
240
- for node in engine.nodes.values():
241
- if node["node_type"] == "load":
242
- node["consumption_mw"] = node["peak_load_mw"] * 0.95
243
 
244
- # Recompute -- this will show a frequency drop
245
- engine.compute_power_flow()
246
- engine.compute_frequency()
247
- engine._record_telemetry()
248
 
 
 
 
 
 
 
 
 
 
249
 
250
- def _setup_cascade_overload(engine: GridEngine, seed: int) -> None:
251
- """
252
- Task 2: A storm snaps the NORTH-CENTRAL primary line (LINE_28, 1200MW).
253
- Power reroutes through secondary paths and overloads them.
254
- """
255
- # Trip the primary backbone line
256
- engine.edges["LINE_28"]["status"] = "TRIPPED"
257
- engine.edges["LINE_28"]["current_load_mw"] = 0.0
258
 
259
- # Increase load to stress secondary paths
260
- for node in engine.nodes.values():
261
- if node["node_type"] == "load":
262
- node["consumption_mw"] = node["peak_load_mw"] * 0.90
263
 
264
- # Recompute -- secondary lines will be overloaded
265
- engine.compute_power_flow()
266
- engine.compute_frequency()
267
- engine.set_forced_edge_load("LINE_29", engine.edges["LINE_29"]["capacity_mw"] * 1.50)
268
- engine.set_forced_edge_load("LINE_34", engine.edges["LINE_34"]["capacity_mw"] * 0.88)
269
- engine.set_forced_edge_load("LINE_22", engine.edges["LINE_22"]["capacity_mw"] * 0.82)
270
- engine._record_telemetry()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
 
272
 
273
- def _setup_phantom_injection(engine: GridEngine, seed: int) -> Dict[str, Any]:
274
- """
275
- Task 3: NODE_14 is spoofed to report receiving 100MW when actually 0MW.
276
- Returns attack configuration for the spoof engine.
277
- """
278
- # NODE_14 is the target: its actual generation is already set to 500MW
279
- # The spoof will make it appear to have 600MW (adding phantom 100MW)
280
- attack_config = {
281
- "type": "phantom_injection",
282
- "target_node": "NODE_14",
283
- "phantom_mw": 100.0, # Extra MW injected into reports
284
- "start_tick": 0,
285
- "active": True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  }
 
 
 
 
 
287
 
288
- # Slightly reduce overall generation to make the grid vulnerable
289
- engine.nodes["NODE_14"]["generation_mw"] = 400.0 # Actual is 400, spoof reports 500
290
 
291
- engine.compute_power_flow()
292
- engine.compute_frequency()
293
- engine._record_telemetry()
 
294
 
295
- return attack_config
296
 
 
 
 
297
 
298
- def _setup_stuxnet_resonance(engine: GridEngine, seed: int) -> Dict[str, Any]:
299
- """
300
- Task 4: NODE_17 (1500MW turbine) is being oscillated at 0.5Hz intervals.
301
- Agent must inject counter-signal at correct hz_offset.
302
- """
303
- attack_config = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  "type": "resonance_oscillation",
305
- "target_node": "NODE_17",
306
- "oscillation_hz": 0.5, # Attack frequency offset
307
- "start_tick": 0,
308
- "destruction_tick": 10, # Turbine destroyed if not countered by tick 10
 
 
309
  "active": True,
310
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
 
312
- engine.compute_power_flow()
313
- engine.compute_frequency()
314
- engine._record_telemetry()
315
-
316
- return attack_config
317
 
 
 
 
318
 
319
- def _setup_black_start(engine: GridEngine, seed: int) -> None:
320
- """
321
- Task 5: Entire grid is dark. All nodes de-energized except NODE_01 (hydro dam).
322
- Agent must restart the grid from scratch.
323
- """
324
- # De-energize everything
325
- for node in engine.nodes.values():
326
- node["energized"] = False
327
- node["generation_mw"] = 0.0
328
- node["consumption_mw"] = 0.0
329
- node["voltage_kv"] = 0.0
330
-
331
- # Trip all lines
332
- for edge in engine.edges.values():
333
- edge["status"] = "TRIPPED"
334
- edge["current_load_mw"] = 0.0
335
-
336
- # NODE_01 (hydro dam) can be energized — it has black-start capability
337
- engine.nodes["NODE_01"]["energized"] = True
338
- engine.nodes["NODE_01"]["voltage_kv"] = 345.0
339
- # But generation is still 0 — agent must dispatch
340
-
341
- # Set frequency to near-zero (grid is dead)
342
- engine.frequency_hz = 59.0
343
-
344
- engine._record_telemetry()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ NexusGrid — Seeded Scenario Generator.
3
 
4
+ Every task is a *family* of scenarios. The episode seed drives a dedicated
5
+ random stream (``SeedSequence([seed, task_id])``) that picks the disturbance,
6
+ its location, its timing and the operating point, so a policy cannot pass by
7
+ memorising one fixed action sequence.
8
+
9
+ Seeds ``>= EVAL_SEED_START`` draw from held-out parameter sets (for Task 2,
10
+ a disjoint part of the validated contingency catalog) so evaluation runs on
11
+ scenarios a policy never trained on.
12
  """
13
 
14
  from __future__ import annotations
15
 
16
+ import copy
17
+ import json
18
+ import math
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+ from typing import Any, Dict, List, Optional
22
 
23
+ import numpy as np
24
 
25
+ from .grid_engine import GridEngine
26
 
 
27
  MAX_TICKS = {
28
  0: 3, # Smoke test
29
  1: 15, # Duck curve
 
51
  5: "expert",
52
  }
53
 
54
+ EVAL_SEED_START = 10_000
55
+ FORECAST_HORIZON = 6
56
+ ZONES = ("NORTH", "SOUTH", "EAST", "WEST", "CENTRAL")
57
+ CATALOG_PATH = Path(__file__).with_name("data") / "cascade_catalog.json"
58
 
59
+ BACKBONE_LINES = [f"LINE_{i}" for i in range(28, 41)]
60
+ PHANTOM_TARGETS = ["NODE_02", "NODE_06", "NODE_09", "NODE_13", "NODE_14", "NODE_17"]
61
+ RESONANCE_TARGETS = ["NODE_17", "NODE_09", "NODE_13", "NODE_01"]
62
+ BLACK_START_UNITS = ["NODE_01", "NODE_13"]
63
+
64
+
65
+ def is_eval_seed(seed: int) -> bool:
66
+ return int(seed) >= EVAL_SEED_START
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ def scenario_rng(task_id: int, seed: int) -> np.random.Generator:
70
+ return np.random.Generator(np.random.PCG64(np.random.SeedSequence([int(seed), int(task_id), 3])))
 
 
71
 
72
 
73
  # ---------------------------------------------------------------------------
74
+ # Base network
75
  # ---------------------------------------------------------------------------
76
 
77
+ def build_base_topology(engine: GridEngine, load_factor: float = 0.85, solar_irradiance: float = 0.6) -> None:
78
  """
79
+ Build the 20-bus, 40-line network and balance it at ``load_factor``.
80
 
81
+ Regions: NORTH, SOUTH, EAST, WEST, CENTRAL. Critical loads: NODE_03 and
82
+ NODE_15 (hospitals), NODE_11 (water treatment), NODE_18 (data centre).
83
  """
84
+ add = engine.add_node
85
+ # NORTH
86
+ add("NODE_01", "hydro", capacity_mw=1200, region="NORTH", black_start_capable=True)
87
+ add("NODE_02", "gas", capacity_mw=600, region="NORTH")
88
+ add("NODE_03", "load", capacity_mw=0, region="NORTH", critical=True, peak_load_mw=500)
89
+ add("NODE_04", "battery", capacity_mw=300, region="NORTH")
90
+ # SOUTH
91
+ add("NODE_05", "solar", capacity_mw=800, region="SOUTH")
92
+ add("NODE_06", "gas", capacity_mw=500, region="SOUTH")
93
+ add("NODE_07", "load", capacity_mw=0, region="SOUTH", peak_load_mw=400)
94
+ add("NODE_08", "battery", capacity_mw=250, region="SOUTH")
95
+ # EAST
96
+ add("NODE_09", "gas", capacity_mw=900, region="EAST")
97
+ add("NODE_10", "solar", capacity_mw=400, region="EAST")
98
+ add("NODE_11", "load", capacity_mw=0, region="EAST", critical=True, peak_load_mw=600)
99
+ add("NODE_12", "load", capacity_mw=0, region="EAST", peak_load_mw=350)
100
+ # WEST
101
+ add("NODE_13", "hydro", capacity_mw=1000, region="WEST")
102
+ add("NODE_14", "gas", capacity_mw=700, region="WEST")
103
+ add("NODE_15", "load", capacity_mw=0, region="WEST", critical=True, peak_load_mw=450)
104
+ add("NODE_16", "battery", capacity_mw=350, region="WEST")
105
+ # CENTRAL
106
+ add("NODE_17", "gas", capacity_mw=1500, region="CENTRAL")
107
+ add("NODE_18", "load", capacity_mw=0, region="CENTRAL", critical=True, peak_load_mw=700)
108
+ add("NODE_19", "load", capacity_mw=0, region="CENTRAL", peak_load_mw=300)
109
+ add("NODE_20", "battery", capacity_mw=400, region="CENTRAL")
110
+
111
+ line = engine.add_edge
112
+ # Regional networks
113
+ line("LINE_01", "NODE_01", "NODE_02", 800)
114
+ line("LINE_02", "NODE_01", "NODE_03", 600)
115
+ line("LINE_03", "NODE_02", "NODE_03", 500)
116
+ line("LINE_04", "NODE_02", "NODE_04", 400)
117
+ line("LINE_05", "NODE_03", "NODE_04", 350)
118
+ line("LINE_06", "NODE_05", "NODE_06", 600)
119
+ line("LINE_07", "NODE_05", "NODE_07", 500)
120
+ line("LINE_08", "NODE_06", "NODE_07", 450)
121
+ line("LINE_09", "NODE_06", "NODE_08", 350)
122
+ line("LINE_10", "NODE_07", "NODE_08", 300)
123
+ line("LINE_11", "NODE_09", "NODE_10", 600)
124
+ line("LINE_12", "NODE_09", "NODE_11", 700)
125
+ line("LINE_13", "NODE_09", "NODE_12", 500)
126
+ line("LINE_14", "NODE_10", "NODE_11", 450)
127
+ line("LINE_15", "NODE_10", "NODE_12", 350)
128
+ line("LINE_16", "NODE_11", "NODE_12", 400)
129
+ line("LINE_17", "NODE_13", "NODE_14", 700)
130
+ line("LINE_18", "NODE_13", "NODE_15", 600)
131
+ line("LINE_19", "NODE_14", "NODE_15", 500)
132
+ line("LINE_20", "NODE_14", "NODE_16", 450)
133
+ line("LINE_21", "NODE_15", "NODE_16", 350)
134
+ line("LINE_22", "NODE_17", "NODE_18", 1000)
135
+ line("LINE_23", "NODE_17", "NODE_19", 600)
136
+ line("LINE_24", "NODE_17", "NODE_20", 500)
137
+ line("LINE_25", "NODE_18", "NODE_19", 450)
138
+ line("LINE_26", "NODE_18", "NODE_20", 400)
139
+ line("LINE_27", "NODE_19", "NODE_20", 350)
140
+ # Inter-regional backbone
141
+ line("LINE_28", "NODE_01", "NODE_17", 1200) # NORTH-CENTRAL (primary)
142
+ line("LINE_29", "NODE_02", "NODE_09", 800) # NORTH-EAST
143
+ line("LINE_30", "NODE_04", "NODE_13", 500) # NORTH-WEST
144
+ line("LINE_31", "NODE_05", "NODE_17", 900) # SOUTH-CENTRAL
145
+ line("LINE_32", "NODE_06", "NODE_09", 600) # SOUTH-EAST
146
+ line("LINE_33", "NODE_08", "NODE_16", 400) # SOUTH-WEST
147
+ line("LINE_34", "NODE_13", "NODE_17", 800) # WEST-CENTRAL
148
+ line("LINE_35", "NODE_11", "NODE_18", 700) # EAST-CENTRAL
149
+ line("LINE_36", "NODE_12", "NODE_19", 500) # EAST-CENTRAL 2
150
+ line("LINE_37", "NODE_14", "NODE_09", 600) # WEST-EAST
151
+ line("LINE_38", "NODE_03", "NODE_15", 450) # NORTH-WEST (hospitals)
152
+ line("LINE_39", "NODE_07", "NODE_12", 400) # SOUTH-EAST
153
+ line("LINE_40", "NODE_16", "NODE_20", 500) # WEST-CENTRAL batteries
154
 
155
+ engine.weather = {
156
+ zone: {"solar_irradiance": float(solar_irradiance), "wind_speed_ms": 6.0, "cloud_cover": 0.25}
157
+ for zone in ZONES
 
 
 
158
  }
159
+ set_load_factor(engine, load_factor)
160
+ set_solar(engine, {zone: float(solar_irradiance) for zone in ZONES}, cloud=0.25)
161
+ engine.balance_dispatch()
162
+ engine.settle()
163
 
164
 
165
+ def set_load_factor(engine: GridEngine, load_factor: float, jitter: Optional[Dict[str, float]] = None) -> None:
166
+ for nid, n in engine.nodes.items():
167
+ if n["node_type"] != "load":
168
+ continue
169
+ mult = jitter.get(nid, 1.0) if jitter else 1.0
170
+ demand = min(n["peak_load_mw"], n["peak_load_mw"] * load_factor * mult)
171
+ n["base_consumption_mw"] = demand
172
+ if n["energized"]:
173
+ n["demand_mw"] = demand
174
 
 
 
 
 
175
 
176
+ def solar_output_factor(irradiance: float, cloud: float) -> float:
177
+ return max(0.0, min(1.0, irradiance * (1.0 - 0.7 * cloud)))
 
 
178
 
 
 
 
 
179
 
180
+ def set_solar(engine: GridEngine, irradiance: Dict[str, float], cloud: float) -> None:
181
+ for zone, irr in irradiance.items():
182
+ if zone in engine.weather:
183
+ engine.weather[zone]["solar_irradiance"] = float(irr)
184
+ engine.weather[zone]["cloud_cover"] = float(cloud)
185
+ for n in engine.nodes.values():
186
+ if n["node_type"] == "solar":
187
+ irr = irradiance.get(n["region"], 0.5)
188
+ n["available_mw"] = n["capacity_mw"] * solar_output_factor(irr, cloud)
189
 
 
 
 
 
 
 
 
 
190
 
191
+ # ---------------------------------------------------------------------------
192
+ # Time-varying schedules (load and solar curves)
193
+ # ---------------------------------------------------------------------------
 
194
 
195
+ @dataclass
196
+ class Schedule:
197
+ """Per-tick operating conditions: load factor and solar irradiance."""
198
+
199
+ load_factor: List[float]
200
+ irradiance: List[float]
201
+ cloud: float = 0.25
202
+ jitter: Dict[str, float] = field(default_factory=dict)
203
+ wind: float = 6.0
204
+
205
+ def at(self, values: List[float], tick: int) -> float:
206
+ return values[min(max(tick, 0), len(values) - 1)]
207
+
208
+ def apply(self, engine: GridEngine, tick: int) -> None:
209
+ lf = self.at(self.load_factor, tick)
210
+ irr = self.at(self.irradiance, tick)
211
+ set_load_factor(engine, lf, self.jitter)
212
+ set_solar(engine, {zone: irr for zone in ZONES}, self.cloud)
213
+ for zone in ZONES:
214
+ engine.weather[zone]["wind_speed_ms"] = self.wind
215
+ horizon = range(tick + 1, tick + 1 + FORECAST_HORIZON)
216
+ engine.weather_forecast = {zone: [self.at(self.irradiance, t) for t in horizon] for zone in ZONES}
217
+ loads = [(n["peak_load_mw"], self.jitter.get(nid, 1.0)) for nid, n in engine.nodes.items()
218
+ if n["node_type"] == "load"]
219
+ solar_cap = sum(n["capacity_mw"] for n in engine.nodes.values() if n["node_type"] == "solar")
220
+ engine.demand_forecast = [
221
+ round(sum(min(peak, peak * self.at(self.load_factor, t) * mult) for peak, mult in loads), 1)
222
+ for t in horizon
223
+ ]
224
+ engine.solar_forecast = [round(solar_cap * solar_output_factor(self.at(self.irradiance, t), self.cloud), 1)
225
+ for t in horizon]
226
+
227
+
228
+ def _constant(value: float, ticks: int) -> List[float]:
229
+ return [float(value)] * (ticks + FORECAST_HORIZON + 2)
230
+
231
+
232
+ def _ramp(start: float, end: float, ramp_start: int, ramp_len: int, ticks: int) -> List[float]:
233
+ values = []
234
+ for t in range(ticks + FORECAST_HORIZON + 2):
235
+ if t <= ramp_start:
236
+ values.append(start)
237
+ elif t >= ramp_start + ramp_len:
238
+ values.append(end)
239
+ else:
240
+ frac = (t - ramp_start) / ramp_len
241
+ frac = 0.5 - 0.5 * math.cos(math.pi * frac) # smooth S-curve
242
+ values.append(start + (end - start) * frac)
243
+ return values
244
+
245
+
246
+ def _load_jitter(rng: np.random.Generator, engine: GridEngine) -> Dict[str, float]:
247
+ return {nid: float(rng.uniform(0.94, 1.04)) for nid, n in engine.nodes.items() if n["node_type"] == "load"}
248
 
249
 
250
+ # ---------------------------------------------------------------------------
251
+ # Scenario container
252
+ # ---------------------------------------------------------------------------
253
+
254
+ @dataclass
255
+ class Scenario:
256
+ task_id: int
257
+ seed: int
258
+ engine: GridEngine
259
+ schedule: Schedule
260
+ attack_config: Dict[str, Any]
261
+ params: Dict[str, Any]
262
+ brief: str
263
+
264
+ @property
265
+ def max_ticks(self) -> int:
266
+ return MAX_TICKS[self.task_id]
267
+
268
+ def as_dict(self) -> Dict[str, Any]:
269
+ return {
270
+ "engine": self.engine,
271
+ "schedule": self.schedule,
272
+ "attack_config": self.attack_config,
273
+ "params": self.params,
274
+ "brief": self.brief,
275
+ "max_ticks": self.max_ticks,
276
+ "task_name": TASK_NAMES[self.task_id],
277
+ "difficulty": TASK_DIFFICULTIES[self.task_id],
278
+ "split": "eval" if is_eval_seed(self.seed) else "train",
279
+ }
280
+
281
+
282
+ def build_scenario(task_id: int, seed: int = 42) -> Dict[str, Any]:
283
+ """Build the scenario for ``task_id`` drawn from the seed's random stream."""
284
+ if task_id not in MAX_TICKS:
285
+ raise ValueError(f"Unknown task_id: {task_id}")
286
+ rng = scenario_rng(task_id, seed)
287
+ builders = {
288
+ 0: _smoke_test,
289
+ 1: _duck_curve,
290
+ 2: _cascade_overload,
291
+ 3: _phantom_injection,
292
+ 4: _stuxnet_resonance,
293
+ 5: _black_start,
294
  }
295
+ scenario = builders[task_id](rng, int(seed))
296
+ scenario.engine.tick = 0
297
+ scenario.schedule.apply(scenario.engine, 0)
298
+ scenario.engine.settle()
299
+ return scenario.as_dict()
300
 
 
 
301
 
302
+ def _new_engine(seed: int, load_factor: float, irradiance: float) -> GridEngine:
303
+ engine = GridEngine(seed=seed)
304
+ build_base_topology(engine, load_factor=load_factor, solar_irradiance=irradiance)
305
+ return engine
306
 
 
307
 
308
+ # ---------------------------------------------------------------------------
309
+ # Task builders
310
+ # ---------------------------------------------------------------------------
311
 
312
+ def _smoke_test(rng: np.random.Generator, seed: int) -> Scenario:
313
+ lf = float(rng.uniform(0.70, 0.90))
314
+ irr = float(rng.uniform(0.3, 0.8))
315
+ engine = _new_engine(seed, lf, irr)
316
+ schedule = Schedule(load_factor=_constant(lf, 3), irradiance=_constant(irr, 3), jitter=_load_jitter(rng, engine))
317
+ set_load_factor(engine, lf, schedule.jitter)
318
+ engine.balance_dispatch()
319
+ return Scenario(0, seed, engine, schedule, {}, {"load_factor": lf, "irradiance": irr},
320
+ "Normal operations. Issue any safe positive dispatch to prove the control loop works.")
321
+
322
+
323
+ def _duck_curve(rng: np.random.Generator, seed: int) -> Scenario:
324
+ ticks = MAX_TICKS[1]
325
+ lf0 = float(rng.uniform(0.72, 0.80))
326
+ lf1 = float(min(1.0, lf0 + rng.uniform(0.18, 0.26)))
327
+ irr0 = float(rng.uniform(0.72, 0.92))
328
+ irr1 = float(rng.uniform(0.0, 0.06))
329
+ ramp_start = int(rng.integers(1, 3))
330
+ ramp_len = int(rng.integers(5, 9))
331
+ cloud = float(rng.uniform(0.05, 0.25))
332
+ engine = _new_engine(seed, lf0, irr0)
333
+ schedule = Schedule(
334
+ load_factor=_ramp(lf0, lf1, ramp_start, ramp_len + 2, ticks),
335
+ irradiance=_ramp(irr0, irr1, ramp_start, ramp_len, ticks),
336
+ cloud=cloud,
337
+ jitter=_load_jitter(rng, engine),
338
+ )
339
+ set_load_factor(engine, lf0, schedule.jitter)
340
+ set_solar(engine, {z: irr0 for z in ZONES}, cloud)
341
+ engine.balance_dispatch()
342
+ params = {"load_start": lf0, "load_end": lf1, "irradiance_start": irr0, "irradiance_end": irr1,
343
+ "ramp_start": ramp_start, "ramp_len": ramp_len, "cloud": cloud}
344
+ brief = ("Evening ramp: solar output will fall over the next hour while demand climbs to the evening peak. "
345
+ "Use the forecasts and keep frequency inside 59.8-60.2 Hz.")
346
+ return Scenario(1, seed, engine, schedule, {}, params, brief)
347
+
348
+
349
+ def _phantom_injection(rng: np.random.Generator, seed: int) -> Scenario:
350
+ lf = float(rng.uniform(0.80, 0.92))
351
+ irr = float(rng.uniform(0.3, 0.6))
352
+ engine = _new_engine(seed, lf, irr)
353
+ schedule = Schedule(load_factor=_constant(lf, 18), irradiance=_constant(irr, 18), jitter=_load_jitter(rng, engine))
354
+ set_load_factor(engine, lf, schedule.jitter)
355
+ engine.balance_dispatch()
356
+ target = str(rng.choice(PHANTOM_TARGETS))
357
+ start = int(rng.integers(1, 4))
358
+ rate = float(rng.uniform(70.0, 130.0))
359
+ max_loss = float(min(engine.nodes[target]["setpoint_mw"] * 0.95, rng.uniform(350.0, 600.0)))
360
+ others = [nid for nid in engine.nodes if nid != target]
361
+ decoys = [str(x) for x in rng.choice(others, size=2, replace=False)]
362
+ attack = {
363
+ "type": "phantom_injection",
364
+ "target_node": target,
365
+ "start_tick": start,
366
+ "loss_rate_mw": rate,
367
+ "max_loss_mw": max_loss,
368
+ "decoy_nodes": decoys,
369
+ "decoy_tick": int(rng.integers(0, 6)),
370
+ "active": True,
371
+ }
372
+ brief = ("SOC alert: possible SCADA compromise. Telemetry may be falsified. Triage packet logs, verify with "
373
+ "state estimation (max 6 buses per call), quarantine only proven nodes, then restore frequency.")
374
+ return Scenario(3, seed, engine, schedule, attack, {"load_factor": lf, **{k: v for k, v in attack.items() if k != "active"}}, brief)
375
+
376
+
377
+ def _stuxnet_resonance(rng: np.random.Generator, seed: int) -> Scenario:
378
+ lf = float(rng.uniform(0.80, 0.92))
379
+ irr = float(rng.uniform(0.3, 0.6))
380
+ engine = _new_engine(seed, lf, irr)
381
+ schedule = Schedule(load_factor=_constant(lf, 12), irradiance=_constant(irr, 12), jitter=_load_jitter(rng, engine))
382
+ set_load_factor(engine, lf, schedule.jitter)
383
+ engine.balance_dispatch()
384
+ target = str(rng.choice(RESONANCE_TARGETS))
385
+ mode = float(round(rng.uniform(0.30, 0.80) / 0.05) * 0.05)
386
+ attack = {
387
  "type": "resonance_oscillation",
388
+ "target_node": target,
389
+ "mode_hz": round(mode, 2),
390
+ "start_tick": int(rng.integers(0, 2)),
391
+ "initial_amplitude_hz": float(rng.uniform(0.03, 0.05)),
392
+ "growth": float(rng.uniform(1.30, 1.45)),
393
+ "destruction_amplitude_hz": 0.35,
394
  "active": True,
395
  }
396
+ brief = ("PMU alarm: a forced oscillation is building on a large generator. Do not disconnect the unit. "
397
+ "Identify the oscillating unit and its mode from telemetry, damp it with a counter-signal from a "
398
+ "nearby battery (within 2 hops), then detune the unit and rebalance.")
399
+ return Scenario(4, seed, engine, schedule, attack, {"load_factor": lf, **{k: v for k, v in attack.items() if k != "active"}}, brief)
400
+
401
+
402
+ def _black_start(rng: np.random.Generator, seed: int) -> Scenario:
403
+ lf = float(rng.uniform(0.65, 0.85))
404
+ engine = _new_engine(seed, lf, 0.05)
405
+ schedule = Schedule(load_factor=_constant(lf, 50), irradiance=_constant(float(rng.uniform(0.0, 0.08)), 50),
406
+ jitter=_load_jitter(rng, engine), cloud=0.6)
407
+ set_load_factor(engine, lf, schedule.jitter)
408
+ bs_unit = str(rng.choice(BLACK_START_UNITS))
409
+ for nid, n in engine.nodes.items():
410
+ n["black_start_capable"] = nid == bs_unit
411
+ n["energized"] = nid == bs_unit
412
+ n["setpoint_mw"] = 0.0
413
+ n["generation_mw"] = 0.0
414
+ n["consumption_mw"] = 0.0
415
+ n["shed_mw"] = 0.0
416
+ n["frequency_hz"] = 60.0 if nid == bs_unit else 0.0
417
+ n["voltage_kv"] = 345.0 if nid == bs_unit else 0.0
418
+ for e in engine.edges.values():
419
+ e["status"] = "TRIPPED"
420
+ brief = (f"System-wide blackout. Only {bs_unit} has black-start capability. Restart it, energise lines "
421
+ "step by step, raise generation before picking up load, keep each island inside 59.5-60.5 Hz, "
422
+ "and restore critical loads first.")
423
+ return Scenario(5, seed, engine, schedule, {}, {"load_factor": lf, "black_start_unit": bs_unit}, brief)
424
 
 
 
 
 
 
425
 
426
+ # ---------------------------------------------------------------------------
427
+ # Task 2: validated contingency catalog
428
+ # ---------------------------------------------------------------------------
429
 
430
+ def apply_cascade_config(engine: GridEngine, config: Dict[str, Any]) -> None:
431
+ """Apply a stressed dispatch, maintenance outages and the storm trip."""
432
+ set_load_factor(engine, config["load_factor"])
433
+ set_solar(engine, {z: config["irradiance"] for z in ZONES}, 0.25)
434
+ for nid, setpoint in config["setpoints"].items():
435
+ engine.nodes[nid]["setpoint_mw"] = float(setpoint)
436
+ for nid, n in engine.nodes.items():
437
+ if n["node_type"] == "battery":
438
+ n["setpoint_mw"] = 0.0
439
+ for line_id in config["outages"]:
440
+ engine.set_out_of_service(line_id, "maintenance")
441
+ engine.set_out_of_service(config["trip_line"], "storm damage")
442
+ engine.settle()
443
+
444
+
445
+ def stressed_setpoints(engine: GridEngine, rng: np.random.Generator, exporters: List[str]) -> Optional[Dict[str, float]]:
446
+ demand = sum(n["demand_mw"] for n in engine.nodes.values() if n["node_type"] == "load")
447
+ solar = sum(min(n["available_mw"], n["capacity_mw"]) for n in engine.nodes.values() if n["node_type"] == "solar")
448
+ need = demand - solar
449
+ gens = [nid for nid, n in engine.nodes.items() if n["node_type"] in ("hydro", "gas")]
450
+ setpoints = {nid: 0.0 for nid in gens}
451
+ exp_units = [g for g in gens if engine.nodes[g]["region"] in exporters]
452
+ for g in exp_units:
453
+ setpoints[g] = engine.nodes[g]["capacity_mw"] * float(rng.uniform(0.80, 0.95))
454
+ rest = need - sum(setpoints[g] for g in exp_units)
455
+ others = [g for g in gens if g not in exp_units]
456
+ cap_others = sum(engine.nodes[g]["capacity_mw"] for g in others)
457
+ if rest < 0 or cap_others <= 0:
458
+ return None
459
+ for g in others:
460
+ setpoints[g] = rest * engine.nodes[g]["capacity_mw"] / cap_others
461
+ return {k: round(v, 2) for k, v in setpoints.items()}
462
+
463
+
464
+ def cascade_config_check(config: Dict[str, Any]) -> Dict[str, Any]:
465
+ """Return validity information for a Task 2 configuration."""
466
+ engine = GridEngine(seed=0)
467
+ build_base_topology(engine, load_factor=config["load_factor"], solar_irradiance=config["irradiance"])
468
+ # Pre-contingency: outages only, must be secure.
469
+ set_load_factor(engine, config["load_factor"])
470
+ for nid, setpoint in config["setpoints"].items():
471
+ engine.nodes[nid]["setpoint_mw"] = float(setpoint)
472
+ for nid, n in engine.nodes.items():
473
+ if n["node_type"] == "battery":
474
+ n["setpoint_mw"] = 0.0
475
+ for line_id in config["outages"]:
476
+ engine.edges[line_id]["status"] = "TRIPPED"
477
+ engine.settle()
478
+ pre_ok = len(engine.get_stable_islands()) == 1 and engine.get_max_loading() <= 0.97
479
+ engine.edges[config["trip_line"]]["status"] = "TRIPPED"
480
+ engine.settle()
481
+ islands = len(engine.get_stable_islands())
482
+ max_loading = engine.get_max_loading()
483
+ overloaded = engine.get_overloaded_edges(1.0)
484
+ valid = pre_ok and islands == 1 and 1.06 <= max_loading <= 1.35 and abs(engine.frequency_hz - 60.0) < 0.05
485
+ return {"valid": bool(valid), "max_loading": round(max_loading, 3), "overloaded": overloaded}
486
+
487
+
488
+ def generate_cascade_catalog(count: int = 240, seed: int = 2026, max_trials: int = 20000) -> List[Dict[str, Any]]:
489
+ """Search for stressed operating points where one storm trip overloads the grid."""
490
+ rng = np.random.Generator(np.random.PCG64(seed))
491
+ catalog: List[Dict[str, Any]] = []
492
+ seen = set()
493
+ for _ in range(max_trials):
494
+ if len(catalog) >= count:
495
+ break
496
+ lf = float(rng.uniform(0.88, 1.0))
497
+ irr = float(rng.uniform(0.2, 0.5))
498
+ engine = GridEngine(seed=0)
499
+ build_base_topology(engine, load_factor=lf, solar_irradiance=irr)
500
+ exporters = [str(x) for x in rng.choice(list(ZONES), size=2, replace=False)]
501
+ setpoints = stressed_setpoints(engine, rng, exporters)
502
+ if setpoints is None:
503
+ continue
504
+ outages = [str(x) for x in rng.choice(BACKBONE_LINES, size=int(rng.integers(1, 3)), replace=False)]
505
+ candidates = [b for b in BACKBONE_LINES if b not in outages]
506
+ rng.shuffle(candidates)
507
+ for trip in candidates[:6]:
508
+ config = {"load_factor": round(lf, 4), "irradiance": round(irr, 4), "exporters": sorted(exporters),
509
+ "setpoints": setpoints, "outages": sorted(outages), "trip_line": trip}
510
+ key = (tuple(sorted(exporters)), tuple(sorted(outages)), trip, round(lf, 2))
511
+ if key in seen:
512
+ continue
513
+ info = cascade_config_check(config)
514
+ if info["valid"]:
515
+ seen.add(key)
516
+ config["max_loading"] = info["max_loading"]
517
+ config["overloaded"] = info["overloaded"]
518
+ catalog.append(config)
519
+ break
520
+ return catalog
521
+
522
+
523
+ _CATALOG_CACHE: Optional[List[Dict[str, Any]]] = None
524
+
525
+
526
+ def load_cascade_catalog() -> List[Dict[str, Any]]:
527
+ global _CATALOG_CACHE
528
+ if _CATALOG_CACHE is None:
529
+ if CATALOG_PATH.exists():
530
+ _CATALOG_CACHE = json.loads(CATALOG_PATH.read_text(encoding="utf-8"))["configs"]
531
+ else: # pragma: no cover - only when the data file is missing
532
+ _CATALOG_CACHE = generate_cascade_catalog(count=60)
533
+ return _CATALOG_CACHE
534
+
535
+
536
+ def _cascade_overload(rng: np.random.Generator, seed: int) -> Scenario:
537
+ catalog = load_cascade_catalog()
538
+ split_at = int(len(catalog) * 0.8)
539
+ pool = catalog[split_at:] if is_eval_seed(seed) else catalog[:split_at]
540
+ config = copy.deepcopy(pool[int(rng.integers(len(pool)))])
541
+ engine = GridEngine(seed=seed)
542
+ build_base_topology(engine, load_factor=config["load_factor"], solar_irradiance=config["irradiance"])
543
+ apply_cascade_config(engine, config)
544
+ schedule = Schedule(load_factor=_constant(config["load_factor"], 20), irradiance=_constant(config["irradiance"], 20))
545
+ for e in engine.edges.values():
546
+ if e["status"] == "LIVE" and e["loading"] > 1.0:
547
+ e["overload_ticks"] = 0
548
+ outages = ", ".join(config["outages"])
549
+ brief = (f"Storm damage: {config['trip_line']} has tripped while {outages} is out for maintenance. "
550
+ "Power is rerouting and some lines are above their thermal rating. Relays trip lines that stay above "
551
+ "100% for 3 ticks (instantly above 140%). Relieve the overloads without losing critical loads.")
552
+ params = {k: v for k, v in config.items() if k not in ("setpoints",)}
553
+ return Scenario(2, seed, engine, schedule, {}, params, brief)
server/spoof_engine.py CHANGED
@@ -1,9 +1,22 @@
1
  """
2
- NexusGrid — SCADA Spoof Engine (Layer 2).
3
-
4
- Deterministic sensor spoofing engine with three attack vectors.
5
- All randomness uses numpy.random.Generator(PCG64(episode_seed)).
6
- Seed-lock contract: identical seeds produce identical attack sequences.
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  """
8
 
9
  from __future__ import annotations
@@ -14,225 +27,147 @@ import numpy as np
14
 
15
 
16
  class SpoofEngine:
17
- """
18
- Selectively overwrites ground-truth telemetry with fabricated readings.
19
-
20
- Three attack vectors:
21
- 1. Man-in-the-Middle injection — substation reports fabricated MW.
22
- 2. Resonance oscillation — generator frequency modulated ±0.1Hz.
23
- 3. Phantom generation — renewable reports full output during zero-generation.
24
-
25
- Network packet logs show latency spikes 1-2 ticks before a node is spoofed.
26
- """
27
 
28
- # Packet log constants
29
  NORMAL_LATENCY_MS = 5.0
30
  ANOMALY_LATENCY_MS = 120.0
31
  ANOMALY_THRESHOLD_MS = 50.0
32
 
33
  def __init__(self, seed: int = 42):
34
- self._rng = np.random.Generator(np.random.PCG64(seed))
35
- self._seed = seed
36
  self._tick = 0
37
-
38
- # Active spoof configurations
39
  self._spoofs: List[Dict[str, Any]] = []
40
-
41
- # Quarantined nodes (no longer spoofable)
42
  self._quarantined: set = set()
43
-
44
- # Packet log history (for anomaly detection)
45
  self._packet_history: List[Dict[str, Any]] = []
46
-
47
- # Consecutive high-latency counts per source node
48
  self._consecutive_high_latency: Dict[str, int] = {}
49
 
50
  def reset(self, seed: int = 42) -> None:
51
- """Reset spoof engine to initial state."""
52
- self._rng = np.random.Generator(np.random.PCG64(seed))
53
- self._seed = seed
54
- self._tick = 0
55
- self._spoofs = []
56
- self._quarantined = set()
57
- self._packet_history = []
58
- self._consecutive_high_latency = {}
59
 
60
- def configure_attack(self, attack_config: Dict[str, Any]) -> None:
61
- """
62
- Configure an attack based on scenario specification.
63
 
64
- Args:
65
- attack_config: Dict with 'type', 'target_node', and attack-specific fields.
66
- """
67
  if not attack_config or not attack_config.get("active"):
68
  return
69
-
70
- self._spoofs.append(dict(attack_config))
 
 
71
 
72
  def advance_tick(self) -> None:
73
- """Advance the spoof engine by one tick."""
74
  self._tick += 1
75
 
76
- def apply_spoofs(
77
- self,
78
- ground_truth: Dict[str, Dict[str, Any]],
79
- tick: int,
80
- ) -> Dict[str, Dict[str, Any]]:
81
- """
82
- Apply active spoofs to ground-truth telemetry.
83
-
84
- Returns a copy of telemetry with spoofed values injected.
85
- Quarantined nodes are NOT spoofed (replaced with estimator values).
86
- """
 
 
 
 
 
 
 
 
87
  self._tick = tick
88
- spoofed = {}
89
-
90
- for node_id, truth in ground_truth.items():
91
- spoofed[node_id] = dict(truth)
92
-
93
  for spoof in self._spoofs:
94
- if not spoof.get("active"):
95
- continue
96
-
97
  target = spoof.get("target_node")
98
- if not target or target in self._quarantined:
99
- continue
100
-
101
- if target not in spoofed:
102
  continue
103
-
104
- spoof_type = spoof.get("type")
105
-
106
- if spoof_type == "phantom_injection":
107
- # Add phantom MW to generation reading
108
- phantom_mw = spoof.get("phantom_mw", 100.0)
109
- spoofed[target]["generation_mw"] = (
110
- ground_truth[target]["generation_mw"] + phantom_mw
111
- )
112
-
113
- elif spoof_type == "resonance_oscillation":
114
- # Modulate frequency by ±0.1Hz oscillation
115
- oscillation = 0.1 * np.sin(2 * np.pi * spoof.get("oscillation_hz", 0.5) * tick)
116
- spoofed[target]["frequency_hz"] = (
117
- ground_truth[target]["frequency_hz"] + float(oscillation)
118
- )
119
-
120
- elif spoof_type == "mitm_injection":
121
- # Replace generation with fabricated value
122
- fake_mw = spoof.get("fake_mw", 100.0)
123
- spoofed[target]["generation_mw"] = fake_mw
124
-
125
  return spoofed
126
 
127
- def generate_packet_logs(
128
- self,
129
- all_node_ids: List[str],
130
- tick: int,
131
- ) -> List[Dict[str, Any]]:
132
- """
133
- Generate simulated SCADA packet logs.
134
 
135
- Nodes about to be spoofed show latency spikes 1-2 ticks before.
136
- """
137
- self._tick = tick
138
- logs = []
 
 
 
 
 
 
139
 
140
- # Determine which nodes will be spoofed (for pre-attack latency spike)
141
- spoofed_targets = set()
142
  for spoof in self._spoofs:
143
- if spoof.get("active") and spoof.get("target_node"):
144
- spoofed_targets.add(spoof["target_node"])
 
 
 
 
145
 
 
 
 
 
 
146
  for i, node_id in enumerate(all_node_ids):
147
- # Determine latency
148
- if node_id in spoofed_targets and node_id not in self._quarantined:
149
- # Under attack: elevated latency
150
- latency = float(np.clip(
151
- self._rng.normal(self.ANOMALY_LATENCY_MS, 20.0),
152
- self.ANOMALY_THRESHOLD_MS + 1,
153
- 500.0,
154
- ))
155
  else:
156
- # Normal operation
157
- latency = float(np.clip(
158
- self._rng.normal(self.NORMAL_LATENCY_MS, 2.0),
159
- 1.0,
160
- 30.0,
161
- ))
162
-
163
- # Track consecutive high-latency packets
164
  if latency > self.ANOMALY_THRESHOLD_MS:
165
- self._consecutive_high_latency[node_id] = (
166
- self._consecutive_high_latency.get(node_id, 0) + 1
167
- )
168
  else:
169
  self._consecutive_high_latency[node_id] = 0
170
-
171
  anomaly_flag = self._consecutive_high_latency.get(node_id, 0) >= 2
172
-
173
- # Pick a destination (monitoring center or adjacent node)
174
- dest_idx = (i + 1) % len(all_node_ids)
175
- dest_node = all_node_ids[dest_idx]
176
-
177
- log_entry = {
178
- "timestamp": float(tick * 300 + i), # 300s per tick
179
  "source_node": node_id,
180
- "dest_node": dest_node,
181
  "latency_ms": round(latency, 1),
182
  "anomaly_flag": anomaly_flag,
183
- }
184
- logs.append(log_entry)
185
-
186
  self._packet_history.extend(logs)
187
- # Keep last 200 entries
188
  if len(self._packet_history) > 200:
189
  self._packet_history = self._packet_history[-200:]
190
-
191
  return logs
192
 
 
 
 
 
193
  def quarantine_node(self, node_id: str) -> None:
194
- """Mark a node as quarantined — its spoofed readings will be replaced."""
195
  self._quarantined.add(node_id)
196
 
197
- def get_active_spoofs(self) -> List[str]:
198
- """Get list of node IDs currently being actively spoofed."""
199
- return [
200
- s["target_node"]
201
- for s in self._spoofs
202
- if s.get("active") and s.get("target_node") not in self._quarantined
203
- ]
204
 
205
  def get_quarantined(self) -> List[str]:
206
- """Get list of quarantined node IDs."""
207
- return list(self._quarantined)
208
 
209
  def get_recent_packet_logs(self, count: int = 20) -> List[Dict[str, Any]]:
210
- """Get the most recent packet log entries."""
211
  return self._packet_history[-count:]
212
 
213
  def is_resonance_active(self) -> bool:
214
- """Check if a resonance attack is currently active."""
215
- for spoof in self._spoofs:
216
- if spoof.get("type") == "resonance_oscillation" and spoof.get("active"):
217
- if spoof.get("target_node") not in self._quarantined:
218
- return True
219
- return False
220
-
221
- def get_resonance_effect(self, tick: int) -> float:
222
- """
223
- Get the current frequency deviation caused by resonance attack.
224
-
225
- Returns 0.0 if no resonance attack is active or it has been mitigated.
226
- """
227
- for spoof in self._spoofs:
228
- if spoof.get("type") != "resonance_oscillation" or not spoof.get("active"):
229
- continue
230
- if spoof.get("target_node") in self._quarantined:
231
- continue
232
- # Resonance grows over time — modeled as increasing amplitude
233
- base_amplitude = 0.1
234
- growth_factor = min(tick / 5.0, 2.0) # Doubles over 5 ticks
235
- return base_amplitude * growth_factor * float(
236
- np.sin(2 * np.pi * spoof.get("oscillation_hz", 0.5) * tick)
237
- )
238
- return 0.0
 
1
  """
2
+ NexusGrid — SCADA Cyber Layer (Layer 2).
3
+
4
+ Manipulates what operators *see* (telemetry) and emits SCADA packet logs.
5
+ Physical consequences of attacks are applied by the environment; this module
6
+ only decides which readings are falsified and what the network traffic
7
+ looks like. All randomness uses ``numpy.random.Generator(PCG64(seed))``.
8
+
9
+ Attack vectors
10
+ --------------
11
+ * ``phantom_injection`` - false-data injection: the target plant is losing
12
+ output for real, but its SCADA readings keep reporting the missing MW.
13
+ * ``mitm_injection`` - a substation reports a fixed fabricated value.
14
+ * ``resonance_oscillation`` - a forced oscillation on a generator (physical);
15
+ the intrusion is visible in packet latency.
16
+
17
+ Packet logs show sustained latency on a compromised node from one tick before
18
+ the attack becomes active. Decoy nodes produce short latency bursts that also
19
+ raise anomaly flags, so the logs alone are suggestive, not proof.
20
  """
21
 
22
  from __future__ import annotations
 
27
 
28
 
29
  class SpoofEngine:
30
+ """Falsifies telemetry for compromised nodes and generates packet logs."""
 
 
 
 
 
 
 
 
 
31
 
 
32
  NORMAL_LATENCY_MS = 5.0
33
  ANOMALY_LATENCY_MS = 120.0
34
  ANOMALY_THRESHOLD_MS = 50.0
35
 
36
  def __init__(self, seed: int = 42):
37
+ self._seed = int(seed)
38
+ self._rng = np.random.Generator(np.random.PCG64(self._seed + 104_729))
39
  self._tick = 0
 
 
40
  self._spoofs: List[Dict[str, Any]] = []
 
 
41
  self._quarantined: set = set()
 
 
42
  self._packet_history: List[Dict[str, Any]] = []
 
 
43
  self._consecutive_high_latency: Dict[str, int] = {}
44
 
45
  def reset(self, seed: int = 42) -> None:
46
+ self.__init__(seed)
 
 
 
 
 
 
 
47
 
48
+ # ------------------------------------------------------------------
49
+ # Attack configuration
50
+ # ------------------------------------------------------------------
51
 
52
+ def configure_attack(self, attack_config: Dict[str, Any]) -> None:
 
 
53
  if not attack_config or not attack_config.get("active"):
54
  return
55
+ spoof = dict(attack_config)
56
+ spoof.setdefault("start_tick", 0)
57
+ spoof.setdefault("hidden_mw", 0.0)
58
+ self._spoofs.append(spoof)
59
 
60
  def advance_tick(self) -> None:
 
61
  self._tick += 1
62
 
63
+ def set_hidden_mw(self, node_id: str, hidden_mw: float) -> None:
64
+ """Record how many MW the phantom attack is hiding at ``node_id``."""
65
+ for spoof in self._spoofs:
66
+ if spoof.get("target_node") == node_id and spoof.get("type") == "phantom_injection":
67
+ spoof["hidden_mw"] = float(hidden_mw)
68
+
69
+ def is_active(self, spoof: Dict[str, Any], tick: int) -> bool:
70
+ return (
71
+ bool(spoof.get("active"))
72
+ and tick >= int(spoof.get("start_tick", 0))
73
+ and spoof.get("target_node") not in self._quarantined
74
+ )
75
+
76
+ # ------------------------------------------------------------------
77
+ # Telemetry manipulation
78
+ # ------------------------------------------------------------------
79
+
80
+ def apply_spoofs(self, ground_truth: Dict[str, Dict[str, Any]], tick: int) -> Dict[str, Dict[str, Any]]:
81
+ """Return a copy of ``ground_truth`` with falsified readings for compromised nodes."""
82
  self._tick = tick
83
+ spoofed = {node_id: dict(reading) for node_id, reading in ground_truth.items()}
 
 
 
 
84
  for spoof in self._spoofs:
 
 
 
85
  target = spoof.get("target_node")
86
+ if target not in spoofed or not self.is_active(spoof, tick):
 
 
 
87
  continue
88
+ kind = spoof.get("type")
89
+ if kind == "phantom_injection":
90
+ hidden = float(spoof.get("hidden_mw", spoof.get("phantom_mw", 0.0)))
91
+ spoofed[target]["generation_mw"] = round(ground_truth[target]["generation_mw"] + hidden, 2)
92
+ elif kind == "mitm_injection":
93
+ spoofed[target]["generation_mw"] = float(spoof.get("fake_mw", 100.0))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  return spoofed
95
 
96
+ # ------------------------------------------------------------------
97
+ # Packet logs
98
+ # ------------------------------------------------------------------
 
 
 
 
99
 
100
+ def _compromised_nodes(self, tick: int) -> set:
101
+ nodes = set()
102
+ for spoof in self._spoofs:
103
+ target = spoof.get("target_node")
104
+ if not spoof.get("active") or not target or target in self._quarantined:
105
+ continue
106
+ # Command-and-control traffic starts one tick before the attack lands.
107
+ if tick >= int(spoof.get("start_tick", 0)) - 1:
108
+ nodes.add(target)
109
+ return nodes
110
 
111
+ def _decoy_spike(self, node_id: str, tick: int) -> bool:
112
+ """Decoys produce two-tick latency bursts (enough to raise an anomaly flag)."""
113
  for spoof in self._spoofs:
114
+ decoys = spoof.get("decoy_nodes") or []
115
+ if node_id in decoys:
116
+ start = int(spoof.get("decoy_tick", -1)) + decoys.index(node_id) * 3
117
+ if start <= tick <= start + 1:
118
+ return True
119
+ return False
120
 
121
+ def generate_packet_logs(self, all_node_ids: List[str], tick: int) -> List[Dict[str, Any]]:
122
+ """Generate one SCADA packet record per node for this tick."""
123
+ self._tick = tick
124
+ compromised = self._compromised_nodes(tick)
125
+ logs = []
126
  for i, node_id in enumerate(all_node_ids):
127
+ if node_id in compromised:
128
+ latency = float(np.clip(self._rng.normal(self.ANOMALY_LATENCY_MS, 20.0),
129
+ self.ANOMALY_THRESHOLD_MS + 1, 500.0))
130
+ elif self._decoy_spike(node_id, tick):
131
+ latency = float(np.clip(self._rng.normal(90.0, 15.0), self.ANOMALY_THRESHOLD_MS + 1, 500.0))
 
 
 
132
  else:
133
+ latency = float(np.clip(self._rng.normal(self.NORMAL_LATENCY_MS, 2.0), 1.0, 30.0))
 
 
 
 
 
 
 
134
  if latency > self.ANOMALY_THRESHOLD_MS:
135
+ self._consecutive_high_latency[node_id] = self._consecutive_high_latency.get(node_id, 0) + 1
 
 
136
  else:
137
  self._consecutive_high_latency[node_id] = 0
 
138
  anomaly_flag = self._consecutive_high_latency.get(node_id, 0) >= 2
139
+ logs.append({
140
+ "timestamp": float(tick * 300 + i),
 
 
 
 
 
141
  "source_node": node_id,
142
+ "dest_node": all_node_ids[(i + 1) % len(all_node_ids)],
143
  "latency_ms": round(latency, 1),
144
  "anomaly_flag": anomaly_flag,
145
+ })
 
 
146
  self._packet_history.extend(logs)
 
147
  if len(self._packet_history) > 200:
148
  self._packet_history = self._packet_history[-200:]
 
149
  return logs
150
 
151
+ # ------------------------------------------------------------------
152
+ # Quarantine and queries
153
+ # ------------------------------------------------------------------
154
+
155
  def quarantine_node(self, node_id: str) -> None:
 
156
  self._quarantined.add(node_id)
157
 
158
+ def get_active_spoofs(self, tick: Optional[int] = None) -> List[str]:
159
+ """Node IDs whose telemetry is currently falsified (hidden from agents)."""
160
+ t = self._tick if tick is None else tick
161
+ return [s["target_node"] for s in self._spoofs if self.is_active(s, t)]
162
+
163
+ def get_attack_targets(self) -> List[str]:
164
+ return [s["target_node"] for s in self._spoofs if s.get("target_node")]
165
 
166
  def get_quarantined(self) -> List[str]:
167
+ return sorted(self._quarantined)
 
168
 
169
  def get_recent_packet_logs(self, count: int = 20) -> List[Dict[str, Any]]:
 
170
  return self._packet_history[-count:]
171
 
172
  def is_resonance_active(self) -> bool:
173
+ return any(s.get("type") == "resonance_oscillation" and s.get("active") for s in self._spoofs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test_dash.py DELETED
@@ -1,12 +0,0 @@
1
- import traceback
2
- from server.dashboard import on_reset, on_step, on_auto_run, create_power_flow_sankey, create_topology_graph
3
-
4
- try:
5
- r = on_reset(0, 42)
6
- print("reset", len(r))
7
- r2 = on_step("dispatch_generation", "NODE_01", "LINE_01", 100, "CLOSED", -0.5, 5, '["NODE_14"]')
8
- print("step", len(r2))
9
- r3 = on_auto_run(0, 42, 3)
10
- print("auto", len(r3))
11
- except Exception:
12
- traceback.print_exc()
 
 
 
 
 
 
 
 
 
 
 
 
 
test_dashboard_full.py DELETED
@@ -1,120 +0,0 @@
1
- """Regression test for server/dashboard.py."""
2
- from __future__ import annotations
3
-
4
- import sys
5
- import traceback
6
-
7
- import plotly.graph_objects as go
8
-
9
- EXPECTED = 11
10
- ACTIONS = [
11
- ("dispatch_generation", "dispatch_generation", "NODE_01", "LINE_01", 100, "CLOSED", -0.5, 5, '["NODE_14"]'),
12
- ("toggle_circuit_breaker", "toggle_circuit_breaker", "NODE_01", "LINE_01", 0, "OPEN", 0, 0, "[]"),
13
- ("run_state_estimation", "run_state_estimation", "NODE_01", "LINE_01", 0, "CLOSED", 0, 0, '["NODE_01","NODE_02"]'),
14
- ("quarantine_scada_node", "quarantine_scada_node", "NODE_01", "LINE_01", 0, "CLOSED", 0, 0, "[]"),
15
- ("inject_counter_signal", "inject_counter_signal", "NODE_01", "LINE_01", 0, "CLOSED", -0.3, 3, "[]"),
16
- ("advance_tick", "advance_tick", "NODE_01", "LINE_01", 0, "CLOSED", 0, 0, "[]"),
17
- ]
18
-
19
-
20
- FIG_IDX = (0, 1, 3, 4, 5)
21
- STR_IDX = (2, 6, 7, 8, 9, 10)
22
-
23
-
24
- def check(name: str, out, failures: list[str]) -> None:
25
- if len(out) != EXPECTED:
26
- failures.append(f"{name}: got {len(out)} outputs, need {EXPECTED}")
27
- return
28
- for i in FIG_IDX:
29
- if not isinstance(out[i], go.Figure):
30
- failures.append(f"{name}: out[{i}] is {type(out[i]).__name__}, not Figure")
31
- for i in STR_IDX:
32
- if not isinstance(out[i], str):
33
- failures.append(f"{name}: out[{i}] is {type(out[i]).__name__}, not str")
34
-
35
-
36
- def main() -> int:
37
- failures: list[str] = []
38
- from server.dashboard import (
39
- PLOTLY_AVAILABLE,
40
- TASK_META,
41
- create_dashboard,
42
- create_topology_graph,
43
- create_frequency_gauge,
44
- create_power_flow_sankey,
45
- create_task_radar,
46
- create_reward_breakdown,
47
- on_reset,
48
- on_step,
49
- on_auto_run,
50
- dashboard_state,
51
- _refresh,
52
- )
53
-
54
- if not PLOTLY_AVAILABLE:
55
- failures.append("plotly not installed")
56
-
57
- try:
58
- create_dashboard()
59
- print("create_dashboard: OK")
60
- except Exception as exc:
61
- failures.append(f"create_dashboard: {exc}")
62
- traceback.print_exc()
63
-
64
- for tid, meta in enumerate(TASK_META):
65
- name = meta["name"]
66
- try:
67
- out = on_reset(tid, 42)
68
- check(f"reset T{tid}", out, failures)
69
- obs = dashboard_state.current_obs
70
- if not obs.get("topology_graph", {}).get("nodes"):
71
- failures.append(f"T{tid}: no topology nodes")
72
- create_topology_graph(obs)
73
- create_frequency_gauge(dashboard_state.frequency_hz, dashboard_state.freq_history)
74
- pf = create_power_flow_sankey(obs)
75
- if not pf.data:
76
- failures.append(f"T{tid}: power panel has no traces")
77
- create_task_radar(dashboard_state.task_scores)
78
- create_reward_breakdown(dashboard_state.reward_history)
79
- got = pf.data[0].type
80
- want = "bar" if tid == 5 else "sankey"
81
- if got != want:
82
- failures.append(f"T{tid}: expected {want}, got {got}")
83
- print(f" T{tid} {name}: OK ({got})")
84
- except Exception as exc:
85
- failures.append(f"T{tid} {name}: {exc}")
86
- traceback.print_exc()
87
-
88
- on_reset(0, 42)
89
- for row in ACTIONS:
90
- label, args = row[0], row[1:]
91
- try:
92
- out = on_step(*args)
93
- check(f"step {label}", out, failures)
94
- print(f" step {label}: OK")
95
- except Exception as exc:
96
- failures.append(f"step {label}: {exc}")
97
-
98
- for tid in range(len(TASK_META)):
99
- try:
100
- out = on_auto_run(tid, 42, 5)
101
- check(f"auto T{tid}", out, failures)
102
- print(f" auto T{tid}: OK")
103
- except Exception as exc:
104
- failures.append(f"auto T{tid}: {exc}")
105
-
106
- on_reset(3, 7)
107
- check("_refresh", _refresh(), failures)
108
-
109
- if failures:
110
- print(f"\nFAILED ({len(failures)}):")
111
- for item in failures:
112
- print(f" - {item}")
113
- return 1
114
-
115
- print("\nALL CHECKS PASSED — dashboard.py is healthy.")
116
- return 0
117
-
118
-
119
- if __name__ == "__main__":
120
- sys.exit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/conftest.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared fixtures for the NexusGrid test-suite."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+
8
+ import pytest
9
+
10
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
11
+ if ROOT not in sys.path:
12
+ sys.path.insert(0, ROOT)
13
+
14
+ from models import ActionType, GridAction # noqa: E402
15
+ from server.grid_engine import GridEngine # noqa: E402
16
+ from server.nexusgrid_environment import NexusgridEnvironment # noqa: E402
17
+ from server.scenarios import build_base_topology # noqa: E402
18
+
19
+
20
+ @pytest.fixture
21
+ def env() -> NexusgridEnvironment:
22
+ return NexusgridEnvironment()
23
+
24
+
25
+ @pytest.fixture
26
+ def engine() -> GridEngine:
27
+ eng = GridEngine(seed=7)
28
+ build_base_topology(eng, load_factor=0.85, solar_irradiance=0.5)
29
+ return eng
30
+
31
+
32
+ def noop() -> GridAction:
33
+ return GridAction(action_type=ActionType.ADVANCE_TICK)
34
+
35
+
36
+ def run_policy(env: NexusgridEnvironment, policy, task_id: int, seed: int) -> float:
37
+ obs = env.reset(seed=seed, task_id=task_id)
38
+ if hasattr(policy, "reset"):
39
+ policy.reset(seed)
40
+ while not obs.done:
41
+ obs = env.step(policy.act(obs))
42
+ return env.get_score()
tests/test_api.py CHANGED
@@ -1,293 +1,56 @@
1
- """
2
- Test API — proves step()/reset()/state() return correctly typed models.
3
- """
4
 
5
- import sys
6
- import os
7
- sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
8
 
9
- from fastapi.testclient import TestClient
10
 
11
- from models import GridAction, GridObservation, ActionType
12
- from server.nexusgrid_environment import NexusgridEnvironment
13
- from server.app import app
14
 
 
15
 
16
- class TestEnvironmentAPI:
17
- """Test the OpenEnv API interface."""
18
 
19
- def _make_env(self) -> NexusgridEnvironment:
20
- return NexusgridEnvironment()
21
 
22
- def test_reset_returns_observation(self):
23
- """reset() should return a GridObservation."""
24
- env = self._make_env()
25
- obs = env.reset(seed=42, task_id=0)
26
 
27
- assert isinstance(obs, GridObservation)
28
- assert obs.tick == 0
29
- assert obs.task_id == 0
30
- assert obs.done is False
31
- assert 58.0 <= obs.grid_frequency_hz <= 62.0
32
 
33
- def test_reset_topology_present(self):
34
- """reset() observation should contain topology with nodes and edges."""
35
- env = self._make_env()
36
- obs = env.reset(seed=42, task_id=0)
 
 
37
 
38
- topo = obs.topology_graph
39
- assert "nodes" in topo
40
- assert "edges" in topo
41
- assert len(topo["nodes"]) == 20 # 20-node grid
42
- assert len(topo["edges"]) == 40 # 40 edges
43
 
44
- def test_step_returns_observation(self):
45
- """step() should return a GridObservation with reward and done."""
46
- env = self._make_env()
47
- env.reset(seed=42, task_id=0)
 
 
 
 
 
 
48
 
49
- action = GridAction(
50
- action_type=ActionType.DISPATCH_GENERATION,
51
- node_id="NODE_01",
52
- mw=100.0,
53
- )
54
- obs = env.step(action)
55
-
56
- assert isinstance(obs, GridObservation)
57
- assert obs.tick == 1
58
- assert obs.grid_frequency_hz > 0
59
- assert "reward_breakdown" in obs.metadata
60
- assert "rubric_breakdown" in obs.metadata
61
-
62
- def test_step_advance_tick(self):
63
- """advance_tick should increment the tick counter."""
64
- env = self._make_env()
65
- env.reset(seed=42, task_id=1)
66
-
67
- action = GridAction(action_type=ActionType.ADVANCE_TICK)
68
- obs = env.step(action)
69
-
70
- assert obs.tick == 1
71
-
72
- def test_state_returns_state(self):
73
- """state property should return an OpenEnv State."""
74
- env = self._make_env()
75
- env.reset(seed=42, task_id=0)
76
-
77
- state = env.state
78
- assert state.episode_id is not None
79
- assert state.step_count == 0
80
-
81
- def test_health_endpoint_returns_200(self):
82
- """The standalone health endpoint should respond immediately."""
83
- client = TestClient(app)
84
- response = client.get("/health")
85
-
86
- assert response.status_code == 200
87
- assert response.json()["status"] == "healthy"
88
-
89
- def test_web_dashboard_route_available(self):
90
- """The mounted dashboard route should remain available for HF Spaces."""
91
- client = TestClient(app)
92
- response = client.get("/web", follow_redirects=True)
93
-
94
- assert response.status_code == 200
95
-
96
- def test_websocket_reset_step_state_flow(self):
97
- """The persistent OpenEnv WebSocket API should support reset, step, and state."""
98
- client = TestClient(app)
99
-
100
- with client.websocket_connect("/ws") as ws:
101
- ws.send_json({"type": "reset", "data": {"seed": 42, "task_id": 0}})
102
- reset_message = ws.receive_json()
103
- assert reset_message["type"] == "observation"
104
- assert reset_message["data"]["observation"]["tick"] == 0
105
-
106
- ws.send_json(
107
- {
108
- "type": "step",
109
- "data": {
110
- "action_type": "dispatch_generation",
111
- "node_id": "NODE_01",
112
- "mw": 100,
113
- },
114
- }
115
- )
116
- step_message = ws.receive_json()
117
- assert step_message["type"] == "observation"
118
- assert step_message["data"]["observation"]["tick"] == 1
119
-
120
- ws.send_json({"type": "state"})
121
- state_message = ws.receive_json()
122
- assert state_message["type"] == "state"
123
- assert state_message["data"]["step_count"] == 1
124
-
125
- def test_done_when_frequency_below_59(self):
126
- """Episode should terminate when frequency drops below 59.0Hz."""
127
- env = self._make_env()
128
- env.reset(seed=42, task_id=5) # Black start — frequency starts at 59.0
129
-
130
- # In black start, frequency can drop. Let's force it by doing nothing.
131
- # The initial frequency is 59.0 for black start
132
- action = GridAction(action_type=ActionType.ADVANCE_TICK)
133
 
 
 
 
 
 
134
  done = False
135
- for _ in range(5):
136
- obs = env.step(action)
137
- if obs.done:
138
- done = True
139
- break
140
-
141
- # Black start starts at 59.0 which is already at termination boundary
142
- # The env should detect this
143
- assert done or obs.grid_frequency_hz >= 59.0
144
-
145
- def test_smoke_test_scores_1(self):
146
- """Task 0 with valid dispatch should score 1.0."""
147
- env = self._make_env()
148
- env.reset(seed=42, task_id=0)
149
-
150
- action = GridAction(
151
- action_type=ActionType.DISPATCH_GENERATION,
152
- node_id="NODE_01",
153
- mw=100.0,
154
- )
155
- env.step(action)
156
-
157
- score = env.get_score()
158
- assert score == 1.0, f"Smoke test should score 1.0, got {score}"
159
-
160
- def test_dispatch_updates_frequency_without_advance_tick(self):
161
- """Control actions should update the observable grid frequency immediately."""
162
- env = self._make_env()
163
- obs = env.reset(seed=42, task_id=1)
164
- initial_frequency = obs.grid_frequency_hz
165
-
166
- obs = env.step(
167
- GridAction(
168
- action_type=ActionType.DISPATCH_GENERATION,
169
- node_id="NODE_04",
170
- mw=200.0,
171
- )
172
- )
173
-
174
- assert obs.grid_frequency_hz != initial_frequency
175
-
176
- def test_cascade_overload_reset_exposes_overloaded_lines(self):
177
- """Task 2 should surface the reroute overload in the initial observation."""
178
- env = self._make_env()
179
- obs = env.reset(seed=42, task_id=2)
180
-
181
- overloaded = [
182
- edge["id"]
183
- for edge in obs.topology_graph["edges"]
184
- if edge["status"] == "LIVE" and edge["current_load_mw"] >= 0.95 * edge["capacity_mw"]
185
- ]
186
-
187
- assert "LINE_29" in overloaded
188
-
189
- def test_cascade_overload_persists_without_immediate_action(self):
190
- """Task 2 should remain overloaded after a no-op tick until the agent isolates it."""
191
- env = self._make_env()
192
- env.reset(seed=42, task_id=2)
193
-
194
- obs = env.step(GridAction(action_type=ActionType.ADVANCE_TICK))
195
- overloaded = [
196
- edge["id"]
197
- for edge in obs.topology_graph["edges"]
198
- if edge["status"] == "LIVE" and edge["current_load_mw"] >= 0.95 * edge["capacity_mw"]
199
- ]
200
-
201
- assert "LINE_29" in overloaded
202
-
203
- def test_black_start_can_reenergize_critical_loads(self):
204
- """Closing breakers from the hydro island should energize downstream critical loads."""
205
- env = self._make_env()
206
- env.reset(seed=42, task_id=5)
207
-
208
- actions = [
209
- GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id="NODE_01", mw=600.0),
210
- GridAction(action_type=ActionType.TOGGLE_CIRCUIT_BREAKER, edge_id="LINE_02", status="CLOSED"),
211
- GridAction(action_type=ActionType.TOGGLE_CIRCUIT_BREAKER, edge_id="LINE_28", status="CLOSED"),
212
- GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id="NODE_17", mw=400.0),
213
- GridAction(action_type=ActionType.TOGGLE_CIRCUIT_BREAKER, edge_id="LINE_22", status="CLOSED"),
214
- ]
215
-
216
- obs = None
217
- for action in actions:
218
- obs = env.step(action)
219
-
220
- assert obs is not None
221
- assert env._engine.nodes["NODE_03"]["energized"] is True
222
- assert env._engine.nodes["NODE_18"]["energized"] is True
223
- assert env._engine.nodes["NODE_18"]["consumption_mw"] > 0.0
224
- assert env.get_score() > 0.0
225
-
226
- def test_full_restoration_tick_records_first_recovery(self):
227
- """Task 2 should keep the first tick that crosses the restoration threshold."""
228
- env = self._make_env()
229
- env.reset(seed=42, task_id=2)
230
- env.step(GridAction(action_type=ActionType.TOGGLE_CIRCUIT_BREAKER, edge_id="LINE_29", status="OPEN"))
231
- assert env._get_full_restoration_tick() is None
232
-
233
- env.step(GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id="NODE_09", mw=100.0))
234
- assert env._get_full_restoration_tick() is None
235
-
236
- env.step(GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id="NODE_13", mw=100.0))
237
- assert env._get_full_restoration_tick() == 3
238
-
239
- def test_reset_idempotent(self):
240
- """Calling reset(42) multiple times should produce identical observations."""
241
- env = self._make_env()
242
-
243
- obs1 = env.reset(seed=42, task_id=0)
244
- obs2 = env.reset(seed=42, task_id=0)
245
-
246
- assert obs1.grid_frequency_hz == obs2.grid_frequency_hz
247
- assert obs1.tick == obs2.tick
248
- assert obs1.task_id == obs2.task_id
249
-
250
- def test_done_observation_includes_episode_summary(self):
251
- """Final observations should expose a compact episode summary for training logs."""
252
- env = self._make_env()
253
- env.reset(seed=42, task_id=0)
254
-
255
- obs = env.step(
256
- GridAction(
257
- action_type=ActionType.DISPATCH_GENERATION,
258
- node_id="NODE_01",
259
- mw=100.0,
260
- )
261
- )
262
- if not obs.done:
263
- obs = env.step(GridAction(action_type=ActionType.ADVANCE_TICK))
264
- if not obs.done:
265
- obs = env.step(GridAction(action_type=ActionType.ADVANCE_TICK))
266
-
267
- assert obs.done is True
268
- assert "episode_summary" in obs.metadata
269
-
270
- def test_all_action_types_accepted(self):
271
- """All action types should be accepted without crashing."""
272
- env = self._make_env()
273
- env.reset(seed=42, task_id=1)
274
-
275
- actions = [
276
- GridAction(action_type=ActionType.ADVANCE_TICK),
277
- GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id="NODE_01", mw=50),
278
- GridAction(action_type=ActionType.TOGGLE_CIRCUIT_BREAKER, edge_id="LINE_01", status="OPEN"),
279
- GridAction(action_type=ActionType.RUN_STATE_ESTIMATION, subgraph=["NODE_01", "NODE_02"]),
280
- GridAction(action_type=ActionType.QUARANTINE_SCADA_NODE, node_id="NODE_01"),
281
- ]
282
-
283
- for action in actions:
284
- obs = env.step(action)
285
- assert isinstance(obs, GridObservation)
286
-
287
- def test_weather_present(self):
288
- """Observation should include weather data."""
289
- env = self._make_env()
290
- obs = env.reset(seed=42, task_id=0)
291
-
292
- assert len(obs.weather_forecast_matrix) > 0
293
- assert obs.weather_summary != ""
 
1
+ """HTTP and WebSocket API served by server.app."""
 
 
2
 
3
+ from __future__ import annotations
 
 
4
 
5
+ import pytest
6
 
7
+ fastapi = pytest.importorskip("fastapi")
8
+ from fastapi.testclient import TestClient # noqa: E402
 
9
 
10
+ from server.app import app # noqa: E402
11
 
12
+ client = TestClient(app)
 
13
 
 
 
14
 
15
+ def test_health_and_metadata():
16
+ assert client.get("/health").status_code == 200
17
+ meta = client.get("/metadata").json()
18
+ assert meta["name"] == "NexusGrid-CyberPhysEnv" and meta["version"] == "3.0.0"
19
 
 
 
 
 
 
20
 
21
+ def test_tasks_endpoint_lists_rubrics():
22
+ data = client.get("/tasks").json()
23
+ assert data["eval_seed_start"] == 10_000
24
+ assert [t["id"] for t in data["tasks"]] == list(range(6))
25
+ for task in data["tasks"]:
26
+ assert abs(sum(r["weight"] for r in task["rubrics"]) - 1.0) < 1e-9
27
 
 
 
 
 
 
28
 
29
+ def test_http_reset_and_step_are_stateless_but_valid():
30
+ reset = client.post("/reset", json={"seed": 10_000, "task_id": 1})
31
+ assert reset.status_code == 200
32
+ body = reset.json()
33
+ assert body["observation"]["task_id"] == 1
34
+ assert "metadata" not in body["observation"]
35
+ # Plain HTTP creates a fresh environment per request; multi-step episodes use the WebSocket.
36
+ step = client.post("/step", json={"action": {"action_type": "advance_tick"}})
37
+ assert step.status_code == 200
38
+ assert "reset" in step.json()["observation"]["last_action_error"]
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ def test_websocket_session_runs_an_episode():
42
+ with client.websocket_connect("/ws") as ws:
43
+ ws.send_json({"type": "reset", "data": {"seed": 10_000, "task_id": 0}})
44
+ first = ws.receive_json()
45
+ assert first["data"]["observation"]["tick"] == 0
46
  done = False
47
+ steps = 0
48
+ while not done and steps < 5:
49
+ action = {"action_type": "dispatch_generation", "node_id": "NODE_01", "mw": 40} if steps == 0 \
50
+ else {"action_type": "advance_tick"}
51
+ ws.send_json({"type": "step", "data": action})
52
+ msg = ws.receive_json()
53
+ done = msg["data"]["done"]
54
+ steps += 1
55
+ assert done
56
+ assert msg["data"]["observation"]["score"] == pytest.approx(1.0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_dashboard.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression checks for the Gradio dashboard (skipped when gradio/plotly are missing)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+
7
+ import pytest
8
+
9
+ pytest.importorskip("gradio")
10
+ go = pytest.importorskip("plotly.graph_objects")
11
+
12
+ from server import dashboard as dash # noqa: E402
13
+
14
+ FIG_IDX = (0, 1, 3, 4, 5)
15
+ STR_IDX = (2, 6, 7, 8, 9, 10)
16
+ ACTIONS = [
17
+ ("dispatch_generation", "NODE_01", "LINE_01", 100, "CLOSED", -0.5, 5, '["NODE_14"]'),
18
+ ("shed_load", "NODE_07", "LINE_01", 50, "CLOSED", 0, 0, "[]"),
19
+ ("toggle_circuit_breaker", "NODE_01", "LINE_01", 0, "OPEN", 0, 0, "[]"),
20
+ ("run_state_estimation", "NODE_01", "LINE_01", 0, "CLOSED", 0, 0, '["NODE_01","NODE_02"]'),
21
+ ("quarantine_scada_node", "NODE_01", "LINE_01", 0, "CLOSED", 0, 0, "[]"),
22
+ ("inject_counter_signal", "NODE_04", "LINE_01", 0, "CLOSED", -0.3, 3, "[]"),
23
+ ("advance_tick", "NODE_01", "LINE_01", 0, "CLOSED", 0, 0, "[]"),
24
+ ]
25
+
26
+
27
+ def _check(out):
28
+ assert len(out) == 11
29
+ for i in FIG_IDX:
30
+ assert isinstance(out[i], go.Figure), i
31
+ for i in STR_IDX:
32
+ assert isinstance(out[i], str), i
33
+
34
+
35
+ def test_dashboard_builds():
36
+ assert dash.create_dashboard() is not None
37
+
38
+
39
+ @pytest.mark.parametrize("task_id", range(6))
40
+ def test_reset_renders_every_panel(task_id):
41
+ state = dash.DashboardState()
42
+ out = dash.on_reset(task_id, 10_000, state)
43
+ _check(out)
44
+ assert state.current_obs["topology_graph"]["nodes"]
45
+ panel = out[3].data[0].type
46
+ assert panel == ("bar" if task_id == 5 else "sankey")
47
+
48
+
49
+ def test_manual_steps_render():
50
+ state = dash.DashboardState()
51
+ dash.on_reset(3, 10_000, state)
52
+ for row in ACTIONS:
53
+ _check(dash.on_step(*row, state))
54
+ assert len(state.action_log) == len(ACTIONS)
55
+
56
+
57
+ @pytest.mark.parametrize("task_id", range(6))
58
+ def test_expert_autorun_scores(task_id):
59
+ state = dash.DashboardState()
60
+ _check(dash.on_auto_run(task_id, 10_000, 50, state, "expert"))
61
+ assert state.done
62
+ assert state.task_scores[task_id] >= 0.8
63
+
64
+
65
+ def test_sessions_are_isolated():
66
+ template = dash.DashboardState()
67
+ a, b = copy.deepcopy(template), copy.deepcopy(template)
68
+ dash.on_reset(1, 10_000, a)
69
+ dash.on_step("advance_tick", "", "", 0, "CLOSED", 0, 0, "[]", a)
70
+ assert a.tick == 1 and b.tick == 0 and b.env is None
tests/test_engine.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Physics of the grid engine: DC power flow, frequency, protection and actions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+
7
+ from server.grid_engine import GENERATOR_TYPES, GridEngine
8
+ from server.scenarios import build_base_topology
9
+
10
+
11
+ def _net_injection(engine: GridEngine, nid: str) -> float:
12
+ n = engine.nodes[nid]
13
+ return n["generation_mw"] if n["node_type"] in GENERATOR_TYPES else -n["consumption_mw"]
14
+
15
+
16
+ def _line_balance(engine: GridEngine, nid: str) -> float:
17
+ total = 0.0
18
+ for e in engine.edges.values():
19
+ if e["status"] != "LIVE":
20
+ continue
21
+ if e["source"] == nid:
22
+ total += e["flow_mw"]
23
+ elif e["target"] == nid:
24
+ total -= e["flow_mw"]
25
+ return total
26
+
27
+
28
+ class TestPowerFlow:
29
+ def test_base_case_is_balanced_and_nominal(self, engine):
30
+ assert len(engine.get_stable_islands()) == 1
31
+ assert engine.frequency_hz == pytest.approx(60.0, abs=1e-6)
32
+ assert engine.get_total_generation() == pytest.approx(engine.get_total_load(), abs=1e-6)
33
+
34
+ def test_kirchhoff_current_law_holds_at_every_bus(self, engine):
35
+ for nid in engine.nodes:
36
+ assert _line_balance(engine, nid) == pytest.approx(_net_injection(engine, nid), abs=1e-6)
37
+
38
+ def test_kirchhoff_voltage_law_holds_on_every_line(self, engine):
39
+ import math
40
+ for e in engine.edges.values():
41
+ if e["status"] != "LIVE":
42
+ continue
43
+ d_theta = math.radians(engine.nodes[e["source"]]["phase_angle_deg"]
44
+ - engine.nodes[e["target"]]["phase_angle_deg"])
45
+ assert e["flow_mw"] == pytest.approx(d_theta / e["reactance"] * engine.BASE_MVA, abs=1e-6)
46
+
47
+ def test_opening_a_line_redistributes_flow(self, engine):
48
+ before = dict((eid, e["flow_mw"]) for eid, e in engine.edges.items())
49
+ engine.toggle_circuit_breaker("LINE_28", "OPEN")
50
+ assert engine.edges["LINE_28"]["flow_mw"] == 0.0
51
+ changed = [eid for eid, e in engine.edges.items() if abs(e["flow_mw"] - before[eid]) > 1.0]
52
+ assert len(changed) > 3
53
+ for nid in engine.nodes:
54
+ assert _line_balance(engine, nid) == pytest.approx(_net_injection(engine, nid), abs=1e-6)
55
+
56
+ def test_reactance_scales_inversely_with_rating(self, engine):
57
+ assert engine.edges["LINE_28"]["reactance"] < engine.edges["LINE_27"]["reactance"]
58
+
59
+
60
+ class TestFrequency:
61
+ def test_generation_deficit_lowers_frequency_through_stiffness(self, engine):
62
+ engine.nodes["NODE_17"]["setpoint_mw"] -= 150.0
63
+ engine.compute_power_flow()
64
+ target = engine._island_target_hz[0]
65
+ stiffness = engine._island_stiffness(engine.get_stable_islands()[0])
66
+ assert target == pytest.approx(60.0 - 150.0 / stiffness, abs=1e-6)
67
+ f = engine.compute_frequency(smooth=True)
68
+ assert 60.0 > f > target # inertia closes only part of the gap per tick
69
+
70
+ def test_governors_keep_load_served_during_small_deficit(self, engine):
71
+ load_before = engine.get_total_load()
72
+ engine.dispatch_generation("NODE_17", -150.0)
73
+ assert engine.get_total_load() == pytest.approx(load_before, abs=1e-6)
74
+
75
+ def test_ufls_sheds_non_critical_load_below_threshold(self, engine):
76
+ for nid in ("NODE_01", "NODE_13", "NODE_17", "NODE_09"):
77
+ engine.nodes[nid]["setpoint_mw"] = 0.0
78
+ events = []
79
+ for _ in range(4):
80
+ events += engine.advance_tick()
81
+ assert any(e["type"] == "ufls" for e in events)
82
+ shed_nodes = {nid for e in events if e["type"] == "ufls" for nid in e["nodes"]}
83
+ assert shed_nodes and all(not engine.nodes[nid]["critical"] for nid in shed_nodes)
84
+
85
+ def test_weak_island_collapses_outside_hard_limits(self, engine):
86
+ # Isolate NODE_19 (load) with the NODE_20 battery: far too little stiffness for the load.
87
+ engine.nodes["NODE_20"]["setpoint_mw"] = 10.0 # running, so the island stays energised when split
88
+ for eid in ("LINE_23", "LINE_25", "LINE_36", "LINE_24", "LINE_26", "LINE_40"):
89
+ engine.toggle_circuit_breaker(eid, "OPEN")
90
+ assert len(engine.get_stable_islands()) == 2
91
+ events = engine.advance_tick()
92
+ assert any(e["type"] == "island_collapse" and "NODE_19" in e["nodes"] for e in events)
93
+ assert not engine.nodes["NODE_19"]["energized"]
94
+
95
+
96
+ class TestProtection:
97
+ def test_instant_trip_at_140_percent(self, engine):
98
+ line = engine.edges["LINE_02"]
99
+ line["capacity_mw"] = max(1.0, abs(line["flow_mw"]) / 1.5)
100
+ events = engine.advance_tick()
101
+ assert any(e["type"] == "protection_trip" and e["edge"] == "LINE_02" for e in events)
102
+ assert line["status"] == "TRIPPED"
103
+
104
+ def test_sustained_overload_trips_after_three_ticks(self, engine):
105
+ line = engine.edges["LINE_02"]
106
+ line["capacity_mw"] = abs(line["flow_mw"]) / 1.1
107
+ assert engine.advance_tick() == [] or line["status"] == "LIVE"
108
+ engine.advance_tick()
109
+ assert line["status"] == "LIVE"
110
+ events = engine.advance_tick()
111
+ assert any(e["type"] == "protection_trip" and e["edge"] == "LINE_02" for e in events)
112
+
113
+ def test_out_of_service_line_cannot_be_closed(self, engine):
114
+ engine.set_out_of_service("LINE_28", "storm damage")
115
+ result = engine.toggle_circuit_breaker("LINE_28", "CLOSED")
116
+ assert result["success"] is False
117
+ assert "out of service" in result["error"]
118
+ assert engine.edges["LINE_28"]["status"] == "TRIPPED"
119
+
120
+
121
+ class TestActions:
122
+ def test_dispatch_is_ramp_limited(self, engine):
123
+ old = engine.nodes["NODE_17"]["setpoint_mw"]
124
+ result = engine.dispatch_generation("NODE_17", 1000.0)
125
+ assert result["success"] and result["ramp_limited"]
126
+ assert engine.nodes["NODE_17"]["setpoint_mw"] == pytest.approx(old + 150.0)
127
+
128
+ def test_dispatch_rejects_loads_and_unknown_nodes(self, engine):
129
+ assert engine.dispatch_generation("NODE_03", 50)["success"] is False
130
+ assert engine.dispatch_generation("NODE_99", 50)["success"] is False
131
+
132
+ def test_shed_and_restore_load(self, engine):
133
+ served = engine.nodes["NODE_07"]["consumption_mw"]
134
+ engine.shed_load("NODE_07", 100.0)
135
+ assert engine.nodes["NODE_07"]["consumption_mw"] == pytest.approx(served - 100.0, abs=1e-6)
136
+ engine.shed_load("NODE_07", -100.0)
137
+ assert engine.nodes["NODE_07"]["consumption_mw"] == pytest.approx(served, abs=1e-6)
138
+
139
+ def test_critical_load_cannot_be_shed(self, engine):
140
+ assert engine.shed_load("NODE_03", 50.0)["success"] is False
141
+
142
+ def test_restore_also_returns_ufls_shed_load(self, engine):
143
+ node = engine.nodes["NODE_12"]
144
+ node["ufls_fraction"] = 0.2
145
+ engine.compute_power_flow()
146
+ engine.shed_load("NODE_12", -node["demand_mw"])
147
+ assert node["ufls_fraction"] == 0.0
148
+
149
+ def test_state_estimation_finds_falsified_reading(self, engine):
150
+ truth = engine.get_ground_truth_telemetry()
151
+ clean = engine.run_state_estimation(["NODE_09", "NODE_10", "NODE_11"], truth)
152
+ assert clean["consistent"] is True
153
+ truth["NODE_09"]["generation_mw"] += 200.0
154
+ dirty = engine.run_state_estimation(["NODE_09", "NODE_10", "NODE_11"], truth)
155
+ assert dirty["consistent"] is False and dirty["violation_node"] == "NODE_09"
156
+ assert dirty["residual_mw"] == pytest.approx(200.0, abs=3.0)
157
+
158
+ def test_out_of_phase_merge_is_refused(self):
159
+ eng = GridEngine(seed=3)
160
+ build_base_topology(eng, load_factor=0.8, solar_irradiance=0.5)
161
+ # Split NORTH from the rest and unbalance it so the islands drift apart.
162
+ for eid in ("LINE_28", "LINE_29", "LINE_30", "LINE_38"):
163
+ eng.toggle_circuit_breaker(eid, "OPEN")
164
+ assert len(eng.get_stable_islands()) == 2
165
+ eng.nodes["NODE_02"]["setpoint_mw"] += 300.0
166
+ eng.compute_power_flow()
167
+ eng.compute_frequency(smooth=False)
168
+ result = eng.toggle_circuit_breaker("LINE_28", "CLOSED")
169
+ assert result["success"] is False and result["out_of_phase"] is True
170
+ assert eng.edges["LINE_28"]["status"] == "TRIPPED"
171
+
172
+ def test_battery_depletes_and_stops(self, engine):
173
+ battery = engine.nodes["NODE_20"]
174
+ battery["energy_mwh"] = 10.0
175
+ engine.dispatch_generation("NODE_20", 400.0)
176
+ events = []
177
+ for _ in range(3):
178
+ events += engine.advance_tick()
179
+ assert any(e["type"] == "battery_depleted" for e in events)
180
+ assert battery["setpoint_mw"] == 0.0
181
+
182
+ def test_identical_seeds_give_identical_telemetry(self):
183
+ a, b = GridEngine(seed=11), GridEngine(seed=11)
184
+ for eng in (a, b):
185
+ build_base_topology(eng, load_factor=0.8, solar_irradiance=0.4)
186
+ assert a.get_ground_truth_telemetry() == b.get_ground_truth_telemetry()
tests/test_environment.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenEnv environment behaviour: API, hidden information, rewards and determinism."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ import pytest
8
+
9
+ from models import ActionType, GridAction, GridObservation
10
+ from policies import ExpertPolicy
11
+ from server.nexusgrid_environment import NexusgridEnvironment
12
+ from server.scenarios import MAX_TICKS
13
+ from tests.conftest import noop
14
+
15
+
16
+ class TestApi:
17
+ def test_reset_returns_typed_observation(self, env):
18
+ obs = env.reset(seed=1, task_id=1)
19
+ assert isinstance(obs, GridObservation)
20
+ assert obs.tick == 0 and obs.task_id == 1 and not obs.done
21
+ assert len(obs.topology_graph["nodes"]) == 20 and len(obs.topology_graph["edges"]) == 40
22
+ assert obs.max_ticks == MAX_TICKS[1]
23
+ assert obs.task_brief and obs.forecast["system_demand_mw"]
24
+ assert obs.islands and obs.telemetry_stream
25
+
26
+ def test_step_advances_one_tick(self, env):
27
+ env.reset(seed=1, task_id=1)
28
+ obs = env.step(GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id="NODE_01", mw=50))
29
+ assert obs.tick == 1
30
+ assert set(obs.reward_breakdown) == {"progress", "frequency_band", "overload", "events", "invalid_action", "total"}
31
+ assert obs.reward == pytest.approx(obs.reward_breakdown["total"])
32
+
33
+ def test_episode_ends_at_horizon_and_rejects_more_steps(self, env):
34
+ obs = env.reset(seed=1, task_id=0)
35
+ while not obs.done:
36
+ obs = env.step(noop())
37
+ assert obs.tick == MAX_TICKS[0]
38
+ again = env.step(noop())
39
+ assert again.done and again.last_action_error == "Episode already finished"
40
+
41
+ def test_step_before_reset_is_handled(self):
42
+ obs = NexusgridEnvironment().step(noop())
43
+ assert obs.done and "reset" in obs.last_action_error
44
+
45
+ def test_invalid_task_rejected(self, env):
46
+ with pytest.raises(ValueError):
47
+ env.reset(seed=1, task_id=9)
48
+
49
+ def test_state_exposes_score_and_progress(self, env):
50
+ env.reset(seed=3, task_id=2)
51
+ env.step(noop())
52
+ state = env.state
53
+ assert state.step_count == 1 and state.task_id == 2
54
+ assert 0.0 <= state.score <= 1.0
55
+
56
+ def test_invalid_actions_are_reported_and_penalised(self, env):
57
+ env.reset(seed=1, task_id=1)
58
+ obs = env.step(GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id="NODE_03", mw=50))
59
+ assert obs.last_action_error and "not a generator" in obs.last_action_error
60
+ assert obs.reward_breakdown["invalid_action"] < 0
61
+ obs = env.step(GridAction(action_type=ActionType.RUN_STATE_ESTIMATION,
62
+ subgraph=[f"NODE_{i:02d}" for i in range(1, 9)]))
63
+ assert "limited to 6" in obs.last_action_error
64
+
65
+
66
+ class TestHiddenInformation:
67
+ @pytest.mark.parametrize("task_id", [3, 4])
68
+ def test_attack_target_never_serialised(self, env, task_id):
69
+ obs = env.reset(seed=4, task_id=task_id)
70
+ for _ in range(3):
71
+ obs = env.step(noop())
72
+ payload = obs.model_dump(exclude={"metadata"})
73
+ text = json.dumps(payload)
74
+ assert "active_spoofs" not in text and "attack_target" not in text
75
+ assert "hidden_loss" not in text and "target_node" not in text
76
+ assert "attack" in env.debug_state()
77
+
78
+ def test_phantom_attack_falsifies_telemetry_but_not_physics(self, env):
79
+ env.reset(seed=4, task_id=3)
80
+ target = env.debug_state()["attack"]["target_node"]
81
+ for _ in range(6):
82
+ obs = env.step(noop())
83
+ reported = obs.telemetry_stream[-1]
84
+ reading = next(r for r in reported if r["node_id"] == target)
85
+ true_gen = env.engine.nodes[target]["generation_mw"]
86
+ assert env.debug_state()["hidden_loss_mw"] > 100
87
+ assert reading["generation_mw"] - true_gen > 100
88
+
89
+ def test_quarantine_requires_evidence(self, env):
90
+ env.reset(seed=4, task_id=3)
91
+ target = env.debug_state()["attack"]["target_node"]
92
+ obs = env.step(GridAction(action_type=ActionType.QUARANTINE_SCADA_NODE, node_id=target))
93
+ assert "refused" in obs.last_action_error.lower()
94
+ assert env.debug_state()["refused_quarantines"] == 1
95
+
96
+
97
+ class TestRewards:
98
+ @pytest.mark.parametrize("task_id", sorted(MAX_TICKS))
99
+ def test_progress_rewards_telescope_to_final_score(self, env, task_id):
100
+ policy = ExpertPolicy()
101
+ obs = env.reset(seed=10_001, task_id=task_id)
102
+ progress = 0.0
103
+ while not obs.done:
104
+ obs = env.step(policy.act(obs))
105
+ progress += obs.reward_breakdown["progress"]
106
+ assert progress == pytest.approx(env.get_score(), abs=1e-4)
107
+ assert obs.score == pytest.approx(env.get_score(), abs=1e-4)
108
+
109
+ def test_relay_trip_is_penalised(self, env):
110
+ env.reset(seed=2, task_id=2)
111
+ penalties = []
112
+ obs = None
113
+ for _ in range(5):
114
+ obs = env.step(noop())
115
+ penalties.append(obs.reward_breakdown["events"])
116
+ assert min(penalties) < 0
117
+
118
+
119
+ class TestDeterminism:
120
+ @pytest.mark.parametrize("task_id", sorted(MAX_TICKS))
121
+ def test_same_seed_and_actions_give_same_trajectory(self, task_id):
122
+ def trajectory():
123
+ env = NexusgridEnvironment()
124
+ policy = ExpertPolicy()
125
+ obs = env.reset(seed=77, task_id=task_id)
126
+ out = [obs.grid_frequency_hz]
127
+ while not obs.done:
128
+ obs = env.step(policy.act(obs))
129
+ out.append((obs.grid_frequency_hz, obs.reward, json.dumps(obs.network_packet_logs[-3:])))
130
+ return out, env.get_score()
131
+
132
+ assert trajectory() == trajectory()
tests/test_graders.py CHANGED
@@ -1,190 +1,66 @@
1
- """
2
- Test Graders — proves each grader returns expected scores
3
- for known inputs (correct action, wrong order, timeout, zero action).
4
- """
5
-
6
- import sys
7
- import os
8
- sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
9
-
10
- from server.graders import (
11
- grade_smoke_test,
12
- grade_duck_curve,
13
- grade_cascade_overload,
14
- grade_phantom_injection,
15
- grade_stuxnet_resonance,
16
- grade_black_start,
17
- grade_task,
18
- )
19
- from server.reward import RewardCalculator
20
-
21
-
22
- class TestSmokeTestGrader:
23
- def test_valid_dispatch_scores_1(self):
24
- actions = [{"action_type": "dispatch_generation", "mw": 100}]
25
- assert grade_smoke_test(actions, {}) == 1.0
26
-
27
- def test_no_action_scores_0(self):
28
- assert grade_smoke_test([], {}) == 0.0
29
-
30
- def test_wrong_action_scores_0(self):
31
- actions = [{"action_type": "advance_tick"}]
32
- assert grade_smoke_test(actions, {}) == 0.0
33
-
34
- def test_negative_mw_scores_0(self):
35
- actions = [{"action_type": "dispatch_generation", "mw": -100}]
36
- assert grade_smoke_test(actions, {}) == 0.0
37
-
38
-
39
- class TestDuckCurveGrader:
40
- def test_perfect_frequency_scores_high(self):
41
- state = {"frequency_history": [60.0, 59.8, 59.7, 59.8, 60.0]}
42
- actions = [
43
- {"action_type": "dispatch_generation", "tick": 1},
44
- {"action_type": "dispatch_generation", "tick": 2},
45
- ]
46
- score = grade_duck_curve(actions, state)
47
- assert score >= 0.5 # Frequency stayed above 59.5
48
-
49
- def test_frequency_crash_scores_0(self):
50
- state = {"frequency_history": [60.0, 59.5, 59.0, 58.5]}
51
- actions = []
52
- assert grade_duck_curve(actions, state) == 0.0
53
-
54
-
55
- class TestCascadeOverloadGrader:
56
- def test_full_correct_response(self):
57
- actions = [
58
- {"action_type": "toggle_circuit_breaker", "status": "OPEN"},
59
- ]
60
- state = {"critical_nodes_shed": 0, "full_restoration_tick": 5}
61
- score = grade_cascade_overload(actions, state)
62
- assert score >= 0.8
63
-
64
- def test_no_action_scores_0(self):
65
- state = {"critical_nodes_shed": 2}
66
- assert grade_cascade_overload([], state) == 0.0
67
-
68
-
69
- class TestPhantomInjectionGrader:
70
- def test_correct_order_full_score(self):
71
- actions = [
72
- {"action_type": "advance_tick", "tick": 0},
73
- {"action_type": "run_state_estimation", "tick": 1, "result": {"consistent": False}},
74
- {"action_type": "quarantine_scada_node", "tick": 2, "node_id": "NODE_14"},
75
- {"action_type": "dispatch_generation", "tick": 3, "node_id": "NODE_09", "mw": 100},
76
- ]
77
- score = grade_phantom_injection(actions, {"spoof_target": "NODE_14"})
78
- assert score == 1.0
79
-
80
- def test_quarantine_without_estimation_scores_0(self):
81
- actions = [
82
- {"action_type": "quarantine_scada_node", "tick": 1},
83
- ]
84
- score = grade_phantom_injection(actions, {})
85
- assert score == 0.0
86
-
87
- def test_estimation_only_scores_partial(self):
88
- actions = [
89
- {"action_type": "run_state_estimation", "tick": 1, "result": {"consistent": False}},
90
- ]
91
- score = grade_phantom_injection(actions, {})
92
- assert score == 0.2
93
-
94
-
95
- class TestStuxnetResonanceGrader:
96
- def test_correct_injection_requires_ramp_down_and_reroute_for_full_score(self):
97
- actions = [
98
- {"action_type": "inject_counter_signal", "tick": 0, "hz_offset": -0.5},
99
- {"action_type": "dispatch_generation", "tick": 1, "node_id": "NODE_17", "mw": -200},
100
- {"action_type": "dispatch_generation", "tick": 2, "node_id": "NODE_09", "mw": 300},
101
- ]
102
- score = grade_stuxnet_resonance(actions, {})
103
- assert score == 1.0
104
-
105
- def test_correct_injection_without_ramp_down_stays_partial(self):
106
- actions = [
107
- {"action_type": "inject_counter_signal", "tick": 0, "hz_offset": -0.5},
108
- ]
109
- score = grade_stuxnet_resonance(actions, {})
110
- assert score == 0.4
111
-
112
- def test_wrong_offset_partial(self):
113
- actions = [
114
- {"action_type": "inject_counter_signal", "hz_offset": -0.3},
115
- ]
116
- score = grade_stuxnet_resonance(actions, {})
117
- assert score == 0.2
118
-
119
- def test_cutting_turbine_scores_0(self):
120
- actions = [
121
- {"action_type": "toggle_circuit_breaker", "edge_id": "LINE_22", "status": "OPEN"},
122
- ]
123
- assert grade_stuxnet_resonance(actions, {}) == 0.0
124
-
125
-
126
- class TestBlackStartGrader:
127
- def test_hydro_dispatch_checkpoint_a(self):
128
- actions = [
129
- {"action_type": "dispatch_generation", "node_id": "NODE_01", "mw": 500},
130
- ]
131
- state = {"hydro_stable_ticks": 0, "energized_node_count": 1}
132
- score = grade_black_start(actions, state)
133
- assert score >= 0.02 # Checkpoint A × load_fraction
134
-
135
- def test_no_action_scores_0(self):
136
- assert grade_black_start([], {}) == 0.0
137
-
138
- def test_critical_restore_requires_checkpoint_c(self):
139
- actions = [
140
- {"action_type": "dispatch_generation", "node_id": "NODE_01", "mw": 500},
141
- ]
142
- state = {
143
- "hydro_stable_ticks": 3,
144
- "energized_node_count": 10,
145
- "max_island_count": 1,
146
- "successful_mergers": 0,
147
- "premature_mergers": 0,
148
- "critical_nodes_restored": True,
149
- "load_restored_fraction": 0.84,
150
- "transformer_failures": 0,
151
- }
152
- assert grade_black_start(actions, state) == 0.42
153
-
154
-
155
- class TestRewardCalculator:
156
- def test_fault_isolation_reward_only_paid_once_per_episode(self):
157
- reward_calc = RewardCalculator()
158
- base_kwargs = {
159
- "action_type": "toggle_circuit_breaker",
160
- "action_params": {},
161
- "frequency_hz": 60.0,
162
- "overloaded_edges": [],
163
- "critical_nodes_shed": 0,
164
- "is_proactive": False,
165
- "spoof_detected": False,
166
- "has_read_logs_before_estimation": False,
167
- }
168
-
169
- first = reward_calc.compute_tick_reward(fault_isolated=True, **base_kwargs)
170
- second = reward_calc.compute_tick_reward(fault_isolated=True, **base_kwargs)
171
-
172
- assert first["fault_isolation"] == 0.20
173
- assert second["fault_isolation"] == 0.0
174
-
175
-
176
- class TestGradeTaskRouter:
177
- def test_routes_correctly(self):
178
- """grade_task should route to the correct grader."""
179
- # Task 0 with valid action
180
- actions = [{"action_type": "dispatch_generation", "mw": 100}]
181
- assert grade_task(0, actions, {}) == 1.0
182
-
183
- # Invalid task ID
184
- assert grade_task(99, [], {}) == 0.0
185
-
186
- def test_score_clamped(self):
187
- """Scores should always be in [0, 1]."""
188
- for task_id in range(6):
189
- score = grade_task(task_id, [], {})
190
- assert 0.0 <= score <= 1.0
 
1
+ """Graders separate competent operation from doing nothing or acting randomly."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import statistics
6
+
7
+ import pytest
8
+
9
+ from policies import ExpertPolicy, NoopPolicy, RandomPolicy
10
+ from server.graders import grade_task, served_factor
11
+ from server.rubric import TASK_RUBRICS, get_task_rubric_specs
12
+ from server.scenarios import EVAL_SEED_START, MAX_TICKS
13
+ from tests.conftest import run_policy
14
+
15
+ SEEDS = [EVAL_SEED_START + i for i in range(6)]
16
+
17
+
18
+ @pytest.mark.parametrize("task_id", sorted(TASK_RUBRICS))
19
+ def test_rubric_weights_sum_to_one(task_id):
20
+ assert sum(r["weight"] for r in get_task_rubric_specs(task_id)) == pytest.approx(1.0)
21
+
22
+
23
+ @pytest.mark.parametrize("task_id", sorted(MAX_TICKS))
24
+ def test_trivial_policies_score_low_and_expert_high(env, task_id):
25
+ noop = statistics.mean(run_policy(env, NoopPolicy(), task_id, s) for s in SEEDS)
26
+ rand = statistics.mean(run_policy(env, RandomPolicy(s), task_id, s) for s in SEEDS)
27
+ expert = statistics.mean(run_policy(env, ExpertPolicy(), task_id, s) for s in SEEDS)
28
+ assert noop <= 0.25, f"do-nothing scores {noop:.2f} on task {task_id}"
29
+ assert rand <= 0.35, f"random scores {rand:.2f} on task {task_id}"
30
+ assert expert >= 0.85, f"expert scores {expert:.2f} on task {task_id}"
31
+
32
+
33
+ def test_scores_are_clipped(env):
34
+ assert grade_task(99, [], {}) == 0.0
35
+ state = {"done": True, "frequency_history": [60.0] * 4, "max_ticks": 3}
36
+ assert 0.0 <= grade_task(0, [], state) <= 1.0
37
+
38
+
39
+ def test_served_factor_penalises_load_shedding():
40
+ assert served_factor({"served_history": [1.0, 1.0, 1.0]}) == 1.0
41
+ assert served_factor({"served_history": [1.0, 0.89, 0.89]}) == pytest.approx(0.5, abs=1e-6)
42
+
43
+
44
+ def test_duck_curve_collapse_scores_zero():
45
+ state = {"done": True, "frequency_history": [60.0, 59.5, 58.9], "max_ticks": 15}
46
+ assert grade_task(1, [], state) == 0.0
47
+
48
+
49
+ def test_quarantine_without_evidence_costs_points():
50
+ actions = [
51
+ {"action_type": "run_state_estimation", "tick": 2,
52
+ "result": {"consistent": False, "violation_node": "NODE_09"}},
53
+ {"action_type": "quarantine_scada_node", "tick": 3, "node_id": "NODE_09", "result": {"success": True}},
54
+ ]
55
+ state = {"done": True, "attack_target": "NODE_09", "attack_start_tick": 2,
56
+ "frequency_history": [60.0] * 19, "served_history": [1.0] * 19, "max_ticks": 18}
57
+ clean = grade_task(3, actions, {**state, "refused_quarantines": 0})
58
+ sloppy = grade_task(3, actions, {**state, "refused_quarantines": 2})
59
+ assert clean == pytest.approx(1.0)
60
+ assert sloppy == pytest.approx(clean - 0.2)
61
+
62
+
63
+ def test_disconnecting_the_oscillating_unit_scores_zero():
64
+ state = {"done": True, "target_disconnected": True, "best_counter_signal": "correct",
65
+ "attack_neutralized": True, "frequency_history": [60.0] * 13}
66
+ assert grade_task(4, [], state) == 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_inference.py DELETED
@@ -1,181 +0,0 @@
1
- """
2
- Test inference helpers.
3
-
4
- These tests focus on the local Ollama/DeepSeek path where the model often
5
- wraps JSON in reasoning text or code fences.
6
- """
7
-
8
- import sys
9
- import os
10
-
11
- sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
12
-
13
- from inference import (
14
- _is_ollama_backend,
15
- _should_replace_with_fallback,
16
- clamp_submission_score,
17
- get_fallback_action,
18
- parse_action,
19
- )
20
-
21
-
22
- class TestParseAction:
23
- def test_parses_reasoning_plus_fenced_json(self):
24
- response = """
25
- <think>
26
- I should bring up the hydro dam first.
27
- </think>
28
- ```json
29
- {"action_type":"dispatch_generation","node_id":"NODE_01","mw":600}
30
- ```
31
- """
32
- action = parse_action(response)
33
- assert action == {
34
- "action_type": "dispatch_generation",
35
- "node_id": "NODE_01",
36
- "mw": 600,
37
- }
38
-
39
- def test_parses_single_quoted_payload(self):
40
- response = "{'action_type': 'toggle_circuit_breaker', 'edge_id': 'LINE_28', 'status': 'closed'}"
41
- action = parse_action(response)
42
- assert action == {
43
- "action_type": "toggle_circuit_breaker",
44
- "edge_id": "LINE_28",
45
- "status": "CLOSED",
46
- }
47
-
48
- def test_parses_action_wrapped_in_list(self):
49
- response = """
50
- Here is the action:
51
- [
52
- {"action_type":"advance_tick"}
53
- ]
54
- """
55
- action = parse_action(response)
56
- assert action == {"action_type": "advance_tick"}
57
-
58
-
59
- class TestClampSubmissionScore:
60
- def test_clamp_keeps_scores_inside_open_interval(self):
61
- assert 0.0 < clamp_submission_score(0.0) < 1.0
62
- assert 0.0 < clamp_submission_score(1.0) < 1.0
63
- assert clamp_submission_score(0.42) == 0.42
64
-
65
-
66
- class TestOllamaDetection:
67
- def test_local_ollama_url_detected_automatically(self):
68
- assert _is_ollama_backend("http://localhost:11434/v1") is True
69
-
70
- def test_remote_openai_compatible_url_requires_override(self):
71
- assert _is_ollama_backend("https://example.com/v1") is False
72
- assert _is_ollama_backend("https://example.com/v1", compat_override="1") is True
73
-
74
-
75
- class TestFallbackPolicy:
76
- def test_cascade_overload_replaces_non_isolation_action_while_line_is_overloaded(self):
77
- obs = {
78
- "topology_graph": {
79
- "nodes": [
80
- {"id": "NODE_01", "energized": True, "capacity_mw": 1500},
81
- ],
82
- "edges": [
83
- {
84
- "id": "LINE_29",
85
- "status": "LIVE",
86
- "current_load_mw": 950.0,
87
- "capacity_mw": 1000.0,
88
- },
89
- ],
90
- },
91
- "telemetry_stream": [[
92
- {"node_id": "NODE_01", "generation_mw": 600.0},
93
- ]],
94
- }
95
-
96
- action = {"action_type": "dispatch_generation", "node_id": "NODE_01", "mw": 100}
97
- assert _should_replace_with_fallback(task_id=2, tick=0, action_dict=action, obs_dict=obs)
98
-
99
- def test_task3_replaces_early_dispatch_before_logs(self):
100
- obs = {
101
- "network_packet_logs": [],
102
- "metadata": {"active_spoofs": ["NODE_14"]},
103
- }
104
- action = {"action_type": "dispatch_generation", "node_id": "NODE_09", "mw": 100}
105
- assert _should_replace_with_fallback(task_id=3, tick=0, action_dict=action, obs_dict=obs)
106
-
107
- def test_task3_replaces_early_quarantine_before_estimation(self):
108
- obs = {
109
- "network_packet_logs": [{"source_node": "NODE_14", "anomaly_flag": True}],
110
- "metadata": {"active_spoofs": ["NODE_14"]},
111
- }
112
- action = {"action_type": "quarantine_scada_node", "node_id": "NODE_14"}
113
- assert _should_replace_with_fallback(task_id=3, tick=1, action_dict=action, obs_dict=obs)
114
-
115
- def test_task3_replaces_dispatch_before_quarantine(self):
116
- obs = {
117
- "network_packet_logs": [{"source_node": "NODE_14", "anomaly_flag": True}],
118
- "last_state_estimation": {"consistent": False, "violation_node": "NODE_14"},
119
- "metadata": {"active_spoofs": ["NODE_14"]},
120
- }
121
- action = {"action_type": "dispatch_generation", "node_id": "NODE_09", "mw": 100}
122
- assert _should_replace_with_fallback(task_id=3, tick=2, action_dict=action, obs_dict=obs)
123
-
124
- def test_task3_allows_reroute_after_quarantine(self):
125
- obs = {
126
- "topology_graph": {
127
- "nodes": [
128
- {"id": "NODE_09", "energized": True, "capacity_mw": 900},
129
- ],
130
- "edges": [],
131
- },
132
- "telemetry_stream": [[
133
- {"node_id": "NODE_09", "generation_mw": 400.0},
134
- ]],
135
- "network_packet_logs": [{"source_node": "NODE_14", "anomaly_flag": True}],
136
- "last_state_estimation": {"consistent": False, "violation_node": "NODE_14"},
137
- "metadata": {"active_spoofs": []},
138
- }
139
- action = {"action_type": "dispatch_generation", "node_id": "NODE_09", "mw": 100}
140
- assert _should_replace_with_fallback(task_id=3, tick=3, action_dict=action, obs_dict=obs) is False
141
-
142
- def test_task4_replaces_non_injection_opening_move(self):
143
- obs = {
144
- "topology_graph": {"nodes": [], "edges": []},
145
- "telemetry_stream": [],
146
- }
147
- action = {"action_type": "run_state_estimation", "subgraph": ["NODE_17", "NODE_20"]}
148
- assert _should_replace_with_fallback(task_id=4, tick=0, action_dict=action, obs_dict=obs)
149
-
150
- def test_task3_replaces_redundant_estimation_after_quarantine(self):
151
- obs = {
152
- "network_packet_logs": [{"source_node": "NODE_14", "anomaly_flag": True}],
153
- "last_state_estimation": {"consistent": False, "violation_node": "NODE_14"},
154
- "metadata": {"active_spoofs": []},
155
- }
156
- action = {"action_type": "run_state_estimation", "subgraph": ["NODE_14", "NODE_15"]}
157
- assert _should_replace_with_fallback(task_id=3, tick=4, action_dict=action, obs_dict=obs)
158
-
159
- def test_black_start_fallback_only_makes_minimal_progress(self):
160
- obs = {
161
- "topology_graph": {
162
- "nodes": [
163
- {"id": "NODE_01", "energized": True},
164
- {"id": "NODE_03", "energized": False},
165
- ],
166
- "edges": [
167
- {"id": "LINE_02", "status": "TRIPPED"},
168
- ],
169
- },
170
- "telemetry_stream": [[
171
- {"node_id": "NODE_01", "generation_mw": 600.0},
172
- {"node_id": "NODE_03", "generation_mw": 0.0},
173
- ]],
174
- }
175
-
176
- action = get_fallback_action(task_id=5, tick=3, obs_dict=obs)
177
- assert action == {
178
- "action_type": "toggle_circuit_breaker",
179
- "edge_id": "LINE_02",
180
- "status": "CLOSED",
181
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_kirchhoff.py DELETED
@@ -1,119 +0,0 @@
1
- """
2
- Test Kirchhoff Conservation — proves the power flow engine
3
- conserves power at every node on every tick.
4
- """
5
-
6
- import sys
7
- import os
8
- sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
9
-
10
- from server.grid_engine import GridEngine
11
- from server.scenarios import build_base_topology
12
-
13
-
14
- class TestKirchhoff:
15
- """Test that Kirchhoff's laws hold in the grid engine."""
16
-
17
- def test_power_conservation_initial(self):
18
- """After initialization, generation and load should be physically reasonable."""
19
- engine = GridEngine(seed=42)
20
- build_base_topology(engine)
21
-
22
- total_gen = engine.get_total_generation()
23
- total_load = engine.get_total_load()
24
-
25
- # Grid has generation headroom by design — gen >= load
26
- assert total_gen > 0, "Grid should have generation"
27
- assert total_load > 0, "Grid should have load"
28
- # Frequency should reflect the balance
29
- assert 59.0 <= engine.frequency_hz <= 62.0, (
30
- f"Frequency out of range: {engine.frequency_hz}"
31
- )
32
-
33
- def test_frequency_nominal_at_start(self):
34
- """Initial frequency should be near 60Hz."""
35
- engine = GridEngine(seed=42)
36
- build_base_topology(engine)
37
-
38
- assert 59.0 <= engine.frequency_hz <= 61.0, (
39
- f"Initial frequency out of range: {engine.frequency_hz}"
40
- )
41
-
42
- def test_power_conservation_after_ticks(self):
43
- """Generation and load should remain physically reasonable after ticks."""
44
- engine = GridEngine(seed=42)
45
- build_base_topology(engine)
46
-
47
- for _ in range(5):
48
- engine.advance_tick()
49
-
50
- total_gen = engine.get_total_generation()
51
- total_load = engine.get_total_load()
52
-
53
- # After ticks, both gen and load should still be positive
54
- assert total_gen > 0, f"No generation after 5 ticks: {total_gen}"
55
- assert total_load > 0, f"No load after 5 ticks: {total_load}"
56
- # Frequency should remain in valid range
57
- assert 58.0 <= engine.frequency_hz <= 62.0, (
58
- f"Frequency out of range after ticks: {engine.frequency_hz}"
59
- )
60
-
61
- def test_edge_loads_non_negative(self):
62
- """No edge should carry negative load."""
63
- engine = GridEngine(seed=42)
64
- build_base_topology(engine)
65
-
66
- for _ in range(3):
67
- engine.advance_tick()
68
-
69
- for edge_id, edge in engine.edges.items():
70
- assert edge["current_load_mw"] >= 0, (
71
- f"Edge {edge_id} has negative load: {edge['current_load_mw']}"
72
- )
73
-
74
- def test_edge_loads_within_capacity(self):
75
- """Live edges should ideally not exceed capacity significantly."""
76
- engine = GridEngine(seed=42)
77
- build_base_topology(engine)
78
-
79
- for edge_id, edge in engine.edges.items():
80
- if edge["status"] == "LIVE":
81
- # Allow 10% overload for transient states
82
- assert edge["current_load_mw"] <= edge["capacity_mw"] * 1.1, (
83
- f"Edge {edge_id} overloaded: {edge['current_load_mw']} > {edge['capacity_mw']}"
84
- )
85
-
86
- def test_state_estimation_consistent_without_spoofs(self):
87
- """State estimation should report consistent when no spoofs are active."""
88
- engine = GridEngine(seed=42)
89
- build_base_topology(engine)
90
-
91
- ground_truth = engine.get_ground_truth_telemetry()
92
- result = engine.run_state_estimation(
93
- list(engine.nodes.keys())[:5],
94
- ground_truth,
95
- )
96
-
97
- assert result["consistent"] is True, (
98
- f"State estimation inconsistent without spoofs: {result}"
99
- )
100
-
101
- def test_dispatch_changes_generation(self):
102
- """Dispatching generation should change the node's output."""
103
- engine = GridEngine(seed=42)
104
- build_base_topology(engine)
105
-
106
- old_gen = engine.nodes["NODE_01"]["generation_mw"]
107
- result = engine.dispatch_generation("NODE_01", 100)
108
-
109
- assert result["success"] is True
110
- assert engine.nodes["NODE_01"]["generation_mw"] == old_gen + 100
111
-
112
- def test_tripped_line_carries_zero(self):
113
- """Tripping a line should set its load to zero."""
114
- engine = GridEngine(seed=42)
115
- build_base_topology(engine)
116
-
117
- engine.toggle_circuit_breaker("LINE_01", "OPEN")
118
- assert engine.edges["LINE_01"]["status"] == "TRIPPED"
119
- assert engine.edges["LINE_01"]["current_load_mw"] == 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_policies_and_inference.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Baseline policies, the observation-only flow model and the LLM runner helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from types import SimpleNamespace
6
+
7
+ import pytest
8
+
9
+ from inference import LLMPolicy, parse_action, render_observation, to_grid_action
10
+ from models import ActionType, GridAction
11
+ from policies import FlowModel, GridView, RandomPolicy, make_policy
12
+ from server.scenarios import MAX_TICKS
13
+ from tests.conftest import noop
14
+
15
+
16
+ class TestFlowModel:
17
+ def test_reconstructs_engine_flows_from_observation(self, env):
18
+ obs = env.reset(seed=5, task_id=2)
19
+ view = GridView(obs)
20
+ island = view.main_island()
21
+ model = FlowModel(view, island["nodes"])
22
+ predicted = model.predict(deltas={"NODE_17": 0.0}, close=())
23
+ for eid, flow in predicted.items():
24
+ assert flow == pytest.approx(env.engine.edges[eid]["flow_mw"], abs=0.5)
25
+
26
+ def test_predicts_flows_after_redispatch(self, env):
27
+ obs = env.reset(seed=5, task_id=1)
28
+ view = GridView(obs)
29
+ model = FlowModel(view, view.main_island()["nodes"])
30
+ predicted = model.predict(deltas={"NODE_13": 120.0})
31
+ env.engine.dispatch_generation("NODE_13", 120.0)
32
+ for eid, flow in predicted.items():
33
+ assert flow == pytest.approx(env.engine.edges[eid]["flow_mw"], abs=3.0)
34
+
35
+
36
+ @pytest.mark.parametrize("name", ["noop", "random", "expert"])
37
+ @pytest.mark.parametrize("task_id", sorted(MAX_TICKS))
38
+ def test_policies_emit_valid_actions(env, name, task_id):
39
+ policy = make_policy(name, seed=3)
40
+ obs = env.reset(seed=3, task_id=task_id)
41
+ for _ in range(4):
42
+ action = policy.act(obs)
43
+ assert isinstance(action, GridAction)
44
+ obs = env.step(action)
45
+ if obs.done:
46
+ break
47
+
48
+
49
+ def test_random_policy_is_seeded(env):
50
+ obs = env.reset(seed=1, task_id=1)
51
+ a = [RandomPolicy(9).act(obs).model_dump() for _ in range(3)]
52
+ b = [RandomPolicy(9).act(obs).model_dump() for _ in range(3)]
53
+ assert a == b
54
+
55
+
56
+ class TestParseAction:
57
+ def test_reasoning_and_code_fence(self):
58
+ text = '<think>raise hydro</think>\n```json\n{"action_type":"dispatch_generation","node_id":"NODE_01","mw":120}\n```'
59
+ assert parse_action(text) == {"action_type": "dispatch_generation", "node_id": "NODE_01", "mw": 120}
60
+
61
+ def test_aliases_and_single_quotes(self):
62
+ assert parse_action("{'action': 'shed', 'node': 'node_07', 'amount': '80'}") == {
63
+ "action_type": "shed_load", "node_id": "NODE_07", "mw": 80.0}
64
+ assert parse_action("{'action_type': 'toggle_breaker', 'edge': 'line_28', 'status': 'closed'}") == {
65
+ "action_type": "toggle_circuit_breaker", "edge_id": "LINE_28", "status": "CLOSED"}
66
+
67
+ def test_list_wrapper_and_garbage(self):
68
+ assert parse_action('[{"action_type":"advance_tick"}]') == {"action_type": "advance_tick"}
69
+ assert parse_action("I would dispatch something") is None
70
+ assert to_grid_action({"action_type": "dispatch_generation", "node_id": "NODE_01", "mw": 99999}) is None
71
+
72
+
73
+ def test_render_observation_covers_key_signals(env):
74
+ obs = env.reset(seed=4, task_id=4)
75
+ for _ in range(2):
76
+ obs = env.step(noop())
77
+ text = render_observation(obs, ["t0 {\"action_type\":\"advance_tick\"}"])
78
+ for marker in ("TASK 4", "ISLANDS", "GENERATORS", "LOADS", "LIVE CONNECTIONS", "PMU OSCILLATION",
79
+ "YOUR RECENT ACTIONS"):
80
+ assert marker in text
81
+ assert "target_node" not in text
82
+
83
+
84
+ class _FakeClient:
85
+ def __init__(self, replies):
86
+ self.replies = list(replies)
87
+ self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create))
88
+
89
+ def _create(self, **kwargs):
90
+ content = self.replies.pop(0) if self.replies else "nonsense"
91
+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=content))])
92
+
93
+
94
+ def test_llm_policy_pure_mode_counts_invalid_outputs(env):
95
+ policy = LLMPolicy(model="fake", api_base="http://example.invalid/v1",
96
+ client=_FakeClient(['{"action_type":"dispatch_generation","node_id":"NODE_01","mw":50}',
97
+ "no idea"]))
98
+ obs = env.reset(seed=1, task_id=1)
99
+ first = policy.act(obs)
100
+ second = policy.act(env.step(first))
101
+ assert first.action_type == ActionType.DISPATCH_GENERATION
102
+ assert second.action_type == ActionType.ADVANCE_TICK
103
+ assert policy.stats()["invalid_outputs"] == 1 and policy.stats()["fallbacks"] == 0
104
+
105
+
106
+ def test_llm_policy_fallback_is_reported(env):
107
+ policy = LLMPolicy(model="fake", api_base="http://example.invalid/v1", fallback=True,
108
+ client=_FakeClient(["???"]))
109
+ obs = env.reset(seed=1, task_id=1)
110
+ policy.act(obs)
111
+ assert policy.stats()["fallbacks"] == 1
tests/test_reproducibility.py DELETED
@@ -1,117 +0,0 @@
1
- """
2
- Test Reproducibility — runs environment episodes twice with the same seed,
3
- asserts scores are identical (byte-identical).
4
-
5
- Verifies the seed-lock contract: all randomness derives from
6
- numpy.random.Generator(PCG64(episode_seed)).
7
- """
8
-
9
- import sys
10
- import os
11
- sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
12
-
13
- from models import GridAction, ActionType
14
- from server.nexusgrid_environment import NexusgridEnvironment
15
-
16
-
17
- def run_deterministic_episode(task_id: int, seed: int) -> dict:
18
- """
19
- Run a deterministic episode using fixed actions (no LLM).
20
-
21
- Returns dict with score, frequency_history, and final tick.
22
- """
23
- env = NexusgridEnvironment()
24
- obs = env.reset(seed=seed, task_id=task_id)
25
-
26
- # Execute a fixed sequence of actions based on task
27
- if task_id == 0:
28
- actions = [
29
- GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id="NODE_01", mw=100),
30
- ]
31
- elif task_id == 1:
32
- actions = [
33
- GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id="NODE_04", mw=200),
34
- GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id="NODE_08", mw=200),
35
- GridAction(action_type=ActionType.ADVANCE_TICK),
36
- GridAction(action_type=ActionType.ADVANCE_TICK),
37
- ]
38
- else:
39
- actions = [
40
- GridAction(action_type=ActionType.ADVANCE_TICK),
41
- GridAction(action_type=ActionType.ADVANCE_TICK),
42
- ]
43
-
44
- rewards = []
45
- frequencies = []
46
- for action in actions:
47
- obs = env.step(action)
48
- rewards.append(obs.reward)
49
- frequencies.append(obs.grid_frequency_hz)
50
- if obs.done:
51
- break
52
-
53
- score = env.get_score()
54
-
55
- return {
56
- "score": score,
57
- "rewards": rewards,
58
- "frequencies": frequencies,
59
- "tick": obs.tick,
60
- }
61
-
62
-
63
- class TestReproducibility:
64
- """Verify seed-lock contract: same seed → identical results."""
65
-
66
- def test_task0_reproducible(self):
67
- """Task 0 with same seed should produce identical scores."""
68
- result1 = run_deterministic_episode(task_id=0, seed=42)
69
- result2 = run_deterministic_episode(task_id=0, seed=42)
70
-
71
- assert result1["score"] == result2["score"], (
72
- f"Score mismatch: {result1['score']} != {result2['score']}"
73
- )
74
- assert result1["rewards"] == result2["rewards"], "Reward sequence mismatch"
75
- assert result1["frequencies"] == result2["frequencies"], "Frequency sequence mismatch"
76
-
77
- def test_task1_reproducible(self):
78
- """Task 1 with same seed should produce identical scores."""
79
- result1 = run_deterministic_episode(task_id=1, seed=42)
80
- result2 = run_deterministic_episode(task_id=1, seed=42)
81
-
82
- assert result1["score"] == result2["score"]
83
- assert result1["rewards"] == result2["rewards"]
84
-
85
- def test_task1_different_seed_differs(self):
86
- """Task 1 with different seeds should produce different results."""
87
- result1 = run_deterministic_episode(task_id=1, seed=42)
88
- result2 = run_deterministic_episode(task_id=1, seed=99)
89
-
90
- # Frequencies should differ (different weather evolution)
91
- assert result1["frequencies"] != result2["frequencies"], (
92
- "Different seeds should produce different frequency trajectories"
93
- )
94
-
95
- def test_all_tasks_reproducible(self):
96
- """All tasks should be reproducible with the same seed."""
97
- for task_id in range(6):
98
- result1 = run_deterministic_episode(task_id=task_id, seed=42)
99
- result2 = run_deterministic_episode(task_id=task_id, seed=42)
100
-
101
- assert result1["score"] == result2["score"], (
102
- f"Task {task_id} score not reproducible: "
103
- f"{result1['score']} != {result2['score']}"
104
- )
105
-
106
- def test_reset_idempotent(self):
107
- """Calling reset(42) 10 times should produce identical observations."""
108
- env = NexusgridEnvironment()
109
- freq_values = []
110
-
111
- for _ in range(10):
112
- obs = env.reset(seed=42, task_id=0)
113
- freq_values.append(obs.grid_frequency_hz)
114
-
115
- assert len(set(freq_values)) == 1, (
116
- f"reset(42) produced different frequencies: {freq_values}"
117
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_round2.py DELETED
@@ -1,128 +0,0 @@
1
- """Round 2 environment enhancements: curriculum, rubrics, and training logging."""
2
-
3
- import io
4
- import json
5
- import os
6
- import sys
7
-
8
- sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
9
-
10
- from client import NexusgridEnv
11
- from models import ActionType, GridAction
12
- from server.curriculum import CurriculumManager
13
- from server.nexusgrid_environment import NexusgridEnvironment
14
- from server.rubric import evaluate_task_rubrics, get_task_rubric_specs
15
- from server.training_logger import TrainingLogger
16
-
17
-
18
- class TestCurriculumManager:
19
- def test_recommends_task_zero_initially(self):
20
- curriculum = CurriculumManager(unlock_threshold=0.7, window=3)
21
- assert curriculum.get_recommended_task() == 0
22
-
23
- def test_unlocks_next_task_after_threshold(self):
24
- curriculum = CurriculumManager(unlock_threshold=0.7, window=3)
25
- curriculum.record_score(0, 0.8)
26
- curriculum.record_score(0, 0.75)
27
-
28
- assert curriculum.is_unlocked(1) is True
29
- assert curriculum.get_recommended_task() == 1
30
-
31
-
32
- class TestRubrics:
33
- def test_task_three_rubrics_reflect_forensic_sequence(self):
34
- actions = [
35
- {"action_type": "advance_tick", "tick": 0},
36
- {"action_type": "run_state_estimation", "tick": 1, "result": {"consistent": False}},
37
- {"action_type": "quarantine_scada_node", "tick": 2, "node_id": "NODE_14"},
38
- {"action_type": "dispatch_generation", "tick": 3, "node_id": "NODE_09", "mw": 100},
39
- ]
40
- state = {"spoof_target": "NODE_14", "logs_read_before_estimation": True}
41
-
42
- result = evaluate_task_rubrics(3, actions, state)
43
-
44
- assert result["rubrics"]["log_inspection"] == 1.0
45
- assert result["rubrics"]["state_estimation"] == 1.0
46
- assert result["rubrics"]["correct_quarantine"] == 1.0
47
- assert result["rubrics"]["reroute_dispatch"] == 1.0
48
- assert result["weighted_score"] == 1.0
49
-
50
- def test_task_specs_available_for_manifest_sync(self):
51
- specs = get_task_rubric_specs(5)
52
- assert any(spec["name"] == "hydro_bootstrap" for spec in specs)
53
-
54
-
55
- class TestTrainingLogger:
56
- def test_training_logger_writes_jsonl(self):
57
- buffer = io.StringIO()
58
- logger = TrainingLogger(stream=buffer)
59
- record = logger.build_record(
60
- episode=7,
61
- task_id=3,
62
- seed=42,
63
- score=0.6,
64
- rubrics={"state_estimation": 1.0},
65
- actions_taken=["advance_tick", "run_state_estimation"],
66
- frequency_min=59.8,
67
- ticks_used=2,
68
- )
69
- logger.write_episode(record)
70
-
71
- payload = json.loads(buffer.getvalue().strip())
72
- assert payload["episode"] == 7
73
- assert payload["task_id"] == 3
74
- assert payload["rubrics"]["state_estimation"] == 1.0
75
-
76
-
77
- class TestRoundTwoMetadata:
78
- def test_environment_exposes_rubric_breakdown(self):
79
- env = NexusgridEnvironment()
80
- obs = env.reset(seed=42, task_id=3)
81
-
82
- assert "rubric_breakdown" in obs.metadata
83
- assert obs.metadata["rubric_breakdown"]["task_id"] == 3
84
-
85
- def test_emit_training_log_uses_episode_summary(self):
86
- env = NexusgridEnvironment()
87
- env.reset(seed=42, task_id=0)
88
- env.step(GridAction(action_type=ActionType.DISPATCH_GENERATION, node_id="NODE_01", mw=100))
89
-
90
- buffer = io.StringIO()
91
- line = env.emit_training_log(episode=1, logger=TrainingLogger(stream=buffer))
92
- payload = json.loads(line)
93
-
94
- assert payload["episode"] == 1
95
- assert payload["task_id"] == 0
96
- assert "valid_dispatch" in payload["rubrics"]
97
-
98
-
99
- class TestClientMetadataParsing:
100
- def test_client_preserves_metadata(self):
101
- client = NexusgridEnv(base_url="http://localhost:8000")
102
- payload = {
103
- "observation": {
104
- "topology_graph": {},
105
- "telemetry_stream": [],
106
- "weather_forecast_matrix": [],
107
- "network_packet_logs": [],
108
- "grid_frequency_hz": 60.0,
109
- "tick": 1,
110
- "task_id": 2,
111
- "done": False,
112
- "reward": 0.2,
113
- "weather_summary": "",
114
- "metadata": {"rubric_breakdown": {"task_id": 2}},
115
- },
116
- "reward": 0.2,
117
- "done": False,
118
- }
119
-
120
- result = client._parse_result(payload)
121
- assert result.observation.metadata["rubric_breakdown"]["task_id"] == 2
122
-
123
- def test_client_parses_state_with_model_validation(self):
124
- client = NexusgridEnv(base_url="http://localhost:8000")
125
- state = client._parse_state({"episode_id": "ep-1", "step_count": 4, "extra": "ok"})
126
-
127
- assert state.episode_id == "ep-1"
128
- assert state.step_count == 4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_scenarios.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Seeded scenario families, held-out splits and the Task 2 contingency catalog."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+
7
+ from server.scenarios import (
8
+ EVAL_SEED_START,
9
+ MAX_TICKS,
10
+ build_scenario,
11
+ cascade_config_check,
12
+ load_cascade_catalog,
13
+ )
14
+
15
+
16
+ def _fingerprint(scenario):
17
+ engine = scenario["engine"]
18
+ return (
19
+ tuple(sorted((k, round(v, 6) if isinstance(v, float) else str(v)) for k, v in scenario["params"].items()
20
+ if not isinstance(v, (list, dict)))),
21
+ round(engine.get_total_demand(), 4),
22
+ tuple(round(n["setpoint_mw"], 4) for n in engine.nodes.values()),
23
+ )
24
+
25
+
26
+ @pytest.mark.parametrize("task_id", sorted(MAX_TICKS))
27
+ def test_same_seed_reproduces_scenario(task_id):
28
+ assert _fingerprint(build_scenario(task_id, 123)) == _fingerprint(build_scenario(task_id, 123))
29
+
30
+
31
+ @pytest.mark.parametrize("task_id", sorted(MAX_TICKS))
32
+ def test_seeds_produce_different_scenarios(task_id):
33
+ prints = {_fingerprint(build_scenario(task_id, seed)) for seed in range(12)}
34
+ assert len(prints) >= 8
35
+
36
+
37
+ @pytest.mark.parametrize("task_id", sorted(MAX_TICKS))
38
+ def test_split_label(task_id):
39
+ assert build_scenario(task_id, 5)["split"] == "train"
40
+ assert build_scenario(task_id, EVAL_SEED_START + 5)["split"] == "eval"
41
+
42
+
43
+ def test_attack_targets_and_timing_vary():
44
+ targets = {build_scenario(3, s)["attack_config"]["target_node"] for s in range(40)}
45
+ starts = {build_scenario(3, s)["attack_config"]["start_tick"] for s in range(40)}
46
+ modes = {build_scenario(4, s)["attack_config"]["mode_hz"] for s in range(40)}
47
+ assert len(targets) >= 4 and len(starts) >= 2 and len(modes) >= 5
48
+
49
+
50
+ def test_black_start_unit_varies_and_grid_is_dark():
51
+ units = set()
52
+ for s in range(20):
53
+ sc = build_scenario(5, s)
54
+ engine = sc["engine"]
55
+ unit = sc["params"]["black_start_unit"]
56
+ units.add(unit)
57
+ energized = [nid for nid, n in engine.nodes.items() if n["energized"]]
58
+ assert energized == [unit]
59
+ assert all(e["status"] == "TRIPPED" for e in engine.edges.values())
60
+ assert units == {"NODE_01", "NODE_13"}
61
+
62
+
63
+ def test_cascade_catalog_is_split_between_train_and_eval():
64
+ catalog = load_cascade_catalog()
65
+ assert len(catalog) >= 100
66
+ split_at = int(len(catalog) * 0.8)
67
+ train_keys = {(c["trip_line"], tuple(c["outages"]), c["load_factor"]) for c in catalog[:split_at]}
68
+ eval_keys = {(c["trip_line"], tuple(c["outages"]), c["load_factor"]) for c in catalog[split_at:]}
69
+ assert not train_keys & eval_keys
70
+
71
+
72
+ def test_cascade_configs_start_overloaded_but_secure_before_the_trip():
73
+ catalog = load_cascade_catalog()
74
+ for config in catalog[:: max(1, len(catalog) // 12)]:
75
+ info = cascade_config_check(config)
76
+ assert info["valid"], config
77
+ assert 1.06 <= info["max_loading"] <= 1.35
78
+
79
+
80
+ def test_cascade_scenario_locks_out_damaged_lines():
81
+ sc = build_scenario(2, 7)
82
+ engine = sc["engine"]
83
+ locked = [eid for eid, e in engine.edges.items() if e["out_of_service"]]
84
+ assert sc["params"]["trip_line"] in locked
85
+ assert set(sc["params"]["outages"]) <= set(locked)
86
+ assert engine.get_max_loading() > 1.0
87
+
88
+
89
+ def test_duck_curve_forecast_matches_realised_demand():
90
+ sc = build_scenario(1, 9)
91
+ engine, schedule = sc["engine"], sc["schedule"]
92
+ forecast = list(engine.demand_forecast)
93
+ for k, expected in enumerate(forecast[:4], start=1):
94
+ schedule.apply(engine, k)
95
+ assert engine.get_total_demand() == pytest.approx(expected, abs=0.2)
tests/test_spoof_engine.py DELETED
@@ -1,144 +0,0 @@
1
- """
2
- Test Spoof Engine — proves the spoof engine is deterministic given the same seed.
3
- """
4
-
5
- import sys
6
- import os
7
- sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
8
-
9
- from server.spoof_engine import SpoofEngine
10
-
11
-
12
- class TestSpoofEngineDeterminism:
13
- """Verify that the spoof engine produces identical output for the same seed."""
14
-
15
- def test_same_seed_same_packets(self):
16
- """Two engines with the same seed should produce identical packet logs."""
17
- node_ids = [f"NODE_{i:02d}" for i in range(1, 21)]
18
-
19
- engine1 = SpoofEngine(seed=42)
20
- engine2 = SpoofEngine(seed=42)
21
-
22
- logs1 = engine1.generate_packet_logs(node_ids, tick=0)
23
- logs2 = engine2.generate_packet_logs(node_ids, tick=0)
24
-
25
- assert len(logs1) == len(logs2)
26
- for l1, l2 in zip(logs1, logs2):
27
- assert l1["latency_ms"] == l2["latency_ms"], (
28
- f"Latency mismatch: {l1['latency_ms']} != {l2['latency_ms']}"
29
- )
30
- assert l1["anomaly_flag"] == l2["anomaly_flag"]
31
-
32
- def test_different_seed_different_packets(self):
33
- """Two engines with different seeds should produce different packet logs."""
34
- node_ids = [f"NODE_{i:02d}" for i in range(1, 21)]
35
-
36
- engine1 = SpoofEngine(seed=42)
37
- engine2 = SpoofEngine(seed=123)
38
-
39
- logs1 = engine1.generate_packet_logs(node_ids, tick=0)
40
- logs2 = engine2.generate_packet_logs(node_ids, tick=0)
41
-
42
- # At least some latencies should differ
43
- diffs = sum(1 for l1, l2 in zip(logs1, logs2) if l1["latency_ms"] != l2["latency_ms"])
44
- assert diffs > 0, "Different seeds should produce different packet logs"
45
-
46
-
47
- class TestSpoofEngineAttacks:
48
- """Verify spoof engine attack mechanics."""
49
-
50
- def test_phantom_injection_adds_mw(self):
51
- """Phantom injection should add extra MW to reported generation."""
52
- engine = SpoofEngine(seed=42)
53
- engine.configure_attack({
54
- "type": "phantom_injection",
55
- "target_node": "NODE_14",
56
- "phantom_mw": 100.0,
57
- "active": True,
58
- })
59
-
60
- ground_truth = {
61
- "NODE_14": {"generation_mw": 400.0, "voltage_kv": 345.0, "frequency_hz": 60.0},
62
- }
63
-
64
- spoofed = engine.apply_spoofs(ground_truth, tick=0)
65
- assert spoofed["NODE_14"]["generation_mw"] == 500.0 # 400 + 100
66
-
67
- def test_quarantine_stops_spoofing(self):
68
- """After quarantine, node should not be spoofed."""
69
- engine = SpoofEngine(seed=42)
70
- engine.configure_attack({
71
- "type": "phantom_injection",
72
- "target_node": "NODE_14",
73
- "phantom_mw": 100.0,
74
- "active": True,
75
- })
76
-
77
- ground_truth = {
78
- "NODE_14": {"generation_mw": 400.0, "voltage_kv": 345.0, "frequency_hz": 60.0},
79
- }
80
-
81
- # Before quarantine — spoofed
82
- spoofed = engine.apply_spoofs(ground_truth, tick=0)
83
- assert spoofed["NODE_14"]["generation_mw"] == 500.0
84
-
85
- # After quarantine — should return truth
86
- engine.quarantine_node("NODE_14")
87
- spoofed = engine.apply_spoofs(ground_truth, tick=1)
88
- assert spoofed["NODE_14"]["generation_mw"] == 400.0
89
-
90
- def test_active_spoofs_list(self):
91
- """get_active_spoofs should return currently spoofed node IDs."""
92
- engine = SpoofEngine(seed=42)
93
- engine.configure_attack({
94
- "type": "phantom_injection",
95
- "target_node": "NODE_14",
96
- "phantom_mw": 100.0,
97
- "active": True,
98
- })
99
-
100
- assert "NODE_14" in engine.get_active_spoofs()
101
-
102
- engine.quarantine_node("NODE_14")
103
- assert "NODE_14" not in engine.get_active_spoofs()
104
-
105
- def test_anomaly_flag_on_spoofed_nodes(self):
106
- """Spoofed nodes should show anomaly flags in packet logs."""
107
- engine = SpoofEngine(seed=42)
108
- engine.configure_attack({
109
- "type": "phantom_injection",
110
- "target_node": "NODE_14",
111
- "phantom_mw": 100.0,
112
- "active": True,
113
- })
114
-
115
- node_ids = [f"NODE_{i:02d}" for i in range(1, 21)]
116
-
117
- # Generate logs for multiple ticks to build up consecutive high latency
118
- for tick in range(3):
119
- logs = engine.generate_packet_logs(node_ids, tick=tick)
120
-
121
- # NODE_14 should have anomaly_flag set after 2+ ticks
122
- node14_logs = [l for l in logs if l["source_node"] == "NODE_14"]
123
- assert any(l["anomaly_flag"] for l in node14_logs), (
124
- "NODE_14 should show anomaly flag after consecutive high-latency packets"
125
- )
126
-
127
-
128
- class TestSpoofEngineReset:
129
- """Verify reset behavior."""
130
-
131
- def test_reset_clears_state(self):
132
- """Reset should clear all spoofs and quarantines."""
133
- engine = SpoofEngine(seed=42)
134
- engine.configure_attack({
135
- "type": "phantom_injection",
136
- "target_node": "NODE_14",
137
- "phantom_mw": 100.0,
138
- "active": True,
139
- })
140
- engine.quarantine_node("NODE_14")
141
-
142
- engine.reset(seed=99)
143
- assert engine.get_active_spoofs() == []
144
- assert engine.get_quarantined() == []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_training.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Training utilities: the RL action catalogue/features and the GRPO reward."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ import numpy as np
8
+ import pytest
9
+
10
+ from gym_env import CATALOG, FEATURE_SIZE, DiscretizedExpert, featurize
11
+ from policies import GridView
12
+ from server.nexusgrid_environment import NexusgridEnvironment
13
+ from training.grpo_common import INVALID_REWARD, collect_states, score_completion
14
+
15
+
16
+ class TestCatalog:
17
+ def test_catalog_size_and_advance_first(self):
18
+ assert len(CATALOG) == 237
19
+ assert CATALOG.entries[0] == ("advance", ())
20
+
21
+ def test_masks_follow_observation(self, env):
22
+ obs = env.reset(seed=1, task_id=5)
23
+ mask = CATALOG.mask(GridView(obs))
24
+ assert mask[0]
25
+ closable = [CATALOG.describe(i) for i, ok in enumerate(mask) if ok and CATALOG.entries[i][0] == "breaker"]
26
+ assert closable and all("CLOSED" in c for c in closable) # dark grid: only closing lines makes sense
27
+ assert not any(ok for i, ok in enumerate(mask) if CATALOG.entries[i][0] == "quarantine")
28
+
29
+ def test_every_unmasked_action_is_accepted_by_the_environment(self, env):
30
+ obs = env.reset(seed=2, task_id=2)
31
+ view = GridView(obs)
32
+ for idx in np.flatnonzero(CATALOG.mask(view))[:40]:
33
+ action = CATALOG.to_action(int(idx), view)
34
+ assert action.action_type is not None
35
+
36
+ def test_features_have_fixed_size(self, env):
37
+ for task in range(6):
38
+ obs = env.reset(seed=3, task_id=task)
39
+ feats = featurize(GridView(obs))
40
+ assert feats.shape == (FEATURE_SIZE,) and np.isfinite(feats).all()
41
+
42
+ @pytest.mark.parametrize("task_id", [1, 3, 4])
43
+ def test_discretised_expert_still_solves_tasks(self, task_id):
44
+ env = NexusgridEnvironment()
45
+ policy = DiscretizedExpert()
46
+ obs = env.reset(seed=10_002, task_id=task_id)
47
+ while not obs.done:
48
+ obs = env.step(policy.act(obs))
49
+ assert env.get_score() >= 0.8
50
+
51
+
52
+ class TestGrpoReward:
53
+ def test_collect_states_records_rebuildable_prompts(self):
54
+ records = collect_states([1, 3], episodes=2, seed=0)
55
+ assert records
56
+ for r in records:
57
+ assert r["messages"][0]["role"] == "system"
58
+ assert isinstance(json.loads(r["prefix"]), list)
59
+
60
+ def test_invalid_output_is_penalised(self):
61
+ r = collect_states([1], episodes=1, seed=0)[0]
62
+ assert score_completion("I think we should wait", r["task_id"], r["seed"], r["prefix"])["reward"] == INVALID_REWARD
63
+
64
+ def test_reward_prefers_evidence_over_waiting_in_phantom_attack(self):
65
+ env = NexusgridEnvironment()
66
+ obs = env.reset(seed=11, task_id=3)
67
+ prefix = []
68
+ target = env.debug_state()["attack"]["target_node"]
69
+ while not any(p["anomaly_flag"] and p["source_node"] == target for p in obs.network_packet_logs[-20:]):
70
+ prefix.append({"action_type": "advance_tick"})
71
+ obs = env.step(__import__("models").GridAction(action_type="advance_tick"))
72
+ se = json.dumps({"action_type": "run_state_estimation", "subgraph": [target]})
73
+ wait = json.dumps({"action_type": "advance_tick"})
74
+ good = score_completion(se, 3, 11, prefix)["reward"]
75
+ idle = score_completion(wait, 3, 11, prefix)["reward"]
76
+ assert good > idle + 0.2
tests/verify_server.py DELETED
@@ -1,46 +0,0 @@
1
- """Quick server endpoint verification."""
2
- import urllib.request
3
- import json
4
-
5
- def test_endpoint(name, url):
6
- try:
7
- r = urllib.request.urlopen(url)
8
- body = r.read().decode()
9
- print(f" [{name}] Status: {r.status} - PASS")
10
- return body
11
- except Exception as e:
12
- print(f" [{name}] FAIL: {e}")
13
- return None
14
-
15
- print("=" * 50)
16
- print("SERVER ENDPOINT VERIFICATION")
17
- print("=" * 50)
18
-
19
- # Test /health
20
- body = test_endpoint("/health", "http://localhost:8000/health")
21
- if body:
22
- data = json.loads(body)
23
- print(f" Response: {data}")
24
-
25
- # Test /metadata
26
- body = test_endpoint("/metadata", "http://localhost:8000/metadata")
27
- if body:
28
- data = json.loads(body)
29
- print(f" Name: {data.get('name')}")
30
- print(f" Version: {data.get('version')}")
31
-
32
- # Test /docs
33
- body = test_endpoint("/docs", "http://localhost:8000/docs")
34
- if body:
35
- has_swagger = "swagger" in body.lower()
36
- print(f" Has Swagger UI: {has_swagger}")
37
-
38
- # Test /openapi.json
39
- body = test_endpoint("/openapi.json", "http://localhost:8000/openapi.json")
40
- if body:
41
- data = json.loads(body)
42
- paths = list(data.get("paths", {}).keys())
43
- print(f" API Paths: {paths}")
44
-
45
- print("=" * 50)
46
- print("ALL ENDPOINTS VERIFIED!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
training/__init__.py ADDED
File without changes
training/eval_llm_local.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Evaluate a local Hugging Face model (optionally with a LoRA adapter) as a pure
4
+ NexusGrid operator on held-out seeds. No fallback: invalid outputs become
5
+ ``advance_tick`` and are counted.
6
+
7
+ python training/eval_llm_local.py --model Qwen/Qwen3-1.7B --seeds 10 --out results/llm/qwen3-1.7b-base
8
+ python training/eval_llm_local.py --model Qwen/Qwen3-1.7B --adapter runs/grpo/qwen3-1.7b/adapter \\
9
+ --seeds 10 --out results/llm/qwen3-1.7b-grpo
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import sys
17
+ import time
18
+ from pathlib import Path
19
+
20
+ ROOT = Path(__file__).resolve().parents[1]
21
+ if str(ROOT) not in sys.path:
22
+ sys.path.insert(0, str(ROOT))
23
+
24
+ from inference import SYSTEM_PROMPT, LLMPolicy # noqa: E402
25
+ from scripts.evaluate import markdown_table, summarise # noqa: E402
26
+ from server.nexusgrid_environment import NexusgridEnvironment # noqa: E402
27
+ from server.scenarios import EVAL_SEED_START, TASK_NAMES # noqa: E402
28
+
29
+
30
+ class HFLocalPolicy(LLMPolicy):
31
+ """LLMPolicy that generates with a local transformers (or Unsloth) model instead of an HTTP endpoint."""
32
+
33
+ def __init__(self, model_name: str, adapter: str | None = None, load_in_4bit: bool = False,
34
+ max_new_tokens: int = 96, backend: str = "hf"):
35
+ super().__init__(model=model_name if not adapter else f"{model_name}+{Path(adapter).name}",
36
+ api_base="local", client=object())
37
+ import torch
38
+
39
+ self.torch = torch
40
+ if backend == "unsloth":
41
+ from unsloth import FastLanguageModel
42
+
43
+ model, tokenizer = FastLanguageModel.from_pretrained(
44
+ model_name=adapter or model_name, max_seq_length=4096, load_in_4bit=load_in_4bit or "bnb" in model_name)
45
+ FastLanguageModel.for_inference(model)
46
+ self.tokenizer, self.hf_model = tokenizer, model
47
+ else:
48
+ from transformers import AutoModelForCausalLM, AutoTokenizer
49
+
50
+ from training.train_grpo import dtype_kwargs
51
+
52
+ self.tokenizer = AutoTokenizer.from_pretrained(adapter or model_name)
53
+ kwargs = dtype_kwargs(torch.bfloat16 if torch.cuda.is_available() else torch.float32)
54
+ if torch.cuda.is_available():
55
+ kwargs["device_map"] = {"": 0}
56
+ if load_in_4bit:
57
+ from transformers import BitsAndBytesConfig
58
+
59
+ kwargs["quantization_config"] = BitsAndBytesConfig(
60
+ load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16)
61
+ model = AutoModelForCausalLM.from_pretrained(model_name, **kwargs)
62
+ if adapter:
63
+ from peft import PeftModel
64
+
65
+ model = PeftModel.from_pretrained(model, adapter)
66
+ self.hf_model = model.eval()
67
+ self.max_new_tokens = max_new_tokens
68
+
69
+ def complete(self, prompt: str) -> str:
70
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}]
71
+ text = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True,
72
+ enable_thinking=False)
73
+ inputs = self.tokenizer(text=text, return_tensors="pt").to(self.hf_model.device)
74
+ with self.torch.no_grad():
75
+ output = self.hf_model.generate(**inputs, max_new_tokens=self.max_new_tokens, do_sample=False,
76
+ pad_token_id=self.tokenizer.pad_token_id or self.tokenizer.eos_token_id)
77
+ return self.tokenizer.decode(output[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
78
+
79
+
80
+ def main(argv=None) -> int:
81
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
82
+ p.add_argument("--model", default="Qwen/Qwen3-1.7B")
83
+ p.add_argument("--adapter", default=None)
84
+ p.add_argument("--load-in-4bit", action="store_true")
85
+ p.add_argument("--tasks", default="0,1,2,3,4,5")
86
+ p.add_argument("--seeds", type=int, default=10)
87
+ p.add_argument("--backend", choices=["hf", "unsloth"], default="hf")
88
+ p.add_argument("--out", default="results/llm/local")
89
+ p.add_argument("--log", default=None, help="also write all output to this UTF-8 file")
90
+ args = p.parse_args(argv)
91
+
92
+ from training.logutil import tee_output
93
+
94
+ tee_output(args.log)
95
+ policy = HFLocalPolicy(args.model, args.adapter, args.load_in_4bit, backend=args.backend)
96
+ env = NexusgridEnvironment()
97
+ records = []
98
+ started = time.time()
99
+ label = "llm-grpo" if args.adapter else "llm-base"
100
+ for task_id in [int(t) for t in args.tasks.split(",")]:
101
+ for seed in range(EVAL_SEED_START, EVAL_SEED_START + args.seeds):
102
+ before = dict(policy.stats())
103
+ policy.reset(seed)
104
+ obs = env.reset(seed=seed, task_id=task_id)
105
+ while not obs.done:
106
+ obs = env.step(policy.act(obs))
107
+ summary = env.get_episode_summary()
108
+ after = policy.stats()
109
+ records.append({
110
+ "policy": label, "task_id": task_id, "task_name": TASK_NAMES[task_id], "seed": seed,
111
+ "split": "eval", "score": round(summary["score"], 6), "rubrics": summary["rubrics"],
112
+ "steps": summary["ticks_used"], "invalid_actions": summary["invalid_actions"],
113
+ "invalid_outputs": after["invalid_outputs"] - before["invalid_outputs"],
114
+ "events": summary["events"],
115
+ })
116
+ print(f"[eval] task {task_id} seed {seed}: score {summary['score']:.3f} "
117
+ f"invalid outputs {records[-1]['invalid_outputs']}", flush=True)
118
+ out = Path(args.out)
119
+ out.mkdir(parents=True, exist_ok=True)
120
+ (out / "episodes.jsonl").write_text("\n".join(json.dumps(r) for r in records) + "\n", encoding="utf-8")
121
+ rows = summarise(records)
122
+ (out / "summary.json").write_text(json.dumps({"model": args.model, "adapter": args.adapter, "rows": rows,
123
+ "policy_stats": policy.stats(),
124
+ "minutes": round((time.time() - started) / 60, 1)}, indent=2),
125
+ encoding="utf-8")
126
+ (out / "summary.md").write_text(markdown_table(rows) + "\n", encoding="utf-8")
127
+ print(markdown_table(rows))
128
+ return 0
129
+
130
+
131
+ if __name__ == "__main__":
132
+ raise SystemExit(main())
training/grpo_common.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shared pieces for GRPO training of language-model operators.
3
+
4
+ Nothing here needs a GPU or a model, so it is unit-tested in CI.
5
+
6
+ Prompts
7
+ States are collected from expert trajectories with epsilon-exploration
8
+ (random catalogue actions), so the model also sees off-nominal situations.
9
+ Each record stores how to rebuild the state exactly: task, seed and the
10
+ action prefix (the simulator is deterministic).
11
+
12
+ Reward
13
+ The model's own action is executed in the rebuilt environment, followed by
14
+ ``horizon`` passive ticks (``advance_tick``). The reward is the sum of the
15
+ environment's dense rewards over those steps, so it measures what *this*
16
+ action did, including delayed consequences such as relay trips. Output that
17
+ is not a valid action JSON gets ``INVALID_REWARD``. No scripted fallback is
18
+ ever substituted for the model's action.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import copy
24
+ import json
25
+ import random
26
+ from collections import OrderedDict
27
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
28
+
29
+ from gym_env import CATALOG
30
+ from inference import SYSTEM_PROMPT, parse_action, render_observation, to_grid_action
31
+ from models import ActionType, GridAction
32
+ from policies import ExpertPolicy, GridView
33
+ from server.nexusgrid_environment import NexusgridEnvironment
34
+
35
+ INVALID_REWARD = -1.0
36
+ TRAIN_SEED_RANGE = (0, 9000)
37
+
38
+
39
+ def action_to_dict(action: GridAction) -> Dict[str, Any]:
40
+ data = {k: v for k, v in action.model_dump().items() if v is not None}
41
+ data["action_type"] = action.action_type.value
42
+ return data
43
+
44
+
45
+ def history_line(tick: int, action: GridAction) -> str:
46
+ return f"t{tick} {json.dumps(action_to_dict(action), separators=(',', ':'))}"
47
+
48
+
49
+ def build_messages(obs: Any, history: Sequence[str]) -> List[Dict[str, str]]:
50
+ return [{"role": "system", "content": SYSTEM_PROMPT},
51
+ {"role": "user", "content": render_observation(obs, list(history))}]
52
+
53
+
54
+ def collect_states(tasks: Sequence[int], episodes: int, epsilon: float = 0.25, max_states_per_episode: int = 6,
55
+ seed: int = 0, seed_range: Tuple[int, int] = TRAIN_SEED_RANGE) -> List[Dict[str, Any]]:
56
+ """Roll out the expert with exploration and sample decision states from each episode."""
57
+ rng = random.Random(seed)
58
+ env = NexusgridEnvironment()
59
+ records: List[Dict[str, Any]] = []
60
+ for episode in range(episodes):
61
+ task_id = tasks[episode % len(tasks)]
62
+ ep_seed = rng.randrange(*seed_range)
63
+ expert = ExpertPolicy()
64
+ obs = env.reset(seed=ep_seed, task_id=task_id)
65
+ prefix: List[Dict[str, Any]] = []
66
+ history: List[str] = []
67
+ candidates: List[Dict[str, Any]] = []
68
+ while not obs.done:
69
+ expert_action = expert.act(obs)
70
+ candidates.append({
71
+ "task_id": task_id,
72
+ "seed": ep_seed,
73
+ "tick": obs.tick,
74
+ "prefix": json.dumps(prefix),
75
+ "messages": build_messages(obs, history),
76
+ "expert_action": json.dumps(action_to_dict(expert_action)),
77
+ })
78
+ if rng.random() < epsilon:
79
+ view = GridView(obs)
80
+ valid = [i for i, ok in enumerate(CATALOG.mask(view)) if ok]
81
+ action = CATALOG.to_action(rng.choice(valid), view)
82
+ else:
83
+ action = expert_action
84
+ history.append(history_line(obs.tick, action))
85
+ prefix.append(action_to_dict(action))
86
+ obs = env.step(action)
87
+ # Prefer states where the expert actually acted; keep a few quiet ones too.
88
+ active = [c for c in candidates if json.loads(c["expert_action"])["action_type"] != "advance_tick"]
89
+ quiet = [c for c in candidates if c not in active]
90
+ rng.shuffle(active)
91
+ rng.shuffle(quiet)
92
+ keep = active[: max_states_per_episode - 1] + quiet[:1]
93
+ records.extend(keep[:max_states_per_episode])
94
+ return records
95
+
96
+
97
+ _SNAPSHOTS: "OrderedDict[str, Tuple[NexusgridEnvironment, Any]]" = OrderedDict()
98
+ _SNAPSHOT_LIMIT = 64
99
+
100
+
101
+ def rebuild(task_id: int, seed: int, prefix: Iterable[Dict[str, Any]]) -> Tuple[NexusgridEnvironment, Any]:
102
+ """Recreate the exact state (the simulator is deterministic); snapshots are cached per prompt."""
103
+ prefix = list(prefix)
104
+ key = json.dumps([int(task_id), int(seed), prefix], sort_keys=True)
105
+ if key not in _SNAPSHOTS:
106
+ env = NexusgridEnvironment()
107
+ obs = env.reset(seed=int(seed), task_id=int(task_id))
108
+ for action in prefix:
109
+ obs = env.step(GridAction(**action))
110
+ _SNAPSHOTS[key] = (env, obs)
111
+ if len(_SNAPSHOTS) > _SNAPSHOT_LIMIT:
112
+ _SNAPSHOTS.popitem(last=False)
113
+ else:
114
+ _SNAPSHOTS.move_to_end(key)
115
+ env, obs = _SNAPSHOTS[key]
116
+ return copy.deepcopy(env), obs
117
+
118
+
119
+ def score_action(action: Optional[GridAction], task_id: int, seed: int, prefix: Sequence[Dict[str, Any]],
120
+ horizon: int = 2) -> Dict[str, Any]:
121
+ """Dense reward of ``action`` plus ``horizon`` passive ticks, from the rebuilt state."""
122
+ if action is None:
123
+ return {"reward": INVALID_REWARD, "valid": False, "error": "unparseable"}
124
+ env, obs = rebuild(task_id, seed, prefix)
125
+ if obs.done:
126
+ return {"reward": 0.0, "valid": True, "error": "episode already finished"}
127
+ obs = env.step(action)
128
+ total = float(obs.reward)
129
+ error = obs.last_action_error
130
+ for _ in range(horizon):
131
+ if obs.done:
132
+ break
133
+ obs = env.step(GridAction(action_type=ActionType.ADVANCE_TICK))
134
+ total += float(obs.reward)
135
+ return {"reward": round(total, 6), "valid": True, "error": error}
136
+
137
+
138
+ def score_completion(text: str, task_id: int, seed: int, prefix: str | Sequence[Dict[str, Any]],
139
+ horizon: int = 2) -> Dict[str, Any]:
140
+ prefix_list = json.loads(prefix) if isinstance(prefix, str) else list(prefix)
141
+ return score_action(to_grid_action(parse_action(text)), task_id, seed, prefix_list, horizon)
142
+
143
+
144
+ def completion_text(completion: Any) -> str:
145
+ """TRL passes plain strings or chat-style message lists depending on the dataset format."""
146
+ if isinstance(completion, str):
147
+ return completion
148
+ if isinstance(completion, list) and completion and isinstance(completion[0], dict):
149
+ return str(completion[-1].get("content", ""))
150
+ return str(completion)
151
+
152
+
153
+ def make_reward_fn(horizon: int = 2):
154
+ """Reward function with the signature TRL's GRPOTrainer expects."""
155
+
156
+ def nexusgrid_reward(prompts, completions, task_id, seed, prefix, **kwargs) -> List[float]:
157
+ rewards = []
158
+ for text, t, s, p in zip(completions, task_id, seed, prefix):
159
+ rewards.append(score_completion(completion_text(text), int(t), int(s), p, horizon)["reward"])
160
+ return rewards
161
+
162
+ nexusgrid_reward.__name__ = "nexusgrid_reward"
163
+ return nexusgrid_reward
training/logutil.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mirror stdout/stderr to a UTF-8 log file (Windows PowerShell redirection writes UTF-16)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Optional
9
+
10
+
11
+ class _Tee(io.TextIOBase):
12
+ def __init__(self, stream, handle):
13
+ self._stream, self._handle = stream, handle
14
+
15
+ def write(self, data):
16
+ try:
17
+ self._stream.write(data)
18
+ except UnicodeEncodeError:
19
+ self._stream.write(data.encode("ascii", "replace").decode("ascii"))
20
+ self._handle.write(data)
21
+ self._handle.flush()
22
+ return len(data)
23
+
24
+ def flush(self):
25
+ self._stream.flush()
26
+ self._handle.flush()
27
+
28
+
29
+ def tee_output(path: Optional[str]) -> None:
30
+ if not path:
31
+ return
32
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
33
+ handle = open(path, "a", encoding="utf-8")
34
+ sys.stdout = _Tee(sys.stdout, handle)
35
+ sys.stderr = _Tee(sys.stderr, handle)
training/make_tiny_model.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Create a tiny random-weight causal LM with a NexusGrid-trained BPE tokenizer.
4
+
5
+ Used for CPU smoke tests of the GRPO pipeline without downloading a model:
6
+
7
+ python training/make_tiny_model.py --out runs/tiny-model
8
+ python training/train_grpo.py --model runs/tiny-model --cpu --max-steps 2 --dataset-episodes 4 \\
9
+ --num-generations 2 --max-completion-length 16 --out runs/grpo-smoke
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ ROOT = Path(__file__).resolve().parents[1]
19
+ if str(ROOT) not in sys.path:
20
+ sys.path.insert(0, str(ROOT))
21
+
22
+ CHAT_TEMPLATE = (
23
+ "{% for m in messages %}<|{{ m['role'] }}|>\n{{ m['content'] }}<|end|>\n{% endfor %}"
24
+ "{% if add_generation_prompt %}<|assistant|>\n{% endif %}"
25
+ )
26
+
27
+
28
+ def main(argv=None) -> int:
29
+ p = argparse.ArgumentParser()
30
+ p.add_argument("--out", default="runs/tiny-model")
31
+ args = p.parse_args(argv)
32
+
33
+ from tokenizers import Tokenizer, models, pre_tokenizers, trainers
34
+ from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
35
+
36
+ from inference import SYSTEM_PROMPT, render_observation
37
+ from server.nexusgrid_environment import NexusgridEnvironment
38
+
39
+ env = NexusgridEnvironment()
40
+ corpus = [SYSTEM_PROMPT]
41
+ for task in range(6):
42
+ corpus.append(render_observation(env.reset(seed=task, task_id=task)))
43
+ corpus.append('{"action_type":"dispatch_generation","node_id":"NODE_01","mw":120}')
44
+
45
+ tok = Tokenizer(models.BPE(unk_token="<unk>"))
46
+ tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
47
+ trainer = trainers.BpeTrainer(vocab_size=600, special_tokens=["<unk>", "<pad>", "<|end|>", "<|system|>",
48
+ "<|user|>", "<|assistant|>"])
49
+ tok.train_from_iterator(corpus, trainer)
50
+ from tokenizers import decoders
51
+
52
+ tok.decoder = decoders.ByteLevel()
53
+ tokenizer = PreTrainedTokenizerFast(tokenizer_object=tok, unk_token="<unk>", pad_token="<pad>",
54
+ eos_token="<|end|>")
55
+ tokenizer.chat_template = CHAT_TEMPLATE
56
+ config = LlamaConfig(vocab_size=len(tokenizer), hidden_size=64, intermediate_size=128, num_hidden_layers=2,
57
+ num_attention_heads=4, num_key_value_heads=2, max_position_embeddings=4096,
58
+ pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id,
59
+ bos_token_id=tokenizer.eos_token_id)
60
+ model = LlamaForCausalLM(config)
61
+ out = Path(args.out)
62
+ out.mkdir(parents=True, exist_ok=True)
63
+ model.save_pretrained(out)
64
+ tokenizer.save_pretrained(out)
65
+ print(f"tiny model ({sum(p.numel() for p in model.parameters()) / 1e3:.0f}k params) -> {out}")
66
+ return 0
67
+
68
+
69
+ if __name__ == "__main__":
70
+ raise SystemExit(main())
training/plots.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plots for training curves and evaluation summaries (matplotlib, headless)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Dict, List, Sequence
9
+
10
+ import matplotlib
11
+
12
+ matplotlib.use("Agg")
13
+ import matplotlib.pyplot as plt # noqa: E402
14
+
15
+ INK = "#1f2937"
16
+ GRID = "#e5e7eb"
17
+ SERIES = ["#2563eb", "#16a34a", "#dc2626", "#9333ea", "#ea580c", "#0891b2"]
18
+
19
+
20
+ def _style(ax, title: str, xlabel: str, ylabel: str) -> None:
21
+ ax.set_title(title, color=INK, fontsize=12, loc="left")
22
+ ax.set_xlabel(xlabel, color=INK)
23
+ ax.set_ylabel(ylabel, color=INK)
24
+ ax.grid(True, color=GRID, linewidth=0.8)
25
+ for spine in ("top", "right"):
26
+ ax.spines[spine].set_visible(False)
27
+
28
+
29
+ def read_curve(path: Path) -> List[Dict[str, float]]:
30
+ with open(path, encoding="utf-8") as fh:
31
+ return [{k: float(v) for k, v in row.items() if v not in ("", "nan")} for row in csv.DictReader(fh)]
32
+
33
+
34
+ def plot_ppo_curves(runs: Dict[str, Path], out: Path, title: str, references: Dict[str, float] | None = None) -> None:
35
+ """Validation score vs. timesteps for several runs, with horizontal reference lines."""
36
+ fig, ax = plt.subplots(figsize=(7.5, 4.2), dpi=150)
37
+ for i, (label, path) in enumerate(runs.items()):
38
+ rows = [r for r in read_curve(path) if "val_score" in r]
39
+ ax.plot([r["timesteps"] for r in rows], [r["val_score"] for r in rows], marker="o", markersize=3,
40
+ color=SERIES[i % len(SERIES)], label=label, linewidth=2)
41
+ for j, (label, value) in enumerate((references or {}).items()):
42
+ ax.axhline(value, linestyle="--", linewidth=1.2, color=["#6b7280", "#9ca3af", "#111827"][j % 3])
43
+ ax.text(ax.get_xlim()[1], value, f" {label} {value:.2f}", va="center", fontsize=8, color=INK)
44
+ ax.set_ylim(-0.02, 1.05)
45
+ _style(ax, title, "environment steps", "validation score (30 seeds)")
46
+ ax.legend(frameon=False, fontsize=9, loc="lower right")
47
+ fig.tight_layout()
48
+ out.parent.mkdir(parents=True, exist_ok=True)
49
+ fig.savefig(out)
50
+ plt.close(fig)
51
+
52
+
53
+ def plot_grpo_log(log_path: Path, out: Path) -> None:
54
+ history = json.loads(Path(log_path).read_text(encoding="utf-8"))
55
+ points = [(h["step"], h["reward"]) for h in history if "reward" in h and "step" in h]
56
+ if not points:
57
+ return
58
+ steps, rewards = zip(*points)
59
+ window = max(1, len(rewards) // 20)
60
+ smooth = [sum(rewards[max(0, i - window + 1): i + 1]) / len(rewards[max(0, i - window + 1): i + 1])
61
+ for i in range(len(rewards))]
62
+ fig, ax = plt.subplots(figsize=(7.5, 4.2), dpi=150)
63
+ ax.plot(steps, rewards, color="#93c5fd", linewidth=1, label="per step")
64
+ ax.plot(steps, smooth, color="#1d4ed8", linewidth=2.2, label=f"moving average ({window})")
65
+ _style(ax, "GRPO training reward (simulator-scored actions)", "optimizer step", "mean reward")
66
+ ax.legend(frameon=False, fontsize=9)
67
+ fig.tight_layout()
68
+ out.parent.mkdir(parents=True, exist_ok=True)
69
+ fig.savefig(out)
70
+ plt.close(fig)
71
+
72
+
73
+ def plot_policy_bars(rows: Sequence[Dict], out: Path, policies: Sequence[str], title: str) -> None:
74
+ """Grouped bars: mean held-out score per task for each policy."""
75
+ tasks = sorted({(r["task_id"], r["task_name"]) for r in rows})
76
+ lookup = {(r["policy"], r["task_id"]): r for r in rows}
77
+ width = 0.8 / max(1, len(policies))
78
+ fig, ax = plt.subplots(figsize=(8.5, 4.2), dpi=150)
79
+ for i, policy in enumerate(policies):
80
+ xs = [t + (i - (len(policies) - 1) / 2) * width for t, _ in tasks]
81
+ ys = [lookup.get((policy, t), {}).get("mean_score", 0.0) for t, _ in tasks]
82
+ err = [lookup.get((policy, t), {}).get("ci95", 0.0) for t, _ in tasks]
83
+ ax.bar(xs, ys, width=width * 0.95, color=SERIES[i % len(SERIES)], label=policy, yerr=err,
84
+ error_kw={"elinewidth": 0.8, "capsize": 2, "ecolor": INK})
85
+ ax.set_xticks([t for t, _ in tasks])
86
+ ax.set_xticklabels([f"T{t}\n{name.replace('_', ' ')}" for t, name in tasks], fontsize=8)
87
+ ax.set_ylim(0, 1.08)
88
+ _style(ax, title, "", "mean score (held-out seeds, 95% CI)")
89
+ ax.legend(frameon=False, fontsize=9, ncol=len(policies), loc="upper center", bbox_to_anchor=(0.5, -0.18))
90
+ fig.tight_layout()
91
+ out.parent.mkdir(parents=True, exist_ok=True)
92
+ fig.savefig(out)
93
+ plt.close(fig)