File size: 20,389 Bytes
1c64c37 63a8d36 1c64c37 | 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 | import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
from datetime import datetime, timedelta
import random
# Set page configuration
st.set_page_config(
page_title="Smart Grid Management System",
page_icon="⚡",
layout="wide",
)
# Custom CSS to improve the appearance
st.markdown("""
<style>
.main {
padding: 20px;
}
.stButton button {
width: 100%;
}
.agent-level {
background-color: #f0f2f6;
padding: 20px;
border-radius: 10px;
margin-bottom: 20px;
}
.metrics-container {
display: flex;
justify-content: space-between;
}
</style>
""", unsafe_allow_html=True)
# Sidebar for controls
st.sidebar.title("Smart Grid Controls")
ai_level = st.sidebar.slider("AI Agent Level", 0, 4, 0)
simulation_speed = st.sidebar.slider("Simulation Speed", 1, 10, 5)
weather_condition = st.sidebar.selectbox(
"Weather Condition",
["Sunny", "Partially Cloudy", "Cloudy", "Rainy", "Stormy"]
)
# Initialize state
if 'initialized' not in st.session_state:
st.session_state.initialized = True
st.session_state.current_time = datetime.now()
st.session_state.power_demand = 800
st.session_state.renewable_output = 300
st.session_state.conventional_output = 500
st.session_state.battery_charge = 50
st.session_state.grid_stability = 95
st.session_state.electricity_price = 0.12
st.session_state.demand_history = [800]
st.session_state.renewable_history = [300]
st.session_state.conventional_history = [500]
st.session_state.price_history = [0.12]
st.session_state.stability_history = [95]
st.session_state.logs = ["System initialized"]
st.session_state.alerts = []
st.session_state.optimizations = []
st.session_state.cumulative_cost = 0
st.session_state.cumulative_emissions = 0
st.session_state.renewable_percentage = 37.5
st.session_state.last_update = time.time()
# Helper functions
def get_weather_impact(condition):
impacts = {
"Sunny": 1.0,
"Partially Cloudy": 0.7,
"Cloudy": 0.4,
"Rainy": 0.3,
"Stormy": 0.2
}
return impacts.get(condition, 0.5)
def update_system_state():
# Calculate time delta
current_time = time.time()
if current_time - st.session_state.last_update < 0.1 / simulation_speed:
return
st.session_state.last_update = current_time
# Update time
st.session_state.current_time += timedelta(minutes=15)
hour = st.session_state.current_time.hour
# Simulate demand changes (daily pattern + random fluctuation)
demand_pattern = 700 + 200 * np.sin(np.pi * hour / 12)
demand_noise = random.normalvariate(0, 50)
new_demand = max(500, min(1200, demand_pattern + demand_noise))
# Weather impact on renewables
weather_factor = get_weather_impact(weather_condition)
time_factor = 0.5 + 0.5 * np.sin(np.pi * (hour - 6) / 12) if 6 <= hour <= 18 else 0.1
base_renewable = 500 * time_factor * weather_factor
renewable_noise = random.normalvariate(0, 30)
new_renewable = max(50, min(700, base_renewable + renewable_noise))
# Default conventional power (no AI)
new_conventional = max(300, min(1000, new_demand - new_renewable))
# Apply AI agent logic based on level
logs = []
alerts = []
optimizations = []
if ai_level >= 1:
# Level 1: Basic adjustments
if new_demand > new_renewable + new_conventional:
deficit = new_demand - (new_renewable + new_conventional)
if st.session_state.battery_charge > 10:
battery_contribution = min(deficit, st.session_state.battery_charge * 2)
new_conventional -= battery_contribution / 2
st.session_state.battery_charge -= battery_contribution / 2
logs.append(f"L1: Used {battery_contribution/2:.1f} MW from battery storage")
else:
new_conventional = new_demand - new_renewable
logs.append("L1: Increased conventional generation to meet demand")
elif new_renewable + new_conventional > new_demand + 100:
excess = (new_renewable + new_conventional) - new_demand
if st.session_state.battery_charge < 90:
charge_amount = min(excess, (100 - st.session_state.battery_charge) * 2)
new_conventional -= charge_amount / 2
st.session_state.battery_charge += charge_amount / 2
logs.append(f"L1: Charged battery with {charge_amount/2:.1f} MW of excess power")
else:
new_conventional = max(300, new_demand - new_renewable)
logs.append("L1: Reduced conventional generation due to excess supply")
if ai_level >= 2:
# Level 2: Structured reasoning
time_of_day = "peak" if 9 <= hour <= 20 else "off-peak"
weather_outlook = "favorable" if weather_factor > 0.6 else "unfavorable"
if time_of_day == "peak" and weather_outlook == "unfavorable":
if st.session_state.battery_charge > 30:
battery_contribution = st.session_state.battery_charge * 0.3
new_conventional -= battery_contribution
st.session_state.battery_charge -= battery_contribution / 2
logs.append(f"L2: Strategic battery discharge of {battery_contribution:.1f} MW during peak hours")
else:
new_conventional = new_demand - new_renewable
alerts.append("L2: Peak demand expected with low renewable generation. Grid stress likely.")
elif time_of_day == "off-peak" and weather_outlook == "favorable":
if st.session_state.battery_charge < 70:
excess_renewable = max(0, new_renewable - (new_demand * 0.6))
charge_amount = min(excess_renewable, (100 - st.session_state.battery_charge) * 2)
st.session_state.battery_charge += charge_amount / 2
logs.append(f"L2: Strategic battery charging of {charge_amount:.1f} MW during favorable conditions")
# Price optimization
if time_of_day == "peak":
price_adjustment = 0.04
else:
price_adjustment = -0.02
optimizations.append(f"L2: Calculated optimal power mix based on time ({time_of_day}) and weather ({weather_outlook})")
if ai_level >= 3:
# Level 3: Autonomous actions
forecast_hours = 6
predicted_demand = []
predicted_renewable = []
# Simple forecasting (in a real system this would use ML models)
for i in range(forecast_hours):
future_hour = (hour + i) % 24
pred_demand = 700 + 200 * np.sin(np.pi * future_hour / 12) + random.normalvariate(0, 20)
future_weather = weather_factor * (0.9 + 0.2 * random.random())
future_time_factor = 0.5 + 0.5 * np.sin(np.pi * (future_hour - 6) / 12) if 6 <= future_hour <= 18 else 0.1
pred_renewable = 500 * future_time_factor * future_weather + random.normalvariate(0, 10)
predicted_demand.append(pred_demand)
predicted_renewable.append(pred_renewable)
# Look for upcoming supply-demand mismatches
future_deficit = sum(max(0, d - r) for d, r in zip(predicted_demand, predicted_renewable))
future_excess = sum(max(0, r - d) for d, r in zip(predicted_demand, predicted_renewable))
if future_deficit > 500 and st.session_state.battery_charge < 50:
# Preemptively generate more power to charge batteries
new_conventional += 50
st.session_state.battery_charge += 5
logs.append("L3: Preemptive battery charging based on forecasted deficit")
optimizations.append("L3: Initiated demand response program for industrial customers")
if future_excess > 300 and st.session_state.battery_charge > 60:
# Reduce conventional generation in anticipation of excess renewables
new_conventional = max(250, new_conventional - 100)
logs.append("L3: Reduced conventional generation based on forecasted renewable surplus")
# Autonomous grid reconfiguration
if random.random() < 0.1: # Occasional grid optimizations
stability_improvement = random.uniform(0.5, 2.0)
st.session_state.grid_stability = min(99, st.session_state.grid_stability + stability_improvement)
logs.append(f"L3: Autonomous grid reconfiguration improved stability by {stability_improvement:.1f}%")
# Dynamic pricing
if new_demand > 900:
price_adjustment = 0.08
logs.append("L3: Implemented dynamic pricing to reduce peak demand")
elif new_demand < 600:
price_adjustment = -0.04
logs.append("L3: Lowered prices to encourage consumption during surplus")
if ai_level >= 4:
# Level 4: Self-improving AI
# Simulate AI creating new optimization strategies
if random.random() < 0.15: # Occasional new strategy discovery
strategy_types = [
"Discovered micro-grid isolation pattern to improve efficiency",
"Created new demand forecasting model with 12% improved accuracy",
"Developed adaptive battery cycling algorithm to extend storage life",
"Generated new load balancing technique for industrial customers",
"Created virtual power plant configuration using distributed resources"
]
new_strategy = random.choice(strategy_types)
optimizations.append(f"L4: {new_strategy}")
# Apply benefits of the new strategy
improvement_factor = random.uniform(0.05, 0.15)
if "forecasting" in new_strategy:
# Better prediction leads to better conventional power setting
new_conventional = max(250, min(1000, (new_demand - new_renewable) * (1 - improvement_factor)))
elif "battery" in new_strategy:
# Better battery management
st.session_state.battery_charge += 5
elif "load balancing" in new_strategy:
# Improved demand management
new_demand = max(500, new_demand * (1 - improvement_factor))
elif "micro-grid" in new_strategy or "virtual power plant" in new_strategy:
# Improved grid efficiency
new_conventional = max(250, new_conventional * (1 - improvement_factor))
st.session_state.grid_stability += random.uniform(1.0, 3.0)
# Self-optimization of pricing algorithms
base_price = 0.10
factors = {
"demand_factor": 0.00015 * new_demand,
"renewable_factor": -0.0002 * new_renewable,
"stability_factor": -0.0005 * max(0, st.session_state.grid_stability - 90),
"time_factor": 0.03 if 9 <= hour <= 20 else -0.01,
"battery_factor": -0.0003 * st.session_state.battery_charge
}
price_adjustment = sum(factors.values())
# Occasionally generate new pricing components
if random.random() < 0.1:
new_factor_name = random.choice([
"consumer behavior model",
"predictive demand response",
"grid congestion mapping",
"energy market arbitrage"
])
new_factor_value = random.uniform(-0.02, 0.02)
logs.append(f"L4: Developed new pricing component: {new_factor_name}")
price_adjustment += new_factor_value
# Apply changes to the system
st.session_state.power_demand = new_demand
st.session_state.renewable_output = new_renewable
st.session_state.conventional_output = new_conventional
# Calculate price, emissions, and costs
base_price = 0.10
if ai_level < 2:
price_adjustment = 0.02 if 9 <= hour <= 20 else -0.01 # Simple time-of-use pricing
new_price = max(0.05, min(0.30, base_price + price_adjustment))
st.session_state.electricity_price = new_price
# Calculate stability based on supply-demand balance
imbalance = abs((new_renewable + new_conventional) - new_demand)
stability_impact = -0.1 * imbalance / new_demand
# Higher AI levels manage stability better
if ai_level >= 2:
stability_impact *= (1 - (ai_level * 0.2))
st.session_state.grid_stability = max(60, min(99.9, st.session_state.grid_stability + stability_impact))
# Calculate emissions and costs
emissions_rate = 0.5 # tons CO2 per MWh from conventional
hourly_emissions = new_conventional * emissions_rate * (15/60) # For 15-minute intervals
hourly_cost = (new_conventional * 30 + new_renewable * 5) * (15/60) # $30/MWh conventional, $5/MWh renewable
st.session_state.cumulative_emissions += hourly_emissions
st.session_state.cumulative_cost += hourly_cost
# Calculate renewable percentage
st.session_state.renewable_percentage = 100 * new_renewable / (new_renewable + new_conventional)
# Update histories
st.session_state.demand_history.append(new_demand)
st.session_state.renewable_history.append(new_renewable)
st.session_state.conventional_history.append(new_conventional)
st.session_state.price_history.append(new_price)
st.session_state.stability_history.append(st.session_state.grid_stability)
# Keep histories at a reasonable length
max_history = 100
if len(st.session_state.demand_history) > max_history:
st.session_state.demand_history = st.session_state.demand_history[-max_history:]
st.session_state.renewable_history = st.session_state.renewable_history[-max_history:]
st.session_state.conventional_history = st.session_state.conventional_history[-max_history:]
st.session_state.price_history = st.session_state.price_history[-max_history:]
st.session_state.stability_history = st.session_state.stability_history[-max_history:]
# Update logs
st.session_state.logs = logs + st.session_state.logs
if len(st.session_state.logs) > 20:
st.session_state.logs = st.session_state.logs[:20]
st.session_state.alerts = alerts
st.session_state.optimizations = optimizations
# Main dashboard
st.title("⚡ Smart Grid Management System")
# Display current time and simulation level
col1, col2, col3 = st.columns(3)
with col1:
st.subheader(f"Current Time: {st.session_state.current_time.strftime('%Y-%m-%d %H:%M')}")
with col2:
st.subheader(f"Weather: {weather_condition}")
with col3:
st.subheader(f"AI Agent Level: {ai_level}")
# Key Metrics
st.subheader("Grid Status")
metrics_col1, metrics_col2, metrics_col3, metrics_col4 = st.columns(4)
with metrics_col1:
st.metric("Power Demand (MW)", f"{st.session_state.power_demand:.1f}")
with metrics_col2:
st.metric("Renewable Output (MW)", f"{st.session_state.renewable_output:.1f}",
f"{st.session_state.renewable_percentage:.1f}%")
with metrics_col3:
st.metric("Conventional Output (MW)", f"{st.session_state.conventional_output:.1f}")
with metrics_col4:
# stability_color = "green" if st.session_state.grid_stability > 95 else "orange" if st.session_state.grid_stability > 85 else "red"
# st.metric("Grid Stability (%)", f"{st.session_state.grid_stability:.1f}",
# delta_color=stability_color)
stability_delta = "+" if st.session_state.grid_stability > 95 else "-"
stability_delta_value = f"{stability_delta}{abs(95 - st.session_state.grid_stability):.1f}"
stability_delta_color = "normal" if st.session_state.grid_stability > 90 else "inverse"
st.metric("Grid Stability (%)", f"{st.session_state.grid_stability:.1f}",
delta=stability_delta_value, delta_color=stability_delta_color)
# Second row of metrics
metrics2_col1, metrics2_col2, metrics2_col3, metrics2_col4 = st.columns(4)
with metrics2_col1:
st.metric("Electricity Price ($/kWh)", f"${st.session_state.electricity_price:.3f}")
with metrics2_col2:
st.metric("Battery Charge (%)", f"{st.session_state.battery_charge:.1f}")
with metrics2_col3:
st.metric("Cumulative Cost ($)", f"${st.session_state.cumulative_cost:,.2f}")
with metrics2_col4:
st.metric("CO2 Emissions (tons)", f"{st.session_state.cumulative_emissions:.1f}")
# Charts
charts_col1, charts_col2 = st.columns(2)
with charts_col1:
st.subheader("Power Generation and Demand")
fig, ax = plt.subplots(figsize=(10, 4))
x = range(len(st.session_state.demand_history))
ax.plot(x, st.session_state.demand_history, label="Demand", color="red")
ax.plot(x, st.session_state.renewable_history, label="Renewable", color="green")
ax.plot(x, st.session_state.conventional_history, label="Conventional", color="gray")
ax.legend()
st.pyplot(fig)
with charts_col2:
st.subheader("Grid Stability and Pricing")
fig2, ax2 = plt.subplots(figsize=(10, 4))
ax2.plot(x, st.session_state.stability_history, label="Stability %", color="blue")
ax2_twin = ax2.twinx()
ax2_twin.plot(x, st.session_state.price_history, label="Price $/kWh", color="purple")
ax2.legend(loc="upper left")
ax2_twin.legend(loc="upper right")
st.pyplot(fig2)
# AI Agent Information based on level
st.subheader(f"AI Agent Level {ai_level} Operations")
if ai_level == 0:
st.markdown("""
**L0: Data Collection Only**
- Monitoring grid status without decision-making ability
- Displaying real-time data from sensors and meters
- Providing raw data for human operators to make decisions
- No automated analysis or recommendations
""")
elif ai_level == 1:
st.markdown("""
**L1: Basic Tool Use & Simple Decision-Making**
- Performing simple analysis of grid conditions
- Making basic adjustments to conventional generation
- Managing basic battery charging/discharging
- Providing simple alerts and recommendations to operators
""")
elif ai_level == 2:
st.markdown("""
**L2: Structured Reasoning & Sequential Planning**
- Analyzing patterns across multiple data sources
- Creating sequential plans for grid optimization
- Considering weather forecasts in generation planning
- Implementing time-of-use pricing optimization
- Coordinating battery storage with renewable generation
""")
elif ai_level == 3:
st.markdown("""
**L3: Autonomous Actions & Proactive Management**
- Autonomously balancing grid without human intervention
- Implementing demand response programs during peak times
- Proactively preparing for forecasted supply/demand mismatches
- Dynamically adjusting grid configuration for optimal power flow
- Managing distributed energy resources as a virtual power plant
""")
else: # Level 4
st.markdown("""
**L4: Self-Improving System & Workflow Creation**
- Creating and testing new optimization strategies
- Continuously improving forecasting models
- Developing novel pricing mechanisms for demand management
- Optimizing grid topology configurations autonomously
- Learning from past decisions to improve future performance
- Creating specialized workflows for different grid conditions
""")
# Agent actions and logs
log_col1, log_col2 = st.columns(2)
with log_col1:
st.subheader("Recent AI Actions")
if not st.session_state.logs:
st.info("No recent actions")
else:
for log in st.session_state.logs:
st.text(f"• {log}")
with log_col2:
# Alerts
if st.session_state.alerts:
st.subheader("⚠️ Alerts")
for alert in st.session_state.alerts:
st.warning(alert)
# Optimizations
if st.session_state.optimizations:
st.subheader("🔄 Optimizations")
for opt in st.session_state.optimizations:
st.info(opt)
# Update system state
update_system_state()
# Add auto-refresh capability
if simulation_speed > 0:
time.sleep(20.0 / simulation_speed)
st.rerun()
#st.experimental_rerun()
|