source: src/Formula.cpp@ 796aa6

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 796aa6 was ee86a0, checked in by Tillmann Crueger <crueger@…>, 14 years ago

Simplyfied formula parsing using range objects

  • Property mode set to 100644
File size: 13.1 KB
Line 
1/*
2 * Formula.cpp
3 *
4 * Created on: Jul 21, 2010
5 * Author: crueger
6 */
7
8#include "Formula.hpp"
9
10#include <sstream>
11
12#include "World.hpp"
13#include "periodentafel.hpp"
14#include "element.hpp"
15#include "Helpers/Assert.hpp"
16#include "Helpers/Range.hpp"
17
18using namespace std;
19
20Formula::Formula() :
21 numElements(0)
22{}
23
24Formula::Formula(const Formula &src) :
25 elementCounts(src.elementCounts),
26 numElements(src.numElements)
27{}
28
29Formula::Formula(const string &formula) :
30 numElements(0)
31{
32 fromString(formula);
33}
34
35Formula::~Formula()
36{}
37
38Formula &Formula::operator=(const Formula &rhs){
39 // No self-assignment check needed
40 elementCounts=rhs.elementCounts;
41 numElements=rhs.numElements;
42 return *this;
43}
44
45std::string Formula::toString() const{
46 stringstream sstr;
47 for(const_iterator iter=end();iter!=begin();){
48 --iter;
49 sstr << (*iter).first->symbol;
50 if((*iter).second>1)
51 sstr << (*iter).second;
52 }
53 return sstr.str();
54}
55
56void Formula::fromString(const std::string &formula) throw(ParseError){
57 // some constants needed for parsing... Assumes ASCII, change if other encodings are used
58 static const range<char> CapitalLetters = makeRange('A',static_cast<char>('Z'+1));
59 static const range<char> SmallLetters = makeRange('a',static_cast<char>('z'+1));
60 static const range<char> Numbers = makeRange('0',static_cast<char>('9'+1));
61 // clean the formula
62 clear();
63 string::const_iterator end = formula.end(); // will be used frequently
64 for(string::const_iterator it=formula.begin();it!=end;){
65 string shorthand;
66 // Atom names start with a capital letter
67 if(!CapitalLetters.isInRange(*it))
68 throw(ParseError(__FILE__,__LINE__));
69 shorthand+=(*it++);
70 // the rest of the name follows
71 while(it!=end && SmallLetters.isInRange(*it))
72 shorthand+=(*it++);
73 // now we can count the occurences
74 int count = 0;
75 while(it!=end && Numbers.isInRange(*it))
76 count = (count*10) + ((*it++)-Numbers.first);
77 // one is implicit
78 count = (count!=0)?count:1;
79 // test if the shorthand exists
80 if(!World::getInstance().getPeriode()->FindElement(shorthand))
81 throw(ParseError(__FILE__,__LINE__));
82 // done, we can get the next one
83 addElements(shorthand,count);
84 }
85}
86
87bool Formula::checkOut(ostream *output) const{
88 bool result = true;
89 int No = 1;
90
91 if (output != NULL) {
92 *output << "# Ion type data (PP = PseudoPotential, Z = atomic number)" << endl;
93 *output << "#Ion_TypeNr.\tAmount\tZ\tRGauss\tL_Max(PP)L_Loc(PP)IonMass\t# chemical name, symbol" << endl;
94 for(const_iterator iter=begin(); iter!=end();++iter){
95 (*iter).first->No = No;
96 result = result && (*iter).first->Checkout(output, No++, (*iter).second);
97 }
98 return result;
99 } else
100 return false;
101}
102
103unsigned int Formula::getElementCount() const{
104 return numElements;
105}
106
107bool Formula::hasElement(const element *element) const{
108 ASSERT(element,"Invalid pointer in Formula::hasElement(element*)");
109 return hasElement(element->getNumber());
110}
111
112bool Formula::hasElement(atomicNumber_t Z) const{
113 ASSERT(Z>0,"Invalid atomic Number");
114 ASSERT(World::getInstance().getPeriode()->FindElement(Z),"No Element with this number in Periodentafel");
115 return elementCounts.size()>=Z && elementCounts[Z-1];
116}
117
118bool Formula::hasElement(const string &shorthand) const{
119 element * element = World::getInstance().getPeriode()->FindElement(shorthand);
120 return hasElement(element);
121}
122
123void Formula::operator+=(const element *element){
124 ASSERT(element,"Invalid pointer in increment of Formula");
125 operator+=(element->getNumber());
126}
127
128void Formula::operator+=(atomicNumber_t Z){
129 ASSERT(Z>0,"Invalid atomic Number");
130 ASSERT(World::getInstance().getPeriode()->FindElement(Z),"No Element with this number in Periodentafel");
131 elementCounts.resize(max<atomicNumber_t>(Z,elementCounts.size()),0); // No-op when we already have the right size
132 // might need to update number of elements
133 if(!elementCounts[Z-1]){
134 numElements++;
135 }
136 elementCounts[Z-1]++; // atomic numbers start at 1
137}
138
139void Formula::operator+=(const string &shorthand){
140 element * element = World::getInstance().getPeriode()->FindElement(shorthand);
141 operator+=(element);
142}
143
144void Formula::operator-=(const element *element){
145 ASSERT(element,"Invalid pointer in decrement of Formula");
146 operator-=(element->getNumber());
147}
148
149void Formula::operator-=(atomicNumber_t Z){
150 ASSERT(Z>0,"Invalid atomic Number");
151 ASSERT(World::getInstance().getPeriode()->FindElement(Z),"No Element with this number in Periodentafel");
152 ASSERT(elementCounts.size()>=Z && elementCounts[Z-1], "Element not in Formula upon decrement");
153 elementCounts[Z-1]--; // atomic numbers start at 1
154 // might need to update number of elements
155 if(!elementCounts[Z-1]){
156 numElements--;
157 // resize the Array if this was at the last position
158 if(Z==elementCounts.size()){
159 // find the first element from the back that is not equal to zero
160 set_t::reverse_iterator riter = find_if(elementCounts.rbegin(),
161 elementCounts.rend(),
162 bind1st(not_equal_to<mapped_type>(),0));
163 // see how many elements are in this range
164 set_t::reverse_iterator::difference_type diff = riter - elementCounts.rbegin();
165 elementCounts.resize(elementCounts.size()-diff);
166 }
167 }
168}
169
170void Formula::operator-=(const string &shorthand){
171 element * element = World::getInstance().getPeriode()->FindElement(shorthand);
172 operator-=(element);
173}
174
175void Formula::addElements(const element *element,unsigned int count){
176 ASSERT(element,"Invalid pointer in Formula::addElements(element*)");
177 addElements(element->getNumber(),count);
178}
179
180void Formula::addElements(atomicNumber_t Z,unsigned int count){
181 if(count==0) return;
182 ASSERT(Z>0,"Invalid atomic Number");
183 ASSERT(World::getInstance().getPeriode()->FindElement(Z),"No Element with this number in Periodentafel");
184 elementCounts.resize(max<atomicNumber_t>(Z,elementCounts.size()),0); // No-op when we already have the right size
185 // might need to update number of elements
186 if(!elementCounts[Z-1]){
187 numElements++;
188 }
189 elementCounts[Z-1]+=count;
190}
191
192void Formula::addElements(const string &shorthand,unsigned int count){
193 element * element = World::getInstance().getPeriode()->FindElement(shorthand);
194 addElements(element,count);
195}
196
197const unsigned int Formula::operator[](const element *element) const{
198 ASSERT(element,"Invalid pointer in access of Formula");
199 return operator[](element->getNumber());
200}
201
202const unsigned int Formula::operator[](atomicNumber_t Z) const{
203 ASSERT(Z>0,"Invalid atomic Number");
204 ASSERT(World::getInstance().getPeriode()->FindElement(Z),"No Element with this number in Periodentafel");
205 if(elementCounts.size()<Z)
206 return 0;
207 return elementCounts[Z-1]; // atomic numbers start at 1
208}
209
210const unsigned int Formula::operator[](string shorthand) const{
211 element * element = World::getInstance().getPeriode()->FindElement(shorthand);
212 return operator[](element);
213}
214
215bool Formula::operator==(const Formula &rhs) const{
216 // quick check... number of elements used
217 if(numElements != rhs.numElements){
218 return false;
219 }
220 // second quick check, size of vectors (== last element in formula)
221 if(elementCounts.size()!=rhs.elementCounts.size()){
222 return false;
223 }
224 // slow check: all elements
225 // direct access to internal structure means all element-counts have to be compared
226 // this avoids access to periodentafel to find elements though and is probably faster
227 // in total
228 return equal(elementCounts.begin(),
229 elementCounts.end(),
230 rhs.elementCounts.begin());
231}
232
233bool Formula::operator!=(const Formula &rhs) const{
234 return !operator==(rhs);
235}
236
237Formula::iterator Formula::begin(){
238 return iterator(elementCounts,0);
239}
240Formula::const_iterator Formula::begin() const{
241 // this is the only place where this is needed, so this is better than making it mutable
242 return const_iterator(const_cast<set_t&>(elementCounts),0);
243}
244Formula::iterator Formula::end(){
245 return iterator(elementCounts);
246}
247Formula::const_iterator Formula::end() const{
248 // this is the only place where this is needed, so this is better than making it mutable
249 return const_iterator(const_cast<set_t&>(elementCounts));
250}
251
252void Formula::clear(){
253 elementCounts.clear();
254 numElements = 0;
255}
256
257/**************** Iterator structure ********************/
258
259template <class result_type>
260Formula::_iterator<result_type>::_iterator(set_t &_set) :
261 set(&_set)
262{
263 pos=set->size();
264}
265
266template <class result_type>
267Formula::_iterator<result_type>::_iterator(set_t &_set,size_t _pos) :
268 set(&_set),pos(_pos)
269{
270 ASSERT(pos<=set->size(),"invalid position in iterator construction");
271 while(pos<set->size() && (*set)[pos]==0) ++pos;
272}
273
274template <class result_type>
275Formula::_iterator<result_type>::_iterator(const _iterator &rhs) :
276 set(rhs.set),pos(rhs.pos)
277{}
278
279template <class result_type>
280Formula::_iterator<result_type>::~_iterator(){}
281
282template <class result_type>
283Formula::_iterator<result_type>&
284Formula::_iterator<result_type>::operator=(const _iterator<result_type> &rhs){
285 set=rhs.set;
286 pos=rhs.pos;
287 return *this;
288}
289
290template <class result_type>
291bool
292Formula::_iterator<result_type>::operator==(const _iterator<result_type> &rhs){
293 return set==rhs.set && pos==rhs.pos;
294}
295
296template <class result_type>
297bool
298Formula::_iterator<result_type>::operator!=(const _iterator<result_type> &rhs){
299 return !operator==(rhs);
300}
301
302template <class result_type>
303Formula::_iterator<result_type>
304Formula::_iterator<result_type>::operator++(){
305 ASSERT(pos!=set->size(),"Incrementing Formula::iterator beyond end");
306 pos++;
307 while(pos<set->size() && (*set)[pos]==0) ++pos;
308 return *this;
309}
310
311template <class result_type>
312Formula::_iterator<result_type>
313Formula::_iterator<result_type>::operator++(int){
314 Formula::_iterator<result_type> retval = *this;
315 ++(*this);
316 return retval;
317}
318
319template <class result_type>
320Formula::_iterator<result_type>
321Formula::_iterator<result_type>::operator--(){
322 ASSERT(pos!=0,"Decrementing Formula::iterator beyond begin");
323 pos--;
324 while(pos>0 && (*set)[pos]==0) --pos;
325 return *this;
326}
327
328template <class result_type>
329Formula::_iterator<result_type>
330Formula::_iterator<result_type>::operator--(int){
331 Formula::_iterator<result_type> retval = *this;
332 --(*this);
333 return retval;
334}
335
336template <class result_type>
337result_type
338Formula::_iterator<result_type>::operator*(){
339 element *element = World::getInstance().getPeriode()->FindElement(pos+1);
340 ASSERT(element,"Element with position of iterator not found");
341 return make_pair(element,(*set)[pos]);
342}
343
344template <class result_type>
345result_type*
346Formula::_iterator<result_type>::operator->(){
347 // no one can keep this value around, so a static is ok to avoid temporaries
348 static value_type value=make_pair(reinterpret_cast<element*>(0),0); // no default constructor for std::pair
349 element *element = World::getInstance().getPeriode()->FindElement(pos+1);
350 ASSERT(element,"Element with position of iterator not found");
351 value = make_pair(element,(*set)[pos]);
352 return &value;
353}
354
355// explicit instantiation of all iterator template methods
356// this is quite ugly, but there is no better way unless we expose iterator implementation
357
358// instantiate Formula::iterator
359template Formula::iterator::_iterator(set_t&);
360template Formula::iterator::_iterator(set_t&,size_t);
361template Formula::iterator::_iterator(const Formula::iterator&);
362template Formula::iterator::~_iterator();
363template Formula::iterator &Formula::iterator::operator=(const Formula::iterator&);
364template bool Formula::iterator::operator==(const Formula::iterator&);
365template bool Formula::iterator::operator!=(const Formula::iterator&);
366template Formula::iterator Formula::iterator::operator++();
367template Formula::iterator Formula::iterator::operator++(int);
368template Formula::iterator Formula::iterator::operator--();
369template Formula::iterator Formula::iterator::operator--(int);
370template Formula::value_type Formula::iterator::operator*();
371template Formula::value_type *Formula::iterator::operator->();
372
373// instantiate Formula::const_iterator
374template Formula::const_iterator::_iterator(set_t&);
375template Formula::const_iterator::_iterator(set_t&,size_t);
376template Formula::const_iterator::_iterator(const Formula::const_iterator&);
377template Formula::const_iterator::~_iterator();
378template Formula::const_iterator &Formula::const_iterator::operator=(const Formula::const_iterator&);
379template bool Formula::const_iterator::operator==(const Formula::const_iterator&);
380template bool Formula::const_iterator::operator!=(const Formula::const_iterator&);
381template Formula::const_iterator Formula::const_iterator::operator++();
382template Formula::Formula::const_iterator Formula::const_iterator::operator++(int);
383template Formula::Formula::const_iterator Formula::const_iterator::operator--();
384template Formula::Formula::const_iterator Formula::const_iterator::operator--(int);
385template const Formula::value_type Formula::const_iterator::operator*();
386template const Formula::value_type *Formula::const_iterator::operator->();
387
388/********************** I/O of Formulas ************************************************/
389
390std::ostream &operator<<(std::ostream &ost,const Formula &formula){
391 ost << formula.toString();
392 return ost;
393}
Note: See TracBrowser for help on using the repository browser.