"""
Stochastic Load Shedding Simulator
==================================
Features:
- Real traffic distributions (Gaussian, Poisson, Weibull mixture)
- Cascading failure dynamics with propagation probability
- Multi-tier customer impact modeling
- Real-time visualization with animated grid
- Monte Carlo simulation support
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.patches import Circle, FancyBboxPatch, Wedge
from matplotlib.collections import LineCollection, PatchCollection
import matplotlib.colors as mcolors
from dataclasses import dataclass, field
from typing import List, Dict, Tuple, Optional, Set
from enum import Enum
import random
from collections import deque
import scipy.stats as stats
from scipy.special import softmax
import warnings
warnings.filterwarnings('ignore')
# =============================================================================
# ENUMERATIONS AND DATA STRUCTURES
# =============================================================================
class CustomerType(Enum):
RESIDENTIAL = 1
COMMERCIAL = 2
INDUSTRIAL = 3
CRITICAL = 4 # Hospitals, emergency services
class NodeStatus(Enum):
NORMAL = 1
OVERLOADED = 2
FAILED = 3
SHED = 4
ISLANDED = 5
class FailureCause(Enum):
RANDOM = 1
OVERLOAD = 2
CASCADE = 3
EXTERNAL = 4
@dataclass
class Customer:
"""Represents a customer connected to a load node"""
customer_id: int
customer_type: CustomerType
base_demand: float # kW
priority_weight: float # Higher = more critical
outage_cost: float # $/kWh lost
def __post_init__(self):
# Set priority weights based on customer type
priority_map = {
CustomerType.RESIDENTIAL: 1.0,
CustomerType.COMMERCIAL: 2.0,
CustomerType.INDUSTRIAL: 3.0,
CustomerType.CRITICAL: 10.0
}
if self.priority_weight is None:
self.priority_weight = priority_map[self.customer_type]
# Set outage costs based on customer type ($/kWh)
cost_map = {
CustomerType.RESIDENTIAL: 0.5,
CustomerType.COMMERCIAL: 5.0,
CustomerType.INDUSTRIAL: 15.0,
CustomerType.CRITICAL: 100.0
}
if self.outage_cost is None:
self.outage_cost = cost_map[self.customer_type]
@dataclass
class TrafficDistribution:
"""
Real traffic/load distribution model combining multiple distributions
to match real-world patterns
"""
# Daily pattern parameters
peak_hours: Tuple[int, int] = (17, 21) # Evening peak
morning_peak: Tuple[int, int] = (7, 9)
base_load_ratio: float = 0.4 # Minimum load as fraction of peak
# Distribution parameters for randomness
noise_std: float = 0.05 # Gaussian noise
poisson_jumps: float = 0.1 # Probability of sudden load jump
weibull_shape: float = 2.5 # For tail events
def __post_init__(self):
self.rng = np.random.default_rng()
def generate_hourly_pattern(self, hours: int = 24) -> np.ndarray:
"""Generate realistic daily load pattern"""
t = np.linspace(0, 24, 100)
# Base sinusoidal pattern
base = self.base_load_ratio + (1 - self.base_load_ratio) * \
(0.5 + 0.5 * np.sin(2 * np.pi * (t - 6) / 24))
# Add morning peak (Gaussian bump)
morning_center = np.mean(self.morning_peak)
morning = 0.3 * np.exp(-0.5 * ((t - morning_center) / 1.5) ** 2)
# Add evening peak (Gaussian bump)
evening_center = np.mean(self.peak_hours)
evening = 0.4 * np.exp(-0.5 * ((t - evening_center) / 2.0) ** 2)
pattern = base + morning + evening
# Interpolate to desired resolution
t_out = np.linspace(0, 24, hours)
return np.interp(t_out, t, pattern)
def add_stochastic_variations(self, base_load: np.ndarray,
time_steps: int) -> np.ndarray:
"""Add realistic random variations to load"""
# Gaussian noise (small fluctuations)
noise = self.rng.normal(0, self.noise_std, time_steps)
# Poisson jumps (sudden load changes)
jumps = np.zeros(time_steps)
for i in range(time_steps):
if self.rng.random() < self.poisson_jumps:
# Random jump magnitude and direction
jump_size = self.rng.weibull(self.weibull_shape) * 0.1
direction = self.rng.choice([-1, 1])
jumps[i:] += direction * jump_size
# Correlated noise (AR(1) process for smoothness)
ar_coef = 0.8
ar_noise = np.zeros(time_steps)
ar_noise[0] = self.rng.normal(0, 0.02)
for i in range(1, time_steps):
ar_noise[i] = ar_coef * ar_noise[i-1] + self.rng.normal(0, 0.02)
return base_load * (1 + noise + jumps + ar_noise)
def sample_load(self, time_hour: float, base_demand: float) -> float:
"""Sample load at a specific time"""
# Get base pattern value
pattern = self.generate_hourly_pattern(24)
hour_idx = int(time_hour) % 24
next_idx = (hour_idx + 1) % 24
frac = time_hour - int(time_hour)
pattern_val = pattern[hour_idx] * (1 - frac) + pattern[next_idx] * frac
# Add randomness
noise = self.rng.normal(0, self.noise_std)
return max(0, base_demand * pattern_val * (1 + noise))
@dataclass
class GridNode:
"""Represents a node in the power grid"""
node_id: int
name: str
node_type: str # 'generator', 'substation', 'load'
capacity: float # Maximum capacity (MW)
customers: List[Customer] = field(default_factory=list)
connected_lines: List[int] = field(default_factory=list)
# State variables
current_load: float = 0.0
status: NodeStatus = NodeStatus.NORMAL
overload_threshold: float = 1.0
failure_probability: float = 0.001 # Base failure rate
# Position for visualization
position: Tuple[float, float] = (0.0, 0.0)
def get_total_demand(self) -> float:
"""Get total customer demand"""
return sum(c.base_demand for c in self.customers) / 1000 # kW to MW
def get_priority_weight(self) -> float:
"""Get weighted priority of all customers"""
if not self.customers:
return 0.0
return sum(c.priority_weight * c.base_demand for c in self.customers) / \
sum(c.base_demand for c in self.customers)
def get_outage_cost(self) -> float:
"""Get total outage cost per hour"""
return sum(c.outage_cost * c.base_demand for c in self.customers) / 1000
@dataclass
class TransmissionLine:
"""Represents a transmission line between nodes"""
line_id: int
from_node: int
to_node: int
capacity: float # MW
reactance: float # p.u.
# State
current_flow: float = 0.0
is_failed: bool = False
overload_threshold: float = 1.0
def get_loading_ratio(self) -> float:
"""Get current loading as fraction of capacity"""
return abs(self.current_flow) / self.capacity if self.capacity > 0 else 0
class CascadingFailureModel:
"""
Model for cascading failures in power grids
Based on complex network theory and power flow dynamics
"""
def __init__(self,
base_cascade_prob: float = 0.3,
loading_sensitivity: float = 2.0,
time_decay: float = 0.95):
self.base_cascade_prob = base_cascade_prob
self.loading_sensitivity = loading_sensitivity
self.time_decay = time_decay
self.rng = np.random.default_rng()
# Track failure history
self.failure_history: List[Dict] = []
def calculate_failure_probability(self,
node: GridNode,
neighbor_failures: int,
system_stress: float) -> float:
"""
Calculate probability of node failure
P(failure) = base_prob * (1 + neighbor_factor) * stress_factor
"""
# Base failure probability
p_base = node.failure_probability
# Loading factor (exponential increase near capacity)
load_ratio = node.current_load / node.capacity if node.capacity > 0 else 0
if load_ratio > 0.8:
loading_factor = np.exp(self.loading_sensitivity * (load_ratio - 0.8))
else:
loading_factor = 1.0
# Neighbor cascade factor
cascade_factor = 1 + 0.5 * neighbor_failures
# System-wide stress factor
stress_factor = 1 + system_stress
p_failure = p_base * loading_factor * cascade_factor * stress_factor
return min(1.0, p_failure)
def calculate_line_failure_prob(self, line: TransmissionLine) -> float:
"""Calculate transmission line failure probability"""
loading = line.get_loading_ratio()
if loading > 1.0:
# Overloaded - high probability of failure
return 0.5 + 0.5 * (loading - 1.0)
elif loading > 0.9:
# Near capacity
return 0.1 + 0.4 * (loading - 0.9) / 0.1
else:
return 0.001 # Base probability
def propagate_failure(self,
grid: 'PowerGrid',
failed_node_id: int,
time_step: int) -> List[int]:
"""
Propagate a failure through the network
Returns list of newly failed nodes
"""
newly_failed = []
# Get neighbors of failed node
neighbors = grid.get_neighbors(failed_node_id)
for neighbor_id in neighbors:
neighbor = grid.nodes[neighbor_id]
if neighbor.status == NodeStatus.NORMAL:
# Redistribute load to neighbor
load_increase = grid.nodes[failed_node_id].current_load / len(neighbors)
# Calculate failure probability
system_stress = grid.get_system_stress()
p_fail = self.calculate_failure_probability(
neighbor,
neighbor_failures=1,
system_stress=system_stress
)
# Roll for failure
if self.rng.random() < p_fail:
neighbor.status = NodeStatus.FAILED
newly_failed.append(neighbor_id)
# Record failure
self.failure_history.append({
'time': time_step,
'node_id': neighbor_id,
'cause': FailureCause.CASCADE,
'probability': p_fail
})
return newly_failed
class LoadSheddingStrategy:
"""
Implements various load shedding strategies
"""
def __init__(self, strategy: str = 'priority'):
self.strategy = strategy
self.rng = np.random.default_rng()
def select_shedding_candidates(self,
grid: 'PowerGrid',
amount_needed: float) -> List[Tuple[int, float]]:
"""
Select nodes for load shedding
Returns list of (node_id, amount_to_shed) tuples
"""
candidates = []
if self.strategy == 'priority':
# Shed lowest priority loads first
load_nodes = [(n.node_id, n.get_priority_weight(), n.current_load)
for n in grid.nodes.values()
if n.node_type == 'load' and
n.status == NodeStatus.NORMAL and
n.current_load > 0]
# Sort by priority (ascending - shed lowest first)
load_nodes.sort(key=lambda x: x[1])
remaining = amount_needed
for node_id, priority, load in load_nodes:
if remaining <= 0:
break
shed_amount = min(load, remaining)
candidates.append((node_id, shed_amount))
remaining -= shed_amount
elif self.strategy == 'proportional':
# Shed proportionally from all loads
total_load = sum(n.current_load for n in grid.nodes.values()
if n.node_type == 'load' and n.status == NodeStatus.NORMAL)
if total_load > 0:
shed_ratio = min(1.0, amount_needed / total_load)
for node in grid.nodes.values():
if node.node_type == 'load' and node.status == NodeStatus.NORMAL:
shed_amount = node.current_load * shed_ratio
if shed_amount > 0:
candidates.append((node.node_id, shed_amount))
elif self.strategy == 'random':
# Random selection
load_nodes = [(n.node_id, n.current_load) for n in grid.nodes.values()
if n.node_type == 'load' and
n.status == NodeStatus.NORMAL and
n.current_load > 0]
self.rng.shuffle(load_nodes)
remaining = amount_needed
for node_id, load in load_nodes:
if remaining <= 0:
break
shed_amount = min(load, remaining)
candidates.append((node_id, shed_amount))
remaining -= shed_amount
elif self.strategy == 'optimal':
# Optimization-based shedding (minimize customer impact)
load_nodes = [(n.node_id, n.get_outage_cost(), n.current_load)
for n in grid.nodes.values()
if n.node_type == 'load' and
n.status == NodeStatus.NORMAL and
n.current_load > 0]
# Sort by cost per MW (ascending - shed cheapest first)
load_nodes.sort(key=lambda x: x[1])
remaining = amount_needed
for node_id, cost, load in load_nodes:
if remaining <= 0:
break
shed_amount = min(load, remaining)
candidates.append((node_id, shed_amount))
remaining -= shed_amount
return candidates
def execute_shedding(self,
grid: 'PowerGrid',
candidates: List[Tuple[int, float]]) -> Dict:
"""Execute load shedding and return impact metrics"""
total_shed = 0.0
customers_affected = 0
total_cost = 0.0
for node_id, amount in candidates:
node = grid.nodes[node_id]
# Update node load
node.current_load -= amount
total_shed += amount
# Update node status
if node.current_load <= 0:
node.status = NodeStatus.SHED
node.current_load = 0
# Count affected customers
for customer in node.customers:
if customer.base_demand > 0:
customers_affected += 1
# Calculate cost
total_cost += node.get_outage_cost() * (amount / node.get_total_demand()) \
if node.get_total_demand() > 0 else 0
return {
'total_shed': total_shed,
'customers_affected': customers_affected,
'economic_cost': total_cost,
'nodes_shed': len(candidates)
}
class PowerGrid:
"""
Complete power grid model with nodes, lines, and dynamics
"""
def __init__(self, name: str = "Test Grid"):
self.name = name
self.nodes: Dict[int, GridNode] = {}
self.lines: Dict[int, TransmissionLine] = {}
self.traffic_model = TrafficDistribution()
self.cascade_model = CascadingFailureModel()
self.shedding_strategy = LoadSheddingStrategy(strategy='priority')
# Time tracking
self.current_time = 0.0 # Hours
self.time_step = 0.25 # 15 minutes
# Statistics
self.stats_history: List[Dict] = []
self.load_history: List[float] = []
self.generation_history: List[float] = []
self.rng = np.random.default_rng()
def add_node(self, node: GridNode):
"""Add a node to the grid"""
self.nodes[node.node_id] = node
def add_line(self, line: TransmissionLine):
"""Add a transmission line"""
self.lines[line.line_id] = line
# Update node connections
if line.from_node in self.nodes:
self.nodes[line.from_node].connected_lines.append(line.line_id)
if line.to_node in self.nodes:
self.nodes[line.to_node].connected_lines.append(line.line_id)
def get_neighbors(self, node_id: int) -> List[int]:
"""Get neighboring node IDs"""
neighbors = []
if node_id not in self.nodes:
return neighbors
for line_id in self.nodes[node_id].connected_lines:
line = self.lines[line_id]
if line.from_node == node_id:
neighbors.append(line.to_node)
else:
neighbors.append(line.from_node)
return neighbors
def get_system_stress(self) -> float:
"""Calculate overall system stress level"""
# Generator margin
total_generation = sum(n.current_load for n in self.nodes.values()
if n.node_type == 'generator' and
n.status == NodeStatus.NORMAL)
total_capacity = sum(n.capacity for n in self.nodes.values()
if n.node_type == 'generator')
gen_margin = 1 - (total_generation / total_capacity) if total_capacity > 0 else 0
# Line loading
avg_line_loading = np.mean([l.get_loading_ratio() for l in self.lines.values()
if not l.is_failed]) if self.lines else 0
# Failed components
failed_nodes = sum(1 for n in self.nodes.values()
if n.status == NodeStatus.FAILED)
failed_lines = sum(1 for l in self.lines.values() if l.is_failed)
failure_ratio = (failed_nodes + failed_lines) / (len(self.nodes) + len(self.lines))
# Combined stress
stress = (1 - gen_margin) * 0.4 + avg_line_loading * 0.4 + failure_ratio * 0.2
return stress
def update_loads(self):
"""Update loads based on traffic model"""
for node in self.nodes.values():
if node.node_type == 'load' and node.status == NodeStatus.NORMAL:
# Get time-of-day pattern
hour = self.current_time % 24
# Sample from distribution
base_demand = node.get_total_demand()
node.current_load = self.traffic_model.sample_load(hour, base_demand)
def calculate_power_flow(self):
"""Simplified DC power flow calculation"""
# Reset flows
for line in self.lines.values():
line.current_flow = 0.0
# Simple proportional flow based on demand/supply
total_generation = sum(n.current_load for n in self.nodes.values()
if n.node_type == 'generator' and
n.status == NodeStatus.NORMAL)
total_demand = sum(n.current_load for n in self.nodes.values()
if n.node_type == 'load' and
n.status == NodeStatus.NORMAL)
if total_generation == 0:
return
# Distribute flow across lines (simplified)
for line in self.lines.values():
if line.is_failed:
continue
from_node = self.nodes.get(line.from_node)
to_node = self.nodes.get(line.to_node)
if from_node and to_node:
# Simple flow estimate based on node types
if from_node.node_type == 'generator' and to_node.node_type == 'load':
flow = to_node.current_load * (line.capacity / total_generation)
elif to_node.node_type == 'generator' and from_node.node_type == 'load':
flow = -from_node.current_load * (line.capacity / total_generation)
else:
flow = (from_node.current_load - to_node.current_load) * 0.1
line.current_flow = flow
def check_overloads(self) -> Tuple[List[int], List[int]]:
"""Check for overloaded components"""
overloaded_nodes = []
overloaded_lines = []
for node in self.nodes.values():
if node.status == NodeStatus.NORMAL:
if node.current_load > node.capacity * node.overload_threshold:
overloaded_nodes.append(node.node_id)
for line in self.lines.values():
if not line.is_failed:
if line.get_loading_ratio() > line.overload_threshold:
overloaded_lines.append(line.line_id)
return overloaded_nodes, overloaded_lines
def process_failures(self, overloaded_nodes: List[int],
overloaded_lines: List[int]) -> Dict:
"""Process component failures"""
failed_nodes = []
failed_lines = []
# Check node failures
for node_id in overloaded_nodes:
node = self.nodes[node_id]
p_fail = self.cascade_model.calculate_failure_probability(
node, neighbor_failures=0, system_stress=self.get_system_stress()
)
if self.rng.random() < p_fail:
node.status = NodeStatus.FAILED
failed_nodes.append(node_id)
# Check line failures
for line_id in overloaded_lines:
line = self.lines[line_id]
p_fail = self.cascade_model.calculate_line_failure_prob(line)
if self.rng.random() < p_fail:
line.is_failed = True
failed_lines.append(line_id)
# Random failures
for node in self.nodes.values():
if node.status == NodeStatus.NORMAL:
if self.rng.random() < node.failure_probability * 0.01:
node.status = NodeStatus.FAILED
failed_nodes.append(node.node_id)
return {
'failed_nodes': failed_nodes,
'failed_lines': failed_lines
}
def check_generation_balance(self) -> float:
"""Check if generation matches demand"""
total_gen = sum(n.current_load for n in self.nodes.values()
if n.node_type == 'generator' and n.status == NodeStatus.NORMAL)
total_demand = sum(n.current_load for n in self.nodes.values()
if n.node_type == 'load' and n.status == NodeStatus.NORMAL)
return total_gen - total_demand
def step(self) -> Dict:
"""Advance simulation by one time step"""
# Update loads
self.update_loads()
# Calculate power flow
self.calculate_power_flow()
# Check for overloads
overloaded_nodes, overloaded_lines = self.check_overloads()
# Process failures
failures = self.process_failures(overloaded_nodes, overloaded_lines)
# Check generation balance
imbalance = self.check_generation_balance()
# Load shedding if needed
shedding_result = {'total_shed': 0, 'customers_affected': 0,
'economic_cost': 0, 'nodes_shed': 0}
if imbalance < 0:
# Need to shed load
amount_needed = abs(imbalance)
candidates = self.shedding_strategy.select_shedding_candidates(
self, amount_needed
)
shedding_result = self.shedding_strategy.execute_shedding(self, candidates)
# Propagate cascading failures
new_failures = []
for failed_node_id in failures['failed_nodes']:
cascaded = self.cascade_model.propagate_failure(
self, failed_node_id, int(self.current_time / self.time_step)
)
new_failures.extend(cascaded)
failures['cascaded_nodes'] = new_failures
# Record statistics
stats = {
'time': self.current_time,
'total_demand': sum(n.current_load for n in self.nodes.values()
if n.node_type == 'load'),
'total_generation': sum(n.current_load for n in self.nodes.values()
if n.node_type == 'generator'),
'system_stress': self.get_system_stress(),
'overloaded_nodes': len(overloaded_nodes),
'overloaded_lines': len(overloaded_lines),
'failed_nodes': len([n for n in self.nodes.values()
if n.status == NodeStatus.FAILED]),
'failed_lines': sum(1 for l in self.lines.values() if l.is_failed),
**shedding_result,
**failures
}
self.stats_history.append(stats)
# Advance time
self.current_time += self.time_step
return stats
def create_ieee_14_bus_grid() -> PowerGrid:
"""Create a grid based on IEEE 14-bus test system topology"""
grid = PowerGrid(name="IEEE 14-Bus Modified Grid")
# Create nodes with realistic parameters
node_data = [
# (id, name, type, capacity, x, y)
(1, "Generator 1", "generator", 200, 0, 100),
(2, "Generator 2", "generator", 150, 100, 200),
(3, "Generator 3", "generator", 100, 200, 100),
(4, "Substation A", "substation", 150, 100, 100),
(5, "Substation B", "substation", 150, 150, 150),
(6, "Substation C", "substation", 100, 200, 200),
(7, "Load Center 1", "load", 80, 50, 150),
(8, "Load Center 2", "load", 60, 150, 50),
(9, "Load Center 3", "load", 70, 100, 250),
(10, "Industrial Park", "load", 100, 250, 150),
(11, "Commercial District", "load", 90, 200, 250),
(12, "Residential A", "load", 50, 50, 250),
(13, "Residential B", "load", 40, 100, 300),
(14, "Critical Facility", "load", 30, 250, 250),
]
for nid, name, ntype, cap, x, y in node_data:
node = GridNode(
node_id=nid,
name=name,
node_type=ntype,
capacity=cap,
position=(x, y)
)
# Add customers to load nodes
if ntype == 'load':
# Mix of customer types
num_customers = np.random.randint(5, 20)
for i in range(num_customers):
ctype = np.random.choice(list(CustomerType), p=[0.6, 0.25, 0.1, 0.05])
base_demand = np.random.exponential(50) * ctype.value
customer = Customer(
customer_id=nid * 100 + i,
customer_type=ctype,
base_demand=base_demand,
priority_weight=None,
outage_cost=None
)
node.customers.append(customer)
grid.add_node(node)
# Create transmission lines (IEEE 14-bus topology simplified)
line_data = [
# (id, from, to, capacity)
(1, 1, 2, 150),
(2, 1, 4, 150),
(3, 2, 3, 100),
(4, 2, 5, 100),
(5, 3, 4, 80),
(6, 4, 5, 100),
(7, 4, 7, 80),
(8, 4, 8, 80),
(9, 5, 6, 100),
(10, 6, 11, 80),
(11, 6, 12, 60),
(12, 7, 8, 60),
(13, 7, 9, 80),
(14, 9, 10, 80),
(15, 9, 14, 60),
(16, 10, 11, 80),
(17, 12, 13, 50),
(18, 13, 14, 50),
(19, 3, 10, 80),
(20, 8, 14, 60),
]
for lid, from_n, to_n, cap in line_data:
line = TransmissionLine(
line_id=lid,
from_node=from_n,
to_node=to_n,
capacity=cap,
reactance=0.1
)
grid.add_line(line)
return grid
class GridVisualizer:
"""
Real-time visualization of the power grid simulation
"""
def __init__(self, grid: PowerGrid):
self.grid = grid
self.fig = None
self.axes = None
# Color maps
self.status_colors = {
NodeStatus.NORMAL: '#2ecc71', # Green
NodeStatus.OVERLOADED: '#f39c12', # Orange
NodeStatus.FAILED: '#e74c3c', # Red
NodeStatus.SHED: '#9b59b6', # Purple
NodeStatus.ISLANDED: '#3498db' # Blue
}
self.node_type_markers = {
'generator': 's', # Square
'substation': '^', # Triangle
'load': 'o' # Circle
}
def setup_figure(self):
"""Set up the matplotlib figure"""
self.fig = plt.figure(figsize=(16, 10))
# Create grid of subplots
gs = self.fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3)
# Main grid visualization
self.ax_grid = self.fig.add_subplot(gs[:2, :2])
self.ax_grid.set_title('Power Grid Status')
self.ax_grid.set_aspect('equal')
# Load curve
self.ax_load = self.fig.add_subplot(gs[0, 2])
self.ax_load.set_title('Load Profile')
self.ax_load.set_xlabel('Time (hours)')
self.ax_load.set_ylabel('Load (MW)')
# System stress
self.ax_stress = self.fig.add_subplot(gs[1, 2])
self.ax_stress.set_title('System Stress')
self.ax_stress.set_xlabel('Time step')
self.ax_stress.set_ylabel('Stress Level')
# Customer impact
self.ax_impact = self.fig.add_subplot(gs[2, 0])
self.ax_impact.set_title('Customer Impact')
# Economic cost
self.ax_cost = self.fig.add_subplot(gs[2, 1])
self.ax_cost.set_title('Cumulative Economic Cost')
self.ax_cost.set_xlabel('Time step')
self.ax_cost.set_ylabel('Cost ($)')
# Statistics panel
self.ax_stats = self.fig.add_subplot(gs[2, 2])
self.ax_stats.axis('off')
plt.tight_layout()
def draw_grid(self):
"""Draw the power grid network"""
self.ax_grid.clear()
self.ax_grid.set_title(f'Power Grid Status - Time: {self.grid.current_time:.2f}h')
# Draw transmission lines
for line in self.grid.lines.values():
from_node = self.grid.nodes.get(line.from_node)
to_node = self.grid.nodes.get(line.to_node)
if from_node and to_node:
x = [from_node.position[0], to_node.position[0]]
y = [from_node.position[1], to_node.position[1]]
# Line color based on loading
loading = line.get_loading_ratio()
if line.is_failed:
color = '#e74c3c'
linestyle = '--'
linewidth = 1
elif loading > 1.0:
color = '#e74c3c'
linestyle = '-'
linewidth = 3
elif loading > 0.8:
color = '#f39c12'
linestyle = '-'
linewidth = 2
else:
color = '#95a5a6'
linestyle = '-'
linewidth = 1
self.ax_grid.plot(x, y, color=color, linestyle=linestyle,
linewidth=linewidth, alpha=0.7)
# Add flow label
if not line.is_failed:
mid_x = (x[0] + x[1]) / 2
mid_y = (y[0] + y[1]) / 2
self.ax_grid.annotate(f'{abs(line.current_flow):.1f}MW',
(mid_x, mid_y), fontsize=7,
ha='center', va='bottom')
# Draw nodes
for node in self.grid.nodes.values():
x, y = node.position
color = self.status_colors[node.status]
marker = self.node_type_markers[node.node_type]
# Size based on capacity/load
size = 100 + node.capacity * 2
self.ax_grid.scatter(x, y, c=color, marker=marker, s=size,
edgecolors='black', linewidths=1, zorder=5)
# Node label
label = f"{node.node_id}\n{node.current_load:.1f}/{node.capacity:.0f}MW"
self.ax_grid.annotate(label, (x, y + 15), ha='center', fontsize=7)
# Legend
legend_elements = []
for status, color in self.status_colors.items():
legend_elements.append(plt.scatter([], [], c=color, label=status.name))
self.ax_grid.legend(handles=legend_elements, loc='upper left', fontsize=8)
self.ax_grid.set_xlim(-20, 300)
self.ax_grid.set_ylim(0, 350)
def update_plots(self):
"""Update all plots with current data"""
if not self.grid.stats_history:
return
# Load profile
self.ax_load.clear()
times = [s['time'] for s in self.grid.stats_history]
demands = [s['total_demand'] for s in self.grid.stats_history]
generations = [s['total_generation'] for s in self.grid.stats_history]
self.ax_load.plot(times, demands, 'b-', label='Demand', linewidth=2)
self.ax_load.plot(times, generations, 'g--', label='Generation', linewidth=2)
self.ax_load.fill_between(times, demands, generations,
where=[d > g for d, g in zip(demands, generations)],
alpha=0.3, color='red', label='Deficit')
self.ax_load.legend(fontsize=8)
self.ax_load.set_title('Load Profile')
self.ax_load.set_xlabel('Time (hours)')
self.ax_load.set_ylabel('Power (MW)')
# System stress
self.ax_stress.clear()
stress = [s['system_stress'] for s in self.grid.stats_history]
self.ax_stress.fill_between(range(len(stress)), stress, alpha=0.5, color='red')
self.ax_stress.plot(stress, 'r-', linewidth=2)
self.ax_stress.axhline(y=0.7, color='orange', linestyle='--', label='Warning')
self.ax_stress.axhline(y=0.9, color='red', linestyle='--', label='Critical')
self.ax_stress.set_ylim(0, 1)
self.ax_stress.legend(fontsize=8)
self.ax_stress.set_title('System Stress')
# Customer impact pie chart
self.ax_impact.clear()
status_counts = {}
for node in self.grid.nodes.values():
if node.node_type == 'load':
status_name = node.status.name
if status_name not in status_counts:
status_counts[status_name] = 0
status_counts[status_name] += len(node.customers)
if status_counts:
colors = [self.status_colors[NodeStatus[s]] for s in status_counts.keys()]
wedges, texts, autotexts = self.ax_impact.pie(
status_counts.values(),
labels=status_counts.keys(),
colors=colors,
autopct='%1.1f%%'
)
for text in texts + autotexts:
text.set_fontsize(8)
self.ax_impact.set_title('Customer Status')
# Cumulative cost
self.ax_cost.clear()
cumulative_cost = np.cumsum([s['economic_cost'] for s in self.grid.stats_history])
self.ax_cost.fill_between(range(len(cumulative_cost)), cumulative_cost,
alpha=0.5, color='red')
self.ax_cost.plot(cumulative_cost, 'r-', linewidth=2)
self.ax_cost.set_title('Cumulative Economic Cost')
self.ax_cost.set_xlabel('Time step')
self.ax_cost.set_ylabel('Cost ($)')
# Statistics text
self.ax_stats.clear()
self.ax_stats.axis('off')
latest = self.grid.stats_history[-1]
stats_text = (
f"SIMULATION STATISTICS\n"
f"{'='*30}\n"
f"Time: {latest['time']:.2f} hours\n"
f"Total Demand: {latest['total_demand']:.1f} MW\n"
f"Total Generation: {latest['total_generation']:.1f} MW\n"
f"System Stress: {latest['system_stress']:.2%}\n"
f"{'='*30}\n"
f"Overloaded Nodes: {latest['overloaded_nodes']}\n"
f"Overloaded Lines: {latest['overloaded_lines']}\n"
f"Failed Nodes: {latest['failed_nodes']}\n"
f"Failed Lines: {latest['failed_lines']}\n"
f"{'='*30}\n"
f"Load Shed: {latest['total_shed']:.1f} MW\n"
f"Customers Affected: {latest['customers_affected']}\n"
f"Economic Cost: ${latest['economic_cost']:.2f}\n"
)
self.ax_stats.text(0.1, 0.9, stats_text, transform=self.ax_stats.transAxes,
fontsize=9, verticalalignment='top', fontfamily='monospace',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
def animate(self, frame):
"""Animation update function"""
stats = self.grid.step()
self.draw_grid()
self.update_plots()
return []
def run_animation(self, num_frames: int = 100, interval: int = 200):
"""Run the animated simulation"""
self.setup_figure()
anim = FuncAnimation(self.fig, self.animate, frames=num_frames,
interval=interval, blit=False, repeat=False)
plt.show()
return anim
def plot_summary(self):
"""Generate summary plots after simulation"""
if not self.grid.stats_history:
print("No simulation data available.")
return
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
stats = self.grid.stats_history
times = [s['time'] for s in stats]
# 1. Load vs Generation
ax = axes[0, 0]
ax.plot(times, [s['total_demand'] for s in stats], 'b-', label='Demand', lw=2)
ax.plot(times, [s['total_generation'] for s in stats], 'g--', label='Generation', lw=2)
ax.fill_between(times,
[s['total_demand'] for s in stats],
[s['total_generation'] for s in stats],
alpha=0.3, color='red')
ax.set_xlabel('Time (hours)')
ax.set_ylabel('Power (MW)')
ax.set_title('Demand vs Generation')
ax.legend()
ax.grid(True, alpha=0.3)
# 2. System Stress
ax = axes[0, 1]
ax.fill_between(times, [s['system_stress'] for s in stats], alpha=0.5, color='red')
ax.plot(times, [s['system_stress'] for s in stats], 'r-', lw=2)
ax.axhline(0.7, color='orange', ls='--', label='Warning')
ax.axhline(0.9, color='red', ls='--', label='Critical')
ax.set_xlabel('Time (hours)')
ax.set_ylabel('Stress Level')
ax.set_title('System Stress Over Time')
ax.set_ylim(0, 1)
ax.legend()
ax.grid(True, alpha=0.3)
# 3. Component Failures
ax = axes[0, 2]
ax.plot(times, [s['failed_nodes'] for s in stats], 'r-', label='Nodes', lw=2)
ax.plot(times, [s['failed_lines'] for s in stats], 'b-', label='Lines', lw=2)
ax.set_xlabel('Time (hours)')
ax.set_ylabel('Count')
ax.set_title('Component Failures')
ax.legend()
ax.grid(True, alpha=0.3)
# 4. Load Shedding
ax = axes[1, 0]
ax.bar(times, [s['total_shed'] for s in stats], width=0.2, alpha=0.7, color='purple')
ax.set_xlabel('Time (hours)')
ax.set_ylabel('Load Shed (MW)')
ax.set_title('Load Shedding Events')
ax.grid(True, alpha=0.3)
# 5. Economic Impact
ax = axes[1, 1]
cumulative_cost = np.cumsum([s['economic_cost'] for s in stats])
ax.fill_between(times, cumulative_cost, alpha=0.5, color='red')
ax.plot(times, cumulative_cost, 'r-', lw=2)
ax.set_xlabel('Time (hours)')
ax.set_ylabel('Cumulative Cost ($)')
ax.set_title('Economic Impact')
ax.grid(True, alpha=0.3)
# 6. Summary Statistics
ax = axes[1, 2]
ax.axis('off')
total_shed = sum(s['total_shed'] for s in stats)
total_cost = sum(s['economic_cost'] for s in stats)
peak_stress = max(s['system_stress'] for s in stats)
max_failed = max(s['failed_nodes'] for s in stats)
summary = (
f"{'='*40}\n"
f" SIMULATION SUMMARY\n"
f"{'='*40}\n\n"
f"Total Simulation Time: {times[-1]:.1f} hours\n\n"
f"Total Load Shed: {total_shed:.1f} MW\n"
f"Total Economic Cost: ${total_cost:,.2f}\n\n"
f"Peak System Stress: {peak_stress:.1%}\n"
f"Max Failed Nodes: {max_failed}\n\n"
f"Average Load: {np.mean([s['total_demand'] for s in stats]):.1f} MW\n"
f"Average Generation: {np.mean([s['total_generation'] for s in stats]):.1f} MW\n"
f"{'='*40}"
)
ax.text(0.2, 0.5, summary, transform=ax.transAxes,
fontsize=11, verticalalignment='center',
fontfamily='monospace',
bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.8))
plt.tight_layout()
plt.savefig('simulation_summary.png', dpi=150, bbox_inches='tight')
plt.show()
def run_monte_carlo_simulation(grid: PowerGrid,
num_runs: int = 100,
time_horizon: float = 24.0) -> Dict:
"""
Run Monte Carlo simulation to get statistical insights
"""
results = {
'total_shed': [],
'total_cost': [],
'peak_stress': [],
'total_failures': [],
'customers_affected': []
}
for run in range(num_runs):
# Reset grid
for node in grid.nodes.values():
node.status = NodeStatus.NORMAL
node.current_load = 0
for line in grid.lines.values():
line.is_failed = False
line.current_flow = 0
grid.stats_history = []
grid.current_time = 0
# Run simulation
while grid.current_time < time_horizon:
grid.step()
# Collect results
total_shed = sum(s['total_shed'] for s in grid.stats_history)
total_cost = sum(s['economic_cost'] for s in grid.stats_history)
peak_stress = max(s['system_stress'] for s in grid.stats_history)
total_failures = max(s['failed_nodes'] for s in grid.stats_history)
total_customers = max(s['customers_affected'] for s in grid.stats_history)
results['total_shed'].append(total_shed)
results['total_cost'].append(total_cost)
results['peak_stress'].append(peak_stress)
results['total_failures'].append(total_failures)
results['customers_affected'].append(total_customers)
if (run + 1) % 10 == 0:
print(f"Completed {run + 1}/{num_runs} runs")
return results
def plot_monte_carlo_results(results: Dict):
"""Plot Monte Carlo simulation results"""
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
# 1. Total Load Shed Distribution
ax = axes[0, 0]
ax.hist(results['total_shed'], bins=20, alpha=0.7, color='purple', edgecolor='black')
ax.axvline(np.mean(results['total_shed']), color='red', ls='--',
label=f'Mean: {np.mean(results["total_shed"]):.1f}')
ax.axvline(np.percentile(results['total_shed'], 95), color='orange', ls='--',
label=f'95th: {np.percentile(results["total_shed"], 95):.1f}')
ax.set_xlabel('Total Load Shed (MW)')
ax.set_ylabel('Frequency')
ax.set_title('Load Shedding Distribution')
ax.legend()
# 2. Economic Cost Distribution
ax = axes[0, 1]
ax.hist(results['total_cost'], bins=20, alpha=0.7, color='red', edgecolor='black')
ax.axvline(np.mean(results['total_cost']), color='darkred', ls='--',
label=f'Mean: ${np.mean(results["total_cost"]):,.0f}')
ax.set_xlabel('Total Cost ($)')
ax.set_ylabel('Frequency')
ax.set_title('Economic Cost Distribution')
ax.legend()
# 3. Peak Stress Distribution
ax = axes[0, 2]
ax.hist(results['peak_stress'], bins=20, alpha=0.7, color='orange', edgecolor='black')
ax.axvline(np.mean(results['peak_stress']), color='red', ls='--',
label=f'Mean: {np.mean(results["peak_stress"]):.1%}')
ax.set_xlabel('Peak Stress')
ax.set_ylabel('Frequency')
ax.set_title('Peak Stress Distribution')
ax.legend()
# 4. Failure Distribution
ax = axes[1, 0]
failure_counts = {}
for f in results['total_failures']:
failure_counts[f] = failure_counts.get(f, 0) + 1
ax.bar(failure_counts.keys(), failure_counts.values(), color='red', alpha=0.7)
ax.set_xlabel('Number of Failed Nodes')
ax.set_ylabel('Frequency')
ax.set_title('Node Failure Distribution')
# 5. Customer Impact Distribution
ax = axes[1, 1]
ax.hist(results['customers_affected'], bins=20, alpha=0.7, color='blue', edgecolor='black')
ax.axvline(np.mean(results['customers_affected']), color='darkblue', ls='--',
label=f'Mean: {np.mean(results["customers_affected"]):.0f}')
ax.set_xlabel('Customers Affected')
ax.set_ylabel('Frequency')
ax.set_title('Customer Impact Distribution')
ax.legend()
# 6. Risk Metrics
ax = axes[1, 2]
ax.axis('off')
# Calculate risk metrics
var_95 = np.percentile(results['total_cost'], 95)
var_99 = np.percentile(results['total_cost'], 99)
es_95 = np.mean([c for c in results['total_cost'] if c >= var_95])
risk_text = (
f"{'='*40}\n"
f" RISK METRICS (Monte Carlo)\n"
f"{'='*40}\n\n"
f"Based on {len(results['total_cost'])} simulations\n\n"
f"Value at Risk (95%): ${var_95:,.2f}\n"
f"Value at Risk (99%): ${var_99:,.2f}\n"
f"Expected Shortfall (95%): ${es_95:,.2f}\n\n"
f"Mean Load Shed: {np.mean(results['total_shed']):.1f} MW\n"
f"Std Load Shed: {np.std(results['total_shed']):.1f} MW\n\n"
f"Mean Cost: ${np.mean(results['total_cost']):,.2f}\n"
f"Std Cost: ${np.std(results['total_cost']):,.2f}\n\n"
f"Probability of Failure > 0: "
f"{100*sum(1 for f in results['total_failures'] if f > 0)/len(results['total_failures']):.1f}%\n"
f"{'='*40}"
)
ax.text(0.1, 0.5, risk_text, transform=ax.transAxes,
fontsize=10, verticalalignment='center',
fontfamily='monospace',
bbox=dict(boxstyle='round', facecolor='lightyellow', alpha=0.8))
plt.tight_layout()
plt.savefig('monte_carlo_results.png', dpi=150, bbox_inches='tight')
plt.show()
def main():
"""Main function to run the simulator"""
print("="*60)
print(" STOCHASTIC LOAD SHEDDING SIMULATOR")
print(" With Real Traffic Distributions & Cascading Failures")
print("="*60)
# Create grid
print("\n[1] Creating power grid model...")
grid = create_ieee_14_bus_grid()
print(f" - Nodes: {len(grid.nodes)}")
print(f" - Lines: {len(grid.lines)}")
print(f" - Total customers: {sum(len(n.customers) for n in grid.nodes.values())}")
# Display traffic distribution pattern
print("\n[2] Traffic Distribution Model:")
traffic = TrafficDistribution()
daily_pattern = traffic.generate_hourly_pattern(24)
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
hours = np.arange(24)
plt.fill_between(hours, daily_pattern, alpha=0.3, color='blue')
plt.plot(hours, daily_pattern, 'b-', linewidth=2)
plt.xlabel('Hour of Day')
plt.ylabel('Load Factor')
plt.title('Daily Load Pattern')
plt.grid(True, alpha=0.3)
# Show stochastic variations
plt.subplot(1, 2, 2)
base_load = np.ones(100) * 100 # 100 MW base
varied_load = traffic.add_stochastic_variations(base_load, 100)
plt.plot(varied_load, 'g-', linewidth=1, alpha=0.7)
plt.axhline(100, color='red', ls='--', label='Base Load')
plt.xlabel('Time Step')
plt.ylabel('Load (MW)')
plt.title('Stochastic Load Variations')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('traffic_distribution.png', dpi=150)
plt.show()
# Run animated simulation
print("\n[3] Starting animated simulation...")
print(" (Close the animation window to continue)")
visualizer = GridVisualizer(grid)
# Run some steps to get initial data
for _ in range(10):
grid.step()
visualizer.run_animation(num_frames=96, interval=100) # 24 hours at 15-min steps
# Show summary
print("\n[4] Generating summary plots...")
visualizer.plot_summary()
# Monte Carlo analysis
print("\n[5] Running Monte Carlo Simulation (100 runs)...")
# Create fresh grid for Monte Carlo
mc_grid = create_ieee_14_bus_grid()
mc_results = run_monte_carlo_simulation(mc_grid, num_runs=100, time_horizon=24.0)
print("\n[6] Plotting Monte Carlo results...")
plot_monte_carlo_results(mc_results)
print("\n" + "="*60)
print(" Simulation Complete!")
print(" Generated files:")
print(" - traffic_distribution.png")
print(" - simulation_summary.png")
print(" - monte_carlo_results.png")
print("="*60)
if __name__ == "__main__":
main()