graph.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. # copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
  2. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
  3. #
  4. # This file is part of logilab-common.
  5. #
  6. # logilab-common is free software: you can redistribute it and/or modify it under
  7. # the terms of the GNU Lesser General Public License as published by the Free
  8. # Software Foundation, either version 2.1 of the License, or (at your option) any
  9. # later version.
  10. #
  11. # logilab-common is distributed in the hope that it will be useful, but WITHOUT
  12. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  13. # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  14. # details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public License along
  17. # with logilab-common. If not, see <http://www.gnu.org/licenses/>.
  18. """Graph manipulation utilities.
  19. (dot generation adapted from pypy/translator/tool/make_dot.py)
  20. """
  21. __docformat__ = "restructuredtext en"
  22. __metaclass__ = type
  23. import os.path as osp
  24. import os
  25. import sys
  26. import tempfile
  27. from logilab.common.compat import str_encode
  28. def escape(value):
  29. """Make <value> usable in a dot file."""
  30. lines = [line.replace('"', '\\"') for line in value.split('\n')]
  31. data = '\\l'.join(lines)
  32. return '\\n' + data
  33. def target_info_from_filename(filename):
  34. """Transforms /some/path/foo.png into ('/some/path', 'foo.png', 'png')."""
  35. basename = osp.basename(filename)
  36. storedir = osp.dirname(osp.abspath(filename))
  37. target = filename.split('.')[-1]
  38. return storedir, basename, target
  39. class DotBackend:
  40. """Dot File backend."""
  41. def __init__(self, graphname, rankdir=None, size=None, ratio=None,
  42. charset='utf-8', renderer='dot', additionnal_param={}):
  43. self.graphname = graphname
  44. self.renderer = renderer
  45. self.lines = []
  46. self._source = None
  47. self.emit("digraph %s {" % normalize_node_id(graphname))
  48. if rankdir:
  49. self.emit('rankdir=%s' % rankdir)
  50. if ratio:
  51. self.emit('ratio=%s' % ratio)
  52. if size:
  53. self.emit('size="%s"' % size)
  54. if charset:
  55. assert charset.lower() in ('utf-8', 'iso-8859-1', 'latin1'), \
  56. 'unsupported charset %s' % charset
  57. self.emit('charset="%s"' % charset)
  58. for param in additionnal_param.iteritems():
  59. self.emit('='.join(param))
  60. def get_source(self):
  61. """returns self._source"""
  62. if self._source is None:
  63. self.emit("}\n")
  64. self._source = '\n'.join(self.lines)
  65. del self.lines
  66. return self._source
  67. source = property(get_source)
  68. def generate(self, outputfile=None, dotfile=None, mapfile=None):
  69. """Generates a graph file.
  70. :param outputfile: filename and path [defaults to graphname.png]
  71. :param dotfile: filename and path [defaults to graphname.dot]
  72. :rtype: str
  73. :return: a path to the generated file
  74. """
  75. import subprocess # introduced in py 2.4
  76. name = self.graphname
  77. if not dotfile:
  78. # if 'outputfile' is a dot file use it as 'dotfile'
  79. if outputfile and outputfile.endswith(".dot"):
  80. dotfile = outputfile
  81. else:
  82. dotfile = '%s.dot' % name
  83. if outputfile is not None:
  84. storedir, basename, target = target_info_from_filename(outputfile)
  85. if target != "dot":
  86. pdot, dot_sourcepath = tempfile.mkstemp(".dot", name)
  87. os.close(pdot)
  88. else:
  89. dot_sourcepath = osp.join(storedir, dotfile)
  90. else:
  91. target = 'png'
  92. pdot, dot_sourcepath = tempfile.mkstemp(".dot", name)
  93. ppng, outputfile = tempfile.mkstemp(".png", name)
  94. os.close(pdot)
  95. os.close(ppng)
  96. pdot = open(dot_sourcepath, 'w')
  97. pdot.write(str_encode(self.source, 'utf8'))
  98. pdot.close()
  99. if target != 'dot':
  100. if sys.platform == 'win32':
  101. use_shell = True
  102. else:
  103. use_shell = False
  104. if mapfile:
  105. subprocess.call([self.renderer, '-Tcmapx', '-o', mapfile, '-T', target, dot_sourcepath, '-o', outputfile],
  106. shell=use_shell)
  107. else:
  108. subprocess.call([self.renderer, '-T', target,
  109. dot_sourcepath, '-o', outputfile],
  110. shell=use_shell)
  111. os.unlink(dot_sourcepath)
  112. return outputfile
  113. def emit(self, line):
  114. """Adds <line> to final output."""
  115. self.lines.append(line)
  116. def emit_edge(self, name1, name2, **props):
  117. """emit an edge from <name1> to <name2>.
  118. edge properties: see http://www.graphviz.org/doc/info/attrs.html
  119. """
  120. attrs = ['%s="%s"' % (prop, value) for prop, value in props.items()]
  121. n_from, n_to = normalize_node_id(name1), normalize_node_id(name2)
  122. self.emit('%s -> %s [%s];' % (n_from, n_to, ", ".join(attrs)) )
  123. def emit_node(self, name, **props):
  124. """emit a node with given properties.
  125. node properties: see http://www.graphviz.org/doc/info/attrs.html
  126. """
  127. attrs = ['%s="%s"' % (prop, value) for prop, value in props.items()]
  128. self.emit('%s [%s];' % (normalize_node_id(name), ", ".join(attrs)))
  129. def normalize_node_id(nid):
  130. """Returns a suitable DOT node id for `nid`."""
  131. return '"%s"' % nid
  132. class GraphGenerator:
  133. def __init__(self, backend):
  134. # the backend is responsible to output the graph in a particular format
  135. self.backend = backend
  136. # XXX doesn't like space in outpufile / mapfile
  137. def generate(self, visitor, propshdlr, outputfile=None, mapfile=None):
  138. # the visitor
  139. # the property handler is used to get node and edge properties
  140. # according to the graph and to the backend
  141. self.propshdlr = propshdlr
  142. for nodeid, node in visitor.nodes():
  143. props = propshdlr.node_properties(node)
  144. self.backend.emit_node(nodeid, **props)
  145. for subjnode, objnode, edge in visitor.edges():
  146. props = propshdlr.edge_properties(edge, subjnode, objnode)
  147. self.backend.emit_edge(subjnode, objnode, **props)
  148. return self.backend.generate(outputfile=outputfile, mapfile=mapfile)
  149. class UnorderableGraph(Exception):
  150. pass
  151. def ordered_nodes(graph):
  152. """takes a dependency graph dict as arguments and return an ordered tuple of
  153. nodes starting with nodes without dependencies and up to the outermost node.
  154. If there is some cycle in the graph, :exc:`UnorderableGraph` will be raised.
  155. Also the given graph dict will be emptied.
  156. """
  157. # check graph consistency
  158. cycles = get_cycles(graph)
  159. if cycles:
  160. cycles = '\n'.join([' -> '.join(cycle) for cycle in cycles])
  161. raise UnorderableGraph('cycles in graph: %s' % cycles)
  162. vertices = set(graph)
  163. to_vertices = set()
  164. for edges in graph.values():
  165. to_vertices |= set(edges)
  166. missing_vertices = to_vertices - vertices
  167. if missing_vertices:
  168. raise UnorderableGraph('missing vertices: %s' % ', '.join(missing_vertices))
  169. # order vertices
  170. order = []
  171. order_set = set()
  172. old_len = None
  173. while graph:
  174. if old_len == len(graph):
  175. raise UnorderableGraph('unknown problem with %s' % graph)
  176. old_len = len(graph)
  177. deps_ok = []
  178. for node, node_deps in graph.items():
  179. for dep in node_deps:
  180. if dep not in order_set:
  181. break
  182. else:
  183. deps_ok.append(node)
  184. order.append(deps_ok)
  185. order_set |= set(deps_ok)
  186. for node in deps_ok:
  187. del graph[node]
  188. result = []
  189. for grp in reversed(order):
  190. result.extend(sorted(grp))
  191. return tuple(result)
  192. def get_cycles(graph_dict, vertices=None):
  193. '''given a dictionary representing an ordered graph (i.e. key are vertices
  194. and values is a list of destination vertices representing edges), return a
  195. list of detected cycles
  196. '''
  197. if not graph_dict:
  198. return ()
  199. result = []
  200. if vertices is None:
  201. vertices = graph_dict.keys()
  202. for vertice in vertices:
  203. _get_cycles(graph_dict, vertice, [], result)
  204. return result
  205. def _get_cycles(graph_dict, vertice=None, path=None, result=None):
  206. """recursive function doing the real work for get_cycles"""
  207. if vertice in path:
  208. cycle = [vertice]
  209. for node in path[::-1]:
  210. if node == vertice:
  211. break
  212. cycle.insert(0, node)
  213. # make a canonical representation
  214. start_from = min(cycle)
  215. index = cycle.index(start_from)
  216. cycle = cycle[index:] + cycle[0:index]
  217. # append it to result if not already in
  218. if not cycle in result:
  219. result.append(cycle)
  220. return
  221. path.append(vertice)
  222. try:
  223. for node in graph_dict[vertice]:
  224. _get_cycles(graph_dict, node, path, result)
  225. except KeyError:
  226. pass
  227. path.pop()
  228. def has_path(graph_dict, fromnode, tonode, path=None):
  229. """generic function taking a simple graph definition as a dictionary, with
  230. node has key associated to a list of nodes directly reachable from it.
  231. Return None if no path exists to go from `fromnode` to `tonode`, else the
  232. first path found (as a list including the destination node at last)
  233. """
  234. if path is None:
  235. path = []
  236. elif fromnode in path:
  237. return None
  238. path.append(fromnode)
  239. for destnode in graph_dict[fromnode]:
  240. if destnode == tonode or has_path(graph_dict, destnode, tonode, path):
  241. return path[1:] + [tonode]
  242. path.pop()
  243. return None