source: src/molecule.cpp@ f66195

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

forward declarations used to untangle interdependet classes.

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