17SteadyStateSystem::SteadyStateSystem()
19 m_state = make_shared<vector<double>>();
20 m_newt = make_unique<MultiNewton>(1);
24SteadyStateSystem::~SteadyStateSystem()
30 auto t0 = std::chrono::steady_clock::now();
33 std::chrono::steady_clock::now() - t0).count());
41 long int nev =
m_jac->nEvals();
43 m_stats[
"grid_points"].asVector<
long int>().push_back(
48 m_stats[
"jacobian_evals"].asVector<
long int>().push_back(nev);
49 m_stats[
"jacobian_time"].asVector<
double>().push_back(
m_jac->elapsedTime());
68 m_stats[
"grid_points"] = vector<long int>();
69 m_stats[
"steps"] = vector<long int>();
70 m_stats[
"residual_evals"] = vector<long int>();
71 m_stats[
"residual_time"] = vector<double>();
72 m_stats[
"jacobian_evals"] = vector<long int>();
73 m_stats[
"jacobian_time"] = vector<double>();
74 m_stats[
"factorizations"] = vector<long int>();
75 m_stats[
"factor_time"] = vector<double>();
76 m_stats[
"linear_solves"] = vector<long int>();
77 m_stats[
"solve_time"] = vector<double>();
78 m_stats[
"total_time"] = vector<double>();
93 m_state->assign(x.begin(), x.end());
103 auto tStart = std::chrono::steady_clock::now();
116 debuglog(
"\nAttempt Newton solution of steady-state problem.", loglevel);
127 writelog(
"\nSteady Jacobian factorization failed:"
145 std::chrono::steady_clock::now() - tStart).count();
148 debuglog(
"\nNewton steady-state solve failed.\n", loglevel);
153 writelog(
"\nAttempt {} timesteps.", nsteps);
163 writelog(
"\nFinal timestep info: dt= {:<10.4g} log(ss)= {:<10.4g}\n", dt,
172 dt = std::min(dt,
m_tmax);
177SteadyStateSystem::TimeStepGrowthStrategy
178SteadyStateSystem::parseTimeStepGrowthStrategy(
const string& strategy)
180 if (strategy ==
"fixed-growth") {
181 return TimeStepGrowthStrategy::fixed;
182 }
else if (strategy ==
"steady-norm") {
183 return TimeStepGrowthStrategy::steadyNorm;
184 }
else if (strategy ==
"transient-residual") {
185 return TimeStepGrowthStrategy::transientResidual;
186 }
else if (strategy ==
"residual-ratio") {
187 return TimeStepGrowthStrategy::residualRatio;
188 }
else if (strategy ==
"newton-iterations") {
189 return TimeStepGrowthStrategy::newtonIterations;
191 throw CanteraError(
"SteadyStateSystem::setTimeStepGrowthStrategy",
192 "Unknown time step growth strategy '{}'; must be one of "
193 "'fixed-growth', 'steady-norm', 'transient-residual', "
194 "'residual-ratio', or 'newton-iterations'.", strategy);
197string SteadyStateSystem::timeStepGrowthStrategyName(TimeStepGrowthStrategy strategy)
200 case TimeStepGrowthStrategy::fixed:
201 return "fixed-growth";
202 case TimeStepGrowthStrategy::steadyNorm:
203 return "steady-norm";
204 case TimeStepGrowthStrategy::transientResidual:
205 return "transient-residual";
206 case TimeStepGrowthStrategy::residualRatio:
207 return "residual-ratio";
208 case TimeStepGrowthStrategy::newtonIterations:
209 return "newton-iterations";
211 throw CanteraError(
"SteadyStateSystem::timeStepGrowthStrategyName",
212 "Unknown time step growth strategy.");
226 span<const double> x_after)
236 case TimeStepGrowthStrategy::fixed:
238 case TimeStepGrowthStrategy::steadyNorm: {
241 return (ss_after < ss_before) ? growth : 1.0;
243 case TimeStepGrowthStrategy::transientResidual: {
246 return (ts_after < ts_before) ? growth : 1.0;
248 case TimeStepGrowthStrategy::residualRatio: {
251 if (!(ts_after > 0.0) || !(ts_before > ts_after)) {
254 const double exponent = 0.2;
255 double ratio = ts_before / ts_after;
256 double factor = std::pow(ratio, exponent);
257 return std::min(growth, std::max(1.0, factor));
259 case TimeStepGrowthStrategy::newtonIterations: {
260 const int max_iters_for_growth = 3;
261 return (
newton().lastIterations() <= max_iters_for_growth) ? growth : 1.0;
264 throw CanteraError(
"SteadyStateSystem::calculateTimeStepGrowthFactor",
269 span<double> r,
int loglevel)
275 int successiveFailures = 0;
279 writelog(
"\n============================");
280 writelog(
"\n{:<5s} {:<11s} {:<7s}\n",
"step",
"dt (s)",
"log(ss)");
281 writelog(
"============================");
286 writelog(
"\n{:<5d} {:<6.4e} {:>7.4f}", n, dt, log10(ss));
287 }
else if (loglevel > 1) {
289 writelog(
"\nTimestep ({}) dt= {:<11.4e} log(ss)= {:<7.4f}", n, dt, log10(ss));
295 int j0 =
m_jac->nEvals();
298 int status =
newton().
solve(x, r, *
this, loglevel);
304 writelog(
"\nTimestep ({}) succeeded", n);
306 successiveFailures = 0;
309 if (
m_jac->nEvals() == j0) {
312 copy(r.begin(), r.end(), x.begin());
316 dt = std::min(dt,
m_tmax);
319 "Took maximum number of timesteps allowed ({}) without "
325 successiveFailures++;
328 }
else if (loglevel > 1) {
329 writelog(
"\nTimestep ({}) failed", n);
331 if (successiveFailures > 2) {
332 debuglog(
"--> Resetting negative species concentrations", loglevel);
334 successiveFailures = 0;
336 debuglog(
"--> Reducing timestep", loglevel);
340 "Time integration failed. Minimum timestep ({}) reached.",
m_tmin);
349 writelog(
"\n{:<5d} {:<6.4e} {:>7.4f}", n, dt, log10(ss));
350 writelog(
"\n============================");
351 }
else if (loglevel > 1) {
353 writelog(
"\nTimestep ({}) dt= {:<11.4e} log10(ss)= {:<7.4f}\n", n, dt, log10(ss));
365 for (
size_t i = 0; i <
m_size; i++) {
366 ss = std::max(fabs(r[i]),ss);
375 for (
size_t i = 0; i <
m_size; i++) {
376 ts = std::max(fabs(r[i]), ts);
384 m_steps.assign(tsteps.begin(), tsteps.end());
395 "Jacobian evaluator must be instantiated before calling resize()");
414 double rdt_save =
m_rdt;
423 double rdt_old =
m_rdt;
Base class for exceptions thrown by Cantera classes.
virtual string getMessage() const
Method overridden by derived classes to format the error message.
virtual string getMethod() const
Get the name of the method that threw the exception.
virtual double eval(double t) const
Evaluate the function.
Newton iterator for multi-domain, one-dimensional problems.
void setOptions(int maxJacAge=5)
Set options.
int solve(span< const double > x0, span< double > x1, SteadyStateSystem &r, int loglevel)
Find the solution to F(x) = 0 by damped Newton iteration.
int m_nsteps
Number of time steps taken in the current call to solve()
double calculateTimeStepGrowthFactor(span< const double > x_before, span< const double > x_after)
Determine the timestep growth factor after a successful step.
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...
int m_linearSolves
Linear solves on the current grid.
double timeStep(int nsteps, double dt, span< double > x, span< double > r, int loglevel)
Take time steps using Backward Euler.
virtual void resetBadValues(span< double > x)
Reset values such as negative species concentrations.
vector< double > m_xnew
Work array used to hold the residual or the new solution.
virtual void saveStats()
Commit statistics for the current grid into m_stats and reset the staging counters.
unique_ptr< MultiNewton > m_newt
Newton iterator.
void getState(span< double > x) const
Get the converged steady-state solution after calling solve().
size_t size() const
Total solution vector length;.
void factorizeJacobian()
Update the transient term of the Jacobian (forming and factorizing ) and record the elapsed wall-cloc...
virtual void initTimeInteg(double dt, span< const double > x)
Prepare for time stepping beginning with solution x and timestep dt.
AnyMap m_stats
Committed per-grid statistics.
double tsnorm(span< const double > x, span< double > r)
Transient max norm (infinity norm) of the residual evaluated using solution x and the current timeste...
void evalSSJacobian(span< const double > x)
Evaluate the steady-state Jacobian, accessible via linearSolver()
double m_solveTime
Wall time [s] in linear solves.
size_t bandwidth() const
Jacobian bandwidth.
double m_rdt
Reciprocal of time step.
virtual size_t gridSize() const
Value reported as grid_points in solver statistics.
void recordFactorization(double wallTime)
Record wall-clock time [s] spent factorizing the Jacobian.
shared_ptr< SystemJacobian > m_jac
Jacobian evaluator.
void setInitialGuess(span< const double > x)
Set the initial guess. Should be called before solve().
shared_ptr< vector< double > > m_state
Solution vector.
double m_factorTime
Wall time [s] factorizing the Jacobian.
void setTimeStepGrowthStrategy(const string &strategy)
Set the strategy used to grow the timestep after a successful step that reuses the current Jacobian.
virtual void eval(span< const double > x, span< double > r, double rdt=-1.0, int count=1)=0
Evaluate the residual function.
vector< int > m_mask
Transient mask.
void solve(int loglevel=0)
Solve the steady-state problem, taking internal timesteps as necessary until the Newton solver can co...
double ssnorm(span< const double > x, span< double > r)
Steady-state max norm (infinity norm) of the residual evaluated using solution x.
string timeStepGrowthStrategy() const
Get the configured timestep growth strategy.
void setTimeStep(double stepsize, span< const int > tsteps)
Set the number of time steps to try when the steady Newton solver is unsuccessful.
vector< int > m_steps
Array of number of steps to take after each unsuccessful steady-state solve before re-attempting the ...
double m_evaltime
Wall time [s] in standalone residual evals.
TimeStepGrowthStrategy m_tstep_growth_strategy
Selected strategy for successful-step growth.
double m_tfactor
Factor time step is multiplied by if time stepping fails ( < 1 )
bool m_jac_ok
If true, Jacobian is current.
double m_tstep
Initial timestep.
int m_factorizations
Jacobian factorizations on the current grid.
int m_ts_jac_age
Maximum age of the Jacobian in time-stepping mode.
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...
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.
double m_tmax
Maximum timestep size.
int m_ss_jac_age
Maximum age of the Jacobian in steady-state mode.
double m_gridTime
Total wall time [s] solving on the current grid.
int m_nevals
Standalone residual evaluations (not Jacobian fill)
virtual void evalJacobian(span< const double > x0)=0
Evaluates the Jacobian at x0 using finite differences.
virtual void clearStats()
Clear all saved solver statistics and reset the staging counters.
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...
int m_max_history
Constant that determines the maximum number of states stored in the debug log file generated by write...
Func1 * m_time_step_callback
User-supplied function called after each successful timestep.
vector< double > m_xlast_ts
State vector after the last successful set of time steps.
vector< double > m_work1
Work arrays used during Jacobian evaluation.
MultiNewton & newton()
Return a reference to the Newton iterator.
double m_tstep_growth
Growth factor for successful steps that reuse the Jacobian.
Error thrown when time stepping cannot proceed and the steady-state solver should be given a chance t...
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.
Namespace for the Cantera kernel.
const double Tiny
Small number to compare differences of mole fractions against.