source: src/molecule.cpp@ ea7176

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

FIX: Made AtomCount a Cacheable so that the number of atoms in a molecule will always be correct

All unittests working.
All Complete testcases fail.

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