source: src/bondgraph.hpp@ 0ec7fe

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

Removed BondGraph::max_distance along with getter and setter.

  • SetMaxDistanceFromCovalentDistance() was nonsense and prone to faults and misunderstandings.
  • instead getMaxPossibleBondDistance() returns upper cutoff limit based on a given atomset.
  • Property mode set to 100644
File size: 15.0 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.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 range<double> MinMaxDistance(0.,0.);
95 getMinMaxDistance((*iter),(*otheriter), MinMaxDistance, IsAngstroem);
96 if (MinMaxDistance.last > max_distance)
97 max_distance = MinMaxDistance.last;
98 }
99 }
100 return max_distance;
101 }
102
103 /** Returns bond criterion for given pair based on a bond length matrix.
104 * This calls element-version of getMinMaxDistance().
105 * \param *Walker first BondedParticle
106 * \param *OtherWalker second BondedParticle
107 * \param &MinMaxDistance Range for interval on return
108 * \param IsAngstroem whether units are in angstroem or bohr radii
109 */
110 void getMinMaxDistance(
111 const BondedParticle * const Walker,
112 const BondedParticle * const OtherWalker,
113 range<double> &MinMaxDistance,
114 bool IsAngstroem) const;
115
116 /** Returns SQUARED bond criterion for given pair based on a bond length matrix.
117 * This calls element-version of getMinMaxDistance() and squares the values
118 * of either interval end.
119 * \param *Walker first BondedParticle
120 * \param *OtherWalker second BondedParticle
121 * \param &MinMaxDistance Range for interval on return
122 * \param IsAngstroem whether units are in angstroem or bohr radii
123 */
124 void getMinMaxDistanceSquared(
125 const BondedParticle * const Walker,
126 const BondedParticle * const OtherWalker,
127 range<double> &MinMaxDistance,
128 bool IsAngstroem) const;
129
130 /** Creates the adjacency list for a given \a Range of iterable atoms.
131 *
132 * @param Set Range with begin and end iterator
133 */
134 template <class container_type,
135 class iterator_type,
136 class const_iterator_type>
137 void CreateAdjacency(AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set)
138 {
139 LOG(1, "STATUS: Removing all present bonds.");
140 cleanAdjacencyList(Set);
141
142 // count atoms in molecule = dimension of matrix (also give each unique name and continuous numbering)
143 const unsigned int counter = Set.size();
144 if (counter > 1) {
145 LOG(1, "STATUS: Setting max bond distance.");
146 const double max_distance = getMaxPossibleBondDistance(Set);
147
148 LOG(1, "STATUS: Creating LinkedCell structure for given " << counter << " atoms.");
149 PointCloudAdaptor< AtomSetMixin<container_type,iterator_type> > cloud(&Set, "SetOfAtoms");
150 LinkedCell *LC = new LinkedCell(cloud, max_distance);
151
152 CreateAdjacency(*LC);
153 delete (LC);
154
155 // correct bond degree by comparing valence and bond degree
156 LOG(1, "STATUS: Correcting bond degree.");
157 CorrectBondDegree(Set);
158
159 // output bonds for debugging (if bond chain list was correctly installed)
160 LOG(2, "STATUS: Printing list of created bonds.");
161 std::stringstream output;
162 for(const_iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
163 (*AtomRunner)->OutputBondOfAtom(output);
164 output << std::endl << "\t\t";
165 }
166 LOG(2, output.str());
167 } else {
168 LOG(1, "REJECT: AtomCount is " << counter << ", thus no bonds, no connections.");
169 }
170 }
171
172 /** Creates an adjacency list of the given \a Set of atoms.
173 *
174 * Note that the input stream is required to refer to the same number of
175 * atoms also contained in \a Set.
176 *
177 * \param &Set container with atoms
178 * \param *input input stream to parse
179 * \param skiplines how many header lines to skip
180 * \param id_offset is base id compared to World startin at 0
181 */
182 template <class container_type,
183 class iterator_type,
184 class const_iterator_type>
185 void CreateAdjacencyListFromDbondFile(
186 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set,
187 ifstream *input,
188 unsigned int skiplines,
189 int id_offset) const
190 {
191 char line[MAXSTRINGSIZE];
192
193 // check input stream
194 if (input->fail()) {
195 ELOG(0, "Opening of bond file failed \n");
196 return;
197 };
198 // skip headers
199 unsigned int bondcount = 0;
200 for (unsigned int i=0;i<skiplines;i++)
201 input->getline(line,MAXSTRINGSIZE);
202
203 // create lookup map
204 LOG(1, "STATUS: Creating lookup map.");
205 std::map< unsigned int, atom *> AtomLookup;
206 unsigned int counter = id_offset; // if ids do not start at 0
207 for (iterator_type iter = Set.begin(); iter != Set.end(); ++iter) {
208 AtomLookup.insert( make_pair( counter++, *iter) );
209 }
210 LOG(2, "INFO: There are " << counter << " atoms in the given set.");
211
212 LOG(1, "STATUS: Scanning file.");
213 unsigned int atom1, atom2;
214 unsigned int bondcounter = 0;
215 while (!input->eof()) // Check whether we read everything already
216 {
217 input->getline(line,MAXSTRINGSIZE);
218 stringstream zeile(line);
219 if (zeile.str().empty())
220 continue;
221 zeile >> atom1;
222 zeile >> atom2;
223
224 LOG(4, "INFO: Looking for atoms " << atom1 << " and " << atom2 << ".");
225 if (atom2 < atom1) //Sort indices of atoms in order
226 std::swap(atom1, atom2);
227 ASSERT(atom2 < counter,
228 "BondGraph::CreateAdjacencyListFromDbondFile() - ID "
229 +toString(atom2)+" exceeds number of present atoms "+toString(counter)+".");
230 ASSERT(AtomLookup.count(atom1),
231 "BondGraph::CreateAdjacencyListFromDbondFile() - Could not find an atom with the ID given in dbond file");
232 ASSERT(AtomLookup.count(atom2),
233 "BondGraph::CreateAdjacencyListFromDbondFile() - Could not find an atom with the ID given in dbond file");
234 atom * const Walker = AtomLookup[atom1];
235 atom * const OtherWalker = AtomLookup[atom2];
236
237 LOG(3, "INFO: Creating bond between atoms " << atom1 << " and " << atom2 << ".");
238 bond * const Binder = new bond(Walker, OtherWalker, 1, -1);
239 Walker->RegisterBond(WorldTime::getTime(), Binder);
240 OtherWalker->RegisterBond(WorldTime::getTime(), Binder);
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);
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(AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set)
271 {
272 // remove every bond from the list
273 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
274 BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
275 for(BondList::iterator BondRunner = ListOfBonds.begin();
276 !ListOfBonds.empty();
277 BondRunner = ListOfBonds.begin()) {
278 ASSERT((*BondRunner)->Contains(*AtomRunner),
279 "BondGraph::cleanAdjacencyList() - "+
280 toString(*BondRunner)+" does not contain "+
281 toString(*AtomRunner)+".");
282 delete((*BondRunner));
283 }
284 }
285 }
286
287 /** correct bond degree by comparing valence and bond degree.
288 * correct Bond degree of each bond by checking both bond partners for a mismatch between valence and current sum of bond degrees,
289 * iteratively increase the one first where the other bond partner has the fewest number of bonds (i.e. in general bonds oxygene
290 * preferred over carbon bonds). Beforehand, we had picked the first mismatching partner, which lead to oxygenes with single instead of
291 * double bonds as was expected.
292 * @param Set Range with atoms
293 * \return number of bonds that could not be corrected
294 */
295 template <class container_type,
296 class iterator_type,
297 class const_iterator_type>
298 int CorrectBondDegree(AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
299 {
300 // reset
301 resetBondDegree(Set);
302 // re-calculate
303 return calculateBondDegree(Set);
304 }
305
306private:
307 static const double BondThreshold;
308
309 /** Returns the BondLengthMatrix entry for a given index pair.
310 * \param firstelement index/atom number of first element (row index)
311 * \param secondelement index/atom number of second element (column index)
312 * \note matrix is of course symmetric.
313 */
314 double GetBondLength(
315 int firstelement,
316 int secondelement) const;
317
318 /** Returns bond criterion for given pair based on a bond length matrix.
319 * The matrix should be contained in \a this BondGraph and contain an element-
320 * to-element length.
321 * \param *Walker first BondedParticle
322 * \param *OtherWalker second BondedParticle
323 * \param &MinMaxDistance Range for interval on return
324 * \param IsAngstroem whether units are in angstroem or bohr radii
325 */
326 void getMinMaxDistance(
327 const element * const Walker,
328 const element * const OtherWalker,
329 range<double> &MinMaxDistance,
330 bool IsAngstroem) const;
331
332 /** Returns bond criterion for given pair of elements based on a bond length matrix.
333 * The matrix should be contained in \a this BondGraph and contain an element-
334 * to-element length.
335 * \param *Walker first element
336 * \param *OtherWalker second element
337 * @param MinMaxDistance reference to range type set on return
338 * \param IsAngstroem whether units are in angstroem or bohr radii
339 */
340 void BondLengthMatrixMinMaxDistance(
341 const element * const Walker,
342 const element * const OtherWalker,
343 range<double> &DistanceInterval,
344 bool IsAngstroem) const;
345
346 /** Returns bond criterion for given pair of elements based on covalent radius.
347 * \param *Walker first element
348 * \param *OtherWalker second element
349 * @param MinMaxDistance reference to range type set on return
350 * \param IsAngstroem whether units are in angstroem or bohr radii
351 */
352 void CovalentMinMaxDistance(
353 const element * const Walker,
354 const element * const OtherWalker,
355 range<double> &DistanceInterval,
356 bool IsAngstroem) const;
357
358
359 /** Resets the bond::BondDegree of all atoms in the set to 1.
360 *
361 * @param Set Range with atoms
362 */
363 template <class container_type,
364 class iterator_type,
365 class const_iterator_type>
366 void resetBondDegree(AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
367 {
368 // reset bond degrees
369 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
370 BondList &ListOfBonds = (*AtomRunner)->getListOfBonds();
371 for (BondList::iterator BondIter = ListOfBonds.begin();
372 BondIter != ListOfBonds.end();
373 ++BondIter)
374 (*BondIter)->BondDegree = 1;
375 }
376 }
377
378 /** Calculates the bond degree for each atom on the set.
379 *
380 * @param Set Range with atoms
381 * @return number of non-matching bonds
382 */
383 template <class container_type,
384 class iterator_type,
385 class const_iterator_type>
386 int calculateBondDegree(AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
387 {
388 //DoLog(1) && (Log() << Verbose(1) << "Correcting Bond degree of each bond ... " << endl);
389 int No = 0, OldNo = -1;
390 do {
391 OldNo = No;
392 No=0;
393 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
394 No+=(*AtomRunner)->CorrectBondDegree();
395 }
396 } while (OldNo != No);
397 //DoLog(0) && (Log() << Verbose(0) << " done." << endl);
398 return No;
399 }
400
401 //!> Matrix with bond lenth per two elements
402 MatrixContainer *BondLengthMatrix;
403 //!> distance units are angstroem (true), bohr radii (false)
404 bool IsAngstroem;
405};
406
407#endif /* BONDGRAPH_HPP_ */
Note: See TracBrowser for help on using the repository browser.