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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
|
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches from matplotlib.gridspec import GridSpec from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection import networkx as nx from itertools import permutations import warnings warnings.filterwarnings('ignore')
np.random.seed(42)
buses = [ (0, "North Hub", 52.0, -114.5, 0, True), (1, "Alpha Sub", 51.8, -114.0, 120, False), (2, "Beta Sub", 51.6, -113.5, 90, False), (3, "Gamma Sub", 51.4, -114.2, 150, False), (4, "Delta Sub", 51.2, -113.8, 80, False), (5, "East Gen", 51.0, -113.0, 0, True), (6, "Epsilon Sub", 51.5, -112.5, 110, False), (7, "Zeta Sub", 51.8, -112.8, 60, False), (8, "Eta Sub", 52.0, -113.2, 95, False), (9, "Theta Sub", 51.3, -114.8, 140, False), (10, "Iota Sub", 51.1, -114.5, 75, False), (11, "Kappa Sub", 50.9, -113.5, 55, False), (12, "Lambda Sub", 50.8, -112.8, 100, False), (13, "South Hub", 50.6, -113.8, 0, True), ]
lines = [ (0, 1, 0.8, 345), (0, 7, 1.2, 345), (0, 8, 1.0, 345), (1, 2, 0.6, 345), (1, 9, 1.4, 230), (2, 3, 0.9, 230), (2, 4, 1.1, 230), (3, 4, 0.5, 230), (3, 9, 1.3, 230), (4, 5, 1.6, 230), (4, 11, 1.2, 115), (5, 6, 0.7, 230), (5, 12, 1.5, 115), (6, 7, 0.9, 230), (6, 11, 1.1, 115), (7, 8, 0.6, 230), (8, 9, 1.0, 345), (9, 10, 0.8, 230), (10,11, 0.7, 115), (10,13, 1.1, 230), (11,12, 0.9, 115), (11,13, 1.2, 230), (12,13, 0.6, 230), ]
bus_data = {b[0]: {"name": b[1], "lat": b[2], "lon": b[3], "load": b[4], "gen": b[5]} for b in buses} total_load = sum(b[4] for b in buses)
def compute_gic(buses_dict, lines_list, storm_direction_deg=315, storm_intensity=5.0): """ Compute GIC for each line based on: - Line geographic orientation vs storm direction - Line length (from lat/lon) - Earth resistivity model (simplified uniform) storm_direction_deg: direction the storm arrives FROM (degrees, 0=North) storm_intensity: dB/dt in nT/min """ storm_rad = np.radians(storm_direction_deg) storm_vec = np.array([np.sin(storm_rad), np.cos(storm_rad)])
gic_data = {} for i, (fb, tb, res, kv) in enumerate(lines_list): lat1 = buses_dict[fb]["lat"] lon1 = buses_dict[fb]["lon"] lat2 = buses_dict[tb]["lat"] lon2 = buses_dict[tb]["lon"]
dlat = lat2 - lat1 dlon = (lon2 - lon1) * np.cos(np.radians((lat1 + lat2) / 2)) length_km = np.sqrt(dlat**2 + dlon**2) * 111.0
line_vec = np.array([dlon, dlat]) line_len = np.linalg.norm(line_vec) + 1e-9 line_unit = line_vec / line_len
alignment = abs(np.dot(line_unit, storm_vec)) E_induced = storm_intensity * alignment * 0.3
EMF = E_induced * length_km total_R = res + 0.5 + 0.5 I_gic = EMF / total_R
gic_data[i] = { "from": fb, "to": tb, "length_km": length_km, "alignment": alignment, "I_gic": I_gic, "EMF": EMF, "resistance": res, "voltage_kV": kv, } return gic_data
def transformer_reactive_absorption(I_gic, Q0=10.0, beta=0.15): """ Q absorbed by GIC-saturated transformer (MVAR) Q = Q0 * (1 + beta * I_gic^2) """ return Q0 * (1.0 + beta * I_gic**2)
def compute_bus_risk(bus_id, gic_data, buses_dict, active_lines): """ Risk score for a bus = sum of GIC contributions from incident active lines, weighted by transformer loading and voltage level """ total_gic = 0.0 total_Q_absorbed = 0.0 incident = [idx for idx, d in gic_data.items() if idx in active_lines and (d["from"] == bus_id or d["to"] == bus_id)]
for idx in incident: d = gic_data[idx] I = d["I_gic"] voltage_factor = d["voltage_kV"] / 345.0 total_gic += I * voltage_factor total_Q_absorbed += transformer_reactive_absorption(I)
load_weight = buses_dict[bus_id]["load"] / (total_load + 1e-9) risk = total_gic * (1 + 2 * load_weight) + 0.1 * total_Q_absorbed return risk, total_Q_absorbed
def compute_system_state(active_lines, gic_data, buses_dict): """ Compute total system risk, load at risk, and per-bus metrics """ G = nx.Graph() for b in buses_dict: G.add_node(b) for idx in active_lines: d = gic_data[idx] G.add_edge(d["from"], d["to"], line_idx=idx)
gens = [b for b, bd in buses_dict.items() if bd["gen"]]
connected_load = 0.0 for b, bd in buses_dict.items(): if bd["load"] > 0: reachable = any(nx.has_path(G, b, g) for g in gens if g in G) if reachable: connected_load += bd["load"]
load_shed = total_load - connected_load
bus_risks = {} total_Q = 0.0 for b in buses_dict: r, q = compute_bus_risk(b, gic_data, buses_dict, active_lines) bus_risks[b] = r total_Q += q
system_risk = sum(bus_risks.values()) return system_risk, load_shed, bus_risks, total_Q
def greedy_switching_sequence(gic_data, buses_dict, n_switches=6): """ Greedy algorithm: at each step, open the circuit breaker that gives the best risk reduction per MW of load shed. Returns: sequence of (line_idx, risk_before, risk_after, load_shed_delta) """ active_lines = set(range(len(lines))) sequence = []
risk0, shed0, _, q0 = compute_system_state(active_lines, gic_data, buses_dict) history = [{"step": 0, "risk": risk0, "load_shed": shed0, "Q_absorbed": q0, "line_opened": None, "active_count": len(active_lines)}]
for step in range(n_switches): best_score = -np.inf best_line = None best_risk = risk0 best_shed = shed0
for candidate in active_lines: trial = active_lines - {candidate} r, s, _, q = compute_system_state(trial, gic_data, buses_dict) delta_risk = risk0 - r delta_shed = s - shed0
if delta_shed > 50: score = -np.inf else: score = delta_risk - 3.0 * delta_shed / (total_load + 1e-9) * 1000
if score > best_score: best_score = score best_line = candidate best_risk = r best_shed = s
if best_line is None or best_score < 0: break
active_lines.remove(best_line) d = gic_data[best_line] sequence.append({ "step": step + 1, "line_idx": best_line, "from_bus": buses_dict[d["from"]]["name"], "to_bus": buses_dict[d["to"]]["name"], "I_gic": d["I_gic"], "risk_before": risk0, "risk_after": best_risk, "load_shed": best_shed, })
r_new, s_new, _, q_new = compute_system_state(active_lines, gic_data, buses_dict) history.append({"step": step + 1, "risk": r_new, "load_shed": s_new, "Q_absorbed": q_new, "line_opened": best_line, "active_count": len(active_lines)}) risk0 = r_new shed0 = s_new
return sequence, history, active_lines
def simulated_annealing_optimizer(gic_data, buses_dict, greedy_seq, T_init=100.0, T_min=0.5, alpha=0.92, n_iter=400): """ Refine the greedy sequence using Simulated Annealing. Optimizes the ORDER of switching operations. """ if len(greedy_seq) < 2: return greedy_seq, []
line_indices = [s["line_idx"] for s in greedy_seq]
def evaluate_sequence(seq): active = set(range(len(lines))) total_cost = 0.0 r0, s0, _, _ = compute_system_state(active, gic_data, buses_dict) for li in seq: active.discard(li) r, s, _, _ = compute_system_state(active, gic_data, buses_dict) total_cost += r + 5.0 * s return total_cost
current = line_indices[:] current_cost = evaluate_sequence(current) best = current[:] best_cost = current_cost
T = T_init sa_history = [current_cost]
while T > T_min: for _ in range(n_iter): i, j = np.random.choice(len(current), 2, replace=False) neighbor = current[:] neighbor[i], neighbor[j] = neighbor[j], neighbor[i] neighbor_cost = evaluate_sequence(neighbor)
delta = neighbor_cost - current_cost if delta < 0 or np.random.random() < np.exp(-delta / T): current = neighbor current_cost = neighbor_cost if current_cost < best_cost: best = current[:] best_cost = current_cost
sa_history.append(best_cost) T *= alpha
return best, sa_history
def simulate_storm_timeseries(duration_min=120, peak_time=40): """ Simulate a Kp-index storm profile and corresponding GIC intensity over time. Returns time array and storm intensity multiplier. """ t = np.linspace(0, duration_min, 300) intensity = (np.exp(-((t - peak_time)**2) / (2 * 15**2)) + 0.3 * np.exp(-((t - 70)**2) / (2 * 25**2))) intensity = intensity / intensity.max() * 8.0 return t, intensity
def plot_all_results(gic_data, buses_dict, greedy_seq, sa_sequence, greedy_history, sa_history_cost, active_lines_final):
fig = plt.figure(figsize=(22, 28)) fig.patch.set_facecolor('#0f0f1a') gs = GridSpec(4, 3, figure=fig, hspace=0.45, wspace=0.38)
NEON_BLUE = '#00cfff' NEON_GREEN = '#39ff14' NEON_ORANGE = '#ff6b00' NEON_RED = '#ff2d55' NEON_PURPLE = '#bf5fff' NEON_YELLOW = '#ffe600' BG = '#0f0f1a' PANEL_BG = '#16213e'
def style_ax(ax, title): ax.set_facecolor(PANEL_BG) ax.set_title(title, color='white', fontsize=11, fontweight='bold', pad=8) ax.tick_params(colors='#aaaaaa', labelsize=8) for spine in ax.spines.values(): spine.set_edgecolor('#333355') ax.xaxis.label.set_color('#aaaaaa') ax.yaxis.label.set_color('#aaaaaa')
ax1 = fig.add_subplot(gs[0, :2]) style_ax(ax1, "⚡ Power Grid Network — GIC Intensity Map")
lats = np.array([buses_dict[b]["lat"] for b in buses_dict]) lons = np.array([buses_dict[b]["lon"] for b in buses_dict])
max_gic = max(d["I_gic"] for d in gic_data.values()) cmap = plt.cm.plasma
for idx, d in gic_data.items(): fb, tb = d["from"], d["to"] x = [buses_dict[fb]["lon"], buses_dict[tb]["lon"]] y = [buses_dict[fb]["lat"], buses_dict[tb]["lat"]] color = cmap(d["I_gic"] / max_gic) lw = 1.5 if idx in active_lines_final else 0.5 ls = '-' if idx in active_lines_final else '--' alpha = 0.9 if idx in active_lines_final else 0.3 ax1.plot(x, y, color=color, linewidth=lw, linestyle=ls, alpha=alpha, zorder=2)
if idx not in active_lines_final: mx = (x[0] + x[1]) / 2 my = (y[0] + y[1]) / 2 ax1.plot(mx, my, 'x', color=NEON_RED, markersize=8, markeredgewidth=2, zorder=5)
for b, bd in buses_dict.items(): r, _ = compute_bus_risk(b, gic_data, buses_dict, active_lines_final) size = 80 + 200 * (bd["load"] / (max(d["load"] for d in buses_dict.values()) + 1)) color = NEON_YELLOW if bd["gen"] else NEON_BLUE ax1.scatter(bd["lon"], bd["lat"], s=size, c=color, zorder=6, edgecolors='white', linewidths=0.8) ax1.annotate(bd["name"].split()[0], (bd["lon"], bd["lat"]), textcoords="offset points", xytext=(5, 5), fontsize=7, color='white', zorder=7)
ax1.annotate('', xy=(lons.mean() - 0.15, lats.mean() + 0.1), xytext=(lons.mean() - 0.5, lats.mean() + 0.5), arrowprops=dict(arrowstyle='->', color=NEON_ORANGE, lw=2.5, mutation_scale=20)) ax1.text(lons.mean() - 0.52, lats.mean() + 0.52, 'Storm\nNW→SE', color=NEON_ORANGE, fontsize=8, fontweight='bold')
sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(0, max_gic)) plt.colorbar(sm, ax=ax1, label='GIC (A)', pad=0.02) ax1.set_xlabel('Longitude') ax1.set_ylabel('Latitude')
legend_els = [ mpatches.Patch(color=NEON_YELLOW, label='Generator Bus'), mpatches.Patch(color=NEON_BLUE, label='Load Bus'), plt.Line2D([0], [0], color='red', linestyle='--', label='Opened Breaker'), ] ax1.legend(handles=legend_els, loc='lower left', facecolor=PANEL_BG, edgecolor='gray', labelcolor='white', fontsize=8)
ax2 = fig.add_subplot(gs[0, 2]) style_ax(ax2, "GIC per Transmission Line")
gic_vals = [gic_data[i]["I_gic"] for i in range(len(lines))] line_labels = [f"{gic_data[i]['from']}-{gic_data[i]['to']}" for i in range(len(lines))] colors_bar = [NEON_RED if i not in active_lines_final else NEON_BLUE for i in range(len(lines))] bars = ax2.barh(range(len(lines)), gic_vals, color=colors_bar, alpha=0.85) ax2.set_yticks(range(len(lines))) ax2.set_yticklabels(line_labels, fontsize=6) ax2.set_xlabel('GIC (Amperes)') ax2.axvline(x=50, color=NEON_ORANGE, linestyle='--', linewidth=1.5, label='Risk Threshold (50A)') ax2.legend(facecolor=PANEL_BG, edgecolor='gray', labelcolor='white', fontsize=7)
ax3 = fig.add_subplot(gs[1, :2]) style_ax(ax3, "Risk Score Evolution — Greedy Switching Sequence")
steps = [h["step"] for h in greedy_history] risks = [h["risk"] for h in greedy_history] sheds = [h["load_shed"] for h in greedy_history]
ax3.fill_between(steps, risks, alpha=0.2, color=NEON_BLUE) ax3.plot(steps, risks, 'o-', color=NEON_BLUE, linewidth=2.5, markersize=8, label='System Risk Score', zorder=5) ax3b = ax3.twinx() ax3b.plot(steps, sheds, 's--', color=NEON_ORANGE, linewidth=2, markersize=7, label='Load Shed (MW)') ax3b.set_ylabel('Load Shed (MW)', color=NEON_ORANGE) ax3b.tick_params(colors=NEON_ORANGE)
for s in greedy_seq: ax3.annotate( f"Open L{s['line_idx']}\n({s['I_gic']:.0f}A)", xy=(s['step'], s['risk_after']), xytext=(s['step'] + 0.1, s['risk_after'] + risks[0] * 0.04), fontsize=7, color=NEON_GREEN, arrowprops=dict(arrowstyle='->', color=NEON_GREEN, lw=1) )
ax3.set_xlabel('Switching Step') ax3.set_ylabel('System Risk Score') lines1, labels1 = ax3.get_legend_handles_labels() lines2, labels2 = ax3b.get_legend_handles_labels() ax3.legend(lines1 + lines2, labels1 + labels2, facecolor=PANEL_BG, edgecolor='gray', labelcolor='white', fontsize=9, loc='upper right') ax3.set_xticks(steps)
ax4 = fig.add_subplot(gs[1, 2]) style_ax(ax4, "SA Optimization Convergence") if sa_history_cost: ax4.plot(sa_history_cost, color=NEON_PURPLE, linewidth=2) ax4.fill_between(range(len(sa_history_cost)), sa_history_cost, alpha=0.15, color=NEON_PURPLE) ax4.set_xlabel('SA Iteration (temperature step)') ax4.set_ylabel('Total Cost Function') ax4.axhline(y=min(sa_history_cost), color=NEON_GREEN, linestyle='--', linewidth=1.5, label=f'Best: {min(sa_history_cost):.1f}') ax4.legend(facecolor=PANEL_BG, edgecolor='gray', labelcolor='white', fontsize=8)
ax5 = fig.add_subplot(gs[2, 0]) style_ax(ax5, "Transformer Q Absorption vs GIC")
I_range = np.linspace(0, 200, 400) Q_curve = transformer_reactive_absorption(I_range) ax5.plot(I_range, Q_curve, color=NEON_ORANGE, linewidth=2.5) ax5.fill_between(I_range, Q_curve, alpha=0.15, color=NEON_ORANGE) ax5.axvline(x=50, color=NEON_RED, linestyle='--', linewidth=1.5, label='Warning: 50A') ax5.axvline(x=100, color=NEON_RED, linestyle='-', linewidth=2, label='Critical: 100A')
for idx, d in gic_data.items(): if d["I_gic"] > 20: ax5.scatter(d["I_gic"], transformer_reactive_absorption(d["I_gic"]), color=NEON_BLUE, s=50, zorder=5)
ax5.set_xlabel('GIC (A)') ax5.set_ylabel('Q Absorbed (MVAR)') ax5.legend(facecolor=PANEL_BG, edgecolor='gray', labelcolor='white', fontsize=8)
ax6 = fig.add_subplot(gs[2, 1]) style_ax(ax6, "Storm Intensity & System Risk Over Time")
t_storm, kp = simulate_storm_timeseries() risk_ts = [] for k in kp: gic_t = compute_gic(bus_data, lines, storm_intensity=k * 0.625) r, _, _, _ = compute_system_state(set(range(len(lines))), gic_t, bus_data) risk_ts.append(r)
ax6.fill_between(t_storm, kp, alpha=0.3, color=NEON_YELLOW) ax6.plot(t_storm, kp, color=NEON_YELLOW, linewidth=2, label='Kp Index') ax6b = ax6.twinx() ax6b.plot(t_storm, risk_ts, color=NEON_RED, linewidth=2, label='System Risk') ax6b.set_ylabel('System Risk Score', color=NEON_RED) ax6b.tick_params(colors=NEON_RED)
ax6.set_xlabel('Time (minutes)') ax6.set_ylabel('Kp Index', color=NEON_YELLOW) ax6.tick_params(colors=NEON_YELLOW) ax6.axvline(x=40, color=NEON_GREEN, linestyle='--', linewidth=1.5, label='Storm Peak (t=40 min)') lines_a, labels_a = ax6.get_legend_handles_labels() lines_b, labels_b = ax6b.get_legend_handles_labels() ax6.legend(lines_a + lines_b, labels_a + labels_b, facecolor=PANEL_BG, edgecolor='gray', labelcolor='white', fontsize=8)
ax7 = fig.add_subplot(gs[2, 2]) style_ax(ax7, "Per-Bus Risk Score")
all_lines_set = set(range(len(lines))) _, _, bus_risks_before, _ = compute_system_state(all_lines_set, gic_data, bus_data) _, _, bus_risks_after, _ = compute_system_state(active_lines_final, gic_data, bus_data)
bus_ids = list(bus_risks_before.keys()) r_before = [bus_risks_before[b] for b in bus_ids] r_after = [bus_risks_after[b] for b in bus_ids] x_pos = np.arange(len(bus_ids)) w = 0.35
ax7.barh(x_pos - w/2, r_before, w, label='Before', color=NEON_RED, alpha=0.8) ax7.barh(x_pos + w/2, r_after, w, label='After', color=NEON_GREEN, alpha=0.8) ax7.set_yticks(x_pos) ax7.set_yticklabels([bus_data[b]["name"].split()[0] for b in bus_ids], fontsize=7) ax7.set_xlabel('Risk Score') ax7.legend(facecolor=PANEL_BG, edgecolor='gray', labelcolor='white', fontsize=8)
ax8 = fig.add_subplot(gs[3, :2], projection='3d') ax8.set_facecolor(BG) ax8.set_title("3D Risk Landscape: Switching Steps × Bus Nodes × Risk Score", color='white', fontsize=11, fontweight='bold', pad=10)
n_steps = len(greedy_history) n_buses = len(bus_data) bus_list = list(bus_data.keys())
risk_matrix = np.zeros((n_steps, n_buses)) running_active = set(range(len(lines)))
for si, hist in enumerate(greedy_history): if si > 0 and hist["line_opened"] is not None: running_active.discard(hist["line_opened"]) _, _, br, _ = compute_system_state(running_active, gic_data, bus_data) for bi, b in enumerate(bus_list): risk_matrix[si, bi] = br[b]
X_3d = np.arange(n_steps) Y_3d = np.arange(n_buses) X_3d, Y_3d = np.meshgrid(X_3d, Y_3d) Z_3d = risk_matrix.T
surf = ax8.plot_surface(X_3d, Y_3d, Z_3d, cmap='plasma', alpha=0.85, edgecolor='none') ax8.set_xlabel('Switching Step', color='white', labelpad=8) ax8.set_ylabel('Bus Index', color='white', labelpad=8) ax8.set_zlabel('Risk Score', color='white', labelpad=8) ax8.tick_params(colors='#aaaaaa', labelsize=7) ax8.xaxis.pane.fill = False ax8.yaxis.pane.fill = False ax8.zaxis.pane.fill = False ax8.xaxis.pane.set_edgecolor('#333355') ax8.yaxis.pane.set_edgecolor('#333355') ax8.zaxis.pane.set_edgecolor('#333355') plt.colorbar(surf, ax=ax8, shrink=0.4, pad=0.08, label='Risk Score')
ax9 = fig.add_subplot(gs[3, 2]) style_ax(ax9, "Optimized Switching Sequence") ax9.axis('off')
greedy_order = [f"L{s['line_idx']} {s['from_bus'].split()[0]}↔{s['to_bus'].split()[0]}" for s in greedy_seq] sa_order = [f"L{li} {gic_data[li]['from']}↔{gic_data[li]['to']}" for li in sa_sequence]
table_data = [] for i in range(max(len(greedy_order), len(sa_order))): g = greedy_order[i] if i < len(greedy_order) else "—" s = sa_order[i] if i < len(sa_order) else "—" table_data.append([f"Step {i+1}", g, s])
if table_data: tbl = ax9.table( cellText = table_data, colLabels = ["Step", "Greedy Order", "SA-Optimized"], loc = 'center', cellLoc = 'center' ) tbl.auto_set_font_size(False) tbl.set_fontsize(8) tbl.scale(1, 1.6) for (row, col), cell in tbl.get_celld().items(): cell.set_facecolor(PANEL_BG if row > 0 else '#1a1a3e') cell.set_text_props(color='white') cell.set_edgecolor('#333355')
plt.suptitle( "⚡ Geomagnetic Storm Protection — Circuit Breaker Switching Sequence Optimizer", color='white', fontsize=15, fontweight='bold', y=0.995 ) plt.savefig('gic_optimizer.png', dpi=150, bbox_inches='tight', facecolor=fig.get_facecolor()) plt.show() print("Plot saved.")
print("=" * 65) print(" GIC Circuit Breaker Switching Sequence Optimizer") print("=" * 65)
gic_data = compute_gic(bus_data, lines, storm_direction_deg=315, storm_intensity=5.0)
print(f"\n[Storm Parameters]") print(f" Direction: 315° (Northwest → Southeast)") print(f" Intensity: 5.0 nT/min (dB/dt)") print(f"\n[GIC Summary]") print(f" {'Line':>4} {'From':>12} {'To':>12} {'Length(km)':>10} {'GIC(A)':>8}") print(f" {'-'*4} {'-'*12} {'-'*12} {'-'*10} {'-'*8}") for i, d in gic_data.items(): print(f" {i:>4} {bus_data[d['from']]['name']:>12} " f"{bus_data[d['to']]['name']:>12} " f"{d['length_km']:>10.1f} {d['I_gic']:>8.1f}")
all_active = set(range(len(lines))) risk0, shed0, bus_risks0, q0 = compute_system_state(all_active, gic_data, bus_data) print(f"\n[Baseline System State]") print(f" Total System Risk Score : {risk0:.2f}") print(f" Initial Load Shed : {shed0:.1f} MW") print(f" Total Q Absorbed : {q0:.1f} MVAR")
print("\n[Running Greedy Optimizer...]") greedy_seq, greedy_history, final_active = greedy_switching_sequence( gic_data, bus_data, n_switches=6)
print(f"\n[Greedy Switching Sequence]") for s in greedy_seq: print(f" Step {s['step']:>1}: Open L{s['line_idx']:>2} " f"({s['from_bus']:>12} ↔ {s['to_bus']:>12}) " f"GIC={s['I_gic']:5.1f}A " f"Risk: {s['risk_before']:.2f} → {s['risk_after']:.2f}")
risk_f, shed_f, _, q_f = compute_system_state(final_active, gic_data, bus_data) print(f"\n[After Greedy Switching]") print(f" System Risk Score : {risk_f:.2f} (reduction: {100*(risk0-risk_f)/risk0:.1f}%)") print(f" Load Shed : {shed_f:.1f} MW") print(f" Total Q Absorbed : {q_f:.1f} MVAR")
print("\n[Running Simulated Annealing Optimizer...]") sa_sequence, sa_history_cost = simulated_annealing_optimizer( gic_data, bus_data, greedy_seq, T_init=100.0, T_min=0.5, alpha=0.92, n_iter=400)
print(f"\n[SA-Optimized Switching Order]") for step, li in enumerate(sa_sequence): d = gic_data[li] print(f" Step {step+1}: Open L{li:>2} " f"({bus_data[d['from']]['name']:>12} ↔ {bus_data[d['to']]['name']:>12})")
if sa_history_cost: print(f"\n SA Cost: {sa_history_cost[0]:.2f} → {sa_history_cost[-1]:.2f} " f"(improvement: {100*(sa_history_cost[0]-sa_history_cost[-1])/sa_history_cost[0]:.1f}%)")
print("\n[Generating Visualizations...]") plot_all_results(gic_data, bus_data, greedy_seq, sa_sequence, greedy_history, sa_history_cost, final_active)
print("\n[Done] Optimization complete.")
|