source: src/molecule.cpp@ a7b761b

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 Candidate_v1.7.0 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since a7b761b was a7b761b, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Merge branch 'MoleculeStartEndSwitch' into StructureRefactoring

Conflicts:

molecuilder/src/Helpers/Assert.cpp
molecuilder/src/Helpers/Assert.hpp
molecuilder/src/Legacy/oldmenu.cpp
molecuilder/src/Makefile.am
molecuilder/src/Patterns/Cacheable.hpp
molecuilder/src/Patterns/Observer.cpp
molecuilder/src/Patterns/Observer.hpp
molecuilder/src/analysis_correlation.cpp
molecuilder/src/boundary.cpp
molecuilder/src/builder.cpp
molecuilder/src/config.cpp
molecuilder/src/helpers.hpp
molecuilder/src/molecule.cpp
molecuilder/src/molecule.hpp
molecuilder/src/molecule_dynamics.cpp
molecuilder/src/molecule_fragmentation.cpp
molecuilder/src/molecule_geometry.cpp
molecuilder/src/molecule_graph.cpp
molecuilder/src/moleculelist.cpp
molecuilder/src/tesselation.cpp
molecuilder/src/unittests/AnalysisCorrelationToSurfaceUnitTest.cpp
molecuilder/src/unittests/ObserverTest.cpp
molecuilder/src/unittests/ObserverTest.hpp

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