source: src/molecule.cpp@ 5d1611

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 5d1611 was f721c6, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Made more methods of the molecule observable

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