source: src/molecule.cpp@ fb95a5

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

Added lastChanged..Id() to both World and molecule.

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