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/core/rules.py ADDED
@@ -0,0 +1,343 @@
1
+ """Rulebooks: the numbers and switches a market's clearing used from one date until the next change.
2
+
3
+ rules = ercot.rules.on('2026-08-12') # the rulebook in force that day
4
+ rules.shortage_price
5
+ draft = rules.replace(name='draft/longer-ecrs', products={'ECRS': {'duration_hours': 2.0}})
6
+
7
+ A rulebook is never edited once released. A correction, or a proposed rule, is a new rulebook made with replace().
8
+ """
9
+ from dataclasses import dataclass, field, replace
10
+
11
+ import pandas as pd
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Product:
16
+ """One reserve product.
17
+ direction 'up' (held as room above the output) or 'down' (room below it)
18
+ duration_hours how long a battery must be able to sustain the award from its stored energy
19
+ regulation True if the award must also fit inside what the resource can ramp within the interval
20
+ ramp_minutes minutes of ramp that count towards a resource's limit for the product (used by adapters that are
21
+ given ramp rates instead of MW limits)
22
+ demand the demand curve its awards count towards. Default: its own name. Several products can serve
23
+ one demand curve: ERCOT's RRS is met by three kinds of response, each a product of its own
24
+ reserved_mw MW of that demand curve only this product may fill. The other products serving the same curve
25
+ share what is left"""
26
+ name: str
27
+ direction: str
28
+ duration_hours: float = 0.0
29
+ regulation: bool = False
30
+ ramp_minutes: float | None = None
31
+ demand: str | None = None
32
+ reserved_mw: float = 0.0
33
+ capability_columns: tuple = () # for adapters: the published columns holding a resource's capability for it
34
+ offer_price_columns: tuple = () # for adapters: the published offer price columns (the cheapest is used)
35
+ offer_kinds: tuple = () # for adapters: the kinds of offer that can carry it
36
+
37
+ @property
38
+ def serves(self):
39
+ return self.demand or self.name
40
+
41
+ def __post_init__(self):
42
+ if self.direction not in ('up', 'down'):
43
+ raise ValueError(f"product {self.name!r}: direction must be 'up' or 'down'")
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Limit:
48
+ """A cap on the total awards of some reserve products, optionally from some resources only.
49
+
50
+ products the reserve products whose awards are added up
51
+ max_mw the cap in MW, and / or
52
+ max_share the cap as a share of a requirement (`of`: the demand curve's name), and / or
53
+ max_less the cap as a requirement less this many MW, never below zero (`of` again). It says the same as "at least
54
+ this many MW, or the whole requirement if that is smaller, comes from the other resources"
55
+ min_mw, min_share a floor instead of, or as well as, a cap. A floor that cannot be met makes the interval unsolved
56
+ where count only resources whose column matches, e.g. {'type': 'NCLR'}. Default: every resource
57
+ source the rule it comes from"""
58
+ name: str
59
+ products: tuple
60
+ max_mw: float | None = None
61
+ max_share: float | None = None
62
+ max_less: float | None = None
63
+ min_mw: float | None = None
64
+ min_share: float | None = None
65
+ of: str | None = None
66
+ where: tuple = ()
67
+ source: str = ''
68
+
69
+ def __post_init__(self):
70
+ if all(v is None for v in (self.max_mw, self.max_share, self.max_less, self.min_mw, self.min_share)):
71
+ raise ValueError(f'limit {self.name!r}: give max_mw or max_share (or min_mw, min_share)')
72
+ if (self.max_share is not None or self.min_share is not None or self.max_less is not None) and self.of is None:
73
+ raise ValueError(f'limit {self.name!r}: max_share and max_less need `of`, the demand curve they are measured against')
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class Status:
78
+ """What a resource in a given status may do.
79
+ dispatchable the clearing may move it
80
+ reserves which reserves it may carry: {kind of offer: tuple of product names, or None for every product}.
81
+ An empty dict: none
82
+ proxy_reserves False: it is awarded reserves only on offers it submitted, never on the market operator's proxy
83
+ offer for unoffered capacity"""
84
+ name: str
85
+ dispatchable: bool = False
86
+ reserves: dict = field(default_factory=dict, hash=False)
87
+ proxy_reserves: bool = True
88
+
89
+
90
+ FEATURES = ('network', 'reserves', 'storage')
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class Rules:
95
+ """A rulebook. Every field has a default, so Rules() is a plain energy-and-network clearing.
96
+
97
+ name, effective, source what it is, the date it took effect, and the rule change it came from
98
+ shortage_price $/MWh when supply cannot meet demand
99
+ surplus_price $/MWh when supply cannot be backed down far enough (negative)
100
+ default_max_shadow_price $/MWh for a constraint that comes without its own
101
+ dispatch_limits 'both': a resource moves between max(ramp_low, low) and min(ramp_high, high). 'ramp': between
102
+ ramp_low and ramp_high alone, for a market whose dispatch range is not clipped to the
103
+ sustained limits
104
+ block_mw offer curves are cut into steps of at most this many MW
105
+ block_refine times the interval is solved again with every curve cut finer around where its resource
106
+ landed. Each pass cuts block_refine_factor times finer. 0: steps of block_mw only
107
+ offer_curves 'steps': curves cut into steps (block_mw, block_refine). 'exact': each sloped stretch is
108
+ costed as the area under it, a quadratic program (needs the highspy package)
109
+ interval_hours length of one dispatch interval
110
+ regulation_share share of a regulation award that must fit within the interval's ramp range
111
+ products the reserve products, in order
112
+ limits caps on the total awards of groups of reserve products (see Limit)
113
+ price_cap $/MWh. The system lambda and reserve prices are capped here after the solve, and node
114
+ prices above it are pulled down by what the lambda was cut. None: no cap
115
+ shift_factor_cutoff shift factors smaller than this are ignored in the dispatch
116
+ voll, offer_cap, offer_floor, shortage_adder
117
+ the value of lost load, the system-wide offer cap and the offer floor. With
118
+ shortage_price=None the shortage price is voll + offer_cap + shortage_adder, and with
119
+ price_cap=None prices are capped at voll (when voll is given)
120
+ no_offer_price $/MWh for a dispatchable resource with no offer curve
121
+ curve_extension 'flat': a curve's end prices hold beyond its ends. 'floor': the range below its lowest
122
+ point is priced at offer_floor
123
+ zero_split cut every curve at 0 MW, so charging and discharging are separate blocks
124
+ reserve_offer_floor reserve offer prices below this are raised to it
125
+ no_reserve_offer_price $/MW per hour for reserves when no reserve_offers table is given
126
+ self_arranged_price $/MW per hour at which adapters offer self-arranged reserves
127
+ demand_curve_pricing 'mean': a stretch between two demand curve points is worth their average. 'left': the
128
+ price at its start
129
+ storage_signed_energy a battery's output counts with its sign against its stored energy: charging during the
130
+ interval adds exactly that energy to what its reserve awards may draw on
131
+ storage_charge_efficiency share of charging energy stored, for a battery whose `efficiency` is not given
132
+ storage_charge_offset an older reading, off by default: a charging battery may count every MW it could
133
+ stop charging as reserve that needs no stored energy
134
+ storage_passes how many times an interval may be solved again to stop batteries charging and
135
+ discharging at once (see core/features/storage.py). 0 turns the check off
136
+ tolerance_mw MW differences smaller than this are treated as zero
137
+ dispatch_minutes minutes of ramp in the dispatch range (used by the helpers that compute ramp_low/high)
138
+ proxy_*, irr_proxy_price, ruc_*, clr_no_bid_price, shadow_price_caps
139
+ numbers the market's helpers use to build proxy offers, proxy curves and constraint caps
140
+ statuses what each resource status may do (see Status)
141
+ two_step clear twice: once on the competitive constraints for reference prices, then on every
142
+ constraint with mitigated offers (see opensced.core.features.mitigation). Skipped
143
+ when inputs.mitigated says the offers are already the step-2 curves
144
+ mitigated_offer_floors $/MWh by resource category; 'other' is the fallback
145
+ mitigation_adder_share share of a resource's mitigated offer cap at its low limit added to its reference price
146
+ generic_heat_rates MMBtu/MWh used by helpers that build a generic mitigated offer cap from a fuel price
147
+ solver, solver_options passed to scipy.optimize.linprog
148
+ features which parts of the clearing are on: 'network', 'reserves', 'storage'
149
+ notes per-entry provenance: which numbers were read from the rules and which were measured"""
150
+ name: str = 'custom'
151
+ effective: str | None = None
152
+ source: str = ''
153
+ shortage_price: float | None = 5000.0
154
+ surplus_price: float = -250.0
155
+ voll: float | None = None
156
+ offer_cap: float | None = None
157
+ offer_floor: float = -250.0
158
+ shortage_adder: float = 0.0
159
+ default_max_shadow_price: float = 5251.0
160
+ dispatch_limits: str = 'both'
161
+ block_mw: float = 5.0
162
+ block_refine: int = 0
163
+ offer_curves: str = 'steps'
164
+ block_refine_factor: float = 10.0
165
+ interval_hours: float = 5 / 60
166
+ regulation_share: float = 1.0
167
+ products: tuple = ()
168
+ limits: tuple = ()
169
+ price_cap: float | None = None
170
+ shift_factor_cutoff: float = 0.0
171
+ no_offer_price: float = 0.0
172
+ curve_extension: str = 'flat'
173
+ zero_split: bool = True
174
+ reserve_offer_floor: float = 0.0
175
+ no_reserve_offer_price: float = 0.0
176
+ self_arranged_price: float = 0.0
177
+ demand_curve_pricing: str = 'mean'
178
+ storage_signed_energy: bool = True
179
+ storage_charge_efficiency: float = 1.0
180
+ storage_charge_offset: bool = False
181
+ storage_passes: int = 4
182
+ tolerance_mw: float = 1e-6
183
+ dispatch_minutes: float = 5.0
184
+ proxy_price_step: float = 0.01
185
+ proxy_mw_step: float = 1.0
186
+ irr_proxy_price: float = 1500.0
187
+ ruc_offer_floor: float = 250.0
188
+ ruc_reserve_offer_price: float = 250.0
189
+ proxy_reserve_cap: float = 2000.0
190
+ proxy_reserve_plan_share: float = 0.95
191
+ clr_no_bid_price: float | None = None
192
+ shadow_price_caps: dict = field(default_factory=dict, hash=False)
193
+ statuses: tuple = ()
194
+ two_step: bool = False
195
+ mitigated_offer_floors: dict = field(default_factory=dict, hash=False)
196
+ mitigation_adder_share: float = 0.0
197
+ generic_heat_rates: dict = field(default_factory=dict, hash=False)
198
+ solver: str = 'highs'
199
+ solver_options: dict = field(default_factory=dict, hash=False)
200
+ features: tuple = FEATURES
201
+ notes: dict = field(default_factory=dict, compare=False)
202
+
203
+ def __post_init__(self):
204
+ bad = set(self.features) - set(FEATURES)
205
+ if bad:
206
+ raise ValueError(f'unknown feature(s) {sorted(bad)}. Choose from {FEATURES}')
207
+ if self.block_mw <= 0:
208
+ raise ValueError('block_mw must be positive')
209
+
210
+ @property
211
+ def shortage(self):
212
+ """the shortage price in force: shortage_price, or voll + offer_cap + shortage_adder when it is None."""
213
+ if self.shortage_price is not None:
214
+ return self.shortage_price
215
+ if self.voll is None or self.offer_cap is None:
216
+ raise ValueError(f'rulebook {self.name!r}: give shortage_price, or voll and offer_cap to compute it')
217
+ return self.voll + self.offer_cap + self.shortage_adder
218
+
219
+ @property
220
+ def cap(self):
221
+ """the cap applied to prices after the solve: price_cap, or voll, or None."""
222
+ return self.price_cap if self.price_cap is not None else self.voll
223
+
224
+ def status(self, name):
225
+ for s in self.statuses:
226
+ if s.name == name:
227
+ return s
228
+ return None
229
+
230
+ @property
231
+ def product_names(self):
232
+ return tuple(p.name for p in self.products)
233
+
234
+ @property
235
+ def demand_names(self):
236
+ """the demand curves, in order: one per product unless several products serve the same curve."""
237
+ return tuple(dict.fromkeys(p.serves for p in self.products))
238
+
239
+ def serving(self, demand):
240
+ """names of the products whose awards count towards a demand curve."""
241
+ return tuple(p.name for p in self.products if p.serves == demand)
242
+
243
+ def product(self, name):
244
+ for p in self.products:
245
+ if p.name == name:
246
+ return p
247
+ raise KeyError(f'no product {name!r} in rulebook {self.name!r}. It has: {", ".join(self.product_names)}')
248
+
249
+ def has(self, feature):
250
+ return feature in self.features
251
+
252
+ def replace(self, products=None, **changes):
253
+ """A new rulebook with some entries changed. products: {product name: {field: value}} changes those products
254
+ and keeps the rest, e.g. rules.replace(name='draft/x', products={'ECRS': {'duration_hours': 2.0}})."""
255
+ if products is not None:
256
+ unknown = set(products) - set(self.product_names)
257
+ if unknown:
258
+ raise KeyError(f'no product {sorted(unknown)[0]!r} in rulebook {self.name!r}')
259
+ changes['products'] = tuple(replace(p, **products[p.name]) if p.name in products else p for p in self.products)
260
+ if 'name' not in changes:
261
+ changes['name'] = f'{self.name} (modified)'
262
+ return replace(self, **changes)
263
+
264
+ def diff(self, other):
265
+ """What differs from another rulebook: {entry: (this, other)}."""
266
+ out = {}
267
+ from dataclasses import fields as _fields
268
+ for k in (f.name for f in _fields(self) if f.name not in ('name', 'effective', 'source', 'notes', 'products')):
269
+ if getattr(self, k) != getattr(other, k):
270
+ out[k] = (getattr(self, k), getattr(other, k))
271
+ mine, theirs = {p.name: p for p in self.products}, {p.name: p for p in other.products}
272
+ for n in dict.fromkeys(list(mine) + list(theirs)):
273
+ if mine.get(n) != theirs.get(n):
274
+ out[f'products.{n}'] = (mine.get(n), theirs.get(n))
275
+ return out
276
+
277
+ def __repr__(self):
278
+ lines = [f'Rules {self.name!r}' + (f', in force from {self.effective}' if self.effective else ''),
279
+ *([f' source {self.source}'] if self.source else []),
280
+ f' shortage_price ${self.shortage:,.2f}' + ('' if self.shortage_price is not None else f' (voll {self.voll:,.0f} + offer_cap {self.offer_cap:,.0f} + {self.shortage_adder:,.2f})'),
281
+ f' surplus_price ${self.surplus_price:,.2f}',
282
+ f' default_max_shadow_price ${self.default_max_shadow_price:,.2f}',
283
+ f' block_mw {self.block_mw:g} MW',
284
+ f' interval_hours {self.interval_hours:.4g} ({self.interval_hours * 60:g} minutes)',
285
+ f' regulation_share {self.regulation_share:.4g}',
286
+ f' price_cap ' + ('none' if self.cap is None else f'${self.cap:,.2f}'),
287
+ f' shift_factor_cutoff {self.shift_factor_cutoff:g}',
288
+ f' features {", ".join(self.features)}']
289
+ for p in self.products:
290
+ lines.append(f' product {p.name:<9} {p.direction:<4} duration {p.duration_hours:g} h'
291
+ + (', regulation' if p.regulation else '') + (f', {p.ramp_minutes:g} min of ramp' if p.ramp_minutes else '')
292
+ + (f', counts towards {p.demand}' if p.demand else '') + (f', {p.reserved_mw:,.0f} MW reserved for it' if p.reserved_mw else ''))
293
+ for l in self.limits:
294
+ hi = ' and '.join(([f'{l.max_mw:,.0f} MW'] if l.max_mw is not None else []) + ([f'{l.max_share:.0%} of {l.of}'] if l.max_share is not None else []))
295
+ lo = ' and '.join(([f'{l.min_mw:,.0f} MW'] if l.min_mw is not None else []) + ([f'{l.min_share:.0%} of {l.of}'] if l.min_share is not None else []))
296
+ lines.append(f' limit {l.name}: {" + ".join(l.products)}' + (f' at most {hi}' if hi else '') + (f' at least {lo}' if lo else '') + (f' (where {dict(l.where)})' if l.where else ''))
297
+ return '\n'.join(lines)
298
+
299
+
300
+ class Rulebooks:
301
+ """A market's rulebooks in date order.
302
+
303
+ books.on('2026-08-12') the rulebook in force that day
304
+ books.get('ercot/2025-12-05')
305
+ books.versions() a table of every rulebook"""
306
+
307
+ def __init__(self, books):
308
+ self._books = sorted(books, key=lambda r: pd.Timestamp(r.effective))
309
+ if len({r.name for r in self._books}) != len(self._books):
310
+ raise ValueError('rulebook names must be unique')
311
+
312
+ def on(self, date):
313
+ t = pd.Timestamp(date)
314
+ if t.tzinfo is not None:
315
+ t = t.tz_localize(None)
316
+ live = [r for r in self._books if pd.Timestamp(r.effective) <= t]
317
+ if not live:
318
+ first = self._books[0]
319
+ raise LookupError(f'no rulebook for {t.date()}: the earliest is {first.name!r}, in force from {first.effective}. '
320
+ f'Dates before it cleared under rules this package does not model yet')
321
+ return live[-1]
322
+
323
+ def get(self, name):
324
+ for r in self._books:
325
+ if r.name == name:
326
+ return r
327
+ raise KeyError(f'no rulebook {name!r}. Available: {", ".join(r.name for r in self._books)}')
328
+
329
+ @property
330
+ def latest(self):
331
+ return self._books[-1]
332
+
333
+ def versions(self):
334
+ return pd.DataFrame([{'name': r.name, 'effective': r.effective, 'source': r.source} for r in self._books])
335
+
336
+ def __iter__(self):
337
+ return iter(self._books)
338
+
339
+ def __len__(self):
340
+ return len(self._books)
341
+
342
+ def __repr__(self):
343
+ return 'Rulebooks:\n' + '\n'.join(f' {r.effective} {r.name} {r.source}' for r in self._books)
opensced/core/score.py ADDED
@@ -0,0 +1,75 @@
1
+ """Compare cleared prices with published ones."""
2
+ from dataclasses import dataclass
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+
7
+
8
+ @dataclass
9
+ class Score:
10
+ """How close a set of clearings came to published prices.
11
+
12
+ table one row per measure
13
+ by_node mean absolute error per node, worst first
14
+ by_time mean absolute node error per interval"""
15
+ table: pd.DataFrame
16
+ by_node: pd.Series | None = None
17
+ by_time: pd.Series | None = None
18
+
19
+ def summary(self):
20
+ return self.table.to_string(float_format=lambda v: f'{v:,.2f}')
21
+
22
+ def __repr__(self):
23
+ return self.summary()
24
+
25
+
26
+ def _stats(err, what):
27
+ e = np.abs(np.asarray(err, float))
28
+ e = e[np.isfinite(e)]
29
+ if not len(e):
30
+ return None
31
+ return {'compared': what, 'values': len(e), 'mean_abs_error': e.mean(), 'median_abs_error': np.median(e),
32
+ 'p95_abs_error': np.percentile(e, 95), 'max_abs_error': e.max(),
33
+ 'pct_within_1': 100 * (e < 1).mean(), 'pct_within_5': 100 * (e < 5).mean()}
34
+
35
+
36
+ def score(result, system_lambda=None, node_prices=None, reserve_prices=None):
37
+ """Score a DayResult (or a single Result) against published prices.
38
+
39
+ system_lambda Series time -> $/MWh (or one number for a single Result)
40
+ node_prices DataFrame time x node (or a Series node -> price for a single Result)
41
+ reserve_prices DataFrame time x product
42
+
43
+ Only times and nodes present on both sides are compared. Errors are in $/MWh."""
44
+ from opensced.core.result import Result
45
+ if isinstance(result, Result):
46
+ t = result.time if result.time is not None else 0
47
+ lam = pd.Series({t: result.system_lambda})
48
+ nodes = pd.DataFrame({t: result.node_prices()}).T if node_prices is not None else None
49
+ res = pd.DataFrame({t: result.reserve_prices}).T if reserve_prices is not None and result.reserve_prices is not None else None
50
+ system_lambda = None if system_lambda is None else pd.Series({t: float(system_lambda)})
51
+ node_prices = None if node_prices is None else pd.DataFrame({t: node_prices}).T
52
+ reserve_prices = None if reserve_prices is None else pd.DataFrame({t: reserve_prices}).T
53
+ else:
54
+ lam, nodes = result.system_lambda, (result.node_prices if node_prices is not None else None)
55
+ res = result.reserve_prices if reserve_prices is not None else None
56
+ rows, by_node, by_time = [], None, None
57
+ if system_lambda is not None:
58
+ a, b = lam.align(pd.Series(system_lambda), join='inner')
59
+ rows.append(_stats(a - b, 'system lambda'))
60
+ if node_prices is not None:
61
+ a, b = nodes.align(node_prices, join='inner')
62
+ e = (a - b).abs()
63
+ rows.append(_stats(e.to_numpy(), 'node prices'))
64
+ by_node, by_time = e.mean().sort_values(ascending=False).rename('mean_abs_error'), e.mean(axis=1).rename('mean_abs_error')
65
+ if system_lambda is not None: # what ignoring congestion would cost
66
+ pub = pd.Series(system_lambda).reindex(b.index)
67
+ rows.append(_stats(b.sub(pub, axis=0).to_numpy(), 'node prices, if published lambda were used alone'))
68
+ if reserve_prices is not None and res is not None:
69
+ a, b = res.align(reserve_prices, join='inner')
70
+ for c in a.columns:
71
+ rows.append(_stats(a[c] - b[c], f'reserve price {c}'))
72
+ rows = [r for r in rows if r]
73
+ if not rows:
74
+ raise ValueError('nothing to compare: pass system_lambda, node_prices or reserve_prices with matching times and nodes')
75
+ return Score(pd.DataFrame(rows).set_index('compared'), by_node, by_time)
@@ -0,0 +1,105 @@
1
+ """Clearing a run of intervals one after another, each starting from where the last one ended.
2
+
3
+ Most of an interval's inputs come from outside: demand, offers, limits, the constraints. A few do not. They are the
4
+ result of the interval before:
5
+
6
+ output where each dispatchable resource starts: its dispatch in the interval before
7
+ ramp how far it can move from there: [output - ramp_down x minutes, output + ramp_up x minutes], inside its
8
+ sustained limits (needs the resources columns ramp_up and ramp_down, MW per minute)
9
+ soc a battery's state of charge: what it held, less what it discharged, plus what it charged
10
+
11
+ `carry` says which of these the sequence works out itself; the rest are read from each interval's tables as given.
12
+ A resource that is not dispatchable keeps the output it was given, because that is a schedule and not a result.
13
+ A carried output is held inside the new interval's sustained limits: a wind farm whose limit fell cannot start above it.
14
+
15
+ Carrying output assumes every resource did exactly what it was told. Real fleets drift from their instructions, so a
16
+ chained run departs from a market's own record even with perfect inputs; that gap is the cost of the assumption.
17
+
18
+ When a resource's starting output changes, each constraint's `flow` is moved with it, so the tables still describe
19
+ the same network: flow is the flow with every resource at its `output`.
20
+ """
21
+ import numpy as np
22
+ import pandas as pd
23
+
24
+ from opensced.core.features.network import resource_shift_factors
25
+ from opensced.core.model import clear
26
+ from opensced.core.result import DayResult
27
+ from opensced.core.rules import Rules
28
+
29
+ CARRY = ('output', 'ramp', 'soc')
30
+
31
+
32
+ def carry_forward(inputs, previous, rules, carry=CARRY, hours=None):
33
+ """`inputs` for the next interval, updated with what `previous` (the Result of the interval before) left behind.
34
+
35
+ hours: time between the two intervals. Default: rules.interval_hours. -> a new Inputs; `inputs` is not changed."""
36
+ bad = set(carry) - set(CARRY)
37
+ if bad:
38
+ raise ValueError(f'carry: unknown {sorted(bad)}. Choose from {CARRY}')
39
+ if previous is None or not previous.solved or not carry:
40
+ return inputs
41
+ hours = rules.interval_hours if hours is None else hours
42
+ res = inputs.resources.copy().reset_index(drop=True)
43
+ last = previous.dispatch
44
+ was = previous._inputs.resources.set_index('name')
45
+ was_disp = was['dispatchable'] if 'dispatchable' in was else pd.Series(True, index=was.index)
46
+ now_disp = res['dispatchable'].fillna(False).to_numpy(bool) if 'dispatchable' in res else np.ones(len(res), bool)
47
+ moved = now_disp & res['name'].isin(last.index).to_numpy() & res['name'].map(was_disp).fillna(False).to_numpy(bool)
48
+ old = pd.to_numeric(res['output'], errors='coerce').fillna(0.0).to_numpy(float) if 'output' in res else np.zeros(len(res))
49
+ low_, high_ = pd.to_numeric(res['low'], errors='coerce').to_numpy(float), pd.to_numeric(res['high'], errors='coerce').to_numpy(float)
50
+ new = np.where(moved, np.clip(res['name'].map(last).to_numpy(float), low_, np.maximum(high_, low_)), old) # inside this interval's limits
51
+ out = inputs.copy(resources=res, notes=dict(inputs.notes))
52
+ if 'output' in carry or 'ramp' in carry:
53
+ c = inputs.constraints
54
+ if c is not None and len(c) and inputs.shift_factors is not None: # keep flow = flow at the new outputs
55
+ sf = inputs.shift_factors if inputs.resource_nodes is None else resource_shift_factors(inputs.shift_factors, inputs.resource_nodes)
56
+ M = sf.reindex(index=c['name'].to_numpy(), columns=res['name'].to_numpy()).fillna(0.0).to_numpy(float)
57
+ out.constraints = c.assign(flow=pd.to_numeric(c['flow']).to_numpy(float) + M @ (new - old))
58
+ res['output'] = new
59
+ if 'ramp' in carry and 'ramp_up' in res and 'ramp_down' in res:
60
+ up, down = (pd.to_numeric(res[k], errors='coerce').to_numpy(float) for k in ('ramp_up', 'ramp_down'))
61
+ low, high = pd.to_numeric(res['low']).to_numpy(float), pd.to_numeric(res['high']).to_numpy(float)
62
+ m = rules.dispatch_minutes
63
+ ok = moved & np.isfinite(up) & np.isfinite(down)
64
+ hi, lo = np.minimum(new + up * m, high), np.maximum(new - down * m, low)
65
+ hi = np.maximum(hi, lo)
66
+ res['ramp_high'] = np.where(ok, hi, pd.to_numeric(res['ramp_high'], errors='coerce') if 'ramp_high' in res else high)
67
+ res['ramp_low'] = np.where(ok, lo, pd.to_numeric(res['ramp_low'], errors='coerce') if 'ramp_low' in res else low)
68
+ if 'soc' in carry and inputs.storage is not None and previous._inputs.storage is not None and len(inputs.storage):
69
+ st = inputs.storage.copy()
70
+ held = previous._inputs.storage.set_index('resource')['soc']
71
+ eff = previous._inputs.storage.set_index('resource')['efficiency'] if 'efficiency' in previous._inputs.storage else pd.Series(1.0, index=held.index)
72
+ d = st['resource'].map(last).to_numpy(float)
73
+ before = st['resource'].map(held).to_numpy(float)
74
+ e = st['resource'].map(eff).fillna(1.0).to_numpy(float)
75
+ after = before - np.where(d >= 0, d, d * e) * hours # charging stores efficiency x energy
76
+ ok = np.isfinite(after) & st['resource'].map(was_disp).fillna(False).to_numpy(bool)
77
+ after = np.clip(after, st['soc_min'].to_numpy(float), st['soc_max'].to_numpy(float))
78
+ st['soc'] = np.where(ok, after, st['soc'].to_numpy(float))
79
+ out.storage = st
80
+ out.notes['carried'] = tuple(carry)
81
+ return out
82
+
83
+
84
+ def clear_sequence(intervals, rules=None, carry=CARRY, progress=False):
85
+ """Clear intervals in order, carrying state from each into the next.
86
+
87
+ intervals Inputs in time order (or callables returning Inputs, to build each one only when it is needed)
88
+ rules one rulebook, or a function time -> rulebook
89
+ carry which of 'output', 'ramp', 'soc' to carry forward. () clears every interval as given
90
+ The time between intervals is taken from their `time` when both have one. An interval that does not solve breaks
91
+ the chain: the next one starts from its own tables. -> opensced.DayResult"""
92
+ out, previous = {}, None
93
+ items = list(intervals)
94
+ for k, item in enumerate(items):
95
+ x = item() if callable(item) else item
96
+ r = rules(x.time) if callable(rules) else (rules or Rules())
97
+ hours = None
98
+ if previous is not None and x.time is not None and previous.time is not None:
99
+ hours = (pd.Timestamp(x.time) - pd.Timestamp(previous.time)).total_seconds() / 3600
100
+ res = clear(carry_forward(x, previous, r, carry, hours), r)
101
+ out[x.time if x.time is not None else k] = res
102
+ previous = res if res.solved else None
103
+ if progress and (k + 1 == len(items) or (k + 1) % 24 == 0):
104
+ print(f' cleared {k + 1:,} of {len(items):,} intervals', flush=True)
105
+ return DayResult(out)