source: src/molecule.cpp@ 8bb2fd

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 8bb2fd was ead4e6, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Made the periodentafel use STL-containers instead of custom llists

  • Property mode set to 100755
File size: 45.4 KB
Line 
1/** \file molecules.cpp
2 *
3 * Functions for the class molecule.
4 *
5 */
6
7#include <cstring>
8#include <boost/bind.hpp>
9
10#include "World.hpp"
11#include "atom.hpp"
12#include "bond.hpp"
13#include "config.hpp"
14#include "element.hpp"
15#include "graph.hpp"
16#include "helpers.hpp"
17#include "leastsquaremin.hpp"
18#include "linkedcell.hpp"
19#include "lists.hpp"
20#include "log.hpp"
21#include "molecule.hpp"
22#include "memoryallocator.hpp"
23#include "periodentafel.hpp"
24#include "stackclass.hpp"
25#include "tesselation.hpp"
26#include "vector.hpp"
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 */
33molecule::molecule(const periodentafel * const teil) : elemente(teil), start(World::getInstance().createAtom()), end(World::getInstance().createAtom()),
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.),
36 ActiveFlag(false), IndexNr(-1),
37 formula(this,boost::bind(&molecule::calcFormula,this)),
38 last_atom(0),
39 InternalPointer(start)
40{
41 // init atom chain list
42 start->father = NULL;
43 end->father = NULL;
44 link(start,end);
45
46 // init bond chain list
47 link(first,last);
48
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");
55};
56
57molecule *NewMolecule(){
58 return new molecule(World::getInstance().getPeriode());
59}
60
61/** Destructor of class molecule.
62 * Initialises molecule list with correctly referenced start and end, and sets molecule::last_atom to zero.
63 */
64molecule::~molecule()
65{
66 CleanupMolecule();
67 delete(first);
68 delete(last);
69 end->getWorld()->destroyAtom(end);
70 start->getWorld()->destroyAtom(start);
71};
72
73
74void DeleteMolecule(molecule *mol){
75 delete mol;
76}
77
78// getter and setter
79const std::string molecule::getName(){
80 return std::string(name);
81}
82
83void molecule::setName(const std::string _name){
84 OBSERVE;
85 strncpy(name,_name.c_str(),MAXSTRINGSIZE);
86}
87
88moleculeId_t molecule::getId(){
89 return id;
90}
91
92void molecule::setId(moleculeId_t _id){
93 id =_id;
94}
95
96const std::string molecule::getFormula(){
97 return *formula;
98}
99
100std::string molecule::calcFormula(){
101 std::map<atomicNumber_t,unsigned int> counts;
102 stringstream sstr;
103 periodentafel *periode = World::getInstance().getPeriode();
104 for(atom *Walker = start; Walker != end; Walker = Walker->next) {
105 counts[Walker->type->getNumber()]++;
106 }
107 std::map<atomicNumber_t,unsigned int>::reverse_iterator iter;
108 for(iter = counts.rbegin(); iter != counts.rend(); ++iter) {
109 atomicNumber_t Z = (*iter).first;
110 sstr << periode->FindElement(Z)->symbol << (*iter).second;
111 }
112 return sstr.str();
113}
114
115
116/** Adds given atom \a *pointer from molecule list.
117 * Increases molecule::last_atom and gives last number to added atom and names it according to its element::abbrev and molecule::AtomCount
118 * \param *pointer allocated and set atom
119 * \return true - succeeded, false - atom not found in list
120 */
121bool molecule::AddAtom(atom *pointer)
122{
123 bool retval = false;
124 OBSERVE;
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) {
136 Free(&pointer->Name);
137 pointer->Name = Malloc<char>(6, "molecule::AddAtom: *pointer->Name");
138 sprintf(pointer->Name, "%2s%02d", pointer->type->symbol, pointer->nr+1);
139 }
140 }
141 retval = add(pointer, end);
142 }
143 return retval;
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
149 * \return pointer to the newly added atom
150 */
151atom * molecule::AddCopyAtom(atom *pointer)
152{
153 atom *retval = NULL;
154 OBSERVE;
155 if (pointer != NULL) {
156 atom *walker = pointer->clone();
157 walker->Name = Malloc<char>(strlen(pointer->Name) + 1, "atom::atom: *Name");
158 strcpy (walker->Name, pointer->Name);
159 walker->nr = last_atom++; // increase number within molecule
160 add(walker, end);
161 if ((pointer->type != NULL) && (pointer->type->Z != 1))
162 NoNonHydrogen++;
163 AtomCount++;
164 retval=walker;
165 }
166 return retval;
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
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.
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
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$.
193 *
194 * \param *out output stream for debugging
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)
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 */
203bool molecule::AddHydrogenReplacementAtom(bond *TopBond, atom *BottomOrigin, atom *TopOrigin, atom *TopReplacement, bool IsAngstroem)
204{
205 bool AllWentWell = true; // flag gathering the boolean return value of molecule::AddAtom and other functions, as return value on exit
206 OBSERVE;
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
215 double *matrix = NULL;
216 bond *Binder = NULL;
217
218// Log() << Verbose(3) << "Begin of AddHydrogenReplacementAtom." << endl;
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) {
228// Log() << Verbose(4) << "InBondvector is: ";
229// InBondvector.Output(out);
230// Log() << Verbose(0) << endl;
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
241 Free(&matrix);
242 bondlength = InBondvector.Norm();
243// Log() << Verbose(4) << "Corrected InBondvector is now: ";
244// InBondvector.Output(out);
245// Log() << Verbose(0) << endl;
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) {
252 eLog() << Verbose(1) << "There is no typical hydrogen bond distance in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
253 return false;
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:
263 FirstOtherAtom = World::getInstance().createAtom(); // new atom
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);
277// Log() << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
278// FirstOtherAtom->x.Output(out);
279// Log() << Verbose(0) << endl;
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
286 for (BondList::const_iterator Runner = TopOrigin->ListOfBonds.begin(); Runner != TopOrigin->ListOfBonds.end(); (++Runner)) {
287 if ((*Runner) != TopBond) {
288 if (FirstBond == NULL) {
289 FirstBond = (*Runner);
290 FirstOtherAtom = (*Runner)->GetOtherAtom(TopOrigin);
291 } else if (SecondBond == NULL) {
292 SecondBond = (*Runner);
293 SecondOtherAtom = (*Runner)->GetOtherAtom(TopOrigin);
294 } else {
295 eLog() << Verbose(2) << "Detected more than four bonds for atom " << TopOrigin->Name;
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
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;
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 }
311 //Log() << Verbose(3)<< "Orthovector1: ";
312 //Orthovector1.Output(out);
313 //Log() << Verbose(0) << endl;
314 // orthogonal vector and bond vector between origin and replacement form the new plane
315 Orthovector1.MakeNormalVector(&InBondvector);
316 Orthovector1.Normalize();
317 //Log() << Verbose(3) << "ReScaleCheck: " << Orthovector1.Norm() << " and " << InBondvector.Norm() << "." << endl;
318
319 // create the two Hydrogens ...
320 FirstOtherAtom = World::getInstance().createAtom();
321 SecondOtherAtom = World::getInstance().createAtom();
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) {
332 eLog() << Verbose(1) << "There is no typical hydrogen bond angle in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
333 return false;
334 bondangle = 0;
335 }
336 bondangle *= M_PI/180./2.;
337// Log() << Verbose(3) << "ReScaleCheck: InBondvector ";
338// InBondvector.Output(out);
339// Log() << Verbose(0) << endl;
340// Log() << Verbose(3) << "ReScaleCheck: Orthovector ";
341// Orthovector1.Output(out);
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;
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);
352 //Log() << Verbose(3) << "ReScaleCheck: " << FirstOtherAtom->x.Norm() << " and " << SecondOtherAtom->x.Norm() << "." << endl;
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);
360// Log() << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
361// FirstOtherAtom->x.Output(out);
362// Log() << Verbose(0) << endl;
363// Log() << Verbose(4) << "Added " << *SecondOtherAtom << " at: ";
364// SecondOtherAtom->x.Output(out);
365// Log() << Verbose(0) << endl;
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)
375 FirstOtherAtom = World::getInstance().createAtom();
376 SecondOtherAtom = World::getInstance().createAtom();
377 ThirdOtherAtom = World::getInstance().createAtom();
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);
393// Log() << Verbose(3) << "Orthovector1: ";
394// Orthovector1.Output(out);
395// Log() << Verbose(0) << endl;
396 AllWentWell = AllWentWell && Orthovector2.MakeNormalVector(&InBondvector, &Orthovector1);
397// Log() << Verbose(3) << "Orthovector2: ";
398// Orthovector2.Output(out);
399// Log() << Verbose(0) << endl;
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
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;
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);
434// Log() << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
435// FirstOtherAtom->x.Output(out);
436// Log() << Verbose(0) << endl;
437// Log() << Verbose(4) << "Added " << *SecondOtherAtom << " at: ";
438// SecondOtherAtom->x.Output(out);
439// Log() << Verbose(0) << endl;
440// Log() << Verbose(4) << "Added " << *ThirdOtherAtom << " at: ";
441// ThirdOtherAtom->x.Output(out);
442// Log() << Verbose(0) << endl;
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:
454 eLog() << Verbose(1) << "BondDegree does not state single, double or triple bond!" << endl;
455 AllWentWell = false;
456 break;
457 }
458 Free(&matrix);
459
460// Log() << Verbose(3) << "End of AddHydrogenReplacementAtom." << endl;
461 return AllWentWell;
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)
470{
471
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
485 OBSERVE;
486 getline(xyzfile,line,'\n'); // Read numer of atoms in file
487 input = new istringstream(line);
488 *input >> NumberOfAtoms;
489 Log() << Verbose(0) << "Parsing " << NumberOfAtoms << " atoms in file." << endl;
490 getline(xyzfile,line,'\n'); // Read comment
491 Log() << Verbose(1) << "Comment: " << line << endl;
492
493 if (MDSteps == 0) // no atoms yet present
494 MDSteps++;
495 for(i=0;i<NumberOfAtoms;i++){
496 Walker = World::getInstance().createAtom();
497 getline(xyzfile,line,'\n');
498 istringstream *item = new istringstream(line);
499 //istringstream input(line);
500 //Log() << Verbose(1) << "Reading: " << line << endl;
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) {
507 eLog() << Verbose(1) << "Could not parse the element at line: '" << line << "', setting to H.";
508 Walker->type = elemente->FindElement(1);
509 }
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);
514 }
515 for(j=NDIM;j--;) {
516 Walker->x.x[j] = x[j];
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;
520 }
521 AddAtom(Walker); // add to molecule
522 delete(item);
523 }
524 xyzfile.close();
525 delete(input);
526 return true;
527};
528
529/** Creates a copy of this molecule.
530 * \return copy of molecule
531 */
532molecule *molecule::CopyMolecule()
533{
534 molecule *copy = new molecule(elemente);
535 atom *LeftAtom = NULL, *RightAtom = NULL;
536
537 // copy all atoms
538 ActOnCopyWithEachAtom ( &molecule::AddCopyAtom, copy );
539
540 // copy all bonds
541 bond *Binder = first;
542 bond *NewBond = NULL;
543 while(Binder->next != last) {
544 Binder = Binder->next;
545
546 // get the pendant atoms of current bond in the copy molecule
547 copy->ActOnAllAtoms( &atom::EqualsFather, (const atom *)Binder->leftatom, (const atom **)&LeftAtom );
548 copy->ActOnAllAtoms( &atom::EqualsFather, (const atom *)Binder->rightatom, (const atom **)&RightAtom );
549
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
557 ActOnAllAtoms( &atom::CorrectFather );
558
559 // copy values
560 copy->CountAtoms();
561 copy->CountElements();
562 if (first->next != last) { // if adjaceny list is present
563 copy->BondDistance = BondDistance;
564 }
565
566 return copy;
567};
568
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 */
576molecule* molecule::CopyMoleculeFromSubRegion(const Vector offset, const double *parallelepiped) const {
577 molecule *copy = new molecule(elemente);
578
579 ActOnCopyWithEachAtomIfTrue ( &molecule::AddCopyAtom, copy, &atom::IsInParallelepiped, offset, parallelepiped );
580
581 //TODO: copy->BuildInducedSubgraph(this);
582
583 return copy;
584}
585
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 */
592bond * molecule::AddBond(atom *atom1, atom *atom2, int degree)
593{
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++);
597 atom1->RegisterBond(Binder);
598 atom2->RegisterBond(Binder);
599 if ((atom1->type != NULL) && (atom1->type->Z != 1) && (atom2->type != NULL) && (atom2->type->Z != 1))
600 NoNonBonds++;
601 add(Binder, last);
602 } else {
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;
604 }
605 return Binder;
606};
607
608/** Remove bond from bond chain list and from the both atom::ListOfBonds.
609 * \todo Function not implemented yet
610 * \param *pointer bond pointer
611 * \return true - bound found and removed, false - bond not found/removed
612 */
613bool molecule::RemoveBond(bond *pointer)
614{
615 //eLog() << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
616 pointer->leftatom->RegisterBond(pointer);
617 pointer->rightatom->RegisterBond(pointer);
618 removewithoutcheck(pointer);
619 return true;
620};
621
622/** Remove every bond from bond chain list that atom \a *BondPartner is a constituent of.
623 * \todo Function not implemented yet
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{
629 //eLog() << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
630 BondList::const_iterator ForeRunner;
631 while (!BondPartner->ListOfBonds.empty()) {
632 ForeRunner = BondPartner->ListOfBonds.begin();
633 RemoveBond(*ForeRunner);
634 }
635 return false;
636};
637
638/** Set molecule::name from the basename without suffix in the given \a *filename.
639 * \param *filename filename
640 */
641void molecule::SetNameFromFilename(const char *filename)
642{
643 int length = 0;
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
649 const char *endname = strchr(molname, '.');
650 if ((endname == NULL) || (endname < molname))
651 length = strlen(molname);
652 else
653 length = strlen(molname) - strlen(endname);
654 strncpy(name, molname, length);
655 name[length]='\0';
656};
657
658/** Sets the molecule::cell_size to the components of \a *dim (rectangular box)
659 * \param *dim vector class
660 */
661void molecule::SetBoxDimension(Vector *dim)
662{
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];
669};
670
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
674 */
675bool molecule::RemoveAtom(atom *pointer)
676{
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
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;
682 if (ElementsInMolecule[pointer->type->Z] == 0) // was last atom of this element?
683 ElementCount--;
684 RemoveBonds(pointer);
685 return remove(pointer, start, end);
686};
687
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
691 */
692bool molecule::UnlinkAtom(atom *pointer)
693{
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
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;
700 if (ElementsInMolecule[pointer->type->Z] == 0) // was last atom of this element?
701 ElementCount--;
702 unlink(pointer);
703 return true;
704};
705
706/** Removes every atom from molecule list.
707 * \return true - succeeded, false - atom not found in list
708 */
709bool molecule::CleanupMolecule()
710{
711 return (cleanup(first,last) && cleanup(start,end));
712};
713
714/** Finds an atom specified by its continuous number.
715 * \param Nr number of atom withim molecule
716 * \return pointer to atom or NULL
717 */
718atom * molecule::FindAtom(int Nr) const{
719 atom * walker = find(&Nr, start,end);
720 if (walker != NULL) {
721 //Log() << Verbose(0) << "Found Atom Nr. " << walker->nr << endl;
722 return walker;
723 } else {
724 Log() << Verbose(0) << "Atom not found in list." << endl;
725 return NULL;
726 }
727};
728
729/** Asks for atom number, and checks whether in list.
730 * \param *text question before entering
731 */
732atom * molecule::AskAtom(string text)
733{
734 int No;
735 atom *ion = NULL;
736 do {
737 //Log() << Verbose(0) << "============Atom list==========================" << endl;
738 //mol->Output((ofstream *)&cout);
739 //Log() << Verbose(0) << "===============================================" << endl;
740 Log() << Verbose(0) << text;
741 cin >> No;
742 ion = this->FindAtom(No);
743 } while (ion == NULL);
744 return ion;
745};
746
747/** Checks if given coordinates are within cell volume.
748 * \param *x array of coordinates
749 * \return true - is within, false - out of cell
750 */
751bool molecule::CheckBounds(const Vector *x) const
752{
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]));
758 }
759 //return result;
760 return true; /// probably not gonna use the check no more
761};
762
763/** Prints molecule to *out.
764 * \param *out output stream
765 */
766bool molecule::Output(ofstream * const output)
767{
768 int ElementNo[MAX_ELEMENTS], AtomNo[MAX_ELEMENTS];
769 CountElements();
770
771 for (int i=0;i<MAX_ELEMENTS;++i) {
772 AtomNo[i] = 0;
773 ElementNo[i] = 0;
774 }
775 if (output == NULL) {
776 return false;
777 } else {
778 *output << "#Ion_TypeNr._Nr.R[0] R[1] R[2] MoveType (0 MoveIon, 1 FixedIon)" << endl;
779 SetIndexedArrayForEachAtomTo ( ElementNo, &element::Z, &AbsoluteValue, 1);
780 int current=1;
781 for (int i=0;i<MAX_ELEMENTS;++i) {
782 if (ElementNo[i] == 1)
783 ElementNo[i] = current++;
784 }
785 ActOnAllAtoms( &atom::OutputArrayIndexed, output, (const int *)ElementNo, (int *)AtomNo, (const char *) NULL );
786 return true;
787 }
788};
789
790/** Prints molecule with all atomic trajectory positions to *out.
791 * \param *out output stream
792 */
793bool molecule::OutputTrajectories(ofstream * const output)
794{
795 int ElementNo[MAX_ELEMENTS], AtomNo[MAX_ELEMENTS];
796 CountElements();
797
798 if (output == NULL) {
799 return false;
800 } else {
801 for (int step = 0; step < MDSteps; step++) {
802 if (step == 0) {
803 *output << "#Ion_TypeNr._Nr.R[0] R[1] R[2] MoveType (0 MoveIon, 1 FixedIon)" << endl;
804 } else {
805 *output << "# ====== MD step " << step << " =========" << endl;
806 }
807 for (int i=0;i<MAX_ELEMENTS;++i) {
808 AtomNo[i] = 0;
809 ElementNo[i] = 0;
810 }
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 }
817 ActOnAllAtoms( &atom::OutputTrajectory, output, (const int *)ElementNo, AtomNo, (const int)step );
818 }
819 return true;
820 }
821};
822
823/** Outputs contents of each atom::ListOfBonds.
824 * \param *out output stream
825 */
826void molecule::OutputListOfBonds() const
827{
828 Log() << Verbose(2) << endl << "From Contents of ListOfBonds, all non-hydrogen atoms:" << endl;
829 ActOnAllAtoms (&atom::OutputBondOfAtom );
830 Log() << Verbose(0) << endl;
831};
832
833/** Output of element before the actual coordination list.
834 * \param *out stream pointer
835 */
836bool molecule::Checkout(ofstream * const output) const
837{
838 return elemente->Checkout(output, ElementsInMolecule);
839};
840
841/** Prints molecule with all its trajectories to *out as xyz file.
842 * \param *out output stream
843 */
844bool molecule::OutputTrajectoriesXYZ(ofstream * const output)
845{
846 time_t now;
847
848 if (output != NULL) {
849 now = time((time_t *)NULL); // Get the system time and put it into 'now' as 'calender time'
850 for (int step=0;step<MDSteps;step++) {
851 *output << AtomCount << "\n\tCreated by molecuilder, step " << step << ", on " << ctime(&now);
852 ActOnAllAtoms( &atom::OutputTrajectoryXYZ, output, step );
853 }
854 return true;
855 } else
856 return false;
857};
858
859/** Prints molecule to *out as xyz file.
860* \param *out output stream
861 */
862bool molecule::OutputXYZ(ofstream * const output) const
863{
864 time_t now;
865
866 if (output != NULL) {
867 now = time((time_t *)NULL); // Get the system time and put it into 'now' as 'calender time'
868 *output << AtomCount << "\n\tCreated by molecuilder on " << ctime(&now);
869 ActOnAllAtoms( &atom::OutputXYZLine, output );
870 return true;
871 } else
872 return false;
873};
874
875/** Brings molecule::AtomCount and atom::*Name up-to-date.
876 * \param *out output stream for debugging
877 */
878void molecule::CountAtoms()
879{
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)) {
887 Log() << Verbose(3) << "Mismatch in AtomCount " << AtomCount << " and recounted number " << i << ", renaming all." << endl;
888 AtomCount = i;
889
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);
903 Log() << Verbose(3) << "Naming atom nr. " << Walker->nr << " " << Walker->Name << "." << endl;
904 i++;
905 }
906 } else
907 Log() << Verbose(3) << "AtomCount is still " << AtomCount << ", thus counting nothing." << endl;
908 }
909};
910
911/** Brings molecule::ElementCount and molecule::ElementsInMolecule up-to-date.
912 */
913void molecule::CountElements()
914{
915 for(int i=MAX_ELEMENTS;i--;)
916 ElementsInMolecule[i] = 0;
917 ElementCount = 0;
918
919 SetIndexedArrayForEachAtomTo ( ElementsInMolecule, &element::Z, &Increment, 1);
920
921 for(int i=MAX_ELEMENTS;i--;)
922 ElementCount += (ElementsInMolecule[i] != 0 ? 1 : 0);
923};
924
925
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) {
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;
935 configuration.MaxPsiDouble += ElementsInMolecule[i]*((int)elemente->FindElement(i)->Valence);
936 }
937 }
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;
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 */
958int * molecule::IsEqualToWithinThreshold(molecule *OtherMolecule, double threshold)
959{
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
967 Log() << Verbose(3) << "Begin of IsEqualToWithinThreshold." << endl;
968 /// first count both their atoms and elements and update lists thereby ...
969 //Log() << Verbose(0) << "Counting atoms, updating list" << endl;
970 CountAtoms();
971 OtherMolecule->CountAtoms();
972 CountElements();
973 OtherMolecule->CountElements();
974
975 /// ... and compare:
976 /// -# AtomCount
977 if (result) {
978 if (AtomCount != OtherMolecule->AtomCount) {
979 Log() << Verbose(4) << "AtomCounts don't match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
980 result = false;
981 } else Log() << Verbose(4) << "AtomCounts match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
982 }
983 /// -# ElementCount
984 if (result) {
985 if (ElementCount != OtherMolecule->ElementCount) {
986 Log() << Verbose(4) << "ElementCount don't match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
987 result = false;
988 } else Log() << Verbose(4) << "ElementCount match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
989 }
990 /// -# ElementsInMolecule
991 if (result) {
992 for (flag=MAX_ELEMENTS;flag--;) {
993 //Log() << Verbose(5) << "Element " << flag << ": " << ElementsInMolecule[flag] << " <-> " << OtherMolecule->ElementsInMolecule[flag] << "." << endl;
994 if (ElementsInMolecule[flag] != OtherMolecule->ElementsInMolecule[flag])
995 break;
996 }
997 if (flag < MAX_ELEMENTS) {
998 Log() << Verbose(4) << "ElementsInMolecule don't match." << endl;
999 result = false;
1000 } else Log() << Verbose(4) << "ElementsInMolecule match." << endl;
1001 }
1002 /// then determine and compare center of gravity for each molecule ...
1003 if (result) {
1004 Log() << Verbose(5) << "Calculating Centers of Gravity" << endl;
1005 DeterminePeriodicCenter(CenterOfGravity);
1006 OtherMolecule->DeterminePeriodicCenter(OtherCenterOfGravity);
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;
1012 if (CenterOfGravity.DistanceSquared(&OtherCenterOfGravity) > threshold*threshold) {
1013 Log() << Verbose(4) << "Centers of gravity don't match." << endl;
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) {
1020 Log() << Verbose(5) << "Calculating distances" << endl;
1021 Distances = Calloc<double>(AtomCount, "molecule::IsEqualToWithinThreshold: Distances");
1022 OtherDistances = Calloc<double>(AtomCount, "molecule::IsEqualToWithinThreshold: OtherDistances");
1023 SetIndexedArrayForEachAtomTo ( Distances, &atom::nr, &atom::DistanceSquaredToVector, (const Vector &)CenterOfGravity);
1024 SetIndexedArrayForEachAtomTo ( OtherDistances, &atom::nr, &atom::DistanceSquaredToVector, (const Vector &)CenterOfGravity);
1025
1026 /// ... sort each list (using heapsort (o(N log N)) from GSL)
1027 Log() << Verbose(5) << "Sorting distances" << endl;
1028 PermMap = Calloc<size_t>(AtomCount, "molecule::IsEqualToWithinThreshold: *PermMap");
1029 OtherPermMap = Calloc<size_t>(AtomCount, "molecule::IsEqualToWithinThreshold: *OtherPermMap");
1030 gsl_heapsort_index (PermMap, Distances, AtomCount, sizeof(double), CompareDoubles);
1031 gsl_heapsort_index (OtherPermMap, OtherDistances, AtomCount, sizeof(double), CompareDoubles);
1032 PermutationMap = Calloc<int>(AtomCount, "molecule::IsEqualToWithinThreshold: *PermutationMap");
1033 Log() << Verbose(5) << "Combining Permutation Maps" << endl;
1034 for(int i=AtomCount;i--;)
1035 PermutationMap[PermMap[i]] = (int) OtherPermMap[i];
1036
1037 /// ... and compare them step by step, whether the difference is individually(!) below \a threshold for all
1038 Log() << Verbose(4) << "Comparing distances" << endl;
1039 flag = 0;
1040 for (int i=0;i<AtomCount;i++) {
1041 Log() << Verbose(5) << "Distances squared: |" << Distances[PermMap[i]] << " - " << OtherDistances[OtherPermMap[i]] << "| = " << fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) << " ?<? " << threshold << endl;
1042 if (fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) > threshold*threshold)
1043 flag = 1;
1044 }
1045
1046 // free memory
1047 Free(&PermMap);
1048 Free(&OtherPermMap);
1049 Free(&Distances);
1050 Free(&OtherDistances);
1051 if (flag) { // if not equal
1052 Free(&PermutationMap);
1053 result = false;
1054 }
1055 }
1056 /// return pointer to map if all distances were below \a threshold
1057 Log() << Verbose(3) << "End of IsEqualToWithinThreshold." << endl;
1058 if (result) {
1059 Log() << Verbose(3) << "Result: Equal." << endl;
1060 return PermutationMap;
1061 } else {
1062 Log() << Verbose(3) << "Result: Not equal." << endl;
1063 return NULL;
1064 }
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 */
1074int * molecule::GetFatherSonAtomicMap(molecule *OtherMolecule)
1075{
1076 atom *Walker = NULL, *OtherWalker = NULL;
1077 Log() << Verbose(3) << "Begin of GetFatherAtomicMap." << endl;
1078 int *AtomicMap = Malloc<int>(AtomCount, "molecule::GetAtomicMap: *AtomicMap");
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;
1084 Log() << Verbose(4) << "Map is trivial." << endl;
1085 } else {
1086 Log() << Verbose(4) << "Map is ";
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++) {
1098 //Log() << Verbose(4) << "Comparing father " << Walker->father << " with the other one " << OtherWalker->father << "." << endl;
1099 if (Walker->father == OtherWalker)
1100 AtomicMap[Walker->nr] = OtherWalker->nr;
1101 }
1102 }
1103 Log() << Verbose(0) << AtomicMap[Walker->nr] << "\t";
1104 }
1105 Log() << Verbose(0) << endl;
1106 }
1107 Log() << Verbose(3) << "End of GetFatherAtomicMap." << endl;
1108 return AtomicMap;
1109};
1110
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$
1114 * \param *output output stream of temperature file
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)
1118 */
1119bool molecule::OutputTemperatureFromTrajectories(ofstream * const output, int startstep, int endstep)
1120{
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.;
1129 ActOnAllAtoms( &TrajectoryParticle::AddKineticToTemperature, &temperature, step);
1130 *output << step << "\t" << temperature*AtomicEnergyToKelvin << "\t" << temperature << endl;
1131 }
1132 return true;
1133};
1134
1135void molecule::SetIndexedArrayForEachAtomTo ( atom **array, int ParticleInfo::*index) const
1136{
1137 atom *Walker = start;
1138 while (Walker->next != end) {
1139 Walker = Walker->next;
1140 array[(Walker->*index)] = Walker;
1141 }
1142};
1143
1144void molecule::flipActiveFlag(){
1145 ActiveFlag = !ActiveFlag;
1146}
Note: See TracBrowser for help on using the repository browser.