source: src/molecule.cpp@ 962d8d

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

Removed left over parts from old memory-tracker

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