source: src/molecule.cpp@ 02ee15

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

Made the world solely responsible for creating and destroying atoms.

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