source: src/molecule.cpp@ 7f1865d

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 Candidate_v1.7.0 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 7f1865d was b71881, checked in by Frederik Heber <heber@…>, 10 years ago

Added select() and unselect() functions to atom and molecule, also SelectionChanged channel.

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