
    h_                        S r SSKrSSKrSSKrSSKJr  / SQr\R                  " SSS9S 5       r	\R                  " SSS9S 5       r
\" S	5      \R                  " SSS9SS
 j5       5       r\" S	5      \R                  " SSS9SS j5       5       r\" S5      \R                  " SSS9SS j5       5       r\" S5      \R                  " SSS9SS j5       5       r\R                  " SSS9S 5       r\R                  " SSS9S 5       r\" S	5      \R                  " SSS9 SS j5       5       rS rS rS rS rS r\" S5      \R                  " SSS9        SS j5       5       rg)zBGenerators for classes of graphs used in studying social networks.    N)py_random_state)
caveman_graphconnected_caveman_graphrelaxed_caveman_graphrandom_partition_graphplanted_partition_graphgaussian_random_partition_graphring_of_cliqueswindmill_graphstochastic_block_modelLFR_benchmark_graphT)graphsreturns_graphc                     [         R                  " X-  5      nUS:  aJ  [        SX-  U5       H7  n[        R                  " [        X3U-   5      S5      nUR                  U5        M9     U$ )a  Returns a caveman graph of `l` cliques of size `k`.

Parameters
----------
l : int
  Number of cliques
k : int
  Size of cliques

Returns
-------
G : NetworkX Graph
  caveman graph

Notes
-----
This returns an undirected graph, it can be converted to a directed
graph using :func:`nx.to_directed`, or a multigraph using
``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is
described in [1]_ and it is unclear which of the directed
generalizations is most useful.

Examples
--------
>>> G = nx.caveman_graph(3, 3)

See also
--------

connected_caveman_graph

References
----------
.. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.'
   Amer. J. Soc. 105, 493-527, 1999.
   r      )nxempty_graphrange	itertoolscombinationsadd_edges_from)lkGstartedgess        O/var/www/html/env/lib/python3.13/site-packages/networkx/generators/community.pyr   r      sa    N 	quA1u1aeQ'E**5	+BAFEU# ( H    c                     US:  a  [         R                  " S5      e[         R                  " X5      n[        SX-  U5       H0  nUR	                  X3S-   5        UR                  X3S-
  X-  -  5        M2     U$ )a  Returns a connected caveman graph of `l` cliques of size `k`.

The connected caveman graph is formed by creating `n` cliques of size
`k`, then a single edge in each clique is rewired to a node in an
adjacent clique.

Parameters
----------
l : int
  number of cliques
k : int
  size of cliques (k at least 2 or NetworkXError is raised)

Returns
-------
G : NetworkX Graph
  connected caveman graph

Raises
------
NetworkXError
    If the size of cliques `k` is smaller than 2.

Notes
-----
This returns an undirected graph, it can be converted to a directed
graph using :func:`nx.to_directed`, or a multigraph using
``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is
described in [1]_ and it is unclear which of the directed
generalizations is most useful.

Examples
--------
>>> G = nx.connected_caveman_graph(3, 3)

References
----------
.. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.'
   Amer. J. Soc. 105, 493-527, 1999.
r   zDThe size of cliques in a connected caveman graph must be at least 2.r   r   )r   NetworkXErrorr   r   remove_edgeadd_edge)r   r   r   r   s       r   r   r   F   sw    T 	1uR
 	
 	Aq!%#	eQY'	

519/0 $ Hr      c                 <   [         R                  " X5      n[        U5      nUR                  5        Hf  u  pgUR	                  5       U:  d  M  UR                  U5      nUR                  Xh5      (       a  MD  UR                  Xg5        UR                  Xh5        Mh     U$ )a#  Returns a relaxed caveman graph.

A relaxed caveman graph starts with `l` cliques of size `k`.  Edges are
then randomly rewired with probability `p` to link different cliques.

Parameters
----------
l : int
  Number of groups
k : int
  Size of cliques
p : float
  Probability of rewiring each edge.
seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

Returns
-------
G : NetworkX Graph
  Relaxed Caveman Graph

Raises
------
NetworkXError
 If p is not in [0,1]

Examples
--------
>>> G = nx.relaxed_caveman_graph(2, 3, 0.1, seed=42)

References
----------
.. [1] Santo Fortunato, Community Detection in Graphs,
   Physics Reports Volume 486, Issues 3-5, February 2010, Pages 75-174.
   https://arxiv.org/abs/0906.0612
)	r   r   listr   randomchoicehas_edger"   r#   )	r   r   pseedr   nodesuvxs	            r   r   r   |   s}    P 	AGE	;;=1E"Azz!MM!JJq  Hr   c           
      ~   SUs=::  a  S::  d  O  [         R                  " S5      eSUs=::  a  S::  d  O  [         R                  " S5      e[        U 5      n[        U5       VVs/ s H  n[        U5       Vs/ s H  orPM     snPM      nnn[        U5       H
  nXU   U'   M     [	        U USUUSSS9$ s  snf s  snnf )	a  Returns the random partition graph with a partition of sizes.

A partition graph is a graph of communities with sizes defined by
s in sizes. Nodes in the same group are connected with probability
p_in and nodes of different groups are connected with probability
p_out.

Parameters
----------
sizes : list of ints
  Sizes of groups
p_in : float
  probability of edges with in groups
p_out : float
  probability of edges between groups
directed : boolean optional, default=False
  Whether to create a directed graph
seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

Returns
-------
G : NetworkX Graph or DiGraph
  random partition graph of size sum(gs)

Raises
------
NetworkXError
  If p_in or p_out is not in [0,1]

Examples
--------
>>> G = nx.random_partition_graph([10, 10, 10], 0.25, 0.01)
>>> len(G)
30
>>> partition = G.graph["partition"]
>>> len(partition)
3

Notes
-----
This is a generalization of the planted-l-partition described in
[1]_.  It allows for the creation of groups of any size.

The partition is store as a graph attribute 'partition'.

References
----------
.. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports
   Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
g        g      ?zp_in must be in [0,1]zp_out must be in [0,1]NFT)nodelistr+   directed	selfloopssparse)r   r!   lenr   r   )	sizesp_inp_outr+   r2   
num_blocksrsr*   s	            r   r   r      s    r $#677%3788 UJ5::5FG5Fz*	+*A%*	+5FAG:!Q  "	 	 
,Gs   $B97B4B94B9   c                      [        U/U -  X#XES9$ )a  Returns the planted l-partition graph.

This model partitions a graph with n=l*k vertices in
l groups with k vertices each. Vertices of the same
group are linked with a probability p_in, and vertices
of different groups are linked with probability p_out.

Parameters
----------
l : int
  Number of groups
k : int
  Number of vertices in each group
p_in : float
  probability of connecting vertices within a group
p_out : float
  probability of connected vertices between groups
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

Returns
-------
G : NetworkX Graph or DiGraph
  planted l-partition graph

Raises
------
NetworkXError
  If `p_in`, `p_out` are not in `[0, 1]`

Examples
--------
>>> G = nx.planted_partition_graph(4, 3, 0.5, 0.1, seed=42)

See Also
--------
random_partition_model

References
----------
.. [1] A. Condon, R.M. Karp, Algorithms for graph partitioning
    on the planted partition model,
    Random Struct. Algor. 18 (2001) 116-140.

.. [2] Santo Fortunato 'Community Detection in Graphs' Physical Reports
   Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
r+   r2   )r   )r   r   r7   r8   r+   r2   s         r   r   r      s    j "1#'4TUUr      c                    X:  a  [         R                  " S5      eSn/ n [        UR                  XU-  S-   5      5      n	U	S:  a  M)  Xy-   U :  a  UR	                  X-
  5        OXy-  nUR	                  U	5        M[  [        XXFUS9$ )a  Generate a Gaussian random partition graph.

A Gaussian random partition graph is created by creating k partitions
each with a size drawn from a normal distribution with mean s and variance
s/v. Nodes are connected within clusters with probability p_in and
between clusters with probability p_out[1]

Parameters
----------
n : int
  Number of nodes in the graph
s : float
  Mean cluster size
v : float
  Shape parameter. The variance of cluster size distribution is s/v.
p_in : float
  Probability of intra cluster connection.
p_out : float
  Probability of inter cluster connection.
directed : boolean, optional default=False
  Whether to create a directed graph or not
seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

Returns
-------
G : NetworkX Graph or DiGraph
  gaussian random partition graph

Raises
------
NetworkXError
  If s is > n
  If p_in or p_out is not in [0,1]

Notes
-----
Note the number of partitions is dependent on s,v and n, and that the
last partition may be considerably smaller, as it is sized to simply
fill out the nodes [1]

See Also
--------
random_partition_graph

Examples
--------
>>> G = nx.gaussian_random_partition_graph(100, 10, 10, 0.25, 0.1)
>>> len(G)
100

References
----------
.. [1] Ulrik Brandes, Marco Gaertler, Dorothea Wagner,
   Experiments on Graph Clustering Algorithms,
   In the proceedings of the 11th Europ. Symp. Algorithms, 2003.
zs must be <= nr   g      ?r   r>   )r   r!   intgaussappendr   )
nr;   r.   r7   r8   r2   r+   assignedr6   sizes
             r   r	   r	   7  s    z 	u/00HE
4::aQ-.!8?aLL&T  "%u(SSr   c                 z   U S:  a  [         R                  " S5      eUS:  a  [         R                  " S5      e[         R                  " 5       n[        U 5       H^  n[        R
                  " [        X1-  X1-  U-   5      S5      nUR                  U5        UR                  X1-  S-   US-   U-  X-  -  5        M`     U$ )a  Defines a "ring of cliques" graph.

A ring of cliques graph is consisting of cliques, connected through single
links. Each clique is a complete graph.

Parameters
----------
num_cliques : int
    Number of cliques
clique_size : int
    Size of cliques

Returns
-------
G : NetworkX Graph
    ring of cliques graph

Raises
------
NetworkXError
    If the number of cliques is lower than 2 or
    if the size of cliques is smaller than 2.

Examples
--------
>>> G = nx.ring_of_cliques(8, 4)

See Also
--------
connected_caveman_graph

Notes
-----
The `connected_caveman_graph` graph removes a link from each clique to
connect it with the next clique. Instead, the `ring_of_cliques` graph
simply adds the link without removing any link from the cliques.
r   z0A ring of cliques must have at least two cliques(The cliques must have at least two nodesr   )r   r!   Graphr   r   r   r   r#   )num_cliquesclique_sizer   ir   s        r   r
   r
     s    N QQRRQIJJ

A;&&!/1?[#@A1
 	
	

Oa!a%;!6+:S!T	
   Hr   c           
        ^ U S:  a  Sn[         R                  " U5      eTS:  a  [         R                  " S5      e[         R                  " [        R                  " [         R
                  " T5      /U4S j[        U S-
  5       5       5      5      nUR                  S [        TUR                  5       5       5       5        U$ )a  Generate a windmill graph.
A windmill graph is a graph of `n` cliques each of size `k` that are all
joined at one node.
It can be thought of as taking a disjoint union of `n` cliques of size `k`,
selecting one point from each, and contracting all of the selected points.
Alternatively, one could generate `n` cliques of size `k-1` and one node
that is connected to all other nodes in the graph.

Parameters
----------
n : int
    Number of cliques
k : int
    Size of cliques

Returns
-------
G : NetworkX Graph
    windmill graph with n cliques of size k

Raises
------
NetworkXError
    If the number of cliques is less than two
    If the size of the cliques are less than two

Examples
--------
>>> G = nx.windmill_graph(4, 5)

Notes
-----
The node labeled `0` will be the node connected to all other nodes.
Note that windmill graphs are usually denoted `Wd(k,n)`, so the parameters
are in the opposite order as the parameters of this method.
r   z/A windmill graph must have at least two cliquesrH   c              3   V   >#    U  H  n[         R                  " TS -
  5      v   M      g7f)r   N)r   complete_graph).0_r   s     r   	<genexpr>!windmill_graph.<locals>.<genexpr>  s#     $T|!R%6%6q1u%=%=|s   &)r   c              3   *   #    U  H	  nS U4v   M     g7f)r   N )rP   rL   s     r   rR   rS     s     C%BaV%Bs   )	r   r!   disjoint_union_allr   chainrO   r   r   number_of_nodes)rD   r   msgr   s    `  r   r   r     s    L 	1u?s##1uIJJ
q!"$TuQQRU|$T	
	A
 CU1a.?.?.A%BCCHr   c           
      	   [        U 5      [        U5      :w  a  [        R                  " S5      eU H1  n[        U5      [        U5      :w  d  M  [        R                  " S5      e   U(       dz  [        U6  Vs/ s H  n[	        U5      PM     n	n[        X5       HJ  n[        US   US   5       H1  n
[        U
S   U
S   -
  5      S:  d  M  [        R                  " S5      e   ML     U H.  nU H%  nUS:  d  US:  d  M  [        R                  " S5      e   M0     Ubf  [        U5      [        U 5      :w  a  [        R                  " S	5      e[        U5      [        [        U5      5      :w  a  [        R                  " S
5      eO[        [        U 5      5      n[        [        U 5      5      nU(       a,  [        R                  " 5       n[        R                  " X5      nO,[        R                  " 5       n[        R                  " US5      n[        [        U 5      S-   5       Vs/ s H  n[        U SU 5      PM     nn[        [        U5      S-
  5       Vs/ s H  n[        UUU   UUS-       5      PM     snUR                  S'   [        UR                  S   5       H  u  nnU H  nUR!                  UUS9  M     M!     SUl        UR                  S   nU GH  u  pX:X  a  U(       a@  U(       a  [        R                  " UU   UU   5      nOc[        R$                  " UU   S5      nOH[        R&                  " UU   S5      nU(       a'  [        R(                  " U[        UU   UU   5      5      nU H-  nUR+                  5       X   U
   :  d  M  UR,                  " U6   M/     O[        R                  " UU   UU
   5      nU(       a  X   U
   S:X  a  U H  nUR,                  " U6   M     GM  X   U
   S:  a    [.        R0                  " UR+                  5       5      n[.        R2                  " U[.        R0                  " SX   U
   -
  5      -  5      n[5        [        R6                  " UUU5      S5        [5        U5      nUR,                  " U6   M  GM  U H-  nUR+                  5       X   U
   :  d  M  UR,                  " U6   M/     GM     U$ s  snf s  snf s  snf ! [8         a     GM  f = f)a  Returns a stochastic block model graph.

This model partitions the nodes in blocks of arbitrary sizes, and places
edges between pairs of nodes independently, with a probability that depends
on the blocks.

Parameters
----------
sizes : list of ints
    Sizes of blocks
p : list of list of floats
    Element (r,s) gives the density of edges going from the nodes
    of group r to nodes of group s.
    p must match the number of groups (len(sizes) == len(p)),
    and it must be symmetric if the graph is undirected.
nodelist : list, optional
    The block tags are assigned according to the node identifiers
    in nodelist. If nodelist is None, then the ordering is the
    range [0,sum(sizes)-1].
seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.
directed : boolean optional, default=False
    Whether to create a directed graph or not.
selfloops : boolean optional, default=False
    Whether to include self-loops or not.
sparse: boolean optional, default=True
    Use the sparse heuristic to speed up the generator.

Returns
-------
g : NetworkX Graph or DiGraph
    Stochastic block model graph of size sum(sizes)

Raises
------
NetworkXError
  If probabilities are not in [0,1].
  If the probability matrix is not square (directed case).
  If the probability matrix is not symmetric (undirected case).
  If the sizes list does not match nodelist or the probability matrix.
  If nodelist contains duplicate.

Examples
--------
>>> sizes = [75, 75, 300]
>>> probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
>>> g = nx.stochastic_block_model(sizes, probs, seed=0)
>>> len(g)
450
>>> H = nx.quotient_graph(g, g.graph["partition"], relabel=True)
>>> for v in H.nodes(data=True):
...     print(round(v[1]["density"], 3))
0.245
0.348
0.405
>>> for v in H.edges(data=True):
...     print(round(1.0 * v[2]["weight"] / (sizes[v[0]] * sizes[v[1]]), 3))
0.051
0.022
0.07

See Also
--------
random_partition_graph
planted_partition_graph
gaussian_random_partition_graph
gnp_random_graph

References
----------
.. [1] Holland, P. W., Laskey, K. B., & Leinhardt, S.,
       "Stochastic blockmodels: First steps",
       Social networks, 5(2), 109-137, 1983.
z'sizes' and 'p' do not match.z'p' must be a square matrix.r   r   g:0yE>z'p' must be symmetric.zEntries of 'p' not in [0,1].Nz$'nodelist' and 'sizes' do not match.znodelist contains duplicate.r   	partition)blockr   )r5   r   NetworkXExceptionzipr&   abssumsetr   DiGraphr   productrI   combinations_with_replacementgraph	enumerateadd_nodenamepermutationsr   rW   r'   r#   mathlogfloornextisliceStopIteration)r6   r*   r1   r+   r2   r3   r4   rowrL   p_transposejprobblock_rangeg
block_iterr/   size_cumsumblock_idr,   nodepartsr   elograndskips                            r   r   r     sC   b 5zSV""#BCCq6SX&&'EFF  (+Q01tAw0Q$A1qt_qtad{#e+../GHH % %
 Dax4!8**+IJJ  
 x=CJ&&&'MNNx=CH..&&'EFF / U$ E
#KJJL&&{@
HHJ<<[!L
,1#e*q.,AB,Aq3uQqz?,AKB s;'!+,,A 	H[^k!a%&89:,AGGK
 %QWW[%9:%DJJt8J,  ; &AF GGK E6%--eAhaAE%2258Q?E!..uQx;%OOE3uQxq3JKE;;=147*JJN  %%eAha9EtAw!|AJJN a1"&((4;;="9#zz'DHHQa[4I*IJY--eT4@$G K

A   ;;=147*JJN A F H[ 18 CT ) s%   7S$S!S BS##
S21S2c                     [         R                  R                  XU5      nXB:  a'  [         R                  R                  XU5      nXB:  a  M'  U$ )zReturns a random value chosen from the bounded Zipf distribution.

Repeatedly draws values from the Zipf distribution until the
threshold is met, then returns that value.
)r   utilszipf_rv)gammaxmin	thresholdr+   results        r   _zipf_rv_belowr     sC     XXe40F

!!%t4 
Mr   c           	          [        U5       HM  n/ nU" U5      (       d*  UR                  [        XX&5      5        U" U5      (       d  M*  U" U5      (       d  MK  Us  $    [        R                  " S5      e)as  Returns a list of numbers obeying a constrained power law distribution.

``gamma`` and ``low`` are the parameters for the Zipf distribution.

``high`` is the maximum allowed value for values draw from the Zipf
distribution. For more information, see :func:`_zipf_rv_below`.

``condition`` and ``length`` are Boolean-valued functions on
lists. While generating the list, random values are drawn and
appended to the list until ``length`` is satisfied by the created
list. Once ``condition`` is satisfied, the sequence generated in
this way is returned.

``max_iters`` indicates the number of times to generate a list
satisfying ``length``. If the number of iterations exceeds this
value, :exc:`~networkx.exception.ExceededMaxIterations` is raised.

seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.
z#Could not create power law sequence)r   rC   r   r   ExceededMaxIterations)	r   lowhigh	conditionlength	max_itersr+   rL   seqs	            r   _powerlaw_sequencer     sa    , 9++JJ~e$=> ++S>>J  
"
"#H
IIr   c                     Sn[        S5      * nSn[        X4-
  5      U:  a'  UnUSXQ-   U -  -  -  nUS-  n[        X4-
  5      U:  a  M'  U$ )zThe Hurwitz zeta function, or the Riemann zeta function of two arguments.

``x`` must be greater than one and ``q`` must be positive.

This function repeatedly computes subsequent partial sums until
convergence, as decided by ``tolerance``.
r   infr   )floatr_   )r/   q	tolerancezz_prevr   s         r   _hurwitz_zetar     sa     	
AEl]F	A
aj/I
%	Q15Q,	Q aj/I
% Hr   c                   ^  SSK Jn  UnSnXg-
  S-  U-   nSn	Sn
[        X-
  5      T:  a  X:  a  [        R
                  " S5      eSn
[        [        U5      US-   5       H  nXU * S-   -  U" X5      -  -  n
M     X:  a  UnXg-
  S-  U-   nOUnXg-
  S-  U-   nU	S-  n	[        X-
  5      T:  a  M  [        U5      $ ! [         a	    U4S jn Nf = f)z7Returns a minimum degree from the given average degree.r   )zetac                    > [        XT5      $ N)r   )r/   r   r   s     r   r   "_generate_min_degree.<locals>.zeta  s     y11r   r   r   zCould not match average_degree)	scipy.specialr   ImportErrorr_   r   r   r   rA   round)r   average_degree
max_degreer   r   r   min_deg_topmin_deg_botmin_deg_miditrsmid_avg_degr/   s      `        r   _generate_min_degreer     s	   2& KK,1K?KDK
k*
+i
7**+KLLs;'a8A5&1*-e1IIIK 9'%K&49KGK%K&49KGK	 k*
+i
7 1  2	22s   B= =CCc                 6   U Vs/ s H  n[        5       PM     nn[        U 5      n[        [        U5      5      n[        U5       H  n	UR	                  5       n
UR                  [        [        U5      5      5      n[        X
   SU-
  -  5      nXU   :  a  Xk   R                  U
5        OUR                  U
5        [        Xk   5      X   :  a!  UR                  Xk   R	                  5       5        U(       a  M  Us  $    Sn[        R                  " U5      es  snf )a  Returns a list of sets, each of which represents a community.

``degree_seq`` is the degree sequence that must be met by the
graph.

``community_sizes`` is the community size distribution that must be
met by the generated list of sets.

``mu`` is a float in the interval [0, 1] indicating the fraction of
intra-community edges incident to each node.

``max_iters`` is the number of times to try to add a node to a
community. This must be greater than the length of
``degree_seq``, otherwise this function will always fail. If
the number of iterations exceeds this value,
:exc:`~networkx.exception.ExceededMaxIterations` is raised.

seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

The communities returned by this are sets of integers in the set {0,
..., *n* - 1}, where *n* is the length of ``degree_seq``.

r   z:Could not assign communities; try increasing min_community)ra   r5   r&   r   popr(   r   addrC   r   r   )
degree_seqcommunity_sizesmur   r+   rQ   r   rD   freerL   r.   cr;   rY   s                 r   _generate_communitiesr     s    6 --_ce_F-JAa>D9HHJKKc/234*-1r6*+ q!!IMM!KKNvy>O..KK	(tM! " GC

"
"3
''+ .s   D   c           	        ^  US:  d  [         R                  " S5      eUS:  d  [         R                  " S5      eSUs=::  a  S::  d  O  [         R                  " S5      eUc  T nO%SUs=:  a  T ::  d  O  [         R                  " S5      eUSL USL -  (       d  [         R                  " S5      eUc  [        XXiU
5      nXVpS	 nU 4S
 jn[        XXXU5      nUc  [	        U5      nUc  [        U5      nXxpU 4S jnU 4S jn[        X,XXU5      nU
ST -  -  n
[        UUX:U5      n[         R                  " 5       nUR                  [        T 5      5        U H  nU H  nUR                  U5      [        UU   SU-
  -  5      :  aU  UR                  [        U5      5      nUR                  UU5        UR                  U5      [        UU   SU-
  -  5      :  a  MU  UR                  U5      UU   :  aL  UR                  [        T 5      5      nUU;  a  UR                  UU5        UR                  U5      UU   :  a  ML  UUR                  U   S'   M     GM     U$ )a  Returns the LFR benchmark graph.

This algorithm proceeds as follows:

1) Find a degree sequence with a power law distribution, and minimum
   value ``min_degree``, which has approximate average degree
   ``average_degree``. This is accomplished by either

   a) specifying ``min_degree`` and not ``average_degree``,
   b) specifying ``average_degree`` and not ``min_degree``, in which
      case a suitable minimum degree will be found.

   ``max_degree`` can also be specified, otherwise it will be set to
   ``n``. Each node *u* will have $\mu \mathrm{deg}(u)$ edges
   joining it to nodes in communities other than its own and $(1 -
   \mu) \mathrm{deg}(u)$ edges joining it to nodes in its own
   community.
2) Generate community sizes according to a power law distribution
   with exponent ``tau2``. If ``min_community`` and
   ``max_community`` are not specified they will be selected to be
   ``min_degree`` and ``max_degree``, respectively.  Community sizes
   are generated until the sum of their sizes equals ``n``.
3) Each node will be randomly assigned a community with the
   condition that the community is large enough for the node's
   intra-community degree, $(1 - \mu) \mathrm{deg}(u)$ as
   described in step 2. If a community grows too large, a random node
   will be selected for reassignment to a new community, until all
   nodes have been assigned a community.
4) Each node *u* then adds $(1 - \mu) \mathrm{deg}(u)$
   intra-community edges and $\mu \mathrm{deg}(u)$ inter-community
   edges.

Parameters
----------
n : int
    Number of nodes in the created graph.

tau1 : float
    Power law exponent for the degree distribution of the created
    graph. This value must be strictly greater than one.

tau2 : float
    Power law exponent for the community size distribution in the
    created graph. This value must be strictly greater than one.

mu : float
    Fraction of inter-community edges incident to each node. This
    value must be in the interval [0, 1].

average_degree : float
    Desired average degree of nodes in the created graph. This value
    must be in the interval [0, *n*]. Exactly one of this and
    ``min_degree`` must be specified, otherwise a
    :exc:`NetworkXError` is raised.

min_degree : int
    Minimum degree of nodes in the created graph. This value must be
    in the interval [0, *n*]. Exactly one of this and
    ``average_degree`` must be specified, otherwise a
    :exc:`NetworkXError` is raised.

max_degree : int
    Maximum degree of nodes in the created graph. If not specified,
    this is set to ``n``, the total number of nodes in the graph.

min_community : int
    Minimum size of communities in the graph. If not specified, this
    is set to ``min_degree``.

max_community : int
    Maximum size of communities in the graph. If not specified, this
    is set to ``n``, the total number of nodes in the graph.

tol : float
    Tolerance when comparing floats, specifically when comparing
    average degree values.

max_iters : int
    Maximum number of iterations to try to create the community sizes,
    degree distribution, and community affiliations.

seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

Returns
-------
G : NetworkX graph
    The LFR benchmark graph generated according to the specified
    parameters.

    Each node in the graph has a node attribute ``'community'`` that
    stores the community (that is, the set of nodes) that includes
    it.

Raises
------
NetworkXError
    If any of the parameters do not meet their upper and lower bounds:

    - ``tau1`` and ``tau2`` must be strictly greater than 1.
    - ``mu`` must be in [0, 1].
    - ``max_degree`` must be in {1, ..., *n*}.
    - ``min_community`` and ``max_community`` must be in {0, ...,
      *n*}.

    If not exactly one of ``average_degree`` and ``min_degree`` is
    specified.

    If ``min_degree`` is not specified and a suitable ``min_degree``
    cannot be found.

ExceededMaxIterations
    If a valid degree sequence cannot be created within
    ``max_iters`` number of iterations.

    If a valid set of community sizes cannot be created within
    ``max_iters`` number of iterations.

    If a valid community assignment cannot be created within ``10 *
    n * max_iters`` number of iterations.

Examples
--------
Basic usage::

    >>> from networkx.generators.community import LFR_benchmark_graph
    >>> n = 250
    >>> tau1 = 3
    >>> tau2 = 1.5
    >>> mu = 0.1
    >>> G = LFR_benchmark_graph(
    ...     n, tau1, tau2, mu, average_degree=5, min_community=20, seed=10
    ... )

Continuing the example above, you can get the communities from the
node attributes of the graph::

    >>> communities = {frozenset(G.nodes[v]["community"]) for v in G}

Notes
-----
This algorithm differs slightly from the original way it was
presented in [1].

1) Rather than connecting the graph via a configuration model then
   rewiring to match the intra-community and inter-community
   degrees, we do this wiring explicitly at the end, which should be
   equivalent.
2) The code posted on the author's website [2] calculates the random
   power law distributed variables and their average using
   continuous approximations, whereas we use the discrete
   distributions here as both degree and community size are
   discrete.

Though the authors describe the algorithm as quite robust, testing
during development indicates that a somewhat narrower parameter set
is likely to successfully produce a graph. Some suggestions have
been provided in the event of exceptions.

References
----------
.. [1] "Benchmark graphs for testing community detection algorithms",
       Andrea Lancichinetti, Santo Fortunato, and Filippo Radicchi,
       Phys. Rev. E 78, 046110 2008
.. [2] https://www.santofortunato.net/resources

r   ztau1 must be greater than oneztau2 must be greater than oner   z!mu must be in the interval [0, 1]Nz)max_degree must be in the interval (0, n]z8Must assign exactly one of min_degree and average_degreec                 $    [        U 5      S-  S:H  $ )Nr   r   r`   )r   s    r   r   &LFR_benchmark_graph.<locals>.condition  s    3x!|q  r   c                     > [        U 5      T:  $ r   )r5   r   rD   s    r   r   #LFR_benchmark_graph.<locals>.length      3x1}r   c                     > [        U 5      T:H  $ r   r   r   s    r   r   r     r   r   c                     > [        U 5      T:  $ r   r   r   s    r   r   r     r   r   
   	community)r   r!   r   r   minmaxr   rI   add_nodes_fromr   degreer   r(   r&   r#   r,   )rD   tau1tau2r   r   
min_degreer   min_communitymax_communitytolr   r+   r   r   r   r   deg_seqcommscommunitiesr   r   r-   r.   s   `                      r   r   r   )  sP   r !8>??!8>??<a<BCC 
 q JKK4Nd$:;F
 	
 )*9


 ! !DVPTUG GG  t$6dSE aI'tLK
 	
AU1XA((1+gajAF&; <<KKQ(

1a  ((1+gajAF&; << ((1+
*KKa)A:JJq!$ ((1+
* '(AGGAJ{#   Hr   r   )NF)FN)NNFFT)NNNNNgHz>i  N)__doc__r   rj   networkxr   networkx.utilsr   __all___dispatchabler   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   rU   r   r   <module>r      s   H    * T2+ 3+\ T22 32j T2/ 3 /d T2J 3 JZ T23V 3 3Vl T2HT 3 HTV T24 34n T21 31h T2PTc 3 cL	J>$@0(f T2 	C 3 Cr   