Create a grid resilience to heatwaves and wildfires simulation framework.
- User
Create a grid resilience to heatwaves and wildfires simulation framework.
Assistant
Create a grid resilience to heatwaves and wildfires simulation framework.
The user wants a grid resilience simulation framework focused on heatwaves and wildfires. This is a complex systems simulation that should model:
Electrical Grid Components:
Heatwave Effects:
Wildfire Effects:
Resilience Metrics:
I'll create a comprehensive simulation with:
Key features to implement:
Let me create a well-structured, comprehensive simulation framework. This is a comprehensive grid resilience simulation framework that models electrical grid behavior under heatwave and wildfire stress conditions. It includes cascading failures, thermal stress modeling, wildfire spread, and resilience metrics.
"""
Grid Resilience Simulation Framework
=====================================
Simulates electrical grid behavior under heatwave and wildfire stress conditions.
Models cascading failures, thermal dynamics, and recovery processes.
Author: Grid Resilience Research Team
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.patches import Circle, FancyArrowPatch
from matplotlib.collections import LineCollection
import networkx as nx
from dataclasses import dataclass, field
from typing import Dict, List, Tuple, Optional, Set
from enum import Enum
import random
from collections import defaultdict
import matplotlib.animation as animation
from matplotlib.colors import LinearSegmentedColormap
import warnings
warnings.filterwarnings('ignore')
# =============================================================================
# ENUMS AND DATA STRUCTURES
# =============================================================================
class ComponentType(Enum):
GENERATOR = "generator"
SUBSTATION = "substation"
TRANSMISSION_LINE = "transmission_line"
DISTRIBUTION_LINE = "distribution_line"
TRANSFORMER = "transformer"
LOAD = "load"
class ComponentStatus(Enum):
OPERATIONAL = "operational"
STRESSED = "stressed"
FAILED = "failed"
ISOLATED = "isolated"
RECOVERING = "recovering"
class EventType(Enum):
HEATWAVE = "heatwave"
WILDFIRE = "wildfire"
NORMAL = "normal"
@dataclass
class GridComponent:
"""Represents a component in the electrical grid."""
id: str
component_type: ComponentType
location: Tuple[float, float]
capacity: float # MW
current_load: float = 0.0 # MW
status: ComponentStatus = ComponentStatus.OPERATIONAL
age: float = 10.0 # years
criticality: float = 1.0 # importance weight
# Thermal parameters
max_temperature: float = 100.0 # °C
current_temperature: float = 40.0 # °C
thermal_time_constant: float = 1.0 # hours
# Reliability parameters
base_failure_rate: float = 0.001 # failures/hour
repair_time: float = 24.0 # hours
# Status tracking
failed_at: Optional[float] = None
recovery_progress: float = 0.0
@dataclass
class TransmissionLine:
"""Represents a transmission or distribution line."""
id: str
source: str
target: str
capacity: float # MW
length: float # km
voltage_level: float # kV
status: ComponentStatus = ComponentStatus.OPERATIONAL
current_flow: float = 0.0
max_temperature: float = 80.0
current_temperature: float = 30.0
sag_factor: float = 1.0
base_failure_rate: float = 0.002
repair_time: float = 12.0
failed_at: Optional[float] = None
@dataclass
class Wildfire:
"""Represents a wildfire event."""
id: str
origin: Tuple[float, float]
start_time: float
intensity: float # 0-1 scale
spread_rate: float # km/hour
radius: float = 0.0 # current radius in km
wind_direction: float = 0.0 # degrees
wind_speed: float = 20.0 # km/h
containment: float = 0.0 # 0-1 containment level
@dataclass
class Heatwave:
"""Represents a heatwave event."""
start_time: float
duration: float # hours
max_temperature: float # °C
affected_area: Tuple[float, float, float, float] # (x_min, y_min, x_max, y_max)
current_temperature: float = 0.0
humidity: float = 0.3 # relative humidity 0-1
@dataclass
class SimulationState:
"""Stores the current state of the simulation."""
time: float = 0.0
total_demand: float = 0.0
total_generation: float = 0.0
customers_affected: int = 0
active_failures: int = 0
recovered_components: int = 0
economic_loss: float = 0.0
# =============================================================================
# GRID MODEL
# =============================================================================
class GridModel:
"""
Represents the electrical grid topology and state.
Uses NetworkX for graph operations.
"""
def __init__(self, name: str = "Test Grid"):
self.name = name
self.graph = nx.Graph()
self.components: Dict[str, GridComponent] = {}
self.lines: Dict[str, TransmissionLine] = {}
self.loads: Dict[str, float] = {}
self.generators: Dict[str, float] = {}
# Simulation parameters
self.base_demand_multiplier = 1.0
self.frequency = 60.0 # Hz
def add_component(self, component: GridComponent):
"""Add a component (node) to the grid."""
self.graph.add_node(component.id,
component_type=component.component_type,
pos=component.location)
self.components[component.id] = component
if component.component_type == ComponentType.GENERATOR:
self.generators[component.id] = component.capacity
elif component.component_type == ComponentType.LOAD:
self.loads[component.id] = component.capacity
def add_line(self, line: TransmissionLine):
"""Add a transmission line (edge) to the grid."""
self.graph.add_edge(line.source, line.target,
line_id=line.id,
capacity=line.capacity)
self.lines[line.id] = line
def get_connected_components(self, component_id: str) -> Set[str]:
"""Get all components connected to a given component."""
if component_id in self.graph:
return set(self.graph.neighbors(component_id))
return set()
def get_islanded_components(self) -> Set[str]:
"""Find components that are disconnected from generators."""
islanded = set()
# Find all generator nodes
generators = [c.id for c in self.components.values()
if c.component_type == ComponentType.GENERATOR
and c.status == ComponentStatus.OPERATIONAL]
if not generators:
return set(self.components.keys())
# BFS from each generator to find connected nodes
connected = set()
for gen in generators:
if gen in self.graph:
connected.update(nx.single_source_shortest_path_length(self.graph, gen).keys())
# Find disconnected nodes
for comp_id in self.components:
if comp_id not in connected:
islanded.add(comp_id)
return islanded
def calculate_power_flow(self) -> Dict[str, float]:
"""
Simple DC power flow approximation.
Returns power flows on each line.
"""
flows = {}
# Simple proportional flow based on capacity
total_gen = sum(g.capacity for g in self.components.values()
if g.component_type == ComponentType.GENERATOR
and g.status == ComponentStatus.OPERATIONAL)
total_load = sum(l.capacity for l in self.components.values()
if l.component_type == ComponentType.LOAD
and l.status == ComponentStatus.OPERATIONAL)
if total_gen == 0:
return flows
supply_ratio = min(1.0, total_gen / max(total_load, 0.1))
for line_id, line in self.lines.items():
if line.status == ComponentStatus.OPERATIONAL:
# Simple flow estimation
flows[line_id] = min(line.capacity, total_load * 0.3) * supply_ratio
else:
flows[line_id] = 0.0
return flows
# =============================================================================
# RESILIENCE SIMULATOR
# =============================================================================
class GridResilienceSimulator:
"""
Main simulation engine for grid resilience analysis.
"""
def __init__(self, grid: GridModel):
self.grid = grid
self.time = 0.0
self.dt = 0.25 # time step in hours
# Event tracking
self.wildfires: List[Wildfire] = []
self.heatwaves: List[Heatwave] = []
# State tracking
self.state = SimulationState()
self.history: List[SimulationState] = []
self.failure_log: List[Dict] = []
# Ambient conditions
self.ambient_temperature = 25.0 # °C
# Metrics
self.total_customers = 100000
self.price_per_mwh = 150.0 # $/MWh
def set_ambient_temperature(self, temp: float):
"""Set ambient temperature."""
self.ambient_temperature = temp
def add_wildfire(self, wildfire: Wildfire):
"""Add a wildfire event to the simulation."""
self.wildfires.append(wildfire)
def add_heatwave(self, heatwave: Heatwave):
"""Add a heatwave event to the simulation."""
self.heatwaves.append(heatwave)
def calculate_heatwave_temperature(self, component: GridComponent) -> float:
"""Calculate temperature at component location due to heatwaves."""
temp = self.ambient_temperature
for hw in self.heatwaves:
if hw.start_time <= self.time <= hw.start_time + hw.duration:
x_min, y_min, x_max, y_max = hw.affected_area
x, y = component.location
if x_min <= x <= x_max and y_min <= y <= y_max:
# Heat intensity varies with time (bell curve)
progress = (self.time - hw.start_time) / hw.duration
intensity_factor = np.sin(progress * np.pi) # Peaks at middle
temp_increase = (hw.max_temperature - self.ambient_temperature) * intensity_factor
temp = max(temp, self.ambient_temperature + temp_increase)
return temp
def calculate_wildfire_risk(self, component: GridComponent) -> float:
"""Calculate wildfire risk for a component (0-1)."""
risk = 0.0
for wf in self.wildfires:
if wf.containment >= 1.0:
continue
# Calculate distance from fire
dx = component.location[0] - wf.origin[0]
dy = component.location[1] - wf.origin[1]
distance = np.sqrt(dx**2 + dy**2)
# Update fire radius based on spread rate
fire_radius = wf.radius + wf.spread_rate * (self.time - wf.start_time)
fire_radius *= (1.0 - wf.containment)
if distance < fire_radius:
# Inside fire zone
risk = max(risk, wf.intensity)
elif distance < fire_radius + 5: # 5km buffer
# Near fire zone
buffer_risk = wf.intensity * (1.0 - (distance - fire_radius) / 5.0)
risk = max(risk, buffer_risk)
return risk
def calculate_line_temperature(self, line: TransmissionLine,
ambient_temp: float, power_flow: float) -> float:
"""Calculate transmission line temperature."""
# Heat balance: solar + resistive heating - convection - radiation
# Simplified model
source_comp = self.grid.components.get(line.source)
target_comp = self.grid.components.get(line.target)
if not source_comp or not target_comp:
return ambient_temp
# Get ambient temperature (might be affected by heatwave)
avg_ambient = ambient_temp
# Resistive heating (I^2 * R losses converted to heat)
loading_ratio = power_flow / max(line.capacity, 0.1)
resistive_heat = 40.0 * loading_ratio**2 # Up to 40°C increase at full load
# Solar heating (simplified)
solar_heat = 10.0 # Assume daytime
# Line temperature
line_temp = avg_ambient + resistive_heat + solar_heat
# Apply thermal time constant for gradual change
target_temp = line_temp
line.current_temperature += (target_temp - line.current_temperature) * self.dt / line.thermal_time_constant if hasattr(line, 'thermal_time_constant') else (target_temp - line.current_temperature) * 0.1
return line.current_temperature
def calculate_failure_probability(self, component: GridComponent,
stress_factor: float = 1.0) -> float:
"""
Calculate failure probability for a component.
Factors:
- Base failure rate
- Temperature stress
- Age degradation
- Loading stress
- Wildfire risk
"""
# Base rate
prob = component.base_failure_rate * self.dt
# Temperature stress (Arrhenius-like acceleration)
if component.current_temperature > component.max_temperature * 0.7:
temp_ratio = component.current_temperature / component.max_temperature
temp_factor = np.exp(5.0 * (temp_ratio - 0.7))
prob *= temp_factor
# Loading stress
if component.capacity > 0:
load_ratio = component.current_load / component.capacity
if load_ratio > 0.8:
prob *= 1.0 + 5.0 * (load_ratio - 0.8)**2
# Age factor
age_factor = 1.0 + 0.02 * component.age
prob *= age_factor
# Wildfire risk
wildfire_risk = self.calculate_wildfire_risk(component)
prob += wildfire_risk * 0.1 # High risk during fire
# Heatwave stress
heatwave_temp = self.calculate_heatwave_temperature(component)
if heatwave_temp > 35:
heat_factor = 1.0 + 0.1 * (heatwave_temp - 35)
prob *= heat_factor
# Apply general stress factor
prob *= stress_factor
# Criticality affects maintenance priority (lower failure for critical components)
prob /= component.criticality
return min(prob, 0.5) # Cap at 50% per timestep
def calculate_line_failure_probability(self, line: TransmissionLine,
ambient_temp: float,
power_flow: float) -> float:
"""Calculate failure probability for a transmission line."""
prob = line.base_failure_rate * self.dt
# Temperature stress
line_temp = self.calculate_line_temperature(line, ambient_temp, power_flow)
if line_temp > line.max_temperature * 0.8:
temp_ratio = line_temp / line.max_temperature
temp_factor = np.exp(8.0 * (temp_ratio - 0.8))
prob *= temp_factor
# Sag-induced failures (line touches vegetation)
if line_temp > 50:
sag_risk = (line_temp - 50) / 30.0 * 0.01
prob += sag_risk
# Loading stress
if line.capacity > 0:
load_ratio = power_flow / line.capacity
if load_ratio > 0.9:
prob *= 1.0 + 10.0 * (load_ratio - 0.9)**2
# Wildfire risk for line path
source_comp = self.grid.components.get(line.source)
target_comp = self.grid.components.get(line.target)
if source_comp and target_comp:
wildfire_risk = max(
self.calculate_wildfire_risk(source_comp),
self.calculate_wildfire_risk(target_comp)
)
prob += wildfire_risk * 0.15
return min(prob, 0.3)
def process_failures(self):
"""Process component and line failures."""
flows = self.grid.calculate_power_flow()
# Check component failures
for comp_id, component in self.grid.components.items():
if component.status == ComponentStatus.OPERATIONAL:
# Calculate temperature
component.current_temperature = self.calculate_heatwave_temperature(component)
# Calculate failure probability
fail_prob = self.calculate_failure_probability(component)
if random.random() < fail_prob:
self._fail_component(comp_id, "thermal_overload")
# Check line failures
for line_id, line in self.grid.lines.items():
if line.status == ComponentStatus.OPERATIONAL:
flow = flows.get(line_id, 0.0)
fail_prob = self.calculate_line_failure_probability(
line, self.ambient_temperature, flow
)
if random.random() < fail_prob:
self._fail_line(line_id, "thermal_sag")
def _fail_component(self, comp_id: str, cause: str):
"""Handle component failure."""
component = self.grid.components[comp_id]
component.status = ComponentStatus.FAILED
component.failed_at = self.time
# Log failure
self.failure_log.append({
'time': self.time,
'component_id': comp_id,
'type': 'component',
'cause': cause,
'temperature': component.current_temperature
})
# Remove from graph temporarily
if comp_id in self.grid.graph:
# Store edges before removing
neighbors = list(self.grid.graph.neighbors(comp_id))
self.grid.graph.remove_node(comp_id)
# Re-add without edges (isolated)
self.grid.graph.add_node(comp_id)
# Check for cascading effects
self._check_cascading_effects(comp_id)
def _fail_line(self, line_id: str, cause: str):
"""Handle transmission line failure."""
line = self.lines[line_id]
line.status = ComponentStatus.FAILED
line.failed_at = self.time
# Remove edge from graph
if self.grid.graph.has_edge(line.source, line.target):
self.grid.graph.remove_edge(line.source, line.target)
# Log failure
self.failure_log.append({
'time': self.time,
'line_id': line_id,
'type': 'line',
'cause': cause,
'flow': line.current_flow
})
# Check for islanding
self._check_islanding()
def _check_cascading_effects(self, failed_comp_id: str):
"""Check for cascading failure effects."""
# When a generator fails, loads may try to draw from remaining generators
# This can cause overloading
component = self.grid.components[failed_comp_id]
if component.component_type == ComponentType.GENERATOR:
# Redistribute load to other generators
remaining_capacity = sum(
g.capacity for g in self.grid.components.values()
if g.component_type == ComponentType.GENERATOR
and g.status == ComponentStatus.OPERATIONAL
)
if remaining_capacity > 0:
# Increase load on remaining generators
for gen in self.grid.components.values():
if (gen.component_type == ComponentType.GENERATOR and
gen.status == ComponentStatus.OPERATIONAL):
gen.current_load = min(gen.capacity * 1.1, gen.capacity)
def _check_islanding(self):
"""Check and handle islanded components."""
islanded = self.grid.get_islanded_components()
for comp_id in islanded:
component = self.grid.components[comp_id]
if component.status == ComponentStatus.OPERATIONAL:
component.status = ComponentStatus.ISOLATED
def process_recovery(self):
"""Process component recovery."""
for comp_id, component in self.grid.components.items():
if component.status == ComponentStatus.FAILED:
# Check if repair time has elapsed
if component.failed_at is not None:
time_failed = self.time - component.failed_at
if time_failed >= component.repair_time:
component.status = ComponentStatus.OPERATIONAL
component.failed_at = None
component.current_temperature = self.ambient_temperature
self.state.recovered_components += 1
# Reconnect to graph
# (In real implementation, would restore connections)
for line_id, line in self.grid.lines.items():
if line.status == ComponentStatus.FAILED:
if line.failed_at is not None:
time_failed = self.time - line.failed_at
if time_failed >= line.repair_time:
line.status = ComponentStatus.OPERATIONAL
line.failed_at = None
line.current_temperature = self.ambient_temperature
# Reconnect edge
self.grid.graph.add_edge(line.source, line.target,
line_id=line_id,
capacity=line.capacity)
def update_wildfires(self):
"""Update wildfire states."""
for wf in self.wildfires:
# Fire spread
elapsed = self.time - wf.start_time
if elapsed > 0:
# Spread rate affected by containment
effective_spread = wf.spread_rate * (1.0 - wf.containment)
wf.radius = effective_spread * elapsed
# Containment increases over time (firefighting)
wf.containment = min(1.0, wf.containment + 0.01 * self.dt)
def update_heatwaves(self):
"""Update heatwave states."""
for hw in self.heatwaves:
if hw.start_time <= self.time <= hw.start_time + hw.duration:
progress = (self.time - hw.start_time) / hw.duration
hw.current_temperature = hw.max_temperature * np.sin(progress * np.pi)
def update_demand(self):
"""Update power demand based on conditions."""
# Base demand
base_demand = sum(self.grid.loads.values())
# Heatwave increases demand (AC usage)
demand_multiplier = 1.0
for hw in self.heatwaves:
if hw.start_time <= self.time <= hw.start_time + hw.duration:
demand_multiplier += 0.3 * (hw.current_temperature / hw.max_temperature)
# Wildfire may decrease demand in affected areas (evacuation)
for wf in self.wildfires:
if wf.containment < 0.5:
demand_multiplier *= 0.95 # 5% reduction per major fire
self.grid.base_demand_multiplier = demand_multiplier
self.state.total_demand = base_demand * demand_multiplier
def calculate_metrics(self):
"""Calculate resilience metrics."""
# Count operational components
operational_gens = sum(1 for c in self.grid.components.values()
if c.component_type == ComponentType.GENERATOR
and c.status == ComponentStatus.OPERATIONAL)
# Calculate available generation
self.state.total_generation = sum(
c.capacity for c in self.grid.components.values()
if c.component_type == ComponentType.GENERATOR
and c.status == ComponentStatus.OPERATIONAL
)
# Calculate customers affected
failed_loads = sum(1 for c in self.grid.components.values()
if c.component_type == ComponentType.LOAD
and c.status in [ComponentStatus.FAILED, ComponentStatus.ISOLATED])
total_loads = len([c for c in self.grid.components.values()
if c.component_type == ComponentType.LOAD])
if total_loads > 0:
self.state.customers_affected = int(
self.total_customers * failed_loads / total_loads
)
# Count active failures
self.state.active_failures = sum(
1 for c in self.grid.components.values()
if c.status == ComponentStatus.FAILED
) + sum(1 for l in self.grid.lines.values()
if l.status == ComponentStatus.FAILED)
# Economic loss calculation
unmet_demand = max(0, self.state.total_demand - self.state.total_generation)
self.state.economic_loss += unmet_demand * self.dt * self.price_per_mwh
def step(self):
"""Execute one simulation time step."""
self.time += self.dt
self.state.time = self.time
# Update environmental conditions
self.update_wildfires()
self.update_heatwaves()
# Update demand
self.update_demand()
# Process failures
self.process_failures()
# Process recovery
self.process_recovery()
# Calculate metrics
self.calculate_metrics()
# Store history
self.history.append(SimulationState(
time=self.state.time,
total_demand=self.state.total_demand,
total_generation=self.state.total_generation,
customers_affected=self.state.customers_affected,
active_failures=self.state.active_failures,
recovered_components=self.state.recovered_components,
economic_loss=self.state.economic_loss
))
def run(self, duration: float) -> List[SimulationState]:
"""Run simulation for specified duration."""
steps = int(duration / self.dt)
for _ in range(steps):
self.step()
return self.history
# =============================================================================
# GRID BUILDER
# =============================================================================
def create_test_grid() -> GridModel:
"""Create a realistic test grid network."""
grid = GridModel("Regional Power Grid")
# Generators
generators = [
("G1", ComponentType.GENERATOR, (10, 80), 500, 0.001, 5),
("G2", ComponentType.GENERATOR, (90, 85), 400, 0.001, 8),
("G3", ComponentType.GENERATOR, (50, 20), 300, 0.0015, 15),
("G4", ComponentType.GENERATOR, (150, 50), 200, 0.002, 20),
]
for gid, gtype, loc, cap, fail_rate, age in generators:
comp = GridComponent(
id=gid, component_type=gtype, location=loc,
capacity=cap, base_failure_rate=fail_rate, age=age,
criticality=1.5 # Generators are critical
)
grid.add_component(comp)
# Substations
substations = [
("S1", (20, 65), 400, 0.0005, 12),
("S2", (40, 70), 350, 0.0005, 10),
("S3", (70, 60), 400, 0.0006, 8),
("S4", (30, 45), 300, 0.0005, 15),
("S5", (60, 40), 350, 0.0006, 12),
("S6", (100, 55), 300, 0.0007, 18),
("S7", (130, 40), 250, 0.0008, 22),
]
for sid, loc, cap, fail_rate, age in substations:
comp = GridComponent(
id=sid, component_type=ComponentType.SUBSTATION,
location=loc, capacity=cap, base_failure_rate=fail_rate, age=age
)
grid.add_component(comp)
# Load centers
loads = [
("L1", (15, 50), 150, 0.0008, 5),
("L2", (35, 55), 200, 0.0008, 7),
("L3", (55, 50), 180, 0.0009, 6),
("L4", (25, 30), 120, 0.001, 10),
("L5", (50, 35), 160, 0.0009, 8),
("L6", (75, 45), 140, 0.001, 12),
("L7", (95, 35), 100, 0.0012, 15),
("L8", (120, 30), 80, 0.0015, 20),
("L9", (140, 45), 90, 0.0013, 18),
]
for lid, loc, cap, fail_rate, age in loads:
comp = GridComponent(
id=lid, component_type=ComponentType.LOAD,
location=loc, capacity=cap, base_failure_rate=fail_rate, age=age
)
grid.add_component(comp)
# Transmission lines
lines = [
# From generators
("TL_G1_S1", "G1", "S1", 500, 15, 230),
("TL_G1_S4", "G1", "S4", 300, 25, 138),
("TL_G2_S3", "G2", "S3", 400, 20, 230),
("TL_G3_S5", "G3", "S5", 300, 18, 138),
("TL_G4_S7", "G4", "S7", 200, 22, 138),
# Between substations
("TL_S1_S2", "S1", "S2", 350, 22, 138),
("TL_S2_S3", "S2", "S3", 350, 35, 138),
("TL_S1_S4", "S1", "S4", 300, 25, 138),
("TL_S2_S5", "S2", "S5", 300, 30, 138),
("TL_S3_S6", "S3", "S6", 300, 28, 138),
("TL_S4_S5", "S4", "S5", 250, 20, 69),
("TL_S5_S6", "S5", "S6", 250, 32, 69),
("TL_S6_S7", "S6", "S7", 200, 35, 69),
# To loads
("DL_S1_L1", "S1", "L1", 150, 18, 13.8),
("DL_S2_L2", "S2", "L2", 200, 15, 13.8),
("DL_S3_L3", "S3", "L3", 180, 12, 13.8),
("DL_S4_L4", "S4", "L4", 120, 20, 13.8),
("DL_S5_L5", "S5", "L5", 160, 10, 13.8),
("DL_S6_L6", "S6", "L6", 140, 18, 13.8),
("DL_S5_L7", "S5", "L7", 100, 25, 13.8),
("DL_S7_L8", "S7", "L8", 80, 15, 13.8),
("DL_S7_L9", "S7", "L9", 90, 12, 13.8),
]
for lid, src, tgt, cap, length, voltage in lines:
line = TransmissionLine(
id=lid, source=src, target=tgt,
capacity=cap, length=length, voltage_level=voltage,
base_failure_rate=0.001 if voltage >= 138 else 0.002,
repair_time=8 if voltage >= 138 else 4
)
grid.add_line(line)
return grid
# =============================================================================
# VISUALIZATION
# =============================================================================
class GridVisualizer:
"""Visualization class for grid resilience simulation."""
def __init__(self, grid: GridModel, simulator: GridResilienceSimulator):
self.grid = grid
self.simulator = simulator
# Color schemes
self.status_colors = {
ComponentStatus.OPERATIONAL: '#2ecc71',
ComponentStatus.STRESSED: '#f39c12',
ComponentStatus.FAILED: '#e74c3c',
ComponentStatus.ISOLATED: '#9b59b6',
ComponentStatus.RECOVERING: '#3498db'
}
self.component_colors = {
ComponentType.GENERATOR: '#27ae60',
ComponentType.SUBSTATION: '#3498db',
ComponentType.LOAD: '#e67e22',
ComponentType.TRANSFORMER: '#9b59b6'
}
def create_dashboard(self, history: List[SimulationState]):
"""Create comprehensive simulation dashboard."""
fig = plt.figure(figsize=(16, 12))
fig.suptitle('Grid Resilience to Heatwaves and Wildfires - Simulation Dashboard',
fontsize=14, fontweight='bold')
# Create grid layout
gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3)
# Grid topology (large, left side)
ax_grid = fig.add_subplot(gs[0:2, 0:2])
self._draw_grid_topology(ax_grid)
# Power balance
ax_power = fig.add_subplot(gs[0, 2])
self._draw_power_balance(ax_power, history)
# Failures over time
ax_failures = fig.add_subplot(gs[1, 2])
self._draw_failure_history(ax_failures, history)
# Customers affected
ax_customers = fig.add_subplot(gs[2, 0])
self._draw_customers_affected(ax_customers, history)
# Economic impact
ax_economic = fig.add_subplot(gs[2, 1])
self._draw_economic_impact(ax_economic, history)
# Event timeline
ax_timeline = fig.add_subplot(gs[2, 2])
self._draw_event_timeline(ax_timeline, history)
plt.tight_layout()
return fig
def _draw_grid_topology(self, ax):
"""Draw the grid topology with current status."""
ax.set_title('Grid Topology', fontsize=11, fontweight='bold')
# Draw transmission lines
for line_id, line in self.grid.lines.items():
src = self.grid.components.get(line.source)
tgt = self.grid.components.get(line.target)
if src and tgt:
color = self.status_colors.get(line.status, '#95a5a6')
linewidth = 2 if line.voltage_level >= 138 else 1
linestyle = '-' if line.status == ComponentStatus.OPERATIONAL else '--'
ax.plot([src.location[0], tgt.location[0]],
[src.location[1], tgt.location[1]],
color=color, linewidth=linewidth, linestyle=linestyle,
alpha=0.7)
# Draw wildfires
for wf in self.simulator.wildfires:
if wf.containment < 1.0:
fire_radius = wf.radius + wf.spread_rate * (self.simulator.time - wf.start_time)
fire_radius *= (1.0 - wf.containment)
circle = Circle(wf.origin, fire_radius,
color='#e74c3c', alpha=0.3)
ax.add_patch(circle)
# Fire origin marker
ax.plot(wf.origin[0], wf.origin[1], 'r*', markersize=15)
ax.annotate(f'Fire\n{wf.id}', wf.origin,
textcoords='offset points', xytext=(5, 5),
fontsize=8, color='red')
# Draw heatwave zones
for hw in self.simulator.heatwaves:
if hw.start_time <= self.simulator.time <= hw.start_time + hw.duration:
x_min, y_min, x_max, y_max = hw.affected_area
rect = plt.Rectangle((x_min, y_min), x_max - x_min, y_max - y_min,
linewidth=2, edgecolor='orange',
facecolor='yellow', alpha=0.2)
ax.add_patch(rect)
ax.annotate(f'Heatwave\n{hw.current_temperature:.0f}°C',
((x_min + x_max)/2, (y_min + y_max)/2),
ha='center', fontsize=9, color='orange',
fontweight='bold')
# Draw components
for comp_id, component in self.grid.components.items():
x, y = component.location
color = self.component_colors.get(component.component_type, '#95a5a6')
if component.status != ComponentStatus.OPERATIONAL:
color = self.status_colors.get(component.status, color)
# Different markers for different types
if component.component_type == ComponentType.GENERATOR:
marker = 's' # Square
size = 200
elif component.component_type == ComponentType.SUBSTATION:
marker = 'o' # Circle
size = 150
else: # Load
marker = '^' # Triangle
size = 120
ax.scatter(x, y, c=color, s=size, marker=marker,
edgecolors='black', linewidths=1, zorder=5)
# Add label
ax.annotate(comp_id, (x, y), textcoords='offset points',
xytext=(5, 5), fontsize=8)
# Add temperature if high
if component.current_temperature > 40:
ax.annotate(f'{component.current_temperature:.0f}°C',
(x, y), textcoords='offset points',
xytext=(5, -10), fontsize=7, color='red')
# Legend
legend_elements = [
plt.Line2D([0], [0], marker='s', color='w', markerfacecolor='#27ae60',
markersize=10, label='Generator'),
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#3498db',
markersize=10, label='Substation'),
plt.Line2D([0], [0], marker='^', color='w', markerfacecolor='#e67e22',
markersize=10, label='Load'),
plt.Line2D([0], [0], marker='*', color='w', markerfacecolor='red',
markersize=12, label='Wildfire'),
mpatches.Patch(color='yellow', alpha=0.3, label='Heatwave Zone'),
]
ax.legend(handles=legend_elements, loc='upper left', fontsize=8)
ax.set_xlim(-5, 165)
ax.set_ylim(10, 95)
ax.set_xlabel('X (km)')
ax.set_ylabel('Y (km)')
ax.grid(True, alpha=0.3)
def _draw_power_balance(self, ax, history):
"""Draw power generation vs demand."""
times = [h.time for h in history]
demand = [h.total_demand for h in history]
generation = [h.total_generation for h in history]
ax.fill_between(times, demand, alpha=0.3, color='red', label='Demand')
ax.fill_between(times, generation, alpha=0.3, color='green', label='Generation')
ax.plot(times, demand, 'r-', linewidth=2)
ax.plot(times, generation, 'g-', linewidth=2)
ax.set_title('Power Balance (MW)', fontsize=10, fontweight='bold')
ax.set_xlabel('Time (hours)')
ax.legend(fontsize=8)
ax.grid(True, alpha=0.3)
def _draw_failure_history(self, ax, history):
"""Draw active failures over time."""
times = [h.time for h in history]
failures = [h.active_failures for h in history]
colors = ['#e74c3c' if f > 0 else '#2ecc71' for f in failures]
ax.bar(times, failures, width=0.2, color=colors, alpha=0.7)
ax.plot(times, failures, 'k-', linewidth=1)
ax.set_title('Active Component Failures', fontsize=10, fontweight='bold')
ax.set_xlabel('Time (hours)')
ax.set_ylabel('Count')
ax.grid(True, alpha=0.3)
def _draw_customers_affected(self, ax, history):
"""Draw customers affected over time."""
times = [h.time for h in history]
customers = [h.customers_affected for h in history]
ax.fill_between(times, customers, alpha=0.5, color='#e74c3c')
ax.plot(times, customers, 'r-', linewidth=2)
ax.set_title('Customers Affected', fontsize=10, fontweight='bold')
ax.set_xlabel('Time (hours)')
ax.set_ylabel('Customers')
ax.grid(True, alpha=0.3)
def _draw_economic_impact(self, ax, history):
"""Draw cumulative economic loss."""
times = [h.time for h in history]
losses = [h.economic_loss for h in history]
ax.fill_between(times, losses, alpha=0.5, color='#f39c12')
ax.plot(times, losses, color='#d35400', linewidth=2)
ax.set_title('Cumulative Economic Loss ($)', fontsize=10, fontweight='bold')
ax.set_xlabel('Time (hours)')
ax.ticklabel_format(style='plain', axis='y')
ax.grid(True, alpha=0.3)
def _draw_event_timeline(self, ax, history):
"""Draw event timeline."""
ax.set_title('Event Timeline', fontsize=10, fontweight='bold')
y_pos = 0.5
# Draw heatwave events
for i, hw in enumerate(self.simulator.heatwaves):
ax.barh(y_pos + 0.2, hw.duration, left=hw.start_time,
height=0.15, color='orange', alpha=0.7, label='Heatwave' if i == 0 else '')
ax.text(hw.start_time + hw.duration/2, y_pos + 0.2,
f'{hw.max_temperature}°C', ha='center', va='center', fontsize=8)
# Draw wildfire events
for i, wf in enumerate(self.simulator.wildfires):
duration = max(0, self.simulator.time - wf.start_time)
ax.barh(y_pos - 0.2, duration, left=wf.start_time,
height=0.15, color='red', alpha=0.7, label='Wildfire' if i == 0 else '')
ax.text(wf.start_time + 2, y_pos - 0.2,
wf.id, ha='left', va='center', fontsize=8)
# Draw failure events
failure_times = [f['time'] for f in self.simulator.failure_log]
for ft in failure_times:
ax.axvline(x=ft, color='black', linestyle='--', alpha=0.5, linewidth=0.5)
ax.set_xlabel('Time (hours)')
ax.set_yticks([0.3, 0.7])
ax.set_yticklabels(['Wildfire', 'Heatwave'])
ax.set_xlim(0, max(h.time for h in history) if history else 24)
ax.grid(True, alpha=0.3, axis='x')
def run_simulation():
"""Run the complete grid resilience simulation."""
print("="*60)
print("GRID RESILIENCE TO HEATWAVES AND WILDFIRES SIMULATION")
print("="*60)
# Create grid
print("\n[1/5] Creating grid network...")
grid = create_test_grid()
print(f" - {len(grid.components)} components")
print(f" - {len(grid.lines)} transmission lines")
# Create simulator
print("\n[2/5] Initializing simulator...")
simulator = GridResilienceSimulator(grid)
simulator.total_customers = 100000
# Add heatwave event
print("\n[3/5] Adding weather events...")
heatwave = Heatwave(
start_time=8.0, # Starts at hour 8
duration=12.0, # Lasts 12 hours
max_temperature=45.0, # Peak 45°C
affected_area=(0, 20, 100, 90), # Covers most of the grid
humidity=0.2
)
simulator.add_heatwave(heatwave)
print(" - Heatwave: 8h-20h, peak 45°C")
# Add wildfire event
wildfire = Wildfire(
id="WF-001",
origin=(60, 45), # Near the center of the grid
start_time=12.0, # Starts at hour 12
intensity=0.8,
spread_rate=3.0, # 3 km/hour
wind_direction=45, # NE direction
wind_speed=25.0
)
simulator.add_wildfire(wildfire)
print(" - Wildfire WF-001: starts hour 12, 3 km/h spread")
# Run simulation
print("\n[4/5] Running simulation (48 hours)...")
simulator.run(48.0)
# Print results
print("\n[5/5] Simulation Results:")
print("-" * 40)
final_state = simulator.history[-1]
print(f" Total duration: {final_state.time:.1f} hours")
print(f" Peak customers affected: {max(h.customers_affected for h in simulator.history):,}")
print(f" Total component failures: {len(simulator.failure_log)}")
print(f" Components recovered: {final_state.recovered_components}")
print(f" Total economic loss: ${final_state.economic_loss:,.0f}")
# Failure breakdown
if simulator.failure_log:
print("\n Failure Breakdown:")
causes = defaultdict(int)
for f in simulator.failure_log:
causes[f['cause']] += 1
for cause, count in causes.items():
print(f" - {cause}: {count}")
# Create visualization
print("\n[6/6] Generating dashboard...")
visualizer = GridVisualizer(grid, simulator)
fig = visualizer.create_dashboard(simulator.history)
# Additional analysis plots
create_analysis_plots(simulator)
plt.show()
return grid, simulator
def create_analysis_plots(simulator: GridResilienceSimulator):
"""Create additional analysis plots."""
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
fig.suptitle('Resilience Analysis', fontsize=14, fontweight='bold')
# Temperature vs Failures
ax1 = axes[0, 0]
times = [h.time for h in simulator.history]
# Get temperature data
temps = []
for t in times:
max_temp = simulator.ambient_temperature
for hw in simulator.heatwaves:
if hw.start_time <= t <= hw.start_time + hw.duration:
progress = (t - hw.start_time) / hw.duration
hw_temp = hw.max_temperature * np.sin(progress * np.pi)
max_temp = max(max_temp, simulator.ambient_temperature + hw_temp)
temps.append(max_temp)
failures = [h.active_failures for h in simulator.history]
ax1_twin = ax1.twinx()
ax1.plot(times, temps, 'r-', linewidth=2, label='Temperature')
ax1_twin.bar(times, failures, width=0.3, alpha=0.5, color='blue', label='Failures')
ax1.set_xlabel('Time (hours)')
ax1.set_ylabel('Temperature (°C)', color='red')
ax1_twin.set_ylabel('Active Failures', color='blue')
ax1.set_title('Temperature vs Component Failures')
ax1.grid(True, alpha=0.3)
# Recovery rate
ax2 = axes[0, 1]
recovered = [h.recovered_components for h in simulator.history]
cumulative_failures = []
total = 0
for f in simulator.failure_log:
total += 1
for h in simulator.history:
cumulative_failures.append(len([f for f in simulator.failure_log if f['time'] <= h.time]))
ax2.plot(times, cumulative_failures, 'r-', linewidth=2, label='Total Failures')
ax2.plot(times, recovered, 'g-', linewidth=2, label='Recovered')
ax2.fill_between(times, cumulative_failures, recovered, alpha=0.3, color='red', label='Unrecovered')
ax2.set_xlabel('Time (hours)')
ax2.set_ylabel('Component Count')
ax2.set_title('Failure and Recovery Timeline')
ax2.legend()
ax2.grid(True, alpha=0.3)
# Grid resilience index
ax3 = axes[1, 0]
resilience_index = []
for h in simulator.history:
if h.total_demand > 0:
ri = min(1.0, h.total_generation / h.total_demand) * (1 - h.customers_affected / simulator.total_customers)
else:
ri = 1.0
resilience_index.append(ri)
ax3.fill_between(times, resilience_index, alpha=0.5, color='green')
ax3.plot(times, resilience_index, 'g-', linewidth=2)
ax3.axhline(y=0.8, color='orange', linestyle='--', label='Target (0.8)')
ax3.axhline(y=0.5, color='red', linestyle='--', label='Critical (0.5)')
ax3.set_xlabel('Time (hours)')
ax3.set_ylabel('Resilience Index (0-1)')
ax3.set_title('Grid Resilience Index')
ax3.set_ylim(0, 1.1)
ax3.legend()
ax3.grid(True, alpha=0.3)
# Component status distribution
ax4 = axes[1, 1]
status_counts = defaultdict(int)
for comp in simulator.grid.components.values():
status_counts[comp.status.value] += 1
for line in simulator.grid.lines.values():
status_counts[line.status.value] += 1
if status_counts:
labels = list(status_counts.keys())
sizes = list(status_counts.values())
colors = ['#2ecc71', '#f39c12', '#e74c3c', '#9b59b6', '#3498db'][:len(labels)]
ax4.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
ax4.set_title('Final Component Status Distribution')
plt.tight_layout()
# =============================================================================
# MAIN EXECUTION
# =============================================================================
if __name__ == "__main__":
# Set random seed for reproducibility
random.seed(42)
np.random.seed(42)
# Run the simulation
grid, simulator = run_simulation()
print("\n" + "="*60)
print("Simulation Complete!")
print("="*60)
print("\nKey Insights:")
print(" • Heatwaves increase cooling demand and stress equipment")
print(" • Wildfires can cause direct damage and preemptive shutoffs")
print(" • Cascading failures can spread through the network")
print(" • Recovery time depends on repair crew availability")
print(" • Grid topology affects resilience (redundancy helps)")
Simply run the script:
python grid_resilience_simulation.py
The simulation will:
You can modify the create_test_grid() function to model your specific grid topology or adjust the run_simulation() function to test different scenarios.