view python/graph.py @ 274:ea93e0a7a31e

Move docs
author Windel Bouwman
date Wed, 04 Sep 2013 17:35:06 +0200
parents cdc76d183bcc
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)