source: src/molecule.cpp@ 42af9e

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

Removed all Malloc/Calloc/ReAlloc (&Free) and replaced by new and delete/delete[].

Due to the new MemDebug framework there is no need (or even unnecessary/unwanted competition between it and) for the MemoryAllocator and ..UsageObserver anymore.
They can however still be used with c codes such as pcp and alikes.

In Molecuilder lots of glibc corruptions arose and the C-like syntax make it generally harder to get allocation and deallocation straight.

Signed-off-by: Frederik Heber <heber@…>

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