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 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 A2(): G = nx.davis_southern_women_graph() degree_sequence = sorted([d for n, d in G.degree()]) degree_count = { x: degree_sequence.count(x) for x in range(max(degree_sequence) + 1) } return (list(degree_count.keys()), list(degree_count.values()))
def setup_class(cls): cls.Gnp = nx.gnp_random_graph(20, 0.8) cls.Anp = _AntiGraph(nx.complement(cls.Gnp)) cls.Gd = nx.davis_southern_women_graph() cls.Ad = _AntiGraph(nx.complement(cls.Gd)) cls.Gk = nx.karate_club_graph() cls.Ak = _AntiGraph(nx.complement(cls.Gk)) cls.GA = [(cls.Gnp, cls.Anp), (cls.Gd, cls.Ad), (cls.Gk, cls.Ak)]
def nx_test_graphs(): yield nxg_gnp_random(directed=True) yield nxg_gnp_random(directed=False) yield nx.karate_club_graph() yield nx.davis_southern_women_graph() yield named_graph(directed=False, multigraph=False) yield named_graph(directed=False, multigraph=True) yield named_graph(directed=True, multigraph=False) yield named_graph(directed=True, multigraph=True)
def setUp(self): self.Gnp = nx.gnp_random_graph(20, 0.8) self.Anp = _AntiGraph(nx.complement(self.Gnp)) self.Gd = nx.davis_southern_women_graph() self.Ad = _AntiGraph(nx.complement(self.Gd)) self.Gk = nx.karate_club_graph() self.Ak = _AntiGraph(nx.complement(self.Gk)) self.GA = [(self.Gnp, self.Anp), (self.Gd, self.Ad), (self.Gk, self.Ak)]
def test_davis_southern_women_graph(self): G = nx.davis_southern_women_graph() nx.set_edge_attributes(G, 1, "capacity") for flow_func in flow_funcs: T = nx.gomory_hu_tree(G, flow_func=flow_func) assert nx.is_tree(T) for u, v in combinations(G, 2): cut_value, edge = self.minimum_edge_weight(T, u, v) assert nx.minimum_cut_value(G, u, v) == cut_value
def test_davis_southern_women_graph(self): G = nx.davis_southern_women_graph() nx.set_edge_attributes(G, 1, 'capacity') for flow_func in flow_funcs: T = nx.gomory_hu_tree(G, flow_func=flow_func) assert_true(nx.is_tree(T)) for u, v in combinations(G, 2): cut_value, edge = self.minimum_edge_weight(T, u, v) assert_equal(nx.minimum_cut_value(G, u, v), cut_value)
def socialnetwork_graphs(): print("Social networks") print("karate club graph") G = nx.karate_club_graph() draw_graph(G) print("Davis Southern women bipartite graph ") G = nx.davis_southern_women_graph() draw_graph(G) print("Florentine families graph ") G = nx.florentine_families_graph() draw_graph(G)
def test(graph="barbell", algorithm="o_fl", k=-1, v=False, kmin=3, kmax=5): """Runs a quic demo graph = 'karate', 'barbell', 'women', 'florentine' if not a specific graph it will be used as a seed for a random graph algorithm as 'fl' = async fluid detection, requires k 'o_fl' = optimizing fl, requires kmin and kmax 'gn' = garvin_newman k = number of communities to look for if applicable v = verbose flag """ #generate demo graph G = 0 if graph == "karate": G = nx.karate_club_graph() elif graph == "barbell": G = nx.barbell_graph(5, 1) elif graph == "women": G = nx.davis_southern_women_graph() elif graph == "florentine": G = nx.florentine_families_graph() else: G = nx.planted_partition_graph(5, 10, .85, .1, seed=graph) #switch on algorithm bestcom = 0 if algorithm == "fl": if k != -1: bestcom = async_fluid(G, k) else: bestcom = async_fluid(G) elif algorithm == "o_fl": #optimized fl bestcom = opt_async_fluid(G, kmin, kmax) elif algorithm == "gn": bestcom = girvan_newman(G, v) #Label the data and export in gephi readable format comlabel = 1 for c in bestcom: for n in c: G.node[n]['community'] = str(comlabel) comlabel += 1 rw.write_file(G, "test.gexf")
def GraphType(num_nodes, str, p=0.05, m=3): """ :param num_nodes: the number of nodes of the graph (if that option is available) :param str: the type of graph that is used. We have 'erdos' an erdos renyi graph 'powerlaw' a graph with powerlaw degree distribution 'enron' a social network graph loaded from http://snap.stanford.edu/data/email-Enron.html. (36692 nodes) 'karateclub' some karate club graph 'women' women social network :return: the graph """ if str == 'erdos': graph = nx.erdos_renyi_graph(num_nodes, p) elif str == 'powerlaw': graph = nx.powerlaw_cluster_graph(num_nodes, m, p) elif str == 'enron': graph = nx.Graph() edges = np.loadtxt('Enron.txt',skiprows=4) graph.add_edges_from(edges) elif str == 'karateclub': graph = nx.karate_club_graph() elif str == 'women': graph = nx.davis_southern_women_graph() elif str == 'pair': graph = nx.DiGraph() graph.add_edge(0,1) graph.add_edge(1,0) elif str == 'star': graph = nx.star_graph(num_nodes) elif str == 'cycle': graph = nx.cycle_graph(num_nodes) elif str == 'config': max_degree = int(num_nodes/5) #Create some degrees degrees = np.asarray(np.round(np.exp(np.log(max_degree) * np.random.uniform(size=num_nodes))), np.int) #Ensure the total number of degrees is even if sum(degrees) % 2 != 0: degrees[np.random.randint(num_nodes)] += 2 * np.random.randint(2) - 1 #Create a graph and apply the configuration model graph = nx.Graph() graph = nx.configuration_model(degrees, graph) graph = graph.to_directed() return graph
def _define_graph(self, n_mpi_process): # define the graph. graph = networkx.davis_southern_women_graph() # get the mixing matrix. mixing_matrix = networkx.adjacency_matrix(graph).toarray().astype( np.float) degrees = mixing_matrix.sum(axis=1) for node in np.argsort(degrees)[::-1]: mixing_matrix[:, node][mixing_matrix[:, node] == 1] = 1.0 / degrees[node] mixing_matrix[node, :][mixing_matrix[node, :] == 1] = 1.0 / degrees[node] mixing_matrix[node, node] = (1 - np.sum(mixing_matrix[node, :]) + mixing_matrix[node, node]) return mixing_matrix
def __init__(self, num_workers): super().__init__(num_workers) assert num_workers == 32 graph = networkx.davis_southern_women_graph() # get the mixing matrix. mixing_matrix = networkx.adjacency_matrix(graph).toarray().astype(np.float) degrees = mixing_matrix.sum(axis=1) + 1.0 # different from Koloskova et al. for node in np.argsort(degrees)[::-1]: mixing_matrix[:, node][mixing_matrix[:, node] == 1] = 1.0 / degrees[node] mixing_matrix[node, :][mixing_matrix[node, :] == 1] = 1.0 / degrees[node] mixing_matrix[node, node] = ( 1 - np.sum(mixing_matrix[node, :]) + mixing_matrix[node, node] ) self.diffusion_matrix = mixing_matrix self.name = f"Davis southern women graph"
def test_generalized_similarity(): """ Calculate the generalized similarities between events and women in the "classical" Southern Women graph. """ graph = nx.davis_southern_women_graph() women, events, eps, iters = generalized.generalized_similarity(graph) print("Number of iterations:", iters) print("Attained precision:", eps) print("Event network:", len(events), "nodes") print("Least similar events:", sorted(events.edges(data=True), key=lambda x: x[2]['weight'])[0][0:2]) print("Women network:", len(women), "nodes") print("Least similar women:", sorted(women.edges(data=True), key=lambda x: x[2]['weight'])[0][0:2]) with open("examples/women.graphml","wb") as ofile: nx.write_graphml(women, ofile) with open("examples/events.graphml","wb") as ofile: nx.write_graphml(events, ofile)
def generate_networks(io_h): # Dictionary for storing networks with names for dataset list_of_networks = {} n_nodes = 1000 n_edges = np.arange(1, 5, 1) connection_probs = np.arange(0.5, 0.7, 0.1) processed_networks = io_h.get_ignore_list() print('Generating Famous social networks') # Append famous social networks to list n_name = 'kartae_club' if n_name not in processed_networks: list_of_networks[n_name] = nx.karate_club_graph() n_name = 'davis_southern_women_graph' if n_name not in processed_networks: list_of_networks[n_name] = nx.davis_southern_women_graph() n_name = 'florentine_families_graph' if n_name not in processed_networks: list_of_networks[n_name] = nx.florentine_families_graph() print('Generating Barabasi network') for connection in n_edges: # Append Barabasi Graph n_name = '_'.join(['barabasi_albert_graph', str(connection)]) if n_name not in processed_networks: print('Generating ', n_name) list_of_networks[n_name] = nx.barabasi_albert_graph( n_nodes, connection) print('Generating Random Networks') # Generate random networks with connection probabilities for con_prob in connection_probs: n_name = '_'.join(['erdos_renyi_graph', '{:.1f}'.format(con_prob)]) if n_name not in processed_networks: print('Generating {}'.format(n_name)) list_of_networks[n_name] = nx.erdos_renyi_graph(n_nodes, con_prob) print('Finished Generating Networks') return list_of_networks
def main(): g = nx.Graph() nodes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,32] edges= [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 10), (1, 2), (1, 3), (1, 7), (2, 3), (2, 32), (2, 7), (2, 8), (2, 9),(3, 7),(4, 10), (4, 6),(5, 10), (5, 6)] g.add_nodes_from(nodes) g.add_edges_from(edges) source = 0 #the default method delivered from the networkx print list(nx.bfs_edges(g,0)) #call to the bfs final_edges = bfs(g,source) display_graph(final_edges) print "bfs done" #Call to the pivot random walk pivot_random_walk(g,source,20) print "pivot random done" #Call to the pivot random walk g= nx.davis_southern_women_graph() weighted_independence(g,25) print "completion"
def test_davis_southern_women_detail_3_and_4(): solution = { 3: [ { 'Nora Fayette', 'E10', 'Myra Liddel', 'E12', 'E14', 'Frances Anderson', 'Evelyn Jefferson', 'Ruth DeSand', 'Helen Lloyd', 'Eleanor Nye', 'E9', 'E8', 'E5', 'E4', 'E7', 'E6', 'E1', 'Verne Sanderson', 'E3', 'E2', 'Theresa Anderson', 'Pearl Oglethorpe', 'Katherina Rogers', 'Brenda Rogers', 'E13', 'Charlotte McDowd', 'Sylvia Avondale', 'Laura Mandeville', }, ], 4: [ { 'Nora Fayette', 'E10', 'Verne Sanderson', 'E12', 'Frances Anderson', 'Evelyn Jefferson', 'Ruth DeSand', 'Helen Lloyd', 'Eleanor Nye', 'E9', 'E8', 'E5', 'E4', 'E7', 'E6', 'Myra Liddel', 'E3', 'Theresa Anderson', 'Katherina Rogers', 'Brenda Rogers', 'Charlotte McDowd', 'Sylvia Avondale', 'Laura Mandeville', }, ], } G = nx.davis_southern_women_graph() result = nx.k_components(G) for k, components in result.items(): if k < 3: continue assert_true(len(components) == len(solution[k])) for component in components: assert_true(component in solution[k])
def test_davis_southern_women(): G = nx.davis_southern_women_graph() result = nx.k_components(G) _check_connectivity(G, result)
# BusBar500kV, 31-Mar-2019 # D-Wave Challenge 10 import networkx as nx import dwave_networkx as dnx from dwave.system.composites import EmbeddingComposite from dwave.system.samplers import DWaveSampler problem10 = [(nx.florentine_families_graph(), 'families in Renaissance-era Florence'), (nx.karate_club_graph(), 'Karate club'), (nx.davis_southern_women_graph(), 'Davis Southern women graph')] for G, text in problem10: shots = 1000 number_of_rounds = 10 min_max_cut_set = [] for n in range(number_of_rounds): sampler = EmbeddingComposite(DWaveSampler()) max_cut = dnx.maximum_cut(G, sampler, num_reads=shots) min_max_cut_set.append(min(len(max_cut), len(set(G) - set(max_cut)))) print('Max Cut for %s graph is %s.' % (text, min(min_max_cut_set)))
def test_davis_southern_women_detail_3_and_4(): solution = { 3: [{ 'Nora Fayette', 'E10', 'Myra Liddel', 'E12', 'E14', 'Frances Anderson', 'Evelyn Jefferson', 'Ruth DeSand', 'Helen Lloyd', 'Eleanor Nye', 'E9', 'E8', 'E5', 'E4', 'E7', 'E6', 'E1', 'Verne Sanderson', 'E3', 'E2', 'Theresa Anderson', 'Pearl Oglethorpe', 'Katherina Rogers', 'Brenda Rogers', 'E13', 'Charlotte McDowd', 'Sylvia Avondale', 'Laura Mandeville', }, ], 4: [{ 'Nora Fayette', 'E10', 'Verne Sanderson', 'E12', 'Frances Anderson', 'Evelyn Jefferson', 'Ruth DeSand', 'Helen Lloyd', 'Eleanor Nye', 'E9', 'E8', 'E5', 'E4', 'E7', 'E6', 'Myra Liddel', 'E3', 'Theresa Anderson', 'Katherina Rogers', 'Brenda Rogers', 'Charlotte McDowd', 'Sylvia Avondale', 'Laura Mandeville', }, ], } G = nx.davis_southern_women_graph() result = nx.k_components(G) for k, components in result.items(): if k < 3: continue assert_true(len(components) == len(solution[k])) for component in components: assert_true(component in solution[k])
def test_biconnected_davis(): D = nx.davis_southern_women_graph() bcc = list(nx.biconnected_components(D))[0] assert_true(set(D) == bcc) # All nodes in a giant bicomponent # So no articulation points assert_equal(len(list(nx.articulation_points(D))), 0)
def gen_laplacian(data_num=DATA_NUM, opt=27, cache=False): label = None if cache: print('Loading cached graph') graph = pk.load(open('tmp/g.pk', 'rb')) else: print('Generating graph opt {}'.format(opt)) if 1 == opt: graph = gen_rand_graph(data_num=data_num) if 2 == opt: top_num = random.randint(1, data_num) bottom_num = data_num - top_num graph = nx.bipartite.random_graph(top_num, bottom_num, 0.9) label = [d['bipartite'] for n, d in graph.nodes(data=True)] elif 3 == opt: graph = nx.balanced_tree(4, 5) elif 4 == opt: graph = nx.complete_graph(data_num) elif 5 == opt: no1 = random.randint(1, data_num) no2 = random.randint(1, int(data_num / no1)) no3 = data_num / no1 / no2 graph = nx.complete_multipartite_graph(no1, no2, no3) elif 6 == opt: graph = nx.circular_ladder_graph(data_num) elif 7 == opt: graph = nx.cycle_graph(data_num) elif 8 == opt: graph = nx.dorogovtsev_goltsev_mendes_graph(5) elif 9 == opt: top_num = int(random.random() * data_num) bottom_num = data_num / top_num graph = nx.grid_2d_graph(top_num, bottom_num) elif 10 == opt: no1 = random.randint(1, data_num) no2 = random.randint(1, int(data_num / no1)) no3 = data_num / no1 / no2 graph = nx.grid_graph([no1, no2, no3]) elif 11 == opt: graph = nx.hypercube_graph(10) elif 12 == opt: graph = nx.ladder_graph(data_num) elif 13 == opt: top_num = int(random.random() * data_num) bottom_num = data_num - top_num graph = nx.lollipop_graph(top_num, bottom_num) elif 14 == opt: graph = nx.path_graph(data_num) elif 15 == opt: graph = nx.star_graph(data_num) elif 16 == opt: graph = nx.wheel_graph(data_num) elif 17 == opt: graph = nx.margulis_gabber_galil_graph(35) elif 18 == opt: graph = nx.chordal_cycle_graph(data_num) elif 19 == opt: graph = nx.fast_gnp_random_graph(data_num, random.random()) elif 20 == opt: # jump eigen value graph = nx.gnp_random_graph(data_num, random.random()) elif 21 == opt: # disconnected graph graph = nx.dense_gnm_random_graph(data_num, data_num / 2) elif 22 == opt: # disconnected graph graph = nx.gnm_random_graph(data_num, data_num / 2) elif 23 == opt: graph = nx.erdos_renyi_graph(data_num, data_num / 2) elif 24 == opt: graph = nx.binomial_graph(data_num, data_num / 2) elif 25 == opt: graph = nx.newman_watts_strogatz_graph(data_num, 5, random.random()) elif 26 == opt: graph = nx.watts_strogatz_graph(data_num, 5, random.random()) elif 26 == opt: # smooth eigen graph = nx.connected_watts_strogatz_graph(data_num, 5, random.random()) elif 27 == opt: # smooth eigen graph = nx.random_regular_graph(5, data_num) elif 28 == opt: # smooth eigen graph = nx.barabasi_albert_graph(data_num, 5) elif 29 == opt: # smooth eigen graph = nx.powerlaw_cluster_graph(data_num, 5, random.random()) elif 30 == opt: # smooth eigen graph = nx.duplication_divergence_graph(data_num, random.random()) elif 31 == opt: p = random.random() q = random.random() graph = nx.random_lobster(data_num, p, q) elif 32 == opt: p = random.random() q = random.random() k = random.random() graph = nx.random_shell_graph([(data_num / 3, 50, p), (data_num / 3, 40, q), (data_num / 3, 30, k)]) elif 33 == opt: # smooth eigen top_num = int(random.random() * data_num) bottom_num = data_num - top_num graph = nx.k_random_intersection_graph(top_num, bottom_num, 3) elif 34 == opt: graph = nx.random_geometric_graph(data_num, .1) elif 35 == opt: graph = nx.waxman_graph(data_num) elif 36 == opt: graph = nx.geographical_threshold_graph(data_num, .5) elif 37 == opt: top_num = int(random.random() * data_num) bottom_num = data_num - top_num graph = nx.uniform_random_intersection_graph( top_num, bottom_num, .5) elif 39 == opt: graph = nx.navigable_small_world_graph(data_num) elif 40 == opt: graph = nx.random_powerlaw_tree(data_num, tries=200) elif 41 == opt: graph = nx.karate_club_graph() elif 42 == opt: graph = nx.davis_southern_women_graph() elif 43 == opt: graph = nx.florentine_families_graph() elif 44 == opt: graph = nx.complete_multipartite_graph(data_num, data_num, data_num) # OPT 1 # norm_lap = nx.normalized_laplacian_matrix(graph).toarray() # OPT 2: renormalized # pk.dump(graph, open('tmp/g.pk', 'wb')) # plot_graph(graph, label) # note difference: normalized laplacian and normalzation by eigenvalue norm_lap, eigval, eigvec = normalize_lap(graph) return graph, norm_lap, eigval, eigvec
import networkx as nx import matplotlib.pylab as plt from plot_multigraph import plot_multigraph graphs = [ ('karate_club_graph', nx.karate_club_graph()), ('davis_southern_women_graph', nx.davis_southern_women_graph()), ('florentine_families_graph', nx.florentine_families_graph()), ] plot_multigraph(graphs, 2, 2, node_size=50) plt.savefig('graphs/social.png')
def test_ra_clustering_davis(): G = nx.davis_southern_women_graph() cc4 = round(bipartite.robins_alexander_clustering(G), 3) assert_equal(cc4, 0.468)
def create_example_viz(filename): filename = ensure_html_filename(filename) graph = nx.davis_southern_women_graph() create_viz_html(graph, filename)
def test_is_aperiodic_bipartite(): # Bipartite graph G = nx.DiGraph(nx.davis_southern_women_graph()) assert_false(nx.is_aperiodic(G))
adj_iter : iterator An iterator of (node, adjacency set) for all nodes in the graph. """ for n in self.adj: yield (n, set(self.adj) - set(self.adj[n]) - set([n])) if __name__ == '__main__': # Build several pairs of graphs, a regular graph # and the AntiGraph of it's complement, which behaves # as if it were the original graph. Gnp = nx.gnp_random_graph(20,0.8) Anp = AntiGraph(nx.complement(Gnp)) Gd = nx.davis_southern_women_graph() Ad = AntiGraph(nx.complement(Gd)) Gk = nx.karate_club_graph() Ak = AntiGraph(nx.complement(Gk)) pairs = [(Gnp, Anp), (Gd, Ad), (Gk, Ak)] # test connected components for G, A in pairs: gc = [set(c) for c in nx.connected_components(G)] ac = [set(c) for c in nx.connected_components(A)] for comp in ac: assert comp in gc # test biconnected components for G, A in pairs: gc = [set(c) for c in nx.biconnected_components(G)] ac = [set(c) for c in nx.biconnected_components(A)] for comp in ac:
def test_davis_southern_women(): G = nx.davis_southern_women_graph() _check_connectivity(G)
========== Davis Southern Club Women Shows how to make unipartite projections of the graph and compute the properties of those graphs. These data were collected by Davis et al. in the 1930s. They represent observed attendance at 14 social events by 18 Southern women. The graph is bipartite (clubs, women). """ import matplotlib.pyplot as plt import networkx as nx import networkx.algorithms.bipartite as bipartite G = nx.davis_southern_women_graph() women = G.graph['top'] clubs = G.graph['bottom'] print("Biadjacency tar_matrix") print(bipartite.biadjacency_matrix(G, women, clubs)) # project bipartite graph onto women nodes W = bipartite.projected_graph(G, women) print('') print("#Friends, Member") for w in women: print('%d %s' % (W.degree(w), w)) # project bipartite graph onto women nodes keeping number of co-occurence # the degree computed is weighted and counts the total number of shared contacts
def test_biconnected_davis(): D = nx.davis_southern_women_graph() bcc = list(biconnected.biconnected_components(D))[0] assert_true(set(D) == bcc) # All nodes in a giant bicomponent # So no articulation points assert_equal(list(biconnected.articulation_points(D)),[])
def test_davis_southern_women_detail_3_and_4(): solution = { 3: [{ "Nora Fayette", "E10", "Myra Liddel", "E12", "E14", "Frances Anderson", "Evelyn Jefferson", "Ruth DeSand", "Helen Lloyd", "Eleanor Nye", "E9", "E8", "E5", "E4", "E7", "E6", "E1", "Verne Sanderson", "E3", "E2", "Theresa Anderson", "Pearl Oglethorpe", "Katherina Rogers", "Brenda Rogers", "E13", "Charlotte McDowd", "Sylvia Avondale", "Laura Mandeville", }], 4: [{ "Nora Fayette", "E10", "Verne Sanderson", "E12", "Frances Anderson", "Evelyn Jefferson", "Ruth DeSand", "Helen Lloyd", "Eleanor Nye", "E9", "E8", "E5", "E4", "E7", "E6", "Myra Liddel", "E3", "Theresa Anderson", "Katherina Rogers", "Brenda Rogers", "Charlotte McDowd", "Sylvia Avondale", "Laura Mandeville", }], } G = nx.davis_southern_women_graph() result = nx.k_components(G) for k, components in result.items(): if k < 3: continue assert len(components) == len(solution[k]) for component in components: assert component in solution[k]
def test_is_aperiodic_bipartite(): # Bipartite graph G = nx.DiGraph(nx.davis_southern_women_graph()) assert not nx.is_aperiodic(G)
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]