source: src/Fragmentation/PowerSetGenerator.cpp@ d0b375b

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

Extracted power set generation into own class PowerSetGenerator.

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