source: src/molecule.cpp@ 1024cb

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 1024cb was 1024cb, checked in by Frederik Heber <heber@…>, 15 years ago

Merge commit 'jupiter/MoleculeStartEndSwitch' into CommandLineActionMapping

Conflicts:

molecuilder/src/Makefile.am
molecuilder/src/builder.cpp
molecuilder/src/config.cpp
molecuilder/src/helpers.hpp
molecuilder/src/molecule.cpp
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/unittests/AnalysisCorrelationToPointUnitTest.cpp
molecuilder/src/unittests/listofbondsunittest.cpp

Integration of MoleculeStartEndSwitch had the following consequences:

  • no more AtomCount -> getAtomCount()
  • no more start/end -> begin(), end() and iterator
  • no more decent ordering in atomic ids (hence, Simple_configuration/8 and Domain/5, Domain/6 now check by comparing sorted xyz, not confs)

There is still a huge problem with bonds. One test runs into an endless loop.

Signed-off-by: Frederik Heber <heber@…>

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