Example #1
0
def draw_host(g, aHost, aNodes, aLinks):
    clusterName = 'cluster_' + aHost

    gv.graph(g, clusterName)
    g1 = gv.findsubg(g, clusterName)
    gv.setv(g1, "label", aHost)
    # gv.setv(g1, "clusterMode", "local")

    #rank = "same"
    # gv.setv(g1, "rank", rank)

    # draw nodes
    aNodes1 = {}
    for key in aNodes:
        aName = aHost + key
        aType = aNodes[key]
        n = draw_node(g1, key, aName, aType)
        aNodes1[aName] = aName

    # draw edges
    #aLinks1 = {}
    for x in aLinks:
        (x1, x2) = x
        n1 = aHost + x1
        n2 = aHost + x2
        e = draw_edge(g1, n1, n2, aNodes1)
Example #2
0
def gv_layout(nodes,edges,mode="dot"):
	G = gv.graph("root")
	s = gv.graph(G,"test")
	for i in nodes:
		sg = "%02x %s"%(i,nodes[i][0])
		n = gv.node(s,sg)
		if nodes[i][0] in gv_colors:
			gv.setv(n,"color",gv_colors[nodes[i][0]])
			gv.setv(n,"style","filled")

	for i in edges:
		if i[0] in nodes and i[1] in nodes:
			e = gv.edge(G,"%02x %s"%(i[0],nodes[i[0]][0]),"%02x %s"%(i[1],nodes[i[1]][0]))
			gv.setv(e,"dir","none")
	gv.layout(G, mode)
	gv.render(G)
# for debugging purposes
	gv.render(G,'svg','test.svg')
	devs = {}
	fn = gv.firstnode(G)
	try:
		devs[gv.nameof(fn)] = gv.getv(fn,"pos").split(",")
	except:
		print 'Failed in gv_render'
	for i in range(len(nodes)-1):
		fn = gv.nextnode(G,fn)
		devs[gv.nameof(fn)] = gv.getv(fn,"pos").split(",")

	return devs
def draw_host(g, aHost, aNodes, aLinks):
    clusterName = 'cluster_' + aHost

    gv.graph(g, clusterName)
    g1 = gv.findsubg(g, clusterName)
    gv.setv(g1, "label", aHost)
   # gv.setv(g1, "clusterMode", "local")

    #rank = "same"
   # gv.setv(g1, "rank", rank)

    # draw nodes
    aNodes1 = {}
    for key in aNodes:
        aName = aHost + key
        aType = aNodes[key]
        n = draw_node(g1, key, aName, aType)
        aNodes1[aName] = aName

    # draw edges
    #aLinks1 = {}
    for x in aLinks:
        (x1, x2) = x
        n1 = aHost + x1
        n2 = aHost + x2
        e = draw_edge(g1, n1, n2, aNodes1)
Example #4
0
def gv_layout(nodes, edges, mode="dot"):
    G = gv.graph("root")
    s = gv.graph(G, "test")
    for i in nodes:
        sg = "%02x %s" % (i, nodes[i][0])
        n = gv.node(s, sg)
        if nodes[i][0] in gv_colors:
            gv.setv(n, "color", gv_colors[nodes[i][0]])
            gv.setv(n, "style", "filled")

    for i in edges:
        if i[0] in nodes and i[1] in nodes:
            e = gv.edge(G, "%02x %s" % (i[0], nodes[i[0]][0]),
                        "%02x %s" % (i[1], nodes[i[1]][0]))
            gv.setv(e, "dir", "none")
    gv.layout(G, mode)
    gv.render(G)
    # for debugging purposes
    gv.render(G, 'svg', 'test.svg')
    devs = {}
    fn = gv.firstnode(G)
    try:
        devs[gv.nameof(fn)] = gv.getv(fn, "pos").split(",")
    except:
        print 'Failed in gv_render'
    for i in range(len(nodes) - 1):
        fn = gv.nextnode(G, fn)
        devs[gv.nameof(fn)] = gv.getv(fn, "pos").split(",")

    return devs
    def _add(self, handle, node="", edge="", subg="", **attrs):
        """ Adds items to parent graph (given by handle).

        Adds the item to parent Graphviz-item graph handle, sets item
        attributes as necessary and returns a Graphviz.<Type> instance.
        """
        head, tail = '', ''
        if edge:
            head, tail = edge

        node, head, tail, subg = map(encode_page, [node, head, tail, subg])

        self.changed = 1
        if head and tail:
            item = gv.edge(handle, *(head, tail))
            # print "gv.edge(g, '" + "', '".join(edge) + "')"
            graphvizitem = GraphvizEdge(self, item)
        elif node:
            item = gv.node(handle, node)
            # print "gv.node(g, '" + node + "')"
            graphvizitem = GraphvizNode(self, item)
        elif subg:
            # print "item = gv.graph(g,  '%s')" % (subg)
            item = gv.graph(handle, subg)
            graphvizitem = GraphvizSubgraph(self, item)
        else:
            raise ValueError("No graph element type specified")
        self._setattrs(handle=item, **attrs)
        return graphvizitem
 def __init__(self, _out=sys.stdout):
     self.format="svg"
     self.layout="dot"
     sys.path.append(self.GRAPHVIZLIB_PATH)
     import gv
     super(GraphvizGLockWriter, self).__init__(_out)
     self.graph=gv.graph("glockdump")
 def __init__(self, _out=sys.stdout):
     self.format = "svg"
     self.layout = "dot"
     sys.path.append(self.GRAPHVIZLIB_PATH)
     import gv
     super(GraphvizGLockWriter, self).__init__(_out)
     self.graph = gv.graph("glockdump")
Example #8
0
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
Example #9
0
def create_graph():
    logger.debug('Creating graph...')

    graph = gv.graph('xsls')
    gv.setv(graph, 'charset', 'utf-8')
    gv.setv(graph, 'rankdir', 'LR')

    item = gv.protoedge(graph)
    gv.setv(item, 'minlen', '10')
    gv.setv(item, 'dir', 'forward')

    return graph
Example #10
0
def draw_note(g):
    global aColor
    gv.graph(g, "cluster_0")
    g1 = gv.findsubg(g, "cluster_0")
    gv.setv(g1, "color", "white")

    aNodes = []
    length = 0
    for key in aColor:
        c = aColor[key]
        n = gv.node(g1, key)
        gv.setv(n, "shape", "box")
        gv.setv(n, "style", "filled")
        gv.setv(n, "color", c)
        gv.setv(n, "label", key)
        aNodes.append(key)
        length = length + 1

    for i in range(0, length - 1):
        e = gv.edge(g1, aNodes[i], aNodes[i + 1])
        gv.setv(e, "style", "invis")
Example #11
0
def draw_note(g):
    global aColor
    gv.graph(g, "cluster_0")
    g1 = gv.findsubg(g, "cluster_0")
    gv.setv(g1, "color", "white")

    aNodes = []
    length = 0
    for key in aColor:
        c = aColor[key]
        n = gv.node(g1, key)
        gv.setv(n, "shape", "box")
        gv.setv(n, "style", "filled")
        gv.setv(n, "color", c)
        gv.setv(n, "label", key)
        aNodes.append(key)
        length =  length +1

    for i in range(0, length-1):
        e = gv.edge(g1, aNodes[i], aNodes[i+1])
        gv.setv(e, "style", "invis")
Example #12
0
    def draw(self, graph, nodes, nesting):
        subgraph = gv.graph(graph, self.uid.encode('utf-8'))
        gv.setv(subgraph, 'label', self.uid.encode('utf-8'))
        # gv.setv(subgraph, 'rank', 'same')
        gv.setv(subgraph, 'shape', 'box')
        gv.setv(subgraph, 'bgcolor', self.color % (150+nesting*25) if '%' in self.color else self.color)

        for node_uid in self.members:
            if node_uid in nodes:
                gv.node(subgraph, node_uid.encode('utf-8'))

        for child in self.children:
            child.draw(subgraph, nodes, nesting=nesting+1)
Example #13
0
    def draw(self, graph, nodes, nesting):
        subgraph = gv.graph(graph, self.uid.encode('utf-8'))
        gv.setv(subgraph, 'label', self.uid.encode('utf-8'))
        # gv.setv(subgraph, 'rank', 'same')
        gv.setv(subgraph, 'shape', 'box')
        gv.setv(subgraph, 'bgcolor', self.color % (150+nesting*25) if '%' in self.color else self.color)

        for node_uid in self.members:
            if node_uid in nodes:
                gv.node(subgraph, node_uid.encode('utf-8'))

        for child in self.children:
            child.draw(subgraph, nodes, nesting=nesting+1)
Example #14
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
Example #15
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
Example #16
0
		if not s1_cont in ls:
			ls.append(s1_cont)
			ds[s1_name] = s1_cont

	s2 = m1.group(3)
	m2 = r2.match(s2)
	s2_name = m2.group(1)
	s2_cont = filter_cont(m2.group(2))
	if not s2_cont in ls:
		ls.append(s2_cont)
		ds[s2_name] = s2_cont

	t = m1.group(2)
	lt.append((s1_cont, s2_cont, t))

G = gv.graph("G")
N = gv.protonode(G)
E = gv.protoedge(G)
gv.setv(N, 'shape', 'box')

dNodes = {}
for node in ls:
	name = node
	dNodes[name] = gv.node(G, name)

for k in lt:
	edge = gv.edge(dNodes[k[0]], dNodes[k[1]])
	gv.setv(edge, 'label', k[2])
	gv.setv(edge, 'dir', "forward")

gv.layout(G, 'dot')
Example #17
0
import gv,sys
gv.graph("shreyak")
Example #18
0
 def __init__(self, minv, maxv):
     self.gr = gv.graph('py')
     self.set_style()
     self.set_value_range(minv, maxv)
     return
Example #19
0
        if not s1_cont in ls:
            ls.append(s1_cont)
            ds[s1_name] = s1_cont

    s2 = m1.group(3)
    m2 = r2.match(s2)
    s2_name = m2.group(1)
    s2_cont = filter_cont(m2.group(2))
    if not s2_cont in ls:
        ls.append(s2_cont)
        ds[s2_name] = s2_cont

    t = m1.group(2)
    lt.append((s1_cont, s2_cont, t))

G = gv.graph("G")
N = gv.protonode(G)
E = gv.protoedge(G)
gv.setv(N, 'shape', 'box')

dNodes = {}
for node in ls:
    name = node
    dNodes[name] = gv.node(G, name)

for k in lt:
    edge = gv.edge(dNodes[k[0]], dNodes[k[1]])
    gv.setv(edge, 'label', k[2])
    gv.setv(edge, 'dir', "forward")

gv.layout(G, 'dot')
Example #20
0
        except ImportError:
            gv_found = False

igraph_found = True
igraph = None

try:
    import igraph
except ImportError:
    igraph_found = False
    pass

if gv_found:
    # gv needs libag to be initialised before using any read methods,
    # making a graph here seems to ensure aginit() is called
    gv.graph(' ')

cairo_found = True
cairo = None

try:
    import cairo
except ImportError:
    cairo_found = False
    pass

geoip_found = True
GeoIP = None

try:
    import GeoIP
Example #21
0
        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

    for filename in filenames:
        node = gv.node(subgraph, clean(filename))
        gv.setv(node, 'label', filename)


    for dirname in dirnames:
        subgraphfun(subgraph, clean(os.path.join(dirpath,dirname)), dirname)
Example #22
0
	def __init__(self, minv, maxv):
		self.gr = gv.graph('py')
		self.set_style()
		self.set_value_range(minv, maxv)
		return
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 ###################
##################################################################
Example #24
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