source: src/molecule.cpp@ 4ef9b7

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

Removed all inclusions of GSL-Headers from molecule.hpp

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