source: src/molecule.cpp@ db842b

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

Removed molecule's resetFormula() and doCountBonds() and doCountNoNonHydrogen().

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