Cantera  4.0.0a1
Loading...
Searching...
No Matches
Phase.cpp
Go to the documentation of this file.
1/**
2 * @file Phase.cpp
3 * Definition file for class Phase.
4 */
5
6// This file is part of Cantera. See License.txt in the top-level directory or
7// at https://cantera.org/license.txt for license and copyright information.
8
14
15using namespace std;
16
17namespace Cantera
18{
19
20string Phase::name() const
21{
22 return m_name;
23}
24
25void Phase::setName(const string& name)
26{
27 m_name = name;
28}
29
30size_t Phase::nElements() const
31{
32 return m_mm;
33}
34
35size_t Phase::checkElementIndex(size_t m) const
36{
37 if (m < m_mm) {
38 return m;
39 }
40 throw IndexError("Phase::checkElementIndex", "elements", m, m_mm);
41}
42
43string Phase::elementName(size_t m) const
44{
45 if (m < m_mm) {
46 return m_elementNames[m];
47 }
48 throw IndexError("Phase::elementName", "element", m, m_mm);
49}
50
51size_t Phase::elementIndex(const string& elementName, bool raise) const
52{
53 for (size_t i = 0; i < m_mm; i++) {
54 if (m_elementNames[i] == elementName) {
55 return i;
56 }
57 }
58 if (!raise) {
59 return npos;
60 }
61 throw CanteraError("Phase::elementIndex", "Element '{}' not found", elementName);
62}
63
64const vector<string>& Phase::elementNames() const
65{
66 return m_elementNames;
67}
68
69double Phase::atomicWeight(size_t m) const
70{
71 return m_atomicWeights[m];
72}
73
74double Phase::entropyElement298(size_t m) const
75{
77}
78
79span<const double> Phase::atomicWeights() const
80{
81 return m_atomicWeights;
82}
83
84int Phase::atomicNumber(size_t m) const
85{
86 return m_atomicNumbers[m];
87}
88
89int Phase::elementType(size_t m) const
90{
91 return m_elem_type[m];
92}
93
94int Phase::changeElementType(int m, int elem_type)
95{
96 int old = m_elem_type[m];
97 m_elem_type[m] = elem_type;
98 return old;
99}
100
101double Phase::nAtoms(size_t k, size_t m) const
102{
105 return m_speciesComp[m_mm * k + m];
106}
107
108size_t Phase::findSpeciesLower(const string& name) const
109{
110 string nLower = toLowerCopy(name);
111 size_t loc = npos;
112 auto it = m_speciesLower.find(nLower);
113 if (it == m_speciesLower.end()) {
114 return npos;
115 } else {
116 loc = it->second;
117 if (loc == npos) {
118 throw CanteraError("Phase::findSpeciesLower",
119 "Lowercase species name '{}' is not unique. "
120 "Set Phase::caseSensitiveSpecies to true to "
121 "enforce case sensitive species names", nLower);
122 }
123 }
124 return loc;
125}
126
127size_t Phase::speciesIndex(const string& name, bool raise) const
128{
129 size_t loc = npos;
130 auto it = m_speciesIndices.find(name);
131 if (it != m_speciesIndices.end()) {
132 return it->second;
133 } else if (!m_caseSensitiveSpecies) {
134 loc = findSpeciesLower(name);
135 }
136 if (loc==npos && raise) {
137 throw CanteraError("Phase::speciesIndex", "Species '{}' not found", name);
138 }
139
140 return loc;
141}
142
143string Phase::speciesName(size_t k) const
144{
145 if (k < m_kk) {
146 return m_speciesNames[k];
147 }
148 throw IndexError("Phase::speciesName", "species", k, m_kk);
149}
150
151const vector<string>& Phase::speciesNames() const
152{
153 return m_speciesNames;
154}
155
156size_t Phase::checkSpeciesIndex(size_t k) const
157{
158 if (k < m_kk) {
159 return k;
160 }
161 throw IndexError("Phase::checkSpeciesIndex", "species", k, m_kk);
162}
163
164map<string, size_t> Phase::nativeState() const
165{
166 if (isPure()) {
167 if (isCompressible()) {
168 return { {"T", 0}, {"D", 1} };
169 } else {
170 return { {"T", 0}, {"P", 1} };
171 }
172 } else {
173 if (isCompressible()) {
174 return { {"T", 0}, {"D", 1}, {"Y", 2} };
175 } else {
176 return { {"T", 0}, {"P", 1}, {"Y", 2} };
177 }
178 }
179}
180
181string Phase::nativeMode() const
182{
183 map<size_t, string> states; // reverse lookup
184 for (auto& [name, value] : nativeState()) {
185 states[value] = name;
186 }
187 string out;
188 for (auto& [value, name] : states) {
189 out += name;
190 }
191 return out;
192}
193
194vector<string> Phase::fullStates() const
195{
196 if (isPure()) {
197 if (isCompressible()) {
198 return {"TD", "TP", "UV", "DP", "HP", "SP", "SV"};
199 } else {
200 return {"TP", "HP", "SP"};
201 }
202 } else {
203 if (isCompressible()) {
204 return {"TDX", "TDY", "TPX", "TPY", "UVX", "UVY", "DPX", "DPY",
205 "HPX", "HPY", "SPX", "SPY", "SVX", "SVY"};
206 } else {
207 return {"TPX", "TPY", "HPX", "HPY", "SPX", "SPY"};
208 }
209 }
210}
211
212vector<string> Phase::partialStates() const
213{
214 if (isPure()) {
215 return {};
216 } else {
217 if (isCompressible()) {
218 return {"TD", "TP", "UV", "DP", "HP", "SP", "SV"};
219 } else {
220 return {"TP", "HP", "SP"};
221 }
222 }
223}
224
225void Phase::savePartialState(span<double> state) const
226{
227 checkArraySize("Phase::savePartialState", state.size(), partialStateSize());
228 auto native = nativeState();
229 state[native.at("T")] = temperature();
230 if (isCompressible()) {
231 state[native.at("D")] = density();
232 } else {
233 state[native.at("P")] = pressure();
234 }
235}
236
237void Phase::restorePartialState(span<const double> state)
238{
239 checkArraySize("Phase::restorePartialState", state.size(), partialStateSize());
240 auto native = nativeState();
241 setTemperature(state[native.at("T")]);
242 if (isCompressible()) {
243 setDensity(state[native.at("D")]);
244 } else {
245 setPressure(state[native.at("P")]);
246 }
247}
248
249size_t Phase::stateSize() const {
250 if (isPure()) {
251 return partialStateSize();
252 } else {
253 return partialStateSize() + nSpecies();
254 }
255}
256
257void Phase::saveState(span<double> state) const
258{
259 checkArraySize("Phase::saveState", state.size(), stateSize());
260 savePartialState(state);
261 auto native = nativeState();
262 if (native.count("X")) {
263 getMoleFractions(state.subspan(native["X"], nSpecies()));
264 } else if (native.count("Y")) {
265 getMassFractions(state.subspan(native["Y"], nSpecies()));
266 }
267}
268
269void Phase::restoreState(span<const double> state)
270{
271 checkArraySize("Phase::restoreState", state.size(), stateSize());
272 restorePartialState(state);
273 auto native = nativeState();
274
275 if (native.count("X")) {
276 setMoleFractions_NoNorm(state.subspan(native["X"], nSpecies()));
277 } else if (native.count("Y")) {
278 setMassFractions_NoNorm(state.subspan(native["Y"], nSpecies()));
279 }
281}
282
283void Phase::setMoleFractions(span<const double> x)
284{
285 checkArraySize("Phase::setMoleFractions", x.size(), m_kk);
286 // Use m_y as a temporary work vector for the non-negative mole fractions
287 double norm = 0.0;
288 // sum is calculated below as the unnormalized molecular weight
289 double sum = 0;
290 for (size_t k = 0; k < m_kk; k++) {
291 double xk = std::max(x[k], 0.0); // Ignore negative mole fractions
292 m_y[k] = xk;
293 norm += xk;
294 sum += m_molwts[k] * xk;
295 }
296
297 // Set m_ym to the normalized mole fractions divided by the normalized mean
298 // molecular weight:
299 // m_ym_k = X_k / (sum_k X_k M_k)
300 const double invSum = 1.0/sum;
301 for (size_t k=0; k < m_kk; k++) {
302 m_ym[k] = m_y[k]*invSum;
303 }
304
305 // Now set m_y to the normalized mass fractions:
306 // m_y = X_k M_k / (sum_k X_k M_k)
307 for (size_t k=0; k < m_kk; k++) {
308 m_y[k] = m_ym[k] * m_molwts[k];
309 }
310
311 // Calculate the normalized molecular weight
312 m_mmw = sum/norm;
314}
315
316void Phase::setMoleFractions_NoNorm(span<const double> x)
317{
318 checkArraySize("Phase::setMoleFractions_NoNorm", x.size(), m_kk);
319 m_mmw = dot(x.begin(), x.begin() + m_kk, m_molwts.begin());
320 scale(x.begin(), x.begin() + m_kk, m_ym.begin(), 1.0/m_mmw);
321 transform(m_ym.begin(), m_ym.begin() + m_kk, m_molwts.begin(),
322 m_y.begin(), multiplies<double>());
324}
325
327{
328 vector<double> mf = getCompositionFromMap(xMap);
330}
331
332void Phase::setMoleFractionsByName(const string& x)
333{
335}
336
337void Phase::setMassFractions(span<const double> y)
338{
339 checkArraySize("Phase::setMassFractions", y.size(), m_kk);
340 for (size_t k = 0; k < m_kk; k++) {
341 m_y[k] = std::max(y[k], 0.0); // Ignore negative mass fractions
342 }
343 double norm = accumulate(m_y.begin(), m_y.end(), 0.0);
344 scale(m_y.begin(), m_y.end(), m_y.begin(), 1.0/norm);
345
346 transform(m_y.begin(), m_y.end(), m_rmolwts.begin(),
347 m_ym.begin(), multiplies<double>());
348 m_mmw = 1.0 / accumulate(m_ym.begin(), m_ym.end(), 0.0);
350}
351
352void Phase::setMassFractions_NoNorm(span<const double> y)
353{
354 checkArraySize("Phase::setMassFractions_NoNorm", y.size(), m_kk);
355 double sum = 0.0;
356 copy(y.begin(), y.begin() + m_kk, m_y.begin());
357 transform(m_y.begin(), m_y.end(), m_rmolwts.begin(), m_ym.begin(),
358 multiplies<double>());
359 sum = accumulate(m_ym.begin(), m_ym.end(), 0.0);
360 m_mmw = 1.0/sum;
362}
363
365{
366 vector<double> mf = getCompositionFromMap(yMap);
368}
369
370void Phase::setMassFractionsByName(const string& y)
371{
373}
374
375void Phase::setState_TD(double t, double rho)
376{
377 vector<double> state(partialStateSize());
378 savePartialState(state);
379 try {
381 setDensity(rho);
382 } catch (std::exception&) {
383 restorePartialState(state);
384 throw;
385 }
386}
387
388double Phase::molecularWeight(size_t k) const
389{
391 return m_molwts[k];
392}
393
394void Phase::getMolecularWeights(span<double> weights) const
395{
396 auto mw = molecularWeights();
397 checkArraySize("Phase::getMolecularWeights", weights.size(), mw.size());
398 copy(mw.begin(), mw.end(), weights.begin());
399}
400
401span<const double> Phase::molecularWeights() const
402{
403 return m_molwts;
404}
405
406span<const double> Phase::inverseMolecularWeights() const
407{
408 return m_rmolwts;
409}
410
411void Phase::getCharges(span<double> charges) const
412{
413 checkArraySize("Phase::getCharges", charges.size(), m_speciesCharge.size());
414 copy(m_speciesCharge.begin(), m_speciesCharge.end(), charges.begin());
415}
416
418{
419 Composition comp;
420 for (size_t k = 0; k < m_kk; k++) {
421 double x = moleFraction(k);
422 if (x > threshold) {
423 comp[speciesName(k)] = x;
424 }
425 }
426 return comp;
427}
428
430{
431 Composition comp;
432 for (size_t k = 0; k < m_kk; k++) {
433 double x = massFraction(k);
434 if (x > threshold) {
435 comp[speciesName(k)] = x;
436 }
437 }
438 return comp;
439}
440
441void Phase::getMoleFractions(span<double> x) const
442{
443 checkArraySize("Phase::getMoleFractions", x.size(), m_kk);
444 scale(m_ym.begin(), m_ym.end(), x.begin(), m_mmw);
445}
446
447double Phase::moleFraction(size_t k) const
448{
450 return m_ym[k] * m_mmw;
451}
452
453double Phase::moleFraction(const string& nameSpec) const
454{
455 size_t iloc = speciesIndex(nameSpec, false);
456 if (iloc != npos) {
457 return moleFraction(iloc);
458 } else {
459 return 0.0;
460 }
461}
462
463double Phase::massFraction(size_t k) const
464{
466 return m_y[k];
467}
468
469double Phase::massFraction(const string& nameSpec) const
470{
471 size_t iloc = speciesIndex(nameSpec, false);
472 if (iloc != npos) {
473 return massFractions()[iloc];
474 } else {
475 return 0.0;
476 }
477}
478
479void Phase::getMassFractions(span<double> y) const
480{
481 checkArraySize("Phase::getMassFractions", y.size(), m_kk);
482 copy(m_y.begin(), m_y.end(), y.begin());
483}
484
485double Phase::concentration(const size_t k) const
486{
488 return m_y[k] * m_dens * m_rmolwts[k];
489}
490
491void Phase::getConcentrations(span<double> c) const
492{
493 checkArraySize("Phase::getConcentrations", c.size(), m_kk);
494 scale(m_ym.begin(), m_ym.end(), c.begin(), m_dens);
495}
496
497void Phase::setConcentrations(span<const double> conc)
498{
499 assertCompressible("setConcentrations");
500 checkArraySize("Phase::setConcentrations", conc.size(), m_kk);
501
502 // Use m_y as temporary storage for non-negative concentrations
503 double sum = 0.0, norm = 0.0;
504 for (size_t k = 0; k != m_kk; ++k) {
505 double ck = std::max(conc[k], 0.0); // Ignore negative concentrations
506 m_y[k] = ck;
507 sum += ck * m_molwts[k];
508 norm += ck;
509 }
510 m_mmw = sum/norm;
511 setDensity(sum);
512 double rsum = 1.0/sum;
513 for (size_t k = 0; k != m_kk; ++k) {
514 m_ym[k] = m_y[k] * rsum;
515 m_y[k] = m_ym[k] * m_molwts[k]; // m_y is now the mass fraction
516 }
518}
519
520void Phase::setConcentrationsNoNorm(span<const double> conc)
521{
522 assertCompressible("setConcentrationsNoNorm");
523 checkArraySize("Phase::setConcentrationsNoNorm", conc.size(), m_kk);
524
525 double sum = 0.0, norm = 0.0;
526 for (size_t k = 0; k != m_kk; ++k) {
527 sum += conc[k] * m_molwts[k];
528 norm += conc[k];
529 }
530 m_mmw = sum/norm;
531 setDensity(sum);
532 double rsum = 1.0/sum;
533 for (size_t k = 0; k != m_kk; ++k) {
534 m_ym[k] = conc[k] * rsum;
535 m_y[k] = m_ym[k] * m_molwts[k];
536 }
538}
539
540void Phase::setMolesNoTruncate(span<const double> N)
541{
542 checkArraySize("Phase::setMolesNoTruncate", N.size(), m_kk);
543 // get total moles
544 copy(N.begin(), N.begin() + m_kk, m_ym.begin());
545 double totalMoles = accumulate(m_ym.begin(), m_ym.end(), 0.0);
546 // get total mass
547 copy(N.begin(), N.begin() + m_kk, m_y.begin());
548 transform(m_y.begin(), m_y.end(), m_molwts.begin(), m_y.begin(), multiplies<double>());
549 double totalMass = accumulate(m_y.begin(), m_y.end(), 0.0);
550 // mean molecular weight
551 m_mmw = totalMass/totalMoles;
552 // mass fractions
553 scale(m_y.begin(), m_y.end(), m_y.begin(), 1/totalMass);
554 // moles fractions/m_mmw
555 scale(m_ym.begin(), m_ym.end(), m_ym.begin(), 1/(m_mmw * totalMoles));
556 // composition has changed
558}
559
560double Phase::elementalMassFraction(const size_t m) const
561{
562 double Z_m = 0.0;
563 for (size_t k = 0; k != m_kk; ++k) {
564 Z_m += nAtoms(k, m) * atomicWeight(m) / molecularWeight(k)
565 * massFraction(k);
566 }
567 return Z_m;
568}
569
570double Phase::elementalMoleFraction(const size_t m) const
571{
572 double denom = 0;
573 for (size_t k = 0; k < m_kk; k++) {
574 double atoms = 0;
575 for (size_t j = 0; j < nElements(); j++) {
576 atoms += nAtoms(k, j);
577 }
578 denom += atoms * moleFraction(k);
579 }
580 double numerator = 0.0;
581 for (size_t k = 0; k != m_kk; ++k) {
582 numerator += nAtoms(k, m) * moleFraction(k);
583 }
584 return numerator / denom;
585}
586
588{
589 return density()/meanMolecularWeight();
590}
591
592double Phase::molarVolume() const
593{
594 return 1.0/molarDensity();
595}
596
597void Phase::setDensity(const double density_)
598{
599 assertCompressible("setDensity");
600 if (density_ > 0.0) {
601 m_dens = density_;
602 } else {
603 throw CanteraError("Phase::setDensity",
604 "density must be positive. density = {}", density_);
605 }
606}
607
608void Phase::assignDensity(const double density_)
609{
610 if (density_ > 0.0) {
611 m_dens = density_;
612 } else {
613 throw CanteraError("Phase::assignDensity",
614 "density must be positive. density = {}", density_);
615 }
616}
617
619{
620 double cdens = 0.0;
621 for (size_t k = 0; k < m_kk; k++) {
622 cdens += charge(k)*moleFraction(k);
623 }
624 return cdens * Faraday;
625}
626
627double Phase::mean_X(span<const double> Q) const
628{
629 checkArraySize("Phase::mean_X", Q.size(), m_kk);
630 return m_mmw*std::inner_product(m_ym.begin(), m_ym.end(), Q.begin(), 0.0);
631}
632
633double Phase::sum_xlogx() const
634{
635 double sumxlogx = 0;
636 for (size_t k = 0; k < m_kk; k++) {
637 sumxlogx += m_ym[k] * std::log(std::max(m_ym[k], SmallNumber));
638 }
639 return m_mmw * sumxlogx + std::log(m_mmw);
640}
641
642size_t Phase::addElement(const string& symbol, double weight, int atomic_number,
643 double entropy298, int elem_type)
644{
645 // Look up the atomic weight if not given
646 if (weight == 0.0) {
647 try {
648 weight = getElementWeight(symbol);
649 } catch (CanteraError&) {
650 // assume this is just a custom element with zero atomic weight
651 }
652 } else if (weight == -12345.0) {
653 weight = getElementWeight(symbol);
654 }
655
656 // Try to look up the standard entropy if not given. Fail silently.
657 if (entropy298 == ENTROPY298_UNKNOWN) {
658 try {
659 const static AnyMap db = AnyMap::fromYamlFile(
660 "element-standard-entropies.yaml");
661 const AnyMap& elem = db["elements"].getMapWhere("symbol", symbol);
662 entropy298 = elem.convert("entropy298", "J/kmol/K", ENTROPY298_UNKNOWN);
663 } catch (CanteraError&) {
664 }
665 }
666
667 // Check for duplicates
668 auto iter = find(m_elementNames.begin(), m_elementNames.end(), symbol);
669 if (iter != m_elementNames.end()) {
670 size_t m = iter - m_elementNames.begin();
671 if (m_atomicWeights[m] != weight) {
672 throw CanteraError("Phase::addElement",
673 "Duplicate elements ({}) have different weights", symbol);
674 } else {
675 // Ignore attempt to add duplicate element with the same weight
676 return m;
677 }
678 }
679
680 // Add the new element
681 m_atomicWeights.push_back(weight);
682 m_elementNames.push_back(symbol);
683 m_atomicNumbers.push_back(atomic_number);
684 m_entropy298.push_back(entropy298);
685 if (symbol == "E") {
687 } else {
688 m_elem_type.push_back(elem_type);
689 }
690 m_mm++;
691
692 // Update species compositions
693 if (m_kk) {
694 vector<double> old(m_speciesComp);
695 m_speciesComp.resize(m_kk*m_mm, 0.0);
696 for (size_t k = 0; k < m_kk; k++) {
697 size_t m_old = m_mm - 1;
698 for (size_t m = 0; m < m_old; m++) {
699 m_speciesComp[k * m_mm + m] = old[k * (m_old) + m];
700 }
701 m_speciesComp[k * (m_mm) + (m_mm-1)] = 0.0;
702 }
703 }
704
705 return m_mm-1;
706}
707
708bool Phase::addSpecies(shared_ptr<Species> spec)
709{
710 if (m_nSpeciesLocks) {
711 throw CanteraError("Phase::addSpecies",
712 "Cannot add species to ThermoPhase '{}' because it is being "
713 "used by another object,\nsuch as a Reactor, Domain1D (flame), "
714 "SolutionArray, or MultiPhase (Mixture) object.", m_name);
715 }
716
717 if (m_species.find(spec->name) != m_species.end()) {
718 throw CanteraError("Phase::addSpecies",
719 "Phase '{}' already contains a species named '{}'.",
720 m_name, spec->name);
721 }
722
723 vector<double> comp(nElements());
724 for (const auto& [eName, stoich] : spec->composition) {
725 size_t m = elementIndex(eName, false);
726 if (m == npos) { // Element doesn't exist in this phase
728 case UndefElement::ignore:
729 return false;
730
731 case UndefElement::add:
732 addElement(eName);
733 comp.resize(nElements());
734 m = elementIndex(eName, true);
735 break;
736
737 case UndefElement::error:
738 default:
739 throw CanteraError("Phase::addSpecies",
740 "Species '{}' contains an undefined element '{}'.",
741 spec->name, eName);
742 }
743 }
744 comp[m] = stoich;
745 }
746
747 size_t ne = nElements();
748 auto aw = atomicWeights();
749 if (spec->charge != 0.0) {
750 size_t eindex = elementIndex("E", false);
751 if (eindex != npos) {
752 double ecomp = comp[eindex];
753 if (fabs(spec->charge + ecomp) > 0.001) {
754 if (ecomp != 0.0) {
755 throw CanteraError("Phase::addSpecies",
756 "Input charge and element E compositions differ "
757 "for species " + spec->name);
758 } else {
759 // Just fix up the element E composition based on the input
760 // species charge
761 comp[eindex] = -spec->charge;
762 }
763 }
764 } else {
765 addElement("E", 0.000545, 0, 0.0, CT_ELEM_TYPE_ELECTRONCHARGE);
766 ne = nElements();
767 eindex = elementIndex("E", true);
768 comp.resize(ne);
769 comp[ne - 1] = - spec->charge;
770 }
771 }
772
773 double wt = 0.0;
774 for (size_t m = 0; m < ne; m++) {
775 wt += comp[m] * aw[m];
776 }
777
778 // Some surface phases may define species representing empty sites
779 // that have zero molecular weight. Give them a very small molecular
780 // weight to avoid dividing by zero.
781 wt = std::max(wt, Tiny);
782
783 spec->setMolecularWeight(wt);
784
785 m_molwts.push_back(wt);
786 m_rmolwts.push_back(1.0/wt);
787
788 for (size_t m = 0; m < ne; m++) {
789 m_speciesComp.push_back(comp[m]);
790 }
791
792 m_speciesNames.push_back(spec->name);
793 m_species[spec->name] = spec;
794 m_speciesIndices[spec->name] = m_kk;
795 m_speciesCharge.push_back(spec->charge);
796
797 string nLower = toLowerCopy(spec->name);
798 if (m_speciesLower.find(nLower) == m_speciesLower.end()) {
799 m_speciesLower[nLower] = m_kk;
800 } else {
801 m_speciesLower[nLower] = npos;
802 }
803 m_kk++;
804
805 // Ensure that the Phase has a valid mass fraction vector that sums to
806 // one. We will assume that species 0 has a mass fraction of 1.0 and mass
807 // fraction of all other species is 0.0.
808 if (m_kk == 1) {
809 m_y.push_back(1.0);
810 m_ym.push_back(m_rmolwts[0]);
811 m_mmw = 1.0 / m_ym[0];
812 } else {
813 m_y.push_back(0.0);
814 m_ym.push_back(0.0);
815 }
816 m_workS.push_back(0.0);
818 return true;
819}
820
821void Phase::modifySpecies(size_t k, shared_ptr<Species> spec)
822{
823 if (speciesName(k) != spec->name) {
824 throw CanteraError("Phase::modifySpecies",
825 "New species name '{}' does not match existing name '{}'",
826 spec->name, speciesName(k));
827 }
828 const shared_ptr<Species>& old = m_species[spec->name];
829 if (spec->composition != old->composition) {
830 throw CanteraError("Phase::modifySpecies",
831 "New composition for '{}' does not match existing composition",
832 spec->name);
833 }
834 m_species[spec->name] = spec;
836}
837
838void Phase::addSpeciesAlias(const string& name, const string& alias)
839{
840 if (speciesIndex(alias, false) != npos) {
841 throw CanteraError("Phase::addSpeciesAlias",
842 "Invalid alias '{}': species already exists", alias);
843 }
844 size_t k = speciesIndex(name, false);
845 if (k != npos) {
846 m_speciesIndices[alias] = k;
847 } else {
848 throw CanteraError("Phase::addSpeciesAlias",
849 "Unable to add alias '{}' "
850 "(original species '{}' not found).", alias, name);
851 }
852}
853
855{
856 if (!m_nSpeciesLocks) {
857 throw CanteraError("Phase::removeSpeciesLock",
858 "ThermoPhase '{}' has no current species locks.", m_name);
859 }
861}
862
863vector<string> Phase::findIsomers(const Composition& compMap) const
864{
865 vector<string> isomerNames;
866
867 for (const auto& [name, species] : m_species) {
868 if (species->composition == compMap) {
869 isomerNames.emplace_back(name);
870 }
871 }
872
873 return isomerNames;
874}
875
876vector<string> Phase::findIsomers(const string& comp) const
877{
878 return findIsomers(parseCompString(comp));
879}
880
881shared_ptr<Species> Phase::species(const string& name) const
882{
883 size_t k = speciesIndex(name, true);
884 return m_species.at(speciesName(k));
885}
886
887shared_ptr<Species> Phase::species(size_t k) const
888{
890 return m_species.at(m_speciesNames[k]);
891}
892
894 m_undefinedElementBehavior = UndefElement::ignore;
895}
896
898 m_undefinedElementBehavior = UndefElement::add;
899}
900
902 m_undefinedElementBehavior = UndefElement::error;
903}
904
905bool Phase::ready() const
906{
907 return (m_kk > 0);
908}
909
911 m_stateNum++;
912 m_cache.clear();
913}
914
915void Phase::setMolecularWeight(const int k, const double mw)
916{
917 m_molwts[k] = mw;
918 m_rmolwts[k] = 1.0/mw;
919
920 transform(m_y.begin(), m_y.end(), m_rmolwts.begin(), m_ym.begin(),
921 multiplies<double>());
922 m_mmw = 1.0 / accumulate(m_ym.begin(), m_ym.end(), 0.0);
923}
924
926 m_stateNum++;
927}
928
929vector<double> Phase::getCompositionFromMap(const Composition& comp) const
930{
931 vector<double> X(m_kk);
932 for (const auto& [name, value] : comp) {
933 size_t loc = speciesIndex(name, true);
934 X[loc] = value;
935 }
936 return X;
937}
938
939void Phase::massFractionsToMoleFractions(span<const double> Y, span<double> X) const
940{
941 checkArraySize("Phase::massFractionsToMoleFractions", Y.size(), m_kk);
942 checkArraySize("Phase::massFractionsToMoleFractions", X.size(), m_kk);
943 double rmmw = 0.0;
944 for (size_t k = 0; k != m_kk; ++k) {
945 rmmw += Y[k]/m_molwts[k];
946 }
947 if (rmmw == 0.0) {
948 throw CanteraError("Phase::massFractionsToMoleFractions",
949 "no input composition given");
950 }
951 for (size_t k = 0; k != m_kk; ++k) {
952 X[k] = Y[k]/(rmmw*m_molwts[k]);
953 }
954}
955
956void Phase::moleFractionsToMassFractions(span<const double> X, span<double> Y) const
957{
958 checkArraySize("Phase::moleFractionsToMassFractions", X.size(), m_kk);
959 checkArraySize("Phase::moleFractionsToMassFractions", Y.size(), m_kk);
960 double mmw = dot(m_molwts.begin(), m_molwts.end(), X.begin());
961 if (mmw == 0.0) {
962 throw CanteraError("Phase::moleFractionsToMassFractions",
963 "no input composition given");
964 }
965 double rmmw = 1.0/mmw;
966 for (size_t k = 0; k != m_kk; ++k) {
967 Y[k] = X[k]*m_molwts[k]*rmmw;
968 }
969}
970
971} // namespace Cantera
#define CT_ELEM_TYPE_ELECTRONCHARGE
This refers to conservation of electrons.
Definition Elements.h:41
#define ENTROPY298_UNKNOWN
Number indicating we don't know the entropy of the element in its most stable state at 298....
Definition Elements.h:85
Header file for class Phase.
Declaration for class Cantera::Species.
Headers for the factory class that can create known ThermoPhase objects (see Thermodynamic Properties...
A map of string keys to values whose type can vary at runtime.
Definition AnyMap.h:431
double convert(const string &key, const string &units) const
Convert the item stored by the given key to the units specified in units.
Definition AnyMap.cpp:1595
static AnyMap fromYamlFile(const string &name, const string &parent_name="")
Create an AnyMap from a YAML file.
Definition AnyMap.cpp:1841
Base class for exceptions thrown by Cantera classes.
An array index is out of range.
void getMoleFractions(span< double > x) const
Get the species mole fraction vector.
Definition Phase.cpp:441
void getMassFractions(span< double > y) const
Get the species mass fractions.
Definition Phase.cpp:479
span< const double > inverseMolecularWeights() const
Return a const reference to the internal vector of molecular weights.
Definition Phase.cpp:406
virtual vector< string > partialStates() const
Return a vector of settable partial property sets within a phase.
Definition Phase.cpp:212
map< string, size_t > m_speciesLower
Map of lower-case species names to indices.
Definition Phase.h:948
double massFraction(size_t k) const
Return the mass fraction of a single species.
Definition Phase.cpp:463
virtual double molarDensity() const
Molar density (kmol/m^3).
Definition Phase.cpp:587
void assignDensity(const double density_)
Set the internally stored constant density (kg/m^3) of the phase.
Definition Phase.cpp:608
virtual bool addSpecies(shared_ptr< Species > spec)
Add a Species to this Phase.
Definition Phase.cpp:708
int changeElementType(int m, int elem_type)
Change the element type of the mth constraint Reassigns an element type.
Definition Phase.cpp:94
virtual vector< string > fullStates() const
Return a vector containing full states defining a phase.
Definition Phase.cpp:194
void assertCompressible(const string &setter) const
Ensure that phase is compressible.
Definition Phase.h:835
vector< double > m_workS
Vector of size m_kk, used as a temporary holding area.
Definition Phase.h:899
vector< double > m_speciesComp
Atomic composition of the species.
Definition Phase.h:884
ValueCache m_cache
Cached for saved calculations within each ThermoPhase.
Definition Phase.h:855
size_t m_nSpeciesLocks
Reference counter preventing species addition.
Definition Phase.h:890
vector< string > m_speciesNames
Vector of the species names.
Definition Phase.h:942
size_t nSpecies() const
Returns the number of species in the phase.
Definition Phase.h:246
size_t checkElementIndex(size_t m) const
Check that the specified element index is in range.
Definition Phase.cpp:35
bool m_caseSensitiveSpecies
Flag determining whether case sensitive species names are enforced.
Definition Phase.h:896
vector< string > m_elementNames
element names
Definition Phase.h:953
void ignoreUndefinedElements()
Set behavior when adding a species containing undefined elements to just skip the species.
Definition Phase.cpp:893
UndefElement::behavior m_undefinedElementBehavior
Flag determining behavior when adding species with an undefined element.
Definition Phase.h:893
virtual map< string, size_t > nativeState() const
Return a map of properties defining the native state of a substance.
Definition Phase.cpp:164
double chargeDensity() const
Charge density [C/m^3].
Definition Phase.cpp:618
void addUndefinedElements()
Set behavior when adding a species containing undefined elements to add those elements to the phase.
Definition Phase.cpp:897
vector< int > m_atomicNumbers
element atomic numbers
Definition Phase.h:952
size_t m_kk
Number of species in the phase.
Definition Phase.h:875
int atomicNumber(size_t m) const
Atomic number of element m.
Definition Phase.cpp:84
virtual void modifySpecies(size_t k, shared_ptr< Species > spec)
Modify the thermodynamic data associated with a species.
Definition Phase.cpp:821
virtual void setMolesNoTruncate(span< const double > N)
Set the state of the object with moles in [kmol].
Definition Phase.cpp:540
double m_mmw
mean molecular weight of the mixture (kg kmol-1)
Definition Phase.h:920
double elementalMoleFraction(const size_t m) const
Elemental mole fraction of element m.
Definition Phase.cpp:570
size_t speciesIndex(const string &name, bool raise=true) const
Returns the index of a species named 'name' within the Phase object.
Definition Phase.cpp:127
void massFractionsToMoleFractions(span< const double > Y, span< double > X) const
Converts a mixture composition from mole fractions to mass fractions.
Definition Phase.cpp:939
span< const double > molecularWeights() const
Return a const reference to the internal vector of molecular weights.
Definition Phase.cpp:401
void setState_TD(double t, double rho)
Set the internally stored temperature (K) and density (kg/m^3)
Definition Phase.cpp:375
vector< double > m_rmolwts
inverse of species molecular weights (kmol kg-1)
Definition Phase.h:935
double temperature() const
Temperature (K).
Definition Phase.h:585
virtual void setPressure(double p)
Set the internally stored pressure (Pa) at constant temperature and composition.
Definition Phase.h:639
virtual bool isCompressible() const
Return whether phase represents a compressible substance.
Definition Phase.h:270
double meanMolecularWeight() const
The mean molecular weight. Units: (kg/kmol)
Definition Phase.h:676
virtual void restorePartialState(span< const double > state)
Set the internal thermodynamic state of the phase, excluding composition.
Definition Phase.cpp:237
span< const double > massFractions() const
Return a view of the mass fraction array.
Definition Phase.h:465
void removeSpeciesLock()
Decrement species lock counter.
Definition Phase.cpp:854
Composition getMoleFractionsByName(double threshold=0.0) const
Get the mole fractions by name.
Definition Phase.cpp:417
virtual double concentration(const size_t k) const
Concentration of species k.
Definition Phase.cpp:485
double atomicWeight(size_t m) const
Atomic weight of element m.
Definition Phase.cpp:69
void setMassFractionsByName(const Composition &yMap)
Set the species mass fractions by name.
Definition Phase.cpp:364
int elementType(size_t m) const
Return the element constraint type Possible types include:
Definition Phase.cpp:89
virtual void setConcentrationsNoNorm(span< const double > conc)
Set the concentrations without ignoring negative concentrations.
Definition Phase.cpp:520
string speciesName(size_t k) const
Name of the species with index k.
Definition Phase.cpp:143
void getMolecularWeights(span< double > weights) const
Copy the vector of molecular weights into array weights.
Definition Phase.cpp:394
void moleFractionsToMassFractions(span< const double > X, span< double > Y) const
Converts a mixture composition from mass fractions to mole fractions.
Definition Phase.cpp:956
map< string, size_t > m_speciesIndices
Map of species names to indices.
Definition Phase.h:945
virtual void setDensity(const double density_)
Set the internally stored density (kg/m^3) of the phase.
Definition Phase.cpp:597
Composition getMassFractionsByName(double threshold=0.0) const
Get the mass fractions by name.
Definition Phase.cpp:429
virtual size_t stateSize() const
Return size of vector defining internal state of the phase.
Definition Phase.cpp:249
string nativeMode() const
Return string acronym representing the native state of a Phase.
Definition Phase.cpp:181
vector< double > getCompositionFromMap(const Composition &comp) const
Converts a Composition to a vector with entries for each species Species that are not specified are s...
Definition Phase.cpp:929
map< string, shared_ptr< Species > > m_species
Map of Species objects.
Definition Phase.h:888
size_t findSpeciesLower(const string &nameStr) const
Find lowercase species name in m_speciesIndices when case sensitive species names are not enforced an...
Definition Phase.cpp:108
vector< double > m_molwts
species molecular weights (kg kmol-1)
Definition Phase.h:933
virtual vector< string > findIsomers(const Composition &compMap) const
Return a vector with isomers names matching a given composition map.
Definition Phase.cpp:863
virtual bool isPure() const
Return whether phase represents a pure (single species) substance.
Definition Phase.h:260
vector< double > m_y
Mass fractions of the species.
Definition Phase.h:931
void setMoleFractionsByName(const Composition &xMap)
Set the species mole fractions by name.
Definition Phase.cpp:326
vector< int > m_elem_type
Vector of element types.
Definition Phase.h:954
double sum_xlogx() const
Evaluate .
Definition Phase.cpp:633
double mean_X(span< const double > Q) const
Evaluate the mole-fraction-weighted mean of an array Q.
Definition Phase.cpp:627
string m_name
Name of the phase.
Definition Phase.h:910
double moleFraction(size_t k) const
Return the mole fraction of a single species.
Definition Phase.cpp:447
double m_dens
Density (kg m-3).
Definition Phase.h:918
virtual void setConcentrations(span< const double > conc)
Set the concentrations to the specified values within the phase.
Definition Phase.cpp:497
const vector< string > & elementNames() const
Return a read-only reference to the vector of element names.
Definition Phase.cpp:64
virtual void getConcentrations(span< double > c) const
Get the species concentrations (kmol/m^3).
Definition Phase.cpp:491
virtual double density() const
Density (kg/m^3).
Definition Phase.h:610
virtual void compositionChanged()
Apply changes to the state which are needed after the composition changes.
Definition Phase.cpp:925
vector< double > m_atomicWeights
element atomic weights (kg kmol-1)
Definition Phase.h:951
double nAtoms(size_t k, size_t m) const
Number of atoms of element m in species k.
Definition Phase.cpp:101
void addSpeciesAlias(const string &name, const string &alias)
Add a species alias (that is, a user-defined alternative species name).
Definition Phase.cpp:838
span< const double > atomicWeights() const
Return a read-only reference to the vector of atomic weights.
Definition Phase.cpp:79
size_t checkSpeciesIndex(size_t k) const
Check that the specified species index is in range.
Definition Phase.cpp:156
virtual void setTemperature(double temp)
Set the internally stored temperature of the phase (K).
Definition Phase.h:646
size_t nElements() const
Number of elements.
Definition Phase.cpp:30
void setMolecularWeight(const int k, const double mw)
Set the molecular weight of a single species to a given value.
Definition Phase.cpp:915
vector< double > m_entropy298
Entropy at 298.15 K and 1 bar of stable state pure elements (J kmol-1)
Definition Phase.h:957
void getCharges(span< double > charges) const
Copy the vector of species charges into array charges.
Definition Phase.cpp:411
virtual void setMoleFractions_NoNorm(span< const double > x)
Set the mole fractions to the specified values without normalizing.
Definition Phase.cpp:316
vector< double > m_ym
m_ym[k] = mole fraction of species k divided by the mean molecular weight of mixture.
Definition Phase.h:924
virtual void setMoleFractions(span< const double > x)
Set the mole fractions to the specified values.
Definition Phase.cpp:283
const vector< string > & speciesNames() const
Return a const reference to the vector of species names.
Definition Phase.cpp:151
size_t elementIndex(const string &name, bool raise=true) const
Return the index of element named 'name'.
Definition Phase.cpp:51
virtual void setMassFractions(span< const double > y)
Set the mass fractions to the specified values and normalize them.
Definition Phase.cpp:337
virtual bool ready() const
Returns a bool indicating whether the object is ready for use.
Definition Phase.cpp:905
double molecularWeight(size_t k) const
Molecular weight of species k.
Definition Phase.cpp:388
double elementalMassFraction(const size_t m) const
Elemental mass fraction of element m.
Definition Phase.cpp:560
shared_ptr< Species > species(const string &name) const
Return the Species object for the named species.
Definition Phase.cpp:881
virtual double molarVolume() const
Molar volume (m^3/kmol).
Definition Phase.cpp:592
virtual void invalidateCache()
Invalidate any cached values which are normally updated only when a change in state is detected.
Definition Phase.cpp:910
virtual void setMassFractions_NoNorm(span< const double > y)
Set the mass fractions to the specified values without normalizing.
Definition Phase.cpp:352
virtual size_t partialStateSize() const
Get the size of the partial state vector of the phase.
Definition Phase.h:317
virtual void savePartialState(span< double > state) const
Save the current thermodynamic state of the phase, excluding composition.
Definition Phase.cpp:225
virtual void restoreState(span< const double > state)
Restore the state of the phase from a previously saved state vector.
Definition Phase.cpp:269
int m_stateNum
State Change variable.
Definition Phase.h:939
void throwUndefinedElements()
Set the behavior when adding a species containing undefined elements to throw an exception.
Definition Phase.cpp:901
void setName(const string &nm)
Sets the string name for the phase.
Definition Phase.cpp:25
size_t m_mm
Number of elements.
Definition Phase.h:950
virtual double pressure() const
Return the thermodynamic pressure (Pa).
Definition Phase.h:603
string elementName(size_t m) const
Name of the element with index m.
Definition Phase.cpp:43
double charge(size_t k) const
Dimensionless electrical charge of a single molecule of species k The charge is normalized by the the...
Definition Phase.h:561
double entropyElement298(size_t m) const
Entropy of the element in its standard state at 298 K and 1 bar.
Definition Phase.cpp:74
vector< double > m_speciesCharge
Vector of species charges.
Definition Phase.h:886
size_t addElement(const string &symbol, double weight=-12345.0, int atomicNumber=0, double entropy298=ENTROPY298_UNKNOWN, int elem_type=CT_ELEM_TYPE_ABSPOS)
Add an element.
Definition Phase.cpp:642
string name() const
Return the name of the phase.
Definition Phase.cpp:20
virtual void saveState(span< double > state) const
Write to array 'state' the current internal state.
Definition Phase.cpp:257
void clear()
Clear all cached values.
string toLowerCopy(const string &input)
Convert to lower case.
Composition parseCompString(const string &ss, const vector< string > &names)
Parse a composition string into a map consisting of individual key:composition pairs.
double dot(InputIter x_begin, InputIter x_end, InputIter2 y_begin)
Function that calculates a templated inner product.
Definition utilities.h:96
void scale(InputIter begin, InputIter end, OutputIter out, S scale_factor)
Multiply elements of an array by a scale factor.
Definition utilities.h:118
const double Faraday
Faraday constant [C/kmol].
Definition ct_defs.h:134
Namespace for the Cantera kernel.
Definition AnyMap.cpp:595
const size_t npos
index returned by functions to indicate "no position"
Definition ct_defs.h:183
double getElementWeight(const string &ename)
Get the atomic weight of an element.
Definition Elements.cpp:251
const double Tiny
Small number to compare differences of mole fractions against.
Definition ct_defs.h:176
const double SmallNumber
smallest number to compare to zero.
Definition ct_defs.h:161
map< string, double > Composition
Map from string names to doubles.
Definition ct_defs.h:180
void checkArraySize(const char *procedure, size_t available, size_t required)
Wrapper for throwing ArraySizeError.
Contains declarations for string manipulation functions within Cantera.
Various templated functions that carry out common vector and polynomial operations (see Templated Arr...