source: src/molecule.cpp@ ada8df

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

Extracted common code out of Molecule/AtomObserver into EntityObserver.

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