Spaces:
Sleeping
Sleeping
File size: 11,051 Bytes
6dcf14b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | """
Baseline agent for the Wildfire ICS environment.
Rewrites vs original:
1. Wind-aware firebreak placement: builds firebreaks AHEAD of fire in wind
direction instead of only suppressing burning cells reactively.
2. Asset-aware triage: prioritises crews protecting assets closest to fire,
not just the division with the most burning cells.
3. Multi-division dispatch: issues one action per burning division per step
(crew 0 = suppress, crew 1 = firebreak ahead of wind). The original
only ever commanded a single crew globally.
4. No more HOLD on empty divisions — crews reposition toward fire.
5. Boundary-first suppression: when no firebreak is possible, suppresses
boundary cells first to stop cross-division spread.
"""
from typing import Dict, Any, List, Optional, Tuple
CLEAR = 0
BURNING = 1
BURNT = 2
FIREBREAK = 3
DIVISIONS = {
0: {"rows": (0, 9), "cols": (0, 9), "label": "A"},
1: {"rows": (0, 9), "cols": (10, 19), "label": "B"},
2: {"rows": (10, 19), "cols": (0, 9), "label": "C"},
3: {"rows": (10, 19), "cols": (10, 19), "label": "D"},
}
# Wind direction → (row_delta, col_delta) for the cell AHEAD of a burning cell
WIND_AHEAD = {
"N": (-1, 0),
"S": ( 1, 0),
"E": ( 0, 1),
"W": ( 0, -1),
}
class BaselineAgent:
"""
Rule-based baseline agent for the Wildfire ICS environment.
Per-step strategy (in priority order):
1. For each burning division, crew 1 places a firebreak on the CLEAR
cell directly ahead of the closest burning cell in wind direction.
2. crew 0 suppresses the boundary-most burning cell in that division
(boundary = closest to another division, to stop spread early).
3. If no firebreak target exists (no clear cell ahead), both crews suppress.
4. Assets close to fire trigger an immediate protective firebreak ring
around the asset regardless of division assignment.
5. If no fire anywhere, reposition toward grid centre.
"""
def __init__(self, env):
self.env = env
# ------------------------------------------------------------------
# Public interface
# ------------------------------------------------------------------
def select_action(self, obs: Dict[str, Any]) -> Dict[str, Any]:
"""
Return ONE action dict for the current observation.
Picks the highest-priority action from all burning divisions.
"""
grid = obs["grid"]
wind_dir = obs.get("wind", {}).get("direction", "N")
assets = obs.get("assets_at_risk", [])
# 1. Check if any asset is in immediate danger (≤3 cells from fire)
asset_action = self._protect_asset(grid, assets, wind_dir)
if asset_action:
return asset_action
# 2. Find all burning divisions sorted by urgency
burning_divs = self._rank_divisions(grid)
if not burning_divs:
# No fire — reposition crew 0 of division 0 toward centre
return {
"division_id": 0,
"crew_id": 0,
"action_type": "MOVE",
"target_cell": [5, 5],
}
# 3. Pick the most urgent division and dispatch
top_div_id, burning_cells = burning_divs[0]
return self._dispatch(top_div_id, burning_cells, grid, wind_dir)
def select_all_actions(self, obs: Dict[str, Any]) -> List[Dict[str, Any]]:
"""
Return one action per burning division (used by multi-crew callers).
Each burning division gets: crew 0 = suppress, crew 1 = firebreak ahead.
"""
grid = obs["grid"]
wind_dir = obs.get("wind", {}).get("direction", "N")
assets = obs.get("assets_at_risk", [])
actions = []
# Asset protection overrides first
asset_action = self._protect_asset(grid, assets, wind_dir)
if asset_action:
actions.append(asset_action)
for div_id, burning_cells in self._rank_divisions(grid):
if not burning_cells:
continue
action = self._dispatch(div_id, burning_cells, grid, wind_dir)
# Avoid duplicate division+crew combos
key = (action["division_id"], action["crew_id"])
if not any((a["division_id"], a["crew_id"]) == key for a in actions):
actions.append(action)
if not actions:
actions.append({
"division_id": 0, "crew_id": 0,
"action_type": "MOVE", "target_cell": [5, 5],
})
return actions
# ------------------------------------------------------------------
# Core dispatch logic
# ------------------------------------------------------------------
def _dispatch(self, div_id: int, burning_cells: List[Tuple[int, int]],
grid: List[List[int]], wind_dir: str) -> Dict[str, Any]:
"""
For a given division:
- crew 0: suppress the boundary-most burning cell
- crew 1: firebreak one cell ahead of wind from nearest burning cell
Returns crew 0 action (boundary suppress) by default; firebreak when
step is odd (alternates between the two crews).
"""
zone = DIVISIONS[div_id]
use_crew_1 = (self.env.timestep % 2 == 1)
if use_crew_1:
# Try to place a firebreak ahead of wind
fb_target = self._firebreak_ahead(burning_cells, grid, wind_dir)
if fb_target:
return {
"division_id": div_id,
"crew_id": 1,
"action_type": "FIREBREAK",
"target_cell": list(fb_target),
}
# Default: suppress boundary-most cell with crew 0
target = self._boundary_cell(burning_cells, zone)
return {
"division_id": div_id,
"crew_id": 0,
"action_type": "SUPPRESS",
"target_cell": list(target),
}
# ------------------------------------------------------------------
# Asset protection
# ------------------------------------------------------------------
def _protect_asset(self, grid: List[List[int]],
assets: List[Dict], wind_dir: str) -> Optional[Dict]:
"""
If any safe asset has a burning cell within 3 steps, place a
firebreak between the fire and the asset (in wind direction).
Returns an action dict or None.
"""
dr, dc = WIND_AHEAD.get(wind_dir, (0, 0))
endangered = []
for asset in assets:
if asset.get("status") != "safe":
continue
ar, ac = asset["cell"]
dist = self._nearest_fire_dist(grid, ar, ac)
if dist <= 3:
endangered.append((dist, asset))
if not endangered:
return None
# Most endangered asset first
endangered.sort(key=lambda x: x[0])
_, asset = endangered[0]
ar, ac = asset["cell"]
# Place firebreak one cell UPWIND of the asset (between fire and asset)
fb_r, fb_c = ar - dr, ac - dc
fb_r = max(0, min(19, fb_r))
fb_c = max(0, min(19, fb_c))
if grid[fb_r][fb_c] == CLEAR:
div_id = self._cell_to_division(ar, ac)
return {
"division_id": div_id,
"crew_id": 1,
"action_type": "FIREBREAK",
"target_cell": [fb_r, fb_c],
}
# Fallback: suppress any burning cell adjacent to asset
for ddr, ddc in [(-1,0),(1,0),(0,-1),(0,1)]:
nr, nc = ar + ddr, ac + ddc
if 0 <= nr < 20 and 0 <= nc < 20 and grid[nr][nc] == BURNING:
div_id = self._cell_to_division(nr, nc)
return {
"division_id": div_id,
"crew_id": 0,
"action_type": "SUPPRESS",
"target_cell": [nr, nc],
}
return None
# ------------------------------------------------------------------
# Wind-aware firebreak placement
# ------------------------------------------------------------------
def _firebreak_ahead(self, burning_cells: List[Tuple[int, int]],
grid: List[List[int]],
wind_dir: str) -> Optional[Tuple[int, int]]:
"""
Find the CLEAR cell directly ahead (in wind direction) of any
burning cell. Returns the first valid target found, or None.
"""
dr, dc = WIND_AHEAD.get(wind_dir, (0, 0))
for br, bc in burning_cells:
nr, nc = br + dr, bc + dc
if 0 <= nr < 20 and 0 <= nc < 20 and grid[nr][nc] == CLEAR:
return (nr, nc)
return None
# ------------------------------------------------------------------
# Division ranking + helpers
# ------------------------------------------------------------------
def _rank_divisions(self, grid: List[List[int]]) -> List[Tuple[int, List]]:
"""
Return list of (div_id, burning_cells) sorted by burning cell count
descending. Only includes divisions that have at least one burning cell.
"""
result = []
for div_id, zone in DIVISIONS.items():
cells = [
(r, c)
for r in range(zone["rows"][0], zone["rows"][1] + 1)
for c in range(zone["cols"][0], zone["cols"][1] + 1)
if grid[r][c] == BURNING
]
if cells:
result.append((div_id, cells))
result.sort(key=lambda x: -len(x[1]))
return result
def _boundary_cell(self, burning_cells: List[Tuple[int, int]],
zone: Dict) -> Tuple[int, int]:
"""
Among burning cells in a division, pick the one closest to a
division boundary (rows 9/10 or cols 9/10). Suppressing boundary
cells first prevents cross-division fire spread.
"""
def boundary_score(cell):
r, c = cell
return min(abs(r - 9), abs(r - 10), abs(c - 9), abs(c - 10))
return min(burning_cells, key=boundary_score)
def _nearest_fire_dist(self, grid: List[List[int]],
r: int, c: int) -> int:
"""Manhattan distance from (r,c) to the nearest BURNING cell."""
min_dist = 999
for rr in range(20):
for cc in range(20):
if grid[rr][cc] == BURNING:
min_dist = min(min_dist, abs(r - rr) + abs(c - cc))
return min_dist
def _cell_to_division(self, r: int, c: int) -> int:
"""Return division id (0-3) for a given grid cell."""
for div_id, zone in DIVISIONS.items():
if (zone["rows"][0] <= r <= zone["rows"][1] and
zone["cols"][0] <= c <= zone["cols"][1]):
return div_id
return 0
|