source: src/molecule.cpp@ 436f04

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 436f04 was d10eb6, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Made the ReturnFullMatrixForSymmetric return a Matrix object directely instead of a double array

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