source: src/molecule.cpp@ 9df5c6

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 Candidate_v1.7.0 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 9df5c6 was 9df5c6, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Made the Vector::IsInParallelepiped() method take a matrix instead of a double*

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