File size: 3,917 Bytes
dbf1298
e9f5e41
fc54f3c
704d527
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbf1298
70171eb
704d527
 
 
 
 
 
 
 
 
 
 
fc54f3c
704d527
 
 
 
 
 
 
 
 
 
 
 
f04834b
704d527
 
 
 
 
 
 
 
 
 
f04834b
704d527
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f5e41
704d527
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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}")