-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
1549 lines (1324 loc) · 53.9 KB
/
main.py
File metadata and controls
1549 lines (1324 loc) · 53.9 KB
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
### ALGORITMO DE ORDENAÇÃO DE EQUAÇÕES
from warnings import warn
import inspect
import numpy as np
import matplotlib.pyplot as plt
from typing import Tuple, Callable, Union, Dict, Generator
import networkx as nx
# TODO: Make it so that we cannot have two equipments or streams with the same name
# Also, add a few details to the aoe2 picking algorithm when mulitple choices are possible
# TODO: The dynamically defined functions are interesting, but I think it would
# be perhaps more useful if they were defined separately from the objects.
# We'll see in the future how this will develop.
# TODO: URGENT:
# Must stop checking and updating flow composition of outflows, since there
# may be chemical reactions that generate products. Keep the addition of the
# reactants though (never remove substances, only add them).
def aoe2(*fns: Callable, **xs: Union[float, int]):
"""Equation Ordering Algorithm.
The name aoe stands for "Algorítmo de Ordenação de Equações", which means
"Equation Ordering Algorithm". The '2' in the name stands for version 2.
Args:
*fns: Functions that represent the equations that must equal 0.
**xs: Specified/Known variable values.
Returns:
A tuple with the:
- The order in which the equations should be solved (expressed through a
list called ``func_seq``).
- The order in which the variables should be solved for (expressed
through a list called ``var_seq``).
- A list with the project variables (those that must be specified
or optimized).
"""
fns = list(fns)
for entry in fns:
if isinstance(entry, Process):
for equation in entry.equations():
fns.append(equation)
fns.remove(entry)
xs["flow"] = None
xs["equipment"] = None
xs["substance"] = None
# Function <-> Arguments dictionaries (NOT INVERSES)
func_dict = {} # function -> its arguments
var_dict = {} # arguments -> functions it relates to
for f in fns:
var_list = inspect.getfullargspec(f)[0]
func_dict[f] = var_list
for var in var_list:
if var not in var_dict:
var_dict[var] = [f]
else:
var_dict[var].append(f)
if 'plot' in var_dict:
raise NameError("Can't have 'plot' as variable name.")
elif 'graph' in var_dict:
raise NameError("Can't have 'graph' as a variable name.")
# Detecting whether or not the system of equations can be solved
if len(var_dict) < len(fns):
raise ValueError("Impossible system: more Equations than Variables.")
# Calculating the Incidence Matrix
inmx = np.zeros((len(fns), len(var_dict)))
for idx_f, f in enumerate(func_dict):
for idx_x, x in enumerate(var_dict):
if x in func_dict[f] and x not in xs:
inmx[idx_f, idx_x] = 1
#### Definitions
# Sequences:
func_seq = [None] * min(len(fns), len(var_dict))
var_seq = [None] * min(len(fns), len(var_dict))
# Insert indexes:
insert_idx_1 = 0
insert_idx_2 = -1
# List of indexes for opening variables:
go_back_list = []
# Dictionaries between number -> function/variable
num_func = {i: list(func_dict.keys())[i] for i in range(len(func_dict))}
num_var = {i: list(var_dict.keys())[i] for i in range(len(var_dict))}
# Dictionaries between function/variable -> number
func_num = {y: x for x, y in num_func.items()}
var_num = {y: x for x, y in num_var.items()}
def plot_incidence_matrix(inmx, ax=None):
if ax is None:
fig, ax = plt.subplots(1, 1)
img = ax.imshow(inmx)
ax.set_xticks([i for i in range(len(var_dict))])
ax.set_xticklabels([key for key in var_dict])
ax.set_yticks([i for i in range(len(fns))])
ax.set_yticklabels([key.__name__ for key in func_dict])
ax.set_ylabel("Functions")
ax.set_xlabel("Variables")
plt.show(block=True)
if ('graph' in xs) and (xs['graph']):
# TODO: solve the graph "problem"
# (Make a botch so that lines can 'bifurcate')
# Solution (implemented): make nodes for variables too.
function_graph = nx.Graph()
function_graph.add_nodes_from(list((f.__name__, {"subset": 1}) for f in fns))
edge_graph = nx.Graph()
edge_graph.add_nodes_from(list((f.__name__, {"subset": 1}) for f in fns))
edge_list = []
label_dict = {}
for variable in var_dict:
functions = var_dict[variable]
# if len(functions) > 2 or len(functions) == 1:
edge_graph.add_nodes_from([(variable, {'subset': 2})])
for idx1 in range(len(functions)):
if len(functions) == 1:
t = (variable, functions[idx1].__name__)
edge_list.append(t)
label_dict[t] = variable
for idx2 in range(idx1+1, len(functions)):
# if len(functions) > 2:
t1 = (functions[idx1].__name__, variable)
t2 = (variable, functions[idx2].__name__)
edge_list.append(t1)
edge_list.append(t2)
label_dict[t1] = variable
label_dict[t2] = variable
# elif len(functions) == 2:
# t = (functions[idx1].__name__, functions[idx2].__name__)
# edge_list.append(t)
# label_dict[t] = variable
edge_graph.add_edges_from(edge_list)
# graph.add_edges_from(edge_list)
function_graph_options = {
'with_labels': True,
'node_color': 'lightgray',
'node_size': 500
}
edge_graph_options = {
'with_labels': True,
'node_color': 'lightblue',
'node_size': 500
}
hidden_pos = nx.multipartite_layout(edge_graph)
pos = {}
for key in hidden_pos:
if key in function_graph.nodes():
pos[key] = hidden_pos[key]
def plot_graph(ax = None, show: bool = False):
nx.draw(edge_graph, hidden_pos, **edge_graph_options, ax=ax)
nx.draw(function_graph, pos, **function_graph_options, ax=ax)
nx.draw_networkx_edge_labels(edge_graph, hidden_pos,
edge_labels=label_dict, ax=ax)
nx.draw_networkx_edges(edge_graph, hidden_pos, ax=ax)
if show:
plt.show(block=True)
def update_graph():
# Deleting variable nodes that are no longer present:
for idx_x in range(len(var_dict)): # number of columns
var = num_var[idx_x]
if (sum(inmx[:, idx_x]) == 0):
if var in edge_graph.nodes():
edge_graph.remove_node(var)
if var in label_dict.values():
iterable = list(label_dict.keys())
for key in iterable:
if label_dict[key] == var:
del label_dict[key]
# elif sum(inmx[:, idx_x]) == 1:
# if var not in edge_graph.nodes():
# # check in the incidence matrix in the variable is still there for some reason.
# # it it only shows up once, and it didn't before, a node has to be created.
# edge_graph.add_node(var)
# idx_f = np.argmax(inmx[:, idx_x])
# edge_graph.add_edge(var, num_func[idx_f].__name__)
for idx_f in range(len(fns)):
f = num_func[idx_f].__name__
if sum(inmx[idx_f, :]) == 0 and f in edge_graph.nodes():
function_graph.remove_node(f)
edge_graph.remove_node(f)
# Updating label_dict:
iterable = list(label_dict.keys())
for key in iterable:
if f in key:
var = label_dict[key]
del label_dict[key]
if ('plot' in xs) and (xs['plot']):
# Base inmx0 for plotting:
inmx0 = np.zeros((len(fns), len(var_dict)))
for idx_f, f in enumerate(func_dict):
for idx_x, x in enumerate(var_dict):
if x in func_dict[f]:
inmx0[idx_f, idx_x] = 1
fig, axs = plt.subplots(1, 2)
fig.set_size_inches(14, 8)
ax = axs[0]
plot_graph(axs[1])
plot_incidence_matrix(inmx0, ax)
else:
plot_graph()
elif ('plot' in xs) and (xs['plot']):
# Base inmx0 for plotting:
inmx0 = np.zeros((len(fns), len(var_dict)))
for idx_f, f in enumerate(func_dict):
for idx_x, x in enumerate(var_dict):
if x in func_dict[f]:
inmx0[idx_f, idx_x] = 1
plot_incidence_matrix(inmx0)
# The actual loop.
while True:
if ('plot' in xs) and (xs['plot']):
if ('graph' in xs) and (xs['graph']):
fig, axs = plt.subplots(1, 2)
fig.set_size_inches(14, 8)
update_graph()
plot_graph(axs[1])
ax = axs[0]
else:
fig, ax = plt.subplots(1, 1)
plot_incidence_matrix(inmx, ax)
elif ('graph' in xs) and (xs['graph']):
update_graph()
plot_graph(show=True)
# Test for equations with only one variable:
for idx_f, row in enumerate(inmx):
if sum(row) == 1:
idx_x = np.argmax(row)
func_seq[insert_idx_1] = idx_f
var_seq[insert_idx_1] = idx_x
insert_idx_1 += 1
inmx[:, idx_x] = 0
inmx[idx_f, :] = 0
print(f"\nSingle variable equation: {num_func[idx_f].__name__};"
f"\nAssociated Variable: {num_var[idx_x]}.")
break
else:
# If the loop didn't break, then no variables were updated
# Loop through columns to check for variables of unit frequency:
instances = np.zeros(len(var_dict))
for idx_x in range(inmx.shape[1]):
col = inmx[:, idx_x]
instances[idx_x] = sum(col)
if sum(col) == 1:
idx_f = np.argmax(col)
func_seq[insert_idx_2] = idx_f
var_seq[insert_idx_2] = idx_x
insert_idx_2 -= 1
inmx[idx_f, :] = 0
print(f"\nVariable of unit frequency: {num_var[idx_x]};\n"
f"Associated Equation: {num_func[idx_f].__name__}.")
break
else:
# Loops
instances[instances == 0] = 100
idx_x = np.argmin(instances)
x = num_var[idx_x]
for f in var_dict[x]:
idx_f = func_num[f]
if idx_f not in func_seq:
func_seq[insert_idx_2] = idx_f
go_back_list.append(insert_idx_2)
insert_idx_2 -= 1
inmx[idx_f, :] = 0
print(f"\nLOOP:\n"
f"\tEquation: {num_func[idx_f].__name__};")
break
else:
raise RuntimeError("Unexpected Error.")
# If the incidence matrix is empty
if not inmx.any():
break
# Variáveis de Abertura:
open_vars = []
if go_back_list:
for idx in go_back_list:
idx_list = list(range(len(var_seq)+idx))
# idx_list.reverse()
max_idx = -1
for x in func_dict[num_func[func_seq[idx]]]:
# If the variable hasn't been attributed:
if var_num[x] not in var_seq:
# Going backwards in the sequence:
for loop_idx in idx_list:
if x in func_dict[num_func[func_seq[loop_idx]]]:
if loop_idx > max_idx:
var_seq[idx] = var_num[x]
max_idx = loop_idx
print(f"\nSmallest loop so far: "
f"{x} with {len(var_seq)+idx - loop_idx} "
f"equations of distance.")
# Skip to the next variable
break
open_x = num_var[var_seq[idx]]
print(f"\nOpening variable: {open_x}")
open_vars.append(open_x)
# for x in func_dict[num_func[func_seq[idx]]]: # ai ai
#
#
# if var_num[x] not in var_seq:
# var_seq[idx] = var_num[x]
# break
var_seq = [num_var[i] for i in var_seq]
func_seq = [num_func[i] for i in func_seq]
proj_vars = [x for x in var_dict if x not in var_seq]
print(
f"\nEquation sequence:\n",
*(f"\t- {func.__name__};\n" for func in func_seq),
f"\nVariable sequence:\n",
*(f"\t- {x};\n" for x in var_seq),
)
if open_vars:
print(
f"Opening variables:\n",
*(f"\t- {x};\n" for x in open_vars)
)
if proj_vars:
print(
f"Project Variables:\n",
*(f"\t- {x};\n" for x in proj_vars)
)
return func_seq, var_seq, proj_vars
class Substance:
"""Class for a chemical substance.
Class Attributes:
_name: The molecule's _name
mm: Molar mass (kg/kmol).
composition: The number of atoms of each element that the molecule has.
atomic_mass: Look-up table for atomic masses.
"""
name = None
mm = None
T_boil = None
latent_heat = None
composition = {
"H": 0,
"He": 0,
# ...
}
@staticmethod
def remove_substances(cls_inst: Union['Flow', 'Equipment'], *substances: 'Substance'):
"""Method for removing substances from a current or equipment.
"""
for substance in substances:
try:
cls_inst.composition.remove(substance)
except ValueError: # ValueError: list.remove(x): x not in list
continue
cls_inst._x.pop(f'x_{cls_inst.name}_{substance.name}')
@classmethod
def cp(substance, T, T_ref: None) -> float:
"""Function for calculating the substance's cp value at a given
temperature T or its mean cp value at a temperature range [T, T_ref]
(or [T, T_ref])
.. warning::
ENERGY BALANCES IMPLICITLY ASSUME THAT CP OF COMPLEX SOLUTIONS IS
THE WEIGHTED MEAN OF THE INDIVIDUAL SUBSTANCES' CPs.
Args:
T: The stream's temperature [K].
T_ref: The temperature we are using as a reference [K].
Returns:
The mean Cp value at the temperature interval.
If there's a phase change, then it will automatically add the
latent heat term in such a way that, when the result is multiplied
by (T-T_ref), we get the correct result for energy/mass flow rate
"""
if T_ref is not None:
if T < substance.T_boil and substance.T_boil < T_ref:
# it's divided by the (T-Tref) so we can get the correct
# values when we mutiply it by that factor
# Mean at liquid * (Tboil - T_ref)/(T-T_ref)
# + (latent_heat/(T - T_ref))
# + Mean at vapour * (T_ref - Tboil)/(T-T_ref)
pass
elif T > substance.T_boil and substance.T_boil > T_ref:
# Wait, is it the same expression? I think so.
pass
else:
# Do the mean at the interval
pass
else:
# Do the mean at the interval
pass
class Flow:
"""A process current.
TODO: There still need to be constant updates of the w, wmol, x, xmol
quantities.
Class Attributes:
tolerance: Tolerance for mass/molar fraction sum errors.
Attributes:
composition: A list with the substances present in the flow.
w: Flow rate (mass per unit time).
x: A ``dict`` for storing the value of the mass fractions.
Each entry corresponds to a component. Sum must
equal one. Unknown values are marked as ``None``.
wmol: Flow rate (mol per unit time).
xmol: Molar fractions.
T: Temperature (in K).
"""
tolerance = 0.05
def __init__(self, name: str, *substances: Substance, **info: float):
if substances == ():
warn("No substances informed.")
self.composition = list(substances)
self.equations = {} # Actual equations
self._equations = {} # Equations checked by aoe.
# Name and restriction addition:
if not isinstance(name, str):
raise TypeError("Please inform a valid name (string type).")
self._update_restriction(name) # self._name is defined here.
# Composition and flow rate information
self.w = None
self.x = {}
self._x = {}
for substance in substances:
self.x[substance] = None
self._x[f'x_{self.name}_{substance.name}'] = None
self.T = None
self.add_info(**info)
# Equipment (connection) information
self.leaves = None
self.enters = None
def __str__(self):
return self.name
def __contains__(self, item: Substance):
if item in self.composition:
return True
else:
return False
@property
def name(self):
return self._name
@staticmethod
def restriction(flow: 'Flow') -> float:
"""Mass fraction restriction equation (sum(x) = 1).
.. warning::
As of now, the code ignores the ``None`` values (considers them
as equal to zero). No Exception is raised.
Args:
flow: A Flow object
Returns:
The sum of the stream's mass fractions minus 1.
"""
x = list(flow.x.values())
try:
while True:
x.remove(None)
except ValueError: # list.remove(None): None not in list.
pass
# TODO: should an error be generated when None is still specified?
# added the "float" because I may change the type of x in the future.
return float(sum(x)) - 1
def add_info(self, **info: float):
# TODO: add this info to the equations? How will this work?
backup_x = self.x.copy()
dictionary = {substance.name: substance for substance in self.x}
try:
for kwarg in info:
data = info[kwarg]
if kwarg in dictionary:
if data > 1 or data < 0:
raise ValueError(
f"Informed an invalid value for a mass fraction: "
f"{kwarg} = {data}."
)
self.x[dictionary[kwarg]] = data
self._x[f"x_{self.name}_{kwarg}"] = data
# self.equations[f"x_{self.name}_{kwarg}"] = data
elif kwarg == "w":
if data < 0:
raise ValueError(
f"Informed a negative flow rate: "
f"{kwarg} = {data}."
)
self.w = data
# self.equations["w"] = data
# Add more information in the future.
else:
warn(f"User unknown specified property: {kwarg} = {data}.")
if self.restriction(self) > Flow.tolerance:
raise ValueError("Restriction Error: sum(x) > 1.")
except ValueError as e:
self.x = backup_x
raise ValueError(e)
def add_substances(self, *substances: Substance, **info: float):
"""Method for adding substances to the current.
Args:
substances: :class:`Substance` objects of the substances we want to
add.
info: Additional info we want to add the the flow's attributes. It
doesn't have to be related the the substances that are being
added.
"""
for substance in substances:
if substance in self.composition:
continue
else:
self.composition.append(substance)
self.x[substance] = None
self._x[f'x_{self.name}_{substance.name}'] = None
self.add_info(**info)
self._update_restriction(self.name) # Updating the restriction function
def remove_substances(self, *substances: Substance, **info: float):
for substance in substances:
if substance not in self.composition:
continue
else:
self._x.pop(f'x_{self.name}_{substance.name}')
self.x.pop(substance)
# Update mass and molar fractions
self.add_info(**info)
self._update_restriction(self.name)
def _update_restriction(self, name):
while True:
generator = (f'x_{name}_{substance.name}: None = None, '
for substance in self.composition)
args = "flow: 'Flow', "
for entry in generator:
args += entry
try:
string =\
f"""
def mass_fraction_restriction_{name}({args}) -> float:
'''Mass fraction restriction equation (sum(x) = 1).
This function is created dynamically with the
:func:`Flow._update_restriction` method. It should not be called by the
user, but only by the equation ordering algorithm.
'''
warn("Do not call protected methods.")
return Flow.restriction(flow)
self._equations['restriction'] = mass_fraction_restriction_{name}
"""
exec(string)
break
except SyntaxError:
name = input(
f"Invalid name: {name}. Please inform a new name.")
self._name = name
def _add_connections(
self, leaves: 'Equipment' = None, enters: 'Equipment' = None):
"""Method for beginning and end points for the flow.
Will be useful in the future when we define a :class:`Process` class.
"""
if leaves is not None:
self.leaves = leaves
# leaves.add_outflows(self)
if enters is not None:
self.enters = enters
# enters.add_inflows(self)
def _remove_connections(self, leaves: bool = False, enters: bool = False,
equipment: 'Equipment' = None):
"""Method for removing connections.
TODO: possibly remove 'leaves' and 'enters' arguments, since this
method should only be called through the remove_flow method (from
the Equipment class).
"""
if (not leaves) and (not enters) and equipment is None:
warn("No connection was removed because None were specified.")
if leaves:
# self.leaves.remove_flow(self)
print(f"Removed {self.leaves.name} from {self.name}.leaves.")
self.leaves = None
if enters:
# self.enters.remove_flow(self)
print(f"Removed {self.enters.name} from {self.name}.enters.")
self.enters = None
if equipment is not None:
if equipment == self.enters:
# self.enters.remove_flow(self)
print(f"Removed {self.enters.name} from {self.name}.enters.")
self.enters = None
elif equipment == self.leaves:
# self.leaves.remove_flow(self)
print(f"Removed {self.leaves.name} from {self.name}.leaves.")
self.leaves = None
else:
raise NameError(f"Equipment {equipment} isn't connected to this"
f" process current {self}."
f" It connects {self.leaves} to {self.enters}.")
class Equipment:
"""Class for equipments
TODO: There still need to be constant updates of the w and x
quantities.
"""
def __init__(self, name: str):
self._name = name
self.composition = []
self.w = None
self.x = {}
# Not yet implemented:
self._reaction = True
self.reaction_list = []
self.reaction_rate = {}
self.reaction_rate_mol = {}
self.inflow = []
self.outflow = []
self.equations = {}
self._equations = {}
self.heat = None # Heat
self.work = None # Work
self.T_ref = None # Reference Temperature for Enthalpy Calc.
def __str__(self):
return self.name
def __iter__(self):
for flow in self.outflow:
yield flow
for flow in self.inflow:
yield flow
def __contains__(self, item: Union[Substance, Flow]):
"""Tests if a Substance is present in the equipment, or if a Flow enters
or leaves it.
TODO: Add the possibility of item being a string
"""
if (item in self.inflow) or item in (self.outflow):
return True
elif item in self.composition:
return True
else:
return False
@property
def name(self):
return self._name
@property
def reaction(self):
return self._reaction
@staticmethod
def component_mass_balance(equipment: 'Equipment', substance: Substance) -> float:
"""Component Mass Balance for substance a given substance and equipment.
TODO: maybe raise an error if the return value goes over the tolerance.
"""
if substance not in equipment:
raise TypeError(
f"This equipment does not have this substance in it:"
f" {substance.name}"
)
inflows = equipment.inflow
outflows = equipment.outflow
result = 0
for flow in equipment:
if substance in flow:
if flow.w is None:
raise ValueError(
f"Uninitialized value for flow rate at stream: "
f"{flow.name}")
elif flow.x[substance] is None:
raise ValueError(
f"Uninitialized mass fraction at stream: {flow.name}")
if flow in outflows:
result += flow.w * flow.x[substance]
else:
result -= flow.w * flow.x[substance]
return result
@staticmethod
def energy_balance(equipment: 'Equipment', T_ref: float = None) -> float:
inflows = equipment.inflow
outflows = equipment.outflow
result = 0
if T_ref is None:
if equipment.T_ref is None:
T_ref = equipment.inflow[0].T
equipment.T_ref = T_ref
else:
T_ref = equipment.T_ref
else:
equipment.T_ref = T_ref
for flow in equipment:
for substance in flow:
if flow.w is None:
raise ValueError(
f"Uninitialized value for flow rate at stream:"
f" {flow.name}")
elif flow.x[substance] is None:
raise ValueError(
f"Uninitialized mass fraction at stream: {flow.name}")
else:
if flow in outflows:
sign = 1
elif flow in inflows:
sign = -1
else:
raise RuntimeError(
"Unexpected Error."
" Flow neither in inflow nor outflow")
result += sign * flow.w * flow.x[substance] * \
Substance.cp(substance, flow.T, T_ref) * \
(flow.T - T_ref)
if equipment.heat is not None:
result += equipment.heat
if equipment.work is not None:
result += equipment.heat
return result
def _update_balances(self):
"""Generates the component mass balances for each substance that comes
into the equipment, as well as the system's energy balance.
"""
name = self.name
while True:
try:
# Pick a substance
for substance in self.composition:
w = []
x = []
# Pick a stream:
for flow in self:
# If the substance is present on that stream:
if substance in flow:
w.append(f"W_{flow.name}")
mass_fraction = f"x_{flow.name}_{substance.name}"
if mass_fraction not in flow._x:
raise NameError(
f"Mass fraction {mass_fraction} not in the stream."
f" Possibly a naming error (check if the naming"
f" convention has changed). The stream contains"
f" the following mass fractions:\n{flow._x}.")
x.append(mass_fraction)
# mass balance:
args = "equipment: 'Equipment', substance: Substance, "
for w_val, x_val in zip(w, x):
args += f"{w_val}: None = None, "
args += f"{x_val}: None = None, "
string =\
f"""
def component_mass_balance_{name}_{substance.name}({args}) -> float:
'''Component Mass Balance for substance {substance.name}.
This function is generated automatically and dynamically by the
:func:`Equipment._update_mass_balance` method. It should only be used
by the equation ordering algorithm.
'''
warn("Do not call protected methods.")
return Equipment.component_mass_balance(equipment, substance)
self._equations['mass_balance_{name}_{substance.name}'] = \\
component_mass_balance_{name}_{substance.name}
"""
exec(string)
break
except SyntaxError:
name = input(
f"Invalid name: {name}. Please inform a new name."
)
self._name = name
w = []
x = []
T = []
for flow in self:
T.append(f"T_{flow.name}")
w.append(f"W_{flow.name}")
for substance in flow.composition:
mass_fraction = f"x_{flow.name}_{substance.name}"
if mass_fraction not in flow._x:
raise NameError(
f"Mass fraction {mass_fraction} not in the stream."
f" Possibly a naming error (check if the naming"
f" convention has changed). The stream contains"
f" the following mass fractions:\n{flow._x}.")
x.append(mass_fraction)
# energy balance:
# For the sake of generality, we'll assume each eqp. will have a T_ref
args = f"equipment: 'Equipment', Q_{name}: float = None," \
f" W_{name}: float = None, T_ref_{name}: float = None, "
for w_val in w:
args += f"{w_val}: None = None, "
for x_val in x:
args += f"{x_val}: None = None, "
for T_val in T:
args += f"{T_val}: None = None, "
string = \
f"""
def energy_balance_{name}({args}) -> float:
'''Energy balance for equipment {name}.
This function is generated automatically and dynamically by the
:func:`Equipment._update_balances` method. It should only be used
by the equation ordering algorithm.
'''
warn("Do not call protected methods.")
return Equipment.energy_balance(equipment)
self.equations['energy_balance_{name}'] = \\
energy_balance_{name}
"""
exec(string)
def add_inflows(self, *inflows: Flow):
"""Method for adding a current to the inflows.
Automatically adds new substances to the class's composition attribute.
Args:
*inflows: :class:`Flow` objects we want to add to the inflow.
"""
self._add_flow("inflow", "outflow", *inflows)
def add_outflows(self, *outflows: Flow):
"""Method for adding a current to the outflows.
Args:
*outflows: :class:`Flow` objects we want to add to the inflow.
"""
self._add_flow("outflow", "inflow", *outflows)
def _add_flow(self, direction: str, other_direction: str, *flows: Flow):
"""Adds flows to the the equipment
Args:
direction: "inflow" or "outflow".
other_direction: "outflow" or "inflow".
flows: :class:`Flow` objects we want to add to the in or outflow.
"""
attribute = getattr(self, direction)
other_attribute = getattr(self, other_direction)
for flow in flows:
if flow in attribute:
warn(f"Current {flow} already in {direction}, skipped.")
continue
elif flow in other_attribute:
warn(f"Current {flow} already in {other_direction}, make"
f" sure to correctly specify the flow direction. Nothing"
f" has been changed.")
continue
else:
attribute.append(flow)
if direction == 'inflow':
flow._add_connections(enters=self)
elif direction == 'outflow':
flow._add_connections(leaves=self)
# If a new substance is added:
# if direction == 'outflow':
# for substance in flow.composition:
# if substance not in self.composition:
# warn(f"Ouflow {flow.name} has a substance that does not"
# f" enter the equipment: {substance}.")
# composition attribute is already updated there^
self.update_composition()
def remove_flow(self, flow: Union[str, Flow]):
"""Method for removing a current from the in and outflows.
Args:
flow: Either a :class:`Flow` object or the name of an instance of
one.
"""
if isinstance(flow, Flow):
name = flow.name
elif isinstance(flow, str):
name = flow
pass
else:
raise TypeError(f"Invalid type: {type(flow)}."
f" Argument must be string or a 'Flow' instance.")
# Checking for its presence in the inflow
for object in self.inflow:
if object.name == name:
if isinstance(flow, str):
flow = object
flow._remove_connections(equipment=self)
self.inflow.remove(object)
# Checking for its presence in the outflow
for object in self.outflow:
if object.name == name:
if isinstance(flow, str):
flow = object
flow._remove_connections(equipment=self)
self.outflow.remove(object)
# Updating the equipment's and possibly the outflow's compositions:
# substances = []