source: src/Graph/BondGraph.hpp@ 1ac24b

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

Added serialization capability to class BondGraph.

  • Property mode set to 100644
File size: 15.3 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 <boost/serialization/array.hpp>
23
24#include "AtomSet.hpp"
25#include "Bond/bond.hpp"
26#include "CodePatterns/Assert.hpp"
27#include "CodePatterns/Log.hpp"
28#include "CodePatterns/Range.hpp"
29#include "CodePatterns/Verbose.hpp"
30#include "Element/element.hpp"
31#include "Fragmentation/MatrixContainer.hpp"
32#include "linkedcell.hpp"
33#include "IPointCloud.hpp"
34#include "PointCloudAdaptor.hpp"
35#include "WorldTime.hpp"
36
37/****************************************** forward declarations *****************************/
38
39class molecule;
40class BondedParticle;
41class MatrixContainer;
42
43/********************************************** definitions *********************************/
44
45/********************************************** declarations *******************************/
46
47
48class BondGraph {
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;
53public:
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 */
57 BondGraph(bool IsA);
58
59 /** Destructor of class BondGraph.
60 */
61 ~BondGraph();
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 */
69 bool LoadBondLengthTable(std::istream &input);
70
71 /** Determines the maximum of all element::CovalentRadius for elements present in \a &Set.
72 *
73 * I.e. the function returns a sensible cutoff criteria for bond recognition,
74 * e.g. to be used for LinkedCell or others.
75 *
76 * \param &Set AtomSetMixin with all particles to consider
77 */
78 template <class container_type,
79 class iterator_type,
80 class const_iterator_type>
81 double getMaxPossibleBondDistance(
82 const AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
83 {
84 double max_distance = 0.;
85 // get all elements
86 std::set< const element *> PresentElements;
87 for(const_iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
88 PresentElements.insert( (*AtomRunner)->getType() );
89 }
90 // create all element combinations
91 for (std::set< const element *>::const_iterator iter = PresentElements.begin();
92 iter != PresentElements.end();
93 ++iter) {
94 for (std::set< const element *>::const_iterator otheriter = iter;
95 otheriter != PresentElements.end();
96 ++otheriter) {
97 const range<double> MinMaxDistance(getMinMaxDistance((*iter),(*otheriter)));
98 if (MinMaxDistance.last > max_distance)
99 max_distance = MinMaxDistance.last;
100 }
101 }
102 return max_distance;
103 }
104
105 /** Returns bond criterion for given pair based on a bond length matrix.
106 * This calls element-version of getMinMaxDistance().
107 * \param *Walker first BondedParticle
108 * \param *OtherWalker second BondedParticle
109 * \return Range with bond interval
110 */
111 range<double> getMinMaxDistance(
112 const BondedParticle * const Walker,
113 const BondedParticle * const OtherWalker) const;
114
115 /** Returns SQUARED bond criterion for given pair based on a bond length matrix.
116 * This calls element-version of getMinMaxDistance() and squares the values
117 * of either interval end.
118 * \param *Walker first BondedParticle
119 * \param *OtherWalker second BondedParticle
120 * \return Range with bond interval
121 */
122 range<double> getMinMaxDistanceSquared(
123 const BondedParticle * const Walker,
124 const BondedParticle * const OtherWalker) 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 //const bond * Binder =
236 Walker->addBond(WorldTime::getTime(), OtherWalker);
237 bondcounter++;
238 }
239 LOG(1, "STATUS: "<< bondcounter << " bonds have been parsed.");
240 }
241
242 /** Creates an adjacency list of the molecule.
243 * Generally, we use the CSD approach to bond recognition, that is the the distance
244 * between two atoms A and B must be within [Rcov(A)+Rcov(B)-t,Rcov(A)+Rcov(B)+t] with
245 * a threshold t = 0.4 Angstroem.
246 * To make it O(N log N) the function uses the linked-cell technique as follows:
247 * The procedure is step-wise:
248 * -# Remove every bond in list
249 * -# Count the atoms in the molecule with CountAtoms()
250 * -# partition cell into smaller linked cells of size \a bonddistance
251 * -# put each atom into its corresponding cell
252 * -# go through every cell, check the atoms therein against all possible bond partners in the 27 adjacent cells, add bond if true
253 * -# correct the bond degree iteratively (single->double->triple bond)
254 * -# finally print the bond list to \a *out if desired
255 * \param &LC Linked Cell Container with all atoms
256 */
257 void CreateAdjacency(LinkedCell &LC) const;
258
259 /** Removes all bonds within the given set of iterable atoms.
260 *
261 * @param Set Range with atoms
262 */
263 template <class container_type,
264 class iterator_type,
265 class const_iterator_type>
266 void cleanAdjacencyList(
267 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
268 {
269 // remove every bond from the list
270 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
271 (*AtomRunner)->removeAllBonds();
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
305 /** Equality comparator for class BondGraph.
306 *
307 * @param other other instance to compare to
308 * @return true - if equal in every member variable, except static
309 * \a BondGraph::BondThreshold.
310 */
311 bool operator==(const BondGraph &other) const;
312
313 /** Unequality comparator for class BondGraph.
314 *
315 * @param other other instance to compare to
316 * @return false - if equal in every member variable, except static
317 * \a BondGraph::BondThreshold.
318 */
319 bool operator!=(const BondGraph &other) const {
320 return !(*this == other);
321 }
322
323private:
324
325 /** Returns the BondLengthMatrix entry for a given index pair.
326 * \param firstelement index/atom number of first element (row index)
327 * \param secondelement index/atom number of second element (column index)
328 * \note matrix is of course symmetric.
329 */
330 double GetBondLength(
331 int firstelement,
332 int secondelement) const;
333
334 /** Returns bond criterion for given pair based on a bond length matrix.
335 * This calls either the covalent or the bond matrix criterion.
336 * \param *Walker first BondedParticle
337 * \param *OtherWalker second BondedParticle
338 * \return Range with bond interval
339 */
340 range<double> getMinMaxDistance(
341 const element * const Walker,
342 const element * const OtherWalker) const;
343
344 /** Returns bond criterion for given pair of elements based on a bond length matrix.
345 * The matrix should be contained in \a this BondGraph and contain an element-
346 * to-element length.
347 * \param *Walker first element
348 * \param *OtherWalker second element
349 * \return Range with bond interval
350 */
351 range<double> BondLengthMatrixMinMaxDistance(
352 const element * const Walker,
353 const element * const OtherWalker) const;
354
355 /** Returns bond criterion for given pair of elements based on covalent radius.
356 * \param *Walker first element
357 * \param *OtherWalker second element
358 * \return Range with bond interval
359 */
360 range<double> CovalentMinMaxDistance(
361 const element * const Walker,
362 const element * const OtherWalker) const;
363
364
365 /** Resets the bond::BondDegree of all atoms in the set to 1.
366 *
367 * @param Set Range with atoms
368 */
369 template <class container_type,
370 class iterator_type,
371 class const_iterator_type>
372 void resetBondDegree(
373 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
374 {
375 // reset bond degrees
376 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
377 (*AtomRunner)->resetBondDegree();
378 }
379 }
380
381 /** Calculates the bond degree for each atom on the set.
382 *
383 * @param Set Range with atoms
384 * @return number of non-matching bonds
385 */
386 template <class container_type,
387 class iterator_type,
388 class const_iterator_type>
389 int calculateBondDegree(
390 AtomSetMixin<container_type,iterator_type,const_iterator_type> &Set) const
391 {
392 //DoLog(1) && (Log() << Verbose(1) << "Correcting Bond degree of each bond ... " << endl);
393 int No = 0, OldNo = -1;
394 do {
395 OldNo = No;
396 No=0;
397 for(iterator_type AtomRunner = Set.begin(); AtomRunner != Set.end(); ++AtomRunner) {
398 No+=(*AtomRunner)->CorrectBondDegree();
399 }
400 } while (OldNo != No);
401 //DoLog(0) && (Log() << Verbose(0) << " done." << endl);
402 return No;
403 }
404
405 bool operator==(const periodentafel &other) const;
406
407 bool operator!=(const periodentafel &other) const {
408 return !(*this == other);
409 }
410
411private:
412 // default constructor for serialization
413 BondGraph();
414
415 friend class boost::serialization::access;
416 // serialization
417 template<class Archive>
418 void serialize(Archive & ar, const unsigned int version)
419 {
420 //ar & const_cast<double &>(BondThreshold);
421 ar & BondLengthMatrix;
422 ar & IsAngstroem;
423 }
424
425 //!> half width of the interval for allowed bond distances
426 static const double BondThreshold;
427 //!> Matrix with bond lenth per two elements
428 MatrixContainer *BondLengthMatrix;
429 //!> distance units are angstroem (true), bohr radii (false)
430 bool IsAngstroem;
431};
432
433#endif /* BONDGRAPH_HPP_ */
Note: See TracBrowser for help on using the repository browser.