source: src/molecule.cpp@ 9df5c6

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

Made the Vector::IsInParallelepiped() method take a matrix instead of a double*

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