source: src/molecule.cpp@ e3c4c5

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 e3c4c5 was 5be798, checked in by Frederik Heber <heber@…>, 10 years ago

Removed molecule::lastChanged().

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