source: src/molecule.cpp@ 3e50ff

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 3e50ff was 49e1ae, checked in by Frederik Heber <heber@…>, 15 years ago

cstring header was missing in files, supplying definition of strlen, strcpy, and so on.

This was noted on laptop with gcc 4.1 (on workstation we have gcc 4.2)

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