source: src/molecule.cpp@ cef1d7

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 cef1d7 was 6adb96, checked in by Tillmann Crueger <crueger@…>, 16 years ago

Added possibility for views to catch name changes of molecules

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