Smart_Grid / app.py
hareshchander's picture
Update app.py
f04834b verified
Raw History Blame Contribute Delete
3.92 kB
import streamlit as st
import pandas as pd
import plotly.express as px
import torch
import torch.nn as nn
import numpy as np
from app_backend import fetch_weather, generate_synthetic_data, optimize_load
# ----------------------------
# Dummy PyTorch Model Definition
# ----------------------------
class GridStabilityModel(nn.Module):
def __init__(self):
super(GridStabilityModel, self).__init__()
self.net = nn.Sequential(
nn.Linear(3, 16),
nn.ReLU(),
nn.Linear(16, 8),
nn.ReLU(),
nn.Linear(8, 1),
nn.Sigmoid()
)
def forward(self, x):
return self.net(x)
# Load or instantiate model
model = GridStabilityModel()
model.eval() # Set model to eval mode
# Function to predict stability score using the model
def predict_stability(data):
# Select features for prediction
features = data[['load_demand_kwh', 'solar_output_kw', 'wind_output_kw']].values.astype(np.float32)
inputs = torch.tensor(features)
with torch.no_grad():
outputs = model(inputs).numpy().flatten()
# Average score as a simple indicator
stability_score = np.mean(outputs)
return stability_score
# ----------------------------
# Constants
# ----------------------------
API_KEY = "84e26811a314599e940f343b4d5894a7"
DEFAULT_LOCATION = "New York"
# Sidebar
st.sidebar.title("Real-Time Smart Grid Dashboard")
location = st.sidebar.text_input("Enter Location", DEFAULT_LOCATION)
# Fetch and display weather data
weather = fetch_weather(API_KEY, location)
if weather:
st.sidebar.write(f"Temperature: {weather['temperature']} °C")
st.sidebar.write(f"Wind Speed: {weather['wind_speed']} m/s")
st.sidebar.write(f"Weather: {weather['weather']}")
# Main dashboard title
st.title("AI Powered Smart Grid Dashboard for Integration Stability and Energy Trade")
# User upload section
uploaded_file = st.file_uploader("Upload your Smart Grid CSV file", type=["csv"])
if uploaded_file is not None:
data = pd.read_csv(uploaded_file)
st.success("File uploaded successfully!")
else:
st.info("No file uploaded. Using synthetic data for demonstration.")
data = generate_synthetic_data()
# Required columns check
required_columns = ["timestamp", "load_demand_kwh", "solar_output_kw", "wind_output_kw", "grid_health"]
if all(col in data.columns for col in required_columns):
# Plot load demand
fig_load = px.line(data, x="timestamp", y="load_demand_kwh", title="Load Demand Over Time")
st.plotly_chart(fig_load)
# Renewable energy contribution plot
fig_renew = px.bar(
data,
x="timestamp",
y=["solar_output_kw", "wind_output_kw"],
title="Renewable Energy Contributions",
labels={"value": "Power (kW)", "variable": "Energy Source"}
)
st.plotly_chart(fig_renew)
# Grid health overview
st.subheader("Grid Health Overview")
grid_health_counts = data["grid_health"].value_counts()
st.bar_chart(grid_health_counts)
# PyTorch model prediction - Stability score
stability_score = predict_stability(data)
st.subheader("Predicted Grid Stability Score (0=Low, 1=High)")
st.metric(label="Grid Stability Score", value=f"{stability_score:.3f}")
# Optimization recommendations based on last timestamp
current_demand = data["load_demand_kwh"].iloc[-1]
current_solar = data["solar_output_kw"].iloc[-1]
current_wind = data["wind_output_kw"].iloc[-1]
recommendation = optimize_load(current_demand, current_solar, current_wind)
st.subheader("Recommendations")
st.write(f"Current Load Demand: {current_demand} kWh")
st.write(f"Solar Output: {current_solar} kW")
st.write(f"Wind Output: {current_wind} kW")
st.write(f"Recommendation: {recommendation}")
else:
st.error(f"The uploaded data is missing one or more required columns: {required_columns}")