Nektar++
PtsIO.cpp
Go to the documentation of this file.
1////////////////////////////////////////////////////////////////////////////////
2//
3// File: PtsIO.cpp
4//
5// For more information, please see: http://www.nektar.info/
6//
7// The MIT License
8//
9// Copyright (c) 2014 Kilian Lackhove
10// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
11// Department of Aeronautics, Imperial College London (UK), and Scientific
12// Computing and Imaging Institute, University of Utah (USA).
13//
14// Permission is hereby granted, free of charge, to any person obtaining a
15// copy of this software and associated documentation files (the "Software"),
16// to deal in the Software without restriction, including without limitation
17// the rights to use, copy, modify, merge, publish, distribute, sublicense,
18// and/or sell copies of the Software, and to permit persons to whom the
19// Software is furnished to do so, subject to the following conditions:
20//
21// The above copyright notice and this permission notice shall be included
22// in all copies or substantial portions of the Software.
23//
24// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
25// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
29// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
30// DEALINGS IN THE SOFTWARE.
31//
32// Description: I/O routines relating to Pts data
33//
34////////////////////////////////////////////////////////////////////////////////
35
37#include <boost/algorithm/string.hpp>
38
39#include <fstream>
40
41#include <boost/format.hpp>
42
43#ifdef NEKTAR_USE_MPI
44#include <mpi.h>
45#endif
46
49
50using namespace std;
51
53{
54
55PtsIO::PtsIO(CommSharedPtr pComm, bool sharedFilesystem)
56 : FieldIOXml(pComm, sharedFilesystem)
57{
58}
59
60/**
61 * @brief Import a pts field from file
62 *
63 * @param inFile filename of the file to read
64 * @param ptsField the resulting pts field.
65 */
66void PtsIO::Import(const string &inFile, PtsFieldSharedPtr &ptsField,
67 FieldMetaDataMap &fieldmetadatamap, DomainRangeShPtr &Range)
68{
69 std::string infile = inFile;
70
71 fs::path pinfilename(infile);
72
73 // check to see that infile is a directory
74 if (fs::is_directory(pinfilename))
75 {
76 fs::path infofile("Info.xml");
77 fs::path fullpath = pinfilename / infofile;
78 infile = PortablePath(fullpath);
79
80 std::vector<std::string> filenames;
81 std::vector<std::vector<unsigned int>> elementIDs_OnPartitions;
82
83 ImportMultiFldFileIDs(infile, filenames, elementIDs_OnPartitions,
84 fieldmetadatamap);
85
86 // Load metadata
87 ImportFieldMetaData(infile, fieldmetadatamap);
88
89 if (filenames.size() == m_comm->GetSpaceComm()->GetSize())
90 {
91 // only load the file that matches this rank
92 filenames.clear();
93 boost::format pad("P%1$07d.%2$s");
94 pad % m_comm->GetSpaceComm()->GetRank() % GetFileEnding();
95 filenames.push_back(pad.str());
96 }
97
98 for (int i = 0; i < filenames.size(); ++i)
99 {
100 fs::path pfilename(filenames[i]);
101 fullpath = pinfilename / pfilename;
102 string fname = PortablePath(fullpath);
103
104 if (i == 0)
105 {
106 v_ImportPtsFieldData(fname, ptsField, Range);
107 }
108 else
109 {
111 v_ImportPtsFieldData(fname, newPtsField, Range);
113 newPtsField->GetPts(pts);
114 ptsField->AddPoints(pts);
115 }
116 }
117 }
118 else
119 {
120 v_ImportPtsFieldData(infile, ptsField, Range);
121 }
122}
123
124/**
125 * @brief Save a pts field to a file
126 *
127 * @param outFile filename of the file
128 * @param ptsField the pts field
129 */
130void PtsIO::Write(const string &outFile,
132 const bool backup)
133{
134 size_t nTotvars = ptsField->GetNFields() + ptsField->GetDim();
135 size_t np = ptsField->GetNpoints();
136
137 std::string filename = SetUpOutput(outFile, true, backup);
138 SetUpFieldMetaData(outFile);
139
140 // until tinyxml gains support for line break, write the xml manually
141 std::ofstream ptsFile;
142 ptsFile.open(filename.c_str());
143
144 ptsFile << R"(<?xml version="1.0" encoding="utf-8" ?>)" << endl;
145 ptsFile << "<NEKTAR>" << endl;
146 ptsFile << " <POINTS ";
147 ptsFile << "DIM=\"" << ptsField->GetDim() << "\" ";
148 string fn = boost::algorithm::join(ptsField->GetFieldNames(), ",");
149 ptsFile << "FIELDS=\"" << fn << "\" ";
150 ptsFile << ">" << endl;
151
153 ptsField->GetPts(pts);
154 for (size_t i = 0; i < np; ++i)
155 {
156 ptsFile << " ";
157 ptsFile << pts[0][i];
158 for (size_t j = 1; j < nTotvars; ++j)
159 {
160 ptsFile << " " << pts[j][i];
161 }
162 ptsFile << endl;
163 }
164 ptsFile << " </POINTS>" << endl;
165 ptsFile << "</NEKTAR>" << endl;
166
167 ptsFile.close();
168}
169
170/**
171 *
172 */
173void PtsIO::v_ImportPtsFieldData(const string inFile,
174 PtsFieldSharedPtr &ptsField,
175 [[maybe_unused]] DomainRangeShPtr &Range)
176{
177 TiXmlDocument docInput(inFile);
178 bool loadOkay1 = docInput.LoadFile();
179
180 std::stringstream errstr;
181 errstr << "Unable to load file: " << inFile << std::endl;
182 errstr << "Reason: " << docInput.ErrorDesc() << std::endl;
183 errstr << "Position: Line " << docInput.ErrorRow() << ", Column "
184 << docInput.ErrorCol() << std::endl;
185 ASSERTL0(loadOkay1, errstr.str());
186
187 TiXmlElement *nektar = docInput.FirstChildElement("NEKTAR");
188 TiXmlElement *points = nektar->FirstChildElement("POINTS");
189 int dim;
190 int err = points->QueryIntAttribute("DIM", &dim);
191
192 ASSERTL0(err == TIXML_SUCCESS, "Unable to read attribute DIM.");
193
194 std::string fields = points->Attribute("FIELDS");
195
196 vector<string> fieldNames;
197 if (!fields.empty())
198 {
199 bool valid = ParseUtils::GenerateVector(fields, fieldNames);
200 ASSERTL0(
201 valid,
202 "Unable to process list of field variable in FIELDS attribute: " +
203 fields);
204 }
205
206 map<PtsInfo, int> ptsInfo = NullPtsInfoMap;
207
208 const char *ptinfo = points->Attribute("PTSINFO");
209 if (ptinfo && boost::iequals(ptinfo, "EquiSpaced"))
210 {
211 ptsInfo[eIsEquiSpacedData] = 1;
212 }
213
214 int np;
215 err = points->QueryIntAttribute("PTSPERELMTEDGE", &np);
216 if (err == TIXML_SUCCESS)
217 {
218 ptsInfo[ePtsPerElmtEdge] = np;
219 }
220
221 size_t nfields = fieldNames.size();
222 size_t totvars = dim + nfields;
223
224 TiXmlNode *pointsBody = points->FirstChild();
225
226 std::istringstream pointsDataStrm(pointsBody->ToText()->Value());
227
228 vector<NekDouble> ptsSerial;
230
231 try
232 {
233 NekDouble ptsStream;
234 while (!pointsDataStrm.fail())
235 {
236 pointsDataStrm >> ptsStream;
237
238 ptsSerial.push_back(ptsStream);
239 }
240 }
241 catch (...)
242 {
243 NEKERROR(ErrorUtil::efatal, "Unable to read Points data.");
244 }
245
246 size_t npts = ptsSerial.size() / totvars;
247
248 for (size_t i = 0; i < totvars; ++i)
249 {
250 pts[i] = Array<OneD, NekDouble>(npts);
251 }
252
253 for (size_t i = 0; i < npts; ++i)
254 {
255 for (size_t j = 0; j < totvars; ++j)
256 {
257 pts[j][i] = ptsSerial[i * totvars + j];
258 }
259 }
260
261 ptsField = MemoryManager<PtsField>::AllocateSharedPtr(dim, fieldNames, pts,
262 ptsInfo);
263}
264
265/**
266 *
267 */
268void PtsIO::SetUpFieldMetaData(const string outname)
269{
270 ASSERTL0(!outname.empty(), "Empty path given to SetUpFieldMetaData()");
271
272 int nprocs = m_comm->GetSpaceComm()->GetSize();
273 int rank = m_comm->GetSpaceComm()->GetRank();
274
275 fs::path specPath(outname);
276
277 // Collate per-process element lists on root process to generate
278 // the info file.
279 if (rank == 0)
280 {
281 // Set up output names
282 std::vector<std::string> filenames;
283 std::vector<std::vector<unsigned int>> ElementIDs;
284 for (int i = 0; i < nprocs; ++i)
285 {
286 boost::format pad("P%1$07d.%2$s");
287 pad % i % GetFileEnding();
288 filenames.push_back(pad.str());
289
290 std::vector<unsigned int> tmp;
291 tmp.push_back(0);
292 ElementIDs.push_back(tmp);
293 }
294
295 // Write the Info.xml file
296 string infofile =
297 LibUtilities::PortablePath(specPath / fs::path("Info.xml"));
298
299 cout << "Writing: " << specPath << endl;
300
301 const FieldMetaDataMap fieldmetadatamap;
302 WriteMultiFldFileIDs(infofile, filenames, ElementIDs, fieldmetadatamap);
303 }
304}
305} // namespace Nektar::LibUtilities
#define ASSERTL0(condition, msg)
Definition: ErrorUtil.hpp:208
#define NEKERROR(type, msg)
Assert Level 0 – Fundamental assert which is used whether in FULLDEBUG, DEBUG or OPT compilation mode...
Definition: ErrorUtil.hpp:202
DataSourceSharedPtr ImportFieldMetaData(const std::string &filename, FieldMetaDataMap &fieldmetadatamap)
Import the metadata from a field file.
Definition: FieldIO.h:371
std::string SetUpOutput(const std::string outname, bool perRank, bool backup=false)
Set up the filesystem ready for output.
Definition: FieldIO.cpp:404
LibUtilities::CommSharedPtr m_comm
Communicator to use when writing parallel format.
Definition: FieldIO.h:280
std::string GetFileEnding() const
Helper function that determines default file extension.
Definition: FieldIO.h:273
void ImportMultiFldFileIDs(const std::string &inFile, std::vector< std::string > &fileNames, std::vector< std::vector< unsigned int > > &elementList, FieldMetaDataMap &fieldmetadatamap)
Read file containing element ID to partition mapping.
Definition: FieldIOXml.cpp:419
void WriteMultiFldFileIDs(const std::string &outfile, const std::vector< std::string > fileNames, std::vector< std::vector< unsigned int > > &elementList, const FieldMetaDataMap &fieldinfomap=NullFieldMetaDataMap)
Write out a file containing element ID to partition mapping.
Definition: FieldIOXml.cpp:372
void Write(const std::string &outFile, const PtsFieldSharedPtr &ptsField, const bool backup=false)
Save a pts field to a file.
Definition: PtsIO.cpp:130
PtsIO(LibUtilities::CommSharedPtr pComm, bool sharedFilesystem=false)
Definition: PtsIO.cpp:55
void SetUpFieldMetaData(const std::string outname)
Definition: PtsIO.cpp:268
virtual void v_ImportPtsFieldData(const std::string inFile, PtsFieldSharedPtr &ptsField, DomainRangeShPtr &Range=NullDomainRangeShPtr)
Definition: PtsIO.cpp:173
void Import(const std::string &inFile, PtsFieldSharedPtr &ptsField, FieldMetaDataMap &fieldmetadatamap=NullFieldMetaDataMap, DomainRangeShPtr &Range=NullDomainRangeShPtr)
Import a pts field from file.
Definition: PtsIO.cpp:66
static std::shared_ptr< DataType > AllocateSharedPtr(const Args &...args)
Allocate a shared pointer from the memory pool.
static bool GenerateVector(const std::string &str, std::vector< T > &out)
Takes a comma-separated string and converts it to entries in a vector.
Definition: ParseUtils.cpp:130
static std::map< PtsInfo, int > NullPtsInfoMap
Definition: PtsField.h:66
std::map< std::string, std::string > FieldMetaDataMap
Definition: FieldIO.h:50
static std::string PortablePath(const fs::path &path)
create portable path on different platforms for std::filesystem path.
Definition: Filesystem.hpp:56
std::shared_ptr< PtsField > PtsFieldSharedPtr
Definition: PtsField.h:184
std::shared_ptr< DomainRange > DomainRangeShPtr
Definition: DomainRange.h:64
std::shared_ptr< Comm > CommSharedPtr
Pointer to a Communicator object.
Definition: Comm.h:55
double NekDouble