source: src/molecule.cpp@ d386e8

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

Broken: Merge commit 'Gitosis/stable' into stable

Conflicts:

molecuilder/src/Actions/AnalysisAction/PairCorrelationToPointAction.cpp
molecuilder/src/Actions/AnalysisAction/PairCorrelationToSurfaceAction.cpp
molecuilder/src/Makefile.am

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