view python/graph.py @ 276:56d37ed4b4d2

phaa
author Windel Bouwman
date Mon, 16 Sep 2013 21:51:17 +0200
parents ea93e0a7a31e
children 046017431c6a
line wrap: on
line source


class Graph:
    """
       Generic graph base class.
       Can dump to graphiz dot format for example!
    """
    def __init__(self):
        self.nodes = []
        self.edges = []

    def newNode(self):
        n = Node(self)
        self.nodes.append(n)
        return n

    def addEdge(self, n, m):
        """ Add an edge from n to m """
        if (n, m) not in self.edges and (m, n) not in self.edges:
            self.edges.append((n, m))
            n.succ.append(m)
            m.pred.append(n)

    def delEdge(self):
        # TODO
        pass
        
    def to_dot(self, f):
        """ Generate graphviz dot representation """
        #print('digraph G {', file=f)
        for node in self.nodes:
            print('{} [label="{}" shape=box3d];'.format(id(node), node), file=f)
        for n, m in self.edges:
            print('{} -> {};'.format(id(n), id(m)), file=f)
        #print('}', file=f)


class Node:
    """
       Node in a graph.
    """
    def __init__(self, g):
        self.g = g
        self.succ = []
        self.pred = []

    @property
    def Adj(self):
        return set(self.succ) | set(self.pred)