source: src/molecule.cpp@ a356f2

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

BIG CHANGE: config::load and config::save in ParseCommandLineOptions() and main() replaced with FormatParser replacements.

Fragmentation:

  • FIX: MoleculeFillWithMoleculeAction: filler atoms have to be removed before the system can be stored to file.
  • FIX: PcpParser::load() - has to put the molecule also into World's MoleculeListClass (otherwise the name cannot be set right after loading)
  • new Libparser.a
  • all sources from PARSER subdir are compiled into libparser such that only ParserUnitTest is recompiled.

Testfixes:

  • testsuite-fragmentation - changes to due to different -f calling syntax.
  • most of the xyz files had to be replaced due to a single whitespace at the end of each entry: Domain/6, Simple_configuration/2, Simple_configuration/3, Simple_configuration/4, Simple_configuration/5, Simple_configuration/8
  • in many cases were the number orbitals (and thus MaxMinStopStep) wrong: Filling/1, Simple_configuration/4, Simple_configuration/5

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

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