source: src/Parser/TremoloParser.cpp@ bcfb77

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

HUGE: Removed all calls to Log(), eLog(), replaced by LOG() and ELOG().

  • Replaced DoLog(.) && (Log() << Verbose(.) << ... << std::endl) by Log(., ...).
  • Replaced Log() << Verbose(.) << .. << by Log(., ...)
  • on multiline used stringstream to generate and message which was finally used in LOG(., output.str())
  • there should be no more occurence of Log(). LOG() and ELOG() must be used instead.
  • Eventually, this will allow for storing all errors and re-printing them on program exit which would be very helpful to ascertain error-free runs for the user.
  • 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 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.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 std::cerr << "Clearing usedFields." << std::endl;
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 std::cerr << "Clearing usedFields." << std::endl;
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 // TODO: Is unique for FormatParser< tremolo >::usedFields still required?
229 vector<string>::iterator it = unique(usedFields.begin(), usedFields.end()); // skips all duplicates in the vector
230
231 TremoloKey::atomDataKey currentField;
232
233 LOG(4, "INFO: Saving atom " << *currentAtom << ", its father id is " << currentAtom->GetTrueFather()->getId());
234
235 for (it = usedFields.begin(); it != usedFields.end(); it++) {
236 currentField = knownKeys[it->substr(0, it->find("="))];
237 switch (currentField) {
238 case TremoloKey::x :
239 // for the moment, assume there are always three dimensions
240 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getPosition());
241 *file << currentAtom->at(0) << "\t";
242 *file << currentAtom->at(1) << "\t";
243 *file << currentAtom->at(2) << "\t";
244 break;
245 case TremoloKey::u :
246 // for the moment, assume there are always three dimensions
247 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getAtomicVelocity());
248 *file << currentAtom->getAtomicVelocity()[0] << "\t";
249 *file << currentAtom->getAtomicVelocity()[1] << "\t";
250 *file << currentAtom->getAtomicVelocity()[2] << "\t";
251 break;
252 case TremoloKey::type :
253 if (additionalAtomData.count(currentAtom->getId())) {
254 if (additionalAtomData[currentAtom->getId()].get(currentField) != "-") {
255 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << additionalAtomData[currentAtom->getId()].get(currentField));
256 *file << additionalAtomData[currentAtom->getId()].get(currentField) << "\t";
257 } else {
258 LOG(3, "Writing for type " << knownKeyNames[currentField] << " default value: " << currentAtom->getType()->getSymbol());
259 *file << currentAtom->getType()->getSymbol() << "\t";
260 }
261 } else if (additionalAtomData.count(currentAtom->GetTrueFather()->getId())) {
262 if (additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField) != "-") {
263 LOG(3, "Writing for type " << knownKeyNames[currentField] << " stuff from father: " << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField));
264 *file << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField) << "\t";
265 } else {
266 LOG(3, "Writing for type " << knownKeyNames[currentField] << " default value from father: " << currentAtom->GetTrueFather()->getType()->getSymbol());
267 *file << currentAtom->GetTrueFather()->getType()->getSymbol() << "\t";
268 }
269 } else {
270 LOG(3, "Writing for type " << knownKeyNames[currentField] << " its default value: " << currentAtom->getType()->getSymbol());
271 *file << currentAtom->getType()->getSymbol() << "\t";
272 }
273 break;
274 case TremoloKey::Id :
275 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getId()+1);
276 *file << currentAtom->getId()+1 << "\t";
277 break;
278 case TremoloKey::neighbors :
279 LOG(3, "Writing type " << knownKeyNames[currentField]);
280 writeNeighbors(file, atoi(it->substr(it->find("=") + 1, 1).c_str()), currentAtom);
281 break;
282 case TremoloKey::resSeq :
283 if (additionalAtomData.count(currentAtom->getId())) {
284 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << additionalAtomData[currentAtom->getId()].get(currentField));
285 *file << additionalAtomData[currentAtom->getId()].get(currentField);
286 } else if (currentAtom->getMolecule() != NULL) {
287 LOG(3, "Writing for type " << knownKeyNames[currentField] << " its own id: " << currentAtom->getMolecule()->getId()+1);
288 *file << setw(4) << currentAtom->getMolecule()->getId()+1;
289 } else {
290 LOG(3, "Writing for type " << knownKeyNames[currentField] << " default value: " << defaultAdditionalData.get(currentField));
291 *file << defaultAdditionalData.get(currentField);
292 }
293 *file << "\t";
294 break;
295 default :
296 if (additionalAtomData.count(currentAtom->getId())) {
297 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << additionalAtomData[currentAtom->getId()].get(currentField));
298 *file << additionalAtomData[currentAtom->getId()].get(currentField);
299 } else if (additionalAtomData.count(currentAtom->GetTrueFather()->getId())) {
300 LOG(3, "Writing for type " << knownKeyNames[currentField] << " stuff from father: " << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField));
301 *file << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField);
302 } else {
303 LOG(3, "Writing for type " << knownKeyNames[currentField] << " the default: " << defaultAdditionalData.get(currentField));
304 *file << defaultAdditionalData.get(currentField);
305 }
306 *file << "\t";
307 break;
308 }
309 }
310
311 *file << endl;
312}
313
314/**
315 * Writes the neighbor information of one atom to the provided stream.
316 *
317 * Note that ListOfBonds of WorldTime::CurrentTime is used.
318 *
319 * \param stream where to write neighbor information to
320 * \param number of neighbors
321 * \param reference to the atom of which to take the neighbor information
322 */
323void FormatParser< tremolo >::writeNeighbors(ostream* file, int numberOfNeighbors, atom* currentAtom) {
324 const BondList& ListOfBonds = currentAtom->getListOfBonds();
325 // sort bonded indices
326 typedef std::set<atomId_t> sortedIndices;
327 sortedIndices sortedBonds;
328 for (BondList::const_iterator iter = ListOfBonds.begin();
329 iter != ListOfBonds.end(); ++iter)
330 sortedBonds.insert((*iter)->GetOtherAtom(currentAtom)->getId());
331 // print indices
332 sortedIndices::const_iterator currentBond = sortedBonds.begin();
333 for (int i = 0; i < numberOfNeighbors; i++) {
334 *file << (currentBond != sortedBonds.end() ? (*currentBond)+1 : 0) << "\t";
335 if (currentBond != sortedBonds.end())
336 ++currentBond;
337 }
338}
339
340/**
341 * Stores keys from the ATOMDATA line.
342 *
343 * \param line to parse the keys from
344 * \param with which offset the keys begin within the line
345 */
346void FormatParser< tremolo >::parseAtomDataKeysLine(string line, int offset) {
347 string keyword;
348 stringstream lineStream;
349
350 lineStream << line.substr(offset);
351 std::cerr << "Clearing usedFields in parseAtomDataKeysLine." << std::endl;
352 usedFields.clear();
353 while (lineStream.good()) {
354 lineStream >> keyword;
355 if (knownKeys[keyword.substr(0, keyword.find("="))] == TremoloKey::noKey) {
356 // TODO: throw exception about unknown key
357 cout << "Unknown key: " << keyword << " is not part of the tremolo format specification." << endl;
358 break;
359 }
360 usedFields.push_back(keyword);
361 }
362 //LOG(1, "INFO: " << usedFields);
363}
364
365/** Sets the properties per atom to print to .data file by parsing line from
366 * \a atomdata_string.
367 *
368 * We just call \sa FormatParser< tremolo >::parseAtomDataKeysLine() which is left
369 * private.,
370 *
371 * @param atomdata_string line to parse with space-separated values
372 */
373void FormatParser< tremolo >::setAtomData(const std::string &atomdata_string)
374{
375 parseAtomDataKeysLine(atomdata_string, 0);
376}
377
378
379/**
380 * Reads one data line of a tremolo file and interprets it according to the keys
381 * obtained from the ATOMDATA line.
382 *
383 * \param line to parse as an atom
384 * \param *newmol molecule to add atom to
385 */
386void FormatParser< tremolo >::readAtomDataLine(string line, molecule *newmol = NULL) {
387 vector<string>::iterator it;
388 stringstream lineStream;
389 atom* newAtom = World::getInstance().createAtom();
390 TremoloAtomInfoContainer *atomInfo = NULL;
391 additionalAtomData[newAtom->getId()] = TremoloAtomInfoContainer(); // fill with default values
392 atomInfo = &additionalAtomData[newAtom->getId()];
393 TremoloKey::atomDataKey currentField;
394 ConvertTo<double> toDouble;
395 ConvertTo<int> toInt;
396 Vector tempVector;
397
398 // setup tokenizer, splitting up white-spaced entries
399 typedef boost::tokenizer<boost::char_separator<char> >
400 tokenizer;
401 boost::char_separator<char> whitespacesep(" \t");
402 tokenizer tokens(line, whitespacesep);
403 ASSERT(tokens.begin() != tokens.end(),
404 "FormatParser< tremolo >::readAtomDataLine - empty string, need at least ' '!");
405 tokenizer::iterator tok_iter = tokens.begin();
406 // then associate each token to each file
407 for (it = usedFields.begin(); it < usedFields.end(); it++) {
408 const std::string keyName = it->substr(0, it->find("="));
409 currentField = knownKeys[keyName];
410 const string word = *tok_iter;
411 LOG(4, "INFO: Parsing key " << keyName << " with remaining data " << word);
412 switch (currentField) {
413 case TremoloKey::x :
414 // for the moment, assume there are always three dimensions
415 for (int i=0;i<NDIM;i++) {
416 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for x["+toString(i)+"]!");
417 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
418 newAtom->set(i, toDouble(*tok_iter));
419 tok_iter++;
420 }
421 break;
422 case TremoloKey::u :
423 // for the moment, assume there are always three dimensions
424 for (int i=0;i<NDIM;i++) {
425 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for u["+toString(i)+"]!");
426 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
427 tempVector[i] = toDouble(*tok_iter);
428 tok_iter++;
429 }
430 newAtom->setAtomicVelocity(tempVector);
431 break;
432 case TremoloKey::type :
433 {
434 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
435 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
436 std::string element(knownTypes[(*tok_iter)]);
437 // put type name into container for later use
438 atomInfo->set(currentField, *tok_iter);
439 LOG(4, "INFO: Parsing element " << (*tok_iter) << " as " << element << " according to KnownTypes.");
440 tok_iter++;
441 newAtom->setType(World::getInstance().getPeriode()->FindElement(element));
442 ASSERT(newAtom->getType(), "Type was not set for this atom");
443 break;
444 }
445 case TremoloKey::Id :
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 atomIdMap[toInt(*tok_iter)] = newAtom->getId();
449 tok_iter++;
450 break;
451 case TremoloKey::neighbors :
452 for (int i=0;i<atoi(it->substr(it->find("=") + 1, 1).c_str());i++) {
453 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
454 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
455 lineStream << *tok_iter << "\t";
456 tok_iter++;
457 }
458 readNeighbors(&lineStream,
459 atoi(it->substr(it->find("=") + 1, 1).c_str()), newAtom->getId());
460 break;
461 default :
462 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
463 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
464 atomInfo->set(currentField, *tok_iter);
465 tok_iter++;
466 break;
467 }
468 }
469 if (newmol != NULL) {
470 //LOG(0, "New Atom: " << *newAtom << " with type " << newAtom->getType()->getName());
471 newmol->AddAtom(newAtom);
472 }
473}
474
475/**
476 * Reads neighbor information for one atom from the input.
477 *
478 * \param line stream where to read the information from
479 * \param numberOfNeighbors number of neighbors to read
480 * \param atomid world id of the atom the information belongs to
481 */
482void FormatParser< tremolo >::readNeighbors(stringstream* line, int numberOfNeighbors, int atomId) {
483 int neighborId = 0;
484 for (int i = 0; i < numberOfNeighbors; i++) {
485 *line >> neighborId;
486 // 0 is used to fill empty neighbor positions in the tremolo file.
487 if (neighborId > 0) {
488 LOG(4, "INFO: Atom with global id " << atomId
489 << " has neighbour with serial " << neighborId);
490 additionalAtomData[atomId].neighbors.push_back(neighborId);
491 }
492 }
493}
494
495/**
496 * Checks whether the provided name is within the list of used fields.
497 *
498 * \param field name to check
499 *
500 * \return true if the field name is used
501 */
502bool FormatParser< tremolo >::isUsedField(string fieldName) {
503 bool fieldNameExists = false;
504 for (vector<string>::iterator usedField = usedFields.begin(); usedField != usedFields.end(); usedField++) {
505 if (usedField->substr(0, usedField->find("=")) == fieldName)
506 fieldNameExists = true;
507 }
508
509 return fieldNameExists;
510}
511
512
513/**
514 * Adds the collected neighbor information to the atoms in the world. The atoms
515 * are found by their current ID and mapped to the corresponding atoms with the
516 * Id found in the parsed file.
517 */
518void FormatParser< tremolo >::processNeighborInformation() {
519 if (!isUsedField("neighbors")) {
520 return;
521 }
522
523 for(map<int, TremoloAtomInfoContainer>::iterator currentInfo = additionalAtomData.begin();
524 currentInfo != additionalAtomData.end(); currentInfo++
525 ) {
526 if (!currentInfo->second.neighbors_processed) {
527 for(vector<int>::iterator neighbor = currentInfo->second.neighbors.begin();
528 neighbor != currentInfo->second.neighbors.end(); neighbor++
529 ) {
530// LOG(1, "INFO: Creating bond between ("
531// << currentInfo->first
532// << ") and ("
533// << atomIdMap[*neighbor] << "|" << *neighbor << ")");
534 World::getInstance().getAtom(AtomById(currentInfo->first))
535 ->addBond(WorldTime::getTime(), World::getInstance().getAtom(AtomById(atomIdMap[*neighbor])));
536 }
537 currentInfo->second.neighbors_processed = true;
538 }
539 }
540}
541
542/**
543 * Replaces atom IDs read from the file by the corresponding world IDs. All IDs
544 * IDs of the input string will be replaced; expected separating characters are
545 * "-" and ",".
546 *
547 * \param string in which atom IDs should be adapted
548 *
549 * \return input string with modified atom IDs
550 */
551std::string FormatParser< tremolo >::adaptIdDependentDataString(string data) {
552 // there might be no IDs
553 if (data == "-") {
554 return "-";
555 }
556
557 char separator;
558 int id;
559 stringstream line, result;
560 line << data;
561
562 line >> id;
563 result << atomIdMap[id];
564 while (line.good()) {
565 line >> separator >> id;
566 result << separator << atomIdMap[id];
567 }
568
569 return result.str();
570}
571
572/**
573 * Corrects the atom IDs in each imprData entry to the corresponding world IDs
574 * as they might differ from the originally read IDs.
575 */
576void FormatParser< tremolo >::adaptImprData() {
577 if (!isUsedField("imprData")) {
578 return;
579 }
580
581 for(map<int, TremoloAtomInfoContainer>::iterator currentInfo = additionalAtomData.begin();
582 currentInfo != additionalAtomData.end(); currentInfo++
583 ) {
584 currentInfo->second.imprData = adaptIdDependentDataString(currentInfo->second.imprData);
585 }
586}
587
588/**
589 * Corrects the atom IDs in each torsion entry to the corresponding world IDs
590 * as they might differ from the originally read IDs.
591 */
592void FormatParser< tremolo >::adaptTorsion() {
593 if (!isUsedField("torsion")) {
594 return;
595 }
596
597 for(map<int, TremoloAtomInfoContainer>::iterator currentInfo = additionalAtomData.begin();
598 currentInfo != additionalAtomData.end(); currentInfo++
599 ) {
600 currentInfo->second.torsion = adaptIdDependentDataString(currentInfo->second.torsion);
601 }
602}
603
604/** Creates knownTypes as the identity, e.g. H -> H, He -> He, ... .
605 *
606 */
607void FormatParser< tremolo >::createKnownTypesByIdentity()
608{
609 // remove old mapping
610 knownTypes.clear();
611 // make knownTypes the identity mapping
612 const periodentafel *periode = World::getInstance().getPeriode();
613 for (periodentafel::const_iterator iter = periode->begin();
614 iter != periode->end();
615 ++iter) {
616 knownTypes.insert( make_pair(iter->second->getSymbol(), iter->second->getSymbol()) );
617 }
618}
619
620/** Parses a .potentials file and creates from it the knownTypes file.
621 *
622 * @param file input stream of .potentials file
623 */
624void FormatParser< tremolo >::parseKnownTypes(std::istream &file)
625{
626 const periodentafel *periode = World::getInstance().getPeriode();
627 // remove old mapping
628 knownTypes.clear();
629
630 LOG(3, "additionalAtomData contains: " << additionalAtomData);
631
632 // parse in file
633 typedef boost::tokenizer<boost::char_separator<char> >
634 tokenizer;
635 boost::char_separator<char> tokensep(":\t ,;");
636 boost::char_separator<char> equalitysep("\t =");
637 std::string line;
638 while (file.good()) {
639 std::getline( file, line );
640 LOG(4, "INFO: full line of parameters is '" << line << "'");
641 if (line.find("particle:") != string::npos) {
642 LOG(3, "INFO: found line '" << line << "' containing keyword 'particle:'.");
643 tokenizer tokens(line, tokensep);
644 ASSERT(tokens.begin() != tokens.end(),
645 "FormatParser< tremolo >::parseKnownTypes() - line with 'particle:' but no particles separated by comma.");
646 // look for particle_type
647 std::string particle_type("NULL");
648 std::string element_type("NULL");
649 for (tokenizer::iterator tok_iter = tokens.begin();
650 tok_iter != tokens.end();
651 ++tok_iter) {
652 if ((*tok_iter).find("particle_type") != string::npos) {
653 LOG(3, "INFO: found line '" << line << "' containing keyword 'particle_type'.");
654 tokenizer token((*tok_iter), equalitysep);
655 ASSERT(token.begin() != token.end(),
656 "FormatParser< tremolo >::parseKnownTypes() - could not split particle_type by equality sign");
657 tokenizer::iterator particle_iter = token.begin();
658 particle_iter++;
659 particle_type = *particle_iter;
660 }
661 if ((*tok_iter).find("element_name") != string::npos) {
662 LOG(3, "INFO: found line '" << line << "' containing keyword 'element_name'.");
663 tokenizer token((*tok_iter), equalitysep);
664 ASSERT(token.begin() != token.end(),
665 "FormatParser< tremolo >::parseKnownTypes() - could not split particle_type by equality sign");
666 tokenizer::iterator element_iter = token.begin();
667 element_iter++;
668 element_type = *element_iter;
669 }
670 }
671 if ((particle_type != "NULL") && (element_type != "NULL")) {
672 if (periode->FindElement(element_type) != NULL) {
673 LOG(1, "INFO: Added Type " << particle_type << " as reference to element " << element_type << ".");
674 knownTypes.insert( make_pair (particle_type, element_type) );
675 } else {
676 ELOG(1, "INFO: Either Type " << particle_type << " or " << element_type << " could not be recognized." );
677 }
678 } else {
679 ELOG(1, "INFO: Desired element " << element_type << " is not known." );
680 }
681 }
682 }
683
684}
Note: See TracBrowser for help on using the repository browser.