source: src/molecule.cpp@ 24a5e0

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

Added -Wall flag and fixed several small hickups

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