source: src/Parser/TremoloParser.cpp@ 5a667d

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 Candidate_v1.7.0 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 5a667d was 5a667d, checked in by Frederik Heber <heber@…>, 14 years ago

AtomDataValidator implemented, uses static FormatParser<tremolo>::testParseAtomDataKeysLine().

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