OGS
FileTools.cpp
Go to the documentation of this file.
1
15#include "FileTools.h"
16
17#include <spdlog/fmt/bundled/core.h>
18
19#include <boost/algorithm/string/predicate.hpp>
20#include <boost/endian/conversion.hpp>
21#include <boost/interprocess/file_mapping.hpp>
22#include <boost/interprocess/mapped_region.hpp>
23#include <filesystem>
24#include <fstream>
25#include <typeindex>
26#include <unordered_map>
27
28#include "BaseLib/Logging.h"
29#include "Error.h"
30
31namespace
32{
35
38} // anonymous namespace
39
40namespace BaseLib
41{
43{
44 return project_directory_is_set;
45}
46
50bool IsFileExisting(const std::string& strFilename)
51{
52 return std::filesystem::exists(std::filesystem::path(strFilename));
53}
54
55std::tuple<std::string, std::string::size_type, std::string::size_type>
56getParenthesizedString(std::string const& in,
57 char const open_char,
58 char const close_char,
59 std::string::size_type pos)
60{
61 auto const pos_curly_brace_open = in.find_first_of(open_char, pos);
62 if (pos_curly_brace_open == std::string::npos)
63 {
64 return std::make_tuple("", std::string::npos, std::string::npos);
65 }
66 auto const pos_curly_brace_close =
67 in.find_first_of(close_char, pos_curly_brace_open);
68 if (pos_curly_brace_close == std::string::npos)
69 {
70 return std::make_tuple("", std::string::npos, std::string::npos);
71 }
72 return std::make_tuple(
73 in.substr(pos_curly_brace_open + 1,
74 pos_curly_brace_close - (pos_curly_brace_open + 1)),
75 pos_curly_brace_open, pos_curly_brace_close);
76}
77
78std::string containsKeyword(std::string const& str, std::string const& keyword)
79{
80 auto const position = str.find(keyword);
81 if (position != std::string::npos)
82 {
83 return str.substr(0, position);
84 }
85 return "";
86}
87
88template <typename T>
89bool substituteKeyword(std::string& result,
90 std::string const& parenthesized_string,
91 std::string::size_type const begin,
92 std::string::size_type const end,
93 std::string const& keyword, T& data)
94{
95 std::string precision_specification =
96 containsKeyword(parenthesized_string, keyword);
97
98 if (precision_specification.empty())
99 {
100 return false;
101 }
102
103 std::unordered_map<std::type_index, char> type_specification;
104 type_specification[std::type_index(typeid(int))] = 'd';
105 type_specification[std::type_index(typeid(double))] = 'f'; // default
106 type_specification[std::type_index(typeid(std::string))] = 's';
107
108 auto const& b = precision_specification.back();
109 // see https://fmt.dev/latest/syntax/#format-specification-mini-language
110 if (b == 'e' || b == 'E' || b == 'f' || b == 'F' || b == 'g' || b == 'G')
111 {
112 type_specification[std::type_index(typeid(double))] = b;
113 precision_specification.pop_back();
114 }
115
116 std::string const generated_fmt_string =
117 "{" + precision_specification +
118 type_specification[std::type_index(typeid(data))] + "}";
119 result.replace(
120 begin, end - begin + 1,
121 fmt::vformat(generated_fmt_string, fmt::make_format_args(data)));
122
123 return true;
124}
125
126std::string constructFormattedFileName(std::string const& format_specification,
127 std::string const& mesh_name,
128 int const timestep,
129 double const t,
130 int const iteration)
131{
132 char const open_char = '{';
133 char const close_char = '}';
134 std::string::size_type begin = 0;
135 std::string::size_type end = std::string::npos;
136 std::string result = format_specification;
137
138 while (begin != std::string::npos)
139 {
140 auto length_before_substitution = result.length();
141 // find next parenthesized string
142 std::string str = "";
143 std::tie(str, begin, end) =
144 getParenthesizedString(result, open_char, close_char, begin);
145 if (!substituteKeyword(result, str, begin, end, "timestep", timestep) &&
146 !substituteKeyword(result, str, begin, end, "time", t) &&
147 !substituteKeyword(result, str, begin, end, "iteration", iteration))
148 {
149 substituteKeyword(result, str, begin, end, "meshname", mesh_name);
150 }
151 begin = end - (length_before_substitution - result.length());
152 }
153
154 return result;
155}
156
157double swapEndianness(double const& v)
158{
159 union
160 {
161 double v;
162 char c[sizeof(double)];
163 } a{}, b{};
164
165 a.v = v;
166 for (unsigned short i = 0; i < sizeof(double) / 2; i++)
167 {
168 b.c[i] = a.c[sizeof(double) / 2 - i - 1];
169 }
170
171 for (unsigned short i = sizeof(double) / 2; i < sizeof(double); i++)
172 {
173 b.c[i] = a.c[sizeof(double) + sizeof(double) / 2 - i - 1];
174 }
175
176 return b.v;
177}
178
179std::string dropFileExtension(std::string const& filename)
180{
181 auto const filename_path = std::filesystem::path(filename);
182 return (filename_path.parent_path() / filename_path.stem()).string();
183}
184
185std::string extractBaseName(std::string const& pathname)
186{
187 return std::filesystem::path(pathname).filename().string();
188}
189
190std::string extractBaseNameWithoutExtension(std::string const& pathname)
191{
192 std::string basename = extractBaseName(pathname);
193 return dropFileExtension(basename);
194}
195
196std::string getFileExtension(const std::string& path)
197{
198 return std::filesystem::path(path).extension().string();
199}
200
201bool hasFileExtension(std::string const& extension, std::string const& filename)
202{
203 return boost::iequals(extension, getFileExtension(filename));
204}
205
206std::string extractPath(std::string const& pathname)
207{
208 return std::filesystem::path(pathname).parent_path().string();
209}
210
211std::string joinPaths(std::string const& pathA, std::string const& pathB)
212{
213 return (std::filesystem::path(pathA) /= std::filesystem::path(pathB))
214 .string();
215}
216
217std::string const& getProjectDirectory()
218{
219 if (!project_directory_is_set)
220 {
221 OGS_FATAL("The project directory has not yet been set.");
222 }
223 return project_directory;
224}
225
226void setProjectDirectory(std::string const& dir)
227{
228 if (project_directory_is_set)
229 {
230 OGS_FATAL("The project directory has already been set.");
231 }
232 // TODO Remove these global vars. They are a possible source of errors when
233 // invoking OGS from Python multiple times within a single session.
234 project_directory = dir;
235 project_directory_is_set = true;
236}
237
239{
240 project_directory.clear();
241 project_directory_is_set = false;
242}
243
244void removeFile(std::string const& filename)
245{
246 bool const success =
247 std::filesystem::remove(std::filesystem::path(filename));
248 if (success)
249 {
250 DBUG("Removed '{:s}'", filename);
251 }
252}
253
254void removeFiles(std::vector<std::string> const& files)
255{
256 for (auto const& file : files)
257 {
258 removeFile(file);
259 }
260}
261
262bool createOutputDirectory(std::string const& dir)
263{
264 if (dir.empty())
265 {
266 return false;
267 }
268
269 std::error_code mkdir_err;
270 if (std::filesystem::create_directories(dir, mkdir_err))
271 {
272 INFO("Output directory {:s} created.", dir);
273 }
274 else if (mkdir_err.value() != 0)
275 {
276 WARN("Could not create output directory {:s}. Error code {:d}, {:s}",
277 dir, mkdir_err.value(), mkdir_err.message());
278 return false;
279 }
280 return true;
281}
282
283std::vector<double> readDoublesFromBinaryFile(const std::string& filename)
284{
285 auto prj_dir = BaseLib::getProjectDirectory();
286 std::string path_to_file = BaseLib::joinPaths(prj_dir, filename);
287 std::string file_extension = BaseLib::getFileExtension(filename);
288 if (file_extension != ".bin")
289 {
290 OGS_FATAL(
291 "Currently only binary files with extension '.bin' supported. The "
292 "specified file has extension {:s}.",
293 file_extension)
294 }
295 return BaseLib::readBinaryVector<double>(path_to_file);
296}
297
298template <typename T>
299T readBinaryValue(std::istream& in)
300{
301 T v;
302 in.read(reinterpret_cast<char*>(&v), sizeof(T));
303 return v;
304}
305
306// explicit template instantiation
307template float readBinaryValue<float>(std::istream&);
308template double readBinaryValue<double>(std::istream&);
309
310template <typename T>
311std::vector<T> readBinaryVector(std::string const& filename,
312 std::size_t const start_element,
313 std::size_t const num_elements)
314{
315 if (!IsFileExisting(filename))
316 {
317 OGS_FATAL("File {:s} not found", filename);
318 }
319
320 // Determine file size
321 std::uintmax_t file_size = std::filesystem::file_size(filename);
322 std::size_t total_elements = file_size / sizeof(T);
323
324 if (start_element >= total_elements)
325 {
326 OGS_FATAL("Start element is beyond file size");
327 }
328
329 // Calculate the number of elements to read
330 std::size_t const elements_to_read =
331 std::min(num_elements, total_elements - start_element);
332
333 // Calculate offset and size to map
334 std::size_t const offset = start_element * sizeof(T);
335 std::size_t const size_to_map = elements_to_read * sizeof(T);
336
337 // Create a file mapping
338 boost::interprocess::file_mapping file(filename.c_str(),
339 boost::interprocess::read_only);
340
341 // Map the specified region
342 boost::interprocess::mapped_region region(
343 file, boost::interprocess::read_only, offset, size_to_map);
344
345 // Get the address of the mapped region
346 auto* addr = region.get_address();
347
348 // Create vector and copy data
349 std::vector<T> result(elements_to_read);
350 std::memcpy(result.data(), addr, size_to_map);
351
352 if constexpr (std::endian::native != std::endian::little)
353 {
354 boost::endian::endian_reverse_inplace(result);
355 }
356
357 return result;
358}
359
360// explicit template instantiation
361template std::vector<float> readBinaryVector<float>(std::string const&,
362 std::size_t const,
363 std::size_t const);
364template std::vector<double> readBinaryVector<double>(std::string const&,
365 std::size_t const,
366 std::size_t const);
367
368template <typename T>
369void writeValueBinary(std::ostream& out, T const& val)
370{
371 out.write(reinterpret_cast<const char*>(&val), sizeof(T));
372}
373
374// explicit template instantiation
375template void writeValueBinary<std::size_t>(std::ostream&, std::size_t const&);
376
377} // end namespace BaseLib
#define OGS_FATAL(...)
Definition Error.h:26
Filename manipulation routines.
void INFO(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:35
void DBUG(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:30
void WARN(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:40
std::string containsKeyword(std::string const &str, std::string const &keyword)
Definition FileTools.cpp:78
std::string constructFormattedFileName(std::string const &format_specification, std::string const &mesh_name, int const timestep, double const t, int const iteration)
void removeFile(std::string const &filename)
std::vector< T > readBinaryVector(std::string const &filename, std::size_t const start_element, std::size_t const num_elements)
std::string const & getProjectDirectory()
Returns the directory where the prj file resides.
std::string getFileExtension(const std::string &path)
void writeValueBinary(std::ostream &out, T const &val)
write value as binary into the given output stream
std::string extractPath(std::string const &pathname)
std::vector< double > readDoublesFromBinaryFile(const std::string &filename)
std::tuple< std::string, std::string::size_type, std::string::size_type > getParenthesizedString(std::string const &in, char const open_char, char const close_char, std::string::size_type pos)
Definition FileTools.cpp:56
T readBinaryValue(std::istream &in)
bool IsFileExisting(const std::string &strFilename)
Returns true if given file exists.
Definition FileTools.cpp:50
template void writeValueBinary< std::size_t >(std::ostream &, std::size_t const &)
template std::vector< double > readBinaryVector< double >(std::string const &, std::size_t const, std::size_t const)
template float readBinaryValue< float >(std::istream &)
std::string extractBaseNameWithoutExtension(std::string const &pathname)
std::string dropFileExtension(std::string const &filename)
bool isProjectDirectorySet()
Returns true if the project directory is set.
Definition FileTools.cpp:42
std::string joinPaths(std::string const &pathA, std::string const &pathB)
void unsetProjectDirectory()
Unsets the project directory.
template double readBinaryValue< double >(std::istream &)
std::string extractBaseName(std::string const &pathname)
double swapEndianness(double const &v)
bool createOutputDirectory(std::string const &dir)
bool substituteKeyword(std::string &result, std::string const &parenthesized_string, std::string::size_type const begin, std::string::size_type const end, std::string const &keyword, T &data)
Definition FileTools.cpp:89
void setProjectDirectory(std::string const &dir)
Sets the project directory.
bool hasFileExtension(std::string const &extension, std::string const &filename)
void removeFiles(std::vector< std::string > const &files)
template std::vector< float > readBinaryVector< float >(std::string const &, std::size_t const, std::size_t const)
std::string project_directory
The directory where the prj file resides.
Definition FileTools.cpp:34
bool project_directory_is_set
Whether the project directory has already been set.
Definition FileTools.cpp:37