source: src/molecule.cpp@ 112b09

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

Added #include "Helpers/MemDebug.hpp" to all .cpp files

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