12 · Understand and calculate SLLE with openCOSMO-RS¶
This tutorial follows benzene + water, then benzene + water + ethanol, from model construction to phase diagrams. Every activity coefficient is evaluated by the real compiled openCOSMO-RS backend using Turbomole conformers.
By the end you should be able to:
- Explain the inputs to
ReducedChartand why its coordinates are ordinary species amounts here. - Construct a liquid model and a separate pure-solid model, with matching reference states.
- Run a flash and read compositions, phase amounts and physical residuals.
- Locate the binary S+L₁+L₂ invariant and plot the surrounding LLE and SLE boundaries.
- Map the ternary L, LLE, SLE and SLLE assemblages over many feed compositions.
Run the cells in order in a fresh kernel. No previous notebook state is required. See the course index and phase-equilibrium theory.
1. Set up the real model inputs¶
Install ThermoWeave and the compiled backend using the portable COSMO-RS setup guide, then configure:
THERMOWEAVE_COSMO_ROOT: your COSMOconf25 root or itsNeutralSpeciesdirectory.THERMOWEAVE_OPENCOSMORS_BUILD: directory containing the compiledopenCOSMORSextension, if it is not already importable.THERMOWEAVE_COSMO_PARAMETERS: parameter name or JSON path; the default here isdefault_turbomole.
The tutorial helper loads all matching COSMO_TZVPD_FINE/*.cosmo conformers for
C6H6_001_benzene, H2O and C2H6O_001_ethanol. The inputs are user-owned and are
not downloaded or bundled. The printed filenames, hashes and parameter identity
let you check exactly which inputs produced the saved results.
Keep one component order throughout: benzene, water, ethanol. Every composition, charge, molar mass and solid-composition vector follows that order.
# Standard Python tools for recording the inputs used in this calculation.
import hashlib
import importlib
import json
import os
from functools import lru_cache
from pathlib import Path
# NumPy holds composition arrays; Matplotlib draws the phase diagrams.
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import brentq
# COSMO-RS provides liquid activities; HELD selects the stable phase assemblage.
from thermoweave import FusionProperties, build_cosmors_model, load_parametrization
from thermoweave.equilibrium.reduced_held import ReducedChart, ReducedHELD, Solid
from thermoweave.equilibrium.sle import solubility
# These helpers load cited data, format results and check the physical balances.
# They do not replace COSMO-RS with another activity model.
from _support import (
COMPONENTS,
check_flash,
cosmo_components,
held_settings,
phase_label,
phase_table,
solid_gibbs,
ternary_axes,
ternary_plot,
)
np.set_printoptions(precision=8, suppress=True)
names = ["benzene", "water", "ethanol"]
definitions, manifest = cosmo_components(names) # Locate actual conformer files.
parameter_source = os.environ.get("THERMOWEAVE_COSMO_PARAMETERS", "default_turbomole")
parametrization = load_parametrization(parameter_source)
# Exclude the machine-specific source path before hashing the parameter content.
identity = {
key: value for key, value in parametrization.to_dict().items() if key != "source"
}
parameter_hash = hashlib.sha256(
json.dumps(identity, sort_keys=True).encode()
).hexdigest()
backend = importlib.import_module(
os.environ.get("THERMOWEAVE_OPENCOSMORS_MODULE", "openCOSMORS")
)
print("Backend extension:", Path(backend.__file__).name)
print("Parametrization:", Path(parameter_source).name)
print("Parameter-content SHA256:", parameter_hash)
print("Actual conformer manifest:", json.dumps(manifest, indent=2))
# The float C++ backend has numerical noise. These explicit tolerances use
# finite-difference steps large enough to resolve changes above that noise.
settings = held_settings(noisy=True)
physical_tolerance = 5e-5 # Dimensionless chemical-potential residual tolerance.
print("Solver settings:", settings)
Backend extension: openCOSMORS.cpython-312-x86_64-linux-gnu.so
Parametrization: default_turbomole
Parameter-content SHA256: 4053ef017418f317c99a8527e6e5b9911297e33efe419744ec9431d4a5bb63eb
Actual conformer manifest: [
{
"name": "benzene",
"basis": "COSMO_TZVPD_FINE",
"conformers": [
{
"file": "C6H6_001_benzene_CnfS1_c000.cosmo",
"sha256": "3114b29eadf951907d29a6c16888952ce99a1f3af6a210074fd972868d76d4fc"
}
]
},
{
"name": "water",
"basis": "COSMO_TZVPD_FINE",
"conformers": [
{
"file": "H2O_c000.cosmo",
"sha256": "2d46cfea8920ed3770e91a4cf3dcc4720205e8b6483d4be834b832a0da6df44a"
}
]
},
{
"name": "ethanol",
"basis": "COSMO_TZVPD_FINE",
"conformers": [
{
"file": "C2H6O_001_ethanol_CnfS1_c000.cosmo",
"sha256": "4c848f182351b681256edf70c609ef51f643b99c52ff5ad45ee53b9ebab333ce"
},
{
"file": "C2H6O_001_ethanol_CnfS1_c001.cosmo",
"sha256": "121a8e463a3d1b9e32cdea31309026106708960f948489d821b7b2281469c5b8"
}
]
}
]
Solver settings: HELDSettings(stage1_starts=12, screen_points=96, max_iterations=60, max_starts=12, verify_cap=10, verify_random=5, cut_tol=1e-06, polish_tol=2e-05, fd_step=0.001, polish_max_nfev=60, cluster_radius=0.01, distinct_tol=0.001, max_polish_trials=12, inner_maxiter=300, inner_ftol=1e-10, inner_gtol=1e-07, inner_batch_iters=40, inner_refine=0, polish_pilot_nfev=10, polish_pilot_ratio=0.01, min_neutral_fraction=0.0, stage3_gap=0.001, inner_method='newton', polish_fused=True, seed=0)
What assumptions are we making?¶
The liquid model returns \(\ln\gamma_i(T,\mathbf x)\) on the pure-liquid standard state, so the relative chemical potential is \(\ln(x_i\gamma_i)\). The condensed phase calculation is interpreted at 101325 Pa. This COSMO-RS activity model does not calculate pressure-dependent volumes or a vapour phase.
Only pure benzene(s) is supplied as a candidate solid. Its potential relative to pure liquid benzene is
solid_gibbs(T) implements this expression using the cited fusion data in
tutorials/data/real_mixtures.json: constant fusion enthalpy, \(\Delta C_p=0\).
There are no solid solutions, hydrates or additional solids. All temperatures
used here exceed the melting points of water and ethanol. The figures are
model predictions, not a fit or an experimental validation of SLLE.
# Display the physical inputs instead of hiding the solid model in a helper.
benzene_data = COMPONENTS["benzene"]
Tm = benzene_data["melting_temperature_K"]
fusion = FusionProperties(Tm, benzene_data["enthalpy_of_fusion_J_mol"])
print("Benzene melting temperature [K]:", Tm)
print("Benzene fusion enthalpy [J/mol]:", fusion.enthalpy_of_fusion_J_mol)
print("Fusion-data reference:", benzene_data["fusion_reference"])
print("Source:", benzene_data["source_url"])
Benzene melting temperature [K]: 278.69 Benzene fusion enthalpy [J/mol]: 9866.3 Fusion-data reference: Oliver, Eaton and Huffman (1948), selected row in NIST Chemistry WebBook Source: https://webbook.nist.gov/cgi/cbook.cgi?ID=C71432&Mask=4
2. Why use ReducedChart for an ordinary neutral mixture?¶
ReducedHELD uses a chart to describe which amounts are conserved, together
with charges, molar masses and standard potentials. Its constructor requires an
explicit chart; it does not insert one automatically.
The name comes from its more general use with reactions and electrolytes. For
this tutorial there are no reactions (nu is omitted) and no ions (every
charge is zero). ReducedChart.build therefore defaults to
No chemical coordinate is eliminated. The binary chart is 2×2 and the ternary chart is 3×3. HELD normalizes amounts by total mass internally for optimization, then returns species mole amounts on the original feed basis. This normalization is separate from reducing coordinates by reaction/charge constraints. Neither is the EoS convention of reduced temperature or pressure.
| Argument | Meaning in this notebook |
|---|---|
charges=[0., 0.] |
Benzene and water are neutral. These are not initial compositions. |
molar_masses |
One positive value per species, in the same order; we use g/mol consistently. HELD needs them for mass normalization and mass fractions. |
nu, ln_K omitted |
No reactions or reaction equilibrium constants are introduced. |
mu0 omitted |
Zero relative pure-liquid standard potentials, consistent with the activity model and the fusion term. |
The solver searches liquid phases of the supplied model. Supplying solids=[...]
adds possible solid phases; it does not force them to appear.
binary_names = names[:2] # Keep benzene at index 0 and water at index 1.
binary_model = build_cosmors_model(parametrization, definitions[:2])
# Zero charges + omitted reactions => the identity chart for this neutral binary.
binary_chart = ReducedChart.build(
charges=np.zeros(2),
molar_masses=[COMPONENTS[name]["molar_mass_g_mol"] for name in binary_names],
)
print("Binary coordinate matrix Lambda:\n", binary_chart.Lambda)
print("Number of reactions:", binary_chart.n_reactions)
np.testing.assert_array_equal(binary_chart.Lambda, np.eye(2))
assert binary_chart.n_reactions == 0
BINARY SPECS
-------------------------
compile mode: RELEASE
openmp: activated
vectorization: AVX
-------------------------
Binary coordinate matrix Lambda:
[[1. 0.]
[0. 1.]]
Number of reactions: 0
3. Run and read a binary flash¶
A flash fixes temperature and total feed amounts, then minimizes the total
Gibbs energy over allowed liquid/solid assemblages. Here [0.5, 0.5] means
0.5 mol benzene + 0.5 mol water, so its numerical values also equal overall mole
fractions. Scaling both amounts scales phase amounts but not phase compositions.
result.mole_fractions gives the composition inside each phase.
result.phases gives the species mole amounts in each phase.
phase_table prints phase mole fractions and phase mass fractions separately.
check_flash verifies conservation, liquid isoactivity, solid saturation and the
reconstructed Gibbs energy. certified reports the configured multistart
stability search, rather than a mathematical proof of global optimality.
def binary_flash(temperature, feed, include_solid=True):
"""Flash a binary feed [mol benzene, mol water] at the given temperature."""
# Below water's melting point this restricted solid list would be incomplete.
assert temperature > COMPONENTS["water"]["melting_temperature_K"]
solids = []
if include_solid:
# [1, 0] is pure benzene(s); its energy must be updated with temperature.
solids = [Solid("benzene(s)", [1.0, 0.0], solid_gibbs(temperature))]
solver = ReducedHELD(
binary_model, float(temperature), binary_chart, settings, solids=solids
)
return solver.flash(feed) # The solver chooses which candidate phases exist.
binary_feed = np.array([0.5, 0.5]) # One mole total feed.
for temperature in [275.0, 279.0]:
answer = binary_flash(temperature, binary_feed)
print("Temperature [K]:", temperature, "; assemblage:", phase_label(answer))
print(phase_table(answer, binary_names))
print(
check_flash(
binary_model, temperature, binary_feed, answer, tol=physical_tolerance
)
)
loadMolecules for every molecule worked...
Temperature [K]: 275.0 ; assemblage: S+L
[{'phase': 'liquid', 'mole_fraction_of_total': 0.5001385316423111, 'mass_fraction_of_total': 0.1876362198009498, 'x_benzene': 0.0002769865382934042, 'x_water': 0.9997230134617064}, {'phase': 'benzene(s)', 'mole_fraction_of_total': 0.4998614683576888, 'mass_fraction_of_total': 0.8123637801990503, 'x_benzene': 1.0, 'x_water': 0.0}]
{'species_balance_error_mol': 2.2407631306009534e-12, 'liquid_mu_error_over_RT': 0.0, 'solid_saturation_error_over_RT': np.float64(2.087156441427096e-08), 'gibbs_reconstruction_error_over_RT': np.float64(1.1449174941446927e-16), 'phase_mole_fractions': [0.5001385316418347, 0.4998614683572126], 'phase_mass_fractions': [0.1876362198009498, 0.8123637801990503]}
Temperature [K]: 279.0 ; assemblage: L1+L2
[{'phase': 'liquid', 'mole_fraction_of_total': 0.4998817339074455, 'mass_fraction_of_total': 0.8123478390520092, 'x_benzene': 0.9999218017207405, 'x_water': 7.819827925951799e-05}, {'phase': 'liquid', 'mole_fraction_of_total': 0.5001182660925545, 'mass_fraction_of_total': 0.18765216094799086, 'x_benzene': 0.0003146375460519196, 'x_water': 0.999685362453948}]
{'species_balance_error_mol': 2.220446049250313e-16, 'liquid_mu_error_over_RT': 2.4248317112909867e-15, 'solid_saturation_error_over_RT': 0.0, 'gibbs_reconstruction_error_over_RT': np.float64(5.421010862427522e-20), 'phase_mole_fractions': [0.4998817339074455, 0.5001182660925545], 'phase_mass_fractions': [0.8123478390520092, 0.18765216094799086]}
With the saved input set, the 275 K feed forms solid benzene + a water-rich
liquid; at 279 K it forms two liquids. The next step finds the temperature
separating those behaviours. Changing the parametrization can change the result;
the assertions below describe the printed default_turbomole example.
4. Locate the binary S+L₁+L₂ invariant¶
First suppress solids to find a liquid–liquid tie line. Below the freezing transition, this liquid-only calculation can be metastable with respect to benzene(s). It is an intermediate calculation, not the final stable diagram.
At the invariant \(T_*\), the common benzene chemical potential in the two liquids also equals the solid potential:
brentq varies temperature until this residual changes sign and vanishes.
It does not fit any model parameter. Sorting the two liquid compositions by
benzene content keeps L1 water-rich and L2 benzene-rich in this binary section.
@lru_cache(maxsize=128)
def binary_liquids(temperature):
"""Return the two liquid compositions, without allowing any solid."""
# Caching avoids repeating expensive flashes at identical temperatures.
answer = binary_flash(float(temperature), [0.5, 0.5], include_solid=False)
assert answer.converged and answer.certified
assert answer.phase_kinds == ["liquid", "liquid"]
liquids = np.asarray(sorted(answer.mole_fractions, key=lambda x: x[0]))
assert (
liquids[1, 0] - liquids[0, 0] > 0.5
) # Reject a trivial identical-phase solution.
return liquids
def binary_freezing_residual(temperature):
organic_liquid = binary_liquids(float(temperature))[1]
ln_gamma_B = binary_model.ln_activity_coefficients(
float(temperature), organic_liquid
)[0]
mu_B = np.log(organic_liquid[0]) + ln_gamma_B # Relative chemical potential / RT.
return float(mu_B - solid_gibbs(temperature)) # Zero means solid saturation.
# The endpoint signs bracket the transition for this particular input set.
print(
"Freezing residual at bracket ends:",
binary_freezing_residual(278.0),
binary_freezing_residual(Tm),
)
binary_T_star = brentq(binary_freezing_residual, 278.0, Tm, xtol=2e-5)
binary_X = binary_liquids(float(binary_T_star))
print("Predicted binary S+L1+L2 temperature [K]:", binary_T_star)
print("Liquid compositions [benzene, water]:\n", binary_X)
print("Solid saturation residual:", binary_freezing_residual(binary_T_star))
Freezing residual at bracket ends: 0.010498485614075273 -7.385359384668531e-05
Predicted binary S+L1+L2 temperature [K]: 278.6851799711727 Liquid compositions [benzene, water]: [[0.00031291 0.99968709] [0.99992371 0.00007629]] Solid saturation residual: 1.0068601251898325e-08
Verify the three-phase candidate¶
The binary three-phase temperature is an invariant at fixed pressure. It is not a finite area of three-phase equilibrium on a T–x diagram. At exactly this temperature, three phase amounts are not uniquely fixed by two component balances; a flash may choose an equally stable two-phase representation.
We therefore compare chemical potentials and total Gibbs energy, rather than requiring the flash to print exactly three phases. The weights below construct one possible feed for a three-phase candidate. The independent flash still chooses its own phase compositions and amounts.
# Every component must have the same relative chemical potential in both liquids.
binary_mu = np.log(binary_X) + binary_model.ln_activity_coefficients_batch(
float(binary_T_star), binary_X
)
np.testing.assert_allclose(binary_mu[0], binary_mu[1], atol=physical_tolerance, rtol=0)
np.testing.assert_allclose(
binary_mu[:, 0], solid_gibbs(binary_T_star), atol=physical_tolerance, rtol=0
)
# Each row is one phase composition; beta contains phase MOLE fractions.
three_X = np.vstack([binary_X, [1.0, 0.0]])
beta = np.array([0.35, 0.35, 0.30])
invariant_feed = beta @ three_X # Molar lever rule: z = sum_p beta_p * x_p.
verified = binary_flash(float(binary_T_star), invariant_feed)
candidate_G = sum(
beta[i] * binary_model.reduced_mixing_gibbs(binary_T_star, x)
for i, x in enumerate(binary_X)
) + beta[2] * solid_gibbs(binary_T_star)
print("Flash representation:", verified.phase_kinds)
print("Candidate three-phase G/RT:", candidate_G, "; flashed G/RT:", verified.gibbs)
assert verified.converged and verified.certified
np.testing.assert_allclose(candidate_G, verified.gibbs, atol=2e-6, rtol=0)
Flash representation: ['liquid', 'benzene(s)'] Candidate three-phase G/RT: -0.0001565983041242006 ; flashed G/RT: -0.00015660182786569288
5. Calculate many binary LLE and SLE boundary points¶
A pair of isolated flashes does not show a phase diagram. We now calculate:
- Below \(T_*\): the stable water-rich liquidus, from \(\ln(x_B\gamma_B)=g_B^S/(RT)\). Feeds between that liquid composition and pure benzene form S+L.
- Above \(T_*\): both ends of the liquid–liquid tie line, found by liquid-only HELD flashes. Intermediate feeds form L₁+L₂.
- Between \(T_*\) and \(T_m\): a very narrow benzene-rich liquid+solid interval. A separate bracket selects its concentrated saturation root; taking the first dilute solubility root would select a different branch.
There is a single-liquid interval between the benzene-rich LLE boundary and its liquidus. The third plot magnifies it in composition and temperature. The narrow window is a prediction of these inputs; its many displayed digits are not a claim of experimental accuracy.
# Temperatures are deliberately denser near the tiny interval T_star < T < Tm.
low_T = np.linspace(274.0, binary_T_star, 18)
mid_T = np.linspace(binary_T_star, Tm, 12)
lle_T = np.unique(np.r_[mid_T, np.linspace(Tm + 0.15, 284.0, 18)])
# solubility returns the dilute (water-rich) saturation root in a binary mixture.
low_sle = [solubility(binary_model, 0, float(t), fusion) for t in low_T[:-1]]
low_x = np.r_[[point.solubility for point in low_sle], binary_X[0, 0]]
assert max(point.residual for point in low_sle) < physical_tolerance
# Each row holds [x_B in water-rich liquid, x_B in benzene-rich liquid].
lle_ends = np.array([binary_liquids(float(t))[:, 0] for t in lle_T])
mid_ends = lle_ends[: len(mid_T)]
# At T_star the rich liquid is saturated; at Tm the pure liquid is saturated.
rich_sle_x = [binary_X[1, 0]]
for t, liquid_ends in zip(mid_T[1:-1], mid_ends[1:-1]):
def saturation_residual(x_B):
x = [x_B, 1.0 - x_B]
return (
np.log(x_B)
+ binary_model.ln_activity_coefficients(float(t), x)[0]
- solid_gibbs(t)
)
# Restrict the root to the stable benzene-rich side of the miscibility gap.
rich_sle_x.append(brentq(saturation_residual, liquid_ends[1], 1.0, xtol=1e-12))
rich_sle_x = np.r_[rich_sle_x, 1.0]
print(
"Boundary points: dilute SLE =",
len(low_T),
"; LLE tie lines =",
len(lle_T),
"; rich SLE =",
len(mid_T),
)
print("Predicted rich SLE temperature window [mK]:", 1000.0 * (Tm - binary_T_star))
Boundary points: dilute SLE = 18 ; LLE tie lines = 30 ; rich SLE = 12 Predicted rich SLE temperature window [mK]: 4.8200288272823855
# The shaded regions use computed coexistence compositions, not interpolated
# phase labels from isolated feeds. Markers show the actual calculation points.
# Separate figures keep labels readable in the website's content column.
figures_axes = [
plt.subplots(figsize=(7.5, 4.6), layout="constrained") for _ in range(3)
]
axes = [ax for fig, ax in figures_axes]
for ax in axes[:2]:
ax.fill_betweenx(
low_T, low_x, 1.0, color="tab:orange", alpha=0.22, label="S + L (water-rich)"
)
ax.fill_betweenx(
lle_T,
lle_ends[:, 0],
lle_ends[:, 1],
color="tab:blue",
alpha=0.16,
label="L1 + L2",
)
ax.plot(low_x, low_T, "o-", color="tab:orange", ms=3)
ax.plot(lle_ends[:, 0], lle_T, ".-", color="tab:blue", ms=4)
ax.plot(lle_ends[:, 1], lle_T, ".-", color="tab:blue", ms=4)
ax.axhline(
binary_T_star, color="black", ls="--", lw=0.8, label="S + L1 + L2 invariant"
)
ax.set(
xlabel="Benzene mole fraction", ylabel="Temperature [K]", ylim=(274.0, 284.0)
)
ax.grid(alpha=0.2)
axes[0].set(xlim=(0.0, 1.0), title="Full binary diagram")
axes[0].legend(fontsize=9, loc="lower left")
axes[1].set(xlim=(0.0, 1.15 * lle_ends[:, 0].max()), title="Water-rich boundary detail")
axes[1].ticklabel_format(axis="x", style="sci", scilimits=(0, 0))
# A second coordinate system resolves both the narrow composition and mK scales.
water_ppm_lle = 1e6 * (1.0 - mid_ends[:, 1])
water_ppm_sle = 1e6 * (1.0 - rich_sle_x)
delta_T_mK = 1000.0 * (mid_T - binary_T_star)
zoom_max = 1.4 * water_ppm_lle.max()
ax = axes[2]
ax.fill_betweenx(
delta_T_mK,
0.0,
water_ppm_sle,
color="tab:red",
alpha=0.22,
label="S + L (benzene-rich)",
)
ax.fill_betweenx(
delta_T_mK,
water_ppm_sle,
water_ppm_lle,
color="tab:green",
alpha=0.15,
label="Single liquid",
)
ax.fill_betweenx(
delta_T_mK, water_ppm_lle, zoom_max, color="tab:blue", alpha=0.16, label="L1 + L2"
)
ax.plot(water_ppm_sle, delta_T_mK, "o-", color="tab:red", ms=3, label="SLE liquidus")
ax.plot(water_ppm_lle, delta_T_mK, ".-", color="tab:blue", label="LLE binodal")
ax.axhline(0.0, color="black", ls="--", lw=0.8)
ax.set(
xlim=(0.0, zoom_max),
ylim=(0.0, delta_T_mK[-1]),
xlabel="Water in benzene-rich liquid [mole ppm]",
ylabel=r"$T - T_*$ [mK]",
title="Benzene-rich SLE / LLE detail",
)
ax.legend(fontsize=9)
ax.grid(alpha=0.2)
for fig, ax in figures_axes:
fig.suptitle("openCOSMO-RS: benzene + water, condensed phases at 1 atm")
plt.show()
The coloured intervals correspond to overall feed compositions that split between their boundary phases. On the second figure, a feed left of the boundary is a single water-rich liquid. On the third figure, move from pure benzene towards increasing dissolved water: S+L, then L, then L₁+L₂. The full diagram cannot resolve this very narrow feature without the zoom.
As an independent check, flash two temperatures with solids enabled and compare their liquid compositions with the boundary calculations. An SLE equality alone does not establish stability against another liquid.
for temperature, expected, expected_x in [
(float(low_T[7]), "S+L", low_x[7]),
(float(lle_T[-1]), "L1+L2", lle_ends[-1, 0]),
]:
answer = binary_flash(temperature, [0.5, 0.5])
checks = check_flash(
binary_model, temperature, [0.5, 0.5], answer, tol=physical_tolerance
)
assert phase_label(answer) == expected
liquid_x = sorted(
x[0]
for x, kind in zip(answer.mole_fractions, answer.phase_kinds)
if kind == "liquid"
)
np.testing.assert_allclose(liquid_x[0], expected_x, atol=2e-6, rtol=0)
print("Checked stable boundary at T =", temperature, "K:", expected, checks)
Checked stable boundary at T = 275.92919175283583 K: S+L {'species_balance_error_mol': 1.1102230246251565e-16, 'liquid_mu_error_over_RT': 0.0, 'solid_saturation_error_over_RT': np.float64(1.942890293094024e-16), 'gibbs_reconstruction_error_over_RT': np.float64(3.469446951953614e-18), 'phase_mole_fractions': [0.5001428731295863, 0.49985712687041384], 'phase_mass_fractions': [0.1876432754916431, 0.8123567245083568]}
Checked stable boundary at T = 284.0 K: L1+L2 {'species_balance_error_mol': 1.1102230246251565e-16, 'liquid_mu_error_over_RT': 2.5585544967399176e-15, 'solid_saturation_error_over_RT': 0.0, 'gibbs_reconstruction_error_over_RT': np.float64(0.0), 'phase_mole_fractions': [0.49988542023375715, 0.5001145797662429], 'phase_mass_fractions': [0.8123311878587012, 0.18766881214129894]}
6. Add ethanol and calculate ternary SLLE¶
At 275 K, ethanol changes mutual solubility enough for this model to predict
S+L₁+L₂ for the feed [0.50, 0.20, 0.30]. The liquid model now needs all three
conformer records. The solid remains pure benzene, represented by [1, 0, 0].
At fixed T/P, a ternary three-phase equilibrium has fixed phase compositions. Feeds inside the tie triangle have different amounts of those same phases. This finite triangle is different from the binary three-phase invariant at one temperature. The triangular diagram below uses ordinary mole fractions.
# Build the three-component liquid model in the same benzene/water/ethanol order.
model = build_cosmors_model(parametrization, definitions)
T, P = 275.0, 101325.0 # P records the condensed-phase interpretation, not a PVT solve.
assert T > max(
COMPONENTS[name]["melting_temperature_K"] for name in ["water", "ethanol"]
)
# Verify the pure-liquid standard-state convention for the component present.
for i in range(3):
pure = np.eye(3)[i]
assert abs(model.ln_activity_coefficients(T, pure)[i]) < 1e-5
# This is again an identity chart: three neutral, nonreacting species retained.
chart = ReducedChart.build(
charges=np.zeros(3),
molar_masses=[COMPONENTS[name]["molar_mass_g_mol"] for name in names],
)
print("Ternary coordinate matrix Lambda:\n", chart.Lambda)
np.testing.assert_array_equal(chart.Lambda, np.eye(3))
solid = Solid("benzene(s)", [1.0, 0.0, 0.0], solid_gibbs(T))
solver = ReducedHELD(model, T, chart, settings, solids=[solid])
feed = np.array([0.50, 0.20, 0.30]) # One mole total; not prescribed phase amounts.
result = solver.flash(feed)
assert result.phase_kinds.count("liquid") == 2 and "benzene(s)" in result.phase_kinds
print(phase_table(result, names))
print(check_flash(model, T, feed, result, tol=physical_tolerance))
BINARY SPECS
-------------------------
compile mode: RELEASE
openmp: activated
vectorization: AVX
-------------------------
loadMolecules for every molecule worked...
Ternary coordinate matrix Lambda:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[{'phase': 'liquid', 'mole_fraction_of_total': 0.482033647250305, 'mass_fraction_of_total': 0.3271341916158446, 'x_benzene': 0.10890431474219063, 'x_water': 0.4002420531624783, 'x_ethanol': 0.49085363209533106}, {'phase': 'liquid', 'mole_fraction_of_total': 0.26869299773190664, 'mass_fraction_of_total': 0.32811781216020247, 'x_benzene': 0.7377606076055877, 'x_water': 0.02631203178906886, 'x_ethanol': 0.23592736060534342}, {'phase': 'benzene(s)', 'mole_fraction_of_total': 0.24927335501778833, 'mass_fraction_of_total': 0.34474799622395297, 'x_benzene': 1.0, 'x_water': 0.0, 'x_ethanol': 0.0}]
{'species_balance_error_mol': 2.0574425052544143e-08, 'liquid_mu_error_over_RT': 1.2595358198086437e-07, 'solid_saturation_error_over_RT': np.float64(3.431873328366142e-07), 'gibbs_reconstruction_error_over_RT': np.float64(1.978334163155182e-11), 'phase_mole_fractions': [0.4820336590640868, 0.26869300431709103, 0.24927336112703205], 'phase_mass_fractions': [0.3271341916158446, 0.32811781216020247, 0.34474799622395297]}
Read the result and verify the molar lever rule¶
X[p, i] below is the mole fraction of component i inside phase p.
beta[p] is the fraction of the total feed moles present in that phase.
It is distinct from result.mass_fractions[p]. The identity
\(\mathbf z=\boldsymbol\beta^T X\) reconstructs the feed composition.
Two liquids must have equal relative chemical potentials for all three components. Benzene in each liquid must additionally match benzene(s). Water and ethanol do not enter this pure solid, so their potentials need not equal a solid potential.
X = np.asarray(result.mole_fractions) # One full composition row per phase.
beta = np.array([amounts.sum() for amounts in result.phases]) / feed.sum()
liquid_ids = [i for i, kind in enumerate(result.phase_kinds) if kind == "liquid"]
mu = np.array(
[np.log(X[i]) + model.ln_activity_coefficients(T, X[i]) for i in liquid_ids]
)
print("Phase kinds:", result.phase_kinds)
print("Liquid chemical potentials / RT:\n", mu)
print("Solid benzene potential / RT:", solid.gibbs)
print("Phase mole fractions:", beta)
print("Phase mass fractions:", result.mass_fractions)
np.testing.assert_allclose(beta @ X, feed / feed.sum(), atol=physical_tolerance, rtol=0)
np.testing.assert_allclose(mu[0], mu[1], atol=physical_tolerance, rtol=0)
np.testing.assert_allclose(mu[:, 0], solid.gibbs, atol=physical_tolerance, rtol=0)
# Vertices are computed phase compositions; the black cross is the overall feed.
fig, ax = ternary_plot(result, feed, "openCOSMO-RS: benzene(s) + L1 + L2 at 275 K")
plt.show()
Phase kinds: ['liquid', 'liquid', 'benzene(s)'] Liquid chemical potentials / RT: [[-0.05713405 -0.14580111 -0.78710794] [-0.05713393 -0.145801 -0.78710795]] Solid benzene potential / RT: -0.05713370899434305 Phase mole fractions: [0.48203366 0.268693 0.24927336] Phase mass fractions: [0.32713419 0.32811781 0.344748 ]
7. Change the feed inside the three-phase region¶
Construct another feed as a convex combination of the computed vertices, then flash it independently. The weights construct the new total feed, but are not supplied to the solver as prescribed phase amounts. The phase order can change between runs, so sort vertices before comparing them.
second_feed = np.array([0.25, 0.40, 0.35]) @ X # Positive weights summing to one.
second = solver.flash(second_feed)
print("Second feed [benzene, water, ethanol]:", second_feed)
print(phase_table(second, names))
print(check_flash(model, T, second_feed, second, tol=physical_tolerance))
assert second.phase_kinds.count("liquid") == 2 and "benzene(s)" in second.phase_kinds
first_vertices = np.array(sorted(X, key=lambda x: x[0]))
second_vertices = np.array(sorted(second.mole_fractions, key=lambda x: x[0]))
np.testing.assert_allclose(first_vertices, second_vertices, atol=5e-4, rtol=0)
Second feed [benzene, water, ethanol]: [0.67233032 0.11058533 0.21708435]
[{'phase': 'liquid', 'mole_fraction_of_total': 0.400019057803207, 'mass_fraction_of_total': 0.4276806642806939, 'x_benzene': 0.7377651768417393, 'x_water': 0.02631123544507492, 'x_ethanol': 0.23592358771318594}, {'phase': 'liquid', 'mole_fraction_of_total': 0.24999542332050598, 'mass_fraction_of_total': 0.1485394112925179, 'x_benzene': 0.10890072934711247, 'x_water': 0.4002485168482057, 'x_ethanol': 0.4908507538046819}, {'phase': 'benzene(s)', 'mole_fraction_of_total': 0.34998551887628704, 'mass_fraction_of_total': 0.4237799244267882, 'x_benzene': 1.0, 'x_water': 0.0, 'x_ethanol': 0.0}]
{'species_balance_error_mol': 3.463069699061183e-08, 'liquid_mu_error_over_RT': 1.6170517869174006e-07, 'solid_saturation_error_over_RT': np.float64(7.70782433365258e-08), 'gibbs_reconstruction_error_over_RT': np.float64(1.026034812667831e-11), 'phase_mole_fractions': [0.40001905187194065, 0.24999541961370897, 0.34998551368689096], 'phase_mass_fractions': [0.4276806642806939, 0.1485394112925179, 0.4237799244267882]}
8. Survey the surrounding LLE and SLE regions¶
A single tie triangle hides most of the phase behaviour. We now flash a lattice
of 91 total feeds (resolution=12) across the composition triangle. This
means 12 equal subdivisions along each edge, not 12 total calculations. Increase
it to 20 for 231 lattice feeds when exploring a smaller region in more detail.
The saved survey may take several minutes on a laptop.
We also add interior points to the three-phase triangle: a regular lattice can miss a thin region. Every point, including those extra feeds, is flashed and checked independently. These additional feeds do not force a three-phase result.
| Label | Stable phases among those supplied |
|---|---|
L |
One liquid |
L1+L2 |
Two liquids (LLE) |
S+L |
Pure benzene solid + one liquid (SLE) |
S+L1+L2 |
Pure benzene solid + two liquids (SLLE) |
S |
Pure benzene solid |
We retain feeds that fail the convergence/stability checks as unresolved. A set of coloured feed points is a sampled phase map, not a resolved binodal or liquidus curve. Tie lines and liquid endpoints below come from the actual flashes; we do not draw a smooth boundary through different feed labels.
resolution = 12 # 91 lattice points; raise this only after the coarse map works.
survey_feeds = []
for i in range(resolution + 1):
for j in range(resolution + 1 - i):
# All three coordinates are nonnegative and sum to one mole.
z = np.array([i, j, resolution - i - j], dtype=float) / resolution
survey_feeds.append(z)
# Explicit positive phase-mole weights select additional feeds inside the triangle.
interior_weights = np.array(
[
[0.2, 0.2, 0.6],
[0.2, 0.6, 0.2],
[0.6, 0.2, 0.2],
[0.4, 0.4, 0.2],
[0.4, 0.2, 0.4],
[0.2, 0.4, 0.4],
]
)
survey_feeds.extend(interior_weights @ X)
survey_feeds.extend([feed, second_feed])
survey_feeds = np.unique(np.round(survey_feeds, 12), axis=0) # Remove duplicate feeds.
# Keep the complete answer so we can plot both the feed and its phase endpoints.
survey = []
unresolved = []
for index, z in enumerate(survey_feeds):
answer = solver.flash(z)
if answer.converged and answer.certified:
# A flag alone is insufficient: check the direct physical residuals too.
try:
check_flash(model, T, z, answer, tol=physical_tolerance)
except AssertionError as error:
unresolved.append((z, "Physical check failed: " + str(error)))
else:
survey.append((z, phase_label(answer), answer))
else:
unresolved.append((z, "Solver convergence/stability check failed"))
if (index + 1) % 20 == 0 or index + 1 == len(survey_feeds):
print("Flashed", index + 1, "/", len(survey_feeds), "feeds")
counts = {
label: sum(entry[1] == label for entry in survey)
for label in sorted({entry[1] for entry in survey})
}
print("Accepted feeds by assemblage:", counts)
print("Unresolved feeds:", len(unresolved))
for z, reason in unresolved:
print(" Refine this feed:", z, ";", reason)
Flashed 20 / 99 feeds
Flashed 40 / 99 feeds
Flashed 60 / 99 feeds
Flashed 80 / 99 feeds
Flashed 99 / 99 feeds
Accepted feeds by assemblage: {'L': 36, 'L1+L2': 6, 'S': 1, 'S+L': 42, 'S+L1+L2': 11}
Unresolved feeds: 3
Refine this feed: [0.25 0.33333333 0.41666667] ; Physical check failed: 0.0003609208228688779
Refine this feed: [0.58333333 0.16666667 0.25 ] ; Physical check failed: 0.001550317628918059
Refine this feed: [0.83333333 0. 0.16666667] ; Solver convergence/stability check failed
Plot feeds, tie lines and the computed SLLE triangle¶
The first figure answers “what phases does this overall feed form?” The second figure shows selected two-phase tie lines: LLE lines join two liquid compositions; SLE lines join a saturated liquid to pure benzene(s). A feed lies on the segment joining its coexisting phases, with its position set by their phase mole amounts.
The open circles in the second figure are liquid endpoint compositions, not feeds. Each three-phase feed lies inside the orange triangle. The solid and both liquid vertices are fixed at this T/P, although phase amounts vary across the triangle.
from matplotlib.patches import Polygon
from matplotlib.lines import Line2D
# Use the same colours on the feed map and the equilibrium tie-line diagram.
colours = {
"L": "tab:green",
"L1+L2": "tab:blue",
"S+L": "tab:red",
"S+L1+L2": "tab:orange",
"S": "tab:purple",
}
# A full-width figure for each view keeps the phase labels and endpoints legible.
figures_axes = [
plt.subplots(figsize=(7.5, 5.5), layout="constrained") for _ in range(2)
]
axes = [ax for fig, ax in figures_axes]
for ax in axes:
corners = ternary_axes(ax) # Physical mole fractions -> 2D drawing coordinates.
vertices_xy = X @ corners
ax.add_patch(
Polygon(
vertices_xy,
closed=True,
facecolor="tab:orange",
edgecolor="tab:orange",
alpha=0.2,
)
)
# Plot the overall composition of every accepted flash, coloured by assemblage.
for label in colours:
points = [z for z, kind, answer in survey if kind == label]
if points:
xy = np.asarray(points) @ corners
axes[0].scatter(
xy[:, 0],
xy[:, 1],
s=28,
color=colours[label],
label=f"{label} ({len(points)})",
zorder=3,
)
if unresolved:
xy = np.asarray([z for z, reason in unresolved]) @ corners
axes[0].scatter(
xy[:, 0], xy[:, 1], marker="x", color="black", label="Unresolved", zorder=4
)
axes[0].set_title("Overall feeds: sampled phase assemblages")
axes[0].legend(fontsize=9, loc="upper right")
# Show a readable subset of the computed two-phase lines; all feeds were solved.
for label in ["L1+L2", "S+L"]:
entries = [(z, answer) for z, kind, answer in survey if kind == label]
stride = max(1, int(np.ceil(len(entries) / 9)))
for z, answer in entries[::stride]:
endpoints = np.asarray(answer.mole_fractions) @ corners
axes[1].plot(
endpoints[:, 0], endpoints[:, 1], color=colours[label], alpha=0.4, lw=0.8
)
liquid_rows = [
x
for x, kind in zip(answer.mole_fractions, answer.phase_kinds)
if kind == "liquid"
]
liquid_xy = np.asarray(liquid_rows) @ corners
axes[1].scatter(
liquid_xy[:, 0],
liquid_xy[:, 1],
s=20,
facecolors="none",
edgecolors=colours[label],
)
axes[1].scatter(
vertices_xy[:, 0], vertices_xy[:, 1], s=45, color="tab:orange", zorder=4
)
# Identify liquid roles from component compositions, regardless of solver order.
water_rich_id = min(liquid_ids, key=lambda i: X[i, 0])
for index, (xy, kind) in enumerate(zip(vertices_xy, result.phase_kinds)):
label = (
"S"
if kind == "benzene(s)"
else ("L (water-rich)" if index == water_rich_id else "L (benzene-rich)")
)
axes[1].annotate(label, xy, xytext=(4, 8), textcoords="offset points", fontsize=9)
axes[1].set_title("Computed coexistence: liquid endpoints and tie lines")
axes[1].legend(
handles=[
Line2D([0], [0], color="tab:blue", label="LLE tie lines"),
Line2D([0], [0], color="tab:red", label="SLE tie lines"),
Polygon([[0, 0]], facecolor="tab:orange", alpha=0.3, label="SLLE tie triangle"),
],
fontsize=9,
loc="upper right",
)
for fig, ax in figures_axes:
fig.suptitle("openCOSMO-RS: benzene / water / ethanol, 275 K, 1 atm")
plt.show()
Read the saved survey critically¶
For the printed default inputs, 96 of 99 feeds pass the checks: 36 single liquids, 6 LLE feeds, 42 SLE feeds, 11 SLLE feeds and 1 pure solid. Three feeds remain unresolved and appear as black crosses. Two fail a direct physical residual check despite the solver flags; one does not pass the solver's own convergence/stability check. Do not assign those crosses a phase label from their neighbours. Revisit their search settings and physical residuals before using them to refine a boundary.
The blue LLE feeds lie above the orange SLLE triangle; the red SLE feeds lie below it, and green single-liquid feeds occupy much of the ethanol-rich region. These statements describe this computed example, not every COSMO-RS parameter set. The extra orange feeds make the three-phase region visible even where the regular lattice is too coarse to sample it well.
9. What to change in your own calculation¶
- A new feed: change its three mole amounts, rerun the flash and checks, then locate it on the map. Feed composition does not prescribe phase composition.
- A new temperature: reconstruct the solid with
solid_gibbs(new_T)and create a new solver. Recalculate the triangle and survey; do not reuse vertices from 275 K. - A new component: change the conformer records, all component-ordered arrays, the molar masses and the set of possible solids, with appropriate fusion data.
- A new parametrization: print its identity and inspect the resulting phases before reusing assertions about a three-phase region or temperature bracket.
- More detail: refine temperatures/compositions around a boundary or increase
the survey resolution.
resolution=20produces 231 lattice feeds, plus the extra interior feeds, so it costs more model evaluations.
_support.py supplies data, plotting, solver settings and independent checks;
model construction, chart construction, flashes and boundary equations stay
visible above. SAFT and COSMO-RS need not predict the same boundaries. Compare
models at identical conditions with consistent solid/reference-state conventions,
then compare with measurements to assess predictive accuracy.
Continue with the phase-equilibrium theory, the binary SAFT calculation, or the ternary SAFT calculation.
<style>
['pre { line-height: 125%; }\ntd.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\nspan.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\ntd.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\nspan.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\n.highlight-ipynb .hll { background-color: var(--jp-cell-editor-active-background) }\n.highlight-ipynb { background: var(--jp-cell-editor-background); color: var(--jp-mirror-editor-variable-color) }\n.highlight-ipynb .c { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment */\n.highlight-ipynb .err { color: var(--jp-mirror-editor-error-color) } /* Error */\n.highlight-ipynb .k { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword */\n.highlight-ipynb .o { color: var(--jp-mirror-editor-operator-color); font-weight: bold } /* Operator */\n.highlight-ipynb .p { color: var(--jp-mirror-editor-punctuation-color) } /* Punctuation */\n.highlight-ipynb .ch { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Hashbang */\n.highlight-ipynb .cm { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Multiline */\n.highlight-ipynb .cp { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Preproc */\n.highlight-ipynb .cpf { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.PreprocFile */\n.highlight-ipynb .c1 { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Single */\n.highlight-ipynb .cs { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Special */\n.highlight-ipynb .kc { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Constant */\n.highlight-ipynb .kd { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Declaration */\n.highlight-ipynb .kn { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Namespace */\n.highlight-ipynb .kp { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Pseudo */\n.highlight-ipynb .kr { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Reserved */\n.highlight-ipynb .kt { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Type */\n.highlight-ipynb .m { color: var(--jp-mirror-editor-number-color) } /* Literal.Number */\n.highlight-ipynb .s { color: var(--jp-mirror-editor-string-color) } /* Literal.String */\n.highlight-ipynb .ow { color: var(--jp-mirror-editor-operator-color); font-weight: bold } /* Operator.Word */\n.highlight-ipynb .pm { color: var(--jp-mirror-editor-punctuation-color) } /* Punctuation.Marker */\n.highlight-ipynb .w { color: var(--jp-mirror-editor-variable-color) } /* Text.Whitespace */\n.highlight-ipynb .mb { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Bin */\n.highlight-ipynb .mf { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Float */\n.highlight-ipynb .mh { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Hex */\n.highlight-ipynb .mi { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Integer */\n.highlight-ipynb .mo { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Oct */\n.highlight-ipynb .sa { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Affix */\n.highlight-ipynb .sb { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Backtick */\n.highlight-ipynb .sc { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Char */\n.highlight-ipynb .dl { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Delimiter */\n.highlight-ipynb .sd { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Doc */\n.highlight-ipynb .s2 { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Double */\n.highlight-ipynb .se { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Escape */\n.highlight-ipynb .sh { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Heredoc */\n.highlight-ipynb .si { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Interpol */\n.highlight-ipynb .sx { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Other */\n.highlight-ipynb .sr { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Regex */\n.highlight-ipynb .s1 { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Single */\n.highlight-ipynb .ss { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Symbol */\n.highlight-ipynb .il { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Integer.Long */']
</style>