source: src/Parser/TremoloParser.cpp@ 794bc8

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 794bc8 was 6f0841, checked in by Frederik Heber <heber@…>, 13 years ago

Shifted all modules related to atoms into own subfolder src/Atom/

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