CoolProp 7.2.0
An open-source fluid property and humid air property database
FlashRoutines.cpp
Go to the documentation of this file.
1#include "VLERoutines.h"
2#include "FlashRoutines.h"
6#include "Configuration.h"
7
8#if defined(ENABLE_CATCH)
9# include <catch2/catch_all.hpp>
11#endif
12
13#include "boost/math/tools/toms748_solve.hpp"
14
15namespace CoolProp {
16
18 if (HEOS.PhaseEnvelope.built) {
19 // Use the phase envelope if already constructed to determine phase boundary
20 // Determine whether you are inside (two-phase) or outside (single-phase)
21 SimpleState closest_state;
22 std::size_t i;
23 bool twophase = PhaseEnvelopeRoutines::is_inside(HEOS.PhaseEnvelope, iP, HEOS._p, iT, HEOS._T, i, closest_state);
24 if (!twophase && HEOS._T > closest_state.T) {
25 // Gas solution - bounded between phase envelope temperature and very high temperature
26 //
27 // Start with a guess value from SRK
28 CoolPropDbl rhomolar_guess = HEOS.solver_rho_Tp_SRK(HEOS._T, HEOS._p, iphase_gas);
29
30 solver_TP_resid resid(HEOS, HEOS._T, HEOS._p);
31 std::string errstr;
33 try {
34 // Try using Newton's method
35 CoolPropDbl rhomolar = Newton(resid, rhomolar_guess, 1e-10, 100);
36 // Make sure the solution is within the bounds
37 if (!is_in_closed_range(static_cast<CoolPropDbl>(closest_state.rhomolar), static_cast<CoolPropDbl>(0.0), rhomolar)) {
38 throw ValueError("out of range");
39 }
40 HEOS.update_DmolarT_direct(rhomolar, HEOS._T);
41 } catch (...) {
42 // If that fails, try a bounded solver
43 CoolPropDbl rhomolar = Brent(resid, closest_state.rhomolar, 1e-10, DBL_EPSILON, 1e-10, 100);
44 // Make sure the solution is within the bounds
45 if (!is_in_closed_range(static_cast<CoolPropDbl>(closest_state.rhomolar), static_cast<CoolPropDbl>(0.0), rhomolar)) {
46 throw ValueError("out of range");
47 }
48 }
49 HEOS.unspecify_phase();
50 HEOS._Q = -1;
51 } else {
52 // Liquid solution
53 throw ValueError();
54 }
55 } else {
57 // Blind flash call
58 // Following the strategy of Gernert, 2014
60 if (!stability_tester.is_stable()) {
61 // There is a phase split and liquid and vapor phases are formed
62 CoolProp::SaturationSolvers::PTflash_twophase_options o;
63 stability_tester.get_liq(o.x, o.rhomolar_liq);
64 stability_tester.get_vap(o.y, o.rhomolar_vap);
65 o.z = HEOS.get_mole_fractions();
66 o.T = HEOS.T();
67 o.p = HEOS.p();
68 o.omega = 1.0;
69 CoolProp::SaturationSolvers::PTflash_twophase solver(HEOS, o);
70 solver.solve();
72 HEOS._Q = (o.z[0] - o.x[0]) / (o.y[0] - o.x[0]); // All vapor qualities are the same (these are the residuals in the solver)
73 HEOS._rhomolar = 1 / (HEOS._Q / HEOS.SatV->rhomolar() + (1 - HEOS._Q) / HEOS.SatL->rhomolar());
74 } else {
75 // It's single-phase
76 double rho = HEOS.solver_rho_Tp_global(HEOS.T(), HEOS.p(), 20000);
77 HEOS.update_DmolarT_direct(rho, HEOS.T());
78 HEOS._Q = -1;
79 HEOS._phase = iphase_liquid;
80 }
81 } else {
82 // It's single-phase, and phase is imposed
83 double rho = HEOS.solver_rho_Tp(HEOS.T(), HEOS.p());
84 HEOS.update_DmolarT_direct(rho, HEOS.T());
85 HEOS._Q = -1;
86 HEOS._phase = HEOS.imposed_phase_index;
87 }
88 }
89}
91 if (HEOS.is_pure_or_pseudopure) {
92 if (HEOS.imposed_phase_index == iphase_not_imposed) // If no phase index is imposed (see set_components function)
93 {
94 // At very low temperature (near the triple point temp), the isotherms are VERY steep
95 // Thus it can be very difficult to determine state based on ps = f(T)
96 // So in this case, we do a phase determination based on p, generally it will be useful enough
97 if (HEOS._T < 0.9 * HEOS.Ttriple() + 0.1 * HEOS.calc_Tmax_sat()) {
98 // Find the phase, while updating all internal variables possible using the pressure
99 bool saturation_called = false;
100 HEOS.p_phase_determination_pure_or_pseudopure(iT, HEOS._T, saturation_called);
101 } else {
102 // Find the phase, while updating all internal variables possible using the temperature
104 }
105 // Check if twophase solution
106 if (!HEOS.isHomogeneousPhase()) {
107 throw ValueError("twophase not implemented yet");
108 }
109 } else {
110 // Phase is imposed. Update _phase in case it was reset elsewhere by another call
111 HEOS._phase = HEOS.imposed_phase_index;
112 }
113 // Find density
114 HEOS._rhomolar = HEOS.solver_rho_Tp(HEOS._T, HEOS._p);
115 HEOS._Q = -1;
116 } else {
117 PT_flash_mixtures(HEOS);
118 }
119}
120
121// Define the residual to be driven to zero
123{
124 public:
128 double call(double T) {
130 CoolPropDbl peos = HEOS->p();
131 CoolPropDbl r = (peos - p) / p;
132 return r;
133 };
134 double deriv(double T) {
135 // dp/dT|rho / pspecified
136 return HEOS->first_partial_deriv(iP, iT, iDmolar) / p;
137 };
138 double second_deriv(double T) {
139 // d2p/dT2|rho / pspecified
141 };
142};
143
144/***
145\f[
146\begin{array}{l}
147p = \frac{{RT}}{{v - b}} - \frac{{a\alpha }}{{v\left( {v + b} \right)}}\\
148\alpha = \left( {1 + \kappa \left( {1 - \sqrt {{T_r}} } \right)} \right)\left( {1 + \kappa \left( {1 - \sqrt {{T_r}} } \right)} \right) = 1 + 2\kappa \left( {1 - \sqrt {{T_r}} } \right) + {\kappa ^2}{\left( {1 - \sqrt {{T_r}} } \right)^2}\\
149\alpha = 1 + 2\kappa \left( {1 - \sqrt {{T_r}} } \right) + {\kappa ^2}{\left( {1 - \sqrt {{T_r}} } \right)^2}\\
150\alpha = 1 + 2\kappa - 2\kappa \sqrt {{T_r}} + {\kappa ^2}\left[ {1 - 2\sqrt {{T_r}} + {T_r}} \right]\\
151T = {T_r}{T_c}\\
152p = \frac{{R{T_r}{T_c}}}{{v - b}} - \frac{{a\left( {1 + 2\kappa - 2\kappa \sqrt {{T_r}} + {\kappa ^2}\left[ {1 - 2\sqrt {{T_r}} + {T_r}} \right]} \right)}}{{v\left( {v + b} \right)}}\\
153\\
154{\rm{Factor in terms of }}\sqrt {{T_r}} \\
155\\
156p = \frac{{R{T_r}{T_c}}}{{v - b}} - \frac{{a\left( {1 + 2\kappa + {\kappa ^2} - 2\kappa \sqrt {{T_r}} + {\kappa ^2}\left[ { - 2\sqrt {{T_r}} + {T_r}} \right]} \right)}}{{v\left( {v + b} \right)}}\\
157p = \frac{{R{T_r}{T_c}}}{{v - b}} - \frac{{a\left( {1 + 2\kappa + {\kappa ^2} - 2\kappa (1 + \kappa )\sqrt {{T_r}} + {\kappa ^2}{T_r}} \right)}}{{v\left( {v + b} \right)}}\\
158p = \frac{{R{T_r}{T_c}}}{{v - b}} - \frac{{a\left( {1 + 2\kappa + {\kappa ^2}} \right)}}{{v\left( {v + b} \right)}} + \frac{{2a\kappa (1 + \kappa )}}{{v\left( {v + b} \right)}}\sqrt {{T_r}} - \frac{{a{\kappa ^2}}}{{v\left( {v + b} \right)}}{T_r}\\
1590 = \left[ {\frac{{R{T_c}}}{{v - b}} - \frac{{a{\kappa ^2}}}{{v\left( {v + b} \right)}}} \right]{T_r} + \frac{{2a\kappa (1 + \kappa )}}{{v\left( {v + b} \right)}}\sqrt {{T_r}} - \frac{{a\left( {1 + 2\kappa + {\kappa ^2}} \right)}}{{v\left( {v + b} \right)}} - p
160\end{array}
161\f]
162 */
163double FlashRoutines::T_DP_PengRobinson(HelmholtzEOSMixtureBackend& HEOS, double rhomolar, double p) {
164 double omega, R, kappa, a, b, A, B, C, Tc, pc, V = 1 / rhomolar;
165 omega = HEOS.acentric_factor();
166 Tc = HEOS.T_critical();
167 pc = HEOS.p_critical();
168 R = HEOS.gas_constant();
169
170 kappa = 0.37464 + 1.54226 * omega - 0.26992 * omega * omega;
171 a = 0.457235 * R * R * Tc * Tc / pc;
172 b = 0.077796 * R * Tc / pc;
173 double den = V * V + 2 * b * V - b * b;
174
175 // A sqrt(Tr)^2 + B sqrt(Tr) + C = 0
176 A = R * Tc / (V - b) - a * kappa * kappa / (den);
177 B = +2 * a * kappa * (1 + kappa) / (den);
178 C = -a * (1 + 2 * kappa + kappa * kappa) / (den)-p;
179
180 //D = B*B-4*A*C;
181
182 double sqrt_Tr1 = (-B + sqrt(B * B - 4 * A * C)) / (2 * A);
183 //double sqrt_Tr2 = (-B-sqrt(B*B-4*A*C))/(2*A);
184 return sqrt_Tr1 * sqrt_Tr1 * Tc;
185};
186
188 // Comment out the check for an imposed phase. There's no code to handle if it is!
189 // Solver below and flash calculations (if two phase) have to be called anyway.
190 //
191 // if (HEOS.imposed_phase_index == iphase_not_imposed) // If no phase index is imposed (see set_components function)
192 // {
193 if (HEOS.is_pure_or_pseudopure) {
194 // Find the phase, while updating all internal variables possible using the pressure
195 bool saturation_called = false;
196 HEOS.p_phase_determination_pure_or_pseudopure(iDmolar, HEOS._rhomolar, saturation_called);
197
198 if (HEOS.isHomogeneousPhase()) {
199 CoolPropDbl T0;
200 if (HEOS._phase == iphase_liquid) {
201 // If it is a liquid, start off at the ancillary value
202 if (saturation_called) {
203 T0 = HEOS.SatL->T();
204 } else {
205 T0 = HEOS._TLanc.pt();
206 }
207 } else if (HEOS._phase == iphase_supercritical_liquid) {
208 // If it is a supercritical
209 T0 = 1.1 * HEOS.T_critical();
210 } else if (HEOS._phase == iphase_gas || HEOS._phase == iphase_supercritical_gas || HEOS._phase == iphase_supercritical) {
211 // First, get a guess for density from Peng-Robinson
212 T0 = T_DP_PengRobinson(HEOS, HEOS.rhomolar(), HEOS.p());
213 } else {
214 throw ValueError("I should never get here");
215 }
216 if (!std::isfinite(T0)) {
217 throw ValueError("Starting value of T0 is not valid in DP_flash");
218 }
219 // Then, do the solver using the full EOS
220 solver_DP_resid resid(&HEOS, HEOS.rhomolar(), HEOS.p());
221 std::string errstr;
222 Halley(resid, T0, 1e-10, 100);
223 HEOS._Q = -1;
224 // Update the state for conditions where the state was guessed
226 if (!get_config_bool(DONT_CHECK_PROPERTY_LIMITS) && HEOS._T > 1.5 * HEOS.Tmax()) {
227 throw CoolProp::OutOfRangeError(format("DP yielded T > 1.5Tmax w/ T (%g) K").c_str());
228 }
229 } else {
230 // Nothing to do here; phase determination has handled this already
231 }
232 } else {
233 throw NotImplementedError("DP_flash not ready for mixtures");
234 }
235 // }
236 // TO DO: Put the imposed phase check back in
237 // and provide the else code here if it is imposed.
238}
239
241{
242 public:
246 double call(double T) {
247 HEOS.update(QT_INPUTS, 0, T); // Doesn't matter whether liquid or vapor, we are just doing a full VLE call for given T
251 return (1 / rhomolar - 1 / rhoL) / (1 / rhoV - 1 / rhoL) - Q_target;
252 }
253 double deriv(double T) {
254 return _HUGE;
255 }
256 double second_deriv(double T) {
257 return _HUGE;
258 }
259};
260
263 options.use_logdelta = false;
265 if (HEOS.is_pure_or_pseudopure) {
266 // Bump the temperatures to hopefully yield more reliable results
267 double Tmax = HEOS.T_critical() - 0.1;
268 double Tmin = HEOS.Tmin() + 0.1;
269 double rhomolar = HEOS._rhomolar;
270 double Q = HEOS._Q;
271 const double eps = 1e-12; // small tolerance to allow for slop in iterative calculations
272 if (rhomolar >= (HEOS.rhomolar_critical() + eps) && Q > (0 + eps)) {
274 format("DQ inputs are not defined for density (%g) above critical density (%g) and Q>0", rhomolar, HEOS.rhomolar_critical()).c_str());
275 }
276 DQ_flash_residual resid(HEOS, rhomolar, Q);
277 Brent(resid, Tmin, Tmax, DBL_EPSILON, 1e-10, 100);
278 HEOS._p = HEOS.SatV->p();
279 HEOS._T = HEOS.SatV->T();
280 HEOS._rhomolar = rhomolar;
281 HEOS._Q = Q;
282 HEOS._phase = iphase_twophase;
283 } else {
284 throw NotImplementedError("DQ_flash not ready for mixtures");
285 }
286}
289 options.use_logdelta = false;
291 if (Tguess < 0) {
292 options.use_guesses = true;
293 options.T = Tguess;
294 CoolProp::SaturationAncillaryFunction& rhoL = HEOS.get_components()[0].ancillaries.rhoL;
295 CoolProp::SaturationAncillaryFunction& rhoV = HEOS.get_components()[0].ancillaries.rhoV;
296 options.rhoL = rhoL.evaluate(Tguess);
297 options.rhoV = rhoV.evaluate(Tguess);
298 }
299 if (HEOS.is_pure_or_pseudopure) {
300 if (std::abs(HEOS.Q() - 1) > 1e-10) {
301 throw ValueError(format("non-unity quality not currently allowed for HQ_flash"));
302 }
303 // Do a saturation call for given h for vapor, first with ancillaries, then with full saturation call
305 SaturationSolvers::saturation_PHSU_pure(HEOS, HEOS.hmolar(), options);
306 HEOS._p = HEOS.SatV->p();
307 HEOS._T = HEOS.SatV->T();
308 HEOS._rhomolar = HEOS.SatV->rhomolar();
309 HEOS._phase = iphase_twophase;
310 } else {
311 throw NotImplementedError("HQ_flash not ready for mixtures");
312 }
313}
315 if (HEOS.is_pure_or_pseudopure) {
316
317 if (std::abs(HEOS.smolar() - HEOS.get_state("reducing").smolar) < 0.001) {
318 HEOS._p = HEOS.p_critical();
319 HEOS._T = HEOS.T_critical();
320 HEOS._rhomolar = HEOS.rhomolar_critical();
322 } else if (std::abs(HEOS.Q()) < 1e-10) {
323 // Do a saturation call for given s for liquid, first with ancillaries, then with full saturation call
326 options.use_logdelta = false;
328 SaturationSolvers::saturation_PHSU_pure(HEOS, HEOS.smolar(), options);
329 HEOS._p = HEOS.SatL->p();
330 HEOS._T = HEOS.SatL->T();
331 HEOS._rhomolar = HEOS.SatL->rhomolar();
332 HEOS._phase = iphase_twophase;
333 } else if (std::abs(HEOS.Q() - 1) < 1e-10) {
334 // Do a saturation call for given s for vapor, first with ancillaries, then with full saturation call
337 options.use_logdelta = false;
339 SaturationSolvers::saturation_PHSU_pure(HEOS, HEOS.smolar(), options);
340 HEOS._p = HEOS.SatV->p();
341 HEOS._T = HEOS.SatV->T();
342 HEOS._rhomolar = HEOS.SatV->rhomolar();
343 HEOS._phase = iphase_twophase;
344 } else {
345 throw ValueError(format("non-zero or 1 quality not currently allowed for QS_flash"));
346 }
347 } else {
348 throw NotImplementedError("QS_flash not ready for mixtures");
349 }
350}
352 CoolPropDbl T = HEOS._T;
353 CoolPropDbl Q = HEOS._Q;
354 if (HEOS.is_pure_or_pseudopure) {
355
356 if (get_config_bool(ENABLE_SUPERANCILLARIES) && HEOS.is_pure()) {
357 auto& optsuperanc = HEOS.get_superanc_optional();
358 if (optsuperanc) {
359 auto& superanc = optsuperanc.value();
360
361 CoolPropDbl Tcrit_num = superanc.get_Tcrit_num();
362 if (T > Tcrit_num) {
363 throw ValueError(
364 format("Temperature to QT_flash [%0.8Lg K] may not be above the numerical critical point of %0.15Lg K", T, Tcrit_num));
365 }
366 auto rhoL = superanc.eval_sat(T, 'D', 0);
367 auto rhoV = superanc.eval_sat(T, 'D', 1);
368 auto p = superanc.eval_sat(T, 'P', 1);
369 HEOS.SatL->update_TDmolarP_unchecked(T, rhoL, p);
370 HEOS.SatV->update_TDmolarP_unchecked(T, rhoV, p);
371 HEOS._p = p;
372 HEOS._rhomolar = 1 / (Q / rhoV + (1 - Q) / rhoL);
373 HEOS._phase = iphase_twophase;
374 return;
375 }
376 }
377
378 // The maximum possible saturation temperature
379 // Critical point for pure fluids, slightly different for pseudo-pure, very different for mixtures
380 CoolPropDbl Tmax_sat = HEOS.calc_Tmax_sat() + 1e-13;
381
382 // Check what the minimum limits for the equation of state are
383 CoolPropDbl Tmin_satL, Tmin_satV, Tmin_sat;
384 HEOS.calc_Tmin_sat(Tmin_satL, Tmin_satV);
385 Tmin_sat = std::max(Tmin_satL, Tmin_satV) - 1e-13;
386
387 // Get a reference to keep the code a bit cleaner
388 const CriticalRegionSplines& splines = HEOS.components[0].EOS().critical_region_splines;
389
390 if ((get_config_bool(CRITICAL_WITHIN_1UK) && std::abs(T - Tmax_sat) < 1e-6) || std::abs(T - Tmax_sat) < 1e-12) {
391 // If exactly(ish) at the critical temperature, liquid and vapor have the critial density
392 HEOS.SatL->update(DmolarT_INPUTS, HEOS.rhomolar_critical(), HEOS._T);
393 HEOS.SatV->update(DmolarT_INPUTS, HEOS.rhomolar_critical(), HEOS._T);
394 HEOS._rhomolar = HEOS.rhomolar_critical();
395 HEOS._p = 0.5 * HEOS.SatV->p() + 0.5 * HEOS.SatL->p();
396 } else if (!is_in_closed_range(Tmin_sat - 0.1, Tmax_sat, T) && (CoolProp::get_config_bool(DONT_CHECK_PROPERTY_LIMITS) == false)) {
397 throw ValueError(format("Temperature to QT_flash [%0.8Lg K] must be in range [%0.8Lg K, %0.8Lg K]", T, Tmin_sat - 0.1, Tmax_sat));
398 } else if (get_config_bool(CRITICAL_SPLINES_ENABLED) && splines.enabled && HEOS._T > splines.T_min) {
399 double rhoL = _HUGE, rhoV = _HUGE;
400 // Use critical region spline if it has it and temperature is in its range
401 splines.get_densities(T, splines.rhomolar_min, HEOS.rhomolar_critical(), splines.rhomolar_max, rhoL, rhoV);
402 HEOS.SatL->update(DmolarT_INPUTS, rhoL, HEOS._T);
403 HEOS.SatV->update(DmolarT_INPUTS, rhoV, HEOS._T);
404 HEOS._p = 0.5 * HEOS.SatV->p() + 0.5 * HEOS.SatL->p();
405 HEOS._rhomolar = 1 / (HEOS._Q / HEOS.SatV->rhomolar() + (1 - HEOS._Q) / HEOS.SatL->rhomolar());
406 } else if (!(HEOS.components[0].EOS().pseudo_pure)) {
407 // Set some input options
409
410 // Actually call the solver
412
413 HEOS._p = 0.5 * HEOS.SatV->p() + 0.5 * HEOS.SatL->p();
414 HEOS._rhomolar = 1 / (HEOS._Q / HEOS.SatV->rhomolar() + (1 - HEOS._Q) / HEOS.SatL->rhomolar());
415 } else {
416 // Pseudo-pure fluid
417 CoolPropDbl rhoLanc = _HUGE, rhoVanc = _HUGE, rhoLsat = _HUGE, rhoVsat = _HUGE;
418 if (std::abs(HEOS._Q) < DBL_EPSILON) {
419 HEOS._p = HEOS.components[0].ancillaries.pL.evaluate(HEOS._T); // These ancillaries are used explicitly
420 rhoLanc = HEOS.components[0].ancillaries.rhoL.evaluate(HEOS._T);
421 HEOS.SatL->update_TP_guessrho(HEOS._T, HEOS._p, rhoLanc);
422 HEOS._rhomolar = HEOS.SatL->rhomolar();
423 } else if (std::abs(HEOS._Q - 1) < DBL_EPSILON) {
424 HEOS._p = HEOS.components[0].ancillaries.pV.evaluate(HEOS._T); // These ancillaries are used explicitly
425 rhoVanc = HEOS.components[0].ancillaries.rhoV.evaluate(HEOS._T);
426 HEOS.SatV->update_TP_guessrho(HEOS._T, HEOS._p, rhoVanc);
427 HEOS._rhomolar = HEOS.SatV->rhomolar();
428 } else {
429 throw CoolProp::ValueError(format("For pseudo-pure fluid, quality must be equal to 0 or 1. Two-phase quality is not defined"));
430 }
431
432 try {
433 } catch (...) {
434 // Near the critical point, the behavior is not very nice, so we will just use the ancillary
435 rhoLsat = rhoLanc;
436 rhoVsat = rhoVanc;
437 }
438 }
439 // Load the outputs
440 HEOS._phase = iphase_twophase;
441 } else {
442 if (HEOS.PhaseEnvelope.built) {
443 PT_Q_flash_mixtures(HEOS, iT, HEOS._T);
444 } else {
445 // Set some input options
448 options.Nstep_max = 20;
449
450 // Get an extremely rough guess by interpolation of ln(p) v. T curve where the limits are mole-fraction-weighted
452
453 // Use Wilson iteration to obtain updated guess for pressure
454 pguess = SaturationSolvers::saturation_Wilson(HEOS, HEOS._Q, HEOS._T, SaturationSolvers::imposed_T, HEOS.mole_fractions, pguess);
455
456 // Actually call the successive substitution solver
457 SaturationSolvers::successive_substitution(HEOS, HEOS._Q, HEOS._T, pguess, HEOS.mole_fractions, HEOS.K, options);
458
459 // -----
460 // Newton-Raphson
461 // -----
462
463 SaturationSolvers::newton_raphson_saturation NR;
464 SaturationSolvers::newton_raphson_saturation_options IO;
465
466 IO.bubble_point = (HEOS._Q < 0.5);
467
468 IO.x = options.x;
469 IO.y = options.y;
470 IO.rhomolar_liq = options.rhomolar_liq;
471 IO.rhomolar_vap = options.rhomolar_vap;
472 IO.T = options.T;
473 IO.p = options.p;
474 IO.Nstep_max = 30;
475
476 IO.imposed_variable = SaturationSolvers::newton_raphson_saturation_options::T_IMPOSED;
477
478 if (IO.bubble_point) {
479 // Compositions are z, z_incipient
480 NR.call(HEOS, IO.x, IO.y, IO);
481 } else {
482 // Compositions are z, z_incipient
483 NR.call(HEOS, IO.y, IO.x, IO);
484 }
485
486 HEOS._p = IO.p;
487 HEOS._rhomolar = 1 / (HEOS._Q / IO.rhomolar_vap + (1 - HEOS._Q) / IO.rhomolar_liq);
488 }
489 // Load the outputs
490 HEOS._phase = iphase_twophase;
491 HEOS._p = HEOS.SatV->p();
492 HEOS._rhomolar = 1 / (HEOS._Q / HEOS.SatV->rhomolar() + (1 - HEOS._Q) / HEOS.SatL->rhomolar());
493 HEOS._T = HEOS.SatL->T();
494 }
495}
496
497void get_Henrys_coeffs_FP(const std::string& CAS, double& A, double& B, double& C, double& Tmin, double& Tmax) {
498 // Coeffs from Fernandez-Prini JPCRD 2003 DOI: 10.1063/1.1564818
499 if (CAS == "7440-59-7") //Helium
500 {
501 A = -3.52839;
502 B = 7.12983;
503 C = 4.47770;
504 Tmin = 273.21;
505 Tmax = 553.18;
506 } else if (CAS == "7440-01-9") // Ne
507 {
508 A = -3.18301;
509 B = 5.31448;
510 C = 5.43774;
511 Tmin = 273.20;
512 Tmax = 543.36;
513 } else if (CAS == "7440-37-1") // Ar
514 {
515 A = -8.40954;
516 B = 4.29587;
517 C = 10.52779;
518 Tmin = 273.19;
519 Tmax = 568.36;
520 } else if (CAS == "7439-90-9") // Kr
521 {
522 A = -8.97358;
523 B = 3.61508;
524 C = 11.29963;
525 Tmin = 273.19;
526 Tmax = 525.56;
527 } else if (CAS == "7440-63-3") // Xe
528 {
529 A = -14.21635;
530 B = 4.00041;
531 C = 15.60999;
532 Tmin = 273.22;
533 Tmax = 574.85;
534 } else if (CAS == "1333-74-0") // H2
535 {
536 A = -4.73284;
537 B = 6.08954;
538 C = 6.06066;
539 Tmin = 273.15;
540 Tmax = 636.09;
541 } else if (CAS == "7727-37-9") // N2
542 {
543 A = -9.67578;
544 B = 4.72162;
545 C = 11.70585;
546 Tmin = 278.12;
547 Tmax = 636.46;
548 } else if (CAS == "7782-44-7") // O2
549 {
550 A = -9.44833;
551 B = 4.43822;
552 C = 11.42005;
553 Tmin = 274.15;
554 Tmax = 616.52;
555 } else if (CAS == "630-08-0") // CO
556 {
557 A = -10.52862;
558 B = 5.13259;
559 C = 12.01421;
560 Tmin = 278.15;
561 Tmax = 588.67;
562 } else if (CAS == "124-38-9") // CO2
563 {
564 A = -8.55445;
565 B = 4.01195;
566 C = 9.52345;
567 Tmin = 274.19;
568 Tmax = 642.66;
569 } else if (CAS == "7783-06-4") // H2S
570 {
571 A = -4.51499;
572 B = 5.23538;
573 C = 4.42126;
574 Tmin = 273.15;
575 Tmax = 533.09;
576 } else if (CAS == "74-82-8") // CH4
577 {
578 A = -10.44708;
579 B = 4.66491;
580 C = 12.12986;
581 Tmin = 275.46;
582 Tmax = 633.11;
583 } else if (CAS == "74-84-0") // C2H6
584 {
585 A = -19.67563;
586 B = 4.51222;
587 C = 20.62567;
588 Tmin = 275.44;
589 Tmax = 473.46;
590 } else if (CAS == "2551-62-4") // SF6
591 {
592 A = -16.56118;
593 B = 2.15289;
594 C = 20.35440;
595 Tmin = 283.14;
596 Tmax = 505.55;
597 } else {
598 throw ValueError("Bad component in Henry's law constants");
599 }
600}
602 if (HEOS.is_pure_or_pseudopure) {
603
604 if (get_config_bool(ENABLE_SUPERANCILLARIES) && HEOS.is_pure()) {
605 auto& optsuperanc = HEOS.get_superanc_optional();
606 if (optsuperanc) {
607 auto& superanc = optsuperanc.value();
608 CoolPropDbl pmax_num = superanc.get_pmax();
609 if (HEOS._p > pmax_num) {
610 throw ValueError(
611 format("Pressure to PQ_flash [%0.8Lg Pa] may not be above the numerical critical point of %0.15Lg Pa", HEOS._p, pmax_num));
612 }
613 auto T = superanc.get_T_from_p(HEOS._p);
614 auto rhoL = superanc.eval_sat(T, 'D', 0);
615 auto rhoV = superanc.eval_sat(T, 'D', 1);
616 auto p = HEOS._p;
617 HEOS.SatL->update_TDmolarP_unchecked(T, rhoL, p);
618 HEOS.SatV->update_TDmolarP_unchecked(T, rhoV, p);
619 HEOS._T = T;
620 HEOS._p = p;
621 HEOS._rhomolar = 1 / (HEOS._Q / HEOS.SatV->rhomolar() + (1 - HEOS._Q) / HEOS.SatL->rhomolar());
622 HEOS._phase = iphase_twophase;
623 return;
624 }
625 }
626
627 if (HEOS.components[0].EOS().pseudo_pure) {
628 // It is a pseudo-pure mixture
629
630 HEOS._TLanc = HEOS.components[0].ancillaries.pL.invert(HEOS._p);
631 HEOS._TVanc = HEOS.components[0].ancillaries.pV.invert(HEOS._p);
632 // Get guesses for the ancillaries for density
633 CoolPropDbl rhoL = HEOS.components[0].ancillaries.rhoL.evaluate(HEOS._TLanc);
634 CoolPropDbl rhoV = HEOS.components[0].ancillaries.rhoV.evaluate(HEOS._TVanc);
635 // Solve for the density
636 HEOS.SatL->update_TP_guessrho(HEOS._TLanc, HEOS._p, rhoL);
637 HEOS.SatV->update_TP_guessrho(HEOS._TVanc, HEOS._p, rhoV);
638
639 // Load the outputs
640 HEOS._phase = iphase_twophase;
641 HEOS._p = HEOS._Q * HEOS.SatV->p() + (1 - HEOS._Q) * HEOS.SatL->p();
642 HEOS._T = HEOS._Q * HEOS.SatV->T() + (1 - HEOS._Q) * HEOS.SatL->T();
643 HEOS._rhomolar = 1 / (HEOS._Q / HEOS.SatV->rhomolar() + (1 - HEOS._Q) / HEOS.SatL->rhomolar());
644 } else {
645 // Critical point for pure fluids, slightly different for pseudo-pure, very different for mixtures
646 CoolPropDbl pmax_sat = HEOS.calc_pmax_sat();
647
648 // Check what the minimum limits for the equation of state are
649 CoolPropDbl pmin_satL, pmin_satV, pmin_sat;
650 HEOS.calc_pmin_sat(pmin_satL, pmin_satV);
651 pmin_sat = std::max(pmin_satL, pmin_satV);
652
653 // Check for being AT the critical point
654 if (is_in_closed_range(pmax_sat * (1 - 1e-10), pmax_sat * (1 + 1e-10), static_cast<CoolPropDbl>(HEOS._p))) {
655 // Load the outputs
657 HEOS._p = HEOS.p_critical();
658 HEOS._rhomolar = HEOS.rhomolar_critical();
659 HEOS._T = HEOS.T_critical();
660 return;
661 }
662
663 // Check limits
664 if (CoolProp::get_config_bool(DONT_CHECK_PROPERTY_LIMITS) == false) {
665 if (!is_in_closed_range(pmin_sat * 0.999999, pmax_sat * 1.000001, static_cast<CoolPropDbl>(HEOS._p))) {
666 throw ValueError(format("Pressure to PQ_flash [%6g Pa] must be in range [%8Lg Pa, %8Lg Pa]", HEOS._p, pmin_sat, pmax_sat));
667 }
668 }
669 // ------------------
670 // It is a pure fluid
671 // ------------------
672
673 // Set some input options
675 // Specified variable is pressure
677 // Use logarithm of delta as independent variables
678 options.use_logdelta = false;
679
680 double increment = 0.4;
681
682 try {
683 for (double omega = 1.0; omega > 0; omega -= increment) {
684 try {
685 options.omega = omega;
686
687 // Actually call the solver
688 SaturationSolvers::saturation_PHSU_pure(HEOS, HEOS._p, options);
689
690 // If you get here, there was no error, all is well
691 break;
692 } catch (...) {
693 if (omega < 1.1 * increment) {
694 throw;
695 }
696 // else we are going to try again with a smaller omega
697 }
698 }
699 } catch (...) {
700 // We may need to polish the solution at low pressure
702 }
703
704 // Load the outputs
705 HEOS._phase = iphase_twophase;
706 HEOS._p = HEOS._Q * HEOS.SatV->p() + (1 - HEOS._Q) * HEOS.SatL->p();
707 HEOS._rhomolar = 1 / (HEOS._Q / HEOS.SatV->rhomolar() + (1 - HEOS._Q) / HEOS.SatL->rhomolar());
708 HEOS._T = HEOS.SatL->T();
709 }
710 } else {
711 if (HEOS.PhaseEnvelope.built) {
712 PT_Q_flash_mixtures(HEOS, iP, HEOS._p);
713 } else {
714
715 // Set some input options
718 io.Nstep_max = 10;
719
720 // Get an extremely rough guess by interpolation of ln(p) v. T curve where the limits are mole-fraction-weighted
722
723 // Use Wilson iteration to obtain updated guess for temperature
724 Tguess = SaturationSolvers::saturation_Wilson(HEOS, HEOS._Q, HEOS._p, SaturationSolvers::imposed_p, HEOS.mole_fractions, Tguess);
725
726 std::vector<CoolPropDbl> K = HEOS.K;
727
728 if (get_config_bool(HENRYS_LAW_TO_GENERATE_VLE_GUESSES) && std::abs(HEOS._Q - 1) < 1e-10) {
729 const std::vector<CoolPropFluid>& components = HEOS.get_components();
730 std::size_t iWater = 0;
731 double p1star = PropsSI("P", "T", Tguess, "Q", 1, "Water");
732 const std::vector<CoolPropDbl> y = HEOS.mole_fractions;
733 std::vector<CoolPropDbl> x(y.size());
734 for (std::size_t i = 0; i < components.size(); ++i) {
735 if (components[i].CAS == "7732-18-5") {
736 iWater = i;
737 continue;
738 } else {
739 double A, B, C, Tmin, Tmax;
740 get_Henrys_coeffs_FP(components[i].CAS, A, B, C, Tmin, Tmax);
741 double T_R = Tguess / 647.096, tau = 1 - T_R;
742 double k_H = p1star * exp(A / T_R + B * pow(tau, 0.355) / T_R + C * pow(T_R, -0.41) * exp(tau));
743 x[i] = y[i] * HEOS._p / k_H;
744 //
745 K[i] = y[i] / x[i];
746 }
747 }
748 // Update water K factor
749 double summer = 0;
750 for (std::size_t i = 0; i < y.size(); ++i) {
751 if (i != iWater) {
752 summer += x[i];
753 }
754 }
755 x[iWater] = summer;
756 K[iWater] = y[iWater] / x[iWater];
757 }
758
759 // Actually call the successive substitution solver
760 SaturationSolvers::successive_substitution(HEOS, HEOS._Q, Tguess, HEOS._p, HEOS.mole_fractions, K, io);
761
762 // -----
763 // Newton-Raphson
764 // -----
765
766 SaturationSolvers::newton_raphson_saturation NR;
767 SaturationSolvers::newton_raphson_saturation_options IO;
768
769 IO.bubble_point = (HEOS._Q < 0.5);
770 IO.x = io.x;
771 IO.y = io.y;
772 IO.rhomolar_liq = io.rhomolar_liq;
773 IO.rhomolar_vap = io.rhomolar_vap;
774 IO.T = io.T;
775 IO.p = io.p;
776 IO.Nstep_max = 30;
777 IO.imposed_variable = SaturationSolvers::newton_raphson_saturation_options::P_IMPOSED;
778
779 if (IO.bubble_point) {
780 // Compositions are z, z_incipient
781 NR.call(HEOS, IO.x, IO.y, IO);
782 } else {
783 // Compositions are z, z_incipient
784 NR.call(HEOS, IO.y, IO.x, IO);
785 }
786 }
787
788 // Load the outputs
789 HEOS._phase = iphase_twophase;
790 HEOS._p = HEOS.SatV->p();
791 HEOS._rhomolar = 1 / (HEOS._Q / HEOS.SatV->rhomolar() + (1 - HEOS._Q) / HEOS.SatL->rhomolar());
792 HEOS._T = HEOS.SatL->T();
793 }
794}
795
797 SaturationSolvers::newton_raphson_saturation NR;
798 SaturationSolvers::newton_raphson_saturation_options IO;
799 IO.rhomolar_liq = guess.rhomolar_liq;
800 IO.rhomolar_vap = guess.rhomolar_vap;
801 IO.x = std::vector<CoolPropDbl>(guess.x.begin(), guess.x.end());
802 IO.y = std::vector<CoolPropDbl>(guess.y.begin(), guess.y.end());
803 IO.T = guess.T;
804 IO.p = HEOS._p;
805 IO.bubble_point = false;
806 IO.imposed_variable = SaturationSolvers::newton_raphson_saturation_options::P_IMPOSED;
807
808 if (std::abs(HEOS.Q()) < 1e-10) {
809 IO.bubble_point = true;
810 NR.call(HEOS, IO.x, IO.y, IO);
811 } else if (std::abs(HEOS.Q() - 1) < 1e-10) {
812 IO.bubble_point = false;
813 NR.call(HEOS, IO.y, IO.x, IO);
814 } else {
815 throw ValueError(format("Quality must be 0 or 1"));
816 }
817
818 // Load the other outputs
819 HEOS._phase = iphase_twophase;
820 HEOS._rhomolar = 1 / (HEOS._Q / IO.rhomolar_vap + (1 - HEOS._Q) / IO.rhomolar_liq);
821 HEOS._T = IO.T;
822}
824 SaturationSolvers::newton_raphson_saturation NR;
825 SaturationSolvers::newton_raphson_saturation_options IO;
826 IO.rhomolar_liq = guess.rhomolar_liq;
827 IO.rhomolar_vap = guess.rhomolar_vap;
828 IO.x = std::vector<CoolPropDbl>(guess.x.begin(), guess.x.end());
829 IO.y = std::vector<CoolPropDbl>(guess.y.begin(), guess.y.end());
830 IO.T = HEOS._T;
831 IO.p = guess.p;
832 IO.bubble_point = false;
833 IO.imposed_variable = SaturationSolvers::newton_raphson_saturation_options::T_IMPOSED;
834
835 if (get_debug_level() > 9) {
836 std::cout << format(" QT w/ guess p %g T %g dl %g dv %g x %s y %s\n", IO.p, IO.T, IO.rhomolar_liq, IO.rhomolar_vap,
837 vec_to_string(IO.x, "%g").c_str(), vec_to_string(IO.y, "%g").c_str());
838 }
839
840 if (std::abs(HEOS.Q()) < 1e-10) {
841 IO.bubble_point = true;
842 NR.call(HEOS, IO.x, IO.y, IO);
843 } else if (std::abs(HEOS.Q() - 1) < 1e-10) {
844 IO.bubble_point = false;
845 NR.call(HEOS, IO.y, IO.x, IO);
846 } else {
847 throw ValueError(format("Quality must be 0 or 1"));
848 }
849
850 // Load the other outputs
851 HEOS._p = IO.p;
852 HEOS._phase = iphase_twophase;
853 HEOS._rhomolar = 1 / (HEOS._Q / IO.rhomolar_vap + (1 - HEOS._Q) / IO.rhomolar_liq);
854}
855
857 HEOS.solver_rho_Tp(HEOS.T(), HEOS.p(), guess.rhomolar);
858 // Load the other outputs
859 HEOS._phase = iphase_gas; // Guessed for mixtures
860 if (HEOS.is_pure_or_pseudopure) {
861 if (HEOS._p > HEOS.p_critical()) {
862 if (HEOS._T > HEOS.T_critical()) {
864 } else {
866 }
867 } else {
868 if (HEOS._T > HEOS.T_critical()) {
870 } else if (HEOS._rhomolar > HEOS.rhomolar_critical()) {
871 HEOS._phase = iphase_liquid;
872 } else {
873 HEOS._phase = iphase_gas;
874 }
875 }
876 }
877
878 HEOS._Q = -1;
879}
880
882
883 // Find the intersections in the phase envelope
884 std::vector<std::pair<std::size_t, std::size_t>> intersections =
886
888
889 enum quality_options
890 {
891 SATURATED_LIQUID,
892 SATURATED_VAPOR,
893 TWO_PHASE
894 };
895 quality_options quality;
896 if (std::abs(HEOS._Q) < 100 * DBL_EPSILON) {
897 quality = SATURATED_LIQUID;
898 } else if (std::abs(HEOS._Q - 1) < 100 * DBL_EPSILON) {
899 quality = SATURATED_VAPOR;
900 } else if (HEOS._Q > 0 && HEOS._Q < 1) {
901 quality = TWO_PHASE;
902 } else {
903 throw ValueError("Quality is not within 0 and 1");
904 }
905
906 if (quality == SATURATED_LIQUID || quality == SATURATED_VAPOR) {
907 // *********************************************************
908 // Bubble- or dew-point calculation
909 // *********************************************************
910 // Find the correct solution
911 std::vector<std::size_t> solutions;
912 for (std::vector<std::pair<std::size_t, std::size_t>>::const_iterator it = intersections.begin(); it != intersections.end(); ++it) {
913 if (std::abs(env.Q[it->first] - HEOS._Q) < 10 * DBL_EPSILON && std::abs(env.Q[it->second] - HEOS._Q) < 10 * DBL_EPSILON) {
914 solutions.push_back(it->first);
915 }
916 }
917
918 if (solutions.size() == 1) {
919
920 std::size_t& imax = solutions[0];
921
922 // Shift the solution if needed to ensure that imax+2 and imax-1 are both in range
923 if (imax + 2 >= env.T.size()) {
924 imax--;
925 } else if (imax == 0) {
926 imax++;
927 }
928 // Here imax+2 or imax-1 is still possibly out of range:
929 // 1. If imax initially is 1, and env.T.size() <= 3, then imax will become 0.
930 // 2. If imax initially is 0, and env.T.size() <= 2, then imax will become MAX_UINT.
931 // 3. If imax+2 initially is more than env.T.size(), then single decrement will not bring it to range
932
933 SaturationSolvers::newton_raphson_saturation NR;
934 SaturationSolvers::newton_raphson_saturation_options IO;
935
936 if (other == iP) {
937 IO.p = HEOS._p;
938 IO.imposed_variable = SaturationSolvers::newton_raphson_saturation_options::P_IMPOSED;
939 // p -> rhomolar_vap
940 IO.rhomolar_vap = CubicInterp(env.p, env.rhomolar_vap, imax - 1, imax, imax + 1, imax + 2, static_cast<CoolPropDbl>(IO.p));
941 IO.T = CubicInterp(env.rhomolar_vap, env.T, imax - 1, imax, imax + 1, imax + 2, IO.rhomolar_vap);
942 } else if (other == iT) {
943 IO.T = HEOS._T;
944 IO.imposed_variable = SaturationSolvers::newton_raphson_saturation_options::T_IMPOSED;
945 // T -> rhomolar_vap
946 IO.rhomolar_vap = CubicInterp(env.T, env.rhomolar_vap, imax - 1, imax, imax + 1, imax + 2, static_cast<CoolPropDbl>(IO.T));
947 IO.p = CubicInterp(env.rhomolar_vap, env.p, imax - 1, imax, imax + 1, imax + 2, IO.rhomolar_vap);
948 } else {
949 throw ValueError();
950 }
951 IO.rhomolar_liq = CubicInterp(env.rhomolar_vap, env.rhomolar_liq, imax - 1, imax, imax + 1, imax + 2, IO.rhomolar_vap);
952
953 if (quality == SATURATED_VAPOR) {
954 IO.bubble_point = false;
955 IO.y = HEOS.get_mole_fractions(); // Because Q = 1
956 IO.x.resize(IO.y.size());
957 for (std::size_t i = 0; i < IO.x.size() - 1; ++i) // First N-1 elements
958 {
959 IO.x[i] = CubicInterp(env.rhomolar_vap, env.x[i], imax - 1, imax, imax + 1, imax + 2, IO.rhomolar_vap);
960 }
961 IO.x[IO.x.size() - 1] = 1 - std::accumulate(IO.x.begin(), IO.x.end() - 1, 0.0);
962 NR.call(HEOS, IO.y, IO.x, IO);
963 } else {
964 IO.bubble_point = true;
965 IO.x = HEOS.get_mole_fractions(); // Because Q = 0
966 IO.y.resize(IO.x.size());
967 // Phases are inverted, so "liquid" is actually the lighter phase
968 std::swap(IO.rhomolar_liq, IO.rhomolar_vap);
969 for (std::size_t i = 0; i < IO.y.size() - 1; ++i) // First N-1 elements
970 {
971 // Phases are inverted, so liquid mole fraction (x) of phase envelope is actually the vapor phase mole fraction
972 // Use the liquid density as well
973 IO.y[i] = CubicInterp(env.rhomolar_vap, env.x[i], imax - 1, imax, imax + 1, imax + 2, IO.rhomolar_liq);
974 }
975 IO.y[IO.y.size() - 1] = 1 - std::accumulate(IO.y.begin(), IO.y.end() - 1, 0.0);
976 NR.call(HEOS, IO.x, IO.y, IO);
977 }
978 } else if (solutions.size() == 0) {
979 throw ValueError("No solution was found in PQ_flash");
980 } else {
981 throw ValueError("More than 1 solution was found in PQ_flash");
982 }
983 } else {
984 // *********************************************************
985 // Two-phase calculation for given vapor quality
986 // *********************************************************
987
988 // Find the correct solution
989 std::vector<std::size_t> liquid_solutions, vapor_solutions;
990 for (std::vector<std::pair<std::size_t, std::size_t>>::const_iterator it = intersections.begin(); it != intersections.end(); ++it) {
991 if (std::abs(env.Q[it->first] - 0) < 10 * DBL_EPSILON && std::abs(env.Q[it->second] - 0) < 10 * DBL_EPSILON) {
992 liquid_solutions.push_back(it->first);
993 }
994 if (std::abs(env.Q[it->first] - 1) < 10 * DBL_EPSILON && std::abs(env.Q[it->second] - 1) < 10 * DBL_EPSILON) {
995 vapor_solutions.push_back(it->first);
996 }
997 }
998
999 if (liquid_solutions.size() != 1 || vapor_solutions.size() != 1) {
1000 throw ValueError(format("Number liquid solutions [%d] or vapor solutions [%d] != 1", liquid_solutions.size(), vapor_solutions.size()));
1001 }
1002 std::size_t iliq = liquid_solutions[0], ivap = vapor_solutions[0];
1003
1004 SaturationSolvers::newton_raphson_twophase NR;
1005 SaturationSolvers::newton_raphson_twophase_options IO;
1006 IO.beta = HEOS._Q;
1007
1008 CoolPropDbl rhomolar_vap_sat_vap, T_sat_vap, rhomolar_liq_sat_vap, rhomolar_liq_sat_liq, T_sat_liq, rhomolar_vap_sat_liq, p_sat_liq,
1009 p_sat_vap;
1010
1011 if (other == iP) {
1012 IO.p = HEOS._p;
1013 p_sat_liq = IO.p;
1014 p_sat_vap = IO.p;
1015 IO.imposed_variable = SaturationSolvers::newton_raphson_twophase_options::P_IMPOSED;
1016
1017 // Calculate the interpolated values for beta = 0 and beta = 1
1018 rhomolar_vap_sat_vap = CubicInterp(env.p, env.rhomolar_vap, ivap - 1, ivap, ivap + 1, ivap + 2, static_cast<CoolPropDbl>(IO.p));
1019 T_sat_vap = CubicInterp(env.rhomolar_vap, env.T, ivap - 1, ivap, ivap + 1, ivap + 2, rhomolar_vap_sat_vap);
1020 rhomolar_liq_sat_vap = CubicInterp(env.rhomolar_vap, env.rhomolar_liq, ivap - 1, ivap, ivap + 1, ivap + 2, rhomolar_vap_sat_vap);
1021
1022 // Phase inversion for liquid solution (liquid is vapor and vice versa)
1023 rhomolar_liq_sat_liq = CubicInterp(env.p, env.rhomolar_vap, iliq - 1, iliq, iliq + 1, iliq + 2, static_cast<CoolPropDbl>(IO.p));
1024 T_sat_liq = CubicInterp(env.rhomolar_vap, env.T, iliq - 1, iliq, iliq + 1, iliq + 2, rhomolar_liq_sat_liq);
1025 rhomolar_vap_sat_liq = CubicInterp(env.rhomolar_vap, env.rhomolar_liq, iliq - 1, iliq, iliq + 1, iliq + 2, rhomolar_liq_sat_liq);
1026 } else if (other == iT) {
1027 IO.T = HEOS._T;
1028 T_sat_liq = IO.T;
1029 T_sat_vap = IO.T;
1030 IO.imposed_variable = SaturationSolvers::newton_raphson_twophase_options::T_IMPOSED;
1031
1032 // Calculate the interpolated values for beta = 0 and beta = 1
1033 rhomolar_vap_sat_vap = CubicInterp(env.T, env.rhomolar_vap, ivap - 1, ivap, ivap + 1, ivap + 2, static_cast<CoolPropDbl>(IO.T));
1034 p_sat_vap = CubicInterp(env.rhomolar_vap, env.p, ivap - 1, ivap, ivap + 1, ivap + 2, rhomolar_vap_sat_vap);
1035 rhomolar_liq_sat_vap = CubicInterp(env.rhomolar_vap, env.rhomolar_liq, ivap - 1, ivap, ivap + 1, ivap + 2, rhomolar_vap_sat_vap);
1036
1037 // Phase inversion for liquid solution (liquid is vapor and vice versa)
1038 rhomolar_liq_sat_liq = CubicInterp(env.T, env.rhomolar_vap, iliq - 1, iliq, iliq + 1, iliq + 2, static_cast<CoolPropDbl>(IO.T));
1039 p_sat_liq = CubicInterp(env.rhomolar_vap, env.p, iliq - 1, iliq, iliq + 1, iliq + 2, rhomolar_liq_sat_liq);
1040 rhomolar_vap_sat_liq = CubicInterp(env.rhomolar_vap, env.rhomolar_liq, iliq - 1, iliq, iliq + 1, iliq + 2, rhomolar_liq_sat_liq);
1041 } else {
1042 throw ValueError();
1043 }
1044
1045 // Weight the guesses by the vapor mole fraction
1046 IO.rhomolar_vap = IO.beta * rhomolar_vap_sat_vap + (1 - IO.beta) * rhomolar_vap_sat_liq;
1047 IO.rhomolar_liq = IO.beta * rhomolar_liq_sat_vap + (1 - IO.beta) * rhomolar_liq_sat_liq;
1048 IO.T = IO.beta * T_sat_vap + (1 - IO.beta) * T_sat_liq;
1049 IO.p = IO.beta * p_sat_vap + (1 - IO.beta) * p_sat_liq;
1050
1051 IO.z = HEOS.get_mole_fractions();
1052 IO.x.resize(IO.z.size());
1053 IO.y.resize(IO.z.size());
1054
1055 for (std::size_t i = 0; i < IO.x.size() - 1; ++i) // First N-1 elements
1056 {
1057 CoolPropDbl x_sat_vap = CubicInterp(env.rhomolar_vap, env.x[i], ivap - 1, ivap, ivap + 1, ivap + 2, rhomolar_vap_sat_vap);
1058 CoolPropDbl y_sat_vap = CubicInterp(env.rhomolar_vap, env.y[i], ivap - 1, ivap, ivap + 1, ivap + 2, rhomolar_vap_sat_vap);
1059
1060 CoolPropDbl x_sat_liq = CubicInterp(env.rhomolar_vap, env.y[i], iliq - 1, iliq, iliq + 1, iliq + 2, rhomolar_liq_sat_liq);
1061 CoolPropDbl y_sat_liq = CubicInterp(env.rhomolar_vap, env.x[i], iliq - 1, iliq, iliq + 1, iliq + 2, rhomolar_liq_sat_liq);
1062
1063 IO.x[i] = IO.beta * x_sat_vap + (1 - IO.beta) * x_sat_liq;
1064 IO.y[i] = IO.beta * y_sat_vap + (1 - IO.beta) * y_sat_liq;
1065 }
1066 IO.x[IO.x.size() - 1] = 1 - std::accumulate(IO.x.begin(), IO.x.end() - 1, 0.0);
1067 IO.y[IO.y.size() - 1] = 1 - std::accumulate(IO.y.begin(), IO.y.end() - 1, 0.0);
1068 NR.call(HEOS, IO);
1069 }
1070}
1072 class Residual : public FuncWrapper1D
1073 {
1074
1075 public:
1077 CoolPropDbl rhomolar_spec; // Specified value for density
1078 parameters other; // Key for other value
1079 CoolPropDbl value; // value for S,H,U
1080 CoolPropDbl Qd; // Quality from density
1081 Residual(HelmholtzEOSMixtureBackend& HEOS, CoolPropDbl rhomolar_spec, parameters other, CoolPropDbl value)
1082 : HEOS(HEOS), rhomolar_spec(rhomolar_spec), other(other), value(value) {
1083 Qd = _HUGE;
1084 };
1085 double call(double T) {
1086 HEOS.update(QT_INPUTS, 0, T);
1087 HelmholtzEOSMixtureBackend &SatL = HEOS.get_SatL(), &SatV = HEOS.get_SatV();
1088 // Quality from density
1089 Qd = (1 / rhomolar_spec - 1 / SatL.rhomolar()) / (1 / SatV.rhomolar() - 1 / SatL.rhomolar());
1090 // Quality from other parameter (H,S,U)
1091 CoolPropDbl Qo = (value - SatL.keyed_output(other)) / (SatV.keyed_output(other) - SatL.keyed_output(other));
1092 // Residual is the difference between the two
1093 return Qo - Qd;
1094 }
1095 } resid(HEOS, rhomolar_spec, other, value);
1096
1097 // Critical point for pure fluids, slightly different for pseudo-pure, very different for mixtures
1098 CoolPropDbl Tmax_sat = HEOS.calc_Tmax_sat() - 1e-13;
1099
1100 // Check what the minimum limits for the equation of state are
1101 CoolPropDbl Tmin_satL, Tmin_satV, Tmin_sat;
1102 HEOS.calc_Tmin_sat(Tmin_satL, Tmin_satV);
1103 Tmin_sat = std::max(Tmin_satL, Tmin_satV) - 1e-13;
1104
1105 Brent(resid, Tmin_sat, Tmax_sat - 0.01, DBL_EPSILON, 1e-12, 20);
1106 // Solve once more with the final vapor quality
1107 HEOS.update(QT_INPUTS, resid.Qd, HEOS.T());
1108}
1109// D given and one of P,H,S,U
1111 // Define the residual to be driven to zero
1112 class solver_resid : public FuncWrapper1DWithTwoDerivs
1113 {
1114 public:
1116 CoolPropDbl rhomolar, value;
1117 parameters other;
1118 CoolPropDbl Tmin, Tmax;
1119
1120 solver_resid(HelmholtzEOSMixtureBackend* HEOS, CoolPropDbl rhomolar, CoolPropDbl value, parameters other, CoolPropDbl Tmin, CoolPropDbl Tmax)
1121 : HEOS(HEOS), rhomolar(rhomolar), value(value), other(other), Tmin(Tmin), Tmax(Tmax) {
1124 };
1125 double call(double T) {
1126 HEOS->update_DmolarT_direct(rhomolar, T);
1127 double eos = HEOS->keyed_output(other);
1128 if (other == iP) {
1129 // For p, should use fractional error
1130 return (eos - value) / value;
1131 } else {
1132 // For everything else, use absolute error
1133 return eos - value;
1134 }
1135 };
1136 double deriv(double T) {
1137 if (other == iP) {
1138 return HEOS->first_partial_deriv(other, iT, iDmolar) / value;
1139 }
1140 return HEOS->first_partial_deriv(other, iT, iDmolar);
1141 };
1142 double second_deriv(double T) {
1143 if (other == iP) {
1144 return HEOS->second_partial_deriv(other, iT, iDmolar, iT, iDmolar) / value;
1145 }
1146 return HEOS->second_partial_deriv(other, iT, iDmolar, iT, iDmolar);
1147 };
1148 bool input_not_in_range(double T) {
1149 return (T < Tmin || T > Tmax);
1150 }
1151 };
1152
1153 if (HEOS.is_pure_or_pseudopure) {
1154 CoolPropFluid& component = HEOS.components[0];
1155
1156 shared_ptr<HelmholtzEOSMixtureBackend> Sat;
1157 CoolPropDbl rhoLtriple = component.triple_liquid.rhomolar;
1158 CoolPropDbl rhoVtriple = component.triple_vapor.rhomolar;
1159 // Check if in the "normal" region
1160 if (HEOS._rhomolar >= rhoVtriple && HEOS._rhomolar <= rhoLtriple) {
1161 CoolPropDbl yL, yV, value, y_solid;
1162 CoolPropDbl TLtriple = component.triple_liquid.T;
1163 CoolPropDbl TVtriple = component.triple_vapor.T;
1164
1165 // First check if solid (below the line connecting the triple point values) - this is an error for now
1166 switch (other) {
1167 case iSmolar:
1168 yL = HEOS.calc_smolar_nocache(TLtriple, rhoLtriple);
1169 yV = HEOS.calc_smolar_nocache(TVtriple, rhoVtriple);
1170 value = HEOS._smolar;
1171 break;
1172 case iHmolar:
1173 yL = HEOS.calc_hmolar_nocache(TLtriple, rhoLtriple);
1174 yV = HEOS.calc_hmolar_nocache(TVtriple, rhoVtriple);
1175 value = HEOS._hmolar;
1176 break;
1177 case iUmolar:
1178 yL = HEOS.calc_umolar_nocache(TLtriple, rhoLtriple);
1179 yV = HEOS.calc_umolar_nocache(TVtriple, rhoVtriple);
1180 value = HEOS._umolar;
1181 break;
1182 case iP:
1183 yL = HEOS.calc_pressure_nocache(TLtriple, rhoLtriple);
1184 yV = HEOS.calc_pressure_nocache(TVtriple, rhoVtriple);
1185 value = HEOS._p;
1186 break;
1187 default:
1188 throw ValueError(format("Input is invalid"));
1189 }
1190 y_solid = (yV - yL) / (1 / rhoVtriple - 1 / rhoLtriple) * (1 / HEOS._rhomolar - 1 / rhoLtriple) + yL;
1191
1192 if (value < y_solid) {
1193 throw ValueError(format("Other input [%d:%g] is solid", other, value));
1194 }
1195
1196 // Check if other is above the saturation value.
1198 optionsD.omega = 1;
1199 optionsD.use_logdelta = false;
1200 optionsD.max_iterations = 200;
1201 for (int i_try = 0; i_try < 7; i_try++) {
1202 try {
1203 if (HEOS._rhomolar > HEOS.rhomolar_critical()) {
1205 SaturationSolvers::saturation_D_pure(HEOS, HEOS._rhomolar, optionsD);
1206 // SatL and SatV have the saturation values
1207 Sat = HEOS.SatL;
1208 } else {
1210 SaturationSolvers::saturation_D_pure(HEOS, HEOS._rhomolar, optionsD);
1211 // SatL and SatV have the saturation values
1212 Sat = HEOS.SatV;
1213 }
1214 break; // good solve
1215 } catch (CoolPropBaseError) {
1216 optionsD.omega /= 2;
1217 optionsD.max_iterations *= 2;
1218 if (i_try >= 6) {
1219 throw;
1220 }
1221 }
1222 }
1223
1224 // If it is above, it is not two-phase and either liquid, vapor or supercritical
1225 if (value > Sat->keyed_output(other)) {
1226 solver_resid resid(&HEOS, HEOS._rhomolar, value, other, Sat->keyed_output(iT), HEOS.Tmax() * 1.5);
1227 try {
1228 HEOS._T = Halley(resid, 0.5 * (Sat->keyed_output(iT) + HEOS.Tmax() * 1.5), 1e-10, 100);
1229 } catch (...) {
1230 HEOS._T = Brent(resid, Sat->keyed_output(iT), HEOS.Tmax() * 1.5, DBL_EPSILON, 1e-12, 100);
1231 }
1232 HEOS._Q = 10000;
1233 HEOS._p = HEOS.calc_pressure_nocache(HEOS.T(), HEOS.rhomolar());
1234 HEOS.unspecify_phase();
1235 // Update the phase flag
1237 } else {
1238 // Now we know that temperature is between Tsat(D) +- tolerance and the minimum temperature for the fluid
1239 if (other == iP) {
1240 // Iterate to find T(p), its just a saturation call
1241
1242 // Set some input options
1244 // Specified variable is pressure
1246 // Use logarithm of delta as independent variables
1247 optionsPHSU.use_logdelta = false;
1248
1249 // Actually call the solver
1250 SaturationSolvers::saturation_PHSU_pure(HEOS, HEOS._p, optionsPHSU);
1251
1252 // Load the outputs
1253 HEOS._phase = iphase_twophase;
1254 HEOS._Q = (1 / HEOS._rhomolar - 1 / HEOS.SatL->rhomolar()) / (1 / HEOS.SatV->rhomolar() - 1 / HEOS.SatL->rhomolar());
1255 HEOS._T = HEOS.SatL->T();
1256 } else {
1257 // Residual is difference in quality calculated from density and quality calculated from the other parameter
1258 // Iterate to find T
1259 HSU_D_flash_twophase(HEOS, HEOS._rhomolar, other, value);
1260 HEOS._phase = iphase_twophase;
1261 }
1262 }
1263 }
1264 // Check if vapor/solid region below triple point vapor density
1265 else if (HEOS._rhomolar < component.triple_vapor.rhomolar) {
1266 CoolPropDbl y, value;
1267 CoolPropDbl TVtriple = component.triple_vapor.T; //TODO: separate TL and TV for ppure
1268
1269 // If value is above the value calculated from X(Ttriple, _rhomolar), it is vapor
1270 switch (other) {
1271 case iSmolar:
1272 y = HEOS.calc_smolar_nocache(TVtriple, HEOS._rhomolar);
1273 value = HEOS._smolar;
1274 break;
1275 case iHmolar:
1276 y = HEOS.calc_hmolar_nocache(TVtriple, HEOS._rhomolar);
1277 value = HEOS._hmolar;
1278 break;
1279 case iUmolar:
1280 y = HEOS.calc_umolar_nocache(TVtriple, HEOS._rhomolar);
1281 value = HEOS._umolar;
1282 break;
1283 case iP:
1284 y = HEOS.calc_pressure_nocache(TVtriple, HEOS._rhomolar);
1285 value = HEOS._p;
1286 break;
1287 default:
1288 throw ValueError(format("Input is invalid"));
1289 }
1290 if (value > y) {
1291 solver_resid resid(&HEOS, HEOS._rhomolar, value, other, TVtriple, HEOS.Tmax() * 1.5);
1292 HEOS._phase = iphase_gas;
1293 try {
1294 HEOS._T = Halley(resid, 0.5 * (TVtriple + HEOS.Tmax() * 1.5), DBL_EPSILON, 100);
1295 } catch (...) {
1296 HEOS._T = Brent(resid, TVtriple, HEOS.Tmax() * 1.5, DBL_EPSILON, 1e-12, 100);
1297 }
1298 HEOS._Q = 10000;
1299 HEOS.calc_pressure();
1300 } else {
1301 throw ValueError(format("D < DLtriple %g %g", value, y));
1302 }
1303
1304 }
1305 // Check in the liquid/solid region above the triple point density
1306 else {
1307 CoolPropDbl y, value;
1308 CoolPropDbl TLtriple = component.EOS().Ttriple;
1309
1310 // If value is above the value calculated from X(Ttriple, _rhomolar), it is vapor
1311 switch (other) {
1312 case iSmolar:
1313 y = HEOS.calc_smolar_nocache(TLtriple, HEOS._rhomolar);
1314 value = HEOS._smolar;
1315 break;
1316 case iHmolar:
1317 y = HEOS.calc_hmolar_nocache(TLtriple, HEOS._rhomolar);
1318 value = HEOS._hmolar;
1319 break;
1320 case iUmolar:
1321 y = HEOS.calc_umolar_nocache(TLtriple, HEOS._rhomolar);
1322 value = HEOS._umolar;
1323 break;
1324 case iP:
1325 y = HEOS.calc_pressure_nocache(TLtriple, HEOS._rhomolar);
1326 value = HEOS._p;
1327 break;
1328 default:
1329 throw ValueError(format("Input is invalid"));
1330 }
1331 if (value > y) {
1332 solver_resid resid(&HEOS, HEOS._rhomolar, value, other, TLtriple, HEOS.Tmax() * 1.5);
1333 HEOS._phase = iphase_liquid;
1334 try {
1335 HEOS._T = Halley(resid, 0.5 * (TLtriple + HEOS.Tmax() * 1.5), DBL_EPSILON, 100);
1336 } catch (...) {
1337 HEOS._T = Brent(resid, TLtriple, HEOS.Tmax() * 1.5, DBL_EPSILON, 1e-12, 100);
1338 }
1339 HEOS._Q = 10000;
1340 HEOS.calc_pressure();
1341 } else {
1342 throw ValueError(format("D < DLtriple %g %g", value, y));
1343 }
1344 }
1345 // Update the state for conditions where the state was guessed
1346 if (HEOS.phase() != iphase_twophase) {
1348 }
1349 } else
1350 throw NotImplementedError("PHSU_D_flash not ready for mixtures");
1351}
1352
1354 double A[2][2], B[2][2];
1355 CoolPropDbl y = _HUGE;
1357 _HEOS.update(DmolarT_INPUTS, rhomolar0, T0);
1358 CoolPropDbl Tc = HEOS.calc_T_critical();
1359 CoolPropDbl rhoc = HEOS.calc_rhomolar_critical();
1360 CoolPropDbl R = HEOS.gas_constant();
1361 CoolPropDbl p = HEOS.p();
1362 switch (other) {
1363 case iHmolar:
1364 y = HEOS.hmolar();
1365 break;
1366 case iSmolar:
1367 y = HEOS.smolar();
1368 break;
1369 default:
1370 throw ValueError("other is invalid in HSU_P_flash_singlephase_Newton");
1371 }
1372
1373 CoolPropDbl worst_error = 999;
1374 int iter = 0;
1375 bool failed = false;
1376 CoolPropDbl omega = 1.0, f2, df2_dtau, df2_ddelta;
1377 CoolPropDbl tau = _HEOS.tau(), delta = _HEOS.delta();
1378 while (worst_error > 1e-6 && failed == false) {
1379
1380 // All the required partial derivatives
1381 CoolPropDbl a0 = _HEOS.calc_alpha0_deriv_nocache(0, 0, HEOS.mole_fractions, tau, delta, Tc, rhoc);
1382 CoolPropDbl da0_ddelta = _HEOS.calc_alpha0_deriv_nocache(0, 1, HEOS.mole_fractions, tau, delta, Tc, rhoc);
1383 CoolPropDbl da0_dtau = _HEOS.calc_alpha0_deriv_nocache(1, 0, HEOS.mole_fractions, tau, delta, Tc, rhoc);
1384 CoolPropDbl d2a0_dtau2 = _HEOS.calc_alpha0_deriv_nocache(2, 0, HEOS.mole_fractions, tau, delta, Tc, rhoc);
1385 CoolPropDbl d2a0_ddelta_dtau = 0.0;
1386
1387 CoolPropDbl ar = _HEOS.calc_alphar_deriv_nocache(0, 0, HEOS.mole_fractions, tau, delta);
1388 CoolPropDbl dar_dtau = _HEOS.calc_alphar_deriv_nocache(1, 0, HEOS.mole_fractions, tau, delta);
1389 CoolPropDbl dar_ddelta = _HEOS.calc_alphar_deriv_nocache(0, 1, HEOS.mole_fractions, tau, delta);
1390 CoolPropDbl d2ar_ddelta_dtau = _HEOS.calc_alphar_deriv_nocache(1, 1, HEOS.mole_fractions, tau, delta);
1391 CoolPropDbl d2ar_ddelta2 = _HEOS.calc_alphar_deriv_nocache(0, 2, HEOS.mole_fractions, tau, delta);
1392 CoolPropDbl d2ar_dtau2 = _HEOS.calc_alphar_deriv_nocache(2, 0, HEOS.mole_fractions, tau, delta);
1393
1394 CoolPropDbl f1 = delta / tau * (1 + delta * dar_ddelta) - p / (rhoc * R * Tc);
1395 CoolPropDbl df1_dtau = (1 + delta * dar_ddelta) * (-delta / tau / tau) + delta / tau * (delta * d2ar_ddelta_dtau);
1396 CoolPropDbl df1_ddelta = (1.0 / tau) * (1 + 2.0 * delta * dar_ddelta + delta * delta * d2ar_ddelta2);
1397 switch (other) {
1398 case iHmolar: {
1399 f2 = (1 + delta * dar_ddelta) + tau * (da0_dtau + dar_dtau) - tau * y / (R * Tc);
1400 df2_dtau = delta * d2ar_ddelta_dtau + da0_dtau + dar_dtau + tau * (d2a0_dtau2 + d2ar_dtau2) - y / (R * Tc);
1401 df2_ddelta = (dar_ddelta + delta * d2ar_ddelta2) + tau * (d2a0_ddelta_dtau + d2ar_ddelta_dtau);
1402 break;
1403 }
1404 case iSmolar: {
1405 f2 = tau * (da0_dtau + dar_dtau) - ar - a0 - y / R;
1406 df2_dtau = tau * (d2a0_dtau2 + d2ar_dtau2) + (da0_dtau + dar_dtau) - dar_dtau - da0_dtau;
1407 df2_ddelta = tau * (d2a0_ddelta_dtau + d2ar_ddelta_dtau) - dar_ddelta - da0_ddelta;
1408 break;
1409 }
1410 default:
1411 throw ValueError("other variable in HSU_P_flash_singlephase_Newton is invalid");
1412 }
1413
1414 //First index is the row, second index is the column
1415 A[0][0] = df1_dtau;
1416 A[0][1] = df1_ddelta;
1417 A[1][0] = df2_dtau;
1418 A[1][1] = df2_ddelta;
1419
1420 //double det = A[0][0]*A[1][1]-A[1][0]*A[0][1];
1421
1422 MatInv_2(A, B);
1423 tau -= omega * (B[0][0] * f1 + B[0][1] * f2);
1424 delta -= omega * (B[1][0] * f1 + B[1][1] * f2);
1425
1426 if (std::abs(f1) > std::abs(f2))
1427 worst_error = std::abs(f1);
1428 else
1429 worst_error = std::abs(f2);
1430
1431 if (!ValidNumber(f1) || !ValidNumber(f2)) {
1432 throw SolutionError(format("Invalid values for inputs p=%g y=%g for fluid %s in HSU_P_flash_singlephase", p, y, _HEOS.name().c_str()));
1433 }
1434
1435 iter += 1;
1436 if (iter > 100) {
1437 throw SolutionError(format("HSU_P_flash_singlephase did not converge with inputs p=%g h=%g for fluid %s", p, y, _HEOS.name().c_str()));
1438 }
1439 }
1440
1441 HEOS.update(DmolarT_INPUTS, rhoc * delta, Tc / tau);
1442}
1444 CoolPropDbl Tmax, phases phase) {
1445 if (!ValidNumber(HEOS._p)) {
1446 throw ValueError("value for p in HSU_P_flash_singlephase_Brent is invalid");
1447 };
1448 if (!ValidNumber(value)) {
1449 throw ValueError("value for other in HSU_P_flash_singlephase_Brent is invalid");
1450 };
1451 class solver_resid : public FuncWrapper1DWithTwoDerivs
1452 {
1453 public:
1455 CoolPropDbl p, value;
1456 parameters other;
1457 int iter;
1458 CoolPropDbl eos0, eos1, rhomolar, rhomolar0, rhomolar1;
1459 CoolPropDbl Tmin, Tmax;
1460
1461 solver_resid(HelmholtzEOSMixtureBackend* HEOS, CoolPropDbl p, CoolPropDbl value, parameters other, double Tmin, double Tmax)
1462 : HEOS(HEOS),
1463 p(p),
1464 value(value),
1465 other(other),
1466 iter(0),
1467 eos0(-_HUGE),
1468 eos1(-_HUGE),
1469 rhomolar(_HUGE),
1470 rhomolar0(_HUGE),
1471 rhomolar1(_HUGE),
1472 Tmin(Tmin),
1473 Tmax(Tmax) {
1474 // Specify the state to avoid saturation calls, but only if phase is subcritical
1475 switch (CoolProp::phases phase = HEOS->phase()) {
1476 case iphase_liquid:
1477 case iphase_gas:
1478 HEOS->specify_phase(phase);
1479 default:
1480 // Otherwise don't do anything (this is to make compiler happy)
1481 {
1482 }
1483 }
1484 }
1485 double call(double T) {
1486
1487 if (iter < 2 || std::abs(rhomolar1 / rhomolar0 - 1) > 0.05) {
1488 // Run the solver with T,P as inputs; but only if the last change in density was greater than a few percent
1489 HEOS->update(PT_INPUTS, p, T);
1490 } else {
1491 // Run the solver with T,P as inputs; but use the guess value for density from before
1492 HEOS->update_TP_guessrho(T, p, rhomolar);
1493 }
1494
1495 // Get the value of the desired variable
1496 CoolPropDbl eos = HEOS->keyed_output(other);
1497
1498 // Store the value of density
1499 rhomolar = HEOS->rhomolar();
1500
1501 if (verbosity > 0 && iter == 0) {
1502 std::cout << format("T: %0.15g rho: %0.15g eos: %0.15g", T, rhomolar, eos);
1503 }
1504
1505 // Difference between the two is to be driven to zero
1506 CoolPropDbl r = eos - value;
1507
1508 // Store values for later use if there are errors
1509 if (iter == 0) {
1510 eos0 = eos;
1511 rhomolar0 = rhomolar;
1512 } else if (iter == 1) {
1513 eos1 = eos;
1514 rhomolar1 = rhomolar;
1515 } else {
1516 eos0 = eos1;
1517 eos1 = eos;
1518 rhomolar0 = rhomolar1;
1519 rhomolar1 = rhomolar;
1520 }
1521
1522 iter++;
1523 return r;
1524 };
1525 double deriv(double T) {
1526 return HEOS->first_partial_deriv(other, iT, iP);
1527 }
1528 double second_deriv(double T) {
1529 return HEOS->second_partial_deriv(other, iT, iP, iT, iP);
1530 }
1531 bool input_not_in_range(double x) {
1532 return (x < Tmin || x > Tmax);
1533 }
1534 };
1535 solver_resid resid(&HEOS, HEOS._p, value, other, Tmin, Tmax);
1536
1537 class resid_2D : public FuncWrapperND
1538 {
1539 public:
1541 CoolPropDbl p, value;
1542 parameters other;
1543 int iter;
1544 std::vector<std::vector<double>> J = {{-1.0, -1.0}, {-1.0, -1.0}};
1545
1546 resid_2D(HelmholtzEOSMixtureBackend* HEOS, double p, CoolPropDbl value, parameters other, double Tmin, double Tmax)
1547 : HEOS(HEOS), p(p), value(value), other(other), iter(0) {}
1548 std::vector<double> call(const std::vector<double>& x) override {
1549 double T = x[0], rhomolar = x[1];
1550 HEOS->update_DmolarT_direct(rhomolar, T);
1551 J[0][0] = HEOS->first_partial_deriv(iP, iT, iDmolar) / p;
1552 J[0][1] = HEOS->first_partial_deriv(iP, iDmolar, iT) / p;
1553 J[1][0] = HEOS->first_partial_deriv(other, iT, iDmolar);
1554 J[1][1] = HEOS->first_partial_deriv(other, iDmolar, iT);
1555
1556 return {(HEOS->p() - p) / p, HEOS->keyed_output(other) - value};
1557 }
1558 std::vector<std::vector<double>> Jacobian(const std::vector<double>& /*x*/) override {
1559 // pre-calculated in call function
1560 return J;
1561 }
1562 };
1563 resid_2D solver_resid2d(&HEOS, HEOS._p, value, other, Tmin, Tmax);
1564
1565 // Get residual values at the bounds
1566 double resid_Tmin = resid.call(Tmin);
1567 double rhomolar_Tmin = HEOS.rhomolar();
1568
1569 double resid_Tmax = resid.call(Tmax);
1570 double rhomolar_Tmax = HEOS.rhomolar();
1571
1572 // For the derivative-based methods, figure out which point to start from
1573 bool use_min = std::abs(resid_Tmin) < std::abs(resid_Tmax);
1574 double Tstart = use_min ? Tmin : Tmax;
1575 double rhomolarstart = use_min ? rhomolar_Tmin : rhomolar_Tmax;
1576
1577 try {
1578 if (get_debug_level() > 0) {
1579 resid.verbosity = 1;
1580 }
1581 if (resid_Tmin * resid_Tmax < 0) {
1582 // The residual values bound zero, use the TOMS748 method (no derivatives)
1583 // See: https://www.boost.org/doc/libs/1_58_0/libs/math/doc/html/math_toolkit/internals1/roots2.html#math_toolkit.internals1.roots2.algorithm_toms_748_alefeld_potra
1584 //
1585 // It is like a supercharged version of Brent's method, which is practically guaranteed
1586 // to converge for any continuous function, and take the optimal step among bisection
1587 // and higher-order methods
1588 resid.iter = 0;
1589 boost::math::uintmax_t max_iter = 100;
1590
1591 auto f = [&resid](const double T) { return resid.call(T); };
1592 // Want 44 bits to be correct, tolerance is 2^(1-bits) ::
1593 // >>> 2**(1-44)
1594 // 1.1368683772161603e-13
1595 auto [l, r] = toms748_solve(f, Tmin, Tmax, resid_Tmin, resid_Tmax, boost::math::tools::eps_tolerance<double>(44), max_iter);
1596 if (!is_in_closed_range(Tmin, Tmax, static_cast<CoolPropDbl>(resid.HEOS->T()))) {
1597 throw ValueError(format("TOMS748 method yielded out of bound T of %g", static_cast<CoolPropDbl>(resid.HEOS->T())));
1598 }
1599
1600 // Un-specify the phase of the fluid
1601 HEOS.unspecify_phase();
1603 } else {
1604 resid.iter = 0;
1605 Halley(resid, Tstart, 1e-12, 100);
1606 if (!is_in_closed_range(Tmin, Tmax, static_cast<CoolPropDbl>(resid.HEOS->T())) || resid.HEOS->phase() != phase) {
1607 throw ValueError("Halley's method was unable to find a solution in HSU_P_flash_singlephase_Brent");
1608 }
1609 // Un-specify the phase of the fluid
1610 HEOS.unspecify_phase();
1612 }
1613 } catch (...) {
1614 try {
1615 double p_critical_ = HEOS.p_critical();
1616 if (0.95 * p_critical_ > HEOS._p || HEOS._p > p_critical_) {
1617 throw;
1618 }
1619 if (get_debug_level() > 0) {
1620 std::cout << resid.errstring << std::endl;
1621 }
1622 std::vector<double> x0 = {Tstart, rhomolarstart};
1623 NDNewtonRaphson_Jacobian(&solver_resid2d, x0, 1e-12, 20, 1.0);
1624 if (!is_in_closed_range(Tmin, Tmax, static_cast<CoolPropDbl>(solver_resid2d.HEOS->T())) || solver_resid2d.HEOS->phase() != phase) {
1625 throw ValueError("2D Newton method was unable to find a solution in HSU_P_flash_singlephase_Brent");
1626 }
1627 // Un-specify the phase of the fluid
1628 HEOS.unspecify_phase();
1630 } catch (...) {
1631 if (get_debug_level() > 0) {
1632 std::cout << resid.errstring << std::endl;
1633 }
1634 // Un-specify the phase of the fluid
1635 HEOS.unspecify_phase();
1636
1637 // Determine why you were out of range if you can
1638 //
1639 CoolPropDbl eos0 = resid.eos0, eos1 = resid.eos1;
1640 std::string name = get_parameter_information(other, "short");
1641 std::string units = get_parameter_information(other, "units");
1642 if (eos1 > eos0 && value > eos1) {
1643 throw ValueError(
1644 format("HSU_P_flash_singlephase_Brent could not find a solution because %s [%Lg %s] is above the maximum value of %0.12Lg %s",
1645 name.c_str(), value, units.c_str(), eos1, units.c_str()));
1646 }
1647 if (eos1 > eos0 && value < eos0) {
1648 throw ValueError(
1649 format("HSU_P_flash_singlephase_Brent could not find a solution because %s [%Lg %s] is below the minimum value of %0.12Lg %s",
1650 name.c_str(), value, units.c_str(), eos0, units.c_str()));
1651 }
1652 throw;
1653 }
1654 }
1655}
1656
1657// P given and one of H, S, or U
1659 bool saturation_called = false;
1660 CoolPropDbl value;
1661
1662 // Find the phase, while updating all internal variables possible
1663 switch (other) {
1664 case iSmolar:
1665 value = HEOS.smolar();
1666 break;
1667 case iHmolar:
1668 value = HEOS.hmolar();
1669 break;
1670 case iUmolar:
1671 value = HEOS.umolar();
1672 break;
1673 default:
1674 throw ValueError(format("Input for other [%s] is invalid", get_parameter_information(other, "long").c_str()));
1675 }
1676 if (HEOS.is_pure_or_pseudopure) {
1677
1678 // Find the phase, while updating all internal variables possible
1679 HEOS.p_phase_determination_pure_or_pseudopure(other, value, saturation_called);
1680
1681 if (HEOS.isHomogeneousPhase()) {
1682 // Now we use the single-phase solver to find T,rho given P,Y using a
1683 // bounded 1D solver by adjusting T and using given value of p
1684 CoolPropDbl Tmin, Tmax;
1685 switch (HEOS._phase) {
1686 case iphase_gas: {
1687 Tmax = 1.5 * HEOS.Tmax();
1688 if (HEOS._p < HEOS.p_triple()) {
1689 Tmin = std::max(HEOS.Tmin(), HEOS.Ttriple());
1690 } else {
1691
1692 if (get_config_bool(ENABLE_SUPERANCILLARIES) && HEOS.is_pure()) {
1693 auto& optsuperanc = HEOS.get_superanc_optional();
1694 if (optsuperanc) {
1695 auto& superanc = optsuperanc.value();
1696 CoolPropDbl pmax_num = superanc.get_pmax();
1697 if (HEOS._p > pmax_num) {
1698 throw ValueError(
1699 format("Pressure to PQ_flash [%0.8Lg Pa] may not be above the numerical critical point of %0.15Lg Pa", HEOS._p,
1700 pmax_num));
1701 }
1702 Tmin = superanc.get_T_from_p(HEOS._p);
1703 break;
1704 }
1705 }
1706 if (saturation_called) {
1707 Tmin = HEOS.SatV->T();
1708 } else {
1709 Tmin = HEOS._TVanc.pt() - 0.01;
1710 }
1711 }
1712 break;
1713 }
1714 case iphase_liquid: {
1715
1716 // Sometimes the minimum pressure for the melting line is a bit above the triple point pressure
1717 if (HEOS.has_melting_line() && HEOS._p > HEOS.calc_melting_line(iP_min, -1, -1)) {
1718 Tmin = HEOS.calc_melting_line(iT, iP, HEOS._p) - 1e-3;
1719 } else {
1720 Tmin = HEOS.Tmin() - 1e-3;
1721 }
1722
1723 if (get_config_bool(ENABLE_SUPERANCILLARIES) && HEOS.is_pure()) {
1724 auto& optsuperanc = HEOS.get_superanc_optional();
1725 if (optsuperanc) {
1726 auto& superanc = optsuperanc.value();
1727 CoolPropDbl pmax_num = superanc.get_pmax();
1728 if (HEOS._p > pmax_num) {
1729 throw ValueError(format(
1730 "Pressure to PQ_flash [%0.8Lg Pa] may not be above the numerical critical point of %0.15Lg Pa", HEOS._p, pmax_num));
1731 }
1732 Tmax = superanc.get_T_from_p(HEOS._p);
1733 break;
1734 }
1735 }
1736
1737 if (saturation_called) {
1738 Tmax = HEOS.SatL->T();
1739 } else {
1740 Tmax = HEOS._TLanc.pt() + 0.01;
1741 }
1742
1743 break;
1744 }
1747 case iphase_supercritical: {
1748 Tmax = 1.5 * HEOS.Tmax();
1749 // Sometimes the minimum pressure for the melting line is a bit above the triple point pressure
1750 if (HEOS.has_melting_line() && HEOS._p > HEOS.calc_melting_line(iP_min, -1, -1)) {
1751 Tmin = HEOS.calc_melting_line(iT, iP, HEOS._p) - 1e-3;
1752 } else {
1753 Tmin = HEOS.Tmin() - 1e-3;
1754 }
1755 break;
1756 }
1757 default: {
1758 throw ValueError(format("Not a valid homogeneous state"));
1759 }
1760 }
1761 try {
1762 HSU_P_flash_singlephase_Brent(HEOS, other, value, Tmin, Tmax, HEOS._phase);
1763 } catch (std::exception& e) {
1764 throw ValueError(format("unable to solve 1phase PY flash with Tmin=%Lg, Tmax=%Lg due to error: %s", Tmin, Tmax, e.what()));
1765 }
1766 HEOS._Q = -1;
1767 // Update the state for conditions where the state was guessed
1769 }
1770 } else {
1771 if (HEOS.PhaseEnvelope.built) {
1772 // Determine whether you are inside or outside
1773 SimpleState closest_state;
1774 std::size_t iclosest;
1775 bool twophase = PhaseEnvelopeRoutines::is_inside(HEOS.PhaseEnvelope, iP, HEOS._p, other, value, iclosest, closest_state);
1776
1777 if (!twophase) {
1778 PY_singlephase_flash_resid resid(HEOS, HEOS._p, other, value);
1779 // If that fails, try a bounded solver
1780 Brent(resid, closest_state.T + 10, 1000, DBL_EPSILON, 1e-10, 100);
1781 HEOS.unspecify_phase();
1782 } else {
1783 throw ValueError("two-phase solution for Y");
1784 }
1785
1786 } else {
1787 throw ValueError("phase envelope must be built to carry out HSU_P_flash for mixture");
1788 }
1789 }
1790}
1792 // Define the residual to be driven to zero
1793 class solver_resid : public FuncWrapper1DWithTwoDerivs
1794 {
1795 public:
1797 CoolPropDbl T, value;
1798 parameters other;
1799
1800 solver_resid(HelmholtzEOSMixtureBackend* HEOS, CoolPropDbl T, CoolPropDbl value, parameters other)
1801 : HEOS(HEOS), T(T), value(value), other(other) {}
1802 double call(double rhomolar) {
1803 HEOS->update_DmolarT_direct(rhomolar, T);
1804 double eos = HEOS->keyed_output(other);
1805 return eos - value;
1806 };
1807 double deriv(double rhomolar) {
1808 return HEOS->first_partial_deriv(other, iDmolar, iT);
1809 }
1810 double second_deriv(double rhomolar) {
1811 return HEOS->second_partial_deriv(other, iDmolar, iT, iDmolar, iT);
1812 }
1813 };
1814 solver_resid resid(&HEOS, T, value, other);
1815
1816 double T_critical_ = (HEOS.is_pure_or_pseudopure) ? HEOS.T_critical() : HEOS._crit.T;
1817
1818 // Supercritical temperature
1819 if (HEOS._T > T_critical_) {
1820 CoolPropDbl yc, ymin, y;
1822 CoolPropDbl rhomin = 1e-10;
1823
1824 // Determine limits for the other variable
1825 switch (other) {
1826 case iSmolar: {
1827 yc = HEOS.calc_smolar_nocache(HEOS._T, rhoc);
1828 ymin = HEOS.calc_smolar_nocache(HEOS._T, rhomin);
1829 y = HEOS._smolar;
1830 break;
1831 }
1832 case iHmolar: {
1833 yc = HEOS.calc_hmolar_nocache(HEOS._T, rhoc);
1834 ymin = HEOS.calc_hmolar_nocache(HEOS._T, rhomin);
1835 y = HEOS._hmolar;
1836 break;
1837 }
1838 case iUmolar: {
1839 yc = HEOS.calc_umolar_nocache(HEOS._T, rhoc);
1840 ymin = HEOS.calc_umolar_nocache(HEOS._T, rhomin);
1841 y = HEOS._umolar;
1842 break;
1843 }
1844 default:
1845 throw ValueError();
1846 }
1847 if (is_in_closed_range(yc, ymin, y)) {
1848 Brent(resid, rhoc, rhomin, LDBL_EPSILON, 1e-9, 100);
1849 } else if (y < yc) {
1850 // Increase rhomelt until it bounds the solution
1851 int step_count = 0;
1852 while (!is_in_closed_range(ymin, yc, y)) {
1853 rhoc *= 1.1; // Increase density by a few percent
1854 switch (other) {
1855 case iSmolar:
1856 yc = HEOS.calc_smolar_nocache(HEOS._T, rhoc);
1857 break;
1858 case iHmolar:
1859 yc = HEOS.calc_hmolar_nocache(HEOS._T, rhoc);
1860 break;
1861 case iUmolar:
1862 yc = HEOS.calc_umolar_nocache(HEOS._T, rhoc);
1863 break;
1864 default:
1865 throw ValueError(format("Input is invalid"));
1866 }
1867 if (step_count > 30) {
1868 throw ValueError(format("Even by increasing rhoc, not able to bound input; input %Lg is not in range %Lg,%Lg", y, yc, ymin));
1869 }
1870 step_count++;
1871 }
1872 Brent(resid, rhomin, rhoc, LDBL_EPSILON, 1e-9, 100);
1873 } else {
1874 throw ValueError(format("input %Lg is not in range %Lg,%Lg,%Lg", y, yc, ymin));
1875 }
1876 // Update the state (T > Tc)
1877 if (HEOS._p < HEOS.p_critical()) {
1879 } else {
1881 }
1882 }
1883 // Subcritical temperature liquid
1884 else if ((HEOS._phase == iphase_liquid) || (HEOS._phase == iphase_supercritical_liquid)) {
1885 CoolPropDbl ymelt, yL, y;
1886 CoolPropDbl rhomelt = HEOS.components[0].triple_liquid.rhomolar;
1887 CoolPropDbl rhoL = static_cast<double>(HEOS._rhoLanc);
1888
1889 switch (other) {
1890 case iSmolar: {
1891 ymelt = HEOS.calc_smolar_nocache(HEOS._T, rhomelt);
1892 yL = HEOS.calc_smolar_nocache(HEOS._T, rhoL);
1893 y = HEOS._smolar;
1894 break;
1895 }
1896 case iHmolar: {
1897 ymelt = HEOS.calc_hmolar_nocache(HEOS._T, rhomelt);
1898 yL = HEOS.calc_hmolar_nocache(HEOS._T, rhoL);
1899 y = HEOS._hmolar;
1900 break;
1901 }
1902 case iUmolar: {
1903 ymelt = HEOS.calc_umolar_nocache(HEOS._T, rhomelt);
1904 yL = HEOS.calc_umolar_nocache(HEOS._T, rhoL);
1905 y = HEOS._umolar;
1906 break;
1907 }
1908 default:
1909 throw ValueError();
1910 }
1911
1912 CoolPropDbl rhomolar_guess = (rhomelt - rhoL) / (ymelt - yL) * (y - yL) + rhoL;
1913
1914 try {
1915 Halley(resid, rhomolar_guess, 1e-8, 100);
1916 } catch (...) {
1917 Secant(resid, rhomolar_guess, 0.0001 * rhomolar_guess, 1e-12, 100);
1918 }
1919 }
1920 // Subcritical temperature gas
1921 else if (HEOS._phase == iphase_gas) {
1922 CoolPropDbl rhomin = 1e-14;
1923 CoolPropDbl rhoV = static_cast<double>(HEOS._rhoVanc);
1924
1925 try {
1926 Halley(resid, 0.5 * (rhomin + rhoV), 1e-8, 100);
1927 } catch (...) {
1928 try {
1929 Brent(resid, rhomin, rhoV, LDBL_EPSILON, 1e-12, 100);
1930 } catch (...) {
1931 throw ValueError();
1932 }
1933 }
1934 } else {
1935 throw ValueError(format("phase to solver_for_rho_given_T_oneof_HSU is invalid"));
1936 }
1937};
1938
1941 // Use the phase defined by the imposed phase
1942 HEOS._phase = HEOS.imposed_phase_index;
1943 double T_critical_ = (HEOS.is_pure_or_pseudopure) ? HEOS.T_critical() : HEOS._crit.T;
1944 // The remaining code in this branch was added to set some needed parameters if phase is imposed,
1945 // since HEOS.T_phase_determination_pure_or_pseudopure() is not being called.
1946 if (HEOS._T < T_critical_) //
1947 {
1948 // TODO: is it a bug that this branch can be accessed for mixtures?
1949 HEOS._rhoVanc = HEOS.components[0].ancillaries.rhoV.evaluate(HEOS._T);
1950 HEOS._rhoLanc = HEOS.components[0].ancillaries.rhoL.evaluate(HEOS._T);
1951 if (HEOS._phase == iphase_liquid) {
1952 HEOS._Q = -1000;
1953 } else if (HEOS._phase == iphase_gas) {
1954 HEOS._Q = 1000;
1955 } else if (HEOS._phase == iphase_twophase) {
1956 // Actually have to use saturation information sadly
1957 // For the given temperature, find the saturation state
1958 // Run the saturation routines to determine the saturation densities and pressures
1961 SaturationSolvers::saturation_T_pure(HEOS1, HEOS._T, options);
1962
1963 if (other != iDmolar) {
1964 // Update the states
1965 if (HEOS.SatL) HEOS.SatL->update(DmolarT_INPUTS, HEOS._rhoLanc, HEOS._T);
1966 if (HEOS.SatV) HEOS.SatV->update(DmolarT_INPUTS, HEOS._rhoVanc, HEOS._T);
1967 // Update the two-Phase variables
1968 HEOS._rhoLmolar = HEOS.SatL->rhomolar();
1969 HEOS._rhoVmolar = HEOS.SatV->rhomolar();
1970 }
1971
1972 CoolPropDbl Q;
1973
1974 switch (other) {
1975 case iDmolar:
1976 Q = (1 / HEOS.rhomolar() - 1 / HEOS1.SatL->rhomolar()) / (1 / HEOS1.SatV->rhomolar() - 1 / HEOS1.SatL->rhomolar());
1977 break;
1978 case iSmolar:
1979 Q = (HEOS.smolar() - HEOS1.SatL->smolar()) / (HEOS1.SatV->smolar() - HEOS1.SatL->smolar());
1980 break;
1981 case iHmolar:
1982 Q = (HEOS.hmolar() - HEOS1.SatL->hmolar()) / (HEOS1.SatV->hmolar() - HEOS1.SatL->hmolar());
1983 break;
1984 case iUmolar:
1985 Q = (HEOS.umolar() - HEOS1.SatL->umolar()) / (HEOS1.SatV->umolar() - HEOS1.SatL->umolar());
1986 break;
1987 default:
1988 throw ValueError(format("bad input for other"));
1989 }
1990 if (Q < 0) {
1991 HEOS._Q = -1;
1992 } else if (Q > 1) {
1993 HEOS._Q = 1;
1994 } else {
1995 HEOS._Q = Q;
1996 // Load the outputs
1997 HEOS._p = HEOS._Q * HEOS1.SatV->p() + (1 - HEOS._Q) * HEOS1.SatL->p();
1998 HEOS._rhomolar = 1 / (HEOS._Q / HEOS.SatV->rhomolar() + (1 - HEOS._Q) / HEOS.SatL->rhomolar());
1999 }
2000 } else if (HEOS._phase == iphase_supercritical_liquid) {
2001 HEOS._Q = -1000;
2002 } else
2003 throw ValueError(format("Temperature specified is not the imposed phase region."));
2004 } else if (HEOS._T > T_critical_ && HEOS._T > HEOS.components[0].EOS().Ttriple) {
2005 HEOS._Q = 1e9;
2006 }
2007 } else {
2008 if (HEOS.is_pure_or_pseudopure) {
2009 // Find the phase, while updating all internal variables possible
2010 switch (other) {
2011 case iDmolar:
2013 break;
2014 case iSmolar:
2016 break;
2017 case iHmolar:
2019 break;
2020 case iUmolar:
2022 break;
2023 default:
2024 throw ValueError(format("Input is invalid"));
2025 }
2026 } else {
2027 HEOS._phase = iphase_gas;
2028 throw NotImplementedError("DHSU_T_flash does not support mixtures (yet)");
2029 }
2030 }
2031
2032 //if (HEOS.isHomogeneousPhase() && !ValidNumber(HEOS._p)) // original, pre 1352
2033 // only the solver requires single phase
2034 if (((other == iDmolar) || HEOS.isHomogeneousPhase()) && !ValidNumber(HEOS._p)) // post 1352
2035 {
2036 switch (other) {
2037 case iDmolar:
2038 break;
2039 case iHmolar:
2041 break;
2042 case iSmolar:
2044 break;
2045 case iUmolar:
2047 break;
2048 default:
2049 break;
2050 }
2051 HEOS.calc_pressure();
2052 HEOS._Q = -1;
2053 }
2054 if (HEOS.is_pure_or_pseudopure && HEOS._phase != iphase_twophase) {
2055 // Update the state for conditions where the state was guessed
2057 }
2058}
2060 HS_flash_twophaseOptions& options) {
2061 class Residual : public FuncWrapper1D
2062 {
2063
2064 public:
2066 CoolPropDbl hmolar, smolar, Qs;
2067 Residual(HelmholtzEOSMixtureBackend& HEOS, CoolPropDbl hmolar_spec, CoolPropDbl smolar_spec)
2068 : HEOS(HEOS), hmolar(hmolar_spec), smolar(smolar_spec), Qs(_HUGE) {};
2069 double call(double T) {
2070 HEOS.update(QT_INPUTS, 0, T);
2071 HelmholtzEOSMixtureBackend &SatL = HEOS.get_SatL(), &SatV = HEOS.get_SatV();
2072 // Quality from entropy
2073 Qs = (smolar - SatL.smolar()) / (SatV.smolar() - SatL.smolar());
2074 // Quality from enthalpy
2075 CoolPropDbl Qh = (hmolar - SatL.hmolar()) / (SatV.hmolar() - SatL.hmolar());
2076 // Residual is the difference between the two
2077 return Qh - Qs;
2078 }
2079 } resid(HEOS, hmolar_spec, smolar_spec);
2080
2081 // Critical point for pure fluids, slightly different for pseudo-pure, very different for mixtures
2082 CoolPropDbl Tmax_sat = HEOS.calc_Tmax_sat() - 1e-13;
2083
2084 // Check what the minimum limits for the equation of state are
2085 CoolPropDbl Tmin_satL, Tmin_satV, Tmin_sat;
2086 HEOS.calc_Tmin_sat(Tmin_satL, Tmin_satV);
2087 Tmin_sat = std::max(Tmin_satL, Tmin_satV) - 1e-13;
2088
2089 Brent(resid, Tmin_sat, Tmax_sat - 0.01, DBL_EPSILON, 1e-12, 20);
2090 // Run once more with the final vapor quality
2091 HEOS.update(QT_INPUTS, resid.Qs, HEOS.T());
2092}
2094 HS_flash_singlephaseOptions& options) {
2095 int iter = 0;
2096 double resid = 9e30, resid_old = 9e30;
2097 CoolProp::SimpleState reducing = HEOS.get_state("reducing");
2098 do {
2099 // Independent variables are T0 and rhomolar0, residuals are matching h and s
2100 Eigen::Vector2d r;
2101 Eigen::Matrix2d J;
2102 r(0) = HEOS.hmolar() - hmolar_spec;
2103 r(1) = HEOS.smolar() - smolar_spec;
2104 J(0, 0) = HEOS.first_partial_deriv(iHmolar, iTau, iDelta);
2105 J(0, 1) = HEOS.first_partial_deriv(iHmolar, iDelta, iTau);
2106 J(1, 0) = HEOS.first_partial_deriv(iSmolar, iTau, iDelta);
2107 J(1, 1) = HEOS.first_partial_deriv(iSmolar, iDelta, iTau);
2108 // Step in v obtained from Jv = -r
2109 Eigen::Vector2d v = J.colPivHouseholderQr().solve(-r);
2110 bool good_solution = false;
2111 double tau0 = HEOS.tau(), delta0 = HEOS.delta();
2112 // Calculate the old residual after the last step
2113 resid_old = sqrt(POW2(HEOS.hmolar() - hmolar_spec) + POW2(HEOS.smolar() - smolar_spec));
2114 for (double frac = 1.0; frac > 0.001; frac /= 2) {
2115 try {
2116 // Calculate new values
2117 double tau_new = tau0 + options.omega * frac * v(0);
2118 double delta_new = delta0 + options.omega * frac * v(1);
2119 double T_new = reducing.T / tau_new;
2120 double rhomolar_new = delta_new * reducing.rhomolar;
2121 // Update state with step
2122 HEOS.update(DmolarT_INPUTS, rhomolar_new, T_new);
2123 resid = sqrt(POW2(HEOS.hmolar() - hmolar_spec) + POW2(HEOS.smolar() - smolar_spec));
2124 if (resid > resid_old) {
2125 throw ValueError(format("residual not decreasing; frac: %g, resid: %g, resid_old: %g", frac, resid, resid_old));
2126 }
2127 good_solution = true;
2128 break;
2129 } catch (...) {
2130 HEOS.clear();
2131 continue;
2132 }
2133 }
2134 if (!good_solution) {
2135 throw ValueError(format("Not able to get a solution"));
2136 }
2137 iter++;
2138 if (iter > 50) {
2139 throw ValueError(format("HS_flash_singlephase took too many iterations; residual is %g; prior was %g", resid, resid_old));
2140 }
2141 } while (std::abs(resid) > 1e-9);
2142}
2144 // Randomly obtain a starting value that is single-phase
2145 double logp = ((double)rand() / (double)RAND_MAX) * (log(HEOS.pmax()) - log(HEOS.p_triple())) + log(HEOS.p_triple());
2146 T = ((double)rand() / (double)RAND_MAX) * (HEOS.Tmax() - HEOS.Ttriple()) + HEOS.Ttriple();
2147 p = exp(logp);
2148}
2150 // Use TS flash and iterate on T (known to be between Tmin and Tmax)
2151 // in order to find H
2152 double hmolar = HEOS.hmolar(), smolar = HEOS.smolar();
2153 class Residual : public FuncWrapper1D
2154 {
2155 public:
2157 CoolPropDbl hmolar, smolar;
2158 Residual(HelmholtzEOSMixtureBackend& HEOS, CoolPropDbl hmolar_spec, CoolPropDbl smolar_spec)
2159 : HEOS(HEOS), hmolar(hmolar_spec), smolar(smolar_spec) {};
2160 double call(double T) {
2161 HEOS.update(SmolarT_INPUTS, smolar, T);
2162 double r = HEOS.hmolar() - hmolar;
2163 return r;
2164 }
2165 } resid(HEOS, hmolar, smolar);
2166 std::string errstr;
2167 // Find minimum temperature
2168 bool good_Tmin = false;
2169 double Tmin = HEOS.Ttriple();
2170 double rmin;
2171 do {
2172 try {
2173 rmin = resid.call(Tmin);
2174 good_Tmin = true;
2175 } catch (...) {
2176 Tmin += 0.5;
2177 }
2178 if (Tmin > HEOS.Tmax()) {
2179 throw ValueError("Cannot find good Tmin");
2180 }
2181 } while (!good_Tmin);
2182
2183 // Find maximum temperature
2184 bool good_Tmax = false;
2185 double Tmax = HEOS.Tmax() * 1.01; // Just a little above, so if we use Tmax as input, it should still work
2186 double rmax;
2187 do {
2188 try {
2189 rmax = resid.call(Tmax);
2190 good_Tmax = true;
2191 } catch (...) {
2192 Tmax -= 0.1;
2193 }
2194 if (Tmax < Tmin) {
2195 throw ValueError("Cannot find good Tmax");
2196 }
2197 } while (!good_Tmax);
2198 if (rmin * rmax > 0 && std::abs(rmax) < std::abs(rmin)) {
2199 throw CoolProp::ValueError(format("HS inputs correspond to temperature above maximum temperature of EOS [%g K]", HEOS.Tmax()));
2200 }
2201 Brent(resid, Tmin, Tmax, DBL_EPSILON, 1e-10, 100);
2202}
2203
2204#if defined(ENABLE_CATCH)
2205
2206TEST_CASE("PD with T very large should yield error", "[PDflash]") {
2207 shared_ptr<HelmholtzEOSBackend> HEOS(new HelmholtzEOSBackend("R134a"));
2208 double Tc = HEOS->T_critical();
2209 HEOS->update(DmassT_INPUTS, 1.1, 1.5 * Tc);
2210 CHECK_THROWS(HEOS->update(DmassP_INPUTS, 2, 5 * HEOS->p()));
2211}
2212
2213TEST_CASE("Stability testing", "[stability]") {
2214 shared_ptr<HelmholtzEOSMixtureBackend> HEOS(new HelmholtzEOSMixtureBackend(strsplit("n-Propane&n-Butane&n-Pentane&n-Hexane", '&')));
2215 std::vector<double> z(4);
2216 z[0] = 0.1;
2217 z[1] = 0.2;
2218 z[2] = 0.3;
2219 z[3] = 0.4;
2220 HEOS->set_mole_fractions(z);
2221
2222 HEOS->update(PQ_INPUTS, 101325, 0);
2223 double TL = HEOS->T();
2224
2225 HEOS->update(PQ_INPUTS, 101325, 1);
2226 double TV = HEOS->T();
2227
2228 SECTION("Liquid (feed is stable)") {
2229 StabilityRoutines::StabilityEvaluationClass stability_tester(*HEOS);
2230 for (double T = TL - 1; T >= 100; T -= 1) {
2231 stability_tester.set_TP(T, 101325);
2232 CAPTURE(T);
2233 CHECK_NOTHROW(stability_tester.is_stable());
2234 }
2235 }
2236 SECTION("Vapor (feed is stable)") {
2237 StabilityRoutines::StabilityEvaluationClass stability_tester(*HEOS);
2238 for (double T = TV + 1; T <= 500; T += 1) {
2239 stability_tester.set_TP(T, 101325);
2240 CAPTURE(T);
2241 CHECK_NOTHROW(stability_tester.is_stable());
2242 }
2243 }
2244 SECTION("Two-phase (feed is unstable)") {
2245 StabilityRoutines::StabilityEvaluationClass stability_tester(*HEOS);
2246 stability_tester.set_TP((TV + TL) / 2.0, 101325);
2247 CHECK(stability_tester.is_stable() == false);
2248 }
2249}
2250
2251TEST_CASE("Test critical points for methane + H2S", "[critical_points]") {
2252 shared_ptr<HelmholtzEOSMixtureBackend> HEOS(new HelmholtzEOSMixtureBackend(strsplit("Methane&H2S", '&')));
2253
2254 double zz[] = {0.998, 0.97, 0.9475, 0.94, 0.93, 0.86, 0.85, 0.84, 0.75, 0.53, 0.52, 0.51, 0.49, 0.36, 0.24, 0.229, 0.09};
2255 int Npts[] = {2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 1, 1, 1, 1}; // Number of critical points that should be found
2256 int imax = sizeof(zz) / sizeof(double);
2257
2258 for (int i = 0; i < imax; ++i) {
2259 double z0 = zz[i];
2260 std::vector<double> z(2);
2261 z[0] = z0;
2262 z[1] = 1 - z0;
2263 HEOS->set_mole_fractions(z);
2264 CAPTURE(z0);
2265 std::vector<CriticalState> pts = HEOS->all_critical_points();
2266 CHECK(pts.size() == Npts[i]);
2267 }
2268}
2269
2270TEST_CASE("Test critical points for nitrogen + ethane with HEOS", "[critical_points]") {
2271 shared_ptr<HelmholtzEOSMixtureBackend> HEOS(new HelmholtzEOSMixtureBackend(strsplit("Nitrogen&Ethane", '&')));
2272 std::vector<double> zz = linspace(0.001, 0.999, 21);
2273 int failure_count = 0;
2274 for (int i = 0; i < static_cast<std::size_t>(zz.size()); ++i) {
2275 double z0 = zz[i];
2276 std::vector<double> z(2);
2277 z[0] = z0;
2278 z[1] = 1 - z0;
2279 HEOS->set_mole_fractions(z);
2280 CAPTURE(z0);
2281 std::vector<CriticalState> pts;
2282 try {
2283 pts = HEOS->all_critical_points();
2284 } catch (std::exception& e) {
2285 CAPTURE(e.what());
2286 failure_count++;
2287 }
2288 }
2289 // Only an error if more than half fail;
2290 CHECK(failure_count < 10);
2291}
2292
2293TEST_CASE("Test critical points for nitrogen + ethane with PR", "[critical_points]") {
2294 shared_ptr<PengRobinsonBackend> HEOS(new PengRobinsonBackend(strsplit("Nitrogen&Ethane", '&')));
2295 HEOS->set_binary_interaction_double(0, 1, "kij", 0.0407); // Ramırez-Jimenez et al.
2296 std::vector<double> zz = linspace(0.001, 0.999, 21);
2297 for (int i = 0; i < static_cast<std::size_t>(zz.size()); ++i) {
2298 double z0 = zz[i];
2299 std::vector<double> z(2);
2300 z[0] = z0;
2301 z[1] = 1 - z0;
2302 HEOS->set_mole_fractions(z);
2303 CAPTURE(z0);
2304 std::vector<CriticalState> pts;
2305 CHECK_NOTHROW(pts = HEOS->all_critical_points());
2306 }
2307}
2308
2309#endif
2310
2311} /* namespace CoolProp */