source: src/Parser/TremoloParser.cpp@ 0e894a

Action_Thermostats Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests AutomationFragmentation_failures Candidate_v1.6.1 ChemicalSpaceEvaluator Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph Fix_Verbose_Codepatterns ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion Gui_displays_atomic_force_velocity JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool PythonUI_with_named_parameters Recreated_GuiChecks StoppableMakroAction TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps
Last change on this file since 0e894a was 220d2c, checked in by Frederik Heber <frederik.heber@…>, 8 years ago

TremoloParser::load() can deal with multiple time steps.

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