source: src/molecule.cpp@ c8cb0d

Candidate_v1.7.1 stable
Last change on this file since c8cb0d was c8cb0d, checked in by Frederik Heber <frederik.heber@…>, 6 weeks ago

Streamlines channel creation in Observables.

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