Debian Codegraph @

avogadro/io/pdbformat.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "pdbformat.h"
7
8 #include "avogadro/core/avogadrocore.h"
9 #include <avogadro/core/elements.h>
10 #include <avogadro/core/molecule.h>
11 #include <avogadro/core/residue.h>
12 #include <avogadro/core/secondarystructure.h>
13 #include <avogadro/core/spacegroups.h>
14 #include <avogadro/core/unitcell.h>
15 #include <avogadro/core/utilities.h>
16 #include <avogadro/core/vector.h>
17
18 #include <cctype>
19 #include <iostream>
20 #include <istream>
21 #include <string>
22
23 using Avogadro::Core::Array;
24 using Avogadro::Core::Atom;
25 using Avogadro::Core::Elements;
26 using Avogadro::Core::lexicalCast;
27 using Avogadro::Core::Residue;
28 using Avogadro::Core::SecondaryStructureAssigner;
29 using Avogadro::Core::startsWith;
30 using Avogadro::Core::trimmed;
31
32 using std::getline;
33 using std::istringstream;
34 using std::string;
35
36 namespace Avogadro::Io {
37
38 bool PdbFormat::read(std::istream& in, Core::Molecule& mol)
39 {
40 string buffer;
41 std::vector<int> terList;
42 Residue* r = nullptr;
43 size_t currentResidueId = 0;
44 bool ok(false);
45 int coordSet = 0;
46 Array<Vector3> positions;
47 Array<size_t> rawToAtomId;
48 Array<size_t> altAtomIds;
49 Array<int> altAtomCoordSets;
50 Array<char> altAtomLocs;
51 std::set<char> altLocs;
52 Array<Vector3> altAtomPositions;
53
54 while (getline(in, buffer)) { // Read Each line one by one
55 if (!in.good())
56 break;
57
58 if (startsWith(buffer, "ENDMDL")) {
59 // For the first frame (coordSet == 0), positions are stored directly
60 // in the molecule, not in the positions array
61 if (coordSet == 0) {
62 mol.setCoordinate3d(mol.atomPositions3d(), coordSet++);
63 } else if (!positions.empty()) {
64 mol.setCoordinate3d(positions, coordSet++);
65 positions.clear();
66 }
67 }
68
69 // e.g. CRYST1 4.912 4.912 6.696 90.00 90.00 120.00 P1 1
70 // https://www.wwpdb.org/documentation/file-format-content/format33/sect8.html
71 else if (startsWith(buffer, "CRYST1") && buffer.length() >= 55) {
72 // PDB reports in degrees and Angstroms
73 // Avogadro uses radians internally
74 auto a = lexicalCast<Real>(buffer.substr(6, 9));
75 auto b = lexicalCast<Real>(buffer.substr(15, 9));
76 auto c = lexicalCast<Real>(buffer.substr(24, 9));
77 auto alpha = lexicalCast<Real>(buffer.substr(33, 7));
78 auto beta = lexicalCast<Real>(buffer.substr(40, 7));
79 auto gamma = lexicalCast<Real>(buffer.substr(47, 8));
80
81 if (!a || !b || !c || !alpha || !beta || !gamma) {
82 appendError("Failed to parse CRYST1 :" + buffer);
83 return false;
84 }
85
86 auto* cell = new Core::UnitCell(*a, *b, *c, *alpha * DEG_TO_RAD,
87 *beta * DEG_TO_RAD, *gamma * DEG_TO_RAD);
88 if (!cell->isRegular()) {
89 appendError("CRYST1 does not give linear independent lattice vectors");
90 delete cell;
91 return false;
92 }
93 mol.setUnitCell(cell);
94
95 // Parse space group symbol from columns 56-66
96 if (buffer.length() >= 66) {
97 std::string spaceGroup = trimmed(buffer.substr(55, 11));
98 if (!spaceGroup.empty()) {
99 // Tweak PDB space group recognition, e.g. `P 1 21 1` -> `P 1 2_1 1`
100 // In each space-separated token, insert '_' between consecutive
101 // digits
102 for (size_t i = 0; i < spaceGroup.size() - 1; ++i) {
103 if (std::isdigit(spaceGroup[i]) &&
104 std::isdigit(spaceGroup[i + 1])) {
105 spaceGroup.insert(i + 1, 1, '_');
106 ++i; // skip past the inserted '_'
107 }
108 }
109
110 unsigned short hall = Core::SpaceGroups::hallNumber(spaceGroup);
111 if (hall > 0)
112 mol.setHallNumber(hall);
113 }
114 }
115 }
116
117 else if (startsWith(buffer, "ATOM") || startsWith(buffer, "HETATM")) {
118 if (buffer.length() < 54) {
119 appendError("Error reading line.");
120 return false;
121 }
122
123 // First we initialize the residue instance
124 auto residueId = lexicalCast<size_t>(buffer.substr(22, 4), ok);
125 if (!ok) {
126 appendError("Failed to parse residue sequence number: " +
127 buffer.substr(22, 4));
128 return false;
129 }
130
131 if (residueId != currentResidueId) {
132 currentResidueId = residueId;
133
134 auto residueName = lexicalCast<string>(buffer.substr(17, 3), ok);
135 if (!ok) {
136 appendError("Failed to parse residue name: " + buffer.substr(17, 3));
137 return false;
138 }
139
140 char chainId = lexicalCast<char>(buffer.substr(21, 1), ok);
141 if (!ok) {
142 chainId = 'A'; // it's a non-standard "PDB"-like file
143 }
144
145 r = &mol.addResidue(residueName, currentResidueId, chainId);
146 if (startsWith(buffer, "HETATM"))
147 r->setHeterogen(true);
148 }
149
150 auto atomName = lexicalCast<string>(buffer.substr(12, 4), ok);
151 if (!ok) {
152 appendError("Failed to parse atom name: " + buffer.substr(12, 4));
153 return false;
154 }
155
156 Vector3 pos; // Coordinates
157 pos.x() = lexicalCast<Real>(buffer.substr(30, 8), ok);
158 if (!ok) {
159 appendError("Failed to parse x coordinate: " + buffer.substr(30, 8));
160 return false;
161 }
162
163 pos.y() = lexicalCast<Real>(buffer.substr(38, 8), ok);
164 if (!ok) {
165 appendError("Failed to parse y coordinate: " + buffer.substr(38, 8));
166 return false;
167 }
168
169 pos.z() = lexicalCast<Real>(buffer.substr(46, 8), ok);
170 if (!ok) {
171 appendError("Failed to parse z coordinate: " + buffer.substr(46, 8));
172 return false;
173 }
174
175 auto altLoc = lexicalCast<string>(buffer.substr(16, 1), ok);
176
177 string element; // Element symbol, right justified
178 unsigned char atomicNum = 255;
179 if (buffer.size() >= 78) {
180 element = buffer.substr(76, 2);
181 element = trimmed(element);
182 if (element.length() == 2)
183 element[1] = std::tolower(element[1]);
184
185 atomicNum = Elements::atomicNumberFromSymbol(element);
186 if (atomicNum == 255)
187 appendError("Invalid element");
188 }
189
190 if (atomicNum == 255) {
191 // non-standard or old-school PDB file - try to parse the atom name
192 element = trimmed(atomName);
193 // remove any trailing digits
194 while (element.size() && std::isdigit(element.back()))
195 element.pop_back();
196
197 if (element == "SE") // For Sulphur
198 element = 'S';
199
200 atomicNum = Elements::atomicNumberFromSymbol(element);
201 if (atomicNum == 255) {
202 appendError("Invalid element");
203 continue; // skip this invalid record
204 }
205 }
206
207 if (altLoc.compare("") && altLoc.compare("A")) {
208 if (coordSet == 0) {
209 rawToAtomId.push_back(-1);
210 altAtomIds.push_back(mol.atomCount() - 1);
211 } else {
212 altAtomIds.push_back(positions.size() - 1);
213 }
214 altAtomCoordSets.push_back(coordSet);
215 altAtomLocs.push_back(altLoc[0]);
216 altLocs.insert(altLoc[0]);
217 altAtomPositions.push_back(pos);
218 } else if (coordSet == 0) {
219 Atom newAtom = mol.addAtom(atomicNum);
220 newAtom.setPosition3d(pos);
221 if (r != nullptr) {
222 r->addResidueAtom(atomName, newAtom);
223 }
224 rawToAtomId.push_back(mol.atomCount() - 1);
225 } else {
226 positions.push_back(pos);
227 }
228 }
229
230 else if (startsWith(buffer, "TER") &&
231 buffer.length() >= 11) { // This is very important, each TER
232 // record also counts in the serial.
233 // Need to account for that when comparing with CONECT
234 terList.push_back(lexicalCast<int>(buffer.substr(6, 5), ok));
235
236 if (!ok) {
237 appendError("Failed to parse TER serial");
238 return false;
239 }
240 }
241
242 else if (startsWith(buffer, "CONECT")) {
243 if (buffer.length() < 16) {
244 appendError("Error reading line.");
245 return false;
246 }
247
248 int a = lexicalCast<int>(buffer.substr(6, 5), ok);
249 if (!ok) {
250 appendError("Failed to parse bond connection a " + buffer.substr(6, 5));
251 return false;
252 }
253 --a;
254 size_t terCount;
255 for (terCount = 0; terCount < terList.size() && a > terList[terCount];
256 ++terCount)
257 ; // semicolon is intentional
258 a = a - terCount;
259 a = rawToAtomId[a];
260
261 int bCoords[] = { 11, 16, 21, 26 };
262 for (int i = 0; i < 4; i++) {
263 // Check if buffer is long enough for this column
264 if (static_cast<int>(buffer.length()) < bCoords[i] + 5)
265 break;
266 if (trimmed(buffer.substr(bCoords[i], 5)).empty())
267 break;
268
269 else {
270 int b = lexicalCast<int>(buffer.substr(bCoords[i], 5), ok) - 1;
271 if (!ok) {
272 appendError("Failed to parse bond connection b" +
273 std::to_string(i) + " " + buffer.substr(bCoords[i], 5));
274 // return false;
275 continue; // skip this invalid record
276 }
277
278 for (terCount = 0; terCount < terList.size() && b > terList[terCount];
279 ++terCount)
280 ; // semicolon is intentional
281 b = b - terCount;
282 b = rawToAtomId[b];
283
284 if (a >= 0 && b >= 0) {
285 auto aIndex = static_cast<Avogadro::Index>(a);
286 auto bIndex = static_cast<Avogadro::Index>(b);
287 if (aIndex < mol.atomCount() && bIndex < mol.atomCount()) {
288 mol.addBond(aIndex, bIndex, 1);
289 } else {
290 appendError("Invalid bond connection: " + std::to_string(a) +
291 " - " + std::to_string(b));
292 }
293 }
294 }
295 }
296 }
297 } // End while loop
298
299 if (mol.atomCount() == 0) {
300 appendError("No atoms found in this file.");
301 return false;
302 }
303
304 if (!positions.empty()) {
305 // This handles the last set of positions if the file doesn't end with
306 // ENDMDL
307 mol.setCoordinate3d(positions, coordSet);
308 }
309
310 int count = mol.coordinate3dCount() ? mol.coordinate3dCount() : 1;
311 for (int c = 0; c < count; ++c) {
312 for (char l : altLocs) {
313 Array<Vector3> coordinateSet =
314 c == 0 ? mol.atomPositions3d() : mol.coordinate3d(c);
315 bool found = false;
316 for (size_t i = 0; i < altAtomCoordSets.size(); ++i) {
317 if (altAtomCoordSets[i] == c && altAtomLocs[i] == l) {
318 found = true;
319 coordinateSet[altAtomIds[i]] = altAtomPositions[i];
320 }
321 }
322 if (found)
323 mol.setCoordinate3d(
324 coordinateSet, mol.coordinate3dCount() ? mol.coordinate3dCount() : 1);
325 }
326 }
327
328 mol.perceiveBondsSimple();
329 mol.perceiveBondsFromResidueData();
330 perceiveSubstitutedCations(mol);
331
332 // if there are residue data, assign secondary structure
333 if (mol.residueCount() != 0) {
334 SecondaryStructureAssigner ssa;
335 ssa.assign(&mol);
336 }
337
338 return true;
339 } // End read
340
341 std::vector<std::string> PdbFormat::fileExtensions() const
342 {
343 std::vector<std::string> ext;
344 ext.emplace_back("pdb");
345 ext.emplace_back("ent");
346 return ext;
347 }
348
349 std::vector<std::string> PdbFormat::mimeTypes() const
350 {
351 std::vector<std::string> mime;
352 mime.emplace_back("chemical/x-pdb");
353 return mime;
354 }
355
356 void PdbFormat::perceiveSubstitutedCations(Core::Molecule& molecule)
357 {
358 for (Index i = 0; i < molecule.atomCount(); i++) {
359 unsigned char requiredBondCount(0);
360 switch (molecule.atomicNumber(i)) {
361 case 7:
362 case 15:
363 case 33:
364 case 51:
365 requiredBondCount = 4;
366 break;
367 case 8:
368 case 16:
369 case 34:
370 case 52:
371 requiredBondCount = 3;
372 }
373 if (!requiredBondCount)
374 continue;
375
376 unsigned char bondCount(0);
377 Index j = 0;
378 for (const auto& bond : molecule.bonds(i)) {
379 unsigned char otherAtomicNumber(0);
380 otherAtomicNumber = molecule.atomicNumber(bond.getOtherAtom(i).index());
381 bondCount += bond.order();
382 if (otherAtomicNumber && otherAtomicNumber != 6) {
383 bondCount = 0;
384 break;
385 }
386 j++;
387 }
388
389 if (bondCount == requiredBondCount) {
390 molecule.setFormalCharge(i, 1);
391 }
392 }
393 }
394
395 } // namespace Avogadro::Io