source: src/molecule.cpp@ 3139b2

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 3139b2 was 47d041, checked in by Frederik Heber <heber@…>, 13 years ago

HUGE: Removed all calls to Log(), eLog(), replaced by LOG() and ELOG().

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