source: src/molecule.cpp@ 15c75f8

SegFault_gcc4.6
Last change on this file since 15c75f8 was 15c75f8, checked in by Frederik Heber <heber@…>, 11 years ago

molecule has a lastchangedatom member variable now.

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