source: src/molecule.cpp@ fb95a5

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

Added lastChanged..Id() to both World and molecule.

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