K iFLdZddlZddlmZddlZddlmZddlm Z m Z m Z m Z gdZ e dejdd dd Ze dejdd dd Ze d ejdd dd Ze dejdd  ddZe dejdd ddZejdd ddZe dddZe dddZy)zd Generators for some directed graphs, including growing network (GN) graphs and scale-free graphs. N)Counter) empty_graph)discrete_sequencenp_random_statepy_random_stateweighted_choice)gn_graph gnc_graph gnr_graphrandom_k_out_graphscale_free_graphT)graphs returns_graphctd|tj}|jstjd|d}|dk(r|S|j ddddg}t d|D]X}|Dcgc] }|| }}td||d} |j || |jd|| xxdz cc<Z|Scc}w)aBReturns 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`. 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. default+create_using must indicate a Directed Graphc|SN)xs b/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/networkx/generators/directed.pykernelzgn_graph..kernelLsHr) distributionseed) rnxDiGraph is_directed NetworkXErroradd_edgerangerappend) nr create_usingrGdssourceddisttargets rr r sT A|RZZ8A ==?LMM ~  AvJJq! QB1+#%&aq &&"14dCAF 66" !  6 a  H 's7C cdtd|tj}|jstjd|dk(r|St d|D]X}|j d|}|j|kr|dk7rt|j|}|j||Z|S)aReturns 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 probability `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`. 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. rrrr) rr r!r"r#r% randrangerandomnext successorsr$)r'pr(rr)r+r.s rr r `sN A|RZZ8A ==?LMMAv1+#6* ;;=1 1!,,v./F 66" # HrrcPtd|tj}|jstjd|dk(r|St d|D]N}|j d|}|j|D]}|j|||j||P|S)a$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`. References ---------- .. [1] P. L. Krapivsky and S. Redner, Network Growth by Copying, Phys. Rev. E, 71, 036118, 2005k.}, rrrr) rr r!r"r#r%r0r3r$)r'r(rr)r+r.succs rr r s2 A|RZZ8A ==?LMMAv1+#6*LL( %D JJvt $ % 66" # Hrcfd}|>t|dr2t|tjstjd|} ntjgd} |dkr t d|dkr t d|dkr t dt ||z|zd z d k\r t d |dkr t d |dkr t d td| jDg} td| jDg} t| j} | Dcgc]}t|tjs|!} }t| dkDrtd| Ddz}nd}t| krj!}||kr#|}|dz }| j#||| | |}n?|||zkr|| | |}|| | |}n"|| | |}|}|dz }| j#|| j%||| j#|| j#|t| |kr| Scc}w)ucReturns 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. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness`. initial_graph : MultiDiGraph instance, optional Build the scale-free graph starting from this initial MultiDiGraph, if provided. Returns ------- MultiDiGraph 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. c|dkDrCt||z}||t|zz }j|krj|Sj|S)Nr)lenr1choice) candidates node_listdeltabias_sump_deltars r _choose_nodez&scale_free_graph.._choose_nodesW 199~-H(S_"<=G{{}w&{{9--{{:&&r_adjz%initial_graph must be a MultiDiGraph.))rr)rr)rrrzalpha must be > 0.zbeta must be > 0.zgamma must be > 0.g?g& .>zalpha+beta+gamma must equal 1.zdelta_in must be >= 0.zdelta_out must be >= 0.c3.K|] \}}||gzywrr.0idxcounts r z#scale_free_graph..s = Uesem =c3.K|] \}}||gzywrrrDs rrHz#scale_free_graph..s < Uesem .'s8QS[8s!r)hasattr isinstancer MultiDiGraphr# ValueErrorabssum out_degree in_degreelistnodesnumbersNumberr:maxr1r&r$)r'alphabetagammadelta_in delta_outr initial_graphrAr)vswsr= numeric_nodescursorrvws ` rr r sJ|' W]F%C-9""#JK K  OO4 5 z-.. qy,-- z-.. 54<% # %&$.9::!|1221}233 =alln =r BB >-JQKMK =A8-881< a&1* KKM u9A aKF   Q RH5A  RI6ARH5A RI6AA aKF   Q  1a !  ! I a&1*L H]Ls /IIc |rtj}fd}ntj}fd}tj||}t |}|D]# |j fd| |D%|S)a_Returns a random `k`-out graph with uniform attachment. A random `k`-out graph with uniform attachment is a multidigraph generated by the following algorithm. For each node *u*, choose `k` nodes *v* uniformly at random (with replacement). Add a directed edge joining *u* to *v*. Parameters ---------- n : int The number of nodes in the returned graph. k : int The out-degree of each node in the returned graph. self_loops : bool If True, self-loops are allowed when generating the graph. with_replacement : bool If True, neighbors are chosen with replacement and the returned graph will be a directed multigraph. Otherwise, neighbors are chosen without replacement and the returned graph will be a directed graph. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness`. Returns ------- NetworkX graph A `k`-out-regular directed graph generated according to the above algorithm. It will be a multigraph if and only if `with_replacement` is True. Raises ------ ValueError If `with_replacement` is False and `k` is greater than `n`. See also -------- random_k_out_graph Notes ----- The return digraph or multidigraph may not be strongly connected, or even weakly connected. If `with_replacement` is True, this function is similar to :func:`random_k_out_graph`, if that function had parameter `alpha` set to positive infinity. c@s|hz fdtDS)Nc3RK|]}jt ywr)r;rV)rEirWrs rrHz=random_uniform_k_out_graph..sample..s?DKKU ,?s$')r%rfrWkr self_loopss `rsamplez*random_uniform_k_out_graph..samples  ?eAh? ?rcJs||hz }jt|Sr)rprVrms rrpz*random_uniform_k_out_graph..samples& ;;tE{A. .rc3&K|]}|f ywrr)rErfus rrHz-random_uniform_k_out_graph..s:A!Q:s)r rPr!rsetadd_edges_from) r'rnrowith_replacementrr(rpr)rWrss `` ` @rrandom_uniform_k_out_graphrwUswt(  @ zz|  / q,'A FE ; :5)9::; Hrc~|dkr td t|||||S#t$rt|||||cYSwxYw)ac Returns a random `k`-out graph with preferential attachment. .. versionchanged:: 3.5 Different implementations will be used based on whether NumPy is available. See Notes for details. A random `k`-out graph with preferential attachment is a multidigraph generated by the following algorithm. 1. Begin with an empty digraph, and initially set each node to have weight `alpha`. 2. Choose a node `u` with out-degree less than `k` uniformly at random. 3. Choose a node `v` from with probability proportional to its weight. 4. Add a directed edge from `u` to `v`, and increase the weight of `v` by one. 5. If each node has out-degree `k`, halt, otherwise repeat from step 2. For more information on this model of random graph, see [1]_. Parameters ---------- n : int The number of nodes in the returned graph. k : int The out-degree of each node in the returned graph. alpha : float A positive :class:`float` representing the initial weight of each vertex. A higher number means that in step 3 above, nodes will be chosen more like a true uniformly random sample, and a lower number means that nodes are more likely to be chosen as their in-degree increases. If this parameter is not positive, a :exc:`ValueError` is raised. self_loops : bool If True, self-loops are allowed when generating the graph. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness`. Returns ------- :class:`~networkx.classes.MultiDiGraph` A `k`-out-regular multidigraph generated according to the above algorithm. Raises ------ ValueError If `alpha` is not positive. Notes ----- The returned multidigraph may not be strongly connected, or even weakly connected. `random_k_out_graph` has two implementations: an array-based formulation that uses `numpy` (``_random_k_out_graph_numpy``), and a pure-Python implementation (``_random_k_out_graph_python``). The NumPy implementation is more performant, especially for large `n`, and is therefore used by default. If NumPy is not installed in the environment, then the pure Python implementation is executed. However, you can explicitly control which implementation is executed by directly calling the corresponding function:: # Use numpy if available, else Python nx.random_k_out_graph(1000, 5, alpha=1) # Use the numpy-based implementation (raises ImportError if numpy not installed) nx.generators.directed._random_k_out_graph_numpy(1000, 5, alpha=1) # Use the Python-based implementation nx.generators.directed._random_k_out_graph_python(1000, 5, alpha=1) References ---------- .. [1] Peterson, Nicholas R., and Boris Pittel. "Distance between two random `k`-out digraphs, with and without preferential attachment." arXiv preprint arXiv:1311.5961 (2013) . rzalpha must be positive)rQ_random_k_out_graph_numpy ImportError_random_k_out_graph_python)r'rnr[rors rr r sUp qy122I(Auj$GG I)!Qz4HHIs !<<c<ddl}tj|tj}|j |}|j |d}|j ||} ||z} |j |} t||zD]} |j||} |r|j|| | z }n(| | }d| | <|j|| | |z z }|| | <|j| || |xxdz cc<| dz } | | xxdz cc<| | |k(sd|| <|S)Nrr(T)r4rF) numpyr rrParangefullzerosr%r;r$)r'rnr[rornpr)rWremaining_maskweights total_weight out_strengthsrlrsrfu_weights rryrys* qr7A IIaLEWWQ%NggaGu9LHHQKM 1q5\& KKn- .  EW|%; rs 3 T2? 3? DT21 31 hT2# 3# LT2    R 3R jT2L 3L ^T2\I3\I~  <  r