source: src/Parser/PdbParser.cpp@ 830b3e

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 830b3e was 830b3e, checked in by Frederik Heber <heber@…>, 12 years ago

VERBOSE: Changed Parser's verbosity level for stating "Saving changes."

  • Property mode set to 100644
File size: 33.9 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
5 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * PdbParser.cpp
25 *
26 * Created on: Aug 17, 2010
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include "CodePatterns/MemDebug.hpp"
36
37#include "CodePatterns/Assert.hpp"
38#include "CodePatterns/Log.hpp"
39#include "CodePatterns/toString.hpp"
40#include "CodePatterns/Verbose.hpp"
41
42#include "Atom/atom.hpp"
43#include "Bond/bond.hpp"
44#include "Descriptors/AtomIdDescriptor.hpp"
45#include "Element/element.hpp"
46#include "Element/periodentafel.hpp"
47#include "molecule.hpp"
48#include "MoleculeListClass.hpp"
49#include "Parser/PdbParser.hpp"
50#include "World.hpp"
51#include "WorldTime.hpp"
52
53#include <algorithm>
54#include <cmath>
55#include <map>
56#include <vector>
57
58#include <iostream>
59#include <iomanip>
60
61using namespace std;
62
63// declare specialized static variables
64const std::string FormatParserTrait<pdb>::name = "pdb";
65const std::string FormatParserTrait<pdb>::suffix = "pdb";
66const ParserTypes FormatParserTrait<pdb>::type = pdb;
67
68/**
69 * Constructor.
70 */
71FormatParser< pdb >::FormatParser() :
72 FormatParser_common(NULL)
73{
74 knownTokens["ATOM"] = PdbKey::Atom;
75 knownTokens["HETATM"] = PdbKey::Atom;
76 knownTokens["TER"] = PdbKey::Filler;
77 knownTokens["END"] = PdbKey::EndOfTimestep;
78 knownTokens["CONECT"] = PdbKey::Connect;
79 knownTokens["REMARK"] = PdbKey::Remark;
80 knownTokens[""] = PdbKey::EndOfTimestep;
81
82 // argh, why can't just PdbKey::X+(size_t)i
83 PositionEnumMap[0] = PdbKey::X;
84 PositionEnumMap[1] = PdbKey::Y;
85 PositionEnumMap[2] = PdbKey::Z;
86}
87
88/**
89 * Destructor.
90 */
91FormatParser< pdb >::~FormatParser()
92{
93 PdbAtomInfoContainer::clearknownDataKeys();
94 additionalAtomData.clear();
95}
96
97
98/** Parses the initial word of the given \a line and returns the token type.
99 *
100 * @param line line to scan
101 * @return token type
102 */
103enum PdbKey::KnownTokens FormatParser< pdb >::getToken(std::string &line)
104{
105 // look for first space
106 std::string token = line.substr(0,6);
107 const size_t space_location = token.find(' ');
108 const size_t tab_location = token.find('\t');
109 size_t location = space_location < tab_location ? space_location : tab_location;
110 if (location != string::npos) {
111 //LOG(1, "Found space at position " << space_location);
112 token = token.substr(0,space_location);
113 }
114
115 //LOG(1, "Token is " << token);
116 if (knownTokens.count(token) == 0)
117 return PdbKey::NoToken;
118 else
119 return knownTokens[token];
120
121 return PdbKey::NoToken;
122}
123
124/**
125 * Loads atoms from a PDB-formatted file.
126 *
127 * \param PDB file
128 */
129void FormatParser< pdb >::load(istream* file) {
130 string line;
131 size_t linecount = 0;
132 enum PdbKey::KnownTokens token;
133
134 // reset id maps for this file (to correctly parse CONECT entries)
135 resetIdAssociations();
136
137 bool NotEndOfFile = true;
138 molecule *newmol = World::getInstance().createMolecule();
139 newmol->ActiveFlag = true;
140 unsigned int step = 0;
141 // TODO: Remove the insertion into molecule when saving does not depend on them anymore. Also, remove molecule.hpp include
142 World::getInstance().getMolecules()->insert(newmol);
143 while (NotEndOfFile) {
144 bool NotEndOfTimestep = true;
145 while (NotEndOfTimestep && NotEndOfFile) {
146 std::getline(*file, line, '\n');
147 if (!line.empty()) {
148 // extract first token
149 token = getToken(line);
150 switch (token) {
151 case PdbKey::Atom:
152 LOG(3,"INFO: Parsing ATOM entry for time step " << step << ".");
153 readAtomDataLine(step, line, newmol);
154 break;
155 case PdbKey::Remark:
156 LOG(3,"INFO: Parsing REM entry for time step " << step << ".");
157 break;
158 case PdbKey::Connect:
159 LOG(3,"INFO: Parsing CONECT entry for time step " << step << ".");
160 readNeighbors(step, line);
161 break;
162 case PdbKey::Filler:
163 LOG(3,"INFO: Stumbled upon Filler entry for time step " << step << ".");
164 break;
165 case PdbKey::EndOfTimestep:
166 LOG(1,"INFO: Parsing END entry or empty line for time step " << step << ".");
167 NotEndOfTimestep = false;
168 break;
169 default:
170 // TODO: put a throw here
171 ELOG(2, "Unknown token: '" << line << "' for time step " << step << ".");
172 //ASSERT(0, "FormatParser< pdb >::load() - Unknown token in line "+toString(linecount)+": "+line+".");
173 break;
174 }
175 }
176 NotEndOfFile = NotEndOfFile && (file->good());
177 linecount++;
178 }
179 ++step;
180 }
181 LOG(4, "INFO: Listing all newly parsed atoms.");
182 BOOST_FOREACH(atom *_atom, *newmol)
183 LOG(4, "INFO: Atom " << _atom->getName() << " " << *dynamic_cast<AtomInfo *>(_atom) << ".");
184
185 // refresh atom::nr and atom::name
186 newmol->getAtomCount();
187}
188
189/**
190 * Saves the \a atoms into as a PDB file.
191 *
192 * \param file where to save the state
193 * \param atoms atoms to store
194 */
195void FormatParser< pdb >::save(ostream* file, const std::vector<atom *> &AtomList)
196{
197 LOG(2, "DEBUG: Saving changes to pdb.");
198
199 // check for maximum number of time steps
200 size_t max_timesteps = 0;
201 BOOST_FOREACH(atom *_atom, World::getInstance().getAllAtoms()) {
202 LOG(4, "INFO: Atom " << _atom->getName() << " " << *dynamic_cast<AtomInfo *>(_atom) << ".");
203 if (_atom->getTrajectorySize() > max_timesteps)
204 max_timesteps = _atom->getTrajectorySize();
205 }
206 LOG(2,"INFO: Found a maximum of " << max_timesteps << " time steps to store.");
207
208 // re-distribute serials
209 resetIdAssociations();
210 // (new atoms might have been added)
211 int AtomNo = 1; // serial number starts at 1 in pdb
212 for (vector<atom *>::const_iterator atomIt = AtomList.begin(); atomIt != AtomList.end(); atomIt++) {
213 PdbAtomInfoContainer &atomInfo = getadditionalAtomData(*atomIt);
214 associateLocaltoGlobalId(AtomNo, (*atomIt)->getId());
215 atomInfo.set(PdbKey::serial, toString(AtomNo));
216 ++AtomNo;
217 }
218
219 // store all time steps (always do first step)
220 for (size_t step = 0; (step == 0) || (step < max_timesteps); ++step) {
221 {
222 // add initial remark
223 *file << "REMARK created by molecuilder on ";
224 time_t now = time((time_t *)NULL); // Get the system time and put it into 'now' as 'calender time'
225 // ctime ends in \n\0, we have to cut away the newline
226 std::string time(ctime(&now));
227 size_t pos = time.find('\n');
228 if (pos != 0)
229 *file << time.substr(0,pos);
230 else
231 *file << time;
232 *file << ", time step " << step;
233 *file << endl;
234 }
235
236 {
237 std::map<size_t,size_t> MolIdMap;
238 size_t MolNo = 1; // residue number starts at 1 in pdb
239 for (vector<atom *>::const_iterator atomIt = AtomList.begin(); atomIt != AtomList.end(); atomIt++) {
240 const molecule *mol = (*atomIt)->getMolecule();
241 if ((mol != NULL) && (MolIdMap.find(mol->getId()) == MolIdMap.end())) {
242 MolIdMap[mol->getId()] = MolNo++;
243 }
244 }
245 const size_t MaxMol = MolNo;
246
247 // have a count per element and per molecule (0 is for all homeless atoms)
248 std::vector<int> **elementNo = new std::vector<int>*[MaxMol];
249 for (size_t i = 0; i < MaxMol; ++i)
250 elementNo[i] = new std::vector<int>(MAX_ELEMENTS,1);
251 char name[MAXSTRINGSIZE];
252 std::string ResidueName;
253
254 // write ATOMs
255 for (vector<atom *>::const_iterator atomIt = AtomList.begin(); atomIt != AtomList.end(); atomIt++) {
256 PdbAtomInfoContainer &atomInfo = getadditionalAtomData(*atomIt);
257 // gather info about residue
258 const molecule *mol = (*atomIt)->getMolecule();
259 if (mol == NULL) {
260 MolNo = 0;
261 atomInfo.set(PdbKey::resSeq, "0");
262 } else {
263 ASSERT(MolIdMap.find(mol->getId()) != MolIdMap.end(),
264 "FormatParser< pdb >::save() - Mol id "+toString(mol->getId())+" not present despite we set it?!");
265 MolNo = MolIdMap[mol->getId()];
266 atomInfo.set(PdbKey::resSeq, toString(MolIdMap[mol->getId()]));
267 if (atomInfo.get<std::string>(PdbKey::resName) == "-")
268 atomInfo.set(PdbKey::resName, mol->getName().substr(0,3));
269 }
270 // get info about atom
271 const size_t Z = (*atomIt)->getType()->getAtomicNumber();
272 if (atomInfo.get<std::string>(PdbKey::name) == "-") { // if no name set, give it a new name
273 sprintf(name, "%2s%02d",(*atomIt)->getType()->getSymbol().c_str(), (*elementNo[MolNo])[Z]);
274 (*elementNo[MolNo])[Z] = ((*elementNo[MolNo])[Z]+1) % 100; // confine to two digits
275 atomInfo.set(PdbKey::name, name);
276 }
277 // set position
278 for (size_t i=0; i<NDIM;++i) {
279 stringstream position;
280 position << setprecision(7) << (*atomIt)->getPositionAtStep(step).at(i);
281 atomInfo.set(PositionEnumMap[i], position.str());
282 }
283 // change element and charge if changed
284 if (atomInfo.get<std::string>(PdbKey::element) != (*atomIt)->getType()->getSymbol()) {
285 std::string symbol = (*atomIt)->getType()->getSymbol();
286 if ((symbol[1] >= 'a') && (symbol[1] <= 'z'))
287 symbol[1] = (symbol[1] - 'a') + 'A';
288 atomInfo.set(PdbKey::element, symbol);
289 }
290
291 // finally save the line
292 saveLine(file, atomInfo);
293 }
294 for (size_t i = 0; i < MaxMol; ++i)
295 delete elementNo[i];
296 delete elementNo;
297
298 // write CONECTs
299 for (vector<atom *>::const_iterator atomIt = AtomList.begin(); atomIt != AtomList.end(); atomIt++) {
300 writeNeighbors(file, 4, *atomIt);
301 }
302 }
303 // END
304 *file << "END" << endl;
305 }
306
307}
308
309/** Add default info, when new atom is added to World.
310 *
311 * @param id of atom
312 */
313void FormatParser< pdb >::AtomInserted(atomId_t id)
314{
315 //LOG(3, "FormatParser< pdb >::AtomInserted() - notified of atom " << id << "'s insertion.");
316 ASSERT(!isPresentadditionalAtomData(id),
317 "FormatParser< pdb >::AtomInserted() - additionalAtomData already present for newly added atom "
318 +toString(id)+".");
319 // don't insert here as this is our check whether we are in the first time step
320 //additionalAtomData.insert( std::make_pair(id, defaultAdditionalData) );
321}
322
323/** Remove additional AtomData info, when atom has been removed from World.
324 *
325 * @param id of atom
326 */
327void FormatParser< pdb >::AtomRemoved(atomId_t id)
328{
329 //LOG(3, "FormatParser< pdb >::AtomRemoved() - notified of atom " << id << "'s removal.");
330 std::map<const atomId_t, PdbAtomInfoContainer>::iterator iter = additionalAtomData.find(id);
331 // as we do not insert AtomData on AtomInserted, we cannot be assured of its presence
332// ASSERT(iter != additionalAtomData.end(),
333// "FormatParser< pdb >::AtomRemoved() - additionalAtomData is not present for atom "
334// +toString(id)+" to remove.");
335 if (iter != additionalAtomData.end()) {
336 additionalAtomData.erase(iter);
337 }
338}
339
340
341/** Checks whether there is an entry for the given atom's \a _id.
342 *
343 * @param _id atom's id we wish to check on
344 * @return true - entry present, false - only for atom's father or no entry
345 */
346bool FormatParser< pdb >::isPresentadditionalAtomData(const atomId_t _id) const
347{
348 std::map<const atomId_t, PdbAtomInfoContainer>::const_iterator iter = additionalAtomData.find(_id);
349 return (iter != additionalAtomData.end());
350}
351
352
353/** Either returns reference to present entry or creates new with default values.
354 *
355 * @param _atom atom whose entry we desire
356 * @return
357 */
358PdbAtomInfoContainer& FormatParser< pdb >::getadditionalAtomData(atom *_atom)
359{
360 if (additionalAtomData.find(_atom->getId()) != additionalAtomData.end()) {
361 } else if (additionalAtomData.find(_atom->father->getId()) != additionalAtomData.end()) {
362 // use info from direct father
363 additionalAtomData[_atom->getId()] = additionalAtomData[_atom->father->getId()];
364 } else if (additionalAtomData.find(_atom->GetTrueFather()->getId()) != additionalAtomData.end()) {
365 // use info from topmost father
366 additionalAtomData[_atom->getId()] = additionalAtomData[_atom->GetTrueFather()->getId()];
367 } else {
368 // create new entry use default values if nothing else is known
369 additionalAtomData[_atom->getId()] = defaultAdditionalData;
370 }
371 return additionalAtomData[_atom->getId()];
372}
373
374/** Tiny helper function to print a float with a most 8 digits.
375 *
376 * A few examples best give the picture:
377 * 1234.678
378 * 1.234
379 * 0.001
380 * 0.100
381 * 1234567.
382 * 123456.7
383 * -1234.56
384 *
385 * \param value
386 * \return string representation
387 */
388const std::string FormatParser< pdb >::printCoordinate(
389 const double value)
390{
391 size_t meaningful_bits=7; // one for decimal dot
392 if (value < 0) //one for the minus sign
393 --meaningful_bits;
394 // count digits before dot (without minus and round towards zero!)
395 const int full = floor(fabs(value));
396 size_t bits_before_dot = 1;
397 {
398 int tmp = full;
399 for (;bits_before_dot < meaningful_bits;++bits_before_dot) {
400 // even if value is 0...somethingish, we still must start at one digit
401 tmp = tmp/10;
402 if (tmp == 0)
403 break;
404 }
405 }
406 // this fixes bits available after dot
407 const size_t bits_after_dot = std::min((int)meaningful_bits - (int)bits_before_dot, 3);
408 stringstream position;
409 if (bits_after_dot > 0) {
410 if (value < 0)
411 position << "-";
412 const int remainder = round((abs(value)-full)*pow(10,bits_after_dot));
413 position << full << "." << setfill('0') << setw(bits_after_dot) << remainder;
414 if (bits_after_dot == 2)
415 ELOG(2, "PdbParser is writing coordinates with just a two decimal places.");
416 if (bits_after_dot == 1)
417 ELOG(1, "PdbParser is writing coordinates with just a single decimal places.");
418 } else {
419 ELOG(0, "PdbParser is writing coordinates without any decimal places.");
420 position << full << ".";
421 }
422 return position.str();
423}
424
425/**
426 * Writes one line of PDB-formatted data to the provided stream.
427 *
428 * \param stream where to write the line to
429 * \param *currentAtom the atom of which information should be written
430 * \param AtomNo serial number of atom
431 * \param *name name of atom, i.e. H01
432 * \param ResidueName Name of molecule
433 * \param ResidueNo number of residue
434 */
435void FormatParser< pdb >::saveLine(
436 ostream* file,
437 const PdbAtomInfoContainer &atomInfo)
438{
439 *file << setfill(' ') << left << setw(6)
440 << atomInfo.get<std::string>(PdbKey::token);
441 *file << setfill(' ') << right << setw(5)
442 << (atomInfo.get<int>(PdbKey::serial) % 100000); /* atom serial number */
443 *file << " "; /* char 12 is empty */
444 *file << setfill(' ') << left << setw(4)
445 << atomInfo.get<std::string>(PdbKey::name); /* atom name */
446 *file << setfill(' ') << left << setw(1)
447 << atomInfo.get<std::string>(PdbKey::altLoc); /* alternate location/conformation */
448 *file << setfill(' ') << left << setw(3)
449 << atomInfo.get<std::string>(PdbKey::resName); /* residue name */
450 *file << " "; /* char 21 is empty */
451 *file << setfill(' ') << left << setw(1)
452 << atomInfo.get<std::string>(PdbKey::chainID); /* chain identifier */
453 *file << setfill(' ') << left << setw(4)
454 << (atomInfo.get<int>(PdbKey::resSeq) % 10000); /* residue sequence number */
455 *file << setfill(' ') << left << setw(1)
456 << atomInfo.get<std::string>(PdbKey::iCode); /* iCode */
457 *file << " "; /* char 28-30 are empty */
458 // have the following operate on stringstreams such that format specifiers
459 // only act on these
460 for (size_t i=0;i<NDIM;++i) {
461 *file << setfill(' ') << right << setw(8)
462 << printCoordinate(atomInfo.get<double>(PositionEnumMap[i]));
463 }
464 {
465 stringstream occupancy;
466 occupancy << fixed << setprecision(2) << showpoint
467 << atomInfo.get<double>(PdbKey::occupancy); /* occupancy */
468 *file << setfill(' ') << right << setw(6) << occupancy.str();
469 }
470 {
471 stringstream tempFactor;
472 tempFactor << fixed << setprecision(2) << showpoint
473 << atomInfo.get<double>(PdbKey::tempFactor); /* temperature factor */
474 *file << setfill(' ') << right << setw(6) << tempFactor.str();
475 }
476 *file << " "; /* char 68-76 are empty */
477 *file << setfill(' ') << right << setw(2) << atomInfo.get<std::string>(PdbKey::element); /* element */
478 *file << setfill(' ') << right << setw(2) << atomInfo.get<int>(PdbKey::charge); /* charge */
479
480 *file << endl;
481}
482
483/**
484 * Writes the neighbor information of one atom to the provided stream.
485 *
486 * Note that ListOfBonds of WorldTime::CurrentTime is used.
487 *
488 * Also, we fill up the CONECT line to extend over 80 chars.
489 *
490 * \param *file where to write neighbor information to
491 * \param MaxnumberOfNeighbors of neighbors
492 * \param *currentAtom to the atom of which to take the neighbor information
493 */
494void FormatParser< pdb >::writeNeighbors(ostream* file, int MaxnumberOfNeighbors, atom* currentAtom) {
495 int MaxNo = MaxnumberOfNeighbors;
496 int charsleft = 80;
497 const BondList & ListOfBonds = currentAtom->getListOfBonds();
498 if (!ListOfBonds.empty()) {
499 for(BondList::const_iterator currentBond = ListOfBonds.begin(); currentBond != ListOfBonds.end(); ++currentBond) {
500 if (MaxNo >= MaxnumberOfNeighbors) {
501 *file << "CONECT";
502 *file << setw(5) << getLocalId(currentAtom->getId());
503 charsleft = 80-6-5;
504 MaxNo = 0;
505 }
506 *file << setw(5) << getLocalId((*currentBond)->GetOtherAtom(currentAtom)->getId());
507 charsleft -= 5;
508 MaxNo++;
509 if (MaxNo == MaxnumberOfNeighbors) {
510 for (;charsleft > 0; charsleft--)
511 *file << ' ';
512 *file << "\n";
513 }
514 }
515 if (MaxNo != MaxnumberOfNeighbors) {
516 for (;charsleft > 0; charsleft--)
517 *file << ' ';
518 *file << "\n";
519 }
520 }
521}
522
523/** Either returns present atom with given id or a newly created one.
524 *
525 * @param id_string
526 * @return
527 */
528atom* FormatParser< pdb >::getAtomToParse(std::string id_string)
529{
530 // get the local ID
531 ConvertTo<int> toInt;
532 const unsigned int AtomID_local = toInt(id_string);
533 LOG(4, "INFO: Local id is "+toString(AtomID_local)+".");
534 // get the atomic ID if present
535 atom* newAtom = NULL;
536 if (getGlobalId(AtomID_local) != -1) {
537 const unsigned int AtomID_global = getGlobalId(AtomID_local);
538 LOG(4, "INFO: Global id present as " << AtomID_global << ".");
539 // check if atom exists
540 newAtom = World::getInstance().getAtom(AtomById(AtomID_global));
541 LOG(5, "INFO: Listing all present atoms with id.");
542 BOOST_FOREACH(atom *_atom, World::getInstance().getAllAtoms())
543 LOG(5, "INFO: " << *_atom << " with id " << _atom->getId());
544 }
545 // if not exists, create
546 if (newAtom == NULL) {
547 newAtom = World::getInstance().createAtom();
548 //const unsigned int AtomID_global = newAtom->getId();
549 LOG(4, "INFO: No association to global id present, creating atom.");
550 } else {
551 LOG(4, "INFO: Existing atom found: " << *newAtom << ".");
552 }
553 return newAtom;
554}
555
556/** read a line starting with key ATOM.
557 *
558 * We check for line's length and parse only up to this value.
559 *
560 * @param atomInfo container to put information in
561 * @param line line containing key ATOM
562 */
563void FormatParser< pdb >::readPdbAtomInfoContainer(PdbAtomInfoContainer &atomInfo, std::string &line) const
564{
565 const size_t length = line.length();
566 if (length < 80)
567 ELOG(2, "FormatParser< pdb >::readPdbAtomInfoContainer() - pdb is mal-formed, containing less than 80 chars!");
568 if (length >= 6) {
569 LOG(4,"INFO: Parsing token from "+line.substr(0,6)+".");
570 atomInfo.set(PdbKey::token, line.substr(0,6));
571 }
572 if (length >= 11) {
573 LOG(4,"INFO: Parsing serial from "+line.substr(6,5)+".");
574 atomInfo.set(PdbKey::serial, line.substr(6,5));
575 ASSERT(atomInfo.get<int>(PdbKey::serial) != 0,
576 "FormatParser< pdb >::readPdbAtomInfoContainer() - serial 0 is invalid (filler id for conect entries).");
577 }
578
579 if (length >= 16) {
580 LOG(4,"INFO: Parsing name from "+line.substr(12,4)+".");
581 atomInfo.set(PdbKey::name, line.substr(12,4));
582 }
583 if (length >= 17) {
584 LOG(4,"INFO: Parsing altLoc from "+line.substr(16,1)+".");
585 atomInfo.set(PdbKey::altLoc, line.substr(16,1));
586 }
587 if (length >= 20) {
588 LOG(4,"INFO: Parsing resName from "+line.substr(17,3)+".");
589 atomInfo.set(PdbKey::resName, line.substr(17,3));
590 }
591 if (length >= 22) {
592 LOG(4,"INFO: Parsing chainID from "+line.substr(21,1)+".");
593 atomInfo.set(PdbKey::chainID, line.substr(21,1));
594 }
595 if (length >= 26) {
596 LOG(4,"INFO: Parsing resSeq from "+line.substr(22,4)+".");
597 atomInfo.set(PdbKey::resSeq, line.substr(22,4));
598 }
599 if (length >= 27) {
600 LOG(4,"INFO: Parsing iCode from "+line.substr(26,1)+".");
601 atomInfo.set(PdbKey::iCode, line.substr(26,1));
602 }
603
604 if (length >= 60) {
605 LOG(4,"INFO: Parsing occupancy from "+line.substr(54,6)+".");
606 atomInfo.set(PdbKey::occupancy, line.substr(54,6));
607 }
608 if (length >= 66) {
609 LOG(4,"INFO: Parsing tempFactor from "+line.substr(60,6)+".");
610 atomInfo.set(PdbKey::tempFactor, line.substr(60,6));
611 }
612 if (length >= 80) {
613 LOG(4,"INFO: Parsing charge from "+line.substr(78,2)+".");
614 atomInfo.set(PdbKey::charge, line.substr(78,2));
615 }
616 if (length >= 78) {
617 LOG(4,"INFO: Parsing element from "+line.substr(76,2)+".");
618 atomInfo.set(PdbKey::element, line.substr(76,2));
619 } else {
620 LOG(4,"INFO: Trying to parse alternative element from name "+line.substr(12,4)+".");
621 atomInfo.set(PdbKey::element, line.substr(12,4));
622 }
623}
624
625/** Parse an ATOM line from a PDB file.
626 *
627 * Reads one data line of a pdstatus file and interprets it according to the
628 * specifications of the PDB 3.2 format: http://www.wwpdb.org/docs.html
629 *
630 * A new atom is created and filled with available information, non-
631 * standard information is placed in additionalAtomData at the atom's id.
632 *
633 * \param _step time step to use
634 * \param line to parse as an atom
635 * \param newmol molecule to add parsed atoms to
636 */
637void FormatParser< pdb >::readAtomDataLine(const unsigned int _step, std::string &line, molecule *newmol = NULL) {
638 vector<string>::iterator it;
639
640 atom* newAtom = getAtomToParse(line.substr(6,5));
641 LOG(3,"INFO: Parsing END entry or empty line.");
642 bool FirstTimestep = isPresentadditionalAtomData(newAtom->getId()) ? false : true;
643 ASSERT((FirstTimestep && (_step == 0)) || (!FirstTimestep && (_step !=0)),
644 "FormatParser< pdb >::readAtomDataLine() - additionalAtomData present though atom is newly parsed.");
645 if (FirstTimestep) {
646 LOG(3,"INFO: Parsing new atom "+toString(*newAtom)+" "+toString(newAtom->getId())+".");
647 } else {
648 LOG(3,"INFO: Parsing present atom "+toString(*newAtom)+".");
649 }
650 PdbAtomInfoContainer &atomInfo = getadditionalAtomData(newAtom);
651 LOG(4,"INFO: Information in container is "+toString(atomInfo)+".");
652
653 string word;
654 ConvertTo<size_t> toSize_t;
655
656 // check whether serial exists, if so, assign next available
657
658// LOG(2, "Split line:"
659// << line.substr(6,5) << "|"
660// << line.substr(12,4) << "|"
661// << line.substr(16,1) << "|"
662// << line.substr(17,3) << "|"
663// << line.substr(21,1) << "|"
664// << line.substr(22,4) << "|"
665// << line.substr(26,1) << "|"
666// << line.substr(30,8) << "|"
667// << line.substr(38,8) << "|"
668// << line.substr(46,8) << "|"
669// << line.substr(54,6) << "|"
670// << line.substr(60,6) << "|"
671// << line.substr(76,2) << "|"
672// << line.substr(78,2));
673
674 if (FirstTimestep) {
675 // first time step
676 // then fill info container
677 readPdbAtomInfoContainer(atomInfo, line);
678 // associate local with global id
679 associateLocaltoGlobalId(toSize_t(atomInfo.get<std::string>(PdbKey::serial)), newAtom->getId());
680 // set position
681 Vector tempVector;
682 LOG(4,"INFO: Parsing position from ("
683 +line.substr(30,8)+","
684 +line.substr(38,8)+","
685 +line.substr(46,8)+").");
686 PdbAtomInfoContainer::ScanKey(tempVector[0], line.substr(30,8));
687 PdbAtomInfoContainer::ScanKey(tempVector[1], line.substr(38,8));
688 PdbAtomInfoContainer::ScanKey(tempVector[2], line.substr(46,8));
689 newAtom->setPosition(tempVector);
690 // set element
691 std::string value = atomInfo.get<std::string>(PdbKey::element);
692 // make second character lower case if not
693 if ((value[1] >= 'A') && (value[1] <= 'Z'))
694 value[1] = (value[1] - 'A') + 'a';
695 const element *elem = World::getInstance().getPeriode()
696 ->FindElement(value);
697 ASSERT(elem != NULL,
698 "FormatParser< pdb >::readAtomDataLine() - element "+atomInfo.get<std::string>(PdbKey::element)+" is unknown!");
699 newAtom->setType(elem);
700
701 if (newmol != NULL)
702 newmol->AddAtom(newAtom);
703 } else {
704 // not first time step
705 // then parse into different container
706 PdbAtomInfoContainer consistencyInfo;
707 readPdbAtomInfoContainer(consistencyInfo, line);
708 // then check additional info for consistency
709 ASSERT(atomInfo.get<std::string>(PdbKey::token) == consistencyInfo.get<std::string>(PdbKey::token),
710 "FormatParser< pdb >::readAtomDataLine() - difference in token on multiple time step for atom with id "
711 +atomInfo.get<std::string>(PdbKey::serial)+"!");
712 ASSERT(atomInfo.get<std::string>(PdbKey::name) == consistencyInfo.get<std::string>(PdbKey::name),
713 "FormatParser< pdb >::readAtomDataLine() - difference in name on multiple time step for atom with id "
714 +atomInfo.get<std::string>(PdbKey::serial)+":"
715 +atomInfo.get<std::string>(PdbKey::name)+"!="
716 +consistencyInfo.get<std::string>(PdbKey::name)+".");
717 ASSERT(atomInfo.get<std::string>(PdbKey::altLoc) == consistencyInfo.get<std::string>(PdbKey::altLoc),
718 "FormatParser< pdb >::readAtomDataLine() - difference in altLoc on multiple time step for atom with id "
719 +atomInfo.get<std::string>(PdbKey::serial)+"!");
720 ASSERT(atomInfo.get<std::string>(PdbKey::resName) == consistencyInfo.get<std::string>(PdbKey::resName),
721 "FormatParser< pdb >::readAtomDataLine() - difference in resName on multiple time step for atom with id "
722 +atomInfo.get<std::string>(PdbKey::serial)+"!");
723 ASSERT(atomInfo.get<std::string>(PdbKey::chainID) == consistencyInfo.get<std::string>(PdbKey::chainID),
724 "FormatParser< pdb >::readAtomDataLine() - difference in chainID on multiple time step for atom with id "
725 +atomInfo.get<std::string>(PdbKey::serial)+"!");
726 ASSERT(atomInfo.get<std::string>(PdbKey::resSeq) == consistencyInfo.get<std::string>(PdbKey::resSeq),
727 "FormatParser< pdb >::readAtomDataLine() - difference in resSeq on multiple time step for atom with id "
728 +atomInfo.get<std::string>(PdbKey::serial)+"!");
729 ASSERT(atomInfo.get<std::string>(PdbKey::iCode) == consistencyInfo.get<std::string>(PdbKey::iCode),
730 "FormatParser< pdb >::readAtomDataLine() - difference in iCode on multiple time step for atom with id "
731 +atomInfo.get<std::string>(PdbKey::serial)+"!");
732 ASSERT(atomInfo.get<std::string>(PdbKey::occupancy) == consistencyInfo.get<std::string>(PdbKey::occupancy),
733 "FormatParser< pdb >::readAtomDataLine() - difference in occupancy on multiple time step for atom with id "
734 +atomInfo.get<std::string>(PdbKey::serial)+"!");
735 ASSERT(atomInfo.get<std::string>(PdbKey::tempFactor) == consistencyInfo.get<std::string>(PdbKey::tempFactor),
736 "FormatParser< pdb >::readAtomDataLine() - difference in tempFactor on multiple time step for atom with id "
737 +atomInfo.get<std::string>(PdbKey::serial)+"!");
738 ASSERT(atomInfo.get<std::string>(PdbKey::charge) == consistencyInfo.get<std::string>(PdbKey::charge),
739 "FormatParser< pdb >::readAtomDataLine() - difference in charge on multiple time step for atom with id "
740 +atomInfo.get<std::string>(PdbKey::serial)+"!");
741 ASSERT(atomInfo.get<std::string>(PdbKey::element) == consistencyInfo.get<std::string>(PdbKey::element),
742 "FormatParser< pdb >::readAtomDataLine() - difference in element on multiple time step for atom with id "
743 +atomInfo.get<std::string>(PdbKey::serial)+"!");
744 // and parse in trajectory
745 Vector tempVector;
746 LOG(4,"INFO: Parsing trajectory position from ("
747 +line.substr(30,8)+","
748 +line.substr(38,8)+","
749 +line.substr(46,8)+").");
750 PdbAtomInfoContainer::ScanKey(tempVector[0], line.substr(30,8));
751 PdbAtomInfoContainer::ScanKey(tempVector[1], line.substr(38,8));
752 PdbAtomInfoContainer::ScanKey(tempVector[2], line.substr(46,8));
753 LOG(4,"INFO: Adding trajectory point to time step "+toString(_step)+".");
754 // and set position at new time step
755 newAtom->setPositionAtStep(_step, tempVector);
756 }
757
758
759// printAtomInfo(newAtom);
760}
761
762/** Prints all PDB-specific information known about an atom.
763 *
764 */
765void FormatParser< pdb >::printAtomInfo(const atom * const newAtom) const
766{
767 const PdbAtomInfoContainer &atomInfo = additionalAtomData.at(newAtom->getId()); // operator[] const does not exist
768
769 LOG(1, "We know about atom " << newAtom->getId() << ":");
770 LOG(1, "\ttoken is " << atomInfo.get<std::string>(PdbKey::token));
771 LOG(1, "\tserial is " << atomInfo.get<int>(PdbKey::serial));
772 LOG(1, "\tname is " << atomInfo.get<std::string>(PdbKey::name));
773 LOG(1, "\taltLoc is " << atomInfo.get<std::string>(PdbKey::altLoc));
774 LOG(1, "\tresName is " << atomInfo.get<std::string>(PdbKey::resName));
775 LOG(1, "\tchainID is " << atomInfo.get<std::string>(PdbKey::chainID));
776 LOG(1, "\tresSeq is " << atomInfo.get<int>(PdbKey::resSeq));
777 LOG(1, "\tiCode is " << atomInfo.get<std::string>(PdbKey::iCode));
778 LOG(1, "\tX is " << atomInfo.get<double>(PdbKey::X));
779 LOG(1, "\tY is " << atomInfo.get<double>(PdbKey::Y));
780 LOG(1, "\tZ is " << atomInfo.get<double>(PdbKey::Z));
781 LOG(1, "\toccupancy is " << atomInfo.get<double>(PdbKey::occupancy));
782 LOG(1, "\ttempFactor is " << atomInfo.get<double>(PdbKey::tempFactor));
783 LOG(1, "\telement is '" << *(newAtom->getType()) << "'");
784 LOG(1, "\tcharge is " << atomInfo.get<int>(PdbKey::charge));
785}
786
787/**
788 * Reads neighbor information for one atom from the input.
789 *
790 * \param _step time step to use
791 * \param line to parse as an atom
792 */
793void FormatParser< pdb >::readNeighbors(const unsigned int _step, std::string &line)
794{
795 const size_t length = line.length();
796 std::list<size_t> ListOfNeighbors;
797 ConvertTo<size_t> toSize_t;
798
799 // obtain neighbours
800 // show split line for debugging
801 string output;
802 ASSERT(length >=16,
803 "FormatParser< pdb >::readNeighbors() - CONECT entry has not enough entries: "+line+"!");
804// output = "Split line:|";
805// output += line.substr(6,5) + "|";
806 const size_t id = toSize_t(line.substr(6,5));
807 for (size_t index = 11; index <= 26; index+=5) {
808 if (index+5 <= length) {
809 output += line.substr(index,5) + "|";
810 // search for digits
811 int otherid = -1;
812 PdbAtomInfoContainer::ScanKey(otherid, line.substr(index,5));
813 if (otherid > 0)
814 ListOfNeighbors.push_back(otherid);
815 else
816 ELOG(3, "FormatParser< pdb >::readNeighbors() - discarding CONECT entry with id 0.");
817 } else {
818 break;
819 }
820 }
821 LOG(4, output);
822
823 // add neighbours
824 atom *_atom = World::getInstance().getAtom(AtomById(getGlobalId(id)));
825 LOG(2, "STATUS: Atom " << _atom->getId() << " gets " << ListOfNeighbors.size() << " more neighbours.");
826 for (std::list<size_t>::const_iterator iter = ListOfNeighbors.begin();
827 iter != ListOfNeighbors.end();
828 ++iter) {
829 atom * const _Otheratom = World::getInstance().getAtom(AtomById(getGlobalId(*iter)));
830 LOG(3, "INFO: Adding Bond (" << *_atom << "," << *_Otheratom << ")");
831 _atom->addBond(_step, _Otheratom);
832 }
833}
834
835bool FormatParser< pdb >::operator==(const FormatParser< pdb >& b) const
836{
837 bool status = true;
838 World::AtomComposite atoms = World::getInstance().getAllAtoms();
839 for (World::AtomComposite::const_iterator iter = atoms.begin(); iter != atoms.end(); ++iter) {
840 if ((additionalAtomData.find((*iter)->getId()) != additionalAtomData.end())
841 && (b.additionalAtomData.find((*iter)->getId()) != b.additionalAtomData.end())) {
842 const PdbAtomInfoContainer &atomInfo = additionalAtomData.at((*iter)->getId());
843 const PdbAtomInfoContainer &OtheratomInfo = b.additionalAtomData.at((*iter)->getId());
844
845 status = status && (atomInfo.get<std::string>(PdbKey::serial) == OtheratomInfo.get<std::string>(PdbKey::serial));
846 if (!status) ELOG(1, "Mismatch in serials!");
847 status = status && (atomInfo.get<std::string>(PdbKey::name) == OtheratomInfo.get<std::string>(PdbKey::name));
848 if (!status) ELOG(1, "Mismatch in names!");
849 status = status && (atomInfo.get<std::string>(PdbKey::altLoc) == OtheratomInfo.get<std::string>(PdbKey::altLoc));
850 if (!status) ELOG(1, "Mismatch in altLocs!");
851 status = status && (atomInfo.get<std::string>(PdbKey::resName) == OtheratomInfo.get<std::string>(PdbKey::resName));
852 if (!status) ELOG(1, "Mismatch in resNames!");
853 status = status && (atomInfo.get<std::string>(PdbKey::chainID) == OtheratomInfo.get<std::string>(PdbKey::chainID));
854 if (!status) ELOG(1, "Mismatch in chainIDs!");
855 status = status && (atomInfo.get<std::string>(PdbKey::resSeq) == OtheratomInfo.get<std::string>(PdbKey::resSeq));
856 if (!status) ELOG(1, "Mismatch in resSeqs!");
857 status = status && (atomInfo.get<std::string>(PdbKey::iCode) == OtheratomInfo.get<std::string>(PdbKey::iCode));
858 if (!status) ELOG(1, "Mismatch in iCodes!");
859 status = status && (atomInfo.get<std::string>(PdbKey::occupancy) == OtheratomInfo.get<std::string>(PdbKey::occupancy));
860 if (!status) ELOG(1, "Mismatch in occupancies!");
861 status = status && (atomInfo.get<std::string>(PdbKey::tempFactor) == OtheratomInfo.get<std::string>(PdbKey::tempFactor));
862 if (!status) ELOG(1, "Mismatch in tempFactors!");
863 status = status && (atomInfo.get<std::string>(PdbKey::charge) == OtheratomInfo.get<std::string>(PdbKey::charge));
864 if (!status) ELOG(1, "Mismatch in charges!");
865 }
866 }
867
868 return status;
869}
870
Note: See TracBrowser for help on using the repository browser.