CoolProp 8.0.0
An open-source fluid property and humid air property database
PhaseEnvelopeRoutines.cpp
Go to the documentation of this file.
1#ifndef PHASEENVELOPE_H
2#define PHASEENVELOPE_H
3
5#include "VLERoutines.h"
11
12namespace CoolProp {
13
14void PhaseEnvelopeRoutines::build(HelmholtzEOSMixtureBackend& HEOS, const std::string& level) {
15 if (HEOS.get_mole_fractions_ref().empty()) {
16 throw ValueError("Mole fractions have not been set yet.");
17 }
18 bool debug = get_debug_level() > 0 || false;
19 if (HEOS.get_mole_fractions_ref().size() == 1) {
20 // It's a pure fluid
22 env.resize(HEOS.mole_fractions.size());
23
24 // Breakpoints in the phase envelope
25 std::vector<CoolPropDbl> Tbp, Qbp;
26 std::vector<std::size_t> Nbp;
27 // Triple point vapor up to Tmax_sat
28 Tbp.push_back(HEOS.Ttriple());
29 Qbp.push_back(1.0);
30 Nbp.push_back(40);
31
32 if (HEOS.is_pure()) {
33 // Up to critical point, back to triple point on the liquid side
34 Tbp.push_back(HEOS.T_critical() - 1e-3);
35 Qbp.push_back(0.0);
36 Tbp.push_back(HEOS.Ttriple());
37 Nbp.push_back(40);
38 } else {
39 SimpleState max_sat_T = HEOS.get_state("max_sat_T"), max_sat_p = HEOS.get_state("max_sat_p"), crit = HEOS.get_state("critical");
40 if (max_sat_T.rhomolar < crit.rhomolar && max_sat_T.rhomolar < max_sat_p.rhomolar) {
41 Tbp.push_back(HEOS.calc_Tmax_sat());
42 if (max_sat_p.rhomolar < crit.rhomolar) {
43 // psat_max density less than critical density
44 Qbp.push_back(1.0);
45 Qbp.push_back(1.0);
46 Tbp.push_back(max_sat_p.T);
47 Tbp.push_back(crit.T);
48 } else {
49 // Vapor line density less than critical density
50 Qbp.push_back(1.0);
51 Qbp.push_back(0.0);
52 Nbp.push_back(10);
53 Tbp.push_back(crit.T);
54 Tbp.push_back(max_sat_p.T);
55 }
56 Nbp.push_back(10);
57 Nbp.push_back(10);
58 Qbp.push_back(0.0);
59 Nbp.push_back(40);
60 Tbp.push_back(HEOS.Ttriple());
61 } else {
62 throw ValueError(format(""));
63 }
64 }
65
66 for (std::size_t i = 0; i < Tbp.size() - 1; ++i) {
67 CoolPropDbl Tmin = Tbp[i], Tmax = Tbp[i + 1];
68 std::size_t N = Nbp[i];
69 // Integer-indexed grid (cert-flp30-c): N samples from Tmin
70 // to Tmax inclusive — exactly the count the original
71 // is_in_closed_range / `T += (Tmax-Tmin)/(N-1)` targeted,
72 // without FP roundoff dropping or duplicating the endpoint.
73 const CoolPropDbl dT_pe = (Tmax - Tmin) / static_cast<CoolPropDbl>(N - 1);
74 for (std::size_t k_pe = 0; k_pe < N; ++k_pe) {
75 const CoolPropDbl T = Tmin + static_cast<CoolPropDbl>(k_pe) * dT_pe;
76 try {
77 HEOS.update(QT_INPUTS, Qbp[i], T);
78 } catch (...) {
79 continue;
80 }
81 if (Qbp[i] > 0.5) {
85 std::vector<CoolPropDbl>(1, 1.0), std::vector<CoolPropDbl>(1, 1.0));
86 } else {
90 std::vector<CoolPropDbl>(1, 1.0), std::vector<CoolPropDbl>(1, 1.0));
91 }
92 }
93 }
94 } else {
95 // It's a mixture
96 // --------------
97
98 // First we try to generate all the critical points. This
99 // is very useful
100 std::vector<CriticalState> critpts;
101 // try{
102 // critpts = HEOS.all_critical_points();
103 // //throw CoolProp::ValueError("critical points disabled");
104 // }
105 // catch(std::exception &e)
106 // {
107 // if (debug){ std::cout << e.what() << std::endl; }
108 // };
109
110 std::size_t failure_count = 0;
111 // Set some input options
114 io.Nstep_max = 20;
115
116 // Set the pressure to a low pressure
117 HEOS._p = get_config_double(PHASE_ENVELOPE_STARTING_PRESSURE_PA); //[Pa]
118 HEOS._Q = 1;
119
120 // Get an extremely rough guess by interpolation of ln(p) v. T curve where the limits are mole-fraction-weighted
122
123 // Use Wilson iteration to obtain updated guess for temperature
125
126 // Actually call the successive substitution solver
127 io.beta = 1;
128 SaturationSolvers::successive_substitution(HEOS, HEOS._Q, Tguess, HEOS._p, HEOS.mole_fractions, HEOS.K, io);
129
130 // Use the residual function based on x_i, T and rho' as independent variables. rho'' is specified
133
134 IO.bubble_point = false; // Do a "dewpoint" calculation all the way around
135 IO.x = io.x;
136 IO.y = HEOS.mole_fractions;
139 IO.T = io.T;
140 IO.p = io.p;
141 IO.Nstep_max = 30;
142
143 /*
144 IO.p = 1e5;
145 IO.rhomolar_liq = 17257.17130;
146 IO.rhomolar_vap = 56.80022884;
147 IO.T = 219.5200523;
148 IO.x[0] = 0.6689704673;
149 IO.x[1] = 0.3310295327;
150 */
151
152 //IO.rhomolar_liq *= 1.2;
153
155
156 NR.call(HEOS, IO.y, IO.x, IO);
157
158 // Switch to density imposed
160
161 bool dont_extrapolate = false;
162
164 env.resize(HEOS.mole_fractions.size());
165
166 std::size_t iter = 0, //< The iteration counter
167 iter0 = 0; //< A reference point for the counter, can be increased to go back to linear interpolation
168 CoolPropDbl factor = 1.05;
169
170 for (;;) {
171 top_of_loop:; // A goto label so that nested loops can break out to the top of this loop
172
173 if (failure_count > 5) {
174 // Stop since we are stuck at a bad point
175 //throw SolutionError("stuck");
176 return;
177 }
178
179 if (iter - iter0 > 0) {
180 IO.rhomolar_vap *= factor;
181 }
182 if (dont_extrapolate) {
183 // Reset the step to a reasonably small size
184 factor = 1.0001;
185 } else if (iter - iter0 == 2) {
186 IO.T = LinearInterp(env.rhomolar_vap, env.T, iter - 2, iter - 1, IO.rhomolar_vap);
187 IO.rhomolar_liq = LinearInterp(env.rhomolar_vap, env.rhomolar_liq, iter - 2, iter - 1, IO.rhomolar_vap);
188 for (std::size_t i = 0; i < IO.x.size() - 1; ++i) // First N-1 elements
189 {
190 IO.x[i] = LinearInterp(env.rhomolar_vap, env.x[i], iter - 2, iter - 1, IO.rhomolar_vap);
191 }
192 } else if (iter - iter0 == 3) {
193 IO.T = QuadInterp(env.rhomolar_vap, env.T, iter - 3, iter - 2, iter - 1, IO.rhomolar_vap);
194 IO.rhomolar_liq = QuadInterp(env.rhomolar_vap, env.rhomolar_liq, iter - 3, iter - 2, iter - 1, IO.rhomolar_vap);
195 for (std::size_t i = 0; i < IO.x.size() - 1; ++i) // First N-1 elements
196 {
197 IO.x[i] = QuadInterp(env.rhomolar_vap, env.x[i], iter - 3, iter - 2, iter - 1, IO.rhomolar_vap);
198 }
199 } else if (iter - iter0 > 3) {
200 // Use the spline interpolation class of Devin Lane: http://shiftedbits.org/2011/01/30/cubic-spline-interpolation/
201 Spline<double, double> spl_T(env.rhomolar_vap, env.T);
202 IO.T = spl_T.interpolate(IO.rhomolar_vap);
203 Spline<double, double> spl_rho(env.rhomolar_vap, env.rhomolar_liq);
204 IO.rhomolar_liq = spl_rho.interpolate(IO.rhomolar_vap);
205
206 // Check if there is a large deviation from linear interpolation - this suggests a step size that is so large that a minima or maxima of the interpolation function is crossed
207 CoolPropDbl T_linear = LinearInterp(env.rhomolar_vap, env.T, iter - 2, iter - 1, IO.rhomolar_vap);
208 if (std::abs((T_linear - IO.T) / IO.T) > 0.1) {
209 // Try again, but with a smaller step
210 IO.rhomolar_vap /= factor;
211 factor = 1 + (factor - 1) / 2;
212 failure_count++;
213 continue;
214 }
215 for (std::size_t i = 0; i < IO.x.size() - 1; ++i) // First N-1 elements
216 {
217 // Use the spline interpolation class of Devin Lane: http://shiftedbits.org/2011/01/30/cubic-spline-interpolation/
218 Spline<double, double> spl(env.rhomolar_vap, env.x[i]);
219 IO.x[i] = spl.interpolate(IO.rhomolar_vap);
220
221 if (IO.x[i] < 0 || IO.x[i] > 1) {
222 // Try again, but with a smaller step
223 IO.rhomolar_vap /= factor;
224 factor = 1 + (factor - 1) / 2;
225 failure_count++;
226 goto top_of_loop;
227 }
228 }
229 }
230
231 // The last mole fraction is sum of N-1 first elements
232 IO.x[IO.x.size() - 1] = 1 - std::accumulate(IO.x.begin(), IO.x.end() - 1, 0.0);
233
234 // Uncomment to check guess values for Newton-Raphson
235 //std::cout << "\t\tdv " << IO.rhomolar_vap << " dl " << IO.rhomolar_liq << " T " << IO.T << " x " << vec_to_string(IO.x, "%0.10Lg") << std::endl;
236
237 // Dewpoint calculation, liquid (x) is incipient phase
238 try {
239 NR.call(HEOS, IO.y, IO.x, IO);
240 if (!ValidNumber(IO.rhomolar_liq) || !ValidNumber(IO.p) || !ValidNumber(IO.T)) {
241 throw ValueError("Invalid number");
242 }
243 // Reject trivial solution
244 if (std::abs(IO.rhomolar_liq - IO.rhomolar_vap) < 1e-3) {
245 throw ValueError("Trivial solution");
246 }
247 // Reject negative presssure
248 if (IO.p < 0) {
249 throw ValueError("negative pressure");
250 }
251 // Reject steps with enormous steps in temperature
252 if (!env.T.empty() && std::abs(env.T[env.T.size() - 1] - IO.T) > 100) {
253 throw ValueError("Change in temperature too large");
254 }
255 } catch (std::exception& e) {
256 if (debug) {
257 std::cout << e.what() << '\n';
258 }
259 //std::cout << IO.T << " " << IO.p << std::endl;
260 // Try again, but with a smaller step
261 IO.rhomolar_vap /= factor;
262 if (iter < 4) {
263 throw ValueError(format("Unable to calculate at least 4 points in phase envelope; quitting"));
264 }
265 IO.rhomolar_liq = QuadInterp(env.rhomolar_vap, env.rhomolar_liq, iter - 3, iter - 2, iter - 1, IO.rhomolar_vap);
266 factor = 1 + (factor - 1) / 2;
267 failure_count++;
268 continue;
269 }
270
271 if (debug) {
272 std::cout << "dv " << IO.rhomolar_vap << " dl " << IO.rhomolar_liq << " T " << IO.T << " p " << IO.p << " hl " << IO.hmolar_liq
273 << " hv " << IO.hmolar_vap << " sl " << IO.smolar_liq << " sv " << IO.smolar_vap << " x " << vec_to_string(IO.x, "%0.10Lg")
274 << " Ns " << IO.Nsteps << " factor " << factor << '\n';
275 }
276 env.store_variables(IO.T, IO.p, IO.rhomolar_liq, IO.rhomolar_vap, IO.hmolar_liq, IO.hmolar_vap, IO.smolar_liq, IO.smolar_vap, IO.x, IO.y);
277
278 iter++;
279
280 // CoolPropDbl abs_rho_difference = std::abs((IO.rhomolar_liq - IO.rhomolar_vap)/IO.rhomolar_liq);
281
282 // bool next_crosses_crit = false;
283 // if (it_critpts != critpts.end() ){
284 // // Density at the next critical point
285 // double rhoc = (*it_critpts).rhomolar;
286 // // Next vapor density that will be used
287 // double rho_next = IO.rhomolar_vap*factor;
288 // // If the signs of the differences are different, you have crossed
289 // // the critical point density and have a phase inversion
290 // // on your hands
291 // next_crosses_crit = ((IO.rhomolar_vap-rhoc)*(rho_next-rhoc) < 0);
292 // }
293
294 // // Critical point jump
295 // if (next_crosses_crit || (abs_rho_difference < 0.01 && IO.rhomolar_liq > IO.rhomolar_vap)){
296 // //std::cout << "dv" << IO.rhomolar_vap << " dl " << IO.rhomolar_liq << " " << vec_to_string(IO.x, "%0.10Lg") << " " << vec_to_string(IO.y, "%0.10Lg") << std::endl;
297 // CoolPropDbl rhoc_approx = 0.5*IO.rhomolar_liq + 0.5*IO.rhomolar_vap;
298 // if (it_critpts != critpts.end() ){
299 // // We actually know what the critical point is to numerical precision
300 // rhoc_approx = (*it_critpts).rhomolar;
301 // }
302 // CoolPropDbl rho_vap_new = 1.05*rhoc_approx;
303 // // Linearly interpolate to get new guess for T
304 // IO.T = LinearInterp(env.rhomolar_vap,env.T,iter-2,iter-1,rho_vap_new);
305 // IO.rhomolar_liq = LinearInterp(env.rhomolar_vap, env.rhomolar_liq, iter-2, iter-1, rho_vap_new);
306 // for (std::size_t i = 0; i < IO.x.size()-1; ++i){
307 // IO.x[i] = CubicInterp(env.rhomolar_vap, env.x[i], iter-4, iter-3, iter-2, iter-1, rho_vap_new);
308 // }
309 // IO.x[IO.x.size()-1] = 1 - std::accumulate(IO.x.begin(), IO.x.end()-1, 0.0);
310 // factor = rho_vap_new/IO.rhomolar_vap;
311 // dont_extrapolate = true; // So that we use the mole fractions we calculated here instead of the extrapolated values
312 // if (debug) std::cout << "[CRIT jump] new values: dv " << rho_vap_new << " dl " << IO.rhomolar_liq << " " << vec_to_string(IO.x, "%0.10Lg") << " " << vec_to_string(IO.y, "%0.10Lg") << std::endl;
313 // iter0 = iter - 1; // Back to linear interpolation again
314 // continue;
315 // }
316
317 dont_extrapolate = false;
318 if (iter < 5) {
319 continue;
320 }
321 if (IO.Nsteps > 10) {
322 factor = 1 + (factor - 1) / 10;
323 } else if (IO.Nsteps > 5) {
324 factor = 1 + (factor - 1) / 3;
325 } else if (IO.Nsteps <= 4) {
326 factor = 1 + (factor - 1) * 2;
327 }
328 // Min step is 1.01
329 factor = std::max(factor, static_cast<CoolPropDbl>(1.01));
330 // As we approach the critical point, control step size
331 if (std::abs(IO.rhomolar_liq / IO.rhomolar_vap - 1) < 4) {
332 // Max step is 1.1
333 factor = std::min(factor, static_cast<CoolPropDbl>(1.1));
334 }
335
336 // Stop if the pressure is below the starting pressure
337 // or if the composition of one of the phases becomes almost pure
338 CoolPropDbl max_fraction = *std::max_element(IO.x.begin(), IO.x.end());
339 if (iter > 4 && (IO.p < env.p[0] || std::abs(1.0 - max_fraction) < 1e-9)) {
340 env.built = true;
341 env.closed = (IO.p < env.p[0]);
342 if (debug) {
343 std::cout << format("envelope built.\n");
344 std::cout << format("closest fraction to 1.0: distance %g\n", 1 - max_fraction);
345 }
346
347 // Now we refine the phase envelope to add some points in places that are still pretty rough
348 refine(HEOS, level);
349
350 return;
351 }
352
353 // Reset the failure counter
354 failure_count = 0;
355 }
356 }
357}
358
359void PhaseEnvelopeRoutines::refine(HelmholtzEOSMixtureBackend& HEOS, const std::string& level) {
360 bool debug = (get_debug_level() > 0 || false);
365 IO.bubble_point = false;
366 IO.y = HEOS.get_mole_fractions();
367
368 double acceptable_pdiff = 0.5;
369 double acceptable_rhodiff = 0.25;
370 int N = 5; // Number of steps of refining
371 if (level == "veryfine") {
372 acceptable_pdiff = 0.1;
373 acceptable_rhodiff = 0.1;
374 }
375 if (level == "none") {
376 return;
377 }
378 std::size_t i = 0;
379 do {
380
381 // Don't do anything if change in density and pressure is small enough
382 if ((std::abs(env.rhomolar_vap[i] / env.rhomolar_vap[i + 1] - 1) < acceptable_rhodiff)
383 && (std::abs(env.p[i] / env.p[i + 1] - 1) < acceptable_pdiff)) {
384 i++;
385 continue;
386 }
387
388 // Ok, now we are going to do some more refining in this step
389
390 // Vapor densities for this step, vapor density monotonically increasing
391 const double rhomolar_vap_start = env.rhomolar_vap[i], rhomolar_vap_end = env.rhomolar_vap[i + 1];
392
393 double factor = pow(rhomolar_vap_end / rhomolar_vap_start, 1.0 / N);
394
395 int failure_count = 0;
396 // Geometric density sweep (factor = (end/start)^(1/N)); ~N
397 // iterations, no FP accumulation issue worth converting.
398 for (double rhomolar_vap = rhomolar_vap_start * factor; rhomolar_vap < rhomolar_vap_end; rhomolar_vap *= factor) { // NOLINT(cert-flp30-c)
399 IO.rhomolar_vap = rhomolar_vap;
400 IO.x.resize(IO.y.size());
401 if (i < env.T.size() - 3) {
402 IO.T = CubicInterp(env.rhomolar_vap, env.T, i, i + 1, i + 2, i + 3, IO.rhomolar_vap);
403 IO.rhomolar_liq = CubicInterp(env.rhomolar_vap, env.rhomolar_liq, i, i + 1, i + 2, i + 3, IO.rhomolar_vap);
404 for (std::size_t j = 0; j < IO.x.size() - 1; ++j) { // First N-1 elements
405 IO.x[j] = CubicInterp(env.rhomolar_vap, env.x[j], i, i + 1, i + 2, i + 3, IO.rhomolar_vap);
406 }
407 } else {
408 IO.T = CubicInterp(env.rhomolar_vap, env.T, i, i - 1, i - 2, i - 3, IO.rhomolar_vap);
409 IO.rhomolar_liq = CubicInterp(env.rhomolar_vap, env.rhomolar_liq, i, i - 1, i - 2, i - 3, IO.rhomolar_vap);
410 for (std::size_t j = 0; j < IO.x.size() - 1; ++j) { // First N-1 elements
411 IO.x[j] = CubicInterp(env.rhomolar_vap, env.x[j], i, i - 1, i - 2, i - 3, IO.rhomolar_vap);
412 }
413 }
414 IO.x[IO.x.size() - 1] = 1 - std::accumulate(IO.x.begin(), IO.x.end() - 1, 0.0);
415 try {
416 NR.call(HEOS, IO.y, IO.x, IO);
417 if (!ValidNumber(IO.rhomolar_liq) || !ValidNumber(IO.p)) {
418 throw ValueError("invalid numbers");
419 }
421 IO.y, i + 1);
422 if (debug) {
423 std::cout << "dv " << IO.rhomolar_vap << " dl " << IO.rhomolar_liq << " T " << IO.T << " p " << IO.p << " hl " << IO.hmolar_liq
424 << " hv " << IO.hmolar_vap << " sl " << IO.smolar_liq << " sv " << IO.smolar_vap << " x "
425 << vec_to_string(IO.x, "%0.10Lg") << " Ns " << IO.Nsteps << '\n';
426 }
427 } catch (...) {
428 failure_count++;
429 continue;
430 }
431 i++;
432 }
433 // If we had a failure, we don't want to get stuck on this value of i,
434 // so we bump up one and keep moving
435 if (failure_count > 0) {
436 i++;
437 }
438 } while (i < env.T.size() - 1);
439}
440double PhaseEnvelopeRoutines::evaluate(const PhaseEnvelopeData& env, parameters output, parameters iInput1, double value1, std::size_t& i) {
441 int _i = static_cast<int>(i);
442 std::vector<double> const *x = nullptr, *y = nullptr;
443
444 switch (output) {
445 case iT:
446 y = &(env.T);
447 break;
448 case iP:
449 y = &(env.p);
450 break;
451 case iDmolar:
452 y = &(env.rhomolar_vap);
453 break;
454 case iHmolar:
455 y = &(env.hmolar_vap);
456 break;
457 case iSmolar:
458 y = &(env.smolar_vap);
459 break;
460 case iCpmolar:
461 y = &(env.cpmolar_vap);
462 break;
463 case iCvmolar:
464 y = &(env.cvmolar_vap);
465 break;
466 case iviscosity:
467 y = &(env.viscosity_vap);
468 break;
469 case iconductivity:
470 y = &(env.conductivity_vap);
471 break;
472 case ispeed_sound:
473 y = &(env.speed_sound_vap);
474 break;
475 default:
476 throw ValueError("Pointer to vector y is unset in is_inside");
477 }
478
479 double inval = value1;
480 switch (iInput1) {
481 case iT:
482 x = &(env.T);
483 break;
484 case iP:
485 x = &(env.lnp);
486 inval = log(value1);
487 break;
488 case iDmolar:
489 x = &(env.rhomolar_vap);
490 break;
491 case iHmolar:
492 x = &(env.hmolar_vap);
493 break;
494 case iSmolar:
495 x = &(env.smolar_vap);
496 break;
497 default:
498 throw ValueError("Pointer to vector x is unset in is_inside");
499 }
500 if (_i + 2 >= static_cast<int>(y->size())) {
501 _i--;
502 }
503 if (_i + 1 >= static_cast<int>(y->size())) {
504 _i--;
505 }
506 if (_i - 1 < 0) {
507 _i++;
508 }
509
510 double outval = CubicInterp(*x, *y, _i - 1, _i, _i + 1, _i + 2, inval);
511 i = static_cast<std::size_t>(_i);
512 return outval;
513}
515 // No finalization for pure or pseudo-pure fluids
516 if (HEOS.get_mole_fractions_ref().size() == 1) {
517 return;
518 }
519
520 enum maxima_points
521 {
522 PMAX_SAT = 0,
523 TMAX_SAT = 1
524 };
525 std::size_t imax = 0; // Index of the maximal temperature or pressure
526
528
529 // Find the index of the point with the highest temperature
530 std::size_t iTmax = std::distance(env.T.begin(), std::max_element(env.T.begin(), env.T.end()));
531
532 // Find the index of the point with the highest pressure
533 std::size_t ipmax = std::distance(env.p.begin(), std::max_element(env.p.begin(), env.p.end()));
534
535 // Determine if the phase envelope corresponds to a Type I mixture
536 // For now we consider a mixture to be Type I if the pressure at the
537 // end of the envelope is lower than max pressure pressure
538 env.TypeI = env.p[env.p.size() - 1] < env.p[ipmax];
539
540 // Approximate solutions for the maxima of the phase envelope
541 // See method in Gernert. We use our spline class to find the coefficients
542 if (env.TypeI) {
543 for (int imaxima = 0; imaxima <= 1; ++imaxima) {
544 maxima_points maxima;
545 if (imaxima == PMAX_SAT) {
546 maxima = PMAX_SAT;
547 } else if (imaxima == TMAX_SAT) {
548 maxima = TMAX_SAT;
549 } else {
550 throw ValueError("I don't understand your maxima index");
551 }
552
553 // Spline using the points around it
554 SplineClass spline;
555 if (maxima == TMAX_SAT) {
556 imax = iTmax;
557 if (iTmax > env.T.size() - 3) {
558 iTmax -= 2;
559 }
560 spline.add_4value_constraints(env.rhomolar_vap[iTmax - 1], env.rhomolar_vap[iTmax], env.rhomolar_vap[iTmax + 1],
561 env.rhomolar_vap[iTmax + 2], env.T[iTmax - 1], env.T[iTmax], env.T[iTmax + 1], env.T[iTmax + 2]);
562 } else {
563 imax = ipmax;
564 if (ipmax > env.p.size() - 3) {
565 ipmax -= 2;
566 }
567 spline.add_4value_constraints(env.rhomolar_vap[ipmax - 1], env.rhomolar_vap[ipmax], env.rhomolar_vap[ipmax + 1],
568 env.rhomolar_vap[ipmax + 2], env.p[ipmax - 1], env.p[ipmax], env.p[ipmax + 1], env.p[ipmax + 2]);
569 }
570 spline.build(); // y = a*rho^3 + b*rho^2 + c*rho + d
571
572 // Take derivative
573 // dy/drho = 3*a*rho^2 + 2*b*rho + c
574 // Solve quadratic for derivative to find rho
575 int Nsoln = 0;
576 double rho0 = _HUGE, rho1 = _HUGE, rho2 = _HUGE;
577 solve_cubic(0, 3 * spline.a, 2 * spline.b, spline.c, Nsoln, rho0, rho1, rho2);
578
580 IO.rhomolar_vap = _HUGE;
581 // Find the correct solution
582 if (Nsoln == 1) {
583 IO.rhomolar_vap = rho0;
584 } else if (Nsoln == 2) {
585 if (is_in_closed_range(env.rhomolar_vap[imax - 1], env.rhomolar_vap[imax + 1], rho0)) {
586 IO.rhomolar_vap = rho0;
587 }
588 if (is_in_closed_range(env.rhomolar_vap[imax - 1], env.rhomolar_vap[imax + 1], rho1)) {
589 IO.rhomolar_vap = rho1;
590 }
591 } else {
592 throw ValueError("More than 2 solutions found");
593 }
594
595 class solver_resid : public FuncWrapper1D
596 {
597 public:
598 std::size_t imax;
599 maxima_points maxima;
603 solver_resid(HelmholtzEOSMixtureBackend& HEOS, std::size_t imax, maxima_points maxima) : maxima(maxima) {
604 this->HEOS = &HEOS, this->imax = imax;
605 };
606 double call(double rhomolar_vap) override {
607 PhaseEnvelopeData& env = HEOS->PhaseEnvelope;
609 IO.bubble_point = false;
610 IO.rhomolar_vap = rhomolar_vap;
611 IO.y = HEOS->get_mole_fractions();
612 IO.x = IO.y; // Just to give it good size
613 if (imax >= env.T.size() - 2) {
614 imax -= 2;
615 }
616 IO.T = CubicInterp(env.rhomolar_vap, env.T, imax - 1, imax, imax + 1, imax + 2, IO.rhomolar_vap);
617 IO.rhomolar_liq = CubicInterp(env.rhomolar_vap, env.rhomolar_liq, imax - 1, imax, imax + 1, imax + 2, IO.rhomolar_vap);
618 for (std::size_t i = 0; i < IO.x.size() - 1; ++i) // First N-1 elements
619 {
620 IO.x[i] = CubicInterp(env.rhomolar_vap, env.x[i], imax - 1, imax, imax + 1, imax + 2, IO.rhomolar_vap);
621 }
622 IO.x[IO.x.size() - 1] = 1 - std::accumulate(IO.x.begin(), IO.x.end() - 1, 0.0);
623 NR.call(*HEOS, IO.y, IO.x, IO);
624 if (maxima == TMAX_SAT) {
625 return NR.dTsat_dPsat;
626 } else {
627 return NR.dPsat_dTsat;
628 }
629 };
630 };
631
632 solver_resid resid(HEOS, imax, maxima);
633 try {
634 double rho = Brent(resid, IO.rhomolar_vap * 0.95, IO.rhomolar_vap * 1.05, DBL_EPSILON, 1e-12, 100);
635
636 // If maxima point is greater than density at point from the phase envelope, increase index by 1 so that the
637 // insertion will happen *after* the point in the envelope since density is monotonically increasing.
638 if (rho > env.rhomolar_vap[imax]) {
639 imax++;
640 }
641
642 env.insert_variables(resid.IO.T, resid.IO.p, resid.IO.rhomolar_liq, resid.IO.rhomolar_vap, resid.IO.hmolar_liq, resid.IO.hmolar_vap,
643 resid.IO.smolar_liq, resid.IO.smolar_vap, resid.IO.x, resid.IO.y, imax);
644 } catch (...) { // NOLINT(bugprone-empty-catch)
645 // Don't do the insertion
646 }
647 }
648 }
649
650 // Find the index of the point with the highest temperature
651 env.iTsat_max = std::distance(env.T.begin(), std::max_element(env.T.begin(), env.T.end()));
652
653 // Find the index of the point with the highest pressure
654 env.ipsat_max = std::distance(env.p.begin(), std::max_element(env.p.begin(), env.p.end()));
655}
656
657std::vector<std::pair<std::size_t, std::size_t>> PhaseEnvelopeRoutines::find_intersections(const PhaseEnvelopeData& env, parameters iInput,
658 double value) {
659 std::vector<std::pair<std::size_t, std::size_t>> intersections;
660
661 for (std::size_t i = 0; i < env.p.size() - 1; ++i) {
662 bool matched = false;
663 switch (iInput) {
664 case iP:
665 if (is_in_closed_range(env.p[i], env.p[i + 1], value)) {
666 matched = true;
667 }
668 break;
669 case iT:
670 if (is_in_closed_range(env.T[i], env.T[i + 1], value)) {
671 matched = true;
672 }
673 break;
674 case iHmolar:
675 if (is_in_closed_range(env.hmolar_vap[i], env.hmolar_vap[i + 1], value)) {
676 matched = true;
677 }
678 break;
679 case iSmolar:
680 if (is_in_closed_range(env.smolar_vap[i], env.smolar_vap[i + 1], value)) {
681 matched = true;
682 }
683 break;
684 default:
685 throw ValueError(format("bad index to find_intersections"));
686 }
687
688 if (matched) {
689 intersections.emplace_back(i, i + 1);
690 }
691 }
692 return intersections;
693}
695 std::size_t& iclosest, SimpleState& closest_state) {
696 // Find the indices that bound the solution(s)
697 std::vector<std::pair<std::size_t, std::size_t>> intersections = find_intersections(env, iInput1, value1);
698
699 if (get_debug_level() > 5) {
700 std::cout << format("is_inside(%Lg,%Lg); iTsat_max=%d; ipsat_max=%d\n", value1, value2, env.iTsat_max, env.ipsat_max);
701 }
702 // Check whether input is above max value
703 if (iInput1 == iT && 0 < env.iTsat_max && env.iTsat_max < env.T.size() && value1 > env.T[env.iTsat_max]) {
704 return false;
705 }
706 if (iInput1 == iP && 0 < env.ipsat_max && env.ipsat_max < env.p.size() && value1 > env.p[env.ipsat_max]) {
707 return false;
708 }
709
710 // If number of intersections is 0, input is out of range, quit
711 if (intersections.size() == 0) {
712 throw ValueError(format("Input is out of range for primary value [%Lg], inputs were (%s,%Lg,%s,%Lg); no intersections found", value1,
713 get_parameter_information(iInput1, "short").c_str(), value1, get_parameter_information(iInput2, "short").c_str(),
714 value2));
715 }
716
717 // If number of intersections is 1, input will be determined based on the single intersection
718 // Need to know if values increase or decrease to the right of the intersection point
719 if (intersections.size() % 2 != 0) {
720 throw ValueError("Input is weird; odd number of intersections found");
721 }
722
723 // If number of intersections is even, might be a bound
724 if (intersections.size() % 2 == 0) {
725 if (intersections.size() != 2) {
726 throw ValueError("for now only even value accepted is 2");
727 }
728 std::vector<std::size_t> other_indices(4, 0);
729 std::vector<double> const* y = nullptr;
730 std::vector<double> other_values(4, 0);
731 other_indices[0] = intersections[0].first;
732 other_indices[1] = intersections[0].second;
733 other_indices[2] = intersections[1].first;
734 other_indices[3] = intersections[1].second;
735
736 switch (iInput2) {
737 case iT:
738 y = &(env.T);
739 break;
740 case iP:
741 y = &(env.p);
742 break;
743 case iDmolar:
744 y = &(env.rhomolar_vap);
745 break;
746 case iHmolar:
747 y = &(env.hmolar_vap);
748 break;
749 case iSmolar:
750 y = &(env.smolar_vap);
751 break;
752 default:
753 throw ValueError("Pointer to vector y is unset in is_inside");
754 }
755
756 other_values[0] = (*y)[other_indices[0]];
757 other_values[1] = (*y)[other_indices[1]];
758 other_values[2] = (*y)[other_indices[2]];
759 other_values[3] = (*y)[other_indices[3]];
760
761 CoolPropDbl min_other = *(std::min_element(other_values.begin(), other_values.end()));
762 CoolPropDbl max_other = *(std::max_element(other_values.begin(), other_values.end()));
763
764 if (get_debug_level() > 5) {
765 std::cout << format("is_inside: min: %Lg max: %Lg val: %Lg\n", min_other, max_other, value2);
766 }
767
768 // If by using the outer bounds of the second variable, we are outside the range,
769 // then the value is definitely not inside the phase envelope and we don't need to
770 // do any more analysis.
771 if (!is_in_closed_range(min_other, max_other, value2)) {
772 std::vector<CoolPropDbl> d(4, 0);
773 d[0] = std::abs(other_values[0] - value2);
774 d[1] = std::abs(other_values[1] - value2);
775 d[2] = std::abs(other_values[2] - value2);
776 d[3] = std::abs(other_values[3] - value2);
777
778 // Index of minimum distance in the other_values vector
779 std::size_t idist = std::distance(d.begin(), std::min_element(d.begin(), d.end()));
780 // Index of closest point in the phase envelope
781 iclosest = other_indices[idist];
782
783 // Get the state for the point which is closest to the desired value - this
784 // can be used as a bounding value in the outer single-phase flash routine
785 // since you know (100%) that it is a good bound
786 closest_state.T = env.T[iclosest];
787 closest_state.p = env.p[iclosest];
788 closest_state.rhomolar = env.rhomolar_vap[iclosest];
789 closest_state.hmolar = env.hmolar_vap[iclosest];
790 closest_state.smolar = env.smolar_vap[iclosest];
791 closest_state.Q = env.Q[iclosest];
792
793 if (get_debug_level() > 5) {
794 std::cout << format("is_inside: it is not inside") << '\n';
795 }
796 return false;
797 } else {
798 // Now we have to do a saturation flash call in order to determine whether or not we are inside the phase envelope or not
799
800 // First we can interpolate using the phase envelope to get good guesses for the necessary values
801 CoolPropDbl y1 = evaluate(env, iInput2, iInput1, value1, intersections[0].first);
802 CoolPropDbl y2 = evaluate(env, iInput2, iInput1, value1, intersections[1].first);
803 if (is_in_closed_range(y1, y2, value2)) {
804 if (std::abs(y1 - value2) < std::abs(y2 - value2)) {
805 iclosest = intersections[0].first;
806 } else {
807 iclosest = intersections[1].first;
808 }
809 // Get the state for the point which is closest to the desired value - this
810 // can be used as a bounding value in the outer single-phase flash routine
811 // since you know (100%) that it is a good bound
812 closest_state.T = env.T[iclosest];
813 closest_state.p = env.p[iclosest];
814 closest_state.rhomolar = env.rhomolar_vap[iclosest];
815 closest_state.hmolar = env.hmolar_vap[iclosest];
816 closest_state.smolar = env.smolar_vap[iclosest];
817 closest_state.Q = env.Q[iclosest];
818 return true;
819 } else {
820 return false;
821 }
822 }
823 } else {
824 throw ValueError("You have a funny number of intersections in is_inside");
825 }
826}
827
828} /* namespace CoolProp */
829
830#endif