Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,41 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
import plotly.express as px
|
|
|
|
|
|
|
|
|
|
| 4 |
from app_backend import fetch_weather, generate_synthetic_data, optimize_load
|
| 5 |
|
| 6 |
# Constants
|
| 7 |
API_KEY = "84e26811a314599e940f343b4d5894a7"
|
| 8 |
DEFAULT_LOCATION = "New York"
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
# Sidebar
|
| 11 |
st.sidebar.title("Smart Grid Dashboard")
|
| 12 |
location = st.sidebar.text_input("Enter Location", DEFAULT_LOCATION)
|
|
@@ -21,45 +50,61 @@ if weather:
|
|
| 21 |
# Main dashboard title
|
| 22 |
st.title("Real-Time Smart Grid Dashboard")
|
| 23 |
|
| 24 |
-
#
|
| 25 |
uploaded_file = st.file_uploader("Upload your Smart Grid CSV file", type=["csv"])
|
| 26 |
|
| 27 |
if uploaded_file is not None:
|
| 28 |
-
# Read uploaded CSV into DataFrame
|
| 29 |
data = pd.read_csv(uploaded_file)
|
| 30 |
st.success("File uploaded successfully!")
|
| 31 |
else:
|
| 32 |
-
# No file uploaded, fallback to synthetic data
|
| 33 |
st.info("No file uploaded. Using synthetic data for demonstration.")
|
| 34 |
data = generate_synthetic_data()
|
| 35 |
|
| 36 |
-
|
| 37 |
-
required_columns = ["timestamp", "load_demand_kwh", "solar_output_kw", "wind_output_kw", "grid_health"]
|
| 38 |
if all(col in data.columns for col in required_columns):
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
fig_load = px.line(data, x="timestamp", y="
|
| 42 |
st.plotly_chart(fig_load)
|
| 43 |
|
| 44 |
-
# Renewable energy contribution plot
|
| 45 |
fig_renew = px.bar(
|
| 46 |
data,
|
| 47 |
x="timestamp",
|
| 48 |
-
y=["
|
| 49 |
title="Renewable Energy Contributions",
|
| 50 |
labels={"value": "Power (kW)", "variable": "Energy Source"}
|
| 51 |
)
|
| 52 |
st.plotly_chart(fig_renew)
|
| 53 |
|
| 54 |
-
# Grid health overview
|
| 55 |
st.subheader("Grid Health Overview")
|
| 56 |
grid_health_counts = data["grid_health"].value_counts()
|
| 57 |
st.bar_chart(grid_health_counts)
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
# Optimization recommendations based on last timestamp
|
| 60 |
-
current_demand = data["
|
| 61 |
-
current_solar = data["
|
| 62 |
-
current_wind = data["
|
| 63 |
recommendation = optimize_load(current_demand, current_solar, current_wind)
|
| 64 |
|
| 65 |
st.subheader("Recommendations")
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
import plotly.express as px
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import joblib
|
| 7 |
from app_backend import fetch_weather, generate_synthetic_data, optimize_load
|
| 8 |
|
| 9 |
# Constants
|
| 10 |
API_KEY = "84e26811a314599e940f343b4d5894a7"
|
| 11 |
DEFAULT_LOCATION = "New York"
|
| 12 |
|
| 13 |
+
# Define your PyTorch model architecture (match what you trained)
|
| 14 |
+
class GridModel(nn.Module):
|
| 15 |
+
def __init__(self):
|
| 16 |
+
super(GridModel, self).__init__()
|
| 17 |
+
self.layers = nn.Sequential(
|
| 18 |
+
nn.Linear(5, 16),
|
| 19 |
+
nn.ReLU(),
|
| 20 |
+
nn.Linear(16, 8),
|
| 21 |
+
nn.ReLU(),
|
| 22 |
+
nn.Linear(8, 1),
|
| 23 |
+
nn.Sigmoid()
|
| 24 |
+
)
|
| 25 |
+
def forward(self, x):
|
| 26 |
+
return self.layers(x)
|
| 27 |
+
|
| 28 |
+
# Load scaler and model once
|
| 29 |
+
@st.cache_resource
|
| 30 |
+
def load_model_and_scaler():
|
| 31 |
+
scaler = joblib.load("scaler.pkl")
|
| 32 |
+
model = GridModel()
|
| 33 |
+
model.load_state_dict(torch.load("model.pth", map_location=torch.device('cpu')))
|
| 34 |
+
model.eval()
|
| 35 |
+
return model, scaler
|
| 36 |
+
|
| 37 |
+
model, scaler = load_model_and_scaler()
|
| 38 |
+
|
| 39 |
# Sidebar
|
| 40 |
st.sidebar.title("Smart Grid Dashboard")
|
| 41 |
location = st.sidebar.text_input("Enter Location", DEFAULT_LOCATION)
|
|
|
|
| 50 |
# Main dashboard title
|
| 51 |
st.title("Real-Time Smart Grid Dashboard")
|
| 52 |
|
| 53 |
+
# User upload section
|
| 54 |
uploaded_file = st.file_uploader("Upload your Smart Grid CSV file", type=["csv"])
|
| 55 |
|
| 56 |
if uploaded_file is not None:
|
|
|
|
| 57 |
data = pd.read_csv(uploaded_file)
|
| 58 |
st.success("File uploaded successfully!")
|
| 59 |
else:
|
|
|
|
| 60 |
st.info("No file uploaded. Using synthetic data for demonstration.")
|
| 61 |
data = generate_synthetic_data()
|
| 62 |
|
| 63 |
+
required_columns = ["timestamp", "voltage", "frequency", "load", "solar_gen", "wind_gen", "grid_health"]
|
|
|
|
| 64 |
if all(col in data.columns for col in required_columns):
|
| 65 |
|
| 66 |
+
# Show plots (adjust columns if needed)
|
| 67 |
+
fig_load = px.line(data, x="timestamp", y="load", title="Load Over Time")
|
| 68 |
st.plotly_chart(fig_load)
|
| 69 |
|
|
|
|
| 70 |
fig_renew = px.bar(
|
| 71 |
data,
|
| 72 |
x="timestamp",
|
| 73 |
+
y=["solar_gen", "wind_gen"],
|
| 74 |
title="Renewable Energy Contributions",
|
| 75 |
labels={"value": "Power (kW)", "variable": "Energy Source"}
|
| 76 |
)
|
| 77 |
st.plotly_chart(fig_renew)
|
| 78 |
|
|
|
|
| 79 |
st.subheader("Grid Health Overview")
|
| 80 |
grid_health_counts = data["grid_health"].value_counts()
|
| 81 |
st.bar_chart(grid_health_counts)
|
| 82 |
|
| 83 |
+
# Prepare features for model prediction
|
| 84 |
+
features = data[['voltage', 'frequency', 'load', 'solar_gen', 'wind_gen']].values
|
| 85 |
+
X_scaled = scaler.transform(features)
|
| 86 |
+
inputs = torch.tensor(X_scaled, dtype=torch.float32)
|
| 87 |
+
|
| 88 |
+
# Run model prediction
|
| 89 |
+
with torch.no_grad():
|
| 90 |
+
outputs = model(inputs).numpy().flatten()
|
| 91 |
+
|
| 92 |
+
# Compute average output as stability metric
|
| 93 |
+
avg_output = outputs.mean()
|
| 94 |
+
if avg_output < 0.4:
|
| 95 |
+
status = "Unstable"
|
| 96 |
+
elif avg_output < 0.7:
|
| 97 |
+
status = "Warning"
|
| 98 |
+
else:
|
| 99 |
+
status = "Stable"
|
| 100 |
+
|
| 101 |
+
st.subheader("Grid Stability Prediction")
|
| 102 |
+
st.write(f"Predicted Grid Stability Status: **{status}** (Confidence: {avg_output:.2f})")
|
| 103 |
+
|
| 104 |
# Optimization recommendations based on last timestamp
|
| 105 |
+
current_demand = data["load"].iloc[-1]
|
| 106 |
+
current_solar = data["solar_gen"].iloc[-1]
|
| 107 |
+
current_wind = data["wind_gen"].iloc[-1]
|
| 108 |
recommendation = optimize_load(current_demand, current_solar, current_wind)
|
| 109 |
|
| 110 |
st.subheader("Recommendations")
|