source: src/molecule.cpp@ dc0d21

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

Merge branch 'stable' into PcpAndMpqcParser

Conflicts:

molecuilder/src/Makefile.am

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