source: src/molecule.cpp@ 1829c4

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 1829c4 was 8cbb97, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Merge branch 'VectorRefactoring' into StructureRefactoring

Conflicts:

molecuilder/src/Legacy/oldmenu.cpp
molecuilder/src/Makefile.am
molecuilder/src/analysis_correlation.cpp
molecuilder/src/boundary.cpp
molecuilder/src/builder.cpp
molecuilder/src/config.cpp
molecuilder/src/ellipsoid.cpp
molecuilder/src/linkedcell.cpp
molecuilder/src/molecule.cpp
molecuilder/src/molecule_fragmentation.cpp
molecuilder/src/molecule_geometry.cpp
molecuilder/src/molecule_graph.cpp
molecuilder/src/moleculelist.cpp
molecuilder/src/tesselation.cpp
molecuilder/src/tesselationhelpers.cpp
molecuilder/src/unittests/AnalysisCorrelationToSurfaceUnitTest.cpp
molecuilder/src/unittests/bondgraphunittest.cpp
molecuilder/src/vector.cpp
molecuilder/src/vector.hpp

  • Property mode set to 100755
File size: 46.2 KB
RevLine 
[14de469]1/** \file molecules.cpp
[69eb71]2 *
[14de469]3 * Functions for the class molecule.
[69eb71]4 *
[14de469]5 */
6
[49e1ae]7#include <cstring>
[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"
[b34306]27#include "World.hpp"
[0a4f7f]28#include "Plane.hpp"
29#include "Exceptions/LinearDependenceException.hpp"
[14de469]30
31
32/************************************* Functions for class molecule *********************************/
33
34/** Constructor of class molecule.
35 * Initialises molecule list with correctly referenced start and end, and sets molecule::last_atom to zero.
36 */
[23b547]37molecule::molecule(const periodentafel * const teil) : elemente(teil), start(World::getInstance().createAtom()), end(World::getInstance().createAtom()),
[fa649a]38 first(new bond(start, end, 1, -1)), last(new bond(start, end, 1, -1)), MDSteps(0), AtomCount(0),
39 BondCount(0), ElementCount(0), NoNonHydrogen(0), NoNonBonds(0), NoCyclicBonds(0), BondDistance(0.),
[24a5e0]40 ActiveFlag(false), IndexNr(-1),
41 formula(this,boost::bind(&molecule::calcFormula,this)),
42 last_atom(0),
43 InternalPointer(start)
[69eb71]44{
[042f82]45 // init atom chain list
46 start->father = NULL;
47 end->father = NULL;
48 link(start,end);
[fa649a]49
[042f82]50 // init bond chain list
51 link(first,last);
[fa649a]52
[042f82]53 // other stuff
54 for(int i=MAX_ELEMENTS;i--;)
55 ElementsInMolecule[i] = 0;
[5f612ee]56 strcpy(name,World::getInstance().getDefaultName());
[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;
[5f612ee]219 double * const cell_size = World::getInstance().getDomain();
[042f82]220
[e138de]221// Log() << Verbose(3) << "Begin of AddHydrogenReplacementAtom." << endl;
[042f82]222 // create vector in direction of bond
[273382]223 InBondvector = TopReplacement->x - TopOrigin->x;
[042f82]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);
[1bd79e]242 InBondvector -= 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) {
[58ed4a]254 DoeLog(1) && (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
[273382]267 FirstOtherAtom->v = TopReplacement->v; // copy velocity
[042f82]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 }
[1bd79e]275 InBondvector *= BondRescale; // rescale the distance vector to Hydrogen bond length
[273382]276 FirstOtherAtom->x = TopOrigin->x; // set coordination to origin ...
277 FirstOtherAtom->x = InBondvector; // ... and add distance vector to replacement atom
[042f82]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 {
[58ed4a]297 DoeLog(2) && (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 {
[273382]318 Orthovector1.GetOneNormalVector(InBondvector);
[042f82]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);
[273382]333 FirstOtherAtom->v = TopReplacement->v; // copy velocity
[042f82]334 FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
[273382]335 SecondOtherAtom->v = TopReplacement->v; // copy velocity
[042f82]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) {
[58ed4a]341 DoeLog(1) && (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 }
[1bd79e]359 FirstOtherAtom->x *= BondRescale; // rescale by correct BondDistance
360 SecondOtherAtom->x *= 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);
[273382]390 FirstOtherAtom->v = TopReplacement->v; // copy velocity
[042f82]391 FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
[273382]392 SecondOtherAtom->v = TopReplacement->v; // copy velocity
[042f82]393 SecondOtherAtom->FixedIon = TopReplacement->FixedIon;
[273382]394 ThirdOtherAtom->v = TopReplacement->v; // copy velocity
[042f82]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
[273382]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.;
[273382]428 FirstOtherAtom->x.LinearCombinationOfVectors(InBondvector, Orthovector1, Orthovector2, factors);
[042f82]429 factors[1] = -0.5*f;
430 factors[2] = g;
[273382]431 SecondOtherAtom->x.LinearCombinationOfVectors(InBondvector, Orthovector1, Orthovector2, factors);
[042f82]432 factors[2] = -g;
[273382]433 ThirdOtherAtom->x.LinearCombinationOfVectors(InBondvector, Orthovector1, Orthovector2, factors);
[042f82]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
[273382]441 FirstOtherAtom->x += TopOrigin->x;
442 SecondOtherAtom->x += TopOrigin->x;
443 ThirdOtherAtom->x += TopOrigin->x;
[042f82]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:
[58ed4a]469 DoeLog(1) && (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;
[a67d19]504 DoLog(0) && (Log() << Verbose(0) << "Parsing " << NumberOfAtoms << " atoms in file." << endl);
[042f82]505 getline(xyzfile,line,'\n'); // Read comment
[a67d19]506 DoLog(1) && (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) {
[58ed4a]522 DoeLog(1) && (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{
[5f612ee]549 molecule *copy = World::getInstance().createMolecule();
[042f82]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 {
[5f612ee]592 molecule *copy = World::getInstance().createMolecule();
[89c8b2]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 {
[58ed4a]618 DoeLog(1) && (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{
[58ed4a]630 //DoeLog(1) && (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{
[58ed4a]644 //DoeLog(1) && (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{
[5f612ee]678 double * const cell_size = World::getInstance().getDomain();
[0a4f7f]679 cell_size[0] = dim->at(0);
[042f82]680 cell_size[1] = 0.;
[0a4f7f]681 cell_size[2] = dim->at(1);
[042f82]682 cell_size[3] = 0.;
683 cell_size[4] = 0.;
[0a4f7f]684 cell_size[5] = dim->at(2);
[14de469]685};
686
[cee0b57]687/** Removes atom from molecule list and deletes it.
688 * \param *pointer atom to be removed
689 * \return true - succeeded, false - atom not found in list
[a9d254]690 */
[cee0b57]691bool molecule::RemoveAtom(atom *pointer)
[a9d254]692{
[cee0b57]693 if (ElementsInMolecule[pointer->type->Z] != 0) { // this would indicate an error
694 ElementsInMolecule[pointer->type->Z]--; // decrease number of atom of this element
695 AtomCount--;
696 } else
[58ed4a]697 DoeLog(1) && (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--;
[266237]700 RemoveBonds(pointer);
[cee0b57]701 return remove(pointer, start, end);
[a9d254]702};
703
[cee0b57]704/** Removes atom from molecule list, but does not delete it.
705 * \param *pointer atom to be removed
706 * \return true - succeeded, false - atom not found in list
[f3278b]707 */
[cee0b57]708bool molecule::UnlinkAtom(atom *pointer)
[f3278b]709{
[cee0b57]710 if (pointer == NULL)
711 return false;
712 if (ElementsInMolecule[pointer->type->Z] != 0) // this would indicate an error
713 ElementsInMolecule[pointer->type->Z]--; // decrease number of atom of this element
714 else
[58ed4a]715 DoeLog(1) && (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]716 if (ElementsInMolecule[pointer->type->Z] == 0) // was last atom of this element?
717 ElementCount--;
718 unlink(pointer);
719 return true;
[f3278b]720};
721
[cee0b57]722/** Removes every atom from molecule list.
723 * \return true - succeeded, false - atom not found in list
[14de469]724 */
[cee0b57]725bool molecule::CleanupMolecule()
[14de469]726{
[266237]727 return (cleanup(first,last) && cleanup(start,end));
[69eb71]728};
[14de469]729
[cee0b57]730/** Finds an atom specified by its continuous number.
731 * \param Nr number of atom withim molecule
732 * \return pointer to atom or NULL
[14de469]733 */
[cee0b57]734atom * molecule::FindAtom(int Nr) const{
735 atom * walker = find(&Nr, start,end);
736 if (walker != NULL) {
[e138de]737 //Log() << Verbose(0) << "Found Atom Nr. " << walker->nr << endl;
[cee0b57]738 return walker;
739 } else {
[a67d19]740 DoLog(0) && (Log() << Verbose(0) << "Atom not found in list." << endl);
[cee0b57]741 return NULL;
[042f82]742 }
[69eb71]743};
[14de469]744
[cee0b57]745/** Asks for atom number, and checks whether in list.
746 * \param *text question before entering
[a6b7fb]747 */
[cee0b57]748atom * molecule::AskAtom(string text)
[a6b7fb]749{
[cee0b57]750 int No;
751 atom *ion = NULL;
752 do {
[e138de]753 //Log() << Verbose(0) << "============Atom list==========================" << endl;
[cee0b57]754 //mol->Output((ofstream *)&cout);
[e138de]755 //Log() << Verbose(0) << "===============================================" << endl;
[a67d19]756 DoLog(0) && (Log() << Verbose(0) << text);
[cee0b57]757 cin >> No;
758 ion = this->FindAtom(No);
759 } while (ion == NULL);
760 return ion;
[a6b7fb]761};
762
[cee0b57]763/** Checks if given coordinates are within cell volume.
764 * \param *x array of coordinates
765 * \return true - is within, false - out of cell
[14de469]766 */
[cee0b57]767bool molecule::CheckBounds(const Vector *x) const
[14de469]768{
[5f612ee]769 double * const cell_size = World::getInstance().getDomain();
[cee0b57]770 bool result = true;
771 int j =-1;
772 for (int i=0;i<NDIM;i++) {
773 j += i+1;
[0a4f7f]774 result = result && ((x->at(i) >= 0) && (x->at(i) < cell_size[j]));
[042f82]775 }
[cee0b57]776 //return result;
777 return true; /// probably not gonna use the check no more
[69eb71]778};
[14de469]779
[cee0b57]780/** Prints molecule to *out.
781 * \param *out output stream
[14de469]782 */
[e138de]783bool molecule::Output(ofstream * const output)
[14de469]784{
[cee0b57]785 int ElementNo[MAX_ELEMENTS], AtomNo[MAX_ELEMENTS];
786 CountElements();
[042f82]787
[cee0b57]788 for (int i=0;i<MAX_ELEMENTS;++i) {
789 AtomNo[i] = 0;
790 ElementNo[i] = 0;
[042f82]791 }
[e138de]792 if (output == NULL) {
[cee0b57]793 return false;
794 } else {
[e138de]795 *output << "#Ion_TypeNr._Nr.R[0] R[1] R[2] MoveType (0 MoveIon, 1 FixedIon)" << endl;
[e9f8f9]796 SetIndexedArrayForEachAtomTo ( ElementNo, &element::Z, &AbsoluteValue, 1);
[cee0b57]797 int current=1;
798 for (int i=0;i<MAX_ELEMENTS;++i) {
799 if (ElementNo[i] == 1)
800 ElementNo[i] = current++;
801 }
[e138de]802 ActOnAllAtoms( &atom::OutputArrayIndexed, output, (const int *)ElementNo, (int *)AtomNo, (const char *) NULL );
[cee0b57]803 return true;
[042f82]804 }
[14de469]805};
806
[cee0b57]807/** Prints molecule with all atomic trajectory positions to *out.
808 * \param *out output stream
[21c017]809 */
[e138de]810bool molecule::OutputTrajectories(ofstream * const output)
[21c017]811{
[cee0b57]812 int ElementNo[MAX_ELEMENTS], AtomNo[MAX_ELEMENTS];
813 CountElements();
[21c017]814
[e138de]815 if (output == NULL) {
[cee0b57]816 return false;
817 } else {
818 for (int step = 0; step < MDSteps; step++) {
819 if (step == 0) {
[e138de]820 *output << "#Ion_TypeNr._Nr.R[0] R[1] R[2] MoveType (0 MoveIon, 1 FixedIon)" << endl;
[205ccd]821 } else {
[e138de]822 *output << "# ====== MD step " << step << " =========" << endl;
[cee0b57]823 }
824 for (int i=0;i<MAX_ELEMENTS;++i) {
825 AtomNo[i] = 0;
826 ElementNo[i] = 0;
[205ccd]827 }
[e9f8f9]828 SetIndexedArrayForEachAtomTo ( ElementNo, &element::Z, &AbsoluteValue, 1);
829 int current=1;
830 for (int i=0;i<MAX_ELEMENTS;++i) {
831 if (ElementNo[i] == 1)
832 ElementNo[i] = current++;
833 }
[e138de]834 ActOnAllAtoms( &atom::OutputTrajectory, output, (const int *)ElementNo, AtomNo, (const int)step );
[21c017]835 }
[cee0b57]836 return true;
[21c017]837 }
838};
839
[266237]840/** Outputs contents of each atom::ListOfBonds.
[cee0b57]841 * \param *out output stream
[14de469]842 */
[e138de]843void molecule::OutputListOfBonds() const
[14de469]844{
[a67d19]845 DoLog(2) && (Log() << Verbose(2) << endl << "From Contents of ListOfBonds, all non-hydrogen atoms:" << endl);
[e138de]846 ActOnAllAtoms (&atom::OutputBondOfAtom );
[a67d19]847 DoLog(0) && (Log() << Verbose(0) << endl);
[14de469]848};
849
[cee0b57]850/** Output of element before the actual coordination list.
851 * \param *out stream pointer
[14de469]852 */
[e138de]853bool molecule::Checkout(ofstream * const output) const
[14de469]854{
[e138de]855 return elemente->Checkout(output, ElementsInMolecule);
[6e9353]856};
857
[cee0b57]858/** Prints molecule with all its trajectories to *out as xyz file.
859 * \param *out output stream
[d7e30c]860 */
[e138de]861bool molecule::OutputTrajectoriesXYZ(ofstream * const output)
[d7e30c]862{
[cee0b57]863 time_t now;
[042f82]864
[e138de]865 if (output != NULL) {
[681a8a]866 now = time((time_t *)NULL); // Get the system time and put it into 'now' as 'calender time'
[cee0b57]867 for (int step=0;step<MDSteps;step++) {
[e138de]868 *output << AtomCount << "\n\tCreated by molecuilder, step " << step << ", on " << ctime(&now);
869 ActOnAllAtoms( &atom::OutputTrajectoryXYZ, output, step );
[042f82]870 }
[cee0b57]871 return true;
872 } else
873 return false;
[14de469]874};
875
[cee0b57]876/** Prints molecule to *out as xyz file.
877* \param *out output stream
[69eb71]878 */
[e138de]879bool molecule::OutputXYZ(ofstream * const output) const
[4aa03a]880{
[cee0b57]881 time_t now;
[042f82]882
[e138de]883 if (output != NULL) {
[23b830]884 now = time((time_t *)NULL); // Get the system time and put it into 'now' as 'calender time'
[e138de]885 *output << AtomCount << "\n\tCreated by molecuilder on " << ctime(&now);
886 ActOnAllAtoms( &atom::OutputXYZLine, output );
[042f82]887 return true;
[cee0b57]888 } else
889 return false;
890};
[4aa03a]891
[cee0b57]892/** Brings molecule::AtomCount and atom::*Name up-to-date.
[14de469]893 * \param *out output stream for debugging
894 */
[e138de]895void molecule::CountAtoms()
[14de469]896{
[cee0b57]897 int i = 0;
898 atom *Walker = start;
899 while (Walker->next != end) {
900 Walker = Walker->next;
901 i++;
902 }
903 if ((AtomCount == 0) || (i != AtomCount)) {
[a67d19]904 DoLog(3) && (Log() << Verbose(3) << "Mismatch in AtomCount " << AtomCount << " and recounted number " << i << ", renaming all." << endl);
[cee0b57]905 AtomCount = i;
[042f82]906
[cee0b57]907 // count NonHydrogen atoms and give each atom a unique name
908 if (AtomCount != 0) {
909 i=0;
910 NoNonHydrogen = 0;
911 Walker = start;
912 while (Walker->next != end) {
913 Walker = Walker->next;
914 Walker->nr = i; // update number in molecule (for easier referencing in FragmentMolecule lateron)
915 if (Walker->type->Z != 1) // count non-hydrogen atoms whilst at it
916 NoNonHydrogen++;
917 Free(&Walker->Name);
918 Walker->Name = Malloc<char>(6, "molecule::CountAtoms: *walker->Name");
919 sprintf(Walker->Name, "%2s%02d", Walker->type->symbol, Walker->nr+1);
[a67d19]920 DoLog(3) && (Log() << Verbose(3) << "Naming atom nr. " << Walker->nr << " " << Walker->Name << "." << endl);
[cee0b57]921 i++;
[042f82]922 }
[cee0b57]923 } else
[a67d19]924 DoLog(3) && (Log() << Verbose(3) << "AtomCount is still " << AtomCount << ", thus counting nothing." << endl);
[042f82]925 }
[cee0b57]926};
[042f82]927
[cee0b57]928/** Brings molecule::ElementCount and molecule::ElementsInMolecule up-to-date.
929 */
930void molecule::CountElements()
931{
[23b830]932 for(int i=MAX_ELEMENTS;i--;)
[cee0b57]933 ElementsInMolecule[i] = 0;
934 ElementCount = 0;
[042f82]935
[23b830]936 SetIndexedArrayForEachAtomTo ( ElementsInMolecule, &element::Z, &Increment, 1);
937
938 for(int i=MAX_ELEMENTS;i--;)
[cee0b57]939 ElementCount += (ElementsInMolecule[i] != 0 ? 1 : 0);
940};
[042f82]941
942
[cee0b57]943/** Counts necessary number of valence electrons and returns number and SpinType.
944 * \param configuration containing everything
945 */
946void molecule::CalculateOrbitals(class config &configuration)
947{
948 configuration.MaxPsiDouble = configuration.PsiMaxNoDown = configuration.PsiMaxNoUp = configuration.PsiType = 0;
949 for(int i=MAX_ELEMENTS;i--;) {
950 if (ElementsInMolecule[i] != 0) {
[e138de]951 //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]952 configuration.MaxPsiDouble += ElementsInMolecule[i]*((int)elemente->FindElement(i)->Valence);
[042f82]953 }
954 }
[cee0b57]955 configuration.PsiMaxNoDown = configuration.MaxPsiDouble/2 + (configuration.MaxPsiDouble % 2);
956 configuration.PsiMaxNoUp = configuration.MaxPsiDouble/2;
957 configuration.MaxPsiDouble /= 2;
958 configuration.PsiType = (configuration.PsiMaxNoDown == configuration.PsiMaxNoUp) ? 0 : 1;
959 if ((configuration.PsiType == 1) && (configuration.ProcPEPsi < 2)) {
960 configuration.ProcPEGamma /= 2;
961 configuration.ProcPEPsi *= 2;
962 } else {
963 configuration.ProcPEGamma *= configuration.ProcPEPsi;
964 configuration.ProcPEPsi = 1;
965 }
966 configuration.InitMaxMinStopStep = configuration.MaxMinStopStep = configuration.MaxPsiDouble;
[14de469]967};
968
969/** Determines whether two molecules actually contain the same atoms and coordination.
970 * \param *out output stream for debugging
971 * \param *OtherMolecule the molecule to compare this one to
972 * \param threshold upper limit of difference when comparing the coordination.
973 * \return NULL - not equal, otherwise an allocated (molecule::AtomCount) permutation map of the atom numbers (which corresponds to which)
974 */
[e138de]975int * molecule::IsEqualToWithinThreshold(molecule *OtherMolecule, double threshold)
[14de469]976{
[042f82]977 int flag;
978 double *Distances = NULL, *OtherDistances = NULL;
979 Vector CenterOfGravity, OtherCenterOfGravity;
980 size_t *PermMap = NULL, *OtherPermMap = NULL;
981 int *PermutationMap = NULL;
982 bool result = true; // status of comparison
983
[a67d19]984 DoLog(3) && (Log() << Verbose(3) << "Begin of IsEqualToWithinThreshold." << endl);
[042f82]985 /// first count both their atoms and elements and update lists thereby ...
[e138de]986 //Log() << Verbose(0) << "Counting atoms, updating list" << endl;
987 CountAtoms();
988 OtherMolecule->CountAtoms();
[042f82]989 CountElements();
990 OtherMolecule->CountElements();
991
992 /// ... and compare:
993 /// -# AtomCount
994 if (result) {
995 if (AtomCount != OtherMolecule->AtomCount) {
[a67d19]996 DoLog(4) && (Log() << Verbose(4) << "AtomCounts don't match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl);
[042f82]997 result = false;
[e138de]998 } else Log() << Verbose(4) << "AtomCounts match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
[042f82]999 }
1000 /// -# ElementCount
1001 if (result) {
1002 if (ElementCount != OtherMolecule->ElementCount) {
[a67d19]1003 DoLog(4) && (Log() << Verbose(4) << "ElementCount don't match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl);
[042f82]1004 result = false;
[e138de]1005 } else Log() << Verbose(4) << "ElementCount match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
[042f82]1006 }
1007 /// -# ElementsInMolecule
1008 if (result) {
1009 for (flag=MAX_ELEMENTS;flag--;) {
[e138de]1010 //Log() << Verbose(5) << "Element " << flag << ": " << ElementsInMolecule[flag] << " <-> " << OtherMolecule->ElementsInMolecule[flag] << "." << endl;
[042f82]1011 if (ElementsInMolecule[flag] != OtherMolecule->ElementsInMolecule[flag])
1012 break;
1013 }
1014 if (flag < MAX_ELEMENTS) {
[a67d19]1015 DoLog(4) && (Log() << Verbose(4) << "ElementsInMolecule don't match." << endl);
[042f82]1016 result = false;
[e138de]1017 } else Log() << Verbose(4) << "ElementsInMolecule match." << endl;
[042f82]1018 }
1019 /// then determine and compare center of gravity for each molecule ...
1020 if (result) {
[a67d19]1021 DoLog(5) && (Log() << Verbose(5) << "Calculating Centers of Gravity" << endl);
[437922]1022 DeterminePeriodicCenter(CenterOfGravity);
1023 OtherMolecule->DeterminePeriodicCenter(OtherCenterOfGravity);
[8cbb97]1024 DoLog(5) && (Log() << Verbose(5) << "Center of Gravity: " << CenterOfGravity << endl);
1025 DoLog(5) && (Log() << Verbose(5) << "Other Center of Gravity: " << OtherCenterOfGravity << endl);
[273382]1026 if (CenterOfGravity.DistanceSquared(OtherCenterOfGravity) > threshold*threshold) {
[a67d19]1027 DoLog(4) && (Log() << Verbose(4) << "Centers of gravity don't match." << endl);
[042f82]1028 result = false;
1029 }
1030 }
1031
1032 /// ... then make a list with the euclidian distance to this center for each atom of both molecules
1033 if (result) {
[a67d19]1034 DoLog(5) && (Log() << Verbose(5) << "Calculating distances" << endl);
[7218f8]1035 Distances = Calloc<double>(AtomCount, "molecule::IsEqualToWithinThreshold: Distances");
1036 OtherDistances = Calloc<double>(AtomCount, "molecule::IsEqualToWithinThreshold: OtherDistances");
[b453f9]1037 SetIndexedArrayForEachAtomTo ( Distances, &atom::nr, &atom::DistanceSquaredToVector, (const Vector &)CenterOfGravity);
1038 SetIndexedArrayForEachAtomTo ( OtherDistances, &atom::nr, &atom::DistanceSquaredToVector, (const Vector &)CenterOfGravity);
[042f82]1039
1040 /// ... sort each list (using heapsort (o(N log N)) from GSL)
[a67d19]1041 DoLog(5) && (Log() << Verbose(5) << "Sorting distances" << endl);
[7218f8]1042 PermMap = Calloc<size_t>(AtomCount, "molecule::IsEqualToWithinThreshold: *PermMap");
1043 OtherPermMap = Calloc<size_t>(AtomCount, "molecule::IsEqualToWithinThreshold: *OtherPermMap");
[042f82]1044 gsl_heapsort_index (PermMap, Distances, AtomCount, sizeof(double), CompareDoubles);
1045 gsl_heapsort_index (OtherPermMap, OtherDistances, AtomCount, sizeof(double), CompareDoubles);
[7218f8]1046 PermutationMap = Calloc<int>(AtomCount, "molecule::IsEqualToWithinThreshold: *PermutationMap");
[a67d19]1047 DoLog(5) && (Log() << Verbose(5) << "Combining Permutation Maps" << endl);
[042f82]1048 for(int i=AtomCount;i--;)
1049 PermutationMap[PermMap[i]] = (int) OtherPermMap[i];
1050
[29812d]1051 /// ... and compare them step by step, whether the difference is individually(!) below \a threshold for all
[a67d19]1052 DoLog(4) && (Log() << Verbose(4) << "Comparing distances" << endl);
[042f82]1053 flag = 0;
1054 for (int i=0;i<AtomCount;i++) {
[a67d19]1055 DoLog(5) && (Log() << Verbose(5) << "Distances squared: |" << Distances[PermMap[i]] << " - " << OtherDistances[OtherPermMap[i]] << "| = " << fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) << " ?<? " << threshold << endl);
[042f82]1056 if (fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) > threshold*threshold)
1057 flag = 1;
1058 }
1059
[29812d]1060 // free memory
1061 Free(&PermMap);
1062 Free(&OtherPermMap);
1063 Free(&Distances);
1064 Free(&OtherDistances);
[042f82]1065 if (flag) { // if not equal
[29812d]1066 Free(&PermutationMap);
[042f82]1067 result = false;
1068 }
1069 }
1070 /// return pointer to map if all distances were below \a threshold
[a67d19]1071 DoLog(3) && (Log() << Verbose(3) << "End of IsEqualToWithinThreshold." << endl);
[042f82]1072 if (result) {
[a67d19]1073 DoLog(3) && (Log() << Verbose(3) << "Result: Equal." << endl);
[042f82]1074 return PermutationMap;
1075 } else {
[a67d19]1076 DoLog(3) && (Log() << Verbose(3) << "Result: Not equal." << endl);
[042f82]1077 return NULL;
1078 }
[14de469]1079};
1080
1081/** Returns an index map for two father-son-molecules.
1082 * The map tells which atom in this molecule corresponds to which one in the other molecul with their fathers.
1083 * \param *out output stream for debugging
1084 * \param *OtherMolecule corresponding molecule with fathers
1085 * \return allocated map of size molecule::AtomCount with map
1086 * \todo make this with a good sort O(n), not O(n^2)
1087 */
[e138de]1088int * molecule::GetFatherSonAtomicMap(molecule *OtherMolecule)
[14de469]1089{
[042f82]1090 atom *Walker = NULL, *OtherWalker = NULL;
[a67d19]1091 DoLog(3) && (Log() << Verbose(3) << "Begin of GetFatherAtomicMap." << endl);
[29812d]1092 int *AtomicMap = Malloc<int>(AtomCount, "molecule::GetAtomicMap: *AtomicMap");
[042f82]1093 for (int i=AtomCount;i--;)
1094 AtomicMap[i] = -1;
1095 if (OtherMolecule == this) { // same molecule
1096 for (int i=AtomCount;i--;) // no need as -1 means already that there is trivial correspondence
1097 AtomicMap[i] = i;
[a67d19]1098 DoLog(4) && (Log() << Verbose(4) << "Map is trivial." << endl);
[042f82]1099 } else {
[a67d19]1100 DoLog(4) && (Log() << Verbose(4) << "Map is ");
[042f82]1101 Walker = start;
1102 while (Walker->next != end) {
1103 Walker = Walker->next;
1104 if (Walker->father == NULL) {
1105 AtomicMap[Walker->nr] = -2;
1106 } else {
1107 OtherWalker = OtherMolecule->start;
1108 while (OtherWalker->next != OtherMolecule->end) {
1109 OtherWalker = OtherWalker->next;
1110 //for (int i=0;i<AtomCount;i++) { // search atom
1111 //for (int j=0;j<OtherMolecule->AtomCount;j++) {
[e138de]1112 //Log() << Verbose(4) << "Comparing father " << Walker->father << " with the other one " << OtherWalker->father << "." << endl;
[042f82]1113 if (Walker->father == OtherWalker)
1114 AtomicMap[Walker->nr] = OtherWalker->nr;
1115 }
1116 }
[a67d19]1117 DoLog(0) && (Log() << Verbose(0) << AtomicMap[Walker->nr] << "\t");
[042f82]1118 }
[a67d19]1119 DoLog(0) && (Log() << Verbose(0) << endl);
[042f82]1120 }
[a67d19]1121 DoLog(3) && (Log() << Verbose(3) << "End of GetFatherAtomicMap." << endl);
[042f82]1122 return AtomicMap;
[14de469]1123};
1124
[698b04]1125/** Stores the temperature evaluated from velocities in molecule::Trajectories.
1126 * We simply use the formula equivaleting temperature and kinetic energy:
1127 * \f$k_B T = \sum_i m_i v_i^2\f$
[e138de]1128 * \param *output output stream of temperature file
[698b04]1129 * \param startstep first MD step in molecule::Trajectories
1130 * \param endstep last plus one MD step in molecule::Trajectories
1131 * \return file written (true), failure on writing file (false)
[69eb71]1132 */
[e138de]1133bool molecule::OutputTemperatureFromTrajectories(ofstream * const output, int startstep, int endstep)
[698b04]1134{
[042f82]1135 double temperature;
1136 // test stream
1137 if (output == NULL)
1138 return false;
1139 else
1140 *output << "# Step Temperature [K] Temperature [a.u.]" << endl;
1141 for (int step=startstep;step < endstep; step++) { // loop over all time steps
1142 temperature = 0.;
[4455f4]1143 ActOnAllAtoms( &TrajectoryParticle::AddKineticToTemperature, &temperature, step);
[042f82]1144 *output << step << "\t" << temperature*AtomicEnergyToKelvin << "\t" << temperature << endl;
1145 }
1146 return true;
[65de9b]1147};
[4a7776a]1148
[b453f9]1149void molecule::SetIndexedArrayForEachAtomTo ( atom **array, int ParticleInfo::*index) const
[4a7776a]1150{
1151 atom *Walker = start;
1152 while (Walker->next != end) {
1153 Walker = Walker->next;
1154 array[(Walker->*index)] = Walker;
1155 }
1156};
[c68025]1157
1158void molecule::flipActiveFlag(){
1159 ActiveFlag = !ActiveFlag;
1160}
Note: See TracBrowser for help on using the repository browser.