source: src/molecule.cpp@ a063787

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

FIX: Removed double coding in molecule::erase().

  • Property mode set to 100755
File size: 41.1 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 * Copyright (C) 2013 Frederik Heber. All rights reserved.
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/** \file molecules.cpp
25 *
26 * Functions for the class molecule.
27 *
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 <algorithm>
38#include <boost/bind.hpp>
39#include <boost/foreach.hpp>
40#include <cstring>
41
42#include <gsl/gsl_inline.h>
43#include <gsl/gsl_heapsort.h>
44
45#include "molecule.hpp"
46
47#include "Atom/atom.hpp"
48#include "Bond/bond.hpp"
49#include "Box.hpp"
50#include "CodePatterns/enumeration.hpp"
51#include "CodePatterns/Log.hpp"
52#include "CodePatterns/Observer/Notification.hpp"
53#include "config.hpp"
54#include "Descriptors/AtomIdDescriptor.hpp"
55#include "Element/element.hpp"
56#include "Graph/BondGraph.hpp"
57#include "LinearAlgebra/Exceptions.hpp"
58#include "LinearAlgebra/leastsquaremin.hpp"
59#include "LinearAlgebra/Plane.hpp"
60#include "LinearAlgebra/RealSpaceMatrix.hpp"
61#include "LinearAlgebra/Vector.hpp"
62#include "LinkedCell/linkedcell.hpp"
63#include "IdPool_impl.hpp"
64#include "Shapes/BaseShapes.hpp"
65#include "Tesselation/tesselation.hpp"
66#include "World.hpp"
67#include "WorldTime.hpp"
68
69
70/************************************* Functions for class molecule *********************************/
71
72/** Constructor of class molecule.
73 * Initialises molecule list with correctly referenced start and end, and sets molecule::last_atom to zero.
74 */
75molecule::molecule() :
76 Observable("molecule"),
77 MDSteps(0),
78 NoNonBonds(0),
79 NoCyclicBonds(0),
80 ActiveFlag(false),
81 IndexNr(-1),
82 NoNonHydrogen(this,boost::bind(&molecule::doCountNoNonHydrogen,this),"NoNonHydrogen"),
83 BondCount(this,boost::bind(&molecule::doCountBonds,this),"BondCount"),
84 atomIdPool(1, 20, 100),
85 _lastchangedatomid(-1),
86 last_atom(0)
87{
88 // add specific channels
89 Channels *OurChannel = new Channels;
90 Observable::insertNotificationChannel( std::make_pair( static_cast<Observable *>(this), OurChannel) );
91 for (size_t type = 0; type < (size_t)NotificationType_MAX; ++type)
92 OurChannel->addChannel(type);
93
94 strcpy(name,World::getInstance().getDefaultName().c_str());
95};
96
97molecule *NewMolecule(){
98 return new molecule();
99}
100
101/** Destructor of class molecule.
102 * Initialises molecule list with correctly referenced start and end, and sets molecule::last_atom to zero.
103 */
104molecule::~molecule()
105{
106 // inform all UI elements about imminent removal before anything is lost
107 {
108 OBSERVE;
109 NOTIFY(AboutToBeRemoved);
110 }
111 CleanupMolecule();
112};
113
114
115void DeleteMolecule(molecule *mol){
116 delete mol;
117}
118
119// getter and setter
120const std::string molecule::getName() const{
121 return std::string(name);
122}
123
124int molecule::getAtomCount() const{
125 return atomIds.size();
126}
127
128size_t molecule::getNoNonHydrogen() const{
129 return *NoNonHydrogen;
130}
131
132int molecule::getBondCount() const{
133 return *BondCount;
134}
135
136void molecule::setName(const std::string _name){
137 OBSERVE;
138 NOTIFY(MoleculeNameChanged);
139 cout << "Set name of molecule " << getId() << " to " << _name << endl;
140 strncpy(name,_name.c_str(),MAXSTRINGSIZE);
141}
142
143void molecule::InsertLocalToGlobalId(atom * const pointer)
144{
145#ifndef NDEBUG
146 std::pair< LocalToGlobalId_t::iterator, bool > inserter =
147#endif
148 LocalToGlobalId.insert( std::make_pair(pointer->getNr(), pointer) );
149 ASSERT( inserter.second,
150 "molecule::AddAtom() - local number "+toString(pointer->getNr())+" appears twice.");
151}
152
153bool molecule::changeAtomNr(int oldNr, int newNr, atom* target){
154 OBSERVE;
155 if(atomIdPool.reserveId(newNr)){
156 NOTIFY(AtomNrChanged);
157 if (oldNr != -1) // -1 is reserved and indicates no number
158 atomIdPool.releaseId(oldNr);
159 LocalToGlobalId.erase(oldNr);
160 ASSERT (target,
161 "molecule::changeAtomNr() - given target is NULL, cannot set Nr or name.");
162 target->setNr(newNr);
163 _lastchangedatomid = target->getId();
164 InsertLocalToGlobalId(target);
165 setAtomName(target);
166 return true;
167 } else{
168 return false;
169 }
170}
171
172bool molecule::changeAtomId(int oldId, int newId)
173{
174 OBSERVE;
175 if ((!atomIds.contains( oldId )) || (atomIds.contains( newId )))
176 return false;
177 atomIds.erase( oldId );
178 atomIds.insert( newId );
179 return true;
180}
181
182bool molecule::changeId(moleculeId_t newId){
183 // first we move ourselves in the world
184 // the world lets us know if that succeeded
185 if(World::getInstance().changeMoleculeId(id,newId,this)){
186 OBSERVE;
187 NOTIFY(IndexChanged);
188 id = newId;
189 return true;
190 }
191 else{
192 return false;
193 }
194}
195
196
197moleculeId_t molecule::getId() const {
198 return id;
199}
200
201void molecule::setId(moleculeId_t _id){
202 id =_id;
203}
204
205const Formula &molecule::getFormula() const {
206 return formula;
207}
208
209unsigned int molecule::getElementCount() const{
210 return formula.getElementCount();
211}
212
213bool molecule::hasElement(const element *element) const{
214 return formula.hasElement(element);
215}
216
217bool molecule::hasElement(atomicNumber_t Z) const{
218 return formula.hasElement(Z);
219}
220
221bool molecule::hasElement(const string &shorthand) const{
222 return formula.hasElement(shorthand);
223}
224
225/************************** Access to the List of Atoms ****************/
226
227molecule::const_iterator molecule::erase( const_iterator loc )
228{
229 OBSERVE;
230 const_iterator iter = loc;
231 ++iter;
232 atom * const _atom = const_cast<atom *>(*loc);
233 {
234 _lastchangedatomid = _atom->getId();
235 NOTIFY(AtomRemoved);
236 }
237 atomIds.erase( _atom->getId() );
238 {
239 NOTIFY(AtomNrChanged);
240 atomIdPool.releaseId(_atom->getNr());
241 LocalToGlobalId.erase(_atom->getNr());
242 _atom->setNr(-1);
243 }
244 NOTIFY(FormulaChanged);
245 formula-=_atom->getType();
246 _atom->removeFromMolecule();
247 return iter;
248}
249
250molecule::const_iterator molecule::erase( atom * key )
251{
252 const_iterator iter = const_cast<const molecule &>(*this).find(key);
253 if (iter != const_cast<const molecule &>(*this).end())
254 return erase(iter);
255 else
256 return iter;
257}
258
259pair<molecule::iterator,bool> molecule::insert ( atom * const key )
260{
261 OBSERVE;
262 NOTIFY(AtomInserted);
263 _lastchangedatomid = key->getId();
264 std::pair<iterator,bool> res = atomIds.insert(key->getId());
265 if (res.second) { // push atom if went well
266 NOTIFY(AtomNrChanged);
267 key->setNr(atomIdPool.getNextId());
268 InsertLocalToGlobalId(key);
269 setAtomName(key);
270 NOTIFY(FormulaChanged);
271 formula+=key->getType();
272 return res;
273 } else {
274 return pair<iterator,bool>(end(),res.second);
275 }
276}
277
278void molecule::setAtomName(atom *_atom) const
279{
280 std::stringstream sstr;
281 sstr << _atom->getType()->getSymbol() << _atom->getNr();
282 _atom->setName(sstr.str());
283}
284
285World::AtomComposite molecule::getAtomSet()
286{
287 World::AtomComposite vector_of_atoms;
288 for (molecule::iterator iter = begin(); iter != end(); ++iter)
289 vector_of_atoms.push_back(*iter);
290 return vector_of_atoms;
291}
292
293World::ConstAtomComposite molecule::getAtomSet() const
294{
295 World::ConstAtomComposite vector_of_atoms;
296 for (molecule::const_iterator iter = begin(); iter != end(); ++iter)
297 vector_of_atoms.push_back(*iter);
298 return vector_of_atoms;
299}
300
301/** Adds given atom \a *pointer from molecule list.
302 * Increases molecule::last_atom and gives last number to added atom and names it according to its element::abbrev and molecule::AtomCount
303 * \param *pointer allocated and set atom
304 * \return true - succeeded, false - atom not found in list
305 */
306bool molecule::AddAtom(atom *pointer)
307{
308 if (pointer != NULL) {
309 // molecule::insert() is called by setMolecule()
310 pointer->setMolecule(this);
311 }
312 return true;
313};
314
315/** Adds a copy of the given atom \a *pointer from molecule list.
316 * Increases molecule::last_atom and gives last number to added atom.
317 * \param *pointer allocated and set atom
318 * \return pointer to the newly added atom
319 */
320atom * molecule::AddCopyAtom(atom *pointer)
321{
322 atom *retval = NULL;
323 if (pointer != NULL) {
324 atom *walker = pointer->clone();
325 AddAtom(walker);
326 retval=walker;
327 }
328 return retval;
329};
330
331/** Adds a Hydrogen atom in replacement for the given atom \a *partner in bond with a *origin.
332 * Here, we have to distinguish between single, double or triple bonds as stated by \a BondDegree, that each demand
333 * a different scheme when adding \a *replacement atom for the given one.
334 * -# Single Bond: Simply add new atom with bond distance rescaled to typical hydrogen one
335 * -# Double Bond: Here, we need the **BondList of the \a *origin atom, by scanning for the other bonds instead of
336 * *Bond, we use the through these connected atoms to determine the plane they lie in, vector::MakeNormalvector().
337 * The orthonormal vector to this plane along with the vector in *Bond direction determines the plane the two
338 * replacing hydrogens shall lie in. Now, all remains to do is take the usual hydrogen double bond angle for the
339 * element of *origin and form the sin/cos admixture of both plane vectors for the new coordinates of the two
340 * hydrogens forming this angle with *origin.
341 * -# Triple Bond: The idea is to set up a tetraoid (C1-H1-H2-H3) (however the lengths \f$b\f$ of the sides of the base
342 * triangle formed by the to be added hydrogens are not equal to the typical bond distance \f$l\f$ but have to be
343 * determined from the typical angle \f$\alpha\f$ for a hydrogen triple connected to the element of *origin):
344 * We have the height \f$d\f$ as the vector in *Bond direction (from triangle C1-H1-H2).
345 * \f[ h = l \cdot \cos{\left (\frac{\alpha}{2} \right )} \qquad b = 2l \cdot \sin{\left (\frac{\alpha}{2} \right)} \quad \rightarrow \quad d = l \cdot \sqrt{\cos^2{\left (\frac{\alpha}{2} \right)}-\frac{1}{3}\cdot\sin^2{\left (\frac{\alpha}{2}\right )}}
346 * \f]
347 * vector::GetNormalvector() creates one orthonormal vector from this *Bond vector and vector::MakeNormalvector creates
348 * the third one from the former two vectors. The latter ones form the plane of the base triangle mentioned above.
349 * The lengths for these are \f$f\f$ and \f$g\f$ (from triangle H1-H2-(center of H1-H2-H3)) with knowledge that
350 * the median lines in an isosceles triangle meet in the center point with a ratio 2:1.
351 * \f[ f = \frac{b}{\sqrt{3}} \qquad g = \frac{b}{2}
352 * \f]
353 * as the coordination of all three atoms in the coordinate system of these three vectors:
354 * \f$\pmatrix{d & f & 0}\f$, \f$\pmatrix{d & -0.5 \cdot f & g}\f$ and \f$\pmatrix{d & -0.5 \cdot f & -g}\f$.
355 *
356 * \param *out output stream for debugging
357 * \param *Bond pointer to bond between \a *origin and \a *replacement
358 * \param *TopOrigin son of \a *origin of upper level molecule (the atom added to this molecule as a copy of \a *origin)
359 * \param *origin pointer to atom which acts as the origin for scaling the added hydrogen to correct bond length
360 * \param *replacement pointer to the atom which shall be copied as a hydrogen atom in this molecule
361 * \param isAngstroem whether the coordination of the given atoms is in AtomicLength (false) or Angstrom(true)
362 * \return number of atoms added, if < bond::BondDegree then something went wrong
363 * \todo double and triple bonds splitting (always use the tetraeder angle!)
364 */
365//bool molecule::AddHydrogenReplacementAtom(bond::ptr TopBond, atom *BottomOrigin, atom *TopOrigin, atom *TopReplacement, bool IsAngstroem)
366//{
367//// Info info(__func__);
368// bool AllWentWell = true; // flag gathering the boolean return value of molecule::AddAtom and other functions, as return value on exit
369// double bondlength; // bond length of the bond to be replaced/cut
370// double bondangle; // bond angle of the bond to be replaced/cut
371// double BondRescale; // rescale value for the hydrogen bond length
372// bond::ptr FirstBond;
373// bond::ptr SecondBond; // Other bonds in double bond case to determine "other" plane
374// atom *FirstOtherAtom = NULL, *SecondOtherAtom = NULL, *ThirdOtherAtom = NULL; // pointer to hydrogen atoms to be added
375// double b,l,d,f,g, alpha, factors[NDIM]; // hold temporary values in triple bond case for coordination determination
376// Vector Orthovector1, Orthovector2; // temporary vectors in coordination construction
377// Vector InBondvector; // vector in direction of *Bond
378// const RealSpaceMatrix &matrix = World::getInstance().getDomain().getM();
379// bond::ptr Binder;
380//
381// // create vector in direction of bond
382// InBondvector = TopReplacement->getPosition() - TopOrigin->getPosition();
383// bondlength = InBondvector.Norm();
384//
385// // is greater than typical bond distance? Then we have to correct periodically
386// // the problem is not the H being out of the box, but InBondvector have the wrong direction
387// // due to TopReplacement or Origin being on the wrong side!
388// const BondGraph * const BG = World::getInstance().getBondGraph();
389// const range<double> MinMaxBondDistance(
390// BG->getMinMaxDistance(TopOrigin,TopReplacement));
391// if (!MinMaxBondDistance.isInRange(bondlength)) {
392//// LOG(4, "InBondvector is: " << InBondvector << ".");
393// Orthovector1.Zero();
394// for (int i=NDIM;i--;) {
395// l = TopReplacement->at(i) - TopOrigin->at(i);
396// if (fabs(l) > MinMaxBondDistance.last) { // is component greater than bond distance (check against min not useful here)
397// Orthovector1[i] = (l < 0) ? -1. : +1.;
398// } // (signs are correct, was tested!)
399// }
400// Orthovector1 *= matrix;
401// InBondvector -= Orthovector1; // subtract just the additional translation
402// bondlength = InBondvector.Norm();
403//// LOG(4, "INFO: Corrected InBondvector is now: " << InBondvector << ".");
404// } // periodic correction finished
405//
406// InBondvector.Normalize();
407// // get typical bond length and store as scale factor for later
408// ASSERT(TopOrigin->getType() != NULL, "AddHydrogenReplacementAtom: element of TopOrigin is not given.");
409// BondRescale = TopOrigin->getType()->getHBondDistance(TopBond->getDegree()-1);
410// if (BondRescale == -1) {
411// ELOG(1, "There is no typical hydrogen bond distance in replacing bond (" << TopOrigin->getName() << "<->" << TopReplacement->getName() << ") of degree " << TopBond->getDegree() << "!");
412// return false;
413// BondRescale = bondlength;
414// } else {
415// if (!IsAngstroem)
416// BondRescale /= (1.*AtomicLengthToAngstroem);
417// }
418//
419// // discern single, double and triple bonds
420// switch(TopBond->getDegree()) {
421// case 1:
422// FirstOtherAtom = World::getInstance().createAtom(); // new atom
423// FirstOtherAtom->setType(1); // element is Hydrogen
424// FirstOtherAtom->setAtomicVelocity(TopReplacement->getAtomicVelocity()); // copy velocity
425// FirstOtherAtom->setFixedIon(TopReplacement->getFixedIon());
426// if (TopReplacement->getType()->getAtomicNumber() == 1) { // neither rescale nor replace if it's already hydrogen
427// FirstOtherAtom->father = TopReplacement;
428// BondRescale = bondlength;
429// } else {
430// FirstOtherAtom->father = NULL; // if we replace hydrogen, we mark it as our father, otherwise we are just an added hydrogen with no father
431// }
432// InBondvector *= BondRescale; // rescale the distance vector to Hydrogen bond length
433// FirstOtherAtom->setPosition(TopOrigin->getPosition() + InBondvector); // set coordination to origin and add distance vector to replacement atom
434// AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
435//// LOG(4, "INFO: Added " << *FirstOtherAtom << " at: " << FirstOtherAtom->x << ".");
436// Binder = AddBond(BottomOrigin, FirstOtherAtom, 1);
437// Binder->Cyclic = false;
438// Binder->Type = GraphEdge::TreeEdge;
439// break;
440// case 2:
441// {
442// // determine two other bonds (warning if there are more than two other) plus valence sanity check
443// const BondList& ListOfBonds = TopOrigin->getListOfBonds();
444// for (BondList::const_iterator Runner = ListOfBonds.begin();
445// Runner != ListOfBonds.end();
446// ++Runner) {
447// if ((*Runner) != TopBond) {
448// if (FirstBond == NULL) {
449// FirstBond = (*Runner);
450// FirstOtherAtom = (*Runner)->GetOtherAtom(TopOrigin);
451// } else if (SecondBond == NULL) {
452// SecondBond = (*Runner);
453// SecondOtherAtom = (*Runner)->GetOtherAtom(TopOrigin);
454// } else {
455// ELOG(2, "Detected more than four bonds for atom " << TopOrigin->getName());
456// }
457// }
458// }
459// }
460// if (SecondOtherAtom == NULL) { // then we have an atom with valence four, but only 3 bonds: one to replace and one which is TopBond (third is FirstBond)
461// SecondBond = TopBond;
462// SecondOtherAtom = TopReplacement;
463// }
464// if (FirstOtherAtom != NULL) { // then we just have this double bond and the plane does not matter at all
465//// LOG(3, "Regarding the double bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") to be constructed: Taking " << FirstOtherAtom->Name << " and " << SecondOtherAtom->Name << " along with " << TopOrigin->Name << " to determine orthogonal plane.");
466//
467// // determine the plane of these two with the *origin
468// try {
469// Orthovector1 = Plane(TopOrigin->getPosition(), FirstOtherAtom->getPosition(), SecondOtherAtom->getPosition()).getNormal();
470// }
471// catch(LinearDependenceException &excp){
472// LOG(0, boost::diagnostic_information(excp));
473// // TODO: figure out what to do with the Orthovector in this case
474// AllWentWell = false;
475// }
476// } else {
477// Orthovector1.GetOneNormalVector(InBondvector);
478// }
479// //LOG(3, "INFO: Orthovector1: " << Orthovector1 << ".");
480// // orthogonal vector and bond vector between origin and replacement form the new plane
481// Orthovector1.MakeNormalTo(InBondvector);
482// Orthovector1.Normalize();
483// //LOG(3, "ReScaleCheck: " << Orthovector1.Norm() << " and " << InBondvector.Norm() << ".");
484//
485// // create the two Hydrogens ...
486// FirstOtherAtom = World::getInstance().createAtom();
487// SecondOtherAtom = World::getInstance().createAtom();
488// FirstOtherAtom->setType(1);
489// SecondOtherAtom->setType(1);
490// FirstOtherAtom->setAtomicVelocity(TopReplacement->getAtomicVelocity()); // copy velocity
491// FirstOtherAtom->setFixedIon(TopReplacement->getFixedIon());
492// SecondOtherAtom->setAtomicVelocity(TopReplacement->getAtomicVelocity()); // copy velocity
493// SecondOtherAtom->setFixedIon(TopReplacement->getFixedIon());
494// FirstOtherAtom->father = NULL; // we are just an added hydrogen with no father
495// SecondOtherAtom->father = NULL; // we are just an added hydrogen with no father
496// bondangle = TopOrigin->getType()->getHBondAngle(1);
497// if (bondangle == -1) {
498// ELOG(1, "There is no typical hydrogen bond angle in replacing bond (" << TopOrigin->getName() << "<->" << TopReplacement->getName() << ") of degree " << TopBond->getDegree() << "!");
499// return false;
500// bondangle = 0;
501// }
502// bondangle *= M_PI/180./2.;
503//// LOG(3, "INFO: ReScaleCheck: InBondvector " << InBondvector << ", " << Orthovector1 << ".");
504//// LOG(3, "Half the bond angle is " << bondangle << ", sin and cos of it: " << sin(bondangle) << ", " << cos(bondangle));
505// FirstOtherAtom->Zero();
506// SecondOtherAtom->Zero();
507// for(int i=NDIM;i--;) { // rotate by half the bond angle in both directions (InBondvector is bondangle = 0 direction)
508// FirstOtherAtom->set(i, InBondvector[i] * cos(bondangle) + Orthovector1[i] * (sin(bondangle)));
509// SecondOtherAtom->set(i, InBondvector[i] * cos(bondangle) + Orthovector1[i] * (-sin(bondangle)));
510// }
511// FirstOtherAtom->Scale(BondRescale); // rescale by correct BondDistance
512// SecondOtherAtom->Scale(BondRescale);
513// //LOG(3, "ReScaleCheck: " << FirstOtherAtom->x.Norm() << " and " << SecondOtherAtom->x.Norm() << ".");
514// *FirstOtherAtom += TopOrigin->getPosition();
515// *SecondOtherAtom += TopOrigin->getPosition();
516// // ... and add to molecule
517// AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
518// AllWentWell = AllWentWell && AddAtom(SecondOtherAtom);
519//// LOG(4, "INFO: Added " << *FirstOtherAtom << " at: " << FirstOtherAtom->x << ".");
520//// LOG(4, "INFO: Added " << *SecondOtherAtom << " at: " << SecondOtherAtom->x << ".");
521// Binder = AddBond(BottomOrigin, FirstOtherAtom, 1);
522// Binder->Cyclic = false;
523// Binder->Type = GraphEdge::TreeEdge;
524// Binder = AddBond(BottomOrigin, SecondOtherAtom, 1);
525// Binder->Cyclic = false;
526// Binder->Type = GraphEdge::TreeEdge;
527// break;
528// case 3:
529// // take the "usual" tetraoidal angle and add the three Hydrogen in direction of the bond (height of the tetraoid)
530// FirstOtherAtom = World::getInstance().createAtom();
531// SecondOtherAtom = World::getInstance().createAtom();
532// ThirdOtherAtom = World::getInstance().createAtom();
533// FirstOtherAtom->setType(1);
534// SecondOtherAtom->setType(1);
535// ThirdOtherAtom->setType(1);
536// FirstOtherAtom->setAtomicVelocity(TopReplacement->getAtomicVelocity()); // copy velocity
537// FirstOtherAtom->setFixedIon(TopReplacement->getFixedIon());
538// SecondOtherAtom->setAtomicVelocity(TopReplacement->getAtomicVelocity()); // copy velocity
539// SecondOtherAtom->setFixedIon(TopReplacement->getFixedIon());
540// ThirdOtherAtom->setAtomicVelocity(TopReplacement->getAtomicVelocity()); // copy velocity
541// ThirdOtherAtom->setFixedIon(TopReplacement->getFixedIon());
542// FirstOtherAtom->father = NULL; // we are just an added hydrogen with no father
543// SecondOtherAtom->father = NULL; // we are just an added hydrogen with no father
544// ThirdOtherAtom->father = NULL; // we are just an added hydrogen with no father
545//
546// // we need to vectors orthonormal the InBondvector
547// AllWentWell = AllWentWell && Orthovector1.GetOneNormalVector(InBondvector);
548//// LOG(3, "INFO: Orthovector1: " << Orthovector1 << ".");
549// try{
550// Orthovector2 = Plane(InBondvector, Orthovector1,0).getNormal();
551// }
552// catch(LinearDependenceException &excp) {
553// LOG(0, boost::diagnostic_information(excp));
554// AllWentWell = false;
555// }
556//// LOG(3, "INFO: Orthovector2: " << Orthovector2 << ".")
557//
558// // create correct coordination for the three atoms
559// alpha = (TopOrigin->getType()->getHBondAngle(2))/180.*M_PI/2.; // retrieve triple bond angle from database
560// l = BondRescale; // desired bond length
561// b = 2.*l*sin(alpha); // base length of isosceles triangle
562// d = l*sqrt(cos(alpha)*cos(alpha) - sin(alpha)*sin(alpha)/3.); // length for InBondvector
563// f = b/sqrt(3.); // length for Orthvector1
564// g = b/2.; // length for Orthvector2
565//// LOG(3, "Bond length and half-angle: " << l << ", " << alpha << "\t (b,d,f,g) = " << b << ", " << d << ", " << f << ", " << g << ", ");
566//// LOG(3, "The three Bond lengths: " << sqrt(d*d+f*f) << ", " << sqrt(d*d+(-0.5*f)*(-0.5*f)+g*g) << ", " << sqrt(d*d+(-0.5*f)*(-0.5*f)+g*g));
567// factors[0] = d;
568// factors[1] = f;
569// factors[2] = 0.;
570// FirstOtherAtom->LinearCombinationOfVectors(InBondvector, Orthovector1, Orthovector2, factors);
571// factors[1] = -0.5*f;
572// factors[2] = g;
573// SecondOtherAtom->LinearCombinationOfVectors(InBondvector, Orthovector1, Orthovector2, factors);
574// factors[2] = -g;
575// ThirdOtherAtom->LinearCombinationOfVectors(InBondvector, Orthovector1, Orthovector2, factors);
576//
577// // rescale each to correct BondDistance
578//// FirstOtherAtom->x.Scale(&BondRescale);
579//// SecondOtherAtom->x.Scale(&BondRescale);
580//// ThirdOtherAtom->x.Scale(&BondRescale);
581//
582// // and relative to *origin atom
583// *FirstOtherAtom += TopOrigin->getPosition();
584// *SecondOtherAtom += TopOrigin->getPosition();
585// *ThirdOtherAtom += TopOrigin->getPosition();
586//
587// // ... and add to molecule
588// AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
589// AllWentWell = AllWentWell && AddAtom(SecondOtherAtom);
590// AllWentWell = AllWentWell && AddAtom(ThirdOtherAtom);
591//// LOG(4, "INFO: Added " << *FirstOtherAtom << " at: " << FirstOtherAtom->x << ".");
592//// LOG(4, "INFO: Added " << *SecondOtherAtom << " at: " << SecondOtherAtom->x << ".");
593//// LOG(4, "INFO: Added " << *ThirdOtherAtom << " at: " << ThirdOtherAtom->x << ".");
594// Binder = AddBond(BottomOrigin, FirstOtherAtom, 1);
595// Binder->Cyclic = false;
596// Binder->Type = GraphEdge::TreeEdge;
597// Binder = AddBond(BottomOrigin, SecondOtherAtom, 1);
598// Binder->Cyclic = false;
599// Binder->Type = GraphEdge::TreeEdge;
600// Binder = AddBond(BottomOrigin, ThirdOtherAtom, 1);
601// Binder->Cyclic = false;
602// Binder->Type = GraphEdge::TreeEdge;
603// break;
604// default:
605// ELOG(1, "BondDegree does not state single, double or triple bond!");
606// AllWentWell = false;
607// break;
608// }
609//
610// return AllWentWell;
611//};
612
613/** Creates a copy of this molecule.
614 * \param offset translation Vector for the new molecule relative to old one
615 * \return copy of molecule
616 */
617molecule *molecule::CopyMolecule(const Vector &offset)
618{
619 molecule *copy = World::getInstance().createMolecule();
620
621 // copy all atoms
622 std::map< const atom *, atom *> FatherFinder;
623 for (iterator iter = begin(); iter != end(); ++iter) {
624 atom * const copy_atom = copy->AddCopyAtom(*iter);
625 copy_atom->setPosition(copy_atom->getPosition() + offset);
626 FatherFinder.insert( std::make_pair( *iter, copy_atom ) );
627 }
628
629 // copy all bonds
630 for(const_iterator AtomRunner = const_cast<const molecule &>(*this).begin();
631 AtomRunner != const_cast<const molecule &>(*this).end();
632 ++AtomRunner) {
633 const BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
634 for(BondList::const_iterator BondRunner = ListOfBonds.begin();
635 BondRunner != ListOfBonds.end();
636 ++BondRunner)
637 if ((*BondRunner)->leftatom == *AtomRunner) {
638 bond::ptr Binder = (*BondRunner);
639 // get the pendant atoms of current bond in the copy molecule
640 ASSERT(FatherFinder.count(Binder->leftatom),
641 "molecule::CopyMolecule() - No copy of original left atom "
642 +toString(Binder->leftatom)+" for bond copy found");
643 ASSERT(FatherFinder.count(Binder->rightatom),
644 "molecule::CopyMolecule() - No copy of original right atom "
645 +toString(Binder->rightatom)+" for bond copy found");
646 atom * const LeftAtom = FatherFinder[Binder->leftatom];
647 atom * const RightAtom = FatherFinder[Binder->rightatom];
648
649 bond::ptr const NewBond = copy->AddBond(LeftAtom, RightAtom, Binder->getDegree());
650 NewBond->Cyclic = Binder->Cyclic;
651 if (Binder->Cyclic)
652 copy->NoCyclicBonds++;
653 NewBond->Type = Binder->Type;
654 }
655 }
656 // correct fathers
657 //for_each(begin(),end(),mem_fun(&atom::CorrectFather));
658
659 return copy;
660};
661
662
663/** Destroys all atoms inside this molecule.
664 */
665void removeAtomsinMolecule(molecule *&_mol)
666{
667 // copy list of atoms from molecule as it will be changed
668 std::vector<atom *> atoms;
669 atoms.resize(_mol->getAtomCount(), NULL);
670 std::copy(_mol->begin(), _mol->end(), atoms.begin());
671 // remove each atom from world
672 for(std::vector<atom *>::iterator AtomRunner = atoms.begin();
673 AtomRunner != atoms.end(); ++AtomRunner)
674 World::getInstance().destroyAtom(*AtomRunner);
675 // make sure that pointer os not usable
676 _mol = NULL;
677};
678
679
680/**
681 * Copies all atoms of a molecule which are within the defined parallelepiped.
682 *
683 * @param offest for the origin of the parallelepiped
684 * @param three vectors forming the matrix that defines the shape of the parallelpiped
685 */
686molecule* molecule::CopyMoleculeFromSubRegion(const Shape &region) {
687 molecule *copy = World::getInstance().createMolecule();
688
689 // copy all atoms
690 std::map< const atom *, atom *> FatherFinder;
691 for (iterator iter = begin(); iter != end(); ++iter) {
692 if (region.isInside((*iter)->getPosition())) {
693 atom * const copy_atom = copy->AddCopyAtom(*iter);
694 FatherFinder.insert( std::make_pair( *iter, copy_atom ) );
695 }
696 }
697
698 // copy all bonds
699 for(molecule::const_iterator AtomRunner = const_cast<const molecule &>(*this).begin();
700 AtomRunner != const_cast<const molecule &>(*this).end();
701 ++AtomRunner) {
702 const BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
703 for(BondList::const_iterator BondRunner = ListOfBonds.begin();
704 BondRunner != ListOfBonds.end();
705 ++BondRunner)
706 if ((*BondRunner)->leftatom == *AtomRunner) {
707 bond::ptr Binder = (*BondRunner);
708 if ((FatherFinder.count(Binder->leftatom))
709 && (FatherFinder.count(Binder->rightatom))) {
710 // if copy present, then it must be from subregion
711 atom * const LeftAtom = FatherFinder[Binder->leftatom];
712 atom * const RightAtom = FatherFinder[Binder->rightatom];
713
714 bond::ptr const NewBond = copy->AddBond(LeftAtom, RightAtom, Binder->getDegree());
715 NewBond->Cyclic = Binder->Cyclic;
716 if (Binder->Cyclic)
717 copy->NoCyclicBonds++;
718 NewBond->Type = Binder->Type;
719 }
720 }
721 }
722 // correct fathers
723 //for_each(begin(),end(),mem_fun(&atom::CorrectFather));
724
725 //TODO: copy->BuildInducedSubgraph(this);
726
727 return copy;
728}
729
730/** Adds a bond to a the molecule specified by two atoms, \a *first and \a *second.
731 * Also updates molecule::BondCount and molecule::NoNonBonds.
732 * \param *first first atom in bond
733 * \param *second atom in bond
734 * \return pointer to bond or NULL on failure
735 */
736bond::ptr molecule::AddBond(atom *atom1, atom *atom2, int degree)
737{
738 bond::ptr Binder;
739
740 // some checks to make sure we are able to create the bond
741 ASSERT(atom1,
742 "molecule::AddBond() - First atom "+toString(atom1)
743 +" is not a invalid pointer");
744 ASSERT(atom2,
745 "molecule::AddBond() - Second atom "+toString(atom2)
746 +" is not a invalid pointer");
747 ASSERT(isInMolecule(atom1),
748 "molecule::AddBond() - First atom "+toString(atom1)
749 +" is not part of molecule");
750 ASSERT(isInMolecule(atom2),
751 "molecule::AddBond() - Second atom "+toString(atom2)
752 +" is not part of molecule");
753
754 Binder.reset(new bond(atom1, atom2, degree));
755 atom1->RegisterBond(WorldTime::getTime(), Binder);
756 atom2->RegisterBond(WorldTime::getTime(), Binder);
757 if ((atom1->getType() != NULL)
758 && (atom1->getType()->getAtomicNumber() != 1)
759 && (atom2->getType() != NULL)
760 && (atom2->getType()->getAtomicNumber() != 1))
761 NoNonBonds++;
762
763 return Binder;
764};
765
766/** Set molecule::name from the basename without suffix in the given \a *filename.
767 * \param *filename filename
768 */
769void molecule::SetNameFromFilename(const char *filename)
770{
771 OBSERVE;
772 int length = 0;
773 const char *molname = strrchr(filename, '/');
774 if (molname != NULL)
775 molname += sizeof(char); // search for filename without dirs
776 else
777 molname = filename; // contains no slashes
778 const char *endname = strchr(molname, '.');
779 if ((endname == NULL) || (endname < molname))
780 length = strlen(molname);
781 else
782 length = strlen(molname) - strlen(endname);
783 cout << "Set name of molecule " << getId() << " to " << molname << endl;
784 strncpy(name, molname, length);
785 name[length]='\0';
786};
787
788/** Removes atom from molecule list, but does not delete it.
789 * \param *pointer atom to be removed
790 * \return true - succeeded, false - atom not found in list
791 */
792bool molecule::UnlinkAtom(atom *pointer)
793{
794 if (pointer == NULL)
795 return false;
796 pointer->removeFromMolecule();
797 return true;
798};
799
800/** Removes every atom from molecule list.
801 * \return true - succeeded, false - atom not found in list
802 */
803bool molecule::CleanupMolecule()
804{
805 for (molecule::iterator iter = begin(); !empty(); iter = begin())
806 (*iter)->removeFromMolecule();
807 return empty();
808};
809
810/** Finds an atom specified by its continuous number.
811 * \param Nr number of atom withim molecule
812 * \return pointer to atom or NULL
813 */
814atom * molecule::FindAtom(int Nr) const
815{
816 LocalToGlobalId_t::const_iterator iter = LocalToGlobalId.find(Nr);
817 if (iter != LocalToGlobalId.end()) {
818 //LOG(0, "Found Atom Nr. " << walker->getNr());
819 return iter->second;
820 } else {
821 ELOG(1, "Atom with Nr " << Nr << " not found in molecule " << getName() << "'s list.");
822 return NULL;
823 }
824}
825
826/** Checks whether the given atom is a member of this molecule.
827 *
828 * We make use here of molecule::atomIds to get a result on
829 *
830 * @param _atom atom to check
831 * @return true - is member, false - is not
832 */
833bool molecule::isInMolecule(const atom * const _atom) const
834{
835 ASSERT(_atom->getMolecule() == this,
836 "molecule::isInMolecule() - atom is not designated to be in molecule '"
837 +toString(this->getName())+"'.");
838 molecule::const_iterator iter = atomIds.find(_atom->getId());
839 return (iter != atomIds.end());
840}
841
842/** Asks for atom number, and checks whether in list.
843 * \param *text question before entering
844 */
845atom * molecule::AskAtom(std::string text)
846{
847 int No;
848 atom *ion = NULL;
849 do {
850 //std::cout << "============Atom list==========================" << std::endl;
851 //mol->Output((ofstream *)&cout);
852 //std::cout << "===============================================" << std::endl;
853 std::cout << text;
854 cin >> No;
855 ion = this->FindAtom(No);
856 } while (ion == NULL);
857 return ion;
858};
859
860/** Checks if given coordinates are within cell volume.
861 * \param *x array of coordinates
862 * \return true - is within, false - out of cell
863 */
864bool molecule::CheckBounds(const Vector *x) const
865{
866 const RealSpaceMatrix &domain = World::getInstance().getDomain().getM();
867 bool result = true;
868 for (int i=0;i<NDIM;i++) {
869 result = result && ((x->at(i) >= 0) && (x->at(i) < domain.at(i,i)));
870 }
871 //return result;
872 return true; /// probably not gonna use the check no more
873};
874
875/** Prints molecule to *out.
876 * \param *out output stream
877 */
878bool molecule::Output(ostream * const output) const
879{
880 if (output == NULL) {
881 return false;
882 } else {
883 int AtomNo[MAX_ELEMENTS];
884 memset(AtomNo,0,(MAX_ELEMENTS-1)*sizeof(*AtomNo));
885 enumeration<const element*> elementLookup = formula.enumerateElements();
886 *output << "#Ion_TypeNr._Nr.R[0] R[1] R[2] MoveType (0 MoveIon, 1 FixedIon)" << endl;
887 for_each(begin(),end(),boost::bind(&atom::OutputArrayIndexed,_1,output,elementLookup,AtomNo,(const char*)0));
888 return true;
889 }
890};
891
892/** Outputs contents of each atom::ListOfBonds.
893 * \param *out output stream
894 */
895void molecule::OutputListOfBonds() const
896{
897 std::stringstream output;
898 LOG(2, "From Contents of ListOfBonds, all atoms:");
899 for (molecule::const_iterator iter = begin();
900 iter != end();
901 ++iter) {
902 (*iter)->OutputBondOfAtom(output);
903 output << std::endl << "\t\t";
904 }
905 LOG(2, output.str());
906}
907
908/** Brings molecule::AtomCount and atom::*Name up-to-date.
909 * \param *out output stream for debugging
910 */
911size_t molecule::doCountNoNonHydrogen() const
912{
913 int temp = 0;
914 // go through atoms and look for new ones
915 for (molecule::const_iterator iter = begin(); iter != end(); ++iter)
916 if ((*iter)->getType()->getAtomicNumber() != 1) // count non-hydrogen atoms whilst at it
917 ++temp;
918 return temp;
919};
920
921/** Counts the number of present bonds.
922 * \return number of bonds
923 */
924int molecule::doCountBonds() const
925{
926 unsigned int counter = 0;
927 for(molecule::const_iterator AtomRunner = begin(); AtomRunner != end(); ++AtomRunner) {
928 const BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
929 for(BondList::const_iterator BondRunner = ListOfBonds.begin();
930 BondRunner != ListOfBonds.end();
931 ++BondRunner)
932 if ((*BondRunner)->leftatom == *AtomRunner)
933 counter++;
934 }
935 return counter;
936}
937
938
939/** Returns an index map for two father-son-molecules.
940 * The map tells which atom in this molecule corresponds to which one in the other molecul with their fathers.
941 * \param *out output stream for debugging
942 * \param *OtherMolecule corresponding molecule with fathers
943 * \return allocated map of size molecule::AtomCount with map
944 * \todo make this with a good sort O(n), not O(n^2)
945 */
946int * molecule::GetFatherSonAtomicMap(const molecule * const OtherMolecule)
947{
948 LOG(3, "Begin of GetFatherAtomicMap.");
949 int *AtomicMap = new int[getAtomCount()];
950 for (int i=getAtomCount();i--;)
951 AtomicMap[i] = -1;
952 if (OtherMolecule == this) { // same molecule
953 for (int i=getAtomCount();i--;) // no need as -1 means already that there is trivial correspondence
954 AtomicMap[i] = i;
955 LOG(4, "Map is trivial.");
956 } else {
957 std::stringstream output;
958 output << "Map is ";
959 for (molecule::const_iterator iter = const_cast<const molecule &>(*this).begin();
960 iter != const_cast<const molecule &>(*this).end();
961 ++iter) {
962 if ((*iter)->getFather() == NULL) {
963 AtomicMap[(*iter)->getNr()] = -2;
964 } else {
965 for (molecule::const_iterator runner = OtherMolecule->begin(); runner != OtherMolecule->end(); ++runner) {
966 //for (int i=0;i<AtomCount;i++) { // search atom
967 //for (int j=0;j<OtherMolecule->getAtomCount();j++) {
968 //LOG(4, "Comparing father " << (*iter)->getFather() << " with the other one " << (*runner)->getFather() << ".");
969 if ((*iter)->getFather() == (*runner))
970 AtomicMap[(*iter)->getNr()] = (*runner)->getNr();
971 }
972 }
973 output << AtomicMap[(*iter)->getNr()] << "\t";
974 }
975 LOG(4, output.str());
976 }
977 LOG(3, "End of GetFatherAtomicMap.");
978 return AtomicMap;
979};
980
981
982void molecule::flipActiveFlag(){
983 ActiveFlag = !ActiveFlag;
984}
985
986Shape molecule::getBoundingShape(const double scale) const
987{
988 // create Sphere around every atom
989 if (empty())
990 return Nowhere();
991 const_iterator iter = begin();
992 const Vector center = (*iter)->getPosition();
993 const double vdWRadius = (*iter)->getElement().getVanDerWaalsRadius();
994 Shape BoundingShape = Sphere(center, vdWRadius*scale);
995 for(++iter; iter != end(); ++iter) {
996 const Vector center = (*iter)->getPosition();
997 const double vdWRadius = (*iter)->getElement().getVanDerWaalsRadius();
998 if (vdWRadius*scale != 0.)
999 BoundingShape = Sphere(center, vdWRadius*scale) || BoundingShape;
1000 }
1001 return BoundingShape;
1002}
1003
1004Shape molecule::getBoundingSphere(const double boundary) const
1005{
1006 // get center and radius
1007 Vector center;
1008 double radius = 0.;
1009 {
1010 center.Zero();
1011 for(const_iterator iter = begin(); iter != end(); ++iter)
1012 center += (*iter)->getPosition();
1013 if (begin() != end())
1014 center *= 1./(double)size();
1015 for(const_iterator iter = begin(); iter != end(); ++iter) {
1016 const Vector &position = (*iter)->getPosition();
1017 const double temp_distance = position.DistanceSquared(center);
1018 if (temp_distance > radius)
1019 radius = temp_distance;
1020 }
1021 }
1022 // convert radius to true value and add some small boundary
1023 radius = sqrt(radius) + boundary + 1e+6*std::numeric_limits<double>::epsilon();
1024 LOG(1, "INFO: The " << size() << " atoms of the molecule are contained in a sphere at "
1025 << center << " with radius " << radius << ".");
1026
1027 // TODO: When we do not use a Sphere here anymore, then FillRegularGridAction will
1028 // will not work as it expects a sphere due to possible random rotations.
1029 Shape BoundingShape(Sphere(center, radius));
1030 LOG(1, "INFO: Created sphere at " << BoundingShape.getCenter() << " and radius "
1031 << BoundingShape.getRadius() << ".");
1032 return BoundingShape;
1033}
1034
1035void molecule::update(Observable *publisher)
1036{
1037 ASSERT(0, "molecule::update() - did not sign on for any general updates.");
1038}
1039
1040void molecule::recieveNotification(Observable *publisher, Notification_ptr notification)
1041{
1042 const atom * const _atom = dynamic_cast<atom *>(publisher);
1043 if ((_atom != NULL) && containsAtom(_atom)) {
1044#ifdef LOG_OBSERVER
1045 observerLog().addMessage() << "++ Update of Observer "<< observerLog().getName(static_cast<Observer *>(this))
1046 << " received notification from atom " << _atom->getId() << " for channel "
1047 << notification->getChannelNo() << ".";
1048#endif
1049 switch (notification->getChannelNo()) {
1050 case AtomObservable::PositionChanged:
1051 {
1052 // emit others about one of our atoms moved
1053 _lastchangedatomid = _atom->getId();
1054 OBSERVE;
1055 NOTIFY(AtomMoved);
1056 break;
1057 }
1058 case AtomObservable::ElementChanged:
1059 {
1060 // emit others about one of our atoms moved
1061 _lastchangedatomid = _atom->getId();
1062 OBSERVE;
1063 NOTIFY(FormulaChanged);
1064 resetFormula();
1065 break;
1066 }
1067 default:
1068 ASSERT( 0, "molecule::recieveNotification() - we did not sign up for channel "
1069 +toString(notification->getChannelNo()));
1070 break;
1071 }
1072 }
1073}
1074
1075void molecule::subjectKilled(Observable *publisher)
1076{
1077 // do nothing, atom does it all
1078}
1079
1080void molecule::resetFormula()
1081{
1082 // clear
1083 formula.clear();
1084
1085 for (molecule::const_iterator iter = const_cast<const molecule *>(this)->begin();
1086 iter != const_cast<const molecule *>(this)->end(); ++iter)
1087 formula+=(*iter)->getType();
1088}
1089
1090// construct idpool
1091CONSTRUCT_IDPOOL(atomId_t, continuousId)
1092
Note: See TracBrowser for help on using the repository browser.