| 1 | // SPDX-License-Identifier: LGPL-3.0-or-later |
| 2 | // Author: Kristian Lytje |
| 3 | |
| 4 | #include <io/detail/structure/CIFReader.h> |
| 5 | #include <io/File.h> |
| 6 | #include <utility/Exceptions.h> |
| 7 | #include <utility/StringUtils.h> |
| 8 | #include <utility/Console.h> |
| 9 | #include <residue/detail/Residue.h> |
| 10 | #include <constants/Constants.h> |
| 11 | #include <io/pdb/PDBAtom.h> |
| 12 | #include <io/pdb/PDBWater.h> |
| 13 | #include <io/pdb/PDBStructure.h> |
| 14 | #include <settings/All.h> |
| 15 | |
| 16 | #include <fstream> |
| 17 | #include <unordered_map> |
| 18 | |
| 19 | using namespace ausaxs; |
| 20 | |
| 21 | using CIFRow = std::vector<std::string>; |
| 22 | struct CIFSection { |
| 23 | std::vector<std::string> labels; |
| 24 | std::vector<CIFRow> data; |
| 25 | |
| 26 | bool empty() const {return labels.empty() && data.empty();} |
| 27 | |
| 28 | std::unordered_map<std::string, int> get_label_map() const { |
| 29 | std::unordered_map<std::string, int> map; |
| 30 | for (size_t i = 0; i < labels.size(); i++) { |
| 31 | map[labels[i]] = i; |
| 32 | } |
| 33 | return map; |
| 34 | } |
| 35 | }; |
| 36 | |
| 37 | residue::detail::Residue parse_ion(const CIFSection& atom) { |
| 38 | if (atom.data.size() != 1) {throw except::io_error("CIFReader::parse_ion: Invalid number of data entries in atom section");} |
| 39 | auto labels = atom.get_label_map(); |
| 40 | |
| 41 | if (!labels.contains("comp_id")) { |
| 42 | throw except::io_error("CIFReader::parse_ion: Missing required label \"comp_id\" in \"_chem_comp\" section"); |
| 43 | } if (!labels.contains("charge")) { |
| 44 | throw except::io_error("CIFReader::parse_ion: Missing required label \"charge\" in \"_chem_comp\" section"); |
| 45 | } |
| 46 | |
| 47 | std::string comp_id = atom.data[0][labels.at("comp_id")]; |
| 48 | if (!constants::symbols::detail::string_to_atomt_map.contains(comp_id)) { |
| 49 | throw except::io_error("CIFReader::parse_ion: Unrecognized ion: \"" + comp_id + "\""); |
| 50 | } |
| 51 | |
| 52 | int charge = std::stoi(atom.data[0][labels.at("charge")]); |
| 53 | residue::detail::Residue residue(comp_id); |
| 54 | residue.add_atom(comp_id, charge, constants::symbols::parse_element_string(comp_id)); |
| 55 | return residue; |
| 56 | } |
| 57 | |
| 58 | std::vector<residue::detail::Residue> parse_residue(CIFSection& atom, CIFSection& bond) { |
| 59 | if (atom.data.empty() || bond.data.empty()) {throw except::io_error("CIFReader::parse_residue: Empty data section");} |
| 60 | auto atom_labels = atom.get_label_map(); |
| 61 | auto bond_labels = bond.get_label_map(); |
| 62 | |
| 63 | // mandatory labels |
| 64 | if (!atom_labels.contains("comp_id") || !atom_labels.contains("atom_id")) { |
| 65 | throw except::io_error("CIFReader::parse_residue: Missing required labels in \"_chem_comp_atom\" section"); |
| 66 | } |
| 67 | |
| 68 | // optional label |
| 69 | bool has_alt_atom_id = atom_labels.contains("alt_atom_id"); |
| 70 | |
| 71 | // parse atoms |
| 72 | int i_comp_id = atom_labels.at("comp_id"); |
| 73 | int i_atom_id = atom_labels.at("atom_id"); |
| 74 | int i_alt_atom_id = has_alt_atom_id ? atom_labels.at("alt_atom_id") : i_atom_id; |
| 75 | int i_type_symbol = atom_labels.at("type_symbol"); |
| 76 | std::vector<residue::detail::Residue> residues; |
| 77 | std::unordered_map<std::string, size_t> residue_names; |
| 78 | for (size_t i = 0; i < atom.data.size();) { // nested loops are responsible for incrementing i |
| 79 | std::string current_comp_id = atom.data[i][i_comp_id]; |
| 80 | |
| 81 | residue::detail::Residue residue(current_comp_id); |
| 82 | if (i+1 == atom.data.size() || atom.data[i+1][i_comp_id] != current_comp_id) { |
| 83 | // single-atom residue indicates an ion |
| 84 | auto element = constants::symbols::parse_element_string(atom.data[i][i_type_symbol]); |
| 85 | residue.add_atom(atom.data[i][i_atom_id], constants::charge::ionic::get_charge(element), element); |
| 86 | ++i; |
| 87 | } else { |
| 88 | // multi-atom residue |
| 89 | while (i < atom.data.size() && atom.data[i][i_comp_id] == current_comp_id) { |
| 90 | const std::string& atom_id = atom.data[i][i_atom_id]; |
| 91 | const std::string& type_symbol = atom.data[i][i_type_symbol]; |
| 92 | std::string alt_atom_id = atom.data[i][i_alt_atom_id]; |
| 93 | |
| 94 | // sometimes the "1" in e.g. CD1 is omitted, so if the atom_id and alt_atom_id are the same anyway, add this as an alias |
| 95 | if (atom_id == alt_atom_id) { |
| 96 | if (auto N = atom_id.size(); N > 2) { // second character must be a locator e.g. A, B, C, D, E, ... |
| 97 | if (atom_id[N - 1] == '1' && !std::isdigit(atom_id[N - 2])) { // last character must be 1 & previous character must be a locator |
| 98 | alt_atom_id = atom_id.substr(0, N - 1); |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | residue.add_atom(atom_id, alt_atom_id, constants::symbols::parse_element_string(type_symbol)); |
| 103 | ++i; |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | residues.emplace_back(std::move(residue)); |
| 108 | residue_names[current_comp_id] = residues.size()-1; |
| 109 | } |
| 110 | |
| 111 | // parse bonds |
| 112 | if (!bond_labels.contains("comp_id") || !bond_labels.contains("atom_id_1") || !bond_labels.contains("atom_id_2") || !bond_labels.contains("value_order")) { |
| 113 | throw except::io_error("CIFReader::parse_residue: Missing required labels in \"_chem_comp_bond\" section"); |
| 114 | } |
| 115 | |
| 116 | int i_comp_id_bond = bond_labels.at("comp_id"); |
| 117 | int i_atom_id_1 = bond_labels.at("atom_id_1"); |
| 118 | int i_atom_id_2 = bond_labels.at("atom_id_2"); |
| 119 | int i_value_order = bond_labels.at("value_order"); |
| 120 | for (size_t i = 0; i < bond.data.size();) { // nested loops are responsible for incrementing i |
| 121 | const std::string& current_comp_id = bond.data[i][i_comp_id_bond]; |
| 122 | |
| 123 | // parse bonds |
| 124 | auto& current_residue = residues[residue_names.at(current_comp_id)]; |
| 125 | while (i < bond.data.size() && bond.data[i][i_comp_id_bond] == current_comp_id) { |
| 126 | const std::string& atom_id_1 = bond.data[i][i_atom_id_1]; |
| 127 | const std::string& atom_id_2 = bond.data[i][i_atom_id_2]; |
| 128 | unsigned int value_order = residue::detail::Bond::parse_order(bond.data[i][i_value_order]); |
| 129 | current_residue.apply_bond(residue::detail::Bond(atom_id_1, atom_id_2, value_order)); |
| 130 | ++i; |
| 131 | } |
| 132 | |
| 133 | // remove a hydrogen bond from the N-terminus since it will almost always be bonded to the CA of the next chain |
| 134 | if (const auto& m = current_residue.get_name_map(); m.contains("N")) { |
| 135 | current_residue.get_atoms()[(m.at("N"))].hydrogen_bonds -= 1; |
| 136 | } |
| 137 | |
| 138 | // add aliases for O and OXT that are used in e.g. GROMACS output files |
| 139 | // ? it does not seem like there is any way to distinguish between the single and double bonded O's |
| 140 | // ? since there is at most a single O-terminus, the impact of switching them is minimal anyway |
| 141 | current_residue.add_atom("OC1", "OC1", constants::atom_t::O); |
| 142 | current_residue.get_atoms().back().hydrogen_bonds = 1; |
| 143 | current_residue.get_atoms().back().valency = 1; // single-bonded |
| 144 | current_residue.add_atom("OC2", "OC2", constants::atom_t::O); |
| 145 | current_residue.get_atoms().back().valency = 0; // double-bonded |
| 146 | } |
| 147 | |
| 148 | return residues; |
| 149 | } |
| 150 | |
| 151 | void parse_chem_comp_section(CIFSection& atom, CIFSection& bond) { |
| 152 | auto residues = parse_residue(atom, bond); |
| 153 | for (auto& residue : residues) { |
| 154 | constants::hydrogen_atoms::residues.insert(residue.get_name(), residue.to_map()); |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | void parse_atom_site_section(CIFSection& atom, io::pdb::PDBStructure& collection, bool allow_fractional_coords = false) { |
| 159 | if (atom.data.empty()) {throw except::io_error("CIFReader::parse_atom_site_section: Empty data section");} |
| 160 | auto labels = atom.get_label_map(); |
| 161 | |
| 162 | // PDB & mmCIF equivalence: |
| 163 | // Section _atom_site.group_PDB |
| 164 | // Serial_No _atom_site.id |
| 165 | // Atom_Name _atom_site.auth_atom_id |
| 166 | // Alt_Loc _atom_site.label_alt_id |
| 167 | // Residue_Name _atom_site.auth_comp_id |
| 168 | // Strand_ID _atom_site.auth_asym_id |
| 169 | // Residue_No _atom_site.auth_seq_id |
| 170 | // Ins_Code _atom_site.pdbx_PDB_ins_code |
| 171 | // X _atom_site.Cartn_x |
| 172 | // Y _atom_site.Cartn_y |
| 173 | // Z _atom_site.Cartn_z |
| 174 | // Occupancy _atom_site.occupancy |
| 175 | // T_Factor _atom_site.B_iso_or_equiv |
| 176 | // Sigma_X _atom_site.Cartn_x_esd |
| 177 | // Sigma_Y _atom_site.Cartn_y_esd |
| 178 | // Sigma_Z _atom_site.Cartn_z_esd |
| 179 | // Sigma_Occupancy _atom_site.occupancy_esd |
| 180 | // Sigma_T_Factor _atom_site.B_iso_or_equiv_esd |
| 181 | // Symbol _atom_site.type_symbol |
| 182 | // Charge _atom_site.pdbx_formal_charge |
| 183 | |
| 184 | std::string s_residue_name = "auth_comp_id"; |
| 185 | std::string s_coords_x = "Cartn_x"; |
| 186 | std::string s_coords_y = "Cartn_y"; |
| 187 | std::string s_coords_z = "Cartn_z"; |
| 188 | std::string default_to_ATOM = ""; |
| 189 | std::string default_to_UNK = ""; // residue |
| 190 | { // mandatory data |
| 191 | |
| 192 | // prefer author labels |
| 193 | if (!labels.contains(s_residue_name)) {s_residue_name = "label_comp_id";} |
| 194 | |
| 195 | if (!labels.contains("group_PDB")) { // HETATM or ATOM |
| 196 | console::print_text("CIFReader::parse_atom_site_section: Warning: Missing required label \"group_PDB\". Assuming all atoms are standard ATOM records."); |
| 197 | default_to_ATOM = "ATOM"; |
| 198 | } if (!labels.contains(s_residue_name)) { // residue name |
| 199 | console::print_text("CIFReader::parse_atom_site_section: Warning: Missing required label \"" + s_residue_name + "\". No residue information will be used."); |
| 200 | console::print_text_minor("\tDisabling implicit hydrogens."); |
| 201 | settings::molecule::implicit_hydrogens = false; |
| 202 | default_to_UNK = "UNK"; |
| 203 | } if (!labels.contains(s_coords_x)) { // x-coordinate |
| 204 | if (allow_fractional_coords) { |
| 205 | s_coords_x = "fract_x"; |
| 206 | if (!labels.contains(s_coords_x)) { |
| 207 | throw except::io_error("CIFReader::parse_atom_site_section: Missing required label \"Cartn_x\""); |
| 208 | } |
| 209 | } |
| 210 | } if (!labels.contains(s_coords_y)) { // y-coordinate |
| 211 | if (allow_fractional_coords) { |
| 212 | s_coords_y = "fract_y"; |
| 213 | if (!labels.contains(s_coords_y)) { |
| 214 | throw except::io_error("CIFReader::parse_atom_site_section: Missing required label \"Cartn_y\""); |
| 215 | } |
| 216 | } |
| 217 | } if (!labels.contains(s_coords_z)) { // z-coordinate |
| 218 | if (allow_fractional_coords) { |
| 219 | s_coords_z = "fract_z"; |
| 220 | if (!labels.contains(s_coords_z)) { |
| 221 | throw except::io_error("CIFReader::parse_atom_site_section: Missing required label \"Cartn_z\""); |
| 222 | } |
| 223 | } |
| 224 | } if (!labels.contains("type_symbol")) { // atomic element |
| 225 | throw except::io_error("CIFReader::parse_atom_site_section: Missing required label \"type_symbol\""); |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | bool optional_data = true; |
| 230 | std::string s_atom_name = "auth_atom_id"; |
| 231 | std::string s_chainID = "auth_asym_id"; |
| 232 | std::string s_residue_sequence_number = "auth_seq_id"; |
| 233 | { // optional data |
| 234 | |
| 235 | // prefer author labels |
| 236 | if (!labels.contains(s_atom_name)) {s_atom_name = "label_atom_id";} |
| 237 | if (!labels.contains(s_residue_name)) {s_residue_name = "label_comp_id";} |
| 238 | if (!labels.contains(s_chainID)) {s_chainID = "label_asym_id";} |
| 239 | if (!labels.contains(s_residue_sequence_number)) {s_residue_sequence_number = "label_seq_id";} |
| 240 | if (!( |
| 241 | labels.contains("id") && // serial number |
| 242 | labels.contains("label_alt_id") && // alternate location |
| 243 | labels.contains(s_atom_name) && // atom name |
| 244 | labels.contains(s_chainID) && // chain ID |
| 245 | labels.contains(s_residue_sequence_number) && // residue sequence number |
| 246 | labels.contains("pdbx_PDB_ins_code") && // insertion code |
| 247 | labels.contains("occupancy") && // occupancy |
| 248 | labels.contains("B_iso_or_equiv") && // temperature factor |
| 249 | labels.contains("pdbx_formal_charge") // charge |
| 250 | )) { |
| 251 | console::print_text("CIFReader::parse_atom_site_section: Missing optional labels in \"_atom_site\" section. Non-critical data will not be loaded."); |
| 252 | optional_data = false; |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | int i_group_PDB = default_to_ATOM.empty() ? labels.at("group_PDB") : -1; |
| 257 | int i_label_comp_id = default_to_UNK.empty() ? labels.at(s_residue_name) : -1; |
| 258 | int i_coord_x = labels.at(s_coords_x); |
| 259 | int i_coord_y = labels.at(s_coords_y); |
| 260 | int i_coord_z = labels.at(s_coords_z); |
| 261 | int i_type_symbol = labels.at("type_symbol"); |
| 262 | |
| 263 | int i_id = 0, i_label_alt_id = 0, i_label_atom_id = 0, i_label_asym_id = 0, i_label_seq_id = 0, |
| 264 | i_PDB_ins_code = 0, i_occupancy = 0, i_B_iso_or_equiv = 0, i_pdbx_formal_charge = 0; |
| 265 | if (optional_data) { |
| 266 | i_id = labels.at("id"); |
| 267 | i_label_alt_id = labels.at("label_alt_id"); |
| 268 | i_label_atom_id = labels.at(s_atom_name); |
| 269 | i_label_asym_id = labels.at(s_chainID); |
| 270 | i_label_seq_id = labels.at(s_residue_sequence_number); |
| 271 | i_PDB_ins_code = labels.at("pdbx_PDB_ins_code"); |
| 272 | i_occupancy = labels.at("occupancy"); |
| 273 | i_B_iso_or_equiv = labels.at("B_iso_or_equiv"); |
| 274 | i_pdbx_formal_charge = labels.at("pdbx_formal_charge"); |
| 275 | } |
| 276 | |
| 277 | //? not sure what the purpose of this guy is - truncating long input strings? |
| 278 | auto shorten = [] (const std::string& s) -> std::string { |
| 279 | return s.size() < 6 ? s : s.substr(0, 7); |
| 280 | }; |
| 281 | |
| 282 | int discarded_hydrogens = 0; |
| 283 | for (size_t i = 0; i < atom.data.size(); ++i) { |
| 284 | auto& group_PDB = default_to_ATOM.empty() ? atom.data[i][i_group_PDB] : default_to_ATOM; |
| 285 | if (io::pdb::Record::get_type(group_PDB) != io::pdb::RecordType::ATOM) { |
| 286 | throw except::io_error("CIFReader::parse_atom_site_section: Unrecognized group_PDB \"" + group_PDB + "\""); |
| 287 | } |
| 288 | |
| 289 | int serial = 0, resSeq = 0; |
| 290 | double occupancy = 1, tempFactor = 0; |
| 291 | char chainID = ' '; |
| 292 | std::string name, altLoc, resName, iCode, charge; |
| 293 | Vector3<double> coords; |
| 294 | constants::atom_t element; |
| 295 | |
| 296 | // load mandatory data |
| 297 | try { |
| 298 | name = atom.data[i][i_label_atom_id]; |
| 299 | resName = default_to_UNK.empty() ? atom.data[i][i_label_comp_id] : default_to_UNK; |
| 300 | coords = { |
| 301 | std::stod(shorten(atom.data[i][i_coord_x])), |
| 302 | std::stod(shorten(atom.data[i][i_coord_y])), |
| 303 | std::stod(shorten(atom.data[i][i_coord_z])), |
| 304 | }; |
| 305 | element = constants::symbols::parse_element_string(atom.data[i][i_type_symbol]); |
| 306 | if (optional_data) { |
| 307 | altLoc = atom.data[i][i_label_alt_id]; |
| 308 | chainID = atom.data[i][i_label_asym_id][0]; |
| 309 | iCode = atom.data[i][i_PDB_ins_code]; |
| 310 | charge = atom.data[i][i_pdbx_formal_charge]; |
| 311 | if (!atom.data[i][i_id].starts_with('.')) {serial = std::stoi(atom.data[i][i_id]);} |
| 312 | if (!atom.data[i][i_label_seq_id].starts_with('.')) {resSeq = std::stoi(atom.data[i][i_label_seq_id]);} |
| 313 | if (!atom.data[i][i_occupancy].starts_with('.')) {occupancy = std::stod(shorten(atom.data[i][i_occupancy]));} |
| 314 | if (!atom.data[i][i_B_iso_or_equiv].starts_with('.')) {tempFactor = std::stod(shorten(atom.data[i][i_B_iso_or_equiv]));} |
| 315 | } |
| 316 | } catch (const std::exception&) { |
| 317 | console::print_warning( |
| 318 | "CIFReader::parse_atom_site_section: Invalid field values in line: \n\"" + |
| 319 | std::accumulate( |
| 320 | atom.data[i].begin(), atom.data[i].end(), std::string(), |
| 321 | [] (const std::string& a, const std::string& b) {return a + " " + b;} |
| 322 | ) + "\"."); |
| 323 | throw; |
| 324 | } |
| 325 | io::pdb::PDBAtom a(serial, name, altLoc, resName, chainID, resSeq, iCode, coords, occupancy, tempFactor, element, charge); |
| 326 | |
| 327 | // check if this is a hydrogen atom |
| 328 | if (a.element == constants::atom_t::H && !settings::general::keep_hydrogens) { |
| 329 | discarded_hydrogens++; |
| 330 | continue; |
| 331 | } |
| 332 | |
| 333 | // check if this is a water molecule |
| 334 | if (a.is_water()) {collection.add(io::pdb::PDBWater(std::move(a)));} |
| 335 | else {collection.add(std::move(a));} |
| 336 | } |
| 337 | |
| 338 | if (!settings::molecule::use_occupancy) { |
| 339 | for (auto& a : collection.atoms) {a.occupancy = 1.0;} |
| 340 | } |
| 341 | |
| 342 | if (discarded_hydrogens != 0) { |
| 343 | console::print_text("Discarded " + std::to_string(discarded_hydrogens) + " explicit hydrogen atoms."); |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | /** |
| 348 | * @brief Extract all consecutive labels matching a given pattern, including associated data. |
| 349 | * The input stream will be advanced to the end of the block. |
| 350 | * |
| 351 | * @param pattern The label pattern to match. |
| 352 | * @param first_match The first line that matched the pattern. This is necessary since the line has already been read. |
| 353 | * @param input The input stream to read from. |
| 354 | */ |
| 355 | CIFSection extract_section(std::string_view pattern, std::string_view first_match, std::ifstream& input) { |
| 356 | std::vector<std::string> labels; |
| 357 | std::vector<std::vector<std::string>> data; |
| 358 | |
| 359 | // read labels |
| 360 | std::string line = std::string(first_match); |
| 361 | int full_line_size; |
| 362 | data.push_back({}); // add an empty data entry in case the labels also contains data |
| 363 | do { |
| 364 | full_line_size = static_cast<int>(line.size()); |
| 365 | line = utility::remove_leading(utility::remove_trailing(line, "\n\r"), " "); |
| 366 | if (line.empty()) {continue;} |
| 367 | if (line.starts_with('_')) { // label line |
| 368 | auto tokens = utility::split(line, ' '); |
| 369 | |
| 370 | // remove the pattern (and the following . or _) from the label |
| 371 | if (!tokens[0].starts_with(pattern)) { |
| 372 | // end of section, and no data will follow |
| 373 | if (data[0].empty()) {throw except::io_error( |
| 374 | "CIFReader::read: Label group matching \"" + std::string(pattern) + "\"" |
| 375 | " do not have inline data and is followed by more labels. This appears to be a bug. " |
| 376 | );} |
| 377 | input.seekg(-full_line_size-1, std::ios_base::cur); // rewind the last read line in the input stream |
| 378 | return CIFSection{std::move(labels), std::move(data)}; |
| 379 | } |
| 380 | labels.emplace_back(tokens[0].substr(pattern.size()+1)); |
| 381 | |
| 382 | // if the label is followed by a value, add it to the data |
| 383 | if (tokens.size() == 2) {data[0].emplace_back(std::move(tokens[1]));} |
| 384 | continue; |
| 385 | } else { |
| 386 | break; |
| 387 | } |
| 388 | } while(getline(input, line)); |
| 389 | if (data[0].empty()) {data.pop_back();} // remove the dummy data if empty |
| 390 | |
| 391 | static auto starts_with_quotation = [] (std::string_view s) -> bool { |
| 392 | return s.starts_with('"') || s.starts_with('\''); |
| 393 | }; |
| 394 | static auto ends_with_quotation = [] (std::string_view s) -> bool { |
| 395 | return s.ends_with('"') || s.ends_with('\''); |
| 396 | }; |
| 397 | |
| 398 | // read data. note that the first iteration is working on the last read line from the previous loop |
| 399 | do { |
| 400 | full_line_size = static_cast<int>(line.size()); |
| 401 | line = utility::remove_leading_and_trailing(utility::remove_trailing(line, "\n\r"), " "); |
| 402 | if (line.starts_with('#') || line.starts_with('_')) {break;} // end of loop section |
| 403 | if (line.empty()) {continue;} |
| 404 | auto values = utility::split(line, " "); |
| 405 | |
| 406 | int concatenated = 0; |
| 407 | for (size_t i = 0; i < values.size(); i++) { |
| 408 | if (starts_with_quotation(values[i])) { |
| 409 | if (ends_with_quotation(values[i])) { |
| 410 | // single-word quoted value |
| 411 | values[i] = values[i].substr(1, values[i].size()-2); |
| 412 | } else { |
| 413 | // search for the terminating quote |
| 414 | bool found_termination = false; |
| 415 | for (size_t j = i+1; j < values.size(); j++) { |
| 416 | if (ends_with_quotation(values[j])) { |
| 417 | // build concatenated value from values[i]..values[j], stripping quotes |
| 418 | std::string concatenated_value = std::string(values[i].substr(1)); // remove starting quote |
| 419 | for (size_t k = i+1; k < j; k++) { |
| 420 | concatenated_value += " " + values[k]; |
| 421 | } |
| 422 | concatenated_value += " " + std::string(values[j].substr(0, values[j].size()-1)); // remove ending quote |
| 423 | |
| 424 | // compute how many slots we will remove (number of tokens merged) |
| 425 | size_t shift = j - i; |
| 426 | values[i - concatenated] = std::move(concatenated_value); |
| 427 | concatenated += static_cast<int>(shift); |
| 428 | i = j; // skip to the end of the quoted value (outer loop will advance i++ to j+1) |
| 429 | found_termination = true; |
| 430 | break; |
| 431 | } |
| 432 | } |
| 433 | if (found_termination) {continue;} |
| 434 | throw except::io_error("CIFReader::read: Unterminated quote in data section: \n\"" + line + "\""); |
| 435 | } |
| 436 | } |
| 437 | values[i-concatenated] = values[i]; |
| 438 | } |
| 439 | values.resize(values.size()-concatenated); |
| 440 | |
| 441 | // sanity check |
| 442 | if (values.size() != labels.size()) { |
| 443 | throw except::io_error( |
| 444 | "CIFReader::read: Inconsistent number of values in data section: \n\"" + line + "\"" + |
| 445 | "\nExpected " + std::to_string(labels.size()) + " values, got " + std::to_string(values.size()) |
| 446 | ); |
| 447 | } |
| 448 | |
| 449 | data.emplace_back(std::move(values)); |
| 450 | } while(getline(input, line) && !line.starts_with("loop_")); |
| 451 | |
| 452 | // rewind the last read line in the input stream |
| 453 | input.seekg(-static_cast<int>(full_line_size)-1, std::ios_base::cur); |
| 454 | |
| 455 | return CIFSection{std::move(labels), std::move(data)}; |
| 456 | } |
| 457 | |
| 458 | std::vector<residue::detail::Residue> io::detail::cif::read_residue(const io::File& path) { |
| 459 | std::ifstream input(path); |
| 460 | if (!input.is_open()) {throw except::io_error("CIFReader::read_residue: Could not open file \"" + path.str() + "\"");} |
| 461 | |
| 462 | std::string line; |
| 463 | CIFSection chem_comp_atom, chem_comp_bond; |
| 464 | while(getline(input, line)) { |
| 465 | if (line.find("_chem_comp_atom") != std::string::npos) { |
| 466 | chem_comp_atom = extract_section("_chem_comp_atom", line, input); |
| 467 | } |
| 468 | |
| 469 | if (line.find("_chem_comp_bond") != std::string::npos) { |
| 470 | chem_comp_bond = extract_section("_chem_comp_bond", line, input); |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | if (chem_comp_bond.empty()) { |
| 475 | if (chem_comp_atom.empty()) {throw except::io_error("CIFReader::read_residue: Could not find any data sections in file \"" + path.str() + "\"");} |
| 476 | return {parse_ion(chem_comp_atom)}; |
| 477 | } else { |
| 478 | return parse_residue(chem_comp_atom, chem_comp_bond); |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | io::pdb::PDBStructure read_pdbx(CIFSection&& chem_comp_atom, CIFSection&& chem_comp_bond, CIFSection&& atom_site, const std::string& path) { |
| 483 | if (atom_site.empty()) {throw except::io_error("CIFReader::read: Could not find any atomic data section in file \"" + path + "\"");} |
| 484 | if (!chem_comp_atom.empty() && !chem_comp_bond.empty()) {parse_chem_comp_section(chem_comp_atom, chem_comp_bond);} |
| 485 | |
| 486 | io::pdb::PDBStructure file; |
| 487 | parse_atom_site_section(atom_site, file); |
| 488 | |
| 489 | unsigned int n_pa = file.atoms.size(); |
| 490 | unsigned int n_ha = file.waters.size(); |
| 491 | |
| 492 | console::print_text("Successfully read " + std::to_string(n_pa + n_ha) + " atomic records."); |
| 493 | if (n_ha != 0) {console::print_text("\t" + std::to_string(file.waters.size()) + " of these are hydration atoms.");} |
| 494 | console::unindent(); |
| 495 | return file; |
| 496 | } |
| 497 | |
| 498 | io::pdb::PDBStructure read_crystal(CIFSection&& cell_, CIFSection&& atom_site, const std::string&) { |
| 499 | io::pdb::PDBStructure file; |
| 500 | |
| 501 | double a, b, c; |
| 502 | double alpha = 90, beta = 90, gamma = 90; |
| 503 | { |
| 504 | auto labels = cell_.get_label_map(); |
| 505 | if (!labels.contains("length_a") || !labels.contains("length_b") || !labels.contains("length_c")){ |
| 506 | throw except::io_error("CIFReader::read_crystal: Missing required cell size labels in \"_cell\" section"); |
| 507 | } |
| 508 | if (!labels.contains("angle_alpha") || !labels.contains("angle_beta") || !labels.contains("angle_gamma")) { |
| 509 | console::print_text("CIFReader::read_crystal: Missing optional cell angle labels in \"_cell\" section. Assuming 90 degree angles."); |
| 510 | } else { |
| 511 | alpha = std::stod(cell_.data[0][labels.at("angle_alpha")]); |
| 512 | beta = std::stod(cell_.data[0][labels.at("angle_beta")]); |
| 513 | gamma = std::stod(cell_.data[0][labels.at("angle_gamma")]); |
| 514 | } |
| 515 | a = std::stod(cell_.data[0][labels.at("length_a")]); |
| 516 | b = std::stod(cell_.data[0][labels.at("length_b")]); |
| 517 | c = std::stod(cell_.data[0][labels.at("length_c")]); |
| 518 | } |
| 519 | |
| 520 | if (alpha != 90 || beta != 90 || gamma != 90) { |
| 521 | console::print_warning("CIFReader::read_crystal: Non-orthogonal unit cells are currently not supported."); |
| 522 | } |
| 523 | parse_atom_site_section(atom_site, file, true); |
| 524 | for (auto& atom : file.atoms) { |
| 525 | atom.coords.x() *= a; |
| 526 | atom.coords.y() *= b; |
| 527 | atom.coords.z() *= c; |
| 528 | } |
| 529 | |
| 530 | return file; |
| 531 | } |
| 532 | |
| 533 | io::pdb::PDBStructure io::detail::cif::read(const io::File& path) { |
| 534 | console::print_info("Reading CIF file from \"" + path.str() + "\""); |
| 535 | console::indent(); |
| 536 | |
| 537 | std::ifstream input(path); |
| 538 | if (!input.is_open()) {throw except::io_error("CIFReader::read: Could not open file \"" + path.str() + "\"");} |
| 539 | |
| 540 | std::string line; |
| 541 | CIFSection chem_comp_atom, chem_comp_bond, atom_site, cell_; |
| 542 | while(getline(input, line)) { |
| 543 | line = utility::remove_leading(utility::remove_all(line, "\n\r"), " "); |
| 544 | if (line.starts_with("_chem_comp_atom")) { |
| 545 | chem_comp_atom = extract_section("_chem_comp_atom", line, input); |
| 546 | } |
| 547 | |
| 548 | if (line.starts_with("_chem_comp_bond")) { |
| 549 | chem_comp_bond = extract_section("_chem_comp_bond", line, input); |
| 550 | } |
| 551 | |
| 552 | if (line.starts_with("_atom_site")) { |
| 553 | // we have to be a little careful since there may be multiple sections matching "_atom_site*" |
| 554 | // the main one will probably contain "type_symbol", however, so we use that to identify it |
| 555 | auto sec = extract_section("_atom_site", line, input); |
| 556 | if (sec.get_label_map().contains("type_symbol")) { |
| 557 | atom_site = std::move(sec); |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | if (line.starts_with("_cell")) { |
| 562 | cell_ = extract_section("_cell", line, input); |
| 563 | } |
| 564 | } |
| 565 | if (!cell_.empty() && chem_comp_atom.empty() && chem_comp_bond.empty()) { |
| 566 | // this is likely a crystal structure file |
| 567 | return read_crystal(std::move(cell_), std::move(atom_site), path.str()); |
| 568 | } else { |
| 569 | return read_pdbx(std::move(chem_comp_atom), std::move(chem_comp_bond), std::move(atom_site), path.str()); |
| 570 | } |
| 571 | } |