source: src/Parser/PdbParser.cpp@ 50e4e5

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 50e4e5 was 42127c, checked in by Frederik Heber <heber@…>, 13 years ago

Extracted definition of MoleculeListClass and put into own header module.

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