Skip to content

Commit

Permalink
add adjuster first try
Browse files Browse the repository at this point in the history
  • Loading branch information
peterdudfield committed Nov 12, 2024
1 parent 36e4268 commit 367342f
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 0 deletions.
78 changes: 78 additions & 0 deletions india_forecast_app/adjuster.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
from pvsite_datamodel.sqlmodels import ForecastValueSQL, GenerationSQL, ForecastSQL

Check failure on line 1 in india_forecast_app/adjuster.py

View workflow job for this annotation

GitHub Actions / lint_and_test / Lint the code and run the tests

Ruff (D100)

india_forecast_app/adjuster.py:1:1: D100 Missing docstring in public module
from sqlalchemy.sql import func

from datetime import datetime, timedelta
import pandas as pd
from typing import Optional

# Wad to get all the forecast for the last 7 days made, at this time.

Check failure on line 8 in india_forecast_app/adjuster.py

View workflow job for this annotation

GitHub Actions / lint_and_test / Lint the code and run the tests

Ruff (I001)

india_forecast_app/adjuster.py:1:1: I001 Import block is un-sorted or un-formatted
# And find the ME for each forecast horizon

"""
Here is the SQL query that it based off
select
AVG(generation.generation_power_kw - forecast_values.forecast_power_kw)
-- generation.generation_power_kw,
-- forecast_values.forecast_power_kw,
-- forecast_values.start_utc,
,horizon_minutes
-- *
from forecast_values
JOIN forecasts ON forecasts.forecast_uuid = forecast_values.forecast_uuid
join generation on generation.start_utc = forecast_values.start_utc
WHERE forecast_values.start_utc >= '2024-11-05'
AND forecasts.site_uuid = 'adaf6be8-4e30-4c98-ac27-964447e9c8e6'
AND generation.site_uuid = 'adaf6be8-4e30-4c98-ac27-964447e9c8e6'
and extract(hour from forecasts.created_utc) = 7
group by horizon_minutes
-- order by forecast_values.start_utc
"""


def get_me_values(session, hour: int, start_datetime: Optional[datetime] = None) -> pd.DataFrame:
"""
Get the ME values for the last 7 days for a given hour, for a given hour creation time
args:
hour: the hour of whent he forecast is created
start_datetime:: the start datetime to filter on.
session: sqlalchemy session
"""

Check failure on line 42 in india_forecast_app/adjuster.py

View workflow job for this annotation

GitHub Actions / lint_and_test / Lint the code and run the tests

Ruff (D405)

india_forecast_app/adjuster.py:34:5: D405 Section name should be properly capitalized ("args")

if start_datetime is None:
start_datetime = datetime.now() - timedelta(days=7)

query = session.query(
func.avg(ForecastValueSQL.forecast_power_kw - GenerationSQL.generation_power_kw),
ForecastValueSQL.horizon_minutes,
)

# join
query = query.join(ForecastSQL)
query = query.filter(GenerationSQL.start_utc == ForecastValueSQL.start_utc)

# only include the last 7 days
query = query.filter(ForecastValueSQL.start_utc >= start_datetime)
query = query.filter(GenerationSQL.start_utc >= start_datetime)

# filter on site
query = query.filter(ForecastSQL.site_uuid == "adaf6be8-4e30-4c98-ac27-964447e9c8e6")
query = query.filter(GenerationSQL.site_uuid == "adaf6be8-4e30-4c98-ac27-964447e9c8e6")

# filter on created_utc
query = query.filter((func.extract("hour", ForecastSQL.created_utc) == hour))

# group by forecast horizon
query = query.group_by(ForecastValueSQL.horizon_minutes)

# order by forecast horizon
query = query.order_by(ForecastValueSQL.horizon_minutes)

me = query.all()

me_df = pd.DataFrame(me, columns=["me_kw", "horizon_minutes"])

return me_df

28 changes: 28 additions & 0 deletions india_forecast_app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import india_forecast_app
from india_forecast_app.models import PVNetModel, get_all_models
from india_forecast_app.sentry import traces_sampler
from india_forecast_app.adjuster import get_me_values

log = logging.getLogger(__name__)

Check failure on line 26 in india_forecast_app/app.py

View workflow job for this annotation

GitHub Actions / lint_and_test / Lint the code and run the tests

Ruff (I001)

india_forecast_app/app.py:5:1: I001 Import block is un-sorted or un-formatted
version = india_forecast_app.__version__
Expand Down Expand Up @@ -204,6 +205,7 @@ def save_forecast(
write_to_db: bool,
ml_model_name: Optional[str] = None,
ml_model_version: Optional[str] = None,
use_adjuster: bool = True,
):
"""
Saves a forecast for a given site & timestamp
Expand Down Expand Up @@ -238,6 +240,32 @@ def save_forecast(
ml_model_version=ml_model_version,
)

if use_adjuster:
log.info(f"Adjusting forecast for site_id={forecast_meta['site_uuid']}...")
me_values = get_me_values(db_session, forecast_meta["timestamp_utc"].hour)

log.info(f"ME values: {me_values}")

# TODO
# should we put some sort of limits on the adjuster
# perhaps 10% of capacity?

# join forecast_values_df with me_values on horizon_minutes
forecast_values_df_adjust = forecast_values_df.copy()
forecast_values_df_adjust = forecast_values_df_adjust.merge(me_values, on="horizon_minutes", how="left")

Check failure on line 255 in india_forecast_app/app.py

View workflow job for this annotation

GitHub Actions / lint_and_test / Lint the code and run the tests

Ruff (E501)

india_forecast_app/app.py:255:101: E501 Line too long (112 > 100)

# adjust forecast_power_kw by ME values
forecast_values_df_adjust["forecast_power_kw"] = forecast_values_df_adjust["forecast_power_kw"] - forecast_values_df_adjust["me_kw"]

Check failure on line 258 in india_forecast_app/app.py

View workflow job for this annotation

GitHub Actions / lint_and_test / Lint the code and run the tests

Ruff (E501)

india_forecast_app/app.py:258:101: E501 Line too long (140 > 100)

if write_to_db:
insert_forecast_values(
db_session,
forecast_meta,
forecast_values_df_adjust,
ml_model_name=f'{ml_model_name}_adjust',
ml_model_version=ml_model_version,
)

output = f'Forecast for site_id={forecast_meta["site_uuid"]},\
timestamp={forecast_meta["timestamp_utc"]},\
version={forecast_meta["forecast_version"]}:'
Expand Down

0 comments on commit 367342f

Please sign in to comment.