示例#1
0
    def escolherEmparelhamento(self):
        grafox = networkx.from_pydot(self.grafo)
        temM = False

        novoGrafo = pydot.Dot(graph_type='graph')
        for vertice in self.grafo.get_node_list():
            novoGrafo.add_node(vertice)
        for subg in self.grafo.get_subgraph_list():
            if subg.get_name() != 'M':
                novoGrafo.add_subgraph(subg)
                subg.set_rank('same')
        subM = pydot.Subgraph('')
        subM.set_name('M')
        novoGrafo.add_subgraph(subM)

        verticeVizinho = []
        fim = False
        while not fim:
            print "digite o nome do vertice fonte, nada para listar arestas, ou fim para terminar"
            fonte = raw_input(">> ")
            if fonte == '':
                for aresta in self.grafo.get_edge_list():
                    print " aresta:(" + str(aresta.get_source()) + ", " + str(
                        aresta.get_destination()) + ")"
                for aresta in subM.get_edge_list():
                    print " M:(" + str(aresta.get_source()) + ", " + str(
                        aresta.get_destination()) + ")"
            elif fonte == 'fim':
                fim = True
            else:
                print "digite o no alvo"
                alvo = raw_input(">> ")
                if (fonte, alvo) in grafox.edges():
                    if fonte not in verticeVizinho and alvo not in verticeVizinho:
                        subM.add_edge(pydot.Edge(fonte, alvo))
                        verticeVizinho.append(fonte)
                        verticeVizinho.append(alvo)
                        print " inserido:(" + str(fonte) + ", " + str(
                            alvo) + ") em M"
                    else:
                        print "aresta invalido, M deve conter arestas com vertice em comum"
                else:
                    print "nao existe tal aresta"
            print ""

        subMx = networkx.from_pydot(subM)
        for aresta in grafox.edges():
            #if aresta not in subMx.edges():
            novaAresta = pydot.Edge(aresta[0], aresta[1])
            novoGrafo.add_edge(novaAresta)
        self.grafo = novoGrafo
        print self.grafo.to_string()
        return
示例#2
0
	def escolherEmparelhamento(self):
		grafox = networkx.from_pydot(self.grafo)
		temM=False
		
		novoGrafo = pydot.Dot(graph_type='graph')
		for vertice in self.grafo.get_node_list():
			novoGrafo.add_node(vertice)
		for subg in self.grafo.get_subgraph_list():
			if subg.get_name()!='M':
				novoGrafo.add_subgraph(subg)
				subg.set_rank('same')
		subM = pydot.Subgraph('')
		subM.set_name('M')
		novoGrafo.add_subgraph(subM)
		
		
					
		verticeVizinho = []
		fim=False
		while not fim:
			print "digite o nome do vertice fonte, nada para listar arestas, ou fim para terminar"
			fonte = raw_input(">> ")
			if fonte=='':
				for aresta in self.grafo.get_edge_list():
					print " aresta:("+str(aresta.get_source())+", "+str(aresta.get_destination())+")"
				for aresta in subM.get_edge_list():
					print " M:("+str(aresta.get_source())+", "+str(aresta.get_destination())+")"
			elif fonte == 'fim':
				fim = True
			else:
				print "digite o no alvo"
				alvo = raw_input(">> ")
				if (fonte,alvo) in grafox.edges():
					if fonte not in verticeVizinho and alvo not in verticeVizinho:
						subM.add_edge(pydot.Edge(fonte, alvo))
						verticeVizinho.append(fonte)
						verticeVizinho.append(alvo)
						print " inserido:("+str(fonte)+", "+str(alvo)+") em M"
					else:
						print "aresta invalido, M deve conter arestas com vertice em comum"
				else:
					print "nao existe tal aresta"
			print ""
			
		subMx = networkx.from_pydot(subM)
		for aresta in grafox.edges():
			#if aresta not in subMx.edges():
				novaAresta = pydot.Edge(aresta[0], aresta[1])
				novoGrafo.add_edge(novaAresta)
		self.grafo = novoGrafo
		print self.grafo.to_string()
		return
示例#3
0
    def pydot_checks(self, G):
        G.add_edge('A','B')
        G.add_edge('A','C')
        G.add_edge('B','C')
        G.add_edge('A','D')
        G.add_node('E')
        P = nx.to_pydot(G)
        G2 = G.__class__(nx.from_pydot(P))
        assert_graphs_equal(G, G2)

        fname = tempfile.mktemp()
        assert_true( P.write_raw(fname) )

        Pin = pydotplus.graph_from_dot_file(fname)

        n1 = sorted([p.get_name() for p in P.get_node_list()])
        n2 = sorted([p.get_name() for p in Pin.get_node_list()])
        assert_true( n1 == n2 )

        e1=[(e.get_source(),e.get_destination()) for e in P.get_edge_list()]
        e2=[(e.get_source(),e.get_destination()) for e in Pin.get_edge_list()]
        assert_true( sorted(e1)==sorted(e2) )

        Hin = nx.drawing.nx_pydot.read_dot(fname)
        Hin = G.__class__(Hin)
        assert_graphs_equal(G, Hin)
    def draw_lineage(self, recs, nodecolor="mediumseagreen",
                     edgecolor="lightslateblue", dpi=96,
                     lineage_img="GO_lineage.png", engine="pygraphviz",
                     gml=False, draw_parents=True, draw_children=True):
        assert engine in GraphEngines
        if engine == "pygraphviz":
            G = self.make_graph_pygraphviz(recs, nodecolor, edgecolor, dpi,
                              draw_parents=draw_parents, draw_children=draw_children)
        else:
            G = self.make_graph_pydot(recs, nodecolor, edgecolor, dpi,
                              draw_parents=draw_parents, draw_children=draw_children)

        if gml:
            import networkx as nx  # use networkx to do the conversion
            pf = lineage_img.rsplit(".", 1)[0]
            NG = nx.from_agraph(G) if engine == "pygraphviz" else nx.from_pydot(G)

            del NG.graph['node']
            del NG.graph['edge']
            gmlfile = pf + ".gml"
            nx.write_gml(NG, gmlfile)
            print("GML graph written to {0}".format(gmlfile), file=sys.stderr)

        print(("lineage info for terms %s written to %s" %
                             ([rec.id for rec in recs], lineage_img)), file=sys.stderr)

        if engine == "pygraphviz":
            G.draw(lineage_img, prog="dot")
        else:
            G.write_png(lineage_img)
示例#5
0
    def draw_lineage(self, recs, nodecolor="mediumseagreen",
                     edgecolor="lightslateblue", dpi=96,
                     lineage_img="GO_lineage.png", engine="pygraphviz",
                     gml=False, draw_parents=True, draw_children=True):
        """Draw GO DAG subplot."""
        assert engine in GraphEngines
        grph = None
        if engine == "pygraphviz":
            grph = self.make_graph_pygraphviz(recs, nodecolor, edgecolor, dpi,
                                              draw_parents=draw_parents,
                                              draw_children=draw_children)
        else:
            grph = self.make_graph_pydot(recs, nodecolor, edgecolor, dpi,
                                         draw_parents=draw_parents, draw_children=draw_children)

        if gml:
            import networkx as nx  # use networkx to do the conversion
            gmlbase = lineage_img.rsplit(".", 1)[0]
            NG = nx.from_agraph(grph) if engine == "pygraphviz" else nx.from_pydot(grph)

            del NG.graph['node']
            del NG.graph['edge']
            gmlfile = gmlbase + ".gml"
            nx.write_gml(Nself._label_wrapG, gmlfile)
            sys.stderr.write("GML graph written to {0}\n".format(gmlfile))

        sys.stderr.write(("lineage info for terms %s written to %s\n" %
                          ([rec.id for rec in recs], lineage_img)))

        if engine == "pygraphviz":
            grph.draw(lineage_img, prog="dot")
        else:
            grph.write_png(lineage_img)
示例#6
0
    def draw_lineage(self, recs, nodecolor="mediumseagreen",
                     edgecolor="lightslateblue", dpi=96,
                     lineage_img="GO_lineage.png", engine="pygraphviz",
                     gml=False, draw_parents=True, draw_children=True):
        assert engine in GraphEngines
        if engine == "pygraphviz":
            G = self.make_graph_pygraphviz(recs, nodecolor, edgecolor, dpi,
                              draw_parents=draw_parents, draw_children=draw_children)
        else:
            G = self.make_graph_pydot(recs, nodecolor, edgecolor, dpi,
                              draw_parents=draw_parents, draw_children=draw_children)

        if gml:
            import networkx as nx  # use networkx to do the conversion
            pf = lineage_img.rsplit(".", 1)[0]
            NG = nx.from_agraph(G) if engine == "pygraphviz" else nx.from_pydot(G)

            del NG.graph['node']
            del NG.graph['edge']
            gmlfile = pf + ".gml"
            nx.write_gml(NG, gmlfile)
            print("GML graph written to {0}".format(gmlfile), file=sys.stderr)

        print(("lineage info for terms %s written to %s" %
                             ([rec.id for rec in recs], lineage_img)), file=sys.stderr)

        if engine == "pygraphviz":
            G.draw(lineage_img, prog="dot")
        else:
            G.write_png(lineage_img)
示例#7
0
    def pydot_checks(self, G):
        G.add_edge('A', 'B')
        G.add_edge('A', 'C')
        G.add_edge('B', 'C')
        G.add_edge('A', 'D')
        G.add_node('E')
        P = nx.to_pydot(G)
        G2 = G.__class__(nx.from_pydot(P))
        assert_graphs_equal(G, G2)

        fname = tempfile.mktemp()
        assert_true(P.write_raw(fname))

        Pin = pydotplus.graph_from_dot_file(fname)

        n1 = sorted([p.get_name() for p in P.get_node_list()])
        n2 = sorted([p.get_name() for p in Pin.get_node_list()])
        assert_true(n1 == n2)

        e1 = [(e.get_source(), e.get_destination()) for e in P.get_edge_list()]
        e2 = [(e.get_source(), e.get_destination())
              for e in Pin.get_edge_list()]
        assert_true(sorted(e1) == sorted(e2))

        Hin = nx.drawing.nx_pydot.read_dot(fname)
        Hin = G.__class__(Hin)
        assert_graphs_equal(G, Hin)
示例#8
0
    def draw_lineage(self, recs, nodecolor="mediumseagreen",
                     edgecolor="lightslateblue", dpi=96,
                     lineage_img="GO_lineage.png", engine="pygraphviz",
                     gml=False, draw_parents=True, draw_children=True):
        """Draw GO DAG subplot."""
        assert engine in GraphEngines
        grph = None
        if engine == "pygraphviz":
            grph = self.make_graph_pygraphviz(recs, nodecolor, edgecolor, dpi,
                                              draw_parents=draw_parents,
                                              draw_children=draw_children)
        else:
            grph = self.make_graph_pydot(recs, nodecolor, edgecolor, dpi,
                                         draw_parents=draw_parents, draw_children=draw_children)

        if gml:
            import networkx as nx  # use networkx to do the conversion
            gmlbase = lineage_img.rsplit(".", 1)[0]
            obj = nx.from_agraph(grph) if engine == "pygraphviz" else nx.from_pydot(grph)

            del obj.graph['node']
            del obj.graph['edge']
            gmlfile = gmlbase + ".gml"
            nx.write_gml(self.label_wrap, gmlfile)
            sys.stderr.write("GML graph written to {0}\n".format(gmlfile))

        sys.stderr.write(("lineage info for terms %s written to %s\n" %
                          ([rec.item_id for rec in recs], lineage_img)))

        if engine == "pygraphviz":
            grph.draw(lineage_img, prog="dot")
        else:
            grph.write_png(lineage_img)
示例#9
0
def pydotStringToDiGraph(pydotString):

    pydotString = pydotString.encode(encoding='UTF-8')

    P = pydot.graph_from_dot_data(pydotString)

    D = nx.DiGraph(nx.from_pydot(P))

    return D
示例#10
0
	def imprimeEstado(self, sgX, sgY, sgMx, arvore ):
		sgXx = networkx.from_pydot(sgX)
		print "X: "
		print sgXx.nodes()
		
		sgYx = networkx.from_pydot(sgY)
		print "Y: "
		print sgYx.nodes()
		
		print "M: "
		print sgMx.nodes()
		print sgMx.edges()
		
		print "Arvore: "
		print arvore.nodes()
		print arvore.edges()
		
		return
示例#11
0
    def imprimeEstado(self, sgX, sgY, sgMx, arvore):
        sgXx = networkx.from_pydot(sgX)
        print "X: "
        print sgXx.nodes()

        sgYx = networkx.from_pydot(sgY)
        print "Y: "
        print sgYx.nodes()

        print "M: "
        print sgMx.nodes()
        print sgMx.edges()

        print "Arvore: "
        print arvore.nodes()
        print arvore.edges()

        return
示例#12
0
    def process_class_graph(self, classInvokelist, KE_classlist):
        class_dic = {}
        classlist = KE_classlist
        dgraph_class = pydot.Dot(graph_type='digraph')
        dgraph_class.set_edge_defaults(style='solid', weight=0)

        #build the class level
        for keys_id in classlist:
            dnode = pydot.Node(keys_id)
            dnode.set_style('filled')
            dgraph_class.add_node(dnode)

        class_dic = {}
        for line in classInvokelist:
            if line in class_dic.keys():
                class_dic[line] = class_dic[line] + 1
            else:
                class_dic[line] = 1

        pattern = ' ---> '
        for line in class_dic.keys():
            parts = line.split(pattern)
            keys_id = parts[0]
            values_id = parts[1]
            wei = class_dic[line]
            label = str(wei)
            edge1 = pydot.Edge(keys_id, values_id, weight=wei)
            edge1.set_label(label)
            dgraph_class.add_edge(edge1)

        del class_dic
        del classlist
        #write
        #dgraph_class.write("YY_class.dot")
        #self.fcgnx_class_level = nx.DiGraph(nx.from_pydot(dgraph_class))
        try:
            self.fcgnx_class_level = nx.DiGraph(nx.from_pydot(dgraph_class))
            print("Done with networkX class-graph")
        except ImportError:
            print(
                "you networkx may not be 1.9.*, try another import for networkx 1.11.*"
            )
            self.fcgnx_class_level = nx.nx_pydot.from_pydot(dgraph_class)

        #print ("failed, some import issues on the networkX")
        #sys.exit(1)
        del dgraph_class
示例#13
0
文件: bdd_test.py 项目: maweki/dd
def test_to_pydot():
    def f(x):
        return str(abs(x))

    g = x_and_y()
    g.roots.add(2)
    pd = _bdd.to_pydot(g)
    r = nx.from_pydot(pd)
    for u in g:
        assert f(u) in r, u
    for u, (i, v, w) in g._succ.iteritems():
        if v is None or w is None:
            assert v is None, v
            assert w is None, w
            continue
        assert r.has_edge(f(u), f(v)), (u, v)
        assert r.has_edge(f(u), f(w)), (u, w)
示例#14
0
 def exportarParaMatrizAdj(self, nome):
     print('criando arquivo com matriz de adjacencia: ' + nome + '.txt')
     arquivo = open(str(nome) + '.txt', 'w')
     grafox = networkx.from_pydot(self.grafo)
     grafox = grafox.to_undirected()
     listaNo = grafox.nodes()
     for i in range(0, len(listaNo)):
         vizinhos = grafox.neighbors(listaNo[i])
         linha = ""
         for j in range(0, len(listaNo)):
             if listaNo[j] in vizinhos:
                 linha += "1\t"
                 #print listaNo[i]+"("+str(i)+") -- " + listaNo[j]+"("+str(j)+")"
             else:
                 linha += "0\t"
         linha = linha[0:-1] + "\n"
         arquivo.write(linha)
示例#15
0
	def exportarParaMatrizAdj(self, nome):
		print('criando arquivo com matriz de adjacencia: '+nome+'.txt')
		arquivo = open(str(nome)+'.txt', 'w')
		grafox = networkx.from_pydot(self.grafo)
		grafox = grafox.to_undirected()
		listaNo = grafox.nodes()
		for i in range(0, len(listaNo)):
			vizinhos = grafox.neighbors(listaNo[i])
			linha = ""
			for j in range(0, len(listaNo)):
				if listaNo[j] in vizinhos:
					linha+="1\t"
					#print listaNo[i]+"("+str(i)+") -- " + listaNo[j]+"("+str(j)+")"
				else:
					linha+="0\t"
			linha = linha[0:-1]+"\n"
			arquivo.write(linha)
示例#16
0
    def process_class_graph(self, classInvokelist, KE_classlist):
        class_dic = {}
        classlist = KE_classlist
        dgraph_class = pydot.Dot(graph_type = 'digraph')
        dgraph_class.set_edge_defaults(style= 'solid', weight=0) 
        
        #build the class level 
        for keys_id in classlist:
            dnode = pydot.Node(keys_id)
            dnode.set_style('filled')
            dgraph_class.add_node(dnode)
        
        class_dic = {}
        for line in classInvokelist:
            if line in class_dic.keys():
               class_dic[line] = class_dic[line] + 1
            else :
               class_dic[line] = 1
      
        pattern=' ---> '
        for line in class_dic.keys():
            parts = line.split(pattern)
            keys_id = parts[0]
            values_id = parts[1]
            wei = class_dic[line]
            label = str(wei)  
            edge1 = pydot.Edge(keys_id, values_id, weight = wei)
            edge1.set_label(label)
            dgraph_class.add_edge(edge1)

  
        del class_dic
        del classlist
        #write
        #dgraph_class.write("YY_class.dot")
        #self.fcgnx_class_level = nx.DiGraph(nx.from_pydot(dgraph_class))
        try:
            self.fcgnx_class_level = nx.DiGraph(nx.from_pydot(dgraph_class))
            print ("Done with networkX class-graph")
        except AttributeError,ImportError:
            print ("you networkx may not be 1.9.*, try another import for networkx 1.11.*")
            self.fcgnx_class_level = nx.nx_pydot.from_pydot(dgraph_class)
示例#17
0
文件: layout.py 项目: rkdarst/pcd
def layoutgraph(g):
    """Given a Graph object, """

    #g = G.make_networkx()
    #G.colors_to_networkx(g)
    #networkx.write_gml(g.copy(), dirname+'dolphins_gamma%s.gml'%gamma)

    pd = networkx.to_pydot(g)
    #pd.to_string()

    prog = 'neato'
    #prog = 'fdp'
    p = subprocess.Popen('%s -Goverlap=scalexy -Gsplines=true -Gstart=5'%prog,
                         stdin=subprocess.PIPE,stdout=subprocess.PIPE,
                         shell=True)
    out = p.communicate(pd.to_string())
    #from fitz import interactnow

    gnew = networkx.from_pydot(pydot.graph_from_dot_data(out[0]))
    return gnew
示例#18
0
    def pydot_checks(self, G):
        H, P = self.build_graph(G)
        G2 = H.__class__(nx.from_pydot(P))
        self.assert_equal(H, G2)

        fname = tempfile.mktemp()
        assert_true( P.write_raw(fname) )

        Pin = pydot.graph_from_dot_file(fname)   
        n1 = sorted([p.get_name() for p in P.get_node_list()])
        n2 = sorted([p.get_name() for p in Pin.get_node_list()])
        assert_true( n1 == n2 )

        e1=[(e.get_source(),e.get_destination()) for e in P.get_edge_list()]
        e2=[(e.get_source(),e.get_destination()) for e in Pin.get_edge_list()]
        assert_true( sorted(e1)==sorted(e2) )

        Hin = nx.drawing.nx_pydot.read_dot(fname)
        Hin = H.__class__(Hin)
        self.assert_equal(H, Hin)
        os.unlink(fname)
示例#19
0
    def pydot_checks(self, G):
        H, P = self.build_graph(G)
        G2 = H.__class__(nx.from_pydot(P))
        self.assert_equal(H, G2)

        fname = tempfile.mktemp()
        assert_true(P.write_raw(fname))

        Pin = pydot.graph_from_dot_file(fname)
        n1 = sorted([p.get_name() for p in P.get_node_list()])
        n2 = sorted([p.get_name() for p in Pin.get_node_list()])
        assert_true(n1 == n2)

        e1 = [(e.get_source(), e.get_destination()) for e in P.get_edge_list()]
        e2 = [(e.get_source(), e.get_destination()) for e in Pin.get_edge_list()]
        assert_true(sorted(e1) == sorted(e2))

        Hin = nx.drawing.nx_pydot.read_dot(fname)
        Hin = H.__class__(Hin)
        self.assert_equal(H, Hin)
        os.unlink(fname)
    def _submit(self):
        schedule_file = StringIO(self.input_area.toPlainText())
        try:
            graph = generate_serializability_graph(schedule_file)
        except ParseError as error:
            QtGui.QMessageBox(QtGui.QMessageBox.Warning, 'Parse error',
                              str(error)).exec_()
            return
        finally:
            schedule_file.close()

        is_conflict_serializable = (
            networkx.algorithms.simple_cycles(
                networkx.from_pydot(graph)) == [])
        self.conflict_serializable_label.setText(
            'This schedule is{0} conflict serializable.'.format(
                '' if is_conflict_serializable else ' not'))

        self.output_area.load(QtCore.QByteArray(
            graph.create(prog='dot',  # default
                         format='svg')))
示例#21
0
def layoutgraph(g):
    """Given a Graph object, """

    #g = G.make_networkx()
    #G.colors_to_networkx(g)
    #networkx.write_gml(g.copy(), dirname+'dolphins_gamma%s.gml'%gamma)

    pd = networkx.to_pydot(g)
    #pd.to_string()

    prog = 'neato'
    #prog = 'fdp'
    p = subprocess.Popen('%s -Goverlap=scalexy -Gsplines=true -Gstart=5' %
                         prog,
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         shell=True)
    out = p.communicate(pd.to_string())
    #from fitz import interactnow

    gnew = networkx.from_pydot(pydot.graph_from_dot_data(out[0]))
    return gnew
示例#22
0
def fromDotStr(s):
    return networkx.from_pydot(pydot.graph_from_dot_data(s))
示例#23
0
def inv_Lamberts(v):
    x = float(v[0])
    y = float(v[1])
    n = sqrt(x**2 + y**2)
    x = x / n
    y = y / n
    return np.asarray([
        sqrt(1 - (x**2 + y**2) / 4) * x,
        sqrt(1 - (x**2 + y**2) / 4) * y, (x**2 + y**2) / 2 - 1
    ])


print("Done clustering")

g = pydotplus.graph_from_dot_file("test.dot")
Gc = nx.from_pydot(g)

f = open("clustered.dot", "r")
f.readline()
l = f.readlines()
cluster_values = []
cluster = []
pt = []
type_prev = ''
unproj_vals = []

twodpoints = []

ma = 0
mi = 1000
示例#24
0
#!/usr/bin/python

import sys
import argparse
import pydot
import networkx as nx
import pylab as pl

import matplotlib.pyplot as plt

parser = argparse.ArgumentParser(description="Graph network topology graph from UART output")
parser.add_argument("graph_file", help="file with graph in DOT format")
args = parser.parse_args()

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

G_pd = pydot.graph_from_dot_file(args.graph_file)
G = nx.from_pydot(G_pd)
nx.draw(G)

plt.show()
示例#25
0
for col_node_label in columns:
    col_index = columns.index(col_node_label) + 1
    rows = lines[1:]
    for row in rows:
        values = row.split(',')
        row_node_label = values[0]
        connected = True if values[col_index] == '1' else False
        if (connected):
            edge = pydot.Edge(
                col_node_label,
                row_node_label
            )
            graph.add_edge(edge)

# Calculate nodes' betweenness
nx_graph = nx.from_pydot(graph)
results = nx.edge_betweenness_centrality(nx_graph)

# Sort them by descending order
link_betweenness_pairs = sorted(
    results.items(),
    key=lambda x: x[1],
    reverse=True
)

# Add edge's label and change font's colour according to the specificaiton
final_graph = pydot.Dot(graph_type='graph')
max_val = -1
for (edge, betweenness_val) in link_betweenness_pairs:
    # Pen's width should be 5 times of the betweenness_val
    penwidth = betweenness_val * 5
示例#26
0
def handle_msg(line):
    global prev_graph_str
    global G

    # TODO: remove prefix workaround
    m = re.match(r'(?P<prefix>RF: )?digraph', line)
    if m:
        # TODO: remove prefix workaround
        if m.group('prefix') is not None and len(m.group('prefix')) > 0:
            graph_str = line[len(m.group('prefix')):]
        else:
            graph_str = line
        if not args.dedup or graph_str != prev_graph_str:
            print "parser: new graph: ", graph_str

            try:
                G_pd = pydot.graph_from_dot_data(graph_str)
                G_new = nx.from_pydot(G_pd)
            except Exception as e:
                print "Exception while parsing graph str: " + str(e)
                return

            if G is None:
                G = G_new

            updaters[G_new.name](G, G_new)

            draw_graph(G, ax)
            prev_graph_str = graph_str
        return

    m = re.match(r'fence: (?P<posts>.*)', line)
    if m:

        if not G:
            print "error: fence section, before graph"
            return

        nodes = []
        section_status = []
        if len(m.group('posts')) > 0:
            posts = m.group('posts').split()
        else:
            posts = []

        print "posts=", posts
        for post in posts:
            node, status = post.split(':')
            nodes.append(node)
            section_status.append(int(status))

        print "nodes=", nodes

        STATUS_NONE = 0
        STATUS_ACTIVE = 1
        STATUS_BREACHED = 2

        sections = []
        for i, node in enumerate(nodes):
            if i < len(nodes) - 1:
                sections.append(((nodes[i], nodes[i + 1]),
                                section_status[i]))

        print sections

        for u, v in G.edges():
            G[u][v]['beam'] = False
            G[u][v]['breached'] = False

        for node_pair, status in sections:
            out_node, in_node = node_pair
            
            edge = G.edge[out_node][in_node]
            print "edge=", edge
            print "out,in=", out_node, in_node

            print "status=", status
            if status == STATUS_NONE:
                edge['beam'] = False
            elif status == STATUS_ACTIVE:
                print "active"
                edge['beam'] = True
            elif status == STATUS_BREACHED:
                edge['breached'] = True
            print "edge=", edge

        draw_graph(G, ax)
        return

    print "parser: error: unexpected msg: '" + line + "'"
示例#27
0
	def aplicaHungaro(self): # grafo, X, emparelhamento
		
		self.grafoEmp = self.grafo
		
		# busca subgrafos
		lista = self.grafoEmp.get_subgraph_list()
		for i in lista:
			if i.get_name() == "X":
				sgX = i
			elif i.get_name() == "Y":
				sgY = i
			elif i.get_name() == "M":
				sgM = i
		
		arvore = networkx.Graph()
		pesos = {}
		sgMx = networkx.from_pydot(sgM)
		sgMx = sgMx.to_undirected()
		sgXx = networkx.from_pydot(sgX)
		sgXx = sgXx.to_undirected()
		grafoEmpx = networkx.from_pydot(self.grafoEmp)
		grafoEmpx = grafoEmpx.to_undirected()
		
		S = []
		T = []
		
		# segue os passo do algoritmo
		passo = 1
		
		while passo != 0:
			#
			# PASSO O1
			#
			if passo == 1:
				print "\tPasso 1"
				
				if sgMx.edges().__len__() == 0 :
					print "O conjunto M está vazio"
					e = self.grafoEmp.get_edges()[0]
					sgMx.add_edge( e.get_source(), e.get_destination() )
					print "A aresta " + self.imprimeVertice(e) + " foi adicionada a M"
					
				
				self.imprimeEstado(sgX, sgY, sgMx, arvore )
				raw_input("1")
				
				passo = 2
				
			#
			# PASSO O2
			#
			elif passo == 2:
				print "\tPasso 2"
				
				# existe algum vértice não saturado?
				
				i = 0
				encontrouNaoSaturado = False
				S = []
				T = []
				while not encontrouNaoSaturado and i < sgX.get_nodes().__len__():
					print "loop"
					v = sgX.get_nodes()[i]
					if not sgMx.has_node( v.get_name() ):
						print "Vértice não-saturado encontrado em X: "+ v.get_name()
						encontrouNaoSaturado = True
						S.append(v.get_name())
					i +=1
				
				if not encontrouNaoSaturado:
					print "Todos os vértices de X já estão saturados"
					passo = 0
				else:
					arvore = networkx.Graph()
					arvore.add_node( v.get_name() )
					pesos[v.get_name()] = 0
					
					passo = 3
					
				self.imprimeEstado(sgX, sgY, sgMx, arvore )
				raw_input("2")
				
			#
			# PASSO O3
			#
			elif passo == 3:
				print "\tPasso 3"
				
				# verifica se a vizinhança tem o mesmo tamanho de T
				


				T = arvore.nodes()
				
				sgXx = networkx.from_pydot(sgX)
				i = T.__len__() - 1;
				while i >= 0:
					if sgXx.has_node( T[i] ):
						T.remove(T[i])
					i -= 1
				
				print "T:"
				print T				
				S.sort()
				print "S = " + S.__str__()
				
				NS = []
				
				for n in S:
					lista = grafoEmpx.neighbors(n)
					for n2 in lista:
						if n2 not in NS:
							NS.append(n2)
							
				NS.sort()
				print "NS = " + NS.__str__()
				
				if NS.__len__() == T.__len__():
					print "PROBLEMA: O algoritmo não satisfaz o Teorema do Casamento"
					passo = 0
				else:
					
					# busca um y em NS que não está em T
					candidatos = []
					for n in NS:
						if n not in T:
							candidatos.append(n)
					
					y = candidatos[0];
					print "Escolheu "+ y +" entre NS - T: "+ candidatos.__str__()
					
					passo = 4
				
				self.imprimeEstado(sgX, sgY, sgMx, arvore )
				raw_input("3")
				
			#
			# PASSO O4
			#
			elif passo == 4:
				print "\tPasso 4"
				
				# verifica se y é M-saturado
				
				if sgMx.has_node( y ):
					print y + " é M-saturado"
					
					# adiciona novas arestas a arvore
					
					# busca um no na arvore que seja vizinho a y
					lista = arvore.nodes()
					i = 0
					encontrou = False
					while not encontrou and i < lista.__len__():
						if grafoEmpx.has_edge(y, lista[i]):
							arvore.add_edge( y, lista[i] )
							pesos[y] = pesos[lista[i]] + 1
						i +=1
					
					z = sgMx.neighbors( y )[0]
						
					arvore.add_edge( y, z )
					pesos[z] = pesos[y] + 1
					
					T.append(y)
					S.append(z)
					
					passo = 3
					
				else:
					print y + " é M-não-saturado"
					
					atual = y
					print "Atual = "+atual
					vizin = grafoEmpx.neighbors( atual )
					print "Vizinhos de y"
					print vizin
					
					encontrado = False
					i = 0
					while not encontrado and i < vizin.__len__():
						if vizin[i] in arvore.nodes():
							encontrado = True
							prox = vizin[i]
						i += 1
						
					print "Proximo = " + prox
					
					
					if sgMx.has_edge( y, prox ):
						print "Removendo de M: ("+ y +", "+prox+")"
						sgMx.remove_edge( y, prox)
					else:
						print "Adicionando a M: ("+ y +", "+prox+")"
						sgMx.add_edge( y, prox)
					
					anterior = y
					atual = prox
					print "Atual = "+atual
					print "Prox = "+prox
					print "Anterior = "+anterior
					
					while atual != v.get_name():
						vizin = arvore.neighbors( atual )
						print vizin
						for n in vizin:
							if pesos[n] < pesos[atual]:
								prox = n
						
						if sgMx.has_edge( atual, prox ):
							print "Removendo de M: ("+ atual +", "+prox+")"
							sgMx.remove_edge( atual, prox)
						else:
							print "Adicionando a M: ("+ atual +", "+prox+")"
							sgMx.add_edge( atual, prox)
						
						anterior = atual
						atual = prox
						print "Atual = "+atual
						print "Prox = "+prox
						print "Anterior = "+anterior
					
					passo = 2
					
				print "Emparelhamento:"
				print sgMx.nodes()
				print sgMx.edges()
				
				print "Arvore:"
				print arvore.nodes()
				print arvore.edges()
				
				self.imprimeEstado(sgX, sgY, sgMx, arvore )
				raw_input("4")
				
		
		# formata arestas de sgXx em grafoEmp
		
		lista = self.grafoEmp.get_edges()
		for e in lista:
			if sgMx.has_edge( e.get_source(), e.get_destination() ):
				e.set_style("dotted")
		
		return
def analyze(play,num_overlap,act_num):

    dom = parse(play)

    speaker_count = Counter()

    for node in dom.getElementsByTagName('SPEECH'):
        num_lines = len(node.getElementsByTagName('LINE'))
        for speakers in node.getElementsByTagName('SPEAKER'):
            if speakers.firstChild:
                speaker_count.update({speakers.firstChild.nodeValue.upper(): num_lines})

    actors_scene = {}

    acts = [act for act in dom.getElementsByTagName('ACT')]
    act = acts[act_num]

    act_name = act.getElementsByTagName('TITLE')[0].firstChild.nodeValue
    for scene in act.getElementsByTagName('SCENE'):
        scene_name = scene.getElementsByTagName('TITLE')[0].firstChild.nodeValue
        scene_id = act_name + ' ' + scene_name.split('.')[0]

        speaker_list = []
        for speaker in scene.getElementsByTagName('SPEAKER'):
            if speaker.firstChild:
                speaker_list.append(str(speaker.firstChild.nodeValue).upper())
                actors_scene[str(scene_id)] = set(speaker_list)

    graph = pydot.Dot(graph_type='graph',overlap=False)

    N = 100
    for speaker in speaker_count:
        width = log(2*float(speaker_count[speaker]))/float(1)
        #print width
        if speaker in [s for s, l in speaker_count.most_common(N)]:
            fontsize = 1.2*(width*72/(len(speaker)))
            node = pydot.Node(
                speaker,
                fixedsize=True,
                fontsize=fontsize,
                shape='circle',
                width=width,
                penwidth=10
            )
        else:
            node = pydot.Node(
                speaker,
                fixedsize=True,
                shape='point',
                width=width,
                penwidth=3
            )

        graph.add_node(node)

    edge_list = {}
    for scene in actors_scene:
        chars = sorted(actors_scene[scene]) #needs to be sorted, I assume in one order
        num_char = len(chars)
        for i in range(num_char):
            for j in range(i+1,num_char):
                if not edge_list.has_key(chars[i] + ' ' + chars[j]):
                    edge_list[chars[i] + ' ' + chars[j]] = pydot.Edge(
                        chars[i],
                        chars[j],
                        weight=1,
                        penwidth=3
                        )
                else:
                    edge_list[chars[i] + ' ' + chars[j]].set_weight(
                        edge_list[chars[i] + ' ' + chars[j]].get_weight()+1
                        )
                    edge_list[chars[i] + ' ' + chars[j]].set_penwidth(
                        edge_list[chars[i] + ' ' + chars[j]].get_penwidth()+5
                        )

    for edge in edge_list:
        if edge_list[edge].get_weight()>=num_overlap:
            graph.add_edge(edge_list[edge])

    keep_nodes = []
    for edge in graph.get_edge_list():
        keep_nodes.append(edge.get_source())
        keep_nodes.append(edge.get_destination())

    for node in graph.get_node_list():
        if not str(node.get_name()) in keep_nodes:
            graph.del_node(node)
            
    ngraph = nx.from_pydot(graph)
    return nx.density(nx.Graph(ngraph))
示例#29
0
文件: layout.py 项目: rkdarst/pcd
def fromDotStr(s):
    return networkx.from_pydot(pydot.graph_from_dot_data(s))
    tx = np.random.uniform(low=0, high=2 * np.pi)
    ty = np.random.uniform(low=0, high=2 * np.pi)
    tz = np.random.uniform(low=0, high=2 * np.pi)
    for x in range(len(l)):
        l[x] = rotate_z(rotate_y(rotate_x(l[x], tx), ty), tz)
    return l


if (len(sys.argv) < 3):
    print("Usage: pipeline.sh filename similarity")
    sys.exit(0)

g = pydotplus.graph_from_dot_file(sys.argv[1])
sim = sys.argv[2]
graph = ""
nx_graph = nx.from_pydot(g)
Gc = max(nx.connected_component_subgraphs(nx_graph), key=len)

g_mat = np.ones(shape=(len(Gc.nodes()), len(Gc.nodes())))
if (not sim):
    print("Dissimilarity Matrix")
    g_mat = 1000 * g_mat
n_list = list(Gc.nodes())
for e in Gc.edges():
    try:
        #Graph is weighted
        val = float(Gc.get_edge_data(e[0], e[1])[0]['weight'])
        g_mat[n_list.index(e[0])][n_list.index(e[1])] = val
        g_mat[n_list.index(e[1])][n_list.index(e[0])] = val
    except:
        #Graph is unweighted
示例#31
0
    def aplicaHungaro(self):  # grafo, X, emparelhamento

        self.grafoEmp = self.grafo

        # busca subgrafos
        lista = self.grafoEmp.get_subgraph_list()
        for i in lista:
            if i.get_name() == "X":
                sgX = i
            elif i.get_name() == "Y":
                sgY = i
            elif i.get_name() == "M":
                sgM = i

        arvore = networkx.Graph()
        pesos = {}
        sgMx = networkx.from_pydot(sgM)
        sgMx = sgMx.to_undirected()
        sgXx = networkx.from_pydot(sgX)
        sgXx = sgXx.to_undirected()
        grafoEmpx = networkx.from_pydot(self.grafoEmp)
        grafoEmpx = grafoEmpx.to_undirected()

        S = []
        T = []

        # segue os passo do algoritmo
        passo = 1

        while passo != 0:
            #
            # PASSO O1
            #
            if passo == 1:
                print "\tPasso 1"

                if sgMx.edges().__len__() == 0:
                    print "O conjunto M está vazio"
                    e = self.grafoEmp.get_edges()[0]
                    sgMx.add_edge(e.get_source(), e.get_destination())
                    print "A aresta " + self.imprimeVertice(
                        e) + " foi adicionada a M"

                self.imprimeEstado(sgX, sgY, sgMx, arvore)
                raw_input("1")

                passo = 2

            #
            # PASSO O2
            #
            elif passo == 2:
                print "\tPasso 2"

                # existe algum vértice não saturado?

                i = 0
                encontrouNaoSaturado = False
                S = []
                T = []
                while not encontrouNaoSaturado and i < sgX.get_nodes().__len__(
                ):
                    print "loop"
                    v = sgX.get_nodes()[i]
                    if not sgMx.has_node(v.get_name()):
                        print "Vértice não-saturado encontrado em X: " + v.get_name(
                        )
                        encontrouNaoSaturado = True
                        S.append(v.get_name())
                    i += 1

                if not encontrouNaoSaturado:
                    print "Todos os vértices de X já estão saturados"
                    passo = 0
                else:
                    arvore = networkx.Graph()
                    arvore.add_node(v.get_name())
                    pesos[v.get_name()] = 0

                    passo = 3

                self.imprimeEstado(sgX, sgY, sgMx, arvore)
                raw_input("2")

            #
            # PASSO O3
            #
            elif passo == 3:
                print "\tPasso 3"

                # verifica se a vizinhança tem o mesmo tamanho de T

                T = arvore.nodes()

                sgXx = networkx.from_pydot(sgX)
                i = T.__len__() - 1
                while i >= 0:
                    if sgXx.has_node(T[i]):
                        T.remove(T[i])
                    i -= 1

                print "T:"
                print T
                S.sort()
                print "S = " + S.__str__()

                NS = []

                for n in S:
                    lista = grafoEmpx.neighbors(n)
                    for n2 in lista:
                        if n2 not in NS:
                            NS.append(n2)

                NS.sort()
                print "NS = " + NS.__str__()

                if NS.__len__() == T.__len__():
                    print "PROBLEMA: O algoritmo não satisfaz o Teorema do Casamento"
                    passo = 0
                else:

                    # busca um y em NS que não está em T
                    candidatos = []
                    for n in NS:
                        if n not in T:
                            candidatos.append(n)

                    y = candidatos[0]
                    print "Escolheu " + y + " entre NS - T: " + candidatos.__str__(
                    )

                    passo = 4

                self.imprimeEstado(sgX, sgY, sgMx, arvore)
                raw_input("3")

            #
            # PASSO O4
            #
            elif passo == 4:
                print "\tPasso 4"

                # verifica se y é M-saturado

                if sgMx.has_node(y):
                    print y + " é M-saturado"

                    # adiciona novas arestas a arvore

                    # busca um no na arvore que seja vizinho a y
                    lista = arvore.nodes()
                    i = 0
                    encontrou = False
                    while not encontrou and i < lista.__len__():
                        if grafoEmpx.has_edge(y, lista[i]):
                            arvore.add_edge(y, lista[i])
                            pesos[y] = pesos[lista[i]] + 1
                        i += 1

                    z = sgMx.neighbors(y)[0]

                    arvore.add_edge(y, z)
                    pesos[z] = pesos[y] + 1

                    T.append(y)
                    S.append(z)

                    passo = 3

                else:
                    print y + " é M-não-saturado"

                    atual = y
                    print "Atual = " + atual
                    vizin = grafoEmpx.neighbors(atual)
                    print "Vizinhos de y"
                    print vizin

                    encontrado = False
                    i = 0
                    while not encontrado and i < vizin.__len__():
                        if vizin[i] in arvore.nodes():
                            encontrado = True
                            prox = vizin[i]
                        i += 1

                    print "Proximo = " + prox

                    if sgMx.has_edge(y, prox):
                        print "Removendo de M: (" + y + ", " + prox + ")"
                        sgMx.remove_edge(y, prox)
                    else:
                        print "Adicionando a M: (" + y + ", " + prox + ")"
                        sgMx.add_edge(y, prox)

                    anterior = y
                    atual = prox
                    print "Atual = " + atual
                    print "Prox = " + prox
                    print "Anterior = " + anterior

                    while atual != v.get_name():
                        vizin = arvore.neighbors(atual)
                        print vizin
                        for n in vizin:
                            if pesos[n] < pesos[atual]:
                                prox = n

                        if sgMx.has_edge(atual, prox):
                            print "Removendo de M: (" + atual + ", " + prox + ")"
                            sgMx.remove_edge(atual, prox)
                        else:
                            print "Adicionando a M: (" + atual + ", " + prox + ")"
                            sgMx.add_edge(atual, prox)

                        anterior = atual
                        atual = prox
                        print "Atual = " + atual
                        print "Prox = " + prox
                        print "Anterior = " + anterior

                    passo = 2

                print "Emparelhamento:"
                print sgMx.nodes()
                print sgMx.edges()

                print "Arvore:"
                print arvore.nodes()
                print arvore.edges()

                self.imprimeEstado(sgX, sgY, sgMx, arvore)
                raw_input("4")

        # formata arestas de sgXx em grafoEmp

        lista = self.grafoEmp.get_edges()
        for e in lista:
            if sgMx.has_edge(e.get_source(), e.get_destination()):
                e.set_style("dotted")

        return