source: src/molecule.cpp@ e87acf

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 Candidate_v1.7.0 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 e87acf was e87acf, checked in by Tillmann Crueger <crueger@…>, 16 years ago

BROKEN: removed legacy AtomList from molecule class

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