source: molecuilder/src/molecule.cpp@ db6b872

Last change on this file since db6b872 was 98a2987, checked in by Tillmann Crueger <crueger@…>, 16 years ago

Added -Wall flag and fixed several small hickups

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