source: src/Parser/XyzParser.cpp@ 0180d6

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

Enhanced XyzParser to load and save multiple time steps.

  • Property mode set to 100644
File size: 5.2 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * XyzParser.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/Log.hpp"
23#include "CodePatterns/Verbose.hpp"
24#include "XyzParser.hpp"
25#include "World.hpp"
26#include "atom.hpp"
27#include "molecule.hpp"
28#include "element.hpp"
29#include "periodentafel.hpp"
30
31using namespace std;
32
33/**
34 * Constructor.
35 */
36XyzParser::XyzParser() :
37 comment("")
38{}
39
40/**
41 * Destructor.
42 */
43XyzParser::~XyzParser() {
44}
45
46/**
47 * Loads an XYZ file into the World.
48 *
49 * \param XYZ file
50 */
51void XyzParser::load(istream* file)
52{
53 atom* newAtom = NULL;
54 molecule* newmol = NULL;
55 int numberOfAtoms;
56 char commentBuffer[512], type[3];
57 string number;
58 std::list<atom *> AddedAtoms;
59
60 // create the molecule
61 newmol = World::getInstance().createMolecule();
62 newmol->ActiveFlag = true;
63 // TODO: Remove the insertion into molecule when saving does not depend on them anymore. Also, remove molecule.hpp include
64 World::getInstance().getMolecules()->insert(newmol);
65
66 // the first line tells number of atoms,
67 // where we need this construct due to skipping of empty lines below
68 *file >> number >> ws;
69 unsigned int step = 0;
70 std::list<atom *>::iterator CurrentAtom;
71 do {
72 CurrentAtom = AddedAtoms.begin();
73 std::stringstream numberstream(number);
74 numberstream >> numberOfAtoms;
75 // the second line is always a comment
76 file->getline(commentBuffer, 512);
77 comment = commentBuffer;
78
79 for (int i = 0; i < numberOfAtoms; i++) {
80 // parse type and position
81 *file >> type;
82 Vector tempVector;
83 for (int j=0;j<NDIM;j++) {
84 *file >> tempVector[j];
85 }
86 LOG(4, "INFO: Parsed type as " << type << " and position at "
87 << tempVector << " for time step " << step);
88
89 if (step == 0) {
90 newAtom = World::getInstance().createAtom();
91 newAtom->setType(World::getInstance().getPeriode()->FindElement(type));
92 newmol->AddAtom(newAtom);
93 AddedAtoms.push_back(newAtom);
94 LOG(5, "INFO: Created new atom.");
95 } else {
96 ASSERT(CurrentAtom != AddedAtoms.end(),
97 "XyzParser::load() - not enough added atoms.");
98 newAtom = *CurrentAtom++;
99 ASSERT(newAtom->getType() == World::getInstance().getPeriode()->FindElement(type),
100 "XyzParser::load() - atom has different type, mixed up order?");
101 LOG(5, "INFO: Using present atom " << *newAtom << ".");
102 }
103 newAtom->setPositionAtStep(step, tempVector);
104 }
105 getline (*file, number); // eat away rest of last line
106 // skip empty lines
107 unsigned int counter = 0;
108 while (file->good()) {
109 getline (*file, number);
110 LOG(4, "INFO: Skipped line is '" << number << "'");
111 counter++;
112 if (!number.empty())
113 break;
114 }
115 LOG(3, "INFO: I skipped "+toString(counter)+" empty lines.");
116 ++step;
117 } while (file->good());
118 BOOST_FOREACH(atom *_atom, World::getInstance().getAllAtoms())
119 LOG(3, "INFO: Atom " << _atom->getName() << " " << *dynamic_cast<AtomInfo *>(_atom) << ".");
120}
121
122/**
123 * Saves the \a atoms into as a XYZ file.
124 *
125 * \param file where to save the state
126 * \param atoms atoms to store
127 */
128void XyzParser::save(ostream* file, const std::vector<atom *> &atoms) {
129 DoLog(0) && (Log() << Verbose(0) << "Saving changes to xyz." << std::endl);
130
131 // get max and min trajectories
132 unsigned int min_trajectories = 1;
133 unsigned int max_trajectories = 1;
134 for (std::vector<atom *>::const_iterator iter = atoms.begin();
135 iter != atoms.end();
136 ++iter) {
137 if (max_trajectories < (*iter)->getTrajectorySize())
138 max_trajectories = (*iter)->getTrajectorySize();
139 if ((min_trajectories > (*iter)->getTrajectorySize())
140 && (max_trajectories > (*iter)->getTrajectorySize()))
141 min_trajectories = (*iter)->getTrajectorySize();
142 }
143 ASSERT((min_trajectories == max_trajectories) || (min_trajectories == 1),
144 "XyzParser::save() - not all atoms have same number of trajectories.");
145 LOG(2, "INFO: There are " << max_trajectories << " to save.");
146
147 for (unsigned int step = 0; step < max_trajectories; ++step) {
148 if (step != 0)
149 *file << "\n";
150 //if (comment == "") {
151 time_t now = time((time_t *)NULL); // Get the system time and put it into 'now' as 'calender time'
152 comment = "Created by molecuilder on ";
153 // ctime ends in \n\0, we have to cut away the newline
154 std::string time(ctime(&now));
155 size_t pos = time.find('\n');
156 if (pos != 0)
157 comment += time.substr(0,pos);
158 else
159 comment += time;
160 comment += ", time step "+toString(step);
161 //}
162 *file << atoms.size() << endl << "\t" << comment << endl;
163
164 for(vector<atom*>::const_iterator it = atoms.begin(); it != atoms.end(); it++) {
165 *file << noshowpoint << (*it)->getType()->getSymbol();
166 *file << "\t" << (*it)->atStep(0, step);
167 *file << "\t" << (*it)->atStep(1, step);
168 *file << "\t" << (*it)->atStep(2, step);
169 *file << endl;
170 }
171 }
172}
Note: See TracBrowser for help on using the repository browser.