source: src/molecule.cpp@ f60610

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

Fixing ticket #18.

  • each eLog() << Verbose(0) is now followed by performCriticalExit().
  • 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 = NULL;
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(1) << "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 eLog() << Verbose(2) << "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 eLog() << Verbose(1) << "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(1) << "BondDegree does not state single, double or triple bond!" << endl;
397 AllWentWell = false;
398 break;
399 }
400 Free(&matrix);
401
402// Log() << Verbose(3) << "End of AddHydrogenReplacementAtom." << endl;
403 return AllWentWell;
404};
405
406/** Adds given atom \a *pointer from molecule list.
407 * Increases molecule::last_atom and gives last number to added atom.
408 * \param filename name and path of xyz file
409 * \return true - succeeded, false - file not found
410 */
411bool molecule::AddXYZFile(string filename)
412{
413 istringstream *input = NULL;
414 int NumberOfAtoms = 0; // atom number in xyz read
415 int i, j; // loop variables
416 atom *Walker = NULL; // pointer to added atom
417 char shorthand[3]; // shorthand for atom name
418 ifstream xyzfile; // xyz file
419 string line; // currently parsed line
420 double x[3]; // atom coordinates
421
422 xyzfile.open(filename.c_str());
423 if (!xyzfile)
424 return false;
425
426 getline(xyzfile,line,'\n'); // Read numer of atoms in file
427 input = new istringstream(line);
428 *input >> NumberOfAtoms;
429 Log() << Verbose(0) << "Parsing " << NumberOfAtoms << " atoms in file." << endl;
430 getline(xyzfile,line,'\n'); // Read comment
431 Log() << Verbose(1) << "Comment: " << line << endl;
432
433 if (MDSteps == 0) // no atoms yet present
434 MDSteps++;
435 for(i=0;i<NumberOfAtoms;i++){
436 Walker = new atom;
437 getline(xyzfile,line,'\n');
438 istringstream *item = new istringstream(line);
439 //istringstream input(line);
440 //Log() << Verbose(1) << "Reading: " << line << endl;
441 *item >> shorthand;
442 *item >> x[0];
443 *item >> x[1];
444 *item >> x[2];
445 Walker->type = elemente->FindElement(shorthand);
446 if (Walker->type == NULL) {
447 eLog() << Verbose(1) << "Could not parse the element at line: '" << line << "', setting to H.";
448 Walker->type = elemente->FindElement(1);
449 }
450 if (Walker->Trajectory.R.size() <= (unsigned int)MDSteps) {
451 Walker->Trajectory.R.resize(MDSteps+10);
452 Walker->Trajectory.U.resize(MDSteps+10);
453 Walker->Trajectory.F.resize(MDSteps+10);
454 }
455 for(j=NDIM;j--;) {
456 Walker->x.x[j] = x[j];
457 Walker->Trajectory.R.at(MDSteps-1).x[j] = x[j];
458 Walker->Trajectory.U.at(MDSteps-1).x[j] = 0;
459 Walker->Trajectory.F.at(MDSteps-1).x[j] = 0;
460 }
461 AddAtom(Walker); // add to molecule
462 delete(item);
463 }
464 xyzfile.close();
465 delete(input);
466 return true;
467};
468
469/** Creates a copy of this molecule.
470 * \return copy of molecule
471 */
472molecule *molecule::CopyMolecule()
473{
474 molecule *copy = new molecule(elemente);
475 atom *LeftAtom = NULL, *RightAtom = NULL;
476
477 // copy all atoms
478 ActOnCopyWithEachAtom ( &molecule::AddCopyAtom, copy );
479
480 // copy all bonds
481 bond *Binder = first;
482 bond *NewBond = NULL;
483 while(Binder->next != last) {
484 Binder = Binder->next;
485
486 // get the pendant atoms of current bond in the copy molecule
487 copy->ActOnAllAtoms( &atom::EqualsFather, (const atom *)Binder->leftatom, (const atom **)&LeftAtom );
488 copy->ActOnAllAtoms( &atom::EqualsFather, (const atom *)Binder->rightatom, (const atom **)&RightAtom );
489
490 NewBond = copy->AddBond(LeftAtom, RightAtom, Binder->BondDegree);
491 NewBond->Cyclic = Binder->Cyclic;
492 if (Binder->Cyclic)
493 copy->NoCyclicBonds++;
494 NewBond->Type = Binder->Type;
495 }
496 // correct fathers
497 ActOnAllAtoms( &atom::CorrectFather );
498
499 // copy values
500 copy->CountAtoms();
501 copy->CountElements();
502 if (first->next != last) { // if adjaceny list is present
503 copy->BondDistance = BondDistance;
504 }
505
506 return copy;
507};
508
509
510/**
511 * Copies all atoms of a molecule which are within the defined parallelepiped.
512 *
513 * @param offest for the origin of the parallelepiped
514 * @param three vectors forming the matrix that defines the shape of the parallelpiped
515 */
516molecule* molecule::CopyMoleculeFromSubRegion(const Vector offset, const double *parallelepiped) const {
517 molecule *copy = new molecule(elemente);
518
519 ActOnCopyWithEachAtomIfTrue ( &molecule::AddCopyAtom, copy, &atom::IsInParallelepiped, offset, parallelepiped );
520
521 //TODO: copy->BuildInducedSubgraph(this);
522
523 return copy;
524}
525
526/** Adds a bond to a the molecule specified by two atoms, \a *first and \a *second.
527 * Also updates molecule::BondCount and molecule::NoNonBonds.
528 * \param *first first atom in bond
529 * \param *second atom in bond
530 * \return pointer to bond or NULL on failure
531 */
532bond * molecule::AddBond(atom *atom1, atom *atom2, int degree)
533{
534 bond *Binder = NULL;
535 if ((atom1 != NULL) && (FindAtom(atom1->nr) != NULL) && (atom2 != NULL) && (FindAtom(atom2->nr) != NULL)) {
536 Binder = new bond(atom1, atom2, degree, BondCount++);
537 atom1->RegisterBond(Binder);
538 atom2->RegisterBond(Binder);
539 if ((atom1->type != NULL) && (atom1->type->Z != 1) && (atom2->type != NULL) && (atom2->type->Z != 1))
540 NoNonBonds++;
541 add(Binder, last);
542 } else {
543 eLog() << Verbose(1) << "Could not add bond between " << atom1->Name << " and " << atom2->Name << " as one or both are not present in the molecule." << endl;
544 }
545 return Binder;
546};
547
548/** Remove bond from bond chain list and from the both atom::ListOfBonds.
549 * \todo Function not implemented yet
550 * \param *pointer bond pointer
551 * \return true - bound found and removed, false - bond not found/removed
552 */
553bool molecule::RemoveBond(bond *pointer)
554{
555 //eLog() << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
556 pointer->leftatom->RegisterBond(pointer);
557 pointer->rightatom->RegisterBond(pointer);
558 removewithoutcheck(pointer);
559 return true;
560};
561
562/** Remove every bond from bond chain list that atom \a *BondPartner is a constituent of.
563 * \todo Function not implemented yet
564 * \param *BondPartner atom to be removed
565 * \return true - bounds found and removed, false - bonds not found/removed
566 */
567bool molecule::RemoveBonds(atom *BondPartner)
568{
569 //eLog() << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
570 BondList::const_iterator ForeRunner;
571 while (!BondPartner->ListOfBonds.empty()) {
572 ForeRunner = BondPartner->ListOfBonds.begin();
573 RemoveBond(*ForeRunner);
574 }
575 return false;
576};
577
578/** Set molecule::name from the basename without suffix in the given \a *filename.
579 * \param *filename filename
580 */
581void molecule::SetNameFromFilename(const char *filename)
582{
583 int length = 0;
584 const char *molname = strrchr(filename, '/');
585 if (molname != NULL)
586 molname += sizeof(char); // search for filename without dirs
587 else
588 molname = filename; // contains no slashes
589 char *endname = strchr(molname, '.');
590 if ((endname == NULL) || (endname < molname))
591 length = strlen(molname);
592 else
593 length = strlen(molname) - strlen(endname);
594 strncpy(name, molname, length);
595 name[length]='\0';
596};
597
598/** Sets the molecule::cell_size to the components of \a *dim (rectangular box)
599 * \param *dim vector class
600 */
601void molecule::SetBoxDimension(Vector *dim)
602{
603 cell_size[0] = dim->x[0];
604 cell_size[1] = 0.;
605 cell_size[2] = dim->x[1];
606 cell_size[3] = 0.;
607 cell_size[4] = 0.;
608 cell_size[5] = dim->x[2];
609};
610
611/** Removes atom from molecule list and deletes it.
612 * \param *pointer atom to be removed
613 * \return true - succeeded, false - atom not found in list
614 */
615bool molecule::RemoveAtom(atom *pointer)
616{
617 if (ElementsInMolecule[pointer->type->Z] != 0) { // this would indicate an error
618 ElementsInMolecule[pointer->type->Z]--; // decrease number of atom of this element
619 AtomCount--;
620 } else
621 eLog() << Verbose(1) << "Atom " << pointer->Name << " is of element " << pointer->type->Z << " but the entry in the table of the molecule is 0!" << endl;
622 if (ElementsInMolecule[pointer->type->Z] == 0) // was last atom of this element?
623 ElementCount--;
624 RemoveBonds(pointer);
625 return remove(pointer, start, end);
626};
627
628/** Removes atom from molecule list, but does not delete it.
629 * \param *pointer atom to be removed
630 * \return true - succeeded, false - atom not found in list
631 */
632bool molecule::UnlinkAtom(atom *pointer)
633{
634 if (pointer == NULL)
635 return false;
636 if (ElementsInMolecule[pointer->type->Z] != 0) // this would indicate an error
637 ElementsInMolecule[pointer->type->Z]--; // decrease number of atom of this element
638 else
639 eLog() << Verbose(1) << "Atom " << pointer->Name << " is of element " << pointer->type->Z << " but the entry in the table of the molecule is 0!" << endl;
640 if (ElementsInMolecule[pointer->type->Z] == 0) // was last atom of this element?
641 ElementCount--;
642 unlink(pointer);
643 return true;
644};
645
646/** Removes every atom from molecule list.
647 * \return true - succeeded, false - atom not found in list
648 */
649bool molecule::CleanupMolecule()
650{
651 return (cleanup(first,last) && cleanup(start,end));
652};
653
654/** Finds an atom specified by its continuous number.
655 * \param Nr number of atom withim molecule
656 * \return pointer to atom or NULL
657 */
658atom * molecule::FindAtom(int Nr) const{
659 atom * walker = find(&Nr, start,end);
660 if (walker != NULL) {
661 //Log() << Verbose(0) << "Found Atom Nr. " << walker->nr << endl;
662 return walker;
663 } else {
664 Log() << Verbose(0) << "Atom not found in list." << endl;
665 return NULL;
666 }
667};
668
669/** Asks for atom number, and checks whether in list.
670 * \param *text question before entering
671 */
672atom * molecule::AskAtom(string text)
673{
674 int No;
675 atom *ion = NULL;
676 do {
677 //Log() << Verbose(0) << "============Atom list==========================" << endl;
678 //mol->Output((ofstream *)&cout);
679 //Log() << Verbose(0) << "===============================================" << endl;
680 Log() << Verbose(0) << text;
681 cin >> No;
682 ion = this->FindAtom(No);
683 } while (ion == NULL);
684 return ion;
685};
686
687/** Checks if given coordinates are within cell volume.
688 * \param *x array of coordinates
689 * \return true - is within, false - out of cell
690 */
691bool molecule::CheckBounds(const Vector *x) const
692{
693 bool result = true;
694 int j =-1;
695 for (int i=0;i<NDIM;i++) {
696 j += i+1;
697 result = result && ((x->x[i] >= 0) && (x->x[i] < cell_size[j]));
698 }
699 //return result;
700 return true; /// probably not gonna use the check no more
701};
702
703/** Prints molecule to *out.
704 * \param *out output stream
705 */
706bool molecule::Output(ofstream * const output)
707{
708 int ElementNo[MAX_ELEMENTS], AtomNo[MAX_ELEMENTS];
709 CountElements();
710
711 for (int i=0;i<MAX_ELEMENTS;++i) {
712 AtomNo[i] = 0;
713 ElementNo[i] = 0;
714 }
715 if (output == NULL) {
716 return false;
717 } else {
718 *output << "#Ion_TypeNr._Nr.R[0] R[1] R[2] MoveType (0 MoveIon, 1 FixedIon)" << endl;
719 SetIndexedArrayForEachAtomTo ( ElementNo, &element::Z, &AbsoluteValue, 1);
720 int current=1;
721 for (int i=0;i<MAX_ELEMENTS;++i) {
722 if (ElementNo[i] == 1)
723 ElementNo[i] = current++;
724 }
725 ActOnAllAtoms( &atom::OutputArrayIndexed, output, (const int *)ElementNo, (int *)AtomNo, (const char *) NULL );
726 return true;
727 }
728};
729
730/** Prints molecule with all atomic trajectory positions to *out.
731 * \param *out output stream
732 */
733bool molecule::OutputTrajectories(ofstream * const output)
734{
735 int ElementNo[MAX_ELEMENTS], AtomNo[MAX_ELEMENTS];
736 CountElements();
737
738 if (output == NULL) {
739 return false;
740 } else {
741 for (int step = 0; step < MDSteps; step++) {
742 if (step == 0) {
743 *output << "#Ion_TypeNr._Nr.R[0] R[1] R[2] MoveType (0 MoveIon, 1 FixedIon)" << endl;
744 } else {
745 *output << "# ====== MD step " << step << " =========" << endl;
746 }
747 for (int i=0;i<MAX_ELEMENTS;++i) {
748 AtomNo[i] = 0;
749 ElementNo[i] = 0;
750 }
751 SetIndexedArrayForEachAtomTo ( ElementNo, &element::Z, &AbsoluteValue, 1);
752 int current=1;
753 for (int i=0;i<MAX_ELEMENTS;++i) {
754 if (ElementNo[i] == 1)
755 ElementNo[i] = current++;
756 }
757 ActOnAllAtoms( &atom::OutputTrajectory, output, (const int *)ElementNo, AtomNo, (const int)step );
758 }
759 return true;
760 }
761};
762
763/** Outputs contents of each atom::ListOfBonds.
764 * \param *out output stream
765 */
766void molecule::OutputListOfBonds() const
767{
768 Log() << Verbose(2) << endl << "From Contents of ListOfBonds, all non-hydrogen atoms:" << endl;
769 ActOnAllAtoms (&atom::OutputBondOfAtom );
770 Log() << Verbose(0) << endl;
771};
772
773/** Output of element before the actual coordination list.
774 * \param *out stream pointer
775 */
776bool molecule::Checkout(ofstream * const output) const
777{
778 return elemente->Checkout(output, ElementsInMolecule);
779};
780
781/** Prints molecule with all its trajectories to *out as xyz file.
782 * \param *out output stream
783 */
784bool molecule::OutputTrajectoriesXYZ(ofstream * const output)
785{
786 time_t now;
787
788 if (output != NULL) {
789 now = time((time_t *)NULL); // Get the system time and put it into 'now' as 'calender time'
790 for (int step=0;step<MDSteps;step++) {
791 *output << AtomCount << "\n\tCreated by molecuilder, step " << step << ", on " << ctime(&now);
792 ActOnAllAtoms( &atom::OutputTrajectoryXYZ, output, step );
793 }
794 return true;
795 } else
796 return false;
797};
798
799/** Prints molecule to *out as xyz file.
800* \param *out output stream
801 */
802bool molecule::OutputXYZ(ofstream * const output) const
803{
804 time_t now;
805
806 if (output != NULL) {
807 now = time((time_t *)NULL); // Get the system time and put it into 'now' as 'calender time'
808 *output << AtomCount << "\n\tCreated by molecuilder on " << ctime(&now);
809 ActOnAllAtoms( &atom::OutputXYZLine, output );
810 return true;
811 } else
812 return false;
813};
814
815/** Brings molecule::AtomCount and atom::*Name up-to-date.
816 * \param *out output stream for debugging
817 */
818void molecule::CountAtoms()
819{
820 int i = 0;
821 atom *Walker = start;
822 while (Walker->next != end) {
823 Walker = Walker->next;
824 i++;
825 }
826 if ((AtomCount == 0) || (i != AtomCount)) {
827 Log() << Verbose(3) << "Mismatch in AtomCount " << AtomCount << " and recounted number " << i << ", renaming all." << endl;
828 AtomCount = i;
829
830 // count NonHydrogen atoms and give each atom a unique name
831 if (AtomCount != 0) {
832 i=0;
833 NoNonHydrogen = 0;
834 Walker = start;
835 while (Walker->next != end) {
836 Walker = Walker->next;
837 Walker->nr = i; // update number in molecule (for easier referencing in FragmentMolecule lateron)
838 if (Walker->type->Z != 1) // count non-hydrogen atoms whilst at it
839 NoNonHydrogen++;
840 Free(&Walker->Name);
841 Walker->Name = Malloc<char>(6, "molecule::CountAtoms: *walker->Name");
842 sprintf(Walker->Name, "%2s%02d", Walker->type->symbol, Walker->nr+1);
843 Log() << Verbose(3) << "Naming atom nr. " << Walker->nr << " " << Walker->Name << "." << endl;
844 i++;
845 }
846 } else
847 Log() << Verbose(3) << "AtomCount is still " << AtomCount << ", thus counting nothing." << endl;
848 }
849};
850
851/** Brings molecule::ElementCount and molecule::ElementsInMolecule up-to-date.
852 */
853void molecule::CountElements()
854{
855 for(int i=MAX_ELEMENTS;i--;)
856 ElementsInMolecule[i] = 0;
857 ElementCount = 0;
858
859 SetIndexedArrayForEachAtomTo ( ElementsInMolecule, &element::Z, &Increment, 1);
860
861 for(int i=MAX_ELEMENTS;i--;)
862 ElementCount += (ElementsInMolecule[i] != 0 ? 1 : 0);
863};
864
865
866/** Counts necessary number of valence electrons and returns number and SpinType.
867 * \param configuration containing everything
868 */
869void molecule::CalculateOrbitals(class config &configuration)
870{
871 configuration.MaxPsiDouble = configuration.PsiMaxNoDown = configuration.PsiMaxNoUp = configuration.PsiType = 0;
872 for(int i=MAX_ELEMENTS;i--;) {
873 if (ElementsInMolecule[i] != 0) {
874 //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;
875 configuration.MaxPsiDouble += ElementsInMolecule[i]*((int)elemente->FindElement(i)->Valence);
876 }
877 }
878 configuration.PsiMaxNoDown = configuration.MaxPsiDouble/2 + (configuration.MaxPsiDouble % 2);
879 configuration.PsiMaxNoUp = configuration.MaxPsiDouble/2;
880 configuration.MaxPsiDouble /= 2;
881 configuration.PsiType = (configuration.PsiMaxNoDown == configuration.PsiMaxNoUp) ? 0 : 1;
882 if ((configuration.PsiType == 1) && (configuration.ProcPEPsi < 2)) {
883 configuration.ProcPEGamma /= 2;
884 configuration.ProcPEPsi *= 2;
885 } else {
886 configuration.ProcPEGamma *= configuration.ProcPEPsi;
887 configuration.ProcPEPsi = 1;
888 }
889 configuration.InitMaxMinStopStep = configuration.MaxMinStopStep = configuration.MaxPsiDouble;
890};
891
892/** Determines whether two molecules actually contain the same atoms and coordination.
893 * \param *out output stream for debugging
894 * \param *OtherMolecule the molecule to compare this one to
895 * \param threshold upper limit of difference when comparing the coordination.
896 * \return NULL - not equal, otherwise an allocated (molecule::AtomCount) permutation map of the atom numbers (which corresponds to which)
897 */
898int * molecule::IsEqualToWithinThreshold(molecule *OtherMolecule, double threshold)
899{
900 int flag;
901 double *Distances = NULL, *OtherDistances = NULL;
902 Vector CenterOfGravity, OtherCenterOfGravity;
903 size_t *PermMap = NULL, *OtherPermMap = NULL;
904 int *PermutationMap = NULL;
905 bool result = true; // status of comparison
906
907 Log() << Verbose(3) << "Begin of IsEqualToWithinThreshold." << endl;
908 /// first count both their atoms and elements and update lists thereby ...
909 //Log() << Verbose(0) << "Counting atoms, updating list" << endl;
910 CountAtoms();
911 OtherMolecule->CountAtoms();
912 CountElements();
913 OtherMolecule->CountElements();
914
915 /// ... and compare:
916 /// -# AtomCount
917 if (result) {
918 if (AtomCount != OtherMolecule->AtomCount) {
919 Log() << Verbose(4) << "AtomCounts don't match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
920 result = false;
921 } else Log() << Verbose(4) << "AtomCounts match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
922 }
923 /// -# ElementCount
924 if (result) {
925 if (ElementCount != OtherMolecule->ElementCount) {
926 Log() << Verbose(4) << "ElementCount don't match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
927 result = false;
928 } else Log() << Verbose(4) << "ElementCount match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
929 }
930 /// -# ElementsInMolecule
931 if (result) {
932 for (flag=MAX_ELEMENTS;flag--;) {
933 //Log() << Verbose(5) << "Element " << flag << ": " << ElementsInMolecule[flag] << " <-> " << OtherMolecule->ElementsInMolecule[flag] << "." << endl;
934 if (ElementsInMolecule[flag] != OtherMolecule->ElementsInMolecule[flag])
935 break;
936 }
937 if (flag < MAX_ELEMENTS) {
938 Log() << Verbose(4) << "ElementsInMolecule don't match." << endl;
939 result = false;
940 } else Log() << Verbose(4) << "ElementsInMolecule match." << endl;
941 }
942 /// then determine and compare center of gravity for each molecule ...
943 if (result) {
944 Log() << Verbose(5) << "Calculating Centers of Gravity" << endl;
945 DeterminePeriodicCenter(CenterOfGravity);
946 OtherMolecule->DeterminePeriodicCenter(OtherCenterOfGravity);
947 Log() << Verbose(5) << "Center of Gravity: ";
948 CenterOfGravity.Output();
949 Log() << Verbose(0) << endl << Verbose(5) << "Other Center of Gravity: ";
950 OtherCenterOfGravity.Output();
951 Log() << Verbose(0) << endl;
952 if (CenterOfGravity.DistanceSquared(&OtherCenterOfGravity) > threshold*threshold) {
953 Log() << Verbose(4) << "Centers of gravity don't match." << endl;
954 result = false;
955 }
956 }
957
958 /// ... then make a list with the euclidian distance to this center for each atom of both molecules
959 if (result) {
960 Log() << Verbose(5) << "Calculating distances" << endl;
961 Distances = Calloc<double>(AtomCount, "molecule::IsEqualToWithinThreshold: Distances");
962 OtherDistances = Calloc<double>(AtomCount, "molecule::IsEqualToWithinThreshold: OtherDistances");
963 SetIndexedArrayForEachAtomTo ( Distances, &atom::nr, &atom::DistanceSquaredToVector, (const Vector &)CenterOfGravity);
964 SetIndexedArrayForEachAtomTo ( OtherDistances, &atom::nr, &atom::DistanceSquaredToVector, (const Vector &)CenterOfGravity);
965
966 /// ... sort each list (using heapsort (o(N log N)) from GSL)
967 Log() << Verbose(5) << "Sorting distances" << endl;
968 PermMap = Calloc<size_t>(AtomCount, "molecule::IsEqualToWithinThreshold: *PermMap");
969 OtherPermMap = Calloc<size_t>(AtomCount, "molecule::IsEqualToWithinThreshold: *OtherPermMap");
970 gsl_heapsort_index (PermMap, Distances, AtomCount, sizeof(double), CompareDoubles);
971 gsl_heapsort_index (OtherPermMap, OtherDistances, AtomCount, sizeof(double), CompareDoubles);
972 PermutationMap = Calloc<int>(AtomCount, "molecule::IsEqualToWithinThreshold: *PermutationMap");
973 Log() << Verbose(5) << "Combining Permutation Maps" << endl;
974 for(int i=AtomCount;i--;)
975 PermutationMap[PermMap[i]] = (int) OtherPermMap[i];
976
977 /// ... and compare them step by step, whether the difference is individually(!) below \a threshold for all
978 Log() << Verbose(4) << "Comparing distances" << endl;
979 flag = 0;
980 for (int i=0;i<AtomCount;i++) {
981 Log() << Verbose(5) << "Distances squared: |" << Distances[PermMap[i]] << " - " << OtherDistances[OtherPermMap[i]] << "| = " << fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) << " ?<? " << threshold << endl;
982 if (fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) > threshold*threshold)
983 flag = 1;
984 }
985
986 // free memory
987 Free(&PermMap);
988 Free(&OtherPermMap);
989 Free(&Distances);
990 Free(&OtherDistances);
991 if (flag) { // if not equal
992 Free(&PermutationMap);
993 result = false;
994 }
995 }
996 /// return pointer to map if all distances were below \a threshold
997 Log() << Verbose(3) << "End of IsEqualToWithinThreshold." << endl;
998 if (result) {
999 Log() << Verbose(3) << "Result: Equal." << endl;
1000 return PermutationMap;
1001 } else {
1002 Log() << Verbose(3) << "Result: Not equal." << endl;
1003 return NULL;
1004 }
1005};
1006
1007/** Returns an index map for two father-son-molecules.
1008 * The map tells which atom in this molecule corresponds to which one in the other molecul with their fathers.
1009 * \param *out output stream for debugging
1010 * \param *OtherMolecule corresponding molecule with fathers
1011 * \return allocated map of size molecule::AtomCount with map
1012 * \todo make this with a good sort O(n), not O(n^2)
1013 */
1014int * molecule::GetFatherSonAtomicMap(molecule *OtherMolecule)
1015{
1016 atom *Walker = NULL, *OtherWalker = NULL;
1017 Log() << Verbose(3) << "Begin of GetFatherAtomicMap." << endl;
1018 int *AtomicMap = Malloc<int>(AtomCount, "molecule::GetAtomicMap: *AtomicMap");
1019 for (int i=AtomCount;i--;)
1020 AtomicMap[i] = -1;
1021 if (OtherMolecule == this) { // same molecule
1022 for (int i=AtomCount;i--;) // no need as -1 means already that there is trivial correspondence
1023 AtomicMap[i] = i;
1024 Log() << Verbose(4) << "Map is trivial." << endl;
1025 } else {
1026 Log() << Verbose(4) << "Map is ";
1027 Walker = start;
1028 while (Walker->next != end) {
1029 Walker = Walker->next;
1030 if (Walker->father == NULL) {
1031 AtomicMap[Walker->nr] = -2;
1032 } else {
1033 OtherWalker = OtherMolecule->start;
1034 while (OtherWalker->next != OtherMolecule->end) {
1035 OtherWalker = OtherWalker->next;
1036 //for (int i=0;i<AtomCount;i++) { // search atom
1037 //for (int j=0;j<OtherMolecule->AtomCount;j++) {
1038 //Log() << Verbose(4) << "Comparing father " << Walker->father << " with the other one " << OtherWalker->father << "." << endl;
1039 if (Walker->father == OtherWalker)
1040 AtomicMap[Walker->nr] = OtherWalker->nr;
1041 }
1042 }
1043 Log() << Verbose(0) << AtomicMap[Walker->nr] << "\t";
1044 }
1045 Log() << Verbose(0) << endl;
1046 }
1047 Log() << Verbose(3) << "End of GetFatherAtomicMap." << endl;
1048 return AtomicMap;
1049};
1050
1051/** Stores the temperature evaluated from velocities in molecule::Trajectories.
1052 * We simply use the formula equivaleting temperature and kinetic energy:
1053 * \f$k_B T = \sum_i m_i v_i^2\f$
1054 * \param *output output stream of temperature file
1055 * \param startstep first MD step in molecule::Trajectories
1056 * \param endstep last plus one MD step in molecule::Trajectories
1057 * \return file written (true), failure on writing file (false)
1058 */
1059bool molecule::OutputTemperatureFromTrajectories(ofstream * const output, int startstep, int endstep)
1060{
1061 double temperature;
1062 // test stream
1063 if (output == NULL)
1064 return false;
1065 else
1066 *output << "# Step Temperature [K] Temperature [a.u.]" << endl;
1067 for (int step=startstep;step < endstep; step++) { // loop over all time steps
1068 temperature = 0.;
1069 ActOnAllAtoms( &TrajectoryParticle::AddKineticToTemperature, &temperature, step);
1070 *output << step << "\t" << temperature*AtomicEnergyToKelvin << "\t" << temperature << endl;
1071 }
1072 return true;
1073};
1074
1075void molecule::SetIndexedArrayForEachAtomTo ( atom **array, int ParticleInfo::*index) const
1076{
1077 atom *Walker = start;
1078 while (Walker->next != end) {
1079 Walker = Walker->next;
1080 array[(Walker->*index)] = Walker;
1081 }
1082};
Note: See TracBrowser for help on using the repository browser.