File size: 20,519 Bytes
c238d7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d2c4f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c238d7d
0b49a97
 
 
 
e60d54e
0b49a97
 
 
e60d54e
0b49a97
 
 
 
c238d7d
0b49a97
 
 
 
e60d54e
0b49a97
 
e60d54e
0b49a97
 
e60d54e
0b49a97
 
 
c238d7d
0b49a97
 
e60d54e
0b49a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e60d54e
0b49a97
 
 
 
 
341941e
 
 
0b49a97
 
 
 
 
 
 
 
 
 
 
 
 
 
1d2c4f6
0b49a97
 
 
 
1d2c4f6
0b49a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e60d54e
0b49a97
1d2c4f6
0b49a97
 
 
e60d54e
0b49a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e60d54e
 
0b49a97
305f877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b49a97
305f877
0b49a97
 
 
 
5201ecd
 
0b49a97
 
 
 
 
 
 
 
305f877
 
 
0b49a97
305f877
40e64d5
0b49a97
 
305f877
0b49a97
305f877
0b49a97
 
305f877
 
0894c3b
 
 
305f877
 
 
 
 
 
 
 
40e64d5
 
 
 
 
 
305f877
 
 
 
0b49a97
305f877
 
 
 
 
 
0b49a97
 
305f877
 
 
 
 
 
 
 
 
0b49a97
305f877
 
 
 
 
0b49a97
305f877
 
 
 
 
e60d54e
0b49a97
305f877
0b49a97
305f877
 
 
 
 
 
 
 
 
 
 
 
 
 
43bb94b
 
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# import streamlit as st
# import pandas as pd
# import plotly.express as px
# from app_backend import fetch_weather, generate_synthetic_data, optimize_load

# # Constants
# API_KEY = "84e26811a314599e940f343b4d5894a7"
# LOCATION = "Pakistan"

# # Sidebar
# st.sidebar.title("Smart Grid Dashboard")
# location = st.sidebar.text_input("Enter Location", 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 with tabs
# tabs = st.tabs(["Home", "Electricity Storage", "Electricity Trading"])

# with tabs[0]:
#     st.title("Real-Time Smart Grid Dashboard")

#     # Generate synthetic data
#     data = generate_synthetic_data()

#     # Plot total consumption, grid generation, and storage usage
#     fig = px.line(data, x="timestamp", y=["total_consumption_kwh", "grid_generation_kwh", "storage_usage_kwh"],
#                   title="Energy Consumption, Generation, and Storage Usage Over Time",
#                   labels={"value": "Energy (kWh)", "variable": "Energy Source"})
#     st.plotly_chart(fig)

#     # Grid health overview
#     st.subheader("Grid Health Overview")
#     grid_health_counts = data["grid_health"].value_counts()
#     st.bar_chart(grid_health_counts)

#     # Optimization recommendations
#     current_demand = data["total_consumption_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}")

# with tabs[1]:
#     st.title("Energy Storage Overview")

#     # Total energy stored
#     total_storage = 500  # Example of total energy storage
#     st.subheader(f"Total Energy Stored: {total_storage} kWh")

#     # Energy storage contribution from different sources
#     st.subheader("Energy Storage Contributions")
#     energy_sources = pd.DataFrame({
#         "Source": ["Wind", "Solar", "Turbine"],
#         "Energy (kW/min)": [5, 7, 10]
#     })
#     st.bar_chart(energy_sources.set_index("Source"))

#     # Show energy storage status with a rounded circle
#     st.subheader("Energy Storage Circle")
#     st.markdown("Energy storage is a combination of contributions from different renewable sources.")

#     # Visualization of energy storage circle using Plotly
#     storage_data = {
#         "Source": ["Wind", "Solar", "Turbine"],
#         "Energy": [5, 7, 10],
#     }
#     storage_df = pd.DataFrame(storage_data)
#     fig = px.pie(storage_df, names="Source", values="Energy", title="Energy Storage Sources")
#     st.plotly_chart(fig)

# with tabs[2]:
#     st.title("Energy Trading Overview")

#     # Energy cubes
#     st.subheader("Energy Cubes Stored")
#     energy_cubes = pd.DataFrame({
#         "Country": ["China", "Sri Lanka", "Bangladesh"],
#         "Energy (kWh)": [100, 200, 300],
#         "Shareable": [True, True, False]
#     })

#     # Displaying the energy cubes in a grid
#     st.write("Stored energy can be shared with other countries.")
#     st.dataframe(energy_cubes)

#     # Visualization of energy that can be shared
#     st.subheader("Energy Trading Visualization")
#     st.markdown("The following energy amounts are available for sharing with different countries.")
#     trading_fig = px.bar(energy_cubes, x="Country", y="Energy (kWh)", color="Shareable", title="Energy Trading")
#     st.plotly_chart(trading_fig)


# code 2


# import streamlit as st
# import pandas as pd
# import plotly.graph_objects as go
# from app_backend import fetch_weather, generate_synthetic_data, generate_storage_data

# # Constants
# API_KEY = "84e26811a314599e940f343b4d5894a7"
# DEFAULT_LOCATION = "Pakistan"

# # Sidebar for location and weather data
# st.sidebar.title("Smart Grid Dashboard")
# location = st.sidebar.text_input("Enter Location", DEFAULT_LOCATION)
# 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 interface
# st.title("Real-Time Smart Grid Dashboard")

# # Tabs
# tabs = st.tabs(["Home", "Power Storage", "Electricity Trade Management"])

# # Home Tab
# with tabs[0]:
#     st.header("Overview: Power and Energy Usage")
    
#     # Fetch synthetic data
#     data = generate_synthetic_data()

#     # Line Graph for Power Consumption, Generation, and Storage
#     fig = go.Figure()
#     fig.add_trace(go.Scatter(
#         x=data["timestamp"],
#         y=data["total_power_consumption_mw"],
#         mode='lines',
#         name="Total Power Consumption (MW)",
#         line=dict(color="red")
#     ))
#     fig.add_trace(go.Scatter(
#         x=data["timestamp"],
#         y=data["grid_generation_mw"],
#         mode='lines',
#         name="Grid Generation (MW)",
#         line=dict(color="green")
#     ))
#     fig.add_trace(go.Scatter(
#         x=data["timestamp"],
#         y=data["storage_utilization_mw"],
#         mode='lines',
#         name="Storage Utilization (MW)",
#         line=dict(color="blue")
#     ))
#     fig.update_layout(title="Power and Energy Trends", xaxis_title="Time", yaxis_title="Power (MW)")
#     st.plotly_chart(fig)

# # Storage Tab
# with tabs[1]:
#     st.header("Energy Storage Overview")
#     storage_data = generate_storage_data()

#     st.write(f"**Total Energy Stored:** {storage_data['total_stored_kwh']} kWh")
    
#     # Circular storage breakdown
#     sources = ["Wind", "Solar", "Turbine"]
#     values = [storage_data["wind"], storage_data["solar"], storage_data["turbine"]]
    
#     fig = go.Figure(data=[go.Pie(labels=sources, values=values, hole=.4)])
#     fig.update_layout(title="Energy Storage Breakdown")
#     st.plotly_chart(fig)

# # Electricity Trade Management Tab
# with tabs[2]:
#     st.header("Electricity Trade Management")

#     # Sample trade data
#     trade_data = {
#         "Country": ["Srilanka", "China", "Bangladesh"],
#         "Energy Exported (MW)": [50, 30, 70],
#         "Energy Imported (MW)": [20, 40, 10],
#     }
#     trade_df = pd.DataFrame(trade_data)

#     st.subheader("Trade Details")
#     st.write(trade_df)

#     # Visualization
#     fig = go.Figure()
#     fig.add_trace(go.Bar(x=trade_df["Country"], y=trade_df["Energy Exported (MW)"], name="Exported", marker_color='purple'))
#     fig.add_trace(go.Bar(x=trade_df["Country"], y=trade_df["Energy Imported (MW)"], name="Imported", marker_color='orange'))
#     fig.update_layout(title="Energy Trade", barmode='group')
#     st.plotly_chart(fig)


# code 3


# import streamlit as st
# import pandas as pd
# import plotly.graph_objects as go
# from app_backend import fetch_weather, generate_synthetic_data, generate_storage_data

# # Constants
# API_KEY = "84e26811a314599e940f343b4d5894a7"
# DEFAULT_LOCATION = "pakistan"

# # Sidebar for location and weather data
# st.sidebar.title("Smart Grid Dashboard")
# location = st.sidebar.text_input("Enter Location", DEFAULT_LOCATION)
# 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 interface
# st.title("Real-Time Smart Grid Dashboard")

# # Tabs
# tabs = st.tabs(["Home", "Storage", "Electricity Trade Management"])

# # Home Tab
# with tabs[0]:
#     st.header("Overview: Power and Energy Usage")
    
#     # Fetch synthetic data
#     data = generate_synthetic_data()

#     # Line Graph for Power Consumption, Generation, and Storage
#     fig = go.Figure()
#     fig.add_trace(go.Scatter(
#         x=data["timestamp"],
#         y=data["total_power_consumption_mw"],
#         mode='lines',
#         name="Total Power Consumption (MW)",
#         line=dict(color="red")
#     ))
#     fig.add_trace(go.Scatter(
#         x=data["timestamp"],
#         y=data["grid_generation_mw"],
#         mode='lines',
#         name="Grid Generation (MW)",
#         line=dict(color="green")
#     ))
#     fig.add_trace(go.Scatter(
#         x=data["timestamp"],
#         y=data["storage_utilization_mw"],
#         mode='lines',
#         name="Storage Utilization (MW)",
#         line=dict(color="blue")
#     ))
#     fig.update_layout(title="Power and Energy Trends", xaxis_title="Time", yaxis_title="Power (MW)")
#     st.plotly_chart(fig)

#     # Grid Health Indicator
#     #     # Grid health overview
#     # st.subheader("Grid Health Overview")
#     # grid_health_counts = data["grid_health"].value_counts()
#     # st.bar_chart(grid_health_counts)


    
#     st.subheader("Grid Health Status")
#     grid_health = "Stable" if data["grid_generation_mw"].mean() >= data["total_power_consumption_mw"].mean() else "Critical"
#     st.write(f"**Grid Health:** {grid_health}")

#     # AI Recommendations
#     st.subheader("AI Recommendations")
#     recommendations = [
#         "Increase solar panel efficiency by 10% for peak hours.",
#         "Optimize wind turbine alignment based on real-time wind data.",
#         "Store excess energy during low-demand periods for future use.",
#         "Improve grid stability by distributing load dynamically across sectors.",
#     ]
#     for rec in recommendations:
#         st.write(f"- {rec}")

# # Storage Tab
# with tabs[1]:
#     st.header("Energy Storage Overview")
#     storage_data = generate_storage_data()

#     # Individual Circles for Wind, Solar, and Turbine
#     st.subheader("Energy Contributions")
#     col1, col2, col3 = st.columns(3)
#     with col1:
#         st.metric("Wind Energy", f"{storage_data['wind']} MW/min")
#     with col2:
#         st.metric("Solar Energy", f"{storage_data['solar']} MW/min")
#     with col3:
#         st.metric("Turbine Energy", f"{storage_data['turbine']} MW/min")

#     # Central Grid Storage Visualization
#     st.subheader("Total Energy Stored in Grid")
#     fig = go.Figure()
#     fig.add_trace(go.Scatter(x=[0], y=[0], mode='markers+text', text=["Grid"], marker=dict(size=70, color="blue")))
#     fig.add_trace(go.Scatter(
#         x=[-1, 1, 0],
#         y=[1, 1, -1],
#         mode='markers+text',
#         text=["Wind", "Solar", "Turbine"],
#         marker=dict(size=50, color=["green", "yellow", "orange"])
#     ))
#     fig.add_trace(go.Scatter(
#         x=[-0.5, 0.5, 0],
#         y=[0.5, 0.5, -0.5],
#         mode="lines",
#         line=dict(width=3, color="gray"),
#     ))
#     fig.update_layout(
#         title="Energy Storage Visualization",
#         xaxis=dict(visible=False),
#         yaxis=dict(visible=False),
#         showlegend=False
#     )
#     st.plotly_chart(fig)

#     st.write(f"**Total Energy Stored:** {storage_data['total_stored_kwh']} kWh")

# # Electricity Trade Management Tab
# with tabs[2]:
#     st.header("Electricity Trade Management")

#     # Sample trade data
#     trade_data = {
#         "Country": ["Country A", "Country B", "Country C"],
#         "Energy Exported (MW)": [50, 30, 70],
#         "Energy Imported (MW)": [20, 40, 10],
#     }
#     trade_df = pd.DataFrame(trade_data)

#     st.subheader("Trade Details")
#     st.write(trade_df)

#     # Visualization
#     fig = go.Figure()
#     fig.add_trace(go.Bar(x=trade_df["Country"], y=trade_df["Energy Exported (MW)"], name="Exported", marker_color='purple'))
#     fig.add_trace(go.Bar(x=trade_df["Country"], y=trade_df["Energy Imported (MW)"], name="Imported", marker_color='orange'))
#     fig.update_layout(title="Energy Trade", barmode='group')
#     st.plotly_chart(fig)


# code 4



# import streamlit as st
# import plotly.express as px
# from app_backend import fetch_weather, generate_synthetic_data, optimize_load
# import pandas as pd

# # Constants
# API_KEY = "84e26811a314599e940f343b4d5894a7"  # Replace with your OpenWeather API key
# LOCATION = "Pakistan"

# # Sidebar
# st.sidebar.title("Smart Grid Dashboard")
# location = st.sidebar.text_input("Enter Location", LOCATION)

# # Fetch and display weather data
# weather = fetch_weather(API_KEY, location)
# st.sidebar.subheader("Weather Information")
# 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 tabs
# tab1, tab2, tab3 = st.tabs(["Home", "Power Storage", "Power Trading management"])

# # Home Tab
# with tab1:
#     st.title("Real-Time Smart Grid Dashboard")
    
#     # Generate synthetic data
#     data = generate_synthetic_data()
    
#     # Show weather at top
#     if weather:
#         st.write(f"### Location: {location}")
#         st.write(f"Temperature: {weather['temperature']} °C | Wind Speed: {weather['wind_speed']} m/s | Weather: {weather['weather']}")
    
#     # Power consumption graph
#     fig = px.line(
#         data,
#         x="timestamp",
#         y=["power_consumption_mw", "generation_mw", "storage_usage_mw"],
#         labels={"value": "Power (MW)", "variable": "Metric"},
#         title="Power Flow Over Time"
#     )
#     fig.update_traces(mode="lines+markers")
#     st.plotly_chart(fig)
    
#     # Grid health as bar chart
#     st.subheader("Grid Health Overview")
#     grid_health_counts = data["grid_health"].value_counts()
#     fig_health = px.bar(
#         grid_health_counts,
#         x=grid_health_counts.index,
#         y=grid_health_counts.values,
#         labels={"x": "Grid Status", "y": "Count"},
#         title="Grid Health Status"
#     )
#     st.plotly_chart(fig_health)
    
#     # AI recommendations
#     st.subheader("AI Recommendations")
#     current_demand = data["power_consumption_mw"].iloc[-1]
#     current_solar = data["solar_output_mw"].iloc[-1]
#     current_wind = data["wind_output_mw"].iloc[-1]
#     recommendation = optimize_load(current_demand, current_solar, current_wind)
#     st.write(f"**Current Load Demand**: {current_demand} MW")
#     st.write(f"**Solar Output**: {current_solar} MW")
#     st.write(f"**Wind Output**: {current_wind} MW")
#     st.write(f"**Recommendation**: {recommendation}")

# # Storage Tab
# with tab2:
#     st.title("Energy Storage Status")
    
#     # Pie chart of energy percentage contribution
#     storage_data = {
#         "Wind": data["wind_output_mw"].mean(),
#         "Solar": data["solar_output_mw"].mean(),
#         "Turbine": data["turbine_output_mw"].mean()
#     }
#     fig_pie = px.pie(
#         names=storage_data.keys(),
#         values=storage_data.values(),
#         title="Energy Contribution by Resource"
#     )
#     st.plotly_chart(fig_pie)
    
#     # Circle visualization for storage
#     st.subheader("Total Energy Stored")
#     total_storage = sum(storage_data.values())
#     st.write(f"**Total Energy Stored**: {total_storage:.2f} MW")
    
#     st.markdown(
#         """
#         <div style="display: flex; justify-content: center; align-items: center; flex-direction: column;">
#             <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;">
#                 {total_storage:.2f} MW
#             </div>
#             <div style="display: flex; gap: 50px;">
#                 <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;">
#                     Wind<br>{storage_data["Wind"]:.2f} MW
#                 </div>
#                 <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;">
#                     Solar<br>{storage_data["Solar"]:.2f} MW
#                 </div>
#                 <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;">
#                     Turbine<br>{storage_data["Turbine"]:.2f} MW
#                 </div>
#             </div>
#         </div>
#         """,
#         unsafe_allow_html=True
#     )

# # Trading Tab
# with tab3:
#     st.title("Electricity Trade Management")
#     st.write("Under development...")



# code 5


import streamlit as st
import pandas as pd
import plotly.express as px
from app_backend import fetch_weather, generate_synthetic_data, optimize_load

# Constants
API_KEY = "84e26811a314599e940f343b4d5894a7"
LOCATION = "Pakistan"

# Sidebar
st.sidebar.title("Smart Grid Dashboard")
location = st.sidebar.text_input("Enter Location", 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']}")

# Tabs
tab_home, tab_storage, tab_trading = st.tabs(["Home", "Power Storage", "Electricity Trade Management"])

# Home Tab
with tab_home:
    st.title("Real-Time Smart Grid Dashboard")

    # Generate synthetic data
    data = generate_synthetic_data()

    # Grid Health
    # st.subheader("Grid Health Overview")
    # grid_health_counts = data["grid_health"].value_counts()
    # st.bar_chart(grid_health_counts)

    # Power Consumption, Generation & Storage Graph
    st.subheader("Power Consumption, Generation & Storage")
    fig = px.line(data, x="timestamp", y=["load_demand_kwh", "solar_output_kw", "wind_output_kw"], 
                  title="Power Consumption, Generation & Storage", labels={"value": "Power (MW)"})
    fig.update_traces(line=dict(width=2))
    st.plotly_chart(fig)

    # Grid Health
    st.subheader("Grid Health Overview")
    grid_health_counts = data["grid_health"].value_counts()
    st.bar_chart(grid_health_counts)

    
    # Optimization Recommendations
    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} MW")
    st.write(f"Solar Output: {current_solar} MW")
    st.write(f"Wind Output: {current_wind} MW")
    st.write(f"Recommendation: {recommendation}")

# Storage Tab
with tab_storage:
    st.title("Energy Storage Overview")

    # Energy Contribution by Resources
    st.subheader("Energy Contribution Percentage by Resources")
    energy_data = {
        "Wind": 5,
        "Solar": 7,
        "Turbine": 10
    }
    energy_df = pd.DataFrame(list(energy_data.items()), columns=["Source", "Energy (MW)"])
    fig = px.pie(energy_df, values="Energy (MW)", names="Source", title="Energy Contribution by Resources")
    st.plotly_chart(fig)

    # Energy Storage Merge
    st.subheader("Total Energy Stored")
    st.write("Energy stored from all sources:")
    energy_stored = sum(energy_data.values())
    st.write(f"Total Energy Stored: {energy_stored} MW")
    st.write("Energy sources merged into total energy storage:")
    st.write(f"Total Energy Stored in Grid: {energy_stored} MW")

# Trading Tab
with tab_trading:
    st.title("Electricity Trade Management")

    # Simulating Electricity Trade (Energy cubes & trading)
    st.subheader("Energy Trade Overview")
    energy_trade = {
        "USA": 50,
        "Germany": 40,
        "India": 30
    }
    trade_df = pd.DataFrame(list(energy_trade.items()), columns=["Country", "Energy (MW)"])
    fig = px.bar(trade_df, x="Country", y="Energy (MW)", title="Energy Trading Overview")
    st.plotly_chart(fig)

    st.write("Energy cubes available for trading:")
    st.write("The system can trade energy with other countries.")