source: src/molecule.cpp@ 2034f3

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 2034f3 was 47ed3d, checked in by Frederik Heber <heber@…>, 13 years ago

Removed some old output functions in element, Formula, and molecule.

  • This is preparatory for refactoring element into a more general concept that can contain both chemical and derived elements suitable for empirical potential parametrization storage.
  • Removed functions in element: Output(), Checkout().
  • Removed function Formula::checkOut().
  • Removed function molecule::Checkout().
  • functionality added to periodentafel::OutputElement().
  • Property mode set to 100755
File size: 36.8 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
219
220bool molecule::containsAtom(atom* key){
221 return (find(key) != end());
222}
223
224World::AtomComposite molecule::getAtomSet() const
225{
226 World::AtomComposite vector_of_atoms;
227 for (molecule::iterator iter = begin(); iter != end(); ++iter)
228 vector_of_atoms.push_back(*iter);
229 return vector_of_atoms;
230}
231
232/** Adds given atom \a *pointer from molecule list.
233 * Increases molecule::last_atom and gives last number to added atom and names it according to its element::abbrev and molecule::AtomCount
234 * \param *pointer allocated and set atom
235 * \return true - succeeded, false - atom not found in list
236 */
237bool molecule::AddAtom(atom *pointer)
238{
239 OBSERVE;
240 if (pointer != NULL) {
241 insert(pointer);
242 pointer->setMolecule(this);
243 }
244 return true;
245};
246
247/** Adds a copy of the given atom \a *pointer from molecule list.
248 * Increases molecule::last_atom and gives last number to added atom.
249 * \param *pointer allocated and set atom
250 * \return pointer to the newly added atom
251 */
252atom * molecule::AddCopyAtom(atom *pointer)
253{
254 atom *retval = NULL;
255 OBSERVE;
256 if (pointer != NULL) {
257 atom *walker = pointer->clone();
258 walker->setName(pointer->getName());
259 walker->setNr(last_atom++); // increase number within molecule
260 insert(walker);
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 * \param offset translation Vector for the new molecule relative to old one
551 * \return copy of molecule
552 */
553molecule *molecule::CopyMolecule(const Vector &offset) const
554{
555 molecule *copy = World::getInstance().createMolecule();
556
557 // copy all atoms
558 std::map< const atom *, atom *> FatherFinder;
559 for (iterator iter = begin(); iter != end(); ++iter) {
560 atom * const copy_atom = copy->AddCopyAtom(*iter);
561 copy_atom->setPosition(copy_atom->getPosition() + offset);
562 FatherFinder.insert( std::make_pair( *iter, copy_atom ) );
563 }
564
565 // copy all bonds
566 for(const_iterator AtomRunner = begin(); AtomRunner != end(); ++AtomRunner) {
567 const BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
568 for(BondList::const_iterator BondRunner = ListOfBonds.begin();
569 BondRunner != ListOfBonds.end();
570 ++BondRunner)
571 if ((*BondRunner)->leftatom == *AtomRunner) {
572 bond *Binder = (*BondRunner);
573 // get the pendant atoms of current bond in the copy molecule
574 ASSERT(FatherFinder.count(Binder->leftatom),
575 "molecule::CopyMolecule() - No copy of original left atom "
576 +toString(Binder->leftatom)+" for bond copy found");
577 ASSERT(FatherFinder.count(Binder->rightatom),
578 "molecule::CopyMolecule() - No copy of original right atom "
579 +toString(Binder->rightatom)+" for bond copy found");
580 atom * const LeftAtom = FatherFinder[Binder->leftatom];
581 atom * const RightAtom = FatherFinder[Binder->rightatom];
582
583 bond * const NewBond = copy->AddBond(LeftAtom, RightAtom, Binder->BondDegree);
584 NewBond->Cyclic = Binder->Cyclic;
585 if (Binder->Cyclic)
586 copy->NoCyclicBonds++;
587 NewBond->Type = Binder->Type;
588 }
589 }
590 // correct fathers
591 //for_each(begin(),end(),mem_fun(&atom::CorrectFather));
592
593 return copy;
594};
595
596
597/** Destroys all atoms inside this molecule.
598 */
599void molecule::removeAtomsinMolecule()
600{
601 // remove each atom from world
602 for(iterator AtomRunner = begin(); !empty(); AtomRunner = begin())
603 World::getInstance().destroyAtom(*AtomRunner);
604};
605
606
607/**
608 * Copies all atoms of a molecule which are within the defined parallelepiped.
609 *
610 * @param offest for the origin of the parallelepiped
611 * @param three vectors forming the matrix that defines the shape of the parallelpiped
612 */
613molecule* molecule::CopyMoleculeFromSubRegion(const Shape &region) const {
614 molecule *copy = World::getInstance().createMolecule();
615
616 // copy all atoms
617 std::map< const atom *, atom *> FatherFinder;
618 for (iterator iter = begin(); iter != end(); ++iter) {
619 if((*iter)->IsInShape(region)){
620 atom * const copy_atom = copy->AddCopyAtom(*iter);
621 FatherFinder.insert( std::make_pair( *iter, copy_atom ) );
622 }
623 }
624
625 // copy all bonds
626 for(molecule::const_iterator AtomRunner = begin(); AtomRunner != end(); ++AtomRunner) {
627 const BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
628 for(BondList::const_iterator BondRunner = ListOfBonds.begin();
629 BondRunner != ListOfBonds.end();
630 ++BondRunner)
631 if ((*BondRunner)->leftatom == *AtomRunner) {
632 bond *Binder = (*BondRunner);
633 if ((FatherFinder.count(Binder->leftatom))
634 && (FatherFinder.count(Binder->rightatom))) {
635 // if copy present, then it must be from subregion
636 atom * const LeftAtom = FatherFinder[Binder->leftatom];
637 atom * const RightAtom = FatherFinder[Binder->rightatom];
638
639 bond * const NewBond = copy->AddBond(LeftAtom, RightAtom, Binder->BondDegree);
640 NewBond->Cyclic = Binder->Cyclic;
641 if (Binder->Cyclic)
642 copy->NoCyclicBonds++;
643 NewBond->Type = Binder->Type;
644 }
645 }
646 }
647 // correct fathers
648 //for_each(begin(),end(),mem_fun(&atom::CorrectFather));
649
650 //TODO: copy->BuildInducedSubgraph(this);
651
652 return copy;
653}
654
655/** Adds a bond to a the molecule specified by two atoms, \a *first and \a *second.
656 * Also updates molecule::BondCount and molecule::NoNonBonds.
657 * \param *first first atom in bond
658 * \param *second atom in bond
659 * \return pointer to bond or NULL on failure
660 */
661bond * molecule::AddBond(atom *atom1, atom *atom2, int degree)
662{
663 OBSERVE;
664 bond *Binder = NULL;
665
666 // some checks to make sure we are able to create the bond
667 ASSERT(atom1,
668 "molecule::AddBond() - First atom "+toString(atom1)
669 +" is not a invalid pointer");
670 ASSERT(atom2,
671 "molecule::AddBond() - Second atom "+toString(atom2)
672 +" is not a invalid pointer");
673 ASSERT(isInMolecule(atom1),
674 "molecule::AddBond() - First atom "+toString(atom1)
675 +" is not part of molecule");
676 ASSERT(isInMolecule(atom2),
677 "molecule::AddBond() - Second atom "+toString(atom2)
678 +" is not part of molecule");
679
680 Binder = new bond(atom1, atom2, degree);
681 atom1->RegisterBond(WorldTime::getTime(), Binder);
682 atom2->RegisterBond(WorldTime::getTime(), Binder);
683 if ((atom1->getType() != NULL)
684 && (atom1->getType()->getAtomicNumber() != 1)
685 && (atom2->getType() != NULL)
686 && (atom2->getType()->getAtomicNumber() != 1))
687 NoNonBonds++;
688
689 return Binder;
690};
691
692/** Remove bond from bond chain list and from the both atom::ListOfBonds.
693 * Bond::~Bond takes care of bond removal
694 * \param *pointer bond pointer
695 * \return true - bound found and removed, false - bond not found/removed
696 */
697bool molecule::RemoveBond(bond *pointer)
698{
699 //ELOG(1, "molecule::RemoveBond: Function not implemented yet.");
700 delete(pointer);
701 return true;
702};
703
704/** Remove every bond from bond chain list that atom \a *BondPartner is a constituent of.
705 * \todo Function not implemented yet
706 * \param *BondPartner atom to be removed
707 * \return true - bounds found and removed, false - bonds not found/removed
708 */
709bool molecule::RemoveBonds(atom *BondPartner)
710{
711 //ELOG(1, "molecule::RemoveBond: Function not implemented yet.");
712 BondPartner->removeAllBonds();
713 return false;
714};
715
716/** Set molecule::name from the basename without suffix in the given \a *filename.
717 * \param *filename filename
718 */
719void molecule::SetNameFromFilename(const char *filename)
720{
721 int length = 0;
722 const char *molname = strrchr(filename, '/');
723 if (molname != NULL)
724 molname += sizeof(char); // search for filename without dirs
725 else
726 molname = filename; // contains no slashes
727 const char *endname = strchr(molname, '.');
728 if ((endname == NULL) || (endname < molname))
729 length = strlen(molname);
730 else
731 length = strlen(molname) - strlen(endname);
732 cout << "Set name of molecule " << getId() << " to " << molname << endl;
733 strncpy(name, molname, length);
734 name[length]='\0';
735};
736
737/** Sets the molecule::cell_size to the components of \a *dim (rectangular box)
738 * \param *dim vector class
739 */
740void molecule::SetBoxDimension(Vector *dim)
741{
742 RealSpaceMatrix domain;
743 for(int i =0; i<NDIM;++i)
744 domain.at(i,i) = dim->at(i);
745 World::getInstance().setDomain(domain);
746};
747
748/** Removes atom from molecule list and removes all of its bonds.
749 * \param *pointer atom to be removed
750 * \return true - succeeded, false - atom not found in list
751 */
752bool molecule::RemoveAtom(atom *pointer)
753{
754 ASSERT(pointer, "Null pointer passed to molecule::RemoveAtom().");
755 OBSERVE;
756 RemoveBonds(pointer);
757 pointer->removeFromMolecule();
758 return true;
759};
760
761/** Removes atom from molecule list, but does not delete it.
762 * \param *pointer atom to be removed
763 * \return true - succeeded, false - atom not found in list
764 */
765bool molecule::UnlinkAtom(atom *pointer)
766{
767 if (pointer == NULL)
768 return false;
769 pointer->removeFromMolecule();
770 return true;
771};
772
773/** Removes every atom from molecule list.
774 * \return true - succeeded, false - atom not found in list
775 */
776bool molecule::CleanupMolecule()
777{
778 for (molecule::iterator iter = begin(); !empty(); iter = begin())
779 (*iter)->removeFromMolecule();
780 return empty();
781};
782
783/** Finds an atom specified by its continuous number.
784 * \param Nr number of atom withim molecule
785 * \return pointer to atom or NULL
786 */
787atom * molecule::FindAtom(int Nr) const
788{
789 molecule::iterator iter = begin();
790 for (; iter != end(); ++iter)
791 if ((*iter)->getNr() == Nr)
792 break;
793 if (iter != end()) {
794 //LOG(0, "Found Atom Nr. " << walker->getNr());
795 return (*iter);
796 } else {
797 ELOG(1, "Atom not found in molecule " << getName() << "'s list.");
798 return NULL;
799 }
800}
801
802/** Checks whether the given atom is a member of this molecule.
803 *
804 * We make use here of molecule::atomIds to get a result on
805 *
806 * @param _atom atom to check
807 * @return true - is member, false - is not
808 */
809bool molecule::isInMolecule(const atom * const _atom)
810{
811 ASSERT(_atom->getMolecule() == this,
812 "molecule::isInMolecule() - atom is not designated to be in molecule '"
813 +toString(this->getName())+"'.");
814 molecule::const_iterator iter = atomIds.find(_atom->getId());
815 return (iter != atomIds.end());
816}
817
818/** Asks for atom number, and checks whether in list.
819 * \param *text question before entering
820 */
821atom * molecule::AskAtom(std::string text)
822{
823 int No;
824 atom *ion = NULL;
825 do {
826 //std::cout << "============Atom list==========================" << std::endl;
827 //mol->Output((ofstream *)&cout);
828 //std::cout << "===============================================" << std::endl;
829 std::cout << text;
830 cin >> No;
831 ion = this->FindAtom(No);
832 } while (ion == NULL);
833 return ion;
834};
835
836/** Checks if given coordinates are within cell volume.
837 * \param *x array of coordinates
838 * \return true - is within, false - out of cell
839 */
840bool molecule::CheckBounds(const Vector *x) const
841{
842 const RealSpaceMatrix &domain = World::getInstance().getDomain().getM();
843 bool result = true;
844 for (int i=0;i<NDIM;i++) {
845 result = result && ((x->at(i) >= 0) && (x->at(i) < domain.at(i,i)));
846 }
847 //return result;
848 return true; /// probably not gonna use the check no more
849};
850
851/** Prints molecule to *out.
852 * \param *out output stream
853 */
854bool molecule::Output(ostream * const output) const
855{
856 if (output == NULL) {
857 return false;
858 } else {
859 int AtomNo[MAX_ELEMENTS];
860 memset(AtomNo,0,(MAX_ELEMENTS-1)*sizeof(*AtomNo));
861 enumeration<const element*> elementLookup = formula.enumerateElements();
862 *output << "#Ion_TypeNr._Nr.R[0] R[1] R[2] MoveType (0 MoveIon, 1 FixedIon)" << endl;
863 for_each(begin(),end(),boost::bind(&atom::OutputArrayIndexed,_1,output,elementLookup,AtomNo,(const char*)0));
864 return true;
865 }
866};
867
868/** Outputs contents of each atom::ListOfBonds.
869 * \param *out output stream
870 */
871void molecule::OutputListOfBonds() const
872{
873 std::stringstream output;
874 LOG(2, "From Contents of ListOfBonds, all atoms:");
875 for (molecule::const_iterator iter = begin();
876 iter != end();
877 ++iter) {
878 (*iter)->OutputBondOfAtom(output);
879 output << std::endl << "\t\t";
880 }
881 LOG(2, output.str());
882}
883
884/** Brings molecule::AtomCount and atom::*Name up-to-date.
885 * \param *out output stream for debugging
886 */
887size_t molecule::doCountNoNonHydrogen() const
888{
889 int temp = 0;
890 // go through atoms and look for new ones
891 for (molecule::const_iterator iter = begin(); iter != end(); ++iter)
892 if ((*iter)->getType()->getAtomicNumber() != 1) // count non-hydrogen atoms whilst at it
893 ++temp;
894 return temp;
895};
896
897/** Counts the number of present bonds.
898 * \return number of bonds
899 */
900int molecule::doCountBonds() const
901{
902 unsigned int counter = 0;
903 for(molecule::const_iterator AtomRunner = begin(); AtomRunner != end(); ++AtomRunner) {
904 const BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
905 for(BondList::const_iterator BondRunner = ListOfBonds.begin();
906 BondRunner != ListOfBonds.end();
907 ++BondRunner)
908 if ((*BondRunner)->leftatom == *AtomRunner)
909 counter++;
910 }
911 return counter;
912}
913
914
915/** Returns an index map for two father-son-molecules.
916 * The map tells which atom in this molecule corresponds to which one in the other molecul with their fathers.
917 * \param *out output stream for debugging
918 * \param *OtherMolecule corresponding molecule with fathers
919 * \return allocated map of size molecule::AtomCount with map
920 * \todo make this with a good sort O(n), not O(n^2)
921 */
922int * molecule::GetFatherSonAtomicMap(molecule *OtherMolecule)
923{
924 LOG(3, "Begin of GetFatherAtomicMap.");
925 int *AtomicMap = new int[getAtomCount()];
926 for (int i=getAtomCount();i--;)
927 AtomicMap[i] = -1;
928 if (OtherMolecule == this) { // same molecule
929 for (int i=getAtomCount();i--;) // no need as -1 means already that there is trivial correspondence
930 AtomicMap[i] = i;
931 LOG(4, "Map is trivial.");
932 } else {
933 std::stringstream output;
934 output << "Map is ";
935 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
936 if ((*iter)->father == NULL) {
937 AtomicMap[(*iter)->getNr()] = -2;
938 } else {
939 for (molecule::const_iterator runner = OtherMolecule->begin(); runner != OtherMolecule->end(); ++runner) {
940 //for (int i=0;i<AtomCount;i++) { // search atom
941 //for (int j=0;j<OtherMolecule->getAtomCount();j++) {
942 //LOG(4, "Comparing father " << (*iter)->father << " with the other one " << (*runner)->father << ".");
943 if ((*iter)->father == (*runner))
944 AtomicMap[(*iter)->getNr()] = (*runner)->getNr();
945 }
946 }
947 output << AtomicMap[(*iter)->getNr()] << "\t";
948 }
949 LOG(4, output.str());
950 }
951 LOG(3, "End of GetFatherAtomicMap.");
952 return AtomicMap;
953};
954
955
956void molecule::flipActiveFlag(){
957 ActiveFlag = !ActiveFlag;
958}
959
960Shape molecule::getBoundingShape() const
961{
962 // get center and radius
963 Vector center;
964 double radius = 0.;
965 {
966 center.Zero();
967 for(const_iterator iter = begin(); iter != end(); ++iter)
968 center += (*iter)->getPosition();
969 center *= 1./(double)size();
970 for(const_iterator iter = begin(); iter != end(); ++iter) {
971 const Vector &position = (*iter)->getPosition();
972 const double temp_distance = position.DistanceSquared(center);
973 if (temp_distance > radius)
974 radius = temp_distance;
975 }
976 }
977 // convert radius to true value and add some small boundary
978 radius = sqrt(radius) + 1e+6*std::numeric_limits<double>::epsilon();
979 LOG(1, "INFO: The " << size() << " atoms of the molecule are contained in a sphere at "
980 << center << " with radius " << radius << ".");
981
982 Shape BoundingShape(Sphere(center, radius));
983 LOG(1, "INFO: Created sphere at " << BoundingShape.getCenter() << " and radius "
984 << BoundingShape.getRadius() << ".");
985 return BoundingShape;
986}
987
988// construct idpool
989CONSTRUCT_IDPOOL(atomId_t, continuousId)
990
Note: See TracBrowser for help on using the repository browser.