source: src/molecule.cpp@ 15b670

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 15b670 was e08c46, checked in by Frederik Heber <heber@…>, 15 years ago

Removed molecule::first, molecule::last.

  • molecule does not have a chained list of bonds.
  • we have to go through atoms and its bonds, by checking (*BondRunner)->leftatom against (*AtomRunner) we exclude the other half.
  • first,last were present in only a few structures.
  • new functions:
    • molecule::hasBondStructure() - replaces first->next != last construct
    • molecule::CountBonds() - replaces first->next->next == last (i.e. one bond present) and alikes.

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

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