Cantera  4.0.0a1
Loading...
Searching...
No Matches
Kinetics.cpp
Go to the documentation of this file.
1/**
2 * @file Kinetics.cpp Declarations for the base class for kinetics managers
3 * (see @ref kineticsmgr and class @link Cantera::Kinetics Kinetics @endlink).
4 *
5 * Kinetics managers calculate rates of progress of species due to
6 * homogeneous or heterogeneous kinetics.
7 */
8
9// This file is part of Cantera. See License.txt in the top-level directory or
10// at https://cantera.org/license.txt for license and copyright information.
11
18#include "cantera/base/global.h"
19#include <unordered_set>
20#include <boost/algorithm/string.hpp>
21
22using namespace std;
23
24namespace Cantera
25{
26
27shared_ptr<Kinetics> Kinetics::clone(
28 const vector<shared_ptr<ThermoPhase>>& phases) const
29{
30 vector<AnyMap> reactionDefs;
31 for (size_t i = 0; i < nReactions(); i++) {
32 reactionDefs.push_back(reaction(i)->parameters());
33 }
34 AnyMap phaseNode = parameters();
35 phaseNode["__fix-duplicate-reactions__"] = true;
36 AnyMap rootNode;
37 rootNode["reactions"] = std::move(reactionDefs);
38 rootNode.applyUnits();
39 return newKinetics(phases, phaseNode, rootNode, phases[0]->root());
40}
41
42size_t Kinetics::checkReactionIndex(size_t i) const
43{
44 if (i < nReactions()) {
45 return i;
46 }
47 throw IndexError("Kinetics::checkReactionIndex", "reactions", i, nReactions());
48}
49
51{
52 size_t nRxn = nReactions();
53
54 // Stoichiometry managers
58
59 m_rbuf.resize(nRxn);
60
61 // products are created for positive net rate of progress
63 // reactants are destroyed for positive net rate of progress
65}
66
67size_t Kinetics::checkPhaseIndex(size_t m) const
68{
69 if (m < nPhases()) {
70 return m;
71 }
72 throw IndexError("Kinetics::checkPhaseIndex", "phase", m, nPhases());
73}
74
75size_t Kinetics::phaseIndex(const string& ph, bool raise) const
76{
77 if (m_phaseindex.find(ph) == m_phaseindex.end()) {
78 if (raise) {
79 throw CanteraError("Kinetics::phaseIndex", "Phase '{}' not found", ph);
80 }
81 return npos;
82 } else {
83 return m_phaseindex.at(ph) - 1;
84 }
85}
86
87shared_ptr<ThermoPhase> Kinetics::reactionPhase() const
88{
89 return m_thermo[0];
90}
91
92size_t Kinetics::checkSpeciesIndex(size_t k) const
93{
94 if (k < m_kk) {
95 return k;
96 }
97 throw IndexError("Kinetics::checkSpeciesIndex", "species", k, m_kk);
98}
99
101{
102 if (flag == "warn" || flag == "error" || flag == "mark-duplicate"
103 || flag == "modify-efficiency")
104 {
105 m_explicit_third_body_duplicates = flag;
106 } else {
107 throw CanteraError("Kinetics::setExplicitThirdBodyDuplicateHandling",
108 "Invalid flag '{}'", flag);
109 }
110}
111
112pair<size_t, size_t> Kinetics::checkDuplicates(bool throw_err, bool fix)
113{
114 //! Map of (key indicating participating species) to reaction numbers
115 map<size_t, vector<size_t>> participants;
116 vector<map<int, double>> net_stoich;
117 std::unordered_set<size_t> unmatched_duplicates;
118 for (size_t i = 0; i < m_reactions.size(); i++) {
119 if (m_reactions[i]->duplicate) {
120 unmatched_duplicates.insert(i);
121 }
122 }
123
124 vector<InputFileError> errs;
125 for (size_t i = 0; i < m_reactions.size(); i++) {
126 // Get data about this reaction
127 unsigned long int key = 0;
128 Reaction& R = *m_reactions[i];
129 net_stoich.emplace_back();
130 map<int, double>& net = net_stoich.back();
131 for (const auto& [name, stoich] : R.reactants) {
132 int k = static_cast<int>(kineticsSpeciesIndex(name));
133 key += k*(k+1);
134 net[-1 -k] -= stoich;
135 }
136 for (const auto& [name, stoich] : R.products) {
137 int k = static_cast<int>(kineticsSpeciesIndex(name));
138 key += k*(k+1);
139 net[1+k] += stoich;
140 }
141
142 // Compare this reaction to others with similar participants
143 vector<size_t>& related = participants[key];
144 for (size_t m : related) {
145 Reaction& other = *m_reactions[m];
146 if (R.duplicate && other.duplicate) {
147 // marked duplicates
148 unmatched_duplicates.erase(i);
149 unmatched_duplicates.erase(m);
150 continue;
151 } else if (R.type() != other.type()) {
152 continue; // different reaction types
153 } else if (R.rate() && other.rate()
154 && R.rate()->type() != other.rate()->type())
155 {
156 continue; // different rate parameterizations
157 }
158 double c = checkDuplicateStoich(net_stoich[i], net_stoich[m]);
159 if (c == 0) {
160 continue; // stoichiometries differ (not by a multiple)
161 } else if (c < 0.0 && !R.reversible && !other.reversible) {
162 continue; // irreversible reactions in opposite directions
163 } else if (R.usesThirdBody() && other.usesThirdBody()) {
164 ThirdBody& tb1 = *(R.thirdBody());
165 ThirdBody& tb2 = *(other.thirdBody());
166 bool thirdBodyOk = true;
167 for (size_t k = 0; k < nTotalSpecies(); k++) {
168 string s = kineticsSpeciesName(k);
169 if (tb1.efficiency(s) * tb2.efficiency(s) != 0.0) {
170 // non-zero third body efficiencies for species `s` in
171 // both reactions
172 thirdBodyOk = false;
173 break;
174 }
175 }
176 if (thirdBodyOk) {
177 continue; // No overlap in third body efficiencies
178 } else if ((tb1.name() == "M") != (tb2.name() == "M")) {
179 // Exactly one of the reactions uses M as the third body
180 if (m_explicit_third_body_duplicates == "mark-duplicate") {
181 R.duplicate = true;
182 other.duplicate = true;
183 continue;
184 } else if (m_explicit_third_body_duplicates == "modify-efficiency") {
185 if (tb1.name() == "M") {
186 tb1.efficiencies[tb2.name()] = 0.0;
187 } else {
188 tb2.efficiencies[tb1.name()] = 0.0;
189 }
190 continue;
191 } else if (m_explicit_third_body_duplicates == "warn") {
192 InputFileError msg("Kinetics::checkDuplicates",
193 R.input, other.input,
194 "Undeclared duplicate third body reactions with a common "
195 "third body detected.\nAdd the field "
196 "'explicit-third-body-duplicates: mark-duplicate' or\n"
197 "'explicit-third-body-duplicates: modify-efficiency' to "
198 "the YAML phase entry\nto choose how these reactions "
199 "should be handled and suppress this warning.\n"
200 "Reaction {}: {}\nReaction {}: {}\n",
201 m+1, R.equation(), i+1, other.equation());
202 if (!fix) {
203 warn_user("Kinetics::checkDuplicates", msg.what());
204 }
205 continue;
206 } // else m_explicit_third_body_duplicates == "error"
207 }
208 }
209 if (throw_err) {
210 errs.emplace_back("Kinetics::checkDuplicates",
211 R.input, other.input,
212 "Undeclared duplicate reactions detected:\n"
213 "Reaction {}: {}\nReaction {}: {}\n",
214 m+1, R.equation(), i+1, other.equation());
215 } else if (fix) {
216 R.duplicate = true;
217 other.duplicate = true;
218 unmatched_duplicates.erase(i);
219 unmatched_duplicates.erase(m);
220 } else {
221 return {i,m};
222 }
223 }
224 participants[key].push_back(i);
225 }
226 if (unmatched_duplicates.size()) {
227 for (auto i : unmatched_duplicates) {
228 if (throw_err) {
229 errs.emplace_back("Kinetics::checkDuplicates",
230 m_reactions[i]->input,
231 "No duplicate found for declared duplicate reaction number {}"
232 " ({})", i, m_reactions[i]->equation());
233 } else if (fix) {
234 m_reactions[i]->duplicate = false;
235 } else {
236 return {i, i};
237 }
238 }
239 }
240 if (errs.empty()) {
241 return {npos, npos};
242 } else if (errs.size() == 1) {
243 throw errs[0];
244 } else {
245 fmt::memory_buffer msg;
246 for (const auto& err : errs) {
247 fmt_append(msg, "\n{}\n", err.getMessage());
248 }
249 throw CanteraError("Kinetics::checkDuplicates", to_string(msg));
250 }
251}
252
253double Kinetics::checkDuplicateStoich(map<int, double>& r1, map<int, double>& r2) const
254{
255 std::unordered_set<int> keys; // species keys (k+1 or -k-1)
256 for (auto& [speciesKey, stoich] : r1) {
257 keys.insert(speciesKey);
258 }
259 for (auto& [speciesKey, stoich] : r2) {
260 keys.insert(speciesKey);
261 }
262 int k1 = r1.begin()->first;
263 // check for duplicate written in the same direction
264 double ratio = 0.0;
265 if (r1[k1] && r2[k1]) {
266 ratio = r2[k1]/r1[k1];
267 bool different = false;
268 for (int k : keys) {
269 if ((r1[k] && !r2[k]) ||
270 (!r1[k] && r2[k]) ||
271 (r1[k] && fabs(r2[k]/r1[k] - ratio) > 1.e-8)) {
272 different = true;
273 break;
274 }
275 }
276 if (!different) {
277 return ratio;
278 }
279 }
280
281 // check for duplicate written in the reverse direction
282 if (r1[k1] == 0.0 || r2[-k1] == 0.0) {
283 return 0.0;
284 }
285 ratio = r2[-k1]/r1[k1];
286 for (int k : keys) {
287 if ((r1[k] && !r2[-k]) ||
288 (!r1[k] && r2[-k]) ||
289 (r1[k] && fabs(r2[-k]/r1[k] - ratio) > 1.e-8)) {
290 return 0.0;
291 }
292 }
293 return ratio;
294}
295
296string Kinetics::kineticsSpeciesName(size_t k) const
297{
298 for (size_t n = m_start.size()-1; n != npos; n--) {
299 if (k >= m_start[n]) {
300 return thermo(n).speciesName(k - m_start[n]);
301 }
302 }
303 throw IndexError("Kinetics::kineticsSpeciesName", "totalSpecies", k, m_kk);
304}
305
306size_t Kinetics::kineticsSpeciesIndex(const string& nm, bool raise) const
307{
308 for (size_t n = 0; n < m_thermo.size(); n++) {
309 // Check the ThermoPhase object for a match
310 size_t k = thermo(n).speciesIndex(nm, false);
311 if (k != npos) {
312 return k + m_start[n];
313 }
314 }
315 if (raise) {
316 throw CanteraError("Kinetics::kineticsSpeciesIndex",
317 "Species '{}' not found", nm);
318 }
319 return npos;
320}
321
322size_t Kinetics::speciesOffset(const ThermoPhase& phase) const
323{
324 for (size_t n = 0; n < m_thermo.size(); n++) {
325 if (&phase == m_thermo[n].get()) {
326 return m_start[n];
327 }
328 }
329 throw CanteraError("Kinetics::speciesOffset",
330 "Phase '{}' not found in Kinetics object", phase.name());
331}
332
334{
335 for (size_t n = 0; n < m_thermo.size(); n++) {
336 size_t k = thermo(n).speciesIndex(nm, false);
337 if (k != npos) {
338 return thermo(n);
339 }
340 }
341 throw CanteraError("Kinetics::speciesPhase", "unknown species '{}'", nm);
342}
343
344const ThermoPhase& Kinetics::speciesPhase(const string& nm) const
345{
346 for (const auto& thermo : m_thermo) {
347 if (thermo->speciesIndex(nm, false) != npos) {
348 return *thermo;
349 }
350 }
351 throw CanteraError("Kinetics::speciesPhase", "unknown species '{}'", nm);
352}
353
354size_t Kinetics::speciesPhaseIndex(size_t k) const
355{
356 for (size_t n = m_start.size()-1; n != npos; n--) {
357 if (k >= m_start[n]) {
358 return n;
359 }
360 }
361 throw CanteraError("Kinetics::speciesPhaseIndex",
362 "illegal species index: {}", k);
363}
364
365double Kinetics::reactantStoichCoeff(size_t kSpec, size_t irxn) const
366{
367 return m_reactantStoich.stoichCoeffs().coeff(kSpec, irxn);
368}
369
370double Kinetics::productStoichCoeff(size_t kSpec, size_t irxn) const
371{
372 return m_productStoich.stoichCoeffs().coeff(kSpec, irxn);
373}
374
376{
377 updateROP();
378 std::copy(m_ropf.begin(), m_ropf.end(), fwdROP);
379}
380
382{
383 updateROP();
384 std::copy(m_ropr.begin(), m_ropr.end(), revROP);
385}
386
388{
389 updateROP();
390 std::copy(m_ropnet.begin(), m_ropnet.end(), netROP);
391}
392
393void Kinetics::getReactionDelta(const double* prop, double* deltaProp) const
394{
395 fill(deltaProp, deltaProp + nReactions(), 0.0);
396 // products add
397 m_productStoich.incrementReactions(prop, deltaProp);
398 // reactants subtract
399 m_reactantStoich.decrementReactions(prop, deltaProp);
400}
401
402void Kinetics::getRevReactionDelta(const double* prop, double* deltaProp) const
403{
404 fill(deltaProp, deltaProp + nReactions(), 0.0);
405 // products add
406 m_revProductStoich.incrementReactions(prop, deltaProp);
407 // reactants subtract
408 m_reactantStoich.decrementReactions(prop, deltaProp);
409}
410
412{
413 updateROP();
414
415 // zero out the output array
416 fill(cdot, cdot + m_kk, 0.0);
417
418 // the forward direction creates product species
419 m_productStoich.incrementSpecies(m_ropf.data(), cdot);
420
421 // the reverse direction creates reactant species
422 m_reactantStoich.incrementSpecies(m_ropr.data(), cdot);
423}
424
426{
427 updateROP();
428
429 fill(ddot, ddot + m_kk, 0.0);
430 // the reverse direction destroys products in reversible reactions
431 m_revProductStoich.incrementSpecies(m_ropr.data(), ddot);
432 // the forward direction destroys reactants
433 m_reactantStoich.incrementSpecies(m_ropf.data(), ddot);
434}
435
437{
438 updateROP();
439
440 fill(net, net + m_kk, 0.0);
441 // products are created for positive net rate of progress
442 m_productStoich.incrementSpecies(m_ropnet.data(), net);
443 // reactants are destroyed for positive net rate of progress
444 m_reactantStoich.decrementSpecies(m_ropnet.data(), net);
445}
446
448{
449 Eigen::Map<Eigen::VectorXd> out(dwdot, m_kk);
450 Eigen::Map<Eigen::VectorXd> buf(m_rbuf.data(), nReactions());
451 // the forward direction creates product species
452 getFwdRatesOfProgress_ddT(buf.data());
453 out = m_productStoich.stoichCoeffs() * buf;
454 // the reverse direction creates reactant species
455 getRevRatesOfProgress_ddT(buf.data());
456 out += m_reactantStoich.stoichCoeffs() * buf;
457}
458
460{
461 Eigen::Map<Eigen::VectorXd> out(dwdot, m_kk);
462 Eigen::Map<Eigen::VectorXd> buf(m_rbuf.data(), nReactions());
463 // the forward direction creates product species
464 getFwdRatesOfProgress_ddP(buf.data());
465 out = m_productStoich.stoichCoeffs() * buf;
466 // the reverse direction creates reactant species
467 getRevRatesOfProgress_ddP(buf.data());
468 out += m_reactantStoich.stoichCoeffs() * buf;
469}
470
472{
473 Eigen::Map<Eigen::VectorXd> out(dwdot, m_kk);
474 Eigen::Map<Eigen::VectorXd> buf(m_rbuf.data(), nReactions());
475 // the forward direction creates product species
476 getFwdRatesOfProgress_ddC(buf.data());
477 out = m_productStoich.stoichCoeffs() * buf;
478 // the reverse direction creates reactant species
479 getRevRatesOfProgress_ddC(buf.data());
480 out += m_reactantStoich.stoichCoeffs() * buf;
481}
482
483Eigen::SparseMatrix<double> Kinetics::creationRates_ddX()
484{
485 Eigen::SparseMatrix<double> jac;
486 // the forward direction creates product species
488 // the reverse direction creates reactant species
490 return jac;
491}
492
493Eigen::SparseMatrix<double> Kinetics::creationRates_ddCi()
494{
495 Eigen::SparseMatrix<double> jac;
496 // the forward direction creates product species
498 // the reverse direction creates reactant species
500 return jac;
501}
502
504{
505 Eigen::Map<Eigen::VectorXd> out(dwdot, m_kk);
506 Eigen::Map<Eigen::VectorXd> buf(m_rbuf.data(), nReactions());
507 // the reverse direction destroys products in reversible reactions
508 getRevRatesOfProgress_ddT(buf.data());
509 out = m_revProductStoich.stoichCoeffs() * buf;
510 // the forward direction destroys reactants
511 getFwdRatesOfProgress_ddT(buf.data());
512 out += m_reactantStoich.stoichCoeffs() * buf;
513}
514
516{
517 Eigen::Map<Eigen::VectorXd> out(dwdot, m_kk);
518 Eigen::Map<Eigen::VectorXd> buf(m_rbuf.data(), nReactions());
519 // the reverse direction destroys products in reversible reactions
520 getRevRatesOfProgress_ddP(buf.data());
521 out = m_revProductStoich.stoichCoeffs() * buf;
522 // the forward direction destroys reactants
523 getFwdRatesOfProgress_ddP(buf.data());
524 out += m_reactantStoich.stoichCoeffs() * buf;
525}
526
528{
529 Eigen::Map<Eigen::VectorXd> out(dwdot, m_kk);
530 Eigen::Map<Eigen::VectorXd> buf(m_rbuf.data(), nReactions());
531 // the reverse direction destroys products in reversible reactions
532 getRevRatesOfProgress_ddC(buf.data());
533 out = m_revProductStoich.stoichCoeffs() * buf;
534 // the forward direction destroys reactants
535 getFwdRatesOfProgress_ddC(buf.data());
536 out += m_reactantStoich.stoichCoeffs() * buf;
537}
538
539Eigen::SparseMatrix<double> Kinetics::destructionRates_ddX()
540{
541 Eigen::SparseMatrix<double> jac;
542 // the reverse direction destroys products in reversible reactions
544 // the forward direction destroys reactants
546 return jac;
547}
548
549Eigen::SparseMatrix<double> Kinetics::destructionRates_ddCi()
550{
551 Eigen::SparseMatrix<double> jac;
552 // the reverse direction destroys products in reversible reactions
554 // the forward direction destroys reactants
556 return jac;
557}
558
560{
561 Eigen::Map<Eigen::VectorXd> out(dwdot, m_kk);
562 Eigen::Map<Eigen::VectorXd> buf(m_rbuf.data(), nReactions());
563 getNetRatesOfProgress_ddT(buf.data());
564 out = m_stoichMatrix * buf;
565}
566
568{
569 Eigen::Map<Eigen::VectorXd> out(dwdot, m_kk);
570 Eigen::Map<Eigen::VectorXd> buf(m_rbuf.data(), nReactions());
571 getNetRatesOfProgress_ddP(buf.data());
572 out = m_stoichMatrix * buf;
573}
574
576{
577 Eigen::Map<Eigen::VectorXd> out(dwdot, m_kk);
578 Eigen::Map<Eigen::VectorXd> buf(m_rbuf.data(), nReactions());
579 getNetRatesOfProgress_ddC(buf.data());
580 out = m_stoichMatrix * buf;
581}
582
583Eigen::SparseMatrix<double> Kinetics::netProductionRates_ddX()
584{
586}
587
588Eigen::SparseMatrix<double> Kinetics::netProductionRates_ddCi()
589{
591}
592
593void Kinetics::addThermo(shared_ptr<ThermoPhase> thermo)
594{
595 // the phase with lowest dimensionality is assumed to be the
596 // phase/interface at which reactions take place
597 if (thermo->nDim() <= m_mindim) {
598 if (!m_thermo.empty()) {
599 throw CanteraError("Kinetics::addThermo",
600 "The reacting (lowest dimensional) phase must be added first.");
601 }
602 m_mindim = thermo->nDim();
603 }
604
605 m_thermo.push_back(thermo);
606 m_phaseindex[m_thermo.back()->name()] = nPhases();
608}
609
610void Kinetics::setParameters(const AnyMap& phaseNode) {
611 skipUndeclaredThirdBodies(phaseNode.getBool("skip-undeclared-third-bodies", false));
613 phaseNode.getString("explicit-third-body-duplicates", "warn"));
614
615 if (phaseNode.hasKey("rate-multipliers")) {
616 const auto& defaultMultipliers = phaseNode["rate-multipliers"];
617 for (auto& [key, val] : defaultMultipliers) {
618 if (key == "default") {
619 m_defaultPerturb[-1] = val.asDouble();
620 } else {
621 m_defaultPerturb[stoi(key)] = val.asDouble();
622 }
623 }
624 }
625}
626
628{
629 AnyMap out;
630 string name = KineticsFactory::factory()->canonicalize(kineticsType());
631 if (name != "none") {
632 out["kinetics"] = name;
633 if (nReactions() == 0) {
634 out["reactions"] = "none";
635 }
637 out["skip-undeclared-third-bodies"] = true;
638 }
639 if (m_explicit_third_body_duplicates == "error") {
640 // "warn" is the default, and does not need to be added. "mark-duplicate"
641 // and "modify-efficiency" do not need to be propagated here as their
642 // effects are already applied to the corresponding reactions.
643 out["explicit-third-body-duplicates"] = "error";
644 }
645 map<double, int> multipliers;
646 for (auto m : m_perturb) {
647 multipliers[m] += 1;
648 }
649 if (static_cast<size_t>(multipliers[1.0]) != (nReactions())) {
650 int defaultCount = 0;
651 double defaultMultiplier = 1.0;
652 for (auto& [m, count] : multipliers) {
653 if (count > defaultCount) {
654 defaultCount = count;
655 defaultMultiplier = m;
656 }
657 }
658 AnyMap multiplierMap;
659 multiplierMap["default"] = defaultMultiplier;
660 for (size_t i = 0; i < nReactions(); i++) {
661 if (m_perturb[i] != defaultMultiplier) {
662 multiplierMap[to_string(i)] = m_perturb[i];
663 }
664 }
665 out["rate-multipliers"] = multiplierMap;
666 }
667 }
668 return out;
669}
670
672{
673 m_kk = 0;
674 m_start.resize(nPhases());
675
676 for (size_t i = 0; i < m_thermo.size(); i++) {
677 m_start[i] = m_kk; // global index of first species of phase i
678 m_kk += m_thermo[i]->nSpecies();
679 }
680 invalidateCache();
681}
682
683bool Kinetics::addReaction(shared_ptr<Reaction> r, bool resize)
684{
685 r->check();
686 r->validate(*this);
687
688 if (m_kk == 0) {
689 init();
690 }
692
693 // Check validity of reaction within the context of the Kinetics object
694 if (!r->checkSpecies(*this)) {
695 // Do not add reaction
696 return false;
697 }
698
699 // For reactions created outside the context of a Kinetics object, the units
700 // of the rate coefficient can't be determined in advance. Do that here.
701 if (r->rate_units.factor() == 0) {
702 r->rate()->setRateUnits(r->calculateRateCoeffUnits(*this));
703 }
704
705 size_t irxn = nReactions(); // index of the new reaction
706
707 // indices of reactant and product species within this Kinetics object
708 vector<size_t> rk, pk;
709
710 // Reactant and product stoichiometric coefficients, such that rstoich[i] is
711 // the coefficient for species rk[i]
712 vector<double> rstoich, pstoich;
713
714 for (const auto& [name, stoich] : r->reactants) {
715 rk.push_back(kineticsSpeciesIndex(name));
716 rstoich.push_back(stoich);
717 }
718
719 for (const auto& [name, stoich] : r->products) {
720 pk.push_back(kineticsSpeciesIndex(name));
721 pstoich.push_back(stoich);
722 }
723
724 // The default order for each reactant is its stoichiometric coefficient,
725 // which can be overridden by entries in the Reaction.orders map. rorder[i]
726 // is the order for species rk[i].
727 vector<double> rorder = rstoich;
728 for (const auto& [name, order] : r->orders) {
729 size_t k = kineticsSpeciesIndex(name);
730 // Find the index of species k within rk
731 auto rloc = std::find(rk.begin(), rk.end(), k);
732 if (rloc != rk.end()) {
733 rorder[rloc - rk.begin()] = order;
734 } else {
735 // If the reaction order involves a non-reactant species, add an
736 // extra term to the reactants with zero stoichiometry so that the
737 // stoichiometry manager can be used to compute the global forward
738 // reaction rate.
739 rk.push_back(k);
740 rstoich.push_back(0.0);
741 rorder.push_back(order);
742 }
743 }
744
745 m_reactantStoich.add(irxn, rk, rorder, rstoich);
746 // product orders = product stoichiometric coefficients
747 m_productStoich.add(irxn, pk, pstoich, pstoich);
748 if (r->reversible) {
749 m_revindex.push_back(irxn);
750 m_revProductStoich.add(irxn, pk, pstoich, pstoich);
751 } else {
752 m_irrev.push_back(irxn);
753 }
754
755 m_reactions.push_back(r);
756 m_rfn.push_back(0.0);
757 m_delta_gibbs0.push_back(0.0);
758 m_rkcn.push_back(0.0);
759 m_ropf.push_back(0.0);
760 m_ropr.push_back(0.0);
761 m_ropnet.push_back(0.0);
763 m_dH.push_back(0.0);
764
765 if (resize) {
767 }
768
769 for (const auto& [id, callback] : m_reactionAddedCallbacks) {
770 callback();
771 }
772
773 return true;
774}
775
776void Kinetics::modifyReaction(size_t i, shared_ptr<Reaction> rNew)
777{
779 shared_ptr<Reaction>& rOld = m_reactions[i];
780
781 if (rNew->rate()->type() == "electron-collision-plasma") {
782 throw CanteraError("Kinetics::modifyReaction",
783 "Type electron-collision-plasma is not supported. "
784 "Use the rate object of the reaction to modify the data.");
785 }
786
787 if (rNew->type() != rOld->type()) {
788 throw CanteraError("Kinetics::modifyReaction",
789 "Reaction types are different: {} != {}.",
790 rOld->type(), rNew->type());
791 }
792
793 if (rNew->rate()->type() != rOld->rate()->type()) {
794 throw CanteraError("Kinetics::modifyReaction",
795 "ReactionRate types are different: {} != {}.",
796 rOld->rate()->type(), rNew->rate()->type());
797 }
798
799 if (rNew->reactants != rOld->reactants) {
800 throw CanteraError("Kinetics::modifyReaction",
801 "Reactants are different: '{}' != '{}'.",
802 rOld->reactantString(), rNew->reactantString());
803 }
804
805 if (rNew->products != rOld->products) {
806 throw CanteraError("Kinetics::modifyReaction",
807 "Products are different: '{}' != '{}'.",
808 rOld->productString(), rNew->productString());
809 }
810 m_reactions[i] = rNew;
811 invalidateCache();
812}
813
814shared_ptr<Reaction> Kinetics::reaction(size_t i)
815{
817 return m_reactions[i];
818}
819
820shared_ptr<const Reaction> Kinetics::reaction(size_t i) const
821{
823 return m_reactions[i];
824}
825
826}
Base class for kinetics managers and also contains the kineticsmgr module documentation (see Kinetics...
Header file for class ThermoPhase, the base class for phases with thermodynamic properties,...
A map of string keys to values whose type can vary at runtime.
Definition AnyMap.h:431
bool hasKey(const string &key) const
Returns true if the map contains an item named key.
Definition AnyMap.cpp:1477
void applyUnits()
Use the supplied UnitSystem to set the default units, and recursively process overrides from nodes na...
Definition AnyMap.cpp:1761
bool getBool(const string &key, bool default_) const
If key exists, return it as a bool, otherwise return default_.
Definition AnyMap.cpp:1575
const string & getString(const string &key, const string &default_) const
If key exists, return it as a string, otherwise return default_.
Definition AnyMap.cpp:1590
Base class for exceptions thrown by Cantera classes.
const char * what() const override
Get a description of the error.
An array index is out of range.
Error thrown for problems processing information contained in an AnyMap or AnyValue.
Definition AnyMap.h:749
shared_ptr< ThermoPhase > phase(size_t n=0) const
Return pointer to phase associated with Kinetics by index.
Definition Kinetics.h:226
virtual void resizeReactions()
Finalize Kinetics object and associated objects.
Definition Kinetics.cpp:50
virtual void getFwdRatesOfProgress(double *fwdROP)
Return the forward rates of progress of the reactions.
Definition Kinetics.cpp:375
virtual void setParameters(const AnyMap &phaseNode)
Set kinetics-related parameters from an AnyMap phase description.
Definition Kinetics.cpp:610
size_t checkPhaseIndex(size_t m) const
Check that the specified phase index is in range.
Definition Kinetics.cpp:67
ThermoPhase & thermo(size_t n=0)
This method returns a reference to the nth ThermoPhase object defined in this kinetics mechanism.
Definition Kinetics.h:239
vector< shared_ptr< Reaction > > m_reactions
Vector of Reaction objects represented by this Kinetics manager.
Definition Kinetics.h:1490
double checkDuplicateStoich(map< int, double > &r1, map< int, double > &r2) const
Check whether r1 and r2 represent duplicate stoichiometries This function returns a ratio if two reac...
Definition Kinetics.cpp:253
vector< double > m_perturb
Vector of perturbation factors for each reaction's rate of progress vector.
Definition Kinetics.h:1483
vector< double > m_ropf
Forward rate-of-progress for each reaction.
Definition Kinetics.h:1531
shared_ptr< Reaction > reaction(size_t i)
Return the Reaction object for reaction i.
Definition Kinetics.cpp:814
virtual void getRevReactionDelta(const double *g, double *dg) const
Given an array of species properties 'g', return in array 'dg' the change in this quantity in the rev...
Definition Kinetics.cpp:402
void setExplicitThirdBodyDuplicateHandling(const string &flag)
Specify how to handle duplicate third body reactions where one reaction has an explicit third body an...
Definition Kinetics.cpp:100
virtual void getNetRatesOfProgress(double *netROP)
Net rates of progress.
Definition Kinetics.cpp:387
vector< size_t > m_start
m_start is a vector of integers specifying the beginning position for the species vector for the n'th...
Definition Kinetics.h:1508
virtual string kineticsType() const
Identifies the Kinetics manager type.
Definition Kinetics.h:153
vector< double > m_rkcn
Reciprocal of the equilibrium constant in concentration units.
Definition Kinetics.h:1528
shared_ptr< ThermoPhase > reactionPhase() const
Return pointer to phase where the reactions occur.
Definition Kinetics.cpp:87
size_t m_kk
The number of species in all of the phases that participate in this kinetics mechanism.
Definition Kinetics.h:1479
virtual pair< size_t, size_t > checkDuplicates(bool throw_err=true, bool fix=false)
Check for unmarked duplicate reactions and unmatched marked duplicates.
Definition Kinetics.cpp:112
virtual void getReactionDelta(const double *property, double *deltaProperty) const
Change in species properties.
Definition Kinetics.cpp:393
vector< double > m_dH
The enthalpy change for each reaction to calculate Blowers-Masel rates.
Definition Kinetics.h:1543
vector< double > m_ropr
Reverse rate-of-progress for each reaction.
Definition Kinetics.h:1534
size_t nPhases() const
The number of phases participating in the reaction mechanism.
Definition Kinetics.h:189
vector< shared_ptr< ThermoPhase > > m_thermo
m_thermo is a vector of pointers to ThermoPhase objects that are involved with this kinetics operator
Definition Kinetics.h:1502
map< void *, function< void()> > m_reactionAddedCallbacks
Callback functions that are invoked when the reaction is added.
Definition Kinetics.h:1564
AnyMap parameters() const
Return the parameters for a phase definition which are needed to reconstruct an identical object usin...
Definition Kinetics.cpp:627
size_t phaseIndex(const string &ph, bool raise=true) const
Return the index of a phase among the phases participating in this kinetic mechanism.
Definition Kinetics.cpp:75
virtual bool addReaction(shared_ptr< Reaction > r, bool resize=true)
Add a single reaction to the mechanism.
Definition Kinetics.cpp:683
vector< size_t > m_revindex
Indices of reversible reactions.
Definition Kinetics.h:1539
string kineticsSpeciesName(size_t k) const
Return the name of the kth species in the kinetics manager.
Definition Kinetics.cpp:296
virtual void getDestructionRates(double *ddot)
Species destruction rates [kmol/m^3/s or kmol/m^2/s].
Definition Kinetics.cpp:425
virtual void init()
Prepare the class for the addition of reactions, after all phases have been added.
Definition Kinetics.h:1274
shared_ptr< Solution > root() const
Get the Solution object containing this Kinetics object and associated ThermoPhase objects.
Definition Kinetics.h:1407
virtual void modifyReaction(size_t i, shared_ptr< Reaction > rNew)
Modify the rate expression associated with a reaction.
Definition Kinetics.cpp:776
vector< double > m_ropnet
Net rate-of-progress for each reaction.
Definition Kinetics.h:1537
void skipUndeclaredThirdBodies(bool skip)
Determine behavior when adding a new reaction that contains third-body efficiencies for species not d...
Definition Kinetics.h:1336
virtual double productStoichCoeff(size_t k, size_t i) const
Stoichiometric coefficient of species k as a product in reaction i.
Definition Kinetics.cpp:370
virtual void addThermo(shared_ptr< ThermoPhase > thermo)
Add a phase to the kinetics manager object.
Definition Kinetics.cpp:593
vector< double > m_rbuf
Buffer used for storage of intermediate reaction-specific results.
Definition Kinetics.h:1546
Eigen::SparseMatrix< double > m_stoichMatrix
Net stoichiometry (products - reactants)
Definition Kinetics.h:1474
map< string, size_t > m_phaseindex
Mapping of the phase name to the position of the phase within the kinetics object.
Definition Kinetics.h:1516
size_t m_mindim
number of spatial dimensions of lowest-dimensional phase.
Definition Kinetics.h:1519
StoichManagerN m_productStoich
Stoichiometry manager for the products for each reaction.
Definition Kinetics.h:1468
StoichManagerN m_revProductStoich
Stoichiometry manager for the products of reversible reactions.
Definition Kinetics.h:1471
shared_ptr< Kinetics > clone(const vector< shared_ptr< ThermoPhase > > &phases) const
Create a new Kinetics object with the same kinetics model and reactions as this one.
Definition Kinetics.cpp:27
size_t nReactions() const
Number of reactions in the reaction mechanism.
Definition Kinetics.h:161
map< size_t, double > m_defaultPerturb
Default values for perturbations defined in the phase definition's rate-multipliers field.
Definition Kinetics.h:1487
virtual void getRevRatesOfProgress(double *revROP)
Return the Reverse rates of progress of the reactions.
Definition Kinetics.cpp:381
vector< size_t > m_irrev
Indices of irreversible reactions.
Definition Kinetics.h:1540
bool m_hasUndeclaredThirdBodies
Flag indicating whether reactions include undeclared third bodies.
Definition Kinetics.h:1555
size_t kineticsSpeciesIndex(size_t k, size_t n) const
The location of species k of phase n in species arrays.
Definition Kinetics.h:273
vector< double > m_rfn
Forward rate constant for each reaction.
Definition Kinetics.h:1522
size_t checkSpeciesIndex(size_t k) const
Check that the specified species index is in range.
Definition Kinetics.cpp:92
StoichManagerN m_reactantStoich
Stoichiometry manager for the reactants for each reaction.
Definition Kinetics.h:1465
virtual void resizeSpecies()
Resize arrays with sizes that depend on the total number of species.
Definition Kinetics.cpp:671
size_t nTotalSpecies() const
The total number of species in all phases participating in the kinetics mechanism.
Definition Kinetics.h:251
virtual double reactantStoichCoeff(size_t k, size_t i) const
Stoichiometric coefficient of species k as a reactant in reaction i.
Definition Kinetics.cpp:365
virtual void getNetProductionRates(double *wdot)
Species net production rates [kmol/m^3/s or kmol/m^2/s].
Definition Kinetics.cpp:436
ThermoPhase & speciesPhase(const string &nm)
This function looks up the name of a species and returns a reference to the ThermoPhase object of the...
Definition Kinetics.cpp:333
vector< double > m_delta_gibbs0
Delta G^0 for all reactions.
Definition Kinetics.h:1525
size_t checkReactionIndex(size_t m) const
Check that the specified reaction index is in range.
Definition Kinetics.cpp:42
virtual void getCreationRates(double *cdot)
Species creation rates [kmol/m^3/s or kmol/m^2/s].
Definition Kinetics.cpp:411
size_t speciesPhaseIndex(size_t k) const
This function takes as an argument the kineticsSpecies index (that is, the list index in the list of ...
Definition Kinetics.cpp:354
size_t nDim() const
Returns the number of spatial dimensions (1, 2, or 3)
Definition Phase.h:582
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
string speciesName(size_t k) const
Name of the species with index k.
Definition Phase.cpp:143
Abstract base class which stores data about a reaction and its rate parameterization so that it can b...
Definition Reaction.h:25
shared_ptr< ReactionRate > rate()
Get reaction rate pointer.
Definition Reaction.h:147
bool usesThirdBody() const
Check whether reaction involves third body collider.
Definition Reaction.h:161
shared_ptr< ThirdBody > thirdBody()
Get pointer to third-body handler.
Definition Reaction.h:155
bool reversible
True if the current reaction is reversible. False otherwise.
Definition Reaction.h:126
string type() const
The type of reaction, including reaction rate information.
Definition Reaction.cpp:557
string equation() const
The chemical equation for this reaction.
Definition Reaction.cpp:380
Composition products
Product species and stoichiometric coefficients.
Definition Reaction.h:114
Composition reactants
Reactant species and stoichiometric coefficients.
Definition Reaction.h:111
AnyMap input
Input data used for specific models.
Definition Reaction.h:139
bool duplicate
True if the current reaction is marked as duplicate.
Definition Reaction.h:129
void resizeCoeffs(size_t nSpc, size_t nRxn)
Resize the sparse coefficient matrix.
void add(size_t rxn, const vector< size_t > &k)
Add a single reaction to the list of reactions that this stoichiometric manager object handles.
const Eigen::SparseMatrix< double > & stoichCoeffs() const
Return matrix containing stoichiometric coefficients.
Base class for a phase with thermodynamic properties.
A class for managing third-body efficiencies, including default values.
Definition Reaction.h:207
double efficiency(const string &k) const
Get the third-body efficiency for species k
Definition Reaction.cpp:845
Composition efficiencies
Map of species to third body efficiency.
Definition Reaction.h:250
string name() const
Name of the third body collider.
Definition Reaction.h:215
This file contains definitions for utility functions and text for modules, inputfiles and logging,...
virtual Eigen::SparseMatrix< double > fwdRatesOfProgress_ddCi()
Calculate derivatives for forward rates-of-progress with respect to species concentration at constant...
Definition Kinetics.h:815
Eigen::SparseMatrix< double > creationRates_ddCi()
Calculate derivatives for species creation rates with respect to species concentration at constant te...
Definition Kinetics.cpp:493
virtual Eigen::SparseMatrix< double > netRatesOfProgress_ddCi()
Calculate derivatives for net rates-of-progress with respect to species concentration at constant tem...
Definition Kinetics.h:961
void getCreationRates_ddT(double *dwdot)
Calculate derivatives for species creation rates with respect to temperature at constant pressure,...
Definition Kinetics.cpp:447
virtual Eigen::SparseMatrix< double > netRatesOfProgress_ddX()
Calculate derivatives for net rates-of-progress with respect to species mole fractions at constant te...
Definition Kinetics.h:941
Eigen::SparseMatrix< double > destructionRates_ddX()
Calculate derivatives for species destruction rates with respect to species mole fractions at constan...
Definition Kinetics.cpp:539
void getCreationRates_ddC(double *dwdot)
Calculate derivatives for species creation rates with respect to molar concentration at constant temp...
Definition Kinetics.cpp:471
void getDestructionRates_ddP(double *dwdot)
Calculate derivatives for species destruction rates with respect to pressure at constant temperature,...
Definition Kinetics.cpp:515
void getNetProductionRates_ddC(double *dwdot)
Calculate derivatives for species net production rates with respect to molar concentration at constan...
Definition Kinetics.cpp:575
void getDestructionRates_ddT(double *dwdot)
Calculate derivatives for species destruction rates with respect to temperature at constant pressure,...
Definition Kinetics.cpp:503
virtual void getFwdRatesOfProgress_ddP(double *drop)
Calculate derivatives for forward rates-of-progress with respect to pressure at constant temperature,...
Definition Kinetics.h:764
Eigen::SparseMatrix< double > netProductionRates_ddX()
Calculate derivatives for species net production rates with respect to species mole fractions at cons...
Definition Kinetics.cpp:583
Eigen::SparseMatrix< double > creationRates_ddX()
Calculate derivatives for species creation rates with respect to species mole fractions at constant t...
Definition Kinetics.cpp:483
Eigen::SparseMatrix< double > destructionRates_ddCi()
Calculate derivatives for species destruction rates with respect to species concentration at constant...
Definition Kinetics.cpp:549
void getNetProductionRates_ddT(double *dwdot)
Calculate derivatives for species net production rates with respect to temperature at constant pressu...
Definition Kinetics.cpp:559
virtual Eigen::SparseMatrix< double > fwdRatesOfProgress_ddX()
Calculate derivatives for forward rates-of-progress with respect to species mole fractions at constan...
Definition Kinetics.h:795
virtual void getRevRatesOfProgress_ddT(double *drop)
Calculate derivatives for reverse rates-of-progress with respect to temperature at constant pressure,...
Definition Kinetics.h:826
void getCreationRates_ddP(double *dwdot)
Calculate derivatives for species creation rates with respect to pressure at constant temperature,...
Definition Kinetics.cpp:459
virtual void getNetRatesOfProgress_ddT(double *drop)
Calculate derivatives for net rates-of-progress with respect to temperature at constant pressure,...
Definition Kinetics.h:899
virtual void getRevRatesOfProgress_ddP(double *drop)
Calculate derivatives for reverse rates-of-progress with respect to pressure at constant temperature,...
Definition Kinetics.h:837
Eigen::SparseMatrix< double > netProductionRates_ddCi()
Calculate derivatives for species net production rates with respect to species concentration at const...
Definition Kinetics.cpp:588
virtual void getRevRatesOfProgress_ddC(double *drop)
Calculate derivatives for reverse rates-of-progress with respect to molar concentration at constant t...
Definition Kinetics.h:851
void getNetProductionRates_ddP(double *dwdot)
Calculate derivatives for species net production rates with respect to pressure at constant temperatu...
Definition Kinetics.cpp:567
virtual void getNetRatesOfProgress_ddP(double *drop)
Calculate derivatives for net rates-of-progress with respect to pressure at constant temperature,...
Definition Kinetics.h:910
virtual Eigen::SparseMatrix< double > revRatesOfProgress_ddCi()
Calculate derivatives for forward rates-of-progress with respect to species concentration at constant...
Definition Kinetics.h:888
virtual void getFwdRatesOfProgress_ddT(double *drop)
Calculate derivatives for forward rates-of-progress with respect to temperature at constant pressure,...
Definition Kinetics.h:753
void getDestructionRates_ddC(double *dwdot)
Calculate derivatives for species destruction rates with respect to molar concentration at constant t...
Definition Kinetics.cpp:527
virtual void getNetRatesOfProgress_ddC(double *drop)
Calculate derivatives for net rates-of-progress with respect to molar concentration at constant tempe...
Definition Kinetics.h:924
virtual Eigen::SparseMatrix< double > revRatesOfProgress_ddX()
Calculate derivatives for reverse rates-of-progress with respect to species mole fractions at constan...
Definition Kinetics.h:868
virtual void getFwdRatesOfProgress_ddC(double *drop)
Calculate derivatives for forward rates-of-progress with respect to molar concentration at constant t...
Definition Kinetics.h:778
shared_ptr< Kinetics > newKinetics(const string &model)
Create a new Kinetics instance.
void warn_user(const string &method, const string &msg, const Args &... args)
Print a user warning raised from method as CanteraWarning.
Definition global.h:263
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:182
const U & getValue(const map< T, U > &m, const T &key, const U &default_val)
Const accessor for a value in a map.
Definition utilities.h:190
Contains declarations for string manipulation functions within Cantera.
Various templated functions that carry out common vector and polynomial operations (see Templated Arr...