source: src/molecule.cpp@ 0a4f7f

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

Made data internal data-structure of vector class private

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