def test_edge_num_attribute(self): g = nx.karate_club_graph() attr = {(u, v): {"even": int((u+v) % 10)} for (u, v) in g.edges()} nx.set_edge_attributes(g, attr) model = gc.CompositeModel(g) model.add_status("Susceptible") model.add_status("Infected") c = cpm.EdgeNumericalAttribute("even", value=0, op="==", probability=1) model.add_rule("Susceptible", "Infected", c) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0.1) model.set_initial_status(config) iterations = model.iteration_bunch(10) self.assertEqual(len(iterations), 10) model = gc.CompositeModel(g) model.add_status("Susceptible") model.add_status("Infected") c = cpm.EdgeNumericalAttribute("even", value=[3, 10], op="IN", probability=1) model.add_rule("Susceptible", "Infected", c) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0.1) model.set_initial_status(config) iterations = model.iteration_bunch(10) self.assertEqual(len(iterations), 10)
def test_clustering_integer_nodes(self): # This tests an error that would happen when a node had an integer value # greater than the size of the graph orig_club = nx.karate_club_graph() club = nx.relabel_nodes(orig_club, { n: n + 5 for n in orig_club.nodes() }) dendrogram = GreedyAgglomerativeClusterer().cluster(club) dendrogram.clusters() # This would crash
def main(): # Load the karate.GraphML and store that into a g g =nx.karate_club_graph() data = json_graph.node_link_data(g) with open ('graph.json' , 'w') as f: json.dump(data, f, indent=1)
def test_nodes_all_labeled(self): G = nx.karate_club_graph() label_name = 'club' predicted = node_classification.local_and_global_consistency( G, alpha=0, label_name=label_name) for i in range(len(G)): assert_equal(predicted[i], G.node[i][label_name])
def test_run(self): karate = nx.karate_club_graph() louvain = wm.LouvainCommunityDetection(karate) final_partitions = louvain.run() self.assertEqual(final_partitions[-1].modularity() > .38, True) self.assertEqual(len(final_partitions), 2)
def test_nodes_all_labeled(self): G = nx.karate_club_graph() label_name = 'club' predicted = node_classification.harmonic_function( G, label_name=label_name) for i in range(len(G)): assert_equal(predicted[i], G.node[i][label_name])
def test_graphs_karate(): G = nx.karate_club_graph() nx.draw(G, with_labels=True, node_color="lightblue", edge_color="grey") plt.show() # plt.savefig("karate.pdf") print(G.number_of_edges()) print(G.number_of_nodes()) print(G.degree(0) is G.degree()[0])
def test_net_load(self): base = os.path.dirname(os.path.abspath(__file__)) g = nx.karate_club_graph() fname = "%s/edge.txt" % base nx.write_edgelist(g, fname) query = "LOAD_NETWORK g1 FROM %s\n" \ "\n" \ "MODEL model1\n" \ "\n" \ "STATUS Susceptible\n" \ "\n" \ "STATUS Infected\n" \ "\n" \ "STATUS Removed\n" \ "\n" \ "COMPARTMENT c1\n" \ "TYPE NodeStochastic\n" \ "PARAM rate 0.1\n" \ "TRIGGER Infected\n" \ "\n" \ "COMPARTMENT c2\n" \ "TYPE NodeStochastic\n" \ "PARAM rate 0.1\n" \ "COMPOSE c1\n" \ "TRIGGER Infected\n" \ "\n" \ "COMPARTMENT c3\n" \ "TYPE NodeStochastic\n" \ "PARAM rate 0.1\n" \ "\n" \ "RULE\n" \ "FROM Susceptible\n" \ "TO Infected\n" \ "USING c2\n" \ "\n" \ "RULE\n" \ "FROM Infected\n" \ "TO Removed\n" \ "USING c3\n" \ "\n" \ "INITIALIZE\n" \ "SET Infected 0.1\n" \ "\n" \ "EXECUTE model1 ON g1 FOR 10" % fname parser = ep.ExperimentParser() parser.set_query(query) parser.parse() iterations = parser.execute_query() try: os.remove("%s/edge.txt" % base) except OSError: pass self.assertIn('trends', iterations[0])
def main(): G = nx.karate_club_graph() N = NewmanGreedy(G) print N.quality_history try: N.plot_dendrogram() N.plot_quality_history("Karate", os.path.join(os.path.dirname(__file__), "pics", "karate")) except: pass
def test_karate_club_graph_cutset(self): G = nx.karate_club_graph() nx.set_edge_attributes(G, 1, 'capacity') T = nx.gomory_hu_tree(G) assert_true(nx.is_tree(T)) u, v = 0, 33 cut_value, edge = self.minimum_edge_weight(T, u, v) cutset = self.compute_cutset(G, T, edge) assert_equal(cut_value, len(cutset))
def test_default_flow_function_karate_club_graph(self): G = nx.karate_club_graph() nx.set_edge_attributes(G, 1, 'capacity') T = nx.gomory_hu_tree(G) 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 test_biconnected_karate(): K = nx.karate_club_graph() answer = [{0, 1, 2, 3, 7, 8, 9, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33}, {0, 4, 5, 6, 10, 16}, {0, 11}] bcc = list(nx.biconnected_components(K)) assert_components_equal(bcc, answer) assert_equal(set(nx.articulation_points(K)), {0})
def test_karate_1(): karate_k_num = {0: 4, 1: 4, 2: 4, 3: 4, 4: 3, 5: 3, 6: 3, 7: 4, 8: 4, 9: 2, 10: 3, 11: 1, 12: 2, 13: 4, 14: 2, 15: 2, 16: 2, 17: 2, 18: 2, 19: 3, 20: 2, 21: 2, 22: 2, 23: 3, 24: 3, 25: 3, 26: 2, 27: 3, 28: 3, 29: 3, 30: 4, 31: 3, 32: 4, 33: 4} G = nx.karate_club_graph() k_comps = k_components(G) k_num = build_k_number_dict(k_comps) assert_equal(karate_k_num, k_num)
def main(): graph = nx.karate_club_graph(); dendrogram = GreedyAgglomerativeClusterer().cluster(graph) print dendrogram.quality_history print dendrogram.clusters() try: dendrogram.plot(os.path.join(os.path.dirname(__file__), '..', 'pics', 'karate_dend.png'), show=False) dendrogram.plot_quality_history('Karate', os.path.join(os.path.dirname(__file__), '..', 'pics', 'karate'), show=False) except: pass
def write_karate_adj_mat_by_nx(): g = nx.karate_club_graph() mat = np.zeros((34, 34)) for edge in nx.edges(g): node0 = int(edge[0]) node1 = int(edge[1]) mat[node0][node1] = 1 mat[node1][node0] = 1 np.savetxt("karate_adj_mat.csv", mat, fmt="%.0f", delimiter=",")
def test_postprocessing(): G = nx.karate_club_graph() prediction_all_links = CommonNeighbours(G)() prediction_only_new_links = CommonNeighbours(G, excluded=G.edges())() for link, score in six.iteritems(prediction_all_links): if G.has_edge(*link): assert_not_in(link, prediction_only_new_links) else: assert_equal(score, prediction_only_new_links[link])
def test_biconnected_karate(): K = nx.karate_club_graph() answer = [set([0, 1, 2, 3, 7, 8, 9, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]), set([0, 4, 5, 6, 10, 16]), set([0, 11])] bcc = list(biconnected.biconnected_components(K)) bcc.sort(key=len, reverse=True) assert_true(list(biconnected.biconnected_components(K)) == answer) assert_equal(list(biconnected.articulation_points(K)),[0])
def main(): graph = nx.karate_club_graph(); newman = NewmanGreedy(graph) print newman.quality_history print newman.get_clusters() try: newman.plot_dendrogram(os.path.join(os.path.dirname(__file__), '..', 'pics', 'karate_dend.png'), show=False) newman.plot_quality_history('Karate', os.path.join(os.path.dirname(__file__), '..', 'pics', 'karate'), show=False) except: pass
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 initialize(): global g, nextg random.seed(76502) g = nx.karate_club_graph() g.pos = nx.spring_layout(g) for i in g.nodes_iter(): g.node[i]['natural_freq'] = random.random() for i in g.nodes_iter(): g.node[i]['theta'] = random.random() print g.node[0]['natural_freq'] nextg = g.copy()
def loadData(nameGraph): global gt global problem_name problem_name=nameGraph if (nameGraph==karate_club): graph=nx.karate_club_graph() #standard graph in networkx gt=ksgt elif (nameGraph==dolphins): graph=nx.read_gml('..\data\dolphins\dolphins.gml') gt=dgt return graph
def test_labeled_nodes_are_not_changed(self): G = nx.karate_club_graph() label_name = 'club' label_removed = set([0, 1, 2, 3, 4, 5, 6, 7]) for i in label_removed: del G.node[i][label_name] predicted = node_classification.harmonic_function( G, label_name=label_name) label_not_removed = set(list(range(len(G)))) - label_removed for i in label_not_removed: assert_equal(predicted[i], G.node[i][label_name])
def test_karate_1(): karate_k_num = {0: 4, 1: 4, 2: 4, 3: 4, 4: 3, 5: 3, 6: 3, 7: 4, 8: 4, 9: 2, 10: 3, 11: 1, 12: 2, 13: 4, 14: 2, 15: 2, 16: 2, 17: 2, 18: 2, 19: 3, 20: 2, 21: 2, 22: 2, 23: 3, 24: 3, 25: 3, 26: 2, 27: 3, 28: 3, 29: 3, 30: 4, 31: 3, 32: 4, 33: 4} approx_karate_k_num = karate_k_num.copy() approx_karate_k_num[24] = 2 approx_karate_k_num[25] = 2 G = nx.karate_club_graph() k_comps = k_components(G) k_num = build_k_number_dict(k_comps) assert_in(k_num, (karate_k_num, approx_karate_k_num))
def test_from_networkx_with_node_attrs(self): import networkx as nx G = nx.karate_club_graph() graph = Graph.from_networkx(G, nx.circular_layout) clubs = np.array([ 'Mr. Hi', 'Mr. Hi', 'Mr. Hi', 'Mr. Hi', 'Mr. Hi', 'Mr. Hi', 'Mr. Hi', 'Mr. Hi', 'Mr. Hi', 'Officer', 'Mr. Hi', 'Mr. Hi', 'Mr. Hi', 'Mr. Hi', 'Officer', 'Officer', 'Mr. Hi', 'Mr. Hi', 'Officer', 'Mr. Hi', 'Officer', 'Mr. Hi', 'Officer', 'Officer', 'Officer', 'Officer', 'Officer', 'Officer', 'Officer', 'Officer', 'Officer', 'Officer', 'Officer', 'Officer']) self.assertEqual(graph.nodes.dimension_values('club'), clubs)
def test_renumbering_modules(self): """ Test that the renumbering of the module dictionary is correct """ #input = {1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 6, 7: 6, 8: 6, 9: 6, 10: 6} input = {0: 17, 1: 17, 2: 12, 3: 12, 4: 10, 5: 16, 6: 16, 7: 12, 8: 32, 9: 12, 10: 10, 11: 17, 12: 12, 13: 12, 14: 32, 15: 32, 16: 16, 17: 17, 18: 32, 19: 17, 20: 32, 21: 17, 22: 32, 23: 25, 24: 27, 25: 25, 26: 29, 27: 27, 28: 31, 29: 29, 30: 32, 31: 31, 32: 32, 33: 32} #expected_output = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1} expected_output = {0: 0, 1: 0, 2: 1, 3: 1, 4: 2, 5: 3, 6: 3, 7: 1, 8: 4, 9: 1, 10: 2, 11: 0, 12: 1, 13: 1, 14: 4, 15: 4, 16: 3, 17: 0, 18: 4, 19: 0, 20: 4, 21: 0, 22: 4, 23: 5, 24: 6, 25: 5, 26: 7, 27: 6, 28: 8, 29: 7, 30: 4, 31: 8, 32: 4, 33: 4} #set up mock object, we just need some graph here to create the instance graph = nx.karate_club_graph() info_partition = infomap.Infomap(graph) result = info_partition.renumber_modules(input) self.assertDictEqual(result, expected_output)
def test_non_repeated_cuts(): # The algorithm was repeating the cut {0, 1} for the giant biconnected # component of the Karate club graph. K = nx.karate_club_graph() G = max(list(nx.biconnected_component_subgraphs(K)), key=len) solution = [{32, 33}, {2, 33}, {0, 3}, {0, 1}, {29, 33}] cuts = list(nx.all_node_cuts(G)) if len(solution) != len(cuts): print(nx.info(G)) print("Solution: {}".format(solution)) print("Result: {}".format(cuts)) assert_true(len(solution) == len(cuts)) for cut in cuts: assert_true(cut in solution)
def example_clustering(): G = nx.karate_club_graph() #first compute the best partition partition = community.best_partition(G) #drawing pos = nx.spring_layout(G) plt.figure(figsize=(12,12)) plt.axis('off') nx.draw_networkx_nodes(G, pos, node_size=200, cmap=plt.cm.RdYlBu, node_color=partition.values()) nx.draw_networkx_edges(G,pos, alpha=0.5) plt.savefig("figure/karate_communities.png")
def test_karate(self): """"test modularity on Zachary's karate club""" graph = nx.karate_club_graph() part = co.best_partition(graph) self.assertTrue(co.modularity(part, graph) > 0.41) for e1, e2 in graph.edges_iter(): graph[e1][e2]["test_weight"] = 1. part_weight = co.best_partition(graph, weight="test_weight") self.assertAlmostEqual(co.modularity(part, graph), co.modularity(part_weight, graph, "test_weight")) part_res_low = co.best_partition(graph, resolution=0.1) self.assertTrue( len(set(part.values())) < len(set(part_res_low.values())))
def test_countwodn(self): g = nx.karate_club_graph() model = gc.CompositeModel(g) model.add_status("Susceptible") model.add_status("Infected") c = cpm.CountDown(name="time", iterations=4) model.add_rule("Susceptible", "Infected", c) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0.1) model.set_initial_status(config) iterations = model.iteration_bunch(100) self.assertEqual(len(iterations), 100)
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 test_karate(): G = nx.karate_club_graph() result = nx.k_components(G) _check_connectivity(G, result)
# # This function returns a NetworkX layout, which is really just a # dictionary of node positions (2D X-Y tuples) indexed by the node # name. def forceatlas2_networkx_layout(G, pos=None, **kwargs): import networkx assert isinstance(G, networkx.classes.graph.Graph), "Not a networkx graph" assert isinstance(pos, dict) or ( pos is None), "pos must be specified as a dictionary, as in networkx" M = numpy.asarray(networkx.to_numpy_matrix(G)) if pos is None: l = forceatlas2(M, pos=None, **kwargs) else: poslist = numpy.asarray([pos[i] for i in G.nodes()]) l = forceatlas2(M, pos=poslist, **kwargs) return dict(zip(G.nodes(), l)) import matplotlib.pyplot as plt import networkx import random G = networkx.karate_club_graph() pos = {i: (random.random(), random.random()) for i in G.nodes()} # Optionally specify positions as a dictionary # networkx.draw_networkx(G, pos) # plt.show() l = forceatlas2_networkx_layout( G, pos, niter=1000) # Optionally specify iteration count networkx.draw_networkx(G, l) plt.show()
def test_karate(): G = nx.karate_club_graph() _check_separating_sets(G)
# -*- coding: utf-8 -*- """ Created on Tue Dec 24 16:11:33 2019 @author: zixing.mei """ import networkx as nx from networkx.algorithms import community import itertools G = nx.karate_club_graph() comp = community.girvan_newman(G) # 令社区个数为4,这样会依次得到K=2,K=3,K=4时候的划分结果 k = 4 limited = itertools.takewhile(lambda c: len(c) <= k, comp) for communities in limited: print(tuple(sorted(c) for c in communities)) import networkx as nx import community G = nx.karate_club_graph() part = community.best_partition(G) print(len(part)) import math import numpy as np from sklearn import metrics def NMI(A,B):
def initialize(): global g g = nx.karate_club_graph() g.pos = nx.spring_layout(g) for i in g.nodes(): g.node[i]['state'] = 1 if random() < .5 else 0
Parameters: arg1 (G): Graph object input Returns: c: generator, holds lists of node labels in each community Other functions used: edge_to_remove(G) """ c = nx.connected_component_subgraphs( g ) # return connective component of graph as subgraph (we only have 1 so returns 1) num_graphs = len(list(c)) # gives number of subgraphs (always starts at 1) print('Initial number of communities ', num_graphs) # now must remove edges based on betweenness centrality value of edges while num_graphs == 1: g.remove_edge(*edge_to_remove(g)) # ((a,b)) --> (a,b) c = nx.connected_component_subgraphs(g) num_graphs = len(list(c)) print('The number of communities are ', num_graphs) return c # Example Usage: G_test = nx.karate_club_graph() comm_node_list = girvan_newman(G_test)
''' AI기초통계 13장 빅데이터 분석 과제 209페이지 하단 20. 5. 25. 차재관 작성 ''' import networkx as nx import matplotlib.pyplot as plt G = nx.karate_club_graph() # 내장된 데이터를 가져와 G에 저장 nx.draw(G, with_labels=True, node_color='lightblue', edge_color='yellow') plt.show()
plt.rcParams.update({ 'figure.figsize': (7.5, 7.5), 'axes.spines.right': False, 'axes.spines.left': False, 'axes.spines.top': False, 'axes.spines.bottom': False}) # Seed random number generator import random from numpy import random as nprand seed = hash("Network Science in Python") % 2**32 nprand.seed(seed) random.seed(seed) # Import NetworkX import networkx as nx G_karate = nx.karate_club_graph() the club to which the member represented by that node belongs, either ‘Mr. Hi’ or ‘Officer’. nx.draw_networkx(G_karate, pos=nx.circular_layout(G_karate)) def get_color(i, r_off=1, g_off=1, b_off=1): r0, g0, b0 = 0, 0, 0 n = 16 low, high = 0.1, 0.9 span = high - low r = low + span * (((i + r_off) * 3) % n) / (n - 1) g = low + span * (((i + g_off) * 5) % n) / (n - 1) b = low + span * (((i + b_off) * 7) % n) / (n - 1) return (r, g, b) import networkx.algorithms.community as nxcom
def test_non_randomness(): G = nx.karate_club_graph() np.testing.assert_almost_equal(nx.non_randomness(G, 2)[0], 11.7, decimal=2) np.testing.assert_almost_equal(nx.non_randomness(G)[0], 7.21, decimal=2) # infers 3 communities
def load_dataset(name): dolphin_path = 'Datasets/dolphins.gml' adjnoun_path = "Datasets/adjnoun.gml" football_path = 'Datasets/football.gml' polbooks_path = 'Datasets/polbooks.gml' email_edges = 'Datasets/email-Eu-core.txt' email_labels = 'Datasets/email-Eu-core-department-labels.txt' # # Polblogs # if(name=='polblogs'): # G_data = nx.read_gml(polblogs_path) # G_data = G_data.to_undirected() # G_data = nx.Graph(G_data) # B_data = nx.modularity_matrix(G_data) # Karate if(name == 'karate'): G_data = nx.karate_club_graph() B_data = nx.modularity_matrix(G_data) # Football elif(name == 'football'): G_data = nx.read_gml(football_path) B_data = nx.modularity_matrix(G_data) # Polbooks elif(name == 'polbooks'): G_data = nx.read_gml(polbooks_path) B_data = nx.modularity_matrix(G_data) # Dolphin elif(name == 'dolphin'): G_data = nx.read_gml(dolphin_path) B_data = nx.modularity_matrix(G_data) # lfr 0.1 elif(name == 'lfr 0.1'): G_data = nx.Graph() data, labels = load_data(0.1) for index, item in enumerate(labels): G_data.add_node(index+1, value=item) for item in data: G_data.add_edge(*item) B_data = nx.modularity_matrix(G_data) # lfr 0.3 elif(name == 'lfr 0.3'): G_data = nx.Graph() data, labels = load_data(0.3) for index, item in enumerate(labels): G_data.add_node(index+1, value=item) for item in data: G_data.add_edge(*item) B_data = nx.modularity_matrix(G_data) # lfr 0.5 elif(name == 'lfr 0.5'): G_data = nx.Graph() data, labels = load_data(0.5) for index, item in enumerate(labels): G_data.add_node(index+1, value=item) for item in data: G_data.add_edge(*item) B_data = nx.modularity_matrix(G_data) elif(name == 'email'): G_data=nx.Graph() with open(email_edges) as f: for line in f: if(len(line)>0): x=(line.split()) G_data.add_edge(int(x[0]),int(x[1])) G_data.remove_nodes_from([658,653,648,798,731,772,670,691,675,684,660,711,744,808,746,580,633,732,703]) B_data = nx.modularity_matrix(G_data) return G_data, B_data
def test_karate(): G = nx.karate_club_graph() _check_augmentations(G)
def rs_test_zkc_num_distances(): G = nx.karate_club_graph() num_distances, _ = ss.all_pairs_shortest_paths_rolling_sum(G) assert num_distances == len(G)**2
def test_zkc_num_distances(): G = nx.karate_club_graph() num_distances = sum(ss.all_pairs_shortest_paths(G).values()) assert num_distances == len(G)**2
def rs_test_zkc_sum_distances(): G = nx.karate_club_graph() tup = ss.all_pairs_shortest_paths_rolling_sum(G) _, sum_distances = tup assert sum_distances == sum( [sum(x.values()) for _, x in nx.all_pairs_shortest_path_length(G)])
def test_zkc_sum_distances(): G = nx.karate_club_graph() sum_distances = sum( [k * v for k, v in ss.all_pairs_shortest_paths(G).items()]) assert sum_distances == sum( [sum(x.values()) for _, x in nx.all_pairs_shortest_path_length(G)])
def test_random_triad(): """Tests the random_triad function""" G = nx.karate_club_graph() G = G.to_directed() for i in range(100): assert nx.is_triad(nx.random_triad(G))
# -*- coding: utf-8 -*- """ Created on Tue Dec 1 10:23:20 2015 @author: jim """ import networkx as nx import community as cty import pandas as pd import igraph as ig import louvain # networkx approach ----------------------------------------------------------- # get karate club graph graph = nx.karate_club_graph() # get graph measures -------------------------- # order (# vertices) and size (# edges) order = graph.order() size = graph.size() # degree distribution degrees = nx.degree(graph) # density density = nx.density(graph) # diameter diameter = nx.diameter(graph) # dispersion
import networkx as ntx from lib.stochastic_blockmodel import StochasticBlockModel from lib.utils import to_adjacency_matrix if __name__ == "__main__": karate_graph = ntx.karate_club_graph() karate_matrix = to_adjacency_matrix(karate_graph) n_cluster_row = 3 n_cluster_col = 3 sbm = StochasticBlockModel(karate_matrix, n_cluster_row, n_cluster_col) sbm.initialize() Z1_means, Z2_means = sbm.fit(burn_in=100, n_sample=1000, sample_step=10, results_file="samples")
dtype = 'float64' import tqdm import pandas as pd from relaxflow.relax import RELAX from collapsedclustering import CollapsedStochasticBlock, KLcorrectedBound import tensornets as tn from itertools import product from AMSGrad.optimizers import AMSGrad as amsgrad from networkx import karate_club_graph, adjacency_matrix karate = karate_club_graph() X = adjacency_matrix(karate).toarray().astype('float64') N = 9 X = X[:N, :N] #FLAGS name = 'shadowvsrelax' version = 1 Ntest = 0 #number of edges to use for testing K = 2 #number of communities to look for folder = name + 'V{}K{}'.format(version, K) #factors variations to run experiments over random_restarts = 2 nsteps = 10000
from src.libnrl import node2vec, graph import networkx as nx def nx_to_openne_graph(nxgraph): dg = nx.to_directed(nxgraph) nx.set_edge_attributes(dg, 1.0, 'weight') g = graph.Graph() g.G = dg g.encode_node() return g # 2d embeddings for zachary network zachary = nx.karate_club_graph() zachary = nx.relabel_nodes(zachary, {n: str(n) for n in zachary.nodes}) embeddings = node2vec.Node2vec(nx_to_openne_graph(zachary), 10, 80, 2) print(embeddings.vectors)
def test_compute_ricci_curvature_edges(): G = nx.karate_club_graph() orc = OllivierRicci(G, method="OTD", alpha=0.5) output = orc.compute_ricci_curvature_edges([(0, 1)]) npt.assert_almost_equal(output[0, 1], 0.111111)
from networkx import karate_club_graph,to_numpy_matrix import numpy as np import pandas as pd zkc=karate_club_graph() order=sorted(list(zkc.nodes())) NODE_SIZE=len(order) #Adjacency matrix A=to_numpy_matrix(zkc,nodelist=order) #Unit matrix college I=np.eye(zkc.number_of_nodes()) # self loops A_hat=A+I #Standardized adjacency matrix D_hat=np.array(np.sum(A_hat,axis=0))[0] D_hat=np.matrix(np.diag(D_hat)) W1=np.random.normal(loc=0,scale=1,size=(zkc.number_of_nodes(),4)) W2=np.random.normal(loc=1,size=(W1.shape[1],2)) relu=lambda x:np.maximum(0,x) def gcn_layer(A_hat,D_hat,X,W): return relu(D_hat**-1*A_hat*X*W)
def test_ricci_community_all_possible_clusterings(): G = nx.karate_club_graph() orc = OllivierRicci(G, exp_power=1, alpha=0.5) orc.compute_ricci_flow(iterations=40) cc = orc.ricci_community_all_possible_clusterings() cuts = [x[0] for x in cc] clusterings = [x[1] for x in cc] cuts_ans = [ 1.4196268583579972, 1.2196268583579943, 1.1446268583579933, 1.119626858357993, 1.0946268583579926 ] clusterings_ans = [{ 0: 0, 1: 0, 2: 0, 3: 0, 7: 0, 9: 0, 11: 0, 12: 0, 13: 0, 17: 0, 19: 0, 21: 0, 4: 1, 5: 1, 6: 1, 10: 1, 16: 1, 32: 2, 33: 2, 8: 2, 14: 2, 15: 2, 18: 2, 20: 2, 22: 2, 23: 2, 24: 2, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2 }, { 0: 0, 1: 0, 2: 0, 3: 0, 7: 0, 9: 0, 11: 0, 12: 0, 13: 0, 17: 0, 19: 0, 21: 0, 4: 1, 5: 1, 6: 1, 10: 1, 16: 1, 32: 2, 33: 2, 8: 2, 14: 2, 15: 2, 18: 2, 20: 2, 22: 2, 23: 2, 24: 2, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2 }, { 0: 0, 1: 0, 2: 0, 3: 0, 7: 0, 9: 0, 11: 0, 12: 0, 13: 0, 17: 0, 19: 0, 21: 0, 4: 1, 5: 1, 6: 1, 10: 1, 16: 1, 32: 2, 33: 2, 8: 2, 14: 2, 15: 2, 18: 2, 20: 2, 22: 2, 23: 2, 24: 2, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2 }, { 0: 0, 1: 0, 2: 0, 3: 0, 7: 0, 9: 0, 11: 0, 12: 0, 13: 0, 17: 0, 19: 0, 21: 0, 4: 1, 5: 1, 6: 1, 10: 1, 16: 1, 32: 2, 33: 2, 8: 2, 14: 2, 15: 2, 18: 2, 20: 2, 22: 2, 23: 2, 24: 2, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2 }, { 0: 0, 1: 0, 2: 0, 3: 0, 7: 0, 9: 0, 11: 0, 12: 0, 13: 0, 17: 0, 19: 0, 21: 0, 4: 1, 5: 1, 6: 1, 10: 1, 16: 1, 32: 2, 33: 2, 8: 2, 14: 2, 15: 2, 18: 2, 20: 2, 22: 2, 23: 2, 24: 2, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2 }] npt.assert_array_almost_equal(cuts, cuts_ans) assert clusterings == clusterings_ans
def generate_karate_club_graph(): plt.figure() T = nx.karate_club_graph() nx.draw(T, with_labels=True, node_color="lightblue", edge_color="green") plt.savefig("Karate Club Relational Graph.pdf")
def test_karate(): G = nx.karate_club_graph() _check_connectivity(G)
import networkx as nx #importing the packages import random import matplotlib.pyplot as plt g = nx.karate_club_graph() #making the Zachary karate club graph def betweenness(g): #Function to find the betweenness in the graph count = 0 res = [] mat = [] for i in xrange(len( g.nodes())): #Making the matrix to store the betweenness value. mat.append([]) for j in xrange(len(g.nodes())): mat[i].append(0.0) #Initialising it with 0. for i in range(len(g.nodes()) ): #Finding the shortest path between every pair of node. path = nx.single_source_shortest_path( g, i) #Function to get the shortest path. for p in range(len(path)): for k in range(len(path[p]) - 1): mat[path[p][k]][path[p][k + 1]] += 1.0 count = count + len(path) for i in range(len(g.nodes())): #finding the betweenness. for j in range(len(g.nodes())): mat[i][j] = mat[i][j] / count """for i in range(len(g.nodes())): for j in range(i+1,len(g.nodes())): list1 = nx.shortest_path(g,source=i,target=j) for k in range(len(list1)):
def demo_karate(): """demo_karate""" g = nx.karate_club_graph() plot(g)
node_size=500, alpha=0.8) # Draws the edges between the corresponding nodes NX.draw_networkx_edges(G, pos, width=1.0, alpha=0.5) # Draws the labels for each node (e.g., 1, 2, 3, ... n) new_labels = dict((x, x + 1) for x in G.nodes()) NX.draw_networkx_labels(G, pos, new_labels, font_size=14, font_color='black') # Turns the axis off, and saves the graph to the corresponding 'output' file P.axis("off") P.savefig(output) P.draw() P.close() # Function that iteratively removes an edge from the original graph, and saves the new graph to a .png file # Note: This function loops until all edges have been removed! G = NX.karate_club_graph() eNum = G.number_of_edges() for i in range(eNum): pos = NX.spring_layout(G) output = "img/karate%(id)02d.png" % {"id": i} drawGraph(G, pos, output) updateGraph(G)
def get_karate(num_nodes_per_graph=None, aggregation_type="sum", sparse_matrix=True): # F = nx.read_edgelist("./data/karate/edges.txt", nodetype=int) G = nx.karate_club_graph() # edge = np.loadtxt("./data/karate/edges.txt", dtype=np.int32) # 0-based indexing # edge_inv = np.flip(edge, axis=1) # edges = np.concatenate((edge, edge_inv)) # G = nx.DiGraph() # G.add_edges_from(edges) G = G.to_directed() e = len(G.edges) n = len(G.nodes) # F = nx.Graph() # F.add_edges_from(G.edges) edges, agg_matrix = nx_to_format(G, aggregation_type, sparse_matrix=sparse_matrix) is_multilabel = False n_classes = 4 targets = [0] * n # class_nodes = [[]] * n_classes # NB keeps broadcasting also at append time class_nodes = [[], [], [], []] with open("./data/karate/classes.txt") as f: for line in f: node, node_class = map(int, line.split(" ")) targets[node] = node_class class_nodes[node_class].append(node) d_l = n # node_labels = torch.zeros(*[n, d_l]) node_labels = torch.eye(n) targets = torch.tensor(targets, dtype=torch.long) idx_train = [] idx_test = [] for c in class_nodes: perm = np.random.permutation(c) idx_train += list(perm[:1]) # first index for training idx_test += list(perm[1:]) # all other indexes for testing # idx_train += list(perm) # first index for training # idx_test += list(perm) # all other indexes for testing idx_valid = torch.LongTensor(idx_train) idx_train = torch.LongTensor(idx_train) idx_test = torch.LongTensor(idx_test) return Dataset( "karate", n, e, d_l, is_multilabel, n_classes, edges, agg_matrix, node_labels, targets, idx_train, idx_valid, idx_test, )