source: src/molecule.cpp@ e5ad5c

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

Huge change from ofstream * (const) out --> Log().

  • first shift was done via regular expressions
  • then via error messages from the code
  • note that class atom, class element and class molecule kept in parts their output stream, was they print to file.
  • make check runs fine
  • MISSING: Verbosity is not fixed for everything (i.e. if no endl; is present and next has Verbose(0) ...)

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

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