Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

graph.py 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. # Copyright (c) 2015-2017 Claudiu Popa <pcmanticore@gmail.com>
  2. # Copyright (c) 2015 Florian Bruhin <me@the-compiler.org>
  3. # Copyright (c) 2016 Ashley Whetter <ashley@awhetter.co.uk>
  4. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  5. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  6. """Graph manipulation utilities.
  7. (dot generation adapted from pypy/translator/tool/make_dot.py)
  8. """
  9. import os.path as osp
  10. import os
  11. import sys
  12. import tempfile
  13. import codecs
  14. def target_info_from_filename(filename):
  15. """Transforms /some/path/foo.png into ('/some/path', 'foo.png', 'png')."""
  16. basename = osp.basename(filename)
  17. storedir = osp.dirname(osp.abspath(filename))
  18. target = filename.split('.')[-1]
  19. return storedir, basename, target
  20. class DotBackend(object):
  21. """Dot File backend."""
  22. def __init__(self, graphname, rankdir=None, size=None, ratio=None,
  23. charset='utf-8', renderer='dot', additional_param=None):
  24. if additional_param is None:
  25. additional_param = {}
  26. self.graphname = graphname
  27. self.renderer = renderer
  28. self.lines = []
  29. self._source = None
  30. self.emit("digraph %s {" % normalize_node_id(graphname))
  31. if rankdir:
  32. self.emit('rankdir=%s' % rankdir)
  33. if ratio:
  34. self.emit('ratio=%s' % ratio)
  35. if size:
  36. self.emit('size="%s"' % size)
  37. if charset:
  38. assert charset.lower() in ('utf-8', 'iso-8859-1', 'latin1'), \
  39. 'unsupported charset %s' % charset
  40. self.emit('charset="%s"' % charset)
  41. for param in additional_param.items():
  42. self.emit('='.join(param))
  43. def get_source(self):
  44. """returns self._source"""
  45. if self._source is None:
  46. self.emit("}\n")
  47. self._source = '\n'.join(self.lines)
  48. del self.lines
  49. return self._source
  50. source = property(get_source)
  51. def generate(self, outputfile=None, dotfile=None, mapfile=None):
  52. """Generates a graph file.
  53. :param str outputfile: filename and path [defaults to graphname.png]
  54. :param str dotfile: filename and path [defaults to graphname.dot]
  55. :param str mapfile: filename and path
  56. :rtype: str
  57. :return: a path to the generated file
  58. """
  59. import subprocess # introduced in py 2.4
  60. name = self.graphname
  61. if not dotfile:
  62. # if 'outputfile' is a dot file use it as 'dotfile'
  63. if outputfile and outputfile.endswith(".dot"):
  64. dotfile = outputfile
  65. else:
  66. dotfile = '%s.dot' % name
  67. if outputfile is not None:
  68. storedir, _, target = target_info_from_filename(outputfile)
  69. if target != "dot":
  70. pdot, dot_sourcepath = tempfile.mkstemp(".dot", name)
  71. os.close(pdot)
  72. else:
  73. dot_sourcepath = osp.join(storedir, dotfile)
  74. else:
  75. target = 'png'
  76. pdot, dot_sourcepath = tempfile.mkstemp(".dot", name)
  77. ppng, outputfile = tempfile.mkstemp(".png", name)
  78. os.close(pdot)
  79. os.close(ppng)
  80. pdot = codecs.open(dot_sourcepath, 'w', encoding='utf8')
  81. pdot.write(self.source)
  82. pdot.close()
  83. if target != 'dot':
  84. use_shell = sys.platform == 'win32'
  85. if mapfile:
  86. subprocess.call([self.renderer, '-Tcmapx', '-o',
  87. mapfile, '-T', target, dot_sourcepath,
  88. '-o', outputfile],
  89. shell=use_shell)
  90. else:
  91. subprocess.call([self.renderer, '-T', target,
  92. dot_sourcepath, '-o', outputfile],
  93. shell=use_shell)
  94. os.unlink(dot_sourcepath)
  95. return outputfile
  96. def emit(self, line):
  97. """Adds <line> to final output."""
  98. self.lines.append(line)
  99. def emit_edge(self, name1, name2, **props):
  100. """emit an edge from <name1> to <name2>.
  101. edge properties: see http://www.graphviz.org/doc/info/attrs.html
  102. """
  103. attrs = ['%s="%s"' % (prop, value) for prop, value in props.items()]
  104. n_from, n_to = normalize_node_id(name1), normalize_node_id(name2)
  105. self.emit('%s -> %s [%s];' % (n_from, n_to, ', '.join(sorted(attrs))))
  106. def emit_node(self, name, **props):
  107. """emit a node with given properties.
  108. node properties: see http://www.graphviz.org/doc/info/attrs.html
  109. """
  110. attrs = ['%s="%s"' % (prop, value) for prop, value in props.items()]
  111. self.emit('%s [%s];' % (normalize_node_id(name), ', '.join(sorted(attrs))))
  112. def normalize_node_id(nid):
  113. """Returns a suitable DOT node id for `nid`."""
  114. return '"%s"' % nid
  115. def get_cycles(graph_dict, vertices=None):
  116. '''given a dictionary representing an ordered graph (i.e. key are vertices
  117. and values is a list of destination vertices representing edges), return a
  118. list of detected cycles
  119. '''
  120. if not graph_dict:
  121. return ()
  122. result = []
  123. if vertices is None:
  124. vertices = graph_dict.keys()
  125. for vertice in vertices:
  126. _get_cycles(graph_dict, [], set(), result, vertice)
  127. return result
  128. def _get_cycles(graph_dict, path, visited, result, vertice):
  129. """recursive function doing the real work for get_cycles"""
  130. if vertice in path:
  131. cycle = [vertice]
  132. for node in path[::-1]:
  133. if node == vertice:
  134. break
  135. cycle.insert(0, node)
  136. # make a canonical representation
  137. start_from = min(cycle)
  138. index = cycle.index(start_from)
  139. cycle = cycle[index:] + cycle[0:index]
  140. # append it to result if not already in
  141. if cycle not in result:
  142. result.append(cycle)
  143. return
  144. path.append(vertice)
  145. try:
  146. for node in graph_dict[vertice]:
  147. # don't check already visited nodes again
  148. if node not in visited:
  149. _get_cycles(graph_dict, path, visited, result, node)
  150. visited.add(node)
  151. except KeyError:
  152. pass
  153. path.pop()