source: src/molecule.cpp@ 2a76b0

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

Made fields name and symbol of element class private

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