Skip to content

Commit

Permalink
[Phase] Species molecular weight is set earlier
Browse files Browse the repository at this point in the history
Since setting the species molecular weight can throw, all modifications
to Phase member variables should be done after calling
Species::setMolecularWeight() so that the Phase instance is not left in
an inconsistent state.
  • Loading branch information
bryanwweber authored and speth committed Jun 24, 2022
1 parent c0c4cad commit 4973556
Showing 1 changed file with 24 additions and 15 deletions.
39 changes: 24 additions & 15 deletions src/thermo/Phase.cpp
Expand Up @@ -773,6 +773,7 @@ bool Phase::addSpecies(shared_ptr<Species> spec) {
"Phase '{}' already contains a species named '{}'.",
m_name, spec->name);
}

vector_fp comp(nElements());
for (const auto& elem : spec->composition) {
size_t m = elementIndex(elem.first);
Expand All @@ -797,20 +798,7 @@ bool Phase::addSpecies(shared_ptr<Species> spec) {
comp[m] = elem.second;
}

m_speciesNames.push_back(spec->name);
m_species[spec->name] = spec;
m_speciesIndices[spec->name] = m_kk;
m_speciesCharge.push_back(spec->charge);
size_t ne = nElements();

std::string nLower = toLowerCopy(spec->name);
if (m_speciesLower.find(nLower) == m_speciesLower.end()) {
m_speciesLower[nLower] = m_kk;
} else {
m_speciesLower[nLower] = npos;
}

double wt = 0.0;
const vector_fp& aw = atomicWeights();
if (spec->charge != 0.0) {
size_t eindex = elementIndex("E");
Expand All @@ -835,18 +823,39 @@ bool Phase::addSpecies(shared_ptr<Species> spec) {
comp[ne - 1] = - spec->charge;
}
}

double wt = 0.0;
for (size_t m = 0; m < ne; m++) {
m_speciesComp.push_back(comp[m]);
wt += comp[m] * aw[m];
}

// Some surface phases may define species representing empty sites
// that have zero molecular weight. Give them a very small molecular
// weight to avoid dividing by zero.
wt = std::max(wt, Tiny);

// Since this method can throw, all the modifications of the member variables
// should be done after this method call to avoid inconsistent state.
spec->setMolecularWeight(wt);

m_molwts.push_back(wt);
m_rmolwts.push_back(1.0/wt);
spec->setMolecularWeight(wt);

for (size_t m = 0; m < ne; m++) {
m_speciesComp.push_back(comp[m]);
}

m_speciesNames.push_back(spec->name);
m_species[spec->name] = spec;
m_speciesIndices[spec->name] = m_kk;
m_speciesCharge.push_back(spec->charge);

std::string nLower = toLowerCopy(spec->name);
if (m_speciesLower.find(nLower) == m_speciesLower.end()) {
m_speciesLower[nLower] = m_kk;
} else {
m_speciesLower[nLower] = npos;
}
m_kk++;

// Ensure that the Phase has a valid mass fraction vector that sums to
Expand Down

0 comments on commit 4973556

Please sign in to comment.