source: src/Graph/DepthFirstSearchAnalysis.cpp@ 47d041

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

HUGE: Removed all calls to Log(), eLog(), replaced by LOG() and ELOG().

  • Replaced DoLog(.) && (Log() << Verbose(.) << ... << std::endl) by Log(., ...).
  • Replaced Log() << Verbose(.) << .. << by Log(., ...)
  • on multiline used stringstream to generate and message which was finally used in LOG(., output.str())
  • there should be no more occurence of Log(). LOG() and ELOG() must be used instead.
  • Eventually, this will allow for storing all errors and re-printing them on program exit which would be very helpful to ascertain error-free runs for the user.
  • Property mode set to 100644
File size: 16.4 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 * DepthFirstSearchAnalysis.cpp
10 *
11 * Created on: Feb 16, 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 "DepthFirstSearchAnalysis.hpp"
23
24#include <algorithm>
25#include <functional>
26
27#include "atom.hpp"
28#include "Bond/bond.hpp"
29#include "CodePatterns/Assert.hpp"
30#include "CodePatterns/Info.hpp"
31#include "CodePatterns/Log.hpp"
32#include "CodePatterns/Verbose.hpp"
33#include "Descriptors/AtomDescriptor.hpp"
34#include "molecule.hpp"
35#include "MoleculeLeafClass.hpp"
36#include "MoleculeListClass.hpp"
37#include "World.hpp"
38
39DepthFirstSearchAnalysis::DepthFirstSearchAnalysis() :
40 CurrentGraphNr(0),
41 ComponentNumber(0),
42 BackStepping(false)
43{
44 ResetAllBondsToUnused();
45}
46
47DepthFirstSearchAnalysis::~DepthFirstSearchAnalysis()
48{}
49
50void DepthFirstSearchAnalysis::Init()
51{
52 CurrentGraphNr = 0;
53 ComponentNumber = 0;
54 BackStepping = false;
55 std::for_each(World::getInstance().getAtomIter(),World::getInstance().atomEnd(),
56 std::mem_fun(&atom::resetGraphNr));
57 std::for_each(World::getInstance().getAtomIter(),World::getInstance().atomEnd(),
58 std::mem_fun(&atom::InitComponentNr));
59}
60
61
62bond * DepthFirstSearchAnalysis::FindNextUnused(atom *vertex) const
63{
64 const BondList& ListOfBonds = vertex->getListOfBonds();
65 for (BondList::const_iterator Runner = ListOfBonds.begin();
66 Runner != ListOfBonds.end();
67 ++Runner)
68 if ((*Runner)->IsUsed() == GraphEdge::white)
69 return ((*Runner));
70 return NULL;
71}
72
73
74void DepthFirstSearchAnalysis::ResetAllBondsToUnused() const
75{
76 World::AtomComposite allatoms = World::getInstance().getAllAtoms();
77 for(World::AtomComposite::const_iterator AtomRunner = allatoms.begin();
78 AtomRunner != allatoms.end();
79 ++AtomRunner) {
80 const BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
81 for(BondList::const_iterator BondRunner = ListOfBonds.begin();
82 BondRunner != ListOfBonds.end();
83 ++BondRunner)
84 if ((*BondRunner)->leftatom == *AtomRunner)
85 (*BondRunner)->ResetUsed();
86 }
87}
88
89void DepthFirstSearchAnalysis::SetNextComponentNumber(atom *vertex, int nr) const
90{
91 size_t i = 0;
92 ASSERT(vertex != NULL,
93 "DepthFirstSearchAnalysis::SetNextComponentNumber() - Given vertex is NULL!");
94 const BondList& ListOfBonds = vertex->getListOfBonds();
95 for (; i < ListOfBonds.size(); i++) {
96 if (vertex->ComponentNr[i] == -1) { // check if not yet used
97 vertex->ComponentNr[i] = nr;
98 break;
99 } else if (vertex->ComponentNr[i] == nr) // if number is already present, don't add another time
100 break; // breaking here will not cause error!
101 }
102 ASSERT(i < ListOfBonds.size(),
103 "DepthFirstSearchAnalysis::SetNextComponentNumber() - All Component entries are already occupied!");
104}
105
106
107bool DepthFirstSearchAnalysis::PickLocalBackEdges(atom **ListOfLocalAtoms, std::deque<bond *> *&LocalStack) const
108{
109 bool status = true;
110 if (BackEdgeStack.empty()) {
111 ELOG(1, "Reference BackEdgeStack is empty!");
112 return false;
113 }
114 bond *Binder = BackEdgeStack.front();
115 bond *FirstBond = Binder; // mark the first bond, so that we don't loop through the stack indefinitely
116 atom *Walker = NULL, *OtherAtom = NULL;
117
118 do { // go through all bonds and push local ones
119 Walker = ListOfLocalAtoms[Binder->leftatom->getNr()]; // get one atom in the reference molecule
120 if (Walker != NULL) { // if this Walker exists in the subgraph ...
121 const BondList& ListOfBonds = Walker->getListOfBonds();
122 for (BondList::const_iterator Runner = ListOfBonds.begin();
123 Runner != ListOfBonds.end();
124 ++Runner) {
125 OtherAtom = (*Runner)->GetOtherAtom(Walker);
126 if (OtherAtom == ListOfLocalAtoms[(*Runner)->rightatom->getNr()]) { // found the bond
127 LocalStack->push_front((*Runner));
128 LOG(3, "INFO: Found local edge " << *(*Runner) << ".");
129 break;
130 }
131 }
132 }
133 ASSERT(!BackEdgeStack.empty(), "DepthFirstSearchAnalysis::PickLocalBackEdges() - ReferenceStack is empty!");
134 Binder = BackEdgeStack.front(); // loop the stack for next item
135 LOG(3, "Current candidate edge " << Binder << ".");
136 } while (FirstBond != Binder);
137
138 return status;
139}
140
141
142
143void DepthFirstSearchAnalysis::OutputGraphInfoPerAtom() const
144{
145 LOG(1, "Final graph info for each atom is:");
146 World::AtomComposite allatoms = World::getInstance().getAllAtoms();
147 for_each(allatoms.begin(),allatoms.end(),mem_fun(&atom::OutputGraphInfo));
148}
149
150
151void DepthFirstSearchAnalysis::OutputGraphInfoPerBond() const
152{
153 LOG(1, "Final graph info for each bond is:");
154 World::AtomComposite allatoms = World::getInstance().getAllAtoms();
155 for(World::AtomComposite::const_iterator AtomRunner = allatoms.begin();
156 AtomRunner != allatoms.end();
157 ++AtomRunner) {
158 const BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
159 for(BondList::const_iterator BondRunner = ListOfBonds.begin();
160 BondRunner != ListOfBonds.end();
161 ++BondRunner)
162 if ((*BondRunner)->leftatom == *AtomRunner) {
163 const bond *Binder = *BondRunner;
164 if (DoLog(2)) {
165 std::stringstream output;
166 output << ((Binder->Type == GraphEdge::TreeEdge) ? "TreeEdge " : "BackEdge ") << *Binder << ": <";
167 output << ((Binder->leftatom->SeparationVertex) ? "SP," : "") << "L" << Binder->leftatom->LowpointNr << " G" << Binder->leftatom->GraphNr << " Comp.";
168 Binder->leftatom->OutputComponentNumber(&output);
169 output << " === ";
170 output << ((Binder->rightatom->SeparationVertex) ? "SP," : "") << "L" << Binder->rightatom->LowpointNr << " G" << Binder->rightatom->GraphNr << " Comp.";
171 Binder->rightatom->OutputComponentNumber(&output);
172 output << ">.";
173 LOG(2, output.str());
174 }
175 if (Binder->Cyclic) // cyclic ??
176 LOG(3, "Lowpoint at each side are equal: CYCLIC!");
177 }
178 }
179}
180
181
182unsigned int DepthFirstSearchAnalysis::CyclicBondAnalysis() const
183{
184 unsigned int NoCyclicBonds = 0;
185 World::AtomComposite allatoms = World::getInstance().getAllAtoms();
186 for(World::AtomComposite::const_iterator AtomRunner = allatoms.begin();
187 AtomRunner != allatoms.end();
188 ++AtomRunner) {
189 const BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
190 for(BondList::const_iterator BondRunner = ListOfBonds.begin();
191 BondRunner != ListOfBonds.end();
192 ++BondRunner)
193 if ((*BondRunner)->leftatom == *AtomRunner)
194 if ((*BondRunner)->rightatom->LowpointNr == (*BondRunner)->leftatom->LowpointNr) { // cyclic ??
195 (*BondRunner)->Cyclic = true;
196 NoCyclicBonds++;
197 }
198 }
199 return NoCyclicBonds;
200}
201
202
203void DepthFirstSearchAnalysis::SetWalkersGraphNr(atom *&Walker)
204{
205 if (!BackStepping) { // if we don't just return from (8)
206 Walker->GraphNr = CurrentGraphNr;
207 Walker->LowpointNr = CurrentGraphNr;
208 LOG(1, "Setting Walker[" << Walker->getName() << "]'s number to " << Walker->GraphNr << " with Lowpoint " << Walker->LowpointNr << ".");
209 AtomStack.push_front(Walker);
210 CurrentGraphNr++;
211 }
212}
213
214
215void DepthFirstSearchAnalysis::ProbeAlongUnusedBond(atom *&Walker, bond *&Binder)
216{
217 atom *OtherAtom = NULL;
218
219 do { // (3) if Walker has no unused egdes, go to (5)
220 BackStepping = false; // reset backstepping flag for (8)
221 if (Binder == NULL) // if we don't just return from (11), Binder is already set to next unused
222 Binder = FindNextUnused(Walker);
223 if (Binder == NULL)
224 break;
225 LOG(2, "Current Unused Bond is " << *Binder << ".");
226 // (4) Mark Binder used, ...
227 Binder->MarkUsed(GraphEdge::black);
228 OtherAtom = Binder->GetOtherAtom(Walker);
229 LOG(2, "(4) OtherAtom is " << OtherAtom->getName() << ".");
230 if (OtherAtom->GraphNr != -1) {
231 // (4a) ... if "other" atom has been visited (GraphNr != 0), set lowpoint to minimum of both, go to (3)
232 Binder->Type = GraphEdge::BackEdge;
233 BackEdgeStack.push_front(Binder);
234 Walker->LowpointNr = (Walker->LowpointNr < OtherAtom->GraphNr) ? Walker->LowpointNr : OtherAtom->GraphNr;
235 LOG(3, "(4a) Visited: Setting Lowpoint of Walker[" << Walker->getName() << "] to " << Walker->LowpointNr << ".");
236 } else {
237 // (4b) ... otherwise set OtherAtom as Ancestor of Walker and Walker as OtherAtom, go to (2)
238 Binder->Type = GraphEdge::TreeEdge;
239 OtherAtom->Ancestor = Walker;
240 Walker = OtherAtom;
241 LOG(3, "(4b) Not Visited: OtherAtom[" << OtherAtom->getName() << "]'s Ancestor is now " << OtherAtom->Ancestor->getName() << ", Walker is OtherAtom " << OtherAtom->getName() << ".");
242 break;
243 }
244 Binder = NULL;
245 } while (1); // (3)
246}
247
248
249void DepthFirstSearchAnalysis::CheckForaNewComponent(atom *&Walker, ConnectedSubgraph &Subgraph)
250{
251 atom *OtherAtom = NULL;
252
253 // (5) if Ancestor of Walker is ...
254 LOG(1, "(5) Number of Walker[" << Walker->getName() << "]'s Ancestor[" << Walker->Ancestor->getName() << "] is " << Walker->Ancestor->GraphNr << ".");
255
256 if (Walker->Ancestor->GraphNr != Root->GraphNr) {
257 // (6) (Ancestor of Walker is not Root)
258 if (Walker->LowpointNr < Walker->Ancestor->GraphNr) {
259 // (6a) set Ancestor's Lowpoint number to minimum of of its Ancestor and itself, go to Step(8)
260 Walker->Ancestor->LowpointNr = (Walker->Ancestor->LowpointNr < Walker->LowpointNr) ? Walker->Ancestor->LowpointNr : Walker->LowpointNr;
261 LOG(2, "(6) Setting Walker[" << Walker->getName() << "]'s Ancestor[" << Walker->Ancestor->getName() << "]'s Lowpoint to " << Walker->Ancestor->LowpointNr << ".");
262 } else {
263 // (7) (Ancestor of Walker is a separating vertex, remove all from stack till Walker (including), these and Ancestor form a component
264 Walker->Ancestor->SeparationVertex = true;
265 LOG(2, "(7) Walker[" << Walker->getName() << "]'s Ancestor[" << Walker->Ancestor->getName() << "]'s is a separating vertex, creating component.");
266 SetNextComponentNumber(Walker->Ancestor, ComponentNumber);
267 LOG(3, "(7) Walker[" << Walker->getName() << "]'s Ancestor's Compont is " << ComponentNumber << ".");
268 SetNextComponentNumber(Walker, ComponentNumber);
269 LOG(3, "(7) Walker[" << Walker->getName() << "]'s Compont is " << ComponentNumber << ".");
270 do {
271 ASSERT(!AtomStack.empty(), "DepthFirstSearchAnalysis_CheckForaNewComponent() - AtomStack is empty!");
272 OtherAtom = AtomStack.front();
273 AtomStack.pop_front();
274 Subgraph.push_back(OtherAtom);
275 SetNextComponentNumber(OtherAtom, ComponentNumber);
276 LOG(3, "(7) Other[" << OtherAtom->getName() << "]'s Compont is " << ComponentNumber << ".");
277 } while (OtherAtom != Walker);
278 ComponentNumber++;
279 }
280 // (8) Walker becomes its Ancestor, go to (3)
281 LOG(2, "(8) Walker[" << Walker->getName() << "] is now its Ancestor " << Walker->Ancestor->getName() << ", backstepping. ");
282 Walker = Walker->Ancestor;
283 BackStepping = true;
284 }
285}
286
287
288void DepthFirstSearchAnalysis::CleanRootStackDownTillWalker(atom *&Walker, bond *&Binder, ConnectedSubgraph &Subgraph)
289{
290 atom *OtherAtom = NULL;
291
292 if (!BackStepping) { // coming from (8) want to go to (3)
293 // (9) remove all from stack till Walker (including), these and Root form a component
294 //AtomStack.Output(out);
295 SetNextComponentNumber(Root, ComponentNumber);
296 LOG(3, "(9) Root[" << Root->getName() << "]'s Component is " << ComponentNumber << ".");
297 SetNextComponentNumber(Walker, ComponentNumber);
298 LOG(3, "(9) Walker[" << Walker->getName() << "]'s Component is " << ComponentNumber << ".");
299 do {
300 ASSERT(!AtomStack.empty(), "DepthFirstSearchAnalysis::CleanRootStackDownTillWalker() - AtomStack is empty!");
301 OtherAtom = AtomStack.front();
302 AtomStack.pop_front();
303 Subgraph.push_back(OtherAtom);
304 SetNextComponentNumber(OtherAtom, ComponentNumber);
305 LOG(3, "(7) Other[" << OtherAtom->getName() << "]'s Component is " << ComponentNumber << ".");
306 } while (OtherAtom != Walker);
307 ComponentNumber++;
308
309 // (11) Root is separation vertex, set Walker to Root and go to (4)
310 Walker = Root;
311 Binder = FindNextUnused(Walker);
312 if (Binder != NULL) { // Root is separation vertex
313 LOG(1, "(10) Walker is Root[" << Root->getName() << "], next Unused Bond is " << *Binder << ".");
314 LOG(1, "(11) Root is a separation vertex.");
315 Walker->SeparationVertex = true;
316 } else {
317 LOG(1, "(10) Walker is Root[" << Root->getName() << "], no next Unused Bond.");
318 }
319 }
320}
321
322
323const std::deque<bond *>& DepthFirstSearchAnalysis::getBackEdgeStack() const
324{
325 return BackEdgeStack;
326}
327
328
329void DepthFirstSearchAnalysis::operator()()
330{
331 Info FunctionInfo("DepthFirstSearchAnalysis");
332 ListOfConnectedSubgraphs.clear();
333 int OldGraphNr = 0;
334 atom *Walker = NULL;
335 bond *Binder = NULL;
336
337 if (World::getInstance().numAtoms() == 0)
338 return;
339
340 Init();
341
342 LOG(0, "STATUS: Start walking the bond graph.");
343 for(World::AtomIterator iter = World::getInstance().getAtomIter();
344 iter != World::getInstance().atomEnd();) { // don't advance, is done at the end
345 Root = *iter;
346 // (1) mark all edges unused, empty stack, set atom->GraphNr = -1 for all
347 AtomStack.clear();
348
349 // put into new subgraph molecule and add this to list of subgraphs
350 ConnectedSubgraph CurrentSubgraph;
351 CurrentSubgraph.push_back(Root);
352
353 OldGraphNr = CurrentGraphNr;
354 Walker = Root;
355 do { // (10)
356 do { // (2) set number and Lowpoint of Atom to i, increase i, push current atom
357 SetWalkersGraphNr(Walker);
358
359 ProbeAlongUnusedBond(Walker, Binder);
360
361 if (Binder == NULL) {
362 LOG(2, "No more Unused Bonds.");
363 break;
364 } else
365 Binder = NULL;
366 } while (1); // (2)
367
368 // if we came from backstepping, yet there were no more unused bonds, we end up here with no Ancestor, because Walker is Root! Then we are finished!
369 if ((Walker == Root) && (Binder == NULL))
370 break;
371
372 CheckForaNewComponent( Walker, CurrentSubgraph);
373
374 CleanRootStackDownTillWalker(Walker, Binder, CurrentSubgraph);
375
376 } while ((BackStepping) || (Binder != NULL)); // (10) halt only if Root has no unused edges
377
378 ListOfConnectedSubgraphs.push_back(CurrentSubgraph);
379 // From OldGraphNr to CurrentGraphNr ranges an disconnected subgraph
380 std::stringstream output;
381 output << CurrentSubgraph;
382 LOG(0, "STATUS: Disconnected subgraph ranges from " << OldGraphNr << " to "
383 << CurrentGraphNr-1 << ": " << output.str());
384
385 // step on to next root
386 while (iter != World::getInstance().atomEnd()) {
387 if ((*iter)->GraphNr != -1) { // if already discovered, step on
388 iter++;
389 } else {
390 LOG(1,"Current next subgraph root candidate is " << (*iter)->getName()
391 << " with GraphNr " << (*iter)->GraphNr << ".");
392 break;
393 }
394 }
395 }
396 LOG(0, "STATUS: Done walking the bond graph.");
397
398 // set cyclic bond criterium on "same LP" basis
399 CyclicBondAnalysis();
400
401 OutputGraphInfoPerAtom();
402
403 OutputGraphInfoPerBond();
404}
405
406void DepthFirstSearchAnalysis::UpdateMoleculeStructure() const
407{
408 // remove all of World's molecules
409 for (World::MoleculeIterator iter = World::getInstance().getMoleculeIter();
410 World::getInstance().getMoleculeIter() != World::getInstance().moleculeEnd();
411 iter = World::getInstance().getMoleculeIter()) {
412 World::getInstance().getMolecules()->erase(*iter);
413 World::getInstance().destroyMolecule(*iter);
414 }
415 // instantiate new molecules
416 molecule *newmol = NULL;
417 for (ConnectedSubgraphList::const_iterator iter = ListOfConnectedSubgraphs.begin();
418 iter != ListOfConnectedSubgraphs.end();
419 ++iter) {
420 LOG(0, "STATUS: Creating new molecule:");
421 std::stringstream output;
422 newmol = (*iter).getMolecule();
423 newmol->Output(&output);
424 std::stringstream outstream(output.str());
425 std::string line;
426 while (getline(outstream, line)) {
427 LOG(0, "\t"+line);
428 }
429 }
430}
431
432MoleculeLeafClass *DepthFirstSearchAnalysis::getMoleculeStructure() const
433{
434 MoleculeLeafClass *Subgraphs = new MoleculeLeafClass(NULL);
435 MoleculeLeafClass *MolecularWalker = Subgraphs;
436 for (World::MoleculeIterator iter = World::getInstance().getMoleculeIter();
437 iter != World::getInstance().moleculeEnd();
438 ++iter) {
439 // TODO: Remove the insertion into molecule when saving does not depend on them anymore. Also, remove molecule.hpp include
440 MolecularWalker = new MoleculeLeafClass(MolecularWalker);
441 MolecularWalker->Leaf = (*iter);
442 }
443 return Subgraphs;
444}
445
Note: See TracBrowser for help on using the repository browser.