source: src/molecule.cpp@ ceaab1

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

AddAtom now adds a molecule (atom always associated with a molecule).

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