-
Notifications
You must be signed in to change notification settings - Fork 314
Expand file tree
/
Copy pathcontrol_volume0d.py
More file actions
2188 lines (1922 loc) · 87.8 KB
/
Copy pathcontrol_volume0d.py
File metadata and controls
2188 lines (1922 loc) · 87.8 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
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES).
#
# Copyright (c) 2018-2026 by the software owners: The Regents of the
# University of California, through Lawrence Berkeley National Laboratory,
# National Technology & Engineering Solutions of Sandia, LLC, Carnegie Mellon
# University, West Virginia University Research Corporation, et al.
# All rights reserved. Please see the files COPYRIGHT.md and LICENSE.md
# for full copyright and license information.
#################################################################################
"""
Base class for control volumes.
"""
# TODO: Missing docstrings
# pylint: disable=missing-function-docstring
# We use some private attributes here to hide these from the user
# pylint: disable=protected-access
__author__ = "Andrew Lee, Douglas Allan"
# Import Pyomo libraries
from pyomo.environ import Constraint, Reals, units as pyunits, Var, value
from pyomo.common.collections import ComponentMap
from pyomo.dae import DerivativeVar
from pyomo.common.deprecation import deprecation_warning
# Import IDAES cores
from idaes.core import (
declare_process_block_class,
ControlVolumeBlockData,
FlowDirection,
MaterialFlowBasis,
MaterialBalanceType,
)
from idaes.core.util.exceptions import (
BalanceTypeNotSupportedError,
BurntToast,
ConfigurationError,
PropertyNotSupportedError,
)
from idaes.core.util.tables import create_stream_table_dataframe
from idaes.core.util import scaling as iscale
import idaes.logger as idaeslog
from idaes.core.base.control_volume_base import ControlVolumeScalerBase
from idaes.core.scaling import DefaultScalingRecommendation
_log = idaeslog.getLogger(__name__)
# TODO : Custom terms in material balances, other types of material balances
# TODO : Improve flexibility for get_material_flow_terms and associated
class ControlVolume0DScaler(ControlVolumeScalerBase):
"""
Scaler object for the ControlVolume0D
"""
DEFAULT_SCALING_FACTORS = {
# We could scale volume by magnitude if it were being fixed
# by the user, but we often have the volume given by an
# equality constraint involving geometry in the parent
# unit model.
"volume": DefaultScalingRecommendation.userInputRequired,
"phase_fraction": 10, # May have already been created by property package
}
def _get_reference_state_block(self, model):
"""
This method gives the parent class ControlVolumeScalerBase
methods a state block with the same index as the material
and energy balances to get scaling information from
"""
return model.properties_out
def variable_scaling_routine(
self, model, overwrite: bool = False, submodel_scalers: ComponentMap = None
):
"""
Routine to apply scaling factors to variables in model.
Derived classes must overload this method.
Args:
model: model to be scaled
overwrite: whether to overwrite existing scaling factors
submodel_scalers: ComponentMap of Scalers to use for sub-models
Returns:
None
"""
self.call_submodel_scaler_method(
submodel=model.properties_in,
submodel_scalers=submodel_scalers,
method="variable_scaling_routine",
overwrite=overwrite,
)
self.propagate_state_scaling(
target_state=model.properties_out,
source_state=model.properties_in,
overwrite=overwrite,
)
self.call_submodel_scaler_method(
submodel=model.properties_out,
submodel_scalers=submodel_scalers,
method="variable_scaling_routine",
overwrite=overwrite,
)
if hasattr(model, "volume"):
for v in model.volume.values():
self.scale_variable_by_default(v, overwrite=overwrite)
if hasattr(model, "phase_fraction"):
for v in model.phase_fraction.values():
self.scale_variable_by_default(v, overwrite=overwrite)
super().variable_scaling_routine(
model, overwrite=overwrite, submodel_scalers=submodel_scalers
)
def constraint_scaling_routine(
self, model, overwrite: bool = False, submodel_scalers: ComponentMap = None
):
"""
Routine to apply scaling factors to constraints in model.
Derived classes must overload this method.
Args:
model: model to be scaled
overwrite: whether to overwrite existing scaling factors
submodel_scalers: ComponentMap of Scalers to use for sub-models
Returns:
None
"""
for props in [model.properties_in, model.properties_out]:
self.call_submodel_scaler_method(
submodel=props,
submodel_scalers=submodel_scalers,
method="constraint_scaling_routine",
overwrite=overwrite,
)
super().constraint_scaling_routine(
model, overwrite=overwrite, submodel_scalers=submodel_scalers
)
@declare_process_block_class(
"ControlVolume0DBlock",
doc="""
ControlVolume0DBlock is a specialized Pyomo block for IDAES non-discretized
control volume blocks, and contains instances of ControlVolume0DBlockData.
ControlVolume0DBlock should be used for any control volume with a defined
volume and distinct inlets and outlets which does not require spatial
discretization. This encompasses most basic unit models used in process
modeling.""",
)
class ControlVolume0DBlockData(ControlVolumeBlockData):
"""
0-Dimensional (Non-Discretized) ControlVolume Class
This class forms the core of all non-discretized IDAES models. It provides
methods to build property and reaction blocks, and add mass, energy and
momentum balances. The form of the terms used in these constraints is
specified in the chosen property package.
"""
default_scaler = ControlVolume0DScaler
def add_geometry(self):
"""
Method to create volume Var in ControlVolume.
Args:
None
Returns:
None
"""
units = self.config.property_package.get_metadata().get_derived_units
self.volume = Var(
self.flowsheet().time,
initialize=1.0,
doc="Volume of material in control volume",
units=units("volume"),
)
def add_state_blocks(
self, information_flow=FlowDirection.forward, has_phase_equilibrium=None
):
"""
This method constructs the inlet and outlet state blocks for the
control volume.
Args:
information_flow: a FlowDirection Enum indicating whether
information flows from inlet-to-outlet or outlet-to-inlet
has_phase_equilibrium: indicates whether equilibrium calculations
will be required in state blocks
package_arguments: dict-like object of arguments to be passed to
state blocks as construction arguments
Returns:
None
"""
if has_phase_equilibrium is None:
raise ConfigurationError(
"{} add_state_blocks method was not provided with a "
"has_phase_equilibrium argument.".format(self.name)
)
elif has_phase_equilibrium not in [True, False]:
raise ConfigurationError(
"{} add_state_blocks method was provided with an invalid "
"has_phase_equilibrium argument. Must be True or False".format(
self.name
)
)
tmp_dict = dict(**self.config.property_package_args)
tmp_dict["has_phase_equilibrium"] = has_phase_equilibrium
# tmp_dict["parameters"] = self.config.property_package
if information_flow == FlowDirection.forward:
tmp_dict["defined_state"] = True
elif information_flow == FlowDirection.backward:
tmp_dict["defined_state"] = False
else:
raise ConfigurationError(
"{} invalid value for information_flow argument. "
"Valid values are FlowDirection.forward and "
"FlowDirection.backward".format(self.name)
)
self.properties_in = self.config.property_package.build_state_block(
self.flowsheet().time, doc="Material properties at inlet", **tmp_dict
)
# Reverse defined_state
tmp_dict_2 = dict(**tmp_dict)
tmp_dict_2["defined_state"] = not tmp_dict["defined_state"]
self.properties_out = self.config.property_package.build_state_block(
self.flowsheet().time, doc="Material properties at outlet", **tmp_dict_2
)
def add_reaction_blocks(self, has_equilibrium=None):
"""
This method constructs the reaction block for the control volume.
Args:
has_equilibrium: indicates whether equilibrium calculations
will be required in reaction block
package_arguments: dict-like object of arguments to be passed to
reaction block as construction arguments
Returns:
None
"""
if has_equilibrium is None:
raise ConfigurationError(
"{} add_reaction_blocks method was not provided with a "
"has_equilibrium argument.".format(self.name)
)
elif has_equilibrium not in [True, False]:
raise ConfigurationError(
"{} add_reaction_blocks method was provided with an "
"invalid has_equilibrium argument. Must be True or False".format(
self.name
)
)
tmp_dict = dict(**self.config.reaction_package_args)
tmp_dict["state_block"] = self.properties_out
tmp_dict["has_equilibrium"] = has_equilibrium
self.reactions = self.config.reaction_package.build_reaction_block(
self.flowsheet().time,
doc="Reaction properties in control volume",
**tmp_dict,
)
def _add_material_balance_common(
self,
balance_type,
has_rate_reactions,
has_equilibrium_reactions,
has_phase_equilibrium,
has_mass_transfer,
custom_molar_term,
custom_mass_term,
):
# Get dynamic and holdup flags from config block
dynamic = self.config.dynamic
has_holdup = self.config.has_holdup
component_list = self.properties_in.component_list
phase_list = self.properties_in.phase_list
pc_set = self.properties_in.phase_component_set
# Check that reaction block exists if required
rblock = None
if has_rate_reactions or has_equilibrium_reactions:
try:
rblock = self.reactions
except AttributeError:
raise ConfigurationError(
"{} does not contain a Reaction Block, but material "
"balances have been set to contain reaction terms. "
"Please construct a reaction block before adding "
"balance equations.".format(self.name)
)
if has_equilibrium_reactions:
# Check that reaction block is set to calculate equilibrium
for t in self.flowsheet().time:
if self.reactions[t].config.has_equilibrium is False:
raise ConfigurationError(
"{} material balance was set to include "
"equilibrium reactions, however the associated "
"ReactionBlock was not set to include equilibrium "
"constraints (has_equilibrium_reactions=False). "
"Please correct your configuration arguments.".format(self.name)
)
if has_phase_equilibrium:
# First, check that phase equilibrium makes sense
if len(self.config.property_package.phase_list) < 2:
msg = (
"Property package has only one phase; control volume cannot include phase "
"equilibrium terms. Some property packages support phase equilibrium "
"implicitly in which case additional terms are not necessary. "
"You should set has_phase_equilibrium=False."
)
deprecation_warning(
msg=msg, logger=_log, version="2.0.0", remove_in="2.14.0"
)
has_phase_equilibrium = False
else:
# Check that state blocks are set to calculate equilibrium
for t in self.flowsheet().time:
if not self.properties_out[t].config.has_phase_equilibrium:
raise ConfigurationError(
"{} material balance was set to include phase "
"equilibrium, however the associated outlet "
"StateBlock was not set to include equilibrium "
"constraints (has_phase_equilibrium=False). Please"
" correct your configuration arguments.".format(self.name)
)
if not self.properties_in[t].config.has_phase_equilibrium:
raise ConfigurationError(
"{} material balance was set to include phase "
"equilibrium, however the associated inlet "
"StateBlock was not set to include equilibrium "
"constraints (has_phase_equilibrium=False). Please"
" correct your configuration arguments.".format(self.name)
)
# Get units from property package
units = self.config.property_package.get_metadata().get_derived_units
if (
self.properties_in[self.flowsheet().time.first()].get_material_flow_basis()
== MaterialFlowBasis.molar
):
flow_units = units("flow_mole")
elif (
self.properties_in[self.flowsheet().time.first()].get_material_flow_basis()
== MaterialFlowBasis.mass
):
flow_units = units("flow_mass")
else:
flow_units = None
# Get units for accumulation term if required
acc_units = None
if self.config.dynamic:
f_time_units = self.flowsheet().time_units
if (f_time_units is None) ^ (units("time") is None):
raise ConfigurationError(
"{} incompatible time unit specification between "
"flowsheet and property package. Either both must use "
"units, or neither.".format(self.name)
)
if f_time_units is None:
acc_units = None
elif (
self.properties_in[
self.flowsheet().time.first()
].get_material_flow_basis()
== MaterialFlowBasis.molar
):
acc_units = units("amount") / f_time_units
elif (
self.properties_in[
self.flowsheet().time.first()
].get_material_flow_basis()
== MaterialFlowBasis.mass
):
acc_units = units("mass") / f_time_units
else:
acc_units = None
# Check if reaction package exists, and get units
if hasattr(self.config, "reaction_package"):
if self.config.reaction_package is not None:
if (
self.reactions[
self.flowsheet().time.first()
].get_reaction_rate_basis()
== MaterialFlowBasis.molar
):
rxn_flow_units = units("flow_mole")
elif (
self.reactions[
self.flowsheet().time.first()
].get_reaction_rate_basis()
== MaterialFlowBasis.mass
):
rxn_flow_units = units("flow_mass")
else: # reaction basis not defined
rxn_flow_units = None
else: # reaction package is NoneType object
rxn_flow_units = None
else: # reaction package not defined
rxn_flow_units = None
# Test for components that must exist prior to calling this method
if has_holdup:
if not hasattr(self, "volume"):
raise ConfigurationError(
"{} control volume must have volume defined to have "
"holdup and/or rate reaction terms. Please call the "
"add_geometry method before adding balance equations.".format(
self.name
)
)
# Material holdup and accumulation
if has_holdup:
if (
self.properties_in[
self.flowsheet().time.first()
].get_material_flow_basis()
== MaterialFlowBasis.mass
):
holdup_units = units("mass")
elif (
self.properties_in[
self.flowsheet().time.first()
].get_material_flow_basis()
== MaterialFlowBasis.molar
):
holdup_units = units("amount")
else:
holdup_units = None
self.material_holdup = Var(
self.flowsheet().time,
pc_set,
domain=Reals,
initialize=1.0,
doc="Material holdup in control volume",
units=holdup_units,
)
if dynamic:
self.material_accumulation = DerivativeVar(
self.material_holdup,
wrt=self.flowsheet().time,
doc="Material accumulation in control volume",
units=acc_units,
)
# Create material balance terms as required
# Kinetic reaction generation
if has_rate_reactions:
if not hasattr(self.config.reaction_package, "rate_reaction_idx"):
raise PropertyNotSupportedError(
"{} Reaction package does not contain a list of rate "
"reactions (rate_reaction_idx), thus does not support "
"rate-based reactions.".format(self.name)
)
self.rate_reaction_generation = Var(
self.flowsheet().time,
pc_set,
domain=Reals,
initialize=0.0,
doc="Amount of component generated in unit by kinetic reactions",
units=rxn_flow_units,
) # use reaction package flow basis
# Equilibrium reaction generation
if has_equilibrium_reactions:
if not hasattr(self.config.reaction_package, "equilibrium_reaction_idx"):
raise PropertyNotSupportedError(
"{} Reaction package does not contain a list of "
"equilibrium reactions (equilibrium_reaction_idx), thus "
"does not support equilibrium-based reactions.".format(self.name)
)
self.equilibrium_reaction_generation = Var(
self.flowsheet().time,
pc_set,
domain=Reals,
initialize=0.0,
doc="Amount of component generated in control volume "
"by equilibrium reactions",
units=rxn_flow_units,
) # use reaction package flow basis
# Inherent reaction generation
if self.properties_out.include_inherent_reactions:
if not hasattr(self.config.property_package, "inherent_reaction_idx"):
raise PropertyNotSupportedError(
"{} Property package does not contain a list of "
"inherent reactions (inherent_reaction_idx), but "
"include_inherent_reactions is True.".format(self.name)
)
self.inherent_reaction_generation = Var(
self.flowsheet().time,
pc_set,
domain=Reals,
initialize=0.0,
doc="Amount of component generated in control volume "
"by inherent reactions",
units=flow_units,
) # use property package flow basis
# Phase equilibrium generation
if has_phase_equilibrium and balance_type == MaterialBalanceType.componentPhase:
if not hasattr(self.config.property_package, "phase_equilibrium_idx"):
raise PropertyNotSupportedError(
"{} Property package does not contain a list of phase "
"equilibrium reactions (phase_equilibrium_idx), thus does "
"not support phase equilibrium.".format(self.name)
)
self.phase_equilibrium_generation = Var(
self.flowsheet().time,
self.config.property_package.phase_equilibrium_idx,
domain=Reals,
initialize=0.0,
doc="Amount of generation in control volume by phase equilibria",
units=flow_units,
) # use property package flow basis
# Material transfer term
if has_mass_transfer:
self.mass_transfer_term = Var(
self.flowsheet().time,
pc_set,
domain=Reals,
initialize=0.0,
doc="Component material transfer into unit",
units=flow_units,
)
# Create rules to substitute material balance terms
# Accumulation term
def accumulation_term(b, t, p, j):
return (
pyunits.convert(b.material_accumulation[t, p, j], to_units=flow_units)
if dynamic
else 0
)
def phase_equilibrium_term(b, t, p, j):
sd = {}
for r in b.config.property_package.phase_equilibrium_idx:
if b.config.property_package.phase_equilibrium_list[r][0] == j:
if b.config.property_package.phase_equilibrium_list[r][1][0] == p:
sd[r] = 1
elif b.config.property_package.phase_equilibrium_list[r][1][1] == p:
sd[r] = -1
else:
sd[r] = 0
else:
sd[r] = 0
return sum(
b.phase_equilibrium_generation[t, r] * sd[r]
for r in b.config.property_package.phase_equilibrium_idx
)
# TODO: Need to set material_holdup = 0 for non-present component-phase
# pairs. Not ideal, but needed to close DoF. Is there a better way?
# Material Holdup
if has_holdup:
if not hasattr(self, "phase_fraction"):
self._add_phase_fractions()
@self.Constraint(
self.flowsheet().time, pc_set, doc="Material holdup calculations"
)
def material_holdup_calculation(b, t, p, j):
if (p, j) in pc_set:
return b.material_holdup[t, p, j] == (
b.volume[t]
* self.phase_fraction[t, p]
* b.properties_out[t].get_material_density_terms(p, j)
)
if has_rate_reactions:
# Add extents of reaction and stoichiometric constraints
self.rate_reaction_extent = Var(
self.flowsheet().time,
self.config.reaction_package.rate_reaction_idx,
domain=Reals,
initialize=0.0,
doc="Extent of kinetic reactions",
units=rxn_flow_units,
) # use reaction package flow basis
@self.Constraint(
self.flowsheet().time,
pc_set,
doc="Kinetic reaction stoichiometry constraint",
)
def rate_reaction_stoichiometry_constraint(b, t, p, j):
if (p, j) in pc_set:
rparam = rblock[t].params
return b.rate_reaction_generation[t, p, j] == (
sum(
rparam.rate_reaction_stoichiometry[r, p, j]
* b.rate_reaction_extent[t, r]
for r in b.config.reaction_package.rate_reaction_idx
)
)
else:
return Constraint.Skip
if has_equilibrium_reactions:
# Add extents of reaction and stoichiometric constraints
self.equilibrium_reaction_extent = Var(
self.flowsheet().time,
self.config.reaction_package.equilibrium_reaction_idx,
domain=Reals,
initialize=0.0,
doc="Extent of equilibrium reactions",
units=rxn_flow_units,
) # use reaction package flow basis
@self.Constraint(
self.flowsheet().time, pc_set, doc="Equilibrium reaction stoichiometry"
)
def equilibrium_reaction_stoichiometry_constraint(b, t, p, j):
if (p, j) in pc_set:
return b.equilibrium_reaction_generation[t, p, j] == (
sum(
rblock[t].params.equilibrium_reaction_stoichiometry[r, p, j]
* b.equilibrium_reaction_extent[t, r]
for r in b.config.reaction_package.equilibrium_reaction_idx
)
)
else:
return Constraint.Skip
if self.properties_out.include_inherent_reactions:
# Add extents of reaction and stoichiometric constraints
self.inherent_reaction_extent = Var(
self.flowsheet().time,
self.config.property_package.inherent_reaction_idx,
domain=Reals,
initialize=0.0,
doc="Extent of inherent reactions",
units=flow_units,
) # use property package flow basis
@self.Constraint(
self.flowsheet().time, pc_set, doc="Inherent reaction stoichiometry"
)
def inherent_reaction_stoichiometry_constraint(b, t, p, j):
if (p, j) in pc_set:
return b.inherent_reaction_generation[t, p, j] == (
sum(
b.properties_out[t].params.inherent_reaction_stoichiometry[
r, p, j
]
* b.inherent_reaction_extent[t, r]
for r in b.config.property_package.inherent_reaction_idx
)
)
else:
return Constraint.Skip
# Add custom terms and material balances
if balance_type == MaterialBalanceType.componentPhase:
def user_term_mol(b, t, p, j):
flow_basis = b.properties_out[t].get_material_flow_basis()
if flow_basis == MaterialFlowBasis.molar:
return custom_molar_term(t, p, j)
elif flow_basis == MaterialFlowBasis.mass:
try:
return (
custom_molar_term(t, p, j) * b.properties_out[t].mw_comp[j]
)
except AttributeError:
raise PropertyNotSupportedError(
"{} property package does not support "
"molecular weight (mw), which is required for "
"using custom terms in material balances.".format(self.name)
)
else:
raise ConfigurationError(
"{} contained a custom_molar_term argument, but "
"the property package used an undefined basis "
"(MaterialFlowBasis.other). Custom terms can "
"only be used when the property package declares "
"a molar or mass flow basis.".format(self.name)
)
def user_term_mass(b, t, p, j):
flow_basis = b.properties_out[t].get_material_flow_basis()
if flow_basis == MaterialFlowBasis.mass:
return custom_mass_term(t, p, j)
elif flow_basis == MaterialFlowBasis.molar:
try:
return (
custom_mass_term(t, p, j) / b.properties_out[t].mw_comp[j]
)
except AttributeError:
raise PropertyNotSupportedError(
"{} property package does not support "
"molecular weight (mw), which is required for "
"using custom terms in material balances.".format(self.name)
)
else:
raise ConfigurationError(
"{} contained a custom_mass_term argument, but "
"the property package used an undefined basis "
"(MaterialFlowBasis.other). Custom terms can "
"only be used when the property package declares "
"a molar or mass flow basis.".format(self.name)
)
@self.Constraint(self.flowsheet().time, pc_set, doc="Material balances")
def material_balances(b, t, p, j):
if (p, j) in pc_set:
rhs = b.properties_in[t].get_material_flow_terms(
p, j
) - b.properties_out[t].get_material_flow_terms(p, j)
if has_rate_reactions:
rhs += b.rate_reaction_generation[t, p, j] * b._rxn_rate_conv(
t, j
)
if has_equilibrium_reactions:
rhs += b.equilibrium_reaction_generation[t, p, j]
if b.properties_out.include_inherent_reactions:
rhs += b.inherent_reaction_generation[t, p, j]
if (
has_phase_equilibrium
and balance_type == MaterialBalanceType.componentPhase
):
rhs += phase_equilibrium_term(b, t, p, j)
if has_mass_transfer:
rhs += b.mass_transfer_term[t, p, j]
if custom_molar_term is not None:
rhs += user_term_mol(b, t, p, j)
if custom_mass_term is not None:
rhs += user_term_mass(b, t, p, j)
return accumulation_term(b, t, p, j) == rhs
else:
return Constraint.Skip
elif balance_type == MaterialBalanceType.componentTotal:
def user_term_mol(b, t, j):
flow_basis = b.properties_out[t].get_material_flow_basis()
if flow_basis == MaterialFlowBasis.molar:
return custom_molar_term(t, j)
elif flow_basis == MaterialFlowBasis.mass:
try:
return custom_molar_term(t, j) * b.properties_out[t].mw_comp[j]
except AttributeError:
raise PropertyNotSupportedError(
"{} property package does not support "
"molecular weight (mw), which is required for "
"using custom terms in material balances.".format(self.name)
)
else:
raise ConfigurationError(
"{} contained a custom_molar_term argument, but "
"the property package used an undefined basis "
"(MaterialFlowBasis.other). Custom terms can "
"only be used when the property package declares "
"a molar or mass flow basis.".format(self.name)
)
def user_term_mass(b, t, j):
flow_basis = b.properties_out[t].get_material_flow_basis()
if flow_basis == MaterialFlowBasis.mass:
return custom_mass_term(t, j)
elif flow_basis == MaterialFlowBasis.molar:
try:
return custom_mass_term(t, j) / b.properties_out[t].mw_comp[j]
except AttributeError:
raise PropertyNotSupportedError(
"{} property package does not support "
"molecular weight (mw), which is required for "
"using custom terms in material balances.".format(self.name)
)
else:
raise ConfigurationError(
"{} contained a custom_mass_term argument, but "
"the property package used an undefined basis "
"(MaterialFlowBasis.other). Custom terms can "
"only be used when the property package declares "
"a molar or mass flow basis.".format(self.name)
)
@self.Constraint(
self.flowsheet().time, component_list, doc="Material balances"
)
def material_balances(b, t, j):
cplist = []
for p in phase_list:
if (p, j) in pc_set:
cplist.append(p)
rhs = sum(
b.properties_in[t].get_material_flow_terms(p, j) for p in cplist
) - sum(
b.properties_out[t].get_material_flow_terms(p, j) for p in cplist
)
if has_rate_reactions:
rhs += sum(
b.rate_reaction_generation[t, p, j] for p in cplist
) * b._rxn_rate_conv(t, j)
if has_equilibrium_reactions:
rhs += sum(
b.equilibrium_reaction_generation[t, p, j] for p in cplist
)
if b.properties_out.include_inherent_reactions:
rhs += sum(b.inherent_reaction_generation[t, p, j] for p in cplist)
if has_mass_transfer:
rhs += sum(b.mass_transfer_term[t, p, j] for p in cplist)
if custom_molar_term is not None:
rhs += user_term_mol(b, t, j)
if custom_mass_term is not None:
rhs += user_term_mass(b, t, j)
return sum(accumulation_term(b, t, p, j) for p in cplist) == rhs
else:
raise BurntToast()
return self.material_balances
def add_phase_component_balances(
self,
has_rate_reactions=False,
has_equilibrium_reactions=False,
has_phase_equilibrium=False,
has_mass_transfer=False,
custom_molar_term=None,
custom_mass_term=None,
):
"""
This method constructs a set of 0D material balances indexed by time,
phase and component.
Args:
has_rate_reactions: whether default generation terms for rate
reactions should be included in material balances
has_equilibrium_reactions: whether generation terms should for
chemical equilibrium reactions should be included in
material balances
has_phase_equilibrium: whether generation terms should for phase
equilibrium behaviour should be included in material
balances
has_mass_transfer: whether generic mass transfer terms should be
included in material balances
custom_molar_term: a Pyomo Expression representing custom terms to
be included in material balances on a molar basis.
Expression must be indexed by time, phase list and component list
custom_mass_term: a Pyomo Expression representing custom terms to
be included in material balances on a mass basis.
Expression must be indexed by time, phase list and component list
Returns:
Constraint object representing material balances
"""
self._add_material_balance_common(
balance_type=MaterialBalanceType.componentPhase,
has_rate_reactions=has_rate_reactions,
has_equilibrium_reactions=has_equilibrium_reactions,
has_phase_equilibrium=has_phase_equilibrium,
has_mass_transfer=has_mass_transfer,
custom_molar_term=custom_molar_term,
custom_mass_term=custom_mass_term,
)
return self.material_balances
def add_total_component_balances(
self,
has_rate_reactions=False,
has_equilibrium_reactions=False,
has_phase_equilibrium=False,
has_mass_transfer=False,
custom_molar_term=None,
custom_mass_term=None,
):
"""
This method constructs a set of 0D material balances indexed by time
and component.
Args:
has_rate_reactions: whether default generation terms for rate
reactions should be included in material balances
has_equilibrium_reactions: whether generation terms should for
chemical equilibrium reactions should be included in
material balances
has_phase_equilibrium: whether generation terms should for phase
equilibrium behaviour should be included in material balances
has_mass_transfer: whether generic mass transfer terms should be
included in material balances
custom_molar_term: a Pyomo Expression representing custom terms to
be included in material balances on a molar basis.
Expression must be indexed by time, phase list and component list
custom_mass_term: a Pyomo Expression representing custom terms to
be included in material balances on a mass basis.
Expression must be indexed by time, phase list and component list
Returns:
Constraint object representing material balances
"""
self._add_material_balance_common(
balance_type=MaterialBalanceType.componentTotal,
has_rate_reactions=has_rate_reactions,
has_equilibrium_reactions=has_equilibrium_reactions,
has_phase_equilibrium=has_phase_equilibrium,
has_mass_transfer=has_mass_transfer,
custom_molar_term=custom_molar_term,
custom_mass_term=custom_mass_term,
)
return self.material_balances
def add_total_element_balances(
self,
has_rate_reactions=False,
has_equilibrium_reactions=False,
has_phase_equilibrium=False,
has_mass_transfer=False,
custom_elemental_term=None,
):
"""
This method constructs a set of 0D element balances indexed by time.
Args:
has_rate_reactions: whether default generation terms for rate
reactions should be included in material balances
has_equilibrium_reactions: whether generation terms should for
chemical equilibrium reactions should be included in
material balances
has_phase_equilibrium: whether generation terms should for phase
equilibrium behaviour should be included in material
balances
has_mass_transfer: whether generic mass transfer terms should be
included in material balances
custom_elemental_term: a Pyomo Expression representing custom
terms to be included in material balances on a molar
elemental basis. Expression must be indexed by time and
element list
Returns:
Constraint object representing material balances
"""
# Get dynamic and holdup flags from config block
dynamic = self.config.dynamic
has_holdup = self.config.has_holdup
component_list = self.properties_in.component_list
phase_list = self.properties_in.phase_list
phase_component_set = self.properties_in.phase_component_set
# Check that property package supports element balances