source: src/molecule.cpp@ 436f04

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

Made the ReturnFullMatrixForSymmetric return a Matrix object directely instead of a double array

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