flexmeasures.data.models.planning.storage

Module Attributes

flexmeasures.data.models.planning.storage.SCHEDULING_RESULT_KEY = 'scheduling_result'

Key used to store and retrieve the SchedulingJobResult in RQ job metadata and in the multi-result list returned by StorageScheduler.compute().

flexmeasures.data.models.planning.storage.REACTION_DIRECTIONS_UP = {'consumption-up', 'production-down'}

The reaction directions that move a device’s power up (consumption-up, production-down) or down (consumption-down, production-up).

Functions

flexmeasures.data.models.planning.storage.add_storage_constraints(start: datetime, end: datetime, resolution: timedelta, soc_at_start: float, soc_targets: list[dict[str, datetime | float]] | Series | None, soc_maxima: list[dict[str, datetime | float]] | Series | None, soc_minima: list[dict[str, datetime | float]] | Series | None, soc_max: float | None, soc_min: float | None) → DataFrame

Collect all constraints for a given storage device in a DataFrame that the device_scheduler can interpret.

Parameters:
  • start – Start of the schedule.

  • end – End of the schedule.

  • resolution – Timedelta used to resample the constraints to the resolution of the schedule.

  • soc_at_start – State of charge at the start time.

  • soc_targets – Exact targets for the state of charge at each time.

  • soc_maxima – Maximum state of charge at each time.

  • soc_minima – Minimum state of charge at each time.

  • soc_max – Maximum state of charge at all times, if configured.

  • soc_min – Minimum state of charge at all times, if configured.

Returns:

Constraints (StorageScheduler.COLUMNS) for a storage device, at each time step (index). See device_scheduler for possible column names.

flexmeasures.data.models.planning.storage.build_device_soc_values(soc_values: Quantity | list[dict[str, datetime | float]] | Series | None, soc_at_start: float, start_of_schedule: datetime, end_of_schedule: datetime, resolution: timedelta) → Series

Utility function to create a Pandas series from SOC values we got from the flex-model.

Should set NaN anywhere where there is no target.

SOC values should be indexed by their due date. For example, for quarter-hourly targets from 5 to 6 AM:

>>> df = pd.Series(data=[1, 1.5, 2, 2.5, 3], index=pd.date_range(pd.Timestamp("2010-01-01T05"), pd.Timestamp("2010-01-01T06"), freq=pd.Timedelta("PT15M"), inclusive="both"))
>>> print(df)
2010-01-01 05:00:00    1.0
2010-01-01 05:15:00    1.5
2010-01-01 05:30:00    2.0
2010-01-01 05:45:00    2.5
2010-01-01 06:00:00    3.0
Freq: 15min, dtype: float64

TODO: this function could become the deserialization method of a new TimedEventSchema (targets, plural), which wraps TimedEventSchema.

flexmeasures.data.models.planning.storage.create_constraint_violations_message(constraint_violations: list) → str

Create a human-readable message with the constraint_violations.

Parameters:

constraint_violations – List with the constraint violations.

Returns:

Human-readable message.

flexmeasures.data.models.planning.storage.default_soc_min(stock_model: dict) → float | None

Return the lower SoC bound to assume for a stock whose flex-model sets no soc-min.

An energy stock cannot hold less than nothing, so its default lower bound is 0. That reasoning only holds for energy (and shares of a capacity): once fill levels may come in other units (see issue #2847), such as degrees Celsius for a freezer, 0 is no longer a physical boundary, and this function should return None for those units. For now, all stocks are converted to MWh, so the default is always 0.

Parameters:

stock_model – The deserialized flex-model entry that holds the stock’s SoC parameters.

Returns:

The default lower bound in the stock’s unit (currently MWh), or None for no lower bound.

flexmeasures.data.models.planning.storage.evaluate_expression(values: dict[str, ndarray], expression: str) → ndarray

Evaluate a single column, or the difference or product of two columns.

Supported expressions are column, column - column and column * column. Operators must be surrounded by spaces, since column names may contain dashes.

Parameters:
  • values – Float arrays by column name.

  • expression – Expression to evaluate.

Returns:

Array with the result of the expression.

flexmeasures.data.models.planning.storage.get_pattern_match_word(word: str) → str

Get a regex pattern to match a word

The conditions to delimit a word are:

  • start of line

  • whitespace

  • end of line

  • word boundary

  • arithmetic operations

Returns:

regex expression

flexmeasures.data.models.planning.storage.nearest_soc_belief(sensor: Sensor, start: datetime, lookup_radius: timedelta, **source_filters) → Series | None

Find the nearest deterministic SoC reading, favoring the later one on a tie.

flexmeasures.data.models.planning.storage.prepend_series(series: Series, value) → Series

Prepend a value to a time series

Parameters:
  • series – series containing the timed values

  • value – value to place in the first position

flexmeasures.data.models.planning.storage.report_commitment_costs_by_name(commitments, costs) → dict[str, float]

Key commitment costs by commitment name.

Costs of same-named commitments of the same provenance are summed (e.g. one custom commitment bound per device). A custom commitment whose name collides with a scheduler-internal one is reported under “<name> (custom)” instead, to keep both cost entries readable.

flexmeasures.data.models.planning.storage.soc_lookup_radius(resolution: timedelta, slack_steps: int = 4) → timedelta

Return the time allowed on either side of the schedule start for an SoC reading.

flexmeasures.data.models.planning.storage.validate_constraints(constraints_df: DataFrame, constraints: list[tuple[str, str, str]], round_to_decimals: int | None = 6) → list[dict]

Validate the feasibility of several constraints on the same dataframe.

Evaluates the constraints on numpy arrays rather than with pd.eval, which is slow on large dataframes. Missing values are treated as 0 when comparing, but time steps where any involved column is missing are not reported.

Parameters:
  • constraints_df – DataFrame with the constraints.

  • constraints – List of (lhs, inequality, rhs) tuples. Each side is a column name, or the difference (” - “) or product (” * “) of two column names.

  • round_to_decimals – Number of decimals to round off to before validating constraints.

Returns:

List of constraint violations, specifying their time, constraint and violation.

flexmeasures.data.models.planning.storage.validate_power_constraints(constraints: DataFrame) → list[dict]

Check that the power constraints of a device are consistent, e.g. derivative min <= derivative max.

  1. Power validation in the same time frame

    D.1) derivative min <= derivative max D.2) derivative min <= derivative equals D.3) derivative equals <= derivative max

These checks apply to any device, including devices without a stock, for which the stock-based validation of validate_storage_constraints does not apply. Time steps where any involved constraint is unset are skipped.

Parameters:

constraints – dataframe containing the constraints of a device.

Returns:

List of constraint violations, specifying their time, constraint and violation.

flexmeasures.data.models.planning.storage.validate_storage_constraints(constraints: DataFrame, soc_at_start: float, soc_min: float | None, soc_max: float | None, resolution: timedelta) → list[dict]

Check that the storage constraints are fulfilled, e.g min <= equals <= max.

  1. Global validation

    A.1) min >= soc_min A.2) max <= soc_max

  2. Validation in the same time frame

    B.1) min <= max B.2) min <= equals B.3) equals <= max

  3. Validation in different time frames

    C.1) equals(t) - equals(t-1) <= derivative_max(t) C.2) derivative_min(t) <= equals(t) - equals(t-1) C.3) min(t) - max(t-1) <= derivative_max(t) C.4) max(t) - min(t-1) >= derivative_min(t) C.5) equals(t) - max(t-1) <= derivative_max(t) C.6) derivative_min(t) <= equals(t) - min(t-1)

Parameters:
  • constraints – dataframe containing the constraints of a storage device

  • soc_at_start – State of charge at the start time.

  • soc_min – Minimum state of charge at all times, if configured.

  • soc_max – Maximum state of charge at all times, if configured.

  • resolution – Constant duration between the start of each time step.

Returns:

List of constraint violations, specifying their time, constraint and violation.

Classes

class flexmeasures.data.models.planning.storage.MetaStorageScheduler(sensor: Sensor | None = None, start: datetime | None = None, end: datetime | None = None, resolution: timedelta | None = None, belief_time: datetime | None = None, asset_or_sensor: GenericAsset | Sensor | None = None, round_to_decimals: int | None = 6, flex_model: list[dict] | dict | None = None, flex_context: dict | None = None, return_multiple: bool = False)

This class defines the constraints of a schedule for a storage device from the flex-model, flex-context, and sensor and asset attributes

_bare_commodity_context(commodity: str) → dict

Return the context of a commodity that the flex-context lists no context for.

Such a commodity has no grid connection or prices, which makes it an internal node whose devices balance each other, e.g. the steam between a device turning electricity into steam and a device consuming that steam. Its devices relax their constraints as a bare commodity context does by default, rather than following the breach prices and relax flags at the top level of the flex-context, which concern electricity.

_build_scoped_commitment(commitment_spec, scoped_sensors, scoped_group, commitment_index) → FlowCommitment | None

Build one aggregate-flow FlowCommitment for a scoped commitment.

Returns None (logged) when the scope matches no device in the flex-model, so the commitment binds nothing rather than failing the whole schedule.

Raises:

ValueError – When the scoped devices span more than one commodity.

static _default_missing_directional_capacity_to_zero(flex_model_d: dict) → None

Given a missing capacity opposite a non-zero directional capacity, default the missing capacity to zero.

_get_commodity_contexts(commodities: Iterable[str] = ()) → dict[str, dict]

Return commodity-specific flex-contexts.

Supports the new format:

"commodities": [
    {"commodity": "electricity", ...},
    {"commodity": "gas", ...},
]

and keeps backwards compatibility with old top-level fields.

Parameters:

commodities – Commodities in use by devices, each of which gets a bare context if the flex-context lists none for it, as if the flex-context listed just {“commodity”: …} (see _bare_commodity_context).

_get_device_power_capacity(flex_model: list[dict], assets: list[GenericAsset], query_window: tuple[datetime, datetime], resolution: timedelta, beliefs_before: datetime | None) → list[Sensor | SensorReference | list[dict] | Quantity | Series]

The device power capacity for each device must be known for the optimization problem to stay bounded.

We search for the power capacity in the following order:

  1. Look for the power_capacity_in_mw field in the deserialized flex-model.

  2. Look for the power-capacity flex-model field of the asset.

  3. Look for the greatest device consumption-capacity or production-capacity.

  4. Look for the site-power-capacity attribute of the asset.

_get_largest_device_capacity(flex_model_d: dict, query_window: tuple[datetime, datetime], resolution: timedelta, beliefs_before: datetime | None) → Sensor | SensorReference | list[dict] | Quantity | Series | None

Return the largest configured directional capacity, if any.

_get_soc_capacity_for_percent_conversion(flex_model: dict, sensor: Sensor | None = None) → str

Return the capacity used to convert percentage-based SoC values.

Parameters:
  • flex_model – Flex model containing the SoC configuration.

  • sensor – Optional scheduled power sensor whose asset can provide fallback capacity.

Returns:

Capacity expressed in MWh.

_get_soc_lookup_radius(sensor: Sensor | None = None, slack_steps: int = 4) → timedelta

Return the half-width of the SoC lookup interval.

We search for a nearby SoC value in the interval [self.start - slack_steps * resolution, self.start + slack_steps * resolution]. Using four resolution steps by default keeps the lookup tolerant to small timing offsets while still rejecting stale values. For example, a 15-minute resolution yields a 1-hour lookup radius.

Parameters:
  • sensor – Optional sensor whose resolution should be used.

  • slack_steps – Number of resolution steps accepted on either side of the schedule start.

Returns:

Half-width of the SoC lookup interval.

static _is_non_zero_capacity(capacity: str | int | float | Quantity | Sensor | SensorReference | list) → bool

Return whether a configured capacity should imply zero capacity in the opposite direction.

_possibly_relax_off_tick_soc_constraints(flex_model: dict, sensor: Sensor | None, power_sensor: Sensor | None = None) → None

Enable SoC constraint relaxation if the (serialized) flex-model contains off-tick SoC events.

The detection uses the scheduler’s actual resolution (falling back to the sensor’s event resolution), matching the resolution later used to project off-tick SoC constraints onto the scheduling ticks.

When relaxation is enabled purely because of off-tick projection (rather than by the user’s own flex-context settings), softening is scoped to the stocks that actually use off-tick SoC constraints (tracked here by their stock key, so all devices sharing the stock are covered). An entry without a resolvable stock key is tracked by its power sensor instead (its stock gets a synthetic key only later, when the device inventory is built).

_prepare(skip_validation: bool = False) → tuple

This function prepares the required data to compute the schedule:

  • price data

  • device constraint

  • ems constraints

Parameters:

skip_validation – If True, skip validation of constraints specified in the data.

Returns:

Input data for the scheduler

_record_soc_at_start_datetime(stock_key, soc_datetime: datetime | None) → None

Remember at which time a stock’s starting state of charge is actually known.

Keyed by the stock key (a None key covers the single-sensor case where the stock key cannot be resolved, e.g. a state-of-charge time series). Used to project an off-tick starting SoC onto the next scheduling tick (see flexmeasures.data.models.planning.soc_projection.project_off_tick_soc_at_start()).

_resolve_commitment_scope(scoped_sensors, scoped_group) → tuple[list[int], str]

Resolve a scoped commitment’s device set to canonical solver indices.

Both scopes include a device whether it is flexible or inflexible: a group scope yields the group’s (leaf) members, and a sensors scope yields the devices recording the listed power sensors. So listing a group’s member sensors resolves to the same set as scoping by that group. Canonical indices always come from the device inventory, never from re-enumerating raw flex-model lists.

The commitment then binds the net signed aggregate of these devices’ flow (consumption positive, production negative), so consumers add, producers subtract, and any inflexible (fixed) member contributes its fixed signed power.

Returns:

A (sorted device indices, human-readable scope description) pair.

_resolve_soc_at_start_from_sensor(state_of_charge_sensor: Sensor | SensorReference, flex_model: dict, sensor: Sensor | None = None) → float

Resolve soc-at-start from a state-of-charge sensor.

Parameters:
  • state_of_charge_sensor – Instantaneous SoC sensor or sensor reference (with optional source filters).

  • flex_model – Flex model containing the SoC configuration.

  • sensor – Optional scheduled power sensor.

Returns:

Starting SoC in MWh.

_resolve_soc_at_start_from_state_of_charge(flex_model: dict, sensor: Sensor | None = None) → float | None

Resolve soc-at-start from the state-of-charge field.

Parameters:
  • flex_model – Flex model containing the SoC configuration.

  • sensor – Optional scheduled power sensor.

Returns:

Starting SoC in MWh if it can be inferred.

_resolve_soc_at_start_from_time_series(soc_time_series: list[dict], sensor: Sensor | None = None, stock_key=None) → float

Resolve soc-at-start from a state-of-charge time series.

Parameters:
  • soc_time_series – SoC time series specification.

  • sensor – Optional scheduled power sensor.

  • stock_key – Key of the stock whose SoC is being resolved, if known (a time series does not resolve to a stock key by itself).

Returns:

Starting SoC in MWh.

_resolve_stock_soc_at_start(stock_model: dict, sensor: Sensor | None = None, stock_key=None) → float | None

Resolve or default a stock’s soc-at-start (in MWh).

Used in multi-device mode, where soc-at-start is not resolved during deserialization. This mirrors ensure_soc_at_start() for the deserialized stock-owning entry: resolve a configured state_of_charge, fall back to the legacy asset attribute, and finally default constrained storage to an empty stock.

In line with single-sensor mode’s ensure_soc_at_start(), a state of charge that is given but cannot be resolved fails the schedule: a ValueError is raised, e.g. for a state-of-charge sensor without a recent value.

Parameters:
  • stock_model – The deserialized flex-model entry owning the stock’s SoC parameters.

  • sensor – The stock’s (first) device power sensor, used for the SoC lookup radius.

Returns:

Starting stock in MWh, or None if the entry has no state-of-charge semantics.

_soc_breach_price(commodity_contexts: dict[str, dict], commodity: str, flex_model_d: dict, field: str)

Look up a SoC breach price for a device, in the context of its commodity.

In order of precedence, the price comes from:

  1. the device’s priority, if its flex-model names one, and the priorities of the device’s commodity context set the price for it,

  2. the device’s commodity context, which also holds the default breach prices, unless it keeps its SoC constraints hard.

Parameters:
  • commodity_contexts – The commodity contexts, as returned by _get_commodity_contexts.

  • commodity – The commodity of the device.

  • flex_model_d – The flex-model of the device.

  • field – One of “soc_minima_breach_price”, “soc_maxima_breach_price” and “soc_delta_breach_price”.

Returns:

The breach price, or None if the SoC constraints stay hard.

_soc_relaxation_applies_to(stock_key, sensor_d: Sensor | None = None) → bool

Whether SoC constraint softening applies to the stock with this key.

Softening applies to all stocks, unless relaxation was auto-enabled purely for off-tick SoC constraint projection, in which case it is scoped to the stocks that use off-tick SoC constraints (covering all devices sharing them). A stock tracked by power sensor (for lack of a resolvable stock key) is matched via the device’s power sensor.

_soc_relaxation_user_enabled() → bool

Whether the user’s own (serialized) flex-context already softens SoC constraints.

That is the case when any context defines a SoC breach price explicitly (also for one of its priorities), sets relax-soc-constraints to True, or leaves relaxation to the general relax-constraints flag (which defaults to True). The top level only counts as a context when it serves as the electricity context, i.e. when no electricity context is listed (see merge_flex_contexts).

_validate_priorities()

Check that each priority named in the flex-model is listed in the priorities of the device’s commodity context.

A misspelled priority would otherwise silently fall back to the breach prices of the commodity context.

compute_schedule() → Series | None

Schedule a battery or Charge Point based directly on the latest beliefs regarding market prices within the specified time window. For the resulting consumption schedule, consumption is defined as positive values.

Deprecated method in v0.14. As an alternative, use MetaStorageScheduler.compute().

convert_to_commitments(**timing_kwargs) → list[FlowCommitment | StockCommitment]

Convert list of commitment specifications (dicts) to a list of FlowCommitments.

Commitments are collected from the top-level flex-context and from each commodity context; a commitment within a commodity context always binds that context’s commodity (matching how the UI editor scopes commitments per commodity tab).

An unscoped commitment binds the aggregate flow of all its commodity’s devices; a scoped commitment (a sensors list or group reference) binds a subset. Device indices come from the device inventory, never from the raw flex-model list.

User-given commitment names are kept as is, but the resulting commitments are tagged with provenance “custom”, so cost reporting can tell them apart from the commitments the scheduler sets up internally (e.g. “electricity net energy”).

deserialize_flex_config()

Deserialize storage flex model and the flex context against schemas. Before that, we fill in values from wider context, if possible. Mostly, we allow several fields to come from sensor attributes. TODO: this work could maybe go to the schema as a pre-load hook (if we pass in the sensor to schema initialization)

Note: Before we apply the flex config schemas, we need to use the flex config identifiers with hyphens,

(this is how they are represented to outside, e.g. by the API), after deserialization we use internal schema names (with underscores).

enable_relax_soc_constraints() → None

Relax SoC constraints when off-tick SoC events require scheduling-tick projection.

Projection can add bounds (and stricter combinations of bounds), which could render the problem infeasible if they remain hard constraints. Therefore, relax-soc-constraints is enabled unless the user explicitly disabled it, in which case we respect that choice and only log a warning.

ensure_soc_at_start(flex_model: dict | None = None, sensor: Sensor | None = None) → dict

Ensure we have a starting state of charge - if needed. Preferably, a starting soc is given. Otherwise, we try to retrieve the current state of charge from the configured state-of-charge field. If that doesn’t work, we try the (old-style) asset attribute. Finally, we default the starting soc to 0 when there are soc constraints. Some assets don’t use the concept of a state of charge, and without soc targets or bounds the starting soc doesn’t matter.

get_min_max_targets() → tuple[float | None, float | None]

This happens before deserializing the flex-model.

include_reaction: bool = False

Whether any flex-model device opted in to the reaction rules by setting react to true. When True and return_multiple is True, compute() also returns one "reaction_rule" entry per flexible device that set react, containing per-slot values for the reaction rule setpoint = clip(p - react * (m_uncontrolled - reference), band), where m_uncontrolled is the measured uncontrolled power at the connection, see Reacting to deviations at the connection.

possibly_extend_end(soc_targets, sensor: Sensor = None)

Extend schedule period in case a target exceeds its end.

The schedule’s duration is possibly limited by the server config setting ‘FLEXMEASURES_MAX_PLANNING_HORIZON’.

todo: when deserialize_flex_config becomes a single schema for the whole scheduler,

this function would become a class method with a @post_load decorator.

resolve_flex_config() → dict

A storage scheduler also reads flex config from the asset tree, so merge that in before recording it.

Without this, the data source would describe only what the trigger message said, which for a minimal trigger message is next to nothing.

class flexmeasures.data.models.planning.storage.StorageScheduler(sensor: Sensor | None = None, start: datetime | None = None, end: datetime | None = None, resolution: timedelta | None = None, belief_time: datetime | None = None, asset_or_sensor: GenericAsset | Sensor | None = None, round_to_decimals: int | None = 6, flex_model: list[dict] | dict | None = None, flex_context: dict | None = None, return_multiple: bool = False)
_add_group_schedules(storage_schedule: dict, ems_schedule: list[Series]) → dict

Compute each group’s aggregate power schedule.

  • Sensor-referenced groups: the aggregate is recorded under the group’s own power sensor (as before), added in-place to storage_schedule (still in MW, native scheduler convention; unit conversion happens later, alongside other device sensors).

  • Asset-referenced groups: the group entry defines no power sensor of its own; instead, the aggregate is recorded via the group entry’s own consumption/ production output sensors, if defined.

  • Either kind of group may additionally define consumption/production output sensors, in which case the aggregate is also split and recorded there.

The consumption/production output schedules are returned separately (already unit-converted, like _build_consumption_production_schedules) rather than added to storage_schedule, to avoid double unit conversion.

Returns:

Dict mapping each group output sensor to its power schedule.

static _apply_stock_delta_slack(device_constraints: list[DataFrame], model, sensors: list, resolution: timedelta, currency_unit: str) → list[DataFrame]

Take the part of each device’s stock delta that the plan leaves unapplied out of its stock delta.

The state-of-charge schedule is then built from the stock delta the plan actually applies, so it shows the stock the plan expects, rather than a stock that crosses soc-min or soc-max. The device constraints are copied where they change, so the originals are left as they were. A warning states how much forecast usage and gain the plan left out, per device, and at what price. It states what was left out, not why: usually, the forecast outruns what the device can deliver, but a soc-delta-breach-price set below the energy prices also makes leaving the forecast out the cheaper option.

static _build_consumption_production_schedules(flex_model: list[dict], ems_schedule: DataFrame) → dict

Build consumption and/or production power schedules for devices that define output sensors.

Each device’s flex model may define a consumption sensor, a production sensor, or both. The schedule stored on each sensor depends on which sensors are defined:

  • Only consumption sensor defined: the full power schedule is written to that sensor using the scheduler’s native sign convention (consumption positive, production negative). make_schedule applies no further sign change because the sensor already has consumption_is_positive=True.

  • Only production sensor defined: the full power schedule is written to that sensor in the scheduler’s native sign convention (consumption positive, production negative). make_schedule inverts the sign based on the sensor’s consumption_is_positive=False attribute so that production is stored as positive values.

  • Both consumption and production sensors defined: only the non-negative part of the schedule (charging / consuming) is written to the consumption sensor, and only the non-positive part (discharging / producing, still as negative values) is written to the production sensor. make_schedule inverts the sign for the production sensor.

The consumption_is_positive attribute is set on each output sensor when the scheduling job is created (see create_scheduling_job), not here. This method only clips the series; sign handling is left entirely to make_schedule.

Unit conversion from MW to each sensor’s unit is applied.

Parameters:
  • flex_model – List of per-device flex models (after deserialization).

  • ems_schedule – DataFrame of per-device power schedules in MW (consumption positive).

Returns:

Dict mapping each output sensor to its power schedule.

static _build_soc_schedule(flex_model: list[dict], ems_schedule: list[Series], soc_at_start: list[float], device_constraints: list, resolution: timedelta, stock_groups: dict[int, list[int]]) → tuple[dict, dict]

Build the state-of-charge schedule for each stock group.

Supports both:

  • original logic: one device per stock group

  • local/shared-stock logic: multiple devices contribute to one shared stock

For shared stock groups, each device contribution is integrated separately with its own conversion efficiencies and stock delta, then summed. The shared initial stock is integrated along with the first device’s contribution, so that the storage losses apply to it, too. All contributions use the group’s storage efficiency, taken from its first device, just like the solver does (see group_stock_balance).

Also computes the MWh SoC for devices that have soc-minima or soc-maxima constraints (even without a state-of-charge sensor) so that unresolved targets can be checked later. For a shared stock group, every device in the group is tracked against the group’s combined MWh SoC series, since they share the same physical stock.

Converts the integrated stock schedule from MWh to the state-of-charge sensor unit. For ‘%’ sensors, the soc-max flex-model field is used as capacity. If soc-max is missing or zero for a ‘%’ sensor, the schedule is skipped with a warning.

Note: soc-max is a QuantityField (not a VariableQuantityField), so it is always a float after deserialization and cannot be a sensor reference. The isinstance guard below is therefore a defensive check for forward-compatibility.

Returns:

Tuple of (soc_schedule keyed by SoC sensor in sensor unit, soc_schedule_mwh keyed by device index in MWh).

_compute_commodity_aggregate_schedules(storage_schedule: dict, ems_schedule: DataFrame) → None

Compute per-commodity aggregate power flows for aggregate-consumption and aggregate-production sensors.

This method populates the storage_schedule dict with aggregate schedules for each commodity that defines aggregate-consumption and/or aggregate-production sensors in its commodity context.

The sign convention and split logic follows the same pattern as _build_consumption_production_schedules:

  • Only aggregate-consumption defined: full aggregate schedule (consumption +, production -)

  • Only aggregate-production defined: full aggregate schedule (consumption +, production -) (sign will be flipped by make_schedule based on consumption_is_positive=False)

  • Both defined: consumption sensor gets non-negative part, production sensor gets non-positive part (sign will be flipped for production by make_schedule)

For backwards compatibility, when no commodity_contexts are defined, all devices are treated as electricity devices and use the top-level flex-context fields.

Parameters:
  • storage_schedule – Dict to populate with aggregate schedules (will be modified in-place)

  • ems_schedule – DataFrame of per-device power schedules in MW (consumption positive)

_compute_reaction_rules(sensors: list, ems_schedule: list[Series], device_constraints: list[DataFrame], ems_constraints: list[DataFrame], commitments: list, initial_stock: list[float], resolution: timedelta) → list[dict]

Compute the per-slot reaction rule of each flexible device that set react, see Reacting to deviations at the connection.

The client applies setpoint = clip(p - react * (m_uncontrolled - reference), band) per slot, where p is the planned power and m_uncontrolled the measured uncontrolled power at the connection.

Per flexible device and slot, this returns:

  • p: the planned power (MW, consumption positive), the schedule itself;

  • react: the share of the deviation from the balance point (m_uncontrolled - reference) the device absorbs, 1 where the price kink is within the device’s reach, 0 otherwise. The kink is within reach when the plan sits on a kink (see _intended_connection_power()), the device could reach the power that balances the connection at it (regardless of its stock), and its band (see below) is more than a single point. The plan is at the kink when its connection power equals the intended power (within the float tolerance), when it misses the kink only because of the device’s operation modes (see _mode_shaped_miss()), or when a capacity binds (hard, or breach-priced and met or breached); otherwise it is off the kink. A capacity kink out of the device’s reach falls back to the price kink, where there is one. Shares in between are reserved for a later version. Reacting devices form a chain in flex-model order, each absorbing what the devices before it could not; the client walks that chain. A device whose reaction time exceeds the scheduling resolution gets 0;

  • reference: the uncontrolled power the plan is balanced against. Normally the uncontrolled forecast the plan assumed: the inflexible device forecasts of the commodity, without any flexible device’s plan. Only where the device’s operation modes keep the plan from balancing the connection exactly (see _mode_shaped_miss()), it is the intended connection power minus the planned power of the reacting devices, i.e. the forecast shifted by the plan’s miss: where the plan holds the connection at zero, the negative of the planned device power, and where a capacity binds, the capacity minus it;

  • band: where the device reacts, every range the plan leaves feasible (see _device_band_ranges()): the device’s operation modes cut to its own limits, each narrowed by state-of-charge reachability under hard and soft limits alike, and dropped when reachability empties it. Off the kink, the band only keeps the kink’s side of the plan (the ranges at or above p where the connection power is above the intended power, at or below p where it is below), so the device absorbs deviations that would push the connection across the kink, and follows the plan against deviations that push it further away; where that leaves a single point, such as at the device’s power limit, the device gets react 0. Whether and when the device changes mode is the controller’s policy; a reacting device rounds a value that falls in a hole to the edge on the side of its current mode, which at the start of a slot is the plan’s range, so the house as forecast returns the plan. A device with react 0 gets the single range (p, p).

All values are in MW (consumption positive). Range sides are finite, since the scheduler requires a power capacity for every device. Soft (breach-priced) capacities do not narrow the band; only hard bounds do. Each entry also carries retrigger_on_band_exit, whether the client should trigger a new schedule when a reaction leaves its band.

_compute_unresolved_targets(flex_model: list[dict], soc_schedule_mwh: dict, start: datetime, end: datetime, resolution: timedelta, most_relevant_only: bool = False) → tuple[list, list]

Compute unmet and met SoC minima/maxima targets per device.

For each device that has soc-minima or soc-maxima constraints in the flex model, compares the computed MWh SoC schedule against those constraints. Devices without a state_of_charge Sensor are included as long as a device key can be determined from the power sensor.

The result includes asset ID for each constraint. Devices for which an asset ID cannot be determined are skipped.

Constraints are evaluated over the window (start + resolution, end) (i.e. the first scheduled slot through the end of the schedule). The start slot itself is the initial condition (soc_at_start), not a scheduled value, so it is excluded.

Note: soc-targets are modelled as hard constraints and are not checked here, as by definition the scheduler will not allow any deviation from them.

Parameters:
  • flex_model – The deserialized flex model (list of per-device dicts).

  • soc_schedule_mwh – MWh SoC schedule keyed by device index d.

  • start – Start of the schedule.

  • end – End of the schedule.

  • resolution – Schedule resolution.

  • most_relevant_only – If False (the default), report every violated/met slot. If True, report only the single most relevant slot (the first violation, or the tightest margin). Either way, the result holds a list.

Returns:

A tuple (unresolved, resolved).

unresolved is a list of dicts, each with "asset" field and constraint info. Each constraint entry is a list of dicts {"datetime": <ISO 8601 UTC string>, "violation": "<value> kWh"} (one per violated slot, or just the first if most_relevant_only is True), where violation is always positive.

resolved is also a list of dicts with "asset" field and constraint info. Each constraint entry is a list of dicts {"datetime": <ISO 8601 UTC string>, "margin": "<value> kWh"} (one per met slot, or just the slot with the tightest/smallest positive margin if most_relevant_only is True).

static _cut_to_directions(ranges: list[tuple[float, float]], p: float, directions: set[str], tolerance: float) → list[tuple[float, float]]

Cut power ranges to the directions a device may move in from its planned power p (see _direction_bounds()).

Ranges left empty by the cut are dropped; a range holding p keeps holding it.

static _deduplicate_outputs(outputs: list[dict]) → list[dict]

Safety net: never let one sensor appear in multiple outputs.

All outputs are saved with identical belief coordinates in the same scheduling-job transaction, so a duplicate sensor is guaranteed to violate the timed_belief primary key and fail the whole job. Keep the first entry for a sensor and drop (with a warning) any later one.

_device_band_ranges(d: int, ems_schedule: list[Series], device_constraints: list[DataFrame], initial_stock: list[float], directions: set[str], tolerance: float) → tuple[list[list[tuple[float, float]]], list[list[tuple[float, float]]]]

Per slot, all the ranges device d may move within, with and without the stock narrowing.

Both start from the device’s own bounds, cut to its reaction directions and split by its operation modes (see _response_band()); the first list is also narrowed so that the stock constraints stay reachable (see _stock_reachability_band()), the second says how far the device could reach regardless of its stock.

static _direction_bounds(p: float, directions: set[str], tolerance: float) → tuple[float, float]

The power bounds a device may move within, given its planned power p and the directions it can respond in.

consumption-up and production-down open the range above p, each on its own half-axis, and consumption-down and production-up open the range below p.

_electricity_device_indices() → list[int]

Return the device indices (flexible and inflexible) belonging to the electricity commodity.

static _flow_to_stock_change(power: ndarray, eta_up: ndarray, eta_down: ndarray) → ndarray

Map device power (MW, consumption positive) to a per-slot stock change.

Applies the charging efficiency to consumed flows and the (inverse) discharging efficiency to produced flows, mirroring the LP’s stock accounting.

_intended_connection_power(commodity_to_devices: dict[str, list[int]], ems_schedule: list[Series], ems_constraints: list[DataFrame], commitments: list, tolerance: float) → tuple[dict[str, ndarray], dict[str, ndarray]]

Per commodity and slot, the connection powers at which the plan sits on a price kink, NaN where it does not.

Two kinks are returned: the price kink at zero, where the production price is below the consumption price or at or below zero, and the capacity kink, where the plan sits at the site capacity (within the float tolerance). A site capacity is a kink whether it is hard or breach-priced (soft), since the cost jumps by the breach price where the connection crosses it. Where the plan breaches a soft capacity on purpose, the capacity kink is still at that capacity. Where both a hard and a soft capacity bind, the capacity kink is at the hard one. A plan held just below the capacity by a device’s operation modes is not at the capacity kink; it may still be at the price kink.

static _merge_group_output_schedules(consumption_production_schedule: dict, group_output_schedules: dict) → None

Merge group output schedules (already unit-converted) into consumption_production_schedule in-place, avoiding overwrite of a device’s own output sensor with a group’s.

static _mode_shaped_miss(ranges: list[tuple[float, float]], balancing_power: float, plan: float, tolerance: float) → bool

Whether a plan misses the balancing power only because the device’s modes leave a gap there.

That is the case when the power that would balance the connection lies strictly inside a gap between two ranges, and the plan sits at an edge of that gap (the planner’s nearest feasible point).

_reconstruct_commodity_to_devices() → dict[str, list[int]]

Return the mapping of commodity -> device indices, as enumerated by the device inventory.

Device enumeration order (the inventory’s canonical order, also used by _prepare()):

  1. flexible devices (from the flex-model), in order,

  2. top-level (electricity) inflexible devices, in order,

  3. each commodity context’s own inflexible devices, in the order the commodity contexts are given (within each context, fields are read in INFLEXIBLE_DEVICE_FIELDS order).

The returned device indices line up with entries of ems_schedule / device_constraints.

static _response_band(p: float, lo: float, hi: float, modes: list[tuple[float, float]] | None, directions: set[str], tolerance: float) → list[tuple[float, float]]

The power ranges a device may move within during one slot, given its planned power p.

Starts from the device’s own bounds [lo, hi] (MW, consumption positive), cut to the directions the device can respond in (see _direction_bounds()). The result is then split by the device’s operation modes, so that no range spans a hole between two modes. The range holding p is widened to include p exactly, against numerical noise in the plan.

Returns:

A sorted list of disjoint (min, max) ranges, one of which contains p.

_soc_target_violations(soc_targets, soc_mwh: Series, start: datetime, end: datetime, resolution: timedelta, precision: int, most_relevant_only: bool) → list[dict]

Report time slots where the scheduled state of charge misses a soc target.

A target is a two-sided constraint, so a violation is the absolute deviation from the target, in either direction. There is no headroom to report when a target is met, so targets never produce a “resolved” entry.

static _split_schedule_over_output_sensors(flex_model_d: dict, power_series: Series, schedules: dict) → None

Save a power schedule (in MW, consumption positive) to the output sensor(s) (consumption/production) defined on a single flex-model entry, in-place on schedules (mapping output sensor -> power schedule).

Follows the same conventions as _build_consumption_production_schedules():

  • Only consumption sensor defined: the full power schedule is written to that sensor using the scheduler’s native sign convention (consumption positive, production negative). make_schedule applies no further sign change because the sensor already has consumption_is_positive=True.

  • Only production sensor defined: the full power schedule is written to that sensor in the scheduler’s native sign convention (consumption positive, production negative). make_schedule inverts the sign based on the sensor’s consumption_is_positive=False attribute so that production is stored as positive values.

  • Both consumption and production sensors defined: only the non-negative part of the schedule (charging / consuming) is written to the consumption sensor, and only the non-positive part (discharging / producing, still as negative values) is written to the production sensor. make_schedule inverts the sign for the production sensor.

Unit conversion from MW to each sensor’s unit is applied.

_stock_reachability_band(d: int, ems_schedule: list[Series], device_constraints: list[DataFrame], initial_stock: list[float], power_lo: ndarray, power_hi: ndarray) → tuple[ndarray, ndarray]

Per-slot power bounds for device d such that its stock constraints stay reachable.

One-slot deviation analysis: for each slot t we assume the device deviates from its planned power only in slot t, after which it may re-plan freely within its own per-slot power band (power_lo/power_hi). The stock reached at the end of slot t must lie in the backward-propagated “safe set”, from which all remaining stock minima, maxima and targets (of the device’s stock group) remain reachable. Sustained (multi-slot) simultaneous deviations of several devices may still need tighter bounds; deriving those is left for a later revision (e.g. via extra LP solves).

Stock bounds live on the first device of the device’s stock group; deviations of any group member move the shared stock. Other group members are held to their planned schedules.

Storage-efficiency decay is propagated consistently with apply_stock_changes_and_losses (how="linear").

Returns:

(lo, hi) arrays of power bounds in MW (may be ±inf where unconstrained).

compute(skip_validation: bool = False) → Series | list[dict[str, Any]] | None

Schedule a battery or Charge Point based directly on the latest beliefs regarding market prices within the specified time window. For the resulting consumption schedule, consumption is defined as positive values.

Parameters:

skip_validation – If True, skip validation of constraints specified in the data.

Returns:

The computed schedule.