source: src/molecule.cpp@ 05a97c

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

Replaced some error conditions with ASSERTs

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