From c552ef8486884e16773da1f94f473320002117ff Mon Sep 17 00:00:00 2001 From: Philipp Rehner Date: Fri, 2 Oct 2026 18:58:25 +0200 Subject: [PATCH] Implement FC-SAFT equation of state --- CHANGELOG.md | 5 + crates/feos/Cargo.toml | 2 + crates/feos/src/fcsaft/dft/dispersion.rs | 122 +++ crates/feos/src/fcsaft/dft/fused_chain.rs | 93 +++ crates/feos/src/fcsaft/dft/mod.rs | 285 +++++++ crates/feos/src/fcsaft/eos/dispersion.rs | 146 ++++ crates/feos/src/fcsaft/eos/mod.rs | 205 +++++ .../src/fcsaft/homosegmented/fcsaft_binary.rs | 706 ++++++++++++++++++ .../src/fcsaft/homosegmented/fcsaft_pure.rs | 361 +++++++++ crates/feos/src/fcsaft/homosegmented/mod.rs | 485 ++++++++++++ .../src/fcsaft/homosegmented/parameters.rs | 163 ++++ crates/feos/src/fcsaft/homosegmented/polar.rs | 139 ++++ crates/feos/src/fcsaft/mod.rs | 43 ++ crates/feos/src/fcsaft/parameters.rs | 121 +++ crates/feos/src/fcsaft/record.rs | 119 +++ crates/feos/src/fcsaft/reference.rs | 165 ++++ crates/feos/src/hard_sphere/mod.rs | 26 +- crates/feos/src/lib.rs | 2 + docs/api/ad.md | 4 +- docs/api/dft.md | 1 + docs/api/eos.md | 1 + docs/theory/models/fcsaft.md | 114 +++ docs/theory/models/hard_spheres.md | 4 +- docs/theory/models/index.md | 1 + py-feos/Cargo.toml | 5 +- py-feos/src/ad/mod.rs | 42 +- py-feos/src/eos/fcsaft.rs | 137 ++++ py-feos/src/eos/mod.rs | 2 + py-feos/src/lib.rs | 6 +- py-feos/src/parameter/mod.rs | 71 +- py-feos/src/residual.rs | 14 + 31 files changed, 3570 insertions(+), 20 deletions(-) create mode 100644 crates/feos/src/fcsaft/dft/dispersion.rs create mode 100644 crates/feos/src/fcsaft/dft/fused_chain.rs create mode 100644 crates/feos/src/fcsaft/dft/mod.rs create mode 100644 crates/feos/src/fcsaft/eos/dispersion.rs create mode 100644 crates/feos/src/fcsaft/eos/mod.rs create mode 100644 crates/feos/src/fcsaft/homosegmented/fcsaft_binary.rs create mode 100644 crates/feos/src/fcsaft/homosegmented/fcsaft_pure.rs create mode 100644 crates/feos/src/fcsaft/homosegmented/mod.rs create mode 100644 crates/feos/src/fcsaft/homosegmented/parameters.rs create mode 100644 crates/feos/src/fcsaft/homosegmented/polar.rs create mode 100644 crates/feos/src/fcsaft/mod.rs create mode 100644 crates/feos/src/fcsaft/parameters.rs create mode 100644 crates/feos/src/fcsaft/record.rs create mode 100644 crates/feos/src/fcsaft/reference.rs create mode 100644 docs/theory/models/fcsaft.md create mode 100644 py-feos/src/eos/fcsaft.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index c22587814..bb2e54c4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added `drho_dn` and `drho_dt_n` to DFT profiles to calculate derivatives of density profiles at constant number of particles. [#403](https://github.com/feos-org/feos/pull/403) - Added the association functionals of Yu and Wu, WDA, and iSAFT with the fractions of non-bonded sites as additional variables of the density profile. The version is selected with `AssociationVersion` (default iSAFT). [#403](https://github.com/feos-org/feos/pull/403) - Added `non_bonded_fractions` to DFT profiles to access the fractions of non-bonded association sites. [#403](https://github.com/feos-org/feos/pull/403) +- Added the heterosegmented fused-chain SAFT (FC-SAFT) equation of state and Helmholtz energy functional (feature `fcsaft`). +- Added optional bond records (`bond_records`/`bonds_path`) to `GcParameters` in Python for models that require bond parameters. +- Added `FcSaftPure` and `FcSaftBinary`, optimized pure-component and binary implementations of FC-SAFT that support automatic differentiation with respect to model parameters, available in Python as `EquationOfStateAD.FcSaftNonAssoc` and `EquationOfStateAD.FcSaftFull`. ### Changed - Removed most heap allocations from the evaluation of the residual Helmholtz energy of PC-SAFT. [#397](https://github.com/feos-org/feos/pull/397) @@ -20,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `HelmholtzEnergyFunctional::evaluate_bulk` passes each contribution to a closure instead of returning a `Vec`. [#397](https://github.com/feos-org/feos/pull/397) - `MonomerShape::NonSpherical` holds a reference `&DVector` to the segment numbers instead of an owned `DVector`. [#397](https://github.com/feos-org/feos/pull/397) - `StateHD::new_density` takes the partial densities by value. [#397](https://github.com/feos-org/feos/pull/397) +- The `ad` feature of the Python package no longer activates any models. The `EquationOfStateAD` variants are available depending on the active model features (`pcsaft`, `fcsaft`). - Changed data type of initial temperatures or pressure for phase equilibrium calculations (`TemperatureOrPressure::Other`) from `D` to `f64`. [#369](https://github.com/feos-org/feos/pull/369) - Reworked DFT solution algorithms slightly for the cases in which additional specifications are given. [#371](https://github.com/feos-org/feos/pull/371) - External potentials are passed and returned as quantities (energies) instead of reduced units. [#372](https://github.com/feos-org/feos/pull/372) @@ -40,6 +44,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - The Newton solver for cDFT now correctly handles specifications other than the chemical potential. [#384](https://github.com/feos-org/feos/pull/384) +- The analytic (non-cross-associating) branches of the Yu-Wu association functional now evaluate the association strength for the correct segments instead of always using the parameters of the first segment. ### Packaging - Removed the `gauss-quad` dependency which was only used in the FEA potential calculation. [#376](https://github.com/feos-org/feos/pull/376) diff --git a/crates/feos/Cargo.toml b/crates/feos/Cargo.toml index 28e6e6109..c6c50afc9 100644 --- a/crates/feos/Cargo.toml +++ b/crates/feos/Cargo.toml @@ -42,6 +42,7 @@ dft = ["feos-dft", "petgraph", "ndarray", "num-dual/ndarray", "feos-derive"] association = [] pcsaft = ["association"] epcsaft = ["association"] +fcsaft = ["association", "petgraph"] gc_pcsaft = ["association"] uvtheory = [] pets = [] @@ -53,6 +54,7 @@ all_models = [ "dft", "pcsaft", "epcsaft", + "fcsaft", "gc_pcsaft", "uvtheory", "pets", diff --git a/crates/feos/src/fcsaft/dft/dispersion.rs b/crates/feos/src/fcsaft/dft/dispersion.rs new file mode 100644 index 000000000..2791fbf6a --- /dev/null +++ b/crates/feos/src/fcsaft/dft/dispersion.rs @@ -0,0 +1,122 @@ +use crate::fcsaft::eos::dispersion::{A0, A1, A2, B0, B1, B2}; +use crate::fcsaft::parameters::FcSaftPars; +use crate::fcsaft::reference::ReferenceFluid; +use crate::hard_sphere::HardSphereProperties; +use feos_core::FeosResult; +use feos_dft::{FunctionalContribution, WeightFunction, WeightFunctionInfo, WeightFunctionShape}; +use nalgebra::DVector; +use ndarray::*; +use num_dual::DualNum; +use std::f64::consts::{FRAC_PI_6, PI}; + +#[derive(Clone)] +pub struct DispersionFunctional<'a> { + parameters: &'a FcSaftPars, +} + +impl<'a> DispersionFunctional<'a> { + pub fn new(parameters: &'a FcSaftPars) -> Self { + Self { parameters } + } +} + +impl<'a> FunctionalContribution for DispersionFunctional<'a> { + fn name(&self) -> &'static str { + "Dispersion functional" + } + + fn weight_functions + Copy>( + &self, + temperature: N, + ) -> WeightFunctionInfo { + let p = &self.parameters; + let d = p.hs_diameter(temperature); + WeightFunctionInfo::new(p.component_index.len(), false).add( + WeightFunction::new_scaled( + d.zip_map(&p.psi_dft, |d, psi| d * psi), + WeightFunctionShape::Theta, + ), + false, + ) + } + + fn helmholtz_energy_density + Copy>( + &self, + temperature: N, + density: ArrayView2, + ) -> FeosResult> { + // auxiliary variables + let p = &self.parameters; + let n = p.sigma.len(); + + // temperature dependent segment diameter + let d = p.hs_diameter(temperature); + let av = p.fused_sphere_coefficients(&d); + let [a, v] = &av; + + // packing fraction + let eta = density + .outer_iter() + .zip(d.iter().zip(v.iter())) + .map(|(rho, (&d, &v))| &rho * (d.powi(3) * v * FRAC_PI_6)) + .reduce(|a, b| a + b) + .unwrap(); + + // local densities of the molecules of every component + let n_comp = p.component_index[n - 1] + 1; + let mut m_i: DVector = DVector::zeros(n_comp); + let mut s_i: Vec = vec![0.0; n_comp]; + for (&c, &a) in p.component_index.iter().zip(a.iter()) { + m_i[c] += a; + s_i[c] += 1.0; + } + let mut rho_comp: Array2 = Array::zeros((n_comp, eta.len())); + for (rho, &c) in density.outer_iter().zip(p.component_index.iter()) { + let mut rho_c = rho_comp.index_axis_mut(Axis(0), c); + rho_c += &rho.mapv(|r| r / s_i[c]); + } + + // mean segment number and compressibility term of the local reference fluid + // (in the limit of vanishing density m_bar = 1 and C1 = 1) + let reference = ReferenceFluid::new(&p.component_index, &p.bonds, &d, &av); + let mut m_bar: Array1 = Array::ones(eta.raw_dim()); + let mut c1: Array1 = Array::ones(eta.raw_dim()); + let mut x = DVector::zeros(n_comp); + for (k, rho) in rho_comp.axis_iter(Axis(1)).enumerate() { + let density = rho.sum(); + if density.re() > f64::EPSILON { + x.iter_mut().zip(rho).for_each(|(x, &r)| *x = r / density); + m_bar[k] = x.dot(&m_i); + c1[k] = reference.helmholtz_energy_density(density, &x).1; + } + } + + // mixture densities, crosswise interactions of all segments on all chains + let mut rho1mix: Array1 = Array::zeros(eta.raw_dim()); + let mut rho2mix: Array1 = Array::zeros(eta.raw_dim()); + for i in 0..n { + for j in 0..n { + let eps_ij = temperature.recip() * p.epsilon_k_ij[(i, j)]; + let sigma_ij = p.sigma_ij[(i, j)].powi(3); + let rho_ij = &density.index_axis(Axis(0), i) * &density.index_axis(Axis(0), j); + rho1mix += &rho_ij.mapv(|x| x * (eps_ij * sigma_ij * a[i] * a[j])); + rho2mix += &rho_ij.mapv(|x| x * (eps_ij * eps_ij * sigma_ij * a[i] * a[j])); + } + } + + // I1 and I2 + let mut i1: Array1 = Array::zeros(eta.raw_dim()); + let mut i2: Array1 = Array::zeros(eta.raw_dim()); + let mut eta_i: Array1 = Array::ones(eta.raw_dim()); + let m1 = (m_bar.clone() - 1.0) / &m_bar; + let m2 = (m_bar.clone() - 2.0) / &m_bar * &m1; + for i in 0..=6 { + i1 = i1 + (&m2 * A2[i] + &m1 * A1[i] + A0[i]) * &eta_i; + i2 = i2 + (&m2 * B2[i] + &m1 * B1[i] + B0[i]) * &eta_i; + eta_i = &eta_i * η + } + + // Helmholtz energy density + Ok((-rho1mix * i1 * 2.0 - rho2mix * m_bar * c1 * i2) * PI) + } +} diff --git a/crates/feos/src/fcsaft/dft/fused_chain.rs b/crates/feos/src/fcsaft/dft/fused_chain.rs new file mode 100644 index 000000000..52f7007d1 --- /dev/null +++ b/crates/feos/src/fcsaft/dft/fused_chain.rs @@ -0,0 +1,93 @@ +use crate::fcsaft::parameters::FcSaftPars; +use crate::hard_sphere::HardSphereProperties; +use feos_core::FeosResult; +use feos_dft::{FunctionalContribution, WeightFunction, WeightFunctionInfo, WeightFunctionShape}; +use ndarray::*; +use num_dual::DualNum; +use petgraph::visit::EdgeRef; + +#[derive(Clone)] +pub struct FusedChainFunctional<'a> { + parameters: &'a FcSaftPars, +} + +impl<'a> FusedChainFunctional<'a> { + pub fn new(parameters: &'a FcSaftPars) -> Self { + Self { parameters } + } +} + +impl<'a> FunctionalContribution for FusedChainFunctional<'a> { + fn name(&self) -> &'static str { + "Fused hard chain functional" + } + + fn weight_functions + Copy>( + &self, + temperature: N, + ) -> WeightFunctionInfo { + let p = &self.parameters; + let d = p.hs_diameter(temperature); + let [a, v] = p.fused_sphere_coefficients(&d); + WeightFunctionInfo::new(p.component_index.len(), true) + .add( + WeightFunction { + prefactor: a.component_div(&(&d * N::from(8.0))), + kernel_radius: d.clone(), + shape: WeightFunctionShape::Theta, + }, + true, + ) + .add( + WeightFunction { + prefactor: v / N::from(8.0), + kernel_radius: d, + shape: WeightFunctionShape::Theta, + }, + true, + ) + } + + fn helmholtz_energy_density + Copy>( + &self, + temperature: N, + weighted_densities: ArrayView2, + ) -> FeosResult> { + let p = &self.parameters; + + // number of segments + let n = weighted_densities.shape()[0] - 2; + + // temperature dependent segment diameter + let diameter = p.hs_diameter(temperature); + + // weighted densities + let rho = weighted_densities.slice_axis(Axis(0), Slice::new(0, Some(n as isize), 1)); + let zeta2 = weighted_densities.index_axis(Axis(0), n); + let zeta3 = weighted_densities.index_axis(Axis(0), n + 1); + + let z3i = zeta3.mapv(|z3| (-z3 + 1.0).recip()); + + let mut phi = Array1::zeros(zeta2.raw_dim()); + for i in p.bonds.node_indices() { + let rho_i = rho.index_axis(Axis(0), i.index()); + let y = p + .bonds + .edges(i) + .map(|e| { + let l = *e.weight(); + let s1 = diameter[e.source().index()]; + let s2 = diameter[e.target().index()]; + let b = -((s1 - s2).powi(2) - 4.0 * l.powi(2)) / (4.0 * l); + let z2l = zeta2.mapv(|z2| z2 * b); + &z2l * &z3i * &z3i * (z2l * &z3i * 0.5 + 1.5) + &z3i + }) + .reduce(|acc, y| acc * y); + if let Some(y) = y { + phi -= &(y.map(N::ln) * rho_i * 0.5); + } + } + + Ok(phi) + } +} diff --git a/crates/feos/src/fcsaft/dft/mod.rs b/crates/feos/src/fcsaft/dft/mod.rs new file mode 100644 index 000000000..7246da146 --- /dev/null +++ b/crates/feos/src/fcsaft/dft/mod.rs @@ -0,0 +1,285 @@ +use super::FcSaftOptions; +use super::parameters::FcSaftPars; +use super::record::FcSaftParameters; +use crate::association::{AssociationVersion, SaftAssociationFunctional}; +use crate::hard_sphere::{FMTContribution, FMTVersion}; +use feos_core::{FeosResult, Molarweight, ResidualDyn, StateHD, Subset}; +use feos_derive::FunctionalContribution; +use feos_dft::adsorption::FluidParameters; +use feos_dft::{ + FunctionalContribution, HelmholtzEnergyFunctional, HelmholtzEnergyFunctionalDyn, MoleculeShape, +}; +use nalgebra::DVector; +use ndarray::Array1; +use num_dual::DualNum; +use petgraph::graph::UnGraph; +use quantity::MolarWeight; +use std::f64::consts::FRAC_PI_6; + +mod dispersion; +mod fused_chain; +use dispersion::DispersionFunctional; +use fused_chain::FusedChainFunctional; + +/// Heterosegmented FC-SAFT Helmholtz energy functional. +pub struct FcSaftFunctional { + pub parameters: FcSaftParameters, + pub params: FcSaftPars, + fmt_version: FMTVersion, + association_version: AssociationVersion, + options: FcSaftOptions, +} + +impl FcSaftFunctional { + pub fn new(parameters: FcSaftParameters) -> Self { + Self::with_options( + parameters, + FMTVersion::WhiteBear, + AssociationVersion::ISaft, + FcSaftOptions::default(), + ) + } + + pub fn with_options( + parameters: FcSaftParameters, + fmt_version: FMTVersion, + association_version: AssociationVersion, + options: FcSaftOptions, + ) -> Self { + let params = FcSaftPars::new(¶meters); + Self { + parameters, + params, + fmt_version, + association_version, + options, + } + } +} + +impl Subset for FcSaftFunctional { + fn subset(&self, component_list: &[usize]) -> Self { + Self::with_options( + self.parameters.subset(component_list), + self.fmt_version, + self.association_version, + self.options, + ) + } +} + +impl ResidualDyn for FcSaftFunctional { + fn components(&self) -> usize { + self.parameters.molar_weight.len() + } + + fn compute_max_density + Copy>(&self, molefracs: &DVector) -> D { + let p = &self.params; + let [_, v] = p.fused_sphere_coefficients(&p.sigma); + let segment_volume: D = (0..p.sigma.len()) + .map(|i| molefracs[p.component_index[i]] * p.sigma[i].powi(3) * v[i]) + .sum(); + (segment_volume * FRAC_PI_6).recip() * self.options.max_eta + } + + fn for_each_contribution + Copy>( + &self, + state: &StateHD, + f: impl FnMut(&'static str, D), + ) { + self.evaluate_bulk(state, f) + } +} + +impl HelmholtzEnergyFunctionalDyn for FcSaftFunctional { + type Contribution<'a> = FcSaftFunctionalContribution<'a>; + type Association<'a> = SaftAssociationFunctional<'a, FcSaftPars>; + + fn molecule_shape(&self) -> MoleculeShape<'_> { + MoleculeShape::Heterosegmented(&self.params.component_index) + } + + fn contributions<'a>(&'a self) -> impl Iterator> { + let mut contributions = Vec::with_capacity(4); + + // Hard sphere contribution + let hs = FMTContribution::new(&self.params, self.fmt_version); + contributions.push(hs.into()); + + // Fused hard chains + let chain = FusedChainFunctional::new(&self.params); + contributions.push(chain.into()); + + // Dispersion + let disp = DispersionFunctional::new(&self.params); + contributions.push(disp.into()); + + contributions.into_iter() + } + + fn bond_lengths + Copy>(&self, _: N) -> UnGraph<(), N> { + self.params.bonds.map(|_, _| (), |_, &l| N::from(l)) + } + + fn association(&self) -> Option> { + (!self.parameters.association.is_empty()).then(|| { + SaftAssociationFunctional::new( + &self.params, + &self.parameters.association, + self.association_version, + ) + }) + } +} + +impl Molarweight for FcSaftFunctional { + fn molar_weight(&self) -> MolarWeight> { + self.parameters.molar_weight.clone() + } +} + +impl FluidParameters for FcSaftFunctional { + fn epsilon_k_ff(&self) -> DVector { + self.params.epsilon_k.clone() + } + + fn sigma_ff(&self) -> DVector { + self.params.sigma.clone() + } +} + +/// Individual contributions for the FC-SAFT Helmholtz energy functional. +#[derive(FunctionalContribution)] +pub enum FcSaftFunctionalContribution<'a> { + Fmt(FMTContribution<'a, FcSaftPars>), + FusedChain(FusedChainFunctional<'a>), + Dispersion(DispersionFunctional<'a>), +} + +#[cfg(test)] +mod test { + use super::*; + use crate::fcsaft::{FcSaft, FcSaftAssociationRecord, FcSaftBondRecord, FcSaftRecord}; + use approx::assert_relative_eq; + use feos_core::parameter::{ + AssociationRecord, BinarySegmentRecord, ChemicalRecord, SegmentRecord, + }; + use feos_core::{FeosResult, ReferenceSystem, State}; + use nalgebra::dvector; + use quantity::{KELVIN, METER, MOL}; + + fn binary_mixture() -> FeosResult { + let association = vec![AssociationRecord::new( + Some(FcSaftAssociationRecord::new(0.03, 2500.0)), + 1.0, + 1.0, + 0.0, + )]; + let segments = [ + SegmentRecord::new("A".into(), 15.0, FcSaftRecord::new(3.6, 180.0, None)), + SegmentRecord::new("B".into(), 14.0, FcSaftRecord::new(3.2, 220.0, None)), + SegmentRecord::with_association( + "C".into(), + 17.0, + FcSaftRecord::new(2.9, 300.0, None), + association, + ), + ]; + let bond = |id1: &str, id2: &str, l| { + BinarySegmentRecord::new(id1.into(), id2.into(), Some(FcSaftBondRecord::new(l))) + }; + let bonds = [ + bond("A", "B", 2.2), + bond("B", "B", 2.0), + bond("B", "C", 2.4), + ]; + let chemical_records = vec![ + ChemicalRecord::new( + Default::default(), + vec!["A".into(), "B".into(), "C".into()], + None, + ), + ChemicalRecord::new( + Default::default(), + vec!["A".into(), "B".into(), "B".into(), "A".into()], + None, + ), + ]; + let binary = [BinarySegmentRecord::new( + "A".into(), + "C".into(), + Some(crate::fcsaft::FcSaftBinaryRecord::new(0.05)), + )]; + FcSaftParameters::from_segments_with_bonds( + chemical_records, + &segments, + Some(&binary), + &bonds, + ) + } + + #[test] + fn test_bulk_implementation() -> FeosResult<()> { + let eos = FcSaft::new(binary_mixture()?); + let func = FcSaftFunctional::new(binary_mixture()?); + let t = 300.0 * KELVIN; + let v = METER.powi::<3>(); + let n = dvector![300.0, 200.0] * MOL; + let p_eos = State::new_nvt(&&eos, t, v, &n)?.pressure_contributions(); + let mut p_func = State::new_nvt(&&func, t, v, &n)?.pressure_contributions(); + // the functional additionally reports the (vanishing) ideal chain contribution + // (before the association contribution) + let i = p_func + .iter() + .position(|(name, _)| *name == "Ideal chain") + .unwrap(); + assert_eq!(p_func.remove(i).1.to_reduced(), 0.0); + assert_eq!(p_eos.len(), p_func.len()); + for ((name_eos, p_eos), (name_func, p_func)) in p_eos.iter().zip(&p_func) { + println!("{name_eos:20} {p_eos:13.8} | {name_func:30} {p_func:13.8}"); + assert_relative_eq!(p_eos, p_func, max_relative = 1e-10); + } + Ok(()) + } + + #[test] + fn test_bulk_implementation_monomers() -> FeosResult<()> { + // mixtures that contain monomers, including a mixture of only monomers + let segment_records = [ + SegmentRecord::new("A".into(), 16.0, FcSaftRecord::new(3.7, 150.0, None)), + SegmentRecord::new("B".into(), 40.0, FcSaftRecord::new(3.4, 120.0, None)), + ]; + let bond_records = [BinarySegmentRecord::new( + "B".into(), + "B".into(), + Some(FcSaftBondRecord::new(2.0)), + )]; + for segments in [1, 2] { + let chemical_records = vec![ + ChemicalRecord::new(Default::default(), vec!["A".into()], None), + ChemicalRecord::new(Default::default(), vec!["B".into(); segments], None), + ]; + let params = || { + FcSaftParameters::from_segments_with_bonds( + chemical_records.clone(), + &segment_records, + None, + &bond_records, + ) + }; + let eos = FcSaft::new(params()?); + let func = FcSaftFunctional::new(params()?); + let t = 300.0 * KELVIN; + let v = METER.powi::<3>(); + let n = dvector![300.0, 200.0] * MOL; + let p_eos = State::new_nvt(&&eos, t, v, &n)?.pressure_contributions(); + let p_func = State::new_nvt(&&func, t, v, &n)?.pressure_contributions(); + for ((name, p_eos), (_, p_func)) in p_eos.iter().zip(&p_func) { + println!("{segments} {name:20} {p_eos:13.8} {p_func:13.8}"); + assert!(p_func.into_reduced().is_finite()); + assert_relative_eq!(p_eos, p_func, max_relative = 1e-10); + } + } + Ok(()) + } +} diff --git a/crates/feos/src/fcsaft/eos/dispersion.rs b/crates/feos/src/fcsaft/eos/dispersion.rs new file mode 100644 index 000000000..e06ca3365 --- /dev/null +++ b/crates/feos/src/fcsaft/eos/dispersion.rs @@ -0,0 +1,146 @@ +use feos_core::StateHD; +use nalgebra::{DMatrix, DVector}; +use num_dual::DualNum; +use std::f64::consts::{FRAC_PI_6, PI}; + +pub const A0: [f64; 7] = [ + 0.91056314451539, + 0.63612814494991, + 2.68613478913903, + -26.5473624914884, + 97.7592087835073, + -159.591540865600, + 91.2977740839123, +]; +pub const A1: [f64; 7] = [ + -0.7967554406765953, + 2.6790885480460225, + -3.487146197861997, + 12.880375286361222, + -63.678387954754264, + 135.2293725600522, + -92.36174418380334, +]; +pub const A2: [f64; 7] = [ + 0.07899144809821383, + -0.46265604871501964, + -0.16852522804500122, + -0.5690540299027762, + -0.10891595731602507, + 6.978853948715148, + -5.413574400329618, +]; +pub const B0: [f64; 7] = [ + 0.72409469413165, + 2.23827918609380, + -4.00258494846342, + -21.00357681484648, + 26.8556413626615, + 206.5513384066188, + -355.60235612207947, +]; +pub const B1: [f64; 7] = [ + 0.2384607176760574, + 6.430183782977854, + -16.03207359098296, + 6.551695787529511, + 31.444257990183306, + -500.9301850495875, + 762.2725790356507, +]; +pub const B2: [f64; 7] = [ + -0.3521344090059574, + -4.861304748454132, + 49.256434792398586, + -153.85773541338776, + 82.30476426689317, + 1467.9798510614366, + -2009.0462529305892, +]; + +/// Model constants of the dispersion contribution: `[a1, a2, b1, b2]`. +pub type DispersionConstants = [[f64; 7]; 4]; + +/// The dispersion contribution of FC-SAFT. +/// +/// The contribution is evaluated for "segments", which are either the individual +/// segments of the heterosegmented model, or the components of the homosegmented +/// model (with the reduced surface $m$ and volume $m^*$ of the whole molecule). +pub(crate) struct Dispersion { + component_index: DVector, + sigma3_ij: DMatrix, + epsilon_k_ij: DMatrix, + a1: [f64; 7], + a2: [f64; 7], + b1: [f64; 7], + b2: [f64; 7], +} + +impl Dispersion { + pub(crate) fn new( + component_index: &DVector, + sigma_ij: &DMatrix, + epsilon_k_ij: &DMatrix, + model_constants: Option, + ) -> Self { + let [a1, a2, b1, b2] = model_constants.unwrap_or([A1, A2, B1, B2]); + Self { + component_index: component_index.clone(), + sigma3_ij: sigma_ij.map(|s| s.powi(3)), + epsilon_k_ij: epsilon_k_ij.clone(), + a1, + a2, + b1, + b2, + } + } + + /// The Helmholtz energy density for given temperature dependent diameters, + /// surface and volume coefficients $a$ and $v$, and compressibility term $C_1$. + pub(crate) fn helmholtz_energy_density + Copy>( + &self, + state: &StateHD, + diameter: &DVector, + [a, v]: &[DVector; 2], + c1: D, + ) -> D { + // auxiliary variables + let n = diameter.len(); + let c = &self.component_index; + let rho = &state.partial_density; + let x = &state.molefracs; + + // packing fraction + let eta: D = (0..n) + .map(|i| rho[c[i]] * v[i] * diameter[i].powi(3) * FRAC_PI_6) + .sum(); + + // mean segment number + let m: D = (0..n).map(|i| x[c[i]] * a[i]).sum(); + + // mixture densities, crosswise interactions of all segments on all chains + let mut rho1mix = D::zero(); + let mut rho2mix = D::zero(); + for i in 0..n { + for j in 0..n { + let eps_ij = state.temperature.recip() * self.epsilon_k_ij[(i, j)]; + let rho1 = rho[c[i]] * rho[c[j]] * a[i] * a[j] * eps_ij * self.sigma3_ij[(i, j)]; + rho1mix += rho1; + rho2mix += rho1 * eps_ij; + } + } + + // I1 and I2 + let mut i1 = D::zero(); + let mut i2 = D::zero(); + let mut eta_i = D::one(); + for i in 0..=6 { + i1 += ((m - 1.0) / m * ((m - 2.0) / m * self.a2[i] + self.a1[i]) + A0[i]) * eta_i; + i2 += ((m - 1.0) / m * ((m - 2.0) / m * self.b2[i] + self.b1[i]) + B0[i]) * eta_i; + eta_i *= eta; + } + + // Helmholtz energy density + (-rho1mix * i1 * 2.0 - rho2mix * m * c1 * i2) * PI + } +} diff --git a/crates/feos/src/fcsaft/eos/mod.rs b/crates/feos/src/fcsaft/eos/mod.rs new file mode 100644 index 000000000..a9cc7b6fa --- /dev/null +++ b/crates/feos/src/fcsaft/eos/mod.rs @@ -0,0 +1,205 @@ +use super::FcSaftOptions; +use super::parameters::FcSaftPars; +use super::record::FcSaftParameters; +use super::reference::ReferenceFluid; +use crate::association::Association; +use crate::hard_sphere::HardSphereProperties; +use feos_core::{Molarweight, ResidualDyn, StateHD, Subset}; +use nalgebra::DVector; +use num_dual::DualNum; +use quantity::MolarWeight; +use std::f64::consts::FRAC_PI_6; + +pub(crate) mod dispersion; +use dispersion::Dispersion; +pub use dispersion::DispersionConstants; + +/// Heterosegmented FC-SAFT equation of state. +pub struct FcSaft { + pub parameters: FcSaftParameters, + pub params: FcSaftPars, + options: FcSaftOptions, + dispersion: Dispersion, + association: Option, + model_constants: Option, +} + +impl FcSaft { + pub fn new(parameters: FcSaftParameters) -> Self { + Self::with_options(parameters, FcSaftOptions::default(), None) + } + + pub fn with_options( + parameters: FcSaftParameters, + options: FcSaftOptions, + model_constants: Option, + ) -> Self { + let params = FcSaftPars::new(¶meters); + let dispersion = Dispersion::new( + ¶ms.component_index, + ¶ms.sigma_ij, + ¶ms.epsilon_k_ij, + model_constants, + ); + let association = (!parameters.association.is_empty()) + .then(|| Association::new(options.max_iter_cross_assoc, options.tol_cross_assoc)); + Self { + parameters, + params, + options, + dispersion, + association, + model_constants, + } + } +} + +impl ResidualDyn for FcSaft { + fn components(&self) -> usize { + self.parameters.molar_weight.len() + } + + fn compute_max_density + Copy>(&self, molefracs: &DVector) -> D { + let p = &self.params; + let [_, v] = p.fused_sphere_coefficients(&p.sigma); + let segment_volume: D = (0..p.sigma.len()) + .map(|i| molefracs[p.component_index[i]] * p.sigma[i].powi(3) * v[i]) + .sum(); + (segment_volume * FRAC_PI_6).recip() * self.options.max_eta + } + + fn for_each_contribution + Copy>( + &self, + state: &StateHD, + mut f: impl FnMut(&'static str, D), + ) { + let p = &self.params; + let d = p.hs_diameter(state.temperature); + let av = p.fused_sphere_coefficients(&d); + + let density = state.partial_density.sum(); + let reference = ReferenceFluid::new(&p.component_index, &p.bonds, &d, &av); + let ([hs, chain], c1) = reference.helmholtz_energy_density(density, &state.molefracs); + f("Hard Sphere", hs); + f("Fused-sphere chain", chain); + f( + "Dispersion", + self.dispersion.helmholtz_energy_density(state, &d, &av, c1), + ); + if let Some(association) = self.association.as_ref() { + f( + "Association", + association.helmholtz_energy_density( + &self.params, + &self.parameters.association, + state, + &d, + ), + ) + } + } +} + +impl Subset for FcSaft { + fn subset(&self, component_list: &[usize]) -> Self { + Self::with_options( + self.parameters.subset(component_list), + self.options, + self.model_constants, + ) + } +} + +impl Molarweight for FcSaft { + fn molar_weight(&self) -> MolarWeight> { + self.parameters.molar_weight.clone() + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::fcsaft::new_pure_homosegmented; + use crate::fcsaft::{FcSaftBondRecord, FcSaftRecord}; + use approx::assert_relative_eq; + use feos_core::parameter::{BinarySegmentRecord, ChemicalRecord, Identifier, SegmentRecord}; + use feos_core::{FeosResult, ReferenceSystem, Residual, State}; + use nalgebra::dvector; + use num_dual::Dual64; + use quantity::{KELVIN, METER, MOL}; + + #[test] + fn test_dispersion() -> FeosResult<()> { + let params = new_pure_homosegmented(Identifier::default(), 2, 3.0, 150.0, 1.5, 20.0, None)?; + let mut model_constants = [[0.0; 7]; 4]; + model_constants[0][0] = 1e-8; + let eos = FcSaft::with_options(params, Default::default(), Some(model_constants)); + let state = StateHD::new(100.0f64, 1000.0, &dvector![1.0]); + let d = eos.params.hs_diameter(state.temperature); + let av = eos.params.fused_sphere_coefficients(&d); + let reference = + ReferenceFluid::new(&eos.params.component_index, &eos.params.bonds, &d, &av); + let (_, c1) = reference.helmholtz_energy_density(1e-3, &DVector::from_element(1, 1.0)); + let a = eos.dispersion.helmholtz_energy_density(&state, &d, &av, c1); + assert!(a.is_finite()); + let state = State::new_nvt(&&eos, 100.0 * KELVIN, 10.0 * METER.powi::<3>(), MOL)?; + assert_eq!(state.total_molar_weight(), 20.0 * quantity::GRAM / MOL); + Ok(()) + } + + /// Monomer (component 1) and a fused trimer (component 2). + fn monomer_trimer() -> FeosResult { + let segment_records = [ + SegmentRecord::new("A".into(), 16.0, FcSaftRecord::new(3.7, 150.0, None)), + SegmentRecord::new("B".into(), 15.0, FcSaftRecord::new(3.5, 180.0, None)), + ]; + let chemical_records = vec![ + ChemicalRecord::new(Default::default(), vec!["A".into()], None), + ChemicalRecord::new(Default::default(), vec!["B".into(); 3], None), + ]; + let bond_records = [BinarySegmentRecord::new( + "B".into(), + "B".into(), + Some(FcSaftBondRecord::new(2.5)), + )]; + let params = FcSaftParameters::from_segments_with_bonds( + chemical_records, + &segment_records, + None, + &bond_records, + )?; + Ok(FcSaft::new(params)) + } + + #[test] + fn test_infinite_dilution() -> FeosResult<()> { + // the derivative of the Helmholtz energy w.r.t. the density of the trimer + // has to be continuous for a vanishing amount of trimer + let eos = monomer_trimer()?; + let mu = |rho2: f64| { + let state = StateHD::new_density( + Dual64::from(300.0), + dvector![Dual64::from(0.01), Dual64::from(rho2).derivative()], + ); + (&eos) + .reduced_helmholtz_energy_density_contributions(&state) + .into_iter() + .map(|(name, a)| (name, a.eps)) + .collect::>() + }; + for ((name, mu_0), (_, mu_dilute)) in mu(0.0).into_iter().zip(mu(1e-12)) { + println!("{name:20} {mu_0:.12} {mu_dilute:.12}"); + assert_relative_eq!(mu_0, mu_dilute, max_relative = 1e-8); + } + Ok(()) + } + + #[test] + fn test_second_virial_coefficient() -> FeosResult<()> { + // C1 has to be well-defined at zero density + let eos = monomer_trimer()?; + let b = (&eos).second_virial_coefficient(300.0 * KELVIN, dvector![0.4, 0.6])?; + assert!(b.into_reduced().is_finite()); + Ok(()) + } +} diff --git a/crates/feos/src/fcsaft/homosegmented/fcsaft_binary.rs b/crates/feos/src/fcsaft/homosegmented/fcsaft_binary.rs new file mode 100644 index 000000000..a993613f3 --- /dev/null +++ b/crates/feos/src/fcsaft/homosegmented/fcsaft_binary.rs @@ -0,0 +1,706 @@ +use super::fcsaft_pure::reduced_volume; +use super::polar::{AD, BD, CD}; +use crate::fcsaft::eos::dispersion::{A0, A1, A2, B0, B1, B2}; +use crate::hard_sphere::HardSphere; +use feos_core::{Residual, StateHD, ad::ParametersAD}; +use nalgebra::{SVector, U2}; +use num_dual::{Dual2, DualNum, DualVec, jacobian, second_derivative}; +use std::f64::consts::{FRAC_PI_6, PI}; + +const PI_SQ_43: f64 = 4.0 / 3.0 * PI * PI; + +const MAX_ETA: f64 = 0.5; + +/// Optimized implementation of FC-SAFT for a binary mixture of (homosegmented) components. +#[derive(Clone, Copy)] +pub struct FcSaftBinary(pub ([[D; N]; 2], D)); + +impl FcSaftBinary { + pub fn new(parameters: [[D; N]; 2], kij: D) -> Self { + Self((parameters, kij)) + } +} + +impl ParametersAD for FcSaftBinary { + fn build + Copy>( + mut f: impl FnMut(&'static str, bool) -> D, + ) -> FcSaftBinary { + FcSaftBinary::new( + [ + [ + f("s1", false), + f("l1", true), + f("sigma1", true), + f("epsilon_k1", true), + f("mu1", true), + ], + [ + f("s2", false), + f("l2", true), + f("sigma2", true), + f("epsilon_k2", true), + f("mu2", true), + ], + ], + f("k_ij", true), + ) + } +} + +impl ParametersAD for FcSaftBinary { + fn build + Copy>( + mut f: impl FnMut(&'static str, bool) -> D, + ) -> FcSaftBinary { + FcSaftBinary::new( + [ + [ + f("s1", false), + f("l1", true), + f("sigma1", true), + f("epsilon_k1", true), + f("mu1", true), + f("kappa_ab1", true), + f("epsilon_k_ab1", true), + f("na1", false), + f("nb1", false), + ], + [ + f("s2", false), + f("l2", true), + f("sigma2", true), + f("epsilon_k2", true), + f("mu2", true), + f("kappa_ab2", true), + f("epsilon_k_ab2", true), + f("na2", false), + f("nb2", false), + ], + ], + f("k_ij", true), + ) + } +} + +/// Hard spheres and fused chains, and the compressibility term C1 from the +/// second derivative of the reference fluid w.r.t. the density. +fn reference + Copy>( + [s1, s2]: [D; 2], + [l1, l2]: [D; 2], + [m1, m2]: [D; 2], + [m_star1, m_star2]: [D; 2], + [x1, x2]: [D; 2], + [d1, d2]: [D; 2], + density: D, +) -> (D, [D; 7], D, D, D) { + // Packing fractions (divided by the density) + let zeta = [ + s1 * x1 + s2 * x2, + m1 * x1 * d1 + m2 * x2 * d2, + m1 * x1 * d1.powi(2) + m2 * x2 * d2.powi(2), + m_star1 * x1 * d1.powi(3) + m_star2 * x2 * d2.powi(3), + ] + .map(|z| z * FRAC_PI_6); + let zeta_23 = Dual2::from_re(zeta[2] / zeta[3]); + + let (reference, _, d2_reference) = second_derivative( + |rho: Dual2| { + let zeta = zeta.map(|z| rho.scale(&z)); + let hs = HardSphere::bmcsl_helmholtz_energy_density(zeta, zeta_23); + let frac_1mz3 = -(zeta[3] - 1.0).recip(); + let [ln_y1, ln_y2] = [l1, l2].map(|l| { + let z2l = zeta[2].scale(&l); + (z2l * frac_1mz3 * frac_1mz3 * (z2l * frac_1mz3 * 0.5 + 1.5) + frac_1mz3).ln() + }); + let hc = -rho * (ln_y1.scale(&(x1 * (s1 - 1.0))) + ln_y2.scale(&(x2 * (s2 - 1.0)))); + hs + hc + }, + density, + ); + let c1 = (d2_reference * density + 1.0).recip(); + + let zeta2 = zeta[2] * density; + let eta = zeta[3] * density; + let eta2 = eta * eta; + let eta3 = eta2 * eta; + let etas = [ + D::one(), + eta, + eta2, + eta3, + eta2 * eta2, + eta2 * eta3, + eta3 * eta3, + ]; + let frac_1mz3 = (-eta + 1.0).recip(); + + (reference, etas, zeta2, frac_1mz3, c1) +} + +#[expect(clippy::too_many_arguments)] +fn dispersion + Copy>( + [m1, m2]: [D; 2], + [sigma1, sigma2]: [D; 2], + [epsilon_k1, epsilon_k2]: [D; 2], + kij: D, + [x1, x2]: [D; 2], + t_inv: D, + [rho1, rho2]: [D; 2], + etas: [D; 7], + c1: D, +) -> (D, [D; 3], [D; 3]) { + // binary interactions + let m = x1 * m1 + x2 * m2; + let epsilon_k11 = epsilon_k1 * t_inv; + let epsilon_k12 = (epsilon_k1 * epsilon_k2).sqrt() * t_inv; + let epsilon_k22 = epsilon_k2 * t_inv; + let sigma11_3 = sigma1.powi(3); + let sigma12_3 = ((sigma1 + sigma2) * 0.5).powi(3); + let sigma22_3 = sigma2.powi(3); + let d11 = rho1 * rho1 * m1 * m1 * epsilon_k11 * sigma11_3; + let d12 = rho1 * rho2 * m1 * m2 * epsilon_k12 * sigma12_3 * (-kij + 1.0); + let d22 = rho2 * rho2 * m2 * m2 * epsilon_k22 * sigma22_3; + let rho1mix = d11 + d12 * 2.0 + d22; + let rho2mix = d11 * epsilon_k11 + d12 * epsilon_k12 * (-kij + 1.0) * 2.0 + d22 * epsilon_k22; + + // I1 and I2 + let mm1 = (m - 1.0) / m; + let mm2 = (m - 2.0) / m; + let mut i1 = D::zero(); + let mut i2 = D::zero(); + for i in 0..7 { + i1 += (mm1 * (mm2 * A2[i] + A1[i]) + A0[i]) * etas[i]; + i2 += (mm1 * (mm2 * B2[i] + B1[i]) + B0[i]) * etas[i]; + } + + // dispersion + let disp = (-rho1mix * i1 * 2.0 - rho2mix * m * c1 * i2) * PI; + + ( + disp, + [sigma11_3, sigma12_3, sigma22_3], + [epsilon_k11, epsilon_k12, epsilon_k22], + ) +} + +#[expect(clippy::too_many_arguments)] +fn dipoles + Copy>( + [m1, m2]: [D; 2], + [m_star1, m_star2]: [D; 2], + [sigma1, sigma2]: [D; 2], + [sigma11_3, sigma12_3, sigma22_3]: [D; 3], + [epsilon_k11, epsilon_k12, epsilon_k22]: [D; 3], + [mu1, mu2]: [D; 2], + temperature: D, + [rho1, rho2]: [D; 2], + etas: [D; 7], +) -> D { + // Note: the reduced dipole moment is normalized with the reduced volume m*. + // Using the reduced surface m (which replaces the segment number of PC-SAFT + // everywhere else) would be an equally valid generalization to fused chains. + let mu_term1 = mu1 * mu1 / (m_star1 * temperature * 1.380649e-4) * rho1; + let mu_term2 = mu2 * mu2 / (m_star2 * temperature * 1.380649e-4) * rho2; + let sigma111 = sigma11_3; + let sigma112 = sigma1 * ((sigma1 + sigma2) * 0.5).powi(2); + let sigma122 = sigma2 * ((sigma1 + sigma2) * 0.5).powi(2); + let sigma222 = sigma22_3; + + let m11_dipole = if m1.re() > 2.0 { D::from(2.0) } else { m1 }; + let m22_dipole = if m2.re() > 2.0 { D::from(2.0) } else { m2 }; + let m12_dipole = (m11_dipole * m22_dipole).sqrt(); + let [j2_11, j2_12, j2_22] = [ + (m11_dipole, epsilon_k11), + (m12_dipole, epsilon_k12), + (m22_dipole, epsilon_k22), + ] + .map(|(m, e)| { + let m1 = (m - 1.0) / m; + let m2 = m1 * (m - 2.0) / m; + let mut j2 = D::zero(); + for i in 0..5 { + let a = m2 * AD[i][2] + m1 * AD[i][1] + AD[i][0]; + let b = m2 * BD[i][2] + m1 * BD[i][1] + BD[i][0]; + j2 += (a + b * e) * etas[i]; + } + j2 + }); + let m112_dipole = (m11_dipole * m11_dipole * m22_dipole).cbrt(); + let m122_dipole = (m11_dipole * m22_dipole * m22_dipole).cbrt(); + let [j3_111, j3_112, j3_122, j3_222] = + [m11_dipole, m112_dipole, m122_dipole, m22_dipole].map(|m| { + let m1 = (m - 1.0) / m; + let m2 = m1 * (m - 2.0) / m; + let mut j3 = D::zero(); + for i in 0..4 { + j3 += (m2 * CD[i][2] + m1 * CD[i][1] + CD[i][0]) * etas[i]; + } + j3 + }); + + let phi2 = (mu_term1 * mu_term1 / sigma11_3 * j2_11 + + mu_term1 * mu_term2 / sigma12_3 * j2_12 * 2.0 + + mu_term2 * mu_term2 / sigma22_3 * j2_22) + * (-PI); + let phi3 = (mu_term1.powi(3) / sigma111 * j3_111 + + mu_term1.powi(2) * mu_term2 / sigma112 * j3_112 * 3.0 + + mu_term1 * mu_term2.powi(2) / sigma122 * j3_122 * 3.0 + + mu_term2.powi(3) / sigma222 * j3_222) + * (-PI_SQ_43); + + let mut polar = phi2 * phi2 / (phi2 - phi3); + if polar.re().is_nan() { + polar = phi2 + } + + polar +} + +fn association + Copy>( + assoc_params: [[D; 4]; 2], + [sigma11_3, _, sigma22_3]: [D; 3], + t_inv: D, + [rho1, rho2]: [D; 2], + [d1, d2]: [D; 2], + zeta2: D, + frac_1mz3: D, +) -> D { + let [ + [kappa_ab1, epsilon_k_ab1, na1, nb1], + [kappa_ab2, epsilon_k_ab2, na2, nb2], + ] = assoc_params; + + let d11 = d1 * 0.5; + let d12 = d1 * d2 / (d1 + d2); + let d22 = d2 * 0.5; + let [k11, k12, k22] = [d11, d12, d22].map(|d| d * zeta2 * frac_1mz3); + let s11 = sigma11_3 * kappa_ab1; + let mut s12 = (sigma11_3 * sigma22_3 * kappa_ab1 * kappa_ab2).sqrt(); + if s12.re() == 0.0 { + s12 = D::zero(); + } + let s22 = sigma22_3 * kappa_ab2; + let e11 = (epsilon_k_ab1 * t_inv).exp() - 1.0; + let e12 = ((epsilon_k_ab1 + epsilon_k_ab2) * 0.5 * t_inv).exp() - 1.0; + let e22 = (epsilon_k_ab2 * t_inv).exp() - 1.0; + let d11 = frac_1mz3 * (k11 * (k11 * 2.0 + 3.0) + 1.0) * s11 * e11; + let d12 = frac_1mz3 * (k12 * (k12 * 2.0 + 3.0) + 1.0) * s12 * e12; + let d22 = frac_1mz3 * (k22 * (k22 * 2.0 + 3.0) + 1.0) * s22 * e22; + let rhoa1 = rho1 * na1; + let rhob1 = rho1 * nb1; + let rhoa2 = rho2 * na2; + let rhob2 = rho2 * nb2; + + let [mut xa1, mut xa2] = [D::from(0.2); 2]; + for _ in 0..50 { + let (g, j) = jacobian( + |x| { + let [xa1, xa2] = x.data.0[0]; + let xb1_i = + xa1 * DualVec::from_re(rhoa1 * d11) + xa2 * DualVec::from_re(rhoa2 * d12) + 1.0; + let xb2_i = + xa1 * DualVec::from_re(rhoa1 * d12) + xa2 * DualVec::from_re(rhoa2 * d22) + 1.0; + + let f1 = xa1 - 1.0 + + xa1 / xb1_i * DualVec::from_re(rhob1 * d11) + + xa1 / xb2_i * DualVec::from_re(rhob2 * d12); + let f2 = xa2 - 1.0 + + xa2 / xb1_i * DualVec::from_re(rhob1 * d12) + + xa2 / xb2_i * DualVec::from_re(rhob2 * d22); + + SVector::from([f1, f2]) + }, + &SVector::from([xa1, xa2]), + ); + + let [g1, g2] = g.data.0[0]; + let [[j11, j12], [j21, j22]] = j.data.0; + let det = j11 * j22 - j12 * j21; + + let delta_xa1 = (j22 * g1 - j12 * g2) / det; + let delta_xa2 = (-j21 * g1 + j11 * g2) / det; + if delta_xa1.re() < xa1.re() * 0.8 { + xa1 -= delta_xa1; + } else { + xa1 *= 0.2; + } + if delta_xa2.re() < xa2.re() * 0.8 { + xa2 -= delta_xa2; + } else { + xa2 *= 0.2; + } + + if g1.re().abs() < 1e-15 && g2.re().abs() < 1e-15 { + break; + } + } + + let xb1 = (xa1 * rhoa1 * d11 + xa2 * rhoa2 * d12 + 1.0).recip(); + let xb2 = (xa1 * rhoa1 * d12 + xa2 * rhoa2 * d22 + 1.0).recip(); + let f = |x: D| x.ln() - x * 0.5 + 0.5; + + rhoa1 * f(xa1) + rhoa2 * f(xa2) + rhob1 * f(xb1) + rhob2 * f(xb2) +} + +#[expect(clippy::too_many_arguments)] +fn helmholtz_energy_density + Copy>( + temperature: D, + rho: [D; 2], + s: [D; 2], + l: [D; 2], + sigma: [D; 2], + epsilon_k: [D; 2], + mu: [D; 2], + kij: D, + assoc_params: Option<[[D; 4]; 2]>, +) -> D { + // temperature dependent segment diameter + let t_inv = temperature.recip(); + let [sigma1, sigma2] = sigma; + let [epsilon_k1, epsilon_k2] = epsilon_k; + let d1 = sigma1 * (-(epsilon_k1 * -3. * t_inv).exp() * 0.12 + 1.0); + let d2 = sigma2 * (-(epsilon_k2 * -3. * t_inv).exp() * 0.12 + 1.0); + let d = [d1, d2]; + + // reduced surface and volume of the fused chains + let m = [0, 1].map(|i| l[i] / d[i] * (s[i] - 1.0) + 1.0); + let m_star = [0, 1].map(|i| reduced_volume(s[i], l[i], d[i])); + + // density and composition + let [rho1, rho2] = rho; + let density = rho1 + rho2; + let x = [rho1 / density, rho2 / density]; + + // reference fluid (hard spheres and fused chains) + let (reference, etas, zeta2, frac_1mz3, c1) = reference(s, l, m, m_star, x, d, density); + + // dispersion + let (disp, sigma_3, epsilon_k_mix) = + dispersion(m, sigma, epsilon_k, kij, x, t_inv, rho, etas, c1); + + // dipoles + let m_star_sigma = [0, 1].map(|i| reduced_volume(s[i], l[i], sigma[i])); + let polar = dipoles( + m, + m_star_sigma, + sigma, + sigma_3, + epsilon_k_mix, + mu, + temperature, + rho, + etas, + ); + + // association + if let Some(p) = assoc_params { + let assoc = association(p, sigma_3, t_inv, rho, d, zeta2, frac_1mz3); + reference + disp + polar + assoc + } else { + reference + disp + polar + } +} + +fn max_density + Copy, const N: usize>( + [p1, p2]: &[[D; N]; 2], + molefracs: &SVector, +) -> D { + let [x1, x2] = molefracs.data.0[0]; + let [v1, v2] = [p1, p2].map(|p| reduced_volume(p[0], p[1], p[2]) * p[2].powi(3)); + ((v1 * x1 + v2 * x2) * FRAC_PI_6).recip() * MAX_ETA +} + +impl + Copy> Residual for FcSaftBinary { + fn components(&self) -> usize { + 2 + } + + type Real = FcSaftBinary; + type Lifted + Copy> = FcSaftBinary; + fn re(&self) -> Self::Real { + FcSaftBinary(( + self.0.0.each_ref().map(|x| x.each_ref().map(D::re)), + self.0.1.re(), + )) + } + fn lift + Copy>(&self) -> Self::Lifted { + FcSaftBinary(( + self.0 + .0 + .each_ref() + .map(|x| x.each_ref().map(D2::from_inner)), + D2::from_inner(&self.0.1), + )) + } + + fn compute_max_density(&self, molefracs: &SVector) -> D { + max_density(&self.0.0, molefracs) + } + + fn for_each_contribution(&self, state: &StateHD, mut f: impl FnMut(&'static str, D)) { + f( + "FC-SAFT (binary, non-assoc)", + self.reduced_residual_helmholtz_energy_density(state), + ) + } + + fn reduced_residual_helmholtz_energy_density(&self, state: &StateHD) -> D { + let ([p1, p2], kij) = self.0; + let [s1, l1, sigma1, epsilon_k1, mu1] = p1; + let [s2, l2, sigma2, epsilon_k2, mu2] = p2; + let s = [s1, s2]; + let l = [l1, l2]; + let sigma = [sigma1, sigma2]; + let epsilon_k = [epsilon_k1, epsilon_k2]; + let mu = [mu1, mu2]; + + let [rho1, rho2] = state.partial_density.data.0[0]; + let rho = [rho1, rho2]; + + helmholtz_energy_density( + state.temperature, + rho, + s, + l, + sigma, + epsilon_k, + mu, + kij, + None, + ) + } +} + +impl + Copy> Residual for FcSaftBinary { + fn components(&self) -> usize { + 2 + } + + type Real = FcSaftBinary; + type Lifted + Copy> = FcSaftBinary; + fn re(&self) -> Self::Real { + FcSaftBinary(( + self.0.0.each_ref().map(|x| x.each_ref().map(D::re)), + self.0.1.re(), + )) + } + fn lift + Copy>(&self) -> Self::Lifted { + FcSaftBinary(( + self.0 + .0 + .each_ref() + .map(|x| x.each_ref().map(D2::from_inner)), + D2::from_inner(&self.0.1), + )) + } + + fn compute_max_density(&self, molefracs: &SVector) -> D { + max_density(&self.0.0, molefracs) + } + + fn for_each_contribution(&self, state: &StateHD, mut f: impl FnMut(&'static str, D)) { + f( + "FC-SAFT (binary)", + self.reduced_residual_helmholtz_energy_density(state), + ) + } + + fn reduced_residual_helmholtz_energy_density(&self, state: &StateHD) -> D { + let ([p1, p2], kij) = self.0; + let [ + s1, + l1, + sigma1, + epsilon_k1, + mu1, + kappa_ab1, + epsilon_k_ab1, + na1, + nb1, + ] = p1; + let [ + s2, + l2, + sigma2, + epsilon_k2, + mu2, + kappa_ab2, + epsilon_k_ab2, + na2, + nb2, + ] = p2; + let s = [s1, s2]; + let l = [l1, l2]; + let sigma = [sigma1, sigma2]; + let epsilon_k = [epsilon_k1, epsilon_k2]; + let mu = [mu1, mu2]; + let assoc_params = Some([ + [kappa_ab1, epsilon_k_ab1, na1, nb1], + [kappa_ab2, epsilon_k_ab2, na2, nb2], + ]); + + let [rho1, rho2] = state.partial_density.data.0[0]; + let rho = [rho1, rho2]; + + helmholtz_energy_density( + state.temperature, + rho, + s, + l, + sigma, + epsilon_k, + mu, + kij, + assoc_params, + ) + } +} + +#[cfg(test)] +pub mod test { + use super::FcSaftBinary; + use crate::fcsaft::FcSaftAssociationRecord; + use crate::fcsaft::FcSaftBinaryRecord; + use crate::fcsaft::homosegmented::{FcSaftHomo, FcSaftHomoParameters, FcSaftHomoRecord}; + use approx::assert_relative_eq; + use feos_core::ad::{BubblePointPressure, ParametersAD, PropertyAD}; + use feos_core::parameter::{AssociationRecord, PureRecord}; + use feos_core::{Contributions::Total, FeosResult, PhaseEquilibrium, State}; + use nalgebra::{U1, U13, dvector, vector}; + use quantity::{KELVIN, KILO, METER, MOL, PASCAL}; + + pub fn fcsaft_binary() -> FeosResult<(FcSaftBinary, FcSaftHomo)> { + let params = [ + [3.0, 2.5, 3.4, 180.0, 2.2, 0.03, 2500., 2.0, 1.0], + [2.0, 3.0, 3.6, 250.0, 1.2, 0.015, 1500., 1.0, 2.0], + ]; + let kij = 0.15; + let records = params.map(|p| { + PureRecord::with_association( + Default::default(), + 0.0, + FcSaftHomoRecord::new(p[0] as usize, p[1], p[2], p[3], p[4]), + vec![AssociationRecord::new( + Some(FcSaftAssociationRecord::new(p[5], p[6])), + p[7], + p[8], + 0.0, + )], + ) + }); + let params_feos = + FcSaftHomoParameters::new_binary(records, Some(FcSaftBinaryRecord::new(kij)), vec![])?; + let eos = FcSaftHomo::new(params_feos); + Ok((FcSaftBinary::new(params, kij), eos)) + } + + #[test] + fn test_fcsaft_binary() -> FeosResult<()> { + let (fcsaft, eos) = fcsaft_binary()?; + + let temperature = 300.0 * KELVIN; + let volume = 2.3 * METER * METER * METER; + let moles = dvector![1.3, 2.5] * KILO * MOL; + + let state = State::new_nvt(&&eos, temperature, volume, &moles)?; + let a_feos = state.residual_molar_helmholtz_energy(); + let mu_feos = state.residual_chemical_potential(); + let p_feos = state.pressure(Total); + let s_feos = state.residual_molar_entropy(); + let h_feos = state.residual_molar_enthalpy(); + + let moles = vector![1.3, 2.5] * KILO * MOL; + let state = State::new_nvt(&fcsaft, temperature, volume, moles)?; + let a_ad = state.residual_molar_helmholtz_energy(); + let mu_ad = state.residual_chemical_potential(); + let p_ad = state.pressure(Total); + let s_ad = state.residual_molar_entropy(); + let h_ad = state.residual_molar_enthalpy(); + + println!("\nMolar Helmholtz energy:\n{a_feos}"); + println!("{a_ad}"); + assert_relative_eq!(a_feos, a_ad, max_relative = 1e-14); + + println!("\nChemical potential:\n{}", mu_feos.get(0)); + println!("{}", mu_ad.get(0)); + assert_relative_eq!(mu_feos.get(0), mu_ad.get(0), max_relative = 1e-14); + + println!("\nPressure:\n{p_feos}"); + println!("{p_ad}"); + assert_relative_eq!(p_feos, p_ad, max_relative = 1e-14); + + println!("\nMolar entropy:\n{s_feos}"); + println!("{s_ad}"); + assert_relative_eq!(s_feos, s_ad, max_relative = 1e-14); + + println!("\nMolar enthalpy:\n{h_feos}"); + println!("{h_ad}"); + assert_relative_eq!(h_feos, h_ad, max_relative = 1e-14); + + Ok(()) + } + + #[test] + fn test_bubble_point_pressure_derivatives() -> FeosResult<()> { + let fcsaft_params = [ + "l1", + "sigma1", + "epsilon_k1", + "mu1", + "kappa_ab1", + "epsilon_k_ab1", + "l2", + "sigma2", + "epsilon_k2", + "mu2", + "kappa_ab2", + "epsilon_k_ab2", + "k_ij", + ]; + let indices = [1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 15, 18]; + let (fcsaft, _) = fcsaft_binary()?; + let ([p1, p2], kij) = fcsaft.0; + let mut flat_params = p1.to_vec(); + flat_params.extend_from_slice(&p2); + flat_params.push(kij); + + let temperature = 450.0 * KELVIN; + let x = 0.4; + let fcsaft_ad = FcSaftBinary::::seed_derivatives(&flat_params, fcsaft_params); + let p = BubblePointPressure(temperature, x, None).evaluate(&fcsaft_ad)?; + let p = p.convert_into(PASCAL); + let (p, grad) = (p.re, p.eps.unwrap_generic(U13, U1)); + + println!("{p:.5}"); + println!("{grad:.5?}"); + + for ((i, par), j) in fcsaft_params.into_iter().enumerate().zip(indices) { + let h = flat_params[j] * 1e-6; + let p_h = |h: f64| { + let mut params = flat_params.clone(); + params[j] += h; + let eos: FcSaftBinary = FcSaftBinary::new( + [0, 9].map(|k| std::array::from_fn(|l| params[k + l])), + params[18], + ); + PhaseEquilibrium::bubble_point( + &eos, + temperature, + vector![x, 1.0 - x], + None, + None, + Default::default(), + ) + .map(|vle| vle.vapor().pressure(Total).convert_into(PASCAL)) + }; + let dp_h = (p_h(h)? - p_h(-h)?) / (2.0 * h); + let dp = grad[i]; + println!( + "{par:14}: {:11.5} {:11.5} {:.3e}", + dp_h, + dp, + ((dp_h - dp) / dp).abs() + ); + assert_relative_eq!(dp, dp_h, max_relative = 1e-6); + } + Ok(()) + } +} diff --git a/crates/feos/src/fcsaft/homosegmented/fcsaft_pure.rs b/crates/feos/src/fcsaft/homosegmented/fcsaft_pure.rs new file mode 100644 index 000000000..3152e676b --- /dev/null +++ b/crates/feos/src/fcsaft/homosegmented/fcsaft_pure.rs @@ -0,0 +1,361 @@ +use super::polar::{AD, BD, CD}; +use crate::fcsaft::eos::dispersion::{A0, A1, A2, B0, B1, B2}; +use crate::hard_sphere::HardSphere; +use feos_core::{Residual, StateHD, ad::ParametersAD}; +use nalgebra::{SVector, U1}; +use num_dual::{Dual2, DualNum, second_derivative}; +use std::f64::consts::{FRAC_PI_6, PI}; + +const PI_SQ_43: f64 = 4.0 / 3.0 * PI * PI; + +const MAX_ETA: f64 = 0.5; + +/// Optimized implementation of FC-SAFT for a single (homosegmented) component. +#[derive(Clone, Copy)] +pub struct FcSaftPure + Copy, const N: usize>(pub [D; N]); + +/// Reduced volume $m^*$ of a chain of `s` fused spheres with bond length `l` and diameter `d`. +pub(super) fn reduced_volume + Copy>(s: D, l: D, d: D) -> D { + let ld = l / d; + ld * (-ld * ld + 3.0) * (s - 1.0) * 0.5 + 1.0 +} + +fn helmholtz_energy_density_non_assoc + Copy>( + s: D, + l: D, + sigma: D, + epsilon_k: D, + mu: D, + temperature: D, + density: D, +) -> (D, [D; 3]) { + // temperature dependent segment diameter + let diameter = sigma * (-(epsilon_k * (-3.) / temperature).exp() * 0.12 + 1.0); + + // reduced surface and volume of the fused chain + let m = l / diameter * (s - 1.0) + 1.0; + let m_star = reduced_volume(s, l, diameter); + + let eta = m_star * density * diameter.powi(3) * FRAC_PI_6; + let eta2 = eta * eta; + let eta3 = eta2 * eta; + let eta_m1 = (-eta + 1.0).recip(); + let etas = [ + D::one(), + eta, + eta2, + eta3, + eta2 * eta2, + eta2 * eta3, + eta3 * eta3, + ]; + + // reference fluid (hard spheres and fused chain) and its second derivative + // w.r.t. the density, which yields the compressibility term C1 + let (reference, _, d2_reference) = second_derivative( + |rho: Dual2| { + let zeta = [ + s, + m * diameter, + m * diameter.powi(2), + m_star * diameter.powi(3), + ] + .map(|c| rho.scale(&(c * FRAC_PI_6))); + let zeta_23 = Dual2::from_re(m / (m_star * diameter)); + let hs = HardSphere::bmcsl_helmholtz_energy_density(zeta, zeta_23); + let frac_1mz3 = -(zeta[3] - 1.0).recip(); + let z2l = zeta[2].scale(&l); + let y = z2l * frac_1mz3 * frac_1mz3 * (z2l * frac_1mz3 * 0.5 + 1.5) + frac_1mz3; + let hc = -rho * y.ln().scale(&(s - 1.0)); + hs + hc + }, + density, + ); + let c1 = (d2_reference * density + 1.0).recip(); + + // dispersion + let e = epsilon_k / temperature; + let s3 = sigma.powi(3); + let mut i1 = D::zero(); + let mut i2 = D::zero(); + let m1 = (m - 1.0) / m; + let m2 = (m - 2.0) / m; + for i in 0..7 { + i1 += (m1 * (m2 * A2[i] + A1[i]) + A0[i]) * etas[i]; + i2 += (m1 * (m2 * B2[i] + B1[i]) + B0[i]) * etas[i]; + } + let i = i1 * 2.0 + c1 * i2 * m * e; + let disp = -density * density * m.powi(2) * e * s3 * i * PI; + + // dipoles + // Note: the reduced dipole moment is normalized with the reduced volume m*. + // Using the reduced surface m (which replaces the segment number of PC-SAFT + // everywhere else) would be an equally valid generalization to fused chains. + let mu2 = mu.powi(2) / (reduced_volume(s, l, sigma) * temperature * 1.380649e-4); + let m_dipole = if m.re() > 2.0 { D::from(2.0) } else { m }; + let m1 = (m_dipole - 1.0) / m_dipole; + let m2 = m1 * (m_dipole - 2.0) / m_dipole; + let mut j1 = D::zero(); + let mut j2 = D::zero(); + for i in 0..5 { + let a = m2 * AD[i][2] + m1 * AD[i][1] + AD[i][0]; + let b = m2 * BD[i][2] + m1 * BD[i][1] + BD[i][0]; + j1 += (a + b * e) * etas[i]; + if i < 4 { + j2 += (m2 * CD[i][2] + m1 * CD[i][1] + CD[i][0]) * etas[i]; + } + } + + // mu is factored out of these expressions to deal with the case where mu=0 + let phi2 = -density * density * j1 / s3 * PI; + let phi3 = -density * density * density * j2 / s3 * PI_SQ_43; + let dipole = phi2 * phi2 * mu2 * mu2 / (phi2 - phi3 * mu2); + + (reference + disp + dipole, [eta, eta_m1, m / m_star]) +} + +fn helmholtz_energy_density + Copy>( + parameters: &[D; 9], + temperature: D, + density: D, +) -> D { + let [s, l, sigma, epsilon_k, mu, kappa_ab, epsilon_k_ab, na, nb] = *parameters; + let (non_assoc, [eta, eta_m1, m_m_star]) = + helmholtz_energy_density_non_assoc(s, l, sigma, epsilon_k, mu, temperature, density); + + // association + let delta_assoc = ((epsilon_k_ab / temperature).exp() - 1.0) * sigma.powi(3) * kappa_ab; + let k = eta * eta_m1 * m_m_star; + let delta = (k * (k * 0.5 + 1.5) + 1.0) * eta_m1 * delta_assoc; + let rhoa = na * density; + let rhob = nb * density; + let aux = (rhoa - rhob) * delta + 1.0; + let sqrt = (aux * aux + rhob * delta * 4.0).sqrt(); + let (xa, xb) = if na > nb { + let xb = (sqrt + aux).recip() * 2.0; + let xa = (rhob * delta * xb + 1.0).recip(); + (xa, xb) + } else { + let xa = (sqrt - aux + 2.0).recip() * 2.0; + let xb = (rhoa * delta * xa + 1.0).recip(); + (xa, xb) + }; + let assoc = rhoa * (xa.ln() - xa * 0.5 + 0.5) + rhob * (xb.ln() - xb * 0.5 + 0.5); + + non_assoc + assoc +} + +impl + Copy> Residual for FcSaftPure { + fn components(&self) -> usize { + 1 + } + + type Real = FcSaftPure; + type Lifted + Copy> = FcSaftPure; + fn re(&self) -> Self::Real { + FcSaftPure(self.0.each_ref().map(D::re)) + } + fn lift + Copy>(&self) -> Self::Lifted { + FcSaftPure(self.0.each_ref().map(D2::from_inner)) + } + + fn compute_max_density(&self, _: &SVector) -> D { + let &[s, l, sigma, ..] = &self.0; + (reduced_volume(s, l, sigma) * sigma.powi(3) * FRAC_PI_6).recip() * MAX_ETA + } + + fn for_each_contribution(&self, state: &StateHD, mut f: impl FnMut(&'static str, D)) { + f( + "FC-SAFT (pure)", + self.reduced_residual_helmholtz_energy_density(state), + ) + } + + fn reduced_residual_helmholtz_energy_density(&self, state: &StateHD) -> D { + let density = state.partial_density.data.0[0][0]; + helmholtz_energy_density(&self.0, state.temperature, density) + } +} + +impl + Copy> Residual for FcSaftPure { + fn components(&self) -> usize { + 1 + } + + type Real = FcSaftPure; + type Lifted + Copy> = FcSaftPure; + fn re(&self) -> Self::Real { + FcSaftPure(self.0.each_ref().map(D::re)) + } + fn lift + Copy>(&self) -> Self::Lifted { + FcSaftPure(self.0.each_ref().map(D2::from_inner)) + } + + fn compute_max_density(&self, _: &SVector) -> D { + let &[s, l, sigma, ..] = &self.0; + (reduced_volume(s, l, sigma) * sigma.powi(3) * FRAC_PI_6).recip() * MAX_ETA + } + + fn for_each_contribution(&self, state: &StateHD, mut f: impl FnMut(&'static str, D)) { + f( + "FC-SAFT (pure, non-assoc)", + self.reduced_residual_helmholtz_energy_density(state), + ) + } + + fn reduced_residual_helmholtz_energy_density(&self, state: &StateHD) -> D { + let density = state.partial_density.data.0[0][0]; + let [s, l, sigma, epsilon_k, mu] = self.0; + helmholtz_energy_density_non_assoc(s, l, sigma, epsilon_k, mu, state.temperature, density).0 + } +} + +impl ParametersAD for FcSaftPure { + fn build + Copy>( + mut f: impl FnMut(&'static str, bool) -> D, + ) -> FcSaftPure { + FcSaftPure([ + f("s", false), + f("l", true), + f("sigma", true), + f("epsilon_k", true), + f("mu", true), + ]) + } +} + +impl ParametersAD for FcSaftPure { + fn build + Copy>( + mut f: impl FnMut(&'static str, bool) -> D, + ) -> FcSaftPure { + FcSaftPure([ + f("s", false), + f("l", true), + f("sigma", true), + f("epsilon_k", true), + f("mu", true), + f("kappa_ab", true), + f("epsilon_k_ab", true), + f("na", false), + f("nb", false), + ]) + } +} + +#[cfg(test)] +pub mod test { + use super::*; + use crate::fcsaft::homosegmented::{FcSaftHomo, FcSaftHomoParameters, FcSaftHomoRecord}; + use crate::fcsaft::{FcSaft, FcSaftAssociationRecord, new_pure_homosegmented}; + use approx::assert_relative_eq; + use feos_core::parameter::{AssociationRecord, Identifier, PureRecord}; + use feos_core::{Contributions::Total, FeosResult, State}; + use nalgebra::{dvector, vector}; + use quantity::{KELVIN, KILO, METER, MOL}; + + pub fn fcsaft() -> FeosResult<(FcSaftPure, FcSaftHomo)> { + let s = 3; + let l = 2.5; + let sigma = 3.4; + let epsilon_k = 180.0; + let mu = 2.2; + let kappa_ab = 0.03; + let epsilon_k_ab = 2500.; + let na = 2.0; + let nb = 1.0; + let params = FcSaftHomoParameters::new_pure(PureRecord::with_association( + Default::default(), + 0.0, + FcSaftHomoRecord::new(s, l, sigma, epsilon_k, mu), + vec![AssociationRecord::new( + Some(FcSaftAssociationRecord::new(kappa_ab, epsilon_k_ab)), + na, + nb, + 0.0, + )], + ))?; + let eos = FcSaftHomo::new(params); + let params = [ + s as f64, + l, + sigma, + epsilon_k, + mu, + kappa_ab, + epsilon_k_ab, + na, + nb, + ]; + Ok((FcSaftPure(params), eos)) + } + + #[test] + fn test_fcsaft_pure() -> FeosResult<()> { + let (fcsaft, eos) = fcsaft()?; + + let temperature = 350.0 * KELVIN; + let volume = 2.3 * METER * METER * METER; + let moles = dvector![1.3] * KILO * MOL; + + let state = State::new_nvt(&&eos, temperature, volume, &moles)?; + let a_feos = state.residual_molar_helmholtz_energy(); + let mu_feos = state.residual_chemical_potential(); + let p_feos = state.pressure(Total); + let s_feos = state.residual_molar_entropy(); + let h_feos = state.residual_molar_enthalpy(); + + let moles = vector![1.3] * KILO * MOL; + let state = State::new_nvt(&fcsaft, temperature, volume, moles)?; + let a_ad = state.residual_molar_helmholtz_energy(); + let mu_ad = state.residual_chemical_potential(); + let p_ad = state.pressure(Total); + let s_ad = state.residual_molar_entropy(); + let h_ad = state.residual_molar_enthalpy(); + + println!("\nMolar Helmholtz energy:\n{a_feos}"); + println!("{a_ad}"); + assert_relative_eq!(a_feos, a_ad, max_relative = 1e-14); + + println!("\nChemical potential:\n{}", mu_feos.get(0)); + println!("{}", mu_ad.get(0)); + assert_relative_eq!(mu_feos.get(0), mu_ad.get(0), max_relative = 1e-14); + + println!("\nPressure:\n{p_feos}"); + println!("{p_ad}"); + assert_relative_eq!(p_feos, p_ad, max_relative = 1e-14); + + println!("\nMolar entropy:\n{s_feos}"); + println!("{s_ad}"); + assert_relative_eq!(s_feos, s_ad, max_relative = 1e-14); + + println!("\nMolar enthalpy:\n{h_feos}"); + println!("{h_ad}"); + assert_relative_eq!(h_feos, h_ad, max_relative = 1e-14); + + Ok(()) + } + + #[test] + fn test_fcsaft_pure_heterosegmented() -> FeosResult<()> { + let (s, l, sigma, epsilon_k) = (4, 2.1, 3.6, 220.0); + let fcsaft = FcSaftPure([s as f64, l, sigma, epsilon_k, 0.0]); + let params = + new_pure_homosegmented(Identifier::default(), s, sigma, epsilon_k, l, 0.0, None)?; + let eos = FcSaft::new(params); + + let temperature = 300.0 * KELVIN; + let volume = 1.7 * METER * METER * METER; + + let state = State::new_nvt(&&eos, temperature, volume, &(dvector![2.1] * KILO * MOL))?; + let a_feos = state.residual_molar_helmholtz_energy(); + let p_feos = state.pressure(Total); + + let state = State::new_nvt(&fcsaft, temperature, volume, vector![2.1] * KILO * MOL)?; + let a_ad = state.residual_molar_helmholtz_energy(); + let p_ad = state.pressure(Total); + + assert_relative_eq!(a_feos, a_ad, max_relative = 1e-13); + assert_relative_eq!(p_feos, p_ad, max_relative = 1e-13); + Ok(()) + } +} diff --git a/crates/feos/src/fcsaft/homosegmented/mod.rs b/crates/feos/src/fcsaft/homosegmented/mod.rs new file mode 100644 index 000000000..a4aaa0c9f --- /dev/null +++ b/crates/feos/src/fcsaft/homosegmented/mod.rs @@ -0,0 +1,485 @@ +//! Homosegmented formulation of FC-SAFT for chains of identical fused spheres. +use super::eos::dispersion::Dispersion; +use super::reference::ReferenceFluid; +use super::{DispersionConstants, FcSaftOptions}; +use crate::association::Association; +use crate::hard_sphere::HardSphereProperties; +use feos_core::{Molarweight, ResidualDyn, StateHD, Subset}; +use nalgebra::DVector; +use num_dual::DualNum; +use quantity::MolarWeight; +use std::f64::consts::FRAC_PI_6; + +mod fcsaft_binary; +mod fcsaft_pure; +mod parameters; +mod polar; +pub use fcsaft_binary::FcSaftBinary; +pub use fcsaft_pure::FcSaftPure; +pub use parameters::{FcSaftHomoParameters, FcSaftHomoPars, FcSaftHomoRecord}; +use polar::Dipole; + +/// Homosegmented FC-SAFT equation of state. +pub struct FcSaftHomo { + pub parameters: FcSaftHomoParameters, + pub params: FcSaftHomoPars, + options: FcSaftOptions, + dispersion: Dispersion, + dipole: Option, + association: Option, + model_constants: Option, +} + +impl FcSaftHomo { + pub fn new(parameters: FcSaftHomoParameters) -> Self { + Self::with_options(parameters, FcSaftOptions::default(), None) + } + + /// Homosegmented FC-SAFT with custom options and (optionally) custom + /// model constants `[a1, a2, b1, b2]` of the dispersion contribution. + pub fn with_options( + parameters: FcSaftHomoParameters, + options: FcSaftOptions, + model_constants: Option, + ) -> Self { + let params = FcSaftHomoPars::new(¶meters); + let dispersion = Dispersion::new( + ¶ms.component_index, + ¶ms.sigma_ij, + ¶ms.epsilon_k_ij, + model_constants, + ); + let dipole = (!params.dipole_comp.is_empty()).then_some(Dipole); + let association = (!parameters.association.is_empty()) + .then(|| Association::new(options.max_iter_cross_assoc, options.tol_cross_assoc)); + Self { + parameters, + params, + options, + dispersion, + dipole, + association, + model_constants, + } + } +} + +impl ResidualDyn for FcSaftHomo { + fn components(&self) -> usize { + self.parameters.pure.len() + } + + fn compute_max_density + Copy>(&self, molefracs: &DVector) -> D { + let p = &self.params; + let [_, m_star] = p.m_values(&p.sigma); + let msigma3 = m_star.component_mul(&p.sigma.map(|s| s.powi(3))); + (msigma3.map(D::from).dot(molefracs) * FRAC_PI_6).recip() * self.options.max_eta + } + + fn for_each_contribution + Copy>( + &self, + state: &StateHD, + mut f: impl FnMut(&'static str, D), + ) { + let p = &self.params; + let d = p.hs_diameter(state.temperature); + + let density = state.partial_density.sum(); + let m = p.m_values(&d); + let ([hs, chain], c1) = ReferenceFluid::new_homosegmented(&p.s, &p.l, &d, &m) + .helmholtz_energy_density(density, &state.molefracs); + f("Hard Sphere", hs); + f("Fused-sphere chain", chain); + f( + "Dispersion", + self.dispersion.helmholtz_energy_density(state, &d, &m, c1), + ); + if let Some(dipole) = self.dipole.as_ref() { + f( + "Dipole", + dipole.helmholtz_energy_density(&self.params, state), + ) + } + if let Some(association) = self.association.as_ref() { + f( + "Association", + association.helmholtz_energy_density( + &self.params, + &self.parameters.association, + state, + &d, + ), + ) + } + } +} + +impl Subset for FcSaftHomo { + fn subset(&self, component_list: &[usize]) -> Self { + Self::with_options( + self.parameters.subset(component_list), + self.options, + self.model_constants, + ) + } +} + +impl Molarweight for FcSaftHomo { + fn molar_weight(&self) -> MolarWeight> { + self.parameters.molar_weight.clone() + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::fcsaft::{ + FcSaft, FcSaftAssociationRecord, FcSaftBondRecord, FcSaftParameters, FcSaftRecord, + }; + use approx::assert_relative_eq; + use feos_core::FeosResult; + use feos_core::State; + use feos_core::parameter::{ + AssociationRecord, BinarySegmentRecord, ChemicalRecord, PureRecord, SegmentRecord, + }; + use quantity::{KELVIN, METER, MOL}; + + #[test] + fn test_homo() -> FeosResult<()> { + let s = 3; + let l = 2.5; + let sigma = 3.5; + let epsilon_k = 250.0; + let association = vec![AssociationRecord::new( + Some(FcSaftAssociationRecord::new(0.03, 2500.0)), + 1.0, + 1.0, + 0.0, + )]; + + let pr = PureRecord::with_association( + Default::default(), + 0.0, + FcSaftHomoRecord::new(s, l, sigma, epsilon_k, 0.0), + association.clone(), + ); + let params_homo = FcSaftHomoParameters::new_pure(pr)?; + let fcsaft_homo = FcSaftHomo::new(params_homo); + + let mut segments = vec!["S".into(); s - 1]; + segments.push("SA".into()); + let cr = ChemicalRecord::new(Default::default(), segments, None); + let sr = SegmentRecord::new("S".into(), 0.0, FcSaftRecord::new(sigma, epsilon_k, None)); + let sr_a = SegmentRecord::with_association( + "SA".into(), + 0.0, + FcSaftRecord::new(sigma, epsilon_k, None), + association, + ); + let br = [ + BinarySegmentRecord::new("S".into(), "S".into(), Some(FcSaftBondRecord::new(l))), + BinarySegmentRecord::new("S".into(), "SA".into(), Some(FcSaftBondRecord::new(l))), + ]; + let params = FcSaftParameters::from_segments_with_bonds(vec![cr], &[sr, sr_a], None, &br)?; + let fcsaft = FcSaft::new(params); + + let t = 300.0 * KELVIN; + let v = METER.powi::<3>(); + let n = 500.0 * MOL; + let c_homo = State::new_nvt(&&fcsaft_homo, t, v, n)?.pressure_contributions(); + let c = State::new_nvt(&&fcsaft, t, v, n)?.pressure_contributions(); + assert_eq!(c.len(), 5); + assert_eq!(c_homo.len(), 5); + for i in 0..5 { + println!("{:20} {:13.8} {:13.8}", c[i].0, c[i].1, c_homo[i].1); + } + for i in 0..5 { + assert_relative_eq!(c[i].1, c_homo[i].1, max_relative = 1e-10); + } + + Ok(()) + } + + #[test] + fn test_homo_mixture() -> FeosResult<()> { + // (s, l, sigma, epsilon_k) + let components = [(3, 2.5, 3.5, 250.0), (6, 2.0, 3.8, 220.0)]; + let names = ["A", "B"]; + let segment_records: Vec<_> = (0..2) + .map(|i| { + let (_, _, sigma, epsilon_k) = components[i]; + SegmentRecord::new( + names[i].into(), + 1.0, + FcSaftRecord::new(sigma, epsilon_k, None), + ) + }) + .collect(); + let bond_records: Vec<_> = (0..2) + .map(|i| { + let l = components[i].1; + BinarySegmentRecord::new( + names[i].into(), + names[i].into(), + Some(FcSaftBondRecord::new(l)), + ) + }) + .collect(); + + for order in [[0, 1], [1, 0]] { + let pure_records = order + .iter() + .map(|&i| { + let (s, l, sigma, epsilon_k) = components[i]; + let record = FcSaftHomoRecord::new(s, l, sigma, epsilon_k, 0.0); + PureRecord::new(Default::default(), 1.0, record) + }) + .collect(); + let fcsaft_homo = FcSaftHomo::new(FcSaftHomoParameters::new(pure_records, vec![])?); + + let chemical_records = order + .iter() + .map(|&i| { + let segments = vec![names[i].into(); components[i].0]; + ChemicalRecord::new(Default::default(), segments, None) + }) + .collect(); + let params = FcSaftParameters::from_segments_with_bonds( + chemical_records, + &segment_records, + None, + &bond_records, + )?; + let fcsaft = FcSaft::new(params); + + let t = 300.0 * KELVIN; + let v = METER.powi::<3>(); + for x1 in [0.0, 0.1, 0.5, 0.9, 1.0] { + let n = nalgebra::dvector![x1, 1.0 - x1] * 2000.0 * MOL; + let c_homo = State::new_nvt(&&fcsaft_homo, t, v, &n)?.pressure_contributions(); + let c = State::new_nvt(&&fcsaft, t, v, &n)?.pressure_contributions(); + assert_eq!(c.len(), c_homo.len()); + for ((name, p), (_, p_homo)) in c.iter().zip(&c_homo) { + println!("{order:?} {x1:4.2} {name:20} {p:13.8} {p_homo:13.8}"); + assert_relative_eq!(p, p_homo, max_relative = 1e-10); + } + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests_parameter_fit { + use super::fcsaft_pure::test::fcsaft; + use super::*; + use approx::assert_relative_eq; + use feos_core::DensityInitialization::Liquid; + use feos_core::ad::{ + BoilingTemperature, EquilibriumLiquidDensity, LiquidDensity, PropertyAD, VaporPressure, + }; + use feos_core::{FeosResult, PhaseEquilibrium, State, ad::ParametersAD}; + use nalgebra::{U1, U3, U9}; + use num_dual::DualStruct; + use quantity::{BAR, KELVIN, LITER, MOL, PASCAL, Pressure}; + + fn fcsaft_non_assoc() -> FcSaftPure { + let s = 3.0; + let l = 2.5; + let sigma = 3.4; + let epsilon_k = 180.0; + let mu = 2.2; + let params = [s, l, sigma, epsilon_k, mu]; + FcSaftPure(params) + } + + #[test] + fn test_vapor_pressure_derivatives() -> FeosResult<()> { + let fcsaft_params = [ + "s", + "l", + "sigma", + "epsilon_k", + "mu", + "kappa_ab", + "epsilon_k_ab", + "na", + "nb", + ]; + let (fcsaft, _) = fcsaft()?; + let fcsaft_ad = FcSaftPure::::seed_derivatives(&fcsaft.0, fcsaft_params); + let temperature = 300.0 * KELVIN; + let p = VaporPressure(temperature).evaluate(&fcsaft_ad)?; + let p = p.convert_into(PASCAL); + let (p, grad) = (p.re, p.eps.unwrap_generic(U9, U1)); + + println!("{p:.5}"); + println!("{grad:.5?}"); + + // central differences, because the vapor pressure is strongly curved in some + // of the parameters (e.g., sigma) + for (i, par) in fcsaft_params.into_iter().enumerate() { + let h = fcsaft.0[i] * 1e-6; + let p_h = |h: f64| { + let mut params = fcsaft.0; + params[i] += h; + PhaseEquilibrium::pure_t(&FcSaftPure(params), temperature, None, Default::default()) + .map(|(p, _)| p.convert_into(PASCAL)) + }; + let dp_h = (p_h(h)? - p_h(-h)?) / (2.0 * h); + let dp = grad[i]; + println!( + "{par:12}: {:11.5} {:11.5} {:.3e}", + dp_h, + dp, + ((dp_h - dp) / dp).abs() + ); + assert_relative_eq!(dp, dp_h, max_relative = 1e-6); + } + Ok(()) + } + + #[test] + fn test_vapor_pressure_derivatives_fit() -> FeosResult<()> { + let fcsaft = fcsaft_non_assoc(); + let fcsaft_ad = + FcSaftPure::::seed_derivatives(&fcsaft.0, ["l", "sigma", "epsilon_k"]); + let temperature = 200.0 * KELVIN; + let p = VaporPressure(temperature).evaluate(&fcsaft_ad)?; + let p = p.convert_into(PASCAL); + let (p, grad) = (p.re, p.eps.unwrap_generic(U3, U1)); + + println!("{p:.5}"); + println!("{grad:.5?}"); + + for (i, par) in ["l", "sigma", "epsilon_k"].into_iter().enumerate() { + let mut params = fcsaft.0; + let h = params[i + 1] * 1e-7; + params[i + 1] += h; + let fcsaft_h = FcSaftPure(params); + let (p_h, _) = + PhaseEquilibrium::pure_t(&fcsaft_h, temperature, None, Default::default())?; + let dp_h = (p_h.convert_into(PASCAL) - p) / h; + let dp = grad[i]; + println!( + "{par:12}: {:11.5} {:11.5} {:.3e}", + dp_h, + dp, + ((dp_h - dp) / dp).abs() + ); + assert_relative_eq!(dp, dp_h, max_relative = 1e-6); + } + Ok(()) + } + + #[test] + fn test_boiling_temperature_derivatives_fit() -> FeosResult<()> { + let fcsaft = fcsaft_non_assoc(); + let fcsaft_ad = + FcSaftPure::::seed_derivatives(&fcsaft.0, ["l", "sigma", "epsilon_k"]); + let pressure = BAR; + let t = BoilingTemperature(pressure).evaluate(&fcsaft_ad)?; + let t = t.convert_into(KELVIN); + let (t, grad) = (t.re, t.eps.unwrap_generic(U3, U1)); + + println!("{t:.5}"); + println!("{grad:.5?}"); + + let (t_check, _) = PhaseEquilibrium::pure_p( + &fcsaft_ad, + Pressure::from_inner(&pressure), + None, + Default::default(), + )?; + let t_check = t_check.convert_into(KELVIN); + let (t_check, grad_check) = (t_check.re, t_check.eps.unwrap_generic(U3, U1)); + println!("{t_check:.5}"); + println!("{grad_check:.5?}"); + assert_relative_eq!(t, t_check, max_relative = 1e-15); + assert_relative_eq!(grad, grad_check, max_relative = 1e-15); + + for (i, par) in ["l", "sigma", "epsilon_k"].into_iter().enumerate() { + let mut params = fcsaft.0; + let h = params[i + 1] * 1e-8; + params[i + 1] += h; + let fcsaft_h = FcSaftPure(params); + let (t_h, _) = PhaseEquilibrium::pure_p(&fcsaft_h, pressure, None, Default::default())?; + let dt_h = (t_h.convert_into(KELVIN) - t) / h; + let dt = grad[i]; + println!( + "{par:12}: {:11.5} {:11.5} {:.3e}", + dt_h, + dt, + ((dt_h - dt) / dt).abs() + ); + assert_relative_eq!(dt, dt_h, max_relative = 1e-6); + } + Ok(()) + } + + #[test] + fn test_equilibrium_liquid_density_derivatives_fit() -> FeosResult<()> { + let fcsaft = fcsaft_non_assoc(); + let fcsaft_ad = + FcSaftPure::::seed_derivatives(&fcsaft.0, ["l", "sigma", "epsilon_k"]); + let temperature = 200.0 * KELVIN; + let rho = EquilibriumLiquidDensity(temperature).evaluate(&fcsaft_ad)?; + let rho = rho.convert_into(MOL / LITER); + let (rho, rho_grad) = (rho.re, rho.eps.unwrap_generic(U3, U1)); + + println!("{rho:.5}"); + println!("{rho_grad:.5?}"); + + for (i, par) in ["l", "sigma", "epsilon_k"].into_iter().enumerate() { + let mut params = fcsaft.0; + let h = params[i + 1] * 1e-7; + params[i + 1] += h; + let fcsaft_h = FcSaftPure(params); + let (_, [_, rho_h]) = + PhaseEquilibrium::pure_t(&fcsaft_h, temperature, None, Default::default())?; + let drho_h = (rho_h.convert_into(MOL / LITER) - rho) / h; + let drho = rho_grad[i]; + println!( + "{par:12}: {:11.5} {:11.5} {:.3e}", + drho_h, + drho, + ((drho_h - drho) / drho).abs() + ); + assert_relative_eq!(drho, drho_h, max_relative = 1e-6); + } + Ok(()) + } + + #[test] + fn test_liquid_density_derivatives_fit() -> FeosResult<()> { + let fcsaft = fcsaft_non_assoc(); + let fcsaft_ad = + FcSaftPure::::seed_derivatives(&fcsaft.0, ["l", "sigma", "epsilon_k"]); + let temperature = 200.0 * KELVIN; + let pressure = BAR; + let rho = LiquidDensity(temperature, pressure).evaluate(&fcsaft_ad)?; + let rho = rho.convert_into(MOL / LITER); + let (rho, grad) = (rho.re, rho.eps.unwrap_generic(U3, U1)); + + println!("{rho:.5}"); + println!("{grad:.5?}"); + + for (i, par) in ["l", "sigma", "epsilon_k"].into_iter().enumerate() { + let mut params = fcsaft.0; + let h = params[i + 1] * 1e-7; + params[i + 1] += h; + let fcsaft_h = FcSaftPure(params); + let rho_h = State::new_npt(&fcsaft_h, temperature, pressure, (), Some(Liquid))?.density; + let drho_h = (rho_h.convert_into(MOL / LITER) - rho) / h; + let drho = grad[i]; + println!( + "{par:12}: {:11.5} {:11.5} {:.3e}", + drho_h, + drho, + ((drho_h - drho) / drho).abs() + ); + assert_relative_eq!(drho, drho_h, max_relative = 1e-6); + } + Ok(()) + } +} diff --git a/crates/feos/src/fcsaft/homosegmented/parameters.rs b/crates/feos/src/fcsaft/homosegmented/parameters.rs new file mode 100644 index 000000000..82d110f69 --- /dev/null +++ b/crates/feos/src/fcsaft/homosegmented/parameters.rs @@ -0,0 +1,163 @@ +use crate::association::AssociationStrength; +use crate::fcsaft::record::{FcSaftAssociationRecord, FcSaftBinaryRecord}; +use crate::hard_sphere::{HardSphereProperties, MonomerShape}; +use feos_core::parameter::{CombiningRule, Parameters}; +use nalgebra::{DMatrix, DVector}; +use num_dual::DualNum; +use num_traits::Zero; +use quantity::{JOULE, KB, KELVIN}; +use serde::{Deserialize, Serialize}; + +/// Pure-component parameters of the homosegmented FC-SAFT equation of state. +#[derive(Serialize, Deserialize, Clone, Default)] +pub struct FcSaftHomoRecord { + /// Segment number + pub s: usize, + /// Bond length in units of Angstrom + pub l: f64, + /// Segment diameter in units of Angstrom + pub sigma: f64, + /// Energetic parameter in units of Kelvin + pub epsilon_k: f64, + /// Dipole moment in units of Debye + #[serde(skip_serializing_if = "f64::is_zero")] + #[serde(default)] + pub mu: f64, +} + +impl FcSaftHomoRecord { + pub fn new(s: usize, l: f64, sigma: f64, epsilon_k: f64, mu: f64) -> Self { + Self { + s, + l, + sigma, + epsilon_k, + mu, + } + } +} + +impl CombiningRule for FcSaftAssociationRecord { + fn combining_rule( + _: &FcSaftHomoRecord, + _: &FcSaftHomoRecord, + parameters_i: &Self, + parameters_j: &Self, + ) -> Self { + Self::combine(parameters_i, parameters_j) + } +} + +/// Parameter set required for the homosegmented FC-SAFT equation of state. +pub type FcSaftHomoParameters = + Parameters; + +/// The homosegmented FC-SAFT parameters in an easier accessible format. +pub struct FcSaftHomoPars { + pub component_index: DVector, + pub s: DVector, + pub l: DVector, + pub sigma: DVector, + pub epsilon_k: DVector, + pub mu2: DVector, + pub sigma_ij: DMatrix, + pub epsilon_k_ij: DMatrix, + pub e_k_ij: DMatrix, + pub dipole_comp: Vec, +} + +impl FcSaftHomoPars { + pub fn new(parameters: &FcSaftHomoParameters) -> Self { + let n = parameters.pure.len(); + + let [s, l, sigma, epsilon_k, mu] = + parameters.collate(|pr| [pr.s as f64, pr.l, pr.sigma, pr.epsilon_k, pr.mu]); + let [k_ij] = parameters.collate_binary(|br| [br.k_ij]); + + let ld = l.component_div(&sigma); + let m_star = DVector::from_fn(n, |i, _| { + 1.0 + 0.5 * ld[i] * (3.0 - ld[i] * ld[i]) * (s[i] - 1.0) + }); + // Note: the reduced dipole moment is normalized with the reduced volume m*. + // Using the reduced surface m (which replaces the segment number of PC-SAFT + // everywhere else) would be an equally valid generalization to fused chains. + let mu2 = DVector::from_fn(n, |i, _| { + mu[i] * mu[i] / (m_star[i] * sigma[i].powi(3) * epsilon_k[i]) + * 1e-19 + * (JOULE / KELVIN / KB).into_value() + }); + let dipole_comp = mu2 + .iter() + .enumerate() + .filter_map(|(i, &mu2)| (mu2.abs() > 0.0).then_some(i)) + .collect(); + + let sigma_ij = DMatrix::from_fn(n, n, |i, j| 0.5 * (sigma[i] + sigma[j])); + let e_k_ij = DMatrix::from_fn(n, n, |i, j| (epsilon_k[i] * epsilon_k[j]).sqrt()); + let epsilon_k_ij = (-k_ij).add_scalar(1.0).component_mul(&e_k_ij); + + Self { + component_index: DVector::from_fn(n, |i, _| i), + s, + l, + sigma, + epsilon_k, + mu2, + sigma_ij, + epsilon_k_ij, + e_k_ij, + dipole_comp, + } + } + + /// The mean segment number $m$ and the reduced volume $m^*$ of every component. + pub fn m_values + Copy>( + &self, + diameter: &DVector, + ) -> [DVector; 2] { + let ld = DVector::from_fn(diameter.len(), |i, _| diameter[i].recip() * self.l[i]); + let m = DVector::from_fn(ld.len(), |i, _| ld[i] * (self.s[i] - 1.0) + 1.0); + let m_star = DVector::from_fn(ld.len(), |i, _| { + (-(ld[i] * ld[i]) + 3.0) * ld[i] * 0.5 * (self.s[i] - 1.0) + 1.0 + }); + [m, m_star] + } +} + +impl HardSphereProperties for FcSaftHomoPars { + fn monomer_shape + Copy>( + &self, + temperature: N, + ) -> MonomerShape<'_, N> { + let [m, m_star] = self.m_values(&self.hs_diameter(temperature)); + MonomerShape::Heterosegmented( + [self.s.map(N::from), m.clone(), m, m_star], + &self.component_index, + ) + } + + fn hs_diameter + Copy>(&self, temperature: D) -> DVector { + let ti = temperature.recip() * -3.0; + DVector::from_fn(self.sigma.len(), |i, _| { + -((ti * self.epsilon_k[i]).exp() * 0.12 - 1.0) * self.sigma[i] + }) + } +} + +impl AssociationStrength for FcSaftHomoPars { + type Record = FcSaftAssociationRecord; + + fn association_strength_ij + Copy>( + &self, + temperature: D, + comp_i: usize, + comp_j: usize, + assoc_ij: &Self::Record, + ) -> D { + let si = self.sigma[comp_i]; + let sj = self.sigma[comp_j]; + (temperature.recip() * assoc_ij.epsilon_k_ab).exp_m1() + * assoc_ij.kappa_ab + * (si * sj).powf(1.5) + } +} diff --git a/crates/feos/src/fcsaft/homosegmented/polar.rs b/crates/feos/src/fcsaft/homosegmented/polar.rs new file mode 100644 index 000000000..f86601f50 --- /dev/null +++ b/crates/feos/src/fcsaft/homosegmented/polar.rs @@ -0,0 +1,139 @@ +use super::FcSaftHomoPars; +use crate::hard_sphere::HardSphereProperties; +use feos_core::StateHD; +use num_dual::DualNum; +use std::f64::consts::{FRAC_PI_3, FRAC_PI_6, PI}; + +// Dipole parameters +pub(super) const AD: [[f64; 3]; 5] = [ + [0.30435038064, 0.95346405973, -1.16100802773], + [-0.13585877707, -1.83963831920, 4.52586067320], + [1.44933285154, 2.01311801180, 0.97512223853], + [0.35569769252, -7.37249576667, -12.2810377713], + [-2.06533084541, 8.23741345333, 5.93975747420], +]; + +pub(super) const BD: [[f64; 3]; 5] = [ + [0.21879385627, -0.58731641193, 3.48695755800], + [-1.18964307357, 1.24891317047, -14.9159739347], + [1.16268885692, -0.50852797392, 15.3720218600], + [0.0; 3], + [0.0; 3], +]; + +pub(super) const CD: [[f64; 3]; 4] = [ + [-0.06467735252, -0.95208758351, -0.62609792333], + [0.19758818347, 2.99242575222, 1.29246858189], + [-0.80875619458, -2.38026356489, 1.65427830900], + [0.69028490492, -0.27012609786, -3.43967436378], +]; + +const PI_SQ_43: f64 = 4.0 * PI * FRAC_PI_3; + +fn pair_integral_ij + Copy>( + mij1: D, + mij2: D, + etas: &[D], + a: &[[f64; 3]], + b: &[[f64; 3]], + eps_ij_t: D, +) -> D { + (0..a.len()) + .map(|i| { + etas[i] + * (eps_ij_t * (mij2 * b[i][2] + mij1 * b[i][1] + b[i][0]) + + (mij2 * a[i][2] + mij1 * a[i][1] + a[i][0])) + }) + .sum() +} + +fn triplet_integral_ijk + Copy>( + mijk1: D, + mijk2: D, + etas: &[D], + c: &[[f64; 3]], +) -> D { + (0..c.len()) + .map(|i| etas[i] * (mijk2 * c[i][2] + mijk1 * c[i][1] + c[i][0])) + .sum() +} + +pub(super) struct Dipole; + +impl Dipole { + pub(super) fn helmholtz_energy_density + Copy>( + &self, + parameters: &FcSaftHomoPars, + state: &StateHD, + ) -> D { + let p = parameters; + let ndipole = p.dipole_comp.len(); + + let t_inv = state.temperature.inv(); + let eps_ij_t = p.e_k_ij.map(|v| t_inv * v); + let sig_ij_3 = p.sigma_ij.map(|v| v.powi(3)); + let mu2_term: Vec = p + .dipole_comp + .iter() + .map(|&i| t_inv * sig_ij_3[(i, i)] * p.epsilon_k[i] * p.mu2[i]) + .collect(); + + let rho = &state.partial_density; + let d = p.hs_diameter(state.temperature); + let [m, m_star] = p.m_values(&d); + let eta = (0..d.len()) + .map(|i| rho[i] * m_star[i] * d[i].powi(3)) + .sum::() + * FRAC_PI_6; + let eta2 = eta * eta; + let etas = [D::one(), eta, eta2, eta2 * eta, eta2 * eta2]; + + // mean segment numbers (limited to m=2) + let clamp = |m: D| if m.re() > 2.0 { D::from(2.0) } else { m }; + let m: Vec<_> = p.dipole_comp.iter().map(|&i| clamp(m[i])).collect(); + + let mut phi2 = D::zero(); + let mut phi3 = D::zero(); + for i in 0..ndipole { + let di = p.dipole_comp[i]; + for j in i..ndipole { + let dj = p.dipole_comp[j]; + let mij = (m[i] * m[j]).sqrt(); + let mij1 = (mij - 1.0) / mij; + let mij2 = mij1 * (mij - 2.0) / mij; + let c = if i == j { 1.0 } else { 2.0 }; + phi2 -= rho[di] + * rho[dj] + * mu2_term[i] + * mu2_term[j] + * pair_integral_ij(mij1, mij2, &etas, &AD, &BD, eps_ij_t[(di, dj)]) + / sig_ij_3[(di, dj)] + * c; + for k in j..ndipole { + let dk = p.dipole_comp[k]; + let mijk = (m[i] * m[j] * m[k]).cbrt(); + let mijk1 = (mijk - 1.0) / mijk; + let mijk2 = mijk1 * (mijk - 2.0) / mijk; + let c = if i == k { + 1.0 + } else if i == j || j == k { + 3.0 + } else { + 6.0 + }; + phi3 -= rho[di] * rho[dj] * rho[dk] * mu2_term[i] * mu2_term[j] * mu2_term[k] + / (p.sigma_ij[(di, dj)] * p.sigma_ij[(di, dk)] * p.sigma_ij[(dj, dk)]) + * triplet_integral_ijk(mijk1, mijk2, &etas, &CD) + * c; + } + } + } + phi2 *= PI; + phi3 *= PI_SQ_43; + let mut result = phi2 * phi2 / (phi2 - phi3); + if result.re().is_nan() { + result = phi2 + } + result + } +} diff --git a/crates/feos/src/fcsaft/mod.rs b/crates/feos/src/fcsaft/mod.rs new file mode 100644 index 000000000..75a238944 --- /dev/null +++ b/crates/feos/src/fcsaft/mod.rs @@ -0,0 +1,43 @@ +//! Fused-chain SAFT (FC-SAFT) +//! +//! Equation of state and Helmholtz energy functional for (heterosegmented) +//! chains of fused hard spheres with explicit bond lengths. + +#[cfg(feature = "dft")] +mod dft; +mod eos; +pub mod homosegmented; +mod parameters; +mod record; +mod reference; + +#[cfg(feature = "dft")] +pub use dft::{FcSaftFunctional, FcSaftFunctionalContribution}; +pub use eos::{DispersionConstants, FcSaft}; +pub use homosegmented::{FcSaftBinary, FcSaftHomo, FcSaftPure}; +pub use parameters::FcSaftPars; +pub use record::{ + FcSaftAssociationRecord, FcSaftBinaryRecord, FcSaftBondRecord, FcSaftParameters, FcSaftRecord, + new_pure_homosegmented, +}; + +/// Customization options for the FC-SAFT equation of state and functional. +#[derive(Copy, Clone)] +pub struct FcSaftOptions { + /// maximum packing fraction + pub max_eta: f64, + /// maximum number of iterations for cross association calculation + pub max_iter_cross_assoc: usize, + /// tolerance for cross association calculation + pub tol_cross_assoc: f64, +} + +impl Default for FcSaftOptions { + fn default() -> Self { + Self { + max_eta: 0.5, + max_iter_cross_assoc: 50, + tol_cross_assoc: 1e-10, + } + } +} diff --git a/crates/feos/src/fcsaft/parameters.rs b/crates/feos/src/fcsaft/parameters.rs new file mode 100644 index 000000000..7df66ef4b --- /dev/null +++ b/crates/feos/src/fcsaft/parameters.rs @@ -0,0 +1,121 @@ +use super::record::{FcSaftAssociationRecord, FcSaftParameters}; +use crate::association::AssociationStrength; +use crate::hard_sphere::{HardSphereProperties, MonomerShape}; +use nalgebra::{DMatrix, DVector}; +use num_dual::DualNum; +use petgraph::graph::{NodeIndex, UnGraph}; + +/// psi parameter for the dispersion functional of fused chains. +const PSI_FUSED_CHAINS: f64 = 1.5; + +/// The FC-SAFT parameters in an easier accessible format. +pub struct FcSaftPars { + pub component_index: DVector, + pub sigma: DVector, + pub epsilon_k: DVector, + pub bonds: UnGraph<(), f64>, + pub psi_dft: DVector, + pub k_ij: DMatrix, + pub sigma_ij: DMatrix, + pub epsilon_k_ij: DMatrix, +} + +impl FcSaftPars { + pub fn new(parameters: &FcSaftParameters) -> Self { + let component_index = parameters.component_index().into(); + + let [sigma, epsilon_k] = parameters.collate(|pr| [pr.sigma, pr.epsilon_k]); + let [psi_dft] = parameters.collate(|pr| [pr.psi_dft.unwrap_or(PSI_FUSED_CHAINS)]); + + // every segment is a node in the graph, so that single-segment molecules are included + let n = sigma.len(); + let mut bonds = UnGraph::with_capacity(n, parameters.bonds.len()); + (0..n).for_each(|_| { + bonds.add_node(()); + }); + for b in ¶meters.bonds { + bonds.add_edge( + NodeIndex::new(b.id1), + NodeIndex::new(b.id2), + b.model_record.bond_length, + ); + } + + // Combining rules dispersion + let [k_ij] = parameters.collate_binary(|br| [br.k_ij]); + let sigma_ij = DMatrix::from_fn(n, n, |i, j| 0.5 * (sigma[i] + sigma[j])); + let epsilon_k_ij = DMatrix::from_fn(n, n, |i, j| { + (epsilon_k[i] * epsilon_k[j]).sqrt() * (1.0 - k_ij[(i, j)]) + }); + + Self { + component_index, + sigma, + epsilon_k, + bonds, + psi_dft, + k_ij, + sigma_ij, + epsilon_k_ij, + } + } + + /// The geometry coefficients of the fused spheres: the reduced surface $a_\alpha$ + /// and the reduced volume $v_\alpha$ of every segment. + pub fn fused_sphere_coefficients + Copy>( + &self, + diameter: &DVector, + ) -> [DVector; 2] { + let mut a = DVector::from_element(diameter.len(), D::one()); + let mut v = DVector::from_element(diameter.len(), D::one()); + for e in self.bonds.edge_indices() { + let (n1, n2) = self.bonds.edge_endpoints(e).unwrap(); + let l12 = self.bonds[e]; + for (i, j) in [(n1.index(), n2.index()), (n2.index(), n1.index())] { + let (d1, d2) = (diameter[i], diameter[j]); + let delta12 = (d1.powi(2) - d2.powi(2) + 4.0 * l12.powi(2)) / (8.0 * l12); + a[i] -= (-delta12 * 2.0 / d1 + 1.0) * 0.5; + v[i] -= (-delta12 * 3.0 / d1 + (delta12 / d1).powi(3) * 4.0 + 1.0) * 0.5; + } + } + [a, v] + } +} + +impl HardSphereProperties for FcSaftPars { + fn monomer_shape + Copy>( + &self, + temperature: N, + ) -> MonomerShape<'_, N> { + let [a, v] = self.fused_sphere_coefficients(&self.hs_diameter(temperature)); + MonomerShape::Heterosegmented( + [DVector::from_element(a.len(), N::one()), a.clone(), a, v], + &self.component_index, + ) + } + + fn hs_diameter + Copy>(&self, temperature: D) -> DVector { + let ti = temperature.recip() * -3.0; + DVector::from_fn(self.sigma.len(), |i, _| { + -((ti * self.epsilon_k[i]).exp() * 0.12 - 1.0) * self.sigma[i] + }) + } +} + +impl AssociationStrength for FcSaftPars { + type Record = FcSaftAssociationRecord; + + fn association_strength_ij + Copy>( + &self, + temperature: D, + comp_i: usize, + comp_j: usize, + assoc_ij: &Self::Record, + ) -> D { + let si = self.sigma[comp_i]; + let sj = self.sigma[comp_j]; + (temperature.recip() * assoc_ij.epsilon_k_ab).exp_m1() + * assoc_ij.kappa_ab + * (si * sj).powf(1.5) + } +} diff --git a/crates/feos/src/fcsaft/record.rs b/crates/feos/src/fcsaft/record.rs new file mode 100644 index 000000000..4fa1c0c4c --- /dev/null +++ b/crates/feos/src/fcsaft/record.rs @@ -0,0 +1,119 @@ +use feos_core::FeosResult; +use feos_core::parameter::{ + BinarySegmentRecord, ChemicalRecord, CombiningRule, GcParameters, Identifier, SegmentRecord, +}; +use serde::{Deserialize, Serialize}; + +/// FC-SAFT segment parameters. +#[derive(Serialize, Deserialize, Clone, Default)] +pub struct FcSaftRecord { + /// Segment diameter in units of Angstrom + pub sigma: f64, + /// Energetic parameter in units of Kelvin + pub epsilon_k: f64, + /// Interaction range parameter for the dispersion functional + #[serde(skip_serializing_if = "Option::is_none")] + pub psi_dft: Option, +} + +impl FcSaftRecord { + pub fn new(sigma: f64, epsilon_k: f64, psi_dft: Option) -> Self { + Self { + sigma, + epsilon_k, + psi_dft, + } + } +} + +/// FC-SAFT association parameters. +#[derive(Serialize, Deserialize, Clone, Copy, Default, PartialEq, Debug)] +pub struct FcSaftAssociationRecord { + /// Association volume parameter + pub kappa_ab: f64, + /// Association energy parameter in units of Kelvin + pub epsilon_k_ab: f64, +} + +impl FcSaftAssociationRecord { + pub fn new(kappa_ab: f64, epsilon_k_ab: f64) -> Self { + Self { + kappa_ab, + epsilon_k_ab, + } + } + + pub(super) fn combine(parameters_i: &Self, parameters_j: &Self) -> Self { + Self { + kappa_ab: (parameters_i.kappa_ab * parameters_j.kappa_ab).sqrt(), + epsilon_k_ab: 0.5 * (parameters_i.epsilon_k_ab + parameters_j.epsilon_k_ab), + } + } +} + +impl CombiningRule for FcSaftAssociationRecord { + fn combining_rule( + _: &FcSaftRecord, + _: &FcSaftRecord, + parameters_i: &Self, + parameters_j: &Self, + ) -> Self { + Self::combine(parameters_i, parameters_j) + } +} + +/// FC-SAFT binary segment-segment interaction parameters. +#[derive(Serialize, Deserialize, Clone, Copy, Default)] +pub struct FcSaftBinaryRecord { + /// Binary dispersion interaction parameter + #[serde(default)] + pub k_ij: f64, +} + +impl FcSaftBinaryRecord { + pub fn new(k_ij: f64) -> Self { + Self { k_ij } + } +} + +/// FC-SAFT bond parameters. +#[derive(Serialize, Deserialize, Clone, Copy)] +pub struct FcSaftBondRecord { + /// Distance between the centers of two bonded segments in units of Angstrom + pub bond_length: f64, +} + +impl FcSaftBondRecord { + pub fn new(bond_length: f64) -> Self { + Self { bond_length } + } +} + +/// Parameter set required for the FC-SAFT equation of state and Helmholtz energy functional. +pub type FcSaftParameters = + GcParameters; + +/// Parameters for a pure component that consists of `segments` identical +/// fused spheres with the given bond length. +pub fn new_pure_homosegmented( + identifier: Identifier, + segments: usize, + sigma: f64, + epsilon_k: f64, + bond_length: f64, + molarweight: f64, + psi_dft: Option, +) -> FeosResult { + let chemical = ChemicalRecord::new(identifier, vec!["S".into(); segments], None); + let segment = SegmentRecord::new( + "S".into(), + molarweight / segments as f64, + FcSaftRecord::new(sigma, epsilon_k, psi_dft), + ); + let bond = BinarySegmentRecord::new( + "S".into(), + "S".into(), + Some(FcSaftBondRecord::new(bond_length)), + ); + FcSaftParameters::from_segments_with_bonds(vec![chemical], &[segment], None, &[bond]) +} diff --git a/crates/feos/src/fcsaft/reference.rs b/crates/feos/src/fcsaft/reference.rs new file mode 100644 index 000000000..562aca6ab --- /dev/null +++ b/crates/feos/src/fcsaft/reference.rs @@ -0,0 +1,165 @@ +use crate::hard_sphere::HardSphere; +use nalgebra::{DVector, Matrix4xX}; +use num_dual::{Dual2, DualNum, second_derivative}; +use petgraph::graph::UnGraph; +use petgraph::visit::EdgeRef; +use std::f64::consts::FRAC_PI_6; + +/// The reference fluid of FC-SAFT: fused hard spheres (BMCSL) and the +/// fused-sphere chain contribution. +/// +/// All temperature dependent quantities are evaluated on construction, so that +/// [ReferenceFluid::helmholtz_energy_density] only has to evaluate a scalar +/// expression in the density. This expression is evaluated with a second-order +/// dual number, which yields the compressibility term +/// $$C_1=\left(1+\rho\frac{\partial^2\phi^\mathrm{ref}}{\partial\rho^2}\right)^{-1}$$ +/// (at constant temperature and composition) of the dispersion contribution +/// together with the Helmholtz energy densities. +pub(crate) struct ReferenceFluid { + /// $\frac{\pi}{6}\sum_{\alpha\in i}C_{k,\alpha}d_\alpha^k$ for every component $i$ + zeta: Matrix4xX, + /// component index, geometry factor $b$, and number of every (type of) bond + bonds: Vec<(usize, D, f64)>, +} + +impl + Copy> ReferenceFluid { + /// The reference fluid of the heterosegmented model. + /// + /// Requires the component index and the temperature dependent diameter + /// and fused-sphere coefficients $a$ and $v$ of every segment, as well as + /// the bond lengths. + pub(crate) fn new( + component_index: &DVector, + bonds: &UnGraph<(), f64>, + diameter: &DVector, + [a, v]: &[DVector; 2], + ) -> Self { + let n = component_index.iter().max().map_or(0, |&c| c + 1); + let mut zeta = Matrix4xX::zeros(n); + for (i, &c) in component_index.iter().enumerate() { + let d = diameter[i]; + zeta[(0, c)] += D::from(FRAC_PI_6); + zeta[(1, c)] += a[i] * d * FRAC_PI_6; + zeta[(2, c)] += a[i] * d * d * FRAC_PI_6; + zeta[(3, c)] += v[i] * d * d * d * FRAC_PI_6; + } + let bonds = bonds + .edge_references() + .map(|e| { + let (i, j) = (e.source().index(), e.target().index()); + let l = *e.weight(); + let (di, dj) = (diameter[i], diameter[j]); + let b = -((di - dj).powi(2) - 4.0 * l.powi(2)) / (4.0 * l); + (component_index[i], b, 1.0) + }) + .collect(); + Self { zeta, bonds } + } + + /// The reference fluid of the homosegmented model. + /// + /// Requires the number of segments `s` and bond lengths `l` of every + /// component, as well as the temperature dependent diameter and the + /// reduced surface $m$ and volume $m^*$. + pub(crate) fn new_homosegmented( + s: &DVector, + l: &DVector, + diameter: &DVector, + [m, m_star]: &[DVector; 2], + ) -> Self { + let zeta = Matrix4xX::from_fn(s.len(), |k, i| { + let c = [D::from(s[i]), m[i], m[i], m_star[i]]; + c[k] * diameter[i].powi(k as i32) * FRAC_PI_6 + }); + let bonds = (0..s.len()) + .filter(|&i| s[i] > 1.0) + .map(|i| (i, D::from(l[i]), s[i] - 1.0)) + .collect(); + Self { zeta, bonds } + } + + /// The Helmholtz energy densities of the hard-sphere and the chain + /// contribution, and the compressibility term $C_1$. + pub(crate) fn helmholtz_energy_density( + &self, + density: D, + molefracs: &DVector, + ) -> ([D; 2], D) { + let zeta_hat: [D; 4] = (&self.zeta * molefracs).into(); + let zeta_23 = Dual2::from_re(zeta_hat[2] / zeta_hat[3]); + + // reference fluid and its second derivative w.r.t. the density, which + // yields the compressibility term C1 + let ((hs, _, d2_hs), (chain, _, d2_chain)) = second_derivative( + |rho: Dual2| { + // the packing fractions are linear in the density + let zeta = zeta_hat.map(|z| rho.scale(&z)); + + // hard spheres + let hs = HardSphere::bmcsl_helmholtz_energy_density(zeta, zeta_23); + + // fused-sphere chains + let frac_1mz3 = -(zeta[3] - 1.0).recip(); + let ln_y = self + .bonds + .iter() + .map(|&(c, b, count)| { + let z2b = zeta[2].scale(&b); + let y = + z2b * frac_1mz3 * frac_1mz3 * (z2b * frac_1mz3 * 0.5 + 1.5) + frac_1mz3; + y.ln().scale(&(molefracs[c] * count)) + }) + .fold(Dual2::from_re(D::zero()), |acc, x| acc + x); + (hs, -rho * ln_y) + }, + density, + ); + + let c1 = ((d2_hs + d2_chain) * density + 1.0).recip(); + ([hs, chain], c1) + } +} + +#[cfg(test)] +mod test { + use super::*; + use approx::assert_relative_eq; + use nalgebra::dvector; + + /// C1 of PC-SAFT, i.e., for tangent chains with `m` segments. + fn c1_pcsaft(m: f64, eta: f64) -> f64 { + (m * (eta * 8.0 - eta.powi(2) * 2.0) / (eta - 1.0).powi(4) + - (m - 1.0) + * (eta * 20.0 - eta.powi(2) * 27.0 + eta.powi(3) * 12.0 - eta.powi(4) * 2.0) + / ((eta - 1.0) * (eta - 2.0)).powi(2) + + 1.0) + .recip() + } + + #[test] + fn test_compressibility_term_tangent_chains() { + // for tangent spheres (l = d) the reduced surface and volume are equal to + // the number of segments and C1 reduces to the expression of PC-SAFT + let eta = 0.3; + for s in [1, 2, 5] { + let m = s as f64; + let density = eta / (m * FRAC_PI_6); + let c1 = c1_pcsaft(m, eta); + + let d = dvector![1.0]; + let geometry = [dvector![m], dvector![m]]; + let homo = + ReferenceFluid::new_homosegmented(&dvector![m], &dvector![1.0], &d, &geometry); + let (_, c1_homo) = homo.helmholtz_energy_density(density, &dvector![1.0]); + assert_relative_eq!(c1_homo, c1, max_relative = 1e-14); + + let component_index = DVector::zeros(s); + let bonds = UnGraph::from_edges((1..s as u32).map(|i| (i - 1, i, 1.0))); + let d = DVector::from_element(s, 1.0); + let geometry = [DVector::from_element(s, 1.0), DVector::from_element(s, 1.0)]; + let hetero = ReferenceFluid::new(&component_index, &bonds, &d, &geometry); + let (_, c1_hetero) = hetero.helmholtz_energy_density(density, &dvector![1.0]); + assert_relative_eq!(c1_hetero, c1, max_relative = 1e-14); + } + } +} diff --git a/crates/feos/src/hard_sphere/mod.rs b/crates/feos/src/hard_sphere/mod.rs index d7403d046..c51b99909 100644 --- a/crates/feos/src/hard_sphere/mod.rs +++ b/crates/feos/src/hard_sphere/mod.rs @@ -27,7 +27,10 @@ pub enum MonomerShape<'a, D> { /// Properties of (generalized) hard sphere systems. pub trait HardSphereProperties { /// The [MonomerShape] used in the model. - fn monomer_shape + Copy>(&self, temperature: D) -> MonomerShape<'_, D>; + fn monomer_shape + Copy>( + &self, + temperature: D, + ) -> MonomerShape<'_, D>; /// The temperature dependent hard-sphere diameters of every segment. fn hs_diameter + Copy>(&self, temperature: D) -> DVector; @@ -44,7 +47,10 @@ pub trait HardSphereProperties { } /// The geometry coefficients $C_{k,\alpha}$ for every segment. - fn geometry_coefficients + Copy>(&self, temperature: D) -> [DVector; 4] { + fn geometry_coefficients + Copy>( + &self, + temperature: D, + ) -> [DVector; 4] { match self.monomer_shape(temperature) { MonomerShape::Spherical(n) => { let m = DVector::from_element(n, D::from(1.0)); @@ -151,12 +157,22 @@ impl HardSphere { let zeta_23 = zeta[2] / zeta[3]; let density = state.partial_density.sum(); zeta.iter_mut().for_each(|z| *z *= density); + let a = Self::bmcsl_helmholtz_energy_density(zeta, zeta_23); + (a, zeta, diameter) + } + + /// The BMCSL Helmholtz energy density for given packing fractions $\zeta_k$ + /// and the (density independent) ratio $\zeta_2/\zeta_3$. + #[inline] + pub fn bmcsl_helmholtz_energy_density + Copy>( + zeta: [D; 4], + zeta_23: D, + ) -> D { let frac_1mz3 = -(zeta[3] - 1.0).recip(); - let a = (zeta[1] * zeta[2] * frac_1mz3 * 3.0 + (zeta[1] * zeta[2] * frac_1mz3 * 3.0 + zeta[2].powi(2) * frac_1mz3.powi(2) * zeta_23 + (zeta[2] * zeta_23.powi(2) - zeta[0]) * (-zeta[3]).ln_1p()) - / std::f64::consts::FRAC_PI_6; - (a, zeta, diameter) + / std::f64::consts::FRAC_PI_6 } #[inline] diff --git a/crates/feos/src/lib.rs b/crates/feos/src/lib.rs index 0fbdffa71..ad98bccee 100644 --- a/crates/feos/src/lib.rs +++ b/crates/feos/src/lib.rs @@ -44,6 +44,8 @@ pub mod hard_sphere; // models #[cfg(feature = "epcsaft")] pub mod epcsaft; +#[cfg(feature = "fcsaft")] +pub mod fcsaft; #[cfg(feature = "gc_pcsaft")] pub mod gc_pcsaft; #[cfg(feature = "multiparameter")] diff --git a/docs/api/ad.md b/docs/api/ad.md index 5aa52dd56..0890a186a 100644 --- a/docs/api/ad.md +++ b/docs/api/ad.md @@ -6,7 +6,7 @@ This section refers specifically to automatic (implicit) differentiation of phas Within Rust most phase equilibrium calculations can be used in an AD context, e.g., in order to calculate derivatives of process models (see [here](https://github.com/feos-org/feos-campd)). The Python interface focuses on the important use case of massively parallel phase equilibrium calculations for parameter estimation or prediction. ## Available equations of state -Only a subset of the models in FeOs can be used to calculate derivatives with respect to model parameters. However, those dedicated implementations also result in unprecedented performance (see example below). Similar to the [`EquationOfState`](eos.md#the-equationofstate-class) class, models with AD capabilities are collected in the `EquationOfStateAD` class. +Only a subset of the models in FeOs can be used to calculate derivatives with respect to model parameters. However, those dedicated implementations also result in unprecedented performance (see example below). Similar to the [`EquationOfState`](eos.md#the-equationofstate-class) class, models with AD capabilities are collected in the `EquationOfStateAD` class. The AD interface is enabled with the `ad` feature; the PC-SAFT and FC-SAFT variants are only available if the respective model features (`pcsaft`, `fcsaft`) are active as well. The currently available models are: @@ -14,6 +14,8 @@ The currently available models are: |-|-|-|-| |`PcSaftNonAssoc`|The PC-SAFT equation of state including a dipolar contribution but no association|`m`, `sigma`, `epsilon_k`, `mu`|`k_ij`| |`PcSaftFull`|The PC-SAFT equation of state with a dipolar contribution and association|`m`, `sigma`, `epsilon_k`, `mu`, `kappa_ab`, `epsilon_k_ab`, `na`, `nb`|`k_ij`| +|`FcSaftNonAssoc`|The (homosegmented) FC-SAFT equation of state including a dipolar contribution but no association|`s`, `l`, `sigma`, `epsilon_k`, `mu`|`k_ij`| +|`FcSaftFull`|The (homosegmented) FC-SAFT equation of state with a dipolar contribution and association|`s`, `l`, `sigma`, `epsilon_k`, `mu`, `kappa_ab`, `epsilon_k_ab`, `na`, `nb`|`k_ij`| ## Properties All properties that have parallel automatic differentiation with respect to model parameters enabled are available from the `Property` class diff --git a/docs/api/dft.md b/docs/api/dft.md index a99af7020..807722774 100644 --- a/docs/api/dft.md +++ b/docs/api/dft.md @@ -11,6 +11,7 @@ Implementations of Helmholtz energy functionals for DFT. .. autosummary:: HelmholtzEnergyFunctional.pcsaft HelmholtzEnergyFunctional.gc_pcsaft + HelmholtzEnergyFunctional.fcsaft HelmholtzEnergyFunctional.pets HelmholtzEnergyFunctional.saftvrqmie HelmholtzEnergyFunctional.fmt diff --git a/docs/api/eos.md b/docs/api/eos.md index 3683890bc..d1290aaf4 100644 --- a/docs/api/eos.md +++ b/docs/api/eos.md @@ -14,6 +14,7 @@ The `State` and `PhaseEquilibrium` objects are used to define thermodynamic cond EquationOfState.pcsaft EquationOfState.epcsaft EquationOfState.gc_pcsaft + EquationOfState.fcsaft EquationOfState.peng_robinson EquationOfState.pets EquationOfState.uvtheory diff --git a/docs/theory/models/fcsaft.md b/docs/theory/models/fcsaft.md new file mode 100644 index 000000000..db40a6dfc --- /dev/null +++ b/docs/theory/models/fcsaft.md @@ -0,0 +1,114 @@ +# FC-SAFT + +The fused-chain SAFT (FC-SAFT) equation of state describes molecules as chains of hard spheres that overlap ("fuse") with an explicit bond length. Compared to PC-SAFT, where the segments are tangent and the segment number $m$ is a (non-integer) model parameter, FC-SAFT uses an integer number of segments and treats the bond length $l$ as the parameter that determines the shape of the molecule. The reference fluid is the [fused-sphere chain model](https://doi.org/10.1103/PhysRevE.105.034110), and the dispersion contribution follows the structure of PC-SAFT ([Gross and Sadowski, 2001](https://doi.org/10.1021/ie0003887)). + +The residual Helmholtz energy is a sum of four contributions: + +$$A^\mathrm{res}=A^\mathrm{hs}+A^\mathrm{chain}+A^\mathrm{disp}+A^\mathrm{assoc}$$ + +$\text{FeO}_\text{s}$ provides two versions of the model: +- a **heterosegmented** (segment-based) model, in which every segment $\alpha$ has its own parameters $\sigma_\alpha$ and $\varepsilon_\alpha$, and the molecular structure is given by a bond graph with bond lengths $l_{\alpha\beta}$. Segments are distinguished by their position in the molecule, i.e., two segments of the same type can have different geometries depending on their neighbors. +- a **homosegmented** model, in which every molecule $i$ consists of $s_i$ identical segments in a linear chain with a single bond length $l_i$. This version additionally includes a dipolar contribution and is available as specialized implementations for pure components (`FcSaftPure`) and binary mixtures (`FcSaftBinary`) that support automatic differentiation with respect to model parameters. + +Crucially, the homosegmented version is mathematically identical to a heterosegmented molecule with uniform segment parameters and bond lengths. This sets FC-SAFT apart from PC-SAFT and SAFT-VR-Mie, because their heterosegmented counterparts (gc-PC-SAFT and SAFT-$\gamma$-Mie) do not simplify to the molecular equation of state for homosegmented chains. + +## Geometry of fused spheres + +Throughout the model, the temperature dependent segment diameter of PC-SAFT is used + +$$d_\alpha=\sigma_\alpha\left(1-0.12e^{\frac{-3\varepsilon_\alpha}{k_\mathrm{B}T}}\right)$$ + +Two bonded segments $\alpha$ and $\beta$ with a bond length $l_{\alpha\beta}<\frac{1}{2}(d_\alpha+d_\beta)$ overlap. The distance of the center of segment $\alpha$ to the plane of intersection is + +$$h_{\alpha\beta}=\frac{d_\alpha^2-d_\beta^2+4l_{\alpha\beta}^2}{8l_{\alpha\beta}}$$ + +Subtracting the spherical caps cut off by all bonded neighbors yields the reduced surface area $a_\alpha$ and the reduced volume $v_\alpha$ of every segment (relative to a free sphere) + +$$a_\alpha=1-\frac{1}{2}\sum_{\beta\in\mathcal{B}_\alpha}\left(1-\frac{2h_{\alpha\beta}}{d_\alpha}\right),~~~~v_\alpha=1-\frac{1}{2}\sum_{\beta\in\mathcal{B}_\alpha}\left(1-\frac{3h_{\alpha\beta}}{d_\alpha}+4\frac{h_{\alpha\beta}^3}{d_\alpha^3}\right)$$ + +where $\mathcal{B}_\alpha$ is the set of segments bonded to $\alpha$. For a homosegmented chain with $s_i$ segments and $\lambda_i=l_i/d_i$, the sums over all segments of a molecule simplify to + +$$m_i=\sum_{\alpha\in i}a_\alpha=1+\left(s_i-1\right)\lambda_i,~~~~m_i^*=\sum_{\alpha\in i}v_\alpha=1+\left(s_i-1\right)\frac{3\lambda_i-\lambda_i^3}{2}$$ + +For tangent spheres ($\lambda_i=1$), $m_i=m_i^*=s_i$ and the PC-SAFT geometry is recovered. + +## Reference fluid + +### Hard spheres + +The hard-sphere contribution is calculated from the generalized [BMCSL equation of state](hard_spheres.md) with the geometry coefficients $C_{0,\alpha}=1$, $C_{1,\alpha}=C_{2,\alpha}=a_\alpha$, and $C_{3,\alpha}=v_\alpha$, i.e., with the packing fractions + +$$\zeta_k=\frac{\pi}{6}\sum_\alpha\rho_\alpha C_{k,\alpha}d_\alpha^k$$ + +where $\rho_\alpha$ is the density of the molecule that contains segment $\alpha$. In the homosegmented model, the coefficients of the molecules are $s_i$, $m_i$, $m_i$, and $m_i^*$. + +### Fused-sphere chain + +The chain contribution is the TPT1 expression evaluated for every bond + +$$\frac{\beta A^\mathrm{chain}}{V}=-\sum_i\rho_i\sum_{\alpha\beta\in\mathcal{B}_i}\ln y_{\alpha\beta}$$ + +where the inner sum runs over all bonds of molecule $i$. The cavity correlation function at the bond length is + +$$y_{\alpha\beta}=\frac{1}{1-\zeta_3}+\frac{3}{2}\frac{b_{\alpha\beta}\zeta_2}{\left(1-\zeta_3\right)^2}+\frac{1}{2}\frac{b_{\alpha\beta}^2\zeta_2^2}{\left(1-\zeta_3\right)^3},~~~~b_{\alpha\beta}=\frac{4l_{\alpha\beta}^2-\left(d_\alpha-d_\beta\right)^2}{4l_{\alpha\beta}}$$ + +For tangent spheres, $b_{\alpha\beta}=\frac{2d_\alpha d_\beta}{d_\alpha+d_\beta}$ and the PC-SAFT chain term is recovered. In the homosegmented model, the sum reduces to $(s_i-1)\ln y_i$ with $b_i=l_i$. + +## Dispersion + +The dispersion contribution has the same structure as in PC-SAFT, but is evaluated for interactions between all segments + +$$\frac{\beta A^\mathrm{disp}}{V}=-\pi\sum_\alpha\sum_\beta\rho_\alpha\rho_\beta a_\alpha a_\beta\frac{\varepsilon_{\alpha\beta}}{k_\mathrm{B}T}\sigma_{\alpha\beta}^3\left(2I_1(\bar{m},\eta)+\bar{m}C_1I_2(\bar{m},\eta)\frac{\varepsilon_{\alpha\beta}}{k_\mathrm{B}T}\right)$$ + +with the combining rules + +$$\sigma_{\alpha\beta}=\frac{1}{2}\left(\sigma_\alpha+\sigma_\beta\right),~~~~\varepsilon_{\alpha\beta}=\sqrt{\varepsilon_\alpha\varepsilon_\beta}\left(1-k_{\alpha\beta}\right)$$ + +The reduced surface areas $a_\alpha$ weigh the interactions of the fused segments. The mean segment number is $\bar m=\sum_ix_im_i$ with $m_i=\sum_{\alpha\in i}a_\alpha$. The integrals $I_1$ and $I_2$ are power series in the packing fraction $\eta=\zeta_3$ + +$$I_1=\sum_{k=0}^6\left(a_{0k}+\frac{\bar m-1}{\bar m}a_{1k}+\frac{\bar m-1}{\bar m}\frac{\bar m-2}{\bar m}a_{2k}\right)\eta^k,~~~~I_2=\sum_{k=0}^6\left(b_{0k}+\frac{\bar m-1}{\bar m}b_{1k}+\frac{\bar m-1}{\bar m}\frac{\bar m-2}{\bar m}b_{2k}\right)\eta^k$$ + +The constants $a_{0k}$ and $b_{0k}$ are the PC-SAFT values, whereas $a_{1k}$, $a_{2k}$, $b_{1k}$, and $b_{2k}$ are adjusted to fused-sphere chains. + +In the homosegmented model, all segments of a molecule share the same parameters, so the sums over the segments of each molecule can be carried out explicitly with $\sum_{\alpha\in i}a_\alpha=m_i$. The double sum then runs over components + +$$\frac{\beta A^\mathrm{disp}}{V}=-\pi\sum_i\sum_j\rho_i\rho_jm_im_j\frac{\varepsilon_{ij}}{k_\mathrm{B}T}\sigma_{ij}^3\left(2I_1(\bar{m},\eta)+\bar{m}C_1I_2(\bar{m},\eta)\frac{\varepsilon_{ij}}{k_\mathrm{B}T}\right)$$ + +with $\bar m=\sum_ix_im_i$ and $\eta=\frac{\pi}{6}\sum_i\rho_im_i^*d_i^3$. + +### Compressibility term + +In PC-SAFT, the compressibility term $C_1$ is evaluated from a closed-form expression that is specific to tangent hard-sphere chains. For fused chains, the expression is not applicable. Instead, $C_1$ is calculated directly from its definition using the Helmholtz energy density of the reference fluid $\phi^\mathrm{ref}=\beta(A^\mathrm{hs}+A^\mathrm{chain})/V$ + +$$C_1=\left(\frac{\partial\left(\rho\left(1+Z^\mathrm{ref}\right)\right)}{\partial\rho}\right)_{T,x_i}^{-1}=\left(1+\rho\left(\frac{\partial^2\phi^\mathrm{ref}}{\partial\rho^2}\right)_{T,x_i}\right)^{-1}$$ + +The second derivative is calculated exactly using second-order dual numbers during the evaluation of the reference fluid, so that the Helmholtz energy of the reference fluid and $C_1$ are obtained in a single pass. + +## Association + +The association contribution uses the general expression described in the section on [association](association.md) with the PC-SAFT association strength + +$$\Delta^{\alpha\beta}=\left(\frac{1}{1-\zeta_3}+\frac{\frac{3}{2}d_{ij}\zeta_2}{\left(1-\zeta_3\right)^2}+\frac{\frac{1}{2}d_{ij}^2\zeta_2^2}{\left(1-\zeta_3\right)^3}\right)\sqrt{\sigma_i^3\kappa^\alpha\sigma_j^3\kappa^\beta}\left(e^{\frac{\varepsilon^\alpha+\varepsilon^\beta}{2k_\mathrm{B}T}}-1\right)$$ + +where the packing fractions $\zeta_2$ and $\zeta_3$ are those of the fused-sphere reference fluid. + +## Dipolar interactions + +The homosegmented model includes the dipolar contribution of [Gross and Vrabec (2006)](https://doi.org/10.1002/aic.10683) + +$$\frac{\beta A^\mathrm{dd}}{V}=\frac{\phi_2^\mathrm{dd}}{1-\phi_3^\mathrm{dd}/\phi_2^\mathrm{dd}}$$ + +The second- and third-order terms $\phi_2^\mathrm{dd}$ and $\phi_3^\mathrm{dd}$ are evaluated as in PC-SAFT with two adjustments to the fused-sphere geometry: the reduced dipole moment is defined using the reduced volume of the molecule + +$$\mu_i^{*2}=\frac{\mu_i^2}{m_i^*\varepsilon_i\sigma_i^3}$$ + +and the integrals $J_2$ and $J_3$ are evaluated with the packing fraction $\eta=\zeta_3$ and the reduced surface $m_i$ (limited to $m_i\leq2$) in place of the PC-SAFT segment number. + +## Helmholtz energy functional + +The heterosegmented model is also available as Helmholtz energy functional for inhomogeneous systems. Its contributions reduce to the equation of state for homogeneous systems. + +- **Hard spheres:** [fundamental measure theory](hard_spheres.md) with the geometry coefficients of the fused-sphere chain. +- **Chain:** the bulk expression with the segment densities $\rho_\alpha(\mathbf{r})$ and weighted densities $\bar\zeta_2$ and $\bar\zeta_3$ obtained from averaging over spheres with radius $d_\alpha$. Each bond is counted from both of its segments with a factor $\frac{1}{2}$. +- **Dispersion:** the bulk expression evaluated with segment densities that are averaged over spheres with radius $\psi_\alpha d_\alpha$. The default value is $\psi_\alpha=1.5$ and can be adjusted for every segment (`psi_dft`). The local mean segment number $\bar m$ and the compressibility term $C_1$ are evaluated from the local composition of the weighted densities, where $C_1$ is calculated exactly from the bulk reference fluid as described above. In the limit of vanishing density, $\bar m=1$ and $C_1=1$. +- **Association:** the functional of [Yu and Wu (2002)](https://doi.org/10.1063/1.1463435) in the formulation for heterosegmented molecules. diff --git a/docs/theory/models/hard_spheres.md b/docs/theory/models/hard_spheres.md index 26c2a278f..6c4cc73d6 100644 --- a/docs/theory/models/hard_spheres.md +++ b/docs/theory/models/hard_spheres.md @@ -17,8 +17,8 @@ The geometry coefficients $C_{k,\alpha}$ and the segment diameters $d_\alpha$ de |$d_\alpha$|$\sigma_\alpha$|$\sigma_\alpha\left(1-0.12e^{\frac{-3\varepsilon_\alpha}{k_\mathrm{B}T}}\right)$|$\sigma_\alpha$| |$C_{0,\alpha}$|$1$|$m_\alpha$|$1$| |$C_{1,\alpha}$|$1$|$m_\alpha$|$A_\alpha^*$| -|$C_{1,\alpha}$|$1$|$m_\alpha$|$A_\alpha^*$| -|$C_{1,\alpha}$|$1$|$m_\alpha$|$V_\alpha^*$| +|$C_{2,\alpha}$|$1$|$m_\alpha$|$A_\alpha^*$| +|$C_{3,\alpha}$|$1$|$m_\alpha$|$V_\alpha^*$| ## Fundamental measure theory diff --git a/docs/theory/models/index.md b/docs/theory/models/index.md index efccaf1cd..1ca9a46e1 100644 --- a/docs/theory/models/index.md +++ b/docs/theory/models/index.md @@ -9,4 +9,5 @@ It is currently still under construction. You can help by [contributing](https:/ hard_spheres association + fcsaft ``` \ No newline at end of file diff --git a/py-feos/Cargo.toml b/py-feos/Cargo.toml index 78e7844a4..2e88f04fb 100644 --- a/py-feos/Cargo.toml +++ b/py-feos/Cargo.toml @@ -47,6 +47,7 @@ default = [] dft = ["feos/dft", "feos-dft", "petgraph"] pcsaft = ["feos/pcsaft"] epcsaft = ["feos/epcsaft"] +fcsaft = ["feos/fcsaft"] gc_pcsaft = ["feos/gc_pcsaft"] uvtheory = ["feos/uvtheory"] pets = ["feos/pets"] @@ -57,12 +58,14 @@ multiparameter = ["feos/multiparameter"] rayon = ["dep:rayon", "ndarray/rayon", "feos-core/rayon", "feos-dft?/rayon"] # Loading parameters from a sqlite database. Not active for emscripten wheel. sqlite = ["feos-core/rusqlite"] -ad = ["feos/pcsaft"] +# AD interface for the models that support it (requires `pcsaft` and/or `fcsaft`). +ad = [] # EoS and DFT model implementations. all_models = [ "dft", "pcsaft", "epcsaft", + "fcsaft", "gc_pcsaft", "uvtheory", "pets", diff --git a/py-feos/src/ad/mod.rs b/py-feos/src/ad/mod.rs index b69238ec0..bc327dc8b 100644 --- a/py-feos/src/ad/mod.rs +++ b/py-feos/src/ad/mod.rs @@ -1,4 +1,7 @@ use crate::eos::PyEquationOfState; +#[cfg(feature = "fcsaft")] +use feos::fcsaft::{FcSaftBinary, FcSaftPure}; +#[cfg(feature = "pcsaft")] use feos::pcsaft::{PcSaftBinary, PcSaftPure}; use feos_core::ad::{ BoilingTemperature, BubblePointPressure, DewPointPressure, EnthalpyOfVaporization, @@ -17,20 +20,38 @@ pub use dataset::{PyBinaryDataset, PyPureDataset}; #[pyclass(name = "EquationOfStateAD", eq, eq_int, from_py_object)] #[derive(Clone, Copy, PartialEq)] pub enum PyEquationOfStateAD { + #[cfg(feature = "pcsaft")] PcSaftNonAssoc, + #[cfg(feature = "pcsaft")] PcSaftFull, + #[cfg(feature = "fcsaft")] + FcSaftNonAssoc, + #[cfg(feature = "fcsaft")] + FcSaftFull, } enum BinaryModels { + #[cfg(feature = "pcsaft")] PcSaftNonAssoc, + #[cfg(feature = "pcsaft")] PcSaftFull, + #[cfg(feature = "fcsaft")] + FcSaftNonAssoc, + #[cfg(feature = "fcsaft")] + FcSaftFull, } impl From for BinaryModels { fn from(value: PyEquationOfStateAD) -> Self { match value { + #[cfg(feature = "pcsaft")] PyEquationOfStateAD::PcSaftNonAssoc => Self::PcSaftNonAssoc, + #[cfg(feature = "pcsaft")] PyEquationOfStateAD::PcSaftFull => Self::PcSaftFull, + #[cfg(feature = "fcsaft")] + PyEquationOfStateAD::FcSaftNonAssoc => Self::FcSaftNonAssoc, + #[cfg(feature = "fcsaft")] + PyEquationOfStateAD::FcSaftFull => Self::FcSaftFull, } } } @@ -450,7 +471,7 @@ impl PyPropertyAD { } macro_rules! expand_models { - ($enum:ty, $prop:ident, $($model:ident: $type:ty),*) => { + ($enum:ty, $prop:ident, $($(#[$meta:meta])* $model:ident: $type:ty),*) => { paste!( #[pyfunction] fn [<_ $prop _derivatives>]<'py>( @@ -461,6 +482,7 @@ macro_rules! expand_models { ) -> GradResult<'py> { match <$enum>::from(model) { $( + $(#[$meta])* <$enum>::$model => { $prop::<$type>(parameter_names, parameters, input) })* @@ -476,8 +498,8 @@ macro_rules! impl_evaluate_gradients { (binary, [$($prop:ident: $prop_type:ty),*], $models:tt) => { $(impl_evaluate_gradients!(U2,BinaryModels,$prop,$prop_type,$models,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,max:15);)* }; - ($n:ty, $enum:ty, $prop:ident, $prop_type:ty, {$($model:ident: $type:ty),*}, $($p:literal,)* max: $max:literal) => { - expand_models!($enum, $prop, $($model: $type),*); + ($n:ty, $enum:ty, $prop:ident, $prop_type:ty, {$($(#[$meta:meta])* $model:ident: $type:ty),*}, $($p:literal,)* max: $max:literal) => { + expand_models!($enum, $prop, $($(#[$meta])* $model: $type),*); fn $prop<'py, R: ParametersAD<$n>>( parameter_names: &Bound<'py, PyAny>, parameters: &Bound<'py, PyAny>, @@ -526,11 +548,21 @@ macro_rules! impl_evaluate_gradients { impl_evaluate_gradients!( pure, [vapor_pressure: VaporPressure, boiling_temperature: BoilingTemperature, liquid_density: LiquidDensity, equilibrium_liquid_density: EquilibriumLiquidDensity, enthalpy_of_vaporization: EnthalpyOfVaporization, residual_isobaric_heat_capacity: ResidualIsobaricHeatCapacity], - {PcSaftNonAssoc: PcSaftPure, PcSaftFull: PcSaftPure} + { + #[cfg(feature = "pcsaft")] PcSaftNonAssoc: PcSaftPure, + #[cfg(feature = "pcsaft")] PcSaftFull: PcSaftPure, + #[cfg(feature = "fcsaft")] FcSaftNonAssoc: FcSaftPure, + #[cfg(feature = "fcsaft")] FcSaftFull: FcSaftPure + } ); impl_evaluate_gradients!( binary, [bubble_point_pressure: BubblePointPressure, dew_point_pressure: DewPointPressure], - {PcSaftNonAssoc: PcSaftBinary, PcSaftFull: PcSaftBinary} + { + #[cfg(feature = "pcsaft")] PcSaftNonAssoc: PcSaftBinary, + #[cfg(feature = "pcsaft")] PcSaftFull: PcSaftBinary, + #[cfg(feature = "fcsaft")] FcSaftNonAssoc: FcSaftBinary, + #[cfg(feature = "fcsaft")] FcSaftFull: FcSaftBinary + } ); diff --git a/py-feos/src/eos/fcsaft.rs b/py-feos/src/eos/fcsaft.rs new file mode 100644 index 000000000..1ae5afe7f --- /dev/null +++ b/py-feos/src/eos/fcsaft.rs @@ -0,0 +1,137 @@ +use super::PyEquationOfState; +#[cfg(feature = "dft")] +use crate::dft::{PyAssociationVersion, PyFMTVersion, PyHelmholtzEnergyFunctional}; +use crate::ideal_gas::IdealGasModel; +use crate::parameter::{PyGcParameters, PyParameters}; +use crate::residual::ResidualModel; +#[cfg(feature = "dft")] +use feos::fcsaft::FcSaftFunctional; +use feos::fcsaft::{FcSaft, FcSaftHomo, FcSaftOptions}; +use feos_core::{EquationOfState, ResidualDyn}; +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; +use std::sync::Arc; + +#[pymethods] +impl PyEquationOfState { + /// Fused-chain SAFT (FC-SAFT) equation of state. + /// + /// With `Parameters`, the homosegmented model is used, in which every + /// molecule consists of `s` identical segments with bond length `l` + /// (pure-component parameters `s`, `l`, `sigma`, `epsilon_k`, optionally + /// `mu` and association sites). This version includes a dipolar contribution. + /// With `GcParameters`, the heterosegmented model is used. + /// + /// Parameters + /// ---------- + /// parameters : Parameters | GcParameters + /// The parameters of the FC-SAFT equation of state to use. GcParameters + /// require bond records that specify the bond lengths between segments. + /// max_eta : float, optional + /// Maximum packing fraction. Defaults to 0.5. + /// max_iter_cross_assoc : unsigned integer, optional + /// Maximum number of iterations for cross association. Defaults to 50. + /// tol_cross_assoc : float + /// Tolerance for convergence of cross association. Defaults to 1e-10. + /// model_params : [[float]], optional + /// Model constants [a1, a2, b1, b2] (each with 7 entries) of the + /// dispersion contribution. Defaults to the FC-SAFT constants in feos. + /// + /// Returns + /// ------- + /// EquationOfState + /// The FC-SAFT equation of state that can be used to compute thermodynamic + /// states. + #[staticmethod] + #[pyo3( + signature = (parameters, max_eta=0.5, max_iter_cross_assoc=50, tol_cross_assoc=1e-10, model_params=None), + text_signature = "(parameters, max_eta=0.5, max_iter_cross_assoc=50, tol_cross_assoc=1e-10, model_params=None)" + )] + pub fn fcsaft( + parameters: &Bound<'_, PyAny>, + max_eta: f64, + max_iter_cross_assoc: usize, + tol_cross_assoc: f64, + model_params: Option<[[f64; 7]; 4]>, + ) -> PyResult { + let options = FcSaftOptions { + max_eta, + max_iter_cross_assoc, + tol_cross_assoc, + }; + let residual = if let Ok(parameters) = parameters.extract::() { + ResidualModel::FcSaftHomo(FcSaftHomo::with_options( + parameters.try_convert()?, + options, + model_params, + )) + } else if let Ok(parameters) = parameters.extract::() { + ResidualModel::FcSaft(FcSaft::with_options( + parameters.try_convert_heterosegmented_with_bonds()?, + options, + model_params, + )) + } else { + return Err(PyErr::new::( + "Argument `parameters` must be Parameters or GcParameters", + )); + }; + let ideal_gas = vec![IdealGasModel::NoModel; residual.components()]; + Ok(Self(Arc::new(EquationOfState::new(ideal_gas, residual)))) + } +} + +#[cfg(feature = "dft")] +#[pymethods] +impl PyHelmholtzEnergyFunctional { + /// (heterosegmented) fused-chain SAFT (FC-SAFT) Helmholtz energy functional. + /// + /// Parameters + /// ---------- + /// parameters: GcParameters + /// The set of FC-SAFT parameters. Requires bond records that specify + /// the bond lengths between segments. + /// fmt_version: FMTVersion, optional + /// The specific variant of the FMT term. Defaults to FMTVersion.WhiteBear + /// association_version: AssociationVersion, optional + /// The version of the association functional. Defaults to AssociationVersion.ISaft + /// max_eta : float, optional + /// Maximum packing fraction. Defaults to 0.5. + /// max_iter_cross_assoc : unsigned integer, optional + /// Maximum number of iterations for cross association. Defaults to 50. + /// tol_cross_assoc : float + /// Tolerance for convergence of cross association. Defaults to 1e-10. + /// + /// Returns + /// ------- + /// HelmholtzEnergyFunctional + #[staticmethod] + #[pyo3( + signature = (parameters, fmt_version=PyFMTVersion::WhiteBear, association_version=PyAssociationVersion::ISaft, max_eta=0.5, max_iter_cross_assoc=50, tol_cross_assoc=1e-10), + text_signature = "(parameters, fmt_version=FMTVersion.WhiteBear, association_version=AssociationVersion.ISaft, max_eta=0.5, max_iter_cross_assoc=50, tol_cross_assoc=1e-10)" + )] + fn fcsaft( + parameters: PyGcParameters, + fmt_version: PyFMTVersion, + association_version: PyAssociationVersion, + max_eta: f64, + max_iter_cross_assoc: usize, + tol_cross_assoc: f64, + ) -> PyResult { + let options = FcSaftOptions { + max_eta, + max_iter_cross_assoc, + tol_cross_assoc, + }; + let func = ResidualModel::FcSaftFunctional(FcSaftFunctional::with_options( + parameters.try_convert_heterosegmented_with_bonds()?, + fmt_version.into(), + association_version.into(), + options, + )); + let ideal_gas = vec![IdealGasModel::NoModel; func.components()]; + Ok(PyEquationOfState(Arc::new(EquationOfState::new( + ideal_gas, func, + )))) + } +} diff --git a/py-feos/src/eos/mod.rs b/py-feos/src/eos/mod.rs index 0bc7f1a00..f6ab6263a 100644 --- a/py-feos/src/eos/mod.rs +++ b/py-feos/src/eos/mod.rs @@ -15,6 +15,8 @@ type Quot = >::Output; mod constructors; #[cfg(feature = "epcsaft")] mod epcsaft; +#[cfg(feature = "fcsaft")] +mod fcsaft; #[cfg(feature = "gc_pcsaft")] mod gc_pcsaft; #[cfg(feature = "multiparameter")] diff --git a/py-feos/src/lib.rs b/py-feos/src/lib.rs index bad32f52d..e35660661 100644 --- a/py-feos/src/lib.rs +++ b/py-feos/src/lib.rs @@ -3,7 +3,9 @@ use feos_core::Verbosity; use pyo3::prelude::*; -#[cfg(feature = "ad")] +#[cfg(all(feature = "ad", not(any(feature = "pcsaft", feature = "fcsaft"))))] +compile_error!("The `ad` feature requires at least one of the features `pcsaft` and `fcsaft`."); +#[cfg(all(feature = "ad", any(feature = "pcsaft", feature = "fcsaft")))] pub(crate) mod ad; #[cfg(feature = "dft")] pub(crate) mod dft; @@ -180,7 +182,7 @@ fn feos(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; // AD - #[cfg(feature = "ad")] + #[cfg(all(feature = "ad", any(feature = "pcsaft", feature = "fcsaft")))] { m.add_class::()?; m.add_class::()?; diff --git a/py-feos/src/parameter/mod.rs b/py-feos/src/parameter/mod.rs index 3905adae5..78adcef43 100644 --- a/py-feos/src/parameter/mod.rs +++ b/py-feos/src/parameter/mod.rs @@ -564,6 +564,8 @@ pub struct PyGcParameters { chemical_records: Vec, segment_records: Vec>, binary_segment_records: Option>>, + #[serde(default, skip_serializing_if = "Option::is_none")] + bond_records: Option>>, } impl PyGcParameters { @@ -623,6 +625,48 @@ impl PyGcParameters { ) .map_err(PyFeosError::from)?) } + + #[cfg(feature = "fcsaft")] + pub fn try_convert_heterosegmented_with_bonds( + self, + ) -> PyResult> + where + for<'de> P: Deserialize<'de> + Clone, + for<'de> B: Deserialize<'de> + Clone, + for<'de> A: Deserialize<'de> + CombiningRule

+ Clone, + for<'de> Bo: Deserialize<'de> + Clone, + { + let Some(bond_records) = self.bond_records else { + return Err(PyFeosError::Error( + "The model requires bond records, but none were provided.".to_string(), + ) + .into()); + }; + let segment_records = self + .segment_records + .into_iter() + .map(|r| Ok(serde_json::from_value(serde_json::to_value(r)?)?)) + .collect::, PyFeosError>>()?; + let binary_segment_records = self + .binary_segment_records + .map(|bsr| { + bsr.into_iter() + .map(|r| Ok(serde_json::from_value(serde_json::to_value(r)?)?)) + .collect::, PyFeosError>>() + }) + .transpose()?; + let bond_records = bond_records + .into_iter() + .map(|r| Ok(serde_json::from_value(serde_json::to_value(r)?)?)) + .collect::, PyFeosError>>()?; + Ok(GcParameters::::from_segments_with_bonds( + self.chemical_records, + &segment_records, + binary_segment_records.as_deref(), + &bond_records, + ) + .map_err(PyFeosError::from)?) + } } #[pymethods] @@ -638,22 +682,28 @@ impl PyGcParameters { /// all individual segments. /// binary_segment_records : [BinarySegmentRecord], optional /// A list of binary segment-segment parameters. + /// bond_records : [BinarySegmentRecord], optional + /// A list of bond parameters (e.g., bond lengths) for models that + /// require them. #[staticmethod] - #[pyo3(text_signature = "(chemical_records, segment_records, binary_segment_records=None)", - signature = (chemical_records, segment_records, binary_segment_records=None))] + #[pyo3(text_signature = "(chemical_records, segment_records, binary_segment_records=None, bond_records=None)", + signature = (chemical_records, segment_records, binary_segment_records=None, bond_records=None))] fn from_segments( chemical_records: Vec, segment_records: Vec, binary_segment_records: Option>, + bond_records: Option>, ) -> Self { let chemical_records = chemical_records.into_iter().map(|r| r.into()).collect(); let segment_records = segment_records.into_iter().map(|r| r.into()).collect(); let binary_segment_records = binary_segment_records.map(|bsr| bsr.into_iter().map(|r| r.into()).collect()); + let bond_records = bond_records.map(|br| br.into_iter().map(|r| r.into()).collect()); Self { chemical_records, segment_records, binary_segment_records, + bond_records, } } @@ -671,10 +721,13 @@ impl PyGcParameters { /// Path to file containing binary segment-segment parameters. /// identifier_option : IdentifierOption, optional, defaults to IdentifierOption.Name /// Identifier that is used to search substance. + /// bonds_path : str, optional + /// Path to file containing bond parameters (e.g., bond lengths) for + /// models that require them. #[staticmethod] #[pyo3( - signature = (substances, pure_path, segments_path, binary_path=None, identifier_option=PyIdentifierOption::Name), - text_signature = "(substances, pure_path, segments_path, binary_path=None, identifier_option=IdentiferOption.Name)" + signature = (substances, pure_path, segments_path, binary_path=None, identifier_option=PyIdentifierOption::Name, bonds_path=None), + text_signature = "(substances, pure_path, segments_path, binary_path=None, identifier_option=IdentiferOption.Name, bonds_path=None)" )] fn from_json_segments( substances: Vec, @@ -682,6 +735,7 @@ impl PyGcParameters { segments_path: &str, binary_path: Option<&str>, identifier_option: PyIdentifierOption, + bonds_path: Option<&str>, ) -> PyResult { let chemical_records = PyChemicalRecord::from_json(substances, pure_path, identifier_option)?; @@ -694,10 +748,18 @@ impl PyGcParameters { }) .transpose() .map_err(PyFeosError::from)?; + let bond_records = bonds_path + .map(|p| { + BinarySegmentRecord::from_json(p) + .map(|brs| brs.into_iter().map(|r| r.into()).collect()) + }) + .transpose() + .map_err(PyFeosError::from)?; Ok(Self::from_segments( chemical_records, segment_records, binary_segment_records, + bond_records, )) } @@ -736,6 +798,7 @@ impl PyGcParameters { chemical_records, segment_records, binary_segment_records, + None, )) } diff --git a/py-feos/src/residual.rs b/py-feos/src/residual.rs index db9ae8130..9f7a0583d 100644 --- a/py-feos/src/residual.rs +++ b/py-feos/src/residual.rs @@ -35,6 +35,14 @@ pub enum ResidualModel { #[implement(molar_weight)] GcPcSaft(feos::gc_pcsaft::GcPcSaft), + #[cfg(feature = "fcsaft")] + #[implement(molar_weight)] + FcSaft(feos::fcsaft::FcSaft), + + #[cfg(feature = "fcsaft")] + #[implement(molar_weight)] + FcSaftHomo(feos::fcsaft::FcSaftHomo), + #[implement(molar_weight, parameter_info)] PengRobinson(PengRobinson), @@ -77,6 +85,10 @@ pub enum ResidualModel { #[implement(molar_weight, functional, bond_lengths, association, fluid_parameters)] GcPcSaftFunctional(feos::gc_pcsaft::GcPcSaftFunctional), + #[cfg(all(feature = "dft", feature = "fcsaft"))] + #[implement(molar_weight, functional, bond_lengths, association, fluid_parameters)] + FcSaftFunctional(feos::fcsaft::FcSaftFunctional), + #[cfg(all(feature = "dft", feature = "pets"))] #[implement( molar_weight, @@ -109,6 +121,8 @@ pub enum FunctionalContributionVariant<'a> { PcSaftFunctional(feos::pcsaft::PcSaftFunctionalContribution<'a>), #[cfg(feature = "gc_pcsaft")] GcPcSaftFunctional(feos::gc_pcsaft::GcPcSaftFunctionalContribution<'a>), + #[cfg(feature = "fcsaft")] + FcSaftFunctional(feos::fcsaft::FcSaftFunctionalContribution<'a>), #[cfg(feature = "pets")] PetsFunctional(feos::pets::PetsFunctionalContribution<'a>), Fmt(feos::hard_sphere::FMTContribution<'a, feos::hard_sphere::HardSphereParameters>),