source: src/molecule.cpp@ a0fa14

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 Candidate_v1.7.0 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 a0fa14 was cbd409, checked in by Frederik Heber <heber@…>, 10 years ago

Added Cacheable MoleculeCenter to molecule which is cleverly updated.

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