keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
feos-org/feos
crates/feos-core/src/phase_equilibria/mod.rs
.rs
7,362
243
use crate::equation_of_state::Residual; use crate::errors::{FeosError, FeosResult}; use crate::state::{DensityInitialization, State}; use crate::{Contributions, ReferenceSystem}; use nalgebra::allocator::Allocator; use nalgebra::{DVector, DefaultAllocator, Dim, Dyn, OVector}; use num_dual::{DualNum, DualStruct}; use quantity::{Energy, Moles, Pressure, RGAS, Temperature}; use std::fmt; use std::fmt::Write; mod bubble_dew; #[cfg(feature = "ndarray")] mod phase_diagram_binary; #[cfg(feature = "ndarray")] mod phase_diagram_pure; #[cfg(feature = "ndarray")] mod phase_envelope; mod stability_analysis; mod tp_flash; mod vle_pure; pub use bubble_dew::TemperatureOrPressure; #[cfg(feature = "ndarray")] pub use phase_diagram_binary::PhaseDiagramHetero; #[cfg(feature = "ndarray")] pub use phase_diagram_pure::PhaseDiagram; /// A thermodynamic equilibrium state. /// /// The struct is parametrized over the number of phases with most features /// being implemented for the two phase vapor/liquid or liquid/liquid case. /// /// ## Contents /// /// + [Bubble and dew point calculations](#bubble-and-dew-point-calculations) /// + [Heteroazeotropes](#heteroazeotropes) /// + [Flash calculations](#flash-calculations) /// + [Pure component phase equilibria](#pure-component-phase-equilibria) /// + [Utility functions](#utility-functions) #[derive(Debug, Clone)] pub struct PhaseEquilibrium<E, const P: usize, N: Dim = Dyn, D: DualNum<f64> + Copy = f64>( pub [State<E, N, D>; P], ) where DefaultAllocator: Allocator<N>; // impl<E, const P: usize> Clone for PhaseEquilibrium<E, P> { // fn clone(&self) -> Self { // Self(self.0.clone()) // } // } impl<E: Residual, const P: usize> fmt::Display for PhaseEquilibrium<E, P> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for (i, s) in self.0.iter().enumerate() { writeln!(f, "phase {i}: {s}")?; } Ok(()) } } impl<E: Residual, const P: usize> PhaseEquilibrium<E, P> { pub fn _repr_markdown_(&self) -> String { if self.0[0].eos.components() == 1 { let mut res = "||temperature|density|\n|-|-|-|\n".to_string(); for (i, s) in self.0.iter().enumerate() { writeln!( res, "|phase {}|{:.5}|{:.5}|", i + 1, s.temperature, s.density ) .unwrap(); } res } else { let mut res = "||temperature|density|molefracs|\n|-|-|-|-|\n".to_string(); for (i, s) in self.0.iter().enumerate() { writeln!( res, "|phase {}|{:.5}|{:.5}|{:.5?}|", i + 1, s.temperature, s.density, s.molefracs.as_slice() ) .unwrap(); } res } } } impl<E: Residual<N, D>, N: Dim, D: DualNum<f64> + Copy> PhaseEquilibrium<E, 2, N, D> where DefaultAllocator: Allocator<N>, { pub fn vapor(&self) -> &State<E, N, D> { &self.0[0] } pub fn liquid(&self) -> &State<E, N, D> { &self.0[1] } } impl<E> PhaseEquilibrium<E, 3> { pub fn vapor(&self) -> &State<E> { &self.0[0] } pub fn liquid1(&self) -> &State<E> { &self.0[1] } pub fn liquid2(&self) -> &State<E> { &self.0[2] } } impl<E: Residual<N>, N: Dim> PhaseEquilibrium<E, 2, N> where DefaultAllocator: Allocator<N>, { pub(super) fn from_states(state1: State<E, N>, state2: State<E, N>) -> Self { let (vapor, liquid) = if state1.density.re() < state2.density.re() { (state1, state2) } else { (state2, state1) }; Self([vapor, liquid]) } /// Creates a new PhaseEquilibrium that contains two states at the /// specified temperature, pressure and molefracs. /// /// The constructor can be used in custom phase equilibrium solvers or, /// e.g., to generate initial guesses for an actual VLE solver. /// In general, the two states generated are NOT in an equilibrium. pub fn new_xpt( eos: &E, temperature: Temperature, pressure: Pressure, vapor_molefracs: &OVector<f64, N>, liquid_molefracs: &OVector<f64, N>, ) -> FeosResult<Self> { let liquid = State::new_xpt( eos, temperature, pressure, liquid_molefracs, Some(DensityInitialization::Liquid), )?; let vapor = State::new_xpt( eos, temperature, pressure, vapor_molefracs, Some(DensityInitialization::Vapor), )?; Ok(Self([vapor, liquid])) } pub(super) fn vapor_phase_fraction(&self) -> f64 { (self.vapor().total_moles / (self.vapor().total_moles + self.liquid().total_moles)) .into_value() } } impl<E: Residual, const P: usize> PhaseEquilibrium<E, P> { pub(super) fn update_pressure( mut self, temperature: Temperature, pressure: Pressure, ) -> FeosResult<Self> { for s in self.0.iter_mut() { *s = State::new_npt( &s.eos, temperature, pressure, &s.moles, Some(DensityInitialization::InitialDensity(s.density)), )?; } Ok(self) } pub(super) fn update_moles( &mut self, pressure: Pressure, moles: [&Moles<DVector<f64>>; P], ) -> FeosResult<()> { for (i, s) in self.0.iter_mut().enumerate() { *s = State::new_npt( &s.eos, s.temperature, pressure, moles[i], Some(DensityInitialization::InitialDensity(s.density)), )?; } Ok(()) } // Total Gibbs energy excluding the constant contribution RT sum_i N_i ln(\Lambda_i^3) pub(super) fn total_gibbs_energy(&self) -> Energy { self.0.iter().fold(Energy::from_reduced(0.0), |acc, s| { let ln_rho_m1 = s.partial_density.to_reduced().map(|r| r.ln() - 1.0); acc + s.residual_helmholtz_energy() + s.pressure(Contributions::Total) * s.volume + RGAS * s.temperature * s.total_moles * s.molefracs.dot(&ln_rho_m1) }) } } const TRIVIAL_REL_DEVIATION: f64 = 1e-5; /// # Utility functions impl<E: Residual<N>, N: Dim> PhaseEquilibrium<E, 2, N> where DefaultAllocator: Allocator<N>, { pub(super) fn check_trivial_solution(self) -> FeosResult<Self> { if Self::is_trivial_solution(self.vapor(), self.liquid()) { Err(FeosError::TrivialSolution) } else { Ok(self) } } /// Check if the two states form a trivial solution pub fn is_trivial_solution(state1: &State<E, N>, state2: &State<E, N>) -> bool { let rho1 = state1.molefracs.clone() * state1.density.into_reduced(); let rho2 = state2.molefracs.clone() * state2.density.into_reduced(); rho1.into_iter() .zip(&rho2) .fold(0.0, |acc, (rho1, rho2)| (rho2 / rho1 - 1.0).abs().max(acc)) < TRIVIAL_REL_DEVIATION } }
Rust
3D
feos-org/feos
crates/feos-core/src/phase_equilibria/bubble_dew.rs
.rs
30,455
933
use crate::errors::{FeosError, FeosResult}; use crate::phase_equilibria::PhaseEquilibrium; use crate::state::{ Contributions, DensityInitialization::{InitialDensity, Liquid, Vapor}, }; use crate::{ReferenceSystem, Residual, SolverOptions, State, Verbosity}; use nalgebra::allocator::Allocator; use nalgebra::{DMatrix, DVector, DefaultAllocator, Dim, Dyn, OVector, U1}; #[cfg(feature = "ndarray")] use ndarray::Array1; use num_dual::linalg::LU; use num_dual::{DualNum, DualStruct, Gradients}; use quantity::{Density, Dimensionless, Moles, Pressure, Quantity, RGAS, SIUnit, Temperature}; const MAX_ITER_INNER: usize = 5; const TOL_INNER: f64 = 1e-9; const MAX_ITER_OUTER: usize = 400; const TOL_OUTER: f64 = 1e-10; const MAX_TSTEP: f64 = 20.0; const MAX_LNPSTEP: f64 = 0.1; const NEWTON_TOL: f64 = 1e-3; /// Trait that enables functions to be generic over their input unit. pub trait TemperatureOrPressure<D: DualNum<f64> + Copy = f64>: Copy { type Other: Copy; const IDENTIFIER: &'static str; fn temperature(&self) -> Option<Temperature<D>>; fn pressure(&self) -> Option<Pressure<D>>; fn temperature_pressure( &self, tp_init: Option<Self::Other>, ) -> (Option<Temperature<D>>, Option<Pressure<D>>, bool); fn from_state<E: Residual<N, D>, N: Gradients>(state: &State<E, N, D>) -> Self::Other where DefaultAllocator: Allocator<N>; #[cfg(feature = "ndarray")] fn linspace( &self, start: Self::Other, end: Self::Other, n: usize, ) -> (Temperature<Array1<f64>>, Pressure<Array1<f64>>); } impl<D: DualNum<f64> + Copy> TemperatureOrPressure<D> for Temperature<D> { type Other = Pressure<D>; const IDENTIFIER: &'static str = "temperature"; fn temperature(&self) -> Option<Temperature<D>> { Some(*self) } fn pressure(&self) -> Option<Pressure<D>> { None } fn temperature_pressure( &self, tp_init: Option<Self::Other>, ) -> (Option<Temperature<D>>, Option<Pressure<D>>, bool) { (Some(*self), tp_init, true) } fn from_state<E: Residual<N, D>, N: Gradients>(state: &State<E, N, D>) -> Self::Other where DefaultAllocator: Allocator<N>, { state.pressure(Contributions::Total) } #[cfg(feature = "ndarray")] fn linspace( &self, start: Pressure<D>, end: Pressure<D>, n: usize, ) -> (Temperature<Array1<f64>>, Pressure<Array1<f64>>) { ( Temperature::linspace(self.re(), self.re(), n), Pressure::linspace(start.re(), end.re(), n), ) } } // For some inexplicable reason this does not compile if the `Pressure` type is // used instead of the explicit unit. Maybe the type is too complicated for the // compiler? impl<D: DualNum<f64> + Copy> TemperatureOrPressure<D> for Quantity<D, SIUnit<-2, -1, 1, 0, 0, 0, 0>> { type Other = Temperature<D>; const IDENTIFIER: &'static str = "pressure"; fn temperature(&self) -> Option<Temperature<D>> { None } fn pressure(&self) -> Option<Pressure<D>> { Some(*self) } fn temperature_pressure( &self, tp_init: Option<Self::Other>, ) -> (Option<Temperature<D>>, Option<Pressure<D>>, bool) { (tp_init, Some(*self), false) } fn from_state<E: Residual<N, D>, N: Dim>(state: &State<E, N, D>) -> Self::Other where DefaultAllocator: Allocator<N>, { state.temperature } #[cfg(feature = "ndarray")] fn linspace( &self, start: Temperature<D>, end: Temperature<D>, n: usize, ) -> (Temperature<Array1<f64>>, Pressure<Array1<f64>>) { ( Temperature::linspace(start.re(), end.re(), n), Pressure::linspace(self.re(), self.re(), n), ) } } /// # Bubble and dew point calculations impl<E: Residual<N, D>, N: Gradients, D: DualNum<f64> + Copy> PhaseEquilibrium<E, 2, N, D> where DefaultAllocator: Allocator<N> + Allocator<N, N> + Allocator<U1, N>, { /// Calculate a phase equilibrium for a given temperature /// or pressure and composition of the liquid phase. pub fn bubble_point<TP: TemperatureOrPressure<D>>( eos: &E, temperature_or_pressure: TP, liquid_molefracs: &OVector<D, N>, tp_init: Option<TP::Other>, vapor_molefracs: Option<&OVector<f64, N>>, options: (SolverOptions, SolverOptions), ) -> FeosResult<Self> { Self::bubble_dew_point( eos, temperature_or_pressure, liquid_molefracs, tp_init, vapor_molefracs, true, options, ) } /// Calculate a phase equilibrium for a given temperature /// or pressure and composition of the vapor phase. pub fn dew_point<TP: TemperatureOrPressure<D>>( eos: &E, temperature_or_pressure: TP, vapor_molefracs: &OVector<D, N>, tp_init: Option<TP::Other>, liquid_molefracs: Option<&OVector<f64, N>>, options: (SolverOptions, SolverOptions), ) -> FeosResult<Self> { Self::bubble_dew_point( eos, temperature_or_pressure, vapor_molefracs, tp_init, liquid_molefracs, false, options, ) } pub(super) fn bubble_dew_point<TP: TemperatureOrPressure<D>>( eos: &E, temperature_or_pressure: TP, vapor_molefracs: &OVector<D, N>, tp_init: Option<TP::Other>, liquid_molefracs: Option<&OVector<f64, N>>, bubble: bool, options: (SolverOptions, SolverOptions), ) -> FeosResult<Self> { let (temperature, pressure, iterate_p) = temperature_or_pressure.temperature_pressure(tp_init); Self::bubble_dew_point_tp( eos, temperature, pressure, vapor_molefracs, liquid_molefracs, bubble, iterate_p, options, ) } #[expect(clippy::too_many_arguments)] fn bubble_dew_point_tp( eos: &E, temperature: Option<Temperature<D>>, pressure: Option<Pressure<D>>, molefracs_spec: &OVector<D, N>, molefracs_init: Option<&OVector<f64, N>>, bubble: bool, iterate_p: bool, options: (SolverOptions, SolverOptions), ) -> FeosResult<Self> { let eos_re = eos.re(); let mut temperature_re = temperature.map(|t| t.re()); let mut pressure_re = pressure.map(|p| p.re()); let molefracs_spec_re = molefracs_spec.map(|x| x.re()); let (v1, rho2) = if iterate_p { // temperature is specified let temperature_re = temperature_re.as_mut().unwrap(); // First use given initial pressure if applicable if let Some(p) = pressure_re.as_mut() { PhaseEquilibrium::iterate_bubble_dew( &eos_re, temperature_re, p, &molefracs_spec_re, molefracs_init, bubble, iterate_p, options, )? } else { // Next try to initialize with an ideal gas assumption let x2 = PhaseEquilibrium::starting_pressure_ideal_gas( &eos_re, *temperature_re, &molefracs_spec_re, bubble, ) .and_then(|(p, x)| { pressure_re = Some(p); PhaseEquilibrium::iterate_bubble_dew( &eos_re, temperature_re, pressure_re.as_mut().unwrap(), &molefracs_spec_re, molefracs_init.or(Some(&x)), bubble, iterate_p, options, ) }); // Finally use the spinodal to initialize the calculation x2.or_else(|_| { PhaseEquilibrium::starting_pressure_spinodal( &eos_re, *temperature_re, &molefracs_spec_re, ) .and_then(|p| { pressure_re = Some(p); PhaseEquilibrium::iterate_bubble_dew( &eos_re, temperature_re, pressure_re.as_mut().unwrap(), &molefracs_spec_re, molefracs_init, bubble, iterate_p, options, ) }) })? } } else { // pressure is specified let pressure_re = pressure_re.as_mut().unwrap(); let temperature_re = temperature_re.as_mut().expect("An initial temperature is required for the calculation of bubble/dew points at given pressure!"); PhaseEquilibrium::iterate_bubble_dew( &eos.re(), temperature_re, pressure_re, &molefracs_spec_re, molefracs_init, bubble, iterate_p, options, )? }; // implicit differentiation let mut t = D::from(temperature_re.unwrap().into_reduced()); let mut p = D::from(pressure_re.unwrap().into_reduced()); let mut molar_volume = D::from(v1); let mut rho2 = rho2.map(D::from); for _ in 0..D::NDERIV { if iterate_p { Self::newton_step_t( eos, t, molefracs_spec, &mut p, &mut molar_volume, &mut rho2, Verbosity::None, ) } else { Self::newton_step_p( eos, &mut t, molefracs_spec, p, &mut molar_volume, &mut rho2, Verbosity::None, ) }; } let state1 = State::new_intensive( eos, Temperature::from_reduced(t), Density::from_reduced(molar_volume.recip()), molefracs_spec, )?; let rho2_total = rho2.sum(); let x2 = rho2 / rho2_total; let state2 = State::new_intensive( eos, Temperature::from_reduced(t), Density::from_reduced(rho2_total), &x2, )?; Ok(PhaseEquilibrium(if bubble { [state2, state1] } else { [state1, state2] })) } fn newton_step_t( eos: &E, temperature: D, molefracs: &OVector<D, N>, pressure: &mut D, molar_volume: &mut D, partial_density_other_phase: &mut OVector<D, N>, verbosity: Verbosity, ) -> f64 { // calculate properties let (p_1, mu_res_1, dp_1, dmu_1) = eos.dmu_drho(temperature, partial_density_other_phase); let (p_2, mu_res_2, dp_2, dmu_2) = eos.dmu_dv(temperature, *molar_volume, molefracs); // calculate residual let n = molefracs.len(); let f = DVector::from_fn(n + 2, |i, _| { if i == n { p_1 - *pressure } else if i == n + 1 { p_2 - *pressure } else { mu_res_1[i] - mu_res_2[i] + (partial_density_other_phase[i] * *molar_volume / molefracs[i]).ln() * temperature } }); // calculate Jacobian let jac = DMatrix::from_fn(n + 2, n + 2, |i, j| { if i < n && j < n { dmu_1[(i, j)] } else if i < n && j == n { -dmu_2[i] } else if i == n && j < n { dp_1[j] } else if i == n + 1 && j == n { dp_2 } else if i >= n && j == n + 1 { -D::one() } else { D::zero() } }); // calculate Newton step let dx = LU::<_, _, Dyn>::new(jac).unwrap().solve(&f); // apply Newton step for i in 0..n { partial_density_other_phase[i] -= dx[i]; } *molar_volume -= dx[n]; *pressure -= dx[n + 1]; let error = f.map(|r| r.re()).norm(); let x = partial_density_other_phase.map(|r| r.re()); let x = &x / x.sum(); log_iteration( verbosity, Some(error), Temperature::from_reduced(temperature.re()), Pressure::from_reduced(pressure.re()), x.as_slice(), true, ); error } fn newton_step_p( eos: &E, temperature: &mut D, molefracs: &OVector<D, N>, pressure: D, molar_volume: &mut D, partial_density_other_phase: &mut OVector<D, N>, verbosity: Verbosity, ) -> f64 { // calculate properties let (p_1, mu_res_1, dp_1, dmu_1) = eos.dmu_drho(*temperature, partial_density_other_phase); let (p_2, mu_res_2, dp_2, dmu_2) = eos.dmu_dv(*temperature, *molar_volume, molefracs); let (dp_dt_1, dmu_res_dt_1) = eos.dmu_dt(*temperature, partial_density_other_phase); let (dp_dt_2, dmu_res_dt_2) = eos.dmu_dt(*temperature, &(molefracs / *molar_volume)); // calculate residual let n = molefracs.len(); let f = DVector::from_fn(n + 2, |i, _| { if i == n { p_1 - pressure } else if i == n + 1 { p_2 - pressure } else { mu_res_1[i] - mu_res_2[i] + (partial_density_other_phase[i] * *molar_volume / molefracs[i]).ln() * *temperature } }); // calculate Jacobian let jac = DMatrix::from_fn(n + 2, n + 2, |i, j| { if i < n && j < n { dmu_1[(i, j)] } else if i < n && j == n { -dmu_2[i] } else if i < n && j == n + 1 { dmu_res_dt_1[i] - dmu_res_dt_2[i] + (partial_density_other_phase[i] * *molar_volume / molefracs[i]).ln() } else if i == n && j < n { dp_1[j] } else if i == n && j == n + 1 { dp_dt_1 } else if i == n + 1 && j == n { dp_2 } else if i == n + 1 && j == n + 1 { dp_dt_2 } else { D::zero() } }); // calculate Newton step let dx = LU::<_, _, Dyn>::new(jac).unwrap().solve(&f); // apply Newton step for i in 0..n { partial_density_other_phase[i] -= dx[i]; } *molar_volume -= dx[n]; *temperature -= dx[n + 1]; let error = f.map(|r| r.re()).norm(); let x = partial_density_other_phase.map(|r| r.re()); let x = &x / x.sum(); log_iteration( verbosity, Some(error), Temperature::from_reduced(temperature.re()), Pressure::from_reduced(pressure.re()), x.as_slice(), true, ); error } } /// # Bubble and dew point calculations impl<E: Residual<N>, N: Gradients> PhaseEquilibrium<E, 2, N> where DefaultAllocator: Allocator<N> + Allocator<N, N> + Allocator<U1, N>, { #[expect(clippy::too_many_arguments)] fn iterate_bubble_dew( eos: &E, temperature: &mut Temperature, pressure: &mut Pressure, molefracs_spec: &OVector<f64, N>, molefracs_init: Option<&OVector<f64, N>>, bubble: bool, iterate_p: bool, options: (SolverOptions, SolverOptions), ) -> FeosResult<(f64, OVector<f64, N>)> { let [mut state1, mut state2] = if bubble { Self::starting_x2_bubble(eos, *temperature, *pressure, molefracs_spec, molefracs_init) } else { Self::starting_x2_dew(eos, *temperature, *pressure, molefracs_spec, molefracs_init) }?; let (options_inner, options_outer) = options; // initialize variables let mut err_out = 1.0; let mut k_out = 0; if PhaseEquilibrium::is_trivial_solution(&state1, &state2) { log_iter!(options_outer.verbosity, "Trivial solution encountered!"); return Err(FeosError::TrivialSolution); } log_iter!( options_outer.verbosity, "res outer loop | res inner loop | temperature | pressure | molefracs second phase", ); log_iter!(options_outer.verbosity, "{:-<104}", ""); log_iteration( options_outer.verbosity, None, *temperature, *pressure, state2.molefracs.as_slice(), false, ); // Outer loop for finding x2 for ko in 0..options_outer.max_iter.unwrap_or(MAX_ITER_OUTER) { // Iso-Fugacity equation err_out = if err_out > NEWTON_TOL { // Inner loop for finding T or p for _ in 0..options_inner.max_iter.unwrap_or(MAX_ITER_INNER) { let res = if iterate_p { Self::adjust_p( *temperature, pressure, &mut state1, &mut state2, options_inner.verbosity, )? } else { Self::adjust_t( temperature, *pressure, &mut state1, &mut state2, options_inner.verbosity, )? }; if res < options_inner.tol.unwrap_or(TOL_INNER) { break; } } Self::adjust_x2(&state1, &mut state2, options_outer.verbosity) } else { let mut t = temperature.into_reduced(); let mut p = pressure.into_reduced(); let mut molar_volume = state1.density.into_reduced().recip(); let mut rho2 = state2.partial_density.to_reduced(); let err = if iterate_p { Self::newton_step_t( &state1.eos, t, &state1.molefracs, &mut p, &mut molar_volume, &mut rho2, options_outer.verbosity, ) } else { Self::newton_step_p( &state1.eos, &mut t, &state1.molefracs, p, &mut molar_volume, &mut rho2, options_outer.verbosity, ) }; *temperature = Temperature::from_reduced(t); *pressure = Pressure::from_reduced(p); state1.density = Density::from_reduced(molar_volume.recip()); state2.partial_density = Density::from_reduced(rho2); Ok(err) }?; if Self::is_trivial_solution(&state1, &state2) { log_iter!(options_outer.verbosity, "Trivial solution encountered!"); return Err(FeosError::TrivialSolution); } if err_out < options_outer.tol.unwrap_or(TOL_OUTER) { k_out = ko + 1; break; } } if err_out < options_outer.tol.unwrap_or(TOL_OUTER) { log_result!( options_outer.verbosity, "Bubble/dew point: calculation converged in {} step(s)\n", k_out ); Ok(( state1.density.into_reduced().recip(), state2.partial_density.to_reduced(), )) } else { // not converged, return error Err(FeosError::NotConverged(String::from( "bubble-dew-iteration", ))) } } fn adjust_p( temperature: Temperature, pressure: &mut Pressure, state1: &mut State<E, N>, state2: &mut State<E, N>, verbosity: Verbosity, ) -> FeosResult<f64> { // calculate K = phi_1/phi_2 = x_2/x_1 let ln_phi_1 = state1.ln_phi(); let ln_phi_2 = state2.ln_phi(); let k = (&ln_phi_1 - &ln_phi_2).map(f64::exp); // calculate residual let xk = state1.molefracs.component_mul(&k); let f = xk.sum() - 1.0; // Derivative w.r.t. ln(pressure) let ln_phi_1_dp = state1.dln_phi_dp(); let ln_phi_2_dp = state2.dln_phi_dp(); let df = ((ln_phi_1_dp - ln_phi_2_dp) * *pressure) .into_value() .component_mul(&xk) .sum(); let mut lnpstep = -f / df; // catch too big p-steps lnpstep = lnpstep.clamp(-MAX_LNPSTEP, MAX_LNPSTEP); // Update p *pressure *= lnpstep.exp(); // update states with new temperature/pressure Self::adjust_states(temperature, *pressure, state1, state2, None)?; // log log_iteration( verbosity, Some(f), temperature, *pressure, state2.molefracs.as_slice(), false, ); Ok(f.abs()) } fn adjust_t( temperature: &mut Temperature, pressure: Pressure, state1: &mut State<E, N>, state2: &mut State<E, N>, verbosity: Verbosity, ) -> FeosResult<f64> { // calculate K = phi_1/phi_2 = x_2/x_1 let ln_phi_1 = state1.ln_phi(); let ln_phi_2 = state2.ln_phi(); let k = (&ln_phi_1 - &ln_phi_2).map(f64::exp); // calculate residual let f = state1.molefracs.dot(&k) - 1.0; // Derivative w.r.t. temperature let ln_phi_1_dt = state1.dln_phi_dt(); let ln_phi_2_dt = state2.dln_phi_dt(); let df = ((ln_phi_1_dt - ln_phi_2_dt) .component_mul(&Dimensionless::new(state1.molefracs.component_mul(&k)))) .sum(); let mut tstep = -f / df; // catch too big t-steps if tstep < -Temperature::from_reduced(MAX_TSTEP) { tstep = -Temperature::from_reduced(MAX_TSTEP); } else if tstep > Temperature::from_reduced(MAX_TSTEP) { tstep = Temperature::from_reduced(MAX_TSTEP); } // Update t *temperature += tstep; // update states with new temperature Self::adjust_states(*temperature, pressure, state1, state2, None)?; // log log_iteration( verbosity, Some(f), *temperature, pressure, state2.molefracs.as_slice(), false, ); Ok(f.abs()) } fn starting_pressure_ideal_gas( eos: &E, temperature: Temperature, molefracs_spec: &OVector<f64, N>, bubble: bool, ) -> FeosResult<(Pressure, OVector<f64, N>)> { if bubble { Self::starting_pressure_ideal_gas_bubble(eos, temperature, molefracs_spec) } else { Self::starting_pressure_ideal_gas_dew(eos, temperature, molefracs_spec) } } pub(super) fn starting_pressure_ideal_gas_bubble( eos: &E, temperature: Temperature, liquid_molefracs: &OVector<f64, N>, ) -> FeosResult<(Pressure, OVector<f64, N>)> { let density = 0.75 * Density::from_reduced(eos.compute_max_density(liquid_molefracs)); let liquid = State::new_intensive(eos, temperature, density, liquid_molefracs)?; let v_l = liquid.partial_molar_volume(); let p_l = liquid.pressure(Contributions::Total); let mu_l = liquid.residual_chemical_potential(); let k_i = liquid_molefracs.component_mul( &((mu_l - v_l * p_l) / (RGAS * temperature)) .into_value() .map(f64::exp), ); let p = k_i.sum() * RGAS * temperature * density; let y = &k_i / k_i.sum(); Ok((p, y)) } fn starting_pressure_ideal_gas_dew( eos: &E, temperature: Temperature, vapor_molefracs: &OVector<f64, N>, ) -> FeosResult<(Pressure, OVector<f64, N>)> { let mut p: Option<Pressure> = None; let mut x = vapor_molefracs.clone(); for _ in 0..5 { let density = Density::from_reduced(0.75 * eos.compute_max_density(&x)); let liquid = State::new_intensive(eos, temperature, density, &x)?; let v_l = liquid.partial_molar_volume(); let p_l = liquid.pressure(Contributions::Total); let mu_l = liquid.residual_chemical_potential(); let k = vapor_molefracs.clone().component_div( &((mu_l - v_l * p_l) / (RGAS * temperature)) .into_value() .map(f64::exp), ); let k_sum = k.sum(); let p_new = RGAS * temperature * density / k_sum; x = k / k_sum; if let Some(p_old) = p && ((p_new - p_old) / p_old).into_value().abs() < 1e-5 { p = Some(p_new); break; } p = Some(p_new); } Ok((p.unwrap(), x)) } pub(super) fn starting_pressure_spinodal( eos: &E, temperature: Temperature, molefracs: &OVector<f64, N>, ) -> FeosResult<Pressure> { let [sp_v, sp_l] = State::spinodal(eos, temperature, Some(molefracs), Default::default())?; let pv = sp_v.pressure(Contributions::Total); let pl = sp_l.pressure(Contributions::Total); Ok(0.5 * (Pressure::from_reduced(0.0).max(pl) + pv)) } fn starting_x2_bubble( eos: &E, temperature: Temperature, pressure: Pressure, liquid_molefracs: &OVector<f64, N>, vapor_molefracs: Option<&OVector<f64, N>>, ) -> FeosResult<[State<E, N>; 2]> { let liquid_state = State::new_xpt(eos, temperature, pressure, liquid_molefracs, Some(Liquid))?; let xv = match vapor_molefracs { Some(xv) => xv.clone(), None => liquid_state .ln_phi() .map(f64::exp) .component_mul(liquid_molefracs), }; let vapor_state = State::new_xpt(eos, temperature, pressure, &xv, Some(Vapor))?; Ok([liquid_state, vapor_state]) } fn starting_x2_dew( eos: &E, temperature: Temperature, pressure: Pressure, vapor_molefracs: &OVector<f64, N>, liquid_molefracs: Option<&OVector<f64, N>>, ) -> FeosResult<[State<E, N>; 2]> { let vapor_state = State::new_npt( eos, temperature, pressure, &Moles::from_reduced(vapor_molefracs.clone()), Some(Vapor), )?; let xl = match liquid_molefracs { Some(xl) => xl.clone(), None => { let xl = vapor_state .ln_phi() .map(f64::exp) .component_mul(vapor_molefracs); let liquid_state = State::new_xpt(eos, temperature, pressure, &xl, Some(Liquid))?; (vapor_state.ln_phi() - liquid_state.ln_phi()) .map(f64::exp) .component_mul(vapor_molefracs) } }; let liquid_state = State::new_xpt(eos, temperature, pressure, &xl, Some(Liquid))?; Ok([vapor_state, liquid_state]) } fn adjust_states( temperature: Temperature, pressure: Pressure, state1: &mut State<E, N>, state2: &mut State<E, N>, moles_state2: Option<&Moles<OVector<f64, N>>>, ) -> FeosResult<()> { *state1 = State::new_npt( &state1.eos, temperature, pressure, &state1.moles, Some(InitialDensity(state1.density)), )?; *state2 = State::new_npt( &state2.eos, temperature, pressure, moles_state2.unwrap_or(&state2.moles), Some(InitialDensity(state2.density)), )?; Ok(()) } fn adjust_x2( state1: &State<E, N>, state2: &mut State<E, N>, verbosity: Verbosity, ) -> FeosResult<f64> { let x1 = &state1.molefracs; let ln_phi_1 = state1.ln_phi(); let ln_phi_2 = state2.ln_phi(); let k = (ln_phi_1 - ln_phi_2).map(f64::exp); let kx1 = k.component_mul(x1); let err_out = kx1 .component_div(&state2.molefracs) .map(|e| (e - 1.0).abs()) .sum(); let x2 = &kx1 / kx1.sum(); log_iter!( verbosity, "{:<14.8e} | {:14} | {:14} | {:16} |", err_out, "", "", "" ); *state2 = State::new_xpt( &state2.eos, state2.temperature, state2.pressure(Contributions::Total), &x2, Some(InitialDensity(state2.density)), )?; Ok(err_out) } } fn log_iteration( verbosity: Verbosity, error: Option<f64>, temperature: Temperature, pressure: Pressure, x2: &[f64], newton: bool, ) { let error = error.map_or_else(|| format!("{:14}", ""), |e| format!("{:<14.8e}", e.abs())); log_iter!( verbosity, "{:14} | {} | {:12.8} | {:12.8} | {:.8?} {}", "", error, temperature, pressure, x2, if newton { "NEWTON" } else { "" } ); }
Rust
3D
feos-org/feos
crates/feos-core/src/phase_equilibria/tp_flash.rs
.rs
13,855
415
use super::PhaseEquilibrium; use crate::equation_of_state::Residual; use crate::errors::{FeosError, FeosResult}; use crate::state::{Contributions, State}; use crate::{SolverOptions, Verbosity}; use nalgebra::{DVector, Matrix3, Matrix4xX}; use num_dual::{Dual, DualNum, first_derivative}; use quantity::{Dimensionless, Moles, Pressure, Temperature}; const MAX_ITER_TP: usize = 400; const TOL_TP: f64 = 1e-8; /// # Flash calculations impl<E: Residual> PhaseEquilibrium<E, 2> { /// Perform a Tp-flash calculation. If no initial values are /// given, the solution is initialized using a stability analysis. /// /// The algorithm can be use to calculate phase equilibria of systems /// containing non-volatile components (e.g. ions). pub fn tp_flash( eos: &E, temperature: Temperature, pressure: Pressure, feed: &Moles<DVector<f64>>, initial_state: Option<&PhaseEquilibrium<E, 2>>, options: SolverOptions, non_volatile_components: Option<Vec<usize>>, ) -> FeosResult<Self> { State::new_npt(eos, temperature, pressure, feed, None)?.tp_flash( initial_state, options, non_volatile_components, ) } } /// # Flash calculations impl<E: Residual> State<E> { /// Perform a Tp-flash calculation using the [State] as feed. /// If no initial values are given, the solution is initialized /// using a stability analysis. /// /// The algorithm can be use to calculate phase equilibria of systems /// containing non-volatile components (e.g. ions). pub fn tp_flash( &self, initial_state: Option<&PhaseEquilibrium<E, 2>>, options: SolverOptions, non_volatile_components: Option<Vec<usize>>, ) -> FeosResult<PhaseEquilibrium<E, 2>> { // initialization if let Some(init) = initial_state { let vle = self.tp_flash_( init.clone() .update_pressure(self.temperature, self.pressure(Contributions::Total))?, options, non_volatile_components.clone(), ); if vle.is_ok() { return vle; } } let (init1, init2) = PhaseEquilibrium::vle_init_stability(self)?; let vle = self.tp_flash_(init1, options, non_volatile_components.clone()); if vle.is_ok() { return vle; } if let Some(init2) = init2 { self.tp_flash_(init2, options, non_volatile_components) } else { vle } } pub fn tp_flash_( &self, mut new_vle_state: PhaseEquilibrium<E, 2>, options: SolverOptions, non_volatile_components: Option<Vec<usize>>, ) -> FeosResult<PhaseEquilibrium<E, 2>> { // set options let (max_iter, tol, verbosity) = options.unwrap_or(MAX_ITER_TP, TOL_TP); log_iter!( verbosity, " iter | residual | phase I mole fractions | phase II mole fractions " ); log_iter!(verbosity, "{:-<77}", ""); log_iter!( verbosity, " {:4} | | {:10.8?} | {:10.8?}", 0, new_vle_state.vapor().molefracs.data.as_vec(), new_vle_state.liquid().molefracs.data.as_vec(), ); let mut iter = 0; if non_volatile_components.is_none() { // 3 steps of successive substitution new_vle_state.successive_substitution( self, 3, &mut iter, &mut None, tol, verbosity, &non_volatile_components, )?; // check convergence let beta = new_vle_state.vapor_phase_fraction(); let tpd = [ self.tangent_plane_distance(new_vle_state.vapor()), self.tangent_plane_distance(new_vle_state.liquid()), ]; let dg = (1.0 - beta) * tpd[1] + beta * tpd[0]; // fix if only tpd[1] is positive if tpd[0] < 0.0 && dg >= 0.0 { let mut k = (self.ln_phi() - new_vle_state.vapor().ln_phi()).map(f64::exp); // Set k = 0 for non-volatile components if let Some(nvc) = non_volatile_components.as_ref() { nvc.iter().for_each(|&c| k[c] = 0.0); } new_vle_state.update_states(self, &k)?; new_vle_state.successive_substitution( self, 1, &mut iter, &mut None, tol, verbosity, &non_volatile_components, )?; } // fix if only tpd[0] is positive if tpd[1] < 0.0 && dg >= 0.0 { let mut k = (new_vle_state.liquid().ln_phi() - self.ln_phi()).map(f64::exp); // Set k = 0 for non-volatile components if let Some(nvc) = non_volatile_components.as_ref() { nvc.iter().for_each(|&c| k[c] = 0.0); } new_vle_state.update_states(self, &k)?; new_vle_state.successive_substitution( self, 1, &mut iter, &mut None, tol, verbosity, &non_volatile_components, )?; } } //continue with accelerated successive subsitution new_vle_state.accelerated_successive_substitution( self, &mut iter, max_iter, tol, verbosity, &non_volatile_components, )?; Ok(new_vle_state) } fn tangent_plane_distance(&self, trial_state: &State<E>) -> f64 { let ln_phi_z = self.ln_phi(); let ln_phi_w = trial_state.ln_phi(); let z = &self.molefracs; let w = &trial_state.molefracs; w.dot(&(w.map(f64::ln) + ln_phi_w - z.map(f64::ln) - ln_phi_z)) } } impl<E: Residual> PhaseEquilibrium<E, 2> { fn accelerated_successive_substitution( &mut self, feed_state: &State<E>, iter: &mut usize, max_iter: usize, tol: f64, verbosity: Verbosity, non_volatile_components: &Option<Vec<usize>>, ) -> FeosResult<()> { for _ in 0..max_iter { // do 5 successive substitution steps and check for convergence let mut k_vec = Matrix4xX::zeros(self.vapor().eos.components()); // let mut k_vec = Array::zeros((4, self.vapor().eos.components())); if self.successive_substitution( feed_state, 5, iter, &mut Some(&mut k_vec), tol, verbosity, non_volatile_components, )? { log_result!( verbosity, "Tp flash: calculation converged in {} step(s)\n", iter ); return Ok(()); } // calculate total Gibbs energy before the extrapolation let gibbs = self.total_gibbs_energy(); // extrapolate K values let delta_vec = k_vec.rows_range(1..) - k_vec.rows_range(..3); let delta = Matrix3::from_fn(|i, j| delta_vec.row(i).dot(&delta_vec.row(j))); let d = delta[(0, 1)] * delta[(0, 1)] - delta[(0, 0)] * delta[(1, 1)]; let a = (delta[(0, 2)] * delta[(0, 1)] - delta[(1, 2)] * delta[(0, 0)]) / d; let b = (delta[(1, 2)] * delta[(0, 1)] - delta[(0, 2)] * delta[(1, 1)]) / d; let mut k = (k_vec.row(3) + ((b * delta_vec.row(1) + (a + b) * delta_vec.row(2)) / (1.0 - a - b))) .map(f64::exp) .transpose(); // Set k = 0 for non-volatile components if let Some(nvc) = non_volatile_components.as_ref() { nvc.iter().for_each(|&c| k[c] = 0.0); } if !k.iter().all(|i| i.is_finite()) { continue; } // calculate new states let mut trial_vle_state = self.clone(); trial_vle_state.update_states(feed_state, &k)?; if trial_vle_state.total_gibbs_energy() < gibbs { *self = trial_vle_state; } } Err(FeosError::NotConverged("TP flash".to_owned())) } #[expect(clippy::too_many_arguments)] fn successive_substitution( &mut self, feed_state: &State<E>, iterations: usize, iter: &mut usize, k_vec: &mut Option<&mut Matrix4xX<f64>>, abs_tol: f64, verbosity: Verbosity, non_volatile_components: &Option<Vec<usize>>, ) -> FeosResult<bool> { for i in 0..iterations { let ln_phi_v = self.vapor().ln_phi(); let ln_phi_l = self.liquid().ln_phi(); let mut k = (&ln_phi_l - &ln_phi_v).map(f64::exp); // Set k = 0 for non-volatile components if let Some(nvc) = non_volatile_components.as_ref() { nvc.iter().for_each(|&c| k[c] = 0.0); } // check for convergence *iter += 1; let mut res_vec = ln_phi_l - ln_phi_v + self .liquid() .molefracs .component_div(&self.vapor().molefracs) .map(|i| if i > 0.0 { i.ln() } else { 0.0 }); // Set residuum to 0 for non-volatile components if let Some(nvc) = non_volatile_components.as_ref() { nvc.iter().for_each(|&c| res_vec[c] = 0.0); } let res = res_vec.norm(); log_iter!( verbosity, " {:4} | {:14.8e} | {:.8?} | {:.8?}", iter, res, self.vapor().molefracs.data.as_vec(), self.liquid().molefracs.data.as_vec(), ); if res < abs_tol { return Ok(true); } self.update_states(feed_state, &k)?; if let Some(k_vec) = k_vec && i >= iterations - 3 { k_vec.set_row( i + 3 - iterations, &k.map(|ki| if ki > 0.0 { ki.ln() } else { 0.0 }).transpose(), ); } } Ok(false) } fn update_states(&mut self, feed_state: &State<E>, k: &DVector<f64>) -> FeosResult<()> { // calculate vapor phase fraction using Rachford-Rice algorithm let mut beta = self.vapor_phase_fraction(); beta = rachford_rice(&feed_state.molefracs, k, Some(beta))?; // update VLE let v = feed_state.moles.clone().component_mul(&Dimensionless::new( k.map(|k| beta * k / (1.0 - beta + beta * k)), )); let l = feed_state.moles.clone().component_mul(&Dimensionless::new( k.map(|k| (1.0 - beta) / (1.0 - beta + beta * k)), )); self.update_moles(feed_state.pressure(Contributions::Total), [&v, &l])?; Ok(()) } fn vle_init_stability(feed_state: &State<E>) -> FeosResult<(Self, Option<Self>)> { let mut stable_states = feed_state.stability_analysis(SolverOptions::default())?; let state1 = stable_states.pop(); let state2 = stable_states.pop(); if let Some(s1) = state1 { let init1 = Self::from_states(s1.clone(), feed_state.clone()); if let Some(s2) = state2 { Ok((Self::from_states(s1, s2), Some(init1))) } else { Ok((init1, None)) } } else { Err(FeosError::NoPhaseSplit) } } } fn rachford_rice(feed: &DVector<f64>, k: &DVector<f64>, beta_in: Option<f64>) -> FeosResult<f64> { const MAX_ITER: usize = 10; const ABS_TOL: f64 = 1e-6; // check if solution exists let (mut beta_min, mut beta_max) = if feed.dot(k) > 1.0 && feed .component_div(k) .iter() .filter(|x| !x.is_nan()) .sum::<f64>() > 1.0 { (0.0, 1.0) } else { return Err(FeosError::IterationFailed(String::from("rachford_rice"))); }; // look for tighter bounds for (&k, &f) in k.iter().zip(feed.iter()) { if k > 1.0 { let b = (k * f - 1.0) / (k - 1.0); if b > beta_min { beta_min = b; } } if k < 1.0 { let b = (1.0 - f) / (1.0 - k); if b < beta_max { beta_max = b; } } } // initialize let mut beta = 0.5 * (beta_min + beta_max); if let Some(b) = beta_in && b > beta_min && b < beta_max { beta = b; } let g = feed.dot(&k.map(|k| (k - 1.0) / (1.0 - beta + beta * k))); if g > 0.0 { beta_min = beta } else { beta_max = beta } // iterate for _ in 0..MAX_ITER { let (g, dg) = first_derivative( |beta| { let frac = k.map(|k| (-beta + beta * k + 1.0).recip() * (k - 1.0)); feed.map(Dual::from).dot(&frac) }, beta, ); if g > 0.0 { beta_min = beta; } else { beta_max = beta; } let dbeta = g / dg; beta -= dbeta; if beta < beta_min || beta > beta_max { beta = 0.5 * (beta_min + beta_max); } if dbeta.abs() < ABS_TOL { return Ok(beta); } } Ok(beta) }
Rust
3D
feos-org/feos
crates/feos-core/src/phase_equilibria/phase_diagram_binary.rs
.rs
22,761
623
use super::bubble_dew::TemperatureOrPressure; use super::{PhaseDiagram, PhaseEquilibrium}; use crate::errors::{FeosError, FeosResult}; use crate::state::{Contributions, DensityInitialization::Vapor, State, StateBuilder}; use crate::{ReferenceSystem, Residual, SolverOptions, Subset}; use nalgebra::{DVector, dvector, stack, vector}; use ndarray::{Array1, s}; use num_dual::linalg::LU; use quantity::{Density, Moles, Pressure, RGAS, Temperature}; const DEFAULT_POINTS: usize = 51; impl<E: Residual + Subset> PhaseDiagram<E, 2> { /// Create a new binary phase diagram exhibiting a /// vapor/liquid equilibrium. /// /// If a heteroazeotrope occurs and the composition of the liquid /// phases are known, they can be passed as `x_lle` to avoid /// the calculation of unstable branches. pub fn binary_vle<TP: TemperatureOrPressure>( eos: &E, temperature_or_pressure: TP, npoints: Option<usize>, x_lle: Option<(f64, f64)>, bubble_dew_options: (SolverOptions, SolverOptions), ) -> FeosResult<Self> { let npoints = npoints.unwrap_or(DEFAULT_POINTS); // calculate boiling temperature/vapor pressure of pure components let vle_sat = PhaseEquilibrium::vle_pure_comps(eos, temperature_or_pressure); let vle_sat = [vle_sat[1].clone(), vle_sat[0].clone()]; // Only calculate up to specified compositions if let Some(x_lle) = x_lle { let (states1, states2) = Self::calculate_vlle( eos, temperature_or_pressure, npoints, x_lle, vle_sat, bubble_dew_options, )?; let states = states1 .into_iter() .chain(states2.into_iter().rev()) .collect(); return Ok(Self { states }); } // use dew point when calculating a supercritical tx diagram let bubble = temperature_or_pressure.temperature().is_some(); // look for supercritical components let (x_lim, vle_lim, bubble) = match vle_sat { [None, None] => return Err(FeosError::SuperCritical), [Some(vle2), None] => { let cp = State::critical_point_binary( eos, temperature_or_pressure, None, None, None, SolverOptions::default(), )?; let cp_vle = PhaseEquilibrium::from_states(cp.clone(), cp.clone()); ([0.0, cp.molefracs[0]], (vle2, cp_vle), bubble) } [None, Some(vle1)] => { let cp = State::critical_point_binary( eos, temperature_or_pressure, None, None, None, SolverOptions::default(), )?; let cp_vle = PhaseEquilibrium::from_states(cp.clone(), cp.clone()); ([1.0, cp.molefracs[0]], (vle1, cp_vle), bubble) } [Some(vle2), Some(vle1)] => ([0.0, 1.0], (vle2, vle1), true), }; let mut states = iterate_vle( eos, temperature_or_pressure, &x_lim, vle_lim.0, Some(vle_lim.1), npoints, bubble, bubble_dew_options, ); if !bubble { states = states.into_iter().rev().collect(); } Ok(Self { states }) } #[expect(clippy::type_complexity)] fn calculate_vlle<TP: TemperatureOrPressure>( eos: &E, tp: TP, npoints: usize, x_lle: (f64, f64), vle_sat: [Option<PhaseEquilibrium<E, 2>>; 2], bubble_dew_options: (SolverOptions, SolverOptions), ) -> FeosResult<(Vec<PhaseEquilibrium<E, 2>>, Vec<PhaseEquilibrium<E, 2>>)> { match vle_sat { [Some(vle2), Some(vle1)] => { let states1 = iterate_vle( eos, tp, &[0.0, x_lle.0], vle2, None, npoints / 2, true, bubble_dew_options, ); let states2 = iterate_vle( eos, tp, &[1.0, x_lle.1], vle1, None, npoints - npoints / 2, true, bubble_dew_options, ); Ok((states1, states2)) } _ => Err(FeosError::SuperCritical), } } /// Create a new phase diagram using Tp flash calculations. /// /// The usual use case for this function is the calculation of /// liquid-liquid phase diagrams, but it can be used for vapor- /// liquid diagrams as well, as long as the feed composition is /// in a two phase region. pub fn lle<TP: TemperatureOrPressure>( eos: &E, temperature_or_pressure: TP, feed: &Moles<DVector<f64>>, min_tp: TP::Other, max_tp: TP::Other, npoints: Option<usize>, ) -> FeosResult<Self> { let npoints = npoints.unwrap_or(DEFAULT_POINTS); let mut states = Vec::with_capacity(npoints); let (t_vec, p_vec) = temperature_or_pressure.linspace(min_tp, max_tp, npoints); let mut vle = None; for i in 0..npoints { let (t, p) = (t_vec.get(i), p_vec.get(i)); vle = PhaseEquilibrium::tp_flash( eos, t, p, feed, vle.as_ref(), SolverOptions::default(), None, ) .ok(); if let Some(vle) = vle.as_ref() { states.push(vle.clone()); } } Ok(Self { states }) } } #[expect(clippy::too_many_arguments)] fn iterate_vle<E: Residual + Subset, TP: TemperatureOrPressure>( eos: &E, tp: TP, x_lim: &[f64], vle_0: PhaseEquilibrium<E, 2>, vle_1: Option<PhaseEquilibrium<E, 2>>, npoints: usize, bubble: bool, bubble_dew_options: (SolverOptions, SolverOptions), ) -> Vec<PhaseEquilibrium<E, 2>> { let mut vle_vec = Vec::with_capacity(npoints); let x = Array1::linspace(x_lim[0], x_lim[1], npoints); let x = if vle_1.is_some() { x.slice(s![1..-1]) } else { x.slice(s![1..]) }; let tp_0 = Some(TP::from_state(vle_0.vapor())); let mut tp_old = tp_0; let mut y_old = None; vle_vec.push(vle_0); for xi in x { let vle = PhaseEquilibrium::bubble_dew_point( eos, tp, &dvector![*xi, 1.0 - xi], tp_old, y_old.as_ref(), bubble, bubble_dew_options, ); if let Ok(vle) = vle { y_old = Some(if bubble { vle.vapor().molefracs.clone() } else { vle.liquid().molefracs.clone() }); tp_old = Some(TP::from_state(vle.vapor())); vle_vec.push(vle.clone()); } else { y_old = None; tp_old = tp_0; } } if let Some(vle_1) = vle_1 { vle_vec.push(vle_1); } vle_vec } /// Phase diagram (Txy or pxy) for a system with heteroazeotropic phase behavior. pub struct PhaseDiagramHetero<E> { pub vle1: PhaseDiagram<E, 2>, pub vle2: PhaseDiagram<E, 2>, pub lle: Option<PhaseDiagram<E, 2>>, } impl<E: Residual + Subset> PhaseDiagram<E, 2> { /// Create a new binary phase diagram exhibiting a /// vapor/liquid/liquid equilibrium. /// /// The `x_lle` parameter is used as initial values for the calculation /// of the heteroazeotrope. #[expect(clippy::too_many_arguments)] pub fn binary_vlle<TP: TemperatureOrPressure>( eos: &E, temperature_or_pressure: TP, x_lle: (f64, f64), tp_lim_lle: Option<TP::Other>, tp_init_vlle: Option<TP::Other>, npoints_vle: Option<usize>, npoints_lle: Option<usize>, bubble_dew_options: (SolverOptions, SolverOptions), ) -> FeosResult<PhaseDiagramHetero<E>> { let npoints_vle = npoints_vle.unwrap_or(DEFAULT_POINTS); // calculate pure components let vle_sat = PhaseEquilibrium::vle_pure_comps(eos, temperature_or_pressure); let vle_sat = [vle_sat[1].clone(), vle_sat[0].clone()]; // calculate heteroazeotrope let vlle = PhaseEquilibrium::heteroazeotrope( eos, temperature_or_pressure, x_lle, tp_init_vlle, SolverOptions::default(), bubble_dew_options, )?; let x_hetero = (vlle.liquid1().molefracs[0], vlle.liquid2().molefracs[0]); // calculate vapor liquid equilibria let (dia1, dia2) = PhaseDiagram::calculate_vlle( eos, temperature_or_pressure, npoints_vle, x_hetero, vle_sat, bubble_dew_options, )?; // calculate liquid liquid equilibrium let lle = tp_lim_lle .map(|tp_lim| { let tp_hetero = TP::from_state(vlle.vapor()); let x_feed = 0.5 * (x_hetero.0 + x_hetero.1); let feed = Moles::from_reduced(dvector![x_feed, 1.0 - x_feed]); PhaseDiagram::lle( eos, temperature_or_pressure, &feed, tp_lim, tp_hetero, npoints_lle, ) }) .transpose()?; Ok(PhaseDiagramHetero { vle1: PhaseDiagram::new(dia1), vle2: PhaseDiagram::new(dia2), lle, }) } } impl<E: Clone> PhaseDiagramHetero<E> { pub fn vle(&self) -> PhaseDiagram<E, 2> { PhaseDiagram::new( self.vle1 .states .iter() .chain(self.vle2.states.iter().rev()) .cloned() .collect(), ) } } const MAX_ITER_HETERO: usize = 50; const TOL_HETERO: f64 = 1e-8; /// # Heteroazeotropes impl<E: Residual> PhaseEquilibrium<E, 3> { /// Calculate a heteroazeotrope (three phase equilbrium) for a binary /// system and given temperature or pressure. pub fn heteroazeotrope<TP: TemperatureOrPressure>( eos: &E, temperature_or_pressure: TP, x_init: (f64, f64), tp_init: Option<TP::Other>, options: SolverOptions, bubble_dew_options: (SolverOptions, SolverOptions), ) -> FeosResult<Self> { let (temperature, pressure, iterate_p) = temperature_or_pressure.temperature_pressure(tp_init); // let tp_init = tp_init.map(|tp_init| temperature_or_pressure.temperature_pressure(tp_init)); if iterate_p { PhaseEquilibrium::heteroazeotrope_t( eos, temperature.unwrap(), x_init, pressure, options, bubble_dew_options, ) } else { PhaseEquilibrium::heteroazeotrope_p( eos, pressure.unwrap(), x_init, temperature, options, bubble_dew_options, ) } } /// Calculate a heteroazeotrope (three phase equilbrium) for a binary /// system and given temperature. #[expect(clippy::toplevel_ref_arg)] fn heteroazeotrope_t( eos: &E, temperature: Temperature, x_init: (f64, f64), p_init: Option<Pressure>, options: SolverOptions, bubble_dew_options: (SolverOptions, SolverOptions), ) -> FeosResult<Self> { // calculate initial values using bubble point let x1 = dvector![x_init.0, 1.0 - x_init.0]; let x2 = dvector![x_init.1, 1.0 - x_init.1]; let vle1 = PhaseEquilibrium::bubble_point( eos, temperature, &x1, p_init, None, bubble_dew_options, )?; let vle2 = PhaseEquilibrium::bubble_point( eos, temperature, &x2, p_init, None, bubble_dew_options, )?; let mut l1 = vle1.liquid().clone(); let mut l2 = vle2.liquid().clone(); let p0 = (vle1.vapor().pressure(Contributions::Total) + vle2.vapor().pressure(Contributions::Total)) * 0.5; let nv0 = (&vle1.vapor().moles + &vle2.vapor().moles) * 0.5; let mut v = State::new_npt(eos, temperature, p0, &nv0, Some(Vapor))?; for _ in 0..options.max_iter.unwrap_or(MAX_ITER_HETERO) { // calculate properties let dmu_drho_l1 = (l1.dmu_dni(Contributions::Total) * l1.volume).to_reduced(); let dmu_drho_l2 = (l2.dmu_dni(Contributions::Total) * l2.volume).to_reduced(); let dmu_drho_v = (v.dmu_dni(Contributions::Total) * v.volume).to_reduced(); let dp_drho_l1 = (l1.dp_dni(Contributions::Total) * l1.volume) .to_reduced() .transpose(); let dp_drho_l2 = (l2.dp_dni(Contributions::Total) * l2.volume) .to_reduced() .transpose(); let dp_drho_v = (v.dp_dni(Contributions::Total) * v.volume) .to_reduced() .transpose(); let mu_l1_res = l1.residual_chemical_potential().to_reduced(); let mu_l2_res = l2.residual_chemical_potential().to_reduced(); let mu_v_res = v.residual_chemical_potential().to_reduced(); let p_l1 = l1.pressure(Contributions::Total).to_reduced(); let p_l2 = l2.pressure(Contributions::Total).to_reduced(); let p_v = v.pressure(Contributions::Total).to_reduced(); // calculate residual let delta_l1v_mu_ig = (RGAS * v.temperature).to_reduced() * (l1 .partial_density .to_reduced() .component_div(&v.partial_density.to_reduced())) .map(f64::ln); let delta_l2v_mu_ig = (RGAS * v.temperature).to_reduced() * (l2 .partial_density .to_reduced() .component_div(&v.partial_density.to_reduced())) .map(f64::ln); let res = stack![ mu_l1_res - &mu_v_res + delta_l1v_mu_ig; mu_l2_res - &mu_v_res + delta_l2v_mu_ig; vector![p_l1 - p_v]; vector![p_l2 - p_v] ]; // check for convergence if res.norm() < options.tol.unwrap_or(TOL_HETERO) { return Ok(Self([v, l1, l2])); } // calculate Jacobian let jacobian = stack![ dmu_drho_l1, 0 , -&dmu_drho_v; 0 , dmu_drho_l2, -dmu_drho_v; dp_drho_l1 , 0 , -&dp_drho_v; 0 , dp_drho_l2 , -dp_drho_v ]; // calculate Newton step let dx = LU::new(jacobian)?.solve(&res); // apply Newton step let rho_l1 = &l1.partial_density - &Density::from_reduced(dx.rows_range(0..2).into_owned()); let rho_l2 = &l2.partial_density - &Density::from_reduced(dx.rows_range(2..4).into_owned()); let rho_v = &v.partial_density - &Density::from_reduced(dx.rows_range(4..6).into_owned()); // check for negative densities for i in 0..2 { if rho_l1.get(i).is_sign_negative() || rho_l2.get(i).is_sign_negative() || rho_v.get(i).is_sign_negative() { return Err(FeosError::IterationFailed(String::from( "PhaseEquilibrium::heteroazeotrope_t", ))); } } // update states l1 = StateBuilder::new(eos) .temperature(temperature) .partial_density(&rho_l1) .build()?; l2 = StateBuilder::new(eos) .temperature(temperature) .partial_density(&rho_l2) .build()?; v = StateBuilder::new(eos) .temperature(temperature) .partial_density(&rho_v) .build()?; } Err(FeosError::NotConverged(String::from( "PhaseEquilibrium::heteroazeotrope_t", ))) } /// Calculate a heteroazeotrope (three phase equilbrium) for a binary /// system and given pressure. #[expect(clippy::toplevel_ref_arg)] fn heteroazeotrope_p( eos: &E, pressure: Pressure, x_init: (f64, f64), t_init: Option<Temperature>, options: SolverOptions, bubble_dew_options: (SolverOptions, SolverOptions), ) -> FeosResult<Self> { let p = pressure.to_reduced(); // calculate initial values using bubble point let x1 = dvector![x_init.0, 1.0 - x_init.0]; let x2 = dvector![x_init.1, 1.0 - x_init.1]; let vle1 = PhaseEquilibrium::bubble_point(eos, pressure, &x1, t_init, None, bubble_dew_options)?; let vle2 = PhaseEquilibrium::bubble_point(eos, pressure, &x2, t_init, None, bubble_dew_options)?; let mut l1 = vle1.liquid().clone(); let mut l2 = vle2.liquid().clone(); let t0 = (vle1.vapor().temperature + vle2.vapor().temperature) * 0.5; let nv0 = (&vle1.vapor().moles + &vle2.vapor().moles) * 0.5; let mut v = State::new_npt(eos, t0, pressure, &nv0, Some(Vapor))?; for _ in 0..options.max_iter.unwrap_or(MAX_ITER_HETERO) { // calculate properties let dmu_drho_l1 = (l1.dmu_dni(Contributions::Total) * l1.volume).to_reduced(); let dmu_drho_l2 = (l2.dmu_dni(Contributions::Total) * l2.volume).to_reduced(); let dmu_drho_v = (v.dmu_dni(Contributions::Total) * v.volume).to_reduced(); let dmu_res_dt_l1 = (l1.dmu_res_dt()).to_reduced(); let dmu_res_dt_l2 = (l2.dmu_res_dt()).to_reduced(); let dmu_res_dt_v = (v.dmu_res_dt()).to_reduced(); let dp_drho_l1 = (l1.dp_dni(Contributions::Total) * l1.volume) .to_reduced() .transpose(); let dp_drho_l2 = (l2.dp_dni(Contributions::Total) * l2.volume) .to_reduced() .transpose(); let dp_drho_v = (v.dp_dni(Contributions::Total) * v.volume) .to_reduced() .transpose(); let dp_dt_l1 = (l1.dp_dt(Contributions::Total)).to_reduced(); let dp_dt_l2 = (l2.dp_dt(Contributions::Total)).to_reduced(); let dp_dt_v = (v.dp_dt(Contributions::Total)).to_reduced(); let mu_l1_res = l1.residual_chemical_potential().to_reduced(); let mu_l2_res = l2.residual_chemical_potential().to_reduced(); let mu_v_res = v.residual_chemical_potential().to_reduced(); let p_l1 = l1.pressure(Contributions::Total).to_reduced(); let p_l2 = l2.pressure(Contributions::Total).to_reduced(); let p_v = v.pressure(Contributions::Total).to_reduced(); // calculate residual let delta_l1v_dmu_ig_dt = l1 .partial_density .to_reduced() .component_div(&v.partial_density.to_reduced()) .map(f64::ln); let delta_l2v_dmu_ig_dt = l2 .partial_density .to_reduced() .component_div(&v.partial_density.to_reduced()) .map(f64::ln); let delta_l1v_mu_ig = (RGAS * v.temperature).to_reduced() * &delta_l1v_dmu_ig_dt; let delta_l2v_mu_ig = (RGAS * v.temperature).to_reduced() * &delta_l2v_dmu_ig_dt; let res = stack![ mu_l1_res - &mu_v_res + delta_l1v_mu_ig; mu_l2_res - &mu_v_res + delta_l2v_mu_ig; vector![p_l1 - p]; vector![p_l2 - p]; vector![p_v - p] ]; // check for convergence if res.norm() < options.tol.unwrap_or(TOL_HETERO) { return Ok(Self([v, l1, l2])); } let jacobian = stack![ dmu_drho_l1, 0, -&dmu_drho_v, dmu_res_dt_l1 - &dmu_res_dt_v + delta_l1v_dmu_ig_dt; 0, dmu_drho_l2, -dmu_drho_v, dmu_res_dt_l2 - &dmu_res_dt_v + delta_l2v_dmu_ig_dt; dp_drho_l1, 0, 0, vector![dp_dt_l1]; 0, dp_drho_l2, 0, vector![dp_dt_l2]; 0, 0, dp_drho_v, vector![dp_dt_v] ]; // calculate Newton step let dx = LU::new(jacobian)?.solve(&res); // apply Newton step let rho_l1 = l1.partial_density - Density::from_reduced(dx.rows_range(0..2).into_owned()); let rho_l2 = l2.partial_density - Density::from_reduced(dx.rows_range(2..4).into_owned()); let rho_v = v.partial_density - Density::from_reduced(dx.rows_range(4..6).into_owned()); let t = v.temperature - Temperature::from_reduced(dx[6]); // check for negative densities and temperatures for i in 0..2 { if rho_l1.get(i).is_sign_negative() || rho_l2.get(i).is_sign_negative() || rho_v.get(i).is_sign_negative() || t.is_sign_negative() { return Err(FeosError::IterationFailed(String::from( "PhaseEquilibrium::heteroazeotrope_p", ))); } } // update states l1 = StateBuilder::new(eos) .temperature(t) .partial_density(&rho_l1) .build()?; l2 = StateBuilder::new(eos) .temperature(t) .partial_density(&rho_l2) .build()?; v = StateBuilder::new(eos) .temperature(t) .partial_density(&rho_v) .build()?; } Err(FeosError::NotConverged(String::from( "PhaseEquilibrium::heteroazeotrope_p", ))) } }
Rust
3D
feos-org/feos
crates/feos-core/src/phase_equilibria/vle_pure.rs
.rs
18,900
501
use super::{PhaseEquilibrium, TRIVIAL_REL_DEVIATION}; use crate::density_iteration::{_density_iteration, _pressure_spinodal}; use crate::equation_of_state::{Residual, Subset}; use crate::errors::{FeosError, FeosResult}; use crate::state::{Contributions, DensityInitialization, State}; use crate::{ReferenceSystem, SolverOptions, TemperatureOrPressure, Verbosity}; use nalgebra::allocator::Allocator; use nalgebra::{DVector, DefaultAllocator, Dim, dvector}; use num_dual::{DualNum, DualStruct, Gradients}; use quantity::{Density, Pressure, RGAS, Temperature}; const SCALE_T_NEW: f64 = 0.7; const MAX_ITER_PURE: usize = 50; const TOL_PURE: f64 = 1e-12; /// # Pure component phase equilibria impl<E: Residual> PhaseEquilibrium<E, 2> { /// Calculate a phase equilibrium for a pure component. pub fn pure<TP: TemperatureOrPressure>( eos: &E, temperature_or_pressure: TP, initial_state: Option<&Self>, options: SolverOptions, ) -> FeosResult<Self> { if let Some(t) = temperature_or_pressure.temperature() { let (_, rho) = Self::pure_t(eos, t, initial_state, options)?; Ok(Self(rho.map(|r| { State::new_intensive(eos, t, r, &dvector![1.0]).unwrap() }))) } else if let Some(p) = temperature_or_pressure.pressure() { Self::pure_p(eos, p, initial_state, options) } else { unreachable!() } } } impl<E: Residual<N, D>, N: Gradients, D: DualNum<f64> + Copy> PhaseEquilibrium<E, 2, N, D> where DefaultAllocator: Allocator<N>, { /// Calculate a phase equilibrium for a pure component /// and given temperature. pub fn pure_t( eos: &E, temperature: Temperature<D>, initial_state: Option<&Self>, options: SolverOptions, ) -> FeosResult<(Pressure<D>, [Density<D>; 2])> { let eos_f64 = eos.re(); let t = temperature.into_reduced(); // First use given initial state if applicable let mut vle = initial_state.and_then(|init| { let vle = ( init.vapor() .pressure(Contributions::Total) .into_reduced() .re(), [ init.vapor().density.into_reduced().re(), init.liquid().density.into_reduced().re(), ], ); iterate_pure_t(&eos_f64, t.re(), vle, options).ok() }); // Next try to initialize with an ideal gas assumption vle = vle.or_else(|| { _init_pure_ideal_gas(&eos_f64, temperature.re()) .and_then(|vle| iterate_pure_t(&eos_f64, t.re(), vle, options)) .ok() }); // Finally use the spinodal to initialize the calculation let (p, [rho_v, rho_l]) = vle.map_or_else( || { _init_pure_spinodal(&eos_f64, temperature.re()) .and_then(|vle| iterate_pure_t(&eos_f64, t.re(), vle, options)) }, Ok, )?; // Implicit differentiation let mut pressure = D::from(p); let mut vapor_density = D::from(rho_v); let mut liquid_density = D::from(rho_l); let x = E::pure_molefracs(); for _ in 0..D::NDERIV { let v_l = liquid_density.recip(); let v_v = vapor_density.recip(); let (f_l, p_l, dp_l) = eos.p_dpdrho(t, liquid_density, &x); let (f_v, p_v, dp_v) = eos.p_dpdrho(t, vapor_density, &x); pressure = -(f_l * v_l - f_v * v_v + t * (v_v / v_l).ln()) / (v_l - v_v); liquid_density += (pressure - p_l) / dp_l; vapor_density += (pressure - p_v) / dp_v; } Ok(( Pressure::from_reduced(pressure), [ Density::from_reduced(vapor_density), Density::from_reduced(liquid_density), ], )) } } fn iterate_pure_t<E: Residual<N>, N: Dim>( eos: &E, temperature: f64, (mut pressure, [mut vapor_density, mut liquid_density]): (f64, [f64; 2]), options: SolverOptions, ) -> FeosResult<(f64, [f64; 2])> where DefaultAllocator: Allocator<N>, { let (max_iter, tol, verbosity) = options.unwrap_or(MAX_ITER_PURE, TOL_PURE); let x = E::pure_molefracs(); log_iter!( verbosity, " iter | residual | pressure | liquid density | vapor density | Newton steps" ); log_iter!(verbosity, "{:-<103}", ""); log_iter!( verbosity, " {:4} | | {:12.8} | {:12.8} | {:12.8} |", 0, Pressure::from_reduced(pressure), Density::from_reduced(liquid_density), Density::from_reduced(vapor_density) ); for i in 1..=max_iter { // calculate properties let (f_l_res, p_l, p_rho_l) = eos.p_dpdrho(temperature, liquid_density, &x); let (f_v_res, p_v, p_rho_v) = eos.p_dpdrho(temperature, vapor_density, &x); // Estimate the new pressure let v_v = vapor_density.recip(); let v_l = liquid_density.recip(); let delta_v = v_v - v_l; let delta_a = f_v_res * v_v - f_l_res * v_l + temperature * (vapor_density / liquid_density).ln(); let mut p_new = -delta_a / delta_v; // If the pressure becomes negative, assume the gas phase is ideal. The // resulting pressure is always positive. if p_new.is_sign_negative() { p_new = p_v * ((-delta_a - p_v / vapor_density) / temperature).exp(); } // Improve the estimate by exploiting the almost ideal behavior of the gas phase let mut newton_iter = 0; let newton_tol = pressure * delta_v * tol; for _ in 0..20 { let p_frac = p_new / pressure; let f = p_new * delta_v + delta_a + (p_frac.ln() + 1.0 - p_frac) * temperature; let df_dp = delta_v + (1.0 / p_new - 1.0 / pressure) * temperature; p_new -= f / df_dp; newton_iter += 1; if f.abs() < newton_tol { break; } } // Emergency brake if the implementation of the EOS is not safe. if p_new.is_nan() { return Err(FeosError::IterationFailed("pure_t".to_owned())); } // Calculate Newton steps for the densities and update state. liquid_density += (p_new - p_l) / p_rho_l; vapor_density += (p_new - p_v) / p_rho_v; if (vapor_density / liquid_density - 1.0).abs() < TRIVIAL_REL_DEVIATION { return Err(FeosError::TrivialSolution); } // Check for convergence let res = (p_new - pressure).abs(); log_iter!( verbosity, " {:4} | {:14.8e} | {:12.8} | {:12.8} | {:12.8} | {}", i, res, Pressure::from_reduced(p_new), Density::from_reduced(liquid_density), Density::from_reduced(vapor_density), newton_iter ); if res < pressure * tol { log_result!( verbosity, "PhaseEquilibrium::pure_t: calculation converged in {} step(s)\n", i ); return Ok((pressure, [vapor_density, liquid_density])); } pressure = p_new; } Err(FeosError::NotConverged("pure_t".to_owned())) } fn _init_pure_ideal_gas<E: Residual<N>, N: Dim>( eos: &E, temperature: Temperature, ) -> FeosResult<(f64, [f64; 2])> where DefaultAllocator: Allocator<N>, { let x = E::pure_molefracs(); let v = (0.75 * eos.compute_max_density(&x)).recip(); let t = temperature.into_reduced(); let a_res = eos.residual_molar_helmholtz_energy(t, v, &x); let p = t / v * (a_res / t - 1.0).exp(); let rho_v = p / t; let rho_l = v.recip(); let rho_v = _density_iteration(eos, t, p, &x, DensityInitialization::InitialDensity(rho_v))?; let rho_l = _density_iteration(eos, t, p, &x, DensityInitialization::InitialDensity(rho_l))?; Ok((p, [rho_v, rho_l])) } fn _init_pure_spinodal<E: Residual<N>, N: Dim>( eos: &E, temperature: Temperature, ) -> FeosResult<(f64, [f64; 2])> where DefaultAllocator: Allocator<N>, { let x = E::pure_molefracs(); let maxdensity = eos.compute_max_density(&x); let t = temperature.into_reduced(); let (p_l, _) = _pressure_spinodal(eos, t, 0.8 * maxdensity, &x)?; let (p_v, _) = _pressure_spinodal(eos, t, 0.001 * maxdensity, &x)?; let p = 0.5 * (0.0_f64.max(p_l) + p_v); let rho_l = _density_iteration(eos, t, p, &x, DensityInitialization::Liquid)?; let rho_v = _density_iteration(eos, t, p, &x, DensityInitialization::Vapor)?; Ok((p, [rho_v, rho_l])) } impl<E: Residual> PhaseEquilibrium<E, 2> { fn new_pt(eos: &E, temperature: Temperature, pressure: Pressure) -> FeosResult<Self> { let liquid = State::new_xpt( eos, temperature, pressure, &dvector![1.0], Some(DensityInitialization::Liquid), )?; let vapor = State::new_xpt( eos, temperature, pressure, &dvector![1.0], Some(DensityInitialization::Vapor), )?; Ok(Self([vapor, liquid])) } /// Calculate a phase equilibrium for a pure component /// and given pressure. fn pure_p( eos: &E, pressure: Pressure, initial_state: Option<&Self>, options: SolverOptions, ) -> FeosResult<Self> { let (max_iter, tol, verbosity) = options.unwrap_or(MAX_ITER_PURE, TOL_PURE); // Initialize the phase equilibrium let mut vle = match initial_state { Some(init) => init .clone() .update_pressure(init.vapor().temperature, pressure)?, None => PhaseEquilibrium::init_pure_p(eos, pressure)?, }; log_iter!( verbosity, " iter | residual | temperature | liquid density | vapor density " ); log_iter!(verbosity, "{:-<89}", ""); log_iter!( verbosity, " {:4} | | {:13.8} | {:12.8} | {:12.8}", 0, vle.vapor().temperature, vle.liquid().density, vle.vapor().density ); for i in 1..=max_iter { // calculate the pressures and derivatives let (p_l, p_rho_l) = vle.liquid().p_dpdrho(); let (p_v, p_rho_v) = vle.vapor().p_dpdrho(); let p_t_l = vle.liquid().dp_dt(Contributions::Total); let p_t_v = vle.vapor().dp_dt(Contributions::Total); // calculate the residual molar entropies (already cached) let s_l_res = vle.liquid().residual_molar_entropy(); let s_v_res = vle.vapor().residual_molar_entropy(); // calculate the residual molar Helmholtz energies (already cached) let a_l_res = vle.liquid().residual_molar_helmholtz_energy(); let a_v_res = vle.vapor().residual_molar_helmholtz_energy(); // calculate the molar volumes let v_l = 1.0 / vle.liquid().density; let v_v = 1.0 / vle.vapor().density; // estimate the temperature steps let kt = RGAS * vle.vapor().temperature; let ln_rho = (v_l / v_v).into_value().ln(); let delta_t = (pressure * (v_v - v_l) + (a_v_res - a_l_res + kt * ln_rho)) / (s_v_res - s_l_res - RGAS * ln_rho); let t_new = vle.vapor().temperature + delta_t; // calculate Newton steps for the densities and update state. let rho_l = vle.liquid().density + (pressure - p_l - p_t_l * delta_t) / p_rho_l; let rho_v = vle.vapor().density + (pressure - p_v - p_t_v * delta_t) / p_rho_v; if rho_l.is_sign_negative() || rho_v.is_sign_negative() || delta_t.abs() > Temperature::from_reduced(1.0) { // if densities are negative or the temperature step is large use density iteration instead vle = vle .update_pressure(t_new, pressure)? .check_trivial_solution()?; } else { // update state vle = Self([ State::new_pure(eos, t_new, rho_v)?, State::new_pure(eos, t_new, rho_l)?, ]); } // check for convergence let res = delta_t.abs(); log_iter!( verbosity, " {:4} | {:14.8e} | {:13.8} | {:12.8} | {:12.8}", i, res, vle.vapor().temperature, vle.liquid().density, vle.vapor().density ); if res < vle.vapor().temperature * tol { log_result!( verbosity, "PhaseEquilibrium::pure_p: calculation converged in {} step(s)\n", i ); return Ok(vle); } } Err(FeosError::NotConverged("pure_p".to_owned())) } /// Initialize a new VLE for a pure substance for a given pressure. fn init_pure_p(eos: &E, pressure: Pressure) -> FeosResult<Self> { let trial_temperatures = [ Temperature::from_reduced(300.0), Temperature::from_reduced(500.0), Temperature::from_reduced(200.0), ]; let x = dvector![1.0]; let mut vle = None; let mut t0 = Temperature::from_reduced(1.0); for t in trial_temperatures.iter() { t0 = *t; let _vle = PhaseEquilibrium::new_pt(eos, *t, pressure)?; if !Self::is_trivial_solution(_vle.vapor(), _vle.liquid()) { return Ok(_vle); } vle = Some(_vle); } let cp = State::critical_point(eos, None, None, None, SolverOptions::default())?; if pressure > cp.pressure(Contributions::Total) { return Err(FeosError::SuperCritical); }; if let Some(mut e) = vle { if e.vapor().density < cp.density { for _ in 0..8 { t0 *= SCALE_T_NEW; e.0[1] = State::new_xpt(eos, t0, pressure, &x, Some(DensityInitialization::Liquid))?; if e.liquid().density > cp.density { break; } } } else { for _ in 0..8 { t0 /= SCALE_T_NEW; e.0[0] = State::new_xpt(eos, t0, pressure, &x, Some(DensityInitialization::Vapor))?; if e.vapor().density < cp.density { break; } } } for _ in 0..20 { let h = |s: &State<_>| s.residual_enthalpy() + s.total_moles * RGAS * s.temperature; t0 = (h(e.vapor()) - h(e.liquid())) / (e.vapor().residual_entropy() - e.liquid().residual_entropy() - RGAS * e.vapor().total_moles * ((e.vapor().density / e.liquid().density).into_value().ln())); let trial_state = State::new_xpt(eos, t0, pressure, &x, Some(DensityInitialization::Vapor))?; if trial_state.density < cp.density { e.0[0] = trial_state; } let trial_state = State::new_xpt(eos, t0, pressure, &x, Some(DensityInitialization::Liquid))?; if trial_state.density > cp.density { e.0[1] = trial_state; } if e.liquid().temperature == e.vapor().temperature { return Ok(e); } } Err(FeosError::IterationFailed( "new_init_p: could not find proper initial state".to_owned(), )) } else { unreachable!() } } } impl<E: Residual + Subset> PhaseEquilibrium<E, 2> { /// Calculate the pure component vapor pressures of all /// components in the system for the given temperature. pub fn vapor_pressure(eos: &E, temperature: Temperature) -> Vec<Option<Pressure>> { (0..eos.components()) .map(|i| { let pure_eos = eos.subset(&[i]); PhaseEquilibrium::pure_t(&pure_eos, temperature, None, SolverOptions::default()) .map(|(p, _)| p) .ok() }) .collect() } /// Calculate the pure component boiling temperatures of all /// components in the system for the given pressure. pub fn boiling_temperature(eos: &E, pressure: Pressure) -> Vec<Option<Temperature>> { (0..eos.components()) .map(|i| { let pure_eos = eos.subset(&[i]); PhaseEquilibrium::pure_p(&pure_eos, pressure, None, SolverOptions::default()) .map(|vle| vle.vapor().temperature) .ok() }) .collect() } /// Calculate the pure component phase equilibria of all /// components in the system. pub fn vle_pure_comps<TP: TemperatureOrPressure>( eos: &E, temperature_or_pressure: TP, ) -> Vec<Option<PhaseEquilibrium<E, 2>>> { (0..eos.components()) .map(|i| { let pure_eos = eos.subset(&[i]); PhaseEquilibrium::pure( &pure_eos, temperature_or_pressure, None, SolverOptions::default(), ) .and_then(|vle_pure| { let mut molefracs_vapor = DVector::zeros(eos.components()); let mut molefracs_liquid = molefracs_vapor.clone(); molefracs_vapor[i] = 1.0; molefracs_liquid[i] = 1.0; let vapor = State::new_intensive( eos, vle_pure.vapor().temperature, vle_pure.vapor().density, &molefracs_vapor, )?; let liquid = State::new_intensive( eos, vle_pure.liquid().temperature, vle_pure.liquid().density, &molefracs_liquid, )?; Ok(PhaseEquilibrium::from_states(vapor, liquid)) }) .ok() }) .collect() } }
Rust
3D
feos-org/feos
crates/feos-core/src/phase_equilibria/phase_diagram_pure.rs
.rs
4,091
134
use super::PhaseEquilibrium; #[cfg(feature = "rayon")] use crate::ReferenceSystem; use crate::SolverOptions; use crate::equation_of_state::Residual; use crate::errors::FeosResult; use crate::state::{State, StateVec}; #[cfg(feature = "rayon")] use ndarray::{Array1, ArrayView1, Axis}; use quantity::Temperature; #[cfg(feature = "rayon")] use rayon::{ThreadPool, prelude::*}; /// Pure component and binary mixture phase diagrams. #[derive(Clone)] pub struct PhaseDiagram<E, const N: usize> { pub states: Vec<PhaseEquilibrium<E, N>>, } impl<E, const N: usize> PhaseDiagram<E, N> { /// Create a phase diagram from a list of phase equilibria. pub fn new(states: Vec<PhaseEquilibrium<E, N>>) -> Self { Self { states } } } impl<E: Residual> PhaseDiagram<E, 2> { /// Calculate a phase diagram for a pure component. pub fn pure( eos: &E, min_temperature: Temperature, npoints: usize, critical_temperature: Option<Temperature>, options: SolverOptions, ) -> FeosResult<Self> { let mut states = Vec::with_capacity(npoints); let sc = State::critical_point( eos, None, critical_temperature, None, SolverOptions::default(), )?; let max_temperature = min_temperature + (sc.temperature - min_temperature) * ((npoints - 2) as f64 / (npoints - 1) as f64); let temperatures = Temperature::linspace(min_temperature, max_temperature, npoints - 1); let mut vle = None; for ti in &temperatures { vle = PhaseEquilibrium::pure(eos, ti, vle.as_ref(), options).ok(); if let Some(vle) = vle.as_ref() { states.push(vle.clone()); } } states.push(PhaseEquilibrium::from_states(sc.clone(), sc)); Ok(PhaseDiagram::new(states)) } /// Return the vapor states of the diagram. pub fn vapor(&self) -> StateVec<'_, E> { self.states.iter().map(|s| s.vapor()).collect() } /// Return the liquid states of the diagram. pub fn liquid(&self) -> StateVec<'_, E> { self.states.iter().map(|s| s.liquid()).collect() } } #[cfg(feature = "rayon")] impl<E: Residual> PhaseDiagram<E, 2> { fn solve_temperatures( eos: &E, temperatures: ArrayView1<f64>, options: SolverOptions, ) -> FeosResult<Vec<PhaseEquilibrium<E, 2>>> { let mut states = Vec::with_capacity(temperatures.len()); let mut vle = None; for ti in temperatures { vle = PhaseEquilibrium::pure(eos, Temperature::from_reduced(*ti), vle.as_ref(), options) .ok(); if let Some(vle) = vle.as_ref() { states.push(vle.clone()); } } Ok(states) } pub fn par_pure( eos: &E, min_temperature: Temperature, npoints: usize, chunksize: usize, thread_pool: ThreadPool, critical_temperature: Option<Temperature>, options: SolverOptions, ) -> FeosResult<Self> where E: Send + Sync, { let sc = State::critical_point( eos, None, critical_temperature, None, SolverOptions::default(), )?; let max_temperature = min_temperature + (sc.temperature - min_temperature) * ((npoints - 2) as f64 / (npoints - 1) as f64); let temperatures = Array1::linspace( min_temperature.to_reduced(), max_temperature.to_reduced(), npoints - 1, ); let mut states: Vec<PhaseEquilibrium<E, 2>> = thread_pool.install(|| { temperatures .axis_chunks_iter(Axis(0), chunksize) .into_par_iter() .filter_map(|t| Self::solve_temperatures(eos, t, options).ok()) .flatten() .collect() }); states.push(PhaseEquilibrium::from_states(sc.clone(), sc)); Ok(PhaseDiagram::new(states)) } }
Rust
3D
feos-org/feos
crates/feos-core/src/phase_equilibria/stability_analysis.rs
.rs
8,907
231
use super::PhaseEquilibrium; use crate::equation_of_state::Residual; use crate::errors::{FeosError, FeosResult}; use crate::state::{Contributions, DensityInitialization, State}; use crate::{ReferenceSystem, SolverOptions, Verbosity}; use nalgebra::{DMatrix, DVector}; use num_dual::linalg::LU; use num_dual::linalg::smallest_ev; use quantity::Moles; const X_DOMINANT: f64 = 0.99; const MINIMIZE_TOL: f64 = 1E-06; const MIN_EIGENVAL: f64 = 1E-03; const ETA_STEP: f64 = 0.25; const MINIMIZE_KMAX: usize = 100; const ZERO_TPD: f64 = -1E-08; /// # Stability analysis impl<E: Residual> State<E> { /// Determine if the state is stable, i.e. if a phase split should /// occur or not. pub fn is_stable(&self, options: SolverOptions) -> FeosResult<bool> { Ok(self.stability_analysis(options)?.is_empty()) } /// Perform a stability analysis. The result is a list of [State]s with /// negative tangent plane distance (i.e. lower Gibbs energy) that can be /// used as initial estimates for a phase equilibrium calculation. pub fn stability_analysis(&self, options: SolverOptions) -> FeosResult<Vec<State<E>>> { let mut result = Vec::new(); for i_trial in 0..self.eos.components() + 1 { let phase = if i_trial == self.eos.components() { "Vapor phase".to_string() } else { format!("Liquid phase {}", i_trial + 1) }; if let Ok(mut trial_state) = self.define_trial_state(i_trial) { let (tpd, i) = self.minimize_tpd(&mut trial_state, options)?; let msg = if let Some(tpd) = tpd { if tpd < ZERO_TPD { if result .iter() .any(|s| PhaseEquilibrium::is_trivial_solution(s, &trial_state)) { "Found already identified minimum" } else { result.push(trial_state); "Found candidate" } } else { "Found minimum > 0" } } else { "Found trivial solution" }; log_result!(options.verbosity, "{}: {} in {} step(s)\n", phase, msg, i); } } Ok(result) } fn define_trial_state(&self, dominant_component: usize) -> FeosResult<State<E>> { let x_feed = &self.molefracs; let (x_trial, phase) = if dominant_component == self.eos.components() { // try an ideal vapor phase let x_trial = self.ln_phi().map(f64::exp).component_mul(x_feed); (&x_trial / x_trial.sum(), DensityInitialization::Vapor) } else { // try each component as nearly pure phase let factor = (1.0 - X_DOMINANT) / (x_feed.sum() - x_feed[dominant_component]); ( DVector::from_fn(self.eos.components(), |i, _| { if i == dominant_component { X_DOMINANT } else { x_feed[i] * factor } }), DensityInitialization::Liquid, ) }; State::new_npt( &self.eos, self.temperature, self.pressure(Contributions::Total), &Moles::from_reduced(x_trial), Some(phase), ) } fn minimize_tpd( &self, trial: &mut State<E>, options: SolverOptions, ) -> FeosResult<(Option<f64>, usize)> { let (max_iter, tol, verbosity) = options.unwrap_or(MINIMIZE_KMAX, MINIMIZE_TOL); let mut newton = false; let mut scaled_tol = tol; let mut tpd = 1E10; let di = self.molefracs.map(f64::ln) + self.ln_phi(); log_iter!(verbosity, " iter | residual | tpd | Newton"); log_iter!(verbosity, "{:-<46}", ""); for i in 1..=max_iter { let error = if !newton { // case: direct substitution let y = (&di - &trial.ln_phi()).map(f64::exp); let tpd_old = tpd; tpd = 1.0 - y.sum(); let error = (&y / y.sum() - &trial.molefracs).map(f64::abs).sum(); *trial = State::new_npt( &trial.eos, trial.temperature, trial.pressure(Contributions::Total), &Moles::from_reduced(y), Some(DensityInitialization::InitialDensity(trial.density)), )?; if (i > 4 && error > scaled_tol) || (tpd > tpd_old + 1E-05 && i > 2) { newton = true; // switch to newton scheme } error } else { // case: newton step trial.stability_newton_step(&di, &mut tpd)? }; log_iter!( verbosity, " {:4} | {:14.8e} | {:11.8} | {}", i, error, tpd, newton ); if PhaseEquilibrium::is_trivial_solution(self, &*trial) { return Ok((None, i)); } if tpd < -1E-02 { scaled_tol = tol * 1E01 } if tpd < -1E-01 { scaled_tol = tol * 1E02 } if tpd < -1E-01 && i > 5 { scaled_tol = tol * 1E03 } if error < scaled_tol { return Ok((Some(tpd), i)); } } Err(FeosError::NotConverged(String::from("stability analysis"))) } fn stability_newton_step(&mut self, di: &DVector<f64>, tpd: &mut f64) -> FeosResult<f64> { // save old values let tpd_old = *tpd; // calculate residual and ideal hesse matrix let mut hesse = (self.dln_phi_dnj() * Moles::from_reduced(1.0)).into_value(); let lnphi = self.ln_phi(); let y = self.moles.to_reduced(); let ln_y = y.map(|y| if y > f64::EPSILON { y.ln() } else { 0.0 }); let sq_y = y.map(f64::sqrt); let gradient = (&ln_y + &lnphi - di).component_mul(&sq_y); let hesse_ig = DMatrix::identity(self.eos.components(), self.eos.components()); for i in 0..self.eos.components() { hesse.column_mut(i).component_mul_assign(&(sq_y[i] * &sq_y)); if y[i] > f64::EPSILON { hesse[(i, i)] += ln_y[i] + lnphi[i] - di[i]; } } // !----------------------------------------------------------------------------- // ! use method of Murray, by adding a unity matrix to Hessian, if: // ! (1) H is not positive definite // ! (2) step size is too large // ! (3) objective function (tpd) does not descent // !----------------------------------------------------------------------------- let mut adjust_hessian = true; let mut hessian: DMatrix<f64>; let mut eta_h = 1.0; while adjust_hessian { adjust_hessian = false; hessian = &hesse + &(eta_h * &hesse_ig); let (min_eigenval, _) = smallest_ev(hessian.clone()); if min_eigenval < MIN_EIGENVAL && eta_h < 20.0 { eta_h += 2.0 * ETA_STEP; adjust_hessian = true; continue; // continue, because of Hessian-criterion (1): H not positive definite } // solve: hessian * delta_y = gradient let delta_y = LU::new(hessian)?.solve(&gradient); if delta_y .iter() .zip(y.iter()) .any(|(dy, y)| ((0.5 * dy).powi(2) / y).abs() > 5.0) { adjust_hessian = true; eta_h += 2.0 * ETA_STEP; continue; // continue, because of Hessian-criterion (2): too large step-size } let y = (&sq_y - &(delta_y / 2.0)).map(|v| v.powi(2)); let ln_y = y.map(|y| if y > f64::EPSILON { y.ln() } else { 0.0 }); *tpd = 1.0 + y.dot(&(&ln_y + &lnphi - di.add_scalar(1.0))); if *tpd > tpd_old + 0.0 * 1E-03 && eta_h < 30.0 { eta_h += ETA_STEP; adjust_hessian = true; continue; // continue, because of Hessian-criterion (3): tpd does not descent } // accept step and update state *self = State::new_npt( &self.eos, self.temperature, self.pressure(Contributions::Total), &Moles::from_reduced(y), Some(DensityInitialization::InitialDensity(self.density)), )?; } Ok(gradient.map(f64::abs).sum()) } }
Rust
3D
feos-org/feos
crates/feos-core/tests/parameters.rs
.rs
6,481
235
use feos_core::FeosError; use feos_core::parameter::*; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize, Default)] struct MyPureModel { a: f64, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq)] struct MyBinaryModel { b: f64, } type MyParameters = Parameters<MyPureModel, MyBinaryModel, ()>; #[test] fn from_records() { let pr_json = r#" [ { "identifier": { "cas": "123-4-5" }, "molarweight": 16.0426, "a": 0.1 }, { "identifier": { "cas": "678-9-1" }, "molarweight": 32.08412, "a": 0.2 } ] "#; let br_json = r#" [ { "id1": { "cas": "123-4-5" }, "id2": { "cas": "678-9-1" }, "b": 12.0 } ] "#; let pure_records: Vec<_> = serde_json::from_str(pr_json).expect("Unable to parse json."); let binary_records: Vec<_> = serde_json::from_str(br_json).expect("Unable to parse json."); let binary_matrix = MyParameters::binary_matrix_from_records( &pure_records, &binary_records, IdentifierOption::Cas, ) .unwrap(); let p = MyParameters::new(pure_records, binary_matrix).unwrap(); assert_eq!(p.identifiers()[0].cas, Some("123-4-5".into())); assert_eq!(p.identifiers()[1].cas, Some("678-9-1".into())); assert_eq!(p.binary[0].model_record.b, 12.0); } #[test] fn from_json_duplicates_input() { let pure_records = PureRecord::<MyPureModel, ()>::from_json( &["123-4-5", "123-4-5"], "tests/test_parameters2.json", IdentifierOption::Cas, ); assert!(matches!( pure_records, Err(FeosError::IncompatibleParameters(t)) if t == "A substance was defined more than once." )); } #[test] fn from_multiple_json_files_duplicates() { let my_parameters = MyParameters::from_multiple_json( &[ (vec!["123-4-5"], "tests/test_parameters1.json"), (vec!["678-9-1", "123-4-5"], "tests/test_parameters2.json"), ], None, IdentifierOption::Cas, ); assert!(matches!( my_parameters, Err(FeosError::IncompatibleParameters(t)) if t == "A substance was defined more than once." )); let my_parameters = MyParameters::from_multiple_json( &[ (vec!["123-4-5"], "tests/test_parameters1.json"), (vec!["678-9-1"], "tests/test_parameters2.json"), ], None, IdentifierOption::Cas, ) .unwrap(); // test_parameters1: a = 0.5 // test_parameters2: a = 0.1 or 0.3 assert_eq!(my_parameters.pure[0].model_record.a, 0.5); } #[test] fn from_multiple_json_files() { let p = MyParameters::from_multiple_json( &[ (vec!["678-9-1"], "tests/test_parameters2.json"), (vec!["123-4-5"], "tests/test_parameters1.json"), ], Some("tests/test_parameters_binary.json"), IdentifierOption::Cas, ) .unwrap(); // test_parameters1: a = 0.5 // test_parameters2: a = 0.1 or 0.3 assert_eq!(p.pure[1].model_record.a, 0.5); let br = p.binary; assert_eq!(br[0].model_record.b, 12.0); } #[test] fn from_records_missing_binary() { let pr_json = r#" [ { "identifier": { "cas": "123-4-5" }, "molarweight": 16.0426, "a": 0.1 }, { "identifier": { "cas": "678-9-1" }, "molarweight": 32.08412, "a": 0.2 } ] "#; let br_json = r#" [ { "id1": { "cas": "123-4-5" }, "id2": { "cas": "000-00-0" }, "b": 12.0 } ] "#; let pure_records: Vec<_> = serde_json::from_str(pr_json).expect("Unable to parse json."); let binary_records: Vec<_> = serde_json::from_str(br_json).expect("Unable to parse json."); let binary_matrix = MyParameters::binary_matrix_from_records( &pure_records, &binary_records, IdentifierOption::Cas, ) .unwrap(); let p = MyParameters::new(pure_records, binary_matrix).unwrap(); assert_eq!(p.identifiers()[0].cas, Some("123-4-5".into())); assert_eq!(p.identifiers()[1].cas, Some("678-9-1".into())); let br = p.binary; assert_eq!(br.len(), 0); } #[test] fn from_records_correct_binary_order() { let pr_json = r#" [ { "identifier": { "cas": "000-0-0" }, "molarweight": 32.08412, "a": 0.2 }, { "identifier": { "cas": "123-4-5" }, "molarweight": 16.0426, "a": 0.1 }, { "identifier": { "cas": "678-9-1" }, "molarweight": 32.08412, "a": 0.2 } ] "#; let br_json = r#" [ { "id1": { "cas": "123-4-5" }, "id2": { "cas": "678-9-1" }, "b": 12.0 } ] "#; let pure_records: Vec<_> = serde_json::from_str(pr_json).expect("Unable to parse json."); let binary_records: Vec<_> = serde_json::from_str(br_json).expect("Unable to parse json."); let binary_matrix = MyParameters::binary_matrix_from_records( &pure_records, &binary_records, IdentifierOption::Cas, ) .unwrap(); let p = MyParameters::new(pure_records, binary_matrix).unwrap(); assert_eq!(p.identifiers()[0].cas, Some("000-0-0".into())); assert_eq!(p.identifiers()[1].cas, Some("123-4-5".into())); assert_eq!(p.identifiers()[2].cas, Some("678-9-1".into())); assert_eq!(p.binary[0].id1, 1); assert_eq!(p.binary[0].id2, 2); assert_eq!(p.binary[0].model_record.b, 12.0); }
Rust
3D
feos-org/feos
crates/feos-dft/CHANGELOG.md
.md
10,473
158
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). > [!IMPORTANT] > This file contains changes up to `feos-dft` v0.8.0. For newer versions, changes are documented for the entire project rather than individual crates [here](../../CHANGELOG.md). ## [Unreleased] ## [0.8.0] - 2024-12-28 ### Added - Added `henry_coefficients` and `ideal_gas_enthalpy_of_adosrption` to `PoreProfile`. [#263](https://github.com/feos-org/feos/pull/263) ### Packaging - Updated `quantity` dependency to 0.10. [#262](https://github.com/feos-org/feos/pull/262) - Updated `num-dual` dependency to 0.11. [#262](https://github.com/feos-org/feos/pull/262) - Updated `numpy` and `PyO3` dependencies to 0.23. [#262](https://github.com/feos-org/feos/pull/262) - Updated `gauss-quad` dependency to 0.2. [#261](https://github.com/feos-org/feos/pull/261) ## [0.7.0] - 2024-05-21 ### Changed - Updated interfaces according to removal of `HelmholtzEnergyDual` and `HelmholtzEnergy` in `feos-core`. [#226](https://github.com/feos-org/feos/pull/226) - Changed return values of `HelmholtzEnergyFunctional::contributions` from `dyn FunctionalContribution` to `HelmholtzEnergyFunctional::Contribution`. [#226](https://github.com/feos-org/feos/pull/226) ### Removed - Removed `FunctionalContributionDual` trait. [#226](https://github.com/feos-org/feos/pull/226) ### Packaging - Updated `quantity` dependency to 0.8. [#238](https://github.com/feos-org/feos/pull/238) - Updated `num-dual` dependency to 0.9. [#238](https://github.com/feos-org/feos/pull/238) - Updated `numpy` and `PyO3` dependencies to 0.21. [#238](https://github.com/feos-org/feos/pull/238) ## [0.6.0] - 2023-12-19 ### Packaging - Updated `feos-core` dependency to 0.6. ## [0.5.0] - 2023-10-20 ### Added - Implemented `HelmholtzEnergyFunctional` for `EquationOfState` to be able to use functionals as equations of state. [#158](https://github.com/feos-org/feos/pull/158) - Added the possibility to specify the angles of non-orthorombic unit cells. Currently, the external potential must be specified if non-orthorombic unit cells are calculated. [#176](https://github.com/feos-org/feos/pull/176) ### Changed - `HelmholtzEnergyFunctional`: added `Components` trait as trait bound and removed `ideal_gas` method. [#158](https://github.com/feos-org/feos/pull/158) - `DFT<F>` now implements `Residual` and furthermore `IdealGas` if `F` implements `IdealGas`. [#158](https://github.com/feos-org/feos/pull/158) - What properties (and contributions) of `DFTProfile` are available now depends on whether an ideal gas model is provided or not. [#158](https://github.com/feos-org/feos/pull/158) - Pore volumes and other integrated properties (loadings, energies, ...) are now always reported in units of volume. For translationally symmetric pores this is achieved by multiplying with the reference length (1 Å) in every direction with symmetries. [#181](https://github.com/feos-org/feos/pull/181) ### Removed - Removed `DefaultIdealGasContribution` [#158](https://github.com/feos-org/feos/pull/158) - Removed getters for `chemical_potential` (for profiles) and `molar_gibbs_energy` (for `Adsorption1D` and `Adsorption3D`) from Python interface. [#158](https://github.com/feos-org/feos/pull/158) ### Fixed - Added an error, if the unit cells in 3D DFT are too small and violate the minimum image convention. [#176](https://github.com/feos-org/feos/pull/176) ### Packaging - Updated `quantity` dependency to 0.7. - Updated `num-dual` dependency to 0.8. [#137](https://github.com/feos-org/feos/pull/137) - Updated `numpy` and `PyO3` dependencies to 0.20. ## [0.4.1] - 2023-03-20 ### Added - Added new methods `drho_dmu`, `drho_dp` and `drho_dt` that calculate partial derivatives of density profiles to every DFT profile. Also includes direct access to the integrated derivatives `dn_dmu`, `dn_dp` and `dn_dt`. [#134](https://github.com/feos-org/feos/pull/134) - Added `enthalpy_of_adsoprtion` and `partial_molar_enthalpy_of_adsorption` getters to pores and adsorption isotherms. [#135](https://github.com/feos-org/feos/pull/135) ## [0.4.0] - 2023-01-27 ### Added - `PlanarInterface` now has methods for the calculation of the 90-10 interface thickness (`PlanarInterface::interfacial_thickness`), interfacial enrichtment (`PlanarInterface::interfacial_enrichment`), and relative adsorption (`PlanarInterface::relative_adsorption`). [#64](https://github.com/feos-org/feos/pull/64) - Added a matrix-free Newton DFT solver that uses GMRES for the linear subproblem. [#75](https://github.com/feos-org/feos/pull/75) - Solver metrics like execution time and the residuals are automatically logged during every computation. The results can be accessed via the `solver_log` field of `DFTProfile`. [#75](https://github.com/feos-org/feos/pull/75) ### Changed - Added `Send` and `Sync` as supertraits to `HelmholtzEnergyFunctional` and all related traits. [#57](https://github.com/feos-org/feos/pull/57) - Renamed the `3d_dft` feature to `rayon` in accordance to the other feos crates. [#62](https://github.com/feos-org/feos/pull/62) - internally rewrote the implementation of the Euler-Lagrange equation to use a bulk density instead of the chemical potential as variable. [#60](https://github.com/feos-org/feos/pull/60) - Renamed the parameter `beta` of the Picard iteration and Anderson mixing solvers to `damping_coefficient`. [#75](https://github.com/feos-org/feos/pull/75) - Removed generics for units in all structs and traits in favor of static SI units. [#115](https://github.com/feos-org/feos/pull/115) ### Fixed - Fixed the sign of vector weighted densities in Cartesian and cylindrical geometries. The wrong sign had no effects on the Helmholtz energy and thus on density profiles. [#120](https://github.com/feos-org/feos/pull/120) ### Packaging - Updated `pyo3` and `numpy` dependencies to 0.18. [#119](https://github.com/feos-org/feos/pull/119) - Updated `quantity` dependency to 0.6. [#119](https://github.com/feos-org/feos/pull/119) - Updated `num-dual` dependency to 0.6. [#119](https://github.com/feos-org/feos/pull/119) ## [0.3.2] - 2022-10-13 ### Changed - The 3D DFT functionalities (3D pores, solvation free energy, free-energy-averaged potentials) are hidden behind the new `3d_dft` feature. For the Python package, the feature is always enabled. [#51](https://github.com/feos-org/feos/pull/51) ## [0.3.1] - 2022-08-26 ### Changed - `Adsorption::equilibrium_isotherm`, `Adsorption::adsorption_isotherm`, and `Adsorption::desorption_isotherm` only accept `SIArray1`s as input for the pressure discretization. [#50](https://github.com/feos-org/feos/pull/50) - For the calculation of desorption isotherms and the filled branches of equilibrium isotherms, the density profiles are initialized using a liquid bulk density. [#50](https://github.com/feos-org/feos/pull/50) ## [0.3.0] - 2022-07-13 ### Added - Added getters for the fields of `Pore1D` in Python. [#30](https://github.com/feos-org/feos-dft/pull/30) - Added Steele potential with custom combining rules. [#29](https://github.com/feos-org/feos/pull/29) ### Changed - Made FMT functional more flexible w.r.t. the shape of the weight functions. [#31](https://github.com/feos-org/feos-dft/pull/31) - Changed interface of `PairCorrelationFunction` to facilitate the calculation of pair correlation functions in mixtures. [#29](https://github.com/feos-org/feos-dft/pull/29) ### Removed - Moved the implementation of fundamental measure theory to the `feos` crate. [#27](https://github.com/feos-org/feos/pull/27) ## [0.2.0] - 2022-04-12 ### Added - Added `grand_potential_density` getter for DFT profiles in Python. [#22](https://github.com/feos-org/feos-dft/pull/22) ### Changed - Renamed `AxisGeometry` to `Geometry`. [#19](https://github.com/feos-org/feos-dft/pull/19) - Removed `PyGeometry` and `PyFMTVersion` in favor of a simpler implementation using `PyO3`'s new `#[pyclass]` for fieldless enums feature. [#19](https://github.com/feos-org/feos-dft/pull/19) - `DFTSolver` now uses `Verbosity` instead of a `bool` to control its output. [#19](https://github.com/feos-org/feos-dft/pull/19) - `SurfaceTensionDiagram` now uses the new `StateVec` struct to access properties of the bulk phases. [#19](https://github.com/feos-org/feos-dft/pull/19) - `Pore1D::initialize` and `Pore3D::initialize` now accept initial values for the density profiles as optional arguments. [#24](https://github.com/feos-org/feos-dft/pull/24) - Internally restructured the `DFT` structure to avoid redundant data. [#24](https://github.com/feos-org/feos-dft/pull/24) - Removed the `m` function in `FluidParameters`, it is instead inferred from `HelmholtzEnergyFunctional` which is now a supertrait of `FluidParameters`. [#24](https://github.com/feos-org/feos-dft/pull/24) - Added optional field `cutoff_radius` to `ExternalPotential::FreeEnergyAveraged`. [#25](https://github.com/feos-org/feos-dft/pull/25) ### Packaging - Updated `pyo3` and `numpy` dependencies to 0.16. - Updated `quantity` dependency to 0.5. - Updated `num-dual` dependency to 0.5. - Updated `feos-core` dependency to 0.2. - Updated `ang` dependency to 0.6. - Removed `log` dependency. ## [0.1.3] - 2022-02-17 ### Fixed - The pore volume for `Pore3D` is now also accesible from Python. [#16](https://github.com/feos-org/feos-dft/pull/16) ## [0.1.2] - 2022-02-16 ### Added - The pore volume using Helium at 298 K as reference is now directly accesible from `Pore1D` and `Pore3D`. [#13](https://github.com/feos-org/feos-dft/pull/13) ### Changed - Removed the `unsendable` tag from python classes wherever possible. [#14](https://github.com/feos-org/feos-dft/pull/14) ## [0.1.1] - 2022-02-14 ### Added - `HelmholtzEnergyFunctional`s can now overwrite the `ideal_gas` method to provide a non-default ideal gas contribution that is accounted for in the calculation of the entropy, the internal energy and other properties. [#10](https://github.com/feos-org/feos-dft/pull/10) ### Changed - Removed the `functional` field in `Pore1D` and `Pore3D`. [#9](https://github.com/feos-org/feos-dft/pull/9) ### Fixed - Fixed the units of default values for adsorption isotherms. [#8](https://github.com/feos-org/feos-dft/pull/8) ### Packaging - Updated `rustdct` dependency to 0.7. ## [0.1.0] - 2021-12-22 ### Added - Initial release
Markdown
3D
feos-org/feos
crates/feos-dft/src/lib.rs
.rs
753
25
#![warn(clippy::all)] #![warn(clippy::allow_attributes)] pub mod adsorption; mod convolver; mod functional; mod functional_contribution; mod geometry; mod ideal_chain_contribution; pub mod interface; mod pdgt; mod profile; pub mod solvation; mod solver; mod weight_functions; pub use convolver::{Convolver, ConvolverFFT}; pub use functional::{HelmholtzEnergyFunctional, HelmholtzEnergyFunctionalDyn, MoleculeShape}; pub use functional_contribution::FunctionalContribution; pub use geometry::{Axis, Geometry, Grid}; pub use pdgt::PdgtFunctionalProperties; pub use profile::{DFTProfile, DFTSpecification, DFTSpecifications}; pub use solver::{DFTSolver, DFTSolverLog}; pub use weight_functions::{WeightFunction, WeightFunctionInfo, WeightFunctionShape};
Rust
3D
feos-org/feos
crates/feos-dft/src/functional_contribution.rs
.rs
4,484
113
use crate::weight_functions::WeightFunctionInfo; use feos_core::{FeosResult, StateHD}; use ndarray::RemoveAxis; use ndarray::prelude::*; use num_dual::*; use num_traits::Zero; /// Individual functional contribution that can be evaluated using generalized (hyper) dual numbers. pub trait FunctionalContribution: Sync + Send { /// Return the name of the contribution. fn name(&self) -> &'static str; /// Return the weight functions required in this contribution. fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N>; /// Overwrite this if the weight functions in pDGT are different than for DFT. fn weight_functions_pdgt<N: DualNum<f64> + Copy>( &self, temperature: N, ) -> WeightFunctionInfo<N> { self.weight_functions(temperature) } /// Return the Helmholtz energy density for the given temperature and weighted densities. fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, weighted_densities: ArrayView2<N>, ) -> FeosResult<Array1<N>>; fn bulk_helmholtz_energy_density<N: DualNum<f64> + Copy>(&self, state: &StateHD<N>) -> N { // calculate weight functions let weight_functions = self.weight_functions(state.temperature); // calculate segment density let density: Array1<_> = weight_functions .component_index .iter() .map(|&c| state.partial_density[c]) .collect(); // calculate weighted density and Helmholtz energy let weight_constants = weight_functions.weight_constants(Zero::zero(), 0); let weighted_densities = weight_constants.dot(&density).insert_axis(Axis(1)); self.helmholtz_energy_density(state.temperature, weighted_densities.view()) .unwrap()[0] } fn first_partial_derivatives<N: DualNum<f64> + Copy>( &self, temperature: N, weighted_densities: Array2<N>, mut helmholtz_energy_density: ArrayViewMut1<N>, mut first_partial_derivative: ArrayViewMut2<N>, ) -> FeosResult<()> { let mut wd = weighted_densities.mapv(Dual::from_re); let t = Dual::from_re(temperature); let mut phi = Array::zeros(weighted_densities.raw_dim().remove_axis(Axis(0))); for i in 0..wd.shape()[0] { wd.index_axis_mut(Axis(0), i) .map_inplace(|x| x.eps = N::one()); phi = self.helmholtz_energy_density(t, wd.view())?; first_partial_derivative .index_axis_mut(Axis(0), i) .assign(&phi.mapv(|p| p.eps)); wd.index_axis_mut(Axis(0), i) .map_inplace(|x| x.eps = N::zero()); } helmholtz_energy_density.assign(&phi.mapv(|p| p.re)); Ok(()) } fn second_partial_derivatives( &self, temperature: f64, weighted_densities: ArrayView2<f64>, mut helmholtz_energy_density: ArrayViewMut1<f64>, mut first_partial_derivative: ArrayViewMut2<f64>, mut second_partial_derivative: ArrayViewMut3<f64>, ) -> FeosResult<()> { let mut wd = weighted_densities.mapv(HyperDual64::from); let t = HyperDual64::from(temperature); let mut phi = Array::zeros(weighted_densities.raw_dim().remove_axis(Axis(0))); for i in 0..wd.shape()[0] { wd.index_axis_mut(Axis(0), i).map_inplace(|x| x.eps1 = 1.0); for j in 0..=i { wd.index_axis_mut(Axis(0), j).map_inplace(|x| x.eps2 = 1.0); phi = self.helmholtz_energy_density(t, wd.view())?; let p = phi.mapv(|p| p.eps1eps2); second_partial_derivative .index_axis_mut(Axis(0), i) .index_axis_mut(Axis(0), j) .assign(&p); if i != j { second_partial_derivative .index_axis_mut(Axis(0), j) .index_axis_mut(Axis(0), i) .assign(&p); } wd.index_axis_mut(Axis(0), j).map_inplace(|x| x.eps2 = 0.0); } first_partial_derivative .index_axis_mut(Axis(0), i) .assign(&phi.mapv(|p| p.eps1)); wd.index_axis_mut(Axis(0), i).map_inplace(|x| x.eps1 = 0.0); } helmholtz_energy_density.assign(&phi.mapv(|p| p.re)); Ok(()) } }
Rust
3D
feos-org/feos
crates/feos-dft/src/functional.rs
.rs
9,679
265
use crate::convolver::Convolver; use crate::functional_contribution::*; use crate::ideal_chain_contribution::IdealChainContribution; use crate::weight_functions::{WeightFunction, WeightFunctionInfo, WeightFunctionShape}; use feos_core::{EquationOfState, FeosResult, Residual, ResidualDyn, StateHD}; use nalgebra::{DVector, dvector}; use ndarray::*; use num_dual::*; use petgraph::Directed; use petgraph::graph::{Graph, UnGraph}; use petgraph::visit::EdgeRef; use std::borrow::Cow; use std::ops::{Deref, MulAssign}; impl<I: Clone, F: HelmholtzEnergyFunctionalDyn> HelmholtzEnergyFunctionalDyn for EquationOfState<Vec<I>, F> { type Contribution<'a> = F::Contribution<'a> where Self: 'a; fn contributions<'a>(&'a self) -> impl Iterator<Item = Self::Contribution<'a>> { self.residual.contributions() } fn molecule_shape(&self) -> MoleculeShape<'_> { self.residual.molecule_shape() } fn bond_lengths<N: DualNum<f64> + Copy>(&self, temperature: N) -> UnGraph<(), N> { self.residual.bond_lengths(temperature) } } /// Different representations for molecules within DFT. pub enum MoleculeShape<'a> { /// For spherical molecules, the number of components. Spherical(usize), /// For non-spherical molecules in a homosegmented approach, the /// chain length parameter $m$. NonSpherical(&'a DVector<f64>), /// For non-spherical molecules in a heterosegmented approach, /// the component index for every segment. Heterosegmented(&'a DVector<usize>), } /// A general Helmholtz energy functional. pub trait HelmholtzEnergyFunctionalDyn: ResidualDyn { type Contribution<'a>: FunctionalContribution where Self: 'a; /// Return a slice of [FunctionalContribution]s. fn contributions<'a>(&'a self) -> impl Iterator<Item = Self::Contribution<'a>>; /// Return the shape of the molecules and the necessary specifications. fn molecule_shape(&self) -> MoleculeShape<'_>; /// Overwrite this, if the functional consists of heterosegmented chains. fn bond_lengths<N: DualNum<f64> + Copy>(&self, _temperature: N) -> UnGraph<(), N> { Graph::with_capacity(0, 0) } } /// A general Helmholtz energy functional. pub trait HelmholtzEnergyFunctional: Residual { type Contribution<'a>: FunctionalContribution where Self: 'a; /// Return a slice of [FunctionalContribution]s. fn contributions<'a>(&'a self) -> impl Iterator<Item = Self::Contribution<'a>>; /// Return the shape of the molecules and the necessary specifications. fn molecule_shape(&self) -> MoleculeShape<'_>; /// Overwrite this, if the functional consists of heterosegmented chains. fn bond_lengths<N: DualNum<f64> + Copy>(&self, _temperature: N) -> UnGraph<(), N> { Graph::with_capacity(0, 0) } fn weight_functions(&self, temperature: f64) -> Vec<WeightFunctionInfo<f64>> { self.contributions() .map(|c| c.weight_functions(temperature)) .collect() } fn m(&self) -> Cow<'_, [f64]> { match self.molecule_shape() { MoleculeShape::Spherical(n) => Cow::Owned(vec![1.0; n]), MoleculeShape::NonSpherical(m) => Cow::Borrowed(m.as_slice()), MoleculeShape::Heterosegmented(component_index) => { Cow::Owned(vec![1.0; component_index.len()]) } } } fn component_index(&self) -> Cow<'_, [usize]> { match self.molecule_shape() { MoleculeShape::Spherical(n) => Cow::Owned((0..n).collect()), MoleculeShape::NonSpherical(m) => Cow::Owned((0..m.len()).collect()), MoleculeShape::Heterosegmented(component_index) => { Cow::Borrowed(component_index.as_slice()) } } } fn ideal_chain_contribution(&self) -> IdealChainContribution { IdealChainContribution::new(&self.component_index(), &self.m()) } /// Calculate the (residual) intrinsic functional derivative $\frac{\delta\mathcal{\beta F}}{\delta\rho_i(\mathbf{r})}$. #[expect(clippy::type_complexity)] fn functional_derivative<D, N: DualNum<f64> + Copy>( &self, temperature: N, density: &Array<N, D::Larger>, convolver: &dyn Convolver<N, D>, ) -> FeosResult<(Array<N, D>, Array<N, D::Larger>)> where D: Dimension, D::Larger: Dimension<Smaller = D>, { let weighted_densities = convolver.weighted_densities(density); let contributions = self.contributions(); let mut partial_derivatives = Vec::new(); let mut helmholtz_energy_density = Array::zeros(density.raw_dim().remove_axis(Axis(0))); for (c, wd) in contributions.into_iter().zip(weighted_densities) { let nwd = wd.shape()[0]; let ngrid = wd.len() / nwd; let mut phi = Array::zeros(density.raw_dim().remove_axis(Axis(0))); let mut pd = Array::zeros(wd.raw_dim()); c.first_partial_derivatives( temperature, wd.into_shape_with_order((nwd, ngrid)).unwrap(), phi.view_mut().into_shape_with_order(ngrid).unwrap(), pd.view_mut().into_shape_with_order((nwd, ngrid)).unwrap(), )?; partial_derivatives.push(pd); helmholtz_energy_density += &phi; } Ok(( helmholtz_energy_density, convolver.functional_derivative(&partial_derivatives), )) } /// Calculate the bond integrals $I_{\alpha\alpha'}(\mathbf{r})$ fn bond_integrals<D, N: DualNum<f64> + Copy>( &self, temperature: N, exponential: &Array<N, D::Larger>, convolver: &dyn Convolver<N, D>, ) -> Array<N, D::Larger> where D: Dimension, D::Larger: Dimension<Smaller = D>, { // calculate weight functions let bond_lengths = self.bond_lengths(temperature).into_edge_type(); let mut bond_weight_functions = bond_lengths.map( |_, _| (), |_, &l| WeightFunction::new_scaled(dvector![l], WeightFunctionShape::Delta), ); for n in bond_lengths.node_indices() { for e in bond_lengths.edges(n) { bond_weight_functions.add_edge( e.target(), e.source(), WeightFunction::new_scaled(dvector![*e.weight()], WeightFunctionShape::Delta), ); } } let mut i_graph: Graph<_, Option<Array<N, D>>, Directed> = bond_weight_functions.map(|_, _| (), |_, _| None); let bonds = i_graph.edge_count(); let mut calc = 0; // go through the whole graph until every bond has been calculated while calc < bonds { let mut edge_id = None; let mut i1 = None; // find the first bond that can be calculated 'nodes: for node in i_graph.node_indices() { for edge in i_graph.edges(node) { // skip already calculated bonds if edge.weight().is_some() { continue; } // if all bonds from the neighboring segment are calculated calculate the bond let edges = i_graph .edges(edge.target()) .filter(|e| e.target().index() != node.index()); if edges.clone().all(|e| e.weight().is_some()) { edge_id = Some(edge.id()); let i0 = edges.fold( exponential .index_axis(Axis(0), edge.target().index()) .to_owned(), |acc: Array<N, D>, e| acc * e.weight().as_ref().unwrap(), ); i1 = Some(convolver.convolve(i0, &bond_weight_functions[edge.id()])); break 'nodes; } } } if let Some(edge_id) = edge_id { i_graph[edge_id] = i1; calc += 1; } else { panic!("Cycle in molecular structure detected!") } } let mut i = Array::ones(exponential.raw_dim()); for node in i_graph.node_indices() { for edge in i_graph.edges(node) { i.index_axis_mut(Axis(0), node.index()) .mul_assign(edge.weight().as_ref().unwrap()); } } i } fn evaluate_bulk<D: DualNum<f64> + Copy>(&self, state: &StateHD<D>) -> Vec<(&'static str, D)> { let mut res: Vec<_> = self .contributions() .map(|c| (c.name(), c.bulk_helmholtz_energy_density(state))) .collect(); res.push(( "Ideal chain", self.ideal_chain_contribution() .bulk_helmholtz_energy_density(&state.partial_density), )); res } } impl<C: Deref<Target = F> + Clone, F: HelmholtzEnergyFunctionalDyn + ResidualDyn + 'static> HelmholtzEnergyFunctional for C { type Contribution<'a> = F::Contribution<'a> where Self: 'a; fn contributions<'a>(&'a self) -> impl Iterator<Item = Self::Contribution<'a>> { F::contributions(self.deref()) } fn molecule_shape(&self) -> MoleculeShape<'_> { F::molecule_shape(self.deref()) } fn bond_lengths<N: DualNum<f64> + Copy>(&self, temperature: N) -> UnGraph<(), N> { F::bond_lengths(self.deref(), temperature) } }
Rust
3D
feos-org/feos
crates/feos-dft/src/solver.rs
.rs
26,911
783
use crate::{ DFTProfile, FunctionalContribution, HelmholtzEnergyFunctional, WeightFunction, WeightFunctionShape, }; use feos_core::{FeosError, FeosResult, ReferenceSystem, Verbosity, log_iter, log_result}; use nalgebra::{DMatrix, DVector, dvector}; use ndarray::RemoveAxis; use ndarray::prelude::*; use petgraph::Directed; use petgraph::graph::Graph; use petgraph::visit::EdgeRef; use quantity::{SECOND, Time}; use std::collections::VecDeque; use std::fmt; use std::ops::AddAssign; use std::time::{Duration, Instant}; const DEFAULT_PARAMS_PICARD: PicardIteration = PicardIteration { log: false, max_iter: 500, tol: 1e-11, damping_coefficient: None, }; const DEFAULT_PARAMS_ANDERSON_LOG: AndersonMixing = AndersonMixing { log: true, max_iter: 50, tol: 1e-5, damping_coefficient: 0.15, mmax: 100, }; const DEFAULT_PARAMS_ANDERSON: AndersonMixing = AndersonMixing { log: false, max_iter: 150, tol: 1e-11, damping_coefficient: 0.15, mmax: 100, }; const DEFAULT_PARAMS_NEWTON: Newton = Newton { log: false, max_iter: 50, max_iter_gmres: 200, tol: 1e-11, }; #[derive(Clone, Copy, Debug)] struct PicardIteration { log: bool, max_iter: usize, tol: f64, damping_coefficient: Option<f64>, } #[derive(Clone, Copy, Debug)] struct AndersonMixing { log: bool, max_iter: usize, tol: f64, damping_coefficient: f64, mmax: usize, } #[derive(Clone, Copy, Debug)] struct Newton { log: bool, max_iter: usize, max_iter_gmres: usize, tol: f64, } #[derive(Clone, Copy)] enum DFTAlgorithm { PicardIteration(PicardIteration), AndersonMixing(AndersonMixing), Newton(Newton), } /// Settings for the DFT solver. #[derive(Clone)] pub struct DFTSolver { algorithms: Vec<DFTAlgorithm>, pub verbosity: Verbosity, } impl Default for DFTSolver { fn default() -> Self { Self { algorithms: vec![ DFTAlgorithm::AndersonMixing(DEFAULT_PARAMS_ANDERSON_LOG), DFTAlgorithm::AndersonMixing(DEFAULT_PARAMS_ANDERSON), ], verbosity: Default::default(), } } } impl DFTSolver { pub fn new(verbosity: Option<Verbosity>) -> Self { Self { algorithms: vec![], verbosity: verbosity.unwrap_or_default(), } } pub fn picard_iteration( mut self, log: Option<bool>, max_iter: Option<usize>, tol: Option<f64>, damping_coefficient: Option<f64>, ) -> Self { let mut params = DEFAULT_PARAMS_PICARD; params.log = log.unwrap_or(params.log); params.max_iter = max_iter.unwrap_or(params.max_iter); params.tol = tol.unwrap_or(params.tol); params.damping_coefficient = damping_coefficient; self.algorithms.push(DFTAlgorithm::PicardIteration(params)); self } pub fn anderson_mixing( mut self, log: Option<bool>, max_iter: Option<usize>, tol: Option<f64>, damping_coefficient: Option<f64>, mmax: Option<usize>, ) -> Self { let mut params = DEFAULT_PARAMS_ANDERSON; params.log = log.unwrap_or(params.log); params.max_iter = max_iter.unwrap_or(params.max_iter); params.tol = tol.unwrap_or(params.tol); params.damping_coefficient = damping_coefficient.unwrap_or(params.damping_coefficient); params.mmax = mmax.unwrap_or(params.mmax); self.algorithms.push(DFTAlgorithm::AndersonMixing(params)); self } pub fn newton( mut self, log: Option<bool>, max_iter: Option<usize>, max_iter_gmres: Option<usize>, tol: Option<f64>, ) -> Self { let mut params = DEFAULT_PARAMS_NEWTON; params.log = log.unwrap_or(params.log); params.max_iter = max_iter.unwrap_or(params.max_iter); params.max_iter_gmres = max_iter_gmres.unwrap_or(params.max_iter_gmres); params.tol = tol.unwrap_or(params.tol); self.algorithms.push(DFTAlgorithm::Newton(params)); self } } /// A log that stores the residuals and execution time of DFT solvers. #[derive(Clone)] pub struct DFTSolverLog { verbosity: Verbosity, start_time: Instant, residual: Vec<f64>, time: Vec<Duration>, solver: Vec<&'static str>, } impl DFTSolverLog { pub(crate) fn new(verbosity: Verbosity) -> Self { log_iter!( verbosity, "solver | iter | time | residual " ); Self { verbosity, start_time: Instant::now(), residual: Vec::new(), time: Vec::new(), solver: Vec::new(), } } fn add_residual(&mut self, solver: &'static str, iteration: usize, residual: f64) { if iteration == 0 { log_iter!(self.verbosity, "{:-<59}", ""); } self.solver.push(solver); self.residual.push(residual); let time = self.start_time.elapsed(); self.time.push(self.start_time.elapsed()); log_iter!( self.verbosity, "{:22} | {:>4} | {:7.3} | {:.6e}", solver, iteration, time.as_secs_f64() * SECOND, residual, ); } pub fn residual(&self) -> ArrayView1<'_, f64> { (&self.residual).into() } pub fn time(&self) -> Time<Array1<f64>> { self.time.iter().map(|t| t.as_secs_f64() * SECOND).collect() } pub fn solver(&self) -> &[&'static str] { &self.solver } } impl<D: Dimension, F: HelmholtzEnergyFunctional> DFTProfile<D, F> where D::Larger: Dimension<Smaller = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { pub(crate) fn call_solver( &mut self, rho: &mut Array<f64, D::Larger>, rho_bulk: &mut Array1<f64>, solver: &DFTSolver, debug: bool, ) -> FeosResult<()> { let mut converged = false; let mut iterations = 0; let mut log = DFTSolverLog::new(solver.verbosity); for algorithm in &solver.algorithms { let (conv, iter) = match algorithm { DFTAlgorithm::PicardIteration(picard) => { self.solve_picard(*picard, rho, rho_bulk, &mut log) } DFTAlgorithm::AndersonMixing(anderson) => { self.solve_anderson(*anderson, rho, rho_bulk, &mut log) } DFTAlgorithm::Newton(newton) => self.solve_newton(*newton, rho, rho_bulk, &mut log), }?; converged = conv; iterations += iter; } self.solver_log = Some(log); if converged { log_result!(solver.verbosity, "DFT solved in {} iterations", iterations); } else if debug { log_result!( solver.verbosity, "DFT not converged in {} iterations", iterations ); } else { return Err(FeosError::NotConverged(String::from("DFT"))); } Ok(()) } fn solve_picard( &self, picard: PicardIteration, rho: &mut Array<f64, D::Larger>, rho_bulk: &mut Array1<f64>, log: &mut DFTSolverLog, ) -> FeosResult<(bool, usize)> { let solver = if picard.log { "Picard iteration (log)" } else { "Picard iteration" }; for k in 0..picard.max_iter { // calculate residual let (res, res_bulk, res_norm, _, _) = self.euler_lagrange_equation(&*rho, &*rho_bulk, picard.log)?; log.add_residual(solver, k, res_norm); // check for convergence if res_norm < picard.tol { return Ok((true, k)); } // apply line search or constant damping let damping_coefficient = picard.damping_coefficient.map_or_else( || self.line_search(rho, &res, rho_bulk, res_norm, picard.log), Ok, )?; // update solution if picard.log { *rho *= &(&res * damping_coefficient).mapv(f64::exp); *rho_bulk *= &(&res_bulk * damping_coefficient).mapv(f64::exp); } else { *rho += &(&res * damping_coefficient); *rho_bulk += &(&res_bulk * damping_coefficient); } } Ok((false, picard.max_iter)) } fn line_search( &self, rho: &Array<f64, D::Larger>, delta_rho: &Array<f64, D::Larger>, rho_bulk: &Array1<f64>, res0: f64, logarithm: bool, ) -> FeosResult<f64> { let mut alpha = 2.0; // reduce step until a feasible solution is found for _ in 0..8 { alpha *= 0.5; // calculate full step let rho_new = if logarithm { rho * (alpha * delta_rho).mapv(f64::exp) } else { rho + alpha * delta_rho }; let Ok((_, _, res2, _, _)) = self.euler_lagrange_equation(&rho_new, rho_bulk, logarithm) else { continue; }; if res2 > res0 { continue; } // calculate intermediate step let rho_new = if logarithm { rho * (0.5 * alpha * delta_rho).mapv(f64::exp) } else { rho + 0.5 * alpha * delta_rho }; let Ok((_, _, res1, _, _)) = self.euler_lagrange_equation(&rho_new, rho_bulk, logarithm) else { continue; }; // estimate minimum let mut alpha_opt = if res2 - 2.0 * res1 + res0 != 0.0 { alpha * 0.25 * (res2 - 4.0 * res1 + 3.0 * res0) / (res2 - 2.0 * res1 + res0) } else { continue; }; // prohibit negative steps if alpha_opt <= 0.0 { alpha_opt = if res1 < res2 { 0.5 * alpha } else { alpha }; } // prohibit too large steps if alpha_opt > alpha { alpha_opt = alpha; } alpha = alpha_opt; break; } // log_iter!(verbosity, " Line search | {} | ", alpha); Ok(alpha) } fn solve_anderson( &self, anderson: AndersonMixing, rho: &mut Array<f64, D::Larger>, rho_bulk: &mut Array1<f64>, log: &mut DFTSolverLog, ) -> FeosResult<(bool, usize)> { let solver = if anderson.log { "Anderson mixing (log)" } else { "Anderson mixing" }; let mut resm = VecDeque::with_capacity(anderson.mmax); let mut rhom = VecDeque::with_capacity(anderson.mmax); let mut r; let mut alpha; for k in 0..anderson.max_iter { // drop old values if resm.len() == anderson.mmax { resm.pop_front(); rhom.pop_front(); } let m = resm.len() + 1; // calculate residual let (res, res_bulk, res_norm, _, _) = self.euler_lagrange_equation(&*rho, &*rho_bulk, anderson.log)?; log.add_residual(solver, k, res_norm); // check for convergence if res_norm < anderson.tol { return Ok((true, k)); } // save residual and x value resm.push_back((res, res_bulk, res_norm)); if anderson.log { rhom.push_back((rho.mapv(f64::ln), rho_bulk.mapv(f64::ln))); } else { rhom.push_back((rho.clone(), rho_bulk.clone())); } // calculate alpha r = DMatrix::from_fn(m + 1, m + 1, |i, j| match (i == m, j == m) { (false, false) => { let (resi, resi_bulk, _) = &resm[i]; let (resj, resj_bulk, _) = &resm[j]; (resi * resj).sum() + (resi_bulk * resj_bulk).sum() } (true, true) => 0.0, _ => 1.0, }); alpha = DVector::zeros(m + 1); alpha[m] = 1.0; let alpha = r.lu().solve(&alpha); let alpha = alpha.ok_or(FeosError::Error("alpha matrix is not invertible".into()))?; // update solution rho.fill(0.0); rho_bulk.fill(0.0); for i in 0..m { let (rhoi, rhoi_bulk) = &rhom[i]; let (resi, resi_bulk, _) = &resm[i]; *rho += &(alpha[i] * (rhoi + &(anderson.damping_coefficient * resi))); *rho_bulk += &(alpha[i] * (rhoi_bulk + &(anderson.damping_coefficient * resi_bulk))); } if anderson.log { rho.mapv_inplace(f64::exp); rho_bulk.mapv_inplace(f64::exp); } else { rho.mapv_inplace(f64::abs); rho_bulk.mapv_inplace(f64::abs); } } Ok((false, anderson.max_iter)) } fn solve_newton( &self, newton: Newton, rho: &mut Array<f64, D::Larger>, rho_bulk: &mut Array1<f64>, log: &mut DFTSolverLog, ) -> FeosResult<(bool, usize)> { let solver = if newton.log { "Newton (log)" } else { "Newton" }; for k in 0..newton.max_iter { // calculate initial residual let (res, _, res_norm, exp_dfdrho, rho_p) = self.euler_lagrange_equation(rho, rho_bulk, newton.log)?; log.add_residual(solver, k, res_norm); // check convergence if res_norm < newton.tol { return Ok((true, k)); } // calculate second partial derivatives once let second_partial_derivatives = self.second_partial_derivatives(rho)?; // define rhs function let rhs = |delta_rho: &_| { let mut delta_functional_derivative = self.delta_functional_derivative(delta_rho, &second_partial_derivatives); delta_functional_derivative .outer_iter_mut() .zip(self.bulk.eos.m().iter()) .for_each(|(mut q, &m)| q /= m); let delta_i = self.delta_bond_integrals(&exp_dfdrho, &delta_functional_derivative); let rho = if newton.log { &*rho } else { &rho_p }; delta_rho + (delta_functional_derivative - delta_i) * rho }; // update solution let lhs = if newton.log { &*rho * res } else { res }; *rho += &Self::gmres(rhs, &lhs, newton.max_iter_gmres, newton.tol * 1e-2, log)?; rho.mapv_inplace(f64::abs); rho_bulk.mapv_inplace(f64::abs); } Ok((false, newton.max_iter)) } pub(crate) fn gmres<R>( rhs: R, r0: &Array<f64, D::Larger>, max_iter: usize, tol: f64, log: &mut DFTSolverLog, ) -> FeosResult<Array<f64, D::Larger>> where R: Fn(&Array<f64, D::Larger>) -> Array<f64, D::Larger>, { // allocate vectors and arrays let mut v = Vec::with_capacity(max_iter); let mut h: Array2<f64> = Array::zeros([max_iter + 1; 2]); let mut c: Array1<f64> = Array::zeros(max_iter + 1); let mut s: Array1<f64> = Array::zeros(max_iter + 1); let mut gamma: Array1<f64> = Array::zeros(max_iter + 1); gamma[0] = (r0 * r0).sum().sqrt(); v.push(r0 / gamma[0]); log.add_residual("GMRES", 0, gamma[0]); let mut iter = 0; for j in 0..max_iter { // calculate q=Av_j let mut q = rhs(&v[j]); // calculate h_ij v.iter() .enumerate() .for_each(|(i, v_i)| h[(i, j)] = (v_i * &q).sum()); // calculate w_j (stored in q) v.iter() .enumerate() .for_each(|(i, v_i)| q -= &(h[(i, j)] * v_i)); h[(j + 1, j)] = (&q * &q).sum().sqrt(); // update h_ij and h_i+1j if j > 0 { for i in 0..=j - 1 { let temp = c[i + 1] * h[(i, j)] + s[i + 1] * h[(i + 1, j)]; h[(i + 1, j)] = -s[i + 1] * h[(i, j)] + c[i + 1] * h[(i + 1, j)]; h[(i, j)] = temp; } } // update auxiliary variables let beta = (h[(j, j)] * h[(j, j)] + h[(j + 1, j)] * h[(j + 1, j)]).sqrt(); s[j + 1] = h[(j + 1, j)] / beta; c[j + 1] = h[(j, j)] / beta; h[(j, j)] = beta; gamma[j + 1] = -s[j + 1] * gamma[j]; gamma[j] *= c[j + 1]; // check for convergence log.add_residual("GMRES", j + 1, gamma[j + 1].abs()); if gamma[j + 1].abs() >= tol && j + 1 < max_iter { v.push(q / h[(j + 1, j)]); iter += 1; } else { break; } } // calculate solution vector let mut x = Array::zeros(r0.raw_dim()); let mut y = Array::zeros(iter + 1); for i in (0..=iter).rev() { y[i] = (gamma[i] - (i + 1..=iter).map(|k| h[(i, k)] * y[k]).sum::<f64>()) / h[(i, i)]; } v.iter().zip(y).for_each(|(v, y)| x += &(y * v)); Ok(x) } pub(crate) fn second_partial_derivatives( &self, density: &Array<f64, D::Larger>, ) -> FeosResult<Vec<Array<f64, <D::Larger as Dimension>::Larger>>> { let temperature = self.temperature.to_reduced(); let contributions = self.bulk.eos.contributions(); let weighted_densities = self.convolver.weighted_densities(density); let mut second_partial_derivatives = Vec::new(); for (c, wd) in contributions.into_iter().zip(&weighted_densities) { let nwd = wd.shape()[0]; let ngrid = wd.len() / nwd; let mut phi = Array::zeros(density.raw_dim().remove_axis(Axis(0))); let mut pd = Array::zeros(wd.raw_dim()); let dim = wd.shape(); let dim: Vec<_> = std::iter::once(&nwd).chain(dim).cloned().collect(); let mut pd2 = Array::zeros(dim).into_dimensionality().unwrap(); c.second_partial_derivatives( temperature, wd.view().into_shape_with_order((nwd, ngrid)).unwrap(), phi.view_mut().into_shape_with_order(ngrid).unwrap(), pd.view_mut().into_shape_with_order((nwd, ngrid)).unwrap(), pd2.view_mut() .into_shape_with_order((nwd, nwd, ngrid)) .unwrap(), )?; second_partial_derivatives.push(pd2); } Ok(second_partial_derivatives) } pub(crate) fn delta_functional_derivative( &self, delta_density: &Array<f64, D::Larger>, second_partial_derivatives: &[Array<f64, <D::Larger as Dimension>::Larger>], ) -> Array<f64, D::Larger> { let delta_weighted_densities = self.convolver.weighted_densities(delta_density); let delta_partial_derivatives: Vec<_> = second_partial_derivatives .iter() .zip(delta_weighted_densities) .map(|(pd2, wd)| { let mut delta_partial_derivatives = Array::zeros(pd2.raw_dim().remove_axis(Axis(0))); let n = wd.shape()[0]; for i in 0..n { for j in 0..n { delta_partial_derivatives .index_axis_mut(Axis(0), i) .add_assign( &(&pd2.index_axis(Axis(0), i).index_axis(Axis(0), j) * &wd.index_axis(Axis(0), j)), ); } } delta_partial_derivatives }) .collect(); self.convolver .functional_derivative(&delta_partial_derivatives) } pub(crate) fn delta_bond_integrals( &self, exponential: &Array<f64, D::Larger>, delta_functional_derivative: &Array<f64, D::Larger>, ) -> Array<f64, D::Larger> { let temperature = self.temperature.to_reduced(); // calculate weight functions let bond_lengths = self.bulk.eos.bond_lengths(temperature).into_edge_type(); let mut bond_weight_functions = bond_lengths.map( |_, _| (), |_, &l| WeightFunction::new_scaled(dvector![l], WeightFunctionShape::Delta), ); for n in bond_lengths.node_indices() { for e in bond_lengths.edges(n) { bond_weight_functions.add_edge( e.target(), e.source(), WeightFunction::new_scaled(dvector![*e.weight()], WeightFunctionShape::Delta), ); } } let mut i_graph: Graph<_, Option<Array<f64, D>>, Directed> = bond_weight_functions.map(|_, _| (), |_, _| None); let mut delta_i_graph: Graph<_, Option<Array<f64, D>>, Directed> = bond_weight_functions.map(|_, _| (), |_, _| None); let bonds = i_graph.edge_count(); let mut calc = 0; // go through the whole graph until every bond has been calculated while calc < bonds { let mut edge_id = None; let mut i1 = None; let mut delta_i1 = None; // find the first bond that can be calculated 'nodes: for node in i_graph.node_indices() { for edge in i_graph.edges(node) { // skip already calculated bonds if edge.weight().is_some() { continue; } // if all bonds from the neighboring segment are calculated calculate the bond let edges = i_graph .edges(edge.target()) .filter(|e| e.target().index() != node.index()); let delta_edges = delta_i_graph .edges(edge.target()) .filter(|e| e.target().index() != node.index()); if edges.clone().all(|e| e.weight().is_some()) { edge_id = Some(edge.id()); let i0 = edges.fold( exponential .index_axis(Axis(0), edge.target().index()) .to_owned(), |acc: Array<f64, _>, e| acc * e.weight().as_ref().unwrap(), ); let delta_i0 = delta_edges.fold( -&delta_functional_derivative .index_axis(Axis(0), edge.target().index()), |acc: Array<f64, _>, delta_e| acc + delta_e.weight().as_ref().unwrap(), ) * &i0; i1 = Some( self.convolver .convolve(i0, &bond_weight_functions[edge.id()]), ); delta_i1 = Some( (self .convolver .convolve(delta_i0, &bond_weight_functions[edge.id()]) / i1.as_ref().unwrap()) .mapv(|x| if x.is_finite() { x } else { 0.0 }), ); break 'nodes; } } } if let Some(edge_id) = edge_id { i_graph[edge_id] = i1; delta_i_graph[edge_id] = delta_i1; calc += 1; } else { panic!("Cycle in molecular structure detected!") } } let mut delta_i = Array::zeros(exponential.raw_dim()); for node in delta_i_graph.node_indices() { for edge in delta_i_graph.edges(node) { delta_i .index_axis_mut(Axis(0), node.index()) .add_assign(edge.weight().as_ref().unwrap()); } } delta_i } } impl fmt::Display for DFTAlgorithm { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::PicardIteration(picard) => write!(f, "{picard:?}"), Self::AndersonMixing(anderson) => write!(f, "{anderson:?}"), Self::Newton(newton) => write!(f, "{newton:?}"), } } } impl fmt::Display for DFTSolver { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DFTSolver(")?; for algorithm in &self.algorithms { writeln!(f, " {algorithm}")?; } writeln!(f, ")") } } impl DFTSolver { pub fn _repr_markdown_(&self) -> String { let mut res = String::from("|solver|max_iter|tol|\n|-|-:|-:|"); for algorithm in &self.algorithms { let (solver, max_iter, tol) = match algorithm { DFTAlgorithm::PicardIteration(picard) => ( format!( "Picard iteration ({}{})", if picard.log { "log, " } else { "" }, match picard.damping_coefficient { None => "line search".into(), Some(damping_coefficient) => format!("damping_coefficient={damping_coefficient}"), } ), picard.max_iter, picard.tol, ), DFTAlgorithm::AndersonMixing(anderson) => ( format!( "Anderson mixing ({}damping_coefficient={}, mmax={})", if anderson.log { "log, " } else { "" }, anderson.damping_coefficient, anderson.mmax ), anderson.max_iter, anderson.tol, ), DFTAlgorithm::Newton(newton) => ( format!( "Newton ({}max_iter_gmres={})", if newton.log { "log, " } else { "" }, newton.max_iter_gmres ), newton.max_iter, newton.tol, ), }; res += &format!("\n|{solver}|{max_iter}|{tol:e}|"); } res } }
Rust
3D
feos-org/feos
crates/feos-dft/src/geometry.rs
.rs
7,820
237
use feos_core::ReferenceSystem; use ndarray::{Array1, Array2}; use quantity::{Angle, Length, Quantity}; use std::f64::consts::{FRAC_PI_3, PI}; /// Grids with up to three dimensions. #[derive(Clone)] pub enum Grid { Cartesian1(Axis), Cartesian2(Axis, Axis), Periodical2(Axis, Axis, Angle), Cartesian3(Axis, Axis, Axis), Periodical3(Axis, Axis, Axis, [Angle; 3]), Spherical(Axis), Polar(Axis), Cylindrical { r: Axis, z: Axis }, } impl Grid { pub fn new_1d(axis: Axis) -> Self { match axis.geometry { Geometry::Cartesian => Self::Cartesian1(axis), Geometry::Cylindrical => Self::Polar(axis), Geometry::Spherical => Self::Spherical(axis), } } pub fn axes(&self) -> Vec<&Axis> { match self { Self::Cartesian1(x) => vec![x], Self::Cartesian2(x, y) | Self::Periodical2(x, y, _) => vec![x, y], Self::Cartesian3(x, y, z) | Self::Periodical3(x, y, z, _) => vec![x, y, z], Self::Spherical(r) | Self::Polar(r) => vec![r], Self::Cylindrical { r, z } => vec![r, z], } } pub fn axes_mut(&mut self) -> Vec<&mut Axis> { match self { Self::Cartesian1(x) => vec![x], Self::Cartesian2(x, y) | Self::Periodical2(x, y, _) => vec![x, y], Self::Cartesian3(x, y, z) | Self::Periodical3(x, y, z, _) => vec![x, y, z], Self::Spherical(r) | Self::Polar(r) => vec![r], Self::Cylindrical { r, z } => vec![r, z], } } pub fn grids(&self) -> Vec<&Array1<f64>> { self.axes().iter().map(|ax| &ax.grid).collect() } pub(crate) fn integration_weights(&self) -> (Vec<&Array1<f64>>, f64) { ( self.axes() .iter() .map(|ax| &ax.integration_weights) .collect(), self.functional_determinant(), ) } pub(crate) fn functional_determinant(&self) -> f64 { match &self { Self::Periodical2(_, _, alpha) => alpha.sin(), Self::Periodical3(_, _, _, [alpha, beta, gamma]) => { let xi = (alpha.cos() - gamma.cos() * beta.cos()) / gamma.sin(); gamma.sin() * (1.0 - beta.cos().powi(2) - xi * xi).sqrt() } _ => 1.0, } } } /// Geometries of individual axes. #[derive(Copy, Clone, PartialEq)] pub enum Geometry { Cartesian, Cylindrical, Spherical, } impl Geometry { /// Return the number of spatial dimensions for this geometry. pub fn dimension(&self) -> i32 { match self { Self::Cartesian => 1, Self::Cylindrical => 2, Self::Spherical => 3, } } } /// An individual discretized axis. #[derive(Clone)] pub struct Axis { pub geometry: Geometry, pub grid: Array1<f64>, pub edges: Array1<f64>, integration_weights: Array1<f64>, potential_offset: f64, } impl Axis { /// Create a new (equidistant) cartesian axis. /// /// The potential_offset is required to make sure that particles /// can not interact through walls. pub fn new_cartesian(points: usize, length: Length, potential_offset: Option<f64>) -> Self { let potential_offset = potential_offset.unwrap_or(0.0); let l = length.to_reduced() + potential_offset; let cell_size = l / points as f64; let grid = Array1::linspace(0.5 * cell_size, l - 0.5 * cell_size, points); let edges = Array1::linspace(0.0, l, points + 1); let integration_weights = Array1::from_elem(points, cell_size); Self { geometry: Geometry::Cartesian, grid, edges, integration_weights, potential_offset, } } /// Create a new (equidistant) spherical axis. pub fn new_spherical(points: usize, length: Length) -> Self { let l = length.to_reduced(); let cell_size = l / points as f64; let grid = Array1::linspace(0.5 * cell_size, l - 0.5 * cell_size, points); let edges = Array1::linspace(0.0, l, points + 1); let integration_weights = Array1::from_shape_fn(points, |k| { 4.0 * FRAC_PI_3 * cell_size.powi(3) * (3 * k * k + 3 * k + 1) as f64 }); Self { geometry: Geometry::Spherical, grid, edges, integration_weights, potential_offset: 0.0, } } /// Create a new logarithmically scaled cylindrical axis. pub fn new_polar(points: usize, length: Length) -> Self { let l = length.to_reduced(); let mut alpha = 0.002_f64; for _ in 0..20 { alpha = -(1.0 - (-alpha).exp()).ln() / (points - 1) as f64; } let x0 = 0.5 * ((-alpha * points as f64).exp() + (-alpha * (points - 1) as f64).exp()); let grid = (0..points) .map(|i| l * x0 * (alpha * i as f64).exp()) .collect(); let edges = (0..=points) .map(|i| { if i == 0 { 0.0 } else { l * (-alpha * (points - i) as f64).exp() } }) .collect(); let k0 = (2.0 * alpha).exp() * (2.0 * alpha.exp() + (2.0 * alpha).exp() - 1.0) / ((1.0 + alpha.exp()).powi(2) * ((2.0 * alpha).exp() - 1.0)); let integration_weights = (0..points) .map(|i| { (match i { 0 => k0 * (2.0 * alpha).exp(), 1 => ((2.0 * alpha).exp() - k0) * (2.0 * alpha).exp(), _ => (2.0 * alpha * i as f64).exp() * ((2.0 * alpha).exp() - 1.0), }) * ((-2.0 * alpha * points as f64).exp() * PI * l * l) }) .collect(); Self { geometry: Geometry::Cylindrical, grid, edges, integration_weights, potential_offset: 0.0, } } /// Returns the total length of the axis. /// /// This includes the `potential_offset` and used e.g. /// to determine the correct frequency vector in FFT. pub fn length(&self) -> f64 { self.edges[self.grid.len()] - self.edges[0] } /// Returns the volume of the axis. /// /// Depending on the geometry, the result is in m, m² or m³. /// The `potential_offset` is not included in the volume, as /// it is mainly used to calculate excess properties. pub fn volume(&self) -> f64 { let length = self.edges[self.grid.len()] - self.potential_offset - self.edges[0]; (match self.geometry { Geometry::Cartesian => 1.0, Geometry::Cylindrical => 4.0 * PI, Geometry::Spherical => 4.0 * FRAC_PI_3, }) * length.powi(self.geometry.dimension()) } /// Interpolate a function on the given axis. pub fn interpolate<U>( &self, x: f64, y: &Quantity<Array2<f64>, U>, i: usize, ) -> Quantity<f64, U> { let n = self.grid.len(); y.get(( i, if x >= self.edges[n] { n - 1 } else { match self.geometry { Geometry::Cartesian | Geometry::Spherical => (x / self.edges[1]) as usize, Geometry::Cylindrical => { if x < self.edges[1] { 0 } else { (n as f64 - (n - 1) as f64 * (x / self.edges[n]).ln() / (self.edges[1] / self.edges[n]).ln()) as usize } } } }, )) } }
Rust
3D
feos-org/feos
crates/feos-dft/src/weight_functions.rs
.rs
12,516
327
use nalgebra::DVector; use ndarray::*; use num_dual::DualNum; // use rustfft::num_complex::Complex; use std::f64::consts::{FRAC_PI_3, PI}; use std::ops::Mul; /// A weight function corresponding to a single weighted density. #[derive(Clone)] pub struct WeightFunction<T> { /// Factor in front of normalized weight function pub prefactor: DVector<T>, /// Kernel radius of the convolution pub kernel_radius: DVector<T>, /// Shape of the weight function (Dirac delta, Heaviside, etc.) pub shape: WeightFunctionShape, } impl<T: DualNum<f64> + Copy> WeightFunction<T> { /// Create a new weight function without prefactor pub fn new_unscaled(kernel_radius: DVector<T>, shape: WeightFunctionShape) -> Self { Self { prefactor: DVector::from_element(kernel_radius.len(), T::one()), kernel_radius, shape, } } /// Create a new weight function with weight constant = 1 pub fn new_scaled(kernel_radius: DVector<T>, shape: WeightFunctionShape) -> Self { let unscaled = Self::new_unscaled(kernel_radius, shape); let weight_constants = unscaled.scalar_weight_constants(T::zero()); let weight_constants = DVector::from(weight_constants.to_vec()); Self { prefactor: weight_constants.map(|w| w.recip()), kernel_radius: unscaled.kernel_radius, shape, } } /// Calculates the value of the scalar weight function depending on its shape /// `k_abs` describes the absolute value of the Fourier variable pub(crate) fn fft_scalar_weight_functions<D: Dimension, T2: DualNum<f64>>( &self, k_abs: &Array<T2, D>, lanczos: &Option<Array<T2, D>>, ) -> Array<T, D::Larger> where T: Mul<T2, Output = T>, D::Larger: Dimension<Smaller = D>, { // Allocate vector for weight functions let mut d = vec![self.prefactor.len()]; k_abs.shape().iter().for_each(|&x| d.push(x)); let mut w = Array::zeros(d.into_dimension()) .into_dimensionality() .unwrap(); // Calculate weight function for each component for i in 0..self.prefactor.len() { let radius = self.kernel_radius[i]; let p = self.prefactor[i]; let rik = k_abs.mapv(|k| radius * k); let mut w_i = w.index_axis_mut(Axis(0), i); w_i.assign(&match self.shape { WeightFunctionShape::Theta => rik.mapv(|rik| { (rik.sph_j0() + rik.sph_j2()) * 4.0 * FRAC_PI_3 * radius.powi(3) * p }), WeightFunctionShape::Delta => { rik.mapv(|rik| rik.sph_j0() * 4.0 * PI * radius.powi(2) * p) } WeightFunctionShape::KR1 => { rik.mapv(|rik| (rik.sph_j0() + rik.cos()) * 0.5 * radius * p) } WeightFunctionShape::KR0 => rik.mapv(|rik| (rik * rik.sin() * 0.5 + rik.cos()) * p), WeightFunctionShape::DeltaVec => unreachable!(), }); // Apply Lanczos sigma factor if let Some(l) = lanczos { let w_i_l = &w_i * l; w_i.assign(&w_i_l); } } // Return real part of weight function w } /// Calculates the value of the vector weight function depending on its shape /// `k_abs` describes the absolute value of the Fourier variable /// `k` describes the (potentially multi-dimensional) Fourier variable pub(crate) fn fft_vector_weight_functions<D: Dimension, T2: DualNum<f64>>( &self, k_abs: &Array<T2, D>, k: &Array<T2, D::Larger>, lanczos: &Option<Array<T2, D>>, ) -> Array<T, <D::Larger as Dimension>::Larger> where D::Larger: Dimension<Smaller = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, T: Mul<T2, Output = T>, { // Allocate vector for weight functions let mut d = vec![k.shape()[0], self.prefactor.len()]; k.shape().iter().skip(1).for_each(|&x| d.push(x)); let mut w = Array::zeros(d.into_dimension()) .into_dimensionality() .unwrap(); // Iterate all dimensions for (k_x, mut w_x) in k.outer_iter().zip(w.outer_iter_mut()) { // Calculate weight function for each component for i in 0..self.prefactor.len() { let radius = self.kernel_radius[i]; let p = self.prefactor[i]; let rik = k_abs.mapv(|k| radius * k); let mut w_i = w_x.index_axis_mut(Axis(0), i); w_i.assign(&match self.shape { WeightFunctionShape::DeltaVec => { &rik.mapv(|rik| { (rik.sph_j0() + rik.sph_j2()) * (radius.powi(3) * 4.0 * FRAC_PI_3 * p) }) * &k_x } _ => unreachable!(), }); // Apply Lanczos sigma factor if let Some(l) = lanczos { let w_i_l = &w_i * l; w_i.assign(&w_i_l) } } } // Return imaginary part of weight function w } /// Scalar weights for the bulk convolver (for the bulk convolver only the prefactor /// of the normalized weight functions are required) pub fn scalar_weight_constants(&self, k: T) -> Array1<T> { let k = arr0(k); self.fft_scalar_weight_functions(&k, &None) } /// Vector weights for the bulk convolver (for the bulk convolver only the prefactor /// of the normalized weight functions are required) pub fn vector_weight_constants(&self, k: T) -> Array1<T> { let k_abs = arr0(k); let k = arr1(&[k]); self.fft_vector_weight_functions(&k_abs, &k, &None) .index_axis_move(Axis(0), 0) } } /// Possible weight function shapes. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum WeightFunctionShape { /// Heaviside step function Theta, /// Dirac delta function Delta, /// Combination of first & second derivative of Dirac delta function (with different prefactor; only in Kierlik-Rosinberg functional) KR0, /// First derivative of Dirac delta function (with different prefactor; only in Kierlik-Rosinberg functional) KR1, /// Vector-shape as combination of Dirac delta and outward normal DeltaVec, } /// Information about weight functions pub struct WeightFunctionInfo<T> { /// Index of the component that each individual segment belongs to. pub(crate) component_index: DVector<usize>, /// Flag if local density is required in the functional pub(crate) local_density: bool, /// Container for scalar component-wise weighted densities pub(crate) scalar_component_weighted_densities: Vec<WeightFunction<T>>, /// Container for vector component-wise weighted densities pub(crate) vector_component_weighted_densities: Vec<WeightFunction<T>>, /// Container for scalar FMT weighted densities pub(crate) scalar_fmt_weighted_densities: Vec<WeightFunction<T>>, /// Container for vector FMT weighted densities pub(crate) vector_fmt_weighted_densities: Vec<WeightFunction<T>>, } impl<T> WeightFunctionInfo<T> { /// Calculates the total number of weighted densities for each functional /// from multiple weight functions depending on dimension. pub fn n_weighted_densities(&self, dimensions: usize) -> usize { let segments = self.component_index.len(); (if self.local_density { segments } else { 0 }) + self.scalar_component_weighted_densities.len() * segments + self.vector_component_weighted_densities.len() * segments * dimensions + self.scalar_fmt_weighted_densities.len() + self.vector_fmt_weighted_densities.len() * dimensions } } impl<T> WeightFunctionInfo<T> { /// Initializing empty `WeightFunctionInfo`. pub fn new(component_index: DVector<usize>, local_density: bool) -> Self { Self { component_index, local_density, scalar_component_weighted_densities: Vec::new(), vector_component_weighted_densities: Vec::new(), scalar_fmt_weighted_densities: Vec::new(), vector_fmt_weighted_densities: Vec::new(), } } /// Adds and sorts [WeightFunction] depending on information /// about {FMT, component} & {scalar-valued, vector-valued}. pub fn add(mut self, weight_function: WeightFunction<T>, fmt: bool) -> Self { let segments = self.component_index.len(); // Check size of `kernel_radius` if segments != weight_function.kernel_radius.len() { panic!( "Number of segments is fixed to {}; `kernel_radius` has {} entries.", segments, weight_function.kernel_radius.len() ); } // Check size of `prefactor` if segments != weight_function.prefactor.len() { panic!( "Number of segments is fixed to {}; `prefactor` has {} entries.", segments, weight_function.prefactor.len() ); } // Add new `WeightFunction` match (fmt, weight_function.shape) { // {Component, vector} (false, WeightFunctionShape::DeltaVec) => self .vector_component_weighted_densities .push(weight_function), // {Component, scalar} (false, _) => self .scalar_component_weighted_densities .push(weight_function), // {FMT, vector} (true, WeightFunctionShape::DeltaVec) => { self.vector_fmt_weighted_densities.push(weight_function) } // {FMT, scalar} (true, _) => self.scalar_fmt_weighted_densities.push(weight_function), }; // Return self } /// Adds and sorts multiple [WeightFunction]s. pub fn extend(mut self, weight_functions: Vec<WeightFunction<T>>, fmt: bool) -> Self { // Add each element of vector for wf in weight_functions { self = self.add(wf, fmt); } // Return self } /// Expose weight functions outside of this crate pub fn as_slice(&self) -> [&Vec<WeightFunction<T>>; 4] { [ &self.scalar_component_weighted_densities, &self.vector_component_weighted_densities, &self.scalar_fmt_weighted_densities, &self.vector_fmt_weighted_densities, ] } } impl<T: DualNum<f64> + Copy> WeightFunctionInfo<T> { /// calculates the matrix of weight constants for this set of weighted densities pub fn weight_constants(&self, k: T, dimensions: usize) -> Array2<T> { let segments = self.component_index.len(); let n_wd = self.n_weighted_densities(dimensions); let mut weight_constants = Array::zeros([n_wd, segments]); let mut j = 0; if self.local_density { weight_constants .slice_mut(s![j..j + segments, ..]) .into_diag() .assign(&Array::ones(segments)); j += segments; } for w in &self.scalar_component_weighted_densities { weight_constants .slice_mut(s![j..j + segments, ..]) .into_diag() .assign(&w.scalar_weight_constants(k)); j += segments; } if dimensions == 1 { for w in &self.vector_component_weighted_densities { weight_constants .slice_mut(s![j..j + segments, ..]) .into_diag() .assign(&w.vector_weight_constants(k)); j += segments; } } for w in &self.scalar_fmt_weighted_densities { weight_constants .slice_mut(s![j, ..]) .assign(&w.scalar_weight_constants(k)); j += 1; } if dimensions == 1 { for w in &self.vector_fmt_weighted_densities { weight_constants .slice_mut(s![j, ..]) .assign(&w.vector_weight_constants(k)); j += 1; } } weight_constants } }
Rust
3D
feos-org/feos
crates/feos-dft/src/pdgt.rs
.rs
10,682
291
use super::functional::HelmholtzEnergyFunctional; use super::functional_contribution::FunctionalContribution; use super::weight_functions::WeightFunctionInfo; use feos_core::{Contributions, FeosResult, PhaseEquilibrium, ReferenceSystem}; use nalgebra::DVector; use ndarray::*; use num_dual::Dual2_64; use quantity::{ _Area, _Density, _MolarEnergy, Density, Length, Pressure, Quantity, RGAS, SurfaceTension, Temperature, }; use std::ops::{Add, AddAssign, Sub}; type Sum<T1, T2> = <T1 as Add<T2>>::Output; type Diff<T1, T2> = <T1 as Sub<T2>>::Output; type _InfluenceParameter = Diff<Sum<_MolarEnergy, _Area>, _Density>; type InfluenceParameter<T> = Quantity<T, _InfluenceParameter>; impl WeightFunctionInfo<Dual2_64> { fn pdgt_weight_constants(&self) -> (Array2<f64>, Array2<f64>, Array2<f64>) { let k = Dual2_64::from(0.0).derivative(); let w = self.weight_constants(k, 1); (w.mapv(|w| w.re), w.mapv(|w| -w.v1), w.mapv(|w| -0.5 * w.v2)) } } trait PdgtProperties: FunctionalContribution { #[expect(clippy::too_many_arguments)] fn pdgt_properties( &self, temperature: f64, density: &Array2<f64>, helmholtz_energy_density: &mut Array1<f64>, first_partial_derivatives: Option<&mut Array2<f64>>, second_partial_derivatives: Option<&mut Array3<f64>>, influence_diagonal: Option<&mut Array2<f64>>, influence_matrix: Option<&mut Array3<f64>>, ) -> FeosResult<()> { // calculate weighted densities let weight_functions = self.weight_functions_pdgt(Dual2_64::from(temperature)); let (w0, w1, w2) = weight_functions.pdgt_weight_constants(); let weighted_densities = w0.dot(density); // calculate Helmholtz energy and derivatives let w = weighted_densities.shape()[0]; // # of weighted densities let s = density.shape()[0]; // # of segments let n = density.shape()[1]; // # of grid points let mut df = Array::zeros((w, n)); let mut d2f = Array::zeros((w, w, n)); self.second_partial_derivatives( temperature, weighted_densities.view(), helmholtz_energy_density.view_mut(), df.view_mut(), d2f.view_mut(), )?; // calculate partial derivatives w.r.t. density if let Some(df_drho) = first_partial_derivatives { df_drho.assign(&df.t().dot(&w0)); } // calculate second partial derivatives w.r.t. density if let Some(d2f_drho2) = second_partial_derivatives { for i in 0..s { for j in 0..s { for alpha in 0..w { for beta in 0..w { d2f_drho2 .index_axis_mut(Axis(0), i) .index_axis_mut(Axis(0), j) .add_assign( &(&d2f.index_axis(Axis(0), alpha).index_axis(Axis(0), beta) * w0[(alpha, i)] * w0[(beta, j)]), ); } } } } } // calculate influence diagonal if let Some(c) = influence_diagonal { for i in 0..s { for alpha in 0..w { for beta in 0..w { c.index_axis_mut(Axis(0), i).add_assign( &(&d2f.index_axis(Axis(0), alpha).index_axis(Axis(0), beta) * (w1[(alpha, i)] * w1[(beta, i)] - w0[(alpha, i)] * w2[(beta, i)] - w2[(alpha, i)] * w0[(beta, i)])), ); } } } } // calculate influence matrix if let Some(c) = influence_matrix { for i in 0..s { for j in 0..s { for alpha in 0..w { for beta in 0..w { c.index_axis_mut(Axis(0), i) .index_axis_mut(Axis(0), j) .add_assign( &(&d2f.index_axis(Axis(0), alpha).index_axis(Axis(0), beta) * (w1[(alpha, i)] * w1[(beta, j)] - w0[(alpha, i)] * w2[(beta, j)] - w2[(alpha, i)] * w0[(beta, j)])), ); } } } } } Ok(()) } #[expect(clippy::type_complexity)] fn influence_diagonal( &self, temperature: Temperature, density: &Density<Array2<f64>>, ) -> FeosResult<(Pressure<Array1<f64>>, InfluenceParameter<Array2<f64>>)> { let t = temperature.to_reduced(); let n = density.shape()[1]; let mut f = Array::zeros(n); let mut c = Array::zeros(density.raw_dim()); self.pdgt_properties( t, &density.to_reduced(), &mut f, None, None, Some(&mut c), None, )?; Ok(( Pressure::from_reduced(f * t), InfluenceParameter::from_reduced(c * t), )) } } impl<T: FunctionalContribution> PdgtProperties for T {} pub trait PdgtFunctionalProperties: HelmholtzEnergyFunctional { // impl<T: HelmholtzEnergyFunctional> T { fn solve_pdgt( &self, vle: &PhaseEquilibrium<Self, 2>, n_grid: usize, reference_component: usize, z: Option<(&mut Length<Array1<f64>>, &mut Length)>, ) -> FeosResult<(Density<Array2<f64>>, SurfaceTension)> { // calculate density profile let density = if self.components() == 1 { let delta_rho = (vle.vapor().density - vle.liquid().density) / (n_grid + 1) as f64; Density::linspace( vle.liquid().density + delta_rho, vle.vapor().density - delta_rho, n_grid, ) .insert_axis(Axis(0)) } else { self.pdgt_density_profile_mix(vle, n_grid, reference_component)? }; // calculate Helmholtz energy density and influence parameter let mut delta_omega = Pressure::zeros(n_grid); let mut influence_diagonal = InfluenceParameter::zeros(density.raw_dim()); for contribution in self.contributions() { let (f, c) = contribution.influence_diagonal(vle.vapor().temperature, &density)?; delta_omega += &f; influence_diagonal += &c; } delta_omega += &self .ideal_chain_contribution() .helmholtz_energy_density_units::<Ix1>(vle.vapor().temperature, &density)?; // calculate excess grand potential density let mu_res = vle.vapor().residual_chemical_potential(); for i in 0..self.components() { let rhoi = density.index_axis(Axis(0), i).to_owned(); let rhoi_b = vle.vapor().partial_density.get(i); let mui_res = mu_res.get(i); let kt = RGAS * vle.vapor().temperature; delta_omega += &(&rhoi * (&((&rhoi / rhoi_b).into_value().mapv(f64::ln) - 1.0) * kt - mui_res)); } delta_omega += vle.vapor().pressure(Contributions::Total); // calculate density gradients w.r.t. reference density let dx = density.get((reference_component, 0)) - density.get((reference_component, 1)); let drho = gradient( &density, -dx, &vle.liquid().partial_density, &vle.vapor().partial_density, ); // calculate integrand let gamma_int = ((influence_diagonal * delta_omega.clone() * 2.0).mapv(Quantity::sqrt) * drho) .sum_axis(Axis(0)); // calculate z-axis if let Some((z, w)) = z { let z_int = gamma_int.clone() / (delta_omega * 2.0); *z = integrate_trapezoidal_cumulative(&z_int, dx); // calculate equimolar surface let rho_v = density.index_axis(Axis(1), 0).sum(); let rho_l = density.index_axis(Axis(1), n_grid - 1).sum(); let rho_r = (density.sum_axis(Axis(0)) - rho_v) / (rho_l - rho_v); let ze = integrate_trapezoidal(&rho_r * &z_int, dx); // calculate interfacial width let w_temp = integrate_trapezoidal(&rho_r * &*z * z_int, dx); *w = (24.0 * (w_temp - 0.5 * ze.powi::<2>())).sqrt(); // shift density profile *z -= ze; } // integration weights (First and last points are 0) let mut weights = Array::ones(n_grid); weights[0] = 7.0 / 6.0; weights[1] = 23.0 / 24.0; weights[n_grid - 2] = 23.0 / 24.0; weights[n_grid - 1] = 7.0 / 6.0; let weights = &weights * dx; // calculate surface tension Ok((density, (gamma_int * weights).sum())) } fn pdgt_density_profile_mix( &self, _vle: &PhaseEquilibrium<Self, 2>, _n_grid: usize, _reference_component: usize, ) -> FeosResult<Density<Array2<f64>>> { unimplemented!() } } impl<T: HelmholtzEnergyFunctional> PdgtFunctionalProperties for T {} fn gradient<UF: Sub<UX>, UX: Copy>( df: &Quantity<Array2<f64>, UF>, dx: Quantity<f64, UX>, left: &Quantity<DVector<f64>, UF>, right: &Quantity<DVector<f64>, UF>, ) -> Quantity<Array2<f64>, Diff<UF, UX>> { Quantity::from_shape_fn(df.raw_dim(), |(c, i)| { let d = if i == 0 { df.get((c, 1)) - left.get(c) } else if i == df.len() - 1 { right.get(c) - df.get((c, df.len() - 2)) } else { df.get((c, i + 1)) - df.get((c, i - 1)) }; d / (2.0 * dx) }) } pub fn integrate_trapezoidal<UF: Add<UX>, UX>( f: Quantity<Array1<f64>, UF>, dx: Quantity<f64, UX>, ) -> Quantity<f64, Sum<UF, UX>> { let mut weights = Array::ones(f.len()); weights[0] = 0.5; weights[f.len() - 1] = 0.5; (&f * &(&weights * dx)).sum() } pub fn integrate_trapezoidal_cumulative<UF: Add<UX>, UX>( f: &Quantity<Array1<f64>, UF>, dx: Quantity<f64, UX>, ) -> Quantity<Array1<f64>, Sum<UF, UX>> { let mut value = Quantity::zeros(f.len()); for i in 1..value.len() { value.set(i, value.get(i - 1) + (f.get(i - 1) + f.get(i)) * 0.5); } value * dx }
Rust
3D
feos-org/feos
crates/feos-dft/src/ideal_chain_contribution.rs
.rs
2,072
71
use feos_core::{FeosResult, ReferenceSystem}; use nalgebra::DVector; use ndarray::*; use num_dual::DualNum; use quantity::{Density, Pressure, Temperature}; #[derive(Clone)] pub struct IdealChainContribution { component_index: DVector<usize>, m: DVector<f64>, } impl IdealChainContribution { pub fn new(component_index: &[usize], m: &[f64]) -> Self { Self { component_index: DVector::from_column_slice(component_index), m: DVector::from_column_slice(m), } } pub fn bulk_helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, partial_density: &DVector<D>, ) -> D { let segments = self.component_index.len(); if self.component_index[segments - 1] + 1 != segments { return D::zero(); } // calculate segment density let density = self.component_index.map(|c| partial_density[c]); // calculate Helmholtz energy density .component_mul(&self.m.add_scalar(-1.0).map(D::from)) .dot(&density.map(|r| (r.abs() + D::from(f64::EPSILON)).ln() - 1.0)) } pub fn helmholtz_energy_density<D, N>( &self, density: &Array<N, D::Larger>, ) -> FeosResult<Array<N, D>> where D: Dimension, D::Larger: Dimension<Smaller = D>, N: DualNum<f64>, { let mut phi = Array::zeros(density.raw_dim().remove_axis(Axis(0))); for (i, rhoi) in density.outer_iter().enumerate() { phi += &rhoi.mapv(|rhoi| (rhoi.ln() - 1.0) * (self.m[i] - 1.0) * rhoi); } Ok(phi) } pub fn helmholtz_energy_density_units<D>( &self, temperature: Temperature, density: &Density<Array<f64, D::Larger>>, ) -> FeosResult<Pressure<Array<f64, D>>> where D: Dimension, D::Larger: Dimension<Smaller = D>, { let rho = density.to_reduced(); let t = temperature.to_reduced(); Ok(Pressure::from_reduced( self.helmholtz_energy_density(&rho)? * t, )) } }
Rust
3D
feos-org/feos
crates/feos-dft/src/interface/mod.rs
.rs
15,578
423
//! Density profiles at planar interfaces and interfacial tensions. use crate::functional::HelmholtzEnergyFunctional; use crate::geometry::{Axis, Grid}; use crate::pdgt::PdgtFunctionalProperties; use crate::profile::{DFTProfile, DFTSpecifications}; use crate::solver::DFTSolver; use feos_core::{Contributions, FeosError, FeosResult, PhaseEquilibrium, ReferenceSystem}; use ndarray::{Array1, Array2, Axis as Axis_nd, Ix1, s}; use quantity::{Area, Density, Length, Moles, SurfaceTension, Temperature}; use std::sync::Arc; mod surface_tension_diagram; pub use surface_tension_diagram::SurfaceTensionDiagram; const RELATIVE_WIDTH: f64 = 6.0; const MIN_WIDTH: f64 = 100.0; /// Density profile and properties of a planar interface. #[derive(Clone)] pub struct PlanarInterface<F: HelmholtzEnergyFunctional> { pub profile: DFTProfile<Ix1, F>, pub vle: PhaseEquilibrium<F, 2>, pub surface_tension: Option<SurfaceTension>, pub equimolar_radius: Option<Length>, } impl<F: HelmholtzEnergyFunctional> PlanarInterface<F> { pub fn solve_inplace(&mut self, solver: Option<&DFTSolver>, debug: bool) -> FeosResult<()> { // Solve the profile self.profile.solve(solver, debug)?; // postprocess self.surface_tension = Some( (self.profile.integrate( &(self.profile.grand_potential_density()? + self.vle.vapor().pressure(Contributions::Total)), )) / Area::from_reduced(1.0), ); let delta_rho = self.vle.liquid().density - self.vle.vapor().density; self.equimolar_radius = Some( self.profile .integrate(&(self.profile.density.sum_axis(Axis_nd(0)) - self.vle.vapor().density)) / delta_rho / Area::from_reduced(1.0), ); Ok(()) } pub fn solve(mut self, solver: Option<&DFTSolver>) -> FeosResult<Self> { self.solve_inplace(solver, false)?; Ok(self) } } impl<F: HelmholtzEnergyFunctional> PlanarInterface<F> { pub fn new(vle: &PhaseEquilibrium<F, 2>, n_grid: usize, l_grid: Length) -> Self { // generate grid let grid = Grid::Cartesian1(Axis::new_cartesian(n_grid, l_grid, None)); Self { profile: DFTProfile::new(grid, vle.vapor(), None, None, None), vle: vle.clone(), surface_tension: None, equimolar_radius: None, } } pub fn from_tanh( vle: &PhaseEquilibrium<F, 2>, n_grid: usize, l_grid: Length, critical_temperature: Temperature, fix_equimolar_surface: bool, ) -> Self { let mut profile = Self::new(vle, n_grid, l_grid); // calculate segment indices let indices = &profile.profile.bulk.eos.component_index(); // calculate density profile let z0 = 0.5 * l_grid.to_reduced(); let (z0, sign) = (z0.abs(), -z0.signum()); let reduced_temperature = (vle.vapor().temperature / critical_temperature).into_value(); profile.profile.density = Density::from_shape_fn(profile.profile.density.raw_dim(), |(i, z)| { let rho_v = profile.vle.vapor().partial_density.get(indices[i]); let rho_l = profile.vle.liquid().partial_density.get(indices[i]); 0.5 * (rho_l - rho_v) * (sign * (profile.profile.grid.grids()[0][z] - z0) / 3.0 * (2.4728 - 2.3625 * reduced_temperature)) .tanh() + 0.5 * (rho_l + rho_v) }); // specify specification if fix_equimolar_surface { profile.profile.specification = Arc::new(DFTSpecifications::total_moles_from_profile( &profile.profile, )); } profile } pub fn from_pdgt( vle: &PhaseEquilibrium<F, 2>, n_grid: usize, fix_equimolar_surface: bool, ) -> FeosResult<Self> { let dft = &vle.vapor().eos; if dft.component_index().len() != 1 { panic!("Initialization from pDGT not possible for segment DFT or mixtures"); } // calculate density profile from pDGT let n_grid_pdgt = 20; let mut z_pdgt = Length::zeros(n_grid_pdgt); let mut w_pdgt = Length::from_reduced(0.0); let (rho_pdgt, gamma_pdgt) = dft.solve_pdgt(vle, 20, 0, Some((&mut z_pdgt, &mut w_pdgt)))?; if !gamma_pdgt.to_reduced().is_normal() { return Err(FeosError::InvalidState( String::from("DFTProfile::from_pdgt"), String::from("gamma_pdgt"), gamma_pdgt.to_reduced(), )); } // create PlanarInterface let l_grid = Length::from_reduced(MIN_WIDTH).max(w_pdgt * RELATIVE_WIDTH); let mut profile = Self::new(vle, n_grid, l_grid); // interpolate density profile from pDGT to DFT let r = l_grid * 0.5; profile.profile.density = interp_symmetric( vle, z_pdgt, rho_pdgt, &profile.vle, profile.profile.grid.grids()[0], r, )?; // specify specification if fix_equimolar_surface { profile.profile.specification = Arc::new(DFTSpecifications::total_moles_from_profile( &profile.profile, )); } Ok(profile) } } impl<F: HelmholtzEnergyFunctional> PlanarInterface<F> { pub fn shift_equimolar_inplace(&mut self) { let s = self.profile.density.shape(); let m = &self.profile.bulk.eos.m(); let mut rho_l = Density::from_reduced(0.0); let mut rho_v = Density::from_reduced(0.0); let mut rho = Density::zeros(s[1]); for i in 0..s[0] { rho_l += self.profile.density.get((i, 0)) * m[i]; rho_v += self.profile.density.get((i, s[1] - 1)) * m[i]; rho += &(&self.profile.density.index_axis(Axis_nd(0), i) * m[i]); } let x = (rho - rho_v) / (rho_l - rho_v); let ze = self.profile.grid.axes()[0].edges[0] + self.profile.integrate(&x).to_reduced(); self.profile.grid.axes_mut()[0].grid -= ze; } pub fn shift_equimolar(mut self) -> Self { self.shift_equimolar_inplace(); self } /// Relative adsorption of component `i' with respect to `j': \Gamma_i^(j) pub fn relative_adsorption(&self) -> Moles<Array2<f64>> { let s = self.profile.density.shape(); let mut rho_l = Density::zeros(s[0]); let mut rho_v = Density::zeros(s[0]); // Calculate the partial densities in the liquid and in the vapor phase for i in 0..s[0] { rho_l.set(i, self.profile.density.get((i, 0))); rho_v.set(i, self.profile.density.get((i, s[1] - 1))); } // Calculate \Gamma_i^(j) Moles::from_shape_fn((s[0], s[0]), |(i, j)| { if i == j { Moles::from_reduced(0.0) } else { self.profile.integrate( &(-(rho_l.get(i) - rho_v.get(i)) * ((&self.profile.density.index_axis(Axis_nd(0), j) - rho_l.get(j)) / (rho_l.get(j) - rho_v.get(j)) - (&self.profile.density.index_axis(Axis_nd(0), i) - rho_l.get(i)) / (rho_l.get(i) - rho_v.get(i)))), ) } }) } /// Interfacial enrichment of component `i': E_i pub fn interfacial_enrichment(&self) -> Array1<f64> { let s = self.profile.density.shape(); let density = self.profile.density.to_reduced(); let rho_l = density.index_axis(Axis_nd(1), 0); let rho_v = density.index_axis(Axis_nd(1), s[1] - 1); Array1::from_shape_fn(s[0], |i| { *(density .index_axis(Axis_nd(0), i) .iter() .max_by(|&a, &b| a.total_cmp(b)) .unwrap()) // panics only of iterator is empty / rho_l[i].max(rho_v[i]) }) } /// Interface thickness (90-10 number density difference) pub fn interfacial_thickness(&self) -> FeosResult<Length> { let s = self.profile.density.shape(); let rho = self.profile.density.sum_axis(Axis_nd(0)).to_reduced(); let z = self.profile.grid.grids()[0]; let dz = z[1] - z[0]; let limits = (0.9_f64, 0.1_f64); let (limit_upper, limit_lower) = if limits.0 > limits.1 { (limits.0, limits.1) } else { (limits.1, limits.0) }; if limit_upper >= 1.0 || limit_upper.is_sign_negative() { return Err(FeosError::IterationFailed(String::from( "Upper limit 'l' of interface thickness needs to satisfy 0 < l < 1.", ))); } if limit_lower >= 1.0 || limit_lower.is_sign_negative() { return Err(FeosError::IterationFailed(String::from( "Lower limit 'l' of interface thickness needs to satisfy 0 < l < 1.", ))); } // Get the densities in the liquid and in the vapor phase let rho_v = rho[0].min(rho[s[1] - 1]); let rho_l = rho[0].max(rho[s[1] - 1]); if (rho_l - rho_v).abs() < 1.0e-10 { return Ok(Length::from_reduced(0.0)); } // Density boundaries for interface definition let rho_upper = rho_v + limit_upper * (rho_l - rho_v); let rho_lower = rho_v + limit_lower * (rho_l - rho_v); // Get indizes right of intersection between density profile and // constant density boundaries let index_upper_plus = if rho[0] >= rho[s[1] - 1] { rho.iter() .enumerate() .find(|&(_, &x)| (x - rho_upper).is_sign_negative()) .expect("Could not find rho_upper value!") .0 } else { rho.iter() .enumerate() .find(|&(_, &x)| (rho_upper - x).is_sign_negative()) .expect("Could not find rho_upper value!") .0 }; let index_lower_plus = if rho[0] >= rho[s[1] - 1] { rho.iter() .enumerate() .find(|&(_, &x)| (x - rho_lower).is_sign_negative()) .expect("Could not find rho_lower value!") .0 } else { rho.iter() .enumerate() .find(|&(_, &x)| (rho_lower - x).is_sign_negative()) .expect("Could not find rho_lower value!") .0 }; // Calculate distance between two density points using a linear // interpolated density profiles between the two grid points where the // density profile crosses the limiting densities let z_upper = z[index_upper_plus - 1] + (rho_upper - rho[index_upper_plus - 1]) / (rho[index_upper_plus] - rho[index_upper_plus - 1]) * dz; let z_lower = z[index_lower_plus - 1] + (rho_lower - rho[index_lower_plus - 1]) / (rho[index_lower_plus] - rho[index_lower_plus - 1]) * dz; // Return Ok(Length::from_reduced(z_lower - z_upper)) } fn set_density_scale(&mut self, init: &Density<Array2<f64>>) { assert_eq!(self.profile.density.shape(), init.shape()); let n_grid = self.profile.density.shape()[1]; let drho_init = &init.index_axis(Axis_nd(1), 0) - &init.index_axis(Axis_nd(1), n_grid - 1); let rho_init_0 = init.index_axis(Axis_nd(1), n_grid - 1); let drho = &self.profile.density.index_axis(Axis_nd(1), 0) - &self.profile.density.index_axis(Axis_nd(1), n_grid - 1); let rho_0 = self.profile.density.index_axis(Axis_nd(1), n_grid - 1); self.profile.density = Density::from_shape_fn(self.profile.density.raw_dim(), |(i, j)| { ((init.get((i, j)) - rho_init_0.get(i)) / drho_init.get(i)).into_value() * drho.get(i) + rho_0.get(i) }); } pub fn set_density_inplace(&mut self, init: &Density<Array2<f64>>, scale: bool) { if scale { self.set_density_scale(init) } else { assert_eq!(self.profile.density.shape(), init.shape()); self.profile.density = init.clone(); } } pub fn set_density(mut self, init: &Density<Array2<f64>>, scale: bool) -> Self { self.set_density_inplace(init, scale); self } } fn interp_symmetric<F: HelmholtzEnergyFunctional>( vle_pdgt: &PhaseEquilibrium<F, 2>, z_pdgt: Length<Array1<f64>>, rho_pdgt: Density<Array2<f64>>, vle: &PhaseEquilibrium<F, 2>, z: &Array1<f64>, radius: Length, ) -> FeosResult<Density<Array2<f64>>> { let reduced_density = Array2::from_shape_fn(rho_pdgt.raw_dim(), |(i, j)| { ((rho_pdgt.get((i, j)) - vle_pdgt.vapor().partial_density.get(i)) / (vle_pdgt.liquid().partial_density.get(i) - vle_pdgt.vapor().partial_density.get(i))) .into_value() - 0.5 }); let segments = vle_pdgt.vapor().eos.component_index().len(); let mut reduced_density = interp( &z_pdgt.to_reduced(), &reduced_density, &(z - radius.to_reduced()), &Array1::from_elem(segments, 0.5), &Array1::from_elem(segments, -0.5), false, ) + interp( &z_pdgt.to_reduced(), &reduced_density, &(z + radius.to_reduced()), &Array1::from_elem(segments, -0.5), &Array1::from_elem(segments, 0.5), true, ); if radius.is_sign_negative() { reduced_density += 1.0; } Ok(Density::from_shape_fn( reduced_density.raw_dim(), |(i, j)| { reduced_density[(i, j)] * (vle.liquid().partial_density.get(i) - vle.vapor().partial_density.get(i)) + vle.vapor().partial_density.get(i) }, )) } fn interp( x_old: &Array1<f64>, y_old: &Array2<f64>, x_new: &Array1<f64>, y_left: &Array1<f64>, y_right: &Array1<f64>, reverse: bool, ) -> Array2<f64> { let n = x_old.len(); let (x_rev, y_rev) = if reverse { (-&x_old.slice(s![..;-1]), y_old.slice(s![.., ..;-1])) } else { (x_old.to_owned(), y_old.view()) }; let mut y_new = Array2::zeros((y_rev.shape()[0], x_new.len())); let mut k = 0; for i in 0..x_new.len() { while k < n && x_new[i] > x_rev[k] { k += 1; } y_new.slice_mut(s![.., i]).assign(&if k == 0 { y_left + &((&y_rev.slice(s![.., 0]) - y_left) * ((&y_rev.slice(s![.., 1]) - y_left) / (&y_rev.slice(s![.., 0]) - y_left)) .mapv(|x| x.powf((x_new[i] - x_rev[0]) / (x_rev[1] - x_rev[0])))) } else if k == n { y_right + &((&y_rev.slice(s![.., n - 2]) - y_right) * ((&y_rev.slice(s![.., n - 1]) - y_right) / (&y_rev.slice(s![.., n - 2]) - y_right)) .mapv(|x| { x.powf((x_new[i] - x_rev[n - 2]) / (x_rev[n - 1] - x_rev[n - 2])) })) } else { &y_rev.slice(s![.., k - 1]) + &((x_new[i] - x_rev[k - 1]) / (x_rev[k] - x_rev[k - 1]) * (&y_rev.slice(s![.., k]) - &y_rev.slice(s![.., k - 1]))) }); } y_new }
Rust
3D
feos-org/feos
crates/feos-dft/src/interface/surface_tension_diagram.rs
.rs
3,945
104
use super::PlanarInterface; use crate::functional::HelmholtzEnergyFunctional; use crate::solver::DFTSolver; use feos_core::{PhaseEquilibrium, ReferenceSystem, StateVec}; use ndarray::{Array1, Array2}; use quantity::{Length, Moles, SurfaceTension, Temperature}; const DEFAULT_GRID_POINTS: usize = 2048; /// Container structure for the efficient calculation of surface tension diagrams. pub struct SurfaceTensionDiagram<F: HelmholtzEnergyFunctional> { pub profiles: Vec<PlanarInterface<F>>, } // #[expect(clippy::ptr_arg)] impl<F: HelmholtzEnergyFunctional> SurfaceTensionDiagram<F> { pub fn new( dia: &[PhaseEquilibrium<F, 2>], init_densities: Option<bool>, n_grid: Option<usize>, l_grid: Option<Length>, critical_temperature: Option<Temperature>, fix_equimolar_surface: Option<bool>, solver: Option<&DFTSolver>, ) -> Self { let n_grid = n_grid.unwrap_or(DEFAULT_GRID_POINTS); let mut profiles: Vec<PlanarInterface<F>> = Vec::with_capacity(dia.len()); for vle in dia.iter() { // check for a critical point let profile = if PhaseEquilibrium::is_trivial_solution(vle.vapor(), vle.liquid()) { Ok(PlanarInterface::from_tanh( vle, 10, Length::from_reduced(100.0), Temperature::from_reduced(500.0), fix_equimolar_surface.unwrap_or(false), )) } else { // initialize with pDGT for single segments and tanh for mixtures and segment DFT if vle.vapor().eos.component_index().len() == 1 { PlanarInterface::from_pdgt(vle, n_grid, false) } else { Ok(PlanarInterface::from_tanh( vle, n_grid, l_grid.unwrap_or(Length::from_reduced(100.0)), critical_temperature.unwrap_or(Temperature::from_reduced(500.0)), fix_equimolar_surface.unwrap_or(false), )) } .map(|mut profile| { if let Some(init) = profiles.last() && init.profile.density.shape() == profile.profile.density.shape() && let Some(scale) = init_densities { profile.set_density_inplace(&init.profile.density, scale) } profile }) } .and_then(|profile| profile.solve(solver)); if let Ok(profile) = profile { profiles.push(profile); } } Self { profiles } } pub fn vapor(&self) -> StateVec<'_, F> { self.profiles.iter().map(|p| p.vle.vapor()).collect() } pub fn liquid(&self) -> StateVec<'_, F> { self.profiles.iter().map(|p| p.vle.liquid()).collect() } pub fn surface_tension(&mut self) -> SurfaceTension<Array1<f64>> { SurfaceTension::from_shape_fn(self.profiles.len(), |i| { self.profiles[i].surface_tension.unwrap() }) } pub fn relative_adsorption(&self) -> Vec<Moles<Array2<f64>>> { self.profiles .iter() .map(|planar_interf| planar_interf.relative_adsorption()) .collect() } pub fn interfacial_enrichment(&self) -> Vec<Array1<f64>> { self.profiles .iter() .map(|planar_interf| planar_interf.interfacial_enrichment()) .collect() } pub fn interfacial_thickness(&self) -> Length<Array1<f64>> { self.profiles .iter() .map(|planar_interf| planar_interf.interfacial_thickness().unwrap()) .collect() } }
Rust
3D
feos-org/feos
crates/feos-dft/src/convolver/mod.rs
.rs
27,545
686
use crate::geometry::{Axis, Geometry, Grid}; use crate::weight_functions::*; use ndarray::linalg::Dot; use ndarray::prelude::*; use ndarray::{Axis as Axis_nd, RemoveAxis, Slice}; use num_dual::*; use num_traits::Zero; use rustdct::DctNum; use std::ops::{AddAssign, MulAssign, SubAssign}; use std::sync::Arc; mod periodic_convolver; mod transform; pub use periodic_convolver::PeriodicConvolver; use transform::*; /// Trait for numerical convolutions for DFT. /// /// Covers calculation of weighted densities & functional derivatives /// from density profiles & profiles of the partial derivatives of the /// Helmholtz energy functional. /// /// Parametrized over data types `T` and dimension of the problem `D`. pub trait Convolver<T, D: Dimension>: Send + Sync { /// Convolve the profile with the given weight function. fn convolve(&self, profile: Array<T, D>, weight_function: &WeightFunction<T>) -> Array<T, D>; /// Calculate weighted densities via convolution from density profiles. fn weighted_densities(&self, density: &Array<T, D::Larger>) -> Vec<Array<T, D::Larger>>; /// Calculate the functional derivative via convolution from partial derivatives /// of the Helmholtz energy functional. fn functional_derivative( &self, partial_derivatives: &[Array<T, D::Larger>], ) -> Array<T, D::Larger>; } pub(crate) struct BulkConvolver<T> { weight_constants: Vec<Array2<T>>, } impl<T: DualNum<f64> + Copy + Send + Sync> BulkConvolver<T> { #[expect(clippy::new_ret_no_self)] pub(crate) fn new(weight_functions: Vec<WeightFunctionInfo<T>>) -> Arc<dyn Convolver<T, Ix0>> { let weight_constants = weight_functions .into_iter() .map(|w| w.weight_constants(Zero::zero(), 0)) .collect(); Arc::new(Self { weight_constants }) } } impl<T: DualNum<f64> + Copy + Send + Sync> Convolver<T, Ix0> for BulkConvolver<T> where Array2<T>: Dot<Array1<T>, Output = Array1<T>>, { fn convolve(&self, _: Array0<T>, _: &WeightFunction<T>) -> Array0<T> { unreachable!() } fn weighted_densities(&self, density: &Array1<T>) -> Vec<Array1<T>> { self.weight_constants .iter() .map(|w| w.dot(density)) .collect() } fn functional_derivative(&self, partial_derivatives: &[Array1<T>]) -> Array1<T> { self.weight_constants .iter() .zip(partial_derivatives.iter()) .map(|(w, pd)| pd.dot(w)) .reduce(|a, b| a + b) .unwrap() } } /// Base structure to hold either information about the weight function through /// `WeightFunctionInfo` or the weight functions themselves via /// `FFTWeightFunctions`. #[derive(Debug, Clone)] struct FFTWeightFunctions<T, D: Dimension> { /// Either number of components for simple functionals /// or idividual segments for group contribution methods pub(crate) segments: usize, /// Flag if local density is required in the functional pub(crate) local_density: bool, /// Container for scalar component-wise weighted densities pub(crate) scalar_component_weighted_densities: Vec<Array<T, D::Larger>>, /// Container for vector component-wise weighted densities pub(crate) vector_component_weighted_densities: Vec<Array<T, <D::Larger as Dimension>::Larger>>, /// Container for scalar FMT weighted densities pub(crate) scalar_fmt_weighted_densities: Vec<Array<T, D::Larger>>, /// Container for vector FMT weighted densities pub(crate) vector_fmt_weighted_densities: Vec<Array<T, <D::Larger as Dimension>::Larger>>, } impl<T, D: Dimension> FFTWeightFunctions<T, D> { /// Calculates the total number of weighted densities for each functional /// from multiple weight functions depending on dimension. pub fn n_weighted_densities(&self, dimensions: usize) -> usize { (if self.local_density { self.segments } else { 0 }) + self.scalar_component_weighted_densities.len() * self.segments + self.vector_component_weighted_densities.len() * self.segments * dimensions + self.scalar_fmt_weighted_densities.len() + self.vector_fmt_weighted_densities.len() * dimensions } } /// Convolver for 1-D, 2-D & 3-D systems using FFT algorithms to efficiently /// compute convolutions in Fourier space. /// /// Parametrized over the data type `T` and the dimension `D`. pub struct ConvolverFFT<T, D: Dimension> { /// k vectors k_abs: Array<f64, D>, /// Vector of weight functions for each component in multiple dimensions. weight_functions: Vec<FFTWeightFunctions<T, D>>, /// Lanczos sigma factor lanczos_sigma: Option<Array<f64, D>>, /// Possibly curvilinear Fourier transform in the first dimension transform: Box<dyn FourierTransform<T>>, /// Vector of additional cartesian Fourier transforms in the other dimensions cartesian_transforms: Vec<CartesianTransform<T>>, } impl<T, D: Dimension + RemoveAxis + 'static> ConvolverFFT<T, D> where T: DctNum + DualNum<f64>, D::Larger: Dimension<Smaller = D>, D::Smaller: Dimension<Larger = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { /// Create the appropriate FFT convolver for the given grid. pub fn plan( grid: &Grid, weight_functions: &[WeightFunctionInfo<T>], lanczos: Option<i32>, ) -> Arc<dyn Convolver<T, D>> { match grid { Grid::Polar(r) => CurvilinearConvolver::new(r, &[], weight_functions, lanczos), Grid::Spherical(r) => CurvilinearConvolver::new(r, &[], weight_functions, lanczos), Grid::Cartesian1(z) => Self::new(Some(z), &[], weight_functions, lanczos), Grid::Cylindrical { r, z } => { CurvilinearConvolver::new(r, &[z], weight_functions, lanczos) } Grid::Cartesian2(x, y) => Self::new(Some(x), &[y], weight_functions, lanczos), Grid::Periodical2(x, y, alpha) => { PeriodicConvolver::new_2d(&[x, y], *alpha, weight_functions, lanczos) } Grid::Cartesian3(x, y, z) => Self::new(Some(x), &[y, z], weight_functions, lanczos), Grid::Periodical3(x, y, z, angles) => { PeriodicConvolver::new_3d(&[x, y, z], *angles, weight_functions, lanczos) } } } } impl<T, D: Dimension + 'static> ConvolverFFT<T, D> where T: DctNum + DualNum<f64>, D::Larger: Dimension<Smaller = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { #[expect(clippy::new_ret_no_self)] fn new( axis: Option<&Axis>, cartesian_axes: &[&Axis], weight_functions: &[WeightFunctionInfo<T>], lanczos: Option<i32>, ) -> Arc<dyn Convolver<T, D>> { // initialize the Fourier transform let mut cartesian_transforms = Vec::with_capacity(cartesian_axes.len()); let mut k_vec = Vec::with_capacity(cartesian_axes.len() + 1); let mut lengths = Vec::with_capacity(cartesian_axes.len() + 1); let (transform, k_x) = match axis { Some(axis) => match axis.geometry { Geometry::Cartesian => CartesianTransform::new(axis), Geometry::Cylindrical => PolarTransform::new(axis), Geometry::Spherical => SphericalTransform::new(axis), }, None => NoTransform::new(), }; k_vec.push(k_x); lengths.push(axis.map_or(1.0, |axis| axis.length())); for ax in cartesian_axes { let (transform, k_x) = CartesianTransform::new_cartesian(ax); cartesian_transforms.push(transform); k_vec.push(k_x); lengths.push(ax.length()); } // Calculate the full k vectors let mut dim = vec![k_vec.len()]; k_vec.iter().for_each(|k_x| dim.push(k_x.len())); let mut k: Array<_, D::Larger> = Array::zeros(dim).into_dimensionality().unwrap(); let mut k_abs = Array::zeros(k.raw_dim().remove_axis(Axis(0))); for (i, (mut k_i, k_x)) in k.outer_iter_mut().zip(k_vec.iter()).enumerate() { k_i.lanes_mut(Axis_nd(i)) .into_iter() .for_each(|mut l| l.assign(k_x)); k_abs.add_assign(&k_i.mapv(|k| k.powi(2))); } k_abs.map_inplace(|k| *k = k.sqrt()); // Lanczos sigma factor let lanczos_sigma = lanczos.map(|exp| { let mut lanczos = Array::ones(k_abs.raw_dim()); for (i, (k_x, &l)) in k_vec.iter().zip(lengths.iter()).enumerate() { let points = k_x.len(); let m2 = if points % 2 == 0 { points as f64 + 2.0 } else { points as f64 + 1.0 }; let l_x = k_x.mapv(|k| (k * l / m2).sph_j0().powi(exp)); for mut l in lanczos.lanes_mut(Axis_nd(i)) { l.mul_assign(&l_x); } } lanczos }); // calculate weight functions in Fourier space and weight constants let mut fft_weight_functions = Vec::with_capacity(weight_functions.len()); for wf in weight_functions { // Calculates the weight functions values from `k_abs` // Pre-allocation of empty `Vec` let mut scal_comp = Vec::with_capacity(wf.scalar_component_weighted_densities.len()); // Filling array with scalar component-wise weight functions for wf_i in &wf.scalar_component_weighted_densities { scal_comp.push(wf_i.fft_scalar_weight_functions(&k_abs, &lanczos_sigma)); } // Pre-allocation of empty `Vec` let mut vec_comp = Vec::with_capacity(wf.vector_component_weighted_densities.len()); // Filling array with vector-valued component-wise weight functions for wf_i in &wf.vector_component_weighted_densities { vec_comp.push(wf_i.fft_vector_weight_functions(&k_abs, &k, &lanczos_sigma)); } // Pre-allocation of empty `Vec` let mut scal_fmt = Vec::with_capacity(wf.scalar_fmt_weighted_densities.len()); // Filling array with scalar FMT weight functions for wf_i in &wf.scalar_fmt_weighted_densities { scal_fmt.push(wf_i.fft_scalar_weight_functions(&k_abs, &lanczos_sigma)); } // Pre-allocation of empty `Vec` let mut vec_fmt = Vec::with_capacity(wf.vector_fmt_weighted_densities.len()); // Filling array with vector-valued FMT weight functions for wf_i in &wf.vector_fmt_weighted_densities { vec_fmt.push(wf_i.fft_vector_weight_functions(&k_abs, &k, &lanczos_sigma)); } // Initializing `FFTWeightFunctions` structure fft_weight_functions.push(FFTWeightFunctions::<_, D> { segments: wf.component_index.len(), local_density: wf.local_density, scalar_component_weighted_densities: scal_comp, vector_component_weighted_densities: vec_comp, scalar_fmt_weighted_densities: scal_fmt, vector_fmt_weighted_densities: vec_fmt, }); } // Return `FFTConvolver<T, D>` Arc::new(Self { k_abs, weight_functions: fft_weight_functions, lanczos_sigma, transform, cartesian_transforms, }) } } impl<T, D: Dimension> ConvolverFFT<T, D> where T: DctNum + DualNum<f64>, D::Larger: Dimension<Smaller = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { fn forward_transform(&self, f: ArrayView<T, D>, vector_index: Option<usize>) -> Array<T, D> { let mut dim = vec![self.k_abs.shape()[0]]; f.shape().iter().skip(1).for_each(|&d| dim.push(d)); let mut result: Array<_, D> = Array::zeros(dim.clone()).into_dimensionality().unwrap(); for (f, r) in f .lanes(Axis_nd(0)) .into_iter() .zip(result.lanes_mut(Axis_nd(0))) { self.transform .forward_transform(f, r, vector_index != Some(0)); } for (i, transform) in self.cartesian_transforms.iter().enumerate() { dim[i + 1] = self.k_abs.shape()[i + 1]; let mut res: Array<_, D> = Array::zeros(dim.clone()).into_dimensionality().unwrap(); for (f, r) in result .lanes(Axis_nd(i + 1)) .into_iter() .zip(res.lanes_mut(Axis_nd(i + 1))) { transform.forward_transform(f, r, vector_index.is_none_or(|ind| ind != i + 1)); } result = res; } result } fn forward_transform_comps( &self, f: ArrayView<T, D::Larger>, vector_index: Option<usize>, ) -> Array<T, D::Larger> { let mut dim = vec![f.shape()[0]]; self.k_abs.shape().iter().for_each(|&d| dim.push(d)); let mut result = Array::zeros(dim).into_dimensionality().unwrap(); for (f, mut r) in f.outer_iter().zip(result.outer_iter_mut()) { r.assign(&self.forward_transform(f, vector_index)); } result } fn back_transform( &self, mut f: ArrayViewMut<T, D>, mut result: ArrayViewMut<T, D>, vector_index: Option<usize>, ) { let mut dim = vec![result.shape()[0]]; f.shape().iter().skip(1).for_each(|&d| dim.push(d)); let mut res: Array<_, D> = Array::zeros(dim.clone()).into_dimensionality().unwrap(); for (f, r) in f .lanes_mut(Axis_nd(0)) .into_iter() .zip(res.lanes_mut(Axis_nd(0))) { self.transform.back_transform(f, r, vector_index != Some(0)); } for (i, transform) in self.cartesian_transforms.iter().enumerate() { dim[i + 1] = result.shape()[i + 1]; let mut res2: Array<_, D> = Array::zeros(dim.clone()).into_dimensionality().unwrap(); for (f, r) in res .lanes_mut(Axis_nd(i + 1)) .into_iter() .zip(res2.lanes_mut(Axis_nd(i + 1))) { transform.back_transform(f, r, vector_index.is_none_or(|ind| ind != i + 1)); } res = res2; } result.assign(&res); } fn back_transform_comps( &self, mut f: Array<T, D::Larger>, mut result: ArrayViewMut<T, D::Larger>, vector_index: Option<usize>, ) { for (f, r) in f.outer_iter_mut().zip(result.outer_iter_mut()) { self.back_transform(f, r, vector_index); } } } impl<T, D: Dimension> Convolver<T, D> for ConvolverFFT<T, D> where T: DctNum + DualNum<f64>, D::Larger: Dimension<Smaller = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { fn convolve(&self, profile: Array<T, D>, weight_function: &WeightFunction<T>) -> Array<T, D> { // Forward transform let f_k = self.forward_transform(profile.view(), None); // calculate weight function let w = weight_function .fft_scalar_weight_functions(&self.k_abs, &self.lanczos_sigma) .index_axis_move(Axis(0), 0); // Inverse transform let mut result = Array::zeros(profile.raw_dim()); self.back_transform((f_k * w).view_mut(), result.view_mut(), None); result } fn weighted_densities(&self, density: &Array<T, D::Larger>) -> Vec<Array<T, D::Larger>> { // Applying FFT to each row of the matrix `rho` saving the result in `rho_k` let rho_k = self.forward_transform_comps(density.view(), None); // Iterate over all contributions let mut weighted_densities_vec = Vec::with_capacity(self.weight_functions.len()); for wf in &self.weight_functions { // number of weighted densities let n_wd = wf.n_weighted_densities(density.ndim() - 1); // Allocating new array for intended weighted densities let mut dim = vec![n_wd]; density.shape().iter().skip(1).for_each(|&d| dim.push(d)); let mut weighted_densities = Array::zeros(dim).into_dimensionality().unwrap(); // Initilaizing row index for non-local weighted densities let mut k = 0; // Assigning possible local densities to the front of the array if wf.local_density { weighted_densities .slice_axis_mut(Axis(0), Slice::from(0..wf.segments)) .assign(density); k += wf.segments; } // Calculating weighted densities {scalar, component} for wf_i in &wf.scalar_component_weighted_densities { self.back_transform_comps( &rho_k * wf_i, weighted_densities.slice_axis_mut(Axis(0), Slice::from(k..k + wf.segments)), None, ); k += wf.segments; } // Calculating weighted densities {vector, component} for wf_i in &wf.vector_component_weighted_densities { for (i, wf_i) in wf_i.outer_iter().enumerate() { self.back_transform_comps( &rho_k * &wf_i, weighted_densities.slice_axis_mut(Axis(0), Slice::from(k..k + wf.segments)), Some(i), ); k += wf.segments; } } // Calculating weighted densities {scalar, FMT} for wf_i in &wf.scalar_fmt_weighted_densities { self.back_transform( (&rho_k * wf_i).sum_axis(Axis(0)).view_mut(), weighted_densities.index_axis_mut(Axis(0), k), None, ); k += 1; } // Calculating weighted densities {vector, FMT} for wf_i in &wf.vector_fmt_weighted_densities { for (i, wf_i) in wf_i.outer_iter().enumerate() { self.back_transform( (&rho_k * &wf_i).sum_axis(Axis(0)).view_mut(), weighted_densities.index_axis_mut(Axis(0), k), Some(i), ); k += 1; } } // add weighted densities for this contribution to the result weighted_densities_vec.push(weighted_densities); } // Return weighted_densities_vec } fn functional_derivative( &self, partial_derivatives: &[Array<T, D::Larger>], ) -> Array<T, D::Larger> { // Allocate arrays for the result, the local contribution to the functional derivative, // the functional derivative in Fourier space, and the bulk contributions let mut dim = vec![self.weight_functions[0].segments]; partial_derivatives[0] .shape() .iter() .skip(1) .for_each(|&d| dim.push(d)); let mut functional_deriv = Array::zeros(dim).into_dimensionality().unwrap(); let mut functional_deriv_local = Array::zeros(functional_deriv.raw_dim()); let mut dim = vec![self.weight_functions[0].segments]; self.k_abs.shape().iter().for_each(|&d| dim.push(d)); let mut functional_deriv_k = Array::zeros(dim).into_dimensionality().unwrap(); // Iterate over all contributions for (pd, wf) in partial_derivatives.iter().zip(&self.weight_functions) { // Multiplication of `partial_derivatives` with the weight functions in // Fourier space (convolution in real space); summation leads to // functional derivative: the rows in the array are selected from the // running variable `k` with the number of rows needed for this // particular contribution let mut k = 0; // If local densities are present, their contributions are added directly if wf.local_density { functional_deriv_local += &pd.slice_axis(Axis(0), Slice::from(..wf.segments)); k += wf.segments; } // Convolution of functional derivatives {scalar, component} for wf_i in &wf.scalar_component_weighted_densities { let pd_k = self.forward_transform_comps( pd.slice_axis(Axis(0), Slice::from(k..k + wf.segments)), None, ); functional_deriv_k.add_assign(&(&pd_k * wf_i)); k += wf.segments; } // Convolution of functional derivatives {vector, component} for wf_i in &wf.vector_component_weighted_densities { for (i, wf_i) in wf_i.outer_iter().enumerate() { let pd_k = self.forward_transform_comps( pd.slice_axis(Axis(0), Slice::from(k..k + wf.segments)), Some(i), ); functional_deriv_k.add_assign(&(pd_k * &wf_i)); k += wf.segments; } } // Convolution of functional derivatives {scalar, FMT} for wf_i in &wf.scalar_fmt_weighted_densities { let pd_k = self.forward_transform(pd.index_axis(Axis(0), k), None); functional_deriv_k.add_assign(&(wf_i * &pd_k)); k += 1; } // Convolution of functional derivatives {vector, FMT} for wf_i in &wf.vector_fmt_weighted_densities { for (i, wf_i) in wf_i.outer_iter().enumerate() { let pd_k = self.forward_transform(pd.index_axis(Axis(0), k), Some(i)); functional_deriv_k.add_assign(&(&wf_i * &pd_k)); k += 1; } } } // Backward transform of the non-local part of the functional derivative self.back_transform_comps(functional_deriv_k, functional_deriv.view_mut(), None); // Return sum over non-local and local contributions functional_deriv + functional_deriv_local } } /// The curvilinear convolver accounts for the shift that has to be performed /// for spherical and polar transforms. struct CurvilinearConvolver<T, D> { convolver: Arc<dyn Convolver<T, D>>, convolver_boundary: Arc<dyn Convolver<T, D>>, } impl<T, D: Dimension + RemoveAxis + 'static> CurvilinearConvolver<T, D> where T: DctNum + DualNum<f64>, D::Larger: Dimension<Smaller = D>, D::Smaller: Dimension<Larger = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { #[expect(clippy::new_ret_no_self)] fn new( r: &Axis, z: &[&Axis], weight_functions: &[WeightFunctionInfo<T>], lanczos: Option<i32>, ) -> Arc<dyn Convolver<T, D>> { Arc::new(Self { convolver: ConvolverFFT::new(Some(r), z, weight_functions, lanczos), convolver_boundary: ConvolverFFT::new(None, z, weight_functions, lanczos), }) } } impl<T, D: Dimension + RemoveAxis> Convolver<T, D> for CurvilinearConvolver<T, D> where T: DctNum + DualNum<f64>, D::Smaller: Dimension<Larger = D>, D::Larger: Dimension<Smaller = D>, { fn convolve( &self, mut profile: Array<T, D>, weight_function: &WeightFunction<T>, ) -> Array<T, D> { // subtract boundary profile from full profile let profile_boundary = profile .index_axis(Axis(0), profile.shape()[0] - 1) .into_owned(); for mut lane in profile.outer_iter_mut() { lane.sub_assign(&profile_boundary); } // convolve full profile let mut result = self.convolver.convolve(profile, weight_function); // convolve boundary profile let profile_boundary = profile_boundary.insert_axis(Axis(0)); let result_boundary = self .convolver_boundary .convolve(profile_boundary, weight_function); // Add boundary result back to full result let result_boundary = result_boundary.index_axis(Axis(0), 0); for mut lane in result.outer_iter_mut() { lane.add_assign(&result_boundary); } result } /// Calculates weighted densities via convolution from density profiles. fn weighted_densities(&self, density: &Array<T, D::Larger>) -> Vec<Array<T, D::Larger>> { // subtract boundary profile from full profile let density_boundary = density.index_axis(Axis(1), density.shape()[1] - 1); let mut density = density.to_owned(); for mut lane in density.axis_iter_mut(Axis(1)) { lane.sub_assign(&density_boundary); } // convolve full profile let mut wd = self.convolver.weighted_densities(&density); // convolve boundary profile let density_boundary = density_boundary.insert_axis(Axis(1)); let wd_boundary = self .convolver_boundary .weighted_densities(&density_boundary.to_owned()); // Add boundary result back to full result for (wd, wd_boundary) in wd.iter_mut().zip(wd_boundary.iter()) { let wd_view = wd_boundary.index_axis(Axis(1), 0); for mut lane in wd.axis_iter_mut(Axis(1)) { lane.add_assign(&wd_view); } } wd } /// Calculates the functional derivative via convolution from partial derivatives /// of the Helmholtz energy functional. fn functional_derivative( &self, partial_derivatives: &[Array<T, D::Larger>], ) -> Array<T, D::Larger> { // subtract boundary profile from full profile let mut partial_derivatives_full = Vec::new(); let mut partial_derivatives_boundary = Vec::new(); for pd in partial_derivatives { let pd_boundary = pd.index_axis(Axis(1), pd.shape()[1] - 1).to_owned(); let mut pd_full = pd.to_owned(); for mut lane in pd_full.axis_iter_mut(Axis(1)) { lane.sub_assign(&pd_boundary); } partial_derivatives_full.push(pd_full); partial_derivatives_boundary.push(pd_boundary); } // convolve full profile let mut functional_derivative = self .convolver .functional_derivative(&partial_derivatives_full); // convolve boundary profile let mut partial_derivatives_boundary = Vec::new(); for pd in partial_derivatives { let mut pd_boundary = pd.view(); pd_boundary.collapse_axis(Axis(1), pd.shape()[1] - 1); partial_derivatives_boundary.push(pd_boundary.to_owned()); } let functional_derivative_boundary = self .convolver_boundary .functional_derivative(&partial_derivatives_boundary); // Add boundary result back to full result let functional_derivative_view = functional_derivative_boundary.index_axis(Axis(1), 0); for mut lane in functional_derivative.axis_iter_mut(Axis(1)) { lane.add_assign(&functional_derivative_view); } functional_derivative } }
Rust
3D
feos-org/feos
crates/feos-dft/src/convolver/periodic_convolver.rs
.rs
16,122
389
use super::{Convolver, FFTWeightFunctions}; use crate::geometry::Axis; use crate::weight_functions::{WeightFunction, WeightFunctionInfo}; use ndarray::Axis as Axis_nd; use ndarray::*; use num_dual::DualNum; use quantity::Angle; use rustfft::num_complex::Complex; use rustfft::{Fft, FftDirection, FftNum, FftPlanner}; use std::f64::consts::PI; use std::ops::AddAssign; use std::sync::Arc; pub struct PeriodicConvolver<T, D: Dimension> { /// k vectors k_abs: Array<f64, D>, /// Vector of weight functions for each component in multiple dimensions. weight_functions: Vec<FFTWeightFunctions<T, D>>, /// Lanczos sigma factor lanczos_sigma: Option<Array<f64, D>>, /// Vector of forward Fourier transforms in each dimensions forward_transforms: Vec<Arc<dyn Fft<T>>>, /// Vector of inverse Fourier transforms in each dimensions inverse_transforms: Vec<Arc<dyn Fft<T>>>, } impl<T, D: Dimension + 'static> PeriodicConvolver<T, D> where T: FftNum + DualNum<f64>, D::Larger: Dimension<Smaller = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { pub fn new_2d( axes: &[&Axis], angle: Angle, weight_functions: &[WeightFunctionInfo<T>], lanczos: Option<i32>, ) -> Arc<dyn Convolver<T, D>> { let f = |k: &mut Array<f64, D::Larger>| { let k_y = (&k.index_axis(Axis(0), 1) - &k.index_axis(Axis(0), 0) * angle.cos()) / angle.sin(); k.index_axis_mut(Axis(0), 1).assign(&k_y); }; Self::new(axes, f, weight_functions, lanczos) } pub fn new_3d( axes: &[&Axis], angles: [Angle; 3], weight_functions: &[WeightFunctionInfo<T>], lanczos: Option<i32>, ) -> Arc<dyn Convolver<T, D>> { let f = |k: &mut Array<f64, D::Larger>| { let [alpha, beta, gamma] = angles; let [k_u, k_v, k_w] = [0, 1, 2].map(|i| k.index_axis(Axis(0), i)); let k_y = (&k_v - &k_u * gamma.cos()) / gamma.sin(); let xi = (alpha.cos() - gamma.cos() * beta.cos()) / gamma.sin(); let zeta = (1.0 - beta.cos().powi(2) - xi * xi).sqrt(); let k_z = ((gamma.cos() * xi / gamma.sin() - beta.cos()) * &k_u - xi / gamma.sin() * &k_v + &k_w) / zeta; k.index_axis_mut(Axis(0), 1).assign(&k_y); k.index_axis_mut(Axis(0), 2).assign(&k_z); }; Self::new(axes, f, weight_functions, lanczos) } #[expect(clippy::new_ret_no_self)] pub fn new<F: Fn(&mut Array<f64, D::Larger>)>( axes: &[&Axis], non_orthogonal_correction: F, weight_functions: &[WeightFunctionInfo<T>], lanczos: Option<i32>, ) -> Arc<dyn Convolver<T, D>> { // initialize the Fourier transform let mut planner = FftPlanner::new(); let mut forward_transforms = Vec::with_capacity(axes.len()); let mut inverse_transforms = Vec::with_capacity(axes.len()); let mut k_vec = Vec::with_capacity(axes.len()); let mut lengths = Vec::with_capacity(axes.len()); for ax in axes { let points = ax.grid.len(); forward_transforms.push(planner.plan_fft_forward(points)); inverse_transforms.push(planner.plan_fft_inverse(points)); let (min, max) = (-(points as isize / 2), (points as isize - 1) / 2); let k_x: Array1<_> = (0..=max) .chain(min..0) .map(|i| 2.0 * PI * i as f64 / ax.length()) .collect(); k_vec.push(k_x); lengths.push(ax.length()); } // Calculate the full k vectors let mut dim = vec![k_vec.len()]; k_vec.iter().for_each(|k_x| dim.push(k_x.len())); let mut k: Array<_, D::Larger> = Array::zeros(dim).into_dimensionality().unwrap(); for (i, (mut k_i, k_x)) in k.outer_iter_mut().zip(k_vec.iter()).enumerate() { k_i.lanes_mut(Axis_nd(i)) .into_iter() .for_each(|mut l| l.assign(k_x)); } // Correction for non-orthogonal coordinate systems non_orthogonal_correction(&mut k); // Calculate the absolute value of the k vector let mut k_abs = Array::zeros(k.raw_dim().remove_axis(Axis_nd(0))); for k_i in k.outer_iter() { k_abs.add_assign(&k_i.mapv(|k| k.powi(2))); } k_abs.map_inplace(|k| *k = k.sqrt()); // Lanczos sigma factor let lanczos_sigma = lanczos.map(|exp| { let mut lanczos = Array::ones(k_abs.raw_dim()); for (i, (k_x, &l)) in k_vec.iter().zip(lengths.iter()).enumerate() { let points = k_x.len(); let m2 = if points % 2 == 0 { points as f64 + 2.0 } else { points as f64 + 1.0 }; let l_x = k_x.mapv(|k| (k * l / m2).sph_j0().powi(exp)); for mut l in lanczos.lanes_mut(Axis_nd(i)) { l *= &l_x; } } lanczos }); // calculate weight functions in Fourier space and weight constants let mut fft_weight_functions = Vec::with_capacity(weight_functions.len()); for wf in weight_functions { // Calculates the weight functions values from `k_abs` // Pre-allocation of empty `Vec` let mut scal_comp = Vec::with_capacity(wf.scalar_component_weighted_densities.len()); // Filling array with scalar component-wise weight functions for wf_i in &wf.scalar_component_weighted_densities { scal_comp.push(wf_i.fft_scalar_weight_functions(&k_abs, &lanczos_sigma)); } // Pre-allocation of empty `Vec` let mut vec_comp = Vec::with_capacity(wf.vector_component_weighted_densities.len()); // Filling array with vector-valued component-wise weight functions for wf_i in &wf.vector_component_weighted_densities { vec_comp.push(wf_i.fft_vector_weight_functions(&k_abs, &k, &lanczos_sigma)); } // Pre-allocation of empty `Vec` let mut scal_fmt = Vec::with_capacity(wf.scalar_fmt_weighted_densities.len()); // Filling array with scalar FMT weight functions for wf_i in &wf.scalar_fmt_weighted_densities { scal_fmt.push(wf_i.fft_scalar_weight_functions(&k_abs, &lanczos_sigma)); } // Pre-allocation of empty `Vec` let mut vec_fmt = Vec::with_capacity(wf.vector_fmt_weighted_densities.len()); // Filling array with vector-valued FMT weight functions for wf_i in &wf.vector_fmt_weighted_densities { vec_fmt.push(wf_i.fft_vector_weight_functions(&k_abs, &k, &lanczos_sigma)); } // Initializing `FFTWeightFunctions` structure fft_weight_functions.push(FFTWeightFunctions::<_, D> { segments: wf.component_index.len(), local_density: wf.local_density, scalar_component_weighted_densities: scal_comp, vector_component_weighted_densities: vec_comp, scalar_fmt_weighted_densities: scal_fmt, vector_fmt_weighted_densities: vec_fmt, }); } Arc::new(Self { k_abs, weight_functions: fft_weight_functions, lanczos_sigma, forward_transforms, inverse_transforms, }) } } impl<T: FftNum, D: Dimension> PeriodicConvolver<T, D> { fn transform(&self, transform: &Arc<dyn Fft<T>>, mut f: ArrayViewMut1<Complex<T>>) { if let Some(f) = f.as_slice_mut() { transform.process(f); } else { let mut f_cont = f.to_owned(); transform.process(f_cont.as_slice_mut().unwrap()); f.assign(&f_cont); } if let FftDirection::Inverse = transform.fft_direction() { let points = T::from_usize(transform.len()).unwrap(); f.mapv_inplace(|x| x / points); } } fn forward_transform<D2: Dimension>(&self, f: ArrayView<T, D2>) -> Array<Complex<T>, D2> { let offset = D2::NDIM.unwrap() - D::NDIM.unwrap(); let mut result = f.mapv(Complex::from); for (i, transform) in self.forward_transforms.iter().enumerate() { for r in result.lanes_mut(Axis_nd(i + offset)).into_iter() { self.transform(transform, r); } } result } fn inverse_transform<D2: Dimension>(&self, mut f: Array<Complex<T>, D2>) -> Array<T, D2> { let offset = D2::NDIM.unwrap() - D::NDIM.unwrap(); for (i, transform) in self.inverse_transforms.iter().enumerate() { for r in f.lanes_mut(Axis_nd(i + offset)).into_iter() { self.transform(transform, r); } } f.mapv(|x| x.re) } } impl<T, D: Dimension> Convolver<T, D> for PeriodicConvolver<T, D> where T: FftNum + DualNum<f64>, D::Larger: Dimension<Smaller = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { fn convolve(&self, profile: Array<T, D>, weight_function: &WeightFunction<T>) -> Array<T, D> { // Forward transform let f_k = self.forward_transform(profile.view()); // calculate weight function let w = weight_function .fft_scalar_weight_functions(&self.k_abs, &self.lanczos_sigma) .index_axis_move(Axis_nd(0), 0); // Inverse transform self.inverse_transform(f_k * w) } fn weighted_densities(&self, density: &Array<T, D::Larger>) -> Vec<Array<T, D::Larger>> { // Applying FFT to each row of the matrix `rho` saving the result in `rho_k` let rho_k = self.forward_transform(density.view()); // Iterate over all contributions let mut weighted_densities_vec = Vec::with_capacity(self.weight_functions.len()); for wf in &self.weight_functions { // number of weighted densities let n_wd = wf.n_weighted_densities(density.ndim() - 1); // Allocating new array for intended weighted densities let mut dim = vec![n_wd]; density.shape().iter().skip(1).for_each(|&d| dim.push(d)); let mut weighted_densities = Array::zeros(dim).into_dimensionality().unwrap(); // Initilaizing row index for non-local weighted densities let mut k = 0; // Assigning possible local densities to the front of the array if wf.local_density { weighted_densities .slice_axis_mut(Axis_nd(0), Slice::from(0..wf.segments)) .assign(density); k += wf.segments; } // Calculating weighted densities {scalar, component} for wf_i in &wf.scalar_component_weighted_densities { weighted_densities .slice_axis_mut(Axis_nd(0), Slice::from(k..k + wf.segments)) .assign(&self.inverse_transform(&rho_k * wf_i)); k += wf.segments; } // Calculating weighted densities {vector, component} for wf_i in &wf.vector_component_weighted_densities { for wf_i in wf_i.outer_iter() { weighted_densities .slice_axis_mut(Axis_nd(0), Slice::from(k..k + wf.segments)) .assign( &self.inverse_transform((&rho_k * &wf_i).mapv(|x| x * Complex::i())), ); k += wf.segments; } } // Calculating weighted densities {scalar, FMT} for wf_i in &wf.scalar_fmt_weighted_densities { weighted_densities .index_axis_mut(Axis_nd(0), k) .assign(&self.inverse_transform((&rho_k * wf_i).sum_axis(Axis_nd(0)))); k += 1; } // Calculating weighted densities {vector, FMT} for wf_i in &wf.vector_fmt_weighted_densities { for wf_i in wf_i.outer_iter() { weighted_densities.index_axis_mut(Axis_nd(0), k).assign( &self.inverse_transform( (&rho_k * &wf_i) .sum_axis(Axis_nd(0)) .mapv(|x| x * Complex::i()), ), ); k += 1; } } // add weighted densities for this contribution to the result weighted_densities_vec.push(weighted_densities); } // Return weighted_densities_vec } fn functional_derivative( &self, partial_derivatives: &[Array<T, D::Larger>], ) -> Array<T, D::Larger> { // Allocate arrays for the the local contribution to the functional derivative // and the functional derivative in Fourier space let mut dim = vec![self.weight_functions[0].segments]; partial_derivatives[0] .shape() .iter() .skip(1) .for_each(|&d| dim.push(d)); let mut functional_deriv_local: Array<_, D::Larger> = Array::zeros(dim).into_dimensionality().unwrap(); let mut functional_deriv_k = Array::zeros(functional_deriv_local.raw_dim()); // Iterate over all contributions for (pd, wf) in partial_derivatives.iter().zip(&self.weight_functions) { // Multiplication of `partial_derivatives` with the weight functions in // Fourier space (convolution in real space); summation leads to // functional derivative: the rows in the array are selected from the // running variable `k` with the number of rows needed for this // particular contribution let mut k = 0; // If local densities are present, their contributions are added directly if wf.local_density { functional_deriv_local += &pd.slice_axis(Axis_nd(0), Slice::from(..wf.segments)); k += wf.segments; } // Convolution of functional derivatives {scalar, component} for wf_i in &wf.scalar_component_weighted_densities { let pd_k = self .forward_transform(pd.slice_axis(Axis_nd(0), Slice::from(k..k + wf.segments))); functional_deriv_k += &(&pd_k * wf_i); k += wf.segments; } // Convolution of functional derivatives {vector, component} for wf_i in &wf.vector_component_weighted_densities { for wf_i in wf_i.outer_iter() { let pd_k = self.forward_transform( pd.slice_axis(Axis_nd(0), Slice::from(k..k + wf.segments)), ); functional_deriv_k -= &(pd_k * &wf_i).mapv(|x| x * Complex::i()); k += wf.segments; } } // Convolution of functional derivatives {scalar, FMT} for wf_i in &wf.scalar_fmt_weighted_densities { let pd_k = self.forward_transform(pd.index_axis(Axis_nd(0), k)); functional_deriv_k += &(pd_k * wf_i); k += 1; } // Convolution of functional derivatives {vector, FMT} for wf_i in &wf.vector_fmt_weighted_densities { for wf_i in wf_i.outer_iter() { let pd_k = self.forward_transform(pd.index_axis(Axis_nd(0), k)); functional_deriv_k -= &(pd_k * wf_i).mapv(|x| x * Complex::i()); k += 1; } } } // Return sum over non-local and local contributions self.inverse_transform(functional_deriv_k) + functional_deriv_local } }
Rust
3D
feos-org/feos
crates/feos-dft/src/convolver/transform.rs
.rs
12,205
356
use crate::geometry::Axis; use ndarray::prelude::*; use ndarray::*; use num_dual::*; use rustdct::{DctNum, DctPlanner, TransformType2And3}; use rustfft::{Fft, FftPlanner, num_complex::Complex}; use std::f64::consts::PI; use std::sync::Arc; #[derive(Clone, Copy)] enum SinCosTransform { SinForward, SinReverse, CosForward, CosReverse, } impl SinCosTransform { fn is_reverse(&self) -> bool { match self { Self::CosForward | Self::SinForward => false, Self::CosReverse | Self::SinReverse => true, } } } pub(super) trait FourierTransform<T: DualNum<f64>>: Send + Sync { fn forward_transform(&self, f_r: ArrayView1<T>, f_k: ArrayViewMut1<T>, scalar: bool); fn back_transform(&self, f_k: ArrayViewMut1<T>, f_r: ArrayViewMut1<T>, scalar: bool); } pub(super) struct CartesianTransform<T> { dct: Arc<dyn TransformType2And3<T>>, } impl<T: DualNum<f64> + DctNum> CartesianTransform<T> { #[expect(clippy::new_ret_no_self)] pub(super) fn new(axis: &Axis) -> (Box<dyn FourierTransform<T>>, Array1<f64>) { let (s, k) = Self::init(axis); (Box::new(s), k) } pub(super) fn new_cartesian(axis: &Axis) -> (Self, Array1<f64>) { let (s, k) = Self::init(axis); (s, k) } fn init(axis: &Axis) -> (Self, Array1<f64>) { let points = axis.grid.len(); let length = axis.length(); let k_grid = (0..=points).map(|v| PI * v as f64 / length).collect(); ( Self { dct: DctPlanner::new().plan_dct2(points), }, k_grid, ) } fn calculate_transform(&self, slice: &mut [T], transform: SinCosTransform) { match transform { SinCosTransform::CosForward => self.dct.process_dct2(slice), SinCosTransform::CosReverse => self.dct.process_dct3(slice), SinCosTransform::SinForward => self.dct.process_dst2(slice), SinCosTransform::SinReverse => self.dct.process_dst3(slice), } } fn transform(&self, mut f: ArrayViewMut1<T>, transform: SinCosTransform) { let mut f_slice = match transform { SinCosTransform::CosForward | SinCosTransform::CosReverse => f.slice_mut(s![..-1]), SinCosTransform::SinForward | SinCosTransform::SinReverse => f.slice_mut(s![1..]), }; match f_slice.as_slice_mut() { Some(slice) => self.calculate_transform(slice, transform), None => { let mut slice = f_slice.to_owned(); self.calculate_transform(slice.as_slice_mut().unwrap(), transform); f_slice.assign(&slice); } } if transform.is_reverse() { f.map_inplace(|f| { *f /= T::from_f64(0.5).unwrap() * T::from_usize(self.dct.len()).unwrap() }) } } pub(super) fn forward_transform_inplace(&self, f: ArrayViewMut1<T>, scalar: bool) { if scalar { self.transform(f, SinCosTransform::CosForward); } else { self.transform(f, SinCosTransform::SinForward); } } pub(super) fn back_transform_inplace(&self, f: ArrayViewMut1<T>, scalar: bool) { if scalar { self.transform(f, SinCosTransform::CosReverse); } else { self.transform(f, SinCosTransform::SinReverse); } } } impl<T: DualNum<f64> + DctNum> FourierTransform<T> for CartesianTransform<T> { fn forward_transform(&self, f_r: ArrayView1<T>, mut f_k: ArrayViewMut1<T>, scalar: bool) { if scalar { f_k.slice_mut(s![..-1]).assign(&f_r); } else { f_k.slice_mut(s![1..]).assign(&f_r); } self.forward_transform_inplace(f_k, scalar); } fn back_transform(&self, mut f_k: ArrayViewMut1<T>, mut f_r: ArrayViewMut1<T>, scalar: bool) { self.back_transform_inplace(f_k.view_mut(), scalar); if scalar { f_r.assign(&f_k.slice(s![..-1])); } else { f_r.assign(&f_k.slice(s![1..])); } } } pub(super) struct SphericalTransform<T> { r_grid: Array1<f64>, k_grid: Array1<f64>, dct: Arc<dyn TransformType2And3<T>>, } impl<T: DualNum<f64> + DctNum> SphericalTransform<T> { #[expect(clippy::new_ret_no_self)] pub(super) fn new(axis: &Axis) -> (Box<dyn FourierTransform<T>>, Array1<f64>) { let points = axis.grid.len(); let length = axis.length(); let k_grid: Array1<_> = (0..=points).map(|v| PI * v as f64 / length).collect(); ( Box::new(Self { r_grid: axis.grid.clone(), k_grid: k_grid.clone(), dct: DctPlanner::new().plan_dct2(points), }), k_grid, ) } fn sine_transform<S1, S2>( &self, f_in: ArrayBase<S1, Ix1>, mut f_out: ArrayBase<S2, Ix1>, reverse: bool, ) where S1: Data<Elem = T>, S2: RawData<Elem = T> + DataMut, { if reverse { f_out.assign(&f_in.slice(s![1..])); self.dct.process_dst3(f_out.as_slice_mut().unwrap()); let n = f_out.len(); f_out.map_inplace(|f| *f /= T::from_f64(0.5).unwrap() * T::from_usize(n).unwrap()); } else { let mut f_slice = f_out.slice_mut(s![1..]); f_slice.assign(&f_in); self.dct.process_dst2(f_slice.as_slice_mut().unwrap()); } } fn cosine_transform<S1, S2>( &self, f_in: ArrayBase<S1, Ix1>, mut f_out: ArrayBase<S2, Ix1>, reverse: bool, ) where S1: Data<Elem = T>, S2: RawData<Elem = T> + DataMut, { if reverse { f_out.assign(&f_in.slice(s![..-1])); self.dct.process_dct3(f_out.as_slice_mut().unwrap()); let n = f_out.len(); f_out.map_inplace(|f| *f /= T::from_f64(0.5).unwrap() * T::from_usize(n).unwrap()); } else { let mut f_slice = f_out.slice_mut(s![..-1]); f_slice.assign(&f_in); self.dct.process_dct2(f_slice.as_slice_mut().unwrap()); } } } impl<T: DualNum<f64> + DctNum> FourierTransform<T> for SphericalTransform<T> { fn forward_transform(&self, f_r: ArrayView1<T>, mut f_k: ArrayViewMut1<T>, scalar: bool) { if scalar { self.sine_transform(&f_r * &self.r_grid, f_k.view_mut(), false); } else { let mut f_aux = Array::zeros(f_k.raw_dim()); self.cosine_transform(&f_r * &self.r_grid, f_aux.view_mut(), false); self.sine_transform(f_r, f_k.view_mut(), false); let f_k_scaled = &f_k / &self.k_grid - &f_aux; f_k.assign(&f_k_scaled); } let f_k_scaled = &f_k / &self.k_grid; f_k.assign(&f_k_scaled); f_k[0] = T::zero(); } fn back_transform(&self, f_k: ArrayViewMut1<T>, mut f_r: ArrayViewMut1<T>, scalar: bool) { if scalar { self.sine_transform(&f_k * &self.k_grid, f_r.view_mut(), true); } else { let mut f_aux = Array::zeros(f_r.raw_dim()); self.cosine_transform(&f_k * &self.k_grid, f_aux.view_mut(), true); self.sine_transform(f_k, f_r.view_mut(), true); let f_r_scaled = &f_r / &self.r_grid - &f_aux; f_r.assign(&f_r_scaled); } let f_r_scaled = &f_r / &self.r_grid; f_r.assign(&f_r_scaled); } } pub(super) struct PolarTransform<T: DctNum> { r_grid: Array1<f64>, k_grid: Array1<f64>, fft: Arc<dyn Fft<T>>, j: [Array1<Complex<T>>; 2], k0: [f64; 2], alpha: f64, gamma: f64, l: f64, } impl<T: DualNum<f64> + DctNum> PolarTransform<T> { #[expect(clippy::new_ret_no_self)] pub(super) fn new(axis: &Axis) -> (Box<dyn FourierTransform<T>>, Array1<f64>) { let points = axis.grid.len(); let mut alpha = 0.002_f64; for _ in 0..20 { alpha = -(1.0 - (-alpha).exp()).ln() / (points - 1) as f64; } let x0 = 0.5 * ((-alpha * points as f64).exp() + (-alpha * (points - 1) as f64).exp()); let gamma = (alpha * (points - 1) as f64).exp(); let l = axis.length(); let k_grid: Array1<_> = (0..points) .map(|i| x0 * (alpha * i as f64).exp() * gamma / l) .collect(); let k0 = (2.0 * alpha).exp() * (2.0 * alpha.exp() + (2.0 * alpha).exp() - 1.0) / ((1.0 + alpha.exp()).powi(2) * ((2.0 * alpha).exp() - 1.0)); let k0v = (2.0 * alpha).exp() * (2.0 * alpha.exp() + (2.0 * alpha).exp() - 5.0 / 3.0) / ((1.0 + alpha.exp()).powi(2) * ((2.0 * alpha).exp() - 1.0)); let fft = FftPlanner::new().plan_fft_forward(2 * points); let ifft = FftPlanner::new().plan_fft_inverse(2 * points); let mut j = Array1::from_shape_fn(2 * points, |i| { Complex::from(T::from( (gamma * x0 * (alpha * ((i + 1) as f64 - points as f64)).exp()).bessel_j1() / ((2 * points) as f64), )) }); ifft.process(j.as_slice_mut().unwrap()); let mut jv = Array1::from_shape_fn(2 * points, |i| { Complex::from(T::from( (gamma * x0 * (alpha * ((i + 1) as f64 - points as f64)).exp()).bessel_j2() / ((2 * points) as f64), )) }); ifft.process(jv.as_slice_mut().unwrap()); ( Box::new(Self { r_grid: axis.grid.clone(), k_grid: k_grid.clone(), fft, j: [j, jv], k0: [k0, k0v], alpha, gamma, l, }), k_grid, ) } fn transform( &self, f_in: ArrayView1<T>, mut f_out: ArrayViewMut1<T>, scalar: bool, x_in: &Array1<f64>, x_out: &Array1<f64>, mut factor: f64, ) { let n = f_in.len(); let (f_in, alpha, k0, j) = if scalar { (f_in.to_owned(), self.alpha, self.k0[0], &self.j[0]) } else { factor *= factor; (&f_in / x_in, 2.0 * self.alpha, self.k0[1], &self.j[1]) }; let mut phi = Array1::from_shape_fn(2 * n, |i| { if i < n - 1 { (f_in[i] - f_in[i + 1]) * (-alpha * (n - i - 1) as f64).exp() } else { T::zero() } }); phi[0] *= k0; let mut phi = phi.mapv(Complex::from); self.fft.process(phi.as_slice_mut().unwrap()); phi *= j; self.fft.process(phi.as_slice_mut().unwrap()); f_out.assign(&(phi.slice(s![..n]).map(|phi| phi.re * factor) / x_out)); } } impl<T: DualNum<f64> + DctNum> FourierTransform<T> for PolarTransform<T> { fn forward_transform(&self, f_r: ArrayView1<T>, f_k: ArrayViewMut1<T>, scalar: bool) { self.transform(f_r, f_k, scalar, &self.r_grid, &self.k_grid, self.l); } fn back_transform(&self, f_k: ArrayViewMut1<T>, f_r: ArrayViewMut1<T>, scalar: bool) { self.transform( f_k.view(), f_r, scalar, &self.k_grid, &self.r_grid, self.gamma / self.l, ); } } pub(super) struct NoTransform(); impl NoTransform { #[expect(clippy::new_ret_no_self)] pub(super) fn new<T: DualNum<f64>>() -> (Box<dyn FourierTransform<T>>, Array1<f64>) { (Box::new(Self()), arr1(&[0.0])) } } impl<T: DualNum<f64>> FourierTransform<T> for NoTransform { fn forward_transform(&self, f: ArrayView1<T>, mut f_k: ArrayViewMut1<T>, _: bool) { f_k.assign(&f); } fn back_transform(&self, f_k: ArrayViewMut1<T>, mut f_r: ArrayViewMut1<T>, _: bool) { f_r.assign(&f_k); } }
Rust
3D
feos-org/feos
crates/feos-dft/src/profile/mod.rs
.rs
18,298
509
use crate::convolver::{BulkConvolver, Convolver, ConvolverFFT}; use crate::functional::HelmholtzEnergyFunctional; use crate::geometry::Grid; use crate::solver::{DFTSolver, DFTSolverLog}; use feos_core::{FeosError, FeosResult, ReferenceSystem, State}; use nalgebra::{DVector, Dyn, U1}; use ndarray::{ Array, Array1, Array2, Array3, ArrayBase, Axis as Axis_nd, Data, Dimension, Ix1, Ix2, Ix3, RemoveAxis, }; use num_dual::DualNum; use quantity::{_Volume, DEGREES, Density, Length, Moles, Quantity, Temperature, Volume}; use std::ops::{Add, MulAssign}; use std::sync::Arc; mod properties; pub(crate) const MAX_POTENTIAL: f64 = 50.0; #[cfg(feature = "rayon")] pub(crate) const CUTOFF_RADIUS: f64 = 14.0; /// General specifications for the chemical potential in a DFT calculation. /// /// In the most basic case, the chemical potential is specified in a DFT calculation, /// for more general systems, this trait provides the possibility to declare additional /// equations for the calculation of the chemical potential during the iteration. pub trait DFTSpecification<D: Dimension, F>: Send + Sync { fn calculate_bulk_density( &self, profile: &DFTProfile<D, F>, bulk_density: &Array1<f64>, z: &Array1<f64>, ) -> FeosResult<Array1<f64>>; } /// Common specifications for the grand potentials in a DFT calculation. pub enum DFTSpecifications { /// DFT with specified chemical potential. ChemicalPotential, /// DFT with specified number of particles. /// /// The solution is still a grand canonical density profile, but the chemical /// potentials are iterated together with the density profile to obtain a result /// with the specified number of particles. Moles { moles: Array1<f64> }, /// DFT with specified total number of moles. TotalMoles { total_moles: f64 }, } impl DFTSpecifications { /// Calculate the number of particles from the profile. /// /// Call this after initializing the density profile to keep the number of /// particles constant in systems, where the number itself is difficult to obtain. pub fn moles_from_profile<D: Dimension, F: HelmholtzEnergyFunctional>( profile: &DFTProfile<D, F>, ) -> Self where D::Larger: Dimension<Smaller = D>, { let rho = profile.density.to_reduced(); Self::Moles { moles: profile.integrate_reduced_comp(&rho), } } /// Calculate the number of particles from the profile. /// /// Call this after initializing the density profile to keep the total number of /// particles constant in systems, e.g. to fix the equimolar dividing surface. pub fn total_moles_from_profile<D: Dimension, F: HelmholtzEnergyFunctional>( profile: &DFTProfile<D, F>, ) -> Self where D::Larger: Dimension<Smaller = D>, { let rho = profile.density.to_reduced(); let moles = profile.integrate_reduced_comp(&rho).sum(); Self::TotalMoles { total_moles: moles } } } impl<D: Dimension, F: HelmholtzEnergyFunctional> DFTSpecification<D, F> for DFTSpecifications { fn calculate_bulk_density( &self, _profile: &DFTProfile<D, F>, bulk_density: &Array1<f64>, z: &Array1<f64>, ) -> FeosResult<Array1<f64>> { Ok(match self { Self::ChemicalPotential => bulk_density.clone(), Self::Moles { moles } => moles / z, Self::TotalMoles { total_moles } => { bulk_density * *total_moles / (bulk_density * z).sum() } }) } } #[derive(Clone)] /// A one-, two-, or three-dimensional density profile. pub struct DFTProfile<D: Dimension, F> { pub grid: Grid, pub convolver: Arc<dyn Convolver<f64, D>>, pub temperature: Temperature, pub density: Density<Array<f64, D::Larger>>, pub specification: Arc<dyn DFTSpecification<D, F>>, pub external_potential: Array<f64, D::Larger>, pub bulk: State<F>, pub solver_log: Option<DFTSolverLog>, pub lanczos: Option<i32>, } impl<F> DFTProfile<Ix1, F> { pub fn r(&self) -> Length<Array1<f64>> { Length::from_reduced(self.grid.grids()[0].to_owned()) } pub fn z(&self) -> Length<Array1<f64>> { Length::from_reduced(self.grid.grids()[0].to_owned()) } } impl<F> DFTProfile<Ix2, F> { pub fn edges(&self) -> [Length<Array1<f64>>; 2] { [ Length::from_reduced(self.grid.axes()[0].edges.to_owned()), Length::from_reduced(self.grid.axes()[1].edges.to_owned()), ] } pub fn meshgrid(&self) -> [Length<Array2<f64>>; 2] { let (u, v, alpha) = match &self.grid { Grid::Cartesian2(u, v) => (u, v, 90.0 * DEGREES), Grid::Periodical2(u, v, alpha) => (u, v, *alpha), _ => unreachable!(), }; let u_grid = Array::from_shape_fn([u.grid.len(), v.grid.len()], |(i, _)| u.grid[i]); let v_grid = Array::from_shape_fn([u.grid.len(), v.grid.len()], |(_, j)| v.grid[j]); let x = Length::from_reduced(u_grid + &v_grid * alpha.cos()); let y = Length::from_reduced(v_grid * alpha.sin()); [x, y] } pub fn r(&self) -> Length<Array1<f64>> { Length::from_reduced(self.grid.grids()[0].to_owned()) } pub fn z(&self) -> Length<Array1<f64>> { Length::from_reduced(self.grid.grids()[1].to_owned()) } } impl<F> DFTProfile<Ix3, F> { pub fn edges(&self) -> [Length<Array1<f64>>; 3] { [ Length::from_reduced(self.grid.axes()[0].edges.to_owned()), Length::from_reduced(self.grid.axes()[1].edges.to_owned()), Length::from_reduced(self.grid.axes()[2].edges.to_owned()), ] } pub fn meshgrid(&self) -> [Length<Array3<f64>>; 3] { let (u, v, w, [alpha, beta, gamma]) = match &self.grid { Grid::Cartesian3(u, v, w) => (u, v, w, [90.0 * DEGREES; 3]), Grid::Periodical3(u, v, w, angles) => (u, v, w, *angles), _ => unreachable!(), }; let shape = [u.grid.len(), v.grid.len(), w.grid.len()]; let u_grid = Array::from_shape_fn(shape, |(i, _, _)| u.grid[i]); let v_grid = Array::from_shape_fn(shape, |(_, j, _)| v.grid[j]); let w_grid = Array::from_shape_fn(shape, |(_, _, k)| w.grid[k]); let xi = (alpha.cos() - gamma.cos() * beta.cos()) / gamma.sin(); let zeta = (1.0_f64 - beta.cos().powi(2) - xi * xi).sqrt(); let x = Length::from_reduced(u_grid + &v_grid * gamma.cos() + &w_grid * beta.cos()); let y = Length::from_reduced(v_grid * gamma.sin() + &w_grid * xi); let z = Length::from_reduced(w_grid * zeta); [x, y, z] } pub fn x(&self) -> Length<Array1<f64>> { Length::from_reduced(self.grid.grids()[0].to_owned()) } pub fn y(&self) -> Length<Array1<f64>> { Length::from_reduced(self.grid.grids()[1].to_owned()) } pub fn z(&self) -> Length<Array1<f64>> { Length::from_reduced(self.grid.grids()[2].to_owned()) } } impl<D: Dimension + RemoveAxis + 'static, F: HelmholtzEnergyFunctional> DFTProfile<D, F> where D::Larger: Dimension<Smaller = D>, D::Smaller: Dimension<Larger = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { /// Create a new density profile. /// /// If no external potential is specified, it is set to 0. The density is /// initialized based on the bulk state and the external potential. The /// specification is set to `ChemicalPotential` and needs to be overriden /// after this call if something else is required. pub fn new( grid: Grid, bulk: &State<F>, external_potential: Option<Array<f64, D::Larger>>, density: Option<&Density<Array<f64, D::Larger>>>, lanczos: Option<i32>, ) -> Self { // initialize convolver let t = bulk.temperature.to_reduced(); let weight_functions = bulk.eos.weight_functions(t); let convolver = ConvolverFFT::plan(&grid, &weight_functions, lanczos); // initialize external potential let external_potential = external_potential.unwrap_or_else(|| { let mut n_grid = vec![bulk.eos.component_index().len()]; grid.axes() .iter() .for_each(|&ax| n_grid.push(ax.grid.len())); Array::zeros(n_grid).into_dimensionality().unwrap() }); // initialize density let density = if let Some(density) = density { density.to_owned() } else { let exp_dfdrho = (-&external_potential).mapv(f64::exp); let mut bonds = bulk.eos.bond_integrals(t, &exp_dfdrho, convolver.as_ref()); bonds *= &exp_dfdrho; let mut density = Array::zeros(external_potential.raw_dim()); let bulk_density = bulk.partial_density.to_reduced(); for (s, &c) in bulk.eos.component_index().iter().enumerate() { density.index_axis_mut(Axis_nd(0), s).assign( &(bonds.index_axis(Axis_nd(0), s).map(|is| is.min(1.0)) * bulk_density[c]), ); } Density::from_reduced(density) }; Self { grid, convolver, temperature: bulk.temperature, density, specification: Arc::new(DFTSpecifications::ChemicalPotential), external_potential, bulk: bulk.clone(), solver_log: None, lanczos, } } } impl<D: Dimension, F: HelmholtzEnergyFunctional> DFTProfile<D, F> where D::Larger: Dimension<Smaller = D>, { fn integrate_reduced<N: DualNum<f64> + Copy>(&self, mut profile: Array<N, D>) -> N { let (integration_weights, functional_determinant) = self.grid.integration_weights(); for (i, w) in integration_weights.into_iter().enumerate() { for mut l in profile.lanes_mut(Axis_nd(i)) { l.mul_assign(&w.mapv(N::from)); } } profile.sum() * functional_determinant } fn integrate_reduced_comp<S: Data<Elem = N>, N: DualNum<f64> + Copy>( &self, profile: &ArrayBase<S, D::Larger>, ) -> Array1<N> { Array1::from_shape_fn(profile.shape()[0], |i| { self.integrate_reduced(profile.index_axis(Axis_nd(0), i).to_owned()) }) } pub(crate) fn integrate_reduced_segments<S: Data<Elem = N>, N: DualNum<f64> + Copy>( &self, profile: &ArrayBase<S, D::Larger>, ) -> DVector<N> { let integral = self.integrate_reduced_comp(profile); let mut integral_comp = DVector::zeros(self.bulk.eos.components()); for (i, &j) in self.bulk.eos.component_index().iter().enumerate() { integral_comp[j] = integral[i]; } integral_comp } /// Return the volume of the profile. /// /// In periodic directions, the length is assumed to be 1 Å. pub fn volume(&self) -> Volume { let volume: f64 = self.grid.axes().iter().map(|ax| ax.volume()).product(); Volume::from_reduced(volume * self.grid.functional_determinant()) } /// Integrate a given profile over the iteration domain. pub fn integrate<S: Data<Elem = f64>, U>( &self, profile: &Quantity<ArrayBase<S, D>, U>, ) -> Quantity<f64, <_Volume as Add<U>>::Output> where _Volume: Add<U>, { let (integration_weights, functional_determinant) = self.grid.integration_weights(); let mut value = profile.to_owned(); for (i, &w) in integration_weights.iter().enumerate() { for mut l in value.lanes_mut(Axis_nd(i)) { l.mul_assign(w); } } Volume::from_reduced(functional_determinant) * value.sum() } /// Integrate each component individually. pub fn integrate_comp<S: Data<Elem = f64>, U>( &self, profile: &Quantity<ArrayBase<S, D::Larger>, U>, ) -> Quantity<DVector<f64>, <_Volume as Add<U>>::Output> where _Volume: Add<U>, { Quantity::from_fn_generic(Dyn(profile.shape()[0]), U1, |i, _| { self.integrate(&profile.index_axis(Axis_nd(0), i)) }) } /// Integrate each segment individually and aggregate to components. pub fn integrate_segments<S: Data<Elem = f64>, U>( &self, profile: &Quantity<ArrayBase<S, D::Larger>, U>, ) -> Quantity<DVector<f64>, <_Volume as Add<U>>::Output> where _Volume: Add<U>, { let integral = self.integrate_comp(profile); let mut integral_comp = Quantity::new(DVector::zeros(self.bulk.eos.components())); for (i, &j) in self.bulk.eos.component_index().iter().enumerate() { integral_comp.set(j, integral.get(i)); } integral_comp } /// Return the number of moles of each component in the system. pub fn moles(&self) -> Moles<DVector<f64>> { self.integrate_segments(&self.density) } /// Return the total number of moles in the system. pub fn total_moles(&self) -> Moles { self.moles().sum() } } impl<D: Dimension, F> DFTProfile<D, F> where D::Larger: Dimension<Smaller = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, F: HelmholtzEnergyFunctional, { pub fn weighted_densities(&self) -> FeosResult<Vec<Array<f64, D::Larger>>> { Ok(self .convolver .weighted_densities(&self.density.to_reduced())) } #[expect(clippy::type_complexity)] pub fn residual(&self, log: bool) -> FeosResult<(Array<f64, D::Larger>, Array1<f64>, f64)> { // Read from profile let density = self.density.to_reduced(); let partial_density = self.bulk.partial_density.to_reduced(); let bulk_density = self .bulk .eos .component_index() .iter() .map(|&i| partial_density[i]) .collect(); let (res, res_bulk, res_norm, _, _) = self.euler_lagrange_equation(&density, &bulk_density, log)?; Ok((res, res_bulk, res_norm)) } #[expect(clippy::type_complexity)] pub(crate) fn euler_lagrange_equation( &self, density: &Array<f64, D::Larger>, bulk_density: &Array1<f64>, log: bool, ) -> FeosResult<( Array<f64, D::Larger>, Array1<f64>, f64, Array<f64, D::Larger>, Array<f64, D::Larger>, )> { // calculate reduced temperature let temperature = self.temperature.to_reduced(); // calculate intrinsic functional derivative let (_, mut dfdrho) = self.bulk .eos .functional_derivative(temperature, density, self.convolver.as_ref())?; // calculate total functional derivative dfdrho += &self.external_potential; // calculate bulk functional derivative let bulk_convolver = BulkConvolver::new(self.bulk.eos.weight_functions(temperature)); let (_, dfdrho_bulk) = self.bulk.eos.functional_derivative( temperature, bulk_density, bulk_convolver.as_ref(), )?; dfdrho .outer_iter_mut() .zip(dfdrho_bulk) .zip(self.bulk.eos.m().iter()) .for_each(|((mut df, df_b), &m)| { df -= df_b; df /= m }); // calculate bond integrals let exp_dfdrho = dfdrho.mapv(|x| (-x).exp()); let bonds = self .bulk .eos .bond_integrals(temperature, &exp_dfdrho, self.convolver.as_ref()); let mut rho_projected = &exp_dfdrho * bonds; // multiply bulk density rho_projected .outer_iter_mut() .zip(bulk_density.iter()) .for_each(|(mut x, &rho_b)| { x *= rho_b; }); // calculate residual let mut res = if log { rho_projected.mapv(f64::ln) - density.mapv(f64::ln) } else { &rho_projected - density }; // set residual to 0 where external potentials are overwhelming res.iter_mut() .zip(self.external_potential.iter()) .filter(|&(_, &p)| p + f64::EPSILON >= MAX_POTENTIAL) .for_each(|(r, _)| *r = 0.0); // additional residuals for the calculation of the bulk densities let z = self.integrate_reduced_comp(&rho_projected); let res_bulk = bulk_density - self .specification .calculate_bulk_density(self, bulk_density, &z)?; // calculate the norm of the residual let res_norm = ((density - &rho_projected).mapv(|x| x * x).sum() + res_bulk.mapv(|x| x * x).sum()) .sqrt() / ((res.len() + res_bulk.len()) as f64).sqrt(); if res_norm.is_finite() { Ok((res, res_bulk, res_norm, exp_dfdrho, rho_projected)) } else { Err(FeosError::IterationFailed("Euler-Lagrange equation".into())) } } pub fn solve(&mut self, solver: Option<&DFTSolver>, debug: bool) -> FeosResult<()> { // unwrap solver let solver = solver.cloned().unwrap_or_default(); // Read from profile let component_index = self.bulk.eos.component_index().into_owned(); let mut density = self.density.to_reduced(); let partial_density = self.bulk.partial_density.to_reduced(); let mut bulk_density = component_index .iter() .map(|&i| partial_density[i]) .collect(); // Call solver(s) self.call_solver(&mut density, &mut bulk_density, &solver, debug)?; // Update profile self.density = Density::from_reduced(density); let volume = Volume::from_reduced(1.0); let mut moles = self.bulk.moles.clone(); bulk_density .into_iter() .enumerate() .for_each(|(i, r)| moles.set(component_index[i], Density::from_reduced(r) * volume)); self.bulk = State::new_nvt(&self.bulk.eos, self.bulk.temperature, volume, &moles)?; Ok(()) } }
Rust
3D
feos-org/feos
crates/feos-dft/src/profile/properties.rs
.rs
18,996
470
#![allow(type_alias_bounds)] use super::DFTProfile; use crate::convolver::{BulkConvolver, Convolver}; use crate::functional_contribution::FunctionalContribution; use crate::{ConvolverFFT, DFTSolverLog, HelmholtzEnergyFunctional, WeightFunctionInfo}; use feos_core::{Contributions, FeosResult, ReferenceSystem, Total, Verbosity}; use nalgebra::{DMatrix, DVector}; use ndarray::{Array, Array1, Axis, Dimension, RemoveAxis}; use num_dual::{Dual64, DualNum}; use quantity::{ Density, Energy, Entropy, EntropyDensity, MolarEnergy, Moles, Pressure, Quantity, Temperature, }; use std::ops::{AddAssign, Div}; use std::sync::Arc; type DrhoDmu<D: Dimension> = <Density<Array<f64, <D::Larger as Dimension>::Larger>> as Div<MolarEnergy>>::Output; type DnDmu = <Moles<DMatrix<f64>> as Div<MolarEnergy>>::Output; type DrhoDp<D: Dimension> = <Density<Array<f64, D::Larger>> as Div<Pressure>>::Output; type DnDp = <Moles<DVector<f64>> as Div<Pressure>>::Output; type DrhoDT<D: Dimension> = <Density<Array<f64, D::Larger>> as Div<Temperature>>::Output; type DnDT = <Moles<DVector<f64>> as Div<Temperature>>::Output; impl<D: Dimension, F: HelmholtzEnergyFunctional> DFTProfile<D, F> where D::Larger: Dimension<Smaller = D>, { /// Calculate the grand potential density $\omega$. pub fn grand_potential_density(&self) -> FeosResult<Pressure<Array<f64, D>>> { // Calculate residual Helmholtz energy density and functional derivative let t = self.temperature.to_reduced(); let rho = self.density.to_reduced(); let (mut f, dfdrho) = self.bulk .eos .functional_derivative(t, &rho, self.convolver.as_ref())?; // Calculate the grand potential density for ((rho, dfdrho), &m) in rho .outer_iter() .zip(dfdrho.outer_iter()) .zip(self.bulk.eos.m().iter()) { f -= &((&dfdrho + m) * &rho); } let bond_lengths = self.bulk.eos.bond_lengths(t); for segment in bond_lengths.node_indices() { let n = bond_lengths.neighbors(segment).count(); f += &(&rho.index_axis(Axis(0), segment.index()) * (0.5 * n as f64)); } Ok(Pressure::from_reduced(f * t)) } /// Calculate the grand potential $\Omega$. pub fn grand_potential(&self) -> FeosResult<Energy> { Ok(self.integrate(&self.grand_potential_density()?)) } /// Calculate the (residual) intrinsic functional derivative $\frac{\delta\mathcal{F}}{\delta\rho_i(\mathbf{r})}$. pub fn functional_derivative(&self) -> FeosResult<Array<f64, D::Larger>> { let (_, dfdrho) = self.bulk.eos.functional_derivative( self.temperature.to_reduced(), &self.density.to_reduced(), self.convolver.as_ref(), )?; Ok(dfdrho) } } impl<D: Dimension + RemoveAxis + 'static, F: HelmholtzEnergyFunctional> DFTProfile<D, F> where D::Larger: Dimension<Smaller = D>, D::Smaller: Dimension<Larger = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { fn intrinsic_helmholtz_energy_density<N>( &self, temperature: N, density: &Array<f64, D::Larger>, convolver: &dyn Convolver<N, D>, ) -> FeosResult<Array<N, D>> where N: DualNum<f64> + Copy, { let density_dual = density.mapv(N::from); let weighted_densities = convolver.weighted_densities(&density_dual); let functional_contributions = self.bulk.eos.contributions(); let mut helmholtz_energy_density: Array<N, D> = self .bulk .eos .ideal_chain_contribution() .helmholtz_energy_density(&density.mapv(N::from))?; for (c, wd) in functional_contributions.into_iter().zip(weighted_densities) { let nwd = wd.shape()[0]; let ngrid = wd.len() / nwd; helmholtz_energy_density .view_mut() .into_shape_with_order(ngrid) .unwrap() .add_assign(&c.helmholtz_energy_density( temperature, wd.into_shape_with_order((nwd, ngrid)).unwrap().view(), )?); } Ok(helmholtz_energy_density.mapv(|a| a * temperature)) } /// Calculate the residual entropy density $s^\mathrm{res}(\mathbf{r})$. /// /// Untested with heterosegmented functionals. pub fn residual_entropy_density(&self) -> FeosResult<EntropyDensity<Array<f64, D>>> { // initialize convolver let temperature = self.temperature.to_reduced(); let temperature_dual = Dual64::from(temperature).derivative(); let functional_contributions = self.bulk.eos.contributions(); let weight_functions: Vec<WeightFunctionInfo<Dual64>> = functional_contributions .into_iter() .map(|c| c.weight_functions(temperature_dual)) .collect(); let convolver = ConvolverFFT::plan(&self.grid, &weight_functions, self.lanczos); let density = self.density.to_reduced(); let helmholtz_energy_density = self.intrinsic_helmholtz_energy_density( temperature_dual, &density, convolver.as_ref(), )?; Ok(EntropyDensity::from_reduced( helmholtz_energy_density.mapv(|f| -f.eps), )) } /// Calculate the individual contributions to the entropy density. /// /// Untested with heterosegmented functionals. pub fn entropy_density_contributions( &self, temperature: f64, density: &Array<f64, D::Larger>, convolver: &dyn Convolver<Dual64, D>, ) -> FeosResult<Vec<Array<f64, D>>> { let density_dual = density.mapv(Dual64::from); let temperature_dual = Dual64::from(temperature).derivative(); let weighted_densities = convolver.weighted_densities(&density_dual); let functional_contributions = self.bulk.eos.contributions(); let mut helmholtz_energy_density: Vec<Array<Dual64, _>> = Vec::new(); helmholtz_energy_density.push( self.bulk .eos .ideal_chain_contribution() .helmholtz_energy_density(&density.mapv(Dual64::from))?, ); for (c, wd) in functional_contributions.into_iter().zip(weighted_densities) { let nwd = wd.shape()[0]; let ngrid = wd.len() / nwd; helmholtz_energy_density.push( c.helmholtz_energy_density( temperature_dual, wd.into_shape_with_order((nwd, ngrid)).unwrap().view(), )? .into_shape_with_order(density.raw_dim().remove_axis(Axis(0))) .unwrap(), ); } Ok(helmholtz_energy_density .iter() .map(|v| v.mapv(|f| -(f * temperature_dual).eps)) .collect()) } } impl<D: Dimension + RemoveAxis + 'static, F: HelmholtzEnergyFunctional + Total> DFTProfile<D, F> where D::Larger: Dimension<Smaller = D>, D::Smaller: Dimension<Larger = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { fn ideal_gas_contribution_dual( &self, temperature: Dual64, density: &Array<f64, D::Larger>, ) -> Array<Dual64, D> { let lambda = self.bulk.eos.ln_lambda3(temperature); let mut phi = Array::zeros(density.raw_dim().remove_axis(Axis(0))); for (i, rhoi) in density.outer_iter().enumerate() { phi += &rhoi.mapv(|rhoi| (lambda[i] + rhoi.ln() - 1.0) * rhoi); } phi.map(|p| p * temperature) } /// Calculate the entropy density $s(\mathbf{r})$. /// /// Untested with heterosegmented functionals. pub fn entropy_density( &self, contributions: Contributions, ) -> FeosResult<EntropyDensity<Array<f64, D>>> { // initialize convolver let temperature = self.temperature.to_reduced(); let temperature_dual = Dual64::from(temperature).derivative(); let functional_contributions = self.bulk.eos.contributions(); let weight_functions: Vec<WeightFunctionInfo<Dual64>> = functional_contributions .into_iter() .map(|c| c.weight_functions(temperature_dual)) .collect(); let convolver = ConvolverFFT::plan(&self.grid, &weight_functions, self.lanczos); let density = self.density.to_reduced(); let mut helmholtz_energy_density = self.intrinsic_helmholtz_energy_density( temperature_dual, &density, convolver.as_ref(), )?; match contributions { Contributions::Total => { helmholtz_energy_density += &self.ideal_gas_contribution_dual(temperature_dual, &density); } Contributions::IdealGas => panic!( "Entropy density can only be calculated for Contributions::Residual or Contributions::Total" ), Contributions::Residual => (), } Ok(EntropyDensity::from_reduced( helmholtz_energy_density.mapv(|f| -f.eps), )) } /// Calculate the entropy $S$. /// /// Untested with heterosegmented functionals. pub fn entropy(&self, contributions: Contributions) -> FeosResult<Entropy> { Ok(self.integrate(&self.entropy_density(contributions)?)) } /// Calculate the internal energy density $u(\mathbf{r})$. /// /// Untested with heterosegmented functionals. pub fn internal_energy_density( &self, contributions: Contributions, ) -> FeosResult<Pressure<Array<f64, D>>> where D: Dimension, D::Larger: Dimension<Smaller = D>, { // initialize convolver let temperature = self.temperature.to_reduced(); let temperature_dual = Dual64::from(temperature).derivative(); let functional_contributions = self.bulk.eos.contributions(); let weight_functions: Vec<WeightFunctionInfo<Dual64>> = functional_contributions .into_iter() .map(|c| c.weight_functions(temperature_dual)) .collect(); let convolver = ConvolverFFT::plan(&self.grid, &weight_functions, self.lanczos); let density = self.density.to_reduced(); let mut helmholtz_energy_density_dual = self.intrinsic_helmholtz_energy_density( temperature_dual, &density, convolver.as_ref(), )?; match contributions { Contributions::Total => { helmholtz_energy_density_dual += &self.ideal_gas_contribution_dual(temperature_dual, &density); } Contributions::IdealGas => panic!( "Internal energy density can only be calculated for Contributions::Residual or Contributions::Total" ), Contributions::Residual => (), } let helmholtz_energy_density = helmholtz_energy_density_dual .mapv(|f| f.re - f.eps * temperature) + (&self.external_potential * density).sum_axis(Axis(0)) * temperature; Ok(Pressure::from_reduced(helmholtz_energy_density)) } /// Calculate the internal energy $U$. /// /// Untested with heterosegmented functionals. pub fn internal_energy(&self, contributions: Contributions) -> FeosResult<Energy> { Ok(self.integrate(&self.internal_energy_density(contributions)?)) } } impl<D: Dimension + RemoveAxis + 'static, F: HelmholtzEnergyFunctional> DFTProfile<D, F> where D::Larger: Dimension<Smaller = D>, D::Smaller: Dimension<Larger = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { fn density_derivative(&self, lhs: &Array<f64, D::Larger>) -> FeosResult<Array<f64, D::Larger>> { let rho = self.density.to_reduced(); let partial_density = self.bulk.partial_density.to_reduced(); let rho_bulk = self .bulk .eos .component_index() .iter() .map(|&i| partial_density[i]) .collect(); let second_partial_derivatives = self.second_partial_derivatives(&rho)?; let (_, _, _, exp_dfdrho, _) = self.euler_lagrange_equation(&rho, &rho_bulk, false)?; let rhs = |x: &_| { let delta_functional_derivative = self.delta_functional_derivative(x, &second_partial_derivatives); let mut xm = x.clone(); xm.outer_iter_mut() .zip(self.bulk.eos.m().iter()) .for_each(|(mut x, &m)| x *= m); let delta_i = self.delta_bond_integrals(&exp_dfdrho, &delta_functional_derivative); xm + (delta_functional_derivative - delta_i) * &rho }; let mut log = DFTSolverLog::new(Verbosity::None); Self::gmres(rhs, lhs, 200, 1e-13, &mut log) } /// Return the partial derivatives of the density profiles w.r.t. the chemical potentials $\left(\frac{\partial\rho_i(\mathbf{r})}{\partial\mu_k}\right)_T$ pub fn drho_dmu(&self) -> FeosResult<DrhoDmu<D>> { let shape: Vec<_> = std::iter::once(&self.bulk.eos.components()) .chain(self.density.shape()) .copied() .collect(); let mut drho_dmu = Array::zeros(shape).into_dimensionality().unwrap(); let component_index = self.bulk.eos.component_index(); for (k, mut d) in drho_dmu.outer_iter_mut().enumerate() { let mut lhs = self.density.to_reduced(); for (i, mut l) in lhs.outer_iter_mut().enumerate() { if component_index[i] != k { l.fill(0.0); } } d.assign(&self.density_derivative(&lhs)?); } Ok(Quantity::from_reduced( drho_dmu / self.temperature.to_reduced(), )) } /// Return the partial derivatives of the number of moles w.r.t. the chemical potentials $\left(\frac{\partial N_i}{\partial\mu_k}\right)_T$ pub fn dn_dmu(&self) -> FeosResult<DnDmu> { let drho_dmu = self.drho_dmu()?.into_reduced(); let n = drho_dmu.shape()[0]; let mut dn_dmu = DMatrix::zeros(n, n); dn_dmu .column_iter_mut() .zip(drho_dmu.outer_iter()) .for_each(|(mut dn, drho)| dn.add_assign(&self.integrate_reduced_segments(&drho))); Ok(DnDmu::from_reduced(dn_dmu)) } /// Return the partial derivatives of the density profiles w.r.t. the bulk pressure at constant temperature and bulk composition $\left(\frac{\partial\rho_i(\mathbf{r})}{\partial p}\right)_{T,\mathbf{x}}$ pub fn drho_dp(&self) -> FeosResult<DrhoDp<D>> { let mut lhs = self.density.to_reduced(); let v = self.bulk.partial_molar_volume().to_reduced(); for (mut l, &c) in lhs .outer_iter_mut() .zip(self.bulk.eos.component_index().iter()) { l *= v[c]; } Ok(Quantity::from_reduced( self.density_derivative(&lhs)? / self.temperature.to_reduced(), )) } /// Return the partial derivatives of the number of moles w.r.t. the bulk pressure at constant temperature and bulk composition $\left(\frac{\partial N_i}{\partial p}\right)_{T,\mathbf{x}}$ pub fn dn_dp(&self) -> FeosResult<DnDp> { Ok(self.integrate_segments(&self.drho_dp()?)) } /// Return the partial derivatives of the density profiles w.r.t. the temperature at constant bulk pressure and composition $\left(\frac{\partial\rho_i(\mathbf{r})}{\partial T}\right)_{p,\mathbf{x}}$ pub fn drho_dt(&self) -> FeosResult<DrhoDT<D>> { let rho = self.density.to_reduced(); let t = self.temperature.to_reduced(); let rho_dual = rho.mapv(Dual64::from); let t_dual = Dual64::from(t).derivative(); // calculate intrinsic functional derivative let functional_contributions = self.bulk.eos.contributions(); let weight_functions: Vec<WeightFunctionInfo<Dual64>> = functional_contributions .into_iter() .map(|c| c.weight_functions(t_dual)) .collect(); let convolver: Arc<dyn Convolver<_, D>> = ConvolverFFT::plan(&self.grid, &weight_functions, self.lanczos); let (_, mut dfdrho) = self.bulk .eos .functional_derivative(t_dual, &rho_dual, convolver.as_ref())?; // calculate total functional derivative dfdrho += &(&self.external_potential * t).mapv(|v| Dual64::from(v) / t_dual); // calculate bulk functional derivative let partial_density = self.bulk.partial_density.to_reduced(); let rho_bulk: Array1<_> = self .bulk .eos .component_index() .iter() .map(|&i| partial_density[i]) .collect(); let rho_bulk_dual = rho_bulk.mapv(Dual64::from); let bulk_convolver = BulkConvolver::new(weight_functions); let (_, dfdrho_bulk) = self.bulk .eos .functional_derivative(t_dual, &rho_bulk_dual, bulk_convolver.as_ref())?; dfdrho .outer_iter_mut() .zip(dfdrho_bulk) .zip(self.bulk.eos.m().iter()) .for_each(|((mut df, df_b), &m)| { df.map_inplace(|df| *df = (*df - df_b) / Dual64::from(m)); }); // calculate bond integrals let exp_dfdrho = dfdrho.mapv(|x| (-x).exp()); let bonds = self .bulk .eos .bond_integrals(t_dual, &exp_dfdrho, convolver.as_ref()); // solve for drho_dt let mut lhs = (exp_dfdrho * bonds).mapv(|x| (-x.ln() * t_dual).eps); let x = (self.bulk.partial_molar_volume() * self.bulk.dp_dt(Contributions::Total)).to_reduced(); let x: Array1<_> = self .bulk .eos .component_index() .iter() .map(|&i| x[i]) .collect(); lhs.outer_iter_mut() .zip(rho.outer_iter()) .zip(rho_bulk) .zip(self.bulk.eos.m().iter()) .zip(x) .for_each(|((((mut lhs, rho), rho_b), &m), x)| { lhs += &(&rho / rho_b).mapv(f64::ln); lhs *= m; lhs += x; }); lhs *= &(-&rho / t); lhs.iter_mut().for_each(|l| { if !l.is_finite() { *l = 0.0 } }); Ok(Quantity::from_reduced(self.density_derivative(&lhs)?)) } /// Return the partial derivatives of the number of moles w.r.t. the temperature at constant bulk pressure and composition $\left(\frac{\partial N_i}{\partial T}\right)_{p,\mathbf{x}}$ pub fn dn_dt(&self) -> FeosResult<DnDT> { Ok(self.integrate_segments(&self.drho_dt()?)) } }
Rust
3D
feos-org/feos
crates/feos-dft/src/adsorption/mod.rs
.rs
14,655
411
//! Adsorption profiles and isotherms. use super::functional::HelmholtzEnergyFunctional; use super::solver::DFTSolver; use feos_core::{ Contributions, DensityInitialization, FeosError, FeosResult, ReferenceSystem, SolverOptions, State, StateBuilder, }; use nalgebra::{DMatrix, DVector}; use ndarray::{Array1, Array2, Dimension, Ix1, Ix3, RemoveAxis}; use quantity::{Energy, MolarEnergy, Moles, Pressure, Temperature}; use std::iter; mod external_potential; #[cfg(feature = "rayon")] mod fea_potential; mod pore; mod pore2d; pub use external_potential::{ExternalPotential, FluidParameters}; pub use pore::{HenryCoefficient, Pore1D, PoreProfile, PoreProfile1D, PoreSpecification}; pub use pore2d::{Pore2D, PoreProfile2D}; #[cfg(feature = "rayon")] mod pore3d; #[cfg(feature = "rayon")] pub use pore3d::{Pore3D, PoreProfile3D}; const MAX_ITER_ADSORPTION_EQUILIBRIUM: usize = 50; const TOL_ADSORPTION_EQUILIBRIUM: f64 = 1e-8; /// Container structure for the calculation of adsorption isotherms. pub struct Adsorption<D: Dimension, F> { components: usize, pub profiles: Vec<FeosResult<PoreProfile<D, F>>>, } /// Container structure for adsorption isotherms in 1D pores. pub type Adsorption1D<F> = Adsorption<Ix1, F>; /// Container structure for adsorption isotherms in 3D pores. pub type Adsorption3D<F> = Adsorption<Ix3, F>; impl<D: Dimension + RemoveAxis + 'static, F: HelmholtzEnergyFunctional + FluidParameters> Adsorption<D, F> where D::Larger: Dimension<Smaller = D>, D::Smaller: Dimension<Larger = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { fn new(functional: &F, profiles: Vec<FeosResult<PoreProfile<D, F>>>) -> Self { Self { components: functional.components(), profiles, } } /// Calculate an adsorption isotherm (starting at low pressure) pub fn adsorption_isotherm<S: PoreSpecification<D>>( functional: &F, temperature: Temperature, pressure: &Pressure<Array1<f64>>, pore: &S, molefracs: &Option<DVector<f64>>, solver: Option<&DFTSolver>, ) -> FeosResult<Adsorption<D, F>> { Self::isotherm( functional, temperature, pressure, pore, molefracs, DensityInitialization::Vapor, solver, ) } /// Calculate an desorption isotherm (starting at high pressure) pub fn desorption_isotherm<S: PoreSpecification<D>>( functional: &F, temperature: Temperature, pressure: &Pressure<Array1<f64>>, pore: &S, molefracs: &Option<DVector<f64>>, solver: Option<&DFTSolver>, ) -> FeosResult<Adsorption<D, F>> { let pressure = pressure.into_iter().rev().collect(); let isotherm = Self::isotherm( functional, temperature, &pressure, pore, molefracs, DensityInitialization::Liquid, solver, )?; Ok(Adsorption::new( functional, isotherm.profiles.into_iter().rev().collect(), )) } /// Calculate an equilibrium isotherm pub fn equilibrium_isotherm<S: PoreSpecification<D>>( functional: &F, temperature: Temperature, pressure: &Pressure<Array1<f64>>, pore: &S, molefracs: &Option<DVector<f64>>, solver: Option<&DFTSolver>, ) -> FeosResult<Adsorption<D, F>> { let (p_min, p_max) = (pressure.get(0), pressure.get(pressure.len() - 1)); let equilibrium = Self::phase_equilibrium( functional, temperature, p_min, p_max, pore, molefracs, solver, SolverOptions::default(), ); if let Ok(equilibrium) = equilibrium { let p_eq = equilibrium.pressure().get(0); let p_ads = pressure .into_iter() .filter(|&p| p <= p_eq) .chain(iter::once(p_eq)) .collect(); let p_des = iter::once(p_eq) .chain(pressure.into_iter().filter(|&p| p > p_eq)) .collect(); let adsorption = Self::adsorption_isotherm( functional, temperature, &p_ads, pore, molefracs, solver, )? .profiles; let desorption = Self::desorption_isotherm( functional, temperature, &p_des, pore, molefracs, solver, )? .profiles; Ok(Adsorption { profiles: adsorption.into_iter().chain(desorption).collect(), components: functional.components(), }) } else { let adsorption = Self::adsorption_isotherm( functional, temperature, pressure, pore, molefracs, solver, )?; let desorption = Self::desorption_isotherm( functional, temperature, pressure, pore, molefracs, solver, )?; let omega_a = adsorption.grand_potential(); let omega_d = desorption.grand_potential(); let is_ads = Array1::from_shape_fn(adsorption.profiles.len(), |i| { omega_d.get(i).is_nan() || omega_a.get(i) < omega_d.get(i) }); let profiles = is_ads .into_iter() .zip(adsorption.profiles) .zip(desorption.profiles) .map(|((is_ads, a), d)| if is_ads { a } else { d }) .collect(); Ok(Adsorption::new(functional, profiles)) } } fn isotherm<S: PoreSpecification<D>>( functional: &F, temperature: Temperature, pressure: &Pressure<Array1<f64>>, pore: &S, molefracs: &Option<DVector<f64>>, density_initialization: DensityInitialization, solver: Option<&DFTSolver>, ) -> FeosResult<Adsorption<D, F>> { let x = functional.validate_molefracs(molefracs)?; let mut profiles: Vec<FeosResult<PoreProfile<D, F>>> = Vec::with_capacity(pressure.len()); // On the first iteration, initialize the density profile according to the direction // and calculate the external potential once. let mut bulk = State::new_xpt( functional, temperature, pressure.get(0), &x, Some(density_initialization), )?; if functional.components() > 1 && !bulk.is_stable(SolverOptions::default())? { let vle = bulk.tp_flash(None, SolverOptions::default(), None)?; bulk = match density_initialization { DensityInitialization::Liquid => vle.liquid().clone(), DensityInitialization::Vapor => vle.vapor().clone(), _ => unreachable!(), }; } let profile = pore.initialize(&bulk, None, None)?.solve(solver)?.profile; let external_potential = Some(&profile.external_potential); let mut old_density = Some(&profile.density); for i in 0..pressure.len() { let mut bulk = StateBuilder::new(functional) .temperature(temperature) .pressure(pressure.get(i)) .molefracs(&x) .build()?; if functional.components() > 1 && !bulk.is_stable(SolverOptions::default())? { bulk = bulk .tp_flash(None, SolverOptions::default(), None)? .vapor() .clone(); } let p = pore.initialize(&bulk, old_density, external_potential)?; let p2 = pore.initialize(&bulk, None, external_potential)?; profiles.push(p.solve(solver).or_else(|_| p2.solve(solver))); old_density = if let Some(Ok(l)) = profiles.last() { Some(&l.profile.density) } else { None }; } Ok(Adsorption::new(functional, profiles)) } /// Calculate the phase transition from an empty to a filled pore. #[expect(clippy::too_many_arguments)] pub fn phase_equilibrium<S: PoreSpecification<D>>( functional: &F, temperature: Temperature, p_min: Pressure, p_max: Pressure, pore: &S, molefracs: &Option<DVector<f64>>, solver: Option<&DFTSolver>, options: SolverOptions, ) -> FeosResult<Adsorption<D, F>> { let x = functional.validate_molefracs(molefracs)?; // calculate density profiles for the minimum and maximum pressure let vapor_bulk = StateBuilder::new(functional) .temperature(temperature) .pressure(p_min) .molefracs(&x) .vapor() .build()?; let bulk_init = StateBuilder::new(functional) .temperature(temperature) .pressure(p_max) .molefracs(&x) .liquid() .build()?; let liquid_bulk = StateBuilder::new(functional) .temperature(temperature) .pressure(p_max) .molefracs(&x) .vapor() .build()?; let mut vapor = pore.initialize(&vapor_bulk, None, None)?.solve(solver)?; let mut liquid = pore.initialize(&bulk_init, None, None)?.solve(solver)?; // calculate initial value for bulk density let n_dp_drho_v = (vapor.profile.moles() * vapor_bulk.dp_drho(Contributions::Total)).sum(); let n_dp_drho_l = (liquid.profile.moles() * liquid_bulk.dp_drho(Contributions::Total)).sum(); let mut rho = (vapor.grand_potential.unwrap() + n_dp_drho_v - (liquid.grand_potential.unwrap() + n_dp_drho_l)) / (n_dp_drho_v / vapor_bulk.density - n_dp_drho_l / liquid_bulk.density); // update filled pore with limited step size let mut bulk = StateBuilder::new(functional) .temperature(temperature) .pressure(p_max) .molefracs(&x) .vapor() .build()?; let rho0 = liquid_bulk.density; let steps = (10.0 * (rho - rho0) / rho0).into_value().abs().ceil() as usize; let delta_rho = (rho - rho0) / steps as f64; for i in 1..=steps { let rho_i = rho0 + i as f64 * delta_rho; bulk = State::new_intensive(functional, temperature, rho_i, &x)?; liquid = liquid.update_bulk(&bulk).solve(solver)?; } for _ in 0..options.max_iter.unwrap_or(MAX_ITER_ADSORPTION_EQUILIBRIUM) { // update empty pore vapor = vapor.update_bulk(&bulk).solve(solver)?; // update filled pore liquid = liquid.update_bulk(&bulk).solve(solver)?; // calculate moles let n_dp_drho = ((liquid.profile.moles() - vapor.profile.moles()) * bulk.dp_drho(Contributions::Total)) .sum(); // Newton step let delta_rho = (liquid.grand_potential.unwrap() - vapor.grand_potential.unwrap()) / n_dp_drho * bulk.density; if delta_rho.to_reduced().abs() < options.tol.unwrap_or(TOL_ADSORPTION_EQUILIBRIUM) { return Ok(Adsorption::new(functional, vec![Ok(vapor), Ok(liquid)])); } rho += delta_rho; // update bulk phase bulk = State::new_intensive(functional, temperature, rho, &x)?; } Err(FeosError::NotConverged( "Adsorption::phase_equilibrium".into(), )) } pub fn pressure(&self) -> Pressure<Array1<f64>> { Pressure::from_shape_fn(self.profiles.len(), |i| match &self.profiles[i] { Ok(p) => { if p.profile.bulk.eos.components() > 1 && !p.profile.bulk.is_stable(SolverOptions::default()).unwrap() { p.profile .bulk .tp_flash(None, SolverOptions::default(), None) .unwrap() .vapor() .pressure(Contributions::Total) } else { p.profile.bulk.pressure(Contributions::Total) } } Err(_) => Pressure::from_reduced(f64::NAN), }) } pub fn adsorption(&self) -> Moles<Array2<f64>> { Moles::from_shape_fn( (self.components, self.profiles.len()), |(j, i)| match &self.profiles[i] { Ok(p) => p.profile.moles().get(j), Err(_) => Moles::from_reduced(f64::NAN), }, ) } pub fn total_adsorption(&self) -> Moles<Array1<f64>> { Moles::from_shape_fn(self.profiles.len(), |i| match &self.profiles[i] { Ok(p) => p.profile.total_moles(), Err(_) => Moles::from_reduced(f64::NAN), }) } pub fn grand_potential(&self) -> Energy<Array1<f64>> { Energy::from_shape_fn(self.profiles.len(), |i| match &self.profiles[i] { Ok(p) => p.grand_potential.unwrap(), Err(_) => Energy::from_reduced(f64::NAN), }) } pub fn partial_molar_enthalpy_of_adsorption(&self) -> MolarEnergy<DMatrix<f64>> { let h_ads: Vec<_> = self .profiles .iter() .map(|p| { match p .as_ref() .ok() .and_then(|p| p.partial_molar_enthalpy_of_adsorption().ok()) { Some(p) => p, None => { MolarEnergy::from_reduced(DVector::from_element(self.components, f64::NAN)) } } }) .collect(); MolarEnergy::from_fn(self.components, self.profiles.len(), |j, i| h_ads[i].get(j)) } pub fn enthalpy_of_adsorption(&self) -> MolarEnergy<Array1<f64>> { MolarEnergy::from_shape_fn(self.profiles.len(), |i| { match self.profiles[i] .as_ref() .ok() .and_then(|p| p.enthalpy_of_adsorption().ok()) { Some(p) => p, None => MolarEnergy::from_reduced(f64::NAN), } }) } }
Rust
3D
feos-org/feos
crates/feos-dft/src/adsorption/external_potential.rs
.rs
29,011
657
#[cfg(feature = "rayon")] use crate::adsorption::fea_potential::calculate_fea_potential; use crate::functional::HelmholtzEnergyFunctional; #[cfg(feature = "rayon")] use crate::geometry::Geometry; use libm::tgamma; use nalgebra::DVector; use ndarray::{Array1, Array2, Axis as Axis_nd}; #[cfg(feature = "rayon")] use quantity::Length; use std::f64::consts::PI; use std::ops::Deref; const DELTA_STEELE: f64 = 3.35; /// A collection of external potentials. #[derive(Clone)] pub enum ExternalPotential { /// Hard wall potential: $V_i^\mathrm{ext}(z)=\begin{cases}\infty&z\leq\sigma_{si}\\\\0&z>\sigma_{si}\end{cases},~~~~\sigma_{si}=\frac{1}{2}\left(\sigma_{ss}+\sigma_{ii}\right)$ HardWall { sigma_ss: f64 }, /// 9-3 Lennard-Jones potential: $V_i^\mathrm{ext}(z)=\frac{2\pi}{45} m_i\varepsilon_{si}\sigma_{si}^3\rho_s\left(2\left(\frac{\sigma_{si}}{z}\right)^9-15\left(\frac{\sigma_{si}}{z}\right)^3\right),~~~~\varepsilon_{si}=\sqrt{\varepsilon_{ss}\varepsilon_{ii}},~~~~\sigma_{si}=\frac{1}{2}\left(\sigma_{ss}+\sigma_{ii}\right)$ LJ93 { sigma_ss: f64, epsilon_k_ss: f64, rho_s: f64, }, /// Simple 9-3 Lennard-Jones potential: $V_i^\mathrm{ext}(z)=\varepsilon_{si}\left(\left(\frac{\sigma_{si}}{z}\right)^9-\left(\frac{\sigma_{si}}{z}\right)^3\right),~~~~\varepsilon_{si}=\sqrt{\varepsilon_{ss}\varepsilon_{ii}},~~~~\sigma_{si}=\frac{1}{2}\left(\sigma_{ss}+\sigma_{ii}\right)$ SimpleLJ93 { sigma_ss: f64, epsilon_k_ss: f64 }, /// Custom 9-3 Lennard-Jones potential: $V_i^\mathrm{ext}(z)=\varepsilon_{si}\left(\left(\frac{\sigma_{si}}{z}\right)^9-\left(\frac{\sigma_{si}}{z}\right)^3\right)$ CustomLJ93 { sigma_sf: Array1<f64>, epsilon_k_sf: Array1<f64>, }, /// Steele potential: $V_i^\mathrm{ext}(z)=2\pi m_i\xi\varepsilon_{si}\sigma_{si}^2\Delta\rho_s\left(0.4\left(\frac{\sigma_{si}}{z}\right)^{10}-\left(\frac{\sigma_{si}}{z}\right)^4-\frac{\sigma_{si}^4}{3\Delta\left(z+0.61\Delta\right)^3}\right),~~~~\varepsilon_{si}=\sqrt{\varepsilon_{ss}\varepsilon_{ii}},~~~~\sigma_{si}=\frac{1}{2}\left(\sigma_{ss}+\sigma_{ii}\right),~~~~\Delta=3.35$ Steele { sigma_ss: f64, epsilon_k_ss: f64, rho_s: f64, xi: Option<f64>, }, /// Steele potential with custom combining rules: $V_i^\mathrm{ext}(z)=2\pi m_i\xi\varepsilon_{si}\sigma_{si}^2\Delta\rho_s\left(0.4\left(\frac{\sigma_{si}}{z}\right)^{10}-\left(\frac{\sigma_{si}}{z}\right)^4-\frac{\sigma_{si}^4}{3\Delta\left(z+0.61\Delta\right)^3}\right),~~~~\Delta=3.35$ CustomSteele { sigma_sf: Array1<f64>, epsilon_k_sf: Array1<f64>, rho_s: f64, xi: Option<f64>, }, /// Double well potential: $V_i^\mathrm{ext}(z)=\mathrm{min}\left(\frac{2\pi}{45} m_i\varepsilon_{2si}\sigma_{si}^3\rho_s\left(2\left(\frac{2\sigma_{si}}{z}\right)^9-15\left(\frac{2\sigma_{si}}{z}\right)^3\right),0\right)+\frac{2\pi}{45} m_i\varepsilon_{1si}\sigma_{si}^3\rho_s\left(2\left(\frac{\sigma_{si}}{z}\right)^9-15\left(\frac{\sigma_{si}}{z}\right)^3\right),~~~~\varepsilon_{1si}=\sqrt{\varepsilon_{1ss}\varepsilon_{ii}},~~~~\varepsilon_{2si}=\sqrt{\varepsilon_{2ss}\varepsilon_{ii}},~~~~\sigma_{si}=\frac{1}{2}\left(\sigma_{ss}+\sigma_{ii}\right)$ DoubleWell { sigma_ss: f64, epsilon1_k_ss: f64, epsilon2_k_ss: f64, rho_s: f64, }, /// Free-energy averaged potential: #[cfg(feature = "rayon")] FreeEnergyAveraged { coordinates: Length<Array2<f64>>, sigma_ss: Array1<f64>, epsilon_k_ss: Array1<f64>, pore_center: [f64; 3], system_size: [Length; 3], n_grid: [usize; 2], cutoff_radius: Option<f64>, }, /// Custom potential Custom(Array2<f64>), } /// Parameters of the fluid required to evaluate the external potential. pub trait FluidParameters { fn epsilon_k_ff(&self) -> DVector<f64>; fn sigma_ff(&self) -> DVector<f64>; } impl<C: Deref<Target = T>, T: FluidParameters> FluidParameters for C { fn epsilon_k_ff(&self) -> DVector<f64> { T::epsilon_k_ff(self) } fn sigma_ff(&self) -> DVector<f64> { T::sigma_ff(self) } } impl ExternalPotential { // Evaluate the external potential in cartesian coordinates for a given grid and fluid parameters. pub fn calculate_cartesian_potential<P: HelmholtzEnergyFunctional + FluidParameters>( &self, z_grid: &Array1<f64>, fluid_parameters: &P, #[cfg_attr(not(feature = "rayon"), expect(unused_variables))] temperature: f64, ) -> Array2<f64> { if let ExternalPotential::Custom(potential) = self { return potential.clone(); } // Allocate external potential let m = fluid_parameters.m(); let mut ext_pot = Array2::zeros((m.len(), z_grid.len())); for (i, &mi) in m.iter().enumerate() { ext_pot.index_axis_mut(Axis_nd(0), i).assign(&match self { Self::HardWall { sigma_ss } => { let sigma_sf = (fluid_parameters.sigma_ff()[i] + *sigma_ss) * 0.5; z_grid.mapv(|z| if z < sigma_sf { f64::INFINITY } else { 0.0 }) } Self::LJ93 { sigma_ss, epsilon_k_ss, rho_s, } => { // combining rules let epsilon_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon_k_ss).map(|e| e.sqrt()); let sigma_sf = fluid_parameters.sigma_ff().add_scalar(*sigma_ss) * 0.5; 2.0 * PI * mi * epsilon_k_sf[i] * sigma_sf[i].powi(3) * rho_s / 45.0 * (2.0 * (sigma_sf[i] / z_grid).mapv(|x| x.powi(9)) - 15.0 * (sigma_sf[i] / z_grid).mapv(|x| x.powi(3))) } Self::SimpleLJ93 { sigma_ss, epsilon_k_ss, } => { // combining rules let epsilon_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon_k_ss).map(|e| e.sqrt()); let sigma_sf = fluid_parameters.sigma_ff().add_scalar(*sigma_ss) * 0.5; epsilon_k_sf[i] * ((sigma_sf[i] / z_grid).mapv(|x| x.powi(9)) - (sigma_sf[i] / z_grid).mapv(|x| x.powi(3))) } Self::CustomLJ93 { sigma_sf, epsilon_k_sf, } => { epsilon_k_sf[i] * ((sigma_sf[i] / z_grid).mapv(|x| x.powi(9)) - (sigma_sf[i] / z_grid).mapv(|x| x.powi(3))) } Self::Steele { sigma_ss, epsilon_k_ss, rho_s, xi, } => { // combining rules let epsilon_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon_k_ss).map(|e| e.sqrt()); let sigma_sf = fluid_parameters.sigma_ff().add_scalar(*sigma_ss) * 0.5; (2.0 * PI * mi * xi.unwrap_or(1.0) * epsilon_k_sf[i]) * (sigma_sf[i].powi(2) * DELTA_STEELE * rho_s) * (0.4 * (sigma_sf[i] / z_grid).mapv(|x| x.powi(10)) - (sigma_sf[i] / z_grid).mapv(|x| x.powi(4)) - sigma_sf[i].powi(4) / ((3.0 * DELTA_STEELE) * (z_grid + 0.61 * DELTA_STEELE).mapv(|x| x.powi(3)))) } Self::CustomSteele { sigma_sf, epsilon_k_sf, rho_s, xi, } => { (2.0 * PI * mi * xi.unwrap_or(1.0) * epsilon_k_sf[i]) * (sigma_sf[i].powi(2) * DELTA_STEELE * rho_s) * (0.4 * (sigma_sf[i] / z_grid).mapv(|x| x.powi(10)) - (sigma_sf[i] / z_grid).mapv(|x| x.powi(4)) - sigma_sf[i].powi(4) / ((3.0 * DELTA_STEELE) * (z_grid + 0.61 * DELTA_STEELE).mapv(|x| x.powi(3)))) } Self::DoubleWell { sigma_ss, epsilon1_k_ss, epsilon2_k_ss, rho_s, } => { // combining rules let epsilon1_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon1_k_ss).map(|e| e.sqrt()); let epsilon2_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon2_k_ss).map(|e| e.sqrt()); let sigma_sf = fluid_parameters.sigma_ff().add_scalar(*sigma_ss) * 0.5; let bh_tail = (2.0 * PI * mi * epsilon2_k_sf[i] * sigma_sf[i].powi(3) * rho_s / 45.0 * (2.0 * (2.0 * sigma_sf[i] / z_grid).mapv(|x| x.powi(9)) - 15.0 * (2.0 * sigma_sf[i] / z_grid).mapv(|x| x.powi(3)))) .mapv(|x| x.min(0.0)); bh_tail + &(2.0 * PI * mi * epsilon1_k_sf[i] * sigma_sf[i].powi(3) * rho_s / 45.0 * (2.0 * (sigma_sf[i] / z_grid).mapv(|x| x.powi(9)) - 15.0 * (sigma_sf[i] / z_grid).mapv(|x| x.powi(3)))) } #[cfg(feature = "rayon")] Self::FreeEnergyAveraged { coordinates, sigma_ss, epsilon_k_ss, pore_center, system_size, n_grid, cutoff_radius, } => { // combining rules let epsilon_k_sf = (fluid_parameters.epsilon_k_ff()[i] * epsilon_k_ss).map(|e| e.sqrt()); let sigma_sf = (fluid_parameters.sigma_ff()[i] + sigma_ss) * 0.5; calculate_fea_potential( z_grid, mi, coordinates, sigma_sf, epsilon_k_sf, pore_center, system_size, n_grid, temperature, Geometry::Cartesian, *cutoff_radius, ) } _ => unreachable!(), }); } ext_pot } // Evaluate the external potential in cylindrical coordinates for a given grid and fluid parameters. pub fn calculate_cylindrical_potential<P: HelmholtzEnergyFunctional + FluidParameters>( &self, r_grid: &Array1<f64>, pore_size: f64, fluid_parameters: &P, #[cfg_attr(not(feature = "rayon"), expect(unused_variables))] temperature: f64, ) -> Array2<f64> { if let ExternalPotential::Custom(potential) = self { return potential.clone(); } // Allocate external potential let m = fluid_parameters.m(); let mut ext_pot = Array2::zeros((m.len(), r_grid.len())); for (i, &mi) in m.iter().enumerate() { ext_pot.index_axis_mut(Axis_nd(0), i).assign(&match self { Self::HardWall { sigma_ss } => { let sigma_sf = (fluid_parameters.sigma_ff()[i] + *sigma_ss) * 0.5; r_grid.mapv(|r| { if r > pore_size - sigma_sf { f64::INFINITY } else { 0.0 } }) } Self::LJ93 { sigma_ss, epsilon_k_ss, rho_s, } => { // combining rules let epsilon_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon_k_ss).map(|e| e.sqrt()); let sigma_sf = fluid_parameters.sigma_ff().add_scalar(*sigma_ss) * 0.5; (phi(6, &(r_grid / pore_size), sigma_sf[i] / pore_size) - phi(3, &(r_grid / pore_size), sigma_sf[i] / pore_size)) * 2.0 * PI * mi * epsilon_k_sf[i] * sigma_sf[i].powi(3) * *rho_s } Self::SimpleLJ93 { sigma_ss: _, epsilon_k_ss: _, } => { unimplemented!() } Self::CustomLJ93 { sigma_sf: _, epsilon_k_sf: _, } => { unimplemented!() } Self::Steele { sigma_ss, epsilon_k_ss, rho_s, xi, } => { // combining rules let epsilon_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon_k_ss).map(|e| e.sqrt()); let sigma_sf = fluid_parameters.sigma_ff().add_scalar(*sigma_ss) * 0.5; (2.0 * PI * mi * xi.unwrap_or(1.0) * epsilon_k_sf[i]) * (sigma_sf[i].powi(2) * DELTA_STEELE * rho_s) * (psi(6, &(r_grid / pore_size), sigma_sf[i] / pore_size) - psi(3, &(r_grid / pore_size), sigma_sf[i] / pore_size) - sigma_sf[i] / DELTA_STEELE * phi( 3, &(r_grid / (pore_size + DELTA_STEELE * 0.61)), sigma_sf[i] / (pore_size + DELTA_STEELE * 0.61), )) } Self::CustomSteele { sigma_sf, epsilon_k_sf, rho_s, xi, } => { (2.0 * PI * mi * xi.unwrap_or(1.0) * epsilon_k_sf[i]) * (sigma_sf[i].powi(2) * DELTA_STEELE * rho_s) * (psi(6, &(r_grid / pore_size), sigma_sf[i] / pore_size) - psi(3, &(r_grid / pore_size), sigma_sf[i] / pore_size) - sigma_sf[i] / DELTA_STEELE * phi( 3, &(r_grid / (pore_size + DELTA_STEELE * 0.61)), sigma_sf[i] / (pore_size + DELTA_STEELE * 0.61), )) } Self::DoubleWell { sigma_ss, epsilon1_k_ss, epsilon2_k_ss, rho_s, } => { // combining rules let epsilon1_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon1_k_ss).map(|e| e.sqrt()); let epsilon2_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon2_k_ss).map(|e| e.sqrt()); let sigma_sf = fluid_parameters.sigma_ff().add_scalar(*sigma_ss) * 0.5; let bh_tail = ((phi(6, &(r_grid / pore_size), 2.0 * sigma_sf[i] / pore_size) - phi(3, &(r_grid / pore_size), 2.0 * sigma_sf[i] / pore_size)) * 2.0 * PI * mi * epsilon2_k_sf[i] * sigma_sf[i].powi(3) * *rho_s) .mapv(|x| x.min(0.0)); bh_tail + &((phi(6, &(r_grid / pore_size), sigma_sf[i] / pore_size) - phi(3, &(r_grid / pore_size), sigma_sf[i] / pore_size)) * 2.0 * PI * mi * epsilon1_k_sf[i] * sigma_sf[i].powi(3) * *rho_s) } #[cfg(feature = "rayon")] Self::FreeEnergyAveraged { coordinates, sigma_ss, epsilon_k_ss, pore_center, system_size, n_grid, cutoff_radius, } => { // combining rules let epsilon_k_sf = (fluid_parameters.epsilon_k_ff()[i] * epsilon_k_ss).map(|e| e.sqrt()); let sigma_sf = (fluid_parameters.sigma_ff()[i] + sigma_ss) * 0.5; calculate_fea_potential( r_grid, mi, coordinates, sigma_sf, epsilon_k_sf, pore_center, system_size, n_grid, temperature, Geometry::Cylindrical, *cutoff_radius, ) } _ => unreachable!(), }); } ext_pot } // Evaluate the external potential in spherical coordinates for a given grid and fluid parameters. pub fn calculate_spherical_potential<P: HelmholtzEnergyFunctional + FluidParameters>( &self, r_grid: &Array1<f64>, pore_size: f64, fluid_parameters: &P, #[cfg_attr(not(feature = "rayon"), expect(unused_variables))] temperature: f64, ) -> Array2<f64> { if let ExternalPotential::Custom(potential) = self { return potential.clone(); } // Allocate external potential let m = fluid_parameters.m(); let mut ext_pot = Array2::zeros((m.len(), r_grid.len())); for (i, &mi) in m.iter().enumerate() { ext_pot.index_axis_mut(Axis_nd(0), i).assign(&match self { Self::HardWall { sigma_ss } => { let sigma_sf = (fluid_parameters.sigma_ff()[i] + *sigma_ss) * 0.5; r_grid.mapv(|r| { if r > pore_size - sigma_sf { f64::INFINITY } else { 0.0 } }) } Self::LJ93 { sigma_ss, epsilon_k_ss, rho_s, } => { // combining rules let epsilon_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon_k_ss).map(|e| e.sqrt()); let sigma_sf = fluid_parameters.sigma_ff().add_scalar(*sigma_ss) * 0.5; PI * mi * epsilon_k_sf[i] * rho_s * (sigma_sf[i].powi(12) / 90. * ((r_grid - 9.0 * pore_size) / (r_grid - pore_size).mapv(|x| x.powi(9)) - (r_grid + 9.0 * pore_size) / (r_grid + pore_size).mapv(|x| x.powi(9))) - sigma_sf[i].powi(6) / 3. * ((r_grid - 3.0 * pore_size) / (r_grid - pore_size).mapv(|x| x.powi(3)) - (r_grid + 3.0 * pore_size) / (r_grid + pore_size).mapv(|x| x.powi(3)))) / r_grid } Self::SimpleLJ93 { sigma_ss: _, epsilon_k_ss: _, } => { unimplemented!() } Self::CustomLJ93 { sigma_sf: _, epsilon_k_sf: _, } => { unimplemented!() } Self::Steele { sigma_ss, epsilon_k_ss, rho_s, xi, } => { // combining rules let epsilon_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon_k_ss).map(|e| e.sqrt()); let sigma_sf = fluid_parameters.sigma_ff().add_scalar(*sigma_ss) * 0.5; (2.0 * PI * mi * xi.unwrap_or(1.0) * epsilon_k_sf[i]) * (sigma_sf[i].powi(2) * DELTA_STEELE * rho_s) * (2.0 / 5.0 * sum_n(10, r_grid, sigma_sf[i], pore_size) - sum_n(4, r_grid, sigma_sf[i], pore_size) - sigma_sf[i] / (3.0 * DELTA_STEELE) * (sigma_sf[i].powi(3) / r_grid .mapv(|r| (pore_size + 0.61 * DELTA_STEELE - r).powi(3)) + sigma_sf[i].powi(3) / r_grid.mapv(|r| { (pore_size + 0.61 * DELTA_STEELE + r).powi(3) }) + 1.5 * sum_n( 3, r_grid, sigma_sf[i], pore_size + 0.61 * DELTA_STEELE, ))) } Self::CustomSteele { sigma_sf, epsilon_k_sf, rho_s, xi, } => { (2.0 * PI * mi * xi.unwrap_or(1.0) * epsilon_k_sf[i]) * (sigma_sf[i].powi(2) * DELTA_STEELE * rho_s) * (2.0 / 5.0 * sum_n(10, r_grid, sigma_sf[i], pore_size) - sum_n(4, r_grid, sigma_sf[i], pore_size) - sigma_sf[i] / (3.0 * DELTA_STEELE) * (sigma_sf[i].powi(3) / r_grid .mapv(|r| (pore_size + 0.61 * DELTA_STEELE - r).powi(3)) + sigma_sf[i].powi(3) / r_grid.mapv(|r| { (pore_size + 0.61 * DELTA_STEELE + r).powi(3) }) + 1.5 * sum_n( 3, r_grid, sigma_sf[i], pore_size + 0.61 * DELTA_STEELE, ))) } Self::DoubleWell { sigma_ss, epsilon1_k_ss, epsilon2_k_ss, rho_s, } => { // combining rules let epsilon1_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon1_k_ss).map(|e| e.sqrt()); let epsilon2_k_sf = (fluid_parameters.epsilon_k_ff() * *epsilon2_k_ss).map(|e| e.sqrt()); let sigma_sf = fluid_parameters.sigma_ff().add_scalar(*sigma_ss) * 0.5; let bh_tail = (2.0 * PI * mi * epsilon2_k_sf[i] * sigma_sf[i].powi(2) * rho_s * (2.0 / 5.0 * sum_n(10, r_grid, 2.0 * sigma_sf[i], pore_size) - sum_n(4, r_grid, 2.0 * sigma_sf[i], pore_size))) .mapv(|x| x.min(0.0)); bh_tail + &(2.0 * PI * mi * epsilon1_k_sf[i] * sigma_sf[i].powi(2) * rho_s * (2.0 / 5.0 * sum_n(10, r_grid, sigma_sf[i], pore_size) - sum_n(4, r_grid, sigma_sf[i], pore_size))) } #[cfg(feature = "rayon")] Self::FreeEnergyAveraged { coordinates, sigma_ss, epsilon_k_ss, pore_center, system_size, n_grid, cutoff_radius, } => { // combining rules let epsilon_k_sf = (fluid_parameters.epsilon_k_ff()[i] * epsilon_k_ss).map(|e| e.sqrt()); let sigma_sf = (fluid_parameters.sigma_ff()[i] + sigma_ss) * 0.5; calculate_fea_potential( r_grid, mi, coordinates, sigma_sf, epsilon_k_sf, pore_center, system_size, n_grid, temperature, Geometry::Spherical, *cutoff_radius, ) } _ => unreachable!(), }); } ext_pot } } fn phi(n: i32, r_r: &Array1<f64>, sigma_r: f64) -> Array1<f64> { let m3n2 = 3.0 - 2.0 * n as f64; let n2m3 = 2.0 * n as f64 - 3.0; (1.0 - &r_r.mapv(|r| r.powi(2))).mapv(|r| r.powf(m3n2)) * 4.0 * PI.sqrt() / n2m3 * sigma_r.powf(n2m3) * tgamma(n as f64 - 0.5) / tgamma(n as f64) * taylor_2f1_phi(r_r, n) } fn psi(n: i32, r_r: &Array1<f64>, sigma_r: f64) -> Array1<f64> { (1.0 - &r_r.mapv(|r| r.powi(2))).mapv(|r| r.powf(2.0 - 2.0 * n as f64)) * 4.0 * PI.sqrt() * tgamma(n as f64 - 0.5) / tgamma(n as f64) * sigma_r.powf(2.0 * n as f64 - 2.0) * taylor_2f1_psi(r_r, n) } fn sum_n(n: i32, r_grid: &Array1<f64>, sigma: f64, pore_size: f64) -> Array1<f64> { let mut result = Array1::zeros(r_grid.len()); for i in 0..n { result = result + sigma.powi(n) / (pore_size.powi(i) * r_grid.mapv(|r| (pore_size - r).powi(n - i))) + sigma.powi(n) / (pore_size.powi(i) * r_grid.mapv(|r| (pore_size + r).powi(n - i))); } result } fn taylor_2f1_phi(x: &Array1<f64>, n: i32) -> Array1<f64> { match n { 3 => { 1.0 + 3.0 / 4.0 * x.mapv(|x| x.powi(2)) + 3.0 / 64.0 * x.mapv(|x| x.powi(4)) - 1.0 / 256.0 * x.mapv(|x| x.powi(6)) - 15.0 / 16384.0 * x.mapv(|x| x.powi(8)) } 6 => { 1.0 + 63.0 / 4.0 * x.mapv(|x| x.powi(2)) + 2205.0 / 64.0 * x.mapv(|x| x.powi(4)) + 3675.0 / 256.0 * x.mapv(|x| x.powi(6)) + 11025.0 / 16384.0 * x.mapv(|x| x.powi(8)) } _ => unreachable!(), } } fn taylor_2f1_psi(x: &Array1<f64>, n: i32) -> Array1<f64> { match n { 3 => { 1.0 + 9.0 / 4.0 * x.mapv(|x| x.powi(2)) + 9.0 / 64.0 * x.mapv(|x| x.powi(4)) + 1.0 / 256.0 * x.mapv(|x| x.powi(6)) + 9.0 / 16384.0 * x.mapv(|x| x.powi(8)) } 6 => { 1.0 + 81.0 / 4.0 * x.mapv(|x| x.powi(2)) + 3969.0 / 64.0 * x.mapv(|x| x.powi(4)) + 11025.0 / 256.0 * x.mapv(|x| x.powi(6)) + 99125.0 / 16384.0 * x.mapv(|x| x.powi(8)) } _ => unreachable!(), } }
Rust
3D
feos-org/feos
crates/feos-dft/src/adsorption/pore3d.rs
.rs
7,000
218
use super::pore::{PoreProfile, PoreSpecification}; use crate::adsorption::FluidParameters; use crate::functional::HelmholtzEnergyFunctional; use crate::geometry::{Axis, Grid}; use crate::profile::{CUTOFF_RADIUS, DFTProfile, MAX_POTENTIAL}; use feos_core::{FeosError, FeosResult, ReferenceSystem, State}; use ndarray::Zip; use ndarray::prelude::*; use quantity::{Angle, DEGREES, Density, Length}; /// Parameters required to specify a 3D pore. pub struct Pore3D { system_size: [Length; 3], angles: Option<[Angle; 3]>, n_grid: [usize; 3], coordinates: Length<Array2<f64>>, sigma_ss: Array1<f64>, epsilon_k_ss: Array1<f64>, potential_cutoff: Option<f64>, cutoff_radius: Option<Length>, } impl Pore3D { #[expect(clippy::too_many_arguments)] pub fn new( system_size: [Length; 3], n_grid: [usize; 3], coordinates: Length<Array2<f64>>, sigma_ss: Array1<f64>, epsilon_k_ss: Array1<f64>, angles: Option<[Angle; 3]>, potential_cutoff: Option<f64>, cutoff_radius: Option<Length>, ) -> Self { Self { system_size, angles, n_grid, coordinates, sigma_ss, epsilon_k_ss, potential_cutoff, cutoff_radius, } } } /// Density profile and properties of a 3D confined system. pub type PoreProfile3D<F> = PoreProfile<Ix3, F>; impl PoreSpecification<Ix3> for Pore3D { fn initialize<F: HelmholtzEnergyFunctional + FluidParameters>( &self, bulk: &State<F>, density: Option<&Density<Array4<f64>>>, external_potential: Option<&Array4<f64>>, ) -> FeosResult<PoreProfile3D<F>> { let dft: &F = &bulk.eos; // generate grid let x = Axis::new_cartesian(self.n_grid[0], self.system_size[0], None); let y = Axis::new_cartesian(self.n_grid[1], self.system_size[1], None); let z = Axis::new_cartesian(self.n_grid[2], self.system_size[2], None); let coordinates = self.coordinates.to_reduced(); // temperature let t = bulk.temperature.to_reduced(); // For non-orthorombic unit cells, the external potential has to be // provided at the moment if let (Some(_), None) = (self.angles, external_potential) { return Err(FeosError::UndeterminedState( "For non-orthorombic unit cells, the external potential has to provided!".into(), )); } // calculate external potential let external_potential = external_potential.map_or_else( || { external_potential_3d( dft, [&x, &y, &z], self.system_size, coordinates, &self.sigma_ss, &self.epsilon_k_ss, self.cutoff_radius, self.potential_cutoff, t, ) }, |e| Ok(e.clone()), )?; let grid = Grid::Periodical3(x, y, z, self.angles.unwrap_or([90.0 * DEGREES; 3])); Ok(PoreProfile { profile: DFTProfile::new(grid, bulk, Some(external_potential), density, Some(1)), grand_potential: None, interfacial_tension: None, }) } } #[expect(clippy::too_many_arguments)] pub fn external_potential_3d<F: HelmholtzEnergyFunctional + FluidParameters>( functional: &F, axis: [&Axis; 3], system_size: [Length; 3], coordinates: Array2<f64>, sigma_ss: &Array1<f64>, epsilon_ss: &Array1<f64>, cutoff_radius: Option<Length>, potential_cutoff: Option<f64>, reduced_temperature: f64, ) -> FeosResult<Array4<f64>> { // allocate external potential let m = functional.m(); let mut external_potential = Array4::zeros(( m.len(), axis[0].grid.len(), axis[1].grid.len(), axis[2].grid.len(), )); let system_size = [ system_size[0].to_reduced(), system_size[1].to_reduced(), system_size[2].to_reduced(), ]; let cutoff_radius = cutoff_radius .unwrap_or(Length::from_reduced(CUTOFF_RADIUS)) .to_reduced(); if system_size.iter().any(|&s| s < 2.0 * cutoff_radius) { return Err(FeosError::UndeterminedState( "The unit cell is smaller than 2*cutoff".into(), )); } // square cut-off radius let cutoff_radius2 = cutoff_radius.powi(2); // calculate external potential let sigma_ff = functional.sigma_ff(); let epsilon_k_ff = functional.epsilon_k_ff(); Zip::indexed(&mut external_potential).par_for_each(|(i, ix, iy, iz), u| { let distance2 = calculate_distance2( [axis[0].grid[ix], axis[1].grid[iy], axis[2].grid[iz]], &coordinates, system_size, ); let sigma_sf = sigma_ss.mapv(|s| (s + sigma_ff[i]) / 2.0); let epsilon_sf = epsilon_ss.mapv(|e| (e * epsilon_k_ff[i]).sqrt()); *u = (0..sigma_ss.len()) .map(|alpha| { m[i] * evaluate_lj_potential( distance2[alpha], sigma_sf[alpha], epsilon_sf[alpha], cutoff_radius2, ) }) .sum::<f64>() / reduced_temperature }); let potential_cutoff = potential_cutoff.unwrap_or(MAX_POTENTIAL); external_potential.map_inplace(|x| { if *x > potential_cutoff { *x = potential_cutoff } }); Ok(external_potential) } /// Evaluate LJ12-6 potential between solid site "alpha" and fluid segment pub(super) fn evaluate_lj_potential( distance2: f64, sigma: f64, epsilon: f64, cutoff_radius2: f64, ) -> f64 { let sigma_r = sigma.powi(2) / distance2; let potential: f64 = if distance2 > cutoff_radius2 { 0.0 } else if distance2 == 0.0 { f64::INFINITY } else { 4.0 * epsilon * (sigma_r.powi(6) - sigma_r.powi(3)) }; potential } /// Evaluate the squared euclidian distance between a point and the coordinates of all solid atoms. pub(super) fn calculate_distance2( point: [f64; 3], coordinates: &Array2<f64>, system_size: [f64; 3], ) -> Array1<f64> { Array1::from_shape_fn(coordinates.ncols(), |i| { let mut rx = coordinates[[0, i]] - point[0]; let mut ry = coordinates[[1, i]] - point[1]; let mut rz = coordinates[[2, i]] - point[2]; rx -= system_size[0] * (rx / system_size[0]).round(); ry -= system_size[1] * (ry / system_size[1]).round(); rz -= system_size[2] * (rz / system_size[2]).round(); rx.powi(2) + ry.powi(2) + rz.powi(2) }) }
Rust
3D
feos-org/feos
crates/feos-dft/src/adsorption/fea_potential.rs
.rs
5,060
137
use super::pore3d::{calculate_distance2, evaluate_lj_potential}; use crate::profile::{CUTOFF_RADIUS, MAX_POTENTIAL}; use crate::Geometry; use feos_core::ReferenceSystem; use gauss_quad::GaussLegendre; use ndarray::{Array1, Array2, Zip}; use quantity::Length; use std::f64::consts::PI; // Calculate free-energy average potential for given solid structure. #[expect(clippy::too_many_arguments)] pub fn calculate_fea_potential( grid: &Array1<f64>, mi: f64, coordinates: &Length<Array2<f64>>, sigma_sf: Array1<f64>, epsilon_k_sf: Array1<f64>, pore_center: &[f64; 3], system_size: &[Length; 3], n_grid: &[usize; 2], temperature: f64, geometry: Geometry, cutoff_radius: Option<f64>, ) -> Array1<f64> { // allocate external potential let mut potential: Array1<f64> = Array1::zeros(grid.len()); // calculate squared cutoff radius let cutoff_radius2 = cutoff_radius.unwrap_or(CUTOFF_RADIUS).powi(2); // dimensionless solid coordinates let coordinates = Array2::from_shape_fn(coordinates.raw_dim(), |(i, j)| { (coordinates.get((i, j))).to_reduced() }); let system_size = [ system_size[0].to_reduced(), system_size[1].to_reduced(), system_size[2].to_reduced(), ]; // Create secondary axis: // Cartesian coordinates => y // Cylindrical coordinates => phi // Spherical coordinates => phi let (nodes1, weights1) = match geometry { Geometry::Cartesian => { let nodes = Array1::linspace( 0.5 * system_size[1] / n_grid[0] as f64, system_size[1] - 0.5 * system_size[1] / n_grid[0] as f64, n_grid[0], ); let weights = Array1::from_elem(n_grid[0], system_size[1] / n_grid[0] as f64); (nodes, weights) } Geometry::Spherical | Geometry::Cylindrical => { let (unscaled_nodes, unscaled_weights) = GaussLegendre::new(n_grid[0]).unwrap().into_iter().unzip(); let nodes = PI + Array1::from_vec(unscaled_nodes) * PI; let weights = Array1::from_vec(unscaled_weights) * PI; (nodes, weights) } }; // Create tertiary axis // Cartesian coordinates => z // Cylindrical coordinates => z // Spherical coordinates => theta let (nodes2, weights2) = match geometry { Geometry::Cylindrical | Geometry::Cartesian => { let nodes = Array1::linspace( 0.5 * system_size[2] / n_grid[1] as f64, system_size[2] - 0.5 * system_size[2] / n_grid[1] as f64, n_grid[1], ); let weights = Array1::from_elem(n_grid[1], system_size[2] / n_grid[1] as f64); (nodes, weights) } Geometry::Spherical => { let (unscaled_nodes, unscaled_weights) = GaussLegendre::new(n_grid[1]).unwrap().into_iter().unzip(); let nodes = PI / 2.0 + Array1::from_vec(unscaled_nodes) * PI / 2.0; let weights = Array1::from_vec(unscaled_weights) * PI / 2.0 * Array1::from_shape_fn(n_grid[1], |i| nodes[i].sin()); (nodes, weights) } }; // calculate weights let weights = Array2::from_shape_fn((n_grid[0], n_grid[1]), |(i, j)| weights1[i] * weights2[j]); // calculate sum of weights let weights_sum = weights.sum(); // calculate FEA potential Zip::indexed(&mut potential).par_for_each(|i0, f| { let mut potential_2d: Array2<f64> = Array2::zeros((n_grid[0], n_grid[1])); for (i1, &n1) in nodes1.iter().enumerate() { for (i2, &n2) in nodes2.iter().enumerate() { let point = match geometry { Geometry::Cartesian => [grid[i0], n1, n2], Geometry::Cylindrical => [ pore_center[0] + grid[i0] * n1.cos(), pore_center[1] + grid[i0] * n1.sin(), n2, ], Geometry::Spherical => [ pore_center[0] + grid[i0] * n2.sin() * n1.cos(), pore_center[1] + grid[i0] * n2.sin() * n1.sin(), pore_center[2] + grid[i0] * n2.cos(), ], }; let distance2 = calculate_distance2(point, &coordinates, system_size); let potential_sum: f64 = (0..sigma_sf.len()) .map(|alpha| { mi * evaluate_lj_potential( distance2[alpha], sigma_sf[alpha], epsilon_k_sf[alpha], cutoff_radius2, ) / temperature }) .sum(); potential_2d[[i1, i2]] = (-potential_sum.min(MAX_POTENTIAL)).exp(); } } *f = (potential_2d * &weights).sum(); }); -temperature * potential.map(|p| (p / weights_sum).ln()) }
Rust
3D
feos-org/feos
crates/feos-dft/src/adsorption/pore.rs
.rs
12,019
361
use crate::WeightFunctionInfo; use crate::adsorption::{ExternalPotential, FluidParameters}; use crate::convolver::ConvolverFFT; use crate::functional::{HelmholtzEnergyFunctional, HelmholtzEnergyFunctionalDyn, MoleculeShape}; use crate::functional_contribution::FunctionalContribution; use crate::geometry::{Axis, Geometry, Grid}; use crate::profile::{DFTProfile, MAX_POTENTIAL}; use crate::solver::DFTSolver; use feos_core::{ Contributions, FeosResult, ReferenceSystem, ResidualDyn, State, StateBuilder, StateHD, }; use nalgebra::{DVector, dvector}; use ndarray::prelude::*; use ndarray::{Axis as Axis_nd, RemoveAxis}; use num_dual::linalg::LU; use num_dual::{Dual64, DualNum}; use quantity::{ _Moles, _Pressure, Density, Dimensionless, Energy, KELVIN, Length, MolarEnergy, Quantity, RGAS, Temperature, Volume, }; use rustdct::DctNum; use std::ops::Sub; const POTENTIAL_OFFSET: f64 = 2.0; const DEFAULT_GRID_POINTS: usize = 2048; pub type _HenryCoefficient = <_Moles as Sub<_Pressure>>::Output; pub type HenryCoefficient<T> = Quantity<T, _HenryCoefficient>; /// Parameters required to specify a 1D pore. pub struct Pore1D { pub geometry: Geometry, pub pore_size: Length, pub potential: ExternalPotential, pub n_grid: Option<usize>, pub potential_cutoff: Option<f64>, } impl Pore1D { pub fn new( geometry: Geometry, pore_size: Length, potential: ExternalPotential, n_grid: Option<usize>, potential_cutoff: Option<f64>, ) -> Self { Self { geometry, pore_size, potential, n_grid, potential_cutoff, } } } /// Trait for the generic implementation of adsorption applications. pub trait PoreSpecification<D: Dimension> { /// Initialize a new single pore. fn initialize<F: HelmholtzEnergyFunctional + FluidParameters>( &self, bulk: &State<F>, density: Option<&Density<Array<f64, D::Larger>>>, external_potential: Option<&Array<f64, D::Larger>>, ) -> FeosResult<PoreProfile<D, F>>; /// Return the pore volume using Helium at 298 K as reference. fn pore_volume(&self) -> FeosResult<Volume> where D::Larger: Dimension<Smaller = D>, { let bulk = StateBuilder::new(&&Helium) .temperature(298.0 * KELVIN) .density(Density::from_reduced(1.0)) .build()?; let pore = self.initialize(&bulk, None, None)?; let pot = Dimensionless::from_reduced( pore.profile .external_potential .index_axis(Axis(0), 0) .mapv(|v| (-v).exp()), ); Ok(pore.profile.integrate(&pot)) } } /// Density profile and properties of a confined system in arbitrary dimensions. #[derive(Clone)] pub struct PoreProfile<D: Dimension, F> { pub profile: DFTProfile<D, F>, pub grand_potential: Option<Energy>, pub interfacial_tension: Option<Energy>, } /// Density profile and properties of a 1D confined system. pub type PoreProfile1D<F> = PoreProfile<Ix1, F>; impl<D: Dimension + RemoveAxis + 'static, F: HelmholtzEnergyFunctional> PoreProfile<D, F> where D::Larger: Dimension<Smaller = D>, D::Smaller: Dimension<Larger = D>, <D::Larger as Dimension>::Larger: Dimension<Smaller = D::Larger>, { pub fn solve_inplace(&mut self, solver: Option<&DFTSolver>, debug: bool) -> FeosResult<()> { // Solve the profile self.profile.solve(solver, debug)?; // calculate grand potential density let omega = self.profile.grand_potential()?; self.grand_potential = Some(omega); // calculate interfacial tension self.interfacial_tension = Some(omega + self.profile.bulk.pressure(Contributions::Total) * self.profile.volume()); Ok(()) } pub fn solve(mut self, solver: Option<&DFTSolver>) -> FeosResult<Self> { self.solve_inplace(solver, false)?; Ok(self) } pub fn update_bulk(mut self, bulk: &State<F>) -> Self { self.profile.bulk = bulk.clone(); self.grand_potential = None; self.interfacial_tension = None; self } pub fn partial_molar_enthalpy_of_adsorption(&self) -> FeosResult<MolarEnergy<DVector<f64>>> { let a = self.profile.dn_dmu()?; let a_unit = a.get2(0, 0); let b = -self.profile.temperature * self.profile.dn_dt()?; let b_unit = b.get(0); let h_ads = LU::new((a / a_unit).into_value())?.solve(&(b / b_unit).into_value()); Ok(&h_ads * b_unit / a_unit) } pub fn enthalpy_of_adsorption(&self) -> FeosResult<MolarEnergy> { Ok(self .partial_molar_enthalpy_of_adsorption()? .dot(&Dimensionless::new(self.profile.bulk.molefracs.clone()))) } fn _henry_coefficients<N: DualNum<f64> + Copy + DctNum>(&self, temperature: N) -> DVector<N> { if self.profile.bulk.eos.m().iter().any(|&m| m != 1.0) { panic!( "Henry coefficients can only be calculated for spherical and heterosegmented molecules!" ) }; let pot = (self.profile.external_potential.mapv(N::from) * self.profile.temperature.to_reduced()) .mapv(|v| v / temperature); let exp_pot = pot.mapv(|v| (-v).exp()); let functional_contributions = self.profile.bulk.eos.contributions(); let weight_functions: Vec<WeightFunctionInfo<N>> = functional_contributions .into_iter() .map(|c| c.weight_functions(temperature)) .collect(); let convolver = ConvolverFFT::<_, D>::plan(&self.profile.grid, &weight_functions, self.profile.lanczos); let bonds = self .profile .bulk .eos .bond_integrals(temperature, &exp_pot, convolver.as_ref()); self.profile.integrate_reduced_segments(&(exp_pot * bonds)) } pub fn henry_coefficients(&self) -> HenryCoefficient<DVector<f64>> { let t = self.profile.temperature.to_reduced(); Volume::from_reduced(self._henry_coefficients(t)) / (RGAS * self.profile.temperature) } pub fn ideal_gas_enthalpy_of_adsorption(&self) -> MolarEnergy<DVector<f64>> { let t = Dual64::from(self.profile.temperature.to_reduced()).derivative(); let h_dual = self._henry_coefficients(t); let h = h_dual.map(|h| h.re); let dh = h_dual.map(|h| h.eps); let t = self.profile.temperature.to_reduced(); RGAS * self.profile.temperature * Dimensionless::from_reduced((&h - t * dh).component_div(&h)) } } impl PoreSpecification<Ix1> for Pore1D { fn initialize<F: HelmholtzEnergyFunctional + FluidParameters>( &self, bulk: &State<F>, density: Option<&Density<Array2<f64>>>, external_potential: Option<&Array2<f64>>, ) -> FeosResult<PoreProfile1D<F>> { let dft: &F = &bulk.eos; let n_grid = self.n_grid.unwrap_or(DEFAULT_GRID_POINTS); let axis = match self.geometry { Geometry::Cartesian => { let potential_offset = POTENTIAL_OFFSET * bulk .eos .sigma_ff() .iter() .max_by(|a, b| a.total_cmp(b)) .unwrap(); Axis::new_cartesian(n_grid, 0.5 * self.pore_size, Some(potential_offset)) } Geometry::Cylindrical => Axis::new_polar(n_grid, self.pore_size), Geometry::Spherical => Axis::new_spherical(n_grid, self.pore_size), }; // calculate external potential let external_potential = external_potential.map_or_else( || { external_potential_1d( self.pore_size, bulk.temperature, &self.potential, dft, &axis, self.potential_cutoff, ) }, |e| e.clone(), ); // initialize grid let grid = Grid::new_1d(axis); Ok(PoreProfile { profile: DFTProfile::new(grid, bulk, Some(external_potential), density, Some(1)), grand_potential: None, interfacial_tension: None, }) } } fn external_potential_1d<P: HelmholtzEnergyFunctional + FluidParameters>( pore_width: Length, temperature: Temperature, potential: &ExternalPotential, fluid_parameters: &P, axis: &Axis, potential_cutoff: Option<f64>, ) -> Array2<f64> { let potential_cutoff = potential_cutoff.unwrap_or(MAX_POTENTIAL); let effective_pore_size = match axis.geometry { Geometry::Spherical => pore_width.to_reduced(), Geometry::Cylindrical => pore_width.to_reduced(), Geometry::Cartesian => 0.5 * pore_width.to_reduced(), }; let t = temperature.to_reduced(); let mut external_potential = match &axis.geometry { Geometry::Cartesian => { potential.calculate_cartesian_potential( &(effective_pore_size + &axis.grid), fluid_parameters, t, ) + &potential.calculate_cartesian_potential( &(effective_pore_size - &axis.grid), fluid_parameters, t, ) } Geometry::Spherical => potential.calculate_spherical_potential( &axis.grid, effective_pore_size, fluid_parameters, t, ), Geometry::Cylindrical => potential.calculate_cylindrical_potential( &axis.grid, effective_pore_size, fluid_parameters, t, ), } / t; for (i, &z) in axis.grid.iter().enumerate() { if z > effective_pore_size { external_potential .index_axis_mut(Axis_nd(1), i) .fill(potential_cutoff); } } external_potential.map_inplace(|x| { if *x > potential_cutoff { *x = potential_cutoff } }); external_potential } const EPSILON_HE: f64 = 10.9; const SIGMA_HE: f64 = 2.64; #[derive(Clone, Copy)] struct Helium; impl ResidualDyn for Helium { fn components(&self) -> usize { 1 } fn compute_max_density<D: DualNum<f64> + Copy>(&self, _: &DVector<D>) -> D { D::from(1.0) } fn reduced_helmholtz_energy_density_contributions<D: DualNum<f64> + Copy>( &self, state: &StateHD<D>, ) -> Vec<(&'static str, D)> { self.evaluate_bulk(state) } } impl HelmholtzEnergyFunctionalDyn for Helium { type Contribution<'a> = HeliumContribution where Self: 'a; fn contributions<'a>(&'a self) -> impl Iterator<Item = Self::Contribution<'a>> { std::iter::empty() } fn molecule_shape(&self) -> MoleculeShape<'_> { MoleculeShape::Spherical(1) } } impl FluidParameters for &Helium { fn epsilon_k_ff(&self) -> DVector<f64> { dvector![EPSILON_HE] } fn sigma_ff(&self) -> DVector<f64> { dvector![SIGMA_HE] } } struct HeliumContribution; impl FunctionalContribution for HeliumContribution { fn weight_functions<N: DualNum<f64> + Copy>(&self, _: N) -> WeightFunctionInfo<N> { unreachable!() } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, _: N, _: ArrayView2<N>, ) -> FeosResult<Array1<N>> { unreachable!() } fn name(&self) -> &'static str { unreachable!() } }
Rust
3D
feos-org/feos
crates/feos-dft/src/adsorption/pore2d.rs
.rs
1,329
44
use super::{FluidParameters, PoreProfile, PoreSpecification}; use crate::{Axis, DFTProfile, Grid, HelmholtzEnergyFunctional}; use feos_core::{FeosResult, State}; use ndarray::{Array3, Ix2}; use quantity::{Angle, Density, Length}; pub struct Pore2D { system_size: [Length<f64>; 2], angle: Angle, n_grid: [usize; 2], } pub type PoreProfile2D<F> = PoreProfile<Ix2, F>; impl Pore2D { pub fn new(system_size: [Length<f64>; 2], angle: Angle, n_grid: [usize; 2]) -> Self { Self { system_size, angle, n_grid, } } } impl PoreSpecification<Ix2> for Pore2D { fn initialize<F: HelmholtzEnergyFunctional + FluidParameters>( &self, bulk: &State<F>, density: Option<&Density<Array3<f64>>>, external_potential: Option<&Array3<f64>>, ) -> FeosResult<PoreProfile<Ix2, F>> { // generate grid let x = Axis::new_cartesian(self.n_grid[0], self.system_size[0], None); let y = Axis::new_cartesian(self.n_grid[1], self.system_size[1], None); let grid = Grid::Periodical2(x, y, self.angle); Ok(PoreProfile { profile: DFTProfile::new(grid, bulk, external_potential.cloned(), density, Some(1)), grand_potential: None, interfacial_tension: None, }) } }
Rust
3D
feos-org/feos
crates/feos-dft/src/solvation/mod.rs
.rs
262
9
//! Solvation free energies and pair correlaion functions. mod pair_correlation; pub use pair_correlation::{PairCorrelation, PairPotential}; #[cfg(feature = "rayon")] mod solvation_profile; #[cfg(feature = "rayon")] pub use solvation_profile::SolvationProfile;
Rust
3D
feos-org/feos
crates/feos-dft/src/solvation/pair_correlation.rs
.rs
3,292
91
//! Functionalities for the calculation of pair correlation functions. use crate::functional::HelmholtzEnergyFunctional; use crate::profile::MAX_POTENTIAL; use crate::solver::DFTSolver; use crate::{Axis, DFTProfile, Grid}; use feos_core::{Contributions, FeosResult, ReferenceSystem, State}; use ndarray::prelude::*; use quantity::{Energy, Length}; use std::ops::Deref; /// The underlying pair potential, that the Helmholtz energy functional /// models. pub trait PairPotential { /// Return the pair potential of particle i with all other particles. fn pair_potential(&self, i: usize, r: &Array1<f64>, temperature: f64) -> Array2<f64>; } impl<C: Deref<Target = T>, T: PairPotential> PairPotential for C { fn pair_potential(&self, i: usize, r: &Array1<f64>, temperature: f64) -> Array2<f64> { T::pair_potential(self, i, r, temperature) } } /// Density profile and properties of a test particle system. pub struct PairCorrelation<F> { pub profile: DFTProfile<Ix1, F>, pub pair_correlation_function: Option<Array2<f64>>, pub self_solvation_free_energy: Option<Energy>, pub structure_factor: Option<f64>, } impl<F: HelmholtzEnergyFunctional + PairPotential> PairCorrelation<F> { pub fn new(bulk: &State<F>, test_particle: usize, n_grid: usize, width: Length) -> Self { let dft = &bulk.eos; // generate grid let axis = Axis::new_spherical(n_grid, width); // calculate external potential let t = bulk.temperature.to_reduced(); let mut external_potential = dft.pair_potential(test_particle, &axis.grid, t) / t; external_potential.map_inplace(|x| { if *x > MAX_POTENTIAL { *x = MAX_POTENTIAL } }); let grid = Grid::Spherical(axis); Self { profile: DFTProfile::new(grid, bulk, Some(external_potential), None, Some(1)), pair_correlation_function: None, self_solvation_free_energy: None, structure_factor: None, } } pub fn solve_inplace(&mut self, solver: Option<&DFTSolver>, debug: bool) -> FeosResult<()> { // Solve the profile self.profile.solve(solver, debug)?; // calculate pair correlation function self.pair_correlation_function = Some(Array::from_shape_fn( self.profile.density.raw_dim(), |(i, j)| { (self.profile.density.get((i, j)) / self.profile.bulk.partial_density.get(i)) .into_value() }, )); // calculate self solvation free energy self.self_solvation_free_energy = Some(self.profile.integrate( &(self.profile.grand_potential_density()? + self.profile.bulk.pressure(Contributions::Total)), )); // calculate structure factor self.structure_factor = Some( (self.profile.total_moles() - self.profile.bulk.density * self.profile.volume()) .to_reduced() + 1.0, ); Ok(()) } pub fn solve(mut self, solver: Option<&DFTSolver>) -> FeosResult<Self> { self.solve_inplace(solver, false)?; Ok(self) } }
Rust
3D
feos-org/feos
crates/feos-dft/src/solvation/solvation_profile.rs
.rs
6,169
191
use crate::adsorption::FluidParameters; use crate::functional::HelmholtzEnergyFunctional; use crate::geometry::{Axis, Grid}; use crate::profile::{CUTOFF_RADIUS, DFTProfile, MAX_POTENTIAL}; use crate::solver::DFTSolver; use feos_core::{Contributions, FeosResult, ReferenceSystem, State}; use ndarray::Zip; use ndarray::prelude::*; use quantity::{Energy, Length, MolarEnergy, Moles}; /// Density profile and properties of a solute in a inhomogeneous bulk fluid. pub struct SolvationProfile<F: HelmholtzEnergyFunctional> { pub profile: DFTProfile<Ix3, F>, pub grand_potential: Option<Energy>, pub solvation_free_energy: Option<MolarEnergy>, } impl<F: HelmholtzEnergyFunctional> SolvationProfile<F> { pub fn solve_inplace(&mut self, solver: Option<&DFTSolver>, debug: bool) -> FeosResult<()> { // Solve the profile self.profile.solve(solver, debug)?; // calculate grand potential density let omega = self.profile.grand_potential()?; self.grand_potential = Some(omega); // calculate solvation free energy self.solvation_free_energy = Some( (omega + self.profile.bulk.pressure(Contributions::Total) * self.profile.volume()) / Moles::from_reduced(1.0), ); Ok(()) } pub fn solve(mut self, solver: Option<&DFTSolver>) -> FeosResult<Self> { self.solve_inplace(solver, false)?; Ok(self) } } impl<F: HelmholtzEnergyFunctional + FluidParameters> SolvationProfile<F> { #[expect(clippy::too_many_arguments)] pub fn new( bulk: &State<F>, n_grid: [usize; 3], coordinates: Length<Array2<f64>>, sigma_ss: Array1<f64>, epsilon_ss: Array1<f64>, system_size: Option<[Length; 3]>, cutoff_radius: Option<Length>, potential_cutoff: Option<f64>, ) -> FeosResult<Self> { let dft: &F = &bulk.eos; let system_size = system_size.unwrap_or([Length::from_reduced(40.0); 3]); // generate grid let x = Axis::new_cartesian(n_grid[0], system_size[0], None); let y = Axis::new_cartesian(n_grid[1], system_size[1], None); let z = Axis::new_cartesian(n_grid[2], system_size[2], None); // move center of geometry of solute to box center let mut coordinates = Array2::from_shape_fn(coordinates.raw_dim(), |(i, j)| { (coordinates.get((i, j))).to_reduced() }); let center = [ system_size[0].to_reduced() / 2.0, system_size[1].to_reduced() / 2.0, system_size[2].to_reduced() / 2.0, ]; let shift: Array2<f64> = Array2::from_shape_fn((3, 1), |(i, _)| { center[i] - coordinates.row(i).sum() / coordinates.ncols() as f64 }); coordinates = coordinates + shift; // temperature let t = bulk.temperature.to_reduced(); // calculate external potential let external_potential = external_potential_3d( dft, [&x, &y, &z], coordinates, sigma_ss, epsilon_ss, cutoff_radius, potential_cutoff, t, )?; let grid = Grid::Cartesian3(x, y, z); Ok(Self { profile: DFTProfile::new(grid, bulk, Some(external_potential), None, Some(1)), grand_potential: None, solvation_free_energy: None, }) } } #[expect(clippy::too_many_arguments)] fn external_potential_3d<F: HelmholtzEnergyFunctional + FluidParameters>( functional: &F, axis: [&Axis; 3], coordinates: Array2<f64>, sigma_ss: Array1<f64>, epsilon_ss: Array1<f64>, cutoff_radius: Option<Length>, potential_cutoff: Option<f64>, reduced_temperature: f64, ) -> FeosResult<Array4<f64>> { // allocate external potential let m = functional.m(); let mut external_potential = Array4::zeros(( m.len(), axis[0].grid.len(), axis[1].grid.len(), axis[2].grid.len(), )); let cutoff_radius = cutoff_radius .unwrap_or(Length::from_reduced(CUTOFF_RADIUS)) .to_reduced(); // square cut-off radius let cutoff_radius2 = cutoff_radius.powi(2); // calculate external potential let sigma_ff = functional.sigma_ff(); let epsilon_k_ff = functional.epsilon_k_ff(); Zip::indexed(&mut external_potential).par_for_each(|(i, ix, iy, iz), u| { let distance2 = calculate_distance2( [&axis[0].grid[ix], &axis[1].grid[iy], &axis[2].grid[iz]], &coordinates, ); let sigma_sf = sigma_ss.mapv(|s| (s + sigma_ff[i]) / 2.0); let epsilon_sf = epsilon_ss.mapv(|e| (e * epsilon_k_ff[i]).sqrt()); *u = (0..sigma_ss.len()) .map(|alpha| { m[i] * evaluate( distance2[alpha], sigma_sf[alpha], epsilon_sf[alpha], cutoff_radius2, ) }) .sum::<f64>() / reduced_temperature }); let potential_cutoff = potential_cutoff.unwrap_or(MAX_POTENTIAL); external_potential.map_inplace(|x| { if *x > potential_cutoff { *x = potential_cutoff } }); Ok(external_potential) } /// Evaluate LJ12-6 potential between solid site "alpha" and fluid segment fn evaluate(distance2: f64, sigma: f64, epsilon: f64, cutoff_radius2: f64) -> f64 { let sigma_r = sigma.powi(2) / distance2; let potential: f64 = if distance2 > cutoff_radius2 { 0.0 } else if distance2 == 0.0 { f64::INFINITY } else { 4.0 * epsilon * (sigma_r.powi(6) - sigma_r.powi(3)) }; potential } /// Evaluate the squared euclidian distance between a point and the coordinates of all solid atoms. fn calculate_distance2(point: [&f64; 3], coordinates: &Array2<f64>) -> Array1<f64> { Array1::from_shape_fn(coordinates.ncols(), |i| { let rx = coordinates[[0, i]] - point[0]; let ry = coordinates[[1, i]] - point[1]; let rz = coordinates[[2, i]] - point[2]; rx.powi(2) + ry.powi(2) + rz.powi(2) }) }
Rust
3D
feos-org/feos
crates/feos/src/lib.rs
.rs
1,968
74
//! FeOs - An open-source framework for equations of state and classical functional density theory. //! //! # Example: critical point of a pure substance using PC-SAFT //! #![cfg_attr(not(feature = "pcsaft"), doc = "```ignore")] #![cfg_attr(feature = "pcsaft", doc = "```")] //! # use feos_core::FeosError; //! use feos::pcsaft::{PcSaft, PcSaftParameters}; //! use feos_core::parameter::{IdentifierOption}; //! use feos_core::{Contributions, State}; //! use quantity::KELVIN; //! use nalgebra::dvector; //! //! // Read parameters from json file. //! let parameters = PcSaftParameters::from_json( //! vec!["propane"], //! "../../parameters/pcsaft/esper2023.json", //! None, //! IdentifierOption::Name, //! )?; //! //! // Define equation of state. //! let saft = PcSaft::new(parameters); //! //! // Define thermodynamic conditions. //! let critical_point = State::critical_point(&&saft, Some(&dvector![1.0]), None, None, Default::default())?; //! //! // Compute properties. //! let p = critical_point.pressure(Contributions::Total); //! let t = critical_point.temperature; //! println!("Critical point: T={}, p={}.", t, p); //! # Ok::<(), FeosError>(()) //! ``` #![warn(clippy::all)] #![warn(clippy::allow_attributes)] // pub mod estimator; #[cfg(feature = "association")] pub mod association; pub mod hard_sphere; // models #[cfg(feature = "epcsaft")] pub mod epcsaft; #[cfg(feature = "gc_pcsaft")] pub mod gc_pcsaft; #[cfg(feature = "multiparameter")] pub mod multiparameter; #[cfg(feature = "pcsaft")] pub mod pcsaft; #[cfg(feature = "pets")] pub mod pets; #[cfg(feature = "saftvrmie")] pub mod saftvrmie; #[cfg(feature = "saftvrqmie")] pub mod saftvrqmie; #[cfg(feature = "uvtheory")] pub mod uvtheory; pub mod ideal_gas; pub mod core { //! Re-export of all functionalities in [feos_core]. pub use feos_core::*; } #[cfg(feature = "dft")] pub mod dft { //! Re-export of all functionalities in [feos_dft]. pub use feos_dft::*; }
Rust
3D
feos-org/feos
crates/feos/src/saftvrqmie/mod.rs
.rs
830
20
//! SAFT-VRQ Mie equation of state. //! //! Quantum effects are described by the first order Feynman–Hibbs corrections to Mie fluids. //! The model accurately predicts properties for pure substances and mixtures down to 20K. //! For mixtures, the additive hard-sphere reference contribution is extended with a non-additive correction. //! //! # Literature //! - Pure substances: [Aasen et al. (2019)](https://aip.scitation.org/doi/10.1063/1.5111364) //! - Binary mixtures: [Aasen et al. (2020)](https://aip.scitation.org/doi/10.1063/1.5136079) #[cfg(feature = "dft")] mod dft; mod eos; mod parameters; #[cfg(feature = "dft")] pub use dft::SaftVRQMieFunctionalContribution; pub use eos::{FeynmanHibbsOrder, SaftVRQMie, SaftVRQMieOptions}; pub use parameters::{SaftVRQMieBinaryRecord, SaftVRQMieParameters, SaftVRQMieRecord};
Rust
3D
feos-org/feos
crates/feos/src/saftvrqmie/parameters.rs
.rs
10,808
324
use crate::saftvrqmie::eos::FeynmanHibbsOrder; use core::cmp::max; use feos_core::parameter::Parameters; use feos_core::{FeosError, FeosResult}; use nalgebra::{DMatrix, DVector}; use quantity::{KILOGRAM, NAV}; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; /// SAFT-VRQ Mie pure-component parameters. #[derive(Serialize, Deserialize, Clone, Default)] pub struct SaftVRQMieRecord { /// Segment number pub m: f64, /// Segment diameter in units of Angstrom pub sigma: f64, /// Energetic parameter in units of Kelvin pub epsilon_k: f64, /// Repulsive Mie exponent pub lr: f64, /// Attractive Mie exponent pub la: f64, /// Feynman-Hibbs order pub fh: usize, } impl SaftVRQMieRecord { pub fn new( m: f64, sigma: f64, epsilon_k: f64, lr: f64, la: f64, fh: usize, ) -> FeosResult<SaftVRQMieRecord> { if m != 1.0 { return Err(FeosError::IncompatibleParameters( "Segment number `m` is not one. Chain-contributions are currently not supported." .to_string(), )); } Ok(SaftVRQMieRecord { m, sigma, epsilon_k, lr, la, fh, }) } } /// SAFT-VRQ Mie binary mixture parameters. #[derive(Serialize, Deserialize, Clone, Copy, Default)] pub struct SaftVRQMieBinaryRecord { /// correction to energy parameters pub k_ij: f64, /// correction to diameter pub l_ij: f64, } /// Parameter set required for the SAFT-VRQ Mie equation of state and Helmholtz energy functional. pub type SaftVRQMieParameters = Parameters<SaftVRQMieRecord, SaftVRQMieBinaryRecord, ()>; /// Parameter set required for the SAFT-VRQ Mie equation of state and Helmholtz energy functional. pub struct SaftVRQMiePars { pub m: DVector<f64>, pub sigma: DVector<f64>, pub epsilon_k: DVector<f64>, pub sigma_ij: DMatrix<f64>, pub epsilon_k_ij: DMatrix<f64>, pub c_ij: DMatrix<f64>, pub lambda_r_ij: DMatrix<f64>, pub lambda_a_ij: DMatrix<f64>, pub mass_ij: DMatrix<f64>, pub fh_ij: DMatrix<FeynmanHibbsOrder>, } impl SaftVRQMiePars { pub fn new(parameters: &SaftVRQMieParameters) -> FeosResult<Self> { let n = parameters.pure.len(); let [fh] = parameters.collate(|pr| [pr.fh]); let [m, sigma, epsilon_k] = parameters.collate(|pr| [pr.m, pr.sigma, pr.epsilon_k]); let [lr, la] = parameters.collate(|pr| [pr.lr, pr.la]); let molarweight = &parameters.molar_weight; for (i, m) in m.iter().enumerate() { if *m != 1.0 { return Err(FeosError::IncompatibleParameters(format!( "Segment number `m` for component {i} is not one. Chain-contributions are currently not supported." ))); } } let mut fh_ij: DMatrix<FeynmanHibbsOrder> = DMatrix::from_element(n, n, FeynmanHibbsOrder::FH0); let [k_ij, l_ij] = parameters.collate_binary(|b| [b.k_ij, b.l_ij]); let mut epsilon_k_ij = DMatrix::zeros(n, n); let mut sigma_ij = DMatrix::zeros(n, n); let mut e_k_ij = DMatrix::zeros(n, n); let mut lambda_r_ij = DMatrix::zeros(n, n); let mut lambda_a_ij = DMatrix::zeros(n, n); let mut c_ij = DMatrix::zeros(n, n); let mut mass_ij = DMatrix::zeros(n, n); for i in 0..n { for j in 0..n { sigma_ij[(i, j)] = (1.0 - l_ij[(i, j)]) * 0.5 * (sigma[i] + sigma[j]); e_k_ij[(i, j)] = (sigma[i].powi(3) * sigma[j].powi(3)).sqrt() / sigma_ij[(i, j)].powi(3) * (epsilon_k[i] * epsilon_k[j]).sqrt(); epsilon_k_ij[(i, j)] = (1.0 - k_ij[(i, j)]) * e_k_ij[(i, j)]; lambda_r_ij[(i, j)] = ((lr[i] - 3.0) * (lr[j] - 3.0)).sqrt() + 3.0; lambda_a_ij[(i, j)] = ((la[i] - 3.0) * (la[j] - 3.0)).sqrt() + 3.0; c_ij[(i, j)] = lambda_r_ij[(i, j)] / (lambda_r_ij[(i, j)] - lambda_a_ij[(i, j)]) * (lambda_r_ij[(i, j)] / lambda_a_ij[(i, j)]) .powf(lambda_a_ij[(i, j)] / (lambda_r_ij[(i, j)] - lambda_a_ij[(i, j)])); mass_ij[(i, j)] = (2.0 * molarweight.get(i) * molarweight.get(j) / (molarweight.get(i) + molarweight.get(j))) .convert_into(KILOGRAM * NAV); fh_ij[(i, j)] = FeynmanHibbsOrder::try_from(max(fh[i], fh[j]))?; if fh[i] * fh[j] == 2 { return Err(FeosError::IncompatibleParameters(format!( "cannot combine Feynman-Hibbs orders 1 and 2. Component {} has order {} and component {} has order {}.", i, fh[i], j, fh[j] ))); } } } Ok(Self { m, sigma, epsilon_k, sigma_ij, epsilon_k_ij, c_ij, lambda_r_ij, lambda_a_ij, mass_ij, fh_ij, }) } } #[cfg(test)] pub mod utils { use feos_core::parameter::PureRecord; use super::*; pub fn hydrogen_fh(fh: &str) -> SaftVRQMiePars { let hydrogen_json = &(r#" { "identifier": { "cas": "1333-74-0", "name": "hydrogen", "iupac_name": "hydrogen", "smiles": "[HH]", "inchi": "InChI=1S/H2/h1H", "formula": "H2" }, "m": 1.0, "sigma": 3.0243, "epsilon_k": 26.706, "lr": 9.0, "la": 6.0, "fh": "# .to_owned() + fh + r#", "molarweight": 2.0157309551872 }"#); let hydrogen_record: PureRecord<SaftVRQMieRecord, ()> = serde_json::from_str(hydrogen_json).expect("Unable to parse json."); SaftVRQMiePars::new(&SaftVRQMieParameters::new_pure(hydrogen_record).unwrap()).unwrap() } pub fn helium_fh1() -> PureRecord<SaftVRQMieRecord, ()> { let helium_json = r#" { "identifier": { "cas": "1333-74-0", "name": "helium", "iupac_name": "helium", "smiles": "[HH]", "inchi": "InChI=1S/H2/h1H", "formula": "He" }, "m": 1.0, "sigma": 2.7443, "epsilon_k": 5.4195, "lr": 9.0, "la": 6.0, "fh": 1, "molarweight": 4.002601643881807 }"#; serde_json::from_str(helium_json).expect("Unable to parse json.") } pub fn hydrogen_fh2() -> PureRecord<SaftVRQMieRecord, ()> { let helium_json = r#" { "identifier": { "cas": "1333-74-0", "name": "hydrogen", "iupac_name": "hydrogen", "smiles": "[HH]", "inchi": "InChI=1S/H2/h1H", "formula": "H2" }, "m": 1.0, "sigma": 3.0243, "epsilon_k": 26.706, "lr": 9.0, "la": 6.0, "fh": 2, "molarweight": 2.0157309551872 }"#; serde_json::from_str(helium_json).expect("Unable to parse json.") } #[expect(dead_code)] pub fn neon_fh1() -> SaftVRQMieParameters { let neon_json = r#" { "identifier": { "cas": "1333-74-0", "name": "neon", "iupac_name": "neon", "smiles": "[HH]", "inchi": "InChI=1S/H2/h1H", "formula": "Ne" }, "m": 1.0, "sigma": 2.7778, "epsilon_k": 37.501, "lr": 13.0, "la": 6.0, "fh": 1, "molarweight": 20.17969806457545 }"#; let neon_record: PureRecord<SaftVRQMieRecord, ()> = serde_json::from_str(neon_json).expect("Unable to parse json."); SaftVRQMieParameters::new_pure(neon_record).unwrap() } pub fn h2_ne_fh(fh: &str) -> SaftVRQMiePars { let binary_json = &(r#"[ { "identifier": { "cas": "1333-74-0", "name": "hydrogen", "iupac_name": "hydrogen", "smiles": "[HH]", "inchi": "InChI=1S/H2/h1H", "formula": "H2" }, "m": 1.0, "sigma": 3.0243, "epsilon_k": 26.706, "lr": 9.0, "la": 6.0, "fh": "# .to_owned() + fh + r#", "molarweight": 2.0157309551872 }, { "identifier": { "cas": "1333-74-0", "name": "neon", "iupac_name": "neon", "smiles": "[HH]", "inchi": "InChI=1S/H2/h1H", "formula": "H2" }, "m": 1.0, "sigma": 2.7778, "epsilon_k": 37.501, "lr": 13.0, "la": 6.0, "fh": "# + fh + r#", "molarweight": 20.17969806457545 } ]"#); let binary_record: [PureRecord<SaftVRQMieRecord, ()>; 2] = serde_json::from_str(binary_json).expect("Unable to parse json."); SaftVRQMiePars::new( &SaftVRQMieParameters::new_binary( binary_record, Some(SaftVRQMieBinaryRecord { k_ij: 0.105, l_ij: 0.0, }), vec![], ) .unwrap(), ) .unwrap() } } #[cfg(test)] mod test { use super::SaftVRQMieParameters; use super::utils::{helium_fh1, hydrogen_fh2}; use crate::saftvrqmie::SaftVRQMie; #[test] #[should_panic( expected = "cannot combine Feynman-Hibbs orders 1 and 2. Component 0 has order 1 and component 1 has order 2." )] fn incompatible_order() { let order1 = helium_fh1(); let order2 = hydrogen_fh2(); SaftVRQMie::new(SaftVRQMieParameters::new_binary([order1, order2], None, vec![]).unwrap()) .unwrap(); } }
Rust
3D
feos-org/feos
crates/feos/src/saftvrqmie/eos/mod.rs
.rs
8,498
262
#[cfg(feature = "dft")] use crate::hard_sphere::FMTVersion; use super::parameters::{SaftVRQMieParameters, SaftVRQMiePars}; use feos_core::{ FeosError, FeosResult, Molarweight, ReferenceSystem, ResidualDyn, StateHD, Subset, }; use nalgebra::{DMatrix, DVector}; use num_dual::DualNum; use quantity::*; use std::convert::TryFrom; use std::f64::consts::FRAC_PI_6; use std::fs::File; use std::io::BufWriter; pub(crate) mod dispersion; pub(crate) mod hard_sphere; pub(crate) mod non_additive_hs; use dispersion::Dispersion; use hard_sphere::HardSphere; use non_additive_hs::NonAddHardSphere; /// Customization options for the SAFT-VRQ Mie equation of state and functional. #[derive(Copy, Clone)] pub struct SaftVRQMieOptions { pub max_eta: f64, pub inc_nonadd_term: bool, #[cfg(feature = "dft")] pub fmt_version: FMTVersion, } impl Default for SaftVRQMieOptions { fn default() -> Self { Self { max_eta: 0.5, inc_nonadd_term: true, #[cfg(feature = "dft")] fmt_version: FMTVersion::WhiteBear, } } } /// Order of Feynman-Hibbs potential #[derive(Copy, Clone, PartialEq, Debug)] pub enum FeynmanHibbsOrder { /// Mie potential FH0 = 0, /// First order correction FH1 = 1, /// Second order correction FH2 = 2, } impl TryFrom<usize> for FeynmanHibbsOrder { type Error = FeosError; fn try_from(u: usize) -> Result<Self, Self::Error> { match u { 0 => Ok(Self::FH0), 1 => Ok(Self::FH1), 2 => Ok(Self::FH2), _ => Err(FeosError::IncompatibleParameters(format!( "failed to parse value '{u}' as FeynmanHibbsOrder. Has to be one of '0, 1, or 2'." ))), } } } pub(crate) struct TemperatureDependentProperties<D> { sigma_eff_ij: DMatrix<D>, epsilon_k_eff_ij: DMatrix<D>, hs_diameter_ij: DMatrix<D>, quantum_d_ij: DMatrix<D>, } impl<D: DualNum<f64> + Copy> TemperatureDependentProperties<D> { fn new(parameters: &SaftVRQMiePars, temperature: D) -> Self { let n = parameters.m.len(); let sigma_eff_ij = DMatrix::from_fn(n, n, |i, j| -> D { parameters.calc_sigma_eff_ij(i, j, temperature) }); // temperature dependent segment radius let hs_diameter_ij = DMatrix::from_fn(n, n, |i, j| -> D { parameters.hs_diameter_ij(i, j, temperature, sigma_eff_ij[(i, j)]) }); // temperature dependent well depth let epsilon_k_eff_ij = DMatrix::from_fn(n, n, |i, j| -> D { parameters.calc_epsilon_k_eff_ij(i, j, temperature) }); // temperature dependent well depth let quantum_d_ij = DMatrix::from_fn(n, n, |i, j| -> D { parameters.quantum_d_ij(i, j, temperature) }); Self { sigma_eff_ij, epsilon_k_eff_ij, hs_diameter_ij, quantum_d_ij, } } } /// SAFT-VRQ Mie Helmholtz energy model. /// /// # Note /// Currently, only the first-order Feynman-Hibbs term is implemented. pub struct SaftVRQMie { pub parameters: SaftVRQMieParameters, pub params: SaftVRQMiePars, pub options: SaftVRQMieOptions, pub non_additive_hard_sphere: bool, } impl SaftVRQMie { pub fn new(parameters: SaftVRQMieParameters) -> FeosResult<Self> { Self::with_options(parameters, SaftVRQMieOptions::default()) } pub fn with_options( parameters: SaftVRQMieParameters, options: SaftVRQMieOptions, ) -> FeosResult<Self> { let params = SaftVRQMiePars::new(&parameters)?; let non_additive_hard_sphere = params.m.len() > 1 && options.inc_nonadd_term; Ok(Self { parameters, params, options, non_additive_hard_sphere, }) } } impl Subset for SaftVRQMie { fn subset(&self, component_list: &[usize]) -> Self { Self::with_options(self.parameters.subset(component_list), self.options).unwrap() } } impl ResidualDyn for SaftVRQMie { fn components(&self) -> usize { self.parameters.pure.len() } fn compute_max_density<D: num_dual::DualNum<f64> + Copy>(&self, molefracs: &DVector<D>) -> D { let msigma3 = self .params .m .component_mul(&self.params.sigma.map(|v| v.powi(3))); (msigma3.map(D::from).dot(molefracs) * FRAC_PI_6).recip() * self.options.max_eta } fn reduced_helmholtz_energy_density_contributions<D: num_dual::DualNum<f64> + Copy>( &self, state: &StateHD<D>, ) -> Vec<(&'static str, D)> { let mut v = Vec::with_capacity(7); let properties = TemperatureDependentProperties::new(&self.params, state.temperature); v.push(( "Hard Sphere", HardSphere.helmholtz_energy_density(&self.params, state, &properties), )); v.push(( "Dispersion", Dispersion.helmholtz_energy_density(&self.params, state, &properties), )); if self.non_additive_hard_sphere { v.push(( "Non additive Hard Sphere", NonAddHardSphere.helmholtz_energy_density(&self.params, state, &properties), )) } v } } impl Molarweight for SaftVRQMie { fn molar_weight(&self) -> MolarWeight<DVector<f64>> { self.parameters.molar_weight.clone() } } #[cfg(feature = "ndarray")] impl SaftVRQMie { /// Generate energy and force tables to be used with LAMMPS' `pair_style table` command. /// /// For a given `temperature`, `n` values between `r_min` and `r_max` (both including) are tabulated. /// /// Files for all pure substances and all unique pairs are generated, /// where filenames use either the "name" field of the identifier or the index if no name is present. /// /// # Example /// /// For a hydrogen-neon mixture at 30 K, three files will be created. /// /// - "hydrogen_30K.table" for H-H interactions, /// - "neon_30K.table" for Ne-Ne interactions, /// - "hydrogen_neon_30K.table" for H-Ne interactions. pub fn lammps_tables( &self, temperature: Temperature, n: usize, r_min: Length, r_max: Length, ) -> std::io::Result<()> { let t = temperature.to_reduced(); let rs = ndarray::Array1::linspace(r_min.to_reduced(), r_max.to_reduced(), n); let energy_conversion = (KELVIN * RGAS / (KILO * CALORIE / MOL)).into_value(); let force_conversion = (KELVIN * RGAS / (KILO * CALORIE / MOL)).into_value(); let identifiers = self.parameters.identifiers(); let n_components = self.params.sigma.len(); for i in 0..n_components { for j in i..n_components { let name_i = identifiers[i].name.clone().unwrap_or_else(|| i.to_string()); let name_j = identifiers[j].name.clone().unwrap_or_else(|| j.to_string()); let name = if i == j { name_i } else { format!("{name_i}_{name_j}") }; let f = File::create(format!("{name}_{t}K.table"))?; let mut stream = BufWriter::new(f); std::io::Write::write( &mut stream, b"# DATE: YYYY-MM-DD UNITS: real CONTRIBUTOR: YOUR NAME\n", )?; std::io::Write::write( &mut stream, format!("# FH1 potential for {name} at T = {temperature}\n").as_bytes(), )?; std::io::Write::write(&mut stream, format!("FH1_{name}\n").as_bytes())?; std::io::Write::write(&mut stream, format!("N {n}\n\n").as_bytes())?; for (k, &r) in rs.iter().enumerate() { let [u, du, _] = self.params.qmie_potential_ij(i, j, r, t); std::io::Write::write( &mut stream, format!( "{} {:12.8} {:12.8} {:12.8}\n", k + 1, r, u * energy_conversion, -du * force_conversion ) .as_bytes(), )?; } std::io::Write::flush(&mut stream)?; } } Ok(()) } }
Rust
3D
feos-org/feos
crates/feos/src/saftvrqmie/eos/hard_sphere.rs
.rs
14,668
415
#![allow(clippy::excessive_precision)] use super::TemperatureDependentProperties; use crate::saftvrqmie::parameters::SaftVRQMiePars; use feos_core::StateHD; use nalgebra::DVector; use num_dual::DualNum; use std::f64::consts::TAU; use std::fmt; /// Boltzmann's constant in J/K const KB: f64 = 1.380649e-23; const PLANCK: f64 = 6.62607015e-34; const D_QM_PREFACTOR: f64 = PLANCK * PLANCK / (TAU * TAU) / 12.0 * 1e20 / KB; const X_K21: [f64; 21] = [ -0.995657163025808080735527280689003, -0.973906528517171720077964012084452, -0.930157491355708226001207180059508, -0.865063366688984510732096688423493, -0.780817726586416897063717578345042, -0.679409568299024406234327365114874, -0.562757134668604683339000099272694, -0.433395394129247190799265943165784, -0.294392862701460198131126603103866, -0.148874338981631210884826001129720, 0.000000000000000000000000000000000, 0.148874338981631210884826001129720, 0.294392862701460198131126603103866, 0.433395394129247190799265943165784, 0.562757134668604683339000099272694, 0.679409568299024406234327365114874, 0.780817726586416897063717578345042, 0.865063366688984510732096688423493, 0.930157491355708226001207180059508, 0.973906528517171720077964012084452, 0.995657163025808080735527280689003, ]; const W_K21: [f64; 21] = [ 0.011694638867371874278064396062192, 0.032558162307964727478818972459390, 0.054755896574351996031381300244580, 0.075039674810919952767043140916190, 0.093125454583697605535065465083366, 0.109387158802297641899210590325805, 0.123491976262065851077958109831074, 0.134709217311473325928054001771707, 0.142775938577060080797094273138717, 0.147739104901338491374841515972068, 0.149445554002916905664936468389821, 0.147739104901338491374841515972068, 0.142775938577060080797094273138717, 0.134709217311473325928054001771707, 0.123491976262065851077958109831074, 0.109387158802297641899210590325805, 0.093125454583697605535065465083366, 0.075039674810919952767043140916190, 0.054755896574351996031381300244580, 0.032558162307964727478818972459390, 0.011694638867371874278064396062192, ]; impl SaftVRQMiePars { #[inline] pub fn hs_diameter<D: DualNum<f64> + Copy>(&self, temperature: D) -> DVector<D> { DVector::from_fn(self.m.len(), |i, _| -> D { let sigma_eff = self.calc_sigma_eff_ij(i, i, temperature); self.hs_diameter_ij(i, i, temperature, sigma_eff) }) } #[inline] pub fn hs_diameter_ij<D: DualNum<f64> + Copy>( &self, i: usize, j: usize, temperature: D, sigma_eff: D, ) -> D { let r0 = self.zero_integrand(i, j, temperature, sigma_eff); let mut d_hs = r0; for k in 0..21 { let width = (sigma_eff - r0) * 0.5; let r = width * X_K21[k] + width + r0; let u = self.qmie_potential_ij(i, j, r, temperature); let f_u = -(-u[0] / temperature).exp() + 1.0; d_hs += width * f_u * W_K21[k]; } d_hs } pub fn zero_integrand<D: DualNum<f64> + Copy>( &self, i: usize, j: usize, temperature: D, sigma_eff: D, ) -> D { let mut r = sigma_eff * 0.7; let mut f = D::zero(); for _k in 1..20 { let u_vec = self.qmie_potential_ij(i, j, r, temperature); f = u_vec[0] / temperature + f64::EPSILON.ln(); if f.re().abs() < 1.0e-12 { break; } let dfdr = u_vec[1] / temperature; let mut dr = -(f / dfdr); if dr.re().abs() > 0.5 { dr *= 0.5 / dr.re().abs(); } r += dr; } if f.re().abs() > 1.0e-12 { println!("zero_integrand calculation failed {}", f.re().abs()); } r } #[inline] pub fn epsilon_k_eff<D: DualNum<f64> + Copy>(&self, temperature: D) -> DVector<D> { DVector::from_fn(self.m.len(), |i, _| -> D { self.calc_epsilon_k_eff_ij(i, i, temperature) }) } pub fn calc_epsilon_k_eff_ij<D: DualNum<f64> + Copy>( &self, i: usize, j: usize, temperature: D, ) -> D { let mut r = D::one() * self.sigma_ij[(i, j)]; let mut u_vec = [D::zero(), D::zero(), D::zero()]; for _k in 1..20 { u_vec = self.qmie_potential_ij(i, j, r, temperature); if u_vec[1].re().abs() < 1.0e-12 { break; } r += -u_vec[1] / u_vec[2]; } if u_vec[1].re().abs() > 1.0e-12 { println!("calc_epsilon_k_eff_ij calculation failed"); } -u_vec[0] } #[inline] pub fn sigma_eff<D: DualNum<f64> + Copy>(&self, temperature: D) -> DVector<D> { DVector::from_fn(self.m.len(), |i, _| -> D { self.calc_sigma_eff_ij(i, i, temperature) }) } pub fn calc_sigma_eff_ij<D: DualNum<f64> + Copy>( &self, i: usize, j: usize, temperature: D, ) -> D { let mut r = D::one() * self.sigma_ij[(i, j)]; let mut u_vec = [D::zero(), D::zero(), D::zero()]; for _k in 1..20 { u_vec = self.qmie_potential_ij(i, j, r, temperature); if u_vec[0].re().abs() < 1.0e-12 { break; } r += -u_vec[0] / u_vec[1]; } if u_vec[0].re().abs() > 1.0e-12 { println!("calc_sigma_eff_ij calculation failed"); } r } #[inline] pub fn quantum_d_ij<D: DualNum<f64>>(&self, i: usize, j: usize, temperature: D) -> D { quantum_d_mass(self.mass_ij[(i, j)], temperature) } /// Feynman-Hibbs corrected potential pub fn qmie_potential_ij<D: DualNum<f64> + Copy>( &self, i: usize, j: usize, r: D, temperature: D, ) -> [D; 3] { let lr = self.lambda_r_ij[(i, j)]; let la = self.lambda_a_ij[(i, j)]; let s = self.sigma_ij[(i, j)]; let eps = self.epsilon_k_ij[(i, j)]; let c = self.c_ij[(i, j)]; let q1r = lr * (lr - 1.0); let q1a = la * (la - 1.0); let q2r = 0.5 * (lr + 2.0) * (lr + 1.0) * lr * (lr - 1.0); let q2a = 0.5 * (la + 2.0) * (la + 1.0) * la * (la - 1.0); let d = self.quantum_d_ij(i, j, temperature); let mut u = r.powf(lr).recip() * s.powf(lr) - r.powf(la).recip() * s.powf(la); let mut u_r = -r.powf(lr + 1.0).recip() * lr * s.powf(lr) + r.powf(la + 1.0).recip() * la * s.powf(la); let mut u_rr = r.powf(lr + 2.0).recip() * lr * (lr + 1.0) * s.powf(lr) - r.powf(la + 2.0).recip() * la * (la + 1.0) * s.powf(la); if self.fh_ij[(i, j)] as usize > 0 { u += d * (r.powf(lr + 2.0).recip() * q1r * s.powf(lr) - r.powf(la + 2.0).recip() * q1a * s.powf(la)); u_r += d * (r.powf(lr + 3.0).recip() * -q1r * (lr + 2.0) * s.powf(lr) + r.powf(la + 3.0).recip() * q1a * (la + 2.0) * s.powf(la)); u_rr += d * (r.powf(lr + 4.0).recip() * q1r * (lr + 2.0) * (lr + 3.0) * s.powf(lr) - r.powf(la + 4.0).recip() * q1a * (la + 2.0) * (la + 3.0) * s.powf(la)); } if self.fh_ij[(i, j)] as usize > 1 { u += d.powi(2) * (r.powf(lr + 4.0).recip() * q2r * s.powf(lr) - r.powf(la + 4.0).recip() * q2a * s.powf(la)); u_r += d.powi(2) * (-r.powf(lr + 5.0).recip() * q2r * (lr + 4.0) * s.powf(lr) + r.powf(la + 5.0).recip() * q2a * (la + 4.0) * s.powf(la)); u_rr += d.powi(2) * (r.powf(lr + 6.0).recip() * q2r * (lr + 4.0) * (lr + 5.0) * s.powf(lr) - r.powf(la + 6.0).recip() * q2a * (la + 4.0) * (la + 5.0) * s.powf(la)); } u *= c * eps; u_r *= c * eps; u_rr *= c * eps; [u, u_r, u_rr] } } #[inline] pub fn quantum_d_mass<D: DualNum<f64>>(mass: f64, temperature: D) -> D { temperature.recip() / mass * D_QM_PREFACTOR } pub struct HardSphere; impl HardSphere { pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &SaftVRQMiePars, state: &StateHD<D>, properties: &TemperatureDependentProperties<D>, ) -> D { let d = DVector::from_fn(parameters.m.len(), |i, _| properties.hs_diameter_ij[(i, i)]); let zeta = zeta(&parameters.m, &state.partial_density, &d); let frac_1mz3 = -(zeta[3] - 1.0).recip(); let zeta_23 = zeta_23(&parameters.m, &state.molefracs, &d); (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] * (-1.0)).ln_1p()) * 6.0 / std::f64::consts::PI } } impl fmt::Display for HardSphere { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Hard Sphere") } } pub fn zeta<D: DualNum<f64> + Copy>( m: &DVector<f64>, partial_density: &DVector<D>, diameter: &DVector<D>, ) -> [D; 4] { let mut zeta: [D; 4] = [D::zero(), D::zero(), D::zero(), D::zero()]; for i in 0..m.len() { for (k, z) in zeta.iter_mut().enumerate() { *z += partial_density[i] * diameter[i].powi(k as i32) * (std::f64::consts::PI / 6.0 * m[i]); } } zeta } pub fn zeta_23<D: DualNum<f64> + Copy>( m: &DVector<f64>, molefracs: &DVector<D>, diameter: &DVector<D>, ) -> D { let mut zeta: [D; 2] = [D::zero(), D::zero()]; for i in 0..m.len() { for (k, z) in zeta.iter_mut().enumerate() { *z += molefracs[i] * diameter[i].powi((k + 2) as i32) * m[i]; } } zeta[0] / zeta[1] } #[cfg(test)] mod tests { use super::*; use crate::saftvrqmie::parameters::utils::h2_ne_fh; use crate::saftvrqmie::parameters::utils::hydrogen_fh; use approx::assert_relative_eq; use nalgebra::dvector; use num_dual::Dual64; #[test] fn test_quantum_d_mass() { let parameters = hydrogen_fh("1"); let temperature = 26.7060; let r = 3.5; let u0 = parameters.qmie_potential_ij(0, 0, r, temperature); let eps = 1.0e-5; let u2 = parameters.qmie_potential_ij(0, 0, r + eps, temperature); let u1 = parameters.qmie_potential_ij(0, 0, r - eps, temperature); let dudr_num = (u2[0] - u1[0]) / eps / 2.0; let d2udr2_num = (u2[1] - u1[1]) / eps / 2.0; assert!(((dudr_num - u0[1]) / u0[1]).abs() < 1.0e-9); assert!(((d2udr2_num - u0[2]) / u0[2]).abs() < 1.0e-9); } #[test] fn test_sigma_effective() { let parameters = hydrogen_fh("1"); let temperature = 26.7060; let sigma_eff = parameters.calc_sigma_eff_ij(0, 0, temperature); println!("{}", sigma_eff - 3.2540054024660556); assert!((sigma_eff - 3.2540054024660556).abs() < 5.0e-7) } #[test] fn test_eps_div_k_effective() { let parameters = hydrogen_fh("1"); let temperature = 26.7060; let epsilon_k_eff = parameters.calc_epsilon_k_eff_ij(0, 0, temperature); println!("{}", epsilon_k_eff - 21.654396207986697); assert!((epsilon_k_eff - 21.654396207986697).abs() < 1.0e-6) } #[test] fn test_zero_integrand() { let parameters = hydrogen_fh("1"); let temperature = 26.706; let sigma_eff = parameters.calc_sigma_eff_ij(0, 0, temperature); let r0 = parameters.zero_integrand(0, 0, temperature, sigma_eff); println!("{}", r0 - 2.5265031901173732); assert!((r0 - 2.5265031901173732).abs() < 5.0e-7) } #[test] fn test_hs_diameter() { let parameters = hydrogen_fh("1"); let temperature = Dual64::from(26.7060).derivative(); let sigma_eff = parameters.calc_sigma_eff_ij(0, 0, temperature); let d_hs = parameters.hs_diameter_ij(0, 0, temperature, sigma_eff); assert!((d_hs.re - 3.1410453883283341).abs() < 5.0e-8); assert!((d_hs.eps + 8.4528823966252661e-3).abs() < 1.0e-9); } #[test] fn test_hs_helmholtz_energy() { let parameters = hydrogen_fh("1"); let na = 6.02214076e23; let t = 26.7060; let v = 1.0e26; let n = na * 1.1; let s = StateHD::new(t, v / n, &dvector![1.0]); let properties = TemperatureDependentProperties::new(&parameters, s.temperature); let a_rust = HardSphere.helmholtz_energy_density(&parameters, &s, &properties) * v; dbg!(a_rust / na); assert_relative_eq!(a_rust / na, 0.54586730268029837, epsilon = 5e-7); } #[test] fn test_hs_helmholtz_energy_fh2() { let parameters = hydrogen_fh("2"); let na = 6.02214076e23; let t = 26.7060; let v = 1.0e26; let n = na * 1.1; let s = StateHD::new(t, v / n, &dvector![1.0]); let properties = TemperatureDependentProperties::new(&parameters, s.temperature); let a_rust = HardSphere.helmholtz_energy_density(&parameters, &s, &properties) * v; dbg!(a_rust / na); assert_relative_eq!(a_rust / na, 0.5934447545083482, epsilon = 5e-7); } #[test] fn test_hs_helmholtz_energy_mix() { let parameters = h2_ne_fh("1"); let na = 6.02214076e23; let t = 30.0; let v = 1.0e26; let n = dvector![na * 1.1, na * 1.0]; let s = StateHD::new(t, v / n.sum(), &(&n / n.sum())); let properties = TemperatureDependentProperties::new(&parameters, s.temperature); let a_rust = HardSphere.helmholtz_energy_density(&parameters, &s, &properties) * v; dbg!(a_rust / na); // non-additive: 1.8249307925054206 assert_relative_eq!(a_rust / na, 1.8074833133403905, epsilon = 5e-7); } #[test] fn test_hs_helmholtz_energy_mix_fh2() { let parameters = h2_ne_fh("2"); let na = 6.02214076e23; let t = 30.0; let v = 1.0e26; let n = dvector![na * 1.1, na * 1.0]; let s = StateHD::new(t, v / n.sum(), &(&n / n.sum())); let properties = TemperatureDependentProperties::new(&parameters, s.temperature); let a_rust = HardSphere.helmholtz_energy_density(&parameters, &s, &properties) * v; dbg!(a_rust / na); assert_relative_eq!(a_rust / na, 1.898534632022848, epsilon = 5e-7); } }
Rust
3D
feos-org/feos
crates/feos/src/saftvrqmie/eos/non_additive_hs.rs
.rs
3,431
103
use super::TemperatureDependentProperties; use crate::saftvrqmie::eos::hard_sphere::zeta; use crate::saftvrqmie::parameters::SaftVRQMiePars; use feos_core::StateHD; use nalgebra::{DMatrix, DVector}; use num_dual::DualNum; use std::f64::consts::PI; pub struct NonAddHardSphere; impl NonAddHardSphere { pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &SaftVRQMiePars, state: &StateHD<D>, properties: &TemperatureDependentProperties<D>, ) -> D { let p = parameters; let n = p.m.len(); let d_hs_ij = &properties.hs_diameter_ij; // Additive hard-sphere diameter let d_hs_add_ij = DMatrix::from_fn(n, n, |i, j| (d_hs_ij[(i, i)] + d_hs_ij[(j, j)]) * 0.5); let rho_s = DVector::from_fn(n, |i, _| state.partial_density[i] * p.m[i]).sum(); rho_s * reduced_non_additive_hs_energy(p, d_hs_ij, &d_hs_add_ij, &state.partial_density) } } pub fn reduced_non_additive_hs_energy<D: DualNum<f64> + Copy>( parameters: &SaftVRQMiePars, d_hs_ij: &DMatrix<D>, d_hs_add_ij: &DMatrix<D>, rho: &DVector<D>, ) -> D { // auxiliary variables let n = rho.len(); let p = &parameters; let d = DVector::from_fn(n, |i, _| d_hs_ij[(i, i)]); let zeta = zeta(&p.m, rho, &d); let frac_1mz3 = -(zeta[3] - 1.0).recip(); let g_hs_ij = DMatrix::from_fn(n, n, |i, j| { let mu = d[i] * d[j] / (d[i] + d[j]); frac_1mz3 + mu * zeta[2] * frac_1mz3.powi(2) * 3.0 + (mu * zeta[2]).powi(2) * frac_1mz3.powi(3) * 2.0 }); // overall density let rho_s = DVector::from_fn(n, |i, _| -> D { rho[i] * p.m[i] }).sum(); // segment fractions let x_s = DVector::from_fn(n, |i, _| -> D { rho[i] * p.m[i] / rho_s }); DMatrix::from_fn(n, n, |i, j| { -rho_s * x_s[i] * x_s[j] * d_hs_add_ij[(i, j)].powi(2) * g_hs_ij[(i, j)] * (d_hs_add_ij[(i, j)] - d_hs_ij[(i, j)]) * 2.0 * PI }) .sum() } #[cfg(test)] mod tests { use super::*; use crate::saftvrqmie::parameters::utils::h2_ne_fh; use crate::saftvrqmie::parameters::utils::hydrogen_fh; use approx::assert_relative_eq; use nalgebra::dvector; #[test] fn test_non_add_hs_helmholtz_energy() { let parameters = hydrogen_fh("1"); let na = 6.02214076e23; let t = 26.7060; let v = 1.0e26; let n = na * 1.1; let s = StateHD::new(t, v / n, &dvector![1.0]); let properties = TemperatureDependentProperties::new(&parameters, s.temperature); let a_rust = NonAddHardSphere.helmholtz_energy_density(&parameters, &s, &properties) * v; dbg!(a_rust / na); assert_relative_eq!(a_rust / na, 0.0, epsilon = 1e-12); } #[test] fn test_non_add_hs_helmholtz_energy_mix() { let parameters = h2_ne_fh("1"); let na = 6.02214076e23; let t = 30.0; let v = 1.0e26; let n = dvector![na * 1.1, na * 1.0]; let s = StateHD::new(t, v / n.sum(), &(&n / n.sum())); let properties = TemperatureDependentProperties::new(&parameters, s.temperature); let a_rust = NonAddHardSphere.helmholtz_energy_density(&parameters, &s, &properties) * v; dbg!(a_rust / na); assert_relative_eq!(a_rust / na, 1.7874359117834266E-002, epsilon = 5e-7); } }
Rust
3D
feos-org/feos
crates/feos/src/saftvrqmie/eos/dispersion.rs
.rs
33,773
954
use crate::saftvrqmie::parameters::SaftVRQMiePars; use feos_core::StateHD; use nalgebra::{DMatrix, DVector}; use num_dual::DualNum; use std::f64::consts::FRAC_PI_6; use std::fmt; use super::TemperatureDependentProperties; const LAM_COEFF: [[f64; 4]; 4] = [ [0.81096, 1.7888, -37.578, 92.284], [1.0205, -19.341, 151.26, -463.50], [-1.9057, 22.845, -228.14, 973.92], [1.0885, -6.1962, 106.98, -677.64], ]; const PHI: [[f64; 7]; 6] = [ [ 7.5365557, -37.60463, 71.745953, -46.83552, -2.467982, -0.50272, 8.0956883, ], [-359.44, 1825.6, -3168.0, 1884.2, -0.82376, -3.1935, 3.709], [1550.9, -5070.1, 6534.6, -3288.7, -2.7171, 2.0883, 0.0], [ -1.19932, 9.063632, -17.9482, 11.34027, 20.52142, -56.6377, 40.53683, ], [ -1911.28, 21390.175, -51320.7, 37064.54, 1103.742, -3264.61, 2556.181, ], [ 9236.9, -129430.0, 357230.0, -315530.0, 1390.2, -4518.2, 4241.6, ], ]; pub struct Alpha<D: DualNum<f64>> { alpha_ij: DMatrix<D>, } impl<D: DualNum<f64> + Copy> Alpha<D> { pub fn new( parameters: &SaftVRQMiePars, sigma_eff_ij: &DMatrix<D>, epsilon_k_eff_ij: &DMatrix<D>, temperature: D, ) -> Self { let p = parameters; let nc = sigma_eff_ij.shape().0; let mut alpha_ij: DMatrix<D> = DMatrix::zeros(nc, nc); for i in 0..nc { for j in i..nc { let sigma_ratio = D::one() * p.sigma_ij[(i, j)] / sigma_eff_ij[(i, j)]; let eps_ratio = D::one() * p.epsilon_k_ij[(i, j)] / epsilon_k_eff_ij[(i, j)]; let la = p.lambda_a_ij[(i, j)]; let lr = p.lambda_r_ij[(i, j)]; let sigma_ratio_a = sigma_ratio.powf(la); let sigma_ratio_r = sigma_ratio.powf(lr); let dmt = p.quantum_d_ij(i, j, temperature) / p.sigma_ij[(i, j)].powi(2); let ma = sigma_ratio_a / (la - 3.0); let mr = sigma_ratio_r / (lr - 3.0); alpha_ij[(i, j)] = ma - mr; if p.fh_ij[(i, j)] as usize > 0 { let q1a = sigma_ratio_a * sigma_ratio.powi(2) * la; let q1r = sigma_ratio_r * sigma_ratio.powi(2) * lr; alpha_ij[(i, j)] += dmt * (q1a - q1r); } if p.fh_ij[(i, j)] as usize > 1 { let q2a = sigma_ratio_a * sigma_ratio.powi(4) * (la + 2.0) * la * (la - 1.0) * 0.5; let q2r = sigma_ratio_r * sigma_ratio.powi(4) * (lr + 2.0) * lr * (lr - 1.0) * 0.5; alpha_ij[(i, j)] += dmt.powi(2) * (q2a - q2r); } alpha_ij[(i, j)] *= eps_ratio * p.c_ij[(i, j)]; if i != j { alpha_ij[(j, i)] = alpha_ij[(i, j)]; } } } Self { alpha_ij } } fn f(&self, k: usize, i: usize, j: usize) -> D { let a_ij = self.alpha_ij[(i, j)]; let phi = PHI[k]; (a_ij * phi[1] + a_ij.powi(2) * phi[2] + a_ij.powi(3) * phi[3] + phi[0]) / (a_ij * phi[4] + a_ij.powi(2) * phi[5] + a_ij.powi(3) * phi[6] + 1.0) } } pub struct Dispersion; impl Dispersion { pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &SaftVRQMiePars, state: &StateHD<D>, properties: &TemperatureDependentProperties<D>, ) -> D { // auxiliary variables let n = parameters.m.len(); let p = parameters; let rho = &state.partial_density; // temperature dependent segment radius let s_eff_ij = &properties.sigma_eff_ij; // temperature dependent segment radius let d_hs_ij = &properties.hs_diameter_ij; // temperature dependent well depth let epsilon_k_eff_ij = &properties.epsilon_k_eff_ij; // temperature dependent well depth let dq_ij = &properties.quantum_d_ij; // segment fractions let mut x_s = DVector::from_fn(n, |i, _| -> D { state.molefracs[i] * p.m[i] }); let inv_x_s_sum = x_s.sum().recip(); for i in 0..n { x_s[i] *= inv_x_s_sum; } // Segment density let mut rho_s = D::zero(); for i in 0..n { rho_s += rho[i] * p.m[i]; } // packing fractions let zeta = zeta_saft_vrq_mie(&p.m, &x_s, d_hs_ij, rho_s); let zeta_bar = zeta_saft_vrq_mie(&p.m, &x_s, s_eff_ij, rho_s); // alphas .... let alpha = Alpha::new(p, s_eff_ij, epsilon_k_eff_ij, state.temperature); let a1 = first_order_perturbation(p, &x_s, zeta, rho_s, d_hs_ij, s_eff_ij, dq_ij); let a2 = second_order_perturbation( p, &alpha, &x_s, zeta, zeta_bar, rho_s, d_hs_ij, s_eff_ij, dq_ij, ); let a3 = third_order_perturbation(p, &alpha, &x_s, zeta_bar, epsilon_k_eff_ij); let mut n_s = D::zero(); for i in 0..n { n_s += state.partial_density[i] * p.m[i]; } let inv_t = state.temperature.recip(); n_s * (a1 * inv_t + a2 * inv_t.powi(2) + a3 * inv_t.powi(3)) } } #[cfg(feature = "dft")] #[expect(clippy::too_many_arguments)] pub fn dispersion_energy_density<D: DualNum<f64> + Copy>( parameters: &SaftVRQMiePars, d_hs_ij: &DMatrix<D>, s_eff_ij: &DMatrix<D>, epsilon_k_eff_ij: &DMatrix<D>, dq_ij: &DMatrix<D>, alpha: &Alpha<D>, rho: ndarray::ArrayView1<D>, temperature: D, ) -> D { // auxiliary variables let n = rho.len(); let p = &parameters; // Segment density let mut rho_s = D::zero(); for i in 0..n { rho_s += rho[i] * p.m[i]; } // segment fractions let x_s = DVector::from_fn(n, |i, _| -> D { rho[i] * p.m[i] * rho_s.recip() }); // packing fractions let zeta = zeta_saft_vrq_mie(&p.m, &x_s, d_hs_ij, rho_s); let zeta_bar = zeta_saft_vrq_mie(&p.m, &x_s, s_eff_ij, rho_s); let a1 = first_order_perturbation(p, &x_s, zeta, rho_s, d_hs_ij, s_eff_ij, dq_ij); let a2 = second_order_perturbation( p, alpha, &x_s, zeta, zeta_bar, rho_s, d_hs_ij, s_eff_ij, dq_ij, ); let a3 = third_order_perturbation(p, alpha, &x_s, zeta_bar, epsilon_k_eff_ij); let inv_t = temperature.recip(); rho_s * (a1 * inv_t + a2 * inv_t.powi(2) + a3 * inv_t.powi(3)) } fn zeta_saft_vrq_mie<D: DualNum<f64> + Copy>( m: &DVector<f64>, x_s: &DVector<D>, diameter: &DMatrix<D>, rho_s: D, ) -> D { let mut zeta = D::zero(); for i in 0..m.len() { for j in 0..m.len() { zeta += x_s[i] * x_s[j] * diameter[(i, j)].powi(3); } } zeta * FRAC_PI_6 * rho_s } fn first_order_perturbation<D: DualNum<f64> + Copy>( parameters: &SaftVRQMiePars, x_s: &DVector<D>, zeta: D, rho_s: D, d_hs_ij: &DMatrix<D>, s_eff_ij: &DMatrix<D>, dq_ij: &DMatrix<D>, ) -> D { let n = parameters.sigma.len(); let mut a1 = D::zero(); for i in 0..n { for j in i..n { let x0 = d_hs_ij[(i, j)].recip() * parameters.sigma_ij[(i, j)]; let x0_eff = s_eff_ij[(i, j)] / d_hs_ij[(i, j)]; let dq_div_sigma_2 = dq_ij[(i, j)] / parameters.sigma_ij[(i, j)].powi(2); let fac = if i == j { 1.0 } else { 2.0 }; a1 += x_s[i] * x_s[j] * fac * FRAC_PI_6 * rho_s * d_hs_ij[(i, j)].powi(3) * first_order_perturbation_ij( parameters.lambda_a_ij[(i, j)], parameters.lambda_r_ij[(i, j)], parameters.epsilon_k_ij[(i, j)], zeta, x0, x0_eff, parameters.c_ij[(i, j)], dq_div_sigma_2, parameters.fh_ij[(i, j)] as usize, ) } } a1 } #[expect(clippy::too_many_arguments)] fn first_order_perturbation_ij<D: DualNum<f64> + Copy>( lambda_a: f64, lambda_r: f64, epsilon_k: f64, zeta: D, x0: D, x0_eff: D, c: f64, dq_div_sigma_2: D, fh_order: usize, ) -> D { let int_a = combine_sutherland_and_b(lambda_a, epsilon_k, zeta, x0, x0_eff); let int_r = combine_sutherland_and_b(lambda_r, epsilon_k, zeta, x0, x0_eff); let mut a1_ij = int_a - int_r; // Quantum corrections if fh_order > 0 { let int_qa = combine_sutherland_and_b(lambda_a + 2.0, epsilon_k, zeta, x0, x0_eff); let int_qr = combine_sutherland_and_b(lambda_r + 2.0, epsilon_k, zeta, x0, x0_eff); let qa1 = dq_div_sigma_2 * quantum_prefactor(lambda_a); let qr1 = dq_div_sigma_2 * quantum_prefactor(lambda_r); a1_ij += int_qa * qa1 - int_qr * qr1; } if fh_order > 1 { let int_qa2 = combine_sutherland_and_b(lambda_a + 4.0, epsilon_k, zeta, x0, x0_eff); let int_qr2 = combine_sutherland_and_b(lambda_r + 4.0, epsilon_k, zeta, x0, x0_eff); let qa2 = dq_div_sigma_2.powi(2) * quantum_prefactor_second_order(lambda_a); let qr2 = dq_div_sigma_2.powi(2) * quantum_prefactor_second_order(lambda_r); a1_ij += int_qa2 * qa2 - int_qr2 * qr2; } a1_ij * c } fn eta_eff<D: DualNum<f64> + Copy>(lambda: f64, zeta: D) -> D { let inv_lambda = DVector::from(vec![ 1.0, 1.0 / lambda, 1.0 / lambda.powi(2), 1.0 / lambda.powi(3), ]); let c = DVector::from_fn(4, |i, _| { inv_lambda[0] * LAM_COEFF[i][0] + inv_lambda[1] * LAM_COEFF[i][1] + inv_lambda[2] * LAM_COEFF[i][2] + inv_lambda[3] * LAM_COEFF[i][3] }); zeta * (zeta * (zeta * (zeta * c[3] + c[2]) + c[1]) + c[0]) } fn sutherland<D: DualNum<f64> + Copy>(lambda: f64, epsilon_k: f64, zeta: D, x0: D) -> D { let ef = eta_eff(lambda, zeta); (-ef * 0.5 + 1.0) * -12.0 * x0.powf(lambda) * epsilon_k / (lambda - 3.0) / (-ef + 1.0).powi(3) } fn ilambda<D: DualNum<f64>>(lambda: f64, x0: D) -> D { -(x0.powf(3.0 - lambda) - 1.0) / (lambda - 3.0) } fn jlambda<D: DualNum<f64>>(lambda: f64, x0: D) -> D { -(x0.powf(4.0 - lambda) * (lambda - 3.0) - x0.powf(3.0 - lambda) * (lambda - 4.0) - 1.0) / ((lambda - 3.0) * (lambda - 4.0)) } /// Calculate equation 33 of Lafitte 2013 /// B is divided by the packing fraction /// /// \author Morten Hammer, February 2018 fn b<D: DualNum<f64> + Copy>(lambda: f64, epsilon_k: f64, zeta: D, x0: D, x0_eff: D) -> D { let ilambda = ilambda(lambda, x0_eff); let jlambda = jlambda(lambda, x0_eff); let denum = (-zeta + 1.0).powi(3); x0.powf(lambda) * ((-zeta + 2.0) / denum * ilambda + -zeta * 9.0 * (zeta + 1.0) / denum * jlambda) * 6.0 * epsilon_k } #[inline] fn combine_sutherland_and_b<D: DualNum<f64> + Copy>( lambda: f64, epsilon_k: f64, zeta: D, x0: D, x0_eff: D, ) -> D { let int_as = sutherland(lambda, epsilon_k, zeta, x0); let int_b = b(lambda, epsilon_k, zeta, x0, x0_eff); int_as + int_b } #[expect(clippy::too_many_arguments)] fn second_order_perturbation<D: DualNum<f64> + Copy>( parameters: &SaftVRQMiePars, alpha: &Alpha<D>, x_s: &DVector<D>, zeta: D, zeta_bar: D, rho_s: D, d_hs_ij: &DMatrix<D>, s_eff_ij: &DMatrix<D>, dq_ij: &DMatrix<D>, ) -> D { let n = parameters.sigma.len(); let mut a2 = D::zero(); // Calculate isothermal hard sphere compressibillity factor let k = (-zeta + 1.0).powi(4) / (zeta * 4.0 + zeta.powi(2) * 4.0 - zeta.powi(3) * 4.0 + zeta.powi(4) + 1.0); for i in 0..n { for j in i..n { let chi = alpha.f(0, i, j) * zeta_bar + alpha.f(1, i, j) * zeta_bar.powi(5) + alpha.f(2, i, j) * zeta_bar.powi(8); let x0 = d_hs_ij[(i, j)].recip() * parameters.sigma_ij[(i, j)]; let x0_eff = s_eff_ij[(i, j)] / d_hs_ij[(i, j)]; let dq_div_sigma_2 = dq_ij[(i, j)] / parameters.sigma_ij[(i, j)].powi(2); let fac = if i == j { 1.0 } else { 2.0 }; a2 += x_s[i] * x_s[j] * fac * FRAC_PI_6 * rho_s * d_hs_ij[(i, j)].powi(3) * (chi + 1.0) * second_order_perturbation_ij( parameters.lambda_a_ij[(i, j)], parameters.lambda_r_ij[(i, j)], parameters.epsilon_k_ij[(i, j)], zeta, x0, x0_eff, parameters.c_ij[(i, j)], dq_div_sigma_2, parameters.fh_ij[(i, j)] as usize, ) } } a2 * k } #[inline] fn quantum_prefactor(lambda: f64) -> f64 { lambda * (lambda - 1.0) } #[inline] fn quantum_prefactor_second_order(lambda: f64) -> f64 { 0.5 * (lambda + 2.0) * (lambda + 1.0) * lambda * (lambda - 1.0) } #[expect(clippy::too_many_arguments)] fn second_order_perturbation_ij<D: DualNum<f64> + Copy>( lambda_a: f64, lambda_r: f64, epsilon_k: f64, zeta: D, x0: D, x0_eff: D, c: f64, dq_div_sigma_2: D, fh_order: usize, ) -> D { let lambda_2r = 2.0 * lambda_r; let lambda_2a = 2.0 * lambda_a; let lambda_ar = lambda_a + lambda_r; // Quantum contributions of first order let qa1 = dq_div_sigma_2 * quantum_prefactor(lambda_a); let qr1 = dq_div_sigma_2 * quantum_prefactor(lambda_r); // Quantum contributions of second order let qa2 = dq_div_sigma_2.powi(2) * quantum_prefactor_second_order(lambda_a); let qr2 = dq_div_sigma_2.powi(2) * quantum_prefactor_second_order(lambda_r); let mut a2_ij = D::zero(); let mut afac = D::one(); let mut rfac = D::one(); let mut arfac = -D::one() * 2.0; // Loop all contributions // 0: Mie contribution // 1,..: Quantum corrections for q in 0..fh_order * 2 + 1 { let int_a = combine_sutherland_and_b(lambda_2a + 2.0 * q as f64, epsilon_k, zeta, x0, x0_eff); let int_r = combine_sutherland_and_b(lambda_2r + 2.0 * q as f64, epsilon_k, zeta, x0, x0_eff); let int_ar = combine_sutherland_and_b(lambda_ar + 2.0 * q as f64, epsilon_k, zeta, x0, x0_eff); if q == 1 { rfac = qr1 * 2.0; afac = qa1 * 2.0; arfac = -(rfac + afac); } else if q == 2 { rfac = qr1 * qr1; afac = qa1 * qa1; arfac = -qa1 * qr1 * 2.0; if fh_order == 2 { rfac += qr2 * 2.0; afac += qa2 * 2.0; arfac += -(qr2 + qa2) * 2.0; } } else if q == 3 { rfac = qr2 * qr1 * 2.0; afac = qa2 * qa1 * 2.0; arfac = -(qr2 * qa1 + qa2 * qr1) * 2.0; } else if q == 4 { rfac = qr2 * qr2; afac = qa2 * qa2; arfac = -qr2 * qa2 * 2.0; } a2_ij += int_a * afac + int_ar * arfac + int_r * rfac; } a2_ij * 0.5 * epsilon_k * c.powi(2) } fn third_order_perturbation<D: DualNum<f64> + Copy>( parameters: &SaftVRQMiePars, alpha: &Alpha<D>, x_s: &DVector<D>, zeta_bar: D, epsilon_k_eff_ij: &DMatrix<D>, ) -> D { let n = parameters.sigma.len(); let mut a3 = D::zero(); for i in 0..n { for j in 0..n { a3 += x_s[i] * x_s[j] * third_order_perturbation_ij(i, j, epsilon_k_eff_ij[(i, j)], alpha, zeta_bar) } } a3 } fn third_order_perturbation_ij<D: DualNum<f64> + Copy>( i: usize, j: usize, epsilon_k_eff: D, alpha: &Alpha<D>, zeta_bar: D, ) -> D { -epsilon_k_eff.powi(3) * alpha.f(3, i, j) * zeta_bar * (alpha.f(4, i, j) * zeta_bar + alpha.f(5, i, j) * zeta_bar.powi(2)).exp() } impl fmt::Display for Dispersion { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Dispersion") } } #[expect(clippy::excessive_precision)] #[cfg(test)] mod tests { use super::*; use crate::saftvrqmie::parameters::utils::h2_ne_fh; use crate::saftvrqmie::parameters::utils::hydrogen_fh; use approx::assert_relative_eq; use nalgebra::dvector; #[test] fn test_eta_eff() { let lambda_6 = 6.0; let lambda_12 = 12.0; let mut zeta = 0.45; let e_eff_6_045 = eta_eff(lambda_6, zeta); let e_eff_12_045 = eta_eff(lambda_12, zeta); zeta = 0.1; let e_eff_6_01 = eta_eff(lambda_6, zeta); let e_eff_12_01 = eta_eff(lambda_12, zeta); assert_relative_eq!(e_eff_6_045, 0.19401806958333320, epsilon = 1e-7); assert_relative_eq!(e_eff_12_045, 0.32193464807291666, epsilon = 1e-7); assert_relative_eq!(e_eff_6_01, 4.7840898518518506E-002, epsilon = 1e-7); assert_relative_eq!(e_eff_12_01, 7.6226364537037058E-002, epsilon = 1e-7); } #[test] fn test_alpha() { let parameters = hydrogen_fh("1"); let temperature = 26.7060; let n = 1; let s_eff_ij = DMatrix::from_fn(n, n, |i, j| parameters.calc_sigma_eff_ij(i, j, temperature)); let epsilon_k_eff_ij = DMatrix::from_fn(n, n, |i, j| { parameters.calc_epsilon_k_eff_ij(i, j, temperature) }); let alpha = Alpha::new(&parameters, &s_eff_ij, &epsilon_k_eff_ij, temperature); assert_relative_eq!(alpha.alpha_ij[(0, 0)], 1.0239374984636636, epsilon = 5e-8); } #[test] fn test_alpha_fh2() { let temperature = 26.7060; let parameters = hydrogen_fh("2"); let n = 1; let s_eff_ij = DMatrix::from_fn(n, n, |i, j| parameters.calc_sigma_eff_ij(i, j, temperature)); let epsilon_k_eff_ij = DMatrix::from_fn(n, n, |i, j| { parameters.calc_epsilon_k_eff_ij(i, j, temperature) }); let alpha = Alpha::new(&parameters, &s_eff_ij, &epsilon_k_eff_ij, temperature); assert_relative_eq!(alpha.alpha_ij[(0, 0)], 0.9918845918431217, epsilon = 5e-8); } #[test] fn test_sutherland() { let x0 = 1.1; let zeta = 0.333; let lambda = 13.77; let eps_div_k = 13.88; let asa = sutherland(lambda, eps_div_k, zeta, x0); assert_relative_eq!(asa, -122.12017536923423, epsilon = 1e-12); } #[test] fn test_b() { let x0 = 1.1; let zeta = 0.333; let lambda = 13.77; let eps_div_k = 13.88; let ba = b(lambda, eps_div_k, zeta, x0, x0); assert_relative_eq!(ba, 93.436438943866293, epsilon = 1e-12); } #[test] fn test_quantum_d_ij() { let p = hydrogen_fh("1"); let temperature = 26.7060; let dq_ij = p.quantum_d_ij(0, 0, temperature); assert_relative_eq!(dq_ij, 7.5092605940987542e-2, epsilon = 5e-8); } #[test] fn test_first_order_perturbation_ij() { let p = hydrogen_fh("1"); let temperature = 26.7060; let zeta = 0.333; let dq_div_s2 = p.quantum_d_ij(0, 0, temperature) / p.sigma_ij[(0, 0)].powi(2); let s_eff = p.calc_sigma_eff_ij(0, 0, temperature); let d_hs = p.hs_diameter_ij(0, 0, temperature, s_eff); let x0 = d_hs.recip() * p.sigma_ij[(0, 0)]; let x0_eff = s_eff / d_hs; let a1_ij = first_order_perturbation_ij( p.lambda_a_ij[(0, 0)], p.lambda_r_ij[(0, 0)], p.epsilon_k_ij[(0, 0)], zeta, x0, x0_eff, p.c_ij[(0, 0)], dq_div_s2, p.fh_ij[(0, 0)] as usize, ); let rel_err = (a1_ij + 332.00915966785539) / 332.00915966785539; assert_relative_eq!(rel_err, 0.0, epsilon = 1e-7); } #[test] fn test_first_order_perturbation_ij_fh2() { let p = hydrogen_fh("2"); let temperature = 26.7060; let zeta = 0.333; let dq_div_s2 = p.quantum_d_ij(0, 0, temperature) / p.sigma_ij[(0, 0)].powi(2); let s_eff = p.calc_sigma_eff_ij(0, 0, temperature); let d_hs = p.hs_diameter_ij(0, 0, temperature, s_eff); let x0 = d_hs.recip() * p.sigma_ij[(0, 0)]; let x0_eff = s_eff / d_hs; let a1_ij = first_order_perturbation_ij( p.lambda_a_ij[(0, 0)], p.lambda_r_ij[(0, 0)], p.epsilon_k_ij[(0, 0)], zeta, x0, x0_eff, p.c_ij[(0, 0)], dq_div_s2, p.fh_ij[(0, 0)] as usize, ); let rel_err = (a1_ij + 296.53213134819606) / 296.53213134819606; assert_relative_eq!(rel_err, 0.0, epsilon = 1e-7); } #[test] fn test_second_order_perturbation_ij() { let p = hydrogen_fh("1"); let temperature = 26.7060; let zeta = 0.333; let dq_div_s2 = p.quantum_d_ij(0, 0, temperature) / p.sigma_ij[(0, 0)].powi(2); let s_eff = p.calc_sigma_eff_ij(0, 0, temperature); let d_hs = p.hs_diameter_ij(0, 0, temperature, s_eff); let x0 = d_hs.recip() * p.sigma_ij[(0, 0)]; let x0_eff = s_eff / d_hs; let a2_ij = second_order_perturbation_ij( p.lambda_a_ij[(0, 0)], p.lambda_r_ij[(0, 0)], p.epsilon_k_ij[(0, 0)], zeta, x0, x0_eff, p.c_ij[(0, 0)], dq_div_s2, 1, ); let rel_err = (a2_ij + 1907.5055256805874) / 1907.5055256805874; assert_relative_eq!(rel_err, 0.0, epsilon = 1e-7); } #[test] fn test_third_order_perturbation_ij() { let p = hydrogen_fh("1"); let temperature = 26.7060; let zeta_bar = 0.333; let n = 1; let s_eff_ij = DMatrix::from_fn(n, n, |i, j| p.calc_sigma_eff_ij(i, j, temperature)); let epsilon_k_eff_ij = DMatrix::from_fn(n, n, |i, j| p.calc_epsilon_k_eff_ij(i, j, temperature)); let alpha = Alpha::new(&p, &s_eff_ij, &epsilon_k_eff_ij, temperature); let a3_ij = third_order_perturbation_ij(0, 0, epsilon_k_eff_ij[(0, 0)], &alpha, zeta_bar); let rel_err = (a3_ij + 25.807966819127916) / 25.807966819127916; assert_relative_eq!(rel_err, 0.0, epsilon = 5e-7); } #[test] fn test_zeta_saft_vrq_mie() { let p = hydrogen_fh("1"); let t = 26.7060; let v = 1.0e26; let n = 6.02214076e23; let state = StateHD::new(t, v, &dvector![n]); let nc = 1; // temperature dependent sigma let s_eff_ij = DMatrix::from_fn(nc, nc, |i, j| p.calc_sigma_eff_ij(i, j, state.temperature)); // temperature dependent segment diameter let d_hs_ij = DMatrix::from_fn(nc, nc, |i, j| { p.hs_diameter_ij(i, j, state.temperature, s_eff_ij[(i, j)]) }); // segment fractions let mut x_s = DVector::from_fn(nc, |i, _| state.molefracs[i] * p.m[i]); let inv_x_s_sum = x_s.sum().recip(); for i in 0..nc { x_s[i] *= inv_x_s_sum; } // Segment density let mut rho_s = 0.0; for i in 0..nc { rho_s += state.partial_density[i] * p.m[i]; } // packing fractions let zeta = zeta_saft_vrq_mie(&p.m, &x_s, &d_hs_ij, rho_s); let zeta_bar = zeta_saft_vrq_mie(&p.m, &x_s, &s_eff_ij, rho_s); assert_relative_eq!(zeta, 9.7717457994590765E-002, epsilon = 5e-9); assert_relative_eq!(zeta_bar, 0.10864364645845238, epsilon = 5e-9); } #[test] fn test_perturbation_terms() { let p = hydrogen_fh("1"); let t = 26.7060; let v = 1.0e26; let n = 6.02214076e23; let state = StateHD::new(t, v, &dvector![n]); let nc = 1; // temperature dependent sigma let s_eff_ij = DMatrix::from_fn(nc, nc, |i, j| p.calc_sigma_eff_ij(i, j, state.temperature)); // temperature dependent segment diameter let d_hs_ij = DMatrix::from_fn(nc, nc, |i, j| { p.hs_diameter_ij(i, j, state.temperature, s_eff_ij[(i, j)]) }); // segment fractions let mut x_s = DVector::from_fn(nc, |i, _| state.molefracs[i] * p.m[i]); let inv_x_s_sum = x_s.sum().recip(); for i in 0..nc { x_s[i] *= inv_x_s_sum; } // Segment density let mut rho_s = 0.0; for i in 0..nc { rho_s += state.partial_density[i] * p.m[i]; } // packing fractions let zeta = zeta_saft_vrq_mie(&p.m, &x_s, &d_hs_ij, rho_s); let zeta_bar = zeta_saft_vrq_mie(&p.m, &x_s, &s_eff_ij, rho_s); // temperature dependent well depth let epsilon_k_eff_ij = DMatrix::from_fn(nc, nc, |i, j| { p.calc_epsilon_k_eff_ij(i, j, state.temperature) }); // alphas .... let alpha = Alpha::new(&p, &s_eff_ij, &epsilon_k_eff_ij, state.temperature); // temperature dependent well depth let dq_ij = DMatrix::from_fn(nc, nc, |i, j| p.quantum_d_ij(i, j, state.temperature)); let a1 = first_order_perturbation(&p, &x_s, zeta, rho_s, &d_hs_ij, &s_eff_ij, &dq_ij); let a2 = second_order_perturbation( &p, &alpha, &x_s, zeta, zeta_bar, rho_s, &d_hs_ij, &s_eff_ij, &dq_ij, ); let a3 = third_order_perturbation(&p, &alpha, &x_s, zeta_bar, &epsilon_k_eff_ij); let rel_err_a1 = (a1 + 30.702499892515764) / 30.702499892515764; let rel_err_a2 = (a2 + 67.046957636607587) / 67.046957636607587; let rel_err_a3 = (a3 + 470.96241656623727) / 470.96241656623727; assert_relative_eq!(rel_err_a1, 0.0, epsilon = 5e-7); assert_relative_eq!(rel_err_a2, 0.0, epsilon = 5e-7); assert_relative_eq!(rel_err_a3, 0.0, epsilon = 5e-7); } #[test] fn test_perturbation_terms_fh2() { let p = hydrogen_fh("2"); let t = 26.7060; let v = 1.0e26; let n = 6.02214076e23; let state = StateHD::new(t, v, &dvector![n]); let nc = 1; // temperature dependent sigma let s_eff_ij = DMatrix::from_fn(nc, nc, |i, j| p.calc_sigma_eff_ij(i, j, state.temperature)); // temperature dependent segment diameter let d_hs_ij = DMatrix::from_fn(nc, nc, |i, j| { p.hs_diameter_ij(i, j, state.temperature, s_eff_ij[(i, j)]) }); // segment fractions let mut x_s = DVector::from_fn(nc, |i, _| state.molefracs[i] * p.m[i]); let inv_x_s_sum = x_s.sum().recip(); for i in 0..nc { x_s[i] *= inv_x_s_sum; } // Segment density let mut rho_s = 0.0; for i in 0..nc { rho_s += state.partial_density[i] * p.m[i]; } // packing fractions let zeta = zeta_saft_vrq_mie(&p.m, &x_s, &d_hs_ij, rho_s); let zeta_bar = zeta_saft_vrq_mie(&p.m, &x_s, &s_eff_ij, rho_s); // temperature dependent well depth let epsilon_k_eff_ij = DMatrix::from_fn(nc, nc, |i, j| { p.calc_epsilon_k_eff_ij(i, j, state.temperature) }); // alphas .... let alpha = Alpha::new(&p, &s_eff_ij, &epsilon_k_eff_ij, state.temperature); // temperature dependent well depth let dq_ij = DMatrix::from_fn(nc, nc, |i, j| p.quantum_d_ij(i, j, state.temperature)); let a1 = first_order_perturbation(&p, &x_s, zeta, rho_s, &d_hs_ij, &s_eff_ij, &dq_ij); let a2 = second_order_perturbation( &p, &alpha, &x_s, zeta, zeta_bar, rho_s, &d_hs_ij, &s_eff_ij, &dq_ij, ); let a3 = third_order_perturbation(&p, &alpha, &x_s, zeta_bar, &epsilon_k_eff_ij); let rel_err_a1 = (a1 + 29.48107233383977) / 29.48107233383977; let rel_err_a2 = (a2 + 56.178134314767334) / 56.178134314767334; let rel_err_a3 = (a3 + 374.38725161974565) / 374.38725161974565; assert_relative_eq!(rel_err_a1, 0.0, epsilon = 5e-7); assert_relative_eq!(rel_err_a2, 0.0, epsilon = 5e-7); assert_relative_eq!(rel_err_a3, 0.0, epsilon = 5e-7); } #[test] fn test_dispersion() { let parameters = hydrogen_fh("1"); let a_ref = [ -1.2683816065838103, -0.61628364979962436, -0.40740884837300861, -0.30420171646199534, -0.24264152651314486, ]; let na = 6.02214076e23; for (it, &a) in a_ref.iter().enumerate() { let t = 26.7060 * (it + 1) as f64; let v = 1.0e26; let state = StateHD::new(t, v / na, &dvector![1.0]); let properties = TemperatureDependentProperties::new(&parameters, state.temperature); let a_disp = Dispersion.helmholtz_energy_density(&parameters, &state, &properties) / na * v; assert_relative_eq!(a_disp, a, epsilon = 1e-7); } let t = 26.7060; let v = 1.0e26 * 2.0; let n = na * 2.0; let state = StateHD::new(t, v / n, &dvector![1.0]); let properties = TemperatureDependentProperties::new(&parameters, state.temperature); let a_disp = Dispersion.helmholtz_energy_density(&parameters, &state, &properties) / na * v; assert_relative_eq!(a_disp, a_ref[0] * 2.0, epsilon = 1e-7); } #[test] fn test_parameters_mix() { let p = h2_ne_fh("1"); assert_relative_eq!(p.c_ij[(0, 1)], 4.7303195840057679, epsilon = 1e-7); assert_relative_eq!(p.epsilon_k_ij[(0, 1)], 28.246978839971383, epsilon = 1e-7); assert_relative_eq!(p.lambda_a_ij[(0, 1)], 6.0, epsilon = 1e-7); assert_relative_eq!(p.lambda_r_ij[(0, 1)], 10.745966692414834, epsilon = 1e-7); } #[test] fn test_dispersion_mix() { let parameters = h2_ne_fh("1"); let a_ref = [ -4.4340438372333235, -2.1563424617699911, -1.4211021562556054, -1.0581654195146963, -0.84210863940206726, ]; let na = 6.02214076e23; let n = dvector![1.1 * na, 1.0 * na]; let v = 1.0e26; for (it, &a) in a_ref.iter().enumerate() { let t = 30.0 * (it + 1) as f64; let state = StateHD::new(t, v / n.sum(), &(&n / n.sum())); let properties = TemperatureDependentProperties::new(&parameters, state.temperature); let a_disp = Dispersion.helmholtz_energy_density(&parameters, &state, &properties) / na * v; dbg!(it); assert_relative_eq!(a_disp, a, epsilon = 5e-7); } let t = 30.0; let v = 1.0e26 * 2.0; let n = dvector![2.2 * na, 2.0 * na]; let state = StateHD::new(t, v / n.sum(), &(&n / n.sum())); let properties = TemperatureDependentProperties::new(&parameters, state.temperature); let a_disp = Dispersion.helmholtz_energy_density(&parameters, &state, &properties) / na * v; assert_relative_eq!(a_disp, a_ref[0] * 2.0, epsilon = 5e-7); } #[test] fn test_dispersion_mix_fh2() { let parameters = h2_ne_fh("2"); let a_ref = [ -4.319932383710704, -2.138549258896613, -1.4153366793223225, -1.0556128125530364, -0.840761876536818, ]; let na = 6.02214076e23; let n = dvector![1.1 * na, 1.0 * na]; let v = 1.0e26; for (it, &a) in a_ref.iter().enumerate() { let t = 30.0 * (it + 1) as f64; let state = StateHD::new(t, v / n.sum(), &(&n / n.sum())); let properties = TemperatureDependentProperties::new(&parameters, state.temperature); let a_disp = Dispersion.helmholtz_energy_density(&parameters, &state, &properties) / na * v; dbg!(it); assert_relative_eq!(a_disp, a, epsilon = 5e-7); } let t = 30.0; let v = 1.0e26 * 2.0; let n = dvector![2.2 * na, 2.0 * na]; let state = StateHD::new(t, v / n.sum(), &(&n / n.sum())); let properties = TemperatureDependentProperties::new(&parameters, state.temperature); let a_disp = Dispersion.helmholtz_energy_density(&parameters, &state, &properties) / na * v; assert_relative_eq!(a_disp, a_ref[0] * 2.0, epsilon = 5e-7); } #[cfg(feature = "dft")] #[test] fn test_dispersion_energy_density() { let p = hydrogen_fh("1"); let n = p.m.len(); let rho = ndarray::Array1::from_elem(n, 0.01); let t = 25.0; // temperature dependent segment radius // calc & store this in struct let s_eff_ij = DMatrix::from_fn(n, n, |i, j| p.calc_sigma_eff_ij(i, j, t)); // temperature dependent segment radius // calc & store this in struct let d_hs_ij = DMatrix::from_fn(n, n, |i, j| p.hs_diameter_ij(i, j, t, s_eff_ij[(i, j)])); // temperature dependent well depth // calc & store this in struct let epsilon_k_eff_ij = DMatrix::from_fn(n, n, |i, j| p.calc_epsilon_k_eff_ij(i, j, t)); // temperature dependent well depth // calc & store this in struct let dq_ij = DMatrix::from_fn(n, n, |i, j| p.quantum_d_ij(i, j, t)); // alphas .... // calc & store this in struct let alpha = Alpha::new(&p, &s_eff_ij, &epsilon_k_eff_ij, t); let a_disp = dispersion_energy_density( &p, &d_hs_ij, &s_eff_ij, &epsilon_k_eff_ij, &dq_ij, &alpha, rho.view(), t, ); dbg!(rho); dbg!(a_disp); assert_relative_eq!(a_disp, -0.022349175545184223, epsilon = 1e-7); } }
Rust
3D
feos-org/feos
crates/feos/src/saftvrqmie/dft/mod.rs
.rs
3,118
96
use super::SaftVRQMie; use crate::hard_sphere::{FMTContribution, FMTVersion, HardSphereProperties, MonomerShape}; use crate::saftvrqmie::eos::SaftVRQMieOptions; use crate::saftvrqmie::parameters::{SaftVRQMieParameters, SaftVRQMiePars}; use dispersion::AttractiveFunctional; use feos_core::FeosResult; use feos_derive::FunctionalContribution; use feos_dft::adsorption::FluidParameters; use feos_dft::solvation::PairPotential; use feos_dft::{FunctionalContribution, HelmholtzEnergyFunctionalDyn, MoleculeShape}; use nalgebra::DVector; use ndarray::{Array, Array1, Array2}; use non_additive_hs::NonAddHardSphereFunctional; use num_dual::DualNum; mod dispersion; mod non_additive_hs; impl SaftVRQMie { /// SAFT-VRQ Mie model with default options and provided FMT version. pub fn with_fmt_version( parameters: SaftVRQMieParameters, fmt_version: FMTVersion, ) -> FeosResult<Self> { let options = SaftVRQMieOptions { fmt_version, ..Default::default() }; Self::with_options(parameters, options) } } impl HelmholtzEnergyFunctionalDyn for SaftVRQMie { type Contribution<'a> = SaftVRQMieFunctionalContribution<'a>; fn contributions<'a>(&'a self) -> impl Iterator<Item = SaftVRQMieFunctionalContribution<'a>> { let mut contributions = Vec::with_capacity(3); // Hard sphere contribution let hs = FMTContribution::new(&self.params, self.options.fmt_version); contributions.push(hs.into()); // Non-additive hard-sphere contribution if self.options.inc_nonadd_term { let non_add_hs = NonAddHardSphereFunctional::new(&self.params); contributions.push(non_add_hs.into()); } // Dispersion let att = AttractiveFunctional::new(&self.params); contributions.push(att.into()); contributions.into_iter() } fn molecule_shape(&self) -> MoleculeShape<'_> { MoleculeShape::NonSpherical(&self.params.m) } } impl HardSphereProperties for SaftVRQMiePars { fn monomer_shape<N: DualNum<f64>>(&self, _: N) -> MonomerShape<'_, N> { MonomerShape::Spherical(self.m.len()) } fn hs_diameter<D: DualNum<f64> + Copy>(&self, temperature: D) -> DVector<D> { self.hs_diameter(temperature) } } impl FluidParameters for SaftVRQMie { fn epsilon_k_ff(&self) -> DVector<f64> { self.params.epsilon_k.clone() } fn sigma_ff(&self) -> DVector<f64> { self.params.sigma.clone() } } impl PairPotential for SaftVRQMie { fn pair_potential(&self, i: usize, r: &Array1<f64>, temperature: f64) -> Array2<f64> { Array::from_shape_fn((self.params.m.len(), r.len()), |(j, k)| { self.params.qmie_potential_ij(i, j, r[k], temperature)[0] }) } } /// Individual contributions for the SAFT-VRQ Mie Helmholtz energy functional. #[derive(FunctionalContribution)] pub enum SaftVRQMieFunctionalContribution<'a> { Fmt(FMTContribution<'a, SaftVRQMiePars>), NonAddHardSphere(NonAddHardSphereFunctional<'a>), Attractive(AttractiveFunctional<'a>), }
Rust
3D
feos-org/feos
crates/feos/src/saftvrqmie/dft/non_additive_hs.rs
.rs
5,807
181
use crate::saftvrqmie::parameters::SaftVRQMiePars; use feos_core::FeosResult; use feos_dft::{FunctionalContribution, WeightFunction, WeightFunctionInfo, WeightFunctionShape}; use nalgebra::DVector; use ndarray::*; use num_dual::DualNum; use std::f64::consts::PI; pub const N0_CUTOFF: f64 = 1e-9; #[derive(Clone)] pub struct NonAddHardSphereFunctional<'a> { parameters: &'a SaftVRQMiePars, } impl<'a> NonAddHardSphereFunctional<'a> { pub fn new(parameters: &'a SaftVRQMiePars) -> Self { Self { parameters } } } impl<'a> FunctionalContribution for NonAddHardSphereFunctional<'a> { fn name(&self) -> &'static str { "Non-additive hard-sphere functional" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { let p = &self.parameters; let r = p.hs_diameter(temperature) * N::from(0.5); WeightFunctionInfo::new(DVector::from_fn(r.len(), |i, _| i), false) .add( WeightFunction::new_scaled(r.clone(), WeightFunctionShape::Delta), false, ) .add( WeightFunction { prefactor: p.m.map(N::from), kernel_radius: r.clone(), shape: WeightFunctionShape::DeltaVec, }, false, ) .add( WeightFunction { prefactor: p.m.map(N::from), kernel_radius: r, shape: WeightFunctionShape::Theta, }, true, ) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, weighted_densities: ArrayView2<N>, ) -> FeosResult<Array1<N>> { let p = &self.parameters; // number of components let n = p.m.len(); // number of dimensions let dim = (weighted_densities.shape()[0] - 1) / n - 1; // weighted densities let n0i = weighted_densities.slice_axis(Axis(0), Slice::new(0, Some(n as isize), 1)); let n2vi: Vec<_> = (0..dim) .map(|i| { weighted_densities.slice_axis( Axis(0), Slice::new((n * (i + 1)) as isize, Some((n * (i + 2)) as isize), 1), ) }) .collect(); let n3 = weighted_densities.index_axis(Axis(0), n * (dim + 1)); // calculate rho0 let d = p.hs_diameter(temperature); let mut n2i = Array::zeros(n0i.raw_dim()); for i in 0..n { n2i.index_axis_mut(Axis(0), i) .assign(&(&n0i.index_axis(Axis(0), i) * (d[i].powi(2) * (p.m[i] * PI)))); } let mut rho0: Array2<N> = (n2vi .iter() .map(|n2vi| n2vi * n2vi) .fold(Array::zeros(n0i.raw_dim()), |acc, x| acc + x) / -(&n2i * &n2i) + 1.0) * n0i; rho0.iter_mut().zip(&n0i).for_each(|(rho0, &n0i)| { if n0i.re() < N0_CUTOFF { *rho0 = n0i; } }); // calculate xi let n2v: Vec<_> = n2vi.iter().map(|n2vi| n2vi.sum_axis(Axis(0))).collect(); let n2 = n2i.sum_axis(Axis(0)); let mut xi = n2v .iter() .map(|n2v| n2v * n2v) .fold(Array::zeros(n3.raw_dim()), |acc, x| acc + x) / -(&n2 * &n2) + 1.0; xi.iter_mut() .zip(&n0i.sum_axis(Axis(0))) .for_each(|(xi, &n0i)| { if n0i.re() < N0_CUTOFF { *xi = N::one(); } }); // auxiliary variables let n3i = n3.mapv(|n3| (-n3 + 1.0).recip()); // temperature dependent segment radius // calc & store this in struct let s_eff_ij = Array2::from_shape_fn((n, n), |(i, j)| p.calc_sigma_eff_ij(i, j, temperature)); // temperature dependent segment radius // calc & store this in struct let d_hs_ij = Array2::from_shape_fn((n, n), |(i, j)| { p.hs_diameter_ij(i, j, temperature, s_eff_ij[[i, j]]) }); // Additive hard-sphere diameter let d_hs_add_ij = Array2::from_shape_fn((n, n), |(i, j)| (d_hs_ij[[i, i]] + d_hs_ij[[j, j]]) * 0.5); Ok(rho0 .view() .into_shape_with_order([n, rho0.len() / n]) .unwrap() .axis_iter(Axis(1)) .zip(n2.iter()) .zip(n3i.iter()) .zip(xi.iter()) .map(|(((rho0, &n2), &n3i), &xi)| { non_additive_hs_energy_density(p, &d_hs_ij, &d_hs_add_ij, &rho0, n2, n3i, xi) }) .collect::<Array1<N>>() .into_shape_with_order(n2.raw_dim()) .unwrap()) } } pub fn non_additive_hs_energy_density<S, N: DualNum<f64> + Copy>( parameters: &SaftVRQMiePars, d_hs_ij: &Array2<N>, d_hs_add_ij: &Array2<N>, rho0: &ArrayBase<S, Ix1>, n2: N, n3i: N, xi: N, ) -> N where S: Data<Elem = N>, { // auxiliary variables let n = rho0.len(); let p = parameters; let d = Array1::from_shape_fn(n, |i| d_hs_ij[[i, i]]); let g_hs_ij = Array2::from_shape_fn((n, n), |(i, j)| { let mu = d[i] * d[j] / (d[i] + d[j]); n3i + mu * n2 * xi * n3i.powi(2) / 2.0 + (mu * n2 * xi).powi(2) * n3i.powi(3) / 18.0 }); // segment densities let rho0_s = Array1::from_shape_fn(n, |i| -> N { rho0[i] * p.m[i] }); Array2::from_shape_fn((n, n), |(i, j)| { -rho0_s[i] * rho0_s[j] * d_hs_add_ij[[i, j]].powi(2) * g_hs_ij[[i, j]] * (d_hs_add_ij[[i, j]] - d_hs_ij[[i, j]]) * 2.0 * PI }) .sum() }
Rust
3D
feos-org/feos
crates/feos/src/saftvrqmie/dft/dispersion.rs
.rs
3,143
98
use crate::saftvrqmie::eos::dispersion::{Alpha, dispersion_energy_density}; use crate::saftvrqmie::parameters::SaftVRQMiePars; use feos_core::FeosResult; use feos_dft::{FunctionalContribution, WeightFunction, WeightFunctionInfo, WeightFunctionShape}; use nalgebra::{DMatrix, DVector}; use ndarray::*; use num_dual::DualNum; /// psi Parameter for DFT (Sauer2017) const PSI_DFT: f64 = 1.3862; /// psi Parameter for pDGT (Rehner2018) const PSI_PDGT: f64 = 1.3286; #[derive(Clone)] pub struct AttractiveFunctional<'a> { parameters: &'a SaftVRQMiePars, } impl<'a> AttractiveFunctional<'a> { pub fn new(parameters: &'a SaftVRQMiePars) -> Self { Self { parameters } } } fn att_weight_functions<N: DualNum<f64> + Copy>( p: &SaftVRQMiePars, psi: f64, temperature: N, ) -> WeightFunctionInfo<N> { let d = p.hs_diameter(temperature); WeightFunctionInfo::new(DVector::from_fn(d.len(), |i, _| i), false).add( WeightFunction::new_scaled(d * N::from(psi), WeightFunctionShape::Theta), false, ) } impl<'a> FunctionalContribution for AttractiveFunctional<'a> { fn name(&self) -> &'static str { "Attractive functional" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { att_weight_functions(self.parameters, PSI_DFT, temperature) } fn weight_functions_pdgt<N: DualNum<f64> + Copy>( &self, temperature: N, ) -> WeightFunctionInfo<N> { att_weight_functions(self.parameters, PSI_PDGT, temperature) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, density: ArrayView2<N>, ) -> FeosResult<Array1<N>> { // auxiliary variables let p = &self.parameters; let n = p.m.len(); // temperature dependent segment radius // calc & store this in struct let s_eff_ij = DMatrix::from_fn(n, n, |i, j| p.calc_sigma_eff_ij(i, j, temperature)); // temperature dependent segment radius // calc & store this in struct let d_hs_ij = DMatrix::from_fn(n, n, |i, j| { p.hs_diameter_ij(i, j, temperature, s_eff_ij[(i, j)]) }); // temperature dependent well depth // calc & store this in struct let epsilon_k_eff_ij = DMatrix::from_fn(n, n, |i, j| p.calc_epsilon_k_eff_ij(i, j, temperature)); // temperature dependent well depth // calc & store this in struct let dq_ij = DMatrix::from_fn(n, n, |i, j| p.quantum_d_ij(i, j, temperature)); // alphas .... // calc & store this in struct let alpha = Alpha::new(p, &s_eff_ij, &epsilon_k_eff_ij, temperature); let phi = density .axis_iter(Axis(1)) .map(|rho_lane| { dispersion_energy_density( p, &d_hs_ij, &s_eff_ij, &epsilon_k_eff_ij, &dq_ij, &alpha, rho_lane, temperature, ) }) .collect(); Ok(phi) } }
Rust
3D
feos-org/feos
crates/feos/src/multiparameter/mod.rs
.rs
10,869
305
//! High-precision multiparameter equations of state for common pure fluids. //! //! The residual and ideal gas contributions are always parametrized jointly for //! multiparameter equations of state. Construct the equation of state by reading //! parameters, e.g., [MultiParameterParameters::from_json], and passing them to //! the equation of state with [MultiParameter::new]. use feos_core::parameter::Parameters; use feos_core::{EquationOfState, IdealGas, Molarweight, ResidualDyn, StateHD, Subset}; use nalgebra::DVector; use num_dual::DualNum; use quantity::MolarWeight; use serde::Deserialize; use std::f64::consts::E; mod ideal_gas_function; mod residual_function; use ideal_gas_function::{IdealGasFunction, IdealGasFunctionJson}; use residual_function::{ResidualFunction, ResidualFunctionJson}; /// Pure-component parameters for a multiparameter equation of state /// (residual and ideal gas contributions). #[derive(Clone, Deserialize)] pub struct MultiParameterRecord { tc: f64, rhoc: f64, residual: Vec<ResidualFunctionJson>, ideal_gas: Vec<IdealGasFunctionJson>, } /// Parameter set required for the multiparameter equation of state. pub type MultiParameterParameters = Parameters<MultiParameterRecord, (), ()>; /// Residual contribution of the multiparameter equation of state. #[derive(Clone)] pub struct MultiParameter { tc: f64, rhoc: f64, terms: Vec<ResidualFunction>, molar_weight: MolarWeight<DVector<f64>>, } /// Ideal gas contribution of the multiparameter equation of state. #[derive(Clone)] pub struct MultiParameterIdealGas { tc: f64, rhoc: f64, terms: Vec<IdealGasFunction>, } /// Multiparameter equation of state consisting of a residual and a corresponding ideal gas contribution. pub type MultiParameterEquationOfState = EquationOfState<Vec<MultiParameterIdealGas>, MultiParameter>; impl MultiParameter { pub fn new(mut parameters: MultiParameterParameters) -> MultiParameterEquationOfState { if parameters.pure.len() != 1 { panic!("Multiparameter equations of state are only implemented for pure components!"); } let record = parameters.pure.pop().unwrap().model_record; let terms = record.residual.into_iter().flatten().collect(); let residual = Self { tc: record.tc, rhoc: record.rhoc, terms, molar_weight: parameters.molar_weight, }; let terms = record.ideal_gas.into_iter().flatten().collect(); let ideal_gas = MultiParameterIdealGas { tc: record.tc, rhoc: record.rhoc, terms, }; EquationOfState::new(vec![ideal_gas], residual) } } impl ResidualDyn for MultiParameter { fn components(&self) -> usize { 1 } fn compute_max_density<D: DualNum<f64> + Copy>(&self, _: &DVector<D>) -> D { // Not sure what value works well here. This one is based on rho_c = 0.31*rho_max. D::from(6.02214076e-7 * self.rhoc / 0.31) } fn reduced_helmholtz_energy_density_contributions<D: DualNum<f64> + Copy>( &self, state: &StateHD<D>, ) -> Vec<(&'static str, D)> { let rho = state.partial_density.sum(); let delta = rho / (6.02214076e-7 * self.rhoc); let tau = state.temperature.recip() * self.tc; vec![( "Multiparameter", self.terms .iter() .map(|r| r.evaluate(delta, tau) * rho) .sum(), )] } } impl Molarweight for MultiParameter { fn molar_weight(&self) -> MolarWeight<DVector<f64>> { self.molar_weight.clone() } } impl Subset for MultiParameter { fn subset(&self, _: &[usize]) -> Self { self.clone() } } impl IdealGas for MultiParameterIdealGas { fn ln_lambda3<D2: DualNum<f64, Inner = f64> + Copy>(&self, temperature: D2) -> D2 { let tau = temperature.recip() * self.tc; // bit of a hack to convert from phi^0 into ln Lambda^3 let delta = D2::from(E / (6.02214076e-7 * self.rhoc)); self.terms.iter().map(|r| r.evaluate(delta, tau)).sum() } fn ideal_gas_model(&self) -> &'static str { "Ideal Gas (Multiparameter)" } } #[cfg(test)] mod test { use approx::{assert_relative_eq, assert_relative_ne}; use feos_core::parameter::IdentifierOption; use feos_core::{SolverOptions, State, Total}; use nalgebra::{Dyn, SVector, U2, dvector}; use num_dual::{Dual2Vec, hessian}; use quantity::{GRAM, KELVIN, KILO, KILOGRAM, METER, MOL, RGAS}; use super::*; fn water() -> MultiParameterEquationOfState { let parameters = Parameters::from_json( vec!["Water"], "../../parameters/multiparameter/coolprop.json", None, IdentifierOption::Name, ) .unwrap(); MultiParameter::new(parameters) } #[test] fn test_phi_r_1() { let t = 500.; let rho = 838.025; let eos = water(); let tau = eos.tc / t; let delta = rho / (eos.rhoc * eos.molar_weight.get(0).convert_into(KILO * GRAM / MOL)); let (phi, dphi, d2phi) = hessian( |x| { let [delta, tau] = x.data.0[0]; eos.terms .iter() .map(|f| f.evaluate(delta, tau)) .sum::<Dual2Vec<f64, f64, U2>>() }, &SVector::from([delta, tau]), ); println!("{}\n{}\n{}", phi, dphi, d2phi); assert_eq!(format!("{phi:.8}"), "-3.42693206"); assert_eq!(format!("{:.8}", dphi[0]), "-0.36436665"); assert_eq!(format!("{:.8}", dphi[1]), "-5.81403435"); assert_eq!(format!("{:.8}", d2phi[(0, 0)]), "0.85606370"); assert_eq!(format!("{:.8}", d2phi[(0, 1)]), "-1.12176915"); assert_eq!(format!("{:.8}", d2phi[(1, 1)]), "-2.23440737"); } #[test] fn test_phi_r_2() { let t = 647.; let rho = 358.; let eos = water(); let tau = eos.tc / t; let delta = rho / (eos.rhoc * eos.molar_weight.get(0).convert_into(KILO * GRAM / MOL)); let (phi, dphi, d2phi) = hessian( |x| { let [delta, tau] = x.data.0[0]; eos.terms .iter() .map(|f| f.evaluate(delta, tau)) .sum::<Dual2Vec<f64, f64, U2>>() }, &SVector::from([delta, tau]), ); println!("{}\n{}\n{}", phi, dphi, d2phi); assert_eq!(format!("{phi:.8}"), "-1.21202657"); assert_eq!(format!("{:.8}", dphi[0]), "-0.71401202"); assert_eq!(format!("{:.8}", dphi[1]), "-3.21722501"); assert_eq!(format!("{:.8}", d2phi[(0, 0)]), "0.47573070"); assert_eq!(format!("{:.8}", d2phi[(0, 1)]), "-1.33214720"); assert_eq!(format!("{:.8}", d2phi[(1, 1)]), "-9.96029507"); } #[test] fn test_phi_o_1() { let t = 500.; let rho = 838.025; let eos = water(); let tau = eos.tc / t; let delta = rho / (eos.rhoc * eos.molar_weight.get(0).convert_into(KILO * GRAM / MOL)); let (phi, dphi, d2phi) = hessian( |x| { let [delta, tau] = x.data.0[0]; eos.ideal_gas[0] .terms .iter() .map(|r| r.evaluate(delta, tau)) .sum::<Dual2Vec<f64, f64, U2>>() }, &SVector::from([delta, tau]), ); println!("{}\n{}\n{}", phi, dphi, d2phi); assert_eq!(format!("{phi:.7}"), "2.0479773"); assert_eq!(format!("{:.8}", dphi[0]), "0.38423675"); assert_eq!(format!("{:.8}", dphi[1]), "9.04611106"); assert_eq!(format!("{:.8}", d2phi[(0, 0)]), "-0.14763788"); assert_eq!(format!("{:.8}", d2phi[(0, 1)]), "-0.00000000"); assert_eq!(format!("{:.8}", d2phi[(1, 1)]), "-1.93249185"); } #[test] fn test_phi_o_2() { let t = 647.; let rho = 358.; let eos = water(); let tau = eos.tc / t; let delta = rho / (eos.rhoc * eos.molar_weight.get(0).convert_into(KILO * GRAM / MOL)); let (phi, dphi, d2phi) = hessian( |x| { let [delta, tau] = x.data.0[0]; eos.ideal_gas[0] .terms .iter() .map(|r| r.evaluate(delta, tau)) .sum::<Dual2Vec<f64, f64, U2>>() }, &SVector::from([delta, tau]), ); println!("{}\n{}\n{}", phi, dphi, d2phi); assert_eq!(format!("{phi:.8}"), "-1.56319605"); assert_eq!(format!("{:.8}", dphi[0]), "0.89944134"); assert_eq!(format!("{:.8}", dphi[1]), "9.80343918"); assert_eq!(format!("{:.8}", d2phi[(0, 0)]), "-0.80899473"); assert_eq!(format!("{:.8}", d2phi[(0, 1)]), "-0.00000000"); assert_eq!(format!("{:.8}", d2phi[(1, 1)]), "-3.43316334"); } #[test] fn test_ideal_gas_hack() { let t = 647. * KELVIN; let rho = 358. * KILOGRAM / METER.powi::<3>(); let eos = &water(); let mw = eos.molar_weight.get(0); let moles = dvector![1.8] * MOL; let a_feos = eos.ideal_gas_helmholtz_energy(t, moles.sum() * mw / rho, &moles); let phi_feos = (a_feos / RGAS / moles.sum() / t).into_value(); println!("A: {a_feos}"); println!("phi(feos): {phi_feos}"); let delta = (rho / (eos.rhoc * MOL / METER.powi::<3>() * mw)).into_value(); let tau = (eos.tc * KELVIN / t).into_value(); let phi = eos.ideal_gas[0] .terms .iter() .map(|r| r.evaluate(delta, tau)) .sum::<f64>(); println!("phi(IAPWS): {phi}"); assert_relative_eq!(phi_feos, phi, max_relative = 1e-15) } #[test] fn test_critical_point() { let eos = &water(); let options = SolverOptions { verbosity: feos_core::Verbosity::Iter, ..Default::default() }; let cp: State<_, Dyn, f64> = State::critical_point(&eos, None, Some(647. * KELVIN), None, options).unwrap(); println!("{cp}"); assert_relative_eq!(cp.temperature, eos.tc * KELVIN, max_relative = 1e-13); let cp: State<_, Dyn, f64> = State::critical_point(&eos, None, None, None, Default::default()).unwrap(); println!("{cp}"); assert_relative_ne!(cp.temperature, eos.tc * KELVIN, max_relative = 1e-13); let cp: State<_, Dyn, f64> = State::critical_point(&eos, None, Some(700.0 * KELVIN), None, Default::default()) .unwrap(); println!("{cp}"); assert_relative_eq!(cp.temperature, eos.tc * KELVIN, max_relative = 1e-13) } }
Rust
3D
feos-org/feos
crates/feos/src/multiparameter/ideal_gas_function.rs
.rs
5,225
141
use num_dual::DualNum; use serde::Deserialize; use serde_json::Value; use std::collections::HashMap; #[derive(Clone, Deserialize)] pub struct IdealGasFunctionJson { #[serde(rename = "type")] pub ty: String, #[serde(flatten)] parameters: HashMap<String, Value>, } pub struct IdealGasFunctionIterator { inner: IdealGasFunctionJson, count: usize, index: usize, } impl Iterator for IdealGasFunctionIterator { type Item = IdealGasFunction; fn next(&mut self) -> Option<Self::Item> { if self.index == self.count { return None; } let mut parameters: HashMap<_, _> = self .inner .parameters .iter() .map(|(k, v)| { ( k.clone(), if self.inner.ty == "IdealGasHelmholtzCP0AlyLee" { // AlyLee parameters are stored as list instead of named parameters v.clone() } else { v.as_array().map_or(v, |v| &v[self.index]).clone() }, ) }) .collect(); if self.inner.ty == "IdealGasHelmholtzCP0AlyLee" { self.index += 5 } else { self.index += 1; } parameters.insert("type".into(), serde_json::to_value(&self.inner.ty).unwrap()); Some(serde_json::from_value(serde_json::to_value(parameters).unwrap()).unwrap()) } } impl IntoIterator for IdealGasFunctionJson { type Item = IdealGasFunction; type IntoIter = IdealGasFunctionIterator; fn into_iter(self) -> Self::IntoIter { let count = self .parameters .values() .map(|e| e.as_array().map_or(1, Vec::len)) .max() .unwrap(); IdealGasFunctionIterator { count, inner: self, index: 0, } } } #[derive(Clone, Copy, Deserialize)] #[serde(tag = "type")] #[expect(non_snake_case)] pub enum IdealGasFunction { IdealGasHelmholtzLead { a1: f64, a2: f64 }, IdealGasHelmholtzLogTau { a: f64 }, IdealGasHelmholtzPower { n: f64, t: f64 }, IdealGasHelmholtzPlanckEinstein { n: f64, t: f64 }, IdealGasHelmholtzPlanckEinsteinFunctionT { Tcrit: f64, n: f64, v: f64 }, IdealGasHelmholtzPlanckEinsteinGeneralized { c: f64, d: f64, n: f64, t: f64 }, IdealGasHelmholtzCP0AlyLee { T0: f64, Tc: f64, c: [f64; 5] }, IdealGasHelmholtzCP0Constant { T0: f64, Tc: f64, cp_over_R: f64 }, IdealGasHelmholtzCP0PolyT { T0: f64, Tc: f64, c: f64, t: f64 }, IdealGasHelmholtzEnthalpyEntropyOffset { a1: f64, a2: f64 }, } impl IdealGasFunction { pub fn evaluate<D: DualNum<f64> + Copy>(&self, delta: D, tau: D) -> D { match *self { IdealGasFunction::IdealGasHelmholtzLead { a1, a2 } => delta.ln() + a1 + tau * a2, IdealGasFunction::IdealGasHelmholtzLogTau { a } => tau.ln() * a, IdealGasFunction::IdealGasHelmholtzPower { n, t } => tau.powf(t) * n, IdealGasFunction::IdealGasHelmholtzPlanckEinstein { n, t } => { (-(-tau * t).exp()).ln_1p() * n } IdealGasFunction::IdealGasHelmholtzPlanckEinsteinFunctionT { Tcrit, n, v } => { (-(-tau * v / Tcrit).exp()).ln_1p() * n } IdealGasFunction::IdealGasHelmholtzPlanckEinsteinGeneralized { c, d, n, t } => { ((tau * t).exp() * d + c).ln() * n } IdealGasFunction::IdealGasHelmholtzCP0AlyLee { T0, Tc, c } => { let [a, b, c, d, e] = c; let mut res = D::zero(); if a > 0.0 { let tau0 = Tc / T0; res += (-tau / tau0 + 1.0 + (tau / tau0).ln()) * a; } if b > 0.0 { res += (-(-tau * 2.0 * c / Tc).exp()).ln_1p() * b; } if d > 0.0 { res -= ((-tau * 2.0 * e / Tc).exp()).ln_1p() * d; } res } IdealGasFunction::IdealGasHelmholtzCP0Constant { T0, Tc, cp_over_R } => { let tau0 = Tc / T0; (-tau / tau0 + 1.0 + (tau / tau0).ln()) * cp_over_R } IdealGasFunction::IdealGasHelmholtzCP0PolyT { T0, Tc, c, t } => { // unfortunately some models use floats and other models use 0 or -1 which needs to be treated separately... if t.abs() < 10.0 * f64::EPSILON { let tau0 = Tc / T0; (-tau / tau0 + 1.0 + (tau / tau0).ln()) * c } else if (t + 1.0).abs() < 10.0 * f64::EPSILON { let tau0 = Tc / T0; (-tau / Tc * (tau / tau0).ln() + (tau - tau0) / Tc) * c } else { (-tau.powf(-t) * Tc.powf(t) / (t * (t + 1.0)) - tau * T0.powf(t + 1.0) / (Tc * (t + 1.0)) + T0.powf(t) / t) * c } } IdealGasFunction::IdealGasHelmholtzEnthalpyEntropyOffset { a1, a2 } => tau * a2 + a1, } } }
Rust
3D
feos-org/feos
crates/feos/src/multiparameter/residual_function.rs
.rs
5,281
197
use num_dual::DualNum; use serde::Deserialize; use serde_json::Value; use std::collections::HashMap; #[derive(Clone, Deserialize)] pub struct ResidualFunctionJson { #[serde(rename = "type")] ty: String, #[serde(flatten)] parameters: HashMap<String, Vec<Value>>, } pub struct ResidualFunctionIterator { inner: ResidualFunctionJson, count: usize, index: usize, } impl Iterator for ResidualFunctionIterator { type Item = ResidualFunction; fn next(&mut self) -> Option<Self::Item> { if self.index == self.count { return None; } let mut parameters: HashMap<_, _> = self .inner .parameters .iter() .map(|(k, v)| (k.clone(), v[self.index].clone())) .collect(); self.index += 1; parameters.insert("type".into(), serde_json::to_value(&self.inner.ty).unwrap()); Some(serde_json::from_value(serde_json::to_value(parameters).unwrap()).unwrap()) } } impl IntoIterator for ResidualFunctionJson { type Item = ResidualFunction; type IntoIter = ResidualFunctionIterator; fn into_iter(self) -> Self::IntoIter { let count = self.parameters.values().next().unwrap().len(); ResidualFunctionIterator { count, inner: self, index: 0, } } } #[derive(Clone, Copy, Deserialize)] #[serde(tag = "type")] pub enum ResidualFunction { ResidualHelmholtzPower { d: i32, l: i32, n: f64, t: f64, }, ResidualHelmholtzGaussian { d: i32, n: f64, t: f64, beta: f64, epsilon: f64, eta: f64, gamma: f64, }, ResidualHelmholtzNonAnalytic { #[serde(rename = "A")] aa: f64, #[serde(rename = "B")] bb: f64, #[serde(rename = "C")] cc: f64, #[serde(rename = "D")] dd: f64, a: f64, b: f64, beta: f64, n: f64, }, ResidualHelmholtzExponential { d: i32, g: f64, l: i32, n: f64, t: i32, }, ResidualHelmholtzDoubleExponential { d: i32, gd: f64, gt: f64, ld: i32, lt: i32, n: f64, t: i32, }, ResidualHelmholtzGaoB { b: f64, beta: f64, d: i32, epsilon: f64, eta: f64, gamma: f64, n: f64, t: f64, }, ResidualHelmholtzLemmon2005 { d: i32, l: i32, m: f64, n: f64, t: f64, }, } impl ResidualFunction { pub fn evaluate<D: DualNum<f64> + Copy>(&self, delta: D, tau: D) -> D { match *self { ResidualFunction::ResidualHelmholtzPower { d, l, n, t } => { let mut pre = delta.powi(d) * tau.powf(t) * n; if l != 0 { pre *= (-delta.powi(l)).exp() }; pre } ResidualFunction::ResidualHelmholtzGaussian { d, n, t, beta, epsilon, eta, gamma, } => { (delta.powi(d) * tau.powf(t) * n) * (-(delta - epsilon).powi(2) * eta - (tau - gamma).powi(2) * beta).exp() } ResidualFunction::ResidualHelmholtzNonAnalytic { aa, bb, cc, dd, a, b, beta, n, } => { let delta_m1 = (delta - 1.0).powi(2); let psi = (-delta_m1 * cc - (tau - 1.0).powi(2) * dd).exp(); let theta = -tau + 1.0 + delta_m1.powf(0.5 / beta) * aa; let ddelta = theta * theta + delta_m1.powf(a) * bb; ddelta.powf(b) * delta * psi * n } ResidualFunction::ResidualHelmholtzExponential { d, g, l, n, t } => { delta.powi(d) * tau.powi(t) * n * (-delta.powi(l) * g).exp() } ResidualFunction::ResidualHelmholtzDoubleExponential { d, gd, gt, ld, lt, n, t, } => delta.powi(d) * tau.powi(t) * n * (-delta.powi(ld) * gd - tau.powi(lt) * gt).exp(), ResidualFunction::ResidualHelmholtzGaoB { b, beta, d, epsilon, eta, gamma, n, t, } => { let f_delta = delta.powi(d) * ((delta - epsilon).powi(2) * eta).exp(); let f_tau = tau.powf(t) * ((tau - gamma).powi(2) * beta + b).recip().exp(); f_tau * f_delta * n } ResidualFunction::ResidualHelmholtzLemmon2005 { d, l, m, n, t } => { let mut pre = delta.powi(d) * tau.powf(t) * n; if l != 0 { pre *= (-delta.powi(l)).exp() } if m > 0.0 { pre *= (-tau.powf(m)).exp() } pre } } } }
Rust
3D
feos-org/feos
crates/feos/src/association/mod.rs
.rs
19,570
549
//! Generic implementation of the SAFT association contribution //! that can be used across models. use crate::hard_sphere::HardSphereProperties; use feos_core::parameter::{AssociationParameters, AssociationSite, BinaryParameters}; use feos_core::{FeosError, FeosResult, StateHD}; use nalgebra::{DMatrix, DVector}; use num_dual::linalg::LU; use num_dual::*; #[cfg(feature = "dft")] mod dft; #[cfg(feature = "dft")] pub use dft::YuWuAssociationFunctional; /// Calculation of association strength between association sites. /// /// The default implementation for the association strength matrix /// [AssociationStrength::association_strength] multiplies the model-specific /// site-site association strength [AssociationStrength::association_strength_ij] /// with the contact value of the hard-sphere pair correlation function. /// /// For implementations that require a different form, /// [AssociationStrength::association_strength] can be overwritten. pub trait AssociationStrength: HardSphereProperties { type Record; /// Association strength excluding the contact value of the pair correlation function. fn association_strength_ij<D: DualNum<f64> + Copy>( &self, temperature: D, comp_i: usize, comp_j: usize, assoc_ij: &Self::Record, ) -> D; /// Association strength matrix for all association sites. fn association_strength<D: DualNum<f64> + Copy>( &self, state: &StateHD<D>, diameter: &DVector<D>, (sites1, sites2): (&[AssociationSite], &[AssociationSite]), association_parameters: &[BinaryParameters<Self::Record, ()>], ) -> DMatrix<D> { let mut delta = DMatrix::zeros(sites1.len(), sites2.len()); if sites1.len() * sites2.len() == 0 { return delta; } let [zeta2, n3] = self.zeta(state.temperature, &state.partial_density, [2, 3]); let n2 = zeta2 * 6.0; let n3i = (-n3 + 1.0).recip(); for b in association_parameters { let [i, j] = [b.id1, b.id2]; let [comp_i, comp_j] = [sites1[i].assoc_comp, sites2[j].assoc_comp]; // g_HS(d) let di = diameter[comp_i]; let dj = diameter[comp_j]; let k = di * dj / (di + dj) * (n2 * n3i); let g_contact = n3i * (k * (k / 18.0 + 0.5) + 1.0); delta[(i, j)] = g_contact * self.association_strength_ij(state.temperature, comp_i, comp_j, &b.model_record); } delta } } /// Implementation of the association Helmholtz energy /// contribution and functional. #[derive(Clone, Copy)] pub struct Association { max_iter: usize, tol: f64, force_cross_association: bool, } impl Association { pub fn new(max_iter: usize, tol: f64) -> Self { Self { max_iter, tol, force_cross_association: false, } } pub fn new_cross_association(max_iter: usize, tol: f64) -> Self { let mut res = Self::new(max_iter, tol); res.force_cross_association = true; res } #[inline] pub fn helmholtz_energy_density<A: AssociationStrength, D: DualNum<f64> + Copy>( &self, model: &A, parameters: &AssociationParameters<A::Record>, state: &StateHD<D>, diameter: &DVector<D>, ) -> D { let a = parameters; // association strength let delta_ab = model.association_strength(state, diameter, (&a.sites_a, &a.sites_b), &a.binary_ab); let delta_cc = model.association_strength(state, diameter, (&a.sites_c, &a.sites_c), &a.binary_cc); match ( a.sites_a.len() * a.sites_b.len(), a.sites_c.len(), self.force_cross_association, ) { (0, 0, _) => D::zero(), (1, 0, false) => self.helmholtz_energy_density_ab_analytic(a, state, delta_ab[(0, 0)]), (0, 1, false) => self.helmholtz_energy_density_cc_analytic(a, state, delta_cc[(0, 0)]), (1, 1, false) => { self.helmholtz_energy_density_ab_analytic(a, state, delta_ab[(0, 0)]) + self.helmholtz_energy_density_cc_analytic(a, state, delta_cc[(0, 0)]) } _ => { // extract site densities of associating segments let rho: Vec<_> = a .sites_a .iter() .chain(a.sites_b.iter()) .chain(a.sites_c.iter()) .map(|s| state.partial_density[a.component_index[s.assoc_comp]] * s.n) .collect(); let rho = DVector::from(rho); // Helmholtz energy self.helmholtz_energy_density_cross_association(&rho, &delta_ab, &delta_cc, None) .unwrap_or_else(|_| D::from(f64::NAN)) } } } fn helmholtz_energy_density_ab_analytic<A, D: DualNum<f64> + Copy>( &self, parameters: &AssociationParameters<A>, state: &StateHD<D>, delta: D, ) -> D { let a = parameters; // site densities let rhoa = state.partial_density[a.component_index[a.sites_a[0].assoc_comp]] * a.sites_a[0].n; let rhob = state.partial_density[a.component_index[a.sites_b[0].assoc_comp]] * a.sites_b[0].n; // fraction of non-bonded association sites let sqrt = ((delta * (rhoa - rhob) + 1.0).powi(2) + delta * rhob * 4.0).sqrt(); let xa = (sqrt + (delta * (rhob - rhoa) + 1.0)).recip() * 2.0; let xb = (sqrt + (delta * (rhoa - rhob) + 1.0)).recip() * 2.0; rhoa * (xa.ln() - xa * 0.5 + 0.5) + rhob * (xb.ln() - xb * 0.5 + 0.5) } fn helmholtz_energy_density_cc_analytic<A, D: DualNum<f64> + Copy>( &self, parameters: &AssociationParameters<A>, state: &StateHD<D>, delta: D, ) -> D { let a = parameters; // site density let rhoc = state.partial_density[a.component_index[a.sites_c[0].assoc_comp]] * a.sites_c[0].n; // fraction of non-bonded association sites let xc = ((delta * 4.0 * rhoc + 1.0).sqrt() + 1.0).recip() * 2.0; rhoc * (xc.ln() - xc * 0.5 + 0.5) } fn helmholtz_energy_density_cross_association<D: DualNum<f64> + Copy>( &self, rho: &DVector<D>, delta_ab: &DMatrix<D>, delta_cc: &DMatrix<D>, x0: Option<&mut DVector<f64>>, ) -> FeosResult<D> { // check if density is close to 0 if rho.sum().re() < f64::EPSILON { if let Some(x0) = x0 { x0.fill(1.0); } return Ok(D::zero()); } // cross-association according to Michelsen2006 // initialize monomer fraction let mut x = match &x0 { Some(x0) => (*x0).clone(), None => DVector::from_element(rho.len(), 0.2), }; let delta_ab_re = delta_ab.map(|d| d.re()); let delta_cc_re = delta_cc.map(|d| d.re()); let rho_re = rho.map(|r| r.re()); for k in 0..self.max_iter { if Self::newton_step_cross_association( &mut x, &delta_ab_re, &delta_cc_re, &rho_re, self.tol, )? { break; } if k == self.max_iter - 1 { return Err(FeosError::NotConverged("Cross association".into())); } } // calculate derivatives let mut x_dual = x.map(D::from); for _ in 0..D::NDERIV { Self::newton_step_cross_association(&mut x_dual, delta_ab, delta_cc, rho, self.tol)?; } // save monomer fraction if let Some(x0) = x0 { *x0 = x; } // Helmholtz energy density let f = |x: D| x.ln() - x * 0.5 + 0.5; Ok(rho.dot(&x_dual.map(f))) } fn newton_step_cross_association<D: DualNum<f64> + Copy>( x: &mut DVector<D>, delta_ab: &DMatrix<D>, delta_cc: &DMatrix<D>, rho: &DVector<D>, tol: f64, ) -> FeosResult<bool> { let nassoc = x.len(); // gradient let mut g = x.map(|x| x.recip()); // Hessian let mut h: DMatrix<D> = DMatrix::zeros(nassoc, nassoc); // split arrays let (a, b) = delta_ab.shape(); let (c, _) = delta_cc.shape(); let (xa, xc) = x.rows_range_pair(..a + b, a + b..); let (xa, xb) = xa.rows_range_pair(..a, a..); let (rhoa, rhoc) = rho.rows_range_pair(..a + b, a + b..); let (rhoa, rhob) = rhoa.rows_range_pair(..a, a..); for i in 0..nassoc { // calculate gradients let dnx = if i < a { let d = delta_ab.row(i).transpose(); xb.component_mul(&rhob).dot(&d) + 1.0 } else if i < a + b { let d = delta_ab.column(i - a); xa.component_mul(&rhoa).dot(&d) + 1.0 } else { let d = delta_cc.column(i - a - b); xc.component_mul(&rhoc).dot(&d) + 1.0 }; g[i] -= dnx; // approximate hessian h[(i, i)] = -dnx / x[i]; if i < a { for j in 0..b { h[(i, a + j)] = -delta_ab[(i, j)] * rhob[j]; } } else if i < a + b { for j in 0..a { h[(i, j)] = -delta_ab[(j, i - a)] * rhoa[j]; } } else { for j in 0..c { h[(i, a + b + j)] -= delta_cc[(i - a - b, j)] * rhoc[j]; } } } // Newton step // avoid stepping to negative values for x (see Michelsen 2006) let delta_x = LU::new(h)?.solve(&g); x.iter_mut().zip(&delta_x).for_each(|(x, &delta_x)| { if delta_x.re() < x.re() * 0.8 { *x -= delta_x } else { *x *= 0.2 } }); // check convergence Ok(g.map(|g| g.re()).norm() < tol) } } #[cfg(test)] #[cfg(feature = "pcsaft")] mod tests_pcsaft { use super::*; use crate::hard_sphere::HardSphereProperties; use crate::pcsaft::PcSaftRecord; use crate::pcsaft::parameters::utils::water_parameters; use crate::pcsaft::parameters::{PcSaftAssociationRecord, PcSaftPars}; use approx::assert_relative_eq; use feos_core::parameter::{ AssociationRecord, BinaryAssociationRecord, BinaryRecord, Parameters, PureRecord, }; use nalgebra::{dmatrix, dvector}; fn pcsaft() -> PcSaftRecord { PcSaftRecord::new(1.2, 3.5, 245.0, 2.3, 4.4, None, None, None) } fn record( id: &'static str, kappa_ab: f64, epsilon_k_ab: f64, na: f64, nb: f64, ) -> AssociationRecord<PcSaftAssociationRecord> { let pcsaft = PcSaftAssociationRecord::new(kappa_ab, epsilon_k_ab); AssociationRecord::with_id(id.into(), Some(pcsaft), na, nb, 0.0) } fn binary_record( id1: &'static str, id2: &'static str, kappa_ab: f64, epsilon_k_ab: f64, ) -> BinaryAssociationRecord<PcSaftAssociationRecord> { let pcsaft = PcSaftAssociationRecord::new(kappa_ab, epsilon_k_ab); BinaryAssociationRecord { id1: id1.into(), id2: id2.into(), parameters: pcsaft, } } #[test] fn test_binary_parameters() -> FeosResult<()> { let comp1 = vec![record("0", 0.1, 2500., 1.0, 1.0)]; let comp2 = vec![record("0", 0.2, 1500., 1.0, 1.0)]; let comp3 = vec![record("0", 0.3, 500., 0.0, 1.0)]; let comp4 = vec![ record("0", 0.3, 1000., 1.0, 0.0), record("1", 0.3, 2000., 0.0, 1.0), ]; let pure_records = [comp1, comp2, comp3, comp4] .map(|r| PureRecord::with_association(Default::default(), 0.0, pcsaft(), r)) .to_vec(); let binary = [ ([0, 1], binary_record("0", "0", 3.5, 1234.)), ([0, 2], binary_record("0", "0", 3.5, 3140.)), ([1, 3], binary_record("0", "1", 3.5, 3333.)), ]; let binary_records = binary .map(|([i, j], br)| BinaryRecord::with_association(i, j, Some(()), vec![br])) .to_vec(); let params = Parameters::new(pure_records, binary_records)?; let [epsilon_k_ab, kappa_ab] = params .collate_ab(|p| [p.epsilon_k_ab, p.kappa_ab]) .map(|p| p.map(Option::unwrap)); println!("{epsilon_k_ab}"); println!("{kappa_ab}"); let epsilon_k_ab_ref = dmatrix![ 2500., 1234., 3140., 2250.; 1234., 1500., 1000., 3333.; 1750., 1250., 750., 1500.; ]; assert_eq!(epsilon_k_ab, epsilon_k_ab_ref); Ok(()) } #[test] fn test_induced_association() -> FeosResult<()> { let comp1 = vec![record("", 0.1, 2500., 1.0, 1.0)]; let comp2 = vec![record("", 0.1, -500., 0.0, 1.0)]; let comp3 = vec![record("", 0.0, 0.0, 0.0, 1.0)]; let [pr1, pr2, pr3] = [comp1, comp2, comp3] .map(|r| PureRecord::with_association(Default::default(), 0.0, pcsaft(), r)); let br = vec![binary_record("", "", 0.1, 1000.)]; let params1 = Parameters::new_binary([pr1.clone(), pr2], Some(()), vec![])?; let params2 = Parameters::new_binary([pr1, pr3], Some(()), br)?; let [epsilon_k_ab1, kappa_ab1] = params1 .collate_ab(|p| [p.epsilon_k_ab, p.kappa_ab]) .map(|p| p.map(Option::unwrap)); let [epsilon_k_ab2, kappa_ab2] = params2 .collate_ab(|p| [p.epsilon_k_ab, p.kappa_ab]) .map(|p| p.map(Option::unwrap)); println!("{epsilon_k_ab1}"); println!("{epsilon_k_ab2}"); println!("{kappa_ab1}"); println!("{kappa_ab2}"); assert_eq!(epsilon_k_ab1, epsilon_k_ab2); assert_eq!(kappa_ab1, kappa_ab2); Ok(()) } #[test] fn helmholtz_energy() { let parameters = water_parameters(1.0); let params = PcSaftPars::new(&parameters); let assoc = Association::new(50, 1e-10); let t = 350.0; let v = 41.248289328513216; let n = 1.23; let s = StateHD::new(t, v, &dvector![n]); let d = params.hs_diameter(t); let a_rust = assoc.helmholtz_energy_density(&params, &parameters.association, &s, &d) * v / n; assert_relative_eq!(a_rust, -4.229878997054543, epsilon = 1e-10); } #[test] fn helmholtz_energy_cross() { let parameters = water_parameters(1.0); let params = PcSaftPars::new(&parameters); let assoc = Association::new(50, 1e-10); let t = 350.0; let v = 41.248289328513216; let n = 1.23; let s = StateHD::new(t, v, &dvector![n]); let d = params.hs_diameter(t); let a_rust = assoc.helmholtz_energy_density(&params, &parameters.association, &s, &d) * v / n; assert_relative_eq!(a_rust, -4.229878997054543, epsilon = 1e-10); } #[test] fn helmholtz_energy_cross_3b() -> FeosResult<()> { let parameters = water_parameters(2.0); let params = PcSaftPars::new(&parameters); let assoc = Association::new(50, 1e-10); let cross_assoc = Association::new_cross_association(50, 1e-10); let t = 350.0; let v = 41.248289328513216; let n = 1.23; let s = StateHD::new(t, v, &dvector![n]); let d = params.hs_diameter(t); let a_assoc = assoc.helmholtz_energy_density(&params, &parameters.association, &s, &d); let a_cross_assoc = cross_assoc.helmholtz_energy_density(&params, &parameters.association, &s, &d); assert_relative_eq!(a_assoc, a_cross_assoc, epsilon = 1e-10); Ok(()) } } #[cfg(test)] #[cfg(feature = "gc_pcsaft")] mod tests_gc_pcsaft { use super::*; use crate::gc_pcsaft::{GcPcSaftEosParameters, eos::parameter::test::*}; use approx::assert_relative_eq; use feos_core::ReferenceSystem; use nalgebra::dvector; use num_dual::Dual64; use quantity::{METER, MOL, PASCAL, Pressure}; #[test] fn test_assoc_propanol() { let parameters = propanol(); let params = GcPcSaftEosParameters::new(&parameters); let contrib = Association::new(50, 1e-10); let temperature = 300.0; let volume = Dual64::from_re(METER.powi::<3>().to_reduced()).derivative(); let moles = Dual64::from_re((1.5 * MOL).to_reduced()); let molar_volume = volume / moles; let state = StateHD::new( Dual64::from_re(temperature), molar_volume, &dvector![Dual64::from_re(1.0)], ); let diameter = params.hs_diameter(state.temperature); let pressure = Pressure::from_reduced( -(contrib.helmholtz_energy_density( &params, &parameters.association, &state, &diameter, ) * volume) .eps * temperature, ); assert_relative_eq!(pressure, -3.6819598891967344 * PASCAL, max_relative = 1e-10); } #[test] fn test_cross_assoc_propanol() { let parameters = propanol(); let params = GcPcSaftEosParameters::new(&parameters); let contrib = Association::new_cross_association(50, 1e-10); let temperature = 300.0; let volume = Dual64::from_re(METER.powi::<3>().to_reduced()).derivative(); let moles = Dual64::from_re((1.5 * MOL).to_reduced()); let molar_volume = volume / moles; let state = StateHD::new( Dual64::from_re(temperature), molar_volume, &dvector![Dual64::from_re(1.0)], ); let diameter = params.hs_diameter(state.temperature); let pressure = Pressure::from_reduced( -(contrib.helmholtz_energy_density( &params, &parameters.association, &state, &diameter, ) * volume) .eps * temperature, ); assert_relative_eq!(pressure, -3.6819598891967344 * PASCAL, max_relative = 1e-10); } #[test] fn test_cross_assoc_ethanol_propanol() { let parameters = ethanol_propanol(false); let params = GcPcSaftEosParameters::new(&parameters); let contrib = Association::new(50, 1e-10); let temperature = 300.0; let volume = Dual64::from_re(METER.powi::<3>().to_reduced()).derivative(); let moles = (dvector![1.5, 2.5] * MOL).to_reduced().map(Dual64::from_re); let total_moles = moles.sum(); let molar_volume = volume / total_moles; let molefracs = moles / total_moles; let state = StateHD::new(Dual64::from_re(temperature), molar_volume, &molefracs); let diameter = params.hs_diameter(state.temperature); let pressure = Pressure::from_reduced( -(contrib.helmholtz_energy_density( &params, &parameters.association, &state, &diameter, ) * volume) .eps * temperature, ); assert_relative_eq!(pressure, -26.105606376765632 * PASCAL, max_relative = 1e-10); } }
Rust
3D
feos-org/feos
crates/feos/src/association/dft.rs
.rs
12,376
342
use super::*; use feos_core::FeosResult; use feos_core::parameter::GenericParameters; use feos_dft::{FunctionalContribution, WeightFunction, WeightFunctionInfo, WeightFunctionShape}; use ndarray::{Array1, Array2, ArrayBase, ArrayView2, Axis, Data, Ix1, Slice}; use num_dual::DualNum; use std::f64::consts::PI; use std::ops::MulAssign; pub const N0_CUTOFF: f64 = 1e-9; impl Association { /// Association strength for functional of Yu and Wu with xi parameter for inhomogeneity. /// /// Uses the contact value of hard-sphere pair correlation function and model-specific /// implementations for the bonding volume. #[expect(clippy::too_many_arguments)] fn yu_wu_association_strength<A: AssociationStrength, D: DualNum<f64> + Copy>( &self, parameters: &AssociationParameters<A::Record>, model: &A, temperature: D, diameter: &DVector<D>, n2: D, n3i: D, xi: D, ) -> [DMatrix<D>; 2] { let p = parameters; let mut delta_ab = DMatrix::zeros(p.sites_a.len(), p.sites_b.len()); for b in &p.binary_ab { let [i, j] = [b.id1, b.id2]; let di = diameter[p.sites_a[i].assoc_comp]; let dj = diameter[p.sites_b[j].assoc_comp]; let k = di * dj / (di + dj) * (n2 * n3i); delta_ab[(i, j)] = n3i * (k * xi * (k / 18.0 + 0.5) + 1.0) * model.association_strength_ij( temperature, p.sites_a[i].assoc_comp, p.sites_b[j].assoc_comp, &b.model_record, ) } let mut delta_cc = DMatrix::zeros(p.sites_c.len(), p.sites_c.len()); for b in &p.binary_cc { let [i, j] = [b.id1, b.id2]; let di = diameter[p.sites_c[i].assoc_comp]; let dj = diameter[p.sites_c[j].assoc_comp]; let k = di * dj / (di + dj) * (n2 * n3i); delta_cc[(i, j)] = n3i * (k * xi * (k / 18.0 + 0.5) + 1.0) * model.association_strength_ij( temperature, p.sites_c[i].assoc_comp, p.sites_c[j].assoc_comp, &b.model_record, ) } [delta_ab, delta_cc] } } /// Implementation of the association Helmholtz energy functional of Yu and Wu. /// /// [Yang-Xin Yu and Jianzhong Wu (2002)](https://aip.scitation.org/doi/abs/10.1063/1.1463435) /// /// # Note /// /// Uses the contact value of the hard-sphere pair correlation function and model-specific /// implementations for the bonding volume. pub struct YuWuAssociationFunctional<'a, A: AssociationStrength> { model: &'a A, association_parameters: &'a AssociationParameters<A::Record>, association: Association, } impl<'a, A: AssociationStrength> YuWuAssociationFunctional<'a, A> { pub fn new<P, B, Bo, C, Data>( model: &'a A, parameters: &'a GenericParameters<P, B, A::Record, Bo, C, Data>, association: Option<Association>, ) -> Option<Self> { association.map(|a| Self { model, association_parameters: &parameters.association, association: a, }) } } impl<'a, A: AssociationStrength + Sync + Send> FunctionalContribution for YuWuAssociationFunctional<'a, A> where A::Record: Sync + Send, { fn name(&self) -> &'static str { "Association" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { let p = self.model; let r = p.hs_diameter(temperature) * N::from(0.5); let [_, _, _, c3] = p.geometry_coefficients(temperature); WeightFunctionInfo::new(p.component_index().into_owned().into(), false) .add( WeightFunction::new_scaled(r.clone(), WeightFunctionShape::Delta), false, ) .add( WeightFunction { prefactor: c3.clone(), kernel_radius: r.clone(), shape: WeightFunctionShape::DeltaVec, }, false, ) .add( WeightFunction { prefactor: c3, kernel_radius: r, shape: WeightFunctionShape::Theta, }, true, ) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, weighted_densities: ArrayView2<N>, ) -> FeosResult<Array1<N>> { // number of segments let n = self.association_parameters.component_index.len(); // number of dimensions let dim = (weighted_densities.shape()[0] - 1) / n - 1; // weighted densities let n0i = weighted_densities.slice_axis(Axis(0), Slice::new(0, Some(n as isize), 1)); let n2vi: Vec<_> = (0..dim) .map(|i| { weighted_densities.slice_axis( Axis(0), Slice::new((n * (i + 1)) as isize, Some((n * (i + 2)) as isize), 1), ) }) .collect(); let n3 = weighted_densities.index_axis(Axis(0), n * (dim + 1)); // calculate rho0 let [_, _, c2, _] = self.model.geometry_coefficients(temperature); let diameter = self.model.hs_diameter(temperature); let mut n2i = n0i.to_owned(); for (i, mut n2i) in n2i.outer_iter_mut().enumerate() { n2i.mul_assign(diameter[i].powi(2) * c2[i] * PI); } let mut rho0: Array2<N> = (n2vi .iter() .fold(Array2::zeros(n0i.raw_dim()), |acc, n2vi| acc + n2vi * n2vi) / -(&n2i * &n2i) + 1.0) * n0i; rho0.iter_mut().zip(&n0i).for_each(|(rho0, &n0i)| { if n0i.re() < N0_CUTOFF { *rho0 = n0i; } }); // calculate xi let n2v: Vec<_> = n2vi.iter().map(|n2vi| n2vi.sum_axis(Axis(0))).collect(); let n2 = n2i.sum_axis(Axis(0)); let mut xi = n2v .iter() .fold(Array1::zeros(n2.raw_dim()), |acc, n2v| acc + n2v * n2v) / -(&n2 * &n2) + 1.0; xi.iter_mut() .zip(&n0i.sum_axis(Axis(0))) .for_each(|(xi, &n0i)| { if n0i.re() < N0_CUTOFF { *xi = N::one(); } }); // auxiliary variables let n3i = n3.mapv(|n3| (-n3 + 1.0).recip()); self._helmholtz_energy_density(temperature, &rho0, &n2, &n3i, &xi) } } impl<'a, A: AssociationStrength> YuWuAssociationFunctional<'a, A> { pub fn _helmholtz_energy_density<N: DualNum<f64> + Copy, S: Data<Elem = N>>( &self, temperature: N, rho0: &Array2<N>, n2: &ArrayBase<S, Ix1>, n3i: &Array1<N>, xi: &Array1<N>, ) -> FeosResult<Array1<N>> { let a = &self.association_parameters; let t = temperature; let d = self.model.hs_diameter(t); match ( a.sites_a.len() * a.sites_b.len(), a.sites_c.len(), self.association.force_cross_association, ) { (0, 0, _) => Ok(Array1::zeros(n3i.len())), (1, 0, false) => { let params = a.binary_ab.first().map(|r| &r.model_record); Ok(self.helmholtz_energy_density_ab_analytic(params, t, rho0, &d, n2, n3i, xi)) } (0, 1, false) => { let params = a.binary_cc.first().map(|r| &r.model_record); Ok(self.helmholtz_energy_density_cc_analytic(params, t, rho0, &d, n2, n3i, xi)) } (1, 1, false) => { let params_ab = a.binary_ab.first().map(|r| &r.model_record); let params_cc = a.binary_cc.first().map(|r| &r.model_record); Ok( self.helmholtz_energy_density_ab_analytic(params_ab, t, rho0, &d, n2, n3i, xi) + self.helmholtz_energy_density_cc_analytic( params_cc, t, rho0, &d, n2, n3i, xi, ), ) } _ => { let mut x = DVector::from_element(a.sites_a.len() + a.sites_b.len(), 0.2); let (assoc_comp_ab, n_ab): (Vec<_>, Vec<_>) = a .sites_a .iter() .chain(a.sites_b.iter()) .map(|s| (s.assoc_comp, s.n)) .unzip(); let rhoab = Array2::from_shape_fn((x.len(), n3i.len()), |(i, j)| { rho0[(assoc_comp_ab[i], j)] * n_ab[i] }); rhoab .axis_iter(Axis(1)) .zip(n2.iter()) .zip(n3i.iter()) .zip(xi.iter()) .map(|(((rho, &n2), &n3i), &xi)| { let [delta_ab, delta_cc] = self.association.yu_wu_association_strength( self.association_parameters, self.model, t, &d, n2, n3i, xi, ); let rho = DVector::from(rho.to_vec()); self.association.helmholtz_energy_density_cross_association( &rho, &delta_ab, &delta_cc, Some(&mut x), ) }) .collect() } } } #[expect(clippy::too_many_arguments)] fn helmholtz_energy_density_ab_analytic<N: DualNum<f64> + Copy, S: Data<Elem = N>>( &self, parameters: Option<&A::Record>, temperature: N, rho0: &Array2<N>, diameter: &DVector<N>, n2: &ArrayBase<S, Ix1>, n3i: &Array1<N>, xi: &Array1<N>, ) -> Array1<N> { let a = &self.association_parameters; let Some(par) = parameters else { return Array1::zeros(xi.len()); }; // site densities let i = a.sites_a[0].assoc_comp; let j = a.sites_b[0].assoc_comp; let rhoa = &rho0.index_axis(Axis(0), i) * a.sites_a[0].n; let rhob = &rho0.index_axis(Axis(0), j) * a.sites_b[0].n; // association strength let di = diameter[i]; let dj = diameter[j]; let k = n2 * n3i * (di * dj / (di + dj)); let delta = (((&k / 18.0 + 0.5) * &k * xi + 1.0) * n3i) * self.model.association_strength_ij(temperature, 0, 0, par); // no cross association, two association sites let aux = &delta * (&rhob - &rhoa) + 1.0; let xa = ((&aux * &aux + &delta * &rhoa * 4.0).map(N::sqrt) + &aux).map(N::recip) * 2.0; let aux = -aux + 2.0; let xb = ((&aux * &aux + delta * &rhob * 4.0).map(N::sqrt) + aux).map(N::recip) * 2.0; let f = |x: N| x.ln() - x * 0.5 + 0.5; rhoa * xa.mapv(f) + rhob * xb.mapv(f) } #[expect(clippy::too_many_arguments)] fn helmholtz_energy_density_cc_analytic<N: DualNum<f64> + Copy, S: Data<Elem = N>>( &self, parameters: Option<&A::Record>, temperature: N, rho0: &Array2<N>, diameter: &DVector<N>, n2: &ArrayBase<S, Ix1>, n3i: &Array1<N>, xi: &Array1<N>, ) -> Array1<N> { let a = &self.association_parameters; let Some(par) = parameters else { return Array1::zeros(xi.len()); }; // site densities let i = a.sites_c[0].assoc_comp; let rhoc = &rho0.index_axis(Axis(0), i) * a.sites_c[0].n; // association strength let di = diameter[i]; let k = n2 * n3i * (di * 0.5); let delta = (((&k / 18.0 + 0.5) * &k * xi + 1.0) * n3i) * self.model.association_strength_ij(temperature, 0, 0, par); // no cross association, two association sites let xc = ((delta * 4.0 * &rhoc + 1.0).map(N::sqrt) + 1.0).map(N::recip) * 2.0; let f = |x: N| x.ln() - x * 0.5 + 0.5; rhoc * xc.mapv(f) } }
Rust
3D
feos-org/feos
crates/feos/src/hard_sphere/mod.rs
.rs
5,765
138
//! Generic implementation of the hard-sphere contribution //! that can be used across models. use feos_core::StateHD; use nalgebra::DVector; use num_dual::DualNum; use std::borrow::Cow; use std::f64::consts::FRAC_PI_6; #[cfg(feature = "dft")] mod dft; #[cfg(feature = "dft")] pub use dft::{FMTContribution, FMTFunctional, FMTVersion, HardSphereParameters}; /// Different monomer shapes for FMT and BMCSL. pub enum MonomerShape<'a, D> { /// For spherical monomers, the number of components. Spherical(usize), /// For non-spherical molecules in a homosegmented approach, the /// chain length parameter $m$. NonSpherical(DVector<D>), /// For non-spherical molecules in a heterosegmented approach, /// the geometry factors for every segment and the component /// index for every segment. Heterosegmented([DVector<D>; 4], &'a DVector<usize>), } /// Properties of (generalized) hard sphere systems. pub trait HardSphereProperties { /// The [MonomerShape] used in the model. fn monomer_shape<D: DualNum<f64> + Copy>(&self, temperature: D) -> MonomerShape<'_, D>; /// The temperature dependent hard-sphere diameters of every segment. fn hs_diameter<D: DualNum<f64> + Copy>(&self, temperature: D) -> DVector<D>; /// For every segment, the index of the component that it is on. fn component_index(&self) -> Cow<'_, [usize]> { match self.monomer_shape(1.0) { MonomerShape::Spherical(n) => Cow::Owned((0..n).collect()), MonomerShape::NonSpherical(m) => Cow::Owned((0..m.len()).collect()), MonomerShape::Heterosegmented(_, component_index) => { Cow::Borrowed(component_index.as_slice()) } } } /// The geometry coefficients $C_{k,\alpha}$ for every segment. fn geometry_coefficients<D: DualNum<f64> + Copy>(&self, temperature: D) -> [DVector<D>; 4] { match self.monomer_shape(temperature) { MonomerShape::Spherical(n) => { let m = DVector::from_element(n, D::from(1.0)); [m.clone(), m.clone(), m.clone(), m] } MonomerShape::NonSpherical(m) => [m.clone(), m.clone(), m.clone(), m], MonomerShape::Heterosegmented(g, _) => g, } } /// The packing fractions $\zeta_k$. fn zeta<D: DualNum<f64> + Copy, const N: usize>( &self, temperature: D, partial_density: &DVector<D>, k: [i32; N], ) -> [D; N] { let component_index = self.component_index(); let geometry_coefficients = self.geometry_coefficients(temperature); let diameter = self.hs_diameter(temperature); let mut zeta = [D::zero(); N]; for i in 0..diameter.len() { for (z, &k) in zeta.iter_mut().zip(k.iter()) { *z += partial_density[component_index[i]] * diameter[i].powi(k) * (geometry_coefficients[k as usize][i] * FRAC_PI_6); } } zeta } } /// Implementation of the BMCSL equation of state for hard-sphere mixtures. /// /// This structure provides an implementation of the Boublík-Mansoori-Carnahan-Starling-Leland (BMCSL) equation of state ([Boublík, 1970](https://doi.org/10.1063/1.1673824), [Mansoori et al., 1971](https://doi.org/10.1063/1.1675048)) that is often used as reference contribution in SAFT equations of state. The implementation is generalized to allow the description of non-sperical or fused-sphere reference fluids. /// /// The reduced Helmholtz energy is calculated according to /// $$\frac{\beta A}{V}=\frac{6}{\pi}\left(\frac{3\zeta_1\zeta_2}{1-\zeta_3}+\frac{\zeta_2^3}{\zeta_3\left(1-\zeta_3\right)^2}+\left(\frac{\zeta_2^3}{\zeta_3^2}-\zeta_0\right)\ln\left(1-\zeta_3\right)\right)$$ /// with the packing fractions /// $$\zeta_k=\frac{\pi}{6}\sum_\alpha C_{k,\alpha}\rho_\alpha d_\alpha^k,~~~~~~~~k=0\ldots 3.$$ /// /// The geometry coefficients $C_{k,\alpha}$ and the segment diameters $d_\alpha$ are specified via the [HardSphereProperties] trait. pub struct HardSphere; impl HardSphere { /// Returns the Helmholtz energy, packing fractions, and temperature dependent diameters without redundant calculations. #[inline] pub fn helmholtz_energy_density_and_properties< D: DualNum<f64> + Copy, P: HardSphereProperties, >( &self, parameters: &P, state: &StateHD<D>, ) -> (D, [D; 4], DVector<D>) { let p = parameters; let diameter = p.hs_diameter(state.temperature); let component_index = p.component_index(); let geometry_coefficients = p.geometry_coefficients(state.temperature); let mut zeta = [D::zero(); 4]; for i in 0..diameter.len() { for (z, &k) in zeta.iter_mut().zip([0, 1, 2, 3].iter()) { *z += state.molefracs[component_index[i]] * diameter[i].powi(k) * (geometry_coefficients[k as usize][i] * FRAC_PI_6); } } let zeta_23 = zeta[2] / zeta[3]; let density = state.partial_density.sum(); zeta.iter_mut().for_each(|z| *z *= density); let frac_1mz3 = -(zeta[3] - 1.0).recip(); let a = (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) } #[inline] pub fn helmholtz_energy_density<D: DualNum<f64> + Copy, P: HardSphereProperties>( &self, parameters: &P, state: &StateHD<D>, ) -> D { self.helmholtz_energy_density_and_properties(parameters, state) .0 } }
Rust
3D
feos-org/feos
crates/feos/src/hard_sphere/dft.rs
.rs
15,447
376
use feos_core::{FeosResult, ResidualDyn, StateHD, Subset}; use feos_dft::adsorption::FluidParameters; use feos_dft::solvation::PairPotential; use feos_dft::{ FunctionalContribution, HelmholtzEnergyFunctional, HelmholtzEnergyFunctionalDyn, MoleculeShape, WeightFunction, WeightFunctionInfo, WeightFunctionShape, }; use nalgebra::DVector; use ndarray::*; use num_dual::DualNum; use std::f64::consts::PI; use super::{HardSphereProperties, MonomerShape}; const PI36M1: f64 = 1.0 / (36.0 * PI); const N3_CUTOFF: f64 = 1e-5; /// Different versions of fundamental measure theory. #[derive(Clone, Copy, PartialEq)] pub enum FMTVersion { /// White Bear ([Roth et al., 2002](https://doi.org/10.1088/0953-8984/14/46/313)) or modified ([Yu and Wu, 2002](https://doi.org/10.1063/1.1520530)) fundamental measure theory WhiteBear, /// Scalar fundamental measure theory by [Kierlik and Rosinberg, 1990](https://doi.org/10.1103/PhysRevA.42.3382) KierlikRosinberg, /// Anti-symmetric White Bear fundamental measure theory ([Rosenfeld et al., 1997](https://doi.org/10.1103/PhysRevE.55.4245)) and SI of ([Kessler et al., 2021](https://doi.org/10.1016/j.micromeso.2021.111263)) AntiSymWhiteBear, } /// The [FunctionalContribution] for the hard sphere functional. /// /// The struct provides an implementation of different variants of fundamental measure theory ([Rosenfeld, 1989](https://doi.org/10.1103/PhysRevLett.63.980)). Currently, only variants that are consistent with the BMCSL equation of state for hard-sphere mixtures are considered (exluding, e.g., the original Rosenfeld and White-Bear II variants). /// /// The Helmholtz energy density is calculated according to /// $$\beta f=-n_0\ln\left(1-n_3\right)+\frac{n_{12}}{1-n_3}+\frac{1}{36\pi}n_2n_{22}f_3(n_3)$$ /// The expressions for $n_{12}$ and $n_{22}$ depend on the [FMTVersion]. /// /// |[FMTVersion]|$n_{12}$|$n_{22}$| /// |-|:-:|:-:| /// |WhiteBear|$n_1n_2-\vec n_1\cdot\vec n_2$|$n_2^2-3\vec n_2\cdot\vec n_2$| /// |KierlikRosinberg|$n_1n_2$|$n_2^2$| /// |AntiSymWhiteBear|$n_1n_2-\vec n_1\cdot\vec n_2$|$n_2^2\left(1-\frac{\vec n_2\cdot\vec n_2}{n_2^2}\right)^3$| /// /// The value of $f(n_3)$ numerically diverges for small $n_3$. Therefore, it is approximated with a Taylor expansion. /// $$f_3=\begin{cases}\frac{n_3+\left(1-n_3\right)^2\ln\left(1-n_3\right)}{n_3^2\left(1-n_3\right)^2}&\text{if }n_3>10^{-5}\\\\ /// \frac{3}{2}+\frac{8}{3}n_3+\frac{15}{4}n_3^2+\frac{24}{5}n_3^3+\frac{35}{6}n_3^4&\text{else}\end{cases}$$ /// /// The weighted densities $n_k(\mathbf{r})$ are calculated by convolving the density profiles $\rho_\alpha(\mathbf{r})$ with weight functions $\omega_k^\alpha(\mathbf{r})$ /// $$n_k(\mathbf{r})=\sum_\alpha\int\rho_\alpha(\mathbf{r}\')\omega_k^\alpha(\mathbf{r}-\mathbf{r}\')\mathrm{d}\mathbf{r}\'$$ /// /// The weight functions differ between the different [FMTVersion]s. /// /// ||WhiteBear/AntiSymWhiteBear|KierlikRosinberg| /// |-|:-:|:-:| /// |$\omega_0^\alpha(\mathbf{r})$|$\frac{C_{0,\alpha}}{\pi\sigma_\alpha^2}\\,\delta\\!\left(\frac{d_\alpha}{2}-\|\mathbf{r}\|\right)$|$C_{0,\alpha}\left(-\frac{1}{8\pi}\\,\delta\'\'\\!\left(\frac{d_\alpha}{2}-\|\mathbf{r}\|\right)+\frac{1}{2\pi\|\mathbf{r}\|}\\,\delta\'\\!\left(\frac{d_\alpha}{2}-\|\mathbf{r}\|\right)\right)$| /// |$\omega_1^\alpha(\mathbf{r})$|$\frac{C_{1,\alpha}}{2\pi\sigma_\alpha}\\,\delta\\!\left(\frac{d_\alpha}{2}-\|\mathbf{r}\|\right)$|$\frac{C_{1,\alpha}}{8\pi}\\,\delta\'\\!\left(\frac{d_\alpha}{2}-\|\mathbf{r}\|\right)$| /// |$\omega_2^\alpha(\mathbf{r})$|$C_{2,\alpha}\\,\delta\\!\left(\frac{d_\alpha}{2}-\|\mathbf{r}\|\right)$|$C_{2,\alpha}\\,\delta\\!\left(\frac{d_\alpha}{2}-\|\mathbf{r}\|\right)$| /// |$\omega_3^\alpha(\mathbf{r})$|$C_{3,\alpha}\\,\Theta\\!\left(\frac{d_\alpha}{2}-\|\mathbf{r}\|\right)$|$C_{3,\alpha}\\,\Theta\\!\left(\frac{d_\alpha}{2}-\|\mathbf{r}\|\right)$| /// |$\vec\omega_1^\alpha(\mathbf{r})$|$C_{3,\alpha}\frac{\mathbf{r}}{2\pi\sigma_\alpha\|\mathbf{r}\|}\\,\delta\\!\left(\frac{d_\alpha}{2}-\|\mathbf{r}\|\right)$|-| /// |$\vec\omega_2^\alpha(\mathbf{r})$|$C_{3,\alpha}\frac{\mathbf{r}}{\|\mathbf{r}\|}\\,\delta\\!\left(\frac{d_\alpha}{2}-\|\mathbf{r}\|\right)$|-| /// /// The geometry coefficients $C_{k,\alpha}$ and the segment diameters $d_\alpha$ are specified via the [HardSphereProperties] trait. pub struct FMTContribution<'p, P> { pub properties: &'p P, version: FMTVersion, } impl<'p, P> FMTContribution<'p, P> { pub fn new(properties: &'p P, version: FMTVersion) -> Self { Self { properties, version, } } } impl<'p, P: HardSphereProperties + Send + Sync> FunctionalContribution for FMTContribution<'p, P> { fn name(&self) -> &'static str { match self.version { FMTVersion::WhiteBear => "FMT functional (WB)", FMTVersion::KierlikRosinberg => "FMT functional (KR)", FMTVersion::AntiSymWhiteBear => "FMT functional (AntiSymWB)", } } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { let r = self.properties.hs_diameter(temperature) * N::from(0.5); let [c0, c1, c2, c3] = self.properties.geometry_coefficients(temperature); match (self.version, r.len()) { (FMTVersion::WhiteBear | FMTVersion::AntiSymWhiteBear, 1) => WeightFunctionInfo::new( self.properties.component_index().into_owned().into(), false, ) .extend( vec![ WeightFunctionShape::Delta, WeightFunctionShape::Theta, WeightFunctionShape::DeltaVec, ] .into_iter() .zip([c2, c3.clone(), c3]) .map(|(s, c)| WeightFunction { prefactor: c, kernel_radius: r.clone(), shape: s, }) .collect(), false, ), (FMTVersion::WhiteBear | FMTVersion::AntiSymWhiteBear, _) => WeightFunctionInfo::new( self.properties.component_index().into_owned().into(), false, ) .add( WeightFunction { prefactor: c0.zip_map(&r, |c, r| r.powi(-2) * c / (4.0 * PI)), kernel_radius: r.clone(), shape: WeightFunctionShape::Delta, }, true, ) .add( WeightFunction { prefactor: c1.zip_map(&r, |c, r| r.recip() * c / (4.0 * PI)), kernel_radius: r.clone(), shape: WeightFunctionShape::Delta, }, true, ) .add( WeightFunction { prefactor: c2, kernel_radius: r.clone(), shape: WeightFunctionShape::Delta, }, true, ) .add( WeightFunction { prefactor: c3.clone(), kernel_radius: r.clone(), shape: WeightFunctionShape::Theta, }, true, ) .add( WeightFunction { prefactor: c3.zip_map(&r, |c, r| r.recip() * c / (4.0 * PI)), kernel_radius: r.clone(), shape: WeightFunctionShape::DeltaVec, }, true, ) .add( WeightFunction { prefactor: c3, kernel_radius: r, shape: WeightFunctionShape::DeltaVec, }, true, ), (FMTVersion::KierlikRosinberg, _) => WeightFunctionInfo::new( self.properties.component_index().into_owned().into(), false, ) .extend( vec![ WeightFunctionShape::KR0, WeightFunctionShape::KR1, WeightFunctionShape::Delta, WeightFunctionShape::Theta, ] .into_iter() .zip(self.properties.geometry_coefficients(temperature)) .map(|(s, c)| WeightFunction { prefactor: c, kernel_radius: r.clone(), shape: s, }) .collect(), true, ), } } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, weighted_densities: ArrayView2<N>, ) -> FeosResult<Array1<N>> { let pure_component_weighted_densities = matches!( self.version, FMTVersion::WhiteBear | FMTVersion::AntiSymWhiteBear ) && self.properties.component_index().len() == 1; // scalar weighted densities let (n2, n3) = if pure_component_weighted_densities { ( weighted_densities.index_axis(Axis(0), 0), weighted_densities.index_axis(Axis(0), 1), ) } else { ( weighted_densities.index_axis(Axis(0), 2), weighted_densities.index_axis(Axis(0), 3), ) }; let (n0, n1) = if pure_component_weighted_densities { let r = self.properties.hs_diameter(temperature)[0] * 0.5; ( n2.mapv(|n2| n2 / (r * r * 4.0 * PI)), n2.mapv(|n2| n2 / (r * 4.0 * PI)), ) } else { ( weighted_densities.index_axis(Axis(0), 0).to_owned(), weighted_densities.index_axis(Axis(0), 1).to_owned(), ) }; // vector weighted densities let (n1n2, n2n2) = match self.version { FMTVersion::WhiteBear | FMTVersion::AntiSymWhiteBear => { let (n1v, n2v) = if pure_component_weighted_densities { let r = self.properties.hs_diameter(temperature)[0] * 0.5; let n2v = weighted_densities.slice_axis(Axis(0), Slice::new(2, None, 1)); (n2v.mapv(|n2v| n2v / (r * 4.0 * PI)), n2v) } else { let dim = ((weighted_densities.shape()[0] - 4) / 2) as isize; ( weighted_densities .slice_axis(Axis(0), Slice::new(4, Some(4 + dim), 1)) .to_owned(), weighted_densities .slice_axis(Axis(0), Slice::new(4 + dim, Some(4 + 2 * dim), 1)), ) }; match self.version { FMTVersion::WhiteBear => ( &n1 * &n2 - (&n1v * &n2v).sum_axis(Axis(0)), &n2 * &n2 - (&n2v * &n2v).sum_axis(Axis(0)) * 3.0, ), FMTVersion::AntiSymWhiteBear => { let mut xi2 = (&n2v * &n2v).sum_axis(Axis(0)) / n2.map(|n| n.powi(2)); xi2.iter_mut().for_each(|x| { if x.re() > 1.0 { *x = N::one() } }); ( &n1 * &n2 - (&n1v * &n2v).sum_axis(Axis(0)), &n2 * &n2 * xi2.mapv(|x| (-x + 1.0).powi(3)), ) } _ => unreachable!(), } } FMTVersion::KierlikRosinberg => (&n1 * &n2, &n2 * &n2), }; // auxiliary variables let ln31 = n3.mapv(|n3| (-n3).ln_1p()); let n3rec = n3.mapv(|n3| n3.recip()); let n3m1 = n3.mapv(|n3| -n3 + 1.0); let n3m1rec = n3m1.mapv(|n3m1| n3m1.recip()); // use Taylor expansion for f3 at low densities to avoid numerical issues let mut f3 = (&n3m1 * &n3m1 * &ln31 + n3) * &n3rec * n3rec * &n3m1rec * &n3m1rec; f3.iter_mut().zip(n3).for_each(|(f3, &n3)| { if n3.re() < N3_CUTOFF { *f3 = (((n3 * 35.0 / 6.0 + 4.8) * n3 + 3.75) * n3 + 8.0 / 3.0) * n3 + 1.5; } }); Ok(-(&n0 * &ln31) + n1n2 * &n3m1rec + n2n2 * n2 * PI36M1 * f3) } } pub struct HardSphereParameters { sigma: DVector<f64>, } impl HardSphereProperties for HardSphereParameters { fn monomer_shape<N>(&self, _: N) -> MonomerShape<'_, N> { MonomerShape::Spherical(self.sigma.len()) } fn hs_diameter<N: DualNum<f64>>(&self, _: N) -> DVector<N> { self.sigma.map(N::from) } } /// [HelmholtzEnergyFunctional] for hard sphere systems. pub struct FMTFunctional { properties: HardSphereParameters, version: FMTVersion, } impl FMTFunctional { pub fn new(sigma: DVector<f64>, version: FMTVersion) -> Self { let properties = HardSphereParameters { sigma }; Self { properties, version, } } } impl Subset for FMTFunctional { fn subset(&self, component_list: &[usize]) -> Self { let sigma = DVector::from_vec( component_list .iter() .map(|&c| self.properties.sigma[c]) .collect(), ); Self::new(sigma, self.version) } } impl ResidualDyn for FMTFunctional { fn components(&self) -> usize { self.properties.sigma.len() } fn compute_max_density<D: DualNum<f64> + Copy>(&self, molefracs: &DVector<D>) -> D { molefracs.dot(&self.properties.sigma.map(D::from)).recip() * 1.2 } fn reduced_helmholtz_energy_density_contributions<D: DualNum<f64> + Copy>( &self, state: &StateHD<D>, ) -> Vec<(&'static str, D)> { self.evaluate_bulk(state) } } impl HelmholtzEnergyFunctionalDyn for FMTFunctional { type Contribution<'a> = FMTContribution<'a, HardSphereParameters> where Self: 'a; fn contributions<'a>( &'a self, ) -> impl Iterator<Item = FMTContribution<'a, HardSphereParameters>> { std::iter::once(FMTContribution::new(&self.properties, self.version)) } fn molecule_shape(&self) -> MoleculeShape<'_> { MoleculeShape::Spherical(self.properties.sigma.len()) } } impl PairPotential for FMTFunctional { fn pair_potential(&self, i: usize, r: &Array1<f64>, _: f64) -> Array2<f64> { let s = &self.properties.sigma; Array::from_shape_fn((s.len(), r.len()), |(j, k)| { if r[k] > 0.5 * (s[i] + s[j]) { 0.0 } else { f64::INFINITY } }) } } impl FluidParameters for FMTFunctional { fn epsilon_k_ff(&self) -> DVector<f64> { DVector::zeros(self.properties.sigma.len()) } fn sigma_ff(&self) -> DVector<f64> { self.properties.sigma.clone() } }
Rust
3D
feos-org/feos
crates/feos/src/pets/mod.rs
.rs
572
18
//! Perturbed Truncated and Shifted (PeTS) equation of state //! //! [Heier et al. (2018)](https://doi.org/10.1080/00268976.2018.1447153) //! //! PeTS is an equation of state for the truncated and shifted Lennar-Jones fluid with cut-off //! distance 2.5 $\sigma$. //! It utilizes a hard-sphere fluid as reference with an attactive perturbation. #[cfg(feature = "dft")] mod dft; mod eos; mod parameters; #[cfg(feature = "dft")] pub use dft::PetsFunctionalContribution; pub use eos::{Pets, PetsOptions}; pub use parameters::{PetsBinaryRecord, PetsParameters, PetsRecord};
Rust
3D
feos-org/feos
crates/feos/src/pets/parameters.rs
.rs
3,732
117
use feos_core::parameter::Parameters; use serde::{Deserialize, Serialize}; /// PeTS parameters for a pure substance. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct PetsRecord { /// Segment diameter in units of Angstrom pub sigma: f64, /// Energetic parameter in units of Kelvin pub epsilon_k: f64, } impl PetsRecord { /// New PeTS parameters for a pure substance. /// /// # Example /// /// ``` /// use feos::pets::PetsRecord; /// let record = PetsRecord::new(3.7, 120.0); /// ``` pub fn new(sigma: f64, epsilon_k: f64) -> PetsRecord { PetsRecord { sigma, epsilon_k } } } /// Parameters that modify binary interactions. /// /// $\varepsilon_{k,ij} = (1 - k_{ij})\sqrt{\varepsilon_{k,i} \varepsilon_{k,j}}$ #[derive(Serialize, Deserialize, Clone, Copy, Default, Debug)] pub struct PetsBinaryRecord { pub k_ij: f64, } /// Parameter set for the PeTS equation of state and Helmholtz energy functional. pub type PetsParameters = Parameters<PetsRecord, PetsBinaryRecord, ()>; #[cfg(test)] pub mod utils { use super::*; use feos_core::parameter::PureRecord; pub fn argon_parameters() -> PetsParameters { let argon_json = r#" { "identifier": { "cas": "7440-37-1", "name": "argon", "iupac_name": "argon", "smiles": "[Ar]", "inchi": "InChI=1/Ar", "formula": "Ar" }, "sigma": 3.4050, "epsilon_k": 119.8, "molarweight": 39.948 }"#; let argon_record: PureRecord<PetsRecord, ()> = serde_json::from_str(argon_json).expect("Unable to parse json."); PetsParameters::new_pure(argon_record).unwrap() } pub fn krypton_parameters() -> PetsParameters { let krypton_json = r#" { "identifier": { "cas": "7439-90-9", "name": "krypton", "iupac_name": "krypton", "smiles": "[Kr]", "inchi": "InChI=1S/Kr", "formula": "Kr" }, "sigma": 3.6300, "epsilon_k": 163.10, "molarweight": 83.798 }"#; let krypton_record: PureRecord<PetsRecord, ()> = serde_json::from_str(krypton_json).expect("Unable to parse json."); PetsParameters::new_pure(krypton_record).unwrap() } pub fn argon_krypton_parameters() -> PetsParameters { let binary_json = r#"[ { "identifier": { "cas": "7440-37-1", "name": "argon", "iupac_name": "argon", "smiles": "[Ar]", "inchi": "1/Ar", "formula": "Ar" }, "sigma": 3.4050, "epsilon_k": 119.8, "molarweight": 39.948 }, { "identifier": { "cas": "7439-90-9", "name": "krypton", "iupac_name": "krypton", "smiles": "[Kr]", "inchi": "InChI=1S/Kr", "formula": "Kr" }, "sigma": 3.6300, "epsilon_k": 163.10, "molarweight": 83.798 } ]"#; let binary_record: [PureRecord<PetsRecord, ()>; 2] = serde_json::from_str(binary_json).expect("Unable to parse json."); PetsParameters::new_binary(binary_record, None, vec![]).unwrap() } }
Rust
3D
feos-org/feos
crates/feos/src/pets/eos/mod.rs
.rs
7,489
234
use super::parameters::PetsParameters; #[cfg(feature = "dft")] use crate::hard_sphere::FMTVersion; use crate::hard_sphere::{HardSphere, HardSphereProperties, MonomerShape}; use feos_core::{Molarweight, ResidualDyn, Subset}; use nalgebra::{DMatrix, DVector}; use num_dual::DualNum; use quantity::MolarWeight; use std::f64::consts::FRAC_PI_6; pub(crate) mod dispersion; /// Configuration options for the PeTS equation of state and Helmholtz energy functional. /// /// The maximum packing fraction is used to infer initial values /// for routines that depend on starting values for the system density. #[derive(Copy, Clone)] pub struct PetsOptions { /// maximum packing fraction pub max_eta: f64, /// The version of the FMT functional to use #[cfg(feature = "dft")] pub fmt_version: FMTVersion, } impl Default for PetsOptions { fn default() -> Self { Self { max_eta: 0.5, #[cfg(feature = "dft")] fmt_version: FMTVersion::WhiteBear, } } } /// PeTS Helmholtz energy model. pub struct Pets { pub parameters: PetsParameters, pub options: PetsOptions, pub sigma: DVector<f64>, pub epsilon_k: DVector<f64>, pub sigma_ij: DMatrix<f64>, pub epsilon_k_ij: DMatrix<f64>, } impl Pets { /// PeTS model with default options. pub fn new(parameters: PetsParameters) -> Self { Self::with_options(parameters, PetsOptions::default()) } /// PeTS model with provided options. pub fn with_options(parameters: PetsParameters, options: PetsOptions) -> Self { let [sigma, epsilon_k] = parameters.collate(|pr| [pr.sigma, pr.epsilon_k]); let n = parameters.pure.len(); let mut sigma_ij = DMatrix::zeros(n, n); let mut epsilon_k_ij = DMatrix::zeros(n, n); let [k_ij] = parameters.collate_binary(|b| [b.k_ij]); for i in 0..n { for j in 0..n { epsilon_k_ij[(i, j)] = (epsilon_k[i] * epsilon_k[j]).sqrt() * (1.0 - k_ij[(i, j)]); sigma_ij[(i, j)] = 0.5 * (sigma[i] + sigma[j]); } } Self { parameters, options, sigma, epsilon_k, sigma_ij, epsilon_k_ij, } } } // impl Components for Pets { // fn components(&self) -> usize { // self.parameters.pure.len() // } impl Subset for Pets { fn subset(&self, component_list: &[usize]) -> Self { Self::with_options(self.parameters.subset(component_list), self.options) } } impl ResidualDyn for Pets { fn components(&self) -> usize { self.parameters.pure.len() } fn compute_max_density<D: num_dual::DualNum<f64> + Copy>(&self, moles: &DVector<D>) -> D { moles.sum() * self.options.max_eta / (self.sigma.map(|v| D::from(v.powi(3))).component_mul(moles)).sum() / FRAC_PI_6 } fn reduced_helmholtz_energy_density_contributions<D: DualNum<f64> + Copy>( &self, state: &feos_core::StateHD<D>, ) -> Vec<(&'static str, D)> { vec![ ( "Hard Sphere", HardSphere.helmholtz_energy_density(self, state), ), ( "Dispersion", self.dispersion_helmholtz_energy_density(state), ), ] } } impl Molarweight for Pets { fn molar_weight(&self) -> MolarWeight<DVector<f64>> { self.parameters.molar_weight.clone() } } impl HardSphereProperties for Pets { fn monomer_shape<N: DualNum<f64>>(&self, _: N) -> MonomerShape<'_, N> { MonomerShape::Spherical(self.sigma.len()) } fn hs_diameter<D: DualNum<f64> + Copy>(&self, temperature: D) -> DVector<D> { let ti = temperature.recip() * -3.052785558; DVector::from_fn(self.sigma.len(), |i, _| { -((ti * self.epsilon_k[i]).exp() * 0.127112544 - 1.0) * self.sigma[i] }) } } #[cfg(test)] mod tests { use super::*; use crate::pets::parameters::utils::{ argon_krypton_parameters, argon_parameters, krypton_parameters, }; use approx::assert_relative_eq; use feos_core::{Contributions, PhaseEquilibrium, State, StateHD}; use nalgebra::dvector; use quantity::{BAR, KELVIN, METER, MOL, RGAS}; #[test] fn ideal_gas_pressure() { let e = &Pets::new(argon_parameters()); let t = 200.0 * KELVIN; let v = 1e-3 * METER.powi::<3>(); let n = dvector![1.0] * MOL; let s = State::new_nvt(&e, t, v, &n).unwrap(); let p_ig = s.total_moles * RGAS * t / v; assert_relative_eq!(s.pressure(Contributions::IdealGas), p_ig, epsilon = 1e-10); assert_relative_eq!( s.pressure(Contributions::IdealGas) + s.pressure(Contributions::Residual), s.pressure(Contributions::Total), epsilon = 1e-10 ); } #[test] fn hard_sphere_mix() { let argon = Pets::new(argon_parameters()); let krypton = Pets::new(krypton_parameters()); let mix = Pets::new(argon_krypton_parameters()); let t = 250.0; let v = 2.5e28; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a1 = HardSphere.helmholtz_energy_density(&argon, &s); let a2 = HardSphere.helmholtz_energy_density(&krypton, &s); let s1m = StateHD::new(t, v, &dvector![n, 0.0]); let a1m = HardSphere.helmholtz_energy_density(&mix, &s1m); let s2m = StateHD::new(t, v, &dvector![0.0, n]); let a2m = HardSphere.helmholtz_energy_density(&mix, &s2m); assert_relative_eq!(a1, a1m, epsilon = 1e-14); assert_relative_eq!(a2, a2m, epsilon = 1e-14); } #[test] fn new_tpn() { let e = &Pets::new(argon_parameters()); let t = 300.0 * KELVIN; let p = BAR; let m = dvector![1.0] * MOL; let s = State::new_npt(&e, t, p, &m, None).unwrap(); let p_calc = s.pressure(Contributions::Total); assert_relative_eq!(p, p_calc, epsilon = 1e-6); } #[test] fn vle_pure_t() { let e = &Pets::new(argon_parameters()); let t = 300.0 * KELVIN; let vle = PhaseEquilibrium::pure(&e, t, None, Default::default()); if let Ok(v) = vle { assert_relative_eq!( v.vapor().pressure(Contributions::Total), v.liquid().pressure(Contributions::Total), epsilon = 1e-6 ) } } #[test] fn mix_single() { let e1 = &Pets::new(argon_parameters()); let e2 = &Pets::new(krypton_parameters()); let e12 = &Pets::new(argon_krypton_parameters()); let t = 300.0 * KELVIN; let v = 0.02456883872966545 * METER.powi::<3>(); let m1 = dvector![2.0] * MOL; let m1m = dvector![2.0, 0.0] * MOL; let m2m = dvector![0.0, 2.0] * MOL; let s1 = State::new_nvt(&e1, t, v, &m1).unwrap(); let s2 = State::new_nvt(&e2, t, v, &m1).unwrap(); let s1m = State::new_nvt(&e12, t, v, &m1m).unwrap(); let s2m = State::new_nvt(&e12, t, v, &m2m).unwrap(); assert_relative_eq!( s1.pressure(Contributions::Total), s1m.pressure(Contributions::Total), epsilon = 1e-12 ); assert_relative_eq!( s2.pressure(Contributions::Total), s2m.pressure(Contributions::Total), epsilon = 1e-12 ) } }
Rust
3D
feos-org/feos
crates/feos/src/pets/eos/dispersion.rs
.rs
2,890
97
use super::Pets; use crate::hard_sphere::HardSphereProperties; use feos_core::StateHD; use num_dual::DualNum; use std::f64::consts::{FRAC_PI_3, PI}; pub const A: [f64; 7] = [ 0.690603404, 1.189317012, 1.265604153, -24.34554201, 93.67300357, -157.8773415, 96.93736697, ]; pub const B: [f64; 7] = [ 0.664852128, 2.10733079, -9.597951213, -17.37871193, 30.17506222, 209.3942909, -353.2743581, ]; impl Pets { pub fn dispersion_helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, state: &StateHD<D>, ) -> D { // auxiliary variables let n = self.sigma.len(); let rho = &state.partial_density; // temperature dependent segment radius let d3 = self.hs_diameter(state.temperature).map(|d| d.powi(3)); // packing fraction let eta = rho.component_mul(&d3).sum() * 0.5 * FRAC_PI_3; // 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 sigma_ij = self.sigma_ij[(i, j)].powi(3); rho1mix += rho[i] * rho[j] * eps_ij * sigma_ij; rho2mix += rho[i] * rho[j] * eps_ij * eps_ij * sigma_ij; } } // I1, I2 and C1 let mut i1 = D::zero(); let mut i2 = D::zero(); let mut eta_i = D::one(); for i in 0..=6 { i1 += eta_i * A[i]; i2 += eta_i * B[i]; eta_i *= eta; } let c1 = ((eta * 8.0 - eta.powi(2) * 2.0) / (eta - 1.0).powi(4) + 1.0).recip(); // Helmholtz energy (-rho1mix * i1 * 2.0 - rho2mix * c1 * i2) * PI } } #[cfg(test)] mod tests { use super::*; use crate::pets::parameters::utils::{ argon_krypton_parameters, argon_parameters, krypton_parameters, }; use approx::assert_relative_eq; use nalgebra::dvector; #[test] fn mix() { let argon = Pets::new(argon_parameters()); let krypton = Pets::new(krypton_parameters()); let mix = Pets::new(argon_krypton_parameters()); let t = 250.0; let v = 2.5e28; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a1 = argon.dispersion_helmholtz_energy_density(&s); let a2 = krypton.dispersion_helmholtz_energy_density(&s); let s1m = StateHD::new(t, v, &dvector![n, 0.0]); let a1m = mix.dispersion_helmholtz_energy_density(&s1m); let s2m = StateHD::new(t, v, &dvector![0.0, n]); let a2m = mix.dispersion_helmholtz_energy_density(&s2m); assert_relative_eq!(a1, a1m, epsilon = 1e-14); assert_relative_eq!(a2, a2m, epsilon = 1e-14); } }
Rust
3D
feos-org/feos
crates/feos/src/pets/dft/mod.rs
.rs
3,197
100
use super::Pets; use super::eos::PetsOptions; use super::parameters::PetsParameters; use crate::hard_sphere::{FMTContribution, FMTVersion}; use dispersion::AttractiveFunctional; use feos_core::FeosResult; use feos_derive::FunctionalContribution; use feos_dft::adsorption::FluidParameters; use feos_dft::solvation::PairPotential; use feos_dft::{FunctionalContribution, HelmholtzEnergyFunctionalDyn, MoleculeShape}; use nalgebra::DVector; use ndarray::{Array1, Array2}; use num_dual::DualNum; use pure_pets_functional::*; mod dispersion; mod pure_pets_functional; impl Pets { /// PeTS model with default options and provided FMT version. pub fn with_fmt_version(parameters: PetsParameters, fmt_version: FMTVersion) -> Self { let options = PetsOptions { fmt_version, ..Default::default() }; Self::with_options(parameters, options) } } impl HelmholtzEnergyFunctionalDyn for Pets { type Contribution<'a> = PetsFunctionalContribution<'a>; fn molecule_shape(&self) -> MoleculeShape<'_> { MoleculeShape::Spherical(self.sigma.len()) } fn contributions<'a>(&'a self) -> impl Iterator<Item = PetsFunctionalContribution<'a>> { let mut contributions = Vec::with_capacity(2); if matches!( self.options.fmt_version, FMTVersion::WhiteBear | FMTVersion::AntiSymWhiteBear ) && self.sigma.len() == 1 // Pure substance or mixture { // Hard-sphere contribution pure substance let fmt = PureFMTFunctional::new(self, self.options.fmt_version); contributions.push(fmt.into()); // Dispersion contribution pure substance let att = PureAttFunctional::new(self); contributions.push(att.into()); } else { // Hard-sphere contribution mixtures let hs = FMTContribution::new(self, self.options.fmt_version); contributions.push(hs.into()); // Dispersion contribution mixtures let att = AttractiveFunctional::new(self); contributions.push(att.into()); } contributions.into_iter() } } impl FluidParameters for Pets { fn epsilon_k_ff(&self) -> DVector<f64> { self.epsilon_k.clone() } fn sigma_ff(&self) -> DVector<f64> { self.sigma.clone() } } impl PairPotential for Pets { fn pair_potential(&self, i: usize, r: &Array1<f64>, _: f64) -> Array2<f64> { let eps_ij_4 = 4.0 * self.epsilon_k_ij.clone(); let shift_ij = &eps_ij_4 * (2.5.powi(-12) - 2.5.powi(-6)); let rc_ij = 2.5 * &self.sigma_ij; Array2::from_shape_fn((self.sigma.len(), r.len()), |(j, k)| { if r[k] > rc_ij[(i, j)] { 0.0 } else { let att = (self.sigma_ij[(i, j)] / r[k]).powi(6); eps_ij_4[(i, j)] * att * (att - 1.0) - shift_ij[(i, j)] } }) } } #[derive(FunctionalContribution)] pub enum PetsFunctionalContribution<'a> { PureFMT(PureFMTFunctional<'a>), PureAtt(PureAttFunctional<'a>), Fmt(FMTContribution<'a, Pets>), Attractive(AttractiveFunctional<'a>), }
Rust
3D
feos-org/feos
crates/feos/src/pets/dft/pure_pets_functional.rs
.rs
5,578
165
use crate::hard_sphere::{FMTVersion, HardSphereProperties}; use crate::pets::Pets; use crate::pets::eos::dispersion::{A, B}; use feos_core::{FeosError, FeosResult}; use feos_dft::{FunctionalContribution, WeightFunction, WeightFunctionInfo, WeightFunctionShape}; use nalgebra::dvector; use ndarray::*; use num_dual::*; use std::f64::consts::{FRAC_PI_6, PI}; const PI36M1: f64 = 1.0 / (36.0 * PI); const N3_CUTOFF: f64 = 1e-5; #[derive(Clone)] pub struct PureFMTFunctional<'a> { parameters: &'a Pets, version: FMTVersion, } impl<'a> PureFMTFunctional<'a> { pub fn new(parameters: &'a Pets, version: FMTVersion) -> Self { Self { parameters, version, } } } impl<'a> FunctionalContribution for PureFMTFunctional<'a> { fn name(&self) -> &'static str { "Pure FMT" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { let r = self.parameters.hs_diameter(temperature) * N::from(0.5); WeightFunctionInfo::new(dvector![0], false).extend( vec![ WeightFunctionShape::Delta, WeightFunctionShape::Theta, WeightFunctionShape::DeltaVec, ] .into_iter() .map(|s| WeightFunction::new_unscaled(r.clone(), s)) .collect(), false, ) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, weighted_densities: ArrayView2<N>, ) -> FeosResult<Array1<N>> { // Weighted densities let n2 = weighted_densities.index_axis(Axis(0), 0); let n3 = weighted_densities.index_axis(Axis(0), 1); let n2v = weighted_densities.slice_axis(Axis(0), Slice::new(2, None, 1)); // Temperature dependent segment radius let r = self.parameters.hs_diameter(temperature)[0] * 0.5; // Auxiliary variables if n3.iter().any(|n3| n3.re() > 1.0) { return Err(FeosError::IterationFailed(String::from( "PureFMTFunctional", ))); } let ln31 = n3.mapv(|n3| (-n3).ln_1p()); let n3rec = n3.mapv(|n3| n3.recip()); let n3m1 = n3.mapv(|n3| -n3 + 1.0); let n3m1rec = n3m1.mapv(|n3m1| n3m1.recip()); let n1 = n2.mapv(|n2| n2 / (r * 4.0 * PI)); let n0 = n2.mapv(|n2| n2 / (r * r * 4.0 * PI)); let n1v = n2v.mapv(|n2v| n2v / (r * 4.0 * PI)); // Different FMT versions let (n1n2, n2n2) = match self.version { FMTVersion::WhiteBear => ( &n1 * &n2 - (&n1v * &n2v).sum_axis(Axis(0)), &n2 * &n2 - (&n2v * &n2v).sum_axis(Axis(0)) * 3.0, ), FMTVersion::AntiSymWhiteBear => { let mut xi2 = (&n2v * &n2v).sum_axis(Axis(0)) / n2.map(|n| n.powi(2)); xi2.iter_mut().for_each(|x| { if x.re() > 1.0 { *x = N::one() } }); ( &n1 * &n2 - (&n1v * &n2v).sum_axis(Axis(0)), &n2 * &n2 * xi2.mapv(|x| (-x + 1.0).powi(3)), ) } _ => unreachable!(), }; // The f3 term contains a 0/0, therefore a taylor expansion is used for small values of n3 let mut f3 = (&n3m1 * &n3m1 * &ln31 + n3) * &n3rec * n3rec * &n3m1rec * &n3m1rec; f3.iter_mut().zip(n3).for_each(|(f3, &n3)| { if n3.re() < N3_CUTOFF { *f3 = (((n3 * 35.0 / 6.0 + 4.8) * n3 + 3.75) * n3 + 8.0 / 3.0) * n3 + 1.5; } }); let phi = -(&n0 * &ln31) + n1n2 * &n3m1rec + n2n2 * n2 * PI36M1 * f3; Ok(phi) } } #[derive(Clone)] pub struct PureAttFunctional<'a> { parameters: &'a Pets, } impl<'a> PureAttFunctional<'a> { pub fn new(parameters: &'a Pets) -> Self { Self { parameters } } } impl<'a> FunctionalContribution for PureAttFunctional<'a> { fn name(&self) -> &'static str { "Pure attractive" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { let d = self.parameters.hs_diameter(temperature); const PSI: f64 = 1.21; // Homosegmented DFT (Heier2018) WeightFunctionInfo::new(dvector![0], false).add( WeightFunction::new_scaled(d * N::from(PSI), WeightFunctionShape::Theta), false, ) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, weighted_densities: ArrayView2<N>, ) -> Result<Array1<N>, FeosError> { let p = &self.parameters; let rho = weighted_densities.index_axis(Axis(0), 0); // temperature dependent segment radius let d = p.hs_diameter(temperature)[0]; let eta = rho.mapv(|rho| rho * FRAC_PI_6 * d.powi(3)); let e = temperature.recip() * p.epsilon_k[0]; let s3 = p.sigma[0].powi(3); // I1, I2 and C1 let mut i1: Array1<N> = Array::zeros(eta.raw_dim()); let mut i2: Array1<N> = Array::zeros(eta.raw_dim()); for i in 0..=6 { i1 = i1 + eta.mapv(|eta| eta.powi(i as i32) * A[i]); i2 = i2 + eta.mapv(|eta| eta.powi(i as i32) * B[i]); } let c1 = eta.mapv(|eta| ((eta * 8.0 - eta.powi(2) * 2.0) / (eta - 1.0).powi(4) + 1.0).recip()); let phi = rho.mapv(|rho| -(rho).powi(2) * e * s3 * PI) * (i1 * 2.0 + c1 * i2.mapv(|i2| i2 * e)); Ok(phi) } }
Rust
3D
feos-org/feos
crates/feos/src/pets/dft/dispersion.rs
.rs
3,580
105
use crate::hard_sphere::HardSphereProperties; use crate::pets::Pets; use crate::pets::eos::dispersion::{A, B}; use feos_core::FeosError; use feos_dft::{FunctionalContribution, WeightFunction, WeightFunctionInfo, WeightFunctionShape}; use nalgebra::DVector; use ndarray::*; use num_dual::DualNum; use std::f64::consts::{FRAC_PI_6, PI}; /// psi Parameter for DFT (Heier2018) const PSI_DFT: f64 = 1.21; /// psi Parameter for pDGT (not adjusted, yet) const PSI_PDGT: f64 = 1.21; #[derive(Clone)] pub struct AttractiveFunctional<'a> { parameters: &'a Pets, } impl<'a> AttractiveFunctional<'a> { pub fn new(parameters: &'a Pets) -> Self { Self { parameters } } fn att_weight_functions<N: DualNum<f64> + Copy>( &self, psi: f64, temperature: N, ) -> WeightFunctionInfo<N> { let d = self.parameters.hs_diameter(temperature); WeightFunctionInfo::new(DVector::from_fn(d.len(), |i, _| i), false).add( WeightFunction::new_scaled(d * N::from(psi), WeightFunctionShape::Theta), false, ) } } impl<'a> FunctionalContribution for AttractiveFunctional<'a> { fn name(&self) -> &'static str { "Attractive functional" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { self.att_weight_functions(PSI_DFT, temperature) } fn weight_functions_pdgt<N: DualNum<f64> + Copy>( &self, temperature: N, ) -> WeightFunctionInfo<N> { self.att_weight_functions(PSI_PDGT, temperature) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, density: ArrayView2<N>, ) -> Result<Array1<N>, FeosError> { // auxiliary variables let p = &self.parameters; let n = p.sigma.len(); // temperature dependent segment diameter let d = p.hs_diameter(temperature); // packing fraction let eta = density.outer_iter().zip(d.map(|d| d.powi(3)).iter()).fold( Array::zeros(density.raw_dim().remove_axis(Axis(0))), |acc: Array1<N>, (rho, &d3)| acc + &rho * d3, ) * FRAC_PI_6; // mixture densities, crosswise interactions of all segments on all chains let mut rho1mix: Array1<N> = Array::zeros(eta.raw_dim()); let mut rho2mix: Array1<N> = Array::zeros(eta.raw_dim()); for i in 0..n { for j in 0..n { let eps_ij_t = temperature.recip() * p.epsilon_k_ij[(i, j)]; let sigma_ij_3 = p.sigma_ij[(i, j)].powi(3); rho1mix = rho1mix + (&density.index_axis(Axis(0), i) * &density.index_axis(Axis(0), j)) .mapv(|x| x * (eps_ij_t * sigma_ij_3)); rho2mix = rho2mix + (&density.index_axis(Axis(0), i) * &density.index_axis(Axis(0), j)) .mapv(|x| x * (eps_ij_t * eps_ij_t * sigma_ij_3)); } } // I1, I2 and C1 let mut i1: Array1<N> = Array::zeros(eta.raw_dim()); let mut i2: Array1<N> = Array::zeros(eta.raw_dim()); let mut eta_i: Array1<N> = Array::ones(eta.raw_dim()); for i in 0..=6 { i1 = i1 + &eta_i * A[i]; i2 = i2 + &eta_i * B[i]; eta_i = &eta_i * &eta; } let c1 = eta.mapv(|eta| ((eta * 8.0 - eta.powi(2) * 2.0) / (eta - 1.0).powi(4) + 1.0).recip()); // Helmholtz energy density Ok((-rho1mix * i1 * 2.0 - rho2mix * c1 * i2) * PI) } }
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/mod.rs
.rs
592
17
//! Heterosegmented Group Contribution PC-SAFT //! //! - [Gross et al. (2003)](https://doi.org/10.1021/ie020509y) //! - [Sauer et al. (2014)](https://doi.org/10.1021/ie502203w) #![expect(unexpected_cfgs)] #[cfg(feature = "dft")] mod dft; pub(crate) mod eos; #[cfg(feature = "micelles")] pub mod micelles; mod record; #[cfg(feature = "dft")] pub use dft::{GcPcSaftFunctional, GcPcSaftFunctionalContribution, GcPcSaftFunctionalParameters}; pub use eos::{GcPcSaft, GcPcSaftAD, GcPcSaftADParameters, GcPcSaftEosParameters, GcPcSaftOptions}; pub use record::{GcPcSaftParameters, GcPcSaftRecord};
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/record.rs
.rs
1,969
69
use feos_core::parameter::{CombiningRule, GcParameters}; use num_traits::Zero; use serde::{Deserialize, Serialize}; /// gc-PC-SAFT pure-component parameters. #[derive(Serialize, Deserialize, Clone, Default)] pub struct GcPcSaftRecord { /// Segment shape factor pub m: 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, /// interaction range parameter for the dispersion functional #[serde(skip_serializing_if = "Option::is_none")] pub psi_dft: Option<f64>, } impl GcPcSaftRecord { pub fn new(m: f64, sigma: f64, epsilon_k: f64, mu: f64, psi_dft: Option<f64>) -> Self { Self { m, sigma, epsilon_k, mu, psi_dft, } } } #[derive(Serialize, Deserialize, Clone, Copy, Default, PartialEq, Debug)] pub struct GcPcSaftAssociationRecord { /// Association volume parameter pub kappa_ab: f64, /// Association energy parameter in units of Kelvin pub epsilon_k_ab: f64, } impl GcPcSaftAssociationRecord { pub fn new(kappa_ab: f64, epsilon_k_ab: f64) -> Self { Self { kappa_ab, epsilon_k_ab, } } } impl CombiningRule<GcPcSaftRecord> for GcPcSaftAssociationRecord { fn combining_rule( _: &GcPcSaftRecord, _: &GcPcSaftRecord, 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), } } } /// Parameter set required for the gc-PC-SAFT equation of state. pub type GcPcSaftParameters<C> = GcParameters<GcPcSaftRecord, f64, GcPcSaftAssociationRecord, (), C>;
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/micelles.rs
.rs
9,984
295
use feos_core::{Contributions, EosError, EosResult, EosUnit, SolverOptions, State, StateBuilder}; use feos_dft::{ Axis, ConvolverFFT, DFT, DFTProfile, DFTSolver, DFTSpecification, Geometry, Grid, HelmholtzEnergyFunctional, WeightFunctionInfo, }; use ndarray::prelude::*; use quantity::{QuantityArray2, QuantityScalar, SIArray1}; pub enum MicelleInitialization { ExternalPotential(f64, f64), Density(QuantityArray2), } impl MicelleInitialization { fn density(&self) -> Option<&QuantityArray2> { match self { Self::ExternalPotential(_, _) => None, Self::Density(density) => Some(density), } } } pub enum MicelleSpecification { ChemicalPotential, Size { delta_n_surfactant: f64, pressure: SINumber, }, } impl<U: EosUnit, F: HelmholtzEnergyFunctional> DFTSpecification<U, Ix1, F> for MicelleSpecification { fn calculate_bulk_density( &self, profile: &DFTProfile<U, Ix1, F>, bulk_density: &Array1<f64>, z: &Array1<f64>, ) -> EosResult<Array1<f64>> { Ok(match self { Self::ChemicalPotential => bulk_density.clone(), Self::Size { delta_n_surfactant, pressure, } => { let rho_s_bulk = bulk_density[1]; let rho_w_bulk = bulk_density[0]; let volume = SIUnit::reference_volume(); let moles = arr1(&[rho_w_bulk, rho_s_bulk]) * SIUnit::reference_density() * volume; let bulk = State::new_nvt(&profile.dft, profile.temperature, volume, &moles)?; let f_bulk = bulk.helmholtz_energy(Contributions::Total) / bulk.volume; let mu_bulk = bulk.chemical_potential(Contributions::Total); let mu_s_bulk = mu_bulk.get(1); let mu_w_bulk = mu_bulk.get(0); let n_s_bulk = (rho_s_bulk * profile.volume()).to_reduced(SIUnit::reference_moles())?; let mut spec = (delta_n_surfactant + n_s_bulk) / z; spec[0] = ((pressure + f_bulk - rho_s_bulk * mu_s_bulk) / mu_w_bulk) .to_reduced(SIUnit::reference_density())?; spec } }) } } pub struct MicelleProfile<U: EosUnit, F: HelmholtzEnergyFunctional> { pub profile: DFTProfile<U, Ix1, F>, pub delta_omega: Option<SINumber>, pub delta_n: Option<SIArray1>, } impl<U: EosUnit, F: HelmholtzEnergyFunctional> Clone for MicelleProfile<U, F> { fn clone(&self) -> Self { Self { profile: self.profile.clone(), delta_omega: self.delta_omega, delta_n: self.delta_n.clone(), } } } impl<U: EosUnit, F: HelmholtzEnergyFunctional> MicelleProfile<U, F> { pub fn solve_inplace(&mut self, solver: Option<&DFTSolver>, debug: bool) -> EosResult<()> { self.profile.solve(solver, debug)?; self.post_process() } pub fn solve(mut self, solver: Option<&DFTSolver>) -> EosResult<Self> { self.solve_inplace(solver, false)?; Ok(self) } pub fn solve_micelle_inplace( &mut self, solver1: Option<&DFTSolver>, solver2: Option<&DFTSolver>, debug: bool, ) -> EosResult<()> { self.profile.solve(solver1, true)?; self.profile.external_potential.fill(0.0); self.profile.solve(solver2, debug)?; self.post_process() } pub fn solve_micelle( mut self, solver1: Option<&DFTSolver>, solver2: Option<&DFTSolver>, ) -> EosResult<Self> { self.solve_micelle_inplace(solver1, solver2, false)?; Ok(self) } fn post_process(&mut self) -> EosResult<()> { // calculate excess grand potential self.delta_omega = Some(self.profile.integrate( &(self.profile.dft.grand_potential_density( self.profile.temperature, &self.profile.density, &self.profile.convolver, )? + self.profile.bulk.pressure(Contributions::Total)), )); // calculate excess particles self.delta_n = Some(self.profile.moles() - &self.profile.bulk.partial_density * self.profile.volume()); Ok(()) } } impl<U: EosUnit + 'static, F: HelmholtzEnergyFunctional> MicelleProfile<U, F> { fn new( bulk: &State<U, F>, axis: Axis, initialization: MicelleInitialization, specification: MicelleSpecification, ) -> EosResult<Self> { let dft = &bulk.eos; // calculate external potential let t = bulk .temperature .to_reduced(SIUnit::reference_temperature())?; let mut external_potential = Array2::zeros((dft.component_index().len(), axis.grid.len())); if let MicelleInitialization::ExternalPotential(peak, width) = initialization { external_potential.index_axis_mut(Axis(0), 0).assign( &axis .grid .mapv(|r| peak * (-0.5 * r * r / (width * width)).exp()), ); } // initialize convolver let grid = match axis.geometry { Geometry::Spherical => Grid::Spherical(axis), Geometry::Cylindrical => Grid::Polar(axis), _ => unreachable!(), }; let contributions = dft.contributions(); let weight_functions: Vec<WeightFunctionInfo<f64>> = contributions .iter() .map(|c| c.weight_functions(t)) .collect(); let convolver = ConvolverFFT::plan(&grid, &weight_functions, Some(1)); // create profile let mut profile = DFTProfile::new( grid, convolver, bulk, Some(external_potential), initialization.density(), )?; // specify specification profile.specification = Arc::new(specification); Ok(Self { profile, delta_omega: None, delta_n: None, }) } pub fn new_spherical( bulk: &State<U, F>, n_grid: usize, width: SINumber, initialization: MicelleInitialization, specification: MicelleSpecification, ) -> EosResult<Self> { Self::new( bulk, Axis::new_spherical(n_grid, width)?, initialization, specification, ) } pub fn new_cylindrical( bulk: &State<U, F>, n_grid: usize, width: SINumber, initialization: MicelleInitialization, specification: MicelleSpecification, ) -> EosResult<Self> { Self::new( bulk, Axis::new_polar(n_grid, width)?, initialization, specification, ) } pub fn update_specification(&self, specification: MicelleSpecification) -> Self { let mut profile = self.clone(); profile.profile.specification = Arc::new(specification); profile.delta_omega = None; profile.delta_n = None; profile } } const MAX_ITER_MICELLE: usize = 50; const TOL_MICELLE: f64 = 1e-5; impl<U: EosUnit + 'static, F: HelmholtzEnergyFunctional> MicelleProfile<U, F> { pub fn critical_micelle( mut self, solver: Option<&DFTSolver>, options: SolverOptions, ) -> EosResult<Self> { let n_grid = self.profile.r().len(); let temperature = self.profile.bulk.temperature; let t = temperature.to_reduced(SIUnit::reference_temperature())?; let pressure = self.profile.bulk.pressure(Contributions::Total); let eos = self.profile.bulk.eos.clone(); let indices = self.profile.bulk.eos.component_index().into_owned(); self.profile.specification = Arc::new(MicelleSpecification::ChemicalPotential); for _ in 0..options.max_iter.unwrap_or(MAX_ITER_MICELLE) { // check for convergence if self .delta_omega .unwrap() .to_reduced(SIUnit::reference_energy())? .abs() < options.tol.unwrap_or(TOL_MICELLE) * t { return Ok(self); } let bulk = &mut self.profile.bulk; let mut x = bulk.molefracs[1]; // Calculate Newton step let delta_n = self.delta_n.as_ref().unwrap(); let dp_drho = bulk.dp_dni(Contributions::Total) * bulk.volume; let dmu_drho = bulk.dmu_dni(Contributions::Total) * bulk.volume; let p_term = (dp_drho.get(1) - dp_drho.get(0)) / (dp_drho.get(1) * x + dp_drho.get(0) * (1.0 - x)); let a = delta_n.get(1) * dmu_drho.get((1, 1)) + delta_n.get(0) * dmu_drho.get((1, 0)); let b = delta_n.get(1) * dmu_drho.get((0, 1)) + delta_n.get(0) * dmu_drho.get((0, 0)); let domega_dx = -(((a - b) * x + b) * p_term + a - b) * bulk.density; x -= self.delta_omega.unwrap().to_reduced(domega_dx)?; // udpate bulk and chemical potential *bulk = StateBuilder::new(&eos) .temperature(temperature) .pressure(pressure) .molefracs(&arr1(&[1.0 - x, x])) .build()?; // update density profile for (i, &j) in indices.iter().enumerate() { let rho_bulk = self.profile.density.get((i, n_grid - 1)); for k in 0..n_grid { let rho_old = self.profile.density.get((i, k)); self.profile .density .try_set((i, k), rho_old + bulk.partial_density.get(j) - rho_bulk)?; } } // solve profile self = self.solve(solver)?; } Err(EosError::NotConverged( "MicelleProfile::criticelle_micelle".into(), )) } }
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/eos/mod.rs
.rs
5,913
190
use super::record::GcPcSaftParameters; use crate::association::Association; use crate::hard_sphere::{HardSphere, HardSphereProperties}; use feos_core::{Molarweight, ResidualDyn, Subset}; use nalgebra::DVector; use num_dual::DualNum; use quantity::MolarWeight; use std::f64::consts::FRAC_PI_6; mod ad; pub(crate) mod dispersion; mod hard_chain; pub(crate) mod parameter; mod polar; pub use ad::{GcPcSaftAD, GcPcSaftADParameters}; use dispersion::Dispersion; use hard_chain::HardChain; pub use parameter::GcPcSaftEosParameters; use polar::Dipole; /// Customization options for the gc-PC-SAFT equation of state and functional. #[derive(Copy, Clone)] pub struct GcPcSaftOptions { /// 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 GcPcSaftOptions { fn default() -> Self { Self { max_eta: 0.5, max_iter_cross_assoc: 50, tol_cross_assoc: 1e-10, } } } /// gc-PC-SAFT equation of state pub struct GcPcSaft { parameters: GcPcSaftParameters<f64>, params: GcPcSaftEosParameters, options: GcPcSaftOptions, association: Option<Association>, dipole: Option<Dipole>, } impl GcPcSaft { pub fn new(parameters: GcPcSaftParameters<f64>) -> Self { Self::with_options(parameters, GcPcSaftOptions::default()) } pub fn with_options(parameters: GcPcSaftParameters<f64>, options: GcPcSaftOptions) -> Self { let params = GcPcSaftEosParameters::new(&parameters); let association = (!parameters.association.is_empty()) .then(|| Association::new(options.max_iter_cross_assoc, options.tol_cross_assoc)); let dipole = if !params.dipole_comp.is_empty() { Some(Dipole::new(&params)) } else { None }; Self { parameters, params, options, association, dipole, } } } impl ResidualDyn for GcPcSaft { fn components(&self) -> usize { self.parameters.molar_weight.len() } fn compute_max_density<D: DualNum<f64> + Copy>(&self, molefracs: &DVector<D>) -> D { let p = &self.params; let molefracs_segments = DVector::from(p.component_index.clone()).map(|i| molefracs[i]); (p.m.component_mul(&p.sigma.map(|v| v.powi(3))) .map(D::from) .dot(&molefracs_segments) * FRAC_PI_6) .recip() * self.options.max_eta } fn reduced_helmholtz_energy_density_contributions<D: DualNum<f64> + Copy>( &self, state: &feos_core::StateHD<D>, ) -> Vec<(&'static str, D)> { let mut v = Vec::with_capacity(7); let d = self.params.hs_diameter(state.temperature); v.push(( "Hard Sphere", HardSphere.helmholtz_energy_density(&self.params, state), )); v.push(( "Hard Chain", HardChain.helmholtz_energy_density(&self.params, state), )); v.push(( "Dispersion", Dispersion.helmholtz_energy_density(&self.params, state), )); if let Some(dipole) = self.dipole.as_ref() { v.push(( "Dipole", dipole.helmholtz_energy_density(&self.params, state), )) } if let Some(association) = self.association.as_ref() { v.push(( "Association", association.helmholtz_energy_density( &self.params, &self.parameters.association, state, &d, ), )) } v } } impl Subset for GcPcSaft { fn subset(&self, component_list: &[usize]) -> Self { Self::with_options(self.parameters.subset(component_list), self.options) } } impl Molarweight for GcPcSaft { fn molar_weight(&self) -> MolarWeight<DVector<f64>> { self.parameters.molar_weight.clone() } } #[cfg(test)] mod test { use super::*; use crate::gc_pcsaft::eos::parameter::test::*; use approx::assert_relative_eq; use feos_core::ReferenceSystem; use feos_core::StateHD; use nalgebra::dvector; use num_dual::Dual64; use quantity::{METER, MOL, PASCAL, Pressure}; #[test] fn hs_propane() { let parameters = propane(); let temperature = 300.0; let volume = Dual64::from_re(METER.powi::<3>().to_reduced()).derivative(); let moles = Dual64::from_re((1.5 * MOL).to_reduced()); let molar_volume = volume / moles; let state = StateHD::new( Dual64::from_re(temperature), molar_volume, &dvector![Dual64::from_re(1.0)], ); let pressure = Pressure::from_reduced( -(HardSphere.helmholtz_energy_density(&parameters, &state) * volume).eps * temperature, ); assert_relative_eq!(pressure, 1.5285037907989527 * PASCAL, max_relative = 1e-10); } #[test] fn hs_propanol() { let parameters = GcPcSaftEosParameters::new(&propanol()); let temperature = 300.0; let volume = Dual64::from_re(METER.powi::<3>().to_reduced()).derivative(); let moles = Dual64::from_re((1.5 * MOL).to_reduced()); let molar_volume = volume / moles; let state = StateHD::new( Dual64::from_re(temperature), molar_volume, &dvector![Dual64::from_re(1.0)], ); let pressure = Pressure::from_reduced( -(HardSphere.helmholtz_energy_density(&parameters, &state) * volume).eps * temperature, ); assert_relative_eq!(pressure, 2.3168212018200243 * PASCAL, max_relative = 1e-10); } }
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/eos/hard_chain.rs
.rs
2,824
86
use super::GcPcSaftEosParameters; use crate::hard_sphere::HardSphereProperties; use feos_core::StateHD; use num_dual::*; pub(super) struct HardChain; impl HardChain { pub(super) fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &GcPcSaftEosParameters, state: &StateHD<D>, ) -> D { // temperature dependent segment diameter let diameter = parameters.hs_diameter(state.temperature); // Packing fractions let [zeta2, zeta3] = parameters.zeta(state.temperature, &state.partial_density, [2, 3]); // Helmholtz energy let frac_1mz3 = -(zeta3 - 1.0).recip(); let c = zeta2 * frac_1mz3 * frac_1mz3; parameters .bonds .iter() .map(|&([i, j], count)| { let (di, dj) = (diameter[i], diameter[j]); let cdij = c * di * dj / (di + dj); let g = frac_1mz3 + cdij * 3.0 - cdij * cdij * (zeta3 - 1.0) * 2.0; -state.partial_density[parameters.component_index[i]] * count * g.ln() }) .sum() } } #[cfg(test)] mod test { use super::*; use crate::gc_pcsaft::eos::parameter::test::*; use approx::assert_relative_eq; use feos_core::ReferenceSystem; use nalgebra::dvector; use num_dual::Dual64; use quantity::{METER, MOL, PASCAL, Pressure}; #[test] fn test_hc_propane() { let parameters = propane(); let temperature = 300.0; let volume = METER.powi::<3>().to_reduced(); let volume = Dual64::from_re(volume).derivative(); let moles = (1.5 * MOL).to_reduced(); let state = StateHD::new( Dual64::from_re(temperature), volume, &dvector![Dual64::from_re(moles)], ); let pressure = Pressure::from_reduced( -(HardChain.helmholtz_energy_density(&parameters, &state) * volume).eps * temperature, ); assert_relative_eq!( pressure, -7.991735636207462e-1 * PASCAL, max_relative = 1e-10 ); } #[test] fn test_hc_propanol() { let parameters = GcPcSaftEosParameters::new(&propanol()); let temperature = 300.0; let volume = METER.powi::<3>().to_reduced(); let volume = Dual64::from_re(volume).derivative(); let moles = (1.5 * MOL).to_reduced(); let state = StateHD::new( Dual64::from_re(temperature), volume, &dvector![Dual64::from_re(moles)], ); let pressure = Pressure::from_reduced( -(HardChain.helmholtz_energy_density(&parameters, &state) * volume).eps * temperature, ); assert_relative_eq!(pressure, -1.2831486124723626 * PASCAL, max_relative = 1e-10); } }
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/eos/ad.rs
.rs
21,546
543
use super::dispersion::{A0, A1, A2, B0, B1, B2}; use super::polar::{AD, BD, CD}; use feos_core::{Residual, StateHD}; use nalgebra::{Const, SMatrix, SVector}; use num_dual::DualNum; use quantity::{JOULE, KB, KELVIN}; use std::collections::HashMap; use std::f64::consts::{FRAC_PI_6, PI}; use std::sync::LazyLock; const PI_SQ_43: f64 = 4.0 / 3.0 * PI * PI; const MAX_ETA: f64 = 0.5; const N_GROUPS: usize = 20; const GROUPS: [&str; N_GROUPS] = [ "CH3", "CH2", ">CH", ">C<", "=CH2", "=CH", "=C<", "C≡CH", "CH2_hex", "CH_hex", "CH2_pent", "CH_pent", "CH_arom", "C_arom", "CH=O", ">C=O", "OCH3", "OCH2", "HCOO", "COO", ]; const M: [f64; N_GROUPS] = [ 0.77247, 0.7912, 0.52235, -0.70131, 0.70581, 0.90182, 0.98505, 1.1615, 0.8793, 0.42115, 0.90057, 0.69343, 0.88259, 0.77531, 1.1889, 1.1889, 1.1907, 1.1817, 1.2789, 1.2869, ]; const SIGMA: [f64; N_GROUPS] = [ 3.6937, 3.0207, 0.99912, 0.5435, 3.163, 2.8864, 2.245, 3.3187, 2.9995, 1.3078, 3.0437, 1.2894, 2.9475, 1.6719, 3.2948, 3.1026, 2.7795, 3.009, 3.373, 3.0643, ]; const EPSILON_K: [f64; N_GROUPS] = [ 181.49, 157.23, 269.84, 0.0, 171.34, 158.9, 146.86, 255.13, 157.93, 131.79, 158.34, 140.69, 156.51, 178.81, 316.91, 280.43, 284.91, 203.11, 307.44, 273.9, ]; const MU: [f64; N_GROUPS] = [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.4126, 3.4167, 0.0, 2.6945, 2.6808, 3.3428, ]; const K_AB_LIST: [((&str, &str), f64); 128] = [ (("CH3", "C≡CH"), 0.1652754031504817), (("CH2", "C≡CH"), -0.006553805247652898), ((">CH", "C≡CH"), -0.45179562711827204), ((">CH", "CH_arom"), -0.2623133986577006), (("CH3", "C_arom"), 0.1029438146806397), (("CH2", "C_arom"), -0.019417887747868838), (("CH3", "CH_arom"), 0.03524440115729556), (("CH2", "CH_arom"), -0.005376660474268035), ((">CH", "C_arom"), -0.4536159179058391), (("CH3", "CH=O"), 0.07114002498453002), (("CH2", "CH=O"), 0.05810424929073859), ((">C=O", "CH3"), 0.06638452980811302), ((">C=O", "CH2"), 0.053964852486994674), ((">C=O", ">CH"), -0.01886821792425231), (("CH3", "OCH2"), 0.0040270442665658705), ((">CH", "OCH3"), -0.217389127174595), (("CH2", "OCH2"), -0.015001007000489858), (("CH3", "OCH3"), 0.04370031373865), ((">CH", "OCH2"), -0.038601031822155345), (("CH2", "OCH3"), 0.021857618541656035), (("CH3", "HCOO"), 0.046221094393257035), (("CH2", "HCOO"), 0.07467469076976556), ((">CH", "COO"), 0.17498779403987508), (("CH3", "COO"), 0.05050525601666908), (("CH2", "COO"), 0.04126150329459275), (("=CH2", "C≡CH"), 0.28518205265981117), (("=CH", "C≡CH"), -0.19471892756822953), (("=C<", "C≡CH"), -0.37966037059629637), (("=CH", "C_arom"), -0.04794957652572591), (("=C<", "C_arom"), -0.19059760666493372), (("=CH2", "C_arom"), 0.002829235390387696), (("=CH", "CH_arom"), 0.008744506522926979), (("=C<", "CH_arom"), -0.15988275905975652), (("=CH2", "CH_arom"), 0.039714702972518216), (("=C<", ">C=O"), -0.23303936628601363), (("=CH2", ">C=O"), 0.0451103450863995), (("=CH", ">C=O"), 0.0028282796817093118), (("=CH2", "OCH3"), -0.017336555493171858), (("=CH", "OCH2"), 0.028713611730255537), (("=C<", "OCH2"), -0.040576835006969125), (("=CH2", "OCH2"), 0.02792348761278379), (("=CH", "OCH3"), 0.021854680107075346), (("=C<", "OCH3"), -0.21464227012985213), (("=CH", "HCOO"), -0.021573291908933357), (("=C<", "HCOO"), -0.021791386613505864), (("=CH2", "COO"), -0.08063693709595326), (("=CH", "COO"), -0.07829355920744586), (("=C<", "COO"), -0.19510136763283895), (("CH_arom", "C≡CH"), -0.04955767628386867), (("C_arom", "C≡CH"), -0.04953394596854589), (("CH=O", "C≡CH"), -0.33948211818518437), ((">C=O", "C≡CH"), -0.3657376137845608), (("C≡CH", "OCH2"), -0.3344648388007797), (("C≡CH", "OCH3"), -0.38290586519600983), (("C≡CH", "HCOO"), -0.24272079727170506), (("COO", "C≡CH"), -0.3654438081227738), (("C≡CH", "OH"), -0.10409652963367089), (("CH_arom", "C_arom"), -0.12728867698722554), (("CH_arom", "CH_arom"), -0.023433119170883764), (("C_arom", "C_arom"), -0.28421918877688607), (("CH2_hex", "CH_arom"), 0.001447550584366187), (("CH_hex", "C_arom"), -0.40316115168074723), (("CH_arom", "CH_hex"), -0.3576321797883022), (("CH2_hex", "C_arom"), 0.08521616156959391), (("CH_arom", "CH_pent"), -0.18714862430161244), (("CH_pent", "C_arom"), 0.03457714936255159), (("CH2_pent", "C_arom"), 0.03812116290565423), (("CH2_pent", "CH_arom"), 0.004966663517893626), (("CH=O", "C_arom"), -0.025044677100339502), (("CH=O", "CH_arom"), -0.06309730593619743), ((">C=O", "CH_arom"), -0.1106708081496441), ((">C=O", "C_arom"), -0.04717854573415193), (("C_arom", "OCH3"), -0.14006221692396298), (("CH_arom", "OCH2"), -0.11744345395130776), (("CH_arom", "OCH3"), -0.06563917699710337), (("C_arom", "OCH2"), -0.03747169315781876), (("CH_arom", "HCOO"), -0.04404325532489947), (("C_arom", "HCOO"), 0.2898776740748664), (("CH_arom", "COO"), -0.10600926342624745), (("COO", "C_arom"), -0.11054573554364296), (("C_arom", "OH"), 0.2990171120344822), (("CH_arom", "OH"), -0.039398695604311314), (("C_arom", "NH2"), 0.4535791221221567), (("CH_arom", "NH2"), -0.06290638692043257), (("CH2_hex", "CH=O"), 0.09047030071006708), (("CH=O", "CH_hex"), -0.14747598417210014), ((">C=O", "CH_hex"), 0.0676825668907787), ((">C=O", "CH2_hex"), 0.09082375748804353), (("CH2_hex", "OCH3"), 0.042823701076275526), (("CH_hex", "OCH2"), -0.0936451919984422), (("CH_hex", "OCH3"), 0.12111386208387202), (("CH2_hex", "OCH2"), 0.013698887705260425), (("CH2_hex", "HCOO"), 0.08719198819954514), (("CH2_hex", "COO"), 0.05937938878778157), (("CH_hex", "COO"), -0.10319900739370075), (("CH2_hex", "OH"), 0.06127398203560399), (("CH_hex", "OH"), 0.35825180807831797), (("CH2_pent", "COO"), 0.05124310486288829), (("CH_pent", "OH"), 0.11518421254437769), (("CH2_pent", "OH"), 0.08215868571093943), (("CH=O", "CH=O"), -0.1570556622280003), ((">C=O", "CH=O"), -0.16452206370456918), (("CH=O", "OCH2"), 0.0027095251191336708), (("CH=O", "HCOO"), -0.07673278642721204), (("CH=O", "COO"), -0.16365969940991995), (("CH=O", "OH"), -0.12245349842770242), ((">C=O", ">C=O"), -0.17931771307891634), ((">C=O", "OCH3"), -0.20038719736411056), ((">C=O", "OCH2"), 0.04468736703539099), ((">C=O", "HCOO"), -0.13541978245760022), ((">C=O", "COO"), -0.14605212162381323), ((">C=O", "OH"), -0.1392769563372809), ((">C=O", "NH2"), -0.371931948310995), (("OCH2", "OCH2"), 0.09662571077941844), (("OCH2", "OCH3"), -0.2812620283200189), (("OCH3", "OCH3"), -0.13909723652059505), (("HCOO", "OCH3"), -0.0929570619422749), (("COO", "OCH2"), -0.11408007406963222), (("COO", "OCH3"), -0.21710938244245623), (("OCH2", "OH"), -0.014272196525878467), (("OCH3", "OH"), -0.039585706351111166), (("HCOO", "HCOO"), -0.14303475853269773), (("COO", "HCOO"), -0.14056680898820434), (("HCOO", "OH"), -0.11204049889700908), (("COO", "COO"), -0.1879219131496382), (("COO", "OH"), -0.09507071103459414), (("COO", "NH2"), -0.2799573216348791), (("NH2", "OH"), -0.42107448986356144), ]; static K_AB_MAP: LazyLock<HashMap<(&str, &str), f64>> = LazyLock::new(|| { K_AB_LIST .into_iter() .map(|((s1, s2), val)| ((s2, s1), val)) .chain(K_AB_LIST) .collect() }); static K_AB: LazyLock<SMatrix<f64, N_GROUPS, N_GROUPS>> = LazyLock::new(|| { SMatrix::from_fn(|i, j| *K_AB_MAP.get(&(GROUPS[i], GROUPS[j])).unwrap_or(&0.0)) }); /// Parameters used to instantiate [GcPcSaftAD]. #[derive(Clone)] pub struct GcPcSaftADParameters<D, const N: usize> { pub groups: SMatrix<D, N_GROUPS, N>, pub bonds: [Vec<([usize; 2], D)>; N], } impl<D: DualNum<f64> + Copy, const N: usize> GcPcSaftADParameters<D, N> { pub fn re(&self) -> GcPcSaftADParameters<f64, N> { let Self { groups, bonds } = self; let groups = groups.map(|g| g.re()); let bonds = bonds .each_ref() .map(|b| b.iter().map(|&(b, v)| (b, v.re())).collect()); GcPcSaftADParameters { groups, bonds } } } impl<D: DualNum<f64> + Copy, const N: usize> GcPcSaftADParameters<D, N> { pub fn from_groups( group_map: [&HashMap<&'static str, D>; N], bond_map: [&HashMap<[&'static str; 2], D>; N], ) -> Self { let groups = SMatrix::from(group_map.map(|r| GROUPS.map(|g| *r.get(g).unwrap_or(&D::zero())))); let group_indices: HashMap<_, _> = GROUPS .into_iter() .enumerate() .map(|(g, i)| (i, g)) .collect(); let bonds = bond_map.map(|r| { r.iter() .map(|([g1, g2], &c)| ([group_indices[g1], group_indices[g2]], c)) .collect() }); Self { groups, bonds } } } /// The heterosegmented GC model for PC-SAFT by Sauer et al. #[derive(Clone)] pub struct GcPcSaftAD<D, const N: usize>(pub GcPcSaftADParameters<D, N>); impl<D: DualNum<f64> + Copy, const N: usize> Residual<Const<N>, D> for GcPcSaftAD<D, N> { fn components(&self) -> usize { N } type Real = GcPcSaftAD<f64, N>; type Lifted<D2: DualNum<f64, Inner = D> + Copy> = GcPcSaftAD<D2, N>; fn re(&self) -> Self::Real { GcPcSaftAD(self.0.re()) } fn lift<D2: DualNum<f64, Inner = D> + Copy>(&self) -> Self::Lifted<D2> { let GcPcSaftADParameters { groups, bonds } = &self.0; let groups = groups.map(|x| D2::from_inner(&x)); let bonds = bonds .each_ref() .map(|b| b.iter().map(|&(b, v)| (b, D2::from_inner(&v))).collect()); GcPcSaftAD(GcPcSaftADParameters { groups, bonds }) } fn compute_max_density(&self, molefracs: &SVector<D, N>) -> D { let msigma3: SVector<f64, N_GROUPS> = SVector::from_fn(|i, _| M[i] * SIGMA[i].powi(3)); let msigma3 = msigma3.map(D::from); let GcPcSaftADParameters { groups, bonds: _ } = &self.0; let msigma3 = apply_group_count(groups, &msigma3).row_sum(); // let x: f64 = msigma3.iter().zip(molefracs).map(|&(ms3, x)| x * ms3).sum(); ((msigma3 * molefracs).into_scalar() * FRAC_PI_6).recip() * MAX_ETA } fn reduced_helmholtz_energy_density_contributions( &self, state: &StateHD<D, Const<N>>, ) -> Vec<(&'static str, D)> { vec![( "gc-PC-SAFT", self.reduced_residual_helmholtz_energy_density(state), )] } fn reduced_residual_helmholtz_energy_density(&self, state: &StateHD<D, Const<N>>) -> D { let GcPcSaftADParameters { groups, bonds } = &self.0; let density = &state.partial_density; // convert parameters let m = apply_group_count(groups, &SVector::from(M.map(D::from))); let sigma = SVector::from(SIGMA.map(D::from)); let epsilon_k = SVector::from(EPSILON_K.map(D::from)); let mu = SVector::from(MU.map(D::from)); // temperature dependent segment diameter let t_inv = state.temperature.recip(); let diameter = (epsilon_k * (t_inv * -3.0)) .map(|x| -x.exp() * 0.12 + 1.0) .component_mul(&sigma); // packing fractions let mut zeta = [D::zero(); 4]; for c in 0..N { for i in 0..diameter.len() { for (z, &k) in zeta.iter_mut().zip([0, 1, 2, 3].iter()) { *z += density[c] * diameter[i].powi(k) * m[(i, c)] * FRAC_PI_6; } } } let zeta_23 = zeta[2] / zeta[3]; let frac_1mz3 = -(zeta[3] - 1.0).recip(); // hard sphere let hs = (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] * (-1.0)).ln_1p()) / std::f64::consts::FRAC_PI_6; // hard chain let c = zeta[2] * frac_1mz3 * frac_1mz3; let hc: D = bonds .iter() .zip(density.iter()) .flat_map(|(bonds, &rho)| { bonds.iter().map(move |([i, j], count)| { let (di, dj) = (diameter[*i], diameter[*j]); let cdij = c * di * dj / (di + dj); let g = frac_1mz3 + cdij * 3.0 - cdij * cdij * (zeta[3] - 1.0) * 2.0; -rho * count * g.ln() }) }) .sum(); // packing fraction let eta = zeta[3]; // mean segment number let molefracs = density / density.sum(); let mbar = m.row_sum().tr_dot(&molefracs); // crosswise interactions of all groups on all chains let eps_ij = SVector::from(EPSILON_K).map(f64::sqrt); let eps_ij = eps_ij * eps_ij.transpose(); let mut rho1mix = D::zero(); let mut rho2mix = D::zero(); for (m_i, &rho_i) in m.column_iter().zip(density.iter()) { for (m_j, &rho_j) in m.column_iter().zip(density.iter()) { for i in 0..N_GROUPS { for j in 0..N_GROUPS { let k_ab = if m_i != m_j { K_AB[(i, j)] } else { 0.0 }; let eps_ij_t = state.temperature.recip() * eps_ij[(i, j)] * (1.0 - k_ab); let sigma_ij = ((SIGMA[i] + SIGMA[j]) * 0.5).powi(3); let rho1 = rho_i * rho_j * (eps_ij_t * m_i[i] * m_j[j] * sigma_ij); rho1mix += rho1; rho2mix += rho1 * eps_ij_t; } } } } // I1, I2 and C1 let mut i1 = D::zero(); let mut i2 = D::zero(); let mut eta_i = D::one(); let m1 = (mbar - 1.0) / mbar; let m2 = (mbar - 2.0) / mbar * m1; for i in 0..=6 { i1 += (m2 * A2[i] + m1 * A1[i] + A0[i]) * eta_i; i2 += (m2 * B2[i] + m1 * B1[i] + B0[i]) * eta_i; eta_i *= eta; } let c1 = (mbar * (eta * 8.0 - eta.powi(2) * 2.0) / (eta - 1.0).powi(4) + (D::one() - mbar) * (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(); // dispersion let disp = (-rho1mix * i1 * 2.0 - rho2mix * mbar * c1 * i2) * PI; // dipoles let m_mix = m.row_sum(); let sigma_mix = apply_group_count(&m, &sigma.map(|s| s.powi(3))) .row_sum() .component_div(&m_mix) .map(|s| s.cbrt()); let epsilon_k_mix = apply_group_count(&m, &epsilon_k) .row_sum() .component_div(&m_mix); let mu2 = apply_group_count(groups, &mu.component_mul(&mu)) .row_sum() .component_div(&m_mix) * (t_inv * 1e-19 * JOULE.convert_into(KELVIN * KB)); let m_mix = m_mix.map(|m| if m.re() > 2.0 { D::from(2.0) } else { m }); let mut phi2 = D::zero(); let mut phi3 = D::zero(); for i in 0..N { for j in i..N { let sigma_ij_3 = ((sigma_mix[i] + sigma_mix[j]) * 0.5).powi(3); let mij = (m_mix[i] * m_mix[j]).sqrt(); let mij1 = (mij - 1.0) / mij; let mij2 = mij1 * (mij - 2.0) / mij; let eps_ij_t = t_inv * (epsilon_k_mix[i] * epsilon_k_mix[j]).sqrt(); let c = if i == j { 1.0 } else { 2.0 }; phi2 -= (density[i] * density[j] * mu2[i] * mu2[j]) * pair_integral(mij1, mij2, eta, eps_ij_t) / sigma_ij_3 * c; for k in j..N { let sigma_ij = (sigma_mix[i] + sigma_mix[j]) * 0.5; let sigma_ik = (sigma_mix[i] + sigma_mix[k]) * 0.5; let sigma_jk = (sigma_mix[j] + sigma_mix[k]) * 0.5; let mijk = (m_mix[i] * m_mix[j] * m_mix[k]).cbrt(); let mijk1 = (mijk - 1.0) / mijk; let mijk2 = mijk1 * (mijk - 2.0) / mijk; let c = if i == j && i == k { 1.0 } else if i == j || i == k || j == k { 3.0 } else { 6.0 }; phi3 -= (density[i] * density[j] * density[k] * mu2[i] * mu2[j] * mu2[k]) * triplet_integral(mijk1, mijk2, eta) / (sigma_ij * sigma_ik * sigma_jk) * c; } } } phi2 *= PI; phi3 *= PI_SQ_43; let mut dipole = phi2 * phi2 / (phi2 - phi3); if dipole.re().is_nan() { dipole = phi2 } hs + hc + disp + dipole } } fn apply_group_count<D: DualNum<f64> + Copy, const N: usize>( groups: &SMatrix<D, N_GROUPS, N>, x: &SVector<D, N_GROUPS>, ) -> SMatrix<D, N_GROUPS, N> { let mut ms = *groups; ms.column_iter_mut() .for_each(|mut s| s.component_mul_assign(x)); ms } fn pair_integral<D: DualNum<f64> + Copy>(mij1: D, mij2: D, eta: D, eps_ij_t: D) -> D { let mut eta_i = D::one(); let mut j = D::zero(); for (ad, bd) in AD.into_iter().zip(BD) { j += (eps_ij_t * (mij2 * bd[2] + mij1 * bd[1] + bd[0]) + (mij2 * ad[2] + mij1 * ad[1] + ad[0])) * eta_i; eta_i *= eta; } j } fn triplet_integral<D: DualNum<f64> + Copy>(mij1: D, mij2: D, eta: D) -> D { let mut eta_i = D::one(); let mut j = D::zero(); for cd in CD { j += (mij2 * cd[2] + mij1 * cd[1] + cd[0]) * eta_i; eta_i *= eta; } j } #[cfg(test)] pub mod test { use super::{EPSILON_K, GROUPS, GcPcSaftAD, GcPcSaftADParameters, M, MU, SIGMA}; use crate::gc_pcsaft::{GcPcSaft, GcPcSaftParameters as GcPcSaftEosParameters, GcPcSaftRecord}; use approx::assert_relative_eq; use feos_core::parameter::{ChemicalRecord, SegmentRecord}; use feos_core::{Contributions::Total, FeosResult, State}; use nalgebra::{dvector, vector}; use quantity::{KELVIN, KILO, METER, MOL}; use std::collections::HashMap; pub fn gcpcsaft() -> FeosResult<(GcPcSaftADParameters<f64, 1>, GcPcSaft)> { let cr = ChemicalRecord::new( Default::default(), vec!["CH3".into(), ">C=O".into(), "CH2".into(), "CH3".into()], None, ); let segment_records: Vec<_> = M .into_iter() .zip(SIGMA) .zip(EPSILON_K) .zip(MU) .zip(GROUPS) .map(|((((m, sigma), epsilon_k), mu), g)| { SegmentRecord::new( g.into(), 0.0, GcPcSaftRecord::new(m, sigma, epsilon_k, mu, None), ) }) .collect(); let params = GcPcSaftEosParameters::from_segments_hetero(vec![cr], &segment_records, None)?; let eos = GcPcSaft::new(params); let mut groups = HashMap::new(); groups.insert("CH3", 2.0); groups.insert(">C=O", 1.0); groups.insert("CH2", 1.0); let mut bonds = HashMap::new(); bonds.insert(["CH3", ">C=O"], 1.0); bonds.insert([">C=O", "CH2"], 1.0); bonds.insert(["CH2", "CH3"], 1.0); let params = GcPcSaftADParameters::from_groups([&groups], [&bonds]); Ok((params, eos)) } #[test] fn test_gcpcsaft() -> FeosResult<()> { let (params, eos) = gcpcsaft()?; let temperature = 300.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 eos_ad = GcPcSaftAD(params); let moles = vector![1.3] * KILO * MOL; let state = State::new_nvt(&eos_ad, 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!("\nHelmholtz energy density:\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(()) } }
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/eos/dispersion.rs
.rs
5,059
169
use super::GcPcSaftEosParameters; use crate::hard_sphere::HardSphereProperties; use feos_core::StateHD; use num_dual::DualNum; use std::f64::consts::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.30840169182720, 0.18605311591713, -2.50300472586548, 21.4197936296668, -65.2558853303492, 83.3186804808856, -33.7469229297323, ]; pub const A2: [f64; 7] = [ -0.09061483509767, 0.45278428063920, 0.59627007280101, -1.72418291311787, -4.13021125311661, 13.7766318697211, -8.67284703679646, ]; 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.57554980753450, 0.69950955214436, 3.89256733895307, -17.21547164777212, 192.6722644652495, -161.8264616487648, -165.2076934555607, ]; pub const B2: [f64; 7] = [ 0.09768831158356, -0.25575749816100, -9.15585615297321, 20.64207597439724, -38.80443005206285, 93.6267740770146, -29.66690558514725, ]; pub(super) struct Dispersion; impl Dispersion { pub(super) fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &GcPcSaftEosParameters, state: &StateHD<D>, ) -> D { // auxiliary variables let p = parameters; let n = p.m.len(); let rho = &state.partial_density; // packing fraction let eta = p.zeta(state.temperature, &state.partial_density, [3])[0]; // mean segment number let m = p.m.iter() .zip(p.component_index.iter()) .map(|(&m, &i)| state.molefracs[i] * m) .sum::<D>(); // 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() * p.epsilon_k_ij[(i, j)]; let sigma_ij = p.sigma_ij[(i, j)].powi(3); let rho1 = rho[p.component_index[i]] * rho[p.component_index[j]] * (eps_ij * p.m[i] * p.m[j] * sigma_ij); rho1mix += rho1; rho2mix += rho1 * eps_ij; } } // I1, I2 and C1 let mut i1 = D::zero(); let mut i2 = D::zero(); let mut eta_i = D::one(); let m1 = (m - 1.0) / m; let m2 = (m - 2.0) / m * m1; for i in 0..=6 { i1 += (m2 * A2[i] + m1 * A1[i] + A0[i]) * eta_i; i2 += (m2 * B2[i] + m1 * B1[i] + B0[i]) * eta_i; eta_i *= eta; } let c1 = (m * (eta * 8.0 - eta.powi(2) * 2.0) / (eta - 1.0).powi(4) + (D::one() - m) * (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(); // Helmholtz energy (-rho1mix * i1 * 2.0 - rho2mix * m * c1 * i2) * PI } } #[cfg(test)] mod test { use super::*; use crate::gc_pcsaft::eos::parameter::test::*; use approx::assert_relative_eq; use feos_core::ReferenceSystem; use nalgebra::dvector; use num_dual::Dual64; use quantity::{METER, MOL, PASCAL, Pressure}; #[test] fn test_dispersion_propane() { let parameters = propane(); let temperature = 300.0; let volume = Dual64::from_re(METER.powi::<3>().to_reduced()).derivative(); let moles = Dual64::from_re((1.5 * MOL).to_reduced()); let molar_volume = volume / moles; let state = StateHD::new( Dual64::from_re(temperature), molar_volume, &dvector![Dual64::from_re(1.0)], ); let pressure = Pressure::from_reduced( -(Dispersion.helmholtz_energy_density(&parameters, &state) * volume).eps * temperature, ); assert_relative_eq!(pressure, -2.846724434944439 * PASCAL, max_relative = 1e-10); } #[test] fn test_dispersion_propanol() { let parameters = GcPcSaftEosParameters::new(&propanol()); let temperature = 300.0; let volume = Dual64::from_re(METER.powi::<3>().to_reduced()).derivative(); let moles = Dual64::from_re((1.5 * MOL).to_reduced()); let molar_volume = volume / moles; let state = StateHD::new( Dual64::from_re(temperature), molar_volume, &dvector![Dual64::from_re(1.0)], ); let pressure = Pressure::from_reduced( -(Dispersion.helmholtz_energy_density(&parameters, &state) * volume).eps * temperature, ); assert_relative_eq!(pressure, -5.432173507270732 * PASCAL, max_relative = 1e-10); } }
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/eos/polar.rs
.rs
6,481
174
use super::GcPcSaftEosParameters; use crate::hard_sphere::HardSphereProperties; use feos_core::StateHD; use nalgebra::DMatrix; use num_dual::DualNum; use std::f64::consts::{FRAC_PI_3, PI}; // Dipole parameters pub 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 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 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], ]; pub const PI_SQ_43: f64 = 4.0 * PI * FRAC_PI_3; fn pair_integral_ij<D: DualNum<f64> + Copy>(mij1: f64, mij2: f64, eta: D, eps_ij_t: D) -> D { let eta2 = eta * eta; let etas = [D::one(), eta, eta2, eta2 * eta, eta2 * eta2]; (0..AD.len()) .map(|i| { etas[i] * (eps_ij_t * (BD[i][0] + mij1 * BD[i][1] + mij2 * BD[i][2]) + (AD[i][0] + mij1 * AD[i][1] + mij2 * AD[i][2])) }) .sum() } fn triplet_integral_ijk<D: DualNum<f64> + Copy>(mijk1: f64, mijk2: f64, eta: D) -> D { let eta2 = eta * eta; let etas = [D::one(), eta, eta2, eta2 * eta]; (0..CD.len()) .map(|i| etas[i] * (CD[i][0] + mijk1 * CD[i][1] + mijk2 * CD[i][2])) .sum() } pub(super) struct Dipole { mij1: DMatrix<f64>, mij2: DMatrix<f64>, mijk1: Vec<DMatrix<f64>>, mijk2: Vec<DMatrix<f64>>, f2_term: DMatrix<f64>, f3_term: Vec<DMatrix<f64>>, } impl Dipole { pub fn new(parameters: &GcPcSaftEosParameters) -> Self { let ndipole = parameters.dipole_comp.len(); let f2_term = DMatrix::from_fn(ndipole, ndipole, |i, j| { parameters.mu2[i] * parameters.mu2[j] / parameters.s_ij[(i, j)].powi(3) }); let f3_term = (0..ndipole) .map(|i| { DMatrix::from_fn(ndipole, ndipole, |j, k| { parameters.mu2[i] * parameters.mu2[j] * parameters.mu2[k] / (parameters.s_ij[(i, j)] * parameters.s_ij[(i, k)] * parameters.s_ij[(j, k)]) }) }) .collect(); let mut mij1 = DMatrix::zeros(ndipole, ndipole); let mut mij2 = DMatrix::zeros(ndipole, ndipole); let mut mijk1 = vec![DMatrix::zeros(ndipole, ndipole); ndipole]; let mut mijk2 = vec![DMatrix::zeros(ndipole, ndipole); ndipole]; for i in 0..ndipole { let mi = parameters.m_mix[i].min(2.0); mij1[(i, i)] = (mi - 1.0) / mi; mij2[(i, i)] = mij1[(i, i)] * (mi - 2.0) / mi; mijk1[i][(i, i)] = mij1[(i, i)]; mijk2[i][(i, i)] = mij2[(i, i)]; for j in i + 1..ndipole { let mj = parameters.m_mix[j].min(2.0); let mij = (mi * mj).sqrt(); mij1[(i, j)] = (mij - 1.0) / mij; mij2[(i, j)] = mij1[(i, j)] * (mij - 2.0) / mij; let mijk = (mi * mi * mj).cbrt(); mijk1[i][(i, j)] = (mijk - 1.0) / mijk; mijk2[i][(i, j)] = mijk1[i][(i, j)] * (mijk - 2.0) / mijk; let mijk = (mi * mj * mj).cbrt(); mijk1[i][(j, j)] = (mijk - 1.0) / mijk; mijk2[i][(j, j)] = mijk1[i][(j, j)] * (mijk - 2.0) / mijk; for k in j + 1..ndipole { let mk = parameters.m_mix[k].min(2.0); let mijk = (mi * mj * mk).cbrt(); mijk1[i][(j, k)] = (mijk - 1.0) / mijk; mijk2[i][(j, k)] = mijk1[i][(j, k)] * (mijk - 2.0) / mijk; } } } Self { mij1, mij2, mijk1, mijk2, f2_term, f3_term, } } } impl Dipole { pub(super) fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &GcPcSaftEosParameters, state: &StateHD<D>, ) -> D { let p = parameters; let ndipole = p.dipole_comp.len(); let t_inv = state.temperature.inv(); let eps_ij_t = DMatrix::from_fn(ndipole, ndipole, |i, j| t_inv * p.e_k_ij[(i, j)]); let rho = &state.partial_density; let eta = p.zeta(state.temperature, &state.partial_density, [3])[0]; let mut phi2 = D::zero(); let mut phi3 = D::zero(); for i in 0..ndipole { let di = p.dipole_comp[i]; phi2 -= (rho[di] * rho[di] * self.f2_term[(i, i)]) * pair_integral_ij(self.mij1[(i, i)], self.mij2[(i, i)], eta, eps_ij_t[(i, i)]); phi3 -= (rho[di] * rho[di] * rho[di] * self.f3_term[i][(i, i)]) * triplet_integral_ijk(self.mijk1[i][(i, i)], self.mijk2[i][(i, i)], eta); for j in (i + 1)..ndipole { let dj = p.dipole_comp[j]; phi2 -= (rho[di] * rho[dj] * self.f2_term[(i, j)]) * pair_integral_ij(self.mij1[(i, j)], self.mij2[(i, j)], eta, eps_ij_t[(i, j)]) * 2.0; phi3 -= (rho[di] * rho[di] * rho[dj] * self.f3_term[i][(i, j)]) * triplet_integral_ijk(self.mijk1[i][(i, j)], self.mijk2[i][(i, j)], eta) * 3.0; phi3 -= (rho[di] * rho[dj] * rho[dj] * self.f3_term[i][(j, j)]) * triplet_integral_ijk(self.mijk1[i][(j, j)], self.mijk2[i][(j, j)], eta) * 3.0; for k in (j + 1)..ndipole { let dk = p.dipole_comp[k]; phi3 -= (rho[di] * rho[dj] * rho[dk] * self.f3_term[i][(j, k)]) * triplet_integral_ijk(self.mijk1[i][(j, k)], self.mijk2[i][(j, k)], eta) * 6.0; } } } phi2 *= t_inv * t_inv * PI; phi3 *= t_inv.powi(3) * PI_SQ_43; let mut result = phi2 * phi2 / (phi2 - phi3); if result.re().is_nan() { result = phi2 } result } }
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/eos/parameter.rs
.rs
9,010
262
use crate::association::AssociationStrength; use crate::gc_pcsaft::record::{GcPcSaftAssociationRecord, GcPcSaftParameters}; use crate::hard_sphere::{HardSphereProperties, MonomerShape}; use itertools::Itertools; use nalgebra::{DMatrix, DVector}; use num_dual::DualNum; use quantity::{JOULE, KB, KELVIN}; /// Parameter set required for the gc-PC-SAFT equation of state. #[derive(Clone)] pub struct GcPcSaftEosParameters { pub component_index: DVector<usize>, pub m: DVector<f64>, pub sigma: DVector<f64>, pub epsilon_k: DVector<f64>, pub bonds: Vec<([usize; 2], f64)>, pub dipole_comp: DVector<usize>, pub mu2: DVector<f64>, pub m_mix: DVector<f64>, pub s_ij: DMatrix<f64>, pub e_k_ij: DMatrix<f64>, pub sigma_ij: DMatrix<f64>, pub epsilon_k_ij: DMatrix<f64>, } // The gc-PC-SAFT parameters in an easier accessible format. impl GcPcSaftEosParameters { pub fn new(parameters: &GcPcSaftParameters<f64>) -> Self { let component_index = parameters.component_index().into(); let [m, sigma, epsilon_k] = parameters.collate(|pr| [pr.m, pr.sigma, pr.epsilon_k]); let m = m.component_mul(&parameters.segment_counts()); let bonds = parameters .bonds .iter() .map(|b| ([b.id1, b.id2], b.count)) .collect(); let mut dipole_comp = Vec::new(); let mut mu2 = Vec::new(); let mut m_mix = Vec::new(); let mut sigma_mix = Vec::new(); let mut epsilon_k_mix = Vec::new(); let mut m_i: DVector<f64> = DVector::zeros(parameters.molar_weight.len()); let mut sigma_i: DVector<f64> = DVector::zeros(parameters.molar_weight.len()); let mut epsilon_k_i: DVector<f64> = DVector::zeros(parameters.molar_weight.len()); let mut mu2_i: DVector<f64> = DVector::zeros(parameters.molar_weight.len()); for p in &parameters.pure { m_i[p.component_index] += p.model_record.m * p.count; sigma_i[p.component_index] += p.model_record.m * p.model_record.sigma.powi(3) * p.count; epsilon_k_i[p.component_index] += p.model_record.m * p.model_record.epsilon_k * p.count; mu2_i[p.component_index] += p.model_record.mu.powi(2); } for (i, &mu2_i) in mu2_i.iter().enumerate() { if mu2_i > 0.0 { dipole_comp.push(i); mu2.push(mu2_i / m_i[i] * (1e-19 * (JOULE / KELVIN / KB).into_value())); m_mix.push(m_i[i]); sigma_mix.push((sigma_i[i] / m_i[i]).cbrt()); epsilon_k_mix.push(epsilon_k_i[i] / m_i[i]); } } // Combining rules dispersion let [k_ij] = parameters.collate_binary(|&br| [br]); let sigma_ij = DMatrix::from_fn(sigma.len(), sigma.len(), |i, j| 0.5 * (sigma[i] + sigma[j])); let epsilon_k_ij = DMatrix::from_fn(epsilon_k.len(), epsilon_k.len(), |i, j| { (epsilon_k[i] * epsilon_k[j]).sqrt() }) .component_mul(&((-k_ij).add_scalar(1.0))); // Combining rules polar let s_ij = DMatrix::from_fn(dipole_comp.len(), dipole_comp.len(), |i, j| { 0.5 * (sigma_mix[i] + sigma_mix[j]) }); let e_k_ij = DMatrix::from_fn(dipole_comp.len(), dipole_comp.len(), |i, j| { (epsilon_k_mix[i] * epsilon_k_mix[j]).sqrt() }); Self { component_index, m, sigma, epsilon_k, bonds, dipole_comp: DVector::from_vec(dipole_comp), mu2: DVector::from_vec(mu2), m_mix: DVector::from_vec(m_mix), s_ij, e_k_ij, sigma_ij, epsilon_k_ij, } } } impl GcPcSaftEosParameters { pub fn phi(mut self, phi: &[f64]) -> Self { for i in (0..self.m.len()).combinations_with_replacement(2) { let (i, j) = (i[0], i[1]); self.epsilon_k_ij[(i, j)] *= (phi[self.component_index[i]] * phi[self.component_index[j]]).sqrt(); } self } } impl HardSphereProperties for GcPcSaftEosParameters { fn monomer_shape<N: DualNum<f64>>(&self, _: N) -> MonomerShape<'_, N> { let m = self.m.map(N::from); MonomerShape::Heterosegmented([m.clone(), m.clone(), m.clone(), m], &self.component_index) } fn hs_diameter<D: DualNum<f64> + Copy>(&self, temperature: D) -> DVector<D> { 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 GcPcSaftEosParameters { type Record = GcPcSaftAssociationRecord; fn association_strength_ij<D: DualNum<f64> + Copy>( &self, temperature: D, comp_i: usize, comp_j: usize, assoc_ij: &Self::Record, ) -> D { let f_ab = (temperature.recip() * assoc_ij.epsilon_k_ab).exp_m1(); let k_ab = assoc_ij.kappa_ab * (self.sigma[comp_i] * self.sigma[comp_j]).powf(1.5); f_ab * k_ab } } #[cfg(test)] pub mod test { use super::*; use crate::gc_pcsaft::GcPcSaftRecord; use feos_core::parameter::{ AssociationRecord, BinarySegmentRecord, ChemicalRecord, Identifier, SegmentRecord, }; type Pure = SegmentRecord<GcPcSaftRecord, GcPcSaftAssociationRecord>; type Binary = BinarySegmentRecord<f64, GcPcSaftAssociationRecord>; fn ch3() -> Pure { SegmentRecord::new( "CH3".into(), 15.0, GcPcSaftRecord::new(0.77247, 3.6937, 181.49, 0.0, None), ) } fn ch2() -> Pure { SegmentRecord::new( "CH2".into(), 14.0, GcPcSaftRecord::new(0.7912, 3.0207, 157.23, 0.0, None), ) } fn oh() -> Pure { SegmentRecord::with_association( "OH".into(), 17.0, GcPcSaftRecord::new(1.0231, 2.7702, 334.29, 0.0, None), vec![AssociationRecord::new( Some(GcPcSaftAssociationRecord::new(0.009583, 2575.9)), 1.0, 1.0, 0.0, )], ) } pub fn ch3_oh() -> Binary { BinarySegmentRecord::new("CH3".to_string(), "OH".to_string(), Some(-0.0087)) } pub fn propane() -> GcPcSaftEosParameters { let pure = ChemicalRecord::new( Identifier::new(Some("74-98-6"), Some("propane"), None, None, None, None), vec!["CH3".into(), "CH2".into(), "CH3".into()], None, ); let params = GcPcSaftParameters::from_segments_hetero(vec![pure], &[ch3(), ch2()], None).unwrap(); GcPcSaftEosParameters::new(&params) } pub fn propanol() -> GcPcSaftParameters<f64> { let pure = ChemicalRecord::new( Identifier::new(Some("71-23-8"), Some("1-propanol"), None, None, None, None), vec!["CH3".into(), "CH2".into(), "CH2".into(), "OH".into()], None, ); GcPcSaftParameters::from_segments_hetero(vec![pure], &[ch3(), ch2(), oh()], None).unwrap() } pub fn ethanol_propanol(binary: bool) -> GcPcSaftParameters<f64> { let ethanol = ChemicalRecord::new( Identifier::new(Some("64-17-5"), Some("ethanol"), None, None, None, None), vec!["CH3".into(), "CH2".into(), "OH".into()], None, ); let propanol = ChemicalRecord::new( Identifier::new(Some("71-23-8"), Some("1-propanol"), None, None, None, None), vec!["CH3".into(), "CH2".into(), "CH2".into(), "OH".into()], None, ); let binary = if binary { Some(vec![ch3_oh()]) } else { None }; GcPcSaftParameters::from_segments_hetero( vec![ethanol, propanol], &[ch3(), ch2(), oh()], binary.as_deref(), ) .unwrap() } #[test] fn test_kij() { let params = ethanol_propanol(true); let identifiers: Vec<_> = params .pure .iter() .map(|r| &r.identifier) .enumerate() .collect(); let params = GcPcSaftEosParameters::new(&params); let ch3 = identifiers.iter().find(|&&(_, id)| id == "CH3").unwrap(); let ch2 = identifiers .iter() .skip(3) .find(|&&(_, id)| id == "CH2") .unwrap(); let oh = identifiers .iter() .skip(3) .find(|&&(_, id)| id == "OH") .unwrap(); // println!("{:?}", params.identifiers); // println!("{}", params.k_ij); // CH3 - CH2 assert_eq!( params.epsilon_k_ij[(ch3.0, ch2.0)], (181.49f64 * 157.23).sqrt() ); // CH3 - OH assert_eq!( params.epsilon_k_ij[(ch3.0, oh.0)], (181.49f64 * 334.29).sqrt() * 1.0087 ); } }
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/dft/mod.rs
.rs
6,409
205
use super::eos::GcPcSaftOptions; use super::record::GcPcSaftAssociationRecord; use crate::association::{Association, YuWuAssociationFunctional, AssociationStrength}; use crate::gc_pcsaft::GcPcSaftParameters; use crate::hard_sphere::{FMTContribution, FMTVersion, HardSphereProperties, MonomerShape}; 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 hard_chain; mod parameter; use dispersion::AttractiveFunctional; use hard_chain::ChainFunctional; pub use parameter::GcPcSaftFunctionalParameters; /// gc-PC-SAFT Helmholtz energy functional. pub struct GcPcSaftFunctional { parameters: GcPcSaftParameters<()>, params: GcPcSaftFunctionalParameters, association: Option<Association>, fmt_version: FMTVersion, options: GcPcSaftOptions, } impl GcPcSaftFunctional { pub fn new(parameters: GcPcSaftParameters<()>) -> Self { Self::with_options( parameters, FMTVersion::WhiteBear, GcPcSaftOptions::default(), ) } pub fn with_options( parameters: GcPcSaftParameters<()>, fmt_version: FMTVersion, saft_options: GcPcSaftOptions, ) -> Self { let params = GcPcSaftFunctionalParameters::new(&parameters); let association = (!parameters.association.is_empty()).then(|| { Association::new( saft_options.max_iter_cross_assoc, saft_options.tol_cross_assoc, ) }); Self { parameters, params, association, fmt_version, options: saft_options, } } } impl Subset for GcPcSaftFunctional { fn subset(&self, component_list: &[usize]) -> Self { Self::with_options( self.parameters.subset(component_list), self.fmt_version, self.options, ) } } impl ResidualDyn for GcPcSaftFunctional { fn components(&self) -> usize { self.parameters.molar_weight.len() } fn compute_max_density<D: DualNum<f64> + Copy>(&self, molefracs: &DVector<D>) -> D { let p = &self.params; let msigma3 = p.m.zip_map(&p.sigma, |m, s| m * s.powi(3) * m); let molefracs_segments: DVector<_> = p .component_index .iter() .map(|&i| molefracs[i]) .collect::<Vec<_>>() .into(); (msigma3.map(D::from).dot(&molefracs_segments) * FRAC_PI_6).recip() * self.options.max_eta } fn reduced_helmholtz_energy_density_contributions<D: DualNum<f64> + Copy>( &self, state: &StateHD<D>, ) -> Vec<(&'static str, D)> { self.evaluate_bulk(state) } } impl HelmholtzEnergyFunctionalDyn for GcPcSaftFunctional { type Contribution<'a> = GcPcSaftFunctionalContribution<'a>; fn molecule_shape(&self) -> MoleculeShape<'_> { MoleculeShape::Heterosegmented(&self.params.component_index) } fn contributions<'a>(&'a self) -> impl Iterator<Item = GcPcSaftFunctionalContribution<'a>> { let mut contributions = Vec::with_capacity(4); let assoc = YuWuAssociationFunctional::new(&self.params, &self.parameters, self.association); // Hard sphere contribution let hs = FMTContribution::new(&self.params, self.fmt_version); contributions.push(hs.into()); // Hard chains let chain = ChainFunctional::new(&self.params); contributions.push(chain.into()); // Dispersion let att = AttractiveFunctional::new(&self.params); contributions.push(att.into()); // Association if let Some(assoc) = assoc { contributions.push(assoc.into()); } contributions.into_iter() } fn bond_lengths<N: DualNum<f64> + Copy>(&self, temperature: N) -> UnGraph<(), N> { // temperature dependent segment diameter let d = self.params.hs_diameter(temperature); self.params.bonds.map( |_, _| (), |e, _| { let (i, j) = self.params.bonds.edge_endpoints(e).unwrap(); let di = d[i.index()]; let dj = d[j.index()]; (di + dj) * 0.5 }, ) } } impl Molarweight for GcPcSaftFunctional { fn molar_weight(&self) -> MolarWeight<DVector<f64>> { self.parameters.molar_weight.clone() } } impl HardSphereProperties for GcPcSaftFunctionalParameters { fn monomer_shape<N: DualNum<f64>>(&self, _: N) -> MonomerShape<'_, N> { let m = self.m.map(N::from); MonomerShape::Heterosegmented([m.clone(), m.clone(), m.clone(), m], &self.component_index) } fn hs_diameter<D: DualNum<f64> + Copy>(&self, temperature: D) -> DVector<D> { 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 GcPcSaftFunctionalParameters { type Record = GcPcSaftAssociationRecord; fn association_strength_ij<D: DualNum<f64> + 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) } } impl FluidParameters for GcPcSaftFunctional { fn epsilon_k_ff(&self) -> DVector<f64> { self.params.epsilon_k.clone() } fn sigma_ff(&self) -> DVector<f64> { self.params.sigma.clone() } } /// Individual contributions for the gc-PC-SAFT Helmholtz energy functional. #[derive(FunctionalContribution)] pub enum GcPcSaftFunctionalContribution<'a> { Fmt(FMTContribution<'a, GcPcSaftFunctionalParameters>), Chain(ChainFunctional<'a>), Attractive(AttractiveFunctional<'a>), Association(YuWuAssociationFunctional<'a, GcPcSaftFunctionalParameters>), }
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/dft/hard_chain.rs
.rs
2,964
88
use super::GcPcSaftFunctionalParameters; use crate::hard_sphere::HardSphereProperties; use feos_core::FeosError; use feos_dft::{FunctionalContribution, WeightFunction, WeightFunctionInfo, WeightFunctionShape}; use ndarray::*; use num_dual::DualNum; use petgraph::visit::EdgeRef; #[derive(Clone)] pub struct ChainFunctional<'a> { parameters: &'a GcPcSaftFunctionalParameters, } impl<'a> ChainFunctional<'a> { pub fn new(parameters: &'a GcPcSaftFunctionalParameters) -> Self { Self { parameters } } } impl<'a> FunctionalContribution for ChainFunctional<'a> { fn name(&self) -> &'static str { "Hard chain functional (GC)" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { let p = &self.parameters; let d = p.hs_diameter(temperature); WeightFunctionInfo::new(p.component_index.clone(), true) .add( WeightFunction { prefactor: p.m.map(|m| (m / 8.0).into()).component_div(&d), kernel_radius: d.clone(), shape: WeightFunctionShape::Theta, }, true, ) .add( WeightFunction { prefactor: p.m.map(|m| (m / 8.0).into()), kernel_radius: d, shape: WeightFunctionShape::Theta, }, true, ) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, weighted_densities: ArrayView2<N>, ) -> Result<Array1<N>, FeosError> { let p = &self.parameters; // number of segments let segments = weighted_densities.shape()[0] - 2; // weighted densities let rho = weighted_densities.slice_axis(Axis(0), Slice::new(0, Some(segments as isize), 1)); let zeta2 = weighted_densities.index_axis(Axis(0), segments); let zeta3 = weighted_densities.index_axis(Axis(0), segments + 1); // temperature dependent segment diameter let d = p.hs_diameter(temperature); // Helmholtz energy let frac_1mz3 = zeta3.mapv(|z3| (-z3 + 1.0).recip()); let c = &zeta2 * &frac_1mz3 * &frac_1mz3; let mut phi = Array::zeros(zeta2.raw_dim()); for i in p.bonds.node_indices() { let rho_i = rho.index_axis(Axis(0), i.index()); let edges = p.bonds.edges(i); let y = edges .map(|e| { let di = d[e.source().index()]; let dj = d[e.target().index()]; let cdij = &c * di * dj / (di + dj); &frac_1mz3 + &cdij * 3.0 - &cdij * &cdij * (&zeta3 - 1.0) * 2.0 }) .reduce(|acc, y| acc * y); if let Some(y) = y { phi -= &(y.map(N::ln) * rho_i * 0.5); } } Ok(phi) } }
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/dft/dispersion.rs
.rs
4,488
121
use super::parameter::GcPcSaftFunctionalParameters; use crate::gc_pcsaft::eos::dispersion::{A0, A1, A2, B0, B1, B2}; use crate::hard_sphere::HardSphereProperties; use feos_core::FeosError; use feos_dft::{FunctionalContribution, WeightFunction, WeightFunctionInfo, WeightFunctionShape}; use ndarray::*; use num_dual::DualNum; use std::f64::consts::{FRAC_PI_6, PI}; #[derive(Clone)] pub struct AttractiveFunctional<'a> { parameters: &'a GcPcSaftFunctionalParameters, } impl<'a> AttractiveFunctional<'a> { pub fn new(parameters: &'a GcPcSaftFunctionalParameters) -> Self { Self { parameters } } } impl<'a> FunctionalContribution for AttractiveFunctional<'a> { fn name(&self) -> &'static str { "Attractive functional (GC)" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { let p = &self.parameters; let d = p.hs_diameter(temperature); WeightFunctionInfo::new(p.component_index.clone(), false).add( WeightFunction::new_scaled( d.zip_map(&p.psi_dft, |d, p| d * p), WeightFunctionShape::Theta, ), false, ) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, density: ArrayView2<N>, ) -> Result<Array1<N>, FeosError> { // auxiliary variables let p = &self.parameters; let n = p.m.len(); // temperature dependent segment diameter let d = p.hs_diameter(temperature); // packing fraction let d3m = d.zip_map(&p.m, |d, m| d.powi(3) * (m * FRAC_PI_6)); let eta = density .outer_iter() .zip(&d3m) .map(|(rho, &d3m)| &rho * d3m) .reduce(|a, b| a + b) .unwrap(); // mean segment number let mut m_i: Array1<f64> = Array::zeros(p.component_index[n - 1] + 1); let mut s_i: Array1<f64> = Array::zeros(p.component_index[n - 1] + 1); for (&c, &m) in p.component_index.iter().zip(p.m.iter()) { m_i[c] += m; s_i[c] += 1.0; } let mut rhog: Array1<N> = Array::zeros(eta.raw_dim()); let mut m_bar: Array1<N> = Array::zeros(eta.raw_dim()); for (rho, &c) in density.outer_iter().zip(p.component_index.iter()) { m_bar += &(&rho * m_i[c] / s_i[c]); rhog += &(&rho / s_i[c]); } m_bar.iter_mut().zip(rhog.iter()).for_each(|(m, &r)| { if r.re() > f64::EPSILON { *m /= r } else { *m = N::one() } }); // mixture densities, crosswise interactions of all segments on all chains let mut rho1mix: Array1<N> = Array::zeros(eta.raw_dim()); let mut rho2mix: Array1<N> = 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); rho1mix = rho1mix + (&density.index_axis(Axis(0), i) * &density.index_axis(Axis(0), j)) .mapv(|x| x * (eps_ij * sigma_ij * p.m[i] * p.m[j])); rho2mix = rho2mix + (&density.index_axis(Axis(0), i) * &density.index_axis(Axis(0), j)) .mapv(|x| x * (eps_ij * eps_ij * sigma_ij * p.m[i] * p.m[j])); } } // I1, I2 and C1 let mut i1: Array1<N> = Array::zeros(eta.raw_dim()); let mut i2: Array1<N> = Array::zeros(eta.raw_dim()); let mut eta_i: Array1<N> = 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 * &eta; } let c1 = Zip::from(&eta).and(&m_bar).map_collect(|&eta, &m| { (m * (eta * 8.0 - eta.powi(2) * 2.0) / (eta - 1.0).powi(4) + (eta * (eta * (eta * (eta * 2.0 - 12.0) + 27.0) - 20.0)) / ((eta - 1.0) * (eta - 2.0)).powi(2) * (m - 1.0) + 1.0) .recip() }); // Helmholtz energy density Ok((-rho1mix * i1 * 2.0 - rho2mix * m_bar * c1 * i2) * PI) } }
Rust
3D
feos-org/feos
crates/feos/src/gc_pcsaft/dft/parameter.rs
.rs
1,699
53
use crate::gc_pcsaft::GcPcSaftParameters; use nalgebra::{DMatrix, DVector}; use petgraph::graph::{Graph, UnGraph}; /// psi Parameter for heterosegmented DFT (Mairhofer2018) const PSI_GC_DFT: f64 = 1.5357; /// Parameter set required for the gc-PC-SAFT Helmholtz energy functional. pub struct GcPcSaftFunctionalParameters { pub component_index: DVector<usize>, pub m: DVector<f64>, pub sigma: DVector<f64>, pub epsilon_k: DVector<f64>, pub bonds: UnGraph<(), ()>, pub psi_dft: DVector<f64>, pub sigma_ij: DMatrix<f64>, pub epsilon_k_ij: DMatrix<f64>, } impl GcPcSaftFunctionalParameters { pub fn new(parameters: &GcPcSaftParameters<()>) -> Self { let component_index = parameters.component_index().into(); let [m, sigma, epsilon_k] = parameters.collate(|pr| [pr.m, pr.sigma, pr.epsilon_k]); let [psi_dft] = parameters.collate(|pr| [pr.psi_dft.unwrap_or(PSI_GC_DFT)]); let bonds = Graph::from_edges( parameters .bonds .iter() .map(|b| (b.id1 as u32, b.id2 as u32)), ); // Combining rules dispersion let [k_ij] = parameters.collate_binary(|&br| [br]); let sigma_ij = DMatrix::from_fn(sigma.len(), sigma.len(), |i, j| 0.5 * (sigma[i] + sigma[j])); let epsilon_k_ij = DMatrix::from_fn(epsilon_k.len(), epsilon_k.len(), |i, j| { (epsilon_k[i] * epsilon_k[j]).sqrt() * (1.0 - k_ij[(i, j)]) }); Self { component_index, m, sigma, epsilon_k, bonds, psi_dft, sigma_ij, epsilon_k_ij, } } }
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/mod.rs
.rs
465
14
//! Perturbed-Chain Statistical Associating Fluid Theory (PC-SAFT) //! //! [Gross et al. (2001)](https://doi.org/10.1021/ie0003887) #[cfg(feature = "dft")] mod dft; mod eos; pub(crate) mod parameters; #[cfg(feature = "dft")] pub use dft::{PcSaftFunctional, PcSaftFunctionalContribution}; pub use eos::{DQVariants, PcSaft, PcSaftBinary, PcSaftOptions, PcSaftPure}; pub use parameters::{PcSaftAssociationRecord, PcSaftBinaryRecord, PcSaftParameters, PcSaftRecord};
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/parameters.rs
.rs
23,536
692
use feos_core::FeosResult; use feos_core::parameter::{CombiningRule, FromSegments, FromSegmentsBinary, Parameters}; use nalgebra::{DMatrix, DVector}; use num_traits::Zero; use quantity::{JOULE, KB, KELVIN}; use serde::{Deserialize, Serialize}; use std::ops::AddAssign; /// PC-SAFT pure-component parameters. #[derive(Serialize, Deserialize, Clone)] #[serde(deny_unknown_fields)] pub struct PcSaftRecord { /// Segment number pub m: 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, /// Quadrupole moment in units of Debye * Angstrom #[serde(skip_serializing_if = "f64::is_zero")] #[serde(default)] pub q: f64, /// Entropy scaling coefficients for the viscosity #[serde(skip_serializing_if = "Option::is_none")] viscosity: Option<[f64; 4]>, /// Entropy scaling coefficients for the diffusion coefficient #[serde(skip_serializing_if = "Option::is_none")] diffusion: Option<[f64; 5]>, /// Entropy scaling coefficients for the thermal conductivity #[serde(skip_serializing_if = "Option::is_none")] thermal_conductivity: Option<[f64; 4]>, } impl FromSegments for PcSaftRecord { fn from_segments(segments: &[(Self, f64)]) -> FeosResult<Self> { let mut m = 0.0; let mut sigma3 = 0.0; let mut epsilon_k = 0.0; let mut mu = 0.0; let mut q = 0.0; segments.iter().for_each(|(s, n)| { m += s.m * n; sigma3 += s.m * s.sigma.powi(3) * n; epsilon_k += s.m * s.epsilon_k * n; mu += s.mu * n; q += s.q * n; }); // entropy scaling let mut viscosity = if segments .iter() .all(|(record, _)| record.viscosity.is_some()) { Some([0.0; 4]) } else { None }; let mut thermal_conductivity = if segments .iter() .all(|(record, _)| record.thermal_conductivity.is_some()) { Some([0.0; 4]) } else { None }; let diffusion = if segments .iter() .all(|(record, _)| record.diffusion.is_some()) { Some([0.0; 5]) } else { None }; let n_t = segments.iter().fold(0.0, |acc, (_, n)| acc + n); segments.iter().for_each(|(s, n)| { let s3 = s.m * s.sigma.powi(3) * n; if let Some(p) = viscosity.as_mut() { let [a, b, c, d] = s.viscosity.unwrap(); p[0] += s3 * a; p[1] += s3 * b / sigma3.powf(0.45); p[2] += n * c; p[3] += n * d; } if let Some(p) = thermal_conductivity.as_mut() { let [a, b, c, d] = s.thermal_conductivity.unwrap(); p[0] += n * a; p[1] += n * b; p[2] += n * c; p[3] += n_t * d; } // if let Some(p) = diffusion.as_mut() { // let [a, b, c, d, e] = s.diffusion.unwrap(); // p[0] += s3 * a; // p[1] += s3 * b / sigma3.powf(0.45); // p[2] += *n * c; // p[3] += *n * d; // } }); // correction due to difference in Chapman-Enskog reference between GC and regular formulation. viscosity = viscosity.map(|v| [v[0] - 0.5 * m.ln(), v[1], v[2], v[3]]); Ok(Self { m, sigma: (sigma3 / m).cbrt(), epsilon_k: epsilon_k / m, mu, q, viscosity, diffusion, thermal_conductivity, }) } } impl PcSaftRecord { #[expect(clippy::too_many_arguments)] pub fn new( m: f64, sigma: f64, epsilon_k: f64, mu: f64, q: f64, viscosity: Option<[f64; 4]>, diffusion: Option<[f64; 5]>, thermal_conductivity: Option<[f64; 4]>, ) -> PcSaftRecord { PcSaftRecord { m, sigma, epsilon_k, mu, q, viscosity, diffusion, thermal_conductivity, } } } /// Association parameters for the PC-SAFT equation of state. #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub struct PcSaftAssociationRecord { /// Association volume parameter pub kappa_ab: f64, /// Association energy parameter in units of Kelvin pub epsilon_k_ab: f64, } impl PcSaftAssociationRecord { pub fn new(kappa_ab: f64, epsilon_k_ab: f64) -> Self { Self { kappa_ab, epsilon_k_ab, } } } impl CombiningRule<PcSaftRecord> for PcSaftAssociationRecord { fn combining_rule( _: &PcSaftRecord, _: &PcSaftRecord, parameters_i: &Self, parameters_j: &Self, ) -> Self { let kappa_ab = (parameters_i.kappa_ab * parameters_j.kappa_ab).sqrt(); let epsilon_k_ab = 0.5 * (parameters_i.epsilon_k_ab + parameters_j.epsilon_k_ab); Self { kappa_ab, epsilon_k_ab, } } } /// PC-SAFT binary interaction parameters. #[derive(Serialize, Deserialize, Clone, Copy, Default)] pub struct PcSaftBinaryRecord { /// Binary dispersion interaction parameter pub k_ij: f64, } impl PcSaftBinaryRecord { pub fn new(k_ij: f64) -> Self { Self { k_ij } } } impl FromSegmentsBinary for PcSaftBinaryRecord { fn from_segments_binary(segments: &[(Self, f64, f64)]) -> FeosResult<Self> { let (k_ij, n) = segments.iter().fold((0.0, 0.0), |(k_ij, n), (br, n1, n2)| { let nab = n1 * n2; (k_ij + br.k_ij * nab, n + nab) }); Ok(Self { k_ij: k_ij / n }) } } /// Parameter set required for the PC-SAFT equation of state and Helmholtz energy functional. pub type PcSaftParameters = Parameters<PcSaftRecord, PcSaftBinaryRecord, PcSaftAssociationRecord>; /// The PC-SAFT parameters in an easier accessible format. pub struct PcSaftPars { pub m: DVector<f64>, pub sigma: DVector<f64>, pub epsilon_k: DVector<f64>, pub mu2: DVector<f64>, pub q2: DVector<f64>, pub sigma_ij: DMatrix<f64>, pub epsilon_k_ij: DMatrix<f64>, pub e_k_ij: DMatrix<f64>, pub ndipole: usize, pub nquadpole: usize, pub dipole_comp: Vec<usize>, pub quadpole_comp: Vec<usize>, pub viscosity: Option<DMatrix<f64>>, pub diffusion: Option<DMatrix<f64>>, pub thermal_conductivity: Option<DMatrix<f64>>, } impl PcSaftPars { pub fn new(parameters: &PcSaftParameters) -> Self { let n = parameters.pure.len(); let [m, sigma, epsilon_k] = parameters.collate(|pr| [pr.m, pr.sigma, pr.epsilon_k]); let [viscosity, thermal_conductivity] = parameters.collate(|pr| [pr.viscosity, pr.thermal_conductivity]); let [diffusion] = parameters.collate(|pr| [pr.diffusion]); let [k_ij] = parameters.collate_binary(|br| [br.k_ij]); let [mu2, q2] = parameters.collate(|pr| { [ pr.mu * pr.mu / (pr.m * pr.sigma.powi(3) * pr.epsilon_k) * 1e-19 * (JOULE / KELVIN / KB).into_value(), pr.q * pr.q / (pr.m * pr.sigma.powi(5) * pr.epsilon_k) * 1e-19 * (JOULE / KELVIN / KB).into_value(), ] }); let dipole_comp: Vec<usize> = mu2 .iter() .enumerate() .filter_map(|(i, &mu2)| (mu2.abs() > 0.0).then_some(i)) .collect(); let ndipole = dipole_comp.len(); let quadpole_comp: Vec<usize> = q2 .iter() .enumerate() .filter_map(|(i, &q2)| (q2.abs() > 0.0).then_some(i)) .collect(); let nquadpole = quadpole_comp.len(); let mut sigma_ij = DMatrix::zeros(n, n); let mut e_k_ij = DMatrix::zeros(n, n); for i in 0..n { for j in 0..n { e_k_ij[(i, j)] = (epsilon_k[i] * epsilon_k[j]).sqrt(); sigma_ij[(i, j)] = 0.5 * (sigma[i] + sigma[j]); } } let epsilon_k_ij = (-k_ij).add_scalar(1.0).component_mul(&e_k_ij); let viscosity = if viscosity.iter().any(|v| v.is_none()) { None } else { let mut v = DMatrix::zeros(4, viscosity.len()); for (i, vi) in viscosity.iter().enumerate() { v.column_mut(i) .add_assign(&DVector::from(vi.unwrap().to_vec())); } Some(v) }; let diffusion = if diffusion.iter().any(|v| v.is_none()) { None } else { let mut v = DMatrix::zeros(5, diffusion.len()); for (i, vi) in diffusion.iter().enumerate() { v.column_mut(i) .add_assign(&DVector::from(vi.unwrap().to_vec())); } Some(v) }; let thermal_conductivity = if thermal_conductivity.iter().any(|v| v.is_none()) { None } else { let mut v = DMatrix::zeros(4, thermal_conductivity.len()); for (i, vi) in thermal_conductivity.iter().enumerate() { v.column_mut(i) .add_assign(&DVector::from(vi.unwrap().to_vec())); } Some(v) }; Self { m, sigma, epsilon_k, mu2, q2, sigma_ij, epsilon_k_ij, e_k_ij, ndipole, nquadpole, dipole_comp, quadpole_comp, viscosity, diffusion, thermal_conductivity, } } } #[cfg(test)] pub mod utils { use super::*; use crate::pcsaft::PcSaft; use feos_core::parameter::{BinarySegmentRecord, ChemicalRecord, PureRecord, SegmentRecord}; pub fn propane_parameters() -> PcSaft { let propane_json = r#" { "identifier": { "cas": "74-98-6", "name": "propane", "iupac_name": "propane", "smiles": "CCC", "inchi": "InChI=1/C3H8/c1-3-2/h3H2,1-2H3", "formula": "C3H8" }, "m": 2.001829, "sigma": 3.618353, "epsilon_k": 208.1101, "viscosity": [-0.8013, -1.9972,-0.2907, -0.0467], "thermal_conductivity": [-0.15348, -0.6388, 1.21342, -0.01664], "diffusion": [-0.675163251512047, 0.3212017677695878, 0.100175249144429, 0.0, 0.0], "molarweight": 44.0962 }"#; let propane_record: PureRecord<PcSaftRecord, PcSaftAssociationRecord> = serde_json::from_str(propane_json).expect("Unable to parse json."); PcSaft::new(PcSaftParameters::new_pure(propane_record).unwrap()) } pub fn carbon_dioxide_parameters() -> PcSaftPars { let co2_json = r#" { "identifier": { "cas": "124-38-9", "name": "carbon-dioxide", "iupac_name": "carbon dioxide", "smiles": "O=C=O", "inchi": "InChI=1/CO2/c2-1-3", "formula": "CO2" }, "molarweight": 44.0098, "m": 1.5131, "sigma": 3.1869, "epsilon_k": 163.333, "q": 4.4 }"#; let co2_record: PureRecord<PcSaftRecord, PcSaftAssociationRecord> = serde_json::from_str(co2_json).expect("Unable to parse json."); PcSaftPars::new(&PcSaftParameters::new_pure(co2_record).unwrap()) } pub fn butane_parameters() -> PcSaft { let butane_json = r#" { "identifier": { "cas": "106-97-8", "name": "butane", "iupac_name": "butane", "smiles": "CCCC", "inchi": "InChI=1/C4H10/c1-3-4-2/h3-4H2,1-2H3", "formula": "C4H10" }, "m": 2.331586, "sigma": 3.7086010000000003, "epsilon_k": 222.8774, "molarweight": 58.123 }"#; let butane_record: PureRecord<PcSaftRecord, PcSaftAssociationRecord> = serde_json::from_str(butane_json).expect("Unable to parse json."); PcSaft::new(PcSaftParameters::new_pure(butane_record).unwrap()) } pub fn nonane_parameters() -> PcSaft { let nonane_json = r#" { "identifier": { "cas": "111-84-2", "name": "nonane", "iupac_name": "nonane", "smiles": "CCCCCCCCC", "inchi": "InChI=1S/C9H20/c1-3-5-7-9-8-6-4-2/h3-9H2,1-2H3", "formula": "C9H20" }, "molarweight": 128.258, "m": 4.2079, "sigma": 3.8448, "epsilon_k": 244.51, "viscosity": [ -1.4629, -3.0058, -0.5842, -0.1222 ] }"#; let nonane_record: PureRecord<PcSaftRecord, PcSaftAssociationRecord> = serde_json::from_str(nonane_json).expect("Unable to parse json."); PcSaft::new(PcSaftParameters::new_pure(nonane_record).unwrap()) } pub fn dme_parameters() -> PcSaftPars { let dme_json = r#" { "identifier": { "cas": "115-10-6", "name": "dimethyl-ether", "iupac_name": "methoxymethane", "smiles": "COC", "inchi": "InChI=1/C2H6O/c1-3-2/h1-2H3", "formula": "C2H6O" }, "m": 2.2634, "sigma": 3.2723, "epsilon_k": 210.29, "mu": 1.3, "molarweight": 46.0688 }"#; let dme_record: PureRecord<PcSaftRecord, PcSaftAssociationRecord> = serde_json::from_str(dme_json).expect("Unable to parse json."); PcSaftPars::new(&PcSaftParameters::new_pure(dme_record).unwrap()) } pub fn water_parameters(na: f64) -> PcSaftParameters { let water_json = r#" { "identifier": { "cas": "7732-18-5", "name": "water_np", "iupac_name": "oxidane", "smiles": "O", "inchi": "InChI=1/H2O/h1H2", "formula": "H2O" }, "m": 1.065587, "sigma": 3.000683, "epsilon_k": 366.5121, "molarweight": 18.0152, "association_sites": [ { "kappa_ab": 0.034867983, "epsilon_k_ab": 2500.6706, "na": 1.0, "nb": 1.0 } ] }"#; let mut water_record: PureRecord<PcSaftRecord, PcSaftAssociationRecord> = serde_json::from_str(water_json).expect("Unable to parse json."); water_record.association_sites[0].na = na; PcSaftParameters::new_pure(water_record).unwrap() } pub fn dme_co2_parameters() -> PcSaftPars { let binary_json = r#"[ { "identifier": { "cas": "115-10-6", "name": "dimethyl-ether", "iupac_name": "methoxymethane", "smiles": "COC", "inchi": "InChI=1/C2H6O/c1-3-2/h1-2H3", "formula": "C2H6O" }, "molarweight": 46.0688, "m": 2.2634, "sigma": 3.2723, "epsilon_k": 210.29, "mu": 1.3 }, { "identifier": { "cas": "124-38-9", "name": "carbon-dioxide", "iupac_name": "carbon dioxide", "smiles": "O=C=O", "inchi": "InChI=1/CO2/c2-1-3", "formula": "CO2" }, "molarweight": 44.0098, "m": 1.5131, "sigma": 3.1869, "epsilon_k": 163.333, "q": 4.4 } ]"#; let binary_record: [PureRecord<PcSaftRecord, PcSaftAssociationRecord>; 2] = serde_json::from_str(binary_json).expect("Unable to parse json."); PcSaftPars::new(&PcSaftParameters::new_binary(binary_record, None, vec![]).unwrap()) } pub fn propane_butane_parameters() -> PcSaft { let binary_json = r#"[ { "identifier": { "cas": "74-98-6", "name": "propane", "iupac_name": "propane", "smiles": "CCC", "inchi": "InChI=1/C3H8/c1-3-2/h3H2,1-2H3", "formula": "C3H8" }, "m": 2.0018290000000003, "sigma": 3.618353, "epsilon_k": 208.1101, "viscosity": [-0.8013, -1.9972, -0.2907, -0.0467], "thermal_conductivity": [-0.15348, -0.6388, 1.21342, -0.01664], "diffusion": [-0.675163251512047, 0.3212017677695878, 0.100175249144429, 0.0, 0.0], "molarweight": 44.0962 }, { "identifier": { "cas": "106-97-8", "name": "butane", "iupac_name": "butane", "smiles": "CCCC", "inchi": "InChI=1/C4H10/c1-3-4-2/h3-4H2,1-2H3", "formula": "C4H10" }, "m": 2.331586, "sigma": 3.7086010000000003, "epsilon_k": 222.8774, "viscosity": [-0.9763, -2.2413, -0.3690, -0.0605], "diffusion": [-0.8985872992958458, 0.3428584416613513, 0.10236616087103916, 0.0, 0.0], "molarweight": 58.123 } ]"#; let binary_record: [PureRecord<PcSaftRecord, PcSaftAssociationRecord>; 2] = serde_json::from_str(binary_json).expect("Unable to parse json."); PcSaft::new(PcSaftParameters::new_binary(binary_record, None, vec![]).unwrap()) } pub fn nonane_heptane_parameters() -> PcSaft { let binary_json = r#"[ { "identifier": { "cas": "111-84-2", "name": "nonane", "iupac_name": "nonane", "smiles": "CCCCCCCCC", "inchi": "InChI=1S/C9H20/c1-3-5-7-9-8-6-4-2/h3-9H2,1-2H3", "formula": "C9H20" }, "molarweight": 128.258, "m": 4.2079, "sigma": 3.8448, "epsilon_k": 244.51, "viscosity": [ -1.4629, -3.0058, -0.5842, -0.1222 ] }, { "identifier": { "cas": "142-82-5", "name": "heptane", "iupac_name": "heptane", "smiles": "CCCCCCC", "inchi": "InChI=1S/C7H16/c1-3-5-7-6-4-2/h3-7H2,1-2H3", "formula": "C7H16" }, "molarweight": 100.204, "m": 3.4831, "sigma": 3.8049, "epsilon_k": 238.4, "viscosity": [ -1.2979, -2.6936, -0.4951, -0.0988 ] } ]"#; let binary_record: [PureRecord<PcSaftRecord, PcSaftAssociationRecord>; 2] = serde_json::from_str(binary_json).expect("Unable to parse json."); PcSaft::new(PcSaftParameters::new_binary(binary_record, None, vec![]).unwrap()) } #[test] pub fn test_kij() -> FeosResult<()> { let ch3: String = "CH3".into(); let ch2: String = "CH2".into(); let oh = "OH".into(); let propane = ChemicalRecord::new( Default::default(), vec![ch3.clone(), ch2.clone(), ch3.clone()], None, ); let ethanol = ChemicalRecord::new(Default::default(), vec![ch3, ch2, oh], None); let segment_records = SegmentRecord::from_json("../../parameters/pcsaft/sauer2014_homo.json")?; let kij = [("CH3", "OH", -0.2), ("CH2", "OH", -0.1)]; let binary_segment_records: Vec<_> = kij .iter() .map(|&(id1, id2, k_ij)| { BinarySegmentRecord::new(id1.into(), id2.into(), Some(PcSaftBinaryRecord { k_ij })) }) .collect(); let params = PcSaftParameters::from_segments( vec![propane, ethanol], &segment_records, Some(&binary_segment_records), )?; assert_eq!(params.binary[0].id1, 0); assert_eq!(params.binary[0].id2, 1); assert_eq!(params.binary[0].model_record.k_ij, -0.5 / 9.); Ok(()) } #[test] fn test_association_json() -> FeosResult<()> { let json1 = r#" { "identifier": { "name": "comp1" }, "m": 1.065587, "sigma": 3.000683, "epsilon_k": 366.5121, "association_sites": [ { "kappa_ab": 0.034867983, "epsilon_k_ab": 2500.6706, "na": 1.0, "nb": 1.0 } ] }"#; let record1: PureRecord<PcSaftRecord, PcSaftAssociationRecord> = serde_json::from_str(json1)?; let json2 = r#" { "identifier": { "name": "comp2" }, "m": 1.065587, "sigma": 3.000683, "epsilon_k": 366.5121, "association_sites": [ { "id": "site1", "kappa_ab": 0.034867983, "epsilon_k_ab": 2500.6706, "na": 1.0, "nb": 1.0 }, { "id": "site2", "kappa_ab": 0.01, "epsilon_k_ab": 2200.0, "nb": 1.0 } ] }"#; let record2: PureRecord<PcSaftRecord, PcSaftAssociationRecord> = serde_json::from_str(json2)?; // println!("{record1}"); // println!("{record2}"); assert_eq!( record1.association_sites[0].parameters.unwrap().kappa_ab, record2.association_sites[0].parameters.unwrap().kappa_ab ); Ok(()) } }
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/eos/pcsaft_binary.rs
.rs
19,148
594
use super::dispersion::{A0, A1, A2, B0, B1, B2}; use super::polar::{AD, BD, CD}; use feos_core::{ParametersAD, Residual, StateHD}; use nalgebra::{SVector, U2}; use num_dual::{DualNum, DualSVec64, DualVec, jacobian}; 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 PC-SAFT for a binary mixture. #[derive(Clone, Copy)] pub struct PcSaftBinary<D, const N: usize>(pub ([[D; N]; 2], D)); impl<D, const N: usize> PcSaftBinary<D, N> { pub fn new(parameters: [[D; N]; 2], kij: D) -> Self { Self((parameters, kij)) } } impl<D: DualNum<f64> + Copy, const N: usize> From<&[f64]> for PcSaftBinary<D, N> { fn from(parameters: &[f64]) -> Self { if parameters.len() != 2 * N + 1 { panic!( "This version of PC-SAFT requires exactly {} parameters!", 2 * N + 1 ) } let (Ok(p1), Ok(p2)): (Result<[f64; N], _>, Result<[f64; N], _>) = (parameters[..N].try_into(), parameters[N..2 * N].try_into()) else { unreachable!() }; let kij = D::from(parameters[2 * N]); Self::new([p1.map(D::from), p2.map(D::from)], kij) } } impl ParametersAD<2> for PcSaftBinary<f64, 4> { fn index_parameters_mut<'a, const P: usize>( eos: &'a mut Self::Lifted<DualSVec64<P>>, index: &str, ) -> &'a mut DualSVec64<P> { match index { "k_ij" => &mut eos.0.1, _ => panic!("{index} is not a valid binary PC-SAFT parameter!"), } } } impl ParametersAD<2> for PcSaftBinary<f64, 8> { fn index_parameters_mut<'a, const P: usize>( eos: &'a mut Self::Lifted<DualSVec64<P>>, index: &str, ) -> &'a mut DualSVec64<P> { match index { "k_ij" => &mut eos.0.1, _ => panic!("{index} is not a valid binary PC-SAFT parameter!"), } } } fn hard_sphere<D: DualNum<f64> + Copy>( [m1, m2]: [D; 2], [x1, x2]: [D; 2], [d1, d2]: [D; 2], density: D, ) -> (D, [D; 7], D, D, D) { // Packing fractions let zeta = [0, 1, 2, 3].map(|k| (m1 * x1 * d1.powi(k) + m2 * x2 * d2.powi(k)) * FRAC_PI_6); let zeta_23 = zeta[2] / zeta[3]; let [zeta0, zeta1, zeta2, zeta3] = zeta.map(|z| z * density); let frac_1mz3 = (-zeta3 + 1.0).recip(); let eta = zeta3; let eta2 = eta * eta; let eta3 = eta2 * eta; let etas = [ D::one(), eta, eta2, eta3, eta2 * eta2, eta2 * eta3, eta3 * eta3, ]; // hard sphere let hs = (zeta1 * zeta2 * frac_1mz3 * 3.0 + zeta2.powi(2) * frac_1mz3.powi(2) * zeta_23 + (zeta2 * zeta_23.powi(2) - zeta0) * (-zeta3).ln_1p()) / std::f64::consts::FRAC_PI_6; (hs, etas, zeta2, zeta3, frac_1mz3) } fn hard_chain<D: DualNum<f64> + Copy>( [m1, m2]: [D; 2], [d1, d2]: [D; 2], [rho1, rho2]: [D; 2], zeta2: D, zeta3: D, frac_1mz3: D, ) -> D { let c = zeta2 * frac_1mz3 * frac_1mz3; let g_hs = [d1, d2].map(|d| frac_1mz3 + d * c * 1.5 - (d * c).powi(2) * (zeta3 - 1.0) * 0.5); -(rho1 * (m1 - 1.0) * g_hs[0].ln() + rho2 * (m2 - 1.0) * g_hs[1].ln()) } #[expect(clippy::too_many_arguments)] fn dispersion<D: DualNum<f64> + 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], frac_1mz3: 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, I2 and C1 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]; } let eta_m2 = frac_1mz3 * frac_1mz3; let c1 = (m * (etas[1] * 8.0 - etas[2] * 2.0) * eta_m2 * eta_m2 + 1.0 - (m - 1.0) * (etas[1] * 20.0 - etas[2] * 27.0 + etas[3] * 12.0 - etas[4] * 2.0) / ((etas[1] - 1.0) * (etas[1] - 2.0)).powi(2)) .recip(); // 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<D: DualNum<f64> + Copy>( [m1, m2]: [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 { let mu_term1 = mu1 * mu1 / (m1 * temperature * 1.380649e-4) * rho1; let mu_term2 = mu2 * mu2 / (m2 * 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<D: DualNum<f64> + 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<D: DualNum<f64> + Copy>( temperature: D, rho: [D; 2], m: [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]; // density and composition let [rho1, rho2] = rho; let density = rho1 + rho2; let x = [rho1 / density, rho2 / density]; // hard sphere let (hs, etas, zeta2, zeta3, frac_1mz3) = hard_sphere(m, x, d, density); // hard chain let hc = hard_chain(m, d, rho, zeta2, zeta3, frac_1mz3); // dispersion let (disp, sigma_3, epsilon_k_mix) = dispersion(m, sigma, epsilon_k, kij, x, t_inv, rho, etas, frac_1mz3); // dipoles let polar = dipoles(m, 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); hs + hc + disp + polar + assoc } else { hs + hc + disp + polar } } impl<D: DualNum<f64> + Copy> Residual<U2, D> for PcSaftBinary<D, 4> { fn components(&self) -> usize { 2 } type Real = PcSaftBinary<f64, 4>; type Lifted<D2: DualNum<f64, Inner = D> + Copy> = PcSaftBinary<D2, 4>; fn re(&self) -> Self::Real { PcSaftBinary(( self.0.0.each_ref().map(|x| x.each_ref().map(D::re)), self.0.1.re(), )) } fn lift<D2: DualNum<f64, Inner = D> + Copy>(&self) -> Self::Lifted<D2> { PcSaftBinary(( 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, 2>) -> D { let &([p1, p2], _) = &self.0; let [x1, x2] = molefracs.data.0[0]; let [m1, sigma1, ..] = p1; let [m2, sigma2, ..] = p2; ((m1 * sigma1.powi(3) * x1 + m2 * sigma2.powi(3) * x2) * FRAC_PI_6).recip() * MAX_ETA } fn reduced_helmholtz_energy_density_contributions( &self, state: &StateHD<D, U2>, ) -> Vec<(&'static str, D)> { vec![( "PC-SAFT (binary, non-assoc)", self.reduced_residual_helmholtz_energy_density(state), )] } fn reduced_residual_helmholtz_energy_density(&self, state: &StateHD<D, U2>) -> D { let ([p1, p2], kij) = self.0; let [m1, sigma1, epsilon_k1, mu1] = p1; let [m2, sigma2, epsilon_k2, mu2] = p2; let m = [m1, m2]; 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, m, sigma, epsilon_k, mu, kij, None) } } impl<D: DualNum<f64> + Copy> Residual<U2, D> for PcSaftBinary<D, 8> { fn components(&self) -> usize { 2 } type Real = PcSaftBinary<f64, 8>; type Lifted<D2: DualNum<f64, Inner = D> + Copy> = PcSaftBinary<D2, 8>; fn re(&self) -> Self::Real { PcSaftBinary(( self.0.0.each_ref().map(|x| x.each_ref().map(D::re)), self.0.1.re(), )) } fn lift<D2: DualNum<f64, Inner = D> + Copy>(&self) -> Self::Lifted<D2> { PcSaftBinary(( 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, 2>) -> D { let &([p1, p2], _) = &self.0; let [x1, x2] = molefracs.data.0[0]; let [m1, sigma1, ..] = p1; let [m2, sigma2, ..] = p2; ((m1 * sigma1.powi(3) * x1 + m2 * sigma2.powi(3) * x2) * FRAC_PI_6).recip() * MAX_ETA } fn reduced_helmholtz_energy_density_contributions( &self, state: &StateHD<D, U2>, ) -> Vec<(&'static str, D)> { vec![( "PC-SAFT (binary)", self.reduced_residual_helmholtz_energy_density(state), )] } fn reduced_residual_helmholtz_energy_density(&self, state: &StateHD<D, U2>) -> D { let ([p1, p2], kij) = self.0; let [ m1, sigma1, epsilon_k1, mu1, kappa_ab1, epsilon_k_ab1, na1, nb1, ] = p1; let [ m2, sigma2, epsilon_k2, mu2, kappa_ab2, epsilon_k_ab2, na2, nb2, ] = p2; let m = [m1, m2]; 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, m, sigma, epsilon_k, mu, kij, assoc_params, ) } } #[cfg(test)] pub mod test { use super::PcSaftBinary; use crate::pcsaft::{ PcSaft, PcSaftAssociationRecord, PcSaftBinaryRecord, PcSaftParameters, PcSaftRecord, }; use approx::assert_relative_eq; use feos_core::parameter::{AssociationRecord, PureRecord}; use feos_core::{Contributions::Total, FeosResult, State}; use nalgebra::{dvector, vector}; use quantity::{KELVIN, KILO, METER, MOL}; pub fn pcsaft_binary() -> FeosResult<(PcSaftBinary<f64, 8>, PcSaft)> { let params = [ [1.5, 3.4, 180.0, 2.2, 0.03, 2500., 2.0, 1.0], [2.5, 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, PcSaftRecord::new(p[0], p[1], p[2], p[3], 0.0, None, None, None), vec![AssociationRecord::new( Some(PcSaftAssociationRecord::new(p[4], p[5])), p[6], p[7], 0.0, )], ) }); let params_feos = PcSaftParameters::new_binary(records, Some(PcSaftBinaryRecord::new(kij)), vec![])?; let eos = PcSaft::new(params_feos); Ok((PcSaftBinary::new(params, kij), eos)) } #[test] fn test_pcsaft_binary() -> FeosResult<()> { let (pcsaft, eos) = pcsaft_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(&pcsaft, 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(); for (s, c) in state.residual_molar_helmholtz_energy_contributions() { println!("{s:20} {c}"); } 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(()) } }
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/eos/mod.rs
.rs
31,417
939
use super::parameters::{PcSaftAssociationRecord, PcSaftParameters, PcSaftPars}; use crate::association::{Association, AssociationStrength}; use crate::hard_sphere::{HardSphere, HardSphereProperties, MonomerShape}; use feos_core::{ EntropyScaling, Molarweight, ReferenceSystem, Residual, ResidualDyn, StateHD, Subset, }; use nalgebra::DVector; use num_dual::{DualNum, partial2}; use quantity::ad::first_derivative; use quantity::*; use std::f64::consts::{FRAC_PI_6, PI}; pub(crate) mod dispersion; pub(crate) mod hard_chain; mod pcsaft_binary; mod pcsaft_pure; pub(crate) mod polar; use dispersion::Dispersion; use hard_chain::HardChain; pub use pcsaft_binary::PcSaftBinary; pub use pcsaft_pure::PcSaftPure; pub use polar::DQVariants; use polar::{Dipole, DipoleQuadrupole, Quadrupole}; /// Customization options for the PC-SAFT equation of state and functional. #[derive(Copy, Clone)] pub struct PcSaftOptions { pub max_eta: f64, pub max_iter_cross_assoc: usize, pub tol_cross_assoc: f64, pub dq_variant: DQVariants, } impl Default for PcSaftOptions { fn default() -> Self { Self { max_eta: 0.5, max_iter_cross_assoc: 50, tol_cross_assoc: 1e-10, dq_variant: DQVariants::DQ35, } } } /// PC-SAFT equation of state. pub struct PcSaft { pub parameters: PcSaftParameters, params: PcSaftPars, options: PcSaftOptions, hard_chain: bool, dipole: bool, quadrupole: bool, dipole_quadrupole: bool, association: Option<Association>, } impl PcSaft { pub fn new(parameters: PcSaftParameters) -> Self { Self::with_options(parameters, PcSaftOptions::default()) } pub fn with_options(parameters: PcSaftParameters, options: PcSaftOptions) -> Self { let params = PcSaftPars::new(&parameters); let hard_chain = params.m.iter().any(|m| (m - 1.0).abs() > 1e-15); let dipole = params.ndipole > 0; let quadrupole = params.nquadpole > 0; let dipole_quadrupole = params.ndipole > 0 && params.nquadpole > 0; let association = (!parameters.association.is_empty()) .then(|| Association::new(options.max_iter_cross_assoc, options.tol_cross_assoc)); Self { parameters, params, options, hard_chain, dipole, quadrupole, dipole_quadrupole, association, } } } impl ResidualDyn for PcSaft { fn components(&self) -> usize { self.parameters.pure.len() } fn compute_max_density<D: DualNum<f64> + Copy>(&self, molefracs: &DVector<D>) -> D { let msigma3 = self .params .m .component_mul(&self.params.sigma.map(|v| v.powi(3))); (msigma3.map(D::from).dot(molefracs) * FRAC_PI_6).recip() * self.options.max_eta } fn reduced_helmholtz_energy_density_contributions<D: DualNum<f64> + Copy>( &self, state: &StateHD<D>, ) -> Vec<(&'static str, D)> { let mut v = Vec::with_capacity(7); let d = self.params.hs_diameter(state.temperature); v.push(( "Hard Sphere", HardSphere.helmholtz_energy_density(&self.params, state), )); if self.hard_chain { v.push(( "Hard Chain", HardChain.helmholtz_energy_density(&self.params, state), )) } v.push(( "Dispersion", Dispersion.helmholtz_energy_density(&self.params, state), )); if self.dipole { v.push(( "Dipole", Dipole.helmholtz_energy_density(&self.params, state), )) } if self.quadrupole { v.push(( "Quadrupole", Quadrupole.helmholtz_energy_density(&self.params, state), )) } if self.dipole_quadrupole { v.push(( "DipoleQuadrupole", DipoleQuadrupole.helmholtz_energy_density( &self.params, state, self.options.dq_variant, ), )) } if let Some(association) = self.association.as_ref() { v.push(( "Association", association.helmholtz_energy_density( &self.params, &self.parameters.association, state, &d, ), )) } v } } impl Subset for PcSaft { fn subset(&self, component_list: &[usize]) -> Self { Self::with_options(self.parameters.subset(component_list), self.options) } } impl Molarweight for PcSaft { fn molar_weight(&self) -> MolarWeight<DVector<f64>> { self.parameters.molar_weight.clone() } } impl HardSphereProperties for PcSaftPars { fn monomer_shape<N: DualNum<f64>>(&self, _: N) -> MonomerShape<'_, N> { MonomerShape::NonSpherical(self.m.map(N::from)) } fn hs_diameter<D: DualNum<f64> + Copy>(&self, temperature: D) -> DVector<D> { 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 PcSaftPars { type Record = PcSaftAssociationRecord; fn association_strength_ij<D: DualNum<f64> + Copy>( &self, temperature: D, comp_i: usize, comp_j: usize, association_parameters_ij: &Self::Record, ) -> D { let f_ab = (temperature.recip() * association_parameters_ij.epsilon_k_ab).exp_m1(); let k_ab = association_parameters_ij.kappa_ab * (self.sigma[comp_i] * self.sigma[comp_j]).powf(1.5); f_ab * k_ab } } fn omega11(t: f64) -> f64 { 1.06036 * t.powf(-0.15610) + 0.19300 * (-0.47635 * t).exp() + 1.03587 * (-1.52996 * t).exp() + 1.76474 * (-3.89411 * t).exp() } fn omega22(t: f64) -> f64 { 1.16145 * t.powf(-0.14874) + 0.52487 * (-0.77320 * t).exp() + 2.16178 * (-2.43787 * t).exp() - 6.435e-4 * t.powf(0.14874) * (18.0323 * t.powf(-0.76830) - 7.27371).sin() } #[inline] fn chapman_enskog_thermal_conductivity( temperature: Temperature, molarweight: MolarWeight, m: f64, sigma: f64, epsilon_k: f64, ) -> ThermalConductivity { let t = temperature.into_reduced(); 0.083235 * (t * m / molarweight.convert_to(GRAM / MOL)).sqrt() / sigma.powi(2) / omega22(t / epsilon_k) * WATT / METER / KELVIN } impl EntropyScaling for PcSaft { fn viscosity_reference( &self, temperature: Temperature, _: Volume, moles: &Moles<DVector<f64>>, ) -> Viscosity { let p = &self.params; let mw = &self.parameters.molar_weight; let x = (moles / moles.sum()).into_value(); let ce: Vec<_> = (0..self.components()) .map(|i| { let tr = (temperature / p.epsilon_k[i] / KELVIN).into_value(); 5.0 / 16.0 * (mw.get(i) * KB / NAV * temperature / PI).sqrt() / omega22(tr) / (p.sigma[i] * ANGSTROM).powi::<2>() }) .collect(); let mut ce_mix = 0.0 * MILLI * PASCAL * SECOND; for i in 0..self.components() { let denom: f64 = (0..self.components()) .map(|j| { x[j] * (1.0 + (ce[i] / ce[j]).into_value().sqrt() * (mw.get(j) / mw.get(i)).powf(1.0 / 4.0)) .powi(2) / (8.0 * (1.0 + (mw.get(i) / mw.get(j)).into_value())).sqrt() }) .sum(); ce_mix += ce[i] * x[i] / denom } ce_mix } fn viscosity_correlation(&self, s_res: f64, x: &DVector<f64>) -> f64 { let coefficients = self .params .viscosity .as_ref() .expect("Missing viscosity coefficients."); let m = x.dot(&self.params.m); let s = s_res / m; let pref = x.component_mul(&self.params.m) / m; let a = coefficients.row(0).transpose().dot(x); let b = coefficients.row(1).transpose().dot(&pref); let c = coefficients.row(2).transpose().dot(&pref); let d = coefficients.row(3).transpose().dot(&pref); a + b * s + c * s.powi(2) + d * s.powi(3) } fn diffusion_reference( &self, temperature: Temperature, volume: Volume, moles: &Moles<DVector<f64>>, ) -> Diffusivity { if self.components() != 1 { panic!("Diffusion coefficients in PC-SAFT are only implemented for pure components!"); } let p = &self.params; let mw = &self.parameters.molar_weight; let density = moles.sum() / volume; let res: Vec<_> = (0..self.components()) .map(|i| { let tr = (temperature / p.epsilon_k[i] / KELVIN).into_value(); 3.0 / 8.0 / (p.sigma[i] * ANGSTROM).powi::<2>() / omega11(tr) / (density * NAV) * (temperature * RGAS / PI / mw.get(i) / p.m[i]).sqrt() }) .collect(); res[0] } fn diffusion_correlation(&self, s_res: f64, x: &DVector<f64>) -> f64 { if self.components() != 1 { panic!("Diffusion coefficients in PC-SAFT are only implemented for pure components!"); } let coefficients = self .params .diffusion .as_ref() .expect("Missing diffusion coefficients."); let m = x.dot(&self.params.m); let s = s_res / m; let pref = x.component_mul(&self.params.m) / m; let a = coefficients.row(0).transpose().dot(x); let b = coefficients.row(1).transpose().dot(&pref); let c = coefficients.row(2).transpose().dot(&pref); let d = coefficients.row(3).transpose().dot(&pref); let e = coefficients.row(4).transpose().dot(&pref); a + b * s - c * (1.0 - s.exp()) * s.powi(2) - d * s.powi(4) - e * s.powi(8) } // Equation 4 of DOI: 10.1021/acs.iecr.9b04289 fn thermal_conductivity_reference( &self, temperature: Temperature, volume: Volume, moles: &Moles<DVector<f64>>, ) -> ThermalConductivity { if self.components() != 1 { panic!("Thermal conductivity in PC-SAFT is only implemented for pure components!"); } let p = &self.params; let mws = self.molar_weight(); let (_, s_res) = first_derivative( partial2( |t, &v, n| -self.residual_helmholtz_energy_unit(t, v, n) / n.sum(), &volume, moles, ), temperature, ); let res: Vec<_> = (0..self.components()) .map(|i| { let tr = (temperature / p.epsilon_k[i] / KELVIN).into_value(); let s_res_reduced = s_res.into_reduced() / p.m[i]; let ref_ce = chapman_enskog_thermal_conductivity( temperature, mws.get(i), p.m[i], p.sigma[i], p.epsilon_k[i], ); let alpha_visc = (-s_res_reduced / -0.5).exp(); let ref_ts = (-0.0167141 * tr / p.m[i] + 0.0470581 * (tr / p.m[i]).powi(2)) * (p.m[i] * p.m[i] * p.sigma[i].powi(3) * p.epsilon_k[i]) * 1e-5 * WATT / METER / KELVIN; ref_ce + ref_ts * alpha_visc }) .collect(); res[0] } fn thermal_conductivity_correlation(&self, s_res: f64, x: &DVector<f64>) -> f64 { if self.components() != 1 { panic!("Thermal conductivity in PC-SAFT is only implemented for pure components!"); } let coefficients = self .params .thermal_conductivity .as_ref() .expect("Missing thermal conductivity coefficients"); let m = x.dot(&self.params.m); let s = s_res / m; let pref = x.component_mul(&self.params.m) / m; let a = coefficients.row(0).transpose().dot(x); let b = coefficients.row(1).transpose().dot(&pref); let c = coefficients.row(2).transpose().dot(&pref); let d = coefficients.row(3).transpose().dot(&pref); a + b * s + c * (1.0 - s.exp()) + d * s.powi(2) } } #[cfg(test)] mod tests { use super::*; use crate::pcsaft::parameters::utils::{ butane_parameters, nonane_heptane_parameters, nonane_parameters, propane_butane_parameters, propane_parameters, }; use approx::assert_relative_eq; use feos_core::*; use nalgebra::dvector; use quantity::{BAR, KELVIN, METER, PASCAL, RGAS}; #[test] fn ideal_gas_pressure() { let e = &propane_parameters(); let t = 200.0 * KELVIN; let v = 1e-3 * METER.powi::<3>(); let n = dvector![1.0] * MOL; let s = State::new_nvt(&e, t, v, &n).unwrap(); let p_ig = s.total_moles * RGAS * t / v; assert_relative_eq!(s.pressure(Contributions::IdealGas), p_ig, epsilon = 1e-10); assert_relative_eq!( s.pressure(Contributions::IdealGas) + s.pressure(Contributions::Residual), s.pressure(Contributions::Total), epsilon = 1e-10 ); } #[test] fn ideal_gas_heat_capacity_joback() { let e = &propane_parameters(); let t = 200.0 * KELVIN; let v = 1e-3 * METER.powi::<3>(); let n = dvector![1.0] * MOL; let s = State::new_nvt(&e, t, v, &n).unwrap(); let p_ig = s.total_moles * RGAS * t / v; assert_relative_eq!(s.pressure(Contributions::IdealGas), p_ig, epsilon = 1e-10); assert_relative_eq!( s.pressure(Contributions::IdealGas) + s.pressure(Contributions::Residual), s.pressure(Contributions::Total), epsilon = 1e-10 ); } #[test] fn hard_sphere() { let t = 250.0; let v = 1000.0; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a_rust = HardSphere .helmholtz_energy_density(&propane_parameters().params as &PcSaftPars, &s) * v; assert_relative_eq!(a_rust, 0.410610492598808, epsilon = 1e-10); } #[test] fn hard_sphere_mix() { let t = 250.0; let v = 1000.0; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a1 = HardSphere.helmholtz_energy_density(&propane_parameters().params as &PcSaftPars, &s); let a2 = HardSphere.helmholtz_energy_density(&butane_parameters().params as &PcSaftPars, &s); let s1m = StateHD::new(t, v, &dvector![n, 0.0]); let a1m = HardSphere .helmholtz_energy_density(&propane_butane_parameters().params as &PcSaftPars, &s1m); let s2m = StateHD::new(t, v, &dvector![0.0, n]); let a2m = HardSphere .helmholtz_energy_density(&propane_butane_parameters().params as &PcSaftPars, &s2m); assert_relative_eq!(a1, a1m, epsilon = 1e-14); assert_relative_eq!(a2, a2m, epsilon = 1e-14); } #[test] fn new_tpn() { let e = &propane_parameters(); let t = 300.0 * KELVIN; let p = BAR; let m = dvector![1.5] * MOL; let s = State::new_npt(&e, t, p, &m, None); let p_calc = if let Ok(state) = s { state.pressure(Contributions::Total) } else { 0.0 * PASCAL }; assert_relative_eq!(p, p_calc, epsilon = 1e-6); } #[test] fn vle_pure() { let e = &propane_parameters(); let t = 300.0 * KELVIN; let vle = PhaseEquilibrium::pure(&e, t, None, Default::default()); if let Ok(v) = vle { assert_relative_eq!( v.vapor().pressure(Contributions::Total), v.liquid().pressure(Contributions::Total), epsilon = 1e-6 ) } } #[test] fn critical_point() { let e = &propane_parameters(); let t = 300.0 * KELVIN; let cp = State::critical_point(&e, None, Some(t), None, Default::default()); if let Ok(v) = cp { assert_relative_eq!(v.temperature, 375.1244078318015 * KELVIN, epsilon = 1e-8) } } #[test] fn mix_single() { let e1 = &propane_parameters(); let e2 = &butane_parameters(); let e12 = &propane_butane_parameters(); let t = 300.0 * KELVIN; let v = 0.02456883872966545 * METER.powi::<3>(); let m1 = dvector![2.0] * MOL; let m1m = dvector![2.0, 0.0] * MOL; let m2m = dvector![0.0, 2.0] * MOL; let s1 = State::new_nvt(&e1, t, v, &m1).unwrap(); let s2 = State::new_nvt(&e2, t, v, &m1).unwrap(); let s1m = State::new_nvt(&e12, t, v, &m1m).unwrap(); let s2m = State::new_nvt(&e12, t, v, &m2m).unwrap(); assert_relative_eq!( s1.pressure(Contributions::Total), s1m.pressure(Contributions::Total), epsilon = 1e-12 ); assert_relative_eq!( s2.pressure(Contributions::Total), s2m.pressure(Contributions::Total), epsilon = 1e-12 ) } #[test] fn viscosity() -> FeosResult<()> { let e = &propane_parameters(); let t = 300.0 * KELVIN; let p = BAR; let n = dvector![1.0] * MOL; let s = State::new_npt(&e, t, p, &n, None)?; assert_relative_eq!( s.viscosity(), 0.00797 * MILLI * PASCAL * SECOND, epsilon = 1e-5 ); assert_relative_eq!( s.ln_viscosity_reduced(), (s.viscosity() / e.viscosity_reference(s.temperature, s.volume, &s.moles)) .into_value() .ln(), epsilon = 1e-15 ); Ok(()) } #[test] fn viscosity_mix() -> FeosResult<()> { // Test case: compare fig 15 of Lötgering-Lin 2018 (https://doi.org/10.1021/acs.iecr.7b04871) let e = &nonane_heptane_parameters(); let nonane = &nonane_parameters(); let t = 303.15 * KELVIN; let p = 500.0 * BAR; let n = dvector![0.25, 0.75] * MOL; let viscosity_mix = State::new_npt(&e, t, p, &n, None)?.viscosity(); let viscosity_paper = 0.68298 * MILLI * PASCAL * SECOND; assert_relative_eq!(viscosity_paper, viscosity_mix, epsilon = 1e-8); // Make sure pure substance case is recovered let n_pseudo_mix = dvector![1.0, 0.0] * MOL; let viscosity_pseudo_mix = State::new_npt(&e, t, p, &n_pseudo_mix, None)?.viscosity(); let n_nonane = dvector![1.0] * MOL; let viscosity_nonane = State::new_npt(&nonane, t, p, &n_nonane, None)?.viscosity(); assert_relative_eq!(viscosity_pseudo_mix, viscosity_nonane, epsilon = 1e-15); Ok(()) } #[test] fn diffusion() -> FeosResult<()> { let e = &propane_parameters(); let t = 300.0 * KELVIN; let p = BAR; let n = dvector![1.0] * MOL; let s = State::new_npt(&e, t, p, &n, None)?; assert_relative_eq!( s.diffusion(), 0.01505 * (CENTI * METER).powi::<2>() / SECOND, epsilon = 1e-5 ); assert_relative_eq!( s.ln_diffusion_reduced(), (s.diffusion() / e.diffusion_reference(s.temperature, s.volume, &s.moles)) .into_value() .ln(), epsilon = 1e-15 ); Ok(()) } } #[cfg(test)] mod tests_parameter_fit { use super::pcsaft_binary::test::pcsaft_binary; use super::pcsaft_pure::test::pcsaft; use super::*; use approx::assert_relative_eq; use feos_core::DensityInitialization::Liquid; use feos_core::{Contributions, PropertiesAD, ReferenceSystem}; use feos_core::{FeosResult, ParametersAD, PhaseEquilibrium, State}; use nalgebra::{U1, U3, U8, vector}; use num_dual::{DualStruct, DualVec}; use quantity::{BAR, KELVIN, LITER, MOL, PASCAL}; fn pcsaft_non_assoc() -> PcSaftPure<f64, 4> { let m = 1.5; let sigma = 3.4; let epsilon_k = 180.0; let mu = 2.2; let params = [m, sigma, epsilon_k, mu]; PcSaftPure(params) } #[test] fn test_vapor_pressure_derivatives() -> FeosResult<()> { let pcsaft_params = [ "m", "sigma", "epsilon_k", "mu", "kappa_ab", "epsilon_k_ab", "na", "nb", ]; let (pcsaft, _) = pcsaft()?; let pcsaft_ad = pcsaft.named_derivatives(pcsaft_params); let temperature = 250.0 * KELVIN; let p = pcsaft_ad.vapor_pressure(temperature)?; let p = p.convert_into(PASCAL); let (p, grad) = (p.re, p.eps.unwrap_generic(U8, U1)); println!("{p:.5}"); println!("{grad:.5?}"); for (i, par) in pcsaft_params.into_iter().enumerate() { let mut params = pcsaft.0; let h = params[i] * 1e-7; params[i] += h; let pcsaft_h = PcSaftPure(params); let (p_h, _) = PhaseEquilibrium::pure_t(&pcsaft_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_vapor_pressure_derivatives_fit() -> FeosResult<()> { let pcsaft = pcsaft_non_assoc(); let pcsaft_ad = pcsaft.named_derivatives(["m", "sigma", "epsilon_k"]); let temperature = 150.0 * KELVIN; let p = pcsaft_ad.vapor_pressure(temperature)?; 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 ["m", "sigma", "epsilon_k"].into_iter().enumerate() { let mut params = pcsaft.0; let h = params[i] * 1e-7; params[i] += h; let pcsaft_h = PcSaftPure(params); let (p_h, _) = PhaseEquilibrium::pure_t(&pcsaft_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_equilibrium_liquid_density_derivatives_fit() -> FeosResult<()> { let pcsaft = pcsaft_non_assoc(); let pcsaft_ad = pcsaft.named_derivatives(["m", "sigma", "epsilon_k"]); let temperature = 150.0 * KELVIN; let (p, rho) = pcsaft_ad.equilibrium_liquid_density(temperature)?; let p = p.convert_into(PASCAL); let rho = rho.convert_into(MOL / LITER); let (p, p_grad) = (p.re, p.eps.unwrap_generic(U3, U1)); let (rho, rho_grad) = (rho.re, rho.eps.unwrap_generic(U3, U1)); println!("{p:.5} {rho:.5}"); println!("{p_grad:.5?}"); println!("{rho_grad:.5?}"); for (i, par) in ["m", "sigma", "epsilon_k"].into_iter().enumerate() { let mut params = pcsaft.0; let h = params[i] * 1e-7; params[i] += h; let pcsaft_h = PcSaftPure(params); let (p_h, [_, rho_h]) = PhaseEquilibrium::pure_t(&pcsaft_h, temperature, None, Default::default())?; let dp_h = (p_h.convert_into(PASCAL) - p) / h; let drho_h = (rho_h.convert_into(MOL / LITER) - rho) / h; let dp = p_grad[i]; let drho = rho_grad[i]; println!( "{par:12}: {:11.5} {:11.5} {:.3e} {:11.5} {:11.5} {:.3e}", dp_h, dp, ((dp_h - dp) / dp).abs(), drho_h, drho, ((drho_h - drho) / drho).abs() ); assert_relative_eq!(dp, dp_h, max_relative = 1e-6); } Ok(()) } #[test] fn test_liquid_density_derivatives_fit() -> FeosResult<()> { let pcsaft = pcsaft_non_assoc(); let pcsaft_ad = pcsaft.named_derivatives(["m", "sigma", "epsilon_k"]); let temperature = 150.0 * KELVIN; let pressure = BAR; let rho = pcsaft_ad.liquid_density(temperature, pressure)?; 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 ["m", "sigma", "epsilon_k"].into_iter().enumerate() { let mut params = pcsaft.0; let h = params[i] * 1e-7; params[i] += h; let pcsaft_h = PcSaftPure(params); let rho_h = State::new_xpt( &pcsaft_h, temperature, pressure, &vector![1.0], 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(()) } #[test] fn test_bubble_point_pressure() -> FeosResult<()> { let (pcsaft, _) = pcsaft_binary()?; let pcsaft_ad = pcsaft.named_derivatives(["k_ij"]); let temperature = 500.0 * KELVIN; let x = vector![0.5, 0.5]; let p = pcsaft_ad.bubble_point_pressure(temperature, None, x)?; let p = p.convert_into(BAR); let (p, [[grad]]) = (p.re, p.eps.unwrap_generic(U1, U1).data.0); println!("{p:.5}"); println!("{grad:.5?}"); let (params, mut kij) = pcsaft.0; let h = 1e-7; kij += h; let pcsaft_h = PcSaftBinary::new(params, kij); let p_h = PhaseEquilibrium::bubble_point( &pcsaft_h, temperature, &x, None, None, Default::default(), )? .vapor() .pressure(Contributions::Total); let dp_h = (p_h.convert_into(BAR) - p) / h; println!( "k_ij: {:11.5} {:11.5} {:.3e}", dp_h, grad, ((dp_h - grad) / grad).abs() ); assert_relative_eq!(grad, dp_h, max_relative = 1e-6); Ok(()) } #[test] fn test_dew_point_pressure() -> FeosResult<()> { let (pcsaft, _) = pcsaft_binary()?; let pcsaft_ad = pcsaft.named_derivatives(["k_ij"]); let temperature = 500.0 * KELVIN; let y = vector![0.5, 0.5]; let p = pcsaft_ad.dew_point_pressure(temperature, None, y)?; let p = p.convert_into(BAR); let (p, [[grad]]) = (p.re, p.eps.unwrap_generic(U1, U1).data.0); println!("{p:.5}"); println!("{grad:.5?}"); let (params, mut kij) = pcsaft.0; let h = 1e-7; kij += h; let pcsaft_h = PcSaftBinary::new(params, kij); let p_h = PhaseEquilibrium::dew_point( &pcsaft_h, temperature, &y, None, None, Default::default(), )? .vapor() .pressure(Contributions::Total); let dp_h = (p_h.convert_into(BAR) - p) / h; println!( "k_ij: {:11.5} {:11.5} {:.3e}", dp_h, grad, ((dp_h - grad) / grad).abs() ); assert_relative_eq!(grad, dp_h, max_relative = 1e-6); Ok(()) } #[test] fn test_bubble_point_temperature() -> FeosResult<()> { let (pcsaft, _) = pcsaft_binary()?; let pcsaft_ad = pcsaft.named_derivatives(["k_ij"]); let pressure = Pressure::from_reduced(DualVec::from(45. * BAR.into_reduced())); let t_init = Temperature::from_reduced(DualVec::from(500.0)); let x = vector![0.5, 0.5].map(DualVec::from); let t = PhaseEquilibrium::bubble_point( &pcsaft_ad, pressure, &x, Some(t_init), None, Default::default(), )? .vapor() .temperature; let t = t.convert_into(KELVIN); let (t, [[grad]]) = (t.re, t.eps.unwrap_generic(U1, U1).data.0); println!("{t:.5}"); println!("{grad:.5?}"); let (params, mut kij) = pcsaft.0; let h = 1e-7; kij += h; let pcsaft_h = PcSaftBinary::new(params, kij); let t_h = PhaseEquilibrium::bubble_point( &pcsaft_h, pressure.re(), &x.map(|x| x.re()), Some(t_init.re()), None, Default::default(), )? .vapor() .temperature; let dt_h = (t_h.convert_into(KELVIN) - t) / h; println!( "k_ij: {:11.5} {:11.5} {:.3e}", dt_h, grad, ((dt_h - grad) / grad).abs() ); assert_relative_eq!(grad, dt_h, max_relative = 1e-6); Ok(()) } #[test] fn test_dew_point_temperature() -> FeosResult<()> { let (pcsaft, _) = pcsaft_binary()?; let pcsaft_ad = pcsaft.named_derivatives(["k_ij"]); let pressure = Pressure::from_reduced(DualVec::from(45. * BAR.into_reduced())); let t_init = Temperature::from_reduced(DualVec::from(500.0)); let x = vector![0.5, 0.5].map(DualVec::from); let t = PhaseEquilibrium::dew_point( &pcsaft_ad, pressure, &x, Some(t_init), None, Default::default(), )? .vapor() .temperature; let t = t.convert_into(KELVIN); let (t, [[grad]]) = (t.re, t.eps.unwrap_generic(U1, U1).data.0); println!("{t:.5}"); println!("{grad:.5?}"); let (params, mut kij) = pcsaft.0; let h = 1e-7; kij += h; let pcsaft_h = PcSaftBinary::new(params, kij); let t_h = PhaseEquilibrium::dew_point( &pcsaft_h, pressure.re(), &x.map(|x| x.re()), Some(t_init.re()), None, Default::default(), )? .vapor() .temperature; let dt_h = (t_h.convert_into(KELVIN) - t) / h; println!( "k_ij: {:11.5} {:11.5} {:.3e}", dt_h, grad, ((dt_h - grad) / grad).abs() ); assert_relative_eq!(grad, dt_h, max_relative = 1e-6); Ok(()) } }
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/eos/hard_chain.rs
.rs
2,159
62
use crate::hard_sphere::HardSphereProperties; use crate::pcsaft::parameters::PcSaftPars; use feos_core::StateHD; use num_dual::*; pub struct HardChain; impl HardChain { #[inline] pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &PcSaftPars, state: &StateHD<D>, ) -> D { let d = parameters.hs_diameter(state.temperature); let [zeta2, zeta3] = parameters.zeta(state.temperature, &state.partial_density, [2, 3]); let frac_1mz3 = -(zeta3 - 1.0).recip(); let c = zeta2 * frac_1mz3 * frac_1mz3; let g_hs = d.map(|d| frac_1mz3 + d * c * 1.5 - d.powi(2) * c.powi(2) * (zeta3 - 1.0) * 0.5); state .partial_density .component_mul(&g_hs.map(|g| g.ln())) .dot(&(-parameters.m.map(|m| D::from(m - 1.0)))) } } #[cfg(test)] mod tests { use super::*; use crate::pcsaft::parameters::utils::{ butane_parameters, propane_butane_parameters, propane_parameters, }; use approx::assert_relative_eq; use nalgebra::dvector; #[test] fn helmholtz_energy() { let t = 250.0; let v = 1000.0; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a_rust = HardChain.helmholtz_energy_density(&propane_parameters().params, &s) * v; assert_relative_eq!(a_rust, -0.12402626171926148, epsilon = 1e-10); } #[test] fn mix() { let t = 250.0; let v = 2.5; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a1 = HardChain.helmholtz_energy_density(&propane_parameters().params, &s); let a2 = HardChain.helmholtz_energy_density(&butane_parameters().params, &s); let s1m = StateHD::new(t, v, &dvector![n, 0.0]); let a1m = HardChain.helmholtz_energy_density(&propane_butane_parameters().params, &s1m); let s2m = StateHD::new(t, v, &dvector![0.0, n]); let a2m = HardChain.helmholtz_energy_density(&propane_butane_parameters().params, &s2m); assert_relative_eq!(a1, a1m, epsilon = 1e-14); assert_relative_eq!(a2, a2m, epsilon = 1e-14); } }
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/eos/pcsaft_pure.rs
.rs
10,511
311
use super::dispersion::{A0, A1, A2, B0, B1, B2}; use super::polar::{AD, BD, CD}; use feos_core::{ParametersAD, Residual, StateHD}; use nalgebra::{SVector, U1}; use num_dual::{DualNum, DualSVec64}; 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 PC-SAFT for a single component. #[derive(Clone, Copy)] pub struct PcSaftPure<D: DualNum<f64> + Copy, const N: usize>(pub [D; N]); fn helmholtz_energy_density_non_assoc<D: DualNum<f64> + Copy>( m: D, sigma: D, epsilon_k: D, mu: D, temperature: D, density: D, ) -> (D, [D; 2]) { // temperature dependent segment diameter let diameter = sigma * (-(epsilon_k * (-3.) / temperature).exp() * 0.12 + 1.0); let eta = m * density * diameter.powi(3) * FRAC_PI_6; let eta2 = eta * eta; let eta3 = eta2 * eta; let eta_m1 = (-eta + 1.0).recip(); let eta_m2 = eta_m1 * eta_m1; let etas = [ D::one(), eta, eta2, eta3, eta2 * eta2, eta2 * eta3, eta3 * eta3, ]; // hard sphere let hs = m * density * (eta * 4.0 - eta2 * 3.0) * eta_m2; // hard chain let g = (-eta * 0.5 + 1.0) * eta_m1 * eta_m2; let hc = -density * (m - 1.0) * g.ln(); // 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 c1 = (m * (eta * 8.0 - eta2 * 2.0) * eta_m2 * eta_m2 + 1.0 - (m - 1.0) * (eta * 20.0 - eta2 * 27.0 + eta2 * eta * 12.0 - eta2 * eta2 * 2.0) / ((eta - 1.0) * (eta - 2.0)).powi(2)) .recip(); let i = i1 * 2.0 + c1 * i2 * m * e; let disp = -density * density * m.powi(2) * e * s3 * i * PI; // dipoles let mu2 = mu.powi(2) / (m * 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); (hs + hc + disp + dipole, [eta, eta_m1]) } fn helmholtz_energy_density<D: DualNum<f64> + Copy>( parameters: &[D; 8], temperature: D, density: D, ) -> D { let [m, sigma, epsilon_k, mu, kappa_ab, epsilon_k_ab, na, nb] = *parameters; let (non_assoc, [eta, eta_m1]) = helmholtz_energy_density_non_assoc(m, 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; 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 = (sqrt + 1.0 + (rhob - rhoa) * delta).recip() * 2.0; let xb = (sqrt + 1.0 - (rhob - rhoa) * delta).recip() * 2.0; let assoc = rhoa * (xa.ln() - xa * 0.5 + 0.5) + rhob * (xb.ln() - xb * 0.5 + 0.5); non_assoc + assoc } impl<D: DualNum<f64> + Copy> Residual<U1, D> for PcSaftPure<D, 8> { fn components(&self) -> usize { 1 } type Real = PcSaftPure<f64, 8>; type Lifted<D2: DualNum<f64, Inner = D> + Copy> = PcSaftPure<D2, 8>; fn re(&self) -> Self::Real { PcSaftPure(self.0.each_ref().map(D::re)) } fn lift<D2: DualNum<f64, Inner = D> + Copy>(&self) -> Self::Lifted<D2> { PcSaftPure(self.0.each_ref().map(D2::from_inner)) } fn compute_max_density(&self, _: &SVector<D, 1>) -> D { let &[m, sigma, ..] = &self.0; (m * sigma.powi(3) * FRAC_PI_6).recip() * MAX_ETA } fn reduced_helmholtz_energy_density_contributions( &self, state: &StateHD<D, U1>, ) -> Vec<(&'static str, D)> { vec![( "PC-SAFT (pure)", self.reduced_residual_helmholtz_energy_density(state), )] } fn reduced_residual_helmholtz_energy_density(&self, state: &StateHD<D, U1>) -> D { let density = state.partial_density.data.0[0][0]; helmholtz_energy_density(&self.0, state.temperature, density) } } impl<D: DualNum<f64> + Copy> Residual<U1, D> for PcSaftPure<D, 4> { fn components(&self) -> usize { 1 } type Real = PcSaftPure<f64, 4>; type Lifted<D2: DualNum<f64, Inner = D> + Copy> = PcSaftPure<D2, 4>; fn re(&self) -> Self::Real { PcSaftPure(self.0.each_ref().map(D::re)) } fn lift<D2: DualNum<f64, Inner = D> + Copy>(&self) -> Self::Lifted<D2> { PcSaftPure(self.0.each_ref().map(D2::from_inner)) } fn compute_max_density(&self, _: &SVector<D, 1>) -> D { let &[m, sigma, ..] = &self.0; (m * sigma.powi(3) * FRAC_PI_6).recip() * MAX_ETA } fn reduced_helmholtz_energy_density_contributions( &self, state: &StateHD<D, U1>, ) -> Vec<(&'static str, D)> { vec![( "PC-SAFT (pure, non-assoc)", self.reduced_residual_helmholtz_energy_density(state), )] } fn reduced_residual_helmholtz_energy_density(&self, state: &StateHD<D, U1>) -> D { let density = state.partial_density.data.0[0][0]; let [m, sigma, epsilon_k, mu] = self.0; helmholtz_energy_density_non_assoc(m, sigma, epsilon_k, mu, state.temperature, density).0 } } impl<D: DualNum<f64> + Copy, const N: usize> From<&[f64]> for PcSaftPure<D, N> { fn from(parameters: &[f64]) -> Self { let Ok(parameters): Result<[f64; N], _> = parameters.try_into() else { panic!("This version of PC-SAFT requires exactly {N} parameters!") }; Self(parameters.map(D::from)) } } impl ParametersAD<1> for PcSaftPure<f64, 4> { fn index_parameters_mut<'a, const P: usize>( eos: &'a mut Self::Lifted<DualSVec64<P>>, index: &str, ) -> &'a mut DualSVec64<P> { match index { "m" => &mut eos.0[0], "sigma" => &mut eos.0[1], "epsilon_k" => &mut eos.0[2], "mu" => &mut eos.0[3], _ => panic!("{index} is not a valid PC-SAFT parameter!"), } } } impl ParametersAD<1> for PcSaftPure<f64, 8> { fn index_parameters_mut<'a, const P: usize>( eos: &'a mut Self::Lifted<DualSVec64<P>>, index: &str, ) -> &'a mut DualSVec64<P> { match index { "m" => &mut eos.0[0], "sigma" => &mut eos.0[1], "epsilon_k" => &mut eos.0[2], "mu" => &mut eos.0[3], "kappa_ab" => &mut eos.0[4], "epsilon_k_ab" => &mut eos.0[5], "na" => &mut eos.0[6], "nb" => &mut eos.0[7], _ => panic!("{index} is not a valid PC-SAFT parameter!"), } } } #[cfg(test)] pub mod test { use crate::pcsaft::PcSaftRecord; use super::super::{PcSaft, PcSaftAssociationRecord, PcSaftParameters}; use super::*; use approx::assert_relative_eq; use feos_core::parameter::{AssociationRecord, PureRecord}; use feos_core::{Contributions::Total, FeosResult, State}; use nalgebra::{dvector, vector}; use quantity::{KELVIN, KILO, METER, MOL}; pub fn pcsaft() -> FeosResult<(PcSaftPure<f64, 8>, PcSaft)> { let m = 1.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 = PcSaftParameters::new_pure(PureRecord::with_association( Default::default(), 0.0, PcSaftRecord::new(m, sigma, epsilon_k, mu, 0.0, None, None, None), vec![AssociationRecord::new( Some(PcSaftAssociationRecord::new(kappa_ab, epsilon_k_ab)), na, nb, 0.0, )], ))?; let eos = PcSaft::new(params); let params = [m, sigma, epsilon_k, mu, kappa_ab, epsilon_k_ab, na, nb]; Ok((PcSaftPure(params), eos)) } #[test] fn test_pcsaft_pure() -> FeosResult<()> { let (pcsaft, eos) = pcsaft()?; 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(&pcsaft, 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(()) } }
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/eos/dispersion.rs
.rs
4,609
159
use super::PcSaftPars; use crate::hard_sphere::HardSphereProperties; use feos_core::StateHD; use num_dual::DualNum; use std::f64::consts::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.30840169182720, 0.18605311591713, -2.50300472586548, 21.4197936296668, -65.2558853303492, 83.3186804808856, -33.7469229297323, ]; pub const A2: [f64; 7] = [ -0.09061483509767, 0.45278428063920, 0.59627007280101, -1.72418291311787, -4.13021125311661, 13.7766318697211, -8.67284703679646, ]; 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.57554980753450, 0.69950955214436, 3.89256733895307, -17.21547164777212, 192.6722644652495, -161.8264616487648, -165.2076934555607, ]; pub const B2: [f64; 7] = [ 0.09768831158356, -0.25575749816100, -9.15585615297321, 20.64207597439724, -38.80443005206285, 93.6267740770146, -29.66690558514725, ]; pub struct Dispersion; impl Dispersion { pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &PcSaftPars, state: &StateHD<D>, ) -> D { // auxiliary variables let n = parameters.m.len(); let p = parameters; let rho = &state.partial_density; // packing fraction let m = p.m.map(D::from); let [eta] = parameters.zeta(state.temperature, &state.partial_density, [3]); // mean segment number let m = state.molefracs.dot(&m); // inverse temperature let t_inv = state.temperature.recip(); // 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 = t_inv * p.epsilon_k_ij[(i, j)]; let sigma_ij = p.sigma_ij[(i, j)].powi(3); rho1mix += rho[i] * rho[j] * p.m[i] * p.m[j] * eps_ij * sigma_ij; rho2mix += rho[i] * rho[j] * p.m[i] * p.m[j] * eps_ij * eps_ij * sigma_ij; } } // I1, I2 and C1 let mut i1 = D::zero(); let mut i2 = D::zero(); let mut eta_i = D::one(); let m1_m = (m - 1.0) / m; let m2_m = (m - 2.0) / m; for i in 0..=6 { i1 += (m1_m * (m2_m * A2[i] + A1[i]) + A0[i]) * eta_i; i2 += (m1_m * (m2_m * B2[i] + B1[i]) + B0[i]) * eta_i; eta_i *= eta; } let c1 = (m * (eta * 8.0 - eta.powi(2) * 2.0) / (eta - 1.0).powi(4) + (D::one() - m) * (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(); // Helmholtz energy (-rho1mix * i1 * 2.0 - rho2mix * m * c1 * i2) * PI } } #[cfg(test)] mod tests { use super::*; use crate::pcsaft::parameters::utils::{ butane_parameters, propane_butane_parameters, propane_parameters, }; use approx::assert_relative_eq; use nalgebra::dvector; #[test] fn helmholtz_energy() { let params = &propane_parameters().params; let t = 250.0; let v = 1000.0; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a_rust = Dispersion.helmholtz_energy_density(params, &s) * v; assert_relative_eq!(a_rust, -1.0622531100351962, epsilon = 1e-10); } #[test] fn mix() { let propane = &propane_parameters().params; let butane = &butane_parameters().params; let mix = &propane_butane_parameters().params; let t = 250.0; let v = 1000.0; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a1 = Dispersion.helmholtz_energy_density(propane, &s); let a2 = Dispersion.helmholtz_energy_density(butane, &s); let s1m = StateHD::new(t, v, &dvector![n, 0.0]); let a1m = Dispersion.helmholtz_energy_density(mix, &s1m); let s2m = StateHD::new(t, v, &dvector![0.0, n]); let a2m = Dispersion.helmholtz_energy_density(mix, &s2m); assert_relative_eq!(a1, a1m, epsilon = 1e-14); assert_relative_eq!(a2, a2m, epsilon = 1e-14); } }
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/eos/polar.rs
.rs
19,475
576
use super::PcSaftPars; use crate::hard_sphere::HardSphereProperties; use feos_core::StateHD; use nalgebra::DMatrix; use num_dual::DualNum; use std::f64::consts::{FRAC_PI_3, PI}; pub const ALPHA: f64 = 1.1937350; // Dipole parameters pub 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 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 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], ]; // Quadrupole parameters pub const AQ: [[f64; 3]; 5] = [ [1.237830788, 1.285410878, 1.794295401], [2.435503144, -11.46561451, 0.769510293], [1.633090469, 22.08689285, 7.264792255], [-1.611815241, 7.46913832, 94.48669892], [6.977118504, -17.19777208, -77.1484579], ]; pub const BQ: [[f64; 3]; 5] = [ [0.454271755, -0.813734006, 6.868267516], [-4.501626435, 10.06402986, -5.173223765], [3.585886783, -10.87663092, -17.2402066], [0.0; 3], [0.0; 3], ]; pub const CQ: [[f64; 3]; 4] = [ [-0.500043713, 2.000209381, 3.135827145], [6.531869153, -6.78386584, 7.247588801], [-16.01477983, 20.38324603, 3.075947834], [14.42597018, -10.89598394, 0.0], ]; // Dipole-Quadrupole parameters pub const ADQ: [[f64; 3]; 4] = [ [0.697094963, -0.673459279, 0.670340770], [-0.633554144, -1.425899106, -4.338471826], [2.945509028, 4.19441392, 7.234168360], [-1.467027314, 1.0266216, 0.0], ]; pub const BDQ: [[f64; 3]; 4] = [ [-0.484038322, 0.67651011, -1.167560146], [1.970405465, -3.013867512, 2.13488432], [-2.118572671, 0.46742656, 0.0], [0.0; 3], ]; pub const CDQ: [[f64; 2]; 3] = [ [0.795009692, -2.099579397], [3.386863396, -5.941376392], [0.475106328, -0.178820384], ]; pub const PI_SQ_43: f64 = 4.0 * PI * FRAC_PI_3; pub struct MeanSegmentNumbers { pub mij1: DMatrix<f64>, pub mij2: DMatrix<f64>, pub mijk1: Vec<DMatrix<f64>>, pub mijk2: Vec<DMatrix<f64>>, } pub enum Multipole { Dipole, Quadrupole, } impl MeanSegmentNumbers { pub fn new(parameters: &PcSaftPars, polarity: Multipole) -> Self { let (npoles, comp) = match polarity { Multipole::Dipole => (parameters.ndipole, &parameters.dipole_comp), Multipole::Quadrupole => (parameters.nquadpole, &parameters.quadpole_comp), }; let mut mij1 = DMatrix::zeros(npoles, npoles); let mut mij2 = DMatrix::zeros(npoles, npoles); let mut mijk1 = vec![DMatrix::zeros(npoles, npoles); npoles]; let mut mijk2 = vec![DMatrix::zeros(npoles, npoles); npoles]; for i in 0..npoles { let mi = parameters.m[comp[i]].min(2.0); for j in i..npoles { let mj = parameters.m[comp[j]].min(2.0); let mij = (mi * mj).sqrt(); mij1[(i, j)] = (mij - 1.0) / mij; mij2[(i, j)] = mij1[(i, j)] * (mij - 2.0) / mij; for k in j..npoles { let mk = parameters.m[comp[k]].min(2.0); let mijk = (mi * mj * mk).cbrt(); mijk1[i][(j, k)] = (mijk - 1.0) / mijk; mijk2[i][(j, k)] = mijk1[i][(j, k)] * (mijk - 2.0) / mijk; } } } Self { mij1, mij2, mijk1, mijk2, } } } fn pair_integral_ij<D: DualNum<f64> + Copy>( mij1: f64, mij2: f64, etas: &[D], a: &[[f64; 3]], b: &[[f64; 3]], eps_ij_t: D, ) -> D { (0..a.len()) .map(|i| { etas[i] * (eps_ij_t * (b[i][0] + mij1 * b[i][1] + mij2 * b[i][2]) + (a[i][0] + mij1 * a[i][1] + mij2 * a[i][2])) }) .sum() } fn triplet_integral_ijk<D: DualNum<f64> + Copy>( mijk1: f64, mijk2: f64, etas: &[D], c: &[[f64; 3]], ) -> D { (0..c.len()) .map(|i| etas[i] * (c[i][0] + mijk1 * c[i][1] + mijk2 * c[i][2])) .sum() } fn triplet_integral_ijk_dq<D: DualNum<f64> + Copy>(mijk: f64, etas: &[D], c: &[[f64; 2]]) -> D { (0..c.len()) .map(|i| etas[i] * (c[i][0] + mijk * c[i][1])) .sum() } pub struct Dipole; impl Dipole { #[inline] pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &PcSaftPars, state: &StateHD<D>, ) -> D { let m = MeanSegmentNumbers::new(parameters, Multipole::Dipole); let p = parameters; 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<D> = 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 [eta] = parameters.zeta(state.temperature, rho, [3]); let eta2 = eta * eta; let etas = [D::one(), eta, eta2, eta2 * eta, eta2 * eta2]; let mut phi2 = D::zero(); let mut phi3 = D::zero(); for i in 0..p.ndipole { let di = p.dipole_comp[i]; for j in i..p.ndipole { let dj = p.dipole_comp[j]; let c = if i == j { 1.0 } else { 2.0 }; phi2 -= rho[di] * rho[dj] * mu2_term[i] * mu2_term[j] * pair_integral_ij( m.mij1[(i, j)], m.mij2[(i, j)], &etas, &AD, &BD, eps_ij_t[(di, dj)], ) / sig_ij_3[(di, dj)] * c; for k in j..p.ndipole { let dk = p.dipole_comp[k]; 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(m.mijk1[i][(j, k)], m.mijk2[i][(j, k)], &etas, &CD) * c; } } } phi2 *= PI; phi3 *= PI_SQ_43; let mut result = phi2 * phi2 / (phi2 - phi3); if result.re().is_nan() { result = phi2 } result } } pub struct Quadrupole; impl Quadrupole { #[inline] pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &PcSaftPars, state: &StateHD<D>, ) -> D { let m = MeanSegmentNumbers::new(parameters, Multipole::Quadrupole); let p = parameters; 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 q2_term: Vec<D> = p .quadpole_comp .iter() .map(|&i| t_inv * p.sigma[i].powi(5) * p.epsilon_k[i] * p.q2[i]) .collect(); let rho = &state.partial_density; let [eta] = parameters.zeta(state.temperature, rho, [3]); let eta2 = eta * eta; let etas = [D::one(), eta, eta2, eta2 * eta, eta2 * eta2]; let mut phi2 = D::zero(); let mut phi3 = D::zero(); for i in 0..p.nquadpole { let di = p.quadpole_comp[i]; for j in i..p.nquadpole { let dj = p.quadpole_comp[j]; let c = if i == j { 1.0 } else { 2.0 }; phi2 -= (rho[di] * rho[dj] * q2_term[i] * q2_term[j] * pair_integral_ij( m.mij1[(i, j)], m.mij2[(i, j)], &etas, &AQ, &BQ, eps_ij_t[(di, dj)], )) / p.sigma_ij[(di, dj)].powi(7) * c; for k in j..p.nquadpole { let dk = p.quadpole_comp[k]; 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] * q2_term[i] * q2_term[j] * q2_term[k] / (sig_ij_3[(di, dj)] * sig_ij_3[(di, dk)] * sig_ij_3[(dj, dk)]) * triplet_integral_ijk(m.mijk1[i][(j, k)], m.mijk2[i][(j, k)], &etas, &CQ) * c; } } } phi2 *= PI * 0.5625; phi3 *= PI * PI * 0.5625; let mut result = phi2 * phi2 / (phi2 - phi3); if result.re().is_nan() { result = phi2 } result } } /// Different combination rules used in the dipole-quadrupole contribution. #[derive(Clone, Copy, PartialEq)] pub enum DQVariants { DQ35, DQ44, } pub struct DipoleQuadrupole; impl DipoleQuadrupole { #[inline] pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &PcSaftPars, state: &StateHD<D>, variant: DQVariants, ) -> D { let p = parameters; let t_inv = state.temperature.inv(); let eps_ij_t = p.e_k_ij.map(|v| t_inv * v); let q2_term: Vec<D> = p .quadpole_comp .iter() .map(|&i| t_inv * p.sigma[i].powi(4) * p.epsilon_k[i] * p.q2[i]) .collect(); let mu2_term: Vec<D> = p .dipole_comp .iter() .map(|&i| t_inv * p.sigma[i].powi(4) * p.epsilon_k[i] * p.mu2[i]) .collect(); let rho = &state.partial_density; let [eta] = parameters.zeta(state.temperature, rho, [3]); let eta2 = eta * eta; let etas = [D::one(), eta, eta2, eta2 * eta, eta2 * eta2]; // mean segment number let mut mdq1 = DMatrix::zeros(p.ndipole, p.nquadpole); let mut mdq2 = DMatrix::zeros(p.ndipole, p.nquadpole); let mut mdqd = vec![DMatrix::zeros(p.nquadpole, p.ndipole); p.ndipole]; let mut mdqq = vec![DMatrix::zeros(p.nquadpole, p.nquadpole); p.ndipole]; for i in 0..p.ndipole { let di = p.dipole_comp[i]; let mi = p.m[di].min(2.0); for j in 0..p.nquadpole { let qj = p.quadpole_comp[j]; let mj = p.m[qj].min(2.0); let m = (mi * mj).sqrt(); mdq1[(i, j)] = (m - 1.0) / m; mdq2[(i, j)] = mdq1[(i, j)] * (m - 2.0) / m; for k in 0..p.ndipole { let dk = p.dipole_comp[k]; let mk = p.m[dk].min(2.0); let m = (mi * mj * mk).cbrt(); mdqd[i][(j, k)] = (m - 1.0) / m; } for k in 0..p.nquadpole { let qk = p.quadpole_comp[k]; let mk = p.m[qk].min(2.0); let m = (mi * mj * mk).cbrt(); mdqq[i][(j, k)] = (m - 1.0) / m; } } } let mut phi2 = D::zero(); let mut phi3 = D::zero(); for i in 0..p.ndipole { for j in 0..p.nquadpole { let di = p.dipole_comp[i]; let qj = p.quadpole_comp[j]; let mu2_q2_term = match variant { DQVariants::DQ35 => mu2_term[i] / p.sigma[di] * q2_term[j] * p.sigma[qj], DQVariants::DQ44 => mu2_term[i] * q2_term[j], }; phi2 -= rho[di] * rho[qj] * mu2_q2_term / p.sigma_ij[(di, qj)].powi(5) * pair_integral_ij( mdq1[(i, j)], mdq2[(i, j)], &etas, &ADQ, &BDQ, eps_ij_t[(di, qj)], ); for k in 0..p.ndipole { let dk = p.dipole_comp[k]; phi3 += rho[di] * rho[qj] * rho[dk] * mu2_term[i] * q2_term[j] * mu2_term[k] / (p.sigma_ij[(di, qj)] * p.sigma_ij[(di, dk)] * p.sigma_ij[(qj, dk)]) .powi(2) * triplet_integral_ijk_dq(mdqd[i][(j, k)], &etas, &CDQ); } for k in 0..p.nquadpole { let qk = p.quadpole_comp[k]; phi3 += rho[di] * rho[qj] * rho[qk] * mu2_term[i] * q2_term[j] * q2_term[k] / (p.sigma_ij[(di, qj)] * p.sigma_ij[(di, qk)] * p.sigma_ij[(qj, qk)]) .powi(2) * ALPHA * triplet_integral_ijk_dq(mdqq[i][(j, k)], &etas, &CDQ); } } } phi2 *= PI * 2.25; phi3 *= PI * PI; let mut result = phi2 * phi2 / (phi2 - phi3); if result.re().is_nan() { result = phi2 } result } } #[cfg(test)] mod tests { use super::*; use crate::pcsaft::PcSaftParameters; use crate::pcsaft::eos::dispersion::Dispersion; use crate::pcsaft::parameters::utils::{ carbon_dioxide_parameters, dme_co2_parameters, dme_parameters, }; use approx::assert_relative_eq; use feos_core::StateHD; use feos_core::parameter::IdentifierOption; use itertools::Itertools; use nalgebra::{DVector, dvector}; #[test] fn test_dipolar_contribution() { let dme = dme_parameters(); let t = 350.0; let v = 1000.0; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a = Dipole.helmholtz_energy_density(&dme, &s) * v; assert_relative_eq!(a, -1.40501033595417E-002, epsilon = 1e-6); } #[test] fn test_dipolar_contribution_mix() { let parameters = PcSaftPars::new( &PcSaftParameters::from_json( vec!["acetone", "butanal", "dimethyl ether"], "../../parameters/pcsaft/gross2006.json", None, IdentifierOption::Name, ) .unwrap(), ); let t = 350.0; let v = 1000.0; let s = StateHD::new(t, v, &dvector![1.0, 2.0, 3.0]); let a = Dipole.helmholtz_energy_density(&parameters, &s) * v; assert_relative_eq!(a, -1.4126308106201688, epsilon = 1e-10); } #[test] fn test_dipolar_contribution_order() { let a: Vec<_> = ["acetone", "butanal", "dimethyl ether"] .into_iter() .permutations(3) .zip([1.0, 2.0, 3.0].into_iter().permutations(3)) .map(|(components, n)| { let parameters = PcSaftPars::new( &PcSaftParameters::from_json( components.clone(), "../../parameters/pcsaft/gross2006.json", None, IdentifierOption::Name, ) .unwrap(), ); let t = 350.0; let v = 1000.0; let s = StateHD::new(t, v, &DVector::from(n)); let a = Dipole.helmholtz_energy_density(&parameters, &s) * v; println!("{components:?}: {a}"); a }) .collect(); for (a, b) in a.into_iter().tuple_windows() { assert_relative_eq!(a, b, epsilon = 1e-10); } } #[test] fn test_quadrupolar_contribution() { let co2 = carbon_dioxide_parameters(); let t = 350.0; let v = 1000.0; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a = Quadrupole.helmholtz_energy_density(&co2, &s) * v; assert_relative_eq!(a, -4.38559558854186E-002, epsilon = 1e-6); } #[test] fn test_quadrupolar_contribution_mix() { let parameters = PcSaftPars::new( &PcSaftParameters::from_json( vec!["carbon dioxide", "chlorine", "ethylene"], "../../parameters/pcsaft/gross2005_literature.json", None, IdentifierOption::Name, ) .unwrap(), ); let t = 350.0; let v = 1000.0; let s = StateHD::new(t, v, &dvector![1.0, 2.0, 3.0]); let a = Quadrupole.helmholtz_energy_density(&parameters, &s) * v; assert_relative_eq!(a, -0.2748017468669352, epsilon = 1e-10); } #[test] fn test_quadrupolar_contribution_order() { let a: Vec<_> = ["carbon dioxide", "chlorine", "ethylene"] .into_iter() .permutations(3) .zip([1.0, 2.0, 3.0].into_iter().permutations(3)) .map(|(components, n)| { let parameters = PcSaftPars::new( &PcSaftParameters::from_json( components.clone(), "../../parameters/pcsaft/gross2005_literature.json", None, IdentifierOption::Name, ) .unwrap(), ); let t = 350.0; let v = 1000.0; let s = StateHD::new(t, v, &DVector::from(n)); let a = Quadrupole.helmholtz_energy_density(&parameters, &s) * v; println!("{components:?}: {a}"); a }) .collect(); for (a, b) in a.into_iter().tuple_windows() { assert_relative_eq!(a, b, epsilon = 1e-10); } } #[test] fn test_dipolar_quadrupolar_contribution() { let mix = dme_co2_parameters(); // let dpqp = DipoleQuadrupole { // parameters: Arc::new(dme_co2_parameters()), // variant: DQVariants::DQ35, // }; let t = 350.0; let v = 1000.0; let n_dme = 1.0; let n_co2 = 1.0; let n = n_dme + n_co2; let s = StateHD::new(t, v / n, &(dvector![n_dme, n_co2] / n)); // let a_dpqp = dpqp.helmholtz_energy_density(&s)*v; let a_disp = Dispersion.helmholtz_energy_density(&mix, &s) * v; let a_qp = Quadrupole.helmholtz_energy_density(&mix, &s) * v; let a_dp = Dipole.helmholtz_energy_density(&mix, &s) * v; assert_relative_eq!(a_disp, -1.6283622072860044, epsilon = 1e-6); assert_relative_eq!(a_dp, -1.35361827881345E-002, epsilon = 1e-6); assert_relative_eq!(a_qp, -4.20168059082731E-002, epsilon = 1e-6); // assert_relative_eq!(a_dpqp, -2.2316252638709004E-002, epsilon = 1e-6); } }
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/dft/mod.rs
.rs
5,991
188
use super::PcSaftParameters; use super::parameters::PcSaftPars; use crate::association::{Association, YuWuAssociationFunctional}; use crate::hard_sphere::{FMTContribution, FMTVersion}; use crate::pcsaft::eos::PcSaftOptions; use feos_core::{FeosResult, Molarweight, ResidualDyn, StateHD, Subset}; use feos_derive::FunctionalContribution; use feos_dft::adsorption::FluidParameters; use feos_dft::solvation::PairPotential; use feos_dft::{ FunctionalContribution, HelmholtzEnergyFunctional, HelmholtzEnergyFunctionalDyn, MoleculeShape, }; use nalgebra::DVector; use ndarray::{Array1, Array2}; use num_dual::DualNum; use num_traits::One; use quantity::MolarWeight; use std::f64::consts::FRAC_PI_6; mod dispersion; mod hard_chain; mod polar; mod pure_saft_functional; use dispersion::AttractiveFunctional; use hard_chain::ChainFunctional; use pure_saft_functional::*; /// PC-SAFT Helmholtz energy functional. pub struct PcSaftFunctional { pub parameters: PcSaftParameters, association: Option<Association>, params: PcSaftPars, fmt_version: FMTVersion, options: PcSaftOptions, } impl PcSaftFunctional { pub fn new(parameters: PcSaftParameters) -> Self { Self::with_options(parameters, FMTVersion::WhiteBear, PcSaftOptions::default()) } pub fn new_full(parameters: PcSaftParameters, fmt_version: FMTVersion) -> Self { Self::with_options(parameters, fmt_version, PcSaftOptions::default()) } pub fn with_options( parameters: PcSaftParameters, fmt_version: FMTVersion, saft_options: PcSaftOptions, ) -> Self { let params = PcSaftPars::new(&parameters); let association = (!parameters.association.is_empty()).then(|| { Association::new( saft_options.max_iter_cross_assoc, saft_options.tol_cross_assoc, ) }); Self { parameters, association, params, fmt_version, options: saft_options, } } } impl Subset for PcSaftFunctional { fn subset(&self, component_list: &[usize]) -> Self { Self::with_options( self.parameters.subset(component_list), self.fmt_version, self.options, ) } } impl ResidualDyn for PcSaftFunctional { fn components(&self) -> usize { self.parameters.pure.len() } fn compute_max_density<D: DualNum<f64> + Copy>(&self, molefracs: &DVector<D>) -> D { let p = &self.params; let msigma3 = p.m.zip_map(&p.sigma, |m, s| m * s.powi(3)); (msigma3.map(D::from).dot(molefracs) * FRAC_PI_6).recip() * self.options.max_eta } fn reduced_helmholtz_energy_density_contributions<D: DualNum<f64> + Copy>( &self, state: &StateHD<D>, ) -> Vec<(&'static str, D)> { self.evaluate_bulk(state) } } impl HelmholtzEnergyFunctionalDyn for PcSaftFunctional { type Contribution<'a> = PcSaftFunctionalContribution<'a> where Self: 'a; fn contributions<'a>(&'a self) -> impl Iterator<Item = PcSaftFunctionalContribution<'a>> { let mut contributions = Vec::with_capacity(4); let assoc = YuWuAssociationFunctional::new(&self.params, &self.parameters, self.association); if matches!( self.fmt_version, FMTVersion::WhiteBear | FMTVersion::AntiSymWhiteBear ) && self.params.m.len() == 1 { let fmt_assoc = PureFMTAssocFunctional::new(&self.params, assoc, self.fmt_version); contributions.push(fmt_assoc.into()); if self.params.m.iter().any(|&mi| mi > 1.0) { let chain = PureChainFunctional::new(&self.params); contributions.push(chain.into()); } let att = PureAttFunctional::new(&self.params); contributions.push(att.into()); } else { // Hard sphere contribution let hs = FMTContribution::new(&self.params, self.fmt_version); contributions.push(hs.into()); // Hard chains if self.params.m.iter().any(|&mi| !mi.is_one()) { let chain = ChainFunctional::new(&self.params); contributions.push(chain.into()); } // Dispersion let att = AttractiveFunctional::new(&self.params); contributions.push(att.into()); // Association if let Some(assoc) = assoc { contributions.push(assoc.into()); } } contributions.into_iter() } fn molecule_shape(&self) -> MoleculeShape<'_> { MoleculeShape::NonSpherical(&self.params.m) } } impl Molarweight for PcSaftFunctional { fn molar_weight(&self) -> MolarWeight<DVector<f64>> { self.parameters.molar_weight.clone() } } impl FluidParameters for PcSaftFunctional { fn epsilon_k_ff(&self) -> DVector<f64> { self.params.epsilon_k.clone() } fn sigma_ff(&self) -> DVector<f64> { self.params.sigma.clone() } } impl PairPotential for PcSaftFunctional { fn pair_potential(&self, i: usize, r: &Array1<f64>, _: f64) -> Array2<f64> { let sigma_ij = &self.params.sigma_ij; let eps_ij_4 = 4.0 * &self.params.epsilon_k_ij; Array2::from_shape_fn((self.params.m.len(), r.len()), |(j, k)| { let att = (sigma_ij[(i, j)] / r[k]).powi(6); eps_ij_4[(i, j)] * att * (att - 1.0) }) } } /// Individual contributions for the PC-SAFT Helmholtz energy functional. #[derive(FunctionalContribution)] #[expect(private_interfaces)] pub enum PcSaftFunctionalContribution<'a> { PureFMTAssoc(PureFMTAssocFunctional<'a>), PureChain(PureChainFunctional<'a>), PureAtt(PureAttFunctional<'a>), Fmt(FMTContribution<'a, PcSaftPars>), Chain(ChainFunctional<'a>), Attractive(AttractiveFunctional<'a>), Association(YuWuAssociationFunctional<'a, PcSaftPars>), }
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/dft/hard_chain.rs
.rs
3,036
85
use crate::hard_sphere::HardSphereProperties; use crate::pcsaft::parameters::PcSaftPars; use feos_core::FeosError; use feos_dft::{FunctionalContribution, WeightFunction, WeightFunctionInfo, WeightFunctionShape}; use nalgebra::DVector; use ndarray::*; use num_dual::DualNum; #[derive(Clone)] pub(crate) struct ChainFunctional<'a> { parameters: &'a PcSaftPars, } impl<'a> ChainFunctional<'a> { pub(crate) fn new(parameters: &'a PcSaftPars) -> Self { Self { parameters } } } impl<'a> FunctionalContribution for ChainFunctional<'a> { fn name(&self) -> &'static str { "Hard chain functional" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { let p = &self.parameters; let d = p.hs_diameter(temperature); WeightFunctionInfo::new(DVector::from_fn(d.len(), |i, _| i), true) .add( WeightFunction { prefactor: p.m.map(|m| (m / 8.0).into()).component_div(&d), kernel_radius: d.clone(), shape: WeightFunctionShape::Theta, }, true, ) .add( WeightFunction { prefactor: p.m.map(|m| (m / 8.0).into()), kernel_radius: d.clone(), shape: WeightFunctionShape::Theta, }, true, ) .add( WeightFunction::new_scaled(d, WeightFunctionShape::Delta), false, ) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, weighted_densities: ArrayView2<N>, ) -> Result<Array1<N>, FeosError> { let p = &self.parameters; // number of segments let n = (weighted_densities.shape()[0] - 2) / 2; // weighted densities let rho = weighted_densities.slice_axis(Axis(0), Slice::new(0, Some(n as isize), 1)); // negative lambdas lead to nan, therefore the absolute value is used let lambda = weighted_densities .slice_axis(Axis(0), Slice::new(n as isize, Some(2 * n as isize), 1)) .mapv(|l| if l.re() < 0.0 { -l } else { l } + N::from(f64::EPSILON)); let zeta2 = weighted_densities.index_axis(Axis(0), 2 * n); let zeta3 = weighted_densities.index_axis(Axis(0), 2 * n + 1); // temperature dependent segment diameter let d = p.hs_diameter(temperature); let z3i = zeta3.mapv(|z3| (-z3 + 1.0).recip()); let mut phi = Array::zeros(zeta2.raw_dim()); for (i, (lambdai, rhoi)) in lambda.outer_iter().zip(rho.outer_iter()).enumerate() { // cavity correlation let z2d = zeta2.mapv(|z2| z2 * d[i]); let yi = &z2d * &z3i * &z3i * (z2d * &z3i * 0.5 + 1.5) + &z3i; // Helmholtz energy density phi = phi - (yi * lambdai).mapv(|x| x.ln() - 1.0) * rhoi * (p.m[i] - 1.0); } Ok(phi) } }
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/dft/dispersion.rs
.rs
4,758
132
use super::polar::helmholtz_energy_density_polar; use crate::hard_sphere::HardSphereProperties; use crate::pcsaft::eos::dispersion::{A0, A1, A2, B0, B1, B2}; use crate::pcsaft::parameters::PcSaftPars; use feos_core::FeosError; use feos_dft::{FunctionalContribution, WeightFunction, WeightFunctionInfo, WeightFunctionShape}; use nalgebra::DVector; use ndarray::*; use num_dual::DualNum; use std::f64::consts::{FRAC_PI_6, PI}; /// psi Parameter for DFT (Sauer2017) const PSI_DFT: f64 = 1.3862; /// psi Parameter for pDGT (Rehner2018) const PSI_PDGT: f64 = 1.3286; #[derive(Clone)] pub(crate) struct AttractiveFunctional<'a> { parameters: &'a PcSaftPars, } impl<'a> AttractiveFunctional<'a> { pub(crate) fn new(parameters: &'a PcSaftPars) -> Self { Self { parameters } } } fn att_weight_functions<N: DualNum<f64> + Copy>( p: &PcSaftPars, psi: f64, temperature: N, ) -> WeightFunctionInfo<N> { let d = p.hs_diameter(temperature); let psi = N::from(psi); WeightFunctionInfo::new(DVector::from_fn(d.len(), |i, _| i), false).add( WeightFunction::new_scaled(d * psi, WeightFunctionShape::Theta), false, ) } impl<'a> FunctionalContribution for AttractiveFunctional<'a> { fn name(&self) -> &'static str { "Attractive functional" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { att_weight_functions(self.parameters, PSI_DFT, temperature) } fn weight_functions_pdgt<N: DualNum<f64> + Copy>( &self, temperature: N, ) -> WeightFunctionInfo<N> { att_weight_functions(self.parameters, PSI_PDGT, temperature) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, density: ArrayView2<N>, ) -> Result<Array1<N>, FeosError> { // auxiliary variables let p = &self.parameters; let n = p.m.len(); // temperature dependent segment radius let d = p.hs_diameter(temperature); // packing fraction let d3m = d.zip_map(&p.m, |d, m| d.powi(3) * (m * FRAC_PI_6)); let eta = density.outer_iter().zip(&d3m).fold( Array::zeros(density.raw_dim().remove_axis(Axis(0))), |acc: Array1<N>, (rho, &d3m)| acc + &rho * d3m, ); // mean segment number let mut rhog = Array::zeros(eta.raw_dim()); let mut m_bar = Array::zeros(eta.raw_dim()); for (rhoi, &mi) in density.axis_iter(Axis(0)).zip(p.m.iter()) { m_bar += &(&rhoi * mi); rhog += &rhoi; } m_bar.iter_mut().zip(rhog.iter()).for_each(|(m, &r)| { if r.re() > f64::EPSILON { *m /= r } else { *m = N::one() } }); // mixture densities, crosswise interactions of all segments on all chains let mut rho1mix: Array1<N> = Array::zeros(eta.raw_dim()); let mut rho2mix: Array1<N> = Array::zeros(eta.raw_dim()); for i in 0..n { for j in 0..n { let eps_ij_t = temperature.recip() * p.epsilon_k_ij[(i, j)]; let sigma_ij_3 = p.sigma_ij[(i, j)].powi(3); rho1mix = rho1mix + (&density.index_axis(Axis(0), i) * &density.index_axis(Axis(0), j)) .mapv(|x| x * (eps_ij_t * sigma_ij_3 * p.m[i] * p.m[j])); rho2mix = rho2mix + (&density.index_axis(Axis(0), i) * &density.index_axis(Axis(0), j)) .mapv(|x| x * (eps_ij_t * eps_ij_t * sigma_ij_3 * p.m[i] * p.m[j])); } } // I1, I2 and C1 let mut i1: Array1<N> = Array::zeros(eta.raw_dim()); let mut i2: Array1<N> = Array::zeros(eta.raw_dim()); let mut eta_i: Array1<N> = 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 * &eta; } let c1 = Zip::from(&eta).and(&m_bar).map_collect(|&eta, &m| { (m * (eta * 8.0 - eta.powi(2) * 2.0) / (eta - 1.0).powi(4) + (eta * (eta * (eta * (eta * 2.0 - 12.0) + 27.0) - 20.0)) / ((eta - 1.0) * (eta - 2.0)).powi(2) * (m - 1.0) + 1.0) .recip() }); // Helmholtz energy density let phi_polar = helmholtz_energy_density_polar(p, temperature, density)?; Ok((-rho1mix * i1 * 2.0 - rho2mix * m_bar * c1 * i2) * PI + phi_polar) } }
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/dft/pure_saft_functional.rs
.rs
10,940
310
use super::polar::{pair_integral_ij, triplet_integral_ijk}; use crate::association::YuWuAssociationFunctional; use crate::hard_sphere::{FMTVersion, HardSphereProperties}; use crate::pcsaft::eos::dispersion::{A0, A1, A2, B0, B1, B2}; use crate::pcsaft::eos::polar::{AD, AQ, BD, BQ, CD, CQ, PI_SQ_43}; use crate::pcsaft::parameters::PcSaftPars; use feos_core::{FeosError, FeosResult}; use feos_dft::{FunctionalContribution, WeightFunction, WeightFunctionInfo, WeightFunctionShape}; use nalgebra::dvector; use ndarray::*; use num_dual::*; use std::f64::consts::{FRAC_PI_6, PI}; const PI36M1: f64 = 1.0 / (36.0 * PI); const N3_CUTOFF: f64 = 1e-5; const N0_CUTOFF: f64 = 1e-9; pub(crate) struct PureFMTAssocFunctional<'a> { parameters: &'a PcSaftPars, association: Option<YuWuAssociationFunctional<'a, PcSaftPars>>, version: FMTVersion, } impl<'a> PureFMTAssocFunctional<'a> { pub(crate) fn new( params: &'a PcSaftPars, association: Option<YuWuAssociationFunctional<'a, PcSaftPars>>, version: FMTVersion, ) -> Self { Self { parameters: params, association, version, } } } impl<'a> FunctionalContribution for PureFMTAssocFunctional<'a> { fn name(&self) -> &'static str { "Pure FMT+association" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { let r = self.parameters.hs_diameter(temperature) * N::from(0.5); WeightFunctionInfo::new(dvector![0], false).extend( vec![ WeightFunctionShape::Delta, WeightFunctionShape::Theta, WeightFunctionShape::DeltaVec, ] .into_iter() .map(|s| WeightFunction { prefactor: self.parameters.m.map(|m| m.into()), kernel_radius: r.clone(), shape: s, }) .collect(), false, ) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, weighted_densities: ArrayView2<N>, ) -> FeosResult<Array1<N>> { let p = &self.parameters; // weighted densities let n2 = weighted_densities.index_axis(Axis(0), 0); let n3 = weighted_densities.index_axis(Axis(0), 1); let n2v = weighted_densities.slice_axis(Axis(0), Slice::new(2, None, 1)); // temperature dependent segment radius let r = self.parameters.hs_diameter(temperature)[0] * 0.5; // auxiliary variables if n3.iter().any(|n3| n3.re() > 1.0) { return Err(FeosError::IterationFailed(String::from( "PureFMTAssocFunctional", ))); } let ln31 = n3.mapv(|n3| (-n3).ln_1p()); let n3rec = n3.mapv(|n3| n3.recip()); let n3m1 = n3.mapv(|n3| -n3 + 1.0); let n3m1rec = n3m1.mapv(|n3m1| n3m1.recip()); let n1 = n2.mapv(|n2| n2 / (r * 4.0 * PI)); let n0 = n2.mapv(|n2| n2 / (r * r * 4.0 * PI)); let n1v = n2v.mapv(|n2v| n2v / (r * 4.0 * PI)); let (n1n2, n2n2) = match self.version { FMTVersion::WhiteBear => ( &n1 * &n2 - (&n1v * &n2v).sum_axis(Axis(0)), &n2 * &n2 - (&n2v * &n2v).sum_axis(Axis(0)) * 3.0, ), FMTVersion::AntiSymWhiteBear => { let mut xi2 = (&n2v * &n2v).sum_axis(Axis(0)) / n2.map(|n| n.powi(2)); xi2.iter_mut().for_each(|x| { if x.re() > 1.0 { *x = N::one() } }); ( &n1 * &n2 - (&n1v * &n2v).sum_axis(Axis(0)), &n2 * &n2 * xi2.mapv(|x| (-x + 1.0).powi(3)), ) } _ => unreachable!(), }; // The f3 term contains a 0/0, therefore a taylor expansion is used for small values of n3 let mut f3 = (&n3m1 * &n3m1 * &ln31 + n3) * &n3rec * n3rec * &n3m1rec * &n3m1rec; f3.iter_mut().zip(n3).for_each(|(f3, &n3)| { if n3.re() < N3_CUTOFF { *f3 = (((n3 * 35.0 / 6.0 + 4.8) * n3 + 3.75) * n3 + 8.0 / 3.0) * n3 + 1.5; } }); let mut phi = -(&n0 * &ln31) + n1n2 * &n3m1rec + n2n2 * n2 * PI36M1 * f3; // association if let Some(a) = self.association.as_ref() { let mut xi = -(&n2v * &n2v).sum_axis(Axis(0)) / (&n2 * &n2) + 1.0; xi.iter_mut().zip(&n2).for_each(|(xi, &n2)| { if n2.re() < N0_CUTOFF * 4.0 * PI * p.m[0] * r.re().powi(2) { *xi = N::one(); } }); let rho0 = (&n0 / p.m[0] * &xi).insert_axis(Axis(0)); phi += &(a._helmholtz_energy_density(temperature, &rho0, &n2, &n3m1rec, &xi))?; } Ok(phi) } } #[derive(Clone)] pub(crate) struct PureChainFunctional<'a> { parameters: &'a PcSaftPars, } impl<'a> PureChainFunctional<'a> { pub(crate) fn new(parameters: &'a PcSaftPars) -> Self { Self { parameters } } } impl<'a> FunctionalContribution for PureChainFunctional<'a> { fn name(&self) -> &'static str { "Pure chain" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { let d = self.parameters.hs_diameter(temperature); WeightFunctionInfo::new(dvector![0], true) .add( WeightFunction::new_scaled(d.clone(), WeightFunctionShape::Delta), false, ) .add( WeightFunction { prefactor: (&self.parameters.m / 8.0).map(|x| x.into()), kernel_radius: d, shape: WeightFunctionShape::Theta, }, false, ) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, _: N, weighted_densities: ArrayView2<N>, ) -> FeosResult<Array1<N>> { let rho = weighted_densities.index_axis(Axis(0), 0); // negative lambdas lead to nan, therefore the absolute value is used let lambda = weighted_densities .index_axis(Axis(0), 1) .map(|&l| if l.re() < 0.0 { -l } else { l } + N::from(f64::EPSILON)); let eta = weighted_densities.index_axis(Axis(0), 2); let y = eta.mapv(|eta| (eta * 0.5 - 1.0) / (eta - 1.0).powi(3)); Ok(-(y * lambda).mapv(|x| (x.ln() - 1.0) * (self.parameters.m[0] - 1.0)) * rho) } } #[derive(Clone)] pub(crate) struct PureAttFunctional<'a> { parameters: &'a PcSaftPars, } impl<'a> PureAttFunctional<'a> { pub(crate) fn new(parameters: &'a PcSaftPars) -> Self { Self { parameters } } } impl<'a> FunctionalContribution for PureAttFunctional<'a> { fn name(&self) -> &'static str { "Pure attractive" } fn weight_functions<N: DualNum<f64> + Copy>(&self, temperature: N) -> WeightFunctionInfo<N> { let d = self.parameters.hs_diameter(temperature); const PSI: f64 = 1.3862; // Homosegmented DFT (Sauer2017) let psi = N::from(PSI); WeightFunctionInfo::new(dvector![0], false).add( WeightFunction::new_scaled(d * psi, WeightFunctionShape::Theta), false, ) } fn weight_functions_pdgt<N: DualNum<f64> + Copy>( &self, temperature: N, ) -> WeightFunctionInfo<N> { let d = self.parameters.hs_diameter(temperature); const PSI: f64 = 1.3286; // pDGT (Rehner2018) let psi = N::from(PSI); WeightFunctionInfo::new(dvector![0], false).add( WeightFunction::new_scaled(d * psi, WeightFunctionShape::Theta), false, ) } fn helmholtz_energy_density<N: DualNum<f64> + Copy>( &self, temperature: N, weighted_densities: ArrayView2<N>, ) -> FeosResult<Array1<N>> { let p = &self.parameters; let rho = weighted_densities.index_axis(Axis(0), 0); // temperature dependent segment radius let d = p.hs_diameter(temperature)[0]; let eta = rho.mapv(|rho| rho * FRAC_PI_6 * p.m[0] * d.powi(3)); let m1 = (p.m[0] - 1.0) / p.m[0]; let m2 = m1 * (p.m[0] - 2.0) / p.m[0]; let e = temperature.recip() * p.epsilon_k[0]; let s3 = p.sigma[0].powi(3); // I1, I2 and C1 let mut i1: Array1<N> = Array::zeros(eta.raw_dim()); let mut i2: Array1<N> = Array::zeros(eta.raw_dim()); for i in 0..=6 { i1 = i1 + eta.mapv(|eta| eta.powi(i as i32) * (A0[i] + m1 * A1[i] + m2 * A2[i])); i2 = i2 + eta.mapv(|eta| eta.powi(i as i32) * (B0[i] + m1 * B1[i] + m2 * B2[i])); } let c1 = eta.mapv(|eta| { ((eta * 8.0 - eta.powi(2) * 2.0) / (eta - 1.0).powi(4) * p.m[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 - p.m[0]) + 1.0) .recip() }); let mut phi = rho.mapv(|rho| -(rho * p.m[0]).powi(2) * e * s3 * PI) * (i1 * 2.0 + c1 * i2.mapv(|i2| i2 * p.m[0] * e)); // dipoles if p.ndipole > 0 { let mu2_term = e * s3 * p.mu2[0]; let m = p.m[0].min(2.0); let m1 = (m - 1.0) / m; let m2 = m1 * (m - 2.0) / m; let phi2 = -(&rho * &rho) * pair_integral_ij(m1, m2, &eta, &AD, &BD, e) * (mu2_term * mu2_term / s3 * PI); let phi3 = -(&rho * &rho * rho) * triplet_integral_ijk(m1, m2, &eta, &CD) * (mu2_term * mu2_term * mu2_term / s3 * PI_SQ_43); let mut phi_d = &phi2 * &phi2 / (&phi2 - &phi3); phi_d.iter_mut().zip(phi2.iter()).for_each(|(p, &p2)| { if p.re().is_nan() { *p = p2; } }); phi += &phi_d; } // quadrupoles if p.nquadpole > 0 { let q2_term = e * p.sigma[0].powi(5) * p.q2[0]; let m = p.m[0].min(2.0); let m1 = (m - 1.0) / m; let m2 = m1 * (m - 2.0) / m; let phi2 = -(&rho * &rho) * pair_integral_ij(m1, m2, &eta, &AQ, &BQ, e) * (q2_term * q2_term / p.sigma[0].powi(7) * PI * 0.5625); let phi3 = (&rho * &rho * rho) * triplet_integral_ijk(m1, m2, &eta, &CQ) * (q2_term * q2_term * q2_term / s3.powi(3) * PI * PI * 0.5625); let mut phi_q = &phi2 * &phi2 / (&phi2 - &phi3); phi_q.iter_mut().zip(phi2.iter()).for_each(|(p, &p2)| { if p.re().is_nan() { *p = p2; } }); phi += &phi_q; } Ok(phi) } }
Rust
3D
feos-org/feos
crates/feos/src/pcsaft/dft/polar.rs
.rs
14,011
369
use crate::hard_sphere::HardSphereProperties; use crate::pcsaft::eos::polar::{ AD, ADQ, ALPHA, AQ, BD, BDQ, BQ, CD, CDQ, CQ, MeanSegmentNumbers, Multipole, PI_SQ_43, }; use crate::pcsaft::parameters::PcSaftPars; use feos_core::FeosError; use ndarray::*; use num_dual::DualNum; use std::f64::consts::{FRAC_PI_3, PI}; pub(super) fn helmholtz_energy_density_polar<N: DualNum<f64> + Copy>( parameters: &PcSaftPars, temperature: N, density: ArrayView2<N>, ) -> Result<Array1<N>, FeosError> { // temperature dependent segment radius let r = parameters.hs_diameter(temperature) * N::from(0.5); // packing fraction let r3m = r.zip_map(&parameters.m, |r, m| r * r * r * (m * 4.0 * FRAC_PI_3)); let eta = density.outer_iter().zip(&r3m).fold( Array::zeros(density.raw_dim().remove_axis(Axis(0))), |acc: Array1<N>, (rho, &r3m)| acc + &rho * r3m, ); let mut phi = Array::zeros(eta.raw_dim()); if parameters.ndipole > 0 { phi += &phi_polar_dipole(parameters, temperature, density, &eta)?; } if parameters.nquadpole > 0 { phi += &phi_polar_quadrupole(parameters, temperature, density, &eta)?; } if parameters.ndipole > 0 && parameters.nquadpole > 0 { phi += &phi_polar_dipole_quadrupole(parameters, temperature, density, &eta)?; } Ok(phi) } pub fn pair_integral_ij<N: DualNum<f64> + Copy>( mij1: f64, mij2: f64, eta: &Array1<N>, a: &[[f64; 3]], b: &[[f64; 3]], eps_ij_t: N, ) -> Array1<N> { let eta2 = eta * eta; let etas = [ &Array::ones(eta.raw_dim()), eta, &eta2, &(&eta2 * eta), &(&eta2 * &eta2), ]; let mut integral = Array::zeros(eta.raw_dim()); for i in 0..a.len() { integral += &(etas[i] * (eps_ij_t * (b[i][0] + mij1 * b[i][1] + mij2 * b[i][2]) + a[i][0] + mij1 * a[i][1] + mij2 * a[i][2])); } integral } pub fn triplet_integral_ijk<N: DualNum<f64>>( mijk1: f64, mijk2: f64, eta: &Array1<N>, c: &[[f64; 3]], ) -> Array1<N> { let eta2 = eta * eta; let etas = [&Array::ones(eta.raw_dim()), eta, &eta2, &(&eta2 * eta)]; let mut integral = Array::zeros(eta.raw_dim()); for i in 0..c.len() { integral += &(etas[i] * (c[i][0] + mijk1 * c[i][1] + mijk2 * c[i][2])); } integral } fn triplet_integral_ijk_dq<N: DualNum<f64>>( mijk: f64, eta: &Array1<N>, c: &[[f64; 2]], ) -> Array1<N> { let etas = [&Array::ones(eta.raw_dim()), eta, &(eta * eta)]; let mut integral = Array::zeros(eta.raw_dim()); for i in 0..c.len() { integral += &(etas[i] * (c[i][0] + mijk * c[i][1])); } integral } fn phi_polar_dipole<N: DualNum<f64> + Copy>( p: &PcSaftPars, temperature: N, density: ArrayView2<N>, eta: &Array1<N>, ) -> Result<Array1<N>, FeosError> { // mean segment number let m = MeanSegmentNumbers::new(p, Multipole::Dipole); let t_inv = 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: Array1<N> = p .dipole_comp .iter() .map(|&i| eps_ij_t[(i, i)] * sig_ij_3[(i, i)] * p.mu2[i]) .collect(); let mut phi2 = Array::zeros(eta.raw_dim()); let mut phi3 = Array::zeros(eta.raw_dim()); for i in 0..p.ndipole { let di = p.dipole_comp[i]; phi2 -= &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), di) * pair_integral_ij( m.mij1[(i, i)], m.mij2[(i, i)], eta, &AD, &BD, eps_ij_t[(di, di)], ) * (mu2_term[i] * mu2_term[i] / sig_ij_3[(di, di)])); phi3 -= &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), di) * density.index_axis(Axis(0), di) * triplet_integral_ijk(m.mijk1[i][(i, i)], m.mijk2[i][(i, i)], eta, &CD) * (mu2_term[i] * mu2_term[i] * mu2_term[i] / sig_ij_3[(di, di)])); for j in i + 1..p.ndipole { let dj = p.dipole_comp[j]; phi2 -= &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), dj) * pair_integral_ij( m.mij1[(i, j)], m.mij2[(i, j)], eta, &AD, &BD, eps_ij_t[(di, dj)], ) * (mu2_term[i] * mu2_term[j] / sig_ij_3[(di, dj)] * 2.0)); phi3 -= &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), di) * density.index_axis(Axis(0), dj) * triplet_integral_ijk(m.mijk1[i][(i, j)], m.mijk2[i][(i, j)], eta, &CD) * (mu2_term[i] * mu2_term[i] * mu2_term[j] / (p.sigma_ij[(di, di)] * p.sigma_ij[(di, dj)] * p.sigma_ij[(di, dj)]) * 3.0)); phi3 -= &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), dj) * density.index_axis(Axis(0), dj) * triplet_integral_ijk(m.mijk1[i][(j, j)], m.mijk2[i][(j, j)], eta, &CD) * (mu2_term[i] * mu2_term[j] * mu2_term[j] / (p.sigma_ij[(di, dj)] * p.sigma_ij[(di, dj)] * p.sigma_ij[(dj, dj)]) * 3.0)); for k in j + 1..p.ndipole { let dk = p.dipole_comp[k]; phi3 -= &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), dj) * density.index_axis(Axis(0), dk) * triplet_integral_ijk(m.mijk1[i][(j, k)], m.mijk2[i][(j, k)], eta, &CD) * (mu2_term[i] * mu2_term[j] * mu2_term[k] / (p.sigma_ij[(di, dj)] * p.sigma_ij[(di, dk)] * p.sigma_ij[(dj, dk)]) * 6.0)); } } } phi2 = phi2 * PI; phi3 = phi3 * PI_SQ_43; let mut result = &phi2 * &phi2 / (&phi2 - &phi3); result.iter_mut().zip(phi2.iter()).for_each(|(r, &p2)| { if r.re().is_nan() { *r = p2; } }); Ok(result) } fn phi_polar_quadrupole<N: DualNum<f64> + Copy>( p: &PcSaftPars, temperature: N, density: ArrayView2<N>, eta: &Array1<N>, ) -> Result<Array1<N>, FeosError> { // mean segment number let m = MeanSegmentNumbers::new(p, Multipole::Quadrupole); let t_inv = 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 q2_term: Array1<N> = p .quadpole_comp .iter() .map(|&i| eps_ij_t[(i, i)] * p.sigma[i].powi(5) * p.q2[i]) .collect(); let mut phi2 = Array::zeros(eta.raw_dim()); let mut phi3 = Array::zeros(eta.raw_dim()); for i in 0..p.nquadpole { let di = p.quadpole_comp[i]; phi2 -= &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), di) * pair_integral_ij( m.mij1[(i, i)], m.mij2[(i, i)], eta, &AQ, &BQ, eps_ij_t[(di, di)], ) * (q2_term[i] * q2_term[i] / p.sigma_ij[(di, di)].powi(7))); phi3 += &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), di) * density.index_axis(Axis(0), di) * triplet_integral_ijk(m.mijk1[i][(i, i)], m.mijk2[i][(i, i)], eta, &CQ) * (q2_term[i] * q2_term[i] * q2_term[i] / sig_ij_3[(di, di)].powi(3))); for j in i + 1..p.nquadpole { let dj = p.quadpole_comp[j]; phi2 -= &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), dj) * pair_integral_ij( m.mij1[(i, j)], m.mij2[(i, j)], eta, &AQ, &BQ, eps_ij_t[(di, dj)], ) * (q2_term[i] * q2_term[j] / p.sigma_ij[(di, dj)].powi(7))); phi3 += &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), di) * density.index_axis(Axis(0), dj) * triplet_integral_ijk(m.mijk1[i][(i, j)], m.mijk2[i][(i, j)], eta, &CQ) * (q2_term[i] * q2_term[i] * q2_term[j] / (sig_ij_3[(di, di)] * sig_ij_3[(di, dj)] * sig_ij_3[(di, dj)]) * 3.0)); phi3 += &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), dj) * density.index_axis(Axis(0), dj) * triplet_integral_ijk(m.mijk1[i][(j, j)], m.mijk2[i][(j, j)], eta, &CQ) * (q2_term[i] * q2_term[j] * q2_term[j] / (sig_ij_3[(di, dj)] * sig_ij_3[(di, dj)] * sig_ij_3[(dj, dj)]) * 3.0)); for k in j + 1..p.nquadpole { let dk = p.quadpole_comp[k]; phi3 += &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), dj) * density.index_axis(Axis(0), dk) * triplet_integral_ijk(m.mijk1[i][(j, k)], m.mijk2[i][(j, k)], eta, &CQ) * (q2_term[i] * q2_term[j] * q2_term[k] / (sig_ij_3[(di, dj)] * sig_ij_3[(di, dk)] * sig_ij_3[(dj, dk)]) * 6.0)); } } } phi2 = phi2 * (PI * 0.5625); phi3 = phi3 * (PI * PI * 0.5625); let mut result = &phi2 * &phi2 / (&phi2 - &phi3); result.iter_mut().zip(phi2.iter()).for_each(|(r, &p2)| { if r.re().is_nan() { *r = p2; } }); Ok(result) } fn phi_polar_dipole_quadrupole<N: DualNum<f64> + Copy>( p: &PcSaftPars, temperature: N, density: ArrayView2<N>, eta: &Array1<N>, ) -> Result<Array1<N>, FeosError> { let t_inv = temperature.inv(); let eps_ij_t = p.e_k_ij.map(|v| t_inv * v); let mu2_term: Array1<N> = p .dipole_comp .iter() .map(|&i| eps_ij_t[(i, i)] * p.sigma[i].powi(4) * p.mu2[i]) .collect(); let q2_term: Array1<N> = p .quadpole_comp .iter() .map(|&i| eps_ij_t[(i, i)] * p.sigma[i].powi(4) * p.q2[i]) .collect(); // mean segment number let mut mdq1 = Array2::zeros((p.ndipole, p.nquadpole)); let mut mdq2 = Array2::zeros((p.ndipole, p.nquadpole)); let mut mdqd = Array3::zeros((p.ndipole, p.nquadpole, p.ndipole)); let mut mdqq = Array3::zeros((p.ndipole, p.nquadpole, p.nquadpole)); for i in 0..p.ndipole { let di = p.dipole_comp[i]; let mi = p.m[di].min(2.0); for j in 0..p.nquadpole { let qj = p.quadpole_comp[j]; let mj = p.m[qj].min(2.0); let m = (mi * mj).sqrt(); mdq1[(i, j)] = (m - 1.0) / m; mdq2[(i, j)] = mdq1[(i, j)] * (m - 2.0) / m; for k in 0..p.ndipole { let dk = p.dipole_comp[k]; let mk = p.m[dk].min(2.0); let m = (mi * mj * mk).cbrt(); mdqd[(i, j, k)] = (m - 1.0) / m; } for k in 0..p.nquadpole { let qk = p.quadpole_comp[k]; let mk = p.m[qk].min(2.0); let m = (mi * mj * mk).cbrt(); mdqq[(i, j, k)] = (m - 1.0) / m; } } } let mut phi2 = Array::zeros(eta.raw_dim()); let mut phi3 = Array::zeros(eta.raw_dim()); for i in 0..p.ndipole { let di = p.dipole_comp[i]; for j in 0..p.nquadpole { let qj = p.quadpole_comp[j]; phi2 -= &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), qj) * pair_integral_ij( mdq1[(i, j)], mdq2[(i, j)], eta, &ADQ, &BDQ, eps_ij_t[(di, qj)], ) * (mu2_term[i] / p.sigma[di] * q2_term[j] * p.sigma[qj] / p.sigma_ij[(di, qj)].powi(5))); for k in 0..p.ndipole { let dk = p.dipole_comp[k]; phi3 += &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), qj) * density.index_axis(Axis(0), dk) * triplet_integral_ijk_dq(mdqd[(i, j, k)], eta, &CDQ) * (mu2_term[i] * q2_term[j] * mu2_term[k] / (p.sigma_ij[(di, qj)] * p.sigma_ij[(di, dk)] * p.sigma_ij[(qj, dk)]) .powi(2))); } for k in 0..p.nquadpole { let qk = p.quadpole_comp[k]; phi3 += &(&density.index_axis(Axis(0), di) * &density.index_axis(Axis(0), qj) * density.index_axis(Axis(0), qk) * triplet_integral_ijk_dq(mdqq[(i, j, k)], eta, &CDQ) * (mu2_term[i] * q2_term[j] * q2_term[k] / (p.sigma_ij[(di, qj)] * p.sigma_ij[(di, qk)] * p.sigma_ij[(qj, qk)]) .powi(2) * ALPHA)); } } } phi2 = phi2 * (PI * 2.25); phi3 = phi3 * (PI * PI); let mut result = &phi2 * &phi2 / (&phi2 - &phi3); result.iter_mut().zip(phi2.iter()).for_each(|(r, &p2)| { if r.re().is_nan() { *r = p2; } }); Ok(result) }
Rust
3D
feos-org/feos
crates/feos/src/epcsaft/mod.rs
.rs
319
10
//! Electrolyte Perturbed-Chain Statistical Associating Fluid Theory (ePC-SAFT) mod eos; pub(crate) mod parameters; pub use eos::{ElectrolytePcSaft, ElectrolytePcSaftOptions, ElectrolytePcSaftVariants}; pub use parameters::{ ElectrolytePcSaftBinaryRecord, ElectrolytePcSaftParameters, ElectrolytePcSaftRecord, };
Rust
3D
feos-org/feos
crates/feos/src/epcsaft/parameters.rs
.rs
25,501
773
use crate::association::AssociationStrength; use crate::epcsaft::eos::permittivity::PermittivityRecord; use crate::hard_sphere::{HardSphereProperties, MonomerShape}; use feos_core::parameter::{CombiningRule, FromSegments, Parameters}; use feos_core::{FeosError, FeosResult}; use nalgebra::{DMatrix, DVector}; use num_dual::DualNum; use num_traits::Zero; use serde::{Deserialize, Serialize}; /// ePC-SAFT pure-component parameters. #[derive(Serialize, Deserialize, Clone, Default)] pub struct ElectrolytePcSaftRecord { /// Segment number pub m: f64, /// Segment diameter in units of Angstrom pub sigma: f64, /// Energetic parameter in units of Kelvin pub epsilon_k: f64, #[serde(default)] #[serde(skip_serializing_if = "f64::is_zero")] pub z: f64, #[serde(skip_serializing_if = "Option::is_none")] pub permittivity_record: Option<PermittivityRecord>, } impl FromSegments for ElectrolytePcSaftRecord { fn from_segments(segments: &[(Self, f64)]) -> FeosResult<Self> { let mut m = 0.0; let mut sigma3 = 0.0; let mut epsilon_k = 0.0; let mut z = 0.0; segments.iter().for_each(|(s, n)| { m += s.m * n; sigma3 += s.m * s.sigma.powi(3) * n; epsilon_k += s.m * s.epsilon_k * n; z += s.z; }); Ok(Self { m, sigma: (sigma3 / m).cbrt(), epsilon_k: epsilon_k / m, z, permittivity_record: None, }) } } impl ElectrolytePcSaftRecord { pub fn new( m: f64, sigma: f64, epsilon_k: f64, z: f64, permittivity_record: Option<PermittivityRecord>, ) -> ElectrolytePcSaftRecord { ElectrolytePcSaftRecord { m, sigma, epsilon_k, z, permittivity_record, } } } #[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Debug)] pub struct ElectrolytePcSaftAssociationRecord { /// Association volume parameter pub kappa_ab: f64, /// Association energy parameter in units of Kelvin pub epsilon_k_ab: f64, } impl ElectrolytePcSaftAssociationRecord { pub fn new(kappa_ab: f64, epsilon_k_ab: f64) -> Self { Self { kappa_ab, epsilon_k_ab, } } } impl CombiningRule<ElectrolytePcSaftRecord> for ElectrolytePcSaftAssociationRecord { fn combining_rule( _: &ElectrolytePcSaftRecord, _: &ElectrolytePcSaftRecord, 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), } } } /// ePC-SAFT binary interaction parameters. #[derive(Serialize, Deserialize, Clone, Default)] pub struct ElectrolytePcSaftBinaryRecord { /// Binary dispersion interaction parameter pub k_ij: Vec<f64>, } impl ElectrolytePcSaftBinaryRecord { pub fn new(k_ij: Vec<f64>) -> Self { Self { k_ij } } } /// Parameter set required for the ePC-SAFT equation of state. pub type ElectrolytePcSaftParameters = Parameters< ElectrolytePcSaftRecord, ElectrolytePcSaftBinaryRecord, ElectrolytePcSaftAssociationRecord, >; /// Parameter set required for the ePC-SAFT equation of state. pub struct ElectrolytePcSaftPars { pub m: DVector<f64>, pub sigma: DVector<f64>, pub epsilon_k: DVector<f64>, pub z: DVector<f64>, pub k_ij: DMatrix<Vec<f64>>, pub sigma_ij: DMatrix<f64>, pub e_k_ij: DMatrix<f64>, pub nionic: usize, pub nsolvent: usize, pub water_sigma_t_comp: Option<usize>, pub ionic_comp: DVector<usize>, pub solvent_comp: DVector<usize>, pub permittivity: Vec<Option<PermittivityRecord>>, } impl ElectrolytePcSaftPars { pub fn sigma_t<D: DualNum<f64> + Copy>(&self, temperature: D) -> DVector<D> { let mut sigma_t = DVector::from_fn(self.sigma.len(), |i, _| D::from(self.sigma[i])); if let Some(i) = self.water_sigma_t_comp { sigma_t[i] += (temperature * -0.01775).exp() * 10.11 - (temperature * -0.01146).exp() * 1.417; } sigma_t } pub fn sigma_ij_t<D: DualNum<f64> + Copy>(&self, temperature: D) -> DMatrix<D> { let diameter = self.sigma_t(temperature); let n = diameter.len(); let mut sigma_ij_t = DMatrix::zeros(n, n); for i in 0..n { for j in 0..n { sigma_ij_t[(i, j)] = (diameter[i] + diameter[j]) * 0.5; } } sigma_ij_t } } impl ElectrolytePcSaftPars { pub fn new(parameters: &ElectrolytePcSaftParameters) -> FeosResult<Self> { let n = parameters.pure.len(); let [m, sigma, epsilon_k, z] = parameters.collate(|pr| [pr.m, pr.sigma, pr.epsilon_k, pr.z]); let mut water_sigma_t_comp = None; for (i, _) in parameters.pure.iter().enumerate() { // check if component i is water with temperature-dependent sigma if (m[i] * 1000.0).round() / 1000.0 == 1.205 && epsilon_k[i].round() == 354.0 { // Godforsaken code below // // if let Some(record) = record.association_sites.first() { // if let Some(assoc) = record.parameters { // if (assoc.kappa_ab * 1000.0).round() / 1000.0 == 0.045 // && assoc.epsilon_k_ab.round() == 2426.0 // { water_sigma_t_comp = Some(i); // } // } // } } } let ionic_comp: DVector<usize> = z .iter() .enumerate() .filter_map(|(i, &zi)| (zi.abs() > 0.0).then_some(i)) .collect::<Vec<_>>() .into(); let nionic = ionic_comp.len(); let solvent_comp: DVector<usize> = z .iter() .enumerate() .filter_map(|(i, &zi)| (zi.abs() == 0.0).then_some(i)) .collect::<Vec<_>>() .into(); let nsolvent = solvent_comp.len(); let mut k_ij: DMatrix<Vec<f64>> = DMatrix::from_element(n, n, vec![0., 0., 0., 0.]); for br in &parameters.binary { let i = br.id1; let j = br.id2; let r = &br.model_record; if r.k_ij.len() > 4 { return Err(FeosError::IncompatibleParameters(format!( "Binary interaction for component {i} with {j} is parametrized with more than 4 k_ij coefficients." ))); } else { (0..r.k_ij.len()).for_each(|k| { k_ij[(i, j)][k] = r.k_ij[k]; k_ij[(j, i)][k] = r.k_ij[k]; }); } } // No binary interaction between charged species of same kind (+/+ and -/-) ionic_comp.iter().for_each(|&ai| { k_ij[(ai, ai)][0] = 1.0; for k in 1..4usize { k_ij[(ai, ai)][k] = 0.0; } }); let mut sigma_ij = DMatrix::zeros(n, n); let mut e_k_ij = DMatrix::zeros(n, n); for i in 0..n { for j in 0..n { e_k_ij[(i, j)] = (epsilon_k[i] * epsilon_k[j]).sqrt(); sigma_ij[(i, j)] = 0.5 * (sigma[i] + sigma[j]); } } // Permittivity records let mut permittivity_records: Vec<Option<PermittivityRecord>> = parameters .pure .iter() .map(|record| record.clone().model_record.permittivity_record) .collect(); // Check if permittivity_records contains maximum one record for each solvent // Permittivity if nionic != 0 && permittivity_records .iter() .enumerate() .any(|(i, record)| record.is_none() && z[i] == 0.0) { return Err(FeosError::IncompatibleParameters( "Provide permittivity record for all solvent components.".to_string(), )); } let mut modeltypes: Vec<usize> = vec![]; permittivity_records .iter() .filter(|&record| record.is_some()) .for_each(|record| match record.as_ref().unwrap() { PermittivityRecord::PerturbationTheory { .. } => { modeltypes.push(1); } PermittivityRecord::ExperimentalData { .. } => { modeltypes.push(2); } }); // check if modeltypes contains a mix of 1 and 2 if modeltypes.contains(&1) && modeltypes.contains(&2) { return Err(FeosError::IncompatibleParameters( "Inconsistent models for permittivity.".to_string(), )); } if !modeltypes.is_empty() && modeltypes[0] == 2 { for permittivity_record in &permittivity_records { if let Some(PermittivityRecord::ExperimentalData { data }) = permittivity_record.as_ref() { // check if length of data is greater than 0 if data.is_empty() { return Err(FeosError::IncompatibleParameters( "Experimental data for permittivity must contain at least one data point.".to_string(), )); } } } } if !modeltypes.is_empty() && modeltypes[0] == 2 { // order points in data by increasing temperature let mut permittivity_records_clone = permittivity_records.clone(); permittivity_records_clone .iter_mut() .filter(|record| record.is_some()) .enumerate() .for_each(|(i, record)| { if let PermittivityRecord::ExperimentalData { data } = record.as_mut().unwrap() { let mut data = data.clone(); data.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap()); // check if all temperatures a.0 in data are finite, if not, make them finite by rounding to four digits data.iter_mut().for_each(|a| { if !a.0.is_finite() { a.0 = (a.0 * 1e4).round() / 1e4; } }); // save data again in record permittivity_records[i] = Some(PermittivityRecord::ExperimentalData { data }); } }); } Ok(Self { m, sigma, epsilon_k, z, k_ij, sigma_ij, e_k_ij, nionic, nsolvent, ionic_comp, solvent_comp, water_sigma_t_comp, permittivity: permittivity_records, }) } } impl HardSphereProperties for ElectrolytePcSaftPars { fn monomer_shape<N: DualNum<f64>>(&self, _: N) -> MonomerShape<'_, N> { MonomerShape::NonSpherical(self.m.map(N::from)) } fn hs_diameter<D: DualNum<f64> + Copy>(&self, temperature: D) -> DVector<D> { let sigma_t = self.sigma_t(temperature); let ti = temperature.recip() * -3.0; let mut d = DVector::from_fn(sigma_t.len(), |i, _| { -((ti * self.epsilon_k[i]).exp() * 0.12 - 1.0) * sigma_t[i] }); for i in 0..self.nionic { let ai = self.ionic_comp[i]; d[ai] = D::one() * sigma_t[ai] * (1.0 - 0.12); } d } } impl AssociationStrength for ElectrolytePcSaftPars { type Record = ElectrolytePcSaftAssociationRecord; fn association_strength_ij<D: DualNum<f64> + Copy>( &self, temperature: D, comp_i: usize, comp_j: usize, assoc_ij: &Self::Record, ) -> D { let sigma_t = self.sigma_t(temperature); let si = sigma_t[comp_i]; let sj = sigma_t[comp_j]; (temperature.recip() * assoc_ij.epsilon_k_ab).exp_m1() * assoc_ij.kappa_ab * (si * sj).powf(1.5) } } #[cfg(test)] pub mod utils { use super::*; use feos_core::parameter::{BinaryRecord, Identifier, IdentifierOption, PureRecord}; type Pure = PureRecord<ElectrolytePcSaftRecord, ElectrolytePcSaftAssociationRecord>; type Binary = BinaryRecord<Identifier, ElectrolytePcSaftBinaryRecord, ElectrolytePcSaftAssociationRecord>; pub fn propane_parameters() -> ElectrolytePcSaftParameters { let propane_json = r#" { "identifier": { "cas": "74-98-6", "name": "propane", "iupac_name": "propane", "smiles": "CCC", "inchi": "InChI=1/C3H8/c1-3-2/h3H2,1-2H3", "formula": "C3H8" }, "m": 2.001829, "sigma": 3.618353, "epsilon_k": 208.1101, "molarweight": 44.0962 }"#; let propane_record: Pure = serde_json::from_str(propane_json).expect("Unable to parse json."); ElectrolytePcSaftParameters::new_pure(propane_record).unwrap() } pub fn butane_parameters() -> ElectrolytePcSaftParameters { let butane_json = r#" { "identifier": { "cas": "106-97-8", "name": "butane", "iupac_name": "butane", "smiles": "CCCC", "inchi": "InChI=1/C4H10/c1-3-4-2/h3-4H2,1-2H3", "formula": "C4H10" }, "m": 2.331586, "sigma": 3.7086010000000003, "epsilon_k": 222.8774, "molarweight": 58.123 }"#; let butane_record: Pure = serde_json::from_str(butane_json).expect("Unable to parse json."); ElectrolytePcSaftParameters::new_pure(butane_record).unwrap() } pub fn water_nacl_parameters_perturb() -> ElectrolytePcSaftParameters { // Water parameters from Held et al. (2014), originally from Fuchs et al. (2006) let pure_json = r#"[ { "identifier": { "cas": "7732-18-5", "name": "water_np_sigma_t", "iupac_name": "oxidane", "smiles": "O", "inchi": "InChI=1/H2O/h1H2", "formula": "H2O" }, "m": 1.2047, "sigma": 2.7927, "epsilon_k": 353.95, "kappa_ab": 0.04509, "epsilon_k_ab": 2425.7, "permittivity_record": { "PerturbationTheory": { "dipole_scaling": 5.199 , "polarizability_scaling": 0.0 , "correlation_integral_parameter": 0.1276 } }, "molarweight": 18.0152 }, { "identifier": { "cas": "110-54-3", "name": "na+", "formula": "na+" }, "m": 1, "sigma": 2.8232, "epsilon_k": 230.0, "z": 1, "permittivity_record": { "PerturbationTheory": { "dipole_scaling": 0.0, "polarizability_scaling": 0.0, "correlation_integral_parameter": 0.0658 } }, "molarweight": 22.98977 }, { "identifier": { "cas": "7782-50-5", "name": "cl-", "formula": "cl-" }, "m": 1, "sigma": 2.7560, "epsilon_k": 170, "z": -1, "permittivity_record": { "PerturbationTheory": { "dipole_scaling": 7.3238, "polarizability_scaling": 0.0, "correlation_integral_parameter": 0.2620 } }, "molarweight": 35.45 } ]"#; let binary_json = r#"[ { "id1": { "cas": "7732-18-5", "name": "water_np_sigma_t", "iupac_name": "oxidane", "smiles": "O", "inchi": "InChI=1/H2O/h1H2", "formula": "H2O" }, "id2": { "cas": "110-54-3", "name": "sodium ion", "formula": "na+" }, "k_ij": [ 0.0045, 0.0, 0.0, 0.0 ] }, { "id1": { "cas": "7732-18-5", "name": "water_np_sigma_t", "iupac_name": "oxidane", "smiles": "O", "inchi": "InChI=1/H2O/h1H2", "formula": "H2O" }, "id2": { "cas": "7782-50-5", "name": "chloride ion", "formula": "cl-" }, "k_ij": [ -0.25, 0.0, 0.0, 0.0 ] }, { "id1": { "cas": "110-54-3", "name": "sodium ion", "formula": "na+" }, "id2": { "cas": "7782-50-5", "name": "chloride ion", "formula": "cl-" }, "k_ij": [ 0.317, 0.0, 0.0, 0.0 ] } ]"#; let pure_records: Vec<Pure> = serde_json::from_str(pure_json).expect("Unable to parse json."); let binary_records: Vec<Binary> = serde_json::from_str(binary_json).expect("Unable to parse json."); ElectrolytePcSaftParameters::from_records( pure_records, binary_records, IdentifierOption::Name, ) .unwrap() } pub fn water_nacl_parameters() -> ElectrolytePcSaftParameters { // Water parameters from Held et al. (2014), originally from Fuchs et al. (2006) let pure_json = r#"[ { "identifier": { "cas": "7732-18-5", "name": "water_np_sigma_t", "iupac_name": "oxidane", "smiles": "O", "inchi": "InChI=1/H2O/h1H2", "formula": "H2O" }, "m": 1.2047, "sigma": 2.7927, "epsilon_k": 353.95, "kappa_ab": 0.04509, "epsilon_k_ab": 2425.7, "permittivity_record": { "ExperimentalData": { "data": [ [ 280.15, 84.89 ], [ 298.15, 78.39 ], [ 360.15, 58.73 ] ] } }, "molarweight": 18.0152 }, { "identifier": { "cas": "110-54-3", "name": "na+", "formula": "na+" }, "m": 1, "sigma": 2.8232, "epsilon_k": 230.0, "z": 1, "permittivity_record": { "ExperimentalData": { "data": [ [ 298.15, 8.0 ] ] } }, "molarweight": 22.98977 }, { "identifier": { "cas": "7782-50-5", "name": "cl-", "formula": "cl-" }, "m": 1, "sigma": 2.7560, "epsilon_k": 170, "z": -1, "permittivity_record": { "ExperimentalData": { "data": [ [ 298.15, 8.0 ] ] } }, "molarweight": 35.45 } ]"#; let binary_json = r#"[ { "id1": { "cas": "7732-18-5", "name": "water_np_sigma_t", "iupac_name": "oxidane", "smiles": "O", "inchi": "InChI=1/H2O/h1H2", "formula": "H2O" }, "id2": { "cas": "110-54-3", "name": "sodium ion", "formula": "na+" }, "k_ij": [ 0.0045, 0.0, 0.0, 0.0 ] }, { "id1": { "cas": "7732-18-5", "name": "water_np_sigma_t", "iupac_name": "oxidane", "smiles": "O", "inchi": "InChI=1/H2O/h1H2", "formula": "H2O" }, "id2": { "cas": "7782-50-5", "name": "chloride ion", "formula": "cl-" }, "k_ij": [ -0.25, 0.0, 0.0, 0.0 ] }, { "id1": { "cas": "110-54-3", "name": "sodium ion", "formula": "na+" }, "id2": { "cas": "7782-50-5", "name": "chloride ion", "formula": "cl-" }, "k_ij": [ 0.317, 0.0, 0.0, 0.0 ] } ]"#; let pure_records: Vec<Pure> = serde_json::from_str(pure_json).expect("Unable to parse json."); let binary_records: Vec<Binary> = serde_json::from_str(binary_json).expect("Unable to parse json."); ElectrolytePcSaftParameters::from_records( pure_records, binary_records, IdentifierOption::Name, ) .unwrap() } pub fn propane_butane_parameters() -> ElectrolytePcSaftParameters { let records_json = r#"[ { "identifier": { "cas": "74-98-6", "name": "propane", "iupac_name": "propane", "smiles": "CCC", "inchi": "InChI=1/C3H8/c1-3-2/h3H2,1-2H3", "formula": "C3H8" }, "m": 2.0018290000000003, "sigma": 3.618353, "epsilon_k": 208.1101, "molarweight": 44.0962 }, { "identifier": { "cas": "106-97-8", "name": "butane", "iupac_name": "butane", "smiles": "CCCC", "inchi": "InChI=1/C4H10/c1-3-4-2/h3-4H2,1-2H3", "formula": "C4H10" }, "m": 2.331586, "sigma": 3.7086010000000003, "epsilon_k": 222.8774, "molarweight": 58.123 } ]"#; let records: [Pure; 2] = serde_json::from_str(records_json).expect("Unable to parse json."); ElectrolytePcSaftParameters::new_binary(records, None, vec![]).unwrap() } }
Rust
3D
feos-org/feos
crates/feos/src/epcsaft/eos/mod.rs
.rs
10,110
309
use super::parameters::{ElectrolytePcSaftParameters, ElectrolytePcSaftPars}; use crate::association::Association; use crate::hard_sphere::{HardSphere, HardSphereProperties}; use feos_core::{FeosResult, ResidualDyn, Subset}; use feos_core::{Molarweight, StateHD}; use nalgebra::DVector; use num_dual::DualNum; use quantity::*; use std::f64::consts::FRAC_PI_6; pub(crate) mod born; pub(crate) mod dispersion; pub(crate) mod hard_chain; pub(crate) mod ionic; pub(crate) mod permittivity; use born::Born; use dispersion::Dispersion; use hard_chain::HardChain; use ionic::Ionic; /// Implemented variants of the ePC-SAFT equation of state. #[derive(Copy, Clone, PartialEq)] pub enum ElectrolytePcSaftVariants { Advanced, Revised, } /// Customization options for the ePC-SAFT equation of state. #[derive(Copy, Clone)] pub struct ElectrolytePcSaftOptions { pub max_eta: f64, pub max_iter_cross_assoc: usize, pub tol_cross_assoc: f64, pub epcsaft_variant: ElectrolytePcSaftVariants, } impl Default for ElectrolytePcSaftOptions { fn default() -> Self { Self { max_eta: 0.5, max_iter_cross_assoc: 50, tol_cross_assoc: 1e-10, epcsaft_variant: ElectrolytePcSaftVariants::Advanced, } } } /// electrolyte PC-SAFT (ePC-SAFT) equation of state. pub struct ElectrolytePcSaft { pub parameters: ElectrolytePcSaftParameters, pub params: ElectrolytePcSaftPars, pub options: ElectrolytePcSaftOptions, hard_chain: bool, association: Option<Association>, ionic: bool, born: bool, } impl ElectrolytePcSaft { pub fn new(parameters: ElectrolytePcSaftParameters) -> FeosResult<Self> { Self::with_options(parameters, ElectrolytePcSaftOptions::default()) } pub fn with_options( parameters: ElectrolytePcSaftParameters, options: ElectrolytePcSaftOptions, ) -> FeosResult<Self> { let params = ElectrolytePcSaftPars::new(&parameters)?; let hard_chain = params.m.iter().any(|m| (m - 1.0).abs() > 1e-15); let association = (!parameters.association.is_empty()) .then(|| Association::new(options.max_iter_cross_assoc, options.tol_cross_assoc)); let ionic = params.nionic > 0; let born = ionic && matches!(options.epcsaft_variant, ElectrolytePcSaftVariants::Advanced); Ok(Self { parameters, params, options, hard_chain, association, ionic, born, }) } } impl Subset for ElectrolytePcSaft { fn subset(&self, component_list: &[usize]) -> Self { Self::with_options(self.parameters.subset(component_list), self.options).unwrap() } } impl ResidualDyn for ElectrolytePcSaft { fn components(&self) -> usize { self.parameters.pure.len() } fn compute_max_density<D: DualNum<f64> + Copy>(&self, molefracs: &DVector<D>) -> D { let msigma3 = self .params .m .component_mul(&self.params.sigma.map(|v| v.powi(3))); (msigma3.map(D::from).dot(molefracs) * FRAC_PI_6).recip() * self.options.max_eta } fn reduced_helmholtz_energy_density_contributions<D: DualNum<f64> + Copy>( &self, state: &StateHD<D>, ) -> Vec<(&'static str, D)> { let mut v = Vec::with_capacity(7); let d = self.params.hs_diameter(state.temperature); v.push(( "Hard Sphere", HardSphere.helmholtz_energy_density(&self.params, state), )); if self.hard_chain { v.push(( "Hard Chain", HardChain.helmholtz_energy_density(&self.params, state), )) } v.push(( "Dispersion", Dispersion.helmholtz_energy_density(&self.params, state, &d), )); if let Some(association) = self.association.as_ref() { v.push(( "Association", association.helmholtz_energy_density( &self.params, &self.parameters.association, state, &d, ), )) } if self.ionic { v.push(( "Ionic", Ionic.helmholtz_energy_density( &self.params, state, &d, self.options.epcsaft_variant, ), )) }; if self.born { v.push(( "Born", Born.helmholtz_energy_density(&self.params, state, &d), )) }; v } } impl Molarweight for ElectrolytePcSaft { fn molar_weight(&self) -> MolarWeight<DVector<f64>> { self.parameters.molar_weight.clone() } } #[cfg(test)] mod tests { use super::*; use crate::epcsaft::parameters::utils::{ butane_parameters, propane_butane_parameters, propane_parameters, }; use approx::assert_relative_eq; use feos_core::*; use nalgebra::dvector; #[test] fn ideal_gas_pressure() { let e = ElectrolytePcSaft::new(propane_parameters()).unwrap(); let t = 200.0 * KELVIN; let v = 1e-3 * METER.powi::<3>(); let n = dvector![1.0] * MOL; let s = State::new_nvt(&&e, t, v, &n).unwrap(); let p_ig = s.total_moles * RGAS * t / v; assert_relative_eq!(s.pressure(Contributions::IdealGas), p_ig, epsilon = 1e-10); assert_relative_eq!( s.pressure(Contributions::IdealGas) + s.pressure(Contributions::Residual), s.pressure(Contributions::Total), epsilon = 1e-10 ); } #[test] fn ideal_gas_heat_capacity_joback() { let e = ElectrolytePcSaft::new(propane_parameters()).unwrap(); let t = 200.0 * KELVIN; let v = 1e-3 * METER.powi::<3>(); let n = dvector![1.0] * MOL; let s = State::new_nvt(&&e, t, v, &n).unwrap(); let p_ig = s.total_moles * RGAS * t / v; assert_relative_eq!(s.pressure(Contributions::IdealGas), p_ig, epsilon = 1e-10); assert_relative_eq!( s.pressure(Contributions::IdealGas) + s.pressure(Contributions::Residual), s.pressure(Contributions::Total), epsilon = 1e-10 ); } #[test] fn hard_sphere() { let p = ElectrolytePcSaftPars::new(&propane_parameters()).unwrap(); let t = 250.0; let v = 1000.0; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a_rust = HardSphere.helmholtz_energy_density(&p, &s) * v; assert_relative_eq!(a_rust, 0.410610492598808, epsilon = 1e-10); } #[test] fn hard_sphere_mix() { let p1 = ElectrolytePcSaftPars::new(&propane_parameters()).unwrap(); let p2 = ElectrolytePcSaftPars::new(&butane_parameters()).unwrap(); let p12 = ElectrolytePcSaftPars::new(&propane_butane_parameters()).unwrap(); let t = 250.0; let v = 2.5e28; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a1 = HardSphere.helmholtz_energy_density(&p1, &s); let a2 = HardSphere.helmholtz_energy_density(&p2, &s); let s1m = StateHD::new(t, v, &dvector![n, 0.0]); let a1m = HardSphere.helmholtz_energy_density(&p12, &s1m); let s2m = StateHD::new(t, v, &dvector![0.0, n]); let a2m = HardSphere.helmholtz_energy_density(&p12, &s2m); assert_relative_eq!(a1, a1m, epsilon = 1e-14); assert_relative_eq!(a2, a2m, epsilon = 1e-14); } #[test] fn new_tpn() { let e = ElectrolytePcSaft::new(propane_parameters()).unwrap(); let t = 300.0 * KELVIN; let p = BAR; let m = dvector![1.0] * MOL; let s = State::new_npt(&&e, t, p, &m, None); let p_calc = if let Ok(state) = s { state.pressure(Contributions::Total) } else { 0.0 * PASCAL }; assert_relative_eq!(p, p_calc, epsilon = 1e-6); } #[test] fn vle_pure() { let e = ElectrolytePcSaft::new(propane_parameters()).unwrap(); let t = 300.0 * KELVIN; let vle = PhaseEquilibrium::pure(&&e, t, None, Default::default()); if let Ok(v) = vle { assert_relative_eq!( v.vapor().pressure(Contributions::Total), v.liquid().pressure(Contributions::Total), epsilon = 1e-6 ) } } #[test] fn critical_point() { let e = ElectrolytePcSaft::new(propane_parameters()).unwrap(); let t = 300.0 * KELVIN; let cp = State::critical_point(&&e, None, Some(t), None, Default::default()); if let Ok(v) = cp { assert_relative_eq!(v.temperature, 375.1244078318015 * KELVIN, epsilon = 1e-8) } } #[test] fn mix_single() { let e1 = ElectrolytePcSaft::new(propane_parameters()).unwrap(); let e2 = ElectrolytePcSaft::new(butane_parameters()).unwrap(); let e12 = ElectrolytePcSaft::new(propane_butane_parameters()).unwrap(); let t = 300.0 * KELVIN; let v = 0.02456883872966545 * METER.powi::<3>(); let m1 = dvector![2.0] * MOL; let m1m = dvector![2.0, 0.0] * MOL; let m2m = dvector![0.0, 2.0] * MOL; let s1 = State::new_nvt(&&e1, t, v, &m1).unwrap(); let s2 = State::new_nvt(&&e2, t, v, &m1).unwrap(); let s1m = State::new_nvt(&&e12, t, v, &m1m).unwrap(); let s2m = State::new_nvt(&&e12, t, v, &m2m).unwrap(); assert_relative_eq!( s1.pressure(Contributions::Total), s1m.pressure(Contributions::Total), epsilon = 1e-12 ); assert_relative_eq!( s2.pressure(Contributions::Total), s2m.pressure(Contributions::Total), epsilon = 1e-12 ); assert_relative_eq!( s2.pressure(Contributions::Total), s2m.pressure(Contributions::Total), epsilon = 1e-12 ) } }
Rust
3D
feos-org/feos
crates/feos/src/epcsaft/eos/hard_chain.rs
.rs
2,382
68
use crate::epcsaft::parameters::ElectrolytePcSaftPars; use crate::hard_sphere::HardSphereProperties; use feos_core::StateHD; use nalgebra::DVector; use num_dual::*; pub struct HardChain; impl HardChain { #[inline] pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &ElectrolytePcSaftPars, state: &StateHD<D>, ) -> D { let p = parameters; let d = p.hs_diameter(state.temperature); let [zeta2, zeta3] = p.zeta(state.temperature, &state.partial_density, [2, 3]); let frac_1mz3 = -(zeta3 - 1.0).recip(); let c = zeta2 * frac_1mz3 * frac_1mz3; let g_hs = d.map(|d| frac_1mz3 + d * c * 1.5 - d.powi(2) * c.powi(2) * (zeta3 - 1.0) * 0.5); DVector::from_fn(p.m.len(), |i, _| { state.partial_density[i] * (1.0 - p.m[i]) * g_hs[i].ln() }) .sum() } } #[cfg(test)] mod tests { use super::*; use crate::epcsaft::parameters::utils::{ butane_parameters, propane_butane_parameters, propane_parameters, }; use approx::assert_relative_eq; use nalgebra::dvector; #[test] fn helmholtz_energy() { let p = ElectrolytePcSaftPars::new(&propane_parameters()).unwrap(); let t = 250.0; let v = 1000.0; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a_rust = HardChain.helmholtz_energy_density(&p, &s) * v; assert_relative_eq!(a_rust, -0.12402626171926148, epsilon = 1e-10); } #[test] fn mix() { let p1 = ElectrolytePcSaftPars::new(&propane_parameters()).unwrap(); let p2 = ElectrolytePcSaftPars::new(&butane_parameters()).unwrap(); let p12 = ElectrolytePcSaftPars::new(&propane_butane_parameters()).unwrap(); let t = 250.0; let v = 2.5e28; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a1 = HardChain.helmholtz_energy_density(&p1, &s); let a2 = HardChain.helmholtz_energy_density(&p2, &s); let s1m = StateHD::new(t, v, &dvector![n, 0.0]); let a1m = HardChain.helmholtz_energy_density(&p12, &s1m); let s2m = StateHD::new(t, v, &dvector![0.0, n]); let a2m = HardChain.helmholtz_energy_density(&p12, &s2m); assert_relative_eq!(a1, a1m, epsilon = 1e-14); assert_relative_eq!(a2, a2m, epsilon = 1e-14); } }
Rust
3D
feos-org/feos
crates/feos/src/epcsaft/eos/permittivity.rs
.rs
9,345
264
use feos_core::{FeosError, FeosResult, StateHD}; use nalgebra::DVector; use num_dual::DualNum; use serde::{Deserialize, Serialize}; use std::f64::consts::PI; use crate::epcsaft::eos::ElectrolytePcSaftVariants; use crate::epcsaft::parameters::ElectrolytePcSaftPars; #[derive(Serialize, Deserialize, Clone, Debug)] pub enum PermittivityRecord { ExperimentalData { data: Vec<(f64, f64)>, }, PerturbationTheory { dipole_scaling: f64, polarizability_scaling: f64, correlation_integral_parameter: f64, }, } #[derive(Clone)] pub struct Permittivity<D: DualNum<f64>> { pub permittivity: D, } impl<D: DualNum<f64> + Copy> Permittivity<D> { pub fn new( state: &StateHD<D>, parameters: &ElectrolytePcSaftPars, epcsaft_variant: &ElectrolytePcSaftVariants, ) -> FeosResult<Self> { // Set permittivity to an arbitrary value of 1 if system contains no ions // Ionic and Born contributions will be zero anyways if parameters.nionic == 0 { return Ok(Self { permittivity: D::one() * 1., }); } let all_comp: Vec<_> = (0..parameters.m.len()).collect(); if let ElectrolytePcSaftVariants::Advanced = epcsaft_variant { // check if permittivity is Some for all components if parameters .permittivity .iter() .any(|record| record.is_none()) { return Err(FeosError::IncompatibleParameters( "Provide permittivities for all components for ePC-SAFT advanced.".to_string(), )); } // Extract parameters from PermittivityRecords let mut mu_scaling: Vec<&f64> = vec![]; let mut alpha_scaling: Vec<&f64> = vec![]; let mut ci_param: Vec<&f64> = vec![]; let mut datas: Vec<Vec<(f64, f64)>> = vec![]; parameters .permittivity .iter() .for_each(|record| match record.as_ref().unwrap() { PermittivityRecord::PerturbationTheory { dipole_scaling, polarizability_scaling, correlation_integral_parameter, } => { mu_scaling.push(dipole_scaling); alpha_scaling.push(polarizability_scaling); ci_param.push(correlation_integral_parameter); } PermittivityRecord::ExperimentalData { data } => { datas.push(data.clone()); } }); if let PermittivityRecord::ExperimentalData { .. } = parameters.permittivity[0].as_ref().unwrap() { let permittivity = Self::from_experimental_data(&datas, state.temperature, &state.molefracs) .permittivity; return Ok(Self { permittivity }); } if let PermittivityRecord::PerturbationTheory { .. } = parameters.permittivity[0].as_ref().unwrap() { let permittivity = Self::from_perturbation_theory( state, &mu_scaling, &alpha_scaling, &ci_param, &all_comp, ) .permittivity; return Ok(Self { permittivity }); } } if let ElectrolytePcSaftVariants::Revised = epcsaft_variant { if parameters.nsolvent > 1 { return Err(FeosError::IncompatibleParameters( "ePC-SAFT revised cannot be used for more than 1 solvent.".to_string(), )); }; let permittivity = match parameters.permittivity[parameters.solvent_comp[0]] .as_ref() .unwrap() { PermittivityRecord::ExperimentalData { data } => { Self::pure_from_experimental_data(data, state.temperature).permittivity } PermittivityRecord::PerturbationTheory { dipole_scaling, polarizability_scaling, correlation_integral_parameter, } => { Self::pure_from_perturbation_theory( state, *dipole_scaling, *polarizability_scaling, *correlation_integral_parameter, ) .permittivity } }; return Ok(Self { permittivity }); }; Err(FeosError::IncompatibleParameters( "Permittivity computation failed".to_string(), )) } pub fn pure_from_experimental_data(data: &[(f64, f64)], temperature: D) -> Self { let permittivity_pure = Self::interpolate(data, temperature).permittivity; Self { permittivity: permittivity_pure, } } pub fn pure_from_perturbation_theory( state: &StateHD<D>, dipole_scaling: f64, polarizability_scaling: f64, correlation_integral_parameter: f64, ) -> Self { // reciprocal thermodynamic temperature let boltzmann = 1.380649e-23; let beta = (state.temperature * boltzmann).recip(); // Density let density = state.partial_density.sum(); // dipole density y -> scaled dipole density y_star let y_star = density * (beta * dipole_scaling * 1e-19 + polarizability_scaling * 3.) * 4. / 9. * PI; // correlation integral let correlation_integral = ((-y_star).exp() - 1.0) * correlation_integral_parameter + 1.0; // dielectric constan let permittivity_pure = y_star * 3.0 * (y_star.powi(2) * (correlation_integral * (17. / 16.) - 1.0) + y_star + 1.0) + 1.0; Self { permittivity: permittivity_pure, } } pub fn from_experimental_data( data: &[Vec<(f64, f64)>], temperature: D, molefracs: &DVector<D>, ) -> Self { let permittivity = data .iter() .enumerate() .map(|(i, d)| Self::interpolate(d, temperature).permittivity * molefracs[i]) .sum(); Self { permittivity } } pub fn from_perturbation_theory( state: &StateHD<D>, dipole_scaling: &[&f64], polarizability_scaling: &[&f64], correlation_integral_parameter: &[&f64], comp: &[usize], ) -> Self { //let nsolvent = comp.len(); // reciprocal thermodynamic temperature let boltzmann = 1.380649e-23; let beta = (state.temperature * boltzmann).recip(); // Determine scaled dipole density and correlation integral parameter of the mixture let mut y_star = D::zero(); let mut correlation_integral_parameter_mixture = D::zero(); for i in comp.iter() { let rho_i = state.partial_density[*i]; let x_i = state.molefracs[*i]; y_star += rho_i * (beta * *dipole_scaling[*i] * 1e-19 + polarizability_scaling[*i] * 3.) * 4. / 9. * PI; correlation_integral_parameter_mixture += x_i * *correlation_integral_parameter[*i]; } // correlation integral let correlation_integral = ((-y_star).exp() - 1.0) * correlation_integral_parameter_mixture + 1.0; // permittivity let permittivity = y_star * 3.0 * (y_star.powi(2) * (correlation_integral * (17. / 16.) - 1.0) + y_star + 1.0) + 1.0; Self { permittivity } } /// Structure: &[(temperature, epsilon)] /// Assume ordered by temperature /// and temperatures are all finite. pub fn interpolate(interpolation_points: &[(f64, f64)], temperature: D) -> Self { // if there is only one point, return it (means constant permittivity) if interpolation_points.len() == 1 { return Self { permittivity: D::one() * interpolation_points[0].1, }; } // find index where temperature could be inserted let i = interpolation_points.binary_search_by(|&(ti, _)| { ti.partial_cmp(&temperature.re()) .expect("Unexpected value for temperature in interpolation points.") }); // unwrap let i = i.unwrap_or_else(|i| i); let n = interpolation_points.len(); // check cases: // 0. : below lowest temperature // >= n : above highest temperature // else : regular interpolation let (l, u) = match i { 0 => (interpolation_points[0], interpolation_points[1]), i if i >= n => (interpolation_points[n - 2], interpolation_points[n - 1]), _ => (interpolation_points[i - 1], interpolation_points[i]), }; let permittivity_pure = (temperature - l.0) / (u.0 - l.0) * (u.1 - l.1) + l.1; Self { permittivity: permittivity_pure, } } }
Rust
3D
feos-org/feos
crates/feos/src/epcsaft/eos/ionic.rs
.rs
3,671
121
use crate::epcsaft::eos::permittivity::Permittivity; use crate::epcsaft::parameters::ElectrolytePcSaftPars; use feos_core::StateHD; use nalgebra::DVector; use num_dual::DualNum; use std::f64::consts::PI; use super::ElectrolytePcSaftVariants; const EPSILON_0: f64 = 8.85416e-12; const QE: f64 = 1.602176634e-19f64; const BOLTZMANN: f64 = 1.380649e-23; impl ElectrolytePcSaftPars { pub fn bjerrum_length<D: DualNum<f64> + Copy>( &self, state: &StateHD<D>, epcsaft_variant: ElectrolytePcSaftVariants, ) -> D { // relative permittivity of water (usually function of T,p,x) let epsilon_r = Permittivity::new(state, self, &epcsaft_variant) .unwrap() .permittivity; let epsreps0 = epsilon_r * EPSILON_0; let qe2 = QE.powi(2); // Bjerrum length (state.temperature * 4.0 * std::f64::consts::PI * epsreps0 * BOLTZMANN).recip() * qe2 * 1.0e10 } } pub struct Ionic; impl Ionic { pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &ElectrolytePcSaftPars, state: &StateHD<D>, diameter: &DVector<D>, variant: ElectrolytePcSaftVariants, ) -> D { // Extract parameters let p = parameters; // Set to zero if one of the ions is 0 let sum_mole_fraction: f64 = p.ionic_comp.iter().map(|&i| state.molefracs[i].re()).sum(); if sum_mole_fraction == 0. { return D::zero(); } // Calculate Bjerrum length let lambda_b = p.bjerrum_length(state, variant); // Calculate inverse Debye length let mut sum_dens_z = D::zero(); for i in 0..state.molefracs.len() { //let ai = p.ionic_comp[i]; sum_dens_z += state.partial_density[i] * p.z[i].powi(2); } let kappa = (lambda_b * sum_dens_z * 4.0 * PI).sqrt(); let chi: Vec<D> = diameter .iter() .map(|&d| { (kappa * d).powi(3).recip() * ((kappa * d + 1.0).ln() - (kappa * d + 1.0) * 2.0 + (kappa * d + 1.0).powi(2) * 0.5 + 1.5) }) .collect(); let mut sum_rho_z_chi = D::zero(); for (i, chi) in chi.into_iter().enumerate() { sum_rho_z_chi += chi * state.partial_density[i] * p.z[i].powi(2); } -kappa * lambda_b * sum_rho_z_chi } } #[cfg(test)] mod tests { use super::ElectrolytePcSaftVariants::Advanced; use super::*; use crate::epcsaft::parameters::utils::{water_nacl_parameters, water_nacl_parameters_perturb}; use crate::hard_sphere::HardSphereProperties; use approx::assert_relative_eq; use nalgebra::dvector; #[test] fn helmholtz_energy_perturb() { let p = ElectrolytePcSaftPars::new(&water_nacl_parameters_perturb()).unwrap(); let t = 298.0; let v = 31.875; let s = StateHD::new(t, v, &dvector![0.9, 0.05, 0.05]); let d = p.hs_diameter(t); let a_rust = Ionic.helmholtz_energy_density(&p, &s, &d, Advanced) * v; assert_relative_eq!(a_rust, -0.07775796084032328, epsilon = 1e-10); } #[test] fn helmholtz_energy() { let p = ElectrolytePcSaftPars::new(&water_nacl_parameters()).unwrap(); let t = 298.0; let v = 31.875; let s = StateHD::new(t, v, &dvector![0.9, 0.05, 0.05]); let d = p.hs_diameter(t); let a_rust = Ionic.helmholtz_energy_density(&p, &s, &d, Advanced) * v; assert_relative_eq!(a_rust, -0.07341337106244776, epsilon = 1e-10); } }
Rust
3D
feos-org/feos
crates/feos/src/epcsaft/eos/dispersion.rs
.rs
6,133
199
use crate::epcsaft::parameters::ElectrolytePcSaftPars; 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.30840169182720, 0.18605311591713, -2.50300472586548, 21.4197936296668, -65.2558853303492, 83.3186804808856, -33.7469229297323, ]; pub const A2: [f64; 7] = [ -0.09061483509767, 0.45278428063920, 0.59627007280101, -1.72418291311787, -4.13021125311661, 13.7766318697211, -8.67284703679646, ]; 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.57554980753450, 0.69950955214436, 3.89256733895307, -17.21547164777212, 192.6722644652495, -161.8264616487648, -165.2076934555607, ]; pub const B2: [f64; 7] = [ 0.09768831158356, -0.25575749816100, -9.15585615297321, 20.64207597439724, -38.80443005206285, 93.6267740770146, -29.66690558514725, ]; pub const T_REF: f64 = 298.15; impl ElectrolytePcSaftPars { pub fn k_ij_t<D: DualNum<f64>>(&self, temperature: D) -> DMatrix<f64> { let k_ij = &self.k_ij; let n = self.m.len(); let mut k_ij_t = DMatrix::zeros(n, n); for i in 0..n { for j in 0..n { // Calculate k_ij(T) k_ij_t[(i, j)] = (temperature.re() - T_REF) * k_ij[(i, j)][1] + (temperature.re() - T_REF).powi(2) * k_ij[(i, j)][2] + (temperature.re() - T_REF).powi(3) * k_ij[(i, j)][3] + k_ij[(i, j)][0]; } } //println!("k_ij_t: {}", k_ij_t); k_ij_t } pub fn epsilon_k_ij_t<D: DualNum<f64>>(&self, temperature: D) -> DMatrix<f64> { let k_ij_t = self.k_ij_t(temperature); let n = self.m.len(); let mut epsilon_k_ij_t = DMatrix::zeros(n, n); for i in 0..n { for j in 0..n { epsilon_k_ij_t[(i, j)] = (1.0 - k_ij_t[(i, j)]) * self.e_k_ij[(i, j)]; } } epsilon_k_ij_t } } pub struct Dispersion; impl Dispersion { pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &ElectrolytePcSaftPars, state: &StateHD<D>, diameter: &DVector<D>, ) -> D { // auxiliary variables let n = parameters.m.len(); let p = parameters; let rho = &state.partial_density; // convert sigma_ij let sigma_ij_t = p.sigma_ij_t(state.temperature); // convert epsilon_k_ij let epsilon_k_ij_t = p.epsilon_k_ij_t(state.temperature); // packing fraction let eta = rho.dot(&diameter.zip_map(&p.m, |d, m| d.powi(3) * m)) * FRAC_PI_6; // mean segment number let m = state.molefracs.dot(&p.m.map(D::from)); // 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() * epsilon_k_ij_t[(i, j)]; let sigma_ij = sigma_ij_t[(i, j)].powi(3); rho1mix += rho[i] * rho[j] * p.m[i] * p.m[j] * eps_ij * sigma_ij; rho2mix += rho[i] * rho[j] * p.m[i] * p.m[j] * eps_ij * eps_ij * sigma_ij; } } // I1, I2 and C1 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 * A2[i] + A1[i]) + A0[i]) * eta_i; i2 += ((m - 1.0) / m * ((m - 2.0) / m * B2[i] + B1[i]) + B0[i]) * eta_i; eta_i *= eta; } let c1 = (m * (eta * 8.0 - eta.powi(2) * 2.0) / (eta - 1.0).powi(4) + (D::one() - m) * (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(); // Helmholtz energy (-rho1mix * i1 * 2.0 - rho2mix * m * c1 * i2) * PI } } #[cfg(test)] mod tests { use super::*; use crate::epcsaft::parameters::utils::{ butane_parameters, propane_butane_parameters, propane_parameters, }; use crate::hard_sphere::HardSphereProperties; use approx::assert_relative_eq; use nalgebra::dvector; #[test] fn helmholtz_energy() { let p = ElectrolytePcSaftPars::new(&propane_parameters()).unwrap(); let t = 250.0; let v = 1000.0; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let d = p.hs_diameter(t); let a_rust = Dispersion.helmholtz_energy_density(&p, &s, &d) * v; assert_relative_eq!(a_rust, -1.0622531100351962, epsilon = 1e-10); } #[test] fn mix() { let p1 = ElectrolytePcSaftPars::new(&propane_parameters()).unwrap(); let p2 = ElectrolytePcSaftPars::new(&butane_parameters()).unwrap(); let p12 = ElectrolytePcSaftPars::new(&propane_butane_parameters()).unwrap(); let t = 250.0; let v = 2.5e28; let n = 1.0; let s = StateHD::new(t, v, &dvector![n]); let a1 = Dispersion.helmholtz_energy_density(&p1, &s, &p1.hs_diameter(t)); let a2 = Dispersion.helmholtz_energy_density(&p2, &s, &p2.hs_diameter(t)); let s1m = StateHD::new(t, v, &dvector![n, 0.0]); let a1m = Dispersion.helmholtz_energy_density(&p12, &s1m, &p12.hs_diameter(t)); let s2m = StateHD::new(t, v, &dvector![0.0, n]); let a2m = Dispersion.helmholtz_energy_density(&p12, &s2m, &p12.hs_diameter(t)); assert_relative_eq!(a1, a1m, epsilon = 1e-14); assert_relative_eq!(a2, a2m, epsilon = 1e-14); } }
Rust
3D
feos-org/feos
crates/feos/src/epcsaft/eos/born.rs
.rs
2,227
73
use super::ElectrolytePcSaftVariants; use crate::epcsaft::eos::permittivity::Permittivity; use crate::epcsaft::parameters::ElectrolytePcSaftPars; use feos_core::StateHD; use nalgebra::DVector; use num_dual::DualNum; pub struct Born; impl Born { pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &ElectrolytePcSaftPars, state: &StateHD<D>, diameter: &DVector<D>, ) -> D { // Parameters let p = parameters; // Calculate Bjerrum length let lambda_b = p.bjerrum_length(state, ElectrolytePcSaftVariants::Advanced); // Calculate relative permittivity let epsilon_r = Permittivity::new(state, p, &ElectrolytePcSaftVariants::Advanced) .unwrap() .permittivity; // Calculate sum rhoi zi^2 / di let mut sum_rhoi_zi_ai = D::zero(); for i in 0..state.molefracs.len() { sum_rhoi_zi_ai += state.partial_density[i] * p.z[i].powi(2) / diameter[i]; } // Calculate born contribution -lambda_b * (epsilon_r - 1.) * sum_rhoi_zi_ai } } #[cfg(test)] mod tests { use super::*; use crate::epcsaft::parameters::utils::{water_nacl_parameters, water_nacl_parameters_perturb}; use crate::hard_sphere::HardSphereProperties; use approx::assert_relative_eq; use nalgebra::dvector; #[test] fn helmholtz_energy_perturb() { let p = ElectrolytePcSaftPars::new(&water_nacl_parameters_perturb()).unwrap(); let t = 298.0; let v = 31.875; let s = StateHD::new(t, v, &dvector![0.9, 0.05, 0.05]); let d = p.hs_diameter(t); let a_rust = Born.helmholtz_energy_density(&p, &s, &d) * v; assert_relative_eq!(a_rust, -22.51064553710294, epsilon = 1e-10); } #[test] fn helmholtz_energy() { let p = ElectrolytePcSaftPars::new(&water_nacl_parameters()).unwrap(); let t = 298.0; let v = 31.875; let s = StateHD::new(t, v, &dvector![0.9, 0.05, 0.05]); let d = p.hs_diameter(t); let a_rust = Born.helmholtz_energy_density(&p, &s, &d) * v; assert_relative_eq!(a_rust, -22.525624511559244, epsilon = 1e-10); } }
Rust
3D
feos-org/feos
crates/feos/src/uvtheory/mod.rs
.rs
2,368
64
//! uv-theory for fluids interacting with a Mie potential. //! //! # Implementations //! //! ## uv-theory //! //! [van Westen et al. (2021)](https://doi.org/10.1063/5.0073572): utilizing second virial coeffients and Barker-Henderson or Weeks-Chandler-Andersen perturbation. //! #![cfg_attr(not(feature = "uvtheory"), doc = "```ignore")] #![cfg_attr(feature = "uvtheory", doc = "```")] //! # use feos_core::FeosError; //! use feos::uvtheory::{Perturbation, UVTheory, UVTheoryOptions, UVTheoryParameters, UVTheoryRecord}; //! //! let params = UVTheoryRecord::new(24.0, 7.0, 3.0, 150.0); //! //! let default_options = UVTheoryOptions { //! max_eta: 0.5, //! perturbation: Perturbation::WeeksChandlerAndersen, //! }; //! // Define equation of state. //! let uv_wca = &UVTheory::new(UVTheoryParameters::from_model_records(vec![params])?); //! // this is identical to above //! let uv_wca = &UVTheory::with_options(UVTheoryParameters::from_model_records(vec![params])?, default_options); //! //! // use Barker-Henderson perturbation //! let options = UVTheoryOptions { //! max_eta: 0.5, //! perturbation: Perturbation::BarkerHenderson, //! }; //! let uv_bh = UVTheory::with_options(UVTheoryParameters::from_model_records(vec![params])?, options); //! # Ok::<(), FeosError>(()) //! ``` //! //! ## uv-B3-theory //! //! - utilizing third virial coefficients for pure fluids with attractive exponent of 6 and Weeks-Chandler-Andersen perturbation. Manuscript submitted. //! #![cfg_attr(not(feature = "uvtheory"), doc = "```ignore")] #![cfg_attr(feature = "uvtheory", doc = "```")] //! # use feos_core::FeosError; //! use feos::uvtheory::{Perturbation, UVTheory, UVTheoryOptions, UVTheoryParameters, UVTheoryRecord}; //! //! let params = UVTheoryRecord::new(24.0, 6.0, 3.0, 150.0); //! //! let parameters = UVTheoryParameters::from_model_records(vec![params])?; //! //! // use uv-B3-theory //! let options = UVTheoryOptions { //! max_eta: 0.5, //! perturbation: Perturbation::WeeksChandlerAndersenB3, //! }; //! // Define equation of state. //! let uv_b3 = UVTheory::with_options(parameters, options); //! # Ok::<(), FeosError>(()) //! ``` mod eos; mod parameters; pub use eos::{ BarkerHenderson, Perturbation, UVTheory, UVTheoryOptions, WeeksChandlerAndersen, WeeksChandlerAndersenB3, }; pub use parameters::{UVTheoryParameters, UVTheoryRecord};
Rust
3D
feos-org/feos
crates/feos/src/uvtheory/parameters.rs
.rs
6,937
194
use super::{BarkerHenderson, Perturbation, WeeksChandlerAndersen}; use crate::hard_sphere::{HardSphereProperties, MonomerShape}; use feos_core::parameter::Parameters; use nalgebra::{DMatrix, DVector, SMatrix, matrix, stack, vector}; use num_dual::DualNum; use serde::{Deserialize, Serialize}; /// uv-theory parameters for a pure substance #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub struct UVTheoryRecord { rep: f64, att: f64, sigma: f64, epsilon_k: f64, } impl UVTheoryRecord { /// Single substance record for uv-theory pub fn new(rep: f64, att: f64, sigma: f64, epsilon_k: f64) -> Self { Self { rep, att, sigma, epsilon_k, } } } /// Constants for BH temperature dependent HS diameter. const CD_BH: SMatrix<f64, 4, 3> = matrix![ 0.0, 1.09360455168912E-02, 0.0; -2.00897880971934E-01, -1.27074910870683E-02, 0.0; 1.40422470174053E-02, 7.35946850956932E-02, 1.28463973950737E-02; 3.71527116894441E-03, 5.05384813757953E-03, 4.91003312452622E-02]; #[inline] pub fn mie_prefactor<D: DualNum<f64> + Copy>(rep: D, att: D) -> D { rep / (rep - att) * (rep / att).powd(att / (rep - att)) } #[inline] pub fn mean_field_constant<D: DualNum<f64> + Copy>(rep: D, att: D, x: D) -> D { mie_prefactor(rep, att) * (x.powd(-att + 3.0) / (att - 3.0) - x.powd(-rep + 3.0) / (rep - 3.0)) } /// Parameters for all substances for uv-theory equation of state and Helmholtz energy functional pub type UVTheoryParameters = Parameters<UVTheoryRecord, f64, ()>; /// Parameters for all substances for uv-theory equation of state and Helmholtz energy functional #[derive(Debug, Clone)] pub struct UVTheoryPars { pub perturbation: Perturbation, pub rep: DVector<f64>, pub att: DVector<f64>, pub sigma: DVector<f64>, pub epsilon_k: DVector<f64>, pub rep_ij: DMatrix<f64>, pub att_ij: DMatrix<f64>, pub sigma_ij: DMatrix<f64>, pub eps_k_ij: DMatrix<f64>, pub cd_bh_pure: Vec<[f64; 5]>, pub cd_bh_binary: DMatrix<[f64; 5]>, } impl UVTheoryPars { pub fn new(parameters: &UVTheoryParameters, perturbation: Perturbation) -> Self { let n = parameters.pure.len(); let [rep, att, sigma, epsilon_k] = parameters.collate(|pr| [pr.rep, pr.att, pr.sigma, pr.epsilon_k]); let mut rep_ij = DMatrix::zeros(n, n); let mut att_ij = DMatrix::zeros(n, n); let mut sigma_ij = DMatrix::zeros(n, n); let mut eps_k_ij = DMatrix::zeros(n, n); let [k_ij] = parameters.collate_binary(|&br| [br]); for i in 0..n { rep_ij[(i, i)] = rep[i]; att_ij[(i, i)] = att[i]; sigma_ij[(i, i)] = sigma[i]; eps_k_ij[(i, i)] = epsilon_k[i]; for j in i + 1..n { rep_ij[(i, j)] = (rep[i] * rep[j]).sqrt(); rep_ij[(j, i)] = rep_ij[(i, j)]; att_ij[(i, j)] = (att[i] * att[j]).sqrt(); att_ij[(j, i)] = att_ij[(i, j)]; sigma_ij[(i, j)] = 0.5 * (sigma[i] + sigma[j]); sigma_ij[(j, i)] = sigma_ij[(i, j)]; eps_k_ij[(i, j)] = (1.0 - k_ij[(i, j)]) * (epsilon_k[i] * epsilon_k[j]).sqrt(); eps_k_ij[(j, i)] = eps_k_ij[(i, j)]; } } // BH temperature dependent HS diameter, eq. 21 let cd_bh_pure: Vec<_> = rep.iter().map(|&mi| bh_coefficients(mi, 6.0)).collect(); let cd_bh_binary = DMatrix::from_fn(n, n, |i, j| bh_coefficients(rep_ij[(i, j)], 6.0)); Self { perturbation, rep, att, sigma, epsilon_k, rep_ij, att_ij, sigma_ij, eps_k_ij, cd_bh_pure, cd_bh_binary, } } } #[expect(clippy::toplevel_ref_arg)] fn bh_coefficients(rep: f64, att: f64) -> [f64; 5] { let inv_a76 = 1.0 / mean_field_constant(7.0, att, 1.0); let am6 = mean_field_constant(rep, att, 1.0); let alpha = 1.0 / am6 - inv_a76; let c0 = vector![-2.0 * rep / ((att - rep) * mie_prefactor(rep, att))]; let x = stack![c0; CD_BH * vector![1.0, alpha, alpha * alpha]]; x.data.0[0] } impl HardSphereProperties for UVTheoryPars { fn monomer_shape<D: DualNum<f64> + Copy>(&self, _: D) -> MonomerShape<'_, D> { MonomerShape::Spherical(self.sigma.len()) } fn hs_diameter<D: DualNum<f64> + Copy>(&self, temperature: D) -> DVector<D> { match self.perturbation { Perturbation::BarkerHenderson => BarkerHenderson::diameter_bh(self, temperature), Perturbation::WeeksChandlerAndersen => { WeeksChandlerAndersen::diameter_wca(self, temperature) } Perturbation::WeeksChandlerAndersenB3 => { WeeksChandlerAndersen::diameter_wca(self, temperature) } } } } #[cfg(test)] pub mod utils { use super::*; use feos_core::parameter::{Identifier, PureRecord}; use std::f64; pub fn new_simple(rep: f64, att: f64, sigma: f64, epsilon_k: f64) -> UVTheoryParameters { UVTheoryParameters::new_pure(PureRecord::new( Default::default(), 0.0, UVTheoryRecord::new(rep, att, sigma, epsilon_k), )) .unwrap() } pub fn test_parameters( rep: f64, att: f64, sigma: f64, epsilon: f64, p: Perturbation, ) -> UVTheoryPars { let identifier = Identifier::new(Some("1"), None, None, None, None, None); let model_record = UVTheoryRecord::new(rep, att, sigma, epsilon); let pr = PureRecord::new(identifier, 1.0, model_record); UVTheoryPars::new(&UVTheoryParameters::new_pure(pr).unwrap(), p) } pub fn test_parameters_mixture( rep: DVector<f64>, att: DVector<f64>, sigma: DVector<f64>, epsilon: DVector<f64>, ) -> UVTheoryParameters { let identifier = Identifier::new(Some("1"), None, None, None, None, None); let model_record = UVTheoryRecord::new(rep[0], att[0], sigma[0], epsilon[0]); let pr1 = PureRecord::new(identifier, 1.0, model_record); // let identifier2 = Identifier::new(Some("1"), None, None, None, None, None); let model_record2 = UVTheoryRecord::new(rep[1], att[1], sigma[1], epsilon[1]); let pr2 = PureRecord::new(identifier2, 1.0, model_record2); UVTheoryParameters::new_binary([pr1, pr2], None, vec![]).unwrap() } pub fn methane_parameters(rep: f64, att: f64) -> UVTheoryParameters { let identifier = Identifier::new(Some("1"), None, None, None, None, None); let model_record = UVTheoryRecord::new(rep, att, 3.7039, 150.03); let pr = PureRecord::new(identifier, 1.0, model_record); UVTheoryParameters::new_pure(pr).unwrap() } }
Rust
3D
feos-org/feos
crates/feos/src/uvtheory/eos/mod.rs
.rs
9,910
283
use super::parameters::{UVTheoryParameters, UVTheoryPars}; use feos_core::{Molarweight, ResidualDyn, Subset}; use nalgebra::DVector; use num_dual::DualNum; use quantity::MolarWeight; use std::f64::consts::FRAC_PI_6; mod bh; pub use bh::BarkerHenderson; mod wca; pub use wca::{WeeksChandlerAndersen, WeeksChandlerAndersenB3}; /// Type of perturbation. #[derive(Clone, Copy, PartialEq, Debug)] pub enum Perturbation { BarkerHenderson, WeeksChandlerAndersen, WeeksChandlerAndersenB3, } /// Configuration options for uv-theory #[derive(Clone)] pub struct UVTheoryOptions { pub max_eta: f64, pub perturbation: Perturbation, } impl Default for UVTheoryOptions { fn default() -> Self { Self { max_eta: 0.5, perturbation: Perturbation::WeeksChandlerAndersen, } } } /// uv-theory equation of state pub struct UVTheory { pub parameters: UVTheoryParameters, params: UVTheoryPars, options: UVTheoryOptions, } impl UVTheory { /// uv-theory with default options (WCA). pub fn new(parameters: UVTheoryParameters) -> Self { Self::with_options(parameters, UVTheoryOptions::default()) } /// uv-theory with provided options. pub fn with_options(parameters: UVTheoryParameters, options: UVTheoryOptions) -> Self { let params = UVTheoryPars::new(&parameters, options.perturbation); Self { parameters, params, options, } } } impl Subset for UVTheory { fn subset(&self, component_list: &[usize]) -> Self { Self::with_options(self.parameters.subset(component_list), self.options.clone()) } } impl ResidualDyn for UVTheory { fn components(&self) -> usize { self.parameters.pure.len() } fn compute_max_density<D: DualNum<f64> + Copy>(&self, molefracs: &DVector<D>) -> D { let sigma3 = self.params.sigma.map(|v| v.powi(3)); (sigma3.map(D::from).dot(molefracs) * FRAC_PI_6).recip() * self.options.max_eta } fn reduced_helmholtz_energy_density_contributions<D: DualNum<f64> + Copy>( &self, state: &feos_core::StateHD<D>, ) -> Vec<(&'static str, D)> { match &self.options.perturbation { Perturbation::BarkerHenderson => { BarkerHenderson.residual_helmholtz_energy_contributions(&self.params, state) } Perturbation::WeeksChandlerAndersen => { WeeksChandlerAndersen.residual_helmholtz_energy_contributions(&self.params, state) } Perturbation::WeeksChandlerAndersenB3 => { WeeksChandlerAndersenB3.residual_helmholtz_energy_contributions(&self.params, state) } } } } impl Molarweight for UVTheory { fn molar_weight(&self) -> MolarWeight<DVector<f64>> { self.parameters.molar_weight.clone() } } #[cfg(test)] #[expect(clippy::excessive_precision)] mod test { use super::*; use crate::uvtheory::parameters::utils::{new_simple, test_parameters_mixture}; use crate::uvtheory::parameters::*; use approx::assert_relative_eq; use feos_core::parameter::{Identifier, PureRecord}; use feos_core::{FeosResult, State}; use nalgebra::dvector; use quantity::{ANGSTROM, KELVIN, MOL, NAV, RGAS}; #[test] fn helmholtz_energy_pure_wca() -> FeosResult<()> { let sig = 3.7039; let eps_k = 150.03; let parameters = new_simple(24.0, 6.0, sig, eps_k); let eos = &UVTheory::new(parameters); let reduced_temperature = 4.0; let reduced_density = 1.0; let temperature = reduced_temperature * eps_k * KELVIN; let moles = dvector![2.0] * MOL; let volume = (sig * ANGSTROM).powi::<3>() / reduced_density * NAV * 2.0 * MOL; let s = State::new_nvt(&eos, temperature, volume, &moles).unwrap(); let a = (s.residual_molar_helmholtz_energy() / (RGAS * temperature)).into_value(); assert_relative_eq!(a, 2.972986567516, max_relative = 1e-12); //wca Ok(()) } #[test] fn helmholtz_energy_pure_bh() -> FeosResult<()> { let eps_k = 150.03; let sig = 3.7039; let rep = 24.0; let att = 6.0; let parameters = new_simple(rep, att, sig, eps_k); let options = UVTheoryOptions { max_eta: 0.5, perturbation: Perturbation::BarkerHenderson, }; let eos = &UVTheory::with_options(parameters, options); let reduced_temperature = 4.0; let reduced_density = 1.0; let temperature = reduced_temperature * eps_k * KELVIN; let moles = dvector![2.0] * MOL; let volume = (sig * ANGSTROM).powi::<3>() / reduced_density * NAV * 2.0 * MOL; let s = State::new_nvt(&eos, temperature, volume, &moles).unwrap(); let a = (s.residual_molar_helmholtz_energy() / (RGAS * temperature)).into_value(); assert_relative_eq!(a, 2.993577305779432, max_relative = 1e-12); Ok(()) } #[test] fn helmholtz_energy_pure_uvb3() -> FeosResult<()> { let eps_k = 150.03; let sig = 3.7039; let rep = 12.0; let att = 6.0; let parameters = new_simple(rep, att, sig, eps_k); let options = UVTheoryOptions { max_eta: 0.5, perturbation: Perturbation::WeeksChandlerAndersenB3, }; let eos = &UVTheory::with_options(parameters, options); let reduced_temperature = 4.0; let reduced_density = 0.5; let temperature = reduced_temperature * eps_k * KELVIN; let moles = dvector![2.0] * MOL; let volume = (sig * ANGSTROM).powi::<3>() / reduced_density * NAV * 2.0 * MOL; let s = State::new_nvt(&eos, temperature, volume, &moles).unwrap(); let a = (s.residual_molar_helmholtz_energy() / (RGAS * temperature)).into_value(); dbg!(a); assert_relative_eq!(a, 0.37659379124271003, max_relative = 1e-12); Ok(()) } #[test] fn helmholtz_energy_mixtures_bh() -> FeosResult<()> { // Mixture of equal components --> result must be the same as for pure fluid /// // component 1 let rep1 = 24.0; let eps_k1 = 150.03; let sig1 = 3.7039; let r1 = UVTheoryRecord::new(rep1, 6.0, sig1, eps_k1); let i = Identifier::new(None, None, None, None, None, None); // compontent 2 let rep2 = 24.0; let eps_k2 = 150.03; let sig2 = 3.7039; let r2 = UVTheoryRecord::new(rep2, 6.0, sig2, eps_k2); let j = Identifier::new(None, None, None, None, None, None); ////////////// let pr1 = PureRecord::new(i, 1.0, r1); let pr2 = PureRecord::new(j, 1.0, r2); let uv_parameters = UVTheoryParameters::new_binary([pr1, pr2], None, vec![])?; // state let reduced_temperature = 4.0; let eps_k_x = (eps_k1 + eps_k2) / 2.0; // Check rule!! let t_x = reduced_temperature * eps_k_x * KELVIN; let sig_x = (sig1 + sig2) / 2.0; // Check rule!! let reduced_density = 1.0; let moles = dvector![1.7, 0.3] * MOL; let total_moles = moles.sum(); let volume = (sig_x * ANGSTROM).powi::<3>() / reduced_density * NAV * total_moles; // EoS let options = UVTheoryOptions { max_eta: 0.5, perturbation: Perturbation::BarkerHenderson, }; let eos_bh = &UVTheory::with_options(uv_parameters, options); let state_bh = State::new_nvt(&eos_bh, t_x, volume, &moles).unwrap(); let a_bh = (state_bh.residual_molar_helmholtz_energy() / (RGAS * t_x)).into_value(); assert_relative_eq!(a_bh, 2.993577305779432, max_relative = 1e-12); Ok(()) } #[test] fn helmholtz_energy_wca_mixture() -> FeosResult<()> { let parameters = test_parameters_mixture( dvector![12.0, 12.0], dvector![6.0, 6.0], dvector![1.0, 1.0], dvector![1.0, 0.5], ); let p = UVTheoryPars::new(&parameters, Perturbation::WeeksChandlerAndersen); // state let reduced_temperature = 1.0; let t_x = reduced_temperature * p.epsilon_k[0] * KELVIN; let reduced_density = 0.9; let moles = dvector![0.4, 0.6] * MOL; let total_moles = moles.sum(); let volume = (p.sigma[0] * ANGSTROM).powi::<3>() / reduced_density * NAV * total_moles; // EoS let eos_wca = &UVTheory::new(parameters); let state_wca = State::new_nvt(&eos_wca, t_x, volume, &moles).unwrap(); let a_wca = (state_wca.residual_helmholtz_energy() / (RGAS * t_x * state_wca.total_moles)) .into_value(); assert_relative_eq!(a_wca, -0.597791038364405, max_relative = 1e-5); Ok(()) } #[test] fn helmholtz_energy_wca_mixture_different_sigma() -> FeosResult<()> { let parameters = test_parameters_mixture( dvector![12.0, 12.0], dvector![6.0, 6.0], dvector![1.0, 2.0], dvector![1.0, 0.5], ); let p = UVTheoryPars::new(&parameters, Perturbation::WeeksChandlerAndersen); // state let reduced_temperature = 1.5; let t_x = reduced_temperature * p.epsilon_k[0] * KELVIN; let sigma_x_3 = (0.4 + 0.6 * 8.0) * ANGSTROM.powi::<3>(); let density = 0.52000000000000002 / sigma_x_3; let moles = dvector![0.4, 0.6] * MOL; let total_moles = moles.sum(); let volume = NAV * total_moles / density; // EoS let eos_wca = &UVTheory::new(parameters); let state_wca = State::new_nvt(&eos_wca, t_x, volume, &moles).unwrap(); let a_wca = (state_wca.residual_molar_helmholtz_energy() / (RGAS * t_x)).into_value(); assert_relative_eq!(a_wca, -0.034206207363139396, max_relative = 1e-5); Ok(()) } }
Rust
3D
feos-org/feos
crates/feos/src/uvtheory/eos/bh/mod.rs
.rs
1,039
36
use crate::hard_sphere::HardSphere; use crate::uvtheory::parameters::UVTheoryPars; use attractive_perturbation::AttractivePerturbation; use feos_core::StateHD; use num_dual::DualNum; use reference_perturbation::ReferencePerturbation; mod attractive_perturbation; mod hard_sphere; mod reference_perturbation; pub struct BarkerHenderson; impl BarkerHenderson { pub fn residual_helmholtz_energy_contributions<D: DualNum<f64> + Copy>( &self, parameters: &UVTheoryPars, state: &StateHD<D>, ) -> Vec<(&'static str, D)> { vec![ ( "Hard Sphere (BH)", HardSphere.helmholtz_energy_density(parameters, state), ), ( "Reference Perturbation (BH)", ReferencePerturbation.helmholtz_energy_density(parameters, state), ), ( "Attractive Perturbation (BH)", AttractivePerturbation.helmholtz_energy_density(parameters, state), ), ] } }
Rust
3D
feos-org/feos
crates/feos/src/uvtheory/eos/bh/hard_sphere.rs
.rs
4,637
133
use super::BarkerHenderson; use crate::uvtheory::parameters::UVTheoryPars; use nalgebra::{DMatrix, DVector, dvector}; use num_dual::DualNum; const BH_CONSTANTS_ETA_B: [[f64; 2]; 3] = [ [-0.960919783, -0.921097447], [-0.547468020, -3.508014069], [-2.253750186, 3.581161364], ]; const BH_CONSTANTS_ETA_A: [[f64; 4]; 4] = [ [-1.217417282, 6.754987582, -0.5919326153, -28.99719604], [1.579548775, -26.93879416, 0.3998915410, 106.9446266], [-1.993990512, 44.11863355, -40.10916106, -29.6130848], [0.0, 0.0, 0.0, 0.0], ]; /// Dimensionless Hard-sphere diameter according to Barker-Henderson division. /// Eq. S23 and S24. impl BarkerHenderson { pub fn diameter_bh<D: DualNum<f64> + Copy>( parameters: &UVTheoryPars, temperature: D, ) -> DVector<D> { parameters .cd_bh_pure .iter() .enumerate() .map(|(i, c)| { let t = temperature / parameters.epsilon_k[i]; let d = t.powf(0.25) * c[1] + t.powf(0.75) * c[2] + t.powf(1.25) * c[3]; (t * c[0] + d * (t + 1.0).ln() + t.powi(2) * c[4] + 1.0) .powf(-0.5 / parameters.rep[i]) * parameters.sigma[i] }) .collect::<Vec<_>>() .into() } } pub(super) fn packing_fraction<D: DualNum<f64> + Copy>( partial_density: &DVector<D>, diameter: &DVector<D>, ) -> D { (0..partial_density.len()).fold(D::zero(), |acc, i| { acc + partial_density[i] * diameter[i].powi(3) * (std::f64::consts::PI / 6.0) }) } pub(super) fn packing_fraction_b<D: DualNum<f64> + Copy>( parameters: &UVTheoryPars, diameter: &DVector<D>, eta: D, ) -> DMatrix<D> { let n = parameters.att.len(); DMatrix::from_fn(n, n, |i, j| { let tau = -(diameter[i] / parameters.sigma[i] + diameter[j] / parameters.sigma[j]) * 0.5 + 1.0; //dimensionless let tau2 = tau * tau; let c = dvector![ tau * BH_CONSTANTS_ETA_B[0][0] + tau2 * BH_CONSTANTS_ETA_B[0][1], tau * BH_CONSTANTS_ETA_B[1][0] + tau2 * BH_CONSTANTS_ETA_B[1][1], tau * BH_CONSTANTS_ETA_B[2][0] + tau2 * BH_CONSTANTS_ETA_B[2][1], ]; eta + eta * c[0] + eta * eta * c[1] + eta.powi(3) * c[2] }) } pub(super) fn packing_fraction_a<D: DualNum<f64> + Copy>( parameters: &UVTheoryPars, diameter: &DVector<D>, eta: D, ) -> DMatrix<D> { let n = parameters.att.len(); DMatrix::from_fn(n, n, |i, j| { let tau = -(diameter[i] / parameters.sigma[i] + diameter[j] / parameters.sigma[j]) * 0.5 + 1.0; let tau2 = tau * tau; let rep_inv = 1.0 / parameters.rep_ij[(i, j)]; let c = dvector![ tau * (BH_CONSTANTS_ETA_A[0][0] + BH_CONSTANTS_ETA_A[0][1] * rep_inv) + tau2 * (BH_CONSTANTS_ETA_A[0][2] + BH_CONSTANTS_ETA_A[0][3] * rep_inv), tau * (BH_CONSTANTS_ETA_A[1][0] + BH_CONSTANTS_ETA_A[1][1] * rep_inv) + tau2 * (BH_CONSTANTS_ETA_A[1][2] + BH_CONSTANTS_ETA_A[1][3] * rep_inv), tau * (BH_CONSTANTS_ETA_A[2][0] + BH_CONSTANTS_ETA_A[2][1] * rep_inv) + tau2 * (BH_CONSTANTS_ETA_A[2][2] + BH_CONSTANTS_ETA_A[2][3] * rep_inv), tau * (BH_CONSTANTS_ETA_A[3][0] + BH_CONSTANTS_ETA_A[3][1] * rep_inv) + tau2 * (BH_CONSTANTS_ETA_A[3][2] + BH_CONSTANTS_ETA_A[3][3] * rep_inv), ]; eta + eta * c[0] + eta * eta * c[1] + eta.powi(3) * c[2] + eta.powi(4) * c[3] }) } #[cfg(test)] #[expect(clippy::excessive_precision)] mod test { use super::*; use crate::uvtheory::{ Perturbation::BarkerHenderson as BH, parameters::utils::{methane_parameters, test_parameters}, }; #[test] fn test_bh_diameter() { let p = test_parameters(12.0, 6.0, 1.0, 1.0, BH); assert_eq!( BarkerHenderson::diameter_bh(&p, 2.0)[0], 0.95777257352360246 ); let p = test_parameters(24.0, 6.0, 1.0, 1.0, BH); assert_eq!( BarkerHenderson::diameter_bh(&p, 5.0)[0], 0.95583586434435486 ); // Methane let p = UVTheoryPars::new(&methane_parameters(12.0, 6.0), BH); assert_eq!( BarkerHenderson::diameter_bh(&p, 2.0 * p.epsilon_k[0])[0] / p.sigma[0], 0.95777257352360246 ); let p = UVTheoryPars::new(&methane_parameters(24.0, 6.0), BH); assert_eq!( BarkerHenderson::diameter_bh(&p, 5.0 * p.epsilon_k[0])[0] / p.sigma[0], 0.95583586434435486 ); } }
Rust
3D
feos-org/feos
crates/feos/src/uvtheory/eos/bh/attractive_perturbation.rs
.rs
9,275
274
use super::BarkerHenderson; use crate::uvtheory::parameters::*; use feos_core::StateHD; use nalgebra::DVector; use num_dual::DualNum; use std::f64::consts::{FRAC_PI_3, PI}; const C_BH: [[f64; 4]; 2] = [ [ 0.168966996450507, -0.991545819144238, 0.743142180601202, -4.32349593441145, ], [ -0.532628162859638, 2.66039013993583, -1.95070279905704, -0.000137219512394905, ], ]; /// Constants for BH u-fraction. const CU_BH: [[f64; 2]; 4] = [ [0.72188, 0.0], [-0.0059822, 2.4676], [2.2919, 14.9735], [5.1647, 2.4017], ]; /// Constants for BH effective inverse reduced temperature. const C2: [[f64; 2]; 3] = [ [1.50542979585173e-03, 3.90426109607451e-02], [3.23388827421376e-04, 1.29508541592689e-02], [5.25749466058948e-05, 5.26748277148572e-04], ]; #[derive(Debug, Clone)] pub(super) struct AttractivePerturbation; impl AttractivePerturbation { /// Helmholtz energy for attractive perturbation, eq. 52 pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &UVTheoryPars, state: &StateHD<D>, ) -> D { let p = parameters; let x = &state.molefracs; let t = state.temperature; let density = state.partial_density.sum(); // vdw effective one fluid properties let (rep_x, att_x, sigma_x, weighted_sigma3_ij, epsilon_k_x, d_x) = one_fluid_properties(p, x, t); let t_x = state.temperature / epsilon_k_x; let rho_x = density * sigma_x.powi(3); let mean_field_constant_x = mean_field_constant(rep_x, att_x, D::one()); let i_bh = correlation_integral_bh(rho_x, mean_field_constant_x, rep_x, att_x, d_x); let delta_a1u = density / t_x * i_bh * 2.0 * PI * weighted_sigma3_ij; let u_fraction_bh = u_fraction_bh( rep_x, density * x.dot(&p.sigma.map(|s| D::from(s.powi(3)))), t_x.recip(), ); let b21u = delta_b12u(t_x, mean_field_constant_x, weighted_sigma3_ij); let b2bar = residual_virial_coefficient(p, x, state.temperature); density * (delta_a1u + (-u_fraction_bh + 1.0) * (b2bar - b21u) * density) } } fn delta_b12u<D: DualNum<f64>>(t_x: D, mean_field_constant_x: D, weighted_sigma3_ij: D) -> D { -mean_field_constant_x / t_x * 2.0 * PI * weighted_sigma3_ij } fn residual_virial_coefficient<D: DualNum<f64> + Copy>( p: &UVTheoryPars, x: &DVector<D>, t: D, ) -> D { let mut delta_b2bar = D::zero(); for (i, xi) in x.iter().enumerate() { for (j, xj) in x.iter().enumerate() { delta_b2bar += *xi * *xj * p.sigma_ij[(i, j)].powi(3) * delta_b2(t / p.eps_k_ij[(i, j)], p.rep_ij[(i, j)], p.att_ij[(i, j)]); } } delta_b2bar } fn correlation_integral_bh<D: DualNum<f64> + Copy>( rho_x: D, mean_field_constant_x: D, rep_x: D, att_x: D, d_x: D, ) -> D { let c = coefficients_bh(rep_x, att_x, d_x); -mean_field_constant_x + mie_prefactor(rep_x, att_x) * (c[0] * rho_x + c[1] * rho_x.powi(2)) / (c[2] * rho_x + 1.0).powi(2) } /// U-fraction according to Barker-Henderson division. /// Eq. 15 fn u_fraction_bh<D: DualNum<f64> + Copy>(rep_x: D, reduced_density: D, one_fluid_beta: D) -> D { let mut c = [D::zero(); 4]; let inv_rep = rep_x.recip(); for i in 0..4 { c[i] = inv_rep * CU_BH[i][1] + CU_BH[i][0]; } let a = 1.2187; let b = 4.2773; (activation(c[1], one_fluid_beta) * (-c[0] + 1.0) + c[0]) * (reduced_density.powf(a) * c[2] + reduced_density.powf(b) * c[3]).tanh() } /// Activation function used for u-fraction according to Barker-Henderson division. /// Eq. 16 fn activation<D: DualNum<f64> + Copy>(c: D, one_fluid_beta: D) -> D { one_fluid_beta * c.sqrt() / (one_fluid_beta.powi(2) * c + 1.0).sqrt() } fn one_fluid_properties<D: DualNum<f64> + Copy>( p: &UVTheoryPars, x: &DVector<D>, t: D, ) -> (D, D, D, D, D, D) { let d = BarkerHenderson::diameter_bh(p, t); // &p.sigma; let mut epsilon_k = D::zero(); let mut weighted_sigma3_ij = D::zero(); let mut rep = D::zero(); let mut att = D::zero(); let mut d_x_3 = D::zero(); for (i, xi) in x.iter().enumerate() { d_x_3 += *xi * d[i].powi(3); for (j, xj) in x.iter().enumerate() { let _y = *xi * *xj * p.sigma_ij[(i, j)].powi(3); weighted_sigma3_ij += _y; epsilon_k += _y * p.eps_k_ij[(i, j)]; rep += *xi * *xj * p.rep_ij[(i, j)]; att += *xi * *xj * p.att_ij[(i, j)]; } } let sigma_x = x.dot(&p.sigma.map(|v| D::from(v.powi(3)))).powf(1.0 / 3.0); let dx = d_x_3.powf(1.0 / 3.0) / sigma_x; ( rep, att, sigma_x, weighted_sigma3_ij, epsilon_k / weighted_sigma3_ij, dx, ) } fn coefficients_bh<D: DualNum<f64> + Copy>(rep: D, att: D, d: D) -> [D; 3] { let c11 = d.powd(-rep + 6.0) * ((D::one() * 2.0f64).powd(-rep + 3.0) - d.powd(rep - 3.0)) / (-rep + 3.0) + (-d.powi(3) * 8.0 + 1.0) / 24.0; let c12 = (d.powd(-rep + 6.0) * ((D::one() * 2.0f64).powd(-rep + 4.0) - d.powd(rep - 4.0)) / (-rep + 4.0) + (-d.powi(2) * 4.0 + 1.0) / 8.0) * -0.75; let c13 = (((d * 2.0).powd(-rep + 6.0) - 1.0) / (-rep + 6.0) - (d * 2.0).ln() * d.powd(-att + 6.0)) / 16.0; let rep_inv = rep.recip(); let c1 = (c11 + c12 + c13) * FRAC_PI_3 * 4.0; let c2 = rep_inv * C_BH[0][1] + C_BH[0][0] - (rep_inv * C_BH[0][3] + C_BH[0][2]) * (-d + 1.0); let c3 = rep_inv * C_BH[1][1] + C_BH[1][0] - (rep_inv * C_BH[1][3] + C_BH[1][2]) * (-d + 1.0); [c1, c2, c3] } fn delta_b2<D: DualNum<f64> + Copy>(reduced_temperature: D, rep: f64, att: f64) -> D { let rc = 5.0; let alpha = mean_field_constant(rep, att, rc); let yeff = y_eff(reduced_temperature, rep, att); -(yeff * (rc.powi(3) - 1.0) / 3.0 + reduced_temperature.recip() * alpha) * 2.0 * PI } fn y_eff<D: DualNum<f64> + Copy>(reduced_temperature: D, rep: f64, att: f64) -> D { // optimize: move this part to parameter initialization let rc = 5.0; let rs = 1.0; let c0 = 1.0 - 3.0 * (mean_field_constant(rep, att, rs) - mean_field_constant(rep, att, rc)) / (rc.powi(3) - rs.powi(3)); let c1 = C2[0][0] + C2[0][1] / rep; let c2 = C2[1][0] + C2[1][1] / rep; let c3 = C2[2][0] + C2[2][1] / rep; let beta = reduced_temperature.recip(); let beta_eff = beta * (-(beta * (beta * c2 + beta.powi(3) * c3 + c1) + 1.0).recip() * c0 + 1.0); beta_eff.exp() - 1.0 } #[cfg(test)] mod test { use super::*; use crate::uvtheory::Perturbation::BarkerHenderson as BH; use crate::uvtheory::parameters::utils::methane_parameters; use approx::assert_relative_eq; use nalgebra::dvector; #[test] fn test_attractive_perturbation() { // m = 12, t = 4.0, rho = 1.0 let reduced_temperature = 4.0; let reduced_density = 1.0; let p = UVTheoryPars::new(&methane_parameters(24.0, 6.0), BH); let state = StateHD::new( reduced_temperature * p.epsilon_k[0], p.sigma[0].powi(3) / reduced_density, &dvector![1.0], ); let x = &state.molefracs; let (rep_x, att_x, sigma_x, weighted_sigma3_ij, epsilon_k_x, d_x) = one_fluid_properties(&p, &state.molefracs, state.temperature); let t_x = state.temperature / epsilon_k_x; let rho_x = state.partial_density.sum() * sigma_x.powi(3); let mean_field_constant_x = mean_field_constant(rep_x, att_x, 1.0); let i_bh = correlation_integral_bh(rho_x, mean_field_constant_x, rep_x, att_x, d_x); let delta_a1u = state.partial_density.sum() / t_x * i_bh * 2.0 * PI * weighted_sigma3_ij; dbg!(delta_a1u); //assert!(delta_a1u == -1.1470186919354); assert_relative_eq!(delta_a1u, -1.1470186919354, epsilon = 1e-12); let u_fraction_bh = u_fraction_bh( rep_x, state.partial_density.sum() * (x * &p.sigma.map(|s| s.powi(3))).sum(), t_x.recip(), ); dbg!(u_fraction_bh); //assert!(u_fraction_bh == 0.743451055308332); assert_relative_eq!(u_fraction_bh, 0.743451055308332, epsilon = 1e-5); let b21u = delta_b12u(t_x, mean_field_constant_x, weighted_sigma3_ij); dbg!(b21u); assert!(b21u / p.sigma[0].powi(3) == -0.949898568221715); let b2bar = residual_virial_coefficient(&p, x, state.temperature); dbg!(b2bar); assert_relative_eq!( b2bar / p.sigma[0].powi(3), -1.00533412744652, epsilon = 1e-12 ); //assert!(b2bar ==-1.00533412744652); //let a_test = state.moles.sum() // * (delta_a1u + (-u_fraction_bh + 1.0) * (b2bar - b21u) * state.partial_density.sum()); let a = AttractivePerturbation.helmholtz_energy_density(&p, &state) / state.partial_density.sum(); dbg!(a); //assert!(-1.16124062615291 == a) assert_relative_eq!(-1.16124062615291, a, epsilon = 1e-5); } }
Rust
3D
feos-org/feos
crates/feos/src/uvtheory/eos/bh/reference_perturbation.rs
.rs
2,147
60
use super::BarkerHenderson; use super::hard_sphere::{packing_fraction, packing_fraction_a, packing_fraction_b}; use crate::uvtheory::parameters::UVTheoryPars; use feos_core::StateHD; use num_dual::DualNum; use std::f64::consts::PI; #[derive(Debug, Clone)] pub(super) struct ReferencePerturbation; impl ReferencePerturbation { /// Helmholtz energy for perturbation reference (Mayer-f), eq. 29 pub fn helmholtz_energy_density<D: DualNum<f64> + Copy>( &self, parameters: &UVTheoryPars, state: &StateHD<D>, ) -> D { let p = parameters; let n = p.sigma.len(); let x = &state.molefracs; let d = BarkerHenderson::diameter_bh(p, state.temperature); let eta = packing_fraction(&state.partial_density, &d); let eta_a = packing_fraction_a(p, &d, eta); let eta_b = packing_fraction_b(p, &d, eta); let mut a = D::zero(); for i in 0..n { for j in 0..n { let d_ij = (d[i] + d[j]) * 0.5; // (d[i] * p.sigma[i] + d[j] * p.sigma[j]) * 0.5; a += x[i] * x[j] * (((-eta_a[(i, j)] * 0.5 + 1.0) / (-eta_a[(i, j)] + 1.0).powi(3)) - ((-eta_b[(i, j)] * 0.5 + 1.0) / (-eta_b[(i, j)] + 1.0).powi(3))) * (-d_ij.powi(3) + p.sigma_ij[(i, j)].powi(3)) } } -a * state.partial_density.sum().powi(2) * 2.0 / 3.0 * PI } } #[cfg(test)] mod test { use super::*; use crate::uvtheory::{Perturbation, parameters::utils::test_parameters}; use approx::assert_relative_eq; use nalgebra::dvector; #[test] fn test_delta_a0_bh() { // m = 12.0, t = 4.0, rho = 1.0 let reduced_temperature = 4.0; let reduced_density = 1.0; let p = test_parameters(24.0, 6.0, 1.0, 1.0, Perturbation::BarkerHenderson); let state = StateHD::new(reduced_temperature, 1.0 / reduced_density, &dvector![1.0]); let a = ReferencePerturbation.helmholtz_energy_density(&p, &state) / reduced_density; assert_relative_eq!(a, -0.0611105573289734, epsilon = 1e-10); } }
Rust
3D
feos-org/feos
crates/feos/src/uvtheory/eos/wca/mod.rs
.rs
1,999
66
use crate::hard_sphere::HardSphere; use crate::uvtheory::parameters::UVTheoryPars; use feos_core::StateHD; mod attractive_perturbation; mod attractive_perturbation_uvb3; mod hard_sphere; mod reference_perturbation; mod reference_perturbation_uvb3; use attractive_perturbation::AttractivePerturbation; use attractive_perturbation_uvb3::AttractivePerturbationB3; use num_dual::DualNum; use reference_perturbation::ReferencePerturbation; use reference_perturbation_uvb3::ReferencePerturbationB3; pub struct WeeksChandlerAndersen; impl WeeksChandlerAndersen { pub fn residual_helmholtz_energy_contributions<D: DualNum<f64> + Copy>( &self, parameters: &UVTheoryPars, state: &StateHD<D>, ) -> Vec<(&'static str, D)> { vec![ ( "Hard Sphere (WCA)", HardSphere.helmholtz_energy_density(parameters, state), ), ( "Reference Perturbation (WCA)", ReferencePerturbation.helmholtz_energy_density(parameters, state), ), ( "Attractive Perturbation (WCA)", AttractivePerturbation.helmholtz_energy_density(parameters, state), ), ] } } pub struct WeeksChandlerAndersenB3; impl WeeksChandlerAndersenB3 { pub fn residual_helmholtz_energy_contributions<D: DualNum<f64> + Copy>( &self, parameters: &UVTheoryPars, state: &StateHD<D>, ) -> Vec<(&'static str, D)> { vec![ ( "Hard Sphere (WCA)", HardSphere.helmholtz_energy_density(parameters, state), ), ( "Reference Perturbation (WCA B3)", ReferencePerturbationB3.helmholtz_energy_density(parameters, state), ), ( "Attractive Perturbation (WCA B3)", AttractivePerturbationB3.helmholtz_energy_density(parameters, state), ), ] } }
Rust
3D
feos-org/feos
crates/feos/src/uvtheory/eos/wca/hard_sphere.rs
.rs
10,995
309
use crate::uvtheory::WeeksChandlerAndersen; use crate::uvtheory::parameters::UVTheoryPars; use nalgebra::{DMatrix, DVector, dvector}; use num_dual::DualNum; use std::f64::consts::PI; pub(super) const WCA_CONSTANTS_Q: [[f64; 4]; 3] = [ [1.92840364363978, 4.43165896265079E-01, 0.0, 0.0], [ 5.20120816141761E-01, 1.82526759234412E-01, 1.10319989659929E-02, -7.97813995328348E-05, ], [ 0.0, 1.29885156087242E-02, 6.41039871789327E-03, 1.85866741090323E-05, ], ]; const WCA_CONSTANTS_ETA_A: [[f64; 4]; 4] = [ [-0.888512176, 0.265207151, -0.851803291, -1.380304110], [-0.395548410, -0.626398537, -1.484059291, -3.041216688], [-2.905719617, -1.778798984, -1.556827067, -4.308085347], [0.429154871, 20.765871545, 9.341250676, -33.787719418], ]; const WCA_CONSTANTS_ETA_B: [[f64; 2]; 3] = [ [-0.883143456, -0.618156214], [-0.589914255, -3.015264636], [-2.152046477, 4.7038689542], ]; // New Fit to numerical integrals for uv-B3-theory pub(super) const WCA_CONSTANTS_ETA_A_UVB3: [[f64; 4]; 4] = [ [2.64043218, -1.2184421, -22.90786387, 0.96433414], [-16.75643936, 30.83929771, 73.08711814, -166.57701616], [19.53170162, -88.87955657, -76.51387192, 443.68942745], [-3.77740877, 83.04694547, 21.62502721, -304.8643176], ]; pub(super) const WCA_CONSTANTS_ETA_B_UVB3: [[f64; 2]; 3] = [ [2.19821588, -20.45005484], [-13.47050687, 56.65701375], [12.90119266, -42.71680606], ]; /// Dimensionless Hard-sphere diameter according to Weeks-Chandler-Andersen division. impl WeeksChandlerAndersen { pub fn diameter_wca<D: DualNum<f64> + Copy>( parameters: &UVTheoryPars, temperature: D, ) -> DVector<D> { parameters .sigma .iter() .enumerate() .map(|(i, _b)| { let t = temperature / parameters.epsilon_k[i]; let rm = (parameters.rep[i] / parameters.att[i]) .powf(1.0 / (parameters.rep[i] - parameters.att[i])); let c = (parameters.rep[i] / 6.0) .powf(-parameters.rep[i] / (12.0 - 2.0 * parameters.rep[i])) - 1.0; (((t.sqrt() * c + 1.0).powf(2.0 / parameters.rep[i])).recip() * rm) * parameters.sigma[i] }) .collect::<Vec<_>>() .into() } } pub(super) fn dimensionless_diameter_q_wca<D: DualNum<f64> + Copy>( t_x: D, rep_x: D, att_x: D, ) -> D { let nu = rep_x; let n = att_x; let rs = (nu / n).powd((nu - n).recip()); let coeffs = dvector![ (nu * 2.0 * PI / n).sqrt(), (nu - 7.0) * WCA_CONSTANTS_Q[0][1] + WCA_CONSTANTS_Q[0][0], (nu - 7.0) * WCA_CONSTANTS_Q[1][1] + (nu - 7.0).powi(2) * WCA_CONSTANTS_Q[1][2] + (nu - 7.0).powi(3) * WCA_CONSTANTS_Q[1][3] + WCA_CONSTANTS_Q[1][0], (nu - 7.0) * WCA_CONSTANTS_Q[2][1] + (nu - 7.0).powi(2) * WCA_CONSTANTS_Q[2][2] + (nu - 7.0).powi(3) * WCA_CONSTANTS_Q[2][3] + WCA_CONSTANTS_Q[2][0], ]; (t_x.powf(2.0) * coeffs[3] + t_x.powf(3.0 / 2.0) * coeffs[2] + t_x * coeffs[1] + t_x.powf(1.0 / 2.0) * coeffs[0] + 1.0) .powd(-(nu * 2.0).recip()) * rs } pub(super) fn packing_fraction<D: DualNum<f64> + Copy>( partial_density: &DVector<D>, diameter: &DVector<D>, ) -> D { (0..partial_density.len()).fold(D::zero(), |acc, i| { acc + partial_density[i] * diameter[i].powi(3) * (std::f64::consts::PI / 6.0) }) } #[inline] pub(super) fn dimensionless_length_scale<D: DualNum<f64> + Copy>( parameters: &UVTheoryPars, temperature: D, ) -> DVector<D> { parameters .sigma .iter() .enumerate() .map(|(i, _c)| { let rs = (parameters.rep[i] / parameters.att[i]) .powf(1.0 / (parameters.rep[i] - parameters.att[i])); -WeeksChandlerAndersen::diameter_wca(parameters, temperature)[i] + rs * parameters.sigma[i] // parameters.sigma[i] }) .collect::<Vec<_>>() .into() } #[inline] pub(super) fn packing_fraction_b<D: DualNum<f64> + Copy>( parameters: &UVTheoryPars, eta: D, temperature: D, ) -> DMatrix<D> { let n = parameters.att.len(); let dimensionless_lengths = dimensionless_length_scale(parameters, temperature); DMatrix::from_fn(n, n, |i, j| { let tau = (dimensionless_lengths[i] + dimensionless_lengths[j]) / parameters.sigma_ij[(i, j)] * 0.5; //dimensionless let tau2 = tau * tau; let c = dvector![ tau * WCA_CONSTANTS_ETA_B[0][0] + tau2 * WCA_CONSTANTS_ETA_B[0][1], tau * WCA_CONSTANTS_ETA_B[1][0] + tau2 * WCA_CONSTANTS_ETA_B[1][1], tau * WCA_CONSTANTS_ETA_B[2][0] + tau2 * WCA_CONSTANTS_ETA_B[2][1], ]; eta + eta * c[0] + eta * eta * c[1] + eta.powi(3) * c[2] }) } pub(super) fn packing_fraction_b_uvb3<D: DualNum<f64> + Copy>( parameters: &UVTheoryPars, eta: D, temperature: D, ) -> DMatrix<D> { let n = parameters.att.len(); let dimensionless_lengths = dimensionless_length_scale(parameters, temperature); DMatrix::from_fn(n, n, |i, j| { let tau = (dimensionless_lengths[i] + dimensionless_lengths[j]) / parameters.sigma_ij[(i, j)] * 0.5; //dimensionless let tau2 = tau * tau; let c = dvector![ tau * WCA_CONSTANTS_ETA_B_UVB3[0][0] + tau2 * WCA_CONSTANTS_ETA_B_UVB3[0][1], tau * WCA_CONSTANTS_ETA_B_UVB3[1][0] + tau2 * WCA_CONSTANTS_ETA_B_UVB3[1][1], tau * WCA_CONSTANTS_ETA_B_UVB3[2][0] + tau2 * WCA_CONSTANTS_ETA_B_UVB3[2][1], ]; eta + eta * c[0] + eta * eta * c[1] + eta.powi(3) * c[2] }) } pub(super) fn packing_fraction_a<D: DualNum<f64> + Copy>( parameters: &UVTheoryPars, eta: D, temperature: D, ) -> DMatrix<D> { let dimensionless_lengths = dimensionless_length_scale(parameters, temperature); let n = parameters.att.len(); DMatrix::from_fn(n, n, |i, j| { let tau = (dimensionless_lengths[i] + dimensionless_lengths[j]) / parameters.sigma_ij[(i, j)] * 0.5; //dimensionless let tau2 = tau * tau; let rep_inv = 1.0 / parameters.rep_ij[(i, j)]; let c = dvector![ tau * (WCA_CONSTANTS_ETA_A[0][0] + WCA_CONSTANTS_ETA_A[0][1] * rep_inv) + tau2 * (WCA_CONSTANTS_ETA_A[0][2] + WCA_CONSTANTS_ETA_A[0][3] * rep_inv), tau * (WCA_CONSTANTS_ETA_A[1][0] + WCA_CONSTANTS_ETA_A[1][1] * rep_inv) + tau2 * (WCA_CONSTANTS_ETA_A[1][2] + WCA_CONSTANTS_ETA_A[1][3] * rep_inv), tau * (WCA_CONSTANTS_ETA_A[2][0] + WCA_CONSTANTS_ETA_A[2][1] * rep_inv) + tau2 * (WCA_CONSTANTS_ETA_A[2][2] + WCA_CONSTANTS_ETA_A[2][3] * rep_inv), tau * (WCA_CONSTANTS_ETA_A[3][0] + WCA_CONSTANTS_ETA_A[3][1] * rep_inv) + tau2 * (WCA_CONSTANTS_ETA_A[3][2] + WCA_CONSTANTS_ETA_A[3][3] * rep_inv), ]; eta + eta * c[0] + eta * eta * c[1] + eta.powi(3) * c[2] + eta.powi(4) * c[3] }) } pub(super) fn packing_fraction_a_uvb3<D: DualNum<f64> + Copy>( parameters: &UVTheoryPars, eta: D, temperature: D, ) -> DMatrix<D> { let dimensionless_lengths = dimensionless_length_scale(parameters, temperature); let n = parameters.att.len(); DMatrix::from_fn(n, n, |i, j| { let tau = (dimensionless_lengths[i] + dimensionless_lengths[j]) / parameters.sigma_ij[(i, j)] * 0.5; //dimensionless let tau2 = tau * tau; let rep_inv = 1.0 / parameters.rep_ij[(i, j)]; let c = dvector![ tau * (WCA_CONSTANTS_ETA_A_UVB3[0][0] + WCA_CONSTANTS_ETA_A_UVB3[0][1] * rep_inv) + tau2 * (WCA_CONSTANTS_ETA_A_UVB3[0][2] + WCA_CONSTANTS_ETA_A_UVB3[0][3] * rep_inv), tau * (WCA_CONSTANTS_ETA_A_UVB3[1][0] + WCA_CONSTANTS_ETA_A_UVB3[1][1] * rep_inv) + tau2 * (WCA_CONSTANTS_ETA_A_UVB3[1][2] + WCA_CONSTANTS_ETA_A_UVB3[1][3] * rep_inv), tau * (WCA_CONSTANTS_ETA_A_UVB3[2][0] + WCA_CONSTANTS_ETA_A_UVB3[2][1] * rep_inv) + tau2 * (WCA_CONSTANTS_ETA_A_UVB3[2][2] + WCA_CONSTANTS_ETA_A_UVB3[2][3] * rep_inv), tau * (WCA_CONSTANTS_ETA_A_UVB3[3][0] + WCA_CONSTANTS_ETA_A_UVB3[3][1] * rep_inv) + tau2 * (WCA_CONSTANTS_ETA_A_UVB3[3][2] + WCA_CONSTANTS_ETA_A_UVB3[3][3] * rep_inv), ]; eta + eta * c[0] + eta * eta * c[1] + eta.powi(3) * c[2] + eta.powi(4) * c[3] }) } #[cfg(test)] #[expect(clippy::excessive_precision)] mod test { use super::*; use crate::hard_sphere::HardSphere; use crate::uvtheory::Perturbation::WeeksChandlerAndersen as WCA; use crate::uvtheory::parameters::utils::{ methane_parameters, test_parameters, test_parameters_mixture, }; use approx::assert_relative_eq; use feos_core::StateHD; #[test] fn test_wca_diameter() { let p = test_parameters(24.0, 6.0, 2.0, 1.0, WCA); let temp = 4.0; assert_eq!( WeeksChandlerAndersen::diameter_wca(&p, temp)[0] / p.sigma[0], 0.9614325601663462 ); // Methane let p = UVTheoryPars::new(&methane_parameters(24.0, 6.0), WCA); assert_eq!( WeeksChandlerAndersen::diameter_wca(&p, 4.0 * p.epsilon_k[0])[0] / p.sigma[0], 0.9614325601663462 ); assert_eq!( WeeksChandlerAndersen::diameter_wca(&p, 4.0 * p.epsilon_k[0])[0] / p.sigma[0], 0.9614325601663462 ); assert_relative_eq!( dimensionless_diameter_q_wca(temp, p.rep[0], p.att[0]), 0.9751576149023506, epsilon = 1e-8 ); assert_relative_eq!( dimensionless_length_scale(&p, 4.0 * p.epsilon_k[0])[0] / p.sigma[0], 0.11862717872596029, epsilon = 1e-8 ); } #[test] fn test_hard_sphere_wca_mixture() { let molefracs = dvector![0.40000000000000002, 0.59999999999999998]; let reduced_temperature = 1.0; let reduced_density = 0.90000000000000002; let reduced_volume = 1.0 / reduced_density; let p = UVTheoryPars::new( &test_parameters_mixture( dvector![12.0, 12.0], dvector![6.0, 6.0], dvector![1.0, 1.0], dvector![1.0, 0.5], ), WCA, ); let state = StateHD::new(reduced_temperature, reduced_volume, &molefracs); let a = HardSphere.helmholtz_energy_density(&p, &state) * reduced_volume; assert_relative_eq!(a, 3.8636904888563084, epsilon = 1e-10); } }
Rust