Nektar++
Loading...
Searching...
No Matches
TestFieldFileRoundTrip.cpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: TestFieldFileRoundTrip.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: Field file write/read round trip, the path a restart takes.
32//
33///////////////////////////////////////////////////////////////////////////////
34
38
41
42#include <boost/test/unit_test.hpp>
43
44#include <cstring>
45#include <fstream>
46#include <string>
47#include <vector>
48
50{
51
52/**
53 * A mesh of two quadrilaterals and four triangles over the unit square. The
54 * two shapes are the point of it: ExpList::GetFieldDefinitions() emits one
55 * field definition per shape, and a reader that handles only the last of them
56 * is the failure this test exists to catch. A single shape mesh cannot see it.
57 */
58static const std::string sessionTemplate =
59 R"END(<?xml version="1.0" encoding="UTF-8"?>
60<NEKTAR>
61 <GEOMETRY DIM="2" SPACE="2">
62
63 <VERTEX>
64 <V ID="0"> 0.0 0.0 0.0 </V>
65 <V ID="1"> 0.5 0.0 0.0 </V>
66 <V ID="2"> 1.0 0.0 0.0 </V>
67 <V ID="3"> 0.0 0.5 0.0 </V>
68 <V ID="4"> 0.5 0.5 0.0 </V>
69 <V ID="5"> 1.0 0.5 0.0 </V>
70 <V ID="6"> 0.0 1.0 0.0 </V>
71 <V ID="7"> 0.5 1.0 0.0 </V>
72 <V ID="8"> 1.0 1.0 0.0 </V>
73 </VERTEX>
74
75 <EDGE>
76 <E ID="0"> 0 1 </E>
77 <E ID="1"> 1 2 </E>
78 <E ID="2"> 0 3 </E>
79 <E ID="3"> 1 4 </E>
80 <E ID="4"> 2 5 </E>
81 <E ID="5"> 3 4 </E>
82 <E ID="6"> 4 5 </E>
83 <E ID="7"> 3 6 </E>
84 <E ID="8"> 4 7 </E>
85 <E ID="9"> 5 8 </E>
86 <E ID="10"> 6 7 </E>
87 <E ID="11"> 7 8 </E>
88 <E ID="12"> 3 7 </E>
89 <E ID="13"> 4 8 </E>
90 </EDGE>
91
92 <ELEMENT>
93 <Q ID="0"> 0 3 5 2 </Q>
94 <Q ID="1"> 1 4 6 3 </Q>
95 <T ID="2"> 5 8 12 </T>
96 <T ID="3"> 12 10 7 </T>
97 <T ID="4"> 6 9 13 </T>
98 <T ID="5"> 13 11 8 </T>
99 </ELEMENT>
100
101 <COMPOSITE>
102 <C ID="0"> Q[0-1] </C>
103 <C ID="1"> T[2-5] </C>
104 </COMPOSITE>
105
106 <DOMAIN> C[0-1] </DOMAIN>
107
108 </GEOMETRY>
109
110 <EXPANSIONS>
111 <E COMPOSITE="C[0]" FIELDS="u" TYPE="@TYPE@" NUMMODES="@NMODES@"/>
112 <E COMPOSITE="C[1]" FIELDS="u" TYPE="@TYPE@" NUMMODES="@NMODES@"/>
113 </EXPANSIONS>
114
115 <CONDITIONS>
116 <PARAMETERS>
117 <P> TimeStep = 0.01 </P>
118 </PARAMETERS>
119
120 <VARIABLES>
121 <V ID="0"> u </V>
122 </VARIABLES>
123
124 <BOUNDARYREGIONS />
125 <BOUNDARYCONDITIONS />
126 </CONDITIONS>
127
128</NEKTAR>
129)END";
130
131/**
132 * @brief Write a coefficient vector to a field file and read it back.
133 *
134 * This is the path a restart takes: the solver projects its state to
135 * coefficients, ExpList::AppendFieldData() lays them out per field definition,
136 * and on resumption ExpList::ExtractDataToCoeffs() puts them back. The
137 * coefficients are the state, so anything the round trip loses is state the
138 * resumed run does not have.
139 *
140 * The reader is called once per field definition and accumulates into one
141 * vector, which is what makes a mesh of more than one element shape the
142 * interesting case: a reader that starts from zero each call returns only the
143 * shape it was given last and silently zeros the others. On this mesh that
144 * would leave the two quadrilaterals - the first 32 coefficients - at zero
145 * while the triangles survived.
146 */
147/// Substitute every occurrence of @p token in @p text with @p value.
148static void Substitute(std::string &text, const std::string &token,
149 const std::string &value)
150{
151 for (std::size_t at = text.find(token); at != std::string::npos;
152 at = text.find(token))
153 {
154 text.replace(at, token.size(), value);
155 }
156}
157
158/**
159 * @brief A uniquely named directory under the system temporary directory,
160 * removed with everything in it when the object goes out of scope.
161 *
162 */
164{
165 explicit ScratchDirectory(const std::string &stem)
166 : m_path(fs::temp_directory_path() / LibUtilities::UniquePath(stem))
167 {
168 fs::create_directories(m_path);
169 }
170
172 {
173 // Clean-up is best effort; a destructor must not throw.
174 try
175 {
176 fs::remove_all(m_path);
177 }
178 catch (...)
179 {
180 }
181 }
182
185
186 fs::path m_path;
187};
188
189static void RoundTrip(const std::string &expansionType)
190{
191 std::string sessionFile = sessionTemplate;
192 Substitute(sessionFile, "@TYPE@", expansionType);
193 Substitute(sessionFile, "@NMODES@", "4");
194
195 // Write the session out so the reader has a file to open.
196 ScratchDirectory scratch("FieldFileRoundTrip");
197 fs::path sessionPath = scratch.m_path / fs::path("FieldFileRoundTrip" +
198 expansionType + ".xml");
199 fs::path fieldPath = scratch.m_path / fs::path("FieldFileRoundTrip" +
200 expansionType + ".fld");
201
202 std::ofstream sessionOut(sessionPath.string());
203 sessionOut << sessionFile;
204 sessionOut.close();
205
206 int argc = 2;
207 std::string exe = "FieldFileRoundTrip";
208 std::string file = sessionPath.string();
209 char *argv[] = {exe.data(), file.data(), nullptr};
210
217
218 // Both shapes must be present, or the test cannot see the failure it is
219 // written for.
220 std::vector<LibUtilities::FieldDefinitionsSharedPtr> fieldDefs =
221 expList->GetFieldDefinitions();
222 BOOST_REQUIRE_MESSAGE(fieldDefs.size() > 1,
223 "Expected one field definition per element shape.");
224
225 // A distinct value per coefficient, so a misplaced one is visible rather
226 // than coincidentally right.
227 const int nCoeffs = expList->GetNcoeffs();
228 std::vector<NekDouble> written(nCoeffs);
229 for (int i = 0; i < nCoeffs; ++i)
230 {
231 written[i] = 1.0 + 0.25 * i;
232 }
233
234 std::vector<std::vector<NekDouble>> fieldData(fieldDefs.size());
235 for (std::size_t i = 0; i < fieldDefs.size(); ++i)
236 {
237 fieldDefs[i]->m_fields.push_back("u");
238 expList->AppendFieldData(fieldDefs[i], fieldData[i], written);
239 }
240
243 fieldIO->Write(fieldPath.string(), fieldDefs, fieldData);
244
245 // Read it back the way a restart does.
246 std::vector<LibUtilities::FieldDefinitionsSharedPtr> readDefs;
247 std::vector<std::vector<NekDouble>> readData;
248 fieldIO->Import(fieldPath.string(), readDefs, readData);
249
250 std::string variable = "u";
251 std::vector<NekDouble> read(nCoeffs, 0.0);
252 for (std::size_t i = 0; i < readDefs.size(); ++i)
253 {
254 expList->ExtractDataToCoeffs(readDefs[i], readData[i], variable, read);
255 }
256
257 for (int i = 0; i < nCoeffs; ++i)
258 {
259 BOOST_CHECK_CLOSE(read[i], written[i], 1.0e-8);
260 }
261
262 session->Finalise();
263}
264
265/**
266 * @brief Round trip a coefficient vector through a different polynomial order
267 * and back.
268 *
269 * Restarting at the order the file was written at is the easy case:
270 * ExpList::ExtractDataToCoeffs() sees a matching mode count and basis and
271 * copies the element's coefficients straight across, never consulting the
272 * expansion. Restarting at a *different* order is what sends it into the per
273 * element routine, which switches on the basis type and knows how to place
274 * mode (i,j) of one order among the modes of another. A basis that switch does
275 * not name cannot be read at all.
276 *
277 * Writing at one order, reading at a higher one and coming back is exact for a
278 * hierarchical basis - the added modes are zero and are dropped again - so the
279 * original coefficients are the expected answer, without the test needing to
280 * know how the modes are laid out.
281 */
282static void RoundTripOrderChange(const std::string &expansionType)
283{
284 ScratchDirectory scratch("FieldOrderChange");
285
286 auto build = [&expansionType, &scratch](const std::string &numModes,
287 const std::string &tag) {
288 std::string text = sessionTemplate;
289 Substitute(text, "@TYPE@", expansionType);
290 Substitute(text, "@NMODES@", numModes);
291
292 fs::path path = scratch.m_path / fs::path("FieldOrderChange" +
293 expansionType + tag + ".xml");
294 std::ofstream out(path.string());
295 out << text;
296 out.close();
297 return path;
298 };
299
300 fs::path lowPath = build("4", "Low");
301 fs::path highPath = build("5", "High");
302 fs::path fieldLow = scratch.m_path / fs::path("FieldOrderChange" +
303 expansionType + "Low.fld");
304 fs::path fieldHigh = scratch.m_path / fs::path("FieldOrderChange" +
305 expansionType + "High.fld");
306
307 std::string exe = "FieldOrderChange";
308 std::string lowFile = lowPath.string();
309 std::string highFile = highPath.string();
310
311 int argc = 2;
312 char *argvLow[] = {exe.data(), lowFile.data(), nullptr};
319 graphLow);
320
321 char *argvHigh[] = {exe.data(), highFile.data(), nullptr};
328 graphHigh);
329
330 BOOST_REQUIRE(expLow->GetNcoeffs() != expHigh->GetNcoeffs());
331
332 // Writes @p coeffs from @p exp into a field file.
333 auto writeField = [](const MultiRegions::ExpListSharedPtr &exp,
335 std::vector<NekDouble> &coeffs, const fs::path &path) {
336 std::vector<LibUtilities::FieldDefinitionsSharedPtr> defs =
337 exp->GetFieldDefinitions();
338 std::vector<std::vector<NekDouble>> data(defs.size());
339 for (std::size_t i = 0; i < defs.size(); ++i)
340 {
341 defs[i]->m_fields.push_back("u");
342 exp->AppendFieldData(defs[i], data[i], coeffs);
343 }
344 LibUtilities::FieldIO::CreateDefault(session)->Write(path.string(),
345 defs, data);
346 };
347
348 // Reads a field file back into a coefficient vector sized for @p exp.
349 auto readField = [](const MultiRegions::ExpListSharedPtr &exp,
351 const fs::path &path) {
352 std::vector<LibUtilities::FieldDefinitionsSharedPtr> defs;
353 std::vector<std::vector<NekDouble>> data;
354 LibUtilities::FieldIO::CreateDefault(session)->Import(path.string(),
355 defs, data);
356 std::string variable = "u";
357 std::vector<NekDouble> coeffs(exp->GetNcoeffs(), 0.0);
358 for (std::size_t i = 0; i < defs.size(); ++i)
359 {
360 exp->ExtractDataToCoeffs(defs[i], data[i], variable, coeffs);
361 }
362 return coeffs;
363 };
364
365 std::vector<NekDouble> written(expLow->GetNcoeffs());
366 for (std::size_t i = 0; i < written.size(); ++i)
367 {
368 written[i] = 1.0 + 0.25 * static_cast<NekDouble>(i);
369 }
370
371 writeField(expLow, sessionLow, written, fieldLow);
372
373 // Up to the higher order, then back down.
374 std::vector<NekDouble> raised = readField(expHigh, sessionHigh, fieldLow);
375 writeField(expHigh, sessionHigh, raised, fieldHigh);
376 std::vector<NekDouble> read = readField(expLow, sessionLow, fieldHigh);
377
378 BOOST_REQUIRE_EQUAL(read.size(), written.size());
379 for (std::size_t i = 0; i < written.size(); ++i)
380 {
381 BOOST_CHECK_CLOSE(read[i], written[i], 1.0e-8);
382 }
383
384 sessionLow->Finalise();
385 sessionHigh->Finalise();
386}
387
388/// The modified basis, which is what almost every session uses.
389BOOST_AUTO_TEST_CASE(TestFieldFileRoundTripHybridMeshModified)
390{
391 RoundTrip("MODIFIED");
392}
393
394/**
395 * The orthogonal basis, whose second direction is eOrtho_B rather than
396 * eModified_B. The per-element extraction asserts on the basis it is given,
397 * so a basis it does not name cannot be read back at all - the failure is an
398 * assertion rather than wrong numbers, and no modified-basis session reaches
399 * it.
400 */
401BOOST_AUTO_TEST_CASE(TestFieldFileRoundTripHybridMeshOrthogonal)
402{
403 RoundTrip("ORTHOGONAL");
404}
405
406/// Restarting at a different order, which is what reaches the per element
407/// extraction, for each basis.
408BOOST_AUTO_TEST_CASE(TestFieldFileOrderChangeModified)
409{
410 RoundTripOrderChange("MODIFIED");
411}
412
413BOOST_AUTO_TEST_CASE(TestFieldFileOrderChangeOrthogonal)
414{
415 RoundTripOrderChange("ORTHOGONAL");
416}
417
418} // namespace Nektar::FieldFileRoundTripTest
LibUtilities::SessionReaderSharedPtr session
SpatialDomains::MeshGraphSharedPtr graph
static std::shared_ptr< FieldIO > CreateDefault(const LibUtilities::SessionReaderSharedPtr session)
Returns an object for the default FieldIO method.
Definition FieldIO.cpp:194
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 MeshGraphSharedPtr Read(const LibUtilities::SessionReaderSharedPtr pSession, LibUtilities::DomainRangeShPtr rng=LibUtilities::NullDomainRangeShPtr, bool fillGraph=true, SpatialDomains::MeshGraphSharedPtr partitionedGraph=nullptr)
static void Substitute(std::string &text, const std::string &token, const std::string &value)
Write a coefficient vector to a field file and read it back.
static void RoundTripOrderChange(const std::string &expansionType)
Round trip a coefficient vector through a different polynomial order and back.
static const std::string sessionTemplate
BOOST_AUTO_TEST_CASE(TestFieldFileRoundTripHybridMeshModified)
The modified basis, which is what almost every session uses.
static void RoundTrip(const std::string &expansionType)
std::shared_ptr< FieldIO > FieldIOSharedPtr
Definition FieldIO.h:322
std::shared_ptr< SessionReader > SessionReaderSharedPtr
static fs::path UniquePath(std::string specFileStem)
Create a unique (random) path, based on an input stem string. The returned string is a filename or di...
std::shared_ptr< ExpList > ExpListSharedPtr
Shared pointer to an ExpList object.
std::shared_ptr< MeshGraph > MeshGraphSharedPtr
Definition MeshGraph.h:287
A uniquely named directory under the system temporary directory, removed with everything in it when t...
ScratchDirectory & operator=(const ScratchDirectory &)=delete
ScratchDirectory(const ScratchDirectory &)=delete