source: src/molecule.cpp@ 22425a

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 22425a was 4d2b33, checked in by Frederik Heber <heber@…>, 13 years ago

FIX: molecule does not need a periodentafel.

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