Example #1
0
def create_node_graph(output="jpg"):
    nodes = {}
    switch_edge_ports = {}
    edge_list = []

    for link in discovery.adjacency_list:
        node1_name = longlong_to_octstr(link[0])[6:].replace(':', '')
        node2_name = longlong_to_octstr(link[2])[6:].replace(':', '')
        nodes[node1_name] = True
        nodes[node2_name] = True
        edge_list.append((node1_name, node2_name))
        switch_edge_ports[(node1_name, node2_name)] = (link[1], link[3])

    g = pydot.graph_from_edges(edge_list, directed=True)

    # for all edge inferred by discovery, set port labels
    for linkt in switch_edge_ports:
        edgel = g.get_edge(linkt[0], linkt[1])
        if type(edgel) != type([]):
            edgel.set('headlabel', str(switch_edge_ports[linkt][1]))
            edgel.set('taillabel', str(switch_edge_ports[linkt][0]))
        else:
            for edge in edgel:
                edge.set('headlabel', str(switch_edge_ports[linkt][1]))
                edge.set('taillabel', str(switch_edge_ports[linkt][0]))

    for node in g.get_node_list():
        node.set('style', 'filled,setlinewidth(2)')
        node.set('fillcolor', '#ffffcc')
        node.set('color', '#99cc99')
        node.set('tooltip', 'switch')

    return dot_output(g, "pyapps/www/discovery." + output)
Example #2
0
def makebranchgrapsh(data, commdct):
    """return the edges for the all branches"""
    allgraphs = []
    alledges = []

    objkey = 'BRANCH'
    cnamefield = "Component %s Name"
    inletfield = "Component %s Inlet Node Name"
    outletfield = "Component %s Outlet Node Name"

    numobjects = len(data.dt[objkey])
    cnamefields = loops.repeatingfields(data, commdct, objkey, cnamefield)
    inletfields = loops.repeatingfields(data, commdct, objkey, inletfield)
    outletfields = loops.repeatingfields(data, commdct, objkey, outletfield)

    inlts = loops.extractfields(data, commdct, 
        objkey, [inletfields] * numobjects)
    cmps = loops.extractfields(data, commdct, 
        objkey, [cnamefields] * numobjects)
    otlts = loops.extractfields(data, commdct, 
        objkey, [outletfields] * numobjects)

    zipped = list(zip(inlts, cmps, otlts))
    tzipped = [transpose2d(item) for item in zipped]
    for i in range(len(data.dt[objkey])):
        tt = tzipped[i]
        # branchname = data.dt[objkey][i][1]
        edges = []
        for t0 in tt:
            edges = edges + [(t0[0], t0[1]), (t0[1], t0[2])]
        g=pydot.graph_from_edges(edges, directed=True)
        allgraphs.append(g)
        alledges = alledges + edges
    return alledges
Example #3
0
def dump(node):
    global filecnt
    for c in node:
        if c.tag == "dependencies":
            if c.get('type') == 'collapsed-dependencies':
                filecnt += 1
                edge_list = []
                governor_iter = c.getiterator('governor')
                dependent_iter = c.getiterator('dependent')
                # for e in c.getiterator("governor"):
                #     print(e.tag)
                for governor, dependent in zip(governor_iter, dependent_iter):
                    print('{} {}'.format(governor.text, dependent.text))
                    edge_list.append([governor.text, dependent.text])
                # if c.tag == 'governor':
                #     print('governor:'.format(c.text))
                # elif c.tag == 'dependent':
                #     print('dependent:'.format(c.text))
                g = pydot.graph_from_edges(edge_list, directed=True)
                g.write('./pydot{0:02d}.png'.format(filecnt), prog='dot', format='png')
                edge_list.clear()
            # print(c.keys())
            # for i in c:
            #     if i.tag == 'word':
            #         who = i.text
            #     if i.tag == 'NER' and i.text == 'PERSON':
            #         print(who);who=''
        dump(c)
Example #4
0
def task_57(root):
    """
	57. 係り受け解析
	Stanford Core NLPの係り受け解析の結果(collapsed-dependencies)を有向グラフとして可視化せよ.可視化には,係り受け木をDOT言語に変換し,Graphvizを用いるとよい.また,Pythonから有向グラフを直接的に可視化するには,pydotを使うとよい.
	"""
    """
	具体的には、ROOTと各単語、依存関係の発生している方向を各エッジについて読み込んで、それを描画すればok.
	"""

    # ひとまず、依存関係を各文章毎に書き出してみる
    edge_list = []
    for i, sentence in enumerate(root[0][0]):
        print i, "番目の文の依存関係は..."
        tmp = []
        for dependency in sentence[3]:
            print dependency[0].text, "->", dependency[1].text
            tmp.append(tuple([dependency[0].text, dependency[1].text]))
        edge_list.append(tmp)
        print "\n"

    # 同じディレクトリ以下にgraph_pngという書き出し用のディレクトリを作成。。。
    for i, edges in enumerate(edge_list):
        g = pydot.graph_from_edges(edges, directed=True)
        file_name = "./graph_png/nlp_" + str(i) + ".png"
        g.write_png(file_name, prog='dot')

    return
def create_node_graph(output = "jpg"):
    nodes = {}
    switch_edge_ports = {} 
    edge_list = [] 

    for link in discovery.adjacency_list:    
        node1_name = longlong_to_octstr(link[0])[6:].replace(':','')
        node2_name = longlong_to_octstr(link[2])[6:].replace(':','')
        nodes[node1_name] = True
        nodes[node2_name] = True
        edge_list.append((node1_name, node2_name))
        switch_edge_ports[(node1_name, node2_name)] = (link[1], link[3])

    g = pydot.graph_from_edges(edge_list, directed=True)

    # for all edge inferred by discovery, set port labels    
    for linkt in switch_edge_ports:
        edgel = g.get_edge(linkt[0], linkt[1])
        if type(edgel) != type([]):
            edgel.set('headlabel',str(switch_edge_ports[linkt][1]))
            edgel.set('taillabel',str(switch_edge_ports[linkt][0]))
        else:    
            for edge in edgel:
                edge.set('headlabel',str(switch_edge_ports[linkt][1]))
                edge.set('taillabel',str(switch_edge_ports[linkt][0]))

    for node in g.get_node_list():
        node.set('style', 'filled,setlinewidth(2)')
        node.set('fillcolor', '#ffffcc')
        node.set('color', '#99cc99')
        node.set('tooltip', 'switch')

    return dot_output(g, "pyapps/www/discovery."+output)
Example #6
0
def modalsmap(words,conditionals):
    '''
    given a speech list in the form of {'YOUNG SIWARD': ['What', 'is','thy',
    'name','?'], } creates a graphviz map of conditionals per (important)
    character
    '''
    import pydot

    all = []
    for char, words in conditionals.items():
        for word in words:
            all.append((char,word[0].lower()))

            
    graphic = pydot.graph_from_edges(all)
    for char in conditionals:
        new = pydot.Node(char,color='green',shape='doubleoctagon',fontname='Arial',fontsize='12',rank='source', ranksep = '1.2')
        graphic.add_node(new)
    for char, word in all:
        new = pydot.Node(word,color='purple',shape='note',fontname='Arial',fontsize='8')
        graphic.add_node(new)


    graphic.set_overlap('TRUE')
    graphic.set_splines('True')
    graphic.set_suppress_disconnected('TRUE')
    graphic.write_png('/tmp/test.png',prog='twopi')
Example #7
0
def graph(x, name=None):
    """Display a directed graph of the Component structure of x

    :param x: A Component or Manager to graph
    :type  x: Component or Manager

    :param name: A name for the graph (defaults to x's name)
    :type  name: str

    @return: A directed graph representing x's Component sturcture.
    @rtype:  str
    """
    def getname(c):
        return "%s-%s" % (c.name, md5(str(hash(c))).hexdigest()[-4:])

    if HAS_PYDOT:
        graph_edges = []
        for (u, v) in edges(x):
            graph_edges.append(("\"%s\"" % getname(u), "\"%s\"" % getname(v)))

        g = pydot.graph_from_edges(graph_edges, directed=True)
        g.write("%s.dot" % (name or x.name))
        g.write("%s.png" % (name or x.name), format="png")

    def printer(d, x):
        return "%s* %s" % (" " * d, x)

    return "\n".join(walk(x, printer))
Example #8
0
def read_graph(fname):
    g = pydot.graph_from_edges([])

    # g = read_as_info(g, '%s.as_info' % fname)
    g = read_edges(g, "%s.edges" % fname)

    return g
def graph_to_pydot(g, **kwds):
    """ Return a pydot Graph from a graph.

    :Parameters: 

        - `g`: a graph implementing :class:`openalea.container.interface.graph.IEdgeListGraph` interface.
        -`prog`: default is dot. value must one of :

            * dot for hierarchical layout of directed graph
            * neato and fdp for spring model layouts
            * twopi for radial layout
            * circo for circular layout

    :Returns: 

        - A pydot graph.

    :Examples:

        >>> dotg = graph_to_pydot(g)
        >>> dotg.write_svg('toto.svg', prog='circo')

    """
    edges = set((str(g.source(eid)), str(g.target(eid))) for eid in g.edges())
    graph = pydot.graph_from_edges(edges, directed=True)

    return graph
Example #10
0
def grph(edges,filename):
   g=pydot.graph_from_edges(edges) 
   if filename:
       f = filename + ".svg"
   else:
       f = "graph.svg"
   g.write_svg(f, prog='dot') 
Example #11
0
def plot2d(g, image_name, scale=None, orientation=90):
    """Compute an image of the tree via graphviz.

    :Parameters:

        - `g` (int) : an MTG object
        - `image_name` (str) : output filename e.g. test.png

    :Optional parameters:

        - `scale` (int): represents the MTG's scale to look at (default max)
        - `orientation` (int): orientation angle (default 90)

    """
    import pydot
    if scale is None:
        scale = max(g.scales_iter())
    label = g.property('label')
    edges = g.iteredges(scale=scale)

    if label:
        f = lambda id: label.get(id, str(id))
    else:
        f = str
    pydot_graph = pydot.graph_from_edges(
        ((f(x), f(y)) for x, y in g.iteredges(scale=scale)))

    # Attributes
    pydot_graph.set('orientation', orientation)

    ext = os.path.splitext(image_name)[1].strip('.')
    return pydot_graph.write(image_name, prog='dot', format=ext)
Example #12
0
def makebranchgrapsh(data, commdct):
    """return the edges for the all branches"""
    allgraphs = []
    alledges = []

    objkey = 'BRANCH'
    cnamefield = "Component %s Name"
    inletfield = "Component %s Inlet Node Name"
    outletfield = "Component %s Outlet Node Name"

    numobjects = len(data.dt[objkey])
    cnamefields = loops.repeatingfields(data, commdct, objkey, cnamefield)
    inletfields = loops.repeatingfields(data, commdct, objkey, inletfield)
    outletfields = loops.repeatingfields(data, commdct, objkey, outletfield)

    inlts = loops.extractfields(data, commdct, objkey,
                                [inletfields] * numobjects)
    cmps = loops.extractfields(data, commdct, objkey,
                               [cnamefields] * numobjects)
    otlts = loops.extractfields(data, commdct, objkey,
                                [outletfields] * numobjects)

    zipped = zip(inlts, cmps, otlts)
    tzipped = [transpose2d(item) for item in zipped]
    for i in range(len(data.dt[objkey])):
        tt = tzipped[i]
        # branchname = data.dt[objkey][i][1]
        edges = []
        for t0 in tt:
            edges = edges + [(t0[0], t0[1]), (t0[1], t0[2])]
        g = pydot.graph_from_edges(edges, directed=True)
        allgraphs.append(g)
        alledges = alledges + edges
    return alledges
Example #13
0
def plot2d(g, image_name, scale=None, orientation=90 ):
    """Compute an image of the tree via graphviz.

    :Parameters:

        - `g` (int) : an MTG object
        - `image_name` (str) : output filename e.g. test.png

    :Optional parameters:

        - `scale` (int): represents the MTG's scale to look at (default max)
        - `orientation` (int): orientation angle (default 90)

    """
    import pydot
    if scale is None:
        scale = max(g.scales_iter())
    label = g.property('label')
    edges = g.iteredges(scale=scale)

    if label:
        f = lambda id: label.get(id, str(id))
    else:
        f = str
    pydot_graph = pydot.graph_from_edges(((f(x), f(y)) for x, y in g.iteredges(scale=scale)))

    # Attributes
    pydot_graph.set('orientation', orientation)

    ext = os.path.splitext(image_name)[1].strip('.')
    return pydot_graph.write(image_name, prog='dot',format=ext)
Example #14
0
def graph(x, name=None):
    """Display a directed graph of the Component structure of x

    :param x: A Component or Manager to graph
    :type  x: Component or Manager

    :param name: A name for the graph (defaults to x's name)
    :type  name: str

    @return: A directed graph representing x's Component sturcture.
    @rtype:  str
    """

    def getname(c):
        return "%s-%s" % (c.name, md5(str(hash(c))).hexdigest()[-4:])

    if HAS_PYDOT:
        graph_edges = []
        for (u, v) in edges(x):
            graph_edges.append(("\"%s\"" % getname(u), "\"%s\"" % getname(v)))

        g = pydot.graph_from_edges(graph_edges, directed=True)
        g.write("%s.dot" % (name or x.name))
        g.write("%s.png" % (name or x.name), format="png")

    def printer(d, x):
        return "%s* %s" % (" " * d, x)

    return "\n".join(walk(x, printer))
Example #15
0
def grph(edges, filename):
    g = pydot.graph_from_edges(edges)
    if filename:
        f = filename + ".svg"
    else:
        f = "graph.svg"
    g.write_svg(f, prog='dot')
Example #16
0
File: main.py Project: dioh/arplot
def plot_graph(rel, file_name):
    import pydot # import pydot or you're not going to get anywhere my friend :D 

    # first you create a new graph, you do that with pydot.Dot()
    #graph = pydot.Dot(graph_type='digraph')

    graph = pydot.graph_from_edges(rel, directed = True)
    graph.write_png(file_name)
Example #17
0
def graph(node, filename=None):
    edges = descend(node)
    g = pydot.graph_from_edges(edges)
    if filename is not None:
        f = filename + ".png"
    else:
        f = "graph.png"
    g.write(f, prog="dot", format="png")
Example #18
0
def draw_tree(edges, sentence_id):
    n = pydot.Node('node')
    n.fontname = "AppleGothic.ttf"
    n.fontsize = 9
    n.fontcolor = "blue"
    g = pydot.graph_from_edges(edges, directed=True)
    g.add_node(n)
    g.write_jpeg('57/{}.jpg'.format(sentence_id), prog='dot')
Example #19
0
def graph(node, filename):
    edges = descend(node)
    g = pydot.graph_from_edges(edges)
    if filename:
        f = filename + ".png"
    else:
        f = "graph.png"
    g.write_png(f, prog='dot')
Example #20
0
def graph(node, filename):
	edges = descend(node)
	g=pydot.graph_from_edges(edges) 
	if filename:
		f = filename + ".png"
	else:
		f = "graph.png"
	g.write_png(f, prog='dot') 
Example #21
0
File: 44.py Project: oamam/100knock
def draw_tree(edges):
    n = pydot.Node('node')
    n.fontname = "AppleGothic.ttf"
    n.fontsize = 9
    n.fontcolor = "blue"
    g = pydot.graph_from_edges(edges, directed=True)
    g.add_node(n)
    g.write_jpeg('44.jpg', prog='dot')
Example #22
0
def showGraph(chunkList): #chunkのリストを受け取って、そこからグラフを表示までやってくれる関数を作る
    edges = []
    for c in chunkList:
        if c.dst != -1:
            edges.append((c.getText().encode('utf-8'),chunkList[c.dst].getText().encode('utf-8'))) #cがかかりもと、chunkList[c.dst]がかかり先のchunkインスタンス

    g = pydot.graph_from_edges(edges,directed = True)
    g.write_jpeg('dot.jpg', prog='dot')
Example #23
0
    def make_dot(self):
        import pydot

        edges = []
        for node in self.toplevel_nodes:
            for claimed in node.claimed_nodes:
                edges.append((str(node), str(claimed)))
        g = pydot.graph_from_edges(edges)
        g.write_jpeg("graph_from_edges_dot.jpg", prog="dot")
Example #24
0
def fourtyfour():
    import pydot
    chunk_list = fourtyone()
    chunks = chunk_list[10]
    edges = []
    for chunk in chunks:
        edges.append((int(chunk.dep_id), chunk.dst))
    g = pydot.graph_from_edges(edges)
    g.write_jpeg('graph_from_edges_dot.jpg', prog='dot')
Example #25
0
    def view_dynkin_diagram(self, action):
        """
        Draw the generalized Dynkin diagram associated to the current basis
        """

        #        TODO:
        #        1) dialog to save jpeg file
        #        2) better managment of temporary file

        nq = self.__app.Groupoid.braid_for_basis(
            self.__app.Groupoid.Bases[self.__app.Groupoid.CurrentBasis])
        nq = triang(self.__app.Groupoid.NumberOfParameters, nq,
                    self.__app.Groupoid.Order)
        edges = []
        for i in xrange(self.__app.Groupoid.Rank):
            edges.append((i + 1, i + 1))
            for j in xrange(i + 1, self.__app.Groupoid.Rank):
                if notone(self.__app.Groupoid.NumberOfParameters, nq[i][j],
                          self.__app.Groupoid.Order):
                    edges.append((i + 1, j + 1))
        jpeg = pydot.graph_from_edges(edges)
        for i in xrange(self.__app.Groupoid.Rank):
            ei = jpeg.get_edge(str(i + 1), str(i + 1))
            ei.set('headlabel', nq[i][i])
            ei.set('color', 'transparent')
            for j in xrange(i + 1, self.__app.Groupoid.Rank):
                try:
                    eij = jpeg.get_edge(str(i + 1), str(j + 1))
                    eij.set_label(nq[i][j])
                except:
                    pass
        nl = jpeg.get_node_list()
        for n in nl:
            n.set('style', 'filled')
            n.set('fillcolor', 'red')
            n.set('shape', 'circle')
            n.set('fixedsize', 'true')
            n.set('width', .3)

        jpeg.write_jpeg('dynkin.jpg', prog='neato')

        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_title('Dynkin diagram')
        window.set_resizable(False)
        window.set_border_width(10)

        vbox = gtk.VBox(False, 0)
        window.add(vbox)
        vbox.show()

        image = gtk.Image()
        image.set_from_file("dynkin.jpg")
        image.show()

        vbox.pack_end(image, True, True, 2)
        window.show()
Example #26
0
def showGraph(chunkList):  #chunkのリストを受け取って、そこからグラフを表示までやってくれる関数を作る
    edges = []
    for c in chunkList:
        if c.dst != -1:
            edges.append((c.getText().encode('utf-8'),
                          chunkList[c.dst].getText().encode('utf-8')
                          ))  #cがかかりもと、chunkList[c.dst]がかかり先のchunkインスタンス

    g = pydot.graph_from_edges(edges, directed=True)
    g.write_jpeg('dot.jpg', prog='dot')
Example #27
0
def dependency_to_graph(dependency):
    edges = []
    for dep in dependency.findall("dep"):
        governor = dep.find("governor")
        dependent = dep.find("dependent")
        edges.append((graph_rep(governor), graph_rep(dependent)))

    for e in edges:
        print(e)
    return pydot.graph_from_edges(edges)
Example #28
0
def run():
    if len(sys.argv) != 2:
        print >> sys.stderr, 'Usage: %s filename' % os.path.basename(sys.argv[0])
        return 1
        
    edges = [map(int, l[:-1].split()) for l in open(sys.argv[1])][1:]
    
    g = pydot.graph_from_edges(edges)
    basename = sys.argv[1][:sys.argv[1].rfind('.')]
    g.write_png(basename + '.png')
Example #29
0
 def graph(sentence):
     edges = []
     for chunk in sentence:
         if chunk.dst == -1:
             continue
         direction = (chunk.join_surface(),
                      sentence[chunk.dst].join_surface())
         edges.append(direction)
     g = pydot.graph_from_edges(edges, directed=True)
     g.write_png('knock44.png')
Example #30
0
def run():
    if len(sys.argv) != 2:
        print >> sys.stderr, 'Usage: %s filename' % os.path.basename(
            sys.argv[0])
        return 1

    edges = [map(int, l[:-1].split()) for l in open(sys.argv[1])][1:]

    g = pydot.graph_from_edges(edges)
    basename = sys.argv[1][:sys.argv[1].rfind('.')]
    g.write_png(basename + '.png')
Example #31
0
    def graph_title(self, title):
        s = set()
        l = []

        for ref in self.refs:
            if not ref[0].startswith("%s." % title):
                continue
            for to in ref[1]:
                if not to.startswith("%s." % title):
                    continue
                s.add((ref[0], to))
                l.append((ref[0], to))


        g = pydot.graph_from_edges(l, directed=True)
        #g.write_jpeg("graphs/%s.jpg" % title)
        g.write_pdf("graphs/default/%s.pdf" % title)

        g = pydot.graph_from_edges(s, directed=True)
        #g.write_jpeg("graphs/%s_no_dups.jpg" % title)
        g.write_pdf("graphs/no_dups/%s.pdf" % title)
Example #32
0
def create_graph(edges, seq):

    graph = pydot.graph_from_edges(edge_list=edges, directed=True)

    # フォント設定
    n = pydot.Node("node")
    n.fontname = "Osaka.ttf"
    n.fontsize = 9
    graph.add_node(n)

    # グラフを出力
    graph.write_png("graph/graph_from_edges_dot_" + str(seq) + ".png", prog="dot")
Example #33
0
    def view_dynkin_diagram(self, action):
        """
        Draw the generalized Dynkin diagram associated to the current basis
        """

#        TODO: 
#        1) dialog to save jpeg file 
#        2) better managment of temporary file

        nq = self.__app.Groupoid.braid_for_basis(self.__app.Groupoid.Bases[self.__app.Groupoid.CurrentBasis])
        nq = triang(self.__app.Groupoid.NumberOfParameters,nq,self.__app.Groupoid.Order)
        edges = []
        for i in xrange(self.__app.Groupoid.Rank):
            edges.append((i+1,i+1))
            for j in xrange(i+1,self.__app.Groupoid.Rank):
                if notone(self.__app.Groupoid.NumberOfParameters, nq[i][j], self.__app.Groupoid.Order):
                    edges.append((i+1,j+1))
        jpeg=pydot.graph_from_edges(edges)
        for i in xrange(self.__app.Groupoid.Rank):
            ei = jpeg.get_edge(str(i+1),str(i+1))
            ei.set('headlabel',nq[i][i])
            ei.set('color','transparent')
            for j in xrange(i+1,self.__app.Groupoid.Rank):
                try:
                    eij = jpeg.get_edge(str(i+1),str(j+1))
                    eij.set_label(nq[i][j])
                except:
                    pass
        nl = jpeg.get_node_list()
        for n in nl:
            n.set('style','filled')
            n.set('fillcolor','red')
            n.set('shape','circle')
            n.set('fixedsize','true')
            n.set('width',.3)

        jpeg.write_jpeg('dynkin.jpg', prog='neato')

        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_title('Dynkin diagram')
        window.set_resizable(False)
        window.set_border_width(10)
        
        vbox = gtk.VBox(False, 0)
        window.add(vbox)
        vbox.show()

        image = gtk.Image()
        image.set_from_file("dynkin.jpg")
        image.show()
        
        vbox.pack_end(image, True, True, 2)
        window.show()
Example #34
0
def convert_dotlang(tree):
    i = 0
    root = tree.getroot()
    for depend in root.findall('.//dependencies'):
        if depend.get('type') == "collapsed-dependencies":
            data = []
            for dep in depend.findall('dep'):
                g = dep.find('governor').text
                d = dep.find('dependent').text
                data.append((g, d))
            g = pydot.graph_from_edges(data)
            g.write_jpeg('./fig/sen{}.jpg'.format(i), prog='dot')
            i += 1
Example #35
0
File: core.py Project: abayer/hue
 def graph(self):
   """
   Returns a pydot.Dot object representing the dependency graph.
   Requires pydot to be available.
   """
   import pydot
   edges = set()
   for p in self.packages.values():
     for f in p.files:
       for id in f.requires:
         f2 = self.get(id)
         edges.add( ("--".join([p.key, f.shortname]), "--".join([f2.package.key, f2.shortname])) )
   return pydot.graph_from_edges(edges, directed=True)
Example #36
0
def vis_dag(chunks):
    chunk_names = list(
        map(lambda chunk: "_".join([m.surface for m in chunk.morphs]), chunks))
    edges = []
    for idx, chunk in enumerate(chunks):
        if chunk.dst < 0:
            continue
        edges.append((chunk_names[idx], chunk_names[chunk.dst]))
    for idx, edge in enumerate(edges):
        print("{}: {}".format(idx, edge))
    if True:
        g = pydot.graph_from_edges(edges)
        g.write_jpeg("44.jpeg", prog="dot")
Example #37
0
def convert_dotlang(tree):
    i = 0
    root = tree.getroot()
    for depend in root.findall('.//dependencies'):
        if depend.get('type') == "collapsed-dependencies":
            data = []
            for dep in depend.findall('dep'):
                g = dep.find('governor').text
                d = dep.find('dependent').text
                data.append((g, d))
            g = pydot.graph_from_edges(data)
            g.write_jpeg('./fig/sen{}.jpg'.format(i), prog='dot')
            i += 1
Example #38
0
 def graph(self):
     """
 Returns a pydot.Dot object representing the dependency graph.
 Requires pydot to be available.
 """
     import pydot
     edges = set()
     for p in self.packages.values():
         for f in p.files:
             for id in f.requires:
                 f2 = self.get(id)
                 edges.add(("--".join([p.key, f.shortname]),
                            "--".join([f2.package.key, f2.shortname])))
     return pydot.graph_from_edges(edges, directed=True)
Example #39
0
def draw_knode(aknode,outfile=''):
    """draw a pretty figure of a knode
    """
    import sets,pydot
    edges = Edges()
    aknode.traverse(edges)

    g = pydot.graph_from_edges(edges.edges)
    g.add_node(pydot.Node(name='node',color='lightblue2',style='filled'))
    g.parent_graph.type = 'digraph'
    if outfile == '':
        g.write_jpeg('graph_output.jpg', prog='dot')
    else:
        g.write_jpeg(outfile, prog='dot')
Example #40
0
def pyknp_dependency_visualize(comment_list, withstr=False):
    for sentence_list in comment_list:
        graph = []
        for cid, chunk in enumerate(sentence_list):
            if chunk.dst != -1:
                src_str = str(cid) + ":" + chunk.midasi
                dst_str = str(
                    chunk.dst) + ":" + sentence_list[chunk.dst].midasi
                graph.append((src_str, dst_str))
                if withstr:
                    print("{}  =>  {}".format(src_str, dst_str))

        g = pydot.graph_from_edges(graph, directed=True)
        #g.write_png("result.png")
        display_png(Image(g.create_png()))
Example #41
0
def pyknp_dependency_visualize(result_list, withstr=False):
    for result in result_list:
        graph = []
        bnst_dic = dict((x.bnst_id, x) for x in result.bnst_list())
        for bnst in result.bnst_list():
            if bnst.parent_id != -1:
                src_str = "".join(mrph.midasi for mrph in bnst.mrph_list())
                dst_str = "".join(mrph.midasi for mrph in bnst_dic[bnst.parent_id].mrph_list())
                graph.append((src_str, dst_str))
                if withstr:
                    print("{}  =>  {}".format(src_str,dst_str))

        g=pydot.graph_from_edges(graph,directed=True)
        #g.write_png("result.png")
        display_png(Image(g.create_png()))
Example #42
0
def printGraph(ingraph,outputname='out.jpg'):
    """Gets an NetworkGraph object and 'prints' it in jpg file."""
    print 'Building DNS cache...'
    dnscache={}
    for t in ingraph.graph.keys():
        if not t in dnscache.keys() and not t==OurNode:
            try: dnscache[t]=socket.gethostbyaddr(t)[0]
            #added gaierror to avoid exceptions on grapher nodes:
            except(socket.herror,socket.gaierror): pass
    if MakeASNLookup:
        print 'Building ASN cache...'
        ascache={}
        for t in ingraph.graph.keys():
            if not t in ascache.keys() and not t==OurNode:
                try: ascache[t]=query.getASN(t)
                except:pass
    if MakeCountryLookup:
        print 'Building country code cache...'
        ccache={}
        for t in ingraph.graph.keys():
            if not t in ccache.keys() and not t==OurNode:
                try: ccache[t]=query.getCountry(t)
                except:pass
    edges=[]
    print 'Creating the output image...'
    for k in ingraph.graph.keys():
        for t in ingraph.graph[k]:
            if not (k,t) in edges:
                edge1=t
                edge2=k
                if t in dnscache.keys():
                    edge1=dnscache[t]
                if k in dnscache.keys():
                    edge2=dnscache[k]
                if MakeASNLookup:
                    if t in ascache.keys():
                        edge1+=" ["+str(ascache[t])+"]"
                    if k in ascache.keys():
                        edge2+=" ["+str(ascache[k])+"]"
                if MakeCountryLookup:
                    if t in ccache.keys():
                        edge1+=" ["+str(ccache[t])+"]"
                    if k in ascache.keys():
                        edge2+=" ["+str(ccache[k])+"]"
                if not (edge2,edge1) in edges:edges.append((edge1,edge2))
    g=pydot.graph_from_edges(edges)
    g.dpi=GraphDpi
    g.write_jpeg(outputname, prog='dot') 
Example #43
0
    def solve(self):
        '''
        insert your code
        '''
        pcttc = ParseCabochaTextToChunks()
        text = pcttc.parse('neko.txt.cabocha')

        sentence = text[7]      # As the dependency graph becomes too complex, we visualize only 8th sentence in this time
        edges = []
        for chunk in sentence:
            if chunk.dst is not None:
                edges.append((chunk.get_text(), sentence[chunk.dst].get_text()))
        g = pydot.graph_from_edges(edges)
        g.write_jpeg('44.jpg', prog='dot')
        
        return None
Example #44
0
def cabocha_dependency_visualize(novel_list, withstr=False):
    for sentence_list in novel_list:
        graph = []
        for chunk in sentence_list:
            src_str=chunk.surfaces()
            dst_str=""
            if chunk.dst!=-1:
                dst_str=sentence_list[chunk.dst].surfaces()
            if src_str!="" and dst_str!="":
                graph.append((src_str,dst_str))
                if withstr:
                    print("{}  =>  {}".format(src_str,dst_str))
        
        g=pydot.graph_from_edges(graph,directed=True)
        #g.write_png("result.png")
        display_png(Image(g.create_png()))
Example #45
0
def plot_graph():
    import pydot

    edges_list = []
    metadata = MetadataHistory()

    for obj in ModelObjectIterator():
        history = metadata.getHistory(obj.getID())
        for i in range(len(history) - 1):
            f = lambda x: "%s -> %s" % (obj.getID(), x.update_controller_action)
            edge = (f(history[i]), f(history[i + 1]))
            edges_list.append(edge)

    graph = pydot.graph_from_edges(edges_list, directed=True)

    graph.write_png("/home/danito/.faraday/history.png")
Example #46
0
def plot_graph():
    import pydot

    edges_list = []
    metadata = MetadataHistory()

    for obj in ModelObjectIterator():
        history = metadata.getHistory(obj.getID())
        for i in range(len(history) - 1):
            f = lambda x: "%s -> %s" % (obj.getID(), x.update_controller_action
                                        )
            edge = (f(history[i]), f(history[i + 1]))
            edges_list.append(edge)

    graph = pydot.graph_from_edges(edges_list, directed=True)

    graph.write_png("/home/danito/.faraday/history.png")
Example #47
0
File: 44.py Project: yagays/nlp100
def dependency_tree(sentence, filename="output/44.png"):
    edge = []
    for chunk in sentence:
        if not chunk.srcs:
            continue

        for i in chunk.srcs:
            source_chunk = sentence[i]
            target_chunk = chunk

            if source_chunk.phrase_wo_mark() and target_chunk.phrase_wo_mark():
                edge.append([
                    source_chunk.phrase_wo_mark(),
                    target_chunk.phrase_wo_mark()
                ])
    graph = pydot.graph_from_edges(edge)
    graph.write_png(filename)
Example #48
0
def main(f):
    tree = ET.parse(f)
    elem = tree.getroot()
    for dependencies in elem.findall(".//dependencies"):
        edge = []
        if dependencies.attrib.get("type") == "collapsed-dependencies":                
            for dep in dependencies.findall(".//dep"):
                dep_tuple = (dep[0].text,dep[1].text)
                if "," in dep_tuple or "." in dep_tuple:
                    pass
                else:
                    edge.append(dep_tuple)
        if len(edge) != 0:           
            g = pydot.graph_from_edges(edge, directed = True)
            g.write_jpeg("test_graph.jpg", prog='dot')
            #初めの分だけグラフを作りたかったので 
            break
Example #49
0
def graph(x, name=None):
    """Display a directed graph of the Component structure of x

    @param x: A Component or Manager to graph
    @type  x: Component or Manager

    @param name: A name for the graph (defaults to x's name)
    @type  name: str

    @return: A directed graph representing x's Component sturcture.
    @rtype:  str
    """

    try:
        import pydot
        
        graph_edges = []
        nodes = []
        names = []
        for (u, v) in edges(x):
            if v.name in names and v not in nodes:
                i = 1
                new_name = "%s-%d" % (v.name, i)
                while new_name in names:
                    i += 1
                    new_name = "%s-%d" % (v.name, i)
                graph_edges.append((u.name, new_name))
            else:
                nodes.append(u)
                nodes.append(v)
                names.append(v.name)
                graph_edges.append((u.name, v.name))

        g = pydot.graph_from_edges(graph_edges, directed=True)
        g.write("%s.dot" % (name or x.name))
        g.write("%s.png" % (name or x.name), format="png")
    except ImportError:
        pass
    except:
        raise

    def printer(d, x):
        return "%s* %s" % (" " * d, x)

    return "\n".join(walk(x, printer))
Example #50
0
def graph(x, name=None):
    """Display a directed graph of the Component structure of x

    @param x: A Component or Manager to graph
    @type  x: Component or Manager

    @param name: A name for the graph (defaults to x's name)
    @type  name: str

    @return: A directed graph representing x's Component sturcture.
    @rtype:  str
    """

    try:
        import pydot

        graph_edges = []
        nodes = []
        names = []
        for (u, v) in edges(x):
            if v.name in names and v not in nodes:
                i = 1
                new_name = "%s-%d" % (v.name, i)
                while new_name in names:
                    i += 1
                    new_name = "%s-%d" % (v.name, i)
                graph_edges.append((u.name, new_name))
            else:
                nodes.append(u)
                nodes.append(v)
                names.append(v.name)
                graph_edges.append((u.name, v.name))

        g = pydot.graph_from_edges(graph_edges, directed=True)
        g.write("%s.dot" % (name or x.name))
        g.write("%s.png" % (name or x.name), format="png")
    except ImportError:
        pass
    except:
        raise

    def printer(d, x):
        return "%s* %s" % (" " * d, x)

    return "\n".join(walk(x, printer))
Example #51
0
    def solve(self):
        '''
        insert your code
        '''
        pcttc = ParseCabochaTextToChunks()
        text = pcttc.parse('neko.txt.cabocha')

        sentence = text[
            7]  # As the dependency graph becomes too complex, we visualize only 8th sentence in this time
        edges = []
        for chunk in sentence:
            if chunk.dst is not None:
                edges.append(
                    (chunk.get_text(), sentence[chunk.dst].get_text()))
        g = pydot.graph_from_edges(edges)
        g.write_jpeg('44.jpg', prog='dot')

        return None
def tree_to_pydot(t, root=None, **kwds):
    """ Return a pydot directed Graph from a tree.

    :Parameters: 
        - `t`: a tree implementing :class:`openalea.container.interface.tree.ITree` interface.
    :Returns: 
        - A pydot graph.

    :Examples:

        >>> dotg = tree_to_pydot(t)
        >>> dotg.write_svg('toto.svg', prog='dot')

    """
    if root is None:
        root = t.root
    edges = set((str(t.parent(vid)), str(vid)) for vid in pre_order(t, root) if vid != root)
    graph = pydot.graph_from_edges(edges, directed=True)

    return graph
Example #53
0
 def toDot(self):
     import pydot
     edges = []
     edg_keys = []
     for g in self.vertices:
         g_lab = str(g) + " - " + (self.vertice_labelling[g])
         for g2 in self.edges[g]:
             g2_lab = str(g2) + " - " + (self.vertice_labelling[g2])
             edges.append((g_lab,g2_lab))
             edg_keys.append((g,g2))  
     #print edges,edg_keys
     g = pydot.graph_from_edges(edges,directed=True)
     for e in g.edge_list:
         i = edges.index((e.get_source(),e.get_destination()))
         if self.edge_labelling[edg_keys[i]]=="+":
             e.set_label("+")
         elif self.edge_labelling[edg_keys[i]]=="-":
             e.set_label("-")
             e.set_arrowhead("tee")
         else: # no info
             e.set_label(self.edge_labelling[edg_keys[i]])
             e.set_arrowhead("none")
     return g
Example #54
0
    def rebuildDAG(self):
        # we will only build a DAG with the nodes that actually have a relationship
        # all single nodes are omitted, this includes the ones without a known DOI
        allDois  = []
        DAG      = []

        papers = KKDocument.objects.all()
        for p in papers:
            if p.doi != "": allDois.append( p.doi )

        allDois = uniq( allDois )

        for doi in allDois:
            doc = get_document(doi)
            for c in doc.citings.split(';'):
                if c in allDois:
                    child  = self.cleanAndWrapStr(get_document(c).title)
                    parent = self.cleanAndWrapStr(get_document(doi).title)
                    DAG.append( (parent, child) )

        import pydot

        g = pydot.graph_from_edges(DAG, directed=True)
        g.write_jpeg('dag.jpg', prog='dot')
Example #55
0
import pydot

class Lista(list):
    def __init__(self):
        list.__init__(self)

    def edges(self):
        lista=[]
        for n in range(len(self)-1):
            lista.append((self.__getitem__(n),self.__getitem__(n+1)))
        return lista


hola=Lista()
hola+=[1,2,3,4,5,1,2,3,1,23,1,4,5,6]
edges=hola.edges()
g=pydot.graph_from_edges(edges) 
g.write_png('graph_from_edges_dot.png', prog='dot') 
Example #56
0
from q53 import *

import pydot



if __name__ == "__main__":
    root = readXml("nlp_sample.txt.xml") #xmlから木構造を作る

    edges = []

    for sentences in root.iter("sentences"):
        for sentence in sentences.iter("sentence"):
            sentenceId = sentence.get("id")
            for dependency in sentence.iter("dependencies"):
                if dependency.get("type") == "collapsed-dependencies":
                    for dep in dependency.iter("dep"):
                        type = dep.get("type")
                        gov = "%s(%s,%s)" % (dep.find("governor").text,sentenceId,dep.find("governor").get("idx"))
                        dependent = "%s(%s,%s)" % (dep.find("dependent").text,sentenceId,dep.find("dependent").get("idx"))

                        edges.append((gov,dependent))
#graph = pydot.Doc(graph_type='')
#graph.add_edge(edge)
#graph.write_png("aaa.png")

#StanfordCoreNLPではtodotformat()として、出力をdot言語にできる

    g = pydot.graph_from_edges(edges,directed=True)
    g.write_jpeg("dot.jpg",prog = "dot")
def makeplantloop(iddfile, fname):
    """make the plant loop"""
    data, commdct = readidf.readdatacommdct(fname, iddfile=iddfile)


    # in plantloop get:
    #     demand inlet, outlet, branchlist
    #     supply inlet, outlet, branchlist
    plantloops = loops.plantloopfields(data, commdct)
    plantloop = plantloops[0]
    #     
    # supply barnchlist
    #     branch1 -> inlet, outlet
    #     branch2 -> inlet, outlet
    #     branch3 -> inlet, outlet
    sbranchlist = plantloop[3]
    if sbranchlist.strip() != "":
        sbranches = loops.branchlist2branches(data, commdct, sbranchlist)
        s_in_out = [loops.branch_inlet_outlet(data, commdct, 
                                        sbranch) for sbranch in sbranches]
        sbranchinout = dict(zip(sbranches, s_in_out))                            

    dbranchlist = plantloop[6]
    if dbranchlist.strip() != "":
        dbranches = loops.branchlist2branches(data, commdct, dbranchlist)
        d_in_out = [loops.branch_inlet_outlet(data, commdct, 
                                        dbranch) for dbranch in dbranches]
        dbranchinout = dict(zip(dbranches, d_in_out))                            
    #     
    # splitters
    #     inlet
    #     outlet1
    #     outlet2
    splitters = loops.splitterfields(data, commdct)
    #     
    # mixer
    #     outlet
    #     inlet1
    #     inlet2

    mixers = loops.mixerfields(data, commdct)
    #     
    # supply barnchlist
    #     branch1 -> inlet, outlet
    #     branch2 -> inlet, outlet
    #     branch3 -> inlet, outlet
    #         
    # CONNET INLET OUTLETS
    edges = []
    # get all branches
    branchkey = "branch".upper()
    branches = data.dt[branchkey]
    branch_i_o = {}
    for br in branches:
        br_name = br[1]
        in_out = loops.branch_inlet_outlet(data, commdct, br_name)
        branch_i_o[br_name] = dict(zip(["inlet", "outlet"], in_out))
    for br_name, in_out in branch_i_o.items():
        edges.append((in_out["inlet"], br_name))
        edges.append((br_name, in_out["outlet"]))



    # connect splitter to nodes
    for splitter in splitters:
        # splitter_inlet = inletbranch.node
        splittername = splitter[0]
        inletbranchname = splitter[1] 
        splitter_inlet = branch_i_o[inletbranchname]["outlet"]
        # edges = splitter_inlet -> splittername
        edges.append((splitter_inlet, splittername))
        # splitter_outlets = ouletbranches.nodes
        outletbranchnames = [br for br in splitter[2:]]
        splitter_outlets = [branch_i_o[br]["inlet"] for br in outletbranchnames]
        # edges = [splittername -> outlet for outlet in splitter_outlets]
        moreedges = [(splittername, outlet) for outlet in splitter_outlets]
        edges = edges + moreedges

    for mixer in mixers:
        # mixer_outlet = outletbranch.node
        mixername = mixer[0]
        outletbranchname = mixer[1] 
        mixer_outlet = branch_i_o[outletbranchname]["inlet"]
        # edges = mixername -> mixer_outlet
        edges.append((mixername, mixer_outlet))
        # mixer_inlets = inletbranches.nodes
        inletbranchnames = [br for br in mixer[2:]]
        mixer_inlets = [branch_i_o[br]["outlet"] for br in inletbranchnames]
        # edges = [mixername -> inlet for inlet in mixer_inlets]
        moreedges = [(inlet, mixername) for inlet in mixer_inlets]
        edges = edges + moreedges

    # connect demand and supply side
    for plantloop in plantloops:
        supplyinlet = plantloop[1]
        supplyoutlet = plantloop[2]
        demandinlet = plantloop[4]
        demandoutlet = plantloop[5]
        # edges = [supplyoutlet -> demandinlet, demandoutlet -> supplyinlet]
        moreedges = [(supplyoutlet, demandinlet), (demandoutlet, supplyinlet)]
        edges = edges + moreedges
    
    g=pydot.graph_from_edges(edges, directed=True) 
    return g