def uniform_random_intersection_graph(n, m, p, seed=None): """Return a uniform random intersection graph. Parameters ---------- n : int The number of nodes in the first bipartite set (nodes) m : int The number of nodes in the second bipartite set (attributes) p : float Probability of connecting nodes between bipartite sets seed : int, optional Seed for random number generator (default=None). See Also -------- gnp_random_graph References ---------- .. [1] K.B. Singer-Cohen, Random Intersection Graphs, 1995, PhD thesis, Johns Hopkins University .. [2] Fill, J. A., Scheinerman, E. R., and Singer-Cohen, K. B., Random intersection graphs when m = !(n): An equivalence theorem relating the evolution of the g(n, m, p) and g(n, p) models. Random Struct. Algorithms 16, 2 (2000), 156–176. """ G=bipartite.random_graph(n, m, p, seed=seed) return nx.projected_graph(G, range(n))
def generate_graph(self, node_count): if self.generate_dense and node_count > 2: # generate a dense bipartite graph # there are no triangles in such graph n = np.random.randint(1, node_count) m = node_count - n g_0 = bipartite.random_graph(n, m, 0.5) # randomly shuffle the nodes. g = nx.Graph() shuffled_nodes = list(g_0.nodes) g.add_nodes_from(shuffled_nodes) random.shuffle(shuffled_nodes) for e in g_0.edges: g.add_edge(shuffled_nodes[e[0]], shuffled_nodes[e[1]]) # add a few edges which may form triangles n_edges = int(np.log(node_count)) + 1 nodes = list(g.nodes) for _ in range(n_edges): v1 = random.choice(nodes) v2 = random.choice(nodes) if v1 != v2: g.add_edge(v1, v2) return g else: # generate a random graph with such sparsity that several triangles are expected. eps = 0.2 p = ((1 + eps) * np.log(node_count)) / node_count return nx.generators.gnp_random_graph(node_count, p, directed=False)
def random_bipartite_graph(n, k, p): ''' n: number of nodes in the first bipatite set k: number of nodes in the second bipartite set p: probability for edge creation ''' return bp.random_graph(n, k, p)
def generate_random_2mode(G): top_nodes = {n for n, d in G.nodes(data=True) if d['bipartite'] == 0} bot_nodes = set(G) - top_nodes size = G.size() density = bp.density(G, top_nodes) #return bp.gnmk_random_graph(len(top_nodes), len(bot_nodes), size) return bp.random_graph(len(top_nodes), len(bot_nodes), density)
def main(): G = nx.complete_graph(10) #完全グラフ G2 = nx.barbell_graph(10, 10) #ようわからん G3 = nx.watts_strogatz_graph(100, 15, 0.1) #small world graph #watts_strogatz_graph(n,k,p) n: number of node, k:nearest neoghbors, G4 = nx.complete_bipartite_graph(3, 3) #完全二部グラフ G5 = nx.scale_free_graph(50) G6 = nx.newman_watts_strogatz_graph(100, 10, 0.05) G7 = nx.binomial_graph(10, 0.2) # z=[int(random.gammavariate(alpha=9.0,beta=2.0)) for i in range(6)] # G8 = nx.configuration_model(z) # aseq = [1,2,1] # bseq = [2,1,1] # G8 = nx.configuration_model(aseq,bseq) G8 = bp.random_graph(5, 5, 0.5) pos = nx.spring_layout(G6) # pos = nx.circular_layout(G5) plt.axis('off') nx.draw(G6, pos, with_labels=False) plt.show()
def random_bipartite_graph_generation_and_dump_in_json(): nb_sommets = 10 seed = 29 n1 = random.randint(1, nb_sommets - 1) n2 = nb_sommets - n1 p = 0.85 print("n1 = ", n1) print("n2 = ", n2) g = bipartite.random_graph(n1, n2, p, seed, directed=False) V1, V2 = nx.bipartite.sets(g) graph_for_json = dict() graph_for_json = { "seed": seed, "graph_type": "bipartite", "total_node_count": len(g.nodes), "V1_node_count": len(V1), "V2_node_count": len(V2), "edge_count": len(list(g.edges)), "nodes": sorted(g.nodes), "edges": list(g.edges) } with open('test_dumps/random_bipartite_1.json', 'w', encoding='utf8') as json_file: json_file.write(data_to_json(graph_for_json))
def uniform_random_intersection_graph(n, m, p, seed=None): """Returns a uniform random intersection graph. Parameters ---------- n : int The number of nodes in the first bipartite set (nodes) m : int The number of nodes in the second bipartite set (attributes) p : float Probability of connecting nodes between bipartite sets seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. See Also -------- gnp_random_graph References ---------- .. [1] K.B. Singer-Cohen, Random Intersection Graphs, 1995, PhD thesis, Johns Hopkins University .. [2] Fill, J. A., Scheinerman, E. R., and Singer-Cohen, K. B., Random intersection graphs when m = !(n): An equivalence theorem relating the evolution of the g(n, m, p) and g(n, p) models. Random Struct. Algorithms 16, 2 (2000), 156–176. """ G = bipartite.random_graph(n, m, p, seed) return nx.projected_graph(G, range(n))
def test_biadjacency_matrix(self): tops = [2,5,10] bots = [5,10,15] for i in range(len(tops)): G = bipartite.random_graph(tops[i], bots[i], 0.2) top = [n for n,d in G.nodes(data=True) if d['bipartite']==0] M = bipartite.biadjacency_matrix(G, top) assert_equal(M.shape[0],tops[i]) assert_equal(M.shape[1],bots[i])
def test_biadjacency_matrix(self): tops = [2, 5, 10] bots = [5, 10, 15] for i in range(len(tops)): G = bipartite.random_graph(tops[i], bots[i], 0.2) top = [n for n, d in G.nodes(data=True) if d['bipartite'] == 0] M = bipartite.biadjacency_matrix(G, top) assert_equal(M.shape[0], tops[i]) assert_equal(M.shape[1], bots[i])
def test_connectivity(): nb_sommets = 15 seed = 29 n1 = random.randint(1, nb_sommets - 1) n2 = nb_sommets - n1 p = 0.5 g = bipartite.random_graph(n1, n2, p, seed, directed=False) return nx.is_connected(g)
def test_biadjacency_matrix(self): pytest.importorskip("scipy") tops = [2, 5, 10] bots = [5, 10, 15] for i in range(len(tops)): G = bipartite.random_graph(tops[i], bots[i], 0.2) top = [n for n, d in G.nodes(data=True) if d["bipartite"] == 0] M = bipartite.biadjacency_matrix(G, top) assert M.shape[0] == tops[i] assert M.shape[1] == bots[i]
def prepareGraf(n1,n2,p): SET=[] G=bipartite.random_graph(n1,n2,p) for edge in G.edges: tuple=(edge[0],edge[1]) SET.append(tuple) return SET
def test_biadjacency_matrix(self): try: import scipy except ImportError: raise SkipTest('SciPy not available.') tops = [2,5,10] bots = [5,10,15] for i in range(len(tops)): G = bipartite.random_graph(tops[i], bots[i], 0.2) top = [n for n,d in G.nodes(data=True) if d['bipartite']==0] M = bipartite.biadjacency_matrix(G, top) assert_equal(M.shape[0],tops[i]) assert_equal(M.shape[1],bots[i])
def test_biadjacency_matrix(self): try: import scipy except ImportError: raise SkipTest('SciPy not available.') tops = [2, 5, 10] bots = [5, 10, 15] for i in range(len(tops)): G = bipartite.random_graph(tops[i], bots[i], 0.2) top = [n for n, d in G.nodes(data=True) if d['bipartite'] == 0] M = bipartite.biadjacency_matrix(G, top) assert_equal(M.shape[0], tops[i]) assert_equal(M.shape[1], bots[i])
def bipartite_generation(tailles, nb_instances, chemin_pour_stockage): #We need to create a dict to count the number of bipartite graphs for each density print("!!! WORK IN PROGRESS !!!") for nb_sommets in tailles: for i in range(1, nb_instances + 1): n1 = random.randint(1, nb_sommets - 1) n2 = nb_sommets - n1 p = 0.5 ################################################## WE HAVE TO DEFINE THIS VALUE g = bipartite.random_graph(n1, n2, p, i, directed=False) if ( nx.is_connected(g) == False ): #the bipartite graph is not connected, we will have to add edges print("YOU STILL HAVE WORK TO DO") V1, V2 = bipartite.sets(g) graph_for_json = dict() graph_for_json = { "seed": i, "graph_type": graph_type, "total_node_count": len(g.nodes), "V1_node_count": len(V1), "V2_node_count": len(V2), "edge_count": len(list(g.edges)), "nodes": sorted(g.nodes), "edges": list(g.edges) } #Computes the density d = 0 #arrondi de la densité #Update the a counter linked to the density name = chemin_pour_stockage + graph_type + "__n=" + str( nb_sommets) + "__d=" + str(d) + "__" + '{:03}'.format( i) + ".json" with open(name, 'w', encoding='utf8') as json_file: json_file.write(data_to_json(graph_for_json))
def random_bipartite_graph_generation(): nb_sommets = 10 seed = 29 n1 = random.randint(1, nb_sommets - 1) n2 = nb_sommets - n1 p = 0.85 print("n1 = ", n1) print("n2 = ", n2) g = bipartite.random_graph(n1, n2, p, seed, directed=False) #V1, V2 = nx.bipartite.sets(g) #print("V1 : ", V1) #print("V2 : ", V2) if (nx.is_connected(g)): print("The graph is connected") else: print("The graph is not connected")
def formGraph(N, M, pos, eta, seed=None): """Form N by N grid of nodes, connect nodes within eta. mu and eta are relative to 1/(N-1) Arguments: t (float): the best-so-far optimal value pos ([type]): [description] eta ([type]): [description] Keyword Arguments: seed ([type]): [description] (default: {None}) Returns: [type]: [description] """ if seed: random.seed(seed) # connect nodes with edges G = bipartite.random_graph(N, M, eta) # G = nx.DiGraph(G) return G
def bipartite(n_nodes, n_edges, split_ratio=0.2, weight_range=None, seed=None): assert n_nodes > 0 set_random_seed(seed) # Bipartite, Sec 4.1 of (Gu, Fu, Zhou, 2018) n_top = int(split_ratio * n_nodes) n_bottom = n_nodes - n_top creation_prob = n_edges / (n_top * n_bottom) G_und = bipartite.random_graph(n_top, n_bottom, p=creation_prob, directed=True) B_und = DAG._graph_to_adjmat(G_und) B = DAG._random_acyclic_orientation(B_und) if weight_range is None: return B else: W = DAG._BtoW(B, n_nodes, weight_range) return W
def make_random_bipartite_data(group1, group2, p, seed): """ :type group1: list :param group1: Ids of first group :type group2: list :param group2: Ids of second group :type p: float :param p: probability of existence of 1 edge :type seed: int :param seed: seed for random generator :rtype: list :return: all edges in the graph """ logging.info(" creating a bipartite graph between {} items in group1, {} " "items in group2 and edge probability {}".format( len(group1), len(group2), p)) if len(group1) == 0 or len(group2) == 0 or p == 0: return [] bp = pd.DataFrame.from_records(list(bipartite.random_graph(len(group1), len(group2), p, seed).edges()), columns=["from", "to"]) logging.info(" (bipartite index created, now resolving item values)") # as all "to" nodes are from the second group, # but numbered by networkx in range(len(group1),len(group1)+len(group2)) # we need to deduct len(group1) to have proper indexes. bp["to"] -= len(group1) bp["from"] = bp.apply(lambda x: group1[x["from"]], axis=1) bp["to"] = bp.apply(lambda x: group2[x["to"]], axis=1) logging.info(" (resolution done, now converting to tuples)") out = [tuple(x) for x in bp.to_records(index=False)] logging.info(" (exiting bipartite)") return out
def sample_data(seed=123): #### load networks (hypothetical) ####### nb_nodes_networkP = 4 nb_nodes_networkD = 6 nb_nodes_networkC = 8 # H**o networks obj_networkP = nx.gnm_random_graph(nb_nodes_networkP, nb_nodes_networkP * 2, seed=seed) obj_networkD = nx.gnm_random_graph(nb_nodes_networkD, nb_nodes_networkD * 2, seed=seed) obj_networkC = nx.gnm_random_graph(nb_nodes_networkC, nb_nodes_networkC * 2, seed=seed) # Hetero networks obj_networkPD = bipartite.random_graph(nb_nodes_networkP, nb_nodes_networkD, 0.8, seed=seed) obj_networkPC = bipartite.random_graph(nb_nodes_networkP, nb_nodes_networkC, 0.8, seed=seed) obj_networkDC = bipartite.random_graph(nb_nodes_networkD, nb_nodes_networkC, 0.8, seed=seed) ### Weight matrices for network propagation (Normalized weighted adjacency matrices) # H**o networks (Assuming no node with degree 0) adj_networkP = nx.adjacency_matrix(obj_networkP) deg_networkP = np.sum(adj_networkP, axis=0) norm_adj_networkP = sp.csr_matrix( adj_networkP / np.sqrt(np.dot(deg_networkP.T, deg_networkP)), dtype=np.float64) adj_networkD = nx.adjacency_matrix(obj_networkD) deg_networkD = np.sum(adj_networkD, axis=0) norm_adj_networkD = sp.csr_matrix( adj_networkD / np.sqrt(np.dot(deg_networkD.T, deg_networkD)), dtype=np.float64) adj_networkC = nx.adjacency_matrix(obj_networkC) deg_networkC = np.sum(adj_networkC, axis=0) norm_adj_networkC = sp.csr_matrix( adj_networkC / np.sqrt(np.dot(deg_networkC.T, deg_networkC)), dtype=np.float64) # Hetero networks biadj_networkPD = bipartite.biadjacency_matrix( obj_networkPD, row_order=range(nb_nodes_networkP)) degP = np.sum(biadj_networkPD, axis=1) degD = np.sum(biadj_networkPD, axis=0) norm_biadj_networkPD = sp.csr_matrix(biadj_networkPD / np.sqrt(np.dot(degP, degD)), dtype=np.float64) norm_biadj_networkPD.data[np.isnan(norm_biadj_networkPD.data)] = 0.0 norm_biadj_networkPD.eliminate_zeros() biadj_networkPC = bipartite.biadjacency_matrix( obj_networkPC, row_order=range(nb_nodes_networkP)) degP = np.sum(biadj_networkPC, axis=1) degC = np.sum(biadj_networkPC, axis=0) norm_biadj_networkPC = sp.csr_matrix(biadj_networkPC / np.sqrt(np.dot(degP, degC)), dtype=np.float64) norm_biadj_networkPC.data[np.isnan(norm_biadj_networkPC.data)] = 0.0 norm_biadj_networkPC.eliminate_zeros() biadj_networkDC = bipartite.biadjacency_matrix( obj_networkDC, row_order=range(nb_nodes_networkD)) degD = np.sum(biadj_networkDC, axis=1) degC = np.sum(biadj_networkDC, axis=0) norm_biadj_networkDC = sp.csr_matrix(biadj_networkDC / np.sqrt(np.dot(degD, degC)), dtype=np.float64) norm_biadj_networkDC.data[np.isnan(norm_biadj_networkDC.data)] = 0.0 norm_biadj_networkDC.eliminate_zeros() return norm_adj_networkP, norm_adj_networkD, norm_adj_networkC, norm_biadj_networkPD, norm_biadj_networkPC, norm_biadj_networkDC
node_shape='s', nodelist=vl) if el: nx.draw_networkx_edges(g, pos=pos, ax=ax, edge_color='r', width=3, edgelist=el) ax.set_title(title) ax.set_axis_off() ax.set_aspect('equal') if __name__ == '__main__': # g = nx.petersen_graph() g = bipartite.random_graph(5, 5, 0.7, seed=1) fix_outer_cycle_pos(g, nx.cycle_basis(g)[3]) fix_all_pos(g) gs_kw = {'height_ratios': [2, 1]} fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(8, 6), gridspec_kw=gs_kw) ip = vc_mat(g) vl = vc(ip) draw(g, ax1, 'vertex cover', vl=vl) draw(g, ax2, 'matching', el=mat(ip)) ip.draw(ax=ax3, title='input') ip.draw(ax=ax4, I=vl, title='set cover')
def bipartite_example(): from networkx.algorithms import bipartite return bipartite.random_graph(10, 5, .4, 0)
import sys if __name__ == '__main__': import timeit import numpy as np from operator import itemgetter from networkx.algorithms import bipartite as nx import networkx.convert as nc from hungarian_algorithm import algorithm from networkx.algorithms import flow as fl lst = [] for k in range(500, 10000, 500): a = int(np.random.uniform(1, k)) lst.append((a, k - a)) for i, j in lst: G = nx.random_graph(i, j, 1) partition_l = set(map(itemgetter(0), G.edges())) content = nx.biadjacency_matrix(G, partition_l).toarray().tolist() # print(len(content)) start = timeit.default_timer() bipartiteMatch(content) stop = timeit.default_timer() print('Hopcroft-Karp Time: n: ', i + j, stop - start) # g = FlowNetwork() # A, B = nx.sets(G) # edges = G.edges() # for i in edges:
def test_bipartite_directed(self): G = bipartite.random_graph(10, 10, 0.1, directed=True) assert_true(bipartite.is_bipartite(G))
def adjacency_matrix_rnd(S1 = 10, S2 = 10, p = 0.33, dir_name = 'graph', index = 1, index2 = 1, flag = False): import networkx as nx from networkx.algorithms import bipartite import matplotlib.pyplot as plt import os from ensure_dir import ensure_dir import my_print as my import my_output as O curr_dir = os.getcwd() #print('dir_name = ', dir_name) file_path = dir_name+'/prova.txt' ensure_dir(file_path) directory = os.path.dirname(file_path) os.chdir(directory) G = bipartite.random_graph(S1, S2, p) deg = list(G.degree()) deg1 = deg[:S1] deg2 = deg[S1:] pos = {x:[0,x] for x in range(S1)} for j in range(S2): pos[S1+j] = [1,j] colors = ['r' for i in range(0,S1)] for j in range(S2): colors.append('b') fig, [ax1, ax] = plt.subplots(1,2, figsize = (9,4)) ax1.set_title('Interazioni mutualistiche casuali') ax1.set_axis_off() ax1.set_autoscale_on(True) nx.draw_networkx(G, pos = pos, node_color = colors, ax = ax1) A = nx.to_numpy_matrix(G) A2 = A.getA() A1 = [] for x in range(S1): A1.append(A2[x][S1:]) ax.grid() xtics = [x-0.5 for x in range(0,S2+1)] ytics = [x-0.5 for x in range(0,S1+1)] ax.set_yticks(ytics) ax.set_xticks(xtics) ax.set_ylabel('Impollinatori') ax.set_xlabel('Piante') ax.set_title('Configurazione casuale con C = '+format(p,'.2f')) ax.set_autoscale_on(True) plt.imshow(A1, cmap = 'Greys') if index == 1: fig.savefig('random_'+format(p,'.2f')+'.png') plt.close() if flag == False: if index == 1: my.print_tuple2(deg1, 'R_degree1-'+repr(index2), dir_name) my.print_tuple2(deg2, 'R_degree2-'+repr(index2), dir_name) else: O.print_list_csv(deg1, 'deg1_R-'+repr(index), dir_name) O.print_list_csv(deg2, 'deg2_R-'+repr(index), dir_name) file_path2 = "C:/Users/Utente/Anaconda3/UserScripts/Programmi cooperazione/" directory2 = os.path.dirname(file_path2) print('directory2 = ', directory2) print('curr_dir = ', curr_dir) os.chdir(directory2) return A1
print("Original Graph") draw_graph(layout5, C) max_flow_C = ford_fulkerson(C, 'S', 'T', flow_debug) print("Max Flow Graph") draw_graph(layout5, C) print("Max Flow", max_flow_C) """#9d Now consider the case where there are n drivers and n riders, and the drivers each driver is connected to each rider with probability p. Fix n = 1000 (or maybe 100 if that’s too much), and estimate the probability that all n riders will get matched for varying values of p. Plot your results. """ diff_p_list = list(np.arange(0, 1.10, 0.10)) prob_all_riders_matched = list() for p in np.arange(0, 1.10, 0.10): brg = bipartite.random_graph(100, 100, p) RB_top = set(n for n, d in brg.nodes(data=True) if d['bipartite'] == 0) RB_bottom = set(brg) - RB_top brg.add_nodes_from('ST' + str(RB_top) + str(RB_bottom)) for (u, v) in brg.edges(): brg.add_edges_from([(u, v, {'capacity': 1, 'flow': 0})]) for elem in RB_top: brg.add_edges_from([('S', elem, {'capacity': 1, 'flow': 0})]) for elem in RB_bottom: brg.add_edges_from([(elem, 'T', {'capacity': 1, 'flow': 0})]) max_flow = ford_fulkerson(brg, 'S', 'T', flow_debug)
import networkx as nx from networkx import write_gpickle from networkx.algorithms import bipartite N = 21 #initialize the list with starting elements: 0, 1 fibonacciSeries = [0, 1] print("Initializing graph generator ...") if N > 2: for i in range(2, N): nextElement = fibonacciSeries[i - 1] + fibonacciSeries[i - 2] fibonacciSeries.append(nextElement) nodes1 = nextElement nodes2 = nextElement probability = 0.7 print("Generating graph " + str(i) + " with " + str(nextElement) + " nodes in each part...") # https://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.generators.bipartite.bipartite_random_graph.html G = bipartite.random_graph(nodes1, nodes2, probability, seed=None, directed=False) write_gpickle(G, "graphs/graph" + str(i) + ".pickle")
del preds[v] for u in L: if u in pred: pu = pred[u] del pred[u] if pu is unmatched or recurse(pu): matching[v] = u return 1 return 0 for v in unmatched: recurse(v) if __name__ == '__main__': import timeit import numpy as np from networkx.algorithms import bipartite as nx from operator import itemgetter G = nx.random_graph(1000, 2000, 0.2) partition_l = set(map(itemgetter(0), G.edges())) content = nx.biadjacency_matrix(G, partition_l).toarray().tolist() start = timeit.default_timer() bipartiteMatch(content) stop = timeit.default_timer() print('Time: ', stop - start)
import random import networkx as nx import matplotlib.pyplot as plt from networkx.algorithms import bipartite graph = bipartite.random_graph(5, 7, 0.2) left_nodes = list(graph.nodes()) left_nodes = left_nodes[:5] right_nodes = list(graph.nodes()) right_nodes = right_nodes[5:] pos = dict() print(graph.edges()) graphique = [[] for i in range(0, 5)] for j in list(graph.edges()): graphique[j[0]].append(j[1]) print(graphique) print(right_nodes, left_nodes) cmpt = 0 for i in left_nodes: cmpt += 1 pos.update({i: (1, cmpt)}) cmpt = 0 for i in right_nodes: cmpt += 1 pos.update({i: (2, cmpt)}) nx.draw(graph, pos=pos, with_labels=True)
def get_random_bipartite_graph(left, right, seed=42): from networkx.algorithms import bipartite #aseq = list(int(3*x) for x in (np.random.pareto(1,left)+1) if x < (left / 9) ) #G = bipartite.preferential_attachment_graph(aseq, 0.8, create_using=nx.Graph) G = bipartite.random_graph(int(left), int(right), 0.7, seed=seed) return G, None
for x in E: if (not f1(I,x,x)): X1.append(x) if (not f2(I,x,x)): X2.append(x) if X1==[] or X2==[]: break P=D.BFS(X1,X2) if len(P)==0: break else: augment(E,I,P) return(I) Gset=[(0,5),(0,8),(1,6),(1,7),(2,5),(2,9),(3,5),(3,8),(4,8),(4,7),(4,9)] G=bipartite.random_graph(10,10,0.5) SET=[] for edge in G.edges: tuple=(edge[0],edge[1]) SET.append(tuple) I=MatroidIntersection(SET,f1,f2) print(I) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # PREPARE GRAPH # # # # # # # # # # # # # # # # # # # # # def prepareGraf(n1,n2,p): SET=[]