source: src/Parser/TremoloParser.cpp@ 4a187d

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 4a187d was 2affd1, checked in by Frederik Heber <heber@…>, 9 years ago

Removed molecules_deprecated from World and unnecessary includes of MoleculeListClass and all insert/erase.

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