epcsaft-pse 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- epcsaft_pse/__init__.py +9 -0
- epcsaft_pse/adapters.py +112 -0
- epcsaft_pse/block.py +313 -0
- epcsaft_pse/composition.py +175 -0
- epcsaft_pse/equilibrium.py +207 -0
- epcsaft_pse/examples/__init__.py +1 -0
- epcsaft_pse/examples/_salt_inputs.py +95 -0
- epcsaft_pse/examples/crystallizer.py +176 -0
- epcsaft_pse/examples/hybrid_brine.py +190 -0
- epcsaft_pse/examples/mcas_brine.py +116 -0
- epcsaft_pse/examples/reactive_sx.py +292 -0
- epcsaft_pse/examples/tests/__init__.py +1 -0
- epcsaft_pse/examples/tests/test_crystallizer.py +116 -0
- epcsaft_pse/examples/tests/test_hybrid_brine.py +77 -0
- epcsaft_pse/examples/tests/test_mcas_brine.py +76 -0
- epcsaft_pse/examples/tests/test_reactive_sx.py +129 -0
- epcsaft_pse/mscontactor.py +404 -0
- epcsaft_pse/py.typed +0 -0
- epcsaft_pse/solver.py +110 -0
- epcsaft_pse-0.2.0.dist-info/METADATA +383 -0
- epcsaft_pse-0.2.0.dist-info/RECORD +23 -0
- epcsaft_pse-0.2.0.dist-info/WHEEL +4 -0
- epcsaft_pse-0.2.0.dist-info/licenses/LICENSE +687 -0
epcsaft_pse/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Process systems engineering interfaces for the ePC-SAFT Engine."""
|
|
2
|
+
|
|
3
|
+
from .adapters import adapt_generic as adapt_generic
|
|
4
|
+
from .adapters import adapt_mcas as adapt_mcas
|
|
5
|
+
from .adapters import generic_property_configuration as generic_property_configuration
|
|
6
|
+
from .block import EpcsaftBlock as EpcsaftBlock
|
|
7
|
+
from .mscontactor import adapt_mscontactor as adapt_mscontactor
|
|
8
|
+
from .mscontactor import mscontactor_reactions as mscontactor_reactions
|
|
9
|
+
from .solver import get_coupled_cyipopt_solver as get_coupled_cyipopt_solver
|
epcsaft_pse/adapters.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""State block adapters for the WaterTAP and IDAES property packages."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from epcsaft import Mixture
|
|
7
|
+
from epcsaft.idaes import property_configuration
|
|
8
|
+
from idaes.core import MaterialFlowBasis # type: ignore[import-untyped]
|
|
9
|
+
from idaes.models.properties.modular_properties.state_definitions import FcTP, FTPx # type: ignore[import-untyped]
|
|
10
|
+
from pyomo.environ import value # type: ignore[import-untyped]
|
|
11
|
+
|
|
12
|
+
from .block import EpcsaftBlock
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def adapt_mcas(
|
|
16
|
+
state: Any,
|
|
17
|
+
*,
|
|
18
|
+
model: Mixture,
|
|
19
|
+
species: Mapping[str, str],
|
|
20
|
+
counter_ion: str | None = None,
|
|
21
|
+
composition: str | None = None,
|
|
22
|
+
**options: Any,
|
|
23
|
+
) -> EpcsaftBlock:
|
|
24
|
+
"""Bind an MCAS liquid state to an Engine block.
|
|
25
|
+
|
|
26
|
+
Composition defaults to MCAS's material-flow basis. Select
|
|
27
|
+
`conc_mass_phase_comp` to use MCAS mass concentrations. Name the
|
|
28
|
+
counter-ion for charged records. Make up charge on the MCAS state.
|
|
29
|
+
"""
|
|
30
|
+
if composition is None:
|
|
31
|
+
composition = {
|
|
32
|
+
MaterialFlowBasis.molar: "flow_mol_phase_comp",
|
|
33
|
+
MaterialFlowBasis.mass: "flow_mass_phase_comp",
|
|
34
|
+
}[state.get_material_flow_basis()]
|
|
35
|
+
if composition not in ("flow_mol_phase_comp", "flow_mass_phase_comp", "conc_mass_phase_comp"):
|
|
36
|
+
raise ValueError(f"Unsupported MCAS composition {composition!r}")
|
|
37
|
+
|
|
38
|
+
charges = dict(zip(model.component_ids, model.parameters.charge_numbers, strict=True))
|
|
39
|
+
for key, component in species.items():
|
|
40
|
+
if key not in state.component_list or component not in charges:
|
|
41
|
+
raise ValueError(f"Unknown MCAS or Engine species in mapping {key!r} -> {component!r}")
|
|
42
|
+
# MCAS stores charges for solutes only. Its solvent is neutral.
|
|
43
|
+
charge = value(state.charge_comp[key]) if key in state.params.solute_set else 0
|
|
44
|
+
if charge != charges[component]:
|
|
45
|
+
raise ValueError(
|
|
46
|
+
f"MCAS charge_comp for {key} is {charge:g}, but Engine charge for "
|
|
47
|
+
f"{component} is {charges[component]:g}"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
return EpcsaftBlock(
|
|
51
|
+
model=model,
|
|
52
|
+
state={"temperature": state.temperature, "pressure": state.pressure},
|
|
53
|
+
composition=getattr(state, composition),
|
|
54
|
+
index=("Liq",),
|
|
55
|
+
species=species,
|
|
56
|
+
counter_ion=counter_ion,
|
|
57
|
+
molar_masses=state.params.mw_comp,
|
|
58
|
+
**options,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def adapt_generic(
|
|
63
|
+
state: Any,
|
|
64
|
+
*,
|
|
65
|
+
model: Mixture,
|
|
66
|
+
phase: str | None = None,
|
|
67
|
+
species: Mapping[str, str] | None = None,
|
|
68
|
+
**options: Any,
|
|
69
|
+
) -> EpcsaftBlock:
|
|
70
|
+
"""Bind a Generic FcTP or FTPx phase to an Engine block with live species weights.
|
|
71
|
+
|
|
72
|
+
The phase defaults to the only phase in a single-phase package. The Engine
|
|
73
|
+
checks electroneutrality directly at the supplied composition.
|
|
74
|
+
"""
|
|
75
|
+
definition = state.params.config.state_definition
|
|
76
|
+
if definition not in (FcTP, FTPx):
|
|
77
|
+
raise ValueError("The Generic adapter requires the FcTP or FTPx state definition")
|
|
78
|
+
if phase is None:
|
|
79
|
+
if len(state.phase_list) != 1:
|
|
80
|
+
raise ValueError("Select a phase for a multiphase Generic state")
|
|
81
|
+
phase = state.phase_list.first()
|
|
82
|
+
phase_data = state.params.get_phase(phase)
|
|
83
|
+
if not (phase_data.is_liquid_phase() or phase_data.is_vapor_phase()):
|
|
84
|
+
raise ValueError(f"Unsupported Generic phase {phase!r}")
|
|
85
|
+
single_fctp = definition is FcTP and len(state.phase_list) == 1
|
|
86
|
+
return EpcsaftBlock(
|
|
87
|
+
model=model,
|
|
88
|
+
state={"temperature": state.temperature, "pressure": state.pressure},
|
|
89
|
+
composition=state.flow_mol_comp if single_fctp else state.flow_mol_phase_comp,
|
|
90
|
+
index=() if single_fctp else (phase,),
|
|
91
|
+
species=species,
|
|
92
|
+
phase="liquid" if phase_data.is_liquid_phase() else "vapor",
|
|
93
|
+
counter_ion=None,
|
|
94
|
+
_allow_uneliminated_charge=True,
|
|
95
|
+
**options,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def generic_property_configuration(
|
|
100
|
+
model: Mixture, *, state_definition: Any = FcTP, **options: Any
|
|
101
|
+
) -> dict[str, Any]:
|
|
102
|
+
"""Declare the Engine's Generic EoS hook with FcTP (default) or FTPx.
|
|
103
|
+
|
|
104
|
+
Options are passed to `epcsaft.idaes.property_configuration`. For FcTP,
|
|
105
|
+
give the component-flow bounds under `flow_mol_comp`. Use the Generic
|
|
106
|
+
state block initializer to seed apparent species before solving.
|
|
107
|
+
"""
|
|
108
|
+
if state_definition not in (FcTP, FTPx):
|
|
109
|
+
raise ValueError("Select the FcTP or FTPx state definition")
|
|
110
|
+
configuration = property_configuration(model, **options)
|
|
111
|
+
configuration["state_definition"] = state_definition
|
|
112
|
+
return configuration
|
epcsaft_pse/block.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""IDAES property and equilibrium declarations driven by the installed Engine ASL adapter."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import math
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
from epcsaft import GAS_CONSTANT_J_PER_MOL_K, DensityBranch, Mixture
|
|
8
|
+
from epcsaft.idaes import (
|
|
9
|
+
PropertyExternalFunction,
|
|
10
|
+
check_endpoint,
|
|
11
|
+
property_configuration,
|
|
12
|
+
)
|
|
13
|
+
from idaes.core import ProcessBlock, ProcessBlockData, declare_process_block_class # type: ignore[import-untyped]
|
|
14
|
+
from idaes.core.util import scaling as iscale # type: ignore[import-untyped]
|
|
15
|
+
from pyomo.common.config import ConfigValue # type: ignore[import-untyped]
|
|
16
|
+
from pyomo.environ import ( # type: ignore[import-untyped]
|
|
17
|
+
Any as AnyIndex,
|
|
18
|
+
)
|
|
19
|
+
from pyomo.environ import (
|
|
20
|
+
Block,
|
|
21
|
+
Constraint,
|
|
22
|
+
Var,
|
|
23
|
+
exp,
|
|
24
|
+
log,
|
|
25
|
+
value,
|
|
26
|
+
)
|
|
27
|
+
from pyomo.environ import (
|
|
28
|
+
units as u,
|
|
29
|
+
)
|
|
30
|
+
from pyomo.util.check_units import check_units_equivalent # type: ignore[import-untyped]
|
|
31
|
+
|
|
32
|
+
from .composition import magnitude, map_composition
|
|
33
|
+
from .equilibrium import EQUILIBRIUM_UNITS, EquilibriumRows, OutputKey
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
|
|
37
|
+
class EpcsaftBlock(ProcessBlock):
|
|
38
|
+
"""Container generated by declare_process_block_class at runtime."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_OUTPUT_UNITS = {
|
|
42
|
+
"density": u.mol / u.m**3,
|
|
43
|
+
"molar_enthalpy": u.J / u.mol,
|
|
44
|
+
"ln_fugacity_coefficient": u.dimensionless,
|
|
45
|
+
"saturation_index": u.dimensionless,
|
|
46
|
+
"water_activity": u.dimensionless,
|
|
47
|
+
"ln_water_activity": u.dimensionless,
|
|
48
|
+
"osmotic_pressure": u.Pa,
|
|
49
|
+
}
|
|
50
|
+
_LOG_OUTPUTS = {"ln_fugacity_coefficient", "ln_water_activity", "saturation_index"}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@declare_process_block_class("EpcsaftBlock")
|
|
54
|
+
class EpcsaftBlockData(ProcessBlockData):
|
|
55
|
+
"""Map a flowsheet state to native property or equilibrium callbacks.
|
|
56
|
+
|
|
57
|
+
Read bound or generated variables from outputs[name, index]. initialize()
|
|
58
|
+
evaluates them and sets scaling. audit() checks the current state independently.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
_stage_flows = False
|
|
62
|
+
CONFIG = ProcessBlockData.CONFIG()
|
|
63
|
+
for option in (
|
|
64
|
+
"model",
|
|
65
|
+
"state",
|
|
66
|
+
"composition",
|
|
67
|
+
"species",
|
|
68
|
+
"basis",
|
|
69
|
+
"solvent",
|
|
70
|
+
"counter_ion",
|
|
71
|
+
"molar_masses",
|
|
72
|
+
"outputs",
|
|
73
|
+
"neutral_reference",
|
|
74
|
+
"problem",
|
|
75
|
+
"continuation",
|
|
76
|
+
"feed_offset",
|
|
77
|
+
"feed_matrix",
|
|
78
|
+
"feed_controls",
|
|
79
|
+
"identity_component",
|
|
80
|
+
"minimum_gap",
|
|
81
|
+
):
|
|
82
|
+
CONFIG.declare(option, ConfigValue())
|
|
83
|
+
for option, default in (
|
|
84
|
+
("mode", "property"),
|
|
85
|
+
("phase", "liquid"),
|
|
86
|
+
("derivatives", "exact"),
|
|
87
|
+
("index", ()),
|
|
88
|
+
("solids", ()),
|
|
89
|
+
("warm_start", False),
|
|
90
|
+
("ion_floor", 1e-20),
|
|
91
|
+
("charge_tolerance", 1e-6),
|
|
92
|
+
("_allow_uneliminated_charge", False),
|
|
93
|
+
):
|
|
94
|
+
CONFIG.declare(option, ConfigValue(default=default))
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def derivatives(self) -> str:
|
|
98
|
+
return self._derivatives
|
|
99
|
+
|
|
100
|
+
def build(self) -> None:
|
|
101
|
+
super().build()
|
|
102
|
+
cfg = self.config
|
|
103
|
+
if cfg.mode not in ("property", "equilibrium"):
|
|
104
|
+
raise ValueError(f"Unknown EpcsaftBlock mode {cfg.mode!r}")
|
|
105
|
+
if cfg.warm_start and cfg.mode != "equilibrium":
|
|
106
|
+
raise ValueError("warm_start requires equilibrium mode")
|
|
107
|
+
self._derivatives = cfg.derivatives
|
|
108
|
+
if self.derivatives not in ("exact", "first_order"):
|
|
109
|
+
raise ValueError("derivatives must be exact or first_order")
|
|
110
|
+
if not isinstance(cfg.model, Mixture):
|
|
111
|
+
raise TypeError("model must be an epcsaft.Mixture")
|
|
112
|
+
if cfg.state is None or set(cfg.state) != {"temperature", "pressure"}:
|
|
113
|
+
raise ValueError("state must specify temperature and pressure")
|
|
114
|
+
if (cfg.composition is None and cfg.feed_controls is None) or cfg.outputs is None:
|
|
115
|
+
raise ValueError("Specify composition and an outputs mapping")
|
|
116
|
+
if not math.isfinite(cfg.charge_tolerance) or cfg.charge_tolerance < 0:
|
|
117
|
+
raise ValueError("charge_tolerance must be finite and nonnegative")
|
|
118
|
+
|
|
119
|
+
self._state = (magnitude(cfg.state["temperature"], u.K), magnitude(cfg.state["pressure"], u.Pa))
|
|
120
|
+
self._composition, floor_variables = map_composition(cfg.model, cfg)
|
|
121
|
+
self._equilibrium = None
|
|
122
|
+
if cfg.mode == "equilibrium":
|
|
123
|
+
self._equilibrium = EquilibriumRows(self, self._composition, self._state)
|
|
124
|
+
units = EQUILIBRIUM_UNITS
|
|
125
|
+
else:
|
|
126
|
+
self._configure_property()
|
|
127
|
+
units = _OUTPUT_UNITS
|
|
128
|
+
|
|
129
|
+
self.outputs: dict[OutputKey, Any] = {}
|
|
130
|
+
self._expressions: dict[OutputKey, Any] = {}
|
|
131
|
+
self._auto_scaling: dict[OutputKey, float] = {}
|
|
132
|
+
self._auto_row_scaling: dict[OutputKey, float] = {}
|
|
133
|
+
self.generated = Block()
|
|
134
|
+
self.output_constraints = Constraint(AnyIndex)
|
|
135
|
+
for key, var in cfg.outputs.items():
|
|
136
|
+
name, index = key
|
|
137
|
+
if name not in units:
|
|
138
|
+
raise ValueError(f"Unknown {cfg.mode} output {name!r}")
|
|
139
|
+
unit = units[name] / u.s if self._stage_flows else units[name]
|
|
140
|
+
expr = self._equilibrium.row(key) if self._equilibrium else self._property(name, index)
|
|
141
|
+
if var is None:
|
|
142
|
+
column = self.generated.component(name)
|
|
143
|
+
if column is None:
|
|
144
|
+
column = Var(AnyIndex, dense=False, units=unit)
|
|
145
|
+
self.generated.add_component(name, column)
|
|
146
|
+
var = column[index]
|
|
147
|
+
elif not self._stage_flows and not getattr(var, "is_variable_type", lambda: False)():
|
|
148
|
+
raise TypeError(f"Output {key} must bind a scalar Var or VarData")
|
|
149
|
+
# Unitless external Vars represent the native magnitude; unit-bearing
|
|
150
|
+
# Vars (e.g. osmotic pressure in bar) retain their declared units.
|
|
151
|
+
if not check_units_equivalent(var, u.dimensionless):
|
|
152
|
+
expr = u.convert(expr * unit, to_units=u.get_units(var))
|
|
153
|
+
self.outputs[key] = var
|
|
154
|
+
self._expressions[key] = expr
|
|
155
|
+
self.output_constraints[key] = var == expr
|
|
156
|
+
|
|
157
|
+
# Change flowsheet bounds only after the complete declaration is admitted.
|
|
158
|
+
for var in floor_variables:
|
|
159
|
+
var.setlb(cfg.ion_floor)
|
|
160
|
+
logging.getLogger(__name__).info("Set lower bound on %s to %g", var.name, cfg.ion_floor)
|
|
161
|
+
|
|
162
|
+
def _configure_property(self) -> None:
|
|
163
|
+
cfg = self.config
|
|
164
|
+
# The Engine configuration owns phase admission and the serialization of
|
|
165
|
+
# thermochemistry, solid laws and their source-basis neutral reference.
|
|
166
|
+
package = property_configuration(
|
|
167
|
+
cfg.model,
|
|
168
|
+
phases=(cfg.phase,),
|
|
169
|
+
solids=cfg.solids,
|
|
170
|
+
neutral_reference=cfg.neutral_reference,
|
|
171
|
+
state_bounds={},
|
|
172
|
+
temperature_ref=298.15,
|
|
173
|
+
pressure_ref=1e5,
|
|
174
|
+
)
|
|
175
|
+
options = package["phases"][cfg.phase]["equation_of_state_options"]
|
|
176
|
+
self._record = options["record"]
|
|
177
|
+
symbol = "epcsaft_pressure_property" + ("_first_order" if self.derivatives == "first_order" else "")
|
|
178
|
+
self.pressure_property = PropertyExternalFunction(library=options["library"], function=symbol)
|
|
179
|
+
self._solid_indices = {s.name: i for i, s in enumerate(cfg.solids)}
|
|
180
|
+
if len(self._solid_indices) != len(cfg.solids):
|
|
181
|
+
raise ValueError("Solid names must be unique")
|
|
182
|
+
|
|
183
|
+
def _row(self, row: int, weights: tuple[Any, ...]) -> Any:
|
|
184
|
+
return self.pressure_property(
|
|
185
|
+
*self._state,
|
|
186
|
+
*weights,
|
|
187
|
+
*self.config.model.active_parameter_values,
|
|
188
|
+
self._record,
|
|
189
|
+
str(row),
|
|
190
|
+
"0" if self.config.phase == "liquid" else "1",
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
def _property(self, name: str, index: str | None) -> Any:
|
|
194
|
+
comp = self._composition
|
|
195
|
+
weights = tuple(comp.weights.values())
|
|
196
|
+
if name == "ln_fugacity_coefficient":
|
|
197
|
+
if index not in comp.keys:
|
|
198
|
+
raise ValueError(f"Unknown flowsheet species {index!r}")
|
|
199
|
+
return self._row(2 + comp.keys.index(index), weights)
|
|
200
|
+
ids = self.config.model.component_ids
|
|
201
|
+
if name == "saturation_index":
|
|
202
|
+
if index not in self._solid_indices:
|
|
203
|
+
raise ValueError(f"Unknown solid {index!r}. Declare its solid law and neutral_reference")
|
|
204
|
+
s = self._solid_indices[index]
|
|
205
|
+
formula = self.config.solids[s].formula
|
|
206
|
+
total = sum(weights)
|
|
207
|
+
return sum(
|
|
208
|
+
nu * (log(weights[i] / total) + self._row(2 + i, weights))
|
|
209
|
+
for i, j in enumerate(ids)
|
|
210
|
+
if (nu := formula.get(j))
|
|
211
|
+
) - self._row(2 + len(ids) + s, weights)
|
|
212
|
+
if index is not None:
|
|
213
|
+
raise ValueError(f"{name} takes index None")
|
|
214
|
+
if name in ("density", "molar_enthalpy"):
|
|
215
|
+
return self._row(0 if name == "density" else 1, weights)
|
|
216
|
+
if "water" not in ids or self.config.phase != "liquid":
|
|
217
|
+
raise ValueError(f"{name} requires a liquid record containing water")
|
|
218
|
+
water = ids.index("water")
|
|
219
|
+
pure = tuple(1.0 if i == water else 0.0 for i in range(len(ids)))
|
|
220
|
+
ln_aw = (
|
|
221
|
+
log(weights[water] / sum(weights)) + self._row(2 + water, weights) - self._row(2 + water, pure)
|
|
222
|
+
)
|
|
223
|
+
if name == "ln_water_activity":
|
|
224
|
+
return ln_aw
|
|
225
|
+
if name == "water_activity":
|
|
226
|
+
return exp(ln_aw)
|
|
227
|
+
return -GAS_CONSTANT_J_PER_MOL_K * self._state[0] * self._row(0, pure) * ln_aw
|
|
228
|
+
|
|
229
|
+
def initialize(self) -> None:
|
|
230
|
+
comp = self._composition
|
|
231
|
+
if comp.counter_ion is not None:
|
|
232
|
+
eliminated = value(comp.weights[comp.counter_ion])
|
|
233
|
+
if eliminated < 0:
|
|
234
|
+
raise ValueError(f"Negative eliminated weight for {comp.counter_ion}: {eliminated:g}")
|
|
235
|
+
delta = comp.imbalance()
|
|
236
|
+
if not delta <= self.config.charge_tolerance:
|
|
237
|
+
raise ValueError(
|
|
238
|
+
f"Charge imbalance for {comp.counter_ion}: {delta:g} exceeds "
|
|
239
|
+
f"charge_tolerance {self.config.charge_tolerance:g}"
|
|
240
|
+
)
|
|
241
|
+
for key, expr in self._expressions.items():
|
|
242
|
+
amount = expr()
|
|
243
|
+
if self.outputs[key].is_variable_type():
|
|
244
|
+
self.outputs[key].set_value(amount)
|
|
245
|
+
self._scale(key, amount)
|
|
246
|
+
|
|
247
|
+
def _scale(self, key: OutputKey, amount: float) -> None:
|
|
248
|
+
var = self.outputs[key]
|
|
249
|
+
factor = iscale.get_scaling_factor(var)
|
|
250
|
+
if factor is None or factor == self._auto_scaling.get(key):
|
|
251
|
+
factor = 1.0 if key[0] in _LOG_OUTPUTS or amount == 0 else 1.0 / abs(amount)
|
|
252
|
+
if var.is_variable_type():
|
|
253
|
+
iscale.set_scaling_factor(var, factor)
|
|
254
|
+
self._auto_scaling[key] = factor
|
|
255
|
+
else:
|
|
256
|
+
self._auto_scaling.pop(key, None)
|
|
257
|
+
row = self.output_constraints[key]
|
|
258
|
+
row_factor = iscale.get_scaling_factor(row)
|
|
259
|
+
if row_factor is None or row_factor == self._auto_row_scaling.get(key):
|
|
260
|
+
iscale.set_scaling_factor(row, factor)
|
|
261
|
+
self._auto_row_scaling[key] = factor
|
|
262
|
+
else:
|
|
263
|
+
self._auto_row_scaling.pop(key, None)
|
|
264
|
+
|
|
265
|
+
def update_scaling(self) -> None:
|
|
266
|
+
"""Refresh the scales at the current state, preserving caller-supplied factors."""
|
|
267
|
+
for key, expr in self._expressions.items():
|
|
268
|
+
self._scale(key, value(expr))
|
|
269
|
+
|
|
270
|
+
def calculate_scaling_factors(self) -> None:
|
|
271
|
+
self.update_scaling()
|
|
272
|
+
|
|
273
|
+
def audit(self) -> dict[str, Any]:
|
|
274
|
+
comp = self._composition
|
|
275
|
+
result: dict[str, Any] = {}
|
|
276
|
+
if comp.counter_ion is not None:
|
|
277
|
+
delta = comp.imbalance()
|
|
278
|
+
weight = value(comp.weights[comp.counter_ion])
|
|
279
|
+
result["charge"] = {
|
|
280
|
+
"counter_ion": comp.counter_ion,
|
|
281
|
+
"delta": delta,
|
|
282
|
+
"eliminated_weight": weight,
|
|
283
|
+
"status": "passed" if weight >= 0 and delta <= self.config.charge_tolerance else "failed",
|
|
284
|
+
}
|
|
285
|
+
if self._equilibrium is not None:
|
|
286
|
+
amounts = (
|
|
287
|
+
{key: flow * u.s for key, flow in self.outputs.items()}
|
|
288
|
+
if self._stage_flows else self.outputs
|
|
289
|
+
)
|
|
290
|
+
result.update(self._equilibrium.audit(amounts))
|
|
291
|
+
return result
|
|
292
|
+
try:
|
|
293
|
+
weights = [value(w) for w in comp.weights.values()]
|
|
294
|
+
total = sum(weights)
|
|
295
|
+
if total <= 0:
|
|
296
|
+
raise ValueError("Total mole weight must be positive")
|
|
297
|
+
endpoint = check_endpoint(
|
|
298
|
+
self.config.model,
|
|
299
|
+
self.config.phase,
|
|
300
|
+
value(self._state[0]),
|
|
301
|
+
value(self._state[1]),
|
|
302
|
+
[w / total for w in weights],
|
|
303
|
+
self.config.model.active_parameter_values,
|
|
304
|
+
)
|
|
305
|
+
status = (
|
|
306
|
+
"unclassified"
|
|
307
|
+
if endpoint.diagnostics.returned_branch == DensityBranch.Unspecified
|
|
308
|
+
else "passed"
|
|
309
|
+
)
|
|
310
|
+
result["endpoint"] = {"status": status, "result": endpoint}
|
|
311
|
+
except (ValueError, RuntimeError) as error:
|
|
312
|
+
result["endpoint"] = {"status": "failed", "message": str(error)}
|
|
313
|
+
return result
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Flowsheet coordinates mapped to the Engine's ordered, unnormalized mole weights."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import warnings
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from epcsaft import Mixture
|
|
10
|
+
from pyomo.core.base.units_container import UnitsError # type: ignore[import-untyped]
|
|
11
|
+
from pyomo.environ import units as u # type: ignore[import-untyped]
|
|
12
|
+
from pyomo.environ import value
|
|
13
|
+
from pyomo.util.check_units import check_units_equivalent # type: ignore[import-untyped]
|
|
14
|
+
|
|
15
|
+
_BASES = {
|
|
16
|
+
"amount": ("mol", u.mol),
|
|
17
|
+
"molar_flow": ("mol/s", u.mol / u.s),
|
|
18
|
+
"mass_flow": ("kg/s", u.kg / u.s),
|
|
19
|
+
"molar_concentration": ("mol/m³", u.mol / u.m**3),
|
|
20
|
+
"mass_concentration": ("kg/m³", u.kg / u.m**3),
|
|
21
|
+
"molality": ("mol/kg", u.mol / u.kg),
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def magnitude(expr: Any, unit: Any) -> Any:
|
|
26
|
+
"""Dimensionless numeric argument in the given unit. Bare inputs are already in it."""
|
|
27
|
+
if check_units_equivalent(expr, u.dimensionless):
|
|
28
|
+
return expr
|
|
29
|
+
return u.convert(expr, to_units=unit) / unit
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _basis(expr: Any, override: str | None) -> str:
|
|
33
|
+
for name, (symbol, unit) in _BASES.items():
|
|
34
|
+
if override is not None:
|
|
35
|
+
if override.replace("m^3", "m³").replace("m3", "m³") in (name, symbol):
|
|
36
|
+
return name
|
|
37
|
+
else:
|
|
38
|
+
try:
|
|
39
|
+
u.convert(expr, to_units=unit)
|
|
40
|
+
return name
|
|
41
|
+
except UnitsError:
|
|
42
|
+
continue
|
|
43
|
+
raise ValueError(
|
|
44
|
+
f"Unsupported composition basis {override or u.get_units(expr)}. Select one of {', '.join(_BASES)}."
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _flowsheet_molar_mass(expr: Any, key: str, supplied: Any) -> Any:
|
|
49
|
+
if supplied is not None and key in supplied:
|
|
50
|
+
return supplied[key]
|
|
51
|
+
if hasattr(expr, "parent_block"):
|
|
52
|
+
owner = expr.parent_block()
|
|
53
|
+
owner_mw = getattr(owner, "mw_comp", None)
|
|
54
|
+
if owner_mw is None:
|
|
55
|
+
owner_mw = getattr(getattr(owner, "params", None), "mw_comp", None)
|
|
56
|
+
if owner_mw is not None and key in owner_mw:
|
|
57
|
+
return owner_mw[key]
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _molar_mass(expr: Any, key: str, supplied: Any, native: float, *, required: bool = False) -> Any:
|
|
62
|
+
entry = _flowsheet_molar_mass(expr, key, supplied)
|
|
63
|
+
if entry is None:
|
|
64
|
+
if required and native <= 0:
|
|
65
|
+
raise ValueError(f"The Engine has no molar mass for {key}. Supply flowsheet molar_masses")
|
|
66
|
+
return native
|
|
67
|
+
mass = magnitude(entry, u.kg / u.mol)
|
|
68
|
+
mw = value(mass)
|
|
69
|
+
if not math.isfinite(mw) or mw <= 0:
|
|
70
|
+
raise ValueError(f"Molar mass of {key} must be positive, got {mw} kg/mol")
|
|
71
|
+
if native > 0 and abs(mw - native) > 1e-4 * native:
|
|
72
|
+
warnings.warn(
|
|
73
|
+
f"Molar mass of {key} is {mw} kg/mol on the flowsheet and {native} kg/mol in the Engine",
|
|
74
|
+
UserWarning,
|
|
75
|
+
stacklevel=4,
|
|
76
|
+
)
|
|
77
|
+
return mass
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def elimination_coefficients(charges: dict[str, int], ion: str | None) -> dict[str, float]:
|
|
81
|
+
"""Coefficients of the dependent counter-ion in either native input map."""
|
|
82
|
+
if ion is None:
|
|
83
|
+
return {}
|
|
84
|
+
return {k: -z / charges[ion] for k, z in charges.items() if z and k != ion}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class Composition:
|
|
89
|
+
keys: tuple[str, ...] # flowsheet keys in Engine order
|
|
90
|
+
supplied: dict[str, Any] # in a common molar basis
|
|
91
|
+
weights: dict[str, Any] # electroneutral callback expressions
|
|
92
|
+
charges: dict[str, int]
|
|
93
|
+
counter_ion: str | None
|
|
94
|
+
|
|
95
|
+
def imbalance(self) -> float:
|
|
96
|
+
ion = self.counter_ion
|
|
97
|
+
if ion is None:
|
|
98
|
+
return 0.0
|
|
99
|
+
difference = abs(value(self.supplied[ion] - self.weights[ion]))
|
|
100
|
+
denominator = sum(abs(z) * value(self.supplied[k]) for k, z in self.charges.items() if z)
|
|
101
|
+
if denominator > 0:
|
|
102
|
+
return difference / denominator
|
|
103
|
+
return 0.0 if difference == 0 else math.inf
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def map_composition(model: Mixture, config: Any) -> tuple[Composition, list[Any]]:
|
|
107
|
+
names = model.component_ids
|
|
108
|
+
by_key = {name: name for name in names} if config.species is None else dict(config.species)
|
|
109
|
+
if len(by_key) != len(names) or set(by_key.values()) != set(names):
|
|
110
|
+
raise ValueError("species must map one-to-one onto the Engine component_ids")
|
|
111
|
+
inverse = {name: key for key, name in by_key.items()}
|
|
112
|
+
keys = tuple(inverse[name] for name in names)
|
|
113
|
+
charges = dict(zip(keys, model.parameters.charge_numbers, strict=True))
|
|
114
|
+
ion = config.counter_ion
|
|
115
|
+
charged = any(charges.values())
|
|
116
|
+
if charged and not charges.get(ion) and (ion is not None or not config._allow_uneliminated_charge):
|
|
117
|
+
raise ValueError("A charged model requires counter_ion naming a charged flowsheet species")
|
|
118
|
+
if not charged and ion is not None:
|
|
119
|
+
raise ValueError("counter_ion requires a charged model")
|
|
120
|
+
|
|
121
|
+
if config.feed_controls is not None:
|
|
122
|
+
if (config.mode != "equilibrium" or config.feed_matrix is None or ion is not None
|
|
123
|
+
or config.composition is not None):
|
|
124
|
+
raise ValueError("feed_controls requires a neutral equilibrium feed_matrix in place of composition")
|
|
125
|
+
return Composition(keys, {}, {}, charges, ion), []
|
|
126
|
+
|
|
127
|
+
source = config.composition
|
|
128
|
+
prefix = tuple(config.index or ())
|
|
129
|
+
if isinstance(source, Mapping) and prefix:
|
|
130
|
+
raise ValueError("index applies only to an indexed composition component")
|
|
131
|
+
|
|
132
|
+
def at(key: str) -> Any:
|
|
133
|
+
return source[(*prefix, key)] if prefix else source[key]
|
|
134
|
+
|
|
135
|
+
# The solvent may be absent from a molality stream; classify using a solute.
|
|
136
|
+
solvent = config.solvent if config.solvent is not None else inverse.get("water")
|
|
137
|
+
probe = next((k for k in keys if k != solvent), keys[0])
|
|
138
|
+
basis = _basis(at(probe), config.basis)
|
|
139
|
+
if basis == "molality" and (solvent not in keys or charges[solvent]):
|
|
140
|
+
raise ValueError("Molality requires a neutral solvent specified by flowsheet key")
|
|
141
|
+
unit = _BASES[basis][1]
|
|
142
|
+
mass_basis = basis in ("mass_flow", "mass_concentration")
|
|
143
|
+
floor = config.ion_floor
|
|
144
|
+
if floor is not None and (not math.isfinite(floor) or floor <= 0):
|
|
145
|
+
raise ValueError("ion_floor must be finite and positive in flowsheet variable units")
|
|
146
|
+
supplied = {}
|
|
147
|
+
floor_variables = []
|
|
148
|
+
for key, mw in zip(keys, model.parameters.molar_masses, strict=True):
|
|
149
|
+
if basis == "molality" and key == solvent:
|
|
150
|
+
if mw <= 0:
|
|
151
|
+
raise ValueError(f"Solvent {key} requires an Engine molar mass for molality")
|
|
152
|
+
owner_expr = source[key] if isinstance(source, Mapping) and key in source else at(probe)
|
|
153
|
+
_molar_mass(owner_expr, key, config.molar_masses, mw)
|
|
154
|
+
supplied[key] = 1.0 / mw
|
|
155
|
+
continue
|
|
156
|
+
expr = at(key)
|
|
157
|
+
if config.basis is None and check_units_equivalent(expr, u.dimensionless):
|
|
158
|
+
raise ValueError(f"Composition of {key} has no basis units")
|
|
159
|
+
weight = magnitude(expr, unit)
|
|
160
|
+
if mass_basis or config.molar_masses is not None:
|
|
161
|
+
mass = _molar_mass(expr, key, config.molar_masses, mw, required=mass_basis)
|
|
162
|
+
if mass_basis:
|
|
163
|
+
weight = weight / mass
|
|
164
|
+
supplied[key] = weight
|
|
165
|
+
if (
|
|
166
|
+
floor is not None
|
|
167
|
+
and charges[key]
|
|
168
|
+
and getattr(expr, "is_variable_type", lambda: False)()
|
|
169
|
+
and (expr.lb is None or expr.lb < floor)
|
|
170
|
+
):
|
|
171
|
+
floor_variables.append(expr)
|
|
172
|
+
weights = dict(supplied)
|
|
173
|
+
if ion is not None:
|
|
174
|
+
weights[ion] = sum(a * supplied[k] for k, a in elimination_coefficients(charges, ion).items())
|
|
175
|
+
return Composition(keys, supplied, weights, charges, ion), floor_variables
|