def test_barbell(): G = nx.barbell_graph(5, 0) _check_augmentations(G) G = nx.barbell_graph(5, 2) _check_augmentations(G) G = nx.barbell_graph(5, 3) _check_augmentations(G) G = nx.barbell_graph(5, 4) _check_augmentations(G)
def test_disconnected_graph_root_node(self): """Test for a single component of a disconnected graph.""" G = nx.barbell_graph(3, 0) H = nx.barbell_graph(3, 0) mapping = dict(zip(range(6), 'abcdef')) nx.relabel_nodes(H, mapping, copy=False) G = nx.union(G, H) chains = list(nx.chain_decomposition(G, root='a')) expected = [ [('a', 'b'), ('b', 'c'), ('c', 'a')], [('d', 'e'), ('e', 'f'), ('f', 'd')], ] self.assertEqual(len(chains), len(expected)) for chain in chains: self.assertContainsChain(chain, expected)
def test_good_partition(self): """Tests that a good partition has a high performance measure. """ G = barbell_graph(3, 0) partition = [{0, 1, 2}, {3, 4, 5}] assert_almost_equal(14 / 15, performance(G, partition))
def test025_barbell_graph(self): """ Very small barbell graph. """ g = nx.barbell_graph(9, 2) mate2 = nx.max_weight_matching( g, True ) td.showGraph(g, mate2, "test025_barbell_graph_edmonds") mate1 = mv.max_cardinality_matching( g ) self.assertEqual( len(mate1), len(mate2) )
def test_single_edge(self): """Tests for a cut of a single edge.""" G = nx.barbell_graph(3, 0) S = {0, 1, 2} T = {3, 4, 5} assert_equal(nx.cut_size(G, S, T), 1) assert_equal(nx.cut_size(G, T, S), 1)
def force(request): G = nx.barbell_graph(6, 3) # write json formatted data d = json_graph.node_link_data(G) #node-link format to serialize # write json to client # json.dump(d, open('data/force.json', 'w')) return HttpResponse(json.dumps(d), mimetype='application/json')
def test_directed(self): """Tests that each directed edge is counted once in the cut.""" G = nx.barbell_graph(3, 0).to_directed() S = {0, 1, 2} T = {3, 4, 5} assert_equal(nx.cut_size(G, S, T), 2) assert_equal(nx.cut_size(G, T, S), 2)
def test_directed_symmetric(self): """Tests that a cut in a directed graph is symmetric.""" G = nx.barbell_graph(3, 0).to_directed() S = {0, 1, 4} T = {2, 3, 5} assert_equal(nx.cut_size(G, S, T), 8) assert_equal(nx.cut_size(G, T, S), 8)
def test_barbell(): G=nx.barbell_graph(8,4) G.add_path([7,20,21,22]) G.add_cycle([22,23,24,25]) pts=set(biconnected.articulation_points(G)) assert_equal(pts,set([7,8,9,10,11,12,20,21,22])) answer = [set([12, 13, 14, 15, 16, 17, 18, 19]), set([0, 1, 2, 3, 4, 5, 6, 7]), set([22, 23, 24, 25]), set([11, 12]), set([10, 11]), set([9, 10]), set([8, 9]), set([7, 8]), set([21, 22]), set([20, 21]), set([7, 20])] bcc=list(biconnected.biconnected_components(G)) bcc.sort(key=len, reverse=True) assert_equal(bcc,answer) G.add_edge(2,17) pts=set(biconnected.articulation_points(G)) assert_equal(pts,set([7,20,21,22]))
def data(ndata=100): """ On request, this returns a list of ``ndata`` randomly made data points. :param ndata: (optional) The number of data points to return. :returns data: A JSON string of ``ndata`` data points. """ # x = 10 * np.random.rand(ndata) - 5 # y = 0.5 * x + 0.5 * np.random.randn(ndata) # A = 10. ** np.random.rand(ndata) # c = np.random.rand(ndata) # return json.dumps([{"_id": i, "x": x[i], "y": y[i], "area": A[i], # "color": c[i]} # for i in range(ndata)]) G = nx.barbell_graph(6, 3) # this d3 example uses the name attribute for the mouse-hover value, # so add a name to each node for n in G: G.node[n]['name'] = n # write json formatted data return json.dumps(json_graph.node_link_data(G)) # node-link format to serialize
def test_graph(self): G = nx.barbell_graph(5, 0) S = set(range(5)) T = set(G) - S expansion = nx.edge_expansion(G, S, T) expected = 1 / 5 assert_equal(expected, expansion)
def test_symmetric(self): """Tests that the cut size is symmetric.""" G = nx.barbell_graph(3, 0) S = {0, 1, 4} T = {2, 3, 5} assert_equal(nx.cut_size(G, S, T), 4) assert_equal(nx.cut_size(G, T, S), 4)
def test_clique_removal(): graph = nx.complete_graph(10) i, cs = apxa.clique_removal(graph) idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by clique_removal!") for clique in cs: cdens = nx.density(graph.subgraph(clique)) eq_(cdens, 1.0, "clique not found by clique_removal!") graph = nx.trivial_graph(nx.Graph()) i, cs = apxa.clique_removal(graph) idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!") # we should only have 1-cliques. Just singleton nodes. for clique in cs: cdens = nx.density(graph.subgraph(clique)) eq_(cdens, 0.0, "clique not found by clique_removal!") graph = nx.barbell_graph(10, 5, nx.Graph()) i, cs = apxa.clique_removal(graph) idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!") for clique in cs: cdens = nx.density(graph.subgraph(clique)) eq_(cdens, 1.0, "clique not found by clique_removal!")
def test_disconnected_graph(self): """Test for a graph with multiple connected components.""" G = nx.barbell_graph(3, 0) H = nx.barbell_graph(3, 0) mapping = dict(zip(range(6), 'abcdef')) nx.relabel_nodes(H, mapping, copy=False) G = nx.union(G, H) chains = list(nx.chain_decomposition(G)) expected = [ [(0, 1), (1, 2), (2, 0)], [(3, 4), (4, 5), (5, 3)], [('a', 'b'), ('b', 'c'), ('c', 'a')], [('d', 'e'), ('e', 'f'), ('f', 'd')], ] self.assertEqual(len(chains), len(expected)) for chain in chains: self.assertContainsChain(chain, expected)
def test_is_locally_k_edge_connected(): G = nx.barbell_graph(10, 0) assert_true(is_locally_k_edge_connected(G, 5, 15, k=1)) assert_false(is_locally_k_edge_connected(G, 5, 15, k=2)) G = nx.Graph() G.add_nodes_from([5, 15]) assert_false(is_locally_k_edge_connected(G, 5, 15, k=2))
def test_graph(self): G = nx.barbell_graph(5, 0) # Consider the singleton sets containing the "bridge" nodes. # There is only one cut edge, and each set has volume five. S = {4} T = {5} conductance = nx.conductance(G, S, T) expected = 1 / 5 assert_equal(expected, conductance)
def test_lobster(self): import networkx as nx import matplotlib.pyplot as plt #g = nx.random_lobster(15, 0.8, 0.1) g = nx.barbell_graph(7, 5) #g = nx.erdos_renyi_graph(15, 0.2) nx.draw_graphviz(g) plt.savefig("/tmp/lobster.png") print distancematrix.matrix_calls(g.edges(), 7)
def test_graph(self): G = nx.barbell_graph(5, 0) S = set(range(5)) T = set(G) - S expansion = nx.mixing_expansion(G, S, T) # There is one cut edge, and the total number of edges in the # graph is twice the total number of edges in a clique of size # five, plus one more for the bridge. expected = 1 / (2 * (5 * 4 + 1)) assert_equal(expected, expansion)
def test_barbell(self): G = nx.barbell_graph(3, 0) partition = [{0, 1, 2}, {3, 4, 5}] M = nx.quotient_graph(G, partition, relabel=True) assert_equal(sorted(M), [0, 1]) assert_equal(sorted(M.edges()), [(0, 1)]) for n in M: assert_equal(M.node[n]['nedges'], 3) assert_equal(M.node[n]['nnodes'], 3) assert_equal(M.node[n]['density'], 1)
def test_barbell(self): G=networkx.barbell_graph(3,0) partition=[[0,1,2],[3,4,5]] M=networkx.blockmodel(G,partition) assert_equal(sorted(M.nodes()),[0,1]) assert_equal(sorted(M.edges()),[(0,1)]) for n in M.nodes(): assert_equal(M.node[n]['nedges'],3) assert_equal(M.node[n]['nnodes'],3) assert_equal(M.node[n]['density'],1.0)
def test_barbell_graph(self): # The (3, 0) barbell graph has two triangles joined by a single edge. G = nx.barbell_graph(3, 0) chains = list(nx.chain_decomposition(G, root=0)) expected = [ [(0, 1), (1, 2), (2, 0)], [(3, 4), (4, 5), (5, 3)], ] self.assertEqual(len(chains), len(expected)) for chain in chains: self.assertContainsChain(chain, expected)
def test_barbell_plus(self): G=networkx.barbell_graph(3,0) G.add_edge(0,5) # add extra edge between bells partition=[[0,1,2],[3,4,5]] M=networkx.blockmodel(G,partition) assert_equal(sorted(M.nodes()),[0,1]) assert_equal(sorted(M.edges()),[(0,1)]) assert_equal(M[0][1]['weight'],2) for n in M.nodes(): assert_equal(M.node[n]['nedges'],3) assert_equal(M.node[n]['nnodes'],3) assert_equal(M.node[n]['density'],1.0)
def test_barbell_plus(self): G = nx.barbell_graph(3, 0) # Add an extra edge joining the bells. G.add_edge(0, 5) partition = [{0, 1, 2}, {3, 4, 5}] M = nx.quotient_graph(G, partition, relabel=True) assert_equal(sorted(M), [0, 1]) assert_equal(sorted(M.edges()), [(0, 1)]) assert_equal(M[0][1]['weight'], 2) for n in M: assert_equal(M.node[n]['nedges'], 3) assert_equal(M.node[n]['nnodes'], 3) assert_equal(M.node[n]['density'], 1)
def test_is_k_edge_connected(): G = nx.barbell_graph(10, 0) assert_true(is_k_edge_connected(G, k=1)) assert_false(is_k_edge_connected(G, k=2)) G = nx.Graph() G.add_nodes_from([5, 15]) assert_false(is_k_edge_connected(G, k=1)) assert_false(is_k_edge_connected(G, k=2)) G = nx.complete_graph(5) assert_true(is_k_edge_connected(G, k=1)) assert_true(is_k_edge_connected(G, k=2)) assert_true(is_k_edge_connected(G, k=3)) assert_true(is_k_edge_connected(G, k=4))
def test_adapted_type(): dj.errors._switch_adapted_types(True) c = adapted.Connectivity() graphs = [ nx.lollipop_graph(4, 2), nx.star_graph(5), nx.barbell_graph(3, 1), nx.cycle_graph(5) ] c.insert((i, g) for i, g in enumerate(graphs)) returned_graphs = c.fetch('conn_graph', order_by='connid') for g1, g2 in zip(graphs, returned_graphs): assert_true(isinstance(g2, nx.Graph)) assert_equal(len(g1.edges), len(g2.edges)) assert_true(0 == len(nx.symmetric_difference(g1, g2).edges)) c.delete() dj.errors._switch_adapted_types(False)
def test_quadratic_ranges_partially_specified(self): graph = nx.barbell_graph(4, 16) decision_variables = (0, 4, 3) feasible_configurations = {(0, 0, 1): 0.} spec = pm.Specification(graph, decision_variables, feasible_configurations, ising_quadratic_ranges={0: {1: [0, 1], 2: [-1, 0]}, 2: {0: [-1, 0]}}, vartype=dimod.BINARY) ising_quadratic_ranges = spec.ising_quadratic_ranges for u in ising_quadratic_ranges: for v in ising_quadratic_ranges[u]: self.assertIs(ising_quadratic_ranges[u][v], ising_quadratic_ranges[v][u]) for u, v in graph.edges: self.assertIn(v, ising_quadratic_ranges[u]) self.assertIn(u, ising_quadratic_ranges[v]) self.assertEqual(ising_quadratic_ranges[0][1], [0, 1])
def test_construction_from_edgelist(self): graph = nx.barbell_graph(10, 7) decision_variables = (0, 4, 3) feasible_configurations = {(-1, -1, -1): 0.} # specification from edges spec0 = pm.Specification(graph.edges, decision_variables, feasible_configurations, vartype=dimod.SPIN) # specification from graph spec1 = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN) self.assertEqual(spec0, spec1)
def test_node2vec_embedding_barbell_graph_correct_shape_is_returned(self): graph = nx.barbell_graph(25, 2) for s, t in graph.edges(): graph.add_edge(s, t, weight=1) model = n2v.node2vec_embed(graph) model_matrix: np.ndarray = model[0] vocab_list = model[1] self.assertIsNotNone(model) self.assertIsNotNone(model[0]) self.assertIsNotNone(model[1]) # model matrix should be 34 x 128 self.assertEqual(model_matrix.shape[0], 52) self.assertEqual(model_matrix.shape[1], 128) # vocab list should have exactly 34 elements self.assertEqual(len(vocab_list), 52)
def test_to_networkx_graph(self): graph = nx.barbell_graph(7, 6) # build a BQM model = dimod.BinaryQuadraticModel({v: -.1 for v in graph}, {edge: -.4 for edge in graph.edges}, 1.3, vartype=dimod.SPIN) # get the graph BQM = dimod.to_networkx_graph(model) self.assertEqual(set(graph), set(BQM)) for u, v in graph.edges: self.assertIn(u, BQM[v]) for v, bias in model.linear.items(): self.assertEqual(bias, BQM.nodes[v]['bias'])
def test_typical(self): graph = nx.barbell_graph(17, 8) edgelist = set(graph.edges()) adj = dwave.embedding.utils.edgelist_to_adjacency(edgelist) # test that they're equal for u, v in edgelist: self.assertIn(u, adj) self.assertIn(v, adj) self.assertIn(u, adj[v]) self.assertIn(v, adj[u]) for u in adj: for v in adj[u]: self.assertTrue((u, v) in edgelist or (v, u) in edgelist) self.assertFalse((u, v) in edgelist and (v, u) in edgelist)
def networkx_graph(): """ ========== Javascript ========== Example of writing JSON format graph data and using the D3 Javascript library to produce an HTML/Javascript drawing. """ # Author: Aric Hagberg <*****@*****.**> # Copyright (C) 2011-2018 by # Aric Hagberg <*****@*****.**> # Dan Schult <*****@*****.**> # Pieter Swart <*****@*****.**> # All rights reserved. # BSD license. import json import flask import networkx as nx from networkx.readwrite import json_graph G = nx.barbell_graph(6, 3) # this d3 example uses the name attribute for the mouse-hover value, # so add a name to each node for n in G: G.nodes[n]['name'] = n # write json formatted data d = json_graph.node_link_data(G) # node-link format to serialize # write json json.dump(d, open('/home/vorberg/Documents/networkx/examples/javascript/force/force.json', 'w')) print('Wrote node-link JSON data to /home/vorberg/Documents/networkx/examples/javascript/force/force.json') # Serve the file over http to allow for cross origin requests app = flask.Flask(__name__, static_folder="/home/vorberg/Documents/networkx/examples/javascript/force") @app.route('/<path:path>') def static_proxy(path): return app.send_static_file(path) print('\nGo to http://localhost:8000/force.html to see the example\n') app.run(port=8000)
def communities_using_brute(gfg): nodes = gfg.nodes() n = gfg.number_of_nodes() first_community = [] for i in range(1, n / 2 + 1): c = [list(a) for a in itertools.combiantions(nodes, i)] first_community.extend(c) second_community = [] for i in range(len(first_community)): b = list(set(nodes) - set(first_community[i])) second_community.append(b) # Which division is best... intra_edges1 = [] intra_edges2 = [] inter_edges = [] ratio = [] # ratio of number of intra/number of inter community edges for i in range(len(first_community)): intra_edges1.append(gfg.subgraph(first_community[i]).number_of_edges()) for i in range(len(second_community)): intra_edges2.append(gfg.subgraph(second_community[i]).number_of_edges()) e = g.number_of_edges() for i in range(len(first_community)): inter_edges.append(e - intra_edges1[i] - intra_edges2[i]) # Calculate the Ratio for i in range(len(first_community)): ratio.append((float)intra_edges1[i] + intra_edges2[i])/inter_edges[i]) maxV = max(ratio) mindex = ratio.index(maxV) print '[ ', first_community[mindex], ' ] , [ ', second_community[mindex], ' ]' # Example graph gfg = nx.barbell_graph(5, 0) communities_using_brute(gfg)
def generate_graph_original(n, type='random', d=0, m=0, k=5, p=.5, periodic=False, with_positions=True, create_using=None): ''' INPUTS: n Number of nodes d Average degree of the graph type Type of graph periodic Bool: is the graph periodic? with_positions create_using OUTPUTS: Graph with the specified parameters and of the specified type ''' try: if type == 'hypercube': graph = nx.hypercube_graph(n) return graph elif type == 'random': graph = nx.random_regular_graph(d, n) return graph elif type == 'erdos_renyi': graph = nx.erdos_renyi_graph(n, m) elif type == 'complete': graph = nx.complete_graph(n) elif type == 'dumbell': graph = nx.barbell_graph(n // 2 - 1, n - 2 * (n // 2 - 1)) elif type == 'dumbell_multiple': m = 10 N = 5 L = 2 graph = generate_dumbell_multiple_cliques(m, N, L) return graph except ValueError: print("The specified graph type was invalid.")
def test_med_cohort_graph_generates_embedding(self): graph = nx.barbell_graph(10, 2) for edge in graph.edges(): graph.add_edge(edge[0], edge[1], weight=1) result = tc.embedding.omnibus_embedding( [graph, graph], embedding_method=tc.embedding.EmbeddingMethod. ADJACENCY_SPECTRAL_EMBEDDING, elbow_cut=None) self.assertIsNotNone(result) for containers in result: self.assertEqual(len(containers[0].embedding.shape), len(containers[1].embedding.shape)) self.assertEqual(len(containers[0].vertex_labels), len(containers[1].vertex_labels))
def graph_type_mgr(graph_type, N, d): if graph_type == 1: G = nx.random_regular_graph(d, N) density_type = 'Degree' if d == 2: graph_type_str = 'Chain' elif d >= N-1: graph_type_str = 'Complete' else: graph_type_str = 'Random regular graph' elif graph_type == 2: G = nx.gnp_random_graph(N, d) density_type = 'Independent edge probability' if d >= 1: graph_type_str = 'Complete graph' else: graph_type_str = 'Erdos-Renyi' elif graph_type == 3: G = nx.barabasi_albert_graph(N, d) density_type = 'Number of attachment for new nodes' graph_type_str = 'Preferential attachment' elif graph_type == 4: h = int(np.floor(np.log(N*(d-2) + 1)/np.log(d-1))) - 1 # Consider one extra height level in the tree... G = nx.balanced_tree(d-1, h+1) # ... and remove the additional nodes to have N nodes. G = nx.Graph(G.subgraph(list(G.nodes)[:N])) density_type = 'Degree' graph_type_str = 'Balanced tree' elif graph_type == 5: if (N - d) % 2 == 0: n = (N - d) // 2 else: n = (N - d) // 2 d += 1 G = nx.barbell_graph(n, d) density_type = 'Bridge length' graph_type_str = 'Barbell' else: raise ValueError('Unknown graph type.') return G, density_type, graph_type_str
def test_linear_ranges_specified(self): graph = nx.barbell_graph(4, 16) decision_variables = (0, 4, 3) feasible_configurations = {(0, 0, 1): 0.} spec = pm.Specification(graph, decision_variables, feasible_configurations, ising_linear_ranges={v: [-v, 2] for v in graph}, vartype=dimod.BINARY) # check default energy ranges for v in graph: self.assertEqual(spec.ising_linear_ranges[v], [-v, 2]) spec = pm.Specification(graph, decision_variables, feasible_configurations, ising_linear_ranges={v: (-v, 2) for v in graph}, vartype=dimod.BINARY) # check default energy ranges for v in graph: self.assertEqual(spec.ising_linear_ranges[v], [-v, 2])
def barbell_graph(m1,m2): """Function to generate barbell graph. A n-barbell graph is the simple graph obtained by connecting two copies of a complete graph K_n by a bridge. Return the Barbell Graph: two complete graphs connected by a path. For m1 > 1 and m2 >= 0. Two identical complete graphs K_{m1} form the left and right bells, and are connected by a path P_{m2}. The 2*m1+m2 nodes are numbered 0,...,m1-1 for the left barbell, m1,...,m1+m2-1 for the path, and m1+m2,...,2*m1+m2-1 for the right barbell. """ graph = nx.barbell_graph(m1,m2) ## for com_nc, one hot #onehot_com = np.array([[1,0,0]]*m1+[[0,1,0]]*m2+[[0,0,1]]*m1) is slower when num of nodes > 2000 node_labels_com = np.zeros(m1*2+m2).astype(int) node_labels_com[m1:m1+m2] = 2 node_labels_com[m1+m2:] = 1 ## one hot onehot_com = np.zeros((m1*2+m2,3)).astype(int) onehot_com[np.arange(m1*2+m2), node_labels_com] = 1 ## for role_nc, one hot node_labels_role = np.zeros(m1*2+m2).astype(int) p,q = divmod(m2, 2) for i in range(p+1): node_labels_role[[m1-1+i,m1+m2-i]] = i+1 if q: node_labels_role[m1+p] = p+2 onehot_role = np.zeros((m1*2+m2,p+q+2)).astype(int) onehot_role[np.arange(m1*2+m2), node_labels_role] = 1 return graph, scipy.sparse.csr_matrix(onehot_com), scipy.sparse.csr_matrix(onehot_role)
def testCliqueNumber(self): # test K3 k3 = nx.complete_graph(3) clique = DalGraph(k3).clique_number() self.assertEqual(clique, 3, "Clique Number on K3") # test K5 k5 = nx.complete_graph(5) clique = DalGraph(k5).clique_number() self.assertEqual(clique, 5, "Clique Number on K5") # test K8 k8 = nx.complete_graph(8) clique = DalGraph(k8).clique_number() self.assertEqual(clique, 8, "Clique Number on K8") # test C4 c4 = make_cycle(4) clique = DalGraph(c4).clique_number() self.assertEqual(clique, None, "Clique Number on C4") # test random graph rando = nx.barbell_graph(10, 10) clique = DalGraph(rando).clique_number() self.assertEqual(clique, None, "Clique Number on random graph")
def test_complete_to_chordal_graph(self): fgrg = nx.fast_gnp_random_graph test_graphs = [ nx.barbell_graph(6, 2), nx.cycle_graph(15), nx.wheel_graph(20), nx.grid_graph([10, 4]), nx.ladder_graph(15), nx.star_graph(5), nx.bull_graph(), fgrg(20, 0.3, seed=1), ] for G in test_graphs: H, a = nx.complete_to_chordal_graph(G) assert nx.is_chordal(H) assert len(a) == H.number_of_nodes() if nx.is_chordal(G): assert G.number_of_edges() == H.number_of_edges() assert set(a.values()) == {0} else: assert len(set(a.values())) == H.number_of_nodes()
def test_adapted_virtual(): dj.errors._switch_adapted_types(True) c = virtual_module.Connectivity() graphs = [ nx.lollipop_graph(4, 2), nx.star_graph(5), nx.barbell_graph(3, 1), nx.cycle_graph(5), ] c.insert((i, g) for i, g in enumerate(graphs)) c.insert1({"connid": 100}) # test work with NULLs returned_graphs = c.fetch("conn_graph", order_by="connid") for g1, g2 in zip_longest(graphs, returned_graphs): if g1 is None: assert_true(g2 is None) else: assert_true(isinstance(g2, nx.Graph)) assert_equal(len(g1.edges), len(g2.edges)) assert_true(0 == len(nx.symmetric_difference(g1, g2).edges)) c.delete() dj.errors._switch_adapted_types(False)
def test_pca_reduces_to_expected_dimensionality(self): graph = nx.barbell_graph(10, 2) for edge in graph.edges(): graph.add_edge(edge[0], edge[1], weight=1) expected_dimension = 1 container = tc.embedding.adjacency_embedding(graph, maximum_dimensions=5, svd_seed=1234) embedding_reduced = tc.embedding.pca(embedding=container.embedding, num_components=expected_dimension) # the embedding reduced by PCA should have the same height as the input embedding # but the dimensions should be reduced to exactly the dimension specified in pca call self.assertIsNotNone(embedding_reduced) self.assertEqual(container.embedding.shape[0], embedding_reduced.shape[0]) self.assertEqual(embedding_reduced.shape[1], expected_dimension)
def test_resolution_parameter_impact(): G = nx.barbell_graph(5, 3) gamma = 1 expected = [ frozenset(range(5)), frozenset(range(8, 13)), frozenset(range(5, 8)) ] assert greedy_modularity_communities(G, resolution=gamma) == expected assert naive_greedy_modularity_communities(G, resolution=gamma) == expected gamma = 2.5 expected = [{0, 1, 2, 3}, {9, 10, 11, 12}, {5, 6, 7}, {4}, {8}] assert greedy_modularity_communities(G, resolution=gamma) == expected assert naive_greedy_modularity_communities(G, resolution=gamma) == expected gamma = 0.3 expected = [frozenset(range(8)), frozenset(range(8, 13))] assert greedy_modularity_communities(G, resolution=gamma) == expected assert naive_greedy_modularity_communities(G, resolution=gamma) == expected
def test_linear_ranges_bad(self): graph = nx.barbell_graph(4, 16) decision_variables = (0, 4, 3) feasible_configurations = {(0, 0, 1): 0.} with self.assertRaises(ValueError): pm.Specification(graph, decision_variables, feasible_configurations, ising_linear_ranges={v: [-v, 'a'] for v in graph}, vartype=dimod.BINARY) with self.assertRaises(TypeError): pm.Specification( graph, decision_variables, feasible_configurations, ising_linear_ranges={v: [-v, 1, 1] for v in graph}, vartype=dimod.BINARY)
def testHoleNumber(self): # test C3 c3 = make_cycle(3) hole = DalGraph(c3).hole_number() self.assertEqual(hole, 3, "Hole Number on C3") # test C5 c5 = make_cycle(5) hole = DalGraph(c5).hole_number() self.assertEqual(hole, 5, "Hole Number on C5") # test C8 c8 = make_cycle(8) hole = DalGraph(c8).hole_number() self.assertEqual(hole, 8, "Hole Number on C8") # test K4 k4 = nx.complete_graph(4) hole = DalGraph(k4).hole_number() self.assertEqual(hole, None, "Hole Number on K4") # test random graph rando = nx.barbell_graph(10, 10) hole = DalGraph(rando).hole_number() self.assertEqual(hole, None, "Hole Number on random graph")
def creat_graph(m1, m2): m_1 = 2*m1+m2 m_2 = m1+m2 g = nx.barbell_graph(m1, m2) color = ['b','g','r','y'] color_1 = color[0] color_2 = color[1] color_3 = color[2] node_colors = [] for i in range(g.number_of_nodes()): if i < m1-1: node_colors.append(color_1) else: if i == m1 - 1: node_colors.append(color_2) else: if i < m_2: node_colors.append(color_3) else: if i == m_2: node_colors.append(color_2) else: node_colors.append(color_1) # g.add_node(m+1) # g.add_node(m+2) # g.add_node(m+3) # g.add_node(m+4) # g.add_edge(7,m+1) # g.add_edge(m+1,m+2) # g.add_edge(m+2,m+3) # g.add_edge(m+2,m+4) adj = nx.adjacency_matrix(g) features = np.identity(adj.shape[0]) nx.draw(g, with_labels = True, node_color = node_colors) print(adj.todense()) plt.show() return adj, features, node_colors
def barbell_graph(m1,m2): graph = nx.barbell_graph(m1,m2) ## for com_nc, one hot #onehot_com = np.array([[1,0,0]]*m1+[[0,1,0]]*m2+[[0,0,1]]*m1) is slower when num of nodes > 2000 node_labels_com = np.zeros(m1*2+m2).astype(int) node_labels_com[m1:m1+m2] = 2 node_labels_com[m1+m2:] = 1 ## one hot onehot_com = np.zeros((m1*2+m2,3)).astype(int) onehot_com[np.arange(m1*2+m2), node_labels_com] = 1 ## for role_nc, one hot node_labels_role = np.zeros(m1*2+m2).astype(int) p,q = divmod(m2, 2) for i in range(p+1): node_labels_role[[m1-1+i,m1+m2-i]] = i+1 if q: node_labels_role[m1+p] = p+2 onehot_role = np.zeros((m1*2+m2,p+q+2)).astype(int) onehot_role[np.arange(m1*2+m2), node_labels_role] = 1 return graph, scipy.sparse.csr_matrix(onehot_com), scipy.sparse.csr_matrix(onehot_role)
def test_modularity(): G = nx.barbell_graph(3, 0) C = [{0, 1, 4}, {2, 3, 5}] assert almost_equal(-16 / (14**2), modularity(G, C)) C = [{0, 1, 2}, {3, 4, 5}] assert almost_equal((35 * 2) / (14**2), modularity(G, C)) n = 1000 G = nx.erdos_renyi_graph(n, 0.09, seed=42, directed=True) C = [set(range(n // 2)), set(range(n // 2, n))] assert almost_equal(0.00017154251389292754, modularity(G, C)) G = nx.margulis_gabber_galil_graph(10) mid_value = G.number_of_nodes() // 2 nodes = list(G.nodes) C = [set(nodes[:mid_value]), set(nodes[mid_value:])] assert almost_equal(0.13, modularity(G, C)) G = nx.DiGraph() G.add_edges_from([(2, 1), (2, 3), (3, 4)]) C = [{1, 2}, {3, 4}] assert almost_equal(2 / 9, modularity(G, C))
def test_graph_insert_retrieve(self): conn = self.clean_connection graph = nx.barbell_graph(8, 8) nodelist = sorted(graph) edgelist = sorted(sorted(edge) for edge in graph.edges) with conn as cur: pmc.insert_graph(cur, nodelist, edgelist) # should only be one graph graphs = list(pmc.iter_graph(cur)) self.assertEqual(len(graphs), 1) (nodelist_, edgelist_), = graphs self.assertEqual(nodelist, nodelist_) self.assertEqual(edgelist, edgelist_) # trying to reinsert should still result in only one graph with conn as cur: pmc.insert_graph(cur, nodelist, edgelist) graphs = list(pmc.iter_graph(cur)) self.assertEqual(len(graphs), 1) # inserting with an empty dict as encoded_data should populate it encoded_data = {} with conn as cur: pmc.insert_graph(cur, nodelist, edgelist, encoded_data) self.assertIn('num_nodes', encoded_data) self.assertIn('num_edges', encoded_data) self.assertIn('edges', encoded_data) # now adding another graph should result in two items graph = nx.complete_graph(4) nodelist = sorted(graph) edgelist = sorted(sorted(edge) for edge in graph.edges) with conn as cur: pmc.insert_graph(cur, nodelist, edgelist) graphs = list(pmc.iter_graph(cur)) self.assertEqual(len(graphs), 2)
def test_ramsey(): # this should only find the complete graph graph = nx.complete_graph(10) c, i = apxa.ramsey_R2(graph) cdens = nx.density(graph.subgraph(c)) assert cdens == 1.0, "clique not found by ramsey!" idens = nx.density(graph.subgraph(i)) assert idens == 0.0, "i-set not found by ramsey!" # this trival graph has no cliques. should just find i-sets graph = nx.trivial_graph(nx.Graph()) c, i = apxa.ramsey_R2(graph) cdens = nx.density(graph.subgraph(c)) assert cdens == 0.0, "clique not found by ramsey!" idens = nx.density(graph.subgraph(i)) assert idens == 0.0, "i-set not found by ramsey!" graph = nx.barbell_graph(10, 5, nx.Graph()) c, i = apxa.ramsey_R2(graph) cdens = nx.density(graph.subgraph(c)) assert cdens == 1.0, "clique not found by ramsey!" idens = nx.density(graph.subgraph(i)) assert idens == 0.0, "i-set not found by ramsey!"
def test_ramsey(): # this should only find the complete nxgraph graph = nx.complete_graph(10) c, i = apxa.ramsey_R2(graph) cdens = nx.density(graph.subgraph(c)) eq_(cdens, 1.0, "clique not found by ramsey!") idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!") # this trival nxgraph has no cliques. should just find i-sets graph = nx.trivial_graph(nx.Graph()) c, i = apxa.ramsey_R2(graph) cdens = nx.density(graph.subgraph(c)) eq_(cdens, 0.0, "clique not found by ramsey!") idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!") graph = nx.barbell_graph(10, 5, nx.Graph()) c, i = apxa.ramsey_R2(graph) cdens = nx.density(graph.subgraph(c)) eq_(cdens, 1.0, "clique not found by ramsey!") idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!")
def main(): print("Creating Graph \n") G = nx.barbell_graph(50, 50) print("Printing initialization values through Init algorithm \n") x = init_G.init(G) print(x) print("\n\n") print("Printing CompIS algorithm output\n\n") x = iscomplement.comp_is(G) print(x) print("\n\n") print("Printing Max Clique\n\n") maxclique = traditional_maxclique.traditional_maxclique(G) print("maxclique: {}\n".format(maxclique)) print("Please refer to the source codes to check line by line implementation of the code according to the algo\n") print("Also refer to rmc.py to see line by line implementation of overall algorithm") print("We were unable to implement 3/8 algorithms from the paper: tciSeed, divSeed, and scSeed") print("As a result, could not run RMC in it's entirety, but our implementation closely matches the algorithm in the paper") print("_______END____________")
def test_graphs(self): H = nx.complete_graph(2) H.add_edge(2, 3) graphs = [nx.complete_graph(7), dnx.chimera_graph(2, 1, 3), nx.balanced_tree(5, 3), nx.barbell_graph(8, 11), nx.cycle_graph(5), H] for G in graphs: tw, order = dnx.treewidth_branch_and_bound(G) self.assertEqual(dnx.elimination_order_width(G, order), tw) tw, order = dnx.min_width_heuristic(G) self.assertEqual(dnx.elimination_order_width(G, order), tw) tw, order = dnx.min_fill_heuristic(G) self.assertEqual(dnx.elimination_order_width(G, order), tw) tw, order = dnx.max_cardinality_heuristic(G) self.assertEqual(dnx.elimination_order_width(G, order), tw)
def test_barbell_graph(self): G = nx.barbell_graph(10, 5) independent_set, cliques = clique_removal(G) assert is_independent_set(G, independent_set) assert all(is_clique(G, clique) for clique in cliques)
def setUp(self): self.G = nx.barbell_graph(4, 6)
from modules import drawer import networkx import random import pickle k_p = -1 # proportional coefficient k_i = -10000 k_d = 0 dt = 0.01 net_size = 40 for k_d in [i * -.1 for i in xrange(5)]: for k_i in [i * -1000 for i in xrange(5)]: for k_p in [i * -1 for i in xrange(5)]: graph = networkx.barbell_graph(net_size / 2, 0) trajectory = [] u = {} e = {} e_i = {} e_d = {} for n in graph: graph.node[n]['x'] = random.random() * n / 20.0 trajectory.append([graph.node[n]['x']]) u[n] = [] e[n] = [] e_i[n] = [] e_d[n] = [] # pickle.dump([graph, trajectory], open("graph.dat","wa")) [graph, trajectory] = pickle.load(open("graph.dat", "r"))
========== Example of writing JSON format graph data and using the D3 Javascript library to produce an HTML/Javascript drawing. You will need to download the following directory: - https://github.com/networkx/networkx/tree/master/examples/javascript/force """ import json import flask import networkx as nx from networkx.readwrite import json_graph G = nx.barbell_graph(10, 2) # this d3 example uses the name attribute for the mouse-hover value, # so add a name to each node for n in G: G.nodes[n]["name"] = n # write json formatted data d = json_graph.node_link_data(G) # node-link format to serialize # write json json.dump(d, open("force/force.json", "w")) print("Wrote node-link JSON data to force/force.json") # Serve the file over http to allow for cross origin requests app = flask.Flask(__name__, static_folder="force") @app.route("/")
def test_result_barbell_graph_20_10(self): assert (calc_and_compare(NX.barbell_graph(20, 10)))
def test_result_barbell_graph_5_5(self): assert (calc_and_compare(NX.barbell_graph(5, 5)))
def test_barbell(): G = nx.barbell_graph(8, 4) nx.add_path(G, [7, 20, 21, 22]) nx.add_cycle(G, [22, 23, 24, 25]) pts = set(nx.articulation_points(G)) assert_equal(pts, {7, 8, 9, 10, 11, 12, 20, 21, 22}) answer = [ {12, 13, 14, 15, 16, 17, 18, 19}, {0, 1, 2, 3, 4, 5, 6, 7}, {22, 23, 24, 25}, {11, 12}, {10, 11}, {9, 10}, {8, 9}, {7, 8}, {21, 22}, {20, 21}, {7, 20}, ] assert_components_equal(list(nx.biconnected_components(G)), answer) G.add_edge(2,17) pts = set(nx.articulation_points(G)) assert_equal(pts, {7, 20, 21, 22})