source: src/molecule.cpp@ 1bd79e

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

Changed implementation of Vector to forward operations to contained objects

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