source: src/Fragmentation/PowerSetGenerator.cpp@ 917be8

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 917be8 was 0aa122, checked in by Frederik Heber <heber@…>, 13 years ago

Updated all source files's copyright note to current year 2012.

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