| 1 | // SPDX-License-Identifier: LGPL-3.0-or-later |
| 2 | // Author: Kristian Lytje |
| 3 | |
| 4 | #include <io/detail/structure/XYZReader.h> |
| 5 | #include <io/ExistingFile.h> |
| 6 | #include <utility/Console.h> |
| 7 | #include <settings/MoleculeSettings.h> |
| 8 | |
| 9 | #include <fstream> |
| 10 | |
| 11 | using namespace ausaxs; |
| 12 | using namespace ausaxs::io::pdb; |
| 13 | |
| 14 | io::pdb::PDBStructure io::detail::xyz::read(const io::File& path) { |
| 15 | console::print_info("Reading XYZ structure file from \"" + path.str() + "\""); |
| 16 | console::indent(); |
| 17 | if (settings::molecule::implicit_hydrogens) { |
| 18 | console::print_text("Note: implicit hydrogens setting is enabled, but XYZ files do not contain enough information to assign hydrogens. Disabling."); |
| 19 | settings::molecule::implicit_hydrogens = false; |
| 20 | } |
| 21 | |
| 22 | io::pdb::PDBStructure res; |
| 23 | std::ifstream input(path); |
| 24 | if (!input.is_open()) {throw except::io_error("XYZReader::read: Could not open file \"" + path.str() + "\"");} |
| 25 | |
| 26 | int section_id = 0; // 0 = header, 1 = atoms, 2 = footer |
| 27 | std::string line; |
| 28 | while(getline(input, line)) { |
| 29 | if (utility::remove_all(line, " \n\r").empty()) {continue;} |
| 30 | auto tokens = utility::split(line, " \t"); |
| 31 | |
| 32 | // skip header |
| 33 | if (tokens.size() != 4 && section_id == 0) {continue;} |
| 34 | else {section_id = 1;} // progress to main data section |
| 35 | if (tokens.size() != 4 && section_id == 1) {break;} // progress to footer |
| 36 | |
| 37 | PDBAtom atom; |
| 38 | atom.element = constants::symbols::parse_element_string(tokens[0]); |
| 39 | atom.coordinates().x() = std::stod(tokens[1]); |
| 40 | atom.coordinates().y() = std::stod(tokens[2]); |
| 41 | atom.coordinates().z() = std::stod(tokens[3]); |
| 42 | res.atoms.emplace_back(std::move(atom)); |
| 43 | } |
| 44 | |
| 45 | console::print_text("Successfully read " + std::to_string(res.atoms.size()) + " atomic records."); |
| 46 | console::unindent(); |
| 47 | return res; |
| 48 | } |