demandresponse
This module computes incentive-based demand response (DR) revenue from
electricity consumption data, modeled along two composable axes –
BaselineMethod for how the counterfactual is measured and
PaymentStructure for how it is paid – with three entry points:
calculate_dr_revenue, build_pyomo_dr_revenue (pyomo only, is netted
into the model’s active objective), and calculate_itemized_dr_revenue (post-optimization,
per-event breakdown).
Baselines are computed per settlement interval (see resolution on
BaselineMethod), so the shape of the counterfactual is preserved
for reporting and comparison against metered data. PaymentStructure adds
settlement mode ("average" settles the window-mean reduction once;
"interval" settles each interval against the payment schedule), and a
payout axis (payment_basis/payout_basis choose "per_event" vs.
"per_hour" pricing, and payout adds a flat, performance-independent
participation payment in $/kW of bid).
Input formats
Events
An event is a dict built by add_event. A collection of events is a
list of these dicts, or a pandas.DataFrame with one row per event
(events_to_dataframe). The keys are available as Python string variables
denoted in all caps since they are global constants.
Key (constant) |
Type |
Description |
|---|---|---|
|
|
Calendar date of the event |
|
|
Hour of day (0-24) the event begins |
|
|
Length of the event in hours |
|
|
Advance notice before the event in hours |
|
|
Candidate baseline days (anything |
|
|
Bid capacity in kW |
|
|
Capacity price in $/kW (or $/kW-hour with |
|
|
Day-of adjustment factor to apply as-is; |
|
|
Called capacity summed over every event hour in the event’s month, used
by |
baseline_days should already exclude any date that is itself another
event’s date; add_event does not check this.
Time zones
Power data may be indexed by a tz-naive or a tz-aware DatetimeIndex.
Event dates, start hours, and baseline days are always read as local
wall-clock times, as utility programs define them: an event at
start_hour=16 covers 4 pm local time on every day, on either side of a
daylight-saving change. A tz-aware event_date, baseline day, or
region_x1s key keeps its local wall-clock date and drops the time zone.
"interval_datetime" in the per-event results is returned in the data’s
time zone.
On a daylight-saving day, a window that covers the skipped spring-forward
hour has no data in that hour and raises ValueError. In a window that
covers the repeated fall-back hour, both occurrences fall in the same
wall-clock interval and are averaged. Windows away from the change (such as
afternoon or evening events) are unaffected.
Payment function
A payment function is a list of region dicts, each with float values
under the keys "x1", "x2", "y1", and "y2" (REGION_X1,
REGION_X2, REGION_Y1, REGION_Y2). Region [x1, x2) covers a
span of delivered ratio (reduction divided by bid capacity) and maps it
linearly onto payment ratios y1 to y2. A region whose x2 is
infinite pays a flat y1. Bounds may be given as the strings
"Infinity"/"-Infinity" (as produced by json.load on a quoted JSON
value); these are coerced to inf/-inf. Entry points that take
payment_function expect a PaymentStructure (or subclass)
instance, built from the regions list, e.g.
PaymentStructure(regions), not the raw list.
Baseline methods
A BaselineMethod computes the counterfactual power the site
would have drawn absent the event, which is subtracted from actual power
to get the reduction a program pays for. BaselineMethod is an abstract
base class: it holds the shared resolution setting and replace, and
each subclass implements calculate_event_baseline. The module has
built-in subclasses for four baseline methods.
SimilarDaysBaseline
The default baseline: the average power across a configurable number of the
most recent eligible “similar days” (candidate days are supplied per-event
via BASELINE_DAYS), with Saturdays/Sundays and configured holidays
excluded by default. Its defaults (10 similar weekdays, 3-hour day-of
adjustment) match PG&E’s Capacity Bidding Program (CBP).
Day selection. _rank_days drops ineligible candidate days and ranks
the rest, most preferred first; select_days keeps the first
n_baseline_days of that ranking. The default ranking prefers the most
recent days. select_days raises ValueError when no eligible day
remains and warns when fewer remain than n_baseline_days.
Holidays. When exclude_holidays=True, a day is excluded if it is a
holiday in the holidays package’s
calendar for holiday_country (an ISO 3166-1 code such as "US") and
optional holiday_subdiv (such as "CA"), or if it appears in
holiday_dates. holiday_country defaults to "US", as in CBP; set it
to None to use holiday_dates alone.
Per-interval averaging. The event window is split into equal-width
settlement intervals of width resolution (a string of the form
"[int][unit]", e.g. "15m" or "1h", parsed by
utils.get_freq_binsize_minutes). For each baseline day, the mean power in
each interval is computed; the baseline for interval k is then the mean of
interval k across all selected days. The result is one value per
interval, not one value per day. When resolution is None, the width is
inferred from the spacing of model_datetime_index (when a model is given)
or historical_power_kW.index, as the smallest gap between timestamps.
Gaps in the data are allowed, but an index whose gaps are not all whole
multiples of the smallest one raises ValueError. Pass it explicitly when that spacing differs
from the settlement interval you want (e.g. hourly meter data settled at
15-minute resolution). The event duration must be an integer multiple of the
interval width. Index t of the returned array (or Var) is a position
within the event window, with 0 at the event start.
Day-of adjustment. The averaged baseline can be scaled by a day-of
adjustment factor: the event day’s mean power over the adjustment window,
divided by the mean power over the same window pooled across all selected
baseline days. The adjustment window is
[event_start - adjustment_offset_hours,
event_start - adjustment_offset_hours + adjustment_duration_hours); for
example, adjustment_offset_hours=4, adjustment_duration_hours=2 uses the
window from 4 hours to 2 hours before the event. The window must end at or
before the event start. The factor is clipped to adjustment_clip so one
anomalous morning can’t swing the baseline too far, and is skipped (factor
1.0, with a warning) when the denominator is near zero. It is always
computed from historical_power_kW, never from the model.
adjustment_offset_hours=None disables the adjustment. To use a factor
calculated elsewhere (e.g. one published by the utility), pass
adjustment_factor to add_event or directly to calculate_event_baseline. It is
applied as-is, without clipping, in place of the calculated factor. If
both are given they must match, or calculate_event_baseline raises ValueError.
Adjustment factor in the model. With adjustment_in_model=True and a
model, the factor is added as a fixed pyomo.environ.Var named
varstr + "_adjustment_factor" and multiplied into the baseline
symbolically. Retune it with model.<varstr>_adjustment_factor.fix(1.15)
and re-solve without rebuilding the model. Do not .unfix() it: the solver
would then pick the revenue-maximizing factor, and baseline * factor
would become bilinear. With the default False, the factor is folded in as
a constant, and the baseline calculate_event_baseline returns is a plain numpy.ndarray
whenever every baseline day is historical.
Baseline days inside the optimization horizon. When calculate_event_baseline is
given a model, model_power_kW, and
model_datetime_index, any baseline day whose event window lies fully
inside the model horizon is computed from the decision variable rather than
from history. A window that only partially overlaps the horizon falls back to
history. If at least one day is computed from the model (or the adjustment
factor is in the model), the baseline is returned as an indexed Var named
varstr with a defining constraint varstr + "_constraint".
No baselining. Passing n_baseline_days=0 turns off baselining
entirely – day selection and the day-of adjustment are both skipped and the
baseline is a flat zero – for programs (such as some interruption-based
ones) whose settlement has no historical counterfactual at all. Because a
zero baseline makes every kW of actual consumption look like a negative
reduction, pair it with either a payout-only payment structure or a payment
schedule whose lowest region extends to -Infinity (as the bundled
CBP-style schedule does). A schedule whose lowest x1 is finite does not
cover a negative delivered ratio: find_region raises a ValueError, and the
Pyomo/cvxpy formulations enforce reduction >= x1 * bid_capacity_kW, so the
optimizer can never consume above baseline during an event.
TopUsageDaysBaseline
A subclass of SimilarDaysBaseline that keeps the same averaging mechanism but
ranks candidate days by highest mean power draw over the event window
instead of by recency, so the baseline reflects the days the site used the
most power rather than the most recent ones. This is the “high-X-of-Y”
style baseline used by some utility programs, and is otherwise configured
identically to SimilarDaysBaseline (same day-of adjustment, weekend/holiday
exclusion, etc.). A day with no data in the event window is ranked last; if
it is still selected, the baseline calculation raises on it.
FixedLevelBaseline
The baseline is a constant, contracted “firm service level” agreed with the
utility ahead of time, rather than anything derived from historical
consumption. Every event uses the same firm_level_kW value, and there is
no day selection, ranking, or day-of adjustment to configure (it subclasses
BaselineMethod directly, not SimilarDaysBaseline).
historical_power_kW and
model_datetime_index are consulted only to infer the interval width when
resolution is None, and no components are added to a model.
UnilateralInterruptionBaseline
Models programs where the utility – not the site – decides when and how
much load is interrupted, holding consumption at or below a fixed level
(0 by default, i.e. a full interruption) for the event’s duration. This
is enforced as a hard constraint, varstr + "_interruption_constraint",
on the entries of model_power_kW inside the event window, rather than
treated as a revenue opportunity the operator chooses to pursue. It
therefore has no ex-post/numpy evaluation path: calculate_event_baseline raises
NotImplementedError without a model. The interruption level is
returned in the baseline’s position to keep a consistent interface, but the
reduction it implies is not the basis for payment, so pair it with a
payout-only payment structure. interruption_level_kW must be
non-negative.
Payment structures
A PaymentStructure turns a reduction (baseline minus actual power)
into a dollar amount. The module has built-in classes for three Payment
methods.
PaymentStructure
The default payment structure: a piecewise-linear capacity payment keyed on
the delivered ratio (reduction as a fraction of the bid capacity), through
the regions of the payment function. The capacity payment is
payment_ratio * capacity_price * bid_capacity_kW. On top of that, an
optional flat, performance-independent payout can be added – or used
alone, by passing regions=None, for programs whose revenue is entirely a
flat participation payment (for example, paired with
UnilateralInterruptionBaseline). payout is in $/kW of
``bid_capacity_kW``, not a flat dollar amount, since one structure is
shared across events with different bid sizes.
Note
The default settlement="interval" matches PG&E’s CBP, which settles
each hour separately, but the default payment_basis="per_event" does
not: CBP pays a monthly capacity payment. To model CBP, also set
payment_basis="monthly_share" (see below).
Settlement. When the reduction carries more than one settlement
interval, settlement controls how the capacity payment is aggregated:
"interval"(default): evaluate the payment function at each interval’s own delivered ratio, then average the resulting payments. This matches PG&E’s CBP, which settles each event hour separately, and is the more rigorous reading when the payment function is nonlinear over the realized range. In pyomo, it multiplies the number of region-selection binaries by the number of intervals."average": average the per-interval reduction into one delivered ratio, then evaluate the payment function once. This keeps the pyomo formulation to one region-selection block per event. The two modes agree exactly when the function is linear over the realized range, and always agree for a single scalar reduction.
Payment basis. payment_basis and payout_basis choose whether the
capacity price and payout are settled once per event ("per_event",
default), scale with the event’s duration ("per_hour", i.e. $/kW-hour),
or split a monthly payment across the month’s called hours
("monthly_share"). "per_hour" requires "duration_hours" on the
event.
"monthly_share" models programs, such as PG&E’s CBP, that pay a monthly
Base Capacity Payment (capacity_price in $/kW-month times
bid_capacity_kW) and allocate it to each called hour in proportion to
that hour’s called capacity. Each event’s capacity payment is
payment_ratio * capacity_price * bid_capacity_kW
* bid_capacity_kW * duration_hours / monthly_called_capacity_kWh
so the same-month events together earn exactly one Base Capacity Payment
at full delivery. bid_capacity_kW is taken as the called capacity in
every hour of the event; split an event whose hours have different called
capacities into separate events. events_to_dataframe (and so every
entry point that takes an events list) fills in a missing
"monthly_called_capacity_kWh" by summing bid_capacity_kW *
duration_hours over the events in the same calendar month. A value given
on any event (via add_event) applies to its whole month, and events in
the same month that give different values raise ValueError. Give it
explicitly when the events passed in don’t cover the whole month – for
example, an optimization horizon that ends mid-month, or a total taken from
a utility settlement statement. Pair it with settlement="interval" and an
hourly resolution to apply the performance adjustment hour by hour, as
CBP does.
Region lookup. find_region takes either a delivered_ratio
(returns the region containing it) or a region_x1 (returns the region
whose x1 matches). Passing neither raises ValueError; passing both
raises unless the delivered ratio falls in the region identified by
region_x1.
CapacityEnergyPayment
A two-part payment: the same piecewise capacity payment as
PaymentStructure, plus a flat $/kWh payment on the energy actually
curtailed. This models programs that pay separately for having capacity
available (the capacity term) and for the energy actually reduced during
the event (the energy term). The energy term is
energy_price * mean(reduction_kW) * duration_hours, which equals the sum
of each interval’s own energy since intervals are equal-width. It is
independent of settlement.
MarketIndexedPayment
The same piecewise capacity payment as PaymentStructure, except the
capacity price is resolved at evaluation/build time from a caller-supplied
price_lookup(event) callable rather than a fixed value on the event.
This models programs whose price tracks a wholesale or day-ahead market
index rather than a flat contracted rate. The price is resolved once, when
the expression is built, so a model built this way is tied to the prices in
force at build time.
Optimization formulations
PaymentStructure.build_expression dispatches on the type of
reduction_kW.
Realized values (numpy.ndarray or a Python number): the region is
already determined, so this calls evaluate.
cvxpy (cvxpy.Expression/cvxpy.Variable): requires a known
region_x1 and builds only that region, returning
(revenue_expr, constraints) for the caller to add to their own
cvxpy.Problem. A vector reduction is averaged for "average"
settlement; for "interval" settlement the region bound constraints apply
to every interval. The revenue expression is identical in both modes, since
the payment ratio is affine within one fixed region. To search across
regions with cvxpy, re-build the expression for a new region_x1 when the
solution falls outside the assumed one. calculate_dr_revenue does not
support cvxpy.
pyomo (pyomo.environ.Var/expression, or a list/tuple of per-interval
expressions): builds every region onto model at once using a
disaggregated binary-selection formulation (Balas’ extended form), so the
solver chooses the region when region_x1=None. Passing region_x1
fixes the region binaries instead. Infinite region bounds are replaced by
±1000 times the bid capacity.
Every region component is indexed by settlement interval t and region.
"average" settlement builds a single interval (t = 0) holding the
window-mean reduction; "interval" settlement builds one region-selection
block per interval. A per-interval revenue Expression lets a solved model
be audited per interval. A scalar region_x1 fixes the same region for
every interval; a list of length n_intervals fixes them individually.
Fixing one region for every interval is a tighter feasible set than
"average" settlement (which only constrains the mean) and can make a
previously feasible plan infeasible, so prefer region_x1=None with
"interval" settlement.
If the structure has no regions (payout-only), no region components are created and the revenue is the constant payout.
Pyomo component names
Every pyomo component is named varstr + "_" + suffix, with the suffixes
available as module constants. BASELINE_COMPONENT_SUFFIXES and
PAYMENT_COMPONENT_SUFFIXES collect them. varstr must be unique per
call on a given model, since reusing it raises a pyomo “component already
exists” error. calculate_dr_revenue and build_pyomo_dr_revenue check
for such clashes before adding anything and raise ValueError, so calling
them twice on one model needs a different varstr_prefix. They name each
event f"{varstr_prefix}_{i}" (i is the event’s position in date
order) and its baseline f"{varstr_prefix}_{i}_baseline_kW".
A model is meant to price all its events under one payment structure. The
first structure built into a model is recorded on it, and building revenue
into the same model with a structure of a different class or different
settings raises a UserWarning.
Constant name |
Description |
Value |
Created by |
|---|---|---|---|
|
Baseline defining constraint |
|
|
|
Fixed day-of adjustment factor |
|
|
|
Interruption upper bound |
|
|
|
Binary, 1 iff the region is active |
|
|
|
Exactly one region is active |
|
|
|
Region’s share of the reduction |
|
|
|
Share |
|
|
|
Share |
|
|
|
Reduction equals the sum of shares |
|
|
|
Per-interval revenue |
|
|
|
Revenue |
|
|
|
Defines revenue |
|
|
|
Energy revenue |
|
|
|
Defines energy revenue |
|
|
|
Capacity plus energy revenue |
|
|
|
Defines total revenue |
|
|
Entry points
calculate_dr_revenuedispatches onpower_kW: realizedpandas/numpydata is settled ex-post viacalculate_itemized_dr_revenue, while apyomo.environ.Varhas each event’s baseline and revenue components built ontomodel, returning the total revenue expression.region_x1soptionally fixes each event’s region, keyed by event date (e.g.{"2024-01-08": 0.6}); events missing from it leave the region choice to the solver.build_pyomo_dr_revenuecallscalculate_dr_revenueand nets the total revenue into the model’s single active objective, whatever its name: subtracted from a minimization objective, added to a maximization one. If the model has no active objective, it adds a minimization objective namedobjective(or a unique variant if that name is taken). More than one active objective raisesValueErrorbefore anything is added.calculate_itemized_dr_revenuereturns apandas.DataFramewith one row per event (seecalculate_event_revenuefor the columns). Each event is sliced and re-baselined independently, so results never mix time windows across events.build_event_revenuehandles a single event and expectspower_kWalready sliced to that event’s window, matching the convention incosts.pyof passing in already-relevant consumption slices.
Combining baselines and payment structures
Because baseline method and payment structure are independent axes, real programs are represented by pairing whichever combination matches their rules. A few examples:
A day-ahead capacity bidding program (e.g. PG&E’s CBP) pairs the default
SimilarDaysBaseline(10 similar weekdays, 3-hour day-of adjustment, US holidays excluded,resolution="1h") withPaymentStructure(regions, payment_basis="monthly_share"), whose regions ramp payment up with delivered ratio. The monthly Base Capacity Payment is split across the month’s called hours and each hour is adjusted for its own performance.A firm service level program, where the customer commits to staying at or below a contracted demand level, pairs
FixedLevelBaselinewith aPaymentStructureusingpayment_basis="per_hour"so the payment (or penalty) scales with how long the level was exceeded.An emergency curtailment or interruptible program, where the utility itself cuts load, pairs
UnilateralInterruptionBaselinewith a payout-onlyPaymentStructure(regions=None) that pays a flat $/kW participation payment regardless of the (utility-controlled) reduction.A wholesale-indexed capacity program pairs
TopUsageDaysBaseline(so the baseline reflects the site’s highest-usage days) withMarketIndexedPayment, so the price paid tracks a day-ahead market index instead of a flat rate.A combined capacity-and-energy incentive program pairs the default
SimilarDaysBaselinewithCapacityEnergyPayment, paying both a capacity-based incentive and a$/kWhrate for the energy actually curtailed.
Extending BaselineMethod and PaymentStructure
Both axes are designed to be subclassed, and every public entry point
(calculate_dr_revenue, build_pyomo_dr_revenue,
calculate_itemized_dr_revenue, and friends) takes a BaselineMethod
instance and accepts a PaymentStructure instance in place of a list of
regions, so a custom subclass drops in without further plumbing.
To add a new similar-days variant, subclass SimilarDaysBaseline and
override one of:
_rank_days(candidate_days, historical_power_kW, event)to change which candidate days are eligible and how they’re ranked, while keeping the averaging mechanism (seeTopUsageDaysBaseline, which callssuper()._rank_days(...)to reuse the eligibility rule and only replaces the ranking). Prefer this over overridingselect_days._adjustment_factor(valid_days, historical_power_kW, event)to change how the day-of scaling factor is computed.
For a baseline that isn’t a historical day-average at all, subclass
BaselineMethod directly, call super().__init__(resolution), and
implement calculate_event_baseline(historical_power_kW, event, *,
model=None, model_power_kW=None, model_datetime_index=None, varstr=None,
adjustment_factor=None) (see FixedLevelBaseline and
UnilateralInterruptionBaseline). The implementation must honor
calculate_event_baseline’s calling contract: return a (value, model)
pair, with model left None ex-post (or raise), adding any pyomo
components under varstr when a model is given.
To add a new payment structure, subclass PaymentStructure and override
evaluate and build_expression as a pair – evaluate is used for
ex-post settlement and build_expression is used to build the same
payment into an optimization model, and if the two diverge, an optimized
plan will not reconcile with its ex-post settlement. CapacityEnergyPayment
and MarketIndexedPayment show two ways to keep them in sync: the former
adds an extra term to both methods after delegating the capacity portion to
super(); the latter resolves a field on event (the market price)
before delegating both methods to super() unchanged.
Calculate incentive-based demand response revenue.
See demandresponse for a description of the module.
- class eeco.demandresponse.BaselineMethod(resolution=None)[source]
Abstract base for demand response baseline methods.
Subclasses implement calculate_event_baseline. Use replace to derive a variant with some settings changed.
- Parameters:
resolution (str or None) – Settlement interval width (e.g., “15m”, “1h”). None infers it from the data or model index.
- abstract calculate_event_baseline(historical_power_kW, event, *, model=None, model_power_kW=None, model_datetime_index=None, varstr=None, adjustment_factor=None)[source]
Calculate the per-interval baseline power for a single event.
- Parameters:
historical_power_kW (pandas.Series) – Historical power consumption in kW, indexed by timestamp.
event (dict) – Single event dict. See add_event for the keys.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add baseline components to. None for ex-post use.
model_power_kW (pyomo.environ.Var or None) – Power decision variable over the optimization horizon.
model_datetime_index (pandas.DatetimeIndex or None) – Timestamp of each entry of model_power_kW.
varstr (str or None) – Name prefix for components created on model.
adjustment_factor (float or None) – Day-of adjustment factor to apply as-is, for methods that use one.
- Returns:
(baseline_kW, model).
- Return type:
- replace(**changes)[source]
Return a new instance with some settings changed.
- Parameters:
**changes – Constructor arguments to override. Unspecified settings keep this instance’s values.
- Returns:
New instance of the same class; self is unchanged.
- Return type:
- Raises:
TypeError – If a key is not a constructor argument.
ValueError – If the resulting settings fail constructor validation.
- class eeco.demandresponse.CapacityEnergyPayment(regions, energy_price, **payment_kwargs)[source]
Piecewise-linear capacity payment plus a flat payment per kWh curtailed.
- Parameters:
regions (list of dict or None) – Capacity payment schedule, as for PaymentStructure.
energy_price (float) – Energy payment rate in $/kWh.
**payment_kwargs – Keyword arguments passed to PaymentStructure.
- build_expression(event, reduction_kW, region_x1=None, model=None, varstr='')[source]
Build the capacity and energy revenue expression for an event.
- Parameters:
event (dict) – Single event dict. See add_event for the keys.
reduction_kW (float, numpy.ndarray, cvxpy.Expression, or pyomo.environ.Var) – Load reduction in kW, as a realized value or a decision-variable expression, per interval or as a window mean. A list or tuple of pyomo expressions is also accepted.
region_x1 (float, list of float, or None) – x1 bound of the region to fix. Required for cvxpy.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add components to. Required for pyomo.
varstr (str) – Name prefix for pyomo components created on model.
- Raises:
ValueError – In the cases listed for PaymentStructure.build_expression, or if event has no “duration_hours”.
TypeError – If reduction_kW is not a supported type.
- Returns:
(revenue, model) for numpy or scalar reduction_kW, (total_revenue_var, model) for pyomo, or (revenue_expr, constraints) for cvxpy.
- Return type:
- evaluate(event, reduction_kW)[source]
Calculate realized capacity and energy revenue for a known reduction.
- Parameters:
event (dict) – Single event dict. See add_event for the keys.
reduction_kW (float or numpy.ndarray) – Load reduction in kW, as a window mean or per interval.
- Raises:
ValueError – In the cases listed for PaymentStructure.evaluate, or if event has no “duration_hours”.
- Returns:
Revenue (positive) or penalty (negative) in USD.
- Return type:
- class eeco.demandresponse.FixedLevelBaseline(firm_level_kW, resolution=None)[source]
Baseline fixed at a contracted firm service level.
- Parameters:
firm_level_kW (float) – Contracted firm demand level in kW.
resolution (str or None) – Settlement interval width (e.g., “15m”, “1h”). None infers it from the data or model index.
- Raises:
ValueError – If firm_level_kW is negative.
- calculate_event_baseline(historical_power_kW, event, *, model=None, model_power_kW=None, model_datetime_index=None, varstr=None, adjustment_factor=None)[source]
Return the firm service level as a flat per-interval baseline.
- Parameters:
historical_power_kW (pandas.Series) – Historical power consumption in kW. Only its index is used, to infer the interval width.
event (dict) – Single event dict. See add_event for the keys.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Returned unchanged. No components are added.
model_power_kW (pyomo.environ.Var or None) – Unused.
model_datetime_index (pandas.DatetimeIndex or None) – Used only to infer the interval width.
varstr (str or None) – Unused.
adjustment_factor (float or None) – Unused.
- Returns:
(baseline_kW, model), where baseline_kW is firm_level_kW repeated once per interval.
- Return type:
- class eeco.demandresponse.MarketIndexedPayment(regions, price_lookup, **payment_kwargs)[source]
Piecewise-linear capacity payment priced from a market index.
- Parameters:
regions (list of dict or None) – Payment schedule, as for PaymentStructure.
price_lookup (callable) – Function price_lookup(event) -> float returning the capacity price in $/kW for an event.
**payment_kwargs – Keyword arguments passed to PaymentStructure.
- build_expression(event, reduction_kW, region_x1=None, model=None, varstr='')[source]
Build the revenue expression for an event at the market price.
- Parameters:
event (dict) – Single event dict. See add_event for the keys.
reduction_kW (float, numpy.ndarray, cvxpy.Expression, or pyomo.environ.Var) – Load reduction in kW, as a realized value or a decision-variable expression, per interval or as a window mean. A list or tuple of pyomo expressions is also accepted.
region_x1 (float, list of float, or None) – x1 bound of the region to fix. Required for cvxpy.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add components to. Required for pyomo.
varstr (str) – Name prefix for pyomo components created on model.
- Raises:
ValueError – In the cases listed for PaymentStructure.build_expression.
TypeError – If reduction_kW is not a supported type.
- Returns:
As for PaymentStructure.build_expression.
- Return type:
- evaluate(event, reduction_kW)[source]
Calculate realized revenue at the market price for a known reduction.
- Parameters:
event (dict) – Single event dict. See add_event for the keys.
reduction_kW (float or numpy.ndarray) – Load reduction in kW, as a window mean or per interval.
- Raises:
ValueError – In the cases listed for PaymentStructure.evaluate.
- Returns:
Revenue (positive) or penalty (negative) in USD.
- Return type:
- class eeco.demandresponse.PaymentStructure(regions, settlement='interval', payment_basis='per_event', payout=0.0, payout_basis='per_event')[source]
Piecewise-linear capacity payment with an optional flat payout.
- Parameters:
regions (list of dict or None) – Payment schedule. Each dict has float values under the keys “x1”, “x2” (delivered ratio bounds) and “y1”, “y2” (payment ratios at those bounds). Bounds may be “Infinity”/”-Infinity” strings; a region with an infinite bound pays a flat ratio from its finite end. Regions whose lowest x1 is finite cannot cover a negative delivered ratio, and in optimization they force reduction >= x1 * bid. None or [] means no capacity payment.
settlement (str) – “interval” (default) or “average”.
payment_basis (str) – “per_event” (default), “per_hour”, or “monthly_share”. With “monthly_share”, the capacity price is $/kW-month and each event is paid its share bid_capacity_kW * duration_hours / monthly_called_capacity_kWh of the monthly payment.
payout (float) – Flat participation payment in $/kW of bid capacity.
payout_basis (str) – “per_event” (default), “per_hour”, or “monthly_share”.
- Raises:
ValueError – If settlement, payment_basis, or payout_basis is not a supported value.
- build_expression(event, reduction_kW, region_x1=None, model=None, varstr='')[source]
Build the revenue expression for an event.
- Parameters:
event (dict) – Single event dict. See add_event for the keys.
reduction_kW (float, numpy.ndarray, cvxpy.Expression, or pyomo.environ.Var) – Load reduction in kW, as a realized value or a decision-variable expression, per interval or as a window mean. A list or tuple of pyomo expressions is also accepted.
region_x1 (float, list of float, or None) – x1 bound of the region to fix. Required for cvxpy. Optional for pyomo, where None lets the solver choose.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add components to. Required for pyomo.
varstr (str) – Name prefix for pyomo components created on model.
- Raises:
ValueError – If reduction_kW is cvxpy and region_x1 matches no region, if reduction_kW is pyomo and model is None or a given region_x1 matches no region.
TypeError – If reduction_kW is not a supported type.
- Warns:
UserWarning – If model already holds revenue built from a different payment structure.
- Returns:
(revenue, model) for numpy or scalar reduction_kW, (revenue_var, model) for pyomo, or (revenue_expr, constraints) for cvxpy.
- Return type:
- evaluate(event, reduction_kW)[source]
Calculate realized revenue for a known reduction.
- Parameters:
event (dict) – Single event dict. See add_event for the keys.
reduction_kW (float or numpy.ndarray) – Load reduction in kW, as a window mean or per interval.
- Raises:
ValueError – If event[“bid_capacity_kW”] is not positive, if no region contains a resulting delivered ratio, or if a “per_hour” basis is used and event has no “duration_hours”.
- Returns:
Revenue (positive) or penalty (negative) in USD.
- Return type:
- find_region(delivered_ratio=None, region_x1=None)[source]
Look up a payment region by delivered ratio or by its x1 bound.
- Parameters:
delivered_ratio (float or None) – Delivered ratio contained in the region.
region_x1 (float or None) – x1 bound of the region.
- Raises:
ValueError – If neither argument is given, if both are given and delivered_ratio is outside the region identified by region_x1, if no region matches, or if there are no regions.
- Returns:
The matching region.
- Return type:
- class eeco.demandresponse.SimilarDaysBaseline(n_baseline_days=10, adjustment_offset_hours=4, adjustment_duration_hours=3, adjustment_clip=(0.8, 1.2), exclude_weekends=True, exclude_holidays=True, holiday_country='US', holiday_subdiv=None, holiday_dates=None, adjustment_in_model=False, resolution=None)[source]
Average-of-similar-days baseline with an optional day-of adjustment.
- Parameters:
n_baseline_days (int) – Number of eligible baseline days to average. 0 disables baselining and yields an all-zero baseline.
adjustment_offset_hours (int or None) – Hours before the event start at which the day-of adjustment window begins. None disables the day-of adjustment.
adjustment_duration_hours (int) – Length of the day-of adjustment window in hours. Ignored when adjustment_offset_hours is None.
adjustment_clip (tuple of float) – (low, high) bounds on the day-of adjustment factor.
exclude_weekends (bool) – If True, drop Saturdays and Sundays from the candidate baseline days.
exclude_holidays (bool) – If True, drop holidays from the candidate baseline days.
holiday_country (str or None) – ISO 3166-1 country code passed to holidays.country_holidays. Defaults to “US”, as in PG&E’s CBP. None uses only holiday_dates.
holiday_subdiv (str or None) – Subdivision code (e.g., “CA”) passed to holidays.country_holidays.
holiday_dates (list or None) – Additional dates to treat as holidays.
adjustment_in_model (bool) – If True and a model is given to calculate_event_baseline, add the day-of adjustment factor to the model as a fixed pyomo.environ.Var.
resolution (str or None) – Settlement interval width (e.g., “15m”, “1h”). None infers it from the data or model index.
- Raises:
ValueError – If n_baseline_days is negative, or if adjustment_offset_hours is not None and adjustment_duration_hours is not positive or exceeds adjustment_offset_hours.
- calculate_event_baseline(historical_power_kW, event, *, model=None, model_power_kW=None, model_datetime_index=None, varstr=None, adjustment_factor=None)[source]
Calculate the per-interval baseline power for a single event.
- Parameters:
historical_power_kW (pandas.Series) – Historical power consumption in kW, indexed by timestamp.
event (dict) – Single event dict. See add_event for the keys.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add baseline components to. None for ex-post use.
model_power_kW (pyomo.environ.Var or None) – Power decision variable over the optimization horizon. Required when model is given.
model_datetime_index (pandas.DatetimeIndex or None) – Timestamp of each entry of model_power_kW. Required when model is given.
varstr (str or None) – Name of the baseline Var created on model. Required when model is given.
adjustment_factor (float or None) – Day-of adjustment factor to apply as-is. None uses event[“adjustment_factor”] if set, otherwise calculates it with _adjustment_factor.
- Raises:
ValueError – If model is given without model_power_kW, model_datetime_index, and varstr, if a selected baseline day has missing data, or if adjustment_factor is not positive or differs from event[“adjustment_factor”].
- Returns:
(baseline_kW, model), where baseline_kW is the per-interval baseline in kW as a numpy.ndarray or an indexed pyomo.environ.Var, and model is None ex-post.
- Return type:
- select_days(candidate_days, historical_power_kW, event)[source]
Select the baseline days to average for an event.
- Parameters:
candidate_days (list of pandas.Timestamp) – Days proposed for this event’s baseline.
historical_power_kW (pandas.Series) – Historical power consumption in kW, indexed by timestamp.
event (dict) – Single event dict. See add_event for the keys.
- Raises:
ValueError – If no eligible days remain after filtering.
- Warns:
UserWarning – If fewer eligible days remain than n_baseline_days.
- Returns:
At most n_baseline_days days, most preferred first.
- Return type:
- class eeco.demandresponse.TopUsageDaysBaseline(n_baseline_days=10, adjustment_offset_hours=4, adjustment_duration_hours=3, adjustment_clip=(0.8, 1.2), exclude_weekends=True, exclude_holidays=True, holiday_country='US', holiday_subdiv=None, holiday_dates=None, adjustment_in_model=False, resolution=None)[source]
Baseline that averages the highest-usage eligible days.
Takes the same parameters as SimilarDaysBaseline.
- class eeco.demandresponse.UnilateralInterruptionBaseline(interruption_level_kW=0.0, resolution=None)[source]
Utility-controlled interruption enforced as an upper bound on power.
- Parameters:
interruption_level_kW (float) – Power level in kW the load is held at or below during an event.
resolution (str or None) – Settlement interval width (e.g., “15m”, “1h”). None infers it from the model index.
- Raises:
ValueError – If interruption_level_kW is negative.
- calculate_event_baseline(historical_power_kW, event, *, model=None, model_power_kW=None, model_datetime_index=None, varstr=None, adjustment_factor=None)[source]
Constrain modeled power to the interruption level during an event.
- Parameters:
historical_power_kW (pandas.Series) – Unused.
event (dict) – Single event dict. See add_event for the keys.
model (pyomo.environ.Model or pyomo.environ.Block) – Model to add the interruption constraint to.
model_power_kW (pyomo.environ.Var) – Power decision variable over the optimization horizon.
model_datetime_index (pandas.DatetimeIndex) – Timestamp of each entry of model_power_kW.
varstr (str) – Name prefix for the constraint created on model.
adjustment_factor (float or None) – Unused.
- Raises:
NotImplementedError – If model is None.
ValueError – If model_power_kW, model_datetime_index, or varstr is missing, or if the event window matches no entries of model_datetime_index.
- Returns:
(baseline_kW, model), where baseline_kW is interruption_level_kW repeated once per interval.
- Return type:
- eeco.demandresponse.add_event(events, event_date, start_hour, duration_hours, notification_hours, baseline_days, bid_capacity_kW, capacity_price, adjustment_factor=None, monthly_called_capacity_kWh=None)[source]
Append a demand response event to an events list.
- Parameters:
events (list of dict or None) – Events list to append to. None starts a new list.
event_date (datetime.date, datetime.datetime, or str) – Calendar date of the event, in local time. A tz-aware value keeps its local wall-clock date and drops the time zone.
start_hour (float) – Hour of day (0-24) the event begins, in local wall-clock time.
duration_hours (float) – Length of the event in hours.
notification_hours (float) – Advance notice before the event in hours.
baseline_days (list) – Candidate baseline days for the event, in local time.
bid_capacity_kW (float) – Bid capacity in kW.
capacity_price (float) – Capacity price in $/kW.
adjustment_factor (float or None) – Day-of adjustment factor to apply as-is. None calculates it from historical data.
monthly_called_capacity_kWh (float or None) – Sum of called capacity in kWh over every event hour in the event’s month, used by the “monthly_share” basis. None sums it over the events passed to events_to_dataframe and the entry points.
- Raises:
ValueError – If duration_hours, bid_capacity_kW, or a given adjustment_factor or monthly_called_capacity_kWh is not positive, notification_hours is negative, or baseline_days is empty.
- Warns:
UserWarning – If capacity_price is zero.
- Returns:
New list with the event appended. Each event dict has the keys
”event_date” : pandas.Timestamp, tz-naive
”start_hour” : float
”duration_hours” : float
”notification_hours” : float
”baseline_days” : list
”bid_capacity_kW” : float
”capacity_price” : float
”adjustment_factor” : float or None
”monthly_called_capacity_kWh” : float or None
- Return type:
- eeco.demandresponse.build_event_revenue(power_kW, event, baseline_kW, payment_function, region_x1=None, model=None, varstr='')[source]
Calculate or build the demand response revenue for a single event.
- Parameters:
power_kW (numpy.ndarray, cvxpy.Expression, cvxpy.Variable, or pyomo.environ.Var) – Power consumption in kW during the event window only.
event (dict) – Single event dict with the keys
“event_date” : pandas.Timestamp
“start_hour” : float
“duration_hours” : float
“notification_hours” : float
“baseline_days” : list
“bid_capacity_kW” : float
“capacity_price” : float
“adjustment_factor” : float or None
“monthly_called_capacity_kWh” : float or None
as returned by add_event.
baseline_kW (float, numpy.ndarray, or pyomo.environ.Var) – Baseline power in kW, as a single value or one value per interval.
payment_function (PaymentStructure) – Payment structure used to price the delivered reduction.
region_x1 (float, list of float, or None) – x1 bound of the region to fix. Required for cvxpy. Optional for pyomo, where None lets the solver choose.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add components to. Required for pyomo.
varstr (str) – Name prefix for pyomo components created on model.
- Raises:
ValueError – If power_kW is cvxpy and region_x1 is None, or if the length of baseline_kW does not match power_kW.
TypeError – If power_kW is not a supported type.
- Returns:
(revenue, model) for numpy power_kW, (revenue_var, model) for pyomo, or (revenue_expr, constraints) for cvxpy.
- Return type:
- eeco.demandresponse.build_pyomo_dr_revenue(power_kW, datetime_index, events, historical_power_kW, baseline_method, model, payment_function, region_x1s=None, varstr_prefix='dr_event')[source]
Build demand response revenue on a pyomo model and net it into the model’s active objective.
Revenue is subtracted from a minimization objective and added to a maximization objective, whatever the objective is named. If the model has no active objective, a minimization objective of -total_revenue is added as model.objective (or a unique variant of that name if taken).
- Parameters:
power_kW (pyomo.environ.Var) – Power decision variable over the optimization horizon.
datetime_index (pandas.DatetimeIndex) – Timestamp of each entry of power_kW.
events (list of dict or pandas.DataFrame) – Events from add_event.
historical_power_kW (pandas.Series) – Historical power consumption in kW, indexed by timestamp.
baseline_method (BaselineMethod) – Baseline method, e.g. SimilarDaysBaseline().
model (pyomo.environ.Model or pyomo.environ.Block) – Model to add components to.
payment_function (PaymentStructure) – Payment structure used to price the delivered reduction.
region_x1s (dict or None) – x1 bound of the region to fix for each event, keyed by event date (e.g., {“2024-01-08”: 0.6}). Events not in the dict let the solver choose.
varstr_prefix (str) – Name prefix for pyomo components created on model.
- Raises:
ValueError – If an event window matches no entries of datetime_index, if model already has a component this call would create (e.g., from an earlier call with the same varstr_prefix), or if model has more than one active objective.
- Returns:
(total_revenue, model), where total_revenue is a pyomo expression.
- Return type:
- eeco.demandresponse.calculate_dr_revenue(power_kW, events, baseline_method, payment_function, historical_power_kW=None, datetime_index=None, model=None, region_x1s=None, varstr_prefix='dr_event')[source]
Calculate or build demand response revenue across all events.
- Parameters:
power_kW (pandas.Series, numpy.ndarray, or pyomo.environ.Var) – Power consumption in kW, as realized data or a decision variable.
events (list of dict or pandas.DataFrame) – Events from add_event.
baseline_method (BaselineMethod) – Baseline method, e.g. SimilarDaysBaseline().
payment_function (PaymentStructure) – Payment structure used to price the delivered reduction.
historical_power_kW (pandas.Series or None) – Historical power consumption in kW, indexed by timestamp. Required for pyomo.
datetime_index (pandas.DatetimeIndex or None) – Timestamp of each entry of power_kW. Required for pyomo and for a numpy.ndarray power_kW.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add components to. Required for pyomo.
region_x1s (dict or None) – x1 bound of the region to fix for each event, keyed by event date (e.g., {“2024-01-08”: 0.6}). Events not in the dict let the solver choose. Only used for pyomo.
varstr_prefix (str) – Name prefix for pyomo components created on model.
- Raises:
NotImplementedError – If power_kW is a cvxpy type.
ValueError – For pyomo, if datetime_index, historical_power_kW, or model is missing, or if an event window matches no entries of datetime_index.
TypeError – If power_kW is not a supported type.
- Returns:
(total_revenue, model), where total_revenue is a float in USD for realized data or a pyomo expression for a decision variable.
- Return type:
- eeco.demandresponse.calculate_event_revenue(historical_power_kW, event, baseline_method, payment_function)[source]
Calculate realized demand response revenue for a single event.
- Parameters:
historical_power_kW (pandas.Series) – Power consumption in kW, indexed by timestamp, covering the event and its baseline days.
event (dict) – Single event dict with the keys “event_date” (pandas.Timestamp), “start_hour” (float), “duration_hours” (float), “notification_hours” (float), “baseline_days” (list), “bid_capacity_kW” (float), “capacity_price” (float), “adjustment_factor” (float or None), and “monthly_called_capacity_kWh” (float or None), as returned by add_event.
baseline_method (BaselineMethod) – Baseline method, e.g. SimilarDaysBaseline().
payment_function (PaymentStructure) – Payment structure used to price the delivered reduction.
- Raises:
ValueError – If any settlement interval of the event window has no data in historical_power_kW.
- Returns:
Event results with the keys
”event_date” : pandas.Timestamp
”baseline_kW” : float, event-window mean
”actual_kW” : float, event-window mean
”reduction_kW” : float, event-window mean
”delivered_ratio” : float
”revenue” : float, in USD
”baseline_profile_kW” : numpy.ndarray, per interval
”actual_profile_kW” : numpy.ndarray, per interval
”reduction_profile_kW” : numpy.ndarray, per interval
”interval_datetime” : pandas.DatetimeIndex, in the time zone of historical_power_kW.index
- Return type:
- eeco.demandresponse.calculate_itemized_dr_revenue(power_kW, events, baseline_method, payment_function, datetime_index=None)[source]
Calculate realized demand response revenue for each event.
- Parameters:
power_kW (pandas.Series or numpy.ndarray) – Power consumption in kW.
events (list of dict or pandas.DataFrame) – Events from add_event.
baseline_method (BaselineMethod) – Baseline method, e.g. SimilarDaysBaseline().
payment_function (PaymentStructure) – Payment structure used to price the delivered reduction.
datetime_index (pandas.DatetimeIndex or None) – Timestamp of each entry of power_kW. Required when power_kW is a numpy.ndarray.
- Raises:
ValueError – If datetime_index is missing or mismatched for a numpy.ndarray power_kW, or if an event window has no data.
- Returns:
(per_event_df, total_revenue), where per_event_df has one row per event with the columns returned by calculate_event_revenue and total_revenue is in USD.
- Return type:
- eeco.demandresponse.events_to_dataframe(events)[source]
Convert an events list into a DataFrame sorted by event date.
- Parameters:
events (list of dict or pandas.DataFrame) – Events from add_event.
- Raises:
ValueError – If two events in the same month give different “monthly_called_capacity_kWh” values.
- Returns:
One row per event, sorted by tz-naive local “event_date”, with missing “monthly_called_capacity_kWh” values filled in by _fill_monthly_called_capacity.
- Return type: