source: src/Fragmentation/PowerSetGenerator.cpp@ 730d7a

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

Extracted KeySet from graph.hpp and made into distinct class.

  • member function operator<() replaces former KeyCompare struct.
  • 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/KeySet.hpp"
29#include "Fragmentation/UniqueFragments.hpp"
30
31/** Constructor of class PowerSetGenerator.
32 *
33 */
34PowerSetGenerator::PowerSetGenerator(class UniqueFragments *_FragmentSearch, int Order) :
35 BondsPerSPList(Order),
36 FragmentSearch(_FragmentSearch)
37{}
38
39/** Destructor of class PowerSetGenerator.
40 *
41 */
42PowerSetGenerator::~PowerSetGenerator()
43{
44 FragmentSearch = NULL;
45}
46
47/** Clears the touched list
48 * \param verbosity verbosity level
49 * \param *&TouchedList touched list
50 * \param SubOrder current suborder
51 * \param TouchedIndex currently touched
52 */
53void PowerSetGenerator::ClearingTouched(int verbosity, int *&TouchedList, int SubOrder, int &TouchedIndex)
54{
55 Log() << Verbose(1+verbosity) << "Clearing touched list." << endl;
56 for (TouchedIndex=SubOrder+1;TouchedIndex--;) // empty touched list
57 TouchedList[TouchedIndex] = -1;
58 TouchedIndex = 0;
59
60}
61
62/** Adds the current combination of the power set to the snake stack.
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 verbosity verbosity level
144 * \param *FragmentSet snake stack to remove from
145 * \param *&TouchedList touched list
146 * \param TouchedIndex currently touched
147 */
148void PowerSetGenerator::RemoveAllTouchedFromSnakeStack(int verbosity, KeySet *FragmentSet, int *&TouchedList, int &TouchedIndex)
149{
150 int Removal = 0;
151 for(int j=0;j<TouchedIndex;j++) {
152 Removal = TouchedList[j];
153 Log() << Verbose(2+verbosity) << "Removing item nr. " << Removal << " from snake stack." << endl;
154 FragmentSet->erase(Removal);
155 TouchedList[j] = -1;
156 }
157 DoLog(2) && (Log() << Verbose(2) << "Remaining local nr.s on snake stack are: ");
158 for(KeySet::iterator runner = FragmentSet->begin(); runner != FragmentSet->end(); runner++)
159 DoLog(0) && (Log() << Verbose(0) << (*runner) << " ");
160 DoLog(0) && (Log() << Verbose(0) << endl);
161 TouchedIndex = 0; // set Index to 0 for list of atoms added on this level
162};
163
164
165/** 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.
166 * -# initialises UniqueFragments structure
167 * -# fills edge list via BFS
168 * -# creates the fragment by calling recursive function SPFragmentGenerator with UniqueFragments structure, 0 as
169 root distance, the edge set, its dimension and the current suborder
170 * -# Free'ing structure
171 * 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
172 * with SP of 2, then those with SP of 3, then those with SP of 4 and so on.
173 * \param RestrictedKeySet Restricted vertex set to use in context of molecule
174 * \return number of inserted fragments
175 * \note ShortestPathList in FragmentSearch structure is probably due to NumberOfAtomsSPLevel and SP not needed anymore
176 */
177int PowerSetGenerator::operator()(KeySet &RestrictedKeySet)
178{
179 int Counter = FragmentSearch->FragmentCounter; // mark current value of counter
180
181 DoLog(0) && (Log() << Verbose(0) << endl);
182 DoLog(0) && (Log() << Verbose(0) << "Begin of PowerSetGenerator with order " << BondsPerSPList.getOrder() << " at Root " << *FragmentSearch->getRoot() << "." << endl);
183
184 BondsPerSPList.SetSPList(FragmentSearch->getRoot());
185
186 // do a BFS search to fill the SP lists and label the found vertices
187 BondsPerSPList.FillSPListandLabelVertices(FragmentSearch->getRoot()->GetTrueFather()->getNr(), RestrictedKeySet);
188
189 // outputting all list for debugging
190 BondsPerSPList.OutputSPList();
191
192 // creating fragments with the found edge sets (may be done in reverse order, faster)
193 int SP = BondsPerSPList.CountNumbersInBondsList();
194 DoLog(0) && (Log() << Verbose(0) << "Total number of edges is " << SP << "." << endl);
195 if (SP >= (BondsPerSPList.getOrder()-1)) {
196 // start with root (push on fragment stack)
197 DoLog(0) && (Log() << Verbose(0) << "Starting fragment generation with " << *FragmentSearch->getRoot() << ", local nr is " << FragmentSearch->getRoot()->getNr() << "." << endl);
198 FragmentSearch->FragmentSet->clear();
199 DoLog(0) && (Log() << Verbose(0) << "Preparing subset for this root and calling generator." << endl);
200
201 // prepare the subset and call the generator
202 std::vector<bond*> BondsList;
203 BondsList.resize(BondsPerSPList.BondsPerSPCount[0]);
204 ASSERT(BondsPerSPList.BondsPerSPList[0].size() != 0,
205 "molecule::PowerSetGenerator() - BondsPerSPList.BondsPerSPList[0] contains no root bond.");
206 BondsList[0] = (*BondsPerSPList.BondsPerSPList[0].begin()); // on SP level 0 there's only the root bond
207
208 SPFragmentGenerator(0, BondsList, BondsPerSPList.BondsPerSPCount[0], BondsPerSPList.getOrder());
209 } else {
210 DoLog(0) && (Log() << Verbose(0) << "Not enough total number of edges to build " << BondsPerSPList.getOrder() << "-body fragments." << endl);
211 }
212
213 // as FragmentSearch structure is used only once, we don't have to clean it anymore
214 // remove root from stack
215 DoLog(0) && (Log() << Verbose(0) << "Removing root again from stack." << endl);
216 FragmentSearch->FragmentSet->erase(FragmentSearch->getRoot()->getNr());
217
218 // free'ing the bonds lists
219 BondsPerSPList.ResetSPList();
220
221 // return list
222 DoLog(0) && (Log() << Verbose(0) << "End of PowerSetGenerator." << endl);
223 return (FragmentSearch->FragmentCounter - Counter);
224};
225
226/** From a given set of Bond sorted by Shortest Path distance, create all possible fragments of size \a SetDimension.
227 * -# loops over every possible combination (2^dimension of edge set)
228 * -# inserts current set, if there's still space left
229 * -# yes: calls SPFragmentGenerator with structure, created new edge list and size respective to root dist
230ance+1
231 * -# no: stores fragment into keyset list by calling InsertFragmentIntoGraph
232 * -# removes all items added into the snake stack (in UniqueFragments structure) added during level (root
233distance) and current set
234 * \param RootDistance current shortest path level, whose set of edges is represented by **BondsSet
235 * \param BondsSet array of bonds to check
236 * \param SetDimension Number of possible bonds on this level (i.e. size of the array BondsSet[])
237 * \param SubOrder remaining number of allowed vertices to add
238 */
239void PowerSetGenerator::SPFragmentGenerator(int RootDistance, std::vector<bond *> &BondsSet, int SetDimension, int SubOrder)
240{
241 int verbosity = 0; //FragmentSearch->ANOVAOrder-SubOrder;
242 int NumCombinations;
243 int bits, TouchedIndex, SubSetDimension, SP, Added;
244 int SpaceLeft;
245 int *TouchedList = new int[SubOrder + 1];
246 KeySetTestPair TestKeySetInsert;
247
248 NumCombinations = 1 << SetDimension;
249
250 // here for all bonds of Walker all combinations of end pieces (from the bonds)
251 // have to be added and for the remaining ANOVA order GraphCrawler be called
252 // recursively for the next level
253
254 Log() << Verbose(1+verbosity) << "Begin of SPFragmentGenerator." << endl;
255 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;
256
257 // initialised touched list (stores added atoms on this level)
258 ClearingTouched(verbosity, TouchedList, SubOrder, TouchedIndex);
259
260 // create every possible combination of the endpieces
261 Log() << Verbose(1+verbosity) << "Going through all combinations of the power set." << endl;
262 for (int i=1;i<NumCombinations;i++) { // sweep through all power set combinations (skip empty set!)
263 // count the set bit of i
264 bits = 0;
265 for (int j=SetDimension;j--;)
266 bits += (i & (1 << j)) >> j;
267
268 Log() << Verbose(1+verbosity) << "Current set is " << Binary(i | (1 << SetDimension)) << ", number of bits is " << bits << "." << endl;
269 if (bits <= SubOrder) { // if not greater than additional atoms allowed on stack, continue
270 // --1-- add this set of the power set of bond partners to the snake stack
271 Added = AddPowersetToSnakeStack(verbosity, i, SetDimension, FragmentSearch->FragmentSet, BondsSet, TouchedList, TouchedIndex);
272
273 SpaceLeft = SubOrder - Added ;// SubOrder - bits; // due to item's maybe being already present, this does not work anymore
274 if (SpaceLeft > 0) {
275 Log() << Verbose(1+verbosity) << "There's still some space left on stack: " << SpaceLeft << "." << endl;
276 if (SubOrder > 1) { // Due to Added above we have to check extra whether we're not already reaching beyond the desired Order
277 // --2-- look at all added end pieces of this combination, construct bond subsets and sweep through a power set of these by recursion
278 SP = RootDistance+1; // this is the next level
279
280 // first count the members in the subset
281 SubSetDimension = CountSetMembers(BondsPerSPList.BondsPerSPList[SP].begin(), BondsPerSPList.BondsPerSPList[SP].end(), TouchedList, TouchedIndex);
282
283 // then allocate and fill the list
284 std::vector<bond *> BondsList;
285 BondsList.resize(SubSetDimension);
286 SubSetDimension = FillBondsList(BondsList, BondsPerSPList.BondsPerSPList[SP].begin(), BondsPerSPList.BondsPerSPList[SP].end(), TouchedList, TouchedIndex);
287
288 // then iterate
289 Log() << Verbose(2+verbosity) << "Calling subset generator " << SP << " away from root " << *FragmentSearch->getRoot() << " with sub set dimension " << SubSetDimension << "." << endl;
290 SPFragmentGenerator(SP, BondsList, SubSetDimension, SubOrder-bits);
291 }
292 } else {
293 // --2-- otherwise store the complete fragment
294 Log() << Verbose(1+verbosity) << "Enough items on stack for a fragment!" << endl;
295 // store fragment as a KeySet
296 DoLog(2) && (Log() << Verbose(2) << "Found a new fragment[" << FragmentSearch->FragmentCounter << "], local nr.s are: ");
297 for(KeySet::iterator runner = FragmentSearch->FragmentSet->begin(); runner != FragmentSearch->FragmentSet->end(); runner++)
298 DoLog(0) && (Log() << Verbose(0) << (*runner) << " ");
299 DoLog(0) && (Log() << Verbose(0) << endl);
300 FragmentSearch->InsertFragmentIntoGraph();
301 }
302
303 // --3-- remove all added items in this level from snake stack
304 Log() << Verbose(1+verbosity) << "Removing all items that were added on this SP level " << RootDistance << "." << endl;
305 RemoveAllTouchedFromSnakeStack(verbosity, FragmentSearch->FragmentSet, TouchedList, TouchedIndex);
306 } else {
307 Log() << Verbose(2+verbosity) << "More atoms to add for this set (" << bits << ") than space left on stack " << SubOrder << ", skipping this set." << endl;
308 }
309 }
310 delete[](TouchedList);
311 Log() << Verbose(1+verbosity) << "End of SPFragmentGenerator, " << RootDistance << " away from Root " << *FragmentSearch->getRoot() << " and SubOrder is " << SubOrder << "." << endl;
312};
Note: See TracBrowser for help on using the repository browser.