Nektar++
Loading...
Searching...
No Matches
TestTimeOps.hpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: TestTimeOps.hpp
4//
5// For more information, please see: http://www.nektar.info
6//
7// The MIT License
8//
9// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
10// Department of Aeronautics, Imperial College London (UK), and Scientific
11// Computing and Imaging Institute, University of Utah (USA).
12//
13// Permission is hereby granted, free of charge, to any person obtaining a
14// copy of this software and associated documentation files (the "Software"),
15// to deal in the Software without restriction, including without limitation
16// the rights to use, copy, modify, merge, publish, distribute, sublicense,
17// and/or sell copies of the Software, and to permit persons to whom the
18// Software is furnished to do so, subject to the following conditions:
19//
20// The above copyright notice and this permission notice shall be included
21// in all copies or substantial portions of the Software.
22//
23// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
26// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
29// DEALINGS IN THE SOFTWARE.
30//
31// Description: Test fixture for the time-integration schemes, driven through
32// the SolverCore TimeOp interface.
33//
34///////////////////////////////////////////////////////////////////////////////
35
36#pragma once
37
38#include <SolverCore/TimeOps/TimeOp.hpp>
39
45
48
49#include <cmath>
50#include <cstdlib>
51#include <cstring>
52#include <iostream>
53#include <string>
54#include <vector>
55
56using namespace Nektar;
57using namespace Nektar::LibUtilities;
58using namespace Nektar::MultiRegions;
59using namespace Nektar::SolverCore;
60
62
63/**
64 * @class TestTimeOps
65 *
66 * A test fixture that integrates the scalar test problem
67 * du/dt = (alpha + beta) u in time, alpha being the non-stiff factor carried
68 * by the explicit part of a scheme and beta the stiff factor carried by the
69 * implicit part. The exact solution u = e^((alpha + beta) t) with u(t=0) = 1
70 * gives the reference the observed order of accuracy is measured against.
71 *
72 * The fixture constructor (destructor) is called before (after) each call to
73 * the BOOST_FIXTURE_TEST_CASE(<test name>, <fixture>) macro.
74 *
75 * See "Single test case fixture" on the Boost.Test documentation for more
76 * details:
77 * https://www.boost.org/doc/libs/1_82_0/libs/test/doc/html/boost_test/tests_organization/fixtures/case.html
78 */
79template <typename TData> class TestTimeOps
80{
81public:
82 TestTimeOps() = default;
83 ~TestTimeOps() = default;
84
85 /**
86 * @brief Read the session, build the expansion list and allocate the
87 * fields the test cases work on.
88 */
89 void Configure()
90 {
91 SetSession();
92 SetExpList();
93 SetFixture();
94 }
95
96 /**
97 * @brief Set the initial condition and the analytic solution it is
98 * expected to reach at the final time.
99 *
100 * @param alpha non-stiff factor, integrated by the explicit part
101 * @param beta stiff factor, integrated by the implicit part
102 */
103 void SetTestCase(const TData alpha, const TData beta)
104 {
105 // Initialise math kernel
106 std::string execName = Operator<TData>::GetOpExecSpace(m_session);
107 m_math = Math::MathHelper(execName);
108
109 // Set initial value, laid out as ToVector() returns it so that
110 // CopyVector() interleaves it and leaves the padding zero.
111 std::vector<TData> in;
112 for (unsigned int nc = 0; nc < m_in.GetNumComponents(); ++nc)
113 {
114 for (auto &block : m_in.GetBlocks())
115 {
116 for (size_t el = 0; el < block.GetNumElements(); ++el)
117 {
118 for (unsigned int phys = 0; phys < block.GetNumData();
119 ++phys)
120 {
121 in.push_back(1.0 + phys);
122 }
123 }
124 }
125 }
126 m_in.template CopyVector<NektarSpaces::HostSpace>(in);
127
128 // Parameters for analytic solution
129 m_alpha = alpha; // non-stiff factor
130 m_beta = beta; // stiff factor
131
132 const double final_time = 0.5;
133
134 // Compute expected solution
135 ExpectedSolution(final_time);
136 }
137
138 /**
139 * @brief Integrate the test problem for @p numsteps steps of the scheme
140 * given, leaving the result in the output field.
141 */
142 void RunTestCase(const std::string scheme, const std::string variant,
143 const unsigned int order,
144 const std::vector<TData> freeParams,
145 const unsigned int numsteps)
146 {
147 // Copy m_in to m_out since operator uses apply with inout type
148 m_out.template Copy<NektarSpaces::HostSpace>(m_in);
149
150 // Initialise Time-stepping operator
151 auto op = TimeOp<TData>::Create(m_expList, m_session->GetVariables(),
152 scheme, order, variant, freeParams);
153 op->DefineExplicitRhs(&TestTimeOps::DoExplicitRHS, this);
154 op->DefineImplicitRhs(&TestTimeOps::DoImplicitRHS, this);
155 op->DefineImplicit(&TestTimeOps::DoLHS, this);
156 op->DefineProjection(&TestTimeOps::DoProjection, this);
157
158 // Initialise timestepping operator
159 // Loop all steps
160 while (op->GetStep() < numsteps)
161 {
162 // Evolve PDE for one timestep
163 op->Apply(m_out);
164 }
165 }
166
167 /**
168 * @brief Fill the expected field with the analytic solution at
169 * @p final_time.
170 */
171 void ExpectedSolution(const double final_time)
172 {
173 // We solve the analytic problem du/dt = \alpha u + \beta u,
174 // where \alpha is mild parameter leading to the explicit part
175 // and \beta is a stiff parameter leading to the implicit part.
176 // The solution is u = e^((\alpha + \beta)*t) and u(t=0) = 1.0
177 m_expected.template Copy<NektarSpaces::HostSpace>(m_in);
178 m_math.mul(exp((m_alpha + m_beta) * final_time), m_expected,
179 m_expected);
180 }
181
182 /**
183 * @brief Integrate the test problem over a sequence of timesteps and
184 * check the order the error converges at against the order claimed by
185 * the scheme.
186 */
187 bool CheckOrderOfAccuracy(const std::string scheme,
188 const std::string variant,
189 const unsigned int order,
190 const std::vector<TData> freeParams = {})
191 {
192 // The timestep ladder is test configuration, not field data: keeping
193 // it double makes final_time/dt land exactly on an integer step count
194 // whatever TData is. At float, 0.5f/0.001f is 499.99997, which
195 // truncates to 499 and stops the integration a step short.
196 const double final_time = 0.5;
197
198 std::vector<double> timesteps;
199
200 if (order <= 2)
201 {
202 timesteps = {0.1, 0.05, 0.025, 0.01, 0.005, 0.001, 0.0005};
203 }
204 else if (order <= 3)
205 {
206 timesteps = {0.1, 0.05, 0.025, 0.01, 0.005, 0.001};
207 }
208 else if (order == 4)
209 {
210 timesteps = {0.1, 0.05, 0.02, 0.01, 0.005};
211 }
212 else if (order == 5)
213 {
214 if (scheme == "ImplicitSDC" || scheme == "IMEXSDC" ||
215 scheme == "ImplicitGEM" || scheme == "IMEXGEM")
216 {
217 timesteps = {0.1, 0.05, 0.02, 0.01, 0.005};
218 }
219 else
220 {
221 timesteps = {0.2, 0.1, 0.05, 0.025};
222 }
223 }
224 else
225 {
226 if (scheme == "IMEXSDC")
227 {
228 timesteps = {0.1, 0.05, 0.02, 0.01, 0.005};
229 }
230 else
231 {
232 timesteps = {0.4, 0.2, 0.1};
233 }
234 }
235
236 std::vector<TData> errors;
237
238 for (double dt : timesteps)
239 {
240 // Change timestep in m_session to propagate to TimeOp at runtime
241 m_session->SetParameter("TimeStep", dt);
242
243 // Run simulation
244 RunTestCase(scheme, variant, order, freeParams, final_time / dt);
245
246 // Compute error at final time (L2 norm; adapt as needed)
248 TData error = std::sqrt(m_math.l2norm(m_out) / m_math.l2norm(m_in));
249 errors.push_back(error);
250 }
251
252 // Compute observed order of accuracy from (dt, error) pairs
253 std::vector<TData> orders;
254 for (size_t i = 0; i < timesteps.size() - 1; ++i)
255 {
256 TData order = log(errors[i] / errors[i + 1]) /
257 log(timesteps[i] / timesteps[i + 1]);
258 orders.push_back(order);
259 }
260
261 // Use last observed order
262 TData observedOrder = orders.back();
263
264 // Check if observed order is close to expected order (within tolerance)
265 if (std::isnan(observedOrder) || std::isinf(observedOrder) ||
266 observedOrder < 0.9 * order) // Choose tolerance
267 {
268 std::cerr << "Order of accuracy test failed! Observed: "
269 << observedOrder << ", Expected: " << order << std::endl;
270 return false;
271 }
272 else
273 {
274 std::cout << "Order of accuracy verified: " << observedOrder
275 << std::endl;
276 return true;
277 }
278 }
279
280protected:
281 std::string m_meshName = "";
282 TData m_alpha = 0;
283 TData m_beta = 0;
284
286
292
293 /**
294 * @brief Create the session from the mesh named by the derived fixture and
295 * the execution space given on the command line.
296 */
298 {
299 std::string execStr(GlobalConfiguration::ExecStr());
300
301 BOOST_TEST_MESSAGE("Creating input and output fields");
302
303 // Construct a fake command-line argument array to be fed to
304 // Session::Reader::CreateInstance. The first element stands for
305 // the name of the executable which, in our case, doesn't matter.
306 int argc = 3;
307 char **argv = new char *[argc];
308 argv[0] = strdup("exe_name");
309 argv[1] = strdup(m_meshName.data());
310 argv[2] = strdup(("--opExecSpace=" + execStr).c_str());
311
313
314 for (int i = 0; i < argc; ++i)
315 {
316 free(argv[i]);
317 }
318 delete[] argv;
319 }
320
328
330 {
331 const unsigned int ncomp = m_session->GetVariables().size();
332 auto blockAttr = GetBlockAttributes<TData, FieldState::Phys>(m_expList);
333
334 m_in = Field<TData, FieldState::Phys>("f_in", blockAttr, ncomp, 1);
335 m_out = Field<TData, FieldState::Phys>("f_out", blockAttr, ncomp, 1);
336 m_expected =
337 Field<TData, FieldState::Phys>("f_expected", blockAttr, ncomp, 1);
338 }
339
340 /**
341 * @brief Implicit solve of the stiff part of the test problem.
342 */
345 [[maybe_unused]] const TData &time, const TData &lambda)
346 {
347 // Factor for implicit/stiff part of analytic test problem
348 auto factor = 1.0 / (1.0 - lambda * m_beta);
349
350 // Multiply extrapolated rhs
351 m_math.mul(factor, in, out);
352 }
353
354 /**
355 * @brief Right-hand side of the non-stiff part of the test problem.
356 */
359 [[maybe_unused]] const TData &time, const TData &factor)
360 {
361 // Multiply solution by factor
362 m_math.mul(m_alpha * factor, in, out);
363 }
364
365 /**
366 * @brief Right-hand side of the stiff part of the test problem.
367 */
370 [[maybe_unused]] const TData &time, const TData &factor)
371 {
372 // Multiply solution by factor
373 m_math.mul(m_beta * factor, in, out);
374 }
375
376 /**
377 * @brief Projection between timesteps, the identity for this test problem.
378 */
381 [[maybe_unused]] const TData &time)
382 {
383 // Multiply solution by factor
384 m_math.mul(1.0, in, out);
385 }
386};
387
388// clang-format off
389#if defined(NEKTAR_ENABLE_SINGLE_PRECISION)
390#define TESTFLOAT(type, filename) \
391 class type##float : public TestTimeOps<float> \
392 { \
393 public: \
394 type##float() \
395 { \
396 m_meshName = filename; \
397 } \
398 };
399#else
400#define TESTFLOAT(type, filename)
401#endif
402#if defined(NEKTAR_ENABLE_DOUBLE_PRECISION)
403#define TESTDOUBLE(type, filename) \
404 class type : public TestTimeOps<double> \
405 { \
406 public: \
407 type() \
408 { \
409 m_meshName = filename; \
410 } \
411 };
412#else
413#define TESTDOUBLE(type, filename)
414#endif
415#define TEST(type, filename) \
416 TESTFLOAT(type, filename) \
417 TESTDOUBLE(type, filename)
418// clang-format on
419
420TEST(segment, "run/segment.xml")
421
422#include <UnitTests/TestBoostTeardown.hpp>
SpatialDomains::MeshGraphSharedPtr graph
#define NEKTAR_TEST_GLOBAL_CONFIGURATION(args)
#define TEST(type, filename)
SpatialDomains::Geometry * el
A Field represents expansion data to be operated on.
std::vector< BlockAccessor< TData, TState > > & GetBlocks()
Get BlockAccessors for the field.
unsigned int GetNumComponents() const
Gets the number of components for a vector field.
static SessionReaderSharedPtr CreateInstance(int argc, char *argv[])
Creates an instance of the SessionReader class.
LIB_MATH_EXPORT T::value_type l2norm(T &, const std::string &execSpace="")
LIB_MATH_EXPORT void sub(T &x, T &y, T &z, const std::string &execSpace="")
LIB_MATH_EXPORT void mul(const typename T::value_type alpha, T &x, T &y, const std::string &execSpace="")
static std::shared_ptr< DataType > AllocateSharedPtr(const Args &...args)
Allocate a shared pointer from the memory pool.
static std::string GetOpExecSpace(std::shared_ptr< LibUtilities::SessionReader > session, const bool warn=true)
Return the execution space name ("opExecSpace") for an operator.
Definition Operator.hpp:190
static MeshGraphSharedPtr Read(const LibUtilities::SessionReaderSharedPtr pSession, LibUtilities::DomainRangeShPtr rng=LibUtilities::NullDomainRangeShPtr, bool fillGraph=true, SpatialDomains::MeshGraphSharedPtr partitionedGraph=nullptr)
SessionReaderSharedPtr m_session
void DoExplicitRHS(Field< TData, FieldState::Phys > &in, Field< TData, FieldState::Phys > &out, const TData &time, const TData &factor)
Right-hand side of the non-stiff part of the test problem.
Math::MathHelper m_math
Field< TData, FieldState::Phys > m_expected
Field< TData, FieldState::Phys > m_in
void DoImplicitRHS(Field< TData, FieldState::Phys > &in, Field< TData, FieldState::Phys > &out, const TData &time, const TData &factor)
Right-hand side of the stiff part of the test problem.
ExpListSharedPtr m_expList
void RunTestCase(const std::string scheme, const std::string variant, const unsigned int order, const std::vector< TData > freeParams, const unsigned int numsteps)
Integrate the test problem for numsteps steps of the scheme given, leaving the result in the output f...
void DoProjection(Field< TData, FieldState::Phys > &in, Field< TData, FieldState::Phys > &out, const TData &time)
Projection between timesteps, the identity for this test problem.
~TestTimeOps()=default
Field< TData, FieldState::Phys > m_out
void Configure()
Read the session, build the expansion list and allocate the fields the test cases work on.
void SetExpList()
void SetSession()
Create the session from the mesh named by the derived fixture and the execution space given on the co...
void SetTestCase(const TData alpha, const TData beta)
Set the initial condition and the analytic solution it is expected to reach at the final time.
void SetFixture()
bool CheckOrderOfAccuracy(const std::string scheme, const std::string variant, const unsigned int order, const std::vector< TData > freeParams={})
Integrate the test problem over a sequence of timesteps and check the order the error converges at ag...
void DoLHS(Field< TData, FieldState::Phys > &in, Field< TData, FieldState::Phys > &out, const TData &time, const TData &lambda)
Implicit solve of the stiff part of the test problem.
TestTimeOps()=default
void ExpectedSolution(const double final_time)
Fill the expected field with the analytic solution at final_time.
std::string m_meshName
std::shared_ptr< SessionReader > SessionReaderSharedPtr
@ beta
Gauss Radau pinned at x=-1,.
Definition PointsType.h:59
std::shared_ptr< ExpList > ExpListSharedPtr
Shared pointer to an ExpList object.
@ Exec
exe – ExecName
scalarT< T > log(scalarT< T > in)
Definition scalar.hpp:309