source: src/molecule.cpp@ b21a64

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

Huge refactoring to make const what is const (ticket #38), continued.

  • too many changes because of too many cross-references to be able to list them up here.
  • NOTE that "make check" runs fine and did catch several error.
  • note that we had to use const_iterator several times when the map, ... was declared const.
  • at times we changed an allocated LinkedCell LCList(...) into

const LinkedCell *LCList;
LCList = new LinkedCell(...);

  • also mutable (see ticket #5) was used, e.g. for molecule::InternalPointer (PointCloud changes are allowed, because they are just accounting).

Signed-off-by: Frederik Heber <heber@…>

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