hareshchander commited on
Commit
704d527
·
verified ·
1 Parent(s): a52a784

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -85
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 os
8
-
9
- # -----------------------------
10
- # Model Definition
11
- # -----------------------------
12
- class SimpleNN(nn.Module):
13
- def __init__(self, input_size, hidden_size, output_size):
14
- super(SimpleNN, self).__init__()
15
- self.fc1 = nn.Linear(input_size, hidden_size)
16
- self.relu = nn.ReLU()
17
- self.fc2 = nn.Linear(hidden_size, output_size)
18
- self.softmax = nn.Softmax(dim=1)
 
 
 
 
 
 
 
 
19
 
20
  def forward(self, x):
21
- out = self.fc1(x)
22
- out = self.relu(out)
23
- out = self.fc2(out)
24
- return self.softmax(out)
25
-
26
- # -----------------------------
27
- # Load Model and Scaler
28
- # -----------------------------
29
- @st.cache_resource
30
- def load_model_and_scaler():
31
- input_size = 6
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
- predicted = torch.argmax(outputs, dim=1).numpy()
57
-
58
- data['Outage_Prediction'] = ['No Outage' if p == 0 else 'Line Outage' for p in predicted]
59
- return data
60
-
61
- # -----------------------------
62
- # Streamlit UI
63
- # -----------------------------
64
- st.set_page_config(page_title="Smart Grid Outage Predictor", layout="centered")
65
- st.title("🔌 Smart Grid Line Outage Detection")
66
- st.write("Upload smart grid sensor data to detect possible line outages using a PyTorch model.")
67
-
68
- uploaded_file = st.file_uploader("📂 Upload your smart grid CSV file", type=["csv"])
69
-
70
- if uploaded_file:
71
- try:
72
- df = pd.read_csv(uploaded_file)
73
- st.subheader("📊 Uploaded Data")
74
- st.dataframe(df.head())
75
-
76
- model, scaler = load_model_and_scaler()
77
- result_df = make_prediction(df, model, scaler)
78
-
79
- if result_df is not None:
80
- st.subheader("✅ Outage Predictions")
81
- st.dataframe(result_df)
82
-
83
- st.subheader("📈 Voltage vs Current")
84
- fig = px.scatter(result_df, x='Voltage', y='Current', color='Outage_Prediction',
85
- title="Voltage vs Current with Prediction Labels",
86
- labels={'Voltage': 'Voltage (V)', 'Current': 'Current (A)'})
87
- st.plotly_chart(fig)
88
-
89
- except Exception as e:
90
- st.error(f"⚠️ Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  else:
92
- st.info("Awaiting CSV file with these columns: Voltage, Current, Frequency, Load, Power_Factor, Temperature")
 
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}")