sisi4s
Loading...
Searching...
No Matches
XyzParser.hpp
Go to the documentation of this file.
1#ifndef _XYZ_PARSER_
2#define _XYZ_PARSER_
3
4#include <string>
5#include <vector>
6#include <algorithm>
7#include <fstream>
8#include <map>
9#include <util/Parsing.hpp>
10#include <regex>
11
12struct Atom {
13 const std::string symbol;
14 const struct {
15 double x, y, z;
17};
18
19namespace pars {
20
21struct XyzParser {
22
23 const Regex sep = blank + oneOrMore // any number > 1 of spaces or tabs
24 ,
25 atom = upper + lower + optional // atom is Upper + lower?
26 ,
27 xyz_line = bof + blank + anyOf // spaces at the start allowed
28 + capture(atom.s) + sep.s // capture atom symbol
31
32 Atom parseLine(const std::string &line) {
33 std::smatch m;
34 std::regex_match(line, m, xyz_line.r);
35 if (m.size() == 0) { throw "Line " + line + " is malformed"; }
36 return {std::string(m[1]),
37 {std::atof(std::string(m[2]).c_str()),
38 std::atof(std::string(m[3]).c_str()),
39 std::atof(std::string(m[4]).c_str())}};
40 }
41
42 std::vector<Atom> parseFile(const std::string &fileName) {
43 std::fstream f(fileName);
44 std::string line;
45 std::vector<Atom> atoms;
46 if (!f.good()) throw "File " + fileName + " not found";
47 if (!f.is_open()) throw "File IO error: " + fileName;
48
49 std::getline(f, line); // Number of atoms
50 const int natoms = std::atoi(line.c_str());
51
52 std::getline(f, line); // Title of xyz file
53
54 // parse lines
55 for (int i(0); i < natoms; i++) {
56 std::getline(f, line);
57 atoms.push_back(parseLine(line));
58 }
59
60 return atoms;
61 }
62};
63
64} // namespace pars
65
66#endif
Definition Parsing.cxx:6
const Str lower("[[:lower:]]")
const Str bof("^")
const Str blank("[[:blank:]]")
const Str eof("$")
const Str anyOf("*")
const Str oneOrMore("+")
const Str optional("?")
const Str upper("[[:upper:]]")
const std::function< Str(Str)> capture([](const Str &i) { return "("+i+")";})
const Str realNumber("[-eE+\\d.]+")
Definition XyzParser.hpp:12
double x
Definition XyzParser.hpp:15
const struct Atom::@8 position
const std::string symbol
Definition XyzParser.hpp:13
double y
Definition XyzParser.hpp:15
double z
Definition XyzParser.hpp:15
Definition Parsing.hpp:45
const std::regex r
Definition Parsing.hpp:47
const std::string s
Definition Parsing.hpp:46
Definition XyzParser.hpp:21
const Regex atom
Definition XyzParser.hpp:25
const Regex xyz_line
Definition XyzParser.hpp:27
std::vector< Atom > parseFile(const std::string &fileName)
Definition XyzParser.hpp:42
const Regex sep
Definition XyzParser.hpp:23
Atom parseLine(const std::string &line)
Definition XyzParser.hpp:32