source: src/molecule.cpp@ ceaab1

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

AddAtom now adds a molecule (atom always associated with a molecule).

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