Nektar++
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
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 
36 #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 
50 
51 
52 using namespace std;
53 
54 namespace Nektar
55 {
56 namespace LibUtilities
57 {
58 
59 
60 PtsIO::PtsIO(CommSharedPtr pComm, bool sharedFilesystem)
61  : FieldIOXml(pComm, sharedFilesystem)
62 {
63 }
64 
65 /**
66  * @brief Import a pts field from file
67  *
68  * @param inFile filename of the file to read
69  * @param ptsField the resulting pts field.
70  */
71 void PtsIO::Import(const string &inFile,
72  PtsFieldSharedPtr &ptsField,
73  FieldMetaDataMap &fieldmetadatamap,
74  DomainRangeShPtr &Range)
75 {
76  std::string infile = inFile;
77 
78  fs::path pinfilename(infile);
79 
80  // check to see that infile is a directory
81  if (fs::is_directory(pinfilename))
82  {
83  fs::path infofile("Info.xml");
84  fs::path fullpath = pinfilename / infofile;
85  infile = PortablePath(fullpath);
86 
87  std::vector<std::string> filenames;
88  std::vector<std::vector<unsigned int> > elementIDs_OnPartitions;
89 
91  infile, filenames, elementIDs_OnPartitions, fieldmetadatamap);
92 
93  // Load metadata
94  ImportFieldMetaData(infile, fieldmetadatamap);
95 
96  if (filenames.size() == m_comm->GetSize())
97  {
98  // only load the file that matches this rank
99  filenames.clear();
100  boost::format pad("P%1$07d.%2$s");
101  pad % m_comm->GetRank() % GetFileEnding();
102  filenames.push_back(pad.str());
103  }
104 
105  for (int i = 0; i < filenames.size(); ++i)
106  {
107  fs::path pfilename(filenames[i]);
108  fullpath = pinfilename / pfilename;
109  string fname = PortablePath(fullpath);
110 
111  if (i == 0)
112  {
113  ImportFieldData(fname, ptsField, Range);
114  }
115  else
116  {
118  ImportFieldData(fname, newPtsField, Range);
120  newPtsField->GetPts(pts);
121  ptsField->AddPoints(pts);
122  }
123 
124  }
125  }
126  else
127  {
128  ImportFieldData(infile, ptsField, Range);
129  }
130 }
131 
132 /**
133  * @brief Save a pts field to a file
134  *
135  * @param outFile filename of the file
136  * @param ptsField the pts field
137  */
138 void PtsIO::Write(const string &outFile,
140  const bool backup)
141 {
142  size_t nTotvars = ptsField->GetNFields() + ptsField->GetDim();
143  size_t np = ptsField->GetNpoints();
144 
145  std::string filename = SetUpOutput(outFile, true, backup);
146  SetUpFieldMetaData(outFile);
147 
148  // until tinyxml gains support for line break, write the xml manually
149  std::ofstream ptsFile;
150  ptsFile.open(filename.c_str());
151 
152  ptsFile << "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" << endl;
153  ptsFile << "<NEKTAR>" << endl;
154  ptsFile << " <POINTS ";
155  ptsFile << "DIM=\"" << ptsField->GetDim() << "\" ";
156  string fn = boost::algorithm::join(ptsField->GetFieldNames(), ",");
157  ptsFile << "FIELDS=\"" << fn << "\" ";
158  ptsFile << ">" << endl;
159 
161  ptsField->GetPts(pts);
162  for (size_t i = 0; i < np; ++i)
163  {
164  ptsFile << " ";
165  ptsFile << pts[0][i];
166  for (size_t j = 1; j < nTotvars; ++j)
167  {
168  ptsFile << " " << pts[j][i];
169  }
170  ptsFile << endl;
171  }
172  ptsFile << " </POINTS>" << endl;
173  ptsFile << "</NEKTAR>" << endl;
174 
175  ptsFile.close();
176 
177  // this is what the above cpart would read if tinyxml
178  // supported line breaks
179  /*
180  // Create the file (partition)
181  TiXmlDocument doc;
182  TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "utf-8", "");
183  doc.LinkEndChild(decl);
184 
185  TiXmlElement *root = new TiXmlElement("NEKTAR");
186  doc.LinkEndChild(root);
187 
188  TiXmlElement *pointsTag = new TiXmlElement("POINTS");
189  root->LinkEndChild(pointsTag);
190 
191  pointsTag->SetAttribute("DIM", ptsField->GetDim());
192 
193  string fn = boost::algorithm::join(ptsField->GetFieldNames(), ",");
194  pointsTag->SetAttribute("FIELDS", fn);
195 
196  Array <OneD, Array <OneD, NekDouble > > pts;
197  ptsField->GetPts(pts);
198  ostringstream os;
199  for (int i = 0; i < np; ++i)
200  {
201  os << pts[0][i];
202  for (int j = 1; j < nTotvars; ++j)
203  {
204  os << " " << pts[j][i];
205  }
206  os << " ";
207  }
208 
209  pointsTag->LinkEndChild(new TiXmlText(os.str()));
210 
211  doc.SaveFile(filename);
212  */
213 }
214 void PtsIO::ImportFieldData(const string inFile, PtsFieldSharedPtr &ptsField, DomainRangeShPtr &Range)
215 {
216  v_ImportFieldData(inFile, ptsField, Range);
217 }
218 
219 
220 void PtsIO::v_ImportFieldData(const string inFile, PtsFieldSharedPtr &ptsField, DomainRangeShPtr &Range)
221 {
222  boost::ignore_unused(Range);
223  TiXmlDocument docInput(inFile);
224  bool loadOkay1 = docInput.LoadFile();
225 
226  std::stringstream errstr;
227  errstr << "Unable to load file: " << inFile << std::endl;
228  errstr << "Reason: " << docInput.ErrorDesc() << std::endl;
229  errstr << "Position: Line " << docInput.ErrorRow() << ", Column "
230  << docInput.ErrorCol() << std::endl;
231  ASSERTL0(loadOkay1, errstr.str());
232 
233  TiXmlElement *nektar = docInput.FirstChildElement("NEKTAR");
234  TiXmlElement *points = nektar->FirstChildElement("POINTS");
235  int dim;
236  int err = points->QueryIntAttribute("DIM", &dim);
237 
238  ASSERTL0(err == TIXML_SUCCESS, "Unable to read attribute DIM.");
239 
240  std::string fields = points->Attribute("FIELDS");
241 
242  vector<string> fieldNames;
243  if (!fields.empty())
244  {
245  bool valid =
246  ParseUtils::GenerateVector(fields, fieldNames);
247  ASSERTL0(
248  valid,
249  "Unable to process list of field variable in FIELDS attribute: " +
250  fields);
251  }
252 
253  map<PtsInfo,int> ptsInfo = NullPtsInfoMap;
254 
255  const char *ptinfo = points->Attribute("PTSINFO");
256  if(ptinfo&&boost::iequals(ptinfo,"EquiSpaced"))
257  {
258  ptsInfo[eIsEquiSpacedData] = 1;
259  }
260 
261  int np;
262  err = points->QueryIntAttribute("PTSPERELMTEDGE",&np);
263  if(err == TIXML_SUCCESS)
264  {
265  ptsInfo[ePtsPerElmtEdge] = np;
266  }
267 
268  size_t nfields = fieldNames.size();
269  size_t totvars = dim + nfields;
270 
271  TiXmlNode *pointsBody = points->FirstChild();
272 
273  std::istringstream pointsDataStrm(pointsBody->ToText()->Value());
274 
275  vector<NekDouble> ptsSerial;
276  Array<OneD, Array<OneD, NekDouble> > pts(totvars);
277 
278  try
279  {
280  NekDouble ptsStream;
281  while (!pointsDataStrm.fail())
282  {
283  pointsDataStrm >> ptsStream;
284 
285  ptsSerial.push_back(ptsStream);
286  }
287  }
288  catch (...)
289  {
290  NEKERROR(ErrorUtil::efatal, "Unable to read Points data.");
291  }
292 
293  size_t npts = ptsSerial.size() / totvars;
294 
295  for (size_t i = 0; i < totvars; ++i)
296  {
297  pts[i] = Array<OneD, NekDouble>(npts);
298  }
299 
300  for (size_t i = 0; i < npts; ++i)
301  {
302  for (size_t j = 0; j < totvars; ++j)
303  {
304  pts[j][i] = ptsSerial[i * totvars + j];
305  }
306  }
307 
308  ptsField = MemoryManager<PtsField>::AllocateSharedPtr(dim, fieldNames, pts, ptsInfo);
309 }
310 
311 void PtsIO::SetUpFieldMetaData(const string outname)
312 {
313  ASSERTL0(!outname.empty(), "Empty path given to SetUpFieldMetaData()");
314 
315  int nprocs = m_comm->GetSize();
316  int rank = m_comm->GetRank();
317 
318  fs::path specPath(outname);
319 
320  // Collate per-process element lists on root process to generate
321  // the info file.
322  if (rank == 0)
323  {
324  // Set up output names
325  std::vector<std::string> filenames;
326  std::vector<std::vector<unsigned int> > ElementIDs;
327  for (int i = 0; i < nprocs; ++i)
328  {
329  boost::format pad("P%1$07d.%2$s");
330  pad % i % GetFileEnding();
331  filenames.push_back(pad.str());
332 
333  std::vector<unsigned int> tmp;
334  tmp.push_back(0);
335  ElementIDs.push_back(tmp);
336  }
337 
338  // Write the Info.xml file
339  string infofile =
340  LibUtilities::PortablePath(specPath / fs::path("Info.xml"));
341 
342  cout << "Writing: " << specPath << endl;
343 
344  const FieldMetaDataMap fieldmetadatamap;
345  WriteMultiFldFileIDs(infofile, filenames, ElementIDs, fieldmetadatamap);
346  }
347 }
348 }
349 }
#define ASSERTL0(condition, msg)
Definition: ErrorUtil.hpp:216
#define NEKERROR(type, msg)
Assert Level 0 – Fundamental assert which is used whether in FULLDEBUG, DEBUG or OPT compilation mode...
Definition: ErrorUtil.hpp:209
DataSourceSharedPtr ImportFieldMetaData(const std::string &filename, FieldMetaDataMap &fieldmetadatamap)
Import the metadata from a field file.
Definition: FieldIO.h:355
std::string SetUpOutput(const std::string outname, bool perRank, bool backup=false)
Set up the filesystem ready for output.
Definition: FieldIO.cpp:410
LibUtilities::CommSharedPtr m_comm
Communicator to use when writing parallel format.
Definition: FieldIO.h:266
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:428
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:380
void Write(const std::string &outFile, const PtsFieldSharedPtr &ptsField, const bool backup=false)
Save a pts field to a file.
Definition: PtsIO.cpp:138
virtual void v_ImportFieldData(const std::string inFile, PtsFieldSharedPtr &ptsField, DomainRangeShPtr &Range=NullDomainRangeShPtr)
Definition: PtsIO.cpp:220
void SetUpFieldMetaData(const std::string outname)
Definition: PtsIO.cpp:311
void ImportFieldData(const std::string inFile, PtsFieldSharedPtr &ptsField, DomainRangeShPtr &Range=NullDomainRangeShPtr)
Definition: PtsIO.cpp:214
virtual std::string GetFileEnding() const
Helper function that determines default file extension.
Definition: PtsIO.h:95
void Import(const std::string &inFile, PtsFieldSharedPtr &ptsField, FieldMetaDataMap &fieldmetadatamap=NullFieldMetaDataMap, DomainRangeShPtr &Range=NullDomainRangeShPtr)
Import a pts field from file.
Definition: PtsIO.cpp:71
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:135
static std::map< PtsInfo, int > NullPtsInfoMap
Definition: PtsField.h:70
std::map< std::string, std::string > FieldMetaDataMap
Definition: FieldIO.h:52
std::string PortablePath(const boost::filesystem::path &path)
create portable path on different platforms for boost::filesystem path
Definition: FileSystem.cpp:41
std::shared_ptr< PtsField > PtsFieldSharedPtr
Definition: PtsField.h:182
std::shared_ptr< DomainRange > DomainRangeShPtr
Definition: DomainRange.h:61
std::shared_ptr< Comm > CommSharedPtr
Pointer to a Communicator object.
Definition: Comm.h:54
The above copyright notice and this permission notice shall be included.
Definition: CoupledSolver.h:1
double NekDouble