source: src/molecule.cpp@ 906822

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

Removed forgotten debug message

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