source: src/molecule.cpp@ b6dbff

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

Merge branch 'stable' into StructureRefactoring

Conflicts:

molecuilder/src/World.cpp

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