source: src/Graph/BondGraph.hpp@ db7e6d

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 Candidate_v1.7.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 db7e6d was db7e6d, checked in by Frederik Heber <heber@…>, 14 years ago

BondedParticle:: register and unregister are private.

  • adding and removing bonds is possible via addBond(), removeBond().
  • this wat we encapsulate the register and unregister and make sure that never a lone bond remains at one side.
  • adapted:
  • Register and UnregisterBond are OBSERVEd.
  • bond::Contains() is const member function now
  • Property mode set to 100644
File size: 14.2 KB
Line 
1/*
2 * bondgraph.hpp
3 *
4 * Created on: Oct 29, 2009
5 * Author: heber
6 */
7
8#ifndef BONDGRAPH_HPP_
9#define BONDGRAPH_HPP_
10
11using namespace std;
12
13/*********************************************** includes ***********************************/
14
15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
20#include <iosfwd>
21
22#include "AtomSet.hpp"
23#include "Bond/bond.hpp"
24#include "CodePatterns/Assert.hpp"
25#include "CodePatterns/Log.hpp"
26#include "CodePatterns/Range.hpp"
27#include "CodePatterns/Verbose.hpp"
28#include "element.hpp"
29#include "linkedcell.hpp"
30#include "IPointCloud.hpp"
31#include "PointCloudAdaptor.hpp"
32#include "WorldTime.hpp"
33
34/****************************************** forward declarations *****************************/
35
36class molecule;
37class BondedParticle;
38class MatrixContainer;
39
40/********************************************** definitions *********************************/
41
42/********************************************** declarations *******************************/
43
44
45class BondGraph {
46 //!> analysis bonds unit test should be friend to access private parts.
47 friend class AnalysisBondsTest;
48 //!> own bond graph unit test should be friend to access private parts.
49 friend class BondGraphTest;
50public:
51 /** Constructor of class BondGraph.
52 * This classes contains typical bond lengths and thus may be used to construct a bond graph for a given molecule.
53 */
54 BondGraph(bool IsA);
55
56 /** Destructor of class BondGraph.
57 */
58 ~BondGraph();
59
60 /** Parses the bond lengths in a given file and puts them int a matrix form.
61 * Allocates \a MatrixContainer for BondGraph::BondLengthMatrix, using MatrixContainer::ParseMatrix(),
62 * but only if parsing is successful. Otherwise variable is left as NULL.
63 * \param &input input stream to parse table from
64 * \return true - success in parsing file, false - failed to parse the file
65 */
66 bool LoadBondLengthTable(std::istream &input);
67
68 /** Determines the maximum of all element::CovalentRadius for elements present in \a &Set.
69 *
70 * I.e. the function returns a sensible cutoff criteria for bond recognition,
71 * e.g. to be used for LinkedCell or others.
72 *
73 * \param &Set AtomSetMixin with all particles to consider
74 */
75 template <class container_type,
76 class iterator_type,
77 class const_iterator_type>
78 double getMaxPossibleBondDistance(
79 const AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
80 {
81 double max_distance = 0.;
82 // get all elements
83 std::set< const element *> PresentElements;
84 for(const_iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
85 PresentElements.insert( (*AtomRunner)->getType() );
86 }
87 // create all element combinations
88 for (std::set< const element *>::const_iterator iter = PresentElements.begin();
89 iter != PresentElements.end();
90 ++iter) {
91 for (std::set< const element *>::const_iterator otheriter = iter;
92 otheriter != PresentElements.end();
93 ++otheriter) {
94 const range<double> MinMaxDistance(getMinMaxDistance((*iter),(*otheriter)));
95 if (MinMaxDistance.last > max_distance)
96 max_distance = MinMaxDistance.last;
97 }
98 }
99 return max_distance;
100 }
101
102 /** Returns bond criterion for given pair based on a bond length matrix.
103 * This calls element-version of getMinMaxDistance().
104 * \param *Walker first BondedParticle
105 * \param *OtherWalker second BondedParticle
106 * \return Range with bond interval
107 */
108 range<double> getMinMaxDistance(
109 const BondedParticle * const Walker,
110 const BondedParticle * const OtherWalker) const;
111
112 /** Returns SQUARED bond criterion for given pair based on a bond length matrix.
113 * This calls element-version of getMinMaxDistance() and squares the values
114 * of either interval end.
115 * \param *Walker first BondedParticle
116 * \param *OtherWalker second BondedParticle
117 * \return Range with bond interval
118 */
119 range<double> getMinMaxDistanceSquared(
120 const BondedParticle * const Walker,
121 const BondedParticle * const OtherWalker) const;
122
123 /** Creates the adjacency list for a given \a Range of iterable atoms.
124 *
125 * @param Set Range with begin and end iterator
126 */
127 template <class container_type,
128 class iterator_type,
129 class const_iterator_type>
130 void CreateAdjacency(
131 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
132 {
133 LOG(1, "STATUS: Removing all present bonds.");
134 cleanAdjacencyList(Set);
135
136 // count atoms in molecule = dimension of matrix (also give each unique name and continuous numbering)
137 const unsigned int counter = Set.size();
138 if (counter > 1) {
139 LOG(1, "STATUS: Setting max bond distance.");
140 const double max_distance = getMaxPossibleBondDistance(Set);
141
142 LOG(1, "STATUS: Creating LinkedCell structure for given " << counter << " atoms.");
143 PointCloudAdaptor< AtomSetMixin<container_type,iterator_type> > cloud(&Set, "SetOfAtoms");
144 LinkedCell *LC = new LinkedCell(cloud, max_distance);
145
146 CreateAdjacency(*LC);
147 delete (LC);
148
149 // correct bond degree by comparing valence and bond degree
150 LOG(1, "STATUS: Correcting bond degree.");
151 CorrectBondDegree(Set);
152
153 // output bonds for debugging (if bond chain list was correctly installed)
154 LOG(2, "STATUS: Printing list of created bonds.");
155 std::stringstream output;
156 for(const_iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
157 (*AtomRunner)->OutputBondOfAtom(output);
158 output << std::endl << "\t\t";
159 }
160 LOG(2, output.str());
161 } else {
162 LOG(1, "REJECT: AtomCount is " << counter << ", thus no bonds, no connections.");
163 }
164 }
165
166 /** Creates an adjacency list of the given \a Set of atoms.
167 *
168 * Note that the input stream is required to refer to the same number of
169 * atoms also contained in \a Set.
170 *
171 * \param &Set container with atoms
172 * \param *input input stream to parse
173 * \param skiplines how many header lines to skip
174 * \param id_offset is base id compared to World startin at 0
175 */
176 template <class container_type,
177 class iterator_type,
178 class const_iterator_type>
179 void CreateAdjacencyListFromDbondFile(
180 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set,
181 ifstream *input,
182 unsigned int skiplines,
183 int id_offset) const
184 {
185 char line[MAXSTRINGSIZE];
186
187 // check input stream
188 if (input->fail()) {
189 ELOG(0, "Opening of bond file failed \n");
190 return;
191 };
192 // skip headers
193 unsigned int bondcount = 0;
194 for (unsigned int i=0;i<skiplines;i++)
195 input->getline(line,MAXSTRINGSIZE);
196
197 // create lookup map
198 LOG(1, "STATUS: Creating lookup map.");
199 std::map< unsigned int, atom *> AtomLookup;
200 unsigned int counter = id_offset; // if ids do not start at 0
201 for (iterator_type iter = Set.begin(); iter != Set.end(); ++iter) {
202 AtomLookup.insert( make_pair( counter++, *iter) );
203 }
204 LOG(2, "INFO: There are " << counter << " atoms in the given set.");
205
206 LOG(1, "STATUS: Scanning file.");
207 unsigned int atom1, atom2;
208 unsigned int bondcounter = 0;
209 while (!input->eof()) // Check whether we read everything already
210 {
211 input->getline(line,MAXSTRINGSIZE);
212 stringstream zeile(line);
213 if (zeile.str().empty())
214 continue;
215 zeile >> atom1;
216 zeile >> atom2;
217
218 LOG(4, "INFO: Looking for atoms " << atom1 << " and " << atom2 << ".");
219 if (atom2 < atom1) //Sort indices of atoms in order
220 std::swap(atom1, atom2);
221 ASSERT(atom2 < counter,
222 "BondGraph::CreateAdjacencyListFromDbondFile() - ID "
223 +toString(atom2)+" exceeds number of present atoms "+toString(counter)+".");
224 ASSERT(AtomLookup.count(atom1),
225 "BondGraph::CreateAdjacencyListFromDbondFile() - Could not find an atom with the ID given in dbond file");
226 ASSERT(AtomLookup.count(atom2),
227 "BondGraph::CreateAdjacencyListFromDbondFile() - Could not find an atom with the ID given in dbond file");
228 atom * const Walker = AtomLookup[atom1];
229 atom * const OtherWalker = AtomLookup[atom2];
230
231 LOG(3, "INFO: Creating bond between atoms " << atom1 << " and " << atom2 << ".");
232 //const bond * Binder =
233 Walker->addBond(WorldTime::getTime(), OtherWalker);
234 bondcounter++;
235 }
236 LOG(1, "STATUS: "<< bondcounter << " bonds have been parsed.");
237 }
238
239 /** Creates an adjacency list of the molecule.
240 * Generally, we use the CSD approach to bond recognition, that is the the distance
241 * between two atoms A and B must be within [Rcov(A)+Rcov(B)-t,Rcov(A)+Rcov(B)+t] with
242 * a threshold t = 0.4 Angstroem.
243 * To make it O(N log N) the function uses the linked-cell technique as follows:
244 * The procedure is step-wise:
245 * -# Remove every bond in list
246 * -# Count the atoms in the molecule with CountAtoms()
247 * -# partition cell into smaller linked cells of size \a bonddistance
248 * -# put each atom into its corresponding cell
249 * -# go through every cell, check the atoms therein against all possible bond partners in the 27 adjacent cells, add bond if true
250 * -# correct the bond degree iteratively (single->double->triple bond)
251 * -# finally print the bond list to \a *out if desired
252 * \param &LC Linked Cell Container with all atoms
253 */
254 void CreateAdjacency(LinkedCell &LC) const;
255
256 /** Removes all bonds within the given set of iterable atoms.
257 *
258 * @param Set Range with atoms
259 */
260 template <class container_type,
261 class iterator_type,
262 class const_iterator_type>
263 void cleanAdjacencyList(
264 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
265 {
266 // remove every bond from the list
267 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
268 BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
269 for(BondList::iterator BondRunner = ListOfBonds.begin();
270 !ListOfBonds.empty();
271 BondRunner = ListOfBonds.begin()) {
272 ASSERT((*BondRunner)->Contains(*AtomRunner),
273 "BondGraph::cleanAdjacencyList() - "+
274 toString(*BondRunner)+" does not contain "+
275 toString(*AtomRunner)+".");
276 delete((*BondRunner));
277 }
278 }
279 }
280
281 /** correct bond degree by comparing valence and bond degree.
282 * correct Bond degree of each bond by checking both bond partners for a mismatch between valence and current sum of bond degrees,
283 * iteratively increase the one first where the other bond partner has the fewest number of bonds (i.e. in general bonds oxygene
284 * preferred over carbon bonds). Beforehand, we had picked the first mismatching partner, which lead to oxygenes with single instead of
285 * double bonds as was expected.
286 * @param Set Range with atoms
287 * \return number of bonds that could not be corrected
288 */
289 template <class container_type,
290 class iterator_type,
291 class const_iterator_type>
292 int CorrectBondDegree(
293 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
294 {
295 // reset
296 resetBondDegree(Set);
297 // re-calculate
298 return calculateBondDegree(Set);
299 }
300
301private:
302 static const double BondThreshold;
303
304 /** Returns the BondLengthMatrix entry for a given index pair.
305 * \param firstelement index/atom number of first element (row index)
306 * \param secondelement index/atom number of second element (column index)
307 * \note matrix is of course symmetric.
308 */
309 double GetBondLength(
310 int firstelement,
311 int secondelement) const;
312
313 /** Returns bond criterion for given pair based on a bond length matrix.
314 * This calls either the covalent or the bond matrix criterion.
315 * \param *Walker first BondedParticle
316 * \param *OtherWalker second BondedParticle
317 * \return Range with bond interval
318 */
319 range<double> getMinMaxDistance(
320 const element * const Walker,
321 const element * const OtherWalker) const;
322
323 /** Returns bond criterion for given pair of elements based on a bond length matrix.
324 * The matrix should be contained in \a this BondGraph and contain an element-
325 * to-element length.
326 * \param *Walker first element
327 * \param *OtherWalker second element
328 * \return Range with bond interval
329 */
330 range<double> BondLengthMatrixMinMaxDistance(
331 const element * const Walker,
332 const element * const OtherWalker) const;
333
334 /** Returns bond criterion for given pair of elements based on covalent radius.
335 * \param *Walker first element
336 * \param *OtherWalker second element
337 * \return Range with bond interval
338 */
339 range<double> CovalentMinMaxDistance(
340 const element * const Walker,
341 const element * const OtherWalker) const;
342
343
344 /** Resets the bond::BondDegree of all atoms in the set to 1.
345 *
346 * @param Set Range with atoms
347 */
348 template <class container_type,
349 class iterator_type,
350 class const_iterator_type>
351 void resetBondDegree(
352 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
353 {
354 // reset bond degrees
355 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
356 BondList &ListOfBonds = (*AtomRunner)->getListOfBonds();
357 for (BondList::iterator BondIter = ListOfBonds.begin();
358 BondIter != ListOfBonds.end();
359 ++BondIter)
360 (*BondIter)->BondDegree = 1;
361 }
362 }
363
364 /** Calculates the bond degree for each atom on the set.
365 *
366 * @param Set Range with atoms
367 * @return number of non-matching bonds
368 */
369 template <class container_type,
370 class iterator_type,
371 class const_iterator_type>
372 int calculateBondDegree(
373 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
374 {
375 //DoLog(1) && (Log() << Verbose(1) << "Correcting Bond degree of each bond ... " << endl);
376 int No = 0, OldNo = -1;
377 do {
378 OldNo = No;
379 No=0;
380 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
381 No+=(*AtomRunner)->CorrectBondDegree();
382 }
383 } while (OldNo != No);
384 //DoLog(0) && (Log() << Verbose(0) << " done." << endl);
385 return No;
386 }
387
388 //!> Matrix with bond lenth per two elements
389 MatrixContainer *BondLengthMatrix;
390 //!> distance units are angstroem (true), bohr radii (false)
391 bool IsAngstroem;
392};
393
394#endif /* BONDGRAPH_HPP_ */
Note: See TracBrowser for help on using the repository browser.