source: src/Parser/TremoloParser.cpp@ d2596b

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

TremoloParser now always writes current domain as "# Box ..." into file.

  • Property mode set to 100644
File size: 23.4 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 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * TremoloParser.cpp
10 *
11 * Created on: Mar 2, 2010
12 * Author: metzler
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 "TremoloParser.hpp"
28
29#include "Atom/atom.hpp"
30#include "Bond/bond.hpp"
31#include "Box.hpp"
32#include "Descriptors/AtomIdDescriptor.hpp"
33#include "Element/element.hpp"
34#include "Element/periodentafel.hpp"
35#include "LinearAlgebra/RealSpaceMatrix.hpp"
36#include "molecule.hpp"
37#include "MoleculeListClass.hpp"
38#include "World.hpp"
39#include "WorldTime.hpp"
40
41
42#include <algorithm>
43#include <boost/tokenizer.hpp>
44#include <iostream>
45#include <iomanip>
46#include <map>
47#include <sstream>
48#include <vector>
49
50// declare specialized static variables
51const std::string FormatParserTrait<tremolo>::name = "tremolo";
52const std::string FormatParserTrait<tremolo>::suffix = "data";
53const ParserTypes FormatParserTrait<tremolo>::type = tremolo;
54
55/**
56 * Constructor.
57 */
58FormatParser< tremolo >::FormatParser() :
59 FormatParser_common(NULL)
60{
61 knownKeys["x"] = TremoloKey::x;
62 knownKeys["u"] = TremoloKey::u;
63 knownKeys["F"] = TremoloKey::F;
64 knownKeys["stress"] = TremoloKey::stress;
65 knownKeys["Id"] = TremoloKey::Id;
66 knownKeys["neighbors"] = TremoloKey::neighbors;
67 knownKeys["imprData"] = TremoloKey::imprData;
68 knownKeys["GroupMeasureTypeNo"] = TremoloKey::GroupMeasureTypeNo;
69 knownKeys["type"] = TremoloKey::type;
70 knownKeys["extType"] = TremoloKey::extType;
71 knownKeys["name"] = TremoloKey::name;
72 knownKeys["resName"] = TremoloKey::resName;
73 knownKeys["chainID"] = TremoloKey::chainID;
74 knownKeys["resSeq"] = TremoloKey::resSeq;
75 knownKeys["occupancy"] = TremoloKey::occupancy;
76 knownKeys["tempFactor"] = TremoloKey::tempFactor;
77 knownKeys["segID"] = TremoloKey::segID;
78 knownKeys["Charge"] = TremoloKey::Charge;
79 knownKeys["charge"] = TremoloKey::charge;
80 knownKeys["GrpTypeNo"] = TremoloKey::GrpTypeNo;
81 knownKeys["torsion"] = TremoloKey::torsion;
82
83 createKnownTypesByIdentity();
84
85 // default behavior: use all possible keys on output
86 for (std::map<std::string, TremoloKey::atomDataKey>::iterator iter = knownKeys.begin(); iter != knownKeys.end(); ++iter)
87 usedFields.push_back(iter->first);
88
89 // and noKey afterwards(!) such that it is not used in usedFields
90 knownKeys[" "] = TremoloKey::noKey; // with this we can detect invalid keys
91
92 // invert knownKeys for debug output
93 for (std::map<std::string, TremoloKey::atomDataKey>::iterator iter = knownKeys.begin(); iter != knownKeys.end(); ++iter)
94 knownKeyNames.insert( make_pair( iter->second, iter->first) );
95
96 additionalAtomData.clear();
97}
98
99/**
100 * Destructor.
101 */
102FormatParser< tremolo >::~FormatParser()
103{
104 LOG(1, "INFO: Clearing usedFields.");
105 usedFields.clear();
106 additionalAtomData.clear();
107 knownKeys.clear();
108}
109
110/**
111 * Loads atoms from a tremolo-formatted file.
112 *
113 * \param tremolo file
114 */
115void FormatParser< tremolo >::load(istream* file) {
116 std::string line;
117 std::string::size_type location;
118
119 // reset the id maps
120 resetIdAssociations();
121
122 LOG(1, "INFO: Clearing usedFields.");
123 usedFields.clear();
124
125 molecule *newmol = World::getInstance().createMolecule();
126 newmol->ActiveFlag = true;
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 (file->good()) {
130 std::getline(*file, line, '\n');
131 if (usedFields.empty()) {
132 location = line.find("ATOMDATA", 0);
133 if (location != string::npos) {
134 parseAtomDataKeysLine(line, location + 8);
135 }
136 }
137 if (line.length() > 0 && line.at(0) != '#') {
138 readAtomDataLine(line, newmol);
139 }
140 }
141 LOG(3, "usedFields after load contains: " << usedFields);
142
143 // refresh atom::nr and atom::name
144 std::vector<atomId_t> atoms(newmol->getAtomCount());
145 std::transform(newmol->begin(), newmol->end(), atoms.begin(),
146 boost::bind(&atom::getId, _1));
147 processNeighborInformation(atoms);
148 adaptImprData();
149 adaptTorsion();
150}
151
152/**
153 * Saves the \a atoms into as a tremolo file.
154 *
155 * \param file where to save the state
156 * \param atoms atoms to store
157 */
158void FormatParser< tremolo >::save(ostream* file, const std::vector<atom *> &AtomList) {
159 LOG(0, "Saving changes to tremolo.");
160
161 std::vector<atom*>::const_iterator atomIt;
162 /*vector<string>::iterator it;*/
163 std::vector<std::string>::iterator it = unique(usedFields.begin(), usedFields.end()); // skips all duplicates in the vector
164
165 LOG(3, "INFO: usedFields before save contains: " << usedFields);
166 //LOG(3, "INFO: additionalAtomData contains: " << additionalAtomData);
167
168 // distribute continuous indices
169 resetIdAssociations();
170 atomId_t lastid = 0;
171 for (atomIt = AtomList.begin(); atomIt != AtomList.end(); atomIt++) {
172 associateLocaltoGlobalId(++lastid, (*atomIt)->getId());
173 }
174
175 // store Atomdata line
176 *file << "# ATOMDATA";
177 for (it=usedFields.begin(); it < usedFields.end(); it++) {
178 *file << "\t" << *it;
179 }
180 *file << endl;
181
182 // store Box info
183 *file << "# Box";
184 const RealSpaceMatrix &M = World::getInstance().getDomain().getM();
185 for (size_t i=0; i<NDIM;++i)
186 for (size_t j=0; j<NDIM;++j)
187 *file << "\t" << M.at(i,j);
188 *file << std::endl;
189
190 // store particles
191 for (atomIt = AtomList.begin(); atomIt != AtomList.end(); atomIt++) {
192 saveLine(file, *atomIt);
193 }
194}
195
196/** Add default info, when new atom is added to World.
197 *
198 * @param id of atom
199 */
200void FormatParser< tremolo >::AtomInserted(atomId_t id)
201{
202 std::map<const atomId_t, TremoloAtomInfoContainer>::iterator iter = additionalAtomData.find(id);
203 ASSERT(iter == additionalAtomData.end(),
204 "FormatParser< tremolo >::AtomInserted() - additionalAtomData already present for newly added atom "
205 +toString(id)+".");
206 // don't add entry, as this gives a default resSeq of 0 not the molecule id
207 // additionalAtomData.insert( std::make_pair(id, TremoloAtomInfoContainer()) );
208}
209
210/** Remove additional AtomData info, when atom has been removed from World.
211 *
212 * @param id of atom
213 */
214void FormatParser< tremolo >::AtomRemoved(atomId_t id)
215{
216 std::map<const atomId_t, TremoloAtomInfoContainer>::iterator iter = additionalAtomData.find(id);
217 // as we do not insert AtomData on AtomInserted, we cannot be assured of its presence
218// ASSERT(iter != additionalAtomData.end(),
219// "FormatParser< tremolo >::AtomRemoved() - additionalAtomData is not present for atom "
220// +toString(id)+" to remove.");
221 if (iter != additionalAtomData.end())
222 additionalAtomData.erase(iter);
223}
224
225/**
226 * Sets the keys for which data should be written to the stream when save is
227 * called.
228 *
229 * \param string of field names with the same syntax as for an ATOMDATA line
230 * but without the prexix "ATOMDATA"
231 */
232void FormatParser< tremolo >::setFieldsForSave(std::string atomDataLine) {
233 parseAtomDataKeysLine(atomDataLine, 0);
234}
235
236
237/**
238 * Writes one line of tremolo-formatted data to the provided stream.
239 *
240 * \param stream where to write the line to
241 * \param reference to the atom of which information should be written
242 */
243void FormatParser< tremolo >::saveLine(ostream* file, atom* currentAtom) {
244 std::vector<string>::iterator it;
245
246 TremoloKey::atomDataKey currentField;
247
248 LOG(4, "INFO: Saving atom " << *currentAtom << ", its father id is " << currentAtom->GetTrueFather()->getId());
249
250 for (it = usedFields.begin(); it != usedFields.end(); it++) {
251 currentField = knownKeys[it->substr(0, it->find("="))];
252 switch (currentField) {
253 case TremoloKey::x :
254 // for the moment, assume there are always three dimensions
255 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getPosition());
256 *file << currentAtom->at(0) << "\t";
257 *file << currentAtom->at(1) << "\t";
258 *file << currentAtom->at(2) << "\t";
259 break;
260 case TremoloKey::u :
261 // for the moment, assume there are always three dimensions
262 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getAtomicVelocity());
263 *file << currentAtom->getAtomicVelocity()[0] << "\t";
264 *file << currentAtom->getAtomicVelocity()[1] << "\t";
265 *file << currentAtom->getAtomicVelocity()[2] << "\t";
266 break;
267 case TremoloKey::type :
268 if (additionalAtomData.count(currentAtom->getId())) {
269 if (additionalAtomData[currentAtom->getId()].get(currentField) != "-") {
270 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << additionalAtomData[currentAtom->getId()].get(currentField));
271 *file << additionalAtomData[currentAtom->getId()].get(currentField) << "\t";
272 } else {
273 LOG(3, "Writing for type " << knownKeyNames[currentField] << " default value: " << currentAtom->getType()->getSymbol());
274 *file << currentAtom->getType()->getSymbol() << "\t";
275 }
276 } else if (additionalAtomData.count(currentAtom->GetTrueFather()->getId())) {
277 if (additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField) != "-") {
278 LOG(3, "Writing for type " << knownKeyNames[currentField] << " stuff from father: " << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField));
279 *file << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField) << "\t";
280 } else {
281 LOG(3, "Writing for type " << knownKeyNames[currentField] << " default value from father: " << currentAtom->GetTrueFather()->getType()->getSymbol());
282 *file << currentAtom->GetTrueFather()->getType()->getSymbol() << "\t";
283 }
284 } else {
285 LOG(3, "Writing for type " << knownKeyNames[currentField] << " its default value: " << currentAtom->getType()->getSymbol());
286 *file << currentAtom->getType()->getSymbol() << "\t";
287 }
288 break;
289 case TremoloKey::Id :
290 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getId()+1);
291 *file << getLocalId(currentAtom->getId()) << "\t";
292 break;
293 case TremoloKey::neighbors :
294 LOG(3, "Writing type " << knownKeyNames[currentField]);
295 writeNeighbors(file, atoi(it->substr(it->find("=") + 1, 1).c_str()), currentAtom);
296 break;
297 case TremoloKey::resSeq :
298 if (additionalAtomData.count(currentAtom->getId())) {
299 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << additionalAtomData[currentAtom->getId()].get(currentField));
300 *file << additionalAtomData[currentAtom->getId()].get(currentField);
301 } else if (currentAtom->getMolecule() != NULL) {
302 LOG(3, "Writing for type " << knownKeyNames[currentField] << " its own id: " << currentAtom->getMolecule()->getId()+1);
303 *file << setw(4) << currentAtom->getMolecule()->getId()+1;
304 } else {
305 LOG(3, "Writing for type " << knownKeyNames[currentField] << " default value: " << defaultAdditionalData.get(currentField));
306 *file << defaultAdditionalData.get(currentField);
307 }
308 *file << "\t";
309 break;
310 default :
311 if (additionalAtomData.count(currentAtom->getId())) {
312 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << additionalAtomData[currentAtom->getId()].get(currentField));
313 *file << additionalAtomData[currentAtom->getId()].get(currentField);
314 } else if (additionalAtomData.count(currentAtom->GetTrueFather()->getId())) {
315 LOG(3, "Writing for type " << knownKeyNames[currentField] << " stuff from father: " << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField));
316 *file << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField);
317 } else {
318 LOG(3, "Writing for type " << knownKeyNames[currentField] << " the default: " << defaultAdditionalData.get(currentField));
319 *file << defaultAdditionalData.get(currentField);
320 }
321 *file << "\t";
322 break;
323 }
324 }
325
326 *file << endl;
327}
328
329/**
330 * Writes the neighbor information of one atom to the provided stream.
331 *
332 * Note that ListOfBonds of WorldTime::CurrentTime is used.
333 *
334 * \param stream where to write neighbor information to
335 * \param number of neighbors
336 * \param reference to the atom of which to take the neighbor information
337 */
338void FormatParser< tremolo >::writeNeighbors(ostream* file, int numberOfNeighbors, atom* currentAtom) {
339 const BondList& ListOfBonds = currentAtom->getListOfBonds();
340 // sort bonded indices
341 typedef std::set<atomId_t> sortedIndices;
342 sortedIndices sortedBonds;
343 for (BondList::const_iterator iter = ListOfBonds.begin();
344 iter != ListOfBonds.end(); ++iter)
345 sortedBonds.insert(getLocalId((*iter)->GetOtherAtom(currentAtom)->getId()));
346 // print indices
347 sortedIndices::const_iterator currentBond = sortedBonds.begin();
348 for (int i = 0; i < numberOfNeighbors; i++) {
349 *file << (currentBond != sortedBonds.end() ? (*currentBond) : 0) << "\t";
350 if (currentBond != sortedBonds.end())
351 ++currentBond;
352 }
353}
354
355/**
356 * Stores keys from the ATOMDATA line.
357 *
358 * \param line to parse the keys from
359 * \param with which offset the keys begin within the line
360 */
361void FormatParser< tremolo >::parseAtomDataKeysLine(std::string line, int offset) {
362 std::string keyword;
363 std::stringstream lineStream;
364
365 lineStream << line.substr(offset);
366 LOG(1, "INFO: Clearing usedFields in parseAtomDataKeysLine.");
367 usedFields.clear();
368 while (lineStream.good()) {
369 lineStream >> keyword;
370 if (knownKeys[keyword.substr(0, keyword.find("="))] == TremoloKey::noKey) {
371 // TODO: throw exception about unknown key
372 cout << "Unknown key: " << keyword << " is not part of the tremolo format specification." << endl;
373 break;
374 }
375 usedFields.push_back(keyword);
376 }
377 //LOG(1, "INFO: " << usedFields);
378}
379
380/** Sets the properties per atom to print to .data file by parsing line from
381 * \a atomdata_string.
382 *
383 * We just call \sa FormatParser< tremolo >::parseAtomDataKeysLine() which is left
384 * private.,
385 *
386 * @param atomdata_string line to parse with space-separated values
387 */
388void FormatParser< tremolo >::setAtomData(const std::string &atomdata_string)
389{
390 parseAtomDataKeysLine(atomdata_string, 0);
391}
392
393
394/**
395 * Reads one data line of a tremolo file and interprets it according to the keys
396 * obtained from the ATOMDATA line.
397 *
398 * \param line to parse as an atom
399 * \param *newmol molecule to add atom to
400 */
401void FormatParser< tremolo >::readAtomDataLine(std::string line, molecule *newmol = NULL) {
402 std::vector<string>::iterator it;
403 std::stringstream lineStream;
404 atom* newAtom = World::getInstance().createAtom();
405 const atomId_t atomid = newAtom->getId();
406 additionalAtomData[atomid] = TremoloAtomInfoContainer(); // fill with default values
407 TremoloAtomInfoContainer *atomInfo = &additionalAtomData[atomid];
408 TremoloKey::atomDataKey currentField;
409 ConvertTo<double> toDouble;
410 ConvertTo<int> toInt;
411 Vector tempVector;
412
413 // setup tokenizer, splitting up white-spaced entries
414 typedef boost::tokenizer<boost::char_separator<char> >
415 tokenizer;
416 boost::char_separator<char> whitespacesep(" \t");
417 tokenizer tokens(line, whitespacesep);
418 ASSERT(tokens.begin() != tokens.end(),
419 "FormatParser< tremolo >::readAtomDataLine - empty string, need at least ' '!");
420 tokenizer::iterator tok_iter = tokens.begin();
421 // then associate each token to each file
422 for (it = usedFields.begin(); it < usedFields.end(); it++) {
423 const std::string keyName = it->substr(0, it->find("="));
424 currentField = knownKeys[keyName];
425 const std::string word = *tok_iter;
426 LOG(4, "INFO: Parsing key " << keyName << " with remaining data " << word);
427 switch (currentField) {
428 case TremoloKey::x :
429 // for the moment, assume there are always three dimensions
430 for (int i=0;i<NDIM;i++) {
431 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for x["+toString(i)+"]!");
432 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
433 newAtom->set(i, toDouble(*tok_iter));
434 tok_iter++;
435 }
436 break;
437 case TremoloKey::u :
438 // for the moment, assume there are always three dimensions
439 for (int i=0;i<NDIM;i++) {
440 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for u["+toString(i)+"]!");
441 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
442 tempVector[i] = toDouble(*tok_iter);
443 tok_iter++;
444 }
445 newAtom->setAtomicVelocity(tempVector);
446 break;
447 case TremoloKey::type :
448 {
449 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
450 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
451 std::string element;
452 try {
453 element = knownTypes.getType(*tok_iter);
454 } catch(IllegalParserKeyException) {
455 // clean up
456 World::getInstance().destroyAtom(newAtom);
457 // give an error
458 ELOG(0, "TremoloParser: I do not understand the element token " << *tok_iter << ".");
459 }
460 // put type name into container for later use
461 atomInfo->set(currentField, *tok_iter);
462 LOG(4, "INFO: Parsing element " << (*tok_iter) << " as " << element << " according to KnownTypes.");
463 tok_iter++;
464 newAtom->setType(World::getInstance().getPeriode()->FindElement(element));
465 ASSERT(newAtom->getType(), "Type was not set for this atom");
466 break;
467 }
468 case TremoloKey::Id :
469 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
470 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
471 associateLocaltoGlobalId(toInt(*tok_iter), atomid);
472 tok_iter++;
473 break;
474 case TremoloKey::neighbors :
475 for (int i=0;i<atoi(it->substr(it->find("=") + 1, 1).c_str());i++) {
476 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
477 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
478 lineStream << *tok_iter << "\t";
479 tok_iter++;
480 }
481 readNeighbors(&lineStream,
482 atoi(it->substr(it->find("=") + 1, 1).c_str()), atomid);
483 break;
484 default :
485 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
486 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
487 atomInfo->set(currentField, *tok_iter);
488 tok_iter++;
489 break;
490 }
491 }
492 LOG(3, "INFO: Parsed atom " << atomid << ".");
493 if (newmol != NULL)
494 newmol->AddAtom(newAtom);
495}
496
497/**
498 * Reads neighbor information for one atom from the input.
499 *
500 * \param line stream where to read the information from
501 * \param numberOfNeighbors number of neighbors to read
502 * \param atomid world id of the atom the information belongs to
503 */
504void FormatParser< tremolo >::readNeighbors(std::stringstream* line, int numberOfNeighbors, int atomId) {
505 int neighborId = 0;
506 for (int i = 0; i < numberOfNeighbors; i++) {
507 *line >> neighborId;
508 // 0 is used to fill empty neighbor positions in the tremolo file.
509 if (neighborId > 0) {
510 LOG(4, "INFO: Atom with global id " << atomId
511 << " has neighbour with serial " << neighborId);
512 additionalAtomData[atomId].neighbors.push_back(neighborId);
513 }
514 }
515}
516
517/**
518 * Checks whether the provided name is within the list of used fields.
519 *
520 * \param field name to check
521 *
522 * \return true if the field name is used
523 */
524bool FormatParser< tremolo >::isUsedField(std::string fieldName) {
525 bool fieldNameExists = false;
526 for (std::vector<std::string>::iterator usedField = usedFields.begin(); usedField != usedFields.end(); usedField++) {
527 if (usedField->substr(0, usedField->find("=")) == fieldName)
528 fieldNameExists = true;
529 }
530
531 return fieldNameExists;
532}
533
534
535/**
536 * Adds the collected neighbor information to the atoms in the world. The atoms
537 * are found by their current ID and mapped to the corresponding atoms with the
538 * Id found in the parsed file.
539 *
540 * @param atoms vector with all newly added (global) atomic ids
541 */
542void FormatParser< tremolo >::processNeighborInformation(const std::vector<atomId_t> &atoms) {
543 if (!isUsedField("neighbors")) {
544 return;
545 }
546
547 for (std::vector<atomId_t>::const_iterator iter = atoms.begin(); iter != atoms.end(); ++iter) {
548 ASSERT(additionalAtomData.count(*iter) != 0,
549 "FormatParser< tremolo >::processNeighborInformation() - global id "
550 +toString(*iter)+" unknown in additionalAtomData.");
551 TremoloAtomInfoContainer &currentInfo = additionalAtomData[*iter];
552 ASSERT (!currentInfo.neighbors_processed,
553 "FormatParser< tremolo >::processNeighborInformation() - neighbors of new atom "
554 +toString(*iter)+" are already processed.");
555 for(std::vector<int>::const_iterator neighbor = currentInfo.neighbors.begin();
556 neighbor != currentInfo.neighbors.end(); neighbor++
557 ) {
558 LOG(3, "INFO: Creating bond between ("
559 << *iter
560 << ") and ("
561 << getGlobalId(*neighbor) << "|" << *neighbor << ")");
562 ASSERT(getGlobalId(*neighbor) != -1,
563 "FormatParser< tremolo >::processNeighborInformation() - global id to local id "
564 +toString(*neighbor)+" is unknown.");
565 World::getInstance().getAtom(AtomById(*iter))
566 ->addBond(WorldTime::getTime(), World::getInstance().getAtom(AtomById(getGlobalId(*neighbor))));
567 }
568 currentInfo.neighbors_processed = true;
569 }
570}
571
572/**
573 * Replaces atom IDs read from the file by the corresponding world IDs. All IDs
574 * IDs of the input string will be replaced; expected separating characters are
575 * "-" and ",".
576 *
577 * \param string in which atom IDs should be adapted
578 *
579 * \return input string with modified atom IDs
580 */
581std::string FormatParser< tremolo >::adaptIdDependentDataString(std::string data) {
582 // there might be no IDs
583 if (data == "-") {
584 return "-";
585 }
586
587 char separator;
588 int id;
589 std::stringstream line, result;
590 line << data;
591
592 line >> id;
593 result << getGlobalId(id);
594 while (line.good()) {
595 line >> separator >> id;
596 result << separator << getGlobalId(id);
597 }
598
599 return result.str();
600}
601
602/**
603 * Corrects the atom IDs in each imprData entry to the corresponding world IDs
604 * as they might differ from the originally read IDs.
605 */
606void FormatParser< tremolo >::adaptImprData() {
607 if (!isUsedField("imprData")) {
608 return;
609 }
610
611 for(std::map<const atomId_t, TremoloAtomInfoContainer>::iterator currentInfo = additionalAtomData.begin();
612 currentInfo != additionalAtomData.end(); currentInfo++
613 ) {
614 currentInfo->second.imprData = adaptIdDependentDataString(currentInfo->second.imprData);
615 }
616}
617
618/**
619 * Corrects the atom IDs in each torsion entry to the corresponding world IDs
620 * as they might differ from the originally read IDs.
621 */
622void FormatParser< tremolo >::adaptTorsion() {
623 if (!isUsedField("torsion")) {
624 return;
625 }
626
627 for(std::map<const atomId_t, TremoloAtomInfoContainer>::iterator currentInfo = additionalAtomData.begin();
628 currentInfo != additionalAtomData.end(); currentInfo++
629 ) {
630 currentInfo->second.torsion = adaptIdDependentDataString(currentInfo->second.torsion);
631 }
632}
633
Note: See TracBrowser for help on using the repository browser.