source: src/molecule.cpp@ 7042f45

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 7042f45 was cbc5fb, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Made the world solely responsible for creating and erasing molecules.

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