Nektar++
Loading...
Searching...
No Matches
TestVarOptiDerivatives.cpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: TestVarOptiDerivatives.cpp
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: Tests that the analytic gradient and Hessian of the variational
32// optimiser's energy functionals agree with the functional they differentiate.
33//
34///////////////////////////////////////////////////////////////////////////////
35
37#include <NekMesh/MeshElements/Element.h>
38#include <NekMesh/MeshElements/Mesh.h>
39#include <NekMesh/Module/ProcessModules/ProcessVarOpti/ElUtil.h>
40#include <NekMesh/Module/ProcessModules/ProcessVarOpti/Evaluator.hxx>
41#include <NekMesh/Module/ProcessModules/ProcessVarOpti/NodeOpti.h>
42#include <NekMesh/Module/ProcessModules/ProcessVarOpti/ProcessVarOpti.h>
43
44#include <boost/test/unit_test.hpp>
45
46#include <array>
47#include <random>
48#include <set>
49#include <string>
50#include <vector>
51
53{
54using namespace Nektar::NekMesh;
55
56/**
57 * @brief The functional, its gradient and its Hessian have to describe the
58 * same function.
59 *
60 * NodeOpti::GetFunctional() returns the energy of the elements around a node
61 * and leaves its analytic first and second derivatives with respect to that
62 * node's position in m_grad. The optimiser trusts both: the Hessian picks the
63 * Newton direction and the gradient decides whether the step that results is
64 * downhill. Neither is checked anywhere else, and an error in either is close
65 * to invisible from the outside -- the mesh still improves, just more slowly
66 * and less reliably, and the module reports nothing unusual.
67 *
68 * So here the derivatives are differenced against the functional the same
69 * code evaluates. Three separate errors were found this way, each in one
70 * functional only: the Hessian of the distortion and Winslow energies carried
71 * the quadrature weight three times over rather than once, and EMatrix<3> --
72 * used by the linear elastic energy, and by nothing else -- had one wrong
73 * term, which vanishes for an undeformed element and so left the derivatives
74 * disagreeing with the functional only once the mesh was curved.
75 *
76 * Each case is run on a valid element and again on a tangled one, since the
77 * Jacobian regularisation that untangling depends on only takes effect when
78 * the Jacobian is negative, and is exactly where the derivatives are hardest.
79 *
80 * A triangle and a tetrahedron cover both dimensions and every branch of
81 * GetFunctional(). The remaining shapes differ only in the ideal mapping,
82 * which varies across the element for a quadrilateral and a prism rather than
83 * being constant; those two are covered end to end by the varopti tests in
84 * utilities/NekMesh/Tests instead, as a single quadrilateral or prism built
85 * here through CreateElementLite and Mesh::MakeOrder does not come out with a
86 * sound node list, which is a separate problem from the one under test.
87 */
88
89namespace
90{
91
92/// A single element, with the mesh that owns it.
93struct TestElement
94{
95 MeshSharedPtr mesh;
97 std::vector<SpatialDomains::PointGeom *> nodes;
98};
99
100/// Reproducible pseudo-random numbers in [-0.5, 0.5]. std::mt19937 is
101/// specified exactly by the standard; the distributions over it are not.
102class Jitter
103{
104public:
105 Jitter(unsigned seed) : m_rng(seed)
106 {
107 }
108
109 NekDouble operator()()
110 {
111 return NekDouble(m_rng()) / NekDouble(std::mt19937::max()) - 0.5;
112 }
113
114private:
115 std::mt19937 m_rng;
116};
117
118/**
119 * @brief What state the element under test is put in.
120 */
121enum class Config
122{
123 /// Valid, and curved enough that nothing is symmetric.
124 eValid,
125 /// A node displaced far enough to invert the element, so that the
126 /// Jacobian regularisation is doing the work.
127 eTangled,
128 /// The straight-sided element itself inverted, which leaves the
129 /// determinant of the ideal mapping negative.
130 eInverted
131};
132
133std::vector<std::vector<NekDouble>> VertexPositions(
135{
136 switch (shape)
137 {
139 return {{0.0, 0.0, 0.0}, {1.0, 0.1, 0.0}, {0.2, 1.0, 0.0}};
141 return {{0.0, 0.0, 0.0},
142 {1.0, 0.1, 0.05},
143 {0.1, 1.0, -0.05},
144 {0.2, 0.15, 1.0}};
145 default:
146 BOOST_FAIL("unsupported shape");
147 return {};
148 }
149}
150
151/**
152 * @brief Build a mesh of one curved element of @p shape at order
153 * @p nummode - 1, with every node jittered so that no symmetry of the element
154 * can hide an error in a cross derivative.
155 */
156TestElement MakeElement(LibUtilities::ShapeType shape, int nummode,
157 unsigned seed, bool invert)
158{
159 const int dim = (shape == LibUtilities::eTriangle) ? 2 : 3;
160
161 TestElement ret;
162 ret.mesh = std::make_shared<Mesh>();
163 auto &graph = ret.mesh->m_meshGraph;
164 graph->SetMeshDimension(dim);
165 graph->SetSpaceDimension(dim);
166
167 std::vector<std::vector<NekDouble>> verts = VertexPositions(shape);
168
169 // Exchanging two vertices turns the element inside out, which is how a
170 // mesh comes to hold a straight-sided element of negative volume.
171 if (invert)
172 {
173 std::swap(verts[1], verts[2]);
174 }
175 std::vector<SpatialDomains::PointGeom *> nodeList(verts.size());
176 for (size_t i = 0; i < verts.size(); ++i)
177 {
178 nodeList[i] = graph->CreatePointGeom(dim, i, verts[i][0], verts[i][1],
179 verts[i][2]);
180 }
181
182 ret.el = CreateElementLite(shape, nodeList, graph, ret.mesh->m_edgeSet,
183 ret.mesh->m_faceSet);
184 ret.mesh->m_elementTags[dim][ret.el] = {0};
185
186 Logger log;
187 ret.mesh->MakeOrder(nummode - 1, LibUtilities::eGaussLobattoLegendre, log);
188
189 ret.nodes = GetCurvedNodes(ret.el);
190
191 Jitter jitter(seed);
192 for (auto *n : ret.nodes)
193 {
194 for (int d = 0; d < dim; ++d)
195 {
196 (*n)[d] += 0.08 * jitter();
197 }
198 }
199
200 return ret;
201}
202
203/// The packed gradient and Hessian the optimiser works with, unpacked.
204struct Derivatives
205{
206 std::vector<NekDouble> grad;
207 std::vector<std::vector<NekDouble>> hess;
208};
209
210template <int DIM> Derivatives Unpack(const std::array<NekDouble, 9> &g)
211{
212 Derivatives ret;
213 ret.grad.assign(g.begin(), g.begin() + DIM);
214 ret.hess.assign(DIM, std::vector<NekDouble>(DIM, 0.0));
215
216 int ct = DIM;
217 for (int m = 0; m < DIM; ++m)
218 {
219 for (int l = m; l < DIM; ++l, ++ct)
220 {
221 ret.hess[m][l] = ret.hess[l][m] = g[ct];
222 }
223 }
224 return ret;
225}
226
227NekDouble MaxAbs(const std::vector<NekDouble> &v)
228{
229 NekDouble ret = 0.0;
230 for (auto x : v)
231 {
232 ret = std::max(ret, std::fabs(x));
233 }
234 return ret;
235}
236
237/**
238 * @brief Difference the functional around @p node and compare with the
239 * analytic derivatives the same evaluation produced.
240 *
241 */
242template <int DIM>
243void CheckDerivatives(NodeOptiSharedPtr opti, SpatialDomains::PointGeom *node,
244 const std::string &what)
245{
246 NekDouble minJac;
247 opti->GetFunctional<DIM>(minJac, true);
248 Derivatives analytic = Unpack<DIM>(opti->GetGrad());
249
250 std::vector<NekDouble> x0(DIM);
251 for (int d = 0; d < DIM; ++d)
252 {
253 x0[d] = (*node)[d];
254 }
255
256 // Central differences at a step h, leaving the node where it was found.
257 auto difference = [&](NekDouble h) {
258 auto eval = [&](std::vector<int> steps) {
259 NekDouble offset[3] = {};
260 for (int d = 0; d < DIM; ++d)
261 {
262 offset[d] = steps[d] * h;
263 }
264 NekDouble dummy;
265 return opti->GetFunctionalAt<DIM>(offset, dummy);
266 };
267
268 Derivatives ret;
269 ret.grad.assign(DIM, 0.0);
270 ret.hess.assign(DIM, std::vector<NekDouble>(DIM, 0.0));
271
272 for (int i = 0; i < DIM; ++i)
273 {
274 std::vector<int> fwd(DIM, 0), bwd(DIM, 0);
275 fwd[i] = 1;
276 bwd[i] = -1;
277 ret.grad[i] = (eval(fwd) - eval(bwd)) / (2.0 * h);
278 }
279
280 for (int i = 0; i < DIM; ++i)
281 {
282 for (int j = 0; j < DIM; ++j)
283 {
284 NekDouble sum = 0.0;
285 for (int si : {1, -1})
286 {
287 for (int sj : {1, -1})
288 {
289 std::vector<int> steps(DIM, 0);
290 steps[i] += si;
291 steps[j] += sj;
292 sum += si * sj * eval(steps);
293 }
294 }
295 ret.hess[i][j] = sum / (4.0 * h * h);
296 }
297 }
298 return ret;
299 };
300
301 // Both differences carry an error in h^2, so Richardson extrapolation of
302 // the two leaves one in h^4. Without it the regularised functional of a
303 // tangled element -- which is where this test is most worth having -- is
304 // curved enough that the difference itself is only good to a few parts in
305 // a thousand, and the tolerance would have to be loose enough to let a
306 // real error through.
307 const NekDouble h = 2e-4;
308 Derivatives d1 = difference(h);
309 Derivatives d2 = difference(0.5 * h);
310
311 Derivatives fd;
312 fd.grad.assign(DIM, 0.0);
313 fd.hess.assign(DIM, std::vector<NekDouble>(DIM, 0.0));
314 for (int i = 0; i < DIM; ++i)
315 {
316 fd.grad[i] = (4.0 * d2.grad[i] - d1.grad[i]) / 3.0;
317 for (int j = 0; j < DIM; ++j)
318 {
319 fd.hess[i][j] = (4.0 * d2.hess[i][j] - d1.hess[i][j]) / 3.0;
320 }
321 }
322
323 const NekDouble gScale = std::max(MaxAbs(fd.grad), 1e-12);
324 for (int i = 0; i < DIM; ++i)
325 {
326 BOOST_CHECK_MESSAGE(
327 std::fabs(analytic.grad[i] - fd.grad[i]) < 1e-6 * gScale,
328 what << ": gradient component " << i << " is " << analytic.grad[i]
329 << ", differencing the functional gives " << fd.grad[i]);
330 }
331
332 NekDouble hScale = 1e-12;
333 for (int i = 0; i < DIM; ++i)
334 {
335 hScale = std::max(hScale, MaxAbs(fd.hess[i]));
336 }
337
338 for (int i = 0; i < DIM; ++i)
339 {
340 for (int j = 0; j < DIM; ++j)
341 {
342 BOOST_CHECK_MESSAGE(std::fabs(analytic.hess[i][j] - fd.hess[i][j]) <
343 1e-4 * hScale,
344 what << ": Hessian entry (" << i << "," << j
345 << ") is " << analytic.hess[i][j]
346 << ", differencing the functional gives "
347 << fd.hess[i][j]);
348 }
349 }
350}
351
352/**
353 * @brief Set up one element, one node of it, and the optimiser object that
354 * owns the functional, then hand it to CheckDerivatives().
355 *
356 * @param tangle Displace the node far enough to invert the element first, so
357 * that the Jacobian regularisation is active.
358 */
359template <int DIM>
360void RunCase(LibUtilities::ShapeType shape, optiType opti,
361 const std::string &optiName, Config config)
362{
363 const int nummode = 4;
364 const int overInt = 2;
365
366 TestElement te =
367 MakeElement(shape, nummode, 20251005u, config == Config::eInverted);
368
369 std::map<LibUtilities::ShapeType, DerivUtilSharedPtr> derivUtils =
370 BuildDerivUtil(nummode, overInt);
371 BOOST_REQUIRE(derivUtils.count(shape) == 1);
372
373 ResidualSharedPtr res = std::make_shared<Residual>();
374 res->val = 1.0;
375 res->startInv = 0;
376 res->worstJac = std::numeric_limits<NekDouble>::max();
377
378 ElUtilSharedPtr elUtil = std::make_shared<ElUtil>(te.el, derivUtils[shape],
379 res, nummode, overInt);
380
381 // Move a node that is not one of the element's vertices, so that the
382 // straight-sided element the functional measures deformation against --
383 // which ElUtil builds from the vertices once, and does not revisit -- is
384 // genuinely independent of the node being differentiated.
385 std::set<SpatialDomains::PointGeom *> verts;
386 for (int i = 0; i < te.el->GetNumVerts(); ++i)
387 {
388 verts.insert(te.el->GetVertex(i));
389 }
390
391 SpatialDomains::PointGeom *node = nullptr;
392 for (auto *n : te.nodes)
393 {
394 if (verts.count(n) == 0)
395 {
396 node = n;
397 }
398 }
399 BOOST_REQUIRE(node != nullptr);
400
401 if (config == Config::eTangled)
402 {
403 (*node)[0] -= 0.9;
404 (*node)[1] -= 0.9;
405 }
406
407 // The regularisation parameter is set from the smallest Jacobian in the
408 // mesh, which CalcMinJac() reduces into the residual. It stays fixed
409 // across the differences below, so the functional really is the smooth
410 // function of the node position that the analytic expressions claim to
411 // differentiate.
412 res->minJac = std::numeric_limits<NekDouble>::max();
413 elUtil->CalcDeriv();
414 elUtil->CalcMinJac();
415
416 std::vector<ElUtilSharedPtr> els{elUtil};
417 NodeOptiSharedPtr nodeOpti = GetNodeOptiFactory().CreateInstance(
418 DIM * 11, node, els, res, derivUtils, opti, te.mesh->m_meshGraph.get());
419
420 const char *configName = config == Config::eValid ? " (valid)"
421 : config == Config::eTangled ? " (tangled)"
422 : " (inverted)";
423 std::string what =
424 optiName + " " + LibUtilities::ShapeTypeMap[shape] + configName;
425
426 if (config == Config::eTangled)
427 {
428 NekDouble minJac;
429 nodeOpti->GetFunctional<DIM>(minJac, false);
430 BOOST_REQUIRE_MESSAGE(minJac < 0.0,
431 what + ": element was meant to be tangled");
432 }
433
434 if (config == Config::eInverted)
435 {
436 BOOST_REQUIRE_MESSAGE(
437 elUtil->maps[9] < 0.0,
438 what + ": the ideal mapping was meant to be inverted");
439 }
440
441 CheckDerivatives<DIM>(nodeOpti, node, what);
442}
443
444const std::vector<std::pair<optiType, std::string>> functionals = {
445 {eLinEl, "linearelastic"},
446 {eHypEl, "hyperelastic"},
447 {eRoca, "distortion"},
448 {eWins, "winslow"}};
449
450} // namespace
451
452BOOST_AUTO_TEST_CASE(TestDerivatives2D)
453{
454 for (auto &[opti, name] : functionals)
455 {
456 {
458 for (Config config :
459 {Config::eValid, Config::eTangled, Config::eInverted})
460 {
461 RunCase<2>(shape, opti, name, config);
462 }
463 }
464 }
465}
466
467BOOST_AUTO_TEST_CASE(TestDerivatives3D)
468{
469 for (auto &[opti, name] : functionals)
470 {
471 {
473 for (Config config :
474 {Config::eValid, Config::eTangled, Config::eInverted})
475 {
476 RunCase<3>(shape, opti, name, config);
477 }
478 }
479 }
480}
481
482/**
483 * @brief Moving a node has to leave the derivatives its elements hold equal
484 * to what differentiating the moved mesh would give.
485 *
486 * Each element keeps the derivatives of its mapping at the integration
487 * points, worked out once per iteration, and the optimiser carries a node's
488 * movement through to them with a rank-one update rather than recomputing
489 * them. That update is what the functional is then evaluated from, so if it
490 * and the full computation ever disagree the optimiser is minimising
491 * something other than the energy of the mesh it is holding -- and it would
492 * not show, because the next iteration recomputes them from scratch and
493 * quietly papers over it.
494 */
495BOOST_AUTO_TEST_CASE(TestMovedNodeDerivatives)
496{
497 const int nummode = 4;
498 const int overInt = 2;
499
501 {
502 const int dim = (shape == LibUtilities::eTriangle) ? 2 : 3;
503
504 TestElement te = MakeElement(shape, nummode, 7u, false);
505
506 std::map<LibUtilities::ShapeType, DerivUtilSharedPtr> derivUtils =
507 BuildDerivUtil(nummode, overInt);
508
509 ResidualSharedPtr res = std::make_shared<Residual>();
510 res->worstJac = std::numeric_limits<NekDouble>::max();
511 res->minJac = std::numeric_limits<NekDouble>::max();
512
513 ElUtilSharedPtr elUtil = std::make_shared<ElUtil>(
514 te.el, derivUtils[shape], res, nummode, overInt);
515
516 elUtil->CalcDeriv();
517
518 // Move a node, and bring the stored derivatives along with it.
519 SpatialDomains::PointGeom *node = te.nodes.back();
520 const NekDouble offset[3] = {0.031, -0.047, 0.013};
521
522 elUtil->MoveNode(elUtil->NodeId(node), offset, dim);
523 for (int d = 0; d < dim; ++d)
524 {
525 (*node)[d] += offset[d];
526 }
527
528 std::vector<NekDouble> updated = elUtil->deriv;
529
530 // Now work them out again from the moved mesh.
531 elUtil->CalcDeriv();
532
533 BOOST_REQUIRE_EQUAL(updated.size(), elUtil->deriv.size());
534
535 NekDouble scale = 0.0, worst = 0.0;
536 for (size_t i = 0; i < updated.size(); ++i)
537 {
538 scale = std::max(scale, std::fabs(elUtil->deriv[i]));
539 worst = std::max(worst, std::fabs(updated[i] - elUtil->deriv[i]));
540 }
541
542 BOOST_CHECK_MESSAGE(worst < 1e-12 * std::max(scale, 1e-12),
544 << ": the rank-one update left the "
545 << "derivatives differing by " << worst);
546 }
547}
548
549/**
550 * @brief The Newton direction has to solve H sk = -G.
551 *
552 * NodeOpti3D3D::Optimise() inverts the 3x3 Hessian through its cofactors.
553 * Two of the nine were wrong, which left the search direction unrelated to
554 * the Newton direction; on the badly conditioned Hessians that the
555 * regularisation produces while untangling, roughly a third of the directions
556 * that resulted pointed uphill, and the Wolfe condition accepts an uphill
557 * step whenever the direction it is handed is not a descent direction. The
558 * mesh still improved, so nothing about the result said that the optimiser
559 * was no longer doing Newton's method.
560 *
561 * The Hessians used here have the eigenvalue spread the regularisation leaves
562 * behind, one of them sitting at the floor of 1e-6.
563 */
564BOOST_AUTO_TEST_CASE(TestNewtonDirection)
565{
566 Jitter jitter(99u);
567
568 for (int t = 0; t < 500; ++t)
569 {
570 NekDouble a[3][3];
571 for (int i = 0; i < 3; ++i)
572 {
573 for (int j = 0; j < 3; ++j)
574 {
575 a[i][j] = jitter();
576 }
577 }
578
579 NekDouble H[3][3];
580 for (int i = 0; i < 3; ++i)
581 {
582 for (int j = 0; j < 3; ++j)
583 {
584 H[i][j] = (i == j) ? 1e-6 : 0.0;
585 for (int k = 0; k < 3; ++k)
586 {
587 H[i][j] += a[i][k] * a[j][k];
588 }
589 }
590 }
591
592 std::vector<NekDouble> grad3 = {jitter(), jitter(), jitter(),
593 H[0][0], H[0][1], H[0][2],
594 H[1][1], H[1][2], H[2][2]};
595
596 NekDouble sk3[3];
597 NewtonDirection<3>(grad3.data(), sk3);
598
599 NekDouble normH = 0.0, normSk = 0.0;
600 for (int i = 0; i < 3; ++i)
601 {
602 normSk = std::max(normSk, std::fabs(sk3[i]));
603 for (int j = 0; j < 3; ++j)
604 {
605 normH = std::max(normH, std::fabs(H[i][j]));
606 }
607 }
608
609 for (int i = 0; i < 3; ++i)
610 {
611 NekDouble Hsk = 0.0;
612 for (int j = 0; j < 3; ++j)
613 {
614 Hsk += H[i][j] * sk3[j];
615 }
616 BOOST_CHECK_SMALL(Hsk + grad3[i], 1e-9 * normH * normSk);
617 }
618
619 BOOST_CHECK_LT(
620 grad3[0] * sk3[0] + grad3[1] * sk3[1] + grad3[2] * sk3[2], 0.0);
621
622 // The same again in two dimensions, on the leading 2x2 block.
623 std::array<NekDouble, 5> grad2 = {grad3[0], grad3[1], H[0][0], H[0][1],
624 H[1][1]};
625 NekDouble sk2[2];
626 NewtonDirection<2>(grad2.data(), sk2);
627
628 for (int i = 0; i < 2; ++i)
629 {
630 NekDouble Hsk = 0.0;
631 for (int j = 0; j < 2; ++j)
632 {
633 Hsk += H[i][j] * sk2[j];
634 }
635 BOOST_CHECK_SMALL(
636 Hsk + grad2[i],
637 1e-9 * normH * std::max(std::fabs(sk2[0]), std::fabs(sk2[1])));
638 }
639
640 BOOST_CHECK_LT(grad2[0] * sk2[0] + grad2[1] * sk2[1], 0.0);
641 }
642}
643
644} // namespace Nektar::NekMeshVarOptiDerivativeUnitTest
SpatialDomains::MeshGraphSharedPtr graph
std::map< int64_t, double > sum
std::mt19937 m_rng
MeshSharedPtr mesh
SpatialDomains::Geometry * el
std::vector< SpatialDomains::PointGeom * > nodes
std::vector< NekDouble > grad
std::vector< std::vector< NekDouble > > hess
Basic logging class for the NekMesh library.
Definition Log.hpp:218
const char *const ShapeTypeMap[SIZE_ShapeType]
Definition ShapeType.hpp:83
@ eGaussLobattoLegendre
1D Gauss-Lobatto-Legendre quadrature points
Definition PointsType.h:51
std::vector< double > d(NPUPPER *NPUPPER)
scalarT< T > log(scalarT< T > in)
Definition scalar.hpp:309