source: src/molecule.cpp@ 6cb9c76

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 6cb9c76 was 0cc92b, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Made the molecule::CopyMolecule() method use STL algorithms

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