#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 22 17:59:53 2019 @author: lsantoca """ from contextlib import redirect_stdout from fifo import Fifo from stack import Stack from graph import Graph class GraphDot(Graph): """Extension de la classe Graph pour produire des visualisation de graohes via le langage dot""" _dotPre = 'graph' _dotSep = '--' def toDot(self): """Draw the graph as dot""" print(self._dotPre + ' {') print(self.__toDotEdges(), end='') print('}') def toDotAll(self): """Draw the graph as dot, with all the informations""" print('{0} {{'.format(self._dotPre)) print(self._toDotVertices()) print(self.__toDotEdges()) print(self.__toDotParent()) print('}') def __toDotEdges(self): done = {} for x in self.vertices: done[x] = [] ret = '' for x in self.vertices: for y in self.adjList[x]: if x not in done[y]: ret += '\t{0} {1} {2}\n'.format(x, self._dotSep, y) done[x].append(y) return ret def _toDotVertices(self): # This method has to be overwritten ret = '' for x in self.vertices: style = '' if x in self.color.keys(): if self.color[x] == 'Gray': style += 'style=filled, fillcolor = gray' elif self.color[x] == 'Black': style += 'style=filled, fontcolor=white, fillcolor = black' else: style += 'style=normal' else: style += 'style=filled, fillcolor = white' label = "\\N" ret += "\t{0} [{1}, label=\"{2}\"]\n".format(x, style, label) return ret def __toDotParent(self): ret = '' for x in self.vertices: if 'parent' in self.__dict__.keys() \ and x in self.parent.keys() \ and self.parent[x] != None: fmt = "\t{2} {1} {0} [constraint=false,color= red]\n" ret += fmt.format(x, self._dotSep, self.parent[x]) return ret def saveToDot(self, fileName=None): if fileName is None: fileName = input('Name of file where to save: ') with open(fileName, 'w') as f: with redirect_stdout(f): self.toDot() def saveToFile(self, fileName, i=0): "Main doSomething used to draw the graph during the parcours" with open('{0}_{1:02d}.dot'.format(fileName, i), 'w') as f: with redirect_stdout(f): self.toDotAll() def bfsWithDot(self, fileName=None): "Parcours en largeur d'un graphe, the resuts is saved in a series of dot files" if fileName is None: fileName = input('Prefix of files where to save: ') self.parcours(Fifo(), doSomething=lambda i: self.saveToFile(fileName, i)) def dfsWithDot(self, fileName=None): "Parcours en profondeur d'un graphe, the resuts is saved in a series of dot files" if fileName is None: fileName = input('Prefix of files where to save: ') self.parcours(Stack(), doSomething=lambda i: self.saveToFile(fileName, i)) petersenEdges = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 1)] \ + [(6, 7), (7, 8), (8, 9), (9, 10), (10, 6)] \ + [(1, 6), (2, 9), (3, 7), (4, 10), (5, 8)] def testIt(): pt = GraphDot(petersenEdges) pt.bfsWithDot('petersenBfs') pt.dfsWithDot('petersenDfs') if __name__ == '__main__': testIt()