source: src/molecule.cpp@ baac79

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

Added molecule::getBoundingShape() and unit test MoleculeUnitTest on it.

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