Skip to content

Commit 4b0177e

Browse files
committed
bug fixes in config , coaching
1 parent a2a05b2 commit 4b0177e

File tree

3 files changed

+120
-26
lines changed

3 files changed

+120
-26
lines changed

codegreen_core/utilities/caching.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ def get_cache_or_update(country, start, deadline, energy_mode="public_data"):
5151
return data_object
5252
else:
5353
print("caches has no country, calling _pull_data(country, start, deadline)")
54+
# print(energy_mode)
5455
return _pull_data(country, start, deadline, energy_mode)
5556

5657

@@ -72,21 +73,25 @@ def _pull_data(country, start, end, energy_mode="public_data"):
7273
else:
7374
return None
7475
last_update = datetime.now().timestamp()
75-
if forecast_data["data_available"]:
76-
last_prediction = forecast_data["data"].iloc[-1]["posix_timestamp"]
77-
else:
78-
last_prediction = pd.Timestamp(datetime.now(), tz="UTC")
76+
#if forecast_data["data_available"]:
77+
# last_prediction = forecast_data["data"].iloc[-1]["startTimeUTC"]
78+
#else:
79+
# last_prediction = pd.Timestamp(datetime.now(), tz="UTC")
7980

8081
df = forecast_data["data"]
82+
del df["startTime"]
8183
df["startTimeUTC"] = pd.to_datetime(df["startTimeUTC"])
8284
df["startTimeUTC"] = df["startTimeUTC"].dt.strftime("%Y%m%d%H%M").astype("str")
85+
last_col = forecast_data["data"].iloc[-1]["startTimeUTC"]
86+
last_prediction = int(datetime.strptime(last_col, "%Y%m%d%H%M").timestamp())
8387
cached_object = {
8488
"data": df.to_dict(),
8589
"time_interval": forecast_data["time_interval"],
8690
"data_available": forecast_data["data_available"],
8791
"last_updated": int(last_update),
8892
"last_prediction": int(last_prediction),
8993
}
94+
#print(cached_object)
9095
cache.set(_get_country_key(country, energy_mode), json.dumps(cached_object))
9196
return cached_object
9297

codegreen_core/utilities/config.py

Lines changed: 56 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,51 @@
55

66
class ConfigError(Exception):
77
"""Custom exception for configuration errors."""
8-
98
pass
109

1110

1211
class Config:
1312
config_data = None
1413
section_name = "codegreen"
15-
boolean_keys = {"enable_energy_caching", "enable_time_prediction_logging"}
16-
defaults = {
17-
"default_energy_mode": "public_data",
18-
"enable_energy_caching": False,
19-
"enable_time_prediction_logging": False,
20-
"energy_redis_path": None,
21-
}
14+
all_keys = [
15+
{
16+
"name":"ENTSOE_token",
17+
"default": "None",
18+
"use":"To fetch data from ENTSOE portal",
19+
"boolean":False,
20+
},
21+
{
22+
"name":"default_energy_mode",
23+
"default":"public_data",
24+
"use":"Determines which type of data to use.",
25+
"boolean":False,
26+
},
27+
{
28+
"name":"enable_energy_caching",
29+
"default":"False",
30+
"use":"To indicate if data used by tools must be cached",
31+
"boolean":True,
32+
},
33+
{
34+
"name":"energy_redis_path",
35+
"default":"None",
36+
"boolean":False,
37+
"use":"Path to redis server to cache data.required if enable_energy_caching is enabled "
38+
},
39+
{
40+
"name":"enable_time_prediction_logging",
41+
"default":"False",
42+
"boolean":True,
43+
"use":"To indicate if logs must me saved in a log file "
44+
},
45+
{
46+
"name":"log_folder_path",
47+
"default":" ",
48+
"boolean":False,
49+
"use":"Path of the folder where logs will be stored"
50+
}
51+
52+
]
2253

2354
@classmethod
2455
def load_config(self, file_path=None):
@@ -41,10 +72,15 @@ def load_config(self, file_path=None):
4172

4273
if self.section_name not in self.config_data:
4374
self.config_data[self.section_name] = {}
44-
for key, default_value in self.defaults.items():
45-
if not self.config_data.has_option(self.section_name, key):
46-
self.config_data.set(self.section_name, key, str(default_value))
47-
75+
raise ConfigError("Invalid config file. The config file must have a section called codegreen")
76+
77+
for ky in self.all_keys:
78+
try :
79+
value = self.config_data.get(self.section_name, ky["name"])
80+
# print(value)
81+
except configparser.NoOptionError:
82+
self.config_data.set(self.section_name, ky["name"],ky["default"])
83+
4884
if self.get("enable_energy_caching") == True:
4985
if self.get("energy_redis_path") is None:
5086
raise ConfigError(
@@ -53,7 +89,7 @@ def load_config(self, file_path=None):
5389
else:
5490
r = redis.from_url(self.get("energy_redis_path"))
5591
r.ping()
56-
# print(self.config_data["default_energy_mode"])
92+
# print("Connection to redis works")
5793

5894
@classmethod
5995
def get(self, key):
@@ -63,13 +99,11 @@ def get(self, key):
6399
)
64100
try:
65101
value = self.config_data.get(self.section_name, key)
66-
if value is None:
67-
# if key not in self.defaults:
68-
# raise KeyError(f"No default value provided for key: {key}")
69-
value = self.defaults.get(key, None)
70-
else:
71-
if key in self.boolean_keys:
72-
value = value.lower() == "true"
102+
config = next((d for d in self.all_keys if d.get("name") == key), None)
103+
if config["boolean"]:
104+
return value.lower() == "true"
73105
return value
74-
except (configparser.NoSectionError, configparser.NoOptionError):
75-
return self.defaults.get(key) # Return default if key is missing
106+
except (configparser.NoSectionError, configparser.NoOptionError) as e:
107+
print("Config not found")
108+
print(key)
109+
raise e

tests/dev.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# run this as : poetry run python -m codegreen_core.tools.test
2+
3+
# import matplotlib
4+
# # matplotlib.use('TkAgg') # Or 'Qt5Agg'
5+
6+
# from .carbon_emission import plot_ce_jobs
7+
# from datetime import datetime
8+
# server1 = {
9+
# "country":"DE",
10+
# "number_core":16,
11+
# "memory_gb": 254,
12+
# }
13+
# jobs = [
14+
# {
15+
# "start_time":datetime(2024,11,10),
16+
# "runtime_minutes" : 120
17+
# }
18+
# ]
19+
20+
21+
# plot_ce_jobs(server1,jobs)
22+
23+
from codegreen_core.tools.loadshift_time import predict_now
24+
from datetime import datetime, timedelta
25+
26+
cases = [
27+
{
28+
"country":"DE",
29+
"h": 5,
30+
"hd": datetime.now()+ timedelta(hours=20)
31+
},
32+
{
33+
"country":"DE",
34+
"h": 4,
35+
"hd": datetime.now()+ timedelta(hours=15)
36+
},
37+
{
38+
"country":"DK",
39+
"h": 4,
40+
"hd": datetime.now()+ timedelta(hours=15)
41+
},
42+
{
43+
"country":"FR",
44+
"h": 4,
45+
"hd": datetime.now()+ timedelta(hours=15)
46+
},
47+
{
48+
"country":"SE",
49+
"h": 4,
50+
"hd": datetime.now()+ timedelta(hours=15)
51+
}
52+
]
53+
54+
for c in cases:
55+
print(predict_now(c["country"],c["h"],0,c["hd"]))

0 commit comments

Comments
 (0)