-
Notifications
You must be signed in to change notification settings - Fork 30
/
shiftable_load.py
261 lines (213 loc) · 9.62 KB
/
shiftable_load.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
from __future__ import annotations
from math import ceil
from datetime import timedelta
import pytz
import pandas as pd
from flexmeasures.data.models.planning import Scheduler
from flexmeasures.data.queries.utils import simplify_index
from flexmeasures.data.models.time_series import Sensor
from flexmeasures.data.schemas.scheduling.shiftable_load import (
ShiftableLoadFlexModelSchema,
LoadType,
OptimizationSense,
)
from flexmeasures.data.schemas.scheduling import FlexContextSchema
class ShiftableLoadScheduler(Scheduler):
__version__ = "1"
__author__ = "Seita"
def compute(self) -> pd.Series | None:
"""Schedule a fix load, defined as a `power` and a `duration`, within the specified time window.
To schedule a battery, please, refer to the StorageScheduler.
For example, this scheduler can plan the start of a process of type `Shiftable` that lasts 5h and requires a power of 10kW.
In that case, the scheduler will find the best (as to minimize/maximize the cost) hour to start the process.
This scheduler supports three types of `load_types`:
- Inflexible: this load requires to be scheduled as soon as possible.
- Breakable: this load can be divisible in smaller consumption periods.
- Shiftable: this load can start at any time within the specified time window.
The resulting schedule provides the power flow at each time period.
Parameters
==========
consumption_price_sensor: it defines the utility (economic, environmental, ) in each
time period. It has units of quantity/energy, for example, EUR/kWh.
power: nominal power of the load.
duration: time that the load last.
optimization_sense: objective of the scheduler, to maximize or minimize.
time_restrictions: time periods in which the load cannot be schedule to.
load_type: Inflexible, Breakable or Shiftable.
:returns: The computed schedule.
"""
if not self.config_deserialized:
self.deserialize_config()
start = self.start.astimezone(pytz.utc)
end = self.end.astimezone(pytz.utc)
resolution = self.resolution
belief_time = self.belief_time
sensor = self.sensor
consumption_price_sensor: Sensor = self.flex_model.get(
"consumption_price_sensor"
)
duration: timedelta = self.flex_model.get("duration")
power = self.flex_model.get("power")
optimization_sense = self.flex_model.get("optimization_sense")
load_type: LoadType = self.flex_model.get("load_type")
time_restrictions = self.flex_model.get("time_restrictions")
# get cost data
cost = consumption_price_sensor.search_beliefs(
event_starts_after=start,
event_ends_before=end,
resolution=resolution,
one_deterministic_belief_per_event=True,
beliefs_before=belief_time,
)
cost = simplify_index(cost)
# create an empty schedule
schedule = pd.Series(
index=pd.date_range(
start,
end,
freq=sensor.event_resolution,
inclusive="left",
name="event_start",
),
data=0,
name="event_value",
)
# convert power to energy using the resolution of the sensor.
# e.g. resolution=15min, power=1kW -> energy=250W
energy = power * consumption_price_sensor.event_resolution / timedelta(hours=1)
# we can fill duration/resolution rows or, if the duration is larger than the schedule
# window, fill the entire window.
rows_to_fill = min(
ceil(duration / consumption_price_sensor.event_resolution), len(schedule)
)
if rows_to_fill == len(schedule):
schedule[:] = energy
return schedule
time_restrictions = (
self.block_invalid_starting_times_for_whole_process_scheduling(
load_type, time_restrictions, duration, rows_to_fill
)
)
# create schedule
if load_type == LoadType.INFLEXIBLE:
self.compute_inflexible(schedule, time_restrictions, rows_to_fill, energy)
elif load_type == LoadType.BREAKABLE:
self.compute_breakable(
schedule,
optimization_sense,
time_restrictions,
cost,
rows_to_fill,
energy,
)
elif load_type == LoadType.SHIFTABLE:
self.compute_shiftable(
schedule,
optimization_sense,
time_restrictions,
cost,
rows_to_fill,
energy,
)
else:
raise ValueError(f"Unknown load type '{load_type}'")
return schedule.tz_convert(self.start.tzinfo)
def block_invalid_starting_times_for_whole_process_scheduling(
self,
load_type: LoadType,
time_restrictions: pd.Series,
duration: timedelta,
rows_to_fill: int,
) -> pd.Series:
"""Blocks time periods where the load cannot be schedule into, making
sure no other time restrictions runs in the middle of the activation of the load
More technically, this function applying an erosion of the time_restrictions array with a block of length duration.
Then, the condition if time_restrictions.sum() == len(time_restrictions):, makes sure that at least we have a spot to place the load.
For example:
time_restriction = [1 0 0 1 1 1 0 0 1 0]
# applying a dilation with duration = 2
time_restriction = [1 0 1 1 1 1 0 1 1 1]
We can only fit a block of duration = 2 in the positions 1 and 6. sum(time_restrictions) == 8,
while the len(time_restriction) == 10, which means we have 10-8=2 positions.
:param load_type: INFLEXIBLE, SHIFTABLE or BREAKABLE
:param time_restrictions: boolean time series indicating time periods in which the load cannot be scheduled.
:param duration: (datetime) duration of the length
:param rows_to_fill: (int) time periods that the load lasts
:return: filtered time restrictions
"""
if load_type in [LoadType.INFLEXIBLE, LoadType.SHIFTABLE]:
# get start time instants that are not feasible, i.e. some time during the ON period goes through
# a time restriction interval
time_restrictions = (
time_restrictions.rolling(duration).max().shift(-rows_to_fill + 1)
)
time_restrictions = (time_restrictions == 1) | time_restrictions.isna()
if time_restrictions.sum() == len(time_restrictions):
raise ValueError(
"Cannot allocate a block of time {duration} given the time restrictions provided."
)
else: # LoadType.BREAKABLE
if (~time_restrictions).sum() < rows_to_fill:
raise ValueError(
"Cannot allocate a block of time {duration} given the time restrictions provided."
)
return time_restrictions
def compute_inflexible(
self,
schedule: pd.Series,
time_restrictions: pd.Series,
rows_to_fill: int,
energy: float,
) -> None:
"""Schedule load as early as possible."""
start = time_restrictions[~time_restrictions].index[0]
schedule.loc[start : start + self.resolution * (rows_to_fill - 1)] = energy
def compute_breakable(
self,
schedule: pd.Series,
optimization_sense: OptimizationSense,
time_restrictions: pd.Series,
cost: pd.DataFrame,
rows_to_fill: int,
energy: float,
) -> None:
"""Break up schedule and divide it over the time slots with the largest utility (max/min cost depending on optimization_sense)."""
cost = cost[~time_restrictions].reset_index()
if optimization_sense == OptimizationSense.MIN:
cost_ranking = cost.sort_values(
by=["event_value", "event_start"], ascending=[True, True]
)
else:
cost_ranking = cost.sort_values(
by=["event_value", "event_start"], ascending=[False, True]
)
schedule.loc[cost_ranking.head(rows_to_fill).event_start] = energy
def compute_shiftable(
self,
schedule: pd.Series,
optimization_sense: OptimizationSense,
time_restrictions: pd.Series,
cost: pd.DataFrame,
rows_to_fill: int,
energy: float,
) -> None:
"""Schedules a block of consumption/production of `rows_to_fill` periods to maximize a utility."""
block_cost = simplify_index(
cost.rolling(rows_to_fill).sum().shift(-rows_to_fill + 1)
)
if optimization_sense == OptimizationSense.MIN:
start = block_cost[~time_restrictions].idxmin()
else:
start = block_cost[~time_restrictions].idxmax()
start = start.iloc[0]
schedule.loc[start : start + self.resolution * (rows_to_fill - 1)] = energy
def deserialize_flex_config(self):
"""Deserialize flex_model using the schema ShiftableLoadFlexModelSchema and
flex_context using FlexContextSchema
"""
if self.flex_model is None:
self.flex_model = {}
self.flex_model = ShiftableLoadFlexModelSchema(
start=self.start, end=self.end, sensor=self.sensor
).load(self.flex_model)
self.flex_context = FlexContextSchema().load(self.flex_context)