Exemplo n.º 1
0
def graph_from_fsa(fsa):
    g = gv.digraph('graph')
    gv.setv(g, 'rankdir', 'LR')
    
    for st in fsa.states():
        n = gv.node(g, str(st))
        gv.setv(n, 'label', str(st))
        
        gv.setv(n, 'shape', ('double' if st in fsa.final_s else '') + 'circle')
        
        if (st == fsa.first_s):
            inv_n = gv.node(g, str(id([])))
            gv.setv(inv_n, 'label', '')
            gv.setv(inv_n, 'style', 'invis')
            gv.setv(gv.edge(inv_n, n), 'color', 'gray51')
    
    for s1, s2, c in fsa.transitions():
        e = gv.edge(g, str(s1), str(s2))
        
        gv.setv(e, 'color', 'gray71')
        gv.setv(e, 'arrowsize', '0.7')
    
        if (c == '#'):
            c = u'\u03bb'
            gv.setv(e, 'fontcolor', 'goldenrod2')
            gv.setv(e, 'style', 'dashed')
        else:
            gv.setv(e, 'fontcolor', 'firebrick2')
            
        gv.setv(e, 'label', (' ' + c + ' ').encode('utf-8'))
    
    return g
Exemplo n.º 2
0
def draw_graph(aData):
    g = gv.digraph("G")

    #gv.setv(g, "label", "TEST")
    #gv.setv(g, "rankdir", "LR")

    # Set node style
    #n = gv.protonode(g0)
    #gv.setv(n, "shape", "ellipse")

    # draw notes
    draw_note(g)

    # draw one common node: swith
    #draw_node(g, "swith", "swith", "swith")

    # draw subgraph
    for key in aData:
        (aHost, aNodes, aLinks) = key
        draw_host(g, aHost, aNodes, aLinks)

    # save file
    gv.write(g, "draw.dot")

    #generate graphic
    gv.layout(g, "dot")
    gv.render(g, "png", "l2_topology.png")
    gv.rm(g)
Exemplo n.º 3
0
def draw_graph(aData):
    g = gv.digraph("G")

    #gv.setv(g, "label", "TEST")
    #gv.setv(g, "rankdir", "LR")

    # Set node style
    #n = gv.protonode(g0)
    #gv.setv(n, "shape", "ellipse")

    # draw notes
    draw_note(g)

    # draw one common node: swith
    #draw_node(g, "swith", "swith", "swith")

    # draw subgraph
    for key in aData:
        (aHost, aNodes, aLinks) = key
        draw_host(g, aHost, aNodes, aLinks)

    # save file
    gv.write(g, "draw.dot")

    #generate graphic
    gv.layout(g, "dot")
    gv.render(g, "png", "l2_topology.png")
    gv.rm(g)
Exemplo n.º 4
0
def render_graphviz(filename, tree, names):
    gv_graph = gv.digraph("ID3")
    gv_root = gv.node(gv_graph, names[tree.attribute][0])

    gv_tree = __graphviz_tree(tree, names, gv_graph, gv_root)

    gv.layout(gv_graph, "dot")
    return gv.render(gv_graph, "png", filename)
Exemplo n.º 5
0
 def __init__(self):
     self.root = collections.deque()
     self.root.append([Node(LEAF, 1, 1)])
     self.depth = 1
     #point to the last inserted
     self.last = 0
     #for draw
     self.G = gv.digraph("G")
     gv.setv(self.G, 'nodesep', '0.05')
     gv.setv(self.G, 'rankdir', 'TB')
     N = gv.protonode(self.G)
     gv.setv(N, 'shape', 'record')
     E = gv.protoedge(self.G)
     gv.setv(E, 'side', 'left')
Exemplo n.º 6
0
    def visualize(self, filepath):
        '''
        This method visualize the graph by graphviz format.
        '''
        nodes = list(self.node_set)

        # trasform the directed edge set of the graph
        # in the set of (src, dst) tuples
        tmp = [(src, list(dsts))
               for src, dsts in self.forward_edge_set.items()]
        edges = []
        for src, dsts in tmp:
            for dst in dsts:
                edges.append((src, dst))

        # render the graph
        graph = gv.add_edges(gv.add_nodes(gv.digraph(), nodes),
                             edges).render(filepath)
Exemplo n.º 7
0
def main():
    # create a new empty graph
    G = gv.digraph('G')
    # define a simple graph ( A->B )
    gv.edge(gv.node(G, 'A'), gv.node(G, 'B'))
    # compute a directed graph layout
    gv.layout(G, 'dot')
    # annotate the graph with the layout information
    gv.render(G)
    # do something with the layout
    n = gv.firstnode(G)
    while n:
        print 'node ' + gv.nameof(n) + ' is at ' + gv.getv(n, 'pos')
        e = gv.firstout(n)
        while e:
            print 'edge ' + gv.nameof(gv.tailof(e)) + '->' + gv.nameof(
                gv.headof(e)) + ' is at ' + gv.getv(e, 'pos')
            e = gv.nextout(n, e)
        n = gv.nextnode(G, n)
Exemplo n.º 8
0
def main():
    # create a new empty graph
    G = gv.digraph("G")
    # define a simple graph ( A->B )
    gv.edge(gv.node(G, "A"), gv.node(G, "B"))
    # compute a directed graph layout
    gv.layout(G, "dot")
    # annotate the graph with the layout information
    gv.render(G)
    # do something with the layout
    n = gv.firstnode(G)
    while n:
        print(f"node {gv.nameof(n)} is at {gv.getv(n, 'pos')}")
        e = gv.firstout(n)
        while e:
            print(
                f"edge {gv.nameof(gv.tailof(e))}->{gv.nameof(gv.headof(e))} is at {gv.getv(e, 'pos')}"
            )
            e = gv.nextout(n, e)
        n = gv.nextnode(G, n)
Exemplo n.º 9
0
def graph_from_parse_tree(root, same_level = False):
    def visit(node, graph, subgraph):
        if isinstance(node, Rule):
            gnode = gv.node(graph, str(id(node)))
            stylize_rule(gnode, node)
            
            for n in node.childs:
                visit(n, graph, subgraph)
                e = gv.edge(graph, str(id(node)), str(id(n)))
                stylize_edge(e)
        else: # Token
            gnode = gv.node(subgraph, str(id(node)))
            stylize_token(gnode, node)

    g = gv.digraph('graph')
    tg = gv.graph(g, 'token_graph')
    
    if (same_level):
        gv.setv(tg, 'rank', 'same')
        
    visit(root, g, tg)
    return g
Exemplo n.º 10
0
    def gen(self, filename):

        f = open(filename)
        src = f.readlines()

        found = 0
        trdefinition = []
        for line in src:
            if (line.find('tr_t') >= 0):
                found = 1
                self.dot = gv.digraph(self.getTrName(line))
                print "Name: ", self.getTrName(line)
                continue

            if (found and line.find('};') >= 0):
                break

            if (found):
                line = line.strip(' ')
                if (line.startswith('/*') or line.endswith('*/') or line.startswith('*')):
                    continue
                line = line.replace('{', '')
                line = line.replace('}', '')
                line = line.strip("\n")
                trdefinition.append(line)
    
        # parsing each line and creating dot graph
        self.createEdge(trdefinition)

        gv.layout(self.dot, "dot")
        gv.render(self.dot, "dot", "out.gv")
        gv.render(self.dot, "png", "out.png")

        print 'finded definition:'
        for line in trdefinition:
            print line

        print '...generating fsm graph'
Exemplo n.º 11
0
#!/usr/bin/python

import gv

g = gv.digraph("G")
n = gv.node(g, "hello")
m = gv.node(g, "world")
e = gv.edge(n, m)
gv.layout(g, "dot")
gv.render(g, "png", "gv_test.png")
gv.rm(g)
Exemplo n.º 12
0
#!/usr/bin/python

# display the kernel module dependencies

# author: Michael Hohn <*****@*****.**>
#  based on: modgraph.tcl by John Ellson <*****@*****.**>

import sys
import gv

modules = open("/proc/modules", 'r').readlines()

G = gv.digraph("G")
N = gv.protonode(G)
E = gv.protoedge(G)

gv.setv(G, 'rankdir', 'LR')
gv.setv(G, 'nodesep', '0.05')
gv.setv(N, 'shape', 'box')
gv.setv(N, 'width', '0')
gv.setv(N, 'height', '0')
gv.setv(N, 'margin', '.03')
gv.setv(N, 'fontsize', '8')
gv.setv(N, 'fontname', 'helvetica')
gv.setv(E, 'arrowsize', '.4')

for rec in modules:
   fields = rec.split(' ')
   n = gv.node(G, fields[0])
   for usedby in fields[3].split(','):
      if (usedby != '-') & (usedby != ''):
Exemplo n.º 13
0
 def __init__(self):
     self.graph = gv.digraph('roles')
     self._role_nodes = {}
Exemplo n.º 14
0
    return text

subgraphs = {}

def subgraphfun(graph,name,label):
    try:
        subgraph = subgraphs[name]
    except:
        subgraph = gv.graph(graph, 'cluster_' + name)
        gv.setv(subgraph, 'label', label)
        subgraphs[name] = subgraph

    return subgraph


graph = gv.digraph('filegraph')


for dirpath, dirnames, filenames in os.walk('src'):
    
    try:
        subgraph = subgraphs[clean(dirpath)]
    except:
        subgraph = gv.graph(graph, 'cluster_' + clean(dirpath))
        gv.setv(subgraph, 'label', dirpath)
        subgraphs[clean(dirpath)] = subgraph
    
    print clean(dirpath)
    print dirnames
    print filenames
Exemplo n.º 15
0
def GetGVData(names,map,contents=None,type="xdot",node_shape='record',debug=0,output_graphic_filename=None,aliases=None):
	large_mode=False
	if len(names)>800:
		large_mode=True

	if not aliases:
		aliases={}
	if not node_shape:
		node_shape="record"
	if not contents:
		contents={}
	root_name="Root"
	if len(names)>0:
		root_name=str(names[0])
	g=gv.digraph(root_name)
	layout_alrogithm='dot'
	node_color=None
	if large_mode:
		node_shape='point'
		gv.setv(g,"model","subset")
		layout_alrogithm='neato'
		layout_alrogithm='twopi'
		node_color='red'
		debug=1
	gv.setYinvert(g)
	name2node={}
	edges=[]

	method='plain'
	for name in names:
		if aliases.has_key(name):
			display_name=str(aliases[name])
		else:
			display_name=str(name)

		if method=='plain':
			node_str=''
			if contents.has_key(name):
				for i in range(0,len(contents[name]),1):
					[address,op,[op1,op2],comment]=contents[name][i]
					node_str+=str(op)
					if op1:
						node_str+=" "+str(op1)
					if op2:
						node_str+=" "+str(op2)
					node_str+='\r\n'
				display_name="{"+display_name+"|"+node_str+"}"
			node=gv.node(g,display_name)
			name2node[name]=node
			gv.setv(node,"shape",node_shape)
			if node_color:
				gv.setv(node,"color",node_color)
	
		elif method=='layered': #dirty look
			node_str=''
			if contents.has_key(name):
				for i in range(0,len(contents[name]),1):
					[address,op,[op1,op2],comment]=contents[name][i]
					node_str+="|{"+MakeLenStr(str(op),5)
					if op1:
						node_str+="|"+MakeLenStr(str(op1),5)
					if op2:
						node_str+="|"+MakeLenStr(str(op2),5)
					node_str+='}'
			node=gv.node(g,"{"+display_name+node_str+"}")
			name2node[name]=node
			gv.setv(node,"shape","record")

		elif method=='subgraph': #Too big
			subg=gv.graph(g,'cluster'+display_name)
			gv.setv(subg,"label",display_name)
			gv.setv(subg,"color","black")
	
			node=gv.node(subg,display_name)
			name2node[name]=node
			nodes.append(node)
			gv.setv(node,"shape","record")
	
			node_str=''
			if contents.has_key(name):
				src=node
				for i in range(0,len(contents[name]),1):
					[address,op,[op1,op2],comment]=contents[name][i]
					node_str=hex(address)+"|"+str(op)
					if op1:
						node_str+="|"+str(op1)
					if op2:
						node_str+="|"+str(op2)
					node=gv.node(subg,node_str)
					nodes.append(node)
					gv.setv(node,"shape","record")
					#edge=gv.edge(src,node)
					src=node

	for name in names:
		if map.has_key(name):
			for dst_name in map[name]:
				if name2node.has_key(name) and name2node.has_key(dst_name):
					edge=gv.edge(name2node[name],name2node[dst_name])
					gv.setv(edge,"invis","")
					edges.append([name,dst_name,edge])
	if debug:
		print 'Start layout'
		start_time=time.time()
	gv.layout(g,layout_alrogithm)
	if debug:
		end_time=time.time()
		elapsed_time=end_time-start_time
		print 'End layout',end_time-start_time

	prefix=''
	for i in range(0,5,1):
		prefix+=hex(random.randint(0,9999))
	
	gv.render(g,type,".temp.dat")
	if debug:
		img_filename=prefix+".jpg"
		dot_filename=prefix+".dot"
		print 'writing',img_filename
		gv.render(g,"jpg",img_filename) #For debugging
		gv.render(g,"dot",dot_filename) #For debugging
		print 'done writing',img_filename

	if output_graphic_filename:
		gv.render(g,"jpg",output_graphic_filename) #For debugging

	node_attrs_map={}
	edge_attrs_maps={}
	for name in name2node.keys():
		node_attrs=GetAttrs(name2node[name])
		node_attrs_map[name]=node_attrs

	for [src,dst,edge] in edges:
		line_attrs=GetAttrs(edge)
		if not edge_attrs_maps.has_key(src):
			edge_attrs_maps[src]={}
		edge_attrs_maps[src][dst]=line_attrs

	###### Get maxx,maxy
	maxx=0
	maxy=0
	graph_attrs=GetAttrs(g)
	if graph_attrs.has_key('bb'):
		[x1str,y1str,x2str,y2str]=re.compile(",").split(graph_attrs['bb'])
		x1=int(x1str)
		y1=int(y1str)
		x2=int(x2str)
		y2=int(y2str)
		maxx=x1
		if x2>maxx:
			maxx=x2
		maxy=y1
		if y2>maxy:
			maxy=y2
	maxx+=200
	maxy+=200
	
	return [[maxx,maxy],node_attrs_map,edge_attrs_maps]

#################### End of Graphviz processor ###################
##################################################################
Exemplo n.º 16
0
#!/usr/bin/python
import sys
import gv

# create a new empty graph
G = gv.digraph('G')

# define a simple graph ( A->B )
gv.edge(gv.node(G, 'A'), gv.node(G, 'B'))

# compute a directed graph layout
gv.layout(G, 'dot')

# annotate the graph with the layout information
gv.render(G)

# do something with the layout
n = gv.firstnode(G)
while n:
    print 'node ' + gv.nameof(n) + ' is at ' + gv.getv(n, 'pos')
    e = gv.firstout(n)
    while e:
        print 'edge ' + gv.nameof(gv.tailof(e)) + '->' + gv.nameof(
            gv.headof(e)) + ' is at ' + gv.getv(e, 'pos')
        e = gv.nextout(n, e)
    n = gv.nextnode(G, n)
Exemplo n.º 17
0
def graph_draw(g,
               pos=None,
               size=(15, 15),
               pin=False,
               layout="neato",
               maxiter=None,
               ratio="fill",
               overlap=False,
               splines=False,
               mode="major",
               vsize=0.1,
               penwidth=1.0,
               eweight=None,
               ewidth=None,
               gprops={},
               vprops={},
               eprops={},
               vcolor=None,
               ecolor=None,
               vcmap=matplotlib.cm.jet,
               vnorm=True,
               ecmap=matplotlib.cm.jet,
               enorm=True,
               output="",
               output_format="auto",
               returngv=False,
               fork=False,
               seed=0):
    """Draw a graph using graphviz."""

    if output != "":
        output = os.path.expanduser(output)
        # check opening file for writing, since graphview will bork if it is not
        # possible to open file
        if os.path.dirname(output) != "" and \
               not os.access(os.path.dirname(output), os.W_OK):
            raise IOError("cannot write to " + os.path.dirname(output))

    if g.is_directed():
        gvg = gv.digraph("G")
    else:
        gvg = gv.graph("G")

    # main graph properties
    gv.setv(gvg, "outputorder", "edgesfirst")
    gv.setv(gvg, "mode", mode)
    if overlap == False:
        if layout == "neato" and mode == "ipsep":
            overlap = "ipsep"
        else:
            overlap = "false"
    else:
        overlap = "true"
    if isinstance(overlap, str):
        gv.setv(gvg, "overlap", overlap)
    if splines:
        gv.setv(gvg, "splines", "true")
    gv.setv(gvg, "ratio", str(ratio))
    gv.setv(gvg, "size",
            "%f,%f" % (size[0] / 2.54, size[1] / 2.54))  # centimeters
    if maxiter != None:
        gv.setv(gvg, "maxiter", str(maxiter))
    if seed != 0:
        if type(seed) == int:
            gv.setv(gvg, "start", "%d" % seed)
        else:
            gv.setv(gvg, "start", seed)

    # apply all user supplied properties
    for k, val in gprops.iteritems():
        if isinstance(val, PropertyMap):
            gv.setv(gvg, k, str(val[g]))
        else:
            gv.setv(gvg, k, str(val))

    # normalize color properties
    if vcolor != None and not isinstance(vcolor, str):
        minmax = [float("inf"), -float("inf")]
        for v in g.vertices():
            c = vcolor[v]
            minmax[0] = min(c, minmax[0])
            minmax[1] = max(c, minmax[1])
        if minmax[0] == minmax[1]:
            minmax[1] += 1
        if vnorm:
            vnorm = matplotlib.colors.normalize(vmin=minmax[0], vmax=minmax[1])

    if ecolor != None and not isinstance(ecolor, str):
        minmax = [float("inf"), -float("inf")]
        for e in g.edges():
            c = ecolor[e]
            minmax[0] = min(c, minmax[0])
            minmax[1] = max(c, minmax[1])
        if minmax[0] == minmax[1]:
            minmax[1] += 1
        if enorm:
            enorm = matplotlib.colors.normalize(vmin=minmax[0], vmax=minmax[1])

    nodes = []
    edges = []

    # add nodes
    for v in g.vertices():
        n = gv.node(gvg, str(g.vertex_index[v]))
        if type(vsize) != tuple:
            vw = vh = vsize
        else:
            vw, vh = vsize
        if type(vw) == PropertyMap:
            vw = vw[v]
        if type(vh) == PropertyMap:
            vh = vh[v]

        if type(vw) == str and vw == "in":
            vw = v.in_degree()
        if type(vw) == str and vw == "out":
            vw = v.out_degree()
        if type(vw) == str and vw == "total":
            vw = v.in_degree() + v.out_degree()

        if type(vh) == str and vh == "in":
            vh = v.in_degree()
        if type(vh) == str and vh == "out":
            vh = v.out_degree()
        if type(vh) == str and vh == "total":
            vh = v.in_degree() + v.out_degree()

        gv.setv(n, "width", "%g" % vw)
        gv.setv(n, "height", "%g" % vh)
        gv.setv(n, "style", "filled")
        gv.setv(n, "color", "black")
        # apply color
        if vcolor != None:
            if isinstance(vcolor, str):
                gv.setv(n, "fillcolor", vcolor)
            else:
                color = tuple(
                    [int(c * 255.0) for c in vcmap(vnorm(vcolor[v]))])
                gv.setv(n, "fillcolor", "#%.2x%.2x%.2x%.2x" % color)
        else:
            gv.setv(n, "fillcolor", "red")
        gv.setv(n, "label", "")

        # user supplied position
        if pos != None:
            gv.setv(n, "pos", "%f,%f" % (pos[0][v], pos[1][v]))
            gv.setv(n, "pin", str(pin))

        # apply all user supplied properties
        for k, val in vprops.iteritems():
            if isinstance(val, PropertyMap):
                gv.setv(n, k, str(val[v]))
            else:
                gv.setv(n, k, str(val))
        nodes.append(n)
    for e in g.edges():
        ge = gv.edge(nodes[g.vertex_index[e.source()]],
                     nodes[g.vertex_index[e.target()]])
        gv.setv(ge, "arrowsize", "0.3")
        if g.is_directed():
            gv.setv(ge, "arrowhead", "vee")
        # apply color
        if ecolor != None:
            if isinstance(ecolor, str):
                gv.setv(ge, "color", ecolor)
            else:
                color = tuple(
                    [int(c * 255.0) for c in ecmap(enorm(ecolor[e]))])
                gv.setv(ge, "color", "#%.2x%.2x%.2x%.2x" % color)

        # apply weight
        if eweight != None:
            if isinstance(eweight, PropertyMap):
                gv.setv(ge, "weight", str(eweight[e]))
            else:
                gv.setv(ge, "weight", str(eweight))

        # apply width
        if ewidth != None:
            if isinstance(ewidth, PropertyMap):
                gv.setv(ge, "penwidth", str(ewidth[e]))
            else:
                gv.setv(ge, "penwidth", str(ewidth))

        # apply all user supplied properties
        for k, v in eprops.iteritems():
            if isinstance(v, PropertyMap):
                gv.setv(ge, k, str(v[e]))
            else:
                gv.setv(ge, k, str(v))
        edges.append(ge)

    gv.layout(gvg, layout)
    gv.render(gvg, "dot", "/dev/null")  # retrieve postitions

    if pos == None:
        pos = (g.new_vertex_property("double"),
               g.new_vertex_property("double"))
    for n in xrange(0, len(nodes)):
        p = gv.getv(nodes[n], "pos")
        p = p.split(",")
        pos[0][g.vertex(n)] = float(p[0])
        pos[1][g.vertex(n)] = float(p[1])

    if output_format == "auto":
        if output == "":
            output_format = "xlib"
        else:
            output_format = output.split(".")[-1]

    # if using xlib we need to fork the process, otherwise good ol' graphviz
    # will call exit() when the window is closed
    if output_format == "xlib" or fork:
        pid = os.fork()
        if pid == 0:
            gv.render(gvg, output_format, output)
            os._exit(0)  # since we forked, it's good to be sure
        if output_format != "xlib":
            os.wait()
    else:
        gv.render(gvg, output_format, output)

    if returngv:
        return pos, gv
    else:
        gv.rm(gvg)
        del gvg
        return pos
Exemplo n.º 18
0
def graph_draw(g, pos=None, size=(15,15), pin=False, layout="neato",
               maxiter=None, ratio="fill", overlap=False, splines=False,
               mode="major", vsize=0.1, penwidth=1.0, eweight=None, ewidth=None,
               gprops={}, vprops={}, eprops={}, vcolor=None, ecolor=None,
               vcmap=matplotlib.cm.jet, vnorm=True, ecmap=matplotlib.cm.jet,
               enorm=True, output="", output_format="auto", returngv=False,
               fork=False, seed=0):
    """Draw a graph using graphviz."""

    if output != "":
        output = os.path.expanduser(output)
        # check opening file for writing, since graphview will bork if it is not
        # possible to open file
        if os.path.dirname(output) != "" and \
               not os.access(os.path.dirname(output), os.W_OK):
            raise IOError("cannot write to " + os.path.dirname(output))

    if g.is_directed():
        gvg = gv.digraph("G")
    else:
        gvg = gv.graph("G")

    # main graph properties
    gv.setv(gvg,"outputorder", "edgesfirst")
    gv.setv(gvg,"mode", mode)
    if overlap == False:
        if layout == "neato" and mode == "ipsep":
            overlap = "ipsep"
        else:
            overlap = "false"
    else:
        overlap = "true"
    if isinstance(overlap,str):
        gv.setv(gvg,"overlap", overlap)
    if splines:
        gv.setv(gvg,"splines", "true")
    gv.setv(gvg,"ratio", str(ratio))
    gv.setv(gvg,"size", "%f,%f" % (size[0]/2.54,size[1]/2.54)) # centimeters
    if maxiter != None:
        gv.setv(gvg,"maxiter", str(maxiter))
    if seed != 0:
        if type(seed) == int:
            gv.setv(gvg, "start", "%d" % seed)
        else:
            gv.setv(gvg, "start", seed)

    # apply all user supplied properties
    for k,val in gprops.iteritems():
        if isinstance(val, PropertyMap):
            gv.setv(gvg, k, str(val[g]))
        else:
            gv.setv(gvg, k, str(val))

    # normalize color properties
    if vcolor != None and not isinstance(vcolor, str):
        minmax = [float("inf"), -float("inf")]
        for v in g.vertices():
            c = vcolor[v]
            minmax[0] = min(c,minmax[0])
            minmax[1] = max(c,minmax[1])
        if minmax[0] == minmax[1]:
            minmax[1] += 1
        if vnorm:
            vnorm = matplotlib.colors.normalize(vmin=minmax[0], vmax=minmax[1])

    if ecolor != None and not isinstance(ecolor, str):
        minmax = [float("inf"), -float("inf")]
        for e in g.edges():
            c = ecolor[e]
            minmax[0] = min(c,minmax[0])
            minmax[1] = max(c,minmax[1])
        if minmax[0] == minmax[1]:
            minmax[1] += 1
        if enorm:
            enorm = matplotlib.colors.normalize(vmin=minmax[0], vmax=minmax[1])

    nodes = []
    edges = []

    # add nodes
    for v in g.vertices():
        n = gv.node(gvg,str(g.vertex_index[v]))
        if type(vsize) != tuple:
            vw = vh = vsize
        else:
            vw, vh = vsize
        if type(vw) == PropertyMap:
            vw = vw[v]
        if type(vh) == PropertyMap:
            vh = vh[v]

        if type(vw) == str and vw == "in":
            vw = v.in_degree()
        if type(vw) == str and vw == "out":
            vw = v.out_degree()
        if type(vw) == str and vw == "total":
            vw = v.in_degree() + v.out_degree()

        if type(vh) == str and vh == "in":
            vh = v.in_degree()
        if type(vh) == str and vh == "out":
            vh = v.out_degree()
        if type(vh) == str and vh == "total":
            vh = v.in_degree() + v.out_degree()

        gv.setv(n, "width", "%g" % vw)
        gv.setv(n, "height", "%g" % vh)
        gv.setv(n, "style", "filled")
        gv.setv(n, "color", "black")
        # apply color
        if vcolor != None:
            if isinstance(vcolor,str):
                gv.setv(n, "fillcolor", vcolor)
            else:
                color = tuple([int(c*255.0) for c in vcmap(vnorm(vcolor[v]))])
                gv.setv(n, "fillcolor", "#%.2x%.2x%.2x%.2x" % color)
        else:
            gv.setv(n, "fillcolor", "red")
        gv.setv(n, "label", "")

        # user supplied position
        if pos != None:
            gv.setv(n, "pos", "%f,%f" % (pos[0][v],pos[1][v]))
            gv.setv(n, "pin", str(pin))

        # apply all user supplied properties
        for k,val in vprops.iteritems():
            if isinstance(val, PropertyMap):
                gv.setv(n, k, str(val[v]))
            else:
                gv.setv(n, k, str(val))
        nodes.append(n)
    for e in g.edges():
        ge = gv.edge(nodes[g.vertex_index[e.source()]],
                     nodes[g.vertex_index[e.target()]])
        gv.setv(ge, "arrowsize", "0.3")
        if g.is_directed():
            gv.setv(ge, "arrowhead", "vee")
        # apply color
        if ecolor != None:
            if isinstance(ecolor,str):
                gv.setv(ge, "color", ecolor)
            else:
                color = tuple([int(c*255.0) for c in ecmap(enorm(ecolor[e]))])
                gv.setv(ge, "color", "#%.2x%.2x%.2x%.2x" % color)

        # apply weight
        if eweight != None:
            if isinstance(eweight, PropertyMap):
                gv.setv(ge, "weight", str(eweight[e]))
            else:
                gv.setv(ge, "weight", str(eweight))

        # apply width
        if ewidth != None:
            if isinstance(ewidth, PropertyMap):
                gv.setv(ge, "penwidth", str(ewidth[e]))
            else:
                gv.setv(ge, "penwidth", str(ewidth))

        # apply all user supplied properties
        for k,v in eprops.iteritems():
            if isinstance(v, PropertyMap):
                gv.setv(ge, k, str(v[e]))
            else:
                gv.setv(ge, k, str(v))
        edges.append(ge)

    gv.layout(gvg, layout)
    gv.render(gvg, "dot", "/dev/null") # retrieve postitions

    if pos == None:
        pos = (g.new_vertex_property("double"), g.new_vertex_property("double"))
    for n in xrange(0, len(nodes)):
        p = gv.getv(nodes[n], "pos")
        p = p.split(",")
        pos[0][g.vertex(n)] = float(p[0])
        pos[1][g.vertex(n)] = float(p[1])

    if output_format == "auto":
        if output == "":
            output_format = "xlib"
        else:
            output_format = output.split(".")[-1]

    # if using xlib we need to fork the process, otherwise good ol' graphviz
    # will call exit() when the window is closed
    if output_format == "xlib" or fork:
        pid = os.fork()
        if pid == 0:
            gv.render(gvg, output_format, output)
            os._exit(0) # since we forked, it's good to be sure
        if output_format != "xlib":
            os.wait()
    else:
        gv.render(gvg, output_format, output)

    if returngv:
        return pos, gv
    else:
        gv.rm(gvg)
        del gvg
        return pos
Exemplo n.º 19
0
			names.append(MakeName(i))
			contents[MakeName(i)]="""hfwohfiowehofhweoif
hfoweihfiowhfoiweh
fweuiohfoiwehiofhweio
hfiowehiofhweofhoew"""
			caller[MakeName(i)]=[]
		for i in range(0,NumOfLines,1):
			src=random.randint(0,NumOfElement-1)
			dst=random.randint(0,NumOfElement-1)
			caller[MakeName(src)].append(MakeName(dst))
		GetGVData(names,caller,contents)
	
	if 0:
		import gv
		nodes=[]
		g = gv.digraph("G")
		n=gv.node(g,"hello")
		nodes.append(n)
		for i in range(0,100,1):
			m = gv.node(g,str(i))
			nodes.append(m)
			e = gv.edge(n,m)
		gv.layout(g, "dot")
		
		gv.render(g,"xdot","test.xdot")
		for node in nodes:
			print "pos=",gv.getv(node,"pos")
		#print "pos=",gv.getv(n,"pos")
		#print "pos=",gv.getv(e,"pos")
	
	
Exemplo n.º 20
0
 def __init__(self):
     self.graph = gv.digraph('roles')
     self._role_nodes = {}
Exemplo n.º 21
0
#!/usr/bin/python
import sys
import gv

# create a new empty graph 
G = gv.digraph('G')

# define a simple graph ( A->B )
gv.edge(gv.node(G, 'A'),gv.node(G, 'B'))

# compute a directed graph layout
gv.layout(G, 'dot')

# annotate the graph with the layout information
gv.render(G)

# do something with the layout
n = gv.firstnode(G)
while n :
    print 'node '+gv.nameof(n)+' is at '+gv.getv(n,'pos')
    e = gv.firstout(n)
    while e :
	print 'edge '+gv.nameof(gv.tailof(e))+'->'+gv.nameof(gv.headof(e))+' is at '+gv.getv(e,'pos')
	e = gv.nextout(n,e)
    n = gv.nextnode(G,n)