source: src/molecule.cpp@ 6b59ab

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

Moved method to rename molecules to a seperate Action

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