source: src/molecule.cpp@ 70ff32

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 70ff32 was b453f9, checked in by Frederik Heber <heber@…>, 15 years ago

Begun with ticket #38 (make const what is const).

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