source: src/Parser/XyzParser.cpp@ d5b90b

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 d5b90b was d5b90b, checked in by Frederik Heber <heber@…>, 12 years ago

FIX: XyzParser had lacking precision beyond coordinates of 100000.

  • made the coordinates be written via a printCoordinate() function for XyzParser, too. Beyond 1000 we write with fixed 3 digit precision.
  • added regression test on printing coordinates with large components.
  • Property mode set to 100644
File size: 6.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 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * XyzParser.cpp
25 *
26 * Created on: Mar 2, 2010
27 * Author: metzler
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include "CodePatterns/MemDebug.hpp"
36
37#include <limits>
38#include <vector>
39
40#include "CodePatterns/Log.hpp"
41#include "CodePatterns/Verbose.hpp"
42
43#include "XyzParser.hpp"
44
45#include "Atom/atom.hpp"
46#include "Element/element.hpp"
47#include "Element/periodentafel.hpp"
48#include "molecule.hpp"
49#include "MoleculeListClass.hpp"
50#include "World.hpp"
51
52using namespace std;
53
54// declare specialized static variables
55const std::string FormatParserTrait<xyz>::name = "xyz";
56const std::string FormatParserTrait<xyz>::suffix = "xyz";
57const ParserTypes FormatParserTrait<xyz>::type = xyz;
58
59/**
60 * Constructor.
61 */
62FormatParser< xyz >::FormatParser() :
63 FormatParser_common(NULL),
64 comment("")
65{}
66
67/**
68 * Destructor.
69 */
70FormatParser< xyz >::~FormatParser()
71{}
72
73/**
74 * Loads an XYZ file into the World.
75 *
76 * \param XYZ file
77 */
78void FormatParser< xyz >::load(istream* file)
79{
80 atom* newAtom = NULL;
81 molecule* newmol = NULL;
82 int numberOfAtoms;
83 string elementtype;
84 string streambuffer;
85 std::vector<atom *> AddedAtoms;
86
87 // create the molecule
88 newmol = World::getInstance().createMolecule();
89 newmol->ActiveFlag = true;
90 // TODO: Remove the insertion into molecule when saving does not depend on them anymore. Also, remove molecule.hpp include
91 World::getInstance().getMolecules()->insert(newmol);
92
93 // the first line tells number of atoms,
94 // where we need this construct due to skipping of empty lines below
95 getline(*file, streambuffer);
96 unsigned int step = 0;
97 while (file->good()) {
98 std::stringstream numberstream(streambuffer);
99 numberstream >> numberOfAtoms;
100 if (step == 0)
101 AddedAtoms.resize(numberOfAtoms);
102 // the second line is always a comment
103 getline(*file, streambuffer);
104 comment = streambuffer;
105 LOG(3, "DEBUG: comment is '" << comment << "'.");
106
107 for (int i = 0; i < numberOfAtoms; i++) {
108 // parse type and position
109 *file >> elementtype;
110 Vector tempVector;
111 for (int j=0;j<NDIM;j++) {
112 *file >> tempVector[j];
113 }
114 LOG(4, "INFO: Parsed type as " << elementtype << " and position at "
115 << tempVector << " for time step " << step);
116
117 if (step == 0) {
118 newAtom = World::getInstance().createAtom();
119 newAtom->setType(World::getInstance().getPeriode()->FindElement(elementtype.c_str()));
120 newmol->AddAtom(newAtom);
121 AddedAtoms[i] = newAtom;
122 LOG(5, "INFO: Created new atom, setting " << i << " th component of AddedAtoms.");
123 } else {
124 newAtom = AddedAtoms[i];
125 LOG(5, "INFO: Using present atom " << *newAtom << " from " << i << " th component of AddedAtoms.");
126 ASSERT(newAtom->getType() == World::getInstance().getPeriode()->FindElement(elementtype.c_str()),
127 "FormatParser< xyz >::load() - atom has different type "+newAtom->getType()->getSymbol()+" than parsed now "+elementtype+", mixed up order?");
128 }
129 newAtom->setPositionAtStep(step, tempVector);
130 }
131 getline (*file, streambuffer); // eat away rest of last line
132 // skip empty lines
133 unsigned int counter = 0;
134 while (file->good()) {
135 getline (*file, streambuffer);
136 LOG(4, "INFO: Skipped line is '" << streambuffer << "'");
137 counter++;
138 if (!streambuffer.empty())
139 break;
140 }
141 LOG(3, "INFO: I skipped "+toString(counter)+" empty lines.");
142 ++step;
143 }
144 BOOST_FOREACH(atom *_atom, World::getInstance().getAllAtoms())
145 LOG(3, "INFO: Atom " << _atom->getName() << " " << *dynamic_cast<AtomInfo *>(_atom) << ".");
146
147 // refresh atom::nr and atom::name
148 newmol->getAtomCount();
149}
150
151const std::string FormatParser< xyz >::printCoordinate(const double value)
152{
153 std::stringstream position;
154 if (fabs(value) > 1000) // enforce precision for large components
155 position << std::fixed << std::setprecision(3) << value;
156 else
157 position << value;
158 return position.str();
159}
160
161/**
162 * Saves the \a atoms into as a XYZ file.
163 *
164 * \param file where to save the state
165 * \param atoms atoms to store
166 */
167void FormatParser< xyz >::save(ostream* file, const std::vector<atom *> &atoms) {
168 LOG(0, "Saving changes to xyz.");
169
170 // get max and min trajectories
171 size_t min_trajectories = std::numeric_limits<size_t>::max();
172 size_t max_trajectories = std::numeric_limits<size_t>::min();
173 for (std::vector<atom *>::const_iterator iter = atoms.begin();
174 iter != atoms.end();
175 ++iter) {
176 if (max_trajectories < (*iter)->getTrajectorySize())
177 max_trajectories = (*iter)->getTrajectorySize();
178 if (min_trajectories > (*iter)->getTrajectorySize())
179 min_trajectories = (*iter)->getTrajectorySize();
180 }
181 // no atoms? Then, they all have same amount
182 if (atoms.size() == 0)
183 min_trajectories = max_trajectories = 1;
184 ASSERT(min_trajectories == max_trajectories,
185 "FormatParser< xyz >::save() - not all atoms have same number of trajectories: "
186 +toString(min_trajectories)+" != "+toString(max_trajectories)+".");
187 LOG(2, "INFO: There are " << max_trajectories << " steps to save.");
188
189 // always store at least one step
190 for (size_t step = 0; (step < max_trajectories) || (step == 0); ++step) {
191 if (step != 0)
192 *file << "\n";
193 //if (comment == "") {
194 time_t now = time((time_t *)NULL); // Get the system time and put it into 'now' as 'calender time'
195 comment = "Created by molecuilder on ";
196 // ctime ends in \n\0, we have to cut away the newline
197 std::string time(ctime(&now));
198 size_t pos = time.find('\n');
199 if (pos != 0)
200 comment += time.substr(0,pos);
201 else
202 comment += time;
203 comment += ", time step "+toString(step);
204 //}
205 *file << atoms.size() << endl << "\t" << comment << endl;
206
207 for(vector<atom*>::const_iterator it = atoms.begin(); it != atoms.end(); it++) {
208 *file << (*it)->getType()->getSymbol();
209 *file << "\t" << printCoordinate((*it)->atStep(0, step));
210 *file << "\t" << printCoordinate((*it)->atStep(1, step));
211 *file << "\t" << printCoordinate((*it)->atStep(2, step));
212 *file << endl;
213 }
214 }
215}
Note: See TracBrowser for help on using the repository browser.