source: src/molecule.cpp@ 8e1f901

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

molecule uses AtomIdSet now, rename getAtoms -> getAtomIds().

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