def dense_gnm_random_graph(n, m, seed=None): """Returns a `G_{n,m}` random graph. In the `G_{n,m}` model, a graph is chosen uniformly at random from the set of all graphs with `n` nodes and `m` edges. This algorithm should be faster than :func:`gnm_random_graph` for dense graphs. Parameters ---------- n : int The number of nodes. m : int The number of edges. seed : int, optional Seed for random number generator (default=None). See Also -------- gnm_random_graph() Notes ----- Algorithm by Keith M. Briggs Mar 31, 2006. Inspired by Knuth's Algorithm S (Selection sampling technique), in section 3.4.2 of [1]_. References ---------- .. [1] Donald E. Knuth, The Art of Computer Programming, Volume 2/Seminumerical algorithms, Third Edition, Addison-Wesley, 1997. """ mmax = n * (n - 1) / 2 if m >= mmax: G = complete_graph(n) else: G = empty_graph(n) G.name = "dense_gnm_random_graph(%s,%s)" % (n, m) if n == 1 or m >= mmax: return G if seed is not None: random.seed(seed) u = 0 v = 1 t = 0 k = 0 while True: if random.randrange(mmax - t) < m - k: G.add_edge(u, v) k += 1 if k == m: return G t += 1 v += 1 if v == n: # go to next row of adjacency matrix u += 1 v = u + 1
def test_correctness(): # note: in the future can restrict all graphs to have the same number of nodes, for analysis graphs = [lambda: basic_graph(), lambda: complete_graph(10), lambda: balanced_tree(3, 5), lambda: barbell_graph(6, 7), lambda: binomial_tree(10), lambda: cycle_graph(50), lambda: path_graph(200), lambda: star_graph(200)] names = ["basic_graph", "complete_graph", "balanced_tree", "barbell_graph", "binomial_tree", "cycle_graph", "path_graph", "star_graph"] for graph, name in zip(graphs, names): print(f"Testing graph {name}...") # Initialize both graphs G_dinitz = graph() G_gr = graph() # Set random capacities of graph edges for u, v in G_dinitz.edges: cap = randint(1, 20) G_dinitz.edges[u, v]["capacity"] = cap G_gr.edges[u, v]["capacity"] = cap # Pick random start and end node start_node = randint(0, len(G_dinitz.nodes)-1) end_node = randint(0, len(G_dinitz.nodes)-1) while start_node == end_node: end_node = randint(0, len(G_dinitz.nodes)-1) # Run max-flow R_dinitz = dinitz(G_dinitz, start_node, end_node) R_gr = goldberg_rao(G_gr, start_node, end_node) # Check correctness d_mf = R_dinitz.graph["flow_value"] gr_mf = R_gr.graph["flow_value"] assert d_mf == gr_mf, f"Computed max flow in {name} graph is {d_mf}, but goldberg_rao function computed {gr_mf}"
def tetrahedral_graph(create_using=None): """ Returns the 3-regular Platonic Tetrahedral graph. Tetrahedral graph has 4 nodes and 6 edges. It is a special case of the complete graph, K4, and wheel graph, W4. It is one of the 5 platonic graphs [1]_. Parameters ---------- create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : networkx Graph Tetrahedral Grpah References ---------- .. [1] https://en.wikipedia.org/wiki/Tetrahedron#Tetrahedral_graph """ G = complete_graph(4, create_using) G.name = "Platonic Tetrahedral graph" return G
def dense_gnm_random_graph(n, m, seed=None): """Returns a `G_{n,m}` random graph. In the `G_{n,m}` model, a graph is chosen uniformly at random from the set of all graphs with `n` nodes and `m` edges. This algorithm should be faster than :func:`gnm_random_graph` for dense graphs. Parameters ---------- n : int The number of nodes. m : int The number of edges. seed : int, optional Seed for random number generator (default=None). See Also -------- gnm_random_graph() Notes ----- Algorithm by Keith M. Briggs Mar 31, 2006. Inspired by Knuth's Algorithm S (Selection sampling technique), in section 3.4.2 of [1]_. References ---------- .. [1] Donald E. Knuth, The Art of Computer Programming, Volume 2/Seminumerical algorithms, Third Edition, Addison-Wesley, 1997. """ mmax=n*(n-1)/2 if m>=mmax: G=complete_graph(n) else: G=empty_graph(n) G.name="dense_gnm_random_graph(%s,%s)"%(n,m) if n==1 or m>=mmax: return G if seed is not None: random.seed(seed) u=0 v=1 t=0 k=0 while True: if random.randrange(mmax-t)<m-k: G.add_edge(u,v) k+=1 if k==m: return G t+=1 v+=1 if v==n: # go to next row of adjacency matrix u+=1 v=u+1
def extended_prefential_attachment(num_nodes, p, r): """Returns a random graph according to the Barabasi-Albert preferential attachment model with the extension explained by Cooper et al. A graph of ``num_nodes`` nodes is grown by attaching new nodes each with ``r`` edges that are preferentially attached to existing nodes with high degree. Parameters ---------- num_nodes : int Number of nodes p : float Probability of doing preferential attachment; with 1 - p, we add an edge to a random neighbour. r : int Number of edges to add for every new vertex. Returns ------- G : Graph """ # Add r initial nodes (m0 in barabasi-speak) G = complete_graph(r) G.name = "extended_barabasi_albert_graph(%s,%s)" % (num_nodes, r) # List of existing nodes, with nodes repeated once for each adjacent edge repeated_nodes = range(0, r) * (r - 1) # Start adding the other n-r nodes. The first node is r. source = r while source < num_nodes: # First edge is (source, vertex_chosen_preferentially) i = random.randint(0, len(repeated_nodes) - 1) x = repeated_nodes[i] G.add_edge(source, x) repeated_nodes.extend([source, x]) # Add the remaining r - 1 edges for i in range(0, r - 1): curr_p = uniform() if curr_p <= p: # Attach new vertex to an existing vertex (by preferential # attachment) i = random.randint(0, len(repeated_nodes) - 1) target = repeated_nodes[i] G.add_edge(source, target) repeated_nodes.extend([source, target]) else: # Attach new vertex to random neighbour of x i = random.randint(0, len(G.neighbors(x)) - 1) target = G.neighbors(x)[i] G.add_edge(source, target) repeated_nodes.extend([source, target]) source += 1 if source % 1000 == 0: print(info(G)) return G
def dense_gnm_random_graph(n, m, seed=None): """Returns a $G_{n,m}$ random graph. In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set of all graphs with $n$ nodes and $m$ edges. This algorithm should be faster than :func:`gnm_random_graph` for dense graphs. Parameters ---------- n : int The number of nodes. m : int The number of edges. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. See Also -------- gnm_random_graph() Notes ----- Algorithm by Keith M. Briggs Mar 31, 2006. Inspired by Knuth's Algorithm S (Selection sampling technique), in section 3.4.2 of [1]_. References ---------- .. [1] Donald E. Knuth, The Art of Computer Programming, Volume 2/Seminumerical algorithms, Third Edition, Addison-Wesley, 1997. """ mmax = n * (n - 1) / 2 if m >= mmax: G = complete_graph(n) else: G = empty_graph(n) if n == 1 or m >= mmax: return G u = 0 v = 1 t = 0 k = 0 while True: if seed.randrange(mmax - t) < m - k: G.add_edge(u, v) k += 1 if k == m: return G t += 1 v += 1 if v == n: # go to next row of adjacency matrix u += 1 v = u + 1
def gnp_random_graph(n, p, seed=None, directed=False): """Returns a `G_{n,p}` random graph, also known as an Erdős-Rényi graph or a binomial graph. The `G_{n,p}` model chooses each of the possible edges with probability ``p``. The functions :func:`binomial_graph` and :func:`erdos_renyi_graph` are aliases of this function. Parameters ---------- n : int The number of nodes. p : float Probability for edge creation. seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=False) If ``True``, this function returns a directed graph. See Also -------- fast_gnp_random_graph Notes ----- This algorithm runs in `O(n^2)` time. For sparse graphs (that is, for small values of `p`), :func:`fast_gnp_random_graph` is a faster algorithm. References ---------- .. [1] P. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959). .. [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959). """ if directed: G=nx.DiGraph() else: G=nx.Graph() G.add_nodes_from(range(n)) G.name="gnp_random_graph(%s,%s)"%(n,p) if p<=0: return G if p>=1: return complete_graph(n,create_using=G) if not seed is None: random.seed(seed) if G.is_directed(): edges=itertools.permutations(range(n),2) else: edges=itertools.combinations(range(n),2) for e in edges: if random.random() < p: G.add_edge(*e) return G
def gnp_random_graph(n, p, seed=None, directed=False): """Returns a `G_{n,p}` random graph, also known as an Erdős-Rényi graph or a binomial graph. The `G_{n,p}` model chooses each of the possible edges with probability ``p``. The functions :func:`binomial_graph` and :func:`erdos_renyi_graph` are aliases of this function. Parameters ---------- n : int The number of nodes. p : float Probability for edge creation. seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=False) If ``True``, this function returns a directed graph. See Also -------- fast_gnp_random_graph Notes ----- This algorithm runs in `O(n^2)` time. For sparse graphs (that is, for small values of `p`), :func:`fast_gnp_random_graph` is a faster algorithm. References ---------- .. [1] P. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959). .. [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959). """ if directed: G = nx.DiGraph() else: G = nx.Graph() G.add_nodes_from(range(n)) G.name = "gnp_random_graph(%s,%s)" % (n, p) if p <= 0: return G if p >= 1: return complete_graph(n, create_using=G) if not seed is None: random.seed(seed) if G.is_directed(): edges = itertools.permutations(range(n), 2) else: edges = itertools.combinations(range(n), 2) for e in edges: if random.random() < p: G.add_edge(*e) return G
def anti_barabasi(n,m): G = complete_graph(m) #target nodes for new nodes targets = list(range(m)) new = m#initialize = m while new < n: G.add_edges_from(zip([new]*m,targets))#add m edge together targets = prob_subset(G,m) new += 1 return G
def gnp_random_graph(n, p, seed=None, directed=False): """Return a random graph G_{n,p} (Erdős-Rényi graph, binomial graph). Chooses each of the possible edges with probability p. This is also called binomial_graph and erdos_renyi_graph. Parameters ---------- n : int The number of nodes. p : float Probability for edge creation. seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=False) If True return a directed graph See Also -------- fast_gnp_random_graph Notes ----- This is an O(n^2) algorithm. For sparse graphs (small p) see fast_gnp_random_graph for a faster algorithm. References ---------- .. [1] P. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959). .. [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959). """ if directed: G=nx.DiGraph() else: G=nx.Graph() G.add_nodes_from(range(n)) G.name="gnp_random_graph(%s,%s)"%(n,p) if p<=0: return G if p>=1: return complete_graph(n,create_using=G) if not seed is None: random.seed(seed) if G.is_directed(): edges=itertools.permutations(range(n),2) else: edges=itertools.combinations(range(n),2) for e in edges: if random.random() < p: G.add_edge(*e) return G
def gnp_random_graph(n, p, seed=None, directed=False): """Return a random graph G_{n,p} (Erdős-Rényi graph, binomial graph). Chooses each of the possible edges with probability p. This is also called binomial_graph and erdos_renyi_graph. Parameters ---------- n : int The number of nodes. p : float Probability for edge creation. seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=False) If True return a directed graph See Also -------- fast_gnp_random_graph Notes ----- This is an O(n^2) algorithm. For sparse graphs (small p) see fast_gnp_random_graph for a faster algorithm. References ---------- .. [1] P. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959). .. [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959). """ if directed: G = nx.DiGraph() else: G = nx.Graph() G.add_nodes_from(range(n)) G.name = "gnp_random_graph(%s,%s)" % (n, p) if p <= 0: return G if p >= 1: return complete_graph(n, create_using=G) if not seed is None: random.seed(seed) if G.is_directed(): edges = itertools.permutations(range(n), 2) else: edges = itertools.combinations(range(n), 2) for e in edges: if random.random() < p: G.add_edge(*e) return G
def gnm_random_graph(n, m, seed=None, directed=False): """Returns a `G_{n,m}` random graph. In the `G_{n,m}` model, a graph is chosen uniformly at random from the set of all graphs with `n` nodes and `m` edges. This algorithm should be faster than :func:`dense_gnm_random_graph` for sparse graphs. Parameters ---------- n : int The number of nodes. m : int The number of edges. seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=False) If True return a directed graph See also -------- dense_gnm_random_graph """ if directed: G = nx.DiGraph() else: G = nx.Graph() G.add_nodes_from(range(n)) G.name = "gnm_random_graph(%s,%s)" % (n, m) if seed is not None: random.seed(seed) if n == 1: return G max_edges = n * (n - 1) if not directed: max_edges /= 2.0 if m >= max_edges: return complete_graph(n, create_using=G) nlist = G.nodes() edge_count = 0 while edge_count < m: # generate random edge,u,v u = random.choice(nlist) v = random.choice(nlist) if u == v or G.has_edge(u, v): continue else: G.add_edge(u, v) edge_count = edge_count + 1 return G
def gnm_random_graph(n, m, seed=None, directed=False): """Returns a `G_{n,m}` random graph. In the `G_{n,m}` model, a graph is chosen uniformly at random from the set of all graphs with `n` nodes and `m` edges. This algorithm should be faster than :func:`dense_gnm_random_graph` for sparse graphs. Parameters ---------- n : int The number of nodes. m : int The number of edges. seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=False) If True return a directed graph See also -------- dense_gnm_random_graph """ if directed: G=nx.DiGraph() else: G=nx.Graph() G.add_nodes_from(range(n)) G.name="gnm_random_graph(%s,%s)"%(n,m) if seed is not None: random.seed(seed) if n==1: return G max_edges=n*(n-1) if not directed: max_edges/=2.0 if m>=max_edges: return complete_graph(n,create_using=G) nlist=G.nodes() edge_count=0 while edge_count < m: # generate random edge,u,v u = random.choice(nlist) v = random.choice(nlist) if u==v or G.has_edge(u,v): continue else: G.add_edge(u,v) edge_count=edge_count+1 return G
def barabasi_albert_with_opinion_graph_formation(self, seed=None): """Returns a random graph according to the Barabási–Albert preferential attachment model. """ if self.growth < 1 or self.growth >= self.size_num: raise nx.NetworkXError("Barabási–Albert network must have m >= 1" " and m < n, m = %d, n = %d" % (self.growth, self.size_num)) # Add m initial nodes (m0 in barabasi-speak) self.graph = complete_graph(self.init_num) s = np.random.random_sample(self.init_num) # print("initial value:", dict(enumerate(s))) nx.set_node_attributes(self.graph, dict(enumerate(s)), 'opinion') repeated_nodes = list(self.graph.nodes(data=False)) # Start adding the other n-m nodes. The first node is m. source = self.growth while source < INIT_SIZE: opinion_value = np.random.random_sample() nodes = list(self.graph.nodes(data=True)) pa_nodes = self.opinion_filter(opinion_value, nodes) targets = self._random_subset(pa_nodes, repeated_nodes, self.growth, seed) self.graph.add_node(source, opinion=opinion_value) self.graph.add_edges_from(zip([source] * self.growth, targets)) repeated_nodes.extend(targets) repeated_nodes.extend([source] * self.growth) source += 1 while source < self.size_num: opinion_value = np.random.random_sample() nodes = list(self.graph.nodes(data=True)) # pa_nodes = self.opinion_filter(opinion_value, nodes) if self.opinion: pa_nodes = self.opinion_filter(opinion_value, nodes) else: for node in nodes: pa_nodes[node[0]] = True targets = self._random_subset(pa_nodes, repeated_nodes, self.growth, seed) self.graph.add_node(source, opinion=opinion_value) self.graph.add_edges_from(zip([source] * self.growth, targets)) # self.d += self.growth repeated_nodes.extend(targets) repeated_nodes.extend([source] * self.growth) # formation in growth self.opinion_formation_in_growth() source += 1 if source in [500, 1000, 1500, 2000]: filename1 = self.save_degree_opinion_distribution(source) filename2 = self.save_inter_distribution(source) access_token = get_access_token() buckets = list_buckets('disstask', access_token) bucket_name = buckets["items"][0]["id"] upload_file(bucket_name, access_token, 'disstask', filename1) upload_file(bucket_name, access_token, 'disstask', filename2) return self.graph
def run_analysis_n_nodes(n, unit_cap, n_runs=1): print(f"Running analysis for {n} nodes...") graphs = [lambda: complete_graph(n)] results_gr = {} results_dinitz = {} for graph, name in zip(graphs, names): # Initialize both graphs G_dinitz = graph() G_gr = G_dinitz.copy() total_time_gr = 0 total_time_dinitz = 0 for _ in range(n_runs): # Set random capacities of graph edges for u, v in G_dinitz.edges: cap = randint(1, 100) if not unit_cap else 1 G_dinitz.edges[u, v]["capacity"] = cap G_gr.edges[u, v]["capacity"] = cap # Pick random start and end node start_node = randint(0, len(G_dinitz.nodes) - 1) end_node = randint(0, len(G_dinitz.nodes) - 1) while start_node == end_node: end_node = randint(0, len(G_dinitz.nodes) - 1) # Run max-flow init_time = time.time() R_dinitz = dinitz(G_dinitz, start_node, end_node) total_time_dinitz += time.time() - init_time init_time = time.time() R_gr = goldberg_rao(G_gr, start_node, end_node) total_time_gr += time.time() - init_time # Check correctness d_mf = R_dinitz.graph["flow_value"] gr_mf = R_gr.graph["flow_value"] if d_mf != gr_mf: vprint( f"\t\t\tComputed max flow in {name} graph is {d_mf}, but goldberg_rao function computed {gr_mf}" .upper()) vprint( f"{name} with {n} nodes took {total_time_gr / n_runs} seconds with goldberg_rao" ) vprint( f"{name} with {n} nodes took {total_time_dinitz / n_runs} seconds with dinitz" ) results_gr[name] = total_time_gr / n_runs results_dinitz[name] = total_time_dinitz / n_runs return results_gr, results_dinitz
def gnm_random_graph(n, m, seed=None, directed=False): """Returns a $G_{n,m}$ random graph. In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set of all graphs with $n$ nodes and $m$ edges. This algorithm should be faster than :func:`dense_gnm_random_graph` for sparse graphs. Parameters ---------- n : int The number of nodes. m : int The number of edges. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. directed : bool, optional (default=False) If True return a directed graph See also -------- dense_gnm_random_graph """ if directed: G = nx.DiGraph() else: G = nx.Graph() G.add_nodes_from(range(n)) if n == 1: return G max_edges = n * (n - 1) if not directed: max_edges /= 2.0 if m >= max_edges: return complete_graph(n, create_using=G) nlist = list(G) edge_count = 0 while edge_count < m: # generate random edge,u,v u = seed.choice(nlist) v = seed.choice(nlist) if u == v or G.has_edge(u, v): continue else: G.add_edge(u, v) edge_count = edge_count + 1 return G
def gnp_random_graph(n, p, seed=None, directed=False): """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph or a binomial graph. The $G_{n,p}$ model chooses each of the possible edges with probability $p$. The functions :func:`binomial_graph` and :func:`erdos_renyi_graph` are aliases of this function. Parameters ---------- n : int The number of nodes. p : float Probability for edge creation. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. directed : bool, optional (default=False) If True, this function returns a directed graph. See Also -------- fast_gnp_random_graph Notes ----- This algorithm [2]_ runs in $O(n^2)$ time. For sparse graphs (that is, for small values of $p$), :func:`fast_gnp_random_graph` is a faster algorithm. References ---------- .. [1] P. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959). .. [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959). """ if directed: edges = itertools.permutations(range(n), 2) G = nx.DiGraph() else: edges = itertools.combinations(range(n), 2) G = nx.Graph() G.add_nodes_from(range(n)) if p <= 0: return G if p >= 1: return complete_graph(n, create_using=G) for e in edges: if seed.random() < p: G.add_edge(*e) return G
def dense_gnm_random_graph(n, m, seed=None): """ Return the random graph G_{n,m}. Gives a graph picked randomly out of the set of all graphs with n nodes and m edges. This algorithm should be faster than gnm_random_graph for dense graphs. :Parameters: - `n`: the number of nodes - `m`: the number of edges - `seed`: seed for random number generator (default=None) Algorithm by Keith M. Briggs Mar 31, 2006. Inspired by Knuth's Algorithm S (Selection sampling technique), in section 3.4.2 of The Art of Computer Programming by Donald E. Knuth Volume 2 / Seminumerical algorithms Third Edition, Addison-Wesley, 1997. """ mmax=n*(n-1)/2 if m>=mmax: G=complete_graph(n) else: G=empty_graph(n) G.name="dense_gnm_random_graph(%s,%s)"%(n,m) if n==1 or m>=mmax: return G if seed is not None: random.seed(seed) u=0 v=1 t=0 k=0 while True: if random.randrange(mmax-t)<m-k: G.add_edge(u,v) k+=1 if k==m: return G t+=1 v+=1 if v==n: # go to next row of adjacency matrix u+=1 v=u+1
def gnm_random_graph(n, m, create_using=None, seed=None): """Return the random graph G_{n,m}. Gives a graph picked randomly out of the set of all graphs with n nodes and m edges. Parameters ---------- n : int The number of nodes. m : int The number of edges. create_using : graph, optional (default Graph) Use specified graph as a container. seed : int, optional Seed for random number generator (default=None). """ if create_using is not None and create_using.is_directed(): raise nx.NetworkXError("Directed Graph not supported") G=empty_graph(n,create_using) G.name="gnm_random_graph(%s,%s)"%(n,m) if seed is not None: random.seed(seed) if n==1: return G if m>=n*(n-1)/2: return complete_graph(n,create_using) nlist=G.nodes() edge_count=0 while edge_count < m: # generate random edge,u,v u = random.choice(nlist) v = random.choice(nlist) if u==v or G.has_edge(u,v): continue # is this faster? # (u,v)=random.sample(nlist,2) # if G.has_edge(u,v): # continue else: G.add_edge(u,v) edge_count=edge_count+1 return G
def gnm_random_graph(n, m, create_using=None, seed=None): """Return the random graph G_{n,m}. Gives a graph picked randomly out of the set of all graphs with n nodes and m edges. Parameters ---------- n : int The number of nodes. m : int The number of edges. create_using : graph, optional (default Graph) Use specified graph as a container. seed : int, optional Seed for random number generator (default=None). """ if create_using is not None and create_using.is_directed(): raise nx.NetworkXError("Directed Graph not supported") G = empty_graph(n, create_using) G.name = "gnm_random_graph(%s,%s)" % (n, m) if seed is not None: random.seed(seed) if n == 1: return G if m >= n * (n - 1) / 2: return complete_graph(n, create_using) nlist = G.nodes() edge_count = 0 while edge_count < m: # generate random edge,u,v u = random.choice(nlist) v = random.choice(nlist) if u == v or G.has_edge(u, v): continue # is this faster? # (u,v)=random.sample(nlist,2) # if G.has_edge(u,v): # continue else: G.add_edge(u, v) edge_count = edge_count + 1 return G
def vehicle_accusation_graph(n, p, seed=None, directed=True): """Return a random vehicle accusation graph G_{n,p}. Chooses each of the possible edges with accusation probability p. Parameters ---------- n : int The number of vehicles. p : float Probability for accusation. seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=True) If True return a directed graph """ if directed: G = nx.DiGraph() else: G = nx.Graph() G.add_nodes_from(range(n)) G.name = 'Vehicle_accusation_graph({}, {})'.format(n, p) if p <= 0: return G if p >= 1: return complete_graph(n, create_using=G) if not seed is None: random.seed(seed) if G.is_directed(): edges = itertools.permutations(range(n), 2) else: edges = itertools.combinations(range(n), 2) for e in edges: if random.random() < p: G.add_edge(*e) """ Remove all isolates in the graph & relabel the nodes of the graph """ if nx.isolates(G): G.remove_nodes_from(nx.isolates(G)) mapping = dict(zip(G.nodes(), range(G.number_of_nodes()))) G = nx.relabel_nodes(G, mapping) return G
def __init__(self, m_0, m , max_num ): self._round = 0 self._network = complete_graph( m_0 ) self._max_nid = m_0 self._nodes_start = dict() self._nodes_end = dict() self._m = m self._max_num = max_num self._choice_list = list() for v in self._network.nodes() : self._nodes_start[ v] = self._round for i in range( self._network.degree( v )): self._choice_list.append( v ) self._round += 1
def gnm_random_graph(n, m, seed=None, directed=False): """Return the random graph G_{n,m}. Produces a graph picked randomly out of the set of all graphs with n nodes and m edges. Parameters ---------- n : int The number of nodes. m : int The number of edges. seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=False) If True return a directed graph """ if directed: G = nx.DiGraph() else: G = nx.Graph() G.add_nodes_from(range(n)) G.name = "gnm_random_graph(%s,%s)" % (n, m) if seed is not None: random.seed(seed) if n == 1: return G max_edges = n * (n - 1) if not directed: max_edges /= 2.0 if m >= max_edges: return complete_graph(n, create_using=G) nlist = G.nodes() edge_count = 0 while edge_count < m: # generate random edge,u,v u = random.choice(nlist) v = random.choice(nlist) if u == v or G.has_edge(u, v): continue else: G.add_edge(u, v) edge_count = edge_count + 1 return G
def gnm_random_graph(n, m, seed=None, directed=False): """Return the random graph G_{n,m}. Produces a graph picked randomly out of the set of all graphs with n nodes and m edges. Parameters ---------- n : int The number of nodes. m : int The number of edges. seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=False) If True return a directed graph """ if directed: G=nx.DiGraph() else: G=nx.Graph() G.add_nodes_from(range(n)) G.name="gnm_random_graph(%s,%s)"%(n,m) if seed is not None: random.seed(seed) if n==1: return G max_edges=n*(n-1) if not directed: max_edges/=2.0 if m>=max_edges: return complete_graph(n,create_using=G) nlist=G.nodes() edge_count=0 while edge_count < m: # generate random edge,u,v u = random.choice(nlist) v = random.choice(nlist) if u==v or G.has_edge(u,v): continue else: G.add_edge(u,v) edge_count=edge_count+1 return G
def vehicle_accusation_graph(n, p, seed=None, directed=True): """Return a random vehicle accusation graph G_{n,p}. Chooses each of the possible edges with accusation probability p. Parameters ---------- n : int The number of vehicles. p : float Probability for accusation. seed : int, optional Seed for random number generator (default=None). directed : bool, optional (default=True) If True return a directed graph """ if directed: G=nx.DiGraph() else: G=nx.Graph() G.add_nodes_from(range(n)) G.name='Vehicle_accusation_graph({}, {})'.format(n, p) if p<=0: return G if p>=1: return complete_graph(n,create_using=G) if not seed is None: random.seed(seed) if G.is_directed(): edges=itertools.permutations(range(n),2) else: edges=itertools.combinations(range(n),2) for e in edges: if random.random() < p: G.add_edge(*e) """ Remove all isolates in the graph & relabel the nodes of the graph """ if nx.isolates(G): G.remove_nodes_from(nx.isolates(G)) mapping = dict(zip(G.nodes(), range(G.number_of_nodes()))) G = nx.relabel_nodes(G, mapping) return G
def barabasi_albert_with_opinion_graph(self, seed=None): """Returns a random graph according to the Barabási–Albert preferential attachment model. """ if self.growth < 1 or self.growth >= self.size_num: raise nx.NetworkXError("Barabási–Albert network must have m >= 1" " and m < n, m = %d, n = %d" % (self.growth, self.size_num)) # Add m initial nodes (m0 in barabasi-speak) self.graph = complete_graph(self.init_num) s = np.random.random_sample(self.init_num) # print("initial value:", dict(enumerate(s))) nx.set_node_attributes(self.graph, dict(enumerate(s)), 'opinion') # List of existing nodes, with nodes repeated once for each adjacent edge repeated_nodes = list(self.graph.nodes(data=False)) # Start adding the other n-m nodes. The first node is m. source = self.growth while source < self.size_num: pa_nodes = {} opinion_value = np.random.random_sample() # Filter nodes from the targets nodes = list(self.graph.nodes(data=True)) # pa_nodes = itemgetter(*targets)(nodes) if self.opinion: pa_nodes = self.opinion_filter(opinion_value, nodes) else: for node in nodes: pa_nodes[node[0]] = True targets = self._random_subset(pa_nodes, repeated_nodes, self.growth, seed) # Add node with opinion self.graph.add_node(source, opinion=opinion_value) # Add edges to m nodes from the source. self.graph.add_edges_from(zip([source] * self.growth, targets)) # Add one node to the list for each new edge just created. repeated_nodes.extend(targets) # And the new node "source" has m edges to add to the list. repeated_nodes.extend([source] * self.growth) # Now choose m unique nodes from the existing nodes # Pick uniformly from repeated_nodes (preferential attachment) # targets = _random_subset(repeated_nodes, m, seed) source += 1 return self.graph
def gnm_random_graph(n, m, seed=None): """ Return the random graph G_{n,m}. Gives a graph picked randomly out of the set of all graphs with n nodes and m edges. :Parameters: - `n`: the number of nodes - `m`: the number of edges - `seed`: seed for random number generator (default=None) """ G=empty_graph(n) G.name="gnm_random_graph(%s,%s)"%(n,m) if seed is not None: random.seed(seed) if n==1: return G if m>=n*(n-1)/2: return complete_graph(n) nlist=G.nodes() edge_count=0 while edge_count < m: # generate random edge,u,v u = random.choice(nlist) v = random.choice(nlist) if u==v or G.has_edge(u,v): continue # is this faster? # (u,v)=random.sample(nlist,2) # if G.has_edge(u,v): # continue else: G.add_edge(u,v) edge_count=edge_count+1 return G
def tetrahedral_graph(): """ Return the 3-regular Platonic Tetrahedral graph.""" G=complete_graph(4) G.name="Platonic Tetrahedral graph" return G
def dense_gnm_random_graph(n, m, create_using=None, seed=None): """Return the random graph G_{n,m}. Gives a graph picked randomly out of the set of all graphs with n nodes and m edges. This algorithm should be faster than gnm_random_graph for dense graphs. Parameters ---------- n : int The number of nodes. m : int The number of edges. create_using : graph, optional (default Graph) Use specified graph as a container. seed : int, optional Seed for random number generator (default=None). See Also -------- gnm_random_graph() Notes ----- Algorithm by Keith M. Briggs Mar 31, 2006. Inspired by Knuth's Algorithm S (Selection sampling technique), in section 3.4.2 of References ---------- .. [1] Donald E. Knuth, The Art of Computer Programming, Volume 2 / Seminumerical algorithms Third Edition, Addison-Wesley, 1997. """ mmax=n*(n-1)/2 if m>=mmax: G=complete_graph(n,create_using) else: if create_using is not None and create_using.is_directed(): raise nx.NetworkXError("Directed Graph not supported") G=empty_graph(n,create_using) G.name="dense_gnm_random_graph(%s,%s)"%(n,m) if n==1 or m>=mmax: return G if seed is not None: random.seed(seed) u=0 v=1 t=0 k=0 while True: if random.randrange(mmax-t)<m-k: G.add_edge(u,v) k+=1 if k==m: return G t+=1 v+=1 if v==n: # go to next row of adjacency matrix u+=1 v=u+1
def tetrahedral_graph(create_using=None): """ Return the 3-regular Platonic Tetrahedral graph.""" G = complete_graph(4, create_using) G.name = "Platonic Tetrahedral graph" return G
def dense_gnm_random_graph(n, m, create_using=None, seed=None): """Return the random graph G_{n,m}. Gives a graph picked randomly out of the set of all graphs with n nodes and m edges. This algorithm should be faster than gnm_random_graph for dense graphs. Parameters ---------- n : int The number of nodes. m : int The number of edges. create_using : graph, optional (default Graph) Use specified graph as a container. seed : int, optional Seed for random number generator (default=None). See Also -------- gnm_random_graph() Notes ----- Algorithm by Keith M. Briggs Mar 31, 2006. Inspired by Knuth's Algorithm S (Selection sampling technique), in section 3.4.2 of References ---------- .. [1] Donald E. Knuth, The Art of Computer Programming, Volume 2 / Seminumerical algorithms Third Edition, Addison-Wesley, 1997. """ mmax = n * (n - 1) / 2 if m >= mmax: G = complete_graph(n, create_using) else: if create_using is not None and create_using.is_directed(): raise nx.NetworkXError("Directed Graph not supported") G = empty_graph(n, create_using) G.name = "dense_gnm_random_graph(%s,%s)" % (n, m) if n == 1 or m >= mmax: return G if seed is not None: random.seed(seed) u = 0 v = 1 t = 0 k = 0 while True: if random.randrange(mmax - t) < m - k: G.add_edge(u, v) k += 1 if k == m: return G t += 1 v += 1 if v == n: # go to next row of adjacency matrix u += 1 v = u + 1
while count_frequencies(graph)[0] not in [0.0, 1.0]: chosen = np.random.randint(0, graph_size) fn_C = death_birth_fitness(graph, chosen, b)[0] graph.nodes[chosen]['name'] = 'C' if np.random.random() < fn_C else 'D' return count_frequencies(graph)[0] if __name__ == '__main__': benefit = 10 with Pool(num_workers) as pool: results = [] for i in tqdm(range(num_refreshes), leave=False, desc='Total'): for j in tqdm(range(network_refresh_interval // num_workers), desc='Batch', leave=False): # Generate a fresh graph with a random cooperator invader = np.random.randint(graph_size) graphs = [ complete_graph(graph_size) for _ in range(num_workers) ] # Initializing graph nodes for G in graphs: for node in G: G.nodes[node]['name'] = 'C' if node == invader else 'D' set_result = pool.map(partial(evolve, b=benefit), graphs) results += set_result # print('{} --> {}'.format(i*network_refresh_interval+j*num_workers,set_result)) print("\nFixation probability of C: {}".format( sum(results) / num_trials))
graph.nodes[chosen]['name'] = 'C' if np.random.random() < fn_C else 'D' return count_frequencies(graph)[0] # plt.show() # hist.append(count_frequencies(graph)[0]) # plt.plot(hist) # plt.show() if __name__ == '__main__': num_trials = 100 graph_size = 100 num_workers = cpu_count() pool = ProcessPool() results = [] invader = np.random.randint(graph_size) graphs = [complete_graph(graph_size) for _ in range(num_trials)] print('Generated graphs') # Initializing graph nodes for G in graphs: for node in G: G.nodes[node]['name'] = 'C' if node == invader else 'D' print('Initialised graphs') future = pool.map(evolve, graphs, timeout=100) iterator = future.result() set_result = [] # with tqdm(total=num_trials,desc='Finished',leave=False) as pbar: while True: try: result = next(iterator) print(result)