Skip to content

Commit f2255c9

Browse files
committed
using black to format code
1 parent 1622276 commit f2255c9

26 files changed

+1492
-1073
lines changed

codegreen_core/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
from .utilities.config import Config
2+
23
Config.load_config()

codegreen_core/data/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
from .main import *
2-
__all__ = ['energy']
2+
3+
__all__ = ["energy"]

codegreen_core/data/entsoe.py

Lines changed: 180 additions & 88 deletions
Large diffs are not rendered by default.

codegreen_core/data/main.py

Lines changed: 52 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import pandas as pd
22
from datetime import datetime
33

4-
from ..utilities.message import Message,CodegreenDataError
5-
from ..utilities import metadata as meta
4+
from ..utilities.message import Message, CodegreenDataError
5+
from ..utilities import metadata as meta
66
from . import entsoe as et
77

8-
def energy(country,start_time,end_time,type="generation",interval60=True)-> dict:
9-
"""
8+
9+
def energy(country, start_time, end_time, type="generation", interval60=True) -> dict:
10+
"""
1011
Returns hourly time series of energy production mix for a specified country and time range.
1112
1213
This method fetches the energy data for the specified country between the specified duration.
@@ -15,30 +16,30 @@ def energy(country,start_time,end_time,type="generation",interval60=True)-> dict
1516
1617
For example, if the source is ENTSOE, the data contains:
1718
18-
========================== ========== ================================================================
19-
Column type Description
20-
========================== ========== ================================================================
21-
startTimeUTC datetime Start date in UTC (60 min interval)
22-
Biomass float64
23-
Fossil Hard coal float64
24-
Geothermal float64
25-
....more energy sources float64
26-
**renewableTotal** float64 The total based on all renewable sources
27-
renewableTotalWS float64 The total production using only Wind and Solar energy sources
28-
nonRenewableTotal float64
29-
total float64 Total using all energy sources
30-
percentRenewable int64
31-
percentRenewableWS int64 Percentage of energy produced using only wind and solar energy
32-
Wind_per int64 Percentages of individual energy sources
33-
Solar_per int64
34-
Nuclear_per int64
35-
Hydroelectricity_per int64
36-
Geothermal_per int64
37-
Natural Gas_per int64
38-
Petroleum_per int64
39-
Coal_per int64
40-
Biomass_per int64
41-
========================== ========== ================================================================
19+
========================== ========== ================================================================
20+
Column type Description
21+
========================== ========== ================================================================
22+
startTimeUTC datetime Start date in UTC (60 min interval)
23+
Biomass float64
24+
Fossil Hard coal float64
25+
Geothermal float64
26+
....more energy sources float64
27+
**renewableTotal** float64 The total based on all renewable sources
28+
renewableTotalWS float64 The total production using only Wind and Solar energy sources
29+
nonRenewableTotal float64
30+
total float64 Total using all energy sources
31+
percentRenewable int64
32+
percentRenewableWS int64 Percentage of energy produced using only wind and solar energy
33+
Wind_per int64 Percentages of individual energy sources
34+
Solar_per int64
35+
Nuclear_per int64
36+
Hydroelectricity_per int64
37+
Geothermal_per int64
38+
Natural Gas_per int64
39+
Petroleum_per int64
40+
Coal_per int64
41+
Biomass_per int64
42+
========================== ========== ================================================================
4243
4344
Note : fields marked bold are calculated based on the data fetched.
4445
@@ -53,25 +54,27 @@ def energy(country,start_time,end_time,type="generation",interval60=True)-> dict
5354
- `time_interval` : the time interval of the DataFrame
5455
:rtype: dict
5556
"""
56-
if not isinstance(country, str):
57-
raise ValueError("Invalid country")
58-
if not isinstance(start_time,datetime):
59-
raise ValueError("Invalid start date")
60-
if not isinstance(end_time, datetime):
61-
raise ValueError("Invalid end date")
62-
if type not in ['generation', 'forecast']:
63-
raise ValueError(Message.INVALID_ENERGY_TYPE)
64-
# check start<end and both are not same
65-
66-
if(start_time > end_time):
67-
raise ValueError("Invalid time.End time should be greater than start time")
57+
if not isinstance(country, str):
58+
raise ValueError("Invalid country")
59+
if not isinstance(start_time, datetime):
60+
raise ValueError("Invalid start date")
61+
if not isinstance(end_time, datetime):
62+
raise ValueError("Invalid end date")
63+
if type not in ["generation", "forecast"]:
64+
raise ValueError(Message.INVALID_ENERGY_TYPE)
65+
# check start<end and both are not same
66+
67+
if start_time > end_time:
68+
raise ValueError("Invalid time.End time should be greater than start time")
6869

69-
e_source = meta.get_country_energy_source(country)
70-
if e_source=="ENTSOE" :
71-
if type == "generation":
72-
return et.get_actual_production_percentage(country,start_time,end_time,interval60)
73-
elif type == "forecast":
74-
return et.get_forecast_percent_renewable(country,start_time,end_time)
75-
else:
76-
raise CodegreenDataError(Message.NO_ENERGY_SOURCE)
77-
return None
70+
e_source = meta.get_country_energy_source(country)
71+
if e_source == "ENTSOE":
72+
if type == "generation":
73+
return et.get_actual_production_percentage(
74+
country, start_time, end_time, interval60
75+
)
76+
elif type == "forecast":
77+
return et.get_forecast_percent_renewable(country, start_time, end_time)
78+
else:
79+
raise CodegreenDataError(Message.NO_ENERGY_SOURCE)
80+
return None

codegreen_core/models/predict.py

Lines changed: 44 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -12,52 +12,59 @@
1212
# Path to the models directory
1313
models_dir = Path(__file__).parent / "files"
1414

15+
1516
def predicted_energy(country):
16-
# do the forecast from now , same return format as data.energy
17-
return {"data":None}
17+
# do the forecast from now , same return format as data.energy
18+
return {"data": None}
19+
1820

1921
# Function to load a specific model by name
20-
def _load_prediction_model(country,version=None):
22+
def _load_prediction_model(country, version=None):
2123
"""Load a model by name"""
22-
model_details = get_prediction_model_details(country,version)
24+
model_details = get_prediction_model_details(country, version)
2325
model_path = models_dir / model_details["name"]
2426
print(model_path)
2527
if not model_path.exists():
2628
raise FileNotFoundError(f"Model does not exist.")
27-
28-
return load_model(model_path,compile=False)
2929

30+
return load_model(model_path, compile=False)
3031

31-
def _run(country,input,model_version=None):
32+
33+
def _run(country, input, model_version=None):
3234
"""Returns the prediction values"""
33-
35+
3436
seq_length = len(input)
35-
date = input[['startTimeUTC']].copy()
37+
date = input[["startTimeUTC"]].copy()
3638
# Convert 'startTimeUTC' column to datetime
37-
date['startTimeUTC'] = pd.to_datetime(date['startTimeUTC'])
39+
date["startTimeUTC"] = pd.to_datetime(date["startTimeUTC"])
3840
# Get the last date value
39-
last_date = date.iloc[-1]['startTimeUTC']
41+
last_date = date.iloc[-1]["startTimeUTC"]
4042
# Calculate the next hour
4143
next_hour = last_date + timedelta(hours=1)
4244
# Create a range of 48 hours starting from the next hour
43-
next_48_hours = pd.date_range(next_hour, periods=48, freq='h')
45+
next_48_hours = pd.date_range(next_hour, periods=48, freq="h")
4446
# Create a DataFrame with the next 48 hours
4547
next_48_hours_df = pd.DataFrame(
46-
{'startTimeUTC': next_48_hours.strftime('%Y%m%d%H%M')})
47-
48-
model_details = get_prediction_model_details(country,model_version)
49-
50-
lstm = load_prediction_model(country,model_version) #load_model(model_path,compile=False)
48+
{"startTimeUTC": next_48_hours.strftime("%Y%m%d%H%M")}
49+
)
50+
51+
model_details = get_prediction_model_details(country, model_version)
52+
53+
lstm = load_prediction_model(
54+
country, model_version
55+
) # load_model(model_path,compile=False)
5156

5257
scaler = StandardScaler()
53-
percent_renewable = input['percentRenewable']
58+
percent_renewable = input["percentRenewable"]
5459
forecast_values_total = []
5560
prev_values_total = percent_renewable.values.flatten()
5661
for _ in range(48):
5762
scaled_prev_values_total = scaler.fit_transform(
58-
prev_values_total.reshape(-1, 1))
59-
x_pred_total = scaled_prev_values_total[-(
60-
seq_length-1):].reshape(1, (seq_length-1), 1)
63+
prev_values_total.reshape(-1, 1)
64+
)
65+
x_pred_total = scaled_prev_values_total[-(seq_length - 1) :].reshape(
66+
1, (seq_length - 1), 1
67+
)
6168
# Make the prediction using the loaded model
6269
predicted_value_total = lstm.predict(x_pred_total, verbose=0)
6370
# Inverse transform the predicted value
@@ -67,24 +74,29 @@ def _run(country,input,model_version=None):
6774
prev_values_total = prev_values_total[1:]
6875
# Create a DataFrame
6976
forecast_df = pd.DataFrame(
70-
{'startTimeUTC': next_48_hours_df['startTimeUTC'], 'percentRenewableForecast': forecast_values_total})
71-
forecast_df["percentRenewableForecast"] = forecast_df["percentRenewableForecast"].round(
72-
).astype(int)
73-
forecast_df['percentRenewableForecast'] = forecast_df['percentRenewableForecast'].apply(
74-
lambda x: 0 if x <= 0 else x)
75-
77+
{
78+
"startTimeUTC": next_48_hours_df["startTimeUTC"],
79+
"percentRenewableForecast": forecast_values_total,
80+
}
81+
)
82+
forecast_df["percentRenewableForecast"] = (
83+
forecast_df["percentRenewableForecast"].round().astype(int)
84+
)
85+
forecast_df["percentRenewableForecast"] = forecast_df[
86+
"percentRenewableForecast"
87+
].apply(lambda x: 0 if x <= 0 else x)
88+
7689
input_percentage = input["percentRenewable"].tolist()
7790
input_start = input.iloc[0]["startTimeUTC"]
78-
input_end = input.iloc[-1]["startTimeUTC"]
79-
91+
input_end = input.iloc[-1]["startTimeUTC"]
92+
8093
return {
8194
"input": {
8295
"country": country,
8396
"model": model_details["name"],
8497
"percentRenewable": input_percentage,
8598
"start": input_start,
86-
"end": input_end
99+
"end": input_end,
87100
},
88-
"output": forecast_df
101+
"output": forecast_df,
89102
}
90-

codegreen_core/models/train.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
# the code for model training comes here # todo later
1+
# the code for model training comes here # todo later

0 commit comments

Comments
 (0)