source: src/bondgraph.hpp@ cff66c

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

Removed bool is Angstroem from all BondGraph::...() member functions.

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