source: src/Parser/PdbParser.cpp@ 7daf73

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 7daf73 was fac58f, checked in by Frederik Heber <heber@…>, 10 years ago

Converted FormatParser::save() to using vector of const atom ptrs.

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