Nektar++
CsvIO.cpp
Go to the documentation of this file.
1 ////////////////////////////////////////////////////////////////////////////////
2 //
3 // File: CsvIO.cpp
4 //
5 // For more information, please see: http://www.nektar.info/
6 //
7 // The MIT License
8 //
9 // Copyright (c) 2017 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: Csv IO
33 //
34 ////////////////////////////////////////////////////////////////////////////////
35 
37 
38 #include <boost/algorithm/string.hpp>
39 #include <boost/tokenizer.hpp>
40 
41 #include <vector>
42 #include <fstream>
43 
44 #include <boost/format.hpp>
45 
46 #ifdef NEKTAR_USE_MPI
47 #include <mpi.h>
48 #endif
49 
50 #include "ErrorUtil.hpp"
53 
54 namespace Nektar
55 {
56 namespace LibUtilities
57 {
58 
59 
60 CsvIO::CsvIO(CommSharedPtr pComm, bool sharedFilesystem)
61  : PtsIO(pComm, sharedFilesystem)
62 {
63 }
64 
65 /**
66  * @brief Save a pts field to a file
67  *
68  * @param outFile filename of the file
69  * @param ptsField the pts field
70  */
71 void CsvIO::Write(const std::string &outFile,
73  const bool backup)
74 {
75  size_t nTotvars = ptsField->GetNFields() + ptsField->GetDim();
76  size_t np = ptsField->GetNpoints();
77 
78  std::string filename = SetUpOutput(outFile, true, backup);
79  SetUpFieldMetaData(outFile);
80 
81  std::ofstream ptsFile;
82  ptsFile.open(filename.c_str());
83 
84  std::vector<std::string> xyz;
85  xyz.push_back("x");
86  xyz.push_back("y");
87  xyz.push_back("z");
88  xyz.resize(ptsField->GetDim());
89 
90  std::string fn = boost::algorithm::join(xyz, ",");
91  ptsFile << "# " << fn << ",";
92  fn = boost::algorithm::join(ptsField->GetFieldNames(), ",");
93  ptsFile << fn;
94  ptsFile << std::endl;
95 
97  ptsField->GetPts(pts);
98  for (size_t i = 0; i < np; ++i)
99  {
100  ptsFile << pts[0][i];
101  for (size_t j = 1; j < nTotvars; ++j)
102  {
103  ptsFile << "," << pts[j][i];
104  }
105  ptsFile << std::endl;
106  }
107 
108  ptsFile.close();
109 }
110 
111 
112 void CsvIO::v_ImportFieldData(const std::string inFile, PtsFieldSharedPtr& ptsField)
113 {
114  std::stringstream errstr;
115  errstr << "Unable to load file: " << inFile << std::endl;
116  std::ifstream in(inFile.c_str());
117  ASSERTL0(in.is_open(), errstr.str());
118 
119  std::string line;
120  std::getline(in, line);
121  boost::erase_first(line, "#");
122 
123  std::vector<std::string> fieldNames;
124  bool valid = ParseUtils::GenerateVector(line, fieldNames);
125  ASSERTL0(valid, "Unable to process list of fields from line: " + line);
126 
127  int dim = 0;
128  for (auto &it : fieldNames)
129  {
130  if (it == "x" || it == "y" || it == "z")
131  {
132  dim++;
133  }
134  }
135 
136  size_t totvars = fieldNames.size();
137 
138  std::vector<NekDouble> ptsSerial;
139  typedef boost::tokenizer< boost::escaped_list_separator<char> > Tokenizer;
140  Tokenizer tok(line);
141  while (getline(in, line))
142  {
143  tok.assign(line);
144 
145  ASSERTL0(std::distance(tok.begin(), tok.end()) ==
146  std::iterator_traits<Tokenizer::iterator>::difference_type(totvars),
147  "wrong number of columns in line: " + line);
148 
149  for (auto &it : tok)
150  {
151  try
152  {
153  ptsSerial.push_back(
154  boost::lexical_cast<NekDouble>(
155  boost::trim_copy(std::string(it))));
156  }
157  catch(const boost::bad_lexical_cast &)
158  {
159  NEKERROR(ErrorUtil::efatal, "could not convert line: " + line);
160  }
161  }
162  }
163 
164  size_t npts = ptsSerial.size() / totvars;
165 
166  Array<OneD, Array<OneD, NekDouble> > pts(totvars);
167  for (size_t i = 0; i < totvars; ++i)
168  {
169  pts[i] = Array<OneD, NekDouble>(npts);
170  }
171 
172  for (size_t i = 0; i < npts; ++i)
173  {
174  for (size_t j = 0; j < totvars; ++j)
175  {
176  pts[j][i] = ptsSerial[i * totvars + j];
177  }
178  }
179 
180  // reorder pts to make x,y,z the first columns
181  std::vector<std::string> dimNames = {"x", "y", "z"};
182  for (int i = 0; i < dim; ++i)
183  {
184  auto p = std::find(fieldNames.begin(), fieldNames.end(), dimNames[i]);
185  if (p != fieldNames.end())
186  {
187  auto j = std::distance(fieldNames.begin(), p);
188 
189  if (i == j)
190  {
191  continue;
192  }
193 
194  Array<OneD, NekDouble> tmp = pts[i];
195  pts[i] = pts[j];
196  pts[j] = tmp;
197 
198  std::string tmp2 = fieldNames[i];
199  fieldNames[i] = fieldNames[j];
200  fieldNames[j] = tmp2;
201  }
202  }
203  fieldNames.erase(fieldNames.begin(), fieldNames.begin() + dim);
204 
205  ptsField = MemoryManager<PtsField>::AllocateSharedPtr(dim, fieldNames, pts);
206 }
207 
208 }
209 }
#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 mod...
Definition: ErrorUtil.hpp:209
std::shared_ptr< Comm > CommSharedPtr
Pointer to a Communicator object.
Definition: Comm.h:53
void Write(const std::string &outFile, const PtsFieldSharedPtr &ptsField, const bool backup=false)
Save a pts field to a file.
Definition: CsvIO.cpp:71
virtual void v_ImportFieldData(const std::string inFile, PtsFieldSharedPtr &ptsField)
Definition: CsvIO.cpp:112
std::shared_ptr< PtsField > PtsFieldSharedPtr
Definition: PtsField.h:179
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
std::string SetUpOutput(const std::string outname, bool perRank, bool backup=false)
Set up the filesystem ready for output.
Definition: FieldIO.cpp:410
void SetUpFieldMetaData(const std::string outname)
Definition: PtsIO.cpp:307
InputIterator find(InputIterator first, InputIterator last, InputIterator startingpoint, const EqualityComparable &value)
Definition: StdRegions.hpp:358
CsvIO(LibUtilities::CommSharedPtr pComm, bool sharedFilesystem=false)
Definition: CsvIO.cpp:60