source: src/Parser/PdbParser.cpp@ f01769

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

Replaced World::getAtom() wherever possible by const version.

  • some AtomSet member functions now have const atom ptr instead of atom ptr.
  • molecule can return const and non-const AtomSet.
  • added FromIdToConstAtom to allow iterate through atoms in molecule (which are stored by id, not by ptr) in const fashion.
  • in molecule::isInMolecule() is now const, ::CopyMolecule..() is non-const (because copying involves father atom who is stored non-const).
  • Property mode set to 100644
File size: 34.1 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(ostream* file, const std::vector<atom *> &AtomList)
197{
198 LOG(2, "DEBUG: Saving changes to pdb.");
199
200 // check for maximum number of time steps
201 size_t max_timesteps = 0;
202 BOOST_FOREACH(atom *_atom, World::getInstance().getAllAtoms()) {
203 LOG(4, "INFO: Atom " << _atom->getName() << " " << *dynamic_cast<AtomInfo *>(_atom) << ".");
204 if (_atom->getTrajectorySize() > max_timesteps)
205 max_timesteps = _atom->getTrajectorySize();
206 }
207 LOG(2,"INFO: Found a maximum of " << max_timesteps << " time steps to store.");
208
209 // re-distribute serials
210 resetIdAssociations();
211 // (new atoms might have been added)
212 int AtomNo = 1; // serial number starts at 1 in pdb
213 for (vector<atom *>::const_iterator atomIt = AtomList.begin(); atomIt != AtomList.end(); atomIt++) {
214 PdbAtomInfoContainer &atomInfo = getadditionalAtomData(*atomIt);
215 associateLocaltoGlobalId(AtomNo, (*atomIt)->getId());
216 atomInfo.set(PdbKey::serial, toString(AtomNo));
217 ++AtomNo;
218 }
219
220 // store all time steps (always do first step)
221 for (size_t step = 0; (step == 0) || (step < max_timesteps); ++step) {
222 {
223 // add initial remark
224 *file << "REMARK created by molecuilder on ";
225 time_t now = time((time_t *)NULL); // Get the system time and put it into 'now' as 'calender time'
226 // ctime ends in \n\0, we have to cut away the newline
227 std::string time(ctime(&now));
228 size_t pos = time.find('\n');
229 if (pos != 0)
230 *file << time.substr(0,pos);
231 else
232 *file << time;
233 *file << ", time step " << step;
234 *file << endl;
235 }
236
237 {
238 std::map<size_t,size_t> MolIdMap;
239 size_t MolNo = 1; // residue number starts at 1 in pdb
240 for (vector<atom *>::const_iterator atomIt = AtomList.begin(); atomIt != AtomList.end(); atomIt++) {
241 const molecule *mol = (*atomIt)->getMolecule();
242 if ((mol != NULL) && (MolIdMap.find(mol->getId()) == MolIdMap.end())) {
243 MolIdMap[mol->getId()] = MolNo++;
244 }
245 }
246 const size_t MaxMol = MolNo;
247
248 // have a count per element and per molecule (0 is for all homeless atoms)
249 std::vector<int> **elementNo = new std::vector<int>*[MaxMol];
250 for (size_t i = 0; i < MaxMol; ++i)
251 elementNo[i] = new std::vector<int>(MAX_ELEMENTS,1);
252 char name[MAXSTRINGSIZE];
253 std::string ResidueName;
254
255 // write ATOMs
256 for (vector<atom *>::const_iterator atomIt = AtomList.begin(); atomIt != AtomList.end(); atomIt++) {
257 PdbAtomInfoContainer &atomInfo = getadditionalAtomData(*atomIt);
258 // gather info about residue
259 const molecule *mol = (*atomIt)->getMolecule();
260 if (mol == NULL) {
261 MolNo = 0;
262 atomInfo.set(PdbKey::resSeq, "0");
263 } else {
264 ASSERT(MolIdMap.find(mol->getId()) != MolIdMap.end(),
265 "FormatParser< pdb >::save() - Mol id "+toString(mol->getId())+" not present despite we set it?!");
266 MolNo = MolIdMap[mol->getId()];
267 atomInfo.set(PdbKey::resSeq, toString(MolIdMap[mol->getId()]));
268 if (atomInfo.get<std::string>(PdbKey::resName) == "-")
269 atomInfo.set(PdbKey::resName, mol->getName().substr(0,3));
270 }
271 // get info about atom
272 const size_t Z = (*atomIt)->getType()->getAtomicNumber();
273 if (atomInfo.get<std::string>(PdbKey::name) == "-") { // if no name set, give it a new name
274 sprintf(name, "%2s%02d",(*atomIt)->getType()->getSymbol().c_str(), (*elementNo[MolNo])[Z]);
275 (*elementNo[MolNo])[Z] = ((*elementNo[MolNo])[Z]+1) % 100; // confine to two digits
276 atomInfo.set(PdbKey::name, name);
277 }
278 // set position
279 for (size_t i=0; i<NDIM;++i) {
280 stringstream position;
281 position << setprecision(7) << (*atomIt)->getPositionAtStep(step).at(i);
282 atomInfo.set(PositionEnumMap[i], position.str());
283 }
284 // change element and charge if changed
285 if (atomInfo.get<std::string>(PdbKey::element) != (*atomIt)->getType()->getSymbol()) {
286 std::string symbol = (*atomIt)->getType()->getSymbol();
287 if ((symbol[1] >= 'a') && (symbol[1] <= 'z'))
288 symbol[1] = (symbol[1] - 'a') + 'A';
289 atomInfo.set(PdbKey::element, symbol);
290 }
291
292 // finally save the line
293 saveLine(file, atomInfo);
294 }
295 for (size_t i = 0; i < MaxMol; ++i)
296 delete elementNo[i];
297 delete[] elementNo;
298
299 // write CONECTs
300 for (vector<atom *>::const_iterator atomIt = AtomList.begin(); atomIt != AtomList.end(); atomIt++) {
301 writeNeighbors(file, 4, *atomIt);
302 }
303 }
304 // END
305 *file << "END" << endl;
306 }
307
308}
309
310/** Add default info, when new atom is added to World.
311 *
312 * @param id of atom
313 */
314void FormatParser< pdb >::AtomInserted(atomId_t id)
315{
316 //LOG(3, "FormatParser< pdb >::AtomInserted() - notified of atom " << id << "'s insertion.");
317 ASSERT(!isPresentadditionalAtomData(id),
318 "FormatParser< pdb >::AtomInserted() - additionalAtomData already present for newly added atom "
319 +toString(id)+".");
320 // don't insert here as this is our check whether we are in the first time step
321 //additionalAtomData.insert( std::make_pair(id, defaultAdditionalData) );
322}
323
324/** Remove additional AtomData info, when atom has been removed from World.
325 *
326 * @param id of atom
327 */
328void FormatParser< pdb >::AtomRemoved(atomId_t id)
329{
330 //LOG(3, "FormatParser< pdb >::AtomRemoved() - notified of atom " << id << "'s removal.");
331 std::map<const atomId_t, PdbAtomInfoContainer>::iterator iter = additionalAtomData.find(id);
332 // as we do not insert AtomData on AtomInserted, we cannot be assured of its presence
333// ASSERT(iter != additionalAtomData.end(),
334// "FormatParser< pdb >::AtomRemoved() - additionalAtomData is not present for atom "
335// +toString(id)+" to remove.");
336 if (iter != additionalAtomData.end()) {
337 additionalAtomData.erase(iter);
338 }
339}
340
341
342/** Checks whether there is an entry for the given atom's \a _id.
343 *
344 * @param _id atom's id we wish to check on
345 * @return true - entry present, false - only for atom's father or no entry
346 */
347bool FormatParser< pdb >::isPresentadditionalAtomData(const atomId_t _id) const
348{
349 std::map<const atomId_t, PdbAtomInfoContainer>::const_iterator iter = additionalAtomData.find(_id);
350 return (iter != additionalAtomData.end());
351}
352
353
354/** Either returns reference to present entry or creates new with default values.
355 *
356 * @param _atom atom whose entry we desire
357 * @return
358 */
359PdbAtomInfoContainer& FormatParser< pdb >::getadditionalAtomData(atom *_atom)
360{
361 if (additionalAtomData.find(_atom->getId()) != additionalAtomData.end()) {
362 } else if (additionalAtomData.find(_atom->getFather()->getId()) != additionalAtomData.end()) {
363 // use info from direct father
364 additionalAtomData[_atom->getId()] = additionalAtomData[_atom->getFather()->getId()];
365 } else if (additionalAtomData.find(_atom->GetTrueFather()->getId()) != additionalAtomData.end()) {
366 // use info from topmost father
367 additionalAtomData[_atom->getId()] = additionalAtomData[_atom->GetTrueFather()->getId()];
368 } else {
369 // create new entry use default values if nothing else is known
370 additionalAtomData[_atom->getId()] = defaultAdditionalData;
371 }
372 return additionalAtomData[_atom->getId()];
373}
374
375/** Tiny helper function to print a float with a most 8 digits.
376 *
377 * A few examples best give the picture:
378 * 1234.678
379 * 1.234
380 * 0.001
381 * 0.100
382 * 1234567.
383 * 123456.7
384 * -1234.56
385 *
386 * \param value
387 * \return string representation
388 */
389const std::string FormatParser< pdb >::printCoordinate(
390 const double value)
391{
392 size_t meaningful_bits=7; // one for decimal dot
393 if (value < 0) //one for the minus sign
394 --meaningful_bits;
395 // count digits before dot (without minus and round towards zero!)
396 int full = floor(fabs(value));
397 size_t bits_before_dot = 1;
398 {
399 int tmp = full;
400 for (;bits_before_dot < meaningful_bits;++bits_before_dot) {
401 // even if value is 0...somethingish, we still must start at one digit
402 tmp = tmp/10;
403 if (tmp == 0)
404 break;
405 }
406 }
407 // this fixes bits available after dot
408 const size_t bits_after_dot = std::min((int)meaningful_bits - (int)bits_before_dot, 3);
409 stringstream position;
410 if (bits_after_dot > 0) {
411 if (value < 0)
412 position << "-";
413 // truncate 999.9 to 999 and not to 1000! (hence, extra check!)
414 int remainder = round((abs(value)-full)*pow(10,bits_after_dot));
415 if (remainder >= pow(10,bits_after_dot)) {
416 remainder = 0;
417 ++full;
418 }
419 position << full << "." << setfill('0') << setw(bits_after_dot) << remainder;
420 if (bits_after_dot == 2)
421 ELOG(2, "PdbParser is writing coordinates with just a two decimal places.");
422 if (bits_after_dot == 1)
423 ELOG(1, "PdbParser is writing coordinates with just a single decimal places.");
424 } else {
425 ELOG(0, "PdbParser is writing coordinates without any decimal places.");
426 position << full << ".";
427 }
428 return position.str();
429}
430
431/**
432 * Writes one line of PDB-formatted data to the provided stream.
433 *
434 * \param stream where to write the line to
435 * \param *currentAtom the atom of which information should be written
436 * \param AtomNo serial number of atom
437 * \param *name name of atom, i.e. H01
438 * \param ResidueName Name of molecule
439 * \param ResidueNo number of residue
440 */
441void FormatParser< pdb >::saveLine(
442 ostream* file,
443 const PdbAtomInfoContainer &atomInfo)
444{
445 *file << setfill(' ') << left << setw(6)
446 << atomInfo.get<std::string>(PdbKey::token);
447 *file << setfill(' ') << right << setw(5)
448 << (atomInfo.get<int>(PdbKey::serial) % 100000); /* atom serial number */
449 *file << " "; /* char 12 is empty */
450 *file << setfill(' ') << left << setw(4)
451 << atomInfo.get<std::string>(PdbKey::name); /* atom name */
452 *file << setfill(' ') << left << setw(1)
453 << atomInfo.get<std::string>(PdbKey::altLoc); /* alternate location/conformation */
454 *file << setfill(' ') << left << setw(3)
455 << atomInfo.get<std::string>(PdbKey::resName); /* residue name */
456 *file << " "; /* char 21 is empty */
457 *file << setfill(' ') << left << setw(1)
458 << atomInfo.get<std::string>(PdbKey::chainID); /* chain identifier */
459 *file << setfill(' ') << left << setw(4)
460 << (atomInfo.get<int>(PdbKey::resSeq) % 10000); /* residue sequence number */
461 *file << setfill(' ') << left << setw(1)
462 << atomInfo.get<std::string>(PdbKey::iCode); /* iCode */
463 *file << " "; /* char 28-30 are empty */
464 // have the following operate on stringstreams such that format specifiers
465 // only act on these
466 for (size_t i=0;i<NDIM;++i) {
467 *file << setfill(' ') << right << setw(8)
468 << printCoordinate(atomInfo.get<double>(PositionEnumMap[i]));
469 }
470 {
471 stringstream occupancy;
472 occupancy << fixed << setprecision(2) << showpoint
473 << atomInfo.get<double>(PdbKey::occupancy); /* occupancy */
474 *file << setfill(' ') << right << setw(6) << occupancy.str();
475 }
476 {
477 stringstream tempFactor;
478 tempFactor << fixed << setprecision(2) << showpoint
479 << atomInfo.get<double>(PdbKey::tempFactor); /* temperature factor */
480 *file << setfill(' ') << right << setw(6) << tempFactor.str();
481 }
482 *file << " "; /* char 68-76 are empty */
483 *file << setfill(' ') << right << setw(2) << atomInfo.get<std::string>(PdbKey::element); /* element */
484 *file << setfill(' ') << right << setw(2) << atomInfo.get<int>(PdbKey::charge); /* charge */
485
486 *file << endl;
487}
488
489/**
490 * Writes the neighbor information of one atom to the provided stream.
491 *
492 * Note that ListOfBonds of WorldTime::CurrentTime is used.
493 *
494 * Also, we fill up the CONECT line to extend over 80 chars.
495 *
496 * \param *file where to write neighbor information to
497 * \param MaxnumberOfNeighbors of neighbors
498 * \param *currentAtom to the atom of which to take the neighbor information
499 */
500void FormatParser< pdb >::writeNeighbors(ostream* file, int MaxnumberOfNeighbors, atom* currentAtom) {
501 int MaxNo = MaxnumberOfNeighbors;
502 int charsleft = 80;
503 const BondList & ListOfBonds = currentAtom->getListOfBonds();
504 if (!ListOfBonds.empty()) {
505 for(BondList::const_iterator currentBond = ListOfBonds.begin(); currentBond != ListOfBonds.end(); ++currentBond) {
506 if (MaxNo >= MaxnumberOfNeighbors) {
507 *file << "CONECT";
508 *file << setw(5) << getLocalId(currentAtom->getId());
509 charsleft = 80-6-5;
510 MaxNo = 0;
511 }
512 *file << setw(5) << getLocalId((*currentBond)->GetOtherAtom(currentAtom)->getId());
513 charsleft -= 5;
514 MaxNo++;
515 if (MaxNo == MaxnumberOfNeighbors) {
516 for (;charsleft > 0; charsleft--)
517 *file << ' ';
518 *file << "\n";
519 }
520 }
521 if (MaxNo != MaxnumberOfNeighbors) {
522 for (;charsleft > 0; charsleft--)
523 *file << ' ';
524 *file << "\n";
525 }
526 }
527}
528
529/** Either returns present atom with given id or a newly created one.
530 *
531 * @param id_string
532 * @return
533 */
534atom* FormatParser< pdb >::getAtomToParse(std::string id_string)
535{
536 // get the local ID
537 ConvertTo<int> toInt;
538 const unsigned int AtomID_local = toInt(id_string);
539 LOG(4, "INFO: Local id is "+toString(AtomID_local)+".");
540 // get the atomic ID if present
541 atom* newAtom = NULL;
542 if (getGlobalId(AtomID_local) != -1) {
543 const unsigned int AtomID_global = getGlobalId(AtomID_local);
544 LOG(4, "INFO: Global id present as " << AtomID_global << ".");
545 // check if atom exists
546 newAtom = World::getInstance().getAtom(AtomById(AtomID_global));
547 LOG(5, "INFO: Listing all present atoms with id.");
548 BOOST_FOREACH(atom *_atom, World::getInstance().getAllAtoms())
549 LOG(5, "INFO: " << *_atom << " with id " << _atom->getId());
550 }
551 // if not exists, create
552 if (newAtom == NULL) {
553 newAtom = World::getInstance().createAtom();
554 //const unsigned int AtomID_global = newAtom->getId();
555 LOG(4, "INFO: No association to global id present, creating atom.");
556 } else {
557 LOG(4, "INFO: Existing atom found: " << *newAtom << ".");
558 }
559 return newAtom;
560}
561
562/** read a line starting with key ATOM.
563 *
564 * We check for line's length and parse only up to this value.
565 *
566 * @param atomInfo container to put information in
567 * @param line line containing key ATOM
568 */
569void FormatParser< pdb >::readPdbAtomInfoContainer(PdbAtomInfoContainer &atomInfo, std::string &line) const
570{
571 const size_t length = line.length();
572 if (length < 80)
573 ELOG(2, "FormatParser< pdb >::readPdbAtomInfoContainer() - pdb is mal-formed, containing less than 80 chars!");
574 if (length >= 6) {
575 LOG(4,"INFO: Parsing token from "+line.substr(0,6)+".");
576 atomInfo.set(PdbKey::token, line.substr(0,6));
577 }
578 if (length >= 11) {
579 LOG(4,"INFO: Parsing serial from "+line.substr(6,5)+".");
580 atomInfo.set(PdbKey::serial, line.substr(6,5));
581 ASSERT(atomInfo.get<int>(PdbKey::serial) != 0,
582 "FormatParser< pdb >::readPdbAtomInfoContainer() - serial 0 is invalid (filler id for conect entries).");
583 }
584
585 if (length >= 16) {
586 LOG(4,"INFO: Parsing name from "+line.substr(12,4)+".");
587 atomInfo.set(PdbKey::name, line.substr(12,4));
588 }
589 if (length >= 17) {
590 LOG(4,"INFO: Parsing altLoc from "+line.substr(16,1)+".");
591 atomInfo.set(PdbKey::altLoc, line.substr(16,1));
592 }
593 if (length >= 20) {
594 LOG(4,"INFO: Parsing resName from "+line.substr(17,3)+".");
595 atomInfo.set(PdbKey::resName, line.substr(17,3));
596 }
597 if (length >= 22) {
598 LOG(4,"INFO: Parsing chainID from "+line.substr(21,1)+".");
599 atomInfo.set(PdbKey::chainID, line.substr(21,1));
600 }
601 if (length >= 26) {
602 LOG(4,"INFO: Parsing resSeq from "+line.substr(22,4)+".");
603 atomInfo.set(PdbKey::resSeq, line.substr(22,4));
604 }
605 if (length >= 27) {
606 LOG(4,"INFO: Parsing iCode from "+line.substr(26,1)+".");
607 atomInfo.set(PdbKey::iCode, line.substr(26,1));
608 }
609
610 if (length >= 60) {
611 LOG(4,"INFO: Parsing occupancy from "+line.substr(54,6)+".");
612 atomInfo.set(PdbKey::occupancy, line.substr(54,6));
613 }
614 if (length >= 66) {
615 LOG(4,"INFO: Parsing tempFactor from "+line.substr(60,6)+".");
616 atomInfo.set(PdbKey::tempFactor, line.substr(60,6));
617 }
618 if (length >= 80) {
619 LOG(4,"INFO: Parsing charge from "+line.substr(78,2)+".");
620 atomInfo.set(PdbKey::charge, line.substr(78,2));
621 }
622 if (length >= 78) {
623 LOG(4,"INFO: Parsing element from "+line.substr(76,2)+".");
624 atomInfo.set(PdbKey::element, line.substr(76,2));
625 } else {
626 LOG(4,"INFO: Trying to parse alternative element from name "+line.substr(12,4)+".");
627 atomInfo.set(PdbKey::element, line.substr(12,4));
628 }
629}
630
631/** Parse an ATOM line from a PDB file.
632 *
633 * Reads one data line of a pdstatus file and interprets it according to the
634 * specifications of the PDB 3.2 format: http://www.wwpdb.org/docs.html
635 *
636 * A new atom is created and filled with available information, non-
637 * standard information is placed in additionalAtomData at the atom's id.
638 *
639 * \param _step time step to use
640 * \param line to parse as an atom
641 * \param newmol molecule to add parsed atoms to
642 */
643void FormatParser< pdb >::readAtomDataLine(const unsigned int _step, std::string &line, molecule *newmol = NULL) {
644 vector<string>::iterator it;
645
646 atom* newAtom = getAtomToParse(line.substr(6,5));
647 LOG(3,"INFO: Parsing END entry or empty line.");
648 bool FirstTimestep = isPresentadditionalAtomData(newAtom->getId()) ? false : true;
649 ASSERT((FirstTimestep && (_step == 0)) || (!FirstTimestep && (_step !=0)),
650 "FormatParser< pdb >::readAtomDataLine() - additionalAtomData present though atom is newly parsed.");
651 if (FirstTimestep) {
652 LOG(3,"INFO: Parsing new atom "+toString(*newAtom)+" "+toString(newAtom->getId())+".");
653 } else {
654 LOG(3,"INFO: Parsing present atom "+toString(*newAtom)+".");
655 }
656 PdbAtomInfoContainer &atomInfo = getadditionalAtomData(newAtom);
657 LOG(4,"INFO: Information in container is "+toString(atomInfo)+".");
658
659 string word;
660 ConvertTo<size_t> toSize_t;
661
662 // check whether serial exists, if so, assign next available
663
664// LOG(2, "Split line:"
665// << line.substr(6,5) << "|"
666// << line.substr(12,4) << "|"
667// << line.substr(16,1) << "|"
668// << line.substr(17,3) << "|"
669// << line.substr(21,1) << "|"
670// << line.substr(22,4) << "|"
671// << line.substr(26,1) << "|"
672// << line.substr(30,8) << "|"
673// << line.substr(38,8) << "|"
674// << line.substr(46,8) << "|"
675// << line.substr(54,6) << "|"
676// << line.substr(60,6) << "|"
677// << line.substr(76,2) << "|"
678// << line.substr(78,2));
679
680 if (FirstTimestep) {
681 // first time step
682 // then fill info container
683 readPdbAtomInfoContainer(atomInfo, line);
684 // associate local with global id
685 associateLocaltoGlobalId(toSize_t(atomInfo.get<std::string>(PdbKey::serial)), newAtom->getId());
686 // set position
687 Vector tempVector;
688 LOG(4,"INFO: Parsing position from ("
689 +line.substr(30,8)+","
690 +line.substr(38,8)+","
691 +line.substr(46,8)+").");
692 PdbAtomInfoContainer::ScanKey(tempVector[0], line.substr(30,8));
693 PdbAtomInfoContainer::ScanKey(tempVector[1], line.substr(38,8));
694 PdbAtomInfoContainer::ScanKey(tempVector[2], line.substr(46,8));
695 newAtom->setPosition(tempVector);
696 // set element
697 std::string value = atomInfo.get<std::string>(PdbKey::element);
698 // make second character lower case if not
699 if ((value[1] >= 'A') && (value[1] <= 'Z'))
700 value[1] = (value[1] - 'A') + 'a';
701 const element *elem = World::getInstance().getPeriode()
702 ->FindElement(value);
703 ASSERT(elem != NULL,
704 "FormatParser< pdb >::readAtomDataLine() - element "+atomInfo.get<std::string>(PdbKey::element)+" is unknown!");
705 newAtom->setType(elem);
706
707 if (newmol != NULL)
708 newmol->AddAtom(newAtom);
709 } else {
710 // not first time step
711 // then parse into different container
712 PdbAtomInfoContainer consistencyInfo;
713 readPdbAtomInfoContainer(consistencyInfo, line);
714 // then check additional info for consistency
715 ASSERT(atomInfo.get<std::string>(PdbKey::token) == consistencyInfo.get<std::string>(PdbKey::token),
716 "FormatParser< pdb >::readAtomDataLine() - difference in token on multiple time step for atom with id "
717 +atomInfo.get<std::string>(PdbKey::serial)+"!");
718 ASSERT(atomInfo.get<std::string>(PdbKey::name) == consistencyInfo.get<std::string>(PdbKey::name),
719 "FormatParser< pdb >::readAtomDataLine() - difference in name on multiple time step for atom with id "
720 +atomInfo.get<std::string>(PdbKey::serial)+":"
721 +atomInfo.get<std::string>(PdbKey::name)+"!="
722 +consistencyInfo.get<std::string>(PdbKey::name)+".");
723 ASSERT(atomInfo.get<std::string>(PdbKey::altLoc) == consistencyInfo.get<std::string>(PdbKey::altLoc),
724 "FormatParser< pdb >::readAtomDataLine() - difference in altLoc on multiple time step for atom with id "
725 +atomInfo.get<std::string>(PdbKey::serial)+"!");
726 ASSERT(atomInfo.get<std::string>(PdbKey::resName) == consistencyInfo.get<std::string>(PdbKey::resName),
727 "FormatParser< pdb >::readAtomDataLine() - difference in resName on multiple time step for atom with id "
728 +atomInfo.get<std::string>(PdbKey::serial)+"!");
729 ASSERT(atomInfo.get<std::string>(PdbKey::chainID) == consistencyInfo.get<std::string>(PdbKey::chainID),
730 "FormatParser< pdb >::readAtomDataLine() - difference in chainID on multiple time step for atom with id "
731 +atomInfo.get<std::string>(PdbKey::serial)+"!");
732 ASSERT(atomInfo.get<std::string>(PdbKey::resSeq) == consistencyInfo.get<std::string>(PdbKey::resSeq),
733 "FormatParser< pdb >::readAtomDataLine() - difference in resSeq on multiple time step for atom with id "
734 +atomInfo.get<std::string>(PdbKey::serial)+"!");
735 ASSERT(atomInfo.get<std::string>(PdbKey::iCode) == consistencyInfo.get<std::string>(PdbKey::iCode),
736 "FormatParser< pdb >::readAtomDataLine() - difference in iCode on multiple time step for atom with id "
737 +atomInfo.get<std::string>(PdbKey::serial)+"!");
738 ASSERT(atomInfo.get<std::string>(PdbKey::occupancy) == consistencyInfo.get<std::string>(PdbKey::occupancy),
739 "FormatParser< pdb >::readAtomDataLine() - difference in occupancy on multiple time step for atom with id "
740 +atomInfo.get<std::string>(PdbKey::serial)+"!");
741 ASSERT(atomInfo.get<std::string>(PdbKey::tempFactor) == consistencyInfo.get<std::string>(PdbKey::tempFactor),
742 "FormatParser< pdb >::readAtomDataLine() - difference in tempFactor on multiple time step for atom with id "
743 +atomInfo.get<std::string>(PdbKey::serial)+"!");
744 ASSERT(atomInfo.get<std::string>(PdbKey::charge) == consistencyInfo.get<std::string>(PdbKey::charge),
745 "FormatParser< pdb >::readAtomDataLine() - difference in charge on multiple time step for atom with id "
746 +atomInfo.get<std::string>(PdbKey::serial)+"!");
747 ASSERT(atomInfo.get<std::string>(PdbKey::element) == consistencyInfo.get<std::string>(PdbKey::element),
748 "FormatParser< pdb >::readAtomDataLine() - difference in element on multiple time step for atom with id "
749 +atomInfo.get<std::string>(PdbKey::serial)+"!");
750 // and parse in trajectory
751 Vector tempVector;
752 LOG(4,"INFO: Parsing trajectory position from ("
753 +line.substr(30,8)+","
754 +line.substr(38,8)+","
755 +line.substr(46,8)+").");
756 PdbAtomInfoContainer::ScanKey(tempVector[0], line.substr(30,8));
757 PdbAtomInfoContainer::ScanKey(tempVector[1], line.substr(38,8));
758 PdbAtomInfoContainer::ScanKey(tempVector[2], line.substr(46,8));
759 LOG(4,"INFO: Adding trajectory point to time step "+toString(_step)+".");
760 // and set position at new time step
761 newAtom->setPositionAtStep(_step, tempVector);
762 }
763
764
765// printAtomInfo(newAtom);
766}
767
768/** Prints all PDB-specific information known about an atom.
769 *
770 */
771void FormatParser< pdb >::printAtomInfo(const atom * const newAtom) const
772{
773 const PdbAtomInfoContainer &atomInfo = additionalAtomData.at(newAtom->getId()); // operator[] const does not exist
774
775 LOG(1, "We know about atom " << newAtom->getId() << ":");
776 LOG(1, "\ttoken is " << atomInfo.get<std::string>(PdbKey::token));
777 LOG(1, "\tserial is " << atomInfo.get<int>(PdbKey::serial));
778 LOG(1, "\tname is " << atomInfo.get<std::string>(PdbKey::name));
779 LOG(1, "\taltLoc is " << atomInfo.get<std::string>(PdbKey::altLoc));
780 LOG(1, "\tresName is " << atomInfo.get<std::string>(PdbKey::resName));
781 LOG(1, "\tchainID is " << atomInfo.get<std::string>(PdbKey::chainID));
782 LOG(1, "\tresSeq is " << atomInfo.get<int>(PdbKey::resSeq));
783 LOG(1, "\tiCode is " << atomInfo.get<std::string>(PdbKey::iCode));
784 LOG(1, "\tX is " << atomInfo.get<double>(PdbKey::X));
785 LOG(1, "\tY is " << atomInfo.get<double>(PdbKey::Y));
786 LOG(1, "\tZ is " << atomInfo.get<double>(PdbKey::Z));
787 LOG(1, "\toccupancy is " << atomInfo.get<double>(PdbKey::occupancy));
788 LOG(1, "\ttempFactor is " << atomInfo.get<double>(PdbKey::tempFactor));
789 LOG(1, "\telement is '" << *(newAtom->getType()) << "'");
790 LOG(1, "\tcharge is " << atomInfo.get<int>(PdbKey::charge));
791}
792
793/**
794 * Reads neighbor information for one atom from the input.
795 *
796 * \param _step time step to use
797 * \param line to parse as an atom
798 */
799void FormatParser< pdb >::readNeighbors(const unsigned int _step, std::string &line)
800{
801 const size_t length = line.length();
802 std::list<size_t> ListOfNeighbors;
803 ConvertTo<size_t> toSize_t;
804
805 // obtain neighbours
806 // show split line for debugging
807 string output;
808 ASSERT(length >=16,
809 "FormatParser< pdb >::readNeighbors() - CONECT entry has not enough entries: "+line+"!");
810// output = "Split line:|";
811// output += line.substr(6,5) + "|";
812 const size_t id = toSize_t(line.substr(6,5));
813 for (size_t index = 11; index <= 26; index+=5) {
814 if (index+5 <= length) {
815 output += line.substr(index,5) + "|";
816 // search for digits
817 int otherid = -1;
818 PdbAtomInfoContainer::ScanKey(otherid, line.substr(index,5));
819 if (otherid > 0)
820 ListOfNeighbors.push_back(otherid);
821 else
822 ELOG(3, "FormatParser< pdb >::readNeighbors() - discarding CONECT entry with id 0.");
823 } else {
824 break;
825 }
826 }
827 LOG(4, output);
828
829 // add neighbours
830 atom * const _atom = World::getInstance().getAtom(AtomById(getGlobalId(id)));
831 LOG(2, "STATUS: Atom " << _atom->getId() << " gets " << ListOfNeighbors.size() << " more neighbours.");
832 for (std::list<size_t>::const_iterator iter = ListOfNeighbors.begin();
833 iter != ListOfNeighbors.end();
834 ++iter) {
835 atom * const _Otheratom = World::getInstance().getAtom(AtomById(getGlobalId(*iter)));
836 LOG(3, "INFO: Adding Bond (" << *_atom << "," << *_Otheratom << ")");
837 _atom->addBond(_step, _Otheratom);
838 }
839}
840
841bool FormatParser< pdb >::operator==(const FormatParser< pdb >& b) const
842{
843 bool status = true;
844 World::AtomComposite atoms = World::getInstance().getAllAtoms();
845 for (World::AtomComposite::const_iterator iter = atoms.begin(); iter != atoms.end(); ++iter) {
846 if ((additionalAtomData.find((*iter)->getId()) != additionalAtomData.end())
847 && (b.additionalAtomData.find((*iter)->getId()) != b.additionalAtomData.end())) {
848 const PdbAtomInfoContainer &atomInfo = additionalAtomData.at((*iter)->getId());
849 const PdbAtomInfoContainer &OtheratomInfo = b.additionalAtomData.at((*iter)->getId());
850
851 status = status && (atomInfo.get<std::string>(PdbKey::serial) == OtheratomInfo.get<std::string>(PdbKey::serial));
852 if (!status) ELOG(1, "Mismatch in serials!");
853 status = status && (atomInfo.get<std::string>(PdbKey::name) == OtheratomInfo.get<std::string>(PdbKey::name));
854 if (!status) ELOG(1, "Mismatch in names!");
855 status = status && (atomInfo.get<std::string>(PdbKey::altLoc) == OtheratomInfo.get<std::string>(PdbKey::altLoc));
856 if (!status) ELOG(1, "Mismatch in altLocs!");
857 status = status && (atomInfo.get<std::string>(PdbKey::resName) == OtheratomInfo.get<std::string>(PdbKey::resName));
858 if (!status) ELOG(1, "Mismatch in resNames!");
859 status = status && (atomInfo.get<std::string>(PdbKey::chainID) == OtheratomInfo.get<std::string>(PdbKey::chainID));
860 if (!status) ELOG(1, "Mismatch in chainIDs!");
861 status = status && (atomInfo.get<std::string>(PdbKey::resSeq) == OtheratomInfo.get<std::string>(PdbKey::resSeq));
862 if (!status) ELOG(1, "Mismatch in resSeqs!");
863 status = status && (atomInfo.get<std::string>(PdbKey::iCode) == OtheratomInfo.get<std::string>(PdbKey::iCode));
864 if (!status) ELOG(1, "Mismatch in iCodes!");
865 status = status && (atomInfo.get<std::string>(PdbKey::occupancy) == OtheratomInfo.get<std::string>(PdbKey::occupancy));
866 if (!status) ELOG(1, "Mismatch in occupancies!");
867 status = status && (atomInfo.get<std::string>(PdbKey::tempFactor) == OtheratomInfo.get<std::string>(PdbKey::tempFactor));
868 if (!status) ELOG(1, "Mismatch in tempFactors!");
869 status = status && (atomInfo.get<std::string>(PdbKey::charge) == OtheratomInfo.get<std::string>(PdbKey::charge));
870 if (!status) ELOG(1, "Mismatch in charges!");
871 }
872 }
873
874 return status;
875}
876
Note: See TracBrowser for help on using the repository browser.