source: src/molecule.cpp@ fa649a

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 fa649a was fa649a, checked in by Frederik Heber <heber@…>, 16 years ago

Small changes.

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