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