source: src/Parser/TremoloParser.cpp@ 045228

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation 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 SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 045228 was 4795cd, checked in by Frederik Heber <heber@…>, 9 years ago

Extracted writeEntry() in TremoloParser::saveLine().

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