source: src/Parser/PdbParser.cpp@ b0a2e3

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

Removed use of PdbKey::timestep, steps are parsed sequentially.

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