chombo-discharge
Loading...
Searching...
No Matches
CD_LookupTable1DImplem.H
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2021-2026 SINTEF Energy Research
3 *
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 */
6
13#ifndef CD_LOOKUPTABLEIMPLEM_H
14#define CD_LOOKUPTABLEIMPLEM_H
15
16// Std includes
17#include <algorithm>
18#include <math.h>
19#include <iomanip>
20#include <fstream>
21#include <limits>
22
23// Our includes
24#include <CD_LookupTable1D.H>
25#include <CD_NamespaceHeader.H>
26
27template <typename T, size_t N, typename I>
29{
30 this->reset();
31}
32
33template <typename T, size_t N, typename I>
34inline void
36{
37 m_isGood = false;
38 m_grid = std::make_tuple(LookupTable::Spacing::Uniform, 0, -1.0, -1.0, -1.0);
39 m_rangeStrategyLo = LookupTable::OutOfRangeStrategy::Constant;
40 m_rangeStrategyHi = LookupTable::OutOfRangeStrategy::Constant;
41
42 m_rawData.clear();
43 m_structuredData.clear();
44}
45
46template <typename T, size_t N, typename I>
47template <typename... Ts>
48inline void
49LookupTable1D<T, N, I>::addData(const Ts&... x) noexcept
51 std::array<T, sizeof...(Ts)> arr = {(T)x...};
52
53 m_rawData.emplace_back(arr);
54}
55
56template <typename T, size_t N, typename I>
57inline void
58LookupTable1D<T, N, I>::addData(const std::array<T, N + 1>& x) noexcept
59{
60 m_rawData.emplace_back(x);
61}
62
63template <typename T, size_t N, typename I>
64inline void
65LookupTable1D<T, N, I>::swap(const size_t a_columnOne, const size_t a_columnTwo) noexcept
66{
67 for (auto& r : m_rawData) {
68 const auto tmp = r[a_columnOne];
69
70 r[a_columnOne] = r[a_columnTwo];
71 r[a_columnTwo] = tmp;
72 }
73
74 for (auto& r : m_structuredData) {
75 const auto tmp = r[a_columnOne];
76
77 r[a_columnOne] = r[a_columnTwo];
78 r[a_columnTwo] = tmp;
79 }
80
81 if (m_isGood) {
82 if (a_columnOne == std::get<4>(m_grid)) {
83 std::get<4>(m_grid) = a_columnOne;
84 }
85 else if (a_columnTwo == std::get<4>(m_grid)) {
86 std::get<4>(m_grid) = a_columnTwo;
87 }
88 }
89}
90
91template <typename T, size_t N, typename I>
92template <size_t K>
93inline void
94LookupTable1D<T, N, I>::scale(const T& a_scale) noexcept
95{
96 for (auto& r : m_rawData) {
97 r[K] *= a_scale;
98 }
99
100 for (auto& r : m_structuredData) {
101 r[K] *= a_scale;
102 }
103
104 if (m_isGood && K == std::get<2>(m_grid)) {
105 std::get<4>(m_grid) *= a_scale;
106 }
107}
108
109template <typename T, size_t N, typename I>
110inline void
111LookupTable1D<T, N, I>::truncate(const T& a_min, const T& a_max, const size_t a_column) noexcept
113 std::vector<std::array<T, N + 1>> truncatedData;
114
115 for (const auto& xy : m_rawData) {
116 if (xy[a_column] >= a_min && xy[a_column] <= a_max) {
117 truncatedData.emplace_back(xy);
118 }
120
121 m_rawData = truncatedData;
122}
123
124template <typename T, size_t N, typename I>
125inline void
127{
128 m_rangeStrategyLo = a_strategy;
129}
130
131template <typename T, size_t N, typename I>
132inline void
134{
135 m_rangeStrategyHi = a_strategy;
136}
138template <typename T, size_t N, typename I>
139inline void
140LookupTable1D<T, N, I>::prepareTable(const size_t& a_independentVariable,
141 const size_t& a_numPoints,
142 const LookupTable::Spacing& a_spacing)
143{
144
145 const std::string baseError = "LookupTable1D<T,N,I>::prepareTable";
146
147 if (a_numPoints <= 1) {
148 throw std::runtime_error(baseError + " - must have 'a_numPoints > 1'");
149 }
150
151 // Sort the raw data along the specified column.
152 using Values = std::array<T, N + 1>;
153 std::vector<Values> sortedData = m_rawData;
154
155 std::sort(sortedData.begin(),
156 sortedData.end(),
157 [i = a_independentVariable](const Values& X1, const Values& X2) -> bool {
158 return X1[i] < X2[i];
159 });
160
161 // Set up the 1D grid
162 T xmin;
163 T xmax;
164 T delta;
165
166 xmin = sortedData.front()[a_independentVariable];
167 xmax = sortedData.back()[a_independentVariable];
168
169 std::vector<T> coords(a_numPoints);
170
171 switch (a_spacing) {
172 case LookupTable::Spacing::Uniform: {
173 delta = (xmax - xmin) / (a_numPoints - 1);
174
175 for (size_t i = 0; i < a_numPoints; i++) {
176 coords[i] = xmin + i * delta;
177 }
178
179 break;
181 case LookupTable::Spacing::Exponential: {
182 if (xmin <= std::numeric_limits<T>::min()) {
183 throw std::runtime_error(baseError + " - but must have all 'x > 0.0' for logarithmic grid");
184 }
185
186 else {
187 delta = log10(xmax / xmin) / (a_numPoints - 1);
188
189 for (int i = 0; i < a_numPoints; i++) {
190 coords[i] = xmin * std::pow(10.0, i * delta);
191 }
192
193 break;
195 }
196 default: {
197 throw std::runtime_error(baseError + " - logic bust (unsupported table spacing system)");
198
199 break;
200 }
202
203 m_structuredData.clear();
204
205 size_t curRow = 0;
206
207 for (const auto& x : coords) {
208 while (curRow < m_rawData.size() - 1) {
209 const auto& row1 = m_rawData[curRow];
210 const auto& row2 = m_rawData[curRow + 1];
211
212 const auto x1 = row1[a_independentVariable];
213 const auto x2 = row2[a_independentVariable];
214
215 if (x >= x1 && x <= x2) {
216 const auto t = (x - x1) / (x2 - x1);
217
218 std::array<T, N + 1> interpRow;
219
220 for (size_t i = 0; i <= N; i++) {
221 interpRow[i] = row1[i] + t * (row2[i] - row1[i]);
222 }
223
224 m_structuredData.emplace_back(interpRow);
225
226 break;
227 }
228
229 curRow++;
230 }
231 }
232
233 m_grid = std::make_tuple(a_spacing, a_independentVariable, xmin, xmax, delta);
234
235 m_isGood = true;
236}
237
238template <typename T, size_t N, typename I>
239inline std::vector<std::array<T, N + 1>>&
241{
242 return (m_rawData);
243}
244
245template <typename T, size_t N, typename I>
246inline std::vector<std::array<T, N + 1>>&
249 return (m_structuredData);
250}
251
252template <typename T, size_t N, typename I>
253inline const std::vector<std::array<T, N + 1>>&
255{
256 return (m_rawData);
257}
258
259template <typename T, size_t N, typename I>
260inline const std::vector<std::array<T, N + 1>>&
262{
263 return (m_structuredData);
264}
265
266template <typename T, size_t N, typename I>
267inline void
268LookupTable1D<T, N, I>::writeRawData(const std::string& a_file) const noexcept
269{
270 this->writeToFile(a_file, m_rawData);
271}
272
273template <typename T, size_t N, typename I>
274inline void
275LookupTable1D<T, N, I>::writeStructuredData(const std::string& a_file) const noexcept
276{
277 this->writeToFile(a_file, m_structuredData);
278}
279
280template <typename T, size_t N, typename I>
281inline void
282LookupTable1D<T, N, I>::outputRawData(std::ostream& a_ostream) const noexcept
283{
284 this->outputData(a_ostream, m_rawData);
285}
286
287template <typename T, size_t N, typename I>
288inline void
289LookupTable1D<T, N, I>::outputStructuredData(std::ostream& a_ostream) const noexcept
290{
291 this->outputData(a_ostream, m_structuredData);
292}
293
294template <typename T, size_t N, typename I>
295inline void
297 const std::vector<std::array<T, N + 1>>& a_data) const noexcept
298{
299 for (const auto& r : a_data) {
300 for (const auto& c : r) {
301 a_ostream << std::left << std::setw(14) << c;
302 }
303 a_ostream << "\n";
304 }
305}
306
307template <typename T, size_t N, typename I>
308inline void
309LookupTable1D<T, N, I>::writeToFile(const std::string& a_file,
310 const std::vector<std::array<T, N + 1>>& a_data) const noexcept
311{
312
313#ifdef CH_MPI
314 if (procID() == 0) {
315#endif
316 std::ofstream file;
317
318 file.open(a_file);
319 this->outputData(file, a_data);
320 file.close();
321#ifdef CH_MPI
322 }
323#endif
324}
325
326template <typename T, size_t N, typename I>
327inline size_t
329{
330 const LookupTable::Spacing& spacing = std::get<0>(m_grid);
331 const T& x0 = std::get<2>(m_grid);
332 const T& delta = std::get<4>(m_grid);
333
334 const size_t numPoints = m_structuredData.size();
335
336 if (numPoints < 2) {
337 throw std::runtime_error("LookupTable1D<T,N,I>::getIndexLo - table must hold at least two points");
338 }
339
340 // Signed on purpose: the floor() below can land a hair below zero for a_x at the very low edge, and
341 // narrowing that straight to size_t would wrap it to an enormous index rather than clamping it.
342 long long idxLo;
343
344 switch (spacing) {
345 case LookupTable::Spacing::Uniform: {
346 idxLo = static_cast<long long>(std::floor((a_x - x0) / delta));
347
348 break;
349 }
350 case LookupTable::Spacing::Exponential: {
351 idxLo = static_cast<long long>(std::floor(log10(a_x / x0) / delta));
352
353 break;
354 }
355 default: {
356 throw std::runtime_error("LookupTable1D<T,N,I>::getIndexLo - logic bust (unsupported table spacing system)");
357 }
358 }
359
360 // The caller reads BOTH idxLo and idxLo + 1, so idxLo has to be the low end of a real interval. At
361 // a_x == xmax it is not: the grid is built so that (xmax - x0)/delta and log10(xmax/x0)/delta are
362 // both exactly numPoints - 1, which puts the upper neighbour one past the end of m_structuredData.
363 // Whether the division lands exactly on numPoints - 1 or a hair below is round-off, so the resulting
364 // out-of-bounds read fired for some grids and not others -- e.g. 4 points over one decade, but not
365 // 50 points over three. Clamping to the last interval is correct in both directions: linear
366 // interpolation there returns the endpoint value exactly at xmax, and the lower clamp absorbs a
367 // -0.0 at xmin.
368 return static_cast<size_t>(std::min(std::max(idxLo, 0LL), static_cast<long long>(numPoints) - 2));
369}
370
371template <typename T, size_t N, typename I>
372inline std::array<T, N + 1>
374{
375 if (!m_isGood) {
376 throw std::runtime_error("LookupTable1D<T, N, I>::interpolate(array) but need to call 'prepareTable first'");
377 }
378
379 const size_t& indVar = std::get<1>(m_grid);
380 const T& xmin = std::get<2>(m_grid);
381 const T& xmax = std::get<3>(m_grid);
382
383 std::array<T, N + 1> ret;
384
385 if (a_x < xmin) {
386 switch (m_rangeStrategyLo) {
387 case LookupTable::OutOfRangeStrategy::Constant: {
388 ret = m_structuredData.front();
389
390 break;
391 }
392 case LookupTable::OutOfRangeStrategy::Interpolate: {
393 const T diffDx = m_structuredData[1][indVar] - m_structuredData[0][indVar];
394 const T extrapDx = m_structuredData[0][indVar] - a_x;
395
396 // Scale by the ratio rather than dividing per column: diffDx does not depend on the column, but the
397 // division did, so an N-column table paid N divisions where one is enough. This is the hot path of
398 // every mobility, diffusion coefficient and reaction rate evaluated from a table -- once per species
399 // per grid cell -- and the compiler cannot hoist the reciprocal itself without -freciprocal-math.
400 const T frac = extrapDx / diffDx;
401
402 ret = m_structuredData.front();
403
404 for (size_t i = 0; i < N + 1; i++) {
405 ret[i] -= (m_structuredData[1][i] - m_structuredData[0][i]) * frac;
406 }
407
408 break;
409 }
410 default: {
411 throw std::runtime_error("LookupTable1D<T, N, I>::interpolate(array) unsupported range strategy at low end");
412
413 break;
414 }
415 }
416 }
417 else if (a_x > xmax) {
418 switch (m_rangeStrategyHi) {
419 case LookupTable::OutOfRangeStrategy::Constant: {
420 ret = m_structuredData.back();
421
422 break;
423 }
424 case LookupTable::OutOfRangeStrategy::Interpolate: {
425 const size_t& size = m_structuredData.size();
426
427 const T diffDx = m_structuredData[size - 1][indVar] - m_structuredData[size - 2][indVar];
428 const T extrapDx = a_x - m_structuredData[size - 1][indVar];
429
430 // One division for the whole row -- see the low-end branch above.
431 const T frac = extrapDx / diffDx;
432
433 ret = m_structuredData.back();
434
435 for (size_t i = 0; i < N + 1; i++) {
436 ret[i] += (m_structuredData[size - 1][i] - m_structuredData[size - 2][i]) * frac;
437 }
438
439 break;
440 }
441 default: {
442 throw std::runtime_error("LookupTable1D<T, N, I>::interpolate(array) unsupported range strategy at low end");
443
444 break;
445 }
446 }
447 }
448 else {
449 const size_t idx = this->getIndexLo(a_x);
450
451 const T diffDx = m_structuredData[idx + 1][indVar] - m_structuredData[idx][indVar];
452 const T interpDx = a_x - m_structuredData[idx][indVar];
453
454 // One division for the whole row -- see the low-end branch above.
455 const T frac = interpDx / diffDx;
456
457 ret = m_structuredData[idx];
458
459 for (size_t i = 0; i < N + 1; i++) {
460 ret[i] += (m_structuredData[idx + 1][i] - m_structuredData[idx][i]) * frac;
461 }
462 }
463
464 return ret;
465}
466
467template <typename T, size_t N, typename I>
468template <size_t K>
469inline T
471{
472 return std::get<K>(this->interpolate(a_x));
473}
474
475template <typename T, size_t N, typename I>
476template <size_t M, typename... Ts>
478LookupTable1D<T, N, I>::slice(const Ts&... a_columns) const noexcept
479{
480 static_assert(M <= N, "LookupTable1D<T, N,I>::slice must have have 'M <= N'");
481
482 std::array<size_t, sizeof...(Ts)> arr = {(size_t)a_columns...};
483
485
486 for (const auto& r : m_rawData) {
487 std::array<T, M + 1> slicedData;
488
489 for (size_t i = 0; i < M + 1; i++) {
490 slicedData[i] = r[arr[i]];
491 }
492
493 ret.addData(slicedData);
494 }
495
496 return ret;
497}
498
499#include <CD_NamespaceFooter.H>
500
501#endif
Declaration of a lookup table in one independent variable.
OutOfRangeStrategy
Strategy for obtaining data when requesting data that is out of range. We can use either constant (i....
Definition CD_LookupTable.H:33
Spacing
Enum for classifying the coordinate system.
Definition CD_LookupTable.H:42
Class for interpolation of f = f(x) data in one independent variable x.
Definition CD_LookupTable1D.H:32
std::vector< std::array< T, N+1 > > & getStructuredData() noexcept
Access function for structured data.
Definition CD_LookupTable1DImplem.H:247
T interpolate(const T &a_x) const
Interpolation function for specific dependent variable K.
Definition CD_LookupTable1DImplem.H:470
void addData(const Ts &... x) noexcept
Add entry.
Definition CD_LookupTable1DImplem.H:49
void swap(size_t a_columnOne, size_t a_columnTwo) noexcept
Utility function for swapping columns.
Definition CD_LookupTable1DImplem.H:65
void setRangeStrategyLo(const LookupTable::OutOfRangeStrategy &a_strategy) noexcept
Set the out-of-range strategy on the low end.
Definition CD_LookupTable1DImplem.H:126
void truncate(const T &a_min, const T &a_max, size_t a_column) noexcept
Utility function for truncating raw data along one of the variables (either dependent or independent)...
Definition CD_LookupTable1DImplem.H:111
size_t getIndexLo(const T &a_x) const
Get the lower index that brackets the input variable between two data points in the structured grid.
Definition CD_LookupTable1DImplem.H:328
void setRangeStrategyHi(const LookupTable::OutOfRangeStrategy &a_strategy) noexcept
Set the out-of-range strategy on the high end.
Definition CD_LookupTable1DImplem.H:133
LookupTable1D() noexcept
Default constructor. Creates a table without any entries.
Definition CD_LookupTable1DImplem.H:28
void writeRawData(const std::string &a_file) const noexcept
Dump raw table data to file.
Definition CD_LookupTable1DImplem.H:268
void outputStructuredData(std::ostream &a_ostream=std::cout) const noexcept
Dump structured table data to file.
Definition CD_LookupTable1DImplem.H:289
void reset() noexcept
Reset everything.
Definition CD_LookupTable1DImplem.H:35
void outputRawData(std::ostream &a_ostream=std::cout) const noexcept
Dump raw table data to output stream.
Definition CD_LookupTable1DImplem.H:282
void prepareTable(const size_t &a_independentVariable, const size_t &a_numPoints, const LookupTable::Spacing &a_spacing)
Turn the raw data into uniform data for fast lookup.
Definition CD_LookupTable1DImplem.H:140
void scale(const T &a_scale) noexcept
Utility function which scales one of the columns (either dependent or independent variable)
Definition CD_LookupTable1DImplem.H:94
void writeToFile(const std::string &a_file, const std::vector< std::array< T, N+1 > > &a_data) const noexcept
Utility function for outputting data to a file.
Definition CD_LookupTable1DImplem.H:309
void writeStructuredData(const std::string &a_file) const noexcept
Dump structured table data to file.
Definition CD_LookupTable1DImplem.H:275
LookupTable1D< T, M, I > slice(const Ts &... a_columns) const noexcept
Slice this table, keeping only the user-specified columns.
Definition CD_LookupTable1DImplem.H:478
void outputData(std::ostream &a_ostream, const std::vector< std::array< T, N+1 > > &a_data) const noexcept
Utility function for outputting data.
Definition CD_LookupTable1DImplem.H:296
std::vector< std::array< T, N+1 > > & getRawData() noexcept
Access function for raw data.
Definition CD_LookupTable1DImplem.H:240