-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathproperties.rs
More file actions
397 lines (363 loc) · 17.3 KB
/
properties.rs
File metadata and controls
397 lines (363 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
use super::DFTProfile;
use crate::convolver::{BulkConvolver, Convolver};
use crate::functional_contribution::{FunctionalContribution, FunctionalContributionDual};
use crate::{ConvolverFFT, DFTSolverLog, HelmholtzEnergyFunctional, WeightFunctionInfo};
use feos_core::{Contributions, EosResult, EosUnit, IdealGas, Verbosity};
use ndarray::{Array, Axis, Dimension, RemoveAxis, ScalarOperand};
use num_dual::{Dual64, DualNum};
use quantity::si::{SIArray, SIArray1, SIArray2, SINumber, SIUnit};
use std::ops::AddAssign;
use std::sync::Arc;
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) -> EosResult<SIArray<D>> {
// Calculate residual Helmholtz energy density and functional derivative
let t = self
.temperature
.to_reduced(SIUnit::reference_temperature())?;
let rho = self.density.to_reduced(SIUnit::reference_density())?;
let (mut f, dfdrho) = self.dft.functional_derivative(t, &rho, &self.convolver)?;
// Calculate the grand potential density
for ((rho, dfdrho), &m) in rho
.outer_iter()
.zip(dfdrho.outer_iter())
.zip(self.dft.m().iter())
{
f -= &((&dfdrho + m) * &rho);
}
let bond_lengths = self.dft.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(f * t * SIUnit::reference_pressure())
}
/// Calculate the grand potential $\Omega$.
pub fn grand_potential(&self) -> EosResult<SINumber> {
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) -> EosResult<Array<f64, D::Larger>> {
let (_, dfdrho) = self.dft.functional_derivative(
self.temperature
.to_reduced(SIUnit::reference_temperature())?,
&self.density.to_reduced(SIUnit::reference_density())?,
&self.convolver,
)?;
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: &Arc<dyn Convolver<N, D>>,
) -> EosResult<Array<N, D>>
where
N: DualNum<f64> + Copy + ScalarOperand,
dyn FunctionalContribution: FunctionalContributionDual<N>,
{
let density_dual = density.mapv(N::from);
let weighted_densities = convolver.weighted_densities(&density_dual);
let functional_contributions = self.dft.contributions();
let mut helmholtz_energy_density: Array<N, D> = self
.dft
.ideal_chain_contribution()
.calculate_helmholtz_energy_density(&density.mapv(N::from))?;
for (c, wd) in functional_contributions.iter().zip(weighted_densities) {
let nwd = wd.shape()[0];
let ngrid = wd.len() / nwd;
helmholtz_energy_density
.view_mut()
.into_shape(ngrid)
.unwrap()
.add_assign(&c.calculate_helmholtz_energy_density(
temperature,
wd.into_shape((nwd, ngrid)).unwrap().view(),
)?);
}
Ok(helmholtz_energy_density * temperature)
}
/// Calculate the residual entropy density $s^\mathrm{res}(\mathbf{r})$.
///
/// Untested with heterosegmented functionals.
pub fn residual_entropy_density(&self) -> EosResult<SIArray<D>> {
// initialize convolver
let temperature = self
.temperature
.to_reduced(SIUnit::reference_temperature())?;
let temperature_dual = Dual64::from(temperature).derivative();
let functional_contributions = self.dft.contributions();
let weight_functions: Vec<WeightFunctionInfo<Dual64>> = functional_contributions
.iter()
.map(|c| c.weight_functions(temperature_dual))
.collect();
let convolver = ConvolverFFT::plan(&self.grid, &weight_functions, None);
let density = self.density.to_reduced(SIUnit::reference_density())?;
let helmholtz_energy_density =
self.intrinsic_helmholtz_energy_density(temperature_dual, &density, &convolver)?;
Ok(helmholtz_energy_density.mapv(|f| -f.eps)
* (SIUnit::reference_entropy() / SIUnit::reference_volume()))
}
/// 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: &Arc<dyn Convolver<Dual64, D>>,
) -> EosResult<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.dft.contributions();
let mut helmholtz_energy_density: Vec<Array<Dual64, D>> =
Vec::with_capacity(functional_contributions.len() + 1);
helmholtz_energy_density.push(
self.dft
.ideal_chain_contribution()
.calculate_helmholtz_energy_density(&density.mapv(Dual64::from))?,
);
for (c, wd) in functional_contributions.iter().zip(weighted_densities) {
let nwd = wd.shape()[0];
let ngrid = wd.len() / nwd;
helmholtz_energy_density.push(
c.calculate_helmholtz_energy_density(
temperature_dual,
wd.into_shape((nwd, ngrid)).unwrap().view(),
)?
.into_shape(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 + IdealGas> 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.dft.ideal_gas_model().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 * temperature
}
/// Calculate the entropy density $s(\mathbf{r})$.
///
/// Untested with heterosegmented functionals.
pub fn entropy_density(&self, contributions: Contributions) -> EosResult<SIArray<D>> {
// initialize convolver
let temperature = self
.temperature
.to_reduced(SIUnit::reference_temperature())?;
let temperature_dual = Dual64::from(temperature).derivative();
let functional_contributions = self.dft.contributions();
let weight_functions: Vec<WeightFunctionInfo<Dual64>> = functional_contributions
.iter()
.map(|c| c.weight_functions(temperature_dual))
.collect();
let convolver = ConvolverFFT::plan(&self.grid, &weight_functions, None);
let density = self.density.to_reduced(SIUnit::reference_density())?;
let mut helmholtz_energy_density =
self.intrinsic_helmholtz_energy_density(temperature_dual, &density, &convolver)?;
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(helmholtz_energy_density.mapv(|f| -f.eps)
* (SIUnit::reference_entropy() / SIUnit::reference_volume()))
}
/// Calculate the entropy $S$.
///
/// Untested with heterosegmented functionals.
pub fn entropy(&self, contributions: Contributions) -> EosResult<SINumber> {
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) -> EosResult<SIArray<D>>
where
D: Dimension,
D::Larger: Dimension<Smaller = D>,
{
// initialize convolver
let temperature = self
.temperature
.to_reduced(SIUnit::reference_temperature())?;
let temperature_dual = Dual64::from(temperature).derivative();
let functional_contributions = self.dft.contributions();
let weight_functions: Vec<WeightFunctionInfo<Dual64>> = functional_contributions
.iter()
.map(|c| c.weight_functions(temperature_dual))
.collect();
let convolver = ConvolverFFT::plan(&self.grid, &weight_functions, None);
let density = self.density.to_reduced(SIUnit::reference_density())?;
let mut helmholtz_energy_density_dual =
self.intrinsic_helmholtz_energy_density(temperature_dual, &density, &convolver)?;
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(helmholtz_energy_density * (SIUnit::reference_energy() / SIUnit::reference_volume()))
}
/// Calculate the internal energy $U$.
///
/// Untested with heterosegmented functionals.
pub fn internal_energy(&self, contributions: Contributions) -> EosResult<SINumber> {
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>) -> EosResult<Array<f64, D::Larger>> {
let rho = self.density.to_reduced(SIUnit::reference_density())?;
let partial_density = self
.bulk
.partial_density
.to_reduced(SIUnit::reference_density())?;
let rho_bulk = self.dft.component_index().mapv(|i| partial_density[i]);
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.dft.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) -> EosResult<SIArray<<D::Larger as Dimension>::Larger>> {
let shape = self.density.shape();
let shape: Vec<_> = std::iter::once(&shape[0]).chain(shape).copied().collect();
let mut drho_dmu = Array::zeros(shape).into_dimensionality().unwrap();
for (k, mut d) in drho_dmu.outer_iter_mut().enumerate() {
let mut lhs = self.density.to_reduced(SIUnit::reference_density())?;
for (i, mut l) in lhs.outer_iter_mut().enumerate() {
if i != k {
l.fill(0.0);
}
}
d.assign(&self.density_derivative(&lhs)?);
}
Ok(drho_dmu
* (SIUnit::reference_density() / SIUnit::reference_molar_entropy() / self.temperature))
}
/// 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) -> EosResult<SIArray2> {
let drho_dmu = self.drho_dmu()?;
let n = drho_dmu.shape()[0];
let dn_dmu = SIArray2::from_shape_fn([n; 2], |(i, j)| {
self.integrate(&drho_dmu.index_axis(Axis(0), i).index_axis(Axis(0), j))
});
Ok(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) -> EosResult<SIArray<D::Larger>> {
let mut lhs = self.density.to_reduced(SIUnit::reference_density())?;
let v = self
.bulk
.partial_molar_volume()
.to_reduced(SIUnit::reference_volume() / SIUnit::reference_moles())?;
for (mut l, &c) in lhs.outer_iter_mut().zip(self.dft.component_index().iter()) {
l *= v[c];
}
self.density_derivative(&lhs)
.map(|x| x / (SIUnit::reference_molar_entropy() * self.temperature))
}
/// 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) -> EosResult<SIArray1> {
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}}$
///
/// Not compatible with heterosegmented DFT.
pub fn drho_dt(&self) -> EosResult<SIArray<D::Larger>> {
let rho = self.density.to_reduced(SIUnit::reference_density())?;
let t = self
.temperature
.to_reduced(SIUnit::reference_temperature())?;
// calculate temperature derivative of functional derivative
let functional_contributions = self.dft.contributions();
let weight_functions: Vec<WeightFunctionInfo<Dual64>> = functional_contributions
.iter()
.map(|c| c.weight_functions(Dual64::from(t).derivative()))
.collect();
let convolver: Arc<dyn Convolver<_, D>> =
ConvolverFFT::plan(&self.grid, &weight_functions, None);
let (_, dfdrhodt) = self.dft.functional_derivative_dual(t, &rho, &convolver)?;
// calculate temperature derivative of bulk functional derivative
let partial_density = self
.bulk
.partial_density
.to_reduced(SIUnit::reference_density())?;
let rho_bulk = self.dft.component_index().mapv(|i| partial_density[i]);
let bulk_convolver = BulkConvolver::new(weight_functions);
let (_, dfdrhodt_bulk) =
self.dft
.functional_derivative_dual(t, &rho_bulk, &bulk_convolver)?;
// solve for drho_dt
let x = (self.bulk.partial_molar_volume() * self.bulk.dp_dt(Contributions::Total))
.to_reduced(SIUnit::reference_molar_entropy())?;
let mut lhs = dfdrhodt.mapv(|d| d.eps);
lhs.outer_iter_mut()
.zip(dfdrhodt_bulk.into_iter())
.zip(x.into_iter())
.for_each(|((mut lhs, d), x)| lhs -= d.eps - x);
lhs.outer_iter_mut()
.zip(rho.outer_iter())
.zip(rho_bulk.into_iter())
.zip(self.dft.m().iter())
.for_each(|(((mut lhs, rho), rho_b), &m)| lhs += &((&rho / rho_b).mapv(f64::ln) * m));
lhs *= &(-&rho / t);
self.density_derivative(&lhs)
.map(|x| x * (SIUnit::reference_density() / SIUnit::reference_temperature()))
}
/// 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}}$
///
/// Not compatible with heterosegmented DFT.
pub fn dn_dt(&self) -> EosResult<SIArray1> {
Ok(self.integrate_segments(&self.drho_dt()?))
}
}