source: src/molecule.cpp@ a7b761b

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 Candidate_v1.7.0 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since a7b761b was a7b761b, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Merge branch 'MoleculeStartEndSwitch' into StructureRefactoring

Conflicts:

molecuilder/src/Helpers/Assert.cpp
molecuilder/src/Helpers/Assert.hpp
molecuilder/src/Legacy/oldmenu.cpp
molecuilder/src/Makefile.am
molecuilder/src/Patterns/Cacheable.hpp
molecuilder/src/Patterns/Observer.cpp
molecuilder/src/Patterns/Observer.hpp
molecuilder/src/analysis_correlation.cpp
molecuilder/src/boundary.cpp
molecuilder/src/builder.cpp
molecuilder/src/config.cpp
molecuilder/src/helpers.hpp
molecuilder/src/molecule.cpp
molecuilder/src/molecule.hpp
molecuilder/src/molecule_dynamics.cpp
molecuilder/src/molecule_fragmentation.cpp
molecuilder/src/molecule_geometry.cpp
molecuilder/src/molecule_graph.cpp
molecuilder/src/moleculelist.cpp
molecuilder/src/tesselation.cpp
molecuilder/src/unittests/AnalysisCorrelationToSurfaceUnitTest.cpp
molecuilder/src/unittests/ObserverTest.cpp
molecuilder/src/unittests/ObserverTest.hpp

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