OpenEnv_Hackathon / server /Wildfire_env.py
Ayush Rawat
fix WildfireEnv > Wildfire_env
e1ea26d
Raw History Blame Contribute Delete
26.9 kB
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
"""
Wildfire Incident Command Environment
Implements the SimFire/SimHarness reward formula from:
"Reinforcement Learning for Wildfire Mitigation in Simulated Disaster
Environments" — Tapley et al., NeurIPS 2023 Workshop
arXiv:2311.15925
Paper reward equations implemented here (Appendix B.2):
Eq 1: DamagedSim_t = Sim[Burned_t] + Sim[Burning_t] + Sim[Mitigated_t]
Eq 2: DamagedBench_t = Bench[Burned_t] + Bench[Burning_t]
Eq 3: NewDamagedSim_t = DamagedSim_t - DamagedSim_{t-1}
Eq 4: NewDamagedBench_t = DamagedBench_t - DamagedBench_{t-1}
Eq 5: TotalEndangered = Bench_final[Burned] (pre-computed at reset)
Eq 6: Reward_t = (NewDamagedBench_t - NewDamagedSim_t) / TotalEndangered
Eq 7: Reward_t += 0.25 / Area_sim (bonus for placing new mitigation on
previously unmitigated clear cell)
Key implementation details:
- A BenchmarkSim shadow runs in parallel WITHOUT agent actions each step.
- TotalEndangered pre-computed at reset() by fast-forwarding benchmark
to completion before the real episode starts.
- Positive reward = agent saved more land than nature would have burned.
- Zero reward = agent performed identically to doing nothing.
- Negative reward = agent's actions made things worse than doing nothing.
Additional fixes vs original:
- Task 3 max_steps corrected 60 -> 75
- burn_age tracker: cells burn 3-5 steps before transitioning to BURNT
- Diagonal fire spread added (more realistic)
- _detect_merges() checks actual boundary cell adjacency
- WETLINE and SCRATCHLINE action types supported with correct efficiencies
- Fuel map adds natural resistance at division boundary rows/cols
"""
import random
import copy
from uuid import uuid4
from typing import Dict, List, Any, Tuple, Optional
from openenv.core.env_server.interfaces import Environment
from openenv.core.env_server.types import State
try:
from ..models import WildfireAction, WildfireObservation
except ImportError:
from models import WildfireAction, WildfireObservation
# ---------------------------------------------------------------------------
# Cell states
# ---------------------------------------------------------------------------
CLEAR = 0
BURNING = 1
BURNT = 2
FIREBREAK = 3
# ---------------------------------------------------------------------------
# Division zones on 20x20 grid
# ---------------------------------------------------------------------------
DIVISIONS = {
"A": {"rows": (0, 9), "cols": (0, 9)},
"B": {"rows": (0, 9), "cols": (10, 19)},
"C": {"rows": (10, 19), "cols": (0, 9)},
"D": {"rows": (10, 19), "cols": (10, 19)},
}
WIND_DIRS = ["N", "S", "E", "W"]
WIND_OFFSETS = {
"N": (-1, 0),
"S": ( 1, 0),
"E": ( 0, 1),
"W": ( 0, -1),
}
ALL_NEIGHBORS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
DIAGONALS = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
# ===========================================================================
# BenchmarkSim — shadow simulation with NO agent actions (paper Section B.2)
# ===========================================================================
class BenchmarkSim:
"""
Lightweight clone of the fire spread that runs WITHOUT any agent
interventions. Used to compute the paper's unmitigated baseline.
Tracks damaged_per_step[t] = DamagedBench_t for every timestep so the
main environment can look up the exact benchmark value at any step.
"""
def __init__(self, grid: List[List[int]], wind: Dict[str, Any],
max_steps: int, fuel_map: List[List[float]],
rng_seed: int = 0):
self.grid = copy.deepcopy(grid)
self.wind = wind
self.max_steps = max_steps
self.fuel_map = fuel_map
self.size = len(grid)
self.rng = random.Random(rng_seed)
self.burn_age: Dict[Tuple[int, int], int] = {}
for r in range(self.size):
for c in range(self.size):
if self.grid[r][c] == BURNING:
self.burn_age[(r, c)] = 0
# Index 0 = initial state before any steps
self.damaged_per_step: List[int] = [self._damaged()]
self.final_burned: int = 0
def prerun(self) -> int:
"""
Paper Eq 5: fast-forward to episode end to get TotalEndangered.
Records damaged_per_step for every timestep.
Returns TotalEndangered (minimum 1 to avoid division by zero).
"""
for _ in range(self.max_steps):
self._spread()
self.damaged_per_step.append(self._damaged())
if self._all_out():
break
self.final_burned = sum(
1 for r in range(self.size)
for c in range(self.size)
if self.grid[r][c] == BURNT
)
return max(self.final_burned, 1)
def step(self) -> int:
"""
Advance one live step. Returns DamagedBench_t (Paper Eq 2).
Called each time the main env calls step() to keep in sync.
"""
self._spread()
d = self._damaged()
self.damaged_per_step.append(d)
return d
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _damaged(self) -> int:
"""Paper Eq 2: Bench[Burned_t] + Bench[Burning_t]"""
return sum(
1 for r in range(self.size)
for c in range(self.size)
if self.grid[r][c] in (BURNING, BURNT)
)
def _all_out(self) -> bool:
return all(
self.grid[r][c] != BURNING
for r in range(self.size)
for c in range(self.size)
)
def _spread(self):
direction = self.wind["direction"]
speed = self.wind["speed"]
primary = WIND_OFFSETS[direction]
new_grid = copy.deepcopy(self.grid)
for r in range(self.size):
for c in range(self.size):
if self.grid[r][c] == BURNING:
age = self.burn_age.get((r, c), 0) + 1
self.burn_age[(r, c)] = age
burnout = 3 + hash((r, c, 99)) % 3
if age >= burnout:
new_grid[r][c] = BURNT
self.burn_age.pop((r, c), None)
for dr, dc in ALL_NEIGHBORS:
nr, nc = r + dr, c + dc
if not (0 <= nr < self.size and 0 <= nc < self.size):
continue
if self.grid[nr][nc] != CLEAR:
continue
fuel = self.fuel_map[nr][nc]
prob = speed * 0.35 * fuel
if (dr, dc) == primary:
prob = speed * 0.80 * fuel
if self.rng.random() < prob:
new_grid[nr][nc] = BURNING
self.burn_age[(nr, nc)] = 0
for dr, dc in DIAGONALS:
nr, nc = r + dr, c + dc
if not (0 <= nr < self.size and 0 <= nc < self.size):
continue
if self.grid[nr][nc] != CLEAR:
continue
fuel = self.fuel_map[nr][nc]
if self.rng.random() < speed * 0.15 * fuel:
new_grid[nr][nc] = BURNING
self.burn_age[(nr, nc)] = 0
self.grid = new_grid
# ===========================================================================
# WildfireEnv — main environment with paper reward formula
# ===========================================================================
class Wildfire_env(Environment):
"""
Wildfire Incident Command RL Environment.
Per-step reward follows the SimFire/SimHarness paper (Tapley et al. 2023):
Reward_t = (NewDamagedBench_t - NewDamagedSim_t) / TotalEndangered
[+ 0.25/400 if new mitigation placed on a previously clear cell]
A positive reward means the agent saved more land this step than an
unmitigated fire would have burned. The total episode reward directly
corresponds to the total proportion of area saved (vs doing nothing).
"""
SUPPORTS_CONCURRENT_SESSIONS: bool = True
def __init__(self):
self._state = State(episode_id=str(uuid4()), step_count=0)
self.grid_size = 20
self.reset()
# ------------------------------------------------------------------
# Core API
# ------------------------------------------------------------------
def reset(self, task: int = 1) -> WildfireObservation:
"""
Reset environment. Pre-runs a benchmark simulation to compute
TotalEndangered (Paper Eq 5) before the real episode begins.
"""
self._state = State(episode_id=str(uuid4()), step_count=0)
self.task = task
self.timestep = 0
self.done = False
self.grid = [[CLEAR] * self.grid_size for _ in range(self.grid_size)]
self.assets_burned_this_step = []
self.front_merges = 0
self.burn_age: Dict[Tuple[int, int], int] = {}
# Wind
if task == 3:
rng = random.Random(42)
self.wind = {
"direction": rng.choice(WIND_DIRS),
"speed": round(rng.uniform(0.3, 0.7), 2),
}
elif task == 2:
self.wind = {"direction": "S", "speed": 0.5}
else:
self.wind = {"direction": "E", "speed": 0.3}
# Task 3 is 75 steps (was wrongly 60 in original)
self.max_steps = {1: 30, 2: 50, 3: 75}[task]
self._init_fire(task)
self._init_assets(task)
self._init_crews()
self.fuel_map = self._build_fuel_map()
# ------------------------------------------------------------------
# Paper Eq 5: pre-run benchmark → TotalEndangered
# ------------------------------------------------------------------
_bench_prerun = BenchmarkSim(
grid=self.grid,
wind=self.wind,
max_steps=self.max_steps,
fuel_map=self.fuel_map,
rng_seed=hash(self.task) & 0xFFFF,
)
self._total_endangered: int = _bench_prerun.prerun()
# Live benchmark kept in sync with main sim step-by-step
self._bench_live = BenchmarkSim(
grid=self.grid,
wind=self.wind,
max_steps=self.max_steps,
fuel_map=self.fuel_map,
rng_seed=hash(self.task) & 0xFFFF,
)
# Paper Eq 3/4: track previous-step damaged counts
self._damaged_sim_prev: int = self._count_damaged_sim()
self._damaged_bench_prev: int = self._bench_live._damaged()
# Track cells where mitigation has been placed (for Eq 7 bonus)
self._mitigated_cells: set = set()
return self._get_obs(reward=0.0, done=False, info={"task": task})
def step(self, action: WildfireAction) -> WildfireObservation: # type: ignore[override]
"""
Apply action, spread fire, step benchmark, compute paper reward.
"""
if self.done:
return self._get_obs(reward=0.0, done=True, info={"error": "Episode done"})
self.assets_burned_this_step = []
info: Dict[str, Any] = {}
# 1. Apply agent action
action_dict = action.model_dump()
result = self._apply_action(action_dict)
info.update(result)
# 2. Spread fire in main (mitigated) sim
self._spread_fire()
# 3. Step the live benchmark (no agent, same physics tick)
damaged_bench_t: int = self._bench_live.step() # Paper Eq 2
# 4. Check assets
for asset in self.assets:
if asset["status"] == "safe":
r, c = asset["cell"]
if self.grid[r][c] in (BURNING, BURNT):
asset["status"] = "burned"
self.assets_burned_this_step.append(asset["id"])
# 5. Front merge check (Task 3 only)
merges = self._detect_merges() if self.task == 3 else 0
self.front_merges += merges
# ------------------------------------------------------------------
# Paper reward formula (Equations 1–7)
# ------------------------------------------------------------------
# Eq 1: DamagedSim_t (burning + burnt + mitigated by agent)
damaged_sim_t: int = self._count_damaged_sim()
# Eq 3 & 4: incremental new damage this step
new_damaged_sim = max(0, damaged_sim_t - self._damaged_sim_prev)
new_damaged_bench = max(0, damaged_bench_t - self._damaged_bench_prev)
# Eq 6: core reward — positive = agent outperformed doing nothing
reward = (new_damaged_bench - new_damaged_sim) / self._total_endangered
# Eq 7: bonus for placing a brand-new mitigation on an unburned cell
if result.get("new_mitigation", False):
reward += 0.25 / (self.grid_size * self.grid_size)
# Extra penalties not in original paper but needed for task 2/3 grading
assets_destroyed = len(self.assets_burned_this_step)
if assets_destroyed > 0:
reward -= 0.5 * assets_destroyed
if merges > 0:
reward -= 0.8 * merges
# 6. Update prev-step trackers
self._damaged_sim_prev = damaged_sim_t
self._damaged_bench_prev = damaged_bench_t
# 7. Advance timestep
self.timestep += 1
self._state.step_count = self.timestep
if self.timestep >= self.max_steps or self._all_fire_contained():
self.done = True
info.update({
"containment_pct": round(self._containment_pct(), 4),
"assets_safe": sum(1 for a in self.assets if a["status"] == "safe"),
"new_damaged_sim": new_damaged_sim,
"new_damaged_bench": new_damaged_bench,
"total_endangered": self._total_endangered,
})
return self._get_obs(reward=round(reward, 6), done=self.done, info=info)
@property
def state(self) -> State:
return self._state
def get_internal_state(self) -> Dict[str, Any]:
return {
"grid": self.grid,
"crews": self.crews,
"wind": self.wind,
"timestep": self.timestep,
"containment_pct": self._containment_pct(),
"assets": self.assets,
"task": self.task,
"done": self.done,
"front_merges": self.front_merges,
"total_endangered": self._total_endangered,
}
# ------------------------------------------------------------------
# Observation builder
# ------------------------------------------------------------------
def _get_obs(self, reward: float = 0.0, done: bool = False,
info: Optional[Dict[str, Any]] = None) -> WildfireObservation:
info = info or {}
division_zones = [
{
"id": i,
"label": div_id,
"row_start": zone["rows"][0],
"row_end": zone["rows"][1],
"col_start": zone["cols"][0],
"col_end": zone["cols"][1],
}
for i, (div_id, zone) in enumerate(DIVISIONS.items())
]
crew_positions = [
{"id": c["id"], "division": c["division"],
"cell": c["cell"], "status": c["status"]}
for c in self.crews
]
burning_per_division = {
label: sum(
1
for r in range(zone["rows"][0], zone["rows"][1] + 1)
for c in range(zone["cols"][0], zone["cols"][1] + 1)
if self.grid[r][c] == BURNING
)
for label, zone in DIVISIONS.items()
}
return WildfireObservation(
grid=self.grid,
division_zones=division_zones,
crew_positions=crew_positions,
wind=self.wind,
assets_at_risk=self.assets,
timestep=self.timestep,
containment_pct=round(self._containment_pct(), 4),
burning_per_division=burning_per_division,
reward=reward,
done=done,
metadata=info,
)
# ------------------------------------------------------------------
# Init helpers
# ------------------------------------------------------------------
def _init_fire(self, task: int):
if task == 1:
for r in range(2, 7):
for c in range(2, 7):
self.grid[r][c] = BURNING
elif task == 2:
for c in range(5, 15):
self.grid[0][c] = BURNING
elif task == 3:
for r in range(2, 7):
self.grid[r][2] = BURNING
self.grid[r][3] = BURNING
for r in range(2, 7):
self.grid[r][12] = BURNING
self.grid[r][13] = BURNING
for r in range(12, 17):
self.grid[r][2] = BURNING
self.grid[r][3] = BURNING
for r in range(self.grid_size):
for c in range(self.grid_size):
if self.grid[r][c] == BURNING:
self.burn_age[(r, c)] = 0
def _init_assets(self, task: int):
if task == 1:
self.assets = []
elif task == 2:
self.assets = [
{"id": "town", "name": "Town", "cell": [15, 10], "status": "safe"},
{"id": "water_tower", "name": "Water Tower", "cell": [12, 5], "status": "safe"},
{"id": "road_junction", "name": "Road Junction", "cell": [14, 15], "status": "safe"},
]
elif task == 3:
self.assets = [
{"id": "A1", "name": "Asset A1", "cell": [ 7, 7], "status": "safe"},
{"id": "A2", "name": "Asset A2", "cell": [ 8, 2], "status": "safe"},
{"id": "B1", "name": "Asset B1", "cell": [ 7, 17], "status": "safe"},
{"id": "B2", "name": "Asset B2", "cell": [ 8, 12], "status": "safe"},
{"id": "C1", "name": "Asset C1", "cell": [17, 7], "status": "safe"},
{"id": "C2", "name": "Asset C2", "cell": [18, 2], "status": "safe"},
]
def _init_crews(self):
self.crews = []
crew_id = 0
for div_idx, (div_label, zone) in enumerate(DIVISIONS.items()):
r_mid = (zone["rows"][0] + zone["rows"][1]) // 2
c_mid = (zone["cols"][0] + zone["cols"][1]) // 2
for offset in [0, 1]:
self.crews.append({
"id": crew_id,
"division": div_idx,
"division_label": div_label,
"cell": [r_mid, c_mid + offset],
"status": "active",
})
crew_id += 1
def _build_fuel_map(self) -> List[List[float]]:
fuel = [[1.0] * self.grid_size for _ in range(self.grid_size)]
for r in range(self.grid_size):
for c in range(self.grid_size):
if r in (9, 10) or c in (9, 10):
fuel[r][c] = 0.5
return fuel
# ------------------------------------------------------------------
# Action handling
# ------------------------------------------------------------------
def _apply_action(self, action: Dict) -> Dict:
try:
div_id = int(action.get("division_id", 0))
crew_id = int(action.get("crew_id", 0))
action_type = str(action.get("action_type", "HOLD")).upper()
target = action.get("target_cell", [0, 0])
r, c = int(target[0]), int(target[1])
except Exception:
return {"error": "Invalid action", "efficiency": 0.0,
"idle": False, "new_mitigation": False}
crew = self._find_crew(div_id, crew_id)
if crew is None:
return {"error": "Crew not found", "efficiency": 0.0,
"idle": False, "new_mitigation": False}
if not (0 <= r < self.grid_size and 0 <= c < self.grid_size):
return {"error": "Out of bounds", "efficiency": 0.0,
"idle": False, "new_mitigation": False}
efficiency = 0.0
idle = False
new_mitigation = False
if action_type == "SUPPRESS":
if self.grid[r][c] == BURNING:
self.grid[r][c] = BURNT
efficiency = 1.0
crew["cell"] = [r, c]
elif action_type in ("FIREBREAK", "SCRATCHLINE"):
eff_map = {"FIREBREAK": 0.5, "SCRATCHLINE": 0.3}
if self.grid[r][c] == CLEAR:
is_new = (r, c) not in self._mitigated_cells
self.grid[r][c] = FIREBREAK
self._mitigated_cells.add((r, c))
efficiency = eff_map[action_type]
new_mitigation = is_new
crew["cell"] = [r, c]
elif action_type == "WETLINE":
if self.grid[r][c] in (CLEAR, BURNING):
is_new = (r, c) not in self._mitigated_cells
self.grid[r][c] = FIREBREAK
self._mitigated_cells.add((r, c))
efficiency = 0.7
new_mitigation = is_new
crew["cell"] = [r, c]
elif action_type == "MOVE":
crew["cell"] = [r, c]
elif action_type == "HOLD":
if self._fire_nearby(crew["cell"]):
idle = True
return {"action": action_type, "efficiency": efficiency,
"idle": idle, "new_mitigation": new_mitigation}
def _find_crew(self, div_id: int, crew_id: int):
div_crews = [c for c in self.crews if c["division"] == div_id]
return div_crews[crew_id] if crew_id < len(div_crews) else None
def _fire_nearby(self, cell: List[int], radius: int = 2) -> bool:
r, c = cell
for dr in range(-radius, radius + 1):
for dc in range(-radius, radius + 1):
nr, nc = r + dr, c + dc
if 0 <= nr < self.grid_size and 0 <= nc < self.grid_size:
if self.grid[nr][nc] == BURNING:
return True
return False
# ------------------------------------------------------------------
# Fire spread (main mitigated sim)
# ------------------------------------------------------------------
def _spread_fire(self):
direction = self.wind["direction"]
speed = self.wind["speed"]
primary = WIND_OFFSETS[direction]
new_grid = copy.deepcopy(self.grid)
for r in range(self.grid_size):
for c in range(self.grid_size):
if self.grid[r][c] == BURNING:
age = self.burn_age.get((r, c), 0) + 1
self.burn_age[(r, c)] = age
burnout = 3 + hash((r, c, self.task)) % 3
if age >= burnout:
new_grid[r][c] = BURNT
self.burn_age.pop((r, c), None)
for dr, dc in ALL_NEIGHBORS:
nr, nc = r + dr, c + dc
if not (0 <= nr < self.grid_size and 0 <= nc < self.grid_size):
continue
if self.grid[nr][nc] != CLEAR:
continue
fuel = self.fuel_map[nr][nc]
prob = speed * 0.35 * fuel
if (dr, dc) == primary:
prob = speed * 0.80 * fuel
if random.random() < prob:
new_grid[nr][nc] = BURNING
self.burn_age[(nr, nc)] = 0
for dr, dc in DIAGONALS:
nr, nc = r + dr, c + dc
if not (0 <= nr < self.grid_size and 0 <= nc < self.grid_size):
continue
if self.grid[nr][nc] != CLEAR:
continue
fuel = self.fuel_map[nr][nc]
if random.random() < speed * 0.15 * fuel:
new_grid[nr][nc] = BURNING
self.burn_age[(nr, nc)] = 0
self.grid = new_grid
# ------------------------------------------------------------------
# Metrics
# ------------------------------------------------------------------
def _count_damaged_sim(self) -> int:
"""Paper Eq 1: Burned + Burning + Mitigated (FIREBREAK) cells."""
return sum(
1 for r in range(self.grid_size)
for c in range(self.grid_size)
if self.grid[r][c] in (BURNING, BURNT, FIREBREAK)
)
def _containment_pct(self) -> float:
burning = sum(
1 for r in range(self.grid_size)
for c in range(self.grid_size)
if self.grid[r][c] == BURNING
)
if burning == 0:
return 1.0
total = sum(
1 for r in range(self.grid_size)
for c in range(self.grid_size)
if self.grid[r][c] in (BURNING, BURNT)
)
return round(1.0 - (burning / max(total, 1)), 4)
def _all_fire_contained(self) -> bool:
return all(
self.grid[r][c] != BURNING
for r in range(self.grid_size)
for c in range(self.grid_size)
)
def _detect_merges(self) -> int:
"""Check actual adjacent boundary cells across all 4 division edges."""
merges = 0
for r in range(0, 10): # A↔B
if self.grid[r][9] == BURNING and self.grid[r][10] == BURNING:
merges += 1; break
for r in range(10, 20): # C↔D
if self.grid[r][9] == BURNING and self.grid[r][10] == BURNING:
merges += 1; break
for c in range(0, 10): # A↔C
if self.grid[9][c] == BURNING and self.grid[10][c] == BURNING:
merges += 1; break
for c in range(10, 20): # B↔D
if self.grid[9][c] == BURNING and self.grid[10][c] == BURNING:
merges += 1; break
return merges