source: src/molecule.cpp@ cd5047

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

Added Logging capabilities to Observer Framework

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