source: src/Graph/BondGraph.hpp@ 3e4fb6

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 3e4fb6 was 68c923, checked in by Frederik Heber <heber@…>, 13 years ago

Lots of small compiler warning fixes.

Issues:

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