source: src/molecule.cpp@ f16a4b

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 f16a4b was 46d958, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Made the world solely responsible for creating and destroying atoms.

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