source: src/Parser/TremoloParser.cpp@ 53ef0d4

Action_Thermostats Add_AtomRandomPerturbation Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_ChronosMutex Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion GeometryObjects Gui_displays_atomic_force_velocity IndependentFragmentGrids_IntegrationTest JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks RotateToPrincipalAxisSystem_UndoRedo StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since 53ef0d4 was ed8a68, checked in by Frederik Heber <heber@…>, 9 years ago

Removed TremoloParser's ElementKeys, superceded by ParticleRegistry.

  • Property mode set to 100644
File size: 36.5 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.
[5aaa43]5 * Copyright (C) 2013 Frederik Heber. All rights reserved.
[94d5ac6]6 *
7 *
8 * This file is part of MoleCuilder.
9 *
10 * MoleCuilder is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * MoleCuilder is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
[bcf653]22 */
23
[6bc51d]24/*
25 * TremoloParser.cpp
26 *
27 * Created on: Mar 2, 2010
28 * Author: metzler
29 */
30
[bf3817]31// include config.h
32#ifdef HAVE_CONFIG_H
33#include <config.h>
34#endif
35
[ad011c]36#include "CodePatterns/MemDebug.hpp"
[112b09]37
[ad011c]38#include "CodePatterns/Assert.hpp"
39#include "CodePatterns/Log.hpp"
[4d4d33]40#include "CodePatterns/toString.hpp"
[ad011c]41#include "CodePatterns/Verbose.hpp"
[42127c]42
[9131f3]43#include "TremoloParser.hpp"
[42127c]44
[6f0841]45#include "Atom/atom.hpp"
[129204]46#include "Bond/bond.hpp"
[ccb487]47#include "Box.hpp"
[42127c]48#include "Descriptors/AtomIdDescriptor.hpp"
[3bdb6d]49#include "Element/element.hpp"
50#include "Element/periodentafel.hpp"
[ed8a68]51#include "Parser/Exceptions.hpp"
52#include "Potentials/Particles/ParticleRegistry.hpp"
[ccb487]53#include "LinearAlgebra/RealSpaceMatrix.hpp"
[740f9f]54#include "Potentials/Particles/ParticleRegistry.hpp"
[42127c]55#include "molecule.hpp"
56#include "World.hpp"
57#include "WorldTime.hpp"
58
[9131f3]59
[9f8b01]60#include <algorithm>
[05e2ed]61#include <boost/bind.hpp>
[4795cd]62#include <boost/function.hpp>
[ca331c]63#include <boost/lambda/lambda.hpp>
[2034f3]64#include <boost/lexical_cast.hpp>
[72d108]65#include <boost/tokenizer.hpp>
[74a444]66#include <iostream>
67#include <iomanip>
[8bf9c6]68#include <map>
69#include <sstream>
[ca331c]70#include <string>
[8bf9c6]71#include <vector>
[9131f3]72
[5a667d]73#include <boost/assign/list_of.hpp> // for 'map_list_of()'
74#include <boost/assert.hpp>
75
[765f16]76// declare specialized static variables
77const std::string FormatParserTrait<tremolo>::name = "tremolo";
78const std::string FormatParserTrait<tremolo>::suffix = "data";
79const ParserTypes FormatParserTrait<tremolo>::type = tremolo;
80
[5a667d]81// static instances
82std::map<std::string, TremoloKey::atomDataKey> FormatParser<tremolo>::knownKeys =
83 boost::assign::map_list_of("x",TremoloKey::x)
84 ("u",TremoloKey::u)
85 ("F",TremoloKey::F)
86 ("stress",TremoloKey::stress)
87 ("Id",TremoloKey::Id)
88 ("neighbors",TremoloKey::neighbors)
89 ("imprData",TremoloKey::imprData)
90 ("GroupMeasureTypeNo",TremoloKey::GroupMeasureTypeNo)
91 ("type",TremoloKey::type)
92 ("extType",TremoloKey::extType)
93 ("name",TremoloKey::name)
94 ("resName",TremoloKey::resName)
95 ("chainID",TremoloKey::chainID)
96 ("resSeq",TremoloKey::resSeq)
97 ("occupancy",TremoloKey::occupancy)
98 ("tempFactor",TremoloKey::tempFactor)
99 ("segID",TremoloKey::segID)
100 ("Charge",TremoloKey::Charge)
101 ("charge",TremoloKey::charge)
102 ("GrpTypeNo",TremoloKey::GrpTypeNo)
103 ("torsion",TremoloKey::torsion)
104 (" ",TremoloKey::noKey); // with this we can detect invalid keys
105
[9131f3]106/**
107 * Constructor.
108 */
[765f16]109FormatParser< tremolo >::FormatParser() :
[05e2ed]110 FormatParser_common(NULL),
111 idglobalizer(boost::bind(&FormatParser< tremolo >::getGlobalId, this, _1)),
112 idlocalizer(boost::bind(&FormatParser< tremolo >::getLocalId, this, _1))
[765f16]113{
[4d4d33]114 // invert knownKeys for debug output
115 for (std::map<std::string, TremoloKey::atomDataKey>::iterator iter = knownKeys.begin(); iter != knownKeys.end(); ++iter)
116 knownKeyNames.insert( make_pair( iter->second, iter->first) );
117
118 additionalAtomData.clear();
[9131f3]119}
120
[5a667d]121
[9131f3]122/**
123 * Destructor.
124 */
[765f16]125FormatParser< tremolo >::~FormatParser()
126{
[23fd43]127 usedFields_save.clear();
[b8d4a3]128 additionalAtomData.clear();
129}
130
131/**
132 * Loads atoms from a tremolo-formatted file.
133 *
134 * \param tremolo file
135 */
[765f16]136void FormatParser< tremolo >::load(istream* file) {
[8bf9c6]137 std::string line;
138 std::string::size_type location;
[b8d4a3]139
[c0e28c]140 // reset the id maps
141 resetIdAssociations();
142
[dc1d9e]143 molecule *newmol = World::getInstance().createMolecule();
[bd2390]144 newmol->ActiveFlag = true;
[b8d4a3]145 while (file->good()) {
146 std::getline(*file, line, '\n');
[23fd43]147 // we only parse in the first ATOMDATA line
148 if (usedFields_load.empty()) {
[b8d4a3]149 location = line.find("ATOMDATA", 0);
150 if (location != string::npos) {
[23fd43]151 parseAtomDataKeysLine(line, location + 8, usedFields_load);
[b8d4a3]152 }
153 }
154 if (line.length() > 0 && line.at(0) != '#') {
[dc1d9e]155 readAtomDataLine(line, newmol);
[b8d4a3]156 }
157 }
[23fd43]158 LOG(3, "DEBUG: Local usedFields is: " << usedFields_load);
[2e352f]159
[9f8b01]160 // refresh atom::nr and atom::name
161 std::vector<atomId_t> atoms(newmol->getAtomCount());
162 std::transform(newmol->begin(), newmol->end(), atoms.begin(),
163 boost::bind(&atom::getId, _1));
164 processNeighborInformation(atoms);
[05e2ed]165 adaptImprData(atoms);
166 adaptTorsion(atoms);
[23fd43]167
168 // append usedFields to global usedFields, is made unique on save, clear after use
169 usedFields_save.insert(usedFields_save.end(), usedFields_load.begin(), usedFields_load.end());
170 usedFields_load.clear();
[b8d4a3]171}
172
173/**
[73916f]174 * Saves the \a atoms into as a tremolo file.
[b8d4a3]175 *
176 * \param file where to save the state
[73916f]177 * \param atoms atoms to store
[b8d4a3]178 */
[fac58f]179void FormatParser< tremolo >::save(
180 std::ostream* file,
181 const std::vector<const atom *> &AtomList) {
[830b3e]182 LOG(2, "DEBUG: Saving changes to tremolo.");
[e97a44]183
[23fd43]184 // install default usedFields if empty so far
185 if (usedFields_save.empty()) {
186 // default behavior: use all possible keys on output
187 for (std::map<std::string, TremoloKey::atomDataKey>::iterator iter = knownKeys.begin();
188 iter != knownKeys.end(); ++iter)
189 if (iter->second != TremoloKey::noKey) // don't add noKey
190 usedFields_save.push_back(iter->first);
191 }
192 // make present usedFields_save unique
193 makeUsedFieldsUnique(usedFields_save);
[a86cda]194 LOG(1, "INFO: Global (with unique entries) usedFields_save is: " << usedFields_save);
[23fd43]195
196 // distribute ids continuously
197 distributeContinuousIds(AtomList);
198
199 // store atomdata
200 save_AtomDataLine(file);
201
202 // store box
203 save_BoxLine(file);
[b8d4a3]204
[23fd43]205 // store particles
[fac58f]206 for (std::vector<const atom*>::const_iterator atomIt = AtomList.begin();
[23fd43]207 atomIt != AtomList.end(); ++atomIt)
208 saveLine(file, *atomIt);
209}
[acd638]210
[5b0581]211struct usedFieldsWeakComparator
212{
213 /** Special comparator regards "neighbors=4" and "neighbors=2" as equal
214 *
215 * \note This one is used for making usedFields unique, i.e. throwing out the "smaller"
216 * neighbors.
217 */
218 bool operator()(const std::string &a, const std::string &b) const
219 {
220 // only compare up to first equality sign
221 return (a.substr(0, a.find_first_of('=')) == b.substr(0, b.find_first_of('=')));
222 }
223};
224
225struct usedFieldsSpecialOrderer
226{
227 /** Special string comparator that regards "neighbors=4" < "neighbors=2" as true and
228 * the other way round as false.
229 *
230 * Here, we implement the operator "\a < \b" in a special way to allow the
231 * above.
232 *
233 * \note This one is used for sorting usedFields in preparation for making it unique.
234 */
235 bool operator()(const std::string &a, const std::string &b) const
236 {
237 // only compare up to first equality sign
238 size_t a_equality = a.find_first_of('=');
239 size_t b_equality = b.find_first_of('=');
240 // if key before equality is not equal, return whether it is smaller or not
241 if (a.substr(0, a_equality) != b.substr(0, b_equality)) {
242 return a.substr(0, a_equality) < b.substr(0, b_equality);
243 } else { // now we know that the key before equality is the same in either string
244 // if one of them has no equality, the one with equality must go before
245 if ((a_equality != std::string::npos) && (b_equality == std::string::npos))
246 return true;
247 if ((a_equality == std::string::npos) && (b_equality != std::string::npos))
248 return false;
249 // if both don't have equality (and the token before is equal), it is not "<" but "=="
250 if ((a_equality == std::string::npos) && (b_equality == std::string::npos))
251 return false;
252 // if now both have equality sign, the larger value after it, must come first
253 return a.substr(a_equality, std::string::npos) > b.substr(b_equality, std::string::npos);
254 }
255 }
256};
257
[23fd43]258/** Helper function to make \given fields unique while preserving the order of first appearance.
259 *
260 * As std::unique only removes element if equal to predecessor, a vector is only
261 * made unique if sorted beforehand. But sorting would destroy order of first
262 * appearance, hence we do the sorting on a temporary field and add the unique
263 * elements in the order as in \a fields.
264 *
265 * @param fields usedFields to make unique while preserving order of appearance
266 */
[27cfde]267void FormatParser< tremolo >::makeUsedFieldsUnique(usedFields_t &fields) const
[23fd43]268{
269 // std::unique only removes if predecessor is equal, not over whole range, hence do it manually
[27cfde]270 usedFields_t temp_fields(fields);
[5b0581]271 usedFieldsSpecialOrderer SpecialOrderer;
272 usedFieldsWeakComparator WeakComparator;
273 std::sort(temp_fields.begin(), temp_fields.end(), SpecialOrderer);
[23fd43]274 usedFields_t::iterator it =
[5b0581]275 std::unique(temp_fields.begin(), temp_fields.end(), WeakComparator);
[23fd43]276 temp_fields.erase(it, temp_fields.end());
[27cfde]277 usedFields_t usedfields(fields);
278 fields.clear();
279 fields.reserve(temp_fields.size());
[23fd43]280 // now go through each usedFields entry, check if in temp_fields and remove there on first occurence
281 for (usedFields_t::const_iterator iter = usedfields.begin();
282 iter != usedfields.end(); ++iter) {
283 usedFields_t::iterator uniqueiter =
284 std::find(temp_fields.begin(), temp_fields.end(), *iter);
285 if (uniqueiter != temp_fields.end()) {
[27cfde]286 fields.push_back(*iter);
[23fd43]287 // add only once to ATOMDATA
288 temp_fields.erase(uniqueiter);
289 }
290 }
291 ASSERT( temp_fields.empty(),
292 "FormatParser< tremolo >::save() - still unique entries left in temp_fields after unique?");
293}
294
295
296/** Resets and distributes the indices continuously.
297 *
298 * \param atoms atoms to store
299 */
[fac58f]300void FormatParser< tremolo >::distributeContinuousIds(
301 const std::vector<const atom *> &AtomList)
[23fd43]302{
[812155]303 resetIdAssociations();
304 atomId_t lastid = 0;
[fac58f]305 for (std::vector<const atom*>::const_iterator atomIt = AtomList.begin();
[23fd43]306 atomIt != AtomList.end(); ++atomIt)
[812155]307 associateLocaltoGlobalId(++lastid, (*atomIt)->getId());
[23fd43]308}
[812155]309
[23fd43]310/** Store Atomdata line to \a file.
311 *
312 * @param file output stream
313 */
314void FormatParser< tremolo >::save_AtomDataLine(std::ostream* file) const
315{
[b8d4a3]316 *file << "# ATOMDATA";
[23fd43]317 for (usedFields_t::const_iterator it=usedFields_save.begin();
318 it != usedFields_save.end(); ++it)
[b8d4a3]319 *file << "\t" << *it;
[23fd43]320 *file << std::endl;
321}
[ccb487]322
[23fd43]323/** Store Box info to \a file
324 *
325 * @param file output stream
326 */
327void FormatParser< tremolo >::save_BoxLine(std::ostream* file) const
328{
[ccb487]329 *file << "# Box";
330 const RealSpaceMatrix &M = World::getInstance().getDomain().getM();
331 for (size_t i=0; i<NDIM;++i)
332 for (size_t j=0; j<NDIM;++j)
333 *file << "\t" << M.at(i,j);
334 *file << std::endl;
[b8d4a3]335}
336
[6bc86c]337/** Add default info, when new atom is added to World.
338 *
339 * @param id of atom
340 */
[765f16]341void FormatParser< tremolo >::AtomInserted(atomId_t id)
[6bc86c]342{
[8bf9c6]343 std::map<const atomId_t, TremoloAtomInfoContainer>::iterator iter = additionalAtomData.find(id);
[6bc86c]344 ASSERT(iter == additionalAtomData.end(),
[765f16]345 "FormatParser< tremolo >::AtomInserted() - additionalAtomData already present for newly added atom "
[6bc86c]346 +toString(id)+".");
347 // don't add entry, as this gives a default resSeq of 0 not the molecule id
348 // additionalAtomData.insert( std::make_pair(id, TremoloAtomInfoContainer()) );
349}
350
351/** Remove additional AtomData info, when atom has been removed from World.
352 *
353 * @param id of atom
354 */
[765f16]355void FormatParser< tremolo >::AtomRemoved(atomId_t id)
[6bc86c]356{
[8bf9c6]357 std::map<const atomId_t, TremoloAtomInfoContainer>::iterator iter = additionalAtomData.find(id);
[6bc86c]358 // as we do not insert AtomData on AtomInserted, we cannot be assured of its presence
359// ASSERT(iter != additionalAtomData.end(),
[765f16]360// "FormatParser< tremolo >::AtomRemoved() - additionalAtomData is not present for atom "
[6bc86c]361// +toString(id)+" to remove.");
362 if (iter != additionalAtomData.end())
363 additionalAtomData.erase(iter);
364}
365
[4795cd]366template <class T>
367T NoOp(const atom * const)
368{
369 return T();
370}
371
372template <class T>
373void writeEntryFromAdditionalAtomData_ifpresent(
374 std::map<const atomId_t, TremoloAtomInfoContainer> &_additionalAtomData,
375 std::map<TremoloKey::atomDataKey, std::string> &_knownKeyNames,
376 std::ostream* _file,
377 const atom * const _currentAtom,
378 const TremoloKey::atomDataKey _currentField,
379 const typename boost::function<T (const atom * const)> _getter)
380{
381 if (_additionalAtomData.count(_currentAtom->getId())) {
382 LOG(3, "Writing for type " << _knownKeyNames[_currentField] << ": "
383 << _additionalAtomData[_currentAtom->getId()].get(_currentField));
384 *_file << _additionalAtomData[_currentAtom->getId()].get(_currentField);
385 } else if (_additionalAtomData.count(_currentAtom->GetTrueFather()->getId())) {
386 LOG(3, "Writing for type " << _knownKeyNames[_currentField] << " stuff from father: "
387 << _additionalAtomData[_currentAtom->GetTrueFather()->getId()].get(_currentField));
388 *_file << _additionalAtomData[_currentAtom->GetTrueFather()->getId()].get(_currentField);
389 } else {
390 LOG(3, "Writing for type " << _knownKeyNames[_currentField] << " its default value: "
391 << _getter(_currentAtom));
392 *_file << _getter(_currentAtom);
393 }
394 *_file << "\t";
395}
396
397template <class T>
398void writeAdditionalAtomDataEntry(
399 std::map<const atomId_t, TremoloAtomInfoContainer> &_additionalAtomData,
400 std::map<TremoloKey::atomDataKey, std::string> &_knownKeyNames,
401 TremoloAtomInfoContainer &_defaultAdditionalData,
402 std::ostream* _file,
403 const atom * const _currentAtom,
404 const TremoloKey::atomDataKey _currentField)
405{
406 if (_additionalAtomData.count(_currentAtom->getId())) {
407 LOG(3, "Writing for type " << _knownKeyNames[_currentField] << ": "
408 << _additionalAtomData[_currentAtom->getId()].get(_currentField));
409 *_file << _additionalAtomData[_currentAtom->getId()].get(_currentField);
410 } else if (_additionalAtomData.count(_currentAtom->GetTrueFather()->getId())) {
411 LOG(3, "Writing for type " << _knownKeyNames[_currentField] << " stuff from father: "
412 << _additionalAtomData[_currentAtom->GetTrueFather()->getId()].get(_currentField));
413 *_file << _additionalAtomData[_currentAtom->GetTrueFather()->getId()].get(_currentField);
414 } else {
415 LOG(3, "Writing for type " << _knownKeyNames[_currentField] << " its default value: "
416 << _defaultAdditionalData.get(_currentField));
417 *_file << _defaultAdditionalData.get(_currentField);
418 }
419 *_file << "\t";
420}
421
422template <class T>
423void writeEntryFromAdditionalAtomData_ifnotempty(
424 std::map<const atomId_t, TremoloAtomInfoContainer> &_additionalAtomData,
425 std::map<TremoloKey::atomDataKey, std::string> &_knownKeyNames,
426 TremoloAtomInfoContainer &_defaultAdditionalData,
427 std::ostream* _file,
428 const atom * const _currentAtom,
429 const TremoloKey::atomDataKey _currentField,
430 const typename boost::function<T (const atom * const)> _getter)
431{
432 if (_additionalAtomData.count(_currentAtom->getId())) {
433 if (_additionalAtomData[_currentAtom->getId()].get(_currentField) != "-") {
434 LOG(3, "Writing for type " << _knownKeyNames[_currentField] << ": "
435 << _additionalAtomData[_currentAtom->getId()].get(_currentField));
436 *_file << _additionalAtomData[_currentAtom->getId()].get(_currentField);
437 } else {
438 LOG(3, "Writing for type " << _knownKeyNames[_currentField] << " default value: "
439 << _getter(_currentAtom));
440 *_file << _getter(_currentAtom);
441 }
442 } else if (_additionalAtomData.count(_currentAtom->GetTrueFather()->getId())) {
443 if (_additionalAtomData[_currentAtom->GetTrueFather()->getId()].get(_currentField) != "-") {
444 LOG(3, "Writing for type " << _knownKeyNames[_currentField] << " stuff from father: "
445 << _additionalAtomData[_currentAtom->GetTrueFather()->getId()].get(_currentField));
446 *_file << _additionalAtomData[_currentAtom->GetTrueFather()->getId()].get(_currentField);
447 } else {
448 LOG(3, "Writing for type " << _knownKeyNames[_currentField] << " default value from father: "
449 << _getter(_currentAtom->GetTrueFather()));
450 *_file << _getter(_currentAtom->GetTrueFather());
451 }
452 } else {
453 LOG(3, "Writing for type " << _knownKeyNames[_currentField] << " its default value: "
454 << _getter(_currentAtom));
455 *_file << _getter(_currentAtom);
456 }
457 *_file << "\t";
458}
459
[b8d4a3]460/**
461 * Writes one line of tremolo-formatted data to the provided stream.
462 *
463 * \param stream where to write the line to
464 * \param reference to the atom of which information should be written
465 */
[fac58f]466void FormatParser< tremolo >::saveLine(
467 std::ostream* file,
468 const atom * const currentAtom)
[23fd43]469{
[b8d4a3]470 TremoloKey::atomDataKey currentField;
471
[47d041]472 LOG(4, "INFO: Saving atom " << *currentAtom << ", its father id is " << currentAtom->GetTrueFather()->getId());
[4d4d33]473
[23fd43]474 for (usedFields_t::iterator it = usedFields_save.begin(); it != usedFields_save.end(); it++) {
[b8d4a3]475 currentField = knownKeys[it->substr(0, it->find("="))];
476 switch (currentField) {
477 case TremoloKey::x :
478 // for the moment, assume there are always three dimensions
[47d041]479 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getPosition());
[d74077]480 *file << currentAtom->at(0) << "\t";
481 *file << currentAtom->at(1) << "\t";
482 *file << currentAtom->at(2) << "\t";
[b8d4a3]483 break;
484 case TremoloKey::u :
485 // for the moment, assume there are always three dimensions
[47d041]486 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getAtomicVelocity());
[bce72c]487 *file << currentAtom->getAtomicVelocity()[0] << "\t";
488 *file << currentAtom->getAtomicVelocity()[1] << "\t";
489 *file << currentAtom->getAtomicVelocity()[2] << "\t";
[b8d4a3]490 break;
[e6e4a0]491 case TremoloKey::F :
492 // for the moment, assume there are always three dimensions
493 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getAtomicForce());
494 *file << currentAtom->getAtomicForce()[0] << "\t";
495 *file << currentAtom->getAtomicForce()[1] << "\t";
496 *file << currentAtom->getAtomicForce()[2] << "\t";
497 break;
[305e7e]498 case TremoloKey::type :
[4795cd]499 writeEntryFromAdditionalAtomData_ifnotempty<std::string>(
500 additionalAtomData,
501 knownKeyNames,
502 defaultAdditionalData,
503 file,
504 currentAtom,
505 currentField,
506 boost::bind(&element::getSymbol, boost::bind(&AtomInfo::getType, _1)));
[b8d4a3]507 break;
508 case TremoloKey::Id :
[47d041]509 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getId()+1);
[812155]510 *file << getLocalId(currentAtom->getId()) << "\t";
[b8d4a3]511 break;
512 case TremoloKey::neighbors :
[47d041]513 LOG(3, "Writing type " << knownKeyNames[currentField]);
[b8d4a3]514 writeNeighbors(file, atoi(it->substr(it->find("=") + 1, 1).c_str()), currentAtom);
515 break;
[05e2ed]516 case TremoloKey::imprData :
517 case TremoloKey::torsion :
518 LOG(3, "Writing type " << knownKeyNames[currentField]);
519 *file << adaptIdDependentDataString(
520 additionalAtomData[currentAtom->getId()].get(currentField),
521 idlocalizer)
522 << "\t";
523 break;
[74a444]524 case TremoloKey::resSeq :
[4d4d33]525 if (additionalAtomData.count(currentAtom->getId())) {
[47d041]526 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << additionalAtomData[currentAtom->getId()].get(currentField));
[74a444]527 *file << additionalAtomData[currentAtom->getId()].get(currentField);
528 } else if (currentAtom->getMolecule() != NULL) {
[47d041]529 LOG(3, "Writing for type " << knownKeyNames[currentField] << " its own id: " << currentAtom->getMolecule()->getId()+1);
[67ab71]530 *file << setw(4) << currentAtom->getMolecule()->getId();
[74a444]531 } else {
[47d041]532 LOG(3, "Writing for type " << knownKeyNames[currentField] << " default value: " << defaultAdditionalData.get(currentField));
[74a444]533 *file << defaultAdditionalData.get(currentField);
534 }
535 *file << "\t";
[4d4d33]536 break;
[2034f3]537 case TremoloKey::charge :
538 if (currentAtom->getCharge() == 0.) {
[4795cd]539 writeEntryFromAdditionalAtomData_ifpresent<double>(
540 additionalAtomData,
541 knownKeyNames,
542 file,
543 currentAtom,
544 currentField,
545 boost::bind(&AtomInfo::getCharge, _1));
[2034f3]546 } else {
547 LOG(3, "Writing for type " << knownKeyNames[currentField] << " AtomInfo::charge : " << currentAtom->getCharge());
[4795cd]548 *file << currentAtom->getCharge() << "\t";
[2034f3]549 }
550 break;
[b8d4a3]551 default :
[4795cd]552 writeAdditionalAtomDataEntry<std::string>(
553 additionalAtomData,
554 knownKeyNames,
555 defaultAdditionalData,
556 file,
557 currentAtom,
558 currentField);
[b8d4a3]559 break;
560 }
561 }
562
[23fd43]563 *file << std::endl;
[b8d4a3]564}
565
566/**
567 * Writes the neighbor information of one atom to the provided stream.
568 *
[9d83b6]569 * Note that ListOfBonds of WorldTime::CurrentTime is used.
570 *
[b8d4a3]571 * \param stream where to write neighbor information to
572 * \param number of neighbors
573 * \param reference to the atom of which to take the neighbor information
574 */
[fac58f]575void FormatParser< tremolo >::writeNeighbors(
576 std::ostream* file,
577 const int numberOfNeighbors,
578 const atom * const currentAtom) {
[9d83b6]579 const BondList& ListOfBonds = currentAtom->getListOfBonds();
[ca2cfa]580 // sort bonded indices
581 typedef std::set<atomId_t> sortedIndices;
582 sortedIndices sortedBonds;
583 for (BondList::const_iterator iter = ListOfBonds.begin();
584 iter != ListOfBonds.end(); ++iter)
[812155]585 sortedBonds.insert(getLocalId((*iter)->GetOtherAtom(currentAtom)->getId()));
[ca2cfa]586 // print indices
587 sortedIndices::const_iterator currentBond = sortedBonds.begin();
[b8d4a3]588 for (int i = 0; i < numberOfNeighbors; i++) {
[812155]589 *file << (currentBond != sortedBonds.end() ? (*currentBond) : 0) << "\t";
[ca2cfa]590 if (currentBond != sortedBonds.end())
[0bbfa1]591 ++currentBond;
[b8d4a3]592 }
[9131f3]593}
594
595/**
[23fd43]596 * Stores keys from the ATOMDATA line in \a fields.
[9131f3]597 *
598 * \param line to parse the keys from
[23fd43]599 * \param offset with which offset the keys begin within the line
600 * \param fields which usedFields to use
[9131f3]601 */
[23fd43]602void FormatParser< tremolo >::parseAtomDataKeysLine(
603 const std::string &line,
604 const int offset,
605 usedFields_t &fields) {
[8bf9c6]606 std::string keyword;
607 std::stringstream lineStream;
[9131f3]608
609 lineStream << line.substr(offset);
[a86cda]610 lineStream >> ws;
[9131f3]611 while (lineStream.good()) {
612 lineStream >> keyword;
[b8d4a3]613 if (knownKeys[keyword.substr(0, keyword.find("="))] == TremoloKey::noKey) {
[ecb799]614 // TODO: throw exception about unknown key
[5a667d]615 cout << "Unknown key: " << keyword.substr(0, keyword.find("=")) << " is not part of the tremolo format specification." << endl;
616 throw IllegalParserKeyException();
[4415da]617 break;
618 }
[23fd43]619 fields.push_back(keyword);
[a86cda]620 lineStream >> ws;
[9131f3]621 }
[a86cda]622 LOG(2, "INFO: " << fields);
[9131f3]623}
624
[5a667d]625/**
626 * Tests whether the keys from the ATOMDATA line can be read correctly.
627 *
628 * \param line to parse the keys from
629 */
630bool FormatParser< tremolo >::testParseAtomDataKeysLine(
631 const std::string &line) {
632 std::string keyword;
633 std::stringstream lineStream;
634
635 // check string after ATOMDATA
636 const std::string AtomData("ATOMDATA");
637 const size_t AtomDataOffset = line.find(AtomData, 0);
638 if (AtomDataOffset == std::string::npos)
639 lineStream << line;
640 else
641 lineStream << line.substr(AtomDataOffset + AtomData.length());
642 while (lineStream.good()) {
643 lineStream >> keyword;
644 //LOG(2, "DEBUG: Checking key " << keyword.substr(0, keyword.find("=")) << ".");
645 if (knownKeys[keyword.substr(0, keyword.find("="))] == TremoloKey::noKey)
646 return false;
647 }
648 //LOG(1, "INFO: " << fields);
649 return true;
650}
651
[ca331c]652std::string FormatParser< tremolo >::getAtomData() const
653{
654 std::stringstream output;
655 std::for_each(usedFields_save.begin(), usedFields_save.end(),
656 output << boost::lambda::_1 << " ");
657 const std::string returnstring(output.str());
658 return returnstring.substr(0, returnstring.find_last_of(" "));
659}
660
661/** Appends the properties per atom to print to .data file by parsing line from
662 * \a atomdata_string.
663 *
664 * We just call \sa FormatParser< tremolo >::parseAtomDataKeysLine().
665 *
666 * @param atomdata_string line to parse with space-separated values
667 */
668void FormatParser< tremolo >::setAtomData(const std::string &atomdata_string)
669{
670 parseAtomDataKeysLine(atomdata_string, 0, usedFields_save);
671}
672
[81c980b]673/** Sets the properties per atom to print to .data file by parsing line from
674 * \a atomdata_string.
675 *
[23fd43]676 * We just call \sa FormatParser< tremolo >::parseAtomDataKeysLine(), however
677 * we clear FormatParser< tremolo >::usedFields_save.
[81c980b]678 *
679 * @param atomdata_string line to parse with space-separated values
680 */
[ca331c]681void FormatParser< tremolo >::resetAtomData(const std::string &atomdata_string)
[81c980b]682{
[23fd43]683 usedFields_save.clear();
684 parseAtomDataKeysLine(atomdata_string, 0, usedFields_save);
[81c980b]685}
686
687
[9131f3]688/**
689 * Reads one data line of a tremolo file and interprets it according to the keys
690 * obtained from the ATOMDATA line.
691 *
692 * \param line to parse as an atom
[dc1d9e]693 * \param *newmol molecule to add atom to
[9131f3]694 */
[23fd43]695void FormatParser< tremolo >::readAtomDataLine(const std::string &line, molecule *newmol = NULL) {
[8bf9c6]696 std::stringstream lineStream;
[4415da]697 atom* newAtom = World::getInstance().createAtom();
[89a31d]698 const atomId_t atomid = newAtom->getId();
699 additionalAtomData[atomid] = TremoloAtomInfoContainer(); // fill with default values
700 TremoloAtomInfoContainer *atomInfo = &additionalAtomData[atomid];
[b8d4a3]701 TremoloKey::atomDataKey currentField;
[72d108]702 ConvertTo<double> toDouble;
703 ConvertTo<int> toInt;
[056e70]704 Vector tempVector;
[740f9f]705 const ParticleRegistry& registry = ParticleRegistry::getConstInstance();
706 const periodentafel& periode = *World::getInstance().getPeriode();
[72d108]707
708 // setup tokenizer, splitting up white-spaced entries
709 typedef boost::tokenizer<boost::char_separator<char> >
710 tokenizer;
711 boost::char_separator<char> whitespacesep(" \t");
712 tokenizer tokens(line, whitespacesep);
713 ASSERT(tokens.begin() != tokens.end(),
[765f16]714 "FormatParser< tremolo >::readAtomDataLine - empty string, need at least ' '!");
[fc41df]715 tokenizer::const_iterator tok_iter = tokens.begin();
[72d108]716 // then associate each token to each file
[fc41df]717 for (usedFields_t::const_iterator it = usedFields_load.begin(); it != usedFields_load.end(); it++) {
[72d108]718 const std::string keyName = it->substr(0, it->find("="));
719 currentField = knownKeys[keyName];
[fc41df]720 ASSERT(tok_iter != tokens.end(),
721 "FormatParser< tremolo >::readAtomDataLine - too few entries in line '"+line+"'!");
722 const std::string &word = *tok_iter;
[47d041]723 LOG(4, "INFO: Parsing key " << keyName << " with remaining data " << word);
[4415da]724 switch (currentField) {
[b8d4a3]725 case TremoloKey::x :
[4415da]726 // for the moment, assume there are always three dimensions
[d74077]727 for (int i=0;i<NDIM;i++) {
[765f16]728 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for x["+toString(i)+"]!");
[fc41df]729 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
730 newAtom->set(i, toDouble(word));
[72d108]731 tok_iter++;
[d74077]732 }
[4415da]733 break;
[b8d4a3]734 case TremoloKey::u :
[4415da]735 // for the moment, assume there are always three dimensions
[72d108]736 for (int i=0;i<NDIM;i++) {
[765f16]737 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for u["+toString(i)+"]!");
[fc41df]738 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
739 tempVector[i] = toDouble(word);
[72d108]740 tok_iter++;
741 }
[056e70]742 newAtom->setAtomicVelocity(tempVector);
[4415da]743 break;
[e6e4a0]744 case TremoloKey::F :
745 // for the moment, assume there are always three dimensions
746 for (int i=0;i<NDIM;i++) {
747 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for F["+toString(i)+"]!");
[fc41df]748 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
749 tempVector[i] = toDouble(word);
[e6e4a0]750 tok_iter++;
751 }
752 newAtom->setAtomicForce(tempVector);
753 break;
[305e7e]754 case TremoloKey::type :
[4d4d33]755 {
[765f16]756 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
[fc41df]757 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
[740f9f]758 std::string elementname;
759 const element * elem = NULL;
760 if (!registry.isPresentByName(word)) {
761 std::string lowercase_word(word);
762 std::transform(word.begin()+1, word.end(), lowercase_word.begin()+1, ::tolower);
763 elem = periode.FindElement(lowercase_word);
764 if (elem == NULL) {
765 // clean up
766 World::getInstance().destroyAtom(newAtom);
767 // give an error
768 ELOG(0, "TremoloParser: tokens " << word << "/" << lowercase_word
769 << " is unknown to neither ParticleRegistry nor Periodentafel.");
770 return;
771 } else {
772 elementname = elem->getSymbol();
773 }
774 } else {
775 const Particle * const p = registry.getByName(word);
776 elementname = p->getElement();
777 elem = periode.FindElement(elementname);
[a275b3]778 }
[4d4d33]779 // put type name into container for later use
[fc41df]780 atomInfo->set(currentField, word);
[740f9f]781 LOG(4, "INFO: Parsing element " << (word) << " as " << elementname << " according to KnownTypes.");
[72d108]782 tok_iter++;
[740f9f]783 newAtom->setType(elem);
[b8d4a3]784 ASSERT(newAtom->getType(), "Type was not set for this atom");
[4415da]785 break;
[4d4d33]786 }
[b8d4a3]787 case TremoloKey::Id :
[765f16]788 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
[fc41df]789 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
790 associateLocaltoGlobalId(toInt(word), atomid);
[72d108]791 tok_iter++;
[4415da]792 break;
[b8d4a3]793 case TremoloKey::neighbors :
[72d108]794 for (int i=0;i<atoi(it->substr(it->find("=") + 1, 1).c_str());i++) {
[765f16]795 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
[fc41df]796 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
797 lineStream << word << "\t";
[72d108]798 tok_iter++;
799 }
[b8d4a3]800 readNeighbors(&lineStream,
[89a31d]801 atoi(it->substr(it->find("=") + 1, 1).c_str()), atomid);
[9131f3]802 break;
[2034f3]803 case TremoloKey::charge :
804 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
[fc41df]805 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
806 atomInfo->set(currentField, word);
807 newAtom->setCharge(boost::lexical_cast<double>(word));
[2034f3]808 tok_iter++;
809 break;
[9131f3]810 default :
[765f16]811 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
[fc41df]812 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
813 atomInfo->set(currentField, word);
[72d108]814 tok_iter++;
[9131f3]815 break;
816 }
817 }
[89a31d]818 LOG(3, "INFO: Parsed atom " << atomid << ".");
819 if (newmol != NULL)
[dc1d9e]820 newmol->AddAtom(newAtom);
[6bc51d]821}
[9131f3]822
[99db9b]823bool FormatParser< tremolo >::saveAtomsInExttypes(
824 std::ostream &output,
825 const std::vector<const atom*> &atoms,
826 const int id) const
[531f27]827{
828 bool status = true;
829 // parse the file
[99db9b]830 for (std::vector<const atom *>::const_iterator iter = atoms.begin();
[531f27]831 iter != atoms.end(); ++iter) {
832 const int atomicid = getLocalId((*iter)->getId());
833 if (atomicid == -1)
834 status = false;
835 output << atomicid << "\t" << id << std::endl;
836 }
837
838 return status;
839}
840
[b8d4a3]841/**
842 * Reads neighbor information for one atom from the input.
843 *
[0bbfa1]844 * \param line stream where to read the information from
845 * \param numberOfNeighbors number of neighbors to read
846 * \param atomid world id of the atom the information belongs to
[b8d4a3]847 */
[fac58f]848void FormatParser< tremolo >::readNeighbors(
849 std::stringstream* line,
850 const int numberOfNeighbors,
851 const int atomId) {
[b8d4a3]852 int neighborId = 0;
853 for (int i = 0; i < numberOfNeighbors; i++) {
854 *line >> neighborId;
855 // 0 is used to fill empty neighbor positions in the tremolo file.
856 if (neighborId > 0) {
[47d041]857 LOG(4, "INFO: Atom with global id " << atomId
858 << " has neighbour with serial " << neighborId);
[b8d4a3]859 additionalAtomData[atomId].neighbors.push_back(neighborId);
860 }
861 }
862}
[9131f3]863
864/**
[23fd43]865 * Checks whether the provided name is within \a fields.
[b8d4a3]866 *
[23fd43]867 * \param fields which usedFields to use
868 * \param fieldName name to check
[b8d4a3]869 * \return true if the field name is used
[9131f3]870 */
[fac58f]871bool FormatParser< tremolo >::isUsedField(
872 const usedFields_t &fields,
873 const std::string &fieldName) const
[23fd43]874{
[b8d4a3]875 bool fieldNameExists = false;
[23fd43]876 for (usedFields_t::const_iterator usedField = fields.begin();
877 usedField != fields.end(); usedField++) {
[b8d4a3]878 if (usedField->substr(0, usedField->find("=")) == fieldName)
879 fieldNameExists = true;
880 }
[9131f3]881
[b8d4a3]882 return fieldNameExists;
883}
884
885
886/**
887 * Adds the collected neighbor information to the atoms in the world. The atoms
888 * are found by their current ID and mapped to the corresponding atoms with the
889 * Id found in the parsed file.
[9f8b01]890 *
891 * @param atoms vector with all newly added (global) atomic ids
[b8d4a3]892 */
[fac58f]893void FormatParser< tremolo >::processNeighborInformation(
894 const std::vector<atomId_t> &atoms) {
[23fd43]895 if (!isUsedField(usedFields_load, "neighbors")) {
[b8d4a3]896 return;
897 }
898
[9f8b01]899 for (std::vector<atomId_t>::const_iterator iter = atoms.begin(); iter != atoms.end(); ++iter) {
900 ASSERT(additionalAtomData.count(*iter) != 0,
901 "FormatParser< tremolo >::processNeighborInformation() - global id "
902 +toString(*iter)+" unknown in additionalAtomData.");
903 TremoloAtomInfoContainer &currentInfo = additionalAtomData[*iter];
904 ASSERT (!currentInfo.neighbors_processed,
905 "FormatParser< tremolo >::processNeighborInformation() - neighbors of new atom "
906 +toString(*iter)+" are already processed.");
907 for(std::vector<int>::const_iterator neighbor = currentInfo.neighbors.begin();
908 neighbor != currentInfo.neighbors.end(); neighbor++
909 ) {
910 LOG(3, "INFO: Creating bond between ("
911 << *iter
912 << ") and ("
913 << getGlobalId(*neighbor) << "|" << *neighbor << ")");
914 ASSERT(getGlobalId(*neighbor) != -1,
915 "FormatParser< tremolo >::processNeighborInformation() - global id to local id "
916 +toString(*neighbor)+" is unknown.");
917 World::getInstance().getAtom(AtomById(*iter))
918 ->addBond(WorldTime::getTime(), World::getInstance().getAtom(AtomById(getGlobalId(*neighbor))));
[9131f3]919 }
[9f8b01]920 currentInfo.neighbors_processed = true;
[9131f3]921 }
[6bc51d]922}
923
[9131f3]924/**
[b8d4a3]925 * Replaces atom IDs read from the file by the corresponding world IDs. All IDs
926 * IDs of the input string will be replaced; expected separating characters are
927 * "-" and ",".
[9131f3]928 *
[b8d4a3]929 * \param string in which atom IDs should be adapted
[05e2ed]930 * \param idgetter function pointer to change the id
[b8d4a3]931 *
932 * \return input string with modified atom IDs
[9131f3]933 */
[05e2ed]934std::string FormatParser< tremolo >::adaptIdDependentDataString(
935 const std::string &data,
936 const boost::function<int (const int)> &idgetter
937 ) {
[b8d4a3]938 // there might be no IDs
939 if (data == "-") {
940 return "-";
941 }
942
943 char separator;
944 int id;
[8bf9c6]945 std::stringstream line, result;
[b8d4a3]946 line << data;
947
948 line >> id;
[05e2ed]949 result << idgetter(id);
[b8d4a3]950 while (line.good()) {
951 line >> separator >> id;
[05e2ed]952 result << separator << idgetter(id);
[b8d4a3]953 }
954
955 return result.str();
[6bc51d]956}
[b8d4a3]957
[05e2ed]958/** Corrects the atom IDs in each imprData entry to the corresponding world IDs
[b8d4a3]959 * as they might differ from the originally read IDs.
[05e2ed]960 *
961 * \param atoms currently parsed in atoms
[b8d4a3]962 */
[05e2ed]963void FormatParser< tremolo >::adaptImprData(const std::vector<atomId_t> &atoms) {
[23fd43]964 if (!isUsedField(usedFields_load, "imprData")) {
[b8d4a3]965 return;
966 }
967
[05e2ed]968 for (std::vector<atomId_t>::const_iterator iter = atoms.begin(); iter != atoms.end(); ++iter) {
969 ASSERT(additionalAtomData.count(*iter) != 0,
970 "FormatParser< tremolo >::processNeighborInformation() - global id "
971 +toString(*iter)+" unknown in additionalAtomData.");
972 TremoloAtomInfoContainer &currentInfo = additionalAtomData[*iter];
973 currentInfo.imprData = adaptIdDependentDataString(currentInfo.imprData, idglobalizer);
[b8d4a3]974 }
[6bc51d]975}
[4415da]976
[05e2ed]977/** Corrects the atom IDs in each torsion entry to the corresponding world IDs
[b8d4a3]978 * as they might differ from the originally read IDs.
[05e2ed]979 *
980 * \param atoms currently parsed in atoms
[b8d4a3]981 */
[05e2ed]982void FormatParser< tremolo >::adaptTorsion(const std::vector<atomId_t> &atoms) {
[23fd43]983 if (!isUsedField(usedFields_load, "torsion")) {
[b8d4a3]984 return;
985 }
986
[05e2ed]987 for (std::vector<atomId_t>::const_iterator iter = atoms.begin(); iter != atoms.end(); ++iter) {
988 ASSERT(additionalAtomData.count(*iter) != 0,
989 "FormatParser< tremolo >::processNeighborInformation() - global id "
990 +toString(*iter)+" unknown in additionalAtomData.");
991 TremoloAtomInfoContainer &currentInfo = additionalAtomData[*iter];
992 currentInfo.torsion = adaptIdDependentDataString(currentInfo.torsion, idglobalizer);
[b8d4a3]993 }
994}
995
Note: See TracBrowser for help on using the repository browser.