source: src/molecule.cpp@ 80c63d

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

Changed conditional criticalExit in constructor of BoundaryTriangleSet to Assertion.

  • Property mode set to 100755
File size: 46.2 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), AtomCount(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 last_atom(0),
39 InternalPointer(begin())
40{
41 // init bond chain list
42 link(first,last);
43
44 // other stuff
45 for(int i=MAX_ELEMENTS;i--;)
46 ElementsInMolecule[i] = 0;
47 cell_size[0] = cell_size[2] = cell_size[5]= 20.;
48 cell_size[1] = cell_size[3] = cell_size[4]= 0.;
49 strcpy(name,"none");
50};
51
52molecule *NewMolecule(){
53 return new molecule(World::get()->getPeriode());
54}
55
56/** Destructor of class molecule.
57 * Initialises molecule list with correctly referenced start and end, and sets molecule::last_atom to zero.
58 */
59molecule::~molecule()
60{
61 CleanupMolecule();
62 delete(first);
63 delete(last);
64};
65
66
67void DeleteMolecule(molecule *mol){
68 delete mol;
69}
70
71// getter and setter
72const std::string molecule::getName(){
73 return std::string(name);
74}
75
76void molecule::setName(const std::string _name){
77 OBSERVE;
78 strncpy(name,_name.c_str(),MAXSTRINGSIZE);
79}
80
81moleculeId_t molecule::getId(){
82 return id;
83}
84
85void molecule::setId(moleculeId_t _id){
86 id =_id;
87}
88
89const std::string molecule::getFormula(){
90 return *formula;
91}
92
93std::string molecule::calcFormula(){
94 int Counts[MAX_ELEMENTS];
95 stringstream sstr;
96 for (int j = 0; j<MAX_ELEMENTS;j++)
97 Counts[j] = 0;
98 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
99 Counts[(*iter)->type->Z]++;
100 }
101 for(element* Elemental = elemente->end; Elemental != elemente->start; Elemental = Elemental->previous) {
102 if (Counts[Elemental->Z] != 0)
103 sstr << Elemental->symbol << Counts[Elemental->Z];
104 }
105 return sstr.str();
106}
107
108/************************** Access to the List of Atoms ****************/
109
110
111molecule::iterator molecule::begin(){
112 return molecule::iterator(atoms.begin(),this);
113}
114
115molecule::const_iterator molecule::begin() const{
116 return atoms.begin();
117}
118
119molecule::iterator molecule::end(){
120 return molecule::iterator(atoms.end(),this);
121}
122
123molecule::const_iterator molecule::end() const{
124 return atoms.end();
125}
126
127bool molecule::empty() const
128{
129 return (begin() == end());
130}
131
132size_t molecule::size() const
133{
134 size_t counter = 0;
135 for (molecule::const_iterator iter = begin(); iter != end (); ++iter)
136 counter++;
137 return counter;
138}
139
140molecule::const_iterator molecule::erase( const_iterator loc )
141{
142 molecule::const_iterator iter = loc;
143 iter--;
144 atoms.erase( loc );
145 return iter;
146}
147
148molecule::const_iterator molecule::erase( atom *& key )
149{
150 molecule::const_iterator iter = find(key);
151 molecule::const_iterator runner = iter;
152 if (runner != begin()) {
153 runner--;
154 if (iter != end())
155 atoms.erase( key );
156 return runner;
157 } else
158 return end();
159}
160
161molecule::const_iterator molecule::find ( atom *& key ) const
162{
163 return atoms.find( key );
164}
165
166pair<molecule::iterator,bool> molecule::insert ( atom * const key )
167{
168 pair<atomSet::iterator,bool> res = atoms.insert(key);
169 return pair<iterator,bool>(iterator(res.first,this),res.second);
170}
171
172/** Adds given atom \a *pointer from molecule list.
173 * Increases molecule::last_atom and gives last number to added atom and names it according to its element::abbrev and molecule::AtomCount
174 * \param *pointer allocated and set atom
175 * \return true - succeeded, false - atom not found in list
176 */
177bool molecule::AddAtom(atom *pointer)
178{
179 OBSERVE;
180 if (pointer != NULL) {
181 pointer->sort = &pointer->nr;
182 AtomCount++;
183 if (pointer->type != NULL) {
184 if (ElementsInMolecule[pointer->type->Z] == 0)
185 ElementCount++;
186 ElementsInMolecule[pointer->type->Z]++; // increase number of elements
187 if (pointer->type->Z != 1)
188 NoNonHydrogen++;
189 if (pointer->Name == NULL) {
190 Free(&pointer->Name);
191 pointer->Name = Malloc<char>(6, "molecule::AddAtom: *pointer->Name");
192 sprintf(pointer->Name, "%2s%02d", pointer->type->symbol, pointer->nr+1);
193 }
194 }
195 insert(pointer);
196 }
197 return true;
198};
199
200/** Adds a copy of the given atom \a *pointer from molecule list.
201 * Increases molecule::last_atom and gives last number to added atom.
202 * \param *pointer allocated and set atom
203 * \return pointer to the newly added atom
204 */
205atom * molecule::AddCopyAtom(atom *pointer)
206{
207 atom *retval = NULL;
208 OBSERVE;
209 if (pointer != NULL) {
210 atom *walker = pointer->clone();
211 walker->Name = Malloc<char>(strlen(pointer->Name) + 1, "atom::atom: *Name");
212 strcpy (walker->Name, pointer->Name);
213 insert(walker);
214 if ((pointer->type != NULL) && (pointer->type->Z != 1))
215 NoNonHydrogen++;
216 AtomCount++;
217 retval=walker;
218 }
219 return retval;
220};
221
222/** Adds a Hydrogen atom in replacement for the given atom \a *partner in bond with a *origin.
223 * Here, we have to distinguish between single, double or triple bonds as stated by \a BondDegree, that each demand
224 * a different scheme when adding \a *replacement atom for the given one.
225 * -# Single Bond: Simply add new atom with bond distance rescaled to typical hydrogen one
226 * -# Double Bond: Here, we need the **BondList of the \a *origin atom, by scanning for the other bonds instead of
227 * *Bond, we use the through these connected atoms to determine the plane they lie in, vector::MakeNormalvector().
228 * The orthonormal vector to this plane along with the vector in *Bond direction determines the plane the two
229 * replacing hydrogens shall lie in. Now, all remains to do is take the usual hydrogen double bond angle for the
230 * element of *origin and form the sin/cos admixture of both plane vectors for the new coordinates of the two
231 * hydrogens forming this angle with *origin.
232 * -# 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
233 * triangle formed by the to be added hydrogens are not equal to the typical bond distance \f$l\f$ but have to be
234 * determined from the typical angle \f$\alpha\f$ for a hydrogen triple connected to the element of *origin):
235 * We have the height \f$d\f$ as the vector in *Bond direction (from triangle C1-H1-H2).
236 * \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 )}}
237 * \f]
238 * vector::GetNormalvector() creates one orthonormal vector from this *Bond vector and vector::MakeNormalvector creates
239 * the third one from the former two vectors. The latter ones form the plane of the base triangle mentioned above.
240 * The lengths for these are \f$f\f$ and \f$g\f$ (from triangle H1-H2-(center of H1-H2-H3)) with knowledge that
241 * the median lines in an isosceles triangle meet in the center point with a ratio 2:1.
242 * \f[ f = \frac{b}{\sqrt{3}} \qquad g = \frac{b}{2}
243 * \f]
244 * as the coordination of all three atoms in the coordinate system of these three vectors:
245 * \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$.
246 *
247 * \param *out output stream for debugging
248 * \param *Bond pointer to bond between \a *origin and \a *replacement
249 * \param *TopOrigin son of \a *origin of upper level molecule (the atom added to this molecule as a copy of \a *origin)
250 * \param *origin pointer to atom which acts as the origin for scaling the added hydrogen to correct bond length
251 * \param *replacement pointer to the atom which shall be copied as a hydrogen atom in this molecule
252 * \param isAngstroem whether the coordination of the given atoms is in AtomicLength (false) or Angstrom(true)
253 * \return number of atoms added, if < bond::BondDegree then something went wrong
254 * \todo double and triple bonds splitting (always use the tetraeder angle!)
255 */
256bool molecule::AddHydrogenReplacementAtom(bond *TopBond, atom *BottomOrigin, atom *TopOrigin, atom *TopReplacement, bool IsAngstroem)
257{
258 bool AllWentWell = true; // flag gathering the boolean return value of molecule::AddAtom and other functions, as return value on exit
259 OBSERVE;
260 double bondlength; // bond length of the bond to be replaced/cut
261 double bondangle; // bond angle of the bond to be replaced/cut
262 double BondRescale; // rescale value for the hydrogen bond length
263 bond *FirstBond = NULL, *SecondBond = NULL; // Other bonds in double bond case to determine "other" plane
264 atom *FirstOtherAtom = NULL, *SecondOtherAtom = NULL, *ThirdOtherAtom = NULL; // pointer to hydrogen atoms to be added
265 double b,l,d,f,g, alpha, factors[NDIM]; // hold temporary values in triple bond case for coordination determination
266 Vector Orthovector1, Orthovector2; // temporary vectors in coordination construction
267 Vector InBondvector; // vector in direction of *Bond
268 double *matrix = NULL;
269 bond *Binder = NULL;
270
271// Log() << Verbose(3) << "Begin of AddHydrogenReplacementAtom." << endl;
272 // create vector in direction of bond
273 InBondvector.CopyVector(&TopReplacement->x);
274 InBondvector.SubtractVector(&TopOrigin->x);
275 bondlength = InBondvector.Norm();
276
277 // is greater than typical bond distance? Then we have to correct periodically
278 // the problem is not the H being out of the box, but InBondvector have the wrong direction
279 // due to TopReplacement or Origin being on the wrong side!
280 if (bondlength > BondDistance) {
281// Log() << Verbose(4) << "InBondvector is: ";
282// InBondvector.Output(out);
283// Log() << Verbose(0) << endl;
284 Orthovector1.Zero();
285 for (int i=NDIM;i--;) {
286 l = TopReplacement->x.x[i] - TopOrigin->x.x[i];
287 if (fabs(l) > BondDistance) { // is component greater than bond distance
288 Orthovector1.x[i] = (l < 0) ? -1. : +1.;
289 } // (signs are correct, was tested!)
290 }
291 matrix = ReturnFullMatrixforSymmetric(cell_size);
292 Orthovector1.MatrixMultiplication(matrix);
293 InBondvector.SubtractVector(&Orthovector1); // subtract just the additional translation
294 Free(&matrix);
295 bondlength = InBondvector.Norm();
296// Log() << Verbose(4) << "Corrected InBondvector is now: ";
297// InBondvector.Output(out);
298// Log() << Verbose(0) << endl;
299 } // periodic correction finished
300
301 InBondvector.Normalize();
302 // get typical bond length and store as scale factor for later
303 BondRescale = TopOrigin->type->HBondDistance[TopBond->BondDegree-1];
304 if (BondRescale == -1) {
305 eLog() << Verbose(1) << "There is no typical hydrogen bond distance in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
306 return false;
307 BondRescale = bondlength;
308 } else {
309 if (!IsAngstroem)
310 BondRescale /= (1.*AtomicLengthToAngstroem);
311 }
312
313 // discern single, double and triple bonds
314 switch(TopBond->BondDegree) {
315 case 1:
316 FirstOtherAtom = World::get()->createAtom(); // new atom
317 FirstOtherAtom->type = elemente->FindElement(1); // element is Hydrogen
318 FirstOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
319 FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
320 if (TopReplacement->type->Z == 1) { // neither rescale nor replace if it's already hydrogen
321 FirstOtherAtom->father = TopReplacement;
322 BondRescale = bondlength;
323 } else {
324 FirstOtherAtom->father = NULL; // if we replace hydrogen, we mark it as our father, otherwise we are just an added hydrogen with no father
325 }
326 InBondvector.Scale(&BondRescale); // rescale the distance vector to Hydrogen bond length
327 FirstOtherAtom->x.CopyVector(&TopOrigin->x); // set coordination to origin ...
328 FirstOtherAtom->x.AddVector(&InBondvector); // ... and add distance vector to replacement atom
329 AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
330// Log() << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
331// FirstOtherAtom->x.Output(out);
332// Log() << Verbose(0) << endl;
333 Binder = AddBond(BottomOrigin, FirstOtherAtom, 1);
334 Binder->Cyclic = false;
335 Binder->Type = TreeEdge;
336 break;
337 case 2:
338 // determine two other bonds (warning if there are more than two other) plus valence sanity check
339 for (BondList::const_iterator Runner = TopOrigin->ListOfBonds.begin(); Runner != TopOrigin->ListOfBonds.end(); (++Runner)) {
340 if ((*Runner) != TopBond) {
341 if (FirstBond == NULL) {
342 FirstBond = (*Runner);
343 FirstOtherAtom = (*Runner)->GetOtherAtom(TopOrigin);
344 } else if (SecondBond == NULL) {
345 SecondBond = (*Runner);
346 SecondOtherAtom = (*Runner)->GetOtherAtom(TopOrigin);
347 } else {
348 eLog() << Verbose(2) << "Detected more than four bonds for atom " << TopOrigin->Name;
349 }
350 }
351 }
352 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)
353 SecondBond = TopBond;
354 SecondOtherAtom = TopReplacement;
355 }
356 if (FirstOtherAtom != NULL) { // then we just have this double bond and the plane does not matter at all
357// 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;
358
359 // determine the plane of these two with the *origin
360 AllWentWell = AllWentWell && Orthovector1.MakeNormalVector(&TopOrigin->x, &FirstOtherAtom->x, &SecondOtherAtom->x);
361 } else {
362 Orthovector1.GetOneNormalVector(&InBondvector);
363 }
364 //Log() << Verbose(3)<< "Orthovector1: ";
365 //Orthovector1.Output(out);
366 //Log() << Verbose(0) << endl;
367 // orthogonal vector and bond vector between origin and replacement form the new plane
368 Orthovector1.MakeNormalVector(&InBondvector);
369 Orthovector1.Normalize();
370 //Log() << Verbose(3) << "ReScaleCheck: " << Orthovector1.Norm() << " and " << InBondvector.Norm() << "." << endl;
371
372 // create the two Hydrogens ...
373 FirstOtherAtom = World::get()->createAtom();
374 SecondOtherAtom = World::get()->createAtom();
375 FirstOtherAtom->type = elemente->FindElement(1);
376 SecondOtherAtom->type = elemente->FindElement(1);
377 FirstOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
378 FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
379 SecondOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
380 SecondOtherAtom->FixedIon = TopReplacement->FixedIon;
381 FirstOtherAtom->father = NULL; // we are just an added hydrogen with no father
382 SecondOtherAtom->father = NULL; // we are just an added hydrogen with no father
383 bondangle = TopOrigin->type->HBondAngle[1];
384 if (bondangle == -1) {
385 eLog() << Verbose(1) << "There is no typical hydrogen bond angle in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
386 return false;
387 bondangle = 0;
388 }
389 bondangle *= M_PI/180./2.;
390// Log() << Verbose(3) << "ReScaleCheck: InBondvector ";
391// InBondvector.Output(out);
392// Log() << Verbose(0) << endl;
393// Log() << Verbose(3) << "ReScaleCheck: Orthovector ";
394// Orthovector1.Output(out);
395// Log() << Verbose(0) << endl;
396// Log() << Verbose(3) << "Half the bond angle is " << bondangle << ", sin and cos of it: " << sin(bondangle) << ", " << cos(bondangle) << endl;
397 FirstOtherAtom->x.Zero();
398 SecondOtherAtom->x.Zero();
399 for(int i=NDIM;i--;) { // rotate by half the bond angle in both directions (InBondvector is bondangle = 0 direction)
400 FirstOtherAtom->x.x[i] = InBondvector.x[i] * cos(bondangle) + Orthovector1.x[i] * (sin(bondangle));
401 SecondOtherAtom->x.x[i] = InBondvector.x[i] * cos(bondangle) + Orthovector1.x[i] * (-sin(bondangle));
402 }
403 FirstOtherAtom->x.Scale(&BondRescale); // rescale by correct BondDistance
404 SecondOtherAtom->x.Scale(&BondRescale);
405 //Log() << Verbose(3) << "ReScaleCheck: " << FirstOtherAtom->x.Norm() << " and " << SecondOtherAtom->x.Norm() << "." << endl;
406 for(int i=NDIM;i--;) { // and make relative to origin atom
407 FirstOtherAtom->x.x[i] += TopOrigin->x.x[i];
408 SecondOtherAtom->x.x[i] += TopOrigin->x.x[i];
409 }
410 // ... and add to molecule
411 AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
412 AllWentWell = AllWentWell && AddAtom(SecondOtherAtom);
413// Log() << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
414// FirstOtherAtom->x.Output(out);
415// Log() << Verbose(0) << endl;
416// Log() << Verbose(4) << "Added " << *SecondOtherAtom << " at: ";
417// SecondOtherAtom->x.Output(out);
418// Log() << Verbose(0) << endl;
419 Binder = AddBond(BottomOrigin, FirstOtherAtom, 1);
420 Binder->Cyclic = false;
421 Binder->Type = TreeEdge;
422 Binder = AddBond(BottomOrigin, SecondOtherAtom, 1);
423 Binder->Cyclic = false;
424 Binder->Type = TreeEdge;
425 break;
426 case 3:
427 // take the "usual" tetraoidal angle and add the three Hydrogen in direction of the bond (height of the tetraoid)
428 FirstOtherAtom = World::get()->createAtom();
429 SecondOtherAtom = World::get()->createAtom();
430 ThirdOtherAtom = World::get()->createAtom();
431 FirstOtherAtom->type = elemente->FindElement(1);
432 SecondOtherAtom->type = elemente->FindElement(1);
433 ThirdOtherAtom->type = elemente->FindElement(1);
434 FirstOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
435 FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
436 SecondOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
437 SecondOtherAtom->FixedIon = TopReplacement->FixedIon;
438 ThirdOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
439 ThirdOtherAtom->FixedIon = TopReplacement->FixedIon;
440 FirstOtherAtom->father = NULL; // we are just an added hydrogen with no father
441 SecondOtherAtom->father = NULL; // we are just an added hydrogen with no father
442 ThirdOtherAtom->father = NULL; // we are just an added hydrogen with no father
443
444 // we need to vectors orthonormal the InBondvector
445 AllWentWell = AllWentWell && Orthovector1.GetOneNormalVector(&InBondvector);
446// Log() << Verbose(3) << "Orthovector1: ";
447// Orthovector1.Output(out);
448// Log() << Verbose(0) << endl;
449 AllWentWell = AllWentWell && Orthovector2.MakeNormalVector(&InBondvector, &Orthovector1);
450// Log() << Verbose(3) << "Orthovector2: ";
451// Orthovector2.Output(out);
452// Log() << Verbose(0) << endl;
453
454 // create correct coordination for the three atoms
455 alpha = (TopOrigin->type->HBondAngle[2])/180.*M_PI/2.; // retrieve triple bond angle from database
456 l = BondRescale; // desired bond length
457 b = 2.*l*sin(alpha); // base length of isosceles triangle
458 d = l*sqrt(cos(alpha)*cos(alpha) - sin(alpha)*sin(alpha)/3.); // length for InBondvector
459 f = b/sqrt(3.); // length for Orthvector1
460 g = b/2.; // length for Orthvector2
461// Log() << Verbose(3) << "Bond length and half-angle: " << l << ", " << alpha << "\t (b,d,f,g) = " << b << ", " << d << ", " << f << ", " << g << ", " << endl;
462// 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;
463 factors[0] = d;
464 factors[1] = f;
465 factors[2] = 0.;
466 FirstOtherAtom->x.LinearCombinationOfVectors(&InBondvector, &Orthovector1, &Orthovector2, factors);
467 factors[1] = -0.5*f;
468 factors[2] = g;
469 SecondOtherAtom->x.LinearCombinationOfVectors(&InBondvector, &Orthovector1, &Orthovector2, factors);
470 factors[2] = -g;
471 ThirdOtherAtom->x.LinearCombinationOfVectors(&InBondvector, &Orthovector1, &Orthovector2, factors);
472
473 // rescale each to correct BondDistance
474// FirstOtherAtom->x.Scale(&BondRescale);
475// SecondOtherAtom->x.Scale(&BondRescale);
476// ThirdOtherAtom->x.Scale(&BondRescale);
477
478 // and relative to *origin atom
479 FirstOtherAtom->x.AddVector(&TopOrigin->x);
480 SecondOtherAtom->x.AddVector(&TopOrigin->x);
481 ThirdOtherAtom->x.AddVector(&TopOrigin->x);
482
483 // ... and add to molecule
484 AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
485 AllWentWell = AllWentWell && AddAtom(SecondOtherAtom);
486 AllWentWell = AllWentWell && AddAtom(ThirdOtherAtom);
487// Log() << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
488// FirstOtherAtom->x.Output(out);
489// Log() << Verbose(0) << endl;
490// Log() << Verbose(4) << "Added " << *SecondOtherAtom << " at: ";
491// SecondOtherAtom->x.Output(out);
492// Log() << Verbose(0) << endl;
493// Log() << Verbose(4) << "Added " << *ThirdOtherAtom << " at: ";
494// ThirdOtherAtom->x.Output(out);
495// Log() << Verbose(0) << endl;
496 Binder = AddBond(BottomOrigin, FirstOtherAtom, 1);
497 Binder->Cyclic = false;
498 Binder->Type = TreeEdge;
499 Binder = AddBond(BottomOrigin, SecondOtherAtom, 1);
500 Binder->Cyclic = false;
501 Binder->Type = TreeEdge;
502 Binder = AddBond(BottomOrigin, ThirdOtherAtom, 1);
503 Binder->Cyclic = false;
504 Binder->Type = TreeEdge;
505 break;
506 default:
507 eLog() << Verbose(1) << "BondDegree does not state single, double or triple bond!" << endl;
508 AllWentWell = false;
509 break;
510 }
511 Free(&matrix);
512
513// Log() << Verbose(3) << "End of AddHydrogenReplacementAtom." << endl;
514 return AllWentWell;
515};
516
517/** Adds given atom \a *pointer from molecule list.
518 * Increases molecule::last_atom and gives last number to added atom.
519 * \param filename name and path of xyz file
520 * \return true - succeeded, false - file not found
521 */
522bool molecule::AddXYZFile(string filename)
523{
524
525 istringstream *input = NULL;
526 int NumberOfAtoms = 0; // atom number in xyz read
527 int i, j; // loop variables
528 atom *Walker = NULL; // pointer to added atom
529 char shorthand[3]; // shorthand for atom name
530 ifstream xyzfile; // xyz file
531 string line; // currently parsed line
532 double x[3]; // atom coordinates
533
534 xyzfile.open(filename.c_str());
535 if (!xyzfile)
536 return false;
537
538 OBSERVE;
539 getline(xyzfile,line,'\n'); // Read numer of atoms in file
540 input = new istringstream(line);
541 *input >> NumberOfAtoms;
542 Log() << Verbose(0) << "Parsing " << NumberOfAtoms << " atoms in file." << endl;
543 getline(xyzfile,line,'\n'); // Read comment
544 Log() << Verbose(1) << "Comment: " << line << endl;
545
546 if (MDSteps == 0) // no atoms yet present
547 MDSteps++;
548 for(i=0;i<NumberOfAtoms;i++){
549 Walker = World::get()->createAtom();
550 getline(xyzfile,line,'\n');
551 istringstream *item = new istringstream(line);
552 //istringstream input(line);
553 //Log() << Verbose(1) << "Reading: " << line << endl;
554 *item >> shorthand;
555 *item >> x[0];
556 *item >> x[1];
557 *item >> x[2];
558 Walker->type = elemente->FindElement(shorthand);
559 if (Walker->type == NULL) {
560 eLog() << Verbose(1) << "Could not parse the element at line: '" << line << "', setting to H.";
561 Walker->type = elemente->FindElement(1);
562 }
563 if (Walker->Trajectory.R.size() <= (unsigned int)MDSteps) {
564 Walker->Trajectory.R.resize(MDSteps+10);
565 Walker->Trajectory.U.resize(MDSteps+10);
566 Walker->Trajectory.F.resize(MDSteps+10);
567 }
568 for(j=NDIM;j--;) {
569 Walker->x.x[j] = x[j];
570 Walker->Trajectory.R.at(MDSteps-1).x[j] = x[j];
571 Walker->Trajectory.U.at(MDSteps-1).x[j] = 0;
572 Walker->Trajectory.F.at(MDSteps-1).x[j] = 0;
573 }
574 AddAtom(Walker); // add to molecule
575 delete(item);
576 }
577 xyzfile.close();
578 delete(input);
579 return true;
580};
581
582/** Creates a copy of this molecule.
583 * \return copy of molecule
584 */
585molecule *molecule::CopyMolecule()
586{
587 molecule *copy = new molecule(elemente);
588 atom *LeftAtom = NULL, *RightAtom = NULL;
589
590 // copy all atoms
591 ActOnCopyWithEachAtom ( &molecule::AddCopyAtom, copy );
592
593 // copy all bonds
594 bond *Binder = first;
595 bond *NewBond = NULL;
596 while(Binder->next != last) {
597 Binder = Binder->next;
598
599 // get the pendant atoms of current bond in the copy molecule
600 copy->ActOnAllAtoms( &atom::EqualsFather, (const atom *)Binder->leftatom, (const atom **)&LeftAtom );
601 copy->ActOnAllAtoms( &atom::EqualsFather, (const atom *)Binder->rightatom, (const atom **)&RightAtom );
602
603 NewBond = copy->AddBond(LeftAtom, RightAtom, Binder->BondDegree);
604 NewBond->Cyclic = Binder->Cyclic;
605 if (Binder->Cyclic)
606 copy->NoCyclicBonds++;
607 NewBond->Type = Binder->Type;
608 }
609 // correct fathers
610 ActOnAllAtoms( &atom::CorrectFather );
611
612 // copy values
613 copy->CountAtoms();
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 if (ElementsInMolecule[pointer->type->Z] != 0) { // this would indicate an error
731 ElementsInMolecule[pointer->type->Z]--; // decrease number of atom of this element
732 AtomCount--;
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 << AtomCount << "\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 << AtomCount << "\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 */
938void molecule::CountAtoms()
939{
940 int i = size();
941 if ((AtomCount == 0) || (i != AtomCount)) {
942 cout << "!!!!!!!!! Counting needed" << endl;
943 Log() << Verbose(3) << "Mismatch in AtomCount " << AtomCount << " and recounted number " << i << ", renaming all." << endl;
944 AtomCount = i;
945
946 // count NonHydrogen atoms and give each atom a unique name
947 if (AtomCount != 0) {
948 i=0;
949 NoNonHydrogen = 0;
950 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
951 (*iter)->nr = i; // update number in molecule (for easier referencing in FragmentMolecule lateron)
952 if ((*iter)->type->Z != 1) // count non-hydrogen atoms whilst at it
953 NoNonHydrogen++;
954 Free(&(*iter)->Name);
955 (*iter)->Name = Malloc<char>(6, "molecule::CountAtoms: *walker->Name");
956 sprintf((*iter)->Name, "%2s%02d", (*iter)->type->symbol, (*iter)->nr+1);
957 Log() << Verbose(3) << "Naming atom nr. " << (*iter)->nr << " " << (*iter)->Name << "." << endl;
958 i++;
959 }
960 } else
961 Log() << Verbose(3) << "AtomCount is still " << AtomCount << ", thus counting nothing." << endl;
962 }
963};
964
965/** Brings molecule::ElementCount and molecule::ElementsInMolecule up-to-date.
966 */
967void molecule::CountElements()
968{
969 for(int i=MAX_ELEMENTS;i--;)
970 ElementsInMolecule[i] = 0;
971 ElementCount = 0;
972
973 SetIndexedArrayForEachAtomTo ( ElementsInMolecule, &element::Z, &Increment, 1);
974
975 for(int i=MAX_ELEMENTS;i--;)
976 ElementCount += (ElementsInMolecule[i] != 0 ? 1 : 0);
977};
978
979
980/** Counts necessary number of valence electrons and returns number and SpinType.
981 * \param configuration containing everything
982 */
983void molecule::CalculateOrbitals(class config &configuration)
984{
985 configuration.MaxPsiDouble = configuration.PsiMaxNoDown = configuration.PsiMaxNoUp = configuration.PsiType = 0;
986 for(int i=MAX_ELEMENTS;i--;) {
987 if (ElementsInMolecule[i] != 0) {
988 //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;
989 configuration.MaxPsiDouble += ElementsInMolecule[i]*((int)elemente->FindElement(i)->Valence);
990 }
991 }
992 configuration.PsiMaxNoDown = configuration.MaxPsiDouble/2 + (configuration.MaxPsiDouble % 2);
993 configuration.PsiMaxNoUp = configuration.MaxPsiDouble/2;
994 configuration.MaxPsiDouble /= 2;
995 configuration.PsiType = (configuration.PsiMaxNoDown == configuration.PsiMaxNoUp) ? 0 : 1;
996 if ((configuration.PsiType == 1) && (configuration.ProcPEPsi < 2)) {
997 configuration.ProcPEGamma /= 2;
998 configuration.ProcPEPsi *= 2;
999 } else {
1000 configuration.ProcPEGamma *= configuration.ProcPEPsi;
1001 configuration.ProcPEPsi = 1;
1002 }
1003 configuration.InitMaxMinStopStep = configuration.MaxMinStopStep = configuration.MaxPsiDouble;
1004};
1005
1006/** Determines whether two molecules actually contain the same atoms and coordination.
1007 * \param *out output stream for debugging
1008 * \param *OtherMolecule the molecule to compare this one to
1009 * \param threshold upper limit of difference when comparing the coordination.
1010 * \return NULL - not equal, otherwise an allocated (molecule::AtomCount) permutation map of the atom numbers (which corresponds to which)
1011 */
1012int * molecule::IsEqualToWithinThreshold(molecule *OtherMolecule, double threshold)
1013{
1014 int flag;
1015 double *Distances = NULL, *OtherDistances = NULL;
1016 Vector CenterOfGravity, OtherCenterOfGravity;
1017 size_t *PermMap = NULL, *OtherPermMap = NULL;
1018 int *PermutationMap = NULL;
1019 bool result = true; // status of comparison
1020
1021 Log() << Verbose(3) << "Begin of IsEqualToWithinThreshold." << endl;
1022 /// first count both their atoms and elements and update lists thereby ...
1023 //Log() << Verbose(0) << "Counting atoms, updating list" << endl;
1024 CountAtoms();
1025 OtherMolecule->CountAtoms();
1026 CountElements();
1027 OtherMolecule->CountElements();
1028
1029 /// ... and compare:
1030 /// -# AtomCount
1031 if (result) {
1032 if (AtomCount != OtherMolecule->AtomCount) {
1033 Log() << Verbose(4) << "AtomCounts don't match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
1034 result = false;
1035 } else Log() << Verbose(4) << "AtomCounts match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
1036 }
1037 /// -# ElementCount
1038 if (result) {
1039 if (ElementCount != OtherMolecule->ElementCount) {
1040 Log() << Verbose(4) << "ElementCount don't match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
1041 result = false;
1042 } else Log() << Verbose(4) << "ElementCount match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
1043 }
1044 /// -# ElementsInMolecule
1045 if (result) {
1046 for (flag=MAX_ELEMENTS;flag--;) {
1047 //Log() << Verbose(5) << "Element " << flag << ": " << ElementsInMolecule[flag] << " <-> " << OtherMolecule->ElementsInMolecule[flag] << "." << endl;
1048 if (ElementsInMolecule[flag] != OtherMolecule->ElementsInMolecule[flag])
1049 break;
1050 }
1051 if (flag < MAX_ELEMENTS) {
1052 Log() << Verbose(4) << "ElementsInMolecule don't match." << endl;
1053 result = false;
1054 } else Log() << Verbose(4) << "ElementsInMolecule match." << endl;
1055 }
1056 /// then determine and compare center of gravity for each molecule ...
1057 if (result) {
1058 Log() << Verbose(5) << "Calculating Centers of Gravity" << endl;
1059 DeterminePeriodicCenter(CenterOfGravity);
1060 OtherMolecule->DeterminePeriodicCenter(OtherCenterOfGravity);
1061 Log() << Verbose(5) << "Center of Gravity: ";
1062 CenterOfGravity.Output();
1063 Log() << Verbose(0) << endl << Verbose(5) << "Other Center of Gravity: ";
1064 OtherCenterOfGravity.Output();
1065 Log() << Verbose(0) << endl;
1066 if (CenterOfGravity.DistanceSquared(&OtherCenterOfGravity) > threshold*threshold) {
1067 Log() << Verbose(4) << "Centers of gravity don't match." << endl;
1068 result = false;
1069 }
1070 }
1071
1072 /// ... then make a list with the euclidian distance to this center for each atom of both molecules
1073 if (result) {
1074 Log() << Verbose(5) << "Calculating distances" << endl;
1075 Distances = Calloc<double>(AtomCount, "molecule::IsEqualToWithinThreshold: Distances");
1076 OtherDistances = Calloc<double>(AtomCount, "molecule::IsEqualToWithinThreshold: OtherDistances");
1077 SetIndexedArrayForEachAtomTo ( Distances, &atom::nr, &atom::DistanceSquaredToVector, (const Vector &)CenterOfGravity);
1078 SetIndexedArrayForEachAtomTo ( OtherDistances, &atom::nr, &atom::DistanceSquaredToVector, (const Vector &)CenterOfGravity);
1079
1080 /// ... sort each list (using heapsort (o(N log N)) from GSL)
1081 Log() << Verbose(5) << "Sorting distances" << endl;
1082 PermMap = Calloc<size_t>(AtomCount, "molecule::IsEqualToWithinThreshold: *PermMap");
1083 OtherPermMap = Calloc<size_t>(AtomCount, "molecule::IsEqualToWithinThreshold: *OtherPermMap");
1084 gsl_heapsort_index (PermMap, Distances, AtomCount, sizeof(double), CompareDoubles);
1085 gsl_heapsort_index (OtherPermMap, OtherDistances, AtomCount, sizeof(double), CompareDoubles);
1086 PermutationMap = Calloc<int>(AtomCount, "molecule::IsEqualToWithinThreshold: *PermutationMap");
1087 Log() << Verbose(5) << "Combining Permutation Maps" << endl;
1088 for(int i=AtomCount;i--;)
1089 PermutationMap[PermMap[i]] = (int) OtherPermMap[i];
1090
1091 /// ... and compare them step by step, whether the difference is individually(!) below \a threshold for all
1092 Log() << Verbose(4) << "Comparing distances" << endl;
1093 flag = 0;
1094 for (int i=0;i<AtomCount;i++) {
1095 Log() << Verbose(5) << "Distances squared: |" << Distances[PermMap[i]] << " - " << OtherDistances[OtherPermMap[i]] << "| = " << fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) << " ?<? " << threshold << endl;
1096 if (fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) > threshold*threshold)
1097 flag = 1;
1098 }
1099
1100 // free memory
1101 Free(&PermMap);
1102 Free(&OtherPermMap);
1103 Free(&Distances);
1104 Free(&OtherDistances);
1105 if (flag) { // if not equal
1106 Free(&PermutationMap);
1107 result = false;
1108 }
1109 }
1110 /// return pointer to map if all distances were below \a threshold
1111 Log() << Verbose(3) << "End of IsEqualToWithinThreshold." << endl;
1112 if (result) {
1113 Log() << Verbose(3) << "Result: Equal." << endl;
1114 return PermutationMap;
1115 } else {
1116 Log() << Verbose(3) << "Result: Not equal." << endl;
1117 return NULL;
1118 }
1119};
1120
1121/** Returns an index map for two father-son-molecules.
1122 * The map tells which atom in this molecule corresponds to which one in the other molecul with their fathers.
1123 * \param *out output stream for debugging
1124 * \param *OtherMolecule corresponding molecule with fathers
1125 * \return allocated map of size molecule::AtomCount with map
1126 * \todo make this with a good sort O(n), not O(n^2)
1127 */
1128int * molecule::GetFatherSonAtomicMap(molecule *OtherMolecule)
1129{
1130 Log() << Verbose(3) << "Begin of GetFatherAtomicMap." << endl;
1131 int *AtomicMap = Malloc<int>(AtomCount, "molecule::GetAtomicMap: *AtomicMap");
1132 for (int i=AtomCount;i--;)
1133 AtomicMap[i] = -1;
1134 if (OtherMolecule == this) { // same molecule
1135 for (int i=AtomCount;i--;) // no need as -1 means already that there is trivial correspondence
1136 AtomicMap[i] = i;
1137 Log() << Verbose(4) << "Map is trivial." << endl;
1138 } else {
1139 Log() << Verbose(4) << "Map is ";
1140 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
1141 if ((*iter)->father == NULL) {
1142 AtomicMap[(*iter)->nr] = -2;
1143 } else {
1144 for (molecule::const_iterator runner = OtherMolecule->begin(); runner != OtherMolecule->end(); ++runner) {
1145 //for (int i=0;i<AtomCount;i++) { // search atom
1146 //for (int j=0;j<OtherMolecule->AtomCount;j++) {
1147 //Log() << Verbose(4) << "Comparing father " << (*iter)->father << " with the other one " << (*runner)->father << "." << endl;
1148 if ((*iter)->father == (*runner))
1149 AtomicMap[(*iter)->nr] = (*runner)->nr;
1150 }
1151 }
1152 Log() << Verbose(0) << AtomicMap[(*iter)->nr] << "\t";
1153 }
1154 Log() << Verbose(0) << endl;
1155 }
1156 Log() << Verbose(3) << "End of GetFatherAtomicMap." << endl;
1157 return AtomicMap;
1158};
1159
1160/** Stores the temperature evaluated from velocities in molecule::Trajectories.
1161 * We simply use the formula equivaleting temperature and kinetic energy:
1162 * \f$k_B T = \sum_i m_i v_i^2\f$
1163 * \param *output output stream of temperature file
1164 * \param startstep first MD step in molecule::Trajectories
1165 * \param endstep last plus one MD step in molecule::Trajectories
1166 * \return file written (true), failure on writing file (false)
1167 */
1168bool molecule::OutputTemperatureFromTrajectories(ofstream * const output, int startstep, int endstep)
1169{
1170 double temperature;
1171 // test stream
1172 if (output == NULL)
1173 return false;
1174 else
1175 *output << "# Step Temperature [K] Temperature [a.u.]" << endl;
1176 for (int step=startstep;step < endstep; step++) { // loop over all time steps
1177 temperature = 0.;
1178 ActOnAllAtoms( &TrajectoryParticle::AddKineticToTemperature, &temperature, step);
1179 *output << step << "\t" << temperature*AtomicEnergyToKelvin << "\t" << temperature << endl;
1180 }
1181 return true;
1182};
1183
1184void molecule::SetIndexedArrayForEachAtomTo ( atom **array, int ParticleInfo::*index) const
1185{
1186 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
1187 array[((*iter)->*index)] = (*iter);
1188 }
1189};
1190
1191void molecule::flipActiveFlag(){
1192 ActiveFlag = !ActiveFlag;
1193}
Note: See TracBrowser for help on using the repository browser.