-
Notifications
You must be signed in to change notification settings - Fork 0
/
diff.txt
1890 lines (1835 loc) · 72.9 KB
/
diff.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/eureca_dhcs/_hydraulic_system_function.py b/eureca_dhcs/_hydraulic_system_function.py
index 2bcb127..b6c7ecd 100644
--- a/eureca_dhcs/_hydraulic_system_function.py
+++ b/eureca_dhcs/_hydraulic_system_function.py
@@ -86,7 +86,7 @@ def hydraulic_balance_system(x, q, network):
* x[branch._unique_matrix_idx] ** 2
* 8
* branch._pipe_len
- / (np.pi**2 * branch._pipe_diameter**5 * branch.get_density())
+ / (np.pi**2 * branch._pipe_int_diameter**5 * branch.get_density())
)
# Colebrook - White equation for each branch
@@ -96,6 +96,12 @@ def hydraulic_balance_system(x, q, network):
# + network._nodes_numbes
# + branch._unique_matrix_idx
# ]
+ # reinolds = (
+ # 4
+ # * x[branch._unique_matrix_idx]
+ # / (np.pi * branch.get_dynamic_viscosity() * branch._pipe_int_diameter)
+ # )
+ # if reinolds > 2300:
system.append(
1
/ np.sqrt(
@@ -107,10 +113,10 @@ def hydraulic_balance_system(x, q, network):
)
+ 2
* np.log(
- branch._roughness / (3.7 * branch._pipe_diameter)
+ branch._roughness / (3.7 * branch._pipe_int_diameter)
+ np.pi
* 2.51
- * branch._pipe_diameter
+ * branch._pipe_int_diameter
* branch.get_dynamic_viscosity()
/ (
4
@@ -125,6 +131,20 @@ def hydraulic_balance_system(x, q, network):
)
)
)
+ # else:
+ # system.append(
+ # x[
+ # network._branches_number
+ # + network._nodes_number
+ # + branch._unique_matrix_idx
+ # ]
+ # - 64
+ # / (
+ # 4
+ # * x[branch._unique_matrix_idx]
+ # / (np.pi * branch.get_dynamic_viscosity() * branch._pipe_int_diameter)
+ # )
+ # )
system.append(
x[network._branches_number + network._nodes_number - 1]
- q[network._branches_number + network._nodes_number - 1]
diff --git a/eureca_dhcs/_thermal_system_function.py b/eureca_dhcs/_thermal_system_function.py
new file mode 100644
index 0000000..df1610d
--- /dev/null
+++ b/eureca_dhcs/_thermal_system_function.py
@@ -0,0 +1,168 @@
+"""
+This script include the function that builds the thermal system
+to pass to scipy.optimize.fsolve
+or np.linalg.solve
+"""
+
+__author__ = "Enrico Prataviera"
+__credits__ = ["Enrico Prataviera"]
+__license__ = "MIT"
+__version__ = "0.1"
+__maintainer__ = "Enrico Prataviera"
+
+import numpy as np
+
+
+def thermal_balance_system_optimization(x, q, network, time_interval):
+ """
+ DO NOT USE! WRONG RESULTS
+ This function builds the thermal system for the solution with f solve:
+
+ The equation are:
+ n_nodes equations: the mixing balances for each node
+ n_branch equations: the energy balance equation of each branch
+
+ The unknown variable are (x vector):
+
+ n_branches temperatures [°C]n_nodes temperatures [°C]
+
+ The known values are (q vector):
+ supply nodes entering temperature [°C]
+ branches capacity previous timestep term and ground loss term
+
+
+ Parameters
+ ----------
+ x : np.array
+ array with the first try value [nodes_temperatures, branches_temperatures].
+ q : np.array
+ boundary conditions [nodes_temperatures, branches capacity and ground loss term].
+ network : Network
+ network object. This is used to manage the index of the matrix with respect to branches and nodes objects.
+ time_interval: int
+ number of seconds per each timestep
+
+ Returns
+ -------
+ system : List
+ Use this function in an fsolve/root.
+
+ """
+
+ # System id the list where equations are inserted
+ system = []
+ # node balances
+ # This equations are the mass balance for each node
+ i = 0
+ for node in network._nodes_object_ordered_list:
+ if node._node_type == "supply":
+ # known condition
+ system.append(x[node._unique_matrix_idx] - q[node._unique_matrix_idx])
+ else:
+ (
+ branches_idx,
+ brnaches_mass_flow,
+ ) = node.get_supply_branches_mass_flow_rates()
+ total = brnaches_mass_flow.sum()
+ vector = np.zeros(network._nodes_number + network._branches_number)
+ vector[branches_idx + network._nodes_number] = brnaches_mass_flow
+ vector[node._unique_matrix_idx] = -1 * total
+ system.append(np.dot(vector, x))
+ for branch in network._branches_object_ordered_list:
+ G = branch._mass_flow_rate * branch.get_specific_heat()
+ C = branch.get_dynamic_capacity()
+ f_loss = branch.ground_loss_factor
+ # to manage negative mass flow rates
+ G = np.abs(G)
+ if branch._mass_flow_rate < 0:
+ supply_node = branch._demand_node_object
+ demand_node = branch._supply_node_object
+ else:
+ supply_node = branch._supply_node_object
+ demand_node = branch._demand_node_object
+ system.append(
+ -1 * G * x[supply_node._unique_matrix_idx]
+ + x[branch._unique_matrix_idx + network._nodes_number]
+ * (C / time_interval + f_loss + 1 * G)
+ + 0 * G * x[demand_node._unique_matrix_idx]
+ + q[branch._unique_matrix_idx + network._nodes_number]
+ )
+ return system
+
+
+def thermal_balance_system_inverse(network, q, time_interval):
+ """
+ This function solve the linear system Ax=q for the thermal balance:
+
+ The equation are:
+ n_nodes equations: the mixing balances for each node
+ n_branch equations: the energy balance equation of each branch
+
+ The unknown variable are (x vector):
+ n_branches temperatures [°C]n_nodes temperatures [°C]
+
+ The known values are (q vector):
+ supply nodes entering temperature [°C]
+ branches capacity previous timestep term and ground loss term
+
+
+ Parameters
+ ----------
+ q : np.array
+ boundary conditions [nodes_temperatures, branches capacity and ground loss term].
+ network : Network
+ network object. This is used to manage the index of the matrix with respect to branches and nodes objects.
+ time_interval: int
+ number of seconds per each timestep
+
+ Returns
+ -------
+ x : np.array
+ array with the solution [nodes_temperatures, branches_temperatures].
+
+ """
+
+ # Problema Termico
+ # TODO Cambiare formula del bilancio di ramo
+
+ AT = np.zeros(
+ [
+ (network._branches_number + network._nodes_number),
+ (network._branches_number + network._nodes_number),
+ ]
+ )
+
+ for node in network._nodes_object_ordered_list:
+ if node._node_type == "supply":
+ AT[node._unique_matrix_idx, node._unique_matrix_idx] = 1
+ else:
+ total_entering_flow_rate = 0.0
+ for (
+ supply_branch_id,
+ supply_branch,
+ ) in node._supply_branches_objects.items():
+ total_entering_flow_rate += supply_branch._mass_flow_rate
+ AT[
+ node._unique_matrix_idx,
+ network._nodes_number + supply_branch._unique_matrix_idx,
+ ] = supply_branch._mass_flow_rate
+ AT[node._unique_matrix_idx, node._unique_matrix_idx] = (
+ -1 * total_entering_flow_rate
+ )
+ for branch in network._branches_object_ordered_list:
+ line = network._nodes_number + branch._unique_matrix_idx
+ G = branch._mass_flow_rate * branch.get_specific_heat()
+ C = branch.get_dynamic_capacity()
+ f_loss = branch.ground_loss_factor
+ # to manage negative mass flow rates
+ G = np.abs(G)
+ if branch._mass_flow_rate < 0:
+ supply_node = branch._demand_node_object
+ demand_node = branch._supply_node_object
+ else:
+ supply_node = branch._supply_node_object
+ demand_node = branch._demand_node_object
+ AT[line, supply_node._unique_matrix_idx] = -1 * G
+ AT[line, demand_node._unique_matrix_idx] = 1 * G * 0
+ AT[line, line] = C / time_interval + G * 1 + f_loss
+ return np.linalg.solve(AT, q), AT, q
diff --git a/eureca_dhcs/branch.py b/eureca_dhcs/branch.py
index ff05ebc..a9513d6 100644
--- a/eureca_dhcs/branch.py
+++ b/eureca_dhcs/branch.py
@@ -10,6 +10,7 @@ import logging
import numpy as np
from eureca_dhcs.exceptions import DuplicateBranch, WrongBranchTemperatureMode
+from eureca_dhcs.soil import Soil
class Branch:
@@ -22,9 +23,9 @@ class Branch:
_counter = 0
# this values are use just for the first timestep calculation
_cooling_starting_temperature = 15 # [°C]
- _heating_starting_temperature = 80 # [°C]
+ _heating_starting_temperature = 55 # [°C]
_starting_mass_flow_rate = 50 # [kg/s]
- _starting_friction_factor = 0.02 # [-]
+ _starting_friction_factor = 0.001 # [-]
# Darcy-Weissback equation
# The friction factor MUST be around this value to make the hydraulic balanc stable
@@ -33,17 +34,30 @@ class Branch:
idx: str,
supply_node: str,
demand_node: str,
- pipe_diameter: float, # [m]
+ pipe_ext_diameter: float, # [m]
+ pipe_thickness: float, # [m]
+ pipe_depth: float, # [m]
+ insulation_thickness: float, # [m]
+ pipe_conductivity: float, # [W/(m/K)]
+ insulation_conductivity: float, # [m]
pipe_len=None, # [m]
roughness=None, # [-]
starting_temperature=None, # [°C]
nodes_objects_dict=None,
+ soil_obj=None,
temperature_mode="Heating",
):
self._idx = idx
self._supply_node_idx = supply_node
self._demand_node_idx = demand_node
- self._pipe_diameter = pipe_diameter
+ self._pipe_thickness = pipe_thickness
+ self._pipe_ext_diameter = pipe_ext_diameter ##############################
+ self._pipe_int_diameter = self._pipe_ext_diameter - 2 * self._pipe_thickness
+ self._pipe_depth = pipe_depth
+ # Other properties
+ self._insulation_thickness = insulation_thickness
+ self._pipe_conductivity = pipe_conductivity
+ self._insulation_conductivity = insulation_conductivity
# Check if pipe len is passed
if pipe_len == None:
@@ -70,9 +84,11 @@ class Branch:
self._unique_matrix_idx = Branch._counter
Branch._counter += 1
# Other useful properties
- self._perimeter = self._pipe_diameter * math.pi
+ self._perimeter = self._pipe_ext_diameter * math.pi
self._external_area = self._perimeter * self._pipe_len
+ self._volume = self._pipe_int_diameter**2 / 4 * np.pi * self._pipe_len
+ self._branch_temperature_array = np.array([])
# Set some values for the dynamic simulation
if starting_temperature != None:
# Default starting temperature
@@ -89,6 +105,8 @@ class Branch:
self._mass_flow_rate_array = np.array([])
self._mass_flow_rate = self._starting_mass_flow_rate
self._friction_factor = self._starting_friction_factor
+ if soil_obj != None:
+ self.calc_ground_loss_factor(soil_obj)
@property
def _idx(self) -> str:
@@ -106,11 +124,11 @@ class Branch:
self.__idx = value
@property
- def _pipe_diameter(self) -> float:
- return self.__pipe_diameter
+ def _pipe_ext_diameter(self) -> float:
+ return self.__pipe_ext_diameter
- @_pipe_diameter.setter
- def _pipe_diameter(self, value: float):
+ @_pipe_ext_diameter.setter
+ def _pipe_ext_diameter(self, value: float):
try:
value = float(value)
except ValueError:
@@ -119,14 +137,14 @@ class Branch:
)
if value > 2.0:
logging.warning(f"Branch {self._idx}, pipe diameter very high: {value} [m]")
- self.__pipe_diameter = value
+ self.__pipe_ext_diameter = value
@property
- def _pipe_diameter(self) -> float:
- return self.__pipe_diameter
+ def _pipe_int_diameter(self) -> float:
+ return self.__pipe_int_diameter
- @_pipe_diameter.setter
- def _pipe_diameter(self, value: float):
+ @_pipe_int_diameter.setter
+ def _pipe_int_diameter(self, value: float):
try:
value = float(value)
except ValueError:
@@ -139,7 +157,109 @@ class Branch:
)
if value > 2.0:
logging.warning(f"Branch {self._idx}, pipe diameter very high: {value} [m]")
- self.__pipe_diameter = value
+ self.__pipe_int_diameter = value
+
+ @property
+ def _pipe_thickness(self) -> float:
+ return self.__pipe_thickness
+
+ @_pipe_thickness.setter
+ def _pipe_thickness(self, value: float):
+ try:
+ value = float(value)
+ except ValueError:
+ raise TypeError(
+ f"Branch {self._idx}, pipe thickness must be a float: {value}"
+ )
+ if value < 0.0:
+ raise ValueError(
+ f"Branch {self._idx}, pipe diameter negative pipe diameter: {value} [m]"
+ )
+ if value > 0.1:
+ logging.warning(
+ f"Branch {self._idx}, pipe thickness very high: {value} [m]"
+ )
+ self.__pipe_thickness = value
+
+ @property
+ def _pipe_depth(self) -> float:
+ return self.__pipe_depth
+
+ @_pipe_depth.setter
+ def _pipe_depth(self, value: float):
+ try:
+ value = float(value)
+ except ValueError:
+ raise TypeError(f"Branch {self._idx}, pipe depth must be a float: {value}")
+ if value > 10.0:
+ logging.warning(f"Branch {self._idx}, pipe depth very high: {value} [m]")
+ self.__pipe_depth = value
+
+ @property
+ def _insulation_thickness(self) -> float:
+ return self.__insulation_thickness
+
+ @_insulation_thickness.setter
+ def _insulation_thickness(self, value: float):
+ try:
+ value = float(value)
+ except ValueError:
+ raise TypeError(
+ f"Branch {self._idx}, insulation thickness must be a float: {value}"
+ )
+ if value < 0.0:
+ raise ValueError(
+ f"Branch {self._idx}, insulation thickness negative: {value} [m]"
+ )
+ if value > 0.1:
+ logging.warning(
+ f"Branch {self._idx}, insulation thickness very high: {value} [m]"
+ )
+ self.__insulation_thickness = value
+
+ @property
+ def _pipe_conductivity(self) -> float:
+ return self.__pipe_conductivity
+
+ @_pipe_conductivity.setter
+ def _pipe_conductivity(self, value: float):
+ try:
+ value = float(value)
+ except ValueError:
+ raise TypeError(
+ f"Branch {self._idx}, pipe conductivity must be a float: {value}"
+ )
+ if value < 0.0:
+ raise ValueError(
+ f"Branch {self._idx}, pipe conductivity negative: {value} [m]"
+ )
+ if value > 100:
+ logging.warning(
+ f"Branch {self._idx}, pipe conductivity very high: {value} [m]"
+ )
+ self.__pipe_conductivity = value
+
+ @property
+ def _insulation_conductivity(self) -> float:
+ return self.__insulation_conductivity
+
+ @_insulation_conductivity.setter
+ def _insulation_conductivity(self, value: float):
+ try:
+ value = float(value)
+ except ValueError:
+ raise TypeError(
+ f"Branch {self._idx}, insulation conductivity must be a float: {value}"
+ )
+ if value < 0.0:
+ raise ValueError(
+ f"Branch {self._idx}, insulation conductivity negative: {value} [m]"
+ )
+ if value > 10:
+ logging.warning(
+ f"Branch {self._idx}, insulation conductivity very high: {value} [m]"
+ )
+ self.__insulation_conductivity = value
@property
def _pipe_len(self) -> float:
@@ -186,6 +306,9 @@ class Branch:
if value < 2.0:
logging.warning(f"Branch {self._idx}, temperature very low: {value} [°C]")
self.__branch_temperature = value
+ self._branch_temperature_array = np.append(
+ self._branch_temperature_array, value
+ )
@property
def _mass_flow_rate(self) -> float:
@@ -243,26 +366,92 @@ class Branch:
self.__pump_pressure_raise = value
def get_density(self):
- # TODO: put correlation for density - self._temperature
- return 1000
+ # https://www.researchgate.net/publication/222573141_Enhanced_modeling_of_moisture_equilibrium_and_transport_in_cementitious_materials_under_arbitrary_temperature_and_relative_humidity_history/figures?lo=1
+ t = self._branch_temperature + 273.15
+ d = 1.54e-8 * t**3 - 1.85e-5 * t**2 + 6.65e-3 * t + 0.247 # [g/cm3]
+ return d * 1000
+
+ def get_specific_heat(self):
+ # TODO: put correlation for spec_heat - self._temperature
+ return 4182 # J/kg K
def get_dynamic_viscosity(self):
- # TODO: put correlation for viscosity - self._temperature
- return 0.36
+ # https://www.researchgate.net/publication/222573141_Enhanced_modeling_of_moisture_equilibrium_and_transport_in_cementitious_materials_under_arbitrary_temperature_and_relative_humidity_history/figures?lo=1
+ t = self._branch_temperature + 273.15
+ # mu = (
+ # 3.38e-8 * t**4 - 4.63e-5 * t**3 + 2.37e-2 * t**2 + 5.45 * t + 470
+ # ) # [kg/(m s)]
+ # https://powderprocess.net/Tools_html/Data_Diagrams/Water_Properties_Correlations.html
+ mu = np.exp(-3.7188 + 578.919 / (-137.546 + t)) / 1000 # [kg/(m s)]
+ return mu
+
+ def get_dynamic_capacity(self):
+ return self.get_density() * self._volume * self.get_specific_heat()
+
+ def calc_soil_linear_resistance(self, soil: Soil):
+ # Based onn ASHRAE DHC Handbook
+ try:
+ soil_conductivity = soil._soil_conductivity
+ except Exception:
+ raise TypeError(
+ f"Branch {self._idx}, calc_ground_resistance \n You must provide a proper soil object with a soil conductivity"
+ )
+ r_0 = self._pipe_ext_diameter / 2 + self._insulation_thickness
+ d = self._pipe_depth
+ if d / r_0 > 4:
+ self._soil_linear_resistance = np.log(2 * d / r_0) / (
+ 2 * np.pi * soil_conductivity
+ )
+ else:
+ self._soil_linear_resistance = np.log(
+ d / r_0 + np.sqrt(d**2 / r_0**2 - 1)
+ ) / (2 * np.pi * soil_conductivity)
+ if d / r_0 < 2:
+ logging.warning(
+ f"Branch {self._idx}, _soil_linear_resistance calculation. Ratio d/r0 lower than 2"
+ )
+
+ def calc_insulation_resistance(self):
+ self._insulation_linear_resistance = np.log(
+ (self._pipe_ext_diameter + self._insulation_thickness * 2)
+ / self._pipe_ext_diameter
+ ) / (2 * np.pi * self._insulation_conductivity)
+
+ def calc_pipe_resistance(self):
+ self._pipe_linear_resistance = np.log(
+ self._pipe_ext_diameter / self._pipe_int_diameter
+ ) / (2 * np.pi * self._pipe_conductivity)
+
+ def calc_ground_loss_factor(self, soil):
+ self.calc_soil_linear_resistance(soil)
+ self.calc_insulation_resistance()
+ self.calc_pipe_resistance()
+
+ R = (
+ self._pipe_linear_resistance
+ + self._insulation_linear_resistance
+ + self._soil_linear_resistance
+ ) # [(m K)/W]
+ U = self._pipe_len / R # [W/K]
+ self.ground_loss_factor = U # W/k
+
+ # def get_ground_temperature(self):
+ # # TODO: put real_t_ground
+ # return 13.0
# # First try flow rate
# # 0.1 m/s flow rate
- # self.first_try_flow_rate = 0.1 * 1000 * self.pipe_diameter**2 / 4
- def get_hydraulic_resistance(self, flow_rate=None):
- # TODO example to try
- # example just to try
- resistance = 2
- return resistance
-
- def get_thermal_conductance(self):
- # TODO example to try
- U = 2 # [W/m2K]
- return self.external_area * U # [W/K]
+ # # self.first_try_flow_rate = 0.1 * 1000 * self.pipe_diameter**2 / 4
+ # def get_hydraulic_resistance(self, flow_rate=None):
+ # # TODO example to try
+ # # example just to try
+ # resistance = 2
+ # return resistance
+
+ # def get_thermal_conductance(self):
+ # # TODO example to try
+ # U = 2 # [W/m2K]
+ # return self.external_area * U # [W/K]
# def set_timestep_flow_rate(self, flow):
# self.timestep_flow_rate = flow
diff --git a/eureca_dhcs/network.py b/eureca_dhcs/network.py
index 60cfa66..a4408b2 100644
--- a/eureca_dhcs/network.py
+++ b/eureca_dhcs/network.py
@@ -14,7 +14,12 @@ from scipy.optimize import root
from eureca_dhcs.node import Node
from eureca_dhcs.branch import Branch
+from eureca_dhcs.soil import Soil
from eureca_dhcs._hydraulic_system_function import hydraulic_balance_system
+from eureca_dhcs._thermal_system_function import (
+ thermal_balance_system_optimization,
+ thermal_balance_system_inverse,
+)
from eureca_dhcs.exceptions import (
EmptyNetworkNodes,
DuplicateNode,
@@ -24,7 +29,9 @@ from eureca_dhcs.exceptions import (
class Network:
- def __init__(self, nodes_dict: dict, branches_dict: dict, output_path=None):
+ def __init__(
+ self, nodes_dict: dict, branches_dict: dict, soil_obj: Soil, output_path=None
+ ):
"""
Creates a district water network starting from nodes and branches dictionaries
See the example below
@@ -51,13 +58,15 @@ class Network:
branches_file : dict
Dict with branches and kwargs.
{
- "1":
- {"id": "Z",
- "supply node": "0",
- "demand node": "2",
- "pipe diameter [m]": 0.3,
- "depth [m]": Na
- },
+ "id": "D",
+ "supply node": "14",
+ "demand node": "15",
+ "pipe ext diameter [m]": 0.3,
+ "depth [m]": 0.8,
+ "pipe thickness [m]": 0.02,
+ "insulation thickness [m]": 0.03,
+ "pipe conductivity [W/(mK)]": 50.0,
+ "insulation conductivity [W/(mK)]": 0.1,
"2":
{...
...}
@@ -65,6 +74,14 @@ class Network:
.
.
+ soil_obj: Soil
+ Soil object to associate to the network (with soil properties)
+
+ output_path: str
+ path to where results are save. If it does not exist the tool creates it
+
+
+
Returns
-------
None.
@@ -79,7 +96,7 @@ class Network:
# Needed to vectorize hydraulic resistances
self._branches_object_ordered_list = []
self._nodes_object_ordered_list = []
-
+ self._soil_obj = soil_obj
# Creation of the nodes objects... THIS MUST BE DONE BEFORE THE CREATION OF BRANCHES
self._create_nodes()
# Creation of the branch objects... THIS MUST BE DONE BEFORE THE CREATION OF BRANCHES
@@ -97,6 +114,18 @@ class Network:
self.output_path = str(output_path)
self._create_output_folder()
+ @property
+ def _soil_obj(self) -> Soil:
+ return self.__soil_obj
+
+ @_soil_obj.setter
+ def _soil_obj(self, value: Soil):
+ if not isinstance(value, Soil):
+ raise TypeError(
+ f"Network soil object, a soil object must be passed. Type: {type(value)}"
+ )
+ self.__soil_obj = value
+
def _create_output_folder(self):
if self.output_path == None:
raise AttributeError(f"To create output file you must set an output folder")
@@ -159,8 +188,14 @@ class Network:
idx=branch["id"],
supply_node=branch["supply node"],
demand_node=branch["demand node"],
- pipe_diameter=branch["pipe diameter [m]"],
+ pipe_ext_diameter=branch["pipe ext diameter [m]"],
+ pipe_thickness=branch["pipe thickness [m]"],
+ pipe_depth=branch["depth [m]"],
+ insulation_thickness=branch["insulation thickness [m]"],
+ pipe_conductivity=branch["pipe conductivity [W/(mK)]"],
+ insulation_conductivity=branch["insulation conductivity [W/(mK)]"],
nodes_objects_dict=self._nodes_object_dict,
+ soil_obj=self._soil_obj,
)
if "pipe length [m]" in branch.keys():
@@ -283,25 +318,105 @@ class Network:
excel_path: str,
number_of_timesteps: int,
):
- hydraulic = pd.read_excel(
+ boundaries = pd.read_excel(
excel_path,
- sheet_name="Hydraulic",
+ sheet_name=["Hydraulic", "Thermal"],
index_col=0,
header=[0, 1, 2],
)
- nodes = hydraulic["Node"]["Mass flow rate [kg/s]"]
+ nodes = boundaries["Hydraulic"]["Node"]["Mass flow rate [kg/s]"]
nodes_dict = nodes.to_dict(orient="List")
- branches = hydraulic["Branch"]["Pump pressure raise [Pa]"]
+ branches = boundaries["Hydraulic"]["Branch"]["Pump pressure raise [Pa]"]
branches_dict = branches.to_dict(orient="List")
# Just to convert in str and np.array
nodes_dict = {str(k): np.array(node) for k, node in nodes_dict.items()}
branches_dict = {
str(k): np.array(branch) for k, branch in branches_dict.items()
}
- self.load_boundary_conditions(nodes_dict, branches_dict, number_of_timesteps)
+ self.load_hydraulic_boundary_conditions(
+ nodes_dict, branches_dict, number_of_timesteps
+ )
+
+ nodes = boundaries["Thermal"]["Node"]["Temperature [°C]"]
+ nodes_dict = nodes.to_dict(orient="List")
+ nodes_dict = {str(k): np.array(node) for k, node in nodes_dict.items()}
+ self.load_thermal_boundary_conditions(nodes_dict, number_of_timesteps)
+
+ def load_thermal_boundary_conditions(
+ self,
+ nodes_boundary_conditions: dict,
+ number_of_timesteps: int,
+ ):
+ """
+ This method execute:
+ self.load_nodes_temperature_boundary_condition(nodes_boundary_conditions, number_of_timesteps)
+
+ Parameters
+ ----------
+ nodes_boundary_conditions : dict
+ Dictionary with the following sintax (temperature of the supply nodes):
+ "1" : np.array([50,55,55,....]),
+ "3" : np.array([70,75,78,....]),
+ .
+ .
+ ..
+
+ number_of_timesteps : int
+ Number of timesteps to be considered.
+
+ Returns
+ -------
+ None.
+ """
+ self.load_nodes_temperature_boundary_condition(
+ nodes_boundary_conditions, number_of_timesteps
+ )
+
+ def load_nodes_temperature_boundary_condition(
+ self, boundary_conditions: dict, number_of_timesteps: int
+ ):
+ """
+ This method loads the temperature boundary conditions of the nodes.
+ Use °C as reference unit.
+
+ Parameters
+ ----------
+ nodes_boundary_conditions : dict
+ Dictionary with the following sintax (temperature of the supply nodes):
+ "1" : np.array([50,55,55,....]),
+ "3" : np.array([70,75,78,....]),
+ .
+ .
+ ..
+
+ number_of_timesteps : int
+ Number of timesteps to be considered.
+
+ Returns
+ -------
+ None.
+ """
- def load_boundary_conditions(
+ for node_k, node in self._nodes_object_dict.items():
+ if node._node_type in ["supply"]:
+ try:
+ if len(boundary_conditions[node_k]) < number_of_timesteps:
+ raise ValueError(
+ f"Node {node._idx}: the boundary condition for the node is shorter than the number of timesteps. Provide a longer boundary condition"
+ )
+ node._boundary_temperature = boundary_conditions[node_k][
+ :number_of_timesteps
+ ]
+ except KeyError:
+ raise BoundaryConditionNotProvided(
+ f"Node {node._idx}: the node is a {node._node_type} node, but no boundary temperature is provided.\nPlease provide a boundary condition"
+ )
+ else:
+ # node._boundary_temperature = np.zeros(number_of_timesteps)
+ pass
+
+ def load_hydraulic_boundary_conditions(
self,
nodes_boundary_conditions: dict,
branches_boundary_conditions: dict,
@@ -309,8 +424,8 @@ class Network:
):
"""
This method execute:
- self.load_nodes_boundary_condition(nodes_boundary_conditions, number_of_timesteps)
- self.load_branches_boundary_condition(branches_boundary_conditions, number_of_timesteps)
+ self.load_nodes_mass_flow_rate_boundary_condition(nodes_boundary_conditions, number_of_timesteps)
+ self.load_branches_pump_pressure_raise_boundary_condition(branches_boundary_conditions, number_of_timesteps)
Parameters
@@ -339,14 +454,14 @@ class Network:
None.
"""
- self.load_nodes_boundary_condition(
+ self.load_nodes_mass_flow_rate_boundary_condition(
nodes_boundary_conditions, number_of_timesteps
)
- self.load_branches_boundary_condition(
+ self.load_branches_pump_pressure_raise_boundary_condition(
branches_boundary_conditions, number_of_timesteps
)
- def load_nodes_boundary_condition(
+ def load_nodes_mass_flow_rate_boundary_condition(
self, boundary_conditions: dict, number_of_timesteps: int
):
"""
@@ -392,7 +507,7 @@ class Network:
else:
node._boundary_mass_flow_rate = np.zeros(number_of_timesteps)
- def load_branches_boundary_condition(
+ def load_branches_pump_pressure_raise_boundary_condition(
self, boundary_conditions: dict, number_of_timesteps: int
):
"""
@@ -443,7 +558,27 @@ class Network:
x0 = self._generate_hydraulic_balance_starting_vector()
x = root(hydraulic_balance_system, x0, args=(q, self), method="hybr")
self._set_hydraulic_balance_results_vector(x.x)
- return x.x
+ return x.x, q, x0
+
+ def solve_thermal_balance(self, timestep: int, time_interval: int = 3600):
+ # Boundary condition
+ q = self._generate_thermal_balance_boundary_condition(timestep, time_interval)
+ # First try vector
+ ################################################################
+ # DO NOT USE thermal_balance_system_optimization: WRONG RESULTS
+ # x0 = self._generate_thermal_balance_starting_vector()
+ # x = root(
+ # thermal_balance_system_optimization,
+ # x0,
+ # args=(q, self, time_interval),
+ # method="hybr",
+ # )
+ ################################################################
+
+ x, A, q = thermal_balance_system_inverse(self, q, time_interval)
+ self._set_thermal_balance_results_vector(x)
+
+ return x
def _generate_hydraulic_balance_boundary_condition(self, timestep):
q = []
@@ -496,6 +631,71 @@ class Network:
[branches_mass_flow_rates, nodes_pressures, branches_friction_factors]
)
+ def _generate_thermal_balance_boundary_condition(self, timestep, time_interval):
+ """
+ Generate thermal balance know term
+ Equations are node mixing balances and branches energy balance
+
+ Parameters
+ ----------
+ timestep : int
+ This is the current time step the simulation is calculating.
+ time_interval : int
+ The time interval between timestep in seconds.
+
+ Raises
+ ------
+ IndexError
+ If the timestep is over the boundary condition.
+
+ Returns
+ -------
+ np.array
+ array of the known terms.
+
+ """
+
+ q = []
+ for node in self._nodes_object_ordered_list:
+ try:
+ q.append(node._boundary_temperature[timestep])
+ except AttributeError:
+ q.append(0.0) # This is the case of a
+ except IndexError:
+ raise IndexError(
+ f"Node {node._idx}: selected timestep {timestep} longer than boundary conditions. "
+ )
+ for branch in self._branches_object_ordered_list:
+
+ C = branch.get_dynamic_capacity()
+ f_loss = branch.ground_loss_factor
+ T_ground = self._soil_obj.get_soil_temperature()
+
+ q.append(C * branch._branch_temperature / time_interval + f_loss * T_ground)
+ return np.array(q)
+
+ def _generate_thermal_balance_starting_vector(self):
+ """
+ Generate the starting guess vector from the value of the previous timestep
+ stored in the nodes and branches abjects
+
+ Returns
+ -------
+ x : np.array
+ array with the first try value [nodes_temperatures, branches_temperatures].
+
+ """
+ nodes_temperatures = np.array(
+ [node._node_temperature for node in self._nodes_object_ordered_list]
+ )
+ branches_temperatures = np.array(
+ [
+ branch._branch_temperature
+ for branch in self._branches_object_ordered_list
+ ]
+ )
+ return np.hstack([nodes_temperatures, branches_temperatures])
+
def _set_hydraulic_balance_results_vector(self, x):
"""
Set the new status variables to the nodes and branches objects
@@ -530,6 +730,39 @@ class Network:
):
node._node_pressure = pressure
+ def _set_thermal_balance_results_vector(self, x):
+ """
+ Set the new status variables to the nodes and branches objects
+
+ Parameters
+ ----------
+ x : np.array
+ array with the results of the hydraulic [nodes_temperatures, branches_temperatures].
+
+ Returns
+ -------
+ None.
+
+ """
+ new_nodes_temperatures = x[: self._nodes_number]
+ new_branches_temperatures = x[
+ self._nodes_number : (self._branches_number + self._nodes_number)
+ ]
+ for temp, node in zip(
+ new_nodes_temperatures,
+ self._nodes_object_ordered_list,
+ ):
+ node._node_temperature = temp
+ for temp, branch in zip(
+ new_branches_temperatures,
+ self._branches_object_ordered_list,
+ ):
+ branch._branch_temperature = temp
+
+ def save_results(self):
+ self.save_hydraulic_results()
+ self.save_thermal_results()
+
def save_hydraulic_results(self):
if self.output_path == None:
logging.warning(
@@ -540,6 +773,16 @@ class Network:
self.save_nodes_pressures()
self.save_branches_mass_flow_rates()
+ def save_thermal_results(self):
+ if self.output_path == None:
+ logging.warning(
+ f"Output folder not provided, results will be saved in the working directory"
+ )
+ self.output_path = os.path.join(".")
+ self._create_output_folder()
+ self.save_nodes_temperatures()
+ self.save_branches_temperatures()
+
def save_nodes_pressures(self):
nodes_pressures_header = ""
matrix = []
@@ -564,8 +807,36 @@ class Network:
branches.write(branches_pressures_header + "\n")
np.savetxt(branches, matrix, delimiter=",", fmt="%.2f")