source: src/molecule.cpp@ 920c70

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

Removed all Malloc/Calloc/ReAlloc (&Free) and replaced by new and delete/delete[].

Due to the new MemDebug framework there is no need (or even unnecessary/unwanted competition between it and) for the MemoryAllocator and ..UsageObserver anymore.
They can however still be used with c codes such as pcp and alikes.

In Molecuilder lots of glibc corruptions arose and the C-like syntax make it generally harder to get allocation and deallocation straight.

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