25ReactorNet::ReactorNet()
30ReactorNet::ReactorNet(shared_ptr<ReactorBase> reactor)
36ReactorNet::ReactorNet(vector<shared_ptr<ReactorBase>>& reactors)
39 for (
auto&
reactor : reactors) {
44ReactorNet::~ReactorNet()
92 throw CanteraError(
"ReactorNet::time",
"Time is not the independent variable"
93 " for this reactor network.");
101 throw CanteraError(
"ReactorNet::distance",
"Distance is not the independent"
102 " variable for this reactor network.");
109 debuglog(
"Initializing reactor network.\n", m_verbose);
110 if (m_reactors.empty()) {
112 "no reactors in network!");
115 map<Solution*, vector<string>> solutions;
117 set<ReactorBase*> surfaces;
119 for (
size_t n = 0; n < m_reactors.size(); n++) {
121 shared_ptr<Solution> bulk = r.
phase();
128 writelog(
"Reactor {:d}: {:d} variables.\n", n, nv);
131 if (r.
type() ==
"FlowReactor" && m_reactors.size() > 1) {
133 "FlowReactors must be used alone.");
135 solutions[bulk.get()].push_back(r.
name());
136 for (
size_t i = 0; i < r.
nSurfs(); i++) {
137 if (r.
surface(i)->
phase()->adjacent(bulk->name()) != bulk) {
139 "Bulk phase '{}' used by interface '{}' must be the same object\n"
140 "as the contents of the adjacent reactor '{}'.",
146 for (
auto surf : surfaces) {
147 solutions[surf->phase().get()].push_back(surf->name());
149 for (
auto& [soln, reactors] : solutions) {
150 if (reactors.size() > 1) {
152 for (
size_t i = 0; i < reactors.size() - 1; i++) {
153 shared += fmt::format(
"'{}', ", reactors[i]);
155 shared += fmt::format(
"'{}'", reactors.back());
156 throw CanteraError(
"ReactorNet::initialize",
"The following reactors /"
157 " reactor surfaces are using the same Solution object: {}. Use"
158 " independent Solution objects or set the 'clone' argument to 'true'"
159 " when creating the Reactor or ReactorSurface objects.", shared);
163 m_ydot.resize(m_nv,0.0);
164 m_yest.resize(m_nv,0.0);
165 m_advancelimits.resize(m_nv,-1.0);
166 m_atol.resize(
neq());
167 fill(m_atol.begin(), m_atol.end(), m_atols);
168 m_integ->setTolerances(m_rtol,
neq(), m_atol.data());
169 m_integ->setSensitivityTolerances(m_rtolsens, m_atolsens);
170 if (!m_linearSolverType.empty()) {
171 m_integ->setLinearSolverType(m_linearSolverType);
174 m_integ->setPreconditioner(m_precon);
176 m_integ->initialize(
m_time, *
this);
181 if (m_integ->preconditionerSide() != PreconditionerSide::NO_PRECONDITION) {
191 debuglog(
"Re-initializing reactor network.\n", m_verbose);
192 m_integ->reinitialize(
m_time, *
this);
193 if (m_integ->preconditionerSide() != PreconditionerSide::NO_PRECONDITION) {
204 m_linearSolverType = linSolverType;
210 m_precon = preconditioner;
231 m_integ->integrate(
time);
232 m_time = m_integ->currentTime();
261 m_integ->integrate(
time);
267 m_time = m_integ->currentTime();
281 if (m_advancelimits.size() != m_nv) {
282 m_advancelimits.assign(m_nv, -1.0);
285 double* ycurr = m_integ->solution();
287 double max_ratio = -1.0;
288 double best_limit = 0.0;
289 for (
size_t j = 0; j < m_nv; j++) {
290 double lim = m_advancelimits[j];
292 double delta = std::abs(ycurr[j] -
m_ybase[j]);
293 double ratio = delta / lim;
294 if (ratio > max_ratio) {
303 double y_start =
m_ybase[jmax];
304 double y_end = ycurr[jmax];
305 double delta = y_end - y_start;
306 writelog(
" Advance limit triggered for component {:d} (dt = {:9.4g}):"
307 " y_start = {:11.6g}, y_end = {:11.6g},"
308 " delta = {:11.6g}, limit = {:9.4g}\n",
309 jmax, dt, y_start, y_end, delta, best_limit);
336 vector<double> y(
neq());
340 solver.
solve(loglevel);
352 vector<double> y0(
neq());
353 vector<double> y1(
neq());
360 return std::dynamic_pointer_cast<EigenSparseJacobian>(solver.
linearSolver())->jacobian();
369 double* cvode_dky = m_integ->solution();
370 for (
size_t j = 0; j < m_nv; j++) {
371 yest[j] = cvode_dky[j];
377 for (
int n = 1; n <= k; n++) {
378 factor *= deltat / n;
379 cvode_dky = m_integ->derivative(
m_time, n);
380 for (
size_t j = 0; j < m_nv; j++) {
381 yest[j] += factor * cvode_dky[j];
389 return m_integ->lastOrder();
407 if (m_advancelimits.size() != m_nv) {
408 m_advancelimits.assign(m_nv, -1.0);
412 double max_ratio = 0.0;
413 for (
size_t i = 0; i < m_nv; i++) {
414 double lim = m_advancelimits[i];
416 double delta = std::abs(y[i] -
m_ybase[i]);
417 double ratio = delta / lim;
418 if (ratio > max_ratio) {
431 auto r = std::dynamic_pointer_cast<Reactor>(
reactor);
434 "Reactor with type '{}' cannot be added to network.",
438 for (
auto current : m_reactors) {
439 if (current->isOde() != r->isOde()) {
441 "Cannot mix Reactor types using both ODEs and DAEs ({} and {})",
442 current->type(), r->type());
444 if (current->timeIsIndependent() != r->timeIsIndependent()) {
446 "Cannot mix Reactor types using time and space as independent variables"
447 "\n({} and {})", current->type(), r->type());
452 m_reactors.push_back(r.get());
458 m_integ->setLinearSolverType(
"DENSE");
468 for (
size_t i=0; i<r.
nWalls(); i++) {
471 if (w.left().type() ==
"Reservoir") {
474 if (w.right().type() ==
"Reservoir") {
479 for (
size_t i=0; i<r.
nInlets(); i++) {
480 auto& in = r.
inlet(i);
482 if (in.in().type() ==
"Reservoir") {
487 for (
size_t i=0; i<r.
nOutlets(); i++) {
490 if (out.out().type() ==
"Reservoir") {
495 for (
size_t i=0; i<r.
nSurfs(); i++) {
501 if (m_integ ==
nullptr) {
503 "Integrator has not been instantiated. Add one or more reactors first.");
512 m_LHS.assign(m_nv, 1);
513 m_RHS.assign(m_nv, 0);
514 for (
size_t n = 0; n < m_reactors.size(); n++) {
515 m_reactors[n]->applySensitivity(p);
518 if (n == m_reactors.size() - 1) {
523 for (
size_t i =
m_start[n]; i < yEnd; i++) {
524 ydot[i] = m_RHS[i] /
m_LHS[i];
526 m_reactors[n]->resetSensitivity(p);
535 for (
size_t n = 0; n < m_reactors.size(); n++) {
536 m_reactors[n]->applySensitivity(p);
537 m_reactors[n]->evalDae(t, y, ydot, residual);
538 m_reactors[n]->resetSensitivity(p);
545 for (
size_t n = 0; n < m_reactors.size(); n++) {
546 m_reactors[n]->getConstraints(constraints +
m_start[n]);
559 double denom = m_integ->solution(k);
563 return m_integ->sensitivity(k, p) / denom;
570 for (
size_t n = 0; n < m_nv; n++) {
573 double dy = m_atol[n] + fabs(ysave)*m_rtol;
578 eval(t, y, m_ydot.data(), p);
581 for (
size_t m = 0; m < m_nv; m++) {
582 j->
value(m,n) = (m_ydot[m] - ydot[m])/dy;
591 for (
size_t n = 0; n < m_reactors.size(); n++) {
592 m_reactors[n]->updateState(y +
m_start[n]);
601 double* cvode_dky = m_integ->derivative(
m_time, k);
602 for (
size_t j = 0; j < m_nv; j++) {
603 dky[j] = cvode_dky[j];
612 for (
size_t n = 0; n < m_reactors.size(); n++) {
613 m_reactors[n]->setAdvanceLimits(limits +
m_start[n]);
619 bool has_limit =
false;
620 for (
size_t n = 0; n < m_reactors.size(); n++) {
621 has_limit |= m_reactors[n]->hasAdvanceLimits();
628 bool has_limit =
false;
629 for (
size_t n = 0; n < m_reactors.size(); n++) {
630 has_limit |= m_reactors[n]->getAdvanceLimits(limits +
m_start[n]);
637 for (
size_t n = 0; n < m_reactors.size(); n++) {
638 m_reactors[n]->getState(y +
m_start[n]);
644 for (
size_t n = 0; n < m_reactors.size(); n++) {
661 for (
auto r : m_reactors) {
663 return r->name() +
": " + r->componentName(i);
669 throw IndexError(
"ReactorNet::componentName",
"component", i0, iTot);
676 for (
auto r : m_reactors) {
678 return r->upperBound(i);
684 throw IndexError(
"ReactorNet::upperBound",
"upperBound", i0, iTot);
691 for (
auto r : m_reactors) {
693 return r->lowerBound(i);
699 throw IndexError(
"ReactorNet::lowerBound",
"lowerBound", i0, iTot);
704 for (
auto r : m_reactors) {
705 r->resetBadValues(y +
m_start[i++]);
710 const string& name,
double value,
double scale)
713 throw CanteraError(
"ReactorNet::registerSensitivityParameter",
714 "Sensitivity parameters cannot be added after the"
715 "integrator has been initialized.");
726 for (
size_t i = 0; i < m_reactors.size(); i++) {
727 m_reactors[i]->setDerivativeSettings(settings);
734 return m_integ->solverStats();
743 return m_integ->linearSolverType();
753 "Must only be called after ReactorNet is initialized.");
755 m_integ->preconditionerSolve(m_nv, rhs, output);
763 auto precon = m_integ->preconditioner();
767 precon->setGamma(gamma);
769 vector<double> yCopy(m_nv);
773 precon->stateAdjustment(yCopy);
777 for (
size_t i = 0; i < m_reactors.size(); i++) {
778 Eigen::SparseMatrix<double> rJac = m_reactors[i]->jacobian();
779 for (
int k=0; k<rJac.outerSize(); ++k) {
780 for (Eigen::SparseMatrix<double>::InnerIterator it(rJac, k); it; ++it) {
787 precon->updatePreconditioner();
794 "Must only be called after ReactorNet is initialized.");
796 auto precon = m_integ->preconditioner();
797 precon->setGamma(gamma);
798 precon->updatePreconditioner();
803 for (
auto reactor : m_reactors) {
805 throw CanteraError(
"ReactorNet::checkPreconditionerSupported",
806 "Preconditioning is only supported for type *MoleReactor,\n"
807 "Reactor type given: '{}'.",
813SteadyReactorSolver::SteadyReactorSolver(
ReactorNet* net,
double* x0)
816 m_size = m_net->neq();
819 m_initialState.assign(x0, x0 + m_size);
821 m_mask.assign(m_size, 1);
823 for (
size_t i = 0; i < net->nReactors(); i++) {
825 for (
auto& m : R.steadyConstraints()) {
826 m_algebraic.push_back(start + m);
830 for (
auto& n : m_algebraic) {
840 vector<double> xv(x, x +
size());
841 m_net->
eval(0.0, x, r,
nullptr);
842 for (
size_t i = 0; i <
size(); i++) {
860 clock_t t0 = clock();
862 m_work2.resize(
size());
864 for (
size_t j = 0; j <
size(); j++) {
866 double xsave = x0[j];
872 double rdx = 1.0 / (x0[j] - xsave);
875 eval(x0, m_work2.data(), 0.0, 0);
878 for (
size_t i = 0; i <
size(); i++) {
879 double delta = m_work2[i] -
m_work1[i];
881 m_jac->setValue(i, j, delta * rdx);
887 m_jac->updateElapsed(
double(clock() - t0) / CLOCKS_PER_SEC);
888 m_jac->incrementEvals();
895 const double* x =
m_state->data();
896 for (
size_t i = 0; i <
size(); i++) {
897 double ewt = m_net->
rtol()*x[i] + m_net->
atol();
898 double f = step[i] / ewt;
901 return sqrt(sum /
size());
925 const string& message,
int loglevel,
int attempt_counter)
927 if (loglevel >= 6 && !
m_state->empty()) {
929 writelog(
"Current state ({}):\n[", header_suffix);
930 for (
size_t i = 0; i < state.size() - 1; i++) {
935 if (loglevel >= 7 && !
m_xnew.empty()) {
936 writelog(
"Current residual ({}):\n[", header_suffix);
937 for (
size_t i = 0; i <
m_xnew.size() - 1; i++) {
944shared_ptr<ReactorNet>
newReactorNet(vector<shared_ptr<ReactorBase>>& reactors)
946 return make_shared<ReactorNet>(reactors);
Header file for class Cantera::Array2D.
Header file for class ReactorSurface.
Header file for base class WallBase.
A map of string keys to values whose type can vary at runtime.
A class for 2D arrays stored in column-major (Fortran-compatible) form.
double & value(size_t i, size_t j)
Returns a changeable reference to position in the matrix.
Base class for exceptions thrown by Cantera classes.
void setDefaultName(map< string, int > &counts)
Set the default name of a connector. Returns false if it was previously set.
vector< double > m_paramScales
Scaling factors for each sensitivity parameter.
bool suppressErrors() const
Get current state of error suppression.
vector< double > m_sens_params
Values for the problem parameters for which sensitivities are computed This is the array which is per...
An array index is out of range.
Abstract base class for ODE system integrators.
virtual void setMaxStepSize(double hmax)
Set the maximum step size.
virtual void setMaxSteps(int nmax)
Set the maximum number of time-steps the integrator can take before reaching the next output time.
virtual int maxSteps()
Returns the maximum number of time-steps the integrator can take before reaching the next output time...
virtual void setMaxErrTestFails(int n)
Set the maximum permissible number of error test failures.
FlowDevice & outlet(size_t n=0)
Return a reference to the n-th outlet FlowDevice connected to this reactor.
size_t nWalls()
Return the number of Wall objects connected to this reactor.
WallBase & wall(size_t n)
Return a reference to the n-th Wall connected to this reactor.
bool setDefaultName(map< string, int > &counts)
Set the default name of a reactor. Returns false if it was previously set.
virtual size_t nSurfs() const
Return the number of surfaces in a reactor.
FlowDevice & inlet(size_t n=0)
Return a reference to the n-th inlet FlowDevice connected to this reactor.
size_t nOutlets()
Return the number of outlet FlowDevice objects connected to this reactor.
size_t nInlets()
Return the number of inlet FlowDevice objects connected to this reactor.
ReactorSurface * surface(size_t n)
Return a reference to the n-th ReactorSurface connected to this reactor.
shared_ptr< Solution > phase()
Access the Solution object used to represent the contents of this reactor.
string name() const
Return the name of this reactor.
A class representing a network of connected reactors.
void setLinearSolverType(const string &linSolverType="DENSE")
Set the type of linear solver used in the integration.
void preconditionerSetup(double t, double *y, double gamma) override
Evaluate the setup processes for the Jacobian preconditioner.
double step()
Advance the state of all reactors with respect to the independent variable (time or space).
virtual int lastOrder() const
Returns the order used for last solution step of the ODE integrator The function is intended for inte...
void eval(double t, double *y, double *ydot, double *p) override
Evaluate the right-hand-side ODE function.
double m_ybase_time
Base time corresponding to m_ybase.
void initialize()
Initialize the reactor network.
void advance(double t)
Advance the state of all reactors in the independent variable (time or space).
size_t neq() const override
Number of equations.
vector< size_t > m_start
m_start[n] is the starting point in the state vector for reactor n
vector< double > m_LHS
m_LHS is a vector representing the coefficients on the "left hand side" of each governing equation
double m_initial_time
The initial value of the independent variable in the system.
void evalJacobian(double t, double *y, double *ydot, double *p, Array2D *j)
Evaluate the Jacobian matrix for the reactor network.
double time()
Current value of the simulation time [s], for reactor networks that are solved in the time domain.
void getConstraints(double *constraints) override
Given a vector of length neq(), mark which variables should be considered algebraic constraints.
double m_time
The independent variable in the system.
AnyMap solverStats() const
Get solver stats from integrator.
Reactor & reactor(int n)
Return a reference to the n-th reactor in this network.
void addReactor(shared_ptr< ReactorBase > reactor)
Add the reactor r to this reactor network.
bool m_limit_check_active
Indicates whether the advance-limit root check is active for the current call to advance(t,...
map< string, int > m_counts
Map used for default name generation.
double upperBound(size_t i) const
Get the upper bound on the i-th component of the global state vector.
virtual void setMaxSteps(int nmax)
Set the maximum number of internal integration steps the integrator will take before reaching the nex...
string componentName(size_t i) const
Return the name of the i-th component of the global state vector.
void evalRootFunctions(double t, const double *y, double *gout) override
Evaluate the advance-limit root function used to stop integration once a limit is met.
size_t nRootFunctions() const override
Root finding is enabled only while enforcing advance limits.
void getStateDae(double *y, double *ydot) override
Fill in the vectors y and ydot with the current state of the system.
void setInitialTime(double time)
Set the initial value of the independent variable (typically time).
virtual void getDerivative(int k, double *dky)
Return k-th derivative at the current state of the system.
void setMaxErrTestFails(int nmax)
Set the maximum number of error test failures permitted by the CVODES integrator in a single step.
size_t registerSensitivityParameter(const string &name, double value, double scale)
Used by Reactor and Wall objects to register the addition of sensitivity parameters so that the React...
double m_maxstep
Maximum integrator internal timestep. Default of 0.0 means infinity.
double distance()
Current position [m] along the length of the reactor network, for reactors that are solved as a funct...
void setSensitivityTolerances(double rtol, double atol)
Set the relative and absolute tolerances for integrating the sensitivity equations.
int maxSteps()
Returns the maximum number of internal integration steps the integrator will take before reaching the...
virtual void setDerivativeSettings(AnyMap &settings)
Set derivative settings of all reactors.
double sensitivity(size_t k, size_t p)
Return the sensitivity of the k-th solution component with respect to the p-th sensitivity parameter.
void updateNames(Reactor &r)
Create reproducible names for reactors and walls/connectors.
void updateState(double *y)
Update the state of all the reactors in the network to correspond to the values in the solution vecto...
void getState(double *y) override
Fill in the vector y with the current state of the system.
void setAdvanceLimits(const double *limits)
Set absolute step size limits during advance.
double rtol()
Relative tolerance.
size_t globalComponentIndex(const string &component, size_t reactor=0)
Return the index corresponding to the component named component in the reactor with index reactor in ...
void solveSteady(int loglevel=0)
Solve directly for the steady-state solution.
bool m_timeIsIndependent
Indicates whether time or space is the independent variable.
double atol()
Absolute integration tolerance.
bool hasAdvanceLimits() const
Check whether ReactorNet object uses advance limits.
vector< double > m_ybase
Base state used for evaluating advance limits during a single advance() call when root-finding is ena...
void setMaxTimeStep(double maxstep)
Set the maximum integrator step.
double lowerBound(size_t i) const
Get the lower bound on the i-th component of the global state vector.
void evalDae(double t, double *y, double *ydot, double *p, double *residual) override
eval coupling for IDA / DAEs
virtual void checkPreconditionerSupported() const
Check that preconditioning is supported by all reactors in the network.
bool m_integrator_init
True if integrator initialization is current.
void reinitialize()
Reinitialize the integrator.
Integrator & integrator()
Return a reference to the integrator.
bool getAdvanceLimits(double *limits) const
Retrieve absolute step size limits during advance.
Eigen::SparseMatrix< double > steadyJacobian(double rdt=0.0)
Get the Jacobian used by the steady-state solver.
string linearSolverType() const
Problem type of integrator.
void updatePreconditioner(double gamma) override
Update the preconditioner based on already computed jacobian values.
void setPreconditioner(shared_ptr< SystemJacobian > preconditioner)
Set preconditioner used by the linear solver.
void preconditionerSolve(double *rhs, double *output) override
Evaluate the linear system Ax=b where A is the preconditioner.
vector< string > m_paramNames
Names corresponding to each sensitivity parameter.
void resetBadValues(double *y)
Reset physically or mathematically problematic values, such as negative species concentrations.
void setTolerances(double rtol, double atol)
Set the relative and absolute tolerances for the integrator.
virtual void getEstimate(double time, int k, double *yest)
Estimate a future state based on current derivatives.
Class Reactor is a general-purpose class for stirred reactors.
size_t neq()
Number of equations (state variables) for this reactor.
size_t nSensParams() const override
Number of sensitivity parameters associated with this reactor.
string type() const override
String indicating the reactor model implemented.
void initialize(double t0=0.0) override
Initialize the reactor.
virtual bool preconditionerSupported() const
Return a false if preconditioning is not supported or true otherwise.
Adapter class to enable using the SteadyStateSystem solver with ReactorNet.
double weightedNorm(const double *step) const override
Compute the weighted norm of step.
vector< double > m_initialState
Initial value of each state variable.
string componentName(size_t i) const override
Get the name of the i-th component of the state vector.
double upperBound(size_t i) const override
Get the upper bound for global component i in the state vector.
vector< size_t > m_algebraic
Indices of variables that are held constant in the time-stepping mode of the steady-state solver.
void evalJacobian(double *x0) override
Evaluates the Jacobian at x0 using finite differences.
void resetBadValues(double *x) override
Reset values such as negative species concentrations.
void writeDebugInfo(const string &header_suffix, const string &message, int loglevel, int attempt_counter) override
Write solver debugging based on the specified log level.
void eval(double *x, double *r, double rdt=-1.0, int count=1) override
Evaluate the residual function.
void initTimeInteg(double dt, double *x) override
Prepare for time stepping beginning with solution x and timestep dt.
double lowerBound(size_t i) const override
Get the lower bound for global component i in the state vector.
virtual void resize()
Call to set the size of internal data structures after first defining the system or if the problem si...
shared_ptr< SystemJacobian > linearSolver() const
Get the the linear solver being used to hold the Jacobian matrix and solve linear systems as part of ...
vector< double > m_xnew
Work array used to hold the residual or the new solution.
double m_jacobianAbsPerturb
Absolute perturbation of each component in finite difference Jacobian.
size_t size() const
Total solution vector length;.
vector< int > & transientMask()
Access the vector indicating which equations contain a transient term.
double rdt() const
Reciprocal of the time step.
virtual void initTimeInteg(double dt, double *x)
Prepare for time stepping beginning with solution x and timestep dt.
double m_rdt
Reciprocal of time step.
double m_jacobianThreshold
Threshold for ignoring small elements in Jacobian.
shared_ptr< SystemJacobian > m_jac
Jacobian evaluator.
shared_ptr< vector< double > > m_state
Solution vector.
void setMaxTimeStepCount(int nmax)
Set the maximum number of timeteps allowed before successful steady-state solve.
void solve(int loglevel=0)
Solve the steady-state problem, taking internal timesteps as necessary until the Newton solver can co...
void getState(double *x) const
Get the converged steady-state solution after calling solve().
double m_jacobianRelPerturb
Relative perturbation of each component in finite difference Jacobian.
vector< double > m_work1
Work arrays used during Jacobian evaluation.
void debuglog(const string &msg, int loglevel)
Write a message to the log only if loglevel > 0.
void writelog(const string &fmt, const Args &... args)
Write a formatted message to the screen.
void scale(InputIter begin, InputIter end, OutputIter out, S scale_factor)
Multiply elements of an array by a scale factor.
Integrator * newIntegrator(const string &itype)
Create new Integrator object.
Namespace for the Cantera kernel.
const size_t npos
index returned by functions to indicate "no position"
void checkFinite(const double tmp)
Check to see that a number is finite (not NaN, +Inf or -Inf)
@ BDF_Method
Backward Differentiation.
shared_ptr< SystemJacobian > newSystemJacobian(const string &type)
Create a SystemJacobian object of the specified type.
const double SmallNumber
smallest number to compare to zero.
shared_ptr< ReactorNet > newReactorNet(vector< shared_ptr< ReactorBase > > &reactors)
Create a reactor network containing one or more coupled reactors.
Various templated functions that carry out common vector and polynomial operations (see Templated Arr...