source: src/molecule.cpp@ 7042f45

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

Made the world solely responsible for creating and erasing molecules.

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