source: src/molecule.cpp@ 8f4df1

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

Merge branch 'AtomicPositionEncapsulation' into stable

Conflicts:

src/Actions/AtomAction/ChangeElementAction.cpp
src/Actions/WorldAction/RemoveSphereOfAtomsAction.cpp
src/Makefile.am
src/UIElements/TextUI/TextDialog.cpp
src/analysis_correlation.hpp
src/atom.cpp
src/atom_atominfo.hpp
src/bond.cpp
src/boundary.cpp
src/molecule_geometry.cpp
src/tesselation.cpp
src/tesselationhelpers.cpp
src/triangleintersectionlist.cpp
src/unittests/Makefile.am

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