def export_gexf(protein_gene_map): G = nx.Graph() count = 0 for protein, gene in protein_gene_map.items(): G.add_node(protein) G.add_nodes_from(gene) G.add_edge(protein, gene) count += 1 c = bipartite.color(G) nx.set_node_attributes(G, 'bipartite', c) nx.write_gexf(G,"protein_gene_map.gexf")
def export_gexf(protein_gene_map): G = nx.Graph() count = 0 for protein, gene in protein_gene_map.items(): G.add_node(protein) G.add_nodes_from(gene) G.add_edge(protein, gene) count += 1 c = bipartite.color(G) nx.set_node_attributes(G, 'bipartite', c) nx.write_gexf(G, "protein_gene_map.gexf")
def buildGraph(vertices, fileName, action, source=-1, target=-1): # print(action, vertices, fileName, action, source) G.clear() pos = nx.spring_layout(G) for i in range(0, len(vertices) - 1, 2): G.add_edge(vertices[i], vertices[i + 1], color="green", weight=7) colors = nx.get_edge_attributes(G, 'color').values() weights = nx.get_edge_attributes(G, 'weight').values() if action == "dfs": try: traverse = [] T = nx.dfs_tree(G, source=source) for i in T.edges(): traverse.append(i[0]) traverse.append(i[1]) ans = [] for i in range(len(traverse) - 1): if traverse[i] != traverse[i + 1]: ans.append(traverse[i]) ans.append(traverse[len(traverse) - 1]) traverse = ans nx.draw(G, with_labels=True, edge_color=colors, width=list(weights), node_size=1005) plt.savefig('./static/images/' + fileName) return traverse except: return "Error" if action == "bfs": try: traverse = [] T = nx.bfs_tree(G, source=source) for i in T.edges(): traverse.append(i[0]) traverse.append(i[1]) ans = [] for i in range(len(traverse) - 1): if traverse[i] != traverse[i + 1]: ans.append(traverse[i]) ans.append(traverse[len(traverse) - 1]) traverse = ans nx.draw(G, with_labels=True, edge_color=colors, width=list(weights), node_size=1005) plt.savefig('./static/images/' + fileName) return traverse except: return "Error" if action == "shortest path": try: traverse = [] T = nx.bidirectional_shortest_path(G, source=source, target=target) print(T) for i in range(len(T) - 1): G.add_edge(T[i], T[i + 1], color='r', weight=10) traverse.append(T[i]) traverse.append(T[len(T) - 1]) print(traverse) colors = nx.get_edge_attributes(G, 'color').values() weights = nx.get_edge_attributes(G, 'weight').values() nx.draw(G, edge_color=colors, with_labels=True, width=list(weights), node_size=1005) plt.savefig('./static/images/' + fileName) return traverse except: return "Error" if action == "bipartite": if bipartite.is_bipartite(G): color = [] T = bipartite.color(G) weight = [] node_size = [] for node in G: if T[node] == 0: color.append('red') weight.append(6) node_size.append(1005) else: color.append('green') weight.append(6) node_size.append(1005) nx.draw(G, node_color=color, width=weight, node_size=node_size, with_labels=True) plt.savefig('./static/images/' + fileName) return True else: return False if action == "cycle": try: traverse = [] T = nx.find_cycle(G, orientation="original") for i in range(len(T)): G.add_edge(T[i][0], T[i][1], color='r', weight=10) traverse.append(T[i][0]) print(traverse) colors = nx.get_edge_attributes(G, 'color').values() weights = nx.get_edge_attributes(G, 'weight').values() nx.draw(G, edge_color=colors, with_labels=True, width=list(weights), node_size=1005) plt.savefig('./static/images/' + fileName) return traverse except: return "Not Contain A Cycle"
def test_not_bipartite_color(self): c = bipartite.color(nx.complete_graph(4))
def test_not_bipartite_color(self): with pytest.raises(nx.NetworkXError): c = bipartite.color(nx.complete_graph(4))
def test_not_bipartite_color(self): c=bipartite.color(nx.complete_graph(4))
def test_bipartite_color(self): G=nx.path_graph(4) c=bipartite.color(G) assert_equal(c,{0: 1, 1: 0, 2: 1, 3: 0})
def plot(): dir_output_graph_content = [] dir_outcomes_content = [] graph_index = -1 print '########## Plot graph section ########## \nAvailable files: \n' for root, dirs, files in os.walk('../outcomes'): for i in range(0,len(files)): print str(i)+'-'+files[i] dir_outcomes_content.append(files[i]) while (graph_index >= len(dir_outcomes_content) or graph_index < 0): try: graph_index = int(raw_input("\nChoose from one of these graphs and type its corresponding index: \n")) except EOFError as error: print '\nBye!' sys.exit(0) graph_outcomes_name = (dir_outcomes_content[graph_index].split('.'))[0] graph_index = -1 for root, dirs, files in os.walk('../output_graph'): counter = 0 for i in range(0,len(files)): if graph_outcomes_name in files[i]: dir_output_graph_content.append(files[i]) print str(counter)+'-'+files[i] counter += 1 while (graph_index >= len(dir_output_graph_content) or graph_index < 0): try: graph_index = int(raw_input("\nChoose the output_graph in function of strategy: \n")) except EOFError as error: print '\nBye!' sys.exit(0) graph_output_graph_name = (dir_output_graph_content[graph_index].split('.'))[0] g_original = nx.read_gpickle('../outcomes/'+graph_outcomes_name+'.pickle')#graph before adding recommended edges g = nx.read_gpickle('../output_graph/'+graph_output_graph_name+'.pickle')#graph after adding recommended edges edges = g.edges() node_list = [] nodes_info = {}#{node:(in_deg,out_deg,ratio),...} bipartite_graph = nx.DiGraph()#for coloring for u,v in edges: if 'color' in g[u][v] and g[u][v]['color'] == 'red': in_deg_u = g_original.in_degree(u) out_deg_u = g_original.out_degree(u) ratio_u = float(in_deg_u)/(float(out_deg_u + 1)) in_deg_v = g_original.in_degree(v) out_deg_v = g_original.out_degree(v) ratio_v = float(in_deg_v)/(float(out_deg_v + 1)) nodes_info.update({u:(in_deg_u,out_deg_u,ratio_u)}) nodes_info.update({v:(in_deg_v,out_deg_v,ratio_v)}) node_list.append(u) node_list.append(v) bipartite_graph.add_edge(u, v)#for coloring else: g[u][v]['color'] = 'black' g_sub = g.subgraph(node_list) colors = [g[u][v]['color'] for u,v in g_sub.edges()] c = bipartite.color(bipartite_graph) list_black = [] list_red = [] for node in g_sub.nodes(): if c[node] == 0: list_black.append(node) else: list_red.append(node) pos = nx.spring_layout(g_sub) nx.draw_networkx_nodes(g_sub, pos, nodelist=list_black, node_color = 'red') nx.draw_networkx_nodes(g_sub, pos, nodelist=list_red, node_color = 'yellow') nx.draw_networkx_edges(g_sub, pos, edge_color=colors) nx.draw_networkx_labels(g_sub, pos, labels = nodes_info, font_size=9) plt.show()
def main(): import sys import networkx as nx from networkx.algorithms import bipartite if len(sys.argv) == 5: C_in = sys.argv[1] P_in = sys.argv[2] prob_in = sys.argv[3] Filename = sys.argv[4] else: print 'Error: there should be 3 input arguments in gen_bipartite_erdos' return # check for input errors #if #print 'C = ' + str(C) #print 'P = ' + str(P) #print 'par = ' + str(par) C = int(float(C_in)) P = int(float(P_in)) prob = float(prob_in) G = nx.generators.bipartite_random_graph(C, P, prob) Adj = nx.adj_matrix(G) if nx.is_connected(G): conn = 1 # get a coloring scheme colors = bipartite.color(G) diameter = nx.diameter(G) else: conn = 0 diameter = 0 print 'Error: generated network was not connected. Try increasing prob' # get a coloring scheme colors = bipartite.color(G) number_of_nodes = C + P # write to file FILE = open(Filename, "w") FILE.write('conn = ' + str(conn) + '\n') FILE.write('C = ' + str(C) + '\n') FILE.write('P = ' + str(P) + '\n') FILE.write('diameter = ' + str(diameter) + '\n') FILE.write('Adj =\n') for node1 in range(number_of_nodes): for node2 in range(number_of_nodes): FILE.write(str(int(Adj[node1, node2])) + ' ') FILE.write('\n') if conn == 1: FILE.write('colors = \n') for node1 in range(number_of_nodes): FILE.write(str(colors[node1]) + ' ') FILE.write('\n') FILE.close()
from networkx.algorithms import bipartite import networkx as nx import matplotlib.pyplot as plt B = nx.Graph() # Add nodes with the node attribute "bipartite" B.add_nodes_from([1, 2, 3, 4], bipartite=0) B.add_nodes_from(["a", "b", "c"], bipartite=1) # Add edges only between nodes of opposite node sets B.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")]) c = bipartite.color(G=B) print(c) nx.draw_planar(G=B, with_labels=True, node_color='g', node_size=800, font_size=14, width=0.8) plt.show()
#matrix.pop() matrix.pop() numpy_matrix = np.matrix(matrix) return numpy_matrix matrix = leer_matrix("Code_CPP/matrix.csv") adjacency = scipy.sparse.csc_matrix(matrix) G = bi.from_biadjacency_matrix(adjacency) infected = leer_matrix("Code_CPP/Datos/infectados.csv") color = bi.color(G) ''' pos=nx.spring_layout(G) w = csv.writer(open("output.csv", "w")) for key,val in pos.items(): w.writerow([key,val[0],val[1]]) ''' pos = {} for i in range(10): pos[i] = np.array([0, 1 - (0.2 * i)]) for i in range(9): pos[10 + i] = np.array([0.2, 0.9 - (0.2 * i)]) for i in range(9): pos[19 + i] = np.array([-0.2, (0.2 * i) - 0.7]) ''' (p,q) = matrix.shape
def add_node_type(network: nx.Graph): assert nx.is_bipartite(network) == True node_type = bipartite.color(network) nx.set_node_attributes(network, node_type, 'Node_Type') return network
nodes_info.update({u: (in_deg_u, out_deg_u, ratio_u)}) nodes_info.update({v: (in_deg_v, out_deg_v, ratio_v)}) node_list.append(u) node_list.append(v) bipartite_graph.add_edge(u, v) #for coloring else: g[u][v]['color'] = 'black' g_sub = g.subgraph(node_list) colors = [g[u][v]['color'] for u, v in g_sub.edges()] c = bipartite.color(bipartite_graph) list_black = [] list_red = [] for node in g_sub.nodes(): if c[node] == 0: list_black.append(node) else: list_red.append(node) pos = nx.spring_layout(g_sub) nx.draw_networkx_nodes(g_sub, pos, nodelist=list_black, node_color='red') nx.draw_networkx_nodes(g_sub, pos, nodelist=list_red, node_color='yellow') nx.draw_networkx_edges(g_sub, pos, edge_color=colors)
def test_bipartite_color(self): G = nx.path_graph(4) c = bipartite.color(G) assert_equal(c, {0: 1, 1: 0, 2: 1, 3: 0})
# messy stuff from here down # should get weighted edges for the projections # have a look at some of the measures available in bipartite df = pd.read_csv('<my_file>.csv', sep=';', header=0, index_col='<index_col_name>') B = nx_graph_from_biadjacency_pandas_df(df) nx.is_connected(B) bottom_nodes, top_nodes = bipartite.sets(B) nx.info(B) for k in B: print(k) list(bottom_nodes) nx.draw(G1, with_labels=True) c = bipartite.color(B) degree = nx.degree(B) G1 = bipartite.projected_graph(B, top_nodes) G2 = bipartite.projected_graph(B, bottom_nodes) nx.write_gexf(B, '<my_file1>.gexf') nx.write_gexf(G1, 'my_file1>_G1.gexf') nx.write_gexf(G2, 'my_file1>_G2.gexf')
def find_chimera_indices(G): """Attempts to determine the Chimera indices of the nodes in graph G. See the :func:`~chimera_graph()` function for a definition of a Chimera graph and Chimera indices. Parameters ---------- G : NetworkX graph Should be a single-tile Chimera graph. Returns ------- chimera_indices : dict A dict of the form {node: (i, j, u, k), ...} where (i, j, u, k) is a 4-tuple of integer Chimera indices. Examples -------- >>> G = dnx.chimera_graph(1, 1, 4) >>> chimera_indices = dnx.find_chimera_indices(G) >>> G = nx.Graph() >>> G.add_edges_from([(0, 2), (1, 2), (1, 3), (0, 3)]) >>> chimera_indices = dnx.find_chimera_indices(G) >>> nx.set_node_attributes(G, chimera_indices, 'chimera_index') """ # if the nodes are orderable, we want the lowest-order one. try: nlist = sorted(G.nodes) except TypeError: nlist = G.nodes() n_nodes = len(nlist) # create the object that will store the indices chimera_indices = {} # ok, let's first check for the simple cases if n_nodes == 0: return chimera_indices elif n_nodes == 1: raise DWaveNetworkXException( 'Singleton graphs are not Chimera-structured') elif n_nodes == 2: return {nlist[0]: (0, 0, 0, 0), nlist[1]: (0, 0, 1, 0)} # next, let's get the bicoloring of the graph; this raises an exception if the graph is # not bipartite coloring = color(G) # we want the color of the node to be the u term in the Chimera-index, so we want the # first node in nlist to be color 0 if coloring[nlist[0]] == 1: coloring = {v: 1 - coloring[v] for v in coloring} # we also want the diameter of the graph # claim: diameter(G) == m + n for |G| > 2 dia = diameter(G) # we have already handled the |G| <= 2 case, so we know, for diameter == 2, that the Chimera # graph is a single tile if dia == 2: shore_indices = [0, 0] for v in nlist: u = coloring[v] chimera_indices[v] = (0, 0, u, shore_indices[u]) shore_indices[u] += 1 return chimera_indices # NB: max degree == shore size <==> one tile raise Exception( 'not yet implemented for Chimera graphs with more than one tile')
def is_balanced(graph_obj, meta_data=False): """ Function to check if a signed graph is balanced. The algorithm used here has been adopted from the paper "On the notion of balance of a signed graph" by Frank Harary and the boook "Networks, Crowds, and Markets: Reasoning About a Highly Connected World" by David Easley and Jon Kleinberg. Args: graph_obj : The signed graph to pass meta_data : Option to get meta data regarding the nature of the balance in the graphs. Default: False Returns: A two tuple: (bool, meta-data dict). The meta-data dict is None, if meta_data is False """ from networkx import Graph from networkx.algorithms import bipartite if graph_obj.is_directed(): undirected_graph_obj = graph_obj.to_undirected() else: undirected_graph_obj = graph_obj nodes = undirected_graph_obj.nodes() node_labels = {} cur_label = 0 for node in nodes: if node not in node_labels: constrained_bfs(undirected_graph_obj, node_labels, cur_label, 1, node) cur_label += 1 num_labels = cur_label set_graph = Graph() set_graph.add_nodes_from([x for x in range(num_labels)]) # check for mutual antagonism between sets and mutual friendship inside sets edges = undirected_graph_obj.edges() balanced = True for edge in edges: f = edge[0] s = edge[1] if undirected_graph_obj[f][s]['weight'] == 1: if node_labels[f] != node_labels[s]: # this shouldn't happen balanced = False break if undirected_graph_obj[f][s]['weight'] == -1: set_graph.add_edge(node_labels[f], node_labels[s]) if node_labels[f] == node_labels[s]: balanced = False break metas = None if meta_data and balanced: # determine strength of balance (bipartite condition for sets antagonism) strong = None if bipartite.is_bipartite(set_graph): strong = True else: strong = False # sets sets = [[] for i in range(num_labels)] for node in node_labels: sets[node_labels[node]].append(node) # possible split split = None if strong: coloring = bipartite.color(set_graph) X = set() Y = set() for set_ in coloring: if coloring[set_] == 0: for node in sets[set_]: X.add(node) else: for node in sets[set_]: Y.add(node) split = {frozenset(X), frozenset(Y)} metas = {} metas['num_original_sets'] = num_labels metas['original_sets'] = sets metas['strength'] = 'strong' if strong else 'weak' metas['possible_split'] = split return (balanced, metas)