PyGraphViz test


In [ ]:
import pygraphviz as pgv
from IPython.display import Image, display, display_png, display_svg, SVG
import random

G = pgv.AGraph()

nodes = ['a','b','c','d','e']
G.add_nodes_from(nodes)

edges = [('a','b'),('b','c'),('b','d'),('d','e')]
for edge in edges:
    G.add_edge(edge[0],edge[1])
print(G)
G.write('simple.dot') # write to simple.dot

layouts = ["neato","dot","twopi","circo","fdp","nop"]
for layout in layouts:
    name = 'simple_'+layout+'.png'
    G.draw(name, prog = layout)
#     print name
#     display(Image(name))

In [ ]:
layout = 'dot'

G.node_attr['shape']='underline'

actual_node = G.get_node('c')

actual_node.attr['color']='orange'
# actual_node.attr['shape']='underline'
name = 'simple_'+layout+'.png'
G.draw(name, prog = layout)
display(Image('simple_dot.png'))

In [ ]:
def display_graph(layout= 'dot', fformat = 'png'):
    if fformat not in ['png','svg']:
        print 'format is not real',fformat
        return
    name = 'simple_'+layout+'.'+fformat
    G.draw(name, prog = layout)
    if fformat == 'svg':
        display(SVG(name))
    else:
        display(Image(name))

End of Test

Get to the real deal


In [110]:
import pygraphviz as pgv
from IPython.display import Image, display, display_png, display_svg, SVG
from random import random

def random_prob():
    return round(random(),3)

class ConversationTree(object):

    def __init__(self, root_sentence):
        self.G = pgv.AGraph(strict=True, directed=True)
        # Basic styling
        self.G.node_attr['shape']='box'
        #
        self.next_node_id = 0
        self.actual_node = None
        self.root = self.add_node(root_sentence)
        self.actual_node = self.root
             
    def add_node(self, sentence, goto = True):
        node = ConversationNode(self, self.actual_node, sentence)
        if goto:
            self.change_actual(node)
        return node
    
    def change_actual(self, new):
        if self.actual_node: # None when adding the root
            self.actual_node.unstyle()
        self.actual_node = new
        self.actual_node.style_actual()        
    
    def next_id(self):
        id_ = self.next_node_id 
        self.next_node_id += 1
        return id_
        
    def display(self, max_lvl_up = -1, layout= 'dot', fformat = 'png'):
        if fformat not in ['png','svg']:
            print 'format is not real',fformat
            return
        name = 'simple_'+layout+'.'+fformat
        self.create_sub_graph()
        tree.G.draw(name, prog = layout)
#         self.G.draw(name, prog = layout)
        if fformat == 'svg':
            display(SVG(name))
        else:
            display(Image(name))           
        
    def up(self, steps = 1):
        for step in range(steps):
            if self.actual_node.parent_edge:
                self.change_actual(self.actual_node.parent())
      
    def create_sub_graph(self, from_node = None, to_node = None):
        print 'all'
        print self.G
        self.G.add_subgraph([self.actual_node.id_],'cc')
        sg = self.G.get_subgraph('cc')
        print 'sub'
        print sg
        
class ConversationNode(object):
    
    def __init__(self, conv_tree, parent, label):
        self.conv_tree = conv_tree
        self.graph = conv_tree.G  
        self.id_ = conv_tree.next_id()
        self.label = label
        self.child_edges = {}
        self.g_node = self.update_graph()
        self.style({'label':str(self.id_) + '/' + self.label})
        if parent:
            self.parent_edge = parent.add_child(self)
        else:
            self.parent_edge = None
    
    def update_graph(self):
        self.graph.add_node(self.id_)
        g_node = self.graph.get_node(self.id_)
        return g_node
    
    def add_child(self, node):
        child_edge = ConversationEdge(self, node,{'prob':random_prob()})   
        self.child_edges[child_edge.id_] = child_edge
        return child_edge
#         node.parent_edge = child_edge

    def parent(self):
        if self.parent_edge:
            return self.parent_edge.from_node
        else: 
            print "root has no parent..."
            return self
        
    def __repr__(self):
        return str(self.id_)

    def style(self, style_dict):
        for k,v in style_dict.iteritems():
            self.g_node.attr[k] = v
    
    def style_actual(self):
        self.style({'color': "orange"}) 
        
    def unstyle(self):
        self.style({'color': "black"})
        
    def all_predecessors(self):
        print self.graph.predecessors(self.id_)
        
class ConversationEdge(object):
        
    def __init__(self,from_node, to_node , prob = None):
        self.id_ = (from_node.id_, to_node.id_)
        self.from_node = from_node
        self.to_node = to_node
        self.g_edge = self.update_graph()
        self.style({'label':random_prob()})
        
    def update_graph(self):
        self.from_node.graph.add_edge(self.id_)
        g_edge = self.from_node.graph.get_edge(*self.id_)     
        return g_edge

    
    def style(self, style_dict):
        for k,v in style_dict.iteritems():
            self.g_edge.attr[k] = v

In [113]:
sentences = {
  'a': 'However, she is prevented by herdisease from ending her life without assistance.',
  'b': 'At the end of her novel existence she dies at peace, well defended from those she parasites.',
  'c': 'In short, I must recapitulate humanity and bear it within myself.',
  'd': 'As long as people live, some of them will fight for sanity and justice and survival.',
  'e': 'In Proceedings of the Annual Meeting of the Peace Science Society, Ann Arbor.'
}

tree = ConversationTree(sentences['a'])
tree.add_node(sentences['b'])
tree.add_node(sentences['c'])
tree.add_node(sentences['d'])

print tree.actual_node
tree.actual_node.all_predecessors()
# tree.display()
# tree.up(2)
# tree.add_node(sentences['e'])
# tree.display()


3
[u'2']

In [ ]: