def from_pandas_edgelist(df, source="source", target="target", edge_attr=None, create_using=None): g = nx.empty_graph(0, create_using) if edge_attr is None: g.add_edges_from(zip(df[source], df[target])) return g # Additional columns requested if edge_attr is True: cols = [c for c in df.columns if c is not source and c is not target] elif isinstance(edge_attr, (list, tuple)): cols = edge_attr else: cols = [edge_attr] if len(cols) == 0: msg = f"Invalid edge_attr argument. No columns found with name: {cols}" raise nx.NetworkXError(msg) try: eattrs = zip(*[df[col] for col in cols]) except (KeyError, TypeError) as e: msg = f"Invalid edge_attr argument: {edge_attr}" raise nx.NetworkXError(msg) from e edges = [] for s, t, attrs in zip(df[source], df[target], eattrs): edges.append((s, t, zip(cols, attrs))) g.add_edges_from(edges) return g
def barabasi_albert_graph(n, m, seed=None): """Returns a random graph according to the Barabási–Albert preferential attachment model. A graph of $n$ nodes is grown by attaching new nodes each with $m$ edges that are preferentially attached to existing nodes with high degree. Parameters ---------- n : int Number of nodes m : int Number of edges to attach from a new node to existing nodes seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- G : Graph Raises ------ NetworkXError If `m` does not satisfy ``1 <= m < n``. References ---------- .. [1] A. L. Barabási and R. Albert "Emergence of scaling in random networks", Science 286, pp 509-512, 1999. """ if m < 1 or m >= n: raise nx.NetworkXError("Barabási–Albert network must have m >= 1" " and m < n, m = %d, n = %d" % (m, n)) # Add m initial nodes (m0 in barabasi-speak) G = empty_graph(m) # Target nodes for new edges targets = list(range(m)) # List of existing nodes, with nodes repeated once for each adjacent edge repeated_nodes = [] # Start adding the other n-m nodes. The first node is m. source = m while source < n: # Add edges to m nodes from the source. G.add_edges_from(zip([source] * m, 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] * m) # 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 G
def random_powerlaw_tree_sequence(n, gamma=3, seed=None, tries=100): """Returns a degree sequence for a tree with a power law distribution. Parameters ---------- n : int, The number of nodes. gamma : float Exponent of the power law. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. tries : int Number of attempts to adjust the sequence to make it a tree. Raises ------ NetworkXError If no valid sequence is found within the maximum number of attempts. Notes ----- A trial power law degree sequence is chosen and then elements are swapped with new elements from a power law distribution until the sequence makes a tree (by checking, for example, that the number of edges is one smaller than the number of nodes). """ # get trial sequence z = powerlaw_sequence(n, exponent=gamma, seed=seed) # round to integer values in the range [0,n] zseq = [min(n, max(int(round(s)), 0)) for s in z] # another sequence to swap values from z = powerlaw_sequence(tries, exponent=gamma, seed=seed) # round to integer values in the range [0,n] swap = [min(n, max(int(round(s)), 0)) for s in z] for deg in swap: # If this degree sequence can be the degree sequence of a tree, return # it. It can be a tree if the number of edges is one fewer than the # number of nodes, or in other words, `n - sum(zseq) / 2 == 1`. We # use an equivalent condition below that avoids floating point # operations. if 2 * n - sum(zseq) == 2: return zseq index = seed.randint(0, n - 1) zseq[index] = swap.pop() raise nx.NetworkXError("Exceeded max (%d) attempts for a valid tree" " sequence." % tries)
def gnr_graph(n, p, create_using=None, seed=None): """Returns the growing network with redirection (GNR) digraph with `n` nodes and redirection probability `p`. The GNR graph is built by adding nodes one at a time with a link to one previously added node. The previous target node is chosen uniformly at random. With probabiliy `p` the link is instead "redirected" to the successor node of the target. The graph is always a (directed) tree. Parameters ---------- n : int The number of nodes for the generated graph. p : float The redirection probability. create_using : NetworkX graph constructor, optional (default DiGraph) Graph type to create. If graph instance, then cleared before populated. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Examples -------- To create the undirected GNR graph, use the :meth:`~DiGraph.to_directed` method:: >>> D = nx.gnr_graph(10, 0.5) # the GNR graph >>> G = D.to_undirected() # the undirected version References ---------- .. [1] P. L. Krapivsky and S. Redner, Organization of Growing Random Networks, Phys. Rev. E, 63, 066123, 2001. """ G = empty_graph(1, create_using, default=nx.DiGraph) if not G.is_directed(): raise nx.NetworkXError("create_using must indicate a Directed Graph") if n == 1: return G for source in range(1, n): target = seed.randrange(0, source) if seed.random() < p and target != 0: target = next(G.successors(target)) G.add_edge(source, target) return G
def connected_watts_strogatz_graph(n, k, p, tries=100, seed=None): """Returns a connected Watts–Strogatz small-world graph. Attempts to generate a connected graph by repeated generation of Watts–Strogatz small-world graphs. An exception is raised if the maximum number of tries is exceeded. Parameters ---------- n : int The number of nodes k : int Each node is joined with its `k` nearest neighbors in a ring topology. p : float The probability of rewiring each edge tries : int Number of attempts to generate a connected graph. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Notes ----- First create a ring over $n$ nodes [1]_. Then each node in the ring is joined to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd). Then shortcuts are created by replacing some edges as follows: for each edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors" with probability $p$ replace it with a new edge $(u, w)$ with uniformly random choice of existing node $w$. The entire process is repeated until a connected graph results. See Also -------- newman_watts_strogatz_graph() watts_strogatz_graph() References ---------- .. [1] Duncan J. Watts and Steven H. Strogatz, Collective dynamics of small-world networks, Nature, 393, pp. 440--442, 1998. """ for i in range(tries): # seed is an RNG so should change sequence each call G = watts_strogatz_graph(n, k, p, seed) if nx.is_connected(G): return G raise nx.NetworkXError("Maximum number of tries exceeded")
def gnc_graph(n, create_using=None, seed=None): """Returns the growing network with copying (GNC) digraph with `n` nodes. The GNC graph is built by adding nodes one at a time with a link to one previously added node (chosen uniformly at random) and to all of that node's successors. Parameters ---------- n : int The number of nodes for the generated graph. create_using : NetworkX graph constructor, optional (default DiGraph) Graph type to create. If graph instance, then cleared before populated. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. References ---------- .. [1] P. L. Krapivsky and S. Redner, Network Growth by Copying, Phys. Rev. E, 71, 036118, 2005k.}, """ G = empty_graph(1, create_using, default=nx.DiGraph) if not G.is_directed(): raise nx.NetworkXError("create_using must indicate a Directed Graph") if n == 1: return G for source in range(1, n): target = seed.randrange(0, source) for succ in G.successors(target): G.add_edge(source, succ) G.add_edge(source, target) return G
def to_nx_graph(data, create_using=None, multigraph_input=False): # noqa: C901 """Make a graph from a known data structure. The preferred way to call this is automatically from the class constructor >>> d = {0: {1: {'weight':1}}} # dict-of-dicts single edge (0,1) >>> G = nx.Graph(d) instead of the equivalent >>> G = nx.from_dict_of_dicts(d) Parameters ---------- data : object to be converted Current known types are: any NetworkX graph dict-of-dicts dict-of-lists container (ie set, list, tuple, iterator) of edges Pandas DataFrame (row per edge) numpy matrix numpy ndarray scipy sparse matrix create_using : nx graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. multigraph_input : bool (default False) If True and data is a dict_of_dicts, try to create a multigraph assuming dict_of_dict_of_lists. If data and create_using are both multigraphs then create a multigraph from a multigraph. """ # networkx graph or graphscope.nx graph if hasattr(data, "adj"): try: result = from_dict_of_dicts( data.adj, create_using=create_using, multigraph_input=data.is_multigraph(), ) if hasattr(data, "graph"): # data.graph should be dict-like result.graph.update(data.graph) if hasattr(data, "nodes"): # data.nodes should be dict-like result.add_nodes_from(data.nodes.items()) return result except Exception as e: raise nx.NetworkXError( "Input is not a correct NetworkX-like graph.") from e # dict of dicts/lists if isinstance(data, dict): try: return from_dict_of_dicts(data, create_using=create_using, multigraph_input=multigraph_input) except Exception: try: return from_dict_of_lists(data, create_using=create_using) except Exception as e: raise TypeError("Input is not known type.") from e # list or generator of edges if isinstance(data, (list, tuple)) or any( hasattr(data, attr) for attr in ["_adjdict", "next", "__next__"]): try: return from_edgelist(data, create_using=create_using) except Exception as e: raise nx.NetworkXError("Input is not a valid edge list") from e # Pandas DataFrame try: import pandas as pd if isinstance(data, pd.DataFrame): if data.shape[0] == data.shape[1]: try: return nx.from_pandas_adjacency(data, create_using=create_using) except Exception as e: msg = "Input is not a correct Pandas DataFrame adjacency matrix." raise nx.NetworkXError(msg) from e else: try: return nx.from_pandas_edgelist(data, edge_attr=True, create_using=create_using) except Exception as e: msg = "Input is not a correct Pandas DataFrame edge-list." raise nx.NetworkXError(msg) from e except ImportError: msg = "pandas not found, skipping conversion test." warnings.warn(msg, ImportWarning) # numpy matrix or ndarray try: import numpy if isinstance(data, (numpy.matrix, numpy.ndarray)): try: return nx.from_numpy_matrix(data, create_using=create_using) except Exception as e: raise nx.NetworkXError( "Input is not a correct numpy matrix or array.") from e except ImportError: warnings.warn("numpy not found, skipping conversion test.", ImportWarning) # scipy sparse matrix - any format try: import scipy if hasattr(data, "format"): try: return nx.from_scipy_sparse_matrix(data, create_using=create_using) except Exception as e: raise nx.NetworkXError( "Input is not a correct scipy sparse matrix type.") from e except ImportError: warnings.warn("scipy not found, skipping conversion test.", ImportWarning) raise nx.NetworkXError("Input is not a known data type for conversion.")
def gn_graph(n, kernel=None, create_using=None, seed=None): """Returns the growing network (GN) digraph with `n` nodes. The GN graph is built by adding nodes one at a time with a link to one previously added node. The target node for the link is chosen with probability based on degree. The default attachment kernel is a linear function of the degree of a node. The graph is always a (directed) tree. Parameters ---------- n : int The number of nodes for the generated graph. kernel : function The attachment kernel. create_using : NetworkX graph constructor, optional (default DiGraph) Graph type to create. If graph instance, then cleared before populated. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Examples -------- To create the undirected GN graph, use the :meth:`~DiGraph.to_directed` method:: >>> D = nx.gn_graph(10) # the GN graph >>> G = D.to_undirected() # the undirected version To specify an attachment kernel, use the `kernel` keyword argument:: >>> D = nx.gn_graph(10, kernel=lambda x: x ** 1.5) # A_k = k^1.5 References ---------- .. [1] P. L. Krapivsky and S. Redner, Organization of Growing Random Networks, Phys. Rev. E, 63, 066123, 2001. """ G = empty_graph(1, create_using, default=nx.DiGraph) if not G.is_directed(): raise nx.NetworkXError("create_using must indicate a Directed Graph") if kernel is None: def kernel(x): return x if n == 1: return G G.add_edge(1, 0) # get started ds = [1, 1] # degree sequence for source in range(2, n): # compute distribution from kernel and degree dist = [kernel(d) for d in ds] # choose target from discrete distribution target = discrete_sequence(1, distribution=dist, seed=seed)[0] G.add_edge(source, target) ds.append(1) # the source has only one link (degree one) ds[target] += 1 # add one to the target link degree return G
def scale_free_graph( n, alpha=0.41, beta=0.54, gamma=0.05, delta_in=0.2, delta_out=0, create_using=None, seed=None, ): """Returns a scale-free directed graph. Parameters ---------- n : integer Number of nodes in graph alpha : float Probability for adding a new node connected to an existing node chosen randomly according to the in-degree distribution. beta : float Probability for adding an edge between two existing nodes. One existing node is chosen randomly according the in-degree distribution and the other chosen randomly according to the out-degree distribution. gamma : float Probability for adding a new node connected to an existing node chosen randomly according to the out-degree distribution. delta_in : float Bias for choosing nodes from in-degree distribution. delta_out : float Bias for choosing nodes from out-degree distribution. create_using : NetworkX graph constructor, optional The default is a MultiDiGraph 3-cycle. If a graph instance, use it without clearing first. If a graph constructor, call it to construct an empty graph. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Examples -------- Create a scale-free graph on one hundred nodes:: >>> G = nx.scale_free_graph(100) Notes ----- The sum of `alpha`, `beta`, and `gamma` must be 1. References ---------- .. [1] B. Bollobás, C. Borgs, J. Chayes, and O. Riordan, Directed scale-free graphs, Proceedings of the fourteenth annual ACM-SIAM Symposium on Discrete Algorithms, 132--139, 2003. """ def _choose_node(G, distribution, delta, psum): cumsum = 0.0 # normalization r = seed.random() for n, d in distribution: cumsum += (d + delta) / psum if r < cumsum: break return n if create_using is None or not hasattr(create_using, "_adj"): # start with 3-cycle G = nx.empty_graph(3, create_using, default=nx.MultiDiGraph) G.add_edges_from([(0, 1), (1, 2), (2, 0)]) else: G = create_using if not (G.is_directed() and G.is_multigraph()): raise nx.NetworkXError("MultiDiGraph required in create_using") if alpha <= 0: raise ValueError("alpha must be > 0.") if beta <= 0: raise ValueError("beta must be > 0.") if gamma <= 0: raise ValueError("gamma must be > 0.") if abs(alpha + beta + gamma - 1.0) >= 1e-9: raise ValueError("alpha+beta+gamma must equal 1.") number_of_edges = G.number_of_edges() while len(G) < n: psum_in = number_of_edges + delta_in * len(G) psum_out = number_of_edges + delta_out * len(G) r = seed.random() # random choice in alpha,beta,gamma ranges if r < alpha: # alpha # add new node v v = len(G) # choose w according to in-degree and delta_in w = _choose_node(G, G.in_degree(), delta_in, psum_in) elif r < alpha + beta: # beta # choose v according to out-degree and delta_out v = _choose_node(G, G.out_degree(), delta_out, psum_out) # choose w according to in-degree and delta_in w = _choose_node(G, G.in_degree(), delta_in, psum_in) else: # gamma # choose v according to out-degree and delta_out v = _choose_node(G, G.out_degree(), delta_out, psum_out) # add new node w w = len(G) G.add_edge(v, w) number_of_edges += 1 return G
def powerlaw_cluster_graph(n, m, p, seed=None): """Holme and Kim algorithm for growing graphs with powerlaw degree distribution and approximate average clustering. Parameters ---------- n : int the number of nodes m : int the number of random edges to add for each new node p : float, Probability of adding a triangle after adding a random edge seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Notes ----- The average clustering has a hard time getting above a certain cutoff that depends on `m`. This cutoff is often quite low. The transitivity (fraction of triangles to possible triangles) seems to decrease with network size. It is essentially the Barabási–Albert (BA) growth model with an extra step that each random edge is followed by a chance of making an edge to one of its neighbors too (and thus a triangle). This algorithm improves on BA in the sense that it enables a higher average clustering to be attained if desired. It seems possible to have a disconnected graph with this algorithm since the initial `m` nodes may not be all linked to a new node on the first iteration like the BA model. Raises ------ NetworkXError If `m` does not satisfy ``1 <= m <= n`` or `p` does not satisfy ``0 <= p <= 1``. References ---------- .. [1] P. Holme and B. J. Kim, "Growing scale-free networks with tunable clustering", Phys. Rev. E, 65, 026107, 2002. """ if m < 1 or n < m: raise nx.NetworkXError( "NetworkXError must have m>1 and m<n, m=%d,n=%d" % (m, n)) if p > 1 or p < 0: raise nx.NetworkXError("NetworkXError p must be in [0,1], p=%f" % (p)) G = empty_graph(m) # add m initial nodes (m0 in barabasi-speak) repeated_nodes = list(G.nodes()) # list of existing nodes to sample from # with nodes repeated once for each adjacent edge source = m # next node is m while source < n: # Now add the other n-1 nodes possible_targets = _random_subset(repeated_nodes, m, seed) # do one preferential attachment for new node target = possible_targets.pop() G.add_edge(source, target) repeated_nodes.append(target) # add one node to list for each new link count = 1 while count < m: # add m-1 more new links if seed.random() < p: # clustering step: add triangle neighborhood = [ nbr for nbr in G.neighbors(target) if not G.has_edge(source, nbr) and not nbr == source ] if neighborhood: # if there is a neighbor without a link nbr = seed.choice(neighborhood) G.add_edge(source, nbr) # add triangle repeated_nodes.append(nbr) count = count + 1 continue # go to top of while loop # else do preferential attachment step if above fails target = possible_targets.pop() G.add_edge(source, target) repeated_nodes.append(target) count = count + 1 repeated_nodes.extend([source] * m) # add source node to list m times source += 1 return G
def extended_barabasi_albert_graph(n, m, p, q, seed=None): """Returns an extended Barabási–Albert model graph. An extended Barabási–Albert model graph is a random graph constructed using preferential attachment. The extended model allows new edges, rewired edges or new nodes. Based on the probabilities $p$ and $q$ with $p + q < 1$, the growing behavior of the graph is determined as: 1) With $p$ probability, $m$ new edges are added to the graph, starting from randomly chosen existing nodes and attached preferentially at the other end. 2) With $q$ probability, $m$ existing edges are rewired by randomly choosing an edge and rewiring one end to a preferentially chosen node. 3) With $(1 - p - q)$ probability, $m$ new nodes are added to the graph with edges attached preferentially. When $p = q = 0$, the model behaves just like the Barabási–Alber mo Parameters ---------- n : int Number of nodes m : int Number of edges with which a new node attaches to existing nodes p : float Probability value for adding an edge between existing nodes. p + q < 1 q : float Probability value of rewiring of existing edges. p + q < 1 seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- G : Graph Raises ------ NetworkXError If `m` does not satisfy ``1 <= m < n`` or ``1 >= p + q`` References ---------- .. [1] Albert, R., & Barabási, A. L. (2000) Topology of evolving networks: local events and universality Physical review letters, 85(24), 5234. """ if m < 1 or m >= n: msg = "Extended Barabasi-Albert network needs m>=1 and m<n, m=%d, n=%d" raise nx.NetworkXError(msg % (m, n)) if p + q >= 1: msg = "Extended Barabasi-Albert network needs p + q <= 1, p=%d, q=%d" raise nx.NetworkXError(msg % (p, q)) # Add m initial nodes (m0 in barabasi-speak) G = empty_graph(m) # List of nodes to represent the preferential attachment random selection. # At the creation of the graph, all nodes are added to the list # so that even nodes that are not connected have a chance to get selected, # for rewiring and adding of edges. # With each new edge, nodes at the ends of the edge are added to the list. attachment_preference = [] attachment_preference.extend(range(m)) # Start adding the other n-m nodes. The first node is m. new_node = m while new_node < n: a_probability = seed.random() # Total number of edges of a Clique of all the nodes clique_degree = len(G) - 1 clique_size = (len(G) * clique_degree) / 2 # Adding m new edges, if there is room to add them if a_probability < p and G.size() <= clique_size - m: # Select the nodes where an edge can be added elligible_nodes = [ nd for nd, deg in G.degree() if deg < clique_degree ] for i in range(m): # Choosing a random source node from elligible_nodes src_node = seed.choice(elligible_nodes) # Picking a possible node that is not 'src_node' or # neighbor with 'src_node', with preferential attachment prohibited_nodes = list(G[src_node]) prohibited_nodes.append(src_node) # This will raise an exception if the sequence is empty dest_node = seed.choice([ nd for nd in attachment_preference if nd not in prohibited_nodes ]) # Adding the new edge G.add_edge(src_node, dest_node) # Appending both nodes to add to their preferential attachment attachment_preference.append(src_node) attachment_preference.append(dest_node) # Adjusting the elligible nodes. Degree may be saturated. if G.degree(src_node) == clique_degree: elligible_nodes.remove(src_node) if (G.degree(dest_node) == clique_degree and dest_node in elligible_nodes): elligible_nodes.remove(dest_node) # Rewiring m edges, if there are enough edges elif p <= a_probability < (p + q) and m <= G.size() < clique_size: # Selecting nodes that have at least 1 edge but that are not # fully connected to ALL other nodes (center of star). # These nodes are the pivot nodes of the edges to rewire elligible_nodes = [ nd for nd, deg in G.degree() if 0 < deg < clique_degree ] for i in range(m): # Choosing a random source node node = seed.choice(elligible_nodes) # The available nodes do have a neighbor at least. neighbor_nodes = list(G[node]) # Choosing the other end that will get dettached src_node = seed.choice(neighbor_nodes) # Picking a target node that is not 'node' or # neighbor with 'node', with preferential attachment neighbor_nodes.append(node) dest_node = seed.choice([ nd for nd in attachment_preference if nd not in neighbor_nodes ]) # Rewire G.remove_edge(node, src_node) G.add_edge(node, dest_node) # Adjusting the preferential attachment list attachment_preference.remove(src_node) attachment_preference.append(dest_node) # Adjusting the elligible nodes. # nodes may be saturated or isolated. if G.degree(src_node) == 0 and src_node in elligible_nodes: elligible_nodes.remove(src_node) if dest_node in elligible_nodes: if G.degree(dest_node) == clique_degree: elligible_nodes.remove(dest_node) else: if G.degree(dest_node) == 1: elligible_nodes.append(dest_node) # Adding new node with m edges else: # Select the edges' nodes by preferential attachment targets = _random_subset(attachment_preference, m, seed) G.add_edges_from(zip([new_node] * m, targets)) # Add one node to the list for each new edge just created. attachment_preference.extend(targets) # The new node has m edges to it, plus itself: m + 1 attachment_preference.extend([new_node] * (m + 1)) new_node += 1 return G
def dual_barabasi_albert_graph(n, m1, m2, p, seed=None): """Returns a random graph according to the dual Barabási–Albert preferential attachment model. A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$ edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that are preferentially attached to existing nodes with high degree. Parameters ---------- n : int Number of nodes m1 : int Number of edges to attach from a new node to existing nodes with probability $p$ m2 : int Number of edges to attach from a new node to existing nodes with probability $1-p$ p : float The probability of attaching $m_1$ edges (as opposed to $m_2$ edges) seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- G : Graph Raises ------ NetworkXError If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n`` or `p` does not satisfy ``0 <= p <= 1``. References ---------- .. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538. """ if m1 < 1 or m1 >= n: raise nx.NetworkXError("Dual Barabási–Albert network must have m1 >= 1" " and m1 < n, m1 = %d, n = %d" % (m1, n)) if m2 < 1 or m2 >= n: raise nx.NetworkXError("Dual Barabási–Albert network must have m2 >= 1" " and m2 < n, m2 = %d, n = %d" % (m2, n)) if p < 0 or p > 1: raise nx.NetworkXError( "Dual Barabási–Albert network must have 0 <= p <= 1," "p = %f" % p) # For simplicity, if p == 0 or 1, just return BA if p == 1: return barabasi_albert_graph(n, m1, seed) elif p == 0: return barabasi_albert_graph(n, m2, seed) # Add max(m1,m2) initial nodes (m0 in barabasi-speak) G = empty_graph(max(m1, m2)) # Target nodes for new edges targets = list(range(max(m1, m2))) # List of existing nodes, with nodes repeated once for each adjacent edge repeated_nodes = [] # Start adding the remaining nodes. source = max(m1, m2) # Pick which m to use first time (m1 or m2) if seed.random() < p: m = m1 else: m = m2 while source < n: # Add edges to m nodes from the source. G.add_edges_from(zip([source] * m, 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] * m) # Pick which m to use next time (m1 or m2) if seed.random() < p: m = m1 else: m = m2 # 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 G
def random_regular_graph(d, n, seed=None): r"""Returns a random $d$-regular graph on $n$ nodes. The resulting graph has no self-loops or parallel edges. Parameters ---------- d : int The degree of each node. n : integer The number of nodes. The value of $n \times d$ must be even. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Notes ----- The nodes are numbered from $0$ to $n - 1$. Kim and Vu's paper [2]_ shows that this algorithm samples in an asymptotically uniform way from the space of random graphs when $d = O(n^{1 / 3 - \epsilon})$. Raises ------ NetworkXError If $n \times d$ is odd or $d$ is greater than or equal to $n$. References ---------- .. [1] A. Steger and N. Wormald, Generating random regular graphs quickly, Probability and Computing 8 (1999), 377-396, 1999. http://citeseer.ist.psu.edu/steger99generating.html .. [2] Jeong Han Kim and Van H. Vu, Generating random regular graphs, Proceedings of the thirty-fifth ACM symposium on Theory of computing, San Diego, CA, USA, pp 213--222, 2003. http://portal.acm.org/citation.cfm?id=780542.780576 """ if (n * d) % 2 != 0: raise nx.NetworkXError("n * d must be even") if not 0 <= d < n: raise nx.NetworkXError("the 0 <= d < n inequality must be satisfied") if d == 0: return empty_graph(n) def _suitable(edges, potential_edges): # Helper subroutine to check if there are suitable edges remaining # If False, the generation of the graph has failed if not potential_edges: return True for s1 in potential_edges: for s2 in potential_edges: # Two iterators on the same dictionary are guaranteed # to visit it in the same order if there are no # intervening modifications. if s1 == s2: # Only need to consider s1-s2 pair one time break if s1 > s2: s1, s2 = s2, s1 if (s1, s2) not in edges: return True return False def _try_creation(): # Attempt to create an edge set edges = set() stubs = list(range(n)) * d while stubs: potential_edges = defaultdict(lambda: 0) seed.shuffle(stubs) stubiter = iter(stubs) for s1, s2 in zip(stubiter, stubiter): if s1 > s2: s1, s2 = s2, s1 if s1 != s2 and ((s1, s2) not in edges): edges.add((s1, s2)) else: potential_edges[s1] += 1 potential_edges[s2] += 1 if not _suitable(edges, potential_edges): return None # failed to find suitable edge set stubs = [ node for node, potential in potential_edges.items() for _ in range(potential) ] return edges # Even though a suitable edge set exists, # the generation of such a set is not guaranteed. # Try repeatedly to find one. edges = _try_creation() while edges is None: edges = _try_creation() G = nx.Graph() G.add_edges_from(edges) return G
def watts_strogatz_graph(n, k, p, seed=None): """Returns a Watts–Strogatz small-world graph. Parameters ---------- n : int The number of nodes k : int Each node is joined with its `k` nearest neighbors in a ring topology. p : float The probability of rewiring each edge seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. See Also -------- newman_watts_strogatz_graph() connected_watts_strogatz_graph() Notes ----- First create a ring over $n$ nodes [1]_. Then each node in the ring is joined to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd). Then shortcuts are created by replacing some edges as follows: for each edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors" with probability $p$ replace it with a new edge $(u, w)$ with uniformly random choice of existing node $w$. In contrast with :func:`newman_watts_strogatz_graph`, the random rewiring does not increase the number of edges. The rewired graph is not guaranteed to be connected as in :func:`connected_watts_strogatz_graph`. References ---------- .. [1] Duncan J. Watts and Steven H. Strogatz, Collective dynamics of small-world networks, Nature, 393, pp. 440--442, 1998. """ if k > n: raise nx.NetworkXError("k>n, choose smaller k or larger n") # If k == n, the graph is complete not Watts-Strogatz if k == n: return nx.complete_graph(n) G = nx.Graph() nodes = list(range(n)) # nodes are labeled 0 to n-1 # connect each node to k/2 neighbors for j in range(1, k // 2 + 1): targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list G.add_edges_from(zip(nodes, targets)) # rewire edges from each node # loop over all nodes in order (label) and neighbors in order (distance) # no self loops or multiple edges allowed for j in range(1, k // 2 + 1): # outer loop is neighbors targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list # inner loop in node order for u, v in zip(nodes, targets): if seed.random() < p: w = seed.choice(nodes) # Enforce no self-loops or multiple edges while w == u or G.has_edge(u, w): w = seed.choice(nodes) if G.degree(u) >= n - 1: break # skip this rewiring else: G.remove_edge(u, v) G.add_edge(u, w) return G
def newman_watts_strogatz_graph(n, k, p, seed=None): """Returns a Newman–Watts–Strogatz small-world graph. Parameters ---------- n : int The number of nodes. k : int Each node is joined with its `k` nearest neighbors in a ring topology. p : float The probability of adding a new edge for each edge. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Notes ----- First create a ring over $n$ nodes [1]_. Then each node in the ring is connected with its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd). Then shortcuts are created by adding new edges as follows: for each edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors" with probability $p$ add a new edge $(u, w)$ with randomly-chosen existing node $w$. In contrast with :func:`watts_strogatz_graph`, no edges are removed. See Also -------- watts_strogatz_graph() References ---------- .. [1] M. E. J. Newman and D. J. Watts, Renormalization group analysis of the small-world network model, Physics Letters A, 263, 341, 1999. https://doi.org/10.1016/S0375-9601(99)00757-4 """ if k > n: raise nx.NetworkXError("k>=n, choose smaller k or larger n") # If k == n the graph return is a complete graph if k == n: return nx.complete_graph(n) G = empty_graph(n) nlist = list(G.nodes()) fromv = nlist # connect the k/2 neighbors for j in range(1, k // 2 + 1): tov = fromv[j:] + fromv[0:j] # the first j are now last for i in range(len(fromv)): G.add_edge(fromv[i], tov[i]) # for each edge u-v, with probability p, randomly select existing # node w and add new edge u-w e = list(G.edges()) for (u, v) in e: if seed.random() < p: w = seed.choice(nlist) # no self-loops and reject if edge u-w exists # is that the correct NWS model? while w == u or G.has_edge(u, w): w = seed.choice(nlist) if G.degree(u) >= n - 1: break # skip this rewiring else: G.add_edge(u, w) return G