File size: 9,488 Bytes
eca7f1c
 
 
 
 
 
 
b74770b
eca7f1c
 
 
 
741ceba
eca7f1c
 
741ceba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eca7f1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35973e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eca7f1c
35973e5
 
 
 
 
eca7f1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35973e5
eca7f1c
 
 
 
 
 
35973e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eca7f1c
35973e5
 
eca7f1c
 
 
35973e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eca7f1c
 
35973e5
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import random
import pandas as pd
import streamlit as st
import pydeck as pdk
from datetime import datetime, timedelta

# ---- Constants ----
POLES_PER_SITE = 12
SITES = {
    "Hyderabad": [17.385044, 78.486671],
    "Gadwal": [16.2351, 77.8052],
    "Kurnool": [15.8281, 78.0373],
    "Ballari": [15.1394, 76.9214]
}

# ---- Set Page Config (Must be first Streamlit command) ----
st.set_page_config(page_title="Smart Pole Monitoring", layout="wide")

# ---- Custom CSS for Advanced UI ----
st.markdown("""
    <style>
    .stApp {
        background-color: #f5f7fa;
    }
    .metric-card {
        background-color: white;
        padding: 15px;
        border-radius: 10px;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        text-align: center;
    }
    .red-alert {
        background-color: #ffe6e6;
        color: #d32f2f;
        padding: 10px;
        border-radius: 5px;
        font-weight: bold;
    }
    .sidebar .sidebar-content {
        background-color: #ffffff;
        border-right: 1px solid #e0e0e0;
    }
    h1, h2, h3 {
        color: #1a237e;
    }
    </style>
""", unsafe_allow_html=True)

# ---- Helper Functions ----
def generate_location(base_lat, base_lon):
    return [
        base_lat + random.uniform(-0.02, 0.02),
        base_lon + random.uniform(-0.02, 0.02)
    ]

def simulate_pole(pole_id, site_name):
    lat, lon = generate_location(*SITES[site_name])
    solar_kwh = round(random.uniform(3.0, 7.5), 2)
    wind_kwh = round(random.uniform(0.5, 2.0), 2)
    power_required = round(random.uniform(4.0, 8.0), 2)
    total_power = solar_kwh + wind_kwh
    power_status = 'Sufficient' if total_power >= power_required else 'Insufficient'

    tilt_angle = round(random.uniform(0, 45), 2)
    vibration = round(random.uniform(0, 5), 2)
    camera_status = random.choice(['Online', 'Offline'])

    # Anomaly detection
    anomalies = []
    if solar_kwh < 4.0:
        anomalies.append("Low Solar Output")
    if wind_kwh < 0.7:
        anomalies.append("Low Wind Output")
    if tilt_angle > 30:
        anomalies.append("Pole Tilt Risk")
    if vibration > 3:
        anomalies.append("Vibration Alert")
    if camera_status == 'Offline':
        anomalies.append("Camera Offline")
    if power_status == 'Insufficient':
        anomalies.append("Power Insufficient")

    # Alert level logic
    alert_level = 'Green'
    if anomalies:
        if tilt_angle > 40 or vibration > 4.5 or len(anomalies) > 1:
            alert_level = 'Red'
        else:
            alert_level = 'Yellow'

    health_score = max(0, 100 - (tilt_angle + vibration * 10))
    timestamp = datetime.now() - timedelta(hours=random.randint(0, 6))

    return {
        'Pole ID': f'{site_name[:3].upper()}-{pole_id:03}',
        'Site': site_name,
        'Latitude': lat,
        'Longitude': lon,
        'Solar (kWh)': solar_kwh,
        'Wind (kWh)': wind_kwh,
        'Power Required (kWh)': power_required,
        'Total Power (kWh)': total_power,
        'Power Status': power_status,
        'Tilt Angle (°)': tilt_angle,
        'Vibration (g)': vibration,
        'Camera Status': camera_status,
        'Health Score': round(health_score, 2),
        'Alert Level': alert_level,
        'Anomalies': ';'.join(anomalies) if anomalies else 'None',
        'Last Checked': timestamp.strftime('%Y-%m-%d %H:%M:%S')
    }

# ---- Streamlit UI ----
st.title("🌍 Smart Renewable Pole Monitoring - Multi-Site")

# Sidebar with enhanced controls
with st.sidebar:
    st.header("🛠️ Control Panel")
    with st.expander("Site Selection", expanded=True):
        selected_site = st.selectbox(
            "Select Site",
            options=list(SITES.keys()),
            index=0,
            help="Choose a site to monitor poles."
        )
    with st.expander("Simulation Settings"):
        num_poles = st.slider("Number of Poles per Site", 5, 50, POLES_PER_SITE)
        simulate_faults = st.checkbox("Simulate Faults", value=True)
    with st.expander("Filters"):
        alert_filter = st.multiselect(
            "Alert Level",
            options=['Green', 'Yellow', 'Red'],
            default=['Green', 'Yellow', 'Red']
        )
        camera_filter = st.multiselect(
            "Camera Status",
            options=['Online', 'Offline'],
            default=['Online', 'Offline']
        )

# Simulate data
if selected_site in SITES:
    with st.spinner(f"Simulating {num_poles} poles at {selected_site}..."):
        poles_data = [simulate_pole(i + 1, site) for site in SITES for i in range(num_poles)]
        df = pd.DataFrame(poles_data)
        site_df = df[df['Site'] == selected_site]

    # Tabs for different views
    tab1, tab2, tab3, tab4 = st.tabs(["📊 Dashboard", "📋 Data Table", "📈 Charts", "📍 Map"])

    with tab1:
        # Dashboard with metrics
        st.subheader("System Overview")
        red_alerts_count = site_df[site_df['Alert Level'] == 'Red'].shape[0]
        if red_alerts_count > 0:
            st.markdown(f"<div class='red-alert'>🚨 {red_alerts_count} Red Alerts Detected! Immediate Action Required!</div>", unsafe_allow_html=True)
        else:
            st.success("✅ No Red Alerts Detected")

        col1, col2, col3, col4 = st.columns(4)
        with col1:
            st.markdown("<div class='metric-card'>", unsafe_allow_html=True)
            st.metric("Total Poles", site_df.shape[0])
            st.markdown("</div>", unsafe_allow_html=True)
        with col2:
            st.markdown("<div class='metric-card'>", unsafe_allow_html=True)
            st.metric("Red Alerts", red_alerts_count, delta_color="inverse")
            st.markdown("</div>", unsafe_allow_html=True)
        with col3:
            st.markdown("<div class='metric-card'>", unsafe_allow_html=True)
            st.metric("Power Insufficiencies", site_df[site_df['Power Status'] == 'Insufficient'].shape[0])
            st.markdown("</div>", unsafe_allow_html=True)
        with col4:
            st.markdown("<div class='metric-card'>", unsafe_allow_html=True)
            st.metric("Average Health Score", round(site_df['Health Score'].mean(), 2))
            st.markdown("</div>", unsafe_allow_html=True)

        # Red Alerts Summary
        red_df = site_df[site_df['Alert Level'] == 'Red']
        if not red_df.empty:
            st.subheader("🚨 Critical Red Alerts")
            st.dataframe(
                red_df[['Pole ID', 'Anomalies', 'Tilt Angle (°)', 'Vibration (g)', 'Power Status', 'Camera Status', 'Health Score', 'Last Checked']],
                use_container_width=True
            )
            csv = red_df.to_csv(index=False)
            st.download_button(
                label="Download Red Alerts CSV",
                data=csv,
                file_name=f"{selected_site}_red_alerts.csv",
                mime="text/csv"
            )

    with tab2:
        # Filtered Data Table
        st.subheader(f"Pole Data for {selected_site}")
        filtered_df = site_df[
            (site_df['Alert Level'].isin(alert_filter)) &
            (site_df['Camera Status'].isin(camera_filter))
        ]
        
        # Conditional formatting for red alerts
        def highlight_red_alerts(row):
            return ['background-color: #ffe6e6' if row['Alert Level'] == 'Red' else '' for _ in row]
        
        st.dataframe(
            filtered_df[['Pole ID', 'Anomalies', 'Solar (kWh)', 'Wind (kWh)', 'Power Status', 'Tilt Angle (°)', 'Vibration (g)', 'Camera Status', 'Health Score', 'Alert Level', 'Last Checked']].style.apply(highlight_red_alerts, axis=1),
            use_container_width=True
        )

    with tab3:
        # Charts
        st.subheader("Energy Generation Comparison")
        st.bar_chart(site_df[['Solar (kWh)', 'Wind (kWh)']].mean())

        st.subheader("Tilt vs. Vibration")
        scatter_data = site_df[['Tilt Angle (°)', 'Vibration (g)', 'Alert Level']].copy()
        scatter_data['color'] = scatter_data['Alert Level'].map({
            'Green': '[0, 255, 0, 160]',
            'Yellow': '[255, 255, 0, 160]',
            'Red': '[255, 0, 0, 160]'
        })
        st.scatter_chart(scatter_data[['Tilt Angle (°)', 'Vibration (g)']])

    with tab4:
        # Map with Red Alerts
        st.subheader("Red Alert Pole Locations")
        if not red_df.empty:
            st.pydeck_chart(pdk.Deck(
                initial_view_state=pdk.ViewState(
                    latitude=SITES[selected_site][0],
                    longitude=SITES[selected_site][1],
                    zoom=12,
                    pitch=50
                ),
                layers=[
                    pdk.Layer(
                        'ScatterplotLayer',
                        data=red_df,
                        get_position='[Longitude, Latitude]',
                        get_color='[255, 0, 0, 160]',
                        get_radius=100,
                        pickable=True,
                        auto_highlight=True
                    )
                ],
                tooltip={
                    "html": "<b>Pole ID:</b> {Pole ID}<br><b>Anomalies:</b> {Anomalies}<br><b>Tilt:</b> {Tilt Angle (°)}°<br><b>Vibration:</b> {Vibration (g)}g<br><b>Health Score:</b> {Health Score}",
                    "style": {"backgroundColor": "white", "color": "#333"}
                }
            ))
        else:
            st.info("No red alerts at this time.")

else:
    st.error("Invalid site. Please enter one of: Hyderabad, Gadwal, Kurnool, Ballari")