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,97 @@
1
+ """A market: its rulebooks and the adapter that turns its public files into input tables."""
2
+ import pandas as pd
3
+
4
+ from opensced.core.model import clear
5
+ from opensced.core.result import DayResult
6
+
7
+
8
+ class Market:
9
+ """Get one with opensced.market('ercot').
10
+
11
+ rules the market's rulebooks: .on(date), .get(name), .versions()
12
+ inputs(...) build one interval's Inputs from the market's published tables
13
+ read_day(folder) load a folder of downloaded files for one operating day
14
+ clear(inputs) clear one interval under the rulebook in force at inputs.time
15
+ clear_day(day, ...) clear every interval of a day"""
16
+
17
+ def __init__(self, name, title, rulebooks, adapter, interval_minutes):
18
+ self.name, self.title, self.rules, self.adapter, self.interval_minutes = name, title, rulebooks, adapter, interval_minutes
19
+ self.__doc__ = f'{title}\n\n{adapter.__doc__ or ""}'
20
+
21
+ def rules_for(self, when=None, rules=None):
22
+ if rules is not None:
23
+ return rules
24
+ return self.rules.latest if when is None else self.rules.on(when)
25
+
26
+ def inputs(self, *args, **kw):
27
+ return self.adapter.inputs(*args, **kw)
28
+
29
+ def read_day(self, folder):
30
+ return self.adapter.read_day(folder)
31
+
32
+ def clear(self, inputs, rules=None, check=True):
33
+ """Clear one interval. rules: defaults to the rulebook in force at inputs.time (the latest if it has none)."""
34
+ return clear(inputs, self.rules_for(inputs.time, rules), check=check)
35
+
36
+ def clear_day(self, day, shift_factors=None, resource_nodes=None, rules=None, times=None, progress=True, carry=(), **options):
37
+ """Clear every interval of a day.
38
+
39
+ day what read_day() returned, or any iterable of Inputs
40
+ shift_factors constraint x node, applied to every interval (a dict time -> table for one per interval)
41
+ resource_nodes resource -> node
42
+ rules one rulebook for every interval. Default: the rulebook in force at each interval's time
43
+ times clear only these intervals
44
+ carry () clears each interval from its own tables (a replay). ('output', 'ramp', 'soc') or any of
45
+ them starts each interval from where the one before ended (see opensced.clear_sequence)
46
+ options passed to the market's adapter, e.g. controllable_loads=False for ERCOT
47
+ -> opensced.DayResult"""
48
+ sf_at = lambda t: shift_factors[t] if isinstance(shift_factors, dict) else shift_factors
49
+ if hasattr(day, 'inputs') and hasattr(day, 'times'):
50
+ ts = list(day.times if times is None else times)
51
+ source = [(t, lambda t=t: day.inputs(t, shift_factors=sf_at(t), resource_nodes=resource_nodes, rules=self.rules_for(t, rules), **options))
52
+ for t in ts]
53
+ else:
54
+ def given(k, i):
55
+ i = i.copy(notes=dict(i.notes))
56
+ if shift_factors is not None:
57
+ i.shift_factors = sf_at(i.time if i.time is not None else k)
58
+ if resource_nodes is not None:
59
+ i.resource_nodes = resource_nodes
60
+ return i
61
+ source = [(i.time if i.time is not None else k, lambda k=k, i=i: given(k, i)) for k, i in enumerate(day)]
62
+ if carry:
63
+ from opensced.core.sequence import clear_sequence
64
+ return clear_sequence([make for _, make in source], lambda t: self.rules_for(t, rules), carry, progress)
65
+ out, n = {}, len(source)
66
+ for k, (t, make) in enumerate(source):
67
+ out[t] = clear(make(), self.rules_for(t, rules))
68
+ if progress and (k + 1 == n or (k + 1) % 24 == 0):
69
+ print(f' cleared {k + 1:,} of {n:,} intervals', flush=True)
70
+ return DayResult(out)
71
+
72
+ def __repr__(self):
73
+ return (f'Market {self.name!r}: {self.title}\n intervals of {self.interval_minutes} minutes\n'
74
+ f' {len(self.rules)} rulebook(s), latest {self.rules.latest.name!r}')
75
+
76
+
77
+ _REGISTRY = {}
78
+ PLANNED = ('pjm', 'miso', 'spp', 'caiso', 'nyiso')
79
+
80
+
81
+ def register(market):
82
+ _REGISTRY[market.name] = market
83
+
84
+
85
+ def list_markets():
86
+ """Names of the markets this version can clear."""
87
+ return sorted(_REGISTRY)
88
+
89
+
90
+ def market(name):
91
+ """A market by name: opensced.market('ercot')."""
92
+ key = str(name).lower()
93
+ if key in _REGISTRY:
94
+ return _REGISTRY[key]
95
+ if key in PLANNED:
96
+ raise NotImplementedError(f'{key.upper()} is planned but not built yet. Available now: {", ".join(list_markets())}')
97
+ raise KeyError(f'no market {name!r}. Available: {", ".join(list_markets())}')
opensced/core/model.py ADDED
@@ -0,0 +1,181 @@
1
+ """clear(): one interval's inputs and a rulebook in, prices and dispatch out.
2
+
3
+ The clearing is one linear program, solved with HiGHS. core/features holds its parts:
4
+
5
+ minimize energy offer cost + reserve offer cost - value of reserves bought on the demand curves
6
+ + shortage_price x shortfall - surplus_price x surplus + max_shadow_price x constraint violations
7
+ subject to the power balance, each resource's limits, reserve headroom, battery state of charge and the network
8
+
9
+ Prices are the program's duals: the system lambda from the power balance, each constraint's shadow price from its
10
+ row, each reserve product's clearing price from its demand row.
11
+ """
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+ from opensced.core import tables
16
+ from opensced.core.features import balance, mitigation, network, reserves, storage
17
+ from opensced.core.program import Program
18
+ from opensced.core.result import Result
19
+ from opensced.core.rules import Rules
20
+
21
+
22
+ def _col(r, name, default):
23
+ if name in r.columns:
24
+ return pd.to_numeric(r[name], errors='coerce').to_numpy(float)
25
+ return np.asarray(default, float) if not np.isscalar(default) else np.full(len(r), float(default))
26
+
27
+
28
+ def _prepare(inputs, rules, focus=None):
29
+ """the resources table as arrays: where each resource starts, how far it may move, what it may carry."""
30
+ r = inputs.resources.reset_index(drop=True)
31
+ names = r['name'].to_numpy()
32
+ low, high = _col(r, 'low', 0), _col(r, 'high', 0)
33
+ ramp_low, ramp_high = _col(r, 'ramp_low', low), _col(r, 'ramp_high', high)
34
+ ramp_low, ramp_high = np.where(np.isnan(ramp_low), low, ramp_low), np.where(np.isnan(ramp_high), high, ramp_high)
35
+ output = np.nan_to_num(_col(r, 'output', 0.0))
36
+ can = r['dispatchable'].fillna(False).to_numpy(bool) if 'dispatchable' in r else np.ones(len(r), bool)
37
+ lo, hi = (ramp_low, ramp_high) if rules.dispatch_limits == 'ramp' else (np.fmax(ramp_low, low), np.fmin(ramp_high, high))
38
+ disp = can & np.isfinite(lo) & np.isfinite(hi) & (hi >= lo)
39
+ lo, hi = np.where(disp, lo, output), np.where(disp, hi, output)
40
+ S = dict(n=len(r), table=r, names=names, at={n: i for i, n in enumerate(names)}, disp=disp, lo=lo, hi=hi, low=low, high=high,
41
+ ramp_low=ramp_low, ramp_high=ramp_high, output=output)
42
+ S['B'] = balance.blocks(S, inputs.energy_offers, rules, {S['at'][k]: v for k, v in focus.items() if k in S['at']} if focus else None)
43
+ S['blocks_of'] = pd.Series(np.arange(len(S['B']))).groupby(S['B'].res.to_numpy()).apply(np.array).to_dict()
44
+ return S
45
+
46
+
47
+ def _storage_state(S, inputs, efficiency=1.0):
48
+ n = S['n']
49
+ S['esr'], S['head'], S['room'], S['eff'] = np.zeros(n, bool), np.full(n, np.inf), np.full(n, np.inf), np.full(n, float(efficiency))
50
+ st = inputs.storage
51
+ if st is None or not len(st):
52
+ return
53
+ i = st['resource'].map(S['at'])
54
+ ok = i.notna().to_numpy()
55
+ i = i[ok].astype(int).to_numpy()
56
+ soc, mn, mx = (pd.to_numeric(st[c], errors='coerce').to_numpy(float)[ok] for c in ('soc', 'soc_min', 'soc_max'))
57
+ good = np.isfinite(soc) & S['disp'][i]
58
+ S['esr'][i[good]] = True
59
+ S['head'][i[good]], S['room'][i[good]] = (soc - mn)[good], (mx - soc)[good]
60
+ if 'efficiency' in st:
61
+ eff = pd.to_numeric(st['efficiency'], errors='coerce').to_numpy(float)[ok]
62
+ S['eff'][i[good]] = np.where(np.isfinite(eff) & (eff > 0), eff, float(efficiency))[good]
63
+
64
+
65
+ def clear(inputs, rules=None, check=True):
66
+ """Clear one interval.
67
+
68
+ result = clear(inputs) # default rulebook: energy and network
69
+ result = clear(inputs, rules=my_rules)
70
+
71
+ inputs an opensced.Inputs (see opensced.schema())
72
+ rules an opensced.Rules. Markets supply dated ones: opensced.market('ercot').rules.on('2026-08-12')
73
+ check validate the tables first. Turn off inside a loop once the inputs are known to be clean.
74
+
75
+ Reserves are cleared when the rulebook has products and inputs.reserve_demand is given. Constraints are enforced
76
+ when inputs.constraints is given. -> opensced.Result"""
77
+ rules = rules or Rules()
78
+ if check:
79
+ tables.validate(inputs, rules.product_names or None, rules.demand_names or None)
80
+ if not rules.two_step or inputs.mitigated:
81
+ return _clear_once(inputs, rules)
82
+ first = _clear_once(mitigation.competitive_only(inputs), rules) # step 1: reference prices
83
+ if not first.solved:
84
+ return first
85
+ first._inputs = inputs # price resources with the full shift-factor table
86
+ reference = first.resource_prices().rename('reference_price')
87
+ second = _clear_once(inputs.copy(energy_offers=mitigation.mitigate(inputs, reference, rules), mitigated=True), rules)
88
+ second.reference_prices, second.step1 = reference, first
89
+ return second
90
+
91
+
92
+ def _clear_once(inputs, rules):
93
+ """the program for the offers as given: solved, then solved again with each resource's curve cut finer around
94
+ where it landed (rules.block_refine passes), so sloped offer curves are priced where they are actually met."""
95
+ result, focus, step = _solve(inputs, rules, None), {}, rules.block_mw
96
+ for _ in range(0 if rules.offer_curves == 'exact' else rules.block_refine):
97
+ if not result.solved:
98
+ break
99
+ fine = step / rules.block_refine_factor
100
+ lo, hi = result._range # a resource at a limit is cut finer too: where its
101
+ for name, mw in result.dispatch[hi - lo > rules.tolerance_mw].items(): # curve slopes away from the limit, the first
102
+ focus.setdefault(name, []).append((float(mw), step, fine)) # coarse step may be all that kept it there
103
+ result, step = _solve(inputs, rules, focus), fine
104
+ return result
105
+
106
+
107
+ def _solve(inputs, rules, focus):
108
+ """one solve of the program."""
109
+ S = _prepare(inputs, rules, focus)
110
+ with_reserves = rules.has('reserves') and bool(rules.products) and inputs.reserve_demand is not None
111
+ S['cons'], S['sf'] = network.matrix(S, inputs, rules.shift_factor_cutoff) if rules.has('network') else (None, None)
112
+ P = Program()
113
+ balance.variables(P, S, rules)
114
+ if with_reserves:
115
+ S['cap'], S['OB'] = reserves.limits(S, inputs, rules)
116
+ _storage_state(S, inputs, rules.storage_charge_efficiency)
117
+ if not rules.has('storage'):
118
+ S['esr'][:] = False
119
+ reserves.award_variables(P, S, rules)
120
+ storage.variables(P, S, rules)
121
+ reserves.offer_variables(P, S, rules)
122
+ reserves.demand_variables(P, S, inputs, rules)
123
+ if S['cons'] is not None:
124
+ network.variables(P, S)
125
+ if with_reserves:
126
+ reserves.resource_rows(P, S, rules)
127
+ storage.rows(P, S, rules)
128
+ reserves.offer_rows(P, S)
129
+ reserves.demand_rows(P, S, inputs, rules)
130
+ if S['cons'] is not None:
131
+ network.rows(P, S)
132
+ eq, rhs = balance.equation(P, S, float(inputs.demand))
133
+ sol = P.solve(eq, rhs, rules.solver, rules.solver_options)
134
+ passes = 0
135
+ while with_reserves and rules.storage_charge_offset and sol.status == 0 and passes < rules.storage_passes and S['esr'].any():
136
+ lower, upper = storage.settle_direction(P, S, sol.x, rules) # one battery, one direction
137
+ if not lower and not upper:
138
+ break
139
+ P.pin(lower, upper)
140
+ again = P.solve(eq, rhs, rules.solver, rules.solver_options)
141
+ if again.status != 0:
142
+ break
143
+ sol, passes = again, passes + 1
144
+ cnames = pd.Index(S['cons']['name'].to_numpy() if S['cons'] is not None else [], name='constraint')
145
+ if sol.status != 0:
146
+ return Result(solved=False, status=str(sol.message), system_lambda=float('nan'), rules=rules, time=inputs.time,
147
+ shadow_prices=pd.Series(np.nan, index=cnames, name='shadow_price'), _inputs=inputs)
148
+ nb = len(S['B'])
149
+ p = S['lo'].copy()
150
+ np.add.at(p, S['B'].res.to_numpy(), sol.x[:nb])
151
+ duals = sol.ineqlin.marginals if P.rows else np.zeros(0)
152
+ slack = P.start('slack')
153
+ awards, prices, bought = None, None, None
154
+ if with_reserves:
155
+ cols = {}
156
+ for name in rules.product_names:
157
+ st, ln = P.var[f'r_{name}']
158
+ a = np.zeros(S['n'])
159
+ a[S['rv'][name]] = sol.x[st:st + ln]
160
+ cols[name] = a
161
+ awards = pd.DataFrame(cols, index=pd.Index(S['names'], name='resource'))
162
+ awards = awards[(awards.abs() > 1e-9).any(axis=1)]
163
+ prices = pd.Series({name: float(-duals[S['reserve_rows'][name]]) for name in rules.demand_names}, name='price')
164
+ bought = pd.Series({name: float(sol.x[P.var[f'q_{name}'][0]:sum(P.var[f'q_{name}'])].sum()) for name in rules.demand_names}, name='mw')
165
+ violation = None
166
+ if S['cons'] is not None:
167
+ v = P.start('violation')
168
+ violation = pd.Series(sol.x[v:v + len(cnames)], index=cnames, name='violation_mw')
169
+ lam = float(sol.eqlin.marginals[0])
170
+ cap = rules.cap
171
+ uncapped = {'system_lambda': lam, 'reserve_prices': prices}
172
+ if cap is not None: # prices are capped after the solve
173
+ prices = None if prices is None else prices.clip(upper=cap)
174
+ out = Result(
175
+ solved=True, status='ok', system_lambda=lam if cap is None else min(lam, cap), uncapped=uncapped, rules=rules, time=inputs.time,
176
+ shadow_prices=pd.Series([float(-duals[k]) for k in S.get('net_rows', [])], index=cnames, name='shadow_price', dtype=float),
177
+ dispatch=pd.Series(p, index=pd.Index(S['names'], name='resource'), name='mw'),
178
+ reserve_awards=awards, reserve_prices=prices, reserve_bought=bought, violations=violation,
179
+ shortfall=float(sol.x[slack]), surplus=float(sol.x[slack + 1]), cost=float(sol.fun), _inputs=inputs)
180
+ out._range = (S['lo'], S['hi'])
181
+ return out
@@ -0,0 +1,107 @@
1
+ """A small program builder: named groups of variables, rows of `sum(coef x var) <= rhs`, one equality.
2
+
3
+ Linear by default, solved with scipy's HiGHS. A group may carry a quadratic cost (cost x + 1/2 quad x^2 per variable);
4
+ the program is then a convex quadratic program and is solved with HiGHS through `highspy`."""
5
+ import numpy as np
6
+ from scipy.optimize import linprog
7
+ from scipy.sparse import coo_matrix
8
+
9
+
10
+ class Program:
11
+ def __init__(self):
12
+ self.var = {} # group name -> (start, length)
13
+ self._cost, self._ub, self._quad = [], [], []
14
+ self.n = 0
15
+ self._r, self._c, self._v, self._b = [], [], [], []
16
+ self.rows = 0
17
+ self._lower, self._upper = {}, {} # bounds set after building: variable index -> value
18
+
19
+ def add(self, name, cost, upper, quad=None):
20
+ """A group of variables, each in [0, upper], costing cost x + 1/2 quad x^2. -> index of the first one."""
21
+ cost, upper = np.asarray(cost, float), np.asarray(upper, float)
22
+ self.var[name] = (self.n, len(cost))
23
+ self._cost.append(cost)
24
+ self._ub.append(upper)
25
+ self._quad.append(np.zeros(len(cost)) if quad is None else np.asarray(quad, float))
26
+ self.n += len(cost)
27
+ return self.var[name][0]
28
+
29
+ def start(self, name):
30
+ return self.var[name][0]
31
+
32
+ def row(self, cols, vals, rhs):
33
+ """sum(vals x variables[cols]) <= rhs. -> the row's index (its dual is read back by that index)."""
34
+ self._r.extend([self.rows] * len(cols))
35
+ self._c.extend(cols)
36
+ self._v.extend(vals)
37
+ self._b.append(rhs)
38
+ self.rows += 1
39
+ return self.rows - 1
40
+
41
+ def pin(self, lower=None, upper=None):
42
+ """Tighten bounds on single variables: {index: new lower bound}, {index: new upper bound}."""
43
+ self._lower.update(lower or {})
44
+ self._upper.update(upper or {})
45
+
46
+ def solve(self, eq, eq_rhs, method='highs', options=None):
47
+ """Minimize cost subject to the rows and `eq @ x == eq_rhs`. -> a result with x, fun, status, message,
48
+ eqlin.marginals and ineqlin.marginals (scipy's, or the same shape from the quadratic solve)."""
49
+ c, ub = np.concatenate(self._cost), np.concatenate(self._ub)
50
+ quad = np.concatenate(self._quad)
51
+ lb = np.zeros(self.n)
52
+ for k, v in self._upper.items():
53
+ ub[k] = v
54
+ for k, v in self._lower.items():
55
+ lb[k] = v
56
+ A = coo_matrix((self._v, (self._r, self._c)), shape=(self.rows, self.n)).tocsr() if self.rows else None
57
+ if (quad > 0).any():
58
+ return _quadratic(c, quad, A, np.array(self._b), eq, eq_rhs, lb, ub)
59
+ return linprog(c, A_ub=A, b_ub=np.array(self._b) if self.rows else None, A_eq=eq[None, :], b_eq=[eq_rhs],
60
+ bounds=list(zip(lb, ub)), method=method, options=options or None)
61
+
62
+
63
+ class _Marginals:
64
+ def __init__(self, marginals):
65
+ self.marginals = marginals
66
+
67
+
68
+ class _Solution:
69
+ def __init__(self, x, fun, status, message, eq_dual, row_duals):
70
+ self.x, self.fun, self.status, self.message = x, fun, status, message
71
+ self.eqlin, self.ineqlin = _Marginals(np.array([eq_dual])), _Marginals(row_duals)
72
+
73
+
74
+ def _quadratic(c, quad, A, b, eq, eq_rhs, lb, ub):
75
+ """min c x + 1/2 sum(quad x^2) s.t. A x <= b, eq x == eq_rhs, lb <= x <= ub, with HiGHS."""
76
+ try:
77
+ import highspy
78
+ except ImportError as e: # pragma: no cover
79
+ raise ImportError('sloped offer curves solved exactly (rules.offer_curves="exact") need the highspy package: '
80
+ 'pip install highspy. Or use rules.offer_curves="steps"') from e
81
+ from scipy.sparse import csc_matrix, vstack
82
+ n, m = len(c), (A.shape[0] if A is not None else 0)
83
+ M = (vstack([A, csc_matrix(eq[None, :])]) if A is not None else csc_matrix(eq[None, :])).tocsc()
84
+ inf = highspy.kHighsInf
85
+ lp = highspy.HighsLp()
86
+ lp.num_col_, lp.num_row_ = n, m + 1
87
+ lp.col_cost_ = c
88
+ lp.col_lower_, lp.col_upper_ = lb, np.where(np.isfinite(ub), ub, inf)
89
+ lp.row_lower_ = np.r_[np.full(m, -inf), eq_rhs]
90
+ lp.row_upper_ = np.r_[np.where(np.isfinite(b), b, inf) if m else np.zeros(0), eq_rhs]
91
+ lp.a_matrix_.format_ = highspy.MatrixFormat.kColwise
92
+ lp.a_matrix_.start_, lp.a_matrix_.index_, lp.a_matrix_.value_ = M.indptr, M.indices, M.data
93
+ h = highspy.Highs()
94
+ h.silent()
95
+ h.passModel(lp)
96
+ hess = highspy.HighsHessian()
97
+ hess.dim_, hess.format_ = n, highspy.HessianFormat.kTriangular
98
+ on = quad > 0
99
+ hess.start_ = np.r_[0, np.cumsum(on)].astype(np.int32)
100
+ hess.index_, hess.value_ = np.where(on)[0].astype(np.int32), quad[on]
101
+ h.passHessian(hess)
102
+ h.run()
103
+ ok = h.getModelStatus() == highspy.HighsModelStatus.kOptimal
104
+ sol = h.getSolution()
105
+ x, duals = np.array(sol.col_value), np.array(sol.row_dual)
106
+ return _Solution(x, float(h.getInfo().objective_function_value), 0 if ok else 1, h.modelStatusToString(h.getModelStatus()),
107
+ duals[m] if len(duals) > m else np.nan, duals[:m])
@@ -0,0 +1,159 @@
1
+ """What a clearing returns."""
2
+ from dataclasses import dataclass, field
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+
7
+
8
+ @dataclass
9
+ class Result:
10
+ """One interval's clearing.
11
+
12
+ system_lambda $/MWh, the energy price every node shares before congestion
13
+ shadow_prices $/MWh per constraint, >= 0 (0 when the constraint does not bind)
14
+ dispatch MW per resource
15
+ reserve_awards MW, resources x products (only resources awarded something); None if reserves were not cleared
16
+ reserve_prices $/MW per hour per demand curve; None if reserves were not cleared
17
+ reserve_bought MW bought on each demand curve (the sum of the awards of the products serving it)
18
+ violations MW by which each constraint is exceeded (priced at its max_shadow_price)
19
+ shortfall MW of demand left unserved (lambda is then the shortage price); surplus is the reverse
20
+ solved False if the program had no solution; `status` says why
21
+ uncapped the system lambda and reserve prices before the rulebook's price cap was applied
22
+ reference_prices each resource's price in step 1 of a two-step clearing; step1 is that step's Result
23
+
24
+ node_prices() price at every node
25
+ summary() a few lines to print"""
26
+ solved: bool
27
+ status: str
28
+ system_lambda: float
29
+ shadow_prices: pd.Series
30
+ rules: object = None
31
+ time: object = None
32
+ dispatch: pd.Series | None = None
33
+ reserve_awards: pd.DataFrame | None = None
34
+ reserve_prices: pd.Series | None = None
35
+ reserve_bought: pd.Series | None = None
36
+ violations: pd.Series | None = None
37
+ shortfall: float = 0.0
38
+ surplus: float = 0.0
39
+ cost: float = float('nan')
40
+ uncapped: dict = field(default_factory=dict, repr=False)
41
+ reference_prices: pd.Series | None = None
42
+ step1: object = field(default=None, repr=False)
43
+ _inputs: object = field(default=None, repr=False)
44
+
45
+ def node_prices(self, shift_factors=None):
46
+ """Price at every node: lambda - sum(shift factor x shadow price).
47
+
48
+ shift_factors: constraint x node. Defaults to the shift factors the interval was cleared with, so the nodes
49
+ are the columns of inputs.shift_factors. Pass a wider table to price nodes that hold no resource (hubs, load
50
+ zones)."""
51
+ sf = shift_factors if shift_factors is not None else getattr(self._inputs, 'shift_factors', None)
52
+ if sf is None:
53
+ raise ValueError('node_prices needs shift factors: none were given to the clearing. '
54
+ 'With no network every node clears at result.system_lambda')
55
+ mu = self.shadow_prices
56
+ S = sf.reindex(mu.index).fillna(0.0)
57
+ lam = self.uncapped.get('system_lambda', self.system_lambda)
58
+ p = lam - S.to_numpy(float).T @ mu.to_numpy(float)
59
+ cap = getattr(self.rules, 'cap', None)
60
+ if cap is not None: # a price above the cap comes down by what the
61
+ p = np.where(p > cap, np.maximum(cap, p - max(lam - cap, 0.0)), p) # lambda was cut, but not below the cap
62
+ return pd.Series(p, index=S.columns, name='price')
63
+
64
+ def resource_prices(self):
65
+ """Price each resource is paid: the price at its node (lambda where it has no shift factors)."""
66
+ from opensced.core.features.network import resource_shift_factors
67
+ i = self._inputs
68
+ names = i.resources['name'].to_numpy()
69
+ if i.shift_factors is None or not len(self.shadow_prices):
70
+ return pd.Series(self.system_lambda, index=pd.Index(names, name='resource'), name='price')
71
+ sf = i.shift_factors if i.resource_nodes is None else resource_shift_factors(i.shift_factors, i.resource_nodes)
72
+ return self.node_prices(sf).reindex(names).fillna(self.system_lambda).rename_axis('resource')
73
+
74
+ @property
75
+ def binding(self):
76
+ """The constraints with a shadow price above zero."""
77
+ return self.shadow_prices[self.shadow_prices > 1e-6].sort_values(ascending=False)
78
+
79
+ def summary(self):
80
+ if not self.solved:
81
+ return f'Clearing{self._when()}: not solved ({self.status})'
82
+ out = [f'Clearing{self._when()}' + (f' [rules: {self.rules.name}]' if self.rules is not None else ''),
83
+ f' system lambda ${self.system_lambda:,.2f} /MWh',
84
+ f' dispatched {self.dispatch.sum():,.1f} MW across {int((self.dispatch.abs() > 1e-6).sum()):,} resources']
85
+ if self.shortfall > 1e-6:
86
+ out.append(f' SHORTFALL {self.shortfall:,.1f} MW unserved: lambda is the shortage price')
87
+ if self.surplus > 1e-6:
88
+ out.append(f' SURPLUS {self.surplus:,.1f} MW that could not be backed down')
89
+ if len(self.shadow_prices):
90
+ b = self.binding
91
+ out.append(f' constraints {len(b):,} of {len(self.shadow_prices):,} binding'
92
+ + (f'; highest ${b.iloc[0]:,.2f} on {b.index[0]}' if len(b) else ''))
93
+ sf = getattr(self._inputs, 'shift_factors', None)
94
+ if sf is not None and len(b):
95
+ p = self.node_prices()
96
+ out.append(f' node prices ${p.min():,.2f} to ${p.max():,.2f} over {len(p):,} nodes')
97
+ if self.reserve_prices is not None:
98
+ for name, price in self.reserve_prices.items():
99
+ out.append(f' {name:<17} {self.reserve_bought[name]:,.0f} MW at ${price:,.2f}')
100
+ return '\n'.join(out)
101
+
102
+ def _when(self):
103
+ return f' {self.time}' if self.time is not None else ''
104
+
105
+ def __repr__(self):
106
+ return self.summary()
107
+
108
+
109
+ @dataclass
110
+ class DayResult:
111
+ """Many intervals cleared one after another. Each attribute is a table with one row per interval.
112
+
113
+ system_lambda Series: time -> $/MWh
114
+ node_prices DataFrame: time x node
115
+ shadow_prices DataFrame: time x constraint (NaN where the constraint was not in that interval)
116
+ reserve_prices DataFrame: time x product
117
+ reserve_awards DataFrame: time x product, total MW
118
+ dispatch DataFrame: time x resource
119
+ results the individual Result objects, by time"""
120
+ results: dict
121
+
122
+ def _series(self, f):
123
+ return {t: f(r) for t, r in self.results.items() if r.solved}
124
+
125
+ @property
126
+ def system_lambda(self):
127
+ return pd.Series({t: r.system_lambda for t, r in self.results.items()}, name='system_lambda').rename_axis('time')
128
+
129
+ @property
130
+ def node_prices(self):
131
+ return pd.DataFrame(self._series(lambda r: r.node_prices())).T.rename_axis('time')
132
+
133
+ @property
134
+ def shadow_prices(self):
135
+ return pd.DataFrame(self._series(lambda r: r.shadow_prices)).T.rename_axis('time')
136
+
137
+ @property
138
+ def reserve_prices(self):
139
+ return pd.DataFrame(self._series(lambda r: r.reserve_prices)).T.rename_axis('time')
140
+
141
+ @property
142
+ def reserve_awards(self):
143
+ return pd.DataFrame(self._series(lambda r: r.reserve_awards.sum())).T.rename_axis('time')
144
+
145
+ @property
146
+ def dispatch(self):
147
+ return pd.DataFrame(self._series(lambda r: r.dispatch)).T.rename_axis('time')
148
+
149
+ @property
150
+ def unsolved(self):
151
+ return [t for t, r in self.results.items() if not r.solved]
152
+
153
+ def __len__(self):
154
+ return len(self.results)
155
+
156
+ def __repr__(self):
157
+ lam = self.system_lambda
158
+ return (f'DayResult: {len(self):,} intervals, {len(self) - len(self.unsolved):,} solved\n'
159
+ f' system lambda mean ${np.nanmean(lam):,.2f}, min ${np.nanmin(lam):,.2f}, max ${np.nanmax(lam):,.2f}')