Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document & refactor scheduling specs for storage flexibility model #511

Merged
merged 41 commits into from Nov 18, 2022
Merged
Show file tree
Hide file tree
Changes from 38 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
ce8169c
Better documentation of flexibility model for storage in endpoint; re…
nhoening Oct 1, 2022
3bed7c0
add changelog entry
nhoening Oct 1, 2022
1fba29e
make tests work, include updating older API versions, make prefer_cha…
nhoening Oct 1, 2022
0e9259d
use storage_specs in CLI command, as well
nhoening Oct 1, 2022
c2b2787
remove default resolution of 15M, for now pass in what you want
nhoening Oct 2, 2022
c0400ae
various review comments
nhoening Oct 28, 2022
4718a8a
black
nhoening Oct 29, 2022
2eef27d
fix tests
nhoening Oct 29, 2022
1f68659
always load sensor when checking storage specs
nhoening Oct 31, 2022
2beb928
begin to handle source model and version during scheduling
nhoening Oct 31, 2022
378caba
we can get multiple sources from our query (in the old setting, when …
nhoening Oct 31, 2022
5b48baf
give our two in-built schedulers an official __author__ and __version__
nhoening Oct 31, 2022
b664910
review comments
nhoening Oct 31, 2022
e9ff60b
refactor getting data source for a job to util function; use the actu…
nhoening Nov 2, 2022
5fe72dc
pass sensor to check_storage_specs, as we always have it already
nhoening Nov 2, 2022
f80171d
wrap Scheduler in classes, unify data source handling a bit more
nhoening Nov 3, 2022
c04f0d7
Merge branch 'main' into refactor-scheduling-storage-specs
nhoening Nov 4, 2022
22cb852
Support pandas 1.4 (#525)
Flix6x Nov 10, 2022
dd47dab
Stop requiring min/max SoC attributes, which have defaults:
Flix6x Nov 10, 2022
add377f
Set up device constraint columns for efficiencies in Charge Point sch…
Flix6x Nov 10, 2022
ccab2ee
Derive flow constraints for battery scheduling, too (copied from Char…
Flix6x Nov 10, 2022
6344cb0
Refactor: rename BatteryScheduler to StorageScheduler
Flix6x Nov 10, 2022
7f9eced
Warn for deprecation of
Flix6x Nov 10, 2022
4bc593c
Use StorageScheduler instead of ChargingStationScheduler
Flix6x Nov 10, 2022
ec40bc0
Deprecate ChargingStationScheduler
Flix6x Nov 10, 2022
6914a4b
Refactor: move StorageScheduler to dedicated module
Flix6x Nov 10, 2022
5e6bd4e
Update docstring
Flix6x Nov 10, 2022
beb2770
fix test
Flix6x Nov 10, 2022
3bf1b97
flake8
Flix6x Nov 10, 2022
ed3284d
Merge remote-tracking branch 'origin/main' into refactor-scheduling-s…
Flix6x Nov 10, 2022
a9899a2
Lose the v in version strings; prefer versions showing up as 'version…
Flix6x Nov 10, 2022
ad22c35
Refactor: rename module
Flix6x Nov 11, 2022
4efe883
Deal with empty SoC targets
Flix6x Nov 11, 2022
09cf700
Stop wrapping DataFrame representations in logging
Flix6x Oct 9, 2022
5a3845d
Log warning instead of raising UnknownForecastException, and assume z…
Flix6x Oct 9, 2022
172753d
mention scheduler merging in changelog
nhoening Nov 16, 2022
78250ef
amend existing data source information to reflect our StorageScheduler
nhoening Nov 16, 2022
ac2ddcc
Merge branch 'main' into refactor-scheduling-storage-specs
nhoening Nov 17, 2022
0bf52dd
add db upgrade notice to changelog
nhoening Nov 17, 2022
e1c2b47
Merge branch 'refactor-scheduling-storage-specs' of github.com:FlexMe…
nhoening Nov 17, 2022
1368fab
more specific downgrade command
nhoening Nov 18, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion documentation/changelog.rst
Expand Up @@ -8,7 +8,7 @@ v0.12.0 | October XX, 2022
New features
-------------

* Hit the replay button to replay what happened, available on the sensor and asset pages [see `PR #463 <http://www.github.com/FlexMeasures/flexmeasures/pull/463>`_]
* Hit the replay button to visually replay what happened, available on the sensor and asset pages [see `PR #463 <http://www.github.com/FlexMeasures/flexmeasures/pull/463>`_]
nhoening marked this conversation as resolved.
Show resolved Hide resolved
* Ability to provide your own custom scheduling function [see `PR #505 <http://www.github.com/FlexMeasures/flexmeasures/pull/505>`_]
* Visually distinguish forecasts/schedules (dashed lines) from measurements (solid lines), and expand the tooltip with timing info regarding the forecast/schedule horizon or measurement lag [see `PR #503 <http://www.github.com/FlexMeasures/flexmeasures/pull/503>`_]
* The asset page also allows to show sensor data from other assets that belong to the same account [see `PR #500 <http://www.github.com/FlexMeasures/flexmeasures/pull/500>`_]
Expand All @@ -28,6 +28,7 @@ Infrastructure / Support
* Remove bokeh dependency and obsolete UI views [see `PR #476 <http://www.github.com/FlexMeasures/flexmeasures/pull/476>`_]
* Fix ``flexmeasures db-ops dump`` and ``flexmeasures db-ops restore`` not working in docker containers [see `PR #530 <http://www.github.com/FlexMeasures/flexmeasures/pull/530>`_] and incorrectly reporting a success when `pg_dump` and `pg_restore` are not installed [see `PR #526 <http://www.github.com/FlexMeasures/flexmeasures/pull/526>`_]
* Plugins can save BeliefsSeries, too, instead of just BeliefsDataFrames [see `PR #523 <http://www.github.com/FlexMeasures/flexmeasures/pull/523>`_]
* Improve documentation and code w.r.t. storage flexibility modelling ― prepare for handling other schedulers & merge battery and car charging schedulers [see `PR #511 <http://www.github.com/FlexMeasures/flexmeasures/pull/511>`_]
* Revised strategy for removing unchanged beliefs when saving data: retain the oldest measurement (ex-post belief), too [see `PR #518 <http://www.github.com/FlexMeasures/flexmeasures/pull/518>`_]


Expand Down
46 changes: 29 additions & 17 deletions documentation/plugin/customisation.rst
Expand Up @@ -15,32 +15,45 @@ but in the background your custom scheduling algorithm is being used.

Let's walk through an example!

First, we need to write a function which accepts arguments just like the in-built schedulers (their code is `here <https://github.com/FlexMeasures/flexmeasures/tree/main/flexmeasures/data/models/planning>`_).
The following minimal example gives you an idea of the inputs and outputs:
First, we need to write a a class (inhering from the Base Scheduler) with a `schedule` function which accepts arguments just like the in-built schedulers (their code is `here <https://github.com/FlexMeasures/flexmeasures/tree/main/flexmeasures/data/models/planning>`_).
The following minimal example gives you an idea of some meta information you can add for labelling your data, as well as the inputs and outputs of such a scheduling function:

.. code-block:: python

from datetime import datetime, timedelta
import pandas as pd
from pandas.tseries.frequencies import to_offset
from flexmeasures.data.models.time_series import Sensor
from flexmeasures.data.models.planning import Scheduler

def compute_a_schedule(
sensor: Sensor,
start: datetime,
end: datetime,
resolution: timedelta,
*args,
**kwargs
):
"""Just a dummy scheduler, advising to do nothing"""
return pd.Series(
0, index=pd.date_range(start, end, freq=resolution, closed="left")
)

class DummyScheduler(Scheduler):

__author__ = "My Company"
__version__ = "2"

def schedule(
self,
sensor: Sensor,
start: datetime,
end: datetime,
resolution: timedelta,
*args,
**kwargs
):
"""
Just a dummy scheduler that always plans to consume at maximum capacity.
(Schedulers return positive values for consumption, and negative values for production)
"""
return pd.Series(
sensor.get_attribute("capacity_in_mw"),
index=pd.date_range(start, end, freq=resolution, closed="left"),
)


.. note:: It's possible to add arguments that describe the asset flexibility and the EMS context in more detail. For example,
for storage assets we support various state-of-charge parameters. For now, the existing schedulers are the best documentation.
for storage assets we support various state-of-charge parameters. For now, the existing in-built schedulers are the best documentation.
We are working on documenting this better, so the learning curve becomes easier.


Finally, make your scheduler be the one that FlexMeasures will use for certain sensors:
Expand All @@ -52,8 +65,7 @@ Finally, make your scheduler be the one that FlexMeasures will use for certain s

scheduler_specs = {
"module": "flexmeasures.data.tests.dummy_scheduler", # or a file path, see note below
"function": "compute_a_schedule",
"source": "My Company"
"class": "DummyScheduler",
}

my_sensor = Sensor.query.filter(Sensor.name == "My power sensor on a flexible asset").one_or_none()
Expand Down
5 changes: 2 additions & 3 deletions flexmeasures/api/common/schemas/sensor_data.py
Expand Up @@ -14,6 +14,7 @@
from flexmeasures.data.models.time_series import Sensor
from flexmeasures.api.common.schemas.sensors import SensorField
from flexmeasures.api.common.utils.api_utils import upsample_values
from flexmeasures.data.models.planning.utils import initialize_index
from flexmeasures.data.schemas.times import AwareDateTimeField, DurationField
from flexmeasures.data.services.time_series import simplify_index
from flexmeasures.utils.time_utils import duration_isoformat, server_now
Expand Down Expand Up @@ -179,9 +180,7 @@ def dump_bdf(self, sensor_data_description: dict, **kwargs) -> dict:
)

# Convert to desired time range
index = pd.date_range(
start=start, end=end, freq=df.event_resolution, closed="left"
)
index = initialize_index(start=start, end=end, resolution=df.event_resolution)
df = df.reindex(index)

# Convert to desired unit
Expand Down
20 changes: 12 additions & 8 deletions flexmeasures/api/v1_2/implementations.py
Expand Up @@ -32,13 +32,14 @@
parse_isodate_str,
)
from flexmeasures.data import db
from flexmeasures.data.models.planning.battery import schedule_battery
from flexmeasures.data.models.planning.storage import StorageScheduler
from flexmeasures.data.models.planning.exceptions import (
UnknownMarketException,
UnknownPricesException,
)
from flexmeasures.data.models.time_series import Sensor
from flexmeasures.data.services.resources import has_assets, can_access_asset
from flexmeasures.data.models.planning.utils import ensure_storage_specs
from flexmeasures.utils.time_utils import duration_isoformat


Expand Down Expand Up @@ -93,17 +94,20 @@ def get_device_message_response(generic_asset_name_groups, duration):
start = datetime.fromisoformat(
sensor.generic_asset.get_attribute("soc_datetime")
)
end = start + planning_horizon
resolution = sensor.event_resolution

# Schedule the asset
storage_specs = dict(
soc_at_start=sensor.generic_asset.get_attribute("soc_in_mwh"),
prefer_charging_sooner=False,
)
storage_specs = ensure_storage_specs(
storage_specs, sensor, start, end, resolution
)
try:
schedule = schedule_battery(
sensor,
start,
start + planning_horizon,
resolution,
soc_at_start=sensor.generic_asset.get_attribute("soc_in_mwh"),
prefer_charging_sooner=False,
schedule = StorageScheduler().schedule(
sensor, start, end, resolution, storage_specs=storage_specs
)
except UnknownPricesException:
return unknown_prices()
Expand Down
43 changes: 23 additions & 20 deletions flexmeasures/api/v1_3/implementations.py
Expand Up @@ -39,11 +39,14 @@
parse_isodate_str,
)
from flexmeasures.data import db
from flexmeasures.data.models.data_sources import DataSource
from flexmeasures.data.models.planning.utils import initialize_series
from flexmeasures.data.models.time_series import Sensor
from flexmeasures.data.queries.utils import simplify_index
from flexmeasures.data.services.resources import has_assets, can_access_asset
from flexmeasures.data.services.scheduling import create_scheduling_job
from flexmeasures.data.services.scheduling import (
create_scheduling_job,
get_data_source_for_job,
)
from flexmeasures.utils.time_utils import duration_isoformat


Expand Down Expand Up @@ -99,6 +102,7 @@ def get_device_message_response(generic_asset_name_groups, duration):
if event_type not in ("soc", "soc-with-targets"):
return unrecognized_event_type(event_type)
connection = current_app.queues["scheduling"].connection
job = None
try: # First try the scheduling queue
job = Job.fetch(event, connection=connection)
except NoSuchJobError: # Then try the most recent event_id (stored as a generic asset attribute)
Expand Down Expand Up @@ -144,19 +148,15 @@ def get_device_message_response(generic_asset_name_groups, duration):
return unknown_schedule("Scheduling job has an unknown status.")
schedule_start = job.kwargs["start"]

schedule_data_source_name = "Seita"
scheduler_source = DataSource.query.filter_by(
name=schedule_data_source_name, type="scheduling script"
).one_or_none()
if scheduler_source is None:
data_source = get_data_source_for_job(job, sensor=sensor)
if data_source is None:
return unknown_schedule(
message + f'no data is known from "{schedule_data_source_name}".'
message + f"no data source could be found for job {job}."
)

power_values = sensor.search_beliefs(
event_starts_after=schedule_start,
event_ends_before=schedule_start + planning_horizon,
source=scheduler_source,
source=data_source,
most_recent_beliefs_only=True,
one_deterministic_belief_per_event=True,
)
Expand Down Expand Up @@ -301,11 +301,12 @@ def post_udi_event_response(unit: str, prior: datetime):
start_of_schedule = datetime
end_of_schedule = datetime + current_app.config.get("FLEXMEASURES_PLANNING_HORIZON")
resolution = sensor.event_resolution
soc_targets = pd.Series(
soc_targets = initialize_series(
np.nan,
index=pd.date_range(
start_of_schedule, end_of_schedule, freq=resolution, closed="right"
), # note that target values are indexed by their due date (i.e. closed="right")
start=start_of_schedule,
end=end_of_schedule,
resolution=resolution,
inclusive="right", # note that target values are indexed by their due date (i.e. inclusive="right")
)

if event_type == "soc-with-targets":
Expand Down Expand Up @@ -359,16 +360,18 @@ def post_udi_event_response(unit: str, prior: datetime):
soc_targets.loc[target_datetime] = target_value

create_scheduling_job(
sensor_id,
sensor,
start_of_schedule,
end_of_schedule,
resolution=resolution,
belief_time=prior, # server time if no prior time was sent
soc_at_start=value,
soc_targets=soc_targets,
soc_min=soc_min,
soc_max=soc_max,
roundtrip_efficiency=roundtrip_efficiency,
storage_specs=dict(
soc_at_start=value,
soc_targets=soc_targets,
soc_min=soc_min,
soc_max=soc_max,
roundtrip_efficiency=roundtrip_efficiency,
),
job_id=form.get("event"),
enqueue=True,
)
Expand Down
6 changes: 4 additions & 2 deletions flexmeasures/api/v1_3/tests/test_api_v1_3.py
Expand Up @@ -88,9 +88,10 @@ def test_post_udi_event_and_get_device_message(
)

# check results are in the database
resolution = timedelta(minutes=15)
job.refresh() # catch meta info that was added on this very instance
data_source_info = job.meta.get("data_source_info")
scheduler_source = DataSource.query.filter_by(
name="Seita", type="scheduling script"
type="scheduling script", **data_source_info
).one_or_none()
assert (
scheduler_source is not None
Expand All @@ -100,6 +101,7 @@ def test_post_udi_event_and_get_device_message(
.filter(TimedBelief.source_id == scheduler_source.id)
.all()
)
resolution = timedelta(minutes=15)
consumption_schedule = pd.Series(
[-v.event_value for v in power_values],
index=pd.DatetimeIndex([v.event_start for v in power_values], freq=resolution),
Expand Down