source: src/Potentials/SerializablePotential.cpp@ a953c4

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

FIX: SerializablePotential::stream_from(), several fixes.

  • equalitysep with tokenizer would have required copying string. Hence, we simply copy and split via string functions as there is only one equality sign.
  • particle types index was off by one.
  • SetParticleType() did not check whether we actually needed to resize and was off by one.
  • Property mode set to 100644
File size: 6.1 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2012 University of Bonn. All rights reserved.
5 * Please see the COPYING file or "Copyright notice" in builder.cpp for details.
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 * SerializablePotential.cpp
26 *
27 * Created on: 23.11.2012
28 * Author: heber
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 "SerializablePotential.hpp"
39
40#include <algorithm>
41#include <boost/foreach.hpp>
42#include <boost/tokenizer.hpp>
43#include <iostream>
44#include <string>
45
46#include "CodePatterns/Assert.hpp"
47#include "CodePatterns/toString.hpp"
48
49#include "Potentials/Exceptions.hpp"
50
51std::ostream& operator<<(std::ostream &ost, const SerializablePotential &potential)
52{
53 potential.stream_to(ost);
54 return ost;
55}
56
57void SerializablePotential::stream_to(std::ostream &ost) const
58{
59 // check stream
60 if (ost.bad())
61 throw SerializablePotentialException();
62
63 /// print parameter key
64 ost << getToken() << ":";
65 /// print associated particles
66 const SerializablePotential::ParticleTypes_t &types = getParticleTypes();
67 for (size_t index=0; index < types.size(); ++index) {
68 ost << "\tparticle_type" << index+1 << "=" << types[index];
69 ost << (index != (types.size()-1) ? std::string(",") : std::string(""));
70 }
71 /// print coefficients
72 const SerializablePotential::ParameterNames_t &paramNames = getParameterNames();
73 const SerializablePotential::parameters_t &params = getParameters();
74 SerializablePotential::ParameterNames_t::const_iterator nameiter = paramNames.begin();
75 SerializablePotential::parameters_t::const_iterator valueiter = params.begin();
76 for (; valueiter != params.end(); ++valueiter, ++nameiter) {
77 ASSERT( nameiter != paramNames.end(),
78 "ManyBodyPotential_Tersoff::operator<<() - there are less names than parameters.");
79 if (*nameiter != std::string(""))
80 ost << ",\t" << *nameiter << "=" << *valueiter;
81 }
82 /// print terminating semi-colon
83 ost << ";";
84}
85
86std::istream& operator>>(std::istream &ist, SerializablePotential &potential)
87{
88 potential.stream_from(ist);
89 return ist;
90}
91
92void SerializablePotential::stream_from(std::istream &ist)
93{
94 // check stream
95 if (ist.bad())
96 throw SerializablePotentialException();
97
98 // create copy of current parameters, hence line may contain not all required
99 SerializablePotential::parameters_t params(getParameters());
100
101 // read in full line
102 std::string linestring;
103 getline(ist, linestring);
104 const std::string whitespace(" \t");
105 const size_t strBegin = linestring.find_first_not_of(whitespace);
106 const size_t colonpos = linestring.find(":");
107 if ((strBegin == std::string::npos) || (colonpos == std::string::npos) ||
108 (linestring.substr(strBegin, colonpos-1) != getToken()))
109 throw SerializablePotentialMissingValueException()
110 << SerializablePotentialKey(getName());
111
112 // tokenize by ","
113 typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
114 boost::char_separator<char> pairsep(",\t ;");
115 std::string remainderstring(linestring.substr(colonpos+1));
116 tokenizer tokens(remainderstring, pairsep); //skip colon
117
118 // step through each token
119 ConvertTo<size_t> ConvertToIndex;
120 ConvertTo<SerializablePotential::parameter_t> ConvertToValue;
121 ConvertTo<SerializablePotential::ParticleType_t> ConvertToParticleType;
122 for (tokenizer::iterator tok_iter = tokens.begin();
123 tok_iter != tokens.end(); ++tok_iter) {
124 const std::string &keyvalue = *tok_iter;
125 const size_t equalitypos = keyvalue.find("=");
126 const std::string key = keyvalue.substr(0,equalitypos);
127 const std::string value = keyvalue.substr(equalitypos+1);
128
129 /// parse the particle_types
130 const std::string typetoken("particle_type");
131 const size_t pos = key.find(typetoken);
132 if (pos != std::string::npos) {
133 // split of type and convert rest to index
134 const size_t indexpos = pos+typetoken.length();
135 const std::string &indexstring = key.substr(indexpos);
136 const size_t index = ConvertToIndex(indexstring);
137 if(index == 0)
138 throw SerializablePotentialMissingValueException() << SerializablePotentialKey(key);
139 // and set the type
140 if (equalitypos == std::string::npos)
141 throw SerializablePotentialMissingValueException() << SerializablePotentialKey(key);
142 setParticleType(index-1, ConvertToParticleType(value));
143 } else {
144 const size_t index = getParameterIndex(key);
145 // parse the coefficients
146 if (index != (size_t)-1) {
147 if (equalitypos == std::string::npos)
148 throw SerializablePotentialMissingValueException() << SerializablePotentialKey(key);
149 params[index] = ConvertToValue(value);
150 } else {
151 throw SerializablePotentialIllegalKeyException() << SerializablePotentialKey(key);
152 }
153 }
154 }
155
156 /// set the new paremeters
157 setParameters(params);
158}
159
160const size_t SerializablePotential::getParameterIndex(const std::string &_name) const
161{
162 const ParameterNames_t& ParameterNames = getParameterNames();
163 ParameterNames_t::const_iterator iter =
164 std::find(ParameterNames.begin(), ParameterNames.end(), _name);
165 if (iter == ParameterNames.end())
166 return (size_t)-1;
167 else
168 return std::distance(ParameterNames.begin(), iter);
169}
170
171const std::string SerializablePotential::getName() const
172{
173 std::string returnstring = getToken() + std::string("_");
174 BOOST_FOREACH(const ParticleType_t &type, getParticleTypes()) {
175 returnstring += toString(type);
176 }
177 return returnstring;
178}
Note: See TracBrowser for help on using the repository browser.