source: src/molecule.cpp@ fc1b24

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 fc1b24 was 2ba827, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Changed all observed places to new observer structure

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