teqp 0.22.0
Loading...
Searching...
No Matches
multifluid.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "nlohmann/json.hpp"
4
5#include <Eigen/Dense>
6#include <string>
7#include <cmath>
8#include <optional>
9#include <variant>
10
11#include "teqp/types.hpp"
12#include "teqp/constants.hpp"
13#include "teqp/filesystem.hpp"
14#include "teqp/json_tools.hpp"
15#include "teqp/exceptions.hpp"
16
17#include "RPinterop/interop.hpp"
18
19#if defined(TEQP_MULTICOMPLEX_ENABLED)
20#include "MultiComplex/MultiComplex.hpp"
21#endif
22
26
27#include <boost/algorithm/string/join.hpp>
28
29#if defined(TEQP_MULTICOMPLEX_ENABLED)
30// See https://eigen.tuxfamily.org/dox/TopicCustomizing_CustomScalar.html
31namespace Eigen {
32 template<typename TN> struct NumTraits<mcx::MultiComplex<TN>> : NumTraits<double> // permits to get the epsilon, dummy_precision, lowest, highest functions
33 {
34 enum {
35 IsComplex = 1,
36 IsInteger = 0,
37 IsSigned = 1,
38 RequireInitialization = 1,
39 ReadCost = 1,
40 AddCost = 3,
41 MulCost = 3
42 };
43 };
44}
45#endif
46
47namespace teqp{
48
49template<typename EOSCollection>
51
52private:
53 const EOSCollection EOSs;
54public:
55 CorrespondingStatesContribution(EOSCollection&& EOSs) : EOSs(EOSs) {};
56
57 auto size() const { return EOSs.size(); }
58
59 template<typename TauType, typename DeltaType, typename MoleFractions>
60 auto alphar(const TauType& tau, const DeltaType& delta, const MoleFractions& molefracs) const {
61 using resulttype = std::common_type_t<decltype(tau), decltype(molefracs[0]), decltype(delta)>; // Type promotion, without the const-ness
62 resulttype alphar = 0.0;
63 auto N = molefracs.size();
64 for (auto i = 0U; i < N; ++i) {
65 alphar += molefracs[i] * EOSs[i].alphar(tau, delta);
66 }
67 return alphar;
68 }
69
70 template<typename TauType, typename DeltaType>
71 auto alphari(const TauType& tau, const DeltaType& delta, std::size_t i) const {
72 return EOSs[i].alphar(tau, delta);
73 }
74
75 auto get_EOS(std::size_t i) const{
76 return EOSs[i];
77 }
78};
79
80template<typename FCollection, typename DepartureFunctionCollection>
82
83private:
84 const FCollection F;
85 const DepartureFunctionCollection funcs;
86public:
87 DepartureContribution(FCollection&& F, DepartureFunctionCollection&& funcs) : F(F), funcs(funcs) {};
88
89 const auto& get_F() const { return F; }
90
91 template<typename TauType, typename DeltaType, typename MoleFractions>
92 auto alphar(const TauType& tau, const DeltaType& delta, const MoleFractions& molefracs) const {
93 using resulttype = std::decay_t<std::common_type_t<decltype(tau), decltype(molefracs[0]), decltype(delta)>>; // Type promotion, without the const-ness
94 resulttype alphar = 0.0;
95 std::size_t N = molefracs.size();
96 for (auto i = 0U; i < N; ++i) {
97 for (auto j = i+1; j < N; ++j) {
98 alphar += molefracs[i] * molefracs[j] * F(i, j) * funcs[i][j].alphar(tau, delta);
99 }
100 }
101 return alphar;
102 }
103
105 template<typename TauType, typename DeltaType>
106 auto get_alpharij(const std::size_t i, const std::size_t j, const TauType& tau, const DeltaType& delta) const {
107 std::size_t N = funcs.size();
108 if (i < 0 || j < 0){
109 throw teqp::InvalidArgument("i or j is negative");
110 }
111 if (i >= N || j >= N){
112 throw teqp::InvalidArgument("i or j is invalid; size is " + std::to_string(N));
113 }
114 return forceeval(funcs[i][j].alphar(tau, delta));
115 }
116};
117
118template<typename CorrespondingTerm, typename DepartureTerm>
120
121private:
122 std::string meta = "";
123public:
125 const CorrespondingTerm corr;
126 const DepartureTerm dep;
129
130 template<class VecType>
131 auto R(const VecType& molefracs) const {
132 return std::visit([&molefracs](const auto& el){ return el.get_R(molefracs); }, Rcalc);
133 }
134
136 void set_meta(const std::string& m) { meta = m; }
138 auto get_meta() const { return meta; }
140 const std::variant<double, std::string> get_BIP(const std::size_t &i, const std::size_t &j, const std::string& key) const{
141 if (key == "F" || key == "Fij"){
142 auto F = dep.get_F();
143 if (0 <= i && i < F.rows() && 0 <= j && j < F.cols()){
144 return F(i,j);
145 }
146 }
147 return redfunc.get_BIP(i, j, key);
148 }
149
151
152 template<typename TType, typename RhoType>
153 auto alphar(TType T,
154 const RhoType& rhovec,
155 const std::optional<typename RhoType::value_type> rhotot = std::nullopt) const
156 {
157 typename RhoType::value_type rhotot_ = (rhotot.has_value()) ? rhotot.value() : std::accumulate(std::begin(rhovec), std::end(rhovec), (decltype(rhovec[0]))0.0);
158 auto molefrac = rhovec / rhotot_;
159 return alphar(T, rhotot_, molefrac);
160 }
161
162 template<typename TType, typename RhoType, typename MoleFracType>
163 auto alphar(const TType &T,
164 const RhoType &rho,
165 const MoleFracType& molefrac) const
166 {
167 if (static_cast<std::size_t>(molefrac.size()) != corr.size()){
168 throw teqp::InvalidArgument("Wrong size of mole fractions; "+std::to_string(corr.size()) + " are loaded but "+std::to_string(molefrac.size()) + " were provided");
169 }
170 auto delta = forceeval(rho / redfunc.get_rhor(molefrac));
171 auto tau = forceeval(redfunc.get_Tr(molefrac) / T);
172 if (molefrac.size() == 1){
173 // Short circuit for pure fluids and avoid mole fractions and departure terms
174 return corr.alphari(tau, delta, 0);
175 }
176 return forceeval(corr.alphar(tau, delta, molefrac) + dep.alphar(tau, delta, molefrac));
177 }
178
179 template<typename TType, typename RhoType, typename MoleFracType>
180 auto alphar_taudelta(const TType &tau,
181 const RhoType &delta,
182 const MoleFracType& molefrac) const
183 {
184 if (static_cast<std::size_t>(molefrac.size()) != corr.size()){
185 throw teqp::InvalidArgument("Wrong size of mole fractions; "+std::to_string(corr.size()) + " are loaded but "+std::to_string(molefrac.size()) + " were provided");
186 }
187 if (molefrac.size() == 1){
188 return corr.alphari(tau, delta, 0U);
189 }
190 return forceeval(corr.alphar(tau, delta, molefrac) + dep.alphar(tau, delta, molefrac));
191 }
192
193 template<typename TType, typename RhoType>
194 inline auto alphar_taudeltai(const TType &tau, const RhoType &delta, const std::size_t i) const
195 {
196 return corr.alphari(tau, delta, i);
197 }
198};
199
200
201/***
202* \brief Get the JSON data structure for a given departure function
203* \param name The name (or alias) of the departure function to be looked up
204* \parm path The root path to the fluid data, or alternatively, the path to the json file directly
205*/
206inline auto get_departure_json(const std::string& name, const std::string& path) {
207 std::string filepath = std::filesystem::is_regular_file(path) ? path : path + "/dev/mixtures/mixture_departure_functions.json";
208 nlohmann::json j = load_a_JSON_file(filepath);
209 std::string js = j.dump(2);
210 // First pass, direct name lookup
211 for (auto& el : j) {
212 if (el.at("Name") == name) {
213 return el;
214 }
215 }
216 // Second pass, iterate over aliases
217 for (auto& el : j) {
218 for (auto &alias : el.at("aliases")) {
219 if (alias == name) {
220 return el;
221 }
222 }
223 }
224 throw std::invalid_argument("Could not match the name: " + name + "when looking up departure function");
225}
226
227inline auto build_departure_function(const nlohmann::json& j) {
228 auto build_power = [&](auto term, auto& dep) {
229 std::size_t N = term["n"].size();
230
231 // Don't add a departure function if there are no coefficients provided
232 if (N == 0) {
233 return;
234 }
235
237
238 auto eigorzero = [&term, &N](const std::string& name) -> Eigen::ArrayXd {
239 if (!term[name].empty()) {
240 return toeig(term[name]);
241 }
242 else {
243 return Eigen::ArrayXd::Zero(N);
244 }
245 };
246
247
248 eos.n = eigorzero("n");
249 eos.t = eigorzero("t");
250 eos.d = eigorzero("d");
251
252 Eigen::ArrayXd c(N), l(N); c.setZero();
253
254 int Nlzero = 0, Nlnonzero = 0;
255 bool contiguous_lzero = false;
256
257 if (term["l"].empty()) {
258 // exponential part not included
259 l.setZero();
260 if (!all_same_length(term, { "n","t","d" })) {
261 throw std::invalid_argument("Lengths are not all identical in polynomial-like term");
262 }
263 }
264 else {
265 if (!all_same_length(term, { "n","t","d","l"})) {
266 throw std::invalid_argument("Lengths are not all identical in exponential term");
267 }
268 l = toeig(term["l"]);
269 // l is included, use it to build c; c_i = 1 if l_i > 0, zero otherwise
270 for (auto i = 0; i < c.size(); ++i) {
271 if (l[i] > 0) {
272 c[i] = 1.0;
273 }
274 }
275
276 // See how many of the first entries have zero values for l_i
277 contiguous_lzero = (l[0] == 0);
278 for (auto i = 0; i < c.size(); ++i) {
279 if (l[i] == 0) {
280 Nlzero++;
281 }
282 }
283 }
284 Nlnonzero = static_cast<int>(l.size()) - Nlzero;
285
286 if (contiguous_lzero && (l.tail(Nlnonzero) == 0).any()) {
287 throw std::invalid_argument("If l_i has zero and non-zero values, the zero values need to come first");
288 }
289
290 eos.c = c;
291 eos.l = l;
292
293 eos.l_i = eos.l.cast<int>();
294
295 if (Nlzero + Nlnonzero != l.size()) {
296 throw std::invalid_argument("Somehow the l lengths don't add up");
297 }
298
299
300 if (((eos.l_i.cast<double>() - eos.l).cwiseAbs() > 0.0).any()) {
301 throw std::invalid_argument("Non-integer entry in l found");
302 }
303
304 // If a contiguous portion of the terms have values of l_i that are zero
305 // it is computationally advantageous to break up the evaluation into
306 // part that has just the n_i*tau^t_i*delta^d_i and the part with the
307 // exponential term exp(-delta^l_i)
308 if (l.sum() == 0) {
309 // No l term at all, just polynomial
310 JustPowerEOSTerm poly;
311 poly.n = eos.n;
312 poly.t = eos.t;
313 poly.d = eos.d;
314 dep.add_term(poly);
315 }
316 else if (l.sum() > 0 && contiguous_lzero){
317 JustPowerEOSTerm poly;
318 poly.n = eos.n.head(Nlzero);
319 poly.t = eos.t.head(Nlzero);
320 poly.d = eos.d.head(Nlzero);
321 dep.add_term(poly);
322
324 e.n = eos.n.tail(Nlnonzero);
325 e.t = eos.t.tail(Nlnonzero);
326 e.d = eos.d.tail(Nlnonzero);
327 e.c = eos.c.tail(Nlnonzero);
328 e.l = eos.l.tail(Nlnonzero);
329 e.l_i = eos.l_i.tail(Nlnonzero);
330 dep.add_term(PowerEOSTerm(e));
331 }
332 else {
333 // Don't try to get too clever, just add the departure term
334 dep.add_term(eos);
335 }
336 };
337
338 auto build_doubleexponential = [&](auto& term, auto& dep) {
339 if (!all_same_length(term, { "n","t","d","ld","gd","lt","gt" })) {
340 throw std::invalid_argument("Lengths are not all identical in double exponential term");
341 }
343 eos.n = toeig(term.at("n"));
344 eos.t = toeig(term.at("t"));
345 eos.d = toeig(term.at("d"));
346 eos.ld = toeig(term.at("ld"));
347 eos.gd = toeig(term.at("gd"));
348 eos.lt = toeig(term.at("lt"));
349 eos.gt = toeig(term.at("gt"));
350 eos.ld_i = eos.ld.cast<int>();
351 dep.add_term(eos);
352 };
353 auto build_Chebyshev2D = [&](auto& term, auto& dep) {
355 int Ntau = term.at("Ntau"); // Degree in tau (there will be Ntau+1 coefficients in the tau direction)
356 int Ndelta = term.at("Ndelta"); // Degree in delta (there will be Ndelta+1 coefficients in the delta direction)
357 Eigen::ArrayXd c = toeig(term.at("a"));
358 if ((Ntau + 1)*(Ndelta + 1) != c.size()){
359 throw std::invalid_argument("Provided length [" + std::to_string(c.size()) + "] is not equal to (Ntau+1)*(Ndelta+1)");
360 }
361 eos.a = c.reshaped(Ntau+1, Ndelta+1).eval(); // All in one long array, then reshaped
362 eos.taumin = term.at("taumin");
363 eos.taumax = term.at("taumax");
364 eos.deltamin = term.at("deltamin");
365 eos.deltamax = term.at("deltamax");
366 dep.add_term(eos);
367 };
368 //auto build_gaussian = [&](auto& term) {
369 // GaussianEOSTerm eos;
370 // eos.n = toeig(term["n"]);
371 // eos.t = toeig(term["t"]);
372 // eos.d = toeig(term["d"]);
373 // eos.eta = toeig(term["eta"]);
374 // eos.beta = toeig(term["beta"]);
375 // eos.gamma = toeig(term["gamma"]);
376 // eos.epsilon = toeig(term["epsilon"]);
377 // if (!all_same_length(term, { "n","t","d","eta","beta","gamma","epsilon" })) {
378 // throw std::invalid_argument("Lengths are not all identical in Gaussian term");
379 // }
380 // return eos;
381 //};
382 auto build_GERG2004 = [&](const auto& term, auto& dep) {
383 if (!all_same_length(term, { "n","t","d","eta","beta","gamma","epsilon" })) {
384 throw std::invalid_argument("Lengths are not all identical in GERG term");
385 }
386 int Npower = term["Npower"];
387 auto NGERG = static_cast<int>(term["n"].size()) - Npower;
388
390 eos.n = toeig(term["n"]).head(Npower);
391 eos.t = toeig(term["t"]).head(Npower);
392 eos.d = toeig(term["d"]).head(Npower);
393 if (term.contains("l")) {
394 eos.l = toeig(term["l"]).head(Npower);
395 }
396 else {
397 eos.l = 0.0 * eos.n;
398 }
399 eos.c = (eos.l > 0).cast<int>().cast<double>();
400 eos.l_i = eos.l.cast<int>();
401 dep.add_term(PowerEOSTerm(eos));
402
404 e.n = toeig(term["n"]).tail(NGERG);
405 e.t = toeig(term["t"]).tail(NGERG);
406 e.d = toeig(term["d"]).tail(NGERG);
407 e.eta = toeig(term["eta"]).tail(NGERG);
408 e.beta = toeig(term["beta"]).tail(NGERG);
409 e.gamma = toeig(term["gamma"]).tail(NGERG);
410 e.epsilon = toeig(term["epsilon"]).tail(NGERG);
411 dep.add_term(e);
412 };
413 auto build_GaussianExponential = [&](const auto& term, auto& dep) {
414 if (!all_same_length(term, { "n","t","d","eta","beta","gamma","epsilon" })) {
415 throw std::invalid_argument("Lengths are not all identical in Gaussian+Exponential term");
416 }
417 int Npower = term["Npower"];
418 auto NGauss = static_cast<int>(term["n"].size()) - Npower;
419
421 eos.n = toeig(term["n"]).head(Npower);
422 eos.t = toeig(term["t"]).head(Npower);
423 eos.d = toeig(term["d"]).head(Npower);
424 if (term.contains("l")) {
425 eos.l = toeig(term["l"]).head(Npower);
426 }
427 else {
428 eos.l = 0.0 * eos.n;
429 }
430 eos.c = (eos.l > 0).cast<int>().cast<double>();
431 eos.l_i = eos.l.cast<int>();
432 dep.add_term(PowerEOSTerm(eos));
433
435 e.n = toeig(term["n"]).tail(NGauss);
436 e.t = toeig(term["t"]).tail(NGauss);
437 e.d = toeig(term["d"]).tail(NGauss);
438 e.eta = toeig(term["eta"]).tail(NGauss);
439 e.beta = toeig(term["beta"]).tail(NGauss);
440 e.gamma = toeig(term["gamma"]).tail(NGauss);
441 e.epsilon = toeig(term["epsilon"]).tail(NGauss);
442 dep.add_term(e);
443 };
444
445 std::string type = j.at("type");
446 DepartureTerms dep;
447 if (type == "Exponential") {
448 build_power(j, dep);
449 }
450 else if (type == "DoubleExponential") {
451 build_doubleexponential(j, dep);
452 }
453 else if (type == "GERG-2004" || type == "GERG-2008") {
454 build_GERG2004(j, dep);
455 }
456 else if (type == "Gaussian+Exponential") {
457 build_GaussianExponential(j, dep);
458 }
459 else if (type == "Chebyshev2D") {
460 build_Chebyshev2D(j, dep);
461 }
462 else if (type == "none") {
463 dep.add_term(NullEOSTerm());
464 }
465 else {
466
467 std::vector<std::string> options = { "Exponential","GERG-2004","GERG-2008","Gaussian+Exponential", "none", "DoubleExponential","Chebyshev2D"};
468 throw std::invalid_argument("Bad departure term type: " + type + ". Options are {" + boost::algorithm::join(options, ",") + "}");
469 }
470 return dep;
471}
472
473inline auto get_departure_function_matrix(const nlohmann::json& depcollection, const nlohmann::json& BIPcollection, const std::vector<std::string>& components, const nlohmann::json& flags) {
474
475 // Allocate the matrix with default models
476 std::vector<std::vector<DepartureTerms>> funcs(components.size()); for (auto i = 0U; i < funcs.size(); ++i) { funcs[i].resize(funcs.size()); }
477
478 // Load the collection of data on departure functions
479
480 auto get_departure_json = [&depcollection](const std::string& Name) {
481 for (auto& el : depcollection) {
482 if (el["Name"] == Name) { return el; }
483 }
484 throw std::invalid_argument("Bad departure function name: "+Name);
485 };
486
487 auto funcsmeta = nlohmann::json::object();
488
489 for (auto i = 0U; i < funcs.size(); ++i) {
490 std::string istr = std::to_string(i);
491 if (funcsmeta.contains(istr)) { funcsmeta[istr] = {}; }
492 for (auto j = i + 1; j < funcs.size(); ++j) {
493 std::string jstr = std::to_string(j);
494 auto [BIP, swap_needed] = reducing::get_BIPdep(BIPcollection, { components[i], components[j] }, flags);
495 std::string funcname = BIP.contains("function") ? BIP["function"] : "";
496 nlohmann::json jj;
497 if (!funcname.empty()) {
498 if (depcollection.empty()){
499 throw teqp::InvalidArgument("No departure functions were loaded, unable to select requested function: " + funcname);
500 }
501 jj = get_departure_json(funcname);
502 funcs[i][j] = build_departure_function(jj);
503 funcs[j][i] = build_departure_function(jj);
504 }
505 else {
506 funcs[i][j].add_term(NullEOSTerm());
507 funcs[j][i].add_term(NullEOSTerm());
508 }
509 funcsmeta[istr][jstr] = { {"departure", jj}, {"BIP", BIP} };
510 funcsmeta[istr][jstr]["BIP"]["swap_needed"] = swap_needed;
511 }
512 }
513 return std::make_tuple(funcs, funcsmeta);
514}
515
516inline auto get_EOS_terms(const nlohmann::json& j)
517{
518 auto alphar = j["EOS"][0]["alphar"];
519
520 if (alphar.empty()){
521 throw teqp::InvalidArgument("alphar array cannot be empty");
522 }
523
524 // First check whether term type is allowed
525 const std::vector<std::string> allowed_types = { "ResidualHelmholtzPower", "ResidualHelmholtzGaussian", "ResidualHelmholtzNonAnalytic","ResidualHelmholtzGaoB", "ResidualHelmholtzLemmon2005", "ResidualHelmholtzExponential", "ResidualHelmholtzDoubleExponential","ResidualHelmholtzGenericCubic","ResidualHelmholtzPCSAFTGrossSadowski2001" };
526
527 auto isallowed = [&](const auto& conventional_types, const std::string& name) {
528 for (auto& a : conventional_types) { if (name == a) { return true; }; } return false;
529 };
530
531 for (auto& term : alphar) {
532 std::string type = term["type"];
533 if (!isallowed(allowed_types, type)) {
534 std::string a = allowed_types[0]; for (auto i = 1U; i < allowed_types.size(); ++i) { a += "," + allowed_types[i]; }
535 throw std::invalid_argument("Bad type:" + type + "; allowed types are: {" + a + "}");
536 }
537 }
538
539 EOSTerms container;
540
541 auto build_power = [&](auto term, auto & container) {
542 std::size_t N = term["n"].size();
543
545
546 auto eigorzero = [&term, &N](const std::string& name) -> Eigen::ArrayXd {
547 if (!term[name].empty()) {
548 return toeig(term[name]);
549 }
550 else {
551 return Eigen::ArrayXd::Zero(N);
552 }
553 };
554
555
556 eos.n = eigorzero("n");
557 eos.t = eigorzero("t");
558 eos.d = eigorzero("d");
559
560 Eigen::ArrayXd c(N), l(N); c.setZero();
561 int Nlzero = 0, Nlnonzero = 0;
562 bool contiguous_lzero;
563 if (term["l"].empty()) {
564 // exponential part not included
565 l.setZero();
566 }
567 else {
568 l = toeig(term["l"]);
569 // l is included, use it to build c; c_i = 1 if l_i > 0, zero otherwise
570 for (auto i = 0; i < c.size(); ++i) {
571 if (l[i] > 0) {
572 c[i] = 1.0;
573 }
574 }
575
576 // See how many of the first entries have zero values for l_i
577 contiguous_lzero = (l[0] == 0);
578 for (auto i = 0; i < c.size(); ++i) {
579 if (l[i] == 0) {
580 Nlzero++;
581 }
582 }
583 }
584 Nlnonzero = static_cast<int>(l.size()) - Nlzero;
585
586 eos.c = c;
587 eos.l = l;
588
589 eos.l_i = eos.l.cast<int>();
590
591 if (Nlzero + Nlnonzero != l.size()) {
592 throw std::invalid_argument("Somehow the l lengths don't add up");
593 }
594
595 if (((eos.l_i.cast<double>() - eos.l).cwiseAbs() > 0.0).any()) {
596 throw std::invalid_argument("Non-integer entry in l found");
597 }
598
599 // If a contiguous portion of the terms have values of l_i that are zero
600 // it is computationally advantageous to break up the evaluation into
601 // part that has just the n_i*tau^t_i*delta^d_i and the part with the
602 // exponential term exp(-delta^l_i)
603 if (l.sum() == 0) {
604 // No l term at all, just polynomial
605 JustPowerEOSTerm poly;
606 poly.n = eos.n;
607 poly.t = eos.t;
608 poly.d = eos.d;
609 container.add_term(poly);
610 }
611 else if (l.sum() > 0 && contiguous_lzero) {
612 JustPowerEOSTerm poly;
613 poly.n = eos.n.head(Nlzero);
614 poly.t = eos.t.head(Nlzero);
615 poly.d = eos.d.head(Nlzero);
616 container.add_term(poly);
617
619 e.n = eos.n.tail(Nlnonzero);
620 e.t = eos.t.tail(Nlnonzero);
621 e.d = eos.d.tail(Nlnonzero);
622 e.c = eos.c.tail(Nlnonzero);
623 e.l = eos.l.tail(Nlnonzero);
624 e.l_i = eos.l_i.tail(Nlnonzero);
625 container.add_term(PowerEOSTerm(e));
626 }
627 else {
628 // Don't try to get too clever, just add the term
629 container.add_term(eos);
630 }
631 };
632
633 auto build_Lemmon2005 = [&](auto term) {
635 eos.n = toeig(term["n"]);
636 eos.t = toeig(term["t"]);
637 eos.d = toeig(term["d"]);
638 eos.m = toeig(term["m"]);
639 eos.l = toeig(term["l"]);
640 eos.l_i = eos.l.cast<int>();
641 if (!all_same_length(term, { "n","t","d","m","l" })) {
642 throw std::invalid_argument("Lengths are not all identical in Lemmon2005 term");
643 }
644 if (((eos.l_i.cast<double>() - eos.l).cwiseAbs() > 0.0).any()) {
645 throw std::invalid_argument("Non-integer entry in l found");
646 }
647 return eos;
648 };
649
650 auto build_gaussian = [&](auto term) {
651 GaussianEOSTerm eos;
652 eos.n = toeig(term["n"]);
653 eos.t = toeig(term["t"]);
654 eos.d = toeig(term["d"]);
655 eos.eta = toeig(term["eta"]);
656 eos.beta = toeig(term["beta"]);
657 eos.gamma = toeig(term["gamma"]);
658 eos.epsilon = toeig(term["epsilon"]);
659 if (!all_same_length(term, { "n","t","d","eta","beta","gamma","epsilon" })) {
660 throw std::invalid_argument("Lengths are not all identical in Gaussian term");
661 }
662 return eos;
663 };
664
665 auto build_exponential = [&](auto term) {
667 eos.n = toeig(term["n"]);
668 eos.t = toeig(term["t"]);
669 eos.d = toeig(term["d"]);
670 eos.g = toeig(term["g"]);
671 eos.l = toeig(term["l"]);
672 eos.l_i = eos.l.cast<int>();
673 if (!all_same_length(term, { "n","t","d","g","l" })) {
674 throw std::invalid_argument("Lengths are not all identical in exponential term");
675 }
676 return eos;
677 };
678
679 auto build_doubleexponential = [&](auto& term) {
680 if (!all_same_length(term, { "n","t","d","ld","gd","lt","gt" })) {
681 throw std::invalid_argument("Lengths are not all identical in double exponential term");
682 }
684 eos.n = toeig(term.at("n"));
685 eos.t = toeig(term.at("t"));
686 eos.d = toeig(term.at("d"));
687 eos.ld = toeig(term.at("ld"));
688 eos.gd = toeig(term.at("gd"));
689 eos.lt = toeig(term.at("lt"));
690 eos.gt = toeig(term.at("gt"));
691 eos.ld_i = eos.ld.cast<int>();
692 return eos;
693 };
694
695 auto build_GaoB = [&](auto term) {
696 GaoBEOSTerm eos;
697 eos.n = toeig(term["n"]);
698 eos.t = toeig(term["t"]);
699 eos.d = toeig(term["d"]);
700 eos.eta = -toeig(term["eta"]); // Watch out for this sign flip!!
701 eos.beta = toeig(term["beta"]);
702 eos.gamma = toeig(term["gamma"]);
703 eos.epsilon = toeig(term["epsilon"]);
704 eos.b = toeig(term["b"]);
705 if (!all_same_length(term, { "n","t","d","eta","beta","gamma","epsilon","b" })) {
706 throw std::invalid_argument("Lengths are not all identical in GaoB term");
707 }
708 return eos;
709 };
710
712 auto build_na = [&](auto& term) {
714 eos.n = toeig(term["n"]);
715 eos.A = toeig(term["A"]);
716 eos.B = toeig(term["B"]);
717 eos.C = toeig(term["C"]);
718 eos.D = toeig(term["D"]);
719 eos.a = toeig(term["a"]);
720 eos.b = toeig(term["b"]);
721 eos.beta = toeig(term["beta"]);
722 if (!all_same_length(term, { "n","A","B","C","D","a","b","beta" })) {
723 throw std::invalid_argument("Lengths are not all identical in nonanalytic term");
724 }
725 return eos;
726 };
727
728 for (auto& term : alphar) {
729 std::string type = term.at("type");
730 if (type == "ResidualHelmholtzPower") {
731 build_power(term, container);
732 }
733 else if (type == "ResidualHelmholtzGaussian") {
734 container.add_term(build_gaussian(term));
735 }
736 else if (type == "ResidualHelmholtzNonAnalytic") {
737 container.add_term(build_na(term));
738 }
739 else if (type == "ResidualHelmholtzLemmon2005") {
740 container.add_term(build_Lemmon2005(term));
741 }
742 else if (type == "ResidualHelmholtzGaoB") {
743 container.add_term(build_GaoB(term));
744 }
745 else if (type == "ResidualHelmholtzExponential") {
746 container.add_term(build_exponential(term));
747 }
748 else if (type == "ResidualHelmholtzDoubleExponential") {
749 container.add_term(build_doubleexponential(term));
750 }
751 else if (type == "ResidualHelmholtzGenericCubic") {
752 container.add_term(GenericCubicTerm(term));
753 }
754 else if (type == "ResidualHelmholtzPCSAFTGrossSadowski2001") {
755 container.add_term(PCSAFTGrossSadowski2001Term(term));
756 }
757 else {
758 throw std::invalid_argument("Bad term type: "+type);
759 }
760 }
761 return container;
762}
763
764inline auto get_EOSs(const std::vector<nlohmann::json>& pureJSON) {
765 std::vector<EOSTerms> EOSs;
766 for (auto& j : pureJSON) {
767 auto term = get_EOS_terms(j);
768 EOSs.emplace_back(term);
769 }
770 return EOSs;
771}
772
773inline auto collect_component_json(const std::vector<std::string>& components, const std::string& root)
774{
775 std::vector<nlohmann::json> out;
776 for (auto c : components) {
777 // First we try to lookup the name as a path, which can be on the filesystem, or relative to the root for default name lookup
778 std::vector<std::filesystem::path> candidates = { c, root + "/dev/fluids/" + c + ".json" };
779 std::filesystem::path selected_path = "";
780 for (auto candidate : candidates) {
781 if (std::filesystem::is_regular_file(candidate)) {
782 selected_path = candidate;
783 break;
784 }
785 }
786 if (selected_path != "") {
787 out.push_back(load_a_JSON_file(selected_path.string()));
788 }
789 else {
790 throw std::invalid_argument("Could not load any of the candidates:" + c);
791 }
792 }
793 return out;
794}
795
796inline auto collect_identifiers(const std::vector<nlohmann::json>& pureJSON)
797{
798 std::vector<std::string> CAS, Name, REFPROP, hash;
799 for (auto j : pureJSON) {
800 auto INFO = j.at("INFO");
801 Name.push_back(INFO.at("NAME"));
802 CAS.push_back(INFO.at("CAS"));
803 REFPROP.push_back(INFO.at("REFPROP_NAME"));
804 if (INFO.contains("HASH")){
805 hash.push_back(INFO.at("HASH"));
806 }
807 }
808 std::map<std::string, std::vector<std::string>> result{
809 {"CAS", CAS},
810 {"Name", Name},
811 {"REFPROP", REFPROP}
812 };
813 if (hash.size() == result["CAS"].size()){
814 result["hash"] = hash;
815 }
816 return result;
817}
818
820template<typename mapvecstring>
821inline auto select_identifier(const nlohmann::json& BIPcollection, const mapvecstring& identifierset, const nlohmann::json& flags){
822 for (const auto &ident: identifierset){
823 std::string key; std::vector<std::string> identifiers;
824 std::tie(key, identifiers) = ident;
825 try{
826 for (auto i = 0U; i < identifiers.size(); ++i){
827 for (auto j = i+1; j < identifiers.size(); ++j){
828 const std::vector<std::string> pair = {identifiers[i], identifiers[j]};
829 reducing::get_BIPdep(BIPcollection, pair, flags);
830 }
831 }
832 return key;
833 }
834 catch(...){
835
836 }
837 }
838 std::string errmsg;
839 for (const auto& [k,v] : identifierset){
840 if (errmsg.empty()){
841 errmsg += k;
842 }else {
843 errmsg += "," + k;
844 }
845 }
846 throw std::invalid_argument("Unable to match any of the identifier options: " + errmsg);
847}
848
850inline auto build_alias_map(const std::string& root) {
851 std::map<std::string, std::string> aliasmap;
852 for (auto path : get_files_in_folder(root + "/dev/fluids", ".json")) {
853 auto j = load_a_JSON_file(path.string());
854 std::string REFPROP_name = j.at("INFO").at("REFPROP_NAME");
855 std::string name = j.at("INFO").at("NAME");
856 for (std::string k : {"NAME", "CAS", "REFPROP_NAME"}) {
857 std::string val = j.at("INFO").at(k);
858 // Skip REFPROP names that match the fluid itself
859 if (k == "REFPROP_NAME" && val == name) {
860 continue;
861 }
862 // Skip invalid REFPROP names
863 if (k == "REFPROP_NAME" && val == "N/A") {
864 continue;
865 }
866 if (aliasmap.count(val) > 0) {
867 throw std::invalid_argument("Duplicated reverse lookup identifier ["+k+"] found in file:" + path.string());
868 }
869 else {
870 aliasmap[val] = std::filesystem::absolute(path).string();
871 }
872 }
873 std::vector<std::string> aliases = j.at("INFO").at("ALIASES");
874
875 for (std::string alias : aliases) {
876 if (alias != REFPROP_name && alias != name) { // Don't add REFPROP name or base name, were already above to list of aliases
877 if (aliasmap.count(alias) > 0) {
878 throw std::invalid_argument("Duplicated alias [" + alias + "] found in file:" + path.string());
879 }
880 else {
881 aliasmap[alias] = std::filesystem::absolute(path).string();
882 }
883 }
884 }
885 }
886 return aliasmap;
887}
888
889
891inline auto _build_multifluid_model(const std::vector<nlohmann::json> &pureJSON, const nlohmann::json& BIPcollection, const nlohmann::json& depcollection, const nlohmann::json& flags = {}) {
892
893 auto get_Rvals = [](const std::vector<nlohmann::json> &pureJSON) -> std::vector<double>{
894 std::vector<double> o;
895 for (auto pure : pureJSON){
896 o.push_back(pure.at("EOS")[0].at("gas_constant"));
897 }
898 return o;
899 };
900
901 auto [Tc, vc] = reducing::get_Tcvc(pureJSON);
902 auto EOSs = get_EOSs(pureJSON);
903 // Array of gas constants for each fluid
904 auto Rvals = get_Rvals(pureJSON);
905
906 // Extract the set of possible identifiers to be used to match parameters
907 auto identifierset = collect_identifiers(pureJSON);
908 // Decide which identifier is to be used (Name, CAS, REFPROP name)
909 auto identifiers = identifierset[select_identifier(BIPcollection, identifierset, flags)];
910
911 // Things related to the mixture
912 auto F = reducing::get_F_matrix(BIPcollection, identifiers, flags);
913 auto [funcs, funcsmeta] = get_departure_function_matrix(depcollection, BIPcollection, identifiers, flags);
914 auto [betaT, gammaT, betaV, gammaV] = reducing::get_BIP_matrices(BIPcollection, identifiers, flags, Tc, vc);
915
916 multifluid::gasconstant::GasConstantCalculator Rcalc = multifluid::gasconstant::MoleFractionWeighted(Rvals);
917
918 if (flags.contains("Rmodel") && flags.at("Rmodel") == "CODATA"){
919 Rcalc = multifluid::gasconstant::CODATA();
920 }
921
922
923 nlohmann::json meta = {
924 {"pures", pureJSON},
925 {"mix", funcsmeta},
926 };
927
928 auto redfunc = ReducingFunctions(std::move(MultiFluidReducingFunction(betaT, gammaT, betaV, gammaV, Tc, vc)));
929
930 auto model = MultiFluid(
931 std::move(redfunc),
932 CorrespondingStatesContribution(std::move(EOSs)),
933 DepartureContribution(std::move(F), std::move(funcs)),
934 std::move(Rcalc)
935 );
936 model.set_meta(meta.dump(1));
937 return model;
938}
939
941inline auto build_multifluid_JSONstr(const std::vector<std::string>& componentJSON, const std::string& BIPJSON, const std::string& departureJSON, const nlohmann::json& flags = {}) {
942
943 // Mixture things
944 const auto BIPcollection = nlohmann::json::parse(BIPJSON);
945 const auto depcollection = nlohmann::json::parse(departureJSON);
946
947 // Pure fluids
948 std::vector<nlohmann::json> pureJSON;
949 for (auto& c : componentJSON) {
950 pureJSON.emplace_back(nlohmann::json::parse(c));
951 }
952 return _build_multifluid_model(pureJSON, BIPcollection, depcollection, flags);
953}
954
963inline auto make_pure_components_JSON(const nlohmann::json& components, const std::optional<std::string>& root = std::nullopt){
964
965 std::vector<nlohmann::json> pureJSON;
966 if (!components.is_array()){
967 throw std::invalid_argument("Must be an array");
968 }
969 std::optional<decltype(build_alias_map(""))> optaliasmap;
970 for (const nlohmann::json& comp : components){
971 auto get_or_aliasmap = [&](){
972 try{
973 return multilevel_JSON_load(comp, root);
974 }
975 catch(...){
976 // Build the alias map if not already constructed
977 if (!optaliasmap && root){
978 optaliasmap = build_alias_map(root.value());
979 if (optaliasmap.value().count(comp) != 1){
980 std::string scomp = comp.get<std::string>();
981 std::string errname = (scomp.size() > 200) ? scomp.substr(0, 200)+"..." : scomp;
982 throw teqp::InvalidArgument("Alias map constructed, but component name is not found in alias map: " + errname);
983 }
984 }
985 else{
986 std::string scomp = comp.get<std::string>();
987 std::string errname = (scomp.size() > 200) ? scomp.substr(0, 200)+"..." : scomp;
988 teqp::InvalidArgument("It was not possible to load the alias map because no path was provided. Failure to load: " + errname);
989 }
990 return multilevel_JSON_load(optaliasmap.value()[comp], root);
991 }
992 };
993 if (comp.is_string()){
994 std::string contents = comp;
995 // Note: first arg to substr is first index to *keep*, no second arg so keep to the end
996 if (contents.find("PATH::") == 0){
997 pureJSON.push_back(load_a_JSON_file(contents.substr(6)));
998 }
999 else if (contents.find("FLDPATH::") == 0){
1000 pureJSON.push_back(RPinterop::FLDfile(contents.substr(9)).make_json(""));
1001 }
1002 else if (contents.find("FLD::") == 0){
1003 pureJSON.push_back(RPinterop::FLDfile(contents.substr(5)).make_json(""));
1004 }
1005 else{
1006 pureJSON.push_back(get_or_aliasmap());
1007 }
1008 }
1009 else{
1010 pureJSON.push_back(get_or_aliasmap());
1011 }
1012 }
1013 return pureJSON;
1014}
1015
1016inline auto build_multifluid_model(const std::vector<std::string>& components, const std::string& root, const std::string& BIPcollectionpath = {}, const nlohmann::json& flags = {}, const std::string& departurepath = {}) {
1017
1018 // Convert the string representations to JSON using the existing routines (a bit slower, but more convenient, more DRY)
1019 nlohmann::json BIPcollection = nlohmann::json::array();
1020 nlohmann::json depcollection = nlohmann::json::array();
1021 if (components.size() > 1){
1022 nlohmann::json B = BIPcollectionpath, D = departurepath;
1023 BIPcollection = multilevel_JSON_load(B, root + "/dev/mixtures/mixture_binary_pairs.json");
1024 depcollection = multilevel_JSON_load(D, root + "/dev/mixtures/mixture_departure_functions.json");
1025 }
1026
1027 return _build_multifluid_model(make_pure_components_JSON(components, root), BIPcollection, depcollection, flags);
1028}
1029
1038inline auto multifluidfactory(const nlohmann::json& spec) {
1039
1040 nlohmann::json flags = (spec.contains("flags")) ? spec.at("flags") : nlohmann::json();
1041
1042 // We are in the interop logical branch in which we will be invoking the REFPROP-interop code
1043 if (spec.contains("HMX.BNC")){
1044 std::vector<nlohmann::json> componentJSON;
1045 for (auto comp : spec.at("components")){
1046 componentJSON.push_back(RPinterop::FLDfile(comp).make_json(""));
1047 }
1048 auto [BIPcollection, depcollection] = RPinterop::HMXBNCfile(spec.at("HMX.BNC")).make_jsons();
1049 return _build_multifluid_model(componentJSON, BIPcollection, depcollection, flags);
1050 }
1051 else{
1052
1053 std::string root = (spec.contains("root")) ? spec.at("root") : "";
1054
1055 auto components = spec.at("components");
1056
1057 nlohmann::json BIPcollection = nlohmann::json::array();
1058 nlohmann::json depcollection = nlohmann::json::array();
1059 if (components.size() > 1){
1060 BIPcollection = multilevel_JSON_load(spec.at("BIP"), root + "/dev/mixtures/mixture_binary_pairs.json");
1061
1062 if (spec.contains("departure")){
1063 std::string msg = "departure was provided but is invalid; options are non-empty array, path to file as string, or JSON data encoded as string";
1064 auto load_departure = [&msg](const nlohmann::json& j){
1065 if (j.is_array() && j.size() > 0){
1066 return j;
1067 }
1068 else if (j.is_string()){
1069 const std::string& s = j;
1070 if (s.find("PATH::") == 0){
1071 return load_a_JSON_file(s.substr(6));
1072 }
1073 else{
1074 try{
1075 try{
1076 return multilevel_JSON_load(s);
1077 }
1078 catch(...){
1079 return nlohmann::json::parse(s);
1080 }
1081 }
1082 catch(...){
1083 throw teqp::InvalidArgument(msg);
1084 }
1085 }
1086 }
1087 else{
1088 throw teqp::InvalidArgument(msg);
1089 }
1090 };
1091
1092 if (root.empty()){
1093 depcollection = load_departure(spec.at("departure"));
1094 }
1095 else{
1096 depcollection = multilevel_JSON_load(spec.at("departure"), root + "/dev/mixtures/mixture_departure_functions.json");
1097 }
1098 }
1099 }
1100
1101 return _build_multifluid_model(make_pure_components_JSON(components, root), BIPcollection, depcollection, flags);
1102 }
1103}
1105inline auto multifluidfactory(const std::string& specstring) {
1106 return multifluidfactory(nlohmann::json::parse(specstring));
1107}
1108
1109
1110
1111//class DummyEOS {
1112//public:
1113// template<typename TType, typename RhoType> auto alphar(TType tau, const RhoType& delta) const { return tau * delta; }
1114//};
1115//class DummyReducingFunction {
1116//public:
1117// template<typename MoleFractions> auto get_Tr(const MoleFractions& molefracs) const { return molefracs[0]; }
1118// template<typename MoleFractions> auto get_rhor(const MoleFractions& molefracs) const { return molefracs[0]; }
1119//};
1120//inline auto build_dummy_multifluid_model(const std::vector<std::string>& components) {
1121// std::vector<DummyEOS> EOSs(2);
1122// std::vector<std::vector<DummyEOS>> funcs(2); for (auto i = 0; i < funcs.size(); ++i) { funcs[i].resize(funcs.size()); }
1123// std::vector<std::vector<double>> F(2); for (auto i = 0; i < F.size(); ++i) { F[i].resize(F.size()); }
1124//
1125// struct Fwrapper {
1126// private:
1127// const std::vector<std::vector<double>> F_;
1128// public:
1129// Fwrapper(const std::vector<std::vector<double>> &F) : F_(F){};
1130// auto operator ()(std::size_t i, std::size_t j) const{ return F_[i][j]; }
1131// };
1132// auto ff = Fwrapper(F);
1133// auto redfunc = DummyReducingFunction();
1134// return MultiFluid(std::move(redfunc), std::move(CorrespondingStatesContribution(std::move(EOSs))), std::move(DepartureContribution(std::move(ff), std::move(funcs))));
1135//}
1136//inline void test_dummy() {
1137// auto model = build_dummy_multifluid_model({ "A", "B" });
1138// std::valarray<double> rhovec = { 1.0, 2.0 };
1139// auto alphar = model.alphar(300.0, rhovec);
1140//}
1141
1142}; // namespace teqp
CorrespondingStatesContribution(EOSCollection &&EOSs)
auto alphari(const TauType &tau, const DeltaType &delta, std::size_t i) const
auto alphar(const TauType &tau, const DeltaType &delta, const MoleFractions &molefracs) const
auto get_EOS(std::size_t i) const
DepartureContribution(FCollection &&F, DepartureFunctionCollection &&funcs)
auto alphar(const TauType &tau, const DeltaType &delta, const MoleFractions &molefracs) const
auto get_alpharij(const std::size_t i, const std::size_t j, const TauType &tau, const DeltaType &delta) const
Call a single departure term at i,j.
const auto & get_F() const
auto add_term(Instance &&instance)
auto alphar(const TType &T, const RhoType &rho, const MoleFracType &molefrac) const
const std::variant< double, std::string > get_BIP(const std::size_t &i, const std::size_t &j, const std::string &key) const
Return a binary interaction parameter.
const CorrespondingTerm corr
auto get_meta() const
Get the metadata stored in string form.
const DepartureTerm dep
void set_meta(const std::string &m)
Store some sort of metadata in string form (perhaps a JSON representation of the model?...
MultiFluid(ReducingFunctions &&redfunc, CorrespondingTerm &&corr, DepartureTerm &&dep, GasConstantCalculator &&Rcalc)
multifluid::gasconstant::GasConstantCalculator GasConstantCalculator
const ReducingFunctions redfunc
const GasConstantCalculator Rcalc
auto alphar(TType T, const RhoType &rhovec, const std::optional< typename RhoType::value_type > rhotot=std::nullopt) const
auto alphar_taudelta(const TType &tau, const RhoType &delta, const MoleFracType &molefrac) const
auto alphar_taudeltai(const TType &tau, const RhoType &delta, const std::size_t i) const
auto R(const VecType &molefracs) const
auto get_rhor(const MoleFractions &molefracs) const
auto get_Tr(const MoleFractions &molefracs) const
auto get_BIP(const std::size_t &i, const std::size_t &j, const std::string &key) const
std::variant< MoleFractionWeighted, CODATA > GasConstantCalculator
auto get_Tcvc(const std::vector< nlohmann::json > &pureJSON)
auto get_F_matrix(const nlohmann::json &collection, const std::vector< std::string > &identifiers, const nlohmann::json &flags)
Get the matrix F of Fij factors multiplying the departure functions.
auto get_BIPdep(const nlohmann::json &collection, const std::vector< std::string > &identifiers, const nlohmann::json &flags)
auto get_BIP_matrices(const nlohmann::json &collection, const std::vector< std::string > &components, const nlohmann::json &flags, const Tcvec &Tc, const vcvec &vc)
Build the matrices of betaT, gammaT, betaV, gammaV for the multi-fluid model.
auto _build_multifluid_model(const std::vector< nlohmann::json > &pureJSON, const nlohmann::json &BIPcollection, const nlohmann::json &depcollection, const nlohmann::json &flags={})
Internal method for actually constructing the model with the provided JSON data structures.
auto get_EOS_terms(const nlohmann::json &j)
auto get_EOSs(const std::vector< nlohmann::json > &pureJSON)
auto build_alias_map(const std::string &root)
Build a reverse-lookup map for finding a fluid JSON structure given a backup identifier.
auto toeig(const std::vector< double > &v) -> Eigen::ArrayXd
Definition types.hpp:10
nlohmann::json load_a_JSON_file(const std::string &path)
Load a JSON file from a specified file.
auto collect_identifiers(const std::vector< nlohmann::json > &pureJSON)
auto build_multifluid_JSONstr(const std::vector< std::string > &componentJSON, const std::string &BIPJSON, const std::string &departureJSON, const nlohmann::json &flags={})
A builder function where the JSON-formatted strings are provided explicitly rather than file paths.
auto get_departure_json(const std::string &name, const std::string &path)
auto get_departure_function_matrix(const nlohmann::json &depcollection, const nlohmann::json &BIPcollection, const std::vector< std::string > &components, const nlohmann::json &flags)
auto build_departure_function(const nlohmann::json &j)
auto all_same_length(const nlohmann::json &j, const std::vector< std::string > &ks)
auto select_identifier(const nlohmann::json &BIPcollection, const mapvecstring &identifierset, const nlohmann::json &flags)
Iterate over the possible options for identifiers to determine which one will satisfy all the binary ...
auto multifluidfactory(const nlohmann::json &spec)
Load a model from a JSON data structure.
auto make_pure_components_JSON(const nlohmann::json &components, const std::optional< std::string > &root=std::nullopt)
auto build_multifluid_model(const std::vector< std::string > &components, const std::string &root, const std::string &BIPcollectionpath={}, const nlohmann::json &flags={}, const std::string &departurepath={})
ReducingTermContainer< MultiFluidReducingFunction, MultiFluidInvariantReducingFunction > ReducingFunctions
auto collect_component_json(const std::vector< std::string > &components, const std::string &root)
auto forceeval(T &&expr)
Definition types.hpp:52
auto multilevel_JSON_load(const nlohmann::json &j, const std::optional< std::string > &default_path=std::nullopt)