source: src/molecule.cpp@ 951aa6

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

Removed molecule's resetFormula() and doCountBonds() and doCountNoNonHydrogen().

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