source: src/Parser/TremoloParser.cpp@ 8bf9c6

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 Candidate_v1.7.0 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 8bf9c6 was 8bf9c6, checked in by Frederik Heber <heber@…>, 14 years ago

All additionalAtomData maps now have const atomId_t as key.

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