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,70 @@
1
+ function mpc = case9
2
+ %CASE9 Power flow data for 9 bus, 3 generator case.
3
+ % Please see CASEFORMAT for details on the case file format.
4
+ %
5
+ % Based on data from p. 70 of:
6
+ %
7
+ % Chow, J. H., editor. Time-Scale Modeling of Dynamic Networks with
8
+ % Applications to Power Systems. Springer-Verlag, 1982.
9
+ % Part of the Lecture Notes in Control and Information Sciences book
10
+ % series (LNCIS, volume 46)
11
+ %
12
+ % which in turn appears to come from:
13
+ %
14
+ % R.P. Schulz, A.E. Turner and D.N. Ewart, "Long Term Power System
15
+ % Dynamics," EPRI Report 90-7-0, Palo Alto, California, 1974.
16
+
17
+ % MATPOWER
18
+
19
+ %% MATPOWER Case Format : Version 2
20
+ mpc.version = '2';
21
+
22
+ %%----- Power Flow Data -----%%
23
+ %% system MVA base
24
+ mpc.baseMVA = 100;
25
+
26
+ %% bus data
27
+ % bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
28
+ mpc.bus = [
29
+ 1 3 0 0 0 0 1 1 0 345 1 1.1 0.9;
30
+ 2 2 0 0 0 0 1 1 0 345 1 1.1 0.9;
31
+ 3 2 0 0 0 0 1 1 0 345 1 1.1 0.9;
32
+ 4 1 0 0 0 0 1 1 0 345 1 1.1 0.9;
33
+ 5 1 90 30 0 0 1 1 0 345 1 1.1 0.9;
34
+ 6 1 0 0 0 0 1 1 0 345 1 1.1 0.9;
35
+ 7 1 100 35 0 0 1 1 0 345 1 1.1 0.9;
36
+ 8 1 0 0 0 0 1 1 0 345 1 1.1 0.9;
37
+ 9 1 125 50 0 0 1 1 0 345 1 1.1 0.9;
38
+ ];
39
+
40
+ %% generator data
41
+ % bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin Pc1 Pc2 Qc1min Qc1max Qc2min Qc2max ramp_agc ramp_10 ramp_30 ramp_q apf
42
+ mpc.gen = [
43
+ 1 72.3 27.03 300 -300 1.04 100 1 250 10 0 0 0 0 0 0 0 0 0 0 0;
44
+ 2 163 6.54 300 -300 1.025 100 1 300 10 0 0 0 0 0 0 0 0 0 0 0;
45
+ 3 85 -10.95 300 -300 1.025 100 1 270 10 0 0 0 0 0 0 0 0 0 0 0;
46
+ ];
47
+
48
+ %% branch data
49
+ % fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
50
+ mpc.branch = [
51
+ 1 4 0 0.0576 0 250 250 250 0 0 1 -360 360;
52
+ 4 5 0.017 0.092 0.158 250 250 250 0 0 1 -360 360;
53
+ 5 6 0.039 0.17 0.358 150 150 150 0 0 1 -360 360;
54
+ 3 6 0 0.0586 0 300 300 300 0 0 1 -360 360;
55
+ 6 7 0.0119 0.1008 0.209 150 150 150 0 0 1 -360 360;
56
+ 7 8 0.0085 0.072 0.149 250 250 250 0 0 1 -360 360;
57
+ 8 2 0 0.0625 0 250 250 250 0 0 1 -360 360;
58
+ 8 9 0.032 0.161 0.306 250 250 250 0 0 1 -360 360;
59
+ 9 4 0.01 0.085 0.176 250 250 250 0 0 1 -360 360;
60
+ ];
61
+
62
+ %%----- OPF Data -----%%
63
+ %% generator cost data
64
+ % 1 startup shutdown n x1 y1 ... xn yn
65
+ % 2 startup shutdown n c(n-1) ... c0
66
+ mpc.gencost = [
67
+ 2 1500 0 3 0.11 5 150;
68
+ 2 2000 0 3 0.085 1.2 600;
69
+ 2 3000 0 3 0.1225 1 335;
70
+ ];
@@ -0,0 +1,139 @@
1
+ """Tests of the MATPOWER ``.m`` input of ``load_mpc`` and ``PowerFlow``.
2
+
3
+ ``test_load_matpower/case9.m`` is MATPOWER 8.1's ``case9.m``, unchanged. The
4
+ other cases are written by the tests, each to exercise one rule of the
5
+ preparation that ``read_matpower`` copies from MATPOWER ``runpf``.
6
+ """
7
+ import numpy as np
8
+ import pandas as pd
9
+ import pytest
10
+ from scipy.sparse import issparse
11
+
12
+ from Solverz import Opt, nr_method
13
+ from SolUtil import PowerFlow
14
+ from SolUtil.sysparser import load_mpc
15
+ from SolUtil.sysparser.eps_function import read_matpower
16
+
17
+ # MATPOWER 8.1 ``runpf`` on case9, in the bus order of the file
18
+ CASE9_VM = [1.04, 1.025, 1.025, 1.02578839284401, 1.01265432401778,
19
+ 1.03235294900237, 1.0158825836275, 1.02576937238645, 0.995630858048295]
20
+ CASE9_VA_DEG = [0.0, 9.28000548164279, 4.66475133313676, -2.21678779994979,
21
+ -3.68739617015706, 1.96671607444908, 0.727536076874292,
22
+ 3.71970115462176, -3.98880527285147]
23
+
24
+ # bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
25
+ BUS = [[10, 3, 0, 0, 0, 0, 1, 1.0, 0, 230, 1, 1.1, 0.9],
26
+ [20, 2, 0, 0, 0, 0, 1, 1.0, 0, 230, 1, 1.1, 0.9],
27
+ [30, 2, 20, 5, 0, 0, 1, 0.98, 0, 230, 1, 1.1, 0.9],
28
+ [40, 1, 60, 20, 0, 0, 1, 1.0, 0, 230, 1, 1.1, 0.9],
29
+ [50, 1, 40, 10, 0, 0, 1, 1.0, 0, 230, 1, 1.1, 0.9]]
30
+ # bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin, then 11 zero columns
31
+ GEN = [[20, 30, 5, 50, -50, 1.03, 100, 1, 100, 0],
32
+ [10, 0, 0, 300, -300, 1.02, 100, 1, 300, 0],
33
+ [30, 25, 0, 50, -50, 1.01, 100, 0, 100, 0], # out of service
34
+ [20, 20, 7, 50, -50, 1.05, 100, 1, 100, 0]] # a second generator at bus 20
35
+ # fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
36
+ BRANCH = [[10, 20, 0.01, 0.1, 0.02, 0, 0, 0, 0, 0, 1, -360, 360],
37
+ [20, 30, 0.01, 0.1, 0.02, 0, 0, 0, 0, 0, 1, -360, 360],
38
+ [30, 40, 0.01, 0.1, 0.02, 0, 0, 0, 0, 0, 1, -360, 360],
39
+ [40, 50, 0.01, 0.1, 0.02, 0, 0, 0, 0, 0, 1, -360, 360],
40
+ [10, 50, 0.01, 0.1, 0.02, 0, 0, 0, 0, 0, 0, -360, 360]] # out of service
41
+
42
+
43
+ def _write_case(path, bus=BUS, gen=GEN, branch=BRANCH):
44
+ """A MATPOWER case file with the given rows; generator rows are padded
45
+ to the 21 columns of the version 2 format."""
46
+ def block(name, rows):
47
+ body = '\n'.join('\t' + '\t'.join(repr(v) for v in row) + ';' for row in rows)
48
+ return f'mpc.{name} = [\n{body}\n];\n'
49
+ gen = [list(row) + [0] * (21 - len(row)) for row in gen]
50
+ path.write_text(f"function mpc = {path.stem}\nmpc.version = '2';\nmpc.baseMVA = 100;\n"
51
+ + block('bus', bus) + block('gen', gen) + block('branch', branch))
52
+ return str(path)
53
+
54
+
55
+ def _assert_same_arrays(a, b):
56
+ assert a.keys() == b.keys()
57
+ for k in a:
58
+ if issparse(a[k]):
59
+ assert a[k].shape == b[k].shape and (a[k] != b[k]).nnz == 0, k
60
+ else:
61
+ assert np.array_equal(np.asarray(a[k]), np.asarray(b[k])), k
62
+
63
+
64
+ def test_matpower_case9_solves_to_the_matpower_solution(datadir):
65
+ pf = PowerFlow(datadir / 'case9.m')
66
+ sol = nr_method(pf.pfmdl, pf.y0, Opt(ite_tol=1e-10))
67
+ assert sol.stats.succeed
68
+ pf.parse_data_post_pf(sol)
69
+ np.testing.assert_allclose(pf.Vm, CASE9_VM, rtol=0, atol=1e-12)
70
+ np.testing.assert_allclose(np.rad2deg(pf.Va), CASE9_VA_DEG, rtol=0, atol=1e-10)
71
+
72
+
73
+ def test_m_and_xlsx_of_one_case_give_the_same_arrays(datadir, tmp_path):
74
+ """The two inputs share every step after reading the tables, so the
75
+ xlsx written from the tables of a ``.m`` file loads to the same arrays."""
76
+ m = datadir / 'case9.m'
77
+ base_mva, bus, branch, gen = read_matpower(m)
78
+ xlsx = tmp_path / 'case9.xlsx'
79
+ with pd.ExcelWriter(xlsx, engine='openpyxl') as xw:
80
+ pd.DataFrame({'baseMVA': base_mva}).to_excel(xw, sheet_name='setting', index=False)
81
+ bus.to_excel(xw, sheet_name='bus', index=False)
82
+ branch.to_excel(xw, sheet_name='branch', index=False)
83
+ gen.to_excel(xw, sheet_name='gen', index=False)
84
+ _assert_same_arrays(load_mpc(str(m)), load_mpc(str(xlsx)))
85
+
86
+
87
+ def test_runpf_preparation(tmp_path):
88
+ """Generators out of service are dropped and those of one bus summed;
89
+ a PV bus without a generator in service becomes a PQ bus; a generator bus
90
+ starts at the setpoint of its first generator; buses are numbered in file
91
+ order; a branch out of service adds nothing to the admittance matrix."""
92
+ mpc = load_mpc(_write_case(tmp_path / 'case_rules.m'))
93
+ assert mpc['nb'] == 5
94
+ np.testing.assert_array_equal(mpc['idx_slack'], [0])
95
+ np.testing.assert_array_equal(mpc['idx_pv'], [1])
96
+ np.testing.assert_array_equal(mpc['idx_pq'], [2, 3, 4])
97
+ np.testing.assert_allclose(mpc['Pg'], [0, 0.5, 0, 0, 0], rtol=0, atol=1e-15)
98
+ np.testing.assert_allclose(mpc['Qg'], [0, 0.12, 0, 0, 0], rtol=0, atol=1e-15)
99
+ np.testing.assert_allclose(mpc['Pd'], [0, 0, 0.2, 0.6, 0.4], rtol=0, atol=1e-15)
100
+ np.testing.assert_array_equal(mpc['Vm'], [1.02, 1.03, 0.98, 1.0, 1.0])
101
+ Y = mpc['Ybus'].toarray()
102
+ assert Y[0, 4] == 0 and Y[4, 0] == 0
103
+ assert Y[0, 1] != 0 and Y[3, 4] != 0
104
+
105
+ base_mva, bus, branch, gen = read_matpower(tmp_path / 'case_rules.m')
106
+ np.testing.assert_array_equal(gen['bus'], [0, 1])
107
+ np.testing.assert_array_equal(gen['Qmax'], [300, 100])
108
+ np.testing.assert_array_equal(branch['status'], [1, 1, 1, 1, 0])
109
+ np.testing.assert_array_equal(branch[['fbus', 'tbus']].to_numpy()[-1], [0, 4])
110
+
111
+ pf = PowerFlow(tmp_path / 'case_rules.m')
112
+ sol = nr_method(pf.pfmdl, pf.y0, Opt(ite_tol=1e-10))
113
+ assert sol.stats.succeed
114
+
115
+
116
+ def test_a_case_without_a_reference_generator_promotes_the_first_pv_bus(tmp_path):
117
+ gen = [row[:7] + [0] + row[8:] if row[0] == 10 else row for row in GEN]
118
+ with pytest.warns(UserWarning, match='promoted to the reference bus'):
119
+ mpc = load_mpc(_write_case(tmp_path / 'case_noref.m', gen=gen))
120
+ np.testing.assert_array_equal(mpc['idx_slack'], [1])
121
+ np.testing.assert_array_equal(mpc['idx_pv'], [])
122
+ np.testing.assert_array_equal(mpc['idx_pq'], [0, 2, 3, 4])
123
+
124
+
125
+ @pytest.mark.parametrize('change, message', [
126
+ ('isolated', 'isolated buses of type 4'),
127
+ ('duplicate', 'duplicate bus numbers'),
128
+ ('unknown', 'references to unknown bus numbers'),
129
+ ])
130
+ def test_cases_the_power_flow_cannot_take_are_refused(tmp_path, change, message):
131
+ bus, branch = [list(row) for row in BUS], [list(row) for row in BRANCH]
132
+ if change == 'isolated':
133
+ bus[4][1] = 4
134
+ elif change == 'duplicate':
135
+ bus[4][0] = 40
136
+ else:
137
+ branch[3][1] = 60
138
+ with pytest.raises(ValueError, match=message):
139
+ load_mpc(_write_case(tmp_path / f'case_{change}.m', bus=bus, branch=branch))
@@ -0,0 +1,98 @@
1
+ """Power-flow tests for ``SolUtil.PowerFlow``.
2
+
3
+ Ports the cookbook power-flow validation: build a MATPOWER case, solve
4
+ it, and cross-check the LoopEqn formulation against the legacy per-bus
5
+ scalar formulation. The two builds are algebraically identical, so their
6
+ complex bus voltages, slack injections, and reconstructed currents must
7
+ agree to Newton tolerance.
8
+
9
+ The LoopEqn path is only supported by the Numba-JIT module printer (the
10
+ inline ``made_numerical`` path does not accept ``LoopEqn``), so
11
+ ``loopeqn=True`` pays a one-off compile cost; the test exercises both
12
+ paths.
13
+
14
+ The fixture ``test_power_flow/case9.xlsx`` is the IEEE 9-bus EPS case
15
+ shared with the cookbook IES chapter (a MATPOWER-format xlsx with
16
+ ``bus`` / ``branch`` / ``gen`` / ``setting`` sheets parsed by
17
+ ``load_mpc``).
18
+ """
19
+ import numpy as np
20
+ import pytest
21
+
22
+ from SolUtil import PowerFlow
23
+
24
+
25
+ @pytest.fixture
26
+ def case_file(datadir):
27
+ f = datadir / 'case9.xlsx'
28
+ if not f.exists():
29
+ pytest.skip(f'case9 fixture not available at {f}')
30
+ return str(f)
31
+
32
+
33
+ def _complex_voltage(pf):
34
+ return pf.Vm * np.exp(1j * pf.Va)
35
+
36
+
37
+ def test_pf_scalar_converges(case_file):
38
+ pf = PowerFlow(case_file, loopeqn=False)
39
+ pf.run()
40
+ assert pf.run_succeed
41
+ # voltage magnitudes are physical (per-unit, near 1.0)
42
+ assert np.all(pf.Vm > 0.8) and np.all(pf.Vm < 1.2)
43
+
44
+
45
+ def test_pf_loopeqn_converges(case_file):
46
+ pf = PowerFlow(case_file, loopeqn=True)
47
+ pf.run()
48
+ assert pf.run_succeed
49
+ assert np.all(pf.Vm > 0.8) and np.all(pf.Vm < 1.2)
50
+
51
+
52
+ def test_pf_loopeqn_matches_scalar(case_file):
53
+ """LoopEqn and legacy scalar formulations must converge to the same
54
+ complex bus voltage and the same reconstructed slack / pv injections."""
55
+ pf_scalar = PowerFlow(case_file, loopeqn=False)
56
+ pf_scalar.run()
57
+ assert pf_scalar.run_succeed
58
+
59
+ pf_loop = PowerFlow(case_file, loopeqn=True)
60
+ pf_loop.run()
61
+ assert pf_loop.run_succeed
62
+
63
+ V_scalar = _complex_voltage(pf_scalar)
64
+ V_loop = _complex_voltage(pf_loop)
65
+ np.testing.assert_allclose(V_loop, V_scalar, rtol=1e-6, atol=1e-6)
66
+
67
+ np.testing.assert_allclose(pf_loop.Pg, pf_scalar.Pg, rtol=1e-6, atol=1e-6)
68
+ np.testing.assert_allclose(pf_loop.Qg, pf_scalar.Qg, rtol=1e-6, atol=1e-6)
69
+ np.testing.assert_allclose(pf_loop.ix, pf_scalar.ix, rtol=1e-6, atol=1e-6)
70
+ np.testing.assert_allclose(pf_loop.iy, pf_scalar.iy, rtol=1e-6, atol=1e-6)
71
+
72
+
73
+ def test_pf_default_is_loopeqn():
74
+ """Default formulation is the LoopEqn build (since 0.9.0)."""
75
+ import inspect
76
+ sig = inspect.signature(PowerFlow.__init__)
77
+ assert sig.parameters['loopeqn'].default is True
78
+
79
+
80
+ def test_pf_scalar_path_is_deprecated(case_file):
81
+ """The legacy inline scalar path warns it is deprecated."""
82
+ with pytest.warns(DeprecationWarning):
83
+ PowerFlow(case_file, loopeqn=False)
84
+
85
+
86
+ def test_pf_two_instances_are_independent(case_file, datadir):
87
+ """Two PowerFlow objects in one process must not share a rendered module.
88
+
89
+ The LoopEqn build renders a module under a per-instance name. With a
90
+ fixed name the second instance got the first instance's F / J / y.
91
+ """
92
+ pf_a = PowerFlow(case_file)
93
+ pf_b = PowerFlow(case_file)
94
+ assert pf_a.pfmdl is not pf_b.pfmdl
95
+ assert pf_a.pfmdl.F is not pf_b.pfmdl.F
96
+ pf_b.run()
97
+ assert pf_b.run_succeed
98
+ assert pf_b.Vm.shape == (pf_b.nb,)
SolUtil/error_cal.py ADDED
@@ -0,0 +1,9 @@
1
+ import numpy as np
2
+
3
+
4
+ def calrmse(a, b):
5
+ a = np.array(a).reshape((-1, ))
6
+ b = np.array(b).reshape((-1, ))
7
+ nz = a.shape[0]
8
+ return np.sqrt(np.sum((a - b) ** 2, axis=0) / nz)
9
+
SolUtil/profile.py ADDED
@@ -0,0 +1,9 @@
1
+ import time
2
+
3
+
4
+ def TimeProf(func, *args):
5
+ start = time.perf_counter()
6
+ res = func(*args)
7
+ end = time.perf_counter()
8
+ print(f'Time elapsed {end-start}s')
9
+ return res
@@ -0,0 +1,3 @@
1
+ from .eps_function import load_mpc
2
+ from .ngs_function import load_ngs
3
+ from .dhs_function import load_hs
@@ -0,0 +1,6 @@
1
+ import numpy as np
2
+
3
+
4
+ def to_writable_array(values, dtype=None):
5
+ # pandas 3 Copy-on-Write can hand out read-only NumPy views for Series-backed data.
6
+ return np.array(values, dtype=dtype, copy=True)
@@ -0,0 +1,209 @@
1
+ import warnings
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ import networkx as nx
6
+ from scipy.sparse import csc_array
7
+
8
+ from ._array_utils import to_writable_array
9
+
10
+
11
+ def load_hs(filename):
12
+ df = pd.read_excel(filename,
13
+ sheet_name=None,
14
+ engine='openpyxl',
15
+ index_col=None
16
+ )
17
+ hc = dict()
18
+
19
+ type_node = to_writable_array(df['node']['type'])
20
+ idx_node = to_writable_array(df['node']['idx'])
21
+ idx_pipe = to_writable_array(df['pipe']['idx'])
22
+ idx_from = to_writable_array(df['pipe']['fnode'])
23
+ idx_to = to_writable_array(df['pipe']['tnode'])
24
+ I_node_cond = df['node']['type'] == 1
25
+ I_node = to_writable_array(df['node'][I_node_cond]['idx'])
26
+ hc['I_node'] = I_node
27
+ s_node_cond = df['node']['type'] == 0
28
+ s_node = to_writable_array(df['node'][s_node_cond]['idx'])
29
+ hc['s_node'] = s_node
30
+ l_node_cond = df['node']['type'] == 2
31
+ l_node = to_writable_array(df['node'][l_node_cond]['idx'])
32
+ hc['l_node'] = l_node
33
+ if len(l_node) == 0:
34
+ warnings.warn('No DHS load node!')
35
+ slack_node_cond = df['node']['type'] == 3
36
+ slack_node = to_writable_array(df['node'][slack_node_cond]['idx'])
37
+ hc['slack_node'] = slack_node
38
+ n_node = len(df['node'])
39
+ hc['n_node'] = n_node
40
+ n_pipe = len(df['pipe'])
41
+ hc['n_pipe'] = n_pipe
42
+ non_slack_nodes = np.setdiff1d(np.arange(n_node), slack_node)
43
+ hc['non_slack_nodes'] = non_slack_nodes
44
+
45
+ if 'delta' in df['node'].columns:
46
+ delta_node = to_writable_array(df['node']['delta'])
47
+ else:
48
+ delta_node = np.zeros(n_node)
49
+ hc['delta_node'] = delta_node
50
+
51
+ if 'delta' in df['pipe'].columns:
52
+ delta_pipe = to_writable_array(df['pipe']['delta'])
53
+ else:
54
+ delta_pipe = np.zeros(n_pipe)
55
+ hc['delta_pipe'] = delta_pipe
56
+
57
+ # loop detection and conversion
58
+ if 'loop' in df:
59
+ hc['pinloop'] = to_writable_array(df['loop']['loop1'])
60
+ else:
61
+ hc['pinloop'] = np.zeros(n_pipe)
62
+
63
+ lam = to_writable_array(df['pipe']['lambda (W/mK)'])
64
+ D = to_writable_array(df['pipe']['D (mm)']) / 1000
65
+ Ts = to_writable_array(df['node']['Ts'])
66
+ Tr = to_writable_array(df['node']['Tr'])
67
+ L = to_writable_array(df['pipe']['L (m)'])
68
+ S = np.pi * (D / 2) ** 2
69
+ m = to_writable_array(df['pipe']['Massflow (kg/s)'])
70
+ hc['m'] = m
71
+
72
+ density = 958.4
73
+ g = 10
74
+ mu = 0.294e-6
75
+ epsilon = 1.25e-3
76
+
77
+ # calculate K
78
+ # Calculate absolute velocity
79
+ v = np.abs(m) / (density * np.pi * (D ** 2) / 4)
80
+
81
+ # Calculate Reynolds number
82
+ Re = v * D / mu
83
+
84
+ # Initialize friction factor array
85
+ f = np.zeros(hc['n_pipe'])
86
+
87
+ # Indices where Re < 2300
88
+ low_Re_indices = np.where(Re < 2300)[0]
89
+ f[low_Re_indices] = 64. / Re[low_Re_indices]
90
+
91
+ # Indices where 2300 <= Re <= 4000
92
+ mid_Re_indices = np.where((Re >= 2300) & (Re <= 4000))[0]
93
+ f[mid_Re_indices] = (((colebrook(4000, epsilon / D[mid_Re_indices]) - 64 / 2300) / (4000 - 2300)) *
94
+ (Re[mid_Re_indices] - 2300) + 64 / 2300)
95
+
96
+ # Indices where Re > 4000
97
+ high_Re_indices = np.where(Re > 4000)[0]
98
+ f[high_Re_indices] = colebrook(Re[high_Re_indices], epsilon / D[high_Re_indices])
99
+
100
+ # Calculate K
101
+ K = 8 * L * f / (D ** 5 * density ** 2 * np.pi ** 2 * g)
102
+
103
+ hc['K'] = K
104
+
105
+ G = nx.DiGraph()
106
+
107
+ for i in range(len(idx_pipe)):
108
+ G.add_node(idx_from[i], type=type_node[idx_from[i]])
109
+ G.add_node(idx_to[i], type=type_node[idx_to[i]])
110
+ G.add_edge(idx_from[i],
111
+ idx_to[i],
112
+ idx=idx_pipe[i],
113
+ c=K[i])
114
+
115
+ A = nx.incidence_matrix(G,
116
+ nodelist=idx_node,
117
+ edgelist=sorted(G.edges(data=True), key=lambda edge: edge[2].get('idx', 1)),
118
+ oriented=True)
119
+ hc['A'] = A
120
+ pipe_from = []
121
+ pipe_to = []
122
+ idx_pipe = []
123
+ for x, y, z in sorted(G.edges(data=True), key=lambda edge: edge[2].get('idx', 1)):
124
+ pipe_from.append(x)
125
+ pipe_to.append(y)
126
+ idx_pipe.append(z['idx'])
127
+
128
+ hc['pipe_from'] = pipe_from
129
+ hc['pipe_to'] = pipe_to
130
+ hc['idx_pipe'] = idx_pipe
131
+ hc['G'] = G
132
+
133
+ hc['lam'] = lam
134
+ hc['D'] = D
135
+ hc['Ts'] = Ts
136
+ hc['Tr'] = Tr
137
+ hc['L'] = L
138
+ hc['S'] = S
139
+ hc['Ta'] = to_writable_array(df['setting']['Ta'])
140
+ hc['Tsource'] = to_writable_array(df['setting']['Tsource'])
141
+ hc['Tload'] = to_writable_array(df['setting']['Tload'])
142
+ hc['phi'] = to_writable_array(df['node']['phi (MW)'], dtype=float)
143
+ if 'Hset' in df['node']:
144
+ hc['Hset'] = to_writable_array(df['node']['Hset'][slack_node])
145
+ else:
146
+ hc['Hset'] = np.zeros(slack_node.shape[0])
147
+
148
+ s_slack_node = s_node.tolist() + slack_node.tolist()
149
+ Cs = csc_array((np.ones(len(s_slack_node)), (s_slack_node, s_slack_node)),
150
+ shape=(hc['n_node'], hc['n_node']))
151
+ Cl = csc_array((np.ones(len(hc['l_node'])), (hc['l_node'], hc['l_node'])),
152
+ shape=(hc['n_node'], hc['n_node']))
153
+ Ci = csc_array((np.ones(len(hc['I_node'])), (hc['I_node'], hc['I_node'])),
154
+ shape=(hc['n_node'], hc['n_node']))
155
+ hc['Cs'] = Cs
156
+ hc['Cl'] = Cl
157
+ hc['Ci'] = Ci
158
+
159
+ return hc
160
+
161
+
162
+ def colebrook(R, K=None):
163
+ """
164
+ Compute the Darcy-Weisbach friction factor according to the Colebrook formula.
165
+
166
+ Parameters:
167
+ R : array_like
168
+ Reynolds' number (should be > 2300).
169
+ K : array_like or None
170
+ Equivalent sand roughness height divided by the hydraulic diameter.
171
+ If None, default value is set to 0.
172
+
173
+ Returns:
174
+ F : array_like
175
+ Friction factor.
176
+
177
+ Raises:
178
+ ValueError
179
+ If any value in R is non-positive or any value in K is negative.
180
+ """
181
+
182
+ # Check for input validity
183
+ if np.any(R <= 0):
184
+ raise ValueError("The Reynolds number must be positive (R>2300).")
185
+ if K is None:
186
+ K = np.zeros_like(R)
187
+ elif np.any(K < 0):
188
+ raise ValueError("The relative sand roughness must be non-negative.")
189
+
190
+ # Constants used in initialization
191
+ X1 = K * R * 0.123968186335417556 # X1 ≈ K * R * log(10) / 18.574
192
+ X2 = np.log(R) - 0.779397488455682028 # X2 ≈ log(R*log(10) / 5.02)
193
+
194
+ # Initial guess for F
195
+ F = X2 - 0.2 # F ≈ X2 - 1/5
196
+
197
+ # First iteration
198
+ E = (np.log(X1 + F) + F - X2) / (1 + X1 + F)
199
+ F = F - (1 + X1 + F + 0.5 * E) * E * (X1 + F) / (1 + X1 + F + E * (1 + E / 3))
200
+
201
+ # Second iteration for higher accuracy
202
+ E = (np.log(X1 + F) + F - X2) / (1 + X1 + F)
203
+ F = F - (1 + X1 + F + 0.5 * E) * E * (X1 + F) / (1 + X1 + F + E * (1 + E / 3))
204
+
205
+ # Finalizing the solution
206
+ F = 1.151292546497022842 / F # F ≈ 0.5 * log(10) / F
207
+ F = F ** 2 # Square F to get the friction factor
208
+
209
+ return F