source: src/Parser/TremoloParser.cpp@ ff4fff9

CombiningParticlePotentialParsing
Last change on this file since ff4fff9 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
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 while (file->good()) {
146 std::getline(*file, line, '\n');
147 // we only parse in the first ATOMDATA line
148 if (usedFields_load.empty()) {
149 location = line.find("ATOMDATA", 0);
150 if (location != string::npos) {
151 parseAtomDataKeysLine(line, location + 8, usedFields_load);
152 }
153 }
154 if (line.length() > 0 && line.at(0) != '#') {
155 readAtomDataLine(line, newmol);
156 }
157 }
158 LOG(3, "DEBUG: Local usedFields is: " << usedFields_load);
159
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);
165 adaptImprData(atoms);
166 adaptTorsion(atoms);
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();
171}
172
173/**
174 * Saves the \a atoms into as a tremolo file.
175 *
176 * \param file where to save the state
177 * \param atoms atoms to store
178 */
179void FormatParser< tremolo >::save(
180 std::ostream* file,
181 const std::vector<const atom *> &AtomList) {
182 LOG(2, "DEBUG: Saving changes to tremolo.");
183
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);
194 LOG(1, "INFO: Global (with unique entries) usedFields_save is: " << usedFields_save);
195
196 // distribute ids continuously
197 distributeContinuousIds(AtomList);
198
199 // store atomdata
200 save_AtomDataLine(file);
201
202 // store box
203 save_BoxLine(file);
204
205 // store particles
206 for (std::vector<const atom*>::const_iterator atomIt = AtomList.begin();
207 atomIt != AtomList.end(); ++atomIt)
208 saveLine(file, *atomIt);
209}
210
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
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 */
267void FormatParser< tremolo >::makeUsedFieldsUnique(usedFields_t &fields) const
268{
269 // std::unique only removes if predecessor is equal, not over whole range, hence do it manually
270 usedFields_t temp_fields(fields);
271 usedFieldsSpecialOrderer SpecialOrderer;
272 usedFieldsWeakComparator WeakComparator;
273 std::sort(temp_fields.begin(), temp_fields.end(), SpecialOrderer);
274 usedFields_t::iterator it =
275 std::unique(temp_fields.begin(), temp_fields.end(), WeakComparator);
276 temp_fields.erase(it, temp_fields.end());
277 usedFields_t usedfields(fields);
278 fields.clear();
279 fields.reserve(temp_fields.size());
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()) {
286 fields.push_back(*iter);
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 */
300void FormatParser< tremolo >::distributeContinuousIds(
301 const std::vector<const atom *> &AtomList)
302{
303 resetIdAssociations();
304 atomId_t lastid = 0;
305 for (std::vector<const atom*>::const_iterator atomIt = AtomList.begin();
306 atomIt != AtomList.end(); ++atomIt)
307 associateLocaltoGlobalId(++lastid, (*atomIt)->getId());
308}
309
310/** Store Atomdata line to \a file.
311 *
312 * @param file output stream
313 */
314void FormatParser< tremolo >::save_AtomDataLine(std::ostream* file) const
315{
316 *file << "# ATOMDATA";
317 for (usedFields_t::const_iterator it=usedFields_save.begin();
318 it != usedFields_save.end(); ++it)
319 *file << "\t" << *it;
320 *file << std::endl;
321}
322
323/** Store Box info to \a file
324 *
325 * @param file output stream
326 */
327void FormatParser< tremolo >::save_BoxLine(std::ostream* file) const
328{
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;
335}
336
337/** Add default info, when new atom is added to World.
338 *
339 * @param id of atom
340 */
341void FormatParser< tremolo >::AtomInserted(atomId_t id)
342{
343 std::map<const atomId_t, TremoloAtomInfoContainer>::iterator iter = additionalAtomData.find(id);
344 ASSERT(iter == additionalAtomData.end(),
345 "FormatParser< tremolo >::AtomInserted() - additionalAtomData already present for newly added atom "
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 */
355void FormatParser< tremolo >::AtomRemoved(atomId_t id)
356{
357 std::map<const atomId_t, TremoloAtomInfoContainer>::iterator iter = additionalAtomData.find(id);
358 // as we do not insert AtomData on AtomInserted, we cannot be assured of its presence
359// ASSERT(iter != additionalAtomData.end(),
360// "FormatParser< tremolo >::AtomRemoved() - additionalAtomData is not present for atom "
361// +toString(id)+" to remove.");
362 if (iter != additionalAtomData.end())
363 additionalAtomData.erase(iter);
364}
365
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
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 */
466void FormatParser< tremolo >::saveLine(
467 std::ostream* file,
468 const atom * const currentAtom)
469{
470 TremoloKey::atomDataKey currentField;
471
472 LOG(4, "INFO: Saving atom " << *currentAtom << ", its father id is " << currentAtom->GetTrueFather()->getId());
473
474 for (usedFields_t::iterator it = usedFields_save.begin(); it != usedFields_save.end(); it++) {
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
479 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getPosition());
480 *file << currentAtom->at(0) << "\t";
481 *file << currentAtom->at(1) << "\t";
482 *file << currentAtom->at(2) << "\t";
483 break;
484 case TremoloKey::u :
485 // for the moment, assume there are always three dimensions
486 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getAtomicVelocity());
487 *file << currentAtom->getAtomicVelocity()[0] << "\t";
488 *file << currentAtom->getAtomicVelocity()[1] << "\t";
489 *file << currentAtom->getAtomicVelocity()[2] << "\t";
490 break;
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;
498 case TremoloKey::type :
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)));
507 break;
508 case TremoloKey::Id :
509 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << currentAtom->getId()+1);
510 *file << getLocalId(currentAtom->getId()) << "\t";
511 break;
512 case TremoloKey::neighbors :
513 LOG(3, "Writing type " << knownKeyNames[currentField]);
514 writeNeighbors(file, atoi(it->substr(it->find("=") + 1, 1).c_str()), currentAtom);
515 break;
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;
524 case TremoloKey::resSeq :
525 if (additionalAtomData.count(currentAtom->getId())) {
526 LOG(3, "Writing for type " << knownKeyNames[currentField] << ": " << additionalAtomData[currentAtom->getId()].get(currentField));
527 *file << additionalAtomData[currentAtom->getId()].get(currentField);
528 } else if (currentAtom->getMolecule() != NULL) {
529 LOG(3, "Writing for type " << knownKeyNames[currentField] << " its own id: " << currentAtom->getMolecule()->getId()+1);
530 *file << setw(4) << currentAtom->getMolecule()->getId();
531 } else {
532 LOG(3, "Writing for type " << knownKeyNames[currentField] << " default value: " << defaultAdditionalData.get(currentField));
533 *file << defaultAdditionalData.get(currentField);
534 }
535 *file << "\t";
536 break;
537 case TremoloKey::charge :
538 if (currentAtom->getCharge() == 0.) {
539 writeEntryFromAdditionalAtomData_ifpresent<double>(
540 additionalAtomData,
541 knownKeyNames,
542 file,
543 currentAtom,
544 currentField,
545 boost::bind(&AtomInfo::getCharge, _1));
546 } else {
547 LOG(3, "Writing for type " << knownKeyNames[currentField] << " AtomInfo::charge : " << currentAtom->getCharge());
548 *file << currentAtom->getCharge() << "\t";
549 }
550 break;
551 default :
552 writeAdditionalAtomDataEntry<std::string>(
553 additionalAtomData,
554 knownKeyNames,
555 defaultAdditionalData,
556 file,
557 currentAtom,
558 currentField);
559 break;
560 }
561 }
562
563 *file << std::endl;
564}
565
566/**
567 * Writes the neighbor information of one atom to the provided stream.
568 *
569 * Note that ListOfBonds of WorldTime::CurrentTime is used.
570 *
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 */
575void FormatParser< tremolo >::writeNeighbors(
576 std::ostream* file,
577 const int numberOfNeighbors,
578 const atom * const currentAtom) {
579 const BondList& ListOfBonds = currentAtom->getListOfBonds();
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)
585 sortedBonds.insert(getLocalId((*iter)->GetOtherAtom(currentAtom)->getId()));
586 // print indices
587 sortedIndices::const_iterator currentBond = sortedBonds.begin();
588 for (int i = 0; i < numberOfNeighbors; i++) {
589 *file << (currentBond != sortedBonds.end() ? (*currentBond) : 0) << "\t";
590 if (currentBond != sortedBonds.end())
591 ++currentBond;
592 }
593}
594
595/**
596 * Stores keys from the ATOMDATA line in \a fields.
597 *
598 * \param line to parse the keys from
599 * \param offset with which offset the keys begin within the line
600 * \param fields which usedFields to use
601 */
602void FormatParser< tremolo >::parseAtomDataKeysLine(
603 const std::string &line,
604 const int offset,
605 usedFields_t &fields) {
606 std::string keyword;
607 std::stringstream lineStream;
608
609 lineStream << line.substr(offset);
610 lineStream >> ws;
611 while (lineStream.good()) {
612 lineStream >> keyword;
613 if (knownKeys[keyword.substr(0, keyword.find("="))] == TremoloKey::noKey) {
614 // TODO: throw exception about unknown key
615 cout << "Unknown key: " << keyword.substr(0, keyword.find("=")) << " is not part of the tremolo format specification." << endl;
616 throw IllegalParserKeyException();
617 break;
618 }
619 fields.push_back(keyword);
620 lineStream >> ws;
621 }
622 LOG(2, "INFO: " << fields);
623}
624
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
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
673/** Sets the properties per atom to print to .data file by parsing line from
674 * \a atomdata_string.
675 *
676 * We just call \sa FormatParser< tremolo >::parseAtomDataKeysLine(), however
677 * we clear FormatParser< tremolo >::usedFields_save.
678 *
679 * @param atomdata_string line to parse with space-separated values
680 */
681void FormatParser< tremolo >::resetAtomData(const std::string &atomdata_string)
682{
683 usedFields_save.clear();
684 parseAtomDataKeysLine(atomdata_string, 0, usedFields_save);
685}
686
687
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
693 * \param *newmol molecule to add atom to
694 */
695void FormatParser< tremolo >::readAtomDataLine(const std::string &line, molecule *newmol = NULL) {
696 std::stringstream lineStream;
697 atom* newAtom = World::getInstance().createAtom();
698 const atomId_t atomid = newAtom->getId();
699 additionalAtomData[atomid] = TremoloAtomInfoContainer(); // fill with default values
700 TremoloAtomInfoContainer *atomInfo = &additionalAtomData[atomid];
701 TremoloKey::atomDataKey currentField;
702 ConvertTo<double> toDouble;
703 ConvertTo<int> toInt;
704 Vector tempVector;
705 const ParticleRegistry& registry = ParticleRegistry::getConstInstance();
706 const periodentafel& periode = *World::getInstance().getPeriode();
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(),
714 "FormatParser< tremolo >::readAtomDataLine - empty string, need at least ' '!");
715 tokenizer::const_iterator tok_iter = tokens.begin();
716 // then associate each token to each file
717 for (usedFields_t::const_iterator it = usedFields_load.begin(); it != usedFields_load.end(); it++) {
718 const std::string keyName = it->substr(0, it->find("="));
719 currentField = knownKeys[keyName];
720 ASSERT(tok_iter != tokens.end(),
721 "FormatParser< tremolo >::readAtomDataLine - too few entries in line '"+line+"'!");
722 const std::string &word = *tok_iter;
723 LOG(4, "INFO: Parsing key " << keyName << " with remaining data " << word);
724 switch (currentField) {
725 case TremoloKey::x :
726 // for the moment, assume there are always three dimensions
727 for (int i=0;i<NDIM;i++) {
728 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for x["+toString(i)+"]!");
729 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
730 newAtom->set(i, toDouble(word));
731 tok_iter++;
732 }
733 break;
734 case TremoloKey::u :
735 // for the moment, assume there are always three dimensions
736 for (int i=0;i<NDIM;i++) {
737 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for u["+toString(i)+"]!");
738 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
739 tempVector[i] = toDouble(word);
740 tok_iter++;
741 }
742 newAtom->setAtomicVelocity(tempVector);
743 break;
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)+"]!");
748 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
749 tempVector[i] = toDouble(word);
750 tok_iter++;
751 }
752 newAtom->setAtomicForce(tempVector);
753 break;
754 case TremoloKey::type :
755 {
756 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
757 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
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);
778 }
779 // put type name into container for later use
780 atomInfo->set(currentField, word);
781 LOG(4, "INFO: Parsing element " << (word) << " as " << elementname << " according to KnownTypes.");
782 tok_iter++;
783 newAtom->setType(elem);
784 ASSERT(newAtom->getType(), "Type was not set for this atom");
785 break;
786 }
787 case TremoloKey::Id :
788 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
789 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
790 associateLocaltoGlobalId(toInt(word), atomid);
791 tok_iter++;
792 break;
793 case TremoloKey::neighbors :
794 for (int i=0;i<atoi(it->substr(it->find("=") + 1, 1).c_str());i++) {
795 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
796 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
797 lineStream << word << "\t";
798 tok_iter++;
799 }
800 readNeighbors(&lineStream,
801 atoi(it->substr(it->find("=") + 1, 1).c_str()), atomid);
802 break;
803 case TremoloKey::charge :
804 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
805 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
806 atomInfo->set(currentField, word);
807 newAtom->setCharge(boost::lexical_cast<double>(word));
808 tok_iter++;
809 break;
810 default :
811 ASSERT(tok_iter != tokens.end(), "FormatParser< tremolo >::readAtomDataLine() - no value for "+keyName+"!");
812 LOG(4, "INFO: Parsing key " << keyName << " with next token " << word);
813 atomInfo->set(currentField, word);
814 tok_iter++;
815 break;
816 }
817 }
818 LOG(3, "INFO: Parsed atom " << atomid << ".");
819 if (newmol != NULL)
820 newmol->AddAtom(newAtom);
821}
822
823bool FormatParser< tremolo >::saveAtomsInExttypes(
824 std::ostream &output,
825 const std::vector<const atom*> &atoms,
826 const int id) const
827{
828 bool status = true;
829 // parse the file
830 for (std::vector<const atom *>::const_iterator iter = atoms.begin();
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
841/**
842 * Reads neighbor information for one atom from the input.
843 *
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
847 */
848void FormatParser< tremolo >::readNeighbors(
849 std::stringstream* line,
850 const int numberOfNeighbors,
851 const int atomId) {
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) {
857 LOG(4, "INFO: Atom with global id " << atomId
858 << " has neighbour with serial " << neighborId);
859 additionalAtomData[atomId].neighbors.push_back(neighborId);
860 }
861 }
862}
863
864/**
865 * Checks whether the provided name is within \a fields.
866 *
867 * \param fields which usedFields to use
868 * \param fieldName name to check
869 * \return true if the field name is used
870 */
871bool FormatParser< tremolo >::isUsedField(
872 const usedFields_t &fields,
873 const std::string &fieldName) const
874{
875 bool fieldNameExists = false;
876 for (usedFields_t::const_iterator usedField = fields.begin();
877 usedField != fields.end(); usedField++) {
878 if (usedField->substr(0, usedField->find("=")) == fieldName)
879 fieldNameExists = true;
880 }
881
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.
890 *
891 * @param atoms vector with all newly added (global) atomic ids
892 */
893void FormatParser< tremolo >::processNeighborInformation(
894 const std::vector<atomId_t> &atoms) {
895 if (!isUsedField(usedFields_load, "neighbors")) {
896 return;
897 }
898
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))));
919 }
920 currentInfo.neighbors_processed = true;
921 }
922}
923
924/**
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 ",".
928 *
929 * \param string in which atom IDs should be adapted
930 * \param idgetter function pointer to change the id
931 *
932 * \return input string with modified atom IDs
933 */
934std::string FormatParser< tremolo >::adaptIdDependentDataString(
935 const std::string &data,
936 const boost::function<int (const int)> &idgetter
937 ) {
938 // there might be no IDs
939 if (data == "-") {
940 return "-";
941 }
942
943 char separator;
944 int id;
945 std::stringstream line, result;
946 line << data;
947
948 line >> id;
949 result << idgetter(id);
950 while (line.good()) {
951 line >> separator >> id;
952 result << separator << idgetter(id);
953 }
954
955 return result.str();
956}
957
958/** Corrects the atom IDs in each imprData entry to the corresponding world IDs
959 * as they might differ from the originally read IDs.
960 *
961 * \param atoms currently parsed in atoms
962 */
963void FormatParser< tremolo >::adaptImprData(const std::vector<atomId_t> &atoms) {
964 if (!isUsedField(usedFields_load, "imprData")) {
965 return;
966 }
967
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);
974 }
975}
976
977/** Corrects the atom IDs in each torsion entry to the corresponding world IDs
978 * as they might differ from the originally read IDs.
979 *
980 * \param atoms currently parsed in atoms
981 */
982void FormatParser< tremolo >::adaptTorsion(const std::vector<atomId_t> &atoms) {
983 if (!isUsedField(usedFields_load, "torsion")) {
984 return;
985 }
986
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);
993 }
994}
995
Note: See TracBrowser for help on using the repository browser.