source: src/molecule.cpp@ 255971

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 SharedLibraries
Last change on this file since 255971 was 952f38, checked in by Frederik Heber <heber@…>, 15 years ago

created LibMolecuilderHelpers.

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