""" 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