Nektar++
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator 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 // License for the specific language governing rights and limitations under
15 // Permission is hereby granted, free of charge, to any person obtaining a
16 // copy of this software and associated documentation files (the "Software"),
17 // to deal in the Software without restriction, including without limitation
18 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
19 // and/or sell copies of the Software, and to permit persons to whom the
20 // Software is furnished to do so, subject to the following conditions:
21 //
22 // The above copyright notice and this permission notice shall be included
23 // in all copies or substantial portions of the Software.
24 //
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
28 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
30 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
31 // DEALINGS IN THE SOFTWARE.
32 //
33 // Description: I/O routines relating to Pts data
34 //
35 ////////////////////////////////////////////////////////////////////////////////
36 
37 #include <boost/algorithm/string.hpp>
39 
40 #include <fstream>
41 
42 #include <boost/format.hpp>
43 
44 #ifdef NEKTAR_USE_MPI
45 #include <mpi.h>
46 #endif
47 
49 
50 
51 namespace Nektar
52 {
53 namespace LibUtilities
54 {
55 
56 void Import(const string &inFile, PtsFieldSharedPtr &ptsField)
57 {
58 #ifdef NEKTAR_USE_MPI
59  int size;
60  int init;
61  MPI_Initialized(&init);
62 
63  // If MPI has been initialised we can check the number of processes
64  // and, if > 1, tell the user he should not be running this
65  // function in parallel. If it is not initialised, we do not
66  // initialise it here, and assume the user knows what they are
67  // doing.
68  if (init)
69  {
70  MPI_Comm_size(MPI_COMM_WORLD, &size);
71  ASSERTL0(size == 1,
72  "This static function is not available in parallel. Please "
73  "instantiate a FieldIO object for parallel use.");
74  }
75 #endif
76  CommSharedPtr c = GetCommFactory().CreateInstance("Serial", 0, 0);
77  PtsIO p(c);
78  p.Import(inFile, ptsField);
79 }
80 
81 void Write(const string &outFile, const PtsFieldSharedPtr &ptsField)
82 {
83 #ifdef NEKTAR_USE_MPI
84  int size;
85  int init;
86  MPI_Initialized(&init);
87 
88  // If MPI has been initialised we can check the number of processes
89  // and, if > 1, tell the user he should not be running this
90  // function in parallel. If it is not initialised, we do not
91  // initialise it here, and assume the user knows what they are
92  // doing.
93  if (init)
94  {
95  MPI_Comm_size(MPI_COMM_WORLD, &size);
96  ASSERTL0(size == 1,
97  "This static function is not available in parallel. Please "
98  "instantiate a FieldIO object for parallel use.");
99  }
100 #endif
101  CommSharedPtr c = GetCommFactory().CreateInstance("Serial", 0, 0);
102  PtsIO p(c);
103  p.Write(outFile, ptsField);
104 }
105 
106 PtsIO::PtsIO(CommSharedPtr pComm, bool sharedFilesystem)
107  : FieldIO(pComm, sharedFilesystem)
108 {
109 }
110 
111 /**
112  * @brief Import a pts field from file
113  *
114  * @param inFile filename of the file to read
115  * @param ptsField the resulting pts field.
116  */
117 void PtsIO::Import(const string &inFile,
118  PtsFieldSharedPtr &ptsField,
119  FieldMetaDataMap &fieldmetadatamap)
120 {
121  std::string infile = inFile;
122 
123  fs::path pinfilename(infile);
124 
125  // check to see that infile is a directory
126  if (fs::is_directory(pinfilename))
127  {
128  fs::path infofile("Info.xml");
129  fs::path fullpath = pinfilename / infofile;
130  infile = PortablePath(fullpath);
131 
132  std::vector<std::string> filenames;
133  std::vector<std::vector<unsigned int> > elementIDs_OnPartitions;
134 
136  infile, filenames, elementIDs_OnPartitions, fieldmetadatamap);
137 
138  // Load metadata
139  ImportFieldMetaData(infile, fieldmetadatamap);
140 
141  // TODO: This currently only loads the filename matching our rank.
142  filenames.clear();
143  boost::format pad("P%1$07d.%2$s");
144  pad % m_comm->GetRank() % GetFileEnding();
145  filenames.push_back(pad.str());
146 
147  for (int i = 0; i < filenames.size(); ++i)
148  {
149  fs::path pfilename(filenames[i]);
150  fullpath = pinfilename / pfilename;
151  string fname = PortablePath(fullpath);
152 
153  TiXmlDocument doc1(fname);
154  bool loadOkay1 = doc1.LoadFile();
155 
156  std::stringstream errstr;
157  errstr << "Unable to load file: " << fname << std::endl;
158  errstr << "Reason: " << doc1.ErrorDesc() << std::endl;
159  errstr << "Position: Line " << doc1.ErrorRow() << ", Column "
160  << doc1.ErrorCol() << std::endl;
161  ASSERTL0(loadOkay1, errstr.str());
162 
163  ImportFieldData(doc1, ptsField);
164  }
165  }
166  else
167  {
168  TiXmlDocument doc(infile);
169  bool loadOkay = doc.LoadFile();
170 
171  std::stringstream errstr;
172  errstr << "Unable to load file: " << infile << std::endl;
173  errstr << "Reason: " << doc.ErrorDesc() << std::endl;
174  errstr << "Position: Line " << doc.ErrorRow() << ", Column "
175  << doc.ErrorCol() << std::endl;
176  ASSERTL0(loadOkay, errstr.str());
177 
178  ImportFieldData(doc, ptsField);
179  }
180 }
181 
182 /**
183  * @brief Save a pts field to a file
184  *
185  * @param outFile filename of the file
186  * @param ptsField the pts field
187  */
188 void PtsIO::Write(const string &outFile,
190 {
191  int nTotvars = ptsField->GetNFields() + ptsField->GetDim();
192  int np = ptsField->GetNpoints();
193 
194  std::string filename = SetUpOutput(outFile);
195  SetUpFieldMetaData(outFile);
196 
197  // until tinyxml gains support for line break, write the xml manually
198  std::ofstream ptsFile;
199  ptsFile.open(filename.c_str());
200 
201  ptsFile << "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" << endl;
202  ptsFile << "<NEKTAR>" << endl;
203  ptsFile << " <POINTS ";
204  ptsFile << "DIM=\"" << ptsField->GetDim() << "\" ";
205  string fn = boost::algorithm::join(ptsField->GetFieldNames(), ",");
206  ptsFile << "FIELDS=\"" << fn << "\" ";
207  ptsFile << ">" << endl;
208 
210  ptsField->GetPts(pts);
211  for (int i = 0; i < np; ++i)
212  {
213  ptsFile << " ";
214  ptsFile << pts[0][i];
215  for (int j = 1; j < nTotvars; ++j)
216  {
217  ptsFile << " " << pts[j][i];
218  }
219  ptsFile << endl;
220  }
221  ptsFile << " </POINTS>" << endl;
222  ptsFile << "</NEKTAR>" << endl;
223 
224  ptsFile.close();
225 
226  // this is what the above cpart would read if tinyxml
227  // supported line breaks
228  /*
229  // Create the file (partition)
230  TiXmlDocument doc;
231  TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "utf-8", "");
232  doc.LinkEndChild(decl);
233 
234  TiXmlElement *root = new TiXmlElement("NEKTAR");
235  doc.LinkEndChild(root);
236 
237  TiXmlElement *pointsTag = new TiXmlElement("POINTS");
238  root->LinkEndChild(pointsTag);
239 
240  pointsTag->SetAttribute("DIM", ptsField->GetDim());
241 
242  string fn = boost::algorithm::join(ptsField->GetFieldNames(), ",");
243  pointsTag->SetAttribute("FIELDS", fn);
244 
245  Array <OneD, Array <OneD, NekDouble > > pts;
246  ptsField->GetPts(pts);
247  ostringstream os;
248  for (int i = 0; i < np; ++i)
249  {
250  os << pts[0][i];
251  for (int j = 1; j < nTotvars; ++j)
252  {
253  os << " " << pts[j][i];
254  }
255  os << " ";
256  }
257 
258  pointsTag->LinkEndChild(new TiXmlText(os.str()));
259 
260  doc.SaveFile(filename);
261  */
262 }
263 
264 void PtsIO::ImportFieldData(TiXmlDocument docInput, PtsFieldSharedPtr &ptsField)
265 {
266  TiXmlElement *nektar = docInput.FirstChildElement("NEKTAR");
267  TiXmlElement *points = nektar->FirstChildElement("POINTS");
268  int dim;
269  int err = points->QueryIntAttribute("DIM", &dim);
270 
271  ASSERTL0(err == TIXML_SUCCESS, "Unable to read attribute DIM.");
272 
273  std::string fields = points->Attribute("FIELDS");
274 
275  vector<string> fieldNames;
276  if (!fields.empty())
277  {
278  bool valid =
279  ParseUtils::GenerateOrderedStringVector(fields.c_str(), fieldNames);
280  ASSERTL0(
281  valid,
282  "Unable to process list of field variable in FIELDS attribute: " +
283  fields);
284  }
285 
286  map<PtsInfo,int> ptsInfo = NullPtsInfoMap;
287 
288  const char *ptinfo = points->Attribute("PTSINFO");
289  if(ptinfo&&boost::iequals(ptinfo,"EquiSpaced"))
290  {
291  ptsInfo[eIsEquiSpacedData] = 1;
292  }
293 
294  int np;
295  err = points->QueryIntAttribute("PTSPERELMTEDGE",&np);
296  if(err == TIXML_SUCCESS)
297  {
298  ptsInfo[ePtsPerElmtEdge] = np;
299  }
300 
301  int nfields = fieldNames.size();
302  int totvars = dim + nfields;
303 
304  TiXmlNode *pointsBody = points->FirstChild();
305 
306  std::istringstream pointsDataStrm(pointsBody->ToText()->Value());
307 
308  vector<NekDouble> ptsSerial;
309  Array<OneD, Array<OneD, NekDouble> > pts(totvars);
310 
311  try
312  {
313  NekDouble ptsStream;
314  while (!pointsDataStrm.fail())
315  {
316  pointsDataStrm >> ptsStream;
317 
318  ptsSerial.push_back(ptsStream);
319  }
320  }
321  catch (...)
322  {
323  ASSERTL0(false, "Unable to read Points data.");
324  }
325 
326  int npts = ptsSerial.size() / totvars;
327 
328  for (int i = 0; i < totvars; ++i)
329  {
330  pts[i] = Array<OneD, NekDouble>(npts);
331  }
332 
333  for (int i = 0; i < npts; ++i)
334  {
335  for (int j = 0; j < totvars; ++j)
336  {
337  pts[j][i] = ptsSerial[i * totvars + j];
338  }
339  }
340 
341  ptsField = MemoryManager<PtsField>::AllocateSharedPtr(dim, fieldNames, pts, ptsInfo);
342 }
343 
344 void PtsIO::SetUpFieldMetaData(const string outname)
345 {
346  ASSERTL0(!outname.empty(), "Empty path given to SetUpFieldMetaData()");
347 
348  int nprocs = m_comm->GetSize();
349  int rank = m_comm->GetRank();
350 
351  fs::path specPath(outname);
352 
353  // Collate per-process element lists on root process to generate
354  // the info file.
355  if (rank == 0)
356  {
357  // Set up output names
358  std::vector<std::string> filenames;
359  std::vector<std::vector<unsigned int> > ElementIDs;
360  for (int i = 0; i < nprocs; ++i)
361  {
362  boost::format pad("P%1$07d.%2$s");
363  pad % i % GetFileEnding();
364  filenames.push_back(pad.str());
365 
366  std::vector<unsigned int> tmp;
367  tmp.push_back(0);
368  ElementIDs.push_back(tmp);
369  }
370 
371  // Write the Info.xml file
372  string infofile =
373  LibUtilities::PortablePath(specPath / fs::path("Info.xml"));
374 
375  cout << "Writing: " << specPath << endl;
376 
377  const FieldMetaDataMap fieldmetadatamap;
378  WriteMultiFldFileIDs(infofile, filenames, ElementIDs, fieldmetadatamap);
379  }
380 }
381 }
382 }
#define ASSERTL0(condition, msg)
Definition: ErrorUtil.hpp:188
static bool GenerateOrderedStringVector(const char *const str, std::vector< std::string > &vec)
Definition: ParseUtils.hpp:143
tBaseSharedPtr CreateInstance(tKey idKey BOOST_PP_COMMA_IF(MAX_PARAM) BOOST_PP_ENUM_BINARY_PARAMS(MAX_PARAM, tParam, x))
Create an instance of the class referred to by idKey.
Definition: NekFactory.hpp:162
static boost::shared_ptr< DataType > AllocateSharedPtr()
Allocate a shared pointer from the memory pool.
void ImportMultiFldFileIDs(const std::string &inFile, std::vector< std::string > &fileNames, std::vector< std::vector< unsigned int > > &elementList, FieldMetaDataMap &fieldmetadatamap)
Definition: FieldIO.cpp:577
std::string SetUpOutput(const std::string outname)
Definition: FieldIO.cpp:1192
std::map< std::string, std::string > FieldMetaDataMap
Definition: FieldIO.h:53
CommFactory & GetCommFactory()
Definition: Comm.cpp:64
boost::shared_ptr< PtsField > PtsFieldSharedPtr
Definition: PtsField.h:262
void Import(const std::string &infilename, std::vector< FieldDefinitionsSharedPtr > &fielddefs, std::vector< std::vector< NekDouble > > &fielddata, FieldMetaDataMap &fieldinfomap, const Array< OneD, int > ElementiDs)
Imports an FLD file.
Definition: FieldIO.cpp:115
PtsIO(LibUtilities::CommSharedPtr pComm, bool sharedFilesystem=false)
Definition: PtsIO.cpp:106
boost::shared_ptr< Comm > CommSharedPtr
Pointer to a Communicator object.
Definition: Comm.h:53
void ImportFieldData(TiXmlDocument docInput, PtsFieldSharedPtr &ptsField)
Definition: PtsIO.cpp:264
void Write(const string &outFile, const PtsFieldSharedPtr &ptsField)
Save a pts field to a file.
Definition: PtsIO.cpp:188
virtual std::string GetFileEnding() const
Definition: PtsIO.h:90
static std::string npts
Definition: InputFld.cpp:43
std::string PortablePath(const boost::filesystem::path &path)
create portable path on different platforms for boost::filesystem path
Definition: FileSystem.cpp:41
double NekDouble
void Import(const string &inFile, PtsFieldSharedPtr &ptsField, FieldMetaDataMap &fieldmetadatamap=NullFieldMetaDataMap)
Import a pts field from file.
Definition: PtsIO.cpp:117
LibUtilities::CommSharedPtr m_comm
Communicator to use when writing parallel format.
Definition: FieldIO.h:191
void WriteMultiFldFileIDs(const std::string &outfile, const std::vector< std::string > fileNames, std::vector< std::vector< unsigned int > > &elementList, const FieldMetaDataMap &fieldinfomap=NullFieldMetaDataMap)
Definition: FieldIO.cpp:537
static map< PtsInfo, int > NullPtsInfoMap
Definition: PtsField.h:71
void SetUpFieldMetaData(const std::string outname)
Definition: PtsIO.cpp:344
Class for operating on FLD files.
Definition: FieldIO.h:137
void ImportFieldMetaData(std::string filename, FieldMetaDataMap &fieldmetadatamap)
Imports the definition of the meta data.
Definition: FieldIO.cpp:637
void Write(const std::string &outFile, std::vector< FieldDefinitionsSharedPtr > &fielddefs, std::vector< std::vector< NekDouble > > &fielddata, const FieldMetaDataMap &fieldinfomap)
Write a field file in serial only.
Definition: FieldIO.cpp:81