/[cvs]/nfo/python/scripts/sixdegrees/boostgraph.py
ViewVC logotype

Diff of /nfo/python/scripts/sixdegrees/boostgraph.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.1 by joko, Fri Feb 8 09:05:02 2008 UTC revision 1.4 by joko, Thu Feb 21 11:29:07 2008 UTC
# Line 3  Line 3 
3  # $Id$  # $Id$
4    
5  # (c) 2008 Andreas Motl <andreas.motl@ilo.de>  # (c) 2008 Andreas Motl <andreas.motl@ilo.de>
6    # (c) 2008 Sebastian Utz <su@rotamente.com>
7    
8  # This program is free software: you can redistribute it and/or modify  # This program is free software: you can redistribute it and/or modify
9  # it under the terms of the GNU Affero General Public License as published by  # it under the terms of the GNU Affero General Public License as published by
# Line 23  Line 24 
24  #  #
25  # BGL-Python Homepage: http://osl.iu.edu/~dgregor/bgl-python/  # BGL-Python Homepage: http://osl.iu.edu/~dgregor/bgl-python/
26  #  #
27  # Documentation:  # Documentation (Boost):
28  #  - http://osl.iu.edu/~dgregor/bgl-python/reference/boost.graph.html  #  - http://www.boost.org/libs/graph/doc/graph_theory_review.html
29  #  - http://www.boost.org/libs/graph/doc/depth_first_search.html  #  - http://www.boost.org/libs/graph/doc/depth_first_search.html
30    #  - http://www.boost.org/boost/graph/depth_first_search.hpp
31    #  - http://www.boost.org/libs/graph/doc/DFSVisitor.html
32    #  - http://www.boost.org/libs/graph/example/dfs-example.cpp
33    #
34    # Documentation (BGL-Python):
35    #  - http://osl.iu.edu/~dgregor/bgl-python/reference/boost.graph.html
36  #  #
37  # Subversion-Repository: https://svn.osl.iu.edu/svn/projects_viz/bgl-python/  # Subversion-Repository: https://svn.osl.iu.edu/svn/projects_viz/bgl-python/
38    
39    
40    RANDOM_MAX_NODES = 10
41    RANDOM_MAX_CHILDREN_PER_NODE = 500
42    MAX_SEARCH_DEPTH = 50
43    
44    
45    ENABLE_PROFILING = False
46    
47    if ENABLE_PROFILING:
48      import profile
49      from profile import Profile
50    
51    
52  import sys, os  import sys, os
53    import random
54    
55  sys.path.append('bgl_python')  sys.path.append('bgl_python')
56  os.environ['PATH'] += ';' + './bgl_python'  os.environ['PATH'] += ';' + './bgl_python'
# Line 41  import boost.graph as bgl Line 61  import boost.graph as bgl
61    
62  # from http://www.boost.org/libs/graph/doc/DFSVisitor.html  # from http://www.boost.org/libs/graph/doc/DFSVisitor.html
63  class tree_edges_dfs_visitor(bgl.dfs_visitor):  class tree_edges_dfs_visitor(bgl.dfs_visitor):
64    #class tree_edges_bfs_visitor(bgl.bfs_visitor):
65        
66    def __init__(self, name_map):    def __init__(self, startVertex, endVertex, maxdepth, color_map):
67        
68        #print dir(self)
69        
70      #bgl.dfs_visitor.__init__(self)      #bgl.dfs_visitor.__init__(self)
71      self.name_map = name_map      #self.name_map = name_map
72        
73        self.startVertex = startVertex
74        self.endVertex = endVertex
75        
76        # for recognizing path switches
77      self.state = True      self.state = True
78        
79        # for tracking paths
80        self.paths = []
81        self.current_path = []
82        
83        # for limiting search depth
84        """
85        self.color_map = color_map
86        self.maxdepth = maxdepth
87        self.depth = 0
88        """
89        
90        self.level = 0
91        
92    
93      #def back_edge(self, e, g):
94      #  self.tree_edge(e, g, 'back_edge')
95    
96      #def forward_or_cross_edge(self, e, g):
97      #  self.tree_edge(e, g, 'forward_or_cross_edge')
98    
99      #def tree_edge(self, e, g):
100      #  self.tree_edge(e, g, 'examine_edge')
101    
102    def tree_edge(self, e, g):    def examine_edge(self, e, g):
103        self._touch_edge(e, g, 'examine_edge')
104    
105      def _touch_edge(self, e, g, label=''):
106        
107      (u, v) = (g.source(e), g.target(e))      (u, v) = (g.source(e), g.target(e))
108      print "Tree edge ",      
109      print self.name_map[u],      # increase current search depth (level)
110        """
111        self.depth += 1
112        
113        # check if maximum depth reached
114        if self.depth == self.maxdepth:
115          # color all succeeding vertices to black (mark as "already visited")
116          # BUG!!! marks too many nodes
117          for child_edge in g.out_edges(v):
118            end_vertex = g.target(child_edge)
119            #self.color_map[end_vertex] = bgl.Color(bgl.Color.gray)
120        """
121        
122        name_map = g.vertex_properties['node_id']
123        
124        if label:
125          print "%s:" % label,
126        print "edge ",
127        print name_map[u],
128      print " -> ",      print " -> ",
129      print self.name_map[v]      print name_map[v]
130      self.state = True      
131        #self.state = True
132        
133        if u == self.startVertex:
134          print "starting"
135          self.current_path = []
136    
137        # skip circular references
138        if v != self.startVertex:
139          self.current_path.append(e)
140    
141        if v == self.endVertex and self.current_path:
142          print "found:"
143          print self.current_path
144          self.paths.append(self.current_path)
145          self.current_path = []
146        
147    
148      """
149    def start_vertex(self, v, g):    def start_vertex(self, v, g):
150        self._seperator('start_vertex')
151        #pass
152      #print 'sssss'      #print 'sssss'
153      self._seperator()  
154      def discover_vertex(self, v, g):
155        #print '>>>'
156        self._seperator('discover_vertex')
157        #pass
158    
159    def initialize_vertex(self, v, g):    def initialize_vertex(self, v, g):
160      #print '>>>'      #print '>>>'
161      self._seperator()      self._seperator('initialize_vertex')
162    
163      def examine_vertex(self, v, g):
164        self._seperator('examine_vertex')
165    
166    def finish_vertex(self, v, g):    def finish_vertex(self, v, g):
167      #print '<<<'      #print '<<<'
168      self._seperator()      if self.current_path:
169          self.paths.append(self.current_path)
170        self.current_path = []
171        self.depth = 0
172        self._seperator('finish_vertex')
173      """
174    
175    def _seperator(self):    def _seperator(self, label = 'unknown'):
176      if self.state:      if 1 or self.state:
177        print '-' * 21        print '-' * 21, label
178        self.state = False        self.state = False
179    
180    
181  def build_fixed_graph():  def build_fixed_graph():
182      
183    graph = bgl.Graph()    graph = bgl.Graph()
184      index = {}
185    
186      # doesn't this work? see http://www.nabble.com/-Graph--Getting-PageRank-to-work-in-BGL-Python-td14207115.html
187    #graph.add_vertex_property_map(name='my_name', type='float')    #graph.add_vertex_property_map(name='my_name', type='float')
188    
189    # 'write_graphviz' requires property 'node_id' on vertices    # 'write_graphviz' requires property 'node_id' on vertices
# Line 85  def build_fixed_graph(): Line 194  def build_fixed_graph():
194    
195    v1 = graph.add_vertex()    v1 = graph.add_vertex()
196    vmap[v1] = '1'    vmap[v1] = '1'
197      index['1'] = v1
198    
199    v2 = graph.add_vertex()    v2 = graph.add_vertex()
200    vmap[v2] = '2'    vmap[v2] = '2'
201      index['2'] = v2
202    
203    v3 = graph.add_vertex()    v3 = graph.add_vertex()
204    vmap[v3] = '3'    vmap[v3] = '3'
205      index['3'] = v3
206    
207    v4 = graph.add_vertex()    v4 = graph.add_vertex()
208    vmap[v4] = '4'    vmap[v4] = '4'
209      index['4'] = v4
210    
211    e1 = graph.add_edge(v1, v2)    e1 = graph.add_edge(v1, v2)
212    e2 = graph.add_edge(v1, v3)    e2 = graph.add_edge(v1, v3)
213    e3 = graph.add_edge(v3, v4)    e3 = graph.add_edge(v3, v4)
214      
215      e4 = graph.add_edge(v1, v4)
216      #e5 = graph.add_edge(v3, v2)
217      #e6 = graph.add_edge(v2, v4)
218    
219    """    """
220    for vertex in graph.vertices:    for vertex in graph.vertices:
# Line 111  def build_fixed_graph(): Line 228  def build_fixed_graph():
228    
229    graph.write_graphviz('friends.dot')    graph.write_graphviz('friends.dot')
230        
231    return graph    return (graph, index)
232    
233    
234    def build_random_graph():
235    
236      graph = bgl.Graph()
237      index = {}
238    
239      vmap = graph.vertex_property_map('string')
240      graph.vertex_properties['node_id'] = vmap
241    
242      count = 0
243      for parent_id in range(1, RANDOM_MAX_NODES + 1):
244        count += 1
245        if count % 100 == 0:
246          sys.stderr.write('.')
247          
248        parent_id_str = str(parent_id)
249        v1New = False
250        if not index.has_key(parent_id_str):
251          #print "adding v1:", parent_id_str
252          myVertex1 = graph.add_vertex()
253          vmap[myVertex1] = parent_id_str
254          index[parent_id_str] = myVertex1
255          v1New = True
256    
257      
258      count = 0
259      #for j in range(1, random.randint(1, RANDOM_MAX_CHILDREN_PER_NODE)):
260      for j in range(1, RANDOM_MAX_CHILDREN_PER_NODE):
261    
262        count += 1
263        if count % 100 == 0:
264          sys.stderr.write('.')
265    
266        parent_id_str = random.choice(index.keys())
267        
268        child_id_str = parent_id_str
269        while child_id_str == parent_id_str:
270          child_id_str = random.choice(index.keys())
271          #print child_id_str
272          
273          myVertex1 = index[parent_id_str]
274          myVertex2 = index[child_id_str]
275          
276          graph.add_edge(myVertex1, myVertex2)
277            
278      sys.stderr.write("\n")
279    
280      return (graph, index)
281    
282    
283    def dump_track(graph, track):
284      track_ids = []
285      for node in track:
286        node_id = graph.vertex_properties['node_id'][node]
287        track_ids.append(node_id)
288      
289      print ' -> '.join(track_ids)
290    
291    def dump_edges(g, edges):
292      name_map = g.vertex_properties['node_id']
293      for e in edges:
294        (u, v) = (g.source(e), g.target(e))
295        print "edge ",
296        print name_map[u],
297        print " -> ",
298        print name_map[v]
299    
300    def find_path_solutions(source, target, graph, paths):
301      
302      print
303      print "=" * 42
304      print "find_path_solutions"
305      print "=" * 42
306    
307      #print visitor.paths
308      #(u, v) = (g.source(e), g.target(e))
309      for path in paths:
310        startVertex = graph.source(path[0])
311        
312        track = []
313        track.append(startVertex)
314        
315        for edge in path:
316          endVertex = graph.target(edge)
317          track.append(endVertex)
318          if source == startVertex and target == endVertex:
319            #print "found:", track
320            dump_track(graph, track)
321    
322    def dump_graph(graph):
323      for edge in graph.edges:
324        (u, v) = (graph.source(edge), graph.target(edge))
325        startIndex = graph.vertex_properties['node_id'][u]
326        endIndex = graph.vertex_properties['node_id'][v]
327        print "%s -> %s" % (startIndex, endIndex)
328        
329    
330  def main():  def main():
331        
332    # Load a graph from the GraphViz file 'mst.dot'    # Load a graph from the GraphViz file 'mst.dot'
333    #graph = bgl.Graph.read_graphviz('mst.dot')    #graph = bgl.Graph.read_graphviz('mst.dot')
334    graph = build_fixed_graph()    (graph, index) = build_fixed_graph()
335      #(graph, index) = build_random_graph()
336    
337      #dump_graph(graph)
338    
339    # Compute all paths rooted from each vertex    # Compute all paths rooted from each vertex
340    #mst_edges = bgl.kruskal_minimum_spanning_tree(graph, weight)    #mst_edges = bgl.kruskal_minimum_spanning_tree(graph, weight)
341    #bgl.depth_first_search(graph, root_vertex = None, visitor = None, color_map = None)    #bgl.depth_first_search(graph, root_vertex = None, visitor = None, color_map = None)
342      
343      """
344    for root in graph.vertices:    for root in graph.vertices:
345      print      print
346      print '=' * 42      print '=' * 42
347      print 'Paths originating from node %s' % graph.vertex_properties['node_id'][root]      print 'Paths originating from node %s' % graph.vertex_properties['node_id'][root]
348      visitor = tree_edges_dfs_visitor(graph.vertex_properties['node_id'])      #cmap = graph.vertex_property_map('color')
349        cmap = None
350        visitor = tree_edges_dfs_visitor(3, graph.vertex_properties['node_id'], cmap)
351        #visitor = tree_edges_bfs_visitor(3, graph.vertex_properties['node_id'], cmap)
352      bgl.depth_first_search(graph, root_vertex = root, visitor = visitor, color_map = None)      bgl.depth_first_search(graph, root_vertex = root, visitor = visitor, color_map = None)
353          #bgl.breadth_first_search(graph, root_vertex = root, visitor = visitor, color_map = None)
354        #find_path_solutions(index['1'], index['4'], graph, visitor.paths)
355      #sys.exit(0)
356      """
357    
358      startIndex = random.choice(index.keys())
359      endIndex = random.choice(index.keys())
360      startIndex = '1'
361      endIndex = '4'
362    
363      print "Trying to find solution for: %s -> %s" % (startIndex, endIndex)
364    
365      startVertex = index[startIndex]
366      endVertex = index[endIndex]
367    
368      def doCompute():
369        cmap = graph.vertex_property_map('color')
370        visitor = tree_edges_dfs_visitor(startVertex, endVertex, MAX_SEARCH_DEPTH, cmap)
371        bgl.depth_first_search(graph, root_vertex = startVertex, visitor = visitor, color_map = None)
372        #bgl.depth_first_visit(graph, root_vertex = startVertex, visitor = visitor, color_map = cmap)
373        #find_path_solutions(startVertex, endVertex, graph, visitor.paths)
374        for path in visitor.paths:
375          print '-' * 21
376          dump_edges(graph, path)
377    
378      if ENABLE_PROFILING:
379        global paths
380        paths = []
381        p = Profile()
382        p.runcall(doCompute)
383        p.print_stats()
384      else:
385        paths = doCompute()
386    
387        
388    # STOP HERE    # STOP HERE
389    sys.exit(0)    sys.exit(0)

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.4

MailToCvsAdmin">MailToCvsAdmin
ViewVC Help
Powered by ViewVC 1.1.26 RSS 2.0 feed