source: src/molecule.cpp@ 93eae36

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 93eae36 was 6aad6f, checked in by Frederik Heber <heber@…>, 13 years ago

FIX: molecule::containsAtom() is now const and has const param, added AtomIdSet::contains().

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