Coverage for ppedit/_dcline.py: 95.1%
126 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 17:40 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 17:40 +0000
1"""DC line model for the PYPOWER solver (private)
3`add_dclines(ppc)` registers PYPOWER `userfcn` callbacks that model the
4rows of `ppc["dcline"]` as in PYPOWER's `toggle_dcline`: each in-service DC
5line becomes a pair of dummy generators, one taking the flow out of the
6"from" bus and one injecting it at the "to" bus, linked in OPF by the loss
7constraint `PT = PF - (LOSS0 + LOSS1 * PF)`. Both terminal buses become PV
8(the REF bus stays REF), so the line also holds the terminal voltages at
9`VF` and `VT` and supplies reactive power within `QMINF..QMAXF` and
10`QMINT..QMAXT` (enforced by OPF only, as for generators).
12This is a reimplementation rather than a call to PYPOWER's `toggle_dcline`,
13which fails with current numpy (float array indices) and mishandles
14`dclinecost`, out-of-service lines in OPF results, and `gencost` with
15reactive power cost rows. pypower8 has no `toggle_dcline` or `add_userfcn`,
16so the OPF loss constraint (`_formulation`) and the callback registration
17(`_add_userfcn`) are ported here from PYPOWER 5.1.
19After the solve, `results["dcline"]` holds every row of the input
20`dcline` (external bus numbers) with `PF`, `PT`, `QF`, `QT`, `VF` and `VT`
21replaced by the solution for in-service lines, padded to 23 columns with
22the OPF multipliers (`MU_PMIN` .. `MU_QMAXT`, zero for power flow).
24References
25----------
27 - PYPOWER 5.1 `toggle_dcline` and `idx_dcline`
28 - R. D. Zimmerman, C. E. Murillo-Sanchez, MATPOWER User's Manual, section
29 "DC Transmission Lines"
30"""
32import numpy as np
33from scipy.sparse import hstack, csr_matrix, diags, identity
35from pypower8.idx_bus import BUS_TYPE, REF, PV # pylint: disable=no-name-in-module
36from pypower8.idx_gen import GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, \
37 GEN_STATUS, PMAX, PMIN, MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN # pylint: disable=no-name-in-module
38from pypower8.idx_cost import MODEL, NCOST, POLYNOMIAL # pylint: disable=no-name-in-module
40(F_BUS,T_BUS,BR_STATUS,PF,PT,QF,QT,VF,VT,PMIN_DC,PMAX_DC,QMINF,QMAXF,QMINT,
41 QMAXT,LOSS0,LOSS1,MU_PMIN_DC,MU_PMAX_DC,MU_QMINF,MU_QMAXF,MU_QMINT,MU_QMAXT) = range(23)
43NCOL = 23
44"""Columns of a solved `dcline` matrix (17 input columns and 6 multipliers)"""
46def _add_userfcn(ppc:dict,stage:str,fcn) -> dict:
47 """Append `fcn` to the `stage` callbacks of `ppc["userfcn"]` (PYPOWER's `add_userfcn`)"""
48 ppc.setdefault("userfcn",{}).setdefault(stage,[]).append({"fcn":fcn})
49 return ppc
51def _formulation(om,args): # pylint: disable=unused-argument
52 """OPF 'formulation' callback: the loss constraint of each in-service DC line
54 With dummy generator injections `Pgf = -PF` and `Pgt = PT`, the loss
55 relation `PT = PF - (LOSS0 + LOSS1 * PF)` becomes
56 `(1 - LOSS1) * Pgf + Pgt = -LOSS0` (as in PYPOWER's
57 `userfcn_dcline_formulation`). `ppc["dcline"]` holds only in-service
58 lines here, and the dummy generators are the last `2 * ndc` gens.
59 """
60 ppc = om.get_ppc()
61 dc = ppc["dcline"]
62 ndc = dc.shape[0]
63 ng = ppc["gen"].shape[0] - 2 * ndc
64 nl0 = -dc[:,LOSS0] / ppc["baseMVA"]
65 a_dc = hstack([csr_matrix((ndc,ng)),diags(1 - dc[:,LOSS1],0,shape=(ndc,ndc)),
66 identity(ndc)],format="csr")
67 return om.add_constraints("dcline",a_dc,nl0,nl0,["Pg"])
69def add_dclines(ppc:dict) -> dict:
70 """Register the DC line callbacks on a `ppc` dict that has a `dcline` matrix"""
71 ppc = _add_userfcn(ppc,"ext2int",_ext2int)
72 ppc = _add_userfcn(ppc,"formulation",_formulation)
73 ppc = _add_userfcn(ppc,"int2ext",_int2ext)
74 return ppc
76def flip_cost(row:np.ndarray) -> np.ndarray:
77 """Return a cost row of PF as a cost row of the "from" dummy generator (PG = -PF)
79 Polynomial coefficients of odd powers change sign; piecewise linear
80 points are mirrored about zero and reversed so MW values increase.
81 """
82 row = np.array(row,dtype=float)
83 n = int(row[NCOST])
84 if row[MODEL] == POLYNOMIAL: 84 ↛ 90line 84 didn't jump to line 90 because the condition on line 84 was always true
85 coef = row[NCOST+1:NCOST+1+n]
86 for j in range(n):
87 if (n-1-j) % 2:
88 coef[j] = -coef[j]
89 else:
90 pts = row[NCOST+1:NCOST+1+2*n].reshape(n,2)
91 pts = np.column_stack([-pts[::-1,0],pts[::-1,1]])
92 row[NCOST+1:NCOST+1+2*n] = pts.ravel()
93 return row
95def _pad(rows,width):
96 rows = np.atleast_2d(np.asarray(rows,dtype=float))
97 if rows.shape[1] < width:
98 rows = np.hstack([rows,np.zeros((rows.shape[0],width-rows.shape[1]))])
99 return rows
101def _ext2int(ppc,*_):
102 """Append the dummy generators (and their costs) in internal indexing"""
103 ext = _pad(ppc["dcline"],NCOL)
104 on = np.flatnonzero(ext[:,BR_STATUS] > 0)
105 ppc["order"]["ext"]["dcline"] = ext
106 ppc["order"]["ext"]["dcline_on"] = on
107 dc = ext[on,:].copy()
108 ndc = len(on)
109 e2i = ppc["order"]["bus"]["e2i"]
110 fbus = e2i[dc[:,F_BUS].astype(int)].astype(int)
111 tbus = e2i[dc[:,T_BUS].astype(int)].astype(int)
112 dc[:,F_BUS],dc[:,T_BUS] = fbus,tbus
113 # consistent starting flows for power flow
114 dc[:,PT] = dc[:,PF] - (dc[:,LOSS0] + dc[:,LOSS1]*dc[:,PF])
115 ppc["dcline"] = dc
117 gen = ppc["gen"]
118 ng = gen.shape[0]
119 fg = np.zeros((ndc,gen.shape[1]))
120 fg[:,MBASE] = 100
121 fg[:,GEN_STATUS] = 1
122 fg[:,PMIN],fg[:,PMAX] = -np.inf,np.inf
123 tg = fg.copy()
124 fg[:,GEN_BUS],tg[:,GEN_BUS] = fbus,tbus
125 fg[:,PG],tg[:,PG] = -dc[:,PF],dc[:,PT]
126 fg[:,QG],tg[:,QG] = dc[:,QF],dc[:,QT]
127 fg[:,VG],tg[:,VG] = dc[:,VF],dc[:,VT]
128 k = dc[:,PMIN_DC] >= 0
129 fg[k,PMAX] = -dc[k,PMIN_DC]
130 k = dc[:,PMAX_DC] >= 0
131 fg[k,PMIN] = -dc[k,PMAX_DC]
132 k = dc[:,PMIN_DC] < 0
133 tg[k,PMIN] = dc[k,PMIN_DC]
134 k = dc[:,PMAX_DC] < 0
135 tg[k,PMAX] = dc[k,PMAX_DC]
136 fg[:,QMIN],fg[:,QMAX] = dc[:,QMINF],dc[:,QMAXF]
137 tg[:,QMIN],tg[:,QMAX] = dc[:,QMINT],dc[:,QMAXT]
138 # keep dummy gens from being read as dispatchable loads (PMIN < 0 = PMAX)
139 for g in (fg,tg):
140 g[(g[:,PMIN] < 0) & (g[:,PMAX] == 0),PMAX] = -1e-6
142 bus = ppc["bus"]
143 ref = bus[:,BUS_TYPE] == REF
144 bus[fbus,BUS_TYPE] = PV
145 bus[tbus,BUS_TYPE] = PV
146 bus[ref,BUS_TYPE] = REF
147 ppc["gen"] = np.vstack([gen,fg,tg])
149 gencost = ppc.get("gencost")
150 if gencost is not None and len(gencost):
151 zero = np.array([[POLYNOMIAL,0,0,2,0,0]])
152 if "dclinecost" in ppc and len(ppc["dclinecost"]):
153 dcc = _pad(ppc["dclinecost"],6)[on,:]
154 fcost = np.vstack([flip_cost(r) for r in dcc]) if ndc else np.zeros((0,6))
155 else:
156 fcost = np.repeat(zero,ndc,axis=0)
157 tcost = np.repeat(zero,ndc,axis=0)
158 width = max(gencost.shape[1],fcost.shape[1] if ndc else 0,6)
159 gencost,fcost,tcost = _pad(gencost,width),_pad(fcost,width),_pad(tcost,width)
160 if gencost.shape[0] == 2*ng: # reactive power costs follow the real power costs 160 ↛ 161line 160 didn't jump to line 161 because the condition on line 160 was never true
161 qcost = np.repeat(_pad(zero,width),2*ndc,axis=0)
162 gencost = np.vstack([gencost[:ng],fcost,tcost,gencost[ng:],qcost])
163 else:
164 gencost = np.vstack([gencost,fcost,tcost])
165 ppc["gencost"] = gencost
166 return ppc
168def _int2ext(results,*_):
169 """Remove the dummy generators and put the DC line solution in `dcline`"""
170 order = results["order"]
171 ext = order["ext"]["dcline"].copy()
172 on = order["ext"]["dcline_on"]
173 ndc = len(on)
174 gen = results["gen"]
175 ng = gen.shape[0] - 2*ndc
176 fg,tg = gen[ng:ng+ndc,:],gen[ng+ndc:,:]
177 ext[on,PF] = -fg[:,PG]
178 ext[on,PT] = tg[:,PG]
179 ext[on,QF] = fg[:,QG]
180 ext[on,QT] = tg[:,QG]
181 ext[on,VF] = fg[:,VG]
182 ext[on,VT] = tg[:,VG]
183 off = np.setdiff1d(np.arange(ext.shape[0]),on)
184 ext[np.ix_(off,[PF,PT,QF,QT])] = 0
185 ext[:,MU_PMIN_DC:] = 0
186 if gen.shape[1] > MU_QMIN:
187 ext[on,MU_PMIN_DC] = fg[:,MU_PMAX] + tg[:,MU_PMIN]
188 ext[on,MU_PMAX_DC] = fg[:,MU_PMIN] + tg[:,MU_PMAX]
189 ext[on,MU_QMINF] = fg[:,MU_QMIN]
190 ext[on,MU_QMAXF] = fg[:,MU_QMAX]
191 ext[on,MU_QMINT] = tg[:,MU_QMIN]
192 ext[on,MU_QMAXT] = tg[:,MU_QMAX]
193 results["gen"] = gen[:ng,:] # int2ext restores gencost from its external copy
194 results["dcline"] = ext
195 return results