source: src/molecule.cpp@ ac9b56

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

Added simple way to retrieve formula of a molecule using caching

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