source: src/molecule.cpp@ 906822

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

Removed forgotten debug message

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