Python networkx.barabasi_albert_graph() Examples
The following are 22
code examples of networkx.barabasi_albert_graph().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: graphcoloring.py From pyDcop with BSD 3-Clause "New" or "Revised" License | 6 votes |
def generate_scalefree_graph(variables_count, m_edge, allow_subgraph): if not allow_subgraph: graph = nx.barabasi_albert_graph(variables_count, m_edge) is_connected = nx.is_connected(graph) while not is_connected: graph = nx.barabasi_albert_graph(variables_count, m_edge) is_connected = nx.is_connected(graph) else: graph = nx.barabasi_albert_graph(variables_count, m_edge) # In the obtained graph, low rank nodes will have a much higher edge count # than high rank nodes. We shuffle the nodes names to avoid this effect: new_nodes = list(range(variables_count)) random.shuffle(new_nodes) node_mapping = {n: nn for n, nn in zip(graph.nodes, new_nodes)} new_graph = nx.Graph((node_mapping[e1], node_mapping[e2]) for e1, e2 in graph.edges) return new_graph
Example #2
Source File: generate_scalefree.py From AMLSim with Apache License 2.0 | 6 votes |
def powerlaw_cluster_generator(_n, _edge_factor): edges = nx.barabasi_albert_graph(_n, _edge_factor, seed=0).edges() # Undirected edges # Swap the direction of half edges to diffuse degree di_edges = [(edges[i][0], edges[i][1]) if i % 2 == 0 else (edges[i][1], edges[i][0]) for i in range(len(edges))] _g = nx.DiGraph() _g.add_edges_from(di_edges) # Create a directed graph return _g
Example #3
Source File: test_attributeclustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def test_ilouvain(self): l1 = [0.1, 0.4, 0.5] l2 = [34, 3, 112] g = nx.barabasi_albert_graph(100, 5) labels = dict() for node in g.nodes(): labels[node] = {"l1": random.choice(l1), "l2": random.choice(l2)} id = dict() for n in g.nodes(): id[n] = n coms = algorithms.ilouvain(g, labels, id) self.assertEqual(type(coms.communities), list)
Example #4
Source File: test_attributeclustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def test_eva(self): l1 = ['one', 'two', 'three', 'four'] l2 = ["A", "B", "C"] g = nx.barabasi_albert_graph(100, 5) labels = dict() for node in g.nodes(): labels[node] = {"l1": random.choice(l1), "l2": random.choice(l2)} coms = algorithms.eva(g, labels, alpha=0.5) self.assertEqual(type(coms.communities), list) if len(coms.communities) > 0: self.assertEqual(type(coms.communities[0]), list) self.assertEqual(type(coms.communities[0][0]), int)
Example #5
Source File: synthetic_structsim.py From gnn-model-explainer with Apache License 2.0 | 6 votes |
def ba(start, width, role_start=0, m=5): """Builds a BA preferential attachment graph, with index of nodes starting at start and role_ids at role_start INPUT: ------------- start : starting index for the shape width : int size of the graph role_start : starting index for the roles OUTPUT: ------------- graph : a house shape graph, with ids beginning at start roles : list of the roles of the nodes (indexed starting at role_start) """ graph = nx.barabasi_albert_graph(width, m) graph.add_nodes_from(range(start, start + width)) nids = sorted(graph) mapping = {nid: start + i for i, nid in enumerate(nids)} graph = nx.relabel_nodes(graph, mapping) roles = [role_start for i in range(width)] return graph, roles
Example #6
Source File: test_fitness_functions.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def test_purity(self): l1 = ['one', 'two', 'three', 'four'] l2 = ["A", "B", "C"] g_attr = nx.barabasi_albert_graph(100, 5) labels = dict() for node in g_attr.nodes(): labels[node] = {"l1": random.choice(l1), "l2": random.choice(l2)} coms = eva(g_attr, labels, alpha=0.8) pur = evaluation.purity(coms) self.assertGreaterEqual(pur.score, 0) self.assertLessEqual(pur.score, 1)
Example #7
Source File: test_distance.py From netrd with MIT License | 6 votes |
def test_quantum_jsd(): """Run the above tests again using the collision entropy instead of the Von Neumann entropy to ensure that all the logic of the JSD implementation is tested. """ with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="JSD is only a metric for 0 ≤ q < 2.") JSD = distance.QuantumJSD() G = nx.karate_club_graph() dist = JSD.dist(G, G, beta=0.1, q=2) assert np.isclose(dist, 0.0) G1 = nx.fast_gnp_random_graph(100, 0.3) G2 = nx.barabasi_albert_graph(100, 5) dist = JSD.dist(G1, G2, beta=0.1, q=2) assert dist > 0.0 G1 = nx.barabasi_albert_graph(100, 4) G2 = nx.fast_gnp_random_graph(100, 0.3) dist1 = JSD.dist(G1, G2, beta=0.1, q=2) dist2 = JSD.dist(G2, G1, beta=0.1, q=2) assert np.isclose(dist1, dist2)
Example #8
Source File: test_graphical.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_valid_degree_sequence2(): n = 100 for i in range(10): G = nx.barabasi_albert_graph(n, 1) deg = (d for n, d in G.degree()) assert_true(nx.is_graphical(deg, method='eg')) assert_true(nx.is_graphical(deg, method='hh'))
Example #9
Source File: test_graphical.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_valid_degree_sequence2(): n = 100 for i in range(10): G = nx.barabasi_albert_graph(n, 1) deg = (d for n, d in G.degree()) assert_true(nx.is_graphical(deg, method='eg')) assert_true(nx.is_graphical(deg, method='hh'))
Example #10
Source File: test_graphical.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_valid_degree_sequence2(): n = 100 for i in range(10): G = nx.barabasi_albert_graph(n,1) deg = list(G.degree().values()) assert_true( nx.is_valid_degree_sequence(deg, method='eg') ) assert_true( nx.is_valid_degree_sequence(deg, method='hh') )
Example #11
Source File: fitness.py From cdlib with BSD 2-Clause "Simplified" License | 5 votes |
def purity(communities): """Purity is the product of the frequencies of the most frequent labels carried by the nodes within the communities :param communities: AttrNodeClustering object :return: FitnessResult object Example: >>> from cdlib.algorithms import eva >>> from cdlib import evaluation >>> import random >>> l1 = ['A', 'B', 'C', 'D'] >>> l2 = ["E", "F", "G"] >>> g = nx.barabasi_albert_graph(100, 5) >>> labels=dict() >>> for node in g.nodes(): >>> labels[node]={"l1":random.choice(l1), "l2":random.choice(l2)} >>> communities = eva(g_attr, labels, alpha=0.5) >>> pur = evaluation.purity(communities) :References: 1. Citraro, Salvatore, and Giulio Rossetti. "Eva: Attribute-Aware Network Segmentation." International Conference on Complex Networks and Their Applications. Springer, Cham, 2019. """ pur = Eva.purity(communities.coms_labels) return FitnessResult(score=pur)
Example #12
Source File: test_distance.py From netrd with MIT License | 5 votes |
def test_symmetry(): """The distance between two graphs must be symmetric.""" G1 = nx.barabasi_albert_graph(100, 4) G2 = nx.fast_gnp_random_graph(100, 0.3) for label, obj in distance.__dict__.items(): if isinstance(obj, type) and BaseDistance in obj.__bases__: dist1 = obj().dist(G1, G2) dist2 = obj().dist(G2, G1) assert np.isclose(dist1, dist2)
Example #13
Source File: test_distance.py From netrd with MIT License | 5 votes |
def test_different_graphs(): """ The distance between two different graphs must be nonzero.""" ## NOTE: This test is not totally rigorous. For example, two different ## networks may have the same eigenvalues, thus a method that compares ## their eigenvalues would result in distance 0. However, this is very ## unlikely in the constructed case, so we rely on it for now. G1 = nx.fast_gnp_random_graph(100, 0.3) G2 = nx.barabasi_albert_graph(100, 5) for obj in distance.__dict__.values(): if isinstance(obj, type) and BaseDistance in obj.__bases__: dist = obj().dist(G1, G2) assert dist > 0.0
Example #14
Source File: data.py From diffpool with MIT License | 5 votes |
def gen_ba(n_range, m_range, num_graphs, feature_generator=None): graphs = [] for i in np.random.choice(n_range, num_graphs): for j in np.random.choice(m_range, 1): graphs.append(nx.barabasi_albert_graph(i,j)) if feature_generator is None: feature_generator = ConstFeatureGen(0) for G in graphs: feature_generator.gen_node_features(G) return graphs
Example #15
Source File: utils.py From GraphRNN with MIT License | 5 votes |
def test_perturbed(): graphs = [] for i in range(100,101): for j in range(4,5): for k in range(500): graphs.append(nx.barabasi_albert_graph(i,j)) g_perturbed = perturb(graphs, 0.9) print([g.number_of_edges() for g in graphs]) print([g.number_of_edges() for g in g_perturbed])
Example #16
Source File: utils.py From graph-generation with MIT License | 5 votes |
def test_perturbed(): graphs = [] for i in range(100,101): for j in range(4,5): for k in range(500): graphs.append(nx.barabasi_albert_graph(i,j)) g_perturbed = perturb(graphs, 0.9) print([g.number_of_edges() for g in graphs]) print([g.number_of_edges() for g in g_perturbed])
Example #17
Source File: data.py From GraphRNN with MIT License | 4 votes |
def calc_adj(self,adj): max_iter = 10000 adj_all = [adj] adj_all_len = 1 i_old = 0 for i in range(max_iter): adj_copy = adj.copy() x_idx = np.random.permutation(adj_copy.shape[0]) adj_copy = adj_copy[np.ix_(x_idx, x_idx)] adj_copy_matrix = np.asmatrix(adj_copy) G = nx.from_numpy_matrix(adj_copy_matrix) # then do bfs in the permuted G start_idx = np.random.randint(adj_copy.shape[0]) x_idx = np.array(bfs_seq(G, start_idx)) adj_copy = adj_copy[np.ix_(x_idx, x_idx)] add_flag = True for adj_exist in adj_all: if np.array_equal(adj_exist, adj_copy): add_flag = False break if add_flag: adj_all.append(adj_copy) adj_all_len += 1 if adj_all_len % 10 ==0: print('adj found:',adj_all_len,'iter used',i) return adj_all # graphs = [nx.barabasi_albert_graph(20,3)] # graphs = [nx.grid_2d_graph(4,4)] # dataset = Graph_sequence_sampler_pytorch_nll(graphs) ############## below are codes not used in current version ############## they are based on pytorch default data loader, we should consider reimplement them in current datasets, since they are more efficient # normal version
Example #18
Source File: data.py From graph-generation with MIT License | 4 votes |
def calc_adj(self,adj): max_iter = 10000 adj_all = [adj] adj_all_len = 1 i_old = 0 for i in range(max_iter): adj_copy = adj.copy() x_idx = np.random.permutation(adj_copy.shape[0]) adj_copy = adj_copy[np.ix_(x_idx, x_idx)] adj_copy_matrix = np.asmatrix(adj_copy) G = nx.from_numpy_matrix(adj_copy_matrix) # then do bfs in the permuted G start_idx = np.random.randint(adj_copy.shape[0]) x_idx = np.array(bfs_seq(G, start_idx)) adj_copy = adj_copy[np.ix_(x_idx, x_idx)] add_flag = True for adj_exist in adj_all: if np.array_equal(adj_exist, adj_copy): add_flag = False break if add_flag: adj_all.append(adj_copy) adj_all_len += 1 if adj_all_len % 10 ==0: print('adj found:',adj_all_len,'iter used',i) return adj_all # graphs = [nx.barabasi_albert_graph(20,3)] # graphs = [nx.grid_2d_graph(4,4)] # dataset = Graph_sequence_sampler_pytorch_nll(graphs) ############## below are codes not used in current version ############## they are based on pytorch default data loader, we should consider reimplement them in current datasets, since they are more efficient # normal version
Example #19
Source File: attribute_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 4 votes |
def eva(g_original, labels, weight='weight', resolution=1., randomize=False, alpha=0.5): """ The Eva algorithm extends the Louvain approach in order to deal with the attributes of the nodes (aka Louvain Extended to Vertex Attributes). It optimizes - combining them linearly - two quality functions, a structural and a clustering one, namely Newman's modularity and purity, estimated as the product of the frequencies of the most frequent labels carried by the nodes within the communities. A parameter alpha tunes the importance of the two functions: an high value of alpha favors the clustering criterion instead of the structural one. :param g_original: a networkx/igraph object :param labels: dictionary specifying for each node (key) a dict (value) specifying the name attribute (key) and its value (value) :param weight: str, optional the key in graph to use as weight. Default to 'weight' :param resolution: double, optional Will change the size of the communities, default to 1. :param randomize: boolean, optional Will randomize the node evaluation order and the community evaluation order to get different partitions at each call, default False :param alpha: float, assumed in [0,1], optional Will tune the importance of modularity and purity criteria, default to 0.5 :return: AttrNodeClustering object :Example: >>> from cdlib.algorithms import eva >>> import networkx as nx >>> import random >>> l1 = ['A', 'B', 'C', 'D'] >>> l2 = ["E", "F", "G"] >>> g_attr = nx.barabasi_albert_graph(100, 5) >>> labels=dict() >>> for node in g_attr.nodes(): >>> labels[node]={"l1":random.choice(l1), "l2":random.choice(l2)} >>> communities = eva(g_attr, labels, alpha=0.8) :References: 1. Citraro, S., & Rossetti, G. (2019, December). Eva: Attribute-Aware Network Segmentation. In International Conference on Complex Networks and Their Applications (pp. 141-151). Springer, Cham. .. note:: Reference implementation: https://github.com/GiulioRossetti/Eva/tree/master/Eva """ g = convert_graph_formats(g_original, nx.Graph) nx.set_node_attributes(g, labels) coms, coms_labels = Eva.eva_best_partition(g, weight=weight, resolution=resolution, randomize=randomize, alpha=alpha) # Reshaping the results coms_to_node = defaultdict(list) for n, c in coms.items(): coms_to_node[c].append(n) coms_eva = [list(c) for c in coms_to_node.values()] return AttrNodeClustering(coms_eva, g_original, "Eva", coms_labels, method_parameters={"weight": weight, "resolution": resolution, "randomize": randomize, "alpha":alpha})
Example #20
Source File: graph_gens.py From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License | 4 votes |
def barabasi_albert_graph(N, deg, dia, dim, domain): ''' Parameters of the graph: n: Number of Nodes m: Number of edges to attach from a new node to existing nodes Formula for m: (m^2)- (Nm)/2 + avg_deg * (N/2) = 0 => From this equation we need to find m : :return: Graph Object ''' ## Calculating thof nodes: 10\nNumber of edges: 16\nAverage degree: 3.2000' ## As does not have for Diameter Variance if dia > 0: return None strt_time = time() m = int(round((N - np.sqrt(N**2 - 4*deg*N))/4)) G = nx.barabasi_albert_graph(n=N, m=m) lcc, _ = graph_util.get_lcc_undirected(G) best_G = lcc best_diam = nx.algorithms.diameter(best_G) best_avg_deg = np.mean(list(dict(nx.degree(best_G)).values())) end_time = time() print('Graph_Name: Barabasi Albert Graph') print('Num_Nodes: ', nx.number_of_nodes(best_G), ' Avg_Deg : ', best_avg_deg, ' Diameter: ', best_diam) print('TIME: ' , end_time - strt_time, ' secs') return best_G, best_avg_deg, best_diam ########################################################################################################################
Example #21
Source File: molecule.py From rl_graph_generation with BSD 3-Clause "New" or "Revised" License | 4 votes |
def init(self, reward_step_total=1, is_normalize=0,dataset='ba'): ''' own init function, since gym does not support passing argument ''' self.is_normalize = bool(is_normalize) self.graph = nx.Graph() self.reward_step_total = reward_step_total self.counter = 0 ## load expert data if dataset == 'caveman': self.dataset = [] for i in range(2, 3): for j in range(6, 11): for k in range(20): self.dataset.append(caveman_special(i, j, p_edge=0.8)) # default 0.8 self.max_node = 25 self.max_action = 150 elif dataset == 'grid': self.dataset = [] for i in range(2, 5): for j in range(2, 6): self.dataset.append(nx.grid_2d_graph(i, j)) self.max_node = 25 self.max_action = 100 else: print('default dataset: barabasi') self.dataset = [] for i in range(4, 21): for j in range(3, 4): for k in range(10): self.dataset.append(nx.barabasi_albert_graph(i, j)) self.max_node = 25 self.max_action = 150 self.action_space = gym.spaces.MultiDiscrete([self.max_node, self.max_node, 3, 2]) self.observation_space = {} self.observation_space['adj'] = gym.Space(shape=[1, self.max_node, self.max_node]) self.observation_space['node'] = gym.Space(shape=[1, self.max_node, 1]) self.level = 0 # for curriculum learning, level starts with 0, and increase afterwards # compatible with molecule env self.max_atom = self.max_node self.atom_type_num = 1
Example #22
Source File: iot.py From pyDcop with BSD 3-Clause "New" or "Revised" License | 4 votes |
def generate_powerlaw_var_constraints( num_var: int, domain_size: int, constraint_range: int ) -> Tuple[Dict[str, Variable], Dict[str, Constraint], Domain]: """ Generate variables and constraints for a power-law based constraints graph. All constraints are binary and the graph is generated using the Barabasi Albert method. Parameters ---------- num_var: int number of variables domain_size: int size of the domain of the variables constraint_range: int range in which constraints take their value (uniform random value of ech possible assignment). Returns ------- A tuple with variables, constraints and domain. """ # Use a barabasi powerlaw based constraints graph graph = nx.barabasi_albert_graph(num_var, 2) # import matplotlib.pyplot as plt # plt.subplot(121) # nx.draw(graph) # default spring_layout # plt.show() domain = Domain("d", "d", range(domain_size)) variables = {} for n in graph.nodes: v = Variable(var_name(n), domain) variables[v.name] = v logger.debug("Create var for node %s : %s", n, v) constraints = {} for i, (n1, n2) in enumerate(graph.edges): v1 = variables[var_name(n1)] v2 = variables[var_name(n2)] values = random_assignment_matrix([v1, v2], range(constraint_range)) c = NAryMatrixRelation([v1, v2], values, name=c_name(n1, n2)) logger.debug("Create constraints for edge (%s, %s) : %s", v1, v2, c) constraints[c.name] = c logger.info( "Generates %s variables and %s constraints in a powerlaw" "network", len(variables), len(constraints), ) return variables, constraints, domain