def setup(): F["i"] = np.random.randint(5,10) F["j"] = np.random.randint(5,10) F["N"] = F["i"]+F["j"] F["G"] = nx.bipartite_random_graph(F["i"],F["j"],.6) F["M"] = nx.bipartite.biadjacency_matrix(F["G"],range(F["i"]))
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=nx.bipartite_random_graph(n, m, p, seed=seed) return nx.projected_graph(G, range(n))
def create_3comms_bipartite(n,m,p,No_isolates=True): import community as comm from networkx.algorithms import bipartite as bip u=0 while True: G=nx.bipartite_random_graph(n,m,p) list_of_isolates=nx.isolates(G) if No_isolates: G.remove_nodes_from(nx.isolates(G)) partition=comm.best_partition(G) sel=max(partition.values()) if sel==2 and nx.is_connected(G): break u+=1 print u,sel ndlss=bip.sets(G) ndls=[list(i) for i in ndlss] slayer1=ndls[0] slayer2=ndls[1] layer1=[i for i,v in partition.items() if v==0] layer2=[i for i,v in partition.items() if v==1] layer3=[i for i,v in partition.items() if v==2] edgeList=[] for e in G.edges(): if (e[0] in slayer1 and e[1] in slayer2) or (e[0] in slayer2 and e[1] in slayer1): edgeList.append(e) return G,layer1,layer2,layer3,slayer1,slayer2,edgeList,partition
def test_bipartite_common_neighbours_equivalent_projection(): B = nx.bipartite_random_graph(30, 50, 0.1) nodes = [v for v in B if B.node[v]['bipartite']] G = nx.bipartite.weighted_projected_graph(B, nodes) expected = CommonNeighbours(B, eligible='bipartite')() assert_dict_equal(Copy(G).predict(weight='weight'), expected)
def setup(): F["i"] = np.random.randint(5, 10) F["j"] = np.random.randint(5, 10) F["N"] = F["i"] + F["j"] F["G"] = nx.bipartite_random_graph(F["i"], F["j"], .6) F["M"] = nx.bipartite.biadjacency_matrix(F["G"], range(F["i"]))
def test_biadjacency_matrix(self): tops = [2,5,10] bots = [5,10,15] for i in range(len(tops)): G = nx.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 obtain_graph(args, suffix=""): """Build a Bipartite graph according to command line arguments Arguments: - `args`: command line options """ if getattr(args, "bp" + suffix) is not None: l, r, p = getattr(args, "bp" + suffix) G = bipartite_random_graph(l, r, p) elif getattr(args, "bm" + suffix) is not None: l, r, m = getattr(args, "bm" + suffix) G = bipartite_gnmk_random_graph(l, r, m) elif getattr(args, "bd" + suffix) is not None: l, r, d = getattr(args, "bd" + suffix) G = bipartite_random_left_regular(l, r, d) elif getattr(args, "bregular" + suffix) is not None: l, r, d = getattr(args, "bregular" + suffix) G = bipartite_random_regular(l, r, d) elif getattr(args, "bshift" + suffix) is not None: N, M, pattern = getattr(args, "bshift" + suffix) G = bipartite_shift(N, M, pattern) elif getattr(args, "bcomplete" + suffix) is not None: l, r = getattr(args, "bcomplete" + suffix) G = complete_bipartite_graph(l, r) # Workaround: the bipartite labels are missing in old version of networkx for i in range(0, l): G.add_node(i, bipartite=0) for i in range(l, l + r): G.add_node(i, bipartite=1) elif getattr(args, "graphformat" + suffix) is not None: try: print("INFO: reading bipartite graph {} from '{}'".format( suffix, getattr(args, "input" + suffix).name), file=sys.stderr) G = readGraph(getattr(args, "input" + suffix), "bipartite", getattr(args, "graphformat" + suffix)) except ValueError, e: print("ERROR ON '{}'. {}".format( getattr(args, "input" + suffix).name, e), file=sys.stderr) exit(-1)
def obtain_graph(args,suffix=""): """Build a Bipartite graph according to command line arguments Arguments: - `args`: command line options """ if getattr(args,"bp"+suffix) is not None: l,r,p = getattr(args,"bp"+suffix) G=bipartite_random_graph(l,r,p) elif getattr(args,"bm"+suffix) is not None: l,r,m = getattr(args,"bm"+suffix) G=bipartite_gnmk_random_graph(l,r,m) elif getattr(args,"bd"+suffix) is not None: l,r,d = getattr(args,"bd"+suffix) G=bipartite_random_left_regular(l,r,d) elif getattr(args,"bregular"+suffix) is not None: l,r,d = getattr(args,"bregular"+suffix) G=bipartite_random_regular(l,r,d) elif getattr(args,"bshift"+suffix) is not None: N,M,pattern = getattr(args,"bshift"+suffix) G=bipartite_shift(N,M,pattern) elif getattr(args,"bcomplete"+suffix) is not None: l,r = getattr(args,"bcomplete"+suffix) G=complete_bipartite_graph(l,r) # Workaround: the bipartite labels are missing in old version of networkx for i in range(0,l): G.add_node(i,bipartite=0) for i in range(l,l+r): G.add_node(i,bipartite=1) elif getattr(args,"graphformat"+suffix) is not None: try: print("INFO: reading bipartite graph {} from '{}'".format(suffix,getattr(args,"input"+suffix).name), file=sys.stderr) G=readGraph(getattr(args,"input"+suffix), "bipartite", getattr(args,"graphformat"+suffix)) except ValueError,e: print("ERROR ON '{}'. {}".format(getattr(args,"input"+suffix).name,e),file=sys.stderr) exit(-1)
def test_biadjacency_matrix(self): try: import numpy except ImportError: raise SkipTest('numpy not available.') tops = [2, 5, 10] bots = [5, 10, 15] for i in range(len(tops)): G = nx.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 numpy except ImportError: raise SkipTest('numpy not available.') tops = [2,5,10] bots = [5,10,15] for i in range(len(tops)): G = nx.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 getRandomBPG(l, m, prob=0.03): g = nx.bipartite_random_graph(l, m, prob) orig = g.copy() print "%d %d %f" % (l, m, prob) # print "before: edges:%d" % len(g.edges()) count = 0 maxcount = CustomData.numAnomEdges(l + m) l, r = bipartite.sets(g) anom = l.pop() # print "adding %d anom edges" % maxcount for i in r: if not g.has_edge(anom, i) and count < maxcount: g.add_edge(anom, i) count += 1 # print "after: edges:%d" % len(g.edges()) return orig, g
def obtain_graph(args): """Build a Bipartite graph according to command line arguments Arguments: - `args`: command line options """ if args.bp is not None: l,r,p = args.bp G=bipartite_random_graph(l,r,p) elif args.bm is not None: l,r,m = args.bm G=bipartite_gnmk_random_graph(l,r,m) elif args.bd is not None: l,r,d = args.bd G=bipartite_random_left_regular(l,r,d) elif args.bregular is not None: l,r,d = args.bregular G=bipartite_random_regular(l,r,d) elif args.bcomplete is not None: l,r = args.bcomplete G=complete_bipartite_graph(l,r) elif args.graphformat is not None: try: G=readGraph(args.input, "bipartite", args.graphformat) except ValueError,e: print("ERROR ON '{}'. {}".format(args.input.name,e),file=sys.stderr) exit(-1)
def __init__(self,metabolites, reactions, p): #We generate any metabolic bipartite graph here, eventually from a set of different generators self.metabolic_network = nx.bipartite_random_graph(metabolites,reactions,p,directed=True) pos = {} for i in xrange(metabolites): pos[i] = (0,i) if self.metabolic_network.in_degree(i)==0 and self.metabolic_network.out_degree(i)==0: if rndm.random()<0.5: self.metabolic_network.add_edge(i,rndm.randint(metabolites,metabolites+reactions-1)) else: self.metabolic_network.add_edge(rndm.randint(metabolites,metabolites+reactions-1),i) for i in xrange(reactions): pos[i+metabolites] = (metabolites, float(i)*metabolites/reactions) if self.metabolic_network.in_degree(i+metabolites)==0: self.metabolic_network.add_edge(rndm.randint(0,metabolites-1),i+metabolites) if self.metabolic_network.out_degree(i+metabolites)==0: self.metabolic_network.add_edge(i+metabolites,rndm.randint(0,metabolites-1)) nx.draw(self.metabolic_network, pos) plt.show()
def create_3comms_bipartite(n, m, p, No_isolates=True): # import community as comm # from networkx.algorithms import bipartite as bip u = 0 while True: G = nx.bipartite_random_graph(n, m, p) list_of_isolates = nx.isolates(G) if No_isolates: G.remove_nodes_from(nx.isolates(G)) partition = comm.best_partition(G) sel = max(partition.values()) if sel == 2 and nx.is_connected(G): break u += 1 # print u,sel ndlss = bipartite.sets(G) print 'n = %i' % len(ndlss[0]) print 'm = %i' % len(ndlss[1]) print 'Number of edges = %i' % len(G.edges()) ndls = [list(i) for i in ndlss] slayer1 = ndls[0] slayer2 = ndls[1] layer1 = [i for i, v in partition.items() if v == 0] layer2 = [i for i, v in partition.items() if v == 1] layer3 = [i for i, v in partition.items() if v == 2] print 'Community1 = ', layer1 print 'Community2 = ', layer2 print 'Community3 = ', layer3 edgeList = [] for e in G.edges(): if (e[0] in slayer1 and e[1] in slayer2) or (e[0] in slayer2 and e[1] in slayer1): edgeList.append(e) return G, layer1, layer2, layer3, slayer1, slayer2, edgeList, partition
def constructMetabNetwork(metabolites, reactions, p): metab = nx.bipartite_random_graph(metabolites,reactions,p,directed=True) pos = {} for i in xrange(metabolites): pos[i] = (0,i) if metab.in_degree(i)==0 and metab.out_degree(i)==0: if rndm.random()<0.5: metab.add_edge(i,rndm.randint(metabolites,metabolites+reactions-1)) else: metab.add_edge(rndm.randint(metabolites,metabolites+reactions-1),i) for i in xrange(reactions): pos[i+metabolites] = (metabolites, float(i)*metabolites/reactions) if metab.in_degree(i+metabolites)==0: metab.add_edge(rndm.randint(0,metabolites-1),i+metabolites) if metab.out_degree(i+metabolites)==0: metab.add_edge(i+metabolites,rndm.randint(0,metabolites-1)) nx.draw(metab, pos) plt.show() return metab
import networkx as nx from networkx.algorithms import bipartite import pylab bp = nx.Graph() bp = nx.bipartite_random_graph(10, 100,.3) left = set(x for x, y in bp.nodes(data = True) if y['bipartite']== 0) right = set(bp) - left edges = bp.edges(left) pylab.scatter([x[0] for x in edges], [y[1] for y in edges]) #centrality = bipartite.centrality.closeness_centrality(bp, set(bp)) # #pylab.plot([centrality[x] for x in centrality]) pylab.show()
""" import networkx as nx import matplotlib.pyplot as plt from networkx.algorithms import bipartite directors = {0: "a", 1: "b", 2: "c", 3: "d", 4: "e"} companies = {0: "A", 1: "B", 2: "C", 3: "D", 4: "E", 5: "F"} labels = directors.copy() newkey = len(directors.keys()) for k in companies.keys(): labels[k + newkey] = companies[k] J = nx.erdos_renyi_graph(5, 0.8) #Directors F = nx.erdos_renyi_graph(6, 0.6) #Companies H = nx.bipartite_random_graph(5, 6, 0.55) #Directors in Companies G = nx.Graph() #Two-Level Graph for node in J.nodes(): G.add_node(node, bipartite=0) for edge in J.edges(): G.add_edge(edge[0], edge[1]) for edge in F.edges(): G.add_edge(edge[0] + 5, edge[1] + 5) for node in F.nodes(): G.add_node(node + 5, bipartite=1) for edge in H.edges(data=True): G.add_edge(edge[0], edge[1]) posJ = nx.spring_layout(J) posF = nx.spring_layout(F) posH = {
4: "Microsoft", 5: "Dell" } posF = nx.spring_layout(F) plt.figure() nx.draw(F, pos=posF, node_color='b', node_size=1800, font_size=10, font_color='#FFFFFF', node_shape='s', with_labels=False) nx.draw_networkx_labels(F, posF, companies, font_size=10, font_color='#FFFFFF') H = nx.bipartite_random_graph(5, 6, 0.55) posH = { 0: (0, 0), 1: (0, 2), 2: (0, 4), 3: (0, 6), 4: (0, 8), 5: (1, -2), 6: (1, 0), 7: (1, 2), 8: (1, 4), 9: (1, 6), 10: (1, 8) } mode1, mode2 = bipartite.sets(H) labels = {
import networkx as nx import matplotlib.pyplot as plt from networkx.algorithms import bipartite directors = {0:"a",1:"b",2:"c",3:"d",4:"e"} companies={0:"A",1:"B",2:"C",3:"D",4:"E",5:"F"} labels= directors.copy() newkey=len(directors.keys()) for k in companies.keys(): labels[k+newkey]=companies[k] J=nx.erdos_renyi_graph(5,0.8) #Directors F=nx.erdos_renyi_graph(6,0.6) #Companies H=nx.bipartite_random_graph(5,6,0.55) #Directors in Companies G=nx.Graph() #Two-Level Graph for node in J.nodes(): G.add_node(node,bipartite=0) for edge in J.edges(): G.add_edge(edge[0],edge[1]) for edge in F.edges(): G.add_edge(edge[0]+5,edge[1]+5) for node in F.nodes(): G.add_node(node+5,bipartite=1) for edge in H.edges(data=True): G.add_edge(edge[0],edge[1]) posJ=nx.spring_layout(J) posF=nx.spring_layout(F) posH={0:(0,0),1:(0,2),2:(0,4),3:(0,6),4:(0,8),5:(1,-2),6:(1,0),7:(1,2),8:(1,4),9:(1,6),10:(1,8)}
J=nx.erdos_renyi_graph(5,0.75) persons = {0:"John",1:"Mary",2:"Tom",3:"Jane",4:"Peter"} posJ=nx.spring_layout(J) plt.figure() nx.draw(J,pos=posJ,node_color='r',node_size=1000,font_size=10,font_color='#FFFFFF',with_labels=False) nx.draw_networkx_labels(J,posJ,persons,font_size=10,font_color='#FFFFFF') F=nx.erdos_renyi_graph(6,0.6) companies={0:"IBM",1:"McIntosh",2:"Xerox",3:"Samsung",4:"Microsoft",5:"Dell"} posF=nx.spring_layout(F) plt.figure() nx.draw(F,pos=posF,node_color='b',node_size=1800,font_size=10,font_color='#FFFFFF',node_shape='s',with_labels=False) nx.draw_networkx_labels(F,posF,companies,font_size=10,font_color='#FFFFFF') H=nx.bipartite_random_graph(5,6,0.55) posH={0:(0,0),1:(0,2),2:(0,4),3:(0,6),4:(0,8),5:(1,-2),6:(1,0),7:(1,2),8:(1,4),9:(1,6),10:(1,8)} mode1, mode2 = bipartite.sets(H) labels = {0:"John",1:"Mary",2:"Tom",3:"Jane",4:"Peter",5:"IBM",6:"McIntosh",7:"Xerox",8:"Samsung",9:"Microsoft",10:"Dell"} plt.figure(facecolor='w') nx.draw_networkx_nodes(H,pos=posH,nodelist=list(mode1),node_color='r',node_size=1000) nx.draw_networkx_nodes(H,pos=posH,nodelist=list(mode2),node_color='b',node_size=1800,node_shape='s') nx.draw_networkx_edges(H,pos=posH) nx.draw_networkx_labels(H,posH,labels,font_size=10,font_color='#FFFFFF') plt.axis('off') G=nx.Graph() for node in J.nodes(): G.add_node(node,bipartite=0) for edge in J.edges(): G.add_edge(edge[0],edge[1])
def synthetic_multi_bipartite(k,n,m,p=[],No_isolates=True): # nx.bipartite_random_graph(n, m, p, seed=None, directed=False) list_of_Graphs=[] list_of_isolates=[] list_of_Graphs_final=[] for ij in range(k): while True: g=nx.bipartite_random_graph(n, m, p[ij]) bipsets=bipartite.sets(g) if len(bipsets[0])==n and len(bipsets[1])==m: break # print len(bipsets[0]),len(bipsets[1]) list_of_Graphs.append(g)#nx.bipartite_random_graph(n, m, p[ij])) # list_of_Graphs.append(nx.bipartite_gnmk_random_graph(n, m, p[ij])) list_of_isolates.append(nx.isolates(list_of_Graphs[ij])) Gagr=nx.Graph() for i in list_of_Graphs: Gagr.add_edges_from(i.edges()) for nd in i.nodes(data=True): Gagr.add_node(nd[0],attr_dict=nd[1]) # print Gagr.nodes() # print Gagr.edges() G=nx.Graph() #The synthetic two-layer graph # Relabing nodes maps nm=n+m mapping={} for i in range(k): mapping[i]={} bisets=bipartite.sets(list_of_Graphs[i]) # print bisets gh=nx.Graph() # for ij in range(nm): for ij in list_of_Graphs[i].nodes(): coucou=ij+i*nm attrd=list_of_Graphs[i].node[ij] # if ij<n: # print ij,ij in bisets[0],coucou if ij in bisets[0]: mapping[i][ij]='A%i' %coucou gh.add_node('A%i' %coucou,attr_dict=attrd) else: mapping[i][ij]='B%i' %coucou gh.add_node('B%i' %coucou,attr_dict=attrd) # print i,gh.nodes() for ed in list_of_Graphs[i].edges(): gh.add_edge(mapping[i][ed[0]],mapping[i][ed[1]]) # print ed # print mapping[i][ed[0]],mapping[i][ed[1]] # print i,i,gh.nodes(data=True),bipartite.sets(gh) # print gh.edges() # list_of_Graphs_final.append(nx.relabel_nodes(list_of_Graphs[i],mapping[i],copy=True)) list_of_Graphs_final.append(gh) list_of_translation_graphs=[] for ij in range(k-1): H1=nx.Graph() #### A small fix to pain in the ass g1=sorted(list_of_Graphs_final[ij].nodes()) g2=sorted(list_of_Graphs_final[ij+1].nodes()) ####### # print '+++++++++++++++++++++' # print list_of_Graphs[ij].nodes(data=True),bipartite.sets(list_of_Graphs[ij]) # print g1 ,bipartite.sets(list_of_Graphs_final[ij]) # print list_of_Graphs_final[ij].nodes(data=True) # print [ik[0] for ik in list_of_Graphs_final[ij].nodes(data=True) if ik[1]['bipartite']==0] # print [ik[0] for ik in list_of_Graphs_final[ij].nodes(data=True) if ik[1]['bipartite']==1] # print mapping[ij] # # print g2,bipartite.sets(list_of_Graphs_final[ij+1]) # print '==============' g1=list_of_Graphs_final[ij].nodes() g2=list_of_Graphs_final[ij+1].nodes() ####### for ji in range(n+m): H1.add_edge(g1[ji],g2[ji]) #a small fix list_of_translation_graphs.append(H1) for i in list_of_Graphs_final: G.add_edges_from(i.edges()) for nd in i.nodes(data=True): G.add_node(nd[0],attr_dict=nd[1]) # G.add_nodes_from(i.nodes()) # luf=set() # for i in list_of_Graphs_final: # luf=luf.union(set(i.edges())) # luf=list(luf) # G.add_edges_from(luf) luf=set() for i in list_of_translation_graphs: luf=luf.union(set(i.edges())) G.add_edges_from(i.edges()) # print G.nodes(data=True) edgeList=list(luf) # G.add_edges_from(luf) nmap={} for i in mapping: # print i,mapping[i] for j in mapping[i]: # print i,j,mapping[i][j] if j<n: nmap[mapping[i][j]]='A%i' %j else: nmap[mapping[i][j]]='B%i' %j return G, list_of_Graphs_final, Gagr, edgeList ,nmap ,mapping#F
pos[i]=[npos[0]+d,npos[1]] plt.figure() nx.draw(G,pos, with_labels=True,nodelist=top_set,node_color='r') nx.draw(G,pos, with_labels=True,nodelist=botom_set,node_color='b') #Διεπίπεδοι Γράφοι: Κατασκευή από σύνθεση δυο δοθέντων γράφων p1=0.2 p2=0.3 q=0.1 n=50 m=70 k=n d=1 #Οριζόντια διαχωριστική απόσταση μεταξύ των ομάδων στον σχεδιασμό του γράφου. Για το circular_layout αρκεί d=0.5, ενώ για το spring_layout καλύτερα d=2. J=nx.erdos_renyi_graph(n,p1) #Ο γράφος του πρώτου επιπέδου F=nx.erdos_renyi_graph(m,p2) #Ο γράφος του δευτέρου επιπέδου H=nx.bipartite_random_graph(n,m,q) #Ο διμερής γράφος που γεφυρώνει τα δυο επίπεδα G=nx.Graph() #Ο τελικός σύνθετος γράφος for node in J.nodes(): G.add_node(node,bipartite=0) for edge in J.edges(): G.add_edge(edge[0],edge[1]) for edge in F.edges(): G.add_edge(edge[0]+k,edge[1]+k) for node in F.nodes(): G.add_node(node+k,bipartite=1) for edge in H.edges(data=True): G.add_edge(edge[0],edge[1]) pos=nx.spring_layout(G) #pos =nx.circular_layout(G) top_set=set() botom_set=set()
print('Generating [Powerlaw Cluster Graph]') n = 100 m = 5 powerlaw_cluster_graph = nx.powerlaw_cluster_graph(n, m, 0.7) outpath = 'powerlaw_cluster_graph_' + str(n) + '_' + str(m) + '.txt' nx.write_edgelist(powerlaw_cluster_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Random Lobster]') n = 100 lobster_graph = nx.random_lobster(n, 0.7, 0.7) outpath = 'random_lobster_graph_' + str(n) + '.txt' nx.write_edgelist(lobster_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Powerlaw Tree]') n = 100 powerlaw_tree = nx.random_powerlaw_tree(n, 3, None, 10000) outpath = 'powerlaw_tree_' + str(n) + '.txt' nx.write_edgelist(powerlaw_cluster_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Bipartite Random Graph]') n = 100 m = 20 bipartite_random_graph = nx.bipartite_random_graph(n, m, 0.7) outpath = 'bipartite_random_graph_' + str(n) + '_' + str(m) + '.txt' nx.write_edgelist(bipartite_random_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath)
__author__ = 'devashishthakur' import networkx as nx from networkx.algorithms import bipartite from networkx import Graph import random from decimal import Decimal import statistics import json import rpyExample from networkx.readwrite import json_graph pageRankNodeMap = {} random_bipartite_graph = Graph() bipartite_size = 1000 random_bipartite_graph = nx.bipartite_random_graph(bipartite_size, bipartite_size, .33) corrupted_node = {} x, y = bipartite.sets(random_bipartite_graph) # number_of_fake_nodes = 5 min_value_x = min(x) max_value = max(y) min_value = min(y) count = 1 degreeMap = nx.degree(random_bipartite_graph) sortedval = sorted(degreeMap.items(), key=lambda x: x[1], reverse=True) for val in range(10):
import networkx # Test the statistics function import pcd.util import pcd.graphs def test_graph_stats(g): pcd.util.graph_stats(g, level=2, _test=True) # Complete graph test_graph_stats(networkx.complete_graph(10)) # Random graphs: test_graph_stats(networkx.gnp_random_graph(10, .9)) test_graph_stats(networkx.gnp_random_graph(50, .5)) test_graph_stats(networkx.gnp_random_graph(100, .1)) # Directed test_graph_stats(networkx.bipartite_random_graph(100, 100, .25, directed=True)) # Real graph: test_graph_stats(pcd.graphs.karate_club())
import networkx as nx from networkx.algorithms import bipartite import matplotlib.pyplot as plt B = nx.bipartite_random_graph(30, 10, 0.5) X, Y = bipartite.sets(B) # select all refugees # all locals pos = dict() pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1 pos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2 pos = nx.spring_layout(B) nx.draw_networkx_nodes(B, pos=pos, nodelist=X, node_color = 'r') nx.draw_networkx_nodes(B, pos=pos, nodelist=Y, node_color = 'b') nx.draw_networkx_edges(B, pos) plt.show()
#step=0.01 step=0.1 an = p1*n am = p2*m dif=abs(n-m) print "The difference in numbers of nodes is %s" %dif print str("The two peaks are at average degrees: ") + str(an ) + str(" and ") + str(am) print print "Q value| J1peak-F1peak" qli=[] absli=[] #while q<0.9: while q<0.5: J=nx.erdos_renyi_graph(n,p1) #Ο γράφος του πρώτου επιπέδου F=nx.erdos_renyi_graph(m,p2) #Ο γράφος του δευτέρου επιπέδου H=nx.bipartite_random_graph(n,m,q) #Ο διμερής γράφος που γεφυρώνει τα δυο επίπεδα G=nx.Graph() #Ο τελικός σύνθετος γράφος for node in J.nodes(): G.add_node(node,bipartite=0) for edge in J.edges(): G.add_edge(edge[0],edge[1]) J1=G.subgraph(J.nodes()) for edge in F.edges(): G.add_edge(edge[0]+k,edge[1]+k) for node in F.nodes(): G.add_node(node+k,bipartite=1) for edge in H.edges(data=True): G.add_edge(edge[0],edge[1]) J1=G.subgraph(J.nodes())
def test_bipartite_directed(self): G = nx.bipartite_random_graph(10, 10, 0.1, directed=True) assert_true(bipartite.is_bipartite(G))
X, Y = nx.bipartite.sets(G) pos = dict() pos.update((n, (1, i)) for i, n in enumerate(X)) pos.update((n, (2, i)) for i, n in enumerate(Y)) nx.draw_networkx(G, pos=pos, edges=G.edges, node_color=["#A5B0E6" for _ in range(M)] + ["#A3481B" for _ in range(N)]) plt.show() if __name__ == "__main__": M, N = 4, 4 G = nx.DiGraph() G = nx.bipartite_random_graph(M, N, 1.0, seed=None, directed=False) attributes = {} for e in G.edges(): G[e[0]][e[1]]['weight'] = random(1, 11) matrix = [[] for _ in range(M)] for i in range(M): for j in range(M, N + M): try: matrix[i].append(G[i][j]["weight"]) except: pass optimal = HungarianAlgorithm(matrix) print(optimal)
def obtain_graph(args, suffix=""): """Build a Bipartite graph according to command line arguments Arguments: - `args`: command line options """ if getattr(args, "bp"+suffix) is not None: l, r, p = getattr(args, "bp"+suffix) G = bipartite_random_graph(l, r, p) elif getattr(args, "bm"+suffix) is not None: l, r, m = getattr(args, "bm"+suffix) G = bipartite_gnmk_random_graph(l, r, m) elif getattr(args, "bd"+suffix) is not None: l, r, d = getattr(args, "bd"+suffix) G = bipartite_random_left_regular(l, r, d) elif getattr(args, "bregular"+suffix) is not None: l, r, d = getattr(args, "bregular"+suffix) G = bipartite_random_regular(l, r, d) elif getattr(args, "bshift"+suffix) is not None: N, M, pattern = getattr(args, "bshift"+suffix) G = bipartite_shift(N, M, pattern) elif getattr(args, "bcomplete"+suffix) is not None: l, r = getattr(args, "bcomplete"+suffix) G = complete_bipartite_graph(l, r) # Workaround: the bipartite labels are missing in old version of networkx for i in range(0, l): G.add_node(i, bipartite=0) for i in range(l, l+r): G.add_node(i, bipartite=1) elif getattr(args, "graphformat"+suffix) is not None: try: print("INFO: reading bipartite graph {} from '{}'".format(suffix, getattr(args, "input"+suffix).name), file=sys.stderr) G = readGraph(getattr(args, "input"+suffix), "bipartite", getattr(args, "graphformat"+suffix)) except ValueError as e: print("ERROR ON '{}'. {}".format( getattr(args, "input"+suffix).name, e), file=sys.stderr) exit(-1) else: raise RuntimeError( "Command line does not specify a bipartite graph") # Graph modifications if getattr(args, "plantbiclique"+suffix) is not None: l, r = getattr(args, "plantbiclique"+suffix) left, right = bipartite_sets(G) if l > len(left) or r > len(right): raise ValueError("Clique cannot be larger than graph") left = random.sample(left, l) right = random.sample(right, r) for v, w in product(left, right): G.add_edge(v, w) if getattr(args, "addedges"+suffix) is not None: k = getattr(args, "addedges"+suffix) G.add_edges_from(sample_missing_edges(G, k)) if hasattr(G, 'name'): G.name = "{} with {} new random edges".format(G.name, k) # Output the graph is requested if getattr(args, "savegraph"+suffix) is not None: writeGraph(G, getattr(args, "savegraph"+suffix), 'bipartite', getattr(args, "graphformat"+suffix)) return G
import networkx as nx from networkx.algorithms import bipartite from networkx import Graph import random from decimal import Decimal import statistics import json import rpyExample from networkx.readwrite import json_graph pageRankNodeMap = {} random_bipartite_graph = Graph() bipartite_size = 1000 random_bipartite_graph = nx.bipartite_random_graph(bipartite_size,bipartite_size,.33) corrupted_node = {} x, y = bipartite.sets(random_bipartite_graph) # number_of_fake_nodes = 5 min_value_x = min(x) max_value = max(y) min_value = min(y) count = 1 degreeMap = nx.degree(random_bipartite_graph) sortedval = sorted(degreeMap.items(),key = lambda x : x[1],reverse=True) for val in range(10):