Cantera
Loading...
Searching...
No Matches
Sim1D.h
Go to the documentation of this file.
1/**
2 * @file Sim1D.h
3 */
4
5// This file is part of Cantera. See License.txt in the top-level directory or
6// at https://cantera.org/license.txt for license and copyright information.
7
8#ifndef CT_SIM1D_H
9#define CT_SIM1D_H
10
11#include "OneDim.h"
12
13namespace Cantera
14{
15
16/**
17 * One-dimensional simulations. Class Sim1D extends class OneDim by storing
18 * the solution vector, and by adding a hybrid Newton/time-stepping solver.
19 * @ingroup onedGroup
20 */
21class Sim1D : public OneDim
22{
23public:
24 //! Default constructor.
25 /*!
26 * This constructor is provided to make the class default-constructible, but
27 * is not meant to be used in most applications. Use the next constructor
28 */
29 Sim1D() {}
30
31 /**
32 * Standard constructor.
33 * @param domains A vector of shared pointers to the domains to be linked together.
34 * The domain pointers must be entered in left-to-right order --- that is,
35 * the pointer to the leftmost domain is domain[0], the pointer to the
36 * domain to its right is domain[1], etc.
37 */
38 Sim1D(span<const shared_ptr<Domain1D>> domains);
39
40 //! @name Setting initial values
41 //!
42 //! These methods are used to set the initial values of solution components.
43 //! @{
44
45protected:
46 /**
47 * Set a single value in the solution vector.
48 * @param dom domain number, beginning with 0 for the leftmost domain.
49 * @param comp component number
50 * @param localPoint grid point within the domain, beginning with 0 for
51 * the leftmost grid point in the domain.
52 * @param value the value.
53 * @since New in %Cantera 3.2. Previously part of public interface.
54 */
55 void _setValue(size_t dom, size_t comp, size_t localPoint, double value);
56
57 /**
58 * Get one entry in the solution vector.
59 * @param dom domain number, beginning with 0 for the leftmost domain.
60 * @param comp component number
61 * @param localPoint grid point within the domain, beginning with 0 for
62 * the leftmost grid point in the domain.
63 * @since New in %Cantera 3.2. Previously part of public interface.
64 */
65 double _value(size_t dom, size_t comp, size_t localPoint) const;
66
67 /**
68 * Get an entry in the work vector, which may contain either a new system state
69 * or the current residual of the system.
70 * @param dom domain index
71 * @param comp component index
72 * @param localPoint grid point within the domain
73 * @since New in %Cantera 3.2. Previously part of public interface.
74 */
75 double _workValue(size_t dom, size_t comp, size_t localPoint) const;
76 //! @}
77
78public:
79
80 //! @name Logging, saving and restoring of solutions
81 //!
82 //! @{
83
84 /**
85 * Show logging information on current solution for all domains.
86 * @since New in %Cantera 3.0.
87 */
88 void show();
89
90 /**
91 * Save current simulation data to a container file or CSV format.
92 *
93 * In order to save the content of a Sim1D object, individual domains are
94 * converted to SolutionArray objects and saved using the SolutionArray::save()
95 * method. For HDF and YAML output, all domains are written to a single container
96 * file with shared header information. Simulation settings of individual domains
97 * are preserved as meta data of the corresponding SolutionArray objects.
98 * For CSV files, only state and auxiliary data of the main 1D domain are saved.
99 *
100 * The complete state of the current object can be restored from HDF and YAML
101 * container files using the restore() method, while individual domains can be
102 * loaded using SolutionArray::restore() for further analysis. While CSV do not
103 * contain complete information, they can still be used for setting initial states
104 * of individual simulation objects for some %Cantera API's.
105 *
106 * @param fname Name of output file (CSV, YAML or HDF)
107 * @param name Identifier of storage location within the container file; this
108 * node/group contains header information and multiple subgroups holding
109 * domain-specific SolutionArray data (YAML/HDF only)
110 * @param desc Custom comment describing the dataset to be stored (YAML/HDF only)
111 * @param overwrite Force overwrite if file/name exists; optional (default=false)
112 * @param compression Compression level (0-9); optional (default=0; HDF only)
113 * @param basis Output mass ("Y"/"mass") or mole ("X"/"mole") fractions;
114 * if not specified (default=""), the native basis of the underlying
115 * ThermoPhase manager is used - @see nativeState (CSV only)
116 */
117 void save(const string& fname, const string& name, const string& desc,
118 bool overwrite=false, int compression=0, const string& basis="",
119 const vector<double>* res=nullptr);
120
121 /**
122 * Save the current solution and its residual vector to a container file.
123 * Residual values are appended to each domain's SolutionArray as extra components
124 * prefixed with `residual-`.
125 * @param fname Name of output container file
126 * @param name Identifier of solution within the container file
127 * @param desc Description of the solution
128 * @param overwrite Force overwrite if name exists; optional (default=false)
129 * @param compression Compression level (optional; HDF only)
130 */
131 void saveResidual(const string& fname, const string& name,
132 const string& desc, bool overwrite=false, int compression=0);
133
134 /**
135 * Retrieve data and settings from a previously saved simulation.
136 *
137 * This method restores a simulation object from YAML or HDF data previously saved
138 * using the save() method.
139 *
140 * @param fname Name of container file (YAML or HDF)
141 * @param name Identifier of location within the container file; this node/group
142 * contains header information and subgroups with domain-specific SolutionArray
143 * data
144 * @return AnyMap containing header information
145 */
146 AnyMap restore(const string& fname, const string& name);
147
148 /**
149 * Retrieve data from a previously saved simulation.
150 *
151 * This method is almost identical to restore() but avoids the return of an AnyMap,
152 * which is not implemented in CLib.
153 *
154 * @param fname Name of container file (YAML or HDF)
155 * @param name Identifier of location within the container file; this node/group
156 * contains header information and subgroups with domain-specific SolutionArray
157 * data
158 */
159 void _restore(const string& fname, const string& name);
160
161 /**
162 * Deletes a `debug_sim1d.yaml` file if it exists. Used to clear the file for
163 * successive calls to the solve() method.
164 */
165 void clearDebugFile() override;
166
167 /**
168 * Write solver debugging information to a YAML file based on the specified log
169 * level.
170 *
171 * This method writes solver debug information to a specified YAML file
172 * (`debug_sim1d.yaml`). The section headers are formatted according to the provided
173 * `header_suffix` and `attempt_counter` arguments. Depending on the log level, the
174 * method will save either the solution information or the residual information
175 * for each attempted solution.
176 *
177 * @param header_suffix Header used to construct a unique section in the YAML file
178 * where the information will be written to.
179 * @param message A string that is written to the `description` tag in the YAML
180 * file.
181 * @param loglevel Controls the type of output that will be written. A `loglevel`
182 * greater than 6 saves the solution, and a `loglevel` greater
183 * than 7 saves the solution with residual vectors appended.
184 * @param attempt_counter An integer counter used to uniquely identify the attempt
185 * which is included in the file header to differentiate
186 * between multiple solution attempts.
187 */
188 void writeDebugInfo(const string& header_suffix, const string& message, int loglevel,
189 int attempt_counter) override;
190
191 //! @}
192
193 /**
194 * Performs the hybrid Newton steady/time-stepping solution.
195 *
196 * The solver attempts to solve the steady-state problem first. If the steady-state
197 * solver fails, the time-stepping solver is used to take multiple time steps to
198 * move the solution closer to the steady-state solution. The steady-state solver is
199 * called again after the timesteps to make further progress towards the steady-state
200 * solution. This process is repeated until the steady-state solver converges or the
201 * maximum number of timesteps is reached.
202 *
203 * At the end of a successful solve, if the `refine_grid` flag is set, the grid will be
204 * analyzed and refined if necessary. If the grid is refined, the solution process
205 * described above is repeated with the new grid. This process is repeated until the
206 * grid no longer needs refinement based on the refine criteria.
207 *
208 * @param loglevel Controls the amount of diagnostic output.
209 * @param refine_grid If `true`, the grid will be refined
210 */
211 void solve(int loglevel = 0, bool refine_grid = true);
212
213 void eval(double rdt=-1.0, int count = 1) {
214 OneDim::eval(npos, *m_state, m_xnew, rdt, count);
215 }
216 using OneDim::eval;
217
218 //! Evaluate the governing equations and return the vector of residuals
219 void getResidual(double rdt, span<double> resid) {
220 OneDim::eval(npos, *m_state, resid, rdt, 0);
221 }
222
223 //! Refine the grid in all domains.
224 //!
225 //! @returns If positive, the number of new grid points added. If negative, the
226 //! number of grid points removed. If zero, the grid is unchanged.
227 //!
228 //! @since Changed in %Cantera 3.1. Previously, the return value was zero if points
229 //! were removed but not added.
230 int refine(int loglevel=0);
231
232 //! Add node for fixed temperature point of freely propagating flame
233 int setFixedTemperature(double t);
234
235 //! Return temperature at the point used to fix the flame location
236 double fixedTemperature();
237
238 //! Return location of the point where temperature is fixed
240
241 /**
242 * Set the left control point location using the specified temperature.
243 * This is used when two-point flame control is active.
244 *
245 * The provided temperature will be used to locate the closest grid point to
246 * that temperature, which will serve to locate the left control point's
247 * coordinate. Starting from the left boundary, the first grid point that is
248 * equal to or exceeds the specified temperature will be used to locate the
249 * left control point's coordinate.
250 */
251 void setLeftControlPoint(double temperature);
252
253 /**
254 * Set the right control point location using the specified temperature.
255 * This is used when two-point flame control is active.
256 *
257 * The provided temperature will be used to locate the closest grid point to
258 * that temperature, which will serve to locate the right control point's
259 * coordinate. Starting from the right boundary, the first grid point that is
260 * equal to or exceeds the specified temperature will be used to locate the
261 * right control point's coordinate.
262 */
263 void setRightControlPoint(double temperature);
264
265 /**
266 * Set grid refinement criteria. If dom >= 0, then the settings
267 * apply only to the specified domain. If dom < 0, the settings
268 * are applied to each domain. @see Refiner::setCriteria.
269 */
270 void setRefineCriteria(int dom = -1, double ratio = 10.0,
271 double slope = 0.8, double curve = 0.8,
272 double prune = -0.1);
273
274 /**
275 * Get the grid refinement criteria. dom must be greater than
276 * or equal to zero (that is, the domain must be specified).
277 * @see Refiner::getCriteria
278 */
279 vector<double> getRefineCriteria(int dom);
280
281 /**
282 * Set the maximum number of grid points in the domain. If dom >= 0,
283 * then the settings apply only to the specified domain. If dom < 0,
284 * the settings are applied to each domain. @see Refiner::setMaxPoints.
285 */
286 void setMaxGridPoints(int dom, int npoints);
287
288 /**
289 * Get the maximum number of grid points in this domain. @see Refiner::maxPoints
290 *
291 * @param dom domain number, beginning with 0 for the leftmost domain.
292 */
293 size_t maxGridPoints(size_t dom);
294
295 //! Set the minimum grid spacing in the specified domain(s).
296 /*!
297 * @param dom Domain index. If dom == -1, the specified spacing is applied
298 * to all domains.
299 * @param gridmin The minimum allowable grid spacing [m]
300 */
301 void setGridMin(int dom, double gridmin);
302
303 //! Set the current solution vector to the last successful time-stepping
304 //! solution. This can be used to examine the solver progress after a failed
305 //! integration.
307
308 //! Set the current solution vector and grid to the last successful steady-
309 //! state solution. This can be used to examine the solver progress after a
310 //! failure during grid refinement.
312
313 //! Get the initial value of the system state from each domain in the simulation.
314 void getInitialSoln();
315
316 //! Evaluate the Jacobian in steady-state mode.
317 void evalSSJacobian();
318
319 //! Solve the equation @f$ J^T \lambda = b @f$.
320 /**
321 * Here, @f$ J = \partial f/\partial x @f$ is the Jacobian matrix of the
322 * system of equations @f$ f(x,p)=0 @f$. This can be used to efficiently
323 * solve for the sensitivities of a scalar objective function @f$ g(x,p) @f$
324 * to a vector of parameters @f$ p @f$ by solving:
325 * @f[ J^T \lambda = \left( \frac{\partial g}{\partial x} \right)^T @f]
326 * for @f$ \lambda @f$ and then computing:
327 * @f[
328 * \left.\frac{dg}{dp}\right|_{f=0} = \frac{\partial g}{\partial p}
329 * - \lambda^T \frac{\partial f}{\partial p}
330 * @f]
331 */
332 void solveAdjoint(span<const double> b, span<double> lambda);
333
334 void resize() override;
335
336 //! Set a function that will be called after each successful steady-state
337 //! solve, before regridding. Intended to be used for observing solver
338 //! progress for debugging purposes.
339 void setSteadyCallback(Func1* callback) {
340 m_steady_callback = callback;
341 }
342
343 //! Set the maximum number of regrid attempts after a timestep failure.
344 //!
345 //! This fallback is used during solve(loglevel, refine_grid=true). Set to `0`
346 //! to disable regrid-on-timestep-failure retries.
347 //!
348 //! @param nmax Maximum retry attempts; must be >= 0.
349 void setTimeStepRegridMax(int nmax) {
350 if (nmax < 0) {
351 throw CanteraError("Sim1D::setTimeStepRegridMax",
352 "Time step regrid retry count must be >= 0. Got {}.", nmax);
353 }
354 m_ts_regrid_max = nmax;
355 }
356
357 //! Get the maximum number of regrid attempts after a timestep failure.
358 int timeStepRegridMax() const {
359 return m_ts_regrid_max;
360 }
361
362protected:
363 //! the solution vector after the last successful steady-state solve (stored
364 //! before grid refinement)
365 vector<double> m_xlast_ss;
366
367 //! the grids for each domain after the last successful steady-state solve
368 //! (stored before grid refinement)
369 vector<vector<double>> m_grid_last_ss;
370
371 //! User-supplied function called after a successful steady-state solve.
373
374 //! 0 disables regrid-on-timestep-failure retries
376
377private:
378 //! Calls method _finalize in each domain.
379 void finalize();
380};
381
382/**
383 * Create a Sim1D object with a list of domains.
384 * @param[in] domains A vector of shared pointers to the domains to be linked together.
385 * The domain pointers must be entered in left-to-right order --- that is,
386 * the pointer to the leftmost domain is domain[0], the pointer to the
387 * domain to its right is domain[1], etc.
388 * @since New in %Cantera 3.2.
389 */
390shared_ptr<Sim1D> newSim1D(vector<shared_ptr<Domain1D>>& domains);
391
392}
393#endif
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.
Base class for 'functor' classes that evaluate a function of one variable.
Definition Func1.h:75
OneDim()=default
Default constructor.
void eval(size_t j, span< const double > x, span< double > r, double rdt=-1.0, int count=1)
Evaluate the multi-domain residual function.
Definition OneDim.cpp:219
void getInitialSoln()
Get the initial value of the system state from each domain in the simulation.
Definition Sim1D.cpp:330
void restoreTimeSteppingSolution()
Set the current solution vector to the last successful time-stepping solution.
Definition Sim1D.cpp:308
void resize() override
Call to set the size of internal data structures after first defining the system or if the problem si...
Definition Sim1D.cpp:836
void save(const string &fname, const string &name, const string &desc, bool overwrite=false, int compression=0, const string &basis="", const vector< double > *res=nullptr)
Save current simulation data to a container file or CSV format.
Definition Sim1D.cpp:62
void saveResidual(const string &fname, const string &name, const string &desc, bool overwrite=false, int compression=0)
Save the current solution and its residual vector to a container file.
Definition Sim1D.cpp:120
double fixedTemperatureLocation()
Return location of the point where temperature is fixed.
Definition Sim1D.cpp:633
vector< vector< double > > m_grid_last_ss
the grids for each domain after the last successful steady-state solve (stored before grid refinement...
Definition Sim1D.h:369
double _value(size_t dom, size_t comp, size_t localPoint) const
Get one entry in the solution vector.
Definition Sim1D.cpp:46
void finalize()
Calls method _finalize in each domain.
Definition Sim1D.cpp:338
void setSteadyCallback(Func1 *callback)
Set a function that will be called after each successful steady-state solve, before regridding.
Definition Sim1D.h:339
int refine(int loglevel=0)
Refine the grid in all domains.
Definition Sim1D.cpp:419
void show()
Show logging information on current solution for all domains.
Definition Sim1D.cpp:296
double fixedTemperature()
Return temperature at the point used to fix the flame location.
Definition Sim1D.cpp:620
void clearDebugFile() override
Deletes a debug_sim1d.yaml file if it exists.
Definition Sim1D.cpp:508
void getResidual(double rdt, span< double > resid)
Evaluate the governing equations and return the vector of residuals.
Definition Sim1D.h:219
double _workValue(size_t dom, size_t comp, size_t localPoint) const
Get an entry in the work vector, which may contain either a new system state or the current residual ...
Definition Sim1D.cpp:54
vector< double > m_xlast_ss
the solution vector after the last successful steady-state solve (stored before grid refinement)
Definition Sim1D.h:365
void setTimeStepRegridMax(int nmax)
Set the maximum number of regrid attempts after a timestep failure.
Definition Sim1D.h:349
void _restore(const string &fname, const string &name)
Retrieve data from a previously saved simulation.
Definition Sim1D.cpp:291
void setMaxGridPoints(int dom, int npoints)
Set the maximum number of grid points in the domain.
Definition Sim1D.cpp:784
int setFixedTemperature(double t)
Add node for fixed temperature point of freely propagating flame.
Definition Sim1D.cpp:529
void solve(int loglevel=0, bool refine_grid=true)
Performs the hybrid Newton steady/time-stepping solution.
Definition Sim1D.cpp:346
void evalSSJacobian()
Evaluate the Jacobian in steady-state mode.
Definition Sim1D.cpp:803
int m_ts_regrid_max
0 disables regrid-on-timestep-failure retries
Definition Sim1D.h:375
AnyMap restore(const string &fname, const string &name)
Retrieve data and settings from a previously saved simulation.
Definition Sim1D.cpp:214
Func1 * m_steady_callback
User-supplied function called after a successful steady-state solve.
Definition Sim1D.h:372
void solveAdjoint(span< const double > b, span< double > lambda)
Solve the equation .
Definition Sim1D.cpp:808
void restoreSteadySolution()
Set the current solution vector and grid to the last successful steady- state solution.
Definition Sim1D.cpp:317
size_t maxGridPoints(size_t dom)
Get the maximum number of grid points in this domain.
Definition Sim1D.cpp:797
int timeStepRegridMax() const
Get the maximum number of regrid attempts after a timestep failure.
Definition Sim1D.h:358
void writeDebugInfo(const string &header_suffix, const string &message, int loglevel, int attempt_counter) override
Write solver debugging information to a YAML file based on the specified log level.
Definition Sim1D.cpp:518
void setRightControlPoint(double temperature)
Set the right control point location using the specified temperature.
Definition Sim1D.cpp:697
vector< double > getRefineCriteria(int dom)
Get the grid refinement criteria.
Definition Sim1D.cpp:761
Sim1D()
Default constructor.
Definition Sim1D.h:29
void setGridMin(int dom, double gridmin)
Set the minimum grid spacing in the specified domain(s).
Definition Sim1D.cpp:771
void setRefineCriteria(int dom=-1, double ratio=10.0, double slope=0.8, double curve=0.8, double prune=-0.1)
Set grid refinement criteria.
Definition Sim1D.cpp:749
void _setValue(size_t dom, size_t comp, size_t localPoint, double value)
Set a single value in the solution vector.
Definition Sim1D.cpp:38
void setLeftControlPoint(double temperature)
Set the left control point location using the specified temperature.
Definition Sim1D.cpp:646
vector< double > m_xnew
Work array used to hold the residual or the new solution.
double rdt() const
Reciprocal of the time step.
shared_ptr< vector< double > > m_state
Solution vector.
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:183
shared_ptr< Sim1D > newSim1D(vector< shared_ptr< Domain1D > > &domains)
Create a Sim1D object with a list of domains.
Definition Sim1D.cpp:842