Nektar++
Loading...
Searching...
No Matches
TestPhysLiftProject.hpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: TestPhysLiftProject.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 of the PhysLiftProject operator unit test: the operator
32// against the four-operator chain it replaces.
33//
34///////////////////////////////////////////////////////////////////////////////
35
36#pragma once
37
39
46
47#include <cmath>
48#include <set>
49#include <string>
50#include <vector>
51
52using namespace Nektar;
53using namespace Nektar::LibUtilities;
54using namespace Nektar::MultiRegions;
55
56/**
57 * @brief The lift-and-project operator against the chain it replaces,
58 * IProductWRTPhysTrace (appending) + IProductWRTBase without integration +
59 * MultiplyByElmtInvMass + BwdTrans, on the mesh of the derived fixture with
60 * its expansions replaced: every element of the given expansion type,
61 * number of modes and number of points per direction.
62 *
63 * Each case is run with and without the trace, with the scale left at one
64 * and overwriting, and with a scale and appending onto a field that already
65 * holds values. Where the execution space interleaves, the case is run
66 * again with the inputs handed in at the operator's width, which the weak
67 * DG right-hand side does, and the inputs are checked to come back intact.
68 */
69template <typename TData>
71 : public TestOp<TData, FieldState::Phys, FieldState::Phys,
72 MultiRegions::DisContField>
73{
74public:
76
77 /**
78 * @brief Run one expansion: @p type with @p nmodes modes and, when
79 * positive, @p npts points per direction (the type's own otherwise).
80 *
81 * @return Whether every variant matched the chain within @p tol,
82 * relative to the largest entry of the reference.
83 */
85 const int nmodes, const int npts, const TData tol)
86 {
87 if (!this->session)
88 {
89 this->SetSession();
90 }
91 SetExpansions(type, nmodes, npts);
92 this->fixt_explist->SetDataWarehouse();
94
95 bool match = true;
96 for (const bool lift : {true, false})
97 {
98 for (const bool append : {false, true})
99 {
100 const TData scale = append ? TData(-0.7) : TData(1.0);
101 match = RunVariant(lift, append, scale, false, tol) && match;
102 if (GlobalConfiguration::ExecStr() == "AVX")
103 {
104 match = RunVariant(lift, append, scale, true, tol) && match;
105 }
106 }
107 }
108 return match;
109 }
110
111 /// The forms and geometry types the cases run so far reached, as
112 /// "Pointwise/affine" and so on, with "/direct lift" where the Device
113 /// SumFac and SumFacTOP implementations lift the trace directly
114 /// (DirectLift()) and "/dense tail" where the Device SumFacTOP
115 /// implementation applies the dense projector
116 /// (PhysLiftProjectDenseTail()).
117 std::set<std::string> m_forms;
118
119protected:
120 /// Read the mesh and give every element @p type with @p nmodes modes
121 /// and @p npts points, then build the expansion list.
123 const int nmodes, const int npts)
124 {
126 for (const auto &var : this->session->GetVariables())
127 {
128 for (const auto &expInfo : graph->GetExpansionInfo(var))
129 {
130 expInfo.second->m_basisKeyVector =
132 expInfo.second->m_geomPtr, type, nmodes, npts);
133 }
134 }
135 const auto &vars = this->session->GetVariables();
136 this->fixt_explist =
138 this->session, graph, vars[0], true, true,
140 }
141
142 /**
143 * @brief Whether the Device SumFac and SumFacTOP implementations lift
144 * the trace of the block of @p exp directly at every point: Pointwise
145 * blocks whose trace values lie at volume points, segments, and
146 * quadrilaterals and hexahedra whose traces have the volume points in
147 * every in-trace direction, and triangles, tetrahedra, prisms and
148 * pyramids of one point.
149 */
151 {
153 MultiRegions::detail::PhysLiftProjectForm::Pointwise)
154 {
155 return false;
156 }
157 const auto shape = exp->DetShapeType();
158 if (shape == LibUtilities::Tri || shape == LibUtilities::Tet ||
159 shape == LibUtilities::Prism || shape == LibUtilities::Pyr)
160 {
161 return exp->GetTotPoints() == 1;
162 }
163 if (shape != LibUtilities::Seg && shape != LibUtilities::Quad &&
164 shape != LibUtilities::Hex)
165 {
166 return false;
167 }
168 const unsigned int dim = exp->GetShapeDimension();
169 const auto pointsKeys = exp->GetPointsKeys();
170 for (unsigned int tr = 0; tr < dim; ++tr)
171 {
172 for (unsigned int d = 0; d + 1 < dim; ++d)
173 {
174 if (!(pointsKeys[exp->GetGeom()->GetDir(tr, d)] ==
175 exp->GetTraceBasisKey(tr, d).GetPointsKey()))
176 {
177 return false;
178 }
179 }
180 }
181 return true;
182 }
183
184 /// Note the form and geometry type of every block.
186 {
187 const auto nblocks =
188 GetBlockAttributes<TData, FieldState::Phys>(
189 this->fixt_explist,
190 MultiRegions::UnitInterleaveWidths(this->fixt_explist))
191 .size();
192 for (unsigned int blk = 0; blk < nblocks; ++blk)
193 {
194 const auto exp =
195 GetCollection(this->fixt_explist, blk).GetExpVector()[0];
196 const auto form = MultiRegions::detail::PhysLiftProjectFormOf(exp);
197 const std::string name =
198 form == MultiRegions::detail::PhysLiftProjectForm::Pointwise
199 ? "Pointwise"
200 : form == MultiRegions::detail::PhysLiftProjectForm::StdInvMass
201 ? "StdInvMass"
202 : "ElmtInvMass";
203 const bool deformed =
204 exp->GetGeomFactors()->GetGtype() == SpatialDomains::eDeformed;
205 m_forms.insert(name + (deformed ? "/deformed" : "/affine") +
206 (DirectLift(exp) ? "/direct lift" : "") +
208 ? "/dense tail"
209 : ""));
210 }
211 }
212
213 /// Values for @p field, element-local and different in every entry and
214 /// component.
215 static std::vector<TData> Values(Field<TData, FieldState::Phys> &field,
216 const TData seed)
217 {
218 std::vector<TData> values = field.template ToVector<TData>();
219 for (size_t i = 0; i < values.size(); ++i)
220 {
221 values[i] = TData(0.25) + std::sin(seed + TData(0.37) * i) +
222 TData(0.5) * std::cos(TData(1.3) * seed + 0.11 * i);
223 }
224 return values;
225 }
226
227 /// One variant: the operator and the chain from the same inputs.
228 bool RunVariant(const bool lift, const bool append, const TData scale,
229 const bool interleaved, const TData tol)
230 {
231 const auto &explist = this->fixt_explist;
232 const auto ncomp = this->session->GetVariables().size();
233 const std::vector<std::string> comps(this->session->GetVariables());
234 const auto physAttr = GetBlockAttributes<TData, FieldState::Phys>(
235 explist, MultiRegions::UnitInterleaveWidths(explist));
236 const auto coefAttr = GetBlockAttributes<TData, FieldState::Coeff>(
237 explist, MultiRegions::UnitInterleaveWidths(explist));
238 const auto traceAttr =
239 GetLocTraceBlockAttributes<TData, FieldState::Phys>(explist);
240
241 Field<TData, FieldState::Phys> in("in", physAttr, ncomp, 1);
242 Field<TData, FieldState::Phys> trace("trace", traceAttr, ncomp, 1);
243 Field<TData, FieldState::Phys> out("out", physAttr, ncomp, 1);
244 Field<TData, FieldState::Phys> expected("expected", physAttr, ncomp, 1);
245 Field<TData, FieldState::Phys> sum("sum", physAttr, ncomp, 1);
246 Field<TData, FieldState::Coeff> coef("coef", coefAttr, ncomp, 1);
247 Field<TData, FieldState::Coeff> coef2("coef2", coefAttr, ncomp, 1);
248 in.template Initialize<NektarSpaces::HostSpace>(0.0);
249 trace.template Initialize<NektarSpaces::HostSpace>(0.0);
250 out.template Initialize<NektarSpaces::HostSpace>(0.0);
251 expected.template Initialize<NektarSpaces::HostSpace>(0.0);
252
253 const auto inValues = Values(in, 0.1);
254 const auto traceValues = Values(trace, 0.7);
255 const auto outValues = Values(out, 1.9);
256 in.template CopyVector<NektarSpaces::HostSpace>(inValues);
257 trace.template CopyVector<NektarSpaces::HostSpace>(traceValues);
258 sum.template CopyVector<NektarSpaces::HostSpace>(inValues);
259 if (append)
260 {
261 out.template CopyVector<NektarSpaces::HostSpace>(outValues);
262 expected.template CopyVector<NektarSpaces::HostSpace>(outValues);
263 }
264
265 // The chain, in the execution space under test.
266 const std::string exec = GlobalConfiguration::ExecStr();
267 auto liftOp = IProductWRTPhysTraceOp<TData>::Create(explist, comps,
268 exec, "SumFac");
269 auto bTransOp =
270 IProductWRTBaseOp<TData>::Create(explist, comps, exec, "SumFac");
272 explist, comps, exec, "Generic");
273 auto bwdTransOp =
274 BwdTransOp<TData>::Create(explist, comps, exec, "SumFac");
275 liftOp->SetAppend(true);
276 bTransOp->SetIntegration(false);
277 bTransOp->SetScale(scale);
278 bwdTransOp->SetAppend(append);
279 if (lift)
280 {
281 liftOp->Apply(trace, sum);
282 }
283 bTransOp->Apply(sum, coef);
284 invMassOp->Apply(coef, coef2);
285 bwdTransOp->Apply(coef2, expected);
286
287 // The operator.
288 auto op = PhysLiftProjectOp<TData>::Create(explist, comps, exec);
289 op->SetScale(scale);
290 op->SetAppend(append);
291 if (interleaved)
292 {
293 // Interleaved at the SIMD width, the host operators' own.
294 const unsigned int interleaveWidth = tinysimd::simd<TData>::width;
295 in.ReshapeStorage(interleaveWidth, exec);
296 trace.ReshapeStorage(interleaveWidth, exec);
297 }
298 if (lift)
299 {
300 op->Apply(in, trace, out);
301 }
302 else
303 {
304 op->Apply(in, out);
305 }
306
307 bool match = Matches(out.template ToVector<TData>(),
308 expected.template ToVector<TData>(), tol);
309 match =
310 Matches(in.template ToVector<TData>(), inValues, TData(0)) && match;
311 match =
312 Matches(trace.template ToVector<TData>(), traceValues, TData(0)) &&
313 match;
314 if (!match)
315 {
316 std::cout << " mismatch: lift " << lift << ", append " << append
317 << ", interleaved " << interleaved << std::endl;
318 }
319 return match;
320 }
321
322 /// Whether @p out matches @p expected within @p tol times the largest
323 /// entry of @p expected.
324 static bool Matches(const std::vector<TData> &out,
325 const std::vector<TData> &expected, const TData tol)
326 {
327 TData norm = 0, err = 0;
328 for (size_t i = 0; i < out.size(); ++i)
329 {
330 norm = std::max(norm, std::abs(expected[i]));
331 err = std::max(err, std::isfinite(out[i])
332 ? std::abs(out[i] - expected[i])
333 : std::numeric_limits<TData>::max());
334 }
335 if (err > tol * norm)
336 {
337 std::cout << " max error " << err << " against max entry " << norm
338 << std::endl;
339 return false;
340 }
341 return true;
342 }
343};
344
345// clang-format off
346#if defined(NEKTAR_ENABLE_DOUBLE_PRECISION)
347#define TEST(type, filename) \
348 class type : public TestPhysLiftProject<double> \
349 { \
350 public: \
351 type() \
352 { \
353 meshName = filename; \
354 } \
355 };
356#else
357#define TEST(type, filename)
358#endif
359// clang-format on
360
361TEST(Seg, "run/segment.xml")
362TEST(SegCurved, "run/segment_curved.xml")
363TEST(QuadTri, "run/square_all_elements.xml")
364TEST(QuadTriCurved, "run/square_all_elements_curved.xml")
365TEST(Tri, "run/tri.xml")
366TEST(TriCurved, "run/tri_curved.xml")
367TEST(Hex, "run/hex.xml")
368TEST(HexCurved, "run/hex_curved.xml")
369TEST(Prism, "run/prism.xml")
370TEST(PrismCurved, "run/prism_curved.xml")
371TEST(Pyr, "run/pyr.xml")
372TEST(PyrCurved, "run/pyr_curved.xml")
373TEST(Tet, "run/tet.xml")
374TEST(TetCurved, "run/tet_curved.xml")
Public interface of the backward-transform (BwdTrans) element operator, which maps a field from coeff...
Whole-field interface of the IProductWRTBase element operator, which takes a physical-space field to ...
Public interface of the IProductWRTPhysTrace element operator, the discontinuous Galerkin lifting ter...
Whole-field interface of the MultiplyByElmtInvMass element operator, which multiplies a coefficient-s...
Public interface of the PhysLiftProject element operator: the trace lift followed by the projection t...
SpatialDomains::MeshGraphSharedPtr graph
#define TEST(type, filename)
std::map< int64_t, double > sum
std::vector< LocalRegions::ExpansionSharedPtr > & GetExpVector()
Definition Collection.h:102
A Field represents expansion data to be operated on.
void ReshapeStorage(const unsigned int &interleaveWidth, const std::string &execSpace)
static std::shared_ptr< DataType > AllocateSharedPtr(const Args &...args)
Allocate a shared pointer from the memory pool.
static std::shared_ptr< BwdTransOp< TData > > Create(const MultiRegions::ExpListSharedPtr &expansionList, const std::vector< std::string > &components, const std::string &execStr="", const std::string &implStr="")
Create a backward-transform operator through the operator and block-operator factories.
static std::shared_ptr< IProductWRTBaseOp< TData > > Create(const MultiRegions::ExpListSharedPtr &expansionList, const std::vector< std::string > &components, const std::string &execStr="", const std::string &implStr="")
Build a complete IProductWRTBase operator through the operator and block-operator factories.
static std::shared_ptr< IProductWRTPhysTraceOp< TData > > Create(const MultiRegions::ExpListSharedPtr &expansionList, const std::vector< std::string > &components, const std::string &execStr="", const std::string &implStr="")
Create a trace inner-product operator through the operator and block-operator factories.
static std::shared_ptr< MultiplyByElmtInvMassOp< TData > > Create(const MultiRegions::ExpListSharedPtr &expansionList, const std::vector< std::string > &components, const std::string &execStr="", const std::string &implStr="")
Build a complete element-wise inverse mass operator through the operator and block-operator factories...
static std::shared_ptr< PhysLiftProjectOp< TData > > Create(const MultiRegions::ExpListSharedPtr &expansionList, const std::vector< std::string > &components, const std::string &execStr="", const std::string &implStr="")
Create the operator through the operator and block-operator factories (see ElmtOp::Create()).
static LibUtilities::BasisKeyVector DefineBasisKeyFromExpansionType(Geometry *in, ExpansionType type, const int order, const int numpoints=-1)
The basis keys of expansion type type at order on in, with numpoints quadrature points in every direc...
static MeshGraphSharedPtr Read(const LibUtilities::SessionReaderSharedPtr pSession, LibUtilities::DomainRangeShPtr rng=LibUtilities::NullDomainRangeShPtr, bool fillGraph=true, SpatialDomains::MeshGraphSharedPtr partitionedGraph=nullptr)
The lift-and-project operator against the chain it replaces, IProductWRTPhysTrace (appending) + IProd...
TestPhysLiftProject()=default
bool RunVariant(const bool lift, const bool append, const TData scale, const bool interleaved, const TData tol)
One variant: the operator and the chain from the same inputs.
bool RunExpansion(const SpatialDomains::ExpansionType type, const int nmodes, const int npts, const TData tol)
Run one expansion: type with nmodes modes and, when positive, npts points per direction (the type's o...
static std::vector< TData > Values(Field< TData, FieldState::Phys > &field, const TData seed)
Values for field, element-local and different in every entry and component.
void SetExpansions(const SpatialDomains::ExpansionType type, const int nmodes, const int npts)
Read the mesh and give every element type with nmodes modes and npts points, then build the expansion...
static bool DirectLift(const LocalRegions::ExpansionSharedPtr &exp)
Whether the Device SumFac and SumFacTOP implementations lift the trace of the block of exp directly a...
void RecordForms()
Note the form and geometry type of every block.
static bool Matches(const std::vector< TData > &out, const std::vector< TData > &expected, const TData tol)
Whether out matches expected within tol times the largest entry of expected.
std::set< std::string > m_forms
The forms and geometry types the cases run so far reached, as "Pointwise/affine" and so on,...
std::shared_ptr< Expansion > ExpansionSharedPtr
Definition Expansion.h:66
bool PhysLiftProjectDenseTail(const LocalRegions::ExpansionSharedPtr &exp)
Whether the Device SumFacTOP implementation applies the block whose representative expansion is exp t...
PhysLiftProjectForm PhysLiftProjectFormOf(const LocalRegions::ExpansionSharedPtr &exp)
The form the block whose representative expansion is exp takes. The square test is on the total count...
Collections::Collection GetCollection(MultiRegions::ExpListSharedPtr expansionList, unsigned int block_idx)
@ eDeformed
Geometry is curved or has non-constant factors.
typename abi< ScalarType, width >::type simd
Definition tinysimd.hpp:138