Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,92 +1,116 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
import torch
|
| 3 |
-
import torch.nn as nn
|
| 4 |
import pandas as pd
|
| 5 |
-
import joblib
|
| 6 |
import plotly.express as px
|
| 7 |
-
import
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
def forward(self, x):
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
hidden_size = 32
|
| 33 |
-
output_size = 2
|
| 34 |
-
|
| 35 |
-
model = SimpleNN(input_size, hidden_size, output_size)
|
| 36 |
-
model.load_state_dict(torch.load("model.pth", map_location=torch.device('cpu')))
|
| 37 |
-
model.eval()
|
| 38 |
-
|
| 39 |
-
scaler = joblib.load("scaler.pkl")
|
| 40 |
-
return model, scaler
|
| 41 |
-
|
| 42 |
-
# -----------------------------
|
| 43 |
-
# Prediction Function
|
| 44 |
-
# -----------------------------
|
| 45 |
-
def make_prediction(data, model, scaler):
|
| 46 |
-
expected_columns = ['Voltage', 'Current', 'Frequency', 'Load', 'Power_Factor', 'Temperature']
|
| 47 |
-
if not all(col in data.columns for col in expected_columns):
|
| 48 |
-
missing_cols = list(set(expected_columns) - set(data.columns))
|
| 49 |
-
st.error(f"Missing columns: {missing_cols}")
|
| 50 |
-
return None
|
| 51 |
-
|
| 52 |
-
X = scaler.transform(data[expected_columns])
|
| 53 |
-
inputs = torch.tensor(X, dtype=torch.float32)
|
| 54 |
with torch.no_grad():
|
| 55 |
-
outputs = model(inputs)
|
| 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 |
else:
|
| 92 |
-
st.
|
|
|
|
| 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 numpy as np
|
| 7 |
+
|
| 8 |
+
from app_backend import fetch_weather, generate_synthetic_data, optimize_load
|
| 9 |
+
|
| 10 |
+
# ----------------------------
|
| 11 |
+
# Dummy PyTorch Model Definition
|
| 12 |
+
# ----------------------------
|
| 13 |
+
class GridStabilityModel(nn.Module):
|
| 14 |
+
def __init__(self):
|
| 15 |
+
super(GridStabilityModel, self).__init__()
|
| 16 |
+
self.net = nn.Sequential(
|
| 17 |
+
nn.Linear(3, 16),
|
| 18 |
+
nn.ReLU(),
|
| 19 |
+
nn.Linear(16, 8),
|
| 20 |
+
nn.ReLU(),
|
| 21 |
+
nn.Linear(8, 1),
|
| 22 |
+
nn.Sigmoid()
|
| 23 |
+
)
|
| 24 |
|
| 25 |
def forward(self, x):
|
| 26 |
+
return self.net(x)
|
| 27 |
+
|
| 28 |
+
# Load or instantiate model
|
| 29 |
+
model = GridStabilityModel()
|
| 30 |
+
model.eval() # Set model to eval mode
|
| 31 |
+
|
| 32 |
+
# Function to predict stability score using the model
|
| 33 |
+
def predict_stability(data):
|
| 34 |
+
# Select features for prediction
|
| 35 |
+
features = data[['load_demand_kwh', 'solar_output_kw', 'wind_output_kw']].values.astype(np.float32)
|
| 36 |
+
inputs = torch.tensor(features)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
with torch.no_grad():
|
| 38 |
+
outputs = model(inputs).numpy().flatten()
|
| 39 |
+
# Average score as a simple indicator
|
| 40 |
+
stability_score = np.mean(outputs)
|
| 41 |
+
return stability_score
|
| 42 |
+
|
| 43 |
+
# ----------------------------
|
| 44 |
+
# Constants
|
| 45 |
+
# ----------------------------
|
| 46 |
+
API_KEY = "84e26811a314599e940f343b4d5894a7"
|
| 47 |
+
DEFAULT_LOCATION = "New York"
|
| 48 |
+
|
| 49 |
+
# Sidebar
|
| 50 |
+
st.sidebar.title("Smart Grid Dashboard")
|
| 51 |
+
location = st.sidebar.text_input("Enter Location", DEFAULT_LOCATION)
|
| 52 |
+
|
| 53 |
+
# Fetch and display weather data
|
| 54 |
+
weather = fetch_weather(API_KEY, location)
|
| 55 |
+
if weather:
|
| 56 |
+
st.sidebar.write(f"Temperature: {weather['temperature']} °C")
|
| 57 |
+
st.sidebar.write(f"Wind Speed: {weather['wind_speed']} m/s")
|
| 58 |
+
st.sidebar.write(f"Weather: {weather['weather']}")
|
| 59 |
+
|
| 60 |
+
# Main dashboard title
|
| 61 |
+
st.title("Real-Time Smart Grid Dashboard")
|
| 62 |
+
|
| 63 |
+
# User upload section
|
| 64 |
+
uploaded_file = st.file_uploader("Upload your Smart Grid CSV file", type=["csv"])
|
| 65 |
+
|
| 66 |
+
if uploaded_file is not None:
|
| 67 |
+
data = pd.read_csv(uploaded_file)
|
| 68 |
+
st.success("File uploaded successfully!")
|
| 69 |
+
else:
|
| 70 |
+
st.info("No file uploaded. Using synthetic data for demonstration.")
|
| 71 |
+
data = generate_synthetic_data()
|
| 72 |
+
|
| 73 |
+
# Required columns check
|
| 74 |
+
required_columns = ["timestamp", "load_demand_kwh", "solar_output_kw", "wind_output_kw", "grid_health"]
|
| 75 |
+
|
| 76 |
+
if all(col in data.columns for col in required_columns):
|
| 77 |
+
|
| 78 |
+
# Plot load demand
|
| 79 |
+
fig_load = px.line(data, x="timestamp", y="load_demand_kwh", title="Load Demand Over Time")
|
| 80 |
+
st.plotly_chart(fig_load)
|
| 81 |
+
|
| 82 |
+
# Renewable energy contribution plot
|
| 83 |
+
fig_renew = px.bar(
|
| 84 |
+
data,
|
| 85 |
+
x="timestamp",
|
| 86 |
+
y=["solar_output_kw", "wind_output_kw"],
|
| 87 |
+
title="Renewable Energy Contributions",
|
| 88 |
+
labels={"value": "Power (kW)", "variable": "Energy Source"}
|
| 89 |
+
)
|
| 90 |
+
st.plotly_chart(fig_renew)
|
| 91 |
+
|
| 92 |
+
# Grid health overview
|
| 93 |
+
st.subheader("Grid Health Overview")
|
| 94 |
+
grid_health_counts = data["grid_health"].value_counts()
|
| 95 |
+
st.bar_chart(grid_health_counts)
|
| 96 |
+
|
| 97 |
+
# PyTorch model prediction - Stability score
|
| 98 |
+
stability_score = predict_stability(data)
|
| 99 |
+
|
| 100 |
+
st.subheader("Predicted Grid Stability Score (0=Low, 1=High)")
|
| 101 |
+
st.metric(label="Grid Stability Score", value=f"{stability_score:.3f}")
|
| 102 |
+
|
| 103 |
+
# Optimization recommendations based on last timestamp
|
| 104 |
+
current_demand = data["load_demand_kwh"].iloc[-1]
|
| 105 |
+
current_solar = data["solar_output_kw"].iloc[-1]
|
| 106 |
+
current_wind = data["wind_output_kw"].iloc[-1]
|
| 107 |
+
recommendation = optimize_load(current_demand, current_solar, current_wind)
|
| 108 |
+
|
| 109 |
+
st.subheader("Recommendations")
|
| 110 |
+
st.write(f"Current Load Demand: {current_demand} kWh")
|
| 111 |
+
st.write(f"Solar Output: {current_solar} kW")
|
| 112 |
+
st.write(f"Wind Output: {current_wind} kW")
|
| 113 |
+
st.write(f"Recommendation: {recommendation}")
|
| 114 |
+
|
| 115 |
else:
|
| 116 |
+
st.error(f"The uploaded data is missing one or more required columns: {required_columns}")
|