source: src/molecule.cpp@ d72064

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

FIX: not using const ref in binding updateBoundingBox() for molecule.

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