source: src/molecule.cpp@ d93d2c

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 d93d2c was 840d02, checked in by Frederik Heber <heber@…>, 9 years ago

FIX: not using const ref in binding updateBoundingBox() for molecule.

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