source: src/Graph/BondGraph.hpp@ 9b6663

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 9b6663 was 9b6663, checked in by Frederik Heber <heber@…>, 13 years ago

Added operator==() to BondGraph.

  • Property mode set to 100644
File size: 14.7 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/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 (*AtomRunner)->removeAllBonds();
269// BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
270// for(BondList::iterator BondRunner = ListOfBonds.begin();
271// !ListOfBonds.empty();
272// BondRunner = ListOfBonds.begin()) {
273// ASSERT((*BondRunner)->Contains(*AtomRunner),
274// "BondGraph::cleanAdjacencyList() - "+
275// toString(*BondRunner)+" does not contain "+
276// toString(*AtomRunner)+".");
277// delete((*BondRunner));
278// }
279 }
280 }
281
282 /** correct bond degree by comparing valence and bond degree.
283 * correct Bond degree of each bond by checking both bond partners for a mismatch between valence and current sum of bond degrees,
284 * iteratively increase the one first where the other bond partner has the fewest number of bonds (i.e. in general bonds oxygene
285 * preferred over carbon bonds). Beforehand, we had picked the first mismatching partner, which lead to oxygenes with single instead of
286 * double bonds as was expected.
287 * @param Set Range with atoms
288 * \return number of bonds that could not be corrected
289 */
290 template <class container_type,
291 class iterator_type,
292 class const_iterator_type>
293 int CorrectBondDegree(
294 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
295 {
296 // reset
297 resetBondDegree(Set);
298 // re-calculate
299 return calculateBondDegree(Set);
300 }
301
302 /** Equality comparator for class BondGraph.
303 *
304 * @param other other instance to compare to
305 * @return true - if equal in every member variable, except static
306 * \a BondGraph::BondThreshold.
307 */
308 bool operator==(const BondGraph &other) const;
309
310 /** Unequality comparator for class BondGraph.
311 *
312 * @param other other instance to compare to
313 * @return false - if equal in every member variable, except static
314 * \a BondGraph::BondThreshold.
315 */
316 bool operator!=(const BondGraph &other) const {
317 return !(*this == other);
318 }
319
320private:
321 static const double BondThreshold;
322
323 /** Returns the BondLengthMatrix entry for a given index pair.
324 * \param firstelement index/atom number of first element (row index)
325 * \param secondelement index/atom number of second element (column index)
326 * \note matrix is of course symmetric.
327 */
328 double GetBondLength(
329 int firstelement,
330 int secondelement) const;
331
332 /** Returns bond criterion for given pair based on a bond length matrix.
333 * This calls either the covalent or the bond matrix criterion.
334 * \param *Walker first BondedParticle
335 * \param *OtherWalker second BondedParticle
336 * \return Range with bond interval
337 */
338 range<double> getMinMaxDistance(
339 const element * const Walker,
340 const element * const OtherWalker) const;
341
342 /** Returns bond criterion for given pair of elements based on a bond length matrix.
343 * The matrix should be contained in \a this BondGraph and contain an element-
344 * to-element length.
345 * \param *Walker first element
346 * \param *OtherWalker second element
347 * \return Range with bond interval
348 */
349 range<double> BondLengthMatrixMinMaxDistance(
350 const element * const Walker,
351 const element * const OtherWalker) const;
352
353 /** Returns bond criterion for given pair of elements based on covalent radius.
354 * \param *Walker first element
355 * \param *OtherWalker second element
356 * \return Range with bond interval
357 */
358 range<double> CovalentMinMaxDistance(
359 const element * const Walker,
360 const element * const OtherWalker) const;
361
362
363 /** Resets the bond::BondDegree of all atoms in the set to 1.
364 *
365 * @param Set Range with atoms
366 */
367 template <class container_type,
368 class iterator_type,
369 class const_iterator_type>
370 void resetBondDegree(
371 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
372 {
373 // reset bond degrees
374 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
375 (*AtomRunner)->resetBondDegree();
376 }
377 }
378
379 /** Calculates the bond degree for each atom on the set.
380 *
381 * @param Set Range with atoms
382 * @return number of non-matching bonds
383 */
384 template <class container_type,
385 class iterator_type,
386 class const_iterator_type>
387 int calculateBondDegree(
388 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
389 {
390 //DoLog(1) && (Log() << Verbose(1) << "Correcting Bond degree of each bond ... " << endl);
391 int No = 0, OldNo = -1;
392 do {
393 OldNo = No;
394 No=0;
395 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
396 No+=(*AtomRunner)->CorrectBondDegree();
397 }
398 } while (OldNo != No);
399 //DoLog(0) && (Log() << Verbose(0) << " done." << endl);
400 return No;
401 }
402
403 //!> Matrix with bond lenth per two elements
404 MatrixContainer *BondLengthMatrix;
405 //!> distance units are angstroem (true), bohr radii (false)
406 bool IsAngstroem;
407};
408
409#endif /* BONDGRAPH_HPP_ */
Note: See TracBrowser for help on using the repository browser.