source: src/molecule.cpp@ 5f612ee

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 5f612ee was 5f612ee, checked in by Frederik Heber <heber@…>, 15 years ago

Merge branch 'Analysis_PairCorrelation' into StructureRefactoring

Conflicts:

molecuilder/src/Makefile.am
molecuilder/src/World.cpp
molecuilder/src/World.hpp
molecuilder/src/boundary.cpp
molecuilder/src/builder.cpp
molecuilder/src/log.cpp
molecuilder/src/moleculelist.cpp
molecuilder/src/periodentafel.cpp
molecuilder/src/tesselation.cpp
molecuilder/src/unittests/AnalysisCorrelationToSurfaceUnitTest.cpp
molecuilder/src/unittests/Makefile.am
molecuilder/src/unittests/bondgraphunittest.cpp
molecuilder/src/unittests/gslvectorunittest.cpp
molecuilder/src/unittests/logunittest.cpp
molecuilder/src/unittests/tesselation_boundarytriangleunittest.hpp
molecuilder/src/vector.cpp
molecuilder/tests/Tesselations/defs.in

Conflicts have been many and too numerous to listen here, just the few general cases

  • new molecule() replaced by World::getInstance().createMolecule()
  • new atom() replaced by World::getInstance().createAtom() where appropriate.
  • Some DoLog()s added interfered with changes to the message produced by Log() << Verbose(.) << ...
  • DoLog() has been erroneously added to TestRunner.cpp as well, there cout is appropriate
  • ...

Additionally, there was a bug in atom::clone(), sort was set to atom::nr of the atom to clone not of the clone itself. This caused a failure of the fragmentation.

This merge has been fully checked from a clean build directory with subsequent configure,make all install and make check.
It configures, compiles and runs all test cases and the test suite without errors.

Signed-off-by: Frederik Heber <heber@…>

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