
    h                        S r SSKrSSKJrJr  SSKJrJ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.S j5       5       r\" S5      \	R                  " SSS9SS.S j5       5       r\" S5      \	R                  " SSS9SS.S j5       5       rSS jrS rS rS r\" S5      \	R                  " SSS9SSS.S j5       5       rS rS rS r\" S5      \	R                  " SSS9SSSS.S j5       5       rS rS rS r\" S5      \	R                  " SSS9SSS.S j5       5       rg) a  Functions for generating trees.

The functions sampling trees at random in this module come
in two variants: labeled and unlabeled. The labeled variants
sample from every possible tree with the given number of nodes
uniformly at random. The unlabeled variants sample from every
possible *isomorphism class* of trees with the given number
of nodes uniformly at random.

To understand the difference, consider the following example.
There are two isomorphism classes of trees with four nodes.
One is that of the path graph, the other is that of the
star graph. The unlabeled variant will return a line graph or
a star graph with probability 1/2.

The labeled variant will return the line graph
with probability 3/4 and the star graph with probability 1/4,
because there are more labeled variants of the line graph
than of the star graph. More precisely, the line graph has
an automorphism group of order 2, whereas the star graph has
an automorphism group of order 6, so the line graph has three
times as many labeled variants as the star graph, and thus
three more chances to be drawn.

Additionally, some functions in this module can sample rooted
trees and forests uniformly at random. A rooted tree is a tree
with a designated root node. A rooted forest is a disjoint union
of rooted trees.
    N)Counterdefaultdict)comb	factorial)py_random_state)prefix_treeprefix_tree_recursiverandom_labeled_treerandom_labeled_rooted_treerandom_labeled_rooted_forestrandom_unlabeled_treerandom_unlabeled_rooted_treerandom_unlabeled_rooted_forestT)graphsreturns_graphc                   ^
^ U
U4S jn[         R                  " 5       mSnTR                  USS9  Sm
TR                  T
SS9  U" X 5      nU[        UR	                  5       5      4/nU(       a~  US   u  pV [        U5      u  px[        T5      S-
  n	TR                  XS9  TR                  XY5        U" X5      nUR                  U	[        UR	                  5       5      45        U(       a  M~  T$ ! [         a    UR                  5          M  f = f)a  Creates a directed prefix tree from a list of paths.

Usually the paths are described as strings or lists of integers.

A "prefix tree" represents the prefix structure of the strings.
Each node represents a prefix of some string. The root represents
the empty prefix with children for the single letter prefixes which
in turn have children for each double letter prefix starting with
the single letter corresponding to the parent node, and so on.

More generally the prefixes do not need to be strings. A prefix refers
to the start of a sequence. The root has children for each one element
prefix and they have children for each two element prefix that starts
with the one element sequence of the parent, and so on.

Note that this implementation uses integer nodes with an attribute.
Each node has an attribute "source" whose value is the original element
of the path to which this node corresponds. For example, suppose `paths`
consists of one path: "can". Then the nodes `[1, 2, 3]` which represent
this path have "source" values "c", "a" and "n".

All the descendants of a node have a common prefix in the sequence/path
associated with that node. From the returned tree, the prefix for each
node can be constructed by traversing the tree up to the root and
accumulating the "source" values along the way.

The root node is always `0` and has "source" attribute `None`.
The root is the only node with in-degree zero.
The nil node is always `-1` and has "source" attribute `"NIL"`.
The nil node is the only node with out-degree zero.


Parameters
----------
paths: iterable of paths
    An iterable of paths which are themselves sequences.
    Matching prefixes among these sequences are identified with
    nodes of the prefix tree. One leaf of the tree is associated
    with each path. (Identical paths are associated with the same
    leaf of the tree.)


Returns
-------
tree: DiGraph
    A directed graph representing an arborescence consisting of the
    prefix tree generated by `paths`. Nodes are directed "downward",
    from parent to child. A special "synthetic" root node is added
    to be the parent of the first node in each path. A special
    "synthetic" leaf node, the "nil" node `-1`, is added to be the child
    of all nodes representing the last element in a path. (The
    addition of this nil node technically makes this not an
    arborescence but a directed acyclic graph; removing the nil node
    makes it an arborescence.)


Notes
-----
The prefix tree is also known as a *trie*.


Examples
--------
Create a prefix tree from a list of strings with common prefixes::

    >>> paths = ["ab", "abs", "ad"]
    >>> T = nx.prefix_tree(paths)
    >>> list(T.edges)
    [(0, 1), (1, 2), (1, 4), (2, -1), (2, 3), (3, -1), (4, -1)]

The leaf nodes can be obtained as predecessors of the nil node::

    >>> root, NIL = 0, -1
    >>> list(T.predecessors(NIL))
    [2, 3, 4]

To recover the original paths that generated the prefix tree,
traverse up the tree from the node `-1` to the node `0`::

    >>> recovered = []
    >>> for v in T.predecessors(NIL):
    ...     prefix = ""
    ...     while v != root:
    ...         prefix = str(T.nodes[v]["source"]) + prefix
    ...         v = next(T.predecessors(v))  # only one predecessor
    ...     recovered.append(prefix)
    >>> sorted(recovered)
    ['ab', 'abs', 'ad']
c                    > [        [        5      nU H4  nU(       d  TR                  U T5        M  UtpEX$   R                  U5        M6     U$ N)r   listadd_edgeappend)parentpathschildrenpathchildrestNILtrees         K/var/www/html/env/lib/python3.13/site-packages/networkx/generators/trees.pyget_children!prefix_tree.<locals>.get_children   sK    t$ Dfc*LEO""4(      r   Nsourcer      )nxDiGraphadd_nodeiteritemsnextStopIterationpoplenr   r   )r   r!   rootr   stackr   remaining_childrenr   remaining_pathsnew_namer   r   s             @@r    r   r   2   s    x ::<DDMM$tM$
CMM#eM$D(HD)*+,E
%*2Y"	%)*<%="E t9q=h-f':hX^^%5 678 %  K  	IIK	s   6C. .DDc                    ^^ UU4S jm[         R                  " 5       nSnUR                  USS9  SmUR                  TSS9  T" XU5        U$ )a  Recursively creates a directed prefix tree from a list of paths.

The original recursive version of prefix_tree for comparison. It is
the same algorithm but the recursion is unrolled onto a stack.

Usually the paths are described as strings or lists of integers.

A "prefix tree" represents the prefix structure of the strings.
Each node represents a prefix of some string. The root represents
the empty prefix with children for the single letter prefixes which
in turn have children for each double letter prefix starting with
the single letter corresponding to the parent node, and so on.

More generally the prefixes do not need to be strings. A prefix refers
to the start of a sequence. The root has children for each one element
prefix and they have children for each two element prefix that starts
with the one element sequence of the parent, and so on.

Note that this implementation uses integer nodes with an attribute.
Each node has an attribute "source" whose value is the original element
of the path to which this node corresponds. For example, suppose `paths`
consists of one path: "can". Then the nodes `[1, 2, 3]` which represent
this path have "source" values "c", "a" and "n".

All the descendants of a node have a common prefix in the sequence/path
associated with that node. From the returned tree, ehe prefix for each
node can be constructed by traversing the tree up to the root and
accumulating the "source" values along the way.

The root node is always `0` and has "source" attribute `None`.
The root is the only node with in-degree zero.
The nil node is always `-1` and has "source" attribute `"NIL"`.
The nil node is the only node with out-degree zero.


Parameters
----------
paths: iterable of paths
    An iterable of paths which are themselves sequences.
    Matching prefixes among these sequences are identified with
    nodes of the prefix tree. One leaf of the tree is associated
    with each path. (Identical paths are associated with the same
    leaf of the tree.)


Returns
-------
tree: DiGraph
    A directed graph representing an arborescence consisting of the
    prefix tree generated by `paths`. Nodes are directed "downward",
    from parent to child. A special "synthetic" root node is added
    to be the parent of the first node in each path. A special
    "synthetic" leaf node, the "nil" node `-1`, is added to be the child
    of all nodes representing the last element in a path. (The
    addition of this nil node technically makes this not an
    arborescence but a directed acyclic graph; removing the nil node
    makes it an arborescence.)


Notes
-----
The prefix tree is also known as a *trie*.


Examples
--------
Create a prefix tree from a list of strings with common prefixes::

    >>> paths = ["ab", "abs", "ad"]
    >>> T = nx.prefix_tree(paths)
    >>> list(T.edges)
    [(0, 1), (1, 2), (1, 4), (2, -1), (2, 3), (3, -1), (4, -1)]

The leaf nodes can be obtained as predecessors of the nil node.

    >>> root, NIL = 0, -1
    >>> list(T.predecessors(NIL))
    [2, 3, 4]

To recover the original paths that generated the prefix tree,
traverse up the tree from the node `-1` to the node `0`::

    >>> recovered = []
    >>> for v in T.predecessors(NIL):
    ...     prefix = ""
    ...     while v != root:
    ...         prefix = str(T.nodes[v]["source"]) + prefix
    ...         v = next(T.predecessors(v))  # only one predecessor
    ...     recovered.append(prefix)
    >>> sorted(recovered)
    ['ab', 'abs', 'ad']
c                 8  > [        [        5      nU  H4  nU(       d  UR                  UT	5        M  UtpVX5   R                  U5        M6     UR	                  5        H<  u  pW[        U5      S-
  nUR                  XS9  UR                  X5        T
" XxU5        M>     g)a   Recursively create a trie from the given list of paths.

`paths` is a list of paths, each of which is itself a list of
nodes, relative to the given `root` (but not including it). This
list of paths will be interpreted as a tree-like structure, in
which two paths that share a prefix represent two branches of
the tree with the same initial segment.

`root` is the parent of the node at index 0 in each path.

`tree` is the "accumulator", the :class:`networkx.DiGraph`
representing the branching to which the new nodes and edges will
be added.

r'   r$   N)r   r   r   r   r,   r0   r*   )r   r1   r   r   r   r   r   r4   r5   r   _helpers            r    r8   &prefix_tree_recursive.<locals>._helper  s    $ t$DdC(LEO""4(  '/nn&6"E4y1}HMM(M1MM$)Ot4 '7r#   r   Nr$   r&   r   )r(   r)   r*   )r   r   r1   r   r8   s      @@r    r	   r	      sP    ~"5J ::<DDMM$tM$
CMM#eM$EKr#   seedr:   c          
         U S:X  a  [         R                  " S5      eU S:X  a  [         R                  " S5      $ [         R                  " [	        U S-
  5       Vs/ s H  o!R                  [	        U 5      5      PM     sn5      $ s  snf )u(  Returns a labeled tree on `n` nodes chosen uniformly at random.

Generating uniformly distributed random Prüfer sequences and
converting them into the corresponding trees is a straightforward
method of generating uniformly distributed random labeled trees.
This function implements this method.

Parameters
----------
n : int
    The number of nodes, greater than zero.
seed : random_state
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`

Returns
-------
 :class:`networkx.Graph`
    A `networkx.Graph` with nodes in the set {0, …, *n* - 1}.

Raises
------
NetworkXPointlessConcept
    If `n` is zero (because the null graph is not a tree).

Examples
--------
>>> G = nx.random_labeled_tree(5, seed=42)
>>> nx.is_tree(G)
True
>>> G.edges
EdgeView([(0, 1), (0, 3), (0, 2), (2, 4)])

A tree with *arbitrarily directed* edges can be created by assigning
generated edges to a ``DiGraph``:

>>> DG = nx.DiGraph()
>>> DG.add_edges_from(G.edges)
>>> nx.is_tree(DG)
True
>>> DG.edges
OutEdgeView([(0, 1), (0, 3), (0, 2), (2, 4)])
r   the null graph is not a treer'      )r(   NetworkXPointlessConceptempty_graphfrom_prufer_sequencerangechoice)nr:   is      r    r
   r
   E  sj    ^ 	Av))*HIIAv~~a  ""5Q<#P<aKKa$9<#PQQ#Ps   #Bc                \    [        XS9nUR                  SU S-
  5      UR                  S'   U$ )a  Returns a labeled rooted tree with `n` nodes.

The returned tree is chosen uniformly at random from all labeled rooted trees.

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

Returns
-------
:class:`networkx.Graph`
    A `networkx.Graph` with integer nodes 0 <= node <= `n` - 1.
    The root of the tree is selected uniformly from the nodes.
    The "root" graph attribute identifies the root of the tree.

Notes
-----
This function returns the result of :func:`random_labeled_tree`
with a randomly selected root.

Raises
------
NetworkXPointlessConcept
    If `n` is zero (because the null graph is not a tree).
r;   r   r'   r1   )r
   randintgraph)rD   r:   ts      r    r   r   {  s0    @ 	A)All1a!e,AGGFOHr#   c                &  ^ S n[         R                  " U 5      nU S:X  a  0 UR                  S'   U$ U" X5      nX@:X  a#  [        [	        U 5      5      UR                  S'   U$ UR                  [	        U 5      U5      n[        [	        U 5      5      R                  U5      n[	        X-
  S-
  5       Vs/ s H  oqR                  SU S-
  5      PM     nn[        U V	s/ s H  oU;   d  M
  U	PM     sn	5      m[        U4S jU 5       5      n
[        U
5      =pU H?  nUR                  X5        TU==   S-  ss'   X:  a  TU   S:X  a  UnM3  [        U
5      =pMA     UR                  XS   5        [        U5      UR                  S'   U$ s  snf s  sn	f )u{  Returns a labeled rooted forest with `n` nodes.

The returned forest is chosen uniformly at random using a
generalization of Prüfer sequences [1]_ in the form described in [2]_.

Parameters
----------
n : int
    The number of nodes.
seed : random_state
   See :ref:`Randomness<randomness>`.

Returns
-------
:class:`networkx.Graph`
    A `networkx.Graph` with integer nodes 0 <= node <= `n` - 1.
    The "roots" graph attribute is a set of integers containing the roots.

References
----------
.. [1] Knuth, Donald E. "Another Enumeration of Trees."
    Canadian Journal of Mathematics, 20 (1968): 1077-1086.
    https://doi.org/10.4153/CJM-1968-104-8
.. [2] Rubey, Martin. "Counting Spanning Trees". Diplomarbeit
    zur Erlangung des akademischen Grades Magister der
    Naturwissenschaften an der Formal- und Naturwissenschaftlichen
    Fakultät der Universität Wien. Wien, May 2000.
c                     UR                  SU S-   U S-
  -  S-
  5      nSn[        SU 5       HB  nU[        U S-
  5      X U-
  -  -  [        US-
  5      [        X-
  5      -  -  -  nX#:  d  M@  Us  $    U $ )Nr   r'   )rG   rB   r   )rD   r:   rcum_sumks        r    	_select_k/random_labeled_rooted_forest.<locals>._select_k  s    LLQUA.23q!A	!a%(1Q<7!a% 9QU#33 G {  r#   r   rootsr'   c              3   >   >#    U  H  nTU   S :X  d  M  Uv   M     g7f)r   N ).0xdegrees     r    	<genexpr>/random_labeled_rooted_forest.<locals>.<genexpr>  s     3q!F1INAAqs   	)r(   r@   rH   setrB   sample
differencerG   r   r+   r-   r   )rD   r:   rO   FrN   rQ   prE   NrU   iteratorulastvrV   s                 @r    r   r     sh   D
 	qAAv!AvuQx=KKa!$EE!H  'A).quqy)9:)9AaQ	)9A:-A1fa-.F3q33HH~A 	

1q	Q	8q	QAH~%D1  JJq(5zAGGGH% 	;-s   2F		F(Fc                     [         R                  " U5      nUR                  U 5        Ub  X$R                  S'   Ub  X4R                  S'   U$ )a  
Converts the (edges, n_nodes) input to a :class:`networkx.Graph`.
The (edges, n_nodes) input is a list of even length, where each pair
of consecutive integers represents an edge, and an integer `n_nodes`.
Integers in the list are elements of `range(n_nodes)`.

Parameters
----------
edges : list of ints
    The flattened list of edges of the graph.
n_nodes : int
    The number of nodes of the graph.
root: int (default=None)
    If not None, the "root" attribute of the graph will be set to this value.
roots: collection of ints (default=None)
    If not None, he "roots" attribute of the graph will be set to this value.

Returns
-------
:class:`networkx.Graph`
    The graph with `n_nodes` nodes and edges given by `edges`.
r1   rQ   )r(   r@   add_edges_fromrH   )edgesn_nodesr1   rQ   Gs        r    _to_nxrh     sH    . 	wAU Hr#   c                 &   [        [        U5      U S-   5       Hl  nUR                  [        [        SU5       VVs/ s H1  n[        SUS-
  U-  S-   5        H  nX1X$U-  -
     -  X   -  PM     M3     snn5      US-
  -  5        Mn     X   $ s  snnf )a  Returns the number of unlabeled rooted trees with `n` nodes.

See also https://oeis.org/A000081.

Parameters
----------
n : int
    The number of nodes
cache_trees : list of ints
    The $i$-th element is the number of unlabeled rooted trees with $i$ nodes,
    which is used as a cache (and is extended to length $n+1$ if needed)

Returns
-------
int
    The number of unlabeled rooted trees with `n` nodes.
r'   )rB   r0   r   sum)rD   cache_treesn_idjs        r    _num_rooted_treesro     s    $ S%q1u- #1c]*"1sQw1nq&89 Ca%K00;>A9 B* a		
 . >s   8Bc           	         UR                  S[        X5      U S-
  -  S-
  5      nSn[        U S-
  SS5       HN  n[        SU S-
  U-  S-   5       H2  nUU[        XU-  -
  U5      -  [        XQ5      -  -  nX4:  d  M-  Xe4s  s  $    MP     g)a  Returns a pair $(j,d)$ with a specific probability

Given $n$, returns a pair of positive integers $(j,d)$ with the probability
specified in formula (5) of Chapter 29 of [1]_.

Parameters
----------
n : int
    The number of nodes
cache_trees : list of ints
    Cache for :func:`_num_rooted_trees`.
seed : random_state
   See :ref:`Randomness<randomness>`.

Returns
-------
(int, int)
    A pair of positive integers $(j,d)$ satisfying formula (5) of
    Chapter 29 of [1]_.

References
----------
.. [1] Nijenhuis, Albert, and Wilf, Herbert S.
    "Combinatorial algorithms: for computers and calculators."
    Academic Press, 1978.
    https://doi.org/10.1016/C2013-0-11243-3
r   r'   r&   N)rG   ro   rB   )rD   rk   r:   r]   cumsumrm   rn   s          r    _select_jd_treesrr   4  s    8 	Q)!9QUCaGHAF1q5!R q1q5Q,*+A#AAI{;<#A34F
 zv , !r#   c                 r  ^ U S:X  a  / SpCX44$ U S:X  a  S/SpCX44$ [        XU5      u  pV[        XU-  -
  X5      u  nm[        XaU5      u  p[        U5       V
s/ s H  n
SX-  T-   4PM     nn
UR                  U5        [        U5       H#  nUR                  U4S jU 5       5        TU	-  mM%     UT4$ s  sn
f )a9  Returns an unlabeled rooted tree with `n` nodes.

Returns an unlabeled rooted tree with `n` nodes chosen uniformly
at random using the "RANRUT" algorithm from [1]_.
The tree is returned in the form: (list_of_edges, number_of_nodes)

Parameters
----------
n : int
    The number of nodes, greater than zero.
cache_trees : list ints
    Cache for :func:`_num_rooted_trees`.
seed : random_state
    See :ref:`Randomness<randomness>`.

Returns
-------
(list_of_edges, number_of_nodes) : list, int
    A random unlabeled rooted tree with `n` nodes as a 2-tuple
    ``(list_of_edges, number_of_nodes)``.
    The root is node 0.

References
----------
.. [1] Nijenhuis, Albert, and Wilf, Herbert S.
    "Combinatorial algorithms: for computers and calculators."
    Academic Press, 1978.
    https://doi.org/10.1016/C2013-0-11243-3
r'   r>   )r   r'   r   c              3   <   >#    U  H  u  pUT-   UT-   4v   M     g 7fr   rS   rT   n1n2t1_nodess      r    rW   0_random_unlabeled_rooted_tree.<locals>.<genexpr>        BrVR2="x-0r   )rr   _random_unlabeled_rooted_treerB   extend)rD   rk   r:   re   rf   rn   rm   t1t2t2_nodesrE   t12_rx   s                @r    r|   r|   ]  s    < 	AvQw~Av 1w~AD1DA0UKNLB0FLB16q
:AAx|h&'C
:IIcN1X
		BrBBH  x< ;s   B4)number_of_treesr:   c          
          U S:X  a  [         R                  " S5      eSS/nUc  [        [        XU5      SS06$ [	        U5       Vs/ s H  n[        [        XU5      SS06PM     sn$ s  snf )u?  Returns a number of unlabeled rooted trees uniformly at random

Returns one or more (depending on `number_of_trees`)
unlabeled rooted trees with `n` nodes drawn uniformly
at random.

Parameters
----------
n : int
    The number of nodes
number_of_trees : int or None (default)
    If not None, this number of trees is generated and returned.
seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

Returns
-------
:class:`networkx.Graph` or list of :class:`networkx.Graph`
    A single `networkx.Graph` (or a list thereof, if `number_of_trees`
    is specified) with nodes in the set {0, …, *n* - 1}.
    The "root" graph attribute identifies the root of the tree.

Notes
-----
The trees are generated using the "RANRUT" algorithm from [1]_.
The algorithm needs to compute some counting functions
that are relatively expensive: in case several trees are needed,
it is advisable to use the `number_of_trees` optional argument
to reuse the counting functions.

Raises
------
NetworkXPointlessConcept
    If `n` is zero (because the null graph is not a tree).

References
----------
.. [1] Nijenhuis, Albert, and Wilf, Herbert S.
    "Combinatorial algorithms: for computers and calculators."
    Academic Press, 1978.
    https://doi.org/10.1016/C2013-0-11243-3
r   r=   r'   r1   )r(   r?   rh   r|   rB   )rD   r   r:   rk   rE   s        r    r   r     s    \ 	Av))*HIIa&K4QTJSQRSS ''A 	-adCL!L'  s   A(c                 :   [        [        U5      U S-   5       Hv  n[        X15      nUR                  [	        [        SUS-   5       VVs/ s H0  n[        SX5-  S-   5        H  nXRX6U-  -
     -  X%S-
     -  PM     M2     snn5      U-  5        Mx     X    $ s  snnf )av  Returns the number of unlabeled rooted forests with `n` nodes, and with
no more than `q` nodes per tree. A recursive formula for this is (2) in
[1]_. This function is implemented using dynamic programming instead of
recursion.

Parameters
----------
n : int
    The number of nodes.
q : int
    The maximum number of nodes for each tree of the forest.
cache_forests : list of ints
    The $i$-th element is the number of unlabeled rooted forests with
    $i$ nodes, and with no more than `q` nodes per tree; this is used
    as a cache (and is extended to length `n` + 1 if needed).

Returns
-------
int
    The number of unlabeled rooted forests with `n` nodes with no more than
    `q` nodes per tree.

References
----------
.. [1] Wilf, Herbert S. "The uniform selection of free trees."
    Journal of Algorithms 2.2 (1981): 204-207.
    https://doi.org/10.1016/0196-6774(81)90021-3
r'   )rB   r0   minr   rj   )rD   qcache_forestsrl   q_irm   rn   s          r    _num_rooted_forestsr     s    : S'Q/#k #1cAg.."1chl3 cEk22]q55II3 J. 		
 0 s   	7Bc           	      
   UR                  S[        XU5      U -  S-
  5      nSn[        USS5       HN  n[        SX-  S-   5       H6  nUU[        XU-  -
  X5      -  [        US-
  X5      -  -  nXE:  d  M1  Xv4s  s  $    MP     g)ax  Given `n` and `q`, returns a pair of positive integers $(j,d)$
such that $j\leq d$, with probability satisfying (F1) of [1]_.

Parameters
----------
n : int
    The number of nodes.
q : int
    The maximum number of nodes for each tree of the forest.
cache_forests : list of ints
    Cache for :func:`_num_rooted_forests`.
seed : random_state
    See :ref:`Randomness<randomness>`.

Returns
-------
(int, int)
    A pair of positive integers $(j,d)$

References
----------
.. [1] Wilf, Herbert S. "The uniform selection of free trees."
    Journal of Algorithms 2.2 (1981): 204-207.
    https://doi.org/10.1016/0196-6774(81)90021-3
r   r'   r&   N)rG   r   rB   )rD   r   r   r:   r]   rq   rm   rn   s           r    _select_jd_forestsr     s    4 	Q+A-@1DqHIAF1a_q!&1*%A%aa%iBC%a!eQ>?F
 zv & r#   c                   ^ U S:X  a  / S/ 4$ [        XX45      u  pV[        XU-  -
  XX45      u  nmn[        XbU5      u  p[        U5       H4  nUR	                  T5        UR                  U4S jU	 5       5        TU
-  mM6     UTU4$ )a  Returns an unlabeled rooted forest with `n` nodes, and with no more
than `q` nodes per tree, drawn uniformly at random. It is an implementation
of the algorithm "Forest" of [1]_.

Parameters
----------
n : int
    The number of nodes.
q : int
    The maximum number of nodes per tree.
cache_trees :
    Cache for :func:`_num_rooted_trees`.
cache_forests :
    Cache for :func:`_num_rooted_forests`.
seed : random_state
   See :ref:`Randomness<randomness>`.

Returns
-------
(edges, n, r) : (list, int, list)
    The forest (edges, n) and a list r of root nodes.

References
----------
.. [1] Wilf, Herbert S. "The uniform selection of free trees."
    Journal of Algorithms 2.2 (1981): 204-207.
    https://doi.org/10.1016/0196-6774(81)90021-3
r   c              3   <   >#    U  H  u  pUT-   UT-   4v   M     g 7fr   rS   ru   s      r    rW   2_random_unlabeled_rooted_forest.<locals>.<genexpr>B  rz   r{   )r   _random_unlabeled_rooted_forestr|   rB   r   r}   )rD   r   rk   r   r:   rn   rm   r~   r1r   r   r   rx   s               @r    r   r     s    : 	AvAr{aM8DA6	E	1=B" 1FLB1X
		(
		BrBBH  xr#   )r   number_of_forestsr:   c          
      $   Uc  U nUS:X  a  U S:w  a  [        S5      eSS/nS/nUc#  [        XXEU5      u  pgn[        Xg[        U5      S9$ / n	[	        U5       H5  n
[        XXEU5      u  pgnU	R                  [        Xg[        U5      S95        M7     U	$ )u  Returns a forest or list of forests selected at random.

Returns one or more (depending on `number_of_forests`)
unlabeled rooted forests with `n` nodes, and with no more than
`q` nodes per tree, drawn uniformly at random.
The "roots" graph attribute identifies the roots of the forest.

Parameters
----------
n : int
    The number of nodes
q : int or None (default)
    The maximum number of nodes per tree.
number_of_forests : int or None (default)
    If not None, this number of forests is generated and returned.
seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

Returns
-------
:class:`networkx.Graph` or list of :class:`networkx.Graph`
    A single `networkx.Graph` (or a list thereof, if `number_of_forests`
    is specified) with nodes in the set {0, …, *n* - 1}.
    The "roots" graph attribute is a set containing the roots
    of the trees in the forest.

Notes
-----
This function implements the algorithm "Forest" of [1]_.
The algorithm needs to compute some counting functions
that are relatively expensive: in case several trees are needed,
it is advisable to use the `number_of_forests` optional argument
to reuse the counting functions.

Raises
------
ValueError
    If `n` is non-zero but `q` is zero.

References
----------
.. [1] Wilf, Herbert S. "The uniform selection of free trees."
    Journal of Algorithms 2.2 (1981): 204-207.
    https://doi.org/10.1016/0196-6774(81)90021-3
r   z.q must be a positive integer if n is positive.r'   )rQ   )
ValueErrorr   rh   rY   rB   r   )rD   r   r   r:   rk   r   gnodesrsresrE   s              r    r   r   G  s    b 	yAv!q&IJJa&KCM 6+d
" ac"g..
C$%6+d
" 	

6!#b'23	 &
 Jr#   c                     [        X5      [        [        SU S-  S-   5       Vs/ s H  n[        X!5      [        X-
  U5      -  PM     sn5      -
  nU S-  S:X  a  U[        [        U S-  U5      S-   S5      -  nU$ s  snf )a  Returns the number of unlabeled trees with `n` nodes.

See also https://oeis.org/A000055.

Parameters
----------
n : int
    The number of nodes.
cache_trees : list of ints
    Cache for :func:`_num_rooted_trees`.

Returns
-------
int
    The number of unlabeled trees with `n` nodes.
r'   r>   r   )ro   rj   rB   r   )rD   rk   rn   rL   s       r    
_num_treesr     s    " 	!)C 1a1fqj)	
) a-0A!%0UU)	
- 	A 	1uz	T#AFK81<a@@H	
s   $A;
c           
      :   [        U S-  X5      u  p4UR                  S[        U S-  U5      5      S:X  a  X4peO[        U S-  X5      u  pVUR                  U VVs/ s H  u  pxXpS-  -   XS-  -   4PM     snn5        UR	                  SU S-  45        X4U-   4$ s  snnf )aF  Returns a bi-centroidal tree on `n` nodes drawn uniformly at random.

This function implements the algorithm Bicenter of [1]_.

Parameters
----------
n : int
    The number of nodes (must be even).
cache : list of ints.
    Cache for :func:`_num_rooted_trees`.
seed : random_state
    See :ref:`Randomness<randomness>`

Returns
-------
(edges, n)
    The tree as a list of edges and number of nodes.

References
----------
.. [1] Wilf, Herbert S. "The uniform selection of free trees."
    Journal of Algorithms 2.2 (1981): 204-207.
    https://doi.org/10.1016/0196-6774(81)90021-3
r>   r   )r|   rG   ro   r}   r   )	rD   cacher:   rI   t_nodesr   r   rv   rw   s	            r    	_bicenterr     s    2 /qAvuCJA||A(a78A=H4Q!VUIHH2>2r!V}bFm,2>?HHaa[    ?s   B
c                 $   U S-  S:X  a  SnO[        [        U S-  U5      S-   S5      nUR                  S[        X5      S-
  5      U:  a  [	        XU5      $ [        U S-
  U S-
  S-  XU5      u  pVnU H  nUR                  X45        M     XVS-   4$ )a  Returns a tree on `n` nodes drawn uniformly at random.
It implements the Wilf's algorithm "Free" of [1]_.

Parameters
----------
n : int
    The number of nodes, greater than zero.
cache_trees : list of ints
    Cache for :func:`_num_rooted_trees`.
cache_forests : list of ints
    Cache for :func:`_num_rooted_forests`.
seed : random_state
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`

Returns
-------
(edges, n)
    The tree as a list of edges and number of nodes.

References
----------
.. [1] Wilf, Herbert S. "The uniform selection of free trees."
    Journal of Algorithms 2.2 (1981): 204-207.
    https://doi.org/10.1016/0196-6774(81)90021-3
r>   r'   r   )r   ro   rG   r   r   r   r   )	rD   rk   r   r:   r]   fn_frL   rE   s	            r    _random_unlabeled_treer     s    6 	1uz"16;7!;Q?||Az!1A56:..3EAEa<T
	 AHHaX 'zr#   c                    U S:X  a  [         R                  " S5      eSS/nS/nUc  [        [        XXB5      6 $ [	        U5       Vs/ s H  n[        [        XXB5      6 PM     sn$ s  snf )u  Returns a tree or list of trees chosen randomly.

Returns one or more (depending on `number_of_trees`)
unlabeled trees with `n` nodes drawn uniformly at random.

Parameters
----------
n : int
    The number of nodes
number_of_trees : int or None (default)
    If not None, this number of trees is generated and returned.
seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

Returns
-------
:class:`networkx.Graph` or list of :class:`networkx.Graph`
    A single `networkx.Graph` (or a list thereof, if
    `number_of_trees` is specified) with nodes in the set {0, …, *n* - 1}.

Raises
------
NetworkXPointlessConcept
    If `n` is zero (because the null graph is not a tree).

Notes
-----
This function generates an unlabeled tree uniformly at random using
Wilf's algorithm "Free" of [1]_. The algorithm needs to
compute some counting functions that are relatively expensive:
in case several trees are needed, it is advisable to use the
`number_of_trees` optional argument to reuse the counting
functions.

References
----------
.. [1] Wilf, Herbert S. "The uniform selection of free trees."
    Journal of Algorithms 2.2 (1981): 204-207.
    https://doi.org/10.1016/0196-6774(81)90021-3
r   r=   r'   )r(   r?   rh   r   rB   )rD   r   r:   rk   r   rE   s         r    r   r     s    X 	Av))*HIIa&KCM-amRSS ?+
+ *1=OP+
 	
 
s   A%)NN) __doc__warningscollectionsr   r   mathr   r   networkxr(   networkx.utilsr   __all___dispatchabler   r	   r
   r   r   rh   ro   rr   r|   r   r   r   r   r   r   r   r   r   rS   r#   r    <module>r      s  <  ,    *	 T2A 3AH T2J 3JZ T2#' 1R 3 1Rh T2*.   3  F T2,0 L 3 Ld@@&R.b T27;$ 4 3 4n*Z$N)X T2+/4d C 3 CL8 !F'T T2044 5
 3 5
r#   