source: src/Graph/BondGraph.hpp@ b1ac7a

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

New function BondGraph::CleanupBondLengthTable().

  • Property mode set to 100644
File size: 15.3 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
[f007a1]22#include <boost/serialization/array.hpp>
23
[3738f0]24#include "AtomSet.hpp"
[129204]25#include "Bond/bond.hpp"
[3738f0]26#include "CodePatterns/Assert.hpp"
27#include "CodePatterns/Log.hpp"
28#include "CodePatterns/Range.hpp"
29#include "CodePatterns/Verbose.hpp"
[3bdb6d]30#include "Element/element.hpp"
[f007a1]31#include "Fragmentation/MatrixContainer.hpp"
[3738f0]32#include "linkedcell.hpp"
33#include "IPointCloud.hpp"
34#include "PointCloudAdaptor.hpp"
[0cbad2]35#include "WorldTime.hpp"
[b48ba6]36
[b70721]37/****************************************** forward declarations *****************************/
38
39class molecule;
[97ebf8]40class BondedParticle;
[b70721]41class MatrixContainer;
42
43/********************************************** definitions *********************************/
44
45/********************************************** declarations *******************************/
46
47
48class BondGraph {
[300220]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;
[b70721]53public:
[e7350d4]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 */
[b70721]57 BondGraph(bool IsA);
[e7350d4]58
59 /** Destructor of class BondGraph.
60 */
[b70721]61 ~BondGraph();
[e7350d4]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 */
[4e855e]69 bool LoadBondLengthTable(std::istream &input);
[e7350d4]70
[829761]71 /** Removes allocated bond length table.
72 *
73 */
74 void CleanupBondLengthTable();
75
[3738f0]76 /** Determines the maximum of all element::CovalentRadius for elements present in \a &Set.
77 *
[0ec7fe]78 * I.e. the function returns a sensible cutoff criteria for bond recognition,
79 * e.g. to be used for LinkedCell or others.
[3738f0]80 *
[0ec7fe]81 * \param &Set AtomSetMixin with all particles to consider
[3738f0]82 */
83 template <class container_type,
84 class iterator_type,
85 class const_iterator_type>
[0ec7fe]86 double getMaxPossibleBondDistance(
87 const AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
[3738f0]88 {
[0ec7fe]89 double max_distance = 0.;
90 // get all elements
91 std::set< const element *> PresentElements;
[3738f0]92 for(const_iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
[0ec7fe]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) {
[607eab]102 const range<double> MinMaxDistance(getMinMaxDistance((*iter),(*otheriter)));
[0ec7fe]103 if (MinMaxDistance.last > max_distance)
104 max_distance = MinMaxDistance.last;
105 }
[3738f0]106 }
107 return max_distance;
108 }
109
[72d90e]110 /** Returns bond criterion for given pair based on a bond length matrix.
[300220]111 * This calls element-version of getMinMaxDistance().
[72d90e]112 * \param *Walker first BondedParticle
113 * \param *OtherWalker second BondedParticle
[607eab]114 * \return Range with bond interval
[72d90e]115 */
[607eab]116 range<double> getMinMaxDistance(
[300220]117 const BondedParticle * const Walker,
[607eab]118 const BondedParticle * const OtherWalker) const;
[300220]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
[607eab]125 * \return Range with bond interval
[300220]126 */
[607eab]127 range<double> getMinMaxDistanceSquared(
[300220]128 const BondedParticle * const Walker,
[607eab]129 const BondedParticle * const OtherWalker) const;
[b70721]130
[3738f0]131 /** Creates the adjacency list for a given \a Range of iterable atoms.
132 *
133 * @param Set Range with begin and end iterator
[e7350d4]134 */
[3738f0]135 template <class container_type,
136 class iterator_type,
137 class const_iterator_type>
[111f4a]138 void CreateAdjacency(
139 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
[3738f0]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.");
[0ec7fe]148 const double max_distance = getMaxPossibleBondDistance(Set);
[3738f0]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
[0cbad2]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 unsigned int bondcount = 0;
202 for (unsigned int i=0;i<skiplines;i++)
203 input->getline(line,MAXSTRINGSIZE);
204
205 // create lookup map
206 LOG(1, "STATUS: Creating lookup map.");
207 std::map< unsigned int, atom *> AtomLookup;
208 unsigned int counter = id_offset; // if ids do not start at 0
209 for (iterator_type iter = Set.begin(); iter != Set.end(); ++iter) {
210 AtomLookup.insert( make_pair( counter++, *iter) );
211 }
212 LOG(2, "INFO: There are " << counter << " atoms in the given set.");
213
214 LOG(1, "STATUS: Scanning file.");
215 unsigned int atom1, atom2;
216 unsigned int bondcounter = 0;
217 while (!input->eof()) // Check whether we read everything already
218 {
219 input->getline(line,MAXSTRINGSIZE);
220 stringstream zeile(line);
221 if (zeile.str().empty())
222 continue;
223 zeile >> atom1;
224 zeile >> atom2;
225
226 LOG(4, "INFO: Looking for atoms " << atom1 << " and " << atom2 << ".");
227 if (atom2 < atom1) //Sort indices of atoms in order
228 std::swap(atom1, atom2);
229 ASSERT(atom2 < counter,
230 "BondGraph::CreateAdjacencyListFromDbondFile() - ID "
231 +toString(atom2)+" exceeds number of present atoms "+toString(counter)+".");
232 ASSERT(AtomLookup.count(atom1),
233 "BondGraph::CreateAdjacencyListFromDbondFile() - Could not find an atom with the ID given in dbond file");
234 ASSERT(AtomLookup.count(atom2),
235 "BondGraph::CreateAdjacencyListFromDbondFile() - Could not find an atom with the ID given in dbond file");
236 atom * const Walker = AtomLookup[atom1];
237 atom * const OtherWalker = AtomLookup[atom2];
238
239 LOG(3, "INFO: Creating bond between atoms " << atom1 << " and " << atom2 << ".");
[db7e6d]240 //const bond * Binder =
241 Walker->addBond(WorldTime::getTime(), OtherWalker);
[0cbad2]242 bondcounter++;
243 }
244 LOG(1, "STATUS: "<< bondcounter << " bonds have been parsed.");
245 }
246
[3738f0]247 /** Creates an adjacency list of the molecule.
248 * Generally, we use the CSD approach to bond recognition, that is the the distance
249 * between two atoms A and B must be within [Rcov(A)+Rcov(B)-t,Rcov(A)+Rcov(B)+t] with
250 * a threshold t = 0.4 Angstroem.
251 * To make it O(N log N) the function uses the linked-cell technique as follows:
252 * The procedure is step-wise:
253 * -# Remove every bond in list
254 * -# Count the atoms in the molecule with CountAtoms()
255 * -# partition cell into smaller linked cells of size \a bonddistance
256 * -# put each atom into its corresponding cell
257 * -# go through every cell, check the atoms therein against all possible bond partners in the 27 adjacent cells, add bond if true
258 * -# correct the bond degree iteratively (single->double->triple bond)
259 * -# finally print the bond list to \a *out if desired
260 * \param &LC Linked Cell Container with all atoms
261 */
[111f4a]262 void CreateAdjacency(LinkedCell &LC) const;
[3738f0]263
264 /** Removes all bonds within the given set of iterable atoms.
265 *
266 * @param Set Range with atoms
267 */
268 template <class container_type,
269 class iterator_type,
270 class const_iterator_type>
[111f4a]271 void cleanAdjacencyList(
272 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
[3738f0]273 {
274 // remove every bond from the list
275 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
[5e2f80]276 (*AtomRunner)->removeAllBonds();
277// BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
278// for(BondList::iterator BondRunner = ListOfBonds.begin();
279// !ListOfBonds.empty();
280// BondRunner = ListOfBonds.begin()) {
281// ASSERT((*BondRunner)->Contains(*AtomRunner),
282// "BondGraph::cleanAdjacencyList() - "+
283// toString(*BondRunner)+" does not contain "+
284// toString(*AtomRunner)+".");
285// delete((*BondRunner));
286// }
[3738f0]287 }
288 }
289
290 /** correct bond degree by comparing valence and bond degree.
291 * correct Bond degree of each bond by checking both bond partners for a mismatch between valence and current sum of bond degrees,
292 * iteratively increase the one first where the other bond partner has the fewest number of bonds (i.e. in general bonds oxygene
293 * preferred over carbon bonds). Beforehand, we had picked the first mismatching partner, which lead to oxygenes with single instead of
294 * double bonds as was expected.
295 * @param Set Range with atoms
296 * \return number of bonds that could not be corrected
297 */
298 template <class container_type,
299 class iterator_type,
300 class const_iterator_type>
[111f4a]301 int CorrectBondDegree(
302 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
[3738f0]303 {
304 // reset
305 resetBondDegree(Set);
306 // re-calculate
307 return calculateBondDegree(Set);
308 }
[af2c424]309
[9b6663]310 /** Equality comparator for class BondGraph.
311 *
312 * @param other other instance to compare to
313 * @return true - if equal in every member variable, except static
314 * \a BondGraph::BondThreshold.
315 */
316 bool operator==(const BondGraph &other) const;
317
318 /** Unequality comparator for class BondGraph.
319 *
320 * @param other other instance to compare to
321 * @return false - if equal in every member variable, except static
322 * \a BondGraph::BondThreshold.
323 */
324 bool operator!=(const BondGraph &other) const {
325 return !(*this == other);
326 }
327
[b70721]328private:
[88b400]329
[300220]330 /** Returns the BondLengthMatrix entry for a given index pair.
331 * \param firstelement index/atom number of first element (row index)
332 * \param secondelement index/atom number of second element (column index)
333 * \note matrix is of course symmetric.
334 */
335 double GetBondLength(
336 int firstelement,
337 int secondelement) const;
338
[e7350d4]339 /** Returns bond criterion for given pair based on a bond length matrix.
[111f4a]340 * This calls either the covalent or the bond matrix criterion.
[e7350d4]341 * \param *Walker first BondedParticle
342 * \param *OtherWalker second BondedParticle
[607eab]343 * \return Range with bond interval
[e7350d4]344 */
[607eab]345 range<double> getMinMaxDistance(
[300220]346 const element * const Walker,
[607eab]347 const element * const OtherWalker) const;
[72d90e]348
[300220]349 /** Returns bond criterion for given pair of elements based on a bond length matrix.
350 * The matrix should be contained in \a this BondGraph and contain an element-
351 * to-element length.
352 * \param *Walker first element
353 * \param *OtherWalker second element
[607eab]354 * \return Range with bond interval
[300220]355 */
[607eab]356 range<double> BondLengthMatrixMinMaxDistance(
[300220]357 const element * const Walker,
[607eab]358 const element * const OtherWalker) const;
[300220]359
360 /** Returns bond criterion for given pair of elements based on covalent radius.
361 * \param *Walker first element
362 * \param *OtherWalker second element
[607eab]363 * \return Range with bond interval
[e7350d4]364 */
[607eab]365 range<double> CovalentMinMaxDistance(
[300220]366 const element * const Walker,
[607eab]367 const element * const OtherWalker) const;
[72d90e]368
[3738f0]369
370 /** Resets the bond::BondDegree of all atoms in the set to 1.
371 *
372 * @param Set Range with atoms
373 */
374 template <class container_type,
375 class iterator_type,
376 class const_iterator_type>
[111f4a]377 void resetBondDegree(
378 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
[3738f0]379 {
380 // reset bond degrees
381 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
[5e2f80]382 (*AtomRunner)->resetBondDegree();
[3738f0]383 }
384 }
385
386 /** Calculates the bond degree for each atom on the set.
387 *
388 * @param Set Range with atoms
389 * @return number of non-matching bonds
390 */
391 template <class container_type,
392 class iterator_type,
393 class const_iterator_type>
[111f4a]394 int calculateBondDegree(
395 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
[3738f0]396 {
397 //DoLog(1) && (Log() << Verbose(1) << "Correcting Bond degree of each bond ... " << endl);
398 int No = 0, OldNo = -1;
399 do {
400 OldNo = No;
401 No=0;
402 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
403 No+=(*AtomRunner)->CorrectBondDegree();
404 }
405 } while (OldNo != No);
406 //DoLog(0) && (Log() << Verbose(0) << " done." << endl);
407 return No;
408 }
409
[f007a1]410 bool operator==(const periodentafel &other) const;
411
412 bool operator!=(const periodentafel &other) const {
413 return !(*this == other);
414 }
415
416private:
417 // default constructor for serialization
418 BondGraph();
419
420 friend class boost::serialization::access;
421 // serialization
422 template<class Archive>
423 void serialize(Archive & ar, const unsigned int version)
424 {
425 //ar & const_cast<double &>(BondThreshold);
426 ar & BondLengthMatrix;
427 ar & IsAngstroem;
428 }
429
430 //!> half width of the interval for allowed bond distances
431 static const double BondThreshold;
[e7350d4]432 //!> Matrix with bond lenth per two elements
[b70721]433 MatrixContainer *BondLengthMatrix;
[e7350d4]434 //!> distance units are angstroem (true), bohr radii (false)
[b70721]435 bool IsAngstroem;
436};
437
438#endif /* BONDGRAPH_HPP_ */
Note: See TracBrowser for help on using the repository browser.