def test_single_nodes(self): # single nodes G = nx.complete_bipartite_graph(2, 3) G.add_edge(2, 4) sbn = sb(G, nodes=[1, 2]) assert_almost_equal(sbn[1], 0.85, places=2) assert_almost_equal(sbn[2], 0.77, places=2) G = nx.complete_bipartite_graph(2, 3) G.add_edge(0, 1) sbn = sb(G, nodes=[1, 2]) assert_almost_equal(sbn[1], 0.73, places=2) assert_almost_equal(sbn[2], 0.82, places=2)
def test_single_nodes(self): # single nodes G=nx.complete_bipartite_graph(2,3) G.add_edge(2,4) sbn=sb(G,nodes=[1,2]) assert_almost_equal(sbn[1],0.85,places=2) assert_almost_equal(sbn[2],0.77,places=2) G=nx.complete_bipartite_graph(2,3) G.add_edge(0,1) sbn=sb(G,nodes=[1,2]) assert_almost_equal(sbn[1],0.73,places=2) assert_almost_equal(sbn[2],0.82,places=2)
def test_single_nodes(self): # single nodes G = nx.complete_bipartite_graph(2, 3) G.add_edge(2, 4) sbn = sb(G, nodes=[1, 2]) assert sbn[1] == pytest.approx(0.85, abs=1e-2) assert sbn[2] == pytest.approx(0.77, abs=1e-2) G = nx.complete_bipartite_graph(2, 3) G.add_edge(0, 1) sbn = sb(G, nodes=[1, 2]) assert sbn[1] == pytest.approx(0.73, abs=1e-2) assert sbn[2] == pytest.approx(0.82, abs=1e-2)
def setup_class(cls): cls.P4 = nx.path_graph(4) cls.K3 = nx.complete_bipartite_graph(3, 3) cls.C4 = nx.cycle_graph(4) cls.davis = nx.davis_southern_women_graph() cls.top_nodes = [n for n, d in cls.davis.nodes(data=True) if d['bipartite'] == 0]
def generate_matching_graph(): matching_graph = nx.complete_bipartite_graph(Settings.NUM_LEFT, Settings.NUM_RIGHT) for _, _, d in matching_graph.edges(data=True): d['weight'] = random.randint(*Settings.MATCHING_WEIGHTS_LIMITS) return matching_graph
def test_k23(self): """Test fault-tolerance of a complete bipartite graph K_{2,3}""" stack_roots = {i: 1 for i in range(2)} dp_links = FaucetTopoGenerator.dp_links_networkx_graph( networkx.complete_bipartite_graph(2, 3)) self.set_up(self.NUM_DPS, self.NUM_VLANS, dp_links, stack_roots) self.network_function()
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 generate_connection_graph(graph_type, params, count): lower_type = graph_type.lower() if lower_type == 'complete': assert (len(params) == 0) return networkx.complete_graph(count) elif lower_type == 'complete-bipartite': assert (len(params) == 2) assert (int(params[0]) > 0.0) assert (int(params[1]) > 0.0) n1 = int(round(count * float(params[0]) / float(params[1]))) n2 = int(round(count * float(params[1]) / float(params[0]))) n1 = 1 if n1 < 1 else n1 n2 = 1 if n2 < 1 else n2 return networkx.complete_bipartite_graph(n1, n2) elif lower_type == 'circular-ladder': assert (len(params) == 0) return networkx.circular_ladder_graph(count) elif lower_type == 'cycle': assert (len(params) == 0) return networkx.cycle_graph(count) elif lower_type == 'periodic-2grid': assert (len(params) == 2) assert (int(params[0]) > 0.0) assert (int(params[1]) > 0.0) width = int(round(math.sqrt(count * float(params[0]) / float(params[1])))) height = int(round(math.sqrt(count * float(params[1]) / float(params[0])))) width = 1 if width < 1 else width height = 1 if height < 1 else height return networkx.grid_2d_graph(width, height, True) elif lower_type == 'nonperiodic-2grid': assert (len(params) == 2) assert (int(params[0]) > 0.0) assert (int(params[1]) > 0.0) width = int(round(math.sqrt(count * float(params[0]) / float(params[1])))) height = int(round(math.sqrt(count * float(params[1]) / float(params[0])))) width = 1 if width < 1 else width height = 1 if height < 1 else height return networkx.grid_2d_graph(width, height, False) elif lower_type == 'hypercube': assert (len(params) == 0) return networkx.hypercube_graph(int(round(math.log(count, 2)))) elif lower_type == 'star': assert (len(params) == 0) return networkx.star_graph(count - 1) elif lower_type == 'wheel': assert (len(params) == 0) return networkx.wheel_graph(count) elif lower_type == 'erdos-reyni': assert (len(params) == 1) return networkx.erdos_renyi_graph(count, float(params[0])) elif lower_type == 'watts-strogatz': assert (len(params) == 2) if int(params[0]) >= count / 2: k = int(count / 2 - 1) else: k = int(params[0]) return networkx.connected_watts_strogatz_graph(count, k, int(params[1])) else: print "Unknown graph type {}".format(lower_type) assert False
def test_create(): g0 = create_test_heterograph() g1 = create_test_heterograph1() g2 = create_test_heterograph2() assert set(g0.ntypes) == set(g1.ntypes) == set(g2.ntypes) assert set(g0.canonical_etypes) == set(g1.canonical_etypes) == set( g2.canonical_etypes) # create from nx complete bipartite graph nxg = nx.complete_bipartite_graph(3, 4) g = dgl.bipartite(nxg, 'user', 'plays', 'game') assert g.ntypes == ['user', 'game'] assert g.etypes == ['plays'] assert g.number_of_edges() == 12 # create from scipy spmat = ssp.coo_matrix(([1, 1, 1], ([0, 0, 1], [2, 3, 2])), shape=(4, 4)) g = dgl.graph(spmat) assert g.number_of_nodes() == 4 assert g.number_of_edges() == 3 # test inferring number of nodes for heterograph g = dgl.heterograph({ ('l0', 'e0', 'l1'): [(0, 1), (0, 2)], ('l0', 'e1', 'l2'): [(2, 2)], ('l2', 'e2', 'l2'): [(1, 1), (3, 3)], }) assert g.number_of_nodes('l0') == 3 assert g.number_of_nodes('l1') == 3 assert g.number_of_nodes('l2') == 4
def complete_bipartite_graph(n, m=None): if m is None: m = n G = nx.complete_bipartite_graph(m, n) G.name = 'bipartite' G.graph['pos'] = nx.bipartite_layout(G, nx.bipartite.sets(G)[0]) return G
def ClawGraph(): """ Returns a claw graph. A claw graph is named for its shape. It is actually a complete bipartite graph with (n1, n2) = (1, 3). PLOTTING: See CompleteBipartiteGraph. EXAMPLES: Show a Claw graph :: sage: (graphs.ClawGraph()).show() # long time Inspect a Claw graph :: sage: G = graphs.ClawGraph() sage: G Claw graph: Graph on 4 vertices """ pos_dict = {0:(0,1),1:(-1,0),2:(0,0),3:(1,0)} import networkx G = networkx.complete_bipartite_graph(1,3) return graph.Graph(G, pos=pos_dict, name="Claw graph")
def test_complete_bipartite(self): G = nx.complete_bipartite_graph(6, 9) result = BytesIO() nx.write_sparse6(G, result) # Compared with sage expected = b'>>sparse6<<:Nk' + b'?G`cJ' * 9 + b'\n' assert_equal(result.getvalue(), expected)
def generate_bipartite_graph_two_groups_sparse(num_nodes, diff=.1, other_val=0): ''' Create bipartite graph where each node has three edges to the other side ''' G = nx.complete_bipartite_graph(num_nodes, num_nodes) #two groups in bipartite graph U = list(nx.bipartite.sets(G)[0]) V = list(nx.bipartite.sets(G)[1]) mo = MatchingOracle(G) d = len(mo.edgelist) thetastar = np.zeros((d, )) for i in range(num_nodes): thetastar[mo.edge_to_idx[(U[i], V[i])]] = 1 for i in range(num_nodes): thetastar[mo.edge_to_idx[(U[i - 1], V[i])]] = 1 - diff np.putmask(thetastar, thetastar == 0, other_val) return G, thetastar
def test_write_sparse6(self): fh = StringIO() nx.write_sparse6(nx.complete_bipartite_graph(6,9), fh) fh.seek(0) assert_equal(fh.read(), '>>sparse6<<:Nk?G`cJ?G`cJ?G`cJ?G`'+ 'cJ?G`cJ?G`cJ?G`cJ?G`cJ?G`cJ\n')
def get_max_bipartite_graph(self, framedif=1): """ Builds a bipartite graph with inverse of euclidian distance as the edge weights, first set contains points in the current frame, second set contains points in the next frame plus a dummy point for each point in the first frame. Weights of edges leading to dummy points are set to nearly maximum distance. :param framedif: How many timeframes back do we look for potential matches, timeframe=1 means only looking at the current one. """ # Initialize lists of existing points and new points, add dummy points into new points list old_points = self.get_last_frame(framedif) new_points = [] for coord in self.frame_list[self.timeframe + 1]: if coord != (-1, -1, -1): new_points.append(coord) for i in range(len(old_points)): new_points.append((-1, -1, -1)) # Build a bipartite graph, set weights to inverse of euclidean distance G = nx.complete_bipartite_graph(len(old_points), len(new_points)) for i in range(0, len(old_points)): for j in range(0, len(new_points)): if new_points[j] != (-1, -1, -1): dist = anisotropic_euclid_distance(old_points[i], new_points[j]) else: dist = self.maxdist - 0.0001 G.edge[i][j + len(old_points)]['weight'] = dist G.node[i]['coordinates'] = old_points[i] G.node[j + len(old_points)]['coordinates'] = new_points[j] return G
def test_write_sparse6(self): fh = StringIO() nx.write_sparse6(nx.complete_bipartite_graph(6, 9), fh) fh.seek(0) assert_equal( fh.read(), '>>sparse6<<:Nk?G`cJ?G`cJ?G`cJ?G`' + 'cJ?G`cJ?G`cJ?G`cJ?G`cJ?G`cJ\n')
def test_bipartite_layout(self): G = nx.complete_bipartite_graph(3,5) top, bottom = nx.bipartite.sets(G) vpos = nx.bipartite_layout(G, top) assert_equal(len(vpos), len(G)) top_x = vpos[list(top)[0]][0] bottom_x = vpos[list(bottom)[0]][0] for node in top: assert_equal(vpos[node][0], top_x) for node in bottom: assert_equal(vpos[node][0], bottom_x) vpos = nx.bipartite_layout(G, top, align='horizontal', center=(2,2), scale=2, aspect_ratio=1) assert_equal(len(vpos), len(G)) top_y = vpos[list(top)[0]][1] bottom_y = vpos[list(bottom)[0]][1] for node in top: assert_equal(vpos[node][1], top_y) for node in bottom: assert_equal(vpos[node][1], bottom_y) assert_raises(ValueError, nx.bipartite_layout, G, top, align='foo')
def calculate_rental_harmony(matrix: np.ndarray): print("Initial Matrix:\n", matrix, "\n") # Variable which holds the matrix's dimensions questions = len(matrix[0]) students = len(matrix) partial_value = int(questions / students) # Define an empty complete bipartite graph G = nx.complete_bipartite_graph(0, 0) # Defining vertex groups students_nodes = [] questions_nodes = [] # Filling vertex groups, one group will be the vertices of the students, # and the other group will be the vertices of the question number for row in range(len(matrix)): students_nodes.append("Student " + str(row + 1)) for column in range(questions): questions_nodes.append("Question " + str(column + 1)) # Assign the vertex groups to the graph G.add_nodes_from(students_nodes, bipartite=1) G.add_nodes_from(questions_nodes, bipartite=0) # Filling vertex groups, each cell describes the level of effort of the # student in a row, for the question in the column, multiply by -1 for row in range(len(matrix)): for column in range(len(matrix[0])): G.add_weighted_edges_from([(students_nodes[row], questions_nodes[column], -1 * matrix[row][column])]) # For all edges in the graph, search for the edges with the lowest weights, # and insert it to the ans array, until the number of edges remains as the number of questions (matrix columns) ans = [] while len(ans) < questions: min_weights = nx.max_weight_matching(G, True) for u, v in nx.max_weight_matching(G, True): if u.__contains__("Question"): ans.append(str(v) + " :" + str(u)[8:]) for nodes in (list(G.neighbors(u))): if nodes is not v: G.remove_edge(nodes, u) else: ans.append(str(u) + " :" + str(v)[8:]) for nodes in (list(G.neighbors(v))): if nodes is not u: G.remove_edge(nodes, v) G.remove_edges_from(min_weights) # Convert the array to a sorted numpy array (Descending) ans = np.array(sorted(ans)) # Print the total effort's sum for each student print("The divide questions for each student:\n", ans, "\n") for row in range(students): student_sum = 0 for value in range(partial_value * row, partial_value * row + partial_value): student_sum += matrix[row][int(str(ans[value])[12:]) - 1] print("For student {}, Total effort for questions is: {}".format(row + 1, student_sum))
def misc_1(): def jaccard(G, u, v): unbrs = set(G[u]) vnbrs = set(G[v]) return float(len(unbrs & vnbrs)) / len(unbrs | vnbrs) def my_weight(G, u, v, weight='weight'): w = 0 print('@@@@@@@@@@@@@@@@') print(G) print((G[u])) print(type(u)) print(G.edges()) print(set(G[u]) & set(G[v])) for nbr in set(G[u]) & set(G[v]): print('{{{{{{{{{{{{{{{{{{') print((nbr)) # print(G[u][nbr].get(weight, 6)) # x0, y0 = G.node[edge[0]]['pos'] w += G[u][nbr][weight] + G[v][nbr][weight] print('w=', w) # w += G[u][nbr].get(weight, 1) + G[v][nbr].get(weight, 1) # w += G.edge[u][nbr].get(weight, 1) + G.edge[v][nbr].get(weight, 1) return w B = nx.complete_bipartite_graph(2, 2) # B = nx.complete_bipartite_graph(3, 3) print('iiiiiiiiiiiiiiiiii') for edge in B.edges(data=True): print(edge) j = 1 for i in B.edges(data=True): print('///////////////') # B[i[0]][i[1]]['weight'] = 22 # print(B[i[0]]) # print(B[i[0]][i[1]]) i[2]['weight'] = j # B[i[0]][i[1]]['weight'] = 22 does the same thing j = j + 1 for edge in B.edges(data=True): print(edge) G = bipartite.generic_weighted_projected_graph(B, [0, 1]) # bi = graphx() # bi.plot_graph(B,'complete') # bi.plot_graph(G,'complete') print(G.edges(data=True)) for edge in G.edges(data=True): # print() print(edge) G = bipartite.generic_weighted_projected_graph(B, [0, 1], weight_function=my_weight) print('Final value') print(G.edges(data=True))
def ClawGraph(): """ Returns a claw graph. A claw graph is named for its shape. It is actually a complete bipartite graph with (n1, n2) = (1, 3). PLOTTING: See CompleteBipartiteGraph. EXAMPLES: Show a Claw graph :: sage: (graphs.ClawGraph()).show() # long time Inspect a Claw graph :: sage: G = graphs.ClawGraph() sage: G Claw graph: Graph on 4 vertices """ pos_dict = {0: (0, 1), 1: (-1, 0), 2: (0, 0), 3: (1, 0)} import networkx G = networkx.complete_bipartite_graph(1, 3) return graph.Graph(G, pos=pos_dict, name="Claw graph")
def test_bipartite_layout(self): G = nx.complete_bipartite_graph(3, 5) top, bottom = nx.bipartite.sets(G) vpos = nx.bipartite_layout(G, top) assert len(vpos) == len(G) top_x = vpos[list(top)[0]][0] bottom_x = vpos[list(bottom)[0]][0] for node in top: assert vpos[node][0] == top_x for node in bottom: assert vpos[node][0] == bottom_x vpos = nx.bipartite_layout(G, top, align='horizontal', center=(2, 2), scale=2, aspect_ratio=1) assert len(vpos) == len(G) top_y = vpos[list(top)[0]][1] bottom_y = vpos[list(bottom)[0]][1] for node in top: assert vpos[node][1] == top_y for node in bottom: assert vpos[node][1] == bottom_y pytest.raises(ValueError, nx.bipartite_layout, G, top, align='foo')
def test_complete_bipartite(self): G = nx.complete_bipartite_graph(6, 9) result = BytesIO() nx.write_sparse6(G, result) # Compared with sage expected = b'>>sparse6<<:Nk' + b'?G`cJ' * 9 + b'\n' assert result.getvalue() == expected
class GraphType: BALANCED_TREE = ('Balanced tree', _balanced_tree) BARBELL = ('Barbell', lambda n: nx.barbell_graph(int(n*.4), int(n*.3))) CIRCULAR_LADDER = ('Circular ladder', lambda n: nx.circular_ladder_graph(int(n/2))) COMPLETE = ('Complete', lambda n: nx.complete_graph(int(n))) COMPLETE_BIPARTITE = ('Complete bipartite', lambda n: nx.complete_bipartite_graph(int(n*.6), int(n*.4))) CYCLE = ('Cycle', lambda n: nx.cycle_graph(int(n))) GRID = ('Grid', lambda n: nx.grid_graph([int(np.sqrt(n))]*2)) HYPERCUBE = ('Hypercube', _hypercube) LADDER = ('Ladder', lambda n: nx.ladder_graph(int(n/2))) LOBSTER = ('Lobster', lambda n: nx.random_lobster(int(n / (1 + .7 + .7*.5)), .7, .5)) LOLLIPOP = ('Lollipop', lambda n: nx.lollipop_graph(int(n/2), int(n/2))) PATH = ('Path', lambda n: nx.path_graph(int(n))) REGULAR = ('Regular', lambda n: nx.random_regular_graph(np.random.randint(10)*2, n)) SCALEFREE = ('Scale-free', lambda n: nx.scale_free_graph(int(n))) SHELL = ('Shell', lambda n: nx.random_shell_graph([(int(n*.1), int(n*.1), .2), (int(n*.3), int(n*.3), .8), (int(n*.6), int(n*.6), .5)])) STAR = ('Star', lambda n: nx.star_graph(int(n - 1))) WAXMAN = ('Waxman', lambda n: nx.waxman_graph(int(n))) WHEEL = ('Wheel', lambda n: nx.wheel_graph(int(n))) all = (BALANCED_TREE, BARBELL, CIRCULAR_LADDER, COMPLETE, COMPLETE_BIPARTITE, CYCLE, GRID, HYPERCUBE, LADDER, LOBSTER, LOLLIPOP, PATH, REGULAR, SCALEFREE, SHELL, STAR, WAXMAN, WHEEL)
def test_create(): g0 = create_test_heterograph() g1 = create_test_heterograph1() g2 = create_test_heterograph2() assert set(g0.ntypes) == set(g1.ntypes) == set(g2.ntypes) assert set(g0.canonical_etypes) == set(g1.canonical_etypes) == set(g2.canonical_etypes) # create from nx complete bipartite graph nxg = nx.complete_bipartite_graph(3, 4) g = dgl.bipartite(nxg, 'user', 'plays', 'game') assert g.ntypes == ['user', 'game'] assert g.etypes == ['plays'] assert g.number_of_edges() == 12 # create from scipy spmat = ssp.coo_matrix(([1,1,1], ([0, 0, 1], [2, 3, 2])), shape=(4, 4)) g = dgl.graph(spmat) assert g.number_of_nodes() == 4 assert g.number_of_edges() == 3 # test inferring number of nodes for heterograph g = dgl.heterograph({ ('l0', 'e0', 'l1'): [(0, 1), (0, 2)], ('l0', 'e1', 'l2'): [(2, 2)], ('l2', 'e2', 'l2'): [(1, 1), (3, 3)], }) assert g.number_of_nodes('l0') == 3 assert g.number_of_nodes('l1') == 3 assert g.number_of_nodes('l2') == 4 # test if validate flag works # h**o graph fail = False try: g = dgl.graph( ([0, 0, 0, 1, 1, 2], [0, 1, 2, 0, 1, 2]), card=2, validate=True ) except DGLError: fail = True finally: assert fail, "should catch a DGLError because node ID is out of bound." # bipartite graph def _test_validate_bipartite(card): fail = False try: g = dgl.bipartite( ([0, 0, 1, 1, 2], [1, 1, 2, 2, 3]), card=card, validate=True ) except DGLError: fail = True finally: assert fail, "should catch a DGLError because node ID is out of bound." _test_validate_bipartite((3, 3)) _test_validate_bipartite((2, 4))
def dispatch(self, dispatch_observ): """ Compute the assignment between drivers and passengers at each time step :param dispatch_observ: a list of dict, the key in the dict includes: order_id, int driver_id, int order_driver_distance, float order_start_location, a list as [lng, lat], float order_finish_location, a list as [lng, lat], float driver_location, a list as [lng, lat], float timestamp, int order_finish_timestamp, int day_of_week, int reward_units, float pick_up_eta, float :return: a list of dict, the key in the dict includes: order_id and driver_id, the pair indicating the assignment """ """ dispatch_observ.sort(key=lambda od_info: od_info['reward_units'], reverse=True) assigned_order = set() assigned_driver = set() dispatch_action = [] for od in dispatch_observ: # make sure each order is assigned to one driver, and each driver is assigned with one order if (od["order_id"] in assigned_order) or (od["driver_id"] in assigned_driver): continue assigned_order.add(od["order_id"]) assigned_driver.add(od["driver_id"]) dispatch_action.append(dict(order_id=od["order_id"], driver_id=od["driver_id"])) return dispatch_action """ id_order = list({}.fromkeys(od['order_id'] for od in dispatch_observ).keys()) id_driver = list({}.fromkeys(od['driver_id'] for od in dispatch_observ).keys()) order_id = dict((order, idx) for idx, order in enumerate(id_order)) driver_id = dict((driver, idx) for idx, driver in enumerate(id_driver)) N = len(order_id) M = len(driver_id) import networkx as nx G = nx.complete_bipartite_graph(N, M) for od in dispatch_observ: order = order_id[od['order_id']] driver = N + driver_id[od['driver_id']] G.edges[order, driver]['weight'] = -od['reward_units'] from networkx.algorithms.bipartite.matching import minimum_weight_full_matching match = minimum_weight_full_matching(G) dispatch_action = [] for idx, order in enumerate(id_order): dispatch_action.append({ 'driver_id': id_driver[match[idx] - N], 'order_id': order }) return dispatch_action
def bipartite_gnmk_random_graph(n, m, k, seed=None, directed=False): """Return a random bipartite nxgraph G_{n,m,k}. Produces a bipartite nxgraph chosen randomly out of the set of all graphs with n top nodes, m bottom nodes, and k edges. Parameters ---------- n : int The number of nodes in the first bipartite set. m : int The number of nodes in the second bipartite set. k : int The number of edges seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=False) If True return a directed nxgraph Examples -------- G = nx.bipartite_gnmk_random_graph(10,20,50) See Also -------- gnm_random_graph Notes ----- If k > m * n then a complete bipartite nxgraph is returned. This nxgraph is a bipartite version of the `G_{nm}` random nxgraph model. """ G = networkx.Graph() G=_add_nodes_with_bipartite_label(G,n,m) if directed: G=nx.DiGraph(G) G.name="bipartite_gnm_random_graph(%s,%s,%s)"%(n,m,k) if seed is not None: random.seed(seed) if n == 1 or m == 1: return G max_edges = n*m # max_edges for bipartite networks if k >= max_edges: # Maybe we should raise an exception here return networkx.complete_bipartite_graph(n, m, create_using=G) top = [n for n,d in G.nodes(data=True) if d['bipartite']==0] bottom = list(set(G) - set(top)) edge_count = 0 while edge_count < k: # generate random edge,u,v u = random.choice(top) v = random.choice(bottom) if v in G[u]: continue else: G.add_edge(u,v) edge_count += 1 return G
def bipartite_gnmk_random_graph(n, m, k, seed=None, directed=False): """Return a random bipartite graph G_{n,m,k}. Produces a bipartite graph chosen randomly out of the set of all graphs with n top nodes, m bottom nodes, and k edges. Parameters ---------- n : int The number of nodes in the first bipartite set. m : int The number of nodes in the second bipartite set. k : int The number of edges seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=False) If True return a directed graph Examples -------- G = nx.bipartite_gnmk_random_graph(10,20,50) See Also -------- gnm_random_graph Notes ----- If k > m * n then a complete bipartite graph is returned. This graph is a bipartite version of the `G_{nm}` random graph model. """ G = networkx.Graph() G = _add_nodes_with_bipartite_label(G, n, m) if directed: G = nx.DiGraph(G) G.name = "bipartite_gnm_random_graph(%s,%s,%s)" % (n, m, k) if seed is not None: random.seed(seed) if n == 1 or m == 1: return G max_edges = n * m # max_edges for bipartite networks if k >= max_edges: # Maybe we should raise an exception here return networkx.complete_bipartite_graph(n, m, create_using=G) top = [n for n, d in G.nodes(data=True) if d['bipartite'] == 0] bottom = list(set(G) - set(top)) edge_count = 0 while edge_count < k: # generate random edge,u,v u = random.choice(top) v = random.choice(bottom) if v in G[u]: continue else: G.add_edge(u, v) edge_count += 1 return G
def test_minimum_weight_full_matching_different_weight_key(self): G = nx.complete_bipartite_graph(2, 2) G.add_edge(0, 2, mass=2) G.add_edge(0, 3, mass=0.2) G.add_edge(1, 2, mass=1) G.add_edge(1, 3, mass=2) matching = minimum_weight_full_matching(G, weight="mass") assert matching == {0: 3, 1: 2, 2: 1, 3: 0}
def build_network(): global BG #create bipartite network BG = nx.complete_bipartite_graph(num_left, num_right) # add nodes left, right = nx.bipartite.sets(BG) # add edges BG.add_weighted_edges_from((u, v, random.random()) for u, v in BG.edges())
def test_invalid_line_graphs(self): # a claw is not a line graph K13 = nx.complete_bipartite_graph(1, 3) assert_raises(nx.NetworkXError, inverse_line_graph, K13) # neither is "K5 minus an edge": K5me = nx.complete_graph(5) K5me.remove_edge(0,1) assert_raises(nx.NetworkXError, inverse_line_graph, K5me)
def test_k_n_m(self): for n in range(2, 6): for m in range(2, 6): g = nx.complete_bipartite_graph(n, m) if n < 3 or m < 3: self.assertTrue(is_planar(g)) else: self.assertFalse(is_planar(g))
def test_k_n_m(self): for n in range(2, 5): for m in range(2, 5): g = nx.complete_bipartite_graph(n, m) if n < 3 or m < 3: self.assertEqual(thickness.thickness(g), 1) else: self.assertEqual(thickness.thickness(g), 2)
def setUp(self): self.P4 = nx.path_graph(4) self.K3 = nx.complete_bipartite_graph(3, 3) self.C4 = nx.cycle_graph(4) self.davis = nx.davis_southern_women_graph() self.top_nodes = [ n for n, d in self.davis.nodes(data=True) if d['bipartite'] == 0 ]
def test_minimum_weight_full_matching_negative_weights(self): G = nx.complete_bipartite_graph(2, 2) G.add_edge(0, 2, weight=-2) G.add_edge(0, 3, weight=0.2) G.add_edge(1, 2, weight=-2) G.add_edge(1, 3, weight=0.3) matching = minimum_weight_full_matching(G) assert matching == {0: 3, 1: 2, 2: 1, 3: 0}
def test_complete_2_partite_graph(self): """Tests that the complete 2-partite graph is the complete bipartite graph. """ G = nx.complete_multipartite_graph(2, 3) H = nx.complete_bipartite_graph(2, 3) assert_nodes_equal(G, H) assert_edges_equal(G.edges(), H.edges())
def gen(n=10, s=1): g, p = nx.complete_bipartite_graph(n, n), {} a, b = nx.bipartite.sets(g) seed(s) for u, v in zip(a, b): p[u] = deque(sample(b, n)) p[v] = sample(a, n) pprint(p) return g, p
def two_tier_topology(n_core, n_edge, n_hosts): """ Return a two-tier datacenter topology. This topology comprises switches organized in two tiers (core and edge) and hosts connected to edge routers. Each core switch is connected to each edge switch while each host is connected to exactly one edge switch. Each node has two attributes: * type: can either be *switch* or *host* * tier: can either be *core*, *edge* or *leaf*. Nodes in the leaf tier are only host, while all core and edge nodes are switches. Each edge has an attribute type as well which can either be *core_edge* if it connects a core and an edge switch or *edge_leaf* if it connects an edge switch to a host. Parameters ---------- n_core : int Total number of core switches n_edge : int Total number of edge switches n_hosts : int Number of hosts connected to each edge switch. Returns ------- topology : DatacenterTopology """ # validate input arguments if not isinstance(n_core, int) and not isinstance(n_edge, int) \ and not isinstance(n_hosts, int): raise TypeError('n_core, n_edge and n_hosts must be integers') if n_core < 1 or n_edge < 1 or n_hosts < 1: raise ValueError('n_core, n_edge and n_hosts must be positive') topo = DatacenterTopology(nx.complete_bipartite_graph(n_core, n_edge)) topo.name = "two_tier_topology(%d,%d,%d)" % (n_core, n_edge, n_hosts) topo.graph['type'] = 'two_tier' for u in range(n_core): topo.node[u]['tier'] = 'core' topo.node[u]['type'] = 'switch' for v in topo.edge[u]: topo.edge[u][v]['type'] = 'core_edge' for u in range(n_core, n_core + n_edge): topo.node[u]['tier'] = 'edge' topo.node[u]['type'] = 'switch' for _ in range(n_hosts): v = topo.number_of_nodes() topo.add_node(v) topo.node[v]['tier'] = 'leaf' topo.node[v]['type'] = 'host' topo.add_edge(u, v, type='edge_leaf') return topo
def test_is_distance_regular(self): assert_true(nx.is_distance_regular(nx.icosahedral_graph())) assert_true(nx.is_distance_regular(nx.petersen_graph())) assert_true(nx.is_distance_regular(nx.cubical_graph())) assert_true(nx.is_distance_regular(nx.complete_bipartite_graph(3,3))) assert_true(nx.is_distance_regular(nx.tetrahedral_graph())) assert_true(nx.is_distance_regular(nx.dodecahedral_graph())) assert_true(nx.is_distance_regular(nx.pappus_graph())) assert_true(nx.is_distance_regular(nx.heawood_graph())) assert_true(nx.is_distance_regular(nx.cycle_graph(3))) # no distance regular assert_false(nx.is_distance_regular(nx.path_graph(4)))
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 setUp(self): try: global nx import networkx as nx except ImportError: raise SkipTest('networkx not available.') self.planar=[] self.planar.extend([nx.path_graph(5), nx.complete_graph(4)]) self.non_planar=[] self.non_planar.extend([nx.complete_graph(5), nx.complete_bipartite_graph(3,3)])
def check_counterexample(G, sub_graph): """Raises an exception if the counterexample is wrong. Parameters ---------- G : NetworkX graph subdivision_nodes : set A set of nodes inducing a subgraph as a counterexample """ # 1. Create the sub graph sub_graph = nx.Graph(sub_graph) # 2. Remove self loops for u in sub_graph: if sub_graph.has_edge(u, u): sub_graph.remove_edge(u, u) # keep track of nodes we might need to contract contract = list(sub_graph) # 3. Contract Edges while len(contract) > 0: contract_node = contract.pop() if contract_node not in sub_graph: # Node was already contracted continue degree = sub_graph.degree[contract_node] # Check if we can remove the node if degree == 2: # Get the two neighbors neighbors = iter(sub_graph[contract_node]) u = next(neighbors) v = next(neighbors) # Save nodes for later contract.append(u) contract.append(v) # Contract edge sub_graph.remove_node(contract_node) sub_graph.add_edge(u, v) # 4. Check for isomorphism with K5 or K3_3 graphs if len(sub_graph) == 5: if not nx.is_isomorphic(nx.complete_graph(5), sub_graph): raise nx.NetworkXException("Bad counter example.") elif len(sub_graph) == 6: if not nx.is_isomorphic(nx.complete_bipartite_graph(3, 3), sub_graph): raise nx.NetworkXException("Bad counter example.") else: raise nx.NetworkXException("Bad counter example.")
def test_quotient_graph_complete_bipartite(self): """Tests that the quotient graph of the complete bipartite graph under the "same neighbors" node relation is `K_2`. """ G = nx.complete_bipartite_graph(2, 3) # Two nodes are equivalent if they are not adjacent but have the same # neighbor set. same_neighbors = lambda u, v: (u not in G[v] and v not in G[u] and G[u] == G[v]) expected = nx.complete_graph(2) actual = nx.quotient_graph(G, same_neighbors) # It won't take too long to run a graph isomorphism algorithm on such # small graphs. assert_true(nx.is_isomorphic(expected, actual))
def test_generate_graph6(self): assert_equal(nx.generate_graph6(nx.empty_graph(0)), '>>graph6<<?') assert_equal(nx.generate_graph6(nx.empty_graph(1)), '>>graph6<<@') G1 = nx.complete_graph(4) assert_equal(nx.generate_graph6(G1, header=True), '>>graph6<<C~') assert_equal(nx.generate_graph6(G1, header=False), 'C~') G2 = nx.complete_bipartite_graph(6,9) assert_equal(nx.generate_graph6(G2, header=False), 'N??F~z{~Fw^_~?~?^_?') # verified by Sage G3 = nx.complete_graph(67) assert_equal(nx.generate_graph6(G3, header=False), '~?@B' + '~' * 368 + 'w')
def setup(self): """Creates a bipartite graph for use in testing matching algorithms. The bipartite graph has a maximum cardinality matching that leaves vertex 1 and vertex 10 unmatched. The first six numbers are the left vertices and the next six numbers are the right vertices. """ self.simple_graph = nx.complete_bipartite_graph(2, 3) self.simple_solution = {0: 2, 1: 3, 2: 0, 3: 1} edges = [(0, 7), (0, 8), (2, 6), (2, 9), (3, 8), (4, 8), (4, 9), (5, 11)] self.top_nodes = set(range(6)) self.graph = nx.Graph() self.graph.add_nodes_from(range(12)) self.graph.add_edges_from(edges) # Example bipartite graph from issue 2127 G = nx.Graph() G.add_nodes_from([ (1, 'C'), (1, 'B'), (0, 'G'), (1, 'F'), (1, 'E'), (0, 'C'), (1, 'D'), (1, 'I'), (0, 'A'), (0, 'D'), (0, 'F'), (0, 'E'), (0, 'H'), (1, 'G'), (1, 'A'), (0, 'I'), (0, 'B'), (1, 'H'), ]) G.add_edge((1, 'C'), (0, 'A')) G.add_edge((1, 'B'), (0, 'A')) G.add_edge((0, 'G'), (1, 'I')) G.add_edge((0, 'G'), (1, 'H')) G.add_edge((1, 'F'), (0, 'A')) G.add_edge((1, 'F'), (0, 'C')) G.add_edge((1, 'F'), (0, 'E')) G.add_edge((1, 'E'), (0, 'A')) G.add_edge((1, 'E'), (0, 'C')) G.add_edge((0, 'C'), (1, 'D')) G.add_edge((0, 'C'), (1, 'I')) G.add_edge((0, 'C'), (1, 'G')) G.add_edge((0, 'C'), (1, 'H')) G.add_edge((1, 'D'), (0, 'A')) G.add_edge((1, 'I'), (0, 'A')) G.add_edge((1, 'I'), (0, 'E')) G.add_edge((0, 'A'), (1, 'G')) G.add_edge((0, 'A'), (1, 'H')) G.add_edge((0, 'E'), (1, 'G')) G.add_edge((0, 'E'), (1, 'H')) self.disconnected_graph = G
def calcMaxBip(V, empirical_means): # Every time a new complete bipartite graph is constructed here. G = nx.complete_bipartite_graph(V, V) # N.B. Indexing from 0 to K-1 edges = list(G.edges_iter()) for (u, v) in edges: # assign negative weights so that MST calculates MaxST G.add_edge(u, v, weight=-(empirical_means[edges.index((u, v))])) T = nx.max_weight_matching(G) temp = T.edges() output = [0] * len(temp) for indx in range(len(output)): output[indx] = edges.index(temp[indx]) return output # Indices are from 0 to K-1
def test_star_graph(self): assert_true(is_isomorphic(star_graph(0), empty_graph(1))) assert_true(is_isomorphic(star_graph(1), path_graph(2))) assert_true(is_isomorphic(star_graph(2), path_graph(3))) assert_true(is_isomorphic(star_graph(5), nx.complete_bipartite_graph(1,5))) s=star_graph(10) assert_equal(sorted(d for n, d in s.degree()), [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10]) assert_raises(networkx.exception.NetworkXError, star_graph, 10, create_using=DiGraph()) ms=star_graph(10, create_using=MultiGraph()) assert_edges_equal(ms.edges(), s.edges()) G=star_graph("abcdefg") assert_equal(len(G), 7) assert_equal(G.size(), 6)
def test_generic_weighted_projected_graph_custom(self): def jaccard(G, u, v): unbrs = set(G[u]) vnbrs = set(G[v]) return float(len(unbrs & vnbrs)) / len(unbrs | vnbrs) def my_weight(G, u, v, weight="weight"): w = 0 for nbr in set(G[u]) & set(G[v]): w += G.edge[u][nbr].get(weight, 1) + G.edge[v][nbr].get(weight, 1) return w B = nx.complete_bipartite_graph(2, 2) for i, (u, v) in enumerate(B.edges()): B.edge[u][v]["weight"] = i + 1 G = bipartite.generic_weighted_projected_graph(B, [0, 1], weight_function=jaccard) assert_equal(G.edges(data=True), [(0, 1, {"weight": 1.0})]) G = bipartite.generic_weighted_projected_graph(B, [0, 1], weight_function=my_weight) assert_equal(G.edges(data=True), [(0, 1, {"weight": 10})]) G = bipartite.generic_weighted_projected_graph(B, [0, 1]) assert_equal(G.edges(data=True), [(0, 1, {"weight": 2})])
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 k23_like(self): # K2,3-like G=nx.complete_bipartite_graph(2,3) G.add_edge(0,1) assert_almost_equal(sb(G),0.769,places=3) G=nx.complete_bipartite_graph(2,3) G.add_edge(2,4) assert_almost_equal(sb(G),0.829,places=3) G=nx.complete_bipartite_graph(2,3) G.add_edge(2,4) G.add_edge(3,4) assert_almost_equal(sb(G),0.731,places=3) G=nx.complete_bipartite_graph(2,3) G.add_edge(0,1) G.add_edge(2,4) assert_almost_equal(sb(G),0.692,places=3) G=nx.complete_bipartite_graph(2,3) G.add_edge(2,4) G.add_edge(3,4) G.add_edge(0,1) assert_almost_equal(sb(G),0.645,places=3) G=nx.complete_bipartite_graph(2,3) G.add_edge(2,4) G.add_edge(3,4) G.add_edge(2,3) assert_almost_equal(sb(G),0.645,places=3) G=nx.complete_bipartite_graph(2,3) G.add_edge(2,4) G.add_edge(3,4) G.add_edge(2,3) G.add_edge(0,1) assert_almost_equal(sb(G),0.597,places=3)
def test_bipartite(self): G = nx.complete_bipartite_graph(12, 34) indep = nx.maximal_independent_set(G, [4, 5, 9, 10]) assert_equal(sorted(indep), list(range(12)))
def CompleteBipartiteGraph(n1, n2): """ Returns a Complete Bipartite Graph sized n1+n2, with each of the nodes [0,(n1-1)] connected to each of the nodes [n1,(n2-1)] and vice versa. A Complete Bipartite Graph is a graph with its vertices partitioned into two groups, V1 and V2. Each v in V1 is connected to every v in V2, and vice versa. PLOTTING: Upon construction, the position dictionary is filled to override the spring-layout algorithm. By convention, each complete bipartite graph will be displayed with the first n1 nodes on the top row (at y=1) from left to right. The remaining n2 nodes appear at y=0, also from left to right. The shorter row (partition with fewer nodes) is stretched to the same length as the longer row, unless the shorter row has 1 node; in which case it is centered. The x values in the plot are in domain [0,maxn1,n2]. In the Complete Bipartite graph, there is a visual difference in using the spring-layout algorithm vs. the position dictionary used in this constructor. The position dictionary flattens the graph and separates the partitioned nodes, making it clear which nodes an edge is connected to. The Complete Bipartite graph plotted with the spring-layout algorithm tends to center the nodes in n1 (see spring_med in examples below), thus overlapping its nodes and edges, making it typically hard to decipher. Filling the position dictionary in advance adds O(n) to the constructor. Feel free to race the constructors below in the examples section. The much larger difference is the time added by the spring-layout algorithm when plotting. (Also shown in the example below). The spring model is typically described as `O(n^3)`, as appears to be the case in the NetworkX source code. EXAMPLES: Two ways of constructing the complete bipartite graph, using different layout algorithms:: sage: import networkx sage: n = networkx.complete_bipartite_graph(389,157); spring_big = Graph(n) # long time sage: posdict_big = graphs.CompleteBipartiteGraph(389,157) # long time Compare the plotting:: sage: n = networkx.complete_bipartite_graph(11,17) sage: spring_med = Graph(n) sage: posdict_med = graphs.CompleteBipartiteGraph(11,17) Notice here how the spring-layout tends to center the nodes of n1 :: sage: spring_med.show() # long time sage: posdict_med.show() # long time View many complete bipartite graphs with a Sage Graphics Array, with this constructor (i.e., the position dictionary filled):: sage: g = [] sage: j = [] sage: for i in range(9): ....: k = graphs.CompleteBipartiteGraph(i+1,4) ....: g.append(k) sage: for i in range(3): ....: n = [] ....: for m in range(3): ....: n.append(g[3*i + m].plot(vertex_size=50, vertex_labels=False)) ....: j.append(n) sage: G = sage.plot.graphics.GraphicsArray(j) sage: G.show() # long time We compare to plotting with the spring-layout algorithm:: sage: g = [] sage: j = [] sage: for i in range(9): ....: spr = networkx.complete_bipartite_graph(i+1,4) ....: k = Graph(spr) ....: g.append(k) sage: for i in range(3): ....: n = [] ....: for m in range(3): ....: n.append(g[3*i + m].plot(vertex_size=50, vertex_labels=False)) ....: j.append(n) sage: G = sage.plot.graphics.GraphicsArray(j) sage: G.show() # long time Trac ticket #12155:: sage: graphs.CompleteBipartiteGraph(5,6).complement() complement(Complete bipartite graph): Graph on 11 vertices """ pos_dict = {} c1 = 1 # scaling factor for top row c2 = 1 # scaling factor for bottom row c3 = 0 # pad to center if top row has 1 node c4 = 0 # pad to center if bottom row has 1 node if n1 > n2: if n2 == 1: c4 = (n1-1)/2 else: c2 = ((n1-1)/(n2-1)) elif n2 > n1: if n1 == 1: c3 = (n2-1)/2 else: c1 = ((n2-1)/(n1-1)) for i in range(n1): x = c1*i + c3 y = 1 pos_dict[i] = (x,y) for i in range(n1+n2)[n1:]: x = c2*(i-n1) + c4 y = 0 pos_dict[i] = (x,y) import networkx G = networkx.complete_bipartite_graph(n1,n2) return Graph(G, pos=pos_dict, name="Complete bipartite graph")
import shubham import networkx as nx g=nx.complete_bipartite_graph(3,5) shubham.min_cut(g)
def three_tier_topology(n_core, n_aggregation, n_edge, n_hosts): """ Return a three-tier data center topology. This topology comprises switches organized in three tiers (core, aggregation and edge) and hosts connected to edge routers. Each core switch is connected to each aggregation, each edge switch is connected to one aggregation switch and finally each host is connected to exactly one edge switch. Each node has two attributes: * type: can either be *switch* or *host* * tier: can either be *core*, *aggregation*, *edge* or *leaf*. Nodes in the leaf tier are only host, while all core, aggregation and edge nodes are switches. Each edge has an attribute type as well which can either be *core_edge* if it connects a core and an aggregation switch, *aggregation_edge*, if it connects an aggregation and a core switch or *edge_leaf* if it connects an edge switch to a host. The total number of hosts is :math:`n_{aggregation} * n_{edge} * n_{hosts}`. Parameters ---------- n_core : int Total number of core switches n_aggregation : int Total number of aggregation switches n_edge : int Number of edge switches per each each aggregation switch n_hosts : int Number of hosts connected to each edge switch. Returns ------- topology : DatacenterTopology """ # Validate input arguments if not isinstance(n_core, int) or not isinstance(n_aggregation, int) \ or not isinstance(n_edge, int) \ or not isinstance(n_hosts, int): raise TypeError('n_core, n_edge, n_aggregation and n_hosts '\ 'must be integers') if n_core < 1 or n_aggregation < 1 or n_edge < 1 or n_hosts < 1: raise ValueError('n_core, n_aggregation, n_edge and n_host '\ 'must be positive') topo = DatacenterTopology(nx.complete_bipartite_graph(n_core, n_aggregation)) topo.name = "three_tier_topology(%d,%d,%d,%d)" % (n_core, n_aggregation, n_edge, n_hosts) topo.graph['type'] = 'three_tier' for u in range(n_core): topo.node[u]['tier'] = 'core' topo.node[u]['type'] = 'switch' for v in topo.edge[u]: topo.edge[u][v]['type'] = 'core_aggregation' for u in range(n_core, n_core + n_aggregation): topo.node[u]['tier'] = 'aggregation' topo.node[u]['type'] = 'switch' for _ in range(n_edge): v = topo.number_of_nodes() topo.add_node(v) topo.node[v]['tier'] = 'edge' topo.node[v]['type'] = 'switch' topo.add_edge(u, v, type='aggregation_edge') total_n_edge = topo.number_of_nodes() for u in range(n_core + n_aggregation, total_n_edge): for _ in range(n_hosts): v = topo.number_of_nodes() topo.add_node(v) topo.node[v]['tier'] = 'leaf' topo.node[v]['type'] = 'host' topo.add_edge(u, v, type='edge_leaf') return topo
def random_graph(n, m, p, seed=None, directed=False): """Return a bipartite random graph. This is a bipartite version of the binomial (Erdős-Rényi) graph. Parameters ---------- n : int The number of nodes in the first bipartite set. m : int The number of nodes in the second bipartite set. p : float Probability for edge creation. seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=False) If True return a directed graph Notes ----- This function is not imported in the main namespace. To use it you have to explicitly import the bipartite package. The bipartite random graph algorithm chooses each of the n*m (undirected) or 2*nm (directed) possible edges with probability p. This algorithm is $O(n+m)$ where $m$ is the expected number of edges. The nodes are assigned the attribute 'bipartite' with the value 0 or 1 to indicate which bipartite set the node belongs to. See Also -------- gnp_random_graph, configuration_model References ---------- .. [1] Vladimir Batagelj and Ulrik Brandes, "Efficient generation of large random networks", Phys. Rev. E, 71, 036113, 2005. """ G = nx.Graph() G = _add_nodes_with_bipartite_label(G, n, m) if directed: G = nx.DiGraph(G) G.name = "fast_gnp_random_graph(%s,%s,%s)" % (n, m, p) if not seed is None: random.seed(seed) if p <= 0: return G if p >= 1: return nx.complete_bipartite_graph(n, m) lp = math.log(1.0 - p) v = 0 w = -1 while v < n: lr = math.log(1.0 - random.random()) w = w + 1 + int(lr / lp) while w >= m and v < n: w = w - m v = v + 1 if v < n: G.add_edge(v, n + w) if directed: # use the same algorithm to # add edges from the "m" to "n" set v = 0 w = -1 while v < n: lr = math.log(1.0 - random.random()) w = w + 1 + int(lr / lp) while w >= m and v < n: w = w - m v = v + 1 if v < n: G.add_edge(n + w, v) return G
def test_bipartite_k5(self): G = nx.complete_bipartite_graph(5,5) assert_equal(list(nx.square_clustering(G).values()), [1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
def complete(): return nx.complete_bipartite_graph(N, M)
from plot_multigraph import plot_multigraph n = 6 hypercube_n = 4 m = 6 r = 2 h = 3 dim = [2, 3] # left out dorogovtsev_goltsev_mendes_graph and null_graph graphs = [ ("balanced_tree", nx.balanced_tree(r, h)), ("barbell_graph", nx.barbell_graph(n, m)), ("complete_graph", nx.complete_graph(n)), ("complete_bipartite_graph", nx.complete_bipartite_graph(n, m)), ("circular_ladder_graph", nx.circular_ladder_graph(n)), ("cycle_graph", nx.cycle_graph(n)), ("empty_graph", nx.empty_graph(n)), ("grid_2d_graph", nx.grid_2d_graph(m, n)), ("grid_graph", nx.grid_graph(dim)), ("hypercube_graph", nx.hypercube_graph(hypercube_n)), ("ladder_graph", nx.ladder_graph(n)), ("lollipop_graph", nx.lollipop_graph(m, n)), ("path_graph", nx.path_graph(n)), ("star_graph", nx.star_graph(n)), ("trivial_graph", nx.trivial_graph()), ("wheel_graph", nx.wheel_graph(n)), ] plot_multigraph(graphs, 4, 4, node_size=50)
def setUp(self): self.P4 = nx.path_graph(4) self.K3 = nx.complete_bipartite_graph(3,3) self.C4 = nx.cycle_graph(4) self.davis = nx.davis_southern_women_graph() self.top_nodes = [n for n,d in self.davis.nodes(data=True) if d['bipartite']==0]