Nektar++
Loading...
Searching...
No Matches
TestMaxStdVelocity.hpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: TestMaxStdVelocity.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: Fixture for the MaxStdVelocity operator. Self contained: it
32// owns its session, expansion list and input field, and takes the expected
33// value from the legacy per-element formula as an independent oracle.
34//
35///////////////////////////////////////////////////////////////////////////////
36
37#pragma once
38
39#include <SolverCore/CFL/MaxStdVelocity/MaxStdVelocityOp.hpp>
40
47
50
51#include <algorithm>
52#include <cmath>
53#include <cstdlib>
54#include <cstring>
55#include <iostream>
56#include <string>
57
58using namespace Nektar;
59using namespace Nektar::LibUtilities;
60using namespace Nektar::MultiRegions;
61using namespace Nektar::SolverCore;
62
64
65/**
66 * @class TestMaxStdVelocity
67 *
68 * @brief Compares MaxStdVelocityOp against the legacy formula.
69 *
70 * The expected value is computed here from the legacy expansion interface -
71 * GetGeomFactors()->GetDerivFactors() element by element - rather than from
72 * the packed factors the operator reads out of the data warehouse. The two
73 * reach the same numbers by different routes, so the comparison checks the
74 * packing and its indexing, the deformed and regular layouts, the exclusion
75 * of padded elements and the per block order weighting, on every mesh the
76 * fixture offers.
77 *
78 * The field carries one velocity component per coordinate direction followed
79 * by a wave speed, and the operator is asked for both weightings: zero, the
80 * incompressible and scalar advection case, and one, where the wave speed
81 * contributes as a sound speed does.
82 *
83 * The fixture constructor (destructor) is called before (after) each call to
84 * the BOOST_FIXTURE_TEST_CASE(<test name>, <fixture>) macro.
85 *
86 * See "Single test case fixture" on the Boost.Test documentation for more
87 * details:
88 * https://www.boost.org/doc/libs/1_82_0/libs/test/doc/html/boost_test/tests_organization/fixtures/case.html
89 */
90template <typename TData> class TestMaxStdVelocity
91{
92public:
93 TestMaxStdVelocity() = default;
95
96 /**
97 * @brief Read the session, build the expansion list and allocate the
98 * field the test cases work on.
99 */
101 {
102 SetSession();
103 SetExpList();
104 m_expList->SetDataWarehouse();
105 SetFixture();
106 }
107
108 /**
109 * @brief Fill the velocity components and the wave speed, and record the
110 * value the operator is expected to return.
111 */
113 {
114 const auto nphys = m_expList->GetTotPoints();
115 const auto coordim = m_expList->GetCoordim(0);
116
117 Array<OneD, double> x(nphys);
118 Array<OneD, double> y(nphys, 0.0);
119 Array<OneD, double> z(nphys, 0.0);
120 m_expList->GetCoords(x, y, z);
121
122 // A velocity that varies over the mesh, so the maximum is not
123 // attained everywhere and a mistake in which point or element is
124 // examined shows up. The wave speed is kept strictly positive, as a
125 // physical sound speed is.
126 for (unsigned int blk = 0; blk < m_in.GetBlocks().size(); ++blk)
127 {
128 auto &inblock = m_in.GetBlocks()[blk];
129 auto inptr =
130 inblock.template GetPtr<NektarSpaces::HostSpace, WriteOnly>();
131
132 for (unsigned int n = 0; n < m_in.GetNumComponents(); ++n)
133 {
134 for (size_t el = 0, cnt = 0; el < inblock.GetNumElements();
135 ++el)
136 {
137 for (unsigned int phys = 0; phys < inblock.GetNumData();
138 ++phys, ++cnt)
139 {
140 const auto xc = static_cast<TData>(x[cnt]);
141 const auto yc = static_cast<TData>(y[cnt]);
142 const auto zc = static_cast<TData>(z[cnt]);
143
144 if (n < coordim)
145 {
146 inptr[cnt] = static_cast<TData>(0.7 + 0.3 * n) +
147 static_cast<TData>(0.4) * xc -
148 static_cast<TData>(0.2) * yc +
149 static_cast<TData>(0.1) * zc * zc;
150 }
151 else
152 {
153 inptr[cnt] = static_cast<TData>(1.3) +
154 static_cast<TData>(0.2) * xc * xc +
155 static_cast<TData>(0.05) * yc;
156 }
157 }
158 }
159 inptr += inblock.CompSize();
160 }
161 }
162
163 // Compute expected solution.
165 }
166
167 /**
168 * @brief Apply the operator with and without the wave speed, once on the
169 * non-interleaved storage reduced to every rank and once on the
170 * interleaved storage reduced to rank zero alone.
171 */
173 {
174 auto op = MaxStdVelocityOp<TData>::Create(m_expList,
175 m_session->GetVariables());
176
177 // Non-interleaved case.
178 op->SetSoundSpeedFactor(TData(0));
179 m_testNoSound = op->Apply(m_in);
180
181 op->SetSoundSpeedFactor(TData(1));
182 m_testWithSound = op->Apply(m_in);
183
184 // Interleaved case.
185 std::string execStr = Operator<TData>::GetOpExecSpace(m_session);
186 m_in.ReshapeStorage(NektarSpaces::GetVectorWidth<TData>(execStr),
187 execStr);
188
189 op->SetRootOnly(true);
190 op->SetSoundSpeedFactor(TData(0));
191 m_testNoSound2 = op->Apply(m_in);
192
193 op->SetSoundSpeedFactor(TData(1));
194 m_testWithSound2 = op->Apply(m_in);
195 }
196
197 /**
198 * @brief Compare both weightings and both storage layouts against the
199 * expected values, with relative tolerance tol.
200 *
201 * @return bool
202 */
203 bool Compare(const TData tol)
204 {
205 bool match = true;
206
207 const auto report = [&match, tol](const std::string &desc,
208 const TData actual,
209 const TData expected) {
210 const auto diff = std::abs(actual - expected);
211 const auto rel =
212 diff / (std::max)(std::abs(expected), static_cast<TData>(1));
213 if (rel > tol)
214 {
215 std::cout << desc << " mismatch: actual=" << actual
216 << ", expected=" << expected << ", rel diff=" << rel
217 << std::endl;
218 match = false;
219 }
220 };
221
222 report("Non-interleaved case without wave speed", m_testNoSound,
224 report("Non-interleaved case with wave speed", m_testWithSound,
226 report("Interleaved case without wave speed", m_testNoSound2,
228 report("Interleaved case with wave speed", m_testWithSound2,
230
231 // The wave speed can only add to the transport rate, and the test
232 // velocity is not uniform, so the two must actually differ - a
233 // factor that was silently ignored would otherwise pass.
235 {
236 std::cout << "Wave speed made no difference: with="
237 << m_testWithSound << ", without=" << m_testNoSound
238 << std::endl;
239 match = false;
240 }
241
242 return match;
243 }
244
245protected:
246 std::string m_meshName = "";
250
251 TData m_testNoSound = 0;
253 TData m_testNoSound2 = 0;
257
259 {
260 std::string execStr(GlobalConfiguration::ExecStr());
261
262 BOOST_TEST_MESSAGE("Creating input field");
263
264 // Construct a fake command-line argument array to be fed to
265 // Session::Reader::CreateInstance. The first element stands for
266 // the name of the executable which, in our case, doesn't matter.
267 int argc = 3;
268 char **argv = new char *[argc];
269 argv[0] = strdup("exe_name");
270 argv[1] = strdup(m_meshName.data());
271 argv[2] = strdup(("--opExecSpace=" + execStr).c_str());
272
274
275 for (int i = 0; i < argc; ++i)
276 {
277 free(argv[i]);
278 }
279 delete[] argv;
280 }
281
288
290 {
291 // One component per coordinate direction, plus the wave speed. This
292 // is the operator's input contract, and is unrelated to the number of
293 // variables the session happens to declare.
294 const unsigned int ncomp = m_expList->GetCoordim(0) + 1;
295 auto blockAttr = GetBlockAttributes<TData, FieldState::Phys>(
296 m_expList, MultiRegions::UnitInterleaveWidths(m_expList));
297
298 m_in = Field<TData, FieldState::Phys>("f_in", blockAttr, ncomp, 1);
299 }
300
301 /**
302 * @brief The oracle: the legacy computation, element by element on the
303 * host.
304 *
305 * Mirrors CompressibleFlowSystem::v_GetMaxStdVelocity, including its
306 * indexing of the derivative factors and its treatment of the wave speed
307 * as acting equally in every direction, then applies the order weight the
308 * operator folds in per block.
309 */
311 {
312 const auto coordim = m_expList->GetCoordim(0);
313 const auto expdim = m_expList->GetExp(0)->GetShapeDimension();
314 const auto nElmts = m_expList->GetExpSize();
315
316 Array<OneD, TData> in = m_in.template ToArray<TData>();
317 const auto nphys = m_expList->GetTotPoints();
318
321
322 for (size_t el = 0; el < nElmts; ++el)
323 {
324 auto exp = m_expList->GetExp(el);
325 const auto offset = m_expList->GetPhys_Offset(el);
326 const auto nqTot = exp->GetTotPoints();
327 const auto &gmat = exp->GetGeomFactors()->GetDerivFactors();
328 const bool deformed =
329 exp->GetGeomFactors()->GetGtype() == SpatialDomains::eDeformed;
330
331 const TData order =
332 (std::max)(static_cast<TData>(exp->EvalBasisNumModesMax()) -
333 static_cast<TData>(1),
334 static_cast<TData>(1));
335 const TData weight = order * order;
336
337 for (unsigned int q = 0; q < nqTot; ++q)
338 {
339 TData sqNoSound = 0;
340 TData sqWithSound = 0;
341
342 for (unsigned int i = 0; i < expdim; ++i)
343 {
344 TData stdVel = 0;
345 TData stdSound = 0;
346 for (unsigned int j = 0; j < coordim; ++j)
347 {
348 const TData g = static_cast<TData>(
349 gmat[expdim * j + i][deformed ? q : 0]);
350 stdVel += g * in[j * nphys + offset + q];
351 stdSound += g;
352 }
353
354 const TData c = in[coordim * nphys + offset + q];
355
356 const TData velNoSound = std::abs(stdVel);
357 const TData velSound =
358 std::abs(stdVel) + std::abs(stdSound * c);
359
360 sqNoSound += velNoSound * velNoSound;
361 sqWithSound += velSound * velSound;
362 }
363
365 std::sqrt(sqNoSound) * weight);
366 m_expectedWithSound = (std::max)(
367 m_expectedWithSound, std::sqrt(sqWithSound) * weight);
368 }
369 }
370 }
371};
372
373// clang-format off
374#if defined(NEKTAR_ENABLE_SINGLE_PRECISION)
375#define TESTFLOAT(type, filename) \
376 class type##float : public TestMaxStdVelocity<float> \
377 { \
378 public: \
379 type##float() \
380 { \
381 m_meshName = filename; \
382 } \
383 };
384#else
385#define TESTFLOAT(type, filename)
386#endif
387#if defined(NEKTAR_ENABLE_DOUBLE_PRECISION)
388#define TESTDOUBLE(type, filename) \
389 class type : public TestMaxStdVelocity<double> \
390 { \
391 public: \
392 type() \
393 { \
394 m_meshName = filename; \
395 } \
396 };
397#else
398#define TESTDOUBLE(type, filename)
399#endif
400#define TEST(type, filename) \
401 TESTFLOAT(type, filename) \
402 TESTDOUBLE(type, filename)
403// clang-format on
404
405TEST(Seg, "run/segment.xml")
406
407TEST(Quad, "run/square.xml")
408
409TEST(QuadVarP, "run/square_varp.xml")
410
411TEST(Tri, "run/tri.xml")
412
413TEST(SquareAllElements, "run/square_all_elements.xml")
414
415TEST(Hex, "run/hex.xml")
416
417TEST(HexVarP, "run/hex_varp.xml")
418
419TEST(Prism, "run/prism.xml")
420
421TEST(Tet, "run/tet.xml")
422
423TEST(CubeAllElements, "run/cube_all_elements.xml")
424
425#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.
void ReshapeStorage(const unsigned int &interleaveWidth, const std::string &execSpace)
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.
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)
Compares MaxStdVelocityOp against the legacy formula.
bool Compare(const TData tol)
Compare both weightings and both storage layouts against the expected values, with relative tolerance...
Field< TData, FieldState::Phys > m_in
void RunTestCase()
Apply the operator with and without the wave speed, once on the non-interleaved storage reduced to ev...
void Configure()
Read the session, build the expansion list and allocate the field the test cases work on.
SessionReaderSharedPtr m_session
ExpListSharedPtr m_expList
~TestMaxStdVelocity()=default
void ExpectedSolution()
The oracle: the legacy computation, element by element on the host.
TestMaxStdVelocity()=default
void SetTestCase()
Fill the velocity components and the wave speed, and record the value the operator is expected to ret...
std::shared_ptr< SessionReader > SessionReaderSharedPtr
std::shared_ptr< ExpList > ExpListSharedPtr
Shared pointer to an ExpList object.
@ eDeformed
Geometry is curved or has non-constant factors.
@ Exec
exe – ExecName