【笔记】

用__all__定义全局变量,即所有可以生成的图

itertools.permutations(range(n), 2):返回n个数中任意取2个元素做排列的元组的迭代器

itertools.combinations(range(n), 2):返回n个数中任意取2个元素做组合的元组的迭代器

itertools.chain(arr1, arr2):将两个数组arr1和arr2链接在一起,返回迭代器,迭代器可被list()与set()转化

=============================================

下面是python-networkx中,生成图的文件random_graphs的源码(加注释):

# -*- coding: utf-8 -*-
#    Copyright (C) 2004-2017 by
#    Aric Hagberg <hagberg@lanl.gov>
#    Dan Schult <dschult@colgate.edu>
#    Pieter Swart <swart@lanl.gov>
#    All rights reserved.
#    BSD license.
"""
Generators for random graphs."""from __future__ import division
import itertools
import math
import randomimport networkx as nx
from .classic import empty_graph, path_graph, complete_graph
from .degree_seq import degree_sequence_tree
from collections import defaultdict__all__ = ['fast_gnp_random_graph','gnp_random_graph','dense_gnm_random_graph','gnm_random_graph','erdos_renyi_graph','binomial_graph','newman_watts_strogatz_graph','watts_strogatz_graph','connected_watts_strogatz_graph','random_regular_graph','barabasi_albert_graph','extended_barabasi_albert_graph','powerlaw_cluster_graph','random_lobster','random_shell_graph','random_powerlaw_tree','random_powerlaw_tree_sequence','random_kernel_graph']#-------------------------------------------------------------------------
#  Some Famous Random Graphs
#-------------------------------------------------------------------------def fast_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 ora binomial graph.Parameters----------n : intThe number of nodes.p : floatProbability for edge creation.seed : int, optionalSeed for random number generator (default=None).directed : bool, optional (default=False)If True, this function returns a directed graph.Notes-----The $G_{n,p}$ graph algorithm chooses each of the $[n (n - 1)] / 2$(undirected) or $n (n - 1)$ (directed) possible edges with probability $p$.This algorithm [1]_ runs in $O(n + m)$ time, where `m` is the expected number ofedges, which equals $p n (n - 1) / 2$. This should be faster than:func:`gnp_random_graph` when $p$ is small and the expected number of edgesis small (that is, the graph is sparse).See Also--------gnp_random_graphReferences----------.. [1] Vladimir Batagelj and Ulrik Brandes,"Efficient generation of large random networks",Phys. Rev. E, 71, 036113, 2005."""G = empty_graph(n)if seed is not None:random.seed(seed)if p <= 0 or p >= 1:return nx.gnp_random_graph(n, p, directed=directed)w = -1lp = math.log(1.0 - p)if directed:G = nx.DiGraph(G)# Nodes in graph are from 0,n-1 (start with v as the first node index).v = 0while v < n:lr = math.log(1.0 - random.random())w = w + 1 + int(lr / lp)if v == w:  # avoid self loopsw = w + 1while v < n <= w:w = w - nv = v + 1if v == w:  # avoid self loopsw = w + 1if v < n:G.add_edge(v, w)else:# Nodes in graph are from 0,n-1 (start with v as the second node index).v = 1while v < n:lr = math.log(1.0 - random.random())w = w + 1 + int(lr / lp)while w >= v and v < n:w = w - vv = v + 1if v < n:G.add_edge(v, w)return Gdef gnp_random_graph(n, p, seed=None, directed=False):"""Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graphor 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` arealiases of this function.Parameters----------n : intThe number of nodes.p : floatProbability for edge creation.seed : int, optionalSeed for random number generator (default=None).directed : bool, optional (default=False)If True, this function returns a directed graph.See Also--------fast_gnp_random_graphNotes-----This algorithm [2]_ runs in $O(n^2)$ time.  For sparse graphs (that is, forsmall 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))if p <= 0:return Gif p >= 1:return complete_graph(n, create_using=G)if seed is not 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# add some aliases to common names
binomial_graph = gnp_random_graph
erdos_renyi_graph = gnp_random_graphdef 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 setof all graphs with $n$ nodes and $m$ edges.This algorithm should be faster than :func:`gnm_random_graph` for densegraphs.Parameters----------n : intThe number of nodes.m : intThe number of edges.seed : int, optionalSeed 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) / 2if m >= mmax:G = complete_graph(n)else:G = empty_graph(n)if n == 1 or m >= mmax:return Gif seed is not None:random.seed(seed)u = 0v = 1t = 0k = 0while True:if random.randrange(mmax - t) < m - k:G.add_edge(u, v)k += 1if k == m:return Gt += 1v += 1if v == n:  # go to next row of adjacency matrixu += 1v = u + 1def 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 setof all graphs with $n$ nodes and $m$ edges.This algorithm should be faster than :func:`dense_gnm_random_graph` forsparse graphs.Parameters----------n : intThe number of nodes.m : intThe number of edges.seed : int, optionalSeed for random number generator (default=None).directed : bool, optional (default=False)If True return a directed graphSee also--------dense_gnm_random_graph"""if directed:G = nx.DiGraph()else:G = nx.Graph()G.add_nodes_from(range(n))if seed is not None:random.seed(seed)if n == 1:return Gmax_edges = n * (n - 1)if not directed:max_edges /= 2.0if m >= max_edges:return complete_graph(n, create_using=G)nlist = list(G)edge_count = 0while edge_count < m:# generate random edge,u,vu = random.choice(nlist)v = random.choice(nlist)if u == v or G.has_edge(u, v):continueelse:G.add_edge(u, v)edge_count = edge_count + 1return Gdef newman_watts_strogatz_graph(n, k, p, seed=None):"""Return a Newman–Watts–Strogatz small-world graph.Parameters----------n : intThe number of nodes.k : intEach node is joined with its `k` nearest neighbors in a ringtopology.p : floatThe probability of adding a new edge for each edge.seed : int, optionalThe seed for the random number generator (the default is None).Notes-----First create a ring over $n$ nodes [1]_.  Then each node in the ring isconnected with its $k$ nearest neighbors (or $k - 1$ neighbors if $k$is odd).  Then shortcuts are created by adding new edges as follows: foreach edge $(u, v)$ in the underlying "$n$-ring with $k$ nearestneighbors" with probability $p$ add a new edge $(u, w)$ withrandomly-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.http://dx.doi.org/10.1016/S0375-9601(99)00757-4"""if seed is not None:random.seed(seed)if k >= n:raise nx.NetworkXError("k>=n, choose smaller k or larger n")G = empty_graph(n)nlist = list(G.nodes())fromv = nlist# connect the k/2 neighborsfor j in range(1, k // 2 + 1):tov = fromv[j:] + fromv[0:j]  # the first j are now lastfor 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-we = list(G.edges())for (u, v) in e:if random.random() < p:w = random.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 = random.choice(nlist)if G.degree(u) >= n - 1:break  # skip this rewiringelse:G.add_edge(u, w)return Gdef watts_strogatz_graph(n, k, p, seed=None):"""Return a Watts–Strogatz small-world graph.Parameters----------n : intThe number of nodesk : intEach node is joined with its `k` nearest neighbors in a ringtopology.p : floatThe probability of rewiring each edgeseed : int, optionalSeed for random number generator (default=None)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 joinedto its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).Then shortcuts are created by replacing some edges as follows: for eachedge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"with probability $p$ replace it with a new edge $(u, w)$ with uniformlyrandom choice of existing node $w$.In contrast with :func:`newman_watts_strogatz_graph`, the random rewiringdoes not increase the number of edges. The rewired graph is not guaranteedto 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 seed is not None:random.seed(seed)G = nx.Graph()nodes = list(range(n))  # nodes are labeled 0 to n-1# connect each node to k/2 neighborsfor j in range(1, k // 2 + 1):targets = nodes[j:] + nodes[0:j]  # first j nodes are now last in listG.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 allowedfor j in range(1, k // 2 + 1):  # outer loop is neighborstargets = nodes[j:] + nodes[0:j]  # first j nodes are now last in list# inner loop in node orderfor u, v in zip(nodes, targets):if random.random() < p:w = random.choice(nodes)# Enforce no self-loops or multiple edgeswhile w == u or G.has_edge(u, w):w = random.choice(nodes)if G.degree(u) >= n - 1:break  # skip this rewiringelse:G.remove_edge(u, v)G.add_edge(u, w)return Gdef 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 ofWatts–Strogatz small-world graphs.  An exception is raised if the maximumnumber of tries is exceeded.Parameters----------n : intThe number of nodesk : intEach node is joined with its `k` nearest neighbors in a ringtopology.p : floatThe probability of rewiring each edgetries : intNumber of attempts to generate a connected graph.seed : int, optionalThe seed for random number generator.See Also--------newman_watts_strogatz_graph()watts_strogatz_graph()"""for i in range(tries):G = watts_strogatz_graph(n, k, p, seed)if nx.is_connected(G):return Graise nx.NetworkXError('Maximum number of tries exceeded')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 : intThe degree of each node.n : integerThe number of nodes. The value of $n \times d$ must be even.seed : hashable objectThe seed for random number generator.Notes-----The nodes are numbered from $0$ to $n - 1$.Kim and Vu's paper [2]_ shows that this algorithm samples in anasymptotically uniform way from the space of random graphs when$d = O(n^{1 / 3 - \epsilon})$.Raises------NetworkXErrorIf $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)if seed is not None:random.seed(seed)def _suitable(edges, potential_edges):# Helper subroutine to check if there are suitable edges remaining# If False, the generation of the graph has failedif not potential_edges:return Truefor 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 timebreakif s1 > s2:s1, s2 = s2, s1if (s1, s2) not in edges:return Truereturn Falsedef _try_creation():# Attempt to create an edge setedges = set()stubs = list(range(n)) * dwhile stubs:potential_edges = defaultdict(lambda: 0)random.shuffle(stubs)stubiter = iter(stubs)for s1, s2 in zip(stubiter, stubiter):if s1 > s2:s1, s2 = s2, s1if s1 != s2 and ((s1, s2) not in edges):edges.add((s1, s2))else:potential_edges[s1] += 1potential_edges[s2] += 1if not _suitable(edges, potential_edges):return None  # failed to find suitable edge setstubs = [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 Gdef _random_subset(seq, m):""" Return m unique elements from seq.This differs from random.sample which can return repeatedelements if seq holds repeated elements."""targets = set()while len(targets) < m:x = random.choice(seq)targets.add(x)return targetsdef barabasi_albert_graph(n, m, seed=None):"""Returns a random graph according to the Barabási–Albert preferentialattachment 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 : intNumber of nodesm : intNumber of edges to attach from a new node to existing nodesseed : int, optionalSeed for random number generator (default=None).Returns-------G : GraphRaises------NetworkXErrorIf `m` does not satisfy ``1 <= m < n``.References----------.. [1] A. L. Barabási and R. Albert "Emergence of scaling inrandom 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))if seed is not None:random.seed(seed)# Add m initial nodes (m0 in barabasi-speak)G = empty_graph(m)# Target nodes for new edgestargets = list(range(m))# List of existing nodes, with nodes repeated once for each adjacent edgerepeated_nodes = []# Start adding the other n-m nodes. The first node is m.source = mwhile 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 attachement)targets = _random_subset(repeated_nodes, m)source += 1return Gdef 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 constructedusing preferential attachment. The extended model allows new egdes,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 rewiredby randomly chosing an edge and rewiring one end to a preferentially chosen node.3) With $(1 - p - q)$ probability, $m$ new nodes are added to the graphwith edges attached preferentially.When $p = q = 0$, the model behaves just like the Barabási–Alber moParameters----------n : intNumber of nodesm : intNumber of edges with which a new node attaches to existing nodesp : floatProbability value for adding an edge between existing nodes. p + q < 1q : floatProbability value of rewiring of existing edges. p + q < 1seed : int (optional, default: None)Seed for random number generatorReturns-------G : GraphRaises------NetworkXErrorIf `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 universalityPhysical 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))if seed is not None:random.seed(seed)# 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 = mwhile new_node < n:a_probability = random.random()# Total number of edges of a Clique of all the nodesclique_degree = len(G) - 1clique_size = (len(G) * clique_degree) / 2# Adding m new edges, if there is room to add themif a_probability < p and G.size() <= clique_size - m:# Select the nodes where an edge can be addedelligible_nodes = [nd for nd, deg in G.degree()if deg < clique_degree]for i in range(m):# Choosing a random source node from elligible_nodessrc_node = random.choice(elligible_nodes)# Picking a possible node that is not 'src_node' or# neighbor with 'src_node', with preferential attachmentprohibited_nodes = list(G[src_node])prohibited_nodes.append(src_node)# This will raise an exception if the sequence is emptydest_node = random.choice([nd for nd in attachment_preferenceif nd not in prohibited_nodes])# Adding the new edgeG.add_edge(src_node, dest_node)# Appending both nodes to add to their preferential attachmentattachment_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 edgeselif 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 rewireelligible_nodes = [nd for nd, deg in G.degree()if 0 < deg < clique_degree]for i in range(m):# Choosing a random source nodenode = random.choice(elligible_nodes)# The available nodes do have a neighbor at least.neighbor_nodes = list(G[node])# Choosing the other end that will get dettachedsrc_node = random.choice(neighbor_nodes)# Picking a target node that is not 'node' or# neighbor with 'node', with preferential attachmentneighbor_nodes.append(node)dest_node = random.choice([nd for nd in attachment_preferenceif nd not in neighbor_nodes])# RewireG.remove_edge(node, src_node)G.add_edge(node, dest_node)# Adjusting the preferential attachment listattachment_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 edgeselse:# Select the edges' nodes by preferential attachmenttargets = _random_subset(attachment_preference, m)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 + 1attachment_preference.extend([new_node] * (m + 1))new_node += 1return Gdef powerlaw_cluster_graph(n, m, p, seed=None):"""Holme and Kim algorithm for growing graphs with powerlawdegree distribution and approximate average clustering.Parameters----------n : intthe number of nodesm : intthe number of random edges to add for each new nodep : float,Probability of adding a triangle after adding a random edgeseed : int, optionalSeed for random number generator (default=None).Notes-----The average clustering has a hard time getting above a certaincutoff that depends on `m`.  This cutoff is often quite low.  Thetransitivity (fraction of triangles to possible triangles) seems todecrease with network size.It is essentially the Barabási–Albert (BA) growth model with anextra step that each random edge is followed by a chance ofmaking an edge to one of its neighbors too (and thus a triangle).This algorithm improves on BA in the sense that it enables ahigher average clustering to be attained if desired.It seems possible to have a disconnected graph with this algorithmsince the initial `m` nodes may not be all linked to a new nodeon the first iteration like the BA model.Raises------NetworkXErrorIf `m` does not satisfy ``1 <= m <= n`` or `p` does notsatisfy ``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))if seed is not None:random.seed(seed)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 edgesource = m               # next node is mwhile source < n:        # Now add the other n-1 nodespossible_targets = _random_subset(repeated_nodes, m)# do one preferential attachment for new nodetarget = possible_targets.pop()G.add_edge(source, target)repeated_nodes.append(target)  # add one node to list for each new linkcount = 1while count < m:  # add m-1 more new linksif random.random() < p:  # clustering step: add triangleneighborhood = [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 linknbr = random.choice(neighborhood)G.add_edge(source, nbr)  # add trianglerepeated_nodes.append(nbr)count = count + 1continue  # go to top of while loop# else do preferential attachment step if above failstarget = possible_targets.pop()G.add_edge(source, target)repeated_nodes.append(target)count = count + 1repeated_nodes.extend([source] * m)  # add source node to list m timessource += 1return Gdef random_lobster(n, p1, p2, seed=None):"""Returns a random lobster graph.A lobster is a tree that reduces to a caterpillar when pruning allleaf nodes. A caterpillar is a tree that reduces to a path graphwhen pruning all leaf nodes; setting `p2` to zero produces a caterpillar.Parameters----------n : intThe expected number of nodes in the backbonep1 : floatProbability of adding an edge to the backbonep2 : floatProbability of adding an edge one level beyond backboneseed : int, optionalSeed for random number generator (default=None)."""# a necessary ingredient in any self-respecting graph libraryif seed is not None:random.seed(seed)llen = int(2 * random.random() * n + 0.5)L = path_graph(llen)# build caterpillar: add edges to path graph with probability p1current_node = llen - 1for n in range(llen):if random.random() < p1:  # add fuzzy caterpillar partscurrent_node += 1L.add_edge(n, current_node)if random.random() < p2:  # add crunchy lobster bitscurrent_node += 1L.add_edge(current_node - 1, current_node)return L  # voila, un lobster!def random_shell_graph(constructor, seed=None):"""Returns a random shell graph for the constructor given.Parameters----------constructor : list of three-tuplesRepresents the parameters for a shell, starting at the centershell.  Each element of the list must be of the form `(n, m,d)`, where `n` is the number of nodes in the shell, `m` isthe number of edges in the shell, and `d` is the ratio ofinter-shell (next) edges to intra-shell edges. If `d` is zero,there will be no intra-shell edges, and if `d` is one therewill be all possible intra-shell edges.seed : int, optionalSeed for random number generator (default=None).Examples-------->>> constructor = [(10, 20, 0.8), (20, 40, 0.8)]>>> G = nx.random_shell_graph(constructor)"""G = empty_graph(0)if seed is not None:random.seed(seed)glist = []intra_edges = []nnodes = 0# create gnm graphs for each shellfor (n, m, d) in constructor:inter_edges = int(m * d)intra_edges.append(m - inter_edges)g = nx.convert_node_labels_to_integers(gnm_random_graph(n, inter_edges),first_label=nnodes)glist.append(g)nnodes += nG = nx.operators.union(G, g)# connect the shells randomlyfor gi in range(len(glist) - 1):nlist1 = list(glist[gi])nlist2 = list(glist[gi + 1])total_edges = intra_edges[gi]edge_count = 0while edge_count < total_edges:u = random.choice(nlist1)v = random.choice(nlist2)if u == v or G.has_edge(u, v):continueelse:G.add_edge(u, v)edge_count = edge_count + 1return Gdef random_powerlaw_tree(n, gamma=3, seed=None, tries=100):"""Returns a tree with a power law degree distribution.Parameters----------n : intThe number of nodes.gamma : floatExponent of the power law.seed : int, optionalSeed for random number generator (default=None).tries : intNumber of attempts to adjust the sequence to make it a tree.Raises------NetworkXErrorIf no valid sequence is found within the maximum number ofattempts.Notes-----A trial power law degree sequence is chosen and then elements areswapped with new elements from a powerlaw distribution until thesequence makes a tree (by checking, for example, that the number ofedges is one smaller than the number of nodes)."""# This call may raise a NetworkXError if the number of tries is succeeded.seq = random_powerlaw_tree_sequence(n, gamma=gamma, seed=seed, tries=tries)G = degree_sequence_tree(seq)return Gdef 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 : floatExponent of the power law.seed : int, optionalSeed for random number generator (default=None).tries : intNumber of attempts to adjust the sequence to make it a tree.Raises------NetworkXErrorIf no valid sequence is found within the maximum number ofattempts.Notes-----A trial power law degree sequence is chosen and then elements areswapped with new elements from a power law distribution untilthe sequence makes a tree (by checking, for example, that the number ofedges is one smaller than the number of nodes)."""if seed is not None:random.seed(seed)# get trial sequencez = nx.utils.powerlaw_sequence(n, exponent=gamma)# 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 fromz = nx.utils.powerlaw_sequence(tries, exponent=gamma)# 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 zseqindex = random.randint(0, n - 1)zseq[index] = swap.pop()raise nx.NetworkXError('Exceeded max (%d) attempts for a valid tree'' sequence.' % tries)def random_kernel_graph(n, kernel_integral, kernel_root=None, seed=None):r"""Return an random graph based on the specified kernel.The algorithm chooses each of the $[n(n-1)]/2$ possible edges withprobability specified by a kernel $\kappa(x,y)$ [1]_.  The kernel$\kappa(x,y)$ must be a symmetric (in $x,y$), non-negative,bounded function.Parameters----------n : intThe number of nodeskernal_integral : functionFunction that returns the definite integral of the kernel $\kappa(x,y)$,$F(y,a,b) := \int_a^b \kappa(x,y)dx$kernel_root: function (optional)Function that returns the root $b$ of the equation $F(y,a,b) = r$.If None, the root is found using :func:`scipy.optimize.brentq`(this requires SciPy).seed : int, optionalSeed for random number generator (default=None)Notes-----The kernel is specified through its definite integral which must beprovided as one of the arguments. If the integral and root of thekernel integral can be found in $O(1)$ time then this algorithm runs intime $O(n+m)$ where m is the expected number of edges [2]_.The nodes are set to integers from $0$ to $n-1$.Examples--------Generate an Erdős–Rényi random graph $G(n,c/n)$, with kernel$\kappa(x,y)=c$ where $c$ is the mean expected degree.>>> def integral(u, w, z):...     return c * (z - w)>>> def root(u, w, r):...     return r / c + w>>> c = 1>>> graph = nx.random_kernel_graph(1000, integral, root)See Also--------gnp_random_graphexpected_degree_graphReferences----------.. [1] Bollobás, Béla,  Janson, S. and Riordan, O."The phase transition in inhomogeneous random graphs",*Random Structures Algorithms*, 31, 3--122, 2007... [2] Hagberg A, Lemons N (2015),"Fast Generation of Sparse Random Kernel Graphs".PLoS ONE 10(9): e0135177, 2015. doi:10.1371/journal.pone.0135177"""if seed is not None:random.seed(seed)if kernel_root is None:import scipy.optimize as optimizedef kernel_root(y, a, r):def my_function(b):return kernel_integral(y, a, b) - rreturn optimize.brentq(my_function, a, 1)graph = nx.Graph()graph.add_nodes_from(range(n))(i, j) = (1, 1)while i < n:r = -math.log(1 - random.random())  # (1-random.random()) in (0, 1]if kernel_integral(i / n, j / n, 1) <= r:i, j = i + 1, i + 1else:j = int(math.ceil(n * kernel_root(i / n, j / n, r)))graph.add_edge(i - 1, j - 1)return graph

【Python】netwokx生成图源码相关推荐

  1. python 网站 源码_在线浏览美图源码,附带python源码

    源码介绍 本源码由@香谢枫林 开发,首页图片做了浏览器窗口自适应,最大化占满PC浏览器和移动浏览器的窗口,并且防止出现滚动条. 源码截图 美图源码1 美图源码2 功能介绍 首页图片设置了4个点击功能区 ...

  2. 新版Free手机、PC、平板、笔记本四端网站缩略展示图在线一键生成网站源码

    这是一款新版Free手机.PC.平板.笔记本四端网站缩略展示图在线一键生成PHP网站源码下载 用户打开网站后输入网址域名,然后点击一下就可以生成手机端. PC电脑端.笔记本端和平板端的网站实时缩略图, ...

  3. python量化实战 顾比倒数线_顾比倒数线 主图源码

    好股票软件下载网(www.goodgupiao.com)提示:您正在下载的是:顾比倒数线 主图源码 P:=21; WH1:=IF(L=LLV(L,P),L,DRAWNULL); WH2:=CONST( ...

  4. DIY官网可视化工具打造低代码可视化一键生成导出源码工具

    DIY官网可视化工具 打造低代码可视化一键生成导出源码工具 设计一次打通设计师+产品经理+技术开发团队必备低代码可视化工具 从想法到原型到源码,一步到位低代码生成源码工具 立即定制DIY官网可视化工具 ...

  5. 图片坐标提取软件/图片坐标点和像素点颜色提取软件/图片坐标获取工具/Python图片坐标获取源码/图片像素坐标获取软件/python tkinter 图片显示(完全开源)

    该软件使用python写的,可以提取像素点的坐标还有也能获取像素点的16进制数据RGB565和RGB888(RGB888仅最新的源码才支持),可以单点坐标也可以按键坐标,甚至可以使用简单的左右键配合使 ...

  6. 我的CSDN笔记总索引(阅读量降序,代码自动遍历生成HTML5源码)

    Python代码用"命令容器"方法os.system(),调用Linux命令行工具crul获取CSDN博文页面源码,Python内置re正则解析出博文笔记信息,按阅读量降序模块输出 ...

  7. python浪漫代码-python七夕浪漫表白源码

    本文实例为大家分享了python七夕浪漫表白的具体代码,供大家参考,具体内容如下 from turtle import * from time import sleep def go_to(x, y) ...

  8. lmbs PHP,PHP的GD2函数创建折线图源码示例

    PHP的GD2函数创建折线图源码示例 代码来自 codego.net/tags/4/1/ if(!is_numeric($data[$i])) die("error id:1"); ...

  9. C++ Opengl纹理贴图源码

    C++ Opengl纹理贴图源码 项目开发环境 项目功能 项目演示 项目源码传送门 项目开发环境 开发语言:C++和IDE:VS2017,操作系统Windows版本windows SDK8.1,三方库 ...

最新文章

  1. codeforces gym100959 I - Robots(稠密图建图优化)
  2. 移动web时代已开启:腾讯X5内核浏览服务
  3. ssl证书链的验证的其它方式
  4. 有血有肉,汇报年终总结
  5. python实现文件压缩
  6. 查看对方IP地址的5种方法
  7. idea启动vue项目
  8. 有一个7升的杯子和一个4升的杯子,如何盛出5升水?
  9. 推荐几款不错的企业网站,前端设计师寻求设计灵感!
  10. Firefox检测到潜在的安全威胁,并因blog.csdn.net要求安全连接而没有继续
  11. kika平台广告sdk集成问题
  12. 全栈很屌?什么是全栈工程师
  13. 什么是水货?如何辨别水货手机?水货手机能不能用?
  14. 看不到同一个网络下的其他计算机,看不到局域网其他计算机怎么办
  15. 软考中级考试一般需要准备多长时间?
  16. Android终端实现个人中心界面
  17. 计算机软件ghb,GHB 文件扩展名: 它是什么以及如何打开它?
  18. ubuntu 中w指令中的IDLE是什么意思
  19. creo管道设计教程_Pro/E Pro/PIPING 管道设计教程|就上UG网
  20. 【转帖】接口测试流程、测试点和测试工具

热门文章

  1. 第14章 网络设备文件管理2-(H3CNE)
  2. 计算机excel2010操作题,计算机应用基础Excel2010综合测试操作步骤参考自测题步骤...
  3. HCIPRS223-V2.5一些总结
  4. WebMatrix进阶教程(8):创建删除数据网页
  5. JavaScript基本数据类型以及内存分配
  6. 令博主崩溃的scanf函数-C语言
  7. CRM系统中,哪个品牌比较好?
  8. 如何用计算机管理员权限,计算机管理员权限如何获得【图解】
  9. File::Stamped 时间戳log文件
  10. 图解硬盘低格操作方法