rehanafzal commited on
Commit
0b49a97
·
verified ·
1 Parent(s): 023a2de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +247 -124
app.py CHANGED
@@ -202,150 +202,273 @@
202
  # code 3
203
 
204
 
205
- import streamlit as st
206
- import pandas as pd
207
- import plotly.graph_objects as go
208
- from app_backend import fetch_weather, generate_synthetic_data, generate_storage_data
209
 
210
- # Constants
211
- API_KEY = "84e26811a314599e940f343b4d5894a7"
212
- DEFAULT_LOCATION = "pakistan"
213
 
214
- # Sidebar for location and weather data
215
- st.sidebar.title("Smart Grid Dashboard")
216
- location = st.sidebar.text_input("Enter Location", DEFAULT_LOCATION)
217
- weather = fetch_weather(API_KEY, location)
218
 
219
- if weather:
220
- st.sidebar.write(f"Temperature: {weather['temperature']} °C")
221
- st.sidebar.write(f"Wind Speed: {weather['wind_speed']} m/s")
222
- st.sidebar.write(f"Weather: {weather['weather']}")
223
 
224
- # Main interface
225
- st.title("Real-Time Smart Grid Dashboard")
226
 
227
- # Tabs
228
- tabs = st.tabs(["Home", "Storage", "Electricity Trade Management"])
229
 
230
- # Home Tab
231
- with tabs[0]:
232
- st.header("Overview: Power and Energy Usage")
233
 
234
- # Fetch synthetic data
235
- data = generate_synthetic_data()
236
 
237
- # Line Graph for Power Consumption, Generation, and Storage
238
- fig = go.Figure()
239
- fig.add_trace(go.Scatter(
240
- x=data["timestamp"],
241
- y=data["total_power_consumption_mw"],
242
- mode='lines',
243
- name="Total Power Consumption (MW)",
244
- line=dict(color="red")
245
- ))
246
- fig.add_trace(go.Scatter(
247
- x=data["timestamp"],
248
- y=data["grid_generation_mw"],
249
- mode='lines',
250
- name="Grid Generation (MW)",
251
- line=dict(color="green")
252
- ))
253
- fig.add_trace(go.Scatter(
254
- x=data["timestamp"],
255
- y=data["storage_utilization_mw"],
256
- mode='lines',
257
- name="Storage Utilization (MW)",
258
- line=dict(color="blue")
259
- ))
260
- fig.update_layout(title="Power and Energy Trends", xaxis_title="Time", yaxis_title="Power (MW)")
261
- st.plotly_chart(fig)
262
 
263
- # Grid Health Indicator
264
- # # Grid health overview
265
- # st.subheader("Grid Health Overview")
266
- # grid_health_counts = data["grid_health"].value_counts()
267
- # st.bar_chart(grid_health_counts)
268
 
269
 
270
 
271
- st.subheader("Grid Health Status")
272
- grid_health = "Stable" if data["grid_generation_mw"].mean() >= data["total_power_consumption_mw"].mean() else "Critical"
273
- st.write(f"**Grid Health:** {grid_health}")
 
 
 
 
 
 
 
 
 
 
 
274
 
275
- # AI Recommendations
276
- st.subheader("AI Recommendations")
277
- recommendations = [
278
- "Increase solar panel efficiency by 10% for peak hours.",
279
- "Optimize wind turbine alignment based on real-time wind data.",
280
- "Store excess energy during low-demand periods for future use.",
281
- "Improve grid stability by distributing load dynamically across sectors.",
282
- ]
283
- for rec in recommendations:
284
- st.write(f"- {rec}")
285
 
286
- # Storage Tab
287
- with tabs[1]:
288
- st.header("Energy Storage Overview")
289
- storage_data = generate_storage_data()
290
-
291
- # Individual Circles for Wind, Solar, and Turbine
292
- st.subheader("Energy Contributions")
293
- col1, col2, col3 = st.columns(3)
294
- with col1:
295
- st.metric("Wind Energy", f"{storage_data['wind']} MW/min")
296
- with col2:
297
- st.metric("Solar Energy", f"{storage_data['solar']} MW/min")
298
- with col3:
299
- st.metric("Turbine Energy", f"{storage_data['turbine']} MW/min")
300
-
301
- # Central Grid Storage Visualization
302
- st.subheader("Total Energy Stored in Grid")
303
- fig = go.Figure()
304
- fig.add_trace(go.Scatter(x=[0], y=[0], mode='markers+text', text=["Grid"], marker=dict(size=70, color="blue")))
305
- fig.add_trace(go.Scatter(
306
- x=[-1, 1, 0],
307
- y=[1, 1, -1],
308
- mode='markers+text',
309
- text=["Wind", "Solar", "Turbine"],
310
- marker=dict(size=50, color=["green", "yellow", "orange"])
311
- ))
312
- fig.add_trace(go.Scatter(
313
- x=[-0.5, 0.5, 0],
314
- y=[0.5, 0.5, -0.5],
315
- mode="lines",
316
- line=dict(width=3, color="gray"),
317
- ))
318
- fig.update_layout(
319
- title="Energy Storage Visualization",
320
- xaxis=dict(visible=False),
321
- yaxis=dict(visible=False),
322
- showlegend=False
323
- )
324
- st.plotly_chart(fig)
325
 
326
- st.write(f"**Total Energy Stored:** {storage_data['total_stored_kwh']} kWh")
327
 
328
- # Electricity Trade Management Tab
329
- with tabs[2]:
330
- st.header("Electricity Trade Management")
331
 
332
- # Sample trade data
333
- trade_data = {
334
- "Country": ["Country A", "Country B", "Country C"],
335
- "Energy Exported (MW)": [50, 30, 70],
336
- "Energy Imported (MW)": [20, 40, 10],
337
- }
338
- trade_df = pd.DataFrame(trade_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
339
 
340
- st.subheader("Trade Details")
341
- st.write(trade_df)
342
 
343
- # Visualization
344
- fig = go.Figure()
345
- fig.add_trace(go.Bar(x=trade_df["Country"], y=trade_df["Energy Exported (MW)"], name="Exported", marker_color='purple'))
346
- fig.add_trace(go.Bar(x=trade_df["Country"], y=trade_df["Energy Imported (MW)"], name="Imported", marker_color='orange'))
347
- fig.update_layout(title="Energy Trade", barmode='group')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
  st.plotly_chart(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
 
 
 
 
 
350
 
351
 
 
202
  # code 3
203
 
204
 
205
+ # import streamlit as st
206
+ # import pandas as pd
207
+ # import plotly.graph_objects as go
208
+ # from app_backend import fetch_weather, generate_synthetic_data, generate_storage_data
209
 
210
+ # # Constants
211
+ # API_KEY = "84e26811a314599e940f343b4d5894a7"
212
+ # DEFAULT_LOCATION = "pakistan"
213
 
214
+ # # Sidebar for location and weather data
215
+ # st.sidebar.title("Smart Grid Dashboard")
216
+ # location = st.sidebar.text_input("Enter Location", DEFAULT_LOCATION)
217
+ # weather = fetch_weather(API_KEY, location)
218
 
219
+ # if weather:
220
+ # st.sidebar.write(f"Temperature: {weather['temperature']} °C")
221
+ # st.sidebar.write(f"Wind Speed: {weather['wind_speed']} m/s")
222
+ # st.sidebar.write(f"Weather: {weather['weather']}")
223
 
224
+ # # Main interface
225
+ # st.title("Real-Time Smart Grid Dashboard")
226
 
227
+ # # Tabs
228
+ # tabs = st.tabs(["Home", "Storage", "Electricity Trade Management"])
229
 
230
+ # # Home Tab
231
+ # with tabs[0]:
232
+ # st.header("Overview: Power and Energy Usage")
233
 
234
+ # # Fetch synthetic data
235
+ # data = generate_synthetic_data()
236
 
237
+ # # Line Graph for Power Consumption, Generation, and Storage
238
+ # fig = go.Figure()
239
+ # fig.add_trace(go.Scatter(
240
+ # x=data["timestamp"],
241
+ # y=data["total_power_consumption_mw"],
242
+ # mode='lines',
243
+ # name="Total Power Consumption (MW)",
244
+ # line=dict(color="red")
245
+ # ))
246
+ # fig.add_trace(go.Scatter(
247
+ # x=data["timestamp"],
248
+ # y=data["grid_generation_mw"],
249
+ # mode='lines',
250
+ # name="Grid Generation (MW)",
251
+ # line=dict(color="green")
252
+ # ))
253
+ # fig.add_trace(go.Scatter(
254
+ # x=data["timestamp"],
255
+ # y=data["storage_utilization_mw"],
256
+ # mode='lines',
257
+ # name="Storage Utilization (MW)",
258
+ # line=dict(color="blue")
259
+ # ))
260
+ # fig.update_layout(title="Power and Energy Trends", xaxis_title="Time", yaxis_title="Power (MW)")
261
+ # st.plotly_chart(fig)
262
 
263
+ # # Grid Health Indicator
264
+ # # # Grid health overview
265
+ # # st.subheader("Grid Health Overview")
266
+ # # grid_health_counts = data["grid_health"].value_counts()
267
+ # # st.bar_chart(grid_health_counts)
268
 
269
 
270
 
271
+ # st.subheader("Grid Health Status")
272
+ # grid_health = "Stable" if data["grid_generation_mw"].mean() >= data["total_power_consumption_mw"].mean() else "Critical"
273
+ # st.write(f"**Grid Health:** {grid_health}")
274
+
275
+ # # AI Recommendations
276
+ # st.subheader("AI Recommendations")
277
+ # recommendations = [
278
+ # "Increase solar panel efficiency by 10% for peak hours.",
279
+ # "Optimize wind turbine alignment based on real-time wind data.",
280
+ # "Store excess energy during low-demand periods for future use.",
281
+ # "Improve grid stability by distributing load dynamically across sectors.",
282
+ # ]
283
+ # for rec in recommendations:
284
+ # st.write(f"- {rec}")
285
 
286
+ # # Storage Tab
287
+ # with tabs[1]:
288
+ # st.header("Energy Storage Overview")
289
+ # storage_data = generate_storage_data()
 
 
 
 
 
 
290
 
291
+ # # Individual Circles for Wind, Solar, and Turbine
292
+ # st.subheader("Energy Contributions")
293
+ # col1, col2, col3 = st.columns(3)
294
+ # with col1:
295
+ # st.metric("Wind Energy", f"{storage_data['wind']} MW/min")
296
+ # with col2:
297
+ # st.metric("Solar Energy", f"{storage_data['solar']} MW/min")
298
+ # with col3:
299
+ # st.metric("Turbine Energy", f"{storage_data['turbine']} MW/min")
300
+
301
+ # # Central Grid Storage Visualization
302
+ # st.subheader("Total Energy Stored in Grid")
303
+ # fig = go.Figure()
304
+ # fig.add_trace(go.Scatter(x=[0], y=[0], mode='markers+text', text=["Grid"], marker=dict(size=70, color="blue")))
305
+ # fig.add_trace(go.Scatter(
306
+ # x=[-1, 1, 0],
307
+ # y=[1, 1, -1],
308
+ # mode='markers+text',
309
+ # text=["Wind", "Solar", "Turbine"],
310
+ # marker=dict(size=50, color=["green", "yellow", "orange"])
311
+ # ))
312
+ # fig.add_trace(go.Scatter(
313
+ # x=[-0.5, 0.5, 0],
314
+ # y=[0.5, 0.5, -0.5],
315
+ # mode="lines",
316
+ # line=dict(width=3, color="gray"),
317
+ # ))
318
+ # fig.update_layout(
319
+ # title="Energy Storage Visualization",
320
+ # xaxis=dict(visible=False),
321
+ # yaxis=dict(visible=False),
322
+ # showlegend=False
323
+ # )
324
+ # st.plotly_chart(fig)
 
 
 
 
 
325
 
326
+ # st.write(f"**Total Energy Stored:** {storage_data['total_stored_kwh']} kWh")
327
 
328
+ # # Electricity Trade Management Tab
329
+ # with tabs[2]:
330
+ # st.header("Electricity Trade Management")
331
 
332
+ # # Sample trade data
333
+ # trade_data = {
334
+ # "Country": ["Country A", "Country B", "Country C"],
335
+ # "Energy Exported (MW)": [50, 30, 70],
336
+ # "Energy Imported (MW)": [20, 40, 10],
337
+ # }
338
+ # trade_df = pd.DataFrame(trade_data)
339
+
340
+ # st.subheader("Trade Details")
341
+ # st.write(trade_df)
342
+
343
+ # # Visualization
344
+ # fig = go.Figure()
345
+ # fig.add_trace(go.Bar(x=trade_df["Country"], y=trade_df["Energy Exported (MW)"], name="Exported", marker_color='purple'))
346
+ # fig.add_trace(go.Bar(x=trade_df["Country"], y=trade_df["Energy Imported (MW)"], name="Imported", marker_color='orange'))
347
+ # fig.update_layout(title="Energy Trade", barmode='group')
348
+ # st.plotly_chart(fig)
349
+
350
+
351
+ # code 4
352
 
 
 
353
 
354
+
355
+ import streamlit as st
356
+ import plotly.express as px
357
+ from app_backend import fetch_weather, generate_synthetic_data, optimize_load
358
+ import pandas as pd
359
+
360
+ # Constants
361
+ API_KEY = "84e26811a314599e940f343b4d5894a7" # Replace with your OpenWeather API key
362
+ LOCATION = "Pakistan"
363
+
364
+ # Sidebar
365
+ st.sidebar.title("Smart Grid Dashboard")
366
+ location = st.sidebar.text_input("Enter Location", LOCATION)
367
+
368
+ # Fetch and display weather data
369
+ weather = fetch_weather(API_KEY, location)
370
+ st.sidebar.subheader("Weather Information")
371
+ if weather:
372
+ st.sidebar.write(f"**Temperature**: {weather['temperature']} °C")
373
+ st.sidebar.write(f"**Wind Speed**: {weather['wind_speed']} m/s")
374
+ st.sidebar.write(f"**Weather**: {weather['weather']}")
375
+
376
+ # Main tabs
377
+ tab1, tab2, tab3 = st.tabs(["Home", "Power Storage", "Power Trading management"])
378
+
379
+ # Home Tab
380
+ with tab1:
381
+ st.title("Real-Time Smart Grid Dashboard")
382
+
383
+ # Generate synthetic data
384
+ data = generate_synthetic_data()
385
+
386
+ # Show weather at top
387
+ if weather:
388
+ st.write(f"### Location: {location}")
389
+ st.write(f"Temperature: {weather['temperature']} °C | Wind Speed: {weather['wind_speed']} m/s | Weather: {weather['weather']}")
390
+
391
+ # Power consumption graph
392
+ fig = px.line(
393
+ data,
394
+ x="timestamp",
395
+ y=["power_consumption_mw", "generation_mw", "storage_usage_mw"],
396
+ labels={"value": "Power (MW)", "variable": "Metric"},
397
+ title="Power Flow Over Time"
398
+ )
399
+ fig.update_traces(mode="lines+markers")
400
  st.plotly_chart(fig)
401
+
402
+ # Grid health as bar chart
403
+ st.subheader("Grid Health Overview")
404
+ grid_health_counts = data["grid_health"].value_counts()
405
+ fig_health = px.bar(
406
+ grid_health_counts,
407
+ x=grid_health_counts.index,
408
+ y=grid_health_counts.values,
409
+ labels={"x": "Grid Status", "y": "Count"},
410
+ title="Grid Health Status"
411
+ )
412
+ st.plotly_chart(fig_health)
413
+
414
+ # AI recommendations
415
+ st.subheader("AI Recommendations")
416
+ current_demand = data["power_consumption_mw"].iloc[-1]
417
+ current_solar = data["solar_output_mw"].iloc[-1]
418
+ current_wind = data["wind_output_mw"].iloc[-1]
419
+ recommendation = optimize_load(current_demand, current_solar, current_wind)
420
+ st.write(f"**Current Load Demand**: {current_demand} MW")
421
+ st.write(f"**Solar Output**: {current_solar} MW")
422
+ st.write(f"**Wind Output**: {current_wind} MW")
423
+ st.write(f"**Recommendation**: {recommendation}")
424
+
425
+ # Storage Tab
426
+ with tab2:
427
+ st.title("Energy Storage Status")
428
+
429
+ # Pie chart of energy percentage contribution
430
+ storage_data = {
431
+ "Wind": data["wind_output_mw"].mean(),
432
+ "Solar": data["solar_output_mw"].mean(),
433
+ "Turbine": data["turbine_output_mw"].mean()
434
+ }
435
+ fig_pie = px.pie(
436
+ names=storage_data.keys(),
437
+ values=storage_data.values(),
438
+ title="Energy Contribution by Resource"
439
+ )
440
+ st.plotly_chart(fig_pie)
441
+
442
+ # Circle visualization for storage
443
+ st.subheader("Total Energy Stored")
444
+ total_storage = sum(storage_data.values())
445
+ st.write(f"**Total Energy Stored**: {total_storage:.2f} MW")
446
+
447
+ st.markdown(
448
+ """
449
+ <div style="display: flex; justify-content: center; align-items: center; flex-direction: column;">
450
+ <div style="width: 150px; height: 150px; border-radius: 50%; background-color: #FFDD00; display: flex; justify-content: center; align-items: center; font-size: 24px; font-weight: bold; margin-bottom: 20px;">
451
+ {total_storage:.2f} MW
452
+ </div>
453
+ <div style="display: flex; gap: 50px;">
454
+ <div style="width: 100px; height: 100px; border-radius: 50%; background-color: #0073FF; display: flex; justify-content: center; align-items: center; font-size: 16px; font-weight: bold;">
455
+ Wind<br>{storage_data["Wind"]:.2f} MW
456
+ </div>
457
+ <div style="width: 100px; height: 100px; border-radius: 50%; background-color: #FF5733; display: flex; justify-content: center; align-items: center; font-size: 16px; font-weight: bold;">
458
+ Solar<br>{storage_data["Solar"]:.2f} MW
459
+ </div>
460
+ <div style="width: 100px; height: 100px; border-radius: 50%; background-color: #28B463; display: flex; justify-content: center; align-items: center; font-size: 16px; font-weight: bold;">
461
+ Turbine<br>{storage_data["Turbine"]:.2f} MW
462
+ </div>
463
+ </div>
464
+ </div>
465
+ """,
466
+ unsafe_allow_html=True
467
+ )
468
 
469
+ # Trading Tab
470
+ with tab3:
471
+ st.title("Electricity Trade Management")
472
+ st.write("Under development...")
473
 
474