source: src/molecule.cpp@ ebcade

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

class molecule implementation split up into six separate parts.

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