コード例 #1
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)
コード例 #2
0
 def writeEnd(self):
     import gv
     gv.layout(self.graph, self.layout)
     if isinstance(self.out, basestring):
         gv.render(self.graph, self.format, self.out)
     else:
         gv.render(self.graph, self.format)
コード例 #3
0
ファイル: ast.py プロジェクト: janelee307/pyREtic-1
    def saveTree(self, filename):
        '''
        Saves the image of AST built with the current node as a root node.

        @param filename:
            filename to which to save. 'png' extension will be appended.

        '''

        import graph
        import gv
        gr = graph.digraph()
        queue = [self]
        i = 0
        h = {}
        while len(queue):
            n = queue.pop()
            h[n] = i
            gr.add_node(i, [('label', n.value)])
            if n.children is not None:
                queue.extend(n.children)
            i += 1
        queue = [self]
        while len(queue):
            n = queue.pop()
            if n.children is not None:
                for c in n.children:
                    gr.add_edge(h[n], h[c])
                    queue.append(c)
        dot = gr.write(fmt='dot')
        gvv = gv.readstring(dot)
        gv.layout(gvv, 'dot')
        gv.render(gvv, 'png', str(filename) + '.png')
コード例 #4
0
    def drawGraph(self, inputs):

        fileName = 'planetModel.png'
        gr = graph()
        self.addGraphNode(1, gr, inputs)
        # Draw as PNG
        #with open("./planetModel.viz", 'wb') as f:
        #dot = write(gr,f)
        #f.write(dot)
        #gvv = gv.readstring(dot)
        #gv.layout(gvv,'dot')
        #gv.render(gvv,'png', fileName)
        #f.close()

        gst = digraph()
        self.addGraphNode(1, gst, inputs)
        with open("./planetModel.viz", 'wb') as f:
            #st, order = breadth_first_search(gst, root=1)
            #gst2 = digraph()
            #gst2.add_spanning_tree(gst.nodes())
            #gst2.(1, 'post')
            dot = write(gst, f)
            f.write(dot)
            gvv = gv.readstring(dot)
            gv.layout(gvv, 'dot')
            gv.render(gvv, 'png', fileName)
            f.close()

        return fileName
コード例 #5
0
ファイル: fa.py プロジェクト: afrolovskiy/compilers_labs
    def draw(self, filename):
        print "initial state:", self.initial_state
        print "final states", self.final_state	
        print "transition table:", self.transition_table 

        vertexes = self.transition_table.keys()
        edges = self._edges()

        gr = digraph()        
        #gr.add_nodes([str(vertex) for vertex in vertexes])
        for vertex in vertexes:
            attrs = []
            
            if ((isinstance(self.final_state, list) and vertex in self.final_state) or
                    (isinstance(self.final_state, int) and vertex == self.final_state)):
                attrs.append('final')
            gr.add_node(str(vertex), attrs=attrs)

        for edge, label in edges.items():
            label = ', '.join(label)
            gr.add_edge(edge=edge, label=label)

        dot = write(gr)
        gvv = gv.readstring(dot)
        gv.layout(gvv, 'dot')
        gv.render(gvv, 'png', '%s.png' % filename)
コード例 #6
0
ファイル: tree.py プロジェクト: lud4ik/learn
 def visualize(self):
     xmldoc = minidom.parse(self.path)
     self.create(xmldoc.childNodes[0])
     dot = 'digraph graphname {{{}{}\n}}\n'.format(self.nodes, self.edges)
     gvv = gv.readstring(dot)
     gv.layout(gvv, 'dot')
     gv.render(gvv, 'png', self.output)
コード例 #7
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
コード例 #8
0
    def draw(self, filename):
        print "initial state:", self.initial_state
        print "final states", self.final_state
        print "transition table:", self.transition_table

        vertexes = self.transition_table.keys()
        edges = self._edges()

        gr = digraph()
        #gr.add_nodes([str(vertex) for vertex in vertexes])
        for vertex in vertexes:
            attrs = []

            if ((isinstance(self.final_state, list)
                 and vertex in self.final_state)
                    or (isinstance(self.final_state, int)
                        and vertex == self.final_state)):
                attrs.append('final')
            gr.add_node(str(vertex), attrs=attrs)

        for edge, label in edges.items():
            label = ', '.join(label)
            gr.add_edge(edge=edge, label=label)

        dot = write(gr)
        gvv = gv.readstring(dot)
        gv.layout(gvv, 'dot')
        gv.render(gvv, 'png', '%s.png' % filename)
コード例 #9
0
 def writeEnd(self):
     import gv
     gv.layout(self.graph, self.layout)
     if isinstance(self.out, basestring):
         gv.render(self.graph, self.format, self.out)
     else:
         gv.render(self.graph, self.format)
コード例 #10
0
ファイル: rdf.py プロジェクト: slok/metaproxy
def str_to_graph_file(rdfString, uri, storePath, fileType='png'):
    stre = parse_string(rdfString, uri)
    dotSer = serialize_stream(stre, 'dot')

    gvv = gv.readstring(dotSer)
    gv.layout(gvv,'dot')
    gv.render(gvv,fileType,storePath)
コード例 #11
0
def drawGraphFromSM(SM, names, outFile):
	fig = plt.figure(1)
	plot1 = plt.imshow(SM, origin='upper', cmap=cm.gray, interpolation='nearest')
	plt.show()
		
	gr = graph()

	namesNew = []
	for i,f in enumerate(names):	
		if sum(SM[i,:])>0:
			gr.add_nodes([f])
			namesNew.append(f)
			
	Max = SM.max()
	Mean = mean(SM)

	Threshold = Mean * 1.5
	for i in range(len(names)):
		for j in range(len(names)):
			if i<j:
				if SM[i][j] > 0:
					gr.add_edge((names[i], names[j]))
	# Draw as PNG
	dot = write(gr)
	gvv = gv.readstring(dot)
	gv.layout(gvv,'dot')
	gv.render(gvv,'png', outFile)
コード例 #12
0
ファイル: planetModel.py プロジェクト: jsrawan-mobo/mrbigdata
 def drawGraph(self, inputs):
     
     fileName = 'planetModel.png'
     gr = graph()
     self.addGraphNode(1,gr, inputs)
 # Draw as PNG
     #with open("./planetModel.viz", 'wb') as f:
         #dot = write(gr,f)
         #f.write(dot)
         #gvv = gv.readstring(dot)
         #gv.layout(gvv,'dot')
         #gv.render(gvv,'png', fileName)
         #f.close()
         
     gst = digraph()
     self.addGraphNode(1,gst, inputs)            
     with open("./planetModel.viz", 'wb') as f:            
         #st, order = breadth_first_search(gst, root=1)
         #gst2 = digraph()
         #gst2.add_spanning_tree(gst.nodes())
         #gst2.(1, 'post')
         dot = write(gst,f)
         f.write(dot)
         gvv = gv.readstring(dot)
         gv.layout(gvv,'dot')
         gv.render(gvv,'png', fileName)   
         f.close()         
         
         
          
     return fileName
コード例 #13
0
def plot_graph(gr):
    """
    draws the graph to file
    """
    p = 100.0 / (len(gr.nodes())+1)
    gr_ext = graph()

    
    for node in gr.nodes():
        if coin(p):
            if not gr_ext.has_node(node):
                gr_ext.add_node(node,attrs=gr.node_attributes(node))
            for n in [ ed[0] for ed in gr.edges() if ed[1] == node ]:
                if coin(0.3):
                    if not gr_ext.has_node(n):
                        gr_ext.add_node(n,attrs=gr.node_attributes(n))
                    #print "Edges:",gr_ext.edges()
                    if not gr_ext.has_edge((node,n)):
                        gr_ext.add_edge((node,n)) 
    dot = write(gr_ext)
    gvv = gv.readstring(dot)
    gv.layout(gvv,'dot')    
    if args[1]== 'karate.txt':
        gv.render(gvv,'png','community1.png') 
    elif args[1] == 'email.txt':
        gv.render(gvv,'png','community2.png')
    elif args[1] == 'hep-th-citations.txt':
        gv.render(gvv,'png','community3.png')
    elif args[1] == 'amazon1.txt':
        gv.render(gvv,'png','community4.png')
    elif args[1] == 'p2p-Gnutella30.txt':
        gv.render(gvv,'png','community5.png')
コード例 #14
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)
コード例 #15
0
ファイル: utils.py プロジェクト: AlexP11223/re-lab
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
コード例 #16
0
ファイル: dag.py プロジェクト: Shootfast/grafpy
	def show(self):
		'Simple method to generate a dotgraph and render it with graphviz'
		import gv
		import os
		import time
		
		dot = self.get_dot()
		# write the dotfile out for testing
		self.write_dot('/tmp/dag.dot')
		
		# Apply the dot layout to the graph
		gvo = gv.readstring(dot) # graphviz object
		gv.layout(gvo, 'dot')
		
		# render the layout into the node attributes
		gv.render(gvo)
		
		# write to a temp file and display in default viewer
		fileout = '/tmp/out.png'
		if os.path.exists(fileout):
			os.remove(fileout)
		gv.render(gvo, 'png', fileout)
		time.sleep(1)
		os.system('xdg-open %s 2> /dev/null' % fileout)
		
		
コード例 #17
0
ファイル: graph_drawer.py プロジェクト: IdenGit/questgen
    def draw(self, path):

        for state in self.kb.filter(facts.State):
            self.add_node(state)

        for jump in self.kb.filter(facts.Jump):
            self.add_edge(jump)

        for link in self.kb.filter(facts.OptionsLink):
            self.add_link(link)

        ######################
        # draw subgraph
        ######################

        subgraphs = []

        for event in self.kb.filter(facts.Event):
            subgraphs.append(SubGraph(uid=event.uid, color=HEAD_COLORS.EVENT_SUBGRAPH, members=event.members))

        for subquest in self.kb.filter(facts.SubQuest):
            subgraphs.append(SubGraph(uid=subquest.uid, color=HEAD_COLORS.SUBQUEST_SUBGRAPH, members=subquest.members))

        for subgraph in subgraphs:
            subgraph.find_children(subgraphs)

        for subgraph in subgraphs:
            subgraph.find_real_children()

        SubGraph.draw_hierarchy(subgraphs, self.graph, self.nodes)

        gv.layout(self.graph, 'dot');
        # gv.render(self.graph, 'dot')
        gv.render(self.graph, path[path.rfind('.')+1:], path)
コード例 #18
0
ファイル: graph_drawer.py プロジェクト: igroglaz/questgen
    def draw(self, path):

        for state in self.kb.filter(facts.State):
            self.add_node(state)

        for jump in self.kb.filter(facts.Jump):
            self.add_edge(jump)

        for link in self.kb.filter(facts.OptionsLink):
            self.add_link(link)

        ######################
        # draw subgraph
        ######################

        subgraphs = []

        for event in self.kb.filter(facts.Event):
            subgraphs.append(SubGraph(uid=event.uid, color=HEAD_COLORS.EVENT_SUBGRAPH, members=event.members))

        for subquest in self.kb.filter(facts.SubQuest):
            subgraphs.append(SubGraph(uid=subquest.uid, color=HEAD_COLORS.SUBQUEST_SUBGRAPH, members=subquest.members))

        for subgraph in subgraphs:
            subgraph.find_children(subgraphs)

        for subgraph in subgraphs:
            subgraph.find_real_children()

        SubGraph.draw_hierarchy(subgraphs, self.graph, self.nodes)

        gv.layout(self.graph, 'dot');
        # gv.render(self.graph, 'dot')
        gv.render(self.graph, path[path.rfind('.')+1:], path)
コード例 #19
0
ファイル: rdf.py プロジェクト: slok/metaproxy
def rdf_to_graph_file(rdfLink, storePath, fileType='png'):
    stre = parse_link(rdfLink)
    dotSer = serialize_stream(stre, 'dot')

    gvv = gv.readstring(dotSer)
    gv.layout(gvv,'dot')
    gv.render(gvv,fileType,storePath)
コード例 #20
0
def save_as_pdf(gr,filename,show_weights=False):

    from pygraph.readwrite.dot import write
    import gv
    dot = write(gr, weighted=show_weights)
    gvv = gv.readstring(dot)
    gv.layout(gvv,'fdp')
    gv.render(gvv,'pdf',filename)
コード例 #21
0
ファイル: re_graphviz.py プロジェクト: giulianoxt/yaree
def render_graph(g, filename, output_dot = None):
    gv.setv(g, 'center', 'true')
    gv.setv(g, 'fontname', 'helvetica')
    gv.layout(g, 'dot')
    
    if (output_dot):
        gv.write(g, output_dot)
    
    gv.render(g, 'png', filename) 
コード例 #22
0
ファイル: visualize.py プロジェクト: lud4ik/learn
def visualize_with_pygraph(args):
    data, nodes = get_input(args.file)
    graph = digraph()
    graph.add_nodes(nodes)
    for start, stop, distance in emit_edge(data):
        graph.add_edge((start, stop), distance)
    dot = write(graph, weighted=True)
    gvv = gv.readstring(dot)
    gv.layout(gvv, 'dot')
    gv.render(gvv, 'png', args.out)
コード例 #23
0
def generate_graph_image (wcbg, png_file):
	g = digraph ()
	g.add_graph (wcbg)
	for edge in g.edges ():
		g.set_edge_weight (edge, wcbg.edge_weight (edge))
	dot = write (g, True)
	gvv = gv.readstring (dot)
	gv.layout (gvv, 'dot')
	png_file = png_file + '.png'
	gv.render (gvv, 'png', png_file)
コード例 #24
0
def generate_graph_image(wcbg, png_file):
    g = digraph()
    g.add_graph(wcbg)
    for edge in g.edges():
        g.set_edge_weight(edge, wcbg.edge_weight(edge))
    dot = write(g, True)
    gvv = gv.readstring(dot)
    gv.layout(gvv, 'dot')
    png_file = png_file + '.png'
    gv.render(gvv, 'png', png_file)
コード例 #25
0
ファイル: script.py プロジェクト: lmagno/wkf2pepa
def dot_pdf(wkf):
	# Write to DOT language and create a pdf file of the digraph with its name
	dot = write(wkf)

	with open(wkf.name + '.dot', 'w') as f:
		f.write(dot)
	
	gvv = gv.readstring(dot)
	gv.layout(gvv,'dot')
	gv.render(gvv,'pdf', wkf.name + '.pdf')
コード例 #26
0
    def matriz_relaciones(self,id_item):
        """
        Obtiene una matriz de la relaciones.
        """

        if id_item is not None:
            id_item=int(id_item)

        antecesores=Relaciones.get_antecesores(id_item)
        sucesores=Relaciones.get_sucesores(id_item)
        item=Item.get_item_by_id(id_item)
        relacionados=[]
        usados=[]

        n = len(antecesores)+len(sucesores)+1
        for antecesor in antecesores:
            if antecesor not in relacionados:
                if (antecesor.estado_oculto=="Activo"):
                    relacionados.append(antecesor)
                    usados.append(antecesor.nombre_item)

        if item not in relacionados:
            relacionados.append(item)
            usados.append(item.nombre_item)

        for sucesor in sucesores:
            if sucesor not in relacionados:
                if (sucesor.estado_oculto=="Activo"):
                    relacionados.append(sucesor)
                    usados.append(sucesor.nombre_item)

        #Graph creation
        gr = graph()

        # Add nodes and edges
        for item in usados:
            gr.add_nodes([item])

        # Add relation and edges

        for item in relacionados:
            padres= Relaciones.get_mis_padres(item.id_item)
            if len(padres)>0:
                for padre in padres:
                    gr.add_edge((item.nombre_item, padre.nombre_item))
            else:
                #remover nodo
                print("hola")


        # Draw as PNG
        dot = write(gr)
        gvv = gv.readstring(dot)
        gv.layout(gvv,'dot')
        gv.render(gvv,'png','/home/hermann/saip2011/saip2011/public/images/arbol.png')
コード例 #27
0
ファイル: clutter_viewer.py プロジェクト: Shootfast/grafpy
	def initialise_nodes(self):
		# Bake in the node attributes from 'dot' layout
		gv.layout(self.gvo, 'dot')
		gv.render(self.gvo)
		
		# iterate over node attributes to get/set node positions
		# see gv.3python.pdf for more info
		# as well as https://mailman.research.att.com/pipermail/graphviz-interest/2006q1/003182.html
		n = gv.firstnode(self.gvo)
		
		#store min and max x and y
		minx = 0
		miny = 0
		maxx = None
		maxy = None
		
		# store the node label and position as reported by Dot layout
		nodepos = {} # {<node object>:(x,y)}
		
		while gv.ok(n) : # check that the iterator returned by firstnode is ok
			label = gv.nameof(n)
			
			spos = gv.getv(n,'pos').split(',') # list of strings 
			(xpos,ypos) = [float(i) for i in spos] # convert to float
			
			node = self.dag.get_node_from_label(label)
			pos = node.get_position()
			
			if pos != None:
				# Set xpos and ypos if they are already defined in node.get_position()
				(xpos,ypos) = pos				
			
			print xpos, ypos
			# set min and max values
			if minx > xpos:
				minx = xpos
			if maxx < xpos:
				maxx = xpos
			if miny > ypos:
				miny = ypos
			if maxy < ypos:
				maxy = ypos
			
			nodepos[node] = (xpos, ypos)
			
			#change node before iteration
			n = gv.nextnode(self.gvo, n)
			
		print "min", minx, miny
		print "max", maxx, maxy
			
		# Set the position in all nodes
		for node, pos in nodepos.iteritems():			
			node.set_position(pos)
コード例 #28
0
    def savePythonGraph(self, filename):
        '''
        Saves CFG as a png image by means of graphviz.

        @param filename: CFG will be saved to "filename.png"

        '''
        try:
            import graph
            import gv
        except ImportError:
            print '# Err: no modules for drawing graphs found... try:'
            print '#> sudo apt-get install python-setuptools ' \
                                                   '# needed for the next line'
            print '#> sudo easy_install python-graph '\
                                           '# This actually installs the thing'
            print '#> sudo apt-get install libgv-python ' \
                                             '# for graphviz in python support'
            print '#> sudo apt-get install python-pydot # for pydot'
            return None
        pattern1 = re.compile(r'\n')
        pattern2 = re.compile(r'\"')
        gr = graph.digraph()
        for n in self.nodes:
            if self.nodes[n].code != '':
                if self.nodes[n].condition is not None:
                    txt = re.sub(pattern1, r'\\l', self.nodes[n].code + \
                          '\n\n' + str(self.nodes[n].condition))
                    txt = re.sub(pattern2, r'\\"', txt)
                    gr.add_node(n, [('label', '"' + txt + '"')])
                    #print '1:::'
                    #print txt
                else:
                    txt = re.sub(pattern1, r'\\l', self.nodes[n].code)
                    txt = re.sub(pattern2, r'\\"', txt)
                    gr.add_node(n, [('label', '"' + txt + '"')])
                    #print '2:::'
                    #print txt
            else:
                txt = re.sub(pattern1, r'\\l', str(self.nodes[n].condition))
                txt = re.sub(pattern2, r'\\"', txt)
                gr.add_node(n, [('label', '"' + txt + '"')])
            if not self.nodes[n].conditional:
                gr.add_node_attribute(n, ('shape', 'box'))
        for n in self.nodes:
            for e in self.nodes[n].outgoing:
                gr.add_edge(n, e.toNode, label=e.type)
        dot = gr.write(fmt='dot')
        #print '>>>>>'
        #print dot
        #print '<<<<<'
        gvv = gv.readstring(dot)
        gv.layout(gvv, 'dot')
        gv.render(gvv, 'png', str(filename) + '.png')
コード例 #29
0
    def savePythonGraph(self, filename):
        '''
        Saves CFG as a png image by means of graphviz.

        @param filename: CFG will be saved to "filename.png"

        '''
        try:
            import graph
            import gv
        except ImportError:
            print '# Err: no modules for drawing graphs found... try:'
            print '#> sudo apt-get install python-setuptools ' \
                                                   '# needed for the next line'
            print '#> sudo easy_install python-graph '\
                                           '# This actually installs the thing'
            print '#> sudo apt-get install libgv-python ' \
                                             '# for graphviz in python support'
            print '#> sudo apt-get install python-pydot # for pydot'
            return None
        pattern1 = re.compile(r'\n')
        pattern2 = re.compile(r'\"')
        gr = graph.digraph()
        for n in self.nodes:
            if self.nodes[n].code != '':
                if self.nodes[n].condition is not None:
                    txt = re.sub(pattern1, r'\\l', self.nodes[n].code + \
                          '\n\n' + str(self.nodes[n].condition))
                    txt = re.sub(pattern2, r'\\"', txt)
                    gr.add_node(n, [('label', '"' + txt + '"')])
                    #print '1:::'
                    #print txt
                else:
                    txt = re.sub(pattern1, r'\\l', self.nodes[n].code)
                    txt = re.sub(pattern2, r'\\"', txt)
                    gr.add_node(n, [('label', '"' + txt + '"')])
                    #print '2:::'
                    #print txt
            else:
                txt = re.sub(pattern1, r'\\l', str(self.nodes[n].condition))
                txt = re.sub(pattern2, r'\\"', txt)
                gr.add_node(n, [('label', '"' + txt + '"')])
            if not self.nodes[n].conditional:
                gr.add_node_attribute(n, ('shape', 'box'))
        for n in self.nodes:
            for e in self.nodes[n].outgoing:
                gr.add_edge(n, e.toNode, label=e.type)
        dot = gr.write(fmt='dot')
        #print '>>>>>'
        #print dot
        #print '<<<<<'
        gvv = gv.readstring(dot)
        gv.layout(gvv, 'dot')
        gv.render(gvv, 'png', str(filename) + '.png')
コード例 #30
0
ファイル: vuash.py プロジェクト: lmagno/wkf2pepa
def dot_pdf(wkf):
	# Write to 'dot' language and create a pdf file of the digraph with its name
	dot = write(wkf)

	dot_file = open(wkf.name + '.dot', "w")
	dot_file.write(dot)
	dot_file.close()
	
	gvv = gv.readstring(dot)
	gv.layout(gvv,'dot')
	gv.render(gvv,'pdf', wkf.name + '.pdf')
コード例 #31
0
ファイル: grapher.py プロジェクト: slackeater/anal-beh
    def export(self, graph, path, type):
        """
        Export the graph
        """
        dot = write(graph)
        gvv = gv.readstring(dot)
        gv.setv(gvv,'rankdir','LR')
        gv.layout(gvv,'dot')

        graphname = path + '/' + type + '.svg-' + str(time.time())
        gv.render(gvv, 'svg', graphname)
        return graphname
コード例 #32
0
def _dep_graph(fn, specs, silent=False):
    """
    Create a dependency graph for the given easyconfigs.
    """

    # check whether module names are unique
    # if so, we can omit versions in the graph
    names = set()
    for spec in specs:
        names.add(spec['ec']['name'])
    omit_versions = len(names) == len(specs)

    def mk_node_name(spec):
        if spec.get('external_module', False):
            node_name = "%s (EXT)" % spec['full_mod_name']
        elif omit_versions:
            node_name = spec['name']
        else:
            node_name = ActiveMNS().det_full_module_name(spec)

        return node_name

    # enhance list of specs
    all_nodes = set()
    for spec in specs:
        spec['module'] = mk_node_name(spec['ec'])
        all_nodes.add(spec['module'])
        spec['unresolved_deps'] = [
            mk_node_name(s) for s in spec['unresolved_deps']
        ]
        all_nodes.update(spec['unresolved_deps'])

    # build directed graph
    dgr = digraph()
    dgr.add_nodes(all_nodes)
    for spec in specs:
        for dep in spec['unresolved_deps']:
            dgr.add_edge((spec['module'], dep))

    # write to file
    dottxt = dot.write(dgr)
    if fn.endswith(".dot"):
        # create .dot file
        write_file(fn, dottxt)
    else:
        # try and render graph in specified file format
        gvv = gv.readstring(dottxt)
        gv.layout(gvv, 'dot')
        gv.render(gvv, fn.split('.')[-1], fn)

    if not silent:
        print "Wrote dependency graph for %d easyconfigs to %s" % (len(specs),
                                                                   fn)
コード例 #33
0
ファイル: pumping.py プロジェクト: cloudozer/color_the_graph
def draw_graph(gr):
    """
    draws the graph to file
    """
    print "Nodes levels after 100 steps:"
    for node in gr.nodes():
    	print "Node: %i - level:%.1f" % (node, dict(gr.node_attributes(node)).get('level'))

    dot = write(gr)
    gvv = gv.readstring(dot)
    gv.layout(gvv,'dot')
    gv.render(gvv,'png','pumping.png') 
コード例 #34
0
ファイル: pumping.py プロジェクト: cloudozer/color_the_graph
def draw_graph(gr):
    """
    draws the graph to file
    """
    print "Nodes levels after 100 steps:"
    for node in gr.nodes():
        print "Node: %i - level:%.1f" % (node, dict(
            gr.node_attributes(node)).get('level'))

    dot = write(gr)
    gvv = gv.readstring(dot)
    gv.layout(gvv, 'dot')
    gv.render(gvv, 'png', 'pumping.png')
コード例 #35
0
ファイル: graphcategories.py プロジェクト: danbretl/mid-tier
    def handle(self, **options):
        gr = graph()

        cats_by_id = dict((c.id, c) for c in Category.objects.all())

        # Add nodes
        dups = count()
        for c in cats_by_id.itervalues():
            try:
                gr.add_node(c)
            except AdditionError:
                dups.next()
                parent = cats_by_id.get(c.parent_id)
                print 'WARNING: duplicate node :: <Category %i | %s>' % (c.id,
                                                                         c)
                print '\twith parent ' + '<Category %i | %s>' % (
                    parent.id, parent) if parent else 'None'

        if dups.next() > 0: return

        # Add edges
        # gr.add_edge((CONCRETE_NODE, ROOT_NODE))
        for c in cats_by_id.itervalues():
            parent = cats_by_id.get(c.parent_id)
            if parent:
                gr.add_edge((c, parent))

        # import ipdb; ipdb.set_trace()
        # The whole tree from the root
        st, order = breadth_first_search(
            gr, root=Category.objects.get(title="Abstract"))
        gst = digraph()
        gst.add_spanning_tree(st)

        dot = write(gst)
        gvv = gv.readstring(dot)

        gv.layout(gvv, 'dot')
        gv.render(gvv, 'pdf', os.path.join(output_dir, 'abstract.pdf'))

        st, order = breadth_first_search(
            gr, root=Category.objects.get(title="Concrete"))
        gst = digraph()
        gst.add_spanning_tree(st)

        dot = write(gst)
        gvv = gv.readstring(dot)

        gv.layout(gvv, 'dot')
        gv.render(gvv, 'pdf', os.path.join(output_dir, 'concrete.pdf'))
コード例 #36
0
ファイル: lib.py プロジェクト: vrthra/trackingvm
 def assert_graphs(self, result, target):
     (_state, graph) = result
     graph = repr(graph)
     ok = graph == target
     if not ok:
         print('target:\n' + target)
         print('result:\n' + graph)
         try:
             graph = readstring(graph)
             layout(graph, 'neato')
             render(graph, 'gtk')
         except Exception, e:
             print(e)
         assert False
コード例 #37
0
ファイル: lib.py プロジェクト: andrewcooke/rxpy
 def assert_graphs(self, result, target):
     (_state, graph) = result
     graph = repr(graph)
     ok = graph == target
     if not ok:
         print('target:\n' + target)
         print('result:\n' + graph)
         try:
             graph = readstring(graph)
             layout(graph, 'neato')
             render(graph, 'gtk')
         except Exception, e:
             print(e)
         assert False
コード例 #38
0
def _dep_graph(fn, specs, silent=False):
    """
    Create a dependency graph for the given easyconfigs.
    """

    # check whether module names are unique
    # if so, we can omit versions in the graph
    names = set()
    for spec in specs:
        names.add(spec['ec']['name'])
    omit_versions = len(names) == len(specs)

    def mk_node_name(spec):
        if spec.get('external_module', False):
            node_name = "%s (EXT)" % spec['full_mod_name']
        elif omit_versions:
            node_name = spec['name']
        else:
            node_name = ActiveMNS().det_full_module_name(spec)

        return node_name

    # enhance list of specs
    all_nodes = set()
    for spec in specs:
        spec['module'] = mk_node_name(spec['ec'])
        all_nodes.add(spec['module'])
        spec['unresolved_deps'] = [mk_node_name(s) for s in spec['unresolved_deps']]
        all_nodes.update(spec['unresolved_deps'])

    # build directed graph
    dgr = digraph()
    dgr.add_nodes(all_nodes)
    for spec in specs:
        for dep in spec['unresolved_deps']:
            dgr.add_edge((spec['module'], dep))

    # write to file
    dottxt = dot.write(dgr)
    if fn.endswith(".dot"):
        # create .dot file
        write_file(fn, dottxt)
    else:
        # try and render graph in specified file format
        gvv = gv.readstring(dottxt)
        gv.layout(gvv, 'dot')
        gv.render(gvv, fn.split('.')[-1], fn)

    if not silent:
        print "Wrote dependency graph for %d easyconfigs to %s" % (len(specs), fn)
コード例 #39
0
ファイル: writer.py プロジェクト: jvorcak/gpylint
    def generate(self, filename):
        '''
        Displays the graph on the canvas
        Uses python-igraph fruchterman-reingold algorithm to decide about
        position of the nodes, then draw these nodes on the canvas and
        draw connections between them
        Author: Jan Vorcak <*****@*****.**>
        '''

        g = gv.readstring(self.source)
        gv.layout(g, 'dot')
        gv.render(g)

        context = CanvasContext().dictionary

        node = gv.firstnode(g)
        while node is not None:
            props = {
                    'filepath' : gv.getv(node, 'filepath'),
                    'title' : gv.getv(node, 'label'),
                    'lineno' : gv.getv(node, 'lineno'),
                    }
            pos = gv.getv(node, 'pos').split(',')
            width = gv.getv(node, 'width')
            height = gv.getv(node, 'height')
            x, y = map(int, pos)
            class_box = ClassBox(props, width, height)
            class_box.matrix.translate(x, y)
            self.view.canvas.add(class_box)
            context[(props['filepath'], props['title'])] = class_box
            node = gv.nextnode(g, node)

        edge = gv.firstedge(g)
        while edge is not None:
            props = {
                    'arrowhead' : gv.getv(edge, 'arrowhead'),
                    'arrowtail' : gv.getv(edge, 'arrowtail'),
                    }

            head = gv.headof(edge)
            tail = gv.tailof(edge)
            head_str = (gv.getv(head, 'filepath'), gv.getv(head, 'label'))
            tail_str = (gv.getv(tail, 'filepath'), gv.getv(tail, 'label'))
            context[head_str]
            context[tail_str]

            edge = gv.nextedge(g, edge)
            set_association(self.view.canvas, context[head_str], \
                    context[tail_str], props)
コード例 #40
0
	def CreateClassDiagram(self):		
		for delphi in self.documentation:
			for delphiClass in delphi.classes:
				self.gr.add_nodes([delphiClass.name])

		for delphi in self.documentation:
			for delphiClass in delphi.classes:
				try:
					self.gr.add_edge((delphiClass.name, delphiClass.superClass))
				except:
					print("Edge already exist")
		dot = write(self.gr)
		gvv = gv.readstring(dot)
		gv.layout(gvv,'dot')
		gv.render(gvv,'svg','Delphi-Classdiagram.svg')
コード例 #41
0
def testGraph():
    gr = graph()
    gr.add_nodes([
        "Portugal", "Spain", "France", "Germany", "Belgium", "Netherlands",
        "Italy"
    ])
    gr.add_nodes([
        "Switzerland", "Austria", "Denmark", "Poland", "Czech Republic",
        "Slovakia", "Hungary"
    ])
    gr.add_nodes(["England", "Ireland", "Scotland", "Wales"])

    gr.add_edge("Portugal", "Spain")
    gr.add_edge("Spain", "France")
    gr.add_edge("France", "Belgium")
    gr.add_edge("France", "Germany")
    gr.add_edge("France", "Italy")
    gr.add_edge("Belgium", "Netherlands")
    gr.add_edge("Germany", "Belgium")
    gr.add_edge("Germany", "Netherlands")
    gr.add_edge("England", "Wales")
    gr.add_edge("England", "Scotland")
    gr.add_edge("Scotland", "Wales")
    gr.add_edge("Switzerland", "Austria")
    gr.add_edge("Switzerland", "Germany")
    gr.add_edge("Switzerland", "France")
    gr.add_edge("Switzerland", "Italy")
    gr.add_edge("Austria", "Germany")
    gr.add_edge("Austria", "Italy")
    gr.add_edge("Austria", "Czech Republic")
    gr.add_edge("Austria", "Slovakia")
    gr.add_edge("Austria", "Hungary")
    gr.add_edge("Denmark", "Germany")
    gr.add_edge("Poland", "Czech Republic")
    gr.add_edge("Poland", "Slovakia")
    gr.add_edge("Poland", "Germany")
    gr.add_edge("Czech Republic", "Slovakia")
    gr.add_edge("Czech Republic", "Germany")
    gr.add_edge("Slovakia", "Hungary")

    # Draw as PNG
    with open("./country.viz", 'wb') as f:
        dot = write(gr, f)
        f.write(dot)
        gvv = gv.readstring(dot)
        gv.layout(gvv, 'dot')
        gv.render(gvv, 'png', 'europe.png')
        Image.open('europe.png').show()
コード例 #42
0
ファイル: helpers.py プロジェクト: libsmelt/Simulator
def output_graph(graph, name, algorithm='neato'):
    """
    Output the graph as png image and also as text file
    @param name Name of the file to write to

    """
    dot = write(graph, True)
    gvv = gv.readstring(dot)

    name = 'graphs/%s' % name

    with open('%s.dot'%name, 'w') as f:
        f.write(dot)

    gv.layout(gvv, algorithm)
    gv.render(gvv, 'png', ('%s.png' % name))
コード例 #43
0
def graphgen(grnodes):
    """Initialises the graph. Ensures that all nodes in the graph are connected.
    Creates an image called graph.png which represents the graph.
    """
    graph = generate(grnodes, int(1.2*grnodes),
                     directed=False, weight_range=(1, 1))
    # Makes sure graphs generated by generate() have all their nodes connected.
    while len(shortest_path(graph, 0)[1]) < grnodes:
        graph = generate(grnodes, int(1.2*grnodes),
                         directed=False, weight_range=(1, 1))
        # print len(shortest_path(graph, 0)[1])
    # Draw as PNG
    dot = write(graph)
    gvv = gv.readstring(dot)
    gv.layout(gvv, 'dot')
    gv.render(gvv, 'png', 'graph.png')
    return graph
コード例 #44
0
ファイル: pdfg.py プロジェクト: backspace4/pdfg
def Main():
    parser = argparse.ArgumentParser()
    parser.add_argument("input_pdf",
                        type=str,
                        help="pdf file that will be analysed.")
    parser.add_argument("-T",
                        "--debug-with-token",
                        action="store_true",
                        help="print token strings.")
    parser.add_argument("-o",
                        "--output-png",
                        default="out.png",
                        help="path to a png file to be written.",
                        type=str)
    args = parser.parse_args()

    tk = Tokenizer(args.input_pdf)

    queue = deque([tk.token(), tk.token(), tk.token()])
    obj_num = ""
    attr = ""
    gr = digraph()

    while not allNone(queue):
        if isObjToken(queue):
            attr = ""
            obj_num = getObjNum(queue)
            if not gr.has_node(obj_num):
                gr.add_node(obj_num)
        elif isIndirect(queue):
            if not gr.has_node(getIndirectNum(queue)):
                gr.add_node(getIndirectNum(queue))
            if not gr.has_edge((obj_num, getIndirectNum(queue))):
                #print "obj: " + obj_num + " to: " + getIndirectNum(queue)
                gr.add_edge((obj_num, getIndirectNum(queue)), label=attr)

        attr = getAttrName(queue, attr)
        debug(queue.popleft(), args.debug_with_token)
        queue.append(tk.token())

    dot = write(gr)
    gvv = gv.readstring(dot)
    gv.layout(gvv, 'dot')
    gv.render(gvv, 'png', args.output_png)
コード例 #45
0
def dep_graph(fn, specs, silent=False):
    """
    Create a dependency graph for the given easyconfigs.
    """

    # check whether module names are unique
    # if so, we can omit versions in the graph
    names = set()
    for spec in specs:
        names.add(spec['module'][0])
    omit_versions = len(names) == len(specs)

    def mk_node_name(mod):
        if omit_versions:
            return mod[0]
        else:
            return '-'.join(mod)

    # enhance list of specs
    for spec in specs:
        spec['module'] = mk_node_name(spec['module'])
        spec['unresolvedDependencies'] = [mk_node_name(s) for s in spec['unresolvedDependencies']]  # [s[0] for s in spec['unresolvedDependencies']]

    # build directed graph
    dgr = digraph()
    dgr.add_nodes([spec['module'] for spec in specs])
    for spec in specs:
        for dep in spec['unresolvedDependencies']:
            dgr.add_edge((spec['module'], dep))

    # write to file
    dottxt = dot.write(dgr)
    if fn.endswith(".dot"):
        # create .dot file
        write_file(fn, dottxt)
    else:
        # try and render graph in specified file format
        gvv = gv.readstring(dottxt)
        gv.layout(gvv, 'dot')
        gv.render(gvv, fn.split('.')[-1], fn)

    if not silent:
        print "Wrote dependency graph for %d easyconfigs to %s" % (len(specs), fn)
コード例 #46
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)
コード例 #47
0
ファイル: deps.py プロジェクト: aecostas/coffeedeps
def main(argv):
    outputfile = "deps.png"

    parser = argparse.ArgumentParser(
        description='Find coffeescript dependencies')
    parser.add_argument('dirs',
                        metavar='dir',
                        nargs='+',
                        help='directories to process')

    parser.add_argument('-o', '--output', help='output file')
    parser.add_argument('-t',
                        action='store_true',
                        help='show dependencies in text mode')

    args = parser.parse_args()

    if args.output is not None:
        outputfile = args.output

    for root, dirs, files in os.walk(args.dirs[0]):
        for f in files:
            fullpath = os.path.join(root, f)
            if os.path.splitext(fullpath)[1] == '.coffee':
                if not prune(fullpath):
                    analyze(fullpath)

    for item in deps:
        for node in deps[item]:
            gr.add_edge((item, "%s.coffee" % (node)))

    if args.t:
        for item in deps:
            print item
            for node in deps[item]:
                print "\t %s.coffee" % (node)

    # Draw as PNG
    dot = write(gr)
    gvv = gv.readstring(dot)
    gv.layout(gvv, 'dot')
    gv.render(gvv, 'png', outputfile)
コード例 #48
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)
コード例 #49
0
def DepGraph(j):
    
    linestring = open('tmp/deps'+str(j)+'.txt', 'r').read()
    lines = linestring.split('\n')  
    
    deps = []
    for _deps in lines:
        ar = _deps.split() 
        if len(ar) > 0:
            deps.append({'from': ar[1].replace(':',''),'to': ar[4].replace(':',''),'vec': ar[6]})

    # znajdz wszystkie instrukcje IND i dodaj je tu
    # deps.append({'from': '12','to': '12','vec': ''})
    # przejrzyj  tmp/petit_loop_0.t  znajdz wszystkie instrukcje od for

    gr = digraph()
    
    
    
    for dep in deps:
        if not gr.has_node(dep['from']):
            gr.add_nodes([dep['from']])
        if not gr.has_node(dep['to']):
            gr.add_nodes([dep['to']])
        
    
    for dep in deps:
        if not gr.has_edge((dep['from'],dep['to'])):
            gr.add_edge((dep['from'],dep['to'])) 
            
    # Draw as PNG
    dot = write(gr)
    gvv = gv.readstring(dot)
    gv.layout(gvv,'dot')
    gv.render(gvv,'png','tmp/scc_'+str(j)+'.png')
    gv.render(gvv, 'eps', 'tmp/scc_' + str(j) + '.eps')

    return gr
コード例 #50
0
# get us some sort order!
sorted_nodes = topological_sorting(gr)
length = len(sorted_nodes)
priority = 1000
for n in sorted_nodes:
    # now that should be the priority in the c file:
    print "%d %s" % (priority, n)
    filename = "../src/iop/%s.c" % n
    if not os.path.isfile(filename):
        filename = "../src/iop/%s.cc" % n
    if not os.path.isfile(filename):
        if not n == "rawspeed":
            print "could not find file `%s', maybe you're not running inside tools/?" % filename
        continue
    replace_all(
        filename, "( )*?(module->priority)( )*?(=).*?(;).*\n",
        "  module->priority = %d; // module order created by iop_dependencies.py, do not edit!\n"
        % priority)
    priority -= 1000.0 / (length - 1.0)

# beauty-print the sorted pipe as pdf:
gr2 = digraph()
gr2.add_nodes(sorted_nodes)
add_edges(gr2)

dot = write(gr2)
gvv = gv.readstring(dot)
gv.layout(gvv, 'dot')
gv.render(gvv, 'pdf', 'iop_deps.pdf')
コード例 #51
0
ファイル: ulggraph.py プロジェクト: sitedata/ulg
def bgp_graph_gen(graphdata, start=None, end=None):
    gr = digraph()

    def transform_nodename(name):
        return name.replace(":", "")

    def transform_label(s):
        return "".join(["&#%d;" % ord(x) for x in s])

    def add_node(graph, v, fillcolor=None, shape='ellipse'):
        vid = transform_nodename(v)
        if (not graph.has_node(vid)):
            params = [('fontsize', FONT_SIZE), ('shape', shape),
                      ('label', transform_label(v))]
            if (fillcolor):
                params = params + [('style', 'filled'),
                                   ('fillcolor', fillcolor)]

            graph.add_node(vid, attrs=params)

    def add_edge(graph,
                 v1,
                 v2,
                 color='black',
                 style='solid',
                 penwidth=REC_LINE_WIDTH,
                 label=None):
        if (v1 == v2):
            return

        vid1 = transform_nodename(v1)
        vid2 = transform_nodename(v2)

        if (not graph.has_edge((vid1, vid2))):
            params = [('color', color), ('style', style),
                      ('penwidth', penwidth)]
            if (label):
                params = params + [
                    ('fontsize', LABEL_FONT_SIZE),
                    ('label', transform_label(" " + label + "  "))
                ]

            graph.add_edge((vid1, vid2), attrs=params)

    for gd in graphdata:
        if (start):
            add_node(gr, start, shape='box', fillcolor=USED_FILL_COLOR)
            add_node(gr, gd[0][0], fillcolor=USED_FILL_COLOR)
            add_edge(gr,
                     start,
                     gd[0][0],
                     color=USED_LINE_COLOR,
                     penwidth=USED_LINE_WIDTH,
                     style='dashed')

        vparams = {}
        eparams = {}
        if (gd[1]['recuse']):
            eparams['color'] = USED_LINE_COLOR
            eparams['penwidth'] = USED_LINE_WIDTH
            vparams['fillcolor'] = USED_FILL_COLOR
        elif (gd[1]['reconly']):
            eparams['color'] = RECONLY_LINE_COLOR
            eparams['style'] = 'dotted'
            eparams['penwidth'] = REC_LINE_WIDTH
        else:
            eparams['penwidth'] = REC_LINE_WIDTH
            eparams['color'] = REC_LINE_COLOR

        i = 0
        while (i < len(gd[0])):
            if (i + 1 < len(gd[0])):
                add_node(gr, gd[0][i], **vparams)
                add_node(gr, gd[0][i + 1], **vparams)

                if ((i == 0) and ('peer' in gd[1])):
                    add_edge(gr,
                             gd[0][i],
                             gd[0][i + 1],
                             label=gd[1]['peer'],
                             **eparams)
                else:
                    add_edge(gr, gd[0][i], gd[0][i + 1], **eparams)
            i = i + 1

        if (end):
            add_node(gr, end, shape='box', fillcolor=USED_FILL_COLOR)
            add_edge(gr,
                     gd[0][-1],
                     end,
                     color=USED_LINE_COLOR,
                     penwidth=USED_LINE_WIDTH,
                     style='dashed')

    dot = write(gr)
    gvv = gv.readstring(dot)
    gv.layout(gvv, 'dot')
    gv.render(gvv, 'png')
コード例 #52
0
ファイル: b1ng.py プロジェクト: wendelas/hacking-com-tapioca
    # Dormindo um pouco para evitar bloqueios
    time.sleep(5)


# Criando grafo
gr = graph()
gr.add_node(RANGE)

# Pegando ips
ips = IPSet([RANGE])

todos = []
for ip in ips:
    todos.append(ip)

# Fazendo shuffle
random.shuffle(todos)
for ip in todos:
    try:
        search(str(ip), gr)
    except httplib.IncompleteRead:
        print "[!] Erro httplib.IncompleteRead: IP (%s)" % ip

st, order = breadth_first_search(gr, root=RANGE)
gst = digraph()
gst.add_spanning_tree(st)
dot = write(gst)
gvv = gv.readstring(dot)
gv.layout(gvv, 'dot')
gv.render(gvv, 'png', 'bing.png')
コード例 #53
0
ファイル: graphDrawer.py プロジェクト: ldyh0456/HTrace
def loads_invalid_obj_list(s):
    decoder = JSONDecoder()
    objs = [decoder.decode(x) for x in s.split()]
    return objs


nodes = loads_invalid_obj_list(sys.stdin.read().strip())
spansBySpanId = {s["SpanID"]: s for s in nodes}
spansByParent = defaultdict(set)

for node in spansBySpanId.values():
    spansByParent[node["ParentID"]].add(node["SpanID"])

count = 0
for x in spansByParent[ROOT_SPAN_ID]:
    count += 1
    gr = digraph()
    gr.add_node(
        x, [("label", spansBySpanId[x]["Description"] + "(" +
             str(spansBySpanId[x]["Stop"] - spansBySpanId[x]["Start"]) + ")")])
    buildGraph(x)
    dot = write(gr)
    gvv = gv.readstring(dot)
    gv.layout(gvv, 'dot')
    gv.render(
        gvv, 'png', './graphs/' + str(datetime.now()) +
        str(spansBySpanId[x]["Description"])[:10] + '.png')

print("Created " + str(count) + " images.")
コード例 #54
0
def render_graph(graph, config):
    gv.layout(graph, 'dot')
    gv.render(graph, config.format, config.output)
コード例 #55
0
ファイル: gv_test.py プロジェクト: Hunter601/Automata-Editor
#!/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)
コード例 #56
0
def _dep_graph_gv(dottxt, filename):
    """Render dependency graph to file using graphviz."""
    # try and render graph in specified file format
    gvv = gv.readstring(dottxt)
    gv.layout(gvv, 'dot')
    gv.render(gvv, os.path.splitext(filename)[-1], filename)