Cantera  3.1.0
Loading...
Searching...
No Matches
Reactor.cpp
Go to the documentation of this file.
1//! @file Reactor.cpp A zero-dimensional reactor
2
3// This file is part of Cantera. See License.txt in the top-level directory or
4// at https://cantera.org/license.txt for license and copyright information.
5
16
17#include <boost/math/tools/roots.hpp>
18
19using namespace std;
20namespace bmt = boost::math::tools;
21
22namespace Cantera
23{
24
25Reactor::Reactor(shared_ptr<Solution> sol, const string& name)
26 : ReactorBase(name)
27{
28 if (!sol || !(sol->thermo())) {
29 warn_deprecated("Reactor::Reactor",
30 "Creation of empty reactor objects is deprecated in Cantera 3.1 and will "
31 "raise\nexceptions thereafter; reactor contents should be provided in the "
32 "constructor.");
33 return;
34 }
35 setSolution(sol);
36 setThermo(*sol->thermo());
37 setKinetics(*sol->kinetics());
38}
39
40void Reactor::setDerivativeSettings(AnyMap& settings)
41{
42 m_kin->setDerivativeSettings(settings);
43 // translate settings to surfaces
44 for (auto S : m_surfaces) {
45 S->kinetics()->setDerivativeSettings(settings);
46 }
47}
48
49void Reactor::setKinetics(Kinetics& kin)
50{
51 m_kin = &kin;
52 if (m_kin->nReactions() == 0) {
53 setChemistry(false);
54 } else {
55 setChemistry(true);
56 }
57}
58
59void Reactor::getState(double* y)
60{
61 if (m_thermo == 0) {
62 throw CanteraError("Reactor::getState",
63 "Error: reactor is empty.");
64 }
65 m_thermo->restoreState(m_state);
66
67 // set the first component to the total mass
68 m_mass = m_thermo->density() * m_vol;
69 y[0] = m_mass;
70
71 // set the second component to the total volume
72 y[1] = m_vol;
73
74 // set the third component to the total internal energy
75 y[2] = m_thermo->intEnergy_mass() * m_mass;
76
77 // set components y+3 ... y+K+2 to the mass fractions of each species
78 m_thermo->getMassFractions(y+3);
79
80 // set the remaining components to the surface species
81 // coverages on the walls
82 getSurfaceInitialConditions(y + m_nsp + 3);
83}
84
85void Reactor::getSurfaceInitialConditions(double* y)
86{
87 size_t loc = 0;
88 for (auto& S : m_surfaces) {
89 S->getCoverages(y + loc);
90 loc += S->thermo()->nSpecies();
91 }
92}
93
94void Reactor::initialize(double t0)
95{
96 if (!m_thermo || (m_chem && !m_kin)) {
97 throw CanteraError("Reactor::initialize", "Reactor contents not set"
98 " for reactor '" + m_name + "'.");
99 }
100 m_thermo->restoreState(m_state);
101 m_sdot.resize(m_nsp, 0.0);
102 m_wdot.resize(m_nsp, 0.0);
103 updateConnected(true);
104
105 for (size_t n = 0; n < m_wall.size(); n++) {
106 WallBase* W = m_wall[n];
107 W->initialize();
108 }
109
110 m_nv = m_nsp + 3;
111 m_nv_surf = 0;
112 size_t maxnt = 0;
113 for (auto& S : m_surfaces) {
114 m_nv_surf += S->thermo()->nSpecies();
115 size_t nt = S->kinetics()->nTotalSpecies();
116 maxnt = std::max(maxnt, nt);
117 }
118 m_nv += m_nv_surf;
119 m_work.resize(maxnt);
120}
121
122size_t Reactor::nSensParams() const
123{
124 size_t ns = m_sensParams.size();
125 for (auto& S : m_surfaces) {
126 ns += S->nSensParams();
127 }
128 return ns;
129}
130
131void Reactor::syncState()
132{
133 ReactorBase::syncState();
134 m_mass = m_thermo->density() * m_vol;
135}
136
137void Reactor::updateState(double* y)
138{
139 // The components of y are [0] the total mass, [1] the total volume,
140 // [2] the total internal energy, [3...K+3] are the mass fractions of each
141 // species, and [K+3...] are the coverages of surface species on each wall.
142 m_mass = y[0];
143 m_vol = y[1];
144 m_thermo->setMassFractions_NoNorm(y+3);
145
146 if (m_energy) {
147 double U = y[2];
148 // Residual function: error in internal energy as a function of T
149 auto u_err = [this, U](double T) {
150 m_thermo->setState_TD(T, m_mass / m_vol);
151 return m_thermo->intEnergy_mass() * m_mass - U;
152 };
153
154 double T = m_thermo->temperature();
155 boost::uintmax_t maxiter = 100;
156 pair<double, double> TT;
157 try {
158 TT = bmt::bracket_and_solve_root(
159 u_err, T, 1.2, true, bmt::eps_tolerance<double>(48), maxiter);
160 } catch (std::exception&) {
161 // Try full-range bisection if bracketing fails (for example, near
162 // temperature limits for the phase's equation of state)
163 try {
164 TT = bmt::bisect(u_err, m_thermo->minTemp(), m_thermo->maxTemp(),
165 bmt::eps_tolerance<double>(48), maxiter);
166 } catch (std::exception& err2) {
167 // Set m_thermo back to a reasonable state if root finding fails
168 m_thermo->setState_TD(T, m_mass / m_vol);
169 throw CanteraError("Reactor::updateState",
170 "{}\nat U = {}, rho = {}", err2.what(), U, m_mass / m_vol);
171 }
172 }
173 if (fabs(TT.first - TT.second) > 1e-7*TT.first) {
174 throw CanteraError("Reactor::updateState", "root finding failed");
175 }
176 m_thermo->setState_TD(TT.second, m_mass / m_vol);
177 } else {
178 m_thermo->setDensity(m_mass/m_vol);
179 }
180
181 updateConnected(true);
182 updateSurfaceState(y + m_nsp + 3);
183}
184
185void Reactor::updateSurfaceState(double* y)
186{
187 size_t loc = 0;
188 for (auto& S : m_surfaces) {
189 S->setCoverages(y+loc);
190 loc += S->thermo()->nSpecies();
191 }
192}
193
194void Reactor::updateConnected(bool updatePressure) {
195 // save parameters needed by other connected reactors
196 m_enthalpy = m_thermo->enthalpy_mass();
197 if (updatePressure) {
198 m_pressure = m_thermo->pressure();
199 }
200 m_intEnergy = m_thermo->intEnergy_mass();
201 m_thermo->saveState(m_state);
202
203 // Update the mass flow rate of connected flow devices
204 double time = 0.0;
205 if (m_net != nullptr) {
206 time = (timeIsIndependent()) ? m_net->time() : m_net->distance();
207 }
208 for (size_t i = 0; i < m_outlet.size(); i++) {
209 m_outlet[i]->setSimTime(time);
210 m_outlet[i]->updateMassFlowRate(time);
211 }
212 for (size_t i = 0; i < m_inlet.size(); i++) {
213 m_inlet[i]->setSimTime(time);
214 m_inlet[i]->updateMassFlowRate(time);
215 }
216 for (size_t i = 0; i < m_wall.size(); i++) {
217 m_wall[i]->setSimTime(time);
218 }
219}
220
221void Reactor::eval(double time, double* LHS, double* RHS)
222{
223 double& dmdt = RHS[0];
224 double* mdYdt = RHS + 3; // mass * dY/dt
225
226 evalWalls(time);
227 m_thermo->restoreState(m_state);
228 const vector<double>& mw = m_thermo->molecularWeights();
229 const double* Y = m_thermo->massFractions();
230
231 evalSurfaces(LHS + m_nsp + 3, RHS + m_nsp + 3, m_sdot.data());
232 // mass added to gas phase from surface reactions
233 double mdot_surf = dot(m_sdot.begin(), m_sdot.end(), mw.begin());
234 dmdt = mdot_surf;
235
236 // volume equation
237 RHS[1] = m_vdot;
238
239 if (m_chem) {
240 m_kin->getNetProductionRates(&m_wdot[0]); // "omega dot"
241 }
242
243 for (size_t k = 0; k < m_nsp; k++) {
244 // production in gas phase and from surfaces
245 mdYdt[k] = (m_wdot[k] * m_vol + m_sdot[k]) * mw[k];
246 // dilution by net surface mass flux
247 mdYdt[k] -= Y[k] * mdot_surf;
248 LHS[k+3] = m_mass;
249 }
250
251 // Energy equation.
252 // @f[
253 // \dot U = -P\dot V + A \dot q + \dot m_{in} h_{in} - \dot m_{out} h.
254 // @f]
255 if (m_energy) {
256 RHS[2] = - m_thermo->pressure() * m_vdot + m_Qdot;
257 } else {
258 RHS[2] = 0.0;
259 }
260
261 // add terms for outlets
262 for (auto outlet : m_outlet) {
263 double mdot = outlet->massFlowRate();
264 dmdt -= mdot; // mass flow out of system
265 if (m_energy) {
266 RHS[2] -= mdot * m_enthalpy;
267 }
268 }
269
270 // add terms for inlets
271 for (auto inlet : m_inlet) {
272 double mdot = inlet->massFlowRate();
273 dmdt += mdot; // mass flow into system
274 for (size_t n = 0; n < m_nsp; n++) {
275 double mdot_spec = inlet->outletSpeciesMassFlowRate(n);
276 // flow of species into system and dilution by other species
277 mdYdt[n] += (mdot_spec - mdot * Y[n]);
278 }
279 if (m_energy) {
280 RHS[2] += mdot * inlet->enthalpy_mass();
281 }
282 }
283}
284
285void Reactor::evalWalls(double t)
286{
287 // time is currently unused
288 m_vdot = 0.0;
289 m_Qdot = 0.0;
290 for (size_t i = 0; i < m_wall.size(); i++) {
291 int f = 2 * m_lr[i] - 1;
292 m_vdot -= f * m_wall[i]->expansionRate();
293 m_Qdot += f * m_wall[i]->heatRate();
294 }
295}
296
297void Reactor::evalSurfaces(double* LHS, double* RHS, double* sdot)
298{
299 fill(sdot, sdot + m_nsp, 0.0);
300 size_t loc = 0; // offset into ydot
301
302 for (auto S : m_surfaces) {
303 Kinetics* kin = S->kinetics();
304 SurfPhase* surf = S->thermo();
305
306 double rs0 = 1.0/surf->siteDensity();
307 size_t nk = surf->nSpecies();
308 double sum = 0.0;
309 S->syncState();
310 kin->getNetProductionRates(&m_work[0]);
311 for (size_t k = 1; k < nk; k++) {
312 RHS[loc + k] = m_work[k] * rs0 * surf->size(k);
313 sum -= RHS[loc + k];
314 }
315 RHS[loc] = sum;
316 loc += nk;
317
318 size_t bulkloc = kin->kineticsSpeciesIndex(m_thermo->speciesName(0));
319 double wallarea = S->area();
320 for (size_t k = 0; k < m_nsp; k++) {
321 sdot[k] += m_work[bulkloc + k] * wallarea;
322 }
323 }
324}
325
326Eigen::SparseMatrix<double> Reactor::finiteDifferenceJacobian()
327{
328 if (m_nv == 0) {
329 throw CanteraError("Reactor::finiteDifferenceJacobian",
330 "Reactor must be initialized first.");
331 }
332 // clear former jacobian elements
333 m_jac_trips.clear();
334
335 Eigen::ArrayXd yCurrent(m_nv);
336 getState(yCurrent.data());
337 double time = (m_net != nullptr) ? m_net->time() : 0.0;
338
339 Eigen::ArrayXd yPerturbed = yCurrent;
340 Eigen::ArrayXd lhsPerturbed(m_nv), lhsCurrent(m_nv);
341 Eigen::ArrayXd rhsPerturbed(m_nv), rhsCurrent(m_nv);
342 lhsCurrent = 1.0;
343 rhsCurrent = 0.0;
344 updateState(yCurrent.data());
345 eval(time, lhsCurrent.data(), rhsCurrent.data());
346
347 double rel_perturb = std::sqrt(std::numeric_limits<double>::epsilon());
348 double atol = (m_net != nullptr) ? m_net->atol() : 1e-15;
349
350 for (size_t j = 0; j < m_nv; j++) {
351 yPerturbed = yCurrent;
352 double delta_y = std::max(std::abs(yCurrent[j]), 1000 * atol) * rel_perturb;
353 yPerturbed[j] += delta_y;
354
355 updateState(yPerturbed.data());
356 lhsPerturbed = 1.0;
357 rhsPerturbed = 0.0;
358 eval(time, lhsPerturbed.data(), rhsPerturbed.data());
359
360 // d ydot_i/dy_j
361 for (size_t i = 0; i < m_nv; i++) {
362 double ydotPerturbed = rhsPerturbed[i] / lhsPerturbed[i];
363 double ydotCurrent = rhsCurrent[i] / lhsCurrent[i];
364 if (ydotCurrent != ydotPerturbed) {
365 m_jac_trips.emplace_back(
366 static_cast<int>(i), static_cast<int>(j),
367 (ydotPerturbed - ydotCurrent) / delta_y);
368 }
369 }
370 }
371 updateState(yCurrent.data());
372
373 Eigen::SparseMatrix<double> jac(m_nv, m_nv);
374 jac.setFromTriplets(m_jac_trips.begin(), m_jac_trips.end());
375 return jac;
376}
377
378
379void Reactor::evalSurfaces(double* RHS, double* sdot)
380{
381 fill(sdot, sdot + m_nsp, 0.0);
382 size_t loc = 0; // offset into ydot
383
384 for (auto S : m_surfaces) {
385 Kinetics* kin = S->kinetics();
386 SurfPhase* surf = S->thermo();
387
388 double rs0 = 1.0/surf->siteDensity();
389 size_t nk = surf->nSpecies();
390 double sum = 0.0;
391 S->syncState();
392 kin->getNetProductionRates(&m_work[0]);
393 for (size_t k = 1; k < nk; k++) {
394 RHS[loc + k] = m_work[k] * rs0 * surf->size(k);
395 sum -= RHS[loc + k];
396 }
397 RHS[loc] = sum;
398 loc += nk;
399
400 size_t bulkloc = kin->kineticsSpeciesIndex(m_thermo->speciesName(0));
401 double wallarea = S->area();
402 for (size_t k = 0; k < m_nsp; k++) {
403 sdot[k] += m_work[bulkloc + k] * wallarea;
404 }
405 }
406}
407
408void Reactor::addSensitivityReaction(size_t rxn)
409{
410 if (!m_chem || rxn >= m_kin->nReactions()) {
411 throw CanteraError("Reactor::addSensitivityReaction",
412 "Reaction number out of range ({})", rxn);
413 }
414
415 size_t p = network().registerSensitivityParameter(
416 name()+": "+m_kin->reaction(rxn)->equation(), 1.0, 1.0);
417 m_sensParams.emplace_back(
418 SensitivityParameter{rxn, p, 1.0, SensParameterType::reaction});
419}
420
421void Reactor::addSensitivitySpeciesEnthalpy(size_t k)
422{
423 if (k >= m_thermo->nSpecies()) {
424 throw CanteraError("Reactor::addSensitivitySpeciesEnthalpy",
425 "Species index out of range ({})", k);
426 }
427
428 size_t p = network().registerSensitivityParameter(
429 name() + ": " + m_thermo->speciesName(k) + " enthalpy",
430 0.0, GasConstant * 298.15);
431 m_sensParams.emplace_back(
432 SensitivityParameter{k, p, m_thermo->Hf298SS(k),
433 SensParameterType::enthalpy});
434}
435
436size_t Reactor::speciesIndex(const string& nm) const
437{
438 // check for a gas species name
439 size_t k = m_thermo->speciesIndex(nm);
440 if (k != npos) {
441 return k;
442 }
443
444 // check for a wall species
445 size_t offset = m_nsp;
446 for (auto& S : m_surfaces) {
447 ThermoPhase* th = S->thermo();
448 k = th->speciesIndex(nm);
449 if (k != npos) {
450 return k + offset;
451 } else {
452 offset += th->nSpecies();
453 }
454 }
455 return npos;
456}
457
458size_t Reactor::componentIndex(const string& nm) const
459{
460 size_t k = speciesIndex(nm);
461 if (k != npos) {
462 return k + 3;
463 } else if (nm == "mass") {
464 return 0;
465 } else if (nm == "volume") {
466 return 1;
467 } else if (nm == "int_energy") {
468 return 2;
469 } else {
470 return npos;
471 }
472}
473
474string Reactor::componentName(size_t k) {
475 if (k == 0) {
476 return "mass";
477 } else if (k == 1) {
478 return "volume";
479 } else if (k == 2) {
480 return "int_energy";
481 } else if (k >= 3 && k < neq()) {
482 k -= 3;
483 if (k < m_thermo->nSpecies()) {
484 return m_thermo->speciesName(k);
485 } else {
486 k -= m_thermo->nSpecies();
487 }
488 for (auto& S : m_surfaces) {
489 ThermoPhase* th = S->thermo();
490 if (k < th->nSpecies()) {
491 return th->speciesName(k);
492 } else {
493 k -= th->nSpecies();
494 }
495 }
496 }
497 throw CanteraError("Reactor::componentName", "Index is out of bounds.");
498}
499
500void Reactor::applySensitivity(double* params)
501{
502 if (!params) {
503 return;
504 }
505 for (auto& p : m_sensParams) {
506 if (p.type == SensParameterType::reaction) {
507 p.value = m_kin->multiplier(p.local);
508 m_kin->setMultiplier(p.local, p.value*params[p.global]);
509 } else if (p.type == SensParameterType::enthalpy) {
510 m_thermo->modifyOneHf298SS(p.local, p.value + params[p.global]);
511 }
512 }
513 for (auto& S : m_surfaces) {
514 S->setSensitivityParameters(params);
515 }
516 m_thermo->invalidateCache();
517 if (m_kin) {
518 m_kin->invalidateCache();
519 }
520}
521
522void Reactor::resetSensitivity(double* params)
523{
524 if (!params) {
525 return;
526 }
527 for (auto& p : m_sensParams) {
528 if (p.type == SensParameterType::reaction) {
529 m_kin->setMultiplier(p.local, p.value);
530 } else if (p.type == SensParameterType::enthalpy) {
531 m_thermo->resetHf298(p.local);
532 }
533 }
534 for (auto& S : m_surfaces) {
535 S->resetSensitivityParameters();
536 }
537 m_thermo->invalidateCache();
538 if (m_kin) {
539 m_kin->invalidateCache();
540 }
541}
542
543void Reactor::setAdvanceLimits(const double *limits)
544{
545 if (m_thermo == 0) {
546 throw CanteraError("Reactor::setAdvanceLimits",
547 "Error: reactor is empty.");
548 }
549 m_advancelimits.assign(limits, limits + m_nv);
550
551 // resize to zero length if no limits are set
552 if (std::none_of(m_advancelimits.begin(), m_advancelimits.end(),
553 [](double val){return val>0;})) {
554 m_advancelimits.resize(0);
555 }
556}
557
558bool Reactor::getAdvanceLimits(double *limits) const
559{
560 bool has_limit = hasAdvanceLimits();
561 if (has_limit) {
562 std::copy(m_advancelimits.begin(), m_advancelimits.end(), limits);
563 } else {
564 std::fill(limits, limits + m_nv, -1.0);
565 }
566 return has_limit;
567}
568
569void Reactor::setAdvanceLimit(const string& nm, const double limit)
570{
571 size_t k = componentIndex(nm);
572 if (k == npos) {
573 throw CanteraError("Reactor::setAdvanceLimit", "No component named '{}'", nm);
574 }
575
576 if (m_thermo == 0) {
577 throw CanteraError("Reactor::setAdvanceLimit",
578 "Error: reactor is empty.");
579 }
580 if (m_nv == 0) {
581 if (m_net == 0) {
582 throw CanteraError("Reactor::setAdvanceLimit",
583 "Cannot set limit on a reactor that is not "
584 "assigned to a ReactorNet object.");
585 } else {
586 m_net->initialize();
587 }
588 } else if (k > m_nv) {
589 throw CanteraError("Reactor::setAdvanceLimit",
590 "Index out of bounds.");
591 }
592 m_advancelimits.resize(m_nv, -1.0);
593 m_advancelimits[k] = limit;
594
595 // resize to zero length if no limits are set
596 if (std::none_of(m_advancelimits.begin(), m_advancelimits.end(),
597 [](double val){return val>0;})) {
598 m_advancelimits.resize(0);
599 }
600}
601
602}
Base class for kinetics managers and also contains the kineticsmgr module documentation (see Kinetics...
Header file for class ReactorSurface.
Header for a simple thermodynamics model of a surface phase derived from ThermoPhase,...
Header file for base class WallBase.
A map of string keys to values whose type can vary at runtime.
Definition AnyMap.h:431
Base class for exceptions thrown by Cantera classes.
Public interface for kinetics managers.
Definition Kinetics.h:125
size_t kineticsSpeciesIndex(size_t k, size_t n) const
The location of species k of phase n in species arrays.
Definition Kinetics.h:276
virtual void getNetProductionRates(double *wdot)
Species net production rates [kmol/m^3/s or kmol/m^2/s].
Definition Kinetics.cpp:413
size_t nSpecies() const
Returns the number of species in the phase.
Definition Phase.h:231
string speciesName(size_t k) const
Name of the species with index k.
Definition Phase.cpp:142
size_t speciesIndex(const string &name) const
Returns the index of a species named 'name' within the Phase object.
Definition Phase.cpp:129
A simple thermodynamic model for a surface phase, assuming an ideal solution model.
Definition SurfPhase.h:98
double size(size_t k) const
Returns the number of sites occupied by one molecule of species k.
Definition SurfPhase.h:221
double siteDensity() const
Returns the site density.
Definition SurfPhase.h:216
Base class for a phase with thermodynamic properties.
Base class for 'walls' (walls, pistons, etc.) connecting reactors.
Definition Wall.h:22
virtual void initialize()
Called just before the start of integration.
Definition Wall.h:82
double dot(InputIter x_begin, InputIter x_end, InputIter2 y_begin)
Function that calculates a templated inner product.
Definition utilities.h:82
const double GasConstant
Universal Gas Constant [J/kmol/K].
Definition ct_defs.h:120
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:180
offset
Offsets of solution components in the 1D solution array.
Definition Flow1D.h:24
void warn_deprecated(const string &source, const AnyBase &node, const string &message)
A deprecation warning for syntax in an input file.
Definition AnyMap.cpp:1997
Various templated functions that carry out common vector and polynomial operations (see Templated Arr...