source: src/molecule.cpp@ d74077

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

Member variable Vector and element of class atom are now private.

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