source: molecuilder/src/molecule.cpp@ 5bf941

Last change on this file since 5bf941 was 7bfc19, checked in by Tillmann Crueger <crueger@…>, 16 years ago

Made the world solely responsible for creating and destroying atoms.

  • Property mode set to 100755
File size: 45.1 KB
RevLine 
[a0bcf1]1/** \file molecules.cpp
[e0c5b1]2 *
[a0bcf1]3 * Functions for the class molecule.
[e0c5b1]4 *
[a0bcf1]5 */
6
[e6fe8a]7#include <cstring>
[f1ef9cc]8#include <boost/bind.hpp>
[e6fe8a]9
[7bfc19]10#include "World.hpp"
[17b3a5c]11#include "atom.hpp"
12#include "bond.hpp"
[e78824]13#include "config.hpp"
[17b3a5c]14#include "element.hpp"
15#include "graph.hpp"
[8ffe32]16#include "helpers.hpp"
[17b3a5c]17#include "leastsquaremin.hpp"
18#include "linkedcell.hpp"
19#include "lists.hpp"
[543ce4]20#include "log.hpp"
[f92d00]21#include "molecule.hpp"
[17b3a5c]22#include "memoryallocator.hpp"
23#include "periodentafel.hpp"
24#include "stackclass.hpp"
25#include "tesselation.hpp"
26#include "vector.hpp"
[a0bcf1]27
28/************************************* Functions for class molecule *********************************/
29
30/** Constructor of class molecule.
31 * Initialises molecule list with correctly referenced start and end, and sets molecule::last_atom to zero.
32 */
[7bfc19]33molecule::molecule(const periodentafel * const teil) : elemente(teil), start(World::get()->createAtom()), end(World::get()->createAtom()),
[df0520]34 first(new bond(start, end, 1, -1)), last(new bond(start, end, 1, -1)), MDSteps(0), AtomCount(0),
35 BondCount(0), ElementCount(0), NoNonHydrogen(0), NoNonBonds(0), NoCyclicBonds(0), BondDistance(0.),
[f1ef9cc]36 ActiveFlag(false), IndexNr(-1), last_atom(0), InternalPointer(start),
37 formula(this,boost::bind(&molecule::calcFormula,this))
[e0c5b1]38{
[a048fa]39 // init atom chain list
40 start->father = NULL;
41 end->father = NULL;
42 link(start,end);
[df0520]43
[a048fa]44 // init bond chain list
45 link(first,last);
[df0520]46
[a048fa]47 // other stuff
48 for(int i=MAX_ELEMENTS;i--;)
49 ElementsInMolecule[i] = 0;
50 cell_size[0] = cell_size[2] = cell_size[5]= 20.;
51 cell_size[1] = cell_size[3] = cell_size[4]= 0.;
52 strcpy(name,"none");
[a0bcf1]53};
54
55/** Destructor of class molecule.
56 * Initialises molecule list with correctly referenced start and end, and sets molecule::last_atom to zero.
57 */
[e0c5b1]58molecule::~molecule()
[a0bcf1]59{
[a048fa]60 CleanupMolecule();
61 delete(first);
62 delete(last);
[7bfc19]63 end->getWorld()->destroyAtom(end);
64 start->getWorld()->destroyAtom(start);
[a0bcf1]65};
66
[834ff3]67
[adcdf8]68// getter and setter
69const std::string molecule::getName(){
70 return std::string(name);
71}
72
73void molecule::setName(const std::string _name){
[8501eb]74 OBSERVE;
[adcdf8]75 strncpy(name,_name.c_str(),MAXSTRINGSIZE);
76}
77
[f1ef9cc]78const std::string molecule::getFormula(){
79 return *formula;
80}
81
82std::string molecule::calcFormula(){
83 int Counts[MAX_ELEMENTS];
84 stringstream sstr;
85 for (int j = 0; j<MAX_ELEMENTS;j++)
86 Counts[j] = 0;
87 for(atom *Walker = start; Walker != end; Walker = Walker->next) {
88 Counts[Walker->type->Z]++;
89 }
90 for(element* Elemental = elemente->end; Elemental != elemente->start; Elemental = Elemental->previous) {
91 if (Counts[Elemental->Z] != 0)
92 sstr << Elemental->symbol << Counts[Elemental->Z];
93 }
94 return sstr.str();
95}
96
[adcdf8]97
[a0bcf1]98/** Adds given atom \a *pointer from molecule list.
[e0c5b1]99 * Increases molecule::last_atom and gives last number to added atom and names it according to its element::abbrev and molecule::AtomCount
[a0bcf1]100 * \param *pointer allocated and set atom
101 * \return true - succeeded, false - atom not found in list
102 */
103bool molecule::AddAtom(atom *pointer)
[e0c5b1]104{
[8fc9b6]105 bool retval = false;
[8501eb]106 OBSERVE;
[a048fa]107 if (pointer != NULL) {
108 pointer->sort = &pointer->nr;
109 pointer->nr = last_atom++; // increase number within molecule
110 AtomCount++;
111 if (pointer->type != NULL) {
112 if (ElementsInMolecule[pointer->type->Z] == 0)
113 ElementCount++;
114 ElementsInMolecule[pointer->type->Z]++; // increase number of elements
115 if (pointer->type->Z != 1)
116 NoNonHydrogen++;
117 if (pointer->Name == NULL) {
[390a2b]118 Free(&pointer->Name);
119 pointer->Name = Malloc<char>(6, "molecule::AddAtom: *pointer->Name");
[a048fa]120 sprintf(pointer->Name, "%2s%02d", pointer->type->symbol, pointer->nr+1);
121 }
122 }
[8fc9b6]123 retval = add(pointer, end);
124 }
125 return retval;
[a0bcf1]126};
127
128/** Adds a copy of the given atom \a *pointer from molecule list.
129 * Increases molecule::last_atom and gives last number to added atom.
130 * \param *pointer allocated and set atom
[bc3953]131 * \return pointer to the newly added atom
[a0bcf1]132 */
133atom * molecule::AddCopyAtom(atom *pointer)
[e0c5b1]134{
[8fc9b6]135 atom *retval = NULL;
[8501eb]136 OBSERVE;
[a048fa]137 if (pointer != NULL) {
[7bfc19]138 atom *walker = pointer->clone();
[390a2b]139 walker->Name = Malloc<char>(strlen(pointer->Name) + 1, "atom::atom: *Name");
[a048fa]140 strcpy (walker->Name, pointer->Name);
[4e4940]141 walker->nr = last_atom++; // increase number within molecule
[a048fa]142 add(walker, end);
143 if ((pointer->type != NULL) && (pointer->type->Z != 1))
144 NoNonHydrogen++;
145 AtomCount++;
[8fc9b6]146 retval=walker;
147 }
148 return retval;
[a0bcf1]149};
150
151/** Adds a Hydrogen atom in replacement for the given atom \a *partner in bond with a *origin.
152 * Here, we have to distinguish between single, double or triple bonds as stated by \a BondDegree, that each demand
153 * a different scheme when adding \a *replacement atom for the given one.
154 * -# Single Bond: Simply add new atom with bond distance rescaled to typical hydrogen one
155 * -# Double Bond: Here, we need the **BondList of the \a *origin atom, by scanning for the other bonds instead of
[a048fa]156 * *Bond, we use the through these connected atoms to determine the plane they lie in, vector::MakeNormalvector().
157 * The orthonormal vector to this plane along with the vector in *Bond direction determines the plane the two
158 * replacing hydrogens shall lie in. Now, all remains to do is take the usual hydrogen double bond angle for the
159 * element of *origin and form the sin/cos admixture of both plane vectors for the new coordinates of the two
160 * hydrogens forming this angle with *origin.
[a0bcf1]161 * -# 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
[a048fa]162 * triangle formed by the to be added hydrogens are not equal to the typical bond distance \f$l\f$ but have to be
163 * determined from the typical angle \f$\alpha\f$ for a hydrogen triple connected to the element of *origin):
164 * We have the height \f$d\f$ as the vector in *Bond direction (from triangle C1-H1-H2).
165 * \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 )}}
166 * \f]
167 * vector::GetNormalvector() creates one orthonormal vector from this *Bond vector and vector::MakeNormalvector creates
168 * the third one from the former two vectors. The latter ones form the plane of the base triangle mentioned above.
169 * The lengths for these are \f$f\f$ and \f$g\f$ (from triangle H1-H2-(center of H1-H2-H3)) with knowledge that
170 * the median lines in an isosceles triangle meet in the center point with a ratio 2:1.
171 * \f[ f = \frac{b}{\sqrt{3}} \qquad g = \frac{b}{2}
172 * \f]
173 * as the coordination of all three atoms in the coordinate system of these three vectors:
174 * \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$.
[e0c5b1]175 *
[a0bcf1]176 * \param *out output stream for debugging
[e0c5b1]177 * \param *Bond pointer to bond between \a *origin and \a *replacement
178 * \param *TopOrigin son of \a *origin of upper level molecule (the atom added to this molecule as a copy of \a *origin)
[a0bcf1]179 * \param *origin pointer to atom which acts as the origin for scaling the added hydrogen to correct bond length
180 * \param *replacement pointer to the atom which shall be copied as a hydrogen atom in this molecule
181 * \param isAngstroem whether the coordination of the given atoms is in AtomicLength (false) or Angstrom(true)
182 * \return number of atoms added, if < bond::BondDegree then something went wrong
183 * \todo double and triple bonds splitting (always use the tetraeder angle!)
184 */
[543ce4]185bool molecule::AddHydrogenReplacementAtom(bond *TopBond, atom *BottomOrigin, atom *TopOrigin, atom *TopReplacement, bool IsAngstroem)
[a0bcf1]186{
[8fc9b6]187 bool AllWentWell = true; // flag gathering the boolean return value of molecule::AddAtom and other functions, as return value on exit
[8501eb]188 OBSERVE;
[a048fa]189 double bondlength; // bond length of the bond to be replaced/cut
190 double bondangle; // bond angle of the bond to be replaced/cut
191 double BondRescale; // rescale value for the hydrogen bond length
192 bond *FirstBond = NULL, *SecondBond = NULL; // Other bonds in double bond case to determine "other" plane
193 atom *FirstOtherAtom = NULL, *SecondOtherAtom = NULL, *ThirdOtherAtom = NULL; // pointer to hydrogen atoms to be added
194 double b,l,d,f,g, alpha, factors[NDIM]; // hold temporary values in triple bond case for coordination determination
195 Vector Orthovector1, Orthovector2; // temporary vectors in coordination construction
196 Vector InBondvector; // vector in direction of *Bond
[4ef101]197 double *matrix = NULL;
[872b51]198 bond *Binder = NULL;
[a048fa]199
[543ce4]200// Log() << Verbose(3) << "Begin of AddHydrogenReplacementAtom." << endl;
[a048fa]201 // create vector in direction of bond
202 InBondvector.CopyVector(&TopReplacement->x);
203 InBondvector.SubtractVector(&TopOrigin->x);
204 bondlength = InBondvector.Norm();
205
206 // is greater than typical bond distance? Then we have to correct periodically
207 // the problem is not the H being out of the box, but InBondvector have the wrong direction
208 // due to TopReplacement or Origin being on the wrong side!
209 if (bondlength > BondDistance) {
[543ce4]210// Log() << Verbose(4) << "InBondvector is: ";
[a048fa]211// InBondvector.Output(out);
[543ce4]212// Log() << Verbose(0) << endl;
[a048fa]213 Orthovector1.Zero();
214 for (int i=NDIM;i--;) {
215 l = TopReplacement->x.x[i] - TopOrigin->x.x[i];
216 if (fabs(l) > BondDistance) { // is component greater than bond distance
217 Orthovector1.x[i] = (l < 0) ? -1. : +1.;
218 } // (signs are correct, was tested!)
219 }
220 matrix = ReturnFullMatrixforSymmetric(cell_size);
221 Orthovector1.MatrixMultiplication(matrix);
222 InBondvector.SubtractVector(&Orthovector1); // subtract just the additional translation
[390a2b]223 Free(&matrix);
[a048fa]224 bondlength = InBondvector.Norm();
[543ce4]225// Log() << Verbose(4) << "Corrected InBondvector is now: ";
[a048fa]226// InBondvector.Output(out);
[543ce4]227// Log() << Verbose(0) << endl;
[a048fa]228 } // periodic correction finished
229
230 InBondvector.Normalize();
231 // get typical bond length and store as scale factor for later
232 BondRescale = TopOrigin->type->HBondDistance[TopBond->BondDegree-1];
233 if (BondRescale == -1) {
[418117a]234 eLog() << Verbose(1) << "There is no typical hydrogen bond distance in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
[8501eb]235 return false;
[a048fa]236 BondRescale = bondlength;
237 } else {
238 if (!IsAngstroem)
239 BondRescale /= (1.*AtomicLengthToAngstroem);
240 }
241
242 // discern single, double and triple bonds
243 switch(TopBond->BondDegree) {
244 case 1:
[7bfc19]245 FirstOtherAtom = World::get()->createAtom(); // new atom
[a048fa]246 FirstOtherAtom->type = elemente->FindElement(1); // element is Hydrogen
247 FirstOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
248 FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
249 if (TopReplacement->type->Z == 1) { // neither rescale nor replace if it's already hydrogen
250 FirstOtherAtom->father = TopReplacement;
251 BondRescale = bondlength;
252 } else {
253 FirstOtherAtom->father = NULL; // if we replace hydrogen, we mark it as our father, otherwise we are just an added hydrogen with no father
254 }
255 InBondvector.Scale(&BondRescale); // rescale the distance vector to Hydrogen bond length
256 FirstOtherAtom->x.CopyVector(&TopOrigin->x); // set coordination to origin ...
257 FirstOtherAtom->x.AddVector(&InBondvector); // ... and add distance vector to replacement atom
258 AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
[543ce4]259// Log() << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
[a048fa]260// FirstOtherAtom->x.Output(out);
[543ce4]261// Log() << Verbose(0) << endl;
[a048fa]262 Binder = AddBond(BottomOrigin, FirstOtherAtom, 1);
263 Binder->Cyclic = false;
264 Binder->Type = TreeEdge;
265 break;
266 case 2:
267 // determine two other bonds (warning if there are more than two other) plus valence sanity check
[872b51]268 for (BondList::const_iterator Runner = TopOrigin->ListOfBonds.begin(); Runner != TopOrigin->ListOfBonds.end(); (++Runner)) {
269 if ((*Runner) != TopBond) {
[a048fa]270 if (FirstBond == NULL) {
[872b51]271 FirstBond = (*Runner);
272 FirstOtherAtom = (*Runner)->GetOtherAtom(TopOrigin);
[a048fa]273 } else if (SecondBond == NULL) {
[872b51]274 SecondBond = (*Runner);
275 SecondOtherAtom = (*Runner)->GetOtherAtom(TopOrigin);
[a048fa]276 } else {
[418117a]277 eLog() << Verbose(2) << "Detected more than four bonds for atom " << TopOrigin->Name;
[a048fa]278 }
279 }
280 }
281 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)
282 SecondBond = TopBond;
283 SecondOtherAtom = TopReplacement;
284 }
285 if (FirstOtherAtom != NULL) { // then we just have this double bond and the plane does not matter at all
[543ce4]286// Log() << Verbose(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." << endl;
[a048fa]287
288 // determine the plane of these two with the *origin
289 AllWentWell = AllWentWell && Orthovector1.MakeNormalVector(&TopOrigin->x, &FirstOtherAtom->x, &SecondOtherAtom->x);
290 } else {
291 Orthovector1.GetOneNormalVector(&InBondvector);
292 }
[543ce4]293 //Log() << Verbose(3)<< "Orthovector1: ";
[a048fa]294 //Orthovector1.Output(out);
[543ce4]295 //Log() << Verbose(0) << endl;
[a048fa]296 // orthogonal vector and bond vector between origin and replacement form the new plane
297 Orthovector1.MakeNormalVector(&InBondvector);
298 Orthovector1.Normalize();
[543ce4]299 //Log() << Verbose(3) << "ReScaleCheck: " << Orthovector1.Norm() << " and " << InBondvector.Norm() << "." << endl;
[a048fa]300
301 // create the two Hydrogens ...
[7bfc19]302 FirstOtherAtom = World::get()->createAtom();
303 SecondOtherAtom = World::get()->createAtom();
[a048fa]304 FirstOtherAtom->type = elemente->FindElement(1);
305 SecondOtherAtom->type = elemente->FindElement(1);
306 FirstOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
307 FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
308 SecondOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
309 SecondOtherAtom->FixedIon = TopReplacement->FixedIon;
310 FirstOtherAtom->father = NULL; // we are just an added hydrogen with no father
311 SecondOtherAtom->father = NULL; // we are just an added hydrogen with no father
312 bondangle = TopOrigin->type->HBondAngle[1];
313 if (bondangle == -1) {
[418117a]314 eLog() << Verbose(1) << "There is no typical hydrogen bond angle in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
[8501eb]315 return false;
[a048fa]316 bondangle = 0;
317 }
318 bondangle *= M_PI/180./2.;
[543ce4]319// Log() << Verbose(3) << "ReScaleCheck: InBondvector ";
[a048fa]320// InBondvector.Output(out);
[543ce4]321// Log() << Verbose(0) << endl;
322// Log() << Verbose(3) << "ReScaleCheck: Orthovector ";
[a048fa]323// Orthovector1.Output(out);
[543ce4]324// Log() << Verbose(0) << endl;
325// Log() << Verbose(3) << "Half the bond angle is " << bondangle << ", sin and cos of it: " << sin(bondangle) << ", " << cos(bondangle) << endl;
[a048fa]326 FirstOtherAtom->x.Zero();
327 SecondOtherAtom->x.Zero();
328 for(int i=NDIM;i--;) { // rotate by half the bond angle in both directions (InBondvector is bondangle = 0 direction)
329 FirstOtherAtom->x.x[i] = InBondvector.x[i] * cos(bondangle) + Orthovector1.x[i] * (sin(bondangle));
330 SecondOtherAtom->x.x[i] = InBondvector.x[i] * cos(bondangle) + Orthovector1.x[i] * (-sin(bondangle));
331 }
332 FirstOtherAtom->x.Scale(&BondRescale); // rescale by correct BondDistance
333 SecondOtherAtom->x.Scale(&BondRescale);
[543ce4]334 //Log() << Verbose(3) << "ReScaleCheck: " << FirstOtherAtom->x.Norm() << " and " << SecondOtherAtom->x.Norm() << "." << endl;
[a048fa]335 for(int i=NDIM;i--;) { // and make relative to origin atom
336 FirstOtherAtom->x.x[i] += TopOrigin->x.x[i];
337 SecondOtherAtom->x.x[i] += TopOrigin->x.x[i];
338 }
339 // ... and add to molecule
340 AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
341 AllWentWell = AllWentWell && AddAtom(SecondOtherAtom);
[543ce4]342// Log() << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
[a048fa]343// FirstOtherAtom->x.Output(out);
[543ce4]344// Log() << Verbose(0) << endl;
345// Log() << Verbose(4) << "Added " << *SecondOtherAtom << " at: ";
[a048fa]346// SecondOtherAtom->x.Output(out);
[543ce4]347// Log() << Verbose(0) << endl;
[a048fa]348 Binder = AddBond(BottomOrigin, FirstOtherAtom, 1);
349 Binder->Cyclic = false;
350 Binder->Type = TreeEdge;
351 Binder = AddBond(BottomOrigin, SecondOtherAtom, 1);
352 Binder->Cyclic = false;
353 Binder->Type = TreeEdge;
354 break;
355 case 3:
356 // take the "usual" tetraoidal angle and add the three Hydrogen in direction of the bond (height of the tetraoid)
[7bfc19]357 FirstOtherAtom = World::get()->createAtom();
358 SecondOtherAtom = World::get()->createAtom();
359 ThirdOtherAtom = World::get()->createAtom();
[a048fa]360 FirstOtherAtom->type = elemente->FindElement(1);
361 SecondOtherAtom->type = elemente->FindElement(1);
362 ThirdOtherAtom->type = elemente->FindElement(1);
363 FirstOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
364 FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
365 SecondOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
366 SecondOtherAtom->FixedIon = TopReplacement->FixedIon;
367 ThirdOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
368 ThirdOtherAtom->FixedIon = TopReplacement->FixedIon;
369 FirstOtherAtom->father = NULL; // we are just an added hydrogen with no father
370 SecondOtherAtom->father = NULL; // we are just an added hydrogen with no father
371 ThirdOtherAtom->father = NULL; // we are just an added hydrogen with no father
372
373 // we need to vectors orthonormal the InBondvector
374 AllWentWell = AllWentWell && Orthovector1.GetOneNormalVector(&InBondvector);
[543ce4]375// Log() << Verbose(3) << "Orthovector1: ";
[a048fa]376// Orthovector1.Output(out);
[543ce4]377// Log() << Verbose(0) << endl;
[a048fa]378 AllWentWell = AllWentWell && Orthovector2.MakeNormalVector(&InBondvector, &Orthovector1);
[543ce4]379// Log() << Verbose(3) << "Orthovector2: ";
[a048fa]380// Orthovector2.Output(out);
[543ce4]381// Log() << Verbose(0) << endl;
[a048fa]382
383 // create correct coordination for the three atoms
384 alpha = (TopOrigin->type->HBondAngle[2])/180.*M_PI/2.; // retrieve triple bond angle from database
385 l = BondRescale; // desired bond length
386 b = 2.*l*sin(alpha); // base length of isosceles triangle
387 d = l*sqrt(cos(alpha)*cos(alpha) - sin(alpha)*sin(alpha)/3.); // length for InBondvector
388 f = b/sqrt(3.); // length for Orthvector1
389 g = b/2.; // length for Orthvector2
[543ce4]390// Log() << Verbose(3) << "Bond length and half-angle: " << l << ", " << alpha << "\t (b,d,f,g) = " << b << ", " << d << ", " << f << ", " << g << ", " << endl;
391// Log() << Verbose(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) << endl;
[a048fa]392 factors[0] = d;
393 factors[1] = f;
394 factors[2] = 0.;
395 FirstOtherAtom->x.LinearCombinationOfVectors(&InBondvector, &Orthovector1, &Orthovector2, factors);
396 factors[1] = -0.5*f;
397 factors[2] = g;
398 SecondOtherAtom->x.LinearCombinationOfVectors(&InBondvector, &Orthovector1, &Orthovector2, factors);
399 factors[2] = -g;
400 ThirdOtherAtom->x.LinearCombinationOfVectors(&InBondvector, &Orthovector1, &Orthovector2, factors);
401
402 // rescale each to correct BondDistance
403// FirstOtherAtom->x.Scale(&BondRescale);
404// SecondOtherAtom->x.Scale(&BondRescale);
405// ThirdOtherAtom->x.Scale(&BondRescale);
406
407 // and relative to *origin atom
408 FirstOtherAtom->x.AddVector(&TopOrigin->x);
409 SecondOtherAtom->x.AddVector(&TopOrigin->x);
410 ThirdOtherAtom->x.AddVector(&TopOrigin->x);
411
412 // ... and add to molecule
413 AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
414 AllWentWell = AllWentWell && AddAtom(SecondOtherAtom);
415 AllWentWell = AllWentWell && AddAtom(ThirdOtherAtom);
[543ce4]416// Log() << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
[a048fa]417// FirstOtherAtom->x.Output(out);
[543ce4]418// Log() << Verbose(0) << endl;
419// Log() << Verbose(4) << "Added " << *SecondOtherAtom << " at: ";
[a048fa]420// SecondOtherAtom->x.Output(out);
[543ce4]421// Log() << Verbose(0) << endl;
422// Log() << Verbose(4) << "Added " << *ThirdOtherAtom << " at: ";
[a048fa]423// ThirdOtherAtom->x.Output(out);
[543ce4]424// Log() << Verbose(0) << endl;
[a048fa]425 Binder = AddBond(BottomOrigin, FirstOtherAtom, 1);
426 Binder->Cyclic = false;
427 Binder->Type = TreeEdge;
428 Binder = AddBond(BottomOrigin, SecondOtherAtom, 1);
429 Binder->Cyclic = false;
430 Binder->Type = TreeEdge;
431 Binder = AddBond(BottomOrigin, ThirdOtherAtom, 1);
432 Binder->Cyclic = false;
433 Binder->Type = TreeEdge;
434 break;
435 default:
[418117a]436 eLog() << Verbose(1) << "BondDegree does not state single, double or triple bond!" << endl;
[a048fa]437 AllWentWell = false;
438 break;
439 }
[4ef101]440 Free(&matrix);
[a048fa]441
[543ce4]442// Log() << Verbose(3) << "End of AddHydrogenReplacementAtom." << endl;
[a048fa]443 return AllWentWell;
[a0bcf1]444};
445
446/** Adds given atom \a *pointer from molecule list.
447 * Increases molecule::last_atom and gives last number to added atom.
448 * \param filename name and path of xyz file
449 * \return true - succeeded, false - file not found
450 */
451bool molecule::AddXYZFile(string filename)
[e0c5b1]452{
[8fc9b6]453
[a048fa]454 istringstream *input = NULL;
455 int NumberOfAtoms = 0; // atom number in xyz read
456 int i, j; // loop variables
457 atom *Walker = NULL; // pointer to added atom
458 char shorthand[3]; // shorthand for atom name
459 ifstream xyzfile; // xyz file
460 string line; // currently parsed line
461 double x[3]; // atom coordinates
462
463 xyzfile.open(filename.c_str());
464 if (!xyzfile)
465 return false;
466
[8501eb]467 OBSERVE;
[a048fa]468 getline(xyzfile,line,'\n'); // Read numer of atoms in file
469 input = new istringstream(line);
470 *input >> NumberOfAtoms;
[543ce4]471 Log() << Verbose(0) << "Parsing " << NumberOfAtoms << " atoms in file." << endl;
[a048fa]472 getline(xyzfile,line,'\n'); // Read comment
[543ce4]473 Log() << Verbose(1) << "Comment: " << line << endl;
[a048fa]474
475 if (MDSteps == 0) // no atoms yet present
476 MDSteps++;
477 for(i=0;i<NumberOfAtoms;i++){
[7bfc19]478 Walker = World::get()->createAtom();
[a048fa]479 getline(xyzfile,line,'\n');
480 istringstream *item = new istringstream(line);
481 //istringstream input(line);
[543ce4]482 //Log() << Verbose(1) << "Reading: " << line << endl;
[a048fa]483 *item >> shorthand;
484 *item >> x[0];
485 *item >> x[1];
486 *item >> x[2];
487 Walker->type = elemente->FindElement(shorthand);
488 if (Walker->type == NULL) {
[3d4969]489 eLog() << Verbose(1) << "Could not parse the element at line: '" << line << "', setting to H.";
[a048fa]490 Walker->type = elemente->FindElement(1);
491 }
[567b7f]492 if (Walker->Trajectory.R.size() <= (unsigned int)MDSteps) {
493 Walker->Trajectory.R.resize(MDSteps+10);
494 Walker->Trajectory.U.resize(MDSteps+10);
495 Walker->Trajectory.F.resize(MDSteps+10);
[a048fa]496 }
497 for(j=NDIM;j--;) {
498 Walker->x.x[j] = x[j];
[567b7f]499 Walker->Trajectory.R.at(MDSteps-1).x[j] = x[j];
500 Walker->Trajectory.U.at(MDSteps-1).x[j] = 0;
501 Walker->Trajectory.F.at(MDSteps-1).x[j] = 0;
[a048fa]502 }
503 AddAtom(Walker); // add to molecule
504 delete(item);
505 }
506 xyzfile.close();
507 delete(input);
508 return true;
[a0bcf1]509};
510
511/** Creates a copy of this molecule.
512 * \return copy of molecule
513 */
514molecule *molecule::CopyMolecule()
515{
[a048fa]516 molecule *copy = new molecule(elemente);
517 atom *LeftAtom = NULL, *RightAtom = NULL;
518
519 // copy all atoms
[8ffe32]520 ActOnCopyWithEachAtom ( &molecule::AddCopyAtom, copy );
[a048fa]521
522 // copy all bonds
523 bond *Binder = first;
524 bond *NewBond = NULL;
525 while(Binder->next != last) {
526 Binder = Binder->next;
[f92d00]527
[a048fa]528 // get the pendant atoms of current bond in the copy molecule
[94d0ad]529 copy->ActOnAllAtoms( &atom::EqualsFather, (const atom *)Binder->leftatom, (const atom **)&LeftAtom );
530 copy->ActOnAllAtoms( &atom::EqualsFather, (const atom *)Binder->rightatom, (const atom **)&RightAtom );
[f92d00]531
[a048fa]532 NewBond = copy->AddBond(LeftAtom, RightAtom, Binder->BondDegree);
533 NewBond->Cyclic = Binder->Cyclic;
534 if (Binder->Cyclic)
535 copy->NoCyclicBonds++;
536 NewBond->Type = Binder->Type;
537 }
538 // correct fathers
[f92d00]539 ActOnAllAtoms( &atom::CorrectFather );
540
[a048fa]541 // copy values
[543ce4]542 copy->CountAtoms();
[a048fa]543 copy->CountElements();
544 if (first->next != last) { // if adjaceny list is present
545 copy->BondDistance = BondDistance;
546 }
547
548 return copy;
[a0bcf1]549};
550
[bc3953]551
552/**
553 * Copies all atoms of a molecule which are within the defined parallelepiped.
554 *
555 * @param offest for the origin of the parallelepiped
556 * @param three vectors forming the matrix that defines the shape of the parallelpiped
557 */
[94d0ad]558molecule* molecule::CopyMoleculeFromSubRegion(const Vector offset, const double *parallelepiped) const {
[bc3953]559 molecule *copy = new molecule(elemente);
560
[8ffe32]561 ActOnCopyWithEachAtomIfTrue ( &molecule::AddCopyAtom, copy, &atom::IsInParallelepiped, offset, parallelepiped );
[bc3953]562
[543ce4]563 //TODO: copy->BuildInducedSubgraph(this);
[bc3953]564
565 return copy;
566}
567
[a0bcf1]568/** Adds a bond to a the molecule specified by two atoms, \a *first and \a *second.
569 * Also updates molecule::BondCount and molecule::NoNonBonds.
570 * \param *first first atom in bond
571 * \param *second atom in bond
572 * \return pointer to bond or NULL on failure
573 */
[f92d00]574bond * molecule::AddBond(atom *atom1, atom *atom2, int degree)
[a0bcf1]575{
[a048fa]576 bond *Binder = NULL;
577 if ((atom1 != NULL) && (FindAtom(atom1->nr) != NULL) && (atom2 != NULL) && (FindAtom(atom2->nr) != NULL)) {
578 Binder = new bond(atom1, atom2, degree, BondCount++);
[872b51]579 atom1->RegisterBond(Binder);
580 atom2->RegisterBond(Binder);
[a048fa]581 if ((atom1->type != NULL) && (atom1->type->Z != 1) && (atom2->type != NULL) && (atom2->type->Z != 1))
582 NoNonBonds++;
583 add(Binder, last);
584 } else {
[418117a]585 eLog() << Verbose(1) << "Could not add bond between " << atom1->Name << " and " << atom2->Name << " as one or both are not present in the molecule." << endl;
[a048fa]586 }
587 return Binder;
[a0bcf1]588};
589
[df0520]590/** Remove bond from bond chain list and from the both atom::ListOfBonds.
[e0c5b1]591 * \todo Function not implemented yet
[a0bcf1]592 * \param *pointer bond pointer
593 * \return true - bound found and removed, false - bond not found/removed
594 */
595bool molecule::RemoveBond(bond *pointer)
596{
[543ce4]597 //eLog() << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
[df0520]598 pointer->leftatom->RegisterBond(pointer);
599 pointer->rightatom->RegisterBond(pointer);
[a048fa]600 removewithoutcheck(pointer);
601 return true;
[a0bcf1]602};
603
604/** Remove every bond from bond chain list that atom \a *BondPartner is a constituent of.
[e0c5b1]605 * \todo Function not implemented yet
[a0bcf1]606 * \param *BondPartner atom to be removed
607 * \return true - bounds found and removed, false - bonds not found/removed
608 */
609bool molecule::RemoveBonds(atom *BondPartner)
610{
[543ce4]611 //eLog() << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
[872b51]612 BondList::const_iterator ForeRunner;
613 while (!BondPartner->ListOfBonds.empty()) {
614 ForeRunner = BondPartner->ListOfBonds.begin();
615 RemoveBond(*ForeRunner);
616 }
[a048fa]617 return false;
[a0bcf1]618};
619
[c830e8e]620/** Set molecule::name from the basename without suffix in the given \a *filename.
621 * \param *filename filename
622 */
[d618b5]623void molecule::SetNameFromFilename(const char *filename)
[c830e8e]624{
625 int length = 0;
[606dfb]626 const char *molname = strrchr(filename, '/');
627 if (molname != NULL)
628 molname += sizeof(char); // search for filename without dirs
629 else
630 molname = filename; // contains no slashes
[e6fe8a]631 const char *endname = strchr(molname, '.');
[c830e8e]632 if ((endname == NULL) || (endname < molname))
633 length = strlen(molname);
634 else
635 length = strlen(molname) - strlen(endname);
636 strncpy(name, molname, length);
[d618b5]637 name[length]='\0';
[c830e8e]638};
639
[a0bcf1]640/** Sets the molecule::cell_size to the components of \a *dim (rectangular box)
641 * \param *dim vector class
642 */
[8f8621]643void molecule::SetBoxDimension(Vector *dim)
[a0bcf1]644{
[a048fa]645 cell_size[0] = dim->x[0];
646 cell_size[1] = 0.;
647 cell_size[2] = dim->x[1];
648 cell_size[3] = 0.;
649 cell_size[4] = 0.;
650 cell_size[5] = dim->x[2];
[a0bcf1]651};
652
[f92d00]653/** Removes atom from molecule list and deletes it.
654 * \param *pointer atom to be removed
655 * \return true - succeeded, false - atom not found in list
[927aba]656 */
[f92d00]657bool molecule::RemoveAtom(atom *pointer)
[927aba]658{
[f92d00]659 if (ElementsInMolecule[pointer->type->Z] != 0) { // this would indicate an error
660 ElementsInMolecule[pointer->type->Z]--; // decrease number of atom of this element
661 AtomCount--;
662 } else
[418117a]663 eLog() << Verbose(1) << "Atom " << pointer->Name << " is of element " << pointer->type->Z << " but the entry in the table of the molecule is 0!" << endl;
[f92d00]664 if (ElementsInMolecule[pointer->type->Z] == 0) // was last atom of this element?
665 ElementCount--;
[872b51]666 RemoveBonds(pointer);
[f92d00]667 return remove(pointer, start, end);
[927aba]668};
669
[f92d00]670/** Removes atom from molecule list, but does not delete it.
671 * \param *pointer atom to be removed
672 * \return true - succeeded, false - atom not found in list
[0fc0b5]673 */
[f92d00]674bool molecule::UnlinkAtom(atom *pointer)
[0fc0b5]675{
[f92d00]676 if (pointer == NULL)
677 return false;
678 if (ElementsInMolecule[pointer->type->Z] != 0) // this would indicate an error
679 ElementsInMolecule[pointer->type->Z]--; // decrease number of atom of this element
680 else
[418117a]681 eLog() << Verbose(1) << "Atom " << pointer->Name << " is of element " << pointer->type->Z << " but the entry in the table of the molecule is 0!" << endl;
[f92d00]682 if (ElementsInMolecule[pointer->type->Z] == 0) // was last atom of this element?
683 ElementCount--;
684 unlink(pointer);
685 return true;
[0fc0b5]686};
687
[f92d00]688/** Removes every atom from molecule list.
689 * \return true - succeeded, false - atom not found in list
[a0bcf1]690 */
[f92d00]691bool molecule::CleanupMolecule()
[a0bcf1]692{
[872b51]693 return (cleanup(first,last) && cleanup(start,end));
[e0c5b1]694};
[a0bcf1]695
[f92d00]696/** Finds an atom specified by its continuous number.
697 * \param Nr number of atom withim molecule
698 * \return pointer to atom or NULL
[a0bcf1]699 */
[f92d00]700atom * molecule::FindAtom(int Nr) const{
701 atom * walker = find(&Nr, start,end);
702 if (walker != NULL) {
[543ce4]703 //Log() << Verbose(0) << "Found Atom Nr. " << walker->nr << endl;
[f92d00]704 return walker;
705 } else {
[543ce4]706 Log() << Verbose(0) << "Atom not found in list." << endl;
[f92d00]707 return NULL;
[a048fa]708 }
[e0c5b1]709};
[a0bcf1]710
[f92d00]711/** Asks for atom number, and checks whether in list.
712 * \param *text question before entering
[d473c3]713 */
[f92d00]714atom * molecule::AskAtom(string text)
[d473c3]715{
[f92d00]716 int No;
717 atom *ion = NULL;
718 do {
[543ce4]719 //Log() << Verbose(0) << "============Atom list==========================" << endl;
[f92d00]720 //mol->Output((ofstream *)&cout);
[543ce4]721 //Log() << Verbose(0) << "===============================================" << endl;
722 Log() << Verbose(0) << text;
[f92d00]723 cin >> No;
724 ion = this->FindAtom(No);
725 } while (ion == NULL);
726 return ion;
[d473c3]727};
728
[f92d00]729/** Checks if given coordinates are within cell volume.
730 * \param *x array of coordinates
731 * \return true - is within, false - out of cell
[a0bcf1]732 */
[f92d00]733bool molecule::CheckBounds(const Vector *x) const
[a0bcf1]734{
[f92d00]735 bool result = true;
736 int j =-1;
737 for (int i=0;i<NDIM;i++) {
738 j += i+1;
739 result = result && ((x->x[i] >= 0) && (x->x[i] < cell_size[j]));
[a048fa]740 }
[f92d00]741 //return result;
742 return true; /// probably not gonna use the check no more
[e0c5b1]743};
[a0bcf1]744
[f92d00]745/** Prints molecule to *out.
746 * \param *out output stream
[a0bcf1]747 */
[543ce4]748bool molecule::Output(ofstream * const output)
[a0bcf1]749{
[f92d00]750 int ElementNo[MAX_ELEMENTS], AtomNo[MAX_ELEMENTS];
751 CountElements();
[a048fa]752
[f92d00]753 for (int i=0;i<MAX_ELEMENTS;++i) {
754 AtomNo[i] = 0;
755 ElementNo[i] = 0;
[a048fa]756 }
[543ce4]757 if (output == NULL) {
[f92d00]758 return false;
759 } else {
[543ce4]760 *output << "#Ion_TypeNr._Nr.R[0] R[1] R[2] MoveType (0 MoveIon, 1 FixedIon)" << endl;
[8ffe32]761 SetIndexedArrayForEachAtomTo ( ElementNo, &element::Z, &AbsoluteValue, 1);
[f92d00]762 int current=1;
763 for (int i=0;i<MAX_ELEMENTS;++i) {
764 if (ElementNo[i] == 1)
765 ElementNo[i] = current++;
766 }
[543ce4]767 ActOnAllAtoms( &atom::OutputArrayIndexed, output, (const int *)ElementNo, (int *)AtomNo, (const char *) NULL );
[f92d00]768 return true;
[a048fa]769 }
[a0bcf1]770};
771
[f92d00]772/** Prints molecule with all atomic trajectory positions to *out.
773 * \param *out output stream
[6fb785]774 */
[543ce4]775bool molecule::OutputTrajectories(ofstream * const output)
[6fb785]776{
[f92d00]777 int ElementNo[MAX_ELEMENTS], AtomNo[MAX_ELEMENTS];
778 CountElements();
[6fb785]779
[543ce4]780 if (output == NULL) {
[f92d00]781 return false;
782 } else {
783 for (int step = 0; step < MDSteps; step++) {
784 if (step == 0) {
[543ce4]785 *output << "#Ion_TypeNr._Nr.R[0] R[1] R[2] MoveType (0 MoveIon, 1 FixedIon)" << endl;
[c95b69]786 } else {
[543ce4]787 *output << "# ====== MD step " << step << " =========" << endl;
[f92d00]788 }
789 for (int i=0;i<MAX_ELEMENTS;++i) {
790 AtomNo[i] = 0;
791 ElementNo[i] = 0;
[c95b69]792 }
[8ffe32]793 SetIndexedArrayForEachAtomTo ( ElementNo, &element::Z, &AbsoluteValue, 1);
794 int current=1;
795 for (int i=0;i<MAX_ELEMENTS;++i) {
796 if (ElementNo[i] == 1)
797 ElementNo[i] = current++;
798 }
[543ce4]799 ActOnAllAtoms( &atom::OutputTrajectory, output, (const int *)ElementNo, AtomNo, (const int)step );
[6fb785]800 }
[f92d00]801 return true;
[6fb785]802 }
803};
804
[872b51]805/** Outputs contents of each atom::ListOfBonds.
[f92d00]806 * \param *out output stream
[a0bcf1]807 */
[543ce4]808void molecule::OutputListOfBonds() const
[a0bcf1]809{
[543ce4]810 Log() << Verbose(2) << endl << "From Contents of ListOfBonds, all non-hydrogen atoms:" << endl;
811 ActOnAllAtoms (&atom::OutputBondOfAtom );
812 Log() << Verbose(0) << endl;
[a0bcf1]813};
814
[f92d00]815/** Output of element before the actual coordination list.
816 * \param *out stream pointer
[a0bcf1]817 */
[543ce4]818bool molecule::Checkout(ofstream * const output) const
[a0bcf1]819{
[543ce4]820 return elemente->Checkout(output, ElementsInMolecule);
[c99adf]821};
822
[f92d00]823/** Prints molecule with all its trajectories to *out as xyz file.
824 * \param *out output stream
[0a08df]825 */
[543ce4]826bool molecule::OutputTrajectoriesXYZ(ofstream * const output)
[0a08df]827{
[f92d00]828 time_t now;
[a048fa]829
[543ce4]830 if (output != NULL) {
[0cd3b2]831 now = time((time_t *)NULL); // Get the system time and put it into 'now' as 'calender time'
[f92d00]832 for (int step=0;step<MDSteps;step++) {
[543ce4]833 *output << AtomCount << "\n\tCreated by molecuilder, step " << step << ", on " << ctime(&now);
834 ActOnAllAtoms( &atom::OutputTrajectoryXYZ, output, step );
[a048fa]835 }
[f92d00]836 return true;
837 } else
838 return false;
[a0bcf1]839};
840
[f92d00]841/** Prints molecule to *out as xyz file.
842* \param *out output stream
[e0c5b1]843 */
[543ce4]844bool molecule::OutputXYZ(ofstream * const output) const
[7670cab]845{
[f92d00]846 time_t now;
[a048fa]847
[543ce4]848 if (output != NULL) {
[972706]849 now = time((time_t *)NULL); // Get the system time and put it into 'now' as 'calender time'
[543ce4]850 *output << AtomCount << "\n\tCreated by molecuilder on " << ctime(&now);
851 ActOnAllAtoms( &atom::OutputXYZLine, output );
[a048fa]852 return true;
[f92d00]853 } else
854 return false;
855};
[7670cab]856
[f92d00]857/** Brings molecule::AtomCount and atom::*Name up-to-date.
[a0bcf1]858 * \param *out output stream for debugging
859 */
[543ce4]860void molecule::CountAtoms()
[a0bcf1]861{
[f92d00]862 int i = 0;
863 atom *Walker = start;
864 while (Walker->next != end) {
865 Walker = Walker->next;
866 i++;
867 }
868 if ((AtomCount == 0) || (i != AtomCount)) {
[543ce4]869 Log() << Verbose(3) << "Mismatch in AtomCount " << AtomCount << " and recounted number " << i << ", renaming all." << endl;
[f92d00]870 AtomCount = i;
[a048fa]871
[f92d00]872 // count NonHydrogen atoms and give each atom a unique name
873 if (AtomCount != 0) {
874 i=0;
875 NoNonHydrogen = 0;
876 Walker = start;
877 while (Walker->next != end) {
878 Walker = Walker->next;
879 Walker->nr = i; // update number in molecule (for easier referencing in FragmentMolecule lateron)
880 if (Walker->type->Z != 1) // count non-hydrogen atoms whilst at it
881 NoNonHydrogen++;
882 Free(&Walker->Name);
883 Walker->Name = Malloc<char>(6, "molecule::CountAtoms: *walker->Name");
884 sprintf(Walker->Name, "%2s%02d", Walker->type->symbol, Walker->nr+1);
[543ce4]885 Log() << Verbose(3) << "Naming atom nr. " << Walker->nr << " " << Walker->Name << "." << endl;
[f92d00]886 i++;
[a048fa]887 }
[f92d00]888 } else
[543ce4]889 Log() << Verbose(3) << "AtomCount is still " << AtomCount << ", thus counting nothing." << endl;
[a048fa]890 }
[f92d00]891};
[a048fa]892
[f92d00]893/** Brings molecule::ElementCount and molecule::ElementsInMolecule up-to-date.
894 */
895void molecule::CountElements()
896{
[972706]897 for(int i=MAX_ELEMENTS;i--;)
[f92d00]898 ElementsInMolecule[i] = 0;
899 ElementCount = 0;
[a048fa]900
[972706]901 SetIndexedArrayForEachAtomTo ( ElementsInMolecule, &element::Z, &Increment, 1);
902
903 for(int i=MAX_ELEMENTS;i--;)
[f92d00]904 ElementCount += (ElementsInMolecule[i] != 0 ? 1 : 0);
905};
[a048fa]906
907
[f92d00]908/** Counts necessary number of valence electrons and returns number and SpinType.
909 * \param configuration containing everything
910 */
911void molecule::CalculateOrbitals(class config &configuration)
912{
913 configuration.MaxPsiDouble = configuration.PsiMaxNoDown = configuration.PsiMaxNoUp = configuration.PsiType = 0;
914 for(int i=MAX_ELEMENTS;i--;) {
915 if (ElementsInMolecule[i] != 0) {
[543ce4]916 //Log() << Verbose(0) << "CalculateOrbitals: " << elemente->FindElement(i)->name << " has a valence of " << (int)elemente->FindElement(i)->Valence << " and there are " << ElementsInMolecule[i] << " of it." << endl;
[f92d00]917 configuration.MaxPsiDouble += ElementsInMolecule[i]*((int)elemente->FindElement(i)->Valence);
[a048fa]918 }
919 }
[f92d00]920 configuration.PsiMaxNoDown = configuration.MaxPsiDouble/2 + (configuration.MaxPsiDouble % 2);
921 configuration.PsiMaxNoUp = configuration.MaxPsiDouble/2;
922 configuration.MaxPsiDouble /= 2;
923 configuration.PsiType = (configuration.PsiMaxNoDown == configuration.PsiMaxNoUp) ? 0 : 1;
924 if ((configuration.PsiType == 1) && (configuration.ProcPEPsi < 2)) {
925 configuration.ProcPEGamma /= 2;
926 configuration.ProcPEPsi *= 2;
927 } else {
928 configuration.ProcPEGamma *= configuration.ProcPEPsi;
929 configuration.ProcPEPsi = 1;
930 }
931 configuration.InitMaxMinStopStep = configuration.MaxMinStopStep = configuration.MaxPsiDouble;
[a0bcf1]932};
933
934/** Determines whether two molecules actually contain the same atoms and coordination.
935 * \param *out output stream for debugging
936 * \param *OtherMolecule the molecule to compare this one to
937 * \param threshold upper limit of difference when comparing the coordination.
938 * \return NULL - not equal, otherwise an allocated (molecule::AtomCount) permutation map of the atom numbers (which corresponds to which)
939 */
[543ce4]940int * molecule::IsEqualToWithinThreshold(molecule *OtherMolecule, double threshold)
[a0bcf1]941{
[a048fa]942 int flag;
943 double *Distances = NULL, *OtherDistances = NULL;
944 Vector CenterOfGravity, OtherCenterOfGravity;
945 size_t *PermMap = NULL, *OtherPermMap = NULL;
946 int *PermutationMap = NULL;
947 bool result = true; // status of comparison
948
[543ce4]949 Log() << Verbose(3) << "Begin of IsEqualToWithinThreshold." << endl;
[a048fa]950 /// first count both their atoms and elements and update lists thereby ...
[543ce4]951 //Log() << Verbose(0) << "Counting atoms, updating list" << endl;
952 CountAtoms();
953 OtherMolecule->CountAtoms();
[a048fa]954 CountElements();
955 OtherMolecule->CountElements();
956
957 /// ... and compare:
958 /// -# AtomCount
959 if (result) {
960 if (AtomCount != OtherMolecule->AtomCount) {
[543ce4]961 Log() << Verbose(4) << "AtomCounts don't match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
[a048fa]962 result = false;
[543ce4]963 } else Log() << Verbose(4) << "AtomCounts match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
[a048fa]964 }
965 /// -# ElementCount
966 if (result) {
967 if (ElementCount != OtherMolecule->ElementCount) {
[543ce4]968 Log() << Verbose(4) << "ElementCount don't match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
[a048fa]969 result = false;
[543ce4]970 } else Log() << Verbose(4) << "ElementCount match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
[a048fa]971 }
972 /// -# ElementsInMolecule
973 if (result) {
974 for (flag=MAX_ELEMENTS;flag--;) {
[543ce4]975 //Log() << Verbose(5) << "Element " << flag << ": " << ElementsInMolecule[flag] << " <-> " << OtherMolecule->ElementsInMolecule[flag] << "." << endl;
[a048fa]976 if (ElementsInMolecule[flag] != OtherMolecule->ElementsInMolecule[flag])
977 break;
978 }
979 if (flag < MAX_ELEMENTS) {
[543ce4]980 Log() << Verbose(4) << "ElementsInMolecule don't match." << endl;
[a048fa]981 result = false;
[543ce4]982 } else Log() << Verbose(4) << "ElementsInMolecule match." << endl;
[a048fa]983 }
984 /// then determine and compare center of gravity for each molecule ...
985 if (result) {
[543ce4]986 Log() << Verbose(5) << "Calculating Centers of Gravity" << endl;
[1b2aa1]987 DeterminePeriodicCenter(CenterOfGravity);
988 OtherMolecule->DeterminePeriodicCenter(OtherCenterOfGravity);
[543ce4]989 Log() << Verbose(5) << "Center of Gravity: ";
990 CenterOfGravity.Output();
991 Log() << Verbose(0) << endl << Verbose(5) << "Other Center of Gravity: ";
992 OtherCenterOfGravity.Output();
993 Log() << Verbose(0) << endl;
[a048fa]994 if (CenterOfGravity.DistanceSquared(&OtherCenterOfGravity) > threshold*threshold) {
[543ce4]995 Log() << Verbose(4) << "Centers of gravity don't match." << endl;
[a048fa]996 result = false;
997 }
998 }
999
1000 /// ... then make a list with the euclidian distance to this center for each atom of both molecules
1001 if (result) {
[543ce4]1002 Log() << Verbose(5) << "Calculating distances" << endl;
[8bc524]1003 Distances = Calloc<double>(AtomCount, "molecule::IsEqualToWithinThreshold: Distances");
1004 OtherDistances = Calloc<double>(AtomCount, "molecule::IsEqualToWithinThreshold: OtherDistances");
[94d0ad]1005 SetIndexedArrayForEachAtomTo ( Distances, &atom::nr, &atom::DistanceSquaredToVector, (const Vector &)CenterOfGravity);
1006 SetIndexedArrayForEachAtomTo ( OtherDistances, &atom::nr, &atom::DistanceSquaredToVector, (const Vector &)CenterOfGravity);
[a048fa]1007
1008 /// ... sort each list (using heapsort (o(N log N)) from GSL)
[543ce4]1009 Log() << Verbose(5) << "Sorting distances" << endl;
[8bc524]1010 PermMap = Calloc<size_t>(AtomCount, "molecule::IsEqualToWithinThreshold: *PermMap");
1011 OtherPermMap = Calloc<size_t>(AtomCount, "molecule::IsEqualToWithinThreshold: *OtherPermMap");
[a048fa]1012 gsl_heapsort_index (PermMap, Distances, AtomCount, sizeof(double), CompareDoubles);
1013 gsl_heapsort_index (OtherPermMap, OtherDistances, AtomCount, sizeof(double), CompareDoubles);
[8bc524]1014 PermutationMap = Calloc<int>(AtomCount, "molecule::IsEqualToWithinThreshold: *PermutationMap");
[543ce4]1015 Log() << Verbose(5) << "Combining Permutation Maps" << endl;
[a048fa]1016 for(int i=AtomCount;i--;)
1017 PermutationMap[PermMap[i]] = (int) OtherPermMap[i];
1018
[390a2b]1019 /// ... and compare them step by step, whether the difference is individually(!) below \a threshold for all
[543ce4]1020 Log() << Verbose(4) << "Comparing distances" << endl;
[a048fa]1021 flag = 0;
1022 for (int i=0;i<AtomCount;i++) {
[543ce4]1023 Log() << Verbose(5) << "Distances squared: |" << Distances[PermMap[i]] << " - " << OtherDistances[OtherPermMap[i]] << "| = " << fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) << " ?<? " << threshold << endl;
[a048fa]1024 if (fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) > threshold*threshold)
1025 flag = 1;
1026 }
1027
[390a2b]1028 // free memory
1029 Free(&PermMap);
1030 Free(&OtherPermMap);
1031 Free(&Distances);
1032 Free(&OtherDistances);
[a048fa]1033 if (flag) { // if not equal
[390a2b]1034 Free(&PermutationMap);
[a048fa]1035 result = false;
1036 }
1037 }
1038 /// return pointer to map if all distances were below \a threshold
[543ce4]1039 Log() << Verbose(3) << "End of IsEqualToWithinThreshold." << endl;
[a048fa]1040 if (result) {
[543ce4]1041 Log() << Verbose(3) << "Result: Equal." << endl;
[a048fa]1042 return PermutationMap;
1043 } else {
[543ce4]1044 Log() << Verbose(3) << "Result: Not equal." << endl;
[a048fa]1045 return NULL;
1046 }
[a0bcf1]1047};
1048
1049/** Returns an index map for two father-son-molecules.
1050 * The map tells which atom in this molecule corresponds to which one in the other molecul with their fathers.
1051 * \param *out output stream for debugging
1052 * \param *OtherMolecule corresponding molecule with fathers
1053 * \return allocated map of size molecule::AtomCount with map
1054 * \todo make this with a good sort O(n), not O(n^2)
1055 */
[543ce4]1056int * molecule::GetFatherSonAtomicMap(molecule *OtherMolecule)
[a0bcf1]1057{
[a048fa]1058 atom *Walker = NULL, *OtherWalker = NULL;
[543ce4]1059 Log() << Verbose(3) << "Begin of GetFatherAtomicMap." << endl;
[390a2b]1060 int *AtomicMap = Malloc<int>(AtomCount, "molecule::GetAtomicMap: *AtomicMap");
[a048fa]1061 for (int i=AtomCount;i--;)
1062 AtomicMap[i] = -1;
1063 if (OtherMolecule == this) { // same molecule
1064 for (int i=AtomCount;i--;) // no need as -1 means already that there is trivial correspondence
1065 AtomicMap[i] = i;
[543ce4]1066 Log() << Verbose(4) << "Map is trivial." << endl;
[a048fa]1067 } else {
[543ce4]1068 Log() << Verbose(4) << "Map is ";
[a048fa]1069 Walker = start;
1070 while (Walker->next != end) {
1071 Walker = Walker->next;
1072 if (Walker->father == NULL) {
1073 AtomicMap[Walker->nr] = -2;
1074 } else {
1075 OtherWalker = OtherMolecule->start;
1076 while (OtherWalker->next != OtherMolecule->end) {
1077 OtherWalker = OtherWalker->next;
1078 //for (int i=0;i<AtomCount;i++) { // search atom
1079 //for (int j=0;j<OtherMolecule->AtomCount;j++) {
[543ce4]1080 //Log() << Verbose(4) << "Comparing father " << Walker->father << " with the other one " << OtherWalker->father << "." << endl;
[a048fa]1081 if (Walker->father == OtherWalker)
1082 AtomicMap[Walker->nr] = OtherWalker->nr;
1083 }
1084 }
[543ce4]1085 Log() << Verbose(0) << AtomicMap[Walker->nr] << "\t";
[a048fa]1086 }
[543ce4]1087 Log() << Verbose(0) << endl;
[a048fa]1088 }
[543ce4]1089 Log() << Verbose(3) << "End of GetFatherAtomicMap." << endl;
[a048fa]1090 return AtomicMap;
[a0bcf1]1091};
1092
[79cd79]1093/** Stores the temperature evaluated from velocities in molecule::Trajectories.
1094 * We simply use the formula equivaleting temperature and kinetic energy:
1095 * \f$k_B T = \sum_i m_i v_i^2\f$
[543ce4]1096 * \param *output output stream of temperature file
[79cd79]1097 * \param startstep first MD step in molecule::Trajectories
1098 * \param endstep last plus one MD step in molecule::Trajectories
1099 * \return file written (true), failure on writing file (false)
[e0c5b1]1100 */
[543ce4]1101bool molecule::OutputTemperatureFromTrajectories(ofstream * const output, int startstep, int endstep)
[79cd79]1102{
[a048fa]1103 double temperature;
1104 // test stream
1105 if (output == NULL)
1106 return false;
1107 else
1108 *output << "# Step Temperature [K] Temperature [a.u.]" << endl;
1109 for (int step=startstep;step < endstep; step++) { // loop over all time steps
1110 temperature = 0.;
[6b937bd]1111 ActOnAllAtoms( &TrajectoryParticle::AddKineticToTemperature, &temperature, step);
[a048fa]1112 *output << step << "\t" << temperature*AtomicEnergyToKelvin << "\t" << temperature << endl;
1113 }
1114 return true;
[f5d7e1]1115};
[7c2f6b]1116
[94d0ad]1117void molecule::SetIndexedArrayForEachAtomTo ( atom **array, int ParticleInfo::*index) const
[7c2f6b]1118{
1119 atom *Walker = start;
1120 while (Walker->next != end) {
1121 Walker = Walker->next;
1122 array[(Walker->*index)] = Walker;
1123 }
1124};
[f00f02]1125
1126void molecule::flipActiveFlag(){
1127 ActiveFlag = !ActiveFlag;
1128}
Note: See TracBrowser for help on using the repository browser.