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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# import pandas as pd
|
| 2 |
+
# import numpy as np
|
| 3 |
+
# import plotly.express as px
|
| 4 |
+
# from datetime import datetime, timedelta
|
| 5 |
+
# import requests
|
| 6 |
+
|
| 7 |
+
# # Function to fetch real-time weather data
|
| 8 |
+
# def fetch_weather(api_key, location):
|
| 9 |
+
# url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=metric"
|
| 10 |
+
# response = requests.get(url).json()
|
| 11 |
+
# if response["cod"] == 200:
|
| 12 |
+
# return {
|
| 13 |
+
# "temperature": response["main"]["temp"],
|
| 14 |
+
# "wind_speed": response["wind"]["speed"],
|
| 15 |
+
# "weather": response["weather"][0]["description"]
|
| 16 |
+
# }
|
| 17 |
+
# return None
|
| 18 |
+
|
| 19 |
+
# # Generate synthetic grid data
|
| 20 |
+
# def generate_synthetic_data():
|
| 21 |
+
# time_index = pd.date_range(start=datetime.now(), periods=24, freq="H")
|
| 22 |
+
# return pd.DataFrame({
|
| 23 |
+
# "timestamp": time_index,
|
| 24 |
+
# "total_consumption_kwh": np.random.randint(200, 500, len(time_index)),
|
| 25 |
+
# "grid_generation_kwh": np.random.randint(150, 400, len(time_index)),
|
| 26 |
+
# "storage_usage_kwh": np.random.randint(50, 150, len(time_index)),
|
| 27 |
+
# "solar_output_kw": np.random.randint(50, 150, len(time_index)),
|
| 28 |
+
# "wind_output_kw": np.random.randint(30, 120, len(time_index)),
|
| 29 |
+
# "grid_health": np.random.choice(["Good", "Moderate", "Critical"], len(time_index))
|
| 30 |
+
# })
|
| 31 |
+
|
| 32 |
+
# # Load optimization recommendation
|
| 33 |
+
# def optimize_load(demand, solar, wind):
|
| 34 |
+
# renewable_supply = solar + wind
|
| 35 |
+
# if renewable_supply >= demand:
|
| 36 |
+
# return "Grid Stable"
|
| 37 |
+
# return "Use Backup or Adjust Load"
|
| 38 |
+
|
| 39 |
+
# # Export functions for use in Streamlit
|
| 40 |
+
# if __name__ == "__main__":
|
| 41 |
+
# print("Backend ready!")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# code2
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# import pandas as pd
|
| 49 |
+
# import numpy as np
|
| 50 |
+
# from datetime import datetime, timedelta
|
| 51 |
+
# import requests
|
| 52 |
+
|
| 53 |
+
# # Function to fetch real-time weather data
|
| 54 |
+
# def fetch_weather(api_key, location):
|
| 55 |
+
# url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=metric"
|
| 56 |
+
# response = requests.get(url).json()
|
| 57 |
+
# if response["cod"] == 200:
|
| 58 |
+
# return {
|
| 59 |
+
# "temperature": response["main"]["temp"],
|
| 60 |
+
# "wind_speed": response["wind"]["speed"],
|
| 61 |
+
# "weather": response["weather"][0]["description"]
|
| 62 |
+
# }
|
| 63 |
+
# return None
|
| 64 |
+
|
| 65 |
+
# # Generate synthetic data
|
| 66 |
+
# def generate_synthetic_data():
|
| 67 |
+
# time_index = pd.date_range(start=datetime.now(), periods=24, freq="H")
|
| 68 |
+
# return pd.DataFrame({
|
| 69 |
+
# "timestamp": time_index,
|
| 70 |
+
# "total_power_consumption_mw": np.random.randint(200, 500, len(time_index)),
|
| 71 |
+
# "grid_generation_mw": np.random.randint(100, 300, len(time_index)),
|
| 72 |
+
# "storage_utilization_mw": np.random.randint(50, 150, len(time_index)),
|
| 73 |
+
# })
|
| 74 |
+
|
| 75 |
+
# # Generate storage data
|
| 76 |
+
# def generate_storage_data():
|
| 77 |
+
# return {
|
| 78 |
+
# "wind": 5,
|
| 79 |
+
# "solar": 7,
|
| 80 |
+
# "turbine": 10,
|
| 81 |
+
# "total_stored_kwh": 2000
|
| 82 |
+
# }
|
| 83 |
+
|
| 84 |
+
# # Export functions for use in Streamlit
|
| 85 |
+
# if __name__ == "__main__":
|
| 86 |
+
# print("Backend ready!")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# code 3
|
| 90 |
+
# import pandas as pd
|
| 91 |
+
# import numpy as np
|
| 92 |
+
# from datetime import datetime, timedelta
|
| 93 |
+
|
| 94 |
+
# # Function to fetch weather data remains unchanged
|
| 95 |
+
|
| 96 |
+
# # Generate synthetic grid data
|
| 97 |
+
# def generate_synthetic_data():
|
| 98 |
+
# time_index = pd.date_range(start=datetime.now(), periods=24, freq="H")
|
| 99 |
+
# return pd.DataFrame({
|
| 100 |
+
# "timestamp": time_index,
|
| 101 |
+
# "power_consumption_mw": np.random.randint(50, 200, len(time_index)),
|
| 102 |
+
# "grid_generation_mw": np.random.randint(30, 150, len(time_index)),
|
| 103 |
+
# "storage_utilization_mw": np.random.randint(10, 50, len(time_index)),
|
| 104 |
+
# "grid_health": np.random.choice(["Good", "Moderate", "Critical"], len(time_index))
|
| 105 |
+
# })
|
| 106 |
+
|
| 107 |
+
# # Generate synthetic storage data
|
| 108 |
+
# def generate_storage_data():
|
| 109 |
+
# wind_storage = np.random.randint(5, 15)
|
| 110 |
+
# solar_storage = np.random.randint(7, 20)
|
| 111 |
+
# turbine_storage = np.random.randint(10, 25)
|
| 112 |
+
# total_storage = wind_storage + solar_storage + turbine_storage
|
| 113 |
+
# return {
|
| 114 |
+
# "wind_storage_mw": wind_storage,
|
| 115 |
+
# "solar_storage_mw": solar_storage,
|
| 116 |
+
# "turbine_storage_mw": turbine_storage,
|
| 117 |
+
# "total_storage_mw": total_storage
|
| 118 |
+
# }
|
| 119 |
+
|
| 120 |
+
# # Generate synthetic trade data
|
| 121 |
+
# def generate_trade_data():
|
| 122 |
+
# countries = ["Country A", "Country B", "Country C"]
|
| 123 |
+
# exports = np.random.randint(10, 50, len(countries))
|
| 124 |
+
# imports = np.random.randint(5, 30, len(countries))
|
| 125 |
+
# return pd.DataFrame({
|
| 126 |
+
# "country": countries,
|
| 127 |
+
# "exports_mw": exports,
|
| 128 |
+
# "imports_mw": imports
|
| 129 |
+
# })
|
| 130 |
+
|
| 131 |
+
# # Updated optimization recommendation
|
| 132 |
+
# def optimize_load(demand, generation, storage):
|
| 133 |
+
# if generation + storage >= demand:
|
| 134 |
+
# return "Grid is Stable with Current Supply"
|
| 135 |
+
# elif demand - (generation + storage) < 20:
|
| 136 |
+
# return "Activate Backup or Optimize Load"
|
| 137 |
+
# else:
|
| 138 |
+
# return "Immediate Action Required: Adjust Load or Increase Generation"
|
| 139 |
+
|
| 140 |
+
# # Export functions
|
| 141 |
+
# if __name__ == "__main__":
|
| 142 |
+
# print("Backend ready for enhanced dashboard!")
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# code 4
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
import pandas as pd
|
| 152 |
+
import numpy as np
|
| 153 |
+
import requests
|
| 154 |
+
from datetime import datetime
|
| 155 |
+
|
| 156 |
+
# Function to fetch real-time weather data
|
| 157 |
+
def fetch_weather(api_key, location):
|
| 158 |
+
url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=metric"
|
| 159 |
+
response = requests.get(url).json()
|
| 160 |
+
if response["cod"] == 200:
|
| 161 |
+
return {
|
| 162 |
+
"temperature": response["main"]["temp"],
|
| 163 |
+
"wind_speed": response["wind"]["speed"],
|
| 164 |
+
"weather": response["weather"][0]["description"]
|
| 165 |
+
}
|
| 166 |
+
return None
|
| 167 |
+
|
| 168 |
+
# Generate synthetic grid data
|
| 169 |
+
def generate_synthetic_data():
|
| 170 |
+
time_index = pd.date_range(start=datetime.now(), periods=24, freq="H")
|
| 171 |
+
return pd.DataFrame({
|
| 172 |
+
"timestamp": time_index,
|
| 173 |
+
"load_demand_kwh": np.random.randint(200, 500, len(time_index)),
|
| 174 |
+
"solar_output_kw": np.random.randint(50, 150, len(time_index)),
|
| 175 |
+
"wind_output_kw": np.random.randint(30, 120, len(time_index)),
|
| 176 |
+
"grid_health": np.random.choice(["Good", "Moderate", "Critical"], len(time_index))
|
| 177 |
+
})
|
| 178 |
+
|
| 179 |
+
# Load optimization recommendation
|
| 180 |
+
def optimize_load(demand, solar, wind):
|
| 181 |
+
renewable_supply = solar + wind
|
| 182 |
+
if renewable_supply >= demand:
|
| 183 |
+
return "Grid Stable"
|
| 184 |
+
return "Use Backup or Adjust Load"
|
| 185 |
+
|
| 186 |
+
if __name__ == "__main__":
|
| 187 |
+
print("Backend ready!")
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
# code 5
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
# import random
|
| 195 |
+
# import pandas as pd
|
| 196 |
+
# def fetch_data():
|
| 197 |
+
# # Simulating fetching data from a database or API
|
| 198 |
+
# data = {
|
| 199 |
+
# 'temperature': random.uniform(-10, 30),
|
| 200 |
+
# 'wind_speed': random.uniform(0, 20),
|
| 201 |
+
# 'weather_condition': random.choice(['Clear', 'Overcast Clouds', 'Thunderstorm', 'Rain']),
|
| 202 |
+
# 'timestamps': pd.date_range("2025-01-01", periods=10, freq='H'),
|
| 203 |
+
# 'total_consumption': [random.uniform(50, 100) for _ in range(10)],
|
| 204 |
+
# 'grid_generation': [random.uniform(30, 80) for _ in range(10)],
|
| 205 |
+
# 'storage_usage': [random.uniform(10, 30) for _ in range(10)],
|
| 206 |
+
# 'solar_storage': random.uniform(10, 30),
|
| 207 |
+
# 'wind_storage': random.uniform(10, 30),
|
| 208 |
+
# 'hydro_storage': random.uniform(10, 30),
|
| 209 |
+
# 'total_storage': random.uniform(50, 100),
|
| 210 |
+
# }
|
| 211 |
+
# return data
|
| 212 |
+
|
| 213 |
+
# def generate_recommendations(data):
|
| 214 |
+
# recommendations = []
|
| 215 |
+
# if data['total_consumption'][-1] > data['grid_generation'][-1]:
|
| 216 |
+
# recommendations.append("Consider integrating additional renewable sources to meet the current demand.")
|
| 217 |
+
# if data['storage_usage'][-1] > data['total_storage'] * 0.8:
|
| 218 |
+
# recommendations.append("Energy storage is running low. Consider optimizing the grid or adding more storage.")
|
| 219 |
+
# return recommendations
|
| 220 |
+
|
| 221 |
+
# def grid_health_status(data):
|
| 222 |
+
# status = "Grid is operating normally."
|
| 223 |
+
# if data['total_consumption'][-1] > 90:
|
| 224 |
+
# status = "Warning: High consumption detected!"
|
| 225 |
+
# if data['wind_speed'] > 15:
|
| 226 |
+
# status = "Warning: High wind speeds, may affect wind turbine output."
|
| 227 |
+
# return status
|
| 228 |
+
|
| 229 |
+
# def generate_trading_options(data):
|
| 230 |
+
# if data['total_storage'] > 60:
|
| 231 |
+
# return "Energy is available for export to neighboring countries."
|
| 232 |
+
# else:
|
| 233 |
+
# return "Energy reserves are low. Trading is not recommended at this moment."
|
| 234 |
+
|