opensced 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- opensced/__init__.py +32 -0
- opensced/core/__init__.py +0 -0
- opensced/core/features/__init__.py +7 -0
- opensced/core/features/balance.py +74 -0
- opensced/core/features/mitigation.py +102 -0
- opensced/core/features/network.py +69 -0
- opensced/core/features/reserves.py +169 -0
- opensced/core/features/storage.py +110 -0
- opensced/core/market.py +97 -0
- opensced/core/model.py +181 -0
- opensced/core/program.py +107 -0
- opensced/core/result.py +159 -0
- opensced/core/rules.py +343 -0
- opensced/core/score.py +75 -0
- opensced/core/sequence.py +105 -0
- opensced/core/tables.py +296 -0
- opensced/examples.py +59 -0
- opensced/markets/__init__.py +2 -0
- opensced/markets/ercot/__init__.py +8 -0
- opensced/markets/ercot/adapter.py +911 -0
- opensced/markets/ercot/helpers.py +277 -0
- opensced/markets/ercot/pricing.py +284 -0
- opensced/markets/ercot/rulebooks.py +164 -0
- opensced-0.1.0.dist-info/METADATA +276 -0
- opensced-0.1.0.dist-info/RECORD +27 -0
- opensced-0.1.0.dist-info/WHEEL +4 -0
- opensced-0.1.0.dist-info/licenses/LICENSE +202 -0
opensced/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""opensced: an open market-clearing engine for power markets.
|
|
2
|
+
|
|
3
|
+
Offers, limits, reserve demand and network constraints in; the system price, the price at every node, dispatch and
|
|
4
|
+
reserve awards out.
|
|
5
|
+
|
|
6
|
+
import opensced
|
|
7
|
+
|
|
8
|
+
case = opensced.examples.three_bus() # a small made-up grid, no data needed
|
|
9
|
+
result = opensced.clear(case)
|
|
10
|
+
print(result)
|
|
11
|
+
result.node_prices()
|
|
12
|
+
|
|
13
|
+
ercot = opensced.market('ercot') # a real market: its rulebooks and file adapter
|
|
14
|
+
day = ercot.read_day('my_data/2026-08-12')
|
|
15
|
+
result = ercot.clear(day.inputs(day.times[0]))
|
|
16
|
+
|
|
17
|
+
print(opensced.schema()) # the input tables, column by column
|
|
18
|
+
"""
|
|
19
|
+
from opensced import examples
|
|
20
|
+
from opensced.core.features.network import resource_shift_factors, unmapped
|
|
21
|
+
from opensced.core.market import list_markets, market
|
|
22
|
+
from opensced.core.model import clear
|
|
23
|
+
from opensced.core.result import DayResult, Result
|
|
24
|
+
from opensced.core.rules import Limit, Product, Rulebooks, Rules
|
|
25
|
+
from opensced.core.score import Score, score
|
|
26
|
+
from opensced.core.sequence import carry_forward, clear_sequence
|
|
27
|
+
from opensced.core.tables import SCHEMA_VERSION, Inputs, schema, validate
|
|
28
|
+
from opensced import markets as _markets # noqa: F401 (registers the built-in markets)
|
|
29
|
+
|
|
30
|
+
__version__ = '0.1.0'
|
|
31
|
+
__all__ = ['clear', 'clear_sequence', 'carry_forward', 'market', 'list_markets', 'Inputs', 'Rules', 'Product', 'Limit', 'Rulebooks', 'Result', 'DayResult', 'score', 'Score',
|
|
32
|
+
'schema', 'validate', 'unmapped', 'resource_shift_factors', 'examples', 'SCHEMA_VERSION', '__version__']
|
|
File without changes
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""The parts of a clearing. Each module adds its variables and rows to the program; core/model.py puts them together.
|
|
2
|
+
|
|
3
|
+
balance energy offer blocks and the power balance (always on)
|
|
4
|
+
reserves reserve awards, reserve offers and the reserve demand curves
|
|
5
|
+
storage battery state of charge under energy and reserve awards
|
|
6
|
+
network transmission constraints and node prices
|
|
7
|
+
"""
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Energy: each dispatchable resource's offer curve cut into blocks, and the power balance.
|
|
2
|
+
|
|
3
|
+
A resource may move between lo = max(ramp_low, low) and hi = min(ramp_high, high), or between ramp_low and ramp_high
|
|
4
|
+
alone under rules.dispatch_limits = 'ramp'. Its curve is cut at its own points
|
|
5
|
+
and into steps of at most rules.block_mw, each priced at the curve's value at the step's midpoint (the curve is linear
|
|
6
|
+
in price between points and flat beyond the ends). A resource that is not dispatchable is held at its output.
|
|
7
|
+
|
|
8
|
+
rules.offer_curves = 'exact' does without steps: each stretch of a curve between two of its points is one variable
|
|
9
|
+
whose cost is the area under the sloped line, price_at_start x + 1/2 slope x^2. The program is then quadratic and
|
|
10
|
+
dispatch lands exactly where each line meets the price. This is the same answer the refined steps converge to.
|
|
11
|
+
|
|
12
|
+
An offer curve is a sloped line between its points, so the cost of a resource is quadratic and its dispatch lands
|
|
13
|
+
where the line meets the price. Steps only approximate that: a 5 MW step on a steep stretch misprices the marginal MW
|
|
14
|
+
by its slope times up to 2.5 MW. rules.block_refine solves again with the curve cut finer around where each resource
|
|
15
|
+
landed (`focus`), each pass ten times finer than the last, until the steps are small enough not to matter.
|
|
16
|
+
|
|
17
|
+
balance sum of dispatch + shortfall - surplus = demand (its dual is the system lambda)
|
|
18
|
+
"""
|
|
19
|
+
import numpy as np
|
|
20
|
+
import pandas as pd
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def blocks(S, energy_offers, rules, focus=None):
|
|
24
|
+
"""-> DataFrame res (resource index), lo, hi, price: the energy blocks of every resource that can move.
|
|
25
|
+
focus {resource index: [(center MW, half width MW, step MW), ...]}: extra cuts around a dispatch, on sloped stretches."""
|
|
26
|
+
lo, hi = S['lo'], S['hi']
|
|
27
|
+
block_mw, tol = rules.block_mw, rules.tolerance_mw
|
|
28
|
+
below = rules.offer_floor if rules.curve_extension == 'floor' else None # price below a curve's lowest point
|
|
29
|
+
curves = {}
|
|
30
|
+
if energy_offers is not None and len(energy_offers):
|
|
31
|
+
at = S['at']
|
|
32
|
+
idx = energy_offers['resource'].map(at)
|
|
33
|
+
ok = idx.notna().to_numpy()
|
|
34
|
+
e = pd.DataFrame({'i': idx[ok].astype(int).to_numpy(), 'mw': pd.to_numeric(energy_offers['mw'])[ok].to_numpy(float),
|
|
35
|
+
'price': pd.to_numeric(energy_offers['price'])[ok].to_numpy(float)})
|
|
36
|
+
e = e[np.isfinite(e.mw) & np.isfinite(e.price)]
|
|
37
|
+
curves = {i: (g.mw.to_numpy(), g.price.to_numpy()) for i, g in e.groupby('i', sort=False)}
|
|
38
|
+
rows, exact = [], rules.offer_curves == 'exact'
|
|
39
|
+
for i in np.where(S['disp'] & (hi - lo > tol))[0]:
|
|
40
|
+
m, p = curves.get(i, (np.array([lo[i], hi[i]]), np.full(2, rules.no_offer_price)))
|
|
41
|
+
o = np.argsort(m, kind='stable')
|
|
42
|
+
m, p = m[o], p[o]
|
|
43
|
+
extra = []
|
|
44
|
+
for c, half, step in (focus or {}).get(i, ()):
|
|
45
|
+
a, b = max(c - half, lo[i]), min(c + half, hi[i])
|
|
46
|
+
if b - a > tol and abs(np.interp(b, m, p, left=below) - np.interp(a, m, p, left=below)) > 1e-9: # flat: nothing to gain
|
|
47
|
+
extra.append(np.arange(a, b + step / 2, step))
|
|
48
|
+
knots = np.unique(np.clip(np.r_[lo[i], m, hi[i], [0.0] if rules.zero_split else [], *extra], lo[i], hi[i])) # 0: charging | discharging
|
|
49
|
+
for a, b in zip(knots[:-1], knots[1:]):
|
|
50
|
+
if b - a <= tol:
|
|
51
|
+
continue
|
|
52
|
+
if exact: # one variable per stretch of the curve: the price
|
|
53
|
+
pa, pb = (float(np.interp(a + 1e-9, m, p, left=below)), float(np.interp(b - 1e-9, m, p, left=below))) # runs
|
|
54
|
+
slope = (pb - pa) / (b - a) # from pa to pb, so its cost is pa x + 1/2 slope x^2
|
|
55
|
+
rows.append((i, a, b, pa, slope) if slope > 0 else (i, a, b, (pa + pb) / 2, 0.0)) # a falling stretch: its mean
|
|
56
|
+
continue
|
|
57
|
+
e = np.linspace(a, b, max(2, int(np.ceil((b - a) / block_mw)) + 1))
|
|
58
|
+
for u, v in zip(e[:-1], e[1:]):
|
|
59
|
+
rows.append((i, u, v, float(np.interp((u + v) / 2, m, p, left=below)), 0.0))
|
|
60
|
+
return pd.DataFrame(rows, columns=['res', 'lo', 'hi', 'price', 'slope'])
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def variables(P, S, rules):
|
|
64
|
+
B = S['B']
|
|
65
|
+
P.add('energy', B.price.to_numpy(), (B.hi - B.lo).to_numpy(), B.slope.to_numpy())
|
|
66
|
+
P.add('slack', [rules.shortage, -rules.surplus_price], [np.inf, np.inf]) # shortfall, surplus
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def equation(P, S, demand):
|
|
70
|
+
eq = np.zeros(P.n)
|
|
71
|
+
eq[:len(S['B'])] = 1.0
|
|
72
|
+
st = P.start('slack')
|
|
73
|
+
eq[st], eq[st + 1] = 1.0, -1.0
|
|
74
|
+
return eq, demand - S['lo'].sum()
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Offer mitigation: the two-step clearing some markets run to stop a resource from setting a high price where it
|
|
2
|
+
faces no competition.
|
|
3
|
+
|
|
4
|
+
step 1 clear with the competitive constraints only. Each resource's price in this run is its reference price.
|
|
5
|
+
step 2 clear with every constraint, after adjusting the energy offer curves:
|
|
6
|
+
floor every curve's prices are raised to the lesser of the resource's reference price and the
|
|
7
|
+
mitigated offer floor for its category (rules.mitigated_offer_floors)
|
|
8
|
+
cap for a resource marked `mitigated`, prices are lowered to the greater of
|
|
9
|
+
reference price + rules.mitigation_adder_share x its mitigated offer cap at its low limit
|
|
10
|
+
its mitigated offer cap at that output (inputs.mitigated_offer_caps)
|
|
11
|
+
With no mitigated offer cap given for it, the cap is the reference price.
|
|
12
|
+
Loads are not mitigated.
|
|
13
|
+
|
|
14
|
+
Which constraints are competitive (constraints.competitive) and which resources are mitigated in the interval
|
|
15
|
+
(resources.mitigated) are inputs: the market's competitiveness test is not run here.
|
|
16
|
+
"""
|
|
17
|
+
import numpy as np
|
|
18
|
+
import pandas as pd
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def competitive_only(inputs):
|
|
22
|
+
"""the inputs with the non-competitive constraints left out: what step 1 sees."""
|
|
23
|
+
c = inputs.constraints
|
|
24
|
+
if c is None or 'competitive' not in c or c['competitive'].fillna(True).all():
|
|
25
|
+
return inputs
|
|
26
|
+
keep = c[c['competitive'].fillna(True).astype(bool)].reset_index(drop=True)
|
|
27
|
+
return inputs.copy(constraints=keep if len(keep) else None)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def clip_curve(mw, price, floor=-np.inf, cap=None):
|
|
31
|
+
"""Hold an offer curve between a floor and a cap, cutting it exactly where it crosses either.
|
|
32
|
+
|
|
33
|
+
mw, price the curve's points (linear in price between them)
|
|
34
|
+
floor $/MWh
|
|
35
|
+
cap None, one number, or (mw points, prices) for a cap that varies with output
|
|
36
|
+
-> (mw, price) with a point added at every crossing, so the result is the true clipped curve and not just the
|
|
37
|
+
original points pulled to the bounds."""
|
|
38
|
+
o = np.argsort(mw, kind='stable')
|
|
39
|
+
m, p = np.asarray(mw, float)[o], np.asarray(price, float)[o]
|
|
40
|
+
if cap is None:
|
|
41
|
+
hi = lambda x: np.full(np.shape(x), np.inf)
|
|
42
|
+
elif np.isscalar(cap):
|
|
43
|
+
hi = lambda x: np.full(np.shape(x), float(cap))
|
|
44
|
+
else:
|
|
45
|
+
cm, cp = np.asarray(cap[0], float), np.asarray(cap[1], float)
|
|
46
|
+
inside = cm[(cm > m[0]) & (cm < m[-1])] # the cap's own corners become curve points
|
|
47
|
+
if len(inside):
|
|
48
|
+
p = np.r_[p, np.interp(inside, m, p)]
|
|
49
|
+
m = np.r_[m, inside]
|
|
50
|
+
o = np.argsort(m, kind='stable')
|
|
51
|
+
m, p = m[o], p[o]
|
|
52
|
+
hi = lambda x: np.interp(x, cm, cp)
|
|
53
|
+
xs, ps = [m[0]], [p[0]]
|
|
54
|
+
for k in range(len(m) - 1):
|
|
55
|
+
a, b, pa, pb = m[k], m[k + 1], p[k], p[k + 1]
|
|
56
|
+
if b > a:
|
|
57
|
+
cuts = []
|
|
58
|
+
if np.isfinite(floor) and (pa - floor) * (pb - floor) < 0:
|
|
59
|
+
cuts.append(a + (floor - pa) / (pb - pa) * (b - a))
|
|
60
|
+
da, db = pa - hi(a), pb - hi(b)
|
|
61
|
+
if np.isfinite(da) and np.isfinite(db) and da * db < 0:
|
|
62
|
+
cuts.append(a + da / (da - db) * (b - a))
|
|
63
|
+
for x in sorted(cuts):
|
|
64
|
+
xs.append(x); ps.append(pa + (pb - pa) * (x - a) / (b - a))
|
|
65
|
+
xs.append(b); ps.append(pb)
|
|
66
|
+
xs, ps = np.array(xs), np.array(ps)
|
|
67
|
+
return xs, np.maximum(np.minimum(ps, hi(xs)), floor)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def mitigate(inputs, reference_prices, rules):
|
|
71
|
+
"""-> the energy_offers table for step 2. reference_prices: Series resource -> $/MWh from step 1."""
|
|
72
|
+
e = inputs.energy_offers
|
|
73
|
+
if e is None or not len(e):
|
|
74
|
+
return e
|
|
75
|
+
r = inputs.resources.set_index('name')
|
|
76
|
+
kind = (r['kind'] if 'kind' in r else pd.Series('generator', index=r.index)).to_dict()
|
|
77
|
+
cat = (r['category'] if 'category' in r else pd.Series('other', index=r.index)).fillna('other').to_dict()
|
|
78
|
+
flagged = set(r.index[r['mitigated'].fillna(False).astype(bool)]) if 'mitigated' in r else set()
|
|
79
|
+
low = r['low'].to_dict()
|
|
80
|
+
floors = rules.mitigated_offer_floors
|
|
81
|
+
other = floors.get('other', -np.inf)
|
|
82
|
+
M = inputs.mitigated_offer_caps
|
|
83
|
+
caps = {} if M is None else {n: (g['mw'].to_numpy(float), g['price'].to_numpy(float)) for n, g in M.sort_values('mw').groupby('resource')}
|
|
84
|
+
ref = reference_prices.to_dict()
|
|
85
|
+
out = []
|
|
86
|
+
for n, g in e.groupby('resource', sort=False):
|
|
87
|
+
mw, price = pd.to_numeric(g['mw']).to_numpy(float), pd.to_numeric(g['price']).to_numpy(float)
|
|
88
|
+
rp = ref.get(n, np.nan)
|
|
89
|
+
if kind.get(n) == 'load' or not np.isfinite(rp) or len(mw) < 1: # loads are not mitigated
|
|
90
|
+
out.append(pd.DataFrame({'resource': n, 'mw': mw, 'price': price}))
|
|
91
|
+
continue
|
|
92
|
+
floor = min(rp, floors.get(cat.get(n, 'other'), other))
|
|
93
|
+
cap = None
|
|
94
|
+
if n in flagged:
|
|
95
|
+
if n in caps:
|
|
96
|
+
cm, cp = caps[n]
|
|
97
|
+
cap = (cm, np.maximum(rp + rules.mitigation_adder_share * float(np.interp(low[n], cm, cp)), cp))
|
|
98
|
+
else:
|
|
99
|
+
cap = rp
|
|
100
|
+
m2, p2 = clip_curve(mw, price, floor, cap)
|
|
101
|
+
out.append(pd.DataFrame({'resource': n, 'mw': m2, 'price': p2}))
|
|
102
|
+
return pd.concat(out, ignore_index=True)
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Transmission constraints.
|
|
2
|
+
|
|
3
|
+
flow + sum over resources of shift factor x (MW - output) <= limit + violation (its dual is the shadow price)
|
|
4
|
+
|
|
5
|
+
`flow` is the flow on the element with every resource at its `output`. A violation costs the constraint's
|
|
6
|
+
max_shadow_price per MW, so a constraint nothing can relieve prices at that cap instead of making the program
|
|
7
|
+
infeasible. A node's price is lambda - sum(shift factor x shadow price).
|
|
8
|
+
"""
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def resource_shift_factors(shift_factors, resource_nodes):
|
|
14
|
+
"""Node shift factors (constraint x node) and a resource -> node map -> shift factors per resource (constraint x
|
|
15
|
+
resource). resource_nodes: Series or dict resource -> node, or DataFrame resource, node[, share]. A resource split
|
|
16
|
+
over several nodes takes the share-weighted mean. A resource on a node with no column gets 0."""
|
|
17
|
+
if isinstance(resource_nodes, pd.DataFrame):
|
|
18
|
+
m = resource_nodes.copy()
|
|
19
|
+
m['share'] = pd.to_numeric(m['share']) if 'share' in m else 1.0
|
|
20
|
+
else:
|
|
21
|
+
s = pd.Series(resource_nodes)
|
|
22
|
+
m = pd.DataFrame({'resource': s.index, 'node': s.to_numpy(), 'share': 1.0})
|
|
23
|
+
m['node'] = m['node'].astype(str)
|
|
24
|
+
cols = pd.Index(shift_factors.columns.astype(str))
|
|
25
|
+
m = m[m['node'].isin(cols)]
|
|
26
|
+
S = shift_factors.to_numpy(float)
|
|
27
|
+
pos = cols.get_indexer(m['node'])
|
|
28
|
+
W = pd.DataFrame(S[:, pos] * m['share'].to_numpy(float), index=shift_factors.index, columns=m['resource'].to_numpy())
|
|
29
|
+
tot = m.groupby('resource', sort=False)['share'].sum()
|
|
30
|
+
out = W.T.groupby(level=0, sort=False).sum().T
|
|
31
|
+
return out / tot.reindex(out.columns).to_numpy()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def unmapped(inputs):
|
|
35
|
+
"""Resources that will not affect any constraint: not in resource_nodes, or on a node with no shift factors."""
|
|
36
|
+
names = inputs.resources['name']
|
|
37
|
+
if inputs.shift_factors is None:
|
|
38
|
+
return list(names)
|
|
39
|
+
sf = inputs.shift_factors if inputs.resource_nodes is None else resource_shift_factors(inputs.shift_factors, inputs.resource_nodes)
|
|
40
|
+
return [n for n in names if n not in sf.columns]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def matrix(S, inputs, cutoff=0.0):
|
|
44
|
+
"""-> the constraints table and the shift-factor matrix constraints x resources, or (None, None)."""
|
|
45
|
+
c = inputs.constraints
|
|
46
|
+
if c is None or not len(c):
|
|
47
|
+
return None, None
|
|
48
|
+
sf = inputs.shift_factors if inputs.resource_nodes is None else resource_shift_factors(inputs.shift_factors, inputs.resource_nodes)
|
|
49
|
+
M = sf.reindex(index=c['name'].to_numpy(), columns=S['names']).fillna(0.0).to_numpy(float)
|
|
50
|
+
if cutoff > 0: # too small to count in the dispatch
|
|
51
|
+
M = np.where(np.abs(M) < cutoff, 0.0, M)
|
|
52
|
+
return c.reset_index(drop=True), M
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def variables(P, S):
|
|
56
|
+
c = S['cons']
|
|
57
|
+
P.add('violation', pd.to_numeric(c['max_shadow_price']).to_numpy(float), np.full(len(c), np.inf))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def rows(P, S):
|
|
61
|
+
c, sf = S['cons'], S['sf']
|
|
62
|
+
lim, flow = pd.to_numeric(c['limit']).to_numpy(float), pd.to_numeric(c['flow']).to_numpy(float)
|
|
63
|
+
by_block = sf[:, S['B'].res.to_numpy()]
|
|
64
|
+
at_output, at_floor = sf @ S['output'], sf @ S['lo']
|
|
65
|
+
v = P.start('violation')
|
|
66
|
+
S['net_rows'] = []
|
|
67
|
+
for j in range(len(c)):
|
|
68
|
+
nz = np.where(np.abs(by_block[j]) > 1e-12)[0]
|
|
69
|
+
S['net_rows'].append(P.row(list(nz) + [v + j], list(by_block[j, nz]) + [-1.0], lim[j] - flow[j] + at_output[j] - at_floor[j]))
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Reserves cleared together with energy.
|
|
2
|
+
|
|
3
|
+
variables r[i, s] MW of product s awarded to resource i (up to its reserve limit)
|
|
4
|
+
z[j, s] MW of offer block j used for product s (when reserve offers are given)
|
|
5
|
+
q[s, k] MW bought on segment k of product s's demand curve
|
|
6
|
+
objective + offer price x z - demand curve price x q
|
|
7
|
+
rows ramp p + share x regulation-up <= ramp_high (rules.regulation_share)
|
|
8
|
+
p - share x regulation-down >= ramp_low
|
|
9
|
+
headroom p + all up awards <= high (or the top of the dispatch range, if that is higher)
|
|
10
|
+
p - all down awards >= low (or the bottom of the dispatch range, if lower)
|
|
11
|
+
offers sum over products of z[j] <= block MW (one MW serves one product)
|
|
12
|
+
r[i, s] = sum of z over i's blocks for s
|
|
13
|
+
demand sum of q[d] <= sum of r[., s] over the products s serving demand curve d
|
|
14
|
+
(its dual is the clearing price)
|
|
15
|
+
reserved when a product has reserved_mw of its demand curve, the other products serving that curve
|
|
16
|
+
together get at most the curve's total MW less the reserved MW
|
|
17
|
+
limits rules.limits: the awards of a group of products, from all or some resources, add up to
|
|
18
|
+
at most a number of MW, a share of a requirement, or a requirement less a number of MW
|
|
19
|
+
|
|
20
|
+
Without reserve offers every resource with a limit may carry the product at $0.
|
|
21
|
+
"""
|
|
22
|
+
import numpy as np
|
|
23
|
+
import pandas as pd
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def limits(S, inputs, rules):
|
|
27
|
+
"""-> {product: MW array over resources}, zero where a resource may not carry it; and the offer blocks
|
|
28
|
+
[(resource index, MW, {product: price})] or None."""
|
|
29
|
+
n, at = S['n'], S['at']
|
|
30
|
+
cap = {p: np.zeros(n) for p in rules.product_names}
|
|
31
|
+
L = inputs.reserve_limits
|
|
32
|
+
if L is not None and len(L):
|
|
33
|
+
i = L['resource'].map(at)
|
|
34
|
+
ok = i.notna().to_numpy() & L['product'].isin(cap).to_numpy()
|
|
35
|
+
for p, g in pd.DataFrame({'i': i[ok].astype(int).to_numpy(), 'p': L['product'][ok].to_numpy(),
|
|
36
|
+
'mw': pd.to_numeric(L['mw'])[ok].to_numpy(float)}).groupby('p', sort=False):
|
|
37
|
+
cap[p][g.i.to_numpy()] = np.maximum(np.nan_to_num(g.mw.to_numpy()), 0.0)
|
|
38
|
+
O, OB = inputs.reserve_offers, None
|
|
39
|
+
if O is not None:
|
|
40
|
+
OB = []
|
|
41
|
+
o = O[O['resource'].isin(at) & O['product'].isin(cap)]
|
|
42
|
+
o = o[(pd.to_numeric(o['mw']) > 0) & np.isfinite(pd.to_numeric(o['price']))]
|
|
43
|
+
for (res, _), g in o.groupby(['resource', 'block'], sort=False):
|
|
44
|
+
OB.append((at[res], float(g['mw'].iloc[0]), dict(zip(g['product'], g['price'].astype(float)))))
|
|
45
|
+
for p in cap:
|
|
46
|
+
offered = np.zeros(n, bool)
|
|
47
|
+
offered[[i for i, _, pr in OB if p in pr]] = True
|
|
48
|
+
cap[p] = np.where(offered, cap[p], 0.0)
|
|
49
|
+
return cap, OB
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def segments(curve, pricing='mean'):
|
|
53
|
+
"""One product's demand curve points (mw, price) -> segments (width, price): the mean price over each stretch."""
|
|
54
|
+
c = curve.sort_values('mw')
|
|
55
|
+
q, p = pd.to_numeric(c['mw']).to_numpy(float), pd.to_numeric(c['price']).to_numpy(float)
|
|
56
|
+
if len(q) and q[0] > 0: # the first point holds from 0
|
|
57
|
+
q, p = np.r_[0.0, q], np.r_[p[0], p]
|
|
58
|
+
w, pr = q[1:] - q[:-1], ((p[:-1] + p[1:]) / 2 if pricing == 'mean' else p[:-1])
|
|
59
|
+
return w[w > 0], pr[w > 0]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def award_variables(P, S, rules):
|
|
63
|
+
S['rv'] = {}
|
|
64
|
+
for p in rules.product_names:
|
|
65
|
+
idx = np.where(S['cap'][p] > rules.tolerance_mw)[0]
|
|
66
|
+
S['rv'][p] = idx
|
|
67
|
+
P.add(f'r_{p}', np.full(len(idx), 0.0 if S['OB'] is not None else rules.no_reserve_offer_price), S['cap'][p][idx])
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def offer_variables(P, S, rules):
|
|
71
|
+
S['zv'] = [] # (block, product, resource, price) per z
|
|
72
|
+
if S['OB'] is None:
|
|
73
|
+
return
|
|
74
|
+
rset = {p: set(S['rv'][p]) for p in S['rv']}
|
|
75
|
+
for j, (i, _, pr) in enumerate(S['OB']):
|
|
76
|
+
for p, price in pr.items():
|
|
77
|
+
if i in rset[p]:
|
|
78
|
+
S['zv'].append((j, p, i, max(price, rules.reserve_offer_floor)))
|
|
79
|
+
P.add('z', [z[3] for z in S['zv']], np.full(len(S['zv']), np.inf))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def demand_variables(P, S, inputs, rules):
|
|
83
|
+
"""the demand curves; and each curve's requirement: inputs.reserve_requirements, else the curve's total MW."""
|
|
84
|
+
D = inputs.reserve_demand
|
|
85
|
+
S['need'] = {}
|
|
86
|
+
given = {} if inputs.reserve_requirements is None else dict(zip(inputs.reserve_requirements['product'], pd.to_numeric(inputs.reserve_requirements['mw'])))
|
|
87
|
+
for d in rules.demand_names:
|
|
88
|
+
w, pr = segments(D[D['product'] == d], rules.demand_curve_pricing)
|
|
89
|
+
S['need'][d] = float(given.get(d, w.sum()))
|
|
90
|
+
P.add(f'q_{d}', -pr, w)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def rcol(P, S, p, i):
|
|
94
|
+
"""index of the award variable of resource i for product p, or None."""
|
|
95
|
+
rv = S['rv'][p]
|
|
96
|
+
j = np.searchsorted(rv, i)
|
|
97
|
+
return P.start(f'r_{p}') + j if j < len(rv) and rv[j] == i else None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def resource_rows(P, S, rules):
|
|
101
|
+
up = [p.name for p in rules.products if p.direction == 'up']
|
|
102
|
+
down = [p.name for p in rules.products if p.direction == 'down']
|
|
103
|
+
reg_up = [p.name for p in rules.products if p.direction == 'up' and p.regulation]
|
|
104
|
+
reg_down = [p.name for p in rules.products if p.direction == 'down' and p.regulation]
|
|
105
|
+
share = rules.regulation_share
|
|
106
|
+
have = set().union(*[set(v) for v in S['rv'].values()]) if S['rv'] else set()
|
|
107
|
+
for i in sorted(have):
|
|
108
|
+
bl = list(S['blocks_of'].get(i, ()))
|
|
109
|
+
lo, hdl, ldl, hsl, lsl = S['lo'][i], S['ramp_high'][i], S['ramp_low'][i], S['high'][i], S['low'][i]
|
|
110
|
+
for p in reg_up:
|
|
111
|
+
r = rcol(P, S, p, i)
|
|
112
|
+
if r is not None:
|
|
113
|
+
P.row(bl + [r], [1.0] * len(bl) + [share], hdl - lo)
|
|
114
|
+
for p in reg_down:
|
|
115
|
+
r = rcol(P, S, p, i)
|
|
116
|
+
if r is not None:
|
|
117
|
+
P.row(bl + [r], [-1.0] * len(bl) + [share], lo - ldl)
|
|
118
|
+
ups = [c for c in (rcol(P, S, p, i) for p in up) if c is not None]
|
|
119
|
+
if ups: # a held resource carries reserves only
|
|
120
|
+
P.row(bl + ups, [1.0] * (len(bl) + len(ups)), max(hsl, S['hi'][i]) - lo) # never tighter than the dispatch range
|
|
121
|
+
downs = [c for c in (rcol(P, S, p, i) for p in down) if c is not None]
|
|
122
|
+
if downs:
|
|
123
|
+
P.row(bl + downs, [-1.0] * len(bl) + [1.0] * len(downs), lo - min(lsl, lo))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def offer_rows(P, S):
|
|
127
|
+
if not S['zv']:
|
|
128
|
+
return
|
|
129
|
+
zst = P.start('z')
|
|
130
|
+
by_block, by_award = {}, {}
|
|
131
|
+
for k, (j, p, i, _) in enumerate(S['zv']):
|
|
132
|
+
by_block.setdefault(j, []).append(zst + k)
|
|
133
|
+
by_award.setdefault((i, p), []).append(zst + k)
|
|
134
|
+
for j, zs in by_block.items():
|
|
135
|
+
P.row(zs, [1.0] * len(zs), S['OB'][j][1])
|
|
136
|
+
for (i, p), zs in by_award.items(): # an award is exactly the offer MW used for it:
|
|
137
|
+
r = rcol(P, S, p, i) # with "at most", a block priced below zero (self-
|
|
138
|
+
P.row([r] + zs, [1.0] + [-1.0] * len(zs), 0.0) # provided reserves) could be counted as used, and
|
|
139
|
+
P.row([r] + zs, [-1.0] + [1.0] * len(zs), 0.0) # its price collected, with nothing awarded
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def demand_rows(P, S, inputs, rules):
|
|
143
|
+
S['reserve_rows'] = {}
|
|
144
|
+
for d in rules.demand_names:
|
|
145
|
+
qs, qn = P.var[f'q_{d}']
|
|
146
|
+
cols = [c for p in rules.serving(d) for c in range(P.var[f'r_{p}'][0], sum(P.var[f'r_{p}']))]
|
|
147
|
+
S['reserve_rows'][d] = P.row(list(range(qs, qs + qn)) + cols, [1.0] * qn + [-1.0] * len(cols), 0.0)
|
|
148
|
+
V = inputs.limit_values # this interval's own numbers for named limits
|
|
149
|
+
V = {} if V is None else {r['limit']: r for r in V.to_dict('records')}
|
|
150
|
+
own = lambda name, key, default: default if name not in V or pd.isna(V[name].get(key, np.nan)) else float(V[name][key])
|
|
151
|
+
for p in rules.products: # MW of a demand curve only one product may fill
|
|
152
|
+
kept = own(p.name, 'min_mw', p.reserved_mw)
|
|
153
|
+
if kept > 0:
|
|
154
|
+
cols = [c for o in rules.serving(p.serves) if o != p.name for c in range(P.var[f'r_{o}'][0], sum(P.var[f'r_{o}']))]
|
|
155
|
+
if cols:
|
|
156
|
+
P.row(cols, [1.0] * len(cols), max(S['need'][p.serves] - kept, 0.0))
|
|
157
|
+
for lim in rules.limits: # caps and floors on groups of products
|
|
158
|
+
ok = np.ones(S['n'], bool)
|
|
159
|
+
for col, val in lim.where:
|
|
160
|
+
ok &= (S['table'][col].to_numpy() == val) if col in S['table'] else False
|
|
161
|
+
cols = [P.start(f'r_{p}') + k for p in lim.products if p in S['rv'] for k, i in enumerate(S['rv'][p]) if ok[i]]
|
|
162
|
+
share = lambda x: None if x is None else x * S['need'][lim.of]
|
|
163
|
+
less = None if lim.max_less is None else max(S['need'][lim.of] - lim.max_less, 0.0)
|
|
164
|
+
hi = [v for v in (own(lim.name, 'max_mw', lim.max_mw), share(lim.max_share), less) if v is not None]
|
|
165
|
+
lo = [v for v in (own(lim.name, 'min_mw', lim.min_mw), share(lim.min_share)) if v is not None]
|
|
166
|
+
if cols and hi:
|
|
167
|
+
P.row(cols, [1.0] * len(cols), min(hi))
|
|
168
|
+
if lo:
|
|
169
|
+
P.row(cols, [-1.0] * len(cols), -max(lo))
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Battery state of charge under energy and reserve awards.
|
|
2
|
+
|
|
3
|
+
What a battery is told to do over one interval, plus every reserve it is awarded, must fit in the energy it holds:
|
|
4
|
+
|
|
5
|
+
discharge side p x interval + sum over up products of r x duration <= soc - soc_min
|
|
6
|
+
charge side eff x (charging MW x interval + sum over down products of r x duration)
|
|
7
|
+
- discharging MW x interval <= soc_max - soc
|
|
8
|
+
|
|
9
|
+
p is the battery's output and is signed: discharging uses stored energy, charging adds to it. So a battery that is
|
|
10
|
+
charging can carry a little more upward reserve, by exactly the energy it takes in during the interval, and no more.
|
|
11
|
+
This is rules.storage_signed_energy, the default.
|
|
12
|
+
|
|
13
|
+
eff is the storage table's `efficiency`: of each MWh taken from the grid, the share that ends up stored. It applies to
|
|
14
|
+
what would be taken in (charging, and a downward reserve if deployed), not to discharge. Checked against ERCOT's
|
|
15
|
+
Reg-Down awards on seven days in 2026 (31,450 battery-runs): with each battery's own efficiency and 30 minutes for
|
|
16
|
+
Reg-Down no award breaks the charge-side row and one in five sits exactly on it.
|
|
17
|
+
|
|
18
|
+
Checked against ERCOT's own awards on five days in 2026 (about 260,000 battery-runs with upward awards): none breaks
|
|
19
|
+
the discharge-side row, and about 40% sit exactly on it.
|
|
20
|
+
|
|
21
|
+
Both sides are floored at what the battery's energy dispatch alone can reach, so a battery that cannot move loses
|
|
22
|
+
reserves instead of making the program infeasible.
|
|
23
|
+
|
|
24
|
+
An older reading, rules.storage_charge_offset, lets a charging battery count every MW it could stop charging as
|
|
25
|
+
reserve that needs no stored energy at all (w below: w <= r, sum of w <= charging MW). It is kept as an option, off by
|
|
26
|
+
default: with it, a linear program finds it pays to charge at peak prices only to sell reserve. Under that option
|
|
27
|
+
settle_direction() also stops a battery from using charging and discharging blocks at once.
|
|
28
|
+
"""
|
|
29
|
+
import numpy as np
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def variables(P, S, rules):
|
|
33
|
+
S['wv'] = {}
|
|
34
|
+
esr = np.where(S['esr'])[0] if rules.storage_charge_offset else np.array([], int) # w exists only under the offset option
|
|
35
|
+
for p in rules.products:
|
|
36
|
+
if p.direction == 'up':
|
|
37
|
+
idx = np.intersect1d(S['rv'][p.name], esr)
|
|
38
|
+
S['wv'][p.name] = idx
|
|
39
|
+
P.add(f'w_{p.name}', np.zeros(len(idx)), np.full(len(idx), np.inf))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def rows(P, S, rules):
|
|
43
|
+
from opensced.core.features.reserves import rcol
|
|
44
|
+
B, stp = S['B'], rules.interval_hours
|
|
45
|
+
bhi, blo = B.hi.to_numpy(), B.lo.to_numpy()
|
|
46
|
+
up = [p for p in rules.products if p.direction == 'up']
|
|
47
|
+
down = [p for p in rules.products if p.direction == 'down']
|
|
48
|
+
signed = rules.storage_signed_energy and not rules.storage_charge_offset
|
|
49
|
+
for i in np.where(S['esr'])[0]:
|
|
50
|
+
bl = S['blocks_of'].get(i, np.array([], int))
|
|
51
|
+
neg, pos = bl[bhi[bl] <= 1e-9], bl[blo[bl] >= -1e-9]
|
|
52
|
+
lo = S['lo'][i]
|
|
53
|
+
d0, c0 = max(lo, 0.0), max(-lo, 0.0) # discharge / charging at the resource's floor
|
|
54
|
+
span = float((bhi[bl] - blo[bl]).sum()) if len(bl) else 0.0
|
|
55
|
+
energy = list(bl) if signed else list(pos) # signed: every block moves stored energy
|
|
56
|
+
cols, vals, ws = list(energy), [stp] * len(energy), []
|
|
57
|
+
for p in up:
|
|
58
|
+
r = rcol(P, S, p.name, i)
|
|
59
|
+
if r is None:
|
|
60
|
+
continue
|
|
61
|
+
cols.append(r); vals.append(p.duration_hours)
|
|
62
|
+
if rules.storage_charge_offset:
|
|
63
|
+
w = P.start(f'w_{p.name}') + int(np.searchsorted(S['wv'][p.name], i))
|
|
64
|
+
cols.append(w); vals.append(-p.duration_hours)
|
|
65
|
+
ws.append(w)
|
|
66
|
+
P.row([w, r], [1.0, -1.0], 0.0)
|
|
67
|
+
P.row(cols, vals, max(S['head'][i] - (lo if signed else d0) * stp, 0.0))
|
|
68
|
+
if ws:
|
|
69
|
+
P.row(ws + list(neg), [1.0] * (len(ws) + len(neg)), c0)
|
|
70
|
+
eff = S['eff'][i] if signed else 1.0 # share of charging energy that ends up stored
|
|
71
|
+
charging = bl[bhi[bl] <= 1e-9] # blocks below 0 MW; the rest discharge
|
|
72
|
+
other = bl[bhi[bl] > 1e-9] if signed else np.array([], int)
|
|
73
|
+
cols, vals = list(charging) + list(other), [-eff * stp] * len(charging) + [-stp] * len(other)
|
|
74
|
+
for p in down:
|
|
75
|
+
r = rcol(P, S, p.name, i)
|
|
76
|
+
if r is not None:
|
|
77
|
+
cols.append(r); vals.append(eff * p.duration_hours)
|
|
78
|
+
reach = -(eff * float((bhi[charging] - blo[charging]).sum()) + float((bhi[other] - blo[other]).sum())) * stp
|
|
79
|
+
start = (eff * min(lo, 0.0) + max(lo, 0.0)) if signed else -c0
|
|
80
|
+
P.row(cols, vals, max(S['room'][i] + start * stp, reach))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def settle_direction(P, S, x, rules):
|
|
84
|
+
"""Bounds that stop batteries charging and discharging at once in the solution x. -> (lower, upper) dicts of
|
|
85
|
+
variable index -> bound; both empty when no battery did."""
|
|
86
|
+
B, tol = S['B'], max(rules.tolerance_mw, 1e-4)
|
|
87
|
+
bhi, blo = B.hi.to_numpy(), B.lo.to_numpy()
|
|
88
|
+
width = bhi - blo
|
|
89
|
+
lower, upper = {}, {}
|
|
90
|
+
for i in np.where(S['esr'])[0]:
|
|
91
|
+
bl = S['blocks_of'].get(i, np.array([], int))
|
|
92
|
+
neg, pos = bl[bhi[bl] <= 1e-9], bl[blo[bl] >= -1e-9]
|
|
93
|
+
if not len(neg) or not len(pos):
|
|
94
|
+
continue
|
|
95
|
+
unused_charging = float((width[neg] - x[neg]).sum())
|
|
96
|
+
discharging = float(x[pos].sum())
|
|
97
|
+
if unused_charging <= tol or discharging <= tol:
|
|
98
|
+
continue
|
|
99
|
+
net = S['lo'][i] + float(x[bl].sum())
|
|
100
|
+
if net >= 0: # it is discharging: no charging to give up
|
|
101
|
+
for k in neg:
|
|
102
|
+
lower[int(k)] = float(width[k])
|
|
103
|
+
for p_, idx in S['wv'].items():
|
|
104
|
+
j = int(np.searchsorted(idx, i))
|
|
105
|
+
if j < len(idx) and idx[j] == i:
|
|
106
|
+
upper[P.start(f'w_{p_}') + j] = 0.0
|
|
107
|
+
else: # it is charging: nothing above 0 MW
|
|
108
|
+
for k in pos:
|
|
109
|
+
upper[int(k)] = 0.0
|
|
110
|
+
return lower, upper
|