source: src/molecule.cpp@ 3d27e6

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 3d27e6 was 389cc8, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Used the formual class instead of single variables inside molecule

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