source: src/bondgraph.hpp@ 300220

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

BondGraph::..MinMaxDistance() changed to use range<double>.

  • Property mode set to 100644
File size: 14.7 KB
RevLine 
[b70721]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
[986ed3]20#include <iosfwd>
[b70721]21
[3738f0]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"
[0cbad2]32#include "WorldTime.hpp"
[b48ba6]33
[b70721]34/****************************************** forward declarations *****************************/
35
36class molecule;
[97ebf8]37class BondedParticle;
[b70721]38class MatrixContainer;
39
40/********************************************** definitions *********************************/
41
42/********************************************** declarations *******************************/
43
44
45class BondGraph {
[300220]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;
[b70721]50public:
[e7350d4]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 */
[b70721]54 BondGraph(bool IsA);
[e7350d4]55
56 /** Destructor of class BondGraph.
57 */
[b70721]58 ~BondGraph();
[e7350d4]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 */
[4e855e]66 bool LoadBondLengthTable(std::istream &input);
[e7350d4]67
[3738f0]68 /** Determines the maximum of all element::CovalentRadius for elements present in \a &Set.
69 *
70 * Sets BondGraph::max_distance
71 *
72 * \param &Set PointCloud with all particles
73 */
74 template <class container_type,
75 class iterator_type,
76 class const_iterator_type>
77 double SetMaxDistanceToMaxOfCovalentRadii(const AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set)
78 {
79 max_distance = 0.;
80
81 for(const_iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
82 const double radius = (*AtomRunner)->getType()->getCovalentRadius();
83 if (radius > max_distance)
84 max_distance = radius;
85 }
86 max_distance *= 2.;
87 max_distance += BondThreshold;
88
89 return max_distance;
90 }
91
92 /** Returns the upper limit on possible bond distances.
93 *
94 * Is set by SetMaxDistanceToMaxOfCovalentRadii(), is needed e.g. as cutoff
95 * for linked-cell.
96 *
97 * \return maximum possible bond distance
[e7350d4]98 */
[3738f0]99 double getMaxDistance() const;
[72d90e]100
101 /** Returns bond criterion for given pair based on a bond length matrix.
[300220]102 * This calls element-version of getMinMaxDistance().
[72d90e]103 * \param *Walker first BondedParticle
104 * \param *OtherWalker second BondedParticle
[300220]105 * \param &MinMaxDistance Range for interval on return
[72d90e]106 * \param IsAngstroem whether units are in angstroem or bohr radii
107 */
[300220]108 void getMinMaxDistance(
109 const BondedParticle * const Walker,
110 const BondedParticle * const OtherWalker,
111 range<double> &MinMaxDistance,
112 bool IsAngstroem) 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 * \param IsAngstroem whether units are in angstroem or bohr radii
121 */
122 void getMinMaxDistanceSquared(
123 const BondedParticle * const Walker,
124 const BondedParticle * const OtherWalker,
125 range<double> &MinMaxDistance,
126 bool IsAngstroem) const;
[b70721]127
[3738f0]128 /** Creates the adjacency list for a given \a Range of iterable atoms.
129 *
130 * @param Set Range with begin and end iterator
[e7350d4]131 */
[3738f0]132 template <class container_type,
133 class iterator_type,
134 class const_iterator_type>
135 void CreateAdjacency(AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set)
136 {
137 LOG(1, "STATUS: Removing all present bonds.");
138 cleanAdjacencyList(Set);
139
140 // count atoms in molecule = dimension of matrix (also give each unique name and continuous numbering)
141 const unsigned int counter = Set.size();
142 if (counter > 1) {
143 LOG(1, "STATUS: Setting max bond distance.");
144 SetMaxDistanceToMaxOfCovalentRadii(Set);
145
146 LOG(1, "STATUS: Creating LinkedCell structure for given " << counter << " atoms.");
147 PointCloudAdaptor< AtomSetMixin<container_type,iterator_type> > cloud(&Set, "SetOfAtoms");
148 LinkedCell *LC = new LinkedCell(cloud, max_distance);
149
150 CreateAdjacency(*LC);
151 delete (LC);
152
153 // correct bond degree by comparing valence and bond degree
154 LOG(1, "STATUS: Correcting bond degree.");
155 CorrectBondDegree(Set);
156
157 // output bonds for debugging (if bond chain list was correctly installed)
158 LOG(2, "STATUS: Printing list of created bonds.");
159 std::stringstream output;
160 for(const_iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
161 (*AtomRunner)->OutputBondOfAtom(output);
162 output << std::endl << "\t\t";
163 }
164 LOG(2, output.str());
165 } else {
166 LOG(1, "REJECT: AtomCount is " << counter << ", thus no bonds, no connections.");
167 }
168 }
169
[0cbad2]170 /** Creates an adjacency list of the given \a Set of atoms.
171 *
172 * Note that the input stream is required to refer to the same number of
173 * atoms also contained in \a Set.
174 *
175 * \param &Set container with atoms
176 * \param *input input stream to parse
177 * \param skiplines how many header lines to skip
178 * \param id_offset is base id compared to World startin at 0
179 */
180 template <class container_type,
181 class iterator_type,
182 class const_iterator_type>
183 void CreateAdjacencyListFromDbondFile(
184 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set,
185 ifstream *input,
186 unsigned int skiplines,
187 int id_offset) const
188 {
189 char line[MAXSTRINGSIZE];
190
191 // check input stream
192 if (input->fail()) {
193 ELOG(0, "Opening of bond file failed \n");
194 return;
195 };
196 // skip headers
197 unsigned int bondcount = 0;
198 for (unsigned int i=0;i<skiplines;i++)
199 input->getline(line,MAXSTRINGSIZE);
200
201 // create lookup map
202 LOG(1, "STATUS: Creating lookup map.");
203 std::map< unsigned int, atom *> AtomLookup;
204 unsigned int counter = id_offset; // if ids do not start at 0
205 for (iterator_type iter = Set.begin(); iter != Set.end(); ++iter) {
206 AtomLookup.insert( make_pair( counter++, *iter) );
207 }
208 LOG(2, "INFO: There are " << counter << " atoms in the given set.");
209
210 LOG(1, "STATUS: Scanning file.");
211 unsigned int atom1, atom2;
212 unsigned int bondcounter = 0;
213 while (!input->eof()) // Check whether we read everything already
214 {
215 input->getline(line,MAXSTRINGSIZE);
216 stringstream zeile(line);
217 if (zeile.str().empty())
218 continue;
219 zeile >> atom1;
220 zeile >> atom2;
221
222 LOG(4, "INFO: Looking for atoms " << atom1 << " and " << atom2 << ".");
223 if (atom2 < atom1) //Sort indices of atoms in order
224 std::swap(atom1, atom2);
225 ASSERT(atom2 < counter,
226 "BondGraph::CreateAdjacencyListFromDbondFile() - ID "
227 +toString(atom2)+" exceeds number of present atoms "+toString(counter)+".");
228 ASSERT(AtomLookup.count(atom1),
229 "BondGraph::CreateAdjacencyListFromDbondFile() - Could not find an atom with the ID given in dbond file");
230 ASSERT(AtomLookup.count(atom2),
231 "BondGraph::CreateAdjacencyListFromDbondFile() - Could not find an atom with the ID given in dbond file");
232 atom * const Walker = AtomLookup[atom1];
233 atom * const OtherWalker = AtomLookup[atom2];
234
235 LOG(3, "INFO: Creating bond between atoms " << atom1 << " and " << atom2 << ".");
236 bond * const Binder = new bond(Walker, OtherWalker, 1, -1);
237 Walker->RegisterBond(WorldTime::getTime(), Binder);
238 OtherWalker->RegisterBond(WorldTime::getTime(), Binder);
239 bondcounter++;
240 }
241 LOG(1, "STATUS: "<< bondcounter << " bonds have been parsed.");
242 }
243
[3738f0]244 /** Creates an adjacency list of the molecule.
245 * Generally, we use the CSD approach to bond recognition, that is the the distance
246 * between two atoms A and B must be within [Rcov(A)+Rcov(B)-t,Rcov(A)+Rcov(B)+t] with
247 * a threshold t = 0.4 Angstroem.
248 * To make it O(N log N) the function uses the linked-cell technique as follows:
249 * The procedure is step-wise:
250 * -# Remove every bond in list
251 * -# Count the atoms in the molecule with CountAtoms()
252 * -# partition cell into smaller linked cells of size \a bonddistance
253 * -# put each atom into its corresponding cell
254 * -# go through every cell, check the atoms therein against all possible bond partners in the 27 adjacent cells, add bond if true
255 * -# correct the bond degree iteratively (single->double->triple bond)
256 * -# finally print the bond list to \a *out if desired
257 * \param &LC Linked Cell Container with all atoms
258 */
259 void CreateAdjacency(LinkedCell &LC);
260
261 /** Removes all bonds within the given set of iterable atoms.
262 *
263 * @param Set Range with atoms
264 */
265 template <class container_type,
266 class iterator_type,
267 class const_iterator_type>
268 void cleanAdjacencyList(AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set)
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(AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
297 {
298 // reset
299 resetBondDegree(Set);
300 // re-calculate
301 return calculateBondDegree(Set);
302 }
[af2c424]303
[b70721]304private:
[88b400]305 static const double BondThreshold;
306
[300220]307 /** Returns the BondLengthMatrix entry for a given index pair.
308 * \param firstelement index/atom number of first element (row index)
309 * \param secondelement index/atom number of second element (column index)
310 * \note matrix is of course symmetric.
311 */
312 double GetBondLength(
313 int firstelement,
314 int secondelement) const;
315
[e7350d4]316 /** Returns bond criterion for given pair based on a bond length matrix.
317 * The matrix should be contained in \a this BondGraph and contain an element-
318 * to-element length.
319 * \param *Walker first BondedParticle
320 * \param *OtherWalker second BondedParticle
[300220]321 * \param &MinMaxDistance Range for interval on return
[e7350d4]322 * \param IsAngstroem whether units are in angstroem or bohr radii
323 */
[300220]324 void getMinMaxDistance(
325 const element * const Walker,
326 const element * const OtherWalker,
327 range<double> &MinMaxDistance,
328 bool IsAngstroem) const;
[72d90e]329
[300220]330 /** Returns bond criterion for given pair of elements based on a bond length matrix.
331 * The matrix should be contained in \a this BondGraph and contain an element-
332 * to-element length.
333 * \param *Walker first element
334 * \param *OtherWalker second element
335 * @param MinMaxDistance reference to range type set on return
336 * \param IsAngstroem whether units are in angstroem or bohr radii
337 */
338 void BondLengthMatrixMinMaxDistance(
339 const element * const Walker,
340 const element * const OtherWalker,
341 range<double> &DistanceInterval,
342 bool IsAngstroem) const;
343
344 /** Returns bond criterion for given pair of elements based on covalent radius.
345 * \param *Walker first element
346 * \param *OtherWalker second element
347 * @param MinMaxDistance reference to range type set on return
[e7350d4]348 * \param IsAngstroem whether units are in angstroem or bohr radii
349 */
[300220]350 void CovalentMinMaxDistance(
351 const element * const Walker,
352 const element * const OtherWalker,
353 range<double> &DistanceInterval,
354 bool IsAngstroem) const;
[72d90e]355
[3738f0]356
357 /** Resets the bond::BondDegree of all atoms in the set to 1.
358 *
359 * @param Set Range with atoms
360 */
361 template <class container_type,
362 class iterator_type,
363 class const_iterator_type>
364 void resetBondDegree(AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
365 {
366 // reset bond degrees
367 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
368 BondList &ListOfBonds = (*AtomRunner)->getListOfBonds();
369 for (BondList::iterator BondIter = ListOfBonds.begin();
370 BondIter != ListOfBonds.end();
371 ++BondIter)
372 (*BondIter)->BondDegree = 1;
373 }
374 }
375
376 /** Calculates the bond degree for each atom on the set.
377 *
378 * @param Set Range with atoms
379 * @return number of non-matching bonds
380 */
381 template <class container_type,
382 class iterator_type,
383 class const_iterator_type>
384 int calculateBondDegree(AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
385 {
386 //DoLog(1) && (Log() << Verbose(1) << "Correcting Bond degree of each bond ... " << endl);
387 int No = 0, OldNo = -1;
388 do {
389 OldNo = No;
390 No=0;
391 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
392 No+=(*AtomRunner)->CorrectBondDegree();
393 }
394 } while (OldNo != No);
395 //DoLog(0) && (Log() << Verbose(0) << " done." << endl);
396 return No;
397 }
398
[e7350d4]399 //!> Matrix with bond lenth per two elements
[b70721]400 MatrixContainer *BondLengthMatrix;
[e7350d4]401 //!> maximum distance over all bonds possible
[b70721]402 double max_distance;
[e7350d4]403 //!> distance units are angstroem (true), bohr radii (false)
[b70721]404 bool IsAngstroem;
405};
406
407#endif /* BONDGRAPH_HPP_ */
Note: See TracBrowser for help on using the repository browser.