Update server/Wildfire_env.py

#7
Files changed (1) hide show
  1. server/Wildfire_env.py +694 -407
server/Wildfire_env.py CHANGED
@@ -1,407 +1,694 @@
1
- # Copyright (c) Meta Platforms, Inc. and affiliates.
2
- # All rights reserved.
3
- #
4
- # This source code is licensed under the BSD-style license found in the
5
- # LICENSE file in the root directory of this source tree.
6
-
7
- import random
8
- import copy
9
- from uuid import uuid4
10
- from typing import Dict, List, Any, Tuple
11
-
12
- from openenv.core.env_server.interfaces import Environment
13
- from openenv.core.env_server.types import State
14
-
15
- try:
16
- from ..models import WildfireAction, WildfireObservation
17
- except ImportError:
18
- from models import WildfireAction, WildfireObservation
19
-
20
- # Cell states
21
- CLEAR = 0
22
- BURNING = 1
23
- BURNT = 2
24
- FIREBREAK = 3
25
-
26
- # Division zones on 20x20 grid
27
- DIVISIONS = {
28
- "A": {"rows": (0, 9), "cols": (0, 9)},
29
- "B": {"rows": (0, 9), "cols": (10, 19)},
30
- "C": {"rows": (10, 19),"cols": (0, 9)},
31
- "D": {"rows": (10, 19),"cols": (10, 19)},
32
- }
33
- DIV_INDEX = ["A", "B", "C", "D"]
34
-
35
- WIND_DIRS = ["N", "S", "E", "W"]
36
-
37
-
38
- class Wildfire_env(Environment):
39
- """
40
- Wildfire Incident Command RL Environment.
41
- Simulates ICS-based wildfire suppression on a 20x20 grid
42
- with hierarchical agent structure (Division Supervisors + Crew Bosses).
43
- """
44
-
45
- SUPPORTS_CONCURRENT_SESSIONS: bool = True
46
-
47
- def __init__(self):
48
- self._state = State(episode_id=str(uuid4()), step_count=0)
49
- self.grid_size = 20
50
- self.reset()
51
-
52
- # ------------------------------------------------------------------
53
- # Core API
54
- # ------------------------------------------------------------------
55
-
56
- def reset(self, task: int = 1) -> WildfireObservation:
57
- """Reset environment to starting state for a given task (1/2/3)."""
58
- self._state = State(episode_id=str(uuid4()), step_count=0)
59
- self.task = task
60
- self.timestep = 0
61
- self.done = False
62
- self.grid = [[CLEAR] * self.grid_size for _ in range(self.grid_size)]
63
- self.assets_burned_this_step = []
64
- self.front_merges = 0
65
-
66
- # Wind
67
- if task == 3:
68
- rng = random.Random(42) # Fixed seed for consistent wind in task 3
69
- self.wind = {
70
- "direction": rng.choice(WIND_DIRS),
71
- "speed": round(rng.uniform(0.3, 0.7), 2)
72
- }
73
- elif task == 2:
74
- self.wind = {"direction": "S", "speed": 0.5}
75
- else:
76
- self.wind = {"direction": "E", "speed": 0.3}
77
-
78
- # Max steps per task
79
- self.max_steps = {1: 30, 2: 50, 3: 60}[task]
80
-
81
- # Place initial fire
82
- self._init_fire(task)
83
-
84
- # Place assets
85
- self._init_assets(task)
86
-
87
- # Place crews (2 per division)
88
- self._init_crews()
89
-
90
- return self._get_obs(reward=0.0, done=False, info={"task": task})
91
-
92
- def step(self, action: WildfireAction) -> WildfireObservation: # type: ignore[override]
93
- """Apply action, spread fire, compute reward."""
94
- if self.done:
95
- return self._get_obs(reward=0.0, done=True, info={"error": "Episode done"})
96
-
97
- self.assets_burned_this_step = []
98
- reward = 0.0
99
- info = {}
100
-
101
- old_containment = self._containment_pct()
102
-
103
- # Apply action
104
- action_dict = action.model_dump()
105
- result = self._apply_action(action_dict)
106
- info.update(result)
107
-
108
- # Spread fire
109
- self._spread_fire()
110
-
111
- # Check assets
112
- for asset in self.assets:
113
- if asset["status"] == "safe":
114
- r, c = asset["cell"]
115
- if self.grid[r][c] == BURNING or self.grid[r][c] == BURNT:
116
- asset["status"] = "burned"
117
- self.assets_burned_this_step.append(asset["id"])
118
-
119
- # Check front merges (task 3)
120
- if self.task == 3:
121
- merges = self._detect_merges()
122
- self.front_merges += merges
123
- else:
124
- merges = 0
125
-
126
- new_containment = self._containment_pct()
127
- containment_delta = new_containment - old_containment
128
-
129
- # Reward components
130
- assets_safe = sum(1 for a in self.assets if a["status"] == "safe")
131
- asset_ratio = assets_safe / len(self.assets) if self.assets else 1.0
132
- crew_eff = result.get("efficiency", 0.0)
133
- idle_pen = 1.0 if result.get("idle", False) else 0.0
134
- assets_destroyed = len(self.assets_burned_this_step)
135
-
136
- reward = (
137
- 0.4 * containment_delta
138
- + 0.3 * asset_ratio
139
- + 0.2 * crew_eff
140
- - 0.1 * idle_pen
141
- - 0.5 * assets_destroyed
142
- - 0.8 * merges
143
- )
144
-
145
- self.timestep += 1
146
- self._state.step_count = self.timestep
147
-
148
- if self.timestep >= self.max_steps or self._all_fire_contained():
149
- self.done = True
150
-
151
- info["containment_pct"] = new_containment
152
- info["assets_safe"] = assets_safe
153
-
154
- return self._get_obs(reward=round(reward, 4), done=self.done, info=info)
155
-
156
- @property
157
- def state(self) -> State:
158
- """
159
- Get the current environment state for OpenEnv internal tracking.
160
- """
161
- return self._state
162
-
163
- def get_internal_state(self) -> Dict[str, Any]:
164
- """Full internal state snapshot for graders."""
165
- return {
166
- "grid": self.grid,
167
- "crews": self.crews,
168
- "wind": self.wind,
169
- "timestep": self.timestep,
170
- "containment_pct": self._containment_pct(),
171
- "assets": self.assets,
172
- "task": self.task,
173
- "done": self.done,
174
- "front_merges": self.front_merges,
175
- }
176
-
177
- # ------------------------------------------------------------------
178
- # Observation
179
- # ------------------------------------------------------------------
180
-
181
- def _get_obs(self, reward: float = 0.0, done: bool = False, info: Dict[str, Any] = None) -> WildfireObservation:
182
- info = info or {}
183
- division_zones = []
184
- for i, (div_id, zone) in enumerate(DIVISIONS.items()):
185
- division_zones.append({
186
- "id": i,
187
- "label": div_id,
188
- "row_start": zone["rows"][0],
189
- "row_end": zone["rows"][1],
190
- "col_start": zone["cols"][0],
191
- "col_end": zone["cols"][1],
192
- })
193
-
194
- crew_positions = []
195
- for crew in self.crews:
196
- crew_positions.append({
197
- "id": crew["id"],
198
- "division": crew["division"],
199
- "cell": crew["cell"],
200
- "status": crew["status"],
201
- })
202
-
203
- burning_per_division = {}
204
- for div_label, zone in DIVISIONS.items():
205
- burning_per_division[div_label] = sum(
206
- 1 for r in range(zone["rows"][0], zone["rows"][1] + 1)
207
- for c in range(zone["cols"][0], zone["cols"][1] + 1)
208
- if self.grid[r][c] == BURNING
209
- )
210
-
211
- return WildfireObservation(
212
- grid=self.grid,
213
- division_zones=division_zones,
214
- crew_positions=crew_positions,
215
- wind=self.wind,
216
- assets_at_risk=self.assets,
217
- timestep=self.timestep,
218
- containment_pct=round(self._containment_pct(), 4),
219
- burning_per_division=burning_per_division,
220
- reward=reward,
221
- done=done,
222
- metadata=info,
223
- )
224
-
225
- # ------------------------------------------------------------------
226
- # Init helpers
227
- # ------------------------------------------------------------------
228
-
229
- def _init_fire(self, task: int):
230
- if task == 1:
231
- for r in range(2, 7):
232
- for c in range(2, 7):
233
- self.grid[r][c] = BURNING
234
- elif task == 2:
235
- for c in range(5, 15):
236
- self.grid[0][c] = BURNING
237
- elif task == 3:
238
- for r in range(2, 6):
239
- self.grid[r][2] = BURNING
240
- self.grid[r][3] = BURNING
241
- for r in range(2, 6):
242
- self.grid[r][12] = BURNING
243
- self.grid[r][13] = BURNING
244
- for r in range(12, 16):
245
- self.grid[r][2] = BURNING
246
- self.grid[r][3] = BURNING
247
-
248
- def _init_assets(self, task: int):
249
- if task == 1:
250
- self.assets = []
251
- elif task == 2:
252
- self.assets = [
253
- {"id": "town", "name": "Town", "cell": [15, 10], "status": "safe"},
254
- {"id": "water_tower", "name": "Water Tower", "cell": [12, 5], "status": "safe"},
255
- {"id": "road_junction","name": "Road Junction", "cell": [14, 15], "status": "safe"},
256
- ]
257
- elif task == 3:
258
- self.assets = [
259
- {"id": "A1", "name": "Asset A1", "cell": [7, 7], "status": "safe"},
260
- {"id": "A2", "name": "Asset A2", "cell": [8, 2], "status": "safe"},
261
- {"id": "B1", "name": "Asset B1", "cell": [7, 17], "status": "safe"},
262
- {"id": "B2", "name": "Asset B2", "cell": [8, 12], "status": "safe"},
263
- {"id": "C1", "name": "Asset C1", "cell": [17, 7], "status": "safe"},
264
- {"id": "C2", "name": "Asset C2", "cell": [18, 2], "status": "safe"},
265
- ]
266
-
267
- def _init_crews(self):
268
- self.crews = []
269
- crew_id = 0
270
- for div_idx, (div_label, zone) in enumerate(DIVISIONS.items()):
271
- r_mid = (zone["rows"][0] + zone["rows"][1]) // 2
272
- c_mid = (zone["cols"][0] + zone["cols"][1]) // 2
273
- for offset in [0, 1]:
274
- self.crews.append({
275
- "id": crew_id,
276
- "division": div_idx,
277
- "division_label": div_label,
278
- "cell": [r_mid, c_mid + offset],
279
- "status": "active",
280
- })
281
- crew_id += 1
282
-
283
- # ------------------------------------------------------------------
284
- # Action handling
285
- # ------------------------------------------------------------------
286
-
287
- def _apply_action(self, action: Dict) -> Dict:
288
- try:
289
- div_id = int(action.get("division_id", 0))
290
- crew_id = int(action.get("crew_id", 0))
291
- action_type = str(action.get("action_type", "HOLD")).upper()
292
- target = action.get("target_cell", [0, 0])
293
- r, c = int(target[0]), int(target[1])
294
- except Exception:
295
- return {"error": "Invalid action format", "efficiency": 0.0, "idle": False}
296
-
297
- crew = self._find_crew(div_id, crew_id)
298
- if crew is None:
299
- return {"error": "Crew not found", "efficiency": 0.0, "idle": False}
300
- if not (0 <= r < self.grid_size and 0 <= c < self.grid_size):
301
- return {"error": "Target out of bounds", "efficiency": 0.0, "idle": False}
302
-
303
- efficiency = 0.0
304
- idle = False
305
-
306
- if action_type == "SUPPRESS":
307
- if self.grid[r][c] == BURNING:
308
- self.grid[r][c] = BURNT
309
- efficiency = 1.0
310
- crew["cell"] = [r, c]
311
- elif action_type == "FIREBREAK":
312
- if self.grid[r][c] == CLEAR:
313
- self.grid[r][c] = FIREBREAK
314
- efficiency = 0.5
315
- crew["cell"] = [r, c]
316
- elif action_type == "MOVE":
317
- crew["cell"] = [r, c]
318
- elif action_type == "HOLD":
319
- if self._fire_nearby(crew["cell"]):
320
- idle = True
321
-
322
- return {"action": action_type, "efficiency": efficiency, "idle": idle}
323
-
324
- def _find_crew(self, div_id: int, crew_id: int):
325
- div_crews = [c for c in self.crews if c["division"] == div_id]
326
- if crew_id < len(div_crews):
327
- return div_crews[crew_id]
328
- return None
329
-
330
- def _fire_nearby(self, cell: List[int], radius: int = 2) -> bool:
331
- r, c = cell
332
- for dr in range(-radius, radius + 1):
333
- for dc in range(-radius, radius + 1):
334
- nr, nc = r + dr, c + dc
335
- if 0 <= nr < self.grid_size and 0 <= nc < self.grid_size:
336
- if self.grid[nr][nc] == BURNING:
337
- return True
338
- return False
339
-
340
- # ------------------------------------------------------------------
341
- # Fire spread
342
- # ------------------------------------------------------------------
343
-
344
- def _spread_fire(self):
345
- direction = self.wind["direction"]
346
- speed = self.wind["speed"]
347
- wind_offsets = {"N": [(-1, 0)], "S": [(1, 0)], "E": [(0, 1)], "W": [(0, -1)]}
348
- primary = wind_offsets[direction]
349
- all_neighbors = [(-1,0),(1,0),(0,-1),(0,1)]
350
-
351
- new_grid = copy.deepcopy(self.grid)
352
- for r in range(self.grid_size):
353
- for c in range(self.grid_size):
354
- if self.grid[r][c] == BURNING:
355
- if random.random() < 0.3:
356
- new_grid[r][c] = BURNT
357
- for dr, dc in all_neighbors:
358
- nr, nc = r + dr, c + dc
359
- if not (0 <= nr < self.grid_size and 0 <= nc < self.grid_size):
360
- continue
361
- if self.grid[nr][nc] != CLEAR:
362
- continue
363
- prob = speed * 0.4
364
- if (dr, dc) in primary:
365
- prob = speed * 0.9
366
- if random.random() < prob:
367
- new_grid[nr][nc] = BURNING
368
- self.grid = new_grid
369
-
370
- # ------------------------------------------------------------------
371
- # Metrics
372
- # ------------------------------------------------------------------
373
-
374
- def _containment_pct(self) -> float:
375
- burning = sum(
376
- 1 for r in range(self.grid_size)
377
- for c in range(self.grid_size)
378
- if self.grid[r][c] == BURNING
379
- )
380
- if burning == 0:
381
- return 1.0
382
- total_affected = sum(
383
- 1 for r in range(self.grid_size)
384
- for c in range(self.grid_size)
385
- if self.grid[r][c] in (BURNING, BURNT)
386
- )
387
- if total_affected == 0:
388
- return 1.0
389
- return round(1.0 - (burning / max(total_affected, 1)), 4)
390
-
391
- def _all_fire_contained(self) -> bool:
392
- return all(
393
- self.grid[r][c] != BURNING
394
- for r in range(self.grid_size)
395
- for c in range(self.grid_size)
396
- )
397
-
398
- def _detect_merges(self) -> int:
399
- div_has_fire = {}
400
- for i, (label, zone) in enumerate(DIVISIONS.items()):
401
- div_has_fire[i] = any(
402
- self.grid[r][c] == BURNING
403
- for r in range(zone["rows"][0], zone["rows"][1] + 1)
404
- for c in range(zone["cols"][0], zone["cols"][1] + 1)
405
- )
406
- adjacent = [(0, 1), (0, 2), (1, 3), (2, 3)]
407
- return sum(1 for a, b in adjacent if div_has_fire.get(a) and div_has_fire.get(b))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Wildfire Incident Command Environment
9
+
10
+ Implements the SimFire/SimHarness reward formula from:
11
+ "Reinforcement Learning for Wildfire Mitigation in Simulated Disaster
12
+ Environments" — Tapley et al., NeurIPS 2023 Workshop
13
+ arXiv:2311.15925
14
+
15
+ Paper reward equations implemented here (Appendix B.2):
16
+ Eq 1: DamagedSim_t = Sim[Burned_t] + Sim[Burning_t] + Sim[Mitigated_t]
17
+ Eq 2: DamagedBench_t = Bench[Burned_t] + Bench[Burning_t]
18
+ Eq 3: NewDamagedSim_t = DamagedSim_t - DamagedSim_{t-1}
19
+ Eq 4: NewDamagedBench_t = DamagedBench_t - DamagedBench_{t-1}
20
+ Eq 5: TotalEndangered = Bench_final[Burned] (pre-computed at reset)
21
+ Eq 6: Reward_t = (NewDamagedBench_t - NewDamagedSim_t) / TotalEndangered
22
+ Eq 7: Reward_t += 0.25 / Area_sim (bonus for placing new mitigation on
23
+ previously unmitigated clear cell)
24
+
25
+ Key implementation details:
26
+ - A BenchmarkSim shadow runs in parallel WITHOUT agent actions each step.
27
+ - TotalEndangered pre-computed at reset() by fast-forwarding benchmark
28
+ to completion before the real episode starts.
29
+ - Positive reward = agent saved more land than nature would have burned.
30
+ - Zero reward = agent performed identically to doing nothing.
31
+ - Negative reward = agent's actions made things worse than doing nothing.
32
+
33
+ Additional fixes vs original:
34
+ - Task 3 max_steps corrected 60 -> 75
35
+ - burn_age tracker: cells burn 3-5 steps before transitioning to BURNT
36
+ - Diagonal fire spread added (more realistic)
37
+ - _detect_merges() checks actual boundary cell adjacency
38
+ - WETLINE and SCRATCHLINE action types supported with correct efficiencies
39
+ - Fuel map adds natural resistance at division boundary rows/cols
40
+ """
41
+
42
+ import random
43
+ import copy
44
+ from uuid import uuid4
45
+ from typing import Dict, List, Any, Tuple, Optional
46
+
47
+ from openenv.core.env_server.interfaces import Environment
48
+ from openenv.core.env_server.types import State
49
+
50
+ try:
51
+ from ..models import WildfireAction, WildfireObservation
52
+ except ImportError:
53
+ from models import WildfireAction, WildfireObservation
54
+
55
+ # ---------------------------------------------------------------------------
56
+ # Cell states
57
+ # ---------------------------------------------------------------------------
58
+ CLEAR = 0
59
+ BURNING = 1
60
+ BURNT = 2
61
+ FIREBREAK = 3
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Division zones on 20x20 grid
65
+ # ---------------------------------------------------------------------------
66
+ DIVISIONS = {
67
+ "A": {"rows": (0, 9), "cols": (0, 9)},
68
+ "B": {"rows": (0, 9), "cols": (10, 19)},
69
+ "C": {"rows": (10, 19), "cols": (0, 9)},
70
+ "D": {"rows": (10, 19), "cols": (10, 19)},
71
+ }
72
+
73
+ WIND_DIRS = ["N", "S", "E", "W"]
74
+
75
+ WIND_OFFSETS = {
76
+ "N": (-1, 0),
77
+ "S": ( 1, 0),
78
+ "E": ( 0, 1),
79
+ "W": ( 0, -1),
80
+ }
81
+
82
+ ALL_NEIGHBORS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
83
+ DIAGONALS = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
84
+
85
+
86
+ # ===========================================================================
87
+ # BenchmarkSim — shadow simulation with NO agent actions (paper Section B.2)
88
+ # ===========================================================================
89
+
90
+ class BenchmarkSim:
91
+ """
92
+ Lightweight clone of the fire spread that runs WITHOUT any agent
93
+ interventions. Used to compute the paper's unmitigated baseline.
94
+
95
+ Tracks damaged_per_step[t] = DamagedBench_t for every timestep so the
96
+ main environment can look up the exact benchmark value at any step.
97
+ """
98
+
99
+ def __init__(self, grid: List[List[int]], wind: Dict[str, Any],
100
+ max_steps: int, fuel_map: List[List[float]],
101
+ rng_seed: int = 0):
102
+ self.grid = copy.deepcopy(grid)
103
+ self.wind = wind
104
+ self.max_steps = max_steps
105
+ self.fuel_map = fuel_map
106
+ self.size = len(grid)
107
+ self.rng = random.Random(rng_seed)
108
+ self.burn_age: Dict[Tuple[int, int], int] = {}
109
+
110
+ for r in range(self.size):
111
+ for c in range(self.size):
112
+ if self.grid[r][c] == BURNING:
113
+ self.burn_age[(r, c)] = 0
114
+
115
+ # Index 0 = initial state before any steps
116
+ self.damaged_per_step: List[int] = [self._damaged()]
117
+ self.final_burned: int = 0
118
+
119
+ def prerun(self) -> int:
120
+ """
121
+ Paper Eq 5: fast-forward to episode end to get TotalEndangered.
122
+ Records damaged_per_step for every timestep.
123
+ Returns TotalEndangered (minimum 1 to avoid division by zero).
124
+ """
125
+ for _ in range(self.max_steps):
126
+ self._spread()
127
+ self.damaged_per_step.append(self._damaged())
128
+ if self._all_out():
129
+ break
130
+
131
+ self.final_burned = sum(
132
+ 1 for r in range(self.size)
133
+ for c in range(self.size)
134
+ if self.grid[r][c] == BURNT
135
+ )
136
+ return max(self.final_burned, 1)
137
+
138
+ def step(self) -> int:
139
+ """
140
+ Advance one live step. Returns DamagedBench_t (Paper Eq 2).
141
+ Called each time the main env calls step() to keep in sync.
142
+ """
143
+ self._spread()
144
+ d = self._damaged()
145
+ self.damaged_per_step.append(d)
146
+ return d
147
+
148
+ # ------------------------------------------------------------------
149
+ # Internal helpers
150
+ # ------------------------------------------------------------------
151
+
152
+ def _damaged(self) -> int:
153
+ """Paper Eq 2: Bench[Burned_t] + Bench[Burning_t]"""
154
+ return sum(
155
+ 1 for r in range(self.size)
156
+ for c in range(self.size)
157
+ if self.grid[r][c] in (BURNING, BURNT)
158
+ )
159
+
160
+ def _all_out(self) -> bool:
161
+ return all(
162
+ self.grid[r][c] != BURNING
163
+ for r in range(self.size)
164
+ for c in range(self.size)
165
+ )
166
+
167
+ def _spread(self):
168
+ direction = self.wind["direction"]
169
+ speed = self.wind["speed"]
170
+ primary = WIND_OFFSETS[direction]
171
+ new_grid = copy.deepcopy(self.grid)
172
+
173
+ for r in range(self.size):
174
+ for c in range(self.size):
175
+ if self.grid[r][c] == BURNING:
176
+ age = self.burn_age.get((r, c), 0) + 1
177
+ self.burn_age[(r, c)] = age
178
+ burnout = 3 + hash((r, c, 99)) % 3
179
+ if age >= burnout:
180
+ new_grid[r][c] = BURNT
181
+ self.burn_age.pop((r, c), None)
182
+
183
+ for dr, dc in ALL_NEIGHBORS:
184
+ nr, nc = r + dr, c + dc
185
+ if not (0 <= nr < self.size and 0 <= nc < self.size):
186
+ continue
187
+ if self.grid[nr][nc] != CLEAR:
188
+ continue
189
+ fuel = self.fuel_map[nr][nc]
190
+ prob = speed * 0.35 * fuel
191
+ if (dr, dc) == primary:
192
+ prob = speed * 0.80 * fuel
193
+ if self.rng.random() < prob:
194
+ new_grid[nr][nc] = BURNING
195
+ self.burn_age[(nr, nc)] = 0
196
+
197
+ for dr, dc in DIAGONALS:
198
+ nr, nc = r + dr, c + dc
199
+ if not (0 <= nr < self.size and 0 <= nc < self.size):
200
+ continue
201
+ if self.grid[nr][nc] != CLEAR:
202
+ continue
203
+ fuel = self.fuel_map[nr][nc]
204
+ if self.rng.random() < speed * 0.15 * fuel:
205
+ new_grid[nr][nc] = BURNING
206
+ self.burn_age[(nr, nc)] = 0
207
+
208
+ self.grid = new_grid
209
+
210
+
211
+ # ===========================================================================
212
+ # WildfireEnv — main environment with paper reward formula
213
+ # ===========================================================================
214
+
215
+ class WildfireEnv(Environment):
216
+ """
217
+ Wildfire Incident Command RL Environment.
218
+
219
+ Per-step reward follows the SimFire/SimHarness paper (Tapley et al. 2023):
220
+
221
+ Reward_t = (NewDamagedBench_t - NewDamagedSim_t) / TotalEndangered
222
+ [+ 0.25/400 if new mitigation placed on a previously clear cell]
223
+
224
+ A positive reward means the agent saved more land this step than an
225
+ unmitigated fire would have burned. The total episode reward directly
226
+ corresponds to the total proportion of area saved (vs doing nothing).
227
+ """
228
+
229
+ SUPPORTS_CONCURRENT_SESSIONS: bool = True
230
+
231
+ def __init__(self):
232
+ self._state = State(episode_id=str(uuid4()), step_count=0)
233
+ self.grid_size = 20
234
+ self.reset()
235
+
236
+ # ------------------------------------------------------------------
237
+ # Core API
238
+ # ------------------------------------------------------------------
239
+
240
+ def reset(self, task: int = 1) -> WildfireObservation:
241
+ """
242
+ Reset environment. Pre-runs a benchmark simulation to compute
243
+ TotalEndangered (Paper Eq 5) before the real episode begins.
244
+ """
245
+ self._state = State(episode_id=str(uuid4()), step_count=0)
246
+ self.task = task
247
+ self.timestep = 0
248
+ self.done = False
249
+ self.grid = [[CLEAR] * self.grid_size for _ in range(self.grid_size)]
250
+ self.assets_burned_this_step = []
251
+ self.front_merges = 0
252
+ self.burn_age: Dict[Tuple[int, int], int] = {}
253
+
254
+ # Wind
255
+ if task == 3:
256
+ rng = random.Random(42)
257
+ self.wind = {
258
+ "direction": rng.choice(WIND_DIRS),
259
+ "speed": round(rng.uniform(0.3, 0.7), 2),
260
+ }
261
+ elif task == 2:
262
+ self.wind = {"direction": "S", "speed": 0.5}
263
+ else:
264
+ self.wind = {"direction": "E", "speed": 0.3}
265
+
266
+ # Task 3 is 75 steps (was wrongly 60 in original)
267
+ self.max_steps = {1: 30, 2: 50, 3: 75}[task]
268
+
269
+ self._init_fire(task)
270
+ self._init_assets(task)
271
+ self._init_crews()
272
+ self.fuel_map = self._build_fuel_map()
273
+
274
+ # ------------------------------------------------------------------
275
+ # Paper Eq 5: pre-run benchmark → TotalEndangered
276
+ # ------------------------------------------------------------------
277
+ _bench_prerun = BenchmarkSim(
278
+ grid=self.grid,
279
+ wind=self.wind,
280
+ max_steps=self.max_steps,
281
+ fuel_map=self.fuel_map,
282
+ rng_seed=hash(self.task) & 0xFFFF,
283
+ )
284
+ self._total_endangered: int = _bench_prerun.prerun()
285
+
286
+ # Live benchmark kept in sync with main sim step-by-step
287
+ self._bench_live = BenchmarkSim(
288
+ grid=self.grid,
289
+ wind=self.wind,
290
+ max_steps=self.max_steps,
291
+ fuel_map=self.fuel_map,
292
+ rng_seed=hash(self.task) & 0xFFFF,
293
+ )
294
+
295
+ # Paper Eq 3/4: track previous-step damaged counts
296
+ self._damaged_sim_prev: int = self._count_damaged_sim()
297
+ self._damaged_bench_prev: int = self._bench_live._damaged()
298
+
299
+ # Track cells where mitigation has been placed (for Eq 7 bonus)
300
+ self._mitigated_cells: set = set()
301
+
302
+ return self._get_obs(reward=0.0, done=False, info={"task": task})
303
+
304
+ def step(self, action: WildfireAction) -> WildfireObservation: # type: ignore[override]
305
+ """
306
+ Apply action, spread fire, step benchmark, compute paper reward.
307
+ """
308
+ if self.done:
309
+ return self._get_obs(reward=0.0, done=True, info={"error": "Episode done"})
310
+
311
+ self.assets_burned_this_step = []
312
+ info: Dict[str, Any] = {}
313
+
314
+ # 1. Apply agent action
315
+ action_dict = action.model_dump()
316
+ result = self._apply_action(action_dict)
317
+ info.update(result)
318
+
319
+ # 2. Spread fire in main (mitigated) sim
320
+ self._spread_fire()
321
+
322
+ # 3. Step the live benchmark (no agent, same physics tick)
323
+ damaged_bench_t: int = self._bench_live.step() # Paper Eq 2
324
+
325
+ # 4. Check assets
326
+ for asset in self.assets:
327
+ if asset["status"] == "safe":
328
+ r, c = asset["cell"]
329
+ if self.grid[r][c] in (BURNING, BURNT):
330
+ asset["status"] = "burned"
331
+ self.assets_burned_this_step.append(asset["id"])
332
+
333
+ # 5. Front merge check (Task 3 only)
334
+ merges = self._detect_merges() if self.task == 3 else 0
335
+ self.front_merges += merges
336
+
337
+ # ------------------------------------------------------------------
338
+ # Paper reward formula (Equations 1–7)
339
+ # ------------------------------------------------------------------
340
+
341
+ # Eq 1: DamagedSim_t (burning + burnt + mitigated by agent)
342
+ damaged_sim_t: int = self._count_damaged_sim()
343
+
344
+ # Eq 3 & 4: incremental new damage this step
345
+ new_damaged_sim = max(0, damaged_sim_t - self._damaged_sim_prev)
346
+ new_damaged_bench = max(0, damaged_bench_t - self._damaged_bench_prev)
347
+
348
+ # Eq 6: core reward — positive = agent outperformed doing nothing
349
+ reward = (new_damaged_bench - new_damaged_sim) / self._total_endangered
350
+
351
+ # Eq 7: bonus for placing a brand-new mitigation on an unburned cell
352
+ if result.get("new_mitigation", False):
353
+ reward += 0.25 / (self.grid_size * self.grid_size)
354
+
355
+ # Extra penalties not in original paper but needed for task 2/3 grading
356
+ assets_destroyed = len(self.assets_burned_this_step)
357
+ if assets_destroyed > 0:
358
+ reward -= 0.5 * assets_destroyed
359
+ if merges > 0:
360
+ reward -= 0.8 * merges
361
+
362
+ # 6. Update prev-step trackers
363
+ self._damaged_sim_prev = damaged_sim_t
364
+ self._damaged_bench_prev = damaged_bench_t
365
+
366
+ # 7. Advance timestep
367
+ self.timestep += 1
368
+ self._state.step_count = self.timestep
369
+
370
+ if self.timestep >= self.max_steps or self._all_fire_contained():
371
+ self.done = True
372
+
373
+ info.update({
374
+ "containment_pct": round(self._containment_pct(), 4),
375
+ "assets_safe": sum(1 for a in self.assets if a["status"] == "safe"),
376
+ "new_damaged_sim": new_damaged_sim,
377
+ "new_damaged_bench": new_damaged_bench,
378
+ "total_endangered": self._total_endangered,
379
+ })
380
+
381
+ return self._get_obs(reward=round(reward, 6), done=self.done, info=info)
382
+
383
+ @property
384
+ def state(self) -> State:
385
+ return self._state
386
+
387
+ def get_internal_state(self) -> Dict[str, Any]:
388
+ return {
389
+ "grid": self.grid,
390
+ "crews": self.crews,
391
+ "wind": self.wind,
392
+ "timestep": self.timestep,
393
+ "containment_pct": self._containment_pct(),
394
+ "assets": self.assets,
395
+ "task": self.task,
396
+ "done": self.done,
397
+ "front_merges": self.front_merges,
398
+ "total_endangered": self._total_endangered,
399
+ }
400
+
401
+ # ------------------------------------------------------------------
402
+ # Observation builder
403
+ # ------------------------------------------------------------------
404
+
405
+ def _get_obs(self, reward: float = 0.0, done: bool = False,
406
+ info: Optional[Dict[str, Any]] = None) -> WildfireObservation:
407
+ info = info or {}
408
+
409
+ division_zones = [
410
+ {
411
+ "id": i,
412
+ "label": div_id,
413
+ "row_start": zone["rows"][0],
414
+ "row_end": zone["rows"][1],
415
+ "col_start": zone["cols"][0],
416
+ "col_end": zone["cols"][1],
417
+ }
418
+ for i, (div_id, zone) in enumerate(DIVISIONS.items())
419
+ ]
420
+
421
+ crew_positions = [
422
+ {"id": c["id"], "division": c["division"],
423
+ "cell": c["cell"], "status": c["status"]}
424
+ for c in self.crews
425
+ ]
426
+
427
+ burning_per_division = {
428
+ label: sum(
429
+ 1
430
+ for r in range(zone["rows"][0], zone["rows"][1] + 1)
431
+ for c in range(zone["cols"][0], zone["cols"][1] + 1)
432
+ if self.grid[r][c] == BURNING
433
+ )
434
+ for label, zone in DIVISIONS.items()
435
+ }
436
+
437
+ return WildfireObservation(
438
+ grid=self.grid,
439
+ division_zones=division_zones,
440
+ crew_positions=crew_positions,
441
+ wind=self.wind,
442
+ assets_at_risk=self.assets,
443
+ timestep=self.timestep,
444
+ containment_pct=round(self._containment_pct(), 4),
445
+ burning_per_division=burning_per_division,
446
+ reward=reward,
447
+ done=done,
448
+ metadata=info,
449
+ )
450
+
451
+ # ------------------------------------------------------------------
452
+ # Init helpers
453
+ # ------------------------------------------------------------------
454
+
455
+ def _init_fire(self, task: int):
456
+ if task == 1:
457
+ for r in range(2, 7):
458
+ for c in range(2, 7):
459
+ self.grid[r][c] = BURNING
460
+ elif task == 2:
461
+ for c in range(5, 15):
462
+ self.grid[0][c] = BURNING
463
+ elif task == 3:
464
+ for r in range(2, 7):
465
+ self.grid[r][2] = BURNING
466
+ self.grid[r][3] = BURNING
467
+ for r in range(2, 7):
468
+ self.grid[r][12] = BURNING
469
+ self.grid[r][13] = BURNING
470
+ for r in range(12, 17):
471
+ self.grid[r][2] = BURNING
472
+ self.grid[r][3] = BURNING
473
+
474
+ for r in range(self.grid_size):
475
+ for c in range(self.grid_size):
476
+ if self.grid[r][c] == BURNING:
477
+ self.burn_age[(r, c)] = 0
478
+
479
+ def _init_assets(self, task: int):
480
+ if task == 1:
481
+ self.assets = []
482
+ elif task == 2:
483
+ self.assets = [
484
+ {"id": "town", "name": "Town", "cell": [15, 10], "status": "safe"},
485
+ {"id": "water_tower", "name": "Water Tower", "cell": [12, 5], "status": "safe"},
486
+ {"id": "road_junction", "name": "Road Junction", "cell": [14, 15], "status": "safe"},
487
+ ]
488
+ elif task == 3:
489
+ self.assets = [
490
+ {"id": "A1", "name": "Asset A1", "cell": [ 7, 7], "status": "safe"},
491
+ {"id": "A2", "name": "Asset A2", "cell": [ 8, 2], "status": "safe"},
492
+ {"id": "B1", "name": "Asset B1", "cell": [ 7, 17], "status": "safe"},
493
+ {"id": "B2", "name": "Asset B2", "cell": [ 8, 12], "status": "safe"},
494
+ {"id": "C1", "name": "Asset C1", "cell": [17, 7], "status": "safe"},
495
+ {"id": "C2", "name": "Asset C2", "cell": [18, 2], "status": "safe"},
496
+ ]
497
+
498
+ def _init_crews(self):
499
+ self.crews = []
500
+ crew_id = 0
501
+ for div_idx, (div_label, zone) in enumerate(DIVISIONS.items()):
502
+ r_mid = (zone["rows"][0] + zone["rows"][1]) // 2
503
+ c_mid = (zone["cols"][0] + zone["cols"][1]) // 2
504
+ for offset in [0, 1]:
505
+ self.crews.append({
506
+ "id": crew_id,
507
+ "division": div_idx,
508
+ "division_label": div_label,
509
+ "cell": [r_mid, c_mid + offset],
510
+ "status": "active",
511
+ })
512
+ crew_id += 1
513
+
514
+ def _build_fuel_map(self) -> List[List[float]]:
515
+ fuel = [[1.0] * self.grid_size for _ in range(self.grid_size)]
516
+ for r in range(self.grid_size):
517
+ for c in range(self.grid_size):
518
+ if r in (9, 10) or c in (9, 10):
519
+ fuel[r][c] = 0.5
520
+ return fuel
521
+
522
+ # ------------------------------------------------------------------
523
+ # Action handling
524
+ # ------------------------------------------------------------------
525
+
526
+ def _apply_action(self, action: Dict) -> Dict:
527
+ try:
528
+ div_id = int(action.get("division_id", 0))
529
+ crew_id = int(action.get("crew_id", 0))
530
+ action_type = str(action.get("action_type", "HOLD")).upper()
531
+ target = action.get("target_cell", [0, 0])
532
+ r, c = int(target[0]), int(target[1])
533
+ except Exception:
534
+ return {"error": "Invalid action", "efficiency": 0.0,
535
+ "idle": False, "new_mitigation": False}
536
+
537
+ crew = self._find_crew(div_id, crew_id)
538
+ if crew is None:
539
+ return {"error": "Crew not found", "efficiency": 0.0,
540
+ "idle": False, "new_mitigation": False}
541
+ if not (0 <= r < self.grid_size and 0 <= c < self.grid_size):
542
+ return {"error": "Out of bounds", "efficiency": 0.0,
543
+ "idle": False, "new_mitigation": False}
544
+
545
+ efficiency = 0.0
546
+ idle = False
547
+ new_mitigation = False
548
+
549
+ if action_type == "SUPPRESS":
550
+ if self.grid[r][c] == BURNING:
551
+ self.grid[r][c] = BURNT
552
+ efficiency = 1.0
553
+ crew["cell"] = [r, c]
554
+
555
+ elif action_type in ("FIREBREAK", "SCRATCHLINE"):
556
+ eff_map = {"FIREBREAK": 0.5, "SCRATCHLINE": 0.3}
557
+ if self.grid[r][c] == CLEAR:
558
+ is_new = (r, c) not in self._mitigated_cells
559
+ self.grid[r][c] = FIREBREAK
560
+ self._mitigated_cells.add((r, c))
561
+ efficiency = eff_map[action_type]
562
+ new_mitigation = is_new
563
+ crew["cell"] = [r, c]
564
+
565
+ elif action_type == "WETLINE":
566
+ if self.grid[r][c] in (CLEAR, BURNING):
567
+ is_new = (r, c) not in self._mitigated_cells
568
+ self.grid[r][c] = FIREBREAK
569
+ self._mitigated_cells.add((r, c))
570
+ efficiency = 0.7
571
+ new_mitigation = is_new
572
+ crew["cell"] = [r, c]
573
+
574
+ elif action_type == "MOVE":
575
+ crew["cell"] = [r, c]
576
+
577
+ elif action_type == "HOLD":
578
+ if self._fire_nearby(crew["cell"]):
579
+ idle = True
580
+
581
+ return {"action": action_type, "efficiency": efficiency,
582
+ "idle": idle, "new_mitigation": new_mitigation}
583
+
584
+ def _find_crew(self, div_id: int, crew_id: int):
585
+ div_crews = [c for c in self.crews if c["division"] == div_id]
586
+ return div_crews[crew_id] if crew_id < len(div_crews) else None
587
+
588
+ def _fire_nearby(self, cell: List[int], radius: int = 2) -> bool:
589
+ r, c = cell
590
+ for dr in range(-radius, radius + 1):
591
+ for dc in range(-radius, radius + 1):
592
+ nr, nc = r + dr, c + dc
593
+ if 0 <= nr < self.grid_size and 0 <= nc < self.grid_size:
594
+ if self.grid[nr][nc] == BURNING:
595
+ return True
596
+ return False
597
+
598
+ # ------------------------------------------------------------------
599
+ # Fire spread (main mitigated sim)
600
+ # ------------------------------------------------------------------
601
+
602
+ def _spread_fire(self):
603
+ direction = self.wind["direction"]
604
+ speed = self.wind["speed"]
605
+ primary = WIND_OFFSETS[direction]
606
+ new_grid = copy.deepcopy(self.grid)
607
+
608
+ for r in range(self.grid_size):
609
+ for c in range(self.grid_size):
610
+ if self.grid[r][c] == BURNING:
611
+ age = self.burn_age.get((r, c), 0) + 1
612
+ self.burn_age[(r, c)] = age
613
+ burnout = 3 + hash((r, c, self.task)) % 3
614
+ if age >= burnout:
615
+ new_grid[r][c] = BURNT
616
+ self.burn_age.pop((r, c), None)
617
+
618
+ for dr, dc in ALL_NEIGHBORS:
619
+ nr, nc = r + dr, c + dc
620
+ if not (0 <= nr < self.grid_size and 0 <= nc < self.grid_size):
621
+ continue
622
+ if self.grid[nr][nc] != CLEAR:
623
+ continue
624
+ fuel = self.fuel_map[nr][nc]
625
+ prob = speed * 0.35 * fuel
626
+ if (dr, dc) == primary:
627
+ prob = speed * 0.80 * fuel
628
+ if random.random() < prob:
629
+ new_grid[nr][nc] = BURNING
630
+ self.burn_age[(nr, nc)] = 0
631
+
632
+ for dr, dc in DIAGONALS:
633
+ nr, nc = r + dr, c + dc
634
+ if not (0 <= nr < self.grid_size and 0 <= nc < self.grid_size):
635
+ continue
636
+ if self.grid[nr][nc] != CLEAR:
637
+ continue
638
+ fuel = self.fuel_map[nr][nc]
639
+ if random.random() < speed * 0.15 * fuel:
640
+ new_grid[nr][nc] = BURNING
641
+ self.burn_age[(nr, nc)] = 0
642
+
643
+ self.grid = new_grid
644
+
645
+ # ------------------------------------------------------------------
646
+ # Metrics
647
+ # ------------------------------------------------------------------
648
+
649
+ def _count_damaged_sim(self) -> int:
650
+ """Paper Eq 1: Burned + Burning + Mitigated (FIREBREAK) cells."""
651
+ return sum(
652
+ 1 for r in range(self.grid_size)
653
+ for c in range(self.grid_size)
654
+ if self.grid[r][c] in (BURNING, BURNT, FIREBREAK)
655
+ )
656
+
657
+ def _containment_pct(self) -> float:
658
+ burning = sum(
659
+ 1 for r in range(self.grid_size)
660
+ for c in range(self.grid_size)
661
+ if self.grid[r][c] == BURNING
662
+ )
663
+ if burning == 0:
664
+ return 1.0
665
+ total = sum(
666
+ 1 for r in range(self.grid_size)
667
+ for c in range(self.grid_size)
668
+ if self.grid[r][c] in (BURNING, BURNT)
669
+ )
670
+ return round(1.0 - (burning / max(total, 1)), 4)
671
+
672
+ def _all_fire_contained(self) -> bool:
673
+ return all(
674
+ self.grid[r][c] != BURNING
675
+ for r in range(self.grid_size)
676
+ for c in range(self.grid_size)
677
+ )
678
+
679
+ def _detect_merges(self) -> int:
680
+ """Check actual adjacent boundary cells across all 4 division edges."""
681
+ merges = 0
682
+ for r in range(0, 10): # A↔B
683
+ if self.grid[r][9] == BURNING and self.grid[r][10] == BURNING:
684
+ merges += 1; break
685
+ for r in range(10, 20): # C↔D
686
+ if self.grid[r][9] == BURNING and self.grid[r][10] == BURNING:
687
+ merges += 1; break
688
+ for c in range(0, 10): # A↔C
689
+ if self.grid[9][c] == BURNING and self.grid[10][c] == BURNING:
690
+ merges += 1; break
691
+ for c in range(10, 20): # B↔D
692
+ if self.grid[9][c] == BURNING and self.grid[10][c] == BURNING:
693
+ merges += 1; break
694
+ return merges