Nektar++
Loading...
Searching...
No Matches
TestNormOps.hpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: TestNormOps.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 NormL2 and NormLinf operators. Self contained:
32// it owns its session, expansion list and input field, and takes the expected
33// norms from the expansion list's own L2/Linf as an independent oracle.
34//
35///////////////////////////////////////////////////////////////////////////////
36
37#pragma once
38
39#include <SolverCore/NormOps/NormL2/NormL2Op.hpp>
40#include <SolverCore/NormOps/NormLinf/NormLinfOp.hpp>
41
48
51
52#include <cmath>
53#include <cstdlib>
54#include <cstring>
55#include <iostream>
56#include <string>
57#include <vector>
58
59using namespace Nektar;
60using namespace Nektar::LibUtilities;
61using namespace Nektar::MultiRegions;
62using namespace Nektar::SolverCore;
63
65
66/**
67 * @class TestNormOps
68 *
69 * A test fixture that fills a physical-space field with an analytic
70 * expression and checks NormL2Op (plain and normalised by the mesh volume)
71 * and NormLinfOp against the norms the expansion list computes itself, both
72 * for the non-interleaved storage and for the interleaved storage the
73 * vectorised and device paths use. The 3DH1 cases give every plane its own
74 * data, so the norms depend on how the planes are combined.
75 *
76 * The fixture constructor (destructor) is called before (after) each call to
77 * the BOOST_FIXTURE_TEST_CASE(<test name>, <fixture>) macro.
78 *
79 * See "Single test case fixture" on the Boost.Test documentation for more
80 * details:
81 * https://www.boost.org/doc/libs/1_82_0/libs/test/doc/html/boost_test/tests_organization/fixtures/case.html
82 */
83template <typename TData> class TestNormOps
84{
85public:
86 TestNormOps() = default;
87 ~TestNormOps() = default;
88
89 /**
90 * @brief Read the session, build the expansion list and allocate the
91 * field the test cases work on.
92 */
93 void Configure()
94 {
95 SetSession();
96 SetExpList();
97 SetFixture();
98 }
99
100 /**
101 * @brief As Configure, on a 3DH1 expansion list with nhomo planes.
102 */
103 void Configure3DH1(const unsigned int nhomo)
104 {
105 m_nhomo = nhomo;
106 SetSession();
108 SetFixture();
109 }
110
111 /**
112 * @brief Fill the input field with an analytic expression and record the
113 * norms it is expected to have.
114 */
116 {
117 const auto nphys = m_expList->GetTotPoints();
118
119 // Get coordinates
120 Array<OneD, double> x(nphys);
121 Array<OneD, double> y(nphys, 0.0);
122 Array<OneD, double> z(nphys, 0.0);
123 m_expList->GetCoords(x, y, z);
124
125 // Set initial conditions.
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 for (unsigned int n = 0;
133 {
134 const auto scale = static_cast<TData>(n + 1);
135 for (size_t el = 0, cnt = 0; el < inblock.GetNumElements();
136 ++el)
137 {
138 for (unsigned int phys = 0; phys < inblock.GetNumData();
139 ++phys, ++cnt)
140 {
141 const auto xc = static_cast<TData>(x[cnt]);
142 const auto yc = static_cast<TData>(y[cnt]);
143 const auto zc = static_cast<TData>(z[cnt]);
144
145 const auto base =
146 static_cast<TData>(0.3) * scale +
147 static_cast<TData>(0.2) * scale * xc +
148 static_cast<TData>(0.1) * (n + 2) * yc * yc -
149 static_cast<TData>(0.05) * scale * zc;
150
151 const auto base_plus_error =
152 static_cast<TData>(0.02) * scale *
153 (static_cast<TData>(1.0) + xc * xc +
154 static_cast<TData>(0.5) * yc +
155 static_cast<TData>(0.25) * zc * zc) +
156 static_cast<TData>(0.003) * (n + 1) *
157 ((cnt % 5) + 1);
158 inptr[cnt] = base - base_plus_error;
159 }
160 }
161 inptr += inblock.CompSize();
162 }
163 }
164
165 // Compute expected solution.
167 }
168
169 /**
170 * @brief Apply the norm operators, once on the non-interleaved storage
171 * reduced to every rank and once on the interleaved storage reduced to
172 * rank zero alone.
173 */
175 {
176 auto l2Op =
177 NormL2Op<TData>::Create(m_expList, m_session->GetVariables());
178 auto linfOp =
179 NormLinfOp<TData>::Create(m_expList, m_session->GetVariables());
180
181 // Non-interleaved case.
182 l2Op->Apply(m_in);
183 m_l2Test = l2Op->GetNorms();
184 m_l2NormalisedTest = l2Op->GetNorms(true);
185
186 linfOp->Apply(m_in);
187 m_linfTest = linfOp->GetNorms();
188
189 // Interleaved case.
190 std::string execStr =
192 m_in.ReshapeStorage(NektarSpaces::GetVectorWidth<TData>(execStr),
193 execStr);
194
195 l2Op->SetRootOnly(true);
196 l2Op->Apply(m_in);
197 m_l2Test2 = l2Op->GetNorms();
198 m_l2NormalisedTest2 = l2Op->GetNorms(true);
199
200 linfOp->SetRootOnly(true);
201 linfOp->Apply(m_in);
202 m_linfTest2 = linfOp->GetNorms();
203 }
204
205 /**
206 * @brief Compare both sets of norms against the expected ones, with
207 * absolute tolerance tol.
208 *
209 * @return bool
210 */
211 bool Compare(const TData tol)
212 {
213 const unsigned int numComp = m_in.GetNumComponents();
214
215 if (m_l2Test.size() != m_l2Expected.size() ||
217 m_linfTest.size() != m_linfExpected.size())
218 {
219 std::cout << "Mismatch of norm vector sizes." << std::endl;
220 return false;
221 }
222
223 bool match = true;
224 std::cout << " - Non-interleaved cases: " << std::endl;
225 for (unsigned int comp = 0; comp < numComp; ++comp)
226 {
227 const auto l2Diff = std::abs(m_l2Test[comp] - m_l2Expected[comp]);
228 const auto l2NormalisedDiff = std::abs(
230 const auto linfDiff =
231 std::abs(m_linfTest[comp] - m_linfExpected[comp]);
232
233 if (l2Diff > tol)
234 {
235 std::cout << "Component " << comp
236 << " mismatch: " << "L2(actual=" << m_l2Test[comp]
237 << ", expected=" << m_l2Expected[comp]
238 << ", diff=" << l2Diff << ")" << std::endl;
239 match = false;
240 }
241
242 if (l2NormalisedDiff > tol)
243 {
244 std::cout << "Component " << comp << " mismatch: "
245 << "L2 normalised(actual=" << m_l2NormalisedTest[comp]
246 << ", expected=" << m_l2NormalisedExpected[comp]
247 << ", diff=" << l2NormalisedDiff << ")" << std::endl;
248 match = false;
249 }
250
251 if (linfDiff > tol)
252 {
253 std::cout << "Component " << comp
254 << " mismatch: " << "Linf(actual=" << m_linfTest[comp]
255 << ", expected=" << m_linfExpected[comp]
256 << ", diff=" << linfDiff << ")" << std::endl;
257 match = false;
258 }
259 }
260
261 std::cout << " - Interleaved cases: " << std::endl;
262 for (unsigned int comp = 0; comp < numComp; ++comp)
263 {
264 const auto l2Diff = std::abs(m_l2Test2[comp] - m_l2Expected[comp]);
265 const auto l2NormalisedDiff = std::abs(
267 const auto linfDiff =
268 std::abs(m_linfTest2[comp] - m_linfExpected[comp]);
269
270 if (l2Diff > tol)
271 {
272 std::cout << "Component " << comp
273 << " mismatch: " << "L2(actual=" << m_l2Test2[comp]
274 << ", expected=" << m_l2Expected[comp]
275 << ", diff=" << l2Diff << ")" << std::endl;
276 match = false;
277 }
278
279 if (l2NormalisedDiff > tol)
280 {
281 std::cout << "Component " << comp
282 << " mismatch: " << "L2 normalised(actual="
283 << m_l2NormalisedTest2[comp]
284 << ", expected=" << m_l2NormalisedExpected[comp]
285 << ", diff=" << l2NormalisedDiff << ")" << std::endl;
286 match = false;
287 }
288
289 if (linfDiff > tol)
290 {
291 std::cout << "Component " << comp << " mismatch: "
292 << "Linf(actual=" << m_linfTest2[comp]
293 << ", expected=" << m_linfExpected[comp]
294 << ", diff=" << linfDiff << ")" << std::endl;
295 match = false;
296 }
297 }
298
299 return match;
300 }
301
302protected:
303 std::string m_meshName = "";
304 /// Number of planes; 1 without a homogeneous direction.
305 unsigned int m_nhomo = 1;
306 /// Homogeneous length of the 3DH1 cases, other than 1 so that it shows.
307 static constexpr double m_homoLen = 2.0;
311
312 std::vector<TData> m_l2Test;
313 std::vector<TData> m_linfTest;
314 std::vector<TData> m_l2Test2;
315 std::vector<TData> m_linfTest2;
316 std::vector<TData> m_l2NormalisedTest;
317 std::vector<TData> m_l2NormalisedTest2;
318 std::vector<TData> m_l2Expected;
319 std::vector<TData> m_l2NormalisedExpected;
320 std::vector<TData> m_linfExpected;
321
323 {
324 std::string execStr(GlobalConfiguration::ExecStr());
325
326 BOOST_TEST_MESSAGE("Creating input field");
327
328 // Construct a fake command-line argument array to be fed to
329 // Session::Reader::CreateInstance. The first element stands for
330 // the name of the executable which, in our case, doesn't matter.
331 int argc = 3;
332 char **argv = new char *[argc];
333 argv[0] = strdup("exe_name");
334 argv[1] = strdup(m_meshName.data());
335 argv[2] = strdup(("--opExecSpace=" + execStr).c_str());
336
338
339 for (int i = 0; i < argc; ++i)
340 {
341 free(argv[i]);
342 }
343 delete[] argv;
344 }
345
353
366
368 {
369 const unsigned int ncomp = m_session->GetVariables().size();
370 auto blockAttr = GetBlockAttributes<TData, FieldState::Phys>(
371 m_expList, MultiRegions::UnitInterleaveWidths(m_expList));
372
373 m_in =
374 Field<TData, FieldState::Phys>("f_in", blockAttr, ncomp, m_nhomo);
375 }
376
377 /**
378 * @brief The oracle: the norms the expansion list computes from the same
379 * data, independently of the operators under test.
380 */
382 {
383 const unsigned int numComp = m_in.GetNumComponents();
384 const auto nphys = m_expList->GetTotPoints();
385
386 Array<OneD, TData> lhs = m_in.template ToArray<TData>();
387
388 // Mesh volume, for the normalised L2 norm: a 3DH1 mesh is one plane
389 // extended over the homogeneous length.
390 const auto volume =
391 (m_nhomo == 1)
392 ? m_expList->Integral(Array<OneD, double>(nphys, 1.0))
393 : m_expList->GetPlane(0)->Integral(Array<OneD, double>(
394 m_expList->GetPlane(0)->GetTotPoints(), 1.0)) *
395 m_homoLen;
396
397 m_l2Expected.resize(numComp);
398 m_l2NormalisedExpected.resize(numComp);
399 m_linfExpected.resize(numComp);
400
401 for (unsigned int comp = 0; comp < numComp; ++comp)
402 {
403 m_l2Expected[comp] = m_expList->L2(lhs + comp * nphys);
405 m_l2Expected[comp] / std::sqrt(volume);
406 m_linfExpected[comp] = m_expList->Linf(lhs + comp * nphys);
407 }
408 }
409};
410
411// clang-format off
412#if defined(NEKTAR_ENABLE_SINGLE_PRECISION)
413#define TESTFLOAT(type, filename) \
414 class type##float : public TestNormOps<float> \
415 { \
416 public: \
417 type##float() \
418 { \
419 m_meshName = filename; \
420 } \
421 };
422#else
423#define TESTFLOAT(type, filename)
424#endif
425#if defined(NEKTAR_ENABLE_DOUBLE_PRECISION)
426#define TESTDOUBLE(type, filename) \
427 class type : public TestNormOps<double> \
428 { \
429 public: \
430 type() \
431 { \
432 m_meshName = filename; \
433 } \
434 };
435#else
436#define TESTDOUBLE(type, filename)
437#endif
438#define TEST(type, filename) \
439 TESTFLOAT(type, filename) \
440 TESTDOUBLE(type, filename)
441// clang-format on
442
443TEST(Seg, "run/segment.xml")
444
445TEST(SegSEM, "run/line_sem.xml")
446
447TEST(Seg3D, "run/segment_3D.xml")
448
449TEST(Quad, "run/square.xml")
450
451TEST(Quad3D, "run/square_3D.xml")
452
453TEST(QuadVarP, "run/square_varp.xml")
454
455TEST(QuadSEM, "run/square_sem.xml")
456
457TEST(Tri, "run/tri.xml")
458
459TEST(Tri3D, "run/tri_3D.xml")
460
461TEST(TriVarP, "run/tri_varp.xml")
462
463TEST(TriNodal, "run/tri_nodal.xml")
464
465TEST(SquareAllElements, "run/square_all_elements.xml")
466
467TEST(Hex, "run/hex.xml")
468
469TEST(HexVarP, "run/hex_varp.xml")
470
471TEST(HexSEM, "run/hex_sem.xml")
472
473TEST(Prism, "run/prism.xml")
474
475TEST(PrismVarP, "run/prism_varp.xml")
476
477TEST(PrismNodal, "run/prism_nodal.xml")
478
479TEST(Pyr, "run/pyr.xml")
480
481TEST(PyrVarP, "run/pyr_varp.xml")
482
483TEST(Tet, "run/tet.xml")
484
485TEST(TetVarP, "run/tet_varp.xml")
486
487TEST(TetNodal, "run/tet_nodal.xml")
488
489TEST(CubePrismHex, "run/cube_prismhex.xml")
490
491TEST(CubeAllElements, "run/cube_all_elements.xml")
492
493#include <UnitTests/TestBoostTeardown.hpp>
SpatialDomains::MeshGraphSharedPtr graph
#define NEKTAR_TEST_GLOBAL_CONFIGURATION(args)
#define TEST(type, filename)
SpatialDomains::Geometry * el
Describes the specification for a Basis.
Definition Basis.h:45
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 GetNumHomoModes() const
Gets the number of homogeneous modes.
unsigned int GetNumComponents() const
Gets the number of components for a vector field.
Defines a specification for a set of points.
Definition Points.h:50
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)
std::vector< TData > m_linfTest
std::vector< TData > m_l2NormalisedTest2
TestNormOps()=default
void SetFixture()
std::vector< TData > m_linfTest2
void SetTestCase()
Fill the input field with an analytic expression and record the norms it is expected to have.
void SetExpList3DH1()
SessionReaderSharedPtr m_session
std::string m_meshName
Field< TData, FieldState::Phys > m_in
unsigned int m_nhomo
Number of planes; 1 without a homogeneous direction.
static constexpr double m_homoLen
Homogeneous length of the 3DH1 cases, other than 1 so that it shows.
void SetExpList()
std::vector< TData > m_l2Test
std::vector< TData > m_l2Expected
void Configure()
Read the session, build the expansion list and allocate the field the test cases work on.
void SetSession()
void Configure3DH1(const unsigned int nhomo)
As Configure, on a 3DH1 expansion list with nhomo planes.
std::vector< TData > m_l2NormalisedTest
void RunTestCase()
Apply the norm operators, once on the non-interleaved storage reduced to every rank and once on the i...
void ExpectedSolution()
The oracle: the norms the expansion list computes from the same data, independently of the operators ...
~TestNormOps()=default
std::vector< TData > m_l2Test2
std::vector< TData > m_l2NormalisedExpected
ExpListSharedPtr m_expList
bool Compare(const TData tol)
Compare both sets of norms against the expected ones, with absolute tolerance tol.
std::vector< TData > m_linfExpected
std::shared_ptr< SessionReader > SessionReaderSharedPtr
@ eFourierEvenlySpaced
1D Evenly-spaced points using Fourier Fit
Definition PointsType.h:74
@ eFourier
Fourier Expansion .
Definition BasisType.h:55
std::shared_ptr< ExpList > ExpListSharedPtr
Shared pointer to an ExpList object.
@ Exec
exe – ExecName