view python/graph.py @ 277:046017431c6a

Started register allocator
author Windel Bouwman
date Thu, 26 Sep 2013 21:14:25 +0200
parents ea93e0a7a31e
children 9fca39eebe50
line wrap: on
line source


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

    def newNode(self):
        n = Node(self)
        self.addNode(n)
        return n

    def addNode(self, n):
        self.nodes.add(n)

    def delNode(self, n):
        self.nodes.remove(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.add((n, m))

    def hasEdge(self, n, m):
        # This can be directional or not :)
        if self.directed:
            return (n, m) in self.edges
        else:
            return (n, m) in self.edges or (m, n) in self.edges

    def adjecent(self, n):
        """ Return all nodes with edges to n """
        return set(m for m in self.nodes if self.hasEdge(n, m))

    def preceeding(self, n):
        assert self.directed
        return set(m for m in self.nodes if self.hasEdge(m, n))

    def succeeding(self, n):
        assert self.directed
        return set(m for m in self.nodes if self.hasEdge(n, m))
        
    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

    @property
    def Succ(self):
        return self.g.succeeding(self)

    @property
    def Pred(self):
        """ Return a set of predecessors """
        return self.g.preceeding(self)

    @property
    def Adj(self):
        return self.g.adjecent(self)

    @property
    def Degree(self):
        return len(self.Adj)