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(""" """, 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()