feos-core 0.10.0

Core traits and functionalities for the `feos` project.
Documentation
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#![expect(clippy::toplevel_ref_arg)]
use super::PhaseEquilibrium;
use crate::errors::FeosResult;
use crate::state::State;
use crate::{Composition, FeosError, ReferenceSystem, SolverOptions, Total, Verbosity};
use nalgebra::allocator::Allocator;
use nalgebra::{DefaultAllocator, Dim, DimAdd, OVector, U1, U2, U3, stack, vector};
use num_dual::linalg::LU;
use num_dual::{
    Dual, Dual64, DualNum, DualStruct, Gradients, first_derivative, implicit_derivative_sp, partial,
};
use quantity::{Density, MolarEnergy, MolarEntropy, Pressure, Quantity, SIUnit, Temperature};

const MAX_ITER_PX: usize = 20;
const TOL_PX: f64 = 1e-11;

type PXVars<N> = <N as DimAdd<U3>>::Output;
type TPVars<N> = <N as DimAdd<U2>>::Output;

impl<E: Total<N, D>, N: Gradients + DimAdd<U2> + DimAdd<U3>, D: DualNum<f64> + Copy>
    PhaseEquilibrium<E, 2, N, D>
where
    DefaultAllocator: Allocator<N>
        + Allocator<N, N>
        + Allocator<PXVars<N>>
        + Allocator<U1, PXVars<N>>
        + Allocator<PXVars<N>, PXVars<N>>
        + Allocator<TPVars<N>>
        + Allocator<U1, TPVars<N>>
        + Allocator<TPVars<N>, TPVars<N>>,
    PXVars<N>: Gradients,
    TPVars<N>: Gradients,
{
    /// Perform a ph-flash calculation. An initial temperature is required
    /// and the system needs to be in the two-phase region at that initial
    /// temperature.
    ///
    /// based on Michelsen's work [State function based flash specifications](https://doi.org/10.1016/S0378-3812(99)00092-8)
    pub fn ph_flash<X: Composition<D, N>>(
        eos: &E,
        pressure: Pressure<D>,
        molar_enthalpy: MolarEnergy<D>,
        feed: X,
        initial_temperature: Temperature,
        options: SolverOptions,
    ) -> FeosResult<Self> {
        PhaseEquilibrium::px_flash(
            eos,
            pressure,
            molar_enthalpy,
            feed,
            initial_temperature,
            options,
        )
    }

    /// Perform a ps-flash calculation. An initial temperature is required
    /// and the system needs to be in the two-phase region at that initial
    /// temperature.
    ///
    /// based on Michelsen's work [State function based flash specifications](https://doi.org/10.1016/S0378-3812(99)00092-8)
    pub fn ps_flash<X: Composition<D, N>>(
        eos: &E,
        pressure: Pressure<D>,
        molar_entropy: MolarEntropy<D>,
        feed: X,
        initial_temperature: Temperature,
        options: SolverOptions,
    ) -> FeosResult<Self> {
        PhaseEquilibrium::px_flash(
            eos,
            pressure,
            molar_entropy,
            feed,
            initial_temperature,
            options,
        )
    }

    // Generic implementation of ph and ps flashes.
    fn px_flash<X: Composition<D, N>, U: PXFlash>(
        eos: &E,
        pressure: Pressure<D>,
        specification: Quantity<D, U>,
        feed: X,
        initial_temperature: Temperature,
        options: SolverOptions,
    ) -> FeosResult<Self>
    where
        Quantity<D, U>: ReferenceSystem<Inner = D>,
        Quantity<Dual64, U>: ReferenceSystem<Inner = Dual64>,
    {
        let (max_iter, tol, verbosity) = options.unwrap_or(MAX_ITER_PX, TOL_PX);
        let (molefracs, total_moles) = feed.into_molefracs(eos)?;

        // initialize with a tp flash
        let eos_f64 = eos.re_total();
        let vle = PhaseEquilibrium::tp_flash(
            &eos_f64,
            initial_temperature,
            pressure.re(),
            molefracs.map(|x| x.re()),
            None,
            Default::default(),
            None,
        )?;

        // extract specifications
        let p = pressure.into_reduced().re();
        let hs = specification.into_reduced().re();
        let z = molefracs.map(|x| x.re());
        let specs = (p, hs, z.clone());

        // extract variables
        let t = initial_temperature.into_reduced();
        let beta = vle.vapor_phase_fraction();
        let rho_v = vle.vapor().density.into_reduced();
        let rho_l = vle.liquid().partial_density().into_reduced();
        let mut vars = stack![rho_l; vector![t, beta, rho_v]];
        let mut old_res = None;

        log_iter!(
            verbosity,
            " iter |  method  | temperature |    residual    |  phase I mole fractions  |  phase II mole fractions  "
        );
        log_iter!(verbosity, "{:-<102}", "");
        log_iter!(
            verbosity,
            " {:4} |          | {:9.5} |                | {:10.8?} | {:10.8?}",
            0,
            Temperature::from_reduced(t),
            (&rho_l / rho_l.sum() + (&z - &rho_l / rho_l.sum()) / beta).as_slice(),
            (&rho_l / rho_l.sum()).as_slice(),
        );

        // iterate
        for k in 0..max_iter {
            // always try a Newton step first
            let (grad, new_vars) = U::newton_step(&eos_f64, &vars, &specs)?;
            let new_res = grad.norm();
            let (method, res) = if let Some(r) = old_res
                && r < new_res
            {
                // if the residual is not reduced, reject the step and do a tp-flash instead
                vars = U::tp_step(&eos_f64, &vars, &specs)?;
                ("Tp-flash", None)
            } else {
                vars = new_vars;
                ("Newton", Some(new_res))
            };

            if let Verbosity::Iter = verbosity {
                let (t, _, _, _, x, y) = unpack_variables(&z, &vars);
                log_iter!(
                    verbosity,
                    " {:4} | {:^8} | {:9.5} | {} | {:10.8?} | {:10.8?}",
                    k + 1,
                    method,
                    Temperature::from_reduced(t),
                    res.map_or(String::from("              "), |r| format!("{r:14.8e}")),
                    y.as_slice(),
                    x.as_slice(),
                );
            }

            if let Some(res) = res
                && res < tol
            {
                log_result!(
                    verbosity,
                    "px flash: calculation converged in {} step(s)\n",
                    k + 1
                );

                // implicit differentiation
                let specs = (
                    pressure.into_reduced(),
                    specification.into_reduced(),
                    molefracs.clone(),
                );
                let vars = implicit_derivative_sp(
                    |variables, specifications| {
                        U::state_function(&eos.lift_total(), variables, specifications)
                    },
                    vars,
                    &specs,
                );
                let (t, beta, rho_l, rho_v, x, y) = unpack_variables(&molefracs, &vars);

                // store results in PhaseEquilibrium
                let liquid = State::new(
                    eos,
                    Temperature::from_reduced(t),
                    Density::from_reduced(rho_l),
                    x,
                )?;
                let vapor = State::new(
                    eos,
                    Temperature::from_reduced(t),
                    Density::from_reduced(rho_v),
                    y,
                )?;
                return Ok(PhaseEquilibrium::with_vapor_phase_fraction(
                    vapor,
                    liquid,
                    beta,
                    total_moles,
                ));
            }
            old_res = res;
        }
        Err(FeosError::NotConverged("px flash".to_owned()))
    }
}

fn unpack_variables<D: DualNum<f64> + Copy, N: Dim + DimAdd<U3>>(
    molefracs: &OVector<D, N>,
    variables: &OVector<D, PXVars<N>>,
) -> (D, D, D, D, OVector<D, N>, OVector<D, N>)
where
    DefaultAllocator: Allocator<N> + Allocator<PXVars<N>>,
{
    let n = molefracs.len();
    let rho_i_l = variables.rows_generic(0, N::from_usize(n)).clone_owned();
    let [[t, beta, rho_v]] = variables.rows_generic(n, U3).clone_owned().data.0;
    let rho_l = rho_i_l.sum();
    let x = rho_i_l / rho_l;
    let y = &x + (molefracs - &x) / beta;
    (t, beta, rho_l, rho_v, x, y)
}

fn unpack_tp_variables<D: DualNum<f64> + Copy, N: Dim + DimAdd<U2>>(
    molefracs: &OVector<D, N>,
    variables: &OVector<D, TPVars<N>>,
) -> (D, D, D, OVector<D, N>, OVector<D, N>)
where
    DefaultAllocator: Allocator<N> + Allocator<TPVars<N>>,
{
    let n = molefracs.len();
    let rho_i_l = variables.rows_generic(0, N::from_usize(n)).clone_owned();
    let [[beta, rho_v]] = variables.rows_generic(n, U2).clone_owned().data.0;
    let rho_l = rho_i_l.sum();
    let x = rho_i_l / rho_l;
    let y = &x + (molefracs - &x) / beta;
    (beta, rho_l, rho_v, x, y)
}

trait PXFlash: Sized + Copy {
    // potential function for which the flash solution is a saddle point.
    fn state_function<E: Total<N, D>, N: Dim + DimAdd<U3>, D: DualNum<f64> + Copy>(
        eos: &E,
        variables: OVector<D, PXVars<N>>,
        args: &(D, D, OVector<D, N>),
    ) -> D
    where
        DefaultAllocator: Allocator<N> + Allocator<PXVars<N>>;

    fn evaluate_property<E: Total<N, D>, N: Gradients, D: DualNum<f64> + Copy>(
        vle: &PhaseEquilibrium<E, 2, N, D>,
    ) -> Quantity<D, Self>
    where
        DefaultAllocator: Allocator<N>;

    // the potential function for a tp-flash specification (Q = A + V*p_spec)
    fn tp_state_function<E: Total<N, D>, N: Dim + DimAdd<U2>, D: DualNum<f64> + Copy>(
        eos: &E,
        variables: OVector<D, TPVars<N>>,
        &(t, p, ref z): &(D, D, OVector<D, N>),
    ) -> D
    where
        DefaultAllocator: Allocator<N> + Allocator<TPVars<N>>,
    {
        let (beta, rho_l, rho_v, x, y) = unpack_tp_variables(z, &variables);
        let potential = |molefracs, rho: D, t| {
            let v = rho.recip();
            let a_res = eos.residual_helmholtz_energy(t, v, &molefracs);
            let a_ig = eos.ideal_gas_molar_helmholtz_energy(t, v, &molefracs);
            a_res + a_ig + v * p
        };
        potential(y, rho_v, t) * beta + potential(x, rho_l, t) * (-beta + 1.0)
    }

    // An undamped Newton step for the gradients of the potential function.
    // Because the ps and ph flashes are saddle points rather then extrema,
    // the value of the potential can not be used as convergence criterion.
    #[expect(clippy::type_complexity)]
    fn newton_step<E: Total<N, D>, N: Dim + DimAdd<U3>, D: DualNum<f64> + Copy>(
        eos: &E,
        variables: &OVector<D, PXVars<N>>,
        specifications: &(D, D, OVector<D, N>),
    ) -> FeosResult<(OVector<D, PXVars<N>>, OVector<D, PXVars<N>>)>
    where
        DefaultAllocator: Allocator<N> + Allocator<PXVars<N>> + Allocator<PXVars<N>, PXVars<N>>,
        PXVars<N>: Gradients,
    {
        let (_, grad, hess) = PXVars::<N>::hessian(
            |variables, specifications| {
                Self::state_function(&eos.lift_total(), variables, specifications)
            },
            variables,
            specifications,
        );
        let dx = LU::new(hess)?.solve(&grad);
        Ok((grad, variables - &dx))
    }

    // A much slower but more robust step that calculates the implicit
    // derivative of the temperature only (which is well behaved
    // according to Michelsen) and then calculates all other variables
    // from a tp-flash.
    fn tp_step<E: Total<N, f64>, N: Gradients + DimAdd<U2> + DimAdd<U3>>(
        eos: &E,
        variables: &OVector<f64, PXVars<N>>,
        &(p, hs_spec, ref z): &(f64, f64, OVector<f64, N>),
    ) -> FeosResult<OVector<f64, PXVars<N>>>
    where
        Quantity<Dual64, Self>: ReferenceSystem<Inner = Dual64>,
        DefaultAllocator: Allocator<N>
            + Allocator<N, N>
            + Allocator<PXVars<N>>
            + Allocator<U1, TPVars<N>>
            + Allocator<TPVars<N>>
            + Allocator<TPVars<N>, TPVars<N>>,
        TPVars<N>: Gradients,
    {
        let (mut t, beta, rho_l, rho_v, x, y) = unpack_variables(z, variables);
        let rho_i_l = rho_l * x;
        let (hs, dhs) = first_derivative(
            partial(
                |t: Dual<_, _>, args: &(_, OVector<_, _>)| {
                    let &(p, ref z) = args;
                    let args = (t, p, z.clone_owned());

                    // implicit differentiation of the tp stationarity condition
                    // to obtain the derivative of the other variables w.r.t. t
                    let tp_vars = implicit_derivative_sp(
                        |variables, args| {
                            Self::tp_state_function(&eos.lift_total().lift_total(), variables, args)
                        },
                        stack![rho_i_l; vector![beta, rho_v]],
                        &args,
                    );
                    let (beta, rho_l, rho_v, x, y) = unpack_tp_variables(z, &tp_vars);

                    // Evaluation of the enthalpy/entropy including the derivatives.
                    let liquid = State::new(
                        &eos.lift_total(),
                        Temperature::from_reduced(t),
                        Density::from_reduced(rho_l),
                        x,
                    )?;
                    let vapor = State::new(
                        &eos.lift_total(),
                        Temperature::from_reduced(t),
                        Density::from_reduced(rho_v),
                        y,
                    )?;
                    Ok::<_, FeosError>(
                        Self::evaluate_property(&PhaseEquilibrium::with_vapor_phase_fraction(
                            vapor, liquid, beta, None,
                        ))
                        .into_reduced(),
                    )
                },
                &(p, z.clone_owned()),
            ),
            t,
        )?;

        // Newton step for the temperature
        t -= (hs - hs_spec) / dhs;

        // pack variables into PhaseEquilibrium for initial values
        let liquid = State::new_density(
            eos,
            Temperature::from_reduced(t),
            Density::from_reduced(rho_i_l),
        )?;
        let vapor = State::new(
            eos,
            Temperature::from_reduced(t),
            Density::from_reduced(rho_v),
            y,
        )?;
        let vle = PhaseEquilibrium::with_vapor_phase_fraction(vapor, liquid, beta, None);

        // tp-flash for all other variables
        let vle = PhaseEquilibrium::tp_flash(
            eos,
            Temperature::from_reduced(t),
            Pressure::from_reduced(p),
            z,
            Some(&vle),
            Default::default(),
            None,
        )?;
        let beta = vle.vapor_phase_fraction();
        let rho_v = vle.vapor().density.into_reduced();
        let rho_l = vle.liquid().partial_density().into_reduced();
        Ok(stack![rho_l; vector![t, beta, rho_v]])
    }
}

impl PXFlash for SIUnit<-2, 2, 1, 0, 0, -1, 0> {
    // the potential function for a ph-flash specification (Q = (A + V*p_spec - H_spec) / T)
    fn state_function<E: Total<N, D>, N: Dim + DimAdd<U3>, D: DualNum<f64> + Copy>(
        eos: &E,
        variables: OVector<D, PXVars<N>>,
        &(p, h, ref z): &(D, D, OVector<D, N>),
    ) -> D
    where
        DefaultAllocator: Allocator<N> + Allocator<PXVars<N>>,
    {
        let (t, beta, rho_l, rho_v, x, y) = unpack_variables(z, &variables);
        let potential = |molefracs, rho: D, t| {
            let v = rho.recip();
            let a_res = eos.residual_helmholtz_energy(t, v, &molefracs);
            let a_ig = eos.ideal_gas_molar_helmholtz_energy(t, v, &molefracs);
            (a_res + a_ig + v * p - h) / t
        };
        potential(y, rho_v, t) * beta + potential(x, rho_l, t) * (-beta + 1.0)
    }

    fn evaluate_property<E: Total<N, D>, N: Gradients, D: DualNum<f64> + Copy>(
        vle: &PhaseEquilibrium<E, 2, N, D>,
    ) -> Quantity<D, Self>
    where
        DefaultAllocator: Allocator<N>,
    {
        vle.molar_enthalpy()
    }
}

impl PXFlash for SIUnit<-2, 2, 1, 0, -1, -1, 0> {
    // the potential function for a ps-flash specification (Q = A + T*S_spec + V*p_spec)
    fn state_function<E: Total<N, D>, N: Dim + DimAdd<U3>, D: DualNum<f64> + Copy>(
        eos: &E,
        variables: OVector<D, PXVars<N>>,
        &(p, s, ref z): &(D, D, OVector<D, N>),
    ) -> D
    where
        DefaultAllocator: Allocator<N> + Allocator<PXVars<N>>,
    {
        let (t, beta, rho_l, rho_v, x, y) = unpack_variables(z, &variables);
        let potential = |molefracs, rho: D, t| {
            let v = rho.recip();
            let a_res = eos.residual_helmholtz_energy(t, v, &molefracs);
            let a_ig = eos.ideal_gas_molar_helmholtz_energy(t, v, &molefracs);
            // Division by t.re() is done to ensure that the state function has the same
            // units (and in conclusion same order of magnitude) as the ph state function.
            // This allows using the same toelrances for both methods.
            (a_res + a_ig + t * s + v * p) / t.re()
        };
        potential(y, rho_v, t) * beta + potential(x, rho_l, t) * (-beta + 1.0)
    }

    fn evaluate_property<E: Total<N, D>, N: Gradients, D: DualNum<f64> + Copy>(
        vle: &PhaseEquilibrium<E, 2, N, D>,
    ) -> Quantity<D, Self>
    where
        DefaultAllocator: Allocator<N>,
    {
        vle.molar_entropy()
    }
}