Cantera  4.0.0a1
Loading...
Searching...
No Matches
OneDim.cpp
Go to the documentation of this file.
1//! @file OneDim.cpp
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
11
12#include <fstream>
13#include <ctime>
14
15using namespace std;
16
17namespace Cantera
18{
19
20OneDim::OneDim(span<const shared_ptr<Domain1D>> domains)
21{
22 for (const auto& dom : domains) {
23 addDomain(dom);
24 }
25 init();
26 resize();
27}
28
29size_t OneDim::domainIndex(const string& name) const
30{
31 for (size_t n = 0; n < m_dom.size(); n++) {
32 if (domain(n).id() == name) {
33 return n;
34 }
35 }
36 throw CanteraError("OneDim::domainIndex", "Domain '{}' not found", name);
37}
38
39std::tuple<string, size_t, string> OneDim::component(size_t i) const {
40 if (i >= m_size) {
41 throw IndexError("OneDim::component", "components", i, m_size);
42 }
43 const auto& [n, j, k] = m_componentInfo[i];
44 Domain1D& dom = domain(n);
45 return make_tuple(dom.id(), j, dom.componentName(k));
46}
47
48string OneDim::componentName(size_t i) const {
49 const auto& [dom, pt, comp] = component(i);
50 return fmt::format("domain {}, component {} at point {}", dom, comp, pt);
51}
52
53pair<string, string> OneDim::componentTableHeader() const
54{
55 return {"", "Domain Pt. Component"};
56}
57
58string OneDim::componentTableLabel(size_t i) const
59{
60 const auto& [dom, pt, comp] = component(i);
61 return fmt::format("{:8s} {:3d} {:<12s}", dom, pt, comp);
62}
63
64double OneDim::upperBound(size_t i) const
65{
66 const auto& [n, j, k] = m_componentInfo[i];
67 Domain1D& dom = domain(n);
68 return dom.upperBound(k);
69}
70
71double OneDim::lowerBound(size_t i) const
72{
73 const auto& [n, j, k] = m_componentInfo[i];
74 Domain1D& dom = domain(n);
75 return dom.lowerBound(k);
76}
77
78void OneDim::addDomain(shared_ptr<Domain1D> d)
79{
80 // if 'd' is not the first domain, link it to the last domain
81 // added (the rightmost one)
82 size_t n = m_dom.size();
83 if (n > 0) {
84 m_dom.back()->append(d.get());
85 }
86
87 // every other domain is a connector
88 if (n % 2 == 0) {
89 m_connect.push_back(d);
90 } else {
91 m_bulk.push_back(d);
92 }
93
94 // add it also to the global domain list, and set its container and position
95 m_dom.push_back(d);
96 d->setData(m_state);
97 d->setContainer(this, m_dom.size()-1);
98 resize();
99}
100
101double OneDim::weightedNorm(span<const double> step) const
102{
103 double sum = 0.0;
104 const double* x = m_state->data();
105 size_t nd = nDomains();
106 for (size_t n = 0; n < nd; n++) {
107 Domain1D& dom = domain(n);
108 double d_sum = 0.0;
109 size_t nv = dom.nComponents();
110 size_t np = dom.nPoints();
111 size_t dstart = start(n);
112
113 for (size_t i = 0; i < nv; i++) {
114 double esum = 0.0;
115 for (size_t j = 0; j < np; j++) {
116 esum += fabs(x[dstart + nv*j + i]);
117 }
118 double ewt = dom.rtol(i)*esum/np + dom.atol(i);
119 for (size_t j = 0; j < np; j++) {
120 double f = step[dstart + nv*j + i]/ewt;
121 d_sum += f*f;
122 }
123 }
124 sum += d_sum;
125 }
126 return sqrt(sum / size());
127}
128
129void OneDim::writeStats(int printTime)
130{
131 saveStats();
132 writelog("\nStatistics:\n\n Grid Timesteps Functions Time Jacobians Time\n");
133 size_t n = m_gridpts.size();
134 for (size_t i = 0; i < n; i++) {
135 if (printTime) {
136 writelog("{:5d} {:5d} {:6d} {:9.4f} {:5d} {:9.4f}\n",
138 m_jacEvals[i], m_jacElapsed[i]);
139 } else {
140 writelog("{:5d} {:5d} {:6d} NA {:5d} NA\n",
142 }
143 }
144}
145
147{
148 if (m_jac) {
149 int nev = m_jac->nEvals();
150 if (nev > 0 && m_nevals > 0) {
151 m_gridpts.push_back(m_pts);
152 m_jacEvals.push_back(m_jac->nEvals());
153 m_jacElapsed.push_back(m_jac->elapsedTime());
154 m_funcEvals.push_back(m_nevals);
155 m_nevals = 0;
156 m_funcElapsed.push_back(m_evaltime);
158 m_timeSteps.push_back(m_nsteps);
159 m_nsteps = 0;
160 }
161 }
162}
163
165{
166 m_gridpts.clear();
167 m_jacEvals.clear();
168 m_jacElapsed.clear();
169 m_funcEvals.clear();
170 m_funcElapsed.clear();
171 m_timeSteps.clear();
172 m_nevals = 0;
173 m_evaltime = 0.0;
174 m_nsteps = 0;
175}
176
178{
179 m_bw = 0;
180 m_nvars.clear();
181 m_loc.clear();
182 m_componentInfo.clear();
183 size_t lc = 0;
184
185 if (left()) {
186 left()->locate();
187 }
188
189 // save the statistics for the last grid
190 saveStats();
191 m_pts = 0;
192 for (size_t i = 0; i < nDomains(); i++) {
193 const auto& d = m_dom[i];
194
195 size_t np = d->nPoints();
196 size_t nv = d->nComponents();
197 for (size_t n = 0; n < np; n++) {
198 m_nvars.push_back(nv);
199 m_loc.push_back(lc);
200 lc += nv;
201 m_pts++;
202 for (size_t k = 0; k < nv; k++) {
203 m_componentInfo.emplace_back(i, n, k);
204 }
205 }
206
207 // update the Jacobian bandwidth
208
209 // bandwidth of the local block
210 size_t bw1 = d->bandwidth();
211 if (bw1 == npos) {
212 bw1 = std::max<size_t>(2*d->nComponents(), 1) - 1;
213 }
214 m_bw = std::max(m_bw, bw1);
215
216 // bandwidth of the block coupling the first point of this
217 // domain to the last point of the previous domain
218 if (i > 0) {
219 size_t bw2 = m_dom[i-1]->bandwidth();
220 if (bw2 == npos) {
221 bw2 = m_dom[i-1]->nComponents();
222 }
223 bw2 += d->nComponents() - 1;
224 m_bw = std::max(m_bw, bw2);
225 }
226 m_size = d->loc() + d->size();
227 }
228 if (!m_jac) {
229 m_jac = newSystemJacobian("banded-direct");
230 }
232}
233
235{
236 Domain1D* d = right();
237 while (d) {
238 if (d->loc() <= i) {
239 return d;
240 }
241 d = d->left();
242 }
243 return 0;
244}
245
246void OneDim::eval(size_t j, span<const double> x, span<double> r, double rdt, int count)
247{
248 clock_t t0 = clock();
249 if (m_interrupt) {
251 }
252 fill(r.begin(), r.end(), 0.0);
253 if (j == npos) {
254 fill(m_mask.begin(), m_mask.end(), 0);
255 }
256 if (rdt < 0.0) {
257 rdt = m_rdt;
258 }
259
260 // iterate over the bulk domains first
261 for (const auto& d : m_bulk) {
262 d->eval(j, x, r, m_mask, rdt);
263 }
264
265 // then over the connector domains
266 for (const auto& d : m_connect) {
267 d->eval(j, x, r, m_mask, rdt);
268 }
269
270 // increment counter and time
271 if (count) {
272 clock_t t1 = clock();
273 m_evaltime += double(t1 - t0)/CLOCKS_PER_SEC;
274 m_nevals++;
275 }
276}
277
278void OneDim::evalJacobian(span<const double> x0)
279{
280 m_jac->reset();
281 clock_t t0 = clock();
282 m_work1.resize(size());
283 m_work2.resize(size());
284 eval(npos, x0, m_work1, 0.0, 0);
285 vector<double> perturbed(x0.begin(), x0.end());
286 size_t ipt = 0;
287 for (size_t j = 0; j < points(); j++) {
288 size_t nv = nVars(j);
289 for (size_t n = 0; n < nv; n++) {
290 // perturb x(n); preserve sign(x(n))
291 double xsave = x0[ipt];
292 double dx = fabs(xsave) * m_jacobianRelPerturb + m_jacobianAbsPerturb;
293 if (xsave < 0) {
294 dx = -dx;
295 }
296 perturbed[ipt] = xsave + dx;
297 double rdx = 1.0 / (perturbed[ipt] - xsave);
298
299 // calculate perturbed residual
300 eval(j, perturbed, m_work2, 0.0, 0);
301
302 // compute nth column of Jacobian
303 for (size_t i = j - 1; i != j+2; i++) {
304 if (i != npos && i < points()) {
305 size_t mv = nVars(i);
306 size_t iloc = loc(i);
307 for (size_t m = 0; m < mv; m++) {
308 double delta = m_work2[m+iloc] - m_work1[m+iloc];
309 if (std::abs(delta) > m_jacobianThreshold || m+iloc == ipt) {
310 m_jac->setValue(m + iloc, ipt, delta * rdx);
311 }
312 }
313 }
314 }
315 perturbed[ipt] = xsave;
316 ipt++;
317 }
318 }
319
320 m_jac->updateElapsed(double(clock() - t0) / CLOCKS_PER_SEC);
321 m_jac->incrementEvals();
322 m_jac->setAge(0);
323}
324
325void OneDim::initTimeInteg(double dt, span<const double> x)
326{
328 // iterate over all domains, preparing each one to begin time stepping
329 Domain1D* d = left();
330 while (d) {
331 d->initTimeInteg(dt, x);
332 d = d->right();
333 }
334}
335
337{
338 if (m_rdt == 0) {
339 return;
340 }
342 // iterate over all domains, preparing them for steady-state solution
343 Domain1D* d = left();
344 while (d) {
345 d->setSteadyMode();
346 d = d->right();
347 }
348}
349
351{
352 if (!m_init) {
353 Domain1D* d = left();
354 while (d) {
355 d->init();
356 d = d->right();
357 }
358 }
359 m_init = true;
360}
361
362void OneDim::resetBadValues(span<double> x)
363{
364 for (auto dom : m_dom) {
365 dom->resetBadValues(x);
366 }
367}
368
369}
Base class for exceptions thrown by Cantera classes.
Base class for one-dimensional domains.
Definition Domain1D.h:29
void initTimeInteg(double dt, span< const double > x0)
Performs the setup required before starting a time-stepping solution.
Definition Domain1D.h:277
size_t nComponents() const
Number of components at each grid point.
Definition Domain1D.h:142
double rtol(size_t n)
Relative tolerance of the nth component.
Definition Domain1D.h:216
Domain1D * left() const
Return a pointer to the left neighbor.
Definition Domain1D.h:557
string id() const
Returns the identifying tag for this domain.
Definition Domain1D.h:577
size_t nPoints() const
Number of grid points in this domain.
Definition Domain1D.h:147
double lowerBound(size_t n) const
Lower bound on the nth component.
Definition Domain1D.h:251
double upperBound(size_t n) const
Upper bound on the nth component.
Definition Domain1D.h:246
Domain1D * right() const
Return a pointer to the right neighbor.
Definition Domain1D.h:562
virtual string componentName(size_t n) const
Name of component n. May be overloaded.
Definition Domain1D.cpp:59
virtual void init()
Initialize.
Definition Domain1D.h:120
double atol(size_t n)
Absolute tolerance of the nth component.
Definition Domain1D.h:221
void setSteadyMode()
Set the internally-stored reciprocal of the time step to 0.0, which is used to indicate that the prob...
Definition Domain1D.h:287
virtual size_t loc(size_t j=0) const
Location of the start of the local solution vector in the global solution vector.
Definition Domain1D.h:522
void locate()
Find the index of the first grid point in this domain, and the start of its variables in the global s...
Definition Domain1D.cpp:187
virtual double eval(double t) const
Evaluate the function.
Definition Func1.cpp:28
An array index is out of range.
size_t start(size_t i) const
The index of the start of domain i in the solution vector.
Definition OneDim.h:91
void init()
Initialize all domains.
Definition OneDim.cpp:350
double weightedNorm(span< const double > step) const override
Compute the weighted norm of a step vector.
Definition OneDim.cpp:101
void resize() override
Call to set the size of internal data structures after first defining the system or if the problem si...
Definition OneDim.cpp:177
string componentName(size_t i) const override
Get the name of the i-th component of the state vector.
Definition OneDim.cpp:48
void saveStats()
Save statistics on function and Jacobian evaluation, and reset the counters.
Definition OneDim.cpp:146
pair< string, string > componentTableHeader() const override
Get header lines describing the column names included in a component label.
Definition OneDim.cpp:53
void initTimeInteg(double dt, span< const double > x) override
Prepare for time stepping beginning with solution x and timestep dt.
Definition OneDim.cpp:325
size_t loc(size_t jg)
Location in the solution vector of the first component of global point jg.
Definition OneDim.h:117
double upperBound(size_t i) const override
Get the upper bound for global component i in the state vector.
Definition OneDim.cpp:64
void addDomain(shared_ptr< Domain1D > d)
Add a domain. Domains are added left-to-right.
Definition OneDim.cpp:78
string componentTableLabel(size_t i) const override
Get elements of the component name, aligned with the column headings given by componentTableHeader().
Definition OneDim.cpp:58
size_t nDomains() const
Number of domains.
Definition OneDim.h:60
vector< double > m_jacElapsed
Time [s] spent evaluating Jacobians on this grid.
Definition OneDim.h:284
Domain1D * right()
Pointer to right-most domain (last added).
Definition OneDim.h:107
size_t domainIndex(const string &name) const
Get the index of the domain named name.
Definition OneDim.cpp:29
OneDim()=default
Default constructor.
void setSteadyMode() override
Prepare to solve the steady-state problem.
Definition OneDim.cpp:336
vector< double > m_funcElapsed
Time [s] spent on residual function evaluations on this grid (not counting evaluations used to constr...
Definition OneDim.h:292
vector< shared_ptr< Domain1D > > m_connect
All connector and boundary domains.
Definition OneDim.h:252
vector< std::tuple< size_t, size_t, size_t > > m_componentInfo
Domain, grid point, and component indices for each element of the global state vector.
Definition OneDim.h:270
vector< shared_ptr< Domain1D > > m_bulk
All bulk/flow domains.
Definition OneDim.h:255
vector< int > m_funcEvals
Number of residual function evaluations on this grid (not counting evaluations used to construct Jaco...
Definition OneDim.h:288
vector< size_t > m_loc
Location in the state vector of the first component of each point, across all domains.
Definition OneDim.h:266
double m_evaltime
Total time [s] spent in eval()
Definition OneDim.h:280
size_t nVars(size_t jg)
Number of solution components at global point jg.
Definition OneDim.h:112
void evalJacobian(span< const double > x0) override
Evaluates the Jacobian at x0 using finite differences.
Definition OneDim.cpp:278
std::tuple< string, size_t, string > component(size_t i) const
Return the domain, local point index, and component name for the i-th component of the global solutio...
Definition OneDim.cpp:39
Domain1D * pointDomain(size_t i)
Return a pointer to the domain global point i belongs to.
Definition OneDim.cpp:234
vector< size_t > m_gridpts
Number of grid points in this grid.
Definition OneDim.h:282
size_t points()
Total number of points.
Definition OneDim.h:139
vector< size_t > m_nvars
Number of variables at each point, across all domains.
Definition OneDim.h:262
int m_nevals
Number of calls to eval()
Definition OneDim.h:279
bool m_init
Indicates whether one-time initialization for each domain has been completed.
Definition OneDim.h:258
void writeStats(int printTime=1)
Write statistics about the number of iterations and Jacobians at each grid level.
Definition OneDim.cpp:129
void clearStats()
Clear saved statistics.
Definition OneDim.cpp:164
size_t m_pts
Total number of points.
Definition OneDim.h:273
void resetBadValues(span< double > x) override
Reset values such as negative species concentrations.
Definition OneDim.cpp:362
vector< int > m_jacEvals
Number of Jacobian evaluations on this grid.
Definition OneDim.h:283
vector< int > m_timeSteps
Number of time steps taken in each call to solve() (for example, for each successive grid refinement)
Definition OneDim.h:296
Domain1D & domain(size_t i) const
Return a reference to domain i.
Definition OneDim.h:65
vector< shared_ptr< Domain1D > > m_dom
All domains comprising the system.
Definition OneDim.h:249
Domain1D * left()
Pointer to left-most domain (first added).
Definition OneDim.h:102
double lowerBound(size_t i) const override
Get the lower bound for global component i in the state vector.
Definition OneDim.cpp:71
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:246
int m_nsteps
Number of time steps taken in the current call to solve()
size_t m_size
Solution vector size
virtual void resize()
Call to set the size of internal data structures after first defining the system or if the problem si...
double m_jacobianAbsPerturb
Absolute perturbation of each component in finite difference Jacobian.
size_t size() const
Total solution vector length;.
double rdt() const
Reciprocal of the time step.
virtual void initTimeInteg(double dt, span< const 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.
vector< int > m_mask
Transient mask.
Func1 * m_interrupt
Function called at the start of every call to eval.
size_t m_bw
Jacobian bandwidth.
virtual void setSteadyMode()
Prepare to solve the steady-state problem.
double m_jacobianRelPerturb
Relative perturbation of each component in finite difference Jacobian.
vector< double > m_work1
Work arrays used during Jacobian evaluation.
void writelog(const string &fmt, const Args &... args)
Write a formatted message to the screen.
Definition global.h:171
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< SystemJacobian > newSystemJacobian(const string &type)
Create a SystemJacobian object of the specified type.