Cantera  3.3.0a1
Loading...
Searching...
No Matches
SteadyStateSystem.h
Go to the documentation of this file.
1//! @file SteadyStateSystem.h
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
6#ifndef CT_STEADYSTATESYSTEM_H
7#define CT_STEADYSTATESYSTEM_H
8
10#include "SystemJacobian.h"
11
12namespace Cantera
13{
14
15class Func1;
16class MultiNewton;
17
18//! Base class for representing a system of differential-algebraic equations and solving
19//! for its steady-state response.
20//!
21//! @since New in %Cantera 3.2.
22//! @ingroup numerics
24{
25public:
27 virtual ~SteadyStateSystem();
28 SteadyStateSystem(const SteadyStateSystem&) = delete;
29 SteadyStateSystem& operator=(const SteadyStateSystem&) = delete;
30
31 //! Evaluate the residual function
32 //!
33 //! @param[in] x State vector
34 //! @param[out] r On return, contains the residual vector
35 //! @param rdt Reciprocal of the time step. if omitted, then the internally stored
36 //! value (accessible using the rdt() method) is used.
37 //! @param count Set to zero to omit this call from the statistics
38 virtual void eval(double* x, double* r, double rdt=-1.0, int count=1) = 0;
39
40 //! Evaluates the Jacobian at x0 using finite differences.
41 //!
42 //! The Jacobian is computed by perturbing each component of `x0`, evaluating the
43 //! residual function, and then estimating the partial derivatives numerically using
44 //! finite differences to determine the corresponding column of the Jacobian.
45 //!
46 //! @param x0 State vector at which to evaluate the Jacobian
47 virtual void evalJacobian(double* x0) = 0;
48
49 //! Compute the weighted norm of `step`.
50 //!
51 //! The purpose is to measure the "size" of the step vector @f$ \Delta x @f$ in a
52 //! way that takes into account the relative importance or scale of different
53 //! solution components. Each component of the step vector is normalized by a weight
54 //! that depends on both the current magnitude of the solution vector and specified
55 //! tolerances. This makes the norm dimensionless and scaled appropriately, avoiding
56 //! issues where some components dominate due to differences in their scales. See
57 //! OneDim::weightedNorm() for a representative implementation.
58 virtual double weightedNorm(const double* step) const = 0;
59
60 //! Set the initial guess. Should be called before solve().
61 void setInitialGuess(const double* x);
62
63 //! Solve the steady-state problem, taking internal timesteps as necessary until
64 //! the Newton solver can converge for the steady problem.
65 //! @param loglevel Controls amount of diagnostic output.
66 void solve(int loglevel=0);
67
68 //! Get the converged steady-state solution after calling solve().
69 void getState(double* x) const;
70
71 //! Steady-state max norm (infinity norm) of the residual evaluated using solution
72 //! x. On return, array r contains the steady-state residual values.
73 double ssnorm(double* x, double* r);
74
75 //! Total solution vector length;
76 size_t size() const {
77 return m_size;
78 }
79
80 //! Call to set the size of internal data structures after first defining the system
81 //! or if the problem size changes, for example after grid refinement.
82 //!
83 //! The #m_size variable should be updated before calling this method
84 virtual void resize();
85
86 //! Jacobian bandwidth.
87 size_t bandwidth() const {
88 return m_bw;
89 }
90
91 //! Get the name of the i-th component of the state vector
92 virtual string componentName(size_t i) const { return fmt::format("{}", i); }
93
94 //! Get header lines describing the column names included in a component label.
95 //! Headings should be aligned with items formatted in the output of
96 //! componentTableLabel(). Two lines are allowed. If only one is needed, the first
97 //! line should be blank.
98 virtual pair<string, string> componentTableHeader() const {
99 return {"", "component name"};
100 }
101
102 //! Get elements of the component name, aligned with the column headings given
103 //! by componentTableHeader().
104 virtual string componentTableLabel(size_t i) const { return componentName(i); }
105
106 //! Get the upper bound for global component *i* in the state vector
107 virtual double upperBound(size_t i) const = 0;
108
109 //! Get the lower bound for global component *i* in the state vector
110 virtual double lowerBound(size_t i) const = 0;
111
112 //! Return a reference to the Newton iterator.
114
115 //! Set the linear solver used to hold the Jacobian matrix and solve linear systems
116 //! as part of each Newton iteration.
117 void setLinearSolver(shared_ptr<SystemJacobian> solver);
118
119 //! Get the the linear solver being used to hold the Jacobian matrix and solve
120 //! linear systems as part of each Newton iteration.
121 shared_ptr<SystemJacobian> linearSolver() const { return m_jac; }
122
123 //! Reciprocal of the time step.
124 double rdt() const {
125 return m_rdt;
126 }
127
128 //! True if transient mode.
129 bool transient() const {
130 return (m_rdt != 0.0);
131 }
132
133 //! True if steady mode.
134 bool steady() const {
135 return (m_rdt == 0.0);
136 }
137
138 //! Prepare for time stepping beginning with solution *x* and timestep *dt*.
139 virtual void initTimeInteg(double dt, double* x);
140
141 //! Prepare to solve the steady-state problem. After invoking this method,
142 //! subsequent calls to solve() will solve the steady-state problem. Sets the
143 //! reciprocal of the time step to zero, and, if it was previously non-zero, signals
144 //! that a new Jacobian will be needed.
145 virtual void setSteadyMode();
146
147 //! Access the vector indicating which equations contain a transient term.
148 //! Elements are 1 for equations with a transient terms and 0 otherwise.
149 vector<int>& transientMask() {
150 return m_mask;
151 }
152
153 //! Take time steps using Backward Euler.
154 //!
155 //! @param nsteps number of steps
156 //! @param dt initial step size
157 //! @param x current solution vector
158 //! @param r solution vector after time stepping
159 //! @param loglevel controls amount of printed diagnostics
160 //! @returns size of last timestep taken
161 double timeStep(int nsteps, double dt, double* x, double* r, int loglevel);
162
163 //! Reset values such as negative species concentrations
164 virtual void resetBadValues(double* x) {}
165
166 //! @name Options
167 //! @{
168
169 //! Set the number of time steps to try when the steady Newton solver is
170 //! unsuccessful.
171 //! @param stepsize Initial time step size [s]
172 //! @param n Length of `tsteps` array
173 //! @param tsteps A sequence of time step counts to take after subsequent failures
174 //! of the steady-state solver. The last value in `tsteps` will be used again
175 //! after further unsuccessful solution attempts.
176 void setTimeStep(double stepsize, size_t n, const int* tsteps);
177
178 //! Set the number of time steps to try when the steady Newton solver is
179 //! unsuccessful.
180 //! @param stepSize Initial time step size [s]
181 //! @param tSteps A sequence of time step counts to take after subsequent failures
182 //! of the steady-state solver. The last value in `tsteps` will be used again
183 //! after further unsuccessful solution attempts.
184 //! @since New in %Cantera 3.2
185 void setTimeStep(double stepSize, const vector<int>& tSteps) {
186 setTimeStep(stepSize, tSteps.size(), tSteps.data());
187 }
188
189 //! Set the minimum time step allowed during time stepping
190 void setMinTimeStep(double tmin) {
191 m_tmin = tmin;
192 }
193
194 //! Set the maximum time step allowed during time stepping
195 void setMaxTimeStep(double tmax) {
196 m_tmax = tmax;
197 }
198
199 //! Sets a factor by which the time step is reduced if the time stepping fails.
200 //! The default value is 0.5.
201 //!
202 //! @param tfactor factor time step is multiplied by if time stepping fails
203 void setTimeStepFactor(double tfactor) {
204 m_tfactor = tfactor;
205 }
206
207 //! Set the maximum number of timeteps allowed before successful steady-state solve
208 void setMaxTimeStepCount(int nmax) {
209 m_nsteps_max = nmax;
210 }
211
212 //! Get the maximum number of timeteps allowed before successful steady-state solve
213 int maxTimeStepCount() const {
214 return m_nsteps_max;
215 }
216 //! @}
217
218 //! Set the maximum number of steps that can be taken using the same Jacobian
219 //! before it must be re-evaluated.
220 //! @param ss_age Age limit during steady-state mode
221 //! @param ts_age Age limit during time stepping mode. If not specified, the
222 //! steady-state age is also used during time stepping.
223 void setJacAge(int ss_age, int ts_age=-1);
224
225 //! Set a function that will be called every time #eval is called.
226 //! Can be used to provide keyboard interrupt support in the high-level
227 //! language interfaces.
228 void setInterrupt(Func1* interrupt) {
229 m_interrupt = interrupt;
230 }
231
232 //! Set a function that will be called after each successful timestep. The
233 //! function will be called with the size of the timestep as the argument.
234 //! Intended to be used for observing solver progress for debugging
235 //! purposes.
236 void setTimeStepCallback(Func1* callback) {
237 m_time_step_callback = callback;
238 }
239
240 //! Configure perturbations used to evaluate finite difference Jacobian
241 //! @param relative Relative perturbation (multiplied by the absolute value of
242 //! each component). Default `1.0e-5`.
243 //! @param absolute Absolute perturbation (independent of component value).
244 //! Default `1.0e-10`.
245 //! @param threshold Threshold below which to exclude elements from the Jacobian
246 //! Default `0.0`.
247 void setJacobianPerturbation(double relative, double absolute, double threshold) {
248 m_jacobianRelPerturb = relative;
249 m_jacobianAbsPerturb = absolute;
250 m_jacobianThreshold = threshold;
251 }
252
253 //! Write solver debugging based on the specified log level.
254 //!
255 //! @see Sim1D::writeDebugInfo for a specific implementation of this capability.
256 virtual void writeDebugInfo(const string& header_suffix, const string& message,
257 int loglevel, int attempt_counter) {}
258
259 //! Delete debug output file that may be created by writeDebugInfo() when solving
260 //! with high `loglevel`.
261 virtual void clearDebugFile() {}
262
263protected:
264 //! Evaluate the steady-state Jacobian, accessible via linearSolver()
265 //! @param[in] x Current state vector, length size()
266 //! @param[out] rsd Storage for the residual, length size()
267 void evalSSJacobian(double* x, double* rsd);
268
269 //! Array of number of steps to take after each unsuccessful steady-state solve
270 //! before re-attempting the steady-state solution. For subsequent time stepping
271 //! calls, the final value is reused. See setTimeStep().
272 vector<int> m_steps = { 10 };
273
274 double m_tstep = 1.0e-5; //!< Initial timestep
275 double m_tmin = 1e-16; //!< Minimum timestep size
276 double m_tmax = 1e+08; //!< Maximum timestep size
277
278 //! Factor time step is multiplied by if time stepping fails ( < 1 )
279 double m_tfactor = 0.5;
280
281 shared_ptr<vector<double>> m_state; //!< Solution vector
282
283 //! Work array used to hold the residual or the new solution
284 vector<double> m_xnew;
285
286 //! State vector after the last successful set of time steps
287 vector<double> m_xlast_ts;
288
289 unique_ptr<MultiNewton> m_newt; //!< Newton iterator
290 double m_rdt = 0.0; //!< Reciprocal of time step
291
292 shared_ptr<SystemJacobian> m_jac; //!< Jacobian evaluator
293 bool m_jac_ok = false; //!< If `true`, Jacobian is current
294
295 size_t m_bw = 0; //!< Jacobian bandwidth
296 size_t m_size = 0; //!< %Solution vector size
297
298 //! Work arrays used during Jacobian evaluation
299 vector<double> m_work1, m_work2;
300
301 vector<int> m_mask; //!< Transient mask. See transientMask()
302 int m_ss_jac_age = 20; //!< Maximum age of the Jacobian in steady-state mode.
303 int m_ts_jac_age = 20; //!< Maximum age of the Jacobian in time-stepping mode.
304
305 //! Counter used to manage the number of states stored in the debug log file
306 //! generated by writeDebugInfo()
308
309 //! Constant that determines the maximum number of states stored in the debug log
310 //! file generated by writeDebugInfo()
312
313 //! Function called at the start of every call to #eval.
314 Func1* m_interrupt = nullptr;
315
316 //! User-supplied function called after each successful timestep.
318
319 int m_nsteps = 0; //!< Number of time steps taken in the current call to solve()
320 int m_nsteps_max = 500; //!< Maximum number of timesteps allowed per call to solve()
321
322 //! Threshold for ignoring small elements in Jacobian
324 //! Relative perturbation of each component in finite difference Jacobian
325 double m_jacobianRelPerturb = 1e-5;
326 //! Absolute perturbation of each component in finite difference Jacobian
327 double m_jacobianAbsPerturb = 1e-10;
328};
329
330}
331
332#endif
Declarations for class SystemJacobian.
Base class for 'functor' classes that evaluate a function of one variable.
Definition Func1.h:75
Newton iterator for multi-domain, one-dimensional problems.
Definition MultiNewton.h:24
Base class for representing a system of differential-algebraic equations and solving for its steady-s...
int m_nsteps
Number of time steps taken in the current call to solve()
size_t m_size
Solution vector size
int m_nsteps_max
Maximum number of timesteps allowed per call to solve()
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.
unique_ptr< MultiNewton > m_newt
Newton iterator.
virtual void resetBadValues(double *x)
Reset values such as negative species concentrations.
double m_jacobianAbsPerturb
Absolute perturbation of each component in finite difference Jacobian.
size_t size() const
Total solution vector length;.
virtual double weightedNorm(const double *step) const =0
Compute the weighted norm of step.
double ssnorm(double *x, double *r)
Steady-state max norm (infinity norm) of the residual evaluated using solution x.
vector< int > & transientMask()
Access the vector indicating which equations contain a transient term.
virtual double upperBound(size_t i) const =0
Get the upper bound for global component i in the state vector.
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.
virtual string componentName(size_t i) const
Get the name of the i-th component of the state vector.
virtual string componentTableLabel(size_t i) const
Get elements of the component name, aligned with the column headings given by componentTableHeader().
size_t bandwidth() const
Jacobian bandwidth.
double m_rdt
Reciprocal of time step.
double m_jacobianThreshold
Threshold for ignoring small elements in Jacobian.
void setMaxTimeStep(double tmax)
Set the maximum time step allowed during time stepping.
shared_ptr< SystemJacobian > m_jac
Jacobian evaluator.
shared_ptr< vector< double > > m_state
Solution vector.
void setMinTimeStep(double tmin)
Set the minimum time step allowed during time stepping.
vector< int > m_mask
Transient mask.
void setTimeStepCallback(Func1 *callback)
Set a function that will be called after each successful timestep.
Func1 * m_interrupt
Function called at the start of every call to eval.
virtual double lowerBound(size_t i) const =0
Get the lower bound for global component i in the state vector.
bool transient() const
True if transient mode.
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 setTimeStepFactor(double tfactor)
Sets a factor by which the time step is reduced if the time stepping fails.
vector< int > m_steps
Array of number of steps to take after each unsuccessful steady-state solve before re-attempting the ...
size_t m_bw
Jacobian bandwidth.
double m_tfactor
Factor time step is multiplied by if time stepping fails ( < 1 )
bool m_jac_ok
If true, Jacobian is current.
void setTimeStep(double stepSize, const vector< int > &tSteps)
Set the number of time steps to try when the steady Newton solver is unsuccessful.
double m_tstep
Initial timestep.
int maxTimeStepCount() const
Get the maximum number of timeteps allowed before successful steady-state solve.
int m_ts_jac_age
Maximum age of the Jacobian in time-stepping mode.
virtual void eval(double *x, double *r, double rdt=-1.0, int count=1)=0
Evaluate the residual function.
double timeStep(int nsteps, double dt, double *x, double *r, int loglevel)
Take time steps using Backward Euler.
void setJacAge(int ss_age, int ts_age=-1)
Set the maximum number of steps that can be taken using the same Jacobian before it must be re-evalua...
void evalSSJacobian(double *x, double *rsd)
Evaluate the steady-state Jacobian, accessible via linearSolver()
virtual void writeDebugInfo(const string &header_suffix, const string &message, int loglevel, int attempt_counter)
Write solver debugging based on the specified log level.
double m_tmin
Minimum timestep size.
void setJacobianPerturbation(double relative, double absolute, double threshold)
Configure perturbations used to evaluate finite difference Jacobian.
double m_tmax
Maximum timestep size.
int m_ss_jac_age
Maximum age of the Jacobian in steady-state mode.
virtual void setSteadyMode()
Prepare to solve the steady-state problem.
virtual void clearDebugFile()
Delete debug output file that may be created by writeDebugInfo() when solving with high loglevel.
int m_attempt_counter
Counter used to manage the number of states stored in the debug log file generated by writeDebugInfo(...
void setLinearSolver(shared_ptr< SystemJacobian > solver)
Set the linear solver used to hold the Jacobian matrix and solve linear systems as part of each Newto...
void setTimeStep(double stepsize, size_t n, const int *tsteps)
Set the number of time steps to try when the steady Newton solver is unsuccessful.
int m_max_history
Constant that determines the maximum number of states stored in the debug log file generated by write...
void setInitialGuess(const double *x)
Set the initial guess. Should be called before solve().
void getState(double *x) const
Get the converged steady-state solution after calling solve().
Func1 * m_time_step_callback
User-supplied function called after each successful timestep.
virtual pair< string, string > componentTableHeader() const
Get header lines describing the column names included in a component label.
virtual void evalJacobian(double *x0)=0
Evaluates the Jacobian at x0 using finite differences.
double m_jacobianRelPerturb
Relative perturbation of each component in finite difference Jacobian.
vector< double > m_xlast_ts
State vector after the last successful set of time steps.
bool steady() const
True if steady mode.
vector< double > m_work1
Work arrays used during Jacobian evaluation.
MultiNewton & newton()
Return a reference to the Newton iterator.
void setInterrupt(Func1 *interrupt)
Set a function that will be called every time eval is called.
This file contains definitions of constants, types and terms that are used in internal routines and a...
Namespace for the Cantera kernel.
Definition AnyMap.cpp:595