source: src/Parser/TremoloParser.cpp@ a636f8

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

FIX: TremoloParser now contains usedFields_load and _save to allow for multiple loading.

  • refactored several functions out of ::save().
  • parseAtomDataKeysLine() and isUsedField now require usedFields ref.
  • FIX: save() now erases duplicate entries still in usedFields.
  • removed setFieldsForSave(), was duplicate of setAtomData().
  • new function makeUsedFieldsUnique() to preserver order of appearance in usedFields.
  • this [closes #141].
  • FIX: made several function parameters constant that were not before.
  • FIX: Removed double readAtomDataLine().
  • Property mode set to 100644
File size: 27.7 KB
RevLine 
[bcf653]1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
[0aa122]4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
[bcf653]5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
[6bc51d]8/*
9 * TremoloParser.cpp
10 *
11 * Created on: Mar 2, 2010
12 * Author: metzler
13 */
14
[bf3817]15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
[ad011c]20#include "CodePatterns/MemDebug.hpp"
[112b09]21
[ad011c]22#include "CodePatterns/Assert.hpp"
23#include "CodePatterns/Log.hpp"
[4d4d33]24#include "CodePatterns/toString.hpp"
[ad011c]25#include "CodePatterns/Verbose.hpp"
[42127c]26
[9131f3]27#include "TremoloParser.hpp"
[42127c]28
[6f0841]29#include "Atom/atom.hpp"
[129204]30#include "Bond/bond.hpp"
[ccb487]31#include "Box.hpp"
[42127c]32#include "Descriptors/AtomIdDescriptor.hpp"
[3bdb6d]33#include "Element/element.hpp"
34#include "Element/periodentafel.hpp"
[ccb487]35#include "LinearAlgebra/RealSpaceMatrix.hpp"
[42127c]36#include "molecule.hpp"
37#include "MoleculeListClass.hpp"
38#include "World.hpp"
39#include "WorldTime.hpp"
40
[9131f3]41
[9f8b01]42#include <algorithm>
[2034f3]43#include <boost/lexical_cast.hpp>
[72d108]44#include <boost/tokenizer.hpp>
[74a444]45#include <iostream>
46#include <iomanip>
[8bf9c6]47#include <map>
48#include <sstream>
49#include <vector>
[9131f3]50
[765f16]51// declare specialized static variables
52const std::string FormatParserTrait<tremolo>::name = "tremolo";
53const std::string FormatParserTrait<tremolo>::suffix = "data";
54const ParserTypes FormatParserTrait<tremolo>::type = tremolo;
55
[9131f3]56/**
57 * Constructor.
58 */
[765f16]59FormatParser< tremolo >::FormatParser() :
60 FormatParser_common(NULL)
61{
[b8d4a3]62 knownKeys["x"] = TremoloKey::x;
63 knownKeys["u"] = TremoloKey::u;
64 knownKeys["F"] = TremoloKey::F;
65 knownKeys["stress"] = TremoloKey::stress;
66 knownKeys["Id"] = TremoloKey::Id;
67 knownKeys["neighbors"] = TremoloKey::neighbors;
68 knownKeys["imprData"] = TremoloKey::imprData;
69 knownKeys["GroupMeasureTypeNo"] = TremoloKey::GroupMeasureTypeNo;
[305e7e]70 knownKeys["type"] = TremoloKey::type;
[b8d4a3]71 knownKeys["extType"] = TremoloKey::extType;
72 knownKeys["name"] = TremoloKey::name;
73 knownKeys["resName"] = TremoloKey::resName;
74 knownKeys["chainID"] = TremoloKey::chainID;
75 knownKeys["resSeq"] = TremoloKey::resSeq;
76 knownKeys["occupancy"] = TremoloKey::occupancy;
77 knownKeys["tempFactor"] = TremoloKey::tempFactor;
78 knownKeys["segID"] = TremoloKey::segID;
79 knownKeys["Charge"] = TremoloKey::Charge;
80 knownKeys["charge"] = TremoloKey::charge;
81 knownKeys["GrpTypeNo"] = TremoloKey::GrpTypeNo;
82 knownKeys["torsion"] = TremoloKey::torsion;
[23fd43]83 knownKeys[" "] = TremoloKey::noKey; // with this we can detect invalid keys
[52baf9]84
[4d4d33]85 createKnownTypesByIdentity();
86
87 // invert knownKeys for debug output
88 for (std::map<std::string, TremoloKey::atomDataKey>::iterator iter = knownKeys.begin(); iter != knownKeys.end(); ++iter)
89 knownKeyNames.insert( make_pair( iter->second, iter->first) );
90
91 additionalAtomData.clear();
[9131f3]92}
93
94/**
95 * Destructor.
96 */
[765f16]97FormatParser< tremolo >::~FormatParser()
98{
[23fd43]99 usedFields_save.clear();
[b8d4a3]100 additionalAtomData.clear();
101 knownKeys.clear();
102}
103
104/**
105 * Loads atoms from a tremolo-formatted file.
106 *
107 * \param tremolo file
108 */
[765f16]109void FormatParser< tremolo >::load(istream* file) {
[8bf9c6]110 std::string line;
111 std::string::size_type location;
[b8d4a3]112
[c0e28c]113 // reset the id maps
114 resetIdAssociations();
115
[dc1d9e]116 molecule *newmol = World::getInstance().createMolecule();
[bd2390]117 newmol->ActiveFlag = true;
118 // TODO: Remove the insertion into molecule when saving does not depend on them anymore. Also, remove molecule.hpp include
119 World::getInstance().getMolecules()->insert(newmol);
[b8d4a3]120 while (file->good()) {
121 std::getline(*file, line, '\n');
[23fd43]122 // we only parse in the first ATOMDATA line
123 if (usedFields_load.empty()) {
[b8d4a3]124 location = line.find("ATOMDATA", 0);
125 if (location != string::npos) {
[23fd43]126 parseAtomDataKeysLine(line, location + 8, usedFields_load);
[b8d4a3]127 }
128 }
129 if (line.length() > 0 && line.at(0) != '#') {
[dc1d9e]130 readAtomDataLine(line, newmol);
[b8d4a3]131 }
132 }
[23fd43]133 LOG(3, "DEBUG: Local usedFields is: " << usedFields_load);
[2e352f]134
[9f8b01]135 // refresh atom::nr and atom::name
136 std::vector<atomId_t> atoms(newmol->getAtomCount());
137 std::transform(newmol->begin(), newmol->end(), atoms.begin(),
138 boost::bind(&atom::getId, _1));
139 processNeighborInformation(atoms);
[b8d4a3]140 adaptImprData();
141 adaptTorsion();
[23fd43]142
143 // append usedFields to global usedFields, is made unique on save, clear after use
144 usedFields_save.insert(usedFields_save.end(), usedFields_load.begin(), usedFields_load.end());
145 usedFields_load.clear();
[b8d4a3]146}
147
148/**
[73916f]149 * Saves the \a atoms into as a tremolo file.
[b8d4a3]150 *
151 * \param file where to save the state
[73916f]152 * \param atoms atoms to store
[b8d4a3]153 */
[23fd43]154void FormatParser< tremolo >::save(std::ostream* file, const std::vector<atom *> &AtomList) {
[47d041]155 LOG(0, "Saving changes to tremolo.");
[e97a44]156
[23fd43]157 // install default usedFields if empty so far
158 if (usedFields_save.empty()) {
159 // default behavior: use all possible keys on output
160 for (std::map<std::string, TremoloKey::atomDataKey>::iterator iter = knownKeys.begin();
161 iter != knownKeys.end(); ++iter)
162 if (iter->second != TremoloKey::noKey) // don't add noKey
163 usedFields_save.push_back(iter->first);
164 }
165 // make present usedFields_save unique
166 makeUsedFieldsUnique(usedFields_save);
167 LOG(1, "DEBUG: Global (with unique entries) usedFields_save is: " << usedFields_save);
168
169 // distribute ids continuously
170 distributeContinuousIds(AtomList);
171
172 // store atomdata
173 save_AtomDataLine(file);
174
175 // store box
176 save_BoxLine(file);
[b8d4a3]177
[23fd43]178 // store particles
179 for (std::vector<atom*>::const_iterator atomIt = AtomList.begin();
180 atomIt != AtomList.end(); ++atomIt)
181 saveLine(file, *atomIt);
182}
[acd638]183
[23fd43]184/** Helper function to make \given fields unique while preserving the order of first appearance.
185 *
186 * As std::unique only removes element if equal to predecessor, a vector is only
187 * made unique if sorted beforehand. But sorting would destroy order of first
188 * appearance, hence we do the sorting on a temporary field and add the unique
189 * elements in the order as in \a fields.
190 *
191 * @param fields usedFields to make unique while preserving order of appearance
192 */
193void FormatParser< tremolo >::makeUsedFieldsUnique(usedFields_t &fields)
194{
195 // std::unique only removes if predecessor is equal, not over whole range, hence do it manually
196 usedFields_t temp_fields(usedFields_save);
197 std::sort(temp_fields.begin(), temp_fields.end());
198 usedFields_t::iterator it =
199 std::unique(temp_fields.begin(), temp_fields.end()); // skips all duplicates in the vector
200 temp_fields.erase(it, temp_fields.end());
201 usedFields_t usedfields(usedFields_save);
202 usedFields_save.clear();
203 usedFields_save.reserve(temp_fields.size());
204 // now go through each usedFields entry, check if in temp_fields and remove there on first occurence
205 for (usedFields_t::const_iterator iter = usedfields.begin();
206 iter != usedfields.end(); ++iter) {
207 usedFields_t::iterator uniqueiter =
208 std::find(temp_fields.begin(), temp_fields.end(), *iter);
209 if (uniqueiter != temp_fields.end()) {
210 usedFields_save.push_back(*iter);
211 // add only once to ATOMDATA
212 temp_fields.erase(uniqueiter);
213 }
214 }
215 ASSERT( temp_fields.empty(),
216 "FormatParser< tremolo >::save() - still unique entries left in temp_fields after unique?");
217}
218
219
220/** Resets and distributes the indices continuously.
221 *
222 * \param atoms atoms to store
223 */
224void FormatParser< tremolo >::distributeContinuousIds(const std::vector<atom *> &AtomList)
225{
[812155]226 resetIdAssociations();
227 atomId_t lastid = 0;
[23fd43]228 for (std::vector<atom*>::const_iterator atomIt = AtomList.begin();
229 atomIt != AtomList.end(); ++atomIt)
[812155]230 associateLocaltoGlobalId(++lastid, (*atomIt)->getId());
[23fd43]231}
[812155]232
[23fd43]233/** Store Atomdata line to \a file.
234 *
235 * @param file output stream
236 */
237void FormatParser< tremolo >::save_AtomDataLine(std::ostream* file) const
238{
[b8d4a3]239 *file << "# ATOMDATA";
[23fd43]240 for (usedFields_t::const_iterator it=usedFields_save.begin();
241 it != usedFields_save.end(); ++it)
[b8d4a3]242 *file << "\t" << *it;
[23fd43]243 *file << std::endl;
244}
[ccb487]245
[23fd43]246/** Store Box info to \a file
247 *
248 * @param file output stream
249 */
250void FormatParser< tremolo >::save_BoxLine(std::ostream* file) const
251{
[ccb487]252 *file << "# Box";
253 const RealSpaceMatrix &M = World::getInstance().getDomain().getM();
254 for (size_t i=0; i<NDIM;++i)
255 for (size_t j=0; j<NDIM;++j)
256 *file << "\t" << M.at(i,j);
257 *file << std::endl;
[b8d4a3]258}
259
[6bc86c]260/** Add default info, when new atom is added to World.
261 *
262 * @param id of atom
263 */
[765f16]264void FormatParser< tremolo >::AtomInserted(atomId_t id)
[6bc86c]265{
[8bf9c6]266 std::map<const atomId_t, TremoloAtomInfoContainer>::iterator iter = additionalAtomData.find(id);
[6bc86c]267 ASSERT(iter == additionalAtomData.end(),
[765f16]268 "FormatParser< tremolo >::AtomInserted() - additionalAtomData already present for newly added atom "
[6bc86c]269 +toString(id)+".");
270 // don't add entry, as this gives a default resSeq of 0 not the molecule id
271 // additionalAtomData.insert( std::make_pair(id, TremoloAtomInfoContainer()) );
272}
273
274/** Remove additional AtomData info, when atom has been removed from World.
275 *
276 * @param id of atom
277 */
[765f16]278void FormatParser< tremolo >::AtomRemoved(atomId_t id)
[6bc86c]279{
[8bf9c6]280 std::map<const atomId_t, TremoloAtomInfoContainer>::iterator iter = additionalAtomData.find(id);
[6bc86c]281 // as we do not insert AtomData on AtomInserted, we cannot be assured of its presence
282// ASSERT(iter != additionalAtomData.end(),
[765f16]283// "FormatParser< tremolo >::AtomRemoved() - additionalAtomData is not present for atom "
[6bc86c]284// +toString(id)+" to remove.");
285 if (iter != additionalAtomData.end())
286 additionalAtomData.erase(iter);
287}
288
[b8d4a3]289/**
290 * Writes one line of tremolo-formatted data to the provided stream.
291 *
292 * \param stream where to write the line to
293 * \param reference to the atom of which information should be written
294 */
[23fd43]295void FormatParser< tremolo >::saveLine(std::ostream* file, const atom* currentAtom)
296{
[b8d4a3]297 TremoloKey::atomDataKey currentField;
298
[47d041]299 LOG(4, "INFO: Saving atom " << *currentAtom << ", its father id is " << currentAtom->GetTrueFather()->getId());
[4d4d33]300
[23fd43]301 for (usedFields_t::iterator it = usedFields_save.begin(); it != usedFields_save.end(); it++) {
[b8d4a3]302 currentField = knownKeys[it->substr(0, it->find("="))];
303 switch (currentField) {
304 case TremoloKey::x :
305 // for the moment, assume there are always three dimensions
[47d041]306 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getPosition());
[d74077]307 *file << currentAtom->at(0) << "\t";
308 *file << currentAtom->at(1) << "\t";
309 *file << currentAtom->at(2) << "\t";
[b8d4a3]310 break;
311 case TremoloKey::u :
312 // for the moment, assume there are always three dimensions
[47d041]313 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getAtomicVelocity());
[bce72c]314 *file << currentAtom->getAtomicVelocity()[0] << "\t";
315 *file << currentAtom->getAtomicVelocity()[1] << "\t";
316 *file << currentAtom->getAtomicVelocity()[2] << "\t";
[b8d4a3]317 break;
[305e7e]318 case TremoloKey::type :
[acd638]319 if (additionalAtomData.count(currentAtom->getId())) {
320 if (additionalAtomData[currentAtom->getId()].get(currentField) != "-") {
[47d041]321 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << additionalAtomData[currentAtom->getId()].get(currentField));
[acd638]322 *file << additionalAtomData[currentAtom->getId()].get(currentField) << "\t";
323 } else {
[47d041]324 LOG(3, "Writing for type " << knownKeyNames[currentField] << " default value: " << currentAtom->getType()->getSymbol());
[acd638]325 *file << currentAtom->getType()->getSymbol() << "\t";
326 }
327 } else if (additionalAtomData.count(currentAtom->GetTrueFather()->getId())) {
328 if (additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField) != "-") {
[47d041]329 LOG(3, "Writing for type " << knownKeyNames[currentField] << " stuff from father: " << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField));
[acd638]330 *file << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField) << "\t";
331 } else {
[47d041]332 LOG(3, "Writing for type " << knownKeyNames[currentField] << " default value from father: " << currentAtom->GetTrueFather()->getType()->getSymbol());
[acd638]333 *file << currentAtom->GetTrueFather()->getType()->getSymbol() << "\t";
334 }
[4d4d33]335 } else {
[47d041]336 LOG(3, "Writing for type " << knownKeyNames[currentField] << " its default value: " << currentAtom->getType()->getSymbol());
[acd638]337 *file << currentAtom->getType()->getSymbol() << "\t";
[4d4d33]338 }
[b8d4a3]339 break;
340 case TremoloKey::Id :
[47d041]341 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getId()+1);
[812155]342 *file << getLocalId(currentAtom->getId()) << "\t";
[b8d4a3]343 break;
344 case TremoloKey::neighbors :
[47d041]345 LOG(3, "Writing type " << knownKeyNames[currentField]);
[b8d4a3]346 writeNeighbors(file, atoi(it->substr(it->find("=") + 1, 1).c_str()), currentAtom);
347 break;
[74a444]348 case TremoloKey::resSeq :
[4d4d33]349 if (additionalAtomData.count(currentAtom->getId())) {
[47d041]350 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << additionalAtomData[currentAtom->getId()].get(currentField));
[74a444]351 *file << additionalAtomData[currentAtom->getId()].get(currentField);
352 } else if (currentAtom->getMolecule() != NULL) {
[47d041]353 LOG(3, "Writing for type " << knownKeyNames[currentField] << " its own id: " << currentAtom->getMolecule()->getId()+1);
[74a444]354 *file << setw(4) << currentAtom->getMolecule()->getId()+1;
355 } else {
[47d041]356 LOG(3, "Writing for type " << knownKeyNames[currentField] << " default value: " << defaultAdditionalData.get(currentField));
[74a444]357 *file << defaultAdditionalData.get(currentField);
358 }
359 *file << "\t";
[4d4d33]360 break;
[2034f3]361 case TremoloKey::charge :
362 if (currentAtom->getCharge() == 0.) {
363 if (additionalAtomData.count(currentAtom->getId())) {
364 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << additionalAtomData[currentAtom->getId()].get(currentField));
365 *file << additionalAtomData[currentAtom->getId()].get(currentField);
366 } else if (additionalAtomData.count(currentAtom->GetTrueFather()->getId())) {
367 LOG(3, "Writing for type " << knownKeyNames[currentField] << " stuff from father: " << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField));
368 *file << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField);
369 } else {
370 LOG(3, "Writing for type " << knownKeyNames[currentField] << " AtomInfo::charge : " << currentAtom->getCharge());
371 *file << currentAtom->getCharge();
372 }
373 } else {
374 LOG(3, "Writing for type " << knownKeyNames[currentField] << " AtomInfo::charge : " << currentAtom->getCharge());
375 *file << currentAtom->getCharge();
376 }
377 *file << "\t";
378 break;
[b8d4a3]379 default :
[4d4d33]380 if (additionalAtomData.count(currentAtom->getId())) {
[47d041]381 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << additionalAtomData[currentAtom->getId()].get(currentField));
[74a444]382 *file << additionalAtomData[currentAtom->getId()].get(currentField);
[4d4d33]383 } else if (additionalAtomData.count(currentAtom->GetTrueFather()->getId())) {
[47d041]384 LOG(3, "Writing for type " << knownKeyNames[currentField] << " stuff from father: " << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField));
[74a444]385 *file << additionalAtomData[currentAtom->GetTrueFather()->getId()].get(currentField);
386 } else {
[47d041]387 LOG(3, "Writing for type " << knownKeyNames[currentField] << " the default: " << defaultAdditionalData.get(currentField));
[74a444]388 *file << defaultAdditionalData.get(currentField);
389 }
[b8d4a3]390 *file << "\t";
391 break;
392 }
393 }
394
[23fd43]395 *file << std::endl;
[b8d4a3]396}
397
398/**
399 * Writes the neighbor information of one atom to the provided stream.
400 *
[9d83b6]401 * Note that ListOfBonds of WorldTime::CurrentTime is used.
402 *
[b8d4a3]403 * \param stream where to write neighbor information to
404 * \param number of neighbors
405 * \param reference to the atom of which to take the neighbor information
406 */
[23fd43]407void FormatParser< tremolo >::writeNeighbors(std::ostream* file, const int numberOfNeighbors, const atom* currentAtom) {
[9d83b6]408 const BondList& ListOfBonds = currentAtom->getListOfBonds();
[ca2cfa]409 // sort bonded indices
410 typedef std::set<atomId_t> sortedIndices;
411 sortedIndices sortedBonds;
412 for (BondList::const_iterator iter = ListOfBonds.begin();
413 iter != ListOfBonds.end(); ++iter)
[812155]414 sortedBonds.insert(getLocalId((*iter)->GetOtherAtom(currentAtom)->getId()));
[ca2cfa]415 // print indices
416 sortedIndices::const_iterator currentBond = sortedBonds.begin();
[b8d4a3]417 for (int i = 0; i < numberOfNeighbors; i++) {
[812155]418 *file << (currentBond != sortedBonds.end() ? (*currentBond) : 0) << "\t";
[ca2cfa]419 if (currentBond != sortedBonds.end())
[0bbfa1]420 ++currentBond;
[b8d4a3]421 }
[9131f3]422}
423
424/**
[23fd43]425 * Stores keys from the ATOMDATA line in \a fields.
[9131f3]426 *
427 * \param line to parse the keys from
[23fd43]428 * \param offset with which offset the keys begin within the line
429 * \param fields which usedFields to use
[9131f3]430 */
[23fd43]431void FormatParser< tremolo >::parseAtomDataKeysLine(
432 const std::string &line,
433 const int offset,
434 usedFields_t &fields) {
[8bf9c6]435 std::string keyword;
436 std::stringstream lineStream;
[9131f3]437
438 lineStream << line.substr(offset);
439 while (lineStream.good()) {
440 lineStream >> keyword;
[b8d4a3]441 if (knownKeys[keyword.substr(0, keyword.find("="))] == TremoloKey::noKey) {
[ecb799]442 // TODO: throw exception about unknown key
[4415da]443 cout << "Unknown key: " << keyword << " is not part of the tremolo format specification." << endl;
444 break;
445 }
[23fd43]446 fields.push_back(keyword);
[9131f3]447 }
[23fd43]448 //LOG(1, "INFO: " << fields);
[9131f3]449}
450
[81c980b]451/** Sets the properties per atom to print to .data file by parsing line from
452 * \a atomdata_string.
453 *
[23fd43]454 * We just call \sa FormatParser< tremolo >::parseAtomDataKeysLine(), however
455 * we clear FormatParser< tremolo >::usedFields_save.
[81c980b]456 *
457 * @param atomdata_string line to parse with space-separated values
458 */
[765f16]459void FormatParser< tremolo >::setAtomData(const std::string &atomdata_string)
[81c980b]460{
[23fd43]461 usedFields_save.clear();
462 parseAtomDataKeysLine(atomdata_string, 0, usedFields_save);
[81c980b]463}
464
465
[9131f3]466/**
467 * Reads one data line of a tremolo file and interprets it according to the keys
468 * obtained from the ATOMDATA line.
469 *
470 * \param line to parse as an atom
[dc1d9e]471 * \param *newmol molecule to add atom to
[9131f3]472 */
[23fd43]473void FormatParser< tremolo >::readAtomDataLine(const std::string &line, molecule *newmol = NULL) {
[8bf9c6]474 std::stringstream lineStream;
[4415da]475 atom* newAtom = World::getInstance().createAtom();
[89a31d]476 const atomId_t atomid = newAtom->getId();
477 additionalAtomData[atomid] = TremoloAtomInfoContainer(); // fill with default values
478 TremoloAtomInfoContainer *atomInfo = &additionalAtomData[atomid];
[b8d4a3]479 TremoloKey::atomDataKey currentField;
[72d108]480 ConvertTo<double> toDouble;
481 ConvertTo<int> toInt;
[056e70]482 Vector tempVector;
[72d108]483
484 // setup tokenizer, splitting up white-spaced entries
485 typedef boost::tokenizer<boost::char_separator<char> >
486 tokenizer;
487 boost::char_separator<char> whitespacesep(" \t");
488 tokenizer tokens(line, whitespacesep);
489 ASSERT(tokens.begin() != tokens.end(),
[765f16]490 "FormatParser< tremolo >::readAtomDataLine - empty string, need at least ' '!");
[72d108]491 tokenizer::iterator tok_iter = tokens.begin();
492 // then associate each token to each file
[23fd43]493 for (usedFields_t::const_iterator it = usedFields_load.begin(); it < usedFields_load.end(); it++) {
[72d108]494 const std::string keyName = it->substr(0, it->find("="));
495 currentField = knownKeys[keyName];
[8bf9c6]496 const std::string word = *tok_iter;
[47d041]497 LOG(4, "INFO: Parsing key " << keyName << " with remaining data " << word);
[4415da]498 switch (currentField) {
[b8d4a3]499 case TremoloKey::x :
[4415da]500 // for the moment, assume there are always three dimensions
[d74077]501 for (int i=0;i<NDIM;i++) {
[765f16]502 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for x["+toString(i)+"]!");
[47d041]503 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
[72d108]504 newAtom->set(i, toDouble(*tok_iter));
505 tok_iter++;
[d74077]506 }
[4415da]507 break;
[b8d4a3]508 case TremoloKey::u :
[4415da]509 // for the moment, assume there are always three dimensions
[72d108]510 for (int i=0;i<NDIM;i++) {
[765f16]511 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for u["+toString(i)+"]!");
[47d041]512 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
[056e70]513 tempVector[i] = toDouble(*tok_iter);
[72d108]514 tok_iter++;
515 }
[056e70]516 newAtom->setAtomicVelocity(tempVector);
[4415da]517 break;
[305e7e]518 case TremoloKey::type :
[4d4d33]519 {
[765f16]520 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
[47d041]521 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
[a275b3]522 std::string element;
523 try {
524 element = knownTypes.getType(*tok_iter);
525 } catch(IllegalParserKeyException) {
526 // clean up
527 World::getInstance().destroyAtom(newAtom);
528 // give an error
529 ELOG(0, "TremoloParser: I do not understand the element token " << *tok_iter << ".");
530 }
[4d4d33]531 // put type name into container for later use
532 atomInfo->set(currentField, *tok_iter);
[47d041]533 LOG(4, "INFO: Parsing element " << (*tok_iter) << " as " << element << " according to KnownTypes.");
[72d108]534 tok_iter++;
[4d4d33]535 newAtom->setType(World::getInstance().getPeriode()->FindElement(element));
[b8d4a3]536 ASSERT(newAtom->getType(), "Type was not set for this atom");
[4415da]537 break;
[4d4d33]538 }
[b8d4a3]539 case TremoloKey::Id :
[765f16]540 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
[47d041]541 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
[c0e28c]542 associateLocaltoGlobalId(toInt(*tok_iter), atomid);
[72d108]543 tok_iter++;
[4415da]544 break;
[b8d4a3]545 case TremoloKey::neighbors :
[72d108]546 for (int i=0;i<atoi(it->substr(it->find("=") + 1, 1).c_str());i++) {
[765f16]547 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
[47d041]548 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
[72d108]549 lineStream << *tok_iter << "\t";
550 tok_iter++;
551 }
[b8d4a3]552 readNeighbors(&lineStream,
[89a31d]553 atoi(it->substr(it->find("=") + 1, 1).c_str()), atomid);
[9131f3]554 break;
[2034f3]555 case TremoloKey::charge :
556 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
557 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
558 atomInfo->set(currentField, *tok_iter);
559 newAtom->setCharge(boost::lexical_cast<double>(*tok_iter));
560 tok_iter++;
561 break;
[9131f3]562 default :
[765f16]563 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
[47d041]564 LOG(4, "INFO: Parsing key " << keyName << " with next token " << *tok_iter);
[72d108]565 atomInfo->set(currentField, *tok_iter);
566 tok_iter++;
[9131f3]567 break;
568 }
569 }
[89a31d]570 LOG(3, "INFO: Parsed atom " << atomid << ".");
571 if (newmol != NULL)
[dc1d9e]572 newmol->AddAtom(newAtom);
[6bc51d]573}
[9131f3]574
[531f27]575bool FormatParser< tremolo >::saveAtomsInExttypes(std::ostream &output, const std::vector<atom*> &atoms, const int id) const
576{
577 bool status = true;
578 // parse the file
579 for (std::vector<atom *>::const_iterator iter = atoms.begin();
580 iter != atoms.end(); ++iter) {
581 const int atomicid = getLocalId((*iter)->getId());
582 if (atomicid == -1)
583 status = false;
584 output << atomicid << "\t" << id << std::endl;
585 }
586
587 return status;
588}
589
[b8d4a3]590/**
591 * Reads neighbor information for one atom from the input.
592 *
[0bbfa1]593 * \param line stream where to read the information from
594 * \param numberOfNeighbors number of neighbors to read
595 * \param atomid world id of the atom the information belongs to
[b8d4a3]596 */
[23fd43]597void FormatParser< tremolo >::readNeighbors(std::stringstream* line, const int numberOfNeighbors, const int atomId) {
[b8d4a3]598 int neighborId = 0;
599 for (int i = 0; i < numberOfNeighbors; i++) {
600 *line >> neighborId;
601 // 0 is used to fill empty neighbor positions in the tremolo file.
602 if (neighborId > 0) {
[47d041]603 LOG(4, "INFO: Atom with global id " << atomId
604 << " has neighbour with serial " << neighborId);
[b8d4a3]605 additionalAtomData[atomId].neighbors.push_back(neighborId);
606 }
607 }
608}
[9131f3]609
610/**
[23fd43]611 * Checks whether the provided name is within \a fields.
[b8d4a3]612 *
[23fd43]613 * \param fields which usedFields to use
614 * \param fieldName name to check
[b8d4a3]615 * \return true if the field name is used
[9131f3]616 */
[23fd43]617bool FormatParser< tremolo >::isUsedField(const usedFields_t &fields, const std::string &fieldName) const
618{
[b8d4a3]619 bool fieldNameExists = false;
[23fd43]620 for (usedFields_t::const_iterator usedField = fields.begin();
621 usedField != fields.end(); usedField++) {
[b8d4a3]622 if (usedField->substr(0, usedField->find("=")) == fieldName)
623 fieldNameExists = true;
624 }
[9131f3]625
[b8d4a3]626 return fieldNameExists;
627}
628
629
630/**
631 * Adds the collected neighbor information to the atoms in the world. The atoms
632 * are found by their current ID and mapped to the corresponding atoms with the
633 * Id found in the parsed file.
[9f8b01]634 *
635 * @param atoms vector with all newly added (global) atomic ids
[b8d4a3]636 */
[9f8b01]637void FormatParser< tremolo >::processNeighborInformation(const std::vector<atomId_t> &atoms) {
[23fd43]638 if (!isUsedField(usedFields_load, "neighbors")) {
[b8d4a3]639 return;
640 }
641
[9f8b01]642 for (std::vector<atomId_t>::const_iterator iter = atoms.begin(); iter != atoms.end(); ++iter) {
643 ASSERT(additionalAtomData.count(*iter) != 0,
644 "FormatParser< tremolo >::processNeighborInformation() - global id "
645 +toString(*iter)+" unknown in additionalAtomData.");
646 TremoloAtomInfoContainer &currentInfo = additionalAtomData[*iter];
647 ASSERT (!currentInfo.neighbors_processed,
648 "FormatParser< tremolo >::processNeighborInformation() - neighbors of new atom "
649 +toString(*iter)+" are already processed.");
650 for(std::vector<int>::const_iterator neighbor = currentInfo.neighbors.begin();
651 neighbor != currentInfo.neighbors.end(); neighbor++
652 ) {
653 LOG(3, "INFO: Creating bond between ("
654 << *iter
655 << ") and ("
656 << getGlobalId(*neighbor) << "|" << *neighbor << ")");
657 ASSERT(getGlobalId(*neighbor) != -1,
658 "FormatParser< tremolo >::processNeighborInformation() - global id to local id "
659 +toString(*neighbor)+" is unknown.");
660 World::getInstance().getAtom(AtomById(*iter))
661 ->addBond(WorldTime::getTime(), World::getInstance().getAtom(AtomById(getGlobalId(*neighbor))));
[9131f3]662 }
[9f8b01]663 currentInfo.neighbors_processed = true;
[9131f3]664 }
[6bc51d]665}
666
[9131f3]667/**
[b8d4a3]668 * Replaces atom IDs read from the file by the corresponding world IDs. All IDs
669 * IDs of the input string will be replaced; expected separating characters are
670 * "-" and ",".
[9131f3]671 *
[b8d4a3]672 * \param string in which atom IDs should be adapted
673 *
674 * \return input string with modified atom IDs
[9131f3]675 */
[955b91]676std::string FormatParser< tremolo >::adaptIdDependentDataString(std::string data) {
[b8d4a3]677 // there might be no IDs
678 if (data == "-") {
679 return "-";
680 }
681
682 char separator;
683 int id;
[8bf9c6]684 std::stringstream line, result;
[b8d4a3]685 line << data;
686
687 line >> id;
[c0e28c]688 result << getGlobalId(id);
[b8d4a3]689 while (line.good()) {
690 line >> separator >> id;
[c0e28c]691 result << separator << getGlobalId(id);
[b8d4a3]692 }
693
694 return result.str();
[6bc51d]695}
[b8d4a3]696
697/**
698 * Corrects the atom IDs in each imprData entry to the corresponding world IDs
699 * as they might differ from the originally read IDs.
700 */
[765f16]701void FormatParser< tremolo >::adaptImprData() {
[23fd43]702 if (!isUsedField(usedFields_load, "imprData")) {
[b8d4a3]703 return;
704 }
705
[8bf9c6]706 for(std::map<const atomId_t, TremoloAtomInfoContainer>::iterator currentInfo = additionalAtomData.begin();
[b8d4a3]707 currentInfo != additionalAtomData.end(); currentInfo++
708 ) {
709 currentInfo->second.imprData = adaptIdDependentDataString(currentInfo->second.imprData);
710 }
[6bc51d]711}
[4415da]712
[b8d4a3]713/**
714 * Corrects the atom IDs in each torsion entry to the corresponding world IDs
715 * as they might differ from the originally read IDs.
716 */
[765f16]717void FormatParser< tremolo >::adaptTorsion() {
[23fd43]718 if (!isUsedField(usedFields_load, "torsion")) {
[b8d4a3]719 return;
720 }
721
[8bf9c6]722 for(std::map<const atomId_t, TremoloAtomInfoContainer>::iterator currentInfo = additionalAtomData.begin();
[b8d4a3]723 currentInfo != additionalAtomData.end(); currentInfo++
724 ) {
725 currentInfo->second.torsion = adaptIdDependentDataString(currentInfo->second.torsion);
726 }
727}
728
Note: See TracBrowser for help on using the repository browser.