-
Notifications
You must be signed in to change notification settings - Fork 314
Expand file tree
/
Copy pathcontrol_volume1d.py
More file actions
2873 lines (2549 loc) · 114 KB
/
Copy pathcontrol_volume1d.py
File metadata and controls
2873 lines (2549 loc) · 114 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
# Import Python libraries
import copy
from enum import Enum
# Import Pyomo libraries
from pyomo.environ import (
ComponentMap,
Constraint,
Expression,
Param,
Reals,
TransformationFactory,
units as pyunits,
Var,
Reference,
value,
)
from pyomo.dae import ContinuousSet, DerivativeVar
from pyomo.common.config import ConfigValue, In
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.base.control_volume_base import ControlVolumeScalerBase
from idaes.core.scaling import DefaultScalingRecommendation
from idaes.core.util.exceptions import (
BalanceTypeNotSupportedError,
BurntToast,
ConfigurationError,
PropertyNotSupportedError,
)
from idaes.core.util.misc import add_object_reference
from idaes.core.util.config import is_transformation_method, is_transformation_scheme
from idaes.core.util import scaling as iscale
import idaes.logger as idaeslog
__author__ = "Andrew Lee, Jaffer Ghouse, Douglas Allan"
_log = idaeslog.getLogger(__name__)
# TODO : Custom terms in material balances, other types of material balances
# Diffusion terms need to be added
# Enumerate options for area
class DistributedVars(Enum):
"""
Enum indicating if a variable is constant across the spatial domain.
"""
variant = 0
uniform = 1
class ControlVolume1DScaler(ControlVolumeScalerBase):
"""
Scaler object for the ControlVolume1D
"""
DEFAULT_SCALING_FACTORS = {
# We could scale length and area 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.
"area": DefaultScalingRecommendation.userInputRequired,
"length": DefaultScalingRecommendation.userInputRequired,
"phase_fraction": 10, # May have already been created by property package
}
_weight_attr_name = "length"
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
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
"""
if model.flow_direction is FlowDirection.forward:
x_in = model.properties.index_set().first()
elif model.flow_direction is FlowDirection.backward:
x_in = model.properties.index_set().last()
elif model.flow_direction is FlowDirection.notSet:
raise RuntimeError(
"Scaler called on ControlVolume1D without a flow "
"direction set. The unit model containing the ControlVolume1D "
"should use the add_geometry method to specify a flow direction "
"as part of model construction."
)
else:
raise BurntToast(
"Unknown flow direction specified. This indicates "
"a new flow direction was added without support being "
"extended to the scaler. Please contact the IDAES "
"development team with this error."
)
self.propagate_state_scaling(
target_state=model.properties,
source_state=model.properties[x_in],
overwrite=overwrite,
)
self.call_submodel_scaler_method(
submodel=model.properties,
submodel_scalers=submodel_scalers,
method="variable_scaling_routine",
overwrite=overwrite,
)
for v in model.area.values():
self.scale_variable_by_default(v, overwrite=overwrite)
self.scale_variable_by_default(model.length, 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
)
if hasattr(model, "_flow_terms"): # pylint: disable=protected-access
for idx, v in model._flow_terms.items():
self.scale_variable_by_definition_constraint(
v, model.material_flow_linking_constraints[idx], overwrite=overwrite
)
if hasattr(model, "material_flow_dx"):
for idx, v in model._flow_terms.items(): # pylint: disable=protected-access
# As domain is normalized, derivative should have same
# scale as flow
self.scale_variable_by_component(
model.material_flow_dx[idx], v, overwrite=overwrite
)
# TODO elemental flows
# if hasattr(self, "elemental_flow_term"):
# for (t, x, e), v in self.elemental_flow_term.items():
# flow_basis = self.properties[t, x].get_material_flow_basis()
# sf = iscale.min_scaling_factor(
# [
# self.properties[t, x].get_material_density_terms(p, j)
# for (p, j) in phase_component_set
# ],
# default=1,
# warning=True,
# )
# if flow_basis == MaterialFlowBasis.molar:
# sf *= 1
# elif flow_basis == MaterialFlowBasis.mass:
# # MW scaling factor is the inverse of its value
# sf *= value(self.properties[t, x].mw_comp[j])
# iscale.set_scaling_factor(v, sf)
# if hasattr(self, "elemental_flow_dx"):
# for (t, x, e), v in self.elemental_flow_dx.items():
# if iscale.get_scaling_factor(v) is None:
# # As domain is normalized, scale should be equal to flow
# sf = iscale.get_scaling_factor(self.elemental_flow_term[t, x, e])
# iscale.set_scaling_factor(v, sf)
if hasattr(model, "_enthalpy_flow"):
for (
idx,
v,
) in model._enthalpy_flow.items(): # pylint: disable=protected-access
self.scale_variable_by_definition_constraint(
v, model.enthalpy_flow_linking_constraint[idx], overwrite=overwrite
)
if hasattr(model, "enthalpy_flow_dx"):
for (
idx,
v,
) in model._enthalpy_flow.items(): # pylint: disable=protected-access
# Normalized domain, so scale should be the same as flow
# TODO is this correct?
self.scale_variable_by_component(
model.enthalpy_flow_dx[idx], v, overwrite=overwrite
)
if hasattr(model, "pressure_dx"):
for (t, x), v in model.pressure_dx.items():
self.scale_variable_by_component(
v, model.properties[t, x].pressure, overwrite=overwrite
)
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
"""
self.call_submodel_scaler_method(
submodel=model.properties,
submodel_scalers=submodel_scalers,
method="constraint_scaling_routine",
overwrite=overwrite,
)
super().constraint_scaling_routine(
model, overwrite=overwrite, submodel_scalers=submodel_scalers
)
if hasattr(model, "material_flow_linking_constraints"):
for idx, v in model._flow_terms.items(): # pylint: disable=protected-access
self.scale_constraint_by_component(
model.material_flow_linking_constraints[idx], v, overwrite=overwrite
)
# TODO element balance
# if hasattr(model, "elemental_flow_constraint"):
# for idx, c in model.elemental_flow_constraint.items():
# self.scale_constraint_by_component(
# c,
# model.elemental_flow_term[idx],
# overwrite=overwrite
# )
if hasattr(model, "enthalpy_flow_linking_constraint"):
for idx, v in model._enthalpy_flow.items():
self.scale_constraint_by_component(
model.enthalpy_flow_linking_constraint[idx], v, overwrite=overwrite
)
if hasattr(model, "material_flow_dx_disc_eq"):
for idx, c in model.material_flow_dx_disc_eq.items():
self.scale_constraint_by_component(
c, model.material_flow_dx[idx], overwrite=overwrite
)
if hasattr(model, "_flow_terms_length_domain_cont_eq"):
for (
idx,
c,
) in (
model._flow_terms_length_domain_cont_eq.items()
): # pylint: disable=protected-access
self.scale_constraint_by_component(
c,
model._flow_terms[idx], # pylint: disable=protected-access
overwrite=overwrite,
)
if hasattr(model, "enthalpy_flow_dx_disc_eq"):
for idx, c in model.enthalpy_flow_dx_disc_eq.items():
self.scale_constraint_by_component(
c, model.enthalpy_flow_dx[idx], overwrite=overwrite
)
if hasattr(model, "_enthalpy_flow_length_domain_cont_eq"):
for (
idx,
c,
) in (
model._enthalpy_flow_length_domain_cont_eq.items()
): # pylint: disable=protected-access
self.scale_constraint_by_component(
c,
model._enthalpy_flow[idx], # pylint: disable=protected-access
overwrite=overwrite,
)
if hasattr(model, "pressure_dx_disc_eq"):
for idx, c in model.pressure_dx_disc_eq.items():
self.scale_constraint_by_component(
c, model.pressure_dx[idx], overwrite=overwrite
)
if hasattr(model, "pressure_length_domain_cont_eq"):
for (t, x), c in model.pressure_length_domain_cont_eq.items():
self.scale_constraint_by_component(
c, model.properties[t, x].pressure, overwrite=overwrite
)
# TODO element flow
# if hasattr(model, "element_flow_dx_disc_eq"):
# for idx, c in model.element_flow_dx_disc_eq.items():
# self.scale_constraint_by_component(
# c,
# model.element_flow_dx[idx],
# overwrite=overwrite
# )
# element_flow_dx_cont_eq
@declare_process_block_class(
"ControlVolume1DBlock",
doc="""
ControlVolume1DBlock is a specialized Pyomo block for IDAES control volume
blocks discretized in one spatial direction, and contains instances of
ControlVolume1DBlockData.
ControlVolume1DBlock should be used for any control volume with a defined
volume and distinct inlets and outlets where there is a single spatial
domain parallel to the material flow direction. This encompasses unit
operations such as plug flow reactors and pipes.""",
)
class ControlVolume1DBlockData(ControlVolumeBlockData):
"""
1-Dimensional ControlVolume Class
This class forms the core of all 1-D 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 = ControlVolume1DScaler
CONFIG = ControlVolumeBlockData.CONFIG()
CONFIG.declare(
"area_definition",
ConfigValue(
default=DistributedVars.uniform,
domain=In(DistributedVars),
description="Argument for defining form of area variable",
doc="""Argument defining whether area variable should be spatially
variant or not. **default** - DistributedVars.uniform.
**Valid values:** {
DistributedVars.uniform - area does not vary across spatial domain,
DistributedVars.variant - area can vary over the domain and is indexed
by time and space.}""",
),
)
CONFIG.declare(
"transformation_method",
ConfigValue(
default=None,
domain=is_transformation_method,
description="DAE transformation method",
doc="""Method to use to transform domain. Must be a method recognised
by the Pyomo TransformationFactory.""",
),
)
CONFIG.declare(
"transformation_scheme",
ConfigValue(
default=None,
domain=is_transformation_scheme,
description="DAE transformation scheme",
doc="""Scheme to use when transforming domain. See Pyomo
documentation for supported schemes.""",
),
)
CONFIG.declare(
"finite_elements",
ConfigValue(
default=None,
domain=int,
description="Number of finite elements",
doc="""Number of finite elements to use in transformation (equivalent
to Pyomo nfe argument).""",
),
)
CONFIG.declare(
"collocation_points",
ConfigValue(
default=None,
domain=int,
description="Number of collocation points",
doc="""Number of collocation points to use (equivalent to Pyomo ncp
argument).""",
),
)
@property
def flow_direction(self):
"""
Property giving the flow direction in the ControlVolume1D
"""
return self._flow_direction
def build(self):
"""
Build method for ControlVolume1DBlock blocks.
Returns:
None
"""
# Call build method from base class
super(ControlVolume1DBlockData, self).build()
self._validate_config_args()
self._flow_direction = FlowDirection.notSet
def _validate_config_args(self):
# Validate DAE config arguments
if self.config.transformation_method is None:
raise ConfigurationError(
"{} was not provided a value for the transformation_method"
" configuration argument. Please provide a valid value.".format(
self.name
)
)
if self.config.transformation_scheme is None:
raise ConfigurationError(
"{} was not provided a value for the transformation_scheme"
" configuration argument. Please provide a valid value.".format(
self.name
)
)
elif (
self.config.transformation_method == "dae.finite_difference"
and self.config.transformation_scheme not in ["BACKWARD", "FORWARD"]
) or (
self.config.transformation_method == "dae.collocation"
and self.config.transformation_scheme
not in ["LAGRANGE-LEGENDRE", "LAGRANGE-RADAU"]
):
raise ConfigurationError(
"{} transformation_scheme configuration argument is not "
"consistent with transformation_method argument. See Pyomo"
" documentation for argument options.".format(self.name)
)
def add_geometry(
self,
length_domain=None,
length_domain_set=None,
length_var=None,
flow_direction=FlowDirection.forward,
):
"""
Method to create spatial domain and volume Var in ControlVolume.
Args:
length_domain: (optional) a ContinuousSet to use as the length
domain for the ControlVolume. If not provided, a new
ContinuousSet will be created (default=None). ContinuousSet
should be normalized to run between 0 and 1.
length_domain_set: (optional) list of point to use to initialize
a new ContinuousSet if length_domain is not provided (default = [0.0, 1.0]).
length_var: (optional) external variable to use for the length of
the spatial domain. If a variable is provided, a reference
will be made to this in place of the length Var.
flow_direction: argument indicating direction of material flow
relative to length domain. Valid values:
* FlowDirection.forward (default), flow goes from 0 to 1.
* FlowDirection.backward, flow goes from 1 to 0
Returns:
None
"""
units = self.config.property_package.get_metadata().get_derived_units
if length_domain is not None:
# Validate domain and make a reference
if isinstance(length_domain, ContinuousSet):
add_object_reference(self, "length_domain", length_domain)
else:
raise ConfigurationError(
"{} length_domain argument must be a Pyomo "
"ContinuousSet object".format(self.name)
)
else:
# Create new length domain
if length_domain_set is None:
length_domain_set = [0.0, 1.0]
self.length_domain = ContinuousSet(
bounds=(0.0, 1.0),
initialize=length_domain_set,
doc="Normalized length domain",
)
# Validated and create flow direction attribute
if flow_direction in (flwd for flwd in FlowDirection):
self._flow_direction = flow_direction
else:
raise ConfigurationError(
"{} invalid value for flow_direction "
"argument. Must be a FlowDirection Enum.".format(self.name)
)
if flow_direction is FlowDirection.forward:
self._flow_direction_term = -1
else:
self._flow_direction_term = 1
# Add geometry variables and constraints
if self.config.area_definition == DistributedVars.variant:
self.area = Var(
self.flowsheet().time,
self.length_domain,
initialize=1.0,
doc="Cross-sectional area of Control Volume",
units=units("area"),
)
else:
self.area = Var(
initialize=1.0,
doc="Cross-sectional area of Control Volume",
units=units("area"),
)
if length_var is not None:
# Validate length_Var and add a reference
if not isinstance(length_var, (Var, Param, Expression)):
raise ConfigurationError(
f"{self.name} length_var must be a Pyomo Var, Param or "
"Expression."
)
elif length_var.is_indexed():
raise ConfigurationError(
f"{self.name} length_var must be a scalar (unindexed) component."
)
add_object_reference(self, "length", length_var)
else:
self.length = Var(
initialize=1.0, doc="Length of Control Volume", units=units("length")
)
def add_state_blocks(
self, information_flow=FlowDirection.forward, has_phase_equilibrium=None
):
"""
This method constructs the 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
)
)
# d0 is config for defined state d1 is config for not defined state
d0 = dict(**self.config.property_package_args)
d0.update(has_phase_equilibrium=has_phase_equilibrium, defined_state=True)
d1 = copy.copy(d0)
d1["defined_state"] = False
def idx_map(i): # i = (t, x)
if (
information_flow == FlowDirection.forward
and i[1] == self.length_domain.first()
):
return 0
elif (
information_flow == FlowDirection.backward
and i[1] == self.length_domain.last()
):
return 0
else:
return 1
self.properties = self.config.property_package.build_state_block(
self.flowsheet().time,
self.length_domain,
doc="Material properties",
initialize={0: d0, 1: d1}, # TODO: What if the domain has different bounds?
idx_map=idx_map,
)
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
)
)
# TODO : Should not have ReactionBlock at inlet
tmp_dict = dict(**self.config.reaction_package_args)
tmp_dict["state_block"] = self.properties
tmp_dict["has_equilibrium"] = has_equilibrium
self.reactions = self.config.reaction_package.build_reaction_block(
self.flowsheet().time,
self.length_domain,
doc="Reaction properties in control volume",
**tmp_dict,
) # TODO: Do we need something similar to above to skip equilibrium at bounds?
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.component_list
phase_list = self.properties.phase_list
pc_set = self.properties.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:
for x in self.length_domain:
if self.reactions[t, x].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:
for x in self.length_domain:
if not self.properties[t, x].config.has_phase_equilibrium:
raise ConfigurationError(
"{} material balance was set to include phase "
"equilibrium, however the associated "
"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 units("length") is not None:
if (
self.properties[
self.flowsheet().time.first(), self.length_domain.first()
].get_material_flow_basis()
== MaterialFlowBasis.molar
):
holdup_l_units = units("amount") / units("length")
flow_units = units("flow_mole")
flow_l_units = units("flow_mole") / units("length")
elif (
self.properties[
self.flowsheet().time.first(), self.length_domain.first()
].get_material_flow_basis()
== MaterialFlowBasis.mass
):
holdup_l_units = units("mass") / units("length")
flow_units = units("flow_mass")
flow_l_units = units("flow_mass") / units("length")
else:
holdup_l_units = None
flow_units = None
flow_l_units = None
else:
holdup_l_units = None
flow_units = None
flow_l_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[
self.flowsheet().time.first(), self.length_domain.first()
].get_material_flow_basis()
== MaterialFlowBasis.other
):
acc_units = None
else:
acc_units = holdup_l_units / f_time_units
# 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(), self.length_domain.first()
].get_reaction_rate_basis()
== MaterialFlowBasis.molar
):
rxn_flow_l_units = units("flow_mole") / units("length")
elif (
self.reactions[
self.flowsheet().time.first(), self.length_domain.first()
].get_reaction_rate_basis()
== MaterialFlowBasis.mass
):
rxn_flow_l_units = units("flow_mass") / units("length")
else: # reaction basis not defined
rxn_flow_l_units = None
else: # reaction package is NoneType object
rxn_flow_l_units = None
else: # reaction package not defined
rxn_flow_l_units = None
# Material holdup and accumulation
if has_holdup:
self.material_holdup = Var(
self.flowsheet().time,
self.length_domain,
pc_set,
domain=Reals,
initialize=1.0,
doc="Material holdup per unit length",
units=holdup_l_units,
)
if dynamic:
self.material_accumulation = DerivativeVar(
self.material_holdup,
wrt=self.flowsheet().time,
doc="Material accumulation per unit length",
units=acc_units,
)
# Create material balance terms as required
# Flow terms and derivatives
self._flow_terms = Var(
self.flowsheet().time,
self.length_domain,
pc_set,
initialize=1.0,
doc="Flow terms for material balance equations",
units=flow_units,
)
@self.Constraint(
self.flowsheet().time,
self.length_domain,
pc_set,
doc="Material flow linking constraints",
)
def material_flow_linking_constraints(b, t, x, p, j):
return b._flow_terms[t, x, p, j] == b.properties[
t, x
].get_material_flow_terms(p, j)
self.material_flow_dx = DerivativeVar(
self._flow_terms,
wrt=self.length_domain,
doc="Partial derivative of material flow wrt to normalized length",
units=flow_units,
)
# 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,
self.length_domain,
pc_set,
domain=Reals,
initialize=0.0,
doc="Amount of component generated in "
"by kinetic reactions per unit length",
units=rxn_flow_l_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,
self.length_domain,
pc_set,
domain=Reals,
initialize=0.0,
doc="Amount of component generated by equilibrium "
"reactions per unit length",
units=rxn_flow_l_units,
) # use reaction package flow basis
# Inherent reaction generation
if self.properties.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,
self.length_domain,
pc_set,
domain=Reals,
initialize=0.0,
doc="Amount of component generated in control volume "
"by inherent reactions",
units=flow_l_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.length_domain,
self.config.property_package.phase_equilibrium_idx,
domain=Reals,
initialize=0.0,
doc="Amount of generation in unit by phase "
"equilibria per unit length",
units=flow_l_units,
) # use property package flow basis
# Material transfer term
if has_mass_transfer:
self.mass_transfer_term = Var(
self.flowsheet().time,
self.length_domain,
pc_set,
domain=Reals,
initialize=0.0,
doc="Component material transfer into unit per unit length",
units=flow_l_units,
)
# Create rules to substitute material balance terms
def phase_equilibrium_term(b, t, x, p, j):
if (
has_phase_equilibrium
and balance_type == MaterialBalanceType.componentPhase
):
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, x, r] * sd[r]
for r in b.config.property_package.phase_equilibrium_idx
)
else:
return 0
# 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,
self.length_domain,
pc_set,
doc="Material holdup calculations",
)