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.
@@ -0,0 +1,277 @@
1
+ """ERCOT's own calculations, for when you have the underlying numbers instead of ERCOT's published result.
2
+
3
+ A replay reads dispatch limits, proxy curves, proxy reserve offers and constraint caps straight from ERCOT's files. A
4
+ forecast has to build them. Each function here follows the Protocol paragraph named in its docstring and takes its
5
+ numbers from the rulebook, so a rule change is a rulebook change.
6
+
7
+ dispatch_limits ramp_low / ramp_high from output and ramp rates 6.5.7.2
8
+ max_shadow_prices a constraint's cap from its kind and voltage Section 22 Attachment P
9
+ proxy_energy_curves offer curves for resources without a full curve 6.5.7.3(4)
10
+ proxy_reserve_offers the linked reserve offer for unoffered capacity 6.5.7.3(5)
11
+ demand the demand to serve from ERCOT's demand target 6.5.7.3(3)
12
+ generic_offer_caps mitigated offer caps from the gas index price 4.4.9.4.1
13
+ battery_efficiency each battery's charging efficiency, off ERCOT's awards 3.7.1.3(1)(c)
14
+ """
15
+ import numpy as np
16
+ import pandas as pd
17
+
18
+
19
+ def dispatch_limits(resources, rules):
20
+ """Fill ramp_low and ramp_high (ERCOT's LDL and HDL) from where each resource is and how fast it can move.
21
+
22
+ Needs columns output, low, high, ramp_up, ramp_down (MW per minute) and, when present, status and kind.
23
+ generation, storage high limit = min(output + ramp_up x minutes, high); low = max(output - ramp_down x minutes, low)
24
+ SHUTDOWN high limit = output - ramp_down x minutes
25
+ STARTUP low limit = output + ramp_up x minutes
26
+ ONHOLD (storage) both 0; ONTEST (storage): both held at output, inside low..high
27
+ loads the same formulas on their negative output: ramping "down" consumes more
28
+ minutes is rules.dispatch_minutes. -> a copy of the table."""
29
+ r = resources.copy()
30
+ m = rules.dispatch_minutes
31
+ out, low, high = (pd.to_numeric(r[c], errors='coerce').to_numpy(float) for c in ('output', 'low', 'high'))
32
+ up, dn = (pd.to_numeric(r[c], errors='coerce').to_numpy(float) for c in ('ramp_up', 'ramp_down'))
33
+ status = r['status'].astype(str).str.upper().to_numpy() if 'status' in r else np.full(len(r), '')
34
+ hi, lo = np.minimum(out + up * m, high), np.maximum(out - dn * m, low)
35
+ hi = np.where(status == 'SHUTDOWN', out - dn * m, hi)
36
+ lo = np.where(np.isin(status, ('STARTUP', 'STARTUP-NS')), out + up * m, lo)
37
+ hold = np.clip(out, low, high)
38
+ test, held = status == 'ONTEST', status == 'ONHOLD'
39
+ hi, lo = np.where(test, hold, hi), np.where(test, hold, lo)
40
+ hi, lo = np.where(held, 0.0, hi), np.where(held, 0.0, lo)
41
+ r['ramp_high'], r['ramp_low'] = hi, lo
42
+ return r
43
+
44
+
45
+ def max_shadow_prices(constraints, rules):
46
+ """Fill max_shadow_price from each constraint's kind ('base' or 'contingency') and voltage, using
47
+ rules.shadow_price_caps: the base-case cap, or the contingency cap for its voltage (above 200 kV, 100 to 200 kV,
48
+ below 100 kV). A constraint with no voltage, or of another kind, gets rules.default_max_shadow_price.
49
+ The higher caps ERCOT sets for irresolvable and stability-limit constraints are not computed here: give those
50
+ directly. -> a copy of the table."""
51
+ c = constraints.copy()
52
+ caps = rules.shadow_price_caps
53
+ kind = c['kind'].astype(str).str.lower() if 'kind' in c else pd.Series('contingency', index=c.index)
54
+ kv = pd.to_numeric(c['kv'], errors='coerce') if 'kv' in c else pd.Series(np.nan, index=c.index)
55
+ by_kv = np.select([kv > 200, kv >= 100, kv < 100], [caps.get('above_200kv'), caps.get('100_to_200kv'), caps.get('below_100kv')], default=np.nan).astype(float)
56
+ cap = np.where(kind == 'base', caps.get('base', np.nan), np.where(kind == 'contingency', by_kv, np.nan)).astype(float)
57
+ c['max_shadow_price'] = np.where(np.isfinite(cap), cap, rules.default_max_shadow_price)
58
+ return c
59
+
60
+
61
+ def proxy_energy_curves(resources, energy_offers, rules, intermittent=('wind', 'pv')):
62
+ """Give every dispatchable generator a full-range offer curve, as ERCOT does before SCED (6.5.7.3(4)).
63
+
64
+ no curve, on an Output Schedule low at the offer floor; the schedule one step above the floor; 1 MW above the
65
+ schedule just under the offer cap; high at the offer cap (4)(a)
66
+ no curve, wind or solar low at the offer floor; 1 MW below high one step above the floor;
67
+ high at rules.irr_proxy_price (4)(c)(i)
68
+ a curve that stops short extended flat from its top to high; 1 MW below its bottom one step above
69
+ the floor, and low at the floor (4)(b)
70
+ Wind and solar are the resources whose `category` is in `intermittent`. Storage, controllable loads and
71
+ RUC-committed resources have proxies of their own (6.5.7.3(4)(d), (6), (8), (9)) that are not built here.
72
+ -> the energy_offers table with the proxy points added."""
73
+ r = resources
74
+ e = energy_offers if energy_offers is not None else pd.DataFrame(columns=['resource', 'mw', 'price'])
75
+ floor, step, mw1, cap = rules.offer_floor, rules.proxy_price_step, rules.proxy_mw_step, rules.offer_cap
76
+ if cap is None:
77
+ raise ValueError('proxy_energy_curves needs rules.offer_cap')
78
+ span = e.groupby('resource')['mw'].agg(['min', 'max']) if len(e) else pd.DataFrame(columns=['min', 'max'])
79
+ top = e.sort_values('mw').groupby('resource')['price'].last() if len(e) else pd.Series(dtype=float)
80
+ add = []
81
+ for x in r.itertuples(index=False):
82
+ if getattr(x, 'kind', 'generator') != 'generator' or not getattr(x, 'dispatchable', True):
83
+ continue
84
+ lo, hi, n = float(x.low), float(x.high), x.name
85
+ if n not in span.index:
86
+ sched = getattr(x, 'output_schedule', np.nan)
87
+ if getattr(x, 'category', 'other') in intermittent:
88
+ pts = [(lo, floor), (max(hi - mw1, lo), floor + step), (hi, rules.irr_proxy_price)]
89
+ elif pd.notna(sched):
90
+ pts = [(lo, floor), (float(sched), floor + step), (min(float(sched) + mw1, hi), cap - step), (hi, cap)]
91
+ else:
92
+ continue
93
+ else:
94
+ pts = []
95
+ if hi > span.loc[n, 'max']:
96
+ pts.append((hi, float(top[n])))
97
+ if lo < span.loc[n, 'min']:
98
+ pts += [(max(span.loc[n, 'min'] - mw1, lo), floor + step), (lo, floor)]
99
+ add += [{'resource': n, 'mw': mw, 'price': p} for mw, p in pts]
100
+ return pd.concat([e, pd.DataFrame(add)], ignore_index=True) if add else e
101
+
102
+
103
+ def proxy_reserve_offers(resources, reserve_offers, reserve_demand, rules, reserve_requirements=None, qualified=None):
104
+ """Add ERCOT's proxy reserve offer for every resource (6.5.7.3(5)): one block linked across the products it is
105
+ qualified for, sized at its high limit (high - low for storage, maximum consumption for loads).
106
+
107
+ Price per product = the higher of
108
+ the floor the lesser of rules.proxy_reserve_cap and the demand curve's price at
109
+ rules.proxy_reserve_plan_share of the requirement, less rules.proxy_price_step
110
+ its own the resource's highest submitted price for that product, and for the products above it in the
111
+ order Reg-Up/RRS > ECRS > Non-Spin, the highest price of the ones below
112
+ A RUC-committed resource (`ruc_committed`) is offered at the higher of its own highest price and
113
+ rules.ruc_reserve_offer_price over its whole range (6.5.7.3(5)(e)).
114
+ qualified: {resource: products}. Default: the products in reserve_limits are not known here, so every resource is
115
+ taken as qualified for every product; pass it to narrow that. -> the reserve_offers table with a 'proxy' block each."""
116
+ o = reserve_offers if reserve_offers is not None else pd.DataFrame(columns=['resource', 'block', 'mw', 'product', 'price'])
117
+ need = {} if reserve_requirements is None else dict(zip(reserve_requirements['product'], reserve_requirements['mw']))
118
+ floor = {}
119
+ for d, c in reserve_demand.groupby('product'):
120
+ c = c.sort_values('mw')
121
+ plan = float(need.get(d, c['mw'].max()))
122
+ floor[d] = min(rules.proxy_reserve_cap, float(np.interp(rules.proxy_reserve_plan_share * plan, c['mw'], c['price']))) - rules.proxy_price_step
123
+ own = o.groupby(['resource', 'product'])['price'].max() if len(o) else pd.Series(dtype=float)
124
+ names = [p.name for p in rules.products]
125
+ below = {p.name: [q.name for q in rules.products[k + 1:] if q.direction == 'up'] if p.direction == 'up' else [] for k, p in enumerate(rules.products)}
126
+ rows = []
127
+ for x in resources.itertuples(index=False):
128
+ kind = getattr(x, 'kind', 'generator')
129
+ mw = float(x.high - x.low) if kind == 'storage' else float(getattr(x, 'max_consumption', np.nan)) if kind == 'load' else float(x.high)
130
+ if not np.isfinite(mw) or mw <= 0:
131
+ continue
132
+ ruc = bool(getattr(x, 'ruc_committed', False))
133
+ price = {}
134
+ for p in reversed(names): # bottom of the order first, so "below" is ready
135
+ if qualified is not None and p not in qualified.get(x.name, ()):
136
+ continue
137
+ mine = own.get((x.name, p), np.nan)
138
+ base = rules.ruc_reserve_offer_price if ruc else floor.get(rules.product(p).serves, np.nan)
139
+ price[p] = np.nanmax([base, mine] + ([] if ruc else [price[q] for q in below[p] if q in price]))
140
+ rows += [{'resource': x.name, 'block': 'proxy', 'mw': mw, 'product': p, 'price': v} for p, v in price.items() if np.isfinite(v)]
141
+ return pd.concat([o, pd.DataFrame(rows)], ignore_index=True) if rows else o
142
+
143
+
144
+ def demand(gtbd, controllable_load_consumption=0.0):
145
+ """The demand the clearing serves: ERCOT's Generation To Be Dispatched less what controllable loads consume
146
+ (6.5.7.3(3)), because those loads are resources in the clearing. ERCOT does not publish GTBD or its formula."""
147
+ return float(gtbd) - float(controllable_load_consumption)
148
+
149
+
150
+ def generic_offer_caps(resources, fuel_index_price, rules, after_2004=(), verifiable=None):
151
+ """The mitigated offer cap ERCOT uses when it has nothing better (4.4.9.4.1): a generic heat rate times the fuel
152
+ index price, the same at every output.
153
+
154
+ fuel_index_price $/MMBtu, the day's natural gas index price
155
+ after_2004 names of resources that began commercial operation after January 1, 2004 (heat rate 14.5
156
+ instead of 10.5, from rules.generic_heat_rates)
157
+ verifiable optional table resource, mw, price: cost-based caps you know. The cap is the higher of the
158
+ two at each point. ERCOT's verifiable costs are confidential, so without this the result
159
+ is a lower bound on the true cap
160
+ -> the mitigated_offer_caps table (resource, mw, price) for generators and storage."""
161
+ hr = rules.generic_heat_rates
162
+ late = set(after_2004)
163
+ rows = []
164
+ known = {} if verifiable is None else {n: g.sort_values('mw') for n, g in verifiable.groupby('resource')}
165
+ for x in resources.itertuples(index=False):
166
+ if getattr(x, 'kind', 'generator') == 'load':
167
+ continue
168
+ generic = hr['in_service_after_2004' if x.name in late else 'in_service_by_2004'] * float(fuel_index_price)
169
+ if x.name in known:
170
+ g = known[x.name]
171
+ rows += [{'resource': x.name, 'mw': float(m), 'price': max(generic, float(p))} for m, p in zip(g['mw'], g['price'])]
172
+ else:
173
+ rows += [{'resource': x.name, 'mw': float(x.low), 'price': generic}, {'resource': x.name, 'mw': float(x.high), 'price': generic}]
174
+ return pd.DataFrame(rows, columns=['resource', 'mw', 'price'])
175
+
176
+
177
+ def battery_efficiency(sced, rules=None, storage_types=('ESR',), min_runs=5, tolerance=0.0015):
178
+ """Each battery's charging efficiency, read off ERCOT's own Reg-Down awards. -> Series resource -> share.
179
+
180
+ Round Trip Efficiency is a registered Resource Parameter (3.7.1.3(1)(c)) that ERCOT does not publish. It shows in
181
+ the awards: when state of charge is what holds a battery's Reg-Down award,
182
+
183
+ efficiency x (Reg-Down duration x award + charging MW x interval) = soc_max - soc + discharging MW x interval
184
+
185
+ so that ratio never falls below the battery's efficiency and keeps returning to it. A battery is given the lowest
186
+ ratio it shows if at least `min_runs` runs sit on it; others are left out (the rulebook's default applies).
187
+ `sced` is 60-Day SCED Disclosure rows for storage, one day or many. On seven days in 2026 this gives 107 of 157
188
+ batteries a value, all between 0.81 and 1.0, the same on every day."""
189
+ from opensced.markets.ercot import adapter, rulebooks
190
+ x = adapter.normalize(sced)
191
+ rules = rules or rulebooks.ALL.latest
192
+ typ = x['Resource Type'].astype(str).str.strip() if 'Resource Type' in x else pd.Series('', index=x.index)
193
+ x = x[typ.isin(storage_types).to_numpy() & (x['Telemetered Resource Status'].astype(str).str.strip() == 'ON').to_numpy()]
194
+ need = ('SOC', 'maxSOC', 'ASAwardsREGDN', 'Base Point')
195
+ if not len(x) or any(c not in x for c in need):
196
+ return pd.Series(dtype=float, name='efficiency')
197
+ n = lambda c: pd.to_numeric(x[c], errors='coerce').to_numpy(float)
198
+ room, award, p = n('maxSOC') - n('SOC'), np.nan_to_num(n('ASAwardsREGDN')), np.nan_to_num(n('Base Point'))
199
+ down = next(q for q in rules.products if q.direction == 'down')
200
+ stp = rules.interval_hours
201
+ ok = (award > 1.0) & (room > 0.05)
202
+ ratio = (room + np.maximum(p, 0) * stp)[ok] / (down.duration_hours * award + np.maximum(-p, 0) * stp)[ok]
203
+ d = pd.DataFrame({'resource': x[adapter.RES].to_numpy()[ok], 'ratio': ratio})
204
+ low = d.groupby('resource').ratio.transform('min')
205
+ at = d[(d.ratio - low) < tolerance].groupby('resource').ratio.agg(['size', 'min'])
206
+ at = at[(at['size'] >= min_runs) & (at['min'] > 0.5) & (at['min'] <= 1.0 + tolerance)]
207
+ return at['min'].clip(upper=1.0).round(4).rename('efficiency')
208
+
209
+
210
+ def qualified_mw(load_resources, rules=None, min_runs=3, tolerance=0.06):
211
+ """The most of each reserve product a controllable Load Resource is qualified to carry, read off ERCOT's own
212
+ awards. -> table resource, product, mw, for adapter.inputs(qualified_mw=...).
213
+
214
+ The qualified amount is registration data ERCOT does not publish. It shows in the awards: with the clearing price
215
+ above the load's own offer and above ERCOT's proxy offer, and room left to drop, the award stops at the same MW
216
+ run after run, month after month, and steps up when the load grows (OB_ALD1 in 2026: Non-Spin 4.4 MW until April
217
+ 11, 12.2 MW from April 24, 27.7 MW by August 23). A load and product get the largest award in the rows given, if at
218
+ least `min_runs` runs sit on it; others are left out and stay limited by telemetered capability alone.
219
+
220
+ This is a lower bound: the largest award seen, which is the qualified amount only when the award was held by it.
221
+ Give it many days, not one. `load_resources` is 60-Day SCED Load Resource rows, one day or many."""
222
+ from opensced.markets.ercot import rulebooks
223
+ rules = rules or rulebooks.ALL.latest
224
+ from opensced.markets.ercot import adapter
225
+ L = adapter.load_columns(load_resources)
226
+ bid = pd.to_numeric(L['SCEDBidCurveMW1'], errors='coerce').notna() if 'SCEDBidCurveMW1' in L else pd.Series(False, index=L.index)
227
+ L = L[bid.to_numpy()] # controllable: it has a bid curve
228
+ name = L['resourceName'].astype(str).str.strip()
229
+ out = []
230
+ for p in rules.products:
231
+ cols = [c.replace('ASCap', 'ASAwards') for c in p.capability_columns if c.replace('ASCap', 'ASAwards') in L]
232
+ if not cols or not len(L):
233
+ continue
234
+ a = sum(pd.to_numeric(L[c], errors='coerce').fillna(0.0) for c in cols)
235
+ top = a.groupby(name).transform('max')
236
+ at = ((a > top - tolerance) & (top > tolerance)).groupby(name).sum()
237
+ g = a.groupby(name).max()[at >= min_runs]
238
+ out.append(pd.DataFrame({'resource': g.index, 'product': p.name, 'mw': g.to_numpy(float)}))
239
+ return pd.concat(out, ignore_index=True) if out else pd.DataFrame(columns=['resource', 'product', 'mw'])
240
+
241
+
242
+ def offline_proxy_units(sced, reserve_offers, min_runs=1):
243
+ """Units ERCOT awards Non-Spin through its proxy offer while they are OFF. -> sorted names, for
244
+ adapter.inputs(offline_proxy=...).
245
+
246
+ An off-line unit is normally awarded only the Non-Spin its QSE offered on an off-line (OFFNS) offer; a quick-start
247
+ unit also gets ERCOT's proxy offer for the rest. A few other units get it too. Measured on 22 days: nine units were
248
+ awarded Non-Spin while OFF with no off-line offer of their own, on 104 of the 122 unit-runs where the proxy price was
249
+ under the clearing price; 78 other units in the same position were never awarded on 4,136 unit-runs. Which units
250
+ is not published, so they are read off the awards: a unit is named when, in at least `min_runs` runs, it is OFF,
251
+ awarded Non-Spin, and its off-line offer row has no Non-Spin price in the blocks a QSE submits (1 to 5).
252
+ `sced` is 60-Day SCED generation rows and `reserve_offers` the 60-Day reserve offers of the same runs."""
253
+ from opensced.markets.ercot import adapter
254
+ s = adapter.normalize(sced)
255
+ st = s['Telemetered Resource Status'].astype(str).str.strip().str.upper()
256
+ won = pd.to_numeric(s['ASAwardsNSPIN'], errors='coerce').fillna(0.0) > 0.05 if 'ASAwardsNSPIN' in s else pd.Series(False, index=s.index)
257
+ a = s.loc[(st == 'OFF') & won, [adapter.TS, adapter.RES]].copy()
258
+ if not len(a):
259
+ return []
260
+ a.columns = ['t', 'n']
261
+ a['t'], a['n'] = pd.to_datetime(a['t']).dt.floor('5min'), a['n'].astype(str).str.strip()
262
+ o = adapter.offer_columns(reserve_offers)
263
+ o = o[o['resourceName'].astype(str).str.strip().isin(set(a['n']))].copy()
264
+ if 'offerType' in o and o['offerType'].notna().any():
265
+ o = o[o['offerType'].astype(str).str.strip() == 'OFFNS']
266
+ else: # files of December 2025 with no offer type
267
+ o = o.assign(offerType=adapter._offer_types(o.rename(columns={'resourceName': 'resource', 'offerType': 'offer_type'})).to_numpy())
268
+ o = o[o['offerType'] == 'OFFNS']
269
+ own = np.zeros(len(o), bool)
270
+ for k in range(1, 6):
271
+ if f'price{k}NSPIN' in o and f'quantityMW{k}' in o:
272
+ own |= (pd.to_numeric(o[f'price{k}NSPIN'], errors='coerce').notna() & (pd.to_numeric(o[f'quantityMW{k}'], errors='coerce') > 0)).to_numpy()
273
+ o = pd.DataFrame({'t': pd.to_datetime(o['SCEDTimestamp']).dt.floor('5min').to_numpy(), 'n': o['resourceName'].astype(str).str.strip().to_numpy(), 'own': own})
274
+ m = a.merge(o.groupby(['t', 'n'], as_index=False)['own'].max(), on=['t', 'n'], how='left')
275
+ m['own'] = m['own'].fillna(False).astype(bool) # no off-line row at all: nothing of its own either
276
+ n = m[~m['own']].groupby('n').size()
277
+ return sorted(n[n >= min_runs].index)
@@ -0,0 +1,284 @@
1
+ """The pricing run: Real-Time Reliability Deployment Price Adders (Protocols 6.5.7.3.1).
2
+
3
+ When ERCOT has taken reliability actions (units committed by RUC, Load Resources deployed, emergency imports), the
4
+ dispatch run's prices are lower than they would have been without them. ERCOT solves SCED a second time with those
5
+ actions undone and adds the difference to settlement prices:
6
+
7
+ adder for energy = max(pricing-run system lambda - dispatch-run system lambda, 0) 6.5.7.3.1(2)(o)
8
+ adder for a reserve = max(pricing-run clearing price - dispatch-run clearing price, 0) 6.5.7.3.1(2)(p)
9
+
10
+ The pricing run changes these inputs:
11
+
12
+ (a) a RUC-committed unit (status ONRUC, not opted out of RUC settlement), or one named in `rmr`: LSL and LDL to
13
+ zero, its reserve offers removed, and for the first step all its capacity offered at the power balance
14
+ penalty price
15
+ (c)-(e) every other on-line resource SCED can move: LDL and HDL widened to what it can reach in 60 minutes from
16
+ its telemetered output (not past LSL and HSL)
17
+ (f) the MW of non-controllable Load Resources that were deployed are added to demand, with a virtual offer for
18
+ the same MW priced from $300 for the first MW to $700 for the last
19
+ (g)-(k) other deployed MW (ERS, DC tie and block load transfer adjustments) added to or taken off demand
20
+ (l)-(n) the two-step clearing again. Step 1 on competitive constraints only, RUC and RMR units at the penalty
21
+ price; each resource's price in it is its reference price. Step 2 on every constraint. In step 2 a RUC or
22
+ RMR unit that is subject to mitigation (Protocols 3.19.4, 6.5.7.3(14)(b)(i)) has its penalty-price curve
23
+ capped at its reference price, so it comes back wherever step 2 would otherwise price above step 1. One that
24
+ is not subject to mitigation stays at the penalty price. Checked on ERCOT's adders both ways:
25
+ August 23, 2026 at 20:00, RUC units mitigated: ERCOT $39.86; capped $39.7; left at the penalty price $209.76
26
+ March 23, 2026 at 21:50, RUC units not mitigated: ERCOT $286.92; at the penalty price $294.78; capped $105.26
27
+ Who is subject to mitigation is an input (`mitigated`): the competitiveness test is not run here.
28
+ mitigated_in_hour() reads it off ERCOT's own curves.
29
+ Every other resource keeps the curve it was given. Give `unmitigated` (the same run built from ERCOT's step 1
30
+ curves, see unmitigated_inputs) to redo their mitigation against the pricing run's own reference prices too
31
+
32
+ With no reliability action in the interval there is no pricing run and the adders are zero.
33
+
34
+ What ERCOT publishes for each run (Real-Time Price Adders, NP6-323-CD): the adders, the RUC and RMR capacity relaxed
35
+ (RTRRUC, RTRRMR) and the MW added to demand (RTDNCLR, RTDERS, the DC tie and BLT columns).
36
+
37
+ from opensced.markets.ercot import pricing
38
+ run = pricing.pricing_run(inputs, deployed_load_mw=122.1)
39
+ run.energy_adder, run.reserve_adders, run.dispatch, run.pricing
40
+ """
41
+ from dataclasses import dataclass, replace
42
+
43
+ import numpy as np
44
+ import pandas as pd
45
+
46
+ from opensced.core.model import clear
47
+ from opensced.markets.ercot.rulebooks import ALL
48
+
49
+ RUC_STATUSES = ('ONRUC',)
50
+ NOT_WIDENED = ('ONRUC', 'ONTEST', 'STARTUP', 'STARTUP-NS', 'SHUTDOWN', 'ONHOLD', 'OUTL')
51
+ RAMP_MINUTES = 60.0
52
+ RUC_OFFER_FLOOR = 250.0 # a RUC-committed unit must offer at or above this
53
+ DEPLOYED_LOAD_BID = (300.0, 700.0) # $/MWh for the first and the last deployed MW
54
+ DEPLOYED = 'deployed load resources'
55
+
56
+
57
+ @dataclass
58
+ class PricingRun:
59
+ dispatch: object # Result of the dispatch run
60
+ pricing: object # Result of the pricing run
61
+ energy_adder: float
62
+ reserve_adders: pd.Series
63
+ relaxed_mw: float # RUC / RMR low limits set to zero, MW
64
+ added_demand_mw: float
65
+
66
+ def __repr__(self):
67
+ ra = ', '.join(f'{k} {v:.2f}' for k, v in self.reserve_adders.items())
68
+ return (f'pricing run: lambda {self.pricing.system_lambda:.2f} against {self.dispatch.system_lambda:.2f} in the dispatch run\n'
69
+ f' energy adder ${self.energy_adder:.2f}; reserve adders {ra}\n'
70
+ f' {self.relaxed_mw:,.1f} MW of RUC/RMR low limits relaxed, {self.added_demand_mw:,.1f} MW added to demand')
71
+
72
+
73
+ def relaxed_units(inputs, rmr=(), opted_out=()):
74
+ """Names of the units the pricing run prices out: ONRUC and not opted out, or named in rmr."""
75
+ r = inputs.resources
76
+ status = r['status'].astype(str).to_numpy() if 'status' in r else np.full(len(r), '')
77
+ m = (np.isin(status, RUC_STATUSES) & ~r['name'].isin(set(opted_out)).to_numpy()) | r['name'].isin(set(rmr)).to_numpy()
78
+ return list(r['name'][m])
79
+
80
+
81
+ def pricing_inputs(inputs, deployed_load_mw=0.0, other_demand_mw=0.0, rmr=(), opted_out=(), ramp_minutes=RAMP_MINUTES,
82
+ keep_binding_limits=False, deployed_load_bid=DEPLOYED_LOAD_BID, deployed_load_node=None, penalty_price=None):
83
+ """The dispatch run's Inputs changed as 6.5.7.3.1(2)(a)-(k) says. -> (Inputs, MW of low limits relaxed)
84
+
85
+ deployed_load_mw MW of deployed non-controllable Load Resources to add back (ERCOT's RTDNCLR)
86
+ other_demand_mw net MW of the other reliability deployments to add to demand (ERS, DC tie, BLT)
87
+ rmr names of Reliability Must-Run units that are on line
88
+ opted_out names of ONRUC units whose QSE opted out of RUC settlement (6.5.7.3.1(1)(a)): they are left as
89
+ they are. ERCOT does not publish who opted out; opted_out_from_relaxed() works it out from the
90
+ relaxed MW ERCOT does publish (RTRRUC)
91
+ penalty_price $/MWh for a RUC or RMR unit's capacity. Default: the rulebook's shortage price
92
+ keep_binding_limits leave a limit where the base point sat on it (NPRR904's wording, not yet in force: with no
93
+ reliability action ERCOT's adders are matched only when every limit is widened)
94
+ deployed_load_node settlement point for the virtual offer, if the network is modelled and you know where"""
95
+ r = inputs.resources.copy()
96
+ status = r['status'].astype(str).to_numpy() if 'status' in r else np.full(len(r), '')
97
+ ruc = (np.isin(status, RUC_STATUSES) & ~r['name'].isin(set(opted_out)).to_numpy()) | r['name'].isin(set(rmr)).to_numpy()
98
+ low, high = r['low'].to_numpy(float), r['high'].to_numpy(float)
99
+ rl = r['ramp_low'].fillna(r['low']).to_numpy(float) if 'ramp_low' in r else low.copy()
100
+ rh = r['ramp_high'].fillna(r['high']).to_numpy(float) if 'ramp_high' in r else high.copy()
101
+ relaxed = float(np.clip(np.maximum(low, rl)[ruc], 0, None).sum())
102
+ low, rl = np.where(ruc, np.minimum(low, 0.0), low), np.where(ruc, np.minimum(rl, 0.0), rl)
103
+ disp = r['dispatchable'].fillna(False).to_numpy(bool) if 'dispatchable' in r else np.ones(len(r), bool)
104
+ if 'telemetered' in r and 'ramp_up' in r:
105
+ tel = r['telemetered'].to_numpy(float)
106
+ up, down = r['ramp_up'].to_numpy(float), r['ramp_down'].to_numpy(float)
107
+ out = r['output'].to_numpy(float)
108
+ load = (r['kind'] == 'load').to_numpy() if 'kind' in r else np.zeros(len(r), bool)
109
+ tel = np.where(load, out, tel) # a controllable load: its consumption going in
110
+ wide = disp & ~ruc & ~np.isin(status, NOT_WIDENED) & np.isfinite(tel) & np.isfinite(up) & np.isfinite(down)
111
+ gen = wide & ~load & (r['kind'] != 'storage').to_numpy() if 'kind' in r else wide
112
+ wide &= ~(gen & (tel < 0.95 * low)) # (c): not a generator running below 95% of LSL
113
+ at_low, at_high = np.abs(out - rl) < 1e-3, np.abs(out - rh) < 1e-3
114
+ new_low = np.maximum(tel - ramp_minutes * down, low)
115
+ new_high = np.minimum(tel + ramp_minutes * up, high)
116
+ rl = np.where(wide & ~(keep_binding_limits & at_low), np.minimum(rl, new_low), rl)
117
+ rh = np.where(wide & ~(keep_binding_limits & at_high), np.maximum(rh, new_high), rh)
118
+ r['low'], r['ramp_low'], r['ramp_high'] = low, rl, rh
119
+ names_ruc = set(r['name'][ruc])
120
+ drop = lambda t: None if t is None else t[~t['resource'].isin(names_ruc)].reset_index(drop=True)
121
+ offers, eo = drop(inputs.reserve_offers), inputs.energy_offers
122
+ if names_ruc:
123
+ pen = float(ALL.on(inputs.time).shortage if penalty_price is None and inputs.time is not None else (penalty_price or ALL.latest.shortage))
124
+ eo = pd.concat([eo[~eo['resource'].isin(names_ruc)], pd.DataFrame([{'resource': n, 'mw': mw, 'price': pen} for n, h in zip(r['name'][ruc], high[ruc]) for mw in (0.0, float(h))])], ignore_index=True)
125
+ limits = drop(inputs.reserve_limits)
126
+ demand = float(inputs.demand) + float(deployed_load_mw) + float(other_demand_mw)
127
+ nodes = inputs.resource_nodes
128
+ if deployed_load_mw > 0: # (f): the deployed MW come back as demand, with a
129
+ row = {c: np.nan for c in r.columns} # virtual offer that serves them at $300 to $700
130
+ row.update(name=DEPLOYED, low=0.0, high=float(deployed_load_mw), ramp_low=0.0, ramp_high=float(deployed_load_mw), output=0.0, dispatchable=True)
131
+ for c, v in (('kind', 'generator'), ('type', 'VIRTUAL'), ('status', 'ON'), ('category', 'other'), ('mitigated', False)):
132
+ if c in r:
133
+ row[c] = v
134
+ r = pd.concat([r, pd.DataFrame([row])], ignore_index=True)
135
+ eo = pd.concat([eo, pd.DataFrame({'resource': DEPLOYED, 'mw': [0.0, float(deployed_load_mw)], 'price': list(deployed_load_bid)})], ignore_index=True)
136
+ if deployed_load_node is not None and nodes is not None:
137
+ nodes = pd.concat([pd.Series(nodes), pd.Series({DEPLOYED: deployed_load_node})])
138
+ for c in ('dispatchable', 'mitigated'):
139
+ if c in r:
140
+ r[c] = r[c].astype(bool)
141
+ return inputs.copy(resources=r, demand=demand, energy_offers=eo, reserve_offers=offers, reserve_limits=limits, resource_nodes=nodes), relaxed
142
+
143
+
144
+ def below_ruc_floor(inputs):
145
+ """Names of ONRUC units offering below the RUC offer floor: a guess at who opted out of RUC settlement. Against
146
+ ERCOT's published relaxed MW it is right on every run of March 23, 2026 and wrong on a third of August 12."""
147
+ e, r = inputs.energy_offers, inputs.resources
148
+ lowest = e[e['mw'] > 0].groupby('resource')['price'].min()
149
+ under = set(lowest.index[lowest < RUC_OFFER_FLOOR - 0.01])
150
+ return sorted(under & set(r['name'][np.isin(r['status'].astype(str), RUC_STATUSES)]))
151
+
152
+
153
+ def capped_by_ercot(day, time):
154
+ """The resources ERCOT capped in one run, read off its curves: step 2 curve below step 1 curve.
155
+ -> (names, table resource, mw, price of their step 2 curves)
156
+
157
+ This only sees a cap that bit. A mitigated resource whose reference price is above its whole offer curve looks
158
+ the same as one that is not mitigated."""
159
+ from opensced.markets.ercot.adapter import NPT, RES
160
+ x = day._by_run[pd.Timestamp(time)].reset_index(drop=True)
161
+ num = lambda c: pd.to_numeric(x[c], errors='coerce').to_numpy(float) if c in x else np.full(len(x), np.nan)
162
+ m1 = np.column_stack([num(f'SCED1CurveMW{j}') for j in range(1, NPT + 1)])
163
+ p1 = np.column_stack([num(f'SCED1CurvePrice{j}') for j in range(1, NPT + 1)])
164
+ m2 = np.column_stack([num(f'SCED2CurveMW{j}') for j in range(1, NPT + 1)])
165
+ p2 = np.column_stack([num(f'SCED2CurvePrice{j}') for j in range(1, NPT + 1)])
166
+ names, capped, caps = x[RES].to_numpy(), [], []
167
+ for i in range(len(x)):
168
+ a, b = np.isfinite(m1[i]) & np.isfinite(p1[i]), np.isfinite(m2[i]) & np.isfinite(p2[i])
169
+ if a.sum() < 2 or b.sum() < 2:
170
+ continue
171
+ u = np.unique(m2[i][b])
172
+ if len(u) < 2:
173
+ continue
174
+ q = (u[:-1] + u[1:]) / 2
175
+ o1, o2 = np.argsort(m1[i][a], kind='stable'), np.argsort(m2[i][b], kind='stable')
176
+ if (np.interp(q, m2[i][b][o2], p2[i][b][o2]) < np.interp(q, m1[i][a][o1], p1[i][a][o1]) - 0.011).any():
177
+ capped.append(names[i])
178
+ caps.append(pd.DataFrame({'resource': names[i], 'mw': m2[i][b][o2], 'price': p2[i][b][o2]}))
179
+ return capped, (pd.concat(caps, ignore_index=True) if caps else None)
180
+
181
+
182
+ def mitigated_in_hour(day, time):
183
+ """Names of the resources ERCOT's curves show as capped in any run of the Operating Hour `time` is in.
184
+
185
+ Mitigation, once applied to a resource, stays for the rest of the Operating Hour (3.19.4), and a cap can only be
186
+ seen in a run where it bit, so the hour is read as a whole. A resource whose reference price stayed above its
187
+ offer curve all hour cannot be told apart from one that was never mitigated: it is left out."""
188
+ t = pd.Timestamp(time)
189
+ names = set()
190
+ for u in day.times:
191
+ if pd.Timestamp(u).floor('h') == t.floor('h'):
192
+ names |= set(capped_by_ercot(day, u)[0])
193
+ return sorted(names)
194
+
195
+
196
+ def opted_out_from_relaxed(inputs, relaxed_mw, tolerance=1.0, rmr=()):
197
+ """Names of the ONRUC units left out of ERCOT's pricing run, worked out from the RUC capacity it says it relaxed
198
+ (RTRRUC in the Real-Time Price Adders report). -> list of names, or None when no set of units adds up
199
+
200
+ ERCOT does not publish who opted out of RUC settlement, but it does publish the total low limit it set to zero.
201
+ The units whose low dispatch limits add up to that total are the ones it relaxed; the rest were left alone.
202
+ With several sets within the tolerance, the one leaving out the fewest units is taken."""
203
+ from itertools import combinations
204
+ r = inputs.resources
205
+ names = relaxed_units(inputs, rmr)
206
+ if not names:
207
+ return []
208
+ x = r.set_index('name')
209
+ low = np.maximum(x['low'], x['ramp_low'].fillna(x['low']) if 'ramp_low' in x else x['low']).clip(lower=0.0).reindex(names).to_numpy(float)
210
+ if len(names) > 16:
211
+ return None
212
+ for k in range(len(names) + 1): # leave out as few as possible
213
+ best = None
214
+ for out in combinations(range(len(names)), k):
215
+ miss = abs(low.sum() - low[list(out)].sum() - float(relaxed_mw))
216
+ if miss <= tolerance and (best is None or miss < best[0]):
217
+ best = (miss, out)
218
+ if best is not None:
219
+ return [names[i] for i in best[1]]
220
+ return None
221
+
222
+
223
+ def unmitigated_inputs(day, time, **options):
224
+ """A run's Inputs from ERCOT's step 1 (unmitigated) curves, with the resources ERCOT capped marked `mitigated` and
225
+ their caps taken from ERCOT's own step 2 curves. day: an ERCOT Day. options: as for day.inputs().
226
+
227
+ A resource was capped where its step 2 curve is below its step 1 curve. Its step 2 curve is then the cap ERCOT
228
+ applied in the dispatch run: the higher of its mitigated offer cap and that run's reference price. In the pricing
229
+ run the cap is the higher of that curve and the pricing run's own reference price."""
230
+ capped, table = capped_by_ercot(day, time)
231
+ return day.inputs(time, curve='SCED1', mitigated=capped, mitigated_offer_caps=table, **options)
232
+
233
+
234
+ def pricing_run(inputs, rules=None, dispatch=None, unmitigated=None, always=False, mitigated=None, **changes):
235
+ """Clear the dispatch run and the pricing run and take the adders. -> PricingRun
236
+
237
+ inputs the dispatch run's Inputs (from ercot.inputs() or Day.inputs())
238
+ rules the rulebook. Default: the one in force at inputs.time
239
+ dispatch the dispatch run's Result, if already cleared
240
+ unmitigated the same run from ERCOT's step 1 curves (unmitigated_inputs). Every resource's curve is then mitigated
241
+ again against the pricing run's reference prices, not only the RUC and RMR units'
242
+ mitigated names of the resources subject to mitigation in the interval (mitigated_in_hour). Only matters for
243
+ RUC and RMR units: one named here is capped at its step 1 price in step 2, any other stays at the
244
+ penalty price. Default: the ones marked `mitigated` in inputs.resources
245
+ always run the pricing solve even when no reliability action is active. By default the adders are zero then:
246
+ 6.5.7.3.1(2) determines them only "for intervals where there are reliability deployments". Some
247
+ deployments are not in ERCOT's published report (off-line Non-Spin brought on line, for one); pass
248
+ always=True for an interval you know had one
249
+ changes deployed_load_mw, other_demand_mw, rmr, ... (see pricing_inputs)"""
250
+ from opensced.core.features import mitigation
251
+ from opensced.core.model import _clear_once
252
+ rules = rules or (ALL.on(inputs.time) if inputs.time is not None else ALL.latest)
253
+ dispatch = dispatch or clear(inputs, rules, check=False)
254
+ changed, relaxed = pricing_inputs(inputs if unmitigated is None else unmitigated, **changes)
255
+ acted = relaxed > 0 or abs(float(changed.demand) - float((inputs if unmitigated is None else unmitigated).demand)) > 0 or bool(changes.get('rmr'))
256
+ if not acted and not always: # nothing was deployed: there is no pricing run
257
+ zero = pd.Series(0.0, index=dispatch.reserve_prices.index, name='adder') if dispatch.reserve_prices is not None else pd.Series(dtype=float, name='adder')
258
+ return PricingRun(dispatch, dispatch, 0.0, zero, 0.0, 0.0)
259
+ source = inputs if unmitigated is None else unmitigated
260
+ units = relaxed_units(source, changes.get('rmr', ()), changes.get('opted_out', ()))
261
+ if unmitigated is None and not units: # only demand was added: one solve
262
+ priced = clear(changed, rules, check=False)
263
+ else:
264
+ step1 = _clear_once(mitigation.competitive_only(changed), rules)
265
+ if not step1.solved:
266
+ priced = step1
267
+ else:
268
+ step1._inputs = changed
269
+ reference = step1.resource_prices().rename('reference_price')
270
+ offers = changed.energy_offers if unmitigated is None else mitigation.mitigate(changed, reference, rules)
271
+ flagged = set(mitigated) if mitigated is not None else (set(source.resources['name'][source.resources['mitigated'].fillna(False).astype(bool)]) if 'mitigated' in source.resources else set())
272
+ capped = [n for n in units if n in flagged and n in reference.index and np.isfinite(reference[n])]
273
+ if capped: # (m): a mitigated priced-out unit is capped at its reference price
274
+ high = changed.resources.set_index('name')['high']
275
+ cap = pd.DataFrame([{'resource': n, 'mw': mw, 'price': float(reference[n])} for n in capped for mw in (0.0, float(high[n]))])
276
+ offers = pd.concat([offers[~offers['resource'].isin(set(capped))], cap], ignore_index=True)
277
+ priced = _clear_once(changed.copy(energy_offers=offers, mitigated=True), rules)
278
+ priced.reference_prices, priced.step1 = reference, step1
279
+ energy = max(priced.system_lambda - dispatch.system_lambda, 0.0) if priced.solved and dispatch.solved else float('nan')
280
+ if priced.reserve_prices is not None and dispatch.reserve_prices is not None:
281
+ reserves = (priced.reserve_prices - dispatch.reserve_prices).clip(lower=0.0).rename('adder')
282
+ else:
283
+ reserves = pd.Series(dtype=float, name='adder')
284
+ return PricingRun(dispatch, priced, energy, reserves, relaxed, float(changed.demand) - float(inputs.demand))