source: src/molecule.cpp@ e24c78

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

Used the formual class instead of single variables inside molecule

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