source: molecuilder/src/molecule.cpp@ e7ea64

Last change on this file since e7ea64 was e7ea64, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Changed implementation of Vector to forward operations to contained objects

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