Nektar++
Loading...
Searching...
No Matches
TestPreconOps.hpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: TestPreconOps.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 shared by the DiagPrecon and NullPrecon unit tests.
32// Self contained: it owns its session, continuous expansion list and fields,
33// and takes the expected result from the legacy MultiRegions preconditioner
34// as an independent oracle.
35//
36///////////////////////////////////////////////////////////////////////////////
37
38#pragma once
39
42#include <SolverCore/PreconOps/PreconOp.hpp>
43
52
55
56#include <cmath>
57#include <cstdio>
58#include <cstdlib>
59#include <cstring>
60#include <iostream>
61#include <string>
62#include <vector>
63
64using namespace Nektar;
65using namespace Nektar::LibUtilities;
66using namespace Nektar::MultiRegions;
67using namespace Nektar::SolverCore;
68
70
71/**
72 * @class TestPreconOps
73 *
74 * @brief Compares a preconditioner operator against its legacy counterpart.
75 *
76 * The operator under test is built through PreconOp::Create for the requested
77 * method and configured against a Helmholtz operator; the expected result
78 * comes from the MultiRegions preconditioner of the same name, built on a
79 * legacy GlobalLinSys for the same problem. The two reach the same numbers by
80 * different routes, so the comparison checks the operator, its configuration
81 * from the element operator, and its handling of the assembled storage.
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 TestPreconOps
91{
92public:
93 TestPreconOps() = default;
94 ~TestPreconOps() = default;
95
96 /**
97 * @brief Read the session, build the continuous expansion list and
98 * allocate the fields the test cases work on.
99 */
101 {
102 SetSession();
103 SetExpList();
104 SetFixture();
105 }
106
107 /**
108 * @brief Set the input coefficients and the problem parameters, and
109 * record the result the preconditioner is expected to produce.
110 */
111 void SetTestCase(const std::string &method)
112 {
113 // Set initial conditions.
114 for (unsigned int blk = 0; blk < m_in.GetBlocks().size(); ++blk)
115 {
116 auto &block = m_in.GetBlocks()[blk];
117 auto inptr =
118 block.template GetPtr<NektarSpaces::HostSpace, WriteOnly>();
119 for (size_t el = 0, cnt = 0; el < block.GetNumElements(); ++el)
120 {
121 for (unsigned int coeff = 0; coeff < block.GetNumData();
122 ++coeff, ++cnt)
123 {
124 inptr[cnt] = 1.0;
125 }
126 }
127 }
128
129 // Get lambda from m_session or default to 10.0
130 m_lambda = m_session->DefinesParameter("Lambda")
131 ? m_session->GetParameter("Lambda")
132 : 10.0;
133
134 // Set up diffusion coefficient.
135 const auto coordDim = m_expList->GetCoordim(0);
136 const auto nDiffCoeff = coordDim * (coordDim + 1) / 2;
137 m_diffCoeff.resize(nDiffCoeff);
138
139 if (coordDim == 1)
140 {
141 m_diffCoeff[0] = 1.0; // D00
142 }
143 else if (coordDim == 2)
144 {
145 m_diffCoeff[0] = 1.0; // D00
146 m_diffCoeff[2] = 1.0; // D11
147 }
148 else
149 {
150 m_diffCoeff[0] = 1.0; // D00
151 m_diffCoeff[2] = 1.0; // D11
152 m_diffCoeff[5] = 1.0; // D22
153 }
154
155 // Compute expected solution.
156 ExpectedSolution(method);
157 }
158
159 /**
160 * @brief Build the preconditioner for @p method, configure it against the
161 * Helmholtz operator and apply it to the assembled input.
162 */
163 void RunTestCase(const std::string &method)
164 {
165 std::string execStr = Operator<TData>::GetOpExecSpace(m_session);
166
168 m_expList, m_session->GetVariables());
169 auto op =
171 auto precon = PreconOp<TData>::Create(
172 m_expList, m_session->GetVariables(), method);
173 op->SetLambda(m_lambda);
174 op->SetDiffCoeff(m_diffCoeff);
175 auto lhs = std::make_shared<LHSOp<TData>>(m_expList,
176 m_session->GetVariables());
177 lhs->SetElmtOp(op);
179 {
180 // Configure and apply for another operator first, so that the
181 // configuration below refills what this one left.
182 const unsigned int ncomp = m_session->GetVariables().size();
184 "f_first",
185 GetBlockAttributes<TData, FieldState::Coeff>(
186 m_expList, MultiRegions::UnitInterleaveWidths(m_expList)),
187 ncomp, 1);
188 op->SetLambda(2.0 * m_lambda + 1.0);
189 precon->Configure(lhs);
190 assmb->Apply(m_in, first);
191 if (execStr == "AVX")
192 {
193 first.ReshapeStorage(
194 NektarSpaces::GetVectorWidth<TData>(execStr), execStr);
195 }
196 precon->Apply(first, first);
197 op->SetLambda(m_lambda);
198 }
199 precon->Configure(lhs);
200 assmb->Apply(m_in, m_out);
201
202 // reshape m_out
203 if (execStr == "AVX")
204 {
205 m_out.ReshapeStorage(NektarSpaces::GetVectorWidth<TData>(execStr),
206 execStr);
207 }
208
209 precon->Apply(m_out, m_out);
210 }
211
212 /**
213 * @brief The oracle: the legacy MultiRegions preconditioner of the same
214 * name, built on a GlobalLinSys for the same Helmholtz problem.
215 */
216 void ExpectedSolution(const std::string &method)
217 {
218 auto nin = m_session->GetVariables().size();
219 auto ncoeff = m_expList->GetNcoeffs();
220
221 // Calculate expected result from Nektar++
222 Array<OneD, TData> incoeffs = m_in.ToArray();
223 Array<OneD, TData> outcoeffs(nin * ncoeff, 0.0);
224
227
228 auto map = std::dynamic_pointer_cast<ContField>(m_expList)
229 ->GetLocalToGlobalMap();
230 GlobalLinSysKey key(StdRegions::eHelmholtz, map, factors);
231 auto globalSys = GetGlobalLinSysFactory().CreateInstance(
232 "IterativeFull", key, m_expList, map);
233 auto precond =
234 GetPreconFactory().CreateInstance(method, globalSys, map);
235 precond->BuildPreconditioner();
236 for (unsigned int n = 0; n < nin; n++)
237 {
239 precond->DoPreconditioner(incoeffs + n * ncoeff,
240 tmp = outcoeffs + n * ncoeff, true);
241 }
242 m_expected.template CopyArray<NektarSpaces::HostSpace>(outcoeffs);
243 }
244
245 /**
246 * @brief Compare the computed field to the expected one, with absolute
247 * tolerance tol. The two must have the same blocks and components; their
248 * interleave widths may differ.
249 *
250 * @return bool
251 */
252 bool Compare(TData tol)
253 {
254 auto rank = m_session->GetComm()->GetRank();
255
257 {
258 std::cout << "Mismatch of number of components." << std::endl;
259 return false;
260 }
261
263 {
264 std::cout << "Mismatch of number of homogeneous modes."
265 << std::endl;
266 return false;
267 }
268
269 if (m_expected.GetBlocks().size() != m_out.GetBlocks().size())
270 {
271 std::cout << "Mismatch of block size." << std::endl;
272 return false;
273 }
274
275 // ToVector() returns every component element by element, whatever
276 // the interleave width of each block, and leaves the fields as they
277 // are.
278 const std::vector<TData> out = m_out.template ToVector<TData>();
279 const std::vector<TData> expected =
280 m_expected.template ToVector<TData>();
281 const size_t compSize =
282 out.size() / (m_out.GetNumComponents() * m_out.GetNumHomoModes());
283
284 bool isMatch = true;
285
286 if (rank == 0)
287 {
288 printf("#elm #pts output expected "
289 "difference\n");
290 }
291 size_t blkOffset = 0;
292 for (unsigned int blk = 0; blk < m_out.GetBlocks().size(); ++blk)
293 {
294 const auto &outBlock = m_out.GetBlocks()[blk];
295 const auto &expBlock = m_expected.GetBlocks()[blk];
296 if ((outBlock.GetNumElements() != expBlock.GetNumElements()) ||
297 (outBlock.GetNumData() != expBlock.GetNumData()))
298 {
299 std::cout << "Mismatch of block structure." << std::endl;
300 return false;
301 }
302 const size_t nElmts = outBlock.GetNumElements();
303 const unsigned int nPts = outBlock.GetNumData();
304
305 for (unsigned int n = 0;
307 {
308 const TData *outptr = out.data() + n * compSize + blkOffset;
309 const TData *expptr =
310 expected.data() + n * compSize + blkOffset;
311 size_t MisMatchcnt = 0, total = 0;
312
313 for (size_t el = 0, cnt = 0; el < nElmts; ++el)
314 {
315 for (unsigned int pts = 0; pts < nPts; ++pts, ++cnt)
316 {
317 if (std::isnan(outptr[cnt]) ||
318 std::isinf(outptr[cnt]) ||
319 std::abs(outptr[cnt] - expptr[cnt]) > tol)
320 {
321 printf("%04lu %04u %20.16f %20.16f %20.16f\n", el,
322 pts, outptr[cnt], expptr[cnt],
323 std::abs(outptr[cnt] - expptr[cnt]));
324 MisMatchcnt++;
325 }
326 total++;
327 }
328 }
329
330 if (MisMatchcnt)
331 {
332 std::cout << "Number of mismatches in component " << n
333 << " on block " << blk << " is " << MisMatchcnt
334 << " out of " << total << " on rank: " << rank
335 << std::endl;
336 isMatch = false;
337 }
338 }
339 blkOffset += nElmts * nPts;
340 }
341
342 return isMatch;
343 }
344
345protected:
346 std::string m_meshName = "";
352
353 TData m_lambda;
354 std::vector<TData> m_diffCoeff;
355
356 // Whether RunTestCase() configures the preconditioner twice, first for
357 // another lambda.
358 bool m_isReconfigured = false;
359
361 {
362 std::string execStr(GlobalConfiguration::ExecStr());
363 std::string implStr(GlobalConfiguration::ImplStr());
364
365 BOOST_TEST_MESSAGE("Creating input and output fields");
366
367 // Construct a fake command-line argument array to be fed to
368 // Session::Reader::CreateInstance. The first element stands for
369 // the name of the executable which, in our case, doesn't matter.
370 int argc = 4;
371 char **argv = new char *[argc];
372 argv[0] = strdup("exe_name");
373 argv[1] = strdup(m_meshName.data());
374 argv[2] = strdup(("--opExecSpace=" + execStr).c_str());
375 argv[3] = strdup(("--opImpl=" + implStr).c_str());
376
378
379 for (int i = 0; i < argc; ++i)
380 {
381 free(argv[i]);
382 }
383 delete[] argv;
384 }
385
386 /**
387 * @brief A continuous field: the preconditioners act on the assembled,
388 * globally continuous coefficients, and the oracle needs the local to
389 * global map that only ContField carries.
390 */
398
400 {
401 const unsigned int ncomp = m_session->GetVariables().size();
402 auto blockAttr = GetBlockAttributes<TData, FieldState::Coeff>(
403 m_expList, MultiRegions::UnitInterleaveWidths(m_expList));
404
405 m_in = Field<TData, FieldState::Coeff>("f_in", blockAttr, ncomp, 1);
406 m_out = Field<TData, FieldState::Coeff>("f_out", blockAttr, ncomp, 1);
407 m_expected =
408 Field<TData, FieldState::Coeff>("f_expected", blockAttr, ncomp, 1);
409 }
410};
411
412// clang-format off
413#if defined(NEKTAR_ENABLE_SINGLE_PRECISION)
414#define TESTFLOAT(type, filename) \
415 class type##float : public TestPreconOps<float> \
416 { \
417 public: \
418 type##float() \
419 { \
420 m_meshName = filename; \
421 } \
422 };
423#else
424#define TESTFLOAT(type, filename)
425#endif
426#if defined(NEKTAR_ENABLE_DOUBLE_PRECISION)
427#define TESTDOUBLE(type, filename) \
428 class type : public TestPreconOps<double> \
429 { \
430 public: \
431 type() \
432 { \
433 m_meshName = filename; \
434 } \
435 };
436#else
437#define TESTDOUBLE(type, filename)
438#endif
439#define TEST(type, filename) \
440 TESTFLOAT(type, filename) \
441 TESTDOUBLE(type, filename)
442// clang-format on
443
444TEST(Helmholtz1D_Seg, "run/Helmholtz1D_P8.xml")
445
446TEST(Helmholtz1D_3C, "run/Helmholtz1D_3C.xml")
447
448TEST(Helmholtz2D_Tri_Quad, "run/Helmholtz2D_varP.xml")
449
450TEST(Helmholtz2D_AllBCs, "run/Helmholtz2D_P7_AllBCs.xml")
451
452TEST(Helmholtz2D_3C, "run/Helmholtz2D_3C.xml")
453
454TEST(Helmholtz3D_Hex, "run/Helmholtz3D_Hex_Heterogeneous.xml")
455
456TEST(Helmholtz3D_Hex_3C, "run/Helmholtz3D_Hex_3C.xml")
457
458TEST(Helmholtz3D_Prism, "run/Helmholtz3D_Prism_VarP.xml")
459
460TEST(Helmholtz3D_Pyr, "run/Helmholtz3D_Pyr_VarP.xml")
461
462TEST(Helmholtz3D_Tet, "run/Helmholtz3D_Tet_VarP.xml")
463
464#include <UnitTests/TestBoostTeardown.hpp>
Public interface for the assemble-scatter operator, which makes element-wise coefficient storage glob...
Public interface of the weak Helmholtz (Helmholtz) element operator, which maps a coefficient-space f...
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.
Nektar::Array< Nektar::OneD, TDataOut > ToArray()
Copy the data to a Nektar::Array, component by component and element by element, without padding,...
unsigned int GetNumHomoModes() const
Gets the number of homogeneous modes.
unsigned int GetNumComponents() const
Gets the number of components for a vector field.
tBasePtr CreateInstance(tKey idKey, tParam... args)
Create an instance of the class referred to by idKey.
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::shared_ptr< AssmbScatrZeroDirOp< TData > > Create(const MultiRegions::ExpListSharedPtr &expansionList, const std::vector< std::string > &components, const std::string &execStr="")
Create an implementation of this operator through the operator factory.
static std::shared_ptr< HelmholtzOp< TData > > Create(const MultiRegions::ExpListSharedPtr &expansionList, const std::vector< std::string > &components, const std::string &execStr="", const std::string &implStr="")
Create a weak-Helmholtz operator through the operator and block-operator factories.
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 a preconditioner operator against its legacy counterpart.
void SetTestCase(const std::string &method)
Set the input coefficients and the problem parameters, and record the result the preconditioner is ex...
void RunTestCase(const std::string &method)
Build the preconditioner for method, configure it against the Helmholtz operator and apply it to the ...
void Configure()
Read the session, build the continuous expansion list and allocate the fields the test cases work on.
SessionReaderSharedPtr m_session
TestPreconOps()=default
Field< TData, FieldState::Coeff > m_out
std::string m_meshName
void ExpectedSolution(const std::string &method)
The oracle: the legacy MultiRegions preconditioner of the same name, built on a GlobalLinSys for the ...
~TestPreconOps()=default
ExpListSharedPtr m_expList
Field< TData, FieldState::Coeff > m_in
Field< TData, FieldState::Coeff > m_expected
std::vector< TData > m_diffCoeff
bool Compare(TData tol)
Compare the computed field to the expected one, with absolute tolerance tol. The two must have the sa...
void SetExpList()
A continuous field: the preconditioners act on the assembled, globally continuous coefficients,...
std::shared_ptr< SessionReader > SessionReaderSharedPtr
GlobalLinSysFactory & GetGlobalLinSysFactory()
std::shared_ptr< ExpList > ExpListSharedPtr
Shared pointer to an ExpList object.
PreconFactory & GetPreconFactory()
std::map< ConstFactorType, NekDouble > ConstFactorMap
@ ExecAndImpl
exe – ExecName ImplName