source: src/molecule.cpp@ 5188f5

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

FIX: Fix of bug introduced during Vector Refactoring

Testsuite now working again

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