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