source: src/molecule.cpp@ 6cfa36

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

Made atoms remove themselves from molecules upon destruction

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