
    h4                     N   S r SSKJr  SSKJr  SSKrSSKJr  / SQr	 " S S\R                  5      r\" S	5      \R                  " S
S9SS j5       5       r\R                  " SSS9SS j5       r\" S	5      \R                  " S
S9S 5       5       r\R                  " SSS9S 5       rg)u  Functions for encoding and decoding trees.

Since a tree is a highly restricted form of graph, it can be represented
concisely in several ways. This module includes functions for encoding
and decoding trees in the form of nested tuples and Prüfer
sequences. The former requires a rooted tree, whereas the latter can be
applied to unrooted trees. Furthermore, there is a bijection from Prüfer
sequences to labeled trees.

    )Counter)chainN)not_implemented_for)from_nested_tuplefrom_prufer_sequenceNotATreeto_nested_tupleto_prufer_sequencec                       \ rS rSrSrSrg)r      zRaised when a function expects a tree (that is, a connected
undirected graph with no cycles) but gets a non-tree graph as input
instead.

 N)__name__
__module____qualname____firstlineno____doc____static_attributes__r       Q/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/tree/coding.pyr   r      s    r   r   directedT)graphsc                    ^^ UU4S jm[         R                  " U 5      (       d  [         R                  " S5      eX;  a  [         R                  " SU  SU 35      eT" XS5      $ )a  Returns a nested tuple representation of the given tree.

The nested tuple representation of a tree is defined
recursively. The tree with one node and no edges is represented by
the empty tuple, ``()``. A tree with ``k`` subtrees is represented
by a tuple of length ``k`` in which each element is the nested tuple
representation of a subtree.

Parameters
----------
T : NetworkX graph
    An undirected graph object representing a tree.

root : node
    The node in ``T`` to interpret as the root of the tree.

canonical_form : bool
    If ``True``, each tuple is sorted so that the function returns
    a canonical form for rooted trees. This means "lighter" subtrees
    will appear as nested tuples before "heavier" subtrees. In this
    way, each isomorphic rooted tree has the same nested tuple
    representation.

Returns
-------
tuple
    A nested tuple representation of the tree.

Notes
-----
This function is *not* the inverse of :func:`from_nested_tuple`; the
only guarantee is that the rooted trees are isomorphic.

See also
--------
from_nested_tuple
to_prufer_sequence

Examples
--------
The tree need not be a balanced binary tree::

    >>> T = nx.Graph()
    >>> T.add_edges_from([(0, 1), (0, 2), (0, 3)])
    >>> T.add_edges_from([(1, 4), (1, 5)])
    >>> T.add_edges_from([(3, 6), (3, 7)])
    >>> root = 0
    >>> nx.to_nested_tuple(T, root)
    (((), ()), (), ((), ()))

Continuing the above example, if ``canonical_form`` is ``True``, the
nested tuples will be sorted::

    >>> nx.to_nested_tuple(T, root, canonical_form=True)
    ((), ((), ()), ((), ()))

Even the path graph can be interpreted as a tree::

    >>> T = nx.path_graph(4)
    >>> root = 0
    >>> nx.to_nested_tuple(T, root)
    ((((),),),)

c                    >^ ^ [        T T   5      U1-
  n[        U5      S:X  a  gU UU4S jU 5       nT(       a  [        U5      n[        U5      $ )aD  Recursively compute the nested tuple representation of the
given rooted tree.

``_parent`` is the parent node of ``root`` in the supertree in
which ``T`` is a subtree, or ``None`` if ``root`` is the root of
the supertree. This argument is used to determine which
neighbors of ``root`` are children and which is the parent.

r   r   c              3   8   >#    U  H  nT" TUT5      v   M     g 7fNr   ).0vr   _make_tupleroots     r   	<genexpr>7to_nested_tuple.<locals>._make_tuple.<locals>.<genexpr>v   s     <8a+aD))8s   )setlensortedtuple)r   r    _parentchildrennestedr   canonical_forms   ``   r   r   $to_nested_tuple.<locals>._make_tupleg   sH     qw<7)+x=A<8<F^FV}r   provided graph is not a treezGraph z contains no node N)nxis_treer   NodeNotFound)r   r    r*   r   s     `@r   r	   r	   #   sW    H* ::a==kk899}ooqc);D6BCCq%%r   T)r   returns_graphc                    ^ U4S jmT" U 5      nU(       a^  [        S/S [        R                  " US5       5       5      n[        U5       VVs0 s H  u  pEXT_M	     nnn[        R                  " X&5      nU$ s  snnf )a  Returns the rooted tree corresponding to the given nested tuple.

The nested tuple representation of a tree is defined
recursively. The tree with one node and no edges is represented by
the empty tuple, ``()``. A tree with ``k`` subtrees is represented
by a tuple of length ``k`` in which each element is the nested tuple
representation of a subtree.

Parameters
----------
sequence : tuple
    A nested tuple representing a rooted tree.

sensible_relabeling : bool
    Whether to relabel the nodes of the tree so that nodes are
    labeled in increasing order according to their breadth-first
    search order from the root node.

Returns
-------
NetworkX graph
    The tree corresponding to the given nested tuple, whose root
    node is node 0. If ``sensible_labeling`` is ``True``, nodes will
    be labeled in breadth-first search order starting from the root
    node.

Notes
-----
This function is *not* the inverse of :func:`to_nested_tuple`; the
only guarantee is that the rooted trees are isomorphic.

See also
--------
to_nested_tuple
from_prufer_sequence

Examples
--------
Sensible relabeling ensures that the nodes are labeled from the root
starting at 0::

    >>> balanced = (((), ()), ((), ()))
    >>> T = nx.from_nested_tuple(balanced, sensible_relabeling=True)
    >>> edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]
    >>> all((u, v) in T.edges() or (v, u) in T.edges() for (u, v) in edges)
    True

c                    > [        U 5      S:X  a  [        R                  " S5      $ [        R                  R	                  U  Vs/ s H  nT" U5      S4PM     sn5      $ s  snf )zRecursively creates a tree from the given sequence of nested
tuples.

This function employs the :func:`~networkx.tree.join` function
to recursively join subtrees into a larger tree.

r      )r$   r-   empty_graphtree
join_trees)sequencechild
_make_trees     r   r9   %from_nested_tuple.<locals>._make_tree   sS     x=A>>!$$ ww!!x"PxeJu$5q#9x"PQQ"Ps   Ar   c              3   *   #    U  H	  u  pUv   M     g 7fr   r   )r   ur   s      r   r!   $from_nested_tuple.<locals>.<genexpr>   s     A.@da.@s   )r   r-   	bfs_edges	enumeraterelabel_nodes)r7   sensible_relabelingr   	bfs_nodesir   labelsr9   s          @r   r   r      su    fR* 	8A 1#Abll1a.@AB	#,Y#78#741!$#78 Q'H	 9s   A7c                 x  ^ ^	 [        T 5      nUS:  a  Sn[        R                  " U5      e[        R                  " T 5      (       d  [        R                  " S5      e[        T 5      [        [        U5      5      :w  a  [        S5      e[        T R                  5       5      m	U U	4S jn[        U	4S j[        U5       5       5      =pE/ n[        US-
  5       H^  nU" U5      nUR                  U5        T	U==   S-  ss'   X:  a  T	U   S:X  a  UnM;  [        U	4S j[        US-   U5       5       5      =pEM`     U$ )	u;  Returns the Prüfer sequence of the given tree.

A *Prüfer sequence* is a list of *n* - 2 numbers between 0 and
*n* - 1, inclusive. The tree corresponding to a given Prüfer
sequence can be recovered by repeatedly joining a node in the
sequence with a node with the smallest potential degree according to
the sequence.

Parameters
----------
T : NetworkX graph
    An undirected graph object representing a tree.

Returns
-------
list
    The Prüfer sequence of the given tree.

Raises
------
NetworkXPointlessConcept
    If the number of nodes in `T` is less than two.

NotATree
    If `T` is not a tree.

KeyError
    If the set of nodes in `T` is not {0, …, *n* - 1}.

Notes
-----
There is a bijection from labeled trees to Prüfer sequences. This
function is the inverse of the :func:`from_prufer_sequence`
function.

Sometimes Prüfer sequences use nodes labeled from 1 to *n* instead
of from 0 to *n* - 1. This function requires nodes to be labeled in
the latter form. You can use :func:`~networkx.relabel_nodes` to
relabel the nodes of your tree to the appropriate format.

This implementation is from [1]_ and has a running time of
$O(n)$.

See also
--------
to_nested_tuple
from_prufer_sequence

References
----------
.. [1] Wang, Xiaodong, Lei Wang, and Yingjie Wu.
       "An optimal algorithm for Prufer codes."
       *Journal of Software Engineering and Applications* 2.02 (2009): 111.
       <https://doi.org/10.4236/jsea.2009.22016>

Examples
--------
There is a bijection between Prüfer sequences and labeled trees, so
this function is the inverse of the :func:`from_prufer_sequence`
function:

>>> edges = [(0, 3), (1, 3), (2, 3), (3, 4), (4, 5)]
>>> tree = nx.Graph(edges)
>>> sequence = nx.to_prufer_sequence(tree)
>>> sequence
[3, 3, 3, 4]
>>> tree2 = nx.from_prufer_sequence(sequence)
>>> list(tree2.edges()) == edges
True

   u>   Prüfer sequence undefined for trees with fewer than two nodesr,   z*tree must have node labels {0, ..., n - 1}c                 4   > [        U4S jTU     5       5      $ )Nc              3   >   >#    U  H  nTU   S :  d  M  Uv   M     g7fr3   Nr   )r   r   degrees     r   r!   6to_prufer_sequence.<locals>.parents.<locals>.<genexpr>/  s     5t!vay1}AAt   	)next)r<   r   rJ   s    r   parents#to_prufer_sequence.<locals>.parents.  s    5qt555r   c              3   >   >#    U  H  nTU   S :X  d  M  Uv   M     g7frI   r   r   krJ   s     r   r!   %to_prufer_sequence.<locals>.<genexpr>1       ;1F1INQQrL   r3   c              3   >   >#    U  H  nTU   S :X  d  M  Uv   M     g7frI   r   rQ   s     r   r!   rS   :       N(;1vayA~QQ(;rL   )r$   r-   NetworkXPointlessConceptr.   r   r#   rangeKeyErrordictrJ   rM   append)
r   nmsgrN   indexr<   resultrC   r   rJ   s
   `        @r   r
   r
      s   V 	AA1uN))#..::a==kk899
1vU1XCDD!((*F6 ;a;;;EF1q5\AJaq	Q	9aANeai(;NNNEA  Mr   c                 X  ^ [        U 5      S-   n[        [        U [        U5      5      5      m[        R
                  " U5      n[        5       n[        U4S j[        U5       5       5      =pEU  H  nUS:  d  XaS-
  :  a  [        R                  " SUS-
   SU 35      eUR                  XV5        UR                  U5        TU==   S-  ss'   Xd:  a  TU   S:X  a  UnMq  [        U4S j[        US-   U5       5       5      =pEM     [        U5      U-
  nUu  pVUR                  XV5        U$ )u  Returns the tree corresponding to the given Prüfer sequence.

A *Prüfer sequence* is a list of *n* - 2 numbers between 0 and
*n* - 1, inclusive. The tree corresponding to a given Prüfer
sequence can be recovered by repeatedly joining a node in the
sequence with a node with the smallest potential degree according to
the sequence.

Parameters
----------
sequence : list
    A Prüfer sequence, which is a list of *n* - 2 integers between
    zero and *n* - 1, inclusive.

Returns
-------
NetworkX graph
    The tree corresponding to the given Prüfer sequence.

Raises
------
NetworkXError
    If the Prüfer sequence is not valid.

Notes
-----
There is a bijection from labeled trees to Prüfer sequences. This
function is the inverse of the :func:`from_prufer_sequence` function.

Sometimes Prüfer sequences use nodes labeled from 1 to *n* instead
of from 0 to *n* - 1. This function requires nodes to be labeled in
the latter form. You can use :func:`networkx.relabel_nodes` to
relabel the nodes of your tree to the appropriate format.

This implementation is from [1]_ and has a running time of
$O(n)$.

References
----------
.. [1] Wang, Xiaodong, Lei Wang, and Yingjie Wu.
       "An optimal algorithm for Prufer codes."
       *Journal of Software Engineering and Applications* 2.02 (2009): 111.
       <https://doi.org/10.4236/jsea.2009.22016>

See also
--------
from_nested_tuple
to_prufer_sequence

Examples
--------
There is a bijection between Prüfer sequences and labeled trees, so
this function is the inverse of the :func:`to_prufer_sequence`
function:

>>> edges = [(0, 3), (1, 3), (2, 3), (3, 4), (4, 5)]
>>> tree = nx.Graph(edges)
>>> sequence = nx.to_prufer_sequence(tree)
>>> sequence
[3, 3, 3, 4]
>>> tree2 = nx.from_prufer_sequence(sequence)
>>> list(tree2.edges()) == edges
True

rF   c              3   >   >#    U  H  nTU   S :X  d  M  Uv   M     g7frI   r   rQ   s     r   r!   'from_prufer_sequence.<locals>.<genexpr>  rT   rL   r   r3   z6Invalid Prufer sequence: Values must be between 0 and z, got c              3   >   >#    U  H  nTU   S :X  d  M  Uv   M     g7frI   r   rQ   s     r   r!   rb     rV   rL   )r$   r   r   rX   r-   r4   r#   rM   NetworkXErroradd_edgeadd)	r7   r\   r   not_orphanedr^   r<   r   orphansrJ   s	           @r   r   r   >  s    F 	HA U8U1X./F
qA 5L;a;;;Eq5AAI""H1VTUSVW  	


1q	Q	9aANeai(;NNNEA  !f|#GDAJJqHr   )F)r   collectionsr   	itertoolsr   networkxr-   networkx.utilsr   __all__NetworkXExceptionr   _dispatchabler	   r   r
   r   r   r   r   <module>rp      s   	     .r##  Z \&  !\&~ T2P 3Pf Z a  !aH T2^ 3^r   