source: src/molecule.cpp@ 4a187d

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 4a187d was deb5ee, checked in by Frederik Heber <heber@…>, 9 years ago

Removed molecule's AboutToBeRemoved channel.

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