SolUtil 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.
Files changed (36) hide show
  1. SolUtil/__init__.py +5 -0
  2. SolUtil/_version.py +24 -0
  3. SolUtil/alternate_solver/__init__.py +1 -0
  4. SolUtil/alternate_solver/solver.py +127 -0
  5. SolUtil/energyflow/__init__.py +5 -0
  6. SolUtil/energyflow/dhs_fault_flow.py +719 -0
  7. SolUtil/energyflow/dhs_flow.py +395 -0
  8. SolUtil/energyflow/gas_flow.py +147 -0
  9. SolUtil/energyflow/hydraulic_mdl.py +232 -0
  10. SolUtil/energyflow/power_flow.py +338 -0
  11. SolUtil/energyflow/test/__init__.py +0 -0
  12. SolUtil/energyflow/test/test_dhs_fault_flow/case_heat_test.xlsx +0 -0
  13. SolUtil/energyflow/test/test_dhs_fault_flow/case_heat_test0.xlsx +0 -0
  14. SolUtil/energyflow/test/test_dhs_fault_flow/case_heat_test1.xlsx +0 -0
  15. SolUtil/energyflow/test/test_dhs_fault_flow.py +27 -0
  16. SolUtil/energyflow/test/test_dhs_flow/BarryIsland.xlsx +0 -0
  17. SolUtil/energyflow/test/test_dhs_flow.py +24 -0
  18. SolUtil/energyflow/test/test_gas_flow/belgium.xlsx +0 -0
  19. SolUtil/energyflow/test/test_gas_flow.py +20 -0
  20. SolUtil/energyflow/test/test_load_matpower/case9.m +70 -0
  21. SolUtil/energyflow/test/test_load_matpower.py +139 -0
  22. SolUtil/energyflow/test/test_power_flow/case9.xlsx +0 -0
  23. SolUtil/energyflow/test/test_power_flow.py +98 -0
  24. SolUtil/error_cal.py +9 -0
  25. SolUtil/profile.py +9 -0
  26. SolUtil/sysparser/__init__.py +3 -0
  27. SolUtil/sysparser/_array_utils.py +6 -0
  28. SolUtil/sysparser/dhs_function.py +209 -0
  29. SolUtil/sysparser/eps_function.py +395 -0
  30. SolUtil/sysparser/ngs_function.py +160 -0
  31. SolUtil/tf2ss.py +14 -0
  32. solutil-0.1.0.dist-info/METADATA +69 -0
  33. solutil-0.1.0.dist-info/RECORD +36 -0
  34. solutil-0.1.0.dist-info/WHEEL +5 -0
  35. solutil-0.1.0.dist-info/licenses/LICENSE +21 -0
  36. solutil-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,395 @@
1
+ import os
2
+ import warnings
3
+
4
+ import numpy as np
5
+ from numpy import exp, diagflat, abs
6
+ import pandas as pd
7
+ from scipy.sparse import csc_array, hstack, spdiags
8
+ from typing import Union, Dict
9
+ from Solverz.solvers.solution import aesol
10
+
11
+ from ._array_utils import to_writable_array
12
+
13
+ # MATPOWER bus types
14
+ PQ, PV, REF, NONE = 1, 2, 3, 4
15
+
16
+ # The columns of the ``bus``, ``branch`` and ``gen`` sheets of a SolUtil xlsx case
17
+ BUS_COLS = ['bus_i', 'type', 'Pd', 'Qd', 'Gs', 'Bs', 'area', 'Vm', 'Va',
18
+ 'baseKV', 'zone', 'Vmax', 'Vmin']
19
+ BRANCH_COLS = ['fbus', 'tbus', 'r', 'x', 'b', 'rateA', 'rateB', 'rateC',
20
+ 'ratio', 'angle', 'status', 'angmin', 'angmax']
21
+ GEN_COLS = ['bus', 'Pg', 'Qg', 'Qmax', 'Qmin', 'Vg', 'mBase', 'status', 'Pmax',
22
+ 'Pmin', 'Pc1', 'Pc2', 'Qc1min', 'Qc1max', 'Qc2min', 'Qc2max',
23
+ 'ramp_agc', 'ramp_10', 'ramp_30', 'ramp_q', 'apf']
24
+
25
+
26
+ def Vm_updater(Vm_pv, Vm_pq, Vm_slack):
27
+ return np.concatenate((Vm_pv, Vm_pq, Vm_slack))
28
+
29
+
30
+ def Va_updater(Va_pvpq, Va_slack):
31
+ return np.concatenate((Va_pvpq, Va_slack))
32
+
33
+
34
+ def S_updater(Ybus, Vm_pv, Vm_pq, Vm_slack, Va_pvpq, Va_slack):
35
+ Vm = Vm_updater(Vm_pv, Vm_pq, Vm_slack)
36
+ Va = Va_updater(Va_pvpq, Va_slack)
37
+ V = Vm * exp(1j * Va)
38
+ Ibus = Ybus @ V
39
+ S = V * Ibus.conj()
40
+ return np.column_stack((S.real, S.imag))
41
+
42
+
43
+ def dSbus_dV_updater(Ybus: Union[csc_array, np.ndarray], Vm_pv, Vm_pq, Vm_slack, Va_pvpq, Va_slack):
44
+ Vm = Vm_updater(Vm_pv, Vm_pq, Vm_slack)
45
+ Va = Va_updater(Va_pvpq, Va_slack)
46
+ n = len(Vm)
47
+ V = Vm * exp(1j * Va)
48
+ Ibus = Ybus @ V
49
+ if isinstance(Ybus, csc_array):
50
+ diagV = csc_array((V, (np.arange(0, n), np.arange(0, n))), shape=(n, n))
51
+ diagIbus = csc_array((Ibus, (np.arange(0, n), np.arange(0, n))), shape=(n, n))
52
+ diagVnorm = csc_array((V / abs(V), (np.arange(0, n), np.arange(0, n))), shape=(n, n))
53
+ else:
54
+ diagV = diagflat(V)
55
+ diagIbus = diagflat(Ibus)
56
+ diagVnorm = diagflat(V / abs(V))
57
+
58
+ dSbusdVa = 1j * diagV @ (diagIbus - Ybus @ diagV).conj()
59
+ dSbusdVm = diagV @ (Ybus @ diagVnorm).conj() + diagIbus.conj() @ diagVnorm
60
+
61
+ if isinstance(Ybus, csc_array):
62
+ return csc_array(hstack([dSbusdVa.real, dSbusdVm.real, dSbusdVa.imag, dSbusdVm.imag],
63
+ format='csc'))
64
+ else:
65
+ return np.hstack([dSbusdVa.real, dSbusdVm.real, dSbusdVa.imag, dSbusdVm.imag])
66
+
67
+
68
+ def makeYbus(baseMVA: np.ndarray, bus: pd.DataFrame, branch: pd.DataFrame):
69
+ nb = len(bus)
70
+ nl = len(branch)
71
+ stat = np.asarray(branch['status'])
72
+ r = np.asarray(branch['r'])
73
+ x = np.asarray(branch['x'])
74
+ b = np.asarray(branch['b'])
75
+ Ys = stat / (r + 1j * x)
76
+ Bc = stat * b
77
+ tap = np.ones((nl,))
78
+ ratio = np.asarray(branch['ratio'])
79
+ i = np.argwhere(ratio)
80
+ tap[i] = ratio[i]
81
+ angle = np.asarray(branch['angle'])
82
+ tap = tap * np.exp(1j * np.pi / 180 * angle)
83
+ Ytt = Ys + 1j * Bc / 2
84
+ Yff = Ytt / (tap * tap.conj())
85
+ Yft = -Ys / tap.conj()
86
+ Ytf = -Ys / tap
87
+
88
+ Ysh = (bus['Gs'] + 1j * bus['Bs']) / baseMVA
89
+ f = np.asarray(branch['fbus'])
90
+ t = np.asarray(branch['tbus'])
91
+ Cf = csc_array((np.ones((nl,)), (np.arange(0, nl), f)),
92
+ (nl, nb))
93
+ Ct = csc_array((np.ones((nl,)), (np.arange(0, nl), t)),
94
+ (nl, nb))
95
+ YffD = csc_array((Yff, (np.arange(0, nl), np.arange(0, nl))), (nl, nl))
96
+ YftD = csc_array((Yft, (np.arange(0, nl), np.arange(0, nl))), (nl, nl))
97
+ YtfD = csc_array((Ytf, (np.arange(0, nl), np.arange(0, nl))), (nl, nl))
98
+ YttD = csc_array((Ytt, (np.arange(0, nl), np.arange(0, nl))), (nl, nl))
99
+ Yf = YffD @ Cf + YftD @ Ct
100
+ Yt = YtfD @ Cf + YttD @ Ct
101
+ Ybus = Cf.T @ Yf + Ct.T @ Yt + csc_array((Ysh, (np.arange(0, nb), np.arange(0, nb))), (nb, nb))
102
+
103
+ return Ybus
104
+
105
+
106
+ def read_matpower(file_name):
107
+ """Read a MATPOWER case file into the tables of a SolUtil case.
108
+
109
+ The file is parsed by matpowercaseframes, and the case is then prepared as
110
+ MATPOWER ``runpf`` prepares it before its Newton iteration, so that
111
+ ``PowerFlow`` solves the problem that MATPOWER solves:
112
+
113
+ - generators out of service are dropped;
114
+ - the generators in service at one bus are summed into one row, whose
115
+ voltage setpoint is that of the first of them;
116
+ - a PV or reference bus without a generator in service becomes a PQ bus,
117
+ and if no reference bus remains, the first PV bus becomes the reference
118
+ bus, with a warning, as in MATPOWER's ``bustypes``;
119
+ - every bus with a generator in service starts at that generator's
120
+ voltage setpoint;
121
+ - the buses are numbered 0 to nb-1 in file order, and the bus columns of
122
+ the branch and gen tables are numbered accordingly.
123
+
124
+ Branches out of service stay in the branch table with status 0, as in the
125
+ xlsx format. Isolated buses, of type 4, are refused, because MATPOWER
126
+ removes them from the case and the xlsx format has no place for them.
127
+
128
+ Returns
129
+ -------
130
+ baseMVA : ndarray of shape (1,)
131
+ bus, branch, gen : pandas.DataFrame
132
+ With the columns of the ``bus``, ``branch`` and ``gen`` sheets of a
133
+ SolUtil xlsx case.
134
+ """
135
+ from matpowercaseframes import CaseFrames
136
+
137
+ cf = CaseFrames(os.fspath(file_name))
138
+ bus = cf.bus.reset_index(drop=True)
139
+ gen = cf.gen.reset_index(drop=True)
140
+ br = cf.branch.reset_index(drop=True)
141
+ base_mva = float(np.asarray(cf.baseMVA).ravel()[0])
142
+ nb = len(bus)
143
+
144
+ ext_ids = bus['BUS_I'].to_numpy().astype(np.int64)
145
+ if len(np.unique(ext_ids)) != nb:
146
+ raise ValueError(f'{file_name}: duplicate bus numbers')
147
+ btype = bus['BUS_TYPE'].to_numpy().astype(np.int64).copy()
148
+ if np.any(btype == NONE):
149
+ raise ValueError(f'{file_name}: {int(np.sum(btype == NONE))} isolated buses of type 4; '
150
+ f'remove them, with their branches and generators, before the power flow')
151
+ e2i = pd.Series(np.arange(nb), index=ext_ids)
152
+
153
+ def remap(col: pd.Series) -> np.ndarray:
154
+ ids = col.to_numpy().astype(np.int64)
155
+ unknown = ~np.isin(ids, ext_ids)
156
+ if unknown.any():
157
+ raise ValueError(f'{file_name}: {int(unknown.sum())} references to unknown bus numbers')
158
+ return e2i.loc[ids].to_numpy()
159
+
160
+ # generators: drop those out of service, sum those of one bus
161
+ on = gen['GEN_STATUS'].to_numpy() > 0
162
+ gen_on = gen.loc[on].reset_index(drop=True)
163
+ gbus = remap(gen_on['GEN_BUS'])
164
+ has_gen = np.zeros(nb, dtype=bool)
165
+ has_gen[gbus] = True
166
+
167
+ def bus_sum(col: str) -> np.ndarray:
168
+ acc = np.zeros(nb)
169
+ np.add.at(acc, gbus, gen_on[col].to_numpy(dtype=float))
170
+ return acc
171
+
172
+ first = ~pd.Series(gbus).duplicated().to_numpy()
173
+ Vg = np.full(nb, np.nan)
174
+ Vg[gbus[first]] = gen_on['VG'].to_numpy(dtype=float)[first]
175
+
176
+ # bus types, as MATPOWER bustypes()
177
+ demoted = ((btype == PV) | (btype == REF)) & ~has_gen
178
+ btype[demoted] = PQ
179
+ if not np.any(btype == REF):
180
+ pv = np.flatnonzero(btype == PV)
181
+ if pv.size == 0:
182
+ raise ValueError(f'{file_name}: no reference bus and no PV bus to make one')
183
+ btype[pv[0]] = REF
184
+ warnings.warn(f'{file_name}: no reference bus with a generator in service; '
185
+ f'bus {ext_ids[pv[0]]} is promoted to the reference bus', stacklevel=2)
186
+
187
+ # voltage start, as MATPOWER runpf
188
+ Vm = bus['VM'].to_numpy(dtype=float).copy()
189
+ Vm[has_gen] = Vg[has_gen]
190
+
191
+ bus_out = pd.DataFrame({
192
+ 'bus_i': np.arange(nb),
193
+ 'type': btype,
194
+ 'Pd': bus['PD'].to_numpy(dtype=float),
195
+ 'Qd': bus['QD'].to_numpy(dtype=float),
196
+ 'Gs': bus['GS'].to_numpy(dtype=float),
197
+ 'Bs': bus['BS'].to_numpy(dtype=float),
198
+ 'area': bus['BUS_AREA'].to_numpy(),
199
+ 'Vm': Vm,
200
+ 'Va': bus['VA'].to_numpy(dtype=float),
201
+ 'baseKV': bus['BASE_KV'].to_numpy(dtype=float),
202
+ 'zone': bus['ZONE'].to_numpy(),
203
+ 'Vmax': bus['VMAX'].to_numpy(dtype=float),
204
+ 'Vmin': bus['VMIN'].to_numpy(dtype=float),
205
+ })[BUS_COLS]
206
+
207
+ branch_out = pd.DataFrame({
208
+ 'fbus': remap(br['F_BUS']),
209
+ 'tbus': remap(br['T_BUS']),
210
+ 'r': br['BR_R'].to_numpy(dtype=float),
211
+ 'x': br['BR_X'].to_numpy(dtype=float),
212
+ 'b': br['BR_B'].to_numpy(dtype=float),
213
+ 'rateA': br['RATE_A'].to_numpy(dtype=float),
214
+ 'rateB': br['RATE_B'].to_numpy(dtype=float),
215
+ 'rateC': br['RATE_C'].to_numpy(dtype=float),
216
+ 'ratio': br['TAP'].to_numpy(dtype=float),
217
+ 'angle': br['SHIFT'].to_numpy(dtype=float),
218
+ 'status': br['BR_STATUS'].to_numpy().astype(np.int64),
219
+ 'angmin': br['ANGMIN'].to_numpy(dtype=float),
220
+ 'angmax': br['ANGMAX'].to_numpy(dtype=float),
221
+ })[BRANCH_COLS]
222
+
223
+ gen_bus = np.flatnonzero(has_gen)
224
+ gen_out = pd.DataFrame({
225
+ 'bus': gen_bus,
226
+ 'Pg': bus_sum('PG')[gen_bus],
227
+ 'Qg': bus_sum('QG')[gen_bus],
228
+ 'Qmax': bus_sum('QMAX')[gen_bus],
229
+ 'Qmin': bus_sum('QMIN')[gen_bus],
230
+ 'Vg': Vg[gen_bus],
231
+ 'mBase': np.full(gen_bus.size, base_mva),
232
+ 'status': np.ones(gen_bus.size, dtype=np.int64),
233
+ 'Pmax': bus_sum('PMAX')[gen_bus],
234
+ 'Pmin': bus_sum('PMIN')[gen_bus],
235
+ })
236
+ for col in GEN_COLS:
237
+ if col not in gen_out:
238
+ gen_out[col] = 0.0
239
+ gen_out = gen_out[GEN_COLS]
240
+
241
+ return np.array([base_mva]), bus_out, branch_out, gen_out
242
+
243
+
244
+ def load_mpc(file_name) -> Dict[str, Union[np.ndarray, csc_array]]:
245
+ """Read a power-flow case into the arrays that ``PowerFlow`` uses.
246
+
247
+ ``file_name`` is either a MATPOWER ``.m`` case file, which
248
+ :func:`read_matpower` reads and prepares as MATPOWER ``runpf`` does, or a
249
+ SolUtil ``.xlsx`` workbook with the sheets ``setting``, ``bus``,
250
+ ``branch`` and ``gen``, whose buses are numbered 0 to nb-1 in file order
251
+ and whose ``gen`` sheet holds one row per bus with a generator in
252
+ service. Both give the same arrays for the same case. The ``.m`` file is
253
+ the faster one to read, because openpyxl spends seconds parsing the XML
254
+ of a large workbook (rzyu45/SolUtil#5).
255
+ """
256
+ if isinstance(file_name, (str, os.PathLike)) and os.fspath(file_name).lower().endswith('.m'):
257
+ baseMVA, bus, branch, gen = read_matpower(file_name)
258
+ else:
259
+ df = pd.read_excel(file_name,
260
+ sheet_name=None,
261
+ engine='openpyxl',
262
+ index_col=None
263
+ )
264
+ bus = df['bus']
265
+ branch = df['branch']
266
+ gen = df['gen']
267
+ baseMVA = to_writable_array(df['setting']['baseMVA'])
268
+ return _mpc_from_tables(baseMVA, bus, branch, gen)
269
+
270
+
271
+ def _mpc_from_tables(baseMVA, bus: pd.DataFrame, branch: pd.DataFrame,
272
+ gen: pd.DataFrame) -> Dict[str, Union[np.ndarray, csc_array]]:
273
+ """The arrays of a case, from its base power and its bus, branch and gen
274
+ tables in the layout of the SolUtil xlsx format."""
275
+ mpc = dict()
276
+ pq = bus['type'] == 1
277
+ pv = bus['type'] == 2
278
+ slack = bus['type'] == 3
279
+ nb = len(bus)
280
+ mpc['baseMVA'] = baseMVA
281
+ idx_pq = to_writable_array(bus[pq]['bus_i'])
282
+ mpc['idx_pq'] = idx_pq
283
+ idx_pv = to_writable_array(bus[pv]['bus_i'])
284
+ mpc['idx_pv'] = idx_pv
285
+ idx_slack = to_writable_array(bus[slack]['bus_i'])
286
+ mpc['idx_slack'] = idx_slack
287
+ Vm = to_writable_array(bus['Vm'], dtype=float)
288
+ mpc['Vm'] = Vm
289
+ Va = np.deg2rad(to_writable_array(bus['Va'], dtype=float))
290
+ mpc['Va'] = Va
291
+ Pd = to_writable_array(bus['Pd'], dtype=float) / baseMVA
292
+ mpc['Pd'] = Pd
293
+ Qd = to_writable_array(bus['Qd'], dtype=float) / baseMVA
294
+ mpc['Qd'] = Qd
295
+ Pg = np.zeros((nb,), dtype=float)
296
+ idx_gen = to_writable_array(gen['bus'])
297
+ Pg[idx_gen] = gen['Pg'] / baseMVA
298
+ mpc['Pg'] = Pg
299
+ Qg = np.zeros((nb,), dtype=float)
300
+ Qg[idx_gen] = gen['Qg'] / baseMVA
301
+ mpc['Qg'] = Qg
302
+ mpc['Ybus'] = makeYbus(baseMVA, bus, branch)
303
+ mpc['nb'] = nb
304
+
305
+ return mpc
306
+
307
+
308
+ def bus_injections(Ybus: Union[csc_array, np.ndarray], Vm: np.ndarray, Va: np.ndarray):
309
+ """Net complex bus injections of a voltage profile, vectorized.
310
+
311
+ With ``V = Vm * exp(1j * Va)`` the injection is ``S = V * conj(Ybus @ V)``.
312
+ Returns ``(P, Q)`` in per unit. ``P[i]`` is the active power that bus ``i``
313
+ feeds into the network, so at a slack bus ``Pg[i] = P[i] + Pd[i]`` and at
314
+ a slack or PV bus ``Qg[i] = Q[i] + Qd[i]``.
315
+
316
+ This replaces the element-wise double loop over ``G[i, j]`` / ``B[i, j]``
317
+ that scaled as ``O(n_gen * n_bus)`` sparse scalar lookups and took hours on
318
+ networks with tens of thousands of buses. One sparse matrix-vector product
319
+ gives every bus at once.
320
+ """
321
+ V = Vm * np.exp(1j * Va)
322
+ S = V * np.conj(Ybus @ V)
323
+ return S.real, S.imag
324
+
325
+
326
+ def parse_data_post_pf(sys: dict, sol: aesol):
327
+ Vm = sys['Vm']
328
+ Va = sys['Va']
329
+ Ybus = sys["Ybus"]
330
+ ref = sys["idx_slack"].tolist()
331
+ pv = sys["idx_pv"].tolist()
332
+ pq = sys["idx_pq"].tolist()
333
+ Pg = sys["Pg"]
334
+ Qg = sys["Qg"]
335
+ Pd = sys["Pd"]
336
+ Qd = sys["Qd"]
337
+ Vm[pq] = sol.y['Vm']
338
+ Va[pv + pq] = sol.y['Va']
339
+
340
+ # update slack Pg and slack / PV Qg from the net bus injections
341
+ P, Q = bus_injections(Ybus, Vm, Va)
342
+ Pg[ref] = P[ref] + Pd[ref]
343
+ Qg[ref + pv] = Q[ref + pv] + Qd[ref + pv]
344
+
345
+ sys['Vm'] = Vm
346
+ sys['Va'] = Va
347
+ sys['Pg'] = Pg
348
+ sys['Qg'] = Qg
349
+ return sys
350
+
351
+
352
+ def plus_load_impedance(Y, Pd, Qd, Vm):
353
+ Yload = (Pd - 1j * Qd) / (Vm ** 2)
354
+ return Y + spdiags(Yload, 0, *Y.shape)
355
+
356
+
357
+ def load_mac(file_name) -> Dict[str, Union[np.ndarray, csc_array]]:
358
+ mpc = dict()
359
+ df = pd.read_excel(file_name,
360
+ sheet_name='machine',
361
+ engine='openpyxl',
362
+ index_col=None
363
+ )
364
+ mpc['ra'] = to_writable_array(df['ra'])
365
+ mpc['xd'] = to_writable_array(df['xd'])
366
+ mpc['xdp'] = to_writable_array(df['xdp'])
367
+ mpc['xq'] = to_writable_array(df['xq'])
368
+ mpc['xqp'] = to_writable_array(df['xqp'])
369
+ mpc['D'] = to_writable_array(df['D'])
370
+ mpc['Tj'] = to_writable_array(df['Tj'])
371
+ mpc['Tdp'] = to_writable_array(df['Tdp'])
372
+ mpc['Tqp'] = to_writable_array(df['Tqp'])
373
+ mpc['nm'] = mpc['Tqp'].shape[0]
374
+ mpc['bus'] = to_writable_array(df['bus'])
375
+ return mpc
376
+
377
+
378
+ def load_GT(file_name) -> Dict[str, Union[np.ndarray, csc_array]]:
379
+ mpc = dict()
380
+ df = pd.read_excel(file_name,
381
+ sheet_name='GT',
382
+ engine='openpyxl',
383
+ index_col=None
384
+ )
385
+ mpc['bus'] = to_writable_array(df['bus'])
386
+ mpc['node'] = to_writable_array(df['node'])
387
+
388
+ mpc['ngt'] = mpc['bus'].shape[0]
389
+
390
+ param_list = ['qmax', 'qmin', 'b', 'c', 'TFS', 'K1', 'K2', 'T1', 'T2', 'kp', 'ki', 'W', 'Y', 'Z', 'kNL', 'TCD',
391
+ 'Cop', 'A', 'B', 'C', 'D', 'E', 'TRbase', 'TG', 'Tref']
392
+ for param in param_list:
393
+ mpc[param] = to_writable_array(df[param])
394
+
395
+ return mpc
@@ -0,0 +1,160 @@
1
+ import matplotlib.pyplot as plt
2
+ import networkx as nx
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ from ._array_utils import to_writable_array
7
+
8
+
9
+ def visualize_ngs(G: nx.DiGraph):
10
+ virtual_pipe = [(u, v) for (u, v, d) in G.edges(data=True) if d["type"] == 0]
11
+ real_pipe = [(u, v) for (u, v, d) in G.edges(data=True) if d["type"] == 1]
12
+ s_node = [n for (n, data) in G.nodes(data=True) if data['type'] == 2]
13
+ ns_node = [n for (n, data) in G.nodes(data=True) if data['type'] == 1]
14
+
15
+ # Visualize the graph and the minimum spanning tree
16
+ pos = nx.planar_layout(G, scale=100)
17
+ # pos = nx.spring_layout(G)
18
+ nx.draw_networkx_nodes(G, pos, nodelist=s_node, node_color='#ff7f0e')
19
+ nx.draw_networkx_nodes(G, pos, nodelist=ns_node, node_color='#17becf')
20
+ nx.draw_networkx_labels(G, pos, font_family="sans-serif")
21
+ nx.draw_networkx_edges(G, pos, edgelist=virtual_pipe, edge_color='grey', alpha=0.5)
22
+ nx.draw_networkx_edges(G, pos, edgelist=real_pipe, edge_color='green')
23
+ nx.draw_networkx_edge_labels(
24
+ G, pos, edge_labels={(u, v): d["idx"] for u, v, d in G.edges(data=True)},
25
+ verticalalignment='top'
26
+ )
27
+ ax = plt.gca()
28
+ ax.margins(10)
29
+ plt.axis("off")
30
+ plt.show()
31
+
32
+
33
+ def load_ngs(filename):
34
+ df = pd.read_excel(filename,
35
+ sheet_name=None,
36
+ engine='openpyxl',
37
+ index_col=None
38
+ )
39
+ gc = dict()
40
+
41
+ type_node = to_writable_array(df['node']['type'])
42
+ type_pipe = to_writable_array(df['pipe']['type'])
43
+ idx_node = to_writable_array(df['node']['idx'])
44
+ idx_pipe = to_writable_array(df['pipe']['idx'])
45
+ idx_from = to_writable_array(df['pipe']['fnode'])
46
+ compress_fac = to_writable_array(df['pipe']['Compress factor'])
47
+ gc['compress_fac'] = compress_fac
48
+ idx_to = to_writable_array(df['pipe']['tnode'])
49
+ ns_node_cond = df['node']['type'] == 1
50
+ ns_node = to_writable_array(df['node'][ns_node_cond]['idx'])
51
+ gc['ns_node'] = ns_node
52
+ s_node_cond = df['node']['type'] != 1
53
+ s_node = to_writable_array(df['node'][s_node_cond]['idx'])
54
+ gc['s_node'] = s_node
55
+ slack_cond = df['node']['type'] == 3
56
+ slack_node = to_writable_array(df['node'][slack_cond]['idx'])
57
+ non_slack_source_node = np.setdiff1d(s_node, slack_node)
58
+ non_slack_node = np.setdiff1d(np.arange(len(df['node'])), slack_node)
59
+ gc['slack'] = slack_node
60
+ gc['n_slack'] = len(slack_node)
61
+ gc['non_slack_source'] = non_slack_source_node
62
+ gc['non_slack_node'] = non_slack_node
63
+ n_node = len(df['node'])
64
+ gc['n_node'] = n_node
65
+ gc['n_pipe'] = len(df['pipe'])
66
+ gc['fs'] = to_writable_array(df['node']['fs'], dtype=np.float64)
67
+ gc['fl'] = to_writable_array(df['node']['fl'], dtype=np.float64)
68
+ gc['delta'] = to_writable_array(df['pipe']['delta'])
69
+
70
+ # loop detection and conversion
71
+ if 'loop' in df:
72
+ pipe_in_loop = df['loop']['loop1'] == 1
73
+ pinloop = to_writable_array(df['loop'][pipe_in_loop]['idx'])
74
+ gc['pinloop'] = pinloop
75
+ else:
76
+ gc['pinloop'] = []
77
+
78
+ lam = to_writable_array(df['pipe']['Friction'])
79
+ D = to_writable_array(df['pipe']['Diameter'])
80
+ Piset = to_writable_array(df['node'][slack_cond]['p'])
81
+ L = to_writable_array(df['pipe']['Length'])
82
+ va = 340
83
+ S = np.pi * (D / 2) ** 2
84
+ C = lam * va ** 2 * L / D / S ** 2 / (1e6 ** 2)
85
+ gc['lam'] = lam
86
+ gc['D'] = D
87
+ gc['Piset'] = Piset
88
+ gc['L'] = L
89
+ gc['va'] = va
90
+ gc['S'] = S
91
+ gc['C'] = C
92
+
93
+ G = nx.DiGraph()
94
+
95
+ for i in range(len(idx_pipe)):
96
+ G.add_node(idx_from[i], type=type_node[idx_from[i]])
97
+ G.add_node(idx_to[i], type=type_node[idx_to[i]])
98
+ G.add_edge(idx_from[i],
99
+ idx_to[i],
100
+ idx=idx_pipe[i],
101
+ type=type_pipe[i],
102
+ c=C[i])
103
+
104
+ A = nx.incidence_matrix(G,
105
+ nodelist=idx_node,
106
+ edgelist=sorted(G.edges(data=True), key=lambda edge: edge[2].get('idx', 1)),
107
+ oriented=True)
108
+ gc['A'] = A
109
+ rpipe_from = []
110
+ rpipe_to = []
111
+ idx_rpipe = []
112
+ pipe_from = []
113
+ pipe_to = []
114
+ idx_pipe = []
115
+ for x, y, z in sorted(G.edges(data=True), key=lambda edge: edge[2].get('idx', 1)):
116
+ if z['type'] == 1:
117
+ rpipe_from.append(x)
118
+ rpipe_to.append(y)
119
+ idx_rpipe.append(z['idx'])
120
+ pipe_from.append(x)
121
+ pipe_to.append(y)
122
+ idx_pipe.append(z['idx'])
123
+
124
+ gc['rpipe_from'] = rpipe_from
125
+ gc['rpipe_to'] = rpipe_to
126
+ gc['idx_rpipe'] = idx_rpipe
127
+ gc['pipe_from'] = pipe_from
128
+ gc['pipe_to'] = pipe_to
129
+ gc['idx_pipe'] = idx_pipe
130
+ gc['G'] = G
131
+
132
+ return gc
133
+
134
+
135
+ def load_GT(filename):
136
+ df = pd.read_excel(filename,
137
+ sheet_name=None,
138
+ engine='openpyxl',
139
+ index_col=None
140
+ )
141
+ gtc = dict()
142
+
143
+ for column_name in df['GT'].columns:
144
+ gtc[column_name] = to_writable_array(df['GT'][column_name])
145
+
146
+ return gtc
147
+
148
+
149
+ def load_P2G(filename):
150
+ df = pd.read_excel(filename,
151
+ sheet_name=None,
152
+ engine='openpyxl',
153
+ index_col=None
154
+ )
155
+ p2gc = dict()
156
+
157
+ for column_name in df['P2G'].columns:
158
+ p2gc[column_name] = to_writable_array(df['P2G'][column_name])
159
+
160
+ return p2gc
SolUtil/tf2ss.py ADDED
@@ -0,0 +1,14 @@
1
+ from scipy.signal import tf2ss as tf2ss1
2
+
3
+
4
+ class ss:
5
+ def __init__(self, A, B, C, D):
6
+ self.A = A
7
+ self.B = B
8
+ self.C = C
9
+ self.D = D
10
+
11
+
12
+ def tf2ss(num, den):
13
+ ABCD = tf2ss1(num, den)
14
+ return ss(*[float(arg[0][0]) for arg in ABCD])
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: SolUtil
3
+ Version: 0.1.0
4
+ Summary: The util lib for Solverz
5
+ Author-email: Ruizhi Yu <rz.yu@foxmail.com>
6
+ Project-URL: Repository, https://github.com/rzyu45/SolUtil
7
+ Classifier: Programming Language :: Python :: 3.10
8
+ Classifier: Programming Language :: Python :: 3.11
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: matplotlib
16
+ Requires-Dist: matpowercaseframes>=2.1
17
+ Requires-Dist: networkx
18
+ Requires-Dist: numpy
19
+ Requires-Dist: openpyxl
20
+ Requires-Dist: pandas
21
+ Requires-Dist: scipy
22
+ Requires-Dist: Solverz>=0.11.0
23
+ Requires-Dist: tqdm
24
+ Requires-Dist: pyomo
25
+ Dynamic: license-file
26
+
27
+ # Solverz Utilities
28
+
29
+ This lib provides the simulation routines for integrated energy systems, including electric power, natural gas and heat.
30
+
31
+ A simple usage of this library can be
32
+
33
+ ```python
34
+ from SolUtil import GasFlow
35
+ gf = GasFlow('belgium.xlsx')
36
+ gf.run()
37
+ print(gf.Pi) # get the node Pressure results
38
+ print(gf.f) # get the pipe mass-flow results
39
+ ```
40
+
41
+ The required `.xlsx` data format can be found in SolUtil/energyflow/test directory for reference.
42
+
43
+ ## Installation
44
+
45
+ ```
46
+ pip install SolUtil
47
+ ```
48
+
49
+ ## Requirements
50
+
51
+ This package requires the `ipopt` optimization solver.
52
+
53
+ On `windows`, download the latest release [here](https://github.com/coin-or/Ipopt/releases). Then add the `bin`
54
+ directory to the system path. Make sure that you can call `ipopt` in your terminal.
55
+
56
+ On `macos`, use `brew install ipopt` to perform the installation.
57
+
58
+ ## MATPOWER case files
59
+
60
+ The power flow also reads a MATPOWER case file directly:
61
+
62
+ ```python
63
+ from SolUtil import PowerFlow
64
+ pf = PowerFlow('case118.m')
65
+ pf.run()
66
+ print(pf.Vm, pf.Va) # get the bus voltage magnitudes and angles
67
+ ```
68
+
69
+ A `.m` file is parsed with `matpowercaseframes` and prepared as MATPOWER `runpf` prepares it: generators out of service are dropped, the generators in service at one bus are summed, a PV or reference bus without a generator in service becomes a PQ bus, and every generator bus starts at its voltage setpoint. For large cases it is much faster to read than the `.xlsx` format.
@@ -0,0 +1,36 @@
1
+ SolUtil/__init__.py,sha256=MB9JsDcOEU4o5iDcr9f1HsgA6Evzjw4xAD4cXZKISAk,144
2
+ SolUtil/_version.py,sha256=GokMBWFC8EXVe0OBqeASWqoiGhL2JucgvcZko8ZVt6o,528
3
+ SolUtil/error_cal.py,sha256=ok1d7tCzGnXJPunBQ5J6snsSm6HtAdVMubonxiMtVoE,187
4
+ SolUtil/profile.py,sha256=8uDAufrkuuew1a0eYmGeSeZCF801fbGt_sdhZF-y5CE,180
5
+ SolUtil/tf2ss.py,sha256=Zc7HZ1vjawL56GKuQ2V4qygM69sp4KGsD_ceGRt5Qyo,267
6
+ SolUtil/alternate_solver/__init__.py,sha256=FB5M-NUImlTFDlVLvphhenkvp3-T2z9nVFTZ_mfRRzI,34
7
+ SolUtil/alternate_solver/solver.py,sha256=lmchhXJuNSCYl0gDeIPtwdvaEc6vQG2dKKSwOcw3OQY,3278
8
+ SolUtil/energyflow/__init__.py,sha256=5uM8D4WjGV2QJ3QEH5pDbVwYW3a8gNV-LKC7Ycc-jo0,160
9
+ SolUtil/energyflow/dhs_fault_flow.py,sha256=d82Dx7lM0ed6SsGzT7oaSDK3G8z4cMduEQH3EeXNs3M,28250
10
+ SolUtil/energyflow/dhs_flow.py,sha256=3DV8PDG0phdxUHF6HmzOZkFnjOXxRCHjoXRQ_Y8uUII,13553
11
+ SolUtil/energyflow/gas_flow.py,sha256=h3ewChuvmGna3Fx-q03zWmA3NRteW504f0AYNnAK8tc,4816
12
+ SolUtil/energyflow/hydraulic_mdl.py,sha256=7MjTF-UBY5T2MSfleXXvkk4y3CwSe5S3kgR8ZSr_cdw,8177
13
+ SolUtil/energyflow/power_flow.py,sha256=ovNAFeH2M72h4RpAeCDhUSZC4W25AGerchRHotgRUag,11783
14
+ SolUtil/energyflow/test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ SolUtil/energyflow/test/test_dhs_fault_flow.py,sha256=gPSvgChNSjzTTEkEn0aMxCyU1STLOtZeMdHAa43r2e4,611
16
+ SolUtil/energyflow/test/test_dhs_flow.py,sha256=kaKnGNy-vpTMqZ1joEEQp0b3hvHizUn8li8_Ak5GwUE,817
17
+ SolUtil/energyflow/test/test_gas_flow.py,sha256=OPxyLwAuK1_qixDBBnFiVqgtrm6-MExlNOa_VGqECno,536
18
+ SolUtil/energyflow/test/test_load_matpower.py,sha256=PVt6GVPaxzSYP9STJQdsMto2f_8EEtAHXKWIkAdaa-M,6769
19
+ SolUtil/energyflow/test/test_power_flow.py,sha256=kik8GrUGb-RGe0n9-xRRb4qjJlBPe-FsKSSQLcC8OVs,3344
20
+ SolUtil/energyflow/test/test_dhs_fault_flow/case_heat_test.xlsx,sha256=NAkgIrDXm-uDNgjMX1Xo8PGB9Cz9mXKR9mUXHfSRVOY,14271
21
+ SolUtil/energyflow/test/test_dhs_fault_flow/case_heat_test0.xlsx,sha256=5tUMfU9l75Qj_vArEQYbBLcSjG8HWBKdnkjRuWzvWzU,14138
22
+ SolUtil/energyflow/test/test_dhs_fault_flow/case_heat_test1.xlsx,sha256=5ydxflBBAuxH9wUptWlVEWfNww3UfzjK9DYeutWeeuo,14010
23
+ SolUtil/energyflow/test/test_dhs_flow/BarryIsland.xlsx,sha256=RIude1rW5jIjn6JPceOGM0a2HrNQVWbNvEHvtjCP5mI,23282
24
+ SolUtil/energyflow/test/test_gas_flow/belgium.xlsx,sha256=Q1cP-JI5gCGQJj4ffjzcizsUKU_yG3PHsst1dkNSDKc,144948
25
+ SolUtil/energyflow/test/test_load_matpower/case9.m,sha256=7lD8e_n2AZwPOjvJTSCXjMZnsI9pXccl0A29mYs1hiM,2235
26
+ SolUtil/energyflow/test/test_power_flow/case9.xlsx,sha256=Bfmltu1gRaSHUQYAlN4RufhHpwAIy_QTI9vgecUDiyI,45171
27
+ SolUtil/sysparser/__init__.py,sha256=p1A37fCVlHtVgSsteUCAGtbUw6i2vl9FvWLkF_k0GVw,104
28
+ SolUtil/sysparser/_array_utils.py,sha256=ADYarCHa74WjKs1oz060UlaabjEi5laxPx1o_hWWiMo,204
29
+ SolUtil/sysparser/dhs_function.py,sha256=X7M4-9d55H5l8L5MeomklDuGsI116B-BE7CGZbVfDGA,6773
30
+ SolUtil/sysparser/eps_function.py,sha256=pKiD9cSrjM2_8aF7WWthSIfDQECLmg66gA_klGaLbJM,14968
31
+ SolUtil/sysparser/ngs_function.py,sha256=DC0--wFF6PyXmCVSPfI5QMfoj5GUXzzLH1PAyP6V2oQ,5400
32
+ solutil-0.1.0.dist-info/licenses/LICENSE,sha256=Yh-XkLWiDjaz53f3vOT2Xxpkm7KVF22oYIbw3eCf1Lo,1086
33
+ solutil-0.1.0.dist-info/METADATA,sha256=KRG7GXClBpv_Gf8zFzFmvyJD6DG1uKSxK2k05Lac5nk,2238
34
+ solutil-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
35
+ solutil-0.1.0.dist-info/top_level.txt,sha256=eEsrSs6MYL3zKNiXBCQ47oqugI9lwq-S0-qrreeVTv0,8
36
+ solutil-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+