source: src/Fragmentation/Exporters/SaturatedFragment.cpp@ 945797

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator 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_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions 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 GeometryObjects Gui_displays_atomic_force_velocity IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since 945797 was fac58f, checked in by Frederik Heber <heber@…>, 10 years ago

Converted FormatParser::save() to using vector of const atom ptrs.

  • required to change all save() functions in all parsers.
  • Property mode set to 100644
File size: 24.8 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 University of Bonn. All rights reserved.
5 * Copyright (C) 2013 Frederik Heber. All rights reserved.
6 *
7 *
8 * This file is part of MoleCuilder.
9 *
10 * MoleCuilder is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * MoleCuilder is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24/*
25 * SaturatedFragment.cpp
26 *
27 * Created on: Mar 3, 2013
28 * Author: heber
29 */
30
31// include config.h
32#ifdef HAVE_CONFIG_H
33#include <config.h>
34#endif
35
36#include "CodePatterns/MemDebug.hpp"
37
38#include "SaturatedFragment.hpp"
39
40#include <cmath>
41#include <iostream>
42
43#include "CodePatterns/Assert.hpp"
44#include "CodePatterns/Log.hpp"
45
46#include "LinearAlgebra/Exceptions.hpp"
47#include "LinearAlgebra/Plane.hpp"
48#include "LinearAlgebra/RealSpaceMatrix.hpp"
49#include "LinearAlgebra/Vector.hpp"
50
51#include "Atom/atom.hpp"
52#include "Bond/bond.hpp"
53#include "config.hpp"
54#include "Descriptors/AtomIdDescriptor.hpp"
55#include "Fragmentation/Exporters/HydrogenPool.hpp"
56#include "Fragmentation/HydrogenSaturation_enum.hpp"
57#include "Graph/BondGraph.hpp"
58#include "World.hpp"
59
60SaturatedFragment::SaturatedFragment(
61 const KeySet &_set,
62 KeySetsInUse_t &_container,
63 HydrogenPool &_hydrogens,
64 const enum HydrogenTreatment _treatment,
65 const enum HydrogenSaturation _saturation,
66 const GlobalSaturationPositions_t &_globalsaturationpositions) :
67 container(_container),
68 set(_set),
69 hydrogens(_hydrogens),
70 FullMolecule(set),
71 treatment(_treatment),
72 saturation(_saturation)
73{
74 // add to in-use container
75 ASSERT( container.find(set) == container.end(),
76 "SaturatedFragment::SaturatedFragment() - the set "
77 +toString(set)+" is already marked as in use.");
78 container.insert(set);
79
80 // prepare saturation hydrogens, either using global information
81 // or if not given, local information (created in the function)
82 if (_globalsaturationpositions.empty())
83 saturate();
84 else
85 saturate(_globalsaturationpositions);
86}
87
88SaturatedFragment::~SaturatedFragment()
89{
90 // release all saturation hydrogens if present
91 for (KeySet::iterator iter = SaturationHydrogens.begin();
92 !SaturationHydrogens.empty();
93 iter = SaturationHydrogens.begin()) {
94 hydrogens.releaseHydrogen(*iter);
95 SaturationHydrogens.erase(iter);
96 }
97
98 // remove ourselves from in-use container
99 KeySetsInUse_t::iterator iter = container.find(set);
100 ASSERT( container.find(set) != container.end(),
101 "SaturatedFragment::SaturatedFragment() - the set "
102 +toString(set)+" is not marked as in use.");
103 container.erase(iter);
104}
105
106typedef std::vector<atom *> atoms_t;
107
108atoms_t gatherAllAtoms(const KeySet &_FullMolecule)
109{
110 atoms_t atoms;
111 for (KeySet::const_iterator iter = _FullMolecule.begin();
112 iter != _FullMolecule.end();
113 ++iter) {
114 atom * const Walker = World::getInstance().getAtom(AtomById(*iter));
115 ASSERT( Walker != NULL,
116 "gatherAllAtoms() - id "
117 +toString(*iter)+" is unknown to World.");
118 atoms.push_back(Walker);
119 }
120
121 return atoms;
122}
123
124typedef std::map<atom *, BondList > CutBonds_t;
125
126CutBonds_t gatherCutBonds(
127 const atoms_t &_atoms,
128 const KeySet &_set,
129 const enum HydrogenTreatment _treatment)
130{
131 // bool LonelyFlag = false;
132 CutBonds_t CutBonds;
133 for (atoms_t::const_iterator iter = _atoms.begin();
134 iter != _atoms.end();
135 ++iter) {
136 atom * const Walker = *iter;
137
138 // go through all bonds
139 const BondList& ListOfBonds = Walker->getListOfBonds();
140 for (BondList::const_iterator BondRunner = ListOfBonds.begin();
141 BondRunner != ListOfBonds.end();
142 ++BondRunner) {
143 atom * const OtherWalker = (*BondRunner)->GetOtherAtom(Walker);
144 // if other atom is in key set or is a specially treated hydrogen
145 if (_set.find(OtherWalker->getId()) != _set.end()) {
146 LOG(4, "DEBUG: Walker " << *Walker << " is bound to " << *OtherWalker << ".");
147 } else if ((_treatment == ExcludeHydrogen)
148 && (OtherWalker->getElementNo() == (atomicNumber_t)1)) {
149 LOG(4, "DEBUG: Walker " << *Walker << " is bound to specially treated hydrogen " <<
150 *OtherWalker << ".");
151 } else {
152 LOG(4, "DEBUG: Walker " << *Walker << " is bound to "
153 << *OtherWalker << ", who is not in this fragment molecule.");
154 if (CutBonds.count(Walker) == 0)
155 CutBonds.insert( std::make_pair(Walker, BondList() ));
156 CutBonds[Walker].push_back(*BondRunner);
157 }
158 }
159 }
160
161 return CutBonds;
162}
163
164typedef std::vector<atomId_t> atomids_t;
165
166atomids_t gatherPresentExcludedHydrogens(
167 const atoms_t &_atoms,
168 const KeySet &_set,
169 const enum HydrogenTreatment _treatment)
170{
171 // bool LonelyFlag = false;
172 atomids_t ExcludedHydrogens;
173 for (atoms_t::const_iterator iter = _atoms.begin();
174 iter != _atoms.end();
175 ++iter) {
176 atom * const Walker = *iter;
177
178 // go through all bonds
179 const BondList& ListOfBonds = Walker->getListOfBonds();
180 for (BondList::const_iterator BondRunner = ListOfBonds.begin();
181 BondRunner != ListOfBonds.end();
182 ++BondRunner) {
183 atom * const OtherWalker = (*BondRunner)->GetOtherAtom(Walker);
184 // if other atom is in key set or is a specially treated hydrogen
185 if (_set.find(OtherWalker->getId()) != _set.end()) {
186 LOG(6, "DEBUG: OtherWalker " << *OtherWalker << " is in set already.");
187 } else if ((_treatment == ExcludeHydrogen)
188 && (OtherWalker->getElementNo() == (atomicNumber_t)1)) {
189 LOG(5, "DEBUG: Adding excluded hydrogen OtherWalker " << *OtherWalker << ".");
190 ExcludedHydrogens.push_back(OtherWalker->getId());
191 } else {
192 LOG(6, "DEBUG: OtherWalker " << *Walker << " is not in this fragment molecule and no hydrogen.");
193 }
194 }
195 }
196
197 return ExcludedHydrogens;
198}
199
200void SaturatedFragment::saturate()
201{
202 // so far, we just have a set of keys. Hence, convert to atom refs
203 // and gather all atoms in a vector
204 std::vector<atom *> atoms = gatherAllAtoms(FullMolecule);
205
206 // go through each atom of the fragment and gather all cut bonds in list
207 CutBonds_t CutBonds = gatherCutBonds(atoms, set, treatment);
208
209 // add excluded hydrogens to FullMolecule if treated specially
210 if (treatment == ExcludeHydrogen) {
211 atomids_t ExcludedHydrogens = gatherPresentExcludedHydrogens(atoms, set, treatment);
212 FullMolecule.insert(ExcludedHydrogens.begin(), ExcludedHydrogens.end());
213 }
214
215 // go through all cut bonds and replace with a hydrogen
216 for (CutBonds_t::const_iterator atomiter = CutBonds.begin();
217 atomiter != CutBonds.end(); ++atomiter) {
218 atom * const Walker = atomiter->first;
219 if (!saturateAtom(Walker, atomiter->second))
220 exit(1);
221 }
222}
223
224void SaturatedFragment::saturate(
225 const GlobalSaturationPositions_t &_globalsaturationpositions)
226{
227 // so far, we just have a set of keys. Hence, convert to atom refs
228 // and gather all atoms in a vector
229 std::vector<atom *> atoms = gatherAllAtoms(FullMolecule);
230
231 // go through each atom of the fragment and gather all cut bonds in list
232 CutBonds_t CutBonds = gatherCutBonds(atoms, set, treatment);
233
234 // add excluded hydrogens to FullMolecule if treated specially
235 if (treatment == ExcludeHydrogen) {
236 atomids_t ExcludedHydrogens = gatherPresentExcludedHydrogens(atoms, set, treatment);
237 FullMolecule.insert(ExcludedHydrogens.begin(), ExcludedHydrogens.end());
238 }
239
240 // go through all cut bonds and replace with a hydrogen
241 if (saturation == DoSaturate) {
242 for (CutBonds_t::const_iterator atomiter = CutBonds.begin();
243 atomiter != CutBonds.end(); ++atomiter) {
244 atom * const Walker = atomiter->first;
245 LOG(4, "DEBUG: We are now saturating dangling bonds of " << *Walker);
246
247 // gather set of positions for this atom from global map
248 GlobalSaturationPositions_t::const_iterator mapiter =
249 _globalsaturationpositions.find(Walker->getId());
250 ASSERT( mapiter != _globalsaturationpositions.end(),
251 "SaturatedFragment::saturate() - no global information for "
252 +toString(*Walker));
253 const SaturationsPositionsPerNeighbor_t &saturationpositions =
254 mapiter->second;
255
256 // go through all cut bonds for this atom
257 for (BondList::const_iterator bonditer = atomiter->second.begin();
258 bonditer != atomiter->second.end(); ++bonditer) {
259 atom * const OtherWalker = (*bonditer)->GetOtherAtom(Walker);
260
261 // get positions from global map
262 SaturationsPositionsPerNeighbor_t::const_iterator positionsiter =
263 saturationpositions.find(OtherWalker->getId());
264 ASSERT(positionsiter != saturationpositions.end(),
265 "SaturatedFragment::saturate() - no information on bond neighbor "
266 +toString(*OtherWalker)+" to atom "+toString(*Walker));
267 ASSERT(!positionsiter->second.empty(),
268 "SaturatedFragment::saturate() - no positions for saturating bond to"
269 +toString(*OtherWalker)+" to atom "+toString(*Walker));
270
271// // get typical bond distance from elements database
272// double BondDistance = Walker->getType()->getHBondDistance(positionsiter->second.size()-1);
273// if (BondDistance < 0.) {
274// ELOG(2, "saturateAtoms() - no typical hydrogen bond distance of degree "
275// +toString(positionsiter->second.size())+" for element "
276// +toString(Walker->getType()->getName()));
277// // try bond degree 1 distance
278// BondDistance = Walker->getType()->getHBondDistance(1-1);
279// if (BondDistance < 0.) {
280// ELOG(1, "saturateAtoms() - no typical hydrogen bond distance for element "
281// +toString(Walker->getType()->getName()));
282// BondDistance = 1.;
283// }
284// }
285
286 // place hydrogen at each point
287 LOG(4, "DEBUG: Places to saturate for atom " << *OtherWalker
288 << " are " << positionsiter->second);
289 atom * const father = Walker;
290 for (SaturationsPositions_t::const_iterator positer = positionsiter->second.begin();
291 positer != positionsiter->second.end(); ++positer) {
292 const atom& hydrogen =
293 setHydrogenReplacement(Walker, *positer, 1., father);
294 FullMolecule.insert(hydrogen.getId());
295 }
296 }
297 }
298 } else
299 LOG(3, "INFO: We are not saturating cut bonds.");
300}
301
302const atom& SaturatedFragment::setHydrogenReplacement(
303 const atom * const _OwnerAtom,
304 const Vector &_position,
305 const double _distance,
306 atom * const _father)
307{
308 atom * const _atom = hydrogens.leaseHydrogen(); // new atom
309 _atom->setPosition( _OwnerAtom->getPosition() + _distance * _position );
310 // always set as fixed ion (not moving during molecular dynamics simulation)
311 _atom->setFixedIon(true);
312 // if we replace hydrogen, we mark it as our father, otherwise we are just an added hydrogen with no father
313 _atom->setFather(_father);
314 SaturationHydrogens.insert(_atom->getId());
315
316 return *_atom;
317}
318
319bool SaturatedFragment::saturateAtom(
320 atom * const _atom,
321 const BondList &_cutbonds)
322{
323 // go through each bond and replace
324 for (BondList::const_iterator bonditer = _cutbonds.begin();
325 bonditer != _cutbonds.end(); ++bonditer) {
326 atom * const OtherWalker = (*bonditer)->GetOtherAtom(_atom);
327 if (!AddHydrogenReplacementAtom(
328 (*bonditer),
329 _atom,
330 OtherWalker,
331 World::getInstance().getConfig()->IsAngstroem == 1))
332 return false;
333 }
334 return true;
335}
336
337bool SaturatedFragment::OutputConfig(
338 std::ostream &out,
339 const ParserTypes _type) const
340{
341 // gather all atoms in a vector
342 std::vector<const atom *> atoms;
343 for (KeySet::const_iterator iter = FullMolecule.begin();
344 iter != FullMolecule.end();
345 ++iter) {
346 const atom * const Walker = const_cast<const World &>(World::getInstance()).
347 getAtom(AtomById(*iter));
348 ASSERT( Walker != NULL,
349 "SaturatedFragment::OutputConfig() - id "
350 +toString(*iter)+" is unknown to World.");
351 atoms.push_back(Walker);
352 }
353
354 // TODO: ScanForPeriodicCorrection() is missing so far!
355 // note however that this is not straight-forward for the following reasons:
356 // - we do not copy all atoms anymore, hence we are forced to shift the real
357 // atoms hither and back again
358 // - we use a long-range potential that supports periodic boundary conditions.
359 // Hence, there we would like the original configuration (split through the
360 // the periodic boundaries). Otherwise, we would have to shift (and probably
361 // interpolate) the potential with OBCs applying.
362
363 // list atoms in fragment for debugging
364 {
365 std::stringstream output;
366 output << "INFO: Contained atoms: ";
367 for (std::vector<const atom *>::const_iterator iter = atoms.begin();
368 iter != atoms.end(); ++iter) {
369 output << (*iter)->getName() << " ";
370 }
371 LOG(3, output.str());
372 }
373
374 // store to stream via FragmentParser
375 const bool intermediateResult =
376 FormatParserStorage::getInstance().save(
377 out,
378 FormatParserStorage::getInstance().getSuffixFromType(_type),
379 atoms);
380
381 return intermediateResult;
382}
383
384atom * const SaturatedFragment::getHydrogenReplacement(atom * const replacement)
385{
386 atom * const _atom = hydrogens.leaseHydrogen(); // new atom
387 _atom->setAtomicVelocity(replacement->getAtomicVelocity()); // copy velocity
388 _atom->setFixedIon(replacement->getFixedIon());
389 // if we replace hydrogen, we mark it as our father, otherwise we are just an added hydrogen with no father
390 _atom->setFather(replacement);
391 SaturationHydrogens.insert(_atom->getId());
392 return _atom;
393}
394
395bool SaturatedFragment::AddHydrogenReplacementAtom(
396 bond::ptr TopBond,
397 atom *Origin,
398 atom *Replacement,
399 bool IsAngstroem)
400{
401// Info info(__func__);
402 bool AllWentWell = true; // flag gathering the boolean return value of molecule::AddAtom and other functions, as return value on exit
403 double bondlength; // bond length of the bond to be replaced/cut
404 double bondangle; // bond angle of the bond to be replaced/cut
405 double BondRescale; // rescale value for the hydrogen bond length
406 bond::ptr FirstBond;
407 bond::ptr SecondBond; // Other bonds in double bond case to determine "other" plane
408 atom *FirstOtherAtom = NULL, *SecondOtherAtom = NULL, *ThirdOtherAtom = NULL; // pointer to hydrogen atoms to be added
409 double b,l,d,f,g, alpha, factors[NDIM]; // hold temporary values in triple bond case for coordination determination
410 Vector Orthovector1, Orthovector2; // temporary vectors in coordination construction
411 Vector InBondvector; // vector in direction of *Bond
412 const RealSpaceMatrix &matrix = World::getInstance().getDomain().getM();
413 bond::ptr Binder;
414
415 // create vector in direction of bond
416 InBondvector = Replacement->getPosition() - Origin->getPosition();
417 bondlength = InBondvector.Norm();
418
419 // is greater than typical bond distance? Then we have to correct periodically
420 // the problem is not the H being out of the box, but InBondvector have the wrong direction
421 // due to Replacement or Origin being on the wrong side!
422 const BondGraph * const BG = World::getInstance().getBondGraph();
423 const range<double> MinMaxBondDistance(
424 BG->getMinMaxDistance(Origin,Replacement));
425 if (!MinMaxBondDistance.isInRange(bondlength)) {
426// LOG(4, "InBondvector is: " << InBondvector << ".");
427 Orthovector1.Zero();
428 for (int i=NDIM;i--;) {
429 l = Replacement->at(i) - Origin->at(i);
430 if (fabs(l) > MinMaxBondDistance.last) { // is component greater than bond distance (check against min not useful here)
431 Orthovector1[i] = (l < 0) ? -1. : +1.;
432 } // (signs are correct, was tested!)
433 }
434 Orthovector1 *= matrix;
435 InBondvector -= Orthovector1; // subtract just the additional translation
436 bondlength = InBondvector.Norm();
437// LOG(4, "INFO: Corrected InBondvector is now: " << InBondvector << ".");
438 } // periodic correction finished
439
440 InBondvector.Normalize();
441 // get typical bond length and store as scale factor for later
442 ASSERT(Origin->getType() != NULL,
443 "SaturatedFragment::AddHydrogenReplacementAtom() - element of Origin is not given.");
444 BondRescale = Origin->getType()->getHBondDistance(TopBond->getDegree()-1);
445 if (BondRescale == -1) {
446 ELOG(1, "There is no typical hydrogen bond distance in replacing bond (" << Origin->getName() << "<->" << Replacement->getName() << ") of degree " << TopBond->getDegree() << "!");
447 BondRescale = Origin->getType()->getHBondDistance(TopBond->getDegree());
448 if (BondRescale == -1) {
449 ELOG(1, "There is no typical hydrogen bond distance in replacing bond (" << Origin->getName() << "<->" << Replacement->getName() << ") of any degree!");
450 return false;
451 BondRescale = bondlength;
452 }
453 } else {
454 if (!IsAngstroem)
455 BondRescale /= (1.*AtomicLengthToAngstroem);
456 }
457
458 // discern single, double and triple bonds
459 switch(TopBond->getDegree()) {
460 case 1:
461 // check whether replacement has been an excluded hydrogen
462 if (Replacement->getType()->getAtomicNumber() == HydrogenPool::HYDROGEN) { // neither rescale nor replace if it's already hydrogen
463 FirstOtherAtom = Replacement;
464 BondRescale = bondlength;
465 } else {
466 FirstOtherAtom = getHydrogenReplacement(Replacement);
467 InBondvector *= BondRescale; // rescale the distance vector to Hydrogen bond length
468 FirstOtherAtom->setPosition(Origin->getPosition() + InBondvector); // set coordination to origin and add distance vector to replacement atom
469 }
470 FullMolecule.insert(FirstOtherAtom->getId());
471// LOG(4, "INFO: Added " << *FirstOtherAtom << " at: " << FirstOtherAtom->x << ".");
472 break;
473 case 2:
474 {
475 // determine two other bonds (warning if there are more than two other) plus valence sanity check
476 const BondList& ListOfBonds = Origin->getListOfBonds();
477 for (BondList::const_iterator Runner = ListOfBonds.begin();
478 Runner != ListOfBonds.end();
479 ++Runner) {
480 if ((*Runner) != TopBond) {
481 if (FirstBond == NULL) {
482 FirstBond = (*Runner);
483 FirstOtherAtom = (*Runner)->GetOtherAtom(Origin);
484 } else if (SecondBond == NULL) {
485 SecondBond = (*Runner);
486 SecondOtherAtom = (*Runner)->GetOtherAtom(Origin);
487 } else {
488 ELOG(2, "Detected more than four bonds for atom " << Origin->getName());
489 }
490 }
491 }
492 }
493 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)
494 SecondBond = TopBond;
495 SecondOtherAtom = Replacement;
496 }
497 if (FirstOtherAtom != NULL) { // then we just have this double bond and the plane does not matter at all
498// LOG(3, "Regarding the double bond (" << Origin->Name << "<->" << Replacement->Name << ") to be constructed: Taking " << FirstOtherAtom->Name << " and " << SecondOtherAtom->Name << " along with " << Origin->Name << " to determine orthogonal plane.");
499
500 // determine the plane of these two with the *origin
501 try {
502 Orthovector1 = Plane(Origin->getPosition(), FirstOtherAtom->getPosition(), SecondOtherAtom->getPosition()).getNormal();
503 }
504 catch(LinearDependenceException &excp){
505 LOG(0, boost::diagnostic_information(excp));
506 // TODO: figure out what to do with the Orthovector in this case
507 AllWentWell = false;
508 }
509 } else {
510 Orthovector1.GetOneNormalVector(InBondvector);
511 }
512 //LOG(3, "INFO: Orthovector1: " << Orthovector1 << ".");
513 // orthogonal vector and bond vector between origin and replacement form the new plane
514 Orthovector1.MakeNormalTo(InBondvector);
515 Orthovector1.Normalize();
516 //LOG(3, "ReScaleCheck: " << Orthovector1.Norm() << " and " << InBondvector.Norm() << ".");
517
518 // create the two Hydrogens ...
519 FirstOtherAtom = getHydrogenReplacement(Replacement);
520 SecondOtherAtom = getHydrogenReplacement(Replacement);
521 FullMolecule.insert(FirstOtherAtom->getId());
522 FullMolecule.insert(SecondOtherAtom->getId());
523 bondangle = Origin->getType()->getHBondAngle(1);
524 if (bondangle == -1) {
525 ELOG(1, "There is no typical hydrogen bond angle in replacing bond (" << Origin->getName() << "<->" << Replacement->getName() << ") of degree " << TopBond->getDegree() << "!");
526 return false;
527 bondangle = 0;
528 }
529 bondangle *= M_PI/180./2.;
530// LOG(3, "INFO: ReScaleCheck: InBondvector " << InBondvector << ", " << Orthovector1 << ".");
531// LOG(3, "Half the bond angle is " << bondangle << ", sin and cos of it: " << sin(bondangle) << ", " << cos(bondangle));
532 FirstOtherAtom->Zero();
533 SecondOtherAtom->Zero();
534 for(int i=NDIM;i--;) { // rotate by half the bond angle in both directions (InBondvector is bondangle = 0 direction)
535 FirstOtherAtom->set(i, InBondvector[i] * cos(bondangle) + Orthovector1[i] * (sin(bondangle)));
536 SecondOtherAtom->set(i, InBondvector[i] * cos(bondangle) + Orthovector1[i] * (-sin(bondangle)));
537 }
538 FirstOtherAtom->Scale(BondRescale); // rescale by correct BondDistance
539 SecondOtherAtom->Scale(BondRescale);
540 //LOG(3, "ReScaleCheck: " << FirstOtherAtom->x.Norm() << " and " << SecondOtherAtom->x.Norm() << ".");
541 *FirstOtherAtom += Origin->getPosition();
542 *SecondOtherAtom += Origin->getPosition();
543 // ... and add to molecule
544// LOG(4, "INFO: Added " << *FirstOtherAtom << " at: " << FirstOtherAtom->x << ".");
545// LOG(4, "INFO: Added " << *SecondOtherAtom << " at: " << SecondOtherAtom->x << ".");
546 break;
547 case 3:
548 // take the "usual" tetraoidal angle and add the three Hydrogen in direction of the bond (height of the tetraoid)
549 FirstOtherAtom = getHydrogenReplacement(Replacement);
550 SecondOtherAtom = getHydrogenReplacement(Replacement);
551 ThirdOtherAtom = getHydrogenReplacement(Replacement);
552 FullMolecule.insert(FirstOtherAtom->getId());
553 FullMolecule.insert(SecondOtherAtom->getId());
554 FullMolecule.insert(ThirdOtherAtom->getId());
555
556 // we need to vectors orthonormal the InBondvector
557 AllWentWell = AllWentWell && Orthovector1.GetOneNormalVector(InBondvector);
558// LOG(3, "INFO: Orthovector1: " << Orthovector1 << ".");
559 try{
560 Orthovector2 = Plane(InBondvector, Orthovector1,0).getNormal();
561 }
562 catch(LinearDependenceException &excp) {
563 LOG(0, boost::diagnostic_information(excp));
564 AllWentWell = false;
565 }
566// LOG(3, "INFO: Orthovector2: " << Orthovector2 << ".")
567
568 // create correct coordination for the three atoms
569 alpha = (Origin->getType()->getHBondAngle(2))/180.*M_PI/2.; // retrieve triple bond angle from database
570 l = BondRescale; // desired bond length
571 b = 2.*l*sin(alpha); // base length of isosceles triangle
572 d = l*sqrt(cos(alpha)*cos(alpha) - sin(alpha)*sin(alpha)/3.); // length for InBondvector
573 f = b/sqrt(3.); // length for Orthvector1
574 g = b/2.; // length for Orthvector2
575// LOG(3, "Bond length and half-angle: " << l << ", " << alpha << "\t (b,d,f,g) = " << b << ", " << d << ", " << f << ", " << g << ", ");
576// LOG(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));
577 factors[0] = d;
578 factors[1] = f;
579 factors[2] = 0.;
580 FirstOtherAtom->LinearCombinationOfVectors(InBondvector, Orthovector1, Orthovector2, factors);
581 factors[1] = -0.5*f;
582 factors[2] = g;
583 SecondOtherAtom->LinearCombinationOfVectors(InBondvector, Orthovector1, Orthovector2, factors);
584 factors[2] = -g;
585 ThirdOtherAtom->LinearCombinationOfVectors(InBondvector, Orthovector1, Orthovector2, factors);
586
587 // rescale each to correct BondDistance
588// FirstOtherAtom->x.Scale(&BondRescale);
589// SecondOtherAtom->x.Scale(&BondRescale);
590// ThirdOtherAtom->x.Scale(&BondRescale);
591
592 // and relative to *origin atom
593 *FirstOtherAtom += Origin->getPosition();
594 *SecondOtherAtom += Origin->getPosition();
595 *ThirdOtherAtom += Origin->getPosition();
596
597 // ... and add to molecule
598// LOG(4, "INFO: Added " << *FirstOtherAtom << " at: " << FirstOtherAtom->x << ".");
599// LOG(4, "INFO: Added " << *SecondOtherAtom << " at: " << SecondOtherAtom->x << ".");
600// LOG(4, "INFO: Added " << *ThirdOtherAtom << " at: " << ThirdOtherAtom->x << ".");
601 break;
602 default:
603 ELOG(1, "BondDegree does not state single, double or triple bond!");
604 AllWentWell = false;
605 break;
606 }
607
608 return AllWentWell;
609};
Note: See TracBrowser for help on using the repository browser.