Cantera  4.0.0a1
Loading...
Searching...
No Matches
IdealGasMoleReactor.cpp
Go to the documentation of this file.
1//! @file IdealGasMoleReactor.cpp A constant volume zero-dimensional
2//! reactor with moles as the state
3
4// This file is part of Cantera. See License.txt in the top-level directory or
5// at https://cantera.org/license.txt for license and copyright information.
6
11#include "cantera/zeroD/Wall.h"
16#include "cantera/numerics/eigen_dense.h"
17#include <limits>
18
19namespace Cantera
20{
21
23{
24 // get mass for calculations
25 m_mass = m_thermo->density() * m_vol;
26
27 // set the first component to the temperature
28 y[0] = m_thermo->temperature();
29
30 // set the second component to the volume
31 y[1] = m_vol;
32
33 // get moles of species in remaining state
34 getMoles(y.subspan(m_sidx));
35}
36
37size_t IdealGasMoleReactor::componentIndex(const string& nm) const
38{
39 if (nm == "temperature") {
40 return 0;
41 }
42 if (nm == "volume") {
43 return 1;
44 }
45 try {
46 return m_thermo->speciesIndex(nm) + m_sidx;
47 } catch (const CanteraError&) {
48 throw CanteraError("IdealGasMoleReactor::componentIndex",
49 "Component '{}' not found", nm);
50 }
51}
52
54{
55 if (k == 0) {
56 return "temperature";
57 } else {
59 }
60}
61
63{
65 m_uk.resize(m_nsp, 0.0);
66}
67
68double IdealGasMoleReactor::upperBound(size_t k) const {
69 if (k == 0) {
70 //@todo: Revise pending resolution of https://github.com/Cantera/enhancements/issues/229
71 return 1.5 * m_thermo->maxTemp();
72 } else {
74 }
75}
76
77double IdealGasMoleReactor::lowerBound(size_t k) const {
78 if (k == 0) {
79 //@todo: Revise pending resolution of https://github.com/Cantera/enhancements/issues/229
80 return 0.5 * m_thermo->minTemp();
81 } else {
83 }
84}
85
87{
90 if (energyEnabled()) {
91 return {1}; // volume
92 } else {
93 return {0, 1}; // temperature and volume
94 }
95}
96
97void IdealGasMoleReactor::updateState(span<const double> y)
98{
99 // the components of y are: [0] the temperature, [1] the volume, [2...K+1) are the
100 // moles of each species, and [K+1...] are the moles of surface
101 // species on each wall.
102 setMassFromMoles(y.subspan(m_sidx));
103 if (y[1] <= 0.0) {
104 throw CanteraError("IdealGasMoleReactor::updateState",
105 "Volume must be positive. Input value was {}", y[1]);
106 }
107 m_vol = y[1];
108 // set state
109 m_thermo->setMolesNoTruncate(y.subspan(m_sidx, m_nsp));
110 m_thermo->setState_TD(y[0], m_mass / m_vol);
112 m_TotalCv = m_mass * m_thermo->cv_mass();
113 updateConnected(true);
114}
115
116void IdealGasMoleReactor::eval(double time, span<double> LHS, span<double> RHS)
117{
118 double& mcvdTdt = RHS[0]; // m * c_v * dT/dt
119 auto dndt = RHS.subspan(m_sidx); // kmol per s
120
121 evalWalls(time);
123 auto imw = m_thermo->inverseMolecularWeights();
124
125 if (m_chem) {
126 m_kin->getNetProductionRates(m_wdot); // "omega dot"
127 }
128
129 // external heat transfer and compression work
130 mcvdTdt += - (m_pressure + m_thermo->internalPressure()) * m_vdot + m_Qdot;
131
132 if (m_energy) {
133 mcvdTdt += m_thermo->intrinsicHeating() * m_vol;
134 }
135
136 for (size_t n = 0; n < m_nsp; n++) {
137 // heat release from gas phase and surface reactions
138 mcvdTdt -= m_wdot[n] * m_uk[n] * m_vol;
139 mcvdTdt -= m_sdot[n] * m_uk[n];
140 // production in gas phase and from surfaces
141 dndt[n] = (m_wdot[n] * m_vol + m_sdot[n]);
142 }
143
144 // add terms for outlets
145 for (auto outlet : m_outlet) {
146 for (size_t n = 0; n < m_nsp; n++) {
147 // flow of species into system and dilution by other species
148 dndt[n] -= outlet->outletSpeciesMassFlowRate(n) * imw[n];
149 }
150 double mdot = outlet->massFlowRate();
151 mcvdTdt -= mdot * m_pressure * m_vol / m_mass; // flow work
152 }
153
154 // add terms for inlets
155 for (auto inlet : m_inlet) {
156 double mdot = inlet->massFlowRate();
157 mcvdTdt += inlet->enthalpy_mass() * mdot;
158 for (size_t n = 0; n < m_nsp; n++) {
159 double mdot_spec = inlet->outletSpeciesMassFlowRate(n);
160 // flow of species into system and dilution by other species
161 dndt[n] += inlet->outletSpeciesMassFlowRate(n) * imw[n];
162 mcvdTdt -= m_uk[n] * imw[n] * mdot_spec;
163 }
164 }
165
166 RHS[1] = m_vdot;
167 if (m_energy) {
168 LHS[0] = m_TotalCv;
169 } else {
170 RHS[0] = 0;
171 }
172}
173
174void IdealGasMoleReactor::evalSteady(double t, span<double> LHS, span<double> RHS)
175{
176 eval(t, LHS, RHS);
177 if (!energyEnabled()) {
178 RHS[0] = m_thermo->temperature() - m_initialTemperature;
179 }
180 RHS[1] = m_vol - m_initialVolume;
181}
182
183void IdealGasMoleReactor::getJacobianElements(vector<Eigen::Triplet<double>>& trips)
184{
185 // dnk_dnj represents d(dot(n_k)) / d (n_j) but is first assigned as
186 // d (dot(omega)) / d c_j, it is later transformed appropriately.
187 Eigen::SparseMatrix<double> dnk_dnj = m_kin->netProductionRates_ddCi();
188
189 // add species to species derivatives elements to the jacobian
190 // calculate ROP derivatives, excluding the terms -n_i / (V * N) dc_i/dn_j
191 // as it substantially reduces matrix sparsity
192 for (int k = 0; k < dnk_dnj.outerSize(); k++) {
193 for (Eigen::SparseMatrix<double>::InnerIterator it(dnk_dnj, k); it; ++it) {
194 trips.emplace_back(static_cast<int>(it.row() + m_offset + m_sidx),
195 static_cast<int>(it.col() + m_offset + m_sidx), it.value());
196 }
197 }
198
199 // Temperature Derivatives
200 if (m_energy) {
201 // getting perturbed state for finite difference
202 double deltaTemp = m_thermo->temperature()
203 * std::sqrt(std::numeric_limits<double>::epsilon());
204 // finite difference temperature derivatives
205 vector<double> lhsPerturbed(m_nv, 1.0), lhsCurrent(m_nv, 1.0);
206 vector<double> rhsPerturbed(m_nv, 0.0), rhsCurrent(m_nv, 0.0);
207 vector<double> yCurrent(m_nv);
208 getState(yCurrent);
209 vector<double> yPerturbed = yCurrent;
210 // perturb temperature
211 yPerturbed[0] += deltaTemp;
212 // getting perturbed state
213 updateState(yPerturbed);
214 double time = (m_net != nullptr) ? m_net->time() : 0.0;
215 eval(time, lhsPerturbed, rhsPerturbed);
216 // reset and get original state
217 updateState(yCurrent);
218 eval(time, lhsCurrent, rhsCurrent);
219 // d ydot_j/dT
220 for (size_t j = 0; j < m_nv; j++) {
221 double ydotPerturbed = rhsPerturbed[j] / lhsPerturbed[j];
222 double ydotCurrent = rhsCurrent[j] / lhsCurrent[j];
223 trips.emplace_back(static_cast<int>(j + m_offset), m_offset,
224 (ydotPerturbed - ydotCurrent) / deltaTemp);
225 }
226 // d T_dot/dnj
227 Eigen::VectorXd netProductionRates = Eigen::VectorXd::Zero(m_nsp);
228 Eigen::VectorXd internal_energy = Eigen::VectorXd::Zero(m_nsp);
229 Eigen::VectorXd specificHeat = Eigen::VectorXd::Zero(m_nsp);
230 // getting species data
231 m_thermo->getPartialMolarIntEnergies(asSpan(internal_energy));
232 m_kin->getNetProductionRates(asSpan(netProductionRates));
233 m_thermo->getPartialMolarCv_TV(asSpan(specificHeat));
234 for (size_t i = 0; i < m_nsp; i++) {
235 netProductionRates[i] *= m_vol;
236 }
237 // scale net production rates by volume to get molar rate
238 double qdot = internal_energy.dot(netProductionRates);
239 double denom = 1 / (m_TotalCv * m_TotalCv);
240 Eigen::VectorXd uk_dnkdnj_sums = dnk_dnj.transpose() * internal_energy;
241 // add derivatives to jacobian
242 for (size_t j = 0; j < m_nsp; j++) {
243 trips.emplace_back(m_offset, static_cast<int>(j + m_offset + m_sidx),
244 (specificHeat[j] * qdot - m_TotalCv * uk_dnkdnj_sums[j]) * denom);
245 }
246 }
247
248 // Add cross-reactor terms due to flow devices and walls.
249 bool includeComposition = !m_jac_skip_connector_composition_dependence;
250 bool includePressureSpecies =
252
254 auto imw = m_thermo->inverseMolecularWeights();
255 for (auto outlet : m_outlet) {
256 for (size_t n = 0; n < m_nsp; n++) {
258 m_offset + m_sidx + n, n, -imw[n], includeComposition,
259 includePressureSpecies);
260 }
261 if (m_energy && m_TotalCv != 0.0 && m_mass != 0.0) {
264 includePressureSpecies);
265 }
266 }
267
268 for (auto inlet : m_inlet) {
269 for (size_t n = 0; n < m_nsp; n++) {
271 m_offset + m_sidx + n, n, imw[n], includeComposition,
272 includePressureSpecies);
273 }
274 if (m_energy && m_TotalCv != 0.0) {
276 inlet->enthalpy_mass() / m_TotalCv, includePressureSpecies);
277 // d(h_in)/d(upstream_state): temperature and (optionally) composition.
279 1.0 / m_TotalCv, includeComposition);
280 for (size_t n = 0; n < m_nsp; n++) {
282 -m_uk[n] * imw[n] / m_TotalCv, includeComposition,
283 includePressureSpecies);
284 }
285 }
286 }
287 }
288
289 if (!m_jac_skip_walls) {
290 for (size_t i = 0; i < m_wall.size(); i++) {
291 int f = 2 * m_lr[i] - 1;
292 m_wall[i]->addExpansionRateJacobian(trips, m_offset + 1, -f,
293 includePressureSpecies);
294 if (m_energy && m_TotalCv != 0.0) {
295 // Connector preconditioner terms include numerator derivatives for
296 // wall work and heat transfer. Derivatives of m_TotalCv are omitted
297 // here to avoid dense temperature/composition fill-in.
298 double expansionCoeff = -(m_pressure + m_thermo->internalPressure())
299 * (-f) / m_TotalCv;
300 m_wall[i]->addExpansionRateJacobian(trips, m_offset, expansionCoeff,
301 includePressureSpecies);
302 m_wall[i]->addHeatRateJacobian(trips, m_offset, f / m_TotalCv);
303 }
304 }
305 }
306}
307
309 double& f_species, span<double> f_energy)
310{
311 f_species = 1.0 / m_vol;
312 for (size_t k = 0; k < m_nsp; k++) {
313 f_energy[k] = - m_uk[k] / m_TotalCv;
314 }
315}
316
318 SparseTriplets& trips, size_t row, double coeff, bool includeSpecies) const
319{
320 // dP/dT|_V = (pi_T + P) / T, where pi_T = internalPressure() = T*(dP/dT)_V - P.
321 // For ideal gas: pi_T = 0, giving P/T; non-ideal EOS returns the correct pi_T.
322 double dPdT = (m_thermo->internalPressure() + m_pressure)
323 / m_thermo->temperature();
324 // dP/dV_total|_T = -1/(V * kappa_T), where kappa_T = isothermalCompressibility().
325 // For ideal gas: kappa_T = 1/P, giving -P/V.
326 double dPdV = -1.0 / (m_vol * m_thermo->isothermalCompressibility());
327 if (!isJacobianLocalRow(row)) {
328 // Local temperature-column entries are already captured by the finite
329 // difference temperature column in getJacobianElements. Cross-reactor
330 // temperature entries are not, so they are added here.
331 trips.emplace_back(row, m_offset, coeff * dPdT);
332 }
333 trips.emplace_back(row, m_offset + 1, coeff * dPdV);
334 if (includeSpecies) {
335 // Species derivatives: use the ideal-gas approximation dP/dn_k = R*T/V for all
336 // k. For non-ideal phases the exact partial molar pressure derivative would
337 // require EOS-specific evaluation, but these terms are skipped by default.
338 double dPdn = GasConstant * m_thermo->temperature() / m_vol;
339 for (size_t k = 0; k < m_nsp; k++) {
340 trips.emplace_back(row, m_offset + m_sidx + k, coeff * dPdn);
341 }
342 }
343}
344
345void IdealGasMoleReactor::addEnthalpyJacobian(SparseTriplets& trips, size_t row,
346 double coeff, bool includeComposition) const
347{
348 // d(h_mass)/dT = cp_mass
349 addTemperatureJacobian(trips, row, coeff * m_thermo->cp_mass());
350 if (includeComposition) {
351 // d(h_mass)/d(n_k) = (h_k_molar - h_mass * W_k) / m_mass
352 vector<double> hbar(m_nsp);
353 m_thermo->getPartialMolarEnthalpies(hbar);
354 double h_mass = m_thermo->enthalpy_mass();
355 auto mw = m_thermo->molecularWeights();
356 for (size_t k = 0; k < m_nsp; k++) {
357 trips.emplace_back(row, m_offset + m_sidx + k,
358 coeff * (hbar[k] - h_mass * mw[k]) / m_mass);
359 }
360 }
361}
362
364 SparseTriplets& trips, size_t row, double coeff) const
365{
366 if (!isJacobianLocalRow(row)) {
367 // Local temperature-column entries are already captured by the finite
368 // difference temperature column in getJacobianElements. Cross-reactor
369 // temperature entries are not, so they are added here.
370 trips.emplace_back(row, m_offset, coeff);
371 }
372}
373
375 SparseTriplets& trips, size_t row, size_t k, double coeff) const
376{
377 auto mw = m_thermo->molecularWeights();
378 double Yk = m_thermo->massFraction(k);
379 // Convert flow-carried composition derivatives from dY_k/dy to dY_k/dn_j.
380 for (size_t j = 0; j < m_nsp; j++) {
381 double dYdn = -Yk * mw[j] / m_mass;
382 if (j == k) {
383 dYdn += mw[k] / m_mass;
384 }
385 trips.emplace_back(row, m_offset + m_sidx + j, coeff * dYdn);
386 }
387}
388
389}
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 class ThermoPhase, the base class for phases with thermodynamic properties,...
Header file for base class WallBase.
Base class for exceptions thrown by Cantera classes.
double outletSpeciesMassFlowRate(size_t k)
Mass flow rate (kg/s) of outlet species k.
void addInletEnthalpyJacobian(SparseTriplets &trips, size_t row, double coeff, bool includeComposition=true)
Add Jacobian terms for the inlet enthalpy dependence on upstream state.
virtual void addMassFlowRateJacobian(SparseTriplets &trips, size_t row, double coeff, bool includePressureSpecies=true)
Add Jacobian terms proportional to derivatives of the mass flow rate.
double enthalpy_mass()
specific enthalpy
void addOutletSpeciesMassFlowRateJacobian(SparseTriplets &trips, size_t row, size_t k, double coeff, bool includeComposition=true, bool includePressureSpecies=true)
Add Jacobian terms proportional to derivatives of outletSpeciesMassFlowRate(k).
double massFlowRate()
Mass flow rate (kg/s).
Definition FlowDevice.h:37
double upperBound(size_t k) const override
Get the upper bound on the k-th component of the local state vector.
void addTemperatureJacobian(SparseTriplets &trips, size_t row, double coeff) const override
Add terms proportional to derivatives with respect to this reactor's temperature.
void eval(double t, span< double > LHS, span< double > RHS) override
Evaluate the reactor governing equations.
void evalSteady(double t, span< double > LHS, span< double > RHS) override
Evaluate the governing equations with modifications for the steady-state solver.
void addSpeciesMassFractionJacobian(SparseTriplets &trips, size_t row, size_t k, double coeff) const override
Add terms proportional to derivatives with respect to a species mass fraction.
size_t componentIndex(const string &nm) const override
Return the index in the solution vector for this reactor of the component named nm.
void addEnthalpyJacobian(SparseTriplets &trips, size_t row, double coeff, bool includeComposition=true) const override
Add terms proportional to derivatives of this reactor's specific enthalpy.
void addPressureJacobian(SparseTriplets &trips, size_t row, double coeff, bool includeSpecies=true) const override
Add terms proportional to derivatives with respect to this reactor's pressure.
vector< double > m_uk
Species molar internal energies.
vector< size_t > initializeSteady() override
Initialize the reactor before solving a steady-state problem.
double lowerBound(size_t k) const override
Get the lower bound on the k-th component of the local state vector.
string componentName(size_t k) override
Return the name of the solution component with index i.
void getJacobianElements(SparseTriplets &trips) override
Calculate an approximate Jacobian to accelerate preconditioned solvers.
void initialize(double t0=0.0) override
Initialize the reactor.
double m_initialTemperature
Initial temperature [K]; used for steady-state calculations.
double m_initialVolume
Initial volume [m³]; used for steady-state calculations.
void updateState(span< const double > y) override
Set the state of the reactor to correspond to the state vector y.
void getState(span< double > y) override
Get the current state of the reactor.
double m_TotalCv
Total heat capacity ( ) [J/K].
void getJacobianScalingFactors(double &f_species, span< double > f_energy) override
Get scaling factors for the Jacobian matrix terms proportional to .
virtual void getNetProductionRates(span< double > wdot)
Species net production rates [kmol/m^3/s or kmol/m^2/s].
Definition Kinetics.cpp:447
double upperBound(size_t k) const override
Get the upper bound on the k-th component of the local state vector.
void getMoles(span< double > y)
Get moles of the system from mass fractions stored by thermo object.
const size_t m_sidx
const value for the species start index
Definition MoleReactor.h:50
double lowerBound(size_t k) const override
Get the lower bound on the k-th component of the local state vector.
string componentName(size_t k) override
Return the name of the solution component with index i.
void setMassFromMoles(span< const double > y)
Set internal mass variable based on moles given.
span< const double > inverseMolecularWeights() const
Return a const reference to the internal vector of molecular weights.
Definition Phase.cpp:416
double massFraction(size_t k) const
Return the mass fraction of a single species.
Definition Phase.cpp:473
virtual void setMolesNoTruncate(span< const double > N)
Set the state of the object with moles in [kmol].
Definition Phase.cpp:550
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
span< const double > molecularWeights() const
Return a const reference to the internal vector of molecular weights.
Definition Phase.cpp:411
void setState_TD(double t, double rho)
Set the internally stored temperature (K) and density (kg/m^3)
Definition Phase.cpp:385
double temperature() const
Temperature (K).
Definition Phase.h:586
virtual double density() const
Density (kg/m^3).
Definition Phase.h:611
FlowDevice & outlet(size_t n=0)
Return a reference to the n-th outlet FlowDevice connected to this reactor.
double m_pressure
Current pressure in the reactor [Pa].
ReactorNet * m_net
The ReactorNet that this reactor is part of.
bool isJacobianLocalRow(size_t row) const
Check whether a global Jacobian row belongs to this reactor.
size_t m_nv
Number of state variables for this reactor.
FlowDevice & inlet(size_t n=0)
Return a reference to the n-th inlet FlowDevice connected to this reactor.
vector< int > m_lr
Vector of length nWalls(), indicating whether this reactor is on the left (0) or right (1) of each wa...
double m_vol
Current volume of the reactor [m^3].
size_t m_offset
Offset into global ReactorNet state vector.
double m_mass
Current mass of the reactor [kg].
size_t m_nsp
Number of homogeneous species in the mixture.
virtual void updateConnected(bool updatePressure)
Update state information needed by connected reactors, flow devices, and walls.
double time()
Current value of the simulation time [s], for reactor networks that are solved in the time domain.
void evalWalls(double t) override
Evaluate terms related to Walls.
Definition Reactor.cpp:209
bool m_jac_skip_connector_pressure_composition_dependence
Omit species terms in pressure derivatives, which can add fill-in.
Definition Reactor.h:189
bool m_jac_skip_connector_composition_dependence
Omit flow composition derivatives, which can add dense connector blocks.
Definition Reactor.h:186
Kinetics * m_kin
Pointer to the homogeneous Kinetics object that handles the reactions.
Definition Reactor.h:166
vector< double > m_wdot
Species net molar production rates.
Definition Reactor.h:170
bool energyEnabled() const override
Returns true if solution of the energy equation is enabled.
Definition Reactor.h:79
bool m_jac_skip_flow_devices
Omit flow-device terms from the sparse Jacobian.
Definition Reactor.h:180
double m_Qdot
net heat transfer into the reactor, through walls [W]
Definition Reactor.h:169
bool m_jac_skip_walls
Omit wall terms from the sparse Jacobian.
Definition Reactor.h:183
void updateSurfaceProductionRates()
Update m_sdot to reflect current production rates of bulk phase species due to reactions on adjacent ...
Definition Reactor.cpp:306
vector< double > m_sdot
Total production rate of bulk phase species on surfaces [kmol/s].
Definition Reactor.h:174
double m_vdot
net rate of volume change from moving walls [m^3/s]
Definition Reactor.h:168
void initialize(double t0=0.0) override
Initialize the reactor.
Definition Reactor.cpp:78
virtual void getPartialMolarEnthalpies(span< double > hbar) const
Returns an array of partial molar enthalpies for the species in the mixture.
virtual void getPartialMolarCv_TV(span< double > cvtilde) const
Return an array of species molar heat capacities associated with the constant-volume partial molar in...
virtual double minTemp(size_t k=npos) const
Minimum temperature for which the thermodynamic data for the species or phase are valid.
virtual double maxTemp(size_t k=npos) const
Maximum temperature for which the thermodynamic data for the species are valid.
virtual double isothermalCompressibility() const
Returns the isothermal compressibility. Units: 1/Pa.
double cv_mass() const
Specific heat at constant volume and composition [J/kg/K].
virtual void getPartialMolarIntEnergies(span< double > ubar) const
Return an array of partial molar internal energies for the species in the mixture.
virtual double internalPressure() const
Return the internal pressure [Pa].
virtual double intrinsicHeating()
Intrinsic volumetric heating rate [W/m³].
double cp_mass() const
Specific heat at constant pressure and composition [J/kg/K].
virtual void getPartialMolarIntEnergies_TV(span< double > utilde) const
Return an array of partial molar internal energies at constant temperature and volume [J/kmol].
double enthalpy_mass() const
Specific enthalpy. Units: J/kg.
Eigen::SparseMatrix< double > netProductionRates_ddCi()
Calculate derivatives for species net production rates with respect to species concentration at const...
Definition Kinetics.cpp:609
const double GasConstant
Universal Gas Constant [J/kmol/K].
Definition ct_defs.h:123
Namespace for the Cantera kernel.
Definition AnyMap.cpp:595
span< double > asSpan(Eigen::DenseBase< Derived > &v)
Convenience wrapper for accessing Eigen vector/array/map data as a span.
Definition eigen_dense.h:46
Various templated functions that carry out common vector and polynomial operations (see Templated Arr...