def test_scale_and_center_arg(self):
        G = nx.complete_graph(9)
        G.add_node(9)
        vpos = nx.random_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2, center=(4,5))
        vpos = nx.spring_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2, center=(4,5))
        vpos = nx.spectral_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2, center=(4,5))
        # circular can have twice as big length
        vpos = nx.circular_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2*2, center=(4,5))
        vpos = nx.shell_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2*2, center=(4,5))

        # check default center and scale
        vpos = nx.random_layout(G)
        self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5))
        vpos = nx.spring_layout(G)
        self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5))
        vpos = nx.spectral_layout(G)
        self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5))
        vpos = nx.circular_layout(G)
        self.check_scale_and_center(vpos, scale=2, center=(0,0))
        vpos = nx.shell_layout(G)
        self.check_scale_and_center(vpos, scale=2, center=(0,0))
def find_football_communities():
    """ Finds the communities produced for the football network, uses compare
    methods to graph
    """
    fgraph = CD.football_graph()
    known = CD.football_known_c()
    temp7 = known[7]
    temp8 = known[8]
    temp9 = known[9]
    known[7] = temp8
    known[8] = temp9
    known[9] = temp7

    center_g = nx.Graph()
    center_g.add_nodes_from(range(12))
    centers = nx.circular_layout(center_g, scale = 10)
            
    pos = {}
    subgraphs = [nx.subgraph(fgraph, c) for c in known]
    count = -1
    for g in subgraphs:
        count += 1
        (off_x, off_y) = centers[count]
        pos_local = nx.circular_layout(g, scale=2.)
        for n, place in pos_local.iteritems():
            pos[n] = place + np.array([off_x, off_y])
    
    compare_methods(fgraph,
                    'football_',
                    param=[1., 1., 5./115., 4, 0, .7, 20],
                    known=known,
                    pos=pos,
                    color_map={76:1, 11:2, 7:3, 102:4, 104:5, 47:6, 98:7,
                               96:8, 23:9, 94:10, 27:0},
                    data_path="FootballGames/football_metis")
    def plot_graphs(self):
        # draw lables
        # choose same layout as in drawing the rest of the graph
        pos_G=nx.circular_layout(self.g1)   # positions for all nodes for G (in this case circular)
        pos_H=nx.circular_layout(self.g2)   # positions for all nodes for H (in this case circular)
        labels_G = {}                 # create a dict with labels
        for item in self.g1.nodes():
            labels_G[item] = item

        labels_H = {}                 # create a dict with labels
        for item in self.g2.nodes():
            labels_H[item] = item

        # color-mapping via numpy
        # list of cmaps can be found here: http://matplotlib.org/examples/color/colormaps_reference.html
        # I chose this cmap because there are no dark colors in it so the labels stay readable regardless
        # the color of the label.
        plt.subplots_adjust(left=0,right=1,bottom=0,top=0.95,wspace=0.01,hspace=0.01)
        plt.subplot(121)
        plt.title("Graph G")
        nx.draw_circular(self.g1, cmap=plt.get_cmap('Set1'), node_color=self.nc1)
        nx.draw_networkx_labels(self.g1, pos_G, labels_G)

        plt.subplot(122)
        plt.title("Graph H")
        nx.draw_circular(self.g2, cmap=plt.get_cmap('Set1'), node_color=self.nc2)
        nx.draw_networkx_labels(self.g2, pos_H, labels_H)

        plt.show()
Exemple #4
0
    def displayRGA(self, pairingoption=1, nodepositions=None):
        """This method will display the RGA pairings.

        It has 2 options of pairings:
            1) pairingoption = 1 (the default) This displays the standard RGA
            pairings where the decision to pair is positive if the relative gain
            array has an element value of more than or equal to 0.5.
            2) pairingoption = 2 This displays the RGA pairs where each input is
            forced to have a paired output. This is selected by using the maximum
            value in each column as a pair.

        It has an optional parameter to set node positions. If left out
        the default node positions will be circular. """

        if pairingoption == 1:
            pairingpattern = self.bristol.pairedvariablesHalf
            message = "Standard RGA Pairings"
            self.G1 = nx.DiGraph()
            self.G1 = self.G.copy()
            print(pairingpattern)
            self.G1.add_edges_from(self.G1.edges(), edgecolour='k')
            self.G1.add_edges_from(pairingpattern, edgecolour='r')
            #correct up to here
            pairingtuplelist = [(row[0], row[1]) for row in pairingpattern] #what a mission to find this error
            edgecolorlist = ["r" if edge in pairingtuplelist else "k" for edge in self.G1.edges()]


            if nodepositions == None:
                nodepositions = nx.circular_layout(self.G1)

            plt.figure(message)
            nx.draw_networkx(self.G1, pos=nodepositions)
            nx.draw_networkx_edges(self.G1, pos=nodepositions, width=2.5, edge_color=edgecolorlist, style='solid', alpha=0.5)
            nx.draw_networkx_nodes(self.G1, pos=nodepositions, node_color='y', node_size=450)
            plt.axis('off')
        else:
            pairingpattern = self.bristol.pairedvariablesMax
            message = "Maximum RGA Pairings"
            self.G2 = nx.DiGraph()
            self.G2 = self.G.copy()
            print(pairingpattern)
            self.G2.add_edges_from(self.G2.edges(), edgecolour='k')
            self.G2.add_edges_from(pairingpattern, edgecolour='r')
        #correct up to here
            pairingtuplelist = [(row[0], row[1]) for row in pairingpattern] #what a mission to find this error
            edgecolorlist = ["r" if edge in pairingtuplelist else "k" for edge in self.G2.edges()]


            if nodepositions == None:
                nodepositions = nx.circular_layout(self.G2)

            plt.figure(message)
            nx.draw_networkx(self.G2, pos=nodepositions)
            nx.draw_networkx_edges(self.G2, pos=nodepositions, width=2.5, edge_color=edgecolorlist, style='solid', alpha=0.5)
            nx.draw_networkx_nodes(self.G2, pos=nodepositions, node_color='y', node_size=450)
            plt.axis('off')
Exemple #5
0
 def test_fixed_node_fruchterman_reingold(self):
     # Dense version (numpy based)
     pos = nx.circular_layout(self.Gi)
     npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos, fixed=[(0, 0)])
     assert_equal(tuple(pos[(0, 0)]), tuple(npos[(0, 0)]))
     # Sparse version (scipy based)
     pos = nx.circular_layout(self.bigG)
     npos = nx.fruchterman_reingold_layout(self.bigG, pos=pos, fixed=[(0, 0)])
     for axis in range(2):
         assert_almost_equal(pos[(0,0)][axis], npos[(0,0)][axis])
 def test_empty_graph(self):
     G=nx.Graph()
     vpos = nx.random_layout(G)
     vpos = nx.circular_layout(G)
     vpos = nx.spring_layout(G)
     vpos = nx.fruchterman_reingold_layout(G)
     vpos = nx.shell_layout(G)
     vpos = nx.spectral_layout(G)
     # center arg
     vpos = nx.random_layout(G, scale=2, center=(4,5))
     vpos = nx.circular_layout(G, scale=2, center=(4,5))
     vpos = nx.spring_layout(G, scale=2, center=(4,5))
     vpos = nx.shell_layout(G, scale=2, center=(4,5))
     vpos = nx.spectral_layout(G, scale=2, center=(4,5))
 def test_single_node(self):
     G = nx.Graph()
     G.add_node(0)
     vpos = nx.random_layout(G)
     vpos = nx.circular_layout(G)
     vpos = nx.spring_layout(G)
     vpos = nx.fruchterman_reingold_layout(G)
     vpos = nx.shell_layout(G)
     vpos = nx.spectral_layout(G)
     # center arg
     vpos = nx.random_layout(G, scale=2, center=(4,5))
     vpos = nx.circular_layout(G, scale=2, center=(4,5))
     vpos = nx.spring_layout(G, scale=2, center=(4,5))
     vpos = nx.shell_layout(G, scale=2, center=(4,5))
     vpos = nx.spectral_layout(G, scale=2, center=(4,5))
Exemple #8
0
def final_graphs(Graphs,psi):
    if Graphs == []:
        print "There are no models for the input formula: ", (syntax.formula_to_string(psi))
        print "So the the negation of it : ", "~(",(syntax.formula_to_string(psi)), ") is valid."

    else:
        for i in range(0,len(Graphs)):
            graph = Graphs[i]

            custom_labels={}
            node_colours=['y']
            for node in graph.nodes():
                custom_labels[node] = graph.node[node]
                node_colours.append('c')

            nx.draw(Graphs[i], nx.circular_layout(Graphs[i]),  node_size=1500, with_labels=True, labels = custom_labels, node_color=node_colours)
            #show with custom labels
            fig_name = "graph" + str(i) + ".png"

            plt.savefig(fig_name)
            plt.show()

        print "Satisfiable models have been displayed."
        if len(Graphs) == 1:
            print "You have ",len(Graphs), " valid model."
        else:
            print "You have ",len(Graphs), " valid models."
        print "Your provided formula is: ", (syntax.formula_to_string(psi))
        print "Pictures of the graphs have been saves as: graph0.png, graph1.png etc."
def main(args):
	pi = scipy.io.loadmat(args[1])
	dims = scipy.io.loadmat(args[2])

	total = 1
	for i in range(len(dims["dims"][0])):
		total = total * dims["dims"][0][i]

	# Debug
	print dims["dims"]
	print total
	print pi["pi"]

	# chain = nx.Graph() 
	chain = pgv.AGraph(directed=True)
	for i in range(total):
		for j in range(total):
			wt = pi["pi"][i][j]
			if (wt > 0):
				chain.add_edge(i + 1, j + 1, weight=wt)
				edge = chain.get_edge(i + 1, j + 1)
				edge.attr['label'] = wt

	pos = nx.circular_layout(chain)
	# pos = nx.shell_layout(chain)
	# nx.draw_networkx_edge_labels(chain, pos, edge_labels = edgeLabels, label_pos = 0.3)
	# nx.draw_networkx_labels(chain, pos, nodeLabels, font_size = 12)
	# nx.draw(chain)

	chain.layout(prog='dot')
	chain.draw('chain.png')
Exemple #10
0
def draw_graph(G,savefile=None):
  pos = nx.circular_layout(G)
  colors = range(G.number_of_edges())
  nx.draw(G,pos,color='#336699',edge_color=colors,width=4,
          edge_cmap=plt.cm.Blues,with_labels=True)
  savefile!=None and plt.savefig(savefile)
  plt.show()
Exemple #11
0
def display(g, title):
    """Displays a graph with the given title."""
    pos = nx.circular_layout(g)
    plt.figure()
    plt.title(title)
    nx.draw(g, pos)
    nx.draw_networkx_edge_labels(g, pos, font_size=20)
def circular_iter(G, start_pos=None):
    if start_pos == None: start_pos = nx.circular_layout(G)

    best_pos = start_pos.copy()

    best_crossings = len(nx_detect_crosses(G,best_pos))
    if best_crossings == 0:
        return best_pos

    for x in range(1,len(G.nodes())):
        print "\nIteration number:",x

        new_pos = all_pair_swaps(G, best_pos)
        new_crossings = len(nx_detect_crosses(G,new_pos))

        if new_crossings < best_crossings:
            best_pos = new_pos.copy()
            best_crossings = new_crossings
            if best_crossings == 0:
                print "Success!  Zero crossings."
                break

        else:
            print "Dead end!  Progress stuck at {} crossings.".format(best_crossings)
            break

    return best_pos
Exemple #13
0
 def show_graph(self):
     graph = nx.Graph(self.graph)
     pos = nx.circular_layout(graph)
     # pos=nx.spectral_layout(graph)
     nx.draw_networkx_nodes(graph, pos, node_color="r", node_size=500, alpha=0.8)
     nx.draw_networkx_edges(graph, pos, width=1, alpha=0.5)
     nx.draw_networkx_edges(
         graph, pos, edge_labels={}, edgelist=self.get_edgelist(), width=8, alpha=0.5, edge_color="r"
     )
     nx.draw_networkx_edge_labels(graph, pos, self.get_list_weights_edge(), label_pos=0.3)
     labels = self.set_labels()
     nx.draw_networkx_labels(graph, pos, labels, font_size=16)
     plt.title("Dijkstra")
     plt.text(
         0.5,
         0.97,
         "Start: " + str(self.start) + " End: " + str(self.end),
         horizontalalignment="center",
         transform=plt.gca().transAxes,
     )
     plt.text(
         0.5,
         0.94,
         "Shortest Path: " + str(self.shortest_path),
         horizontalalignment="center",
         transform=plt.gca().transAxes,
     )
     plt.text(
         0.5, 0.90, "Weights: " + str(self.weights), horizontalalignment="center", transform=plt.gca().transAxes
     )
     plt.text(0.5, 0.86, "Pred: " + str(self.Preds), horizontalalignment="center", transform=plt.gca().transAxes)
     plt.axis("off")
     plt.ion()
     plt.show()
def difference(graph2, graph1):

    D1 = nx.difference(graph2, graph1)
    pos = nx.circular_layout(D1)
    D2 = nx.difference(graph1, graph2)  # edges in graph1 but not in graph2
    pos = nx.circular_layout(D2)

    nx.draw_networkx_nodes(D1,pos, node_color="g", node_size=1000)
    nx.draw_networkx_edges(D1,pos, edge_color='g',width=10) 
    nx.draw_networkx_nodes(D2,pos, node_color="r", node_size=1000)
    nx.draw_networkx_edges(D2,pos, edge_color='r',width=10) 

    plt.show()
#   plt.savefig("M.PDF",facecolor='pink')  #save graph

    return difference
Exemple #15
0
    def generate_minimum(self):
        
        #ele gera a topologia (com pesos) e ja seta os ligados/desligados iniciais.
        for food in self.food_list:
            self.add_node(food,  {'on': True,'Next': True, 'Threshold': 0})   #CORRIGIR ISSO PRA COMIDA QUE TA ERRADO!!!!!
            self.colors.append(palette[1])

        for gene in self.genes_list:
            r = (True == rndm.randint(0,1))
            self.add_node(gene,  {'on': r, 'Next': r, 'Threshold': 0})  #QUANTO COLOCAR PARA O THRESHOLD?
            self.add_edge(gene, gene, {'w': 1.0})    
            self.colors.append(palette[2 if r else 0])
            if r:
                self.switch_dict.update({gene: True})

	for interm in self.intermediate_list:
	    r = (True == rndm.randint(0,1))
            self.add_node(interm,  {'on': r ,'Next': r , 'Threshold': interm % 2})  #quanto deve ser o threshold inicial??
            self.add_edge(interm, interm, {'w': 1.0})
            self.colors.append(palette[3 if r else 0])


        pos2 = nx.circular_layout(self)
        self.pos = {}
        for i in self.control_list:
            self.pos[i] = pos2[self.nodes()[self.control_list.index(i)]]
        self.draw_BN(self.pos, self.control_list)
def draw_graph(graph, graph_layout='shell',
               node_size=1600, node_color='blue', node_alpha=0.3, node_text_size=12,
               edge_color='blue', edge_alpha=0.3, edge_tickness=1, edge_text_pos=0.3,
               text_font='sans-serif', save=True, filename=None):

    edge_labels=dict([((u,v,),d['weight']) for u,v,d in graph.edges(data=True)])
    # these are different layouts for the network you may try
    # shell seems to work best
    if graph_layout == 'spring':
        graph_pos=nx.spring_layout(graph)
    elif graph_layout == 'spectral':
        graph_pos=nx.spectral_layout(graph)
    elif graph_layout == 'random':
        graph_pos=nx.random_layout(graph)
    elif graph_layout == 'circular':
        graph_pos=nx.circular_layout(graph)
    else:
        graph_pos=nx.shell_layout(graph)

    # draw graph
    nx.draw_networkx_nodes(graph, graph_pos, node_size=node_size, alpha=node_alpha, node_color=node_color)
    nx.draw_networkx_edges(graph, graph_pos, width=edge_tickness, alpha=edge_alpha, edge_color=edge_color)
    nx.draw_networkx_labels(graph, graph_pos, font_size=node_text_size, font_family=text_font)
    nx.draw_networkx_edge_labels(graph, graph_pos, edge_labels=edge_labels, label_pos=edge_text_pos)

    # show graph
    if save == True:
        plt.savefig(filename, dpi=1000)
    plt.show()
Exemple #17
0
    def generate_minimum(self):
        
        #ele gera a topologia (com pesos) e ja seta os ligados/desligados iniciais.
        for gene in range(self.number_genes):
            r = (True == rndm.randint(0,1))
            self.add_node(self.genes_list[gene],  {'on': r or (gene in range(self.number_food_total)),'Next': r or (gene in range(self.number_food_total))})
            if gene not in range(self.number_food_total):
                self.add_edge(self.genes_list[gene], self.genes_list[gene], {'w': 1.0})
            self.colors.append(palette[(r or (gene in range(self.number_food_total))) + 0])
            if r and (gene not in range(self.number_food_total)): #or (gene1 in range(self.number_food_total)):
                self.switch_dict.update({self.genes_list[gene]:True})
       
	for interm in range(self.intermediate):
	    r = (True == rndm.randint(0,1))
            self.add_node((interm,),  {'on': r ,'Next': r })
            self.colors.append(palette[r + 0])
##            if r:
##                self.switch_dict.update({(interm,):True})

        pos2 = nx.circular_layout(self)
        self.pos = {}
        for i in self.genes_list + [(c,) for c in range(self.intermediate)]:
            self.pos[i] = pos2[self.nodes()[(self.genes_list + [(c,) for c in range(self.intermediate)]).index(i)]]

        self.draw_BN(self.pos, self.genes_list)
 def test_from_networkx_dictionary_positions(self):
     import networkx as nx
     G = nx.Graph()
     G.add_nodes_from([1, 2, 3])
     positions = nx.circular_layout(G)
     graph = Graph.from_networkx(G, positions)
     self.assertEqual(graph.nodes.dimension_values(2), np.array([1, 2, 3]))
def updatePlot(G, position, spinUp, spinDown, upColor, downColor, ax, E, step):
    """
    Updates plot of network for viewing MC moves.
    """
    pl.cla()
    position = nx.circular_layout(G)
    nx.draw_networkx_nodes(G,position, nodelist=spinUp,
        node_color=upColor)
    nx.draw_networkx_nodes(G,position, nodelist=spinDown,
        node_color=downColor)
    nx.draw_networkx_edges(G,position)
    nx.draw_networkx_labels(G,position)
    ax.text(-0.1, 0.98, 'Spin Up', style='italic',
            bbox={'facecolor':upColor, 'alpha':0.9, 'pad':10})
    ax.text(-0.1, 1.1, 'Spin Down', style='italic',color='White',
            bbox={'facecolor':downColor, 'alpha':0.9, 'pad':10})

    if E:
        os.chdir('./data/')
        if os.path.exists('./animate'):
            pass
        else:
            os.mkdir('./animate/')
        os.chdir('./animate/')
        pl.savefig('animate_'+str(step)+'.png')
        os.chdir('../..')

    pl.draw()
Exemple #20
0
    def generate_minimum(self):
        
        #ele gera a topologia (com pesos) e ja seta os ligados/desligados iniciais.
        for gene in range(self.number_genes):
            r = (True == rndm.randint(0,1))
            self.add_node(self.genes_list[gene],  {'on': r or (gene in range(Constants.food)),'Next': r or (gene in range(Constants.food)), 'Threshold': 0})
            if gene not in range(Constants.food):
                self.add_edge(self.genes_list[gene], self.genes_list[gene], {'w': 1.0})
                self.colors.append(palette[2 if r else 0])
            else:
                self.colors.append(palette[1])
            if r and (gene not in range(Constants.food)): #or (gene1 in range(Constants.food)):
                self.switch_dict.update({self.genes_list[gene]:True})
       
	for interm in range(Constants.intermediate):
	    r = (True == rndm.randint(0,1))
            self.add_node(interm + Constants.metabolites + Constants.reactions,  {'on': r ,'Next': r , 'Threshold': interm % 2})  #quanto deve ser o threshold inicial??
            self.colors.append(palette[3 if r else 0])


        pos2 = nx.circular_layout(self)
        self.pos = {}
        for i in self.genes_list + [c + Constants.metabolites + Constants.reactions for c in range(Constants.intermediate)]:
            self.pos[i] = pos2[self.nodes()[(self.genes_list + [c + Constants.metabolites + Constants.reactions for c in range(Constants.intermediate)]).index(i)]]

        self.draw_BN(self.pos, self.genes_list)
Exemple #21
0
    def displayEigenRankBlendGoogle(self, nodummyvariablelist, alpha, nodepos=None):
        """This method displays the blended weightings of nodes i.e. it takes
        both forward and backward rankings into account.

        Note that this is purely ranking i.e. the standard google rankings do
        not come into play yet."""

        self.blendedrankingGoogle = dict()
        for variable in nodummyvariablelist:
            self.blendedrankingGoogle[variable] = (1 - alpha) * self.gfgain.rankDict[variable] + (alpha) * self.gbgain.rankDict[variable]


        self.EBGG = nx.DiGraph()
        for i in range(self.normalforwardgain.n):
            for j in range(self.normalforwardgain.n):
                if (self.normalforwardgain.gMatrix[i, j] != 0):
                    self.EBGG.add_edge(self.normalforwardgain.gVariables[j], self.normalforwardgain.gVariables[i]) #draws the connectivity graph to visualise rankArray


        plt.figure("Blended Node Rankings: Google")
        rearrange = self.EBGG.nodes()

        for node in self.EBGG.nodes():
            self.EBGG.add_node(node, importance=self.blendedrankingGoogle[node])

        nodelabels = dict((n, [n, round(self.blendedrankingGoogle[n], 3)]) for n in self.EBGG.nodes())
        sizeArray = [self.blendedrankingGoogle[var] * 10000 for var in rearrange]

        if nodepos == None:
            nodepos = nx.circular_layout(self.EBGG)

        nx.draw_networkx(self.EBGG, pos=nodepos , labels=nodelabels, node_size=sizeArray, node_color='y')
        nx.draw_networkx_edges(self.EBGG, pos=nodepos)
        plt.axis("off")
Exemple #22
0
    def displayEdgeWeights(self, nodepos=None):
        """This method will compute and store the edge weights of the ranking web.

        It *NEEDS* the methods displayEigenBlend and displayEigenBlendGoogle to have
        been run!"""

        self.P = nx.DiGraph()
        self.edgelabels = dict()

        for i in range(self.normalforwardgain.n):
            for j in range(self.normalforwardgain.n):
                if (self.normalforwardgain.gMatrix[i, j] != 0):
                    temp = self.normalforwardgain.gMatrix[i, j] * self.blendedranking[self.normalforwardgain.gVariables[j]] - self.blendedrankingGoogle[self.normalforwardgain.gVariables[j]] * self.normalforwardgoogle.gMatrix[i, j]

                    self.edgelabels[(self.normalforwardgain.gVariables[j], self.normalforwardgain.gVariables[i])] = round(-1 * temp, 4)
                    self.P.add_edge(self.normalforwardgain.gVariables[j], self.normalforwardgain.gVariables[i], weight= -1 * temp)

        plt.figure("Edge Weight Graph")

        for node in self.P.nodes():
            self.P.add_node(node, importanceNormal=self.blendedranking[node])
            self.P.add_node(node, importanceGoogle=self.blendedrankingGoogle[node])

        if nodepos == None:
            nodepos = nx.circular_layout(self.P)

        nx.draw_networkx(self.P, pos=nodepos)
        nx.draw_networkx_edge_labels(self.P, pos=nodepos, edge_labels=self.edgelabels, label_pos=0.3)
        nx.draw_networkx_edges(self.P, pos=nodepos, width=2.5, edge_color='k', style='solid', alpha=0.15)
        nx.draw_networkx_nodes(self.P, pos=nodepos, node_color='y', node_size=450)
        plt.axis("off")
Exemple #23
0
    def displayEigenRankGGb(self, nodepos=None):
        """This method constructs a network graph showing connections and rankings
        in terms of node size going BACKWARD and using unity gains between all node
        i.e. the google rank.

        It has an optional parameter nodepos which sets the positions of the nodes,
        if left out the node layout defaults to circular. """


        self.GGB = nx.DiGraph()
        for i in range(self.gbgain.n):
            for j in range(self.gbgain.n):
                if (self.gbgain.gMatrix[i, j] != 0):
                    self.GGB.add_edge(self.gbgain.gVariables[j], self.gbgain.gVariables[i])


        plt.figure("Node Rankings: Google Gain Backward: Scaled")
        rearrange = self.GGB.nodes()

        for node in self.GGB.nodes():
            self.GGB.add_node(node, importance=self.gbgain.rankDict[node])

        nodelabels = dict((n, [n, round(self.gbgain.rankDict[n], 3)]) for n in self.GGB.nodes())
        sizeArray = [self.gbgain.rankDict[var] * 10000 for var in rearrange]

        if nodepos == None:
            nodepos = nx.circular_layout(self.GGB)

        nx.draw_networkx(self.GGB, pos=nodepos , labels=nodelabels, node_size=sizeArray, node_color='y')
        nx.draw_networkx_edges(self.GGB, pos=nodepos)
        plt.axis("off")
Exemple #24
0
 def draw(self):
     """Draws the current game state."""
     unavailables = []
     availables = []
     reds = []
     blues = []
     for i in self.graph.nodes_iter():
         if self.graph.node[i]["label"] == labels.AVAILABLE:
             availables.append(i)
         elif self.graph.node[i]["label"] == labels.RED:
             reds.append(i)
         elif self.graph.node[i]["label"] == labels.BLUE:
             blues.append(i)
         else:
             unavailables.append(i)
     node_labels = {}
     for i in self.graph.nodes_iter():
         node_labels[i] = i
     pos = nx.circular_layout(self.graph)
     nx.draw_networkx_edges(self.graph, pos, edgelist=self.graph.edges(), width=4)
     nx.draw_networkx_nodes(self.graph, pos, nodelist=availables, node_color="w", node_size=500, alpha=1)
     nx.draw_networkx_nodes(self.graph, pos, nodelist=reds, node_color="r", node_size=500, alpha=1)
     nx.draw_networkx_nodes(self.graph, pos, nodelist=blues, node_color="b", node_size=500, alpha=1)
     nx.draw_networkx_nodes(self.graph, pos, nodelist=unavailables, node_color="black", node_size=500, alpha=0.6)
     nx.draw_networkx_node_labels(self.graph, pos, node_labels, font_size=16)
Exemple #25
0
def topology(g):
    if g.size() > 30:
        print "Not drawing topology as size > 30"
    else:
        networkx.draw(g, pos=networkx.circular_layout(g))
        pylab.savefig("topology.png")
        pylab.clf()
Exemple #26
0
	def get(self):
		G = nx.Graph()
		self.add_header("Access-Control-Allow-Origin", "*")
		n_name = self.get_argument('cnode')
		lt = list(one_x_extend(n_name))
		rtid = {"nodes":[],"links":[]}
		for item in cast_path_2_node(lt):
			tmp = {"name":str(item)}
			rtid["nodes"].append(tmp)
		cdict = {}
		for item in enumerate(cast_path_2_node(lt)):
			cdict[str(item[1])] = item[0]
		for item in cast_path_2_link(lt):
			G.add_edge(item[0],item[1])
			tmp = {"source":item[0],"target":item[1]}
			rtid["links"].append(tmp)
		co = choice('01')
		#pos = nx.spring_layout(G, scale=1.0)
		if co == '0':
			pos = nx.circular_layout(G)
		elif co == '1':
			pos = nx.spring_layout(G)
		else:
			pos = nx.shell_layout(G)
		text = ''.join(cast_dict_2_gexf(rtid,pos))
		print text
		self.write(text)
Exemple #27
0
def visualize_weighted_graph(file_name):
    """@todo: Given a file with file that is a graph with first
    column a vertex and preceding columns
    its neighbors and there distances, neighbors are separated by commas

    :a_file: name of the file
    :creates: graph visualization of the Graph and saves it as a file_name.png

    """
    G = nx.Graph()
    with open(file_name) as f:
        for line in f:
            if line:
                line = line.split()
                v1, neighbors = line[0],line[1:]
                for neighbor in neighbors:
                    v2, weight = neighbor.split(',')
                    G.add_edge(v1, v2, weight=int(weight))

    pos=nx.circular_layout(G)
    pylab.figure(2)
    nx.draw(G,pos)
    edge_labels=dict([((u,v,),d['weight'])
                for u,v,d in G.edges(data=True)])
    nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
    pylab.savefig(file_name.replace('txt','png'))
Exemple #28
0
    def displayEigenRankNormalBackward(self, nodepos=None):
        """This method constructs a network graph showing connections and rankings
        in terms of node size going BACKWARD and using the local gains. (it is not
        scaled)

        It has an optional parameter nodepos which sets the positions of the nodes,
        if left out the node layout defaults to circular. """


        self.NBG = nx.DiGraph()
        for i in range(self.normalbackwardgain.n):
            for j in range(self.normalbackwardgain.n):
                if (self.normalbackwardgain.gMatrix[i, j] != 0):
                    self.NBG.add_edge(self.normalbackwardgain.gVariables[j], self.normalbackwardgain.gVariables[i]) #draws the connectivity graph to visualise rankArray


        plt.figure("Node Rankings: Local Gain Backward: Normal")
        rearrange = self.NBG.nodes()

        for node in self.NBG.nodes():
            self.NBG.add_node(node, importance=self.normalbackwardgain.rankDict[node])

        nodelabels = dict((n, [n, round(self.normalbackwardgain.rankDict[n], 3)]) for n in self.NBG.nodes())
        sizeArray = [self.normalbackwardgain.rankDict[var] * 10000 for var in rearrange]

        if nodepos == None:
            nodepos = nx.circular_layout(self.NBG)

        nx.draw_networkx(self.NBG, pos=nodepos , labels=nodelabels, node_size=sizeArray, node_color='y')
        nx.draw_networkx_edges(self.NBG, pos=nodepos)
        plt.axis("off")
def transmission(path,g,src,dest):
 global disp_count
 global bar_colors
 global edge_colors
 global node_colors
 k=0
 j=0
 list_of_edges = g.edges() 
 for node in path :
  k=path.index(node)
  disp_count = disp_count + 1
  if k != (len(path)-1):
   k=path[k+1]
   j=list_of_edges.index((node,k))
   initialize_edge_colors(j)
   #ec[disp_count].remove(-3000) 
   pylab.subplot(121) 
   nx.draw_networkx(g,pos = nx.circular_layout(g),node_color= node_colors,edge_color = edge_colors)
   pylab.annotate("Source",node_positions[src])
   pylab.annotate("Destination",node_positions[dest])
   pylab.title("Transmission")

   he=initializeEnergies(disp_count)
   print he
   pylab.subplot(122)
   pylab.bar(left=[1,2,3,4,5],height=[300,300,300,300,300],width=0.5,color = ['w','w','w','w','w'],linewidth=0) 
   pylab.bar(left=[1,2,3,4,5],height=initializeEnergies(disp_count),width=0.5,color = 'b') 
   pylab.title("Node energies")
   #pylab.legend(["already passed throgh","passing" , "yet to pass"])
   pylab.xlabel('Node number')
   pylab.ylabel('Energy') 
   pylab.suptitle('Leach Protocol', fontsize=12)
   pylab.pause(2)
  else :
     return
def printClusters(msp_list_deleted, msp_list_remain, msp_list, name):
    G = nx.Graph()
    deleted = nx.Graph()
    remain = nx.Graph()

    for l in range(0, len(msp_list)):
        G.add_edge(msp_list[l][1], msp_list[l][2], weight="{0:.2f}".format(msp_list[l][0]))
    pos = nx.circular_layout(G)

    for l in range(0, len(msp_list_deleted)):
        deleted.add_edge(msp_list_deleted[l][1], msp_list_deleted[l][2],
                         weight="{0:.2f}".format(msp_list_deleted[l][0]))

    for l in range(0, len(msp_list_remain)):
        remain.add_edge(msp_list_remain[l][1], msp_list_remain[l][2], weight="{0:.2f}".format(msp_list_remain[l][0]))

    nx.draw(G, pos)
    edge_labels = dict([((u, v,), d['weight']) for u, v, d in G.edges(data=True)])
    edge_labels_deleted = dict([((u, v,), d['weight']) for u, v, d in deleted.edges(data=True)])
    edge_labels_remain = dict([((u, v,), d['weight']) for u, v, d in remain.edges(data=True)])

    nx.draw_networkx_edges(G, pos, edge_labels=edge_labels_deleted)
    nx.draw_networkx_edge_labels(remain, pos, edge_labels=edge_labels)
    nx.draw_networkx_edges(deleted, pos, edge_labels=edge_labels_remain, width=3, edge_color='w', style='dashed')
    plt.savefig(name + ".png")
Exemple #31
0
import sys
import networkx as nx
import matplotlib.pyplot as plt
from antlr4 import *
from EnquestesLexer import EnquestesLexer
from EnquestesParser import EnquestesParser
from antlr4.InputStream import InputStream
from EnquestesVisitor import EnquestesVisitor

if len(sys.argv) > 1:
    input_stream = FileStream(sys.argv[1], encoding='utf-8')
else:
    input_stream = InputStream(input('? '))

lexer = EnquestesLexer(input_stream)
token_stream = CommonTokenStream(lexer)
parser = EnquestesParser(token_stream)
tree = parser.chatboot()
print(tree.toStringTree(recog=parser))

visitor = EnquestesVisitor()
arbol = visitor.visit(tree)

nx.write_gpickle(arbol, "../boot/arbol.pickle")
pos = nx.circular_layout(arbol)
colors = [arbol[u][v]['color'] for u, v in arbol.edges()]
nx.draw(arbol, pos, with_labels=True, edge_color=colors)
plt.show()
    def test_edge_colors_and_widths(self):
        pos = nx.circular_layout(self.G)
        for G in (self.G, self.G.to_directed()):
            nx.draw_networkx_nodes(G, pos, node_color=[(1.0, 1.0, 0.2, 0.5)])
            nx.draw_networkx_labels(G, pos)
            # edge with default color and width
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(0, 1)],
                                   width=None,
                                   edge_color=None)
            # edges with global color strings and widths in lists
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(0, 2), (0, 3)],
                                   width=[3],
                                   edge_color=['r'])
            # edges with color strings and widths for each edge
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(0, 2), (0, 3)],
                                   width=[1, 3],
                                   edge_color=['r', 'b'])
            # edges with fewer color strings and widths than edges
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(1, 2), (1, 3), (2, 3), (3, 4)],
                                   width=[1, 3],
                                   edge_color=['g', 'm', 'c'])
            # edges with more color strings and widths than edges
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(3, 4)],
                                   width=[1, 2, 3, 4],
                                   edge_color=['r', 'b', 'g', 'k'])
            # with rgb tuple and 3 edges - is interpreted with cmap
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(4, 5), (5, 6), (6, 7)],
                                   edge_color=(1.0, 0.4, 0.3))
            # with rgb tuple in list
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(7, 8), (8, 9)],
                                   edge_color=[(0.4, 1.0, 0.0)])
            # with rgba tuple and 4 edges - is interpretted with cmap
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(9, 10), (10, 11), (10, 12),
                                             (10, 13)],
                                   edge_color=(0.0, 1.0, 1.0, 0.5))
            # with rgba tuple in list
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(9, 10), (10, 11), (10, 12),
                                             (10, 13)],
                                   edge_color=[(0.0, 1.0, 1.0, 0.5)])
            # with color string and global alpha
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(11, 12), (11, 13)],
                                   edge_color='purple',
                                   alpha=0.2)
            # with color string in a list
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(11, 12), (11, 13)],
                                   edge_color=['purple'])
            # with single edge and hex color string
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(12, 13)],
                                   edge_color='#1f78b4f0')

            # edge_color as numeric using vmin, vmax
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(7, 8), (8, 9)],
                                   edge_color=[0.2, 0.5],
                                   edge_vmin=0.1,
                                   edge_max=0.6)

            plt.show()
Exemple #33
0
def plot_circular(G,
                  labels=None,
                  dist_text=1.2,
                  cmap="Blues",
                  color_nodes=(),
                  title=""):
    """Plot G as a circular graph.

    Usage
    -----
        import networkx as nx
        G = nx.from_numpy_matrix(A)
        fig = plot_circular(G, labels)
        py.offline.iplot(fig, filename='networkx')
    """
    if labels is None:
        labels = [r"$x_%d$" % i for i in G.nodes]
    pos = nx.circular_layout(G)

    dmin = 1
    # ncenter = 0
    for n in pos:
        x, y = pos[n]
        d = (x - 0.5)**2 + (y - 0.5)**2
        if d < dmin:
            # ncenter = n
            dmin = d

    # pp = nx.single_source_shortest_path_length(G, ncenter)

    pos_array = np.array(list(pos.values()))  # python 3 compatibility

    center = np.array([
        (np.min(pos_array[:, 0]) + np.max(pos_array[:, 0])) / 2,
        (np.min(pos_array[:, 1]) + np.max(pos_array[:, 1])) / 2,
    ])

    # radius = np.linalg.norm(pos_array - center)
    pos_text = center + dist_text * (pos_array - center)  # text position

    # Compute the text angle
    angles = -180 * np.arctan(
        (pos_array[:, 1] - center[1]) / (pos_array[:, 0] - center[0])) / np.pi

    axis = dict(showgrid=False, zeroline=False, showticklabels=False)
    layout = go.Layout(
        title=title,
        titlefont=dict(size=16),
        showlegend=False,
        hovermode="closest",
        margin=dict(b=40, l=5, r=5, t=40),
        width=650,
        height=650,
        annotations=[
            # dict(
            #     text=
            #     "Python code: <a href='https://plot.ly/ipython-notebooks/network-graphs/'> https://plot.ly/ipython-notebooks/network-graphs/</a>",
            #     showarrow=False, xref="paper", yref="paper", x=0.005, y=-0.002)
        ],
        xaxis=dict(axis),
        yaxis=dict(axis),
    )

    # annotations around the circle
    # textangle=angles[k] is the angle with horizontal line through (x,y)
    # in degrees
    # + =clockwise, -=anti-clockwise
    layout["annotations"] += tuple([
        go.layout.Annotation(
            x=pos_text[k][0],
            y=pos_text[k][1],
            text=labels[k],
            textangle=angles[k],
            font=dict(size=20, color="rgb(0,0,0)"),
            showarrow=False,
        ) for k in range(pos_array.shape[0])
    ])

    # V = list(G.nodes())

    Es = G.edges()
    Weights = [edge["weight"] for edge in Es.values()]

    edge_trace = lines_chord(G, pos, labels, Weights, cmap=cmap)
    node_trace = go.Scatter(
        x=[],
        y=[],
        text=[],
        mode="markers",
        hoverinfo="text",
        marker=dict(
            showscale=False,
            colorscale=cmap,
            reversescale=True,
            color=color_nodes,
            size=20,
            colorbar=dict(thickness=15,
                          title="Node Connections",
                          xanchor="left",
                          titleside="right"),
            line=dict(width=2),
        ),
    )

    for node in G.nodes():
        x, y = pos[node]
        node_trace["x"] += tuple([x])
        node_trace["y"] += tuple([y])

    for node, adjacencies in enumerate(G.adjacency()):
        node_trace["marker"]["color"] += tuple([len(adjacencies[1])])
        node_info = "# of connections: {}".format(len(adjacencies[1]))
        node_trace["text"] += tuple([node_info])

    data = edge_trace + [node_trace]
    return go.Figure(data=data, layout=layout)
Exemple #34
0
nodes_reflex = {'Luis(15)','Fernando(16)','Julia(18)'}
nodes_no_reflex = {'Maria(15)','Yanet(17)','Rosi(16)','Desisy(18)',
                   'Pedro(17)','Claudia(16)'}

black=[('Maria(15)','Yanet(17)'),
  ('Maria(15)','Fernando(16)'),('Fernando(16)','Desisy(18)'),
  ('Yanet(17)','Julia(18)'),('Desisy(18)','Pedro(17)'),
  ('Pedro(17)','Julia(18)'),  ('Pedro(17)','Rosi(16)'),
  ('Fernando(16)','Claudia(16)')]

bl=[('Fernando(16)','Desisy(18)'),('Pedro(17)','Rosi(16)')]

lista=['Luis(15)','Julia(18)','Yanet(17)','Rosi(16)','Desisy(18)','Claudia(16)'], ['Maria(15)','Fernando(16)','Pedro(17)']

posicion=nx.circular_layout(A, scale=0.5, center=None, dim=2)

nx.draw_networkx_nodes(A,posicion,nodelist=nodes_reflex,
                       node_size=1800, node_color= '#ea6d6d')
nx.draw_networkx_nodes(A,posicion,nodelist=nodes_no_reflex,
                       node_size=1500, node_color= '#cde95b')
nx.draw_networkx_edges(A, posicion, edgelist=bl, width=5, alpha=0.5,
edge_color='b')
nx.draw_networkx_edges(A, posicion, edgelist=black, width=2,
edge_color='Black')
nx.draw_networkx_labels(A,posicion, font_size=11,font_family='arial',
                        font_color='#4f5148', font_weight='bold')

plot.axis('off')
plot.savefig("Graf9_circular_layout.eps")
plot.show(A)
def completed_graph(inchikey):


    #graphs generated using PIBAS dataset, UniChem and Bio2RDF
    G6 = nx.Graph()
    G8 = nx.Graph()


    #we start from PIBAS local ontology and  for a given InChiKey we found compound acronym 


    sparql = SPARQLWrapper("http://cpctas-lcmb.pmf.kg.ac.rs:2020/sparql")

    sparql.setQuery(
     """  
        PREFIX pibas: <http://cpctas-lcmb.pmf.kg.ac.rs/2012/3/PIBAS#>
        SELECT ?pibas_compound_acronym ?inchikey
        FROM <http://cpctas-lcmb.pmf.kg.ac.rs/2012/3/PIBAS/pibasOntology.owl>
        WHERE
        {
          ?pibas_compound pibas:InChIkey ?inchikey;
                          pibas:acronym ?pibas_compound_acronym.
          FILTER(?inchikey="%s").	

        }
     """% inchikey)  


    sparql.setReturnFormat(JSON)
    final_results = sparql.query().convert()
    for result in final_results["results"]["bindings"]: 
      pibas_acronym=result["pibas_compound_acronym"]["value"]
    #print pibas_acronym

    #add pibas acronym in corresponding form to G6 graph
    pibas_node=pibas_acronym.split(':')[0]+'/'+pibas_acronym.split(':')[1]
    G6.add_node(0,name_label=pibas_node)

    #for a given acronym and PIBAS mapp we found mapping substance
    sparql.setQuery(
     """  
        PREFIX pibas: <http://cpctas-lcmb.pmf.kg.ac.rs/2012/3/PIBAS#>
        SELECT ?mapping_node ?sourceNumber
        FROM <http://cpctas-lcmb.pmf.kg.ac.rs/2012/3/PIBAS/pibasmapping.owl>
        WHERE
        {
          %s pibas:sameAs ?mapping_node;
             pibas:sourceNumber ?sourceNumber.
        }
     """% pibas_acronym) 

    sparql.setReturnFormat(JSON)
    final_results = sparql.query().convert()
    for result in final_results["results"]["bindings"]: 
      pibas_mapping=result["mapping_node"]["value"].split(':')[0]+'/'+result["mapping_node"]["value"].split(':')[1]
      pibas_mapping_source_number=result["sourceNumber"]["value"]

    #print pibas_mapping

    #add pibas mapping node to graph G6
    G6.add_node(1,name_label=pibas_mapping)



    url = 'https://www.ebi.ac.uk/unichem/rest/src_compound_id_all/'+str(pibas_mapping.split('/')[1])+'/'+str(pibas_mapping_source_number)
    #print url
    j=2
    storage = StringIO()
    c = pycurl.Curl()
    c.setopt(c.URL, url)
    c.setopt(c.WRITEFUNCTION, storage.write)
    c.perform()
    c.close()
    content = storage.getvalue()
    unichem_content = json.loads(content)
    for rs in unichem_content: 
     src_compound_id= rs['src_compound_id']
     url = 'https://www.ebi.ac.uk/unichem/rest/sources/'+rs['src_id']
     storage = StringIO()
     c = pycurl.Curl()
     c.setopt(c.URL, url)
     c.setopt(c.WRITEFUNCTION, storage.write)
     c.perform()
     c.close()
     content = storage.getvalue()
     unichem_src_name = json.loads(content)
     for rs in unichem_src_name:
      name=rs['name']
      #print name
      if ((name+'/'+src_compound_id)!=pibas_mapping):
        if((name+'/'+src_compound_id)!=pibas_node):
         G6.add_node(j,name_label=name+'/'+src_compound_id)
         j=j+1



    bio2rdf_dataset=['bindingdb','pubchem','pharmgkb','chebi','kegg_ligand','pdb','drugbank','chembl','pibas','ndc']

    num1=G6.number_of_nodes()
    nodes1=G6.nodes()
    for x in range(0, num1):
     if(((G6.node[x]['name_label']).split('/')[0] in bio2rdf_dataset) and ("pibas" not in (G6.node[x]['name_label']).split('/')[0])):
      
      sparql = SPARQLWrapper("http://cpctas-lcmb.pmf.kg.ac.rs:2020/sparql")
      if((G6.node[x]['name_label']).split('/')[0]=='kegg_ligand'):
       sparql.setQuery(
       """  
        PREFIX bindingdb: <http://bio2rdf.org/bindingdb:>
        PREFIX pubchem: <http://bio2rdf.org/pubchem:>
        PREFIX pharmgkb: <http://bio2rdf.org/pharmgkb:>
        PREFIX chebi: <http://bio2rdf.org/chebi:>
        PREFIX kegg_ligand: <http://bio2rdf.org/kegg:>
        PREFIX pdb: <http://bio2rdf.org/pdb:>
        PREFIX drugbank: <http://bio2rdf.org/drugbank:>
        PREFIX chembl: <http://bio2rdf.org/chembl:> 
        PREFIX ndc: <http://bio2rdf.org/ndc:> 
        select ?p ?o
        WHERE
        {

         SERVICE SILENT<http://kegg.bio2rdf.org/sparql> { 
         OPTIONAL{
          %s:%s ?p ?o.
         FILTER(CONTAINS(str(?p),"http://bio2rdf.org/kegg_vocabulary:x-drugbank") || CONTAINS(str(?p),"http://bio2rdf.org/kegg_vocabulary:x-pubchem.compound") || CONTAINS(str(?p),"http://bio2rdf.org/kegg_vocabulary:x-kegg")  || CONTAINS(str(?p),"http://bio2rdf.org/kegg_vocabulary:x-chembl") || CONTAINS(str(?p),"http://bio2rdf.org/kegg_vocabulary:x-chebi") || CONTAINS(str(?p),"http://bio2rdf.org/kegg_vocabulary:same-as")).
        }
        }

        }

       """ % (((G6.node[x]['name_label']).split('/')[0]),((G6.node[x]['name_label']).split('/')[1])))

      else:
       
       sparql.setQuery(
       """  
        PREFIX bindingdb: <http://bio2rdf.org/bindingdb:>
        PREFIX pubchem: <http://bio2rdf.org/pubchem:>
        PREFIX pharmgkb: <http://bio2rdf.org/pharmgkb:>
        PREFIX chebi: <http://bio2rdf.org/chebi:>
        PREFIX kegg_ligand: <http://bio2rdf.org/kegg:>
        PREFIX pdb: <http://bio2rdf.org/pdb:>
        PREFIX drugbank: <http://bio2rdf.org/drugbank:>
        PREFIX chembl: <http://bio2rdf.org/chembl:>
        PREFIX ndc: <http://bio2rdf.org/ndc:> 
        select ?p ?o
        WHERE
        {

         SERVICE SILENT<http://%s.bio2rdf.org/sparql> { 
         OPTIONAL{
          %s:%s ?p ?o.
         FILTER(CONTAINS(str(?p),"http://bio2rdf.org/%s_vocabulary:x-drugbank") || CONTAINS(str(?p),"http://bio2rdf.org/%s_vocabulary:x-pubchem.compound") || CONTAINS(str(?p),"http://bio2rdf.org/%s_vocabulary:x-kegg")  || CONTAINS(str(?p),"http://bio2rdf.org/%s_vocabulary:x-chembl") || CONTAINS(str(?p),"http://bio2rdf.org/%s_vocabulary:x-chebi") || CONTAINS(str(?p),"http://bio2rdf.org/%s_vocabulary:x-ndc") || CONTAINS(str(?p),"http://bio2rdf.org/%s_vocabulary:same-as")).
        }
        }

        }

       """ % (((G6.node[x]['name_label']).split('/')[0]),((G6.node[x]['name_label']).split('/')[0]),((G6.node[x]['name_label']).split('/')[1]),((G6.node[x]['name_label']).split('/')[0]),((G6.node[x]['name_label']).split('/')[0]),((G6.node[x]['name_label']).split('/')[0]),((G6.node[x]['name_label']).split('/')[0]),((G6.node[x]['name_label']).split('/')[0]),((G6.node[x]['name_label']).split('/')[0]),((G6.node[x]['name_label']).split('/')[0])))

      sparql.setReturnFormat(JSON)
      final_results1 = sparql.query().convert()
      try:
       v=G6.number_of_nodes()
       for result1 in final_results1["results"]["bindings"]:
        if(result1["o"]["value"]!=""):  
         node_for_add=result1["o"]["value"] 
         node_of_second_level=node_for_add.split("/")[-1]
         if(node_of_second_level.split(':')[0]=='kegg'):
          node_for_add='kegg_ligand/'+node_of_second_level.split(':')[1]
         else:
          node_for_add=node_of_second_level.split(':')[0]+'/'+node_of_second_level.split(':')[1]
          #print node_for_add
         compare_node=[]
         for x in range(0,G6.number_of_nodes()):
           compare_node.append(str((G6.node[x]['name_label']).split('/')[0])+'/'+str((G6.node[x]['name_label']).split('/')[1]))

         if(node_for_add not in compare_node):
          G6.add_node(v,name_label=node_for_add,predicate=result1["p"]["value"])
          v=v+1
          #print v
      except:     
        continue



    nodes=G6.nodes()

    #print nodes

    edges = combinations(nodes, 2)
    G6.add_nodes_from(nodes)
    G6.add_edges_from(edges)

    num1=G6.number_of_nodes()
    nodes1=G6.nodes()
    left_graph_for_remove=[]
    for x in range(0, num1):
     if(((G6.node[x]['name_label']).split('/')[0] not in bio2rdf_dataset)):
      G6.remove_node(x)

    nodes1=G6.nodes()
    #print nodes1
    custom_labels1={}
    for x in nodes1:
     custom_labels1[x] = str(x)+':'+G6.node[x]['name_label']
   
    
    #print custom_labels1
    #create and draw graph G6
    pos=nx.circular_layout(G6,dim=2, scale=100)
    plt.clf()
    nx.draw(G6, labels=custom_labels1, with_labels=True)
    plt.savefig('/var/www/specint.org/public_html/specint/img/completed_graph_bio2rdf_'+inchikey+'.png')


    #******************Using Chem2Bio2RDF***********************************************************************************

   
    G7 = nx.Graph()

    
    index_for_new_graph=max(G6.nodes())
    #print index_for_new_graph



    url = 'https://www.ebi.ac.uk/unichem/rest/inchikey/'+inchikey
    #print url
    j=index_for_new_graph+1
    storage = StringIO()
    c = pycurl.Curl()
    c.setopt(c.URL, url)
    c.setopt(c.WRITEFUNCTION, storage.write)
    c.perform()
    c.close()
    content = storage.getvalue()
    unichem_content = json.loads(content)
    for rs in unichem_content: 
     src_compound_id= rs['src_compound_id']
     url = 'https://www.ebi.ac.uk/unichem/rest/sources/'+rs['src_id']
     storage = StringIO()
     c = pycurl.Curl()
     c.setopt(c.URL, url)
     c.setopt(c.WRITEFUNCTION, storage.write)
     c.perform()
     c.close()
     content = storage.getvalue()
     unichem_src_name = json.loads(content)
     for rs in unichem_src_name:
      name=rs['name']
      #print name
      G7.add_node(j,name_label=name+'/'+src_compound_id)
      j=j+1


    chem2bio2rdf_dataset=['bindingdb','pubchem','chebi','kegg_ligand','kegg','pdb','drugbank','chembl','uniprot','matador','ctd','dcdb','hgnc','pharmgkb','hprd']


    num1=G7.number_of_nodes()
    nodes1=G7.nodes()
    for x in range(index_for_new_graph+1,index_for_new_graph+num1):
     if(((G7.node[x]['name_label']).split('/')[0] in bio2rdf_dataset) and ("chembl" not in (G7.node[x]['name_label']).split('/')[0])):
      sparql = SPARQLWrapper("http://cpctas-lcmb.pmf.kg.ac.rs:2020/sparql")
      if((G7.node[x]['name_label']).split('/')[0]=='kegg_ligand'):
       sparql.setQuery(
       """  
        PREFIX bindingdb: <http://chem2bio2rdf.org/bindingdb/resource/>
        PREFIX pubchem: <http://chem2bio2rdf.org/pubchem/resource/>
        PREFIX uniprot: <http://chem2bio2rdf.org/uniprot/resource/>
        PREFIX chebi: <http://chem2bio2rdf.org/chebi/resource/chebi/CHEBI~>
        PREFIX kegg_ligand: <http://chem2bio2rdf.org/kegg/resource/kegg_ligand/>
        PREFIX pdb: <http://chem2bio2rdf.org/pdb/resource/pdb_ligand/>
        PREFIX drugbank: <http://chem2bio2rdf.org/drugbank/resource/>
        PREFIX matador: <http://chem2bio2rdf.org/matador/resource/>
        PREFIX chembl: <http://chem2bio2rdf.org/chembl/resource/> 
        PREFIX uniprot: <http://chem2bio2rdf.org/uniprot/resource/>
        PREFIX db: <http://chem2bio2rdf.org/kegg/resource/>
        select ?o
        WHERE
        {

         SERVICE SILENT<http://cheminfov.informatics.indiana.edu:8080/kegg/sparql> { 
         OPTIONAL{
          %s:%s db:CID ?o.

            }

        }

        }

       """ % (((G7.node[x]['name_label']).split('/')[0]),((G7.node[x]['name_label']).split('/')[1])))
      elif((G7.node[x]['name_label']).split('/')[0]=='drugbank'):
       sparql.setQuery(
       """
        PREFIX db:<http://chem2bio2rdf.org/drugbank/resource/>
        PREFIX drugbank:<http://chem2bio2rdf.org/drugbank/resource/drugbank_drug/>
        select ?o
        WHERE
        {

         
         SERVICE SILENT<http://147.91.203.161:8890/sparql>{
          drugbank:%s db:CID ?o.

            }

        }
       """ % (G7.node[x]['name_label']).split('/')[1])
      else:
       sparql.setQuery(
       """  
        PREFIX bindingdb: <http://bio2rdf.org/bindingdb:>
        PREFIX pubchem: <http://bio2rdf.org/pubchem:>
        PREFIX pharmgkb: <http://bio2rdf.org/pharmgkb:>
        PREFIX chebi: <http://bio2rdf.org/chebi:>
        PREFIX kegg_ligand: <http://bio2rdf.org/kegg:>
        PREFIX pdb: <http://bio2rdf.org/pdb:>
        PREFIX drugbank: <http://bio2rdf.org/drugbank:>
        PREFIX chembl: <http://bio2rdf.org/chembl:>
        PREFIX ndc: <http://bio2rdf.org/ndc:> 
        PREFIX db: <http://chem2bio2rdf.org/%s/resource/>
        select ?o
        WHERE
        {

         SERVICE SILENT<http://cheminfov.informatics.indiana.edu:8080/%s/sparql> { 
         OPTIONAL{
          %s:%s db:CID ?o.
            }
        }

        }

       """ % (((G7.node[x]['name_label']).split('/')[0]),((G7.node[x]['name_label']).split('/')[0]),((G7.node[x]['name_label']).split('/')[0]),((G7.node[x]['name_label']).split('/')[1])))

      sparql.setReturnFormat(JSON)
      final_results1 = sparql.query().convert()
      try:
       v=G7.number_of_nodes()
       for result1 in final_results1["results"]["bindings"]:
        if(result1["o"]["value"]!=""):  
         node_for_add=result1["o"]["value"] 
         node_of_second_level=node_for_add.split("/")[-1]
         if(node_of_second_level.split(':')[0]=='kegg'):
          node_for_add='kegg_ligand/'+node_of_second_level.split(':')[1]
         else:
          node_for_add=node_of_second_level.split(':')[0]+'/'+node_of_second_level.split(':')[1]
          #print node_for_add
         compare_node=[]
         for x in range(index_for_new_graph+1,index_for_new_graph+num1):
           compare_node.append(str((G7.node[x]['name_label']).split('/')[0])+'/'+str((G7.node[x]['name_label']).split('/')[1]))
         if(node_for_add not in compare_node):
          G7.add_node(v,name_label=node_for_add,predicate=result1["p"]["value"])
          v=v+1
          #print v
      except:     
        continue



    nodes=G7.nodes()

    #print nodes

    edges = combinations(nodes, 2)
    G7.add_nodes_from(nodes)
    G7.add_edges_from(edges)

    num1=G7.number_of_nodes()
    nodes1=G7.nodes()
    left_graph_for_remove=[]
    for x in nodes1:
     if(((G7.node[x]['name_label']).split('/')[0] not in chem2bio2rdf_dataset)):
      G7.remove_node(x)


    nodes1=G7.nodes()
    custom_labels1={}
    for x in nodes1:
     custom_labels1[x] = str(x)+':'+G7.node[x]['name_label']


    #create and draw graph G7
    pos=nx.circular_layout(G7,dim=2, scale=100)
    plt.clf()
    nx.draw(G7, labels=custom_labels1, with_labels=True)
    plt.savefig('/var/www/specint.org/public_html/specint/img/completed_graph_chem2bio2rdf_'+inchikey+'.png')


    #*************Join grpahs*************************
    G10=nx.union(G6,G7)

    nodes1=G10.nodes()
    custom_labels1={}
    for x in nodes1:
     custom_labels1[x] = str(x)+':'+G10.node[x]['name_label']

    #create and draw graph G10
    pos=nx.circular_layout(G10,dim=2, scale=300)
    plt.clf()
    nx.draw(G10,  labels=custom_labels1, with_labels=True)
    plt.savefig('/var/www/specint.org/public_html/specint/img/completed_graph_'+inchikey+'.eps',format='eps', dpi=300)
    plt.savefig('/var/www/specint.org/public_html/specint/img/completed_graph_'+inchikey+'.png')
    

       #************************Removing node************************
    nodes_for_connection=[]
    nodes_value_for_connection=[]

    values_for_connected_nodes=['pubchem','chebi','drugbank','kegg_ligand']
    
   
    #print values_for_connected_nodes
    for x in values_for_connected_nodes:
        nodes_for_connection=[]
        #connection_node=random.choice(values_for_connected_nodes)
        connection_node=x
        #print connection_node

        nodes5=G10.nodes()
		
        for x in nodes5:
         if((G10.node[x]['name_label']).split('/')[0]==connection_node):
          nodes_for_connection.append(x)
          nodes_value_for_connection.append((G10.node[x]['name_label']).split('/')[1])


        #print nodes_for_connection

        if(len(nodes_for_connection)>=2):
            my_array_for_node_connected=[]
            for x in range(0,len(nodes_value_for_connection)-1):
              for y in range(x+1,len(nodes_value_for_connection)):
                if(nodes_value_for_connection[x]==nodes_value_for_connection[y]):
                 my_array_for_node_connected.append(nodes_for_connection[x])
                 my_array_for_node_connected.append(nodes_for_connection[y])

            #print my_array_for_node_connected
            #print max(my_array_for_node_connected)
            #print min(my_array_for_node_connected)
            if(len(my_array_for_node_connected)>0):
             G10.remove_node(max(my_array_for_node_connected))

             for_delete=G10.nodes()
            #print for_delete

             position=(G10.nodes()).index(min(my_array_for_node_connected))
            #print position

             for x in for_delete:
              if((x>min(my_array_for_node_connected)) and (x not in G6.nodes())):
               G10.add_edge(min(my_array_for_node_connected),x)

             nodes1=G10.nodes()
             custom_labels1={}
             for x in nodes1:
              custom_labels1[x] = str(x)+':'+G10.node[x]['name_label']
             #create and draw graph G10
             pos=nx.circular_layout(G10,dim=2, scale=300)
             plt.clf()
             nx.draw(G10,  labels=custom_labels1, with_labels=True)
             plt.savefig('/var/www/specint.org/public_html/specint/img/completed_graph_'+inchikey+'.eps',format='eps', dpi=300)
             plt.savefig('/var/www/specint.org/public_html/specint/img/completed_graph_'+inchikey+'.png')
             #H = nx.Graph()
             #H.add_nodes_from(G10.nodes())
             #H.add_edges_from(G10.edges())			
             image='myimage_for_completed_graph.png'
             if(nx.is_connected(G10)==True):
              fv=nx.fiedler_vector(G10,method='lobpcg')
              create_python_file(G10.nodes(),G10.edges(), inchikey)
              return {'fv':fv, 'connection_node':connection_node}
              break
             else:
              #print 'Undirected graph is not connected! Please, try again!';
              return {'fv':'Undirected graph is not connected! Please, try again!'}
            else:
             #print 'Undirected graph is not connected! Please, try again!'
             return {'fv':'Undirected graph is not connected! Please, try again!'}  
        else:
         #return completed_graph(inchikey)
         #continue
         #print 'Undirected graph is not connected! Please, try again!'
         return {'fv':'Undirected graph is not connected! Please, try again!'}
def show_rela_diagnosis(relation, select, cmap=plt.cm.Blues):
    """ Visualize diagnosis on relationships of 4 scales
    
    Args:
        relation: (np.array | torch.tensor) of shpae (60,)
        select: List of select item indices
    """
    mats = vec2mat(relation , select)
        
    fig = plt.figure(figsize=(20, 5))
    all_names = {0:'Top', 1:'Bottom', 2:'Shoe', 3:'Bag', 4:'Accssory'}
    node_names = {i:all_names[s] for i, s in enumerate(select)}
    
    edge_vmax = max(m.max() for m in mats)
    edge_vmin = min(m.min() for m in mats)
    
    container = []
    for idx in range(4):
        A = mats[idx]
        if isinstance(A, torch.Tensor):
            A = A.cpu().data.numpy()
                   
        A = np.triu(A, k=1)
        A = np.round(A, decimals=2)
        container.append(A)
    container = np.stack(container)
    sorted_vedge = sorted(container.ravel(), reverse=True)
        
    for idx in range(4):
        plt.subplot(1, 4, idx+1)
        plt.title("Layer {}".format(idx+1), fontsize=28)
        A = mats[idx]
        if isinstance(A, torch.Tensor):
            A = A.cpu().data.numpy()
                   
        A = np.triu(A, k=1)
        A = np.round(A, decimals=2)
        indices = np.triu_indices(A.shape[0], k=1)
        weights = A[indices[0], indices[1]]
        # Generate graph
        G = nx.Graph()
        for i, j, weight in zip(*indices, weights):
            G.add_edge(node_names[i], node_names[j], weight=weight)
        
        elarge, esmall, filtered_weights = [], [], []
        for e in G.edges(data=True):
            if e[2]['weight'] in sorted_vedge[:3]:
                elarge.append((e[0], e[1]))
            else:
                esmall.append((e[0], e[1]))
                filtered_weights.append(e[2]['weight'])
        pos=nx.circular_layout(G) # positions for all nodes

        # nodes
        nx.draw_networkx_nodes(G, pos, nodelist=[n for n in G.nodes()], node_size=1600, node_color='#A0CBE2')

        # edges
        nx.draw_networkx_edges(G,pos,edgelist=esmall, width=6, alpha=0.5, edge_color=filtered_weights, edge_cmap=cmap,
                               edge_vmax=edge_vmax, edge_vmin=edge_vmin)
        nx.draw_networkx_edges(G,pos,edgelist=elarge, width=6, alpha=0.5, edge_color='red', style='dashed')

        # labels
        labels = nx.get_edge_attributes(G,'weight')
        nx.draw_networkx_labels(G,pos, font_size=18, font_family='Times New Roman')
        if len(select) == 4:
            nx.draw_networkx_edge_labels(G, pos, font_size=18, font_family='Times New Roman', edge_labels=labels, label_pos=0.33)
        else:
            nx.draw_networkx_edge_labels(G, pos, font_size=18, font_family='Times New Roman', edge_labels=labels)
        
        plt.axis('off')
        plt.gca().get_xaxis().set_visible(False)
        plt.gca().get_yaxis().set_visible(False)
    plt.tight_layout()
    plt.show()
Exemple #37
0
G.add_edge(7, 8)
G.add_edge(7, 9)
G.add_edge(7, 14)
G.add_edge(7, 16)
G.add_edge(7, 17)
G.add_edge(8, 9)
G.add_edge(8, 14)
G.add_edge(8, 16)
G.add_edge(8, 17)
G.add_edge(9, 14)
G.add_edge(9, 16)
G.add_edge(9, 17)
G.add_edge(14, 16)
G.add_edge(14, 17)
G.add_edge(16, 17)
G.add_edge(23, 25)
G.add_edge(23, 26)
G.add_edge(23, 27)
G.add_edge(25, 26)
G.add_edge(25, 27)
G.add_edge(26, 27)

print G.nodes()
print nx.fiedler_vector(G, method='lobpcg')

pos = nx.circular_layout(G, dim=50, scale=100)
plt.clf()
nx.draw(G, with_labels=True)
plt.savefig(
    'C:/Users/Branko/Desktop/ZRIHAIZYIMGOAB-UHFFFAOYSA-N_unoriented.png')
Exemple #38
0
            temp_sum += row[i]
            temp_count += 1

g1 = generate_visibility_graph({
    "t": range(len(month_temp)),
    "x": average_temp
})

g2 = generate_visibility_graph({
    "t": range(len(month_humidity)),
    "x": average_humidity
})

print(g1.edges())
print(g2.edges())
graph_pos = nx.circular_layout(g1)
nx.draw_networkx_nodes(g1, graph_pos, node_size=1000, node_color='skyblue')
nx.draw_networkx_edges(g1, graph_pos)
nx.draw_networkx_labels(g1, graph_pos, font_size=12, font_family='sans-serif')

plt.figure()
plt.stem(range(len(month_temp)), average_temp)

plt.figure()
graph_pos = nx.circular_layout(g2)
nx.draw_networkx_nodes(g2, graph_pos, node_size=1000, node_color='skyblue')
nx.draw_networkx_edges(g2, graph_pos)
nx.draw_networkx_labels(g2, graph_pos, font_size=12, font_family='sans-serif')

plt.figure()
plt.stem(range(len(month_humidity)), average_humidity)
Exemple #39
0
def draw_graph(graph,
               vertex_label='label',
               secondary_vertex_label=None,
               edge_label='label',
               secondary_edge_label=None,
               vertex_color=None,
               vertex_color_dict=None,
               vertex_alpha=0.6,
               vertex_border=1,
               vertex_size=600,
               colormap='YlOrRd',
               vmin=0,
               vmax=1,
               invert_colormap=False,
               edge_colormap='YlOrRd',
               edge_vmin=0,
               edge_vmax=1,
               edge_color=None,
               edge_width=None,
               edge_alpha=0.5,
               dark_edge_colormap='YlOrRd',
               dark_edge_vmin=0,
               dark_edge_vmax=1,
               dark_edge_color=None,
               dark_edge_dotted=True,
               dark_edge_alpha=0.3,
               size=10,
               size_x_to_y_ratio=1,
               font_size=9,
               layout='graphviz',
               prog='neato',
               pos=None,
               verbose=True,
               file_name=None,
               title_key='id',
               ignore_for_layout="edge_attribute",
               logscale=False):
    """Plot graph layout."""
    if size is not None:
        size_x = size
        size_y = int(float(size) / size_x_to_y_ratio)
        plt.figure(figsize=(size_x, size_y))
    plt.grid(False)
    plt.axis('off')

    if vertex_label is not None:
        if secondary_vertex_label:
            vertex_labels = dict()
            for u, d in graph.nodes(data=True):
                label1 = _serialize_list(d.get(vertex_label, 'N/A'))
                label2 = _serialize_list(d.get(secondary_vertex_label, 'N/A'))
                vertex_labels[u] = '%s\n%s' % (label1, label2)
        else:
            vertex_labels = dict()
            for u, d in graph.nodes(data=True):
                label = d.get(vertex_label, 'N/A')
                vertex_labels[u] = _serialize_list(label)

    edges_normal = [(u, v) for (u, v, d) in graph.edges(data=True)
                    if d.get('nesting', False) is False]
    edges_nesting = [(u, v) for (u, v, d) in graph.edges(data=True)
                     if d.get('nesting', False) is True]

    if edge_label is not None:
        if secondary_edge_label:
            edge_labels = dict([
                ((
                    u,
                    v,
                ), '%s\n%s' %
                 (d.get(edge_label, ''), d.get(secondary_edge_label, '')))
                for u, v, d in graph.edges(data=True)
            ])
        else:
            edge_labels = dict([((
                u,
                v,
            ), d.get(edge_label, '')) for u, v, d in graph.edges(data=True)])

    if vertex_color is None:
        node_color = 'white'
    elif vertex_color in ['_labels_', '_label_', '__labels__', '__label__']:
        node_color = []
        for u, d in graph.nodes(data=True):
            label = d.get('label', '.')
            if vertex_color_dict is not None:
                node_color.append(vertex_color_dict.get(label, 0))
            else:
                node_color.append(hash(_serialize_list(label)))
    else:
        if invert_colormap:
            node_color = [
                -d.get(vertex_color, 0) for u, d in graph.nodes(data=True)
            ]
        else:
            node_color = [
                d.get(vertex_color, 0) for u, d in graph.nodes(data=True)
            ]
        if logscale is True:
            log_threshold = 0.01
            node_color = [
                math.log(c) if c > log_threshold else math.log(log_threshold)
                for c in node_color
            ]
    if edge_width is None:
        widths = 1
    elif isinstance(edge_width, int):
        widths = edge_width
    else:
        widths = [
            d.get(edge_width, 1) for u, v, d in graph.edges(data=True)
            if 'nesting' not in d
        ]
    if edge_color is None:
        edge_colors = 'black'
    elif edge_color in ['_labels_', '_label_', '__labels__', '__label__']:
        edge_colors = [
            hash(str(d.get('label', '.')))
            for u, v, d in graph.edges(data=True) if 'nesting' not in d
        ]
    else:
        if invert_colormap:
            edge_colors = [
                -d.get(edge_color, 0) for u, v, d in graph.edges(data=True)
                if 'nesting' not in d
            ]
        else:
            edge_colors = [
                d.get(edge_color, 0) for u, v, d in graph.edges(data=True)
                if 'nesting' not in d
            ]
    if dark_edge_color is None:
        dark_edge_colors = 'black'
    else:
        dark_edge_colors = [
            d.get(dark_edge_color, 0) for u, v, d in graph.edges(data=True)
            if 'nesting' in d
        ]
    tmp_edge_set = [(a, b, d) for (a, b, d) in graph.edges(data=True)
                    if ignore_for_layout in d]
    graph.remove_edges_from(tmp_edge_set)

    if pos is None:
        if layout == 'graphviz':
            graph_copy = graph.copy()
            # remove all attributes for graphviz layout
            for u, d in graph_copy.nodes(data=True):
                graph_copy.node[u] = {}
            for u, v, d in graph_copy.edges(data=True):
                graph_copy.edge[u][v] = {}
            pos = nx.graphviz_layout(graph_copy,
                                     prog=prog,
                                     args="-Gmaxiter=1000")
        elif layout == "RNA":
            import RNA
            rna_object = RNA.get_xy_coordinates(graph.graph['structure'])
            pos = {
                i: (rna_object.get(i).X, rna_object.get(i).Y)
                for i in range(len(graph.graph['structure']))
            }
        elif layout == 'circular':
            pos = nx.circular_layout(graph)
        elif layout == 'random':
            pos = nx.random_layout(graph)
        elif layout == 'spring':
            pos = nx.spring_layout(graph)
        elif layout == 'shell':
            pos = nx.shell_layout(graph)
        elif layout == 'spectral':
            pos = nx.spectral_layout(graph)
        elif layout == 'KK':
            pos = KKEmbedder().transform(graph)
        else:
            raise Exception('Unknown layout format: %s' % layout)

    if vertex_border is False:
        linewidths = 0.001
    else:
        linewidths = 1

    graph.add_edges_from(tmp_edge_set)

    nodes = nx.draw_networkx_nodes(graph,
                                   pos,
                                   node_color=node_color,
                                   alpha=vertex_alpha,
                                   node_size=vertex_size,
                                   linewidths=linewidths,
                                   cmap=plt.get_cmap(colormap),
                                   vmin=vmin,
                                   vmax=vmax)
    nodes.set_edgecolor('k')

    nx.draw_networkx_edges(graph,
                           pos,
                           edgelist=edges_normal,
                           width=widths,
                           edge_color=edge_colors,
                           edge_cmap=plt.get_cmap(edge_colormap),
                           edge_vmin=edge_vmin,
                           edge_vmax=edge_vmax,
                           alpha=edge_alpha)
    if dark_edge_dotted:
        style = 'dotted'
    else:
        style = 'solid'
    nx.draw_networkx_edges(graph,
                           pos,
                           edgelist=edges_nesting,
                           width=1,
                           edge_cmap=plt.get_cmap(dark_edge_colormap),
                           edge_vmin=dark_edge_vmin,
                           edge_vmax=dark_edge_vmax,
                           edge_color=dark_edge_colors,
                           style=style,
                           alpha=dark_edge_alpha)
    if edge_label is not None:
        nx.draw_networkx_edge_labels(graph,
                                     pos,
                                     edge_labels=edge_labels,
                                     font_size=font_size)
    if vertex_label is not None:
        nx.draw_networkx_labels(graph,
                                pos,
                                vertex_labels,
                                font_size=font_size,
                                font_color='black')
    if title_key:
        title = str(graph.graph.get(title_key, ''))
        font = FontProperties()
        font.set_family('monospace')
        plt.title(title, fontproperties=font)
    if size is not None:
        # here we decide if we output the image.
        # note: if size is not set, the canvas has been created outside
        # of this function.
        # we wont write on a canvas that we didn't create ourselves.
        if file_name is None:
            plt.show()
        else:
            plt.savefig(file_name,
                        bbox_inches='tight',
                        transparent=True,
                        pad_inches=0)
            plt.close()
Exemple #40
0
def draw_lesion_graph(G, bl, labels=None, subnets=None, lesion_nodes=None):
    """
    Parameters

    subnets : dict
     A colors,label list dict of subnetworks that covers the graph
    """
    if labels is None:
        labels = G.nodes()

    if subnets is None:
        subnets = dict(b=G.nodes())

    all_nodes = set(labels)

    lab_idx = range(len(labels))
    labels_dict = dict(zip(labels, lab_idx))
    idx2lab_dict = dict(zip(lab_idx, labels))

    # Check that all subnets cover the whole graph
    subnet_nodes = []
    for ss in subnets.values():
        subnet_nodes.extend(ss)
    subnet_nodes = set(subnet_nodes)
    assert subnet_nodes == all_nodes

    # Check that the optional lesion list is contained in all the nodes
    if lesion_nodes is None:
        lesion_nodes = set()
    else:
        lesion_nodes = set(lesion_nodes)

    assert lesion_nodes.issubset(all_nodes),\
          "lesion nodes:%s not a subset of nodes" % lesion_nodes

    # Make a table that maps lesion nodes to colors
    lesion_colors = pick_lesion_colors(lesion_nodes, subnets)

    # Compute positions for all nodes - nx has several algorithms
    pos = nx.circular_layout(G)

    # Create the actual plot where the graph will be displayed
    #fig = plt.figure()

    #plt.subplot(1,12,bl+1)

    good_nodes = all_nodes - lesion_nodes
    # Draw nodes
    for node_color, nodes in subnets.items():
        nodelabels = set(nodes) - lesion_nodes
        nodelist = lab2node(nodelabels, labels_dict)
        nx.draw_networkx_nodes(G,
                               pos,
                               nodelist=nodelist,
                               node_color=node_color,
                               node_size=700,
                               node_shape='o')

    for nod in lesion_nodes:
        nx.draw_networkx_nodes(G,
                               pos,
                               nodelist=[labels_dict[nod]],
                               node_color=lesion_colors[nod],
                               node_size=700,
                               node_shape='s')

    # Draw edges
    draw_networkx_edges(G, pos)

    # Draw labels
    nx.draw_networkx_labels(G, pos, idx2lab_dict)
Exemple #41
0
def plot_graph(
    G,
    pos=None,
    colors=None,
    node_labels=None,
    node_size=0.04,
    edgescale=1.0,
    nodeopts={},
    labelopts={},
    arrowopts={},
    bidir_arrows=True,
    cmap='Paired',
):
    """Plot a graphs.  Supports both directed and undirected graphs.
  Undirected edges are drawn as lines while directed edges are drawn
  as arrows.

  For example:

  .. plot::
      :include-source:

      >>> from graphy import plotting
      >>> import networkx as nx
      >>> G=nx.karate_club_graph()
      >>> plotting.plot_graph(G, pos=nx.spring_layout(G), colors=range(G.number_of_nodes())) # doctest: +SKIP


  Parameters
  ----------
  G : networkx Graph object or 2-d np.array
      Graph to plot, either instance of networkx Graph or a 2-d connectivity 
      matrix.
  pos : dict
      Dict specifying positions of nodes, as in {node: (x,y).  If not provided, 
      nodes are arranged along a circle.
  colors : list of ints (default None)
      Color(s) to use for node faces, if desired.
  node_labels : list of strings (default None)
      Labels to use for node labels, if desired.
  node_size : float (default 0.05)
      Size of nodes.
  edgescale : float (default 1.0)
      Controls thickness of edges between nodes.
  nodeopts : dict (default {})
      Extra options to pass into plt.Circle call for plotting nodes.
  labelopts : dict (default {})
      Extra options to pass into plt.text call for plotting labels. 
      Could be used to specify fontsize, for example.
  arrowopts : dict (default {})
      Extra options to pass into plt.arrow call for plotting edges.
  bidir_arrows : bool (default True)
      Whether to draw arrowheads when graph is directed and two 
      nodes are connected bidirectionally.
  cmap : string (default 'Paired')
      Name of colormap to use.
  """
    class MplColorHelper:
        """Class that helps pick colors from specified colormaps.
    """
        def __init__(self, cmap_name, start_val, stop_val):
            self.cmap_name = cmap_name
            self.cmap = plt.get_cmap(cmap_name)
            self.norm = mpl.colors.Normalize(vmin=start_val, vmax=stop_val)
            self.scalarMap = cm.ScalarMappable(norm=self.norm, cmap=self.cmap)

        def get_rgb(self, val):
            return self.scalarMap.to_rgba(val)

    def intersect_two_circles(xy1, r1, xy2, r2):
        d = np.linalg.norm(xy2 - xy1)

        a = (r1**2 - r2**2 + d**2) / (2 * d)
        b = d - a
        h = np.sqrt(r1**2 - a**2)
        xy3 = xy1 + a * (xy2 - xy1) / d

        ix = xy3[0] + h * (xy2[1] - xy1[1]) / d
        iy = xy3[1] - h * (xy2[0] - xy1[0]) / d

        return np.array([ix, iy])

    if isinstance(G, (np.ndarray, np.generic)):
        G = nx.from_numpy_matrix(G, create_using=nx.DiGraph())
    elif not isinstance(G, nx.Graph):
        raise ValueError('Unknown type of graph: %s' % str(type(G)))

    if pos is None:
        pos = nx.circular_layout(G)

    if colors is None:
        colors = 1

    if not isinstance(colors, collections.Iterable):
        colors = [
            colors,
        ] * G.number_of_nodes()

    colors = np.asarray(colors)

    cmap_helper = MplColorHelper(cmap, colors.min(), colors.max())

    bbox = plt.gca().get_window_extent()
    asp_ratio = bbox.width / bbox.height

    node_map = {n: ndx for ndx, n in enumerate(G.nodes())}
    xys = np.array([pos[n] for n in G.nodes()])
    xys -= xys.min(axis=0)
    maxvalues = xys.max(axis=0)
    maxvalues[maxvalues == 0] = 1
    xys /= maxvalues
    xys[:, 0] *= asp_ratio

    plt.xlim([-(3 * node_size) * asp_ratio, (1 + (3 * node_size)) * asp_ratio])
    plt.ylim([-(3 * node_size), 1 + (3 * node_size)])
    plt.axis('off')

    try:
        edge_weights = nx.get_edge_attributes(G, 'weight')
    except KeyError:
        edge_weights = {}

    arrowdict = dict(ec='k', fc='k', length_includes_head=True, shape='full')
    for k, v in arrowopts.items():
        arrowdict[k] = v

    for edge in G.edges():
        startxy = xys[node_map[edge[0]], :].copy()
        endxy = xys[node_map[edge[1]], :].copy()

        arrowdict['lw'] = edge_weights.get(edge, 1.0) * edgescale

        headscale = node_size * 0.5
        has_reverse = (edge[1], edge[0]) in G.edges()
        if G.is_directed() and (not has_reverse or bidir_arrows):
            head_scale = node_size * 0.5
        else:
            head_scale = 0
        arrowdict['head_length'] = head_scale
        arrowdict['head_width'] = head_scale

        if edge[0] == edge[1]:
            loopoffset = np.sign(startxy - xys.mean(axis=0)) * node_size * 1.05
            cloop = plt.Circle(startxy + loopoffset,
                               radius=node_size * 0.65,
                               ec='k',
                               fill=False,
                               lw=arrowdict['lw'])
            plt.gca().add_artist(cloop)
            arrowloc = intersect_two_circles(startxy, node_size,
                                             startxy + loopoffset,
                                             node_size * 0.7)
            arrowlocstart = arrowloc + (arrowloc - startxy) * 1e-5
            plt.arrow(arrowlocstart[0], arrowlocstart[1],
                      arrowloc[0] - arrowlocstart[0],
                      arrowloc[1] - arrowlocstart[1], **arrowdict)

        else:
            angle = np.arctan2(endxy[1] - startxy[1], endxy[0] - startxy[0])
            offset = np.array([np.cos(angle), np.sin(angle)]) * node_size
            startxy += offset
            endxy -= offset

            if nx.is_directed(G) and has_reverse:
                midxy = (startxy + endxy) / 2.0
                plt.arrow(midxy[0], midxy[1], endxy[0] - midxy[0],
                          endxy[1] - midxy[1], **arrowdict)
                plt.arrow(midxy[0], midxy[1], startxy[0] - midxy[0],
                          startxy[1] - midxy[1], **arrowdict)
            else:
                carrowdict = arrowdict
                carrowdict = carrowdict.copy()

                plt.arrow(startxy[0], startxy[1], endxy[0] - startxy[0],
                          endxy[1] - startxy[1], **arrowdict)

    for ndx, xy in enumerate(xys):  # Plot nodes
        cnode = plt.Circle((xy[0], xy[1]),
                           radius=node_size,
                           ec='none',
                           color=cmap_helper.get_rgb(colors[ndx]),
                           **nodeopts)
        plt.gca().add_artist(cnode)
        if node_labels is not None:
            plt.text(xy[0],
                     xy[1],
                     node_labels[ndx],
                     ha='center',
                     va='center',
                     **labelopts)
    estaConnectado = algoritmos.isConnected(G)

    if estaConnectado:
        apl_coeficiente = metricas.APL(
            list(nx.all_pairs_shortest_path_length(G)), 1000000)
        cc = nx.average_clustering(G)
        with open('APL.txt', 'a') as f:
            f.write("%s\n" % apl_coeficiente)
        with open('CC.txt', 'a') as f:
            f.write("%s\n" % cc)
        with open("redes/" + str(contador) + ".txt", 'a') as f:
            f.write("[\n")
            for item in G.edges:
                f.write("%s,\n" % list(item))
            f.write("]\n")
        pos = nx.circular_layout(G, scale=0.5)
        plt.figure(3, figsize=(35, 35))
        labels = {}
        edgeswidth = []
        for i in range(100):
            labels[i] = i

        for i in range(200):
            edgeswidth.append(5)
        nx.draw_circular(G,
                         node_size=1000,
                         labels=labels,
                         width=edgeswidth,
                         arrowsize=10)
        plt.savefig("figuras/" + str(contador) + ".png")
        plt.clf()
Exemple #43
0
def generate_column_correlation_network(df,
                                        th=0.8,
                                        edge_labels_flag=True,
                                        layout="spring_layout"):

    G = nx.Graph()
    col_numerical = list(df.select_dtypes([np.number]).columns)
    comb2_col_numerical = list(itertools.combinations(
        col_numerical, 2))  # Make combinations from col_numerical

    # go over all combinations calculate correlation
    for rec in comb2_col_numerical:
        col1 = rec[0]
        col2 = rec[1]
        corr = df[col1].corr(df[col2], method='pearson')
        corr = round(corr, 2)
        if abs(corr) >= th:  # if correlation is high enoigh add edge to graph
            G.add_edge(col1, col2, weight=corr)

    num_nodes = G.number_of_nodes()
    num_edges = G.number_of_edges()
    if num_nodes <= 1 or num_edges == 0:
        print("netwotk has no nodes (or just 1) or edges")
        return

    # calculate communities
    if num_edges > 1:
        communities_generator = community.girvan_newman(G)
        top_level_communities = next(communities_generator)
        next_level_communities = next(communities_generator)

        display(Markdown("## Communites:"))
        node_to_cc_dict = dict()
        cc = sorted(map(sorted, next_level_communities))
        counter = 0
        if len(cc) == 0:
            print("netwotk has no communites")
            return

        for c in cc:
            counter += 1
            for n in list(c):
                node_to_cc_dict[n] = counter
            print(c)
            print("-------------------")

    # print communites and plot
    display(Markdown("## Network:"))
    print("number of nodes:", num_nodes)
    print("number of edges:", num_edges)
    plt.figure(figsize=(26, 10))
    if layout == "spring_layout":
        pos = nx.spring_layout(G, k=0.15, iterations=20, scale=2)
    elif layout == "planar_layout":
        pos = nx.planar_layout(G)
    elif layout == "circular_layout":
        pos = nx.circular_layout(G)
    else:
        print("problrm with choosing a layout")

    if num_edges > 1:
        com_values = [node_to_cc_dict[n] for n in G.nodes()]
        nx.draw_networkx(G,
                         pos,
                         cmap=plt.get_cmap('jet'),
                         node_color=com_values,
                         with_labels=True,
                         alpha=0.6,
                         font_size=14)
    else:
        nx.draw_networkx(G,
                         pos,
                         cmap=plt.get_cmap('jet'),
                         with_labels=True,
                         alpha=0.6,
                         font_size=16)
    if edge_labels_flag:
        edge_labels = nx.get_edge_attributes(G, 'weight')
        nx.draw_networkx_edge_labels(G,
                                     pos,
                                     edge_labels=edge_labels,
                                     alpha=0.8)
    plt.show()
Exemple #44
0
"Graph Theory - Find Shortest path using Dijkstra Algo"
import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
e = [('a', 'b', 3), ('b', 'c', 9), ('a', 'c', 5), ('c', 'd', 12),
     ('c', 'e', 12)]
G.add_weighted_edges_from(e)
nx.draw(G,
        pos=nx.circular_layout(G),
        nodecolor='r',
        edge_color='b',
        with_labels=True,
        with_edges=True)
nx.draw_networkx_edge_labels(G=G, pos=nx.circular_layout(G))
#print shortest path
print(nx.dijkstra_path(G, 'b', 'd'))
plt.show()
Exemple #45
0
import networkx as net
import matplotlib.pyplot as plt

# create graph
graph = net.DiGraph()

graph.add_edge('Univ', 'ProfA')
graph.add_edge('Univ', 'ProfB')
graph.add_edge('ProfA', 'StudentA')
graph.add_edge('StudentA', 'Univ')
graph.add_edge('ProfB', 'StudentB')
graph.add_edge('StudentB', 'ProfB')

show_graph = True
if show_graph:
    net.draw(graph, pos=net.circular_layout(graph), with_labels=True)
    plt.show()

C = 0.8


def similarity_dict(g, k):
    def sim(a, b):
        sum = 0
        if a == b:
            return 1
        for a_inc, _ in g.in_edges(a):
            for b_inc, _ in g.in_edges(b):
                s = r_prev.get((a_inc, b_inc), 0.)
                sum += s
        return C / (len(g.in_edges(a)) * len(g.in_edges(b))) * sum
Exemple #46
0
AdjL = sc.array(GenRdmAdjList(MaxN, C))
print(AdjL)
Sps = sc.unique(AdjL)  # Get species ids
print(Sps)

# Gnerate species body size data
SizRan = ([-10, 10]) # Use log10 scale
Sizs = sc.random.uniform(SizRan[0], SizRan[1], MaxN) # Randomly distributed node size
print(Sizs)

# Plot histogram of body size
p.hist(Sizs) # log10 scale 
p.hist(10 ** Sizs) # raw scale
p.close('all') # close all open plot objects

pos = nx.circular_layout(Sps) # Take species data and plot in circular layout

# Create a network graph object
G = nx.Graph() #

# Add nodes and links
G.add_nodes_from(Sps)
G.add_edges_from(tuple(AdjL)) # this function needs a tuple input

# Generate node sizes proportional to log body sizes
NodSizs= 1000 * (Sizs-min(Sizs))/(max(Sizs)-min(Sizs))

# Plots the graph and saves to pdf
f = p.figure()
nx.draw_networkx(G, pos, node_size = NodSizs)
f.savefig(r'../results/Food_network.pdf')
Exemple #47
0
def visualize(G: nx.Graph,
              remove_empty_nodes: bool = True,
              layout: str = "spring") -> go.Figure:
    """Generates an interactive plot of a voting network.

    adapted from source: https://plot.ly/python/network-graphs/ 
    :param G: A network as created with the "create_network()" function
    :type G: nx.Graph
    :param remove_empty_nodes: Whether to remove nodes that have no edges: i.e. MEPs that did not vote for any of the bills in the selection, defaults to True
    :param remove_empty_nodes: bool, optional
    :param layout: what layout algorithm should be used. Options are: 'circular', 'random', 'shell', 'spring', 'spectral'. , defaults to "spring"
    :param layout: str, optional
    :raises RuntimeError: If an layout option is given that doesnt exist.
    :return: A plotly figure object containing the plotted network.
    :rtype: go.Figure
    """

    global party_color_map

    if remove_empty_nodes:
        remove_loose_nodes(G)

    #Get Node Positions
    # pos=nx.get_node_attributes(G,'pos')
    print(f"calculating positions with {layout} layout...", flush=True)
    if layout == 'circular':
        pos = nx.circular_layout(G)
    elif layout == 'random':
        pos = nx.random_layout(G)
    elif layout == 'shell':
        pos = nx.shell_layout(G)
    elif layout == 'spring':
        pos = nx.spring_layout(G, iterations=100)
    elif layout == 'spectral':
        pos = nx.spectral_layout(G)
    else:
        raise RuntimeError(f"Unknown layout option: {layout}")
    # print(pos)
    dmin = 1
    ncenter = 0
    for n in pos:
        G.nodes[n]['pos'] = pos[n]
        # pp.pprint(G.nodes[n])

        x, y = pos[n]

        d = (x - 0.5)**2 + (y - 0.5)**2
        if d < dmin:
            ncenter = n
            dmin = d

    p = nx.single_source_shortest_path_length(G, ncenter)

    # Create Edges
    print(f"create {len(G.edges())} edges ...", flush=True)
    edge_trace = go.Scatter(x=[],
                            y=[],
                            line=dict(width=0.5, color='black'),
                            hoverinfo='none',
                            mode='lines')

    for edge in tqdm.tqdm(G.edges()):
        x0, y0 = G.node[edge[0]]['pos']
        x1, y1 = G.node[edge[1]]['pos']
        edge_trace['x'] += tuple([x0, x1, None])
        edge_trace['y'] += tuple([y0, y1, None])

    # Create Nodes
    print("create nodes ...", flush=True)

    node_trace = go.Scatter(x=[],
                            y=[],
                            text=[],
                            mode='markers',
                            hoverinfo='text',
                            marker=dict(color=[], size=[], line=dict(width=2)))

    for node in tqdm.tqdm(G.nodes()):
        x, y = G.node[node]['pos']
        node_trace['x'] += tuple([x])
        node_trace['y'] += tuple([y])

    # Color Node Points
    print("Color Node Points ...", flush=True)

    for i, (key, node) in tqdm.tqdm(enumerate(G.nodes().items())):

        if node.get('type', False) == 'division':
            if node['aye_count'] - node['noes_count'] > 0:
                node_trace['marker']['color'] += tuple(['green'])
            else:
                node_trace['marker']['color'] += tuple(['red'])
            node_info = f"Vote: {node['title']} - Ayes count: {node['aye_count']} - Noes count: {node['noes_count']}"
            node_trace['text'] += tuple([node_info])
            node_trace['marker']['size'] += tuple([15])
        else:
            node_trace['marker']['color'] += tuple(
                [party_color_map[node['party']]])
            node_info = f"{node['name']} - {node['party']} - {node['constituency']}"
            node_trace['text'] += tuple([node_info])
            node_trace['marker']['size'] += tuple([10])

    print("create network graph ...", flush=True)

    fig = go.Figure(data=[edge_trace, node_trace],
                    layout=go.Layout(
                        title='Network graph for votes at uk parliament.',
                        titlefont=dict(size=16),
                        showlegend=False,
                        hovermode='closest',
                        margin=dict(b=20, l=5, r=5, t=40),
                        annotations=[
                            dict(text="test",
                                 showarrow=False,
                                 xref="paper",
                                 yref="paper",
                                 x=0.005,
                                 y=-0.002)
                        ],
                        xaxis=dict(showgrid=False,
                                   zeroline=False,
                                   showticklabels=False),
                        yaxis=dict(showgrid=False,
                                   zeroline=False,
                                   showticklabels=False)))
    print("returning figure")
    return fig
Exemple #48
0
    def DrawButtonSingleCSV_clicked(self):

        #G = nx.DiGraph()
        usbiptocompare = []
        usbidtocompare = []
        usbnametocompare = []
        usbcnamecompare = []
        usbidcheck = []
        usbipcheck = []
        usbnamecheck = []
        usbcnamecheck = []

        #dates
        usbdatecheck = []
        usbtimecheck = []
        usbfirstplugdatecompare = []
        usbfirstplugtimecompare = []

        a = 0
        b = 0
        c = 0

        if self.projectopen and self.drawcsv == False:
            singlecsvfile = self.classdatafilecsv
        else:
            singlecsvfile = QtGui.QFileDialog.getOpenFileName(
                self, 'Open single CSV File to plot')

        with open(singlecsvfile) as f:
            first_line = f.readline()

        self.drawcsv = True

        datacsvfile = []
        with open(singlecsvfile) as f:
            for row in csv.DictReader(f):
                datacsvfile.append(row)

        self.listWidgetRemoteOutput.addItem(
            "Processing data from CSV file ... please wait ...")
        self.listWidgetRemoteOutput.addItem(
            "Click on usb picture to proceed to the next plot")

        QtGui.QApplication.processEvents()

        csvhdheader = "computer_name,computer_ip,usbdevice_name,usbdevice_id,usb_firstplugdate,usb_firstplugtime"

        if first_line.rstrip() != csvhdheader:
            msg = QtGui.QMessageBox()
            msg.setText("Error, file is not HD CSV")
            ret = msg.exec()

        datosjsondump = json.dumps(datacsvfile)
        datosjsonraw = json.loads(datosjsondump)

        datosjson = sorted(datosjsonraw,
                           key=lambda k: datetime.strptime(
                               k['usb_firstplugdate'], "%Y/%m/%d"),
                           reverse=False)

        for item in datosjson:
            usbidtocompare.append(item.get("usbdevice_id"))
            usbiptocompare.append(item.get("computer_ip"))
            usbnametocompare.append(item.get("usbdevice_name"))
            usbcnamecompare.append(item.get("computer_name"))
            usbfirstplugdatecompare.append(item.get("usb_firstplugdate"))
            usbfirstplugtimecompare.append(item.get("usb_firstplugtime"))

        # Remove duplicates
        for i in usbidtocompare:
            if i not in usbidcheck:
                usbidcheck.append(i)
                usbipcheck.append(usbiptocompare[b])
                usbnamecheck.append(usbnametocompare[b])
                usbcnamecheck.append(usbcnamecompare[b])
                #dates
                usbdatecheck.append(usbfirstplugdatecompare[b])
                usbtimecheck.append(usbfirstplugtimecompare[b])

                b = b + 1
            else:
                b = b + 1

        d = 0
        n = 0

        for idusb in usbidcheck:

            G = nx.DiGraph()
            testArrow = matplotlib.patches.ArrowStyle.Fancy(head_length=.4,
                                                            head_width=.4,
                                                            tail_width=.1)
            pathrepo = os.path.dirname(
                os.path.realpath(__file__)) + "\\reports\\"
            timestr = time.strftime("%Y%m%d-%H%M%S")

            preusbipcomp = usbipcheck[d]
            preusbcomputername = usbcnamecheck[d]
            #dates
            preusbdate = usbdatecheck[d]
            preusbtime = usbtimecheck[d]

            # PDF
            pdf = FPDF()
            pdf.add_page()
            pdf.set_font('Arial', 'B', 20)
            pdf.cell(110, 10, 'Hidden Networks USB Report', 1, 1)
            pdf.set_font('Arial', 'B', 15)
            pdf.cell(30, 10, 'USB Name: ' + usbnamecheck[c], 0, 1)
            pdf.cell(30, 10, 'USB id: ' + idusb, 0, 1)
            pdf.cell(30, 15, 'Tracking: ', 0, 1)

            for item in datosjson:
                usbidcomp = item.get("usbdevice_id")
                usbipcomp = item.get("computer_ip")
                computername = item.get("computer_name")
                #date
                usbdate = item.get("usb_firstplugdate")
                usbtime = item.get("usb_firstplugtime")

                if usbidcomp == idusb:
                    #PDF
                    pdf.set_font('Arial', '', 8)
                    pdf.cell(0, 5, 'Connected to: ' + computername, 0, 2)
                    pdf.cell(0, 5, 'IP: ' + usbipcomp, 0, 2)
                    pdf.cell(0, 5, 'Date: ' + usbdate + ' Time: ' + usbtime, 0,
                             2)
                    pdf.cell(0, 10, '--->', 0, 2)

                    listaprueba = [
                        preusbipcomp, preusbcomputername, preusbdate,
                        preusbtime
                    ]
                    nuevonodo = '\n'.join(listaprueba)

                    listaprueba2 = [usbipcomp, computername, usbdate, usbtime]
                    nuevonodo2 = '\n'.join(listaprueba2)
                    G.add_edge(nuevonodo, nuevonodo2)

                    preusbipcomp = usbipcomp
                    preusbcomputername = computername
                    preusbdate = usbdate
                    preusbtime = usbtime
            d = d + 1

            self.listWidgetRemoteOutput.addItem(usbnamecheck[c])
            QtGui.QApplication.processEvents()

            # Graph plot
            #pos = nx.shell_layout(G)
            pos = nx.circular_layout(G, center=(0, 0))

            #Nodes / computers
            num_nodes = G.number_of_nodes()
            list_nodes = list(G.nodes)

            color_map = []
            a = 0
            # Insolated or connected (IP)
            for node in G:
                if list_nodes[a][0] == '\n':
                    color_map.append('lightsalmon')
                else:
                    color_map.append('skyblue')
                a = a + 1

            options = {
                'font_size': '7',
                'node_shape': 'o',
                'node_size': 3000,
                'width': 2,
                'arrowstyle': testArrow,
                'arrowsize': 12,
            }

            nx.draw(G,
                    pos,
                    alpha=0.7,
                    node_color=color_map,
                    edge_color='gray',
                    arrows=True,
                    with_labels=True,
                    **options)
            plt.axis("off")
            plt.gcf().canvas.set_window_title(usbnamecheck[c])
            plt.savefig(pathrepo + idusb + timestr + '.png')

            #pdf.add_page()
            pdf.image(pathrepo + idusb + timestr + '.png', 80, 50, 120)

            #plt.show(nx)

            # Shows  image in new window as subplot
            localrunpath = os.path.dirname(os.path.realpath(__file__))
            print(localrunpath)
            path = localrunpath + "\\images\\{0}".format(usbnamecheck[c])

            if not os.path.exists(path):
                os.makedirs(path)

            bbid_run = "bbid.py -s \"{0}\" -o \"{1}\" --limit 3".format(
                usbnamecheck[c], path)

            try:
                os.system(bbid_run)
                print("Ejecutando ...")
                #subprocess.call([bbid_run])
                usb_image_path = os.listdir(path)[0]
                usb_image_full_path = path + "\\" + usb_image_path
            except:
                print("No Internet ERROR ...")
                usb_image_full_path = localrunpath + "\\" + "notfound.jpg"

            fig, (ax) = plt.subplots()
            #fig.canvas.set_window_title(usbnamecheck[c])

            ax.imshow(plt.imread(usb_image_full_path, ))

            ax.text(0.95,
                    0.01,
                    idusb,
                    verticalalignment='bottom',
                    horizontalalignment='right',
                    transform=ax.transAxes,
                    color='gray',
                    fontsize=15)

            plt.axis("off")
            n = n + 1

            win = plt.gcf().canvas.manager.window
            win.setWindowFlags(win.windowFlags()
                               | QtCore.Qt.CustomizeWindowHint)
            win.setWindowFlags(win.windowFlags()
                               & ~QtCore.Qt.WindowCloseButtonHint)

            # PDF
            pdf.image(usb_image_full_path, 90, 150, 100)

            # Save PDF Report file
            pdf.output(pathrepo + idusb + timestr + '.pdf', 'F')

            plt.show()
            plt.waitforbuttonpress()
            plt.close('all')

            c = c + 1

        self.listWidgetRemoteOutput.addItem("Finished!")
        QtGui.QApplication.processEvents()
plt.xticks(FontProperties = font, size = 5)
plt.ylabel("degree")
plt.show()

plt.figure(figsize = (12, 12))
# 生成社交网络图
G = nx.Graph()
# 添加边
for ii in Red_df2.index:
    G.add_edge(Red_df2.First[ii], Red_df2.Second[ii], weight = Red_df2.weight[ii])
# 定义两种边
elarge = [(u, v) for (u, v, d) in G.edges(data = True) if d['weight'] > 0.3]
emidle = [(u, v) for (u, v, d) in G.edges(data = True) if (d['weight'] > 0.2) & (d['weight'] <= 0.3)]
esmall = [(u, v) for (u, v, d) in G.edges(data = True) if d['weight'] <= 0.2]
# 图的布局
pos = nx.circular_layout(G) # positions for all nodes
# nodes 根据节点的入度和出度来设置节点的大小
nx.draw_networkx_nodes(G, pos, alpha = 0.6, node_size = 20 + Gdegree.degree * 15)
# edges
nx.draw_networkx_edges(G, pos, edgelist = elarge,
                      width = 2, alpha = 0.9, edge_color = 'g')
nx.draw_networkx_edges(G, pos, edgelist = emidle,
                      width = 1.5, alpha = 0.6, edge_color = 'y')
nx.draw_networkx_edges(G, pos, edgelist = esmall,
                      width = 1, alpha = 0.3, edge_color = 'b', style = 'dashed')
# labels
nx.draw_networkx_labels(G, pos, font_size = 10) # font_size = 10, 即设置图中字体的大小
plt.axis('off')
plt.title("《红楼梦》社交网络")
plt.show()
Exemple #50
0
C = 0.75

AdjL = sc.array(GenRdmAdjList(MaxN, C))  ## make adjecency list
AdjL
Sps = sc.unique(AdjL)  # get species ids

SizRan = ([-10, 10])  # use log10 scale
Sizs = sc.random.uniform(SizRan[0], SizRan[1], MaxN)
Sizs
###plotting###

p.hist(Sizs)
# p.show()
p.hist(10**Sizs)  ### plot raw scale
# p.show()
p.close("all")  # close all open plot objects

pos = nx.circular_layout(Sps)

G = nx.Graph()

G.add_nodes_from(Sps)
G.add_edges_from(tuple(AdjL))

NodSizs = 1000 * (Sizs - min(Sizs)) / (max(Sizs) - min(Sizs))

f = p.figure()
nx.draw_networkx(G, pos, node_size=NodSizs)
# p.show()
f.savefig("../Results/DrawFW.pdf")
Exemple #51
0
def generateAdjacencyNonIntersect(overlaps, labels):
    G = nx.DiGraph()

    for x in labels:
        for t in range(0, len(overlaps) - 1):
            if x in overlaps[t] and x not in overlaps[t + 1]:
                for nextbin in range(t + 1, len(overlaps) - 1):
                    if x not in overlaps[nextbin]:
                        ys = [
                            y for y in overlaps[nextbin]
                            if y not in overlaps[t]
                        ]
                        if ys:
                            node_x = Node(x)
                            if not G.has_node(node_x):
                                G.add_node(node_x)

                            node_y = Node(ys[0])
                            weights = [
                                G[node_x][Node(y)]['weight'] for y in ys
                                if G.has_node(Node(y))
                                and G.has_edge(node_x, Node(y))
                            ]
                            if weights:
                                y_index = np.argmax(np.array(weights))
                                node_y = Node(ys[y_index])

                            if not G.has_node(node_y):
                                G.add_node(node_y)

                            if not G.has_edge(node_x, node_y):
                                G.add_edge(node_x, node_y, weight=1.0)
                            else:
                                G[node_x][node_y]['weight'] = G[node_x][
                                    node_y]['weight'] + 1.0

                            break

    bad = [(u, v) for (u, v, w) in G.edges(data='weight') if w <= 1]

    G.remove_edges_from(bad)

    more_bad = []

    for (u, v) in G.edges():
        if not G.has_edge(v, u):
            more_bad.append((u, v))

    G.remove_edges_from(more_bad)

    outdeg = G.out_degree()
    indeg = G.in_degree()
    to_remove = [n for n in G.nodes() if outdeg[n] == 0 and indeg[n] == 0]
    G.remove_nodes_from(to_remove)

    labels = nx.get_edge_attributes(G, 'weight')
    pos = nx.circular_layout(G)
    nx.draw(G, pos)
    nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, label_pos=0.8)
    nx.draw_networkx_labels(G, pos)
    plt.show()
Exemple #52
0
def wl_fig_freq(main, tokens_freq_files, settings, label_x):
    files = main.wl_files.get_selected_files()
    files += [{'name': main.tr('Total')}]

    if settings['rank_min_no_limit']:
        rank_min = 1
    else:
        rank_min = settings['rank_min']

    if settings['rank_max_no_limit']:
        rank_max = None
    else:
        rank_max = settings['rank_max']

    # Line Chart
    if settings['graph_type'] == main.tr('Line Chart'):
        tokens_freq_files = wl_sorting.sorted_tokens_freq_files(
            tokens_freq_files)

        total_freqs = numpy.array(list(zip(*tokens_freq_files))[1]).sum(axis=0)
        total_freq = sum(total_freqs)

        tokens = [item[0] for item in tokens_freq_files[rank_min - 1:rank_max]]
        freqs = [item[1] for item in tokens_freq_files if item[0] in tokens]

        if settings['use_pct']:
            if settings['use_cumulative']:
                matplotlib.pyplot.ylabel(
                    main.tr('Cumulative Percentage Frequency'))
            else:
                matplotlib.pyplot.ylabel(main.tr('Percentage Frequency'))
        else:
            if settings['use_cumulative']:
                matplotlib.pyplot.ylabel(main.tr('Cumulative Frequency'))
            else:
                matplotlib.pyplot.ylabel(main.tr('Frequency'))

        if settings['use_cumulative']:
            for i, freq_files in enumerate(freqs):
                if i >= 1:
                    freqs[i] = [
                        freq_cumulative + freq
                        for freq_cumulative, freq in zip(
                            freqs[i - 1], freq_files)
                    ]

        if settings['use_pct']:
            for i, file in enumerate(files):
                matplotlib.pyplot.plot([
                    freq_files[i] / total_freqs[i] * 100
                    for freq_files in freqs
                ],
                                       label=file['name'])
        else:
            for i, file in enumerate(files):
                matplotlib.pyplot.plot([freq_files[i] for freq_files in freqs],
                                       label=file['name'])

        matplotlib.pyplot.xlabel(label_x)
        matplotlib.pyplot.xticks(
            range(len(tokens)),
            labels=tokens,
            fontproperties=main.settings_custom['figs']['line_chart']['font'],
            rotation=90)

        matplotlib.pyplot.grid(True)
        matplotlib.pyplot.legend()
    # Word Cloud
    elif settings['graph_type'] == main.tr('Word Cloud'):
        if rank_max == None:
            max_words = len(tokens_freq_files) - rank_min + 1
        else:
            max_words = rank_max - rank_min + 1

        word_cloud = wordcloud.WordCloud(
            width=QDesktopWidget().width(),
            height=QDesktopWidget().height(),
            background_color=main.settings_custom['figs']['word_cloud']
            ['bg_color'],
            max_words=max_words)

        for i, file in enumerate(files):
            if file['name'] == settings['use_file']:
                tokens_freq_files = wl_sorting.sorted_tokens_freq_file(
                    tokens_freq_files, i)

                tokens_freq_file = {
                    token: freqs[i]
                    for token, freqs in tokens_freq_files[rank_min -
                                                          1:rank_max]
                }

                break

        # Fix zero frequencies
        for token, freq in tokens_freq_file.items():
            if freq == 0:
                tokens_freq_file[token] += 0.000000000000001

        word_cloud.generate_from_frequencies(tokens_freq_file)

        matplotlib.pyplot.imshow(word_cloud, interpolation='bilinear')
        matplotlib.pyplot.axis('off')
    # Network Graph
    elif settings['graph_type'] == main.tr('Network Graph'):
        for i, file in enumerate(files):
            if file['name'] == settings['use_file']:
                tokens_freq_files = wl_sorting.sorted_tokens_freq_file(
                    tokens_freq_files, i)

                tokens_freq_file = {
                    token: freqs[i]
                    for token, freqs in tokens_freq_files[rank_min -
                                                          1:rank_max]
                }

                break

        graph = networkx.MultiDiGraph()
        graph.add_edges_from(tokens_freq_file)

        if main.settings_custom['figs']['network_graph']['layout'] == main.tr(
                'Circular'):
            layout = networkx.circular_layout(graph)
        elif main.settings_custom['figs']['network_graph'][
                'layout'] == main.tr('Kamada-Kawai'):
            layout = networkx.kamada_kawai_layout(graph)
        elif main.settings_custom['figs']['network_graph'][
                'layout'] == main.tr('Planar'):
            layout = networkx.planar_layout(graph)
        elif main.settings_custom['figs']['network_graph'][
                'layout'] == main.tr('Random'):
            layout = networkx.random_layout(graph)
        elif main.settings_custom['figs']['network_graph'][
                'layout'] == main.tr('Shell'):
            layout = networkx.shell_layout(graph)
        elif main.settings_custom['figs']['network_graph'][
                'layout'] == main.tr('Spring'):
            layout = networkx.spring_layout(graph)
        elif main.settings_custom['figs']['network_graph'][
                'layout'] == main.tr('Spectral'):
            layout = networkx.spectral_layout(graph)

        networkx.draw_networkx_nodes(graph,
                                     pos=layout,
                                     node_size=800,
                                     node_color='#FFFFFF',
                                     alpha=0.4)
        networkx.draw_networkx_edges(graph,
                                     pos=layout,
                                     edgelist=tokens_freq_file,
                                     edge_color=main.settings_custom['figs']
                                     ['network_graph']['edge_color'],
                                     width=wl_misc.normalize_nums(
                                         tokens_freq_file.values(),
                                         normalized_min=1,
                                         normalized_max=5))
        networkx.draw_networkx_labels(graph,
                                      pos=layout,
                                      font_family=main.settings_custom['figs']
                                      ['network_graph']['node_font'],
                                      font_size=main.settings_custom['figs']
                                      ['network_graph']['node_font_size'])
        networkx.draw_networkx_edge_labels(
            graph,
            pos=layout,
            edge_labels=tokens_freq_file,
            font_family=main.settings_custom['figs']['network_graph']
            ['edge_font'],
            font_size=main.settings_custom['figs']['network_graph']
            ['edge_font_size'],
            label_pos=0.2)
Exemple #53
0
import networkx as nx
import matplotlib.pyplot as plt


#Creamos una instancia de un grafo
G = nx.DiGraph()

#Agregamos las aristas en el nodo (junto con los nodos)
G.add_edge(1,2)
G.add_edge(1,1)
G.add_edge(1,4)
G.add_edge(3,4)
G.add_edge(4,5)

#Dibujamos el grafo
nx.draw(G, pos=nx.circular_layout(G), node_color=['b','r','r','r','r'], edge_color='b', with_labels=True)
#Mostramos el grafo en pantalla
plt.show()
Exemple #54
0
    def draw(self,
             method='',
             h_i_shock=None,
             alpha=None,
             max_iter=100,
             is_savefig=False,
             font_size=5,
             node_color='b',
             seed=None,
             **kwargs):
        """draw financial network.

        Parameters:
        ---
        `method`: <str>.
            the optional, the color of nodes map to the important level of bank. i.e. {'dr','nldr','dc',...}. Default = 'dr'.
        
        `h_i_shock`: <np.ndarray>. 
            the initial shock. see `tt.creating_initial_shock()`.

        `alpha`: <float>.
            optional, the parameter of Non-Linear DebtRank. Default = 0.

        `t_max`: <int>. 
            the max number of iteration. Default = 100.

        `is_savefig`: <False>. 
            optional, if True, it will be saved to the current work environment. otherwise, plt.show().

        `font_size`: <int>. 
            the size of the labels of nodes. Default = 5.  

        `node_color`: <str or RGB>.
            the color of nodes. if method is not empty, the colors reflect the importance level.  

        `**kwargs`: 
            customize your figure, see detail in networkx.draw.
        """
        # initial setting
        title = 'The interbank network' + '(%s)' % self._data._label_year
        method = str(method)
        debtrank_alias = {'dr': 'debtrank', 'nldr': 'nonlinear debtrank'}
        importance_alias = {'lp': 'loss_percentile'}
        centrality_alias = {
            'idc': 'in-degree centrality',
            'odc': 'out-degree centrality',
            'dc': 'degree centrality',
            'bc': 'betweenness centrality',
            'cc': 'closeness(in) centrality',
            'occ': 'out-closeness centrality',
            'ec': 'eigenvector(in) centrality',
            'oec': 'out-eigenvector centrality',
            'kc': 'katz centrality',
        }
        # method
        if method in debtrank_alias:
            if h_i_shock is None:
                try:
                    self._h_i_shock = self._data.h_i_shock
                except:
                    raise Exception(
                        "ERROR: the parameter 'h_i_shock' cannot be empty.",
                        h_i_shock)
            else:
                self._h_i_shock = h_i_shock

            assert isinstance(
                self._h_i_shock, (list, np.ndarray)
            ), "ERROR: the 'h_i_shock' you provided should be a list or np.ndarray."
            assert len(
                self._h_i_shock
            ) == self._data._N, "ERROR: the length of 'h_i_shock' you provided is not equal to data."

            # the node labels
            self._node_labels = {}
            for i, j in zip(self._nodes, self._h_i_shock):
                assert j >= 0, "ERROR: the value of h_i_shock should in [0,1]"
                if j == 0.0:
                    self._node_labels[i] = i
                else:
                    self._node_labels[i] = i + r"$\bigstar$"
            # the method of debtrant
            if method == 'dr':
                # the legend labels
                self._legend_labels = [
                    'debtrank < 25%', 'debtrank > 25%', 'debtrank > 50%',
                    'debtrank > 75%'
                ]
                # the color of nodes
                self._nodes_color = self._run_centrality(
                    method='dr', h_i_shock=self._h_i_shock,
                    t_max=max_iter)['node color']
            elif method == 'nldr':
                if alpha is None:
                    alpha = 0
                    print(
                        "Warning: the paramater of 'alpha' is essential! Default = %.2f"
                        % alpha)
                # rename figure title
                title = 'The interbank network, ' + r'$\alpha = %.2f$' % alpha + ' (%s)' % self._data._label_year
                # the legend labels
                self._legend_labels = [
                    'nonlinear debtrank < 25%', 'nonlinear debtrank > 25%',
                    'nonlinear debtrank > 50%', 'nonlinear debtrank > 75%'
                ]
                # the color of nodes
                self._nodes_color = self._run_centrality(
                    method='nldr',
                    h_i_shock=self._h_i_shock,
                    alpha=alpha,
                    t_max=max_iter)['node color']
            else:
                pass  # TODO

            _legend_elements = [
                Line2D([0], [0],
                       marker='o',
                       color="#6495ED",
                       markersize=3.5,
                       label=self._legend_labels[0]),
                Line2D([0], [0],
                       marker='o',
                       color="#EEEE00",
                       markersize=3.5,
                       label=self._legend_labels[1]),
                Line2D([0], [0],
                       marker='o',
                       color="#EE9A00",
                       markersize=3.5,
                       label=self._legend_labels[2]),
                Line2D([0], [0],
                       marker='o',
                       color="#EE0000",
                       markersize=3.5,
                       label=self._legend_labels[3]),
                Line2D([0], [0],
                       marker='*',
                       markerfacecolor="#000000",
                       color='w',
                       markersize=6.5,
                       label='the initial shock')
            ]
            _ncol = 5
        elif method in importance_alias:
            # title
            title = r'$x_{shock} = %.2f$' % kwargs[
                'x_shock'] + ', t = %d' % kwargs[
                    't'] + ' (%s)' % self._data._label_year
            # the node labels
            self._node_labels = dict(zip(self._nodes, self._nodes))
            # 'lp'
            self._legend_labels = [
                'importantance level < 25%', 'importantance level > 25 %',
                'importantance level > 50%', 'importantance level > 75%'
            ]
            # the color of nodes
            self._nodes_color = self._run_centrality(
                method='lp', t=kwargs['t'],
                x_shock=kwargs['x_shock'])['node color']

            _legend_elements = [
                Line2D([0], [0],
                       marker='o',
                       color="#6495ED",
                       markersize=3.5,
                       label=self._legend_labels[0]),
                Line2D([0], [0],
                       marker='o',
                       color="#EEEE00",
                       markersize=3.5,
                       label=self._legend_labels[1]),
                Line2D([0], [0],
                       marker='o',
                       color="#EE9A00",
                       markersize=3.5,
                       label=self._legend_labels[2]),
                Line2D([0], [0],
                       marker='o',
                       color="#EE0000",
                       markersize=3.5,
                       label=self._legend_labels[3])
            ]
            _ncol = 4

        elif method in centrality_alias:
            # the node labels
            self._node_labels = dict(zip(self._nodes, self._nodes))
            # 'dc'
            if method == 'idc':
                # dict: dictionary. see detail in centrality.
                # the legend labels
                self._legend_labels = [
                    'in-degree centrality < 25%', 'in-degree centrality > 25%',
                    'in-degree centrality > 50%', 'in-degree centrality > 75%'
                ]
                # the color of nodes
                self._in_degree_centrality = ct.in_degree_centrality(self._FN)
                self._nodes_color = self._run_centrality(
                    method='idc',
                    centrality=self._in_degree_centrality)['node color']
            elif method == 'odc':
                # dict: dictionary. see detail in centrality.
                # the legend labels
                self._legend_labels = [
                    'out-degree centrality < 25%',
                    'out-degree centrality > 25%',
                    'out-degree centrality > 50%',
                    'out-degree centrality > 75%'
                ]
                # the color of nodes
                self._out_degree_centrality = ct.out_degree_centrality(
                    self._FN)
                self._nodes_color = self._run_centrality(
                    method='odc',
                    centrality=self._out_degree_centrality)['node color']
            elif method == 'dc':
                # dict: dictionary. see detail in centrality.
                # the legend labels
                self._legend_labels = [
                    'degree centrality < 25%', 'degree centrality > 25%',
                    'degree centrality > 50%', 'degree centrality > 75%'
                ]
                # the color of nodes
                self._degree_centrality = ct.degree_centrality(self._FN)
                self._nodes_color = self._run_centrality(
                    method='dc',
                    centrality=self._degree_centrality)['node color']
            elif method == 'bc':
                # dict: dictionary. see detail in centrality.
                # the legend labels
                self._legend_labels = [
                    'betweenness centrality < 25%',
                    'betweenness centrality > 25%',
                    'betweenness centrality > 50%',
                    'betweenness centrality > 75%'
                ]
                # the color of nodes
                self._betweenness_centrality = ct.betweenness_centrality(
                    self._FN, weight='weight', seed=seed)
                self._nodes_color = self._run_centrality(
                    method='bc',
                    centrality=self._betweenness_centrality)['node color']
            elif method == 'cc' or method == 'icc':
                # dict: dictionary. see detail in centrality.
                # the legend labels
                self._legend_labels = [
                    'in-closeness centrality < 25%',
                    'in-closeness centrality > 25%',
                    'in-closeness centrality > 50%',
                    'in-closeness centrality > 75%'
                ]
                # the color of nodes
                self._in_closeness_centrality = ct.closeness_centrality(
                    self._FN, distance='weight')
                self._nodes_color = self._run_centrality(
                    method='cc',
                    centrality=self._in_closeness_centrality)['node color']
            elif method == 'occ':
                # dict: dictionary. see detail in centrality.
                # the legend labels
                self._legend_labels = [
                    'out-closeness centrality < 25%',
                    'out-closeness centrality > 25%',
                    'out-closeness centrality > 50%',
                    'out-closeness centrality > 75%'
                ]
                # the color of nodes
                self._out_closeness_centrality = ct.closeness_centrality(
                    self._FN.reverse(), distance='weight')
                self._nodes_color = self._run_centrality(
                    method='occ',
                    centrality=self._out_closeness_centrality)['node color']
            elif method == 'ec' or method == 'iec':
                # dict: dictionary. see detail in centrality.
                # the legend labels
                self._legend_labels = [
                    'in-eigenvector centrality < 25%',
                    'in-eigenvector centrality > 25%',
                    'in-eigenvector centrality > 50%',
                    'in-eigenvector centrality > 75%'
                ]
                # the color of nodes
                self._in_eigenvector_centrality = ct.eigenvector_centrality(
                    self._FN, max_iter=max_iter, weight='weight')
                self._nodes_color = self._run_centrality(
                    method='ec',
                    centrality=self._in_eigenvector_centrality)['node color']
            elif method == 'oec':
                # dict: dictionary. see detail in centrality.
                # the legend labels
                self._legend_labels = [
                    'out-eigenvector centrality < 25%',
                    'out-eigenvector centrality > 25%',
                    'out-eigenvector centrality > 50%',
                    'out-eigenvector centrality > 75%'
                ]
                # the color of nodes
                self._out_eigenvector_centrality = ct.eigenvector_centrality(
                    self._FN.reverse(), max_iter=max_iter, weight='weight')
                self._nodes_color = self._run_centrality(
                    method='oec',
                    centrality=self._out_eigenvector_centrality)['node color']
            elif method == 'kc':  # bug
                # dict: dictionary. see detail in centrality.
                # the legend labels
                self._legend_labels = [
                    'katz centrality < 25%', 'katz centrality > 25%',
                    'katz centrality > 50%', 'katz centrality > 75%'
                ]
                # the color of nodes
                phi, _ = np.linalg.eig(self._Ad_ij)
                self._katz_centrality = ct.katz_centrality(
                    self._FN, alpha=1 / np.max(phi) - 0.01, weight='weight')
                self._nodes_color = self._run_centrality(
                    method='kc',
                    centrality=self._katz_centrality)['node color']
            else:
                pass  # TODO

            _legend_elements = [
                Line2D([0], [0],
                       marker='o',
                       color="#6495ED",
                       markersize=3.5,
                       label=self._legend_labels[0]),
                Line2D([0], [0],
                       marker='o',
                       color="#EEEE00",
                       markersize=3.5,
                       label=self._legend_labels[1]),
                Line2D([0], [0],
                       marker='o',
                       color="#EE9A00",
                       markersize=3.5,
                       label=self._legend_labels[2]),
                Line2D([0], [0],
                       marker='o',
                       color="#EE0000",
                       markersize=3.5,
                       label=self._legend_labels[3])
            ]
            _ncol = 4

        else:
            # the node labels
            self._node_labels = dict(zip(self._nodes, self._nodes))
            self._nodes_color = node_color  # "#00BFFF"
            print("Warning: the color of nodes have no special meaning.")

        # draw
        draw_default = {
            'node_size': self._node_assets,
            'node_color': self._nodes_color,
            'edge_color': self._edge_color,
            'edge_cmap': plt.cm.binary,
            'labels': self._node_labels,
            'width': 0.8,
            'style': 'solid',
            'with_labels': True
        }

        # customize your nx.draw
        if 'node_size' in kwargs:
            draw_default['node_size'] = kwargs['node_size']
        if 'node_color' in kwargs:
            draw_default['node_color'] = kwargs['node_color']
        if 'edge_cmap' in kwargs:
            draw_default['edge_cmap'] = kwargs['edge_cmap']
        if 'labels' in kwargs:
            draw_default['labels'] = kwargs['labels']
        if 'style' in kwargs:
            draw_default['style'] = kwargs['style']
        if 'with_labels' in kwargs:
            draw_default['with_labels'] = kwargs['with_labels']

        draw_kwargs = draw_default

        plt.rcParams['figure.dpi'] = 160
        plt.rcParams['savefig.dpi'] = 400
        plt.title(title, fontsize=font_size + 2)
        nx.draw(self._FN,
                pos=nx.circular_layout(self._FN),
                font_size=font_size,
                **draw_kwargs)
        if method:
            plt.legend(handles=_legend_elements,
                       ncol=_ncol,
                       fontsize=font_size - 1,
                       loc='lower center',
                       frameon=False)

        if is_savefig:
            net = "interbanknetwork"
            date = parse(self._data._label_year).strftime("%Y%m%d")
            plt.savefig(net + date + '.png', format='png', dpi=400)
            print("save to '%s'" % os.getcwd() + ' and named as %s' %
                  (net + date) + '.png')
        else:
            plt.show()
Exemple #55
0
import numpy.linalg as LA
import numpy as np
from generate import er_multi

sizes = [30,32,41,39]

probs = [[.5,.05,.05,.05],[.05,.5,.05,.05],[.05,.05,.5,.05],[.05,.05,.05,.5]]

G = nx.stochastic_block_model(sizes, probs)

n = 100
k=5
p=.15
G = er_multi(n,k,p)

pos = nx.circular_layout(nx.erdos_renyi_graph(n,p))

#pos = {x:(pos[x[0]][0],pos[x[0]][1],x[1]) for x in G.nodes()}

pos = {x:pos[x[0]] for x in G.nodes()}

LM = (nx.laplacian_matrix(G)).todense()
#LM = (nx.normalized_laplacian_matrix(G)).todense()

LMva, LMve = LA.eigh(LM)

##plt.figure()
#plt.plot(np.sort(LMva),'*')
#plt.show()

#k=5
Exemple #56
0
def plot_logfile_check(logfile, state_names='original'):
    # Run the check
    check_res = BeWatch.db.check_logfile(logfile)

    # State numbering
    if state_names == 'original':
        state_num2names = BeWatch.db.get_state_num2names()  
    elif state_names == 'debug':
        state_num2names = BeWatch.db.get_state_num2names_dbg()  
    else:
        raise ValueError("unknown state names: %r" % state_names)
   
    ## Graph
    # Form the graph object
    G = nx.DiGraph()

    # Nodes
    for arg0 in check_res['norm_stm'].index:
        G.add_node(arg0)

    # Edges, weighted by transition prob
    for arg1, arg1_col in check_res['norm_stm'].iteritems():
        for arg0, val in arg1_col.iteritems():
            if not np.isnan(val):
                G.add_edge(arg0, arg1, weight=val)

    # Edge labels are the weights
    edge_labels=dict([((u,v,), "%0.2f" % d['weight']) 
        for u, v, d in G.edges(data=True)])

    # Draw
    pos = nx.circular_layout(G)
    pos[17] = np.asarray([.25, .05])
    pos[9] = np.asarray([.45, .05])
    pos[8] = np.asarray([0, .05])
    pos[13] = np.asarray([.5, .5])
    f, ax = plt.subplots(figsize=(14, 8))
    nx.draw(G, pos, ax=ax, with_labels=False, node_size=3000, node_shape='s')
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=10)
    nx.draw_networkx_labels(G, pos, check_res['node_labels'], font_size=8)

    f.subplots_adjust(left=.01, right=.99, bottom=.01, top=.99, wspace=0, hspace=0)

    ## Plot hists of all durations
    f, axa = my.plot.auto_subplot(len(check_res['node_all_durations']),
        figsize=(14, 10))
    for node_num, ax in zip(
        sorted(check_res['node_all_durations'].keys()), axa.flatten()):
        data = check_res['node_all_durations'][node_num]
        rng = data.max() - data.min()
        
        tit_str = "%d: %s, %0.3f" % (node_num, 
            state_num2names[node_num].lower(), rng)
        ax.set_title(tit_str, size='small')
        ax.hist(data)
        
        if np.diff(ax.get_xlim()) < .01:
            mean_ax_xlim = np.mean(ax.get_xlim())
            ax.set_xlim((mean_ax_xlim - .005, mean_ax_xlim + .005))

        my.plot.rescue_tick(ax=ax, x=4, y=3)

    f.tight_layout()
    plt.show()      
    old_label: new_label
    for old_label, new_label in itertools.zip_longest(
        sorted(g.nodes()), list_columns_names, fillvalue=1)
}
#print(mapping)

# create a dictionary with zip()
#dictionary = dict(zip(list_columns_int, list_columns_names))
#print(dictionary)

# relabel the names of the nodes from integers back to strings
nx.relabel_nodes(g, mapping, copy=False)

plt.figure(figsize=(20, 10))

pos = nx.circular_layout(g)

#nx.draw(g, pos, node_color='red', edgelist=g.edges(), edge_color=weights, arrowsize=20, with_labels=True, node_size=100, width=1.5, edge_cmap=plt.cm.Reds)

output_file('index.html')

plt.show()

# plotting

# circular layout
plot_circle = Plot(plot_width=1000,
                   plot_height=715,
                   x_range=Range1d(-1.1, 1.1),
                   y_range=Range1d(-1.1, 1.1))
Exemple #58
0
def generateAdjacencyRCC(overlaps, labels):
    PO = nx.Graph()

    for x in labels:
        node_x = Node([x])
        if not PO.has_node(node_x):
            PO.add_node(node_x)

    firing_counts = {}
    for l in labels:
        firing_counts[l] = 0

    for bin in overlaps:
        nodes = [Node([x]) for x in bin]
        for x in bin:
            firing_counts[x] += 1
        for i in range(0, len(nodes)):
            for j in range(i, len(nodes)):
                if not PO.has_edge(nodes[i], nodes[j]):
                    PO.add_edge(nodes[i], nodes[j], weight=1.0)
                else:
                    PO[nodes[i]][nodes[j]]['weight'] = PO[nodes[i]][
                        nodes[j]]['weight'] + 1.0

    # remove proper part nodes

    # averages = {}
    # for node in PO.nodes():
    #     weights = [w for (u,v,w) in PO.edges(node, data='weight')]
    #     averages[node] = np.mean(weights)
    #
    # for (u,v,w) in PO.edges(data='weight'):
    #     forward = PO[u][v]['weight'] / averages[u]
    #     backward = PO[v][u]['weight'] / averages[v]
    #     PO[u][v]['weight'] = max([forward, backward])

    mix = generateAdjacency(overlaps)
    PO = nx.compose(PO, mix)

    # pp_nodes = []
    # PP = nx.Graph()
    # for node in PO.nodes() :
    #     node_fire_count = 0
    #     if not PP.has_node(node):
    #         PP.add_node(node)
    #     for bin in overlaps:
    #         if node not in bin:
    #             continue
    #         node_fire_count += 1
    #         for other in PO.nodes():
    #             if other in bin:
    #                 if not PP.has_node(other):
    #                     PP.add_node(other)
    #                 if not PP.has_edge(node, other):
    #                     PP.add_edge(node, other, weight=1.0)
    #                 else:
    #                     G[node][other]['weight'] = G[node][other]['weight'] + 1.0
    #     for (u,v,w) in PP.edges(data='weight') :
    #         if u == node and w/node_fire_count > 0.7 :
    #             print('{} part of {}'.format(u,v))
    #             if u not in pp_nodes:
    #                 pp_nodes.append(u)
    #
    # PO.remove_nodes_from(pp_nodes)

    # cutoff 25 for W, 140 for figure8
    bad = [(u, v) for (u, v, w) in PO.edges(data='weight') if w <= 6 or u == v]
    PO.remove_edges_from(bad)

    outdeg = PO.degree()
    to_remove = [n for n in PO.nodes() if outdeg[n] == 0]
    PO.remove_nodes_from(to_remove)

    edges = []
    for node in PO.nodes():
        if len(node.cells) > 1:
            for (u, v) in PO.edges(node):
                for (u2, v2) in PO.edges(node):
                    if not v.cells == v2.cells:
                        if PO.has_edge(v, v2):
                            if all(i in node.cells for i in v.cells) and all(
                                    i in node.cells for i in v2.cells):
                                if PO[u][v]['weight'] < (
                                        PO[v][v2]['weight'] *
                                    (3.0 / 4.0)) and PO[u][v2]['weight'] < (
                                        PO[v][v2]['weight'] * 3.0 / 4.0):
                                    edges.append((v, v2))
    print(edges)

    PO.remove_edges_from(edges)

    # for (u,v,w) in PO.edges(data='weight'):
    #     forward = PO[u][v]['weight'] / firing_counts[str(u)]
    #     backward = PO[v][u]['weight'] / firing_counts[str(v)]
    #     PO[u][v]['weight'] = max([forward, backward])

    # adjGraph = generateAdjacencyCount(overlaps, labels)
    #
    # for t in range(1,len(overlaps)-1):
    #     nodes_nm1 = [Node(n) for n in overlaps[t-1]]
    #     nodes_n = [Node(n) for n in overlaps[t]]
    #     nodes_np1 = [Node(n) for n in overlaps[t+1]]
    #     for n in nodes_n:
    #         for nm1 in nodes_nm1:
    #             if PO.has_edge(nm1, n):
    #                 for np1 in nodes_np1:
    #                     if PO.has_edge(n, np1):
    #                         if (not adjGraph.has_edge(n, np1)) :
    #                             PO[nm1][n]['weight'] = PO[nm1][n]['weight'] - 1
    #                         else :
    #                             PO[nm1][n]['weight'] = PO[nm1][n]['weight'] + 1
    #
    # for (u,v,w) in PO.edges(data='weight'):
    #     forward = PO[u][v]['weight']
    #     backward = PO[v][u]['weight']
    #     PO[u][v]['weight'] = max([forward, backward])
    #
    # bad = [(u, v) for (u, v, w) in PO.edges(data='weight') if w <= 0 or u == v]
    # PO.remove_edges_from(bad)
    #
    # outdeg = PO.degree()
    # to_remove = [n for n in PO.nodes() if outdeg[n] == 0]
    # PO.remove_nodes_from(to_remove)

    for node in PO.nodes():
        print([node, getNumComponents([node], PO)])

    labels = nx.get_edge_attributes(PO, 'weight')
    pos = nx.circular_layout(PO)
    nx.draw(PO, pos)
    nx.draw_networkx_edge_labels(PO, pos, edge_labels=labels, label_pos=0.5)
    nx.draw_networkx_labels(PO, pos)
    plt.show()
Exemple #59
0
    def show_domain(self, a=0):
        s = self.state
        plt.figure("Domain")

        if self.networkGraph is None:  # or self.networkPos is None:
            self.networkGraph = nx.Graph()
            # enumerate all computer_ids, simulatenously iterating through
            # neighbors list and compstatus
            for computer_id, (neighbors,
                              compstatus) in enumerate(zip(self.NEIGHBORS, s)):
                # Add a node to network for each computer
                self.networkGraph.add_node(computer_id, node_color="w")
            for uniqueEdge in self.UNIQUE_EDGES:
                self.networkGraph.add_edge(
                    uniqueEdge[0], uniqueEdge[1],
                    edge_color="k")  # Add an edge between each neighbor
            self.networkPos = nx.circular_layout(self.networkGraph)
            nx.draw_networkx_nodes(self.networkGraph,
                                   self.networkPos,
                                   node_color="w")
            nx.draw_networkx_edges(self.networkGraph,
                                   self.networkPos,
                                   edge_color="k")
            nx.draw_networkx_labels(self.networkGraph, self.networkPos)
            plt.show()
        else:
            plt.clf()
            blackEdges = []
            redEdges = []
            greenNodes = []
            redNodes = []
            for computer_id, (neighbors,
                              compstatus) in enumerate(zip(self.NEIGHBORS, s)):
                if compstatus == self.RUNNING:
                    greenNodes.append(computer_id)
                else:
                    redNodes.append(computer_id)
            # Iterate through all unique edges
            for uniqueEdge in self.UNIQUE_EDGES:
                if (s[uniqueEdge[0]] == self.RUNNING
                        and s[uniqueEdge[1]] == self.RUNNING):
                    # Then both computers are working
                    blackEdges.append(uniqueEdge)
                else:  # If either computer is BROKEN, make the edge red
                    redEdges.append(uniqueEdge)
            # "if redNodes", etc. - only draw things in the network if these lists aren't empty / null
            if redNodes:
                nx.draw_networkx_nodes(
                    self.networkGraph,
                    self.networkPos,
                    nodelist=redNodes,
                    node_color="r",
                    linewidths=2,
                )
            if greenNodes:
                nx.draw_networkx_nodes(
                    self.networkGraph,
                    self.networkPos,
                    nodelist=greenNodes,
                    node_color="w",
                    linewidths=2,
                )
            if blackEdges:
                nx.draw_networkx_edges(
                    self.networkGraph,
                    self.networkPos,
                    edgelist=blackEdges,
                    edge_color="k",
                    width=2,
                    style="solid",
                )
            if redEdges:
                nx.draw_networkx_edges(
                    self.networkGraph,
                    self.networkPos,
                    edgelist=redEdges,
                    edge_color="k",
                    width=2,
                    style="dotted",
                )
        nx.draw_networkx_labels(self.networkGraph, self.networkPos)
        plt.figure("Domain").canvas.draw()
        plt.figure("Domain").canvas.flush_events()
#                 [0, 1./5, 0, 4./5, 0, 0],
#                 [1./4, 1./4, 0, 0, 1./4, 1./4],
#                 [1./6, 1./6, 1./6, 1./6, 1./6, 1./6]])

P_1 = np.array([[1, 0, 0, 0, 0, 0], [0.5, 0, 0.5, 0, 0, 0],
                [0.1, 0, 0.5, 0.3, 0, 0.1], [0, 0, 0, 0.7, 0.1, 0.2],
                [1. / 3, 0, 0, 1. / 3, 1. / 3, 0], [0, 0, 0, 0, 0, 1]])

P_2 = np.array([[1, 0, 0, 0, 0, 0], [0, 3. / 4, 1. / 4, 0, 0, 0],
                [0, 1. / 8, 7. / 8, 0, 0, 0],
                [1. / 4, 1. / 4, 0, 1. / 8, 3. / 8, 0],
                [1. / 3, 0, 1. / 6, 1. / 4, 1. / 4, 0], [0, 0, 0, 0, 0, 1]])

T_1 = make_graph(P_1)

plt.figure()
plt.title("Directed Graph of Transition Probabilties")
pos = nx.circular_layout(T_1)
nx.draw(T_1, pos, node_size=1500, node_color="white", with_labels=True)
nx.draw_networkx_edges(T_1, pos, arrows=True)

T_2 = make_graph(P_2)

plt.figure()
plt.title("Directed Graph of Transition Probabilties")
pos = nx.circular_layout(T_2)
nx.draw(T_2, pos, node_size=1500, node_color="white", with_labels=True)
nx.draw_networkx_edges(T_2, pos, arrows=True)

plt.show()