source: src/Fragmentation/PowerSetGenerator.cpp@ 246e13

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 246e13 was 212c179, checked in by Frederik Heber <heber@…>, 14 years ago

Placed all functions related to BondsPerSPList into own class BondsPerShortestPath.

  • Property mode set to 100644
File size: 14.2 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * PowerSetGenerator.cpp
10 *
11 * Created on: Oct 18, 2011
12 * Author: heber
13 */
14
15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
20#include "CodePatterns/MemDebug.hpp"
21
22#include "PowerSetGenerator.hpp"
23
24#include "CodePatterns/Log.hpp"
25
26#include "atom.hpp"
27#include "Bond/bond.hpp"
28#include "Fragmentation/UniqueFragments.hpp"
29
30/** Constructor of class PowerSetGenerator.
31 *
32 */
33PowerSetGenerator::PowerSetGenerator(class UniqueFragments *_FragmentSearch, int Order) :
34 BondsPerSPList(Order),
35 FragmentSearch(_FragmentSearch)
36{}
37
38/** Destructor of class PowerSetGenerator.
39 *
40 */
41PowerSetGenerator::~PowerSetGenerator()
42{
43 FragmentSearch = NULL;
44}
45
46/** Clears the touched list
47 * \param verbosity verbosity level
48 * \param *&TouchedList touched list
49 * \param SubOrder current suborder
50 * \param TouchedIndex currently touched
51 */
52void PowerSetGenerator::ClearingTouched(int verbosity, int *&TouchedList, int SubOrder, int &TouchedIndex)
53{
54 Log() << Verbose(1+verbosity) << "Clearing touched list." << endl;
55 for (TouchedIndex=SubOrder+1;TouchedIndex--;) // empty touched list
56 TouchedList[TouchedIndex] = -1;
57 TouchedIndex = 0;
58
59}
60
61/** Adds the current combination of the power set to the snake stack.
62 * \param verbosity verbosity level
63 * \param CurrentCombination
64 * \param SetDimension maximum number of bits in power set
65 * \param *FragmentSet snake stack to remove from
66 * \param &BondsSet set of bonds
67 * \param *&TouchedList touched list
68 * \param TouchedIndex currently touched
69 * \return number of set bits
70 */
71int PowerSetGenerator::AddPowersetToSnakeStack(int verbosity, int CurrentCombination, int SetDimension, KeySet *FragmentSet, std::vector<bond *> &BondsSet, int *&TouchedList, int &TouchedIndex)
72{
73 atom *OtherWalker = NULL;
74 bool bit = false;
75 KeySetTestPair TestKeySetInsert;
76
77 int Added = 0;
78 for (int j=0;j<SetDimension;j++) { // pull out every bit by shifting
79 bit = ((CurrentCombination & (1 << j)) != 0); // mask the bit for the j-th bond
80 if (bit) { // if bit is set, we add this bond partner
81 OtherWalker = BondsSet[j]->rightatom; // rightatom is always the one more distant, i.e. the one to add
82 //Log() << Verbose(1+verbosity) << "Current Bond is " << BondsSet[j] << ", checking on " << *OtherWalker << "." << endl;
83 Log() << Verbose(2+verbosity) << "Adding " << *OtherWalker << " with nr " << OtherWalker->getNr() << "." << endl;
84 TestKeySetInsert = FragmentSet->insert(OtherWalker->getNr());
85 if (TestKeySetInsert.second) {
86 TouchedList[TouchedIndex++] = OtherWalker->getNr(); // note as added
87 Added++;
88 } else {
89 Log() << Verbose(2+verbosity) << "This was item was already present in the keyset." << endl;
90 }
91 } else {
92 Log() << Verbose(2+verbosity) << "Not adding." << endl;
93 }
94 }
95 return Added;
96};
97
98/** Counts the number of elements in a power set.
99 * \param SetFirst begin iterator first bond
100 * \param SetLast end iterator
101 * \param *&TouchedList touched list
102 * \param TouchedIndex currently touched
103 * \return number of elements
104 */
105int PowerSetGenerator::CountSetMembers(std::list<bond *>::const_iterator SetFirst, std::list<bond *>::const_iterator SetLast, int *&TouchedList, int TouchedIndex)
106{
107 int SetDimension = 0;
108 for( std::list<bond *>::const_iterator Binder = SetFirst;
109 Binder != SetLast;
110 ++Binder) {
111 for (int k=TouchedIndex;k--;) {
112 if ((*Binder)->Contains(TouchedList[k])) // if we added this very endpiece
113 SetDimension++;
114 }
115 }
116 return SetDimension;
117};
118
119/** Fills a list of bonds from another
120 * \param *BondsList bonds array/vector to fill
121 * \param SetFirst begin iterator first bond
122 * \param SetLast end iterator
123 * \param *&TouchedList touched list
124 * \param TouchedIndex currently touched
125 * \return number of elements
126 */
127int PowerSetGenerator::FillBondsList(std::vector<bond *> &BondsList, std::list<bond *>::const_iterator SetFirst, std::list<bond *>::const_iterator SetLast, int *&TouchedList, int TouchedIndex)
128{
129 int SetDimension = 0;
130 for( std::list<bond *>::const_iterator Binder = SetFirst;
131 Binder != SetLast;
132 ++Binder) {
133 for (int k=0;k<TouchedIndex;k++) {
134 if ((*Binder)->leftatom->getNr() == TouchedList[k]) // leftatom is always the closer one
135 BondsList[SetDimension++] = (*Binder);
136 }
137 }
138 return SetDimension;
139};
140
141/** Remove all items that were added on this SP level.
142 * \param verbosity verbosity level
143 * \param *FragmentSet snake stack to remove from
144 * \param *&TouchedList touched list
145 * \param TouchedIndex currently touched
146 */
147void PowerSetGenerator::RemoveAllTouchedFromSnakeStack(int verbosity, KeySet *FragmentSet, int *&TouchedList, int &TouchedIndex)
148{
149 int Removal = 0;
150 for(int j=0;j<TouchedIndex;j++) {
151 Removal = TouchedList[j];
152 Log() << Verbose(2+verbosity) << "Removing item nr. " << Removal << " from snake stack." << endl;
153 FragmentSet->erase(Removal);
154 TouchedList[j] = -1;
155 }
156 DoLog(2) && (Log() << Verbose(2) << "Remaining local nr.s on snake stack are: ");
157 for(KeySet::iterator runner = FragmentSet->begin(); runner != FragmentSet->end(); runner++)
158 DoLog(0) && (Log() << Verbose(0) << (*runner) << " ");
159 DoLog(0) && (Log() << Verbose(0) << endl);
160 TouchedIndex = 0; // set Index to 0 for list of atoms added on this level
161};
162
163
164/** Creates a list of all unique fragments of certain vertex size from a given graph \a Fragment for a given root vertex in the context of \a this molecule.
165 * -# initialises UniqueFragments structure
166 * -# fills edge list via BFS
167 * -# creates the fragment by calling recursive function SPFragmentGenerator with UniqueFragments structure, 0 as
168 root distance, the edge set, its dimension and the current suborder
169 * -# Free'ing structure
170 * Note that we may use the fact that the atoms are SP-ordered on the atomstack. I.e. when popping always the last, we first get all
171 * with SP of 2, then those with SP of 3, then those with SP of 4 and so on.
172 * \param RestrictedKeySet Restricted vertex set to use in context of molecule
173 * \return number of inserted fragments
174 * \note ShortestPathList in FragmentSearch structure is probably due to NumberOfAtomsSPLevel and SP not needed anymore
175 */
176int PowerSetGenerator::operator()(KeySet &RestrictedKeySet)
177{
178 int Counter = FragmentSearch->FragmentCounter; // mark current value of counter
179
180 DoLog(0) && (Log() << Verbose(0) << endl);
181 DoLog(0) && (Log() << Verbose(0) << "Begin of PowerSetGenerator with order " << BondsPerSPList.getOrder() << " at Root " << *FragmentSearch->getRoot() << "." << endl);
182
183 BondsPerSPList.SetSPList(FragmentSearch->getRoot());
184
185 // do a BFS search to fill the SP lists and label the found vertices
186 BondsPerSPList.FillSPListandLabelVertices(FragmentSearch->getRoot()->GetTrueFather()->getNr(), RestrictedKeySet);
187
188 // outputting all list for debugging
189 BondsPerSPList.OutputSPList();
190
191 // creating fragments with the found edge sets (may be done in reverse order, faster)
192 int SP = BondsPerSPList.CountNumbersInBondsList();
193 DoLog(0) && (Log() << Verbose(0) << "Total number of edges is " << SP << "." << endl);
194 if (SP >= (BondsPerSPList.getOrder()-1)) {
195 // start with root (push on fragment stack)
196 DoLog(0) && (Log() << Verbose(0) << "Starting fragment generation with " << *FragmentSearch->getRoot() << ", local nr is " << FragmentSearch->getRoot()->getNr() << "." << endl);
197 FragmentSearch->FragmentSet->clear();
198 DoLog(0) && (Log() << Verbose(0) << "Preparing subset for this root and calling generator." << endl);
199
200 // prepare the subset and call the generator
201 std::vector<bond*> BondsList;
202 BondsList.resize(BondsPerSPList.BondsPerSPCount[0]);
203 ASSERT(BondsPerSPList.BondsPerSPList[0].size() != 0,
204 "molecule::PowerSetGenerator() - BondsPerSPList.BondsPerSPList[0] contains no root bond.");
205 BondsList[0] = (*BondsPerSPList.BondsPerSPList[0].begin()); // on SP level 0 there's only the root bond
206
207 SPFragmentGenerator(0, BondsList, BondsPerSPList.BondsPerSPCount[0], BondsPerSPList.getOrder());
208 } else {
209 DoLog(0) && (Log() << Verbose(0) << "Not enough total number of edges to build " << BondsPerSPList.getOrder() << "-body fragments." << endl);
210 }
211
212 // as FragmentSearch structure is used only once, we don't have to clean it anymore
213 // remove root from stack
214 DoLog(0) && (Log() << Verbose(0) << "Removing root again from stack." << endl);
215 FragmentSearch->FragmentSet->erase(FragmentSearch->getRoot()->getNr());
216
217 // free'ing the bonds lists
218 BondsPerSPList.ResetSPList();
219
220 // return list
221 DoLog(0) && (Log() << Verbose(0) << "End of PowerSetGenerator." << endl);
222 return (FragmentSearch->FragmentCounter - Counter);
223};
224
225/** From a given set of Bond sorted by Shortest Path distance, create all possible fragments of size \a SetDimension.
226 * -# loops over every possible combination (2^dimension of edge set)
227 * -# inserts current set, if there's still space left
228 * -# yes: calls SPFragmentGenerator with structure, created new edge list and size respective to root dist
229ance+1
230 * -# no: stores fragment into keyset list by calling InsertFragmentIntoGraph
231 * -# removes all items added into the snake stack (in UniqueFragments structure) added during level (root
232distance) and current set
233 * \param RootDistance current shortest path level, whose set of edges is represented by **BondsSet
234 * \param BondsSet array of bonds to check
235 * \param SetDimension Number of possible bonds on this level (i.e. size of the array BondsSet[])
236 * \param SubOrder remaining number of allowed vertices to add
237 */
238void PowerSetGenerator::SPFragmentGenerator(int RootDistance, std::vector<bond *> &BondsSet, int SetDimension, int SubOrder)
239{
240 int verbosity = 0; //FragmentSearch->ANOVAOrder-SubOrder;
241 int NumCombinations;
242 int bits, TouchedIndex, SubSetDimension, SP, Added;
243 int SpaceLeft;
244 int *TouchedList = new int[SubOrder + 1];
245 KeySetTestPair TestKeySetInsert;
246
247 NumCombinations = 1 << SetDimension;
248
249 // here for all bonds of Walker all combinations of end pieces (from the bonds)
250 // have to be added and for the remaining ANOVA order GraphCrawler be called
251 // recursively for the next level
252
253 Log() << Verbose(1+verbosity) << "Begin of SPFragmentGenerator." << endl;
254 Log() << Verbose(1+verbosity) << "We are " << RootDistance << " away from Root, which is " << *FragmentSearch->getRoot() << ", SubOrder is " << SubOrder << ", SetDimension is " << SetDimension << " and this means " << NumCombinations-1 << " combination(s)." << endl;
255
256 // initialised touched list (stores added atoms on this level)
257 ClearingTouched(verbosity, TouchedList, SubOrder, TouchedIndex);
258
259 // create every possible combination of the endpieces
260 Log() << Verbose(1+verbosity) << "Going through all combinations of the power set." << endl;
261 for (int i=1;i<NumCombinations;i++) { // sweep through all power set combinations (skip empty set!)
262 // count the set bit of i
263 bits = 0;
264 for (int j=SetDimension;j--;)
265 bits += (i & (1 << j)) >> j;
266
267 Log() << Verbose(1+verbosity) << "Current set is " << Binary(i | (1 << SetDimension)) << ", number of bits is " << bits << "." << endl;
268 if (bits <= SubOrder) { // if not greater than additional atoms allowed on stack, continue
269 // --1-- add this set of the power set of bond partners to the snake stack
270 Added = AddPowersetToSnakeStack(verbosity, i, SetDimension, FragmentSearch->FragmentSet, BondsSet, TouchedList, TouchedIndex);
271
272 SpaceLeft = SubOrder - Added ;// SubOrder - bits; // due to item's maybe being already present, this does not work anymore
273 if (SpaceLeft > 0) {
274 Log() << Verbose(1+verbosity) << "There's still some space left on stack: " << SpaceLeft << "." << endl;
275 if (SubOrder > 1) { // Due to Added above we have to check extra whether we're not already reaching beyond the desired Order
276 // --2-- look at all added end pieces of this combination, construct bond subsets and sweep through a power set of these by recursion
277 SP = RootDistance+1; // this is the next level
278
279 // first count the members in the subset
280 SubSetDimension = CountSetMembers(BondsPerSPList.BondsPerSPList[SP].begin(), BondsPerSPList.BondsPerSPList[SP].end(), TouchedList, TouchedIndex);
281
282 // then allocate and fill the list
283 std::vector<bond *> BondsList;
284 BondsList.resize(SubSetDimension);
285 SubSetDimension = FillBondsList(BondsList, BondsPerSPList.BondsPerSPList[SP].begin(), BondsPerSPList.BondsPerSPList[SP].end(), TouchedList, TouchedIndex);
286
287 // then iterate
288 Log() << Verbose(2+verbosity) << "Calling subset generator " << SP << " away from root " << *FragmentSearch->getRoot() << " with sub set dimension " << SubSetDimension << "." << endl;
289 SPFragmentGenerator(SP, BondsList, SubSetDimension, SubOrder-bits);
290 }
291 } else {
292 // --2-- otherwise store the complete fragment
293 Log() << Verbose(1+verbosity) << "Enough items on stack for a fragment!" << endl;
294 // store fragment as a KeySet
295 DoLog(2) && (Log() << Verbose(2) << "Found a new fragment[" << FragmentSearch->FragmentCounter << "], local nr.s are: ");
296 for(KeySet::iterator runner = FragmentSearch->FragmentSet->begin(); runner != FragmentSearch->FragmentSet->end(); runner++)
297 DoLog(0) && (Log() << Verbose(0) << (*runner) << " ");
298 DoLog(0) && (Log() << Verbose(0) << endl);
299 FragmentSearch->InsertFragmentIntoGraph();
300 }
301
302 // --3-- remove all added items in this level from snake stack
303 Log() << Verbose(1+verbosity) << "Removing all items that were added on this SP level " << RootDistance << "." << endl;
304 RemoveAllTouchedFromSnakeStack(verbosity, FragmentSearch->FragmentSet, TouchedList, TouchedIndex);
305 } else {
306 Log() << Verbose(2+verbosity) << "More atoms to add for this set (" << bits << ") than space left on stack " << SubOrder << ", skipping this set." << endl;
307 }
308 }
309 delete[](TouchedList);
310 Log() << Verbose(1+verbosity) << "End of SPFragmentGenerator, " << RootDistance << " away from Root " << *FragmentSearch->getRoot() << " and SubOrder is " << SubOrder << "." << endl;
311};
Note: See TracBrowser for help on using the repository browser.