source: src/molecule.cpp@ 361805

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

Merge branch 'michi-track-molecules' into stable

Conflicts:

src/World.hpp

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